cuetake 0.7.0 → 0.8.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cuetake",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Local recording runtime for AI agents: plan a browser demo, capture it, and render a finished take.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -106,10 +106,15 @@ export async function startDesktop({ apps, desktop, fps, source, poster, useRunn
106
106
  ready: await ready,
107
107
  async start() { const started = reply('started'); send({ start: true }); return (await started).epochMs; },
108
108
  async stop() { const stopped = reply('stopped'); send({ stop: true }); return stopped; },
109
- request(message) {
110
- if (ended) return Promise.reject(ended);
111
- const id = ++next;
112
- return new Promise((resolve, reject) => { requests.set(id, { resolve, reject }); send({ id, ...message }); });
109
+ async request(message) {
110
+ try {
111
+ if (ended) throw ended;
112
+ const id = ++next;
113
+ return await new Promise((resolve, reject) => { requests.set(id, { resolve, reject }); send({ id, ...message }); });
114
+ } catch (error) {
115
+ // A fresh error, made here after the await, carries the Scenario's call on its stack, which the helper's reply cannot.
116
+ throw new Error(error.message, { cause: error });
117
+ }
113
118
  },
114
119
  kill() { if (child.exitCode === null) child.stdin.end(); },
115
120
  };
@@ -7,6 +7,7 @@ import { shortcutKeys } from './shortcuts.js';
7
7
 
8
8
  // The AX roles of an element that takes typing, where a key pressed alone is typing, not a Shortcut.
9
9
  const FIELDS = new Set(['AXTextField', 'AXTextArea', 'AXComboBox', 'AXSearchField']);
10
+ const isField = ({ role, subrole } = {}) => FIELDS.has(role) || FIELDS.has(subrole);
10
11
  // Characters typed as their key, since a text field takes them as a key press, not as text.
11
12
  const TYPED_AS_KEYS = { '\n': 'Enter', '\t': 'Tab' };
12
13
  // How long a window clicked into may take to come in front, and how often the Director looks.
