@pie-element/placement-ordering 12.0.1 → 12.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/controller.js DELETED
@@ -1,972 +0,0 @@
1
- import _ from 'lodash';
2
- import debug from 'debug';
3
- import { getFeedbackForCorrectness } from '@pie-lib/feedback';
4
- import { partialScoring } from '@pie-lib/controller-utils';
5
- import isEqual from 'lodash/isEqual';
6
- import isEmpty from 'lodash/isEmpty';
7
- import Translator from '@pie-lib/translator';
8
-
9
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
10
- try {
11
- var info = gen[key](arg);
12
- var value = info.value;
13
- } catch (error) {
14
- reject(error);
15
- return;
16
- }
17
-
18
- if (info.done) {
19
- resolve(value);
20
- } else {
21
- Promise.resolve(value).then(_next, _throw);
22
- }
23
- }
24
-
25
- function _asyncToGenerator(fn) {
26
- return function () {
27
- var self = this,
28
- args = arguments;
29
- return new Promise(function (resolve, reject) {
30
- var gen = fn.apply(self, args);
31
-
32
- function _next(value) {
33
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
34
- }
35
-
36
- function _throw(err) {
37
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
38
- }
39
-
40
- _next(undefined);
41
- });
42
- };
43
- }
44
-
45
- function _defineProperty(obj, key, value) {
46
- if (key in obj) {
47
- Object.defineProperty(obj, key, {
48
- value: value,
49
- enumerable: true,
50
- configurable: true,
51
- writable: true
52
- });
53
- } else {
54
- obj[key] = value;
55
- }
56
-
57
- return obj;
58
- }
59
-
60
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
61
-
62
- var combinatorics = {exports: {}};
63
-
64
- /*
65
- * $Id: combinatorics.js,v 0.25 2013/03/11 15:42:14 dankogai Exp dankogai $
66
- *
67
- * Licensed under the MIT license.
68
- * http://www.opensource.org/licenses/mit-license.php
69
- *
70
- * References:
71
- * http://www.ruby-doc.org/core-2.0/Array.html#method-i-combination
72
- * http://www.ruby-doc.org/core-2.0/Array.html#method-i-permutation
73
- * http://en.wikipedia.org/wiki/Factorial_number_system
74
- */
75
-
76
- (function (module, exports) {
77
- (function (root, factory) {
78
- {
79
- module.exports = factory();
80
- }
81
- }(commonjsGlobal, function () {
82
- var version = "0.5.5";
83
- /* combinatory arithmetics */
84
- var P = function(m, n) {
85
- if (n % 1 !== 0) throw new RangeError;
86
- var p = 1;
87
- while (n--) p *= m--;
88
- return p;
89
- };
90
- var C = function(m, n) {
91
- if (n > m) {
92
- return 0;
93
- }
94
- return P(m, n) / P(n, n);
95
- };
96
- var factorial = function(n) {
97
- return P(n, n);
98
- };
99
- var factoradic = function(n, d) {
100
- var f = 1;
101
- if (!d) {
102
- for (d = 1; f < n; f *= ++d);
103
- if (f > n) f /= d--;
104
- } else {
105
- f = factorial(d);
106
- }
107
- var result = [0];
108
- for (; d; f /= d--) {
109
- result[d] = Math.floor(n / f);
110
- n %= f;
111
- }
112
- return result;
113
- };
114
- /* common methods */
115
- var addProperties = function(dst, src) {
116
- Object.keys(src).forEach(function(p) {
117
- Object.defineProperty(dst, p, {
118
- value: src[p],
119
- configurable: p == 'next'
120
- });
121
- });
122
- };
123
- var hideProperty = function(o, p) {
124
- Object.defineProperty(o, p, {
125
- writable: true
126
- });
127
- };
128
- var toArray = function(f) {
129
- var e, result = [];
130
- this.init();
131
- while (e = this.next()) result.push(f ? f(e) : e);
132
- this.init();
133
- return result;
134
- };
135
- var common = {
136
- toArray: toArray,
137
- map: toArray,
138
- forEach: function(f) {
139
- var e;
140
- this.init();
141
- while (e = this.next()) f(e);
142
- this.init();
143
- },
144
- filter: function(f) {
145
- var e, result = [];
146
- this.init();
147
- while (e = this.next()) if (f(e)) result.push(e);
148
- this.init();
149
- return result;
150
- },
151
- find: function(f) {
152
- var e, result;
153
- this.init();
154
- while (e = this.next()) {
155
- if (f(e)) {
156
- result = e;
157
- break;
158
- }
159
- }
160
- this.init();
161
- return result;
162
- },
163
- reduce: function(reducer, result) {
164
- // return this.toArray().reduce(reducer, init);
165
- this.init();
166
- var index = 0;
167
- if (arguments.length < 2) {
168
- result = this.next();
169
- index += 1;
170
- }
171
- var length = this.length;
172
- while(index < length) {
173
- result = reducer(result, this.next(), index, this);
174
- index += 1;
175
- }
176
- return result;
177
- },
178
- lazyMap: function(f) {
179
- this._lazyMap = f;
180
- return this;
181
- },
182
- lazyFilter: function(f) {
183
- Object.defineProperty(this, 'next', {
184
- writable: true
185
- });
186
- if (typeof f !== 'function') {
187
- this.next = this._next;
188
- } else {
189
- if (typeof (this._next) !== 'function') {
190
- this._next = this.next;
191
- }
192
- var _next = this._next.bind(this);
193
- this.next = (function() {
194
- var e;
195
- while (e = _next()) {
196
- if (f(e))
197
- return e;
198
- }
199
- return e;
200
- }).bind(this);
201
- }
202
- Object.defineProperty(this, 'next', {
203
- writable: false
204
- });
205
- return this;
206
- }
207
-
208
- };
209
- /* power set */
210
- var power = function(ary, fun) {
211
- var size = 1 << ary.length,
212
- sizeOf = function() {
213
- return size;
214
- },
215
- that = Object.create(ary.slice(), {
216
- length: {
217
- get: sizeOf
218
- }
219
- });
220
- hideProperty(that, 'index');
221
- addProperties(that, {
222
- valueOf: sizeOf,
223
- init: function() {
224
- that.index = 0;
225
- },
226
- nth: function(n) {
227
- if (n >= size) return;
228
- var i = 0,
229
- result = [];
230
- for (; n; n >>>= 1, i++) if (n & 1) result.push(this[i]);
231
- return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;
232
- },
233
- next: function() {
234
- return this.nth(this.index++);
235
- }
236
- });
237
- addProperties(that, common);
238
- that.init();
239
- return (typeof (fun) === 'function') ? that.map(fun) : that;
240
- };
241
- /* combination */
242
- var nextIndex = function(n) {
243
- var smallest = n & -n,
244
- ripple = n + smallest,
245
- new_smallest = ripple & -ripple,
246
- ones = ((new_smallest / smallest) >> 1) - 1;
247
- return ripple | ones;
248
- };
249
- var combination = function(ary, nelem, fun) {
250
- if (!nelem) nelem = ary.length;
251
- if (nelem < 1) throw new RangeError;
252
- if (nelem > ary.length) throw new RangeError;
253
- var first = (1 << nelem) - 1,
254
- size = C(ary.length, nelem),
255
- maxIndex = 1 << ary.length,
256
- sizeOf = function() {
257
- return size;
258
- },
259
- that = Object.create(ary.slice(), {
260
- length: {
261
- get: sizeOf
262
- }
263
- });
264
- hideProperty(that, 'index');
265
- addProperties(that, {
266
- valueOf: sizeOf,
267
- init: function() {
268
- this.index = first;
269
- },
270
- next: function() {
271
- if (this.index >= maxIndex) return;
272
- var i = 0,
273
- n = this.index,
274
- result = [];
275
- for (; n; n >>>= 1, i++) {
276
- if (n & 1) result[result.length] = this[i];
277
- }
278
-
279
- this.index = nextIndex(this.index);
280
- return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;
281
- }
282
- });
283
- addProperties(that, common);
284
- that.init();
285
- return (typeof (fun) === 'function') ? that.map(fun) : that;
286
- };
287
- /* bigcombination */
288
- var bigNextIndex = function(n, nelem) {
289
-
290
- var result = n;
291
- var j = nelem;
292
- var i = 0;
293
- for (i = result.length - 1; i >= 0; i--) {
294
- if (result[i] == 1) {
295
- j--;
296
- } else {
297
- break;
298
- }
299
- }
300
- if (j == 0) {
301
- // Overflow
302
- result[result.length] = 1;
303
- for (var k = result.length - 2; k >= 0; k--) {
304
- result[k] = (k < nelem-1)?1:0;
305
- }
306
- } else {
307
- // Normal
308
-
309
- // first zero after 1
310
- var i1 = -1;
311
- var i0 = -1;
312
- for (var i = 0; i < result.length; i++) {
313
- if (result[i] == 0 && i1 != -1) {
314
- i0 = i;
315
- }
316
- if (result[i] == 1) {
317
- i1 = i;
318
- }
319
- if (i0 != -1 && i1 != -1) {
320
- result[i0] = 1;
321
- result[i1] = 0;
322
- break;
323
- }
324
- }
325
-
326
- j = nelem;
327
- for (var i = result.length - 1; i >= i1; i--) {
328
- if (result[i] == 1)
329
- j--;
330
- }
331
- for (var i = 0; i < i1; i++) {
332
- result[i] = (i < j)?1:0;
333
- }
334
- }
335
-
336
- return result;
337
-
338
- };
339
- var buildFirst = function(nelem) {
340
- var result = [];
341
- for (var i = 0; i < nelem; i++) {
342
- result[i] = 1;
343
- }
344
- result[0] = 1;
345
- return result;
346
- };
347
- var bigCombination = function(ary, nelem, fun) {
348
- if (!nelem) nelem = ary.length;
349
- if (nelem < 1) throw new RangeError;
350
- if (nelem > ary.length) throw new RangeError;
351
- var first = buildFirst(nelem),
352
- size = C(ary.length, nelem),
353
- maxIndex = ary.length,
354
- sizeOf = function() {
355
- return size;
356
- },
357
- that = Object.create(ary.slice(), {
358
- length: {
359
- get: sizeOf
360
- }
361
- });
362
- hideProperty(that, 'index');
363
- addProperties(that, {
364
- valueOf: sizeOf,
365
- init: function() {
366
- this.index = first.concat();
367
- },
368
- next: function() {
369
- if (this.index.length > maxIndex) return;
370
- var i = 0,
371
- n = this.index,
372
- result = [];
373
- for (var j = 0; j < n.length; j++, i++) {
374
- if (n[j])
375
- result[result.length] = this[i];
376
- }
377
- bigNextIndex(this.index, nelem);
378
- return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;
379
- }
380
- });
381
- addProperties(that, common);
382
- that.init();
383
- return (typeof (fun) === 'function') ? that.map(fun) : that;
384
- };
385
- /* permutation */
386
- var _permutation = function(ary) {
387
- var that = ary.slice(),
388
- size = factorial(that.length);
389
- that.index = 0;
390
- that.next = function() {
391
- if (this.index >= size) return;
392
- var copy = this.slice(),
393
- digits = factoradic(this.index, this.length),
394
- result = [],
395
- i = this.length - 1;
396
- for (; i >= 0; --i) result.push(copy.splice(digits[i], 1)[0]);
397
- this.index++;
398
- return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;
399
- };
400
- return that;
401
- };
402
- // which is really a permutation of combination
403
- var permutation = function(ary, nelem, fun) {
404
- if (!nelem) nelem = ary.length;
405
- if (nelem < 1) throw new RangeError;
406
- if (nelem > ary.length) throw new RangeError;
407
- var size = P(ary.length, nelem),
408
- sizeOf = function() {
409
- return size;
410
- },
411
- that = Object.create(ary.slice(), {
412
- length: {
413
- get: sizeOf
414
- }
415
- });
416
- hideProperty(that, 'cmb');
417
- hideProperty(that, 'per');
418
- addProperties(that, {
419
- valueOf: function() {
420
- return size;
421
- },
422
- init: function() {
423
- /* combination can only be used for less than 31 elements */
424
- if (ary.length < 31) {
425
- this.cmb = combination(ary, nelem);
426
- } else {
427
- this.cmb = bigCombination(ary, nelem);
428
- }
429
-
430
- this.per = _permutation(this.cmb.next());
431
- },
432
- next: function() {
433
- var result = this.per.next();
434
- if (!result) {
435
- var cmb = this.cmb.next();
436
- if (!cmb) return;
437
- this.per = _permutation(cmb);
438
- return this.next();
439
- }
440
- return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;
441
- }
442
- });
443
- addProperties(that, common);
444
- that.init();
445
- return (typeof (fun) === 'function') ? that.map(fun) : that;
446
- };
447
-
448
- var PC = function(m) {
449
- var total = 0;
450
- for (var n = 1; n <= m; n++) {
451
- var p = P(m,n);
452
- total += p;
453
- } return total;
454
- };
455
- // which is really a permutation of combination
456
- var permutationCombination = function(ary, fun) {
457
- // if (!nelem) nelem = ary.length;
458
- // if (nelem < 1) throw new RangeError;
459
- // if (nelem > ary.length) throw new RangeError;
460
- var size = PC(ary.length),
461
- sizeOf = function() {
462
- return size;
463
- },
464
- that = Object.create(ary.slice(), {
465
- length: {
466
- get: sizeOf
467
- }
468
- });
469
- hideProperty(that, 'cmb');
470
- hideProperty(that, 'per');
471
- hideProperty(that, 'nelem');
472
- addProperties(that, {
473
- valueOf: function() {
474
- return size;
475
- },
476
- init: function() {
477
- this.nelem = 1;
478
- // console.log("Starting nelem: " + this.nelem);
479
- this.cmb = combination(ary, this.nelem);
480
- this.per = _permutation(this.cmb.next());
481
- },
482
- next: function() {
483
- var result = this.per.next();
484
- if (!result) {
485
- var cmb = this.cmb.next();
486
- if (!cmb) {
487
- this.nelem++;
488
- // console.log("increment nelem: " + this.nelem + " vs " + ary.length);
489
- if (this.nelem > ary.length) return;
490
- this.cmb = combination(ary, this.nelem);
491
- cmb = this.cmb.next();
492
- if (!cmb) return;
493
- }
494
- this.per = _permutation(cmb);
495
- return this.next();
496
- }
497
- return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;
498
- }
499
- });
500
- addProperties(that, common);
501
- that.init();
502
- return (typeof (fun) === 'function') ? that.map(fun) : that;
503
- };
504
- /* Cartesian Product */
505
- var arraySlice = Array.prototype.slice;
506
- var cartesianProduct = function() {
507
- if (!arguments.length) throw new RangeError;
508
- var args = arraySlice.call(arguments),
509
- size = args.reduce(function(p, a) {
510
- return p * a.length;
511
- }, 1),
512
- sizeOf = function() {
513
- return size;
514
- },
515
- dim = args.length,
516
- that = Object.create(args, {
517
- length: {
518
- get: sizeOf
519
- }
520
- });
521
- if (!size) throw new RangeError;
522
- hideProperty(that, 'index');
523
- addProperties(that, {
524
- valueOf: sizeOf,
525
- dim: dim,
526
- init: function() {
527
- this.index = 0;
528
- },
529
- get: function() {
530
- if (arguments.length !== this.length) return;
531
- var result = [],
532
- d = 0;
533
- for (; d < dim; d++) {
534
- var i = arguments[d];
535
- if (i >= this[d].length) return;
536
- result.push(this[d][i]);
537
- }
538
- return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;
539
- },
540
- nth: function(n) {
541
- var result = [],
542
- d = 0;
543
- for (; d < dim; d++) {
544
- var l = this[d].length;
545
- var i = n % l;
546
- result.push(this[d][i]);
547
- n -= i;
548
- n /= l;
549
- }
550
- return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;
551
- },
552
- next: function() {
553
- if (this.index >= size) return;
554
- var result = this.nth(this.index);
555
- this.index++;
556
- return result;
557
- }
558
- });
559
- addProperties(that, common);
560
- that.init();
561
- return that;
562
- };
563
- /* baseN */
564
- var baseN = function(ary, nelem, fun) {
565
- if (!nelem) nelem = ary.length;
566
- if (nelem < 1) throw new RangeError;
567
- var base = ary.length,
568
- size = Math.pow(base, nelem);
569
- var sizeOf = function() {
570
- return size;
571
- },
572
- that = Object.create(ary.slice(), {
573
- length: {
574
- get: sizeOf
575
- }
576
- });
577
- hideProperty(that, 'index');
578
- addProperties(that, {
579
- valueOf: sizeOf,
580
- init: function() {
581
- that.index = 0;
582
- },
583
- nth: function(n) {
584
- if (n >= size) return;
585
- var result = [];
586
- for (var i = 0; i < nelem; i++) {
587
- var d = n % base;
588
- result.push(ary[d]);
589
- n -= d; n /= base;
590
- }
591
- return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;
592
- },
593
- next: function() {
594
- return this.nth(this.index++);
595
- }
596
- });
597
- addProperties(that, common);
598
- that.init();
599
- return (typeof (fun) === 'function') ? that.map(fun) : that;
600
- };
601
-
602
- /* export */
603
- var Combinatorics = Object.create(null);
604
- addProperties(Combinatorics, {
605
- C: C,
606
- P: P,
607
- factorial: factorial,
608
- factoradic: factoradic,
609
- cartesianProduct: cartesianProduct,
610
- combination: combination,
611
- bigCombination: bigCombination,
612
- permutation: permutation,
613
- permutationCombination: permutationCombination,
614
- power: power,
615
- baseN: baseN,
616
- VERSION: version
617
- });
618
- return Combinatorics;
619
- }));
620
- }(combinatorics));
621
-
622
- function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
623
-
624
- function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
625
- var log$1 = debug('pie-elements:placement-ordering:controller');
626
- var illegalArgumentError = answer => new Error("Cant score answer: ".concat(answer, " it has duplicates and allowDuplicates is false"));
627
- var pairwiseCombinationScore = (correct, answer, opts) => {
628
- opts = _objectSpread$1({
629
- allowDuplicates: false,
630
- orderMustBeComplete: false
631
- }, opts);
632
-
633
- if (!opts.allowDuplicates && !_.isEqual(_.uniq(correct), correct)) {
634
- throw illegalArgumentError(answer);
635
- }
636
-
637
- if (opts.allowDuplicates === false && answer.length !== _.uniq(answer).length) {
638
- return 0;
639
- }
640
-
641
- answer = opts.allowDuplicates !== false ? answer : _.uniq(answer);
642
- log$1('answer:', answer);
643
-
644
- if (!Array.isArray(correct) || correct.length === 0) {
645
- throw new Error('correct must be non empty an array');
646
- }
647
-
648
- if (correct.length === 1) {
649
- return _.isEqual(correct, answer) ? 1 : 0;
650
- }
651
-
652
- if (!Array.isArray(answer) || answer.length < 2) {
653
- return 0;
654
- }
655
-
656
- if (answer.length > correct.length) {
657
- return 0;
658
- }
659
-
660
- if (correct.length !== answer.length && opts.orderMustBeComplete) {
661
- return 0;
662
- }
663
-
664
- var correctCombo = combinatorics.exports.combination(correct, 2).toArray();
665
- var answerCombo = combinatorics.exports.combination(answer, 2).toArray();
666
-
667
- var diff = _.differenceWith(answerCombo, correctCombo, _.isEqual);
668
-
669
- var comboLengthDiff = correctCombo.length - answerCombo.length;
670
- var total = correctCombo.length;
671
- var actual = total - diff.length - comboLengthDiff;
672
- var n = (actual / total).toFixed(2);
673
- return parseFloat(n);
674
- };
675
- /**
676
- * Flattens the correctResponse into an array of ordered identifiers representing the
677
- * correct response.
678
- */
679
-
680
- var flattenCorrect = question => question.correctResponse ? question.correctResponse.map(r => r && r.id ? r.id : r) : [];
681
- /**
682
- * Returns all correct responses for this question
683
- * @param question - array
684
- */
685
-
686
- var getAllCorrectResponses = question => {
687
- var alternates = (question.alternateResponses || []).map(alternate => {
688
- if (Array.isArray(alternate)) {
689
- return alternate;
690
- }
691
-
692
- return alternate.response;
693
- }).filter(item => item !== undefined);
694
- return [flattenCorrect(question), ...alternates];
695
- };
696
- /**
697
- * Returns the score for a session. If weighted scoring is present in the correctResponse
698
- * field for the question, this will be used. If partial scoring is present in the question
699
- * model, this will be used. Otherwise the default scoring mechanism (0 for any incorrect, 1
700
- * for all correct) will be used.
701
- */
702
-
703
- var score = (question, session) => {
704
- var {
705
- value
706
- } = session || {};
707
-
708
- if (!value) {
709
- return 0;
710
- }
711
-
712
- var allCorrectResponse = getAllCorrectResponses(question);
713
- var allowDuplicates = (question.configure && question.configure.removeTilesAfterPlacing) !== false;
714
- /**
715
- * We require this to be the case - locking
716
- */
717
- //const orderMustBeComplete = true;
718
-
719
- var bestScore = 0;
720
- allCorrectResponse.forEach(cr => {
721
- var currentScore = pairwiseCombinationScore(cr, value, {
722
- allowDuplicates
723
- });
724
-
725
- if (currentScore >= bestScore) {
726
- bestScore = currentScore;
727
- }
728
- });
729
- return bestScore;
730
- };
731
-
732
- var defaults = {
733
- choiceLabel: '',
734
- choiceLabelEnabled: true,
735
- choices: [],
736
- correctResponse: [],
737
- feedbackEnabled: false,
738
- numberedGuides: false,
739
- orientation: 'vertical',
740
- partialScoring: true,
741
- placementArea: false,
742
- prompt: '',
743
- promptEnabled: true,
744
- rationale: '',
745
- rationaleEnabled: true,
746
- removeTilesAfterPlacing: true,
747
- scoringType: 'auto',
748
- studentInstructionsEnabled: true,
749
- targetLabel: '',
750
- teacherInstructions: '',
751
- teacherInstructionsEnabled: true,
752
- toolbarEditorPosition: 'bottom'
753
- };
754
-
755
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
756
-
757
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
758
- var log = debug('@pie-element:placement-ordering:controller');
759
- var {
760
- translator
761
- } = Translator;
762
- var questionError = () => new Error('Question is missing required array: correctResponse');
763
- function outcome(question, session, env) {
764
- return new Promise((resolve, reject) => {
765
- if (!session || _.isEmpty(session)) {
766
- resolve({
767
- score: 0,
768
- empty: true
769
- });
770
- }
771
-
772
- if (!question || !question.correctResponse || _.isEmpty(question.correctResponse)) {
773
- reject(questionError());
774
- } else {
775
- try {
776
- var s = score(question, session);
777
- var finalScore = partialScoring.enabled(question, env || {}) ? s : s === 1 ? 1 : 0;
778
- resolve({
779
- score: finalScore
780
- });
781
- } catch (e) {
782
- reject(e);
783
- }
784
- }
785
- });
786
- }
787
- function createDefaultModel() {
788
- var model = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
789
- return new Promise(resolve => {
790
- resolve(_objectSpread(_objectSpread({}, defaults), model));
791
- });
792
- }
793
- var normalize = question => _objectSpread(_objectSpread({}, defaults), {}, {
794
- rationaleEnabled: true,
795
- feedbackEnabled: false,
796
- promptEnabled: true,
797
- teacherInstructionsEnabled: true,
798
- studentInstructionsEnabled: true
799
- }, question);
800
- /**
801
- *
802
- * @param {*} question
803
- * @param {*} session
804
- * @param {*} env
805
- */
806
-
807
- function model(question, session, env) {
808
- return new Promise( /*#__PURE__*/function () {
809
- var _ref = _asyncToGenerator(function* (resolve) {
810
- var normalizedQuestion = normalize(question);
811
- var base = {};
812
-
813
- if (question.alternateResponses && _.every(question.alternateResponses, _.isArray)) {
814
- log('Deprecated structure of alternateResponses is in use'); // eslint-disable-next-line no-console
815
-
816
- console.error('Deprecated structure of alternateResponses is in use');
817
- }
818
-
819
- base.env = env;
820
- base.extraCSSRules = normalizedQuestion.extraCSSRules;
821
- base.outcomes = [];
822
- base.completeLength = (normalizedQuestion.correctResponse || []).length;
823
- base.choices = (normalizedQuestion.choices || []).filter(choice => choice.label);
824
- base.note = normalizedQuestion.note;
825
- base.showNote = normalizedQuestion.alternateResponses && normalizedQuestion.alternateResponses.length > 0;
826
- base.language = normalizedQuestion.language;
827
- log('[model] removing tileSize for the moment.');
828
- base.prompt = normalizedQuestion.promptEnabled ? normalizedQuestion.prompt : null;
829
- base.config = {
830
- orientation: normalizedQuestion.orientation || 'vertical',
831
- includeTargets: normalizedQuestion.placementArea,
832
- choiceLabelEnabled: normalizedQuestion.choiceLabelEnabled,
833
- targetLabel: normalizedQuestion.targetLabel,
834
- choiceLabel: normalizedQuestion.choiceLabel,
835
- showOrdering: normalizedQuestion.numberedGuides,
836
- allowSameChoiceInTargets: !normalizedQuestion.removeTilesAfterPlacing
837
- };
838
- base.disabled = env.mode !== 'gather';
839
-
840
- if (!base.note) {
841
- base.note = translator.t('common:commonCorrectAnswerWithAlternates', {
842
- lng: normalizedQuestion.language
843
- });
844
- }
845
-
846
- if (env.role === 'instructor' && (env.mode === 'view' || env.mode === 'evaluate')) {
847
- base.rationale = normalizedQuestion.rationaleEnabled ? normalizedQuestion.rationale : null;
848
- base.teacherInstructions = normalizedQuestion.teacherInstructionsEnabled ? normalizedQuestion.teacherInstructions : null;
849
- } else {
850
- base.rationale = null;
851
- base.teacherInstructions = null;
852
- }
853
-
854
- if (env.mode === 'evaluate') {
855
- var value = session && session.value || [];
856
- var allCorrectResponses = getAllCorrectResponses(normalizedQuestion);
857
- var bestSetOfResponses = allCorrectResponses.reduce((info, cr) => {
858
- var currentScore = _.reduce(value, (acc, c, idx) => acc + (Array.isArray(cr) && cr[idx] === c ? 1 : 0), 0);
859
-
860
- if (currentScore > info.score) {
861
- return {
862
- arr: cr,
863
- score: currentScore
864
- };
865
- }
866
-
867
- return info;
868
- }, {
869
- arr: [],
870
- score: 0
871
- });
872
- base.outcomes = _.map(value, (c, idx) => {
873
- return {
874
- id: c,
875
- outcome: bestSetOfResponses.arr[idx] === c ? 'correct' : 'incorrect'
876
- };
877
- });
878
- var isResponseCorrect = allCorrectResponses.some(response => _.isEqual(response, value));
879
- var responseScore = score(question, session);
880
- var isCorrect = responseScore === 1;
881
- var isPartialCorrect = !isCorrect && partialScoring.enabled(normalizedQuestion, env || {}) && responseScore !== 0;
882
- base.correctness = isCorrect ? 'correct' : isPartialCorrect ? 'partial' : 'incorrect';
883
-
884
- if (!isResponseCorrect) {
885
- base.correctResponse = flattenCorrect(normalizedQuestion);
886
- } // requirement made in PD-2182
887
-
888
-
889
- if (!normalizedQuestion.feedback) {
890
- normalizedQuestion.feedbackEnabled = false;
891
- }
892
-
893
- var fb = normalizedQuestion.feedbackEnabled ? getFeedbackForCorrectness(base.correctness, normalizedQuestion.feedback) : Promise.resolve(undefined);
894
- fb.then(feedback => {
895
- base.feedback = feedback;
896
- resolve(base);
897
- });
898
- } else {
899
- resolve(base);
900
- }
901
- });
902
-
903
- return function (_x) {
904
- return _ref.apply(this, arguments);
905
- };
906
- }());
907
- }
908
- var createCorrectResponseSession = (question, env) => {
909
- return new Promise(resolve => {
910
- if (env.mode !== 'evaluate' && env.role === 'instructor') {
911
- resolve({
912
- id: '1',
913
- value: flattenCorrect(question)
914
- });
915
- } else {
916
- resolve(null);
917
- }
918
- });
919
- }; // remove all html tags
920
-
921
-
922
- var getContent = html => (html || '').replace(/(<(?!img|iframe|source)([^>]+)>)/gi, '');
923
-
924
- var validate = function validate() {
925
- var model = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
926
- var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
927
- var {
928
- choices,
929
- correctResponse
930
- } = model;
931
- var errors = {};
932
- ['teacherInstructions', 'prompt', 'rationale'].forEach(field => {
933
- var _config$field;
934
-
935
- if ((_config$field = config[field]) !== null && _config$field !== void 0 && _config$field.required && !getContent(model[field])) {
936
- errors[field] = 'This field is required.';
937
- }
938
- });
939
- var reversedChoices = [...(choices || [])].reverse();
940
- var choicesErrors = {};
941
- reversedChoices.forEach((choice, index) => {
942
- var {
943
- id,
944
- label
945
- } = choice;
946
-
947
- if (!getContent(label)) {
948
- choicesErrors[id] = 'Content should not be empty.';
949
- } else {
950
- var identicalAnswer = reversedChoices.slice(index + 1).some(c => c.label === label);
951
-
952
- if (identicalAnswer) {
953
- choicesErrors[id] = 'Content should be unique.';
954
- }
955
- }
956
- });
957
- var choicesIds = (choices || []).map(choice => choice.id);
958
- var correctResponseIds = (correctResponse || []).map(response => response.id || response);
959
-
960
- if (isEqual(choicesIds, correctResponseIds)) {
961
- errors.orderError = 'The correct ordering should not be identical to the initial ordering.';
962
- }
963
-
964
- if (!isEmpty(choicesErrors)) {
965
- errors.choicesErrors = choicesErrors;
966
- }
967
-
968
- return errors;
969
- };
970
-
971
- export { createCorrectResponseSession, createDefaultModel, model, normalize, outcome, questionError, validate };
972
- //# sourceMappingURL=controller.js.map