playwright-touch 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +612 -2
  3. package/dist/android.d.ts +26 -0
  4. package/dist/android.js +113 -0
  5. package/dist/chromium/clock.d.ts +12 -0
  6. package/dist/chromium/clock.js +45 -0
  7. package/dist/chromium/gestures.d.ts +56 -0
  8. package/dist/chromium/gestures.js +500 -0
  9. package/dist/chromium/steady.d.ts +16 -0
  10. package/dist/chromium/steady.js +38 -0
  11. package/dist/cli.d.ts +2 -0
  12. package/dist/cli.js +459 -0
  13. package/dist/index.d.ts +111 -0
  14. package/dist/index.js +149 -0
  15. package/dist/ios/bplist.d.ts +8 -0
  16. package/dist/ios/bplist.js +150 -0
  17. package/dist/ios/device.d.ts +30 -0
  18. package/dist/ios/device.js +48 -0
  19. package/dist/ios/inspector.d.ts +61 -0
  20. package/dist/ios/inspector.js +342 -0
  21. package/dist/ios/iphone.d.ts +27 -0
  22. package/dist/ios/iphone.js +141 -0
  23. package/dist/ios/page.d.ts +90 -0
  24. package/dist/ios/page.js +338 -0
  25. package/dist/ios/paths.d.ts +17 -0
  26. package/dist/ios/paths.js +77 -0
  27. package/dist/ios/simulator.d.ts +24 -0
  28. package/dist/ios/simulator.js +69 -0
  29. package/dist/ios/tab.d.ts +41 -0
  30. package/dist/ios/tab.js +171 -0
  31. package/dist/ios/tools.d.ts +4 -0
  32. package/dist/ios/tools.js +17 -0
  33. package/dist/ios/touch.d.ts +31 -0
  34. package/dist/ios/touch.js +178 -0
  35. package/dist/ios/usbmux.d.ts +34 -0
  36. package/dist/ios/usbmux.js +346 -0
  37. package/dist/layout.d.ts +35 -0
  38. package/dist/layout.js +164 -0
  39. package/dist/measure.d.ts +86 -0
  40. package/dist/measure.js +173 -0
  41. package/dist/own-tabs.d.ts +8 -0
  42. package/dist/own-tabs.js +242 -0
  43. package/dist/playwright-test.d.ts +66 -0
  44. package/dist/playwright-test.js +64 -0
  45. package/dist/polyline.d.ts +10 -0
  46. package/dist/polyline.js +38 -0
  47. package/dist/recipes.d.ts +57 -0
  48. package/dist/recipes.js +135 -0
  49. package/dist/report.d.ts +46 -0
  50. package/dist/report.js +118 -0
  51. package/dist/session.d.ts +35 -0
  52. package/dist/session.js +23 -0
  53. package/dist/show.d.ts +13 -0
  54. package/dist/show.js +51 -0
  55. package/dist/synthetic.d.ts +17 -0
  56. package/dist/synthetic.js +117 -0
  57. package/dist/types.d.ts +58 -0
  58. package/dist/types.js +2 -0
  59. package/package.json +83 -4
