@pie-element/math-inline 10.0.0 → 10.0.1-esm.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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@pie-element/math-inline-configure",
3
3
  "private": true,
4
- "version": "9.0.1",
4
+ "version": "9.0.2-esm.0",
5
5
  "description": "",
6
6
  "main": "lib/index.js",
7
7
  "module": "src/index.js",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@pie-element/math-inline-controller",
3
3
  "private": true,
4
- "version": "8.0.1",
4
+ "version": "8.0.2-esm.0",
5
5
  "description": "",
6
6
  "main": "lib/index.js",
7
7
  "module": "src/index.js",
@@ -0,0 +1,468 @@
1
+ import debug from 'debug';
2
+ import isEmpty from 'lodash/isEmpty';
3
+ import { getActualFeedbackForCorrectness } from '@pie-lib/feedback';
4
+ import Translator from '@pie-lib/translator';
5
+ import * as mv from '@pie-framework/math-validation';
6
+
7
+ function ownKeys(object, enumerableOnly) {
8
+ var keys = Object.keys(object);
9
+
10
+ if (Object.getOwnPropertySymbols) {
11
+ var symbols = Object.getOwnPropertySymbols(object);
12
+ enumerableOnly && (symbols = symbols.filter(function (sym) {
13
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
14
+ })), keys.push.apply(keys, symbols);
15
+ }
16
+
17
+ return keys;
18
+ }
19
+
20
+ function _objectSpread2(target) {
21
+ for (var i = 1; i < arguments.length; i++) {
22
+ var source = null != arguments[i] ? arguments[i] : {};
23
+ i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
24
+ _defineProperty(target, key, source[key]);
25
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
26
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
27
+ });
28
+ }
29
+
30
+ return target;
31
+ }
32
+
33
+ function _defineProperty(obj, key, value) {
34
+ if (key in obj) {
35
+ Object.defineProperty(obj, key, {
36
+ value: value,
37
+ enumerable: true,
38
+ configurable: true,
39
+ writable: true
40
+ });
41
+ } else {
42
+ obj[key] = value;
43
+ }
44
+
45
+ return obj;
46
+ }
47
+
48
+ function _objectWithoutPropertiesLoose(source, excluded) {
49
+ if (source == null) return {};
50
+ var target = {};
51
+ var sourceKeys = Object.keys(source);
52
+ var key, i;
53
+
54
+ for (i = 0; i < sourceKeys.length; i++) {
55
+ key = sourceKeys[i];
56
+ if (excluded.indexOf(key) >= 0) continue;
57
+ target[key] = source[key];
58
+ }
59
+
60
+ return target;
61
+ }
62
+
63
+ function _objectWithoutProperties(source, excluded) {
64
+ if (source == null) return {};
65
+
66
+ var target = _objectWithoutPropertiesLoose(source, excluded);
67
+
68
+ var key, i;
69
+
70
+ if (Object.getOwnPropertySymbols) {
71
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
72
+
73
+ for (i = 0; i < sourceSymbolKeys.length; i++) {
74
+ key = sourceSymbolKeys[i];
75
+ if (excluded.indexOf(key) >= 0) continue;
76
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
77
+ target[key] = source[key];
78
+ }
79
+ }
80
+
81
+ return target;
82
+ }
83
+
84
+ var ResponseTypes = {
85
+ advanced: 'Advanced Multi',
86
+ simple: 'Simple'
87
+ };
88
+
89
+ var defaults = {
90
+ allowTrailingZerosDefault: false,
91
+ customKeys: [],
92
+ equationEditor: '8',
93
+ expression: '',
94
+ feedback: {
95
+ correct: {
96
+ default: 'Correct',
97
+ type: 'none'
98
+ },
99
+ incorrect: {
100
+ default: 'Incorrect',
101
+ type: 'none'
102
+ },
103
+ partial: {
104
+ default: 'Nearly',
105
+ type: 'none'
106
+ }
107
+ },
108
+ feedbackEnabled: false,
109
+ ignoreOrderDefault: false,
110
+ partialScoring: true,
111
+ prompt: '',
112
+ promptEnabled: true,
113
+ rationale: '',
114
+ rationaleEnabled: true,
115
+ responseType: ResponseTypes.advanced,
116
+ responses: [],
117
+ scoringType: 'auto',
118
+ studentInstructionsEnabled: true,
119
+ teacherInstructions: '',
120
+ teacherInstructionsEnabled: true,
121
+ toolbarEditorPosition: 'bottom',
122
+ validationDefault: 'literal'
123
+ };
124
+
125
+ var _excluded = ["extraCSSRules", "responses", "language"];
126
+ var {
127
+ translator
128
+ } = Translator;
129
+ var log = debug('@pie-element:math-inline:controller');
130
+
131
+ var getResponseCorrectness = (model, answerItem, isOutcome) => {
132
+ var correctResponses = model.responses;
133
+ var isAdvanced = model.responseType === ResponseTypes.advanced;
134
+
135
+ if (!answerItem) {
136
+ return {
137
+ correctness: 'unanswered',
138
+ score: isOutcome ? 0 : '0%',
139
+ correct: false
140
+ };
141
+ }
142
+
143
+ var isAnswerCorrect = getIsAnswerCorrect(isAdvanced ? correctResponses : correctResponses.slice(0, 1), answerItem);
144
+ var correctnessObject = {
145
+ correctness: 'incorrect',
146
+ score: isOutcome ? 0 : '0%',
147
+ correct: false
148
+ };
149
+
150
+ if (isAnswerCorrect) {
151
+ correctnessObject.correctness = 'correct';
152
+ correctnessObject.score = isOutcome ? 1 : '100%';
153
+ correctnessObject.correct = true;
154
+ }
155
+
156
+ return correctnessObject;
157
+ };
158
+
159
+ function getIsAnswerCorrect(correctResponseItems, answerItem) {
160
+ var answerCorrect = false;
161
+ (correctResponseItems || []).forEach(correctResponse => {
162
+ if (answerCorrect) return;
163
+ var opts = {
164
+ mode: correctResponse.validation || defaults.validationDefault
165
+ };
166
+
167
+ if (opts.mode === 'literal') {
168
+ opts.literal = {
169
+ allowTrailingZeros: correctResponse.allowTrailingZeros || false,
170
+ ignoreOrder: correctResponse.ignoreOrder || false
171
+ };
172
+ }
173
+
174
+ var acceptedValues = [correctResponse.answer].concat(Object.keys(correctResponse.alternates || {}).map(alternateId => correctResponse.alternates[alternateId]));
175
+
176
+ for (var i = 0; i < acceptedValues.length; i++) {
177
+ try {
178
+ if (mv.latexEqual(answerItem, acceptedValues[i], opts)) {
179
+ answerCorrect = true;
180
+ break;
181
+ }
182
+ } catch (e) {
183
+ log('Parse failure when evaluating math', acceptedValues[i], answerItem, e);
184
+ continue;
185
+ }
186
+ }
187
+ });
188
+ return answerCorrect;
189
+ }
190
+
191
+ var getCorrectness = (question, env, session, isOutcome) => {
192
+ if (env.mode === 'evaluate') {
193
+ return getResponseCorrectness(question, question.responseType === ResponseTypes.advanced ? session && session.completeAnswer || '' : session && session.response, isOutcome);
194
+ }
195
+
196
+ return undefined;
197
+ };
198
+
199
+ function createDefaultModel() {
200
+ var model = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
201
+ return new Promise(resolve => {
202
+ resolve({
203
+ config: _objectSpread2(_objectSpread2({}, defaults), model)
204
+ });
205
+ });
206
+ }
207
+ var outcome = (question, session, env) => {
208
+ return new Promise(resolve => {
209
+ if (env.mode !== 'evaluate') {
210
+ resolve({
211
+ score: undefined,
212
+ completed: undefined
213
+ });
214
+ } else {
215
+ if (!session || isEmpty(session)) {
216
+ resolve({
217
+ score: 0,
218
+ empty: true
219
+ });
220
+ } else {
221
+ var correctness = getCorrectness(question, env, session, true);
222
+ resolve({
223
+ score: correctness.score
224
+ });
225
+ }
226
+ }
227
+ });
228
+ };
229
+ var normalize = question => {
230
+ // making sure that defaults are set
231
+ if (!isEmpty(question.responses)) {
232
+ question.responses = question.responses.map(correctResponse => _objectSpread2(_objectSpread2({}, correctResponse), {}, {
233
+ validation: correctResponse.validation || question.validationDefault,
234
+ allowTrailingZeros: correctResponse.allowTrailingZeros || question.allowTrailingZerosDefault,
235
+ ignoreOrder: correctResponse.ignoreOrder || question.ignoreOrderDefault
236
+ }));
237
+ }
238
+
239
+ return _objectSpread2(_objectSpread2({}, defaults), question);
240
+ };
241
+ var model = (question, session, env) => new Promise(resolve => {
242
+ var _config$responses;
243
+
244
+ var normalizedQuestion = normalize(question);
245
+ var correctness = getCorrectness(normalizedQuestion, env, session);
246
+
247
+ var {
248
+ extraCSSRules,
249
+ responses,
250
+ language
251
+ } = normalizedQuestion,
252
+ config = _objectWithoutProperties(normalizedQuestion, _excluded);
253
+
254
+ config.responses = config.responseType === ResponseTypes.simple ? responses.slice(0, 1) : responses;
255
+ var feedback = env.mode === 'evaluate' && normalizedQuestion.feedbackEnabled ? getActualFeedbackForCorrectness(correctness === null || correctness === void 0 ? void 0 : correctness.correctness, normalizedQuestion.feedback) : undefined;
256
+ var out = {
257
+ extraCSSRules,
258
+ config,
259
+ correctness,
260
+ feedback,
261
+ disabled: env.mode !== 'gather',
262
+ view: env.mode === 'view'
263
+ };
264
+ var note = normalizedQuestion.note || translator.t('mathInline.primaryCorrectWithAlternates', {
265
+ lng: language
266
+ });
267
+ var showNote = (config === null || config === void 0 ? void 0 : (_config$responses = config.responses) === null || _config$responses === void 0 ? void 0 : _config$responses.length) > 1 || ((config === null || config === void 0 ? void 0 : config.responses) || []).some(response => response.validation === 'symbolic' || Object.keys(response.alternates || {}).length > 0);
268
+
269
+ if (env.mode === 'evaluate') {
270
+ out.correctResponse = {};
271
+ out.config.showNote = showNote;
272
+ out.config.note = note;
273
+ } else {
274
+ out.config.responses = [];
275
+ out.config.showNote = false;
276
+ }
277
+
278
+ if (env.role === 'instructor' && (env.mode === 'view' || env.mode === 'evaluate')) {
279
+ out.rationale = normalizedQuestion.rationaleEnabled ? normalizedQuestion.rationale : null;
280
+ out.teacherInstructions = normalizedQuestion.teacherInstructionsEnabled ? normalizedQuestion.teacherInstructions : null;
281
+ } else {
282
+ out.rationale = null;
283
+ out.teacherInstructions = null;
284
+ out.config.rationale = null;
285
+ out.config.teacherInstructions = null;
286
+ }
287
+
288
+ out.config.env = env;
289
+ out.config.prompt = normalizedQuestion.promptEnabled ? normalizedQuestion.prompt : null;
290
+ out.language = language;
291
+ log('out: ', out);
292
+ resolve(out);
293
+ });
294
+
295
+ var escape = string => string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
296
+
297
+
298
+ var simpleSessionResponse = question => new Promise(resolve => {
299
+ var {
300
+ responses,
301
+ id
302
+ } = question;
303
+ var {
304
+ answer
305
+ } = responses && responses.length ? responses[0] : {};
306
+ resolve({
307
+ id,
308
+ response: answer || '',
309
+ completeAnswer: answer || ''
310
+ });
311
+ }); // use this for items like E672793
312
+
313
+
314
+ var removeTrailingEscape = str => str.endsWith('\\') ? str.slice(0, -1) : str;
315
+
316
+ var advancedSessionResponse = question => new Promise(resolve => {
317
+ var {
318
+ responses,
319
+ id
320
+ } = question;
321
+ var {
322
+ answer
323
+ } = responses && responses.length ? responses[0] : {};
324
+
325
+ if (!answer) {
326
+ resolve({
327
+ id,
328
+ answers: {},
329
+ completeAnswer: ''
330
+ });
331
+ return;
332
+ }
333
+
334
+ try {
335
+ var e = question.expression;
336
+ var RESPONSE_TOKEN = /\\{\\{\s*response\s*\\}\\}/g;
337
+ var o = escape(e).split(RESPONSE_TOKEN);
338
+ var to = o.map(t => t === '' ? t : t.replace(/\s+/g, () => '\\s*'));
339
+ var tt = to.join('(.*)');
340
+ var m = answer.match(new RegExp(tt));
341
+ var count = o.length - 1;
342
+
343
+ if (!m) {
344
+ resolve({
345
+ id,
346
+ answers: {},
347
+ completeAnswer: answer
348
+ }); // eslint-disable-next-line no-console
349
+
350
+ console.log("can not find match: ".concat(o, " in ").concat(answer));
351
+ return;
352
+ }
353
+
354
+ m.shift();
355
+ var answers = {};
356
+
357
+ for (var i = 0; i < count; i++) {
358
+ answers["r".concat(i + 1)] = {
359
+ value: removeTrailingEscape(m[i].trim())
360
+ };
361
+ }
362
+
363
+ resolve({
364
+ id,
365
+ answers,
366
+ completeAnswer: answer
367
+ });
368
+ } catch (e) {
369
+ resolve({
370
+ id,
371
+ answers: {},
372
+ completeAnswer: answer
373
+ }); // eslint-disable-next-line no-console
374
+
375
+ console.error(e.toString());
376
+ }
377
+ });
378
+
379
+ var createCorrectResponseSession = (question, env) => {
380
+ if (env.mode === 'evaluate' || env.role !== 'instructor') {
381
+ // eslint-disable-next-line no-console
382
+ console.error('can not create correct response session if mode is evaluate or role is not instructor');
383
+ return Promise.resolve(null);
384
+ }
385
+
386
+ if ((question.responseType || '').toLowerCase() === 'simple') {
387
+ return simpleSessionResponse(question);
388
+ } else {
389
+ return advancedSessionResponse(question);
390
+ }
391
+ }; // remove all html tags
392
+
393
+
394
+ var getContent = html => (html || '').replace(/(<(?!img|iframe|source)([^>]+)>)/gi, '');
395
+
396
+ var validate = function validate() {
397
+ var model = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
398
+ var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
399
+ var {
400
+ expression = '',
401
+ responses,
402
+ responseType
403
+ } = model;
404
+ var {
405
+ maxResponseAreas
406
+ } = config;
407
+ var responsesErrors = {};
408
+ var errors = {};
409
+ ['teacherInstructions', 'prompt', 'rationale'].forEach(field => {
410
+ var _config$field;
411
+
412
+ if ((_config$field = config[field]) !== null && _config$field !== void 0 && _config$field.required && !getContent(model[field])) {
413
+ errors[field] = 'This field is required.';
414
+ }
415
+ });
416
+ (responses || []).forEach((response, index) => {
417
+ var {
418
+ answer
419
+ } = response;
420
+ var reversedAlternates = [...Object.entries(response.alternates || {})].reverse();
421
+ var alternatesErrors = {};
422
+ var responseError = {};
423
+
424
+ if (answer === '') {
425
+ responseError.answer = 'Content should not be empty.';
426
+ }
427
+
428
+ reversedAlternates.forEach((_ref, index) => {
429
+ var [key, value] = _ref;
430
+
431
+ if (value === '') {
432
+ alternatesErrors[key] = 'Content should not be empty.';
433
+ } else {
434
+ var identicalAnswer = answer === value || reversedAlternates.slice(index + 1).some(_ref2 => {
435
+ var [, val] = _ref2;
436
+ return val === value;
437
+ });
438
+
439
+ if (identicalAnswer) {
440
+ alternatesErrors[key] = 'Content should be unique.';
441
+ }
442
+ }
443
+ });
444
+
445
+ if (!isEmpty(responseError) || !isEmpty(alternatesErrors)) {
446
+ responsesErrors[index] = _objectSpread2(_objectSpread2({}, responseError), alternatesErrors);
447
+ }
448
+ });
449
+
450
+ if (responseType === 'Advanced Multi') {
451
+ var nbOfResponseAreas = (expression.match(/\{\{response\}\}/g) || []).length;
452
+
453
+ if (nbOfResponseAreas > maxResponseAreas) {
454
+ errors.responseAreasError = "No more than ".concat(maxResponseAreas, " response areas should be defined.");
455
+ } else if (nbOfResponseAreas < 1) {
456
+ errors.responseAreasError = 'There should be at least 1 response area defined.';
457
+ }
458
+ }
459
+
460
+ if (!isEmpty(responsesErrors)) {
461
+ errors.responsesErrors = responsesErrors;
462
+ }
463
+
464
+ return errors;
465
+ };
466
+
467
+ export { createCorrectResponseSession, createDefaultModel, model, normalize, outcome, validate };
468
+ //# sourceMappingURL=controller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controller.js","sources":["../controller/src/utils.js","../controller/src/defaults.js","../controller/src/index.js"],"sourcesContent":["export const ResponseTypes = {\n advanced: 'Advanced Multi',\n simple: 'Simple',\n};\n","import { ResponseTypes } from './utils';\n\nexport default {\n allowTrailingZerosDefault: false,\n customKeys: [],\n equationEditor: '8',\n expression: '',\n feedback: {\n correct: { default: 'Correct', type: 'none' },\n incorrect: { default: 'Incorrect', type: 'none' },\n partial: { default: 'Nearly', type: 'none' },\n },\n feedbackEnabled: false,\n ignoreOrderDefault: false,\n partialScoring: true,\n prompt: '',\n promptEnabled: true,\n rationale: '',\n rationaleEnabled: true,\n responseType: ResponseTypes.advanced,\n responses: [],\n scoringType: 'auto',\n studentInstructionsEnabled: true,\n teacherInstructions: '',\n teacherInstructionsEnabled: true,\n toolbarEditorPosition: 'bottom',\n validationDefault: 'literal',\n};\n","import debug from 'debug';\nimport isEmpty from 'lodash/isEmpty';\nimport { getActualFeedbackForCorrectness } from '@pie-lib/feedback';\n\nimport { ResponseTypes } from './utils';\nimport Translator from '@pie-lib/translator';\n\nconst { translator } = Translator;\nimport defaults from './defaults';\n\nimport * as mv from '@pie-framework/math-validation';\n\nconst log = debug('@pie-element:math-inline:controller');\n\nconst getResponseCorrectness = (model, answerItem, isOutcome) => {\n const correctResponses = model.responses;\n const isAdvanced = model.responseType === ResponseTypes.advanced;\n\n if (!answerItem) {\n return {\n correctness: 'unanswered',\n score: isOutcome ? 0 : '0%',\n correct: false,\n };\n }\n\n const isAnswerCorrect = getIsAnswerCorrect(isAdvanced ? correctResponses : correctResponses.slice(0, 1), answerItem);\n\n const correctnessObject = {\n correctness: 'incorrect',\n score: isOutcome ? 0 : '0%',\n correct: false,\n };\n\n if (isAnswerCorrect) {\n correctnessObject.correctness = 'correct';\n correctnessObject.score = isOutcome ? 1 : '100%';\n correctnessObject.correct = true;\n }\n\n return correctnessObject;\n};\n\nfunction getIsAnswerCorrect(correctResponseItems, answerItem) {\n let answerCorrect = false;\n\n (correctResponseItems || []).forEach((correctResponse) => {\n if (answerCorrect) return;\n\n const opts = {\n mode: correctResponse.validation || defaults.validationDefault,\n };\n\n if (opts.mode === 'literal') {\n opts.literal = {\n allowTrailingZeros: correctResponse.allowTrailingZeros || false,\n ignoreOrder: correctResponse.ignoreOrder || false,\n };\n }\n\n const acceptedValues = [correctResponse.answer].concat(\n Object.keys(correctResponse.alternates || {}).map((alternateId) => correctResponse.alternates[alternateId]),\n );\n\n for (let i = 0; i < acceptedValues.length; i++) {\n try {\n if (mv.latexEqual(answerItem, acceptedValues[i], opts)) {\n answerCorrect = true;\n break;\n }\n } catch (e) {\n log('Parse failure when evaluating math', acceptedValues[i], answerItem, e);\n continue;\n }\n }\n });\n\n return answerCorrect;\n}\n\nconst getCorrectness = (question, env, session, isOutcome) => {\n if (env.mode === 'evaluate') {\n return getResponseCorrectness(\n question,\n question.responseType === ResponseTypes.advanced\n ? (session && session.completeAnswer) || ''\n : session && session.response,\n isOutcome,\n );\n }\n\n return undefined;\n};\n\nexport function createDefaultModel(model = {}) {\n return new Promise((resolve) => {\n resolve({\n config: {\n ...defaults,\n ...model,\n },\n });\n });\n}\n\nexport const outcome = (question, session, env) => {\n return new Promise((resolve) => {\n if (env.mode !== 'evaluate') {\n resolve({ score: undefined, completed: undefined });\n } else {\n if (!session || isEmpty(session)) {\n resolve({ score: 0, empty: true });\n } else {\n const correctness = getCorrectness(question, env, session, true);\n\n resolve({ score: correctness.score });\n }\n }\n });\n};\n\nexport const normalize = (question) => {\n // making sure that defaults are set\n if (!isEmpty(question.responses)) {\n question.responses = question.responses.map((correctResponse) => ({\n ...correctResponse,\n validation: correctResponse.validation || question.validationDefault,\n allowTrailingZeros: correctResponse.allowTrailingZeros || question.allowTrailingZerosDefault,\n ignoreOrder: correctResponse.ignoreOrder || question.ignoreOrderDefault,\n }));\n }\n\n return { ...defaults, ...question };\n};\n\nexport const model = (question, session, env) =>\n new Promise((resolve) => {\n const normalizedQuestion = normalize(question);\n const correctness = getCorrectness(normalizedQuestion, env, session);\n const { extraCSSRules, responses, language, ...config } = normalizedQuestion;\n\n config.responses = config.responseType === ResponseTypes.simple ? responses.slice(0, 1) : responses;\n\n const feedback =\n env.mode === 'evaluate' && normalizedQuestion.feedbackEnabled\n ? getActualFeedbackForCorrectness(correctness?.correctness, normalizedQuestion.feedback)\n : undefined;\n\n const out = {\n extraCSSRules,\n config,\n correctness,\n feedback,\n disabled: env.mode !== 'gather',\n view: env.mode === 'view',\n };\n\n const note = normalizedQuestion.note || translator.t('mathInline.primaryCorrectWithAlternates', { lng: language });\n const showNote =\n config?.responses?.length > 1 ||\n (config?.responses || []).some(\n (response) => response.validation === 'symbolic' || Object.keys(response.alternates || {}).length > 0,\n );\n\n if (env.mode === 'evaluate') {\n out.correctResponse = {};\n out.config.showNote = showNote;\n out.config.note = note;\n } else {\n out.config.responses = [];\n out.config.showNote = false;\n }\n\n if (env.role === 'instructor' && (env.mode === 'view' || env.mode === 'evaluate')) {\n out.rationale = normalizedQuestion.rationaleEnabled ? normalizedQuestion.rationale : null;\n out.teacherInstructions = normalizedQuestion.teacherInstructionsEnabled\n ? normalizedQuestion.teacherInstructions\n : null;\n } else {\n out.rationale = null;\n out.teacherInstructions = null;\n out.config.rationale = null;\n out.config.teacherInstructions = null;\n }\n\n out.config.env = env;\n out.config.prompt = normalizedQuestion.promptEnabled ? normalizedQuestion.prompt : null;\n out.language = language;\n\n log('out: ', out);\n resolve(out);\n });\n\nconst escape = (string) => string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string\n\nconst simpleSessionResponse = (question) =>\n new Promise((resolve) => {\n const { responses, id } = question;\n const { answer } = responses && responses.length ? responses[0] : {};\n\n resolve({\n id,\n response: answer || '',\n completeAnswer: answer || '',\n });\n });\n\n// use this for items like E672793\nconst removeTrailingEscape = (str) => (str.endsWith('\\\\') ? str.slice(0, -1) : str);\n\nconst advancedSessionResponse = (question) =>\n new Promise((resolve) => {\n const { responses, id } = question;\n const { answer } = responses && responses.length ? responses[0] : {};\n\n if (!answer) {\n resolve({\n id,\n answers: {},\n completeAnswer: '',\n });\n\n return;\n }\n\n try {\n const e = question.expression;\n const RESPONSE_TOKEN = /\\\\{\\\\{\\s*response\\s*\\\\}\\\\}/g;\n\n const o = escape(e).split(RESPONSE_TOKEN);\n const to = o.map((t) => (t === '' ? t : t.replace(/\\s+/g, () => '\\\\s*')));\n const tt = to.join('(.*)');\n\n const m = answer.match(new RegExp(tt));\n\n const count = o.length - 1;\n\n if (!m) {\n resolve({\n id,\n answers: {},\n completeAnswer: answer,\n });\n\n // eslint-disable-next-line no-console\n console.log(`can not find match: ${o} in ${answer}`);\n\n return;\n }\n\n m.shift();\n\n const answers = {};\n\n for (var i = 0; i < count; i++) {\n answers[`r${i + 1}`] = { value: removeTrailingEscape(m[i].trim()) };\n }\n\n resolve({\n id,\n answers,\n completeAnswer: answer,\n });\n } catch (e) {\n resolve({\n id,\n answers: {},\n completeAnswer: answer,\n });\n // eslint-disable-next-line no-console\n console.error(e.toString());\n }\n });\n\nexport const createCorrectResponseSession = (question, env) => {\n if (env.mode === 'evaluate' || env.role !== 'instructor') {\n // eslint-disable-next-line no-console\n console.error('can not create correct response session if mode is evaluate or role is not instructor');\n\n return Promise.resolve(null);\n }\n\n if ((question.responseType || '').toLowerCase() === 'simple') {\n return simpleSessionResponse(question, env);\n } else {\n return advancedSessionResponse(question, env);\n }\n};\n\n// remove all html tags\nconst getInnerText = (html) => (html || '').replaceAll(/<[^>]*>/g, '');\n\n// remove all html tags except img, iframe and source tag for audio\nconst getContent = (html) => (html || '').replace(/(<(?!img|iframe|source)([^>]+)>)/gi, '');\n\nexport const validate = (model = {}, config = {}) => {\n const { expression = '', responses, responseType } = model;\n const { maxResponseAreas } = config;\n const responsesErrors = {};\n const errors = {};\n\n ['teacherInstructions', 'prompt', 'rationale'].forEach((field) => {\n if (config[field]?.required && !getContent(model[field])) {\n errors[field] = 'This field is required.';\n }\n });\n\n (responses || []).forEach((response, index) => {\n const { answer } = response;\n const reversedAlternates = [...Object.entries(response.alternates || {})].reverse();\n const alternatesErrors = {};\n const responseError = {};\n\n if (answer === '') {\n responseError.answer = 'Content should not be empty.';\n }\n\n reversedAlternates.forEach(([key, value], index) => {\n if (value === '') {\n alternatesErrors[key] = 'Content should not be empty.';\n } else {\n const identicalAnswer =\n answer === value || reversedAlternates.slice(index + 1).some(([, val]) => val === value);\n\n if (identicalAnswer) {\n alternatesErrors[key] = 'Content should be unique.';\n }\n }\n });\n\n if (!isEmpty(responseError) || !isEmpty(alternatesErrors)) {\n responsesErrors[index] = { ...responseError, ...alternatesErrors };\n }\n });\n\n if (responseType === 'Advanced Multi') {\n const nbOfResponseAreas = (expression.match(/\\{\\{response\\}\\}/g) || []).length;\n\n if (nbOfResponseAreas > maxResponseAreas) {\n errors.responseAreasError = `No more than ${maxResponseAreas} response areas should be defined.`;\n } else if (nbOfResponseAreas < 1) {\n errors.responseAreasError = 'There should be at least 1 response area defined.';\n }\n }\n\n if (!isEmpty(responsesErrors)) {\n errors.responsesErrors = responsesErrors;\n }\n\n return errors;\n};\n"],"names":["ResponseTypes","advanced","simple","allowTrailingZerosDefault","customKeys","equationEditor","expression","feedback","correct","default","type","incorrect","partial","feedbackEnabled","ignoreOrderDefault","partialScoring","prompt","promptEnabled","rationale","rationaleEnabled","responseType","responses","scoringType","studentInstructionsEnabled","teacherInstructions","teacherInstructionsEnabled","toolbarEditorPosition","validationDefault","translator","Translator","log","debug","getResponseCorrectness","model","answerItem","isOutcome","correctResponses","isAdvanced","correctness","score","isAnswerCorrect","getIsAnswerCorrect","slice","correctnessObject","correctResponseItems","answerCorrect","forEach","correctResponse","opts","mode","validation","defaults","literal","allowTrailingZeros","ignoreOrder","acceptedValues","answer","concat","Object","keys","alternates","map","alternateId","i","length","mv","latexEqual","e","getCorrectness","question","env","session","completeAnswer","response","undefined","createDefaultModel","Promise","resolve","config","_objectSpread","outcome","completed","isEmpty","empty","normalize","normalizedQuestion","extraCSSRules","language","getActualFeedbackForCorrectness","out","disabled","view","note","t","lng","showNote","some","role","escape","string","replace","simpleSessionResponse","id","removeTrailingEscape","str","endsWith","advancedSessionResponse","answers","RESPONSE_TOKEN","o","split","to","tt","join","m","match","RegExp","count","console","shift","value","trim","error","toString","createCorrectResponseSession","toLowerCase","getContent","html","validate","maxResponseAreas","responsesErrors","errors","field","required","index","reversedAlternates","entries","reverse","alternatesErrors","responseError","key","identicalAnswer","val","nbOfResponseAreas","responseAreasError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAO,IAAMA,aAAa,GAAG;AAC3BC,EAAAA,QAAQ,EAAE,gBADiB;AAE3BC,EAAAA,MAAM,EAAE,QAAA;AAFmB,CAAtB;;ACEP,eAAe;AACbC,EAAAA,yBAAyB,EAAE,KADd;AAEbC,EAAAA,UAAU,EAAE,EAFC;AAGbC,EAAAA,cAAc,EAAE,GAHH;AAIbC,EAAAA,UAAU,EAAE,EAJC;AAKbC,EAAAA,QAAQ,EAAE;AACRC,IAAAA,OAAO,EAAE;AAAEC,MAAAA,OAAO,EAAE,SAAX;AAAsBC,MAAAA,IAAI,EAAE,MAAA;AAA5B,KADD;AAERC,IAAAA,SAAS,EAAE;AAAEF,MAAAA,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,OAAA;AACF,KAXD,CAAA,CAAA;;AAaA,IAAI,IAAA,CAAC1D,OAAO,CAACyD,aAAD,CAAR,IAA2B,CAACzD,OAAO,CAACwD,gBAAD,CAAvC,EAA2D;AACzDR,MAAAA,eAAe,CAACI,KAAD,CAAf,GAA8BK,cAAAA,CAAAA,cAAAA,CAAAA,EAAAA,EAAAA,aAA9B,GAAgDD,gBAAhD,CAAA,CAAA;AACD,KAAA;AACF,GA1BD,CAAA,CAAA;;AA4BA,EAAItH,IAAAA,YAAY,KAAK,gBAArB,EAAuC;AACrC,IAAM2H,IAAAA,iBAAiB,GAAG,CAACzI,UAAU,CAAC6G,KAAX,CAAiB,mBAAjB,CAAA,IAAyC,EAA1C,EAA8CnD,MAAxE,CAAA;;AAEA,IAAI+E,IAAAA,iBAAiB,GAAGd,gBAAxB,EAA0C;AACxCE,MAAAA,MAAM,CAACa,kBAAP,GAAA,eAAA,CAAA,MAAA,CAA4Cf,gBAA5C,EAAA,oCAAA,CAAA,CAAA;AACD,KAFD,MAEO,IAAIc,iBAAiB,GAAG,CAAxB,EAA2B;AAChCZ,MAAAA,MAAM,CAACa,kBAAP,GAA4B,mDAA5B,CAAA;AACD,KAAA;AACF,GAAA;;AAED,EAAA,IAAI,CAAC9D,OAAO,CAACgD,eAAD,CAAZ,EAA+B;AAC7BC,IAAAA,MAAM,CAACD,eAAP,GAAyBA,eAAzB,CAAA;AACD,GAAA;;AAED,EAAA,OAAOC,MAAP,CAAA;AACD;;;;"}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "access": "public"
5
5
  },
