cuetake 0.4.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/director.js CHANGED
@@ -1,18 +1,209 @@
1
- import { landing, pauseMs, random, reach, typingDelays } from './motion.js';
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))); };
134
+ const time = () => (Date.now() - startedAt) / 1000;
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
+ }
2
166
 
3
167
  /**
4
168
  * Timed, viewport-aligned interactions shared by all scenarios, moving like a person (see motion.js).
5
- * `said` collects where each Line starts; `voiced` maps the Narration's Line ids to their audio's
6
- * seconds, or is null without one. `speed` scales every move, pause and typing delay it chooses;
7
- * `seed` picks one of many equally human ways to move.
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.
8
177
  */
9
- export function createDirector(page, startedAt, fps, focusTargets, wideWindows, said = [], voiced = null, { speed = 1, seed = 1 } = {}) {
10
- let cursor = { x: 0, y: 0 };
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 };
11
182
  const rand = random(seed);
12
- const wait = ms => page.waitForTimeout(Math.max(0, ms));
13
- const time = () => (Date.now() - startedAt) / 1000;
183
+ const clock = clockOf({ startedAt, voiced }, notes, () => tabs.front.id), { wait, time, focus, fastForward, say } = clock;
14
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
+ }
15
205
  async function glide(to, { size, duration, drag } = {}) {
206
+ const front = await inFront();
16
207
  const path = reach(cursor, to, { size, duration, speed, drag, rand });
17
208
  // Progress follows the clock, so a page slow to take each move cannot stretch the move.
18
209
  const start = Date.now();
@@ -20,45 +211,79 @@ export function createDirector(page, startedAt, fps, focusTargets, wideWindows,
20
211
  await wait(start + i * 1000 / fps - Date.now());
21
212
  t = path.duration ? Math.min(1, (Date.now() - start) / path.duration) : 1;
22
213
  const { x, y } = path.at(t);
23
- await page.mouse.move(x, y);
214
+ await point(front, x, y);
24
215
  }
25
- cursor = { ...to };
216
+ cursor = { x: to.x, y: to.y, tab: front.id };
26
217
  }
27
218
  const move = (x, y, duration) => glide({ x, y }, { duration });
28
219
  // Clicks, typing, drags and cursor shapes are recorded by the in-page probe; only deliberate camera choices live here.
29
- const focus = (box, t = time()) => focusTargets.push({ t, box });
30
- /** Options may be a bare number for the action's main timing; `focus: false` keeps the camera wide. */
31
- const options = (value, key) => typeof value === 'number' ? { [key]: value } : value ?? {};
32
220
  async function act({ focus: follow = true }, action) {
33
221
  const start = time();
34
222
  try { return await action(); }
35
223
  finally { if (follow === false) wideWindows.push({ start, end: time() }); }
36
224
  }
