-
Notifications
You must be signed in to change notification settings - Fork 118
/
part.js
2317 lines (2212 loc) · 89.3 KB
/
part.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2011-14 Newcastle University
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/** @file {@link Numbas.parts}, {@link Numbas.partConstructors}, {@link Numbas.createPart} and the generic {@link Numbas.parts.Part} object */
Numbas.queueScript('part',['base','jme','jme-variables','util','marking'],function() {
var util = Numbas.util;
var jme = Numbas.jme;
var math = Numbas.math;
var marking = Numbas.marking;
var SAVE_STAGED_ANSWER_FREQUENCY = 5000;
/** Definitions of custom part types.
*
* @name custom_part_types
* @type {object}
* @memberof Numbas
*/
/** A unique identifier for a {@link Numbas.parts.Part} object, of the form `qXpY[gZ|sZ]`. Numbering starts from zero, and the `gZ` bit is used only when the part is a gap, and `sZ` is used if it's a step.
*
* @typedef Numbas.parts.partpath
* @type {string}
*/
/** Part type constructors.
* These functions aren't called directly - they're the original part constructor objects before they're extended with the generic part methods, kept for reference so their methods can be reused by other parts.
*
* @see Numbas.partConstructors
* @namespace Numbas.parts
* @memberof Numbas
*/
Numbas.parts = {};
/** Associate part type names with their object constructors.
* These constructors are called by {@link Numbas.createPart} - they should be finalised constructors with all the generic part methods implemented.
* Most often, you do this by extending {@link Numbas.parts.Part}.
*
* @memberof Numbas
*/
var partConstructors = Numbas.partConstructors = {};
/** Create a question part based on an XML definition.
*
* @memberof Numbas
* @param {number} index - The index of the part's definition.
* @param {Element} xml
* @param {Numbas.parts.partpath} [path]
* @param {Numbas.Question} [question]
* @param {Numbas.parts.Part} [parentPart]
* @param {Numbas.storage.BlankStorage} [store] - The storage engine to use.
* @param {Numbas.jme.Scope} [scope] - Scope in which the part should evaluate JME expressions. If not given, the question's scope or {@link Numbas.jme.builtinScope} are used.
* @fires Numbas.Part#event:finaliseLoad
* @returns {Numbas.parts.Part}
* @throws {Numbas.Error} "part.missing type attribute" if the top node in `xml` doesn't have a "type" attribute.
*/
var createPartFromXML = Numbas.createPartFromXML = function(index, xml, path, question, parentPart, store, scope) {
var tryGetAttribute = Numbas.xml.tryGetAttribute;
var type = tryGetAttribute(null,xml,'.','type',[]);
if(type==null) {
throw(new Numbas.Error('part.missing type attribute',{part:util.nicePartName(path)}));
}
var part = createPart(index, type, path, question, parentPart, store, scope);
try {
part.loadFromXML(xml);
part.finaliseLoad();
part.signals.trigger('finaliseLoad');
if(Numbas.display && part.question && part.question.display) {
part.initDisplay();
}
} catch(e) {
if(e.originalMessage=='part.error') {
throw(e);
}
part.error(e.message,{},e);
}
return part;
}
/** Create a question part based on an XML definition.
*
* @memberof Numbas
* @param {number} index - The index of the part's definition.
* @param {object} data
* @param {Numbas.parts.partpath} [path]
* @param {Numbas.Question} [question]
* @param {Numbas.parts.Part} [parentPart]
* @param {Numbas.storage.BlankStorage} [store] - The storage engine to use.
* @param {Numbas.jme.Scope} [scope] - Scope in which the part should evaluate JME expressions. If not given, the question's scope or {@link Numbas.jme.builtinScope} are used.
* @fires Numbas.Part#event:finaliseLoad
* @returns {Numbas.parts.Part}
* @throws {Numbas.Error} "part.missing type attribute" if `data` doesn't have a "type" attribute.
*/
var createPartFromJSON = Numbas.createPartFromJSON = function(index, data, path, question, parentPart, store, scope) {
if(!data.type) {
throw(new Numbas.Error('part.missing type attribute',{part:util.nicePartName(path)}));
}
var part = createPart(index, data.type, path, question, parentPart, store, scope);
part.loadFromJSON(data);
part.finaliseLoad();
part.signals.trigger('finaliseLoad');
return part;
}
/** Create a new question part.
*
* @see Numbas.partConstructors
* @param {number} index - The index of the part's definition.
* @param {string} type
* @param {Numbas.parts.partpath} path
* @param {Numbas.Question} question
* @param {Numbas.parts.Part} parentPart
* @param {Numbas.storage.BlankStorage} [store] - The storage engine to use.
* @param {Numbas.jme.Scope} [scope] - Scope in which the part should evaluate JME expressions. If not given, the question's scope or {@link Numbas.jme.builtinScope} are used.
* @returns {Numbas.parts.Part}
* @throws {Numbas.Error} "part.unknown type" if the given part type is not in {@link Numbas.partConstructors}
* @memberof Numbas
*/
var createPart = Numbas.createPart = function(index, type, path, question, parentPart, store, scope)
{
if(partConstructors[type])
{
var cons = partConstructors[type];
var part = new cons(index, path, question, parentPart, store);
part.type = type;
part.scope = part.makeScope(scope);
return part;
}
else {
throw(new Numbas.Error('part.unknown type',{part:util.nicePartName(path),type:type}));
}
}
/** Base question part object.
*
* @class
* @memberof Numbas.parts
* @param {number} index - The index of the part's definition.
* @param {Numbas.parts.partpath} [path='p0']
* @param {Numbas.Question} question
* @param {Numbas.parts.Part} parentPart
* @param {Numbas.storage.BlankStorage} [store]
* @property {boolean} isStep - Is this part a step?
* @property {boolean} isGap - Is this part a gap?
* @property {string} full_path - A globally-unique path to this part, including the parent question's number.
* @see Numbas.createPart
*/
var Part = Numbas.parts.Part = function(index, path, question, parentPart, store)
{
var p = this;
p.signals = new Numbas.schedule.SignalBox();
p.events = new Numbas.schedule.EventBox();
this.index = index;
this.store = store;
//remember parent question object
this.question = question;
//remember parent part object, so scores can percolate up for steps/gaps
this.parentPart = parentPart;
//remember a path for this part, for stuff like marking and warnings
this.path = path || 'p0';
this.full_path = (this.question ? 'q'+this.question.number : '') + this.path;
this.name = util.capitalise(util.nicePartName(path));
this.label = '';
if(this.question) {
this.question.partDictionary[path] = this;
}
//initialise settings object
this.settings = util.copyobj(Part.prototype.settings);
//initialise gap and step arrays
this.gaps = [];
this.steps = [];
this.alternatives = [];
this.isStep = this.path.match(/s\d+$/)!==null;
this.isGap = this.path.match(/g\d+$/)!==null;
this.settings.errorCarriedForwardReplacements = [];
this.errorCarriedForwardBackReferences = {};
this.nextParts = [];
this.pre_submit_cache = [];
this.markingFeedback = [];
this.finalised_result = {valid: false, credit: 0, states: []};
this.warnings = [];
this.scripts = {};
this.save_staged_answer_debounce = Numbas.util.debounce(SAVE_STAGED_ANSWER_FREQUENCY);
Object.defineProperty(this,"credit", {
/** Proportion of available marks awarded to the student - i.e. `score/marks`. Penalties will affect this instead of the raw score, because of things like the steps marking algorithm.
*
* @type {number}
* @returns {number}
*/
get: function() {
return this.creditFraction.toFloat();
},
set: function(credit) {
this.creditFraction = math.Fraction.fromFloat(credit);
}
});
}
Part.prototype = /** @lends Numbas.parts.Part.prototype */ {
/** Signals produced while loading this part.
*
* @type {Numbas.schedule.SignalBox}
* */
signals: undefined,
/** Storage engine.
*
* @type {Numbas.storage.BlankStorage}
*/
store: undefined,
/** XML defining this part.
*
* @type {Element}
*/
xml: '',
/** JSON defining this part.
*
* @type {object}
*/
json: null,
/** Load the part's settings from an XML `<part>` node.
*
* @param {Element} xml
*/
loadFromXML: function(xml) {
this.xml = xml;
var tryGetAttribute = Numbas.xml.tryGetAttribute;
tryGetAttribute(this,this.xml,'.',['type','marks','useCustomName','customName']);
tryGetAttribute(this.settings,this.xml,'.',['minimumMarks','enableMinimumMarks','stepsPenalty','showCorrectAnswer','showFeedbackIcon','exploreObjective','suggestGoingBack','useAlternativeFeedback'],[]);
//load steps
var stepNodes = this.xml.selectNodes('steps/part');
if(!this.question || !this.question.exam || this.question.exam.settings.allowSteps) {
for(var i=0; i<stepNodes.length; i++) {
var step = Numbas.createPartFromXML(i, stepNodes[i], this.path+'s'+i, this.question, this, this.store);
this.addStep(step,i);
}
} else {
for(var i=0; i<stepNodes.length; i++) {
stepNodes[i].parentElement.removeChild(stepNodes[i]);
}
}
var alternativeNodes = this.xml.selectNodes('alternatives/part');
for(var i=0; i<alternativeNodes.length; i++) {
var alternative = Numbas.createPartFromXML(i, alternativeNodes[i], this.path+'a'+i, this.question, this, this.store);
this.addAlternative(alternative,i);
}
var alternativeFeedbackMessageNode = this.xml.selectSingleNode('alternativefeedbackmessage');
if(alternativeFeedbackMessageNode) {
this.alternativeFeedbackMessage = Numbas.xml.transform(Numbas.xml.templates.question, alternativeFeedbackMessageNode);
}
// set variable replacements
var adaptiveMarkingNode = this.xml.selectSingleNode('adaptivemarking');
tryGetAttribute(this.settings,this.xml,adaptiveMarkingNode,['penalty','strategy'],['adaptiveMarkingPenalty','variableReplacementStrategy']);
var variableReplacementsNode = this.xml.selectSingleNode('adaptivemarking/variablereplacements');
var replacementNodes = variableReplacementsNode.selectNodes('replace');
for(var i=0;i<replacementNodes.length;i++) {
var n = replacementNodes[i];
var vr = {}
tryGetAttribute(vr,n,'.',['variable','part','must_go_first']);
this.addVariableReplacement(vr.variable, vr.part, vr.must_go_first);
}
var nextPartsNode = this.xml.selectSingleNode('nextparts');
var nextPartNodes = nextPartsNode.selectNodes('nextpart');
for(var i=0;i<nextPartNodes.length;i++) {
var nextPartNode = nextPartNodes[i];
var np = new NextPart(this);
np.loadFromXML(nextPartNode);
this.nextParts.push(np);
}
// create the JME marking script for the part
var markingScriptNode = this.xml.selectSingleNode('markingalgorithm');
var markingScriptString = Numbas.xml.getTextContent(markingScriptNode).trim();
var markingScript = {};
tryGetAttribute(markingScript,this.xml,markingScriptNode,['extend']);
var extend_base = markingScript.extend;
this.setMarkingScript(markingScriptString,extend_base);
// custom JavaScript scripts
var scriptNodes = this.xml.selectNodes('scripts/script');
for(var i=0;i<scriptNodes.length; i++) {
var name = scriptNodes[i].getAttribute('name');
var order = scriptNodes[i].getAttribute('order');
var script = Numbas.xml.getTextContent(scriptNodes[i]);
this.setScript(name, order, script);
}
},
/** Load the part's settings from a JSON object.
*
* @param {object} data
*/
loadFromJSON: function(data) {
this.json = data;
var p = this;
var settings = this.settings;
var tryLoad = Numbas.json.tryLoad;
var tryGet = Numbas.json.tryGet;
tryLoad(data,['marks','useCustomName','customName'],this);
this.marks = parseFloat(this.marks);
tryLoad(data,['showCorrectAnswer', 'showFeedbackIcon', 'stepsPenalty','variableReplacementStrategy','adaptiveMarkingPenalty','exploreObjective','suggestGoingBack','useAlternativeFeedback'],this.settings);
var variableReplacements = tryGet(data, 'variableReplacements');
if(variableReplacements) {
variableReplacements.map(function(vr) {
p.addVariableReplacement(vr.variable, vr.part, vr.must_go_first);
});
}
if('steps' in data) {
data.steps.map(function(sd,i) {
var s = createPartFromJSON(i, sd, p.path+'s'+i, p.question, p, p.store);
p.addStep(s,i);
});
}
var alternatives = tryGet(data,'alternatives');
if(alternatives) {
alternatives.forEach(function(ad,i) {
var alternative = Numbas.createPartFromJSON(i, ad, p.path+'a'+i, p.question, p, p.store);
p.addAlternative(alternative,i);
});
}
tryLoad(data,'alternativeFeedbackMessage',this);
var marking = {};
tryLoad(data, ['customMarkingAlgorithm', 'extendBaseMarkingAlgorithm'], marking);
this.setMarkingScript(marking.customMarkingAlgorithm, marking.extendBaseMarkingAlgorithm);
if('scripts' in data) {
for(var name in data.scripts) {
var script = data.scripts[name];
this.setScript(name, script.order, script.script);
}
}
var nextParts = tryGet(data,'nextParts');
if(nextParts) {
nextParts.forEach(function(npdata) {
var np = new NextPart(p);
np.loadFromJSON(npdata);
p.nextParts.push(np);
});
}
},
/** Perform any tidying up or processing that needs to happen once the part's definition has been loaded.
*/
finaliseLoad: function() {
this.marks = this.marks || 0;
this.applyScripts();
if(this.customConstructor) {
try {
this.customConstructor.apply(this);
} catch(e) {
throw(e);
}
}
var scope = this.getScope();
this.nextParts.forEach(function(np) {
if(np.penaltyAmountString!='') {
np.penaltyAmount = np.penalty ? scope.evaluate(np.penaltyAmountString).value : 0;
}
});
},
/** All children of this part: all gaps and steps, but not alternatives.
*
* @returns {Array.<Numbas.jme.parts.Part>}
*/
allChildren: function() {
return this.gaps.concat(this.steps);
},
/** Initialise this part's display object.
* Only called if the question this part belongs to has a display.
*/
initDisplay: function() {
this.display = new Numbas.display.PartDisplay(this);
},
/** Load saved data about this part from storage.
* The part is not resubmitted - you must do this afterwards, once any steps or gaps have been resumed.
*
* @fires Numbas.Part#event:resume
*/
resume: function() {
this.resuming = true;
var part = this;
if(!this.store) {
return;
}
var pobj = this.store.loadPart(this);
this.answered = pobj.answered;
this.stepsShown = pobj.stepsShown;
this.stepsOpen = pobj.stepsOpen;
this.resume_stagedAnswer = pobj.stagedAnswer;
this.steps.forEach(function(s){ s.resume() });
this.pre_submit_cache = pobj.pre_submit_cache;
this.alternatives.forEach(function(alt,i) {
var aobj = pobj.alternatives[i];
if(!aobj) {
return;
}
alt.pre_submit_cache = aobj.pre_submit_cache
});
var scope = this.getScope();
this.display && this.display.updateNextParts();
this.display && this.question && this.question.signals.on(['ready','HTMLAttached'], function() {
part.display.restoreAnswer(part.resume_stagedAnswer!==undefined ? part.resume_stagedAnswer : part.studentAnswer);
})
this.signals.trigger('resume');
this.resuming = false;
},
/** Add a step to this part.
*
* @param {Numbas.parts.Part} step
* @param {number} index - Position of the step.
* @fires Numbas.Part#event:addStep
*/
addStep: function(step, index) {
step.isStep = true;
this.steps.splice(index,0,step);
this.stepsMarks += step.marks;
this.events.trigger('addStep', step, index);
},
/** Add an alternative to this part.
*
* @param {Numbas.parts.Part} alternative
* @param {number} index - Position of the alternative.
* @fires Numbas.Part#event:addAlternative
*/
addAlternative: function(alternative, index) {
alternative.isAlternative = true;
this.alternatives.splice(index,0,alternative);
this.events.trigger('addAlternative', alternative, index);
},
/** A definition of a variable replacement for adaptive marking.
*
* @typedef Numbas.parts.adaptive_variable_replacement_definition
* @property {string} variable - The name of the variable to replace.
* @property {string} part - The path of the part to use.
* @property {boolean} must_go_first - Must the referred part be answered before this part can be marked?
*/
/** Add a variable replacement for this part's adaptive marking.
*
* @param {string} variable - The name of the variable to replace.
* @param {string} part - The path of the part to use.
* @param {boolean} must_go_first - Must the referred part be answered before this part can be marked?
* @fires Numbas.Part#event:addVariableReplacement
*/
addVariableReplacement: function(variable, part, must_go_first) {
if(part==this.path) {
this.error("part.marking.adaptive variable replacement refers to self");
}
if(!part) {
this.error("part.marking.adaptive variable replacement refers to nothing");
}
var vr = {
variable: jme.normaliseName(variable,this.getScope()),
part: part,
must_go_first: must_go_first
};
this.settings.hasVariableReplacements = true;
this.settings.errorCarriedForwardReplacements.push(vr);
this.events.trigger('addVariableReplacement', variable, part);
},
/** The base marking script for this part.
*
* @abstract
* @returns {Numbas.marking.MarkingScript}
*/
baseMarkingScript: function() {},
/** Set this part's JME marking script.
*
* @param {string} markingScriptString
* @param {boolean} extend_base - Does this script extend the built-in script?
*/
setMarkingScript: function(markingScriptString, extend_base) {
if(!this.doesMarking) {
return;
}
var p = this;
var algo = this.baseMarkingScript();
if(markingScriptString) {
algo = new marking.MarkingScript(markingScriptString, extend_base ? algo : undefined, this.getScope());
}
this.markingScript = algo;
// check that the required notes are present
var requiredNotes = ['mark','interpreted_answer'];
requiredNotes.forEach(function(name) {
if(!(name in algo.notes)) {interpreted_answer
p.error("part.marking.missing required note",{note:name});
}
});
},
/** Set a custom JavaScript script.
*
* @param {string} name - The name of the method to override.
* @param {string} order - When should the script run? `'instead'`, `'before'` or `'after'`.
* @param {string} script - The source code of the script.
* @see {Numbas.parts.Part#applyScripts}
*/
setScript: function(name,order,script) {
var p = this;
if(name=='mark') {
// hack on a finalised_state for old marking scripts
script = 'var res = (function(studentAnswer,scope) {'+script+'\n}).apply(this,arguments); \
this.answered = true; \
if(res) { \
return res; \
} else {\
res = { \
states: {mark: this.markingFeedback.slice()}, \
values: {interpreted_answer: Numbas.jme.wrapValue(arguments[0])}, \
state_valid: {mark: true, interpreted_answer: true}, \
state_errors: {}, \
added_because_missing: true \
}; \
this.markingFeedback = []; \
this.credit = 0; \
return res; \
} \
';
name = 'mark_answer';
}
var fn = new Function(['variables','question','part'], 'return (function(){try{'+script+'\n}catch(e){e = new Numbas.Error(\'part.script.error\',{path:this.name,script:this.name,message:e.message}); Numbas.showError(e); throw(e);}})');
var script = function() {
return fn(
p.question ? p.question.unwrappedVariables : {},
p.question,
p
).apply(this,arguments);
}
this.scripts[name] = {script: script, order: order};
},
/** The question this part belongs to.
*
* @type {Numbas.Question}
*/
question: undefined,
/** Reference to parent of this part, if this is a gap or a step.
*
* @type {Numbas.parts.Part}
*/
parentPart: undefined,
/** A question-wide unique 'address' for this part.
*
* @type {Numbas.parts.partpath}
*/
path: '',
/** A readable name for this part, to show to the student.
* Change it with {@link Numbas.parts.Part#setName}.
*
* @type {string}
*/
name: '',
/** Should a custom name be used?
*
* @type {boolean}
*/
useCustomName: false,
/** Custom name for this part, or null if none.
* Variables will be substituted into this string from the part's scope.
*
* @type {string}
*/
customName: '',
/** Assign a name to this part, and then assign names to its children.
*
* @param {number} index - The number of parts before this one that have names.
* @param {number} siblings - The number of siblings this part has.
* @returns {boolean} `true` if this part has a name that should increment the label counter.
* @fires Numbas.Part#event:assignName
*/
assignName: function(index,siblings) {
var p = this;
if(this.useCustomName) {
this.name = jme.contentsubvars(this.customName,this.getScope(),false);
} else if(this.isGap) {
this.name = util.capitalise(R('gap'))+' '+index;
} else if(this.isStep && siblings>0) {
this.name = util.capitalise(R('step'))+' '+index;
} else if(siblings==0) {
this.name = '';
} else {
this.name = util.letterOrdinal(index)+')';
}
/** Assign names to the given child parts.
*
* @param {Array.<Numbas.parts.Part>} children
*/
function assign_child_names(children) {
if(!children) {
return;
}
var i = 0;
children.forEach(function(c) {
var hasName = c.assignName(i,children.length-1);
i += hasName ? 1 : 0;
});
}
assign_child_names(this.gaps);
assign_child_names(this.steps);
assign_child_names(this.alternatives);
this.display && this.display.setName(this.name);
this.events.trigger('assignName',index,siblings);
return this.name != '';
},
/** This part's type, e.g. "jme", "numberentry", ...
*
* @type {string}
*/
type: '',
/** Maximum marks available for this part.
*
* @type {number}
*/
marks: 0,
/** Marks available for the steps, if any.
*
* @type {number}
*/
stepsMarks: 0,
/** Credit as a fraction. Used to avoid simple floating point errors.
*
* @type {Numbas.math.Fraction}
*/
creditFraction: new math.Fraction(0,1),
/** Student's score on this part.
*
* @type {number}
*/
score: 0,
/** Messages explaining how marks were awarded.
*
* @type {Array.<Numbas.parts.feedbackmessage>}
*/
markingFeedback: [],
/** The result of the last marking run.
*
* @type {Numbas.marking.finalised_state}
*/
finalised_result: {valid: false, credit: 0, states: []},
/** Warnings shown next to the student's answer.
*
* @type {Array.<string>}
*/
warnings: [],
/** Has the student changed their answer since last submitting?
*
* @type {boolean}
*/
isDirty: false,
/** Student's answers as visible on the screen (not necessarily yet submitted).
*
* @type {Array.<string>}
*/
stagedAnswer: undefined,
/** Has this part been answered?
*
* @type {boolean}
*/
answered: false,
/** Child gapfill parts.
*
* @type {Numbas.parts.Part[]}
*/
gaps: [],
/** Child step parts.
*
* @type {Numbas.parts.Part[]}
*/
steps: [],
/** Child alternative parts.
*
* @type {Numbas.parts.Part[]}
*/
alternatives: [],
/** Feedback message shown if this part is used as an alternative.
*
* @type {string}
*/
alternativeFeedbackMessage: '',
/** Have the steps been show for this part?
*
* @type {boolean}
*/
stepsShown: false,
/** Is the steps display open?
*
* @type {boolean}
*/
stepsOpen: false,
/** True if this part should be resubmitted because another part it depended on has changed.
*
* @type {boolean}
*/
shouldResubmit: false,
/** Does this mark do any marking? False for information only parts.
*
* @type {boolean}
*/
doesMarking: true,
/** Has the answer to this part been revealed?
*
* @type {boolean}
*/
revealed: false,
/** Is this part locked? If false, the student can change and submit their answer.
*
* @type {boolean}
*/
locked: false,
/** Properties set when the part is generated.
*
* @type {object}
* @property {number} stepsPenalty - Number of marks to deduct when the steps are shown.
* @property {boolean} enableMinimumMarks - Is there a lower limit on the score the student can be awarded for this part?
* @property {number} minimumMarks - Lower limit on the score the student can be awarded for this part.
* @property {boolean} showCorrectAnswer - Show the correct answer on reveal?
* @property {boolean} showFeedbackIcon - Show the tick/cross feedback symbol after this part is submitted?
* @property {boolean} hasVariableReplacements - Does this part have any variable replacement rules?
* @property {string} variableReplacementStrategy - `'originalfirst'` or `'alwaysreplace'`.
* @property {string} exploreObjective - Name of the objective that this part's score counts towards.
* @property {string} suggestGoingBack - In explore mode, suggest to the student to go back to the previous part after completing this one?
* @property {number} adaptiveMarkingPenalty - Number of marks to deduct when adaptive marking is used.
* @property {boolean} useAlternativeFeedback - Show all feedback from an alternative answer? If false, only the alternative feedback message is shown.
* @property {Array.<Numbas.parts.adaptive_variable_replacement_definition>} errorCarriedForwardReplacements - Variable replacements to make during adaptive marking.
*/
settings:
{
stepsPenalty: 0,
enableMinimumMarks: true,
minimumMarks: 0,
showCorrectAnswer: true,
showFeedbackIcon: true,
hasVariableReplacements: false,
variableReplacementStrategy: 'originalfirst',
exploreObjective: null,
suggestGoingBack: false,
adaptiveMarkingPenalty: 0,
useAlternativeFeedback: false,
errorCarriedForwardReplacements: []
},
/** The script to mark this part - assign credit, and give messages and feedback.
*
* @type {Numbas.marking.MarkingScript}
*/
markingScript: null,
/** Throw an error, with the part's identifier prepended to the message.
*
* @param {string} message
* @param {object} args - Arguments for the error message.
* @param {Error} [originalError] - If this is a re-thrown error, the original error object.
* @fires Numbas.Part#event:error
* @throws {Numbas.Error}
*/
error: function(message, args, originalError) {
if(originalError && originalError.originalMessages && originalError.originalMessages[0]=='part.error') {
throw(originalError);
}
var nmessage = R.apply(this,[message,args]);
if(nmessage!=message) {
originalError = new Error(nmessage);
originalError.originalMessages = [message].concat(originalError.originalMessages || []);
}
var niceName = this.name;
this.events.trigger('error', message, args, originalError);
throw(new Numbas.Error('part.error',{path: niceName, message: nmessage},originalError));
},
/** The name of the input widget this part uses, if any.
*
* @returns {string}
*/
input_widget: function() {
return null;
},
/** Options for this part's input widget.
*
* @returns {object}
*/
input_options: function() {
return {};
},
applyScripts: function() {
var part = this;
this.originalScripts = {};
for(var name in this.scripts) {
var script_dict = this.scripts[name];
var order = script_dict.order;
var script = script_dict.script;
switch(name) {
case 'constructor':
this.customConstructor = script;
break;
default:
var originalScript = this[name];
/** Create a function which runs `script` (instead of the built-in script).
*
* @param {Function} script
* @returns {Function}
*/
function instead(script) {
return function() {
return script.apply(part,arguments);
}
}
/** Create a function which runs `script` before `originalScript`.
*
* @param {Function} script
* @param {Function} originalScript
* @returns {Function}
*/
function before(script,originalScript) {
return function() {
script.apply(part,arguments);
return originalScript.apply(part,arguments);
}
}
/** Create a function which runs `script` after `originalScript`.
*
* @param {Function} script
* @param {Function} originalScript
* @returns {Function}
*/
function after(script,originalScript) {
return function() {
var original_result = originalScript.apply(part,arguments);
var after_result = script.apply(part,arguments);
if(!after_result) {
return original_result;
}
if(after_result.added_because_missing && after_result.states && after_result.states.mark) {
after_result.states.mark = original_result.states.mark.concat(after_result.states.mark);
}
return after_result;
}
}
switch(order) {
case 'instead':
this[name] = instead(script);
break;
case 'before':
this[name] = before(script,originalScript);
break;
case 'after':
this[name] = after(script,originalScript);
break;
}
}
}
},
/** Associated display object. It is not safe to assume this is always present - in the editor, parts have no display.
*
* @type {Numbas.display.PartDisplay}
*/
display: undefined,
/** Give the student a warning about this part.
*
* @param {string} warning
* @fires Numbas.Part#event:giveWarning
* @see Numbas.display.PartDisplay.warning
*/
giveWarning: function(warning) {
this.warnings.push(warning);
this.display && this.display.warning(warning);
this.events.trigger('giveWarning', warning);
},
/** Set the list of warnings.
*
* @param {Array.<string>} warnings
* @see Numbas.display.PartDisplay.warning
*/
setWarnings: function(warnings) {
this.warnings = warnings;
this.display && this.display.setWarnings(warnings);
},
/** Remove all warnings.
*
* @see Numbas.display.PartDisplay.warning
*/
removeWarnings: function() {
this.setWarnings([]);
},
/** The total marks available for this part, after applying adaptive marking and steps penalties.
*
* @returns {number}
*/
availableMarks: function() {
var marks = this.marks;
if(this.adaptiveMarkingUsed) {
marks -= this.settings.adaptiveMarkingPenalty;
}
var stepsPart = this.isGap ? this.parentPart : this;
if(stepsPart.steps.length && stepsPart.stepsShown) {
var stepsPenalty = stepsPart.settings.stepsPenalty;
if(this.isGap && this.parentPart.marks>0) {
stepsPenalty *= this.marks / this.parentPart.marks;
}
marks -= stepsPenalty;
}
marks = Math.max(Math.min(this.marks,marks),0);
return marks;
},
/** Calculate the student's score based on their submitted answers.
*
* Calls the parent part's `calculateScore` method at the end.
*
* @fires Numbas.Part#event:calculateScore
*/
calculateScore: function()
{
var marks = this.availableMarks();
if(this.steps.length && this.stepsShown) {
var oScore = this.score = marks * this.credit; //score for main keypart
var stepsScore = 0, stepsMarks=0;
for(var i=0; i<this.steps.length; i++)
{
stepsScore += this.steps[i].score;
stepsMarks += this.steps[i].marks;
}
this.score += stepsScore; //add score from steps to total score
this.score = Math.min(this.score,marks) //if too many marks are awarded for steps, it's possible that getting all the steps right leads to a higher score than just getting the part right. Clip the score to avoid this.
this.applyScoreLimits();
if(stepsMarks!=0 && stepsScore!=0)
{
if(this.credit==1)
this.markingComment(R('part.marking.steps no matter'));
else
{
var change = this.score - oScore;
if(this.submitting) {
this.markingComment(R('part.marking.steps change',{count:change}));
}
}
}
}
else
{
this.score = this.credit * marks;
this.applyScoreLimits();
}
if(this.revealed) {
this.score = 0;
}
if(this.parentPart && !this.parentPart.submitting) {
this.parentPart.calculateScore();
}
this.events.trigger('calculateScore');
this.display && this.display.showScore(this.answered);
},
/** Make sure the awarded score is between the minimum and maximum available.
*/
applyScoreLimits: function() {
var marks = this.availableMarks();
if(this.settings.enableMinimumMarks && this.score<this.settings.minimumMarks) {
this.score = this.settings.minimumMarks;
this.creditFraction = marks!=0 ? math.Fraction.fromFloat(this.settings.minimumMarks,marks) : 0;
this.markingComment(R('part.marking.minimum score applied',{score:this.settings.minimumMarks}));
}
if(this.score>marks) {
this.finalised_result.states.push(Numbas.marking.feedback.sub_credit(this.credit-1, R('part.marking.maximum score applied',{score:marks})));
this.score = marks;
this.creditFraction = math.Fraction.one;
this.markingComment(R('part.marking.maximum score applied',{score:marks}));
}
},
/** Update the stored answer from the student (called when the student changes their answer, but before submitting).
*
* @param {*} answer
* @param {boolean} dontStore - Don't tell the storage that this is happening - use when loading from storage to avoid callback loops.
* @fires Numbas.Part#event:storeAnswer
* @see {Numbas.parts.Part.stagedAnswer}
*/
storeAnswer: function(answer,dontStore) {
var p = this;
this.stagedAnswer = answer;