@instructure/quiz-interactions
Version:
A React UI component Library for quiz interaction types.
468 lines (463 loc) • 20 kB
JavaScript
function _array_like_to_array(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _array_without_holes(arr) {
if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function _assert_this_initialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _call_super(_this, derived, args) {
derived = _get_prototype_of(derived);
return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
}
function _class_call_check(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for(var i = 0; i < props.length; i++){
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _create_class(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _get_prototype_of(o) {
_get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _get_prototype_of(o);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _set_prototype_of(subClass, superClass);
}
function _iterable_to_array(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _non_iterable_spread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _possible_constructor_return(self, call) {
if (call && (_type_of(call) === "object" || typeof call === "function")) {
return call;
}
return _assert_this_initialized(self);
}
function _set_prototype_of(o, p) {
_set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _set_prototype_of(o, p);
}
function _to_consumable_array(arr) {
return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _type_of(obj) {
"@swc/helpers - typeof";
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
function _unsupported_iterable_to_array(o, minLen) {
if (!o) return;
if (typeof o === "string") return _array_like_to_array(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _is_native_reflect_construct() {
try {
var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
} catch (_) {}
return (_is_native_reflect_construct = function() {
return !!result;
})();
}
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import isEmpty from 'lodash/fp/isEmpty';
import { ItemBodyWrapper } from '@instructure/quiz-rce';
import { Text } from '@instructure/ui-text';
import { Button, CloseButton, CondensedButton, IconButton } from '@instructure/ui-buttons';
import { Flex } from '@instructure/quiz-common';
import { IconKeyboardShortcutsLine } from '@instructure/ui-icons';
import { Modal } from '@instructure/ui-modal';
import { Heading } from '@instructure/ui-heading';
import { Table } from '@instructure/ui-table';
import TargetContainer from '../common/TargetContainer';
import t from '@instructure/quiz-i18n/format-message';
import Target from './Target';
var HotSpotTake = /*#__PURE__*/ function(Component) {
"use strict";
_inherits(HotSpotTake, Component);
function HotSpotTake(props) {
_class_call_check(this, HotSpotTake);
var _this;
_this = _call_super(this, HotSpotTake, [
props
]), _define_property(_this, "canAddPoint", function() {
var _this_state = _this.state, selectedCoordinates = _this_state.selectedCoordinates, keyboardCoordinates = _this_state.keyboardCoordinates;
var hotspotsCount = _this.props.interactionData.hotspotsCount;
var totalSelections = selectedCoordinates.length + (keyboardCoordinates ? 1 : 0);
return totalSelections < (hotspotsCount || 1);
}), _define_property(_this, "saveSelectedPoint", function() {
var _this_state = _this.state, selectedCoordinates = _this_state.selectedCoordinates, keyboardCoordinates = _this_state.keyboardCoordinates;
var _this_props = _this.props, multipleHotSpotEnabled = _this_props.multipleHotSpotEnabled, hotspotsCount = _this_props.interactionData.hotspotsCount;
if (!keyboardCoordinates) return;
var updatedCoordinates = _to_consumable_array(selectedCoordinates).concat([
keyboardCoordinates
]);
_this.setState({
selectedCoordinates: updatedCoordinates,
keyboardCoordinates: null,
isSelectingPoint: false
});
var response = !multipleHotSpotEnabled && (!hotspotsCount || hotspotsCount === 1) ? keyboardCoordinates : updatedCoordinates;
_this.props.handleResponseUpdate(response);
}), _define_property(_this, "handleKeyDown", function(event) {
var stepSize = 0.05;
var key = event.key;
if (!_this.state.focusedContainer) return;
if (_this.isAnyInputFocused()) return;
if (key === 's') {
_this.startSelectingPoint();
} else if (key === 'd' && _this.state.isSelectingPoint) {
_this.saveSelectedPoint();
} else if (key === 'Backspace' || key === 'Delete') {
_this.handleResetSelections();
} else if (_this.isArrowKey(key) && _this.state.keyboardCoordinates) {
event.preventDefault();
_this.movePosition(key, stepSize);
}
}), _define_property(_this, "startSelectingPoint", function() {
if (!_this.canAddPoint()) return;
_this.setState({
keyboardCoordinates: {
x: 0.5,
y: 0.5
},
isSelectingPoint: true
});
}), _define_property(_this, "isArrowKey", function(key) {
return [
'ArrowUp',
'ArrowDown',
'ArrowLeft',
'ArrowRight'
].includes(key);
}), _define_property(_this, "movePosition", function(key, stepSize) {
var _this_state_keyboardCoordinates = _this.state.keyboardCoordinates, x = _this_state_keyboardCoordinates.x, y = _this_state_keyboardCoordinates.y;
var offsets = {
ArrowUp: {
x: x,
y: Math.max(y - stepSize, 0)
},
ArrowDown: {
x: x,
y: Math.min(y + stepSize, 1)
},
ArrowLeft: {
x: Math.max(x - stepSize, 0),
y: y
},
ArrowRight: {
x: Math.min(x + stepSize, 1),
y: y
}
};
_this.setState({
keyboardCoordinates: offsets[key]
});
}), _define_property(_this, "handleSetCoordinates", function(coordinatesArray) {
if (!_this.canAddPoint()) return;
var selectedCoordinates = _this.state.selectedCoordinates;
var _this_props = _this.props, multipleHotSpotEnabled = _this_props.multipleHotSpotEnabled, hotspotsCount = _this_props.interactionData.hotspotsCount;
var x = coordinatesArray[0].x / _this.targetContainer.state.imageWidth;
var y = coordinatesArray[0].y / _this.targetContainer.state.imageHeight;
var updatedCoordinates = _to_consumable_array(selectedCoordinates).concat([
{
x: x,
y: y
}
]);
_this.setState({
selectedCoordinates: updatedCoordinates
});
var response = !multipleHotSpotEnabled && (!hotspotsCount || hotspotsCount === 1) ? {
x: x,
y: y
} : updatedCoordinates;
_this.props.handleResponseUpdate(response);
}), _define_property(_this, "targetContainerRef", function(node) {
_this.targetContainer = node;
}), _define_property(_this, "handleResetSelections", function() {
var updatedCoordinates = _this.state.selectedCoordinates.slice(0, -1);
_this.setState({
selectedCoordinates: updatedCoordinates,
keyboardCoordinates: null
});
_this.props.handleResponseUpdate(_this.state.selectedCoordinates);
}), _define_property(_this, "handleCloseShortcutsClick", function() {
_this.setState({
shortcutsModalOpen: false
});
}), _define_property(_this, "handleOpenShortcutsClick", function() {
_this.setState({
shortcutsModalOpen: true
});
});
_this.state = {
selectedCoordinates: [],
keyboardCoordinates: null,
isSelectingPoint: false,
focusedContainer: null,
shortcutsModalOpen: false
};
return _this;
}
_create_class(HotSpotTake, [
{
key: "componentDidMount",
value: function componentDidMount() {
var _this_props_userResponse;
window.addEventListener('keydown', this.handleKeyDown);
var value = (_this_props_userResponse = this.props.userResponse) === null || _this_props_userResponse === void 0 ? void 0 : _this_props_userResponse.value;
if (!isEmpty(value)) {
this.setState({
selectedCoordinates: Array.isArray(value) ? value : [
value
]
});
}
}
},
{
key: "componentWillUnmount",
value: function componentWillUnmount() {
window.removeEventListener('keydown', this.handleKeyDown);
}
},
{
key: "isAnyInputFocused",
value: function isAnyInputFocused() {
var inputs = document.querySelectorAll('input');
return Array.from(inputs).some(function(input) {
return input === document.activeElement;
});
}
},
{
// ===========
// RENDER
// ===========
key: "render",
value: function render() {
var _this = this;
var _this_state = this.state, selectedCoordinates = _this_state.selectedCoordinates, keyboardCoordinates = _this_state.keyboardCoordinates;
var hotspots = selectedCoordinates.length > 0 || keyboardCoordinates ? _to_consumable_array(selectedCoordinates.map(function(coordinate) {
return {
coordinates: [
coordinate
],
drawingType: Target
};
})).concat(_to_consumable_array(keyboardCoordinates ? [
{
coordinates: [
keyboardCoordinates
],
drawingType: Target
}
] : [])) : [
{
coordinates: [
{}
],
drawingType: Target
}
];
var keyboardShortcuts = [
{
id: 'select',
shortcut: 'S',
action: t('Select a point')
},
{
id: 'save',
shortcut: 'D',
action: t('Save the position')
},
{
id: 'delete',
shortcut: 'Backspace/Delete',
action: t('Clear all selections')
},
{
id: 'move',
shortcut: 'Arrow keys',
action: t('Move the point')
}
];
return /*#__PURE__*/ React.createElement(ItemBodyWrapper, {
itemBody: this.props.itemBody
}, /*#__PURE__*/ React.createElement("div", {
className: "fs-mask"
}, /*#__PURE__*/ React.createElement(TargetContainer, {
hotspots: hotspots,
handleSetCoordinates: this.handleSetCoordinates,
ref: this.targetContainerRef,
url: this.props.interactionData.imageUrl,
onFocus: function() {
return _this.setState({
focusedContainer: _this.targetContainer
});
},
onBlur: function() {
return _this.setState({
focusedContainer: null
});
}
})), /*#__PURE__*/ React.createElement(Flex, {
direction: "row",
justifyItems: "space-between",
alignItems: "center",
gap: "small",
margin: "x-small 0 0"
}, /*#__PURE__*/ React.createElement(Flex.Item, null, this.state.selectedCoordinates.length > 0 && /*#__PURE__*/ React.createElement(CondensedButton, {
onClick: this.handleResetSelections,
"data-automation": "sdk-hotspot-take-clear-selections-button"
}, t('Clear my selection'))), /*#__PURE__*/ React.createElement(Flex.Item, null, /*#__PURE__*/ React.createElement(IconButton, {
color: "secondary",
screenReaderLabel: t('Show keyboard shortcuts'),
withBackground: false,
withBorder: false,
onClick: this.handleOpenShortcutsClick
}, /*#__PURE__*/ React.createElement(IconKeyboardShortcutsLine, null)), /*#__PURE__*/ React.createElement(Modal, {
size: "medium",
label: t('Keyboard shortcuts'),
open: this.state.shortcutsModalOpen,
onDismiss: this.handleCloseShortcutsClick,
shouldCloseOnDocumentClick: true
}, /*#__PURE__*/ React.createElement(Modal.Header, null, /*#__PURE__*/ React.createElement(Heading, {
level: "h2"
}, t('Keyboard shortcuts')), /*#__PURE__*/ React.createElement(CloseButton, {
placement: "end",
offset: "small",
onClick: this.handleCloseShortcutsClick,
screenReaderLabel: t('Close')
})), /*#__PURE__*/ React.createElement(Modal.Body, null, /*#__PURE__*/ React.createElement(Table, {
caption: t('Keyboard shortcuts')
}, /*#__PURE__*/ React.createElement(Table.Head, null, /*#__PURE__*/ React.createElement(Table.Row, null, /*#__PURE__*/ React.createElement(Table.ColHeader, {
id: "shortcut"
}, t('Shortcut')), /*#__PURE__*/ React.createElement(Table.ColHeader, {
id: "action"
}, t('Action')))), /*#__PURE__*/ React.createElement(Table.Body, null, keyboardShortcuts.map(function(param) {
var id = param.id, shortcut = param.shortcut, action = param.action;
return /*#__PURE__*/ React.createElement(Table.Row, {
key: id
}, /*#__PURE__*/ React.createElement(Table.RowHeader, null, /*#__PURE__*/ React.createElement(Text, {
id: "shortcut-".concat(id)
}, shortcut)), /*#__PURE__*/ React.createElement(Table.Cell, null, /*#__PURE__*/ React.createElement(Text, {
id: "action-".concat(id)
}, action)));
})))), /*#__PURE__*/ React.createElement(Modal.Footer, null, /*#__PURE__*/ React.createElement(Button, {
onClick: this.handleCloseShortcutsClick
}, t('Close')))))));
}
}
]);
return HotSpotTake;
}(Component);
_define_property(HotSpotTake, "propTypes", {
handleResponseUpdate: PropTypes.func.isRequired,
interactionData: PropTypes.shape({
imageUrl: PropTypes.string.isRequired,
hotspotsCount: PropTypes.number
}).isRequired,
itemBody: PropTypes.string.isRequired,
userResponse: PropTypes.shape({
value: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.shape({
x: PropTypes.number,
y: PropTypes.number
})),
PropTypes.shape({
x: PropTypes.number,
y: PropTypes.number
})
]).isRequired
}),
scoringData: PropTypes.shape({
value: PropTypes.arrayOf(PropTypes.shape({
x: PropTypes.number,
y: PropTypes.number
})).isRequired
}),
multipleHotSpotEnabled: PropTypes.bool
});
/**
---
category: HotSpot
---
HotSpot Take component
```jsx_example
function Example (props) {
const exampleProps = {
itemBody: 'Which of these players is David Ferrer',
interactionData: {
imageUrl: 'https://i.ytimg.com/vi/LgkAebhJ7iE/maxresdefault.jpg'
},
userResponse: {
value: {
x: 0.3,
y: 0.3
}
}
}
return (
<HotSpotTake {...exampleProps} {...props} />
)
}
<SettingsSwitcher locales={LOCALES}>
<TakeStateProvider>
<Example />
</TakeStateProvider>
</SettingsSwitcher>
```
**/ export { HotSpotTake as default };