37
- /** Moves onto a target, landing a little off its center; returns the target and where it landed inside its box. */
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
+ */
38
244
  async function approach(locator, duration, action) {
39
- const target = typeof locator === 'string' ? page.locator(locator) : locator;
40
- const box = await target.boundingBox();
41
- if (!box) throw new Error(`${action} target has no visible bounding box`);
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`);
42
251
  const point = landing(box, rand);
43
252
  await glide(point, { size: Math.min(box.width, box.height), duration });
44
- return { target, position: { x: point.x - box.x, y: point.y - box.y } };
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
+ }
45
268
  }
46
269
  /** `button: 'right'` opens the page's context menu instead. */
47
270
  function click(locator, opts) {
48
271
  const { duration, button = 'left', ...rest } = options(opts, 'duration');
49
272
  return act(rest, async () => {
50
- const { target, position } = await approach(locator, duration, 'Click');
273
+ const { target, position, share } = await approach(locator, duration, 'Click');
51
274
  await pause('beforePress');
52
- // A person holds the button for a moment, so the Cursor's press shows.
53
- await target.click({ position, button, delay: pauseMs('press', speed, rand) });
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; });
54
278
  await pause('afterRelease');
55
279
  });
56
280
  }
57
281
  /** Presses a key or combination, such as 'Meta+K', on whatever has focus; the Final shows it as keycaps. */
58
282
  function press(keys, opts) {
59
283
  return act(options(opts), async () => {
284
+ const { page } = await inFront();
60
285
  await pause('beforeKey');
61
- await page.keyboard.press(keys, { delay: pauseMs('press', speed, rand) });
286
+ await page.keyboard.press(keys, { delay: pauseMs('press', speed, rand) }).catch(error => { if (!page.isClosed()) throw error; });
62
287
  await pause('afterKey');
63
288
  });
64
289
  }
@@ -71,7 +296,7 @@ export function createDirector(page, startedAt, fps, focusTargets, wideWindows,
71
296
  const { msPerChar = 70 / speed, ...rest } = options(opts, 'msPerChar');
72
297
  return act(rest, async () => {
73
298
  await click(locator, rest);
74
- const chars = [...text], delays = typingDelays(text, msPerChar, rand);
299
+ const { page } = await inFront(), chars = [...text], delays = typingDelays(text, msPerChar, rand);
75
300
  for (let i = 0; i < chars.length; i++) {
76
301
  if (i) await wait(delays[i - 1]);
77
302
  await page.keyboard.type(chars[i]);
@@ -82,6 +307,7 @@ export function createDirector(page, startedAt, fps, focusTargets, wideWindows,
82
307
  const { duration, ...rest } = options(opts, 'duration');
83
308
  return act(rest, async () => {
84
309
  await glide(from);
310
+ const { page } = await inFront();
85
311
  await pause('beforePress');
86
312
  await page.mouse.down();
87
313
  try {
@@ -92,18 +318,97 @@ export function createDirector(page, startedAt, fps, focusTargets, wideWindows,
92
318
  await pause('afterRelease');
93
319
  });
94
320
  }
95
- /** Starts a Line. With a Narration it holds for the Line's audio, so the picture follows the voice. */
96
- async function say(id, text) {
97
- const t = time(), earlier = said.find(line => line.id === id);
98
- if (earlier) throw new Error(`Line '${id}' was already said at ${earlier.t.toFixed(2)} s`);
99
- if (voiced) {
100
- if (!voiced.has(id)) throw new Error(`The Narration has no Line '${id}'; its Lines are ${[...voiced.keys()].join(', ')}`);
101
- said.push({ t, id });
102
- await wait((t + voiced.get(id)) * 1000 - (Date.now() - startedAt));
103
- } else {
104
- if (typeof text !== 'string' || !text) throw new Error(`d.say('${id}') needs the Line's text when recording without --narration`);
105
- said.push({ t, id, text });
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');
106
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();
107
408
  }
108
- return { page, wait, time, at: seconds => wait(seconds * 1000 - (Date.now() - startedAt)), move, hover, click, press, type, drag, focus, say };
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
+ };
109
414
  }
package/src/edit.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import { isPopup } from './tabs.js';
2
3
 
3
4
  /**
4
5
  * An Edit holds every choice Render makes; a Scenario's config only seeds the first one. Styling is
@@ -17,8 +18,9 @@ export const DEFAULT_STYLE = {
17
18
  // Cursor, so no click effect is drawn unless named.
18
19
  cursor: { draw: 'arrow', size: 24, color: '#ffffff', press: 0.8 },
19
20
  clickEffect: false,
20
- // quality is the H.264 quantizer (lower is sharper and larger).
21
- output: { width: 3840, height: 2160, quality: 22 },
21
+ // quality is the H.264 quantizer (lower is sharper and larger). shutter is the fraction of each
22
+ // frame over which the camera and the Cursor blur as they move (shutter.js); 0 turns blur off.
23
+ output: { width: 3840, height: 2160, quality: 22, shutter: 0.5 },
22
24
  // padding is a fraction of the short side, one number or [top, right, bottom, left]; radius is in 1080p pixels.
23
25
  frame: { padding: 0.08, radius: 12, chrome: { draw: 'browser' }, background: [{ shader: 'fluted' }], effects: [{ shader: 'shadow' }] },
24
26
  // See camera.js. Each target is framed with `padding` CSS px around it, zooming at most `maxZoom`;
@@ -33,6 +35,13 @@ export const DEFAULT_STYLE = {
33
35
  // subtitle files. Rows hold up to `maxChars` (about 16 in Chinese, 42 otherwise), `maxRows` to a cue,
34
36
  // each shown at least `minDuration`.
35
37
  subtitles: { draw: 'subtitles', burn: true },
38
+ // Drawn over the Final, outside the camera, while it fast-forwards, such as { draw: 'fast-forward' };
39
+ // `false` shows none.
40
+ fastForwardBadge: false,
41
+ // How the Final shows the Tabs (tabs.js): the window cuts to a tab of its own size, or fades over
42
+ // `{ fade }` seconds; a popup window scales and fades in and out over `duration`, from `scale`, unless
43
+ // `popupAnimation` is false. Times are Final seconds.
44
+ tabs: { transition: 'cut', popupAnimation: { duration: 0.2, scale: 0.9 } },
36
45
  };
37
46
 
38
47
  const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -50,42 +59,89 @@ export function merge(base, over) {
50
59
 
51
60
  /** A complete Edit: the defaults under whatever `edit` names. */
