-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtakeDOMSnapshot.js
More file actions
405 lines (358 loc) · 11.9 KB
/
takeDOMSnapshot.js
File metadata and controls
405 lines (358 loc) · 11.9 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
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
const md5 = require('crypto-js/md5');
const parseSrcset = require('parse-srcset');
const findCSSAssetUrls = require('./src/findCSSAssetUrls');
const applyConstructedStylesPatch = require('./src/applyConstructedStylesPatch');
const CSS_ELEMENTS_SELECTOR = 'style,link[rel="stylesheet"][href]';
const COMMENT_PATTERN = /^\/\*.+\*\/$/;
applyConstructedStylesPatch();
const recordedCSSSymbol = applyConstructedStylesPatch.recordedCSSSymbol;
function getContentFromStyleSheet(element) {
let lines;
if (element.textContent) {
// Handle <style> elements with direct textContent
lines = element.textContent.split('\n').map((line) => line.trim());
} else if (element[recordedCSSSymbol]) {
lines = element[recordedCSSSymbol];
} else if (element.sheet && element.sheet.cssRules) {
// Handle <style> or <link> elements that have a sheet property
lines = Array.from(element.sheet.cssRules).map((rule) => rule.cssText);
} else if (element.cssRules) {
// Handle CSSStyleSheet objects (including adoptedStyleSheets)
lines = Array.from(element.cssRules).map((rule) => rule.cssText);
} else {
return '';
}
return lines.filter((line) => line && !COMMENT_PATTERN.test(line)).join('\n');
}
function extractCSSBlocks(doc) {
const blocks = [];
const styleElements = doc.querySelectorAll(CSS_ELEMENTS_SELECTOR);
styleElements.forEach((element) => {
if (element.closest('happo-shadow-content')) {
// Skip if element is inside a happo-shadow-content element. These need to
// be scoped to the shadow root and cannot be part of the global styles.
return;
}
if (element.tagName === 'LINK') {
// <link href>
const href = element.href || element.getAttribute('href');
blocks.push({ key: href, href, baseUrl: element.baseURI });
} else {
const content = getContentFromStyleSheet(element);
// Create a hash so that we can dedupe equal styles
const key = md5(content).toString();
blocks.push({ content, key, baseUrl: element.baseURI });
}
});
(doc.adoptedStyleSheets || []).forEach((sheet) => {
const content = getContentFromStyleSheet(sheet);
const key = md5(content).toString();
blocks.push({ key, content, baseUrl: sheet.href || document.baseURI });
});
return blocks;
}
function defaultHandleBase64Image({ base64Url, element }) {
// Simply make the base64Url the src of the image
element.src = base64Url;
}
function getElementAssetUrls(
element,
{ handleBase64Image = defaultHandleBase64Image },
) {
const allUrls = [];
const allElements = [element].concat(Array.from(element.querySelectorAll('*')));
allElements.forEach((element) => {
if (element.tagName === 'SCRIPT') {
// skip script elements
return;
}
const srcset = element.getAttribute('srcset');
const src = element.getAttribute('src');
const imageHref =
element.tagName.toLowerCase() === 'image' && element.getAttribute('href');
const linkHref =
element.tagName.toLowerCase() === 'link' &&
element.getAttribute('rel') === 'stylesheet' &&
element.getAttribute('href');
const style = element.getAttribute('style');
const base64Url = element._base64Url;
if (base64Url) {
handleBase64Image({ src, base64Url, element });
}
if (src) {
allUrls.push({ url: src, baseUrl: element.baseURI });
}
if (srcset) {
allUrls.push(
...parseSrcset(srcset).map((p) => ({
url: p.url,
baseUrl: element.baseURI,
})),
);
}
if (style) {
allUrls.push(
...findCSSAssetUrls(style).map((url) => ({
url,
baseUrl: element.baseURI,
})),
);
}
if (imageHref) {
allUrls.push({ url: imageHref, baseUrl: element.baseURI });
}
if (linkHref) {
allUrls.push({ url: linkHref, baseUrl: element.baseURI });
}
});
return allUrls.filter(({ url }) => !url.startsWith('data:'));
}
function copyStyles(sourceElement, targetElement) {
const computedStyle = window.getComputedStyle(sourceElement);
for (let i = 0; i < computedStyle.length; i++) {
const key = computedStyle[i];
const value = computedStyle.getPropertyValue(key);
targetElement.style.setProperty(key, value);
}
}
function inlineCanvases(element, { doc, responsiveInlinedCanvases = false }) {
const canvases = [];
if (element.tagName === 'CANVAS') {
canvases.push(element);
}
canvases.push(...Array.from(element.querySelectorAll('canvas')));
let newElement = element;
const replacements = [];
for (const canvas of canvases) {
try {
const canvasImageBase64 = canvas.toDataURL('image/png');
if (canvasImageBase64 === 'data:,') {
continue;
}
const image = doc.createElement('img');
const url = `/.happo-tmp/_inlined/${md5(canvasImageBase64).toString()}.png`;
image.src = url;
image._base64Url = canvasImageBase64;
const style = canvas.getAttribute('style');
if (style) {
image.setAttribute('style', style);
}
const className = canvas.getAttribute('class');
if (className) {
image.setAttribute('class', className);
}
if (responsiveInlinedCanvases) {
image.style.width = '100%';
image.style.height = 'auto';
} else {
const width = canvas.getAttribute('width');
const height = canvas.getAttribute('height');
image.setAttribute('width', width);
image.setAttribute('height', height);
copyStyles(canvas, image);
}
canvas.replaceWith(image);
if (canvas === element) {
// We're inlining the element. Make sure we return the modified element.
newElement = image;
}
replacements.push({ from: canvas, to: image });
} catch (e) {
if (e.name === 'SecurityError') {
console.warn('[HAPPO] Failed to convert tainted canvas to PNG image');
console.warn(e);
} else {
throw e;
}
}
}
function cleanup() {
for (const { from, to } of replacements) {
to.replaceWith(from);
}
}
return { element: newElement, cleanup };
}
function registerScrollPositions(doc) {
const elements = doc.body.querySelectorAll('*');
for (const node of elements) {
if (node.scrollTop !== 0 || node.scrollLeft !== 0) {
node.setAttribute(
'data-happo-scrollposition',
`${node.scrollTop},${node.scrollLeft}`,
);
}
}
}
function registerCheckedInputs(doc) {
const elements = doc.body.querySelectorAll(
'input[type="checkbox"], input[type="radio"]',
);
for (const node of elements) {
if (node.checked) {
node.setAttribute('checked', 'checked');
} else {
node.removeAttribute('checked');
}
}
}
function extractElementAttributes(el) {
const result = {};
[...el.attributes].forEach((item) => {
result[item.name] = item.value;
});
return result;
}
function performDOMTransform({ doc, selector, transform, element }) {
const elements = Array.from(element.querySelectorAll(selector));
if (!elements.length) {
return;
}
const replacements = [];
for (const element of elements) {
const replacement = transform(element, doc);
replacements.push({ from: element, to: replacement });
element.replaceWith(replacement);
}
return () => {
for (const { from, to } of replacements) {
to.replaceWith(from);
}
};
}
function transformToElementArray(elements, doc) {
// Check if 'elements' is already an array
if (Array.isArray(elements)) {
return elements;
}
// Check if 'elements' is a NodeList
if (elements instanceof doc.defaultView.NodeList) {
return Array.from(elements);
}
// Check if 'elements' is a single HTMLElement
if (elements instanceof doc.defaultView.HTMLElement) {
return [elements];
}
if (typeof elements.length !== 'undefined') {
return elements;
}
return [elements];
}
/**
* Injects all shadow roots from the given element.
*
* @param {HTMLElement} element
*/
function inlineShadowRoots(element) {
const elements = [element];
const elementsToProcess = [];
while (elements.length) {
const element = elements.shift();
if (element.shadowRoot) {
elementsToProcess.unshift(element); // LIFO so that leaf nodes are processed first
}
elements.unshift(...element.children); // LIFO so that leaf nodes are processed first
}
for (const element of elementsToProcess) {
const hiddenElement = document.createElement('happo-shadow-content');
hiddenElement.style.display = 'none';
// Add adopted stylesheets as <style> elements
for (const styleSheet of element.shadowRoot.adoptedStyleSheets) {
const styleElement = document.createElement('style');
styleElement.setAttribute('data-happo-inlined', 'true');
const styleContent = getContentFromStyleSheet(styleSheet);
styleElement.textContent = styleContent;
hiddenElement.appendChild(styleElement);
}
hiddenElement.innerHTML += element.shadowRoot.innerHTML;
element.appendChild(hiddenElement);
}
}
function findSvgElementsWithSymbols(element) {
return [...element.ownerDocument.querySelectorAll('svg')].filter((svg) =>
svg.querySelector('symbol'),
);
}
function takeDOMSnapshot({
doc,
element: oneOrMoreElements,
responsiveInlinedCanvases = false,
transformDOM,
handleBase64Image,
strategy = 'hoist',
} = {}) {
const allElements = transformToElementArray(oneOrMoreElements, doc);
const htmlParts = [];
const assetUrls = [];
for (const originalElement of allElements) {
const { element, cleanup: canvasCleanup } = inlineCanvases(originalElement, {
doc,
responsiveInlinedCanvases,
});
registerScrollPositions(doc);
registerCheckedInputs(doc);
const transformCleanup = transformDOM
? performDOMTransform({
doc,
element,
...transformDOM,
})
: undefined;
element.querySelectorAll('script').forEach((scriptEl) => {
scriptEl.parentNode.removeChild(scriptEl);
});
doc
.querySelectorAll('[data-happo-focus]')
.forEach((e) => e.removeAttribute('data-happo-focus'));
if (doc.activeElement && doc.activeElement !== doc.body) {
doc.activeElement.setAttribute('data-happo-focus', 'true');
}
inlineShadowRoots(element);
assetUrls.push(
...getElementAssetUrls(element, {
doc,
handleBase64Image,
}),
);
if (strategy === 'hoist') {
htmlParts.push(element.outerHTML);
} else if (strategy === 'clip') {
element.setAttribute('data-happo-clip', 'true');
htmlParts.push(doc.body.outerHTML);
} else {
throw new Error(`Unknown strategy: ${strategy}`);
}
if (strategy === 'hoist') {
const svgElementsWithSymbols = findSvgElementsWithSymbols(element);
for (const svgElement of svgElementsWithSymbols) {
htmlParts.push(`<div style="display: none;">${svgElement.outerHTML}</div>`);
}
}
if (canvasCleanup) canvasCleanup();
if (transformCleanup) transformCleanup();
}
const cssBlocks = extractCSSBlocks(doc);
const htmlElementAttrs = extractElementAttributes(doc.documentElement);
const bodyElementAttrs = extractElementAttributes(doc.body);
// Remove our shadow content elements so that they don't affect the page
doc.querySelectorAll('happo-shadow-content').forEach((e) => e.remove());
if (strategy === 'clip') {
doc
.querySelectorAll('[data-happo-clip]')
.forEach((e) => e.removeAttribute('data-happo-clip'));
}
return {
html: htmlParts.join('\n'),
assetUrls,
cssBlocks,
htmlElementAttrs,
bodyElementAttrs,
};
}
takeDOMSnapshot.init = function noop() {
// There used to be some code in here to set the baseUrl of all link elements.
// But that's no longer needed (because Node.baseURI exists). We're keeping
// the function around here however to make sure we stay backwards compatible.
};
takeDOMSnapshot.applyConstructedStylesPatch = applyConstructedStylesPatch;
module.exports = takeDOMSnapshot;