@instructure/quiz-interactions
Version:
A React UI component Library for quiz interaction types.
347 lines (338 loc) • 13.3 kB
JavaScript
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
function _callSuper(_this, derived, args) {
function isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
return !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
} catch (e) {
return false;
}
}
derived = _getPrototypeOf(derived);
return _possibleConstructorReturn(_this, isNativeReflectConstruct() ? Reflect.construct(derived, args || [], _getPrototypeOf(_this).constructor) : derived.apply(_this, args));
}
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import update from 'immutability-helper';
import findIndex from 'lodash/findIndex';
import { IconButton } from '@instructure/ui-buttons';
import { Menu } from '@instructure/ui-menu';
import { IconDragHandleLine } from '@instructure/ui-icons';
import { ItemBodyWrapper } from '@instructure/quiz-rce';
import ChoicesList from '../common/ChoicesList';
import CategoriesContainer from '../common/CategoriesContainer';
import FocusGroup from '../../common/components/FocusGroup';
import { UNCATEGORIZED, getSortedCategories } from '../common/utils';
import t from '@instructure/quiz-i18n/es/format-message';
import { v4 as uuid } from 'uuid';
/**
---
category: Categorization
---
Categorization Take component
```jsx_example
const WrappedExample = DragDropContext(HTML5Backend)(CategorizationTake)
function Example (props) {
const exampleProps = {
itemBody: 'Match the name of the celestial body on the left with its correct classification:',
interactionData: {
categoryOrder: ['uuid1', 'uuid2', 'uuid11'],
categories: {
uuid1: { id: 'uuid1', itemBody: 'Planet' },
uuid2: { id: 'uuid2', itemBody: 'Moon' },
uuid11: { id: 'uuid11', itemBody: 'Galaxy' }
},
distractors: {
uuid3: { id: 'uuid3', itemBody: 'Mars' },
uuid4: { id: 'uuid4', itemBody: 'Europa' },
uuid5: { id: 'uuid5', itemBody: 'Venus' },
uuid6: { id: 'uuid6', itemBody: 'Phobos' },
uuid7: { id: 'uuid7', itemBody: 'Deimos' },
uuid8: { id: 'uuid8', itemBody: 'Jupiter' },
uuid9: { id: 'uuid9', itemBody: 'America' },
uuid10: { id: 'uuid10', itemBody: 'Asia' }
}
},
userResponse: {
value: [{
id: 'uuid1',
value: ['uuid3', 'uuid5', 'uuid8'],
type: 'ArrayText'
},{
id: 'uuid2',
value: ['uuid4', 'uuid6', 'uuid7'],
type: 'ArrayText'
}, {
id: 'uuid11',
value: [],
type: 'ArrayText'
}]
}
}
return (
<WrappedExample {...exampleProps} {...props} />
)
}
<SettingsSwitcher locales={LOCALES}>
<TakeStateProvider>
<Example />
</TakeStateProvider>
</SettingsSwitcher>
```
**/
var CategorizationTake = /*#__PURE__*/function (_Component) {
function CategorizationTake(props) {
var _this2;
_classCallCheck(this, CategorizationTake);
_this2 = _callSuper(this, CategorizationTake, [props]);
_defineProperty(_this2, "takeId", uuid());
_defineProperty(_this2, "_timeouts", []);
_defineProperty(_this2, "categoryRefs", []);
// ===========
// ACTIONS
// ===========
_defineProperty(_this2, "resetFocus", function () {
_this2._timeouts = _this2._timeouts.concat(setTimeout(function () {
return _this2.focusGroup.focusFirst('[role="button"]');
}, 100));
});
_defineProperty(_this2, "onMenuItemSelected", function (answerId, categoryId, removed, event, focusNewCategory) {
event && event.preventDefault && event.preventDefault();
var distractorDoesntMatchOptions = !_this2.distractorExists(answerId);
if (distractorDoesntMatchOptions) {
// if distractor for different question
// is dropped into this component
return;
}
var newCategoryIndex = _this2.categoryIndex(removed ? UNCATEGORIZED : categoryId);
var newUserResponse = _this2.props.userResponse.value || [];
// remove answer from former category if exists
var oldCategoryIndex = newUserResponse.findIndex(function (category) {
return category.value.includes(answerId);
});
if (oldCategoryIndex !== -1) {
newUserResponse = _this2.removeAnswerFromCategory(newUserResponse, answerId, oldCategoryIndex);
}
// add answer on new category
if (newCategoryIndex !== -1) {
newUserResponse = _this2.addAnswerOnCategory(newUserResponse, answerId, newCategoryIndex);
}
var selectedCategory = _this2.state.sortedCategories.find(function (category) {
return category.id == categoryId;
});
if (selectedCategory) {
var categoryName = selectedCategory.itemBody;
if (removed) {
_this2.props.notifyScreenreader(t('Answer removed from category {category_name}', {
category_name: categoryName
}));
} else {
_this2.props.notifyScreenreader(t('Answer added to category {category_name}', {
category_name: categoryName
}));
}
}
_this2.props.handleResponseUpdate(_this2.includeUncategorized(newUserResponse));
if (focusNewCategory && _this2.categoryRefs[categoryId]) {
_this2.categoryRefs[categoryId].focus();
}
});
_defineProperty(_this2, "onDrop", function (idNewCategory, answer, focusNewCategory) {
var _answer$id$split = answer.id.split('_'),
_answer$id$split2 = _slicedToArray(_answer$id$split, 2),
answerId = _answer$id$split2[0],
takeId = _answer$id$split2[1];
if (takeId === _this2.takeId || !takeId) {
_this2.onMenuItemSelected(answerId, idNewCategory, false, null, focusNewCategory);
}
});
_defineProperty(_this2, "onDropOut", function (answer) {
var _answer$id$split3 = answer.id.split('_'),
_answer$id$split4 = _slicedToArray(_answer$id$split3, 2),
answerId = _answer$id$split4[0],
takeId = _answer$id$split4[1];
var categ = _this2.props.userResponse.value.find(function (categAux) {
return categAux.value.includes(answerId);
});
// remove the answer from it's current category
if (categ && (takeId === _this2.takeId || !takeId)) {
_this2.onMenuItemSelected(answerId, categ.id, true);
}
});
// ===========
// HELPERS
// ===========
_defineProperty(_this2, "filterDistractors", function (idCategory) {
var _this2$props = _this2.props,
interactionData = _this2$props.interactionData,
userResponse = _this2$props.userResponse;
if (!interactionData.distractors || !userResponse.value) return [];
return _this2.includeUncategorized(userResponse.value).filter(function (category) {
return category.id === idCategory || category.id === UNCATEGORIZED;
}).reduce(function (distractors, category) {
return [].concat(_toConsumableArray(distractors), _toConsumableArray(category.value.map(function (id) {
return interactionData.distractors[id];
})));
}, []);
});
_defineProperty(_this2, "focusGroupRef", function (node) {
_this2.focusGroup = node;
});
_defineProperty(_this2, "handleCategoryRef", function (categoryId) {
return function (node) {
_this2.categoryRefs[categoryId] = node;
};
});
// ===========
// RENDER
// ===========
_defineProperty(_this2, "renderPopover", function (itemId) {
return /*#__PURE__*/React.createElement(Menu, {
trigger: /*#__PURE__*/React.createElement(IconButton, {
size: "small",
withBackground: false,
withBorder: false,
as: "span",
renderIcon: IconDragHandleLine,
screenReaderLabel: t('Select Category for {distractorBody}', {
distractorBody: _this2.getDistractorBody(itemId)
})
})
}, _this2.state.sortedCategories.map(function (categ) {
return /*#__PURE__*/React.createElement(Menu.Item, {
key: categ.id,
onSelect: function onSelect() {
return _this2.onDrop(categ.id, {
id: itemId
}, true);
}
}, categ.itemBody);
}));
});
var _this2$props$interact = _this2.props.interactionData,
categories = _this2$props$interact.categories,
categoryOrder = _this2$props$interact.categoryOrder;
_this2.state = {
sortedCategories: getSortedCategories(categories, categoryOrder)
};
return _this2;
}
_inherits(CategorizationTake, _Component);
return _createClass(CategorizationTake, [{
key: "componentWillUnmount",
value: function componentWillUnmount() {
this._timeouts.forEach(clearTimeout);
}
}, {
key: "categoryIndex",
value: function categoryIndex(idCategory) {
return findIndex(this.props.userResponse.value, {
id: idCategory
});
}
}, {
key: "removeAnswerFromCategory",
value: function removeAnswerFromCategory(source, idAnswer, categoryIndex) {
var answerIndex = source[categoryIndex].value.indexOf(idAnswer);
return update(source, _defineProperty({}, categoryIndex, {
value: {
$splice: [[answerIndex, 1]]
}
}));
}
}, {
key: "addAnswerOnCategory",
value: function addAnswerOnCategory(source, idAnswer, categoryIndex) {
return update(source, _defineProperty({}, categoryIndex, {
value: {
$push: [idAnswer]
}
}));
}
}, {
key: "getDistractorBody",
value: function getDistractorBody(distractorId) {
return this.props.interactionData.distractors[distractorId.split('_')[0]].itemBody;
}
}, {
key: "categorizedDistractors",
value: function categorizedDistractors(userResponseValue) {
if (!userResponseValue) return new Set();
return new Set(userResponseValue.filter(function (category) {
return category.id !== UNCATEGORIZED;
}).reduce(function (ids, category) {
return [].concat(_toConsumableArray(ids), _toConsumableArray(category.value));
}, []));
}
}, {
key: "uncategorizedDistractors",
value: function uncategorizedDistractors(userResponseValue) {
var interactionData = this.props.interactionData;
if (!interactionData.distractors) return [];
var categorized = this.categorizedDistractors(userResponseValue);
return Object.keys(interactionData.distractors).filter(function (id) {
return !categorized.has(id);
});
}
}, {
key: "includeUncategorized",
value: function includeUncategorized(userResponseValue) {
return [].concat(_toConsumableArray(userResponseValue.filter(function (category) {
return category.id !== UNCATEGORIZED;
})), [{
id: UNCATEGORIZED,
value: this.uncategorizedDistractors(userResponseValue),
type: 'ArrayText'
}]);
}
}, {
key: "distractorExists",
value: function distractorExists(answerId) {
var distractorIds = Object.keys(this.props.interactionData.distractors);
return distractorIds.includes(answerId);
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/React.createElement(ItemBodyWrapper, {
itemBody: this.props.itemBody
}, /*#__PURE__*/React.createElement(FocusGroup, {
ref: this.focusGroupRef
}, /*#__PURE__*/React.createElement(CategoriesContainer, {
takeId: this.takeId,
sortedCategories: this.state.sortedCategories,
distractors: this.props.interactionData.distractors,
filterDistractors: this.filterDistractors,
handleCategoryRef: this.handleCategoryRef,
isDraggable: true,
onDrop: this.onDrop,
onDropOut: this.onDropOut,
onMenuItemSelected: this.onMenuItemSelected,
userResponseValue: this.props.userResponse.value
}), /*#__PURE__*/React.createElement(ChoicesList, {
takeId: this.takeId,
actionsContent: this.renderPopover,
distractors: this.filterDistractors(),
onDrop: this.onDropOut,
isDraggable: true
})));
}
}]);
}(Component);
_defineProperty(CategorizationTake, "propTypes", {
handleResponseUpdate: PropTypes.func.isRequired,
interactionData: PropTypes.object.isRequired,
itemBody: PropTypes.string.isRequired,
notifyScreenreader: PropTypes.func.isRequired,
userResponse: PropTypes.object.isRequired
});
export { CategorizationTake as default };