52
61
  export function withDefaults(edit) {
53
- return merge({ schemaVersion: EDIT_VERSION, ...DEFAULT_STYLE, output: { ...DEFAULT_STYLE.output, fps: 60 }, camera: { ...DEFAULT_STYLE.camera, targets: [] }, shortcuts: [], narration: { volume: 1, lines: [] } }, edit);
62
+ return merge({ schemaVersion: EDIT_VERSION, ...DEFAULT_STYLE, output: { ...DEFAULT_STYLE.output, fps: 60 }, camera: { ...DEFAULT_STYLE.camera, targets: [], scrolls: [] }, tabs: { ...DEFAULT_STYLE.tabs, placement: [] }, shortcuts: [], fastForward: [], masks: [], narration: { volume: 1, lines: [] } }, edit);
54
63
  }
55
64
 
65
+ // Seconds after a click within which the App's focus moving to what holds its target counts as the click's.
66
+ const FOCUS_AFTER_CLICK = 1;
67
+
56
68
  /**
57
- * Camera targets: observed clicks, typing and drags, except those inside a `wide` window ({ start, end }
58
- * seconds) from an action with `focus: false`. Like a manual zoom in Screen Studio, an explicit focus
69
+ * Camera targets: observed clicks, typing and drags, and each element an App focused, each in the CSS
70
+ * pixels of its Tab, and each popup window's whole page as it first comes in front, except those
71
+ * inside a `wide` window ({ start, end } seconds) from an action with `focus: false`, and focus a click
72
+ * gave to what holds its target. Like a manual zoom in Screen Studio, an explicit focus
59
73
  * target replaces only the automatic targets inside its own span (from `lead` before it to `hold` after).
60
74
  */
61
75
  export function cameraTargets(timeline, focus, wide = [], camera = {}) {
62
76
  const { lead, hold } = { ...DEFAULT_STYLE.camera, ...camera };
63
77
  const spans = focus.map(f => ({ start: f.t - lead, end: (f.until ?? f.t) + hold }));
64
78
  const inside = (t, windows) => windows.some(w => t >= w.start && t <= w.end);
79
+ const tabs = new Map((timeline.tabs ?? []).map(tab => [tab.id, tab])), framed = new Set();
80
+ // Focus a click gave to what holds its target, such as the text area around a link, adds only a larger box.
81
+ const holds = (outer, inner) => outer.x <= inner.x && outer.y <= inner.y && outer.x + outer.width >= inner.x + inner.width && outer.y + outer.height >= inner.y + inner.height;
82
+ const byClick = focused => timeline.events.some(event => event.type === 'click' && event.box && event.tab === focused.tab && event.t <= focused.t && focused.t - event.t <= FOCUS_AFTER_CLICK && holds(focused.box, event.box));
65
83
  const automatic = timeline.events.filter(event => !inside(event.t, wide) && !inside(event.t, spans)).flatMap(event => {
66
- if (event.type === 'click' && event.box) return [{ t: event.t, box: event.box }];
67
- if (event.type === 'type' && event.box) return [{ t: event.t, box: event.box, until: event.end }];
84
+ const tab = event.tab === undefined ? {} : { tab: event.tab };
85
+ if (event.type === 'focused' && byClick(event)) return [];
86
+ if ((event.type === 'click' || event.type === 'focused') && event.box) return [{ t: event.t, box: event.box, ...tab }];
87
+ if (event.type === 'type' && event.box) return [{ t: event.t, box: event.box, until: event.end, ...tab }];
68
88
  if (event.type === 'drag') {
69
89
  const x = Math.min(event.from.x, event.to.x), y = Math.min(event.from.y, event.to.y);
70
- return [{ t: event.t, box: { x, y, width: Math.abs(event.to.x - event.from.x), height: Math.abs(event.to.y - event.from.y) }, until: event.end }];
90
+ return [{ t: event.t, box: { x, y, width: Math.abs(event.to.x - event.from.x), height: Math.abs(event.to.y - event.from.y) }, until: event.end, ...tab }];
91
+ }
92
+ const opened = tabs.get(event.tab);
93
+ if (event.type === 'front' && opened && isPopup(opened, timeline.viewport) && !framed.has(event.tab)) {
94
+ framed.add(event.tab);
95
+ return [{ t: event.t, box: { x: 0, y: 0, ...opened.viewport }, tab: event.tab }];
71
96
  }
72
97
  return [];
73
98
  });
74
99
  return [...automatic, ...focus].sort((a, b) => a.t - b.t);
75
100
  }