6
6
  "repository": "pie-framework/pie-elements",
7
- "version": "10.0.0",
7
+ "version": "10.0.1-esm.0",
8
8
  "main": "lib/index.js",
9
9
  "description": "",
10
10
  "scripts": {
@@ -29,10 +29,13 @@
29
29
  },
30
30
  "author": "",
31
31
  "license": "ISC",
32
- "gitHead": "1962f924d9957626a101efe7b48fb79573248879",
32
+ "gitHead": "8a8ab6fc8351e5021a69230889157a4a38d80e83",
33
33
  "module": "src/index.js",
34
34
  "exports": {
35
- ".": "./src/index.js",
36
- "./print": "./src/print.js"
35
+ "./controller": {
36
+ "import": "./esm/controller.js",
37
+ "require": "./controller/lib/index.js",
38
+ "default": "./esm/controller.js"
39
+ }
37
40
  }
38
41
  }
@@ -1 +0,0 @@
1
- import{_dll_react as e,_dll_prop_types as t,_dll_material_ui__core as n,_dll_material_ui__core_styles as a,_dll_pie_lib__render_ui as o,_dll_classnames as s,_dll_lodash as i,_dll_material_ui__icons as l,_dll_debug as r,_dll_react_dom as c}from"../../../@pie-lib/shared-module@^1.14.0/module/index.js";import{_dll_pie_lib__config_ui as p}from"../../../@pie-lib/config-module@^2.19.0/module/index.js";import{_dll_pie_lib__editable_html as d}from"../../../@pie-lib/editable-html-module@^5.6.0/module/index.js";import{_dll_pie_lib__math_toolbar as u,_dll_pie_framework__mathquill as m}from"../../../@pie-lib/math-edit-module@^2.4.0/module/index.js";const h=e,g=t,{Card:b}=n,{CardContent:_}=n,{Button:C}=n,{FormControlLabel:y}=n,{Typography:f}=n,{InputLabel:E}=n,{Checkbox:v}=n,{Select:x}=n,{MenuItem:S}=n,{withStyles:w}=a,{color:T}=o,{InputContainer:I}=p,{MathToolbar:A}=u;class k extends h.Component{static __initStatic(){this.propTypes={classes:g.object.isRequired,defaultResponse:g.bool,error:g.object,mode:g.oneOfType([g.string,g.number]),index:g.number,onResponseChange:g.func.isRequired,response:g.object.isRequired,cIgnoreOrder:g.object.isRequired,cAllowTrailingZeros:g.object.isRequired}}static __initStatic2(){this.defaultProps={defaultResponse:!1,mode:"miscellaneous"}}constructor(e){super(e),k.prototype.__init.call(this),k.prototype.__init2.call(this),k.prototype.__init3.call(this),k.prototype.__init4.call(this),k.prototype.__init5.call(this),k.prototype.__init6.call(this),k.prototype.__init7.call(this),k.prototype.__init8.call(this),k.prototype.__init9.call(this),k.prototype.__init10.call(this),k.prototype.__init11.call(this);const{response:{alternates:t}={}}=e||{},n=Object.keys(t||{}).length;this.state={alternateIdCounter:n+1,showKeypad:{openCount:0,main:!1}}}__init(){this.onChange=e=>t=>{const{response:n,onResponseChange:a,index:o}=this.props,s={...n};s[e]=t.target.value,a(s,o)}}__init2(){this.onConfigChanged=e=>t=>{const{response:n,onResponseChange:a,index:o}=this.props,s={...n};s[e]=t.target.checked,a(s,o)}}__init3(){this.onLiteralOptionsChange=e=>()=>{const{response:t,onResponseChange:n,index:a}=this.props,o={...t};o[e]=!t[e],n(o,a)}}__init4(){this.onAnswerChange=e=>{const{response:t,onResponseChange:n,index:a}=this.props,o={...t};o.answer=e,n(o,a)}}__init5(){this.onAlternateAnswerChange=e=>t=>{const{response:n,onResponseChange:a,index:o}=this.props,s={...n};s.alternates[e]=t,a(s,o)}}__init6(){this.onAddAlternate=()=>{const{response:e,onResponseChange:t,index:n}=this.props,{alternateIdCounter:a}=this.state,o={...e};o.alternates||(o.alternates={}),o.alternates[a]="",t(o,n),this.setState({alternateIdCounter:a+1})}}__init7(){this.onRemoveAlternate=e=>()=>{const{response:t,onResponseChange:n,index:a}=this.props,o={...t};delete o.alternates[e],n(o,a),this.setState((t=>({showKeypad:{...t.showKeypad,openCount:t.showKeypad[e]?t.showKeypad.openCount-1:t.showKeypad.openCount}})))}}__init8(){this.onDone=()=>{this.setState((e=>({showKeypad:{...e.showKeypad,openCount:e.showKeypad.openCount-1,main:!1}})))}}__init9(){this.onFocus=()=>{this.setState((e=>({showKeypad:{...e.showKeypad,openCount:e.showKeypad.main?e.showKeypad.openCount:e.showKeypad.openCount+1,main:!0}})))}}__init10(){this.onAlternateFocus=e=>()=>{this.setState((t=>({showKeypad:{...t.showKeypad,openCount:t.showKeypad[e]?t.showKeypad.openCount:t.showKeypad.openCount+1,[e]:!0}})))}}__init11(){this.onAlternateDone=e=>()=>{this.setState((t=>({showKeypad:{...t.showKeypad,openCount:t.showKeypad.openCount-1,[e]:!1}})))}}render(){const{classes:e,mode:t,defaultResponse:n,index:a,response:o,cAllowTrailingZeros:s,cIgnoreOrder:i,error:l}=this.props,{showKeypad:r}=this.state,{validation:c,answer:p,alternates:d,ignoreOrder:u,allowTrailingZeros:m}=o,g=Object.keys(d||{}).length>0,w={editor:e.responseEditor,mathToolbar:e.mathToolbar},T={minHeight:(r.openCount>0?430:230)+"px"};return h.createElement(b,{className:e.responseContainer,style:T},h.createElement(_,{className:e.cardContent},h.createElement("div",{className:e.titleBar},h.createElement(f,{className:e.title,component:"div"},"Response ",""),h.createElement(I,{label:"Validation",className:e.selectContainer},h.createElement(x,{className:e.select,onChange:this.onChange("validation"),value:c||"literal"},h.createElement(S,{value:"literal"},"Literal Validation"),h.createElement(S,{value:"symbolic"},"Symbolic Validation")))),"literal"===c&&h.createElement("div",{className:e.flexContainer},s.enabled&&h.createElement(y,{label:s.label,control:h.createElement(v,{className:e.customColor,checked:m,onChange:this.onLiteralOptionsChange("allowTrailingZeros")})}),i.enabled&&h.createElement(y,{label:i.label,control:h.createElement(v,{className:e.customColor,checked:u,onChange:this.onLiteralOptionsChange("ignoreOrder")})})),h.createElement("div",{className:e.inputContainer},h.createElement(E,null,"Correct Answer"),h.createElement(A,{keypadMode:t,classNames:w,controlledKeypad:!0,showKeypad:r.main,latex:p||"",onChange:this.onAnswerChange,onFocus:this.onFocus,onDone:this.onDone,error:l&&l.answer}),l&&l.answer?h.createElement("div",{className:e.errorText},l.answer):null),g&&Object.keys(d).map(((n,a)=>h.createElement("div",{className:e.inputContainer,key:n},h.createElement("div",{className:e.alternateBar},h.createElement(E,null,"Alternate",Object.keys(d).length>1?` ${a+1}`:""),h.createElement(C,{className:e.removeAlternateButton,type:"secondary",onClick:this.onRemoveAlternate(n)},"Remove")),h.createElement(A,{classNames:w,controlledKeypad:!0,keypadMode:t,showKeypad:r[n]||!1,latex:d[n]||"",onChange:this.onAlternateAnswerChange(n),onFocus:this.onAlternateFocus(n),onDone:this.onAlternateDone(n),error:l&&l[n]}),l&&l[n]?h.createElement("div",{className:e.errorText},l[n]):null))),h.createElement(C,{className:e.alternateButton,type:"primary",onClick:this.onAddAlternate},"ADD ALTERNATE")))}}k.__initStatic(),k.__initStatic2();var N=w((e=>({responseContainer:{marginBottom:2.5*e.spacing.unit,width:"100%",minWidth:"548px",border:`1px solid ${e.palette.grey[700]}`,display:"flex",flexDirection:"column",justifyContent:"space-between"},cardContent:{paddingBottom:2*e.spacing.unit+"px !important"},title:{fontWeight:700,fontSize:"1.2rem",flex:3},selectContainer:{flex:2},inputContainer:{marginBottom:2*e.spacing.unit},titleBar:{display:"flex",alignItems:"center",justifyContent:"space-between"},responseEditor:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",minWidth:"500px",maxWidth:"900px",height:"auto",minHeight:"40px"},mathToolbar:{width:"100%"},alternateButton:{border:`1px solid ${e.palette.grey.A100}`},removeAlternateButton:{marginLeft:2*e.spacing.unit,border:`1px solid ${e.palette.grey.A100}`,color:"gray",fontSize:"0.8rem"},errorText:{fontSize:e.typography.fontSize-2,color:e.palette.error.main,paddingTop:e.spacing.unit},customColor:{color:`${T.tertiary()} !important`}})))(k);const R="Advanced Multi",D="Simple",O=(e={},t={})=>({...t,...e}),j=e,M=t,K=s,{withStyles:P}=a,{InputLabel:q}=n,{Select:B}=n,{MenuItem:F}=n,{Tooltip:H}=n,{isEqual:L}=i,{Info:$}=l,z=d,{InputContainer:G}=p,{MathToolbar:Z}=u,W=m;function Y(e){let t,n=e[0],a=1;for(;a<e.length;){const o=e[a],s=e[a+1];if(a+=2,("optionalAccess"===o||"optionalCall"===o)&&null==n)return;"access"===o||"optionalAccess"===o?(t=n,n=s(n)):"call"!==o&&"optionalCall"!==o||(n=s(((...e)=>n.call(t,...e))),t=void 0)}return n}let U=!1;const V=/{{response}}/gm,J=/\\%response\\%/gm,Q=/\\embed\{answerBlock\}\[r\d*\]/g,X=/\\embed\{newLine\}\[\]/g,ee=/\\newline/g;function te(e){if(e){let t=1;return e.replace(V,(()=>`\\embed{answerBlock}[r${t++}]`)).replace(ee,"\\embed{newLine}[]")}}class ne extends j.Component{static __initStatic(){this.propTypes={classes:M.object.isRequired,model:M.object.isRequired,imageSupport:M.object,uploadSoundSupport:M.object,configuration:M.object,onChange:M.func.isRequired,promptEnabled:M.bool,rationaleEnabled:M.bool,toolbarOpts:M.object}}constructor(e){super(e),ne.prototype.__init.call(this),ne.prototype.__init2.call(this),ne.prototype.__init3.call(this),ne.prototype.__init4.call(this),ne.prototype.__init5.call(this),ne.prototype.__init6.call(this),ne.prototype.__init7.call(this);const t={};if(e.model&&e.model.expression){let n=1;e.model.expression.replace(V,(()=>{t["r"+n++]={value:""}}))}this.state={showKeypad:!1,responseAreas:t,responseIdCounter:Object.keys(t).length}}__init(){this.onChange=e=>t=>{const{model:n,onChange:a}=this.props,o={...n};o[e]="object"==typeof t?t.target.value:t,"expression"===e&&(o[e]=function(e){if(e)return e.replace(Q,(()=>"{{response}}")).replace(J,(()=>"{{response}}")).replace(X,(()=>"\\newline"))}(t)),a(o)}}__init2(){this.onDone=()=>{this.setState({showKeypad:!1})}}__init3(){this.onFocus=()=>{this.setState({showKeypad:!0})}}__init4(){this.onPromptFocus=()=>{this.setState({showKeypad:!1})}}UNSAFE_componentWillMount(){const{classes:e}=this.props;if("undefined"!=typeof window){let t=W.getInterface(2);U||(t.registerEmbed("answerBlock",(t=>({htmlString:`<div class="${K(e.blockContainer,e.blockContainerGeneric)}">\n <div class="${K(e.blockResponse,e.blockResponseGeneric)}" id="${t}Index">Response</div>\n </div>`,text:()=>"text",latex:()=>`\\embed{answerBlock}[${t}]`}))),U=!0)}}componentDidMount(){this.handleAnswerBlockDomUpdate()}componentDidUpdate(){this.handleAnswerBlockDomUpdate()}__init5(){this.handleAnswerBlockDomUpdate=()=>{const{model:e}=this.props,t={};if(e&&e.expression){let n=1;e.expression.replace(V,(()=>{t["r"+n++]={value:""}}))}L(t,this.state.responseAreas)||this.setState({responseAreas:t},(()=>{this.root&&Object.keys(t).length&&Object.keys(t).forEach(((e,t)=>{const n=this.root.querySelector(`#${e}`),a=this.root.querySelector(`#${e}Index`);n&&(W.getInterface(2).StaticMath(n),a.textContent=`R${t+1}`)}))}))}}__init6(){this.onAddResponse=()=>{const{model:e,onChange:t}=this.props,{responseIdCounter:n}=this.state,a={...e};let o=n;for(;e.responses.find((e=>e.id===o));)o++;const s={id:o,validation:"literal",answer:"",alternates:{}};a.responses=a.responses.concat(s),t(a),this.setState({responseIdCounter:s.id})}}__init7(){this.onResponseChange=(e,t)=>{const{model:n,onChange:a}=this.props,o={...n};o.responses[t]=e,a(o)}}render(){const{classes:e,model:t,imageSupport:n,uploadSoundSupport:a,configuration:o,promptEnabled:s,rationaleEnabled:i,toolbarOpts:l}=this.props,{showKeypad:r}=this.state,{prompt:c,expression:p,equationEditor:d,promptEquationEditor:u="8",responses:m,responseType:h,rationale:g,spellCheckEnabled:b,errors:_={}}=t,{baseInputConfiguration:C={},rationale:y={},prompt:f={},ignoreOrder:E={},allowTrailingZeros:v={},maxResponseAreas:x,maxImageWidth:S={},maxImageHeight:w={},mathMlOptions:T={}}=o||{},I=((e={},t={})=>{const{maxResponseAreas:n}=t,{responseType:a}=e;let o="";return"Advanced Multi"===a&&(o="\nThere should be at least 1 "+(n?`and at most ${n} `:"")+"response area"+(n?"s":"")+" defined."),"Validation requirements:\nAll correct answers (the primary and any alternates) should not be empty and should be unique."+o})(o,t),{prompt:A,rationale:k,responsesErrors:M,responseAreasError:K}=_,P=S&&S.prompt,L=w&&w.prompt,W={editor:e.responseEditor,mathToolbar:e.mathToolbar},U=h===R?m:m.slice(0,1),V=j.createElement(H,{classes:{tooltip:e.tooltip},disableFocusListener:!0,disableTouchListener:!0,placement:"right",title:I},j.createElement($,{fontSize:"small",color:"primary",style:{marginLeft:"5px"}}));return j.createElement("div",{ref:e=>this.root=e||this.root,className:e.container},s&&j.createElement(G,{label:f.label,className:e.promptHolder},j.createElement(z,{onFocus:this.onPromptFocus,className:e.prompt,markup:c||"",onChange:this.onChange("prompt"),imageSupport:n,nonEmpty:!1,error:A,toolbarOpts:l,pluginProps:O(Y([f,"optionalAccess",e=>e.inputConfiguration]),C),spellCheck:b,maxImageWidth:P,maxImageHeight:L,uploadSoundSupport:a,languageCharactersProps:[{language:"spanish"},{language:"special"}],mathMlOptions:T}),A&&j.createElement("div",{className:e.errorText},A)),h===R&&j.createElement("div",{className:e.advancedResponse},j.createElement("div",{className:e.flexContainer,style:{justifyContent:"flex-start"}},j.createElement("div",{className:e.title},"Define Response"),V),j.createElement(G,{key:"templateEditorType",label:"Response Template Equation Editor",className:e.selectContainer},j.createElement(B,{className:e.select,onChange:this.onChange("promptEquationEditor"),value:u},j.createElement(F,{value:"non-negative-integers"},"Numeric - Non-Negative Integers"),j.createElement(F,{value:"integers"},"Numeric - Integers"),j.createElement(F,{value:"decimals"},"Numeric - Decimals"),j.createElement(F,{value:"fractions"},"Numeric - Fractions"),j.createElement(F,{value:1},"Grade 1 - 2"),j.createElement(F,{value:3},"Grade 3 - 5"),j.createElement(F,{value:6},"Grade 6 - 7"),j.createElement(F,{value:8},"Grade 8 - HS"),j.createElement(F,{value:"geometry"},"Geometry"),j.createElement(F,{value:"advanced-algebra"},"Advanced Algebra"),j.createElement(F,{value:"statistics"},"Statistics"),j.createElement(F,{value:"item-authoring"},"Item Authoring"))),j.createElement("div",{className:e.responseTemplate,key:"templateHolder"},j.createElement(q,{className:e.templateTitle},"RESPONSE TEMPLATE"),j.createElement(Z,{classNames:W,allowAnswerBlock:!0,keypadMode:u,controlledKeypad:!0,showKeypad:r,latex:te(p)||"",onChange:this.onChange("expression"),onFocus:this.onFocus,onDone:this.onDone,maxResponseAreas:x,error:K})),K&&j.createElement("div",{className:e.errorText},K)),j.createElement("div",{className:e.flexContainer,style:{justifyContent:"flex-start"}},j.createElement("div",{className:e.title},"Define Correct Response"),h===D?V:null),j.createElement(G,{label:"Equation Editor",className:e.selectContainer},j.createElement(B,{className:e.select,onChange:this.onChange("equationEditor"),value:d},j.createElement(F,{value:"non-negative-integers"},"Numeric - Non-Negative Integers"),j.createElement(F,{value:"integers"},"Numeric - Integers"),j.createElement(F,{value:"decimals"},"Numeric - Decimals"),j.createElement(F,{value:"fractions"},"Numeric - Fractions"),j.createElement(F,{value:1},"Grade 1 - 2"),j.createElement(F,{value:3},"Grade 3 - 5"),j.createElement(F,{value:6},"Grade 6 - 7"),j.createElement(F,{value:8},"Grade 8 - HS"),j.createElement(F,{value:"geometry"},"Geometry"),j.createElement(F,{value:"advanced-algebra"},"Advanced Algebra"),j.createElement(F,{value:"statistics"},"Statistics"),j.createElement(F,{value:"item-authoring"},"Item Authoring"))),U.map(((e,t)=>j.createElement(N,{key:e.id,mode:d,response:e,defaultResponse:h===D,onResponseChange:this.onResponseChange,index:t,cIgnoreOrder:E,cAllowTrailingZeros:v,error:M&&M[t]}))),i&&j.createElement(G,{label:y.label,className:e.promptHolder},j.createElement(z,{className:e.prompt,markup:g||"",onChange:this.onChange("rationale"),imageSupport:n,nonEmpty:!1,error:k,toolbarOpts:l,pluginProps:O(Y([y,"optionalAccess",e=>e.inputConfiguration]),{...C,math:{controlledKeypadMode:!1}}),spellCheck:b,maxImageWidth:S&&S.rationale||P,maxImageHeight:w&&w.rationale||L,uploadSoundSupport:a,languageCharactersProps:[{language:"spanish"},{language:"special"}],mathMlOptions:T}),k&&j.createElement("div",{className:e.errorText},k)))}}ne.__initStatic();var ae=P((e=>({container:{display:"flex",flexDirection:"column"},templateTitle:{fontSize:"0.85rem"},title:{fontSize:"1.1rem"},addResponseButton:{border:`1px solid ${e.palette.grey.A100}`,float:"right",width:"150px"},flexContainer:{display:"flex",alignItems:"center",justifyContent:"space-between"},selectContainer:{flex:"initial",width:"40%",marginTop:2*e.spacing.unit,marginBottom:2*e.spacing.unit},responseTemplate:{display:"flex",flexDirection:"column"},responseEditor:{display:"flex",justifyContent:"center",width:"100%",maxWidth:"inherit",height:"auto",minHeight:"130px",textAlign:"left",padding:e.spacing.unit},promptHolder:{width:"100%",paddingTop:2*e.spacing.unit,marginBottom:2*e.spacing.unit},blockContainer:{margin:e.spacing.unit,display:"inline-flex",border:"2px solid grey"},blockContainerGeneric:{margin:e.spacing.unit/2},blockResponse:{fontFamily:"Roboto, Helvetica, Arial, sans-serif !important",flex:2,color:"grey",background:e.palette.grey.A100,fontSize:"0.8rem",padding:e.spacing.unit/2,display:"flex",alignItems:"center",justifyContent:"center",borderRight:"2px solid grey"},blockResponseGeneric:{borderRight:0},blockMath:{color:e.palette.grey[400],padding:e.spacing.unit/2,display:"flex",alignItems:"center",justifyContent:"center",flex:8,"& > .mq-math-mode":{"& > .mq-hasCursor":{"& > .mq-cursor":{display:"none"}}}},tooltip:{fontSize:e.typography.fontSize-2,whiteSpace:"pre-wrap"},errorText:{fontSize:e.typography.fontSize-2,color:e.palette.error.main,paddingTop:e.spacing.unit},advancedResponse:{marginBottom:2.5*e.spacing.unit}})))(ne);const oe=e,{withStyles:se}=a,ie=t,le=r,{FeedbackConfig:re}=p,{settings:ce}=p,{layout:pe}=p,{InputContainer:de}=p,ue=d;function me(e){let t,n=e[0],a=1;for(;a<e.length;){const o=e[a],s=e[a+1];if(a+=2,("optionalAccess"===o||"optionalCall"===o)&&null==n)return;"access"===o||"optionalAccess"===o?(t=n,n=s(n)):"call"!==o&&"optionalCall"!==o||(n=s(((...e)=>n.call(t,...e))),t=void 0)}return n}const he=le("@pie-element:math-inline:configure"),{Panel:ge,toggle:be,radio:_e,dropdown:Ce}=ce;class ye extends oe.Component{constructor(...e){super(...e),ye.prototype.__init.call(this),ye.prototype.__init2.call(this),ye.prototype.__init3.call(this)}static __initStatic(){this.propTypes={onModelChanged:ie.func,onConfigurationChanged:ie.func,classes:ie.object,model:ie.object.isRequired,configuration:ie.object.isRequired,imageSupport:ie.object,uploadSoundSupport:ie.object}}__init(){this.onChange=e=>{this.props.onModelChanged(e)}}__init2(){this.changeTeacherInstructions=e=>{this.props.onModelChanged({...this.props.model,teacherInstructions:e})}}__init3(){this.onFeedbackChange=e=>{const{model:t,onModelChanged:n}=this.props;t.feedback=e,n(t)}}render(){const{classes:e,model:t,imageSupport:n,onModelChanged:a,configuration:o,onConfigurationChanged:s,uploadSoundSupport:i}=this.props,{allowTrailingZeros:l={},baseInputConfiguration:r={},contentDimensions:c={},feedback:p={},ignoreOrder:d={},maxImageWidth:u={},maxImageHeight:m={},prompt:h={},rationale:g={},responseType:b={},scoringType:_={},settingsPanelDisabled:C,spellCheck:y={},studentInstructions:f={},teacherInstructions:E={},withRubric:v={},mathMlOptions:x={},language:S={},languageChoices:w={}}=o||{},{errors:T={},extraCSSRules:I,feedbackEnabled:A,promptEnabled:k,rationaleEnabled:N,spellCheckEnabled:j,teacherInstructionsEnabled:M,toolbarEditorPosition:K}=t||{},{teacherInstructions:P}=T;he("[render] model",t);const q={position:"top"===K?"top":"bottom"},B=u&&u.prompt,F=m&&m.prompt,H={responseType:b.settings&&_e(b.label,[D,R]),feedbackEnabled:p.settings&&be(p.label),promptEnabled:h.settings&&be(h.label),"language.enabled":S.settings&&be(S.label,!0),language:S.settings&&S.enabled&&Ce(w.label,w.options)},L={teacherInstructionsEnabled:E.settings&&be(E.label),studentInstructionsEnabled:f.settings&&be(f.label),rationaleEnabled:g.settings&&be(g.label),spellCheckEnabled:y.settings&&be(y.label),scoringType:_.settings&&_e(_.label,["auto","rubric"]),"ignoreOrder.enabled":d.settings&&be(d.label),"allowTrailingZeros.enabled":l.settings&&be(l.label),rubricEnabled:me([v,"optionalAccess",e=>e.settings])&&be(me([v,"optionalAccess",e=>e.label]))};return oe.createElement(pe.ConfigLayout,{extraCSSRules:I,dimensions:c,hideSettings:C,settings:oe.createElement(ge,{model:t,configuration:o,onChangeModel:e=>a(e),onChangeConfiguration:e=>s(e),groups:{Settings:H,Properties:L}})},M&&oe.createElement(de,{label:E.label,className:e.promptHolder},oe.createElement(ue,{className:e.prompt,markup:t.teacherInstructions||"",onChange:this.changeTeacherInstructions,imageSupport:n,nonEmpty:!1,error:P,toolbarOpts:q,pluginProps:O(me([E,"optionalAccess",e=>e.inputConfiguration]),r),spellCheck:j,maxImageWidth:u&&u.teacherInstructions||B,maxImageHeight:m&&m.teacherInstructions||F,uploadSoundSupport:i,languageCharactersProps:[{language:"spanish"},{language:"special"}],mathMlOptions:x}),P&&oe.createElement("div",{className:e.errorText},P)),oe.createElement(ae,{imageSupport:n,uploadSoundSupport:i,model:t,configuration:o,onChange:this.onChange,rationaleEnabled:N,promptEnabled:k,toolbarOpts:q,spellCheck:j}),A&&oe.createElement(re,{feedback:t.feedback,onChange:this.onFeedbackChange,toolbarOpts:q}))}}ye.__initStatic();var fe=se((e=>({promptHolder:{width:"100%",paddingTop:2*e.spacing.unit,marginBottom:2*e.spacing.unit},errorText:{fontSize:e.typography.fontSize-2,color:e.palette.error.main,paddingTop:e.spacing.unit}})))(ye),Ee={};Object.defineProperty(Ee,"__esModule",{value:!0});class ve extends CustomEvent{constructor(e,t=!1){super(ve.TYPE,{bubbles:!0,detail:{update:e,reset:t}}),this.update=e,this.reset=t}}ve.TYPE="model.updated";var xe=Ee.ModelUpdatedEvent=ve;class Se extends CustomEvent{constructor(e,t){super(Se.TYPE,{bubbles:!0,detail:{src:e,done:t}}),this.src=e,this.done=t}}Se.TYPE="delete.image";var we=Ee.DeleteImageEvent=Se;class Te extends CustomEvent{constructor(e){super(Te.TYPE,{bubbles:!0,detail:e}),this.handler=e}}Te.TYPE="insert.image";var Ie=Ee.InsertImageEvent=Te;class Ae extends CustomEvent{constructor(e,t){super(Ae.TYPE,{bubbles:!0,detail:{src:e,done:t}}),this.src=e,this.done=t}}Ae.TYPE="delete.sound";var ke=Ee.DeleteSoundEvent=Ae;class Ne extends CustomEvent{constructor(e){super(Ne.TYPE,{bubbles:!0,detail:e}),this.handler=e}}Ne.TYPE="insert.sound";var Re=Ee.InsertSoundEvent=Ne,De={allowTrailingZerosDefault:!1,customKeys:[],equationEditor:"8",expression:"",feedback:{correct:{default:"Correct",type:"none"},incorrect:{default:"Incorrect",type:"none"},partial:{default:"Nearly",type:"none"}},feedbackEnabled:!1,ignoreOrderDefault:!1,partialScoring:!0,prompt:"",promptEnabled:!0,rationale:"",rationaleEnabled:!0,responseType:R,responses:[],scoringType:"auto",studentInstructionsEnabled:!0,teacherInstructions:"",teacherInstructionsEnabled:!0,toolbarEditorPosition:"bottom",validationDefault:"literal"},Oe={baseInputConfiguration:{audio:{disabled:!1},video:{disabled:!1},image:{disabled:!1},textAlign:{disabled:!0},showParagraphs:{disabled:!1},separateParagraphs:{disabled:!0}},prompt:{settings:!0,label:"Prompt",inputConfiguration:{audio:{disabled:!1},video:{disabled:!1},image:{disabled:!1}},required:!1},feedback:{settings:!0,label:"Feedback"},responseType:{settings:!0,label:"Response type"},rationale:{settings:!0,label:"Rationale",inputConfiguration:{audio:{disabled:!1},video:{disabled:!1},image:{disabled:!1}},required:!1},settingsPanelDisabled:!1,spellCheck:{label:"Spellcheck",settings:!1,enabled:!0},scoringType:{settings:!1,label:"Scoring Type"},studentInstructions:{settings:!1,label:"Student Instructions"},teacherInstructions:{settings:!0,label:"Teacher Instructions",inputConfiguration:{audio:{disabled:!1},video:{disabled:!1},image:{disabled:!1}},required:!1},partialScoring:{settings:!1,label:"Allow Partial Scoring"},ignoreOrder:{settings:!1,label:"Ignore Order",enabled:!0},allowTrailingZeros:{settings:!1,label:"Allow Trailing Zeros",enabled:!0},maxImageWidth:{teacherInstructions:300,prompt:300,rationale:300},maxImageHeight:{teacherInstructions:300,prompt:300,rationale:300},withRubric:{settings:!1,label:"Add Rubric"},mathMlOptions:{mmlOutput:!1,mmlEditing:!1},language:{settings:!1,label:"Specify Language",enabled:!1},languageChoices:{label:"Language Choices",options:[]}};const je=e,Me=c,{isEmpty:Ke}=i;function Pe(e){let t,n=e[0],a=1;for(;a<e.length;){const o=e[a],s=e[a+1];if(a+=2,("optionalAccess"===o||"optionalCall"===o)&&null==n)return;"access"===o||"optionalAccess"===o?(t=n,n=s(n)):"call"!==o&&"optionalCall"!==o||(n=s(((...e)=>n.call(t,...e))),t=void 0)}return n}const qe=r("pie-elements:math-inline:configure");class Be extends HTMLElement{static __initStatic(){this.createDefaultModel=(e={})=>(Ke(e.responses)||(e.responses=e.responses.map((e=>({...e,validation:e.validation||De.validationDefault,allowTrailingZeros:e.allowTrailingZeros||De.allowTrailingZerosDefault,ignoreOrder:e.ignoreOrder||De.ignoreOrderDefault||!1})))),{...De,...e})}constructor(){super(),this._model=Be.createDefaultModel(),this._configuration=Oe}set model(e){this._model=Be.createDefaultModel(e),this._render()}set configuration(e){const t={...Oe,...e};this._configuration=t,Pe([t,"optionalAccess",e=>e.language,"optionalAccess",e=>e.enabled])?Pe([t,"optionalAccess",e=>e.languageChoices,"optionalAccess",e=>e.options,"optionalAccess",e=>e.length])&&(this._model.language=Pe([t,"optionalAccess",e=>e.languageChoices,"access",e=>e.options,"access",e=>e[0],"access",e=>e.value])):t.language.settings&&this._model.language?(this._configuration.language.enabled=!0,this._configuration.languageChoices.options&&this._configuration.languageChoices.options.length||(this._configuration.languageChoices.options=[]),this._configuration.languageChoices.options.find((e=>e.value===this._model.language))||this._configuration.languageChoices.options.push({value:this._model.language,label:this._model.language})):delete this._model.language,this._render()}onModelChanged(e){this._model=e,qe("[onModelChanged]: ",this._model),this._render(),this.dispatchEvent(new xe(this._model))}onConfigurationChanged(e){this._configuration=e,this._model&&this.onModelChanged(this._model),this._render()}insertImage(e){this.dispatchEvent(new Ie(e))}onDeleteImage(e,t){this.dispatchEvent(new we(e,t))}insertSound(e){this.dispatchEvent(new Re(e))}onDeleteSound(e,t){this.dispatchEvent(new ke(e,t))}_render(){if(this._model){const e=je.createElement(fe,{onModelChanged:this.onModelChanged.bind(this),onConfigurationChanged:this.onConfigurationChanged.bind(this),model:this._model,configuration:this._configuration,imageSupport:{add:this.insertImage.bind(this),delete:this.onDeleteImage.bind(this)},uploadSoundSupport:{add:this.insertSound.bind(this),delete:this.onDeleteSound.bind(this)}});Me.render(e,this)}}}Be.__initStatic();export{Be as default};