cuetake 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Locators of a Take of Apps: Accessibility elements named by role and name, in the style of Playwright's
3
+ * getByRole (ADR 0009). They hold no element; each read or action resolves them again through the helper,
4
+ * whose `request` answers:
5
+ * { windows: {} } the windows of every App of the Take: { ref, app, title, subrole,
6
+ * focused (the window in front), main (its App's front window), frame, ... },
7
+ * `app` indexing the Take's Apps
8
+ * { setFrame: { ref, x, y, width, height } } moves and sizes a window, for `prepare` to arrange the Desktop
9
+ * { find: { within, roles, identifier } } the elements under `within` with one of `roles` ({ role, subrole }, or
10
+ * null for any) and that `identifier` (or any): { ref, role, subrole, title,
11
+ * description, label, identifier, frame }
12
+ * { read: { ref } } the element's { value, text, frame }
13
+ * Frames are Desktop points.
14
+ */
15
+
16
+ // ARIA roles as the AX roles (and subroles) AppKit, SwiftUI and Chromium expose them under.
17
+ const ROLES = {
18
+ button: [['AXButton']], link: [['AXLink']], textbox: [['AXTextField'], ['AXTextArea']], searchbox: [['AXTextField', 'AXSearchField']],
19
+ checkbox: [['AXCheckBox']], switch: [['AXCheckBox', 'AXSwitch']], radio: [['AXRadioButton']], combobox: [['AXComboBox'], ['AXPopUpButton']],
20
+ menu: [['AXMenu']], menubar: [['AXMenuBar']], menuitem: [['AXMenuItem'], ['AXMenuBarItem']], slider: [['AXSlider']],
21
+ tab: [['AXRadioButton', 'AXTabButton']], tablist: [['AXTabGroup']], list: [['AXList']], listbox: [['AXList']], table: [['AXTable']],
22
+ grid: [['AXTable']], row: [['AXRow']], cell: [['AXCell']], tree: [['AXOutline']], treeitem: [['AXRow', 'AXOutlineRow']],
23
+ heading: [['AXHeading']], img: [['AXImage']], image: [['AXImage']], group: [['AXGroup']], toolbar: [['AXToolbar']],
24
+ dialog: [['AXWindow', 'AXDialog'], ['AXSheet']], scrollbar: [['AXScrollBar']], progressbar: [['AXProgressIndicator']],
25
+ text: [['AXStaticText']], window: [['AXWindow']],
26
+ };
27
+ const WORKS = 'getByRole, getByTestId, value, text, isVisible and waitFor';
28
+ const WINDOW = Symbol('window');
29
+ const POLL_MS = 100, READ_TIMEOUT_MS = 10_000, WAIT_TIMEOUT_MS = 30_000;
30
+ const RESOLVE = Symbol('resolve'), MATCHES = Symbol('matches');
31
+
32
+ /** The AX roles an ARIA role or a raw AX role names, as `{ role, subrole }`. */
33
+ function axRoles(role) {
34
+ if (/^AX[A-Z]/.test(role)) return [{ role }];
35
+ const roles = ROLES[role];
36
+ if (!roles) throw new Error(`getByRole does not know the role '${role}'; use an ARIA role (${Object.keys(ROLES).join(', ')}) or an AX role such as AXPopUpButton`);
37
+ return roles.map(([role, subrole]) => subrole ? { role, subrole } : { role });
38
+ }
39
+
40
+ /** Whether `text` matches `name`: a RegExp, the whole string with `exact`, else a part of it in any case. */
41
+ function matches(text, name, exact) {
42
+ if (name instanceof RegExp) return name.test(text);
43
+ return exact ? text === name : text.toLowerCase().includes(String(name).toLowerCase());
44
+ }
45
+
46
+ /** An element's accessible name: its title, else description, else label, else a static text's value. */
47
+ const nameOf = e => e.title || e.description || e.label || (e.role === 'AXStaticText' && typeof e.value === 'string' ? e.value : '');
48
+
49
+ const quote = value => value instanceof RegExp ? String(value) : `'${String(value).replaceAll('\\', '\\\\').replaceAll('\n', '\\n').replaceAll("'", "\\'")}'`;
50
+ const shown = element => `${element.role} ${quote(nameOf(element) || element.identifier)}`;
51
+ const where = ({ x, y, width, height }) => `${x}, ${y}, ${width}×${height}`;
52
+ const visible = element => element.frame.width > 0 && element.frame.height > 0;
53
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
54
+
55
+ /** How a chain of steps reads in a Scenario, for messages. */
56
+ function describe(steps) {
57
+ return steps.map(step => {
58
+ if (step.window === 'front') return 'd.page';
59
+ if (step.window === 'first') return 'page';
60
+ if (step.window) return `d.app(${step.window.label === undefined ? '' : quote(step.window.label)})${step.window.name === undefined ? '' : `.window(${quote(step.window.name)})`}`;
61
+ if (step.testId !== undefined) return `.getByTestId(${quote(step.testId)})`;
62
+ const options = step.name === undefined ? '' : `, { name: ${quote(step.name)}${step.exact ? ', exact: true' : ''} }`;
63
+ return `.getByRole(${quote(step.role)}${options})`;
64
+ }).join('');
65
+ }
66
+
67
+ /** How a list of names reads: 'A', 'A or B', 'A, B or C'. */
68
+ const either = (names, word) => names.length < 2 ? names.join('') : `${names.slice(0, -1).join(', ')} ${word} ${names.at(-1)}`;
69
+
70
+ /**
71
+ * Locators for the Apps behind `helper` (`apps`, the Take's, each { name, bundle, path }): `page(which)`
72
+ * is a window as a page offers it, `'front'` (the window in front when resolved, whichever App owns it)
73
+ * or `'first'` (the first App's first standard window); `app(name)` is one App, offering its front
74
+ * window's locators and `window(title)`, another of its windows by a part of its title. With `arrange`,
75
+ * as for `prepare`, a window also offers `setFrame(box)`, in Desktop points.
76
+ */
77
+ export function appLocators(helper, apps = [], { arrange = false } = {}) {
78
+ /** The elements a chain of steps matches now. */
79
+ async function resolve(steps) {
80
+ const [first, ...rest] = steps, windows = await helper.request({ windows: {} });
81
+ const own = first.window.app === undefined ? windows : windows.filter(w => (w.app ?? 0) === first.window.app);
82
+ let found = first.window === 'front' ? [windows.find(w => w.focused) ?? windows[0]]
83
+ : first.window === 'first' ? [windows.find(w => !w.app && w.subrole === 'AXStandardWindow') ?? windows[0]]
84
+ : first.window.name === undefined ? [own.find(w => w.main) ?? own.find(w => w.subrole === 'AXStandardWindow') ?? own[0]]
85
+ : own.filter(w => matches(w.title ?? '', first.window.name, false));
86
+ found = found.filter(Boolean);
87
+ for (const step of rest) {
88
+ const next = new Map();
89
+ for (const scope of found) {
90
+ const query = step.testId !== undefined ? { within: scope.ref, roles: null, identifier: step.testId } : { within: scope.ref, roles: axRoles(step.role), identifier: null };
91
+ for (const element of await helper.request({ find: query })) {
92
+ if (step.name === undefined || matches(nameOf(element), step.name, step.exact)) next.set(element.ref, element);
93
+ }
94
+ }
95
+ found = [...next.values()];
96
+ }
97
+ return found;
98
+ }
99
+
100
+ /** The one element `steps` match now, or null; several fail at once, as in Playwright's strict mode. */
101
+ async function single(steps) {
102
+ const found = await resolve(steps);
103
+ if (found.length > 1) {
104
+ const listed = found.slice(0, 5).map(e => `${shown(e)} at ${where(e.frame)}`).join('; ') + (found.length > 5 ? `; and ${found.length - 5} more` : '');
105
+ throw new Error(`${describe(steps)} matches ${found.length} elements: ${listed}. Narrow it by name, or inside a locator that holds only one`);
106
+ }
107
+ return found[0] ?? null;
108
+ }
109
+
110
+ /** The one visible element `steps` match, waiting up to `timeout` ms for it. */
111
+ async function visibleOne(steps, timeout = READ_TIMEOUT_MS) {
112
+ for (const deadline = Date.now() + timeout; ;) {
113
+ const element = await single(steps);
114
+ if (element && visible(element)) return element;
115
+ if (Date.now() >= deadline) throw new Error(`${describe(steps)} did not become visible within ${timeout} ms${element ? ': it has no size' : ''}`);
116
+ await sleep(POLL_MS);
117
+ }
118
+ }
119
+
120
+ function locator(steps) {
121
+ const methods = {
122
+ getByRole: (role, { name, exact = false } = {}) => (axRoles(role), locator([...steps, { role, name, exact }])),
123
+ getByTestId: testId => locator([...steps, { testId }]),
124
+ async value() { return (await helper.request({ read: { ref: (await visibleOne(steps)).ref } })).value; },
125
+ async text() { return (await helper.request({ read: { ref: (await visibleOne(steps)).ref } })).text; },
126
+ async isVisible() { const element = await single(steps); return Boolean(element && visible(element)); },
127
+ /** Waits until the locator is `visible` (one element with a size) or `hidden` (none, or one without). */
128
+ async waitFor({ state = 'visible', timeout = WAIT_TIMEOUT_MS } = {}) {
129
+ if (state !== 'visible' && state !== 'hidden') throw new Error(`waitFor needs state 'visible' or 'hidden', not '${state}'`);
130
+ for (const deadline = Date.now() + timeout; ;) {
131
+ const element = await single(steps);
132
+ if (Boolean(element && visible(element)) === (state === 'visible')) return;
133
+ if (Date.now() >= deadline) throw new Error(`${describe(steps)} did not become ${state} within ${timeout} ms`);
134
+ await sleep(POLL_MS);
135
+ }
136
+ },
137
+ toString: () => describe(steps),
138
+ [RESOLVE]: () => visibleOne(steps),
139
+ [MATCHES]: () => resolve(steps),
140
+ };
141
+ return new Proxy(methods, {
142
+ get(target, prop) {
143
+ if (typeof prop === 'symbol' || prop in target || prop === 'then') return target[prop];
144
+ throw new Error(`${prop} does not work on a locator of an App: use ${WORKS}, and act with d.click, d.type, d.hover and d.drag`);
145
+ },
146
+ });
147
+ }
148
+
149
+ function page(which, more = {}) {
150
+ const steps = [{ window: which }], window = locator(steps), prefix = describe(steps);
151
+ const methods = { getByRole: window.getByRole, getByTestId: window.getByTestId, toString: () => prefix, ...more, [WINDOW]: () => visibleOne(steps) };
152
+ if (arrange) methods.setFrame = async box => {
153
+ const { x, y, width, height } = box ?? {};
154
+ if (![x, y, width, height].every(Number.isFinite) || width <= 0 || height <= 0) throw new Error('setFrame needs a box { x, y, width, height } in Desktop points, with a size');
155
+ await helper.request({ setFrame: { ref: (await visibleOne(steps)).ref, x, y, width, height } });
156
+ };
157
+ return new Proxy(methods, {
158
+ get(target, prop) {
159
+ if (typeof prop === 'symbol' || prop in target || prop === 'then') return target[prop];
160
+ throw new Error(`${prefix}.${prop} does not work in a Take of an App: use getByRole, getByTestId, or d.app(name).window(title) for another window${arrange ? '' : '; arrange windows with setFrame in prepare'}`);
161
+ },
162
+ });
163
+ }
164
+
165
+ /** The App `name` names, by its name in any case, or the bundle id or path the Scenario gave; with one App, any. */
166
+ function app(name) {
167
+ const names = apps.map(a => a.name);
168
+ const index = name === undefined ? (apps.length <= 1 ? 0 : -1)
169
+ : apps.findIndex(a => [a.name, a.bundle, a.path].some(known => typeof known === 'string' && known.toLowerCase() === String(name).toLowerCase()));
170
+ if (name === undefined && index < 0) throw new Error(`d.app needs the name of one of the Take's Apps: ${either(names, 'or')}`);
171
+ if (index < 0) throw new Error(`d.app(${quote(name)}) is not an App of this Take, which has ${either(names, 'and')}`);
172
+ return page({ app: index, label: name }, { window: title => page({ app: index, label: name, name: title }) });
173
+ }
174
+
175
+ return { page, app };
176
+ }
177
+
178
+ /** Whether `target` is a window of the Take, as d.page, d.app(name) or window(title) give it. */
179
+ export const isAppWindow = target => typeof target?.[WINDOW] === 'function';
180
+
181
+ /** The window an App window names, waited for: { ref, app, focused, main, frame, ... } in Desktop points. */
182
+ export const resolveWindow = target => target[WINDOW]();
183
+
184
+ /** The ARIA role a Scenario names an AX role and subrole by, or the AX role where none fits. */
185
+ function ariaRole(role, subrole) {
186
+ const fits = loose => Object.keys(ROLES).find(aria => ROLES[aria].some(([r, s]) => r === role && (s ? s === subrole : loose)));
187
+ return fits(false) ?? fits(true) ?? role;
188
+ }
189
+
190
+ const relative = ({ x, y, width, height }, origin) => `${Math.round(x - origin.x)}, ${Math.round(y - origin.y)}, ${Math.round(width)}×${Math.round(height)}`;
191
+
192
+ /**
193
+ * The lines `cuetake tree` prints for the tree the helper lists (`cuetake-capture tree`): each element,
194
+ * indented under its parent, with its role, name, value and frame from its window's top-left corner, and
195
+ * the locator that finds it, by test id where it has one of its own, else by role and the first line of its name.
196
+ */
197
+ export function treeLines({ app, bundle, windows, truncated }) {
198
+ const lines = [`${app} (${bundle}): frames in points from each window's top-left corner, which are Desktop points for the window that fills the Desktop`];
199
+ for (const window of windows) {
200
+ const { width, height } = window.frame;
201
+ lines.push(`window ${quote(nameOf(window))} ${Math.round(width)}×${Math.round(height)}: d.app(${quote(app)}).window(${quote(nameOf(window))})`);
202
+ const visit = (element, depth) => {
203
+ const role = ariaRole(element.role, element.subrole), name = nameOf(element), own = element.identifier && !element.identifier.startsWith('_NS:');
204
+ const value = typeof element.value === 'string' && element.value && element.value !== name ? ` = ${quote(element.value)}` : typeof element.value === 'number' ? ` = ${element.value}` : '';
205
+ const locator = own ? `getByTestId(${quote(element.identifier)})`
206
+ : name ? `getByRole('${role}', { name: ${quote(name.split('\n')[0])} })` : '';
207
+ lines.push(`${' '.repeat(depth)}${role}${name ? ` ${quote(name)}` : ''}${value} ${relative(element.frame, window.frame)}${locator ? `: ${locator}` : ''}`);
208
+ for (const child of element.children ?? []) visit(child, depth + 1);
209
+ };
210
+ for (const child of window.children ?? []) visit(child, 1);
211
+ }
212
+ if (truncated) lines.push('… the tree is longer than 5000 elements; the rest is left out');
213
+ return lines;
214
+ }
215
+
216
+ /** Whether `target` is a locator of an App. */
217
+ export const isAppLocator = target => typeof target?.[RESOLVE] === 'function';
218
+
219
+ /** The one visible element an App locator matches, waiting for it, with its frame in Desktop points. */
220
+ export const resolveOne = target => target[RESOLVE]();
221
+
222
+ /** Every element an App locator matches now, shown or not, without waiting. */
223
+ export const resolveAll = target => target[MATCHES]();
package/src/auth.js CHANGED
@@ -5,8 +5,9 @@ import { join } from 'node:path';
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import { setTimeout as sleep } from 'node:timers/promises';
7
7
  const root = () => process.env.CUETAKE_AUTH_DIR || join(homedir(), '.local/share/cuetake/auth');
8
+ const NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
8
9
  function profilePath(profile) {
9
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(profile)) throw new Error('Use a short lowercase profile name, such as product-demo');
10
+ if (!NAME.test(profile)) throw new Error('Use a short lowercase profile name, such as product-demo');
10
11
  return join(root(), `${profile}.json`);
11
12
  }
12
13
  export async function resolveAuthProfile(profile) {
@@ -14,6 +15,12 @@ export async function resolveAuthProfile(profile) {
14
15
  await fs.access(path).catch(() => { throw new Error(`Auth profile '${profile}' is missing. Run: cuetake login ${profile} <login-url>`); });
15
16
  return path;
16
17
  }
18
+ /** The saved Auth profile files, with any left over from an interrupted save; other files in the folder are not CueTake's. */
19
+ export async function authProfileFiles() {
20
+ const dir = root(), names = await fs.readdir(dir).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
21
+ const paths = names.filter(name => { const [profile, ext, ...rest] = name.split('.'); return NAME.test(profile) && ext === 'json' && (rest.length === 0 || (rest.length === 2 && rest[1] === 'tmp')); });
22
+ return { dir, paths: paths.sort().map(name => join(dir, name)) };
23
+ }
17
24
  /** Accepts a browser context or an already-read storage state. */
18
25
  export async function saveAuthState(source, profile) {
19
26
  const path = profilePath(profile);
package/src/camera.js CHANGED
@@ -2,8 +2,9 @@
2
2
  * Camera math shared by Node and the render page. Pure functions, no imports.
3
3
  *
4
4
  * Modeled on Screen Studio's auto zoom: zooms come from actions; actions close together form one
5
- * zoom segment that moves between them and follows the cursor; the camera moves on a critically
6
- * damped spring, so it never overshoots and settles quickly enough to keep text readable. Because
5
+ * zoom segment, held at one zoom, that moves between them and follows the cursor only as far as they
6
+ * need to stay in view; the camera moves on critically damped springs, so it eases in, never
7
+ * overshoots and settles quickly enough to keep text readable. Because
7
8
  * the whole Timeline is known in advance, the camera starts moving `lead` seconds before each
8
9
  * action and every Final ends on the wide shot.
9
10
  *
@@ -11,7 +12,7 @@
11
12
  */
12
13
 
13
14
  const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
14
- const SAFE_AREA = 0.7; // while zoomed, the cursor stays within this central fraction of the view
15
+ const SAFE_AREA = 0.8; // while zoomed, the cursor stays within this central fraction of the view
15
16
 
16
17
  /** The zoom that frames `box` with `padding` on every side, between 1 and `maxZoom`. */
17
18
  export function fitZoom(box, viewport, { maxZoom, padding }) {
@@ -29,56 +30,102 @@ export function cropAround(x, y, zoom, viewport) {
29
30
  * Zoom segments: each target wants the camera from `lead` before it until `hold` after it (or after
30
31
  * its typing ends); targets whose windows touch or sit within `chainGap` share one segment. Segments
31
32
  * stop `endWide` before the Final ends, and targets that would barely zoom (below `minZoom`) stay wide.
33
+ * A segment's zoom is the closest that fits all its targets, so the camera never zooms within one.
34
+ * No segment spans one of the `cuts`, the times the camera cuts to wide, or one of the `scrolls`
35
+ * ({ start, end }): the camera is back wide `response` before a scroll starts and stays wide until it
36
+ * ends, so the page never moves under a zoom.
32
37
  */
33
- export function zoomSegments(targets, viewport, camera, duration) {
34
- const { lead, hold, chainGap, minZoom, endWide } = camera;
38
+ export function zoomSegments(targets, viewport, camera, duration, cuts = [], scrolls = []) {
39
+ const { lead, hold, chainGap, minZoom, endWide, response = 0 } = camera;
35
40
  const last = duration - endWide;
41
+ const cutBefore = t => cuts.findLast(cut => cut <= t) ?? -Infinity;
42
+ // Targets between the same cuts and scrolls may share a segment; a scroll's span belongs to none.
43
+ const period = t => `${cutBefore(t)}/${scrolls.filter(s => s.start - response <= t).length}`;
36
44
  const segments = [];
37
45
  for (const target of targets.toSorted((a, b) => a.t - b.t)) {
38
46
  const zoom = target.zoom ?? fitZoom(target.box, viewport, camera);
39
47
  if (zoom < minZoom || target.t - lead >= last) continue;
40
48
  const shot = { t: target.t, box: target.box, zoom };
41
- const start = Math.max(0, target.t - lead), end = Math.min(last, Math.max(target.t, target.until ?? target.t) + hold);
49
+ const scrolledBefore = scrolls.findLast(s => s.start - response <= target.t)?.end ?? -Infinity;
50
+ const nextScroll = scrolls.find(s => s.start - response > target.t);
51
+ const start = Math.max(0, target.t - lead, cutBefore(target.t), scrolledBefore);
52
+ const end = Math.min(last, cuts.find(cut => cut > target.t) ?? Infinity, nextScroll ? nextScroll.start - response : Infinity, Math.max(target.t, target.until ?? target.t) + hold);
53
+ if (end <= start) continue;
42
54
  const segment = segments.at(-1);
43
- if (segment && start - segment.end <= chainGap) { segment.shots.push(shot); segment.end = Math.max(segment.end, end); }
44
- else segments.push({ start, end, shots: [shot] });
55
+ if (segment && start - segment.end <= chainGap && period(segment.shots[0].t) === period(target.t)) {
56
+ segment.shots.push(shot);
57
+ segment.end = Math.max(segment.end, end);
58
+ segment.zoom = Math.min(segment.zoom, zoom);
59
+ } else segments.push({ start, end, zoom, shots: [shot] });
45
60
  }
46
61
  return segments;
47
62
  }
48
63
 
49
- /** Where the camera wants to be at `t` (center and zoom) before spring smoothing. `pointerAt(t)` may be null. */
50
- export function intentAt(segments, viewport, camera, t, pointerAt) {
51
- const segment = segments.find(s => t >= s.start && t < s.end);
52
- if (!segment) return { x: viewport.width / 2, y: viewport.height / 2, zoom: 1 };
53
- // Move to each shot `lead` before its action, so the camera arrives as the action happens.
54
- const shot = segment.shots.findLast(s => s.t - camera.lead <= t) ?? segment.shots[0];
55
- const { zoom } = shot;
56
- const half = { x: viewport.width / (2 * zoom), y: viewport.height / (2 * zoom) };
57
- let x = shot.box.x + shot.box.width / 2, y = shot.box.y + shot.box.height / 2;
58
- const pointer = camera.follow ? pointerAt?.(t) : null;
59
- if (pointer) {
60
- x = clamp(x, pointer.x - half.x * SAFE_AREA, pointer.x + half.x * SAFE_AREA);
61
- y = clamp(y, pointer.y - half.y * SAFE_AREA, pointer.y + half.y * SAFE_AREA);
62
- }
63
- return { x: clamp(x, half.x, viewport.width - half.x), y: clamp(y, half.y, viewport.height - half.y), zoom };
64
+ /** The center nearest `center` whose view, `half` wide on each side, holds `low` to `high`. */
65
+ const reach = (center, low, high, half) => clamp(center, high - half, low + half);
66
+
67
+ /**
68
+ * Where the camera wants to be (center and zoom) before spring smoothing, asked frame by frame in time
69
+ * order. It centers on a segment's first target, then moves only as far as each later target, with
70
+ * `padding`, or the cursor needs to stay in view, so actions in one area play out under a still
71
+ * camera. `pointerAt(t)` may be null.
72
+ */
73
+ export function intents(segments, viewport, camera, pointerAt) {
74
+ let framing = null;
75
+ return t => {
76
+ const segment = segments.find(s => t >= s.start && t < s.end);
77
+ if (!segment) { framing = null; return { x: viewport.width / 2, y: viewport.height / 2, zoom: 1 }; }
78
+ // Reach each shot `lead` before its action, so the camera arrives as the action happens.
79
+ const shot = segment.shots.findLast(s => s.t - camera.lead <= t) ?? segment.shots[0];
80
+ const { zoom } = segment, { box } = shot, pad = camera.padding;
81
+ const half = { x: viewport.width / (2 * zoom), y: viewport.height / (2 * zoom) };
82
+ if (framing?.segment !== segment) framing = { segment, shot, x: box.x + box.width / 2, y: box.y + box.height / 2 };
83
+ else if (framing.shot !== shot) {
84
+ framing.shot = shot;
85
+ framing.x = reach(framing.x, box.x - pad, box.x + box.width + pad, half.x);
86
+ framing.y = reach(framing.y, box.y - pad, box.y + box.height + pad, half.y);
87
+ }
88
+ const pointer = camera.follow ? pointerAt?.(t) : null;
89
+ if (pointer) {
90
+ framing.x = clamp(framing.x, pointer.x - half.x * SAFE_AREA, pointer.x + half.x * SAFE_AREA);
91
+ framing.y = clamp(framing.y, pointer.y - half.y * SAFE_AREA, pointer.y + half.y * SAFE_AREA);
92
+ }
93
+ framing.x = clamp(framing.x, half.x, viewport.width - half.x);
94
+ framing.y = clamp(framing.y, half.y, viewport.height - half.y);
95
+ return { x: framing.x, y: framing.y, zoom };
96
+ };
64
97
  }
65
98
 
66
99
  /**
67
- * The visible viewport crop for every output frame. The intent is followed by a critically damped
68
- * spring on center and log-zoom that settles in about `response` seconds.
100
+ * The visible viewport crop for every output frame. The intent is followed by two critically damped
101
+ * springs in series on center and log-zoom, which ease each move in and out and settle in about
102
+ * `response` seconds. At each of the `cuts` the camera is wide at once.
69
103
  */
70
- export function cameraTrack({ targets, viewport, camera, duration, fps, pointerAt }) {
71
- const segments = zoomSegments(targets, viewport, camera, duration);
72
- const omega = 4 / camera.response, steps = 4, dt = 1 / (fps * steps);
73
- const start = intentAt(segments, viewport, camera, 0, pointerAt);
74
- const state = { x: start.x, y: start.y, z: Math.log(start.zoom) }, velocity = { x: 0, y: 0, z: 0 };
104
+ export function cameraTrack({ targets, viewport, camera, duration, fps, pointerAt, cuts = [], scrolls = [] }) {
105
+ const intentAt = intents(zoomSegments(targets, viewport, camera, duration, cuts, scrolls), viewport, camera, pointerAt);
106
+ // The pair settles about as fast as one spring with omega 4 / response.
107
+ const omega = 6.8 / camera.response, steps = 4, dt = 1 / (fps * steps);
108
+ const start = intentAt(0);
109
+ const spring = () => ({ position: { x: start.x, y: start.y, z: Math.log(start.zoom) }, velocity: { x: 0, y: 0, z: 0 } });
110
+ const aim = spring(), view = spring(), state = view.position;
111
+ const follow = ({ position, velocity }, target, key) => {
112
+ velocity[key] += (omega * omega * (target[key] - position[key]) - 2 * omega * velocity[key]) * dt;
113
+ position[key] += velocity[key] * dt;
114
+ };
75
115
  const track = [];
116
+ let cut = 0;
76
117
  for (let i = 0, frames = Math.round(duration * fps); i < frames; i++) {
77
- const goal = intentAt(segments, viewport, camera, i / fps, pointerAt);
118
+ const goal = intentAt(i / fps);
119
+ if (cut < cuts.length && i / fps >= cuts[cut]) {
120
+ while (cut < cuts.length && i / fps >= cuts[cut]) cut++;
121
+ for (const { position, velocity } of [aim, view]) Object.assign(position, { x: viewport.width / 2, y: viewport.height / 2, z: 0 }), Object.assign(velocity, { x: 0, y: 0, z: 0 });
122
+ track.push(cropAround(viewport.width / 2, viewport.height / 2, 1, viewport));
123
+ continue;
124
+ }
78
125
  const target = { x: goal.x, y: goal.y, z: Math.log(goal.zoom) };
79
126
  for (let step = 0; step < steps; step++) for (const key of ['x', 'y', 'z']) {
80
- velocity[key] += (omega * omega * (target[key] - state[key]) - 2 * omega * velocity[key]) * dt;
81
- state[key] += velocity[key] * dt;
127
+ follow(aim, target, key);
128
+ follow(view, aim.position, key);
82
129
  }
83
130
  track.push(cropAround(state.x, state.y, Math.exp(state.z), viewport));
84
131
  }
package/src/cli.js CHANGED
@@ -1,12 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from 'node:util';
3
3
  import pkg from '../package.json' with { type: 'json' };
4
- import { recordScenario, renderTake, verifyTake, previewTake, applyLookToTake, saveLookFromTake } from './pipeline.js';
4
+ import { recordScenario, renderTake, verifyTake, previewTake, applyLookToTake, saveLookFromTake, importNarration } from './pipeline.js';
5
5
  import { listLooks, removeLook } from './look.js';
6
6
  import { BUILTINS, BUILTIN_DIR } from './styles.js';
7
7
  import { doctor, installBrowser } from './environment.js';
8
+ import { uninstall } from './uninstall.js';
8
9
  import { login } from './auth.js';
9
10
  import { extractFrame } from './render.js';
11
+ import { appTree } from './app-capture.js';
12
+ import { treeLines } from './app-locators.js';
10
13
  import { writeFile } from 'node:fs/promises';
11
14
  import { join, resolve } from 'node:path';
12
15
 
@@ -14,7 +17,10 @@ const help = `CueTake ${pkg.version} — browser demos directed by code
14
17
 
15
18
  cuetake doctor
16
19
  cuetake install-browser
17
- cuetake record <scenario.mjs> [--out <new-directory>] [--auth-profile <name>] [--look <name|file.json>] [--headed]
20
+ cuetake uninstall [--auth] [--looks] [--dry-run]
21
+ cuetake record <scenario.mjs> [--out <new-directory>] [--auth-profile <name>] [--look <name|file.json>] [--narration <narration.json>] [--headed] [--use-running]
22
+ cuetake tree <app>
23
+ cuetake narrate import <take-directory> <narration.json>
18
24
  cuetake preview <take-directory> [--look <name|file.json>]... [--at <seconds>]
19
25
  cuetake render <take-directory>
20
26
  cuetake verify <take-directory>
@@ -27,11 +33,22 @@ const help = `CueTake ${pkg.version} — browser demos directed by code
27
33
  cuetake styles
28
34
 
29
35
  install-browser downloads the Chromium build this CueTake version drives (about 150 MB).
36
+ uninstall removes CueTake's npx cache and its browser, unless another Playwright installation uses it.
37
+ It keeps Auth profiles unless --auth and global Looks unless --looks; Take folders and local Looks
38
+ are never touched. --dry-run lists what would go and removes nothing.
30
39
  record captures, renders and verifies a new take; an existing directory is never overwritten.
31
40
  Capture runs headless; --headed shows the browser window while recording.
41
+ A Scenario naming an app instead of a url records a desktop App on macOS: its windows on a Desktop.
42
+ An App the user already runs stops it; --use-running, with the user's consent, records it as it is,
43
+ leaves it running and puts its windows back.
32
44
  --look seeds the first Edit from a Look; fields the Scenario config names win.
33
- preview writes preview.png in the take: the current Edit beside each Look, at --at seconds
34
- or at the end with the camera wide. It never changes edit.json or final.mp4.
45
+ --narration copies a Narration and its audio into the Take first: d.say(id) holds each Line for its audio.
46
+ tree lists the Accessibility tree of a running App (bundle id, name or .app path) with the locator for each
47
+ element, for writing a Scenario of the App. It only reads the App.
48
+ narrate import copies a Narration and its audio into a recorded Take, replacing its earlier one. Lines keep
49
+ their start in edit.json; a new Line takes the start the file gives it. Render plays and subtitles them.
50
+ preview writes preview.png in the take: the current Edit beside each Look, at --at seconds of the
51
+ Final or at the end with the camera wide. It never changes edit.json or final.mp4.
35
52
  render reuses source.webm, timeline.json and edit.json, replacing final.mp4 only on success.
36
53
  frame saves one Final frame as a PNG for inspection.
37
54
  login opens a separate browser; close its window after logging in to save the profile.
@@ -40,16 +57,20 @@ A Look is a take's reusable styling, with the files it draws with. Looks are sav
40
57
  name. list names the code each Look runs. apply rewrites edit.json and copies files into styles/.
41
58
  styles lists the built-in shaders and drawing code, with their files and starting parameters.
42
59
  Styling is agent-written code and is not validated; the render page has no network.
43
- Scenario files are trusted JavaScript. Recording runs locally, without audio.
60
+ Scenario files are trusted JavaScript. Recording runs locally and captures no page audio; Narration is
61
+ voiced beforehand by a speech tool of your choice.
44
62
  `;
45
63
  try {
46
- const { values, positionals } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { out: { type: 'string' }, help: { type: 'boolean', short: 'h' }, 'auth-profile': { type: 'string' }, headed: { type: 'boolean' }, look: { type: 'string', multiple: true }, at: { type: 'string' }, global: { type: 'boolean' }, replace: { type: 'boolean' } } });
64
+ const { values, positionals } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { out: { type: 'string' }, help: { type: 'boolean', short: 'h' }, 'auth-profile': { type: 'string' }, headed: { type: 'boolean' }, look: { type: 'string', multiple: true }, narration: { type: 'string' }, at: { type: 'string' }, global: { type: 'boolean' }, replace: { type: 'boolean' }, auth: { type: 'boolean' }, looks: { type: 'boolean' }, 'dry-run': { type: 'boolean' }, 'use-running': { type: 'boolean' } } });
47
65
  const [command, target] = positionals, looks = values.look ?? [];
48
66
  const print = data => console.log(JSON.stringify(data, null, 2));
49
67
  if (values.help || !command) console.log(help);
50
68
  else if (command === 'doctor') { const result = await doctor(); console.log(JSON.stringify(result, null, 2)); if (!result.ok) process.exitCode = 1; }
51
69
  else if (command === 'install-browser') console.log(JSON.stringify(await installBrowser(), null, 2));
52
- else if (command === 'record' && target && looks.length <= 1) print(await recordScenario(target, values.out, { authProfile: values['auth-profile'], look: looks[0], headed: values.headed }));
70
+ else if (command === 'uninstall' && !target) print(await uninstall({ auth: values.auth, looks: values.looks, dryRun: values['dry-run'] }));
71
+ else if (command === 'record' && target && looks.length <= 1) print(await recordScenario(target, values.out, { authProfile: values['auth-profile'], look: looks[0], narration: values.narration, headed: values.headed, useRunning: values['use-running'] }));
72
+ else if (command === 'tree' && target) console.log(treeLines(await appTree(target)).join('\n'));
73
+ else if (command === 'narrate' && target === 'import' && positionals[3]) print(await importNarration(positionals[2], positionals[3]));
53
74
  else if (command === 'preview' && target) print(await previewTake(target, looks, { at: values.at === undefined ? undefined : Number(values.at) }));
54
75
  else if (command === 'render' && target) { await renderTake(target); console.log(JSON.stringify(await verifyTake(target), null, 2)); }
55
76
  else if (command === 'verify' && target) console.log(JSON.stringify(await verifyTake(target), null, 2));
package/src/cursor.js CHANGED
@@ -3,11 +3,19 @@
3
3
  * Pure functions shared by Node and the render page; CSS pixels and seconds throughout.
4
4
  */
5
5
 
6
+ const PRESS_IN = 0.08, PRESS_OUT = 0.3; // seconds to shrink when a button goes down and to spring back after it is released
7
+
8
+ /** The index of the last entry of `list` (sorted by `time(entry)`) at or before `t`, or -1. */
9
+ function lastAt(list, t, time) {
10
+ let low = 0, high = list.length - 1, found = -1;
11
+ while (low <= high) { const mid = (low + high) >> 1; if (time(list[mid]) <= t) { found = mid; low = mid + 1; } else high = mid - 1; }
12
+ return found;
13
+ }
14
+
6
15
  /** The pointer position at `t`, interpolated between samples; null before the first sample. */
7
16
  export function pointerAt(pointer, t) {
8
- if (!pointer.length || t < pointer[0][0]) return null;
9
- let low = 0, high = pointer.length - 1;
10
- while (low < high) { const mid = (low + high + 1) >> 1; if (pointer[mid][0] <= t) low = mid; else high = mid - 1; }
17
+ const low = lastAt(pointer, t, sample => sample[0]);
18
+ if (low < 0) return null;
11
19
  const [t0, x0, y0] = pointer[low], next = pointer[low + 1];
12
20
  if (!next || next[0] === t0) return { x: x0, y: y0 };
13
21
  const k = (t - t0) / (next[0] - t0);
@@ -26,3 +34,51 @@ export function sparksAt(pressList, clickEffect, t) {
26
34
  const life = (clickEffect.duration ?? 400) / 1000;
27
35
  return pressList.filter(p => t >= p.t && t < p.t + life).map(p => ({ x: p.x, y: p.y, progress: (t - p.t) / life }));
28
36
  }
37
+
38
+ /** When a button is held: each click and drag from press to release. */
39
+ export const heldSpans = events => events.filter(event => event.type === 'click' || event.type === 'drag').map(event => ({ t: event.t, end: event.end ?? event.t }));
40
+
41
+ const easeOut = u => 1 - (1 - u) ** 3;
42
+ const springBack = u => { const c = 1.70158; return 1 + (c + 1) * (u - 1) ** 3 + c * (u - 1) ** 2; };
43
+
44
+ /** The Cursor's scale at `t`: down to `press` while a button is held, springing back after; `press: false` keeps 1. */
45
+ export function pressScale(spans, press, t) {
46
+ if (typeof press !== 'number') return 1;
47
+ const span = spans[lastAt(spans, t, s => s.t)];
48
+ if (!span) return 1;
49
+ const down = held => 1 - (1 - press) * easeOut(Math.min(1, held / PRESS_IN));
50
+ if (t <= span.end) return down(t - span.t);
51
+ const u = (t - span.end) / PRESS_OUT, from = down(span.end - span.t);
52
+ return u >= 1 ? 1 : from + (1 - from) * springBack(u);
53
+ }
54
+
55
+ /** The cursor shape the page asked for at `t`, as a CSS keyword; `default` before the first. */
56
+ export function shapeAt(shapes, t) {
57
+ return shapes[lastAt(shapes, t, entry => entry[0])]?.[1] ?? 'default';
58
+ }
59
+
60
+ // Keywords that name the same picture as one a cursor is more likely to draw.
61
+ const ALIASES = {
62
+ progress: 'wait', 'all-scroll': 'move', 'no-drop': 'not-allowed',
63
+ 'col-resize': 'ew-resize', 'e-resize': 'ew-resize', 'w-resize': 'ew-resize',
64
+ 'row-resize': 'ns-resize', 'n-resize': 'ns-resize', 's-resize': 'ns-resize',
65
+ 'ne-resize': 'nesw-resize', 'sw-resize': 'nesw-resize', 'nw-resize': 'nwse-resize', 'se-resize': 'nwse-resize',
66
+ };
67
+
68
+ /** The shape a cursor drawing `drawn` (a Set of names) shows for `keyword`: itself, its alias, or `default`. */
69
+ export const drawnShape = (keyword, drawn) => drawn.has(keyword) ? keyword : drawn.has(ALIASES[keyword]) ? ALIASES[keyword] : 'default';
70
+
71
+ /**
72
+ * The Cursor through a Take: `at(t)` gives its point, scale and the shape the page asked for,
73
+ * or null before the first pointer sample. `cursor` is the Edit's cursor item.
74
+ */
75
+ export function cursorTrack({ pointer, shapes = [], events }, cursor) {
76
+ const spans = heldSpans(events);
77
+ return {
78
+ at(t) {
79
+ const point = pointerAt(pointer, t);
80
+ if (!point) return null;
81
+ return { ...point, scale: pressScale(spans, cursor.press, t), shape: shapeAt(shapes, t) };
82
+ },
83
+ };
84
+ }