playwright-touch 0.0.0-stage → 0.1.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 (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +495 -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 +485 -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 +108 -0
  14. package/dist/index.js +147 -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/polyline.d.ts +10 -0
  44. package/dist/polyline.js +38 -0
  45. package/dist/report.d.ts +46 -0
  46. package/dist/report.js +118 -0
  47. package/dist/session.d.ts +35 -0
  48. package/dist/session.js +23 -0
  49. package/dist/show.d.ts +13 -0
  50. package/dist/show.js +51 -0
  51. package/dist/types.d.ts +58 -0
  52. package/dist/types.js +2 -0
  53. package/package.json +68 -4
@@ -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>;
@@ -0,0 +1,485 @@
1
+ // The gestures in Chromium, through the browser's own touch input.
2
+ import { sessionOf } from '../session.js';
3
+ import { along, arc } from '../polyline.js';
4
+ import { clockAheadOf } from './clock.js';
5
+ const FRAME_MS = 1000 / 60;
6
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
7
+ const linear = (t) => t;
8
+ const easeOut = (t) => 1 - (1 - t) ** 3;
9
+ const easeInOut = (t) => (t < 0.5 ? 4 * t ** 3 : 1 - (-2 * t + 2) ** 3 / 2);
10
+ const UNIT = {
11
+ up: { x: 0, y: -1 },
12
+ down: { x: 0, y: 1 },
13
+ left: { x: -1, y: 0 },
14
+ right: { x: 1, y: 0 },
15
+ };
16
+ const isLocator = (target) => typeof target.boundingBox === 'function' && typeof target.page === 'function';
17
+ const isPage = (target) => typeof target.viewportSize === 'function';
18
+ /**
19
+ * The size of what the page lays itself out in, in the page's own pixels. On a page without a
20
+ * viewport tag that is 980 px wide on a phone, not the phone's 393, and touch positions count in
21
+ * these pixels too.
22
+ */
23
+ const screenOf = (page) => page.evaluate(() => ({ width: innerWidth, height: innerHeight }));
24
+ /** The rectangle a target covers in the viewport, after scrolling an element into view. */
25
+ async function boxOf(page, target) {
26
+ if (isPage(target)) {
27
+ return { x: 0, y: 0, ...(await screenOf(target)) };
28
+ }
29
+ if (isLocator(target)) {
30
+ await target.scrollIntoViewIfNeeded();
31
+ return visiblePart(page, target);
32
+ }
33
+ return { x: target.x, y: target.y, width: 0, height: 0 };
34
+ }
35
+ /**
36
+ * The part of an element that is on screen, without scrolling. An element taller than the screen
37
+ * is only touched where it can be seen, so its middle is the middle of that part.
38
+ */
39
+ async function visiblePart(page, target) {
40
+ const whole = await target.boundingBox();
41
+ if (!whole)
42
+ throw new Error('playwright-touch: the element is not visible, so there is nothing to touch.');
43
+ // An element in a frame is also cut off by the frame's own edges, which only the frame knows.
44
+ // What it shows of the element is measured there and carried over to the page's coordinates.
45
+ const shown = await target.evaluate((element) => {
46
+ const box = element.getBoundingClientRect();
47
+ return {
48
+ left: Math.max(box.left, 0) - box.left,
49
+ top: Math.max(box.top, 0) - box.top,
50
+ right: Math.min(box.right, innerWidth) - box.left,
51
+ bottom: Math.min(box.bottom, innerHeight) - box.top,
52
+ };
53
+ });
54
+ const box = {
55
+ x: whole.x + shown.left,
56
+ y: whole.y + shown.top,
57
+ width: shown.right - shown.left,
58
+ height: shown.bottom - shown.top,
59
+ };
60
+ if (box.width <= 0 || box.height <= 0)
61
+ throw new Error('playwright-touch: the element is not on screen, so there is nothing to touch.');
62
+ const screen = await screenOf(page);
63
+ const left = Math.max(box.x, 0);
64
+ const top = Math.max(box.y, 0);
65
+ const right = Math.min(box.x + box.width, screen.width);
66
+ const bottom = Math.min(box.y + box.height, screen.height);
67
+ if (right <= left || bottom <= top)
68
+ throw new Error('playwright-touch: the element is not on screen, so there is nothing to touch.');
69
+ return { x: left, y: top, width: right - left, height: bottom - top };
70
+ }
71
+ /**
72
+ * Where a finger should land on a target, after checking that the target is what it would touch.
73
+ * A cookie bar or a sticky header over the element would take the touch instead, and the test
74
+ * would go on as if the element had been touched.
75
+ */
76
+ async function landingOn(page, target) {
77
+ const at = centre(await boxOf(page, target));
78
+ if (!isLocator(target))
79
+ return at;
80
+ const inTheWay = await target.evaluate((element) => {
81
+ const box = element.getBoundingClientRect();
82
+ const x = (Math.max(box.left, 0) + Math.min(box.right, innerWidth)) / 2;
83
+ const y = (Math.max(box.top, 0) + Math.min(box.bottom, innerHeight)) / 2;
84
+ let hit = document.elementFromPoint(x, y);
85
+ // What is hit may sit inside a shadow tree, one level per look.
86
+ while (hit?.shadowRoot) {
87
+ const inner = hit.shadowRoot.elementFromPoint(x, y);
88
+ if (!inner || inner === hit)
89
+ break;
90
+ hit = inner;
91
+ }
92
+ if (!hit)
93
+ return 'nothing at all';
94
+ // The target itself or something inside it counts as the target.
95
+ for (let node = hit; node; node = node.parentNode ?? node.host ?? null)
96
+ if (node === element)
97
+ return null;
98
+ // Something the target sits inside counts only when the target lets touches through on purpose.
99
+ // Otherwise the target is hidden or clipped there, and its parent would take the touch.
100
+ if (getComputedStyle(element).pointerEvents === 'none')
101
+ for (let node = element; node; node = node.parentNode ?? node.host ?? null)
102
+ if (node === hit)
103
+ return null;
104
+ const classes = typeof hit.className === 'string' && hit.className.trim()
105
+ ? '.' + hit.className.trim().split(/\s+/).slice(0, 2).join('.')
106
+ : '';
107
+ return hit.tagName.toLowerCase() + (hit.id ? '#' + hit.id : '') + classes;
108
+ });
109
+ if (inTheWay)
110
+ throw new Error(`playwright-touch: the element is covered by ${inTheWay}, which would take the touch instead.`);
111
+ // An element inside a frame can also be covered by something in the page around the frame, which
112
+ // the frame itself cannot see: a bar of the page, or of a frame in between when frames are
113
+ // nested. So the way up is walked one frame at a time, and at the place the finger lands each
114
+ // page on the way must show the frame below it. A page from another site cannot be looked into
115
+ // from here. From there on the frames are marked for a moment instead, and the outermost page is
116
+ // asked whether it shows a marked frame at that place; a frame from another site cannot be
117
+ // marked either, and there any frame at that place is taken for the right one.
118
+ const mark = `touch${Date.now()}${Math.round(Math.random() * 1e6)}`;
119
+ const framed = await target.evaluate((element, { name, landing }) => {
120
+ if (window === window.top)
121
+ return { framed: false, marked: false, covered: null };
122
+ // The frames on the way up, as far as they can be seen from here.
123
+ const holders = [];
124
+ let complete = true;
125
+ try {
126
+ for (let view = window; view !== view.top; view = view.parent) {
127
+ const holder = view.frameElement;
128
+ if (!holder) {
129
+ complete = false;
130
+ break;
131
+ }
132
+ holders.push(holder);
133
+ }
134
+ }
135
+ catch {
136
+ complete = false;
137
+ }
138
+ // Where the inside of a frame lies in the page that holds it: past its border and padding,
139
+ // and scaled if the frame is.
140
+ const placing = (holder) => {
141
+ const around = holder.getBoundingClientRect();
142
+ const style = getComputedStyle(holder);
143
+ return {
144
+ left: around.left,
145
+ top: around.top,
146
+ inLeft: holder.clientLeft + (parseFloat(style.paddingLeft) || 0),
147
+ inTop: holder.clientTop + (parseFloat(style.paddingTop) || 0),
148
+ scaleX: holder.offsetWidth ? around.width / holder.offsetWidth : 1,
149
+ scaleY: holder.offsetHeight ? around.height / holder.offsetHeight : 1,
150
+ };
151
+ };
152
+ // The place to follow is the one the finger lands on. It is known in the outermost page, so
153
+ // with all frames in sight it is brought down from there; otherwise the middle of what the
154
+ // frame shows of the element has to do.
155
+ const box = element.getBoundingClientRect();
156
+ let point = {
157
+ x: (Math.max(box.left, 0) + Math.min(box.right, innerWidth)) / 2,
158
+ y: (Math.max(box.top, 0) + Math.min(box.bottom, innerHeight)) / 2,
159
+ };
160
+ if (complete) {
161
+ point = landing;
162
+ for (const holder of holders.slice().reverse()) {
163
+ const at = placing(holder);
164
+ point = { x: (point.x - at.left) / at.scaleX - at.inLeft, y: (point.y - at.top) / at.scaleY - at.inTop };
165
+ }
166
+ }
167
+ for (const holder of holders) {
168
+ holder.__playwrightTouchMark = name;
169
+ const at = placing(holder);
170
+ point = { x: at.left + (at.inLeft + point.x) * at.scaleX, y: at.top + (at.inTop + point.y) * at.scaleY };
171
+ let hit = holder.ownerDocument.elementFromPoint(point.x, point.y);
172
+ while (hit?.shadowRoot) {
173
+ const inner = hit.shadowRoot.elementFromPoint(point.x, point.y);
174
+ if (!inner || inner === hit)
175
+ break;
176
+ hit = inner;
177
+ }
178
+ if (hit !== holder) {
179
+ const what = hit ? hit.tagName.toLowerCase() + (hit.id ? '#' + hit.id : '') : 'nothing at all';
180
+ return { framed: true, marked: complete, covered: what };
181
+ }
182
+ }
183
+ return { framed: true, marked: complete, covered: null };
184
+ }, { name: mark, landing: at });
185
+ if (framed.covered)
186
+ throw new Error(`playwright-touch: the element is in a frame that ${framed.covered} covers at that place, which would take the touch instead.`);
187
+ if (framed.framed) {
188
+ const outside = await page.evaluate(({ point, mark: name }) => {
189
+ let hit = document.elementFromPoint(point.x, point.y);
190
+ // The frame may itself sit inside a web component.
191
+ while (hit?.shadowRoot) {
192
+ const inner = hit.shadowRoot.elementFromPoint(point.x, point.y);
193
+ if (!inner || inner === hit)
194
+ break;
195
+ hit = inner;
196
+ }
197
+ if (!hit)
198
+ return 'nothing at all';
199
+ const isFrame = hit.tagName === 'IFRAME' || hit.tagName === 'FRAME';
200
+ if (isFrame && (name === null || hit.__playwrightTouchMark === name))
201
+ return null;
202
+ return hit.tagName.toLowerCase() + (hit.id ? '#' + hit.id : '');
203
+ }, { point: at, mark: framed.marked ? mark : null });
204
+ if (outside)
205
+ throw new Error(`playwright-touch: the element is in a frame that ${outside} covers at that place, which would take the touch instead.`);
206
+ }
207
+ return at;
208
+ }
209
+ const centre = (box) => ({
210
+ x: box.x + box.width / 2,
211
+ y: box.y + box.height / 2,
212
+ });
213
+ const pageOf = (target, fallback) => {
214
+ if (isPage(target))
215
+ return target;
216
+ if (isLocator(target))
217
+ return target.page();
218
+ if (fallback)
219
+ return fallback;
220
+ throw new Error('playwright-touch: a point needs a page to belong to.');
221
+ };
222
+ /**
223
+ * Puts the fingers down, moves them a frame at a time and lifts them, through the browser's own
224
+ * touch input. Every event carries its own timestamp on an even 60 Hz clock: the browser works out
225
+ * the speed of the finger from those, so the momentum does not depend on how busy this process is.
226
+ */
227
+ async function perform(page, { fingers, duration, ease, holdBefore = 0, holdAfter = 0 }) {
228
+ // A page that is not on screen (a locked phone, a tab behind another) draws no frames, and the
229
+ // browser never answers the first touch: say so instead of waiting for ever.
230
+ if ((await page.evaluate(() => document.visibilityState)) !== 'visible') {
231
+ throw new Error('playwright-touch: the page is not on screen, so it cannot be touched. Unlock the phone, or bring the tab to the front.');
232
+ }
233
+ const cdp = await sessionOf(page);
234
+ const points = (k) => fingers.map((path, id) => ({ ...round(path(k)), id, radiusX: 8, radiusY: 8, force: 1 }));
235
+ // Every event is stamped on an even 60 Hz clock, and sent when that clock says, as far as the
236
+ // machine allows. The even stamps are what make a fling repeatable: the browser reads the
237
+ // finger's speed from them. Sending on time matters as well. The first version slept a full
238
+ // frame after every send, which stretched a 400 ms gesture to almost twice that on the wire, and
239
+ // the browser, which smooths scrolling between events by their times, then dropped 15 px of a
240
+ // swipe in about three runs out of a hundred. (Stamping each event with the time it was really
241
+ // sent was tried too and is worse: a swipe then overshoots by 15 px more often than not.)
242
+ const frames = Math.max(2, Math.round(duration / FRAME_MS));
243
+ const ahead = await clockAheadOf(page);
244
+ let clock = Date.now();
245
+ const send = (type, touchPoints) => cdp.send('Input.dispatchTouchEvent', { type, touchPoints, timestamp: (clock + ahead) / 1000 });
246
+ const wait = async (ms) => {
247
+ clock += ms;
248
+ const ahead = clock - Date.now();
249
+ if (ahead > 0)
250
+ await sleep(ahead);
251
+ };
252
+ await send('touchStart', points(0));
253
+ try {
254
+ if (holdBefore > 0)
255
+ await wait(holdBefore);
256
+ if (duration > 0) {
257
+ for (let i = 1; i <= frames; i++) {
258
+ await wait(FRAME_MS);
259
+ await send('touchMove', points(ease(i / frames)));
260
+ }
261
+ }
262
+ if (holdAfter > 0)
263
+ await wait(holdAfter);
264
+ clock += 1;
265
+ await send('touchEnd', []);
266
+ }
267
+ catch (error) {
268
+ // A gesture that broke half way must not leave a finger on the screen.
269
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchCancel', touchPoints: [] }).catch(() => undefined);
270
+ throw error;
271
+ }
272
+ }
273
+ const round = (p) => ({ x: Math.round(p.x), y: Math.round(p.y) });
274
+ const between = (from, to) => (k) => ({ x: from.x + (to.x - from.x) * k, y: from.y + (to.y - from.y) * k });
275
+ /** A stroke given as from/to, or one across the visible part of a target in a direction. */
276
+ async function strokeOf(target, options) {
277
+ const page = pageOf(target);
278
+ if ('from' in options)
279
+ return { page, from: options.from, to: options.to };
280
+ const box = await boxOf(page, target);
281
+ const unit = UNIT[options.direction];
282
+ const along = unit.x !== 0 ? box.width : box.height;
283
+ const distance = options.distance ?? along * 0.6;
284
+ const mid = centre(box);
285
+ return {
286
+ page,
287
+ from: { x: mid.x - (unit.x * distance) / 2, y: mid.y - (unit.y * distance) / 2 },
288
+ to: { x: mid.x + (unit.x * distance) / 2, y: mid.y + (unit.y * distance) / 2 },
289
+ };
290
+ }
291
+ /**
292
+ * A hard flick: the finger is still moving at full speed when it lifts, so the content keeps
293
+ * scrolling on its own momentum, as it does under a thumb.
294
+ */
295
+ export async function fling(target, options) {
296
+ const { page, from, to } = await strokeOf(target, options);
297
+ await perform(page, { fingers: [between(from, to)], duration: options.duration ?? 120, ease: linear });
298
+ }
299
+ /**
300
+ * A controlled swipe: the finger slows to a stop before it lifts, so the content moves by the
301
+ * length of the stroke and no further.
302
+ */
303
+ export async function swipe(target, options) {
304
+ const { page, from, to } = await strokeOf(target, options);
305
+ await perform(page, { fingers: [between(from, to)], duration: options.duration ?? 400, ease: easeOut });
306
+ }
307
+ /**
308
+ * Stops the call a newcomer writes first, `tap(page, '#more')`. JavaScript would let it through and
309
+ * the touch would land in the middle of the page, with nothing to say why the test fails.
310
+ */
311
+ function aimed(name, target, options) {
312
+ if (isPage(target) || typeof options === 'string')
313
+ throw new Error(`playwright-touch: ${name} takes a locator or a point, not the page and a selector. Write ${name}(page.locator('#more')).`);
314
+ }
315
+ /**
316
+ * A quick touch that the browser turns into a click. Playwright's own `tap` needs a context created
317
+ * with `hasTouch`, which the browser on a real phone is not; this one works in both.
318
+ */
319
+ export async function tap(target, options = {}) {
320
+ aimed('tap', target, options);
321
+ const page = pageOf(target, options.page);
322
+ const at = await landingOn(page, target);
323
+ await perform(page, { fingers: [() => at], duration: 0, ease: linear, holdBefore: 60 });
324
+ }
325
+ /** The browsers of real phones, which `connectAndroid` adds its own to. */
326
+ export const realPhones = new WeakSet();
327
+ /**
328
+ * Two quick taps on the same place. The second finger comes down while the browser still waits to
329
+ * see whether the first tap was all there was.
330
+ */
331
+ export async function doubleTap(target, options = {}) {
332
+ aimed('doubleTap', target, options);
333
+ const page = pageOf(target, options.page);
334
+ const at = await landingOn(page, target);
335
+ const twice = async () => {
336
+ await perform(page, { fingers: [() => at], duration: 0, ease: linear, holdBefore: 50 });
337
+ await sleep(90);
338
+ await perform(page, { fingers: [() => at], duration: 0, ease: linear, holdBefore: 50 });
339
+ };
340
+ if (!realPhones.has(page.context()))
341
+ return twice();
342
+ // Chrome on a phone zooms on a double tap unless the page is laid out for phones, and it learns
343
+ // that a page is from what the page draws after a finger has scrolled it or zoomed it. In a tab
344
+ // no finger has moved yet it has not learned it, takes the double tap for a zoom, enlarges the
345
+ // page by a fifth and gives it no click at all. The zoom itself is what teaches it, so the zoom
346
+ // is undone and the double tap made once more. A page that is not laid out for phones zooms the
347
+ // second time as well, which is what a double tap does there.
348
+ const zoom = () => page.evaluate(() => window.visualViewport?.scale ?? 1);
349
+ const before = await zoom();
350
+ await twice();
351
+ // A zoom is under way by now if there is one, and is over when two looks in a row agree.
352
+ await sleep(200);
353
+ let after = await zoom();
354
+ if (after === before)
355
+ return;
356
+ for (let last = NaN; last !== after;) {
357
+ await sleep(120);
358
+ last = after;
359
+ after = await zoom();
360
+ }
361
+ if (after === before)
362
+ return;
363
+ const cdp = await sessionOf(page);
364
+ await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: before });
365
+ await sleep(120);
366
+ await twice();
367
+ }
368
+ /** Rests one finger on the target without moving, long enough for a long-press menu or a pick-up. */
369
+ export async function longPress(target, options = {}) {
370
+ aimed('longPress', target, options);
371
+ const page = pageOf(target, options.page);
372
+ const at = await landingOn(page, target);
373
+ await perform(page, { fingers: [() => at], duration: 0, ease: linear, holdBefore: options.duration ?? 700 });
374
+ }
375
+ /**
376
+ * Carries the source to the destination under one finger and lets go at a standstill. With `hold`,
377
+ * the finger rests first, for lists that pick an item up on a long press.
378
+ */
379
+ export async function drag(start, end, options = {}) {
380
+ const page = pageOf(start, options.page ?? (isLocator(end) ? end.page() : undefined));
381
+ // Bringing one end into view can move the other, so both are scrolled to first and measured after.
382
+ if (isLocator(end))
383
+ await end.scrollIntoViewIfNeeded();
384
+ if (isLocator(start))
385
+ await start.scrollIntoViewIfNeeded();
386
+ const settled = async (target) => isLocator(target) ? centre(await visiblePart(page, target)) : target;
387
+ let to;
388
+ try {
389
+ to = await settled(end);
390
+ }
391
+ catch {
392
+ throw new Error('playwright-touch: both ends of a drag have to be on screen together, and the destination is not.');
393
+ }
394
+ const from = isLocator(start) ? await landingOn(page, start) : start;
395
+ await perform(page, {
396
+ fingers: [between(from, to)],
397
+ duration: options.duration ?? 500,
398
+ ease: easeInOut,
399
+ holdBefore: options.hold ?? 0,
400
+ holdAfter: 120,
401
+ });
402
+ }
403
+ /**
404
+ * Two fingers spreading (scale above 1) or closing (below 1).
405
+ *
406
+ * On a page, the browser zooms by exactly `scale`, where the page allows zooming. On an element,
407
+ * two fingers travel around its centre, for maps and canvases that read the touches themselves.
408
+ */
409
+ export async function pinch(target, options) {
410
+ const page = pageOf(target);
411
+ const box = await boxOf(page, target);
412
+ const mid = centre(box);
413
+ if (isPage(target)) {
414
+ // Fingers given as page coordinates drift apart on their own once the page starts to zoom, so the
415
+ // zoom runs away. The browser's own pinch takes the factor directly and lands on it.
416
+ // The anchor is measured in what is on screen now: on a page that is already zoomed in, the
417
+ // middle of the layout viewport can lie outside it.
418
+ const seen = await page.evaluate(() => ({
419
+ x: (window.visualViewport?.width ?? innerWidth) / 2,
420
+ y: (window.visualViewport?.height ?? innerHeight) / 2,
421
+ }));
422
+ const cdp = await sessionOf(page);
423
+ const duration = options.duration ?? 400;
424
+ const travel = Math.abs(Math.log2(options.scale)) * 400;
425
+ const zoom = () => page.evaluate(() => window.visualViewport?.scale ?? 1);
426
+ const before = await zoom();
427
+ await cdp.send('Input.synthesizePinchGesture', {
428
+ x: Math.round(seen.x),
429
+ y: Math.round(seen.y),
430
+ scaleFactor: options.scale,
431
+ relativeSpeed: Math.max(200, Math.round((travel / duration) * 1000)),
432
+ gestureSourceType: 'touch',
433
+ });
434
+ // Desktop Chrome on Linux, the usual CI browser, ignores the gesture without a word, and so does
435
+ // a page that forbids zooming. Saying so beats returning as if it had worked.
436
+ if (Math.abs(options.scale - 1) > 0.05 && Math.abs((await zoom()) - before) < 0.01) {
437
+ throw new Error('playwright-touch: the page did not zoom. Desktop Chrome on Linux does not pinch-zoom pages; elsewhere the page may forbid zooming, or it is already at the limit.');
438
+ }
439
+ return;
440
+ }
441
+ // Fingers travel along a diagonal, like a thumb and a forefinger; the wider gap must fit the element.
442
+ const wide = Math.max(40, Math.min(box.width, box.height) * 0.45);
443
+ const [startGap, endGap] = options.scale >= 1 ? [wide / options.scale, wide] : [wide, wide * options.scale];
444
+ const finger = (sign) => (k) => {
445
+ const gap = startGap + (endGap - startGap) * k;
446
+ return { x: mid.x + sign * gap * 0.6, y: mid.y - sign * gap * 0.8 };
447
+ };
448
+ await perform(page, {
449
+ fingers: [finger(1), finger(-1)],
450
+ duration: options.duration ?? 400,
451
+ ease: easeInOut,
452
+ holdAfter: 80,
453
+ });
454
+ }
455
+ /**
456
+ * Two fingers turning around the middle of an element, for maps and pictures that follow the
457
+ * angle between the touches. The fingers keep their distance, so nothing is zoomed on the way.
458
+ */
459
+ export async function rotate(target, options) {
460
+ const page = pageOf(target);
461
+ const box = await boxOf(page, target);
462
+ const mid = centre(box);
463
+ const radius = Math.max(20, Math.min(box.width, box.height) * 0.3);
464
+ // The fingers start on a diagonal, like a thumb and a forefinger.
465
+ const finger = (startsAt) => along(arc(mid, radius, startsAt, startsAt + options.degrees));
466
+ await perform(page, {
467
+ fingers: [finger(-45), finger(135)],
468
+ duration: options.duration ?? 500,
469
+ ease: easeInOut,
470
+ holdAfter: 80,
471
+ });
472
+ }
473
+ /** Any gesture, finger by finger. The named gestures cover the usual ones; this is for the rest, a signature or a drawing. */
474
+ export async function gesture(page, options) {
475
+ if (options.fingers.length === 0)
476
+ throw new Error('playwright-touch: a gesture needs at least one finger.');
477
+ await perform(page, {
478
+ fingers: options.fingers.map(along),
479
+ // Without any time to move in, the fingers would lift where they landed.
480
+ duration: Math.max(options.duration ?? 500, FRAME_MS),
481
+ ease: linear,
482
+ holdBefore: options.hold ?? 0,
483
+ holdAfter: 60,
484
+ });
485
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The switch for launching Chromium that makes scroll distances exact. Chromium smooths scrolling
3
+ * between touch events by guessing where the finger is at each frame, and on a busy machine the
4
+ * guess costs a swipe 15 px in some runs. With the smoothing off, the page moves by exactly what
5
+ * the events say.
6
+ *
7
+ * Chromium honours only the last `--disable-features` switch it is given, and Playwright passes
8
+ * one of its own with features it needs switched off. So this returns Playwright's list with one
9
+ * more name in it, read from a browser started for a moment. Pass it where the browser is
10
+ * launched: `launchOptions: { args: await steadyScrollArgs() }`. It does not apply to a browser on
11
+ * a phone.
12
+ */
13
+ export declare function steadyScrollArgs(launch?: {
14
+ channel?: string;
15
+ executablePath?: string;
16
+ }): Promise<string[]>;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The switch for launching Chromium that makes scroll distances exact. Chromium smooths scrolling
3
+ * between touch events by guessing where the finger is at each frame, and on a busy machine the
4
+ * guess costs a swipe 15 px in some runs. With the smoothing off, the page moves by exactly what
5
+ * the events say.
6
+ *
7
+ * Chromium honours only the last `--disable-features` switch it is given, and Playwright passes
8
+ * one of its own with features it needs switched off. So this returns Playwright's list with one
9
+ * more name in it, read from a browser started for a moment. Pass it where the browser is
10
+ * launched: `launchOptions: { args: await steadyScrollArgs() }`. It does not apply to a browser on
11
+ * a phone.
12
+ */
13
+ export async function steadyScrollArgs(launch = {}) {
14
+ const { chromium } = await import('playwright-core');
15
+ // The list is Playwright's and the same for every browser it starts, so any one that is there
16
+ // will do: the one asked for, or else the one Playwright downloaded, or else Chrome itself.
17
+ const candidates = launch.channel || launch.executablePath ? [launch] : [{}, { channel: 'chrome' }, { channel: 'msedge' }];
18
+ let server;
19
+ for (const candidate of candidates) {
20
+ server = await chromium.launchServer(candidate).catch(() => undefined);
21
+ if (server)
22
+ break;
23
+ }
24
+ if (!server)
25
+ throw new Error('playwright-touch: no Chromium-based browser could be started to read the switches from. Run "npx playwright install chromium", or install Chrome.');
26
+ try {
27
+ const theirs = server
28
+ .process()
29
+ .spawnargs.find((argument) => argument.startsWith('--disable-features='))
30
+ ?.slice('--disable-features='.length);
31
+ const features = new Set((theirs ?? '').split(',').filter(Boolean));
32
+ features.add('ResamplingScrollEvents');
33
+ return [`--disable-features=${[...features].join(',')}`];
34
+ }
35
+ finally {
36
+ await server.close();
37
+ }
38
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};