@pie-element/math-templated 5.3.4-next.0 → 6.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/main.js CHANGED
@@ -1,884 +1,768 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
4
  Object.defineProperty(exports, "__esModule", {
6
5
  value: true
7
6
  });
8
- exports["default"] = exports.Main = void 0;
9
-
10
- var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
11
-
12
- var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
13
-
14
- var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
15
-
16
- var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
17
-
18
- var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
19
-
20
- var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
21
-
7
+ exports.default = exports.Main = void 0;
22
8
  var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
23
-
24
9
  var _react = _interopRequireDefault(require("react"));
25
-
26
10
  var _propTypes = _interopRequireDefault(require("prop-types"));
27
-
28
- var _classnames = _interopRequireDefault(require("classnames"));
29
-
30
11
  var _isEqual = _interopRequireDefault(require("lodash/isEqual"));
31
-
32
12
  var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));
33
-
34
- var _styles = require("@material-ui/core/styles");
35
-
36
- var _Tooltip = _interopRequireDefault(require("@material-ui/core/Tooltip"));
37
-
13
+ var _styles = require("@mui/material/styles");
14
+ var _Tooltip = _interopRequireDefault(require("@mui/material/Tooltip"));
38
15
  var _mathInput = require("@pie-lib/math-input");
39
-
40
16
  var _renderUi = require("@pie-lib/render-ui");
41
-
42
17
  var _mathRendering = require("@pie-lib/math-rendering");
43
-
44
18
  var _mathquill = _interopRequireDefault(require("@pie-framework/mathquill"));
45
-
46
19
  var _maskMarkup = require("@pie-lib/mask-markup");
47
-
48
20
  var _correctAnswerToggle = _interopRequireDefault(require("@pie-lib/correct-answer-toggle"));
49
-
50
21
  var _reactDom = _interopRequireDefault(require("react-dom"));
22
+ const StyledUiLayout = (0, _styles.styled)(_renderUi.UiLayout)({
23
+ color: _renderUi.color.text(),
24
+ backgroundColor: _renderUi.color.background(),
25
+ display: 'inline-block'
26
+ });
27
+ const MainContainer = (0, _styles.styled)('div')({
28
+ width: '100%',
29
+ position: 'relative',
30
+ backgroundColor: _renderUi.color.background(),
31
+ color: _renderUi.color.text()
32
+ });
33
+ const PromptContainer = (0, _styles.styled)('div')(({
34
+ theme
35
+ }) => ({
36
+ marginBottom: theme.spacing(2)
37
+ }));
38
+ const CollapsibleContainer = (0, _styles.styled)('div')(({
39
+ theme
40
+ }) => ({
41
+ marginBottom: theme.spacing(2)
42
+ }));
43
+ const InputAndKeypadContainer = (0, _styles.styled)('div')({
44
+ position: 'relative',
45
+ '& > div > div': {
46
+ display: 'flex',
47
+ alignItems: 'baseline',
48
+ flexWrap: 'wrap'
49
+ },
50
+ '& .mq-overarrow-inner': {
51
+ border: 'none !important',
52
+ padding: '0 !important'
53
+ },
54
+ '& .mq-overarrow-inner-right': {
55
+ display: 'none !important'
56
+ },
57
+ '& .mq-overarrow-inner-left': {
58
+ display: 'none !important'
59
+ },
60
+ '& .mq-overarrow.mq-arrow-both': {
61
+ minWidth: '1.23em',
62
+ '& *': {
63
+ lineHeight: '1 !important'
64
+ },
65
+ '&:before': {
66
+ top: '-0.4em',
67
+ left: '-1px'
68
+ },
69
+ '&:after': {
70
+ top: '-2.4em',
71
+ right: '-1px'
72
+ },
73
+ '&.mq-empty:after': {
74
+ top: '-0.45em'
75
+ }
76
+ },
77
+ '& .mq-overarrow.mq-arrow-right': {
78
+ '&:before': {
79
+ top: '-0.4em',
80
+ right: '-1px'
81
+ }
82
+ },
83
+ '& .mq-longdiv-inner': {
84
+ borderTop: '1px solid !important',
85
+ paddingTop: '1.5px !important'
86
+ },
87
+ '& .mq-parallelogram': {
88
+ lineHeight: 0.85
89
+ }
90
+ });
91
+ const Expression = (0, _styles.styled)('div')(({
92
+ theme,
93
+ $incorrect,
94
+ $correct,
95
+ $showCorrectness,
96
+ $correctAnswerShown
97
+ }) => ({
98
+ maxWidth: 'fit-content',
99
+ ...($incorrect && {
100
+ borderColor: `${_renderUi.color.incorrect()} !important`
101
+ }),
102
+ ...($correct && {
103
+ borderColor: `${_renderUi.color.correct()} !important`
104
+ }),
105
+ ...($showCorrectness && {
106
+ border: '2px solid'
107
+ }),
108
+ ...($correctAnswerShown && {
109
+ padding: theme.spacing(1),
110
+ letterSpacing: '0.5px'
111
+ }),
112
+ '& > .mq-math-mode': {
113
+ '& > .mq-root-block': {
114
+ '& > .mq-editable-field': {
115
+ minWidth: '10px',
116
+ padding: theme.spacing(0.25)
117
+ }
118
+ },
119
+ '& sup': {
120
+ top: 0
121
+ }
122
+ }
123
+ }));
124
+ const StyledStatic = (0, _styles.styled)(_mathInput.mq.Static)({
125
+ '& > .mq-root-block': {
126
+ '& > .mq-editable-field': {
127
+ borderColor: _renderUi.color.text()
128
+ }
129
+ }
130
+ });
51
131
 
52
- function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }
53
-
54
- function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
55
-
56
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
57
-
58
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
132
+ // Tooltip styling is handled via slotProps, no need for styled component
133
+
134
+ const ResponseContainer = (0, _styles.styled)('div')(({
135
+ theme
136
+ }) => ({
137
+ zIndex: 10,
138
+ minWidth: '400px',
139
+ marginTop: theme.spacing(2)
140
+ }));
141
+ const PrintContainer = (0, _styles.styled)('div')(({
142
+ theme
143
+ }) => ({
144
+ marginBottom: theme.spacing(1),
145
+ pointerEvents: 'none'
146
+ }));
147
+ const SrOnly = (0, _styles.styled)('h2')({
148
+ position: 'absolute',
149
+ left: '-10000px',
150
+ top: 'auto',
151
+ width: '1px',
152
+ height: '1px',
153
+ overflow: 'hidden'
154
+ });
155
+ const Note = (0, _styles.styled)('div')(({
156
+ theme
157
+ }) => ({
158
+ marginBottom: theme.spacing(2)
159
+ }));
160
+ const StyledToggle = (0, _styles.styled)(_correctAnswerToggle.default)(({
161
+ theme
162
+ }) => ({
163
+ color: _renderUi.color.text(),
164
+ marginBottom: theme.spacing(2)
165
+ }));
166
+
167
+ // CSS for classes used in HTML strings and classList operations
168
+ if (typeof document !== 'undefined') {
169
+ const styleId = 'math-templated-main-styles';
170
+ if (!document.getElementById(styleId)) {
171
+ const style = document.createElement('style');
172
+ style.id = styleId;
173
+ style.textContent = `
174
+ .block-container {
175
+ margin: 8px !important;
176
+ display: inline-flex;
177
+ border: 2px solid grey !important;
178
+ }
179
+ .block-response {
180
+ flex: 2;
181
+ color: grey;
182
+ background: rgba(0, 0, 0, 0.04);
183
+ font-size: 0.8rem !important;
184
+ padding: 4px !important;
185
+ display: flex;
186
+ align-items: center;
187
+ justify-content: center;
188
+ border-right: 2px solid #bdbdbd !important;
189
+ }
190
+ .block-math {
191
+ color: ${_renderUi.color.text()};
192
+ background-color: ${_renderUi.color.background()};
193
+ padding: 4px !important;
194
+ display: flex;
195
+ align-items: center;
196
+ justify-content: center;
197
+ flex: 8;
198
+ }
199
+ .block-math > .mq-math-mode > .mq-hasCursor > .mq-cursor {
200
+ display: none;
201
+ }
202
+ .correct {
203
+ border-color: ${_renderUi.color.correct()} !important;
204
+ }
205
+ .incorrect {
206
+ border-color: ${_renderUi.color.incorrect()} !important;
207
+ }
208
+ `;
209
+ document.head.appendChild(style);
210
+ }
211
+ }
212
+ let registered = false;
59
213
 
