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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Adrian Zawadzki
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,613 @@
1
- # Temporary Holding Version
1
+ # playwright-touch
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Real touch for browser tests: tap, double tap, swipe, fling, drag, long press, pinch and rotate,
4
+ plus measurements taken on the device itself.
5
+
6
+ Playwright's own touchscreen can tap and nothing else. This package sends the rest through the
7
+ browser's touch input, so the page receives trusted touch events and the browser itself works out
8
+ scrolling, momentum and zoom.
9
+
10
+ | Chrome, emulated phone | Safari, iPhone simulator |
11
+ | --- | --- |
12
+ | ![A swipe, a fling, a drag and a pinch in an emulated phone](docs/demo.gif) | ![The same gestures in Safari in an iPhone simulator](docs/demo-safari.gif) |
13
+
14
+ | Where | How it gets there | Needs |
15
+ | --- | --- | --- |
16
+ | Chrome, emulated phone | Playwright | nothing else |
17
+ | Chrome on a real Android phone | Playwright over a USB cable | `adb` |
18
+ | Safari in an iPhone simulator | Safari's Web Inspector, spoken by this package | Xcode, and WebDriverAgent or idb |
19
+ | Safari on a real iPhone | The same Web Inspector, over USB | Xcode, and WebDriverAgent signed for the phone |
20
+
21
+ The same script runs in all four.
22
+
23
+ Not affiliated with Microsoft or the Playwright team.
24
+
25
+ ## Install
26
+
27
+ ```sh
28
+ npm install --save-dev playwright-touch
29
+ ```
30
+
31
+ It works with `@playwright/test`, `playwright` and `playwright-core`, version 1.40 or newer, on Node.js 22 or newer. Through
32
+ Playwright it drives Chromium-based browsers only; Safari is reached without Playwright.
33
+
34
+ ## Try it in a minute
35
+
36
+ Save this as `touch.spec.ts` in a project that has `@playwright/test`, and run
37
+ `npx playwright test touch.spec.ts`. It needs no site of its own.
38
+
39
+ ```ts
40
+ import { test, expect, devices } from '@playwright/test';
41
+ import { fling, swipe, tap } from 'playwright-touch';
42
+
43
+ test.use({ ...devices['Pixel 7'] });
44
+
45
+ test('a swipe stops, a fling carries on', async ({ page }) => {
46
+ await page.setContent(`
47
+ <meta name="viewport" content="width=device-width, initial-scale=1">
48
+ <button id="more" style="width:100%;height:64px">More</button>
49
+ <div style="height:20000px;background:linear-gradient(#fff,#99b)"></div>
50
+ <script>document.getElementById('more').onclick = () => document.title = 'tapped'</script>`);
51
+
52
+ await tap(page.locator('#more'));
53
+ await expect(page).toHaveTitle('tapped');
54
+
55
+ await swipe(page, { direction: 'up', distance: 300 });
56
+ await page.waitForTimeout(500);
57
+ const afterSwipe = await page.evaluate(() => scrollY);
58
+ expect(afterSwipe).toBeGreaterThan(250);
59
+ expect(afterSwipe).toBeLessThan(320);
60
+
61
+ await fling(page, { direction: 'up', distance: 300 });
62
+ await page.waitForTimeout(2500);
63
+ expect(await page.evaluate(() => scrollY) - afterSwipe).toBeGreaterThan(600);
64
+ });
65
+ ```
66
+
67
+ ## From the command line
68
+
69
+ ```sh
70
+ npx playwright-touch report https://example.com --tap '#menu'
71
+ npx playwright-touch fits https://example.com https://example.com/pricing
72
+ ```
73
+
74
+ `report` visits the address cold on every device at hand, flings the page, taps the selector and
75
+ writes `report.html` with one column per device: an emulated phone, the Android phone on the cable
76
+ and a booted iPhone simulator. What is not there is skipped with the reason. `--json numbers.json`
77
+ also writes the numbers alone, for a script that compares them with a budget. `--fingers` draws a
78
+ dot where each finger was in the film strips. `--iphone` adds the iPhone on the cable; it is only
79
+ touched when asked for, because it is somebody's own phone.
80
+
81
+ `fits` opens each address cold at 320, 360 and 393 px, flings it three times and names whatever
82
+ makes the page wider than the screen. It exits with 1 if anything does and with 2 if a page could
83
+ not be opened, so it can guard a build. It also counts the links and buttons that are too small for a
84
+ finger, and with `--targets` those fail the check as well.
85
+
86
+ ## Use
87
+
88
+ ```ts
89
+ import { test, devices } from '@playwright/test';
90
+ import { tap, swipe, fling, drag, longPress, pinch } from 'playwright-touch';
91
+
92
+ test.use({ ...devices['Pixel 7'] });
93
+
94
+ test('the feed keeps scrolling after a flick', async ({ page }) => {
95
+ await page.goto('https://example.com/feed');
96
+
97
+ await tap(page.locator('#menu'));
98
+ await swipe(page.locator('#carousel'), { direction: 'left' }); // moves by the stroke, then stops
99
+ await fling(page, { direction: 'up' }); // carries on by momentum
100
+ await drag(page.locator('#card'), page.locator('#slot'), { hold: 400 });
101
+ await longPress(page.locator('#row'));
102
+ await pinch(page, { scale: 2 }); // zooms the page to twice its size
103
+ await pinch(page.locator('#map'), { scale: 0.5 }); // two fingers closing on an element
104
+ });
105
+ ```
106
+
107
+ The address and the selectors above stand for your own. A direction is the way the finger travels.
108
+ Content follows the finger, so a swipe up scrolls the page down.
109
+
110
+ A complete small project with Playwright Test is in [`examples/playwright-test`](examples/playwright-test):
111
+ the config with the switch for exact scroll distances, and four tests.
112
+
113
+ ### As a Playwright Test fixture
114
+
115
+ With Playwright Test the gestures also come as a fixture. Import `test` from `playwright-touch/test`
116
+ and ask for `touch` next to `page`:
117
+
118
+ ```ts
119
+ import { test, expect } from 'playwright-touch/test';
120
+
121
+ test('the carousel moves under a finger', async ({ page, touch }) => {
122
+ await page.goto('https://example.com');
123
+
124
+ await touch.tap(page.locator('#menu'));
125
+ await touch.swipe(page.locator('#carousel'), { direction: 'left' });
126
+ await touch.fling({ direction: 'up' }); // no target: the whole page
127
+ await expect(page.locator('#footer')).toBeInViewport();
128
+ });
129
+ ```
130
+
131
+ Each gesture is a step of its own, so the report and the trace say `touch.swipe left on
132
+ locator('#carousel')` where the test touched the page. A bare point needs no `{ page }` here, the
133
+ fixture knows its page. To see the fingers in a video or a trace, switch the dots on for a file or
134
+ for the whole project:
135
+
136
+ ```ts
137
+ import { test } from 'playwright-touch/test';
138
+
139
+ test.use({ touchOptions: { showFingers: true } });
140
+ ```
141
+
142
+ `test` is Playwright's own, extended. If you have fixtures of your own, join the two with
143
+ `mergeTests` from `@playwright/test`. The functions from `playwright-touch` keep working next to
144
+ the fixture, and they are still the way to use the package without Playwright Test.
145
+
146
+ ## Gestures
147
+
148
+ | Call | What the finger does |
149
+ | --- | --- |
150
+ | `swipe(target, options)` | Slows to a stop before it lifts. The content moves by the length of the stroke and no further. |
151
+ | `fling(target, options)` | Is still at full speed when it lifts. The browser adds the momentum, as it does under a thumb. |
152
+ | `drag(source, destination, { hold, duration })` | Carries the source to the destination and lets go at a standstill. `hold` rests the finger first, for lists that pick an item up on a long press. |
153
+ | `tap(target)` | Touches and lifts, and the browser turns it into a click. Playwright's own `tap` refuses to run on a real phone, because that browser was not created with `hasTouch`. |
154
+ | `doubleTap(target)` | Taps twice in quick succession. The page gets two clicks and a `dblclick`. |
155
+ | `longPress(target, { duration })` | Rests without moving. 700 ms by default. |
156
+ | `pinch(target, { scale, duration })` | On a page, zooms by `scale` relative to the current zoom: exactly in Chrome, and to within a few percent in Safari, where two fingers do it and the result is checked and corrected. On an element, moves two fingers around its centre, for maps and canvases that read the touches themselves. |
157
+ | `rotate(locator, { degrees, duration })` | Turns two fingers around the middle of an element, clockwise for positive degrees, keeping their distance. For maps and pictures that follow the angle between the touches. |
158
+ | `gesture(page, { fingers, duration, hold })` | Anything else, finger by finger: each finger lands on its first point, passes through the others at an even pace and lifts on the last. |
159
+
160
+ `swipe` and `fling` take a page or a locator, and either a direction or two points:
161
+
162
+ ```ts
163
+ await swipe(page, { direction: 'up' }); // 60 % of the viewport
164
+ await swipe(list, { direction: 'up', distance: 300 }); // 300 CSS pixels inside the element
165
+ await fling(page, { from: { x: 200, y: 600 }, to: { x: 200, y: 200 }, duration: 120 });
166
+ ```
167
+
168
+ `tap`, `doubleTap`, `drag` and `longPress` take a locator or a point. With points only, pass the page
169
+ as well: `longPress({ x: 100, y: 200 }, { page })`.
170
+
171
+ `gesture` is for what has no name, a signature or a drawing. Each finger is a list of points in CSS
172
+ pixels of the viewport:
173
+
174
+ ```ts
175
+ await gesture(page, {
176
+ fingers: [[{ x: 60, y: 300 }, { x: 160, y: 220 }, { x: 260, y: 300 }]], // one finger, a bent line
177
+ duration: 600,
178
+ });
179
+ ```
180
+
181
+ ### What a person is doing
182
+
183
+ Four more gestures are named after the task and built from the ones above.
184
+
185
+ | Call | What it does |
186
+ | --- | --- |
187
+ | `swipeUntilVisible(locator, { direction, within, distance, max })` | Swipes until the middle of the element is in the viewport, the way a person scrolls a list to find a row. Resolves to the number of swipes. Fails when the content stops moving or after `max` swipes (10 by default), and says which. |
188
+ | `pullToRefresh(page, { distance, duration })` | Pulls the page down from near its top by half the screen and comes to rest before lifting. |
189
+ | `edgeSwipe(page, { edge, distance, duration, inset })` | Starts `inset` pixels (2 by default) from the `left`, `right`, `top` or `bottom` edge and comes inward, for a side drawer or a sheet. |
190
+ | `twoFingerSwipe(target, { direction, distance, gap, duration })` | Moves two fingers side by side, for maps and embeds that leave one finger to the page. |
191
+
192
+ ```ts
193
+ const swipes = await swipeUntilVisible(page.locator('#order-42')); // down the page
194
+ await swipeUntilVisible(page.locator('#slide-6'), { // inside a carousel
195
+ direction: 'left',
196
+ within: page.locator('#carousel'),
197
+ });
198
+ await pullToRefresh(page);
199
+ await edgeSwipe(page, { edge: 'left' });
200
+ await twoFingerSwipe(page.locator('#map'), { direction: 'down' });
201
+ ```
202
+
203
+ `pullToRefresh` reaches the handlers of the page, which is what a pull-to-refresh written in
204
+ JavaScript listens to. Chrome's own reload on a pull at the top did not fire in Chrome on an Android
205
+ phone: the page saw a pull of 405 px, and of 700 px, and was not reloaded. To test a reload, call
206
+ `page.reload()`.
207
+
208
+ On a real phone the outermost strip of the screen belongs to the system. In Safari on an iPhone a
209
+ stroke that starts 2 px from the left edge goes back in history and the page never sees it, as
210
+ under a real finger; one that starts 6 px in reached the page (iPhone 12 Pro, iOS 17.5). For a
211
+ drawer of your own page pass `inset: 20`. In Chrome on an Android phone the same stroke from 2 px reached the
212
+ page and did not trigger the system's back gesture.
213
+
214
+ `swipeUntilVisible` does not wait for an element that is not on the page yet, so it works with lists
215
+ that add rows while they scroll. All four are on the Playwright Test fixture as well, as
216
+ `touch.swipeUntilVisible(locator)`, `touch.pullToRefresh()`, `touch.edgeSwipe({ edge })` and
217
+ `touch.twoFingerSwipe(locator, { direction })`.
218
+
219
+ ### Seeing the fingers
220
+
221
+ ```ts
222
+ await showTouches(page);
223
+ ```
224
+
225
+ From then on a dot follows every finger, also on the pages gone to later. The dots are drawn from
226
+ the touches the page really gets, so a dot is proof that a finger arrived there. They show in a
227
+ `film`, they take no touches themselves and they are not part of the layout: a swipe moves the page
228
+ just as far with them. Useful when a gesture does not do what was expected, and in recordings.
229
+
230
+ ## A real Android phone
231
+
232
+ ```ts
233
+ import { connectAndroid, fling } from 'playwright-touch';
234
+
235
+ const phone = await connectAndroid();
236
+ const page = await phone.newPage();
237
+ await page.goto('https://example.com');
238
+ await fling(page, { direction: 'up' });
239
+ await phone.close();
240
+ ```
241
+
242
+ The phone needs USB debugging switched on, this computer trusted, and an unlocked screen. `adb`
243
+ has to be on the `PATH`. Nothing has to be changed in Chrome. `connectAndroid()` joins the Chrome
244
+ that is already running and opens tabs of its own. The owner's tabs, the ones open before and any
245
+ they open meanwhile, are never shown to the test: they are not listed, cannot be attached to by
246
+ the test, and cannot hold the connection up. When the phone is missing,
247
+ untrusted, asleep or locked, it says which one instead of hanging.
248
+
249
+ ## Safari in an iPhone simulator
250
+
251
+ There is no Playwright page here, because Playwright cannot join Safari on iOS. The package talks
252
+ to Safari's Web Inspector itself and touches the screen through the simulator, so the page gets
253
+ real touches, scrolling and momentum.
254
+
255
+ ```ts
256
+ import { connectSimulator } from 'playwright-touch';
257
+
258
+ const phone = await connectSimulator(); // a booted simulator, or { udid } to boot one
259
+ await phone.page.goto('https://en.wikipedia.org/wiki/Touchscreen');
260
+ await phone.page.fling({ direction: 'up' });
261
+ console.log(await phone.page.evaluate(() => scrollY)); // a few thousand pixels down
262
+ await phone.page.tap('#firstHeading');
263
+ await phone.close();
264
+ ```
265
+
266
+ The measurements work here too:
267
+
268
+ ```ts
269
+ const loaded = await phone.page.coldLoad('https://example.com'); // no HTTP cache
270
+ const flung = await phone.page.film(() => phone.page.fling({ direction: 'up' }));
271
+ writeReport('report.html', { title: 'Safari', url: 'https://example.com', device: phone.model, vitals: await phone.page.vitals(), films: [{ label: 'A fling', film: flung }] });
272
+ ```
273
+
274
+ Safari reports the first byte, the paints and interactions. It does not report layout shift or
275
+ long tasks, so those come back as `null` and the report says "not measured" instead of showing a
276
+ zero.
277
+
278
+ It needs Xcode. Targets are CSS selectors or points. Fingers reach the screen in one of two ways:
279
+
280
+ | | With WebDriverAgent running | With only [idb](https://fbidb.io) on the `PATH` |
281
+ | --- | --- | --- |
282
+ | `tap`, `doubleTap`, `longPress` | yes | yes |
283
+ | `fling` | a 300 px fling carried the page about 1800 to 1940 px | 1030 to 1260 px |
284
+ | `swipe` | stops with the finger: a 300 px swipe moves the page 285 px, as in Chrome | coasts: a 300 px swipe moved the page 408 to 431 px |
285
+ | `drag` with `hold` | yes | no rest before the move |
286
+ | `pinch` | yes, two fingers | no |
287
+ | `rotate` | yes, two fingers | no |
288
+ | `gesture` | yes | one finger in a straight line |
289
+ | `film` | about 30 pictures a second | a picture whenever the screen changes |
290
+
291
+ [WebDriverAgent](https://github.com/appium/WebDriverAgent) is the Appium project's helper app. It
292
+ is used when it answers on `http://127.0.0.1:8100` (or at the `wda` option), and idb is the
293
+ fallback. One command boots a simulator without its window, builds WebDriverAgent the first time
294
+ and keeps it running until Ctrl-C:
295
+
296
+ ```sh
297
+ git clone --depth 1 https://github.com/appium/WebDriverAgent.git
298
+ npx playwright-touch simulator --wda ./WebDriverAgent
299
+ ```
300
+
301
+ `node bench/stress-safari.ts` repeats each gesture thirty times through WebDriverAgent. Tap, drag
302
+ with a rest, pinch on an element and swipe came out the same in every run: a 300 px swipe moved the
303
+ page 285 px thirty times out of thirty. A 300 px fling carried it between about 1800 and 1940 px, and a
304
+ page asked to zoom to twice its size ended between 2.03 and 2.07.
305
+
306
+ Connecting again within a few seconds of the last disconnect can take a quarter of a minute: the
307
+ simulator's inspector goes quiet for a while after a short visit, and the package waits it out. A
308
+ new connection takes over the tab the last one left when that tab is still in front, so tabs do
309
+ not pile up in Safari.
310
+
311
+ Numbers measured in a simulator say nothing about a real iPhone.
312
+
313
+ Safari's own WebDriver was tried first and does not do this job: in the simulator a touch stroke
314
+ sent through it never returns, and while its session is open the page receives no real touches.
315
+
316
+ ## Measuring on the device
317
+
318
+ The same connection can tell how the page behaves on that device, on its own processor and network.
319
+
320
+ ```ts
321
+ import { connectAndroid, coldLoad, film, fling, watchVitals, writeReport } from 'playwright-touch';
322
+
323
+ const phone = await connectAndroid();
324
+ const page = await phone.newPage();
325
+
326
+ const loaded = await coldLoad(page, 'https://example.com'); // no HTTP cache, no service worker
327
+ const vitals = await watchVitals(page);
328
+ const flung = await film(page, () => fling(page, { direction: 'up' }), { settle: 2500 });
329
+
330
+ writeReport('report.html', {
331
+ title: 'A cold visit and a fling',
332
+ url: 'https://example.com',
333
+ device: phone.model,
334
+ vitals: await vitals.read(),
335
+ films: [{ label: 'A hard fling', film: flung }],
336
+ });
337
+ await phone.close();
338
+ ```
339
+
340
+ | Call | What it gives |
341
+ | --- | --- |
342
+ | `coldLoad(page, url)` | Opens the address without the HTTP cache, and in Chrome without a service worker, and returns the metrics. Nothing is deleted, so the owner's cache, cookies and sign-ins stay as they were. |
343
+ | `watchVitals(page)` | Collects first byte, first and largest paint, layout shift, the slowest interaction and long tasks, in the page itself. Read it whenever needed, for example after a gesture. |
344
+ | `film(page, action)` | Records the frames the screen showed while the action ran and settled, each with its time. It also says for how long the page kept scrolling after the first touch, wheel turn or key, and the longest pause between two frames in that time, which is how a stall under a fling shows up. Scrolling inside a frame, or done by a script, is not seen. |
345
+ | `findOverflow(page)` | Names what makes the page wider than the screen, the cause of sideways scrolling on a phone. Empty when the page fits. |
346
+ | `findSmallTargets(page, { min })` | Names the links, buttons and form controls too small to hit with a finger: under 24 CSS pixels either way without that much room around them, the measure in WCAG 2.2. Links inside a sentence are left out. `min: 44` checks against the size Apple recommends. |
347
+ | `writeReport(path, report)` | Writes one self-contained HTML file with the metrics, rated against the published thresholds, and the film strips. |
348
+
349
+ All of this also works in an emulated phone, where it is useful for tests but says nothing about
350
+ real hardware.
351
+
352
+ A cold load cannot close connections the browser already holds open, so a second cold load of the
353
+ same site is faster than the first. In one session on the test phone the first visit painted after
354
+ 4.0 s and the next three after 0.4 to 0.6 s.
355
+
356
+ ## One script, two browsers
357
+
358
+ The gestures and measurements take Safari's page as well, so a script typed against `SharedPage`
359
+ runs unchanged in Chrome and in Safari:
360
+
361
+ ```ts
362
+ import { coldLoad, fling, tap, watchVitals, type SharedPage } from 'playwright-touch';
363
+
364
+ async function visit(page: SharedPage, url: string) {
365
+ const loaded = await coldLoad(page, url);
366
+ const vitals = await watchVitals(page);
367
+ await tap(page.locator('#menu'));
368
+ await fling(page, { direction: 'up' });
369
+ return { loaded, after: await vitals.read(), top: await page.evaluate(() => scrollY) };
370
+ }
371
+
372
+ await visit(await androidPhone.newPage(), url); // Chrome, through Playwright
373
+ await visit(simulator.page, url); // Safari, through the Web Inspector
374
+ ```
375
+
376
+ `writeComparison` puts such visits side by side in one report, one column per device. The `report`
377
+ command does exactly that.
378
+
379
+ `SharedPage` is what the two have in common: `goto`, `evaluate` with a function, and `locator` with
380
+ a CSS selector.
381
+
382
+ ## Why momentum is worth getting right
383
+
384
+ A helper that sends touch moves without timestamps leaves the timing to the test machine. The
385
+ browser measures the finger's speed from that timing, so the same stroke flings a different
386
+ distance from run to run, and more so on a busy machine. This package stamps every touch event on
387
+ an even 60 Hz clock, which makes the browser see the same finger speed every time.
388
+
389
+ `node bench/steady.ts` measures it: the same 300 px fling, twelve runs each, on an idle computer
390
+ and with ten processes keeping the processor busy. On a 14-core MacBook, how far the page ended up:
391
+
392
+ | | Idle computer | Busy computer |
393
+ | --- | --- | --- |
394
+ | This package | 873 to 876 px | 852 to 894 px |
395
+ | Hand-written, no timestamps, three rounds | 422 to 580 px | 285 to 648 px |
396
+
397
+ The same fling on a real phone (`node bench/steady.ts --android`, a Motorola edge 30 fusion, twelve
398
+ runs each): this package ended between 1300 and 1316 px, the hand-written helper between 292 and
399
+ 706 px over three rounds. A 300 px swipe on that phone moved the page 292 px in 39 runs out of 40.
400
+
401
+ A phone keeps its own clock, and the events are stamped in its time, not this computer's. The test
402
+ phone was a third of a second behind; stamped in the computer's time, three swipes in thirty turned
403
+ into flings.
404
+
405
+ ### Exact to the pixel
406
+
407
+ `node bench/stress.ts` repeats every gesture a few hundred times. Tap, drag, long press and pinch
408
+ came out the same in every run, idle or busy. A 300 px swipe moved the page 285 px in 200 runs out
409
+ of 200 on an idle computer, and in 165 out of 200 with the processor kept busy; the other 35 ended
410
+ 15 px short.
411
+
412
+ Those 15 px are Chromium's doing: it smooths scrolling between touch events by guessing where the
413
+ finger is at each frame, and on a busy machine the guess can be off. One browser switch turns the
414
+ smoothing off, and then the swipe ends at 285 px in 150 runs out of 150 under the same load.
415
+
416
+ Chromium honours only the last `--disable-features` switch it is given, and Playwright passes one
417
+ of its own. So the switch has to carry Playwright's list as well, and the package works it out for
418
+ the Playwright that is installed:
419
+
420
+ ```sh
421
+ npx playwright-touch steady-args
422
+ # --disable-features=AvoidUnnecessaryBeforeUnloadCheckSync,...,ResamplingScrollEvents
423
+ ```
424
+
425
+ ```ts
426
+ export default defineConfig({ use: { launchOptions: { args: ['--disable-features=...'] } } });
427
+ ```
428
+
429
+ In code that launches the browser itself, `await steadyScrollArgs()` returns the same. Print it
430
+ again after upgrading Playwright. Use it when a test asserts an exact scroll position. It does not
431
+ apply to a browser on a phone, where the point is to see what the phone really does.
432
+
433
+ ## Safari on a real iPhone
434
+
435
+ The same page object, on an iPhone connected by cable:
436
+
437
+ ```ts
438
+ import { connectIphone } from 'playwright-touch';
439
+
440
+ const phone = await connectIphone(); // the iPhone on the cable; { udid } when there are several
441
+ await phone.page.goto('https://en.wikipedia.org/wiki/Touchscreen');
442
+ await phone.page.fling({ direction: 'up' });
443
+ console.log(phone.model, phone.system, await phone.page.evaluate(() => scrollY));
444
+ await phone.close();
445
+ ```
446
+
447
+ The page is read through the Web Inspector, which the phone offers over USB to a Mac its owner
448
+ trusted, and touched through WebDriverAgent running on the phone. The package's own traffic to both
449
+ goes over the cable; it speaks to macOS's own `usbmuxd` and needs no other tool. Before the first
450
+ run:
451
+
452
+ 1. Connect the phone, unlock it and choose Trust.
453
+ 2. Switch on Settings, Privacy & Security, Developer Mode.
454
+ 3. Switch on Settings, Safari, Advanced, Web Inspector, then close Safari and open it again.
455
+ 4. Add an Apple Account in Xcode (Settings, Apple Accounts; a free one works, and the app then
456
+ expires after seven days) and create an Apple Development certificate there.
457
+
458
+ One command then builds WebDriverAgent for the phone, signs it and keeps it running until Ctrl-C:
459
+
460
+ ```sh
461
+ git clone --depth 1 https://github.com/appium/WebDriverAgent.git
462
+ npx playwright-touch iphone --wda ./WebDriverAgent
463
+ ```
464
+
465
+ The first time, the phone asks to trust the developer in Settings, General, VPN & Device
466
+ Management.
467
+
468
+ ### What it does on a person's own phone
469
+
470
+ - **Only its own tab.** The package works in a tab it opened itself. When it disconnects, the tab
471
+ goes back to its start page, and next time only a Safari tab on that start page is taken over.
472
+ The owner's other tabs are listed by the Web Inspector with their titles and addresses, which
473
+ cannot be avoided, but none of them is attached to or read.
474
+ - **No finger outside Safari.** Before every gesture the phone is asked which app is in front. When
475
+ it is not Safari, or the page does not answer, the gesture fails and nothing is touched.
476
+ - **Safari is not restarted unless you say so.** Safari does not always announce a new tab while it
477
+ is running. `connectIphone()` then fails and says so. With `connectIphone({ restartSafari: true })`
478
+ Safari is closed and opened again once; its tabs come back, but their pages reload, so text typed
479
+ into a form or a video that was playing is lost. `phone.restartedSafari` tells whether it
480
+ happened.
481
+ - **A Trust question may appear.** When the phone no longer knows the Mac, connecting puts the
482
+ Trust question on its screen. Nothing happens until its owner answers.
483
+ - **The film shows the whole screen.** A film, and the film strips of `report --iphone`, are
484
+ pictures of the phone's screen. A notification that arrives while one is recorded is in it. Turn
485
+ on a Focus mode before recording something to share.
486
+ - **WebDriverAgent is open while it runs.** It is the Appium project's app, and it accepts commands
487
+ and serves the screen to whoever can reach its ports 8100 and 9100. The `iphone` command starts
488
+ it on the phone's loopback address, so other devices on the phone's Wi-Fi cannot reach it
489
+ (checked: it stopped answering over Wi-Fi and went on answering over the cable). Pages opened on
490
+ the phone itself still can, and while connected the package offers both ports on this
491
+ computer's loopback address. Stop the `iphone` command when you are not testing. Started by hand
492
+ without `TEST_RUNNER_USE_IP=127.0.0.1`, WebDriverAgent listens on the phone's Wi-Fi as well.
493
+ - **Signing registers the phone.** The `iphone` command signs with the team of the Apple
494
+ Development certificate in the keychain and prints which one. With certificates of several teams
495
+ it asks for `--team` instead of choosing.
496
+
497
+ When something is missing, the error says which: no phone on the cable or several, a phone that
498
+ does not trust the Mac, a locked phone, Web Inspector switched off, or WebDriverAgent not running.
499
+
500
+ Measured by hand on an iPhone 12 Pro with iOS 17.5.1, not by a test in this repository: a 300 px
501
+ swipe moved the page 275 or 281 px in twelve runs out of twelve, a 300 px fling carried it between
502
+ 1753 and 1872 px in twenty-eight runs, a pinch asked for 1.8 was read by the page as 1.80 and a
503
+ rotate by 90 degrees as 90.0.
504
+
505
+ ## WebKit and Firefox
506
+
507
+ Playwright can send touch input only to Chromium. A project that also runs its tests in WebKit and
508
+ Firefox can keep the same test: there the package sends each gesture to the page as pointer events,
509
+ touch events and, after a tap, a click, all made by script.
510
+
511
+ | | Chromium | WebKit, Firefox |
512
+ | --- | --- | --- |
513
+ | Handlers on the page (carousels, maps, drag and drop, gesture recognisers) | run | run |
514
+ | A tap clicks, a double tap gives `dblclick` | yes | yes |
515
+ | The page scrolls under the finger | yes | no |
516
+ | A fling coasts on | yes | no |
517
+ | A pinch zooms the page | yes | no, and `pinch(page, …)` says so |
518
+ | Events are trusted (`isTrusted`) | yes | no |
519
+
520
+ So in WebKit and Firefox a test can check what your own code does with a gesture, and cannot check
521
+ what the browser does. The first gesture in each of them prints a line saying this;
522
+ `PLAYWRIGHT_TOUCH_QUIET=1` hides it. `isSynthetic(page)` tells a test which kind of page it has, for
523
+ an assertion that only holds with real input:
524
+
525
+ ```ts
526
+ await swipe(page, { direction: 'up', distance: 300 });
527
+ if (!isSynthetic(page)) expect(await page.evaluate(() => scrollY)).toBe(285);
528
+ ```
529
+
530
+ This is WebKit as Playwright runs it on a desktop. Safari on an iPhone or in the simulator gets real
531
+ fingers, as described above.
532
+
533
+ ## Works with
534
+
535
+ The gestures are tested against the libraries people ask about first. Each test loads the library's
536
+ own build into an emulated phone and checks what the library made of the touch.
537
+
538
+ | Library | Version | What is checked |
539
+ | --- | --- | --- |
540
+ | [Swiper](https://swiperjs.com) | 14.5 | `swipe` and `fling` move one slide, a swipe back returns |
541
+ | [Embla Carousel](https://www.embla-carousel.com) | 8.6 | `swipe` selects the next slide, `fling` the previous |
542
+ | [Leaflet](https://leafletjs.com) | 1.9 | `swipe` pans the map, `pinch` to twice the distance zooms one level |
543
+ | [Hammer.js](https://hammerjs.github.io) | 2.0 | `swipeleft`, `pinch` with its scale, `rotate` with its angle, `press` and `doubletap` are recognised |
544
+
545
+ These run in emulated Chrome with every `npm test`. Swiper, Embla and Hammer.js are also run in
546
+ WebKit and Firefox, with events made by script. A carousel reacts only when the finger lands on
547
+ it: a stroke across a container that is taller than its slides can start on empty space, and Swiper
548
+ ignores that, under a real finger too. Aim at the slides.
549
+
550
+ ## Checked on
551
+
552
+ - An emulated phone in desktop Chrome and in the Chromium that Playwright downloads (`npm test`).
553
+ - Safari in an iPhone 17 simulator with iOS 26.5, through WebDriverAgent 16.15.3 and through idb
554
+ (`npm test` with a simulator booted).
555
+ - Safari on an iPhone 12 Pro with iOS 17.5.1 over USB, through WebDriverAgent 16.15.3: tap, double
556
+ tap, drag, pinch, rotate and swipe by `IPHONE=1 node --test test/iphone.test.ts`; long press,
557
+ fling, a cold load, a film and `report --iphone` by hand.
558
+ - Chrome 157 and 158 on a Motorola edge 30 fusion with Android 14, over adb: gestures, cold loads, metrics,
559
+ films, the overflow check and the `report` command together with the other two. The same fling carries about half as far again on the phone as in emulation.
560
+
561
+ ## Known limits
562
+
563
+ - On a real iPhone the benchmarks and `idb` are not available; the gestures, the measurements and
564
+ `report --iphone` are. It was checked on one phone with iOS 17.5.1. Newer systems may
565
+ offer the Web Inspector only through a tunnel this package does not open.
566
+ - A tab in the background of Safari on a phone does not answer; the tab has to stay in front.
567
+ - On a phone whose default browser is not Safari the tab is still opened in Safari. A phone with
568
+ iOS before 16 was not tried.
569
+ - Through Playwright, real touch input exists only in Chromium. In WebKit and Firefox the gestures
570
+ are events made by script, which reach the page's handlers and nothing else. See
571
+ [WebKit and Firefox](#webkit-and-firefox).
572
+ - Chrome on a phone zooms on a double tap unless the page is laid out for phones, and in a tab no
573
+ finger has scrolled yet it does not know that the page is. The first `doubleTap` there is taken
574
+ for a zoom. `doubleTap` notices, undoes the zoom and taps twice again, so the page gets its two
575
+ clicks and its `dblclick`, after four touches instead of two. A page without a viewport tag
576
+ zooms, as it does under a thumb, and gets no click.
577
+ - In Chrome on a phone the swipe that hides the address bar moves the page by the height of the bar
578
+ less: 236 px instead of 292 px for a 300 px swipe on the phone this was checked on. A thumb gets
579
+ the same.
580
+ - The native long-press menu does not open in Chrome, in emulation or on the phone. `longPress`
581
+ holds the finger down, which is enough for pages that time the press themselves.
582
+ - Desktop Chrome on Linux does not pinch-zoom pages, so `pinch(page)` fails there with a message
583
+ that says so. Pinch on an element works everywhere.
584
+ - In Safari, two fingers closing on a page that cannot get smaller open the tab overview. `pinch`
585
+ on a page therefore never asks for less than the page allows, and says so when the page is
586
+ already at its smallest. An element that does not handle two fingers itself passes them on to
587
+ the page; when that opens the overview, `pinch` fails with a message that says so.
588
+ - `tap`, `longPress` and the start of a `drag` refuse an element that something else covers, such
589
+ as a cookie bar or a sticky header, and name what is in the way. Close it or scroll first.
590
+ - A page that is not on screen cannot be touched. A gesture on a hidden tab or behind a lock screen
591
+ fails with a message that says so.
592
+ - A cold load cannot close connections the browser already holds open.
593
+ - Safari reports no layout shift and no long tasks.
594
+
595
+ ## Working on it
596
+
597
+ ```sh
598
+ npm install
599
+ npm test # emulated tests; phone and simulator tests run when one is attached
600
+ npm run lint # formatting, checked on every pull request; npm run format fixes it
601
+ node bench/steady.ts # how steady a fling is, idle and under load
602
+ node demo/android-playground.ts # every gesture on the Android phone on the cable
603
+ node demo/record.ts # re-records docs/demo.gif (needs ffmpeg)
604
+ node demo/record-safari.ts # re-records docs/demo-safari.gif (needs ffmpeg and WebDriverAgent)
605
+ ```
606
+
607
+ The tests need Chrome installed; `PLAYWRIGHT_TOUCH_BUNDLED=1` runs them in the browser Playwright
608
+ downloads instead. With an iPhone simulator booted they also cover Safari, and
609
+ `PLAYWRIGHT_TOUCH_IDB=1` runs those through idb instead of WebDriverAgent.
610
+
611
+ ## Licence
612
+
613
+ MIT
@@ -0,0 +1,26 @@
1
+ import type { Browser, BrowserContext, Page } from 'playwright-core';
2
+ /** Chrome on an Android phone, joined through `connectAndroid()`. */
3
+ export interface AndroidPhone {
4
+ /** Model name the phone reports, for logs. */
5
+ model: string;
6
+ browser: Browser;
7
+ /** Chrome's own context on the phone. The tabs that were already open are not in it. */
8
+ context: BrowserContext;
9
+ /** Opens a tab of our own. The tabs already open on the phone are left alone. */
10
+ newPage(): Promise<Page>;
11
+ /** Closes the tabs opened through `newPage`, disconnects and removes the port forward. Chrome stays open. */
12
+ close(): Promise<void>;
13
+ }
14
+ /**
15
+ * What the screen is doing, read from `dumpsys power` and `dumpsys window`: a page is only drawn,
16
+ * and so can only be touched, on a screen that is on and past the lock screen.
17
+ */
18
+ export declare function phoneState(power: string, window: string): 'ready' | 'screen off' | 'locked';
19
+ /**
20
+ * Joins Chrome on an Android phone connected over USB (or any device `adb devices` lists) and
21
+ * returns it as a Playwright browser. Needs USB debugging switched on and the computer trusted;
22
+ * nothing has to be changed in Chrome.
23
+ */
24
+ export declare function connectAndroid(options?: {
25
+ serial?: string;
26
+ }): Promise<AndroidPhone>;