-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
577 lines (484 loc) · 20 KB
/
index.html
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
<html>
<head>
<script type="text/javascript">
window.H5PIntegration = {
saveFreq: false,
postUserStatistics: false,
ajax: {
setFinished: undefined,
contentUserData: undefined
},
l10n: {
H5P: {
"fullscreen": "Fullscreen",
"disableFullscreen": "Disable fullscreen",
"download": "Download",
"copyrights": "Rights of use",
"embed": "Embed",
"size": "Size",
"showAdvanced": "Show advanced",
"hideAdvanced": "Hide advanced",
"advancedHelp": "Include this script on your website if you want dynamic sizing of the embedded content:",
"copyrightInformation": "Rights of use",
"close": "Close",
"title": "Title",
"author": "Author",
"year": "Year",
"source": "Source",
"license": "License",
"thumbnail": "Thumbnail",
"noCopyrights": "No copyright information available for this content.",
"reuse": "Reuse",
"reuseContent": "Reuse Content",
"reuseDescription": "Reuse this content.",
"downloadDescription": "Download this content as a H5P file.",
"copyrightsDescription": "View copyright information for this content.",
"embedDescription": "View the embed code for this content.",
"h5pDescription": "Visit H5P.org to check out more cool content.",
"contentChanged": "This content has changed since you last used it.",
"startingOver": "You'll be starting over.",
"by": "by",
"showMore": "Show more",
"showLess": "Show less",
"subLevel": "Sublevel",
"confirmDialogHeader": "Confirm action",
"confirmDialogBody": "Please confirm that you wish to proceed. This action is not reversible.",
"cancelLabel": "Cancel",
"confirmLabel": "Confirm",
"licenseU": "Undisclosed",
"licenseCCBY": "Attribution",
"licenseCCBYSA": "Attribution-ShareAlike",
"licenseCCBYND": "Attribution-NoDerivs",
"licenseCCBYNC": "Attribution-NonCommercial",
"licenseCCBYNCSA": "Attribution-NonCommercial-ShareAlike",
"licenseCCBYNCND": "Attribution-NonCommercial-NoDerivs",
"licenseCC40": "4.0 International",
"licenseCC30": "3.0 Unported",
"licenseCC25": "2.5 Generic",
"licenseCC20": "2.0 Generic",
"licenseCC10": "1.0 Generic",
"licenseGPL": "General Public License",
"licenseV3": "Version 3",
"licenseV2": "Version 2",
"licenseV1": "Version 1",
"licensePD": "Public Domain",
"licenseCC010": "CC0 1.0 Universal (CC0 1.0) Public Domain Dedication",
"licensePDM": "Public Domain Mark",
"licenseC": "Copyright",
"contentType": "Content Type",
"licenseExtras": "License Extras",
"changes": "Changelog",
"contentCopied": "Content is copied to the clipboard",
"connectionLost": "Connection lost. Results will be stored and sent when you regain connection.",
"connectionReestablished": "Connection reestablished.",
"resubmitScores": "Attempting to submit stored results.",
"offlineDialogHeader": "Your connection to the server was lost",
"offlineDialogBody": "We were unable to send information about your completion of this task. Please check your internet connection.",
"offlineDialogRetryMessage": "Retrying in :num....",
"offlineDialogRetryButtonLabel": "Retry now",
"offlineSuccessfulSubmit": "Successfully submitted results."
}
}
};
</script>
<script type="text/javascript" src="./vendor/jquery.js"></script>
<script type="text/javascript" src="./vendor/h5p.js"></script>
<script type="text/javascript" src="./vendor/h5p-event-dispatcher.js"></script>
<script type="text/javascript" src="./vendor/h5p-x-api.js"></script>
<script type="text/javascript" src="./vendor/h5p-x-api-event.js"></script>
<script type="text/javascript" src="./vendor/h5p-content-type.js"></script>
<script type="text/javascript" src="./vendor/h5p-confirmation-dialog.js"></script>
<script type="text/javascript" src="./vendor/request-queue.js"></script>
<script type="text/javascript" src="./vendor/h5p-action-bar.js"></script>
<link rel="stylesheet" href="./vendor/styles/h5p.css">
<link rel="stylesheet" href="./vendor/styles/h5p-confirmation-dialog.css">
<link rel="stylesheet" href="./vendor/styles/h5p-core-button.css">
<script type="text/javascript" src="./vendor/toposort.js"></script>
</head>
<body>
<div id="show-activity" style="display: none">
<div id='h5p-container'></div>
<details style="margin-top: 20px;">
<summary>log events: <span id='log-count'></span></summary>
<div id='logs' style="height: 200px; overflow: auto;"></div>
</details>
</div>
<div id="select-activity" style="display: none">
<ol></ol>
</div>
<script type="text/javascript">
window.H5P.preventInit = true;
// most of this section copied from https://github.com/tunapanda/h5p-standalone
function urlPath(path) {
path = path.trim();
if (path.match(/^[a-z0-9]+:\/\//i)) {
return path;
}
//if path starts with a double slash, it's protocol relative URL
if (path.startsWith('//')) {
return window.location.protocol + path;
}
//if path starts with a slash, its relative in respect to page URL root
if (path.startsWith('/')) {
return window.location.origin + path;
}
let prefix = window.location.protocol + "//" + window.location.host;
if (window.location.pathname.indexOf('/') > -1) {
prefix = prefix + window.location.pathname.split('/').slice(0, -1).join("/");
} else {
prefix = prefix + window.location.pathname;
}
return prefix + "/" + path;
}
class H5PStandalone {
constructor(el, options) {
this.id = options.id || Math.random().toString(36).substr(2, 9);
if (options.h5pJsonPath) {
this.h5pJsonPath = urlPath(options.h5pJsonPath);
} else {
this.h5pJsonPath = urlPath('workspace')
}
if (!options.librariesPath) {
this.librariesPath = this.h5pJsonPath;
} else {
this.librariesPath = urlPath(options.librariesPath);
}
if (!options.contentJsonPath) {
this.contentUrl = urlPath(`${this.h5pJsonPath}/content`);
} else {
this.contentUrl = urlPath(options.contentJsonPath);
}
const displayOptions = {
frame: options.frame, copyright: options.copyright,
embed: options.embed, icon: options.icon,
export: options.export
};
const contentOptions = {
displayOptions,
fullScreen: false,
url: window.location.href.split('?')[0].split('#')[0]
};
if (options.downloadUrl) {
contentOptions.exportUrl = urlPath(options.downloadUrl);
}
if (options.metadata) { // exposing content['id'].metadata key to allow overrides
contentOptions.metadata = options.metadata;
}
const generalIntegrationOptions = {
preventH5PInit: options.preventH5PInit ? options.preventH5PInit : false,
};
// The following behaviour may change in future
if (options.frameJs) {
generalIntegrationOptions.coreScripts = [urlPath(options.frameJs)]
} else {
generalIntegrationOptions.coreScripts = ['./frame.bundle.js']
}
// The following behaviour may change in future
if (options.frameCss) {
generalIntegrationOptions.coreStyles = [urlPath(options.frameCss)];
} else {
generalIntegrationOptions.coreStyles = [urlPath('./styles/h5p.css')];
}
if (options.fullScreen) {
contentOptions.fullScreen = options.fullScreen
}
if (options.xAPIObjectIRI) {
contentOptions.url = options.xAPIObjectIRI; //no validation
}
if (options.embedCode) { // this will not be dependent on displayOptions.embed
contentOptions.embedCode = options.embedCode;
contentOptions.resizeCode = options.resizeCode || ''; // resize code is already bundled in main.bundle.js
}
// Custom options for styles and scripts in analogy to regular H5P overrides
if (typeof options.customCss === 'string') {
options.customCss = [options.customCss];
}
if (typeof options.customJs === 'string') {
options.customJs = [options.customJs];
}
const customOptions = {
customCss: (options.customCss || []).map(style => [urlPath(style)] ),
customJs: (options.customJs || []).map(script => [urlPath(script)] ),
};
if (options.contentUserData) {
contentOptions.contentUserData = options.contentUserData;
}
/**
* following options overrides global H5PIntegration.
*/
if (options.saveFreq) {
H5PIntegration.saveFreq = options.saveFreq
}
if (options.postUserStatistics) {
H5PIntegration.postUserStatistics = false
}
if (options.ajax && options.ajax.setFinishedUrl) {
H5PIntegration.ajax.setFinished = options.ajax.setFinishedUrl
}
if (options.user) {
H5PIntegration['user'] = options.user;
}
if (options.ajax && options.ajax.contentUserDataUrl) {
H5PIntegration.ajax.contentUserData = options.ajax.contentUserDataUrl
}
this.initElement(el);
return this.initH5P(generalIntegrationOptions, contentOptions, customOptions);
}
initElement(el) {
if (!(el instanceof HTMLElement)) {
throw new Error('createH5P must be passed an element');
}
const parent = document.createElement('div');
parent.classList.add('h5p-iframe-wrapper');
parent.style.backgroundColor = '#DDD;';
const iframe = document.createElement('iframe');
iframe.id = `h5p-iframe-${this.id}`;
iframe.src = 'about:blank';
iframe.classList.add('h5p-iframe');
iframe.setAttribute('scrolling', 'no');
iframe.setAttribute('data-content-id', `${this.id}`);
iframe.setAttribute('frameBorder', 0);
iframe.style.width = '100%'
iframe.style.height = '100%'
iframe.style.border = 'none'
iframe.style.display = 'block'
parent.append(iframe);
el.append(parent);
// inject jQuery property to avoid fatal error if required
iframe.contentWindow['jQuery'] = null;
}
async initH5P(generalIntegrationOptions, contentOptions, customOptions) {
this.h5p = await this.getJSON(`${this.h5pJsonPath}/h5p.json`);
const content = await this.getJSON(`${this.contentUrl}/content.json`);
H5PIntegration.pathIncludesVersion = this.pathIncludesVersion = await this.checkIfPathIncludesVersion();
this.mainLibrary = await this.findMainLibrary();
const dependencies = await this.findAllDependencies();
const { styles, scripts } = this.sortDependencies(dependencies, customOptions);
H5PIntegration.urlLibraries = this.librariesPath;
H5PIntegration.contents = H5PIntegration.contents ? H5PIntegration.contents : {};
// this supports embed type = iframe
H5PIntegration.core = {
styles: generalIntegrationOptions.coreStyles,
scripts: generalIntegrationOptions.coreScripts
};
// if embed type is `div` the assets need to be loaded in the parent
for (const script of scripts) {
await new Promise(resolve => {
var scriptTag = document.createElement('script');
scriptTag.setAttribute('src', script);
scriptTag.onload = () => resolve();
document.head.appendChild(scriptTag);
});
}
for (const style of styles) {
var styleTag = document.createElement('link');
styleTag.setAttribute('href', style);
styleTag.setAttribute('rel', 'stylesheet');
document.head.appendChild(styleTag);
}
H5PIntegration.contents[`cid-${this.id}`] = {
library: `${this.mainLibrary.machineName} ${this.mainLibrary.majorVersion}.${this.mainLibrary.minorVersion}`,
jsonContent: JSON.stringify(content),
styles: styles,
scripts: scripts,
displayOptions: contentOptions.displayOptions,
contentUrl: this.contentUrl,
metadata: {}
};
for (const key in contentOptions) {
if (H5PIntegration.contents[`cid-${this.id}`][key] == undefined) { //this is just a guard
H5PIntegration.contents[`cid-${this.id}`][key] = contentOptions[key];
}
}
// add missing content metadata from h5p.json
for (const key in this.h5p) {
if (H5PIntegration.contents[`cid-${this.id}`]['metadata'][key] === undefined) {
H5PIntegration.contents[`cid-${this.id}`]['metadata'][key] = this.h5p[key]
}
}
if (!generalIntegrationOptions.preventH5PInit) {
H5P.init();
}
}
getJSON(url) {
return fetch(url).then(res => res.json());
}
/**
* Check if the library folder include the version or not
* This was changed at some point in H5P and we need to be backwards compatible
*
* @return {boolean}
*/
async checkIfPathIncludesVersion() {
let dependency = this.h5p.preloadedDependencies[0];
let machinePath = dependency.machineName + "-" + dependency.majorVersion + "." + dependency.minorVersion;
let pathIncludesVersion;
try {
await this.getJSON(`${this.librariesPath}/${machinePath}/library.json`);
pathIncludesVersion = true;
} catch (e) {
pathIncludesVersion = false;
}
return pathIncludesVersion;
}
/**
* return the path to a library
* @param {object} library
* @return {string}
*/
libraryPath(library) {
return library.machineName + (this.pathIncludesVersion ? "-" + library.majorVersion + "." + library.minorVersion : '');
}
/**
* FInd the main library for this H5P
* @return {Promise}
*/
findMainLibrary() {
const mainLibraryInfo = this.h5p.preloadedDependencies.find(dep => dep.machineName === this.h5p.mainLibrary);
this.mainLibraryPath = this.h5p.mainLibrary + (this.pathIncludesVersion ? "-" + mainLibraryInfo.majorVersion + "." + mainLibraryInfo.minorVersion : '');
return this.getJSON(`${this.librariesPath}/${this.mainLibraryPath}/library.json`);
}
/**
* find all the libraries used in this H5P
* @return {Promise}
*/
findAllDependencies() {
const directDependencyNames = this.h5p.preloadedDependencies.map(dependency => this.libraryPath(dependency));
return this.loadDependencies(directDependencyNames, []);
}
/**
* searches through all supplied libraries for dependencies, this is recursive and repeats until all deep dependencies have been found
* @param {string[]} toFind list of libraries to find the dependencies of
* @param {string[]} alreadyFound the dependencies that have already been found
*/
async loadDependencies(toFind, alreadyFound) {
// console.log(`loading dependency level: ${dependencyDepth}`);
// dependencyDepth++;
let dependencies = alreadyFound;
let findNext = [];
let newDependencies = await Promise.all(toFind.map((libraryName) => this.findLibraryDependencies(libraryName)));
// loop over newly found libraries
newDependencies.forEach((library) => {
// push into found list
dependencies.push(library);
// check if any dependencies haven't been found yet
library.dependencies.forEach((dependency) => {
if (!dependencies.find((foundLibrary) => foundLibrary.libraryPath === dependency) && !newDependencies.find((foundLibrary) => foundLibrary.libraryPath === dependency)) {
findNext.push(dependency);
}
});
});
if (findNext.length > 0) {
return this.loadDependencies(findNext, dependencies);
}
return dependencies;
}
/**
* Loads a dependencies library.json and finds the libraries it dependson as well ass the JS and CSS it needs
* @param {string} libraryName
*/
async findLibraryDependencies(libraryName) {
const library = await this.getJSON(`${this.librariesPath}/${libraryName}/library.json`);
const libraryPath = this.libraryPath(library);
let dependencies = [];
if (library.preloadedDependencies) {
dependencies = library.preloadedDependencies.map(dependency => this.libraryPath(dependency));
}
return { libraryPath, dependencies, preloadedCss: library.preloadedCss, preloadedJs: library.preloadedJs };
}
/**
* Resolves the library dependency tree and sorts the JS and CSS files into order
* @param {object[]} dependencies
* @param {object[]} customOptions Custom options for styles and scripts.
* @param {string[]} customOptions.customCss Paths of custom stylesheet files.
* @param {string[]} customOptions.customJs Paths of custom script files.
* @return {object}
*/
sortDependencies(dependencies, customOptions) {
const dependencySorter = new Toposort();
let CSSDependencies = {};
let JSDependencies = {};
dependencies.forEach(dependency => {
dependencySorter.add(dependency.libraryPath, dependency.dependencies);
if (dependency.preloadedCss) {
CSSDependencies[dependency.libraryPath] = CSSDependencies[dependency.libraryPath] ? CSSDependencies[dependency.libraryPath] : [];
dependency.preloadedCss.forEach(style => {
CSSDependencies[dependency.libraryPath].push(`${this.librariesPath}/${dependency.libraryPath}/${style.path}`);
});
}
if (dependency.preloadedJs) {
JSDependencies[dependency.libraryPath] = JSDependencies[dependency.libraryPath] ? JSDependencies[dependency.libraryPath] : [];
dependency.preloadedJs.forEach(script => {
JSDependencies[dependency.libraryPath].push(`${this.librariesPath}/${dependency.libraryPath}/${script.path}`);
});
}
});
let styles = [];
let scripts = [];
dependencySorter.sort().reverse().forEach(function (dependencyName) {
Array.prototype.push.apply(styles, CSSDependencies[dependencyName]);
Array.prototype.push.apply(scripts, JSDependencies[dependencyName]);
});
// Append custom styles and scripts at the end to override original values
styles = styles.concat(customOptions.customCss);
scripts = scripts.concat(customOptions.customJs);
return { styles, scripts };
}
}
</script>
<script type="text/javascript">
const basePath = location.pathname.replace(/\/+$/, '/');
if (location.search === '') {
const container = document.getElementById('select-activity')
const list = container.querySelector('ol');
fetch(basePath + 'h5p-test/activities/activities.txt')
.then(response => response.text())
.then(text => text.split('\n').filter(x => !!x))
.then(files => files.forEach(file => {
const li = document.createElement('li')
const a = document.createElement('a')
a.href = `?activity=${file}`
a.textContent = file;
li.appendChild(a);
list.appendChild(li);
}))
.then(() => {
container.style.display = 'block';
});
;
} else {
document.getElementById('show-activity').style.display = 'block';
H5PStandalone.prototype.initElement = function(el) {
if (!(el instanceof HTMLElement)) {
throw new Error('createH5P must be passed an element');
}
const parent = document.createElement('div');
parent.classList.add('h5p-content');
parent.setAttribute('data-content-id', `${this.id}`);
el.append(parent);
}
const el = document.getElementById('h5p-container');
const options = {
librariesPath: basePath + 'h5p-test/libraries',
h5pJsonPath: basePath + 'h5p-test/activities/' + location.search.replace('?activity=', ''),
frameJs: basePath + 'node_modules/h5p-standalone/dist/frame.bundle.js',
frameCss: basePath + 'node_modules/h5p-standalone/dist/styles/h5p.css',
frame: true, // Show frame and buttons below H5P
copyright: true, // Display copyright button
icon: true // Display H5P icon
}
new H5PStandalone(el, options);
const logCountElement = document.getElementById('log-count');
const logsElement = document.getElementById('logs');
let logCount = 0;
H5P.externalDispatcher.on('xAPI', function (event) {
logCount++;
logCountElement.innerText = logCount;
const codeTag = document.createElement('pre');
codeTag.innerText = JSON.stringify(event.data.statement, null, 2);
logsElement.append(codeTag);
});
}
</script>
</body>
</html>