generated from svfranklindemo/xsc-xwalk-site-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib-franklin.js
802 lines (748 loc) · 26.1 KB
/
lib-franklin.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
/* eslint-disable max-classes-per-file */
/*
* Copyright 2022 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* log RUM if part of the sample.
* @param {string} checkpoint identifies the checkpoint in funnel
* @param {Object} data additional data for RUM sample
*/
export function sampleRUM(checkpoint, data = {}) {
sampleRUM.defer = sampleRUM.defer || [];
const defer = (fnname) => {
sampleRUM[fnname] = sampleRUM[fnname]
|| ((...args) => sampleRUM.defer.push({ fnname, args }));
};
sampleRUM.drain = sampleRUM.drain
|| ((dfnname, fn) => {
sampleRUM[dfnname] = fn;
sampleRUM.defer
.filter(({ fnname }) => dfnname === fnname)
.forEach(({ fnname, args }) => sampleRUM[fnname](...args));
});
sampleRUM.always = sampleRUM.always || [];
sampleRUM.always.on = (chkpnt, fn) => { sampleRUM.always[chkpnt] = fn; };
sampleRUM.on = (chkpnt, fn) => { sampleRUM.cases[chkpnt] = fn; };
defer('observe');
defer('cwv');
try {
window.hlx = window.hlx || {};
if (!window.hlx.rum) {
const usp = new URLSearchParams(window.location.search);
const weight = (usp.get('rum') === 'on') ? 1 : 100; // with parameter, weight is 1. Defaults to 100.
// eslint-disable-next-line no-bitwise
const hashCode = (s) => s.split('').reduce((a, b) => (((a << 5) - a) + b.charCodeAt(0)) | 0, 0);
const id = `${hashCode(window.location.href)}-${new Date().getTime()}-${Math.random().toString(16).substr(2, 14)}`;
const random = Math.random();
const isSelected = (random * weight < 1);
// eslint-disable-next-line object-curly-newline
window.hlx.rum = { weight, id, random, isSelected, sampleRUM };
}
const { weight, id } = window.hlx.rum;
if (window.hlx && window.hlx.rum && window.hlx.rum.isSelected) {
const sendPing = (pdata = data) => {
// eslint-disable-next-line object-curly-newline, max-len, no-use-before-define
const body = JSON.stringify({ weight, id, referer: window.location.href, generation: window.hlx.RUM_GENERATION, checkpoint, ...data });
const url = `https://rum.hlx.page/.rum/${weight}`;
// eslint-disable-next-line no-unused-expressions
navigator.sendBeacon(url, body);
// eslint-disable-next-line no-console
console.debug(`ping:${checkpoint}`, pdata);
};
sampleRUM.cases = sampleRUM.cases || {
cwv: () => sampleRUM.cwv(data) || true,
lazy: () => {
// use classic script to avoid CORS issues
const script = document.createElement('script');
script.src = 'https://rum.hlx.page/.rum/@adobe/helix-rum-enhancer@^1/src/index.js';
document.head.appendChild(script);
return true;
},
};
sendPing(data);
if (sampleRUM.cases[checkpoint]) { sampleRUM.cases[checkpoint](); }
}
if (sampleRUM.always[checkpoint]) { sampleRUM.always[checkpoint](data); }
} catch (error) {
// something went wrong
}
}
/**
* Loads a CSS file.
* @param {string} href The path to the CSS file
*/
export function loadCSS(href, callback) {
if (!document.querySelector(`head > link[href="${href}"]`)) {
const link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', href);
if (typeof callback === 'function') {
link.onload = (e) => callback(e.type);
link.onerror = (e) => callback(e.type);
}
document.head.appendChild(link);
} else if (typeof callback === 'function') {
callback('noop');
}
}
/**
* Loads a non module JS file.
* @param {string} src URL to the JS file
* @param {Object} attrs additional optional attributes
*/
export async function loadScript(src, attrs) {
return new Promise((resolve, reject) => {
if (!document.querySelector(`head > script[src="${src}"]`)) {
const script = document.createElement('script');
script.src = src;
if (attrs) {
// eslint-disable-next-line no-restricted-syntax, guard-for-in
for (const attr in attrs) {
script.setAttribute(attr, attrs[attr]);
}
}
script.onload = resolve;
script.onerror = reject;
document.head.append(script);
} else {
resolve();
}
});
}
/**
* Retrieves the content of metadata tags.
* @param {string} name The metadata name (or property)
* @returns {string} The metadata value(s)
*/
export function getMetadata(name, doc = document) {
const attr = name && name.includes(':') ? 'property' : 'name';
const meta = [...doc.head.querySelectorAll(`meta[${attr}="${name}"]`)].map((m) => m.content).join(', ');
return meta || '';
}
/**
* Sanitizes a name for use as class name.
* @param {string} name The unsanitized name
* @returns {string} The class name
*/
export function toClassName(name) {
return typeof name === 'string'
? name.toLowerCase().replace(/[^0-9a-z]/gi, '-').replace(/-+/g, '-').replace(/^-|-$/g, '')
: '';
}
/*
* Sanitizes a name for use as a js property name.
* @param {string} name The unsanitized name
* @returns {string} The camelCased name
*/
export function toCamelCase(name) {
return toClassName(name).replace(/-([a-z])/g, (g) => g[1].toUpperCase());
}
/**
* Gets all the metadata elements that are in the given scope.
* @param {String} scope The scope/prefix for the metadata
* @returns an array of HTMLElement nodes that match the given scope
*/
export function getAllMetadata(scope) {
return [...document.head.querySelectorAll(`meta[property^="${scope}:"],meta[name^="${scope}-"]`)]
.reduce((res, meta) => {
const id = toClassName(meta.name
? meta.name.substring(scope.length + 1)
: meta.getAttribute('property').split(':')[1]);
res[id] = meta.getAttribute('content');
return res;
}, {});
}
/**
* Replace icons with inline SVG and prefix with codeBasePath.
* @param {Element} element
*/
export function decorateIcons(element = document) {
element.querySelectorAll('span.icon').forEach(async (span) => {
if (span.classList.length < 2 || !span.classList[1].startsWith('icon-')) {
return;
}
const icon = span.classList[1].substring(5);
// eslint-disable-next-line no-use-before-define
const resp = await fetch(`${window.hlx.codeBasePath}/icons/${icon}.svg`);
if (resp.ok) {
const iconHTML = await resp.text();
if (iconHTML.match(/<style/i)) {
const img = document.createElement('img');
img.src = `data:image/svg+xml,${encodeURIComponent(iconHTML)}`;
span.appendChild(img);
} else {
span.innerHTML = iconHTML;
}
}
const a = span.closest('a');
if (a) a.title = 'icon';
});
}
/**
* Gets placeholders object
* @param {string} prefix
*/
export async function fetchPlaceholders(prefix = 'default') {
window.placeholders = window.placeholders || {};
const loaded = window.placeholders[`${prefix}-loaded`];
if (!loaded) {
window.placeholders[`${prefix}-loaded`] = new Promise((resolve, reject) => {
try {
fetch(`${prefix === 'default' ? '' : prefix}/placeholders.json`)
.then((resp) => resp.json())
.then((json) => {
const placeholders = {};
json.data.forEach((placeholder) => {
placeholders[toCamelCase(placeholder.Key)] = placeholder.Text;
});
window.placeholders[prefix] = placeholders;
resolve();
})
.catch((error) => {
// error loading placeholders
window.placeholders[prefix] = {};
reject(error);
});
} catch (error) {
// error loading placeholders
window.placeholders[prefix] = {};
reject();
}
});
}
await window.placeholders[`${prefix}-loaded`];
return window.placeholders[prefix];
}
export function getPlaceholderOrDefault(key, defaultText) {
if (!key) {
return defaultText || '';
}
return window.placeholders?.[`/${document.documentElement.lang}`]?.[key] || defaultText || '';
}
/**
* Decorates a block.
* @param {Element} block The block element
*/
export function decorateBlock(block) {
const shortBlockName = block.classList[0];
if (shortBlockName && !block.dataset.blockStatus) {
block.classList.add('block');
block.setAttribute('data-block-name', shortBlockName);
block.setAttribute('data-block-status', 'initialized');
const blockWrapper = block.parentElement;
blockWrapper.classList.add(`${shortBlockName}-wrapper`);
const section = block.closest('.section');
if (section) section.classList.add(`${shortBlockName}-container`);
}
}
/**
* Extracts the config from a block.
* @param {Element} block The block element
* @returns {object} The block config
*/
export function readBlockConfig(block) {
const config = {};
block.querySelectorAll(':scope>div').forEach((row) => {
if (row.children) {
const cols = [...row.children];
if (cols[1]) {
const col = cols[1];
const name = toClassName(cols[0].textContent);
let value = '';
if (col.querySelector('a')) {
const as = [...col.querySelectorAll('a')];
if (as.length === 1) {
value = as[0].href;
} else {
value = as.map((a) => a.href);
}
} else if (col.querySelector('img')) {
const imgs = [...col.querySelectorAll('img')];
if (imgs.length === 1) {
value = imgs[0].src;
} else {
value = imgs.map((img) => img.src);
}
} else if (col.querySelector('p')) {
const ps = [...col.querySelectorAll('p')];
if (ps.length === 1) {
value = ps[0].textContent;
} else {
value = ps.map((p) => p.textContent);
}
} else value = row.children[1].textContent;
config[name] = value;
}
}
});
return config;
}
/**
* Decorates all sections in a container element.
* @param {Element} $main The container element
*/
export function decorateSections(main) {
main.querySelectorAll(':scope > div:not([data-section-status])').forEach((section) => {
const wrappers = [];
let defaultContent = false;
[...section.children].forEach((e) => {
if (e.tagName === 'DIV' || !defaultContent) {
const wrapper = document.createElement('div');
wrappers.push(wrapper);
defaultContent = e.tagName !== 'DIV';
if (defaultContent) wrapper.classList.add('default-content-wrapper');
}
wrappers[wrappers.length - 1].append(e);
});
wrappers.forEach((wrapper) => section.append(wrapper));
section.classList.add('section');
section.setAttribute('data-section-status', 'initialized');
/* process section metadata */
const sectionMeta = section.querySelector('div.section-metadata');
if (sectionMeta) {
const meta = readBlockConfig(sectionMeta);
Object.keys(meta).forEach((key) => {
if (key === 'style') {
const styles = meta.style.split(',').map((style) => toClassName(style.trim()));
styles.forEach((style) => section.classList.add(style));
} else {
section.dataset[toCamelCase(key)] = meta[key];
}
});
sectionMeta.parentNode.remove();
}
});
}
/**
* Updates all section status in a container element.
* @param {Element} main The container element
*/
export function updateSectionsStatus(main) {
const sections = [...main.querySelectorAll(':scope > div.section')];
for (let i = 0; i < sections.length; i += 1) {
const section = sections[i];
const status = section.getAttribute('data-section-status');
if (status !== 'loaded') {
const loadingBlock = section.querySelector('.block[data-block-status="initialized"], .block[data-block-status="loading"]');
if (loadingBlock) {
section.setAttribute('data-section-status', 'loading');
break;
} else {
section.setAttribute('data-section-status', 'loaded');
}
}
}
}
/**
* Decorates all blocks in a container element.
* @param {Element} main The container element
*/
export function decorateBlocks(main) {
main
.querySelectorAll('div.section > div > div')
.forEach(decorateBlock);
}
/**
* Builds a block DOM Element from a two dimensional array
* @param {string} blockName name of the block
* @param {any} content two dimensional array or string or object of content
*/
export function buildBlock(blockName, content) {
const table = Array.isArray(content) ? content : [[content]];
const blockEl = document.createElement('div');
// build image block nested div structure
blockEl.classList.add(blockName);
table.forEach((row) => {
const rowEl = document.createElement('div');
row.forEach((col) => {
const colEl = document.createElement('div');
const vals = col.elems ? col.elems : [col];
vals.forEach((val) => {
if (val) {
if (typeof val === 'string') {
colEl.innerHTML += val;
} else {
colEl.appendChild(val);
}
}
});
rowEl.appendChild(colEl);
});
blockEl.appendChild(rowEl);
});
return (blockEl);
}
/**
* Gets the configuration for the given block, and also passes
* the config through all custom patching helpers added to the project.
*
* @param {Element} block The block element
* @returns {Object} The block config (blockName, cssPath and jsPath)
*/
function getBlockConfig(block) {
const { blockName } = block.dataset;
const cssPath = `${window.hlx.codeBasePath}/blocks/${blockName}/${blockName}.css`;
const jsPath = `${window.hlx.codeBasePath}/blocks/${blockName}/${blockName}.js`;
const original = { blockName, cssPath, jsPath };
return (window.hlx.patchBlockConfig || [])
.filter((fn) => typeof fn === 'function')
.reduce(
(config, fn) => fn(config, original),
{ blockName, cssPath, jsPath },
);
}
/**
* Loads JS and CSS for a module and executes it's default export.
* @param {string} name The module name
* @param {string} jsPath The JS file to load
* @param {string} [cssPath] An optional CSS file to load
* @param {object[]} [args] Parameters to be passed to the default export when it is called
*/
async function loadModule(name, jsPath, cssPath, ...args) {
const cssLoaded = cssPath
? new Promise((resolve) => { loadCSS(cssPath, resolve); })
: Promise.resolve();
const decorationComplete = jsPath
? new Promise((resolve) => {
(async () => {
let mod;
try {
mod = await import(jsPath);
if (mod.default) {
await mod.default.apply(null, args);
}
} catch (error) {
// eslint-disable-next-line no-console
console.log(`failed to load module for ${name}`, error);
}
resolve(mod);
})();
})
: Promise.resolve();
return Promise.all([cssLoaded, decorationComplete])
.then(([, api]) => api);
}
/**
* Loads JS and CSS for a block.
* @param {Element} block The block element
*/
export async function loadBlock(block) {
const status = block.getAttribute('data-block-status');
if (status !== 'loading' && status !== 'loaded') {
block.setAttribute('data-block-status', 'loading');
const { blockName, cssPath, jsPath } = getBlockConfig(block);
try {
await loadModule(blockName, jsPath, cssPath, block);
} catch (error) {
// eslint-disable-next-line no-console
console.log(`failed to load block ${blockName}`, error);
}
block.setAttribute('data-block-status', 'loaded');
}
}
/**
* Loads JS and CSS for all blocks in a container element.
* @param {Element} main The container element
*/
export async function loadBlocks(main) {
updateSectionsStatus(main);
const blocks = [...main.querySelectorAll('div.block')];
for (let i = 0; i < blocks.length; i += 1) {
// eslint-disable-next-line no-await-in-loop
await loadBlock(blocks[i]);
updateSectionsStatus(main);
}
}
/**
* Returns a picture element with webp and fallbacks
* @param {string} src The image URL
* @param {boolean} eager load image eager
* @param {Array} breakpoints breakpoints and corresponding params (eg. width)
*/
export function createOptimizedPicture(src, alt = '', eager = false, breakpoints = [{ media: '(min-width: 400px)', width: '2000' }, { width: '750' }]) {
const url = new URL(src, window.location.href);
const picture = document.createElement('picture');
const { pathname } = url;
const ext = pathname.substring(pathname.lastIndexOf('.') + 1);
// webp
breakpoints.forEach((br) => {
const source = document.createElement('source');
if (br.media) source.setAttribute('media', br.media);
source.setAttribute('type', 'image/webp');
source.setAttribute('srcset', `${pathname}?width=${br.width}&format=webply&optimize=medium`);
picture.appendChild(source);
});
// fallback
breakpoints.forEach((br, i) => {
if (i < breakpoints.length - 1) {
const source = document.createElement('source');
if (br.media) source.setAttribute('media', br.media);
source.setAttribute('srcset', `${pathname}?width=${br.width}&format=${ext}&optimize=medium`);
picture.appendChild(source);
} else {
const img = document.createElement('img');
img.setAttribute('loading', eager ? 'eager' : 'lazy');
img.setAttribute('alt', alt);
picture.appendChild(img);
img.setAttribute('src', `${pathname}?width=${br.width}&format=${ext}&optimize=medium`);
}
});
return picture;
}
/**
* Normalizes all headings within a container element.
* @param {Element} el The container element
* @param {[string]} allowedHeadings The list of allowed headings (h1 ... h6)
*/
export function normalizeHeadings(el, allowedHeadings) {
const allowed = allowedHeadings.map((h) => h.toLowerCase());
el.querySelectorAll('h1, h2, h3, h4, h5, h6').forEach((tag) => {
const h = tag.tagName.toLowerCase();
if (allowed.indexOf(h) === -1) {
// current heading is not in the allowed list -> try first to "promote" the heading
let level = parseInt(h.charAt(1), 10) - 1;
while (allowed.indexOf(`h${level}`) === -1 && level > 0) {
level -= 1;
}
if (level === 0) {
// did not find a match -> try to "downgrade" the heading
while (allowed.indexOf(`h${level}`) === -1 && level < 7) {
level += 1;
}
}
if (level !== 7) {
tag.outerHTML = `<h${level} id="${tag.id}">${tag.textContent}</h${level}>`;
}
}
});
}
/**
* Set template (page structure) and theme (page styles).
*/
export function decorateTemplateAndTheme() {
const addClasses = (elem, classes) => {
classes.split(',').forEach((v) => {
elem.classList.add(toClassName(v.trim()));
});
};
const template = getMetadata('template');
if (template) addClasses(document.body, template);
const theme = getMetadata('theme');
if (theme) addClasses(document.body, theme);
}
/**
* decorates paragraphs containing a single link as buttons.
* @param {Element} element container element
*/
export function decorateButtons(element) {
element.querySelectorAll('a').forEach((a) => {
a.title = a.title || a.textContent;
if (a.href !== a.textContent) {
const up = a.parentElement;
const twoup = a.parentElement.parentElement;
if (!a.querySelector('img')) {
if (up.childNodes.length === 1 && (up.tagName === 'P' || up.tagName === 'DIV')) {
a.className = 'button primary'; // default
up.classList.add('button-container');
}
if (up.childNodes.length === 1 && up.tagName === 'STRONG'
&& twoup.childNodes.length === 1 && twoup.tagName === 'P') {
a.className = 'button primary';
twoup.classList.add('button-container');
}
if (up.childNodes.length === 1 && up.tagName === 'EM'
&& twoup.childNodes.length === 1 && twoup.tagName === 'P') {
a.className = 'button secondary';
twoup.classList.add('button-container');
}
}
}
});
}
/**
* load LCP block and/or wait for LCP in default content.
*/
export async function waitForLCP(lcpBlocks) {
const block = document.querySelector('.block');
const hasLCPBlock = (block && lcpBlocks.includes(block.getAttribute('data-block-name')));
if (hasLCPBlock) await loadBlock(block);
if (window.location.href.indexOf("adventures") != -1) {
document.querySelector('body').classList.add('activity', 'appear');
}else{
document.querySelector('body').classList.add('appear');
}
const lcpCandidate = document.querySelector('main img');
await new Promise((resolve) => {
if (lcpCandidate && !lcpCandidate.complete) {
lcpCandidate.setAttribute('loading', 'eager');
lcpCandidate.addEventListener('load', resolve);
lcpCandidate.addEventListener('error', resolve);
} else {
resolve();
}
});
}
/**
* loads a block named 'header' into header
*/
export function loadHeader(header) {
const headerBlock = buildBlock('header', '');
header.append(headerBlock);
decorateBlock(headerBlock);
return loadBlock(headerBlock);
}
/**
* loads a block named 'footer' into footer
*/
export function loadFooter(footer) {
const footerBlock = buildBlock('footer', '');
footer.append(footerBlock);
decorateBlock(footerBlock);
return loadBlock(footerBlock);
}
// Define an execution context for plugins
export const executionContext = {
createOptimizedPicture,
getAllMetadata,
getMetadata,
decorateBlock,
decorateButtons,
decorateIcons,
loadBlock,
loadCSS,
loadScript,
sampleRUM,
toCamelCase,
toClassName,
};
function parsePluginParams(id, config) {
const pluginId = !config
? id.split('/').splice(id.endsWith('/') ? -2 : -1, 1)[0].replace(/\.js/, '')
: id;
const pluginConfig = {
load: 'eager',
...(typeof config === 'string' || !config
? { url: (config || id).replace(/\/$/, '') }
: config),
};
pluginConfig.options ||= {};
return { id: pluginId, config: pluginConfig };
}
class PluginsRegistry {
#plugins;
constructor() {
this.#plugins = new Map();
}
// Register a new plugin
add(id, config) {
const { id: pluginId, config: pluginConfig } = parsePluginParams(id, config);
this.#plugins.set(pluginId, pluginConfig);
}
// Get the plugin
get(id) { return this.#plugins.get(id); }
// Check if the plugin exists
includes(id) { return !!this.#plugins.has(id); }
// Load all plugins that are referenced by URL, and updated their configuration with the
// actual API they expose
async load(phase) {
[...this.#plugins.entries()]
.filter(([, plugin]) => plugin.condition
&& !plugin.condition(document, plugin.options, executionContext))
.map(([id]) => this.#plugins.delete(id));
return Promise.all([...this.#plugins.entries()]
// Filter plugins that don't match the execution conditions
.filter(([, plugin]) => (
(!plugin.condition || plugin.condition(document, plugin.options, executionContext))
&& phase === plugin.load && plugin.url
))
.map(async ([key, plugin]) => {
try {
// If the plugin has a default export, it will be executed immediately
const pluginApi = (await loadModule(
key,
!plugin.url.endsWith('.js') ? `${plugin.url}/${key}.js` : plugin.url,
!plugin.url.endsWith('.js') ? `${plugin.url}/${key}.css` : null,
document,
plugin.options,
executionContext,
)) || {};
this.#plugins.set(key, { ...plugin, ...pluginApi });
} catch (err) {
// eslint-disable-next-line no-console
console.error('Could not load specified plugin', key);
}
}));
}
// Run a specific phase in the plugin
async run(phase) {
return [...this.#plugins.values()]
.reduce((promise, plugin) => ( // Using reduce to execute plugins sequencially
plugin[phase] && (!plugin.condition
|| plugin.condition(document, plugin.options, executionContext))
? promise.then(() => plugin[phase](document, plugin.options, executionContext))
: promise
), Promise.resolve());
}
}
class TemplatesRegistry {
// Register a new template
// eslint-disable-next-line class-methods-use-this
add(id, url) {
if (Array.isArray(id)) {
id.forEach((i) => window.hlx.templates.add(i));
return;
}
const { id: templateId, config: templateConfig } = parsePluginParams(id, url);
templateConfig.condition = () => toClassName(getMetadata('template')) === templateId;
window.hlx.plugins.add(templateId, templateConfig);
}
// Get the template
// eslint-disable-next-line class-methods-use-this
get(id) { return window.hlx.plugins.get(id); }
// Check if the template exists
// eslint-disable-next-line class-methods-use-this
includes(id) { return window.hlx.plugins.includes(id); }
}
/**
* setup block utils
*/
export function setup() {
window.hlx = window.hlx || {};
window.hlx.codeBasePath = '';
window.hlx.lighthouse = new URLSearchParams(window.location.search).get('lighthouse') === 'on';
window.hlx.patchBlockConfig = [];
window.hlx.plugins = new PluginsRegistry();
window.hlx.templates = new TemplatesRegistry();
const scriptEl = document.querySelector('script[src$="/scripts/scripts.js"]');
if (scriptEl) {
try {
[window.hlx.codeBasePath] = new URL(scriptEl.src).pathname.split('/scripts/scripts.js');
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
}
}
}
/**
* auto init
*/
function init() {
setup();
sampleRUM('top');
window.addEventListener('load', () => sampleRUM('load'));
window.addEventListener('unhandledrejection', (event) => {
sampleRUM('error', { source: event.reason.sourceURL, target: event.reason.line });
});
window.addEventListener('error', (event) => {
sampleRUM('error', { source: event.filename, target: event.lineno });
});
}
init();