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
226 lines (196 loc) · 6.41 KB
/
scripts.js
File metadata and controls
226 lines (196 loc) · 6.41 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
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 applyStoredThemePreference() {
try {
const storedTheme = localStorage.getItem(THEME_STORAGE_KEY);
if (storedTheme !== 'light' && storedTheme !== 'dark') return;
document.documentElement.dataset.theme = storedTheme;
document.body.classList.remove('light-scheme', 'dark-scheme');
document.body.classList.add(`${storedTheme}-scheme`);
} catch (e) {
// do nothing
}
}
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';
function buildAutoBlocks(main) {
try {
// auto load `*/fragments/*` references (exclude #_dnb = do not auto-block)
const allFragments = [...main.querySelectorAll('a[href*="/fragments/"]')].filter((f) => !f.closest('.fragment'));
const fragments = allFragments.filter((a) => {
if (a.href.includes(DNB_HASH)) {
a.href = a.href.replace(DNB_HASH, '').replace(/#$/, '');
return false;
}
return true;
});
if (fragments.length > 0) {
import('../blocks/fragment/fragment.js').then(({ loadFragment }) => {
fragments.forEach(async (fragment) => {
try {
const { pathname } = new URL(fragment.href);
const frag = await loadFragment(pathname);
fragment.parentElement.replaceWith(...frag.children);
await dynamicBlocks(main);
} catch (error) {
console.error('Fragment loading failed', error);
}
});
});
}
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);
}
}
export function decorateMain(main) {
decorateButtons(main);
decorateIcons(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();
applyStoredThemePreference();
const main = doc.querySelector('main');
if (main) {
if (window.isErrorPage) loadErrorPage(main);
decorateMain(main);
document.body.classList.add('appear');
await loadSection(main.querySelector('.section'), waitForFirstImage);
}
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) {
loadHeader(doc.querySelector('header'));
const templateName = getMetadata('template');
if (templateName) {
await loadTemplate(doc, templateName);
}
const main = doc.querySelector('main');
const sections = main ? [...main.querySelectorAll('div.section')] : [];
await Promise.all(sections.map((s) => loadSection(s)));
if (sections[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(doc.querySelector('footer'));
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
}
export async function loadPage() {
await loadEager(document);
await loadLazy(document);
loadDelayed();
}
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));
}());