quiz-interactions
Version:
A React UI component Library for quiz interaction types.
728 lines (624 loc) • 26.5 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf3 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _striptags = _interopRequireDefault(require("striptags"));
var _uuid = require("uuid");
var _getOr = _interopRequireDefault(require("lodash/fp/getOr"));
var _set = _interopRequireDefault(require("lodash/fp/set"));
var _sortBy = _interopRequireDefault(require("lodash/fp/sortBy"));
var _findIndex = _interopRequireDefault(require("lodash/fp/findIndex"));
var _find = _interopRequireDefault(require("lodash/fp/find"));
var _filter = _interopRequireDefault(require("lodash/fp/filter"));
var _last = _interopRequireDefault(require("lodash/fp/last"));
var _map = _interopRequireDefault(require("lodash/fp/map"));
var _xor = _interopRequireDefault(require("lodash/fp/xor"));
var _remove = _interopRequireDefault(require("lodash/fp/remove"));
var _uiForms = require("@instructure/ui-forms");
var _uiFormField = require("@instructure/ui-form-field");
var _uiA11y = require("@instructure/ui-a11y");
var _ChoiceInput = _interopRequireDefault(require("../../common/edit/components/ChoiceInput"));
var _ChoiceInputWrapper = _interopRequireDefault(require("../../common/edit/components/ChoiceInputWrapper"));
var _Errors = _interopRequireDefault(require("../../common/edit/components/Errors"));
var _Footer = _interopRequireDefault(require("../../common/edit/components/Footer"));
var _multiple_choice = _interopRequireDefault(require("../../../records/interactions/multiple_choice"));
var _QuestionSettingsContainer = _interopRequireDefault(require("../../common/edit/components/QuestionSettingsContainer"));
var _QuestionContainer = _interopRequireDefault(require("../../common/edit/components/QuestionContainer"));
var _withEditTools = _interopRequireDefault(require("../../../util/withEditTools"));
var _interactionPoints = _interopRequireDefault(require("../../../util/interactionPoints"));
var _formatMessage = _interopRequireDefault(require("@instructure/quiz-i18n/lib/format-message"));
var _QuestionSettingsPanel = _interopRequireDefault(require("../../common/edit/components/QuestionSettingsPanel"));
var _CalculatorOptionWithOqaatAlert = _interopRequireDefault(require("../../common/edit/components/CalculatorOptionWithOqaatAlert"));
var _class, _class2, _temp;
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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var MultipleChoiceEdit =
/**
---
category: MultipleChoice
---
Multiple Choice Edit component
```jsx_example
function Example (props) {
const exampleProps = {
itemBody: 'Who was the first President of the United States?',
interactionData: {
choices: [
{ id: 'uuid1', itemBody: 'George Washington', position: 1 },
{ id: 'uuid2', itemBody: 'Alexander Hamilton.', position: 2 },
{ id: 'uuid3', itemBody: 'John Adams', position: 3 },
{ id: 'uuid4', itemBody: 'Thomas Jefferson', position: 4 }
]
},
properties: {
varyPointsByAnswer: false,
shuffleRules: {
choices: {
shuffled: true,
toLock: [0, 1]
}
}
},
scoringData: {
value: 'uuid1'
},
additionalOptions: [{
key: 'outcomes',
title: 'Align to Outcomes',
component: 'Placeholder'
}]
}
return (
<MultipleChoiceEdit {...exampleProps} {...props} />
)
}
<SettingsSwitcher locales={LOCALES}>
<EditStateProvider>
<Example />
</EditStateProvider>
</SettingsSwitcher>
```
**/
(0, _withEditTools.default)(_class = (_temp = _class2 =
/*#__PURE__*/
function (_Component) {
(0, _inherits2.default)(MultipleChoiceEdit, _Component);
function MultipleChoiceEdit() {
var _getPrototypeOf2;
var _this;
(0, _classCallCheck2.default)(this, MultipleChoiceEdit);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = (0, _possibleConstructorReturn2.default)(this, (_getPrototypeOf2 = (0, _getPrototypeOf3.default)(MultipleChoiceEdit)).call.apply(_getPrototypeOf2, [this].concat(args)));
_this.state = {
expanded: _this.getChoices().reduce(function (expand, choice) {
expand[choice.id] = false; // eslint-disable-line no-param-reassign
return expand;
}, {})
};
_this.stemElement = null;
_this.choiceRefs = [];
_this._timeouts = [];
_this._choiceWasCreated = false;
_this.handleAnswerFeedbackToggle = function (choiceId) {
_this.setState(function (state) {
return {
expanded: Object.assign({}, state.expanded, (0, _defineProperty2.default)({}, choiceId, !state.expanded[choiceId]))
};
});
};
_this.handleStemRef = function (node) {
_this.stemElement = node;
};
_this.handleCalculatorTypeChange = function (e, value) {
_this.props.changeItemState({
calculatorType: value
});
};
_this.handleRemoveChoice = function (choiceId, index) {
_this.updateFocusOnRemove(index); // Update scoringData
var choices = _this.getChoices();
var scoringData = {};
if (_this.props.scoringData.value === choiceId) {
scoringData.value = null;
}
if (_this.shouldVaryPoints()) {
scoringData.values = (0, _remove.default)({
value: choiceId
}, _this.props.scoringData.values);
}
_this.updateScoringData(scoringData); // Update interactionData and properties
var shuffleRules = _this.props.properties.shuffleRules; // Move the locks in conjuntion with the answers
var toLock = (0, _map.default)(function (value) {
return value < index ? value : value - 1;
}, (0, _filter.default)(function (lock) {
return lock !== index;
}, shuffleRules.choices.toLock));
var localFeedback = Object.assign({}, _this.props.answerFeedback);
delete localFeedback[choiceId];
_this.props.changeItemState({
interactionData: _objectSpread({}, _this.props.interactionData, {
choices: (0, _remove.default)({
id: choiceId
}, choices)
}),
properties: _objectSpread({}, _this.props.properties, {
shuffleRules: (0, _set.default)('choices.toLock', toLock, shuffleRules)
}),
answerFeedback: localFeedback
});
};
_this.handleInputChange = function (choiceId, event, _ref) {
var editorContent = _ref.editorContent;
var choices = _this.getChoices();
var index = (0, _findIndex.default)({
id: choiceId
}, choices);
_this.props.changeItemState({
interactionData: _objectSpread({}, _this.props.interactionData, {
choices: (0, _set.default)("[".concat(index, "].itemBody"), editorContent, choices)
})
});
};
_this.handleCreateChoice = function () {
var id = _this.props.newId();
if (_this.shouldVaryPoints()) {
_this.updateScoringData({
values: [].concat((0, _toConsumableArray2.default)(_this.props.scoringData.values), [{
value: id,
points: 0
}])
});
}
_this._choiceWasCreated = true;
_this.props.changeItemState({
interactionData: _objectSpread({}, _this.props.interactionData, {
choices: [].concat((0, _toConsumableArray2.default)(_this.getChoices()), [{
id: id,
itemBody: '',
position: Math.max.apply(Math, [-1].concat((0, _toConsumableArray2.default)((0, _map.default)('position', _this.getChoices())))) + 1
}])
})
});
};
_this.handleVaryPointsByAnswerChange = function (event) {
_this.toggleVaryPointsByAnswer(event);
};
_this.handleShuffleChange = function (event) {
_this.toggleShuffleChoices();
};
return _this;
}
(0, _createClass2.default)(MultipleChoiceEdit, [{
key: "componentWillUnmount",
value: function componentWillUnmount() {
this._timeouts.forEach(clearTimeout);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
if (this._choiceWasCreated) {
this._choiceWasCreated = false;
(0, _last.default)(this.choiceRefs).focusOnAnswerInput();
}
} // ===========
// HELPERS
// ===========
}, {
key: "getChoices",
value: function getChoices() {
return (0, _getOr.default)([], 'interactionData.choices', this.props);
}
}, {
key: "isShuffled",
value: function isShuffled() {
return (0, _getOr.default)(false, 'properties.shuffleRules.choices.shuffled', this.props);
}
}, {
key: "shouldVaryPoints",
value: function shouldVaryPoints() {
return (0, _getOr.default)(false, 'properties.varyPointsByAnswer', this.props);
}
}, {
key: "isChoiceLocked",
value: function isChoiceLocked(choiceId) {
var index = (0, _findIndex.default)({
id: choiceId
}, this.getChoices());
var lockedChoices = (0, _getOr.default)(false, 'properties.shuffleRules.choices.toLock', this.props);
if (lockedChoices) {
return lockedChoices.includes(index);
}
return false;
}
}, {
key: "getScoringDataValues",
value: function getScoringDataValues() {
return this.props.scoringData.values || (0, _map.default)(function (_ref2) {
var id = _ref2.id;
return {
value: id,
points: 0
};
}, this.getChoices());
}
}, {
key: "updateScoringData",
value: function updateScoringData(changes) {
var scoringData = Object.assign({}, this.props.scoringData, changes); // Only calls pointsChange when necessary
if (this.shouldVaryPoints()) {
if (scoringData.values === null) {
// TODO should values be allowed to be undefined?
delete scoringData.values;
} // TODO Raising pointsChange with undefined would allow consumer to reset to points of their choice
this.props.pointsChange((0, _interactionPoints.default)({
properties: this.props.properties,
scoringData: scoringData
}) || 1);
}
this.props.changeItemState({
scoringData: scoringData
}, {
scoringData: changes
});
}
}, {
key: "updateFocusOnRemove",
value: function updateFocusOnRemove(index) {
var _this2 = this;
if (index === 0) {
// if removing the first choice, focus on stem
this.stemElement.focus();
} else if (this.getChoices().length === 2) {
// if removing the second choice out of two choices
this._timeouts = [].concat((0, _toConsumableArray2.default)(this._timeouts), [setTimeout(function () {
return _this2.choiceRefs[index - 1].focusLast();
})]);
} else {
// all the other cases
this.choiceRefs[index - 1].focusLast();
}
} // Returns true if there are any falsy values (based on default props)
}, {
key: "hasVisibileOptions",
value: function hasVisibileOptions() {
var _this3 = this;
var hiddenOptionKeys = Object.keys(MultipleChoiceEdit.defaultProps.hiddenOptions);
return hiddenOptionKeys.some(function (key) {
return !_this3.props.hiddenOptions[key]; // falsy means at least one visible
});
} // ===========
// HANDLERS
// ===========
}, {
key: "override",
value: function override() {
return this.props.overrideEditableForItem || this.props.overrideEditableForRegrading;
}
}, {
key: "toggleVaryPointsByAnswer",
value: function toggleVaryPointsByAnswer(event) {
var scoringAlgorithm;
if (event.target.checked) {
scoringAlgorithm = 'VaryPointsByAnswer';
this.updateScoringData({
values: this.getScoringDataValues()
});
} else {
scoringAlgorithm = 'Equivalence';
this.updateScoringData({
values: null
});
}
var update = {
scoringAlgorithm: scoringAlgorithm,
properties: {
varyPointsByAnswer: event.target.checked
}
};
this.props.changeItemState(_objectSpread({}, update, {
properties: _objectSpread({}, this.props.properties, {}, update.properties)
}), update);
}
}, {
key: "toggleShuffleChoices",
value: function toggleShuffleChoices() {
var newShuffled = !this.isShuffled();
var properties;
if (this.props.properties.shuffleRules !== void 0) {
properties = (0, _set.default)('shuffleRules.choices.shuffled', newShuffled, this.props.properties);
} else {
properties = {
shuffleRules: {
choices: {
shuffled: newShuffled
}
}
};
}
var messageForScreenreader = newShuffled ? (0, _formatMessage.default)('Shuffling turned on. Navigate to a choice to lock it in place.') : (0, _formatMessage.default)('Shuffling turned off.');
this.props.notifyScreenreader(messageForScreenreader);
this.props.changeItemState({
properties: properties
}, {
properties: {
shuffleRules: {
choices: {
shuffled: newShuffled
}
}
}
});
}
}, {
key: "makeAnswerPointsChangeHandler",
value: function makeAnswerPointsChangeHandler(choiceId) {
var _this4 = this;
return function (points) {
_this4.updateScoringData({
values: (0, _map.default)(function (item) {
return item.value !== choiceId ? item : {
value: choiceId,
points: points
};
}, _this4.getScoringDataValues())
});
};
}
}, {
key: "makeChoiceLockedToggler",
value: function makeChoiceLockedToggler(choiceId) {
var _this5 = this;
return function () {
var index = (0, _findIndex.default)({
id: choiceId
}, _this5.getChoices());
var toLock = (0, _xor.default)([index], _this5.props.properties.shuffleRules.choices.toLock);
var properties = (0, _set.default)('shuffleRules.choices.toLock', toLock, _this5.props.properties);
var messageForScreenreader = _this5.isChoiceLocked(choiceId) ? (0, _formatMessage.default)('Choice unlocked') : (0, _formatMessage.default)('Choice locked');
_this5.props.notifyScreenreader(messageForScreenreader);
_this5.props.changeItemState({
properties: properties
}, {
properties: {
shuffleRules: {
choices: {
toLock: toLock
}
}
}
});
};
} // ===========
// RENDERS
// ===========
}, {
key: "renderChoice",
value: function renderChoice(choice, name, index) {
var _this6 = this;
var shouldVaryPoints = this.shouldVaryPoints();
var choiceInputProps = {
disabledFields: this.override() ? ['answerInput'] : [],
id: choice.id,
itemBody: choice.itemBody,
ref: function ref(node) {
_this6.choiceRefs[index] = node;
},
errors: this.props.getErrors("interactionData.choices.".concat(index, ".itemBody")),
noRCE: !this.props.enableRichContentEditor,
onAnswerPointsChange: this.makeAnswerPointsChangeHandler(choice.id),
onInputChange: this.handleInputChange,
onModalClose: this.props.onModalClose,
onModalOpen: this.props.onModalOpen,
onRemoveChoice: function onRemoveChoice() {
return _this6.handleRemoveChoice(choice.id, index);
},
parentType: this.props.parentType,
shouldRenderRemoveChoice: !this.override() && this.getChoices().length !== 1,
shouldRenderAnswerPoints: shouldVaryPoints,
shouldRenderAnswerFeedback: !this.override() && this.props.answerFeedbackEnabled,
openImportModal: this.props.openImportModal,
readOnlyFields: this.override() ? ['answerInput'] : [],
renderImportModal: this.props.renderImportModal,
handleAnswerFeedbackToggle: this.handleAnswerFeedbackToggle.bind(this),
expanded: this.state.expanded[choice.id],
changeItemState: this.props.changeItemState,
answerFeedback: this.props.answerFeedback,
notifyScreenreader: this.props.notifyScreenreader
};
if (shouldVaryPoints) {
var answerValue = (0, _find.default)({
value: choice.id
}, this.props.scoringData.values) || {};
choiceInputProps.answerPoints = answerValue.points || 0;
}
if (this.isShuffled()) {
choiceInputProps.showLock = true;
choiceInputProps.isLocked = this.isChoiceLocked(choice.id);
choiceInputProps.toggleChoiceLocked = this.makeChoiceLockedToggler(choice.id);
}
var labelText = choice.itemBody.trim() === '' ? (0, _formatMessage.default)('Radio button for blank answer') : (0, _formatMessage.default)('Radio button for answer { answer }', {
answer: (0, _striptags.default)(choice.itemBody)
});
return _react.default.createElement(_ChoiceInputWrapper.default, {
key: choice.id,
choiceInput: _react.default.createElement(_ChoiceInput.default, choiceInputProps),
customInput: _react.default.createElement(_uiForms.RadioInput, {
disabled: this.props.overrideEditableForItem,
onChange: function onChange() {
return _this6.updateScoringData({
value: choice.id
});
},
name: name,
label: _react.default.createElement(_uiA11y.ScreenReaderContent, null, labelText),
value: choice.id,
checked: this.props.scoringData.value === choice.id
})
});
}
}, {
key: "renderInputGroup",
value: function renderInputGroup() {
var _this7 = this;
var choices = (0, _sortBy.default)('position', this.getChoices());
var name = "edit_interaction_".concat(this.props.itemId);
var errors = [].concat((0, _toConsumableArray2.default)(this.props.getErrors('interactionData.choices.$errors')), (0, _toConsumableArray2.default)(this.props.getErrors('scoringData.value')));
return _react.default.createElement(_Errors.default, {
errorList: errors
}, _react.default.createElement(_uiFormField.FormFieldGroup, {
rowSpacing: "small",
name: name,
description: _react.default.createElement(_uiA11y.ScreenReaderContent, null, (0, _formatMessage.default)('A list of potential answers'))
}, choices.map(function (choice, index) {
return _this7.renderChoice(choice, name, index);
})));
}
}, {
key: "renderOptionsDescription",
value: function renderOptionsDescription() {
return _react.default.createElement(_uiA11y.ScreenReaderContent, null, (0, _formatMessage.default)('Multiple choice options'));
}
}, {
key: "render",
value: function render() {
// clean up the references to ChoiceInputs
this.choiceRefs = [];
return _react.default.createElement("div", null, _react.default.createElement(_QuestionContainer.default, {
disabled: this.override(),
enableRichContentEditor: this.props.enableRichContentEditor,
itemBody: this.props.itemBody,
onDescriptionChange: this.props.onDescriptionChange,
onModalClose: this.props.onModalClose,
onModalOpen: this.props.onModalOpen,
openImportModal: this.props.openImportModal,
readOnly: this.override(),
renderImportModal: this.props.renderImportModal,
stemErrors: this.props.getErrors('itemBody'),
textareaRef: this.handleStemRef
}, this.renderInputGroup(), !this.override() && _react.default.createElement(_Footer.default, {
onCreateChoice: this.handleCreateChoice
})), _react.default.createElement(_QuestionSettingsContainer.default, {
additionalOptions: this.props.additionalOptions
}, this.hasVisibileOptions() && _react.default.createElement(_QuestionSettingsPanel.default, {
label: (0, _formatMessage.default)('Options'),
defaultExpanded: true
}, _react.default.createElement(_uiFormField.FormFieldGroup, {
rowSpacing: "small",
description: this.renderOptionsDescription()
}, !this.props.hiddenOptions.calculator && _react.default.createElement(_CalculatorOptionWithOqaatAlert.default, {
disabled: this.props.overrideEditableForRegrading,
calculatorValue: this.props.calculatorType,
onCalculatorTypeChange: this.handleCalculatorTypeChange,
oqaatChecked: this.props.oneQuestionAtATime,
onOqaatChange: this.props.setOneQuestionAtATime
}), !this.props.hiddenOptions.varyPointsByAnswer && _react.default.createElement(_uiForms.Checkbox, {
label: (0, _formatMessage.default)('Vary points by answer'),
onChange: this.handleVaryPointsByAnswerChange,
checked: this.shouldVaryPoints(),
disabled: this.props.overrideEditableForRegrading
}), !this.props.hiddenOptions.shuffleChoices && _react.default.createElement(_uiForms.Checkbox, {
label: (0, _formatMessage.default)('Shuffle Choices'),
onChange: this.handleShuffleChange,
checked: this.isShuffled(),
disabled: this.props.overrideEditableForRegrading
})))));
}
}]);
MultipleChoiceEdit.displayName = "MultipleChoiceEdit";
return MultipleChoiceEdit;
}(_react.Component), _class2.interactionType = _multiple_choice.default, _class2.propTypes = _objectSpread({
additionalOptions: _QuestionSettingsContainer.default.propTypes.additionalOptions,
answerFeedbackEnabled: _propTypes.default.bool,
answerFeedback: _ChoiceInput.default.propTypes.answerFeedback,
calculatorType: _propTypes.default.string,
changeItemState: _propTypes.default.func,
enableRichContentEditor: _propTypes.default.bool,
errors: _propTypes.default.object,
// TODO: This appears unused, figure out if we can delete it
errorsAreShowing: _propTypes.default.bool,
hiddenOptions: _propTypes.default.shape({
calculator: _propTypes.default.bool,
varyPointsByAnswer: _propTypes.default.bool,
shuffleChoices: _propTypes.default.bool
}),
interactionData: _propTypes.default.shape({
choices: _propTypes.default.arrayOf(_propTypes.default.shape({
id: _propTypes.default.string,
itemBody: _propTypes.default.string,
position: _propTypes.default.number
}))
}).isRequired,
itemBody: _propTypes.default.string,
itemId: _propTypes.default.string,
newId: _propTypes.default.func,
notifyScreenreader: _propTypes.default.func,
onModalClose: _propTypes.default.func,
onModalOpen: _propTypes.default.func,
oneQuestionAtATime: _propTypes.default.bool,
overrideEditableForItem: _propTypes.default.bool,
overrideEditableForRegrading: _propTypes.default.bool,
parentType: _propTypes.default.string,
pointsChange: _propTypes.default.func,
properties: _propTypes.default.shape({
varyPointsByAnswer: _propTypes.default.bool,
shuffleRules: _propTypes.default.shape({
choices: _propTypes.default.shape({
shuffled: _propTypes.default.bool,
toLock: _propTypes.default.arrayOf(_propTypes.default.number)
})
})
}).isRequired,
scoringData: _propTypes.default.shape({
value: _propTypes.default.string,
values: _propTypes.default.arrayOf(_propTypes.default.shape({
value: _propTypes.default.string,
points: _propTypes.default.number
}))
}).isRequired,
openImportModal: _propTypes.default.func,
renderImportModal: _propTypes.default.func,
setOneQuestionAtATime: _propTypes.default.func
}, _withEditTools.default.injectedProps), _class2.defaultProps = {
answerFeedbackEnabled: false,
answerFeedback: {},
calculatorType: 'none',
enableRichContentEditor: true,
hiddenOptions: {
calculator: true,
varyPointsByAnswer: false,
shuffleChoices: false
},
newId: _uuid.v4,
notifyScreenreader: Function.prototype,
oneQuestionAtATime: false,
overrideEditableForItem: false,
overrideEditableForRegrading: false,
parentType: '',
pointsChange: Function.prototype,
additionalOptions: void 0,
changeItemState: void 0,
errors: void 0,
errorsAreShowing: void 0,
itemBody: void 0,
itemId: void 0,
onModalClose: void 0,
onModalOpen: void 0,
openImportModal: void 0,
renderImportModal: Function.prototype,
setOneQuestionAtATime: void 0
}, _temp)) || _class;
exports.default = MultipleChoiceEdit;