@instructure/quiz-interactions
Version:
A React UI component Library for quiz interaction types.
476 lines (475 loc) • 22.5 kB
JavaScript
/** @jsx jsx */ 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 _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_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 _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 _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;
})();
}
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 PropTypes from 'prop-types';
import { Table } from '@instructure/ui-table';
import { Text } from '@instructure/ui-text';
import { Spinner } from '@instructure/ui-spinner';
import { Checkbox } from '@instructure/ui-checkbox';
import { PresentationContent, ScreenReaderContent } from '@instructure/ui-a11y-content';
import { Button } from '@instructure/ui-buttons';
import { jsx } from '@instructure/emotion';
import { View } from '@instructure/ui-view';
import { Grid } from '@instructure/ui-grid';
import { Decimal } from '@instructure/quiz-i18n';
import { isScientificNotation } from '@instructure/quiz-scientific-notation';
import { toErrors } from '../../../util/instUIMessages';
import * as util from './util';
import generateStyle from './styles';
import generateComponentTheme from './theme';
import t from '@instructure/quiz-i18n/format-message';
import { NumberInput } from '@instructure/quiz-number-input';
import { SimpleSelect, TextArea, withStyleOverrides } from '@instructure/quiz-common';
import { Alert } from '@instructure/ui-alerts';
var FormulaSection = /*#__PURE__*/ function(Component) {
"use strict";
_inherits(FormulaSection, Component);
function FormulaSection() {
_class_call_check(this, FormulaSection);
var _this;
_this = _call_super(this, FormulaSection, arguments), _define_property(_this, "state", {
marginOfErrorValue: null
}), _define_property(_this, "handleMarginOfErrorChange", function(event, value, normalizedValue) {
_this.setState({
marginOfErrorValue: value
});
_this.props.handleMarginOfErrorChange(event, value, normalizedValue);
}), _define_property(_this, "handleMarginOfErrorBlur", function() {
_this.setState({
marginOfErrorValue: null
});
}), _define_property(_this, "localizedScientificNotation", function(value) {
var _ref = _sliced_to_array((value === null || value === void 0 ? void 0 : value.toString().split('*')) || [], 2), mantissa = _ref[0], exponent = _ref[1];
return "".concat(_this.localizedValue(mantissa), "*").concat(exponent);
}), _define_property(_this, "localizedValue", function(value) {
return value ? Decimal.toLocaleString(value.toString(), _this.props.locale) : null;
}), _define_property(_this, "renderRow", function(solution, idx) {
var inputValues = _this.variableNames.map(function(variableName) {
var _solution_inputs_find;
return (_solution_inputs_find = solution.inputs.find(function(v) {
return v.name === variableName;
})) === null || _solution_inputs_find === void 0 ? void 0 : _solution_inputs_find.value;
});
var _this_props_scoringData_value_numeric = _this.props.scoringData.value.numeric, margin = _this_props_scoringData_value_numeric.margin, marginType = _this_props_scoringData_value_numeric.marginType;
var parsedMargin = Number.parseFloat(margin);
var marginString;
if (margin === '' || parsedMargin === 0 || Number.isNaN(parsedMargin)) {
marginString = null;
} else if (marginType === 'absolute') {
marginString = t(' +/- {margin}', {
margin: _this.formatNumStr(parsedMargin)
});
} else {
marginString = t(' +/- {margin}%', {
margin: _this.formatNumStr(parsedMargin)
});
}
return /*#__PURE__*/ jsx(Table.Row, {
key: idx
}, inputValues.map(function(value, index) {
return(// eslint-disable-next-line react/no-array-index-key
/*#__PURE__*/ jsx(Table.Cell, {
key: index
}, _this.formatNumStr(value)));
}), /*#__PURE__*/ jsx(Table.Cell, null, _this.formatNumStr(solution.output), /*#__PURE__*/ jsx("span", {
css: _this.props.styles.marginPlusMinus
}, marginString)));
});
return _this;
}
_create_class(FormulaSection, [
{
key: "formatNumStr",
value: function formatNumStr(value) {
return isScientificNotation(value) ? this.localizedScientificNotation(value) : this.localizedValue(value);
}
},
{
key: "variableNames",
get: function get() {
return this.props.scoringData.value.variables.map(function(variable) {
return variable.name;
}).sort();
}
},
{
key: "renderGeneratedSolutionsTable",
value: function renderGeneratedSolutionsTable() {
if (this.props.status === util.STATUS_RUNNING) {
return /*#__PURE__*/ jsx("div", null, /*#__PURE__*/ jsx(Spinner, {
renderTitle: t('Running')
}));
}
var solutions = this.props.scoringData.value.generatedSolutions;
var errorMessage = null;
if (this.props.status === util.STATUS_FAILED && solutions.length === 0) {
return /*#__PURE__*/ jsx("div", {
role: "alert"
}, /*#__PURE__*/ jsx(Alert, {
hasShadow: false,
variant: "warning"
}, t('We were not able to find any solutions.')));
}
if (this.props.status === util.STATUS_FAILED) {
errorMessage = util.buildSolutionsGeneratedMessage(this.props.status, solutions.length);
} else if (solutions.length === 0) {
return null;
}
var idPrefix = 'generated-results-';
return /*#__PURE__*/ jsx("div", null, errorMessage && /*#__PURE__*/ jsx("div", {
role: "alert"
}, /*#__PURE__*/ jsx(Alert, {
hasShadow: false,
variant: "warning"
}, errorMessage)), /*#__PURE__*/ jsx("div", {
css: this.props.styles.tableWrapper
}, /*#__PURE__*/ jsx(Table, {
caption: t('Generated Results'),
layout: "fixed"
}, /*#__PURE__*/ jsx(Table.Head, null, /*#__PURE__*/ jsx(Table.Row, null, this.variableNames.map(function(variableName, idx) {
return /*#__PURE__*/ jsx(Table.ColHeader, {
id: idPrefix + idx,
key: idx
}, variableName);
}), /*#__PURE__*/ jsx(Table.ColHeader, {
id: "generated-results-result"
}, t('Result')))), /*#__PURE__*/ jsx(Table.Body, null, solutions.map(this.renderRow)))));
}
},
{
key: "renderGeneratedSolutionsSection",
value: function renderGeneratedSolutionsSection() {
if (this.props.status === util.STATUS_CANCELED) {
return null;
}
return /*#__PURE__*/ jsx("div", {
css: this.props.styles.generatedSolutions
}, this.props.status === util.STATUS_FORMULA_SETUP_INVALID ? /*#__PURE__*/ jsx(Alert, {
liveRegionPoliteness: "polite",
variant: "warning"
}, t('Error in formula setup. See above for details.')) : this.renderGeneratedSolutionsTable());
}
},
{
key: "formulaErrors",
value: function formulaErrors() {
if (this.props.status === util.STATUS_FORMULA_SETUP_INVALID) {
return toErrors(this.props.formulaErrors || []);
}
}
},
{
key: "renderNumberOfGeneratedSolutionsInput",
value: function renderNumberOfGeneratedSolutionsInput() {
var currentSolutionsNumber = String(Number.parseInt(this.props.scoringData.value.answerCount, 10) || 0);
return /*#__PURE__*/ jsx(NumberInput, {
disabled: this.props.overrideEditableForRegrading,
value: currentSolutionsNumber,
onChange: this.props.handleAnswerCountChange,
renderLabel: t('Number of solutions'),
isRequired: true,
messages: toErrors(this.props.generatedSolutionsErrors),
min: "1",
max: "200",
showArrows: true,
"data-automation": "sdk-number-of-solutions-input",
"aria-valuetext": "".concat(currentSolutionsNumber, " ").concat(t('Solutions possible'))
});
}
},
{
key: "renderSolutionPrecisionInput",
value: function renderSolutionPrecisionInput() {
var currentDecimalPlaces = this.props.scoringData.value.answerPrecision || 0;
return /*#__PURE__*/ jsx(NumberInput, {
decimalPrecision: 0,
disabled: this.props.overrideEditableForRegrading,
value: currentDecimalPlaces,
onChange: this.props.handleAnswerPrecisionChange,
renderLabel: t('Decimal places'),
min: "0",
max: "16",
showArrows: true,
"aria-valuetext": "".concat(currentDecimalPlaces, " ").concat(t('Decimal places'))
});
}
},
{
key: "renderScientificNotationCheckbox",
value: function renderScientificNotationCheckbox() {
return /*#__PURE__*/ jsx(Checkbox, {
checked: this.props.scoringData.value.scientificNotation || false,
disabled: this.props.overrideEditableForRegrading,
label: t('Display as Scientific Notation'),
onChange: this.props.handleScientificNotationChange,
variant: "toggle"
});
}
},
{
key: "renderMarginOfErrorTypeSelect",
value: function renderMarginOfErrorTypeSelect() {
return /*#__PURE__*/ jsx(SimpleSelect, {
onChange: this.props.handleMarginOfErrorTypeChange,
value: this.props.scoringData.value.numeric.marginType,
renderLabel: t('Margin type'),
"data-automation": "sdk-formula-margin-of-error-type"
}, /*#__PURE__*/ jsx(SimpleSelect.Option, {
id: "formula-section-select-option-absolute",
value: "absolute"
}, t('Absolute')), /*#__PURE__*/ jsx(SimpleSelect.Option, {
id: "formula-section-select-option-percent",
value: "percent"
}, t('Percent')));
}
},
{
key: "renderMarginOfErrorInput",
value: function renderMarginOfErrorInput() {
var value = this.state.marginOfErrorValue;
if (value === null) {
value = Number.parseFloat(this.props.scoringData.value.numeric.margin);
}
return /*#__PURE__*/ jsx(NumberInput, {
value: value,
onChange: this.handleMarginOfErrorChange,
onBlur: this.handleMarginOfErrorBlur,
renderLabel: t('+/- margin of error'),
min: "0",
"data-automation": "sdk-formula-margin-of-error-value",
showArrows: true,
"aria-valuetext": "".concat(value, " ").concat(t('+/- margin of error'))
});
}
},
{
key: "renderGenerateSolutionsButton",
value: function renderGenerateSolutionsButton() {
return /*#__PURE__*/ jsx(Button, {
type: "submit",
disabled: this.props.overrideEditableForRegrading,
color: "primary",
onClick: this.props.handleGenerateSolutions,
"data-automation": "sdk-generate-button"
}, /*#__PURE__*/ jsx(PresentationContent, null, t('Generate')), /*#__PURE__*/ jsx(ScreenReaderContent, null, t('Generate Solutions')));
}
},
{
key: "render",
value: function render() {
return /*#__PURE__*/ jsx("div", null, /*#__PURE__*/ jsx("div", {
css: this.props.styles.sectionHeading
}, /*#__PURE__*/ jsx(Text, {
size: "large"
}, t('Formula Definition'))), /*#__PURE__*/ jsx("div", {
css: this.props.styles.instructions
}, /*#__PURE__*/ jsx(Text, {
color: "primary"
}, t('Next, write the formula or formulas used to compute' + ' the correct answer. Use the same variable names listed above. (e.g., "5 + x")'))), /*#__PURE__*/ jsx(TextArea, {
disabled: this.props.overrideEditableForRegrading,
value: this.props.scoringData.value.formula,
onChange: this.props.handleFormulaChange,
messages: this.formulaErrors(),
label: /*#__PURE__*/ jsx(ScreenReaderContent, null, t('Formula')),
autoGrow: this.context.disableTextAreaAutoGrow ? false : null,
"data-automation": "sdk-formula-definition-text-area"
}), /*#__PURE__*/ jsx("div", null, /*#__PURE__*/ jsx("div", {
css: this.props.styles.sectionHeading
}, /*#__PURE__*/ jsx(Text, {
size: "large"
}, t('Generate Possible Solutions'))), /*#__PURE__*/ jsx("div", {
css: this.props.styles.instructions
}, /*#__PURE__*/ jsx(Text, {
color: "primary"
}, t('Finally, build as many variable-solution combinations as you need for your quiz.'))), /*#__PURE__*/ jsx("div", {
css: this.props.styles.generateSolutionsInput
}, /*#__PURE__*/ jsx(Grid, {
vAlign: "top",
startAt: "medium"
}, /*#__PURE__*/ jsx(Grid.Row, null, /*#__PURE__*/ jsx(Grid.Col, {
width: 4
}, this.renderNumberOfGeneratedSolutionsInput()), /*#__PURE__*/ jsx(Grid.Col, {
width: 4
}, this.renderSolutionPrecisionInput()), /*#__PURE__*/ jsx(Grid.Col, {
width: 4
}, /*#__PURE__*/ jsx(View, {
as: "div",
margin: "medium 0 0 0",
padding: "xx-small 0 0 0"
}, this.renderScientificNotationCheckbox()))), !this.props.scoringData.value.scientificNotation && /*#__PURE__*/ jsx(Grid.Row, null, /*#__PURE__*/ jsx(Grid.Col, {
width: 4
}, this.renderMarginOfErrorTypeSelect()), /*#__PURE__*/ jsx(Grid.Col, {
width: 4
}, this.renderMarginOfErrorInput())), /*#__PURE__*/ jsx(Grid.Row, null, /*#__PURE__*/ jsx(Grid.Col, {
width: 4
}, this.renderGenerateSolutionsButton())))), this.renderGeneratedSolutionsSection()));
}
}
]);
return FormulaSection;
}(Component);
_define_property(FormulaSection, "displayName", 'FormulaSection');
_define_property(FormulaSection, "componentId", "Quizzes".concat(FormulaSection.displayName));
_define_property(FormulaSection, "propTypes", {
formulaErrors: PropTypes.arrayOf(PropTypes.string),
generatedSolutionsErrors: PropTypes.arrayOf(PropTypes.string),
handleAnswerCountChange: PropTypes.func.isRequired,
handleAnswerPrecisionChange: PropTypes.func.isRequired,
handleFormulaChange: PropTypes.func.isRequired,
handleGenerateSolutions: PropTypes.func.isRequired,
handleMarginOfErrorChange: PropTypes.func.isRequired,
handleMarginOfErrorTypeChange: PropTypes.func.isRequired,
handleScientificNotationChange: PropTypes.func.isRequired,
locale: PropTypes.string.isRequired,
overrideEditableForRegrading: PropTypes.bool.isRequired,
scoringData: PropTypes.object.isRequired,
status: PropTypes.string.isRequired,
styles: PropTypes.object
});
_define_property(FormulaSection, "defaultProps", {
formulaErrors: void 0,
generatedSolutionsErrors: void 0
});
_define_property(FormulaSection, "contextTypes", {
disableTextAreaAutoGrow: PropTypes.bool
});
export { FormulaSection as default };
FormulaSection = _ts_decorate([
withStyleOverrides(generateStyle, generateComponentTheme)
], FormulaSection);