generated from adobe/aem-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscripts.js
More file actions
284 lines (251 loc) · 8.12 KB
/
scripts.js
File metadata and controls
284 lines (251 loc) · 8.12 KB
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
import {
buildBlock,
decorateBlock,
loadHeader,
loadFooter,
decorateButtons,
decorateIcons,
decorateSections,
decorateBlocks,
decorateTemplateAndTheme,
waitForFirstImage,
loadSection,
sampleRUM,
loadCSS,
getMetadata,
} from './aem.js';
import dynamicBlocks from '../blocks/dynamic/index.js';
const THEME_STORAGE_KEY = 'diyfire-theme';
function applyTheme(theme) {
let t = theme ?? (() => { try { return localStorage.getItem(THEME_STORAGE_KEY); } catch (e) { return null; } })();
if (t !== 'light' && t !== 'dark') {
t = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
document.documentElement.dataset.theme = t;
document.body.classList.remove('light-scheme', 'dark-scheme');
document.body.classList.add(`${t}-scheme`);
}
const isYoutubeLink = (url) => ['youtube.com', 'www.youtube.com', 'youtu.be'].includes(url.hostname);
function replaceParagraphWithBlock(link, block) {
const parent = link.parentElement;
if (parent?.tagName === 'P' && parent.children.length === 1) {
parent.replaceWith(block);
} else {
link.replaceWith(block);
}
}
function buildEmbedBlocks(main) {
const youtubeVideos = main.querySelectorAll('a[href*="youtube.com"], a[href*="youtu.be"]');
youtubeVideos.forEach((anchor) => {
if (anchor.closest('.embed.block')) return;
if (anchor.querySelector('.icon')) return;
let url;
try {
url = new URL(anchor.href);
} catch (e) {
return;
}
if (!isYoutubeLink(url)) return;
const block = buildBlock('embed', [[anchor.cloneNode(true)]]);
replaceParagraphWithBlock(anchor, block);
decorateBlock(block);
});
}
async function loadFonts() {
await loadCSS(`${window.hlx.codeBasePath}/styles/fonts.css`);
try {
if (!window.location.hostname.includes('localhost')) sessionStorage.setItem('fonts-loaded', 'true');
} catch (e) {
// do nothing
}
}
/** Hash that opts out of fragment auto-blocking (do not block). Links with #_dnb stay as normal links. */
const DNB_HASH = '#_dnb';
async function loadFragments(section) {
const main = section.closest('main');
const links = [...section.querySelectorAll('a[href*="/fragments/"]')]
.filter((a) => !a.closest('.fragment'));
const fragments = links.filter((a) => {
if (a.href.includes(DNB_HASH)) {
a.href = a.href.replace(DNB_HASH, '').replace(/#$/, '');
return false;
}
return true;
});
if (fragments.length === 0) return;
const { loadFragment } = await import('../blocks/fragment/fragment.js');
await Promise.all(fragments.map(async (a) => {
try {
const { pathname } = new URL(a.href);
const frag = await loadFragment(pathname);
a.parentElement.replaceWith(...frag.children);
} catch (error) {
console.error('Fragment loading failed', error);
}
}));
await dynamicBlocks(main);
}
function buildAutoBlocks(main) {
try {
buildEmbedBlocks(main);
} catch (error) {
console.error('Auto Blocking failed', error);
}
}
function loadErrorPage(main) {
if (window.errorCode === '404') {
const fragmentPath = '/fragments/404';
const fragmentLink = document.createElement('a');
fragmentLink.href = fragmentPath;
fragmentLink.textContent = fragmentPath;
const fragment = buildBlock('fragment', [[fragmentLink]]);
const section = main.querySelector('.section');
if (section) section.replaceChildren(fragment);
}
}
/**
* Inline SVG icons that need to inherit currentColor (e.g. logo).
* Replaces <img src="…/icon.svg"> with the actual <svg> element
* so CSS color and light-dark() work across themes.
* @param {Element} scope element tree to search within
*/
async function inlineColorIcons(scope) {
const icons = scope.querySelectorAll('.icon.icon-logo img[src$=".svg"]');
icons.forEach(async (img) => {
try {
const resp = await fetch(img.src);
if (!resp.ok) return;
const text = await resp.text();
const tmp = document.createElement('div');
tmp.innerHTML = text;
const svg = tmp.querySelector('svg');
if (!svg) return;
svg.setAttribute('role', 'img');
svg.setAttribute('aria-label', img.alt || 'Logo');
img.replaceWith(svg);
} catch (e) { /* keep <img> fallback */ }
});
}
export function decorateMain(main) {
decorateButtons(main);
decorateIcons(main);
inlineColorIcons(main);
buildAutoBlocks(main);
decorateSections(main);
decorateBlocks(main);
}
async function loadTemplate(main) {
try {
const template = getMetadata('template');
if (template) {
const mod = await import(`../templates/${template}/${template}.js`);
loadCSS(`${window.hlx.codeBasePath}/templates/${template}/${template}.css`);
if (mod.default) {
await mod.default(main);
}
}
} catch (error) {
console.error('template loading failed', error);
}
}
async function loadEager(doc) {
document.documentElement.lang = 'en';
decorateTemplateAndTheme();
applyTheme();
const main = doc.querySelector('main');
if (main) {
if (window.isErrorPage) loadErrorPage(main);
decorateMain(main);
document.body.classList.add('appear');
await loadSection(main.querySelector('.section'), async (s) => {
await loadFragments(s);
await waitForFirstImage(s);
});
}
try {
/* if desktop (proxy for fast connection) or fonts already loaded, load fonts.css */
if (window.innerWidth >= 900 || sessionStorage.getItem('fonts-loaded')) {
loadFonts();
}
} catch (e) {
// do nothing
}
}
async function loadLazy(doc) {
const headerEl = doc.querySelector('header');
const footerEl = doc.querySelector('footer');
loadHeader(headerEl);
const templateName = getMetadata('template');
if (templateName) {
await loadTemplate(doc, templateName);
}
const main = doc.querySelector('main');
const sections = main ? [...main.querySelectorAll('div.section')] : [];
for (let i = 0; i < sections.length; i += 1) {
await loadSection(sections[i], loadFragments);
if (i === 0 && sampleRUM.enhance) sampleRUM.enhance();
}
await dynamicBlocks(main);
const { hash } = window.location;
const element = hash ? doc.getElementById(hash.substring(1)) : false;
if (hash && element) element.scrollIntoView();
loadFooter(footerEl);
/* inline logo SVGs in header/footer once they are decorated */
const waitAndInline = (el) => {
const observer = new MutationObserver(() => {
if (el.querySelector('.icon.icon-logo img[src$=".svg"]')) {
observer.disconnect();
inlineColorIcons(el);
}
});
observer.observe(el, { childList: true, subtree: true });
};
waitAndInline(headerEl);
waitAndInline(footerEl);
loadCSS(`${window.hlx.codeBasePath}/styles/lazy-styles.css`);
loadFonts();
const loadQuickEdit = async (...args) => {
const { default: initQuickEdit } = await import('../tools/quick-edit/quick-edit.js');
initQuickEdit(...args);
};
const addSidekickListeners = (sk) => {
sk.addEventListener('custom:quick-edit', loadQuickEdit);
};
const sk = document.querySelector('aem-sidekick');
if (sk) {
addSidekickListeners(sk);
} else {
// wait for sidekick to be loaded
document.addEventListener('sidekick-ready', () => {
// sidekick now loaded
addSidekickListeners(document.querySelector('aem-sidekick'));
}, { once: true });
}
}
function loadDelayed() {
window.setTimeout(() => import('./delayed.js'), 3000);
// load anything that can be postponed to the latest here
}
/**
* Called by aem-embed after decorateMain + block loading.
* Runs project-specific post-decoration logic that would
* normally happen in loadLazy (e.g. dynamic blocks).
*/
export async function decorateEmbed(main) {
await dynamicBlocks(main);
}
export async function loadPage() {
await loadEager(document);
await loadLazy(document);
loadDelayed();
}
if (!window.hlx?.suppressLoadPage) {
loadPage();
(async function loadDa() {
if (!new URL(window.location.href).searchParams.get('dapreview')) return;
import('https://da.live/scripts/dapreview.js').then(({ default: daPreview }) => daPreview(loadPage));
}());
window.addEventListener('aem-theme-change', (e) => {
applyTheme(e.detail?.theme);
});
}