UNPKG

@instructure/quiz-interactions

Version:

A React UI component Library for quiz interaction types.

443 lines (442 loc) • 20.6 kB
/** @jsx jsx */ 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 _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 _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 _type_of(obj) { "@swc/helpers - typeof"; return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; } 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 { Component } from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import { v4 as uuid } from 'uuid'; import { Text } from '@instructure/ui-text'; import { jsx } from '@instructure/emotion'; import t from '@instructure/quiz-i18n/format-message'; import { ItemBodyWrapper } from '@instructure/quiz-rce/components/ItemBodyWrapper/index'; import { FeedbackWrapper } from '@instructure/quiz-results-feedback'; import { trimPunctuation, getTrimmedPunctuation } from '../helpers/punctuation'; import generateStyle from './styles'; import generateComponentTheme from './theme'; import { withStyleOverrides } from '@instructure/quiz-common/util/withStyleOverrides'; var FillBlankResult = /*#__PURE__*/ function(Component) { "use strict"; _inherits(FillBlankResult, Component); function FillBlankResult() { _class_call_check(this, FillBlankResult); var _this; _this = _call_super(this, FillBlankResult, arguments), _define_property(_this, "state", { isMounted: false }), _define_property(_this, "itemBodyWrapperId", uuid()), _define_property(_this, "mutationObserver", null), _define_property(_this, "imageLoadHandlers", []), _define_property(_this, "pendingUpdate", null), _define_property(_this, "mutationDebounceTimeout", null), _define_property(_this, "setupImageLoadListeners", function() { if (!_this.props.richFITB) return; // Clean up existing listeners _this.cleanupImageLoadListeners(); var itemBodyWrapper = document.getElementById(_this.itemBodyWrapperId); if (!itemBodyWrapper) return; var images = itemBodyWrapper.querySelectorAll('img'); images.forEach(function(img) { var handleLoad = function() { // Use requestAnimationFrame to ensure DOM has updated before re-rendering if (_this.pendingUpdate) { cancelAnimationFrame(_this.pendingUpdate); } _this.pendingUpdate = requestAnimationFrame(function() { _this.pendingUpdate = null; _this.forceUpdate(); }); }; // If image is already loaded, still trigger re-render if (img.complete && img.naturalHeight !== 0) { handleLoad(); } else { img.addEventListener('load', handleLoad); _this.imageLoadHandlers.push({ img: img, handler: handleLoad }); } }); }), _define_property(_this, "cleanupImageLoadListeners", function() { _this.imageLoadHandlers.forEach(function(param) { var img = param.img, handler = param.handler; img.removeEventListener('load', handler); }); _this.imageLoadHandlers = []; }), _define_property(_this, "setupMutationObserver", function() { if (!_this.props.richFITB) return; // Clean up existing observer _this.cleanupMutationObserver(); var itemBodyWrapper = document.getElementById(_this.itemBodyWrapperId); if (!itemBodyWrapper) return; // Create observer to watch for blank elements being added to DOM _this.mutationObserver = new MutationObserver(function(mutations) { var hasNewBlankElements = mutations.some(function(mutation) { return Array.from(mutation.addedNodes).some(function(node) { if (node.nodeType === Node.ELEMENT_NODE) { var _node_id, _node_querySelector; return ((_node_id = node.id) === null || _node_id === void 0 ? void 0 : _node_id.startsWith('blank_')) || ((_node_querySelector = node.querySelector) === null || _node_querySelector === void 0 ? void 0 : _node_querySelector.call(node, '[id^="blank_"]')); } return false; }); }); if (hasNewBlankElements) { // Debounce to batch multiple mutations into a single re-render if (_this.mutationDebounceTimeout) { clearTimeout(_this.mutationDebounceTimeout); } _this.mutationDebounceTimeout = setTimeout(function() { _this.mutationDebounceTimeout = null; _this.forceUpdate(); }, 50); } }); _this.mutationObserver.observe(itemBodyWrapper, { childList: true, subtree: true }); }), _define_property(_this, "cleanupMutationObserver", function() { if (_this.mutationObserver) { _this.mutationObserver.disconnect(); _this.mutationObserver = null; } if (_this.mutationDebounceTimeout) { clearTimeout(_this.mutationDebounceTimeout); _this.mutationDebounceTimeout = null; } }), // ============= // RENDER // ============= _define_property(_this, "getBlankStatus", function(blankId) { var blankResult = _this.__getBlankScoredData(blankId); var status; if (blankResult && blankResult.resultScore > 0) { status = 'correct'; } else if (blankResult && blankResult.resultScore <= 0 || _this.__correctnessKnown()) { status = 'incorrect'; } else { status = 'unknown'; } return status; }), _define_property(_this, "renderBlank", function(blankId) { var renderBefore = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : null, renderAfer = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : null; var blankResult = _this.__getBlankScoredData(blankId); var status = _this.getBlankStatus(blankId); var innerStyle = _object_spread({}, _this.props.styles.feedbackWrapper); var mergedStyle = status === 'incorrect' ? _object_spread({}, innerStyle, _this.props.styles.incorrectFeedbackWrapper) : innerStyle; var responseText = blankResult && blankResult.userResponse; return /*#__PURE__*/ jsx("div", { key: blankId, css: _this.props.styles.blank }, renderBefore, /*#__PURE__*/ jsx("div", { css: mergedStyle }, /*#__PURE__*/ jsx(FeedbackWrapper, { userResponse: blankResult && blankResult.userResponse, correctAnswer: blankResult && blankResult.correctAnswer, hiddenCorrectAnswerText: t('Correct answer:'), hiddenIncorrectAnswerText: t('Incorrect answer:'), status: status }, /*#__PURE__*/ jsx("div", { css: _this.props.styles.userResponse }, /*#__PURE__*/ jsx(Text, { wrap: "break-word", color: "primary" }, responseText || (_this.__responseHidden() ? t('(response not displayed)') : t('(no answer)')))))), renderAfer); }), _define_property(_this, "renderStemItemBlank", function(stemItem) { var punctuation = getTrimmedPunctuation(stemItem, _this.props.interactionData.stemItems); return _this.renderBlank(stemItem.blankId, punctuation.start, punctuation.end); }), _define_property(_this, "renderRichBlanks", function() { var itemBodyWrapper = document.getElementById(_this.itemBodyWrapperId); if (!itemBodyWrapper) return null; return _this.props.interactionData.blanks.map(function(blank) { var targetEl = itemBodyWrapper.querySelector("#blank_".concat(blank.id)); return targetEl ? /*#__PURE__*/ ReactDOM.createPortal(_this.renderBlank(blank.id), targetEl, blank.id) : null; }).filter(Boolean); }), _define_property(_this, "renderStemItem", function(stemItem) { if (stemItem.type === 'text') { return /*#__PURE__*/ jsx(Text, { wrap: "break-word", color: "primary", key: stemItem.id }, trimPunctuation(stemItem, _this.props.interactionData.stemItems)); } return _this.renderStemItemBlank(stemItem); }); return _this; } _create_class(FillBlankResult, [ { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { this.props.makeStyles(); if (this.props.interactionData.blanks !== prevProps.interactionData.blanks) { this.renderRichBlanks(); this.setupImageLoadListeners(); this.setupMutationObserver(); } } }, { key: "componentDidMount", value: function componentDidMount() { this.props.makeStyles(); this.setState({ isMounted: true }); this.setupImageLoadListeners(); this.setupMutationObserver(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.cleanupImageLoadListeners(); this.cleanupMutationObserver(); if (this.pendingUpdate) { cancelAnimationFrame(this.pendingUpdate); this.pendingUpdate = null; } if (this.mutationDebounceTimeout) { clearTimeout(this.mutationDebounceTimeout); this.mutationDebounceTimeout = null; } } }, { key: "__multipleChoiceResult", value: function __multipleChoiceResult(blank, blankResultValue, choiceResult) { var pickedChoice = choiceResult.id && this.__getChoiceById(choiceResult.id); var userResponseItemBody = pickedChoice && pickedChoice.itemBody; var correctAnswerItemBody; // For dropdown and wordbank the resultScore is not present if the question was not answered. if (!choiceResult.resultScore || choiceResult.resultScore <= 0) { var correctAnswerKey = Object.keys(blankResultValue).find(function(choice) { return blankResultValue[choice].resultScore === 1; }); var correctAnswer = correctAnswerKey && this.__getChoiceById(correctAnswerKey); correctAnswerItemBody = correctAnswer && correctAnswer.itemBody; } return { resultScore: choiceResult.resultScore, userResponse: userResponseItemBody, correctAnswer: correctAnswerItemBody }; } }, { key: "__specifiedAnswersResult", value: function __specifiedAnswersResult(blank, blankResultValue, choiceResult) { var correctAnswers = Object.keys(blankResultValue).filter(function(answer) { return blankResultValue[answer].resultScore === 1; }); return { resultScore: choiceResult.resultScore, userResponse: choiceResult.id, correctAnswer: correctAnswers.join(t(', ')) }; } }, { key: "__getUserResponseFromChoices", value: function __getUserResponseFromChoices(blankResultValue) { if (!blankResultValue) return {}; var userResponseKey = Object.keys(blankResultValue).find(function(choiceKey) { return blankResultValue[choiceKey].userResponded; }); return Object.assign({}, blankResultValue[userResponseKey], { id: userResponseKey }); } }, { key: "__getBlankScoredData", value: function __getBlankScoredData(blankId) { var scoredData = this.props.scoredData; var blankResult = scoredData.value ? scoredData.value[blankId] : {}; var blank = this.props.interactionData.blanks.find(function(blank) { return blank.id === blankId; }); var blankResultValue = blankResult && blankResult.value; if (!blankResultValue) { if (blankResult && Array.isArray(blankResult.correctAnswer)) { blankResult.correctAnswer = blankResult.correctAnswer.join(t(', ')); } return blankResult; } var choiceResult = this.__getUserResponseFromChoices(blankResultValue); if (blank.answerType !== 'openEntry' && !this.__malformedWordBankBlankResult(blank, blankResult)) { return this.__multipleChoiceResult(blank, blankResultValue, choiceResult); } return this.__specifiedAnswersResult(blank, blankResultValue, choiceResult); } }, { key: "__malformedWordBankBlankResult", value: function __malformedWordBankBlankResult(blank, blankResult) { return blank.answerType === 'wordbank' && 'value' in blankResult && !blank['choices']; } }, { key: "__getChoiceById", value: function __getChoiceById(choiceId) { var blanks = this.props.interactionData.blanks || []; var allChoices = blanks.reduce(function(choices, blank) { return choices.concat(blank.choices || []); }, []); return allChoices.find(function(blank) { return blank.id === choiceId; }); } }, { key: "__responseHidden", value: function __responseHidden() { return !this.props.scoredData.value; } }, { key: "__correctnessKnown", value: function __correctnessKnown() { return typeof this.props.scoredData.correct !== 'undefined'; } }, { key: "render", value: function render() { if (this.props.richFITB) { return /*#__PURE__*/ jsx(ItemBodyWrapper, { id: this.itemBodyWrapperId, itemBody: this.props.itemBody }, this.renderRichBlanks()); } return /*#__PURE__*/ jsx(ItemBodyWrapper, { itemBody: this.props.interactionData.prompt }, /*#__PURE__*/ jsx("div", { css: this.props.styles.stem }, (this.props.interactionData.stemItems || []).slice().sort(function(a, b) { return a.position - b.position; }).map(this.renderStemItem))); } } ]); return FillBlankResult; }(Component); _define_property(FillBlankResult, "displayName", 'FillBlankResult'); _define_property(FillBlankResult, "componentId", "Quizzes".concat(FillBlankResult.displayName)); _define_property(FillBlankResult, "propTypes", { interactionData: PropTypes.object.isRequired, itemBody: PropTypes.string, richFITB: PropTypes.bool, scoredData: PropTypes.shape({ correct: PropTypes.bool, value: PropTypes.objectOf(PropTypes.object) }).isRequired, makeStyles: PropTypes.func, styles: PropTypes.object }); _define_property(FillBlankResult, "defaultProps", { itemBody: '', richFITB: false }); export { FillBlankResult as default }; FillBlankResult = _ts_decorate([ withStyleOverrides(generateStyle, generateComponentTheme) ], FillBlankResult);