60
- var registered = false; // Define a regex pattern to match {{number}}
214
+ // Define a regex pattern to match {{number}}
215
+ const REGEX = /(\{\{\d+\}\})/gm;
216
+ const DEFAULT_KEYPAD_VARIANT = 6;
61
217
 
62
- var REGEX = /(\{\{\d+\}\})/gm;
63
- var DEFAULT_KEYPAD_VARIANT = 6; // !!! If you're using Chrome but have selected the "iPad" device in Chrome Developer Tools, the navigator.userAgent string may still report as
218
+ // !!! If you're using Chrome but have selected the "iPad" device in Chrome Developer Tools, the navigator.userAgent string may still report as
64
219
  // Safari because Chrome on iOS actually uses the Safari rendering engine under the hood due to Apple's restrictions on third-party browser engines.
65
220
  // When you select the "iPad" device in Chrome Developer Tools, you're essentially emulating the behavior of Safari on an iPad, including the user agent string.
66
221
  // Therefore, even though you're using Chrome, the user agent string will resemble that of Safari on an iPad.
67
222
  // Since the regular expression /^((?!chrome|android).)*safari/i checks for the presence of "safari" in the user agent string while excluding "chrome" and "android",
68
223
  // it will return true in this case because "safari" is present in the user agent string emulated by Chrome when in iPad mode.