@@ -0,0 +1,135 @@
1
+ // Gestures named after what a person is doing, built from the plain ones: swipe until something is
2
+ // in view, pull down to refresh, come in from an edge, move with two fingers. Each works on a
3
+ // Playwright page in Chromium and on Safari, because each is made of `swipe` and `gesture`.
4
+ import { gesture, swipe } from './index.js';
5
+ const isSafariLocator = (target) => !!target && target.ios === true && typeof target.selector === 'string';
6
+ const pageOf = (target) => (isSafariLocator(target) ? target.page : target.page());
7
+ /** Runs a script given as text, which is the one form every kind of page takes. */
8
+ const run = (page, script) => page.evaluate(script);
9
+ const UNIT = {
10
+ up: { x: 0, y: -1 },
11
+ down: { x: 0, y: 1 },
12
+ left: { x: -1, y: 0 },
13
+ right: { x: 1, y: 0 },
14
+ };
15
+ const RECT = '((r) => r && ({ x: r.x, y: r.y, width: r.width, height: r.height }))';
16
+ const viewOf = async (page) => ({
17
+ x: 0,
18
+ y: 0,
19
+ ...(await run(page, '({ width: innerWidth, height: innerHeight })')),
20
+ });
21
+ /** Where an element is in the viewport, or null while it is not on the page. */
22
+ async function boxOf(target) {
23
+ if (isSafariLocator(target)) {
24
+ const selector = JSON.stringify(target.selector);
25
+ return run(target.page, `${RECT}(document.querySelector(${selector}) && document.querySelector(${selector}).getBoundingClientRect())`);
26
+ }
27
+ // An element that is not there yet must not hold the loop up: lists often add it while scrolling.
28
+ const counted = target;
29
+ if (typeof counted.count === 'function' && (await counted.count()) === 0)
30
+ return null;
31
+ return target.evaluate((element) => {
32
+ const r = element.getBoundingClientRect();
33
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
34
+ });
35
+ }
36
+ /** How far a page or a scrolling element has moved, as text that changes when it moves. */
37
+ async function positionOf(page, within) {
38
+ if (!within)
39
+ return run(page, '`${scrollX},${scrollY}`');
40
+ if (isSafariLocator(within)) {
41
+ return run(page, `((e) => e ? e.scrollLeft + ',' + e.scrollTop : '')(document.querySelector(${JSON.stringify(within.selector)}))`);
42
+ }
43
+ return within.evaluate((element) => `${element.scrollLeft},${element.scrollTop}`);
44
+ }
45
+ /**
46
+ * Swipes until the middle of the target is inside the viewport, the way a person scrolls a list to
47
+ * find a row. Returns the number of swipes it took, 0 when the target was in view already. Fails
48
+ * when the content stops moving or the tries run out, and says which.
49
+ */
50
+ export async function swipeUntilVisible(target, options = {}) {
51
+ const page = pageOf(target);
52
+ const { direction = 'up', within, distance, max = 10 } = options;
53
+ const inView = async () => {
54
+ const [box, view] = [await boxOf(target), await viewOf(page)];
55
+ if (!box || box.width === 0 || box.height === 0)
56
+ return false;
57
+ const middle = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
58
+ return middle.x >= 0 && middle.x <= view.width && middle.y >= 0 && middle.y <= view.height;
59
+ };
60
+ const settled = () => new Promise((resolve) => setTimeout(resolve, 250));
61
+ for (let swipes = 0;; swipes++) {
62
+ if (await inView())
63
+ return swipes;
64
+ if (swipes === max) {
65
+ throw new Error(`playwright-touch: the target was not in view after ${max} swipe${max === 1 ? '' : 's'} ${direction}. Raise \`max\`, or check the direction.`);
66
+ }
67
+ const before = await positionOf(page, within);
68
+ await swipe(within ?? page, { direction, ...(distance === undefined ? {} : { distance }) });
69
+ await settled();
70
+ if ((await positionOf(page, within)) === before && !(await inView())) {
71
+ throw new Error(`playwright-touch: the content stopped moving after ${swipes + 1} swipe${swipes ? 's' : ''} ${direction} and the target is not in view. It may be the other way, or in another scrolling element (\`within\`).`);
72
+ }
73
+ }
74
+ }
75
+ /**
76
+ * Pulls the page down from near its top, the gesture behind "pull to refresh". The finger comes to
77
+ * rest before it lifts, as a thumb does. The page should be scrolled to its top first.
78
+ */
79
+ export async function pullToRefresh(page, options = {}) {
80
+ const view = await viewOf(page);
81
+ const from = { x: view.width / 2, y: view.height * 0.2 };
82
+ const distance = options.distance ?? view.height * 0.5;
83
+ await swipe(page, { from, to: { x: from.x, y: from.y + distance }, duration: options.duration ?? 600 });
84
+ }
85
+ /**
86
+ * A stroke that starts on an edge of the screen and comes inward, as for a side drawer or a sheet
87
+ * that is pulled up from the bottom. It starts `inset` pixels from the edge, 2 by default.
88
+ *
89
+ * On a real phone the outermost strip of the screen belongs to the system: in Safari on an iPhone a
90
+ * stroke from the left or right edge goes back or forward in history and the page never sees it,
91
+ * as under a real finger. To reach a drawer of the page there, start further in. On an iPhone 12
92
+ * Pro with iOS 17.5 a start 2 px from the left edge went back and one 6 px from it reached the
93
+ * page; `inset: 20` leaves room.
94
+ */
95
+ export async function edgeSwipe(page, options) {
96
+ const view = await viewOf(page);
97
+ const inset = options.inset ?? 2;
98
+ const inward = { left: 'right', right: 'left', top: 'down', bottom: 'up' };
99
+ const unit = UNIT[inward[options.edge]];
100
+ const from = {
101
+ x: options.edge === 'left' ? inset : options.edge === 'right' ? view.width - inset : view.width / 2,
102
+ y: options.edge === 'top' ? inset : options.edge === 'bottom' ? view.height - inset : view.height / 2,
103
+ };
104
+ const distance = options.distance ?? (unit.x !== 0 ? view.width : view.height) * 0.6;
105
+ await swipe(page, {
106
+ from,
107
+ to: { x: from.x + unit.x * distance, y: from.y + unit.y * distance },
108
+ ...(options.duration === undefined ? {} : { duration: options.duration }),
109
+ });
110
+ }
111
+ /**
112
+ * Two fingers moving side by side, for maps and embeds that keep one finger for the page and ask
113
+ * for two to move themselves.
114
+ */
115
+ export async function twoFingerSwipe(target, options) {
116
+ const onElement = isSafariLocator(target) || typeof target.boundingBox === 'function';
117
+ const page = onElement ? pageOf(target) : target;
118
+ const box = onElement ? await boxOf(target) : await viewOf(page);
119
+ if (!box)
120
+ throw new Error('playwright-touch: the element for a two-finger swipe is not on the page.');
121
+ const unit = UNIT[options.direction];
122
+ const distance = options.distance ?? (unit.x !== 0 ? box.width : box.height) * 0.5;
123
+ const gap = options.gap ?? 80;
124
+ const middle = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
125
+ // The fingers sit across the direction of travel, half the gap to each side of the middle.
126
+ const across = { x: unit.y, y: unit.x };
127
+ const finger = (side) => {
128
+ const start = {
129
+ x: middle.x + (across.x * side * gap) / 2 - (unit.x * distance) / 2,
130
+ y: middle.y + (across.y * side * gap) / 2 - (unit.y * distance) / 2,
131
+ };
132
+ return [start, { x: start.x + unit.x * distance, y: start.y + unit.y * distance }];
133
+ };
134
+ await gesture(page, { fingers: [finger(1), finger(-1)], duration: options.duration ?? 400 });
135
+ }
@@ -0,0 +1,46 @@
1
+ import type { Film, Vitals } from './measure.js';
2
+ /** How a metric stands against the published thresholds. */
3
+ export type Rating = 'good' | 'needs improvement' | 'poor';
4
+ declare const LIMITS: {
5
+ readonly ttfb: readonly [800, 1800];
6
+ readonly fcp: readonly [1800, 3000];
7
+ readonly lcp: readonly [2500, 4000];
8
+ readonly inp: readonly [200, 500];
9
+ readonly cls: readonly [0.1, 0.25];
10
+ };
11
+ /** Rates one metric against the published thresholds. A metric the page did not produce has no rating. */
12
+ export declare function rate(metric: keyof typeof LIMITS, value: number | null): Rating | null;
13
+ /** One visit on one device. */
14
+ export interface Run {
15
+ /** What it was measured on, for example the phone's model and browser. */
16
+ device: string;
17
+ vitals: Vitals;
18
+ /** Recordings to show as film strips, in order. */
19
+ films?: {
20
+ label: string;
21
+ film: Film;
22
+ }[];
23
+ }
24
+ /** One visit on one device, with what the report should say about it. */
25
+ export interface Report extends Run {
26
+ title: string;
27
+ /** The address that was measured. */
28
+ url: string;
29
+ /** How many frames of each recording to show. Default 8. */
30
+ framesPerFilm?: number;
31
+ }
32
+ /** The same visit on several devices. */
33
+ export interface Comparison {
34
+ title: string;
35
+ /** The address that was measured. */
36
+ url: string;
37
+ /** The same visit on several devices, shown side by side in this order. */
38
+ runs: Run[];
39
+ /** How many frames of each recording to show. Default 8. */
40
+ framesPerFilm?: number;
41
+ }
42
+ /** Writes the same visit on several devices as one self-contained HTML file: no network, no other files. */
43
+ export declare function writeComparison(path: string, report: Comparison): void;
44
+ /** Writes one visit as one self-contained HTML file. */
45
+ export declare function writeReport(path: string, report: Report): void;
46
+ export {};
package/dist/report.js ADDED
@@ -0,0 +1,118 @@
1
+ import { writeFileSync } from 'node:fs';
2
+ // The thresholds Google publishes for each metric: up to the first is good, past the second is poor.
3
+ const LIMITS = { ttfb: [800, 1800], fcp: [1800, 3000], lcp: [2500, 4000], inp: [200, 500], cls: [0.1, 0.25] };
4
+ /** Rates one metric against the published thresholds. A metric the page did not produce has no rating. */
5
+ export function rate(metric, value) {
6
+ if (value === null)
7
+ return null;
8
+ const [good, poor] = LIMITS[metric];
9
+ return value <= good ? 'good' : value <= poor ? 'needs improvement' : 'poor';
10
+ }
11
+ const escape = (text) => text.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
12
+ /** Evenly spaced items, always with the first and the last. */
13
+ function pick(items, count) {
14
+ if (items.length <= count)
15
+ return items;
16
+ if (count <= 1)
17
+ return items.slice(0, Math.max(0, count));
18
+ return Array.from({ length: count }, (_, i) => items[Math.round((i * (items.length - 1)) / (count - 1))]);
19
+ }
20
+ const METRICS = [
21
+ {
22
+ name: 'Largest contentful paint',
23
+ meaning: 'When the biggest thing on the first screen was drawn.',
24
+ key: 'lcp',
25
+ unit: 'ms',
26
+ },
27
+ {
28
+ name: 'Interaction to next paint',
29
+ meaning: 'The slowest interaction, from touch to the next picture.',
30
+ key: 'inp',
31
+ unit: 'ms',
32
+ },
33
+ { name: 'Cumulative layout shift', meaning: 'How much the page jumped around on its own.', key: 'cls', unit: '' },
34
+ { name: 'First contentful paint', meaning: 'When the first text or image appeared.', key: 'fcp', unit: 'ms' },
35
+ { name: 'Time to first byte', meaning: 'How long the server took to start answering.', key: 'ttfb', unit: 'ms' },
36
+ ];
37
+ const number = (value) => value.toLocaleString('en-GB');
38
+ /** One table cell: the value and, under it, how it rates. A value the browser did not report says so. */
39
+ function cell(key, value, unit) {
40
+ if (value === null)
41
+ return '<td class="value none">not measured</td>';
42
+ const rating = rate(key, value);
43
+ return `<td class="value">${number(value)}${unit ? ' ' + unit : ''}<span class="rating ${rating.replace(/ /g, '-')}">${rating}</span></td>`;
44
+ }
45
+ /** Writes the same visit on several devices as one self-contained HTML file: no network, no other files. */
46
+ export function writeComparison(path, report) {
47
+ const { runs } = report;
48
+ const head = runs.length > 1
49
+ ? `<thead><tr><th></th>${runs.map((run) => `<th scope="col">${escape(run.device)}</th>`).join('')}</tr></thead>`
50
+ : '';
51
+ // No slowest interaction although there were some: each was answered in under 16 ms, which the browser does not list.
52
+ const quick = (run, key) => key === 'inp' && run.vitals.inp === null && run.vitals.interactions > 0;
53
+ const rows = METRICS.map(({ name, meaning, key, unit }) => `<tr><th scope="row">${name}<small>${meaning}</small></th>${runs.map((run) => (quick(run, key) ? '<td class="value">under 16 ms<span class="rating good">good</span></td>' : cell(key, run.vitals[key], unit))).join('')}</tr>`);
54
+ rows.push(`<tr><th scope="row">Interactions seen<small>How many touches the page had to answer.</small></th>${runs.map((run) => `<td class="value">${run.vitals.interactions}</td>`).join('')}</tr>`, `<tr><th scope="row">Long tasks<small>Stretches over 50 ms in which the page could not react.</small></th>${runs
55
+ .map((run) => run.vitals.longTasks === null
56
+ ? '<td class="value none">not measured</td>'
57
+ : `<td class="value">${run.vitals.longTasks}<span class="note">${number(run.vitals.blocked ?? 0)} ms over the limit</span></td>`)
58
+ .join('')}</tr>`);
59
+ const films = runs.flatMap((run) => (run.films ?? []).map(({ label, film }) => {
60
+ const frames = pick(film.frames, report.framesPerFilm ?? 8);
61
+ const strip = frames
62
+ .map((frame) => `<figure><img alt="" src="data:image/jpeg;base64,${frame.jpeg.toString('base64')}"><figcaption>${(frame.at / 1000).toFixed(2)} s</figcaption></figure>`)
63
+ .join('');
64
+ const where = runs.length > 1 ? `${escape(run.device)}: ` : '';
65
+ return `<section><h2>${where}${escape(label)}</h2><p>${film.frames.length} frames in ${(film.duration / 1000).toFixed(1)} s, ${film.scrolledFor === null ? `the longest pause between two of them ${film.longestPause} ms` : `the page scrolled for ${(film.scrolledFor / 1000).toFixed(1)} s with a longest pause of ${film.longestPause} ms`}. ${frames.length} shown.</p><div class="strip">${strip}</div></section>`;
66
+ }));
67
+ const measuredOn = runs.length > 1 ? `${runs.length} devices` : escape(runs[0]?.device ?? '');
68
+ const html = `<!doctype html>
69
+ <html lang="en">
70
+ <head>
71
+ <meta charset="utf-8">
72
+ <meta name="viewport" content="width=device-width, initial-scale=1">
73
+ <title>${escape(report.title)}</title>
74
+ <style>
75
+ :root { color-scheme: light dark; --ink: #1c1c1c; --soft: #666; --line: #ddd; --paper: #fff; }
76
+ @media (prefers-color-scheme: dark) { :root { --ink: #eee; --soft: #aaa; --line: #3a3a3a; --paper: #161616; } }
77
+ body { margin: 0 auto; max-width: 1040px; padding: 24px 16px 64px; font: 16px/1.5 system-ui, sans-serif; color: var(--ink); background: var(--paper); }
78
+ h1 { font-size: 1.5rem; margin: 0 0 4px; } h2 { font-size: 1.1rem; margin: 40px 0 4px; }
79
+ p { margin: 0 0 12px; color: var(--soft); overflow-wrap: anywhere; }
80
+ .table { overflow-x: auto; }
81
+ table { width: 100%; border-collapse: collapse; margin-top: 16px; }
82
+ th, td { text-align: left; padding: 10px 16px 10px 0; border-top: 1px solid var(--line); vertical-align: top; }
83
+ thead th { border-top: 0; font-size: .9rem; color: var(--soft); font-weight: 600; }
84
+ th { font-weight: 600; } th small { display: block; font-weight: 400; color: var(--soft); }
85
+ .value { white-space: nowrap; font-variant-numeric: tabular-nums; } .none { color: var(--soft); }
86
+ .rating, .note { display: block; width: fit-content; margin-top: 4px; font-size: .8rem; }
87
+ .rating { padding: 1px 8px; border-radius: 999px; border: 1px solid currentColor; } .note { color: var(--soft); }
88
+ .good { color: #1a7f37; } .needs-improvement { color: #9a6700; } .poor { color: #cf222e; }
89
+ @media (prefers-color-scheme: dark) { .good { color: #4ac26b; } .needs-improvement { color: #d4a72c; } .poor { color: #ff8182; } }
90
+ .strip { display: flex; gap: 8px; overflow-x: auto; padding-bottom: 8px; }
91
+ figure { margin: 0; flex: 0 0 150px; } img { width: 100%; display: block; border: 1px solid var(--line); border-radius: 6px; }
92
+ figcaption { font-size: .8rem; color: var(--soft); text-align: center; font-variant-numeric: tabular-nums; }
93
+ </style>
94
+ </head>
95
+ <body>
96
+ <h1>${escape(report.title)}</h1>
97
+ <p>${escape(report.url)}<br>Measured on ${measuredOn}, ${new Date().toISOString().slice(0, 16).replace('T', ' ')} UTC.</p>
98
+ <div class="table"><table>
99
+ ${head}
100
+ <tbody>
101
+ ${rows.join('\n')}
102
+ </tbody>
103
+ </table></div>
104
+ ${films.join('\n')}
105
+ </body>
106
+ </html>
107
+ `;
108
+ writeFileSync(path, html);
109
+ }
110
+ /** Writes one visit as one self-contained HTML file. */
111
+ export function writeReport(path, report) {
112
+ writeComparison(path, {
113
+ title: report.title,
114
+ url: report.url,
115
+ runs: [{ device: report.device, vitals: report.vitals, films: report.films }],
116
+ framesPerFilm: report.framesPerFilm,
117
+ });
118
+ }
@@ -0,0 +1,35 @@
1
+ /** A Chrome DevTools Protocol session, as much of it as the package uses. */
2
+ export interface CDPSession {
3
+ send(method: string, params?: Record<string, unknown>): Promise<unknown>;
4
+ on(event: string, listener: (payload: any) => void): unknown;
5
+ off(event: string, listener: (payload: any) => void): unknown;
6
+ }
7
+ /** A Playwright `Page`. */
8
+ export interface Page {
9
+ viewportSize(): {
10
+ width: number;
11
+ height: number;
12
+ } | null;
13
+ evaluate<R>(pageFunction: () => R | Promise<R>): Promise<R>;
14
+ evaluate<R, A>(pageFunction: (argument: A) => R | Promise<R>, argument: A): Promise<R>;
15
+ /** A script given as text, for code that must be the same in every browser. */
16
+ evaluate<R>(script: string): Promise<R>;
17
+ context(): {
18
+ newCDPSession(page: never): Promise<CDPSession>;
19
+ };
20
+ }
21
+ /** A Playwright `Locator`. */
22
+ export interface Locator {
23
+ boundingBox(): Promise<{
24
+ x: number;
25
+ y: number;
26
+ width: number;
27
+ height: number;
28
+ } | null>;
29
+ scrollIntoViewIfNeeded(): Promise<void>;
30
+ evaluate<R>(pageFunction: (element: Element) => R): Promise<R>;
31
+ evaluate<R, A>(pageFunction: (element: Element, argument: A) => R, argument: A): Promise<R>;
32
+ page(): Page;
33
+ }
34
+ /** One DevTools session per page, opened on first use. Touch input and measurements go through it, so the browser must be Chromium. */
35
+ export declare function sessionOf(page: Page): Promise<CDPSession>;
@@ -0,0 +1,23 @@
1
+ const sessions = new WeakMap();
2
+ /** One DevTools session per page, opened on first use. Touch input and measurements go through it, so the browser must be Chromium. */
3
+ export function sessionOf(page) {
4
+ let session = sessions.get(page);
5
+ if (!session) {
6
+ session = page
7
+ .context()
8
+ .newCDPSession(page)
9
+ .catch((error) => {
10
+ // A failure is not remembered: the next gesture gets to try again.
11
+ sessions.delete(page);
12
+ const browser = page.context()
13
+ .browser?.()
14
+ ?.browserType?.()
15
+ ?.name?.();
16
+ if (browser && browser !== 'chromium')
17
+ throw new Error(`playwright-touch works through the Chrome DevTools Protocol, which ${browser} does not offer. Use a Chromium-based browser.`);
18
+ throw new Error(`playwright-touch: could not open a DevTools session for the page: ${error.message.split('\n')[0]}`);
19
+ });
20
+ sessions.set(page, session);
21
+ }
22
+ return session;
23
+ }
package/dist/show.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { Page } from './session.js';
2
+ /**
3
+ * The script that draws the dots, the same in every browser. It listens to the touches the page
4
+ * really gets, so a dot is proof that a finger arrived. The dots take no touches themselves and
5
+ * are not part of the layout.
6
+ */
7
+ export declare const SHOW_TOUCHES = "(() => {\n if (window.__playwrightTouchShown) return;\n window.__playwrightTouchShown = true;\n const SIZE = 36;\n const layer = document.createElement('div');\n layer.setAttribute('aria-hidden', 'true');\n layer.dataset.playwrightTouch = 'fingers';\n layer.style.cssText = 'position:fixed;inset:0;margin:0;padding:0;border:0;pointer-events:none;z-index:2147483647;overflow:hidden;contain:strict;background:none';\n const dots = new Map();\n const place = (dot, touch) => {\n dot.style.transform = 'translate(' + (touch.clientX - SIZE / 2) + 'px,' + (touch.clientY - SIZE / 2) + 'px)';\n };\n const down = (event) => {\n if (!layer.isConnected) (document.body || document.documentElement).appendChild(layer);\n for (const touch of event.changedTouches) {\n let dot = dots.get(touch.identifier);\n if (!dot) {\n dot = document.createElement('div');\n dot.style.cssText = 'position:absolute;left:0;top:0;width:' + SIZE + 'px;height:' + SIZE + 'px;box-sizing:border-box;border-radius:50%;background:rgba(30,120,255,.4);border:2px solid rgba(255,255,255,.95);box-shadow:0 0 0 1px rgba(0,0,0,.4);transition:opacity .25s;will-change:transform';\n layer.appendChild(dot);\n dots.set(touch.identifier, dot);\n }\n place(dot, touch);\n }\n };\n const up = (event) => {\n for (const touch of event.changedTouches) {\n const dot = dots.get(touch.identifier);\n if (!dot) continue;\n dots.delete(touch.identifier);\n // The dot stays for a moment, or a tap would be over before a film could show it.\n dot.style.opacity = '0';\n setTimeout(() => dot.remove(), 300);\n }\n };\n const quietly = { capture: true, passive: true };\n addEventListener('touchstart', down, quietly);\n addEventListener('touchmove', down, quietly);\n addEventListener('touchend', up, quietly);\n addEventListener('touchcancel', up, quietly);\n})()";
8
+ /** Shows the fingers on a Playwright page, now and on every page it goes to. */
9
+ export declare function showTouches(page: Page & {
10
+ addInitScript?(script: {
11
+ content: string;
12
+ }): Promise<unknown>;
13
+ }): Promise<void>;
package/dist/show.js ADDED
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The script that draws the dots, the same in every browser. It listens to the touches the page
3
+ * really gets, so a dot is proof that a finger arrived. The dots take no touches themselves and
4
+ * are not part of the layout.
5
+ */
6
+ export const SHOW_TOUCHES = `(() => {
7
+ if (window.__playwrightTouchShown) return;
8
+ window.__playwrightTouchShown = true;
9
+ const SIZE = 36;
10
+ const layer = document.createElement('div');
11
+ layer.setAttribute('aria-hidden', 'true');
12
+ layer.dataset.playwrightTouch = 'fingers';
13
+ layer.style.cssText = 'position:fixed;inset:0;margin:0;padding:0;border:0;pointer-events:none;z-index:2147483647;overflow:hidden;contain:strict;background:none';
14
+ const dots = new Map();
15
+ const place = (dot, touch) => {
16
+ dot.style.transform = 'translate(' + (touch.clientX - SIZE / 2) + 'px,' + (touch.clientY - SIZE / 2) + 'px)';
17
+ };
18
+ const down = (event) => {
19
+ if (!layer.isConnected) (document.body || document.documentElement).appendChild(layer);
20
+ for (const touch of event.changedTouches) {
21
+ let dot = dots.get(touch.identifier);
22
+ if (!dot) {
23
+ dot = document.createElement('div');
24
+ dot.style.cssText = 'position:absolute;left:0;top:0;width:' + SIZE + 'px;height:' + SIZE + 'px;box-sizing:border-box;border-radius:50%;background:rgba(30,120,255,.4);border:2px solid rgba(255,255,255,.95);box-shadow:0 0 0 1px rgba(0,0,0,.4);transition:opacity .25s;will-change:transform';
25
+ layer.appendChild(dot);
26
+ dots.set(touch.identifier, dot);
27
+ }
28
+ place(dot, touch);
29
+ }
30
+ };
31
+ const up = (event) => {
32
+ for (const touch of event.changedTouches) {
33
+ const dot = dots.get(touch.identifier);
34
+ if (!dot) continue;
35
+ dots.delete(touch.identifier);
36
+ // The dot stays for a moment, or a tap would be over before a film could show it.
37
+ dot.style.opacity = '0';
38
+ setTimeout(() => dot.remove(), 300);
39
+ }
40
+ };
41
+ const quietly = { capture: true, passive: true };
42
+ addEventListener('touchstart', down, quietly);
43
+ addEventListener('touchmove', down, quietly);
44
+ addEventListener('touchend', up, quietly);
45
+ addEventListener('touchcancel', up, quietly);
46
+ })()`;
47
+ /** Shows the fingers on a Playwright page, now and on every page it goes to. */
48
+ export async function showTouches(page) {
49
+ await page.addInitScript?.({ content: SHOW_TOUCHES });
50
+ await page.evaluate(`void ${SHOW_TOUCHES}`);
51
+ }
@@ -0,0 +1,17 @@
1
+ import type { Page } from './session.js';
2
+ import type { Point } from './types.js';
3
+ /** The engine behind a page: `chromium`, `webkit` or `firefox`. A page that cannot say is taken for Chromium. */
4
+ export declare function engineOf(page: Page): string;
5
+ /** True when gestures on this page are events made by script and not the browser's own touch input. */
6
+ export declare const isSynthetic: (page: Page) => boolean;
7
+ export interface Frame {
8
+ /** Milliseconds after the fingers land. */
9
+ at: number;
10
+ points: Point[];
11
+ }
12
+ /**
13
+ * Plays a gesture as script-made events: the fingers land on the first frame, move through the
14
+ * rest on the page's own clock and lift after the last. `then` adds what a browser adds after a
15
+ * tap.
16
+ */
17
+ export declare function performSynthetic(page: Page, frames: Frame[], then?: 'click' | 'dblclick'): Promise<void>;
@@ -0,0 +1,117 @@
1
+ const engines = new WeakMap();
2
+ /** The engine behind a page: `chromium`, `webkit` or `firefox`. A page that cannot say is taken for Chromium. */
3
+ export function engineOf(page) {
4
+ let engine = engines.get(page);
5
+ if (!engine) {
6
+ try {
7
+ engine = page.context().browser?.()?.browserType().name() ?? 'chromium';
8
+ }
9
+ catch {
10
+ engine = 'chromium';
11
+ }
12
+ engines.set(page, engine);
13
+ }
14
+ return engine;
15
+ }
16
+ /** True when gestures on this page are events made by script and not the browser's own touch input. */
17
+ export const isSynthetic = (page) => engineOf(page) !== 'chromium';
18
+ const warned = new Set();
19
+ function warnOnce(engine) {
20
+ if (warned.has(engine) || process.env.PLAYWRIGHT_TOUCH_QUIET)
21
+ return;
22
+ warned.add(engine);
23
+ const name = engine === 'webkit' ? 'WebKit' : engine === 'firefox' ? 'Firefox' : engine;
24
+ process.stderr.write(`playwright-touch: ${name} has no touch input for Playwright, so gestures are sent as events made by script. ` +
25
+ 'Handlers on the page run; the browser does not scroll, coast or zoom. Set PLAYWRIGHT_TOUCH_QUIET=1 to hide this.\n');
26
+ }
27
+ /**
28
+ * Plays a gesture as script-made events: the fingers land on the first frame, move through the
29
+ * rest on the page's own clock and lift after the last. `then` adds what a browser adds after a
30
+ * tap.
31
+ */
32
+ export async function performSynthetic(page, frames, then) {
33
+ warnOnce(engineOf(page));
34
+ await page.evaluate(async ({ frames, then }) => {
35
+ const first = frames[0].points;
36
+ const targets = first.map((p) => document.elementFromPoint(p.x, p.y) ?? document.body);
37
+ const touchOf = (p, id) => {
38
+ const init = {
39
+ identifier: id,
40
+ target: targets[id],
41
+ clientX: p.x,
42
+ clientY: p.y,
43
+ pageX: p.x + scrollX,
44
+ pageY: p.y + scrollY,
45
+ screenX: p.x,
46
+ screenY: p.y,
47
+ radiusX: 8,
48
+ radiusY: 8,
49
+ force: 1,
50
+ };
51
+ try {
52
+ return new Touch(init);
53
+ }
54
+ catch {
55
+ // WebKit on a desktop has no Touch to construct. Handlers read the same fields off this.
56
+ return init;
57
+ }
58
+ };
59
+ const touch = (type, down, changed) => {
60
+ for (const target of new Set(changed.map((t) => t.target))) {
61
+ const lists = {
62
+ touches: down,
63
+ targetTouches: down.filter((t) => t.target === target),
64
+ changedTouches: changed.filter((t) => t.target === target),
65
+ };
66
+ let event;
67
+ try {
68
+ event = new TouchEvent(type, { bubbles: true, cancelable: true, composed: true, ...lists });
69
+ }
70
+ catch {
71
+ event = new UIEvent(type, { bubbles: true, cancelable: true, composed: true, view: window });
72
+ for (const [name, value] of Object.entries(lists))
73
+ Object.defineProperty(event, name, { value });
74
+ }
75
+ target.dispatchEvent(event);
76
+ }
77
+ };
78
+ const pointer = (type, p, id) => targets[id].dispatchEvent(new PointerEvent(type, {
79
+ pointerId: id + 2,
80
+ pointerType: 'touch',
81
+ isPrimary: id === 0,
82
+ clientX: p.x,
83
+ clientY: p.y,
84
+ screenX: p.x,
85
+ screenY: p.y,
86
+ bubbles: true,
87
+ cancelable: true,
88
+ composed: true,
89
+ button: type === 'pointermove' ? -1 : 0,
90
+ buttons: type === 'pointerup' ? 0 : 1,
91
+ pressure: type === 'pointerup' ? 0 : 0.5,
92
+ width: 16,
93
+ height: 16,
94
+ }));
95
+ const mouse = (type, p, detail) => targets[0].dispatchEvent(new MouseEvent(type, { clientX: p.x, clientY: p.y, bubbles: true, cancelable: true, composed: true, detail }));
96
+ const started = performance.now();
97
+ let last = first;
98
+ first.forEach((p, id) => pointer('pointerdown', p, id));
99
+ const landed = first.map(touchOf);
100
+ touch('touchstart', landed, landed);
101
+ for (const frame of frames.slice(1)) {
102
+ const wait = started + frame.at - performance.now();
103
+ if (wait > 0)
104
+ await new Promise((resolve) => setTimeout(resolve, wait));
105
+ last = frame.points;
106
+ last.forEach((p, id) => pointer('pointermove', p, id));
107
+ const moved = last.map(touchOf);
108
+ touch('touchmove', moved, moved);
109
+ }
110
+ last.forEach((p, id) => pointer('pointerup', p, id));
111
+ touch('touchend', [], last.map(touchOf));
112
+ if (then)
113
+ mouse('click', last[0], then === 'dblclick' ? 2 : 1);
114
+ if (then === 'dblclick')
115
+ mouse('dblclick', last[0], 2);
116
+ }, { frames, then });
117
+ }
@@ -0,0 +1,58 @@
1
+ /** A place in the page, in CSS pixels from the top left of what is on screen. */
2
+ export interface Point {
3
+ x: number;
4
+ y: number;
5
+ }
6
+ /** The way the finger travels. Content follows the finger: a swipe up scrolls the page down. */
7
+ export type Direction = 'up' | 'down' | 'left' | 'right';
8
+ /** A stroke given by where the finger lands and where it lifts. */
9
+ export interface StrokeOptions {
10
+ /** Where the finger lands, in CSS pixels of the viewport. */
11
+ from: Point;
12
+ /** Where the finger lifts. */
13
+ to: Point;
14
+ /** How long the finger travels, in milliseconds. */
15
+ duration?: number;
16
+ }
17
+ /** A stroke given by the way the finger travels across the target. */
18
+ export interface DirectedOptions {
19
+ direction: Direction;
20
+ /** Length of the stroke in CSS pixels. Default: 60 % of the element (or the viewport) along the direction. */
21
+ distance?: number;
22
+ /** How long the finger travels, in milliseconds. */
23
+ duration?: number;
24
+ }
25
+ /** How a drag is carried out. */
26
+ export interface DragOptions {
27
+ /** How long the finger rests before it starts to move, for interfaces that pick an item up on a long press. Default 0. */
28
+ hold?: number;
29
+ /** How long the finger travels, in milliseconds. Default 500. */
30
+ duration?: number;
31
+ }
32
+ /** How far two fingers spread or close. */
33
+ export interface PinchOptions {
34
+ /** How far the fingers end up relative to where they start: 2 spreads them to twice the distance (zoom in), 0.5 brings them together. */
35
+ scale: number;
36
+ /** How long the fingers travel, in milliseconds. Default 400. */
37
+ duration?: number;
38
+ }
39
+ /** How two fingers turn around the middle of an element. */
40
+ export interface RotateOptions {
41
+ /** How far the fingers turn, in degrees. Positive is clockwise. */
42
+ degrees: number;
43
+ /** How long the fingers travel, in milliseconds. Default 500. */
44
+ duration?: number;
45
+ }
46
+ /** A gesture described finger by finger, for anything the named gestures do not cover. */
47
+ export interface GestureOptions {
48
+ /**
49
+ * One list of points per finger, in CSS pixels of the viewport. Each finger lands on its first
50
+ * point, passes through the others at an even pace and lifts on the last. All fingers land and
51
+ * lift together.
52
+ */
53
+ fingers: Point[][];
54
+ /** How long the fingers travel, in milliseconds. Default 500. */
55
+ duration?: number;
56
+ /** How long the fingers rest before they move, in milliseconds. Default 0. */
57
+ hold?: number;
58
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ // The shapes the gestures are described in, the same for Chrome and for Safari.
2
+ export {};