-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
225 lines (204 loc) · 6 KB
/
index.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
const md5 = require('crypto-js/md5');
const parseSrcset = require('parse-srcset');
const findCSSAssetUrls = require('./src/findCSSAssetUrls');
before(() => {
cy.task('happoInit');
});
after(() => {
cy.task('happoTeardown');
});
const COMMENT_PATTERN = /^\/\*.+\*\/$/;
let config = {
responsiveInlinedCanvases: false,
};
module.exports = {
configure: userConfig => {
config = { ...config, ...(userConfig || {}) };
},
};
function extractCSSBlocks({ doc }) {
const blocks = [];
const styleElements = doc.querySelectorAll(
'style,link[rel="stylesheet"][href]',
);
const baseUrl = doc.location.origin;
styleElements.forEach(element => {
if (element.tagName === 'LINK') {
// <link href>
const href = element.getAttribute('href');
blocks.push({ key: href, href, baseUrl });
} else {
// <style>
const lines = Array.from(element.sheet.cssRules).map(r => r.cssText);
// Filter out those lines that are comments (these are often source
// mappings)
const content = lines
.filter(line => !COMMENT_PATTERN.test(line))
.join('\n');
// Create a hash so that we can dedupe equal styles
const key = md5(content).toString();
blocks.push({ content, key, baseUrl });
}
});
return blocks;
}
function getSubjectAssetUrls(subject, doc) {
const allUrls = [];
const allElements = [subject].concat(
Array.from(subject.querySelectorAll('*')),
);
const baseUrl = doc.location.origin;
allElements.forEach(element => {
if (element.tagName === 'SCRIPT') {
// skip script elements
return;
}
const srcset = element.getAttribute('srcset');
const src = element.getAttribute('src');
const style = element.getAttribute('style');
const base64Url = element._base64Url;
if (base64Url) {
cy.task('happoRegisterBase64Image', { base64Url, src });
}
if (src) {
allUrls.push({ url: src, baseUrl });
}
if (srcset) {
allUrls.push(...parseSrcset(srcset).map(p => ({ url: p.url, baseUrl })));
}
if (style) {
allUrls.push(...findCSSAssetUrls(style).map(url => ({ url, baseUrl })));
}
});
return allUrls.filter(({ url }) => !url.startsWith('data:'));
}
function inlineCanvases(doc, subject, options) {
const canvases = [];
if (subject.tagName === 'CANVAS') {
canvases.push(subject);
}
canvases.push(...Array.from(subject.querySelectorAll('canvas')));
const responsive =
typeof options.responsiveInlinedCanvases === 'boolean'
? options.responsiveInlinedCanvases
: config.responsiveInlinedCanvases;
let newSubject = subject;
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 (responsive) {
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);
}
canvas.replaceWith(image);
if (canvas === subject) {
// We're inlining the subject (the `cy.get('canvas')` element). Make sure
// we return the modified subject.
newSubject = 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 { subject: newSubject, cleanup };
}
function transformDOM({ doc, selector, transform, subject }) {
const elements = Array.from(subject.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 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}`,
);
}
}
}
Cypress.Commands.add(
'happoScreenshot',
{ prevSubject: true },
(originalSubject, options = {}) => {
const component = options.component || cy.state('runnable').fullTitle();
const variant = options.variant || 'default';
cy.document().then(doc => {
const { subject, cleanup: canvasCleanup } = inlineCanvases(
doc,
originalSubject[0],
options,
);
registerScrollPositions(doc);
const transformCleanup = options.transformDOM
? transformDOM({
doc,
subject,
...options.transformDOM,
})
: undefined;
const html = subject.outerHTML;
const assetUrls = getSubjectAssetUrls(subject, doc);
const cssBlocks = extractCSSBlocks({ doc });
cy.task('happoRegisterSnapshot', {
html,
cssBlocks,
assetUrls,
component,
variant,
targets: options.targets,
});
if (transformCleanup) {
transformCleanup();
}
canvasCleanup();
});
},
);