generated from adobe/aem-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 3
/
nexter.js
156 lines (145 loc) · 4.5 KB
/
nexter.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
const AUTO_BLOCKS = [
{ 'nx-fragment': '/fragments/' },
{ 'nx-youtube': 'https://www.youtube.com' },
];
function getEnv() {
const { host } = new URL(window.location.href);
if (!['.page', 'local'].some((check) => host.includes(check))) return 'prod';
if (['.hlx.', '.aem.'].some((check) => host.includes(check))) return 'stage';
return 'dev';
}
export const [setConfig, getConfig] = (() => {
let config;
return [
(conf = {}) => {
config = {
...conf,
env: getEnv(),
nxBase: `${import.meta.url.replace('/scripts/nexter.js', '')}`,
};
return config;
},
() => (config || setConfig()),
];
})();
export function getMetadata(name, doc = document) {
const attr = name && name.includes(':') ? 'property' : 'name';
const meta = doc.head.querySelector(`meta[${attr}="${name}"]`);
return meta && meta.content;
}
export async function loadStyle(href) {
return new Promise((resolve) => {
if (!document.querySelector(`head > link[href="${href}"]`)) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
link.onload = resolve;
link.onerror = resolve;
document.head.append(link);
} else {
resolve();
}
});
}
export async function loadBlock(block) {
const { classList } = block;
let name = classList[0];
const isNx = name.startsWith('nx-');
if (isNx) name = name.replace('nx-', '');
block.dataset.blockName = name;
const { nxBase, codeBase = '' } = getConfig();
const path = isNx ? `${nxBase}/blocks` : `${codeBase}/blocks`;
const blockPath = `${path}/${name}/${name}`;
const loaded = [new Promise((resolve) => {
(async () => {
try {
await (await import(`${blockPath}.js`)).default(block);
} catch { console.log(`Failed loading: ${name}`); }
resolve();
})();
})];
if (!classList.contains('cmp')) loaded.push(loadStyle(`${blockPath}.css`));
await Promise.all(loaded);
return block;
}
function decorateContent(el) {
const children = [el];
let child = el;
while (child) {
child = child.nextElementSibling;
if (child && child.nodeName !== 'DIV') children.push(child);
}
const block = document.createElement('div');
block.className = 'content';
block.append(...children);
return block;
}
function decorateDefaults(el) {
const firstChild = ':scope > *:not(div):first-child';
const afterBlock = ':scope > div + *:not(div)';
const children = el.querySelectorAll(`${firstChild}, ${afterBlock}`);
children.forEach((child) => {
const prev = child.previousElementSibling;
const content = decorateContent(child);
if (prev) {
prev.insertAdjacentElement('afterend', content);
} else {
el.insertAdjacentElement('afterbegin', content);
}
});
}
function decorateLinks(el) {
const anchors = [...el.querySelectorAll('a')];
return anchors.reduce((acc, a) => {
const { href } = a;
const found = AUTO_BLOCKS.some((pattern) => {
const key = Object.keys(pattern)[0];
if (!href.includes(pattern[key])) return false;
a.classList.add(key, 'auto-block');
return true;
});
if (found) acc.push(a);
return acc;
}, []);
}
function decorateSections(parent, isDoc) {
const selector = isDoc ? 'main > div' : ':scope > div';
return [...parent.querySelectorAll(selector)].map((el) => {
el.classList.add('section');
el.dataset.status = 'decorated';
el.autoBlocks = decorateLinks(el);
el.blocks = [...el.querySelectorAll(':scope > div[class]')];
decorateDefaults(el);
return el;
});
}
function decorateHeader() {
const header = document.querySelector('header');
if (!header) return;
const meta = getMetadata('header') || 'nx-nav cmp';
if (meta === 'off') {
header.remove();
return;
}
header.dataset.status = 'decorated';
header.className = meta;
if (header.classList.contains('nx-nav')) {
document.body.classList.add('nx-app');
}
}
export async function loadArea(area = document) {
const isDoc = area === document;
if (isDoc) {
if (getMetadata('signin')) await import('../utils/signin.js');
document.documentElement.lang = 'en';
decorateHeader();
}
const sections = decorateSections(area, isDoc);
for (const [idx, section] of sections.entries()) {
await Promise.all(section.autoBlocks.map((block) => loadBlock(block)));
await Promise.all(section.blocks.map((block) => loadBlock(block)));
delete section.dataset.status;
if (isDoc && idx === 0) await import('./postlcp.js');
}
if (isDoc) import('./lazy.js');
}