generated from adobe/aem-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathscripts.js
330 lines (297 loc) · 9.43 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
/* global alloy */
import {
sampleRUM,
buildBlock,
loadHeader,
loadFooter,
decorateButtons,
decorateIcons,
decorateLinks,
decorateSections,
decorateBlocks,
decorateTemplateAndTheme,
waitForLCP,
loadBlocks,
loadCSS,
getMetadata,
toClassName,
isCanada,
} from './lib-franklin.js';
import {
analyticsSetConsent,
createInlineScript,
getAlloyInitScript,
getGTMInitScript,
setupAnalyticsTrackingWithAlloy,
setupAnalyticsTrackingWithGTM,
analyticsTrackConversion, trackGTMEvent,
} from './lib-analytics.js';
const LCP_BLOCKS = []; // add your LCP blocks to the list
export function jsx(html, ...args) {
return html.slice(1).reduce((str, elem, i) => str + args[i] + elem, html[0]);
}
/**
* Builds hero block and prepends to main in a new section.
* @param {Element} main The container element
*/
function buildHeroBlock(main) {
const h1 = main.querySelector('h1');
const picture = main.querySelector('picture');
if (!h1 || !picture) {
return;
}
const isPictureInDiv = picture.closest('div');
if (
h1
&& picture
&& !isPictureInDiv
// eslint-disable-next-line no-bitwise
&& (h1.compareDocumentPosition(picture) & Node.DOCUMENT_POSITION_PRECEDING)
) {
const section = document.createElement('div');
section.append(buildBlock('hero', { elems: [picture, h1] }));
main.prepend(section);
}
}
function buildBlockPostPage(main) {
// Below h1
const h1 = main.querySelector('h1');
const socialMediaButtons = document.createRange().createContextualFragment('<div class="sharing"></div>');
if (h1) {
const author = h1.parentElement.querySelector('h1 + p > em');
if (author) {
const authorElem = document.createRange().createContextualFragment(`<p class="author">${author.innerText}</p>`);
author.parentElement.replaceWith(authorElem);
}
h1.parentElement.insertBefore(socialMediaButtons.cloneNode(true), h1.nextSibling);
}
// Below last content
const lastContentSection = main.querySelector('* > div:last-of-type');
if (lastContentSection) {
lastContentSection.appendChild(socialMediaButtons.cloneNode(true));
const fragmentPath = isCanada ? '/ca/blog/fragments/blog-footer' : '/blog/fragments/blog-footer';
const fragment = document.createRange().createContextualFragment(`<div><div class="fragment">${fragmentPath}</div></div>`);
lastContentSection.parentElement.appendChild(fragment);
}
}
/**
* Builds all synthetic blocks in a container element.
* @param {Element} main The container element
*/
function buildAutoBlocks(main) {
try {
if (main.parentNode !== document.body) {
return;
}
const baseDomain = !window.location.port
? `${window.location.protocol}//${window.location.hostname}`
: `${window.location.protocol}//${window.location.hostname}:${window.location.port}`;
if (document.body.classList.contains('blog-post') || document.body.classList.contains('blog-index')) {
main.querySelectorAll('source').forEach((source) => {
let src;
try {
src = new URL(source.srcset);
} catch (e) {
src = new URL(source.srcset, baseDomain);
}
src.pathname = `/blog${src.pathname}`;
source.srcset = `.${src.pathname}${src.search}`;
});
main.querySelectorAll('img').forEach((img) => {
let src;
try {
src = new URL(img.src);
} catch (e) {
src = new URL(img.src, baseDomain);
}
src.pathname = `/blog${src.pathname}`;
img.src = `.${src.pathname}${src.search}`;
});
}
if (!document.body.classList.contains('blog-post')) {
buildHeroBlock(main);
} else {
buildBlockPostPage(main);
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Auto Blocking failed', error);
}
}
export function changeDomain(block) {
block.querySelectorAll('a').forEach((anchor) => {
const url = new URL(anchor.href);
if (url.hostname === 'www.24petwatch.com' || url.hostname === '24petwatch.com') {
url.protocol = window.location.protocol;
url.hostname = window.location.hostname;
url.port = window.location.port;
anchor.href = url.toString();
}
});
}
/**
* Rewrite links to add Canada to the path
* @param {Element} block The block element
*/
export function addCanadaToLinks(block) {
if (isCanada) {
block.querySelectorAll('a').forEach((anchor) => {
if (anchor.getAttribute('rel') === 'alternate') return;
const url = new URL(anchor.href);
const newUrl = new URL(anchor.href, window.location.origin);
if (url.hostname === window.location.hostname) {
// change only for internal links
if (!url.pathname.startsWith('/ca/')) {
newUrl.pathname = `/ca${url.pathname}`;
anchor.href = newUrl.toString();
}
}
});
}
}
/**
* Decorates the main element.
* @param {Element} main The main element
*/
// eslint-disable-next-line import/prefer-default-export
export function decorateMain(main) {
// hopefully forward compatible button decoration
decorateButtons(main);
decorateIcons(main);
changeDomain(main);
addCanadaToLinks(main);
decorateLinks(main);
buildAutoBlocks(main);
decorateSections(main);
decorateBlocks(main);
}
export function loadScript(url, attrs, callback) {
const head = document.querySelector('head');
const script = document.createElement('script');
script.src = url;
script.onload = callback;
if (attrs) {
// eslint-disable-next-line no-restricted-syntax, guard-for-in
for (const attr in attrs) {
script.setAttribute(attr, attrs[attr]);
}
}
head.append(script);
return script;
}
/**
* Loads everything needed to get to LCP.
* @param {Element} doc The container element
*/
async function loadEager(doc) {
document.documentElement.lang = 'en';
decorateTemplateAndTheme();
const main = doc.querySelector('main');
if (main) {
createInlineScript(document, document.body, getAlloyInitScript(), 'text/javascript');
createInlineScript(document, document.body, getGTMInitScript(), 'text/javascript');
decorateMain(main);
document.body.classList.add('appear');
await waitForLCP(LCP_BLOCKS);
}
}
async function initializeConversionTracking() {
const context = {
getMetadata,
toClassName,
};
// eslint-disable-next-line import/no-relative-packages
const { initConversionTracking } = await import('../plugins/rum-conversion/src/index.js');
await initConversionTracking.call(context, document);
// call upon conversion events, sends them to alloy
sampleRUM.always.on('convert', async (data) => {
const { element } = data;
if (!element || !alloy) {
return;
}
// form tracking related logic should be added here if need be.
// see https://github.com/adobe/franklin-rum-conversion#integration-with-analytics-solutions
analyticsTrackConversion({ ...data });
});
}
/**
* instruments the tracking in the main
* @param {Element} main The main element
*/
function instrumentTrackingEvents(main) {
main.querySelectorAll('a')
.forEach((anchor) => {
anchor.addEventListener('click', (e) => {
const linkText = (e.target.textContent || '').trim();
const linkUrl = e.target.href;
const pageUrl = window.location.href;
// track cta clicks on main
if (e.target.classList.contains('button')) {
trackGTMEvent('cta_click', {
link_text: linkText,
link_url: linkUrl,
});
}
// track clicks to call for telephone numbers
if (linkUrl.startsWith('tel')) {
trackGTMEvent('click_to_call', {
page_url: pageUrl,
});
}
// track clicks for Login to MyPetHealth
if (linkUrl === 'https://mypethealth.com/auth/login') {
trackGTMEvent('pet_lost_report_mypethealth_link');
}
});
});
}
function cleanLocalhostLinks(main) {
main.querySelectorAll('a')
.forEach((anchor) => {
if (anchor.href.startsWith('http://localhost:3001')) {
const url = new URL(anchor.href);
url.hostname = 'www.24petwatch.com';
url.scheme = 'https';
url.port = '';
anchor.href = url.toString();
}
});
}
/**
* Loads everything that doesn't need to be delayed.
* @param {Element} doc The container element
*/
async function loadLazy(doc) {
const main = doc.querySelector('main');
await loadBlocks(main);
const { hash } = window.location;
const element = hash ? doc.getElementById(hash.substring(1)) : false;
if (hash && element) element.scrollIntoView();
loadHeader(doc.querySelector('header'));
loadFooter(doc.querySelector('footer'));
loadCSS(`${window.hlx.codeBasePath}/styles/lazy-styles.css`);
sampleRUM('lazy');
sampleRUM.observe(main.querySelectorAll('div[data-block-name]'));
sampleRUM.observe(main.querySelectorAll('picture > img'));
await setupAnalyticsTrackingWithAlloy(document);
await setupAnalyticsTrackingWithGTM();
analyticsSetConsent(true);
await initializeConversionTracking();
instrumentTrackingEvents(main);
cleanLocalhostLinks(main);
}
/**
* Loads everything that happens a lot later,
* without impacting the user experience.
*/
function loadDelayed() {
// eslint-disable-next-line import/no-cycle
window.setTimeout(() => import('./delayed.js'), 3000);
// load anything that can be postponed to the latest here
}
async function loadPage() {
await loadEager(document);
await loadLazy(document);
loadDelayed();
}
loadPage();