UNPKG

@instructure/quiz-interactions

Version:

A React UI component Library for quiz interaction types.

354 lines (345 loc) • 15.9 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); 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 _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _react = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _immutabilityHelper = _interopRequireDefault(require("immutability-helper")); var _findIndex = _interopRequireDefault(require("lodash/findIndex")); var _uiButtons = require("@instructure/ui-buttons"); var _uiMenu = require("@instructure/ui-menu"); var _uiIcons = require("@instructure/ui-icons"); var _quizRce = require("@instructure/quiz-rce"); var _ChoicesList = _interopRequireDefault(require("../common/ChoicesList")); var _CategoriesContainer = _interopRequireDefault(require("../common/CategoriesContainer")); var _FocusGroup = _interopRequireDefault(require("../../common/components/FocusGroup")); var _utils = require("../common/utils"); var _formatMessage = _interopRequireDefault(require("@instructure/quiz-i18n/es/format-message")); var _uuid = require("uuid"); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } 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 = (0, _getPrototypeOf2["default"])(derived); return (0, _possibleConstructorReturn2["default"])(_this, isNativeReflectConstruct() ? Reflect.construct(derived, args || [], (0, _getPrototypeOf2["default"])(_this).constructor) : derived.apply(_this, args)); } /** --- 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 = exports["default"] = /*#__PURE__*/function (_Component) { function CategorizationTake(props) { var _this2; (0, _classCallCheck2["default"])(this, CategorizationTake); _this2 = _callSuper(this, CategorizationTake, [props]); (0, _defineProperty2["default"])(_this2, "takeId", (0, _uuid.v4)()); (0, _defineProperty2["default"])(_this2, "_timeouts", []); (0, _defineProperty2["default"])(_this2, "categoryRefs", []); // =========== // ACTIONS // =========== (0, _defineProperty2["default"])(_this2, "resetFocus", function () { _this2._timeouts = _this2._timeouts.concat(setTimeout(function () { return _this2.focusGroup.focusFirst('[role="button"]'); }, 100)); }); (0, _defineProperty2["default"])(_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 ? _utils.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((0, _formatMessage["default"])('Answer removed from category {category_name}', { category_name: categoryName })); } else { _this2.props.notifyScreenreader((0, _formatMessage["default"])('Answer added to category {category_name}', { category_name: categoryName })); } } _this2.props.handleResponseUpdate(_this2.includeUncategorized(newUserResponse)); if (focusNewCategory && _this2.categoryRefs[categoryId]) { _this2.categoryRefs[categoryId].focus(); } }); (0, _defineProperty2["default"])(_this2, "onDrop", function (idNewCategory, answer, focusNewCategory) { var _answer$id$split = answer.id.split('_'), _answer$id$split2 = (0, _slicedToArray2["default"])(_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); } }); (0, _defineProperty2["default"])(_this2, "onDropOut", function (answer) { var _answer$id$split3 = answer.id.split('_'), _answer$id$split4 = (0, _slicedToArray2["default"])(_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 // =========== (0, _defineProperty2["default"])(_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 === _utils.UNCATEGORIZED; }).reduce(function (distractors, category) { return [].concat((0, _toConsumableArray2["default"])(distractors), (0, _toConsumableArray2["default"])(category.value.map(function (id) { return interactionData.distractors[id]; }))); }, []); }); (0, _defineProperty2["default"])(_this2, "focusGroupRef", function (node) { _this2.focusGroup = node; }); (0, _defineProperty2["default"])(_this2, "handleCategoryRef", function (categoryId) { return function (node) { _this2.categoryRefs[categoryId] = node; }; }); // =========== // RENDER // =========== (0, _defineProperty2["default"])(_this2, "renderPopover", function (itemId) { return /*#__PURE__*/_react["default"].createElement(_uiMenu.Menu, { trigger: /*#__PURE__*/_react["default"].createElement(_uiButtons.IconButton, { size: "small", withBackground: false, withBorder: false, as: "span", renderIcon: _uiIcons.IconDragHandleLine, screenReaderLabel: (0, _formatMessage["default"])('Select Category for {distractorBody}', { distractorBody: _this2.getDistractorBody(itemId) }) }) }, _this2.state.sortedCategories.map(function (categ) { return /*#__PURE__*/_react["default"].createElement(_uiMenu.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: (0, _utils.getSortedCategories)(categories, categoryOrder) }; return _this2; } (0, _inherits2["default"])(CategorizationTake, _Component); return (0, _createClass2["default"])(CategorizationTake, [{ key: "componentWillUnmount", value: function componentWillUnmount() { this._timeouts.forEach(clearTimeout); } }, { key: "categoryIndex", value: function categoryIndex(idCategory) { return (0, _findIndex["default"])(this.props.userResponse.value, { id: idCategory }); } }, { key: "removeAnswerFromCategory", value: function removeAnswerFromCategory(source, idAnswer, categoryIndex) { var answerIndex = source[categoryIndex].value.indexOf(idAnswer); return (0, _immutabilityHelper["default"])(source, (0, _defineProperty2["default"])({}, categoryIndex, { value: { $splice: [[answerIndex, 1]] } })); } }, { key: "addAnswerOnCategory", value: function addAnswerOnCategory(source, idAnswer, categoryIndex) { return (0, _immutabilityHelper["default"])(source, (0, _defineProperty2["default"])({}, 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 !== _utils.UNCATEGORIZED; }).reduce(function (ids, category) { return [].concat((0, _toConsumableArray2["default"])(ids), (0, _toConsumableArray2["default"])(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((0, _toConsumableArray2["default"])(userResponseValue.filter(function (category) { return category.id !== _utils.UNCATEGORIZED; })), [{ id: _utils.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["default"].createElement(_quizRce.ItemBodyWrapper, { itemBody: this.props.itemBody }, /*#__PURE__*/_react["default"].createElement(_FocusGroup["default"], { ref: this.focusGroupRef }, /*#__PURE__*/_react["default"].createElement(_CategoriesContainer["default"], { 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["default"].createElement(_ChoicesList["default"], { takeId: this.takeId, actionsContent: this.renderPopover, distractors: this.filterDistractors(), onDrop: this.onDropOut, isDraggable: true }))); } }]); }(_react.Component); (0, _defineProperty2["default"])(CategorizationTake, "propTypes", { handleResponseUpdate: _propTypes["default"].func.isRequired, interactionData: _propTypes["default"].object.isRequired, itemBody: _propTypes["default"].string.isRequired, notifyScreenreader: _propTypes["default"].func.isRequired, userResponse: _propTypes["default"].object.isRequired });