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