@khanacademy/perseus-score 3.0.0 → 4.0.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.
@@ -0,0 +1,2281 @@
1
+ import _extends from '@babel/runtime/helpers/extends';
2
+ import * as KAS from '@khanacademy/kas';
3
+ import { KhanMath, geometry, angles, coefficients, number } from '@khanacademy/kmath';
4
+ import { PerseusError, Errors, getDecimalSeparator, GrapherUtil, approximateDeepEqual, approximateEqual, deepClone, getMatrixSize, getWidgetIdsFromContent, getUpgradedWidgetOptions } from '@khanacademy/perseus-core';
5
+ import _ from 'underscore';
6
+
7
+ const MISSING_PERCENT_ERROR = "MISSING_PERCENT_ERROR";
8
+ const NEEDS_TO_BE_SIMPLIFIED_ERROR = "NEEDS_TO_BE_SIMPLIFIED_ERROR";
9
+ const APPROXIMATED_PI_ERROR = "APPROXIMATED_PI_ERROR";
10
+ const EXTRA_SYMBOLS_ERROR = "EXTRA_SYMBOLS_ERROR";
11
+ const WRONG_CASE_ERROR = "WRONG_CASE_ERROR";
12
+ const WRONG_LETTER_ERROR = "WRONG_LETTER_ERROR";
13
+ const MULTIPLICATION_SIGN_ERROR = "MULTIPLICATION_SIGN_ERROR";
14
+ const INVALID_SELECTION_ERROR = "INVALID_SELECTION_ERROR";
15
+ const CHOOSE_CORRECT_NUM_ERROR = "CHOOSE_CORRECT_NUM_ERROR";
16
+ const NOT_NONE_ABOVE_ERROR = "NOT_NONE_ABOVE_ERROR";
17
+ const FILL_ALL_CELLS_ERROR = "FILL_ALL_CELLS_ERROR";
18
+ const ErrorCodes = {
19
+ MISSING_PERCENT_ERROR,
20
+ NEEDS_TO_BE_SIMPLIFIED_ERROR,
21
+ APPROXIMATED_PI_ERROR,
22
+ EXTRA_SYMBOLS_ERROR,
23
+ WRONG_CASE_ERROR,
24
+ WRONG_LETTER_ERROR,
25
+ MULTIPLICATION_SIGN_ERROR,
26
+ INVALID_SELECTION_ERROR,
27
+ CHOOSE_CORRECT_NUM_ERROR,
28
+ NOT_NONE_ABOVE_ERROR,
29
+ FILL_ALL_CELLS_ERROR
30
+ };
31
+
32
+ const MAXERROR_EPSILON = Math.pow(2, -42);
33
+
34
+ // TOOD(kevinb): Figure out how this relates to KEScore in
35
+ // perseus-all-package/types.js and see if there's a way to
36
+ // unify these types.
37
+
38
+ /**
39
+ * Answer types
40
+ *
41
+ * Utility for creating answerable questions displayed in exercises
42
+ *
43
+ * Different answer types produce different kinds of input displays, and do
44
+ * different kinds of checking on the solutions.
45
+ *
46
+ * Each of the objects contain two functions, setup and createValidator.
47
+ *
48
+ * The setup function takes a solutionarea and solution, and performs setup
49
+ * within the solutionarea, and then returns an object which contains:
50
+ *
51
+ * answer: a function which, when called, will retrieve the current answer from
52
+ * the solutionarea, which can then be validated using the validator
53
+ * function
54
+ * validator: a function returned from the createValidator function (defined
55
+ * below)
56
+ * solution: the correct answer to the problem
57
+ * showGuess: a function which, when given a guess, shows the guess within the
58
+ * provided solutionarea
59
+ * showGuessCustom: a function which displays parts of a guess that are not
60
+ * within the solutionarea; currently only used for custom
61
+ * answers
62
+ *
63
+ * The createValidator function only takes a solution, and it returns a
64
+ * function which can be used to validate an answer.
65
+ *
66
+ * The resulting validator function returns:
67
+ * - true: if the answer is fully correct
68
+ * - false: if the answer is incorrect
69
+ * - "" (the empty string): if no answer has been provided (e.g. the answer box
70
+ * is left unfilled)
71
+ * - a string: if there is some slight error
72
+ *
73
+ * In most cases, setup and createValidator don't really need the solution DOM
74
+ * element so we have setupFunctional and createValidatorFunctional for them
75
+ * which take only $solution.text() and $solution.data(). This makes it easier
76
+ * to reuse specific answer types.
77
+ *
78
+ * TODO(alpert): Think of a less-absurd name for createValidatorFunctional.
79
+ *
80
+ */
81
+ const KhanAnswerTypes = {
82
+ /*
83
+ * predicate answer type
84
+ *
85
+ * performs simple predicate-based checking of a numeric solution, with
86
+ * different kinds of number formats
87
+ *
88
+ * Uses the data-forms option on the solution to choose which number formats
89
+ * are acceptable. Available data-forms:
90
+ *
91
+ * - integer: 3
92
+ * - proper: 3/5
93
+ * - improper: 5/3
94
+ * - pi: 3 pi
95
+ * - log: log(5)
96
+ * - percent: 15%
97
+ * - mixed: 1 1/3
98
+ * - decimal: 1.7
99
+ *
100
+ * The solution should be a predicate of the form:
101
+ *
102
+ * function(guess, maxError) {
103
+ * return abs(guess - 3) < maxError;
104
+ * }
105
+ *
106
+ */
107
+ predicate: {
108
+ defaultForms: "integer, proper, improper, mixed, decimal",
109
+ createValidatorFunctional: function (predicate, options) {
110
+ // Extract the options from the given solution object
111
+ options = _.extend({
112
+ simplify: "required",
113
+ ratio: false,
114
+ forms: KhanAnswerTypes.predicate.defaultForms
115
+ }, options);
116
+ let acceptableForms;
117
+ // this is maintaining backwards compatibility
118
+ // TODO(merlob) fix all places that depend on this, then delete
119
+ if (!_.isArray(options.forms)) {
120
+ acceptableForms = options.forms.split(/\s*,\s*/);
121
+ } else {
122
+ acceptableForms = options.forms;
123
+ }
124
+
125
+ // TODO(jack): remove options.inexact in favor of options.maxError
126
+ if (options.inexact === undefined) {
127
+ // If we aren't allowing inexact, ensure that we don't have a
128
+ // large maxError as well.
129
+ options.maxError = 0;
130
+ }
131
+ // Allow a small tolerance on maxError, to avoid numerical
132
+ // representation issues (2.3 should be correct for a solution of
133
+ // 2.45 with maxError=0.15).
134
+ options.maxError = +options.maxError + MAXERROR_EPSILON;
135
+
136
+ // If percent is an acceptable form, make sure it's the last one
137
+ // in the list so we don't prematurely complain about not having
138
+ // a percent sign when the user entered the correct answer in a
139
+ // different form (such as a decimal or fraction)
140
+ if (_.contains(acceptableForms, "percent")) {
141
+ acceptableForms = _.without(acceptableForms, "percent");
142
+ acceptableForms.push("percent");
143
+ }
144
+
145
+ // Take text looking like a fraction, and turn it into a number
146
+ const fractionTransformer = function fractionTransformer(text) {
147
+ text = text
148
+ // Replace unicode minus sign with hyphen
149
+ .replace(/\u2212/, "-")
150
+ // Remove space after +, -
151
+ .replace(/([+-])\s+/g, "$1")
152
+ // Remove leading/trailing whitespace
153
+ .replace(/(^\s*)|(\s*$)/gi, "");
154
+
155
+ // Extract numerator and denominator
156
+ const match = text.match(/^([+-]?\d+)\s*\/\s*([+-]?\d+)$/);
157
+ // Fractions are represented as "-\frac{numerator}{denominator}"
158
+ // in Mobile device input instead of "numerator/denominator" as
159
+ // in web-browser.
160
+ const mobileDeviceMatch = text.match(/^([+-]?)\\frac\{([+-]?\d+)\}\{([+-]?\d+)\}$/);
161
+ const parsedInt = parseInt(text, 10);
162
+ if (match || mobileDeviceMatch) {
163
+ let num;
164
+ let denom;
165
+ let simplified = true;
166
+ if (match) {
167
+ num = parseFloat(match[1]);
168
+ denom = parseFloat(match[2]);
169
+ } else {
170
+ num = parseFloat(mobileDeviceMatch[2]);
171
+ if (mobileDeviceMatch[1] === "-") {
172
+ if (num < 0) {
173
+ simplified = false;
174
+ }
175
+ num = -num;
176
+ }
177
+ denom = parseFloat(mobileDeviceMatch[3]);
178
+ }
179
+ simplified = simplified && denom > 0 && (options.ratio || denom !== 1) && KhanMath.getGCD(num, denom) === 1;
180
+ return [{
181
+ value: num / denom,
182
+ exact: simplified
183
+ }];
184
+ }
185
+ if (!isNaN(parsedInt) && "" + parsedInt === text) {
186
+ return [{
187
+ value: parsedInt,
188
+ exact: true
189
+ }];
190
+ }
191
+ return [];
192
+ };
193
+
194
+ /*
195
+ * Different forms of numbers
196
+ *
197
+ * Each function returns a list of objects of the form:
198
+ *
199
+ * {
200
+ * value: numerical value,
201
+ * exact: true/false
202
+ * }
203
+ */
204
+ const forms = {
205
+ // integer, which is encompassed by decimal
206
+ integer: function (text) {
207
+ // Compare the decimal form to the decimal form rounded to
208
+ // an integer. Only accept if the user actually entered an
209
+ // integer.
210
+ const decimal = forms.decimal(text);
211
+ const rounded = forms.decimal(text, 1);
212
+ if (decimal[0].value != null && decimal[0].value === rounded[0].value || decimal[1].value != null && decimal[1].value === rounded[1].value) {
213
+ return decimal;
214
+ }
215
+ return [];
216
+ },
217
+ // A proper fraction
218
+ proper: function (text) {
219
+ const transformed = fractionTransformer(text);
220
+ return transformed.flatMap(o => {
221
+ // All fractions that are less than 1
222
+ if (Math.abs(o.value) < 1) {
223
+ return [o];
224
+ }
225
+ return [];
226
+ });
227
+ },
228
+ // an improper fraction
229
+ improper: function (text) {
230
+ // As our answer keys are always in simplest form, we need
231
+ // to check for the existence of a fraction in the input before
232
+ // validating the answer. If no fraction is found, we consider
233
+ // the answer to be incorrect.
234
+ const fractionExists = text.includes("/") || text.match(/\\(d?frac)/);
235
+ if (!fractionExists) {
236
+ return [];
237
+ }
238
+ const transformed = fractionTransformer(text);
239
+ return transformed.flatMap(o => {
240
+ // All fractions that are greater than 1
241
+ if (Math.abs(o.value) >= 1) {
242
+ return [o];
243
+ }
244
+ return [];
245
+ });
246
+ },
247
+ // pi-like numbers
248
+ pi: function (text) {
249
+ let match;
250
+ let possibilities = [];
251
+
252
+ // Replace unicode minus sign with hyphen
253
+ text = text.replace(/\u2212/, "-");
254
+
255
+ // - pi
256
+ // (Note: we also support \pi (for TeX), p, tau (and \tau,
257
+ // and t), pau.)
258
+ if (match = text.match(/^([+-]?)\s*(\\?pi|p|\u03c0|\\?tau|t|\u03c4|pau)$/i)) {
259
+ possibilities = [{
260
+ value: parseFloat(match[1] + "1"),
261
+ exact: true
262
+ }];
263
+
264
+ // 5 / 6 pi
265
+ } else if (match = text.match(/^([+-]?\s*\d+\s*(?:\/\s*[+-]?\s*\d+)?)\s*\*?\s*(\\?pi|p|\u03c0|\\?tau|t|\u03c4|pau)$/i)) {
266
+ possibilities = fractionTransformer(match[1]);
267
+
268
+ // 4 5 / 6 pi
269
+ } else if (match = text.match(/^([+-]?)\s*(\d+)\s*([+-]?\d+)\s*\/\s*([+-]?\d+)\s*\*?\s*(\\?pi|p|\u03c0|\\?tau|t|\u03c4|pau)$/i)) {
270
+ const sign = parseFloat(match[1] + "1");
271
+ const integ = parseFloat(match[2]);
272
+ const num = parseFloat(match[3]);
273
+ const denom = parseFloat(match[4]);
274
+ const simplified = num < denom && KhanMath.getGCD(num, denom) === 1;
275
+ possibilities = [{
276
+ value: sign * (integ + num / denom),
277
+ exact: simplified
278
+ }];
279
+
280
+ // 5 pi / 6
281
+ } else if (match = text.match(/^([+-]?\s*\d+)\s*\*?\s*(\\?pi|p|\u03c0|\\?tau|t|\u03c4|pau)\s*(?:\/\s*([+-]?\s*\d+))?$/i)) {
282
+ possibilities = fractionTransformer(match[1] + "/" + match[3]);
283
+
284
+ // - pi / 4
285
+ } else if (match = text.match(/^([+-]?)\s*\*?\s*(\\?pi|p|\u03c0|\\?tau|t|\u03c4|pau)\s*(?:\/\s*([+-]?\d+))?$/i)) {
286
+ possibilities = fractionTransformer(match[1] + "1/" + match[3]);
287
+
288
+ // 0
289
+ } else if (text === "0") {
290
+ possibilities = [{
291
+ value: 0,
292
+ exact: true
293
+ }];
294
+
295
+ // 0.5 pi (fallback)
296
+ } else if (match = text.match(/^(.+)\s*\*?\s*(\\?pi|p|\u03c0|\\?tau|t|\u03c4|pau)$/i)) {
297
+ possibilities = forms.decimal(match[1]);
298
+ } else {
299
+ possibilities = _.reduce(KhanAnswerTypes.predicate.defaultForms.split(/\s*,\s*/), function (memo, form) {
300
+ return memo.concat(forms[form](text));
301
+ }, []);
302
+
303
+ // If the answer is a floating point number that's
304
+ // near a multiple of pi, mark is as being possibly
305
+ // an approximation of pi. We actually check if
306
+ // it's a plausible approximation of pi/12, since
307
+ // sometimes the correct answer is like pi/3 or pi/4.
308
+ // We also say it's a pi-approximation if it involves
309
+ // x/7 (since 22/7 is an approximation of pi.)
310
+ // Never mark an integer as being an approximation
311
+ // of pi.
312
+ let approximatesPi = false;
313
+ const number = parseFloat(text);
314
+ if (!isNaN(number) && number !== parseInt(text)) {
315
+ const piMult = Math.PI / 12;
316
+ const roundedNumber = piMult * Math.round(number / piMult);
317
+ if (Math.abs(number - roundedNumber) < 0.01) {
318
+ approximatesPi = true;
319
+ }
320
+ } else if (text.match(/\/\s*7/)) {
321
+ approximatesPi = true;
322
+ }
323
+ if (approximatesPi) {
324
+ _.each(possibilities, function (possibility) {
325
+ possibility.piApprox = true;
326
+ });
327
+ }
328
+ return possibilities;
329
+ }
330
+ let multiplier = Math.PI;
331
+ if (text.match(/\\?tau|t|\u03c4/)) {
332
+ multiplier = Math.PI * 2;
333
+ }
334
+
335
+ // We're taking an early stand along side xkcd in the
336
+ // inevitable ti vs. pau debate... http://xkcd.com/1292
337
+ if (text.match(/pau/)) {
338
+ multiplier = Math.PI * 1.5;
339
+ }
340
+ possibilities.forEach(possibility => {
341
+ possibility.value *= multiplier;
342
+ });
343
+ return possibilities;
344
+ },
345
+ // Converts '' to 1 and '-' to -1 so you can write "[___] x"
346
+ // and accept sane things
347
+ coefficient: function (text) {
348
+ let possibilities = [];
349
+
350
+ // Replace unicode minus sign with hyphen
351
+ text = text.replace(/\u2212/, "-");
352
+ if (text === "") {
353
+ possibilities = [{
354
+ value: 1,
355
+ exact: true
356
+ }];
357
+ } else if (text === "-") {
358
+ possibilities = [{
359
+ value: -1,
360
+ exact: true
361
+ }];
362
+ }
363
+ return possibilities;
364
+ },
365
+ // simple log(c) form
366
+ log: function (text) {
367
+ let match;
368
+ let possibilities = [];
369
+
370
+ // Replace unicode minus sign with hyphen
371
+ text = text.replace(/\u2212/, "-");
372
+ text = text.replace(/[ \(\)]/g, "");
373
+ if (match = text.match(/^log\s*(\S+)\s*$/i)) {
374
+ // @ts-expect-error - TS2322 - Type '{ value: number | undefined; exact: boolean; }[]' is not assignable to type 'never[]'.
375
+ possibilities = forms.decimal(match[1]);
376
+ } else if (text === "0") {
377
+ // @ts-expect-error - TS2322 - Type 'number' is not assignable to type 'never'. | TS2322 - Type 'boolean' is not assignable to type 'never'.
378
+ possibilities = [{
379
+ value: 0,
380
+ exact: true
381
+ }];
382
+ }
383
+ return possibilities;
384
+ },
385
+ // Numbers with percent signs
386
+ percent: function (text) {
387
+ text = String(text).trim();
388
+ // store whether or not there is a percent sign
389
+ let hasPercentSign = false;
390
+ if (text.indexOf("%") === text.length - 1) {
391
+ text = text.substring(0, text.length - 1).trim();
392
+ hasPercentSign = true;
393
+ }
394
+ const transformed = forms.decimal(text);
395
+ transformed.forEach(t => {
396
+ t.exact = hasPercentSign;
397
+ // @ts-expect-error - TS2532 - Object is possibly 'undefined'.
398
+ t.value = t.value / 100;
399
+ });
400
+ return transformed;
401
+ },
402
+ // Mixed numbers, like 1 3/4
403
+ mixed: function (text) {
404
+ const match = text
405
+ // Replace unicode minus sign with hyphen
406
+ .replace(/\u2212/, "-")
407
+ // Remove space after +, -
408
+ .replace(/([+-])\s+/g, "$1")
409
+ // Extract integer, numerator and denominator
410
+ .match(/^([+-]?)(\d+)\s+(\d+)\s*\/\s*(\d+)$/);
411
+ if (match) {
412
+ const sign = parseFloat(match[1] + "1");
413
+ const integ = parseFloat(match[2]);
414
+ const num = parseFloat(match[3]);
415
+ const denom = parseFloat(match[4]);
416
+ const simplified = num < denom && KhanMath.getGCD(num, denom) === 1;
417
+ return [{
418
+ value: sign * (integ + num / denom),
419
+ exact: simplified
420
+ }];
421
+ }
422
+ return [];
423
+ },
424
+ // Decimal numbers -- compare entered text rounded to
425
+ // 'precision' Reciprical of the precision against the correct
426
+ // answer. We round to 1/1e10 by default, which is healthily
427
+ // less than machine epsilon but should be more than any real
428
+ // decimal answer would use. (The 'integer' answer type uses
429
+ // precision == 1.)
430
+ decimal: function (text, precision = 1e10) {
431
+ const normal = function normal(text) {
432
+ text = String(text).trim();
433
+ const match = text
434
+ // Replace unicode minus sign with hyphen
435
+ .replace(/\u2212/, "-")
436
+ // Remove space after +, -
437
+ .replace(/([+-])\s+/g, "$1")
438
+ // Extract integer, numerator and denominator. If
439
+ // commas or spaces are used, they must be in the
440
+ // "correct" places
441
+ .match(/^([+-]?(?:\d{1,3}(?:[, ]?\d{3})*\.?|\d{0,3}(?:[, ]?\d{3})*\.(?:\d{3}[, ]?)*\d{1,3}))$/);
442
+
443
+ // You can't start a number with `0,`, to prevent us
444
+ // interpeting '0.342' as correct for '342'
445
+ const badLeadingZero = text.match(/^0[0,]*,/);
446
+ if (match && !badLeadingZero) {
447
+ let x = parseFloat(match[1].replace(/[, ]/g, ""));
448
+ if (options.inexact === undefined) {
449
+ x = Math.round(x * precision) / precision;
450
+ }
451
+ return x;
452
+ }
453
+ };
454
+ const commas = function commas(text) {
455
+ text = text.replace(/([\.,])/g, function (_, c) {
456
+ return c === "." ? "," : ".";
457
+ });
458
+ return normal(text);
459
+ };
460
+ return [{
461
+ value: normal(text),
462
+ exact: true
463
+ }, {
464
+ value: commas(text),
465
+ exact: true
466
+ }];
467
+ }
468
+ };
469
+
470
+ // validator function
471
+ return function (guess) {
472
+ // The fallback variable is used in place of the answer, if no
473
+ // answer is provided (i.e. the field is left blank)
474
+ const fallback = options.fallback != null ? "" + options.fallback : "";
475
+ guess = String(guess).trim() || fallback;
476
+ const score = {
477
+ empty: guess === "",
478
+ correct: false,
479
+ message: null,
480
+ guess: guess
481
+ };
482
+
483
+ // iterate over all the acceptable forms, and if one of the
484
+ // answers is correct, return true
485
+ acceptableForms.forEach(form => {
486
+ const transformed = forms[form](guess);
487
+ for (let j = 0, l = transformed.length; j < l; j++) {
488
+ const val = transformed[j].value;
489
+ const exact = transformed[j].exact;
490
+ const piApprox = transformed[j].piApprox;
491
+ // If a string was returned, and it exactly matches,
492
+ // return true
493
+ if (predicate(val, options.maxError)) {
494
+ // If the exact correct number was returned,
495
+ // return true
496
+ if (exact || options.simplify === "optional") {
497
+ score.correct = true;
498
+ score.message = options.message || null;
499
+ // If the answer is correct, don't say it's
500
+ // empty. This happens, for example, with the
501
+ // coefficient type where guess === "" but is
502
+ // interpreted as "1" which is correct.
503
+ score.empty = false;
504
+ } else if (form === "percent") {
505
+ // Otherwise, an error was returned
506
+ score.empty = true;
507
+ score.message = ErrorCodes.MISSING_PERCENT_ERROR;
508
+ } else {
509
+ if (options.simplify !== "enforced") {
510
+ score.empty = true;
511
+ }
512
+ score.message = ErrorCodes.NEEDS_TO_BE_SIMPLIFIED_ERROR;
513
+ }
514
+ // The return false below stops the looping of the
515
+ // callback since predicate check succeeded.
516
+ // No more forms to look to verify the user guess.
517
+ return false;
518
+ }
519
+ if (piApprox && predicate(val, Math.abs(val * 0.001))) {
520
+ score.empty = true;
521
+ score.message = ErrorCodes.APPROXIMATED_PI_ERROR;
522
+ }
523
+ }
524
+ });
525
+ if (score.correct === false) {
526
+ let interpretedGuess = false;
527
+ _.each(forms, function (form) {
528
+ const anyAreNaN = _.any(form(guess), function (t) {
529
+ return t.value != null && !_.isNaN(t.value);
530
+ });
531
+ if (anyAreNaN) {
532
+ interpretedGuess = true;
533
+ }
534
+ });
535
+ if (!interpretedGuess) {
536
+ score.empty = true;
537
+ score.message = ErrorCodes.EXTRA_SYMBOLS_ERROR;
538
+ return score;
539
+ }
540
+ }
541
+ return score;
542
+ };
543
+ }
544
+ },
545
+ /*
546
+ * number answer type
547
+ *
548
+ * wraps the predicate answer type to performs simple number-based checking
549
+ * of a solution
550
+ */
551
+ number: {
552
+ convertToPredicate: function (correctAnswer, options) {
553
+ const correctFloat = parseFloat(correctAnswer);
554
+ return [function (guess, maxError) {
555
+ return Math.abs(guess - correctFloat) < maxError;
556
+ }, _extends({}, options, {
557
+ type: "predicate"
558
+ })];
559
+ },
560
+ createValidatorFunctional: function (correctAnswer, options) {
561
+ return KhanAnswerTypes.predicate.createValidatorFunctional(...KhanAnswerTypes.number.convertToPredicate(correctAnswer, options));
562
+ }
563
+ },
564
+ /*
565
+ * The expression answer type parses a given expression or equation
566
+ * and semantically compares it to the solution. In addition, instant
567
+ * feedback is provided by rendering the last answer that fully parsed.
568
+ *
569
+ * Parsing options:
570
+ * functions (e.g. data-functions="f g h")
571
+ * A space or comma separated list of single-letter variables that
572
+ * should be interpreted as functions. Case sensitive. "e" and "i"
573
+ * are reserved.
574
+ *
575
+ * no functions specified: f(x+y) == fx + fy
576
+ * with "f" as a function: f(x+y) != fx + fy
577
+ *
578
+ * Comparison options:
579
+ * same-form (e.g. data-same-form)
580
+ * If present, the answer must match the solution's structure in
581
+ * addition to evaluating the same. Commutativity and excess negation
582
+ * are ignored, but all other changes will trigger a rejection. Useful
583
+ * for requiring a particular form of an equation, or if the answer
584
+ * must be factored.
585
+ *
586
+ * example question: Factor x^2 + x - 2
587
+ * example solution: (x-1)(x+2)
588
+ * accepted answers: (x-1)(x+2), (x+2)(x-1), ---(-x-2)(-1+x), etc.
589
+ * rejected answers: x^2+x-2, x*x+x-2, x(x+1)-2, (x-1)(x+2)^1, etc.
590
+ * rejection message: Your answer is not in the correct form
591
+ *
592
+ * simplify (e.g. data-simplify)
593
+ * If present, the answer must be fully expanded and simplified. Use
594
+ * carefully - simplification is hard and there may be bugs, or you
595
+ * might not agree on the definition of "simplified" used. You will
596
+ * get an error if the provided solution is not itself fully expanded
597
+ * and simplified.
598
+ *
599
+ * example question: Simplify ((n*x^5)^5) / (n^(-2)*x^2)^-3
600
+ * example solution: x^31 / n
601
+ * accepted answers: x^31 / n, x^31 / n^1, x^31 * n^(-1), etc.
602
+ * rejected answers: (x^25 * n^5) / (x^(-6) * n^6), etc.
603
+ * rejection message: Your answer is not fully expanded and simplified
604
+ *
605
+ * Rendering options:
606
+ * times (e.g. data-times)
607
+ * If present, explicit multiplication (such as between numbers) will
608
+ * be rendered with a cross/x symbol (TeX: \times) instead of the usual
609
+ * center dot (TeX: \cdot).
610
+ *
611
+ * normal rendering: 2 * 3^x -> 2 \cdot 3^{x}
612
+ * but with "times": 2 * 3^x -> 2 \times 3^{x}
613
+ */
614
+ expression: {
615
+ parseSolution: function (solutionString, options) {
616
+ let solution = KAS.parse(solutionString, options);
617
+ if (!solution.parsed) {
618
+ throw new PerseusError("The provided solution (" + solutionString + ") didn't parse.", Errors.InvalidInput);
619
+ } else if (options.simplified && !solution.expr.isSimplified()) {
620
+ throw new PerseusError("The provided solution (" + solutionString + ") isn't fully expanded and simplified.", Errors.InvalidInput);
621
+ } else {
622
+ solution = solution.expr;
623
+ }
624
+ return solution;
625
+ },
626
+ createValidatorFunctional: function (solution, options) {
627
+ return function (guess) {
628
+ const score = {
629
+ empty: false,
630
+ correct: false,
631
+ message: null,
632
+ guess: guess,
633
+ // Setting `ungraded` to true indicates that if the
634
+ // guess doesn't match any of the solutions, the guess
635
+ // shouldn't be marked as incorrect; instead, `message`
636
+ // should be shown to the user. This is different from
637
+ // setting `empty` to true, since the behavior of `empty`
638
+ // is that `message` only will be shown if the guess is
639
+ // graded as empty for every solution.
640
+ ungraded: false
641
+ };
642
+
643
+ // Don't bother parsing an empty input
644
+ if (!guess) {
645
+ // @ts-expect-error - TS2540 - Cannot assign to 'empty' because it is a read-only property.
646
+ score.empty = true;
647
+ return score;
648
+ }
649
+ const answer = KAS.parse(guess, options);
650
+
651
+ // An unsuccessful parse doesn't count as wrong
652
+ if (!answer.parsed) {
653
+ // @ts-expect-error - TS2540 - Cannot assign to 'empty' because it is a read-only property.
654
+ score.empty = true;
655
+ return score;
656
+ }
657
+
658
+ // Solution will need to be parsed again if we're creating
659
+ // this from a multiple question type
660
+ if (typeof solution === "string") {
661
+ solution = KhanAnswerTypes.expression.parseSolution(solution, options);
662
+ }
663
+ const result = KAS.compare(answer.expr, solution, options);
664
+ if (result.equal) {
665
+ // Correct answer
666
+ // @ts-expect-error - TS2540 - Cannot assign to 'correct' because it is a read-only property.
667
+ score.correct = true;
668
+ } else if (result.wrongVariableNames || result.wrongVariableCase) {
669
+ // We don't want to give people an error for getting the
670
+ // variable names or the variable case wrong.
671
+ // TODO(aasmund): This should ideally have been handled
672
+ // under the `result.message` condition, but the
673
+ // KAS messages currently aren't translatable.
674
+ // @ts-expect-error - TS2540 - Cannot assign to 'ungraded' because it is a read-only property.
675
+ score.ungraded = true;
676
+ // @ts-expect-error - TS2540 - Cannot assign to 'message' because it is a read-only property.
677
+ score.message = result.wrongVariableCase ? ErrorCodes.WRONG_CASE_ERROR : ErrorCodes.WRONG_LETTER_ERROR;
678
+ // Don't tell the use they're "almost there" in this case, that may not be true and isn't helpful.
679
+ // @ts-expect-error - TS2339 - Property 'suppressAlmostThere' does not exist on type '{ readonly empty: false; readonly correct: false; readonly message: string | null | undefined; readonly guess: any; readonly ungraded: false; }'.
680
+ score.suppressAlmostThere = true;
681
+ } else if (result.message) {
682
+ // Nearly correct answer
683
+ // TODO(aasmund): This message also isn't translatable;
684
+ // need to fix that in KAS
685
+ // @ts-expect-error - TS2540 - Cannot assign to 'message' because it is a read-only property.
686
+ score.message = result.message;
687
+ } else {
688
+ // Replace x with * and see if it would have been correct
689
+ // TODO(aasmund): I think this branch is effectively dead,
690
+ // because the replacement will only work in situations
691
+ // where the variables are wrong (except if the variable
692
+ // is x, in which case the replacement won't work either),
693
+ // which is handled by another branch. When we implement a
694
+ // more sophisticated variable check, revive this or
695
+ // remove it completely if it will never come into play.
696
+ const answerX = KAS.parse(guess.replace(/[xX]/g, "*"), options);
697
+ if (answerX.parsed) {
698
+ const resultX = KAS.compare(answerX.expr, solution, options);
699
+ if (resultX.equal) {
700
+ // @ts-expect-error - TS2540 - Cannot assign to 'ungraded' because it is a read-only property.
701
+ score.ungraded = true;
702
+ // @ts-expect-error - TS2540 - Cannot assign to 'message' because it is a read-only property.
703
+ score.message = ErrorCodes.MULTIPLICATION_SIGN_ERROR;
704
+ } else if (resultX.message) {
705
+ // TODO(aasmund): I18nize `score.message`
706
+ // @ts-expect-error - TS2540 - Cannot assign to 'message' because it is a read-only property.
707
+ score.message = resultX.message + " Also, I'm a computer. I only understand " + "multiplication if you use an " + "asterisk (*) as the multiplication " + "sign.";
708
+ }
709
+ }
710
+ }
711
+ return score;
712
+ };
713
+ }
714
+ }
715
+ };
716
+
717
+ function scoreCategorizer(userInput, rubric) {
718
+ let allCorrect = true;
719
+ rubric.values.forEach((value, i) => {
720
+ if (userInput.values[i] !== value) {
721
+ allCorrect = false;
722
+ }
723
+ });
724
+ return {
725
+ type: "points",
726
+ earned: allCorrect ? 1 : 0,
727
+ total: 1,
728
+ message: null
729
+ };
730
+ }
731
+
732
+ /**
733
+ * Checks userInput from the categorizer widget to see if the user has selected
734
+ * a category for each item.
735
+ * @param userInput - The user's input corresponding to an array of indices that
736
+ * represent the selected category for each row/item.
737
+ * @param validationData - An array of strings corresponding to each row/item
738
+ * @param strings - Used to provide a validation message
739
+ */
740
+ function validateCategorizer(userInput, validationData) {
741
+ const incomplete = validationData.items.some((_, i) => userInput.values[i] == null);
742
+ if (incomplete) {
743
+ return {
744
+ type: "invalid",
745
+ message: ErrorCodes.INVALID_SELECTION_ERROR
746
+ };
747
+ }
748
+ return null;
749
+ }
750
+
751
+ function scoreCSProgram(userInput) {
752
+ // The CS program can tell us whether it's correct or incorrect,
753
+ // and pass an optional message
754
+ if (userInput.status === "correct") {
755
+ return {
756
+ type: "points",
757
+ earned: 1,
758
+ total: 1,
759
+ message: userInput.message || null
760
+ };
761
+ }
762
+ if (userInput.status === "incorrect") {
763
+ return {
764
+ type: "points",
765
+ earned: 0,
766
+ total: 1,
767
+ message: userInput.message || null
768
+ };
769
+ }
770
+ return {
771
+ type: "invalid",
772
+ message: "Keep going, you're not there yet!"
773
+ };
774
+ }
775
+
776
+ function scoreDropdown(userInput, rubric) {
777
+ const correct = rubric.choices[userInput.value - 1].correct;
778
+ return {
779
+ type: "points",
780
+ earned: correct ? 1 : 0,
781
+ total: 1,
782
+ message: null
783
+ };
784
+ }
785
+
786
+ /**
787
+ * Checks if the user has selected an item from the dropdown before scoring.
788
+ * This is shown with a userInput value / index other than 0.
789
+ */
790
+ function validateDropdown(userInput) {
791
+ if (userInput.value === 0) {
792
+ return {
793
+ type: "invalid",
794
+ message: null
795
+ };
796
+ }
797
+ return null;
798
+ }
799
+
800
+ /* Content creators input a list of answers which are matched from top to
801
+ * bottom. The intent is that they can include spcific solutions which should
802
+ * be graded as correct or incorrect (or ungraded!) first, then get more
803
+ * general.
804
+ *
805
+ * We iterate through each answer, trying to match it with the user's input
806
+ * using the following angorithm:
807
+ * - Try to parse the user's input. If it doesn't parse then return "not
808
+ * graded".
809
+ * - For each answer:
810
+ * ~ Try to validate the user's input against the answer. The answer is
811
+ * expected to parse.
812
+ * ~ If the user's input validates (the validator judges it "correct"), we've
813
+ * matched and can stop considering answers.
814
+ * - If there were no matches or the matching answer is considered "ungraded",
815
+ * show the user an error. TODO(joel) - what error?
816
+ * - Otherwise, pass through the resulting points and message.
817
+ */
818
+ function scoreExpression(userInput, rubric, locale) {
819
+ const options = _.clone(rubric);
820
+ _.extend(options, {
821
+ decimal_separator: getDecimalSeparator(locale)
822
+ });
823
+ const createValidator = answer => {
824
+ // We give options to KAS.parse here because it is parsing the
825
+ // solution answer, not the student answer, and we don't want a
826
+ // solution to work if the student is using a different language
827
+ // (different from the content creation language, ie. English).
828
+ const expression = KAS.parse(answer.value, rubric);
829
+ // An answer may not be parsed if the expression was defined
830
+ // incorrectly. For example if the answer is using a symbol defined
831
+ // in the function variables list for the expression.
832
+ if (!expression.parsed) {
833
+ /* c8 ignore next */
834
+ throw new PerseusError("Unable to parse solution answer for expression", Errors.InvalidInput, {
835
+ metadata: {
836
+ rubric: JSON.stringify(rubric)
837
+ }
838
+ });
839
+ }
840
+ return KhanAnswerTypes.expression.createValidatorFunctional(expression.expr, _({}).extend(options, {
841
+ simplify: answer.simplify,
842
+ form: answer.form
843
+ }));
844
+ };
845
+
846
+ // Find the first answer form that matches the user's input and that
847
+ // is considered correct. Also, track whether the input is
848
+ // considered "empty" for all answer forms, and keep the validation
849
+ // result for the first answer form for which the user's input was
850
+ // considered "ungraded".
851
+ // (Terminology reminder: the answer forms are provided by the
852
+ // assessment items; they are not the user's input. Each one might
853
+ // represent a correct answer, an incorrect one (if the exercise
854
+ // creator has predicted certain common wrong answers and wants to
855
+ // provide guidance via a message), or an ungraded one (same idea,
856
+ // but without giving the user an incorrect mark for the question).
857
+ let matchingAnswerForm;
858
+ let matchMessage;
859
+ let allEmpty = true;
860
+ let firstUngradedResult;
861
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
862
+ for (const answerForm of rubric.answerForms || []) {
863
+ const validator = createValidator(answerForm);
864
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
865
+ if (!validator) {
866
+ continue;
867
+ }
868
+ const result = validator(userInput);
869
+
870
+ // Short-circuit as soon as the user's input matches some answer
871
+ // (independently of whether the answer is correct)
872
+ if (result.correct) {
873
+ matchingAnswerForm = answerForm;
874
+ matchMessage = result.message || "";
875
+ break;
876
+ }
877
+ allEmpty = allEmpty && result.empty;
878
+ // If this answer form is correct and the user's input is considered
879
+ // "ungraded" for it, we'll want to keep the evaluation result for
880
+ // later. If the user's input doesn't match any answer forms, we'll
881
+ // show the message from this validation.
882
+ if (answerForm.considered === "correct" && result.ungraded && !firstUngradedResult) {
883
+ firstUngradedResult = result;
884
+ }
885
+ }
886
+
887
+ // Now check to see if we matched any answer form at all, and if
888
+ // we did, whether it's considered correct, incorrect, or ungraded
889
+ if (!matchingAnswerForm) {
890
+ if (firstUngradedResult) {
891
+ // While we didn't directly match with any answer form, we
892
+ // did at some point get an "ungraded" validation result,
893
+ // which might indicate e.g. a mismatch in variable casing.
894
+ // We'll return "invalid", which will let the user try again
895
+ // with no penalty, and the hopefully helpful validation
896
+ // message.
897
+ return {
898
+ type: "invalid",
899
+ message: firstUngradedResult.message,
900
+ suppressAlmostThere: firstUngradedResult.suppressAlmostThere
901
+ };
902
+ }
903
+ if (allEmpty) {
904
+ // If everything graded as empty, it's invalid.
905
+ return {
906
+ type: "invalid",
907
+ message: null
908
+ };
909
+ }
910
+ // We fell through all the possibilities and we're not empty,
911
+ // so the answer is considered incorrect.
912
+ return {
913
+ type: "points",
914
+ earned: 0,
915
+ total: 1
916
+ };
917
+ }
918
+ if (matchingAnswerForm.considered === "ungraded") {
919
+ return {
920
+ type: "invalid",
921
+ message: matchMessage
922
+ };
923
+ }
924
+ // We matched a graded answer form, so we can now tell the user
925
+ // whether their input was correct or incorrect, and hand out
926
+ // points accordingly
927
+ return {
928
+ type: "points",
929
+ earned: matchingAnswerForm.considered === "correct" ? 1 : 0,
930
+ total: 1,
931
+ message: matchMessage
932
+ };
933
+ }
934
+
935
+ /**
936
+ * Checks user input from the expression widget to see if it is scorable.
937
+ *
938
+ * Note: Most of the expression widget's validation requires the Rubric because
939
+ * of its use of KhanAnswerTypes as a core part of scoring.
940
+ *
941
+ * @see `scoreExpression()` for more details.
942
+ */
943
+ function validateExpression(userInput) {
944
+ if (userInput === "") {
945
+ return {
946
+ type: "invalid",
947
+ message: null
948
+ };
949
+ }
950
+ return null;
951
+ }
952
+
953
+ function getCoefficientsByType(data) {
954
+ if (data.coords == null) {
955
+ return undefined;
956
+ }
957
+ if (data.type === "exponential" || data.type === "logarithm") {
958
+ const grader = GrapherUtil.functionForType(data.type);
959
+ return grader.getCoefficients(data.coords, data.asymptote);
960
+ } else if (data.type === "linear" || data.type === "quadratic" || data.type === "absolute_value" || data.type === "sinusoid" || data.type === "tangent") {
961
+ const grader = GrapherUtil.functionForType(data.type);
962
+ return grader.getCoefficients(data.coords);
963
+ } else {
964
+ throw new PerseusError("Invalid grapher type", Errors.InvalidInput);
965
+ }
966
+ }
967
+ function scoreGrapher(userInput, rubric) {
968
+ if (userInput.type !== rubric.correct.type) {
969
+ return {
970
+ type: "points",
971
+ earned: 0,
972
+ total: 1,
973
+ message: null
974
+ };
975
+ }
976
+
977
+ // We haven't moved the coords
978
+ if (userInput.coords == null) {
979
+ return {
980
+ type: "invalid",
981
+ message: null
982
+ };
983
+ }
984
+
985
+ // Get new function handler for grading
986
+ const grader = GrapherUtil.functionForType(userInput.type);
987
+ const guessCoeffs = getCoefficientsByType(userInput);
988
+ const correctCoeffs = getCoefficientsByType(rubric.correct);
989
+ if (guessCoeffs == null || correctCoeffs == null) {
990
+ return {
991
+ type: "invalid",
992
+ message: null
993
+ };
994
+ }
995
+ if (grader.areEqual(guessCoeffs, correctCoeffs)) {
996
+ return {
997
+ type: "points",
998
+ earned: 1,
999
+ total: 1,
1000
+ message: null
1001
+ };
1002
+ }
1003
+ return {
1004
+ type: "points",
1005
+ earned: 0,
1006
+ total: 1,
1007
+ message: null
1008
+ };
1009
+ }
1010
+
1011
+ // TODO: merge this with scoreCSProgram, it's the same code
1012
+ function scoreIframe(userInput) {
1013
+ // The iframe can tell us whether it's correct or incorrect,
1014
+ // and pass an optional message
1015
+ if (userInput.status === "correct") {
1016
+ return {
1017
+ type: "points",
1018
+ earned: 1,
1019
+ total: 1,
1020
+ message: userInput.message || null
1021
+ };
1022
+ }
1023
+ if (userInput.status === "incorrect") {
1024
+ return {
1025
+ type: "points",
1026
+ earned: 0,
1027
+ total: 1,
1028
+ message: userInput.message || null
1029
+ };
1030
+ }
1031
+ return {
1032
+ type: "invalid",
1033
+ message: "Keep going, you're not there yet!"
1034
+ };
1035
+ }
1036
+
1037
+ const {
1038
+ collinear,
1039
+ canonicalSineCoefficients,
1040
+ similar,
1041
+ clockwise
1042
+ } = geometry;
1043
+ const {
1044
+ getClockwiseAngle
1045
+ } = angles;
1046
+ const {
1047
+ getSinusoidCoefficients,
1048
+ getQuadraticCoefficients
1049
+ } = coefficients;
1050
+ function scoreInteractiveGraph(userInput, rubric) {
1051
+ // None-type graphs are not graded
1052
+ if (userInput.type === "none" && rubric.correct.type === "none") {
1053
+ return {
1054
+ type: "points",
1055
+ earned: 0,
1056
+ total: 0,
1057
+ message: null
1058
+ };
1059
+ }
1060
+
1061
+ // When nothing has moved, there will neither be coords nor the
1062
+ // circle's center/radius fields. When those fields are absent, skip
1063
+ // all these checks; just go mark the answer as empty.
1064
+ const hasValue = Boolean(
1065
+ // @ts-expect-error - TS2339 - Property 'coords' does not exist on type 'PerseusGraphType'.
1066
+ userInput.coords ||
1067
+ // @ts-expect-error - TS2339 - Property 'center' does not exist on type 'PerseusGraphType'. | TS2339 - Property 'radius' does not exist on type 'PerseusGraphType'.
1068
+ userInput.center && userInput.radius);
1069
+ if (userInput.type === rubric.correct.type && hasValue) {
1070
+ if (userInput.type === "linear" && rubric.correct.type === "linear" && userInput.coords != null) {
1071
+ const guess = userInput.coords;
1072
+ const correct = rubric.correct.coords;
1073
+
1074
+ // If both of the guess points are on the correct line, it's
1075
+ // correct.
1076
+ if (collinear(correct[0], correct[1], guess[0]) && collinear(correct[0], correct[1], guess[1])) {
1077
+ return {
1078
+ type: "points",
1079
+ earned: 1,
1080
+ total: 1,
1081
+ message: null
1082
+ };
1083
+ }
1084
+ } else if (userInput.type === "linear-system" && rubric.correct.type === "linear-system" && userInput.coords != null) {
1085
+ const guess = userInput.coords;
1086
+ const correct = rubric.correct.coords;
1087
+ if (collinear(correct[0][0], correct[0][1], guess[0][0]) && collinear(correct[0][0], correct[0][1], guess[0][1]) && collinear(correct[1][0], correct[1][1], guess[1][0]) && collinear(correct[1][0], correct[1][1], guess[1][1]) || collinear(correct[0][0], correct[0][1], guess[1][0]) && collinear(correct[0][0], correct[0][1], guess[1][1]) && collinear(correct[1][0], correct[1][1], guess[0][0]) && collinear(correct[1][0], correct[1][1], guess[0][1])) {
1088
+ return {
1089
+ type: "points",
1090
+ earned: 1,
1091
+ total: 1,
1092
+ message: null
1093
+ };
1094
+ }
1095
+ } else if (userInput.type === "quadratic" && rubric.correct.type === "quadratic" && userInput.coords != null) {
1096
+ // If the parabola coefficients match, it's correct.
1097
+ const guessCoeffs = getQuadraticCoefficients(userInput.coords);
1098
+ const correctCoeffs = getQuadraticCoefficients(rubric.correct.coords);
1099
+ if (approximateDeepEqual(guessCoeffs, correctCoeffs)) {
1100
+ return {
1101
+ type: "points",
1102
+ earned: 1,
1103
+ total: 1,
1104
+ message: null
1105
+ };
1106
+ }
1107
+ } else if (userInput.type === "sinusoid" && rubric.correct.type === "sinusoid" && userInput.coords != null) {
1108
+ const guessCoeffs = getSinusoidCoefficients(userInput.coords);
1109
+ const correctCoeffs = getSinusoidCoefficients(rubric.correct.coords);
1110
+ const canonicalGuessCoeffs = canonicalSineCoefficients(guessCoeffs);
1111
+ const canonicalCorrectCoeffs = canonicalSineCoefficients(correctCoeffs);
1112
+ // If the canonical coefficients match, it's correct.
1113
+ if (approximateDeepEqual(canonicalGuessCoeffs, canonicalCorrectCoeffs)) {
1114
+ return {
1115
+ type: "points",
1116
+ earned: 1,
1117
+ total: 1,
1118
+ message: null
1119
+ };
1120
+ }
1121
+ } else if (userInput.type === "circle" && rubric.correct.type === "circle") {
1122
+ if (approximateDeepEqual(userInput.center, rubric.correct.center) && approximateEqual(userInput.radius, rubric.correct.radius)) {
1123
+ return {
1124
+ type: "points",
1125
+ earned: 1,
1126
+ total: 1,
1127
+ message: null
1128
+ };
1129
+ }
1130
+ } else if (userInput.type === "point" && rubric.correct.type === "point" && userInput.coords != null) {
1131
+ let correct = rubric.correct.coords;
1132
+ if (correct == null) {
1133
+ throw new Error("Point graph rubric has null coords");
1134
+ }
1135
+ const guess = userInput.coords.slice();
1136
+ correct = correct.slice();
1137
+ // Everything's already rounded so we shouldn't need to do an
1138
+ // eq() comparison but _.isEqual(0, -0) is false, so we'll use
1139
+ // eq() anyway. The sort should be fine because it'll stringify
1140
+ // it and -0 converted to a string is "0"
1141
+ guess == null || guess.sort();
1142
+ // @ts-expect-error - TS2339 - Property 'sort' does not exist on type 'readonly Coord[]'.
1143
+ correct.sort();
1144
+ if (approximateDeepEqual(guess, correct)) {
1145
+ return {
1146
+ type: "points",
1147
+ earned: 1,
1148
+ total: 1,
1149
+ message: null
1150
+ };
1151
+ }
1152
+ } else if (userInput.type === "polygon" && rubric.correct.type === "polygon" && userInput.coords != null) {
1153
+ const guess = userInput.coords.slice();
1154
+ const correct = rubric.correct.coords.slice();
1155
+ let match;
1156
+ if (rubric.correct.match === "similar") {
1157
+ match = similar(guess, correct, Number.POSITIVE_INFINITY);
1158
+ } else if (rubric.correct.match === "congruent") {
1159
+ match = similar(guess, correct, number.DEFAULT_TOLERANCE);
1160
+ } else if (rubric.correct.match === "approx") {
1161
+ match = similar(guess, correct, 0.1);
1162
+ } else {
1163
+ /* exact */
1164
+ guess.sort();
1165
+ correct.sort();
1166
+ match = approximateDeepEqual(guess, correct);
1167
+ }
1168
+ if (match) {
1169
+ return {
1170
+ type: "points",
1171
+ earned: 1,
1172
+ total: 1,
1173
+ message: null
1174
+ };
1175
+ }
1176
+ } else if (userInput.type === "segment" && rubric.correct.type === "segment" && userInput.coords != null) {
1177
+ let guess = deepClone(userInput.coords);
1178
+ let correct = deepClone(rubric.correct.coords);
1179
+ guess = _.invoke(guess, "sort").sort();
1180
+ correct = _.invoke(correct, "sort").sort();
1181
+ if (approximateDeepEqual(guess, correct)) {
1182
+ return {
1183
+ type: "points",
1184
+ earned: 1,
1185
+ total: 1,
1186
+ message: null
1187
+ };
1188
+ }
1189
+ } else if (userInput.type === "ray" && rubric.correct.type === "ray" && userInput.coords != null) {
1190
+ const guess = userInput.coords;
1191
+ const correct = rubric.correct.coords;
1192
+ if (approximateDeepEqual(guess[0], correct[0]) && collinear(correct[0], correct[1], guess[1])) {
1193
+ return {
1194
+ type: "points",
1195
+ earned: 1,
1196
+ total: 1,
1197
+ message: null
1198
+ };
1199
+ }
1200
+ } else if (userInput.type === "angle" && rubric.correct.type === "angle") {
1201
+ const coords = userInput.coords;
1202
+ const correct = rubric.correct.coords;
1203
+ const allowReflexAngles = rubric.correct.allowReflexAngles;
1204
+
1205
+ // While the angle graph should always have 3 points, our types
1206
+ // technically allow for null values. We'll check for that here.
1207
+ // TODO: (LEMS-2857) We would like to update the type of coords
1208
+ // to be non-nullable, as the graph should always have 3 points.
1209
+ if (!coords) {
1210
+ return {
1211
+ type: "invalid",
1212
+ message: null
1213
+ };
1214
+ }
1215
+
1216
+ // We need to check both the direction of the angle and the
1217
+ // whether the graph allows for reflexive angles in order to
1218
+ // to determine if we need to reverse the coords for scoring.
1219
+ const areClockwise = clockwise([coords[0], coords[2], coords[1]]);
1220
+ const shouldReverseCoords = areClockwise && !allowReflexAngles;
1221
+ const guess = shouldReverseCoords ? coords.slice().reverse() : coords;
1222
+ let match;
1223
+ if (rubric.correct.match === "congruent") {
1224
+ const angles = _.map([guess, correct], function (coords) {
1225
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
1226
+ if (!coords) {
1227
+ return false;
1228
+ }
1229
+ const angle = getClockwiseAngle(coords, allowReflexAngles);
1230
+ return angle;
1231
+ });
1232
+ // @ts-expect-error - TS2556 - A spread argument must either have a tuple type or be passed to a rest parameter.
1233
+ match = approximateEqual(...angles);
1234
+ } else {
1235
+ /* exact */
1236
+ match = approximateDeepEqual(guess[1], correct[1]) && collinear(correct[1], correct[0], guess[0]) && collinear(correct[1], correct[2], guess[2]);
1237
+ }
1238
+ if (match) {
1239
+ return {
1240
+ type: "points",
1241
+ earned: 1,
1242
+ total: 1,
1243
+ message: null
1244
+ };
1245
+ }
1246
+ }
1247
+ }
1248
+
1249
+ // The input wasn't correct, so check if it's a blank input or if it's
1250
+ // actually just wrong
1251
+ if (!hasValue || _.isEqual(userInput, rubric.graph)) {
1252
+ // We're where we started.
1253
+ return {
1254
+ type: "invalid",
1255
+ message: null
1256
+ };
1257
+ }
1258
+ return {
1259
+ type: "points",
1260
+ earned: 0,
1261
+ total: 1,
1262
+ message: null
1263
+ };
1264
+ }
1265
+
1266
+ // Question state for marker as result of user selected answers.
1267
+
1268
+ function scoreLabelImageMarker(userInput, rubric) {
1269
+ const score = {
1270
+ hasAnswers: false,
1271
+ isCorrect: false
1272
+ };
1273
+ if (userInput && userInput.length > 0) {
1274
+ score.hasAnswers = true;
1275
+ }
1276
+ if (rubric.length > 0) {
1277
+ if (userInput && userInput.length === rubric.length) {
1278
+ // All correct answers are selected by the user.
1279
+ score.isCorrect = userInput.every(choice => rubric.includes(choice));
1280
+ }
1281
+ } else if (!userInput || userInput.length === 0) {
1282
+ // Correct as no answers should be selected by the user.
1283
+ score.isCorrect = true;
1284
+ }
1285
+ return score;
1286
+ }
1287
+ function scoreLabelImage(userInput, rubric) {
1288
+ let numCorrect = 0;
1289
+ for (let i = 0; i < userInput.markers.length; i++) {
1290
+ const score = scoreLabelImageMarker(userInput.markers[i].selected, rubric.markers[i].answers);
1291
+ if (score.isCorrect) {
1292
+ numCorrect++;
1293
+ }
1294
+ }
1295
+ return {
1296
+ type: "points",
1297
+ // Markers with no expected answers are graded as correct if user
1298
+ // makes no answer selection.
1299
+ earned: numCorrect === userInput.markers.length ? 1 : 0,
1300
+ total: 1,
1301
+ message: null
1302
+ };
1303
+ }
1304
+
1305
+ function scoreMatcher(userInput, rubric) {
1306
+ const correct = _.isEqual(userInput.left, rubric.left) && _.isEqual(userInput.right, rubric.right);
1307
+ return {
1308
+ type: "points",
1309
+ earned: correct ? 1 : 0,
1310
+ total: 1,
1311
+ message: null
1312
+ };
1313
+ }
1314
+
1315
+ function scoreMatrix(userInput, rubric) {
1316
+ const solution = rubric.answers;
1317
+ const supplied = userInput.answers;
1318
+ const solutionSize = getMatrixSize(solution);
1319
+ const suppliedSize = getMatrixSize(supplied);
1320
+ const incorrectSize = solutionSize[0] !== suppliedSize[0] || solutionSize[1] !== suppliedSize[1];
1321
+ const createValidator = KhanAnswerTypes.number.createValidatorFunctional;
1322
+ let message = null;
1323
+ let incorrect = false;
1324
+ _(suppliedSize[0]).times(row => {
1325
+ _(suppliedSize[1]).times(col => {
1326
+ if (!incorrectSize) {
1327
+ const validator = createValidator(
1328
+ // @ts-expect-error - TS2345 - Argument of type 'number' is not assignable to parameter of type 'string'.
1329
+ solution[row][col], {
1330
+ simplify: true
1331
+ });
1332
+ const result = validator(supplied[row][col]);
1333
+ if (result.message) {
1334
+ // @ts-expect-error - TS2322 - Type 'string' is not assignable to type 'null'.
1335
+ message = result.message;
1336
+ }
1337
+ if (!result.correct) {
1338
+ incorrect = true;
1339
+ }
1340
+ }
1341
+ });
1342
+ });
1343
+ if (incorrectSize) {
1344
+ return {
1345
+ type: "points",
1346
+ earned: 0,
1347
+ total: 1,
1348
+ message: null
1349
+ };
1350
+ }
1351
+ return {
1352
+ type: "points",
1353
+ earned: incorrect ? 0 : 1,
1354
+ total: 1,
1355
+ message: message
1356
+ };
1357
+ }
1358
+
1359
+ /**
1360
+ * Checks user input from the matrix widget to see if it is scorable.
1361
+ *
1362
+ * Note: The matrix widget cannot do much validation without the Scoring
1363
+ * Data because of its use of KhanAnswerTypes as a core part of scoring.
1364
+ *
1365
+ * @see `scoreMatrix()` for more details.
1366
+ */
1367
+ function validateMatrix(userInput) {
1368
+ const supplied = userInput.answers;
1369
+ const suppliedSize = getMatrixSize(supplied);
1370
+ for (let row = 0; row < suppliedSize[0]; row++) {
1371
+ for (let col = 0; col < suppliedSize[1]; col++) {
1372
+ if (supplied[row][col] == null || supplied[row][col].toString().length === 0) {
1373
+ return {
1374
+ type: "invalid",
1375
+ message: ErrorCodes.FILL_ALL_CELLS_ERROR
1376
+ };
1377
+ }
1378
+ }
1379
+ }
1380
+ return null;
1381
+ }
1382
+
1383
+ function scoreNumberLine(userInput, rubric) {
1384
+ const range = rubric.range;
1385
+ const start = rubric.initialX != null ? rubric.initialX : range[0];
1386
+ const startRel = rubric.isInequality ? "ge" : "eq";
1387
+ const correctRel = rubric.correctRel || "eq";
1388
+ const correctPos = number.equal(userInput.numLinePosition,
1389
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
1390
+ rubric.correctX || 0);
1391
+ if (correctPos && correctRel === userInput.rel) {
1392
+ return {
1393
+ type: "points",
1394
+ earned: 1,
1395
+ total: 1,
1396
+ message: null
1397
+ };
1398
+ }
1399
+ if (userInput.numLinePosition === start && userInput.rel === startRel) {
1400
+ // We're where we started.
1401
+ return {
1402
+ type: "invalid",
1403
+ message: null
1404
+ };
1405
+ }
1406
+ return {
1407
+ type: "points",
1408
+ earned: 0,
1409
+ total: 1,
1410
+ message: null
1411
+ };
1412
+ }
1413
+
1414
+ /**
1415
+ * Checks user input is within the allowed range and not the same as the initial
1416
+ * state.
1417
+ * @param userInput
1418
+ * @see 'scoreNumberLine' for the scoring logic.
1419
+ */
1420
+ function validateNumberLine(userInput) {
1421
+ const divisionRange = userInput.divisionRange;
1422
+ const outsideAllowedRange = userInput.numDivisions > divisionRange[1] || userInput.numDivisions < divisionRange[0];
1423
+
1424
+ // TODO: I don't think isTickCrtl is a thing anymore
1425
+ if (userInput.isTickCrtl && outsideAllowedRange) {
1426
+ return {
1427
+ type: "invalid",
1428
+ message: "Number of divisions is outside the allowed range."
1429
+ };
1430
+ }
1431
+ return null;
1432
+ }
1433
+
1434
+ /*
1435
+ * In this file, an `expression` is some portion of valid TeX enclosed in
1436
+ * curly brackets.
1437
+ */
1438
+
1439
+ /*
1440
+ * Find the index at which an expression ends, i.e., has an unmatched
1441
+ * closing curly bracket. This method assumes that we start with a non-open
1442
+ * bracket character and end when we've seen more left than right brackets
1443
+ * (rather than assuming that we start with a bracket character and wait for
1444
+ * bracket equality).
1445
+ */
1446
+ function findEndpoint(tex, currentIndex) {
1447
+ let bracketDepth = 0;
1448
+ for (let i = currentIndex, len = tex.length; i < len; i++) {
1449
+ const c = tex[i];
1450
+ if (c === "{") {
1451
+ bracketDepth++;
1452
+ } else if (c === "}") {
1453
+ bracketDepth--;
1454
+ }
1455
+ if (bracketDepth < 0) {
1456
+ return i;
1457
+ }
1458
+ }
1459
+ // If we never see unbalanced curly brackets, default to the
1460
+ // entire string
1461
+ return tex.length;
1462
+ }
1463
+
1464
+ /*
1465
+ * Parses an individual set of curly brackets into TeX.
1466
+ */
1467
+ function parseNextExpression(tex, currentIndex, handler) {
1468
+ // Find the first '{' and grab subsequent TeX
1469
+ // Ex) tex: '{3}{7}', and we want the '3'
1470
+ const openBracketIndex = tex.indexOf("{", currentIndex);
1471
+
1472
+ // If there is no open bracket, set the endpoint to the end of the string
1473
+ // and the expression to an empty string. This helps ensure we don't
1474
+ // get stuck in an infinite loop when users handtype TeX.
1475
+ if (openBracketIndex === -1) {
1476
+ return {
1477
+ endpoint: tex.length,
1478
+ expression: ""
1479
+ };
1480
+ }
1481
+ const nextExpIndex = openBracketIndex + 1;
1482
+
1483
+ // Truncate to only contain remaining TeX
1484
+ const endpoint = findEndpoint(tex, nextExpIndex);
1485
+ const expressionTeX = tex.substring(nextExpIndex, endpoint);
1486
+ const parsedExp = walkTex(expressionTeX, handler);
1487
+ return {
1488
+ endpoint: endpoint,
1489
+ expression: parsedExp
1490
+ };
1491
+ }
1492
+ function getNextFracIndex(tex, currentIndex) {
1493
+ const dfrac = "\\dfrac";
1494
+ const frac = "\\frac";
1495
+ const nextFrac = tex.indexOf(frac, currentIndex);
1496
+ const nextDFrac = tex.indexOf(dfrac, currentIndex);
1497
+ if (nextFrac > -1 && nextDFrac > -1) {
1498
+ return Math.min(nextFrac, nextDFrac);
1499
+ }
1500
+ if (nextFrac > -1) {
1501
+ return nextFrac;
1502
+ }
1503
+ if (nextDFrac > -1) {
1504
+ return nextDFrac;
1505
+ }
1506
+ return -1;
1507
+ }
1508
+ function walkTex(tex, handler) {
1509
+ if (!tex) {
1510
+ return "";
1511
+ }
1512
+
1513
+ // Ex) tex: '2 \dfrac {3}{7}'
1514
+ let parsedString = "";
1515
+ let currentIndex = 0;
1516
+ let nextFrac = getNextFracIndex(tex, currentIndex);
1517
+
1518
+ // For each \dfrac, find the two expressions (wrapped in {}) and recur
1519
+ while (nextFrac > -1) {
1520
+ // Gather first fragment, preceding \dfrac
1521
+ // Ex) parsedString: '2 '
1522
+ parsedString += tex.substring(currentIndex, nextFrac);
1523
+
1524
+ // Remove everything preceding \dfrac, which has been parsed
1525
+ currentIndex = nextFrac;
1526
+
1527
+ // Parse first expression and move index past it
1528
+ // Ex) firstParsedExpression.expression: '3'
1529
+ const firstParsedExpression = parseNextExpression(tex, currentIndex, handler);
1530
+ currentIndex = firstParsedExpression.endpoint + 1;
1531
+
1532
+ // Parse second expression
1533
+ // Ex) secondParsedExpression.expression: '7'
1534
+ const secondParsedExpression = parseNextExpression(tex, currentIndex, handler);
1535
+ currentIndex = secondParsedExpression.endpoint + 1;
1536
+
1537
+ // Add expressions to running total of parsed expressions
1538
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
1539
+ if (parsedString.length) {
1540
+ parsedString += " ";
1541
+ }
1542
+
1543
+ // Apply a custom handler based on the parsed subexpressions
1544
+ parsedString += handler(firstParsedExpression.expression, secondParsedExpression.expression);
1545
+
1546
+ // Find next DFrac, relative to currentIndex
1547
+ nextFrac = getNextFracIndex(tex, currentIndex);
1548
+ }
1549
+
1550
+ // Add remaining TeX, which is \dfrac-free
1551
+ parsedString += tex.slice(currentIndex);
1552
+ return parsedString;
1553
+ }
1554
+
1555
+ /*
1556
+ * Parse a TeX expression into something interpretable by input-number.
1557
+ * The process is concerned with: (1) parsing fractions, i.e., \dfracs; and
1558
+ * (2) removing backslash-escaping from certain characters (right now, only
1559
+ * percent signs).
1560
+ *
1561
+ * The basic algorithm for handling \dfracs splits on \dfracs and then recurs
1562
+ * on the subsequent "expressions", i.e., the {} pairs that follow \dfrac. The
1563
+ * recursion is to allow for nested \dfrac elements.
1564
+ *
1565
+ * Backslash-escapes are removed with a simple search-and-replace.
1566
+ */
1567
+ function parseTex(tex) {
1568
+ const handler = function handler(exp1, exp2) {
1569
+ return exp1 + "/" + exp2;
1570
+ };
1571
+ const texWithoutFracs = walkTex(tex, handler);
1572
+ return texWithoutFracs.replace("\\%", "%");
1573
+ }
1574
+
1575
+ const answerFormButtons = [{
1576
+ title: "Integers",
1577
+ value: "integer",
1578
+ content: "6"
1579
+ }, {
1580
+ title: "Decimals",
1581
+ value: "decimal",
1582
+ content: "0.75"
1583
+ }, {
1584
+ title: "Proper fractions",
1585
+ value: "proper",
1586
+ content: "\u2157"
1587
+ }, {
1588
+ title: "Improper fractions",
1589
+ value: "improper",
1590
+ content: "\u2077\u2044\u2084"
1591
+ }, {
1592
+ title: "Mixed numbers",
1593
+ value: "mixed",
1594
+ content: "1\u00BE"
1595
+ }, {
1596
+ title: "Numbers with \u03C0",
1597
+ value: "pi",
1598
+ content: "\u03C0"
1599
+ }];
1600
+
1601
+ // This function checks if the user inputted a percent value, parsing
1602
+ // it as a number (and maybe scaling) so that it can be graded.
1603
+ // NOTE(michaelpolyak): Unlike `KhanAnswerTypes.number.percent()` which
1604
+ // can accept several input forms with or without "%", the decision
1605
+ // to parse based on the presence of "%" in the input, is so that we
1606
+ // don't accidently scale the user typed value before grading, CP-930.
1607
+ function maybeParsePercentInput(inputValue, normalizedAnswerExpected) {
1608
+ // If the input value is not a string ending with "%", then there's
1609
+ // nothing more to do. The value will be graded as inputted by user.
1610
+ if (!(typeof inputValue === "string" && inputValue.endsWith("%"))) {
1611
+ return inputValue;
1612
+ }
1613
+ const value = parseFloat(inputValue.slice(0, -1));
1614
+ // If the input value stripped of the "%" cannot be parsed as a
1615
+ // number (the slice is not really necessary for parseFloat to work
1616
+ // if the string starts with a number) then return the original
1617
+ // input for grading.
1618
+ if (isNaN(value)) {
1619
+ return inputValue;
1620
+ }
1621
+
1622
+ // Next, if all correct answers are in the range of |0,1| then we
1623
+ // scale the user typed value. We assume this is the correct thing
1624
+ // to do since the input value ends with "%".
1625
+ if (normalizedAnswerExpected) {
1626
+ return value / 100;
1627
+ }
1628
+
1629
+ // Otherwise, we return input value (number) stripped of the "%".
1630
+ return value;
1631
+ }
1632
+ function scoreNumericInput(userInput, rubric) {
1633
+ var _matchedAnswer$messag;
1634
+ const defaultAnswerForms = answerFormButtons.map(e => e["value"])
1635
+ // Don't default to validating the answer as a pi answer
1636
+ // if answerForm isn't set on the answer
1637
+ // https://khanacademy.atlassian.net/browse/LC-691
1638
+ .filter(e => e !== "pi");
1639
+ const createValidator = answer => {
1640
+ var _answer$answerForms;
1641
+ const stringAnswer = `${answer.value}`;
1642
+
1643
+ // Always validate against the provided answer forms (pi, decimal, etc.)
1644
+ const validatorForms = [...((_answer$answerForms = answer.answerForms) != null ? _answer$answerForms : [])];
1645
+
1646
+ // When an answer is set to strict, we validate using ONLY
1647
+ // the provided answerForms. If strict is false, or if there
1648
+ // were no provided answer forms, we will include all
1649
+ // of the default answer forms in our validator.
1650
+ if (!answer.strict || validatorForms.length === 0) {
1651
+ validatorForms.push(...defaultAnswerForms);
1652
+ }
1653
+ return KhanAnswerTypes.number.createValidatorFunctional(stringAnswer, {
1654
+ message: answer.message,
1655
+ simplify: answer.status === "correct" ? answer.simplify : "optional",
1656
+ inexact: true,
1657
+ // TODO(merlob) backfill / delete
1658
+ maxError: answer.maxError,
1659
+ forms: validatorForms
1660
+ });
1661
+ };
1662
+
1663
+ // We may have received TeX; try to parse it before grading.
1664
+ // If `currentValue` is not TeX, this should be a no-op.
1665
+ const currentValue = parseTex(userInput.currentValue);
1666
+ const normalizedAnswerExpected = rubric.answers.filter(answer => answer.status === "correct").every(answer => answer.value != null && Math.abs(answer.value) <= 1);
1667
+
1668
+ // The coefficient is an attribute of the widget
1669
+ let localValue = currentValue;
1670
+ if (rubric.coefficient) {
1671
+ if (!localValue) {
1672
+ localValue = 1;
1673
+ } else if (localValue === "-") {
1674
+ localValue = -1;
1675
+ }
1676
+ }
1677
+ const matchedAnswer = rubric.answers.map(answer => {
1678
+ const validateFn = createValidator(answer);
1679
+ const score = validateFn(maybeParsePercentInput(localValue, normalizedAnswerExpected));
1680
+ return _extends({}, answer, {
1681
+ score
1682
+ });
1683
+ }).find(answer => {
1684
+ // NOTE: "answer.score.correct" indicates a match via the validate function.
1685
+ // It does NOT indicate that the answer itself is correct.
1686
+ return answer.score.correct || answer.status === "correct" && answer.score.empty;
1687
+ });
1688
+ const result = (matchedAnswer == null ? void 0 : matchedAnswer.status) === "correct" ? matchedAnswer.score : {
1689
+ empty: (matchedAnswer == null ? void 0 : matchedAnswer.status) === "ungraded",
1690
+ correct: (matchedAnswer == null ? void 0 : matchedAnswer.status) === "correct",
1691
+ message: (_matchedAnswer$messag = matchedAnswer == null ? void 0 : matchedAnswer.message) != null ? _matchedAnswer$messag : null};
1692
+ if (result.empty) {
1693
+ return {
1694
+ type: "invalid",
1695
+ message: result.message
1696
+ };
1697
+ }
1698
+ return {
1699
+ type: "points",
1700
+ earned: result.correct ? 1 : 0,
1701
+ total: 1,
1702
+ message: result.message
1703
+ };
1704
+ }
1705
+
1706
+ function scoreOrderer(userInput, rubric) {
1707
+ const correct = _.isEqual(userInput.current, rubric.correctOptions.map(option => option.content));
1708
+ return {
1709
+ type: "points",
1710
+ earned: correct ? 1 : 0,
1711
+ total: 1,
1712
+ message: null
1713
+ };
1714
+ }
1715
+
1716
+ /**
1717
+ * Checks user input from the orderer widget to see if the user has started
1718
+ * ordering the options, making the widget scorable.
1719
+ * @param userInput
1720
+ * @see `scoreOrderer` for more details.
1721
+ */
1722
+ function validateOrderer(userInput) {
1723
+ if (userInput.current.length === 0) {
1724
+ return {
1725
+ type: "invalid",
1726
+ message: null
1727
+ };
1728
+ }
1729
+ return null;
1730
+ }
1731
+
1732
+ function scorePlotter(userInput, rubric) {
1733
+ return {
1734
+ type: "points",
1735
+ earned: approximateDeepEqual(userInput, rubric.correct) ? 1 : 0,
1736
+ total: 1,
1737
+ message: null
1738
+ };
1739
+ }
1740
+
1741
+ /**
1742
+ * Checks user input to confirm it is not the same as the starting values for the graph.
1743
+ * This means the user has modified the graph, and the question can be scored.
1744
+ *
1745
+ * @see 'scorePlotter' for more details on scoring.
1746
+ */
1747
+ function validatePlotter(userInput, validationData) {
1748
+ if (approximateDeepEqual(userInput, validationData.starting)) {
1749
+ return {
1750
+ type: "invalid",
1751
+ message: null
1752
+ };
1753
+ }
1754
+ return null;
1755
+ }
1756
+
1757
+ function scoreRadio(userInput, rubric) {
1758
+ const numSelected = userInput.choicesSelected.reduce((sum, selected) => {
1759
+ return sum + (selected ? 1 : 0);
1760
+ }, 0);
1761
+ const numCorrect = rubric.choices.reduce((sum, currentChoice) => {
1762
+ return currentChoice.correct ? sum + 1 : sum;
1763
+ }, 0);
1764
+ if (numCorrect > 1 && numSelected !== numCorrect) {
1765
+ return {
1766
+ type: "invalid",
1767
+ message: ErrorCodes.CHOOSE_CORRECT_NUM_ERROR
1768
+ };
1769
+ // If NOTA and some other answer are checked, ...
1770
+ }
1771
+ const noneOfTheAboveSelected = rubric.choices.some((choice, index) => choice.isNoneOfTheAbove && userInput.choicesSelected[index]);
1772
+ if (noneOfTheAboveSelected && numSelected > 1) {
1773
+ return {
1774
+ type: "invalid",
1775
+ message: ErrorCodes.NOT_NONE_ABOVE_ERROR
1776
+ };
1777
+ }
1778
+ const correct = userInput.choicesSelected.every((selected, i) => {
1779
+ let isCorrect;
1780
+ if (rubric.choices[i].isNoneOfTheAbove) {
1781
+ isCorrect = rubric.choices.every((choice, j) => {
1782
+ return i === j || !choice.correct;
1783
+ });
1784
+ } else {
1785
+ isCorrect = !!rubric.choices[i].correct;
1786
+ }
1787
+ return isCorrect === selected;
1788
+ });
1789
+ return {
1790
+ type: "points",
1791
+ earned: correct ? 1 : 0,
1792
+ total: 1,
1793
+ message: null
1794
+ };
1795
+ }
1796
+
1797
+ /**
1798
+ * Checks if the user has selected at least one option. Additional validation
1799
+ * is done in scoreRadio to check if the number of selected options is correct
1800
+ * and if the user has selected both a correct option and the "none of the above"
1801
+ * option.
1802
+ * @param userInput
1803
+ * @see `scoreRadio` for the additional validation logic and the scoring logic.
1804
+ */
1805
+ function validateRadio(userInput) {
1806
+ const numSelected = userInput.choicesSelected.reduce((sum, selected) => {
1807
+ return sum + (selected ? 1 : 0);
1808
+ }, 0);
1809
+ if (numSelected === 0) {
1810
+ return {
1811
+ type: "invalid",
1812
+ message: null
1813
+ };
1814
+ }
1815
+ return null;
1816
+ }
1817
+
1818
+ function scoreSorter(userInput, rubric) {
1819
+ const correct = approximateDeepEqual(userInput.options, rubric.correct);
1820
+ return {
1821
+ type: "points",
1822
+ earned: correct ? 1 : 0,
1823
+ total: 1,
1824
+ message: null
1825
+ };
1826
+ }
1827
+
1828
+ /**
1829
+ * Checks user input for the sorter widget to ensure that the user has made
1830
+ * changes before attempting to score the widget.
1831
+ * @param userInput
1832
+ * @see 'scoreSorter' in 'packages/perseus/src/widgets/sorter/score-sorter.ts'
1833
+ * for more details on how the sorter widget is scored.
1834
+ */
1835
+ function validateSorter(userInput) {
1836
+ // If the sorter widget hasn't been changed yet, we treat it as "empty" which
1837
+ // prevents the "Check" button from becoming active. We want the user
1838
+ // to make a change before trying to move forward. This makes an
1839
+ // assumption that the initial order isn't the correct order! However,
1840
+ // this should be rare if it happens, and interacting with the list
1841
+ // will enable the button, so they won't be locked out of progressing.
1842
+ if (!userInput.changed) {
1843
+ return {
1844
+ type: "invalid",
1845
+ message: null
1846
+ };
1847
+ }
1848
+ return null;
1849
+ }
1850
+
1851
+ /**
1852
+ * Filters the given table (modelled as a 2D array) to remove any rows that are
1853
+ * completely empty.
1854
+ *
1855
+ * @returns A new table with only non-empty rows.
1856
+ */
1857
+ const filterNonEmpty = function filterNonEmpty(table) {
1858
+ return table.filter(function (row) {
1859
+ // Return only rows that are non-empty.
1860
+ return row.some(cell => cell);
1861
+ });
1862
+ };
1863
+
1864
+ function validateTable(userInput) {
1865
+ const supplied = filterNonEmpty(userInput);
1866
+ const hasEmptyCell = supplied.some(function (row) {
1867
+ return row.some(function (cell) {
1868
+ return cell === "";
1869
+ });
1870
+ });
1871
+
1872
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
1873
+ if (hasEmptyCell || !supplied.length) {
1874
+ return {
1875
+ type: "invalid",
1876
+ message: null
1877
+ };
1878
+ }
1879
+ return null;
1880
+ }
1881
+
1882
+ function scoreTable(userInput, rubric) {
1883
+ const validationResult = validateTable(userInput);
1884
+ if (validationResult != null) {
1885
+ return validationResult;
1886
+ }
1887
+ const supplied = filterNonEmpty(userInput);
1888
+ const solution = filterNonEmpty(rubric.answers);
1889
+ if (supplied.length !== solution.length) {
1890
+ return {
1891
+ type: "points",
1892
+ earned: 0,
1893
+ total: 1,
1894
+ message: null
1895
+ };
1896
+ }
1897
+ const createValidator = KhanAnswerTypes.number.createValidatorFunctional;
1898
+ let message = null;
1899
+ const allCorrect = solution.every(function (rowSolution) {
1900
+ for (let i = 0; i < supplied.length; i++) {
1901
+ const rowSupplied = supplied[i];
1902
+ const correct = rowSupplied.every(function (cellSupplied, i) {
1903
+ const cellSolution = rowSolution[i];
1904
+ const validator = createValidator(cellSolution, {
1905
+ simplify: true
1906
+ });
1907
+ const result = validator(cellSupplied);
1908
+ if (result.message) {
1909
+ message = result.message;
1910
+ }
1911
+ return result.correct;
1912
+ });
1913
+ if (correct) {
1914
+ supplied.splice(i, 1);
1915
+ return true;
1916
+ }
1917
+ }
1918
+ return false;
1919
+ });
1920
+ return {
1921
+ type: "points",
1922
+ earned: allCorrect ? 1 : 0,
1923
+ total: 1,
1924
+ message
1925
+ };
1926
+ }
1927
+
1928
+ const inputNumberAnswerTypes = {
1929
+ number: {
1930
+ name: "Numbers",
1931
+ forms: "integer, decimal, proper, improper, mixed"
1932
+ },
1933
+ decimal: {
1934
+ name: "Decimals",
1935
+ forms: "decimal"
1936
+ },
1937
+ integer: {
1938
+ name: "Integers",
1939
+ forms: "integer"
1940
+ },
1941
+ rational: {
1942
+ name: "Fractions and mixed numbers",
1943
+ forms: "integer, proper, improper, mixed"
1944
+ },
1945
+ improper: {
1946
+ name: "Improper numbers (no mixed)",
1947
+ forms: "integer, proper, improper"
1948
+ },
1949
+ mixed: {
1950
+ name: "Mixed numbers (no improper)",
1951
+ forms: "integer, proper, mixed"
1952
+ },
1953
+ percent: {
1954
+ name: "Numbers or percents",
1955
+ forms: "integer, decimal, proper, improper, mixed, percent"
1956
+ },
1957
+ pi: {
1958
+ name: "Numbers with pi",
1959
+ forms: "pi"
1960
+ }
1961
+ };
1962
+ function scoreInputNumber(userInput, rubric) {
1963
+ if (rubric.answerType == null) {
1964
+ rubric.answerType = "number";
1965
+ }
1966
+
1967
+ // note(matthewc): this will get immediately parsed again by
1968
+ // `KhanAnswerTypes.number.convertToPredicate`, but a string is
1969
+ // expected here
1970
+ const stringValue = `${rubric.value}`;
1971
+ const val = KhanAnswerTypes.number.createValidatorFunctional(stringValue, {
1972
+ simplify: rubric.simplify,
1973
+ inexact: rubric.inexact || undefined,
1974
+ maxError: rubric.maxError,
1975
+ forms: inputNumberAnswerTypes[rubric.answerType].forms
1976
+ });
1977
+
1978
+ // We may have received TeX; try to parse it before grading.
1979
+ // If `currentValue` is not TeX, this should be a no-op.
1980
+ const currentValue = parseTex(userInput.currentValue);
1981
+ const result = val(currentValue);
1982
+ if (result.empty) {
1983
+ return {
1984
+ type: "invalid",
1985
+ message: result.message
1986
+ };
1987
+ }
1988
+ return {
1989
+ type: "points",
1990
+ earned: result.correct ? 1 : 0,
1991
+ total: 1,
1992
+ message: result.message
1993
+ };
1994
+ }
1995
+
1996
+ /**
1997
+ * Several widgets don't have "right"/"wrong" scoring logic,
1998
+ * so this just says to move on past those widgets
1999
+ *
2000
+ * TODO(LEMS-2543) widgets that use this probably shouldn't have any
2001
+ * scoring logic and the thing scoring an exercise
2002
+ * should just know to skip these
2003
+ */
2004
+ function scoreNoop(points = 0) {
2005
+ return {
2006
+ type: "points",
2007
+ earned: points,
2008
+ total: points,
2009
+ message: null
2010
+ };
2011
+ }
2012
+
2013
+ // The `group` widget is basically a widget hosting a full Perseus system in
2014
+
2015
+ // it. As such, scoring a group means scoring all widgets it contains.
2016
+ function scoreGroup(userInput, rubric, locale) {
2017
+ const scores = scoreWidgetsFunctional(rubric.widgets, Object.keys(rubric.widgets), userInput, locale);
2018
+ return flattenScores(scores);
2019
+ }
2020
+
2021
+ /**
2022
+ * Checks the given user input to see if any answerable widgets have not been
2023
+ * "filled in" (ie. if they're empty). Another way to think about this
2024
+ * function is that its a check to see if we can score the provided input.
2025
+ */
2026
+ function emptyWidgetsFunctional(widgets,
2027
+ // This is a port of old code, I'm not sure why
2028
+ // we need widgetIds vs the keys of the widgets object
2029
+ widgetIds, userInputMap, locale) {
2030
+ return widgetIds.filter(id => {
2031
+ const widget = widgets[id];
2032
+ if (!widget || widget.static === true) {
2033
+ // Static widgets shouldn't count as empty
2034
+ return false;
2035
+ }
2036
+ const validator = getWidgetValidator(widget.type);
2037
+ const userInput = userInputMap[id];
2038
+ const validationData = widget.options;
2039
+ const score = validator == null ? void 0 : validator(userInput, validationData, locale);
2040
+ if (score) {
2041
+ return scoreIsEmpty(score);
2042
+ }
2043
+ });
2044
+ }
2045
+
2046
+ function validateGroup(userInput, validationData, locale) {
2047
+ const emptyWidgets = emptyWidgetsFunctional(validationData.widgets, Object.keys(validationData.widgets), userInput, locale);
2048
+ if (emptyWidgets.length === 0) {
2049
+ return null;
2050
+ }
2051
+ return {
2052
+ type: "invalid",
2053
+ message: null
2054
+ };
2055
+ }
2056
+
2057
+ function validateLabelImage(userInput) {
2058
+ let numAnswered = 0;
2059
+ for (let i = 0; i < userInput.markers.length; i++) {
2060
+ const userSelection = userInput.markers[i].selected;
2061
+ if (userSelection && userSelection.length > 0) {
2062
+ numAnswered++;
2063
+ }
2064
+ }
2065
+ // We expect all question markers to be answered before grading.
2066
+ if (numAnswered !== userInput.markers.length) {
2067
+ return {
2068
+ type: "invalid",
2069
+ message: null
2070
+ };
2071
+ }
2072
+ return null;
2073
+ }
2074
+
2075
+ function validateMockWidget(userInput) {
2076
+ if (userInput.currentValue == null || userInput.currentValue === "") {
2077
+ return {
2078
+ type: "invalid",
2079
+ message: ""
2080
+ };
2081
+ }
2082
+ return null;
2083
+ }
2084
+
2085
+ function scoreMockWidget(userInput, rubric) {
2086
+ const validationResult = validateMockWidget(userInput);
2087
+ if (validationResult != null) {
2088
+ return validationResult;
2089
+ }
2090
+ return {
2091
+ type: "points",
2092
+ earned: userInput.currentValue === rubric.value ? 1 : 0,
2093
+ total: 1,
2094
+ message: ""
2095
+ };
2096
+ }
2097
+
2098
+ const widgets = {};
2099
+ function registerWidget(type, scorer, validator) {
2100
+ widgets[type] = {
2101
+ scorer,
2102
+ validator
2103
+ };
2104
+ }
2105
+ const getWidgetValidator = name => {
2106
+ var _widgets$name$validat, _widgets$name;
2107
+ return (_widgets$name$validat = (_widgets$name = widgets[name]) == null ? void 0 : _widgets$name.validator) != null ? _widgets$name$validat : null;
2108
+ };
2109
+ const getWidgetScorer = name => {
2110
+ var _widgets$name$scorer, _widgets$name2;
2111
+ return (_widgets$name$scorer = (_widgets$name2 = widgets[name]) == null ? void 0 : _widgets$name2.scorer) != null ? _widgets$name$scorer : null;
2112
+ };
2113
+ registerWidget("categorizer", scoreCategorizer, validateCategorizer);
2114
+ registerWidget("cs-program", scoreCSProgram);
2115
+ registerWidget("dropdown", scoreDropdown, validateDropdown);
2116
+ registerWidget("expression", scoreExpression, validateExpression);
2117
+ registerWidget("grapher", scoreGrapher);
2118
+ registerWidget("group", scoreGroup, validateGroup);
2119
+ registerWidget("iframe", scoreIframe);
2120
+ registerWidget("input-number", scoreInputNumber);
2121
+ registerWidget("interactive-graph", scoreInteractiveGraph);
2122
+ registerWidget("label-image", scoreLabelImage, validateLabelImage);
2123
+ registerWidget("matcher", scoreMatcher);
2124
+ registerWidget("matrix", scoreMatrix, validateMatrix);
2125
+ registerWidget("mock-widget", scoreMockWidget, scoreMockWidget);
2126
+ registerWidget("number-line", scoreNumberLine, validateNumberLine);
2127
+ registerWidget("numeric-input", scoreNumericInput);
2128
+ registerWidget("orderer", scoreOrderer, validateOrderer);
2129
+ registerWidget("plotter", scorePlotter, validatePlotter);
2130
+ registerWidget("radio", scoreRadio, validateRadio);
2131
+ registerWidget("sorter", scoreSorter, validateSorter);
2132
+ registerWidget("table", scoreTable, validateTable);
2133
+ registerWidget("deprecated-standin", () => scoreNoop(1));
2134
+ registerWidget("measurer", () => scoreNoop(1));
2135
+ registerWidget("definition", scoreNoop);
2136
+ registerWidget("explanation", scoreNoop);
2137
+ registerWidget("image", scoreNoop);
2138
+ registerWidget("interaction", scoreNoop);
2139
+ registerWidget("molecule", scoreNoop);
2140
+ registerWidget("passage", scoreNoop);
2141
+ registerWidget("passage-ref", scoreNoop);
2142
+ registerWidget("passage-ref-target", scoreNoop);
2143
+ registerWidget("video", scoreNoop);
2144
+
2145
+ const noScore = {
2146
+ type: "points",
2147
+ earned: 0,
2148
+ total: 0,
2149
+ message: null
2150
+ };
2151
+
2152
+ /**
2153
+ * If a widget says that it is empty once it is graded.
2154
+ * Trying to encapsulate references to the score format.
2155
+ */
2156
+ function scoreIsEmpty(score) {
2157
+ // HACK(benkomalo): ugh. this isn't great; the Perseus score objects
2158
+ // overload the type "invalid" for what should probably be three
2159
+ // distinct cases:
2160
+ // - truly empty or not fully filled out
2161
+ // - invalid or malformed inputs
2162
+ // - "almost correct" like inputs where the widget wants to give
2163
+ // feedback (e.g. a fraction needs to be reduced, or `pi` should
2164
+ // be used instead of 3.14)
2165
+ //
2166
+ // Unfortunately the coercion happens all over the place, as these
2167
+ // Perseus style score objects are created *everywhere* (basically
2168
+ // in every widget), so it's hard to change now. We assume that
2169
+ // anything with a "message" is not truly empty, and one of the
2170
+ // latter two cases for now.
2171
+ return score.type === "invalid" && (!score.message || score.message.length === 0);
2172
+ }
2173
+
2174
+ /**
2175
+ * Combine two score objects.
2176
+ *
2177
+ * Given two score objects for two different widgets, combine them so that
2178
+ * if one is wrong, the total score is wrong, etc.
2179
+ */
2180
+ function combineScores(scoreA, scoreB) {
2181
+ let message;
2182
+ if (scoreA.type === "points" && scoreB.type === "points") {
2183
+ if (scoreA.message && scoreB.message && scoreA.message !== scoreB.message) {
2184
+ // TODO(alpert): Figure out how to combine messages usefully
2185
+ message = null;
2186
+ } else {
2187
+ message = scoreA.message || scoreB.message;
2188
+ }
2189
+ return {
2190
+ type: "points",
2191
+ earned: scoreA.earned + scoreB.earned,
2192
+ total: scoreA.total + scoreB.total,
2193
+ message: message
2194
+ };
2195
+ }
2196
+ if (scoreA.type === "points" && scoreB.type === "invalid") {
2197
+ return scoreB;
2198
+ }
2199
+ if (scoreA.type === "invalid" && scoreB.type === "points") {
2200
+ return scoreA;
2201
+ }
2202
+ if (scoreA.type === "invalid" && scoreB.type === "invalid") {
2203
+ if (scoreA.message && scoreB.message && scoreA.message !== scoreB.message) {
2204
+ // TODO(alpert): Figure out how to combine messages usefully
2205
+ message = null;
2206
+ } else {
2207
+ message = scoreA.message || scoreB.message;
2208
+ }
2209
+ return {
2210
+ type: "invalid",
2211
+ message: message
2212
+ };
2213
+ }
2214
+
2215
+ /**
2216
+ * The above checks cover all combinations of score type, so if we get here
2217
+ * then something is amiss with our inputs.
2218
+ */
2219
+ throw new PerseusError("PerseusScore with unknown type encountered", Errors.InvalidInput, {
2220
+ metadata: {
2221
+ scoreA: JSON.stringify(scoreA),
2222
+ scoreB: JSON.stringify(scoreB)
2223
+ }
2224
+ });
2225
+ }
2226
+ function flattenScores(widgetScoreMap) {
2227
+ return Object.values(widgetScoreMap).reduce(combineScores, noScore);
2228
+ }
2229
+
2230
+ /**
2231
+ * score a Perseus item
2232
+ *
2233
+ * @param perseusRenderData - the full answer data, includes the correct answer
2234
+ * @param userInputMap - the user's input for each widget, mapped by ID
2235
+ * @param locale - string locale for math parsing ("de" 1.000,00 vs "en" 1,000.00)
2236
+ */
2237
+ function scorePerseusItem(perseusRenderData, userInputMap, locale) {
2238
+ // There seems to be a chance that PerseusRenderer.widgets might include
2239
+ // widget data for widgets that are not in PerseusRenderer.content,
2240
+ // so this checks that the widgets are being used before scoring them
2241
+ const usedWidgetIds = getWidgetIdsFromContent(perseusRenderData.content);
2242
+ const scores = scoreWidgetsFunctional(perseusRenderData.widgets, usedWidgetIds, userInputMap, locale);
2243
+ return flattenScores(scores);
2244
+ }
2245
+
2246
+ // TODO: combine scorePerseusItem with scoreWidgetsFunctional
2247
+ function scoreWidgetsFunctional(widgets,
2248
+ // This is a port of old code, I'm not sure why
2249
+ // we need widgetIds vs the keys of the widgets object
2250
+ widgetIds, userInputMap, locale) {
2251
+ const upgradedWidgets = getUpgradedWidgetOptions(widgets);
2252
+ const gradedWidgetIds = widgetIds.filter(id => {
2253
+ const props = upgradedWidgets[id];
2254
+ const widgetIsGraded = (props == null ? void 0 : props.graded) == null || props.graded;
2255
+ const widgetIsStatic = !!(props != null && props.static);
2256
+ // Ungraded widgets or widgets set to static shouldn't be graded.
2257
+ return widgetIsGraded && !widgetIsStatic;
2258
+ });
2259
+ const widgetScores = {};
2260
+ gradedWidgetIds.forEach(id => {
2261
+ var _validator;
2262
+ const widget = upgradedWidgets[id];
2263
+ if (!widget) {
2264
+ return;
2265
+ }
2266
+ const userInput = userInputMap[id];
2267
+ const validator = getWidgetValidator(widget.type);
2268
+ const scorer = getWidgetScorer(widget.type);
2269
+
2270
+ // We do validation (empty checks) first and then scoring. If
2271
+ // validation fails, it's result is itself a PerseusScore.
2272
+ const score = (_validator = validator == null ? void 0 : validator(userInput, widget.options, locale)) != null ? _validator : scorer == null ? void 0 : scorer(userInput, widget.options, locale);
2273
+ if (score != null) {
2274
+ widgetScores[id] = score;
2275
+ }
2276
+ });
2277
+ return widgetScores;
2278
+ }
2279
+
2280
+ export { ErrorCodes, KhanAnswerTypes, emptyWidgetsFunctional, flattenScores, getWidgetScorer, getWidgetValidator, inputNumberAnswerTypes, registerWidget, scoreCSProgram, scoreCategorizer, scoreDropdown, scoreExpression, scoreGrapher, scoreIframe, scoreInputNumber, scoreInteractiveGraph, scoreLabelImage, scoreLabelImageMarker, scoreMatcher, scoreMatrix, scoreNumberLine, scoreNumericInput, scoreOrderer, scorePerseusItem, scorePlotter, scoreRadio, scoreSorter, scoreTable, scoreWidgetsFunctional, validateCategorizer, validateDropdown, validateExpression, validateMatrix, validateNumberLine, validateOrderer, validatePlotter, validateRadio, validateSorter, validateTable };
2281
+ //# sourceMappingURL=index.js.map