-
Notifications
You must be signed in to change notification settings - Fork 185
/
Copy pathscreenshotWithClipToContent.ts
55 lines (48 loc) · 1.81 KB
/
screenshotWithClipToContent.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
import type { Page, PlaywrightWorkerOptions } from '@playwright/test';
import { DEFAULT_CROP_TO_CONTENT_SELECTOR } from './constants';
import type { ScreenshotWithClipToContentOptions } from './types';
export async function screenshotWithClipToContent(
page: Page,
options: ScreenshotWithClipToContentOptions = {},
browserName: PlaywrightWorkerOptions['browserName'] | undefined = undefined,
) {
const { cropToContentSelector = DEFAULT_CROP_TO_CONTENT_SELECTOR } = options;
await page.evaluate(() => document.fonts.ready);
// getBoundingClientRect в webkit возвращает некорректные значения, спасает timeout 500ms
// см. https://github.com/VKCOM/VKUI/pull/3417
if (browserName === 'webkit') {
await page.evaluate(
() =>
new Promise((resolve) => {
setTimeout(resolve, 500);
}),
);
}
const clip = await page.evaluate((selector) => {
const size = { right: 0, bottom: 0, x: Infinity, y: Infinity };
document.querySelectorAll(selector).forEach((node) => {
const { x, y, right, bottom } = node.getBoundingClientRect();
size.right = Math.max(size.right, right);
size.bottom = Math.max(size.bottom, bottom);
size.x = Math.min(size.x, x);
size.y = Math.min(size.y, y);
});
return {
x: size.x,
y: size.y,
width: Math.round(size.right - size.x),
height: Math.round(size.bottom - size.y),
};
}, cropToContentSelector);
const viewportSize = page.viewportSize() ?? { width: 0, height: 0 };
// см. https://github.com/VKCOM/VKUI/pull/3272
await page.setViewportSize({
width: Math.max(clip.width, viewportSize.width),
height: Math.max(clip.height, viewportSize.height),
});
return page.screenshot({
clip,
fullPage: true,
animations: 'disabled',
});
}