-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathscrollHelper.ts
67 lines (59 loc) · 2.18 KB
/
scrollHelper.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
import { type Page } from 'playwright';
interface ScrollOptions {
stepSize?: number;
timeout?: number;
scrollOffsetThreshold?: number;
}
/**
* Scroll a specified container element horizontally by the given step size, with a delay between steps.
*
* @param {Page} page - The Playwright page object.
* @param {string} containerSelector - The CSS selector for the scrollable container element.
* @param {ScrollOptions} [options={}] - Optional scroll configuration including step size, timeout, and scroll offset threshold.
* @returns {Promise<void>} - Resolves once the container has been fully scrolled.
*/
const scrollContainer = async (
page: Page,
containerSelector: string,
{ stepSize = 300, timeout = 20, scrollOffsetThreshold = 200 }: ScrollOptions = {}
): Promise<void> => {
// Locate the scrollable container on the page
await page.waitForSelector(containerSelector, { state: 'visible' });
const container = await page.evaluateHandle(
(selector: string) => document.querySelector(selector),
containerSelector
);
// Get the scrollable width and visible width of the container
const { scrollWidth, clientWidth } = await page.evaluate(
(containerElement) =>
containerElement
? {
scrollWidth: containerElement.scrollWidth,
clientWidth: containerElement.clientWidth,
}
: { scrollWidth: 0, clientWidth: 0 }, // Default if no container found
container
);
// Exit early if there's little or no scrollable content
if (scrollWidth <= clientWidth + scrollOffsetThreshold) {
await container.dispose();
return;
}
// Scroll the container in steps until the end of the content is reached
let currentScrollPosition = 0;
while (currentScrollPosition < scrollWidth) {
await page.evaluate(
({ containerElement, step }) => {
if (containerElement) {
containerElement.scrollLeft += step; // Scroll by step size
}
},
{ containerElement: container, step: stepSize }
);
await page.waitForTimeout(timeout);
currentScrollPosition += stepSize;
}
// Clean up the handle after scrolling is complete
await container.dispose();
};
export default scrollContainer;