cuetake 0.3.0 → 0.5.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/src/desktop.js ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * The Desktop of a Take of Apps (ADR 0009), shared by Node and the render page. Pure functions, no imports.
3
+ *
4
+ * The Source shows the Desktop: the windows of the Take's Apps where they are, in their real order, on
5
+ * nothing. The Timeline's `windows` lists which show over time, each state `{ t, shown }` lasting until
6
+ * the next, `shown` back to front as `{ id, app, layer, x, y, width, height, radius }` (`app` indexes
7
+ * the Timeline's `apps`) in Desktop points from its top-left corner,
8
+ * which play the role of CSS pixels. Render draws the Source only inside these windows, so the
9
+ * Background shows between them.
10
+ */
11
+
12
+ /** The windows showing at Source time `t`, back to front. */
13
+ export function windowsAt(windows, t) {
14
+ return (windows ?? []).findLast(state => state.t <= t)?.shown ?? windows?.[0]?.shown ?? [];
15
+ }
16
+
17
+ /**
18
+ * Where `shown` windows are drawn: each clipped to the Desktop (`viewport`, in points), then placed on
19
+ * `page`, the Desktop's rectangle in stage pixels, with its corner radius in stage pixels. A window
20
+ * wholly outside the Desktop is left out. Only a window over no other window drawn under it has the
21
+ * window `effects` (its shadow) around it: the Source already shows the shadow a menu, a sheet or a
22
+ * control's own window casts on the window below.
23
+ */
24
+ export function drawnWindows(shown, viewport, page) {
25
+ const scale = page.w / viewport.width, drawn = [];
26
+ for (const { id, x, y, width, height, radius } of shown) {
27
+ const left = Math.max(0, x), top = Math.max(0, y), right = Math.min(viewport.width, x + width), bottom = Math.min(viewport.height, y + height);
28
+ if (right <= left || bottom <= top) continue;
29
+ const w = right - left, h = bottom - top, window = { x: page.x + left * scale, y: page.y + top * scale, w: w * scale, h: h * scale };
30
+ const over = drawn.some(({ window: under }) => window.x >= under.x && window.y >= under.y && window.x + window.w <= under.x + under.w && window.y + window.h <= under.y + under.h);
31
+ drawn.push({ id, window, radius: Math.min(radius, w / 2, h / 2) * scale, effects: !over });
32
+ }
33
+ return drawn;
34
+ }
35
+
36
+ // The narrowest empty stretch of a title bar a person would aim a click at, in points.
37
+ const TITLE_BAR_MIN = 12;
38
+
39
+ /**
40
+ * Where to click a window's title bar to bring it in front, as a person would: the middle of the widest
41
+ * stretch where nothing lies, no control, no title and no window over it, from `bar`, the helper's
42
+ * samples along the title bar's middle (`{ y, samples: [[x, empty], ...] }`, Desktop points, left to
43
+ * right). Returns `{ x, y, width }`, the stretch's width as the target's size, or null where no stretch
44
+ * is wide enough.
45
+ */
46
+ export function titleBarSpot(bar) {
47
+ let best = null, from = null;
48
+ const samples = bar?.samples ?? [];
49
+ samples.forEach(([x, empty], i) => {
50
+ if (empty && from === null) from = x;
51
+ const last = empty && (i === samples.length - 1 || !samples[i + 1][1]);
52
+ if (last && (!best || x - from > best.width)) best = { from, width: x - from };
53
+ if (!empty) from = null;
54
+ });
55
+ if (!best || best.width < TITLE_BAR_MIN) return null;
56
+ return { x: best.from + best.width / 2, y: bar.y, width: best.width };
57
+ }
58
+
59
+ // How long macOS animates a window closing: TextEdit's shrank for about 70 ms.
60
+ const CLOSING_S = 0.3;
61
+ const at = t => `${t.toFixed(2)} s`;
62
+ const size = w => `${w.width}×${w.height}`;
63
+ const inside = (w, viewport) => w.x >= 0 && w.y >= 0 && w.x + w.width <= viewport.width && w.y + w.height <= viewport.height;
64
+
65
+ const OTHER_INPUT = { pointer: 'the pointer', key: 'a key', scroll: 'a scroll' };
66
+ const listed = times => times.slice(0, 5).map(at).join(', ') + (times.length > 5 ? ` and ${times.length - 5} more` : '');
67
+
68
+ /**
69
+ * What a Final of Apps shows other than as recorded: the first App's first window (the largest at the
70
+ * start) not filling the Desktop, when the Take has one App (with several, `prepare` arranges them), or
71
+ * moving or resizing later; any other window reaching outside the Desktop, which is cut off there; a
72
+ * Desktop recorded at scale 1 or across a change of scale; frames the encoder dropped; and input the
73
+ * Director did not make (`otherInput`, as [t, kind]), which the Timeline leaves out but the App may have
74
+ * reacted to. `capture` is the Tab's stats in capture.json.
75
+ */
76
+ export function desktopWarnings({ viewport, windows = [], duration = Infinity, apps = [] }, { frames = [], dropped = 0, otherInput = [] }) {
77
+ // The first window is the largest of the first App's first layer-0 windows to show: a dialog may show before it.
78
+ const layer0 = state => state.shown.filter(w => w.layer === 0 && !w.app);
79
+ const several = apps.length > 1, ofApp = w => several ? apps[w.app ?? 0]?.name ?? 'an App' : 'the App';
80
+ const warnings = [], first = layer0(windows.find(state => layer0(state).length) ?? { shown: [] }).sort((a, b) => b.width * b.height - a.width * a.height)[0];
81
+ const same = (a, b) => a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
82
+ if (first && !several && !same(first, { x: 0, y: 0, ...viewport })) warnings.push(`The App's first window is ${size(first)} points, not the Desktop's ${size(viewport)}, so the Background shows around it: the App may limit its size; choose a viewport it can fill.`);
83
+ // A closing window shrinks for a moment before it goes; a change it leaves within CLOSING_S of is that, not a move,
84
+ // and so is one within CLOSING_S of the Take's end, which may come before the window goes.
85
+ const showsFirst = state => state.shown.some(w => w.id === first.id);
86
+ const closing = state => duration - state.t <= CLOSING_S || windows.some(later => later.t > state.t && later.t - state.t <= CLOSING_S && !showsFirst(later));
87
+ const moved = first && windows.find(state => state.shown.some(w => w.id === first.id && !same(w, first)) && !closing(state));
88
+ if (moved) {
89
+ const w = moved.shown.find(w => w.id === first.id);
90
+ warnings.push(`At ${at(moved.t)} ${several ? `the first window of ${ofApp(w)}` : "the App's first window"} moved or resized, to ${w.x}, ${w.y}, ${size(w)} points; Render does not correct it, so leave it where the Take put it.`);
91
+ }
92
+ const reported = new Set([first?.id]);
93
+ for (const state of windows) for (const w of state.shown) {
94
+ if (reported.has(w.id) || inside(w, viewport)) continue;
95
+ reported.add(w.id);
96
+ warnings.push(`At ${at(state.t)} a window of ${ofApp(w)} (${size(w)} points) reached outside the Desktop, so the Final shows it cut off.`);
97
+ }
98
+ const scales = new Set(frames.map(frame => frame.scale));
99
+ if (scales.has(1)) warnings.push('The Desktop was recorded at scale 1, so the Final is half as sharp; record on a Retina display.');
100
+ if (scales.size > 1) warnings.push(`The Desktop's scale changed during the Take (${[...scales].join(', ')}), as when a window moves to another display; record again with the App on one display.`);
101
+ if (otherInput.length) {
102
+ const kinds = Object.keys(OTHER_INPUT).filter(kind => otherInput.some(([, k]) => k === kind));
103
+ const what = kinds.map(kind => `${OTHER_INPUT[kind]} at ${listed(otherInput.filter(([, k]) => k === kind).map(([t]) => t))}`).join('; ');
104
+ warnings.push(`Someone used the Mac during the Take: ${what}. The Final's Cursor follows only the Scenario, but the App may have reacted; check those moments with frame, or record again and leave the Mac alone.`);
105
+ }
106
+ if (dropped) warnings.push(`The encoder could not keep up and ${dropped} frames were dropped from the Source; close other work and record again.`);
107
+ return warnings;
108
+ }
package/src/director.js CHANGED
@@ -1,54 +1,414 @@
1
- /** Timed, viewport-aligned interactions shared by all scenarios. */
2
- export function createDirector(page, startedAt, fps, focusTargets, wideWindows) {
3
- let cursor = { x: 0, y: 0 };
4
- const wait = ms => page.waitForTimeout(Math.max(0, ms));
1
+ import { ease, landing, pauseMs, random, reach, scrollMs, typingDelays } from './motion.js';
2
+ import { boxOnPage, onPage, placeOf } from './frames.js';
3
+ import { carried, seenBy, windowMaps } from './tabs.js';
4
+ import { EFFECT_NAMES, MASK_EFFECTS } from './masks.js';
5
+
6
+ /** Milliseconds between the Director's checks of what a mask's locator matches, so a replaced element is followed. */
7
+ const REWATCH_MS = 100;
8
+
9
+ /** Refuses a mask effect masks.js does not draw. */
10
+ export function effectOf(effect) {
11
+ if (!(effect in MASK_EFFECTS)) throw new Error(`d.mask needs effect ${EFFECT_NAMES}, not '${effect}'`);
12
+ }
13
+
14
+ /**
15
+ * Notes a mask of the element `id` (in `notes.elements` and `notes.masks`) from `t`, and calls `watch`
16
+ * every REWATCH_MS until `signal` aborts, unless `skip()`, so the element is followed when its page or
17
+ * App replaces it. Returns the mask's handle, whose `end()` ends it at `time()`.
18
+ */
19
+ export function followMask({ id, tab, name, t, effect, params }, notes, { watch, skip = () => false, signal, time }) {
20
+ notes.elements.push({ id, tab, name });
21
+ const entry = { t, end: null, element: id, effect, ...params };
22
+ notes.masks.push(entry);
23
+ let busy = false;
24
+ const timer = setInterval(() => {
25
+ if (busy || skip()) return;
26
+ busy = true;
27
+ watch().catch(() => {}).finally(() => { busy = false; });
28
+ }, REWATCH_MS);
29
+ timer.unref?.();
30
+ signal?.addEventListener('abort', () => clearInterval(timer), { once: true });
31
+ if (signal?.aborted) clearInterval(timer);
32
+ return { end() { entry.end ??= time(); } };
33
+ }
34
+
35
+ /** Where `d.scroll` puts its target in what scrolls it, as scrollIntoView names them. */
36
+ const ALIGNS = ['start', 'center', 'end', 'nearest'];
37
+ // A scroll lands its target this share of the scrolled view from its edge, so it is not flush against it.
38
+ const SCROLL_MARGIN = 0.1;
39
+ // A container already scrolled once is scrolled again only to correct a target this far off, such as after images loaded above it.
40
+ const CORRECTION_PX = 4;
41
+
42
+ /**
43
+ * Runs in the target's frame: how a person would scroll to `target`, outermost container first. Each
44
+ * container that scrolls either way, the page last of all, is one step: it brings the next container in
45
+ * that scrolls the same way into view (`nearest`), or the target itself, by `block` and `inline`, where
46
+ * no container inside it does. Each step's `delta` is what is left to scroll, in its frame's CSS pixels,
47
+ * clamped to where the container can go; `aim` is null when a wheel at `point` reaches that container
48
+ * first, else a spot of it a wheel does reach, or false when none shows; `at` is its scroll position, to
49
+ * see that it moved. Null when the target shows no box.
50
+ */
51
+ function scrollPlan(target, { block, inline, point, margin }) {
52
+ if (!target.getClientRects().length) return null;
53
+ const page = document.scrollingElement ?? document.documentElement;
54
+ const parentOf = node => node.parentElement ?? node.getRootNode().host ?? null;
55
+ const scrolls = (e, axis) => {
56
+ const range = axis === 'y' ? e.scrollHeight - e.clientHeight : e.scrollWidth - e.clientWidth;
57
+ if (range < 1) return false;
58
+ if (e === page) return ![document.documentElement, document.body].some(root => root && /hidden|clip/.test(getComputedStyle(root)[axis === 'y' ? 'overflowY' : 'overflowX']));
59
+ return /auto|scroll|overlay/.test(getComputedStyle(e)[axis === 'y' ? 'overflowY' : 'overflowX']);
60
+ };
61
+ const containers = [];
62
+ for (let node = parentOf(target); node; node = parentOf(node)) if (node !== page && node instanceof Element && (scrolls(node, 'y') || scrolls(node, 'x'))) containers.push(node);
63
+ containers.push(page);
64
+ containers.reverse();
65
+ const viewOf = e => {
66
+ // The scrolling element's client size is the viewport's, less any scroll bars, in standards and quirks mode alike.
67
+ if (e === page) return { x: 0, y: 0, width: page.clientWidth, height: page.clientHeight };
68
+ const r = e.getBoundingClientRect();
69
+ return { x: r.x + e.clientLeft, y: r.y + e.clientTop, width: e.clientWidth, height: e.clientHeight };
70
+ };
71
+ const shown = v => {
72
+ const x = Math.max(0, v.x), y = Math.max(0, v.y), right = Math.min(innerWidth, v.x + v.width), bottom = Math.min(innerHeight, v.y + v.height);
73
+ return { x, y, width: Math.max(0, right - x), height: Math.max(0, bottom - y) };
74
+ };
75
+ const want = (subject, view, align, axis) => {
76
+ const r = subject.getBoundingClientRect();
77
+ const [low, size, start, length] = axis === 'y' ? [r.top, r.height, view.y, view.height] : [r.left, r.width, view.x, view.width];
78
+ const edge = margin * length, toStart = low - (start + edge), toEnd = low + size - (start + length - edge);
79
+ if (align === 'start') return toStart;
80
+ if (align === 'end') return toEnd;
81
+ if (align === 'center') return low + size / 2 - (start + length / 2);
82
+ if (toStart >= 0 && toEnd <= 0) return 0;
83
+ return toStart < 0 || size > length - 2 * edge ? toStart : toEnd;
84
+ };
85
+ const innermost = (element, axis) => {
86
+ for (let node = element; node; node = parentOf(node)) if (node === page || (node instanceof Element && scrolls(node, axis))) return node;
87
+ return page;
88
+ };
89
+ const hitAt = (x, y) => {
90
+ let hit = document.elementFromPoint(x, y);
91
+ for (let inner; hit?.shadowRoot && (inner = hit.shadowRoot.elementFromPoint(x, y)) && inner !== hit;) hit = inner;
92
+ return hit;
93
+ };
94
+ // Whether a wheel at (x, y) scrolls `container` first along `axis`: no frame and no other container lies there.
95
+ const reaches = (x, y, container, axis) => { const hit = hitAt(x, y); return !!hit && !/^(iframe|frame|embed|object)$/.test(hit.localName) && innermost(hit, axis) === container; };
96
+ const steps = containers.map((container, index) => {
97
+ const view = viewOf(container), delta = {}, at = { x: container.scrollLeft, y: container.scrollTop };
98
+ for (const axis of ['x', 'y']) {
99
+ if (!scrolls(container, axis)) { delta[axis] = 0; continue; }
100
+ const inner = containers.slice(index + 1).find(c => scrolls(c, axis));
101
+ const wanted = want(inner ?? target, view, inner ? 'nearest' : axis === 'y' ? block : inline, axis);
102
+ const range = axis === 'y' ? container.scrollHeight - container.clientHeight : container.scrollWidth - container.clientWidth;
103
+ delta[axis] = Math.round(Math.min(Math.max(wanted, -at[axis]), range - at[axis]));
104
+ }
105
+ const axis = delta.y ? 'y' : 'x', visible = shown(view);
106
+ // Where the cursor goes when the wheel would not reach the container from where it rests: the
107
+ // middle of what shows of it, or the first spot nearest the middle that reaches it.
108
+ let aim = null;
109
+ if (!reaches(point.x, point.y, container, axis)) {
110
+ const spots = [];
111
+ for (let i = 1; i < 8; i++) for (let j = 1; j < 8; j++) spots.push({ x: visible.x + visible.width * i / 8, y: visible.y + visible.height * j / 8 });
112
+ const middle = { x: visible.x + visible.width / 2, y: visible.y + visible.height / 2 };
113
+ spots.sort((a, b) => Math.hypot(a.x - middle.x, a.y - middle.y) - Math.hypot(b.x - middle.x, b.y - middle.y));
114
+ aim = spots.find(spot => reaches(spot.x, spot.y, container, axis)) ?? false;
115
+ }
116
+ const name = container === page ? 'the page' : `<${container.localName}${container.id ? `#${container.id}` : ''}>`;
117
+ return { index, delta, aim, at, name };
118
+ });
119
+ return { steps };
120
+ }
121
+
122
+ /** Options may be a bare number for the action's main timing; `focus: false` keeps the camera wide. */
123
+ export const options = (value, key) => typeof value === 'number' ? { [key]: value } : value ?? {};
124
+
125
+ /**
126
+ * The Director's clock, shared by pages and Apps: waits, camera focus targets, Lines and fast-forwarded
127
+ * waits, timed from `startedAt` (epoch ms) and noted in `notes`. `front()` is the Tab a focus target is
128
+ * in. `state.waited` turns true once the Scenario first waits.
129
+ */
130
+ export function clockOf({ startedAt, voiced = null }, { focus: focusTargets, said, forwarded }, front) {
131
+ const state = { waited: false, forwarding: null };
132
+ // Node's clock, not a page's, since the page in front may close mid-wait.
133
+ const wait = ms => { state.waited = true; return new Promise(resolve => setTimeout(resolve, Math.max(0, ms))); };
5
134
  const time = () => (Date.now() - startedAt) / 1000;
6
- async function move(x, y, duration = 500) {
7
- const from = { ...cursor };
135
+ const focus = (box, t = time()) => focusTargets.push({ t, box, tab: front() });
136
+ /**
137
+ * Runs `action`, a wait the viewer need not sit through, such as `() => reply.waitFor()`;
138
+ * the Final plays it `rate` times faster. Speech cannot speed up with it, so no Line is said inside.
139
+ */
140
+ async function fastForward(action, opts) {
141
+ const { rate = 4 } = options(opts, 'rate');
142
+ if (typeof action !== 'function') throw new Error('d.fastForward needs a function that waits, such as () => reply.waitFor()');
143
+ if (!(typeof rate === 'number' && rate >= 1)) throw new Error(`d.fastForward needs a rate of at least 1, not ${rate}`);
144
+ if (state.forwarding) throw new Error(`d.fastForward was called inside the one from ${state.forwarding.t.toFixed(2)} s`);
145
+ state.waited = true;
146
+ state.forwarding = { t: time(), rate };
147
+ try { return await action(); }
148
+ finally { forwarded.push({ t: state.forwarding.t, end: time(), rate }); state.forwarding = null; }
149
+ }
150
+ /** Starts a Line. With a Narration it holds for the Line's audio, so the picture follows the voice. */
151
+ async function say(id, text) {
152
+ const t = time(), earlier = said.find(line => line.id === id);
153
+ if (earlier) throw new Error(`Line '${id}' was already said at ${earlier.t.toFixed(2)} s`);
154
+ if (state.forwarding) throw new Error(`Line '${id}' is said inside d.fastForward, which the Final plays faster than speech; say it before the wait`);
155
+ if (voiced) {
156
+ if (!voiced.has(id)) throw new Error(`The Narration has no Line '${id}'; its Lines are ${[...voiced.keys()].join(', ')}`);
157
+ said.push({ t, id });
158
+ await wait((t + voiced.get(id)) * 1000 - (Date.now() - startedAt));
159
+ } else {
160
+ if (typeof text !== 'string' || !text) throw new Error(`d.say('${id}') needs the Line's text when recording without --narration`);
161
+ said.push({ t, id, text });
162
+ }
163
+ }
164
+ return { state, wait, time, at: seconds => wait(seconds * 1000 - (Date.now() - startedAt)), focus, fastForward, say };
165
+ }
166
+
167
+ /**
168
+ * Timed, viewport-aligned interactions shared by all scenarios, moving like a person (see motion.js).
169
+ * `tabs` are the Tabs Capture follows (follow-tabs.js); the Director acts only on the one in front.
170
+ * `notes` collects the camera's focus targets and `wide` windows, each scroll (`scrolls`, { t, end }),
171
+ * where each Line starts (`said`),
172
+ * each fast-forwarded wait (`forwarded`) and the pointer path no Tab could see (`pointer`, as
173
+ * [epoch ms, x, y, tab]), and each element masked (`elements`, { id, tab, name }) with its mask
174
+ * (`masks`). `voiced` maps the Narration's Line ids to their audio's seconds, or is null
175
+ * without one. `speed` scales every move, pause and typing delay it chooses; `seed` picks one of many
176
+ * equally human ways to move. `signal` aborts once the Scenario has run, when masks stop following.
177
+ */
178
+ export function createDirector(tabs, { startedAt, fps, voiced = null, speed = 1, seed = 1, signal }, notes) {
179
+ const { wide: wideWindows, pointer, elements = [], masks = [], scrolls = [] } = notes;
180
+ Object.assign(notes, { elements, masks, scrolls });
181
+ let cursor = { x: 0, y: 0, tab: tabs.front.id };
182
+ const rand = random(seed);
183
+ const clock = clockOf({ startedAt, voiced }, notes, () => tabs.front.id), { wait, time, focus, fastForward, say } = clock;
184
+ const pause = name => wait(pauseMs(name, speed, rand));
185
+ /** Moves the front Tab's mouse; where its page cannot see the pointer, the Director notes the path itself. */
186
+ async function point(front, x, y) {
187
+ if (!seenBy({ x, y }, front.viewport)) pointer.push([Date.now(), x, y, front.id]);
188
+ // A popup may close itself while the cursor is on its way; the next action carries the cursor on.
189
+ await front.page.mouse.move(x, y).catch(error => { if (!front.page.isClosed()) throw error; });
190
+ }
191
+ /**
192
+ * The Tab in front, once it records. The cursor follows a change of Tab: it stays where it was over
193
+ * the window, so the new page's mouse is moved there, as converted through where a popup sits.
194
+ */
195
+ async function inFront() {
196
+ const front = tabs.front;
197
+ await tabs.ready(front.page);
198
+ if (cursor.tab !== front.id) {
199
+ const all = tabs.list(), at = carried(cursor, cursor.tab, front.id, windowMaps(all, all[0].viewport));
200
+ cursor = { ...at, tab: front.id };
201
+ await point(front, at.x, at.y);
202
+ }
203
+ return front;
204
+ }
205
+ async function glide(to, { size, duration, drag } = {}) {
206
+ const front = await inFront();
207
+ const path = reach(cursor, to, { size, duration, speed, drag, rand });
208
+ // Progress follows the clock, so a page slow to take each move cannot stretch the move.
8
209
  const start = Date.now();
9
- const frames = Math.max(1, Math.round(duration * fps / 1000));
10
- for (let i = 1; i <= frames; i++) {
11
- const t = i / frames;
12
- const k = t * t * (3 - 2 * t);
13
- await page.mouse.move(from.x + (x - from.x) * k, from.y + (y - from.y) * k);
14
- await wait(start + i * duration / frames - Date.now());
15
- }
16
- cursor = { x, y };
17
- }
18
- // Clicks, typing and drags are recorded by the in-page probe; only deliberate camera choices live here.
19
- const focus = (box, t = time()) => focusTargets.push({ t, box });
20
- /** Options may be a bare number for the action's main timing; `focus: false` keeps the camera wide. */
21
- const options = (value, key) => typeof value === 'number' ? { [key]: value } : value ?? {};
210
+ for (let i = 1, t = 0; t < 1; i++) {
211
+ await wait(start + i * 1000 / fps - Date.now());
212
+ t = path.duration ? Math.min(1, (Date.now() - start) / path.duration) : 1;
213
+ const { x, y } = path.at(t);
214
+ await point(front, x, y);
215
+ }
216
+ cursor = { x: to.x, y: to.y, tab: front.id };
217
+ }
218
+ const move = (x, y, duration) => glide({ x, y }, { duration });
219
+ // Clicks, typing, drags and cursor shapes are recorded by the in-page probe; only deliberate camera choices live here.
22
220
  async function act({ focus: follow = true }, action) {
23
221
  const start = time();
24
222
  try { return await action(); }
25
223
  finally { if (follow === false) wideWindows.push({ start, end: time() }); }
26
224
  }
225
+ /** The located target, refused unless it is in the Tab in front: a person can't click a tab they can't see. */
226
+ async function located(locator, action) {
227
+ const front = await inFront();
228
+ const target = typeof locator === 'string' ? front.page.locator(locator) : locator;
229
+ if (target.page() !== front.page) {
230
+ const tab = tabs.of(target.page());
231
+ throw new Error(tab
232
+ ? `${action} target is in Tab ${tab.id}, behind the one in front; bring it in front first with d.switchTo(page)`
233
+ : `${action} target is on a page Capture does not follow; act on d.page, or on a page the demo opened`);
234
+ }
235
+ return target;
236
+ }
237
+ /**
238
+ * Moves onto a target, landing a little off its center, measured through any iframes it is in.
239
+ * Returns the target and the `position` that makes Playwright press where it landed: Playwright
240
+ * counts it from the padding edge of its own box, which is off inside a cross-origin iframe. Where
241
+ * Playwright's box is off, it would also check the wrong spot for what the press hits, so `share`,
242
+ * where it landed as a share of the box, is returned for the Director to check instead.
243
+ */
244
+ async function approach(locator, duration, action) {
245
+ const target = await located(locator, action);
246
+ const [box, seen, border] = await Promise.all([
247
+ boxOnPage(target), target.boundingBox(),
248
+ target.evaluate(e => { const style = getComputedStyle(e); return { left: parseInt(style.borderLeftWidth, 10) || 0, top: parseInt(style.borderTopWidth, 10) || 0 }; }),
249
+ ]);
250
+ if (!box || !seen) throw new Error(`${action} target has no visible bounding box`);
251
+ const point = landing(box, rand);
252
+ await glide(point, { size: Math.min(box.width, box.height), duration });
253
+ const placed = ['x', 'y', 'width', 'height'].every(key => Math.abs(seen[key] - box[key]) < 0.5);
254
+ return { target, position: { x: point.x - seen.x - border.left, y: point.y - seen.y - border.top }, share: !placed && { x: (point.x - box.x) / box.width, y: (point.y - box.y) / box.height } };
255
+ }
256
+ /** Waits until the target is enabled and is what a press at `share` of its box hits, as Playwright's click waits. */
257
+ async function unblocked(target, share, action) {
258
+ for (const deadline = Date.now() + 10_000; ;) {
259
+ const blocker = await target.evaluate((e, share) => {
260
+ if (e.matches(':disabled')) return 'disabled';
261
+ const r = e.getBoundingClientRect(), hit = e.getRootNode().elementFromPoint(r.x + share.x * r.width, r.y + share.y * r.height);
262
+ return !hit || hit === e || e.contains(hit) ? null : `covered by <${hit.localName}${hit.id ? `#${hit.id}` : ''}>`;
263
+ }, share);
264
+ if (!blocker) return;
265
+ if (Date.now() > deadline) throw new Error(`${action} target is ${blocker} where the Director landed`);
266
+ await wait(100);
267
+ }
268
+ }
269
+ /** `button: 'right'` opens the page's context menu instead. */
27
270
  function click(locator, opts) {
28
- const { duration = 450, ...rest } = options(opts, 'duration');
271
+ const { duration, button = 'left', ...rest } = options(opts, 'duration');
29
272
  return act(rest, async () => {
30
- const target = typeof locator === 'string' ? page.locator(locator) : locator;
31
- const box = await target.boundingBox();
32
- if (!box) throw new Error('Click target has no visible bounding box');
33
- await move(box.x + box.width / 2, box.y + box.height / 2, duration);
34
- await target.click();
273
+ const { target, position, share } = await approach(locator, duration, 'Click');
274
+ await pause('beforePress');
275
+ if (share) await unblocked(target, share, 'Click');
276
+ // A person holds the button for a moment, so the Cursor's press shows. A popup may close itself on the click.
277
+ await target.click({ position, button, delay: pauseMs('press', speed, rand), force: !!share }).catch(error => { if (!target.page().isClosed()) throw error; });
278
+ await pause('afterRelease');
35
279
  });
36
280
  }
281
+ /** Presses a key or combination, such as 'Meta+K', on whatever has focus; the Final shows it as keycaps. */
282
+ function press(keys, opts) {
283
+ return act(options(opts), async () => {
284
+ const { page } = await inFront();
285
+ await pause('beforeKey');
286
+ await page.keyboard.press(keys, { delay: pauseMs('press', speed, rand) }).catch(error => { if (!page.isClosed()) throw error; });
287
+ await pause('afterKey');
288
+ });
289
+ }
290
+ /** Rests the cursor on a target without pressing, so the page shows its hover state. */
291
+ async function hover(locator, opts) {
292
+ const { duration } = options(opts, 'duration');
293
+ await approach(locator, duration, 'Hover');
294
+ }
37
295
  function type(locator, text, opts) {
38
- const { msPerChar = 70, ...rest } = options(opts, 'msPerChar');
296
+ const { msPerChar = 70 / speed, ...rest } = options(opts, 'msPerChar');
39
297
  return act(rest, async () => {
40
298
  await click(locator, rest);
41
- await page.keyboard.type(text, { delay: msPerChar });
299
+ const { page } = await inFront(), chars = [...text], delays = typingDelays(text, msPerChar, rand);
300
+ for (let i = 0; i < chars.length; i++) {
301
+ if (i) await wait(delays[i - 1]);
302
+ await page.keyboard.type(chars[i]);
303
+ }
42
304
  });
43
305
  }
44
306
  function drag(from, to, opts) {
45
- const { duration = 1200, ...rest } = options(opts, 'duration');
307
+ const { duration, ...rest } = options(opts, 'duration');
46
308
  return act(rest, async () => {
47
- await move(from.x, from.y, 400);
309
+ await glide(from);
310
+ const { page } = await inFront();
311
+ await pause('beforePress');
48
312
  await page.mouse.down();
49
- try { await move(to.x, to.y, duration); }
50
- finally { await page.mouse.up(); }
313
+ try {
314
+ await pause('afterGrab');
315
+ await glide(to, { duration, drag: true });
316
+ await pause('beforeDrop');
317
+ } finally { await page.mouse.up(); }
318
+ await pause('afterRelease');
51
319
  });
52
320
  }
53
- return { page, wait, time, at: seconds => wait(seconds * 1000 - (Date.now() - startedAt)), move, click, type, drag, focus };
321
+ /**
322
+ * Masks every element `locator` matches, in any Tab, from now until `end()` is called or the Take
323
+ * ends: `blur` and `cover` hide it, `spotlight` dims the page around it. Capture records each
324
+ * element's box as it moves; a blur or cover made before the Director first waits or acts covers the
325
+ * Take from its first frame. Other options are the effect's parameters (masks.js).
326
+ */
327
+ async function mask(locator, opts = {}) {
328
+ const { effect = 'blur', ...params } = opts;
329
+ effectOf(effect);
330
+ const target = typeof locator === 'string' ? tabs.front.page.locator(locator) : locator, tab = tabs.of(target.page());
331
+ if (!tab) throw new Error('d.mask target is on a page Capture does not follow; mask on d.page, or on a page the demo opened');
332
+ const t = effect !== 'spotlight' && !clock.state.waited ? 0 : time();
333
+ await tabs.ready(tab.page);
334
+ const id = elements.length;
335
+ const watch = () => target.evaluateAll((found, id) => window.__cuetakeProbe?.watch(id, found) ?? false, id);
336
+ if (!await watch()) throw new Error(`d.mask could not follow ${target} in Tab ${tab.id}: Capture's probe is not running in its frame`);
337
+ // The page may replace the element, or navigate; watching again follows what the locator matches now.
338
+ return followMask({ id, tab: tab.id, name: String(target), t, effect, params }, notes, { watch, skip: () => target.page().isClosed(), signal, time });
339
+ }
340
+ /** The Director's plan to scroll to `target` (scrollPlan), with where the target's frame shows on the page. */
341
+ async function scrollSteps(target, block, inline) {
342
+ const handle = await target.elementHandle();
343
+ try {
344
+ const map = await placeOf(await handle.ownerFrame());
345
+ const point = { x: (cursor.x - map.x) / map.sx, y: (cursor.y - map.y) / map.sy };
346
+ const plan = await handle.evaluate(scrollPlan, { block, inline, point, margin: SCROLL_MARGIN });
347
+ if (!plan) throw new Error('Scroll target has no visible bounding box');
348
+ return { map, steps: plan.steps };
349
+ } finally { await handle.dispose(); }
350
+ }
351
+ /** Turns the wheel by `delta` CSS px over `duration` ms, a little each frame, starting fast and settling long. */
352
+ async function wheel(page, delta, duration) {
353
+ const start = Date.now(), sent = { x: 0, y: 0 };
354
+ for (let i = 1, t = 0; t < 1; i++) {
355
+ await wait(start + i * 1000 / fps - Date.now());
356
+ t = duration ? Math.min(1, (Date.now() - start) / duration) : 1;
357
+ const k = ease(t), step = { x: Math.round(delta.x * k) - sent.x, y: Math.round(delta.y * k) - sent.y };
358
+ if (!step.x && !step.y) continue;
359
+ sent.x += step.x; sent.y += step.y;
360
+ await page.mouse.wheel(step.x, step.y);
361
+ }
362
+ }
363
+ /**
364
+ * Scrolls until the target shows where `block` (vertically) and `inline` (horizontally) put it in
365
+ * what scrolls it, as a person turns a wheel or swipes a trackpad: the page first, then each container
366
+ * inside it, each moving both ways at once where it scrolls both. The cursor moves onto a container
367
+ * first when a wheel where it rests would scroll something else. A container that cannot go farther
368
+ * stops there; one that does not move at all fails the Take. Returns the target's box on the page.
369
+ */
370
+ async function scroll(locator, opts) {
371
+ const { duration, block = 'start', inline = 'nearest' } = options(opts, 'duration');
372
+ for (const [name, value] of [['block', block], ['inline', inline]]) if (!ALIGNS.includes(value)) throw new Error(`d.scroll needs ${name} ${ALIGNS.map(a => `'${a}'`).join(', ')}, not '${value}'`);
373
+ const target = await located(locator, 'Scroll'), times = new Map(), start = time();
374
+ let first = true;
375
+ for (;;) {
376
+ const { map, steps } = await scrollSteps(target, block, inline);
377
+ const step = steps.find(({ index, delta }) => {
378
+ const far = Math.max(Math.abs(delta.x), Math.abs(delta.y)), done = times.get(index) ?? 0;
379
+ return far >= 1 && (done === 0 || (done === 1 && far > CORRECTION_PX));
380
+ });
381
+ if (!step) break;
382
+ const { page } = await inFront();
383
+ if (step.aim === false) throw new Error(`Scroll cannot reach ${step.name}: no part of it a wheel would scroll shows`);
384
+ if (step.aim) await glide(onPage(map, { ...step.aim, width: 0, height: 0 }));
385
+ await wheel(page, step.delta, first && duration !== undefined ? duration : scrollMs(Math.hypot(step.delta.x, step.delta.y), { speed }));
386
+ first = false;
387
+ times.set(step.index, (times.get(step.index) ?? 0) + 1);
388
+ const after = (await scrollSteps(target, block, inline)).steps[step.index];
389
+ if (after?.at.x === step.at.x && after?.at.y === step.at.y) {
390
+ throw new Error(`Scroll moved nothing: a wheel at (${Math.round(cursor.x)}, ${Math.round(cursor.y)}) did not scroll ${step.name}; the page may take the wheel itself, or something lies over it`);
391
+ }
392
+ }
393
+ if (!first) {
394
+ // The camera goes wide before the page moves and stays wide until it stops (camera.js).
395
+ scrolls.push({ t: start, end: time() });
396
+ await pause('afterScroll');
397
+ }
398
+ const box = await boxOnPage(target), { viewport } = tabs.front;
399
+ if (!box || box.x + box.width <= 0 || box.y + box.height <= 0 || box.x >= viewport.width || box.y >= viewport.height) {
400
+ throw new Error('Scroll could not bring the target into view; if it is inside an iframe, scroll the iframe into view first with d.scroll(d.page.locator(\'iframe\'))');
401
+ }
402
+ return box;
403
+ }
404
+ /** Brings a Tab back in front, such as the one a closed tab's demo continues in; the cursor stays where it was. */
405
+ async function switchTo(page) {
406
+ await tabs.switchTo(page);
407
+ await inFront();
408
+ }
409
+ return {
410
+ /** The Tab in front. */
411
+ get page() { return tabs.front.page; },
412
+ wait, time, at: clock.at, move, hover, click, press, type, drag, scroll, focus, say, fastForward, mask, switchTo,
413
+ };
54
414
  }