76
101
 
102
+ /** What the address bar shows for a page address: its host, or the whole address when it has none. */
103
+ export function addressOf(url) {
104
+ try { const parsed = new URL(url); return /^https?:$/.test(parsed.protocol) ? parsed.host : url; } catch { return url; }
105
+ }
106
+
107
+ /**
108
+ * The address bar's text when Capture started (`url`), and each change after it (`urls`, as
109
+ * { t, url, tab } in Source time): a full navigation to another host shows the new one from the moment
110
+ * the page took its address. A Tab the demo opens shows the host it opened on, or nothing until its
111
+ * first document commits when it opened on about:blank. The Scenario's `frame.url`, when set, names
112
+ * the host Capture started on, also when a navigation comes back to it.
113
+ */
114
+ export function addressBar(config, timeline) {
115
+ const first = addressOf(timeline.url ?? config.url), shown = host => host === first ? config.frame?.url ?? first : host;
116
+ const urls = [], current = new Map([[0, first]]);
117
+ const change = (t, url, tab) => {
118
+ const host = !url || url === 'about:blank' ? '' : addressOf(url);
119
+ if (host !== (current.get(tab) ?? '')) urls.push({ t, url: shown(host), tab });
120
+ current.set(tab, host);
121
+ };
122
+ const opened = (timeline.tabs ?? []).slice(1).map(tab => ({ t: tab.opened, url: tab.url, tab: tab.id }));
123
+ const committed = (timeline.events ?? []).filter(event => event.type === 'navigate' && event.commit !== undefined).map(event => ({ t: event.commit, url: event.url, tab: event.tab ?? 0 }));
124
+ for (const { t, url, tab } of [...opened, ...committed].sort((a, b) => a.t - b.t)) change(t, url, tab);
125
+ return { url: shown(first), urls };
126
+ }
127
+
77
128
  /**
78
129
  * The first Edit of a Take. Each Line starts where the Scenario said it (`d.say`); its text, audio and
79
130
  * word timings stay in the Take's Narration, since they change only with new audio. The Shortcuts the
80
- * Timeline recorded are the ones shown, so one can be relabeled or removed without recording again.
131
+ * Timeline recorded are the ones shown, so one can be relabeled or removed without recording again, and
132
+ * so are the waits the Scenario fast-forwarded (`d.fastForward`), so one can be retimed (time-map.js),
133
+ * and the elements it masked (`d.mask`), so a mask can be retimed, restyled or removed (masks.js).
81
134
  */
82
135
  export function createEdit(config, timeline, focus, wide = []) {
83
136
  return withDefaults({
84
- cursor: config.cursor, clickEffect: config.clickEffect, keycaps: config.keycaps, subtitles: config.subtitles, output: { ...config.output, fps: config.capture.fps },
85
- // The browser chrome shows the Scenario's host unless the config names something else.
86
- frame: { url: new URL(config.url).host, ...config.frame },
87
- camera: { ...config.camera, targets: cameraTargets(timeline, focus, wide, config.camera) },
137
+ cursor: config.cursor, clickEffect: config.clickEffect, keycaps: config.keycaps, subtitles: config.subtitles, fastForwardBadge: config.fastForwardBadge, output: { ...config.output, fps: config.capture.fps },
138
+ // The browser chrome shows the host the page is on, unless the config names something else. A Take
139
+ // of Apps shows the App's own windows, without chrome, unless the config names one (ADR 0009).
140
+ frame: config.app ? { chrome: false, ...config.frame } : { ...config.frame, ...addressBar(config, timeline) },
141
+ camera: { ...config.camera, targets: cameraTargets(timeline, focus, wide, config.camera), scrolls: timeline.events.filter(event => event.type === 'scroll').map(({ t, end }) => ({ start: t, end })) }, tabs: config.tabs,
88
142
  shortcuts: timeline.events.filter(event => event.type === 'shortcut').map(({ t, keys }) => ({ t, keys })),
143
+ fastForward: timeline.events.filter(event => event.type === 'fastForward').map(({ t, end, rate }) => ({ start: t, end, rate })),
144
+ masks: timeline.events.filter(event => event.type === 'mask').map(({ type, t, end, effect, element, ...params }) => ({ effect, element, start: t, ...(end !== null && end !== undefined && { end }), ...params })),
89
145
  narration: { lines: timeline.events.filter(event => event.type === 'say').map(event => ({ id: event.id, start: event.t })) },
90
146
  });
91
147
  }
