UNPKG

@instructure/quiz-interactions

Version:

A React UI component Library for quiz interaction types.

468 lines (462 loc) • 19.5 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_with_holes(arr) { if (Array.isArray(arr)) return arr; } 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 _iterable_to_array_limit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){ _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally{ try { if (!_n && _i["return"] != null) _i["return"](); } finally{ if (_d) throw _e; } } return _arr; } function _non_iterable_rest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } 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 _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 _sliced_to_array(arr, i) { return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest(); } 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; })(); } 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/format-message'; import { v4 as uuid } from 'uuid'; var CategorizationTake = /*#__PURE__*/ function(Component) { "use strict"; _inherits(CategorizationTake, Component); function CategorizationTake(props) { _class_call_check(this, CategorizationTake); var _this; _this = _call_super(this, CategorizationTake, [ props ]), _define_property(_this, "takeId", uuid()), _define_property(_this, "_timeouts", []), _define_property(_this, "categoryRefs", []), // =========== // ACTIONS // =========== _define_property(_this, "resetFocus", function() { _this._timeouts = _this._timeouts.concat(setTimeout(function() { return _this.focusGroup.focusFirst('[role="button"]'); }, 100)); }), _define_property(_this, "onMenuItemSelected", function(answerId, categoryId, removed, event, focusNewCategory) { event && event.preventDefault && event.preventDefault(); var distractorDoesntMatchOptions = !_this.distractorExists(answerId); if (distractorDoesntMatchOptions) { // if distractor for different question // is dropped into this component return; } var newCategoryIndex = _this.categoryIndex(removed ? UNCATEGORIZED : categoryId); var newUserResponse = _this.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 = _this.removeAnswerFromCategory(newUserResponse, answerId, oldCategoryIndex); } // add answer on new category if (newCategoryIndex !== -1) { newUserResponse = _this.addAnswerOnCategory(newUserResponse, answerId, newCategoryIndex); } var selectedCategory = _this.state.sortedCategories.find(function(category) { return category.id == categoryId; }); if (selectedCategory) { var categoryName = selectedCategory.itemBody; if (removed) { _this.props.notifyScreenreader(t('Answer removed from category {category_name}', { category_name: categoryName })); } else { _this.props.notifyScreenreader(t('Answer added to category {category_name}', { category_name: categoryName })); } } _this.props.handleResponseUpdate(_this.includeUncategorized(newUserResponse)); if (focusNewCategory && _this.categoryRefs[categoryId]) { _this.categoryRefs[categoryId].focus(); } }), _define_property(_this, "onDrop", function(idNewCategory, answer, focusNewCategory) { var _answer_id_split = _sliced_to_array(answer.id.split('_'), 2), answerId = _answer_id_split[0], takeId = _answer_id_split[1]; if (takeId === _this.takeId || !takeId) { _this.onMenuItemSelected(answerId, idNewCategory, false, null, focusNewCategory); } }), _define_property(_this, "onDropOut", function(answer) { var _answer_id_split = _sliced_to_array(answer.id.split('_'), 2), answerId = _answer_id_split[0], takeId = _answer_id_split[1]; var categ = _this.props.userResponse.value.find(function(categAux) { return categAux.value.includes(answerId); }); // remove the answer from it's current category if (categ && (takeId === _this.takeId || !takeId)) { _this.onMenuItemSelected(answerId, categ.id, true); } }), // =========== // HELPERS // =========== _define_property(_this, "filterDistractors", function(idCategory) { var _this_props = _this.props, interactionData = _this_props.interactionData, userResponse = _this_props.userResponse; if (!interactionData.distractors || !userResponse.value) return []; return _this.includeUncategorized(userResponse.value).filter(function(category) { return category.id === idCategory || category.id === UNCATEGORIZED; }).reduce(function(distractors, category) { return _to_consumable_array(distractors).concat(_to_consumable_array(category.value.map(function(id) { return interactionData.distractors[id]; }))); }, []); }), _define_property(_this, "focusGroupRef", function(node) { _this.focusGroup = node; }), _define_property(_this, "handleCategoryRef", function(categoryId) { return function(node) { _this.categoryRefs[categoryId] = node; }; }), // =========== // RENDER // =========== _define_property(_this, "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: _this.getDistractorBody(itemId) }) }) }, _this.state.sortedCategories.map(function(categ) { return /*#__PURE__*/ React.createElement(Menu.Item, { key: categ.id, onSelect: function() { return _this.onDrop(categ.id, { id: itemId }, true); } }, categ.itemBody); })); }); var _this_props_interactionData = _this.props.interactionData, categories = _this_props_interactionData.categories, categoryOrder = _this_props_interactionData.categoryOrder; _this.state = { sortedCategories: getSortedCategories(categories, categoryOrder) }; return _this; } _create_class(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, _define_property({}, categoryIndex, { value: { $splice: [ [ answerIndex, 1 ] ] } })); } }, { key: "addAnswerOnCategory", value: function addAnswerOnCategory(source, idAnswer, categoryIndex) { return update(source, _define_property({}, 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 _to_consumable_array(ids).concat(_to_consumable_array(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 _to_consumable_array(userResponseValue.filter(function(category) { return category.id !== UNCATEGORIZED; })).concat([ { 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 }))); } } ]); return CategorizationTake; }(Component); _define_property(CategorizationTake, "propTypes", { handleResponseUpdate: PropTypes.func.isRequired, interactionData: PropTypes.object.isRequired, itemBody: PropTypes.string.isRequired, notifyScreenreader: PropTypes.func.isRequired, userResponse: PropTypes.object.isRequired }); /** --- 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> ``` **/ export { CategorizationTake as default };