@instructure/quiz-interactions
Version:
A React UI component Library for quiz interaction types.
559 lines (558 loc) • 26 kB
JavaScript
/** @jsx jsx */ 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 _object_spread(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_define_property(target, key, source[key]);
});
}
return target;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _object_spread_props(target, source) {
source = source != null ? source : {};
if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
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;
})();
}
function _ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
import { Component } from 'react';
import PropTypes from 'prop-types';
import { v4 as uuid } from 'uuid';
import striptags from 'striptags';
import assignIn from 'lodash/fp/assignIn';
import set from 'lodash/fp/set';
import last from 'lodash/fp/last';
import omit from 'lodash/omit';
import without from 'lodash/without';
import { jsx } from '@instructure/emotion';
import { ScreenReaderContent, PresentationContent } from '@instructure/ui-a11y-content';
import { Grid } from '@instructure/ui-grid';
import { Checkbox } from '@instructure/ui-checkbox';
import { Text } from '@instructure/ui-text';
import { View } from '@instructure/ui-view';
import AnswerInput from '../../common/edit/components/AnswerInput';
import Footer from '../../common/edit/components/Footer';
import OrderingInteractionType from '../../../records/interactions/ordering';
import QuestionContainer from '../../common/edit/components/QuestionContainer';
import RemoveChoiceButton from '../../common/edit/components/RemoveChoiceButton';
import withEditTools from '../../../util/withEditTools';
import Card from '../../common/components/Card';
import ReorderChoiceButton from '../common/ReorderChoiceButton';
import QuestionSettingsContainer from '../../common/edit/components/QuestionSettingsContainer';
import t from '@instructure/quiz-i18n/format-message';
import QuestionSettingsPanel from '../../common/edit/components/QuestionSettingsPanel';
import CalculatorOptionWithOqaatAlert from '../../common/edit/components/CalculatorOptionWithOqaatAlert';
import { TextInput, Flex, FormFieldGroup } from '@instructure/quiz-common';
var OrderingEdit = /*#__PURE__*/ function(Component) {
"use strict";
_inherits(OrderingEdit, Component);
function OrderingEdit() {
_class_call_check(this, OrderingEdit);
var _this;
_this = _call_super(this, OrderingEdit, arguments), _define_property(_this, "stemElement", null), _define_property(_this, "topLabelRef", null), _define_property(_this, "bottomLabelRef", null), _define_property(_this, "inputRefs", []), _define_property(_this, "reorderRefs", []), _define_property(_this, "removeChoiceRefs", []), _define_property(_this, "_timeouts", []), _define_property(_this, "_choiceWasCreated", false), // ===========
// HANDLERS
// ===========
_define_property(_this, "handleStemRef", function(node) {
_this.stemElement = node;
}), _define_property(_this, "handleTopLabelRef", function(node) {
_this.topLabelRef = node;
}), _define_property(_this, "handleBottomLabelRef", function(node) {
_this.bottomLabelRef = node;
}), _define_property(_this, "handleCalculatorTypeChange", function(e, value) {
_this.props.changeItemState({
calculatorType: value
});
}), _define_property(_this, "handleMoveChoice", function(currI, targetI) {
// Create a new array to preserve immutability
var choices = _this.props.scoringData.value.slice(0);
var ref;
ref = [
choices[currI],
choices[targetI]
], choices[targetI] = ref[0], choices[currI] = ref[1], ref;
_this.props.changeItemState({
scoringData: _object_spread_props(_object_spread({}, _this.props.scoringData), {
value: choices
})
});
_this._timeouts = _to_consumable_array(_this._timeouts).concat([
setTimeout(function() {
return _this.reorderRefs[targetI].focus();
})
]);
}), _define_property(_this, "handleRemoveChoice", function(choiceId, index) {
var choiceOrder = _this.props.scoringData.value;
if (index === 0) {
if (_this.props.properties.includeLabels) {
_this.topLabelRef.focus();
} else {
// added timeout to compensate for RCE sluggishness
_this._timeouts = _to_consumable_array(_this._timeouts).concat([
setTimeout(function() {
return _this.stemElement.focus();
})
]);
}
} else {
if (choiceOrder.length > 3) {
_this.removeChoiceRefs[index - 1].focus();
} else {
_this.reorderRefs[index - 1].focus();
}
}
_this.props.changeItemState({
interactionData: _object_spread_props(_object_spread({}, _this.props.interactionData), {
choices: omit(_this.props.interactionData.choices, choiceId)
}),
scoringData: _object_spread_props(_object_spread({}, _this.props.scoringData), {
value: without(choiceOrder, choiceId)
})
});
}), _define_property(_this, "handleCreateChoice", function() {
var id = uuid();
var newChoice = {
id: id,
itemBody: ''
};
_this._choiceWasCreated = true;
_this.props.changeItemState({
interactionData: _object_spread_props(_object_spread({}, _this.props.interactionData), {
choices: assignIn(_this.props.interactionData.choices, _define_property({}, id, newChoice))
}),
scoringData: _object_spread_props(_object_spread({}, _this.props.scoringData), {
value: _to_consumable_array(_this.props.scoringData.value).concat([
id
])
})
});
_this.props.notifyScreenreader(t('Navigate up to find new choice input'));
}), _define_property(_this, "handleIncludeLabelsChange", function(e) {
var properties = _this.props.properties;
if (!properties.includeLabels) {
_this.props.notifyScreenreader(t('Navigate up to find label fields'));
}
_this.props.changeItemState({
properties: _object_spread_props(_object_spread({}, _this.props.properties), {
includeLabels: !properties['includeLabels']
})
});
}), _define_property(_this, "handleDisplayAnswersParagraphChange", function(e) {
var properties = _this.props.properties;
_this.props.changeItemState({
properties: _object_spread_props(_object_spread({}, _this.props.properties), {
displayAnswersParagraph: !properties['displayAnswersParagraph']
})
});
}), _define_property(_this, "handleInputChange", function(choiceId, event, param) {
var editorContent = param.editorContent;
_this.props.changeItemState({
interactionData: set("choices[".concat(choiceId, "].itemBody"), editorContent, _this.props.interactionData)
});
});
return _this;
}
_create_class(OrderingEdit, [
{
key: "componentWillUnmount",
value: function componentWillUnmount() {
this._timeouts.forEach(clearTimeout);
}
},
{
key: "componentDidUpdate",
value: function componentDidUpdate() {
if (this._choiceWasCreated) {
this._choiceWasCreated = false;
last(this.inputRefs).focus();
}
}
},
{
// ===========
// RENDER
// ===========
key: "renderChoice",
value: function renderChoice(choice, isFinalChoice, index) {
var _this = this;
var choicesLength = this.props.scoringData.value.length;
var nonEditable = this.props.overrideEditableForRegrading;
return /*#__PURE__*/ jsx(Card, {
id: choice.id,
index: index,
key: "".concat(choice.id, "_").concat(index),
moveCard: this.handleMoveChoice
}, /*#__PURE__*/ jsx(Grid, {
colSpacing: "small"
}, /*#__PURE__*/ jsx(Grid.Row, null, /*#__PURE__*/ jsx(Grid.Col, {
width: "auto"
}, /*#__PURE__*/ jsx(View, {
as: "div",
margin: "xx-large 0 0 0",
themeOverride: {
marginXxLarge: '39px'
}
}, /*#__PURE__*/ jsx(Flex, {
direction: "row",
alignItems: "start"
}, /*#__PURE__*/ jsx(Flex.Item, null, /*#__PURE__*/ jsx(ScreenReaderContent, null, t('position {position, number}', {
position: index + 1
})), /*#__PURE__*/ jsx(PresentationContent, null, /*#__PURE__*/ jsx(Text, {
color: "primary"
}, t.number(index + 1))))))), /*#__PURE__*/ jsx(Grid.Col, {
vAlign: "middle"
}, /*#__PURE__*/ jsx(View, {
as: "div",
background: "primary"
}, /*#__PURE__*/ jsx(AnswerInput, {
disabled: nonEditable,
errors: this.props.getErrors("interactionData.choices[".concat(choice.id, "].itemBody")),
id: choice.id,
itemBody: choice.itemBody,
noRCE: !this.props.enableRichContentEditor,
onChangeHandler: this.handleInputChange,
onModalClose: this.props.onModalClose,
onModalOpen: this.props.onModalOpen,
openImportModal: this.props.openImportModal,
ref: function(node) {
_this.inputRefs[index] = node;
},
automationData: "sdk-ordering-answer-".concat(choice.id),
isRequired: true
}))), /*#__PURE__*/ jsx(Grid.Col, {
width: "auto"
}, /*#__PURE__*/ jsx(View, {
as: "div",
margin: "xx-large 0 0 0",
themeOverride: {
marginXxLarge: '30px'
}
}, /*#__PURE__*/ jsx(Flex, {
direction: "row",
justifyItems: "start"
}, /*#__PURE__*/ jsx(Flex.Item, null, /*#__PURE__*/ jsx(ReorderChoiceButton, {
ref: function(node) {
_this.reorderRefs[index] = node;
},
id: choice.id,
isFinalChoice: isFinalChoice,
isFirstChoice: index === 0,
onMoveChoiceUp: function() {
return _this.handleMoveChoice(index, index - 1);
},
onMoveChoiceDown: function() {
return _this.handleMoveChoice(index, index + 1);
},
screenReaderText: t('Reorder Choice: {choice}', {
choice: striptags(choice.itemBody)
})
})), choicesLength > 2 && !nonEditable && /*#__PURE__*/ jsx(Flex.Item, null, /*#__PURE__*/ jsx(RemoveChoiceButton, {
choiceId: choice.id,
ref: function(node) {
_this.removeChoiceRefs[index] = node;
},
onRemoveChoice: function() {
return _this.handleRemoveChoice(choice.id, index);
},
screenReaderText: t('Remove Choice: {choice}', {
choice: striptags(choice.itemBody)
})
}))))))));
}
},
{
key: "renderChoices",
value: function renderChoices() {
var _this = this;
var choiceOrder = this.props.scoringData.value;
var choicesLength = choiceOrder.length;
return choiceOrder.map(function(choiceId, i) {
var isFinalChoice = i + 1 === choicesLength;
var choice = _this.props.interactionData.choices[choiceId];
return /*#__PURE__*/ jsx(View, {
key: "orderchoice-".concat(choiceId),
as: "div",
margin: "x-small 0"
}, _this.renderChoice(choice, isFinalChoice, i));
});
}
},
{
key: "renderLabel",
value: function renderLabel(labelName, description) {
var _this = this;
var automation = 'sdk-ordering-edit-' + labelName;
return /*#__PURE__*/ jsx(View, {
as: "div",
padding: "x-small 0"
}, /*#__PURE__*/ jsx(TextInput, {
ref: labelName === 'topLabel' ? this.handleTopLabelRef : this.handleBottomLabelRef,
renderLabel: description,
isRequired: false,
interaction: this.props.overrideEditableForRegrading ? 'disabled' : 'enabled',
name: labelName,
defaultValue: this.props.properties[labelName] || '',
onChange: function(event) {
_this.props.changeItemState({
properties: _object_spread_props(_object_spread({}, _this.props.properties), _define_property({}, labelName, event.target.value))
});
},
width: "20rem",
messages: this.props.getErrors("properties.".concat(labelName)),
"data-automation": automation
}));
}
},
{
key: "renderOptionsDescription",
value: function renderOptionsDescription() {
return /*#__PURE__*/ jsx(ScreenReaderContent, null, t('Ordering options'));
}
},
{
key: "render",
value: function render() {
var _this_props_properties = this.props.properties, includeLabels = _this_props_properties.includeLabels, displayAnswersParagraph = _this_props_properties.displayAnswersParagraph;
var nonEditable = this.props.overrideEditableForRegrading;
// clean up the references
this.inputRefs = [];
this.removeChoiceRefs = [];
this.reorderRefs = [];
return /*#__PURE__*/ jsx("div", null, /*#__PURE__*/ jsx(QuestionContainer, {
disabled: nonEditable,
enableRichContentEditor: this.props.enableRichContentEditor,
itemBody: this.props.itemBody,
onDescriptionChange: this.props.onDescriptionChange,
onModalClose: this.props.onModalClose,
onModalOpen: this.props.onModalOpen,
openImportModal: this.props.openImportModal,
stemErrors: this.props.getErrors('itemBody'),
textareaRef: this.handleStemRef
}, includeLabels && this.renderLabel('topLabel', t('Top Label')), /*#__PURE__*/ jsx(View, {
as: "div"
}, this.renderChoices()), !nonEditable && /*#__PURE__*/ jsx(Footer, {
onCreateChoice: this.handleCreateChoice,
notifyScreenreader: this.props.notifyScreenreader,
automationData: "sdk-ordering-add-answer"
}), includeLabels && this.renderLabel('bottomLabel', t('Bottom Label'))), /*#__PURE__*/ jsx(QuestionSettingsContainer, {
additionalOptions: this.props.additionalOptions
}, /*#__PURE__*/ jsx(QuestionSettingsPanel, {
label: t('Options'),
defaultExpanded: true
}, /*#__PURE__*/ jsx(FormFieldGroup, {
rowSpacing: "small",
description: this.renderOptionsDescription()
}, this.props.showCalculatorOption && /*#__PURE__*/ jsx(CalculatorOptionWithOqaatAlert, {
disabled: nonEditable,
calculatorValue: this.props.calculatorType,
onCalculatorTypeChange: this.handleCalculatorTypeChange,
oqaatChecked: this.props.oneQuestionAtATime,
onOqaatChange: this.props.setOneQuestionAtATime
}), /*#__PURE__*/ jsx(Checkbox, {
label: t('Display Answers in a Paragraph'),
onChange: this.handleDisplayAnswersParagraphChange,
checked: displayAnswersParagraph || false,
disabled: nonEditable,
"data-automation": "sdk-display-answer-in-paragraph-checkbox"
}), /*#__PURE__*/ jsx(Checkbox, {
label: t('Include Labels'),
onChange: this.handleIncludeLabelsChange,
checked: includeLabels || false,
disabled: nonEditable,
"data-automation": "sdk-include-labels-checkbox"
})))));
}
}
]);
return OrderingEdit;
}(Component);
_define_property(OrderingEdit, "displayName", 'OrderingEdit');
_define_property(OrderingEdit, "componentId", "Quizzes".concat(OrderingEdit.displayName));
_define_property(OrderingEdit, "interactionType", OrderingInteractionType);
_define_property(OrderingEdit, "propTypes", _object_spread_props(_object_spread({
additionalOptions: QuestionSettingsContainer.propTypes.additionalOptions,
calculatorType: PropTypes.string,
enableRichContentEditor: PropTypes.bool,
interactionData: PropTypes.shape({
choices: PropTypes.objectOf(PropTypes.shape({
id: PropTypes.string.isRequired,
itemBody: PropTypes.string.isRequired
})).isRequired
}).isRequired,
itemBody: PropTypes.string,
notifyScreenreader: PropTypes.func,
onModalClose: PropTypes.func,
onModalOpen: PropTypes.func,
oneQuestionAtATime: PropTypes.bool,
openImportModal: PropTypes.func,
overrideEditableForRegrading: PropTypes.bool,
properties: PropTypes.shape({
displayAnswersParagraph: PropTypes.bool,
includeLabels: PropTypes.bool,
topLabel: PropTypes.string,
bottomLabel: PropTypes.string
}).isRequired,
scoringData: PropTypes.shape({
value: PropTypes.arrayOf(PropTypes.string).isRequired
}).isRequired,
setOneQuestionAtATime: PropTypes.func
}, withEditTools.injectedProps), {
styles: PropTypes.object,
showCalculatorOption: PropTypes.bool
}));
_define_property(OrderingEdit, "defaultProps", {
additionalOptions: void 0,
calculatorType: 'none',
enableRichContentEditor: true,
itemBody: void 0,
onModalClose: void 0,
onModalOpen: void 0,
oneQuestionAtATime: false,
openImportModal: void 0,
overrideEditableForRegrading: false,
notifyScreenreader: Function.prototype,
setOneQuestionAtATime: Function.prototype,
showCalculatorOption: true
});
export { OrderingEdit as default };
OrderingEdit = _ts_decorate([
withEditTools
], OrderingEdit);