-
Notifications
You must be signed in to change notification settings - Fork 129
/
cp.js
2315 lines (2023 loc) · 70.6 KB
/
cp.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
import Parent from 'h5p-parent';
import SummarySlide from './summary-slide';
import NavigationLine from './navigation-line';
import SlideBackground from './slide-backgrounds';
import KeywordsMenu from './keyword-menu';
import { jQuery as $ } from './globals';
import { flattenArray, addClickAndKeyboardListeners, isFunction, kebabCase, stripHTML, keyCode } from './utils';
import Slide from './slide.js';
import ConfirmationDialog from './confirmation-dialog';
/**
* @const {string}
*/
const KEYWORD_TITLE_SKIP = null;
/**
* Constructor.
*
* @param {object} params Start paramteres.
* @param {int} id Content identifier
* @param {function} editor
* Set if an editor is initiating this library
* @returns {undefined} Nothing.
*/
let CoursePresentation = function (params, id, extras) {
var that = this;
this.presentation = params.presentation;
this.slides = this.presentation.slides;
this.contentId = id;
this.elementInstances = []; // elementInstances holds the instances for elements in an array.
this.elementsAttached = []; // Map to keep track of which slide has attached elements
this.slidesWithSolutions = [];
this.showCommentsAfterSolution = [];
this.hasAnswerElements = false;
this.ignoreResize = false;
this.isTask = false;
this.standalone = true;
this.isReportingEnabled = false;
this.popups = {};
if (extras.cpEditor) {
this.editor = extras.cpEditor;
}
if (extras) {
this.previousState = extras.previousState;
this.standalone = extras.standalone;
this.isReportingEnabled = extras.isReportingEnabled || extras.isScoringEnabled;
}
this.currentSlideIndex = (this.previousState && this.previousState.progress) ? this.previousState.progress : 0;
this.presentation.keywordListEnabled = (params.presentation.keywordListEnabled === undefined ? true : params.presentation.keywordListEnabled);
this.l10n = $.extend({
slide: 'Slide',
score: 'Score',
yourScore: 'Your score',
maxScore: 'Max score',
total: 'Total',
totalScore: 'Total Score',
showSolutions: 'Show solutions',
summary: 'summary',
retry: 'Retry',
exportAnswers: 'Export text',
close: 'Close',
hideKeywords: 'Hide sidebar navigation menu',
showKeywords: 'Show sidebar navigation menu',
fullscreen: 'Fullscreen',
exitFullscreen: 'Exit fullscreen',
prevSlide: 'Previous slide',
nextSlide: 'Next slide',
currentSlide: 'Current slide',
lastSlide: 'Last slide',
solutionModeTitle: 'Exit solution mode',
solutionModeText: 'Solution Mode',
summaryMultipleTaskText: 'Multiple tasks',
scoreMessage: 'You achieved:',
shareFacebook: 'Share on Facebook',
shareTwitter: 'Share on Twitter',
shareGoogle: 'Share on Google+',
goToSlide: 'Go to slide :num',
solutionsButtonTitle: 'Show comments',
printTitle: 'Print',
printIngress: 'How would you like to print this presentation?',
printAllSlides: 'Print all slides',
printCurrentSlide: 'Print current slide',
noTitle: 'No title',
accessibilitySlideNavigationExplanation: 'Use left and right arrow to change slide in that direction whenever canvas is selected.',
accessibilityProgressBarLabel: 'Choose slide to display',
containsNotCompleted: '@slideName contains not completed interaction',
containsCompleted: '@slideName contains completed interaction',
slideCount: 'Slide @index of @total',
accessibilityCanvasLabel: 'Presentation canvas. Use left and right arrow to move between slides.',
containsOnlyCorrect: "@slideName only has correct answers",
containsIncorrectAnswers: '@slideName has incorrect answers',
shareResult: 'Share Result',
accessibilityTotalScore: 'You got @score of @maxScore points in total',
accessibilityEnteredFullscreen: 'Entered fullscreen',
accessibilityExitedFullscreen: 'Exited fullscreen',
confirmDialogHeader: 'Submit your answers',
confirmDialogText: 'This will submit your results, do you want to continue?',
confirmDialogConfirmText: 'Submit and see results',
confirmDialogConfirmLabel: 'Confirm',
confirmDialogCancelLabel: 'Cancel',
slideshowNavigationLabel: 'Slideshow navigation',
}, params.l10n !== undefined ? params.l10n : {});
if (!!params.override) {
this.activeSurface = !!params.override.activeSurface;
this.hideSummarySlide = !!params.override.hideSummarySlide;
this.enablePrintButton = !!params.override.enablePrintButton;
this.showSummarySlideSolutionButton = params.override.summarySlideSolutionButton !== undefined
? params.override.summarySlideSolutionButton : true;
this.showSummarySlideRetryButton = params.override.summarySlideRetryButton !== undefined
? params.override.summarySlideRetryButton : true;
if (!!params.override.social) {
this.enableTwitterShare = !!params.override.social.showTwitterShare;
this.enableFacebookShare = !!params.override.social.showFacebookShare;
this.enableGoogleShare = !!params.override.social.showGoogleShare;
this.twitterShareStatement = params.override.social.twitterShare.statement;
this.twitterShareHashtags = params.override.social.twitterShare.hashtags;
this.twitterShareUrl = params.override.social.twitterShare.url;
this.facebookShareUrl = params.override.social.facebookShare.url;
this.facebookShareQuote = params.override.social.facebookShare.quote;
this.googleShareUrl = params.override.social.googleShareUrl;
}
}
this.keywordMenu = new KeywordsMenu({
l10n : this.l10n,
currentIndex: this.previousState !== undefined ? this.previousState.progress : 0
});
// Set override for all actions
this.setElementsOverride(params.override);
// Inheritance
Parent.call(this, Slide, params.presentation.slides);
this.on('resize', this.resize, this);
this.on('printing', function (event) {
that.ignoreResize = !event.data.finished;
if (event.data.finished) {
that.resize();
}
else if (event.data.allSlides) {
that.attachAllElements();
}
});
};
CoursePresentation.prototype = Object.create(Parent.prototype);
CoursePresentation.prototype.constructor = CoursePresentation;
/**
* @public
* @return {object}
*/
CoursePresentation.prototype.getCurrentState = function () {
var state = this.previousState ? this.previousState : {};
state.progress = this.getCurrentSlideIndex() || null;
if (!state.answers) {
state.answers = [];
}
state.answered = this.elementInstances
.map((interaction, index) => (this.slideHasAnsweredTask(index)) || null);
// Get answers and answered
for (var slide = 0; slide < this.elementInstances.length; slide++) {
if (this.elementInstances[slide]) {
for (var element = 0; element < this.elementInstances[slide].length; element++) {
var instance = this.elementInstances[slide][element];
if (instance.getCurrentState instanceof Function ||
typeof instance.getCurrentState === 'function') {
if (!state.answers[slide]) {
state.answers[slide] = [];
}
state.answers[slide][element] = instance.getCurrentState();
}
}
}
}
return state;
};
/**
* Returns true if a slide has answered interactions
*
* @param {number} index
* @return {boolean}
*/
CoursePresentation.prototype.slideHasAnsweredTask = function (index) {
const tasks = this.slidesWithSolutions[index] || [];
// Disregard questions where "no answer" is the correct answer.
return tasks
.filter(task => isFunction(task.getAnswerGiven))
.some(task => task.getAnswerGiven() && !H5P.isEmpty(task.getCurrentState()));
};
/**
* Render the presentation inside the given container.
*
* @param {H5P.jQuery} $container Container for this presentation.
* @returns {undefined} Nothing.
*/
CoursePresentation.prototype.attach = function ($container) {
var that = this;
// isRoot is undefined in the editor
if (this.isRoot !== undefined && this.isRoot()) {
this.setActivityStarted();
}
var html =
'<div class="h5p-keymap-explanation hidden-but-read">' + (!this.activeSurface && this.l10n.accessibilitySlideNavigationExplanation) + '</div>' +
'<div class="h5p-fullscreen-announcer hidden-but-read" aria-live="polite"></div>' +
'<div class="h5p-wrapper" tabindex="0" role="region" aria-roledescription="carousel" aria-label="' + (!this.activeSurface && this.l10n.accessibilityCanvasLabel) + '">' +
' <div class="h5p-current-slide-announcer hidden-but-read" aria-live="polite"></div>' +
' <div tabindex="-1"></div>' +
' <div class="h5p-box-wrapper">' +
' <div class="h5p-presentation-wrapper">' +
' <div class="h5p-keywords-wrapper"></div>' +
' <div class="h5p-slides-wrapper"></div>' +
' </div>' +
' </div>' +
' <nav class="h5p-cp-navigation" aria-label="' + this.l10n.slideshowNavigationLabel + '">' +
' <div class="h5p-progressbar" role="tablist" aria-label="' + this.l10n.accessibilityProgressBarLabel + '"></div>' +
' </nav>' +
' <div class="h5p-footer"></div>' +
'</div>';
$container
.attr('role', 'application')
.addClass('h5p-course-presentation')
.html(html);
this.$container = $container;
this.$slideAnnouncer = $container.find('.h5p-current-slide-announcer');
this.$fullscreenAnnouncer = $container.find('.h5p-fullscreen-announcer');
this.$slideTop = this.$slideAnnouncer.next();
this.$wrapper = $container.children('.h5p-wrapper');
if (this.activeSurface) {
this.$wrapper.addClass('h5p-course-presentation-active-surface');
}
this.$wrapper.focus(function () {
that.initKeyEvents();
}).blur(function () {
if (that.keydown !== undefined) {
H5P.jQuery('body').unbind('keydown', that.keydown);
delete that.keydown;
}
}).click(function (event) {
var $target = H5P.jQuery(event.target);
/*
* Add focus to the wrapper so that it may capture keyboard events unless
* the target or one of its parents should handle focus themselves.
*/
const isFocusableElement = that.belongsToTagName(
event.target, ['input', 'textarea', 'a', 'button'], event.currentTarget);
// Does the target element (or one of its parents) have a tabIndex set?
const hasTabIndex = that.hasTabIndex(event.target, event.currentTarget);
// The dialog container (if within a dialog)
const $dialogParent = $target.closest('.h5p-popup-container');
// Is target within a dialog
const isWithinDialog = $dialogParent.length !== 0;
if (!isFocusableElement && !hasTabIndex && !that.editor) {
if (!isWithinDialog) {
// We're not within a dialog, so we can seafely put focus on wrapper
that.$wrapper.focus();
}
else {
// Find the closest tabbable parent element
const $tabbable = $target.closest('[tabindex]');
// Is the parent tabbable element inside the popup?
if ($tabbable.closest('.h5p-popup-container').length === 1) {
// We'll set focus here
$tabbable.focus();
}
else {
// Fallback: set focus on close button
$dialogParent.find('.h5p-close-popup').focus();
}
}
}
if (that.presentation.keywordListEnabled &&
!that.presentation.keywordListAlwaysShow &&
that.presentation.keywordListAutoHide &&
!$target.is('textarea, .h5p-icon-pencil, span')) {
that.hideKeywords(); // Auto-hide keywords
}
});
this.on('exitFullScreen', () => {
this.$footer.removeClass('footer-full-screen');
this.$fullScreenButton.attr('aria-label', this.l10n.fullscreen);
this.$fullscreenAnnouncer.html(this.l10n.accessibilityExitedFullscreen);
});
this.on('enterFullScreen', () => {
this.$fullscreenAnnouncer.html(this.l10n.accessibilityEnteredFullscreen);
});
// Get intended base width from CSS.
var wrapperWidth = parseInt(this.$wrapper.css('width'));
this.width = wrapperWidth !== 0 ? wrapperWidth : 640;
var wrapperHeight = parseInt(this.$wrapper.css('height'));
this.height = wrapperHeight !== 0 ? wrapperHeight : 400;
this.ratio = 16 / 9;
// Intended base font size cannot be read from CSS, as it might be modified
// by mobile browsers already. (The Android native browser does this.)
this.fontSize = 16;
this.$boxWrapper = this.$wrapper.children('.h5p-box-wrapper');
var $presentationWrapper = this.$boxWrapper.children('.h5p-presentation-wrapper');
this.$slidesWrapper = $presentationWrapper.children('.h5p-slides-wrapper');
this.$keywordsWrapper = $presentationWrapper.children('.h5p-keywords-wrapper');
this.$progressbar = this.$wrapper.find('.h5p-progressbar');
this.$footer = this.$wrapper.children('.h5p-footer');
// Determine if keywords pane should be initialized
this.initKeywords = (this.presentation.keywordListEnabled === undefined || this.presentation.keywordListEnabled === true || this.editor !== undefined);
if (this.activeSurface && this.editor === undefined) {
this.initKeywords = false;
this.$boxWrapper.css('height', '100%');
}
this.isSolutionMode = false;
// Create slides and retrieve keyword title details
this.createSlides();
// We have always attached all elements on current slide
this.elementsAttached[this.currentSlideIndex] = true;
// Determine if summary slide should be added
var $summarySlide;
this.showSummarySlide = false;
if (this.hideSummarySlide) {
// Always hide
this.showSummarySlide = !this.hideSummarySlide;
}
else {
// Determine by checking for slides with tasks
this.slidesWithSolutions.forEach(function (slide) {
that.showSummarySlide = slide.length;
});
}
if ((this.editor === undefined) && (this.showSummarySlide || this.hasAnswerElements)) {
// Create the summary slide
var summarySlideParams = {
elements: [],
keywords: []
};
this.slides.push(summarySlideParams);
$summarySlide = H5P.jQuery(Slide.createHTML(summarySlideParams)).appendTo(this.$slidesWrapper);
$summarySlide.addClass('h5p-summary-slide');
if (this.isCurrentSlide(this.slides.length - 1)) {
this.$current = $summarySlide;
}
}
const keywordMenuConfig = this.getKeywordMenuConfig();
// Do not show keywords pane if it's empty and there's no editor!
if (keywordMenuConfig.length > 0 || this.isEditor()) {
// Initialize keyword titles
this.keywordMenu.init(keywordMenuConfig);
this.keywordMenu.on('select', event => this.keywordClick(event.data.index));
this.keywordMenu.on('close', () => this.hideKeywords());
this.keywordMenu.on('select', () => {
this.$currentKeyword = this.$keywords.children('.h5p-current');
});
this.$keywords = $(this.keywordMenu.getElement()).appendTo(this.$keywordsWrapper);
this.$currentKeyword = this.$keywords.children('.h5p-current');
if (this.presentation.keywordListOpacity !== undefined) {
this.setKeywordsOpacity(this.presentation.keywordListOpacity);
}
if (this.presentation.keywordListAlwaysShow) {
this.showKeywords();
}
}
else {
// Remove keyword titles completely
this.$keywordsWrapper.remove();
// Do not show keywords pane if it's empty and there's no editor!
this.initKeywords = false;
}
if (this.editor !== undefined || !this.activeSurface) {
// Initialize touch events
this.initTouchEvents();
// init navigation line
this.navigationLine = new NavigationLine(this);
// Set slide title if initing on slide 0
if (!this.previousState || !this.previousState.progress) {
this.setSlideNumberAnnouncer(0, false);
}
this.summarySlideObject = new SummarySlide(this, $summarySlide);
}
else {
this.$progressbar.add(this.$footer).remove();
if (H5P.fullscreenSupported) {
// Create full screen button
this.$fullScreenButton = H5P.jQuery('<div/>', {
'class': 'h5p-toggle-full-screen',
'aria-label': this.l10n.fullscreen,
role: 'button',
tabindex: 0,
appendTo: this.$wrapper
});
H5P.Tooltip(this.$fullScreenButton.get(0), {position: 'left'});
addClickAndKeyboardListeners(this.$fullScreenButton, () => that.toggleFullScreen());
}
}
new SlideBackground(this);
if (this.previousState && this.previousState.progress) {
this.jumpToSlide(this.previousState.progress, false, null, false, true);
}
};
/**
* Check if a node or one of its parents has a particular tag name.
*
* @param {HTMLElement} node Node to check.
* @param {string|string[]} tagNames Tag name(s).
* @param {HTMLElement} [stop] Optional node to stop. Defaults to body node.
* @return {boolean} True, if node belongs to a node with one of the tag names.
*/
CoursePresentation.prototype.belongsToTagName = function (node, tagNames, stop) {
if (!node) {
return false;
}
// Stop check at DOM tree root
stop = stop || document.body;
if (typeof tagNames === 'string') {
tagNames = [tagNames];
}
tagNames = tagNames.map(tagName => tagName.toLowerCase());
const tagName = node.tagName.toLowerCase();
if (tagNames.indexOf(tagName) !== -1) {
return true;
}
// Having stop can prevent always parsing DOM tree to root
if (stop === node) {
return false;
}
return this.belongsToTagName(node.parentNode, tagNames, stop);
};
/**
* Check if element or one of its parents has tabIndex !== -1.
*
* @param {HTMLElement} element Element to check.
* @param {HTMLElement} [stopElement] Optional element to stop search and return false if none found.
* @return {boolean} True, if one of the element parents has tabIndex !== -1.
*/
CoursePresentation.prototype.hasTabIndex = (element, stopElement) => {
if (element.tabIndex !== -1) {
return true;
}
const parents = $(element).parents();
for (let key in parents) {
if (parents[key].tabIndex !== -1) {
return true;
}
if (stopElement && parents[key] === stopElement) {
return false;
}
}
return false;
}
/**
* Removes old menu items, and create new ones from slides.
* Returns menu items as jQuery
*
* @return {jQuery}
*/
CoursePresentation.prototype.updateKeywordMenuFromSlides = function () {
this.keywordMenu.removeAllMenuItemElements();
const config = this.getKeywordMenuConfig();
return $(this.keywordMenu.init(config));
};
/**
* Creates a keyword menu config based on the slides parameters
*
* @return {KeywordMenuItemConfig[]}
*/
CoursePresentation.prototype.getKeywordMenuConfig = function () {
return this.slides
.map((slide, index) => ({
title: this.createSlideTitle(slide),
subtitle: `${this.l10n.slide} ${index + 1}`,
index
}))
.filter(config => config.title !== KEYWORD_TITLE_SKIP);
};
/**
* Returns the slide title, or "No title" if inside editor without title
*
* @return {string|null}
*/
CoursePresentation.prototype.createSlideTitle = function (slide) {
const fallbackTitleForEditor = this.isEditor() ? this.l10n.noTitle : KEYWORD_TITLE_SKIP;
return this.hasKeywords(slide) ? slide.keywords[0].main : fallbackTitleForEditor;
};
/**
* Returns true if inside the editor
*
* @return {boolean}
*/
CoursePresentation.prototype.isEditor = function () {
return this.editor !== undefined;
};
/**
* Returns true if a slide has keywords
*
* @param {object} slide
* @return {boolean}
*/
CoursePresentation.prototype.hasKeywords = function (slide) {
return slide.keywords !== undefined && slide.keywords.length > 0;
};
/**
* Create slides
* Slides are directly attached to the slides wrapper.
*
* @param {Array} slidesParams
*/
CoursePresentation.prototype.createSlides = function () {
var self = this;
for (let i = 0; i < self.children.length; i++) {
const isCurrentSlide = (i === self.currentSlideIndex);
// Create and append DOM Elements
self.children[i].getElement().appendTo(self.$slidesWrapper);
if (isCurrentSlide) {
self.children[i].setCurrent();
}
if (self.isEditor() || i === 0 || i === 1 || isCurrentSlide) {
self.children[i].appendElements();
}
}
};
/**
* Does an object have functions to determine the score
*
* @public
* @param obj The object to investigate
* @returns {boolean}
*/
CoursePresentation.prototype.hasScoreData = function (obj) {
return (
(typeof obj !== typeof undefined) &&
(typeof obj.getScore === 'function') &&
(typeof obj.getMaxScore === 'function')
);
};
/**
* Return the combined score of all children
*
* @public
* @returns {Number}
*/
CoursePresentation.prototype.getScore = function () {
var self = this;
return flattenArray(self.slidesWithSolutions).reduce(function (sum, slide) {
return sum + (self.hasScoreData(slide) ? slide.getScore() : 0);
}, 0);
};
/**
* Return the combined maxScore of all children
*
* @public
* @returns {Number}
*/
CoursePresentation.prototype.getMaxScore = function () {
var self = this;
return flattenArray(self.slidesWithSolutions).reduce(function (sum, slide) {
return sum + (self.hasScoreData(slide) ? slide.getMaxScore() : 0);
}, 0);
};
/**
* Updates the feedback icons for the progres bar.
*
* @param {array} [slideScores]
*/
CoursePresentation.prototype.setProgressBarFeedback = function (slideScores) {
if (slideScores !== undefined && slideScores) {
// Set feedback icons for progress bar.
slideScores.forEach(singleSlide => {
const $indicator = this.progressbarParts[singleSlide.slide - 1]
.find('.h5p-progressbar-part-has-task');
if ($indicator.hasClass('h5p-answered')) {
const isCorrect = singleSlide.score >= singleSlide.maxScore;
$indicator.addClass(isCorrect ? 'h5p-is-correct' : 'h5p-is-wrong');
this.navigationLine.updateSlideTitle(singleSlide.slide - 1);
}
});
}
else {
// Remove all feedback icons.
this.progressbarParts.forEach(pbPart => {
pbPart.find('.h5p-progressbar-part-has-task')
.removeClass('h5p-is-correct')
.removeClass('h5p-is-wrong');
});
}
};
/**
* Toggle keywords list on/off depending on current state
*/
CoursePresentation.prototype.toggleKeywords = function () {
const keywordsAreShowing = this.$keywordsWrapper.hasClass('h5p-open');
this[keywordsAreShowing ? 'hideKeywords' : 'showKeywords']();
};
/**
* Hide keywords
*/
CoursePresentation.prototype.hideKeywords = function () {
if (this.$keywordsWrapper.hasClass('h5p-open')) {
if (this.$keywordsButton !== undefined) {
this.$keywordsButton.attr('aria-label', this.l10n.showKeywords);
this.$keywordsButton.attr('aria-expanded', 'false');
this.$keywordsButton.focus();
}
this.$keywordsWrapper.removeClass('h5p-open');
}
};
/**
* Show keywords
*/
CoursePresentation.prototype.showKeywords = function () {
if (this.$keywordsWrapper.hasClass('h5p-open')) {
// Already showing
return;
}
if (this.$keywordsButton !== undefined) {
this.$keywordsButton.attr('aria-label', this.l10n.hideKeywords);
this.$keywordsButton.attr('aria-expanded', 'true');
}
this.$keywordsWrapper.addClass('h5p-open');
// Do not focus if always showing
if (!this.presentation.keywordListAlwaysShow) {
this.$keywordsWrapper.find('li[tabindex="0"]').focus();
}
};
/**
* Change the background opacity of the keywords list.
*
* @param {number} value 0 - 100
*/
CoursePresentation.prototype.setKeywordsOpacity = function (value) {
if (this.$keywordsWrapper.css('background-color') !== '') {
const [red, green, blue] = this.$keywordsWrapper.css('background-color').match(/\d+/g);
this.$keywordsWrapper.css('background-color', `rgba(${red}, ${green}, ${blue}, ${value / 100})`);
}
};
/**
* Makes continuous text smaller if it does not fit inside its container.
* Only works in view mode.
*
* @returns {undefined}
*/
CoursePresentation.prototype.fitCT = function () {
if (this.editor !== undefined) {
return;
}
this.$current.find('.h5p-ct').each(function () {
var percent = 100;
var $ct = H5P.jQuery(this);
var parentHeight = $ct.parent().height();
while ($ct.outerHeight() > parentHeight) {
percent--;
$ct.css({
fontSize: percent + '%',
lineHeight: (percent + 65) + '%'
});
if (percent < 0) {
break; // Just in case.
}
}
});
};
/**
* Resize handling.
*
* @param {Boolean} fullscreen
* @returns {undefined}
*/
CoursePresentation.prototype.resize = function () {
var fullscreenOn = this.$container.hasClass('h5p-fullscreen') || this.$container.hasClass('h5p-semi-fullscreen');
if (this.ignoreResize) {
return; // When printing.
}
// Fill up all available width
this.$wrapper.css('width', 'auto');
var width = this.$container.width();
var style = {};
if (fullscreenOn) {
var maxHeight = this.$container.height();
if (width / maxHeight > this.ratio) {
// Top and bottom would be cut off so scale down.
width = maxHeight * this.ratio;
style.width = width + 'px';
}
}
// TODO: Add support for -16 when content conversion script is created?
var widthRatio = width / this.width;
style.height = (width / this.ratio) + 'px';
style.fontSize = (this.fontSize * widthRatio) + 'px';
if (this.editor !== undefined) {
this.editor.setContainerEm(this.fontSize * widthRatio * 0.75);
}
this.$wrapper.css(style);
this.swipeThreshold = widthRatio * 100; // Default swipe threshold is 50px.
// Resize elements
var instances = this.elementInstances[this.$current.index()];
if (instances !== undefined) {
var slideElements = this.slides[this.$current.index()].elements;
for (var i = 0; i < instances.length; i++) {
var instance = instances[i];
if ((instance.preventResize === undefined || instance.preventResize === false) && instance.$ !== undefined && !slideElements[i].displayAsButton) {
H5P.trigger(instance, 'resize');
}
}
}
this.fitCT();
};
/**
* Enter/exit full screen mode.
*/
CoursePresentation.prototype.toggleFullScreen = function () {
if (H5P.isFullscreen || this.$container.hasClass('h5p-fullscreen') || this.$container.hasClass('h5p-semi-fullscreen')) {
// Cancel fullscreen
if (H5P.exitFullScreen !== undefined && H5P.fullScreenBrowserPrefix !== undefined) {
H5P.exitFullScreen();
}
else {
// Use old system
if (H5P.fullScreenBrowserPrefix === undefined) {
// Click button to disable fullscreen
H5P.jQuery('.h5p-disable-fullscreen').click();
}
else {
if (H5P.fullScreenBrowserPrefix === '') {
window.top.document.exitFullScreen();
}
else if (H5P.fullScreenBrowserPrefix === 'ms') {
window.top.document.msExitFullscreen();
}
else {
window.top.document[H5P.fullScreenBrowserPrefix + 'CancelFullScreen']();
}
}
}
}
else {
// Rescale footer buttons
this.$footer.addClass('footer-full-screen');
this.$fullScreenButton.attr('aria-label', this.l10n.exitFullscreen);
H5P.fullScreen(this.$container, this);
if (H5P.fullScreenBrowserPrefix === undefined) {
// Hide disable full screen button. We have our own!
H5P.jQuery('.h5p-disable-fullscreen').hide();
}
}
};
/**
* Set focus.
*/
CoursePresentation.prototype.focus = function () {
this.$wrapper.focus();
};
/**
* Handles click on keyword
*
* @param {number} index
*/
CoursePresentation.prototype.keywordClick = function (index) {
if (this.shouldHideKeywordsAfterSelect()) {
// Auto-hide keywords list
this.hideKeywords();
}
this.jumpToSlide(index, true);
};
CoursePresentation.prototype.shouldHideKeywordsAfterSelect = function () {
return this.presentation.keywordListEnabled &&
!this.presentation.keywordListAlwaysShow &&
this.presentation.keywordListAutoHide &&
this.editor === undefined;
};
/**
* Set the default behaviour override for all actions.
*
* @param {Object} override
*/
CoursePresentation.prototype.setElementsOverride = function (override) {
// Create default object
this.elementsOverride = {
params: {}
};
if (override) {
// Create behaviour object for overriding
this.elementsOverride.params.behaviour = {};
if (override.showSolutionButton) {
// Override show solutions button
this.elementsOverride.params.behaviour.enableSolutionsButton =
(override.showSolutionButton === 'on' ? true : false);
}
if (override.retryButton) {
// Override retry button
this.elementsOverride.params.behaviour.enableRetry =
(override.retryButton === 'on' ? true : false);
}
}
};
/**
* Attach all element instances to slide.
*
* @param {jQuery} $slide
* @param {Number} index
*/
CoursePresentation.prototype.attachElements = function ($slide, index) {
if (this.elementsAttached[index] !== undefined) {
return; // Already attached
}
var slide = this.slides[index];
var instances = this.elementInstances[index];
if (slide.elements !== undefined) {
for (var i = 0; i < slide.elements.length; i++) {
this.attachElement(slide.elements[i], instances[i], $slide, index);
}
}
this.trigger('domChanged', {
'$target': $slide,
'library': 'CoursePresentation',
'key': 'newSlide'
}, {'bubbles': true, 'external': true});
this.elementsAttached[index] = true;
};
/**
* Attach element to slide container.
*
* @param {Object} element
* @param {Object} instance
* @param {jQuery} $slide
* @param {Number} index
* @returns {jQuery}
*/
CoursePresentation.prototype.attachElement = function (element, instance, $slide, index) {
const displayAsButton = (element.displayAsButton !== undefined && element.displayAsButton);
var buttonSizeClass = (element.buttonSize !== undefined ? "h5p-element-button-" + element.buttonSize : "");
var classes = 'h5p-element' +
(displayAsButton ? ' h5p-element-button-wrapper' : '') +
(buttonSizeClass.length ? ' ' + buttonSizeClass : '');
var $elementContainer = H5P.jQuery('<div>', {
'class': classes,
}).css({
left: element.x + '%',
top: element.y + '%',
width: element.width + '%',
height: element.height + '%'
}).appendTo($slide.children('[role="document"]').first());
const isTransparent = element.backgroundOpacity === undefined || element.backgroundOpacity === 0;
$elementContainer.toggleClass('h5p-transparent', isTransparent);
if (displayAsButton) {
const $button = this.createInteractionButton(element, instance);
$button.appendTo($elementContainer);
}
else {
const hasLibrary = element.action && element.action.library;
const libTypePmz = hasLibrary ? this.getLibraryTypePmz(element.action.library) : 'other';
var $outerElementContainer = H5P.jQuery('<div>', {
'class': `h5p-element-outer ${libTypePmz}-outer-element`
}).css({
background: 'rgba(255,255,255,' + (element.backgroundOpacity === undefined ? 0 : element.backgroundOpacity / 100) + ')'
}).appendTo($elementContainer);
var $innerElementContainer = H5P.jQuery('<div>', {
'class': 'h5p-element-inner'
}).appendTo($outerElementContainer);
// H5P.Shape sets it's own size when line in selected
instance.on('set-size', function (event) {
for (let property in event.data) {
$elementContainer.get(0).style[property] = event.data[property];
}
});
instance.attach($innerElementContainer);
if (element.action !== undefined && element.action.library.substr(0, 20) === 'H5P.InteractiveVideo') {
var handleIV = function () {
instance.$container.addClass('h5p-fullscreen');
if (instance.controls.$fullscreen) {
instance.controls.$fullscreen.remove();
}
instance.hasFullScreen = true;
if (instance.controls.$play.hasClass('h5p-pause')) {
instance.$controls.addClass('h5p-autohide');
}
else {
instance.enableAutoHide();
}
};
if (instance.controls !== undefined) {
handleIV();
}
else {
instance.on('controls', handleIV);
}
}