-
Notifications
You must be signed in to change notification settings - Fork 141
/
screenshots.ts
executable file
·226 lines (201 loc) · 6.91 KB
/
screenshots.ts
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
#!/usr/bin/env node
import { isNullish } from "@dfinity/utils";
import { ChromeOptions } from "@wdio/types/build/Capabilities";
import { existsSync, mkdirSync } from "fs";
import { remote } from "webdriverio";
const SCREENSHOTS_DIR =
process.env["SCREENSHOTS_DIR"] ?? "./screenshots/custom";
/** This executable takes screenshots of every page in the showcase.
* This function expects the showcase to be running on 'http://localhost:5174'. Everything
* else is automated. */
async function main() {
// Set up the directory where we'll save the screenshots
if (!existsSync(SCREENSHOTS_DIR)) {
mkdirSync(SCREENSHOTS_DIR, { recursive: true });
}
await withChrome(async (browser) => {
await takeLandingScreenshots(browser);
await takeShowcaseScreenshots(browser);
});
}
/** Take multiple screenshots spanning the entire landing page */
async function takeLandingScreenshots(browser: WebdriverIO.Browser) {
// Use "authorizeNewKnown" as a good variation of the landing page
await visit(browser, "http://localhost:5174/authorizeNewKnown");
// There is no support for full page screenshots, so we take N screenshots
// of the viewport, and scroll to the viewport height in between each screenshot
const [screenshotHeight, totalHeight] = await browser.execute(() => {
return [window.innerHeight, document.body.scrollHeight];
});
const nScreenshots = Math.ceil(totalHeight / screenshotHeight);
for (let i = 0; i < nScreenshots; i++) {
await browser.execute(
(i, screenshotHeight) => {
window.scrollTo(0, i * screenshotHeight);
},
i,
screenshotHeight
);
await browser.saveScreenshot(`${SCREENSHOTS_DIR}/landing_${i + 1}.png`);
}
}
/** Open each showcase page one after the other and screenshot it */
async function takeShowcaseScreenshots(browser: WebdriverIO.Browser) {
await visit(browser, "http://localhost:5174/");
// The landing page has a link for every page. The link tags have `data-page-name`
// attributes, which we gather as the list of page names.
const pageLinks = await browser.$$("[data-page-name]");
const pageNames = await Promise.all(
await pageLinks.map(async (link) => {
const pageName = await link.getAttribute("data-page-name");
return pageName;
})
);
// Iterate the pages and screenshot them
for (const pageName of pageNames) {
await visit(browser, `http://localhost:5174/${pageName}`);
await browser.execute('document.body.style.caretColor = "transparent"');
await browser.saveScreenshot(`${SCREENSHOTS_DIR}/${pageName}.png`);
// When a chasm is present, toggle it
if (await browser.$('[data-action="toggle-chasm"]').isExisting()) {
await browser.$('[data-action="toggle-chasm"]').click();
// Ensure the button is not hovered anymore for screenshot stability
await browser
.$('[data-action="toggle-chasm"]')
.moveTo({ xOffset: -10, yOffset: -10 });
await browser.saveScreenshot(`${SCREENSHOTS_DIR}/${pageName}_open.png`);
}
}
}
/** Create a chrome instance and run callback, deleting session afterwards */
async function withChrome<T>(
cb: (browser: WebdriverIO.Browser) => T
): Promise<T> {
// Screenshot image dimension, if specified
const { mobileEmulation } = readScreenshotsConfig();
const chromeOptions: ChromeOptions = {
// font-render-hinting causing broken kerning on headless chrome seems to be a
// long-standing issue: see https://github.com/puppeteer/puppeteer/issues/2410
// -> disabling it improves things
args: [
"headless",
"disable-gpu",
"font-render-hinting=none",
"hide-scrollbars",
"disable-dev-shm-usage", // disable /dev/shm usage because chrome is prone to crashing otherwise
],
mobileEmulation,
};
const browser = await remote({
capabilities: {
browserName: "chrome",
browserVersion: "122.0.6261.111", // More information about available versions can be found here: https://github.com/GoogleChromeLabs/chrome-for-testing
"goog:chromeOptions": chromeOptions,
},
});
if (isNullish(mobileEmulation)) {
await browser.setWindowSize(1200, 900);
}
const res = await cb(browser);
await browser.deleteSession();
return res;
}
/** Visit page and wait until loaded */
async function visit(browser: WebdriverIO.Browser, url: string) {
await browser.url(url);
/* Disable transitions and animations to make sure we screenshot the (final) actual state */
await browser.execute(() => {
const notransition = `
*, *::before, *::after {
-o-transition-property: none !important;
-moz-transition-property: none !important;
-ms-transition-property: none !important;
-webkit-transition-property: none !important;
transition-property: none !important;
}
`;
const noanimation = `
*, *::before, *::after {
animation: none !important;
}
`;
const style = document.createElement("style");
style.appendChild(document.createTextNode(notransition));
style.appendChild(document.createTextNode(noanimation));
document.body.appendChild(style);
});
/* Make sure lazy images are loaded eagerly */
await browser.execute(() => {
const imgs = Array.from(document.querySelectorAll("img"));
imgs.forEach((img) => {
if (img.getAttribute("loading") === "lazy") {
img.setAttribute("loading", "eager");
}
});
});
/* Make sure everything has loaded */
await browser.waitUntil(
() =>
browser.execute(() => {
const imgs = Array.from(document.querySelectorAll("img"));
return imgs.every((img) => img.complete);
}),
{
timeout: 10 * 1000,
timeoutMsg: "Images did not load after 10 seconds",
}
);
await browser.waitUntil(
() => browser.execute(() => document.readyState === "complete"),
{
timeout: 10 * 1000,
timeoutMsg: "Browser did not load after 10 seconds",
}
);
}
/**
* Read the screenshots configuration based on 'SCREENSHOTS_TYPE'
* (either 'mobile' or 'desktop') and returns the appropriate device
* name and/or window size.
*
* NOTE: deviceMetrics are necessary due to a bug in webdriverio
* (otherwise just use 'deviceName'):
* * https://github.com/webdriverio/webdriverio/issues/8903
*/
function readScreenshotsConfig(): {
mobileEmulation?: {
deviceMetrics: {
width: number;
height: number;
pixelRatio: number;
touch: boolean;
};
};
} {
const screenshotsType = process.env["SCREENSHOTS_TYPE"];
switch (screenshotsType) {
case "mobile":
return {
mobileEmulation: {
// Emulate a small modern device
deviceMetrics: {
width: 360,
height: 640,
pixelRatio: 1,
touch: true,
},
},
};
break;
case undefined:
return {};
break;
case "desktop":
return {};
break;
default:
throw Error("Unknown screenshots type: " + screenshotsType);
break;
}
}
await main();