@@ -140,9 +141,9 @@ export function createAppDirector({ startedAt, fps = 60, voiced = null, speed =
140
141
  return act(options(opts), async () => {
141
142
  const { down: keydown } = macKeys(keys);
142
143
  await pause('beforeKey');
143
- const { role, subrole } = await helper.request({ focused: {} }) ?? {}, t = now();
144
+ const focused = await helper.request({ focused: {} }) ?? {}, t = now();
144
145
  await key(keys, pauseMs('press', speed, rand));
145
- const shown = shortcutKeys({ ...keydown, field: FIELDS.has(role) || FIELDS.has(subrole) });
146
+ const shown = shortcutKeys({ ...keydown, field: isField(focused) });
146
147
  if (shown) notes.events.push({ type: 'shortcut', t, keys: shown });
147
148
  await pause('afterKey');
148
149
  });
@@ -152,11 +153,25 @@ export function createAppDirector({ startedAt, fps = 60, voiced = null, speed =
152
153
  const { duration, ...rest } = options(opts, 'duration');
153
154
  await act(rest, () => approach(target, duration, 'hover'));
154
155
  }
156
+ /**
157
+ * Clicks a field and types into it. `replace: true` first selects what the field holds with Select All,
158
+ * as on a page, so the first character replaces it; with no text, it empties the field. That Select All
159
+ * is typing, so it notes no Shortcut.
160
+ */
155
161
  function type(target, text, opts) {
156
- const { msPerChar = 70 / speed, ...rest } = options(opts, 'msPerChar');
162
+ const { msPerChar = 70 / speed, replace = false, ...rest } = options(opts, 'msPerChar');
157
163
  return act(rest, async () => {
158
164
  await click(target, rest);
159
- const { box } = notes.events.at(-1), chars = [...text], delays = typingDelays(text, msPerChar, rand), t = now();
165
+ const { box } = notes.events.at(-1), chars = [...text], delays = typingDelays(text, msPerChar, rand);
166
+ if (replace) {
167
+ const focused = await helper.request({ focused: {} }) ?? {};
168
+ if (!isField(focused)) throw new Error(`d.type(${isAppLocator(target) ? target : `{ x: ${target.x}, y: ${target.y} }`}, { replace: true }) needs a text field, but after the click ${focused.role ?? 'nothing'} has focus`);
169
+ await pause('beforeKey');
170
+ await key('Meta+A', pauseMs('press', speed, rand));
171
+ await pause('afterKey');
172
+ if (!chars.length) await key('Backspace', 0);
173
+ }
174
+ const t = now();
160
175
  for (let i = 0; i < chars.length; i++) {
161
176
  if (i) await wait(delays[i - 1]);
162
177
  if (TYPED_AS_KEYS[chars[i]]) await key(TYPED_AS_KEYS[chars[i]], 0);
package/src/director.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ease, landing, pauseMs, random, reach, scrollMs, typingDelays } from './motion.js';
2
2
  import { boxOnPage, onPage, placeOf } from './frames.js';
3
+ import { textField } from './probe.js';
3
4
  import { carried, seenBy, windowMaps } from './tabs.js';
4
5
  import { EFFECT_NAMES, MASK_EFFECTS } from './masks.js';
5
6
  import { wordInLine } from './narration.js';
@@ -37,8 +38,10 @@ export function followMask({ id, tab, name, t, effect, params }, notes, { watch,
37
38
  const ALIGNS = ['start', 'center', 'end', 'nearest'];
38
39
  // A scroll lands its target this share of the scrolled view from its edge, so it is not flush against it.
39
40
  const SCROLL_MARGIN = 0.1;
40
- // A container already scrolled once is scrolled again only to correct a target this far off, such as after images loaded above it.
41
+ // A container already scrolled once is scrolled again only to correct a target this far off, such as after images loaded above it;
42
+ // a scroll that fails names a move of the layout, or of a scroll position past where the wheel took it, this large as the reason.
41
43
  const CORRECTION_PX = 4;
44
+ const SETTLE = 'wait until the page settles before d.scroll';
42
45
 
43
46
  /**
44
47
  * Runs in the target's frame: how a person would scroll to `target`, outermost container first. Each
@@ -115,11 +118,53 @@ function scrollPlan(target, { block, inline, point, margin }) {
115
118
  aim = spots.find(spot => reaches(spot.x, spot.y, container, axis)) ?? false;
116
119
  }
117
120
  const name = container === page ? 'the page' : `<${container.localName}${container.id ? `#${container.id}` : ''}>`;
118
- return { index, delta, aim, at, name };
121
+ return { index, delta, aim, at, name, page: container === page };
119
122
  });
120
123
  return { steps };
121
124
  }
122
125
 
126
+ const at = ({ x, y }) => `(${Math.round(x)}, ${Math.round(y)})`;
127
+ const boxText = box => box ? `${at(box)} ${Math.round(box.width)}×${Math.round(box.height)}` : 'gone';
128
+
129
+ /**
130
+ * What `d.scroll` saw when its target ended out of view, and why when it can tell. `startBox` and `box`
131
+ * are the target's box at the start and the end, in top-level CSS px, with `startMap` and `map` placing
132
+ * its frame on the page then (placeOf). `containers` are those that scrolled or that the wheel turned,
133
+ * outermost first, each with its scroll position `from` and `to` in its frame's CSS px and what the wheel
134
+ * `sent` it, or null. The reasons: the layout moved the target, a container moved past where the wheel
135
+ * took it, and the target is in an iframe.
136
+ */
137
+ function outOfView({ startBox, box, startMap, map, viewport, framed, containers }) {
138
+ const facts = `its box on the page was ${boxText(startBox)} at the start and ${boxText(box)} at the end, in the ${viewport.width}×${viewport.height} viewport`;
139
+ const scrolled = containers.length ? `, and ${containers.map(c => `${c.name} scrolled from ${at(c.from)} to ${at(c.to)}`).join(', ')}` : ', and nothing scrolled';
140
+ const why = [];
141
+ // In its frame's CSS px, a target the layout leaves alone moves exactly as far as what scrolls it moves the other way.
142
+ if (startBox && box) {
143
+ const drift = (axis, size) => (box[axis] - map[axis]) / map[size] - (startBox[axis] - startMap[axis]) / startMap[size] + containers.reduce((sum, c) => sum + c.to[axis] - c.from[axis], 0);
144
+ const moved = Math.round(Math.max(Math.abs(drift('x', 'sx')), Math.abs(drift('y', 'sy'))));
145
+ if (moved > CORRECTION_PX) why.push(`the page's layout moved the target ${moved} px while it scrolled, as a list still filtering or loading does; ${SETTLE}`);
146
+ }
147
+ // A container short of where the wheel took it reached its end; one past it was moved by the page.
148
+ const pushed = containers.filter(c => c.sent).map(c => {
149
+ const axis = Math.abs(c.to.y - c.from.y - c.sent.y) >= Math.abs(c.to.x - c.from.x - c.sent.x) ? 'y' : 'x', moved = c.to[axis] - c.from[axis];
150
+ const atEnd = moved * c.sent[axis] >= 0 && Math.abs(moved) <= Math.abs(c.sent[axis]);
151
+ return { name: c.name, extra: atEnd ? 0 : Math.round(moved - c.sent[axis]) };
152
+ }).find(c => Math.abs(c.extra) > CORRECTION_PX);
153
+ if (pushed) why.push(`${pushed.name} moved its own scroll position ${pushed.extra} px past where the wheel took it, as when scroll anchoring answers content added above the view, or the page grows shorter under it; ${SETTLE}`);
154
+ if (framed) why.push("the target is inside an iframe, and d.scroll scrolls only within the iframe's page: scroll the iframe into view first with d.scroll(d.page.locator('iframe'))");
155
+ return `${facts}${scrolled}.${why.map(w => ` ${w[0].toUpperCase()}${w.slice(1)}.`).join('')}`;
156
+ }
157
+
158
+ /** What has focus in a target's document, through shadow roots, when it is not a text field; null when it is one. It runs in the page. */
159
+ function focusedNotField(element, isTextField) {
160
+ let active = element.ownerDocument.activeElement;
161
+ while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
162
+ if (!active) return 'nothing';
163
+ return isTextField(active) ? null : `<${active.localName}${active.id ? `#${active.id}` : ''}>`;
164
+ }
165
+ // Built from source, so Playwright sends the page probe.js's textField with it.
166
+ const focusedNotTextField = new Function('element', `return (${focusedNotField})(element, ${textField});`);
167
+
123
168
  /** How long after the voice said a word the Scenario may wait for it before `verify` warns. */
124
169
  const LATE_WORD_S = 0.2;
125
170
 
@@ -193,6 +238,7 @@ export function clockOf({ startedAt, voiced = null }, { focus: focusTargets, sai
193
238
  * Timed, viewport-aligned interactions shared by all scenarios, moving like a person (see motion.js).
194
239
  * `tabs` are the Tabs Capture follows (follow-tabs.js); the Director acts only on the one in front.
195
240
  * `notes` collects the camera's focus targets and `wide` windows, each scroll (`scrolls`, { t, end }),
241
+ * each Select All `type` pressed to replace a field's text (`replaced`, { t, end, tab }),
196
242
  * where each Line starts (`said`),
197
243
  * each fast-forwarded wait (`forwarded`) and the pointer path no Tab could see (`pointer`, as
198
244
  * [epoch ms, x, y, tab]), and each element masked (`elements`, { id, tab, name }) with its mask
@@ -201,8 +247,8 @@ export function clockOf({ startedAt, voiced = null }, { focus: focusTargets, sai
201
247
  * equally human ways to move. `signal` aborts once the Scenario has run, when masks stop following.
202
248
  */
203
249
  export function createDirector(tabs, { startedAt, fps, voiced = null, speed = 1, seed = 1, signal }, notes) {
204
- const { wide: wideWindows, pointer, elements = [], masks = [], scrolls = [] } = notes;
205
- Object.assign(notes, { elements, masks, scrolls });
250
+ const { wide: wideWindows, pointer, elements = [], masks = [], scrolls = [], replaced = [] } = notes;
251
+ Object.assign(notes, { elements, masks, scrolls, replaced });
206
252
  let cursor = { x: 0, y: 0, tab: tabs.front.id };
207
253
  const rand = random(seed);
208
254
  const clock = clockOf({ startedAt, voiced }, notes, () => tabs.front.id), { wait, time, focus, fastForward, say } = clock;
@@ -317,11 +363,26 @@ export function createDirector(tabs, { startedAt, fps, voiced = null, speed = 1,
317
363
  const { duration } = options(opts, 'duration');
318
364
  await approach(locator, duration, 'Hover');
319
365
  }
366
+ /**
367
+ * Clicks a field and types into it. `replace: true` first selects what the field holds, as a person
368
+ * does with Select All, so the first character replaces it and the field never shows empty; with no
369
+ * text, it empties the field. That Select All is typing, not a Shortcut (`replaced`).
370
+ */
320
371
  function type(locator, text, opts) {
321
- const { msPerChar = 70 / speed, ...rest } = options(opts, 'msPerChar');
372
+ const { msPerChar = 70 / speed, replace = false, ...rest } = options(opts, 'msPerChar');
322
373
  return act(rest, async () => {
323
374
  await click(locator, rest);
324
375
  const { page } = await inFront(), chars = [...text], delays = typingDelays(text, msPerChar, rand);
376
+ if (replace) {
377
+ const target = await located(locator, 'Type'), focused = await target.evaluate(focusedNotTextField);
378
+ if (focused) throw new Error(`d.type(${target}, { replace: true }) needs a text field, but after the click ${focused} has focus`);
379
+ await pause('beforeKey');
380
+ const start = time();
381
+ await page.keyboard.press('ControlOrMeta+A', { delay: pauseMs('press', speed, rand) });
382
+ replaced.push({ t: start, end: time(), tab: tabs.front.id });
383
+ await pause('afterKey');
384
+ if (!chars.length) await page.keyboard.press('Backspace');
385
+ }
325
386
  for (let i = 0; i < chars.length; i++) {
326
387
  if (i) await wait(delays[i - 1]);
327
388
  await page.keyboard.type(chars[i]);
@@ -362,15 +423,19 @@ export function createDirector(tabs, { startedAt, fps, voiced = null, speed = 1,
362
423
  // The page may replace the element, or navigate; watching again follows what the locator matches now.
363
424
  return followMask({ id, tab: tab.id, name: String(target), t, effect, params }, notes, { watch, skip: () => target.page().isClosed(), signal, time });
364
425
  }
365
- /** The Director's plan to scroll to `target` (scrollPlan), with where the target's frame shows on the page. */
426
+ /**
427
+ * The Director's plan to scroll to `target` (scrollPlan), with where the target's frame shows on the
428
+ * page and whether that frame is an iframe; null when the target has no visible box.
429
+ */
366
430
  async function scrollSteps(target, block, inline) {
367
431
  const handle = await target.elementHandle();
368
432
  try {
369
- const map = await placeOf(await handle.ownerFrame());
433
+ const frame = await handle.ownerFrame(), map = await placeOf(frame), framed = Boolean(frame.parentFrame());
370
434
  const point = { x: (cursor.x - map.x) / map.sx, y: (cursor.y - map.y) / map.sy };
371
435
  const plan = await handle.evaluate(scrollPlan, { block, inline, point, margin: SCROLL_MARGIN });
372
- if (!plan) throw new Error('Scroll target has no visible bounding box');
373
- return { map, steps: plan.steps };
436
+ if (!plan) return null;
437
+ if (framed) for (const step of plan.steps) if (step.page) step.name = "the iframe's page";
438
+ return { map, framed, steps: plan.steps };
374
439
  } finally { await handle.dispose(); }
375
440
  }
376
441
  /** Turns the wheel by `delta` CSS px over `duration` ms, a little each frame, starting fast and settling long. */
@@ -395,24 +460,33 @@ export function createDirector(tabs, { startedAt, fps, voiced = null, speed = 1,
395
460
  async function scroll(locator, opts) {
396
461
  const { duration, block = 'start', inline = 'nearest' } = options(opts, 'duration');
397
462
  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}'`);
398
- const target = await located(locator, 'Scroll'), times = new Map(), start = time();
399
- let first = true;
463
+ const target = await located(locator, 'Scroll'), times = new Map(), sent = new Map(), start = time();
464
+ // Each failure names the call, so a Scenario with many scrolls says which one failed and when.
465
+ const fail = text => new Error(`d.scroll(${target}) at ${start.toFixed(1)} s ${text}`);
466
+ const startBox = await boxOnPage(target);
467
+ let first = true, plan = await scrollSteps(target, block, inline);
468
+ if (!plan) throw fail('found no visible box for its target; wait until it shows, such as with await locator.waitFor()');
469
+ const begun = plan;
400
470
  for (;;) {
401
- const { map, steps } = await scrollSteps(target, block, inline);
471
+ const { map, steps } = plan;
402
472
  const step = steps.find(({ index, delta }) => {
403
473
  const far = Math.max(Math.abs(delta.x), Math.abs(delta.y)), done = times.get(index) ?? 0;
404
474
  return far >= 1 && (done === 0 || (done === 1 && far > CORRECTION_PX));
405
475
  });
406
476
  if (!step) break;
407
477
  const { page } = await inFront();
408
- if (step.aim === false) throw new Error(`Scroll cannot reach ${step.name}: no part of it a wheel would scroll shows`);
478
+ if (step.aim === false) throw fail(`cannot reach ${step.name}: no part of it a wheel would scroll shows`);
409
479
  if (step.aim) await glide(onPage(map, { ...step.aim, width: 0, height: 0 }));
410
480
  await wheel(page, step.delta, first && duration !== undefined ? duration : scrollMs(Math.hypot(step.delta.x, step.delta.y), { speed }));
411
481
  first = false;
412
482
  times.set(step.index, (times.get(step.index) ?? 0) + 1);
413
- const after = (await scrollSteps(target, block, inline)).steps[step.index];
483
+ const total = sent.get(step.index) ?? { x: 0, y: 0 };
484
+ sent.set(step.index, { x: total.x + step.delta.x, y: total.y + step.delta.y });
485
+ plan = await scrollSteps(target, block, inline);
486
+ if (!plan) throw fail(`lost its target: it no longer has a visible box, as when the page replaces or hides it; ${SETTLE}`);
487
+ const after = plan.steps[step.index];
414
488
  if (after?.at.x === step.at.x && after?.at.y === step.at.y) {
415
- 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`);
489
+ throw fail(`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`);
416
490
  }
417
491
  }
418
492
  if (!first) {
@@ -422,7 +496,12 @@ export function createDirector(tabs, { startedAt, fps, voiced = null, speed = 1,
422
496
  }
423
497
  const box = await boxOnPage(target), { viewport } = tabs.front;
424
498
  if (!box || box.x + box.width <= 0 || box.y + box.height <= 0 || box.x >= viewport.width || box.y >= viewport.height) {
425
- 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\'))');
499
+ // Where everything ended, read with the box: the page may have moved during the pause after the wheel.
500
+ const end = await scrollSteps(target, block, inline) ?? plan;
501
+ const containers = begun.steps.map(step => ({ step, last: end.steps[step.index] }))
502
+ .filter(({ step, last }) => last?.name === step.name && (sent.has(step.index) || last.at.x !== step.at.x || last.at.y !== step.at.y))
503
+ .map(({ step, last }) => ({ name: step.name, from: step.at, to: last.at, sent: sent.get(step.index) ?? null }));
504
+ throw fail(`could not bring the target into view: ${outOfView({ startBox, box, startMap: begun.map, map: end.map, viewport, framed: end.framed, containers })}`);
426
505
  }
427
506
  return box;
428
507
  }
package/src/edit.js CHANGED
@@ -24,7 +24,7 @@ export const DEFAULT_STYLE = {
24
24
  // frame over which the camera and the Cursor blur as they move (shutter.js); 0 turns blur off.
25
25
  output: { width: 3840, height: 2160, quality: 22, shutter: 0.5 },
26
26
  // padding is a fraction of the short side, one number or [top, right, bottom, left]; radius is in 1080p pixels.
27
- frame: { padding: 0.08, radius: 12, chrome: { draw: 'browser' }, background: [{ shader: 'fluted' }], effects: [{ shader: 'shadow' }] },
27
+ frame: { padding: 0.05, radius: 12, chrome: { draw: 'browser' }, background: [{ shader: 'fluted' }], effects: [{ shader: 'shadow' }] },
28
28
  // See camera.js. Each target is framed with `padding` CSS px around it, zooming at most `maxZoom`;
29
29
  // fits below `minZoom` stay wide. The camera arrives `lead` before an action, holds `hold` after the
30
30
  // last one in a segment, settles in about `response`, and returns wide `endWide` before the end.
@@ -34,8 +34,9 @@ export const DEFAULT_STYLE = {
34
34
  // Meta shows only with `singleKeys`. `false` shows none.
35
35
  keycaps: { draw: 'keycaps', duration: 1.5, singleKeys: false },
36
36
  // Drawn over the Final, outside the camera, while a Line is spoken; `burn: false` keeps them to the
37
- // subtitle files. Rows hold up to `maxChars` (about 16 in Chinese, 42 otherwise), `maxRows` to a cue,
38
- // each shown at least `minDuration`.
37
+ // subtitle files. While burned in with Lines to show, they add `room` (0.04 of the short side) to the
38
+ // frame's bottom padding and sit in the space below the window. Rows hold up to `maxChars` (about 16
39
+ // in Chinese, 42 otherwise), `maxRows` (1) to a cue, each shown at least `minDuration`.
39
40
  subtitles: { draw: 'subtitles', burn: true },
40
41
  // Drawn over the Final, outside the camera, while it fast-forwards, such as { draw: 'fast-forward' };
41
42
  // `false` shows none.
package/src/narration.js CHANGED
@@ -1,16 +1,23 @@
1
1
  /**
2
2
  * Narration timing and Subtitles, shared by Node and the render page. Pure functions, no imports.
3
3
  *
4
- * A placed Line is `{ id, text, start, duration, words? }`: `start` is seconds of Source time,
5
- * `duration` is measured from its audio, and each word is `{ text, start, end }` in seconds from the
6
- * start of the Line's audio. Subtitle cues are `{ id, start, end, rows }`, `id` naming their Line.
4
+ * A placed Line is `{ id, text, start, duration, words?, rows }`: `start` is seconds of Source time,
5
+ * `duration` is measured from its audio, each word is `{ text, start, end }` in seconds from the
6
+ * start of the Line's audio, and `rows` is its text as subtitle rows. Node breaks the rows once
7
+ * (`withRows`) and hands them to the render page, since where rows break depends on the runtime's
8
+ * dictionary. Subtitle cues are `{ id, start, end, rows }`, `id` naming their Line.
7
9
  */
8
10
 
9
- const CJK = /[⺀-鿿豈-﫿＀-￯]/u;
11
+ const CJK_CHARS = '⺀-鿿豈-﫿＀-￯';
12
+ const CJK = new RegExp(`[${CJK_CHARS}]`, 'u');
13
+ /** Spaces, a run of CJK text, or a run of other non-space characters. */
14
+ const RUNS = new RegExp(`\\s+|[${CJK_CHARS}]+|[^\\s${CJK_CHARS}]+`, 'gu');
10
15
  const SENTENCE_END = /[.!?。!?…]["'”’))]*$/u;
11
16
  const CLAUSE_END = /[,;:,、;:—–]["'”’))]*$/u;
12
17
  // Closing punctuation never starts a row; it joins what it follows.
13
18
  const CLOSING = /^[.,;:!?)\]}'"”’。,、;:!?)》」』…]/u;
19
+ // Opening punctuation never ends a row; what follows it joins it.
20
+ const OPENING = /[(\[{“‘(《「『【〈]$/u;
14
21
  /** The characters that are spoken, which word timings count: no spaces or punctuation. */
15
22
  const spoken = text => Array.from(text.replace(/[\s\p{P}\p{S}]/gu, '')).length;
16
23
  const length = text => Array.from(text).length;
@@ -18,21 +25,37 @@ const length = text => Array.from(text).length;
18
25
  /** Whether `text` (or a language tag such as zh-CN) is written without spaces between words. */
19
26
  export const isCjk = (text, language) => /^(zh|ja|ko)\b/i.test(language ?? '') || CJK.test(text);
20
27
 
28
+ let segmenter;
29
+ /** A run of CJK text as its words, by the dictionary of `Intl.Segmenter`, made once on first use. */
30
+ const cjkWords = run => Array.from((segmenter ??= new Intl.Segmenter('zh', { granularity: 'word' })).segment(run), s => s.segment);
31
+
32
+ /**
33
+ * Whether `piece` belongs to the atom before it: closing punctuation, what an opening quote opens,
34
+ * or a lone CJK character after a word that has not taken one yet. The dictionary leaves many a
35
+ * word's character on its own (保|命, 安全|带) and a row should not start with a lone 的; taking one
36
+ * character at most keeps a run of lone characters from becoming one atom wider than a row.
37
+ */
38
+ const joinsLast = (last, piece) => CLOSING.test(piece) || OPENING.test(last.text)
39
+ || (last.cjk && !last.joined && /^\p{L}$/u.test(piece) && /\p{L}$/u.test(last.text));
40
+
21
41
  /**
22
- * The text broken into atoms that rows never split: a CJK character or a run of other non-space
23
- * characters, with any closing punctuation after it. `space` marks a space before the atom.
42
+ * The text broken into atoms that rows never split: a CJK word or a run of other non-space
43
+ * characters, with any punctuation that clings to it. `space` marks a space before the atom.
24
44
  */
25
45
  function atoms(text) {
26
46
  const list = [];
27
- for (const [piece] of text.trim().matchAll(/\s+|[⺀-鿿豈-﫿＀-￯]|[^\s⺀-鿿豈-﫿＀-￯]+/gu)) {
28
- if (/^\s+$/u.test(piece)) { if (list.length) list.at(-1).spaceAfter = true; continue; }
29
- const last = list.at(-1);
30
- if (last && !last.spaceAfter && CLOSING.test(piece)) last.text += piece;
31
- else list.push({ text: piece, space: Boolean(last?.spaceAfter) });
47
+ for (const [run] of text.trim().matchAll(RUNS)) {
48
+ if (/^\s+$/u.test(run)) { if (list.length) list.at(-1).spaceAfter = true; continue; }
49
+ const cjk = CJK.test(run);
50
+ for (const piece of cjk ? cjkWords(run) : [run]) {
51
+ const last = list.at(-1);
52
+ if (last && !last.spaceAfter && joinsLast(last, piece)) { last.text += piece; last.joined = true; }
53
+ else list.push({ text: piece, space: Boolean(last?.spaceAfter), cjk });
54
+ }
32
55
  }
33
56
  return list;
34
57
  }
35
- /** How good a break after `atom` is: sentence end, clause end, between words, inside CJK text. */
58
+ /** How good a break after `atom` is: sentence end, clause end, between spaced words, between CJK words. */
36
59
  const breakScore = (atom, next) => SENTENCE_END.test(atom.text) ? 3 : CLAUSE_END.test(atom.text) ? 2 : next?.space ? 1 : 0.5;
37
60
  const join = list => list.map((atom, i) => (i && atom.space ? ' ' : '') + atom.text).join('');
38
61
 
@@ -40,21 +63,33 @@ const join = list => list.map((atom, i) => (i && atom.space ? ' ' : '') + atom.t
40
63
  * The text as subtitle rows of at most `maxChars` characters, broken at the best place: a sentence
41
64
  * end after the first third of an even row, then a clause end after its first half, then the word
42
65
  * boundary nearest an even width, so a Line one word too long does not leave that word alone on a
43
- * row. A single word longer than a row gets a row of its own.
66
+ * row. Rows that do not fit their count between words take one more row, all of them even again. A
67
+ * single word longer than a row gets a row of its own.
44
68
  */
45
69
  export function subtitleRows(text, maxChars) {
46
- const total = length(text.trim()), even = Math.min(maxChars, Math.ceil(total / Math.ceil(total / maxChars)));
70
+ const list = atoms(text), total = length(text.trim());
71
+ for (let count = Math.ceil(total / maxChars); ; count++) {
72
+ const rows = rowsOf(list, maxChars, Math.min(maxChars, Math.ceil(total / count)));
73
+ if (rows.length <= count) return rows;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Atoms as rows of at most `maxChars` characters, each broken as near `even` as its best break
79
+ * allows, at the fuller row of two equally near, so the Line keeps to fewer rows.
80
+ */
81
+ function rowsOf(list, maxChars, even) {
47
82
  const least = { 3: even * 0.3, 2: even * 0.5 };
48
83
  const rows = [];
49
84
  let row = [];
50
- for (const atom of atoms(text)) {
85
+ for (const atom of list) {
51
86
  row.push(atom);
52
87
  if (row.length < 2 || length(join(row)) <= maxChars) continue;
53
88
  let cut = row.length - 1, best = -1, distance = Infinity;
54
89
  for (let i = 0; i < row.length - 1; i++) {
55
90
  const score = breakScore(row[i], row[i + 1]), prefix = length(join(row.slice(0, i + 1)));
56
91
  if (prefix < (least[score] ?? 0)) continue;
57
- if (score > best || (score === best && Math.abs(prefix - even) < distance)) { best = score; distance = Math.abs(prefix - even); cut = i + 1; }
92
+ if (score > best || (score === best && Math.abs(prefix - even) <= distance)) { best = score; distance = Math.abs(prefix - even); cut = i + 1; }
58
93
  }
59
94
  rows.push(join(row.slice(0, cut)));
60
95
  row = row.slice(cut);
@@ -96,17 +131,20 @@ export function wordInLine(line, text, from = 0) {
96
131
  return { at: clock(line).start(spoken(line.text.slice(0, index))), next: index + match[0].length };
97
132
  }
98
133
 
134
+ /** Lines with their text broken into subtitle rows of `maxChars`, by default about 16 characters in CJK text and 42 otherwise. */
135
+ export const withRows = (lines, language, maxChars) =>
136
+ lines.map(line => ({ ...line, rows: subtitleRows(line.text, maxChars ?? (isCjk(line.text, language) ? 16 : 42)) }));
137
+
99
138
  /**
100
- * Subtitle cues for placed Lines: each Line's rows, `maxRows` to a cue (a cue also ends after a
139
+ * Subtitle cues for placed Lines: each Line's `rows`, `maxRows` to a cue (a cue also ends after a
101
140
  * sentence), shown while they are spoken. A cue shorter than `minDuration` takes time from the next
102
141
  * cue of its Line, or from the silence after its Line, up to `end`, the end of the Final.
103
142
  */
104
- export function subtitleCues(lines, { language, maxChars, maxRows = 2, minDuration = 1, end = Infinity } = {}) {
143
+ export function subtitleCues(lines, { maxRows = 1, minDuration = 1, end = Infinity } = {}) {
105
144
  const cues = [];
106
145
  for (const line of [...lines].sort((a, b) => a.start - b.start)) {
107
- const width = maxChars ?? (isCjk(line.text, language) ? 16 : 42), said = clock(line);
108
- const groups = [];
109
- for (const row of subtitleRows(line.text, width)) {
146
+ const said = clock(line), groups = [];
147
+ for (const row of line.rows) {
110
148
  const last = groups.at(-1);
111
149
  if (last && last.length < maxRows && !SENTENCE_END.test(last.at(-1))) last.push(row); else groups.push([row]);
112
150
  }
@@ -131,8 +169,8 @@ export function subtitleCues(lines, { language, maxChars, maxRows = 2, minDurati
131
169
  /** Whether the Edit's `subtitles` item draws them into the Final; otherwise they go only to the subtitle files. */
132
170
  export const burnsIn = subtitles => Boolean(subtitles) && subtitles.burn !== false;
133
171
 
134
- /** The cues of placed Lines as the Edit's `subtitles` item lays them out, ending by `end`. */
135
- export const cuesFor = (lines, language, subtitles, end) => subtitleCues(lines, { language, maxChars: subtitles?.maxChars, maxRows: subtitles?.maxRows, minDuration: subtitles?.minDuration, end });
172
+ /** The cues of placed Lines as the Edit's `subtitles` item lays them out, ending by `end`; its `maxChars` already broke their rows. */
173
+ export const cuesFor = (lines, subtitles, end) => subtitleCues(lines, { maxRows: subtitles?.maxRows, minDuration: subtitles?.minDuration, end });
136
174
 
137
175
  /**
138
176
  * What stops Lines from playing as placed: a Line overlapping the next one, starting before the
package/src/pipeline.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs/promises';
2
+ import { realpathSync } from 'node:fs';
2
3
  import { dirname, extname, join, resolve } from 'node:path';
3
4
  import { pathToFileURL } from 'node:url';
4
5
  import { doctor } from './environment.js';
@@ -13,11 +14,12 @@ import { appLocators } from './app-locators.js';
13
14
  import { startDesktop } from './app-capture.js';
14
15
  import { desktopWarnings } from './desktop.js';
15
16
  import { collectTimeline } from './probe.js';
17
+ import { isSelectAll } from './shortcuts.js';
16
18
  import { createEdit, evenSize, merge, withDefaults } from './edit.js';
17
19
  import { loadLook, resolvedLook, applyLook, lookFromEdit, saveLook, summarize } from './look.js';
18
20
  import { ensureHome } from './home.js';
19
21
  import { absolute, bundle, forRender } from './styles.js';
20
- import { burnsIn, cuesFor, isCjk, lineProblems, toSrt, toVtt } from './narration.js';
22
+ import { burnsIn, cuesFor, isCjk, lineProblems, toSrt, toVtt, withRows } from './narration.js';
21
23
  import { linesInFinal, timeMap } from './time-map.js';
22
24
  import { maskWarnings } from './masks.js';
23
25
  import pkg from '../package.json' with { type: 'json' };
@@ -110,6 +112,9 @@ export function captureScale(chosen, gpu) {
110
112
  return gpu?.accelerated === false ? { resolutionScale: 1, lowered: true } : { resolutionScale: 2, lowered: false };
111
113
  }
112
114
 
115
+ /** Seconds the page's clock may differ from the Director's when both time one key press. */
116
+ const CLOCK_SLACK_S = 0.05;
117
+
113
118
  /**
114
119
  * The Timeline from `take` (its url, viewport and scale), what Capture observed in each Tab (`observed`,
115
120
  * the probe's by Tab id), what the Director noted and what the recorder saw: every input and page load carries the Tab it happened in,
@@ -123,12 +128,15 @@ export function timelineOf(take, stopped, observed, notes, startedAtMs) {
123
128
  const frameInput = { turned: [...observed.values()].flatMap(seen => seen.turned).sort((a, b) => a - b), unplaced: [...observed.values()].flatMap(seen => seen.unplaced).sort((a, b) => a - b) };
124
129
  // Each element a mask follows, with the boxes the probe in its Tab saw it at.
125
130
  const elements = (notes.elements ?? []).map(element => ({ ...element, boxes: observed.get(element.tab)?.watched?.find(watched => watched.id === element.id)?.boxes ?? [] }));
131
+ // The Select All d.type pressed to replace a field's text is typing, not a Shortcut. The page timed it by its own clock.
132
+ const selectedAll = event => event.type === 'shortcut' && isSelectAll(event.keys)
133
+ && (notes.replaced ?? []).some(({ t, end, tab }) => tab === event.tab && event.t >= t - CLOCK_SLACK_S && event.t <= end + CLOCK_SLACK_S);
126
134
  return {
127
135
  schemaVersion: SCHEMA_VERSION, ...take, duration: stopped.durationSeconds,
128
136
  tabs: stopped.tabs.map(({ id, opener, opened, closed, viewport, url, start }) => ({ id, opener, opened, closed, viewport, url, start })),
129
137
  pointer: pointer.sort((a, b) => a[0] - b[0]), shapes, ...((frameInput.turned.length || frameInput.unplaced.length) && { frameInput }), ...(elements.length && { elements }),
130
138
  events: [
131
- ...[...observed].flatMap(([tab, seen]) => inTab(seen.events, tab)),
139
+ ...[...observed].flatMap(([tab, seen]) => inTab(seen.events, tab)).filter(event => !selectedAll(event)),
132
140
  ...notes.focus.map(f => ({ type: 'focus', ...f })), ...notes.said.map(line => ({ type: 'say', ...line })), ...notes.forwarded.map(span => ({ type: 'fastForward', ...span })), ...(notes.masks ?? []).map(mask => ({ type: 'mask', ...mask })),
133
141
  ...(notes.scrolls ?? []).map(span => ({ type: 'scroll', ...span })),
134
142
  ...stopped.tabs.flatMap(tab => inTab(tab.navigations.map(load => ({ type: 'navigate', ...load })), tab.id)),
@@ -251,6 +259,27 @@ export function appReport({ unquit, running }) {
251
259
  return { ...(unquit.length && { quit: false, unquit }), ...(running.length && { running }), note: notes.join(' ') };
252
260
  }
253
261
 
262
+ const realPath = path => { try { return realpathSync(path); } catch { return path; } };
263
+
264
+ /**
265
+ * Names the line of the Scenario at `scenarioPath` that `error` came from, the innermost one on its
266
+ * stack, at the end of its message's first line, so a failed Take says which call failed. An error whose stack
267
+ * does not pass through the Scenario, such as one from a timer it started, is left as it is.
268
+ */
269
+ export function atScenario(error, scenarioPath) {
270
+ if (!(error instanceof Error) || typeof error.stack !== 'string') return error;
271
+ // Node names an imported module by its real path, with any symlink, such as macOS's /var, resolved.
272
+ const files = [...new Set([resolve(scenarioPath), realPath(resolve(scenarioPath))])];
273
+ const names = files.flatMap(file => [pathToFileURL(file).href, file]);
274
+ for (const frame of error.stack.split('\n').filter(line => /^\s+at /.test(line))) {
275
+ for (const name of names) {
276
+ const line = frame.includes(`${name}:`) && /^:(\d+)/.exec(frame.slice(frame.indexOf(`${name}:`) + name.length))?.[1];
277
+ if (line) { error.message = error.message.replace(/^[^\n]*/, first => `${first} (at ${scenarioPath}:${line})`); return error; }
278
+ }
279
+ }
280
+ return error;
281
+ }
282
+
254
283
  /** New take directories are exclusive: reruns never overwrite a previous take. */
255
284
  export async function recordScenario(scenarioPath, outputDir, options = {}) {
256
285
  const scenario = await import(pathToFileURL(resolve(scenarioPath)).href);
@@ -295,6 +324,7 @@ export async function recordScenario(scenarioPath, outputDir, options = {}) {
295
324
  project = { ...project, status: 'captured', duration: timeline.duration, evidence: evidence ?? null };
296
325
  await writeJson(join(dir, 'project.json'), project);
297
326
  } catch (error) {
327
+ atScenario(error, scenarioPath);
298
328
  await writeJson(join(dir, 'project.json'), { ...project, status: 'failed', error: error.message });
299
329
  throw error;
300
330
  }
@@ -341,7 +371,8 @@ async function loadTake(dir) {
341
371
  }
342
372
 
343
373
  /**
344
- * The Narration as Render takes it, or null for a Take without Lines or without a Narration yet (a
374
+ * The Narration as Render takes it, its Lines broken into subtitle rows here so the render page and
375
+ * verify use the same rows, or null for a Take without Lines or without a Narration yet (a
345
376
  * draft whose Lines `d.say` placed before any audio existed). Burned-in Chinese, Japanese or Korean
346
377
  * Subtitles drawn by the built-in need a font: macOS has PingFang SC; elsewhere the Edit or Look names one.
347
378
  */
@@ -352,7 +383,7 @@ function narrationForRender(edit, narration, dir) {
352
383
  if (builtin && process.platform !== 'darwin' && lines.some(line => isCjk(line.text, narration.language))) {
353
384
  throw new Error('Burned-in Subtitles in this language need a font outside macOS: add one to the Edit or Look as subtitles.files.font (a .woff2, .ttf or .otf file), or set subtitles.burn to false');
354
385
  }
355
- return { language: narration.language, volume: edit.narration.volume, lines };
386
+ return { volume: edit.narration.volume, lines: withRows(lines, narration.language, subtitles?.maxChars) };
356
387
  }
357
388
 
358
389
  /**
@@ -368,8 +399,9 @@ export async function previewTake(directory, refs = [], { at } = {}) {
368
399
  const host = config.url && new URL(config.url).host;
369
400
  const looks = await Promise.all(refs.map(ref => loadLook(ref)));
370
401
  const tiles = [{ name: 'current', edit }, ...looks.map(look => ({ name: look.name, edit: applyLook(edit, resolvedLook(look), host) }))];
371
- const files = {}, shown = tiles.map(({ name, edit }) => ({ name, edit: forRender(atShortSide(edit, 1080), dir, files).edit }));
372
- const png = await composePreview({ sources: sourcesOf(dir, timeline), timeline, at, tiles: shown, files, narration: narrationForRender(edit, narration, dir) });
402
+ // Each tile's own Narration, so its rows follow that tile's subtitles.maxChars.
403
+ const files = {}, shown = tiles.map(({ name, edit }) => ({ name, edit: forRender(atShortSide(edit, 1080), dir, files).edit, narration: narrationForRender(edit, narration, dir) }));
404
+ const png = await composePreview({ sources: sourcesOf(dir, timeline), timeline, at, tiles: shown, files });
373
405
  const preview = join(dir, 'preview.png');
374
406
  await fs.writeFile(preview, png);
375
407
  return { preview, at: at ?? 'end, camera wide', tiles: tiles.map(({ name, edit }) => ({ name, summary: summarize(lookFromEdit(edit)) })) };
@@ -431,7 +463,7 @@ async function narrationProblems(dir, edit, narration, media, map, end) {
431
463
  const inFinal = linesInFinal(narration.lines.map(line => ({ ...line, duration: measured.get(line.id).duration })), map), { lines } = inFinal;
432
464
  problems.push(...inFinal.problems, ...lineProblems(lines, end));
433
465
  if (problems.length) return problems;
434
- const cues = cuesFor(lines, narration.language, edit.subtitles, end);
466
+ const cues = cuesFor(lines, edit.subtitles, end);
435
467
  for (const [name, format] of SUBTITLE_FILES) {
436
468
  const text = await fs.readFile(join(dir, name), 'utf8').catch(() => null);
437
469
  if (text !== format(cues)) problems.push(`${name} ${text === null ? 'is missing' : 'does not match the Lines'}; render again`);
package/src/probe.js CHANGED
@@ -14,10 +14,10 @@ import { contentOf } from './frames.js';
14
14
  * positioning, translation and scaling are all followed. A rotated, skewed or 3D-transformed iframe is
15
15
  * placed as if it were only scaled, and noted. Each document also measures the elements a mask follows
16
16
  * (`watch`), once per animation frame, and sends their boxes whenever they change.
17
- * Times are epoch milliseconds until collectTimeline rebases them. `contentOf` is frames.js's, passed
18
- * in because the probe runs as page source.
17
+ * Times are epoch milliseconds until collectTimeline rebases them. `contentOf` is frames.js's and
18
+ * `textField` this module's, passed in because the probe runs as page source.
19
19
  */
20
- function probe(contentOf) {
20
+ function probe(contentOf, textField) {
21
21
  window.__cuetakeProbe?.dispose();
22
22
  const abort = new AbortController();
23
23
  const send = record => { try { window.__cuetakeRecord?.(record)?.catch?.(() => {}); } catch {} };
@@ -39,8 +39,6 @@ function probe(contentOf) {
39
39
  for (let inner; element?.shadowRoot && (inner = element.shadowRoot.elementFromPoint(x, y)) && inner !== element;) element = inner;
40
40
  return element;
41
41
  };
42
- const editable = element => element.isContentEditable
43
- || element.matches('textarea:not(:disabled), input:not(:disabled):not([type=button],[type=submit],[type=reset],[type=checkbox],[type=radio],[type=range],[type=color],[type=file],[type=image])');
44
42
  const overText = (element, x, y) => {
45
43
  const caret = document.caretPositionFromPoint?.(x, y), node = caret?.offsetNode;
46
44
  const parent = node?.nodeType === Node.TEXT_NODE && node.data.trim() && element.contains(node) && node.parentElement;
@@ -53,7 +51,7 @@ function probe(contentOf) {
53
51
  const element = deepest(x, y);
54
52
  if (!element) return 'default';
55
53
  const keyword = getComputedStyle(element).cursor.match(/([a-z-]+)\s*$/)?.[1] ?? 'auto';
56
- return keyword !== 'auto' ? keyword : editable(element) || overText(element, x, y) ? 'text' : 'default';
54
+ return keyword !== 'auto' ? keyword : textField(element) || overText(element, x, y) ? 'text' : 'default';
57
55
  };
58
56
  // Read after the page's own handlers have run, since they often set the cursor themselves. A move
59
57
  // carries the shape it found, since the pointer may have left this frame and come back to the same
@@ -92,7 +90,7 @@ function probe(contentOf) {
92
90
  on('keydown', e => {
93
91
  const element = focused();
94
92
  const { key, code, ctrlKey, altKey, shiftKey, metaKey, repeat } = e;
95
- send({ kind: 'key', ms: at(e), box: box(element), key, code, ctrlKey, altKey, shiftKey, metaKey, repeat, field: Boolean(element && editable(element)) });
93
+ send({ kind: 'key', ms: at(e), box: box(element), key, code, ctrlKey, altKey, shiftKey, metaKey, repeat, field: Boolean(element && textField(element)) });
96
94
  sampleShape(at(e));
97
95
  });
98
96
  on('keyup', e => sampleShape(at(e)));
@@ -168,7 +166,20 @@ function probe(contentOf) {
168
166
  send({ kind: 'hello' });
169
167
  }
170
168
 
171
- const collectors = new WeakMap(), script = `(${probe})(${contentOf})`;
169
+ /** Whether an element takes typed text: an enabled text input or textarea, or editable content. It runs in the page. */
170
+ export function textField(element) {
171
+ return element.isContentEditable
172
+ || element.matches('textarea:not(:disabled), input:not(:disabled):not([type=button],[type=submit],[type=reset],[type=checkbox],[type=radio],[type=range],[type=color],[type=file],[type=image])');
173
+ }
174
+
175
+ const collectors = new WeakMap(), script = `(${probe})(${contentOf}, ${textField})`;
176
+
177
+ /**
178
+ * The page's frames that hold a document now. One that has not loaded one yet, such as a lazy iframe
179
+ * the page has not scrolled near, would keep an evaluate in it waiting until it does, which may be
180
+ * never; the init script reaches it when it loads.
181
+ */
182
+ const loadedFrames = page => page.frames().filter(frame => frame.url() !== '');
172
183
 
173
184
  /**
174
185
  * Installs the probe in every frame of the page, now and in frames that load later, and starts
@@ -209,7 +220,7 @@ export async function installProbe(page) {
209
220
  records.push({ kind: 'top', frame: idOf(page.mainFrame()) });
210
221
  Object.assign(collector, { idOf, link, records });
211
222
  // Parents first (frames() lists them in tree order), so each child finds its parent's probe to link to.
212
- for (const frame of page.frames()) await frame.evaluate(script).catch(() => {});
223
+ for (const frame of loadedFrames(page)) await frame.evaluate(script).catch(() => {});
213
224
  }
214
225
 
215
226
  /** The entry of `list`, sorted by `ms`, last at or before `ms`, or its first. */
@@ -315,7 +326,7 @@ export async function collectTimeline(page, startedAtMs) {
315
326
  const collector = collectors.get(page);
316
327
  if (!collector) throw new Error('The Timeline probe was never installed on this page');
317
328
  // Records a frame sent before this call arrive before its answer to an evaluate.
318
- await Promise.all(page.frames().map(frame => frame.evaluate(() => 0).catch(() => {})));
329
+ await Promise.all(loadedFrames(page).map(frame => frame.evaluate(() => 0).catch(() => {})));
319
330
  while (collector.pending.size) await Promise.all(collector.pending);
320
331
  const raw = placeRecords(collector.records);
321
332
  const t = ms => Math.round(ms - startedAtMs) / 1000;
@@ -169,7 +169,7 @@ void main() { color = texture(uSprite, uv) * uAlpha; }`;
169
169
 
170
170
  // Item keys CueTake reads itself; every other key is a parameter for the item's shader or drawing code.
171
171
  const OWN_KEYS = new Set(['shader', 'draw', 'image', 'files', 'ref', 'kind', 'url']);
172
- const SLOT_KEYS = new Set(['size', 'hotspot', 'press', 'duration', 'singleKeys', 'reach', 'height', 'burn', 'maxChars', 'maxRows', 'minDuration']);
172
+ const SLOT_KEYS = new Set(['size', 'hotspot', 'press', 'duration', 'singleKeys', 'reach', 'height', 'burn', 'room', 'maxChars', 'maxRows', 'minDuration']);
173
173
  const paramsOf = item => Object.fromEntries(Object.entries(item).filter(([key]) => !OWN_KEYS.has(key) && (item.kind === 'shader' || !SLOT_KEYS.has(key))));
174
174
  const fail = (item, error) => new Error(`${item.ref}: ${error?.message ?? error}`);
175
175
 
@@ -523,16 +523,18 @@ async function loadClickEffect(item, cursor) {
523
523
 
524
524
  /**
525
525
  * Drawing code over the whole Final in 1080p pixels, outside the camera, such as Subtitles and keycaps:
526
- * `draw(ctx, { width, height, ...what, params, files })`. `canvas(width, height, what)` rasterizes it at output size.
526
+ * `draw(ctx, { width, height, below, ...what, params, files })`. `below` is the space under the window
527
+ * with the camera wide, given here in stage pixels and to the drawing in 1080p pixels.
528
+ * `canvas(width, height, what)` rasterizes it at output size.
527
529
  */
528
- async function loadScreenDrawing(item, name) {
530
+ async function loadScreenDrawing(item, name, below) {
529
531
  if (item.kind !== 'draw') throw fail(item, `${name} are drawing code`);
530
532
  const module = await loadModule(item), files = await loadFiles(item), params = paramsOf(item);
531
533
  return {
532
534
  canvas(width, height, what) {
533
535
  const unit = Math.min(width, height) / 1080, ctx = canvas2d(width, height);
534
536
  ctx.scale(unit, unit);
535
- try { module.draw(ctx, { width: width / unit, height: height / unit, ...what, params, files }); } catch (error) { throw fail(item, error); }
537
+ try { module.draw(ctx, { width: width / unit, height: height / unit, below: below / unit, ...what, params, files }); } catch (error) { throw fail(item, error); }
536
538
  return ctx.canvas;
537
539
  },
538
540
  };
@@ -563,7 +565,7 @@ async function prepareNarration(narration, subtitles, seconds, map) {
563
565
  const { lines: placed, problems: forwarded } = linesInFinal(narration.lines.map((line, i) => ({ ...line, duration: buffers[i].duration })), map);
564
566
  const problems = [...forwarded, ...lineProblems(placed, seconds)];
565
567
  if (problems.length) throw new Error(`The Narration does not fit: ${problems.join('; ')}`);
566
- return { placed, buffers, cues: cuesFor(placed, narration.language, subtitles, seconds) };
568
+ return { placed, buffers, cues: cuesFor(placed, subtitles, seconds) };
567
569
  }
568
570
 
569
571
  /** The Lines mixed into one mono track `seconds` long, each at its start and volume. */
@@ -704,7 +706,9 @@ async function createScene(edit, viewport, { pointer, shapes, events, tabs, elem
704
706
  if (maskIssues.length) throw new Error(`The masks cannot be drawn: ${maskIssues.join('; ')}`);
705
707
  const masks = maskTrack(edit.masks, elements, map);
706
708
  const chrome = frame.chrome ? await loadChrome(frame.chrome, viewport.width) : null;
707
- const stage = layout(edit, viewport, chrome?.height ?? 0);
709
+ // Burned-in Subtitles take their room below the window, 0.04 of the short side unless the item says.
710
+ const subtitled = burnsIn(subtitles) && cues.length > 0;
711
+ const stage = layout(edit, viewport, chrome?.height ?? 0, subtitled ? subtitles.room ?? 0.04 : 0);
708
712
  const compositor = createCompositor(stage, brandOf(firstFrame));
709
713
  const pages = new Map();
710
714
  const upload = (tab, videoFrame) => {
@@ -781,9 +785,9 @@ async function createScene(edit, viewport, { pointer, shapes, events, tabs, elem
781
785
  const drawn = new Set(Object.keys(cursorSprites)), track = cursor && cursorTrack({ pointer: placed.pointer, shapes, events: placed.events }, cursor);
782
786
  const effect = clickEffect ? await loadClickEffect(clickEffect, cursor ? Object.fromEntries(Object.entries(cursor).filter(([key]) => !['ref', 'kind', 'url', 'files'].includes(key))) : {}) : null;
783
787
  const pressList = presses(placed.events);
784
- const subtitleDrawing = burnsIn(subtitles) && cues.length ? await loadScreenDrawing(subtitles, 'Subtitles') : null;
785
- const keys = keycapTrack(retimed(shortcuts, map), keycaps), keycapDrawing = keys.shows.length ? await loadScreenDrawing(keycaps, 'Keycaps') : null;
786
- const badgeDrawing = fastForwardBadge && map.spans.length ? await loadScreenDrawing(fastForwardBadge, 'Fast-forward badges') : null;
788
+ const subtitleDrawing = subtitled ? await loadScreenDrawing(subtitles, 'Subtitles', stage.below) : null;
789
+ const keys = keycapTrack(retimed(shortcuts, map), keycaps), keycapDrawing = keys.shows.length ? await loadScreenDrawing(keycaps, 'Keycaps', stage.below) : null;
790
+ const badgeDrawing = fastForwardBadge && map.spans.length ? await loadScreenDrawing(fastForwardBadge, 'Fast-forward badges', stage.below) : null;
787
791
  const unit = Math.min(stage.width, stage.height) / 1080, spacing = 2 * unit; // on-screen pixels between the moments a frame averages
788
792
  /** Where stage point `p` shows on screen, in output pixels, under the camera `view`. */
789
793
  const onScreen = (p, view) => [(p[0] - view.x) * view.zoom + stage.width / 2, (p[1] - view.y) * view.zoom + stage.height / 2];
@@ -1081,7 +1085,7 @@ window.cuetakeMeasure = async lines => {
1081
1085
  * A Preview as a base64 PNG: each tile's Edit composed by the same scene as Render, over the Sources at
1082
1086
  * `at` seconds with the Final's camera, or (`at` null) over the last moment with the camera wide.
1083
1087
  */
1084
- window.cuetakePreview = async ({ sources: sourceUrls, duration, viewport, pointer, shapes, events, tabs, elements, windows, tiles, at, narration }) => {
1088
+ window.cuetakePreview = async ({ sources: sourceUrls, duration, viewport, pointer, shapes, events, tabs, elements, windows, tiles, at }) => {
1085
1089
  const map = timeMap(tiles[0]?.edit.fastForward, duration), t = at ?? map.duration, source = map.sourceAt(t);
1086
1090
  // Each Tab's first frame, and its frame at `t`, the latest at or before it or else its first.
1087
1091
  const frames = new Map(), samples = [];
@@ -1102,7 +1106,7 @@ window.cuetakePreview = async ({ sources: sourceUrls, duration, viewport, pointe
1102
1106
  ctx.fillStyle = '#111114'; ctx.fillRect(0, 0, sheet.width, sheet.height);
1103
1107
  ctx.imageSmoothingQuality = 'high';
1104
1108
  ctx.font = '600 22px system-ui, -apple-system, sans-serif'; ctx.textBaseline = 'middle'; ctx.fillStyle = '#e5e7eb';
1105
- for (const [i, { name, edit }] of tiles.entries()) {
1109
+ for (const [i, { name, edit, narration }] of tiles.entries()) {
1106
1110
  const voice = await prepareNarration(narration, edit.subtitles, Math.round(map.duration * edit.output.fps) / edit.output.fps, map);
1107
1111
  const scene = await createScene(edit, viewport, { pointer, shapes, events, tabs: recorded, elements, windows }, sizes, frames.get(recorded[0].id).first, voice?.cues ?? [], map);
1108
1112
  // At `at` the camera moves as in the Final, blurred the same way; otherwise it is wide and still.
package/src/render.js CHANGED
@@ -122,8 +122,8 @@ function forPage(timeline, sources, files) {
122
122
 
123
123
  /**
124
124
  * Composes the Final from each Tab's Source (`sources`, paths by Tab id), the Timeline and the Edit;
125
- * `files` serves the Edit's styling files (styles.js forRender). `narration` ({ language, volume, lines })
126
- * adds its Lines' audio and Subtitles.
125
+ * `files` serves the Edit's styling files (styles.js forRender). `narration` ({ volume, lines })
126
+ * adds its Lines' audio and Subtitles, each Line with the `rows` it is shown in (narration.js withRows).
127
127
  */
128
128
  export async function renderFinal({ sources, finalPath, timeline, edit, files = {}, narration = null }) {
129
129
  const handle = await fs.open(finalPath, 'w');
@@ -137,12 +137,15 @@ export async function renderFinal({ sources, finalPath, timeline, edit, files =
137
137
  } finally { await handle.close(); }
138
138
  }
139
139
 
140
- /** A Preview PNG of `tiles` ([{ name, edit }]) at `at` seconds, or at the end with the camera wide. No Final is touched. */
141
- export async function composePreview({ sources, timeline, tiles, at, files = {}, narration = null }) {
140
+ /**
141
+ * A Preview PNG of `tiles` ([{ name, edit, narration? }]) at `at` seconds, or at the end with the camera
142
+ * wide, each tile with its own Narration as renderFinal takes one. No Final is touched.
143
+ */
144
+ export async function composePreview({ sources, timeline, tiles, at, files = {} }) {
142
145
  const served = { ...files };
143
- const spoken = narration && { ...narration, lines: servedLines(narration.lines, served) };
146
+ const spoken = tiles.map(tile => ({ ...tile, narration: tile.narration && { ...tile.narration, lines: servedLines(tile.narration.lines, served) } }));
144
147
  const take = forPage(timeline, sources, served);
145
- const png = await withRenderPage({ files: served }, page => page.evaluate(options => window.cuetakePreview(options), { ...take, tiles, at: at ?? null, narration: spoken }));
148
+ const png = await withRenderPage({ files: served }, page => page.evaluate(options => window.cuetakePreview(options), { ...take, tiles: spoken, at: at ?? null }));
146
149
  return Buffer.from(png, 'base64');
147
150
  }
148
151
 
package/src/shortcuts.js CHANGED
@@ -32,6 +32,9 @@ export function shortcutKeys(down) {
32
32
  return [...MODIFIERS.filter(([flag]) => down[flag]).map(([, name]) => name), key];
33
33
  }
34
34
 
35
+ /** Whether a Shortcut's keys are Select All, as Control+A or Meta+A. */
36
+ export const isSelectAll = keys => keys.length === 2 && ['Control', 'Meta'].includes(keys[0]) && keys[1] === 'A';
37
+
35
38
  const sameKeys = (a, b) => a.length === b.length && a.every((key, i) => key === b[i]);
36
39
 
37
40
  /**
package/src/stage.js CHANGED
@@ -16,19 +16,21 @@ export function atShortSide(edit, short) {
16
16
 
17
17
  /**
18
18
  * Where the window, its chrome and the page sit on the stage, in stage pixels. `chrome` is the chrome
19
- * bar's height in CSS pixels; `scale` is stage px per CSS px. The window is as large as fits inside the
20
- * padding and centered in it.
19
+ * bar's height in CSS pixels; `scale` is stage px per CSS px; `room` (a fraction of the short side)
20
+ * adds to the bottom padding, for Subtitles. The window is as large as fits inside the padding and
21
+ * centered in it; `below` is the space under it, where Subtitles and keycaps sit.
21
22
  */
22
- export function layout(edit, viewport, chrome = 0) {
23
+ export function layout(edit, viewport, chrome = 0, room = 0) {
23
24
  const { width, height } = outputSize(edit), short = Math.min(width, height);
24
25
  const padding = [edit.frame.padding ?? 0].flat();
25
- const [top, right, bottom, left] = (padding.length === 4 ? padding : [padding[0], padding[0], padding[0], padding[0]]).map(p => p * short);
26
+ const [top, right, padded, left] = (padding.length === 4 ? padding : [padding[0], padding[0], padding[0], padding[0]]).map(p => p * short);
27
+ const bottom = padded + room * short;
26
28
  const scale = Math.min((width - left - right) / viewport.width, (height - top - bottom) / (viewport.height + chrome));
27
29
  const w = viewport.width * scale, h = (viewport.height + chrome) * scale;
28
30
  const window = { x: left + (width - left - right - w) / 2, y: top + (height - top - bottom - h) / 2, w, h };
29
31
  return {
30
32
  width, height, scale, chrome: chrome * scale, radius: (edit.frame.radius ?? 0) * short / 1080,
31
- window, page: { x: window.x, y: window.y + chrome * scale, w, h: h - chrome * scale },
33
+ window, below: height - window.y - h, page: { x: window.x, y: window.y + chrome * scale, w, h: h - chrome * scale },
32
34
  };
33
35
  }
34
36
 
@@ -1,5 +1,6 @@
1
- // Keycaps: one rounded cap per key of a Shortcut, in a row at the bottom right of the Final, level with the Subtitles.
2
- // Parameters: symbols (macOS symbols such as ⌘ ⇧ ⌥ ⌃, or words such as Ctrl), fontSize, color, cap, edge, right, bottom.
1
+ // Keycaps: one rounded cap per key of a Shortcut, in a row at the bottom right of the Final, centered in the
2
+ // space below the window, level with the Subtitles.
3
+ // Parameters: symbols (macOS symbols such as ⌘ ⇧ ⌥ ⌃, or words such as Ctrl), fontSize, color, cap, edge, right.
3
4
  // Drawn in 1080p pixels over the whole Final, outside the camera; `count` is how many times the keys were pressed.
4
5
  const SYMBOLS = {
5
6
  Meta: '⌘', Control: '⌃', Alt: '⌥', Shift: '⇧', Enter: '↩', Escape: 'esc', Backspace: '⌫', Delete: '⌦', Tab: '⇥', CapsLock: '⇪',
@@ -10,8 +11,8 @@ const WORDS = {
10
11
  ArrowUp: '↑', ArrowDown: '↓', ArrowLeft: '←', ArrowRight: '→', PageUp: 'PgUp', PageDown: 'PgDn', Space: 'Space',
11
12
  };
12
13
 
13
- export function draw(ctx, { width, height, keys, count, params, files }) {
14
- const { symbols = true, fontSize: size = 34, color = '#ffffff', cap = '#1f1f23e6', edge = '#ffffff40', right = 80, bottom = 80 } = params;
14
+ export function draw(ctx, { width, height, below, keys, count, params, files }) {
15
+ const { symbols = true, fontSize: size = 34, color = '#ffffff', cap = '#1f1f23e6', edge = '#ffffff40', right = 80 } = params;
15
16
  const family = files.font ? `"${files.font}"` : '-apple-system, "SF Pro Text", "Helvetica Neue", "DejaVu Sans", system-ui, sans-serif';
16
17
  const labels = keys.map(key => (symbols ? SYMBOLS : WORDS)[key] ?? key);
17
18
  ctx.font = `600 ${size}px ${family}`;
@@ -21,7 +22,7 @@ export function draw(ctx, { width, height, keys, count, params, files }) {
21
22
  const times = count > 1 ? `×${count}` : '';
22
23
  const total = widths.reduce((sum, w) => sum + w, 0) + gap * (labels.length - 1) + (times ? gap + ctx.measureText(times).width : 0);
23
24
  let x = width - right - total;
24
- const y = height - bottom - h;
25
+ const y = height - (below + h) / 2;
25
26
  labels.forEach((label, i) => {
26
27
  ctx.beginPath(); ctx.roundRect(x, y, widths[i], h, size * 0.35);
27
28
  ctx.shadowColor = '#00000059'; ctx.shadowBlur = size * 0.5; ctx.shadowOffsetY = size * 0.1;
@@ -1,17 +1,37 @@
1
- // Subtitles: centered rows of text on a rounded band near the bottom of the Final.
2
- // Parameters: fontSize, weight, color, band (#rrggbbaa, '' for none), bottom (gap below the band), padding.
1
+ // Subtitles: centered rows of text in the space below the window, by default white with a black outline
2
+ // and a light shadow, so they read over any page without a band.
3
+ // Parameters: fontSize, weight, color, stroke (outline color, '' for none), strokeWidth (outline width
4
+ // outside the letters), shadow (#rrggbbaa, '' for none), shadowBlur, shadowOffset (downward),
5
+ // band (#rrggbbaa, '' for none: a rounded band behind the rows), padding (space between the band's edge
6
+ // and the rows).
3
7
  // Drawn in 1080p pixels over the whole Final, outside the camera; a `font` in files replaces the system font.
4
- export function draw(ctx, { width, height, rows, params, files }) {
5
- const { fontSize: size = 40, weight = 600, color = '#ffffff', band = '#000000b3', bottom = 72, padding = 14 } = params;
8
+ export function draw(ctx, { width, height, below, rows, params, files }) {
9
+ const {
10
+ fontSize: size = 48, weight = 600, color = '#ffffff', stroke = '#000000', strokeWidth = 4,
11
+ shadow = '#00000066', shadowBlur = 8, shadowOffset = 2, band = '', padding = 14,
12
+ } = params;
6
13
  const family = files.font ? `"${files.font}"` : '-apple-system, "PingFang SC", "Helvetica Neue", system-ui, sans-serif';
7
14
  ctx.font = `${weight} ${size}px ${family}`;
8
15
  ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
9
16
  const line = size * 1.3, w = Math.max(...rows.map(row => ctx.measureText(row).width)) + 2 * padding * 1.6;
10
- const h = rows.length * line + 2 * padding, y = height - bottom - h;
17
+ const h = rows.length * line + 2 * padding, y = height - (below + h) / 2;
11
18
  if (band) {
12
19
  ctx.fillStyle = band;
13
20
  ctx.beginPath(); ctx.roundRect((width - w) / 2, y, w, h, Math.min(12, h / 2)); ctx.fill();
14
21
  }
22
+ const at = i => y + padding + line * (i + 0.5), outlined = Boolean(stroke) && strokeWidth > 0;
23
+ // The shadow falls from the outermost pass only, so the outline and the letters do not cast it twice.
24
+ const shadowed = paint => {
25
+ if (shadow) Object.assign(ctx, { shadowColor: shadow, shadowBlur, shadowOffsetX: 0, shadowOffsetY: shadowOffset });
26
+ paint();
27
+ Object.assign(ctx, { shadowColor: 'transparent', shadowBlur: 0, shadowOffsetY: 0 });
28
+ };
29
+ if (outlined) {
30
+ // A stroke is centered on the letters' edge; the fill drawn over it hides the inner half.
31
+ Object.assign(ctx, { strokeStyle: stroke, lineWidth: 2 * strokeWidth, lineJoin: 'round' });
32
+ shadowed(() => rows.forEach((row, i) => ctx.strokeText(row, width / 2, at(i))));
33
+ }
15
34
  ctx.fillStyle = color;
16
- rows.forEach((row, i) => ctx.fillText(row, width / 2, y + padding + line * (i + 0.5)));
35
+ const fill = () => rows.forEach((row, i) => ctx.fillText(row, width / 2, at(i)));
36
+ if (outlined) fill(); else shadowed(fill);
17
37
  }
package/src/styles.js CHANGED
@@ -19,8 +19,8 @@ export const BUILTINS = {
19
19
  'arrow-thin': { file: 'arrow.js', params: { thin: true } },
20
20
  dot: { file: 'dot.js', params: {} },
21
21
  spark: { file: 'spark.js', params: { radius: 32, length: 16, count: 8 } },
22
- keycaps: { file: 'keycaps.js', params: { symbols: true, fontSize: 34, color: '#ffffff', cap: '#1f1f23e6', edge: '#ffffff40', right: 80, bottom: 80 } },
23
- subtitles: { file: 'subtitles.js', params: { fontSize: 40, weight: 600, color: '#ffffff', band: '#000000b3', bottom: 72, padding: 14 } },
22
+ keycaps: { file: 'keycaps.js', params: { symbols: true, fontSize: 34, color: '#ffffff', cap: '#1f1f23e6', edge: '#ffffff40', right: 80 } },
23
+ subtitles: { file: 'subtitles.js', params: { fontSize: 48, weight: 600, color: '#ffffff', stroke: '#000000', strokeWidth: 4, shadow: '#00000066', shadowBlur: 8, shadowOffset: 2, band: '', padding: 14 } },
24
24
  'fast-forward': { file: 'fast-forward.js', params: { fontSize: 44, color: '#ffffff', band: '#000000a6', x: 0.5, y: 0.5 } },
25
25
  };
26
26
  export const KINDS = ['shader', 'draw', 'image'];