69
-
70
- var IS_SAFARI = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
71
-
72
- function generateAdditionalKeys() {
73
- var keyData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
74
- return keyData.map(function (key) {
75
- return {
76
- name: key,
77
- latex: key,
78
- write: key,
79
- label: key
80
- };
81
- });
224
+ const IS_SAFARI = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
225
+ function generateAdditionalKeys(keyData = []) {
226
+ return keyData.map(key => ({
227
+ name: key,
228
+ latex: key,
229
+ write: key,
230
+ label: key
231
+ }));
82
232
  }
83
-
84
- function getKeyPadWidth() {
85
- var additionalKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
86
- var equationEditor = arguments.length > 1 ? arguments[1] : undefined;
233
+ function getKeyPadWidth(additionalKeys = [], equationEditor) {
87
234
  return Math.floor(additionalKeys.length / 5) * 30 + (equationEditor === 'miscellaneous' ? 600 : 500);
88
235
  }
89
-
90
236
  function splitByParts(text) {
91
237
  // Use the regex pattern to split the text
92
- var parts = text.split(REGEX); // Filter out empty strings that might result from splitting
93
-
94
- return parts.filter(function (part) {
95
- return part;
96
- });
238
+ const parts = text.split(REGEX);
239
+ // Filter out empty strings that might result from splitting
240
+ return parts.filter(part => part);
97
241
  }
98
-
99
242
  function prepareForStatic(model, state) {
100
- var _ref = model || {},
101
- responses = _ref.responses,
102
- disabled = _ref.disabled,
103
- markup = _ref.markup,
104
- printMode = _ref.printMode,
105
- alwaysShowCorrect = _ref.alwaysShowCorrect;
106
-
243
+ const {
244
+ responses,
245
+ disabled,
246
+ markup,
247
+ printMode,
248
+ alwaysShowCorrect
249
+ } = model || {};
107
250
  if (markup) {
108
251
  if (state.showCorrect) {
109
- return Object.keys(responses || {}).reduce(function (acc, responseKey) {
110
- var _responses$responseKe;
111
-
112
- acc[responseKey] = responses === null || responses === void 0 ? void 0 : (_responses$responseKe = responses[responseKey]) === null || _responses$responseKe === void 0 ? void 0 : _responses$responseKe.answer;
252
+ return Object.keys(responses || {}).reduce((acc, responseKey) => {
253
+ acc[responseKey] = responses?.[responseKey]?.answer;
113
254
  return acc;
114
255
  }, {});
115
256
  }
116
-
117
- var splitted = splitByParts(markup);
118
- return splitted.reduce(function (acc, split) {
257
+ const splitted = splitByParts(markup);
258
+ return splitted.reduce((acc, split) => {
119
259
  if (split.match(REGEX)) {
120
- var responseKey = Main.getResponseKey(split);
121
- var answer = state.session.answers["r".concat(responseKey)];
122
-
260
+ const responseKey = Main.getResponseKey(split);
261
+ const answer = state.session.answers[`r${responseKey}`];
123
262
  if (printMode && !alwaysShowCorrect) {
124
- var blankSpace = '\\ \\ '.repeat(30) + '\\embed{newLine}[] ';
125
- return _objectSpread(_objectSpread({}, acc), {}, (0, _defineProperty2["default"])({}, responseKey, "\\MathQuillMathField[r".concat(responseKey, "]{").concat(blankSpace.repeat(3), "}")));
263
+ const blankSpace = '\\ \\ '.repeat(30) + '\\embed{newLine}[] ';
264
+ return {
265
+ ...acc,
266
+ [responseKey]: `\\MathQuillMathField[r${responseKey}]{${blankSpace.repeat(3)}}`
267
+ };
126
268
  }
127
-
128
269
  if (disabled) {
129
- return _objectSpread(_objectSpread({}, acc), {}, (0, _defineProperty2["default"])({}, responseKey, "\\embed{answerBlock}[r".concat(responseKey, "]")));
270
+ return {
271
+ ...acc,
272
+ [responseKey]: `\\embed{answerBlock}[r${responseKey}]`
273
+ };
130
274
  }
131
-
132
- return _objectSpread(_objectSpread({}, acc), {}, (0, _defineProperty2["default"])({}, responseKey, "\\MathQuillMathField[r".concat(responseKey, "]{").concat(answer && answer.value || '', "}")));
275
+ return {
276
+ ...acc,
277
+ [responseKey]: `\\MathQuillMathField[r${responseKey}]{${answer && answer.value || ''}}`
278
+ };
133
279
  }
134
-
135
280
  return acc;
136
281
  }, {});
137
282
  }
138
283
  }
139
-
140
- var Main = /*#__PURE__*/function (_React$Component) {
141
- (0, _inherits2["default"])(Main, _React$Component);
142
-
143
- var _super = _createSuper(Main);
144
-
145
- // removes {{ and }} and returns only key response. Eg: {{0}} => 0
146
- function Main(props) {
147
- var _this;
148
-
149
- (0, _classCallCheck2["default"])(this, Main);
150
- _this = _super.call(this, props);
151
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleAnswerBlockDomUpdate", function () {
152
- var _this$props = _this.props,
153
- model = _this$props.model,
154
- classes = _this$props.classes;
155
- var _this$state = _this.state,
156
- session = _this$state.session,
157
- showCorrect = _this$state.showCorrect;
158
- var answers = session.answers;
159
-
160
- if (_this.root && model.disabled && !showCorrect) {
161
- Object.keys(answers).forEach(function (answerId) {
162
- var el = _this.root.querySelector("#".concat(answerId));
163
-
164
- var indexEl = _this.root.querySelector("#".concat(answerId, "Index"));
165
-
284
+ class Main extends _react.default.Component {
285
+ constructor(props) {
286
+ super(props);
287
+ (0, _defineProperty2.default)(this, "handleAnswerBlockDomUpdate", () => {
288
+ const {
289
+ model
290
+ } = this.props;
291
+ const {
292
+ session,
293
+ showCorrect
294
+ } = this.state;
295
+ const answers = session.answers;
296
+ if (this.root && model.disabled && !showCorrect) {
297
+ Object.keys(answers).forEach(answerId => {
298
+ const el = this.root.querySelector(`#${answerId}`);
299
+ const indexEl = this.root.querySelector(`#${answerId}Index`);
166
300
  if (el) {
167
- var MQ = _mathquill["default"].getInterface(2);
168
-
169
- var answer = answers[answerId];
301
+ let MQ = _mathquill.default.getInterface(2);
302
+ const answer = answers[answerId];
170
303
  el.textContent = answer && answer.value || '';
171
-
172
304
  if (model.view) {
173
- el.parentElement.parentElement.classList.remove(classes.correct);
174
- el.parentElement.parentElement.classList.remove(classes.incorrect);
305
+ el.parentElement.parentElement.classList.remove('correct');
306
+ el.parentElement.parentElement.classList.remove('incorrect');
175
307
  }
176
-
177
308
  MQ.StaticMath(el);
178
309
  indexEl.textContent = 'R';
179
310
  }
180
311
  });
181
312
  }
182
-
183
- (0, _mathRendering.renderMath)(_this.root);
313
+ (0, _mathRendering.renderMath)(this.root);
184
314
  });
185
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onSubFieldFocus", function (id) {
186
- _this.setState({
315
+ (0, _defineProperty2.default)(this, "onSubFieldFocus", id => {
316
+ this.setState({
187
317
  activeAnswerBlock: id
188
318
  });
189
319
  });
190
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "toNodeData", function (data) {
320
+ (0, _defineProperty2.default)(this, "toNodeData", data => {
191
321
  if (!data) {
192
322
  return;
193
323
  }
194
-
195
- var type = data.type,
196
- value = data.value;
324
+ const {
325
+ type,
326
+ value
327
+ } = data;
197
328
  if (type === 'command' || type === 'cursor') return data;
198
- if (type === 'answer') return _objectSpread({
199
- type: 'answer'
200
- }, data);
329
+ if (type === 'answer') return {
330
+ type: 'answer',
331
+ ...data
332
+ };
201
333
  if (value === 'clear') return {
202
334
  type: 'clear'
203
335
  };
204
336
  return {
205
337
  type: 'write',
206
- value: value
338
+ value
207
339
  };
208
340
  });
209
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "setInput", function (input) {
210
- _this.input = input;
341
+ (0, _defineProperty2.default)(this, "setInput", input => {
342
+ this.input = input;
211
343
  });
212
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onClick", function (data) {
213
- var c = _this.toNodeData(data);
214
-
344
+ (0, _defineProperty2.default)(this, "onClick", data => {
345
+ const c = this.toNodeData(data);
215
346
  if (c.type === 'clear') {
216
- _this.input.clear();
347
+ this.input.clear();
217
348
  } else if (c.type === 'command') {
218
349
  if (Array.isArray(c.value)) {
219
- c.value.forEach(function (vv) {
220
- _this.input.cmd(vv);
350
+ c.value.forEach(vv => {
351
+ this.input.cmd(vv);
221
352
  });
222
353
  } else {
223
- _this.input.cmd(c.value);
354
+ this.input.cmd(c.value);
224
355
  }
225
356
  } else if (c.type === 'cursor') {
226
- _this.input.keystroke(c.value);
357
+ this.input.keystroke(c.value);
227
358
  } else {
228
- _this.input.write(c.value);
359
+ this.input.write(c.value);
229
360
  }
230
-
231
- _this.input.focus();
361
+ this.input.focus();
232
362
  });
233
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "callOnSessionChange", function () {
234
- var onSessionChange = _this.props.onSessionChange;
235
-
363
+ (0, _defineProperty2.default)(this, "callOnSessionChange", () => {
364
+ const {
365
+ onSessionChange
366
+ } = this.props;
236
367
  if (onSessionChange) {
237
- onSessionChange(_this.state.session);
368
+ onSessionChange(this.state.session);
238
369
  }
239
370
  });
240
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "toggleShowCorrect", function (show) {
241
- _this.setState({
371
+ (0, _defineProperty2.default)(this, "toggleShowCorrect", show => {
372
+ this.setState({
242
373
  showCorrect: show
243
- }, _this.handleAnswerBlockDomUpdate);
374
+ }, this.handleAnswerBlockDomUpdate);
244
375
  });
245
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "subFieldChanged", function (name, subfieldValue) {
376
+ (0, _defineProperty2.default)(this, "subFieldChanged", (name, subfieldValue) => {
246
377
  (0, _mathInput.updateSpans)();
247
-
248
378
  if (name) {
249
- _this.setState(function (state) {
250
- return {
251
- session: _objectSpread(_objectSpread({}, state.session), {}, {
252
- answers: _objectSpread(_objectSpread({}, state.session.answers), {}, (0, _defineProperty2["default"])({}, name, {
379
+ this.setState(state => ({
380
+ session: {
381
+ ...state.session,
382
+ answers: {
383
+ ...state.session.answers,
384
+ [name]: {
253
385
  value: subfieldValue
254
- }))
255
- })
256
- };
257
- }, _this.callOnSessionChange);
386
+ }
387
+ }
388
+ }
389
+ }), this.callOnSessionChange);
258
390
  }
259
391
  });
260
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getFieldName", function (changeField, fields) {
261
- var answers = _this.state.session.answers;
262
-
392
+ (0, _defineProperty2.default)(this, "getFieldName", (changeField, fields) => {
393
+ const {
394
+ answers
395
+ } = this.state.session;
263
396
  if (Object.keys(answers || {}).length) {
264
- var keys = Object.keys(answers);
265
- return keys.find(function (k) {
266
- var tf = fields[k];
397
+ const keys = Object.keys(answers);
398
+ return keys.find(k => {
399
+ const tf = fields[k];
267
400
  return tf && tf.id == changeField.id;
268
401
  });
269
402
  }
270
403
  });
271
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onBlur", function (e) {
272
- var _ref2 = e || {},
273
- relatedTarget = _ref2.relatedTarget,
274
- currentTarget = _ref2.currentTarget;
275
-
276
- function getParentWithRoleTooltip(element) {
277
- var depth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
404
+ (0, _defineProperty2.default)(this, "onBlur", e => {
405
+ const {
406
+ relatedTarget,
407
+ currentTarget
408
+ } = e || {};
409
+ function getParentWithRoleTooltip(element, depth = 0) {
278
410
  // only run this max 16 times
279
411
  if (!element || depth >= 16) return null;
280
- var parent = element.offsetParent;
412
+ const parent = element.offsetParent;
281
413
  if (!parent) return null;
282
-
283
414
  if (parent.getAttribute('role') === 'tooltip') {
284
415
  return parent;
285
416
  }
286
-
287
417
  return getParentWithRoleTooltip(parent, depth + 1);
288
418
  }
289
-
290
- function getDeepChildDataKeypad(element) {
291
- var _element$children;
292
-
293
- var depth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
419
+ function getDeepChildDataKeypad(element, depth = 0) {
294
420
  // only run this max 4 times
295
421
  if (!element || depth >= 4) return null;
296
- var child = element === null || element === void 0 ? void 0 : (_element$children = element.children) === null || _element$children === void 0 ? void 0 : _element$children[0];
422
+ const child = element?.children?.[0];
297
423
  if (!child) return null;
298
-
299
424
  if (child.attributes && child.attributes['data-keypad']) {
300
425
  return child;
301
426
  }
302
-
303
427
  return getDeepChildDataKeypad(child, depth + 1);
304
428
  }
305
-
306
- var parentWithTooltipRole = getParentWithRoleTooltip(relatedTarget);
307
- var childWithDataKeypad = parentWithTooltipRole ? getDeepChildDataKeypad(parentWithTooltipRole) : null;
308
-
309
- if (!relatedTarget || !currentTarget || !(childWithDataKeypad !== null && childWithDataKeypad !== void 0 && childWithDataKeypad.attributes['data-keypad'])) {
310
- _this.setState({
429
+ const parentWithTooltipRole = getParentWithRoleTooltip(relatedTarget);
430
+ const childWithDataKeypad = parentWithTooltipRole ? getDeepChildDataKeypad(parentWithTooltipRole) : null;
431
+ if (!relatedTarget || !currentTarget || !childWithDataKeypad?.attributes['data-keypad']) {
432
+ this.setState({
311
433
  activeAnswerBlock: ''
312
434
  });
313
435
  }
314
436
  });
315
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "renderTeacherInstructions", function () {
316
- var _this$props2 = _this.props,
317
- model = _this$props2.model,
318
- classes = _this$props2.classes;
319
-
320
- var _ref3 = model || {},
321
- teacherInstructions = _ref3.teacherInstructions,
322
- animationsDisabled = _ref3.animationsDisabled;
323
-
324
- var showTeacherInstructions = teacherInstructions && ((0, _renderUi.hasText)(teacherInstructions) || (0, _renderUi.hasMedia)(teacherInstructions));
325
-
326
- var teacherInstructionsDiv = /*#__PURE__*/_react["default"].createElement(_renderUi.PreviewPrompt, {
437
+ (0, _defineProperty2.default)(this, "renderTeacherInstructions", () => {
438
+ const {
439
+ model
440
+ } = this.props;
441
+ const {
442
+ teacherInstructions,
443
+ animationsDisabled
444
+ } = model || {};
445
+ const showTeacherInstructions = teacherInstructions && ((0, _renderUi.hasText)(teacherInstructions) || (0, _renderUi.hasMedia)(teacherInstructions));
446
+ const teacherInstructionsDiv = /*#__PURE__*/_react.default.createElement(_renderUi.PreviewPrompt, {
327
447
  defaultClassName: "teacher-instructions",
328
448
  prompt: teacherInstructions
329
449
  });
330
-
331
- return showTeacherInstructions && /*#__PURE__*/_react["default"].createElement("div", {
332
- className: classes.collapsible
333
- }, !animationsDisabled ? /*#__PURE__*/_react["default"].createElement(_renderUi.Collapsible, {
450
+ return showTeacherInstructions && /*#__PURE__*/_react.default.createElement(CollapsibleContainer, null, !animationsDisabled ? /*#__PURE__*/_react.default.createElement(_renderUi.Collapsible, {
334
451
  labels: {
335
452
  hidden: 'Show Teacher Instructions',
336
453
  visible: 'Hide Teacher Instructions'
337
454
  }
338
455
  }, teacherInstructionsDiv) : teacherInstructionsDiv);
339
456
  });
340
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "renderRationale", function () {
341
- var _this$props3 = _this.props,
342
- model = _this$props3.model,
343
- classes = _this$props3.classes;
344
-
345
- var _ref4 = model || {},
346
- rationale = _ref4.rationale,
347
- animationsDisabled = _ref4.animationsDisabled;
348
-
349
- var rationaleDiv = /*#__PURE__*/_react["default"].createElement(_renderUi.PreviewPrompt, {
457
+ (0, _defineProperty2.default)(this, "renderRationale", () => {
458
+ const {
459
+ model
460
+ } = this.props;
461
+ const {
462
+ rationale,
463
+ animationsDisabled
464
+ } = model || {};
465
+ const rationaleDiv = /*#__PURE__*/_react.default.createElement(_renderUi.PreviewPrompt, {
350
466
  prompt: rationale
351
467
  });
352
-
353
- var showRationale = rationale && ((0, _renderUi.hasText)(rationale) || (0, _renderUi.hasMedia)(rationale));
354
- return showRationale && /*#__PURE__*/_react["default"].createElement("div", {
355
- className: classes.collapsible
356
- }, !animationsDisabled ? /*#__PURE__*/_react["default"].createElement(_renderUi.Collapsible, {
468
+ const showRationale = rationale && ((0, _renderUi.hasText)(rationale) || (0, _renderUi.hasMedia)(rationale));
469
+ return showRationale && /*#__PURE__*/_react.default.createElement(CollapsibleContainer, null, !animationsDisabled ? /*#__PURE__*/_react.default.createElement(_renderUi.Collapsible, {
357
470
  labels: {
358
471
  hidden: 'Show Rationale',
359
472
  visible: 'Hide Rationale'
360
473
  }
361
474
  }, rationaleDiv) : rationaleDiv);
362
475
  });
363
- (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "renderPlayerContent", function () {
364
- var _this$props4 = _this.props,
365
- model = _this$props4.model,
366
- classes = _this$props4.classes;
367
- var _this$state2 = _this.state,
368
- activeAnswerBlock = _this$state2.activeAnswerBlock,
369
- showCorrect = _this$state2.showCorrect,
370
- session = _this$state2.session;
371
-
372
- var _ref5 = model || {},
373
- correctness = _ref5.correctness,
374
- disabled = _ref5.disabled,
375
- view = _ref5.view,
376
- responses = _ref5.responses,
377
- equationEditor = _ref5.equationEditor,
378
- customKeys = _ref5.customKeys,
379
- feedback = _ref5.feedback,
380
- _ref5$env = _ref5.env;
381
-
382
- _ref5$env = _ref5$env === void 0 ? {} : _ref5$env;
383
- var mode = _ref5$env.mode,
384
- printMode = _ref5.printMode,
385
- alwaysShowCorrect = _ref5.alwaysShowCorrect;
386
- var emptyResponse = (0, _isEmpty["default"])(responses);
387
- var additionalKeys = generateAdditionalKeys(customKeys);
388
- var statics = prepareForStatic(model, _this.state) || '';
389
- var studentPrintMode = printMode && !alwaysShowCorrect;
390
- return /*#__PURE__*/_react["default"].createElement("div", {
391
- className: classes.inputAndKeypadContainer
392
- }, /*#__PURE__*/_react["default"].createElement(_maskMarkup.Customizable, {
476
+ (0, _defineProperty2.default)(this, "renderPlayerContent", () => {
477
+ const {
478
+ model
479
+ } = this.props;
480
+ const {
481
+ activeAnswerBlock,
482
+ showCorrect,
483
+ session,
484
+ tooltipContainerRef
485
+ } = this.state;
486
+ const {
487
+ correctness,
488
+ disabled,
489
+ view,
490
+ responses,
491
+ equationEditor,
492
+ customKeys,
493
+ feedback,
494
+ env: {
495
+ mode
496
+ } = {},
497
+ printMode,
498
+ alwaysShowCorrect
499
+ } = model || {};
500
+ const emptyResponse = (0, _isEmpty.default)(responses);
501
+ const additionalKeys = generateAdditionalKeys(customKeys);
502
+ const statics = prepareForStatic(model, this.state) || '';
503
+ const studentPrintMode = printMode && !alwaysShowCorrect;
504
+ return /*#__PURE__*/_react.default.createElement(InputAndKeypadContainer, null, /*#__PURE__*/_react.default.createElement(_maskMarkup.Customizable, {
393
505
  disabled: disabled,
394
- markup: model.markup // TODO remove the need of value?
506
+ markup: model.markup
507
+ // TODO remove the need of value?
395
508
  ,
396
509
  value: {},
397
- customMarkMarkupComponent: function customMarkMarkupComponent(id) {
398
- var _cx;
399
-
400
- var responseIsCorrect = mode === 'evaluate' && feedback && feedback[id];
401
-
402
- var MQStatic = /*#__PURE__*/_react["default"].createElement(_mathInput.mq.Static, {
403
- className: classes["static"],
404
- ref: function ref(mqStatic) {
405
- _this.mqStatic = mqStatic || _this.mqStatic;
510
+ customMarkMarkupComponent: id => {
511
+ const responseIsCorrect = mode === 'evaluate' && feedback && feedback[id];
512
+ const MQStatic = /*#__PURE__*/_react.default.createElement(StyledStatic, {
513
+ ref: mqStatic => {
514
+ this.mqStatic = mqStatic || this.mqStatic;
406
515
  },
407
516
  latex: statics[id],
408
- onSubFieldChange: _this.subFieldChanged,
409
- getFieldName: _this.getFieldName,
410
- setInput: _this.setInput,
411
- onSubFieldFocus: _this.onSubFieldFocus,
412
- onBlur: _this.onBlur
517
+ onSubFieldChange: this.subFieldChanged,
518
+ getFieldName: this.getFieldName,
519
+ setInput: this.setInput,
520
+ onSubFieldFocus: this.onSubFieldFocus,
521
+ onBlur: this.onBlur
413
522
  });
414
-
415
- return /*#__PURE__*/_react["default"].createElement("div", {
416
- className: (0, _classnames["default"])(classes.expression, (_cx = {}, (0, _defineProperty2["default"])(_cx, classes.incorrect, !emptyResponse && !responseIsCorrect && !showCorrect), (0, _defineProperty2["default"])(_cx, classes.correct, !emptyResponse && (responseIsCorrect || showCorrect)), (0, _defineProperty2["default"])(_cx, classes.showCorrectness, !emptyResponse && disabled && correctness && !view), (0, _defineProperty2["default"])(_cx, classes.correctAnswerShown, showCorrect), _cx))
417
- }, /*#__PURE__*/_react["default"].createElement(_Tooltip["default"], {
418
- ref: function ref(_ref6) {
419
- return _this.setTooltipRef(_ref6);
420
- },
523
+ return /*#__PURE__*/_react.default.createElement(Expression, {
524
+ ref: tooltipContainerRef,
525
+ $incorrect: !emptyResponse && !responseIsCorrect && !showCorrect,
526
+ $correct: !emptyResponse && (responseIsCorrect || showCorrect),
527
+ $showCorrectness: !emptyResponse && disabled && correctness && !view,
528
+ $correctAnswerShown: showCorrect
529
+ }, /*#__PURE__*/_react.default.createElement(_Tooltip.default, {
530
+ ref: ref => this.setTooltipRef(ref),
421
531
  enterTouchDelay: 0,
422
532
  interactive: true,
423
- open: activeAnswerBlock === "r".concat(id),
424
- classes: {
425
- tooltip: classes.keypadTooltip,
426
- popper: classes.keypadTooltipPopper
427
- },
428
- title: Object.keys(session.answers).map(function (answerId) {
429
- return answerId === activeAnswerBlock && !(showCorrect || disabled) && /*#__PURE__*/_react["default"].createElement("div", {
430
- "data-keypad": true,
431
- key: answerId,
432
- className: classes.responseContainer,
433
- style: {
434
- width: getKeyPadWidth(additionalKeys, equationEditor)
533
+ open: activeAnswerBlock === `r${id}`,
534
+ slotProps: {
535
+ popper: {
536
+ container: tooltipContainerRef?.current || undefined,
537
+ placement: 'bottom-end',
538
+ sx: {
539
+ backgroundColor: 'transparent',
540
+ width: '650px',
541
+ opacity: 1,
542
+ '& .MuiTooltip-arrow': {
543
+ display: 'none'
544
+ }
545
+ },
546
+ modifiers: {
547
+ preventOverflow: {
548
+ enabled: true,
549
+ boundariesElement: 'body'
550
+ },
551
+ flip: {
552
+ enabled: false
553
+ }
435
554
  }
436
- }, /*#__PURE__*/_react["default"].createElement(_mathInput.HorizontalKeypad, {
437
- additionalKeys: additionalKeys,
438
- mode: equationEditor || DEFAULT_KEYPAD_VARIANT,
439
- onClick: _this.onClick
440
- })) || null;
441
- })
442
- }, studentPrintMode ? /*#__PURE__*/_react["default"].createElement("div", {
443
- className: classes.printContainer
444
- }, MQStatic) : MQStatic));
555
+ },
556
+ tooltip: {
557
+ sx: {
558
+ fontSize: 'initial',
559
+ backgroundColor: 'transparent',
560
+ width: '600px',
561
+ marginTop: 0,
562
+ paddingTop: 0,
563
+ boxShadow: 'none'
564
+ }
565
+ }
566
+ },
567
+ title: Object.keys(session.answers).map(answerId => answerId === activeAnswerBlock && !(showCorrect || disabled) && /*#__PURE__*/_react.default.createElement(ResponseContainer, {
568
+ "data-keypad": true,
569
+ key: answerId,
570
+ style: {
571
+ width: getKeyPadWidth(additionalKeys, equationEditor)
572
+ }
573
+ }, /*#__PURE__*/_react.default.createElement(_mathInput.HorizontalKeypad, {
574
+ additionalKeys: additionalKeys,
575
+ mode: equationEditor || DEFAULT_KEYPAD_VARIANT,
576
+ onClick: this.onClick
577
+ })) || null)
578
+ }, studentPrintMode ? /*#__PURE__*/_react.default.createElement(PrintContainer, null, MQStatic) : /*#__PURE__*/_react.default.createElement("div", null, MQStatic)));
445
579
  }
446
580
  }));
447
581
  });
448
- var _answers = {};
449
-
450
- var _ref7 = props || {},
451
- _model = _ref7.model,
452
- _session = _ref7.session;
453
-
454
- var _ref8 = _model || {},
455
- markup = _ref8.markup,
456
- _alwaysShowCorrect = _ref8.alwaysShowCorrect;
457
-
458
- var _ref9 = _session || {},
459
- sessionAnswers = _ref9.answers;
460
-
582
+ const _answers = {};
583
+ const {
584
+ model: _model,
585
+ session: _session
586
+ } = props || {};
587
+ const {
588
+ markup,
589
+ alwaysShowCorrect: _alwaysShowCorrect
590
+ } = _model || {};
591
+ const {
592
+ answers: sessionAnswers
593
+ } = _session || {};
461
594
  if (markup) {
462
595
  // build out local state model using responses declared in markup
463
- (markup || '').replace(REGEX, function (response) {
464
- var responseKey = Main.getResponseKey(response);
465
- var sessionAnswerForResponse = sessionAnswers && sessionAnswers["r".concat(responseKey)];
466
- _answers["r".concat(responseKey)] = {
467
- value: (sessionAnswerForResponse === null || sessionAnswerForResponse === void 0 ? void 0 : sessionAnswerForResponse.value) || ''
596
+ (markup || '').replace(REGEX, response => {
597
+ const responseKey = Main.getResponseKey(response);
598
+ const sessionAnswerForResponse = sessionAnswers && sessionAnswers[`r${responseKey}`];
599
+ _answers[`r${responseKey}`] = {
600
+ value: sessionAnswerForResponse?.value || ''
468
601
  };
469
602
  });
470
603
  }
471
-
472
- _this.state = {
473
- session: _objectSpread(_objectSpread({}, props.session), {}, {
604
+ this.state = {
605
+ session: {
606
+ ...props.session,
474
607
  answers: _answers
475
- }),
608
+ },
476
609
  activeAnswerBlock: '',
477
- showCorrect: _alwaysShowCorrect || false
610
+ showCorrect: _alwaysShowCorrect || false,
611
+ tooltipContainerRef: /*#__PURE__*/_react.default.createRef()
478
612
  };
479
- return _this;
480
613
  }
481
-
482
- (0, _createClass2["default"])(Main, [{
483
- key: "UNSAFE_componentWillMount",
484
- value: function UNSAFE_componentWillMount() {
485
- var classes = this.props.classes;
486
-
487
- if (typeof window !== 'undefined') {
488
- var MQ = _mathquill["default"].getInterface(2);
489
-
490
- if (!registered) {
491
- MQ.registerEmbed('answerBlock', function (data) {
492
- return {
493
- htmlString: "<div class=\"".concat(classes.blockContainer, "\">\n <div class=\"").concat(classes.blockResponse, "\" id=\"").concat(data, "Index\">R</div>\n <div class=\"").concat(classes.blockMath, "\">\n <span id=\"").concat(data, "\"></span>\n </div>\n </div>"),
494
- text: function text() {
495
- return 'text';
496
- },
497
- latex: function latex() {
498
- return "\\embed{answerBlock}[".concat(data, "]");
499
- }
500
- };
501
- });
502
- registered = true;
503
- }
504
- }
505
- }
506
- }, {
507
- key: "UNSAFE_componentWillReceiveProps",
508
- value: function UNSAFE_componentWillReceiveProps(nextProps) {
509
- var _this2 = this;
510
-
511
- var model = this.props.model;
512
-
513
- var _ref10 = nextProps || {},
514
- _ref10$model = _ref10.model,
515
- nextModel = _ref10$model === void 0 ? {} : _ref10$model;
516
-
517
- var _ref11 = model || {},
518
- _ref11$markup = _ref11.markup,
519
- markup = _ref11$markup === void 0 ? '' : _ref11$markup,
520
- _ref11$env = _ref11.env,
521
- env = _ref11$env === void 0 ? {} : _ref11$env;
522
-
523
- var _nextModel$markup = nextModel.markup,
524
- nextMarkup = _nextModel$markup === void 0 ? '' : _nextModel$markup,
525
- _nextModel$env = nextModel.env,
526
- nextEnv = _nextModel$env === void 0 ? {} : _nextModel$env,
527
- _nextModel$alwaysShow = nextModel.alwaysShowCorrect,
528
- nextAlwaysShowCorrect = _nextModel$alwaysShow === void 0 ? false : _nextModel$alwaysShow;
529
-
530
- var isEvaluateMode = function isEvaluateMode(env) {
531
- return env && env.mode === 'evaluate';
532
- };
533
-
534
- if (!isEvaluateMode(env) || !isEvaluateMode(nextEnv)) {
535
- this.setState(function (prevState) {
536
- return _objectSpread(_objectSpread({}, prevState.session), {}, {
537
- showCorrect: false
538
- });
539
- });
614
+ UNSAFE_componentWillMount() {
615
+ if (typeof window !== 'undefined') {
616
+ let MQ = _mathquill.default.getInterface(2);
617
+ if (!registered) {
618
+ MQ.registerEmbed('answerBlock', data => ({
619
+ htmlString: `<div class="block-container">
620
+ <div class="block-response" id="${data}Index">R</div>
621
+ <div class="block-math">
622
+ <span id="${data}"></span>
623
+ </div>
624
+ </div>`,
625
+ text: () => 'text',
626
+ latex: () => `\\embed{answerBlock}[${data}]`
627
+ }));
628
+ registered = true;
540
629
  }
541
-
542
- if (nextAlwaysShowCorrect) {
543
- this.setState({
544
- showCorrect: true
545
- });
546
- }
547
-
548
- var matches = markup.match(REGEX);
549
- var nextMatches = nextMarkup.match(REGEX); // If markup changed, and we no longer have the same response area, the session needs to be updated
550
-
551
- if (!(0, _isEqual["default"])(matches, nextMatches)) {
552
- var newAnswers = {};
553
- var answers = this.state.session.answers;
554
- (nextMatches || []).forEach(function (nextMatch) {
555
- var responseKey = Main.getResponseKey(nextMatch);
556
- var sessionAnswerForResponse = answers && answers["r".concat(responseKey)]; // build out local state model using responses declared in markup
557
-
558
- newAnswers["r".concat(responseKey)] = {
559
- value: (sessionAnswerForResponse === null || sessionAnswerForResponse === void 0 ? void 0 : sessionAnswerForResponse.value) || ''
560
- };
561
- });
562
- this.setState(function (state) {
563
- return {
564
- session: _objectSpread(_objectSpread({}, state.session), {}, {
565
- answers: newAnswers
566
- })
567
- };
568
- }, function () {
569
- _this2.props.onSessionChange(_this2.state.session);
570
-
571
- _this2.handleAnswerBlockDomUpdate();
572
- });
573
- }
574
- }
575
- }, {
576
- key: "shouldComponentUpdate",
577
- value: function shouldComponentUpdate(nextProps, nextState) {
578
- var sameModel = (0, _isEqual["default"])(this.props.model, nextProps.model);
579
- var sameState = (0, _isEqual["default"])(this.state, nextState);
580
- return !sameModel || !sameState;
581
630
  }
582
- }, {
583
- key: "componentDidMount",
584
- value: function componentDidMount() {
585
- var _this3 = this;
586
-
587
- this.handleAnswerBlockDomUpdate();
588
- setTimeout(function () {
589
- return (0, _mathRendering.renderMath)(_this3.root);
590
- }, 100);
591
- }
592
- }, {
593
- key: "componentDidUpdate",
594
- value: function componentDidUpdate() {
595
- this.handleAnswerBlockDomUpdate();
631
+ }
632
+ UNSAFE_componentWillReceiveProps(nextProps) {
633
+ const {
634
+ model
635
+ } = this.props;
636
+ const {
637
+ model: nextModel = {}
638
+ } = nextProps || {};
639
+ const {
640
+ markup = '',
641
+ env = {}
642
+ } = model || {};
643
+ const {
644
+ markup: nextMarkup = '',
645
+ env: nextEnv = {},
646
+ alwaysShowCorrect: nextAlwaysShowCorrect = false
647
+ } = nextModel;
648
+ const isEvaluateMode = env => env && env.mode === 'evaluate';
649
+ if (!isEvaluateMode(env) || !isEvaluateMode(nextEnv)) {
650
+ this.setState(prevState => ({
651
+ ...prevState.session,
652
+ showCorrect: false
653
+ }));
596
654
  }
597
- }, {
598
- key: "setTooltipRef",
599
- value: // function for tooltip
600
- function setTooltipRef(ref) {
601
- // Safari Hack: https://stackoverflow.com/a/42764495/5757635
602
- setTimeout(function () {
603
- if (ref && IS_SAFARI) {
604
- var div = document.querySelector("[role='tooltip']");
605
-
606
- if (div) {
607
- var el = div.firstChild;
608
- el.setAttribute('tabindex', '-1');
609
- }
610
- }
611
- }, 1);
655
+ if (nextAlwaysShowCorrect) {
656
+ this.setState({
657
+ showCorrect: true
658
+ });
612
659
  }
613
- }, {
614
- key: "render",
615
- value: function render() {
616
- var _this4 = this;
617
-
618
- var _this$props5 = this.props,
619
- model = _this$props5.model,
620
- classes = _this$props5.classes;
621
- var showCorrect = this.state.showCorrect;
622
-
623
- var _ref12 = model || {},
624
- prompt = _ref12.prompt,
625
- _ref12$env = _ref12.env;
626
-
627
- _ref12$env = _ref12$env === void 0 ? {} : _ref12$env;
628
- var mode = _ref12$env.mode,
629
- role = _ref12$env.role,
630
- extraCSSRules = _ref12.extraCSSRules,
631
- correctness = _ref12.correctness,
632
- responses = _ref12.responses,
633
- language = _ref12.language,
634
- showNote = _ref12.showNote,
635
- note = _ref12.note;
636
- var emptyResponse = (0, _isEmpty["default"])(responses);
637
- var showCorrectAnswerToggle = !emptyResponse && correctness && correctness.correctness !== 'correct';
638
- var displayNote = (showCorrect || mode === 'view' && role === 'instructor') && showNote && note;
639
- return /*#__PURE__*/_react["default"].createElement(_renderUi.UiLayout, {
640
- extraCSSRules: extraCSSRules,
641
- className: classes.mainContainer,
642
- ref: function ref(r) {
643
- // eslint-disable-next-line react/no-find-dom-node
644
- var domNode = _reactDom["default"].findDOMNode(r);
645
-
646
- _this4.root = domNode || _this4.root;
647
- }
648
- }, /*#__PURE__*/_react["default"].createElement("div", {
649
- className: classes.main
650
- }, mode === 'gather' && /*#__PURE__*/_react["default"].createElement("h2", {
651
- className: classes.srOnly
652
- }, "Math Equation Response Question"), /*#__PURE__*/_react["default"].createElement("div", {
653
- className: classes.main
654
- }, showCorrectAnswerToggle && /*#__PURE__*/_react["default"].createElement(_correctAnswerToggle["default"], {
655
- language: language,
656
- className: classes.toggle,
657
- show: true,
658
- toggled: showCorrect,
659
- onToggle: this.toggleShowCorrect
660
- })), this.renderTeacherInstructions(), prompt && /*#__PURE__*/_react["default"].createElement("div", {
661
- className: classes.promptContainer
662
- }, /*#__PURE__*/_react["default"].createElement(_renderUi.PreviewPrompt, {
663
- prompt: prompt
664
- })), /*#__PURE__*/_react["default"].createElement(_renderUi.Readable, {
665
- "false": true
666
- }, this.renderPlayerContent()), displayNote && /*#__PURE__*/_react["default"].createElement("div", {
667
- className: (0, _classnames["default"])(classes.note, 'note'),
668
- dangerouslySetInnerHTML: {
669
- __html: note
660
+ const matches = markup.match(REGEX);
661
+ const nextMatches = nextMarkup.match(REGEX);
662
+
663
+ // If markup changed, and we no longer have the same response area, the session needs to be updated
664
+ if (!(0, _isEqual.default)(matches, nextMatches)) {
665
+ const newAnswers = {};
666
+ const answers = this.state.session.answers;
667
+ (nextMatches || []).forEach(nextMatch => {
668
+ const responseKey = Main.getResponseKey(nextMatch);
669
+ const sessionAnswerForResponse = answers && answers[`r${responseKey}`];
670
+
671
+ // build out local state model using responses declared in markup
672
+ newAnswers[`r${responseKey}`] = {
673
+ value: sessionAnswerForResponse?.value || ''
674
+ };
675
+ });
676
+ this.setState(state => ({
677
+ session: {
678
+ ...state.session,
679
+ answers: newAnswers
670
680
  }
671
- }), this.renderRationale()));
681
+ }), () => {
682
+ this.props.onSessionChange(this.state.session);
683
+ this.handleAnswerBlockDomUpdate();
684
+ });
672
685
  }
673
- }]);
674
- return Main;
675
- }(_react["default"].Component);
676
-
677
- exports.Main = Main;
678
- (0, _defineProperty2["default"])(Main, "getResponseKey", function (response) {
679
- return (response || '').replaceAll('{{', '').replaceAll('}}', '');
680
- });
681
- (0, _defineProperty2["default"])(Main, "propTypes", {
682
- classes: _propTypes["default"].object,
683
- session: _propTypes["default"].object.isRequired,
684
- onSessionChange: _propTypes["default"].func,
685
- model: _propTypes["default"].object.isRequired
686
- });
687
-
688
- var styles = function styles(theme) {
689
- return {
690
- mainContainer: {
691
- color: _renderUi.color.text(),
692
- backgroundColor: _renderUi.color.background(),
693
- display: 'inline-block'
694
- },
695
- tooltip: {
696
- background: "".concat(_renderUi.color.primaryLight(), " !important"),
697
- color: _renderUi.color.text(),
698
- padding: theme.spacing.unit * 2,
699
- border: "1px solid ".concat(_renderUi.color.secondary()),
700
- fontSize: '16px',
701
- '& :not(.MathJax) > table tr': {
702
- '&:nth-child(2n)': {
703
- backgroundColor: 'unset !important'
704
- }
705
- }
706
- },
707
- tooltipPopper: {
708
- opacity: 1
709
- },
710
- keypadTooltip: {
711
- fontSize: 'initial',
712
- background: 'transparent',
713
- width: '600px',
714
- marginTop: 0,
715
- paddingTop: 0
716
- },
717
- keypadTooltipPopper: {
718
- background: 'transparent',
719
- width: '650px',
720
- opacity: 1
721
- },
722
- promptContainer: {
723
- marginBottom: theme.spacing.unit * 2
724
- },
725
- main: {
726
- width: '100%',
727
- position: 'relative',
728
- backgroundColor: _renderUi.color.background(),
729
- color: _renderUi.color.text()
730
- },
731
- title: {
732
- fontSize: '1.1rem',
733
- display: 'block',
734
- marginTop: theme.spacing.unit * 2,
735
- marginBottom: theme.spacing.unit
736
- },
737
- collapsible: {
738
- marginBottom: theme.spacing.unit * 2
739
- },
740
- responseContainer: {
741
- zIndex: 10,
742
- minWidth: '400px',
743
- marginTop: theme.spacing.unit * 2
744
- },
745
- expression: {
746
- maxWidth: 'fit-content',
747
- '& > .mq-math-mode': {
748
- '& > .mq-root-block': {
749
- '& > .mq-editable-field': {
750
- minWidth: '10px',
751
- padding: theme.spacing.unit / 4
752
- }
753
- },
754
- '& sup': {
755
- top: 0
756
- }
757
- }
758
- },
759
- "static": {
760
- '& > .mq-root-block': {
761
- '& > .mq-editable-field': {
762
- borderColor: _renderUi.color.text()
686
+ }
687
+ shouldComponentUpdate(nextProps, nextState) {
688
+ const sameModel = (0, _isEqual.default)(this.props.model, nextProps.model);
689
+ const sameState = (0, _isEqual.default)(this.state, nextState);
690
+ return !sameModel || !sameState;
691
+ }
692
+ componentDidMount() {
693
+ this.handleAnswerBlockDomUpdate();
694
+ setTimeout(() => (0, _mathRendering.renderMath)(this.root), 100);
695
+ }
696
+ componentDidUpdate() {
697
+ this.handleAnswerBlockDomUpdate();
698
+ }
699
+ // function for tooltip
700
+ setTooltipRef(ref) {
701
+ // Safari Hack: https://stackoverflow.com/a/42764495/5757635
702
+ setTimeout(() => {
703
+ if (ref && IS_SAFARI) {
704
+ const div = document.querySelector("[role='tooltip']");
705
+ if (div) {
706
+ const el = div.firstChild;
707
+ el.setAttribute('tabindex', '-1');
763
708
  }
764
709
  }
765
- },
766
- inputAndKeypadContainer: {
767
- position: 'relative',
768
- '& > div > div': {
769
- display: 'flex',
770
- alignItems: 'baseline',
771
- flexWrap: 'wrap'
772
- },
773
- '& .mq-overarrow-inner': {
774
- border: 'none !important',
775
- padding: '0 !important'
776
- },
777
- '& .mq-overarrow-inner-right': {
778
- display: 'none !important'
779
- },
780
- '& .mq-overarrow-inner-left': {
781
- display: 'none !important'
782
- },
783
- '& .mq-overarrow.mq-arrow-both': {
784
- minWidth: '1.23em',
785
- '& *': {
786
- lineHeight: '1 !important'
787
- },
788
- '&:before': {
789
- top: '-0.4em',
790
- left: '-1px'
791
- },
792
- '&:after': {
793
- top: '-2.4em',
794
- right: '-1px'
795
- },
796
- '&.mq-empty:after': {
797
- top: '-0.45em'
798
- }
799
- },
800
- '& .mq-overarrow.mq-arrow-right': {
801
- '&:before': {
802
- top: '-0.4em',
803
- right: '-1px'
804
- }
805
- },
806
- '& .mq-longdiv-inner': {
807
- borderTop: '1px solid !important',
808
- paddingTop: '1.5px !important'
809
- },
810
- '& .mq-parallelogram': {
811
- lineHeight: 0.85
710
+ }, 1);
711
+ }
712
+ render() {
713
+ const {
714
+ model
715
+ } = this.props;
716
+ const {
717
+ showCorrect
718
+ } = this.state;
719
+ const {
720
+ prompt,
721
+ env: {
722
+ mode,
723
+ role
724
+ } = {},
725
+ extraCSSRules,
726
+ correctness,
727
+ responses,
728
+ language,
729
+ showNote,
730
+ note
731
+ } = model || {};
732
+ const emptyResponse = (0, _isEmpty.default)(responses);
733
+ const showCorrectAnswerToggle = !emptyResponse && correctness && correctness.correctness !== 'correct';
734
+ const displayNote = (showCorrect || mode === 'view' && role === 'instructor') && showNote && note;
735
+ return /*#__PURE__*/_react.default.createElement(StyledUiLayout, {
736
+ extraCSSRules: extraCSSRules,
737
+ ref: r => {
738
+ // eslint-disable-next-line react/no-find-dom-node
739
+ const domNode = _reactDom.default.findDOMNode(r);
740
+ this.root = domNode || this.root;
812
741
  }
813
- },
814
- showCorrectness: {
815
- border: '2px solid'
816
- },
817
- correctAnswerShown: {
818
- padding: theme.spacing.unit,
819
- letterSpacing: '0.5px'
820
- },
821
- correct: {
822
- borderColor: "".concat(_renderUi.color.correct(), " !important")
823
- },
824
- incorrect: {
825
- borderColor: "".concat(_renderUi.color.incorrect(), " !important")
826
- },
827
- blockContainer: {
828
- margin: "".concat(theme.spacing.unit, "px !important"),
829
- display: 'inline-flex',
830
- border: '2px solid grey !important'
831
- },
832
- blockResponse: {
833
- flex: 2,
834
- color: 'grey',
835
- background: theme.palette.grey['A100'],
836
- fontSize: '0.8rem !important',
837
- padding: "".concat(theme.spacing.unit / 2, "px !important"),
838
- display: 'flex',
839
- alignItems: 'center',
840
- justifyContent: 'center',
841
- borderRight: "2px solid ".concat(_renderUi.color.disabled(), " !important")
842
- },
843
- toggle: {
844
- color: _renderUi.color.text(),
845
- marginBottom: theme.spacing.unit * 2
846
- },
847
- blockMath: {
848
- color: _renderUi.color.text(),
849
- backgroundColor: _renderUi.color.background(),
850
- padding: "".concat(theme.spacing.unit / 2, "px !important"),
851
- display: 'flex',
852
- alignItems: 'center',
853
- justifyContent: 'center',
854
- flex: 8,
855
- '& > .mq-math-mode': {
856
- '& > .mq-hasCursor': {
857
- '& > .mq-cursor': {
858
- display: 'none'
859
- }
860
- }
742
+ }, /*#__PURE__*/_react.default.createElement(MainContainer, null, mode === 'gather' && /*#__PURE__*/_react.default.createElement(SrOnly, null, "Math Equation Response Question"), /*#__PURE__*/_react.default.createElement(MainContainer, null, showCorrectAnswerToggle && /*#__PURE__*/_react.default.createElement(StyledToggle, {
743
+ language: language,
744
+ show: true,
745
+ toggled: showCorrect,
746
+ onToggle: this.toggleShowCorrect
747
+ })), this.renderTeacherInstructions(), prompt && /*#__PURE__*/_react.default.createElement(PromptContainer, null, /*#__PURE__*/_react.default.createElement(_renderUi.PreviewPrompt, {
748
+ prompt: prompt
749
+ })), /*#__PURE__*/_react.default.createElement(_renderUi.Readable, {
750
+ false: true
751
+ }, this.renderPlayerContent()), displayNote && /*#__PURE__*/_react.default.createElement(Note, {
752
+ className: "note",
753
+ dangerouslySetInnerHTML: {
754
+ __html: note
861
755
  }
862
- },
863
- printContainer: {
864
- marginBottom: theme.spacing.unit,
865
- pointerEvents: 'none'
866
- },
867
- srOnly: {
868
- position: 'absolute',
869
- left: '-10000px',
870
- top: 'auto',
871
- width: '1px',
872
- height: '1px',
873
- overflow: 'hidden'
874
- },
875
- note: {
876
- marginBottom: theme.spacing.unit * 2
877
- }
878
- };
879
- };
880
-
881
- var _default = (0, _styles.withStyles)(styles)(Main);
882
-
883
- exports["default"] = _default;
756
+ }), this.renderRationale()));
757
+ }
758
+ }
759
+ exports.Main = Main;
760
+ // removes {{ and }} and returns only key response. Eg: {{0}} => 0
761
+ (0, _defineProperty2.default)(Main, "getResponseKey", response => (response || '').replaceAll('{{', '').replaceAll('}}', ''));
762
+ (0, _defineProperty2.default)(Main, "propTypes", {
763
+ session: _propTypes.default.object.isRequired,
764
+ onSessionChange: _propTypes.default.func,
765
+ model: _propTypes.default.object.isRequired
766
+ });
767
+ var _default = exports.default = Main;
884
768
  //# sourceMappingURL=main.js.map