@@ -3,8 +3,13 @@ import { spawn } from 'node:child_process';
3
3
  import { createRequire } from 'node:module';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { chromium } from 'playwright';
6
+ import { appChecks } from './app-capture.js';
6
7
 
7
- /** Checks what CueTake needs; installs nothing. Each failed check names the exact fix. */
8
+ /**
9
+ * Checks what CueTake needs; installs nothing and requests no permission. Each failed check names the
10
+ * exact fix. `ok` covers web pages; on macOS, `apps.ok` also covers the checks marked `for: 'Apps'`,
11
+ * which a Take of an App needs too.
12
+ */
8
13
  export async function doctor() {
9
14
  const checks = [];
10
15
  const [major, minor] = process.versions.node.split('.').map(Number);
@@ -14,11 +19,38 @@ export async function doctor() {
14
19
  const browserPath = chromium.executablePath();
15
20
  try { await fs.access(browserPath); checks.push({ name: 'chromium', ok: true, path: browserPath }); }
16
21
  catch { checks.push({ name: 'chromium', ok: false, fix: 'cuetake install-browser (downloads about 150 MB; ask the user first)' }); }
22
+ if (checks.at(-1).ok) checks.push(await gpu());
17
23
  const platform = process.platform === 'darwin'
18
24
  ? { name: 'platform', ok: true, value: 'macOS' }
19
25
  : { name: 'platform', ok: true, value: process.platform, note: 'Only macOS is verified; capture and Render may behave differently here.' };
20
26
  checks.push(platform);
21
- return { ok: checks.every(c => c.ok), checks };
27
+ if (process.platform === 'darwin') checks.push(...await appChecks());
28
+ return { ok: checks.every(c => c.ok || c.for), ...(process.platform === 'darwin' && { apps: { ok: checks.every(c => c.ok) } }), checks };
29
+ }
30
+
31
+ /** Whether a WebGL renderer name is a GPU; null when Chromium reports none. */
32
+ export const drawsWithGpu = renderer => renderer ? !/swiftshader|llvmpipe|softpipe|software|basic render driver/i.test(renderer) : null;
33
+
34
+ /**
35
+ * Asks the headless Chromium Capture runs in what draws its pages. Without a GPU it rasterizes and encodes
36
+ * on the CPU, and at resolution scale 2 a busy page then gets far fewer frames than it draws. Informational:
37
+ * Capture still works, so the check never fails.
38
+ */
39
+ async function gpu() {
40
+ let renderer = null;
41
+ try {
42
+ const browser = await chromium.launch({ headless: true, channel: 'chromium' });
43
+ try {
44
+ renderer = await (await browser.newPage()).evaluate(() => {
45
+ const gl = document.createElement('canvas').getContext('webgl'), info = gl?.getExtension('WEBGL_debug_renderer_info');
46
+ return info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : null;
47
+ });
48
+ } finally { await browser.close(); }
49
+ } catch {}
50
+ const accelerated = drawsWithGpu(renderer);
51
+ return { name: 'gpu', ok: true, accelerated, renderer,
52
+ ...(accelerated === false && { note: 'Chromium draws without a GPU here, so record captures at resolutionScale 1 unless the Scenario sets one.' }),
53
+ ...(accelerated === null && { note: 'Chromium did not report a renderer.' }) };
22
54
  }
23
55
 
24
56
  function playwright(args) {