-
Notifications
You must be signed in to change notification settings - Fork 22
/
scripts.js
426 lines (384 loc) · 14.2 KB
/
scripts.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
/*
* Copyright 2021 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.
*/
document.title = document.title.split('<br>').join(' ');
function addDefaultClass(element) {
document.querySelectorAll(element).forEach(($div) => {
$div.classList.add('default');
});
}
// TODO: replace with dynamic imports
function loadJSModule(src) {
const module = document.createElement('script');
module.setAttribute('type', 'module');
module.setAttribute('src', src);
document.head.appendChild(module);
}
/**
* Creates a tag with the given name and attributes.
* @param {string} name The tag name
* @param {object} attrs An object containing the attributes
* @returns The new tag
*/
function createTag(name, attrs) {
const el = document.createElement(name);
if (typeof attrs === 'object') {
for (const [key, value] of Object.entries(attrs)) {
el.setAttribute(key, value);
}
}
return el;
}
async function insertLocalResource(type) {
let url = '';
if (window.pages.product && window.pages.locale) {
url = `/${window.pages.product}/${window.pages.locale}/${type}.plain.html`;
}
if (window.pages.product && window.pages.project) {
url = `/${window.pages.product}/${window.pages.locale}/${window.pages.project}/${type}.plain.html`;
}
if (url) {
const resp = await fetch(url);
if (resp.status === 200) {
const html = await resp.text();
const inner = `<div> ${html} </div>`;
document.querySelector(type).innerHTML = inner;
window.hlx.dependencies.push(url);
}
}
// temporary icon fix
document.querySelector(type).classList.add('appear');
}
/* link out to external links */
// called inside decoratePage() twp3.js
function externalLinks(selector) {
const element = document.querySelector(selector);
const links = element.querySelectorAll('a[href]');
links.forEach((linkItem) => {
const linkValue = linkItem.getAttribute('href');
if (linkValue.includes('//') && !linkValue.includes('pages.adobe')) {
linkItem.setAttribute('target', '_blank');
}
});
}
function externalizeImageSources($div) {
$div.querySelectorAll('img').forEach(($img) => {
const { src } = $img;
if (src.startsWith('https://hlx.blob.core.windows.net/external/')) {
const url = new URL(src);
const id = url.pathname.split('/')[2];
const ext = url.hash.split('.')[1];
$img.src = `/hlx_${id}.${ext}`;
}
});
}
// TODO: dedupe with in-app.js, max.js, ete.js, learn.js, on24.js, tutorials.js
function toClassName(name) {
return (name.toLowerCase().replace(/[^0-9a-z]/gi, '-'));
}
// TODO: dedupe with in-app.js, max.js, learn.js, tutorials.js
function turnTableSectionIntoCards($table, cols) {
const $rows = $table.querySelectorAll('tbody tr');
const $cards = createTag('div', { class: `cards ${cols.join('-')}` });
$rows.forEach(($tr) => {
const $card = createTag('div', { class: 'card' });
$tr.querySelectorAll('td').forEach(($td, i) => {
const $div = createTag('div', { class: cols[i] });
const $a = $td.querySelector('a[href]');
if ($a && $a.getAttribute('href').startsWith('https://www.youtube.com/')) {
const yturl = new URL($a.getAttribute('href'));
const vid = yturl.searchParams.get('v');
$div.innerHTML = /* html */`
<div class="video-thumb" style="background-image:url(https://img.youtube.com/vi/${vid}/0.jpg)">
<svg xmlns="http://www.w3.org/2000/svg" width="731" height="731" viewBox="0 0 731 731">
<g id="Group_23" data-name="Group 23" transform="translate(-551 -551)">
<circle id="Ellipse_14" data-name="Ellipse 14" cx="365.5" cy="365.5" r="365.5" transform="translate(551 551)" fill="#1473e6"/>
<path id="Polygon_3" data-name="Polygon 3" d="M87.5,0,175,152H0Z" transform="translate(992.5 829.5) rotate(90)" fill="#fff"/>
</g>
</svg>
</div>`;
$div.addEventListener('click', () => {
$div.innerHTML = /* html */`
<div style="left: 0; width: 100%; height: 0; position: relative; padding-bottom: 56.25%;">
<iframe src="https://www.youtube.com/embed/${vid}?rel=0&autoplay=1" frameBorder="0" style="border: 0; top: 0; left: 0; width: 100%; height: 100%; position: absolute;" allowfullscreen scrolling="no" allow="autoplay; encrypted-media; accelerometer; gyroscope; picture-in-picture"></iframe>
</div>`;
});
} else {
$div.innerHTML = $td.innerHTML;
$div.childNodes.forEach(($child) => {
if ($child.nodeName === '#text') {
const $p = createTag('p');
$p.innerHTML = $child.nodeValue;
$child.parentElement.replaceChild($p, $child);
}
});
}
$card.append($div);
});
$cards.append($card);
});
return ($cards);
}
// TODO: dedupe with in-app.js, max.js,
// templates/default.js, learn.js, on24.js,
// stock-advocates.js, tutorials.js, xd.js
function decorateTables() {
document.querySelectorAll('main div>table').forEach(($table) => {
const $cols = $table.querySelectorAll('thead tr th');
const cols = Array.from($cols).map((e) => toClassName(e.innerHTML));
const $rows = $table.querySelectorAll('tbody tr');
let $div = {};
if (cols.length === 1 && $rows.length === 1) {
$div = createTag('div', { class: `${cols[0]}` });
$div.innerHTML = $rows[0].querySelector('td').innerHTML;
externalizeImageSources($div);
} else {
$div = turnTableSectionIntoCards($table, cols);
}
$table.parentNode.replaceChild($div, $table);
});
}
// TODO: dedupe with stock-advocates.js, tutorials.js
async function loadLocalHeader() {
decorateTables();
const $inlineHeader = document.querySelector('main div.header-block');
if ($inlineHeader) {
const $header = document.querySelector('header');
$inlineHeader.childNodes.forEach((e, i) => {
// in a document, using uppercase and strict equal checks
if (e.nodeName === 'DIV' && !i) {
const $p = createTag('div');
const inner = `<img class="icon icon-${window.pages.product}" src="/icons/${window.pages.product}.svg">${e.outerHTML}`;
$p.innerHTML = inner;
e.parentNode.replaceChild($p, e);
}
if (e.nodeName === 'P' && !i) {
const inner = `<img class="icon icon-${window.pages.product}" src="/icons/${window.pages.product}.svg">${e.innerHTML}`;
e.innerHTML = inner;
}
});
$header.innerHTML = `<div>${$inlineHeader.innerHTML}</div>`;
$inlineHeader.remove();
document.querySelector('header').classList.add('appear');
} else {
await insertLocalResource('header');
}
}
/**
* adds a class to an element.
* @param {string} qs querySelector string
* @param {string} cls css class to be added
* @param {number} parent uplevel
*/
function classify(qs, cls, parent) {
document.querySelectorAll(qs).forEach(($e) => {
let $root = $e;
for (let p = parent; p > 0; p -= 1) {
$root = $root.parentNode;
}
$root.classList.add(cls);
});
}
const debounce = (func, wait, immediate) => {
let timeout;
return function debounced(...args) {
const later = () => {
timeout = null;
if (!immediate) func.apply(this, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(this, args);
};
};
/**
* Checks if <main> is ready to appear
*/
function appearMain() {
if (window.pages.familyCssLoaded && window.pages.decorated) {
const p = window.pages;
const pathSplits = window.location.pathname.split('/');
const pageName = pathSplits[pathSplits.length - 1].split('.')[0];
const classes = [p.product, p.family, p.project, pageName];
classes.forEach((e) => (e ? document.body.classList.add(e) : false));
classify('main', 'appear');
}
}
/**
* Loads a CSS file.
* @param {string} href The path to the CSS file
*/
function loadCSS(href) {
const link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', href);
link.onload = () => {
window.pages.familyCssLoaded = true;
appearMain();
// set_widths();
};
link.onerror = () => {
window.pages.familyCssLoaded = true;
appearMain();
};
document.head.appendChild(link);
}
function loadTemplate() {
document.querySelectorAll('table th').forEach(($th) => {
if ($th.textContent.toLowerCase().trim() === 'template') {
const $table = $th.closest('table');
const template = $table.querySelector('td').textContent;
const $div = createTag('div', { class: 'template' });
$div.innerHTML = template;
$table.parentElement.replaceChild($div, $table);
}
});
let template = 'default';
const $template = document.querySelector('.template');
if ($template) {
template = toClassName($template.textContent);
$template.remove();
}
loadJSModule(`/templates/${template}/${template}.js`);
loadCSS(`/templates/${template}/${template}.css`);
}
function localizeFooter() {
const lang = window.pages.locale;
const footers = {
de: `<div>
<p>Copyright © 2020 Adobe. All rights reserved.</p>
<ul>
<li><a href="https://www.adobe.com/de/privacy.html">Richtlinien für den Datenschutz</a></li>
<li><a href="https://www.adobe.com/de/legal/terms.html">Nutzungsbedingungen</a></li>
<li><a href="https://www.adobe.com/de/privacy/ca-rights.html">Daten zu meiner Person nicht verkaufen</a></li>
<li><a href="https://www.adobe.com/de/privacy/opt-out.html#interest-based-ads"><svg xmlns="http://www.w3.org/2000/svg" class="icon icon-adchoices"><use href="/icons.svg#adchoices"></use></svg> AdAuswahl</a></li>
</ul>
</div>
<div>
<div class="privacy" style="display: block;">
<a href="#" class="openPrivacyModal">Einstellungen</a>
<div id="feds-footer"></div>
</div>
</div>`,
};
if (footers[lang]) {
const $footer = document.querySelector('body>footer');
$footer.innerHTML = footers[lang];
}
}
function fixImages() {
const screenWidth = window.screen.availWidth;
const imgSizes = [375, 768, 1000];
const fitting = imgSizes.filter((s) => s <= screenWidth);
const width = fitting.length ? fitting[fitting.length - 1] * 2 : imgSizes[0] * 2;
let heroProcessed = false;
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
// only handle images with src=/hlx_*
// console.log(node.tagName +':'+node.src);
if (node.tagName === 'IMG' && !node.src.includes('?')) {
let contentHash;
let extension;
if (node.src.includes('/hlx_')) {
const filename = node.src.split('/hlx_')[1];
const splits = filename.split('.');
contentHash = splits[0];
extension = splits[1];
}
if (node.src.startsWith('https://hlx.blob.core.windows.net/external/')) {
const filename = node.src.substring(43);
const splits = filename.split('#');
contentHash = splits[0];
extension = splits[1].split('.')[1];
}
if (contentHash && (extension === 'jpg' || extension === 'jpeg' || extension === 'png')) {
const loading = heroProcessed ? 'lazy' : 'eager';
heroProcessed = true;
node.setAttribute('src', `/hlx_${contentHash}.${extension}?width=${width}&auto=webp&format=pjpg&optimize=medium`);
node.setAttribute('loading', loading);
}
}
});
});
if (document.readyState === 'interactive' || document.readyState === 'complete') {
observer.disconnect();
}
});
observer.observe(document, { childList: true, subtree: true });
}
function styleButtons() {
const links = document.querySelectorAll('main a');
if (!document.querySelectorAll('main a')) return;
links.forEach((link) => {
if (
link.parentElement.parentNode.nodeName === 'P'
&& link.parentElement.parentNode.childElementCount === 1
&& link.parentElement.parentNode.firstElementChild.nodeName === 'STRONG'
) {
link.className = 'button primary';
}
});
}
function run() {
fixImages();
const pathSegments = window.location.pathname.match(/[\w-]+(?=\/)/g);
window.pages = {};
if (pathSegments) {
const product = pathSegments[0];
const locale = pathSegments[1];
const project = pathSegments[2];
window.pages = { product, locale, project };
}
window.hlx = window.hlx || {};
window.hlx.dependencies = [];
if (window.pages.product) {
document.getElementById('favicon-safari').href = `/icons/${window.pages.product}.ico`;
document.getElementById('favicon').href = `/icons/${window.pages.product}.svg`;
}
if (document.readyState === 'loading') {
window.addEventListener('DOMContentLoaded', () => {
localizeFooter();
loadTemplate();
styleButtons();
});
} else {
localizeFooter();
loadTemplate();
}
}
/**
* TODO: remove this switch for modules.
* We can leave the functions on window until
* everything is moved over and tested.
*
* For now, this script is included as a module,
* but also writes to window.
* Gives us the ability to use both ways in the interrim.
*/
// non-module, explicitly add functions to global scope
window.addDefaultClass = addDefaultClass;
window.loadJSModule = loadJSModule;
window.createTag = createTag;
window.insertLocalResource = insertLocalResource;
window.externalLinks = externalLinks;
window.loadCSS = loadCSS;
window.appearMain = appearMain;
window.classify = classify;
window.debounce = debounce;
window.toClassName = toClassName;
window.turnTableSectionIntoCards = turnTableSectionIntoCards;
window.loadLocalHeader = loadLocalHeader;
window.decorateTables = decorateTables;
run();
// module
// export default run;