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,113 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { ownTabsOnly } from './own-tabs.js';
3
+ import { realPhones } from './chromium/gestures.js';
4
+ const CHROME = 'com.android.chrome';
5
+ function adb(args, serial) {
6
+ return new Promise((resolve, reject) => {
7
+ execFile('adb', serial ? ['-s', serial, ...args] : args, { timeout: 15_000 }, (error, stdout, stderr) => {
8
+ if (error && error.code === 'ENOENT')
9
+ reject(new Error('playwright-touch: adb was not found. Install Android platform tools and make sure adb is on the PATH.'));
10
+ else if (error)
11
+ reject(new Error(`playwright-touch: adb ${args.join(' ')} failed: ${(stderr || error.message).trim()}`));
12
+ else
13
+ resolve(stdout);
14
+ });
15
+ });
16
+ }
17
+ /**
18
+ * What the screen is doing, read from `dumpsys power` and `dumpsys window`: a page is only drawn,
19
+ * and so can only be touched, on a screen that is on and past the lock screen.
20
+ */
21
+ export function phoneState(power, window) {
22
+ const wakefulness = /mWakefulness=(\w+)/.exec(power)?.[1];
23
+ if (wakefulness && wakefulness !== 'Awake')
24
+ return 'screen off';
25
+ const focus = /mCurrentFocus=.*$/m.exec(window)?.[0] ?? '';
26
+ if (/mDreamingLockscreen=true/.test(window) || /Keyguard|NotificationShade|Bouncer/i.test(focus))
27
+ return 'locked';
28
+ return 'ready';
29
+ }
30
+ /**
31
+ * Joins Chrome on an Android phone connected over USB (or any device `adb devices` lists) and
32
+ * returns it as a Playwright browser. Needs USB debugging switched on and the computer trusted;
33
+ * nothing has to be changed in Chrome.
34
+ */
35
+ export async function connectAndroid(options = {}) {
36
+ const listed = (await adb(['devices']))
37
+ .split('\n')
38
+ .slice(1)
39
+ .map((line) => line.trim().split(/\s+/))
40
+ .filter((parts) => parts.length >= 2);
41
+ const wanted = options.serial ? listed.filter(([serial]) => serial === options.serial) : listed;
42
+ if (!options.serial && wanted.length > 1)
43
+ throw new Error(`playwright-touch: ${wanted.length} Android devices are connected. Say which one with the serial option: ${wanted.map(([serial]) => serial).join(', ')}.`);
44
+ if (wanted.length === 0)
45
+ throw new Error('playwright-touch: no Android phone found. Connect it with a cable and switch on USB debugging in the developer options.');
46
+ const [serial, status] = wanted[0];
47
+ if (status === 'unauthorized')
48
+ throw new Error('playwright-touch: the phone has not trusted this computer yet. Unlock it and accept the "Allow USB debugging?" prompt.');
49
+ if (status !== 'device')
50
+ throw new Error(`playwright-touch: the phone is ${status}. Reconnect the cable and try again.`);
51
+ const state = phoneState(await adb(['shell', 'dumpsys', 'power'], serial), await adb(['shell', 'dumpsys', 'window'], serial));
52
+ if (state !== 'ready')
53
+ throw new Error(`playwright-touch: the phone is ${state === 'locked' ? 'locked' : 'asleep'}. Unlock it and keep the screen on: a page is not drawn behind the lock screen, so it cannot be touched.`);
54
+ if (!(await adb(['shell', 'pm', 'list', 'packages', CHROME], serial)).includes(CHROME))
55
+ throw new Error('playwright-touch: Chrome is not installed on the phone.');
56
+ // Brings Chrome to the front (starting it if needed) so its pages are drawn.
57
+ await adb(['shell', 'monkey', '-p', CHROME, '-c', 'android.intent.category.LAUNCHER', '1'], serial);
58
+ await new Promise((resolve) => setTimeout(resolve, 1200));
59
+ const port = Number((await adb(['forward', 'tcp:0', 'localabstract:chrome_devtools_remote'], serial)).trim());
60
+ if (!port)
61
+ throw new Error('playwright-touch: could not forward a port to Chrome on the phone.');
62
+ const unforward = () => adb(['forward', '--remove', `tcp:${port}`], serial).catch(() => undefined);
63
+ let chromium;
64
+ try {
65
+ ({ chromium } = await import('playwright-core'));
66
+ }
67
+ catch {
68
+ await unforward();
69
+ throw new Error('playwright-touch: Playwright is not installed here. Add playwright, @playwright/test or playwright-core to the project.');
70
+ }
71
+ // A Chrome that was just started takes a moment to open its debugging socket, so ask until it answers.
72
+ // The connection goes through a relay that hides the tabs already open on the phone.
73
+ let browser;
74
+ let relay;
75
+ let reason = '';
76
+ for (const deadline = Date.now() + 20_000; !browser && Date.now() < deadline;) {
77
+ try {
78
+ relay = await ownTabsOnly(port);
79
+ browser = await chromium.connectOverCDP(`http://127.0.0.1:${relay.port}`, { timeout: 15_000 });
80
+ }
81
+ catch (error) {
82
+ relay?.close();
83
+ reason = error.message.split('\n')[0] ?? '';
84
+ await new Promise((resolve) => setTimeout(resolve, 500));
85
+ }
86
+ }
87
+ if (!browser) {
88
+ await unforward();
89
+ throw new Error(`playwright-touch: Chrome on the phone did not answer (${reason}). Open Chrome on the phone once, then try again.`);
90
+ }
91
+ const context = browser.contexts()[0];
92
+ realPhones.add(context);
93
+ // The name is only for logs, so a phone that will not tell it is no reason to give up.
94
+ const model = (await adb(['shell', 'getprop', 'ro.product.model'], serial).catch(() => 'Android phone')).trim();
95
+ const ours = [];
96
+ return {
97
+ model,
98
+ browser,
99
+ context,
100
+ async newPage() {
101
+ const page = await context.newPage();
102
+ ours.push(page);
103
+ return page;
104
+ },
105
+ async close() {
106
+ for (const page of ours)
107
+ await page.close().catch(() => undefined);
108
+ await browser.close().catch(() => undefined);
109
+ relay?.close();
110
+ await unforward();
111
+ },
112
+ };
113
+ }
@@ -0,0 +1,12 @@
1
+ import { type Page } from '../session.js';
2
+ /**
3
+ * How far the clock of the device the page runs on is ahead of this computer's, in milliseconds.
4
+ * Events are stamped in the device's time. A phone on a cable keeps its own clock: one that was a
5
+ * third of a second behind this computer got every event stamped in its future, read the stamps
6
+ * as "now", and turned three swipes out of thirty into flings.
7
+ *
8
+ * The time is read in a world of its own inside the page, where a test's fake clock or a site's
9
+ * own `Date` does not reach. It is measured again after a minute, and a failed measurement is not
10
+ * kept.
11
+ */
12
+ export declare function clockAheadOf(page: Page): Promise<number>;
@@ -0,0 +1,45 @@
1
+ import { sessionOf } from '../session.js';
2
+ const clocks = new WeakMap();
3
+ /**
4
+ * How far the clock of the device the page runs on is ahead of this computer's, in milliseconds.
5
+ * Events are stamped in the device's time. A phone on a cable keeps its own clock: one that was a
6
+ * third of a second behind this computer got every event stamped in its future, read the stamps
7
+ * as "now", and turned three swipes out of thirty into flings.
8
+ *
9
+ * The time is read in a world of its own inside the page, where a test's fake clock or a site's
10
+ * own `Date` does not reach. It is measured again after a minute, and a failed measurement is not
11
+ * kept.
12
+ */
13
+ export function clockAheadOf(page) {
14
+ const known = clocks.get(page);
15
+ if (known && Date.now() - known.at < 60_000)
16
+ return known.ahead;
17
+ const ahead = (async () => {
18
+ const cdp = await sessionOf(page);
19
+ const tree = (await cdp.send('Page.getFrameTree'));
20
+ const world = (await cdp.send('Page.createIsolatedWorld', {
21
+ frameId: tree.frameTree.frame.id,
22
+ worldName: 'playwright-touch-clock',
23
+ }));
24
+ let best = { trip: Infinity, ahead: 0 };
25
+ for (let i = 0; i < 4; i++) {
26
+ const sent = Date.now();
27
+ const answer = (await cdp.send('Runtime.evaluate', {
28
+ expression: 'Date.now()',
29
+ contextId: world.executionContextId,
30
+ returnByValue: true,
31
+ }));
32
+ const back = Date.now();
33
+ // The answer with the shortest round trip was the least delayed, so its middle is the best guess.
34
+ if (back - sent < best.trip)
35
+ best = { trip: back - sent, ahead: answer.result.value - (sent + back) / 2 };
36
+ }
37
+ // On the same computer the difference is the noise of the measurement, and is left at zero.
38
+ return Math.abs(best.ahead) < 20 ? 0 : Math.round(best.ahead);
39
+ })().catch(() => {
40
+ clocks.delete(page);
41
+ return 0;
42
+ });
43
+ clocks.set(page, { at: Date.now(), ahead });
44
+ return ahead;
45
+ }
@@ -0,0 +1,56 @@
1
+ import { type Locator, type Page } from '../session.js';
2
+ import type { DirectedOptions, DragOptions, GestureOptions, PinchOptions, Point, RotateOptions, StrokeOptions } from '../types.js';
3
+ /** Something a finger can land on: an element, or a point in CSS pixels of the viewport. */
4
+ export type Target = Locator | Point;
5
+ /**
6
+ * A hard flick: the finger is still moving at full speed when it lifts, so the content keeps
7
+ * scrolling on its own momentum, as it does under a thumb.
8
+ */
9
+ export declare function fling(target: Page | Locator, options: StrokeOptions | DirectedOptions): Promise<void>;
10
+ /**
11
+ * A controlled swipe: the finger slows to a stop before it lifts, so the content moves by the
12
+ * length of the stroke and no further.
13
+ */
14
+ export declare function swipe(target: Page | Locator, options: StrokeOptions | DirectedOptions): Promise<void>;
15
+ /**
16
+ * A quick touch that the browser turns into a click. Playwright's own `tap` needs a context created
17
+ * with `hasTouch`, which the browser on a real phone is not; this one works in both.
18
+ */
19
+ export declare function tap(target: Target, options?: {
20
+ page?: Page;
21
+ }): Promise<void>;
22
+ /** The browsers of real phones, which `connectAndroid` adds its own to. */
23
+ export declare const realPhones: WeakSet<object>;
24
+ /**
25
+ * Two quick taps on the same place. The second finger comes down while the browser still waits to
26
+ * see whether the first tap was all there was.
27
+ */
28
+ export declare function doubleTap(target: Target, options?: {
29
+ page?: Page;
30
+ }): Promise<void>;
31
+ /** Rests one finger on the target without moving, long enough for a long-press menu or a pick-up. */
32
+ export declare function longPress(target: Target, options?: {
33
+ duration?: number;
34
+ page?: Page;
35
+ }): Promise<void>;
36
+ /**
37
+ * Carries the source to the destination under one finger and lets go at a standstill. With `hold`,
38
+ * the finger rests first, for lists that pick an item up on a long press.
39
+ */
40
+ export declare function drag(start: Target, end: Target, options?: DragOptions & {
41
+ page?: Page;
42
+ }): Promise<void>;
43
+ /**
44
+ * Two fingers spreading (scale above 1) or closing (below 1).
45
+ *
46
+ * On a page, the browser zooms by exactly `scale`, where the page allows zooming. On an element,
47
+ * two fingers travel around its centre, for maps and canvases that read the touches themselves.
48
+ */
49
+ export declare function pinch(target: Page | Locator, options: PinchOptions): Promise<void>;
50
+ /**
51
+ * Two fingers turning around the middle of an element, for maps and pictures that follow the
52
+ * angle between the touches. The fingers keep their distance, so nothing is zoomed on the way.
53
+ */
54
+ export declare function rotate(target: Locator, options: RotateOptions): Promise<void>;
55
+ /** Any gesture, finger by finger. The named gestures cover the usual ones; this is for the rest, a signature or a drawing. */
56
+ export declare function gesture(page: Page, options: GestureOptions): Promise<void>;