-
Notifications
You must be signed in to change notification settings - Fork 98
/
multichoice.js
678 lines (603 loc) · 19.7 KB
/
multichoice.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
// Will render a Question with multiple choices for answers.
// Options format:
// {
// title: "Optional title for question box",
// question: "Question text",
// answers: [{text: "Answer text", correct: false}, ...],
// singleAnswer: true, // or false, will change rendered output slightly.
// singlePoint: true, // True if question give a single point score only
// // if all are correct, false to give 1 point per
// // correct answer. (Only for singleAnswer=false)
// randomAnswers: false // Whether to randomize the order of answers.
// }
//
// Events provided:
// - h5pQuestionAnswered: Triggered when a question has been answered.
var H5P = H5P || {};
H5P.MultiChoice = function(options, contentId, contentData) {
if (!(this instanceof H5P.MultiChoice))
return new H5P.MultiChoice(options, contentId, contentData);
var self = this;
this.contentId = contentId;
H5P.Question.call(self, 'multichoice');
var $ = H5P.jQuery;
var texttemplate =
'<ul class="h5p-answers">' +
' <% for (var i=0; i < answers.length; i++) { %>' +
' <li class="h5p-answer<% if (userAnswers.indexOf(i) > -1) { %> h5p-selected<% } %>">' +
' <label>' +
' <div class="h5p-input-container">' +
' <% if (behaviour.singleAnswer) { %>' +
' <input type="radio" name="answer" class="h5p-input" value="answer_<%= i %>"<% if (userAnswers.indexOf(i) > -1) { %> checked<% } %> />' +
' <% } else { %>' +
' <input type="checkbox" name="answer_<%= i %>" class="h5p-input" value="answer_<%= i %>"<% if (userAnswers.indexOf(i) > -1) { %> checked<% } %> />' +
' <% } %>' +
' <a width="100%" height="100%" class="h5p-radio-or-checkbox" href="#"><%= answers[i].checkboxOrRadioIcon %></a>' +
' </div><div class="h5p-alternative-container">' +
' <span class="h5p-span"><%= answers[i].text %></span>' +
' </div><div class="h5p-clearfix"></div>' +
' </label>' +
' </li>' +
' <% } %>' +
'</ul>';
var defaults = {
image: null,
question: "No question text provided",
answers: [
{
tipsAndFeedback: {
tip: '',
chosenFeedback: '',
notChosenFeedback: ''
},
text: "Answer 1",
correct: true
}
],
weight: 1,
userAnswers: [],
UI: {
checkAnswerButton: 'Check',
showSolutionButton: 'Show solution',
tryAgainButton: 'Try again'
},
behaviour: {
enableRetry: true,
enableSolutionsButton: true,
type: 'auto',
singlePoint: true,
randomAnswers: false,
showSolutionsRequiresInput: true
}
};
// Make sure tips and feedback exists
if (options.answers) {
options.answers.forEach(function (answer) {
answer.tipsAndFeedback = answer.tipsAndFeedback || {};
});
}
var template = new EJS({text: texttemplate});
var params = $.extend(true, {}, defaults, options);
if (params.behaviour.type === 'auto') {
// Determine number of correct choices
var numCorrect = 0;
for (var i = 0; i < params.answers.length; i++) {
if (params.answers[i].correct) {
numCorrect++;
}
}
// Use single choice if only one choice is correct
params.behaviour.singleAnswer = (numCorrect === 1);
}
else {
params.behaviour.singleAnswer = (params.behaviour.type === 'single');
}
var getCheckboxOrRadioIcon = function (radio, selected) {
var icon;
if (radio) {
icon = selected ? '' : '';
}
else {
icon = selected ? '' : '';
}
return icon;
};
// Initialize buttons and elements.
var $myDom;
var $feedbackDialog;
/**
* Remove all feedback dialogs
*/
var removeFeedbackDialog = function () {
// Remove the open feedback dialogs.
$myDom.unbind('click', removeFeedbackDialog );
$myDom.find('.h5p-feedback-button, .h5p-feedback-dialog').remove();
$myDom.find('.h5p-has-feedback').removeClass('h5p-has-feedback');
if ($feedbackDialog) {
$feedbackDialog.remove();
}
};
var score = 0;
var solutionsVisible = false;
/**
* Add feedback to element
* @param {jQuery} $element Element that feedback will be added to
* @param {string} feedback Feedback string
*/
var addFeedback = function ($element, feedback) {
$feedbackDialog = $('' +
'<div class="h5p-feedback-dialog">' +
'<div class="h5p-feedback-inner">' +
'<div class="h5p-feedback-text">' + feedback + '</div>' +
'</div>' +
'</div>');
//make sure feedback is only added once
if (!$element.find($('.h5p-feedback-dialog')).length ) {
$feedbackDialog.appendTo($element.addClass('h5p-has-feedback'));
}
};
/**
* Register the different parts of the task with the H5P.Question structure.
*/
self.registerDomElements = function () {
if (params.image) {
// Register task image
self.setImage(params.image.path);
}
// Determine if we're using checkboxes or radio buttons
for (var i = 0; i < params.answers.length; i++) {
params.answers[i].checkboxOrRadioIcon = getCheckboxOrRadioIcon(params.behaviour.singleAnswer, params.userAnswers.indexOf(i) > -1);
}
// Register Introduction
self.setIntroduction(params.question);
// Register task content area
$myDom = $(template.render(params));
self.setContent($myDom, {
'class': params.behaviour.singleAnswer ? 'h5p-radio' : 'h5p-check'
});
// Create tips:
$('.h5p-answer', $myDom).each(function (i) {
var $tipContainer = $(this);
var tip = params.answers[i].tipsAndFeedback.tip;
if (tip === undefined) {
return; // No tip
}
tip = tip.trim();
if (!tip.length) {
return; // Empty tip
}
// Add tip
var $multichoiceTip = $('<div>', {
'class': 'multichoice-tip'
}).click(function () {
var openFeedback = !$tipContainer.children('.h5p-feedback-dialog').is($feedbackDialog);
removeFeedbackDialog();
// Do not open feedback if it was open
if (openFeedback) {
// Add tip dialog
addFeedback($tipContainer, tip);
$feedbackDialog.addClass('h5p-has-tip');
}
// Remove tip dialog on dom click
setTimeout(function () {
$myDom.click(removeFeedbackDialog);
}, 100);
// Do not propagate
return false;
});
$('.h5p-alternative-container', this).append($multichoiceTip);
});
// Set event listeners.
$('input', $myDom).change(function () {
var $this = $(this);
var num = parseInt($(this).val().split('_')[1], 10);
if (params.behaviour.singleAnswer) {
params.userAnswers[0] = num;
if (params.answers[num].correct) {
score = 1;
} else {
score = 0;
}
$this.parents('.h5p-answers').find('.h5p-answer.h5p-selected').removeClass("h5p-selected");
$this.parents('.h5p-answers').find('.h5p-radio-or-checkbox').html(getCheckboxOrRadioIcon(true, false));
$this.parents('.h5p-answer').addClass("h5p-selected");
$this.siblings('.h5p-radio-or-checkbox').html(getCheckboxOrRadioIcon(true, true));
} else {
if ($this.is(':checked')) {
$this.parents('.h5p-answer').addClass("h5p-selected");
$this.siblings('.h5p-radio-or-checkbox').html(getCheckboxOrRadioIcon(false, true));
} else {
$this.parents('.h5p-answer').removeClass("h5p-selected");
$this.siblings('.h5p-radio-or-checkbox').html(getCheckboxOrRadioIcon(false, false));
}
calcScore();
}
self.triggerXAPI('interacted');
var answerChecked = false;
$myDom.find('.h5p-answer').each( function () {
if($(this).hasClass('h5p-selected')) {
answerChecked = true;
}
});
if (answerChecked) {
self.hideSolutions();
self.showButton('check-answer');
self.hideButton('try-again');
self.hideButton('show-solution');
}
});
// Adds check and retry button
addButtons();
if (!params.behaviour.singleAnswer) {
calcScore();
}
};
this.showAllSolutions = function () {
if (solutionsVisible) {
return;
}
solutionsVisible = true;
$myDom.find('.h5p-answer').each(function (i, e) {
var $e = $(e);
var a = params.answers[i];
if (a.correct) {
$e.addClass('h5p-correct');
$e.addClass('h5p-should');
}
else {
$e.addClass('h5p-wrong');
$e.addClass('h5p-should-not');
}
$e.find('input').attr('disabled', 'disabled');
});
var max = self.getMaxScore();
// Add css class disabled to labels.
$myDom.find('label').addClass('h5p-mc-disabled');
//Hide buttons and retry depending on settings.
self.hideButton('check-answer');
self.hideButton('show-solution');
if (params.behaviour.enableRetry) {
self.showButton('try-again');
}
self.trigger('resize');
};
/**
* Used in contracts.
* Shows the solution for the task and hides all buttons.
*/
this.showSolutions = function () {
self.showAllSolutions();
self.hideButton('try-again');
};
/**
*
*/
this.hideSolutions = function () {
solutionsVisible = false;
$myDom.find('.h5p-correct').removeClass('h5p-correct');
$myDom.find('.h5p-wrong').removeClass('h5p-wrong');
$myDom.find('.h5p-should').removeClass('h5p-should');
$myDom.find('.h5p-should-not').removeClass('h5p-should-not');
$myDom.find('input').prop('disabled', false);
$myDom.find('.h5p-feedback-button, .h5p-feedback-dialog').remove();
$myDom.find('.h5p-has-feedback').removeClass('h5p-has-feedback');
this.setFeedback(); // Reset feedback
self.trigger('resize');
};
/**
* Resets the whole task.
* Used in contracts with integrated content.
* @private
*/
this.resetTask = function () {
self.answered = false;
self.hideSolutions();
params.userAnswers = [];
removeSelections();
self.showButton('check-answer');
self.hideButton('try-again');
self.hideButton('show-solution');
};
var calculateMaxScore = function () {
if (blankIsCorrect) {
return params.weight;
}
var maxScore = 0;
for (var i = 0; i < params.answers.length; i++) {
var choice = params.answers[i];
if (choice.correct) {
maxScore += (choice.weight !== undefined ? choice.weight : 1);
}
}
return maxScore;
};
this.getMaxScore = function () {
return (!params.behaviour.singleAnswer && !params.behaviour.singlePoint ? calculateMaxScore() : params.weight);
};
/**
* Adds the ui buttons.
* @private
*/
var addButtons = function () {
// Show solution button
self.addButton('show-solution', params.UI.showSolutionButton, function () {
calcScore();
if (self.getAnswerGiven()) {
self.showAllSolutions();
}
}, false);
// Check solution button
self.addButton('check-answer', params.UI.checkAnswerButton, function () {
self.answered = true;
// Unbind removal of feedback dialogs on click
$myDom.unbind('click', removeFeedbackDialog );
// Remove all tip dialogs
removeFeedbackDialog();
disableInput();
self.hideButton('check-answer');
if (params.behaviour.enableSolutionsButton && self.getAnswerGiven()) {
self.showButton('show-solution');
}
if (params.behaviour.enableRetry) {
self.showButton('try-again');
}
self.showCheckSolution();
var xAPIEvent = self.createXAPIEventTemplate('answered');
addQuestionToXAPI(xAPIEvent);
addResponseToXAPI(xAPIEvent);
self.trigger(xAPIEvent);
});
// Try Again button
self.addButton('try-again', params.UI.tryAgainButton, function () {
self.showButton('check-answer');
self.hideButton('try-again');
self.hideButton('show-solution');
self.hideSolutions();
removeSelections();
enableInput();
}, false);
};
/**
* Shows feedback on the selected fields.
* @public
*/
this.showCheckSolution = function () {
$myDom.find('.h5p-answer').each(function (i, e) {
var $e = $(e);
var a = params.answers[i];
if ($e.hasClass('h5p-selected')) {
if (a.correct) {
$e.addClass('h5p-correct');
}
else {
$e.addClass('h5p-wrong');
}
}
var chosen = $e.hasClass('h5p-selected');
if (chosen && a.tipsAndFeedback.chosenFeedback !== undefined && a.tipsAndFeedback.chosenFeedback !== '') {
addFeedback($e, a.tipsAndFeedback.chosenFeedback);
} else if (!chosen && a.tipsAndFeedback.notChosenFeedback !== undefined && a.tipsAndFeedback.notChosenFeedback !== '') {
addFeedback($e, a.tipsAndFeedback.notChosenFeedback);
}
});
// Determine feedback
var max = self.getMaxScore();
var feedback, ratio = (score / max);
if (isFinite(ratio) && ratio > 0) {
feedback = (ratio >= 1 ? params.UI.correctText : params.UI.almostText); }
else {
feedback = params.UI.wrongText;
}
// Show feedback
this.setFeedback(feedback, score, max);
//Disable task if maxscore is achieved
if (score === max) {
finishedTask();
}
//Add disabled css class to label
$myDom.find('label').addClass('h5p-mc-disabled');
self.trigger('resize');
};
/**
* Method to use when the task is correctly answered, removes all buttons and disables input.
*/
var finishedTask = function () {
self.hideButton('check-answer');
self.hideButton('try-again');
self.hideButton('show-solution');
$myDom.find('input').attr('disabled', 'disabled');
self.trigger('resize');
};
/**
* Disables choosing new input.
*/
var disableInput = function () {
$myDom.find('input').attr('disabled', 'disabled');
};
/**
* Enables new input.
*/
var enableInput = function () {
$myDom.find('input').attr('disabled', false);
// Remove css class disabled from labels.
$myDom.find('label').removeClass('h5p-mc-disabled');
};
var blankIsCorrect = true;
for (var i = 0; i < params.answers.length; i++) {
if (params.answers[i].correct) {
blankIsCorrect = false;
break;
}
}
var calcScore = function () {
score = 0;
params.userAnswers = [];
$('input', $myDom).each(function (idx, el) {
var $el = $(el);
if ($el.is(':checked')) {
var choice = params.answers[idx];
var weight = (choice.weight !== undefined ? choice.weight : 1);
if (choice.correct) {
score += weight;
}
else {
score -= weight;
}
var num = parseInt($(el).val().split('_')[1], 10);
params.userAnswers.push(num);
}
});
if (score < 0) {
score = 0;
}
if (!params.userAnswers.length && blankIsCorrect) {
score = params.weight;
}
if (params.behaviour.singlePoint) {
score = (score === calculateMaxScore() ? params.weight : 0);
}
};
/**
* Removes selections from task.
*/
var removeSelections = function () {
$myDom.find('input.h5p-input').each( function () {
this.checked = false;
$(this).parents('.h5p-answer').removeClass("h5p-selected");
//Sets type of icon depending on answer type.
if (params.behaviour.singleAnswer) {
$(this).siblings('.h5p-radio-or-checkbox').html(getCheckboxOrRadioIcon(true, false));
}
else {
$(this).siblings('.h5p-radio-or-checkbox').html(getCheckboxOrRadioIcon(false, false));
}
});
calcScore();
};
/**
* Add the question itselt to the definition part of an xAPIEvent
*/
var addQuestionToXAPI = function(xAPIEvent) {
var definition = xAPIEvent.getVerifiedStatementValue(['object', 'definition']);
definition.description = {
'en-US': params.question
};
definition.type = 'http://adlnet.gov/expapi/activities/cmi.interaction';
definition.interactionType = 'choice';
definition.correctResponsesPattern = [];
definition.choices = [];
for (var i = 0; i < params.answers.length; i++) {
definition.choices[i] = {
'id': params.answers[i].originalOrder + '',
'description': {
'en-US': params.answers[i].text
}
};
if (params.answers[i].correct) {
if (!params.singleAnswer) {
if (definition.correctResponsesPattern.length) {
definition.correctResponsesPattern[0] += '[,]';
// This looks insane, but it's how you separate multiple answers
// that must all be chosen to achieve perfect score...
}
else {
definition.correctResponsesPattern.push('');
}
definition.correctResponsesPattern[0] += params.answers[i].originalOrder;
}
else {
definition.correctResponsesPattern.push('' + params.answers[i].originalOrder);
}
}
}
};
/**
* Add the response part to an xAPI event
*
* @param {H5P.XAPIEvent} xAPIEvent
* The xAPI event we will add a response to
*/
var addResponseToXAPI = function(xAPIEvent) {
xAPIEvent.setScoredResult(score, self.getMaxScore(), self);
if (params.userAnswers === undefined) {
calcScore();
}
var response = '';
for (var i = 0; i < params.userAnswers.length; i++) {
if (response !== '') {
response += '[,]';
}
response += idMap === undefined ? params.userAnswers[i] : idMap[params.userAnswers[i]];
}
xAPIEvent.data.statement.result.response = response;
};
// Initialization code
// Randomize order, if requested
var idMap;
// Store original order in answers
for (i = 0; i < params.answers.length; i++) {
params.answers[i].originalOrder = i;
}
if (params.behaviour.randomAnswers) {
var origOrder = $.extend([], params.answers);
params.answers = H5P.shuffleArray(params.answers);
// Create a map from the new id to the old one
idMap = [];
for (i = 0; i < params.answers.length; i++) {
idMap[i] = params.answers[i].originalOrder;
}
}
// Start with an empty set of user answers.
params.userAnswers = [];
// Restore previous state
if (contentData && contentData.previousState !== undefined) {
// Restore answers
if (contentData.previousState.answers) {
if (!idMap) {
params.userAnswers = contentData.previousState.answers;
}
else {
// The answers have been shuffled, and we must use the id mapping.
for (i = 0; i < contentData.previousState.answers.length; i++) {
for (var k = 0; k < idMap.length; k++) {
if (idMap[k] === contentData.previousState.answers[i]) {
params.userAnswers.push(k);
}
}
}
}
}
}
/**
* Pack the current state of the interactivity into a object that can be
* serialized.
*
* @public
*/
this.getCurrentState = function () {
var state = {};
if (!idMap) {
state.answers = params.userAnswers;
}
else {
// The answers have been shuffled and must be mapped back to their
// original ID.
state.answers = [];
for (var i = 0; i < params.userAnswers.length; i++) {
state.answers.push(idMap[params.userAnswers[i]]);
}
}
return state;
};
this.getAnswerGiven = function() {
return this.answered || params.behaviour.showSolutionsRequiresInput !== true || params.userAnswers.length || blankIsCorrect;
};
this.getScore = function() {
return score;
};
this.getTitle = function() {
return H5P.createTitle(params.question);
};
};
H5P.MultiChoice.prototype = Object.create(H5P.Question.prototype);
H5P.MultiChoice.prototype.constructor = H5P.MultiChoice;