-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathhelpers.ts
More file actions
105 lines (92 loc) · 2.8 KB
/
helpers.ts
File metadata and controls
105 lines (92 loc) · 2.8 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
import type { Page } from '@playwright/test'
const CI_SETTLE_DELAY_MS = 250
const LOCAL_SETTLE_DELAY_MS = 100
function getSettleDelayMs(): number {
return process.env.CI ? CI_SETTLE_DELAY_MS : LOCAL_SETTLE_DELAY_MS
}
/**
* Wait for all fonts to be loaded and a rendering frame to complete.
* Replaces waitForTimeout(1000) after page.goto()
*
* Falls back to waitForLoadState('load') when JavaScript is disabled
* (page.evaluate is not available in JS-disabled contexts).
*/
export async function waitForFontsReady(page: Page): Promise<void> {
await page.waitForLoadState('load')
try {
await page.evaluate(async (settleDelayMs) => {
const wait = (ms: number) =>
new Promise<void>((resolve) => window.setTimeout(resolve, ms))
const nextFrame = () =>
new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
if ('fonts' in document) {
await document.fonts.ready
}
const pendingImages = Array.from(document.images).filter(
(image) => !image.complete,
)
await Promise.all(
pendingImages.map(
(image) =>
new Promise<void>((resolve) => {
image.addEventListener('load', () => resolve(), {
once: true,
})
image.addEventListener('error', () => resolve(), {
once: true,
})
}),
),
)
await nextFrame()
await nextFrame()
await wait(settleDelayMs)
}, getSettleDelayMs())
} catch {
await page.waitForTimeout(getSettleDelayMs())
}
}
/**
* Wait for CSS transitions to settle after a style/theme change.
* Replaces waitForTimeout(100-300) after theme switches, scroll, evaluate, etc.
*
* Falls back to waitForLoadState('load') when JavaScript is disabled.
*/
export async function waitForStyleSettle(page: Page): Promise<void> {
try {
await page.waitForFunction(() => {
return Array.from(
document.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]'),
).every((link) => {
if (!link.href) {
return true
}
const { sheet } = link
if (!sheet) {
return false
}
try {
void sheet.cssRules
return true
} catch {
return false
}
})
})
} catch {
await page.waitForLoadState('load')
}
try {
await page.evaluate(async (settleDelayMs) => {
const wait = (ms: number) =>
new Promise<void>((resolve) => window.setTimeout(resolve, ms))
const nextFrame = () =>
new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
await nextFrame()
await nextFrame()
await wait(settleDelayMs)
}, getSettleDelayMs())
} catch {
await page.waitForTimeout(getSettleDelayMs())
}
}