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,338 @@
1
+ // The page in Safari's front tab: read through the Web Inspector, touched through the simulator.
2
+ import { COLLECTOR, READ, SCROLL_READ, SCROLL_WATCH, longestPauseOf, tidy, } from '../measure.js';
3
+ import { arc } from '../polyline.js';
4
+ import * as paths from './paths.js';
5
+ import { easeInOut, easeOut, linear } from './paths.js';
6
+ import { sleep } from './tools.js';
7
+ import { SHOW_TOUCHES } from '../show.js';
8
+ const UNIT = {
9
+ up: { x: 0, y: -1 },
10
+ down: { x: 0, y: 1 },
11
+ left: { x: -1, y: 0 },
12
+ right: { x: 1, y: 0 },
13
+ };
14
+ /** The page behind `session`. `origin` is where the page starts on the screen, in screen points. */
15
+ export function createPage(session, touch, origin,
16
+ /** Called whenever the tab shows a new document. */
17
+ arrived = async () => { },
18
+ /**
19
+ * On a person's own phone a finger that misses the page lands on their home screen or in another
20
+ * app. With this, every gesture first asks whether Safari is in front, and a page that does not
21
+ * answer is taken for one that cannot be touched.
22
+ */
23
+ guard) {
24
+ // Safari gives positions relative to what is on screen, also when the page is zoomed in: the
25
+ // numbers then count in page pixels, each of which covers more of the screen. Measured on iOS
26
+ // 26.5: an element 240 px from the left read 104 with the view shifted by 136. So a position is
27
+ // enlarged by the zoom and nothing else. The zoom is read before every gesture.
28
+ let zoom = 1;
29
+ /** Whether the fingers are to be shown, on this page and the ones after it. */
30
+ let shown = false;
31
+ const look = async () => {
32
+ await guard?.();
33
+ const now = await session
34
+ .evaluate('({ zoom: visualViewport.scale, inFront: document.hasFocus() })')
35
+ .catch(() => null);
36
+ // Safari's tab overview, or another app, takes every touch meant for the page.
37
+ if (now && !now.inFront) {
38
+ throw new Error('playwright-touch: the page is not in front in Safari, so it cannot be touched. Is the tab overview open, or another app?');
39
+ }
40
+ if (!now && guard) {
41
+ throw new Error('playwright-touch: the page does not answer, so it is not touched. Is Safari still open on the tab this opened?');
42
+ }
43
+ zoom = now?.zoom ?? zoom;
44
+ // The tab may have gone to another page by a tap on a link, which nobody tells us about. The
45
+ // script does nothing where it is already there.
46
+ if (shown)
47
+ await session.evaluate(`void ${SHOW_TOUCHES}`).catch(() => undefined);
48
+ };
49
+ const onScreen = (point) => ({ x: point.x * zoom + origin.x, y: point.y * zoom + origin.y });
50
+ /** The same finger paths as in `paths.ts`, given in page positions. */
51
+ const rest = (at, duration) => paths.rest(onScreen(at), duration);
52
+ const travel = (from, to, duration, ease, restBefore = 0, restAfter = 0) => paths.travel(onScreen(from), onScreen(to), duration, ease, restBefore, restAfter);
53
+ const evaluate = (code) => session.evaluate(typeof code === 'string' ? code : `(${code})()`);
54
+ /** Waits until the page has stopped scrolling: Safari may still be moving after an element was brought into view. */
55
+ const settled = async () => {
56
+ let last = '';
57
+ for (let i = 0, calm = 0; i < 25 && calm < 2; i++) {
58
+ const now = await session.evaluate('[scrollX, scrollY, visualViewport.offsetTop, visualViewport.pageTop].join()');
59
+ calm = now === last ? calm + 1 : 0;
60
+ last = now;
61
+ if (calm < 2)
62
+ await sleep(60);
63
+ }
64
+ };
65
+ const centreOf = async (target) => {
66
+ if (typeof target !== 'string')
67
+ return target;
68
+ const found = await session.evaluate(`(() => { const e = document.querySelector(${JSON.stringify(target)}); if (!e) return false; e.scrollIntoView({ block: 'center', inline: 'center' }); return true; })()`);
69
+ if (!found)
70
+ throw new Error(`playwright-touch: nothing on the page matches ${target}.`);
71
+ await settled();
72
+ return session.evaluate(`(() => { const r = document.querySelector(${JSON.stringify(target)}).getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; })()`);
73
+ };
74
+ /**
75
+ * Checks that a finger at the middle of the element would touch the element, and not a cookie
76
+ * bar or a sticky header over it.
77
+ */
78
+ const uncovered = async (target) => {
79
+ if (typeof target !== 'string')
80
+ return;
81
+ const inTheWay = await session.evaluate(`(() => {
82
+ const element = document.querySelector(${JSON.stringify(target)});
83
+ if (!element) return null;
84
+ const box = element.getBoundingClientRect();
85
+ const x = (Math.max(box.left, 0) + Math.min(box.right, innerWidth)) / 2;
86
+ const y = (Math.max(box.top, 0) + Math.min(box.bottom, innerHeight)) / 2;
87
+ let hit = document.elementFromPoint(x, y);
88
+ while (hit && hit.shadowRoot) { const inner = hit.shadowRoot.elementFromPoint(x, y); if (!inner || inner === hit) break; hit = inner; }
89
+ if (!hit) return 'nothing at all';
90
+ for (let node = hit; node; node = node.parentNode || node.host || null) if (node === element) return null;
91
+ if (getComputedStyle(element).pointerEvents === 'none') for (let node = element; node; node = node.parentNode || node.host || null) if (node === hit) return null;
92
+ return hit.tagName.toLowerCase() + (hit.id ? '#' + hit.id : '');
93
+ })()`);
94
+ if (inTheWay)
95
+ throw new Error(`playwright-touch: ${target} is covered by ${inTheWay}, which would take the touch instead.`);
96
+ };
97
+ /** The centre of a target as it lies now, without scrolling; it has to be on screen. */
98
+ const whereNow = async (target) => {
99
+ if (typeof target !== 'string')
100
+ return target;
101
+ const at = await session.evaluate(`(() => { const e = document.querySelector(${JSON.stringify(target)}); if (!e) return null; const r = e.getBoundingClientRect(); const x = r.left + r.width / 2, y = r.top + r.height / 2; return { x, y, seen: x >= 0 && y >= 0 && x <= innerWidth && y <= innerHeight }; })()`);
102
+ if (!at)
103
+ throw new Error(`playwright-touch: nothing on the page matches ${target}.`);
104
+ if (!at.seen)
105
+ throw new Error(`playwright-touch: ${target} is not on screen together with the other end of the drag.`);
106
+ return { x: at.x, y: at.y };
107
+ };
108
+ /** The rectangle of an element after it was brought into view and the page came to rest. */
109
+ const boxOf = async (selector) => {
110
+ await centreOf(selector);
111
+ return session.evaluate(`(() => { const r = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); return { x: r.left, y: r.top, width: r.width, height: r.height }; })()`);
112
+ };
113
+ const strokeOf = async (options) => {
114
+ if ('from' in options)
115
+ return options;
116
+ const box = options.on
117
+ ? await boxOf(options.on)
118
+ : await session.evaluate('({ x: 0, y: 0, width: visualViewport.width, height: visualViewport.height })');
119
+ const unit = UNIT[options.direction];
120
+ const length = options.distance ?? 0.6 * (unit.x ? box.width : box.height);
121
+ const mid = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
122
+ return {
123
+ from: { x: mid.x - (unit.x * length) / 2, y: mid.y - (unit.y * length) / 2 },
124
+ to: { x: mid.x + (unit.x * length) / 2, y: mid.y + (unit.y * length) / 2 },
125
+ };
126
+ };
127
+ let filming = false;
128
+ const page = {
129
+ ios: true,
130
+ locator: (selector) => ({ ios: true, selector, page }),
131
+ async goto(url, { timeout = 30_000 } = {}) {
132
+ // Every document has its own start time, so a new start time means a new document, also when
133
+ // the address is the same as before.
134
+ const before = await session
135
+ .evaluate('({ started: performance.timeOrigin, href: location.href })')
136
+ .catch(() => null);
137
+ if (before) {
138
+ // An address that differs only after the # stays in the same document; there is nothing to wait for.
139
+ const [target, current] = [new URL(url, before.href), new URL(before.href)];
140
+ if (target.href.includes('#') &&
141
+ target.origin + target.pathname + target.search === current.origin + current.pathname + current.search) {
142
+ await session.evaluate(`void (location.href = ${JSON.stringify(target.href)})`);
143
+ return;
144
+ }
145
+ }
146
+ // Safari on iOS has no command for this, so the page is told to go there itself. The answer may
147
+ // never come when the page is swapped for a new one, and that is fine: the loop below watches
148
+ // for the new document.
149
+ await session.evaluate(`void (location.href = ${JSON.stringify(url)})`).catch(() => undefined);
150
+ for (const deadline = Date.now() + timeout;;) {
151
+ if (Date.now() > deadline)
152
+ throw new Error(`playwright-touch: ${url} did not finish loading in ${timeout} ms.`);
153
+ await sleep(100);
154
+ const state = await session
155
+ .evaluate('({ started: performance.timeOrigin, ready: document.readyState })')
156
+ .catch(() => null);
157
+ if (state && state.ready === 'complete' && state.started !== before?.started) {
158
+ await session.evaluate(`void ${COLLECTOR.replace(/;\s*$/, '')}`).catch(() => undefined);
159
+ if (shown)
160
+ await session.evaluate(`void ${SHOW_TOUCHES}`).catch(() => undefined);
161
+ // A film that is running goes on watching for scrolling in the new document.
162
+ if (filming)
163
+ await session.evaluate(`void ${SCROLL_WATCH}`).catch(() => undefined);
164
+ await arrived();
165
+ return;
166
+ }
167
+ }
168
+ },
169
+ evaluate,
170
+ async coldLoad(url, { settle = 2000, timeout } = {}) {
171
+ await session.command('Network.enable');
172
+ await session.command('Network.setResourceCachingDisabled', { disabled: true });
173
+ try {
174
+ await page.goto(url, { timeout });
175
+ await sleep(settle);
176
+ return await page.vitals();
177
+ }
178
+ finally {
179
+ await session.command('Network.setResourceCachingDisabled', { disabled: false }).catch(() => undefined);
180
+ }
181
+ },
182
+ async vitals() {
183
+ // Safari keeps what happened before anyone listened, so the collector can start late.
184
+ await session.evaluate(`void ${COLLECTOR.replace(/;\s*$/, '')}`);
185
+ await sleep(50);
186
+ const vitals = await session.evaluate(READ);
187
+ if (!vitals)
188
+ throw new Error('playwright-touch: the page could not be measured.');
189
+ return tidy(vitals);
190
+ },
191
+ async film(action, { settle = 1500 } = {}) {
192
+ const frames = [];
193
+ let first = 0;
194
+ const stop = touch.watch((jpeg) => {
195
+ first ||= Date.now();
196
+ frames.push({ at: Date.now() - first, jpeg });
197
+ });
198
+ let started = Date.now();
199
+ let scrolled = null;
200
+ try {
201
+ // The stream needs a moment before its first picture; the recording counts from there.
202
+ for (let i = 0; i < 30 && frames.length === 0; i++)
203
+ await sleep(100);
204
+ started = Date.now();
205
+ await session.evaluate(`void ${SCROLL_WATCH}`).catch(() => undefined);
206
+ filming = true;
207
+ await action();
208
+ await sleep(settle);
209
+ scrolled = await session.evaluate(SCROLL_READ).catch(() => null);
210
+ }
211
+ finally {
212
+ filming = false;
213
+ stop();
214
+ }
215
+ if (frames.length === 0)
216
+ throw new Error(`playwright-touch: ${touch.name} sent no picture of the screen.`);
217
+ // Frames carry the time they arrived here, the page the time it scrolled; both count from 1970.
218
+ const scrolledFor = scrolled !== null && first ? Math.max(0, Math.round(scrolled - first)) : null;
219
+ return {
220
+ frames,
221
+ duration: Date.now() - started,
222
+ longestPause: longestPauseOf(frames, scrolledFor === null ? null : scrolledFor + 100),
223
+ scrolledFor,
224
+ };
225
+ },
226
+ async tap(target) {
227
+ const at = await centreOf(target);
228
+ await uncovered(target);
229
+ await look();
230
+ await touch.perform([rest(at, 60)]);
231
+ },
232
+ async doubleTap(target) {
233
+ const at = await centreOf(target);
234
+ await uncovered(target);
235
+ await look();
236
+ await touch.doubleTap(onScreen(at));
237
+ },
238
+ async longPress(target, { duration = 700 } = {}) {
239
+ const at = await centreOf(target);
240
+ await uncovered(target);
241
+ await look();
242
+ await touch.perform([rest(at, duration)]);
243
+ },
244
+ async swipe(options) {
245
+ const { from, to } = await strokeOf(options);
246
+ await look();
247
+ // Through idb the finger cannot slow down, so it is given more time instead.
248
+ await touch.perform([travel(from, to, options.duration ?? (touch.name === 'idb' ? 900 : 400), easeOut)]);
249
+ },
250
+ async fling(options) {
251
+ const { from, to } = await strokeOf(options);
252
+ await look();
253
+ await touch.perform([travel(from, to, options.duration ?? 100, linear)]);
254
+ },
255
+ async drag(source, destination, { hold = 0, duration = 600 } = {}) {
256
+ // Bringing the destination into view could move the source, so both are measured after the scrolling is done.
257
+ await centreOf(destination);
258
+ await centreOf(source);
259
+ const to = await whereNow(destination);
260
+ const from = await whereNow(source);
261
+ await uncovered(source);
262
+ await look();
263
+ await touch.perform([travel(from, to, duration, easeInOut, hold, 120)]);
264
+ },
265
+ async pinch(target, { scale, duration = 400 }) {
266
+ /** Two fingers on a diagonal, like a thumb and a forefinger, their gap changing by `factor`. */
267
+ const fingers = async (factor) => {
268
+ const box = target === null
269
+ ? await session.evaluate('({ x: 0, y: 0, width: visualViewport.width, height: visualViewport.height })')
270
+ : await boxOf(target);
271
+ await look();
272
+ const mid = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
273
+ const wide = Math.max(40, Math.min(box.width, box.height) * 0.45);
274
+ const [startGap, endGap] = factor >= 1 ? [wide / factor, wide] : [wide, wide * factor];
275
+ const finger = (sign) => travel({ x: mid.x + sign * startGap * 0.6, y: mid.y - sign * startGap * 0.8 }, { x: mid.x + sign * endGap * 0.6, y: mid.y - sign * endGap * 0.8 }, duration, easeOut, 0, 80);
276
+ await touch.perform([finger(1), finger(-1)]);
277
+ };
278
+ if (target !== null) {
279
+ await fingers(scale);
280
+ // Two fingers closing on an element that does not take them close on the page instead, and
281
+ // on a page that cannot get smaller Safari answers that by opening its tab overview.
282
+ if (scale < 1 && !(await session.evaluate('document.hasFocus()').catch(() => true))) {
283
+ throw new Error(`playwright-touch: ${target} did not take the pinch, so Safari opened its tab overview. Elements that handle two fingers themselves prevent that.`);
284
+ }
285
+ return;
286
+ }
287
+ // On the page, Safari itself decides how much two fingers zoom, and it is less than their
288
+ // gap changes: asked for 2, the page went to 1.58. So the zoom is read after each pinch and
289
+ // what is missing is pinched again, at most twice more. A page that will not zoom stays put.
290
+ const zoomNow = () => session.evaluate('visualViewport.scale');
291
+ // The page is as small as it gets when all of its width is on screen. Two fingers closing
292
+ // on it then do not zoom: Safari opens the tab overview, which takes every touch after that.
293
+ // So a pinch never asks for less than the smallest zoom, and at the smallest it is refused.
294
+ const smallest = await session.evaluate('visualViewport.scale * Math.min(1, visualViewport.width / document.documentElement.clientWidth)');
295
+ const wanted = Math.max((await zoomNow()) * scale, smallest);
296
+ if (scale < 1 && (await zoomNow()) <= smallest * 1.01) {
297
+ throw new Error('playwright-touch: the page did not zoom. It is already as small as it gets.');
298
+ }
299
+ for (let attempt = 0; attempt < 3; attempt++) {
300
+ const missing = wanted / (await zoomNow());
301
+ if (Math.abs(missing - 1) < 0.04)
302
+ return;
303
+ // The fingers travel further than the zoom they get, by about this much.
304
+ const factor = missing > 1 ? 1 + (missing - 1) * 1.7 : 1 / (1 + (1 / missing - 1) * 1.7);
305
+ const before = await zoomNow();
306
+ await fingers(Math.min(4, Math.max(0.25, factor)));
307
+ await sleep(500);
308
+ if (Math.abs((await zoomNow()) - before) < 0.005) {
309
+ // Nothing moved at all: the same refusal as in Chrome, so that one script behaves alike
310
+ // in both. If it moved before and now stopped, the page has reached its limit, and that
311
+ // is as far as a pinch goes.
312
+ if (attempt === 0)
313
+ throw new Error('playwright-touch: the page did not zoom. The page may forbid zooming, or it is already at the limit.');
314
+ return;
315
+ }
316
+ }
317
+ },
318
+ async rotate(selector, { degrees, duration = 500 }) {
319
+ const box = await boxOf(selector);
320
+ await look();
321
+ const mid = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
322
+ const radius = Math.max(20, Math.min(box.width, box.height) * 0.3);
323
+ const finger = (startsAt) => paths.through(arc(mid, radius, startsAt, startsAt + degrees).map(onScreen), duration, 0, 80);
324
+ await touch.perform([finger(-45), finger(135)]);
325
+ },
326
+ async gesture({ fingers, duration = 500, hold = 0 }) {
327
+ if (fingers.length === 0)
328
+ throw new Error('playwright-touch: a gesture needs at least one finger.');
329
+ await look();
330
+ await touch.perform(fingers.map((points) => paths.through(points.map(onScreen), Math.max(duration, 17), hold, 60)));
331
+ },
332
+ async showTouches() {
333
+ shown = true;
334
+ await session.evaluate(`void ${SHOW_TOUCHES}`);
335
+ },
336
+ };
337
+ return page;
338
+ }
@@ -0,0 +1,17 @@
1
+ import type { Point } from '../types.js';
2
+ import type { Path } from './touch.js';
3
+ /** How far along the way the finger is (0 to 1) at a share of the time (0 to 1). */
4
+ export type Ease = (t: number) => number;
5
+ export declare const linear: Ease;
6
+ export declare const easeOut: Ease;
7
+ export declare const easeInOut: Ease;
8
+ /** A finger that lands and stays where it is. */
9
+ export declare const rest: (at: Point, duration: number) => Path;
10
+ /** A finger travelling from one point to another, placed by `ease` on every frame, with optional rests. */
11
+ export declare function travel(start: Point, end: Point, duration: number, ease: Ease, restBefore?: number, restAfter?: number): Path;
12
+ /**
13
+ * A finger passing through several points at an even pace. The way is cut into pieces of about
14
+ * 15 px, none shorter than a frame, for the same reason as in `travel`: shorter moves are merged
15
+ * or dropped by the system.
16
+ */
17
+ export declare function through(points: Point[], duration: number, restBefore?: number, restAfter?: number): Path;
@@ -0,0 +1,77 @@
1
+ // The way a finger takes across the screen, in screen points and milliseconds.
2
+ import { along, lengthOf } from '../polyline.js';
3
+ export const linear = (t) => t;
4
+ export const easeOut = (t) => 1 - (1 - t) ** 3;
5
+ export const easeInOut = (t) => (t < 0.5 ? 4 * t ** 3 : 1 - (-2 * t + 2) ** 3 / 2);
6
+ const FRAME = 1000 / 60;
7
+ /** A finger that lands and stays where it is. */
8
+ export const rest = (at, duration) => [
9
+ { ...at, ms: 0 },
10
+ { ...at, ms: duration },
11
+ ];
12
+ /** A finger travelling from one point to another, placed by `ease` on every frame, with optional rests. */
13
+ export function travel(start, end, duration, ease, restBefore = 0, restAfter = 0) {
14
+ const path = [{ ...start, ms: 0 }];
15
+ if (restBefore)
16
+ path.push({ ...start, ms: restBefore });
17
+ if (ease === linear) {
18
+ // A straight, even stroke is given as one move and the system fills in the rest. Cut into
19
+ // frames, a 100 ms fling carried the page anywhere from 548 to 1400 px in thirty runs; as
20
+ // one move, 1806 to 1939.
21
+ path.push({ ...end, ms: duration });
22
+ }
23
+ else {
24
+ // A stroke that changes speed is cut into pieces of equal length, about 15 px each, and
25
+ // the change of speed goes into how long each piece takes. Cut into equal times instead,
26
+ // the slow end of a swipe became moves of a pixel or two, which the system merges or drops:
27
+ // a 300 px swipe then moved the page 264 px, and 231 in two runs out of thirty. In equal
28
+ // lengths it moves it 285 px in thirty runs out of thirty. No piece is shorter than a frame.
29
+ const pieces = Math.max(2, Math.min(Math.round(Math.hypot(end.x - start.x, end.y - start.y) / 15), Math.floor(duration / FRAME)));
30
+ /** The share of the time by which the easing has covered this share of the way. */
31
+ const timeAt = (share) => {
32
+ let [low, high] = [0, 1];
33
+ for (let i = 0; i < 40; i++) {
34
+ const middle = (low + high) / 2;
35
+ if (ease(middle) < share)
36
+ low = middle;
37
+ else
38
+ high = middle;
39
+ }
40
+ return (low + high) / 2;
41
+ };
42
+ let before = 0;
43
+ for (let piece = 1; piece <= pieces; piece++) {
44
+ const now = piece === pieces ? 1 : timeAt(piece / pieces);
45
+ // Where the stroke is fast, a 15 px piece would take less than a frame, and is given a
46
+ // whole frame instead. That stretches a 400 ms swipe to about 500 ms. Joining such pieces
47
+ // into longer ones keeps the time right and was measured to be worse: 255 px with a
48
+ // spread, against 285 px every time.
49
+ path.push({
50
+ x: start.x + ((end.x - start.x) * piece) / pieces,
51
+ y: start.y + ((end.y - start.y) * piece) / pieces,
52
+ ms: Math.max(FRAME, (now - before) * duration),
53
+ });
54
+ before = now;
55
+ }
56
+ }
57
+ if (restAfter)
58
+ path.push({ ...end, ms: restAfter });
59
+ return path;
60
+ }
61
+ /**
62
+ * A finger passing through several points at an even pace. The way is cut into pieces of about
63
+ * 15 px, none shorter than a frame, for the same reason as in `travel`: shorter moves are merged
64
+ * or dropped by the system.
65
+ */
66
+ export function through(points, duration, restBefore = 0, restAfter = 0) {
67
+ const at = along(points);
68
+ const pieces = Math.max(1, Math.min(Math.round(lengthOf(points) / 15), Math.floor(duration / FRAME)));
69
+ const path = [{ ...at(0), ms: 0 }];
70
+ if (restBefore)
71
+ path.push({ ...at(0), ms: restBefore });
72
+ for (let piece = 1; piece <= pieces; piece++)
73
+ path.push({ ...at(piece / pieces), ms: duration / pieces });
74
+ if (restAfter)
75
+ path.push({ ...at(1), ms: restAfter });
76
+ return path;
77
+ }
@@ -0,0 +1,24 @@
1
+ import { type IosPage } from './page.js';
2
+ export type { IosLocator, IosPage } from './page.js';
3
+ /** Safari in an iPhone simulator, joined through `connectSimulator()`. */
4
+ export interface IosSimulator {
5
+ /** The simulated model, for logs. */
6
+ model: string;
7
+ /** What puts the fingers on the screen. */
8
+ touch: 'WebDriverAgent' | 'idb';
9
+ page: IosPage;
10
+ /** Disconnects. Safari and the simulator keep running. */
11
+ close(): Promise<void>;
12
+ }
13
+ /**
14
+ * Joins Safari in a booted iPhone simulator. With `udid`, that simulator is booted first if it is
15
+ * not running (without opening the Simulator window). Needs Xcode.
16
+ *
17
+ * Fingers go through WebDriverAgent when one is running for the simulator (at `wda`, by default
18
+ * http://127.0.0.1:8100): every gesture works and follows its path exactly. Without it they go
19
+ * through `idb`, which has to be on the PATH: one finger, straight lines.
20
+ */
21
+ export declare function connectSimulator(options?: {
22
+ udid?: string;
23
+ wda?: string;
24
+ }): Promise<IosSimulator>;
@@ -0,0 +1,69 @@
1
+ // Safari in an iPhone simulator: pages are read through the Web Inspector and touched through the
2
+ // simulator's own input, so the page gets real touches, scrolling and momentum.
3
+ import { boot, simulators } from './device.js';
4
+ import { WebInspector } from './inspector.js';
5
+ import { createPage } from './page.js';
6
+ import { openTab, remember } from './tab.js';
7
+ import { run, simctl } from './tools.js';
8
+ import { idbTouch, webDriverAgent } from './touch.js';
9
+ /**
10
+ * Joins Safari in a booted iPhone simulator. With `udid`, that simulator is booted first if it is
11
+ * not running (without opening the Simulator window). Needs Xcode.
12
+ *
13
+ * Fingers go through WebDriverAgent when one is running for the simulator (at `wda`, by default
14
+ * http://127.0.0.1:8100): every gesture works and follows its path exactly. Without it they go
15
+ * through `idb`, which has to be on the PATH: one finger, straight lines.
16
+ */
17
+ export async function connectSimulator(options = {}) {
18
+ const all = await simulators();
19
+ const device = options.udid
20
+ ? all.find((one) => one.udid === options.udid)
21
+ : all.find((one) => one.state === 'Booted' && one.name.startsWith('iPhone'));
22
+ if (!device && options.udid) {
23
+ throw new Error(`playwright-touch: no simulator with the identifier ${options.udid}. List them with: xcrun simctl list devices`);
24
+ }
25
+ if (!device) {
26
+ throw new Error('playwright-touch: no iPhone simulator is running. Boot one with: xcrun simctl boot "iPhone 17", or pass its udid.');
27
+ }
28
+ const udid = device.udid;
29
+ await boot(device);
30
+ const idb = async (...args) => {
31
+ try {
32
+ return await run('idb', [...args, '--udid', udid], 'idb was not found. Touch in the simulator goes through it; install it from https://fbidb.io.');
33
+ }
34
+ catch (error) {
35
+ // idb keeps a helper per simulator, and the helper does not survive the simulator being restarted.
36
+ if (/Mach port invalid|connect to companion/.test(error.message))
37
+ throw new Error('playwright-touch: idb lost the simulator, which happens when the simulator was restarted. Run "idb kill" and try again.');
38
+ throw error;
39
+ }
40
+ };
41
+ const touch = (await webDriverAgent(options.wda ?? 'http://127.0.0.1:8100', device)) ?? idbTouch(idb, udid);
42
+ if (touch.name === 'idb')
43
+ await idb('describe');
44
+ const socketPath = (await simctl('getenv', udid, 'RWI_LISTEN_SOCKET')).trim();
45
+ if (!socketPath)
46
+ throw new Error('playwright-touch: the simulator does not offer a Web Inspector socket.');
47
+ const inspector = await WebInspector.open(socketPath);
48
+ let tab;
49
+ try {
50
+ tab = await openTab(inspector, touch, udid, device.name);
51
+ }
52
+ catch (error) {
53
+ await inspector.close();
54
+ await touch.close();
55
+ throw error;
56
+ }
57
+ const { session, origin } = tab;
58
+ return {
59
+ model: device.name,
60
+ touch: touch.name,
61
+ page: createPage(session, touch, origin, () => remember(session, udid)),
62
+ async close() {
63
+ await remember(session, udid);
64
+ await touch.close();
65
+ session.close();
66
+ await inspector.close();
67
+ },
68
+ };
69
+ }
@@ -0,0 +1,41 @@
1
+ import type { Point } from '../types.js';
2
+ import type { InspectorSession, WebInspector } from './inspector.js';
3
+ import type { Touch } from './touch.js';
4
+ /** A tab that answers, and where on the screen its page starts, in screen points. */
5
+ export interface Tab {
6
+ session: InspectorSession;
7
+ origin: Point;
8
+ }
9
+ /** How the tab to work in gets opened, which differs between a simulator and a phone. */
10
+ export interface Opener {
11
+ /** The address of the page the tab starts on. */
12
+ url: string;
13
+ /** Has Safari open that address in a new tab. */
14
+ open(): Promise<void>;
15
+ /** Makes the page that loaded there report touches, where it does not do so by itself. */
16
+ prepare?(session: InspectorSession): Promise<void>;
17
+ /**
18
+ * On a person's own phone the other tabs are theirs. With this set, a tab is only looked into
19
+ * when it is on the start address, which no tab of theirs is, and belongs to Safari.
20
+ */
21
+ ownOnly?: boolean;
22
+ /** Whether Safari is the application in front, where the device can be asked. */
23
+ inFront?(): Promise<boolean>;
24
+ /** Called after the tab was opened, before waiting for it: refuses with a reason when it cannot show up. */
25
+ expect?(): Promise<void>;
26
+ /**
27
+ * Called when the tab was opened and the Web Inspector still does not list it. Safari on a phone
28
+ * does not always announce a tab that another app asked it to open; starting Safari again does.
29
+ */
30
+ revive?(): Promise<void>;
31
+ close(): void;
32
+ }
33
+ /** A page of our own, served from this computer, which a simulator can reach. */
34
+ export declare function servedStart(udid: string): Promise<Opener>;
35
+ /** Writes down which document the tab shows now, so that the next connection can recognise the tab. */
36
+ export declare function remember(session: InspectorSession, udid: string): Promise<void>;
37
+ /**
38
+ * Opens the tab to work in, or takes over the one an earlier connection left, and finds out where
39
+ * on the screen the page starts by touching it once.
40
+ */
41
+ export declare function openTab(inspector: WebInspector, touch: Touch, udid: string, deviceName: string, opener?: Opener): Promise<Tab>;