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.
- package/LICENSE +21 -0
- package/README.md +612 -2
- package/dist/android.d.ts +26 -0
- package/dist/android.js +113 -0
- package/dist/chromium/clock.d.ts +12 -0
- package/dist/chromium/clock.js +45 -0
- package/dist/chromium/gestures.d.ts +56 -0
- package/dist/chromium/gestures.js +500 -0
- package/dist/chromium/steady.d.ts +16 -0
- package/dist/chromium/steady.js +38 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +459 -0
- package/dist/index.d.ts +111 -0
- package/dist/index.js +149 -0
- package/dist/ios/bplist.d.ts +8 -0
- package/dist/ios/bplist.js +150 -0
- package/dist/ios/device.d.ts +30 -0
- package/dist/ios/device.js +48 -0
- package/dist/ios/inspector.d.ts +61 -0
- package/dist/ios/inspector.js +342 -0
- package/dist/ios/iphone.d.ts +27 -0
- package/dist/ios/iphone.js +141 -0
- package/dist/ios/page.d.ts +90 -0
- package/dist/ios/page.js +338 -0
- package/dist/ios/paths.d.ts +17 -0
- package/dist/ios/paths.js +77 -0
- package/dist/ios/simulator.d.ts +24 -0
- package/dist/ios/simulator.js +69 -0
- package/dist/ios/tab.d.ts +41 -0
- package/dist/ios/tab.js +171 -0
- package/dist/ios/tools.d.ts +4 -0
- package/dist/ios/tools.js +17 -0
- package/dist/ios/touch.d.ts +31 -0
- package/dist/ios/touch.js +178 -0
- package/dist/ios/usbmux.d.ts +34 -0
- package/dist/ios/usbmux.js +346 -0
- package/dist/layout.d.ts +35 -0
- package/dist/layout.js +164 -0
- package/dist/measure.d.ts +86 -0
- package/dist/measure.js +173 -0
- package/dist/own-tabs.d.ts +8 -0
- package/dist/own-tabs.js +242 -0
- package/dist/playwright-test.d.ts +66 -0
- package/dist/playwright-test.js +64 -0
- package/dist/polyline.d.ts +10 -0
- package/dist/polyline.js +38 -0
- package/dist/recipes.d.ts +57 -0
- package/dist/recipes.js +135 -0
- package/dist/report.d.ts +46 -0
- package/dist/report.js +118 -0
- package/dist/session.d.ts +35 -0
- package/dist/session.js +23 -0
- package/dist/show.d.ts +13 -0
- package/dist/show.js +51 -0
- package/dist/synthetic.d.ts +17 -0
- package/dist/synthetic.js +117 -0
- package/dist/types.d.ts +58 -0
- package/dist/types.js +2 -0
- package/package.json +83 -4
package/dist/measure.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { sessionOf } from './session.js';
|
|
2
|
+
// Runs in the page before any of its own scripts. Kept as text so it is the same on every page and
|
|
3
|
+
// survives navigations.
|
|
4
|
+
export const COLLECTOR = `(() => {
|
|
5
|
+
if (window.__playwrightTouchVitals) return;
|
|
6
|
+
const can = (type) => (PerformanceObserver.supportedEntryTypes || []).includes(type);
|
|
7
|
+
const v = (window.__playwrightTouchVitals = { fcp: null, lcp: null, cls: can('layout-shift') ? 0 : null, longTasks: can('longtask') ? 0 : null, blocked: can('longtask') ? 0 : null, slow: {} });
|
|
8
|
+
const watch = (type, each, extra) => {
|
|
9
|
+
try { new PerformanceObserver((list) => list.getEntries().forEach(each)).observe(Object.assign({ type, buffered: true }, extra)); } catch (_) {}
|
|
10
|
+
};
|
|
11
|
+
watch('paint', (e) => { if (e.name === 'first-contentful-paint') v.fcp = e.startTime; });
|
|
12
|
+
watch('largest-contentful-paint', (e) => { v.lcp = e.startTime; });
|
|
13
|
+
// Shifts are counted in bursts: a burst ends after a second of calm or five seconds in all, and
|
|
14
|
+
// the score is the worst burst. Shifts right after input are the user's own doing and are left out.
|
|
15
|
+
let burst = 0, first = 0, last = 0;
|
|
16
|
+
watch('layout-shift', (e) => {
|
|
17
|
+
if (e.hadRecentInput) return;
|
|
18
|
+
if (burst && e.startTime - last < 1000 && e.startTime - first < 5000) burst += e.value;
|
|
19
|
+
else { burst = e.value; first = e.startTime; }
|
|
20
|
+
last = e.startTime;
|
|
21
|
+
if (burst > v.cls) v.cls = burst;
|
|
22
|
+
});
|
|
23
|
+
// Safari gives a click no interaction of its own, so a slow click handler would go unseen there;
|
|
24
|
+
// such a click counts as an interaction by itself.
|
|
25
|
+
watch('event', (e) => { const id = e.interactionId || (e.name === 'click' ? 'click' + Math.round(e.startTime) : 0); if (id) v.slow[id] = Math.max(v.slow[id] || 0, e.duration); }, { durationThreshold: 16 });
|
|
26
|
+
watch('longtask', (e) => { v.longTasks++; v.blocked += e.duration - 50; });
|
|
27
|
+
})();`;
|
|
28
|
+
export const READ = `(() => {
|
|
29
|
+
const v = window.__playwrightTouchVitals;
|
|
30
|
+
if (!v) return null;
|
|
31
|
+
const nav = performance.getEntriesByType('navigation')[0];
|
|
32
|
+
const slow = Object.values(v.slow);
|
|
33
|
+
// The browser's own count also includes touches answered too fast to be listed one by one.
|
|
34
|
+
return { ttfb: nav ? nav.responseStart : null, fcp: v.fcp, lcp: v.lcp, cls: v.cls, inp: slow.length ? Math.max(...slow) : null, interactions: Math.max(slow.length, performance.interactionCount || 0), longTasks: v.longTasks, blocked: v.blocked };
|
|
35
|
+
})()`;
|
|
36
|
+
export const tidy = (vitals) => {
|
|
37
|
+
// Everything here comes out of the measured page, so nothing is trusted to be the number it should be.
|
|
38
|
+
const number = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : null);
|
|
39
|
+
const ms = (value) => (number(value) === null ? null : Math.round(number(value)));
|
|
40
|
+
const cls = number(vitals.cls);
|
|
41
|
+
return {
|
|
42
|
+
ttfb: ms(vitals.ttfb),
|
|
43
|
+
fcp: ms(vitals.fcp),
|
|
44
|
+
lcp: ms(vitals.lcp),
|
|
45
|
+
inp: ms(vitals.inp),
|
|
46
|
+
interactions: ms(vitals.interactions) ?? 0,
|
|
47
|
+
longTasks: ms(vitals.longTasks),
|
|
48
|
+
blocked: ms(vitals.blocked),
|
|
49
|
+
cls: cls === null ? null : Math.round(cls * 1000) / 1000,
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Starts collecting metrics on the page and on every page it navigates to. Call it before the
|
|
54
|
+
* navigation that should be measured, then read at any time: after the load, after a gesture.
|
|
55
|
+
*/
|
|
56
|
+
export async function watchVitals(page) {
|
|
57
|
+
await page.addInitScript({ content: COLLECTOR });
|
|
58
|
+
return {
|
|
59
|
+
async read() {
|
|
60
|
+
const vitals = await page.evaluate(READ);
|
|
61
|
+
if (!vitals)
|
|
62
|
+
throw new Error('playwright-touch: nothing was measured on this page. Call watchVitals() before the navigation.');
|
|
63
|
+
return tidy(vitals);
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Opens the address the way a first-time visitor gets it: nothing from the HTTP cache and no
|
|
69
|
+
* service worker in between. Nothing is deleted, so on a real phone the owner's cache, cookies and
|
|
70
|
+
* sign-ins stay as they were. Connections the browser already holds open may be reused.
|
|
71
|
+
*/
|
|
72
|
+
export async function coldLoad(page, url, options = {}) {
|
|
73
|
+
const cdp = await sessionOf(page);
|
|
74
|
+
await cdp.send('Network.enable');
|
|
75
|
+
await cdp.send('Network.setCacheDisabled', { cacheDisabled: true });
|
|
76
|
+
await cdp.send('Network.setBypassServiceWorker', { bypass: true });
|
|
77
|
+
const vitals = await watchVitals(page);
|
|
78
|
+
try {
|
|
79
|
+
await page.goto(url, { waitUntil: 'load', timeout: options.timeout ?? 60_000 });
|
|
80
|
+
// The largest paint and late shifts often land after the load event.
|
|
81
|
+
await page.waitForTimeout(options.settle ?? 2000);
|
|
82
|
+
return await vitals.read();
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
await cdp.send('Network.setCacheDisabled', { cacheDisabled: false }).catch(() => { });
|
|
86
|
+
await cdp.send('Network.setBypassServiceWorker', { bypass: false }).catch(() => { });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* The longest time between two pictures in a row while the page was moving. The wait before the
|
|
91
|
+
* motion starts is not a pause in it, and neither is what happens after the page has come to
|
|
92
|
+
* rest, such as a scroll bar fading out a third of a second later. `until` is when the page last
|
|
93
|
+
* scrolled, on the frames' clock; without it every frame after the first counts.
|
|
94
|
+
*/
|
|
95
|
+
export function longestPauseOf(frames, until = null) {
|
|
96
|
+
let longest = 0;
|
|
97
|
+
for (let i = 2; i < frames.length; i++) {
|
|
98
|
+
const [before, now] = [frames[i - 1].at, frames[i].at];
|
|
99
|
+
if (until !== null && before >= until)
|
|
100
|
+
break;
|
|
101
|
+
// A pause that begins while the page moves and ends after it stopped counts up to the stop:
|
|
102
|
+
// a freeze at the very end of a fling is still a freeze.
|
|
103
|
+
longest = Math.max(longest, (until === null ? now : Math.min(now, until)) - before);
|
|
104
|
+
}
|
|
105
|
+
return longest;
|
|
106
|
+
}
|
|
107
|
+
/** Runs in the page: notes the wall-clock time of every scroll, of the document or of anything inside it. */
|
|
108
|
+
export const SCROLL_WATCH = `(() => {
|
|
109
|
+
window.__playwrightTouchScrolled = null;
|
|
110
|
+
window.__playwrightTouchTouched = false;
|
|
111
|
+
if (window.__playwrightTouchScrollWatch) return;
|
|
112
|
+
window.__playwrightTouchScrollWatch = true;
|
|
113
|
+
// Bringing an element into view before a gesture scrolls the page as well. Only what scrolls
|
|
114
|
+
// after the first touch, wheel turn, click or key belongs to the action.
|
|
115
|
+
for (const type of ['touchstart', 'wheel', 'pointerdown', 'keydown']) addEventListener(type, () => { window.__playwrightTouchTouched = true; }, { capture: true, passive: true });
|
|
116
|
+
addEventListener('scroll', () => { if (window.__playwrightTouchTouched) window.__playwrightTouchScrolled = performance.timeOrigin + performance.now(); }, { capture: true, passive: true });
|
|
117
|
+
})()`;
|
|
118
|
+
export const SCROLL_READ = 'window.__playwrightTouchScrolled ?? null';
|
|
119
|
+
const watched = new WeakSet();
|
|
120
|
+
/**
|
|
121
|
+
* Records what the screen shows while `action` runs, and for `settle` milliseconds after, so that
|
|
122
|
+
* momentum and late paints are in the picture. The browser sends a frame whenever the picture
|
|
123
|
+
* changes, each with the time it was drawn.
|
|
124
|
+
*/
|
|
125
|
+
export async function film(page, action, options = {}) {
|
|
126
|
+
const cdp = await sessionOf(page);
|
|
127
|
+
const frames = [];
|
|
128
|
+
let origin = null;
|
|
129
|
+
const onFrame = (frame) => {
|
|
130
|
+
const stamp = (frame.metadata.timestamp ?? Date.now() / 1000) * 1000;
|
|
131
|
+
origin ??= stamp;
|
|
132
|
+
frames.push({ at: Math.round(stamp - origin), jpeg: Buffer.from(frame.data, 'base64') });
|
|
133
|
+
void cdp.send('Page.screencastFrameAck', { sessionId: frame.sessionId }).catch(() => { });
|
|
134
|
+
};
|
|
135
|
+
cdp.on('Page.screencastFrame', onFrame);
|
|
136
|
+
const started = Date.now();
|
|
137
|
+
let scrolled = null;
|
|
138
|
+
try {
|
|
139
|
+
// The scroll bar fades out a third of a second after the page has come to rest, which would
|
|
140
|
+
// show up as one long pause at the end of every film. Without it the last frame is the last motion.
|
|
141
|
+
await cdp.send('Emulation.setScrollbarsHidden', { hidden: true }).catch(() => undefined);
|
|
142
|
+
// Also for every page the action goes on to, so a film across a navigation still knows what
|
|
143
|
+
// scrolled. Once per page: an init script cannot be taken back.
|
|
144
|
+
if (!watched.has(page)) {
|
|
145
|
+
watched.add(page);
|
|
146
|
+
await page.addInitScript({ content: SCROLL_WATCH }).catch(() => undefined);
|
|
147
|
+
}
|
|
148
|
+
await page.evaluate(SCROLL_WATCH).catch(() => undefined);
|
|
149
|
+
await cdp.send('Page.startScreencast', {
|
|
150
|
+
format: 'jpeg',
|
|
151
|
+
quality: options.quality ?? 60,
|
|
152
|
+
maxWidth: options.width ?? 360,
|
|
153
|
+
maxHeight: 4000,
|
|
154
|
+
everyNthFrame: 1,
|
|
155
|
+
});
|
|
156
|
+
await action();
|
|
157
|
+
await page.waitForTimeout(options.settle ?? 1500);
|
|
158
|
+
scrolled = await page.evaluate(SCROLL_READ).catch(() => null);
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
await cdp.send('Page.stopScreencast').catch(() => { });
|
|
162
|
+
await cdp.send('Emulation.setScrollbarsHidden', { hidden: false }).catch(() => undefined);
|
|
163
|
+
cdp.off('Page.screencastFrame', onFrame);
|
|
164
|
+
}
|
|
165
|
+
// The frames and the page's own clock both count from 1970, so they can be compared directly.
|
|
166
|
+
const scrolledFor = scrolled !== null && origin !== null ? Math.max(0, Math.round(scrolled - origin)) : null;
|
|
167
|
+
return {
|
|
168
|
+
frames,
|
|
169
|
+
duration: Date.now() - started,
|
|
170
|
+
longestPause: longestPauseOf(frames, scrolledFor === null ? null : scrolledFor + 34),
|
|
171
|
+
scrolledFor,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Listens on a local port and relays to the browser at `browserPort`, hiding every tab that was
|
|
3
|
+
* already open. Returns the port to connect to and a way to shut the relay down.
|
|
4
|
+
*/
|
|
5
|
+
export declare function ownTabsOnly(browserPort: number): Promise<{
|
|
6
|
+
port: number;
|
|
7
|
+
close(): void;
|
|
8
|
+
}>;
|
package/dist/own-tabs.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// A small stand-in for Chrome's debugging address that shows a client only the tabs it opens itself.
|
|
2
|
+
//
|
|
3
|
+
// Playwright attaches to every tab it is shown. On somebody's phone that means their tabs, and a
|
|
4
|
+
// single tab that has not loaded yet (Android keeps background tabs unloaded) makes the connection
|
|
5
|
+
// wait for ever. Here the owner's tabs are never attached to and never listed, so they can neither
|
|
6
|
+
// be read nor get in the way.
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { createServer } from 'node:http';
|
|
9
|
+
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
10
|
+
/** Writes one unfragmented WebSocket text frame, as a server (unmasked). */
|
|
11
|
+
function frame(text, opcode = 1) {
|
|
12
|
+
const body = Buffer.from(text);
|
|
13
|
+
const head = body.length < 126
|
|
14
|
+
? Buffer.from([0x80 | opcode, body.length])
|
|
15
|
+
: body.length < 65536
|
|
16
|
+
? Buffer.from([0x80 | opcode, 126, body.length >> 8, body.length & 255])
|
|
17
|
+
: Buffer.concat([Buffer.from([0x80 | opcode, 127]), bigLength(body.length)]);
|
|
18
|
+
return Buffer.concat([head, body]);
|
|
19
|
+
}
|
|
20
|
+
function bigLength(length) {
|
|
21
|
+
const out = Buffer.alloc(8);
|
|
22
|
+
out.writeBigUInt64BE(BigInt(length));
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
/** Reads the client's (masked) frames from a socket and hands over whole text messages. */
|
|
26
|
+
function reader(socket, onText, onClose) {
|
|
27
|
+
let pending = Buffer.alloc(0);
|
|
28
|
+
let parts = [];
|
|
29
|
+
socket.on('data', (chunk) => {
|
|
30
|
+
pending = Buffer.concat([pending, chunk]);
|
|
31
|
+
for (;;) {
|
|
32
|
+
if (pending.length < 2)
|
|
33
|
+
return;
|
|
34
|
+
const opcode = pending[0] & 15;
|
|
35
|
+
const final = (pending[0] & 0x80) !== 0;
|
|
36
|
+
const masked = (pending[1] & 0x80) !== 0;
|
|
37
|
+
let length = pending[1] & 127;
|
|
38
|
+
let offset = 2;
|
|
39
|
+
if (length === 126) {
|
|
40
|
+
if (pending.length < 4)
|
|
41
|
+
return;
|
|
42
|
+
length = pending.readUInt16BE(2);
|
|
43
|
+
offset = 4;
|
|
44
|
+
}
|
|
45
|
+
else if (length === 127) {
|
|
46
|
+
if (pending.length < 10)
|
|
47
|
+
return;
|
|
48
|
+
length = Number(pending.readBigUInt64BE(2));
|
|
49
|
+
offset = 10;
|
|
50
|
+
}
|
|
51
|
+
const start = offset + (masked ? 4 : 0);
|
|
52
|
+
if (pending.length < start + length)
|
|
53
|
+
return;
|
|
54
|
+
const body = Buffer.from(pending.subarray(start, start + length));
|
|
55
|
+
if (masked)
|
|
56
|
+
for (let i = 0; i < body.length; i++)
|
|
57
|
+
body[i] ^= pending[offset + (i & 3)];
|
|
58
|
+
pending = pending.subarray(start + length);
|
|
59
|
+
if (opcode === 8)
|
|
60
|
+
return onClose();
|
|
61
|
+
if (opcode === 9)
|
|
62
|
+
socket.write(frame(body.toString(), 10));
|
|
63
|
+
if (opcode <= 2) {
|
|
64
|
+
parts.push(body);
|
|
65
|
+
if (final) {
|
|
66
|
+
onText(Buffer.concat(parts).toString());
|
|
67
|
+
parts = [];
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
socket.on('close', onClose);
|
|
73
|
+
socket.on('error', onClose);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Listens on a local port and relays to the browser at `browserPort`, hiding every tab that was
|
|
77
|
+
* already open. Returns the port to connect to and a way to shut the relay down.
|
|
78
|
+
*/
|
|
79
|
+
export async function ownTabsOnly(browserPort) {
|
|
80
|
+
if (typeof WebSocket !== 'function')
|
|
81
|
+
throw new Error('playwright-touch: connecting to a phone needs Node.js 22 or newer.');
|
|
82
|
+
const version = (await (await fetch(`http://127.0.0.1:${browserPort}/json/version`, { signal: AbortSignal.timeout(3000) })).json());
|
|
83
|
+
const browserUrl = version.webSocketDebuggerUrl.replace(/^ws:\/\/[^/]+/, `ws://127.0.0.1:${browserPort}`);
|
|
84
|
+
const sockets = new Set();
|
|
85
|
+
const upstreams = new Set();
|
|
86
|
+
const server = createServer((_request, response) => {
|
|
87
|
+
// Playwright asks here for the address of the socket; it gets ours.
|
|
88
|
+
const address = server.address();
|
|
89
|
+
const port = typeof address === 'object' && address ? address.port : 0;
|
|
90
|
+
response
|
|
91
|
+
.writeHead(200, { 'content-type': 'application/json' })
|
|
92
|
+
.end(JSON.stringify({ ...version, webSocketDebuggerUrl: `ws://127.0.0.1:${port}/devtools/browser` }));
|
|
93
|
+
});
|
|
94
|
+
server.on('upgrade', (request, socket) => {
|
|
95
|
+
const key = request.headers['sec-websocket-key'];
|
|
96
|
+
if (!key) {
|
|
97
|
+
socket.destroy();
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
sockets.add(socket);
|
|
101
|
+
const upstream = new WebSocket(browserUrl);
|
|
102
|
+
upstreams.add(upstream);
|
|
103
|
+
// Tabs are told apart by where they come from. A tab is the client's when the client asked the
|
|
104
|
+
// browser for it, or when one of the client's tabs opened it. Every other tab is the owner's,
|
|
105
|
+
// whether it was open before we arrived or appears later.
|
|
106
|
+
const ours = new Set();
|
|
107
|
+
const creating = new Set();
|
|
108
|
+
/** Sessions on the browser itself, as opposed to on a tab. What they report about tabs is filtered like the main connection. */
|
|
109
|
+
const browserSessions = new Set();
|
|
110
|
+
const attachingToBrowser = new Set();
|
|
111
|
+
/** News about tabs that arrived while the client was waiting for a tab it asked for: it may be that tab, or the owner's. */
|
|
112
|
+
let held = [];
|
|
113
|
+
const early = [];
|
|
114
|
+
let ready = false;
|
|
115
|
+
// Requests of our own use ids far below anything a client sends, so the answers can be told apart.
|
|
116
|
+
let own = -1;
|
|
117
|
+
const overBrowser = (sessionId) => !sessionId || browserSessions.has(sessionId);
|
|
118
|
+
const fromClient = (text) => {
|
|
119
|
+
const message = JSON.parse(text);
|
|
120
|
+
if (typeof message.id === 'number') {
|
|
121
|
+
if (message.method === 'Target.createTarget')
|
|
122
|
+
creating.add(message.id);
|
|
123
|
+
if (message.method === 'Target.attachToBrowserTarget')
|
|
124
|
+
attachingToBrowser.add(message.id);
|
|
125
|
+
}
|
|
126
|
+
// A client that names a tab which is not its own is told there is no such tab.
|
|
127
|
+
if (overBrowser(message.sessionId) &&
|
|
128
|
+
message.method?.startsWith('Target.') &&
|
|
129
|
+
message.params?.targetId &&
|
|
130
|
+
!ours.has(message.params.targetId)) {
|
|
131
|
+
socket.write(frame(JSON.stringify({
|
|
132
|
+
id: message.id,
|
|
133
|
+
sessionId: message.sessionId,
|
|
134
|
+
error: { code: -32602, message: 'No target with given id found' },
|
|
135
|
+
})));
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
upstream.send(text);
|
|
139
|
+
};
|
|
140
|
+
const toBrowser = (text) => (ready ? fromClient(text) : early.push(text));
|
|
141
|
+
const done = () => {
|
|
142
|
+
sockets.delete(socket);
|
|
143
|
+
upstreams.delete(upstream);
|
|
144
|
+
socket.destroy();
|
|
145
|
+
if (upstream.readyState <= 1)
|
|
146
|
+
upstream.close();
|
|
147
|
+
};
|
|
148
|
+
/** Lets go of an owner's tab the browser attached us to, without leaving it waiting for a debugger. */
|
|
149
|
+
const letGo = (message) => {
|
|
150
|
+
if (message.method !== 'Target.attachedToTarget' || !message.params?.sessionId)
|
|
151
|
+
return;
|
|
152
|
+
// A new tab is held until its debugger says go. Nobody else will, so say it before leaving,
|
|
153
|
+
// or the owner's new tab would stay blank for as long as we are connected.
|
|
154
|
+
upstream.send(JSON.stringify({ id: own--, method: 'Runtime.runIfWaitingForDebugger', sessionId: message.params.sessionId }));
|
|
155
|
+
upstream.send(JSON.stringify({
|
|
156
|
+
id: own--,
|
|
157
|
+
method: 'Target.detachFromTarget',
|
|
158
|
+
params: { sessionId: message.params.sessionId },
|
|
159
|
+
}));
|
|
160
|
+
};
|
|
161
|
+
upstream.addEventListener('open', () => upstream.send(JSON.stringify({ id: own--, method: 'Target.getTargets' })));
|
|
162
|
+
upstream.addEventListener('close', done);
|
|
163
|
+
upstream.addEventListener('error', done);
|
|
164
|
+
upstream.addEventListener('message', (event) => {
|
|
165
|
+
let text = String(event.data);
|
|
166
|
+
const message = JSON.parse(text);
|
|
167
|
+
if (typeof message.id === 'number' && message.id < 0) {
|
|
168
|
+
// The answer to our opening question marks the moment from which requests are passed on.
|
|
169
|
+
// Any answer will do, an error included: what matters is that the browser is listening.
|
|
170
|
+
if (!ready) {
|
|
171
|
+
ready = true;
|
|
172
|
+
for (const waiting of early.splice(0))
|
|
173
|
+
fromClient(waiting);
|
|
174
|
+
}
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (typeof message.id === 'number') {
|
|
178
|
+
if (attachingToBrowser.delete(message.id) && message.result?.sessionId)
|
|
179
|
+
browserSessions.add(message.result.sessionId);
|
|
180
|
+
if (creating.delete(message.id)) {
|
|
181
|
+
if (message.result?.targetId)
|
|
182
|
+
ours.add(message.result.targetId);
|
|
183
|
+
// What was held back is now known for what it is. The client's own tab is announced
|
|
184
|
+
// before the answer, the order a client expects; with no request left open, the rest is the owner's.
|
|
185
|
+
const waiting = held;
|
|
186
|
+
held = [];
|
|
187
|
+
for (const one of waiting) {
|
|
188
|
+
if (ours.has(one.targetId))
|
|
189
|
+
socket.write(frame(one.text));
|
|
190
|
+
else if (creating.size > 0)
|
|
191
|
+
held.push(one);
|
|
192
|
+
else
|
|
193
|
+
letGo(one.message);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
// A list of tabs is passed on with the client's own tabs only.
|
|
197
|
+
if (message.result?.targetInfos) {
|
|
198
|
+
message.result.targetInfos = message.result.targetInfos.filter((info) => ours.has(info.targetId) || info.type === 'browser');
|
|
199
|
+
text = JSON.stringify(message);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const info = message.params?.targetInfo;
|
|
203
|
+
const targetId = info?.targetId ?? message.params?.targetId;
|
|
204
|
+
// The browser itself is a target too, the one a client attaches to for a session of its own.
|
|
205
|
+
if (overBrowser(message.sessionId) &&
|
|
206
|
+
message.method?.startsWith('Target.') &&
|
|
207
|
+
targetId &&
|
|
208
|
+
info?.type !== 'browser' &&
|
|
209
|
+
!ours.has(targetId)) {
|
|
210
|
+
if (info?.openerId && ours.has(info.openerId)) {
|
|
211
|
+
ours.add(targetId);
|
|
212
|
+
}
|
|
213
|
+
else if (creating.size > 0) {
|
|
214
|
+
held.push({ text, message, targetId });
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
letGo(message);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
socket.write(frame(text));
|
|
223
|
+
});
|
|
224
|
+
socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${createHash('sha1')
|
|
225
|
+
.update(key + GUID)
|
|
226
|
+
.digest('base64')}\r\n\r\n`);
|
|
227
|
+
reader(socket, toBrowser, done);
|
|
228
|
+
});
|
|
229
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
230
|
+
const address = server.address();
|
|
231
|
+
return {
|
|
232
|
+
port: typeof address === 'object' && address ? address.port : 0,
|
|
233
|
+
close() {
|
|
234
|
+
for (const upstream of upstreams)
|
|
235
|
+
if (upstream.readyState <= 1)
|
|
236
|
+
upstream.close();
|
|
237
|
+
for (const socket of sockets)
|
|
238
|
+
socket.destroy();
|
|
239
|
+
server.close();
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { expect } from '@playwright/test';
|
|
2
|
+
import type { Locator } from '@playwright/test';
|
|
3
|
+
import type { SwipeUntilOptions } from './recipes.js';
|
|
4
|
+
import type { DirectedOptions, Direction, DragOptions, GestureOptions, PinchOptions, Point, RotateOptions, StrokeOptions } from './types.js';
|
|
5
|
+
type Stroke = StrokeOptions | DirectedOptions;
|
|
6
|
+
type Spot = Locator | Point;
|
|
7
|
+
type TwoFingerOptions = {
|
|
8
|
+
direction: Direction;
|
|
9
|
+
distance?: number;
|
|
10
|
+
gap?: number;
|
|
11
|
+
duration?: number;
|
|
12
|
+
};
|
|
13
|
+
/** The gestures, already aimed at the test's page. */
|
|
14
|
+
export interface Touch {
|
|
15
|
+
/** A quick touch that the browser turns into a click. */
|
|
16
|
+
tap(target: Spot): Promise<void>;
|
|
17
|
+
/** Two quick taps on the same place. */
|
|
18
|
+
doubleTap(target: Spot): Promise<void>;
|
|
19
|
+
/** Rests one finger on the target without moving. */
|
|
20
|
+
longPress(target: Spot, options?: {
|
|
21
|
+
duration?: number;
|
|
22
|
+
}): Promise<void>;
|
|
23
|
+
/** A stroke that stops before the finger lifts. Across the page, or across an element. */
|
|
24
|
+
swipe(options: Stroke): Promise<void>;
|
|
25
|
+
swipe(target: Locator, options: Stroke): Promise<void>;
|
|
26
|
+
/** A flick that leaves the content scrolling on its momentum. Across the page, or across an element. */
|
|
27
|
+
fling(options: Stroke): Promise<void>;
|
|
28
|
+
fling(target: Locator, options: Stroke): Promise<void>;
|
|
29
|
+
/** Carries the source to the destination under one finger. */
|
|
30
|
+
drag(source: Spot, destination: Spot, options?: DragOptions): Promise<void>;
|
|
31
|
+
/** Two fingers spreading or closing, on the page or on an element. */
|
|
32
|
+
pinch(options: PinchOptions): Promise<void>;
|
|
33
|
+
pinch(target: Locator, options: PinchOptions): Promise<void>;
|
|
34
|
+
/** Two fingers turning around the middle of an element. */
|
|
35
|
+
rotate(target: Locator, options: RotateOptions): Promise<void>;
|
|
36
|
+
/** Any gesture, given as the path of each finger. */
|
|
37
|
+
gesture(options: GestureOptions): Promise<void>;
|
|
38
|
+
/** Swipes until the middle of the target is in view. Resolves to the number of swipes it took. */
|
|
39
|
+
swipeUntilVisible(target: Locator, options?: SwipeUntilOptions): Promise<number>;
|
|
40
|
+
/** Pulls the page down from near its top. */
|
|
41
|
+
pullToRefresh(options?: {
|
|
42
|
+
distance?: number;
|
|
43
|
+
duration?: number;
|
|
44
|
+
}): Promise<void>;
|
|
45
|
+
/** A stroke that starts on an edge of the screen and comes inward. */
|
|
46
|
+
edgeSwipe(options: {
|
|
47
|
+
edge: 'left' | 'right' | 'top' | 'bottom';
|
|
48
|
+
distance?: number;
|
|
49
|
+
duration?: number;
|
|
50
|
+
inset?: number;
|
|
51
|
+
}): Promise<void>;
|
|
52
|
+
/** Two fingers moving side by side, on the page or on an element. */
|
|
53
|
+
twoFingerSwipe(options: TwoFingerOptions): Promise<void>;
|
|
54
|
+
twoFingerSwipe(target: Locator, options: TwoFingerOptions): Promise<void>;
|
|
55
|
+
}
|
|
56
|
+
/** Settings of the `touch` fixture, set with `test.use({ touchOptions: { ... } })` or in the config. */
|
|
57
|
+
export interface TouchOptions {
|
|
58
|
+
/** Draws a dot under every finger, so a video or a trace shows where the page was touched. */
|
|
59
|
+
showFingers: boolean;
|
|
60
|
+
}
|
|
61
|
+
/** Playwright's `test` with a `touch` fixture. Combine it with your own fixtures through `mergeTests`. */
|
|
62
|
+
export declare const test: import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions & {
|
|
63
|
+
touch: Touch;
|
|
64
|
+
touchOptions: TouchOptions;
|
|
65
|
+
}, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
|
|
66
|
+
export { expect };
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// The gestures as a Playwright Test fixture. A test asks for `touch` next to `page` and each gesture
|
|
2
|
+
// shows up as its own step in the report and in the trace:
|
|
3
|
+
//
|
|
4
|
+
// import { test, expect } from 'playwright-touch/test';
|
|
5
|
+
//
|
|
6
|
+
// test('the carousel moves', async ({ page, touch }) => {
|
|
7
|
+
// await page.goto('/');
|
|
8
|
+
// await touch.swipe(page.locator('#carousel'), { direction: 'left' });
|
|
9
|
+
// });
|
|
10
|
+
//
|
|
11
|
+
// This is the one file of the package that imports Playwright Test, so a project that uses only
|
|
12
|
+
// `playwright-core` never loads it.
|
|
13
|
+
import { test as base, expect } from '@playwright/test';
|
|
14
|
+
import * as gestures from './index.js';
|
|
15
|
+
const isLocator = (value) => !!value && typeof value.boundingBox === 'function';
|
|
16
|
+
const nameOf = (target) => isLocator(target) ? String(target) : `(${Math.round(target.x)}, ${Math.round(target.y)})`;
|
|
17
|
+
const strokeOf = (options) => 'direction' in options
|
|
18
|
+
? `${options.direction}${options.distance === undefined ? '' : ` ${options.distance} px`}`
|
|
19
|
+
: `${nameOf(options.from)} to ${nameOf(options.to)}`;
|
|
20
|
+
function touchOn(page) {
|
|
21
|
+
// Boxed, so a gesture that fails is reported on the line of the test that made it.
|
|
22
|
+
const step = (title, body) => base.step(`touch.${title}`, body, { box: true });
|
|
23
|
+
// A bare point does not say which page it is on; the fixture knows.
|
|
24
|
+
const pointed = (...targets) => (targets.every(isLocator) ? {} : { page });
|
|
25
|
+
// The optional first argument: an element to act on, or the options alone for the whole page.
|
|
26
|
+
const split = (first, second) => second === undefined ? [page, first, 'page'] : [first, second, String(first)];
|
|
27
|
+
return {
|
|
28
|
+
tap: (target) => step(`tap ${nameOf(target)}`, () => gestures.tap(target, pointed(target))),
|
|
29
|
+
doubleTap: (target) => step(`doubleTap ${nameOf(target)}`, () => gestures.doubleTap(target, pointed(target))),
|
|
30
|
+
longPress: (target, options = {}) => step(`longPress ${nameOf(target)}`, () => gestures.longPress(target, { ...options, ...pointed(target) })),
|
|
31
|
+
swipe: (first, second) => {
|
|
32
|
+
const [target, options, where] = split(first, second);
|
|
33
|
+
return step(`swipe ${strokeOf(options)} on ${where}`, () => gestures.swipe(target, options));
|
|
34
|
+
},
|
|
35
|
+
fling: (first, second) => {
|
|
36
|
+
const [target, options, where] = split(first, second);
|
|
37
|
+
return step(`fling ${strokeOf(options)} on ${where}`, () => gestures.fling(target, options));
|
|
38
|
+
},
|
|
39
|
+
drag: (source, destination, options = {}) => step(`drag ${nameOf(source)} to ${nameOf(destination)}`, () => gestures.drag(source, destination, { ...options, ...pointed(source, destination) })),
|
|
40
|
+
pinch: (first, second) => {
|
|
41
|
+
const [target, options, where] = split(first, second);
|
|
42
|
+
return step(`pinch ×${options.scale} on ${where}`, () => gestures.pinch(target, options));
|
|
43
|
+
},
|
|
44
|
+
rotate: (target, options) => step(`rotate ${options.degrees}° on ${String(target)}`, () => gestures.rotate(target, options)),
|
|
45
|
+
gesture: (options) => step(`gesture with ${options.fingers.length} finger${options.fingers.length === 1 ? '' : 's'}`, () => gestures.gesture(page, options)),
|
|
46
|
+
swipeUntilVisible: (target, options = {}) => step(`swipeUntilVisible ${String(target)}`, () => gestures.swipeUntilVisible(target, options)),
|
|
47
|
+
pullToRefresh: (options = {}) => step('pullToRefresh', () => gestures.pullToRefresh(page, options)),
|
|
48
|
+
edgeSwipe: (options) => step(`edgeSwipe from the ${options.edge}`, () => gestures.edgeSwipe(page, options)),
|
|
49
|
+
twoFingerSwipe: (first, second) => {
|
|
50
|
+
const [target, options, where] = split(first, second);
|
|
51
|
+
return step(`twoFingerSwipe ${options.direction} on ${where}`, () => gestures.twoFingerSwipe(target, options));
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** Playwright's `test` with a `touch` fixture. Combine it with your own fixtures through `mergeTests`. */
|
|
56
|
+
export const test = base.extend({
|
|
57
|
+
touchOptions: [{ showFingers: false }, { option: true }],
|
|
58
|
+
touch: async ({ page, touchOptions }, use) => {
|
|
59
|
+
if (touchOptions.showFingers)
|
|
60
|
+
await gestures.showTouches(page);
|
|
61
|
+
await use(touchOn(page));
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
export { expect };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Point } from './types.js';
|
|
2
|
+
/** The length of the way through the points. */
|
|
3
|
+
export declare function lengthOf(points: Point[]): number;
|
|
4
|
+
/**
|
|
5
|
+
* The way through the points as a function of progress: 0 is the first point, 1 the last, and
|
|
6
|
+
* equal steps of progress are equal lengths of the way, however unevenly the points are spaced.
|
|
7
|
+
*/
|
|
8
|
+
export declare function along(points: Point[]): (k: number) => Point;
|
|
9
|
+
/** Points on a circle around `centre`, from one angle to another, one about every four degrees. Angles in degrees, clockwise from the right. */
|
|
10
|
+
export declare function arc(centre: Point, radius: number, from: number, to: number): Point[];
|
package/dist/polyline.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** The length of the way through the points. */
|
|
2
|
+
export function lengthOf(points) {
|
|
3
|
+
let length = 0;
|
|
4
|
+
for (let i = 1; i < points.length; i++)
|
|
5
|
+
length += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
|
|
6
|
+
return length;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The way through the points as a function of progress: 0 is the first point, 1 the last, and
|
|
10
|
+
* equal steps of progress are equal lengths of the way, however unevenly the points are spaced.
|
|
11
|
+
*/
|
|
12
|
+
export function along(points) {
|
|
13
|
+
if (points.length === 0)
|
|
14
|
+
throw new Error('playwright-touch: a finger needs at least one point to be at.');
|
|
15
|
+
const total = lengthOf(points);
|
|
16
|
+
if (total === 0)
|
|
17
|
+
return () => points[0];
|
|
18
|
+
return (k) => {
|
|
19
|
+
let left = Math.min(1, Math.max(0, k)) * total;
|
|
20
|
+
for (let i = 1; i < points.length; i++) {
|
|
21
|
+
const [from, to] = [points[i - 1], points[i]];
|
|
22
|
+
const piece = Math.hypot(to.x - from.x, to.y - from.y);
|
|
23
|
+
if (left <= piece && piece > 0) {
|
|
24
|
+
return { x: from.x + ((to.x - from.x) * left) / piece, y: from.y + ((to.y - from.y) * left) / piece };
|
|
25
|
+
}
|
|
26
|
+
left -= piece;
|
|
27
|
+
}
|
|
28
|
+
return points.at(-1);
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** Points on a circle around `centre`, from one angle to another, one about every four degrees. Angles in degrees, clockwise from the right. */
|
|
32
|
+
export function arc(centre, radius, from, to) {
|
|
33
|
+
const steps = Math.max(1, Math.ceil(Math.abs(to - from) / 4));
|
|
34
|
+
return Array.from({ length: steps + 1 }, (_, step) => {
|
|
35
|
+
const angle = ((from + ((to - from) * step) / steps) * Math.PI) / 180;
|
|
36
|
+
return { x: centre.x + radius * Math.cos(angle), y: centre.y + radius * Math.sin(angle) };
|
|
37
|
+
});
|
|
38
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { SharedPage } from './index.js';
|
|
2
|
+
import type { IosLocator, IosPage } from './ios/simulator.js';
|
|
3
|
+
import type { Locator, Page } from './session.js';
|
|
4
|
+
import type { Direction } from './types.js';
|
|
5
|
+
type AnyPage = Page | IosPage | SharedPage;
|
|
6
|
+
type AnyLocator = Locator | IosLocator;
|
|
7
|
+
export interface SwipeUntilOptions {
|
|
8
|
+
/** The way the finger travels. Content follows the finger, so `up` brings up what is below. Default `up`. */
|
|
9
|
+
direction?: Direction;
|
|
10
|
+
/** The scrolling element to swipe on. Default: the page. */
|
|
11
|
+
within?: AnyLocator;
|
|
12
|
+
/** The length of each stroke in pixels. Default: 60 % of the page or the element. */
|
|
13
|
+
distance?: number;
|
|
14
|
+
/** How many swipes to try before giving up. Default 10. */
|
|
15
|
+
max?: number;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Swipes until the middle of the target is inside the viewport, the way a person scrolls a list to
|
|
19
|
+
* find a row. Returns the number of swipes it took, 0 when the target was in view already. Fails
|
|
20
|
+
* when the content stops moving or the tries run out, and says which.
|
|
21
|
+
*/
|
|
22
|
+
export declare function swipeUntilVisible(target: AnyLocator, options?: SwipeUntilOptions): Promise<number>;
|
|
23
|
+
/**
|
|
24
|
+
* Pulls the page down from near its top, the gesture behind "pull to refresh". The finger comes to
|
|
25
|
+
* rest before it lifts, as a thumb does. The page should be scrolled to its top first.
|
|
26
|
+
*/
|
|
27
|
+
export declare function pullToRefresh(page: AnyPage, options?: {
|
|
28
|
+
distance?: number;
|
|
29
|
+
duration?: number;
|
|
30
|
+
}): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* A stroke that starts on an edge of the screen and comes inward, as for a side drawer or a sheet
|
|
33
|
+
* that is pulled up from the bottom. It starts `inset` pixels from the edge, 2 by default.
|
|
34
|
+
*
|
|
35
|
+
* On a real phone the outermost strip of the screen belongs to the system: in Safari on an iPhone a
|
|
36
|
+
* stroke from the left or right edge goes back or forward in history and the page never sees it,
|
|
37
|
+
* as under a real finger. To reach a drawer of the page there, start further in. On an iPhone 12
|
|
38
|
+
* Pro with iOS 17.5 a start 2 px from the left edge went back and one 6 px from it reached the
|
|
39
|
+
* page; `inset: 20` leaves room.
|
|
40
|
+
*/
|
|
41
|
+
export declare function edgeSwipe(page: AnyPage, options: {
|
|
42
|
+
edge: 'left' | 'right' | 'top' | 'bottom';
|
|
43
|
+
distance?: number;
|
|
44
|
+
duration?: number;
|
|
45
|
+
inset?: number;
|
|
46
|
+
}): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* Two fingers moving side by side, for maps and embeds that keep one finger for the page and ask
|
|
49
|
+
* for two to move themselves.
|
|
50
|
+
*/
|
|
51
|
+
export declare function twoFingerSwipe(target: AnyPage | AnyLocator, options: {
|
|
52
|
+
direction: Direction;
|
|
53
|
+
distance?: number;
|
|
54
|
+
gap?: number;
|
|
55
|
+
duration?: number;
|
|
56
|
+
}): Promise<void>;
|
|
57
|
+
export {};
|