-
Notifications
You must be signed in to change notification settings - Fork 115
/
h5peditor.js
1887 lines (1701 loc) · 53.5 KB
/
h5peditor.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
/* global ns */
/**
* This file contains helper functions for the editor.
*/
// Grab common resources set in parent window, but avoid sharing back resources set in iframe)
window.ns = window.H5PEditor = H5P.jQuery.extend(false, {}, window.parent.H5PEditor);
ns.$ = H5P.jQuery;
// Load needed resources from parent.
H5PIntegration = H5P.jQuery.extend(false, {}, window.parent.H5PIntegration);
H5PIntegration.loadedJs = [];
H5PIntegration.loadedCss = [];
/**
* Constants used within editor
*
* @type {{otherLibraries: string}}
*/
ns.constants = {
otherLibraries: 'Other Libraries',
};
/**
* Keep track of our widgets.
*/
ns.widgets = {};
/**
* Caches library data (semantics, js and css)
*/
ns.libraryCache = {};
/**
* Keeps track of callbacks to run once a library gets loaded.
*/
ns.loadedCallbacks = [];
/**
* Keep track of which libraries have been loaded in the browser, i.e CSS is
* added and JS have been run
*
* @type {Object}
*/
ns.libraryLoaded = {};
/**
* Indiciates if the user is using Internet Explorer.
*/
ns.isIE = navigator.userAgent.match(/; MSIE \d+.\d+;/) !== null;
/**
* Keep track of renderable common fields.
*
* @type {Object}
*/
ns.renderableCommonFields = {};
(() => {
const loading = {}; // Map of callbacks for each src being loaded
/**
* Help load JavaScripts, prevents double loading.
*
* @param {string} src
* @param {Function} done Callback
*/
ns.loadJs = (src, done) => {
if (H5P.jsLoaded(src)) {
// Already loaded
done();
return;
}
if (loading[src] !== undefined) {
// Loading in progress...
loading[src].push(done);
return;
}
loading[src] = [done];
// Load using script tag
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'UTF-8';
script.async = false;
script.onload = function () {
H5PIntegration.loadedJs.push(src);
loading[src].forEach(cb => cb());
delete loading[src];
};
script.onerror = function (err) {
loading[src].forEach(cb => cb(err));
delete loading[src];
};
script.src = src;
document.head.appendChild(script);
};
})();
/**
* Helper function invoked when a library is requested. Will add CSS and eval JS
* if not already done.
*
* @private
* @param {string} libraryName On the form "machineName majorVersion.minorVersion"
* @param {Function} callback
*/
ns.libraryRequested = function (libraryName, callback) {
var libraryData = ns.libraryCache[libraryName];
if (!ns.libraryLoaded[libraryName]) {
// Add CSS.
if (libraryData.css !== undefined) {
libraryData.css.forEach(function (path) {
if (!H5P.cssLoaded(path)) {
H5PIntegration.loadedCss.push(path);
if (path) {
ns.$('head').append('<link ' +
'rel="stylesheet" ' +
'href="' + path + '" ' +
'type="text/css" ' +
'/>');
}
}
});
}
// Add JS
var loadingJs = false;
if (libraryData.javascript !== undefined && libraryData.javascript.length) {
libraryData.javascript.forEach(function (path) {
if (!H5P.jsLoaded(path)) {
loadingJs = true;
ns.loadJs(path, function (err) {
if (err) {
console.error('Error while loading script', err);
return;
}
var isFinishedLoading = libraryData.javascript.reduce(function (hasLoaded, jsPath) {
return hasLoaded && H5P.jsLoaded(jsPath);
}, true);
if (isFinishedLoading) {
ns.libraryLoaded[libraryName] = true;
// Need to set translations after all scripts have been loaded
if (libraryData.translations) {
for (var machineName in libraryData.translations) {
H5PEditor.language[machineName] = libraryData.translations[machineName];
}
}
callback(ns.libraryCache[libraryName].semantics);
}
});
}
});
}
if (!loadingJs) {
// Don't have to wait for any scripts, run callback
ns.libraryLoaded[libraryName] = true;
callback(ns.libraryCache[libraryName].semantics);
}
}
else {
// Already loaded, run callback
callback(ns.libraryCache[libraryName].semantics);
}
};
/**
* Loads the given library, inserts any css and js and
* then runs the callback with the samantics as an argument.
*
* @param {string} libraryName
* On the form machineName majorVersion.minorVersion
* @param {function} callback
* @returns {undefined}
*/
ns.loadLibrary = function (libraryName, callback) {
switch (ns.libraryCache[libraryName]) {
default:
// Get semantics from cache.
ns.libraryRequested(libraryName, callback);
break;
case 0:
// Add to queue.
if (ns.loadedCallbacks[libraryName] === undefined) {
ns.loadedCallbacks[libraryName] = [];
}
ns.loadedCallbacks[libraryName].push(callback);
break;
case undefined:
// Load semantics.
ns.libraryCache[libraryName] = 0; // Indicates that others should queue.
ns.loadedCallbacks[libraryName] = []; // Other callbacks to run once loaded.
var library = ns.libraryFromString(libraryName);
var url = ns.getAjaxUrl('libraries', library);
// Add content language to URL
if (ns.contentLanguage !== undefined) {
url += (url.indexOf('?') === -1 ? '?' : '&') + 'language=' + ns.contentLanguage;
}
// Add common fields default lanuage to URL
const defaultLanguage = ns.defaultLanguage; // Avoid changes after sending AJAX
if (defaultLanguage !== undefined) {
url += (url.indexOf('?') === -1 ? '?' : '&') + 'default-language=' + defaultLanguage;
}
// Fire away!
ns.$.ajax({
url: url,
success: function (libraryData) {
libraryData.translation = { // Used to cache all the translations
en: libraryData.semantics
};
let languageSemantics = [];
if (libraryData.language !== null) {
languageSemantics = JSON.parse(libraryData.language).semantics;
delete libraryData.language; // Avoid caching a lot of unused data
}
var semantics = ns.$.extend(true, [], libraryData.semantics, languageSemantics);
if (libraryData.defaultLanguage !== null) {
libraryData.translation[defaultLanguage] = JSON.parse(libraryData.defaultLanguage).semantics;
delete libraryData.defaultLanguage; // Avoid caching a lot of unused data
ns.updateCommonFieldsDefault(semantics, libraryData.translation[defaultLanguage]);
}
libraryData.semantics = semantics;
ns.libraryCache[libraryName] = libraryData;
ns.libraryRequested(libraryName, function (semantics) {
callback(semantics);
// Run queue.
if (ns.loadedCallbacks[libraryName]) {
for (var i = 0; i < ns.loadedCallbacks[libraryName].length; i++) {
ns.loadedCallbacks[libraryName][i](semantics);
}
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
if (window['console'] !== undefined) {
console.warn('Ajax request failed');
console.warn(jqXHR);
console.warn(textStatus);
console.warn(errorThrown);
}
},
dataType: 'json'
});
}
};
/**
* Update common fields default values for the given semantics.
* Works by reference.
*
* @param {Array} semantics
* @param {Array} translation
* @param {boolean} [parentIsCommon] Used to indicated that one of the ancestors is a common field
*/
ns.updateCommonFieldsDefault = function (semantics, translation, parentIsCommon) {
for (let i = 0; i < semantics.length; i++) {
const isCommon = (semantics[i].common === true || parentIsCommon);
if (isCommon && semantics[i].default !== undefined &&
translation[i] !== undefined && translation[i].default !== undefined) {
// Update value
semantics[i].default = translation[i].default;
}
if (semantics[i].fields !== undefined && semantics[i].fields.length &&
translation[i].fields !== undefined && translation[i].fields.length) {
// Look into sub fields
ns.updateCommonFieldsDefault(semantics[i].fields, translation[i].fields, isCommon);
}
if (semantics[i].field !== undefined && translation[i].field !== undefined ) {
// Look into sub field
ns.updateCommonFieldsDefault([semantics[i].field], [translation[i].field], isCommon);
}
}
};
/**
* Reset loaded libraries - i.e removes CSS added previously.
* @method
* @return {[type]}
*/
ns.resetLoadedLibraries = function () {
ns.$('head style.h5p-editor-style').remove();
H5PIntegration.loadedCss = [];
H5PIntegration.loadedJs = [];
ns.loadedCallbacks = [];
ns.libraryLoaded = {};
ns.libraryCache = {};
};
/**
* Render common fields of content type with given machine name
*
* @param {string} machineName Machine name of content type with common fields
* @param {Array} [libraries] Library data for machine name
*/
ns.renderCommonField = function (machineName, libraries) {
var commonFields = ns.renderableCommonFields[machineName].fields;
var renderableCommonFields = [];
var ancestor;
commonFields.forEach(function (field) {
if (!field.rendered) {
var commonField = ns.addCommonField(
field.field,
field.parent,
field.params,
field.ancestor,
true
);
if (commonField.setValues.length === 1) {
renderableCommonFields.push({
field: field,
instance: commonField.instance
});
field.instance = commonField.instance;
}
}
field.rendered = true;
});
// Render common fields if found
if (renderableCommonFields.length) {
var libraryName = machineName === ns.constants.otherLibraries ? machineName
: (machineName.length ? machineName.split(' ')[0] : '');
if (libraries.length && libraries[0].title) {
libraryName = libraries[0].title;
}
// Create a library wrapper
var hasLibraryWrapper = !!ns.renderableCommonFields[machineName].wrapper;
var commonFieldsLibraryWrapper = ns.renderableCommonFields[machineName].wrapper;
if (!hasLibraryWrapper) {
commonFieldsLibraryWrapper = document.createElement('fieldset');
var libraryWrapperClass = libraryName.replace(/\s+/g, '-').toLowerCase();
commonFieldsLibraryWrapper.classList.add('common-fields-library-wrapper');
commonFieldsLibraryWrapper.classList.add('common-fields-' + libraryWrapperClass);
var libraryTitle = document.createElement('legend');
libraryTitle.classList.add('common-field-legend');
libraryTitle.textContent = libraryName;
libraryTitle.tabIndex = '0';
libraryTitle.setAttribute('role', 'button');
libraryTitle.addEventListener('click', function () {
commonFieldsLibraryWrapper.classList.toggle('expanded');
});
libraryTitle.addEventListener('keypress', function (e) {
if (e.which === 32) {
commonFieldsLibraryWrapper.classList.toggle('expanded');
}
});
commonFieldsLibraryWrapper.appendChild(libraryTitle);
ns.renderableCommonFields[machineName].wrapper = commonFieldsLibraryWrapper;
}
renderableCommonFields.forEach(function (commonField) {
commonField.instance.appendTo(ns.$(commonFieldsLibraryWrapper));
// Gather under a common ancestor
if (commonField.field && commonField.field.ancestor) {
ancestor = commonField.field.ancestor;
// Ensure that params are updated after common field instance is
// appended since this ensures that defaults are set for common fields
const field = commonField.field;
const library = field.parent.currentLibrary;
const fieldName = field.field.name;
const ancestorField = ancestor.commonFields[library][fieldName];
ancestorField.params = field.params[fieldName];
}
});
if (!hasLibraryWrapper && ancestor) {
ancestor.$common[0].appendChild(commonFieldsLibraryWrapper);
}
}
};
/**
* Recursively traverse parents to find the library our field belongs to
*
* @param parent
* @returns {*}
*/
ns.getParentLibrary = function (parent) {
if (!parent) {
return null;
}
if (parent.currentLibrary) {
return parent.currentLibrary;
}
return ns.getParentLibrary(parent.parent);
};
/**
* Recursive processing of the semantics chunks.
*
* @param {array} semanticsChunk
* @param {object} params
* @param {jQuery} $wrapper
* @param {mixed} parent
* @param {string} [machineName] Machine name of library that is being processed
* @returns {undefined}
*/
ns.processSemanticsChunk = function (semanticsChunk, params, $wrapper, parent, machineName) {
var ancestor;
parent.children = [];
if (parent.passReadies === undefined) {
throw 'Widget tried to run processSemanticsChunk without handling ready callbacks. [field:' + parent.field.type + ':' + parent.field.name + ']';
}
if (!parent.passReadies) {
// If the parent can't pass ready callbacks we need to take care of them.
parent.readies = [];
}
for (var i = 0; i < semanticsChunk.length; i++) {
var field = semanticsChunk[i];
// Check generic field properties.
if (field.name === undefined) {
throw ns.t('core', 'missingProperty', {':index': i, ':property': 'name'});
}
if (field.type === undefined) {
throw ns.t('core', 'missingProperty', {':index': i, ':property': 'type'});
}
// Set default value.
if (params[field.name] === undefined && field['default'] !== undefined) {
params[field.name] = field['default'];
}
var widget = ns.getWidgetName(field);
// TODO: Remove later, this is here for debugging purposes.
if (ns.widgets[widget] === undefined) {
$wrapper.append('<div>[field:' + field.type + ':' + widget + ':' + field.name + ']</div>');
continue;
}
// Add common fields to bottom of form.
if (field.common !== undefined && field.common) {
if (ancestor === undefined) {
ancestor = ns.findAncestor(parent);
}
var parentLibrary = ns.getParentLibrary(parent);
var library = machineName ? machineName
: (field.library ? field.library
: (parentLibrary ? parentLibrary
: ns.constants.otherLibraries));
ns.renderableCommonFields[library] = ns.renderableCommonFields[library] || {};
ns.renderableCommonFields[library].fields = ns.renderableCommonFields[library].fields || [];
// Add renderable if it doesn't exist
ns.renderableCommonFields[library].fields.push({
field: field,
parent: parent,
params: params,
ancestor: ancestor,
rendered: false
});
continue;
}
var fieldInstance = new ns.widgets[widget](parent, field, params[field.name], function (field, value) {
if (value === undefined) {
delete params[field.name];
}
else {
params[field.name] = value;
}
});
fieldInstance.appendTo($wrapper);
parent.children.push(fieldInstance);
}
// Render all gathered common field
if (ns.renderableCommonFields) {
for (var commonFieldMachineName in ns.renderableCommonFields) {
if (commonFieldMachineName === ns.constants.otherLibraries) {
// No need to grab library info
ns.renderCommonField(commonFieldMachineName);
}
else {
// Get title for common fields group
H5PEditor.LibraryListCache.getLibraries(
[commonFieldMachineName],
ns.renderCommonField.bind(this, commonFieldMachineName)
);
}
}
}
if (!parent.passReadies) {
// Run ready callbacks.
for (i = 0; i < parent.readies.length; i++) {
parent.readies[i]();
}
delete parent.readies;
}
};
/**
* Attach ancestor of parent's common fields to a new wrapper
*
* @param {Object} parent Parent content type instance that common fields should be attached to
* @param {HTMLElement} wrapper New wrapper of common fields
*/
ns.setCommonFieldsWrapper = function (parent, wrapper) {
var ancestor = ns.findAncestor(parent);
// Hide the ancestor whose children will be reattached elsewhere
wrapper.appendChild(ancestor.$common[0]);
};
/**
* Add a field to the common container.
*
* @param {object} field
* @param {object} parent
* @param {object} params
* @param {object} ancestor
* @param {boolean} [skipAppendTo] Skips appending the common field if set
* @returns {undefined}
*/
ns.addCommonField = function (field, parent, params, ancestor, skipAppendTo) {
var commonField;
// Group all fields based on library name + version
if (ancestor.commonFields[parent.currentLibrary] === undefined) {
ancestor.commonFields[parent.currentLibrary] = {};
}
// Field name will have to be unique for library
if (ancestor.commonFields[parent.currentLibrary][field.name] === undefined) {
var widget = ns.getWidgetName(field);
ancestor.commonFields[parent.currentLibrary][field.name] = {
instance: new ns.widgets[widget](parent, field, params[field.name], function (field, value) {
for (var i = 0; i < commonField.setValues.length; i++) {
commonField.setValues[i](field, value);
}
}),
setValues: [],
parents: []
};
}
commonField = ancestor.commonFields[parent.currentLibrary][field.name];
commonField.parents.push(ns.findLibraryAncestor(parent));
commonField.setValues.push(function (field, value) {
if (value === undefined) {
delete params[field.name];
}
else {
params[field.name] = value;
}
});
if (commonField.setValues.length === 1) {
ancestor.$common.parent().removeClass('hidden');
if (!skipAppendTo) {
commonField.instance.appendTo(ancestor.$common);
}
commonField.params = params[field.name];
}
else {
params[field.name] = commonField.params;
}
parent.children.push(commonField.instance);
return commonField;
};
/**
* Find the nearest library ancestor. Used when adding commonfields.
*
* @param {object} parent
* @returns {ns.findLibraryAncestor.parent|@exp;ns@call;findLibraryAncestor}
*/
ns.findLibraryAncestor = function (parent) {
if (parent.parent === undefined || parent.field.type === 'library') {
return parent;
}
return ns.findLibraryAncestor(parent.parent);
};
/**
* getParentZebra
*
* Alternate the background color of fields
*
* @param parent
* @returns {string} to determine background color of callee
*/
ns.getParentZebra = function (parent) {
if (parent.zebra) {
return parent.zebra;
}
else {
return ns.getParentZebra(parent.parent);
}
};
/**
* Find the nearest ancestor which handles commonFields.
*
* @param {type} parent
* @returns {@exp;ns@call;findAncestor|ns.findAncestor.parent}
*/
ns.findAncestor = function (parent) {
if (parent.commonFields === undefined) {
return ns.findAncestor(parent.parent);
}
return parent;
};
/**
* Call remove on the given children.
*
* @param {Array} children
* @returns {unresolved}
*/
ns.removeChildren = function (children) {
if (children === undefined) {
return;
}
for (var i = 0; i < children.length; i++) {
// Common fields will be removed by library.
var isCommonField = (children[i].field === undefined ||
children[i].field.common === undefined ||
!children[i].field.common);
var hasRemove = (children[i].remove instanceof Function ||
typeof children[i].remove === 'function');
if (isCommonField && hasRemove) {
children[i].remove();
}
}
};
/**
* Find field from path.
*
* @param {String} path
* @param {Object} parent
* @returns {@exp;ns.Form@call;findField|Boolean}
*/
ns.findField = function (path, parent) {
if (typeof path === 'string') {
path = path.split('/');
}
if (path[0] === '..') {
path.splice(0, 1);
return ns.findField(path, parent.parent);
}
if (parent.children) {
for (var i = 0; i < parent.children.length; i++) {
if (parent.children[i].field.name === path[0]) {
path.splice(0, 1);
if (path.length) {
return ns.findField(path, parent.children[i]);
}
else {
return parent.children[i];
}
}
}
}
return false;
};
/**
* Find a semantics field in the semantics structure by name of the field
* Will return the first found by depth first search if there are identically named fields
*
* @param {string} fieldName Name of the field we wish to find
* @param {Object|Array} semanticsStructure Semantics we wish to find the field within
* @returns {null|Object} Returns the field if found, otherwise null.
*/
ns.findSemanticsField = function (fieldName, semanticsStructure) {
if (Array.isArray(semanticsStructure)) {
for (let i = 0; i < semanticsStructure.length; i++) {
var semanticsField = ns.findSemanticsField(fieldName, semanticsStructure[i]);
if (semanticsField !== null) {
// Return immediately if field is found
return semanticsField;
}
}
return null;
}
else if (semanticsStructure.name === fieldName) {
return semanticsStructure;
}
else if (semanticsStructure.field) {
// Process field
return ns.findSemanticsField(fieldName, semanticsStructure.field);
}
else if (semanticsStructure.fields) {
// Process fields
return ns.findSemanticsField(fieldName, semanticsStructure.fields);
}
else {
// No matching semantics found within known properties and list structures
return null;
}
};
/**
* Follow a field and get all changes to its params.
*
* @param {Object} parent The parent object of the field.
* @param {String} path Relative to parent object.
* @param {Function} callback Gets called for params changes.
* @returns {undefined}
*/
ns.followField = function (parent, path, callback) {
if (path === undefined) {
return;
}
// Find field when tree is ready.
parent.ready(function () {
var def;
if (path instanceof Object) {
// We have an object with default values
def = H5P.cloneObject(path);
if (path.field === undefined) {
callback(path, null);
return; // Exit if we have no field to follow.
}
path = def.field;
delete def.field;
}
var field = ns.findField(path, parent);
if (!field) {
throw ns.t('core', 'unknownFieldPath', {':path': path});
}
if (field.changes === undefined) {
throw ns.t('core', 'noFollow', {':path': path});
}
var params = (field.params === undefined ? def : field.params);
callback(params, field.changes.length + 1);
field.changes.push(function () {
var params = (field.params === undefined ? def : field.params);
callback(params);
});
});
};
/**
* Create HTML wrapper for error messages.
*
* @param {String} message
* @returns {String}
*/
ns.createError = function (message) {
return '<p>' + message + '</p>';
};
/**
* Turn a numbered importance into a string.
*
* @param {string} importance
* @returns {String}
*/
ns.createImportance = function (importance) {
return importance ? 'importance-' + importance : '';
};
/**
* Create HTML wrapper for field items.
* Makes sure the different elements are placed in an consistent order.
*
* @param {string} type
* @param {string} [label]
* @param {string} [description]
* @param {string} [content]
* @deprecated since version 1.12 (Jan. 2017, will be removed Jan. 2018). Use createFieldMarkup instead.
* @see createFieldMarkup
* @returns {string} HTML
*/
ns.createItem = function (type, label, description, content) {
return '<div class="field ' + type + '">' +
(label ? label : '') +
(description ? '<div class="h5peditor-field-description">' + description + '</div>' : '') +
(content ? content : '') +
'<div class="h5p-errors"></div>' +
'</div>';
};
/**
* An object describing the semantics of a field
* @typedef {Object} SemanticField
* @property {string} name
* @property {string} type
* @property {string} label
* @property {string} [importance]
* @property {string} [description]
* @property {string} [widget]
* @property {boolean} [optional]
*/
/**
* Create HTML wrapper for a field item.
* Replacement for createItem()
*
* @since 1.12
* @param {SemanticField} field
* @param {string} content
* @param {string} [inputId]
* @return {string}
*/
ns.createFieldMarkup = function (field, content, inputId) {
content = content || '';
var markup = this.createLabel(field, '', inputId) + this.createDescription(field.description, inputId) + content;
return this.wrapFieldMarkup(field, markup);
};
/**
* Create HTML wrapper for a boolean field item.
*
* @param {SemanticField} field
* @param {string} content
* @param {string} [inputId]
*
* @return {string}
*/
ns.createBooleanFieldMarkup = function (field, content, inputId) {
var markup = '<label class="h5peditor-label">' +
content + (field.label || field.name || '') + '</label>' +
this.createDescription(field.description, inputId);
return this.wrapFieldMarkup(field, markup);
};
/**
* Wraps a field with some metadata classes, and adds error field
*
* @param {SemanticField} field
* @param {string} markup
*
* @private
* @return {string}
*/
ns.wrapFieldMarkup = function (field, markup) {
// removes undefined and joins
var wrapperClasses = this.joinNonEmptyStrings(['field', 'field-name-' + field.name, field.type, ns.createImportance(field.importance), field.widget]);
// wrap and return
return '<div class="' + wrapperClasses + '">' +
markup +
'<div class="h5p-errors"></div>' +
'</div>';
};
/**
* Joins an array of strings if they are defined and non empty
*
* @param {string[]} arr
* @param {string} [separator] Default is space
* @return {string}
*/
ns.joinNonEmptyStrings = function (arr, separator) {
separator = separator || ' ';
return arr.filter(function (str) {
return str !== undefined && str.length > 0;
}).join(separator);
};
/**
* Create HTML for select options.
*
* @param {String} value
* @param {String} text
* @param {Boolean} selected
* @returns {String}
*/
ns.createOption = function (value, text, selected) {
return '<option value="' + value + '"' + (selected !== undefined && selected ? ' selected="selected"' : '') + '>' + text + '</option>';
};
/**
* Create HTML for text input.
*
* @param {String} value
* @param {number} maxLength
* @param {String} placeholder
* @param {number} [id]
* @param {number} [describedby]
* @returns {String}
*/
ns.createText = function (value, maxLength, placeholder, id, describedby) {
var html = '<input class="h5peditor-text" type="text"';
if (id !== undefined) {
html += ' id="' + id + '"';
}
if (describedby !== undefined) {
html += ' aria-describedby="' + describedby + '"';
}
if (value !== undefined) {
html += ' value="' + value + '"';
}
if (placeholder !== undefined) {
html += ' placeholder="' + placeholder + '"';
}
html += ' maxlength="' + (maxLength === undefined ? 255 : maxLength) + '"/>';
return html;
};
ns.getNextFieldId = (function (counter) {
/**
* Generates a consistent and unique field ID for the given field.
*
* @param {Object} field
* @return {number}
*/
return function (field) {
return 'field-' + field.name.toLowerCase() + '-' + (counter++);
};
})(-1);
/**
* Helps generates a consistent description ID across fields.
*
* @param {string} id
* @return {string}
*/
ns.getDescriptionId = function (id) {
return id + '-description';
};
/**
* Create a label to wrap content in.
*
* @param {SemanticField} field
* @param {String} [content]
* @param {String} [inputId]
* @returns {String}
*/
ns.createLabel = function (field, content, inputId) {
// New items can be added next to the label within the flex-wrapper
var html = '<label class="h5peditor-label-wrapper"';
if (inputId !== undefined) {
html += ' for="' + inputId + '"';
}
html+= '>'
// Temporary fix for the old version of CoursePresentation's custom editor
if (field.widget === 'coursepresentation' && field.name === 'presentation') {
field.label = 0;
}
if (field.label !== 0) {
html += '<span class="h5peditor-label' + (field.optional ? '' : ' h5peditor-required') + '">' + (field.label === undefined ? field.name : field.label) + '</span>';
}
return html + (content || '') + '</label>';
};
/**
* Create a description
* @param {String} description
* @param {number} [inputId] Used to reference description from input
* @returns {string}