UNPKG

@instructure/quiz-interactions

Version:

A React UI component Library for quiz interaction types.

623 lines (622 loc) • 27.7 kB
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 React, { Component } from 'react'; import PropTypes from 'prop-types'; import { v4 as uuid } from 'uuid'; import { ScreenReaderContent } from '@instructure/ui-a11y-content'; import { View } from '@instructure/ui-view'; import { Grid } from '@instructure/ui-grid'; import withEditTools from '../../../util/withEditTools'; import Errors from '../../common/edit/components/Errors'; import FocusGroup from '../../common/components/FocusGroup'; import Footer from '../../common/edit/components/Footer'; import NumericInteractionType from '../../../records/interactions/numeric'; import QuestionSettingsContainer from '../../common/edit/components/QuestionSettingsContainer'; import QuestionContainer from '../../common/edit/components/QuestionContainer'; import RemoveChoiceButton from '../../common/edit/components/RemoveChoiceButton'; import t from '@instructure/quiz-i18n/format-message'; import { Decimal } from '@instructure/quiz-i18n'; import QuestionSettingsPanel from '../../common/edit/components/QuestionSettingsPanel'; import CalculatorOptionWithOqaatAlert from '../../common/edit/components/CalculatorOptionWithOqaatAlert'; import ExactResponse from './ExactResponse'; import MarginOfError from './MarginOfError'; import PreciseResponse from './PreciseResponse'; import RequirementHelpModal from './RequirementHelpModal'; import WithinARange from './WithinARange'; import { EXACT_RESPONSE, MARGIN_OF_ERROR, PERCENT, PRECISE_RESPONSE, SIGNIFICANT_DIGITS, WITHIN_A_RANGE } from './constants'; import NumericTypeSelect from './NumericTypeSelect'; import { FormFieldGroup, parseSeparators } from '@instructure/quiz-common'; import { ApplyLocaleContext } from '@instructure/ui-i18n'; export function getNewValue(answer, type) { var newValue = { id: answer.id || '', type: type }; switch(type){ case EXACT_RESPONSE: Object.assign(newValue, { value: answer.value || '' }); break; case MARGIN_OF_ERROR: Object.assign(newValue, { value: answer.value || '', margin: answer.margin || '', marginType: answer.marginType || PERCENT }); break; case WITHIN_A_RANGE: Object.assign(newValue, { start: answer.start || '', end: answer.end || '' }); break; case PRECISE_RESPONSE: Object.assign(newValue, { value: answer.value || '', precision: answer.precision || '', precisionType: answer.precisionType || SIGNIFICANT_DIGITS }); break; } return newValue; } var NumericEdit = /*#__PURE__*/ function(Component) { "use strict"; _inherits(NumericEdit, Component); function NumericEdit() { _class_call_check(this, NumericEdit); var _this; _this = _call_super(this, NumericEdit, arguments), _define_property(_this, "typeSelectInputRefs", {}), _define_property(_this, "choicesFocusGroup", null), _define_property(_this, "stemElement", null), _define_property(_this, "_timeouts", []), _define_property(_this, "state", { helpModalOpen: false }), // =========== // HANDLERS // =========== _define_property(_this, "handleTypeChange", function(event, param) { var id = param.id, type = param.type; var answers = _to_consumable_array(_this.answers); var index = answers.findIndex(function(answer) { return answer.id === id; }); console.assert(index !== -1); // eslint-disable-line no-console answers[index] = getNewValue(answers[index], type); _this.props.changeItemState({ scoringData: _object_spread_props(_object_spread({}, _this.props.scoringData), { value: answers }) }); setTimeout(function() { _this.typeSelectInputRefs[id].focus(); }, 0); }), _define_property(_this, "handleChange", function(event, answer) { var answers = _to_consumable_array(_this.answers); var index = answers.findIndex(function(param) { var id = param.id; return id === answer.id; }); console.assert(index !== -1); // eslint-disable-line no-console var updatedAnswer = _object_spread({}, answers[index], answer); answers[index] = updatedAnswer; _this.props.changeItemState({ scoringData: _object_spread_props(_object_spread({}, _this.props.scoringData), { value: answers }) }); }), _define_property(_this, "handleCalculatorTypeChange", function(e, value) { _this.props.changeItemState({ calculatorType: value }); }), _define_property(_this, "handleCreateAnswer", function() { _this._timeouts = _to_consumable_array(_this._timeouts).concat([ setTimeout(function() { return _this.choicesFocusGroup.focusLast('select'); }, 100) ]); var id = _this.props.newId(); var newValue = getNewValue({ id: id }, EXACT_RESPONSE); _this.props.changeItemState({ scoringData: _object_spread_props(_object_spread({}, _this.props.scoringData), { value: _to_consumable_array(_this.answers).concat([ newValue ]) }) }); }), _define_property(_this, "handleRemoveChoice", function(id) { // In FF clicking on a button doesn't focus it if (document.activeElement !== document.body) { _this.updateFocusOnRemove(); } var answers = _this.answers.filter(function(answer) { return answer.id !== id; }); _this.props.changeItemState({ scoringData: _object_spread_props(_object_spread({}, _this.props.scoringData), { value: answers }) }); }), _define_property(_this, "openHelpModal", function() { return _this.setState({ helpModalOpen: true }); }), _define_property(_this, "closeHelpModal", function() { return _this.setState({ helpModalOpen: false }); }), _define_property(_this, "handleChoicesFocusGroupRef", function(node) { _this.choicesFocusGroup = node; }), _define_property(_this, "handleStemRef", function(node) { _this.stemElement = node; }), _define_property(_this, "setTypeSelectInputRef", function(id, node) { _this.typeSelectInputRefs[id] = node; }), _define_property(_this, "renderAnswerWrapper", function(answer) { var id = answer.id, type = answer.type; return /*#__PURE__*/ React.createElement(Grid, { startAt: "medium", key: id, colSpacing: "small" }, /*#__PURE__*/ React.createElement(Grid.Row, null, /*#__PURE__*/ React.createElement(Grid.Col, { rowSpacing: "none" }, /*#__PURE__*/ React.createElement(FormFieldGroup, { vAlign: "top", rowSpacing: "none", name: id, layout: "columns", description: /*#__PURE__*/ React.createElement(ScreenReaderContent, null, t('Possible answer')) }, _this.renderAnswerContents(answer))), _this.answers.length > 1 && /*#__PURE__*/ React.createElement(Grid.Col, { width: "auto" }, /*#__PURE__*/ React.createElement(View, { as: "div", margin: "large 0 0", themeOverride: { marginLarge: '1.875rem' } }, /*#__PURE__*/ React.createElement(RemoveChoiceButton, { onClick: function() { return _this.handleRemoveChoice(answer.id); }, choiceId: type, screenReaderText: t('Remove Answer: {answer}', { answer: _this.stringifyAnswer(answer) }) }))))); }); return _this; } _create_class(NumericEdit, [ { key: "componentWillUnmount", value: function componentWillUnmount() { this._timeouts.forEach(clearTimeout); } }, { key: "componentDidMount", value: function componentDidMount() { Decimal.accountSettingDelimiters = this.props.separatorConfig ? parseSeparators(this.props.separatorConfig) : null; } }, { key: "locale", get: function get() { return this.props.locale || this.context.locale || 'en-US'; } }, { key: "answers", get: function get() { return this.props.scoringData.value; } }, { key: "stringifyAnswer", value: function stringifyAnswer(param) { var type = param.type, value = param.value, start = param.start, end = param.end, margin = param.margin, marginType = param.marginType, precision = param.precision, precisionType = param.precisionType; var orBlank = function(val) { return val || 'blank'; }; var _obj; return (_obj = {}, _define_property(_obj, EXACT_RESPONSE, t('value of {value}', { value: orBlank(value) })), _define_property(_obj, MARGIN_OF_ERROR, t('value of {value} with a margin of error of {margin} {marginType}', { value: orBlank(value), margin: orBlank(margin), marginType: marginType })), _define_property(_obj, WITHIN_A_RANGE, t('range from {start} to {end}', { start: orBlank(start), end: orBlank(end) })), _define_property(_obj, PRECISE_RESPONSE, t('value of {value} with a precision of {precision} {precisionType}', { value: orBlank(value), precision: orBlank(precision), precisionType: precisionType })), _obj)[type]; } }, { key: "updateFocusOnRemove", value: function updateFocusOnRemove() { var _this = this; var selector = 'button'; var textContent = 'Remove Answer'; if (!this.choicesFocusGroup.previousExists(selector, textContent)) { // if removing the first choice, focus on stem // added timeout to compensate for RCE sluggishness this._timeouts = _to_consumable_array(this._timeouts).concat([ setTimeout(function() { return _this.stemElement.focus(); }, 100) ]); } else if (this.answers.length === 2) { // if removing the second choice out of two choices this._timeouts = _to_consumable_array(this._timeouts).concat([ setTimeout(function() { return _this.choicesFocusGroup.focusLast(); }, 100) ]); } else { // all the other cases this.choicesFocusGroup.focusPrevious(selector, textContent); } } }, { // =========== // RENDERS // =========== key: "renderAnswerField", value: function renderAnswerField(param, index) { var id = param.id, value = param.value; return /*#__PURE__*/ React.createElement(ExactResponse, { id: id, locale: this.locale, messages: this.props.getErrors("scoringData.value[".concat(index, "]"), {}), numericTypeSelect: this.renderNumericTypeSelect(id, EXACT_RESPONSE), onChange: this.handleChange, value: value }); } }, { key: "renderPrecisionAnswer", value: function renderPrecisionAnswer(param, index) { var id = param.id, precision = param.precision, precisionType = param.precisionType, value = param.value; return /*#__PURE__*/ React.createElement(PreciseResponse, { id: id, locale: this.locale, messages: this.props.getErrors("scoringData.value[".concat(index, "]"), {}), numericTypeSelect: this.renderNumericTypeSelect(id, PRECISE_RESPONSE), onChange: this.handleChange, precision: precision, precisionType: precisionType, value: value }); } }, { key: "renderMarginAnswer", value: function renderMarginAnswer(param, index) { var id = param.id, margin = param.margin, marginType = param.marginType, value = param.value; return /*#__PURE__*/ React.createElement(MarginOfError, { id: id, locale: this.locale, margin: margin, marginType: marginType, messages: this.props.getErrors("scoringData.value[".concat(index, "]"), {}), numericTypeSelect: this.renderNumericTypeSelect(id, MARGIN_OF_ERROR), onChange: this.handleChange, value: value }); } }, { key: "renderRangeAnswer", value: function renderRangeAnswer(param, index) { var id = param.id, start = param.start, end = param.end; return /*#__PURE__*/ React.createElement(WithinARange, { end: end, id: id, locale: this.locale, messages: this.props.getErrors("scoringData.value[".concat(index, "]"), {}), numericTypeSelect: this.renderNumericTypeSelect(id, WITHIN_A_RANGE), onChange: this.handleChange, start: start }); } }, { key: "renderNumericTypeSelect", value: function renderNumericTypeSelect(id, value) { return /*#__PURE__*/ React.createElement(NumericTypeSelect, { id: id, inputRef: this.setTypeSelectInputRef, onChange: this.handleTypeChange, onClickHelp: this.openHelpModal, value: value }); } }, { key: "renderAnswerContents", value: function renderAnswerContents(answer) { var index = this.answers.findIndex(function(param) { var id = param.id; return id === answer.id; }); console.assert(index !== -1); // eslint-disable-line no-console switch(answer.type){ case WITHIN_A_RANGE: return this.renderRangeAnswer(answer, index); case MARGIN_OF_ERROR: return this.renderMarginAnswer(answer, index); case PRECISE_RESPONSE: return this.renderPrecisionAnswer(answer, index); default: return this.renderAnswerField(answer, index); } } }, { key: "renderOptionsDescription", value: function renderOptionsDescription() { return /*#__PURE__*/ React.createElement(ScreenReaderContent, null, t('Numeric options')); } }, { key: "render", value: function render() { var name = "edit_interaction_".concat(this.props.itemId); return /*#__PURE__*/ React.createElement("div", null, /*#__PURE__*/ React.createElement(QuestionContainer, { disabled: this.props.overrideEditableForRegrading, 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 }, /*#__PURE__*/ React.createElement(FocusGroup, { ref: this.handleChoicesFocusGroupRef, asComponent: Errors, asProps: { errorList: this.props.getErrors('scoringData.errors') } }, /*#__PURE__*/ React.createElement(FormFieldGroup, { vAlign: "bottom", rowSpacing: "medium", name: name, description: /*#__PURE__*/ React.createElement(ScreenReaderContent, null, t('A list of possible answers')) }, this.answers.map(this.renderAnswerWrapper))), /*#__PURE__*/ React.createElement(Footer, { buttonText: t('Possible Answer'), onCreateChoice: this.handleCreateAnswer, screenReaderText: t('Add Possible Answer'), notifyScreenreader: this.props.notifyScreenreader, automationData: "sdk-add-possible-answer-button" })), /*#__PURE__*/ React.createElement(QuestionSettingsContainer, { additionalOptions: this.props.additionalOptions }, this.props.showCalculatorOption && /*#__PURE__*/ React.createElement(QuestionSettingsPanel, { label: t('Options'), defaultExpanded: true }, /*#__PURE__*/ React.createElement(FormFieldGroup, { rowSpacing: "small", description: this.renderOptionsDescription() }, /*#__PURE__*/ React.createElement(CalculatorOptionWithOqaatAlert, { disabled: this.props.overrideEditableForRegrading, calculatorValue: this.props.calculatorType, onCalculatorTypeChange: this.handleCalculatorTypeChange, oqaatChecked: this.props.oneQuestionAtATime, onOqaatChange: this.props.setOneQuestionAtATime })))), /*#__PURE__*/ React.createElement(RequirementHelpModal, { onDismiss: this.closeHelpModal, open: this.state.helpModalOpen })); } } ]); return NumericEdit; }(Component); _define_property(NumericEdit, "interactionType", NumericInteractionType); _define_property(NumericEdit, "propTypes", _object_spread_props(_object_spread({ additionalOptions: QuestionSettingsContainer.propTypes.additionalOptions, calculatorType: PropTypes.string, changeItemState: PropTypes.func, enableRichContentEditor: PropTypes.bool, itemBody: PropTypes.string.isRequired, itemId: PropTypes.string, locale: PropTypes.string, newId: PropTypes.func, onModalClose: PropTypes.func, onModalOpen: PropTypes.func, oneQuestionAtATime: PropTypes.bool, openImportModal: PropTypes.func, overrideEditableForRegrading: PropTypes.bool, scoringData: PropTypes.shape({ value: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string.isRequired, type: PropTypes.string.isRequired })).isRequired }).isRequired, setOneQuestionAtATime: PropTypes.func }, withEditTools.injectedProps), { showCalculatorOption: PropTypes.bool, separatorConfig: PropTypes.shape({ decimalSeparator: PropTypes.string, thousandSeparator: PropTypes.string }) })); _define_property(NumericEdit, "contextType", ApplyLocaleContext); _define_property(NumericEdit, "defaultProps", { calculatorType: 'none', enableRichContentEditor: true, oneQuestionAtATime: false, overrideEditableForRegrading: false, newId: uuid, setOneQuestionAtATime: Function.prototype, additionalOptions: void 0, changeItemState: void 0, itemId: void 0, locale: void 0, onModalClose: void 0, onModalOpen: void 0, openImportModal: void 0, showCalculatorOption: true }); export { NumericEdit as default }; NumericEdit = _ts_decorate([ withEditTools ], NumericEdit);