cuetake 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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/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
@@ -8,6 +8,8 @@ import { doctor, installBrowser } from './environment.js';
8
8
  import { uninstall } from './uninstall.js';
9
9
  import { login } from './auth.js';
10
10
  import { extractFrame } from './render.js';
11
+ import { appTree } from './app-capture.js';
12
+ import { treeLines } from './app-locators.js';
11
13
  import { writeFile } from 'node:fs/promises';
12
14
  import { join, resolve } from 'node:path';
13
15
 
@@ -16,7 +18,8 @@ const help = `CueTake ${pkg.version} — browser demos directed by code
16
18
  cuetake doctor
17
19
  cuetake install-browser
18
20
  cuetake uninstall [--auth] [--looks] [--dry-run]
19
- cuetake record <scenario.mjs> [--out <new-directory>] [--auth-profile <name>] [--look <name|file.json>] [--narration <narration.json>] [--headed]
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>
20
23
  cuetake narrate import <take-directory> <narration.json>
21
24
  cuetake preview <take-directory> [--look <name|file.json>]... [--at <seconds>]
22
25
  cuetake render <take-directory>
@@ -35,12 +38,17 @@ uninstall removes CueTake's npx cache and its browser, unless another Playwright
35
38
  are never touched. --dry-run lists what would go and removes nothing.
36
39
  record captures, renders and verifies a new take; an existing directory is never overwritten.
37
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.
38
44
  --look seeds the first Edit from a Look; fields the Scenario config names win.
39
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.
40
48
  narrate import copies a Narration and its audio into a recorded Take, replacing its earlier one. Lines keep
41
49
  their start in edit.json; a new Line takes the start the file gives it. Render plays and subtitles them.
42
- preview writes preview.png in the take: the current Edit beside each Look, at --at seconds
43
- or at the end with the camera wide. It never changes edit.json or final.mp4.
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.
44
52
  render reuses source.webm, timeline.json and edit.json, replacing final.mp4 only on success.
45
53
  frame saves one Final frame as a PNG for inspection.
46
54
  login opens a separate browser; close its window after logging in to save the profile.
@@ -53,14 +61,15 @@ Scenario files are trusted JavaScript. Recording runs locally and captures no pa
53
61
  voiced beforehand by a speech tool of your choice.
54
62
  `;
55
63
  try {
56
- 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' } } });
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' } } });
57
65
  const [command, target] = positionals, looks = values.look ?? [];
58
66
  const print = data => console.log(JSON.stringify(data, null, 2));
59
67
  if (values.help || !command) console.log(help);
60
68
  else if (command === 'doctor') { const result = await doctor(); console.log(JSON.stringify(result, null, 2)); if (!result.ok) process.exitCode = 1; }
61
69
  else if (command === 'install-browser') console.log(JSON.stringify(await installBrowser(), null, 2));
62
70
  else if (command === 'uninstall' && !target) print(await uninstall({ auth: values.auth, looks: values.looks, dryRun: values['dry-run'] }));
63
- 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 }));
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'));
64
73
  else if (command === 'narrate' && target === 'import' && positionals[3]) print(await importNarration(positionals[2], positionals[3]));
65
74
  else if (command === 'preview' && target) print(await previewTake(target, looks, { at: values.at === undefined ? undefined : Number(values.at) }));
66
75
  else if (command === 'render' && target) { await renderTake(target); console.log(JSON.stringify(await verifyTake(target), null, 2)); }
package/src/desktop.js ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * The Desktop of a Take of Apps (ADR 0009), shared by Node and the render page. Pure functions, no imports.
3
+ *
4
+ * The Source shows the Desktop: the windows of the Take's Apps where they are, in their real order, on
5
+ * nothing. The Timeline's `windows` lists which show over time, each state `{ t, shown }` lasting until
6
+ * the next, `shown` back to front as `{ id, app, layer, x, y, width, height, radius }` (`app` indexes
7
+ * the Timeline's `apps`) in Desktop points from its top-left corner,
8
+ * which play the role of CSS pixels. Render draws the Source only inside these windows, so the
9
+ * Background shows between them.
10
+ */
11
+
12
+ /** The windows showing at Source time `t`, back to front. */
13
+ export function windowsAt(windows, t) {
14
+ return (windows ?? []).findLast(state => state.t <= t)?.shown ?? windows?.[0]?.shown ?? [];
15
+ }
16
+
17
+ /**
18
+ * Where `shown` windows are drawn: each clipped to the Desktop (`viewport`, in points), then placed on
19
+ * `page`, the Desktop's rectangle in stage pixels, with its corner radius in stage pixels. A window
20
+ * wholly outside the Desktop is left out. Only a window over no other window drawn under it has the
21
+ * window `effects` (its shadow) around it: the Source already shows the shadow a menu, a sheet or a
22
+ * control's own window casts on the window below.
23
+ */
24
+ export function drawnWindows(shown, viewport, page) {
25
+ const scale = page.w / viewport.width, drawn = [];
26
+ for (const { id, x, y, width, height, radius } of shown) {
27
+ const left = Math.max(0, x), top = Math.max(0, y), right = Math.min(viewport.width, x + width), bottom = Math.min(viewport.height, y + height);
28
+ if (right <= left || bottom <= top) continue;
29
+ const w = right - left, h = bottom - top, window = { x: page.x + left * scale, y: page.y + top * scale, w: w * scale, h: h * scale };
30
+ const over = drawn.some(({ window: under }) => window.x >= under.x && window.y >= under.y && window.x + window.w <= under.x + under.w && window.y + window.h <= under.y + under.h);
31
+ drawn.push({ id, window, radius: Math.min(radius, w / 2, h / 2) * scale, effects: !over });
32
+ }
33
+ return drawn;
34
+ }
35
+
36
+ // The narrowest empty stretch of a title bar a person would aim a click at, in points.
37
+ const TITLE_BAR_MIN = 12;
38
+
39
+ /**
40
+ * Where to click a window's title bar to bring it in front, as a person would: the middle of the widest
41
+ * stretch where nothing lies, no control, no title and no window over it, from `bar`, the helper's
42
+ * samples along the title bar's middle (`{ y, samples: [[x, empty], ...] }`, Desktop points, left to
43
+ * right). Returns `{ x, y, width }`, the stretch's width as the target's size, or null where no stretch
44
+ * is wide enough.
45
+ */
46
+ export function titleBarSpot(bar) {
47
+ let best = null, from = null;
48
+ const samples = bar?.samples ?? [];
49
+ samples.forEach(([x, empty], i) => {
50
+ if (empty && from === null) from = x;
51
+ const last = empty && (i === samples.length - 1 || !samples[i + 1][1]);
52
+ if (last && (!best || x - from > best.width)) best = { from, width: x - from };
53
+ if (!empty) from = null;
54
+ });
55
+ if (!best || best.width < TITLE_BAR_MIN) return null;
56
+ return { x: best.from + best.width / 2, y: bar.y, width: best.width };
57
+ }
58
+
59
+ // How long macOS animates a window closing: TextEdit's shrank for about 70 ms.
60
+ const CLOSING_S = 0.3;
61
+ const at = t => `${t.toFixed(2)} s`;
62
+ const size = w => `${w.width}×${w.height}`;
63
+ const inside = (w, viewport) => w.x >= 0 && w.y >= 0 && w.x + w.width <= viewport.width && w.y + w.height <= viewport.height;
64
+
65
+ const OTHER_INPUT = { pointer: 'the pointer', key: 'a key', scroll: 'a scroll' };
66
+ const listed = times => times.slice(0, 5).map(at).join(', ') + (times.length > 5 ? ` and ${times.length - 5} more` : '');
67
+
68
+ /**
69
+ * What a Final of Apps shows other than as recorded: the first App's first window (the largest at the
70
+ * start) not filling the Desktop, when the Take has one App (with several, `prepare` arranges them), or
71
+ * moving or resizing later; any other window reaching outside the Desktop, which is cut off there; a
72
+ * Desktop recorded at scale 1 or across a change of scale; frames the encoder dropped; and input the
73
+ * Director did not make (`otherInput`, as [t, kind]), which the Timeline leaves out but the App may have
74
+ * reacted to. `capture` is the Tab's stats in capture.json.
75
+ */
76
+ export function desktopWarnings({ viewport, windows = [], duration = Infinity, apps = [] }, { frames = [], dropped = 0, otherInput = [] }) {
77
+ // The first window is the largest of the first App's first layer-0 windows to show: a dialog may show before it.
78
+ const layer0 = state => state.shown.filter(w => w.layer === 0 && !w.app);
79
+ const several = apps.length > 1, ofApp = w => several ? apps[w.app ?? 0]?.name ?? 'an App' : 'the App';
80
+ const warnings = [], first = layer0(windows.find(state => layer0(state).length) ?? { shown: [] }).sort((a, b) => b.width * b.height - a.width * a.height)[0];
81
+ const same = (a, b) => a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
82
+ if (first && !several && !same(first, { x: 0, y: 0, ...viewport })) warnings.push(`The App's first window is ${size(first)} points, not the Desktop's ${size(viewport)}, so the Background shows around it: the App may limit its size; choose a viewport it can fill.`);
83
+ // A closing window shrinks for a moment before it goes; a change it leaves within CLOSING_S of is that, not a move,
84
+ // and so is one within CLOSING_S of the Take's end, which may come before the window goes.
85
+ const showsFirst = state => state.shown.some(w => w.id === first.id);
86
+ const closing = state => duration - state.t <= CLOSING_S || windows.some(later => later.t > state.t && later.t - state.t <= CLOSING_S && !showsFirst(later));
87
+ const moved = first && windows.find(state => state.shown.some(w => w.id === first.id && !same(w, first)) && !closing(state));
88
+ if (moved) {
89
+ const w = moved.shown.find(w => w.id === first.id);
90
+ warnings.push(`At ${at(moved.t)} ${several ? `the first window of ${ofApp(w)}` : "the App's first window"} moved or resized, to ${w.x}, ${w.y}, ${size(w)} points; Render does not correct it, so leave it where the Take put it.`);
91
+ }
92
+ const reported = new Set([first?.id]);
93
+ for (const state of windows) for (const w of state.shown) {
94
+ if (reported.has(w.id) || inside(w, viewport)) continue;
95
+ reported.add(w.id);
96
+ warnings.push(`At ${at(state.t)} a window of ${ofApp(w)} (${size(w)} points) reached outside the Desktop, so the Final shows it cut off.`);
97
+ }
98
+ const scales = new Set(frames.map(frame => frame.scale));
99
+ if (scales.has(1)) warnings.push('The Desktop was recorded at scale 1, so the Final is half as sharp; record on a Retina display.');
100
+ if (scales.size > 1) warnings.push(`The Desktop's scale changed during the Take (${[...scales].join(', ')}), as when a window moves to another display; record again with the App on one display.`);
101
+ if (otherInput.length) {
102
+ const kinds = Object.keys(OTHER_INPUT).filter(kind => otherInput.some(([, k]) => k === kind));
103
+ const what = kinds.map(kind => `${OTHER_INPUT[kind]} at ${listed(otherInput.filter(([, k]) => k === kind).map(([t]) => t))}`).join('; ');
104
+ warnings.push(`Someone used the Mac during the Take: ${what}. The Final's Cursor follows only the Scenario, but the App may have reacted; check those moments with frame, or record again and leave the Mac alone.`);
105
+ }
106
+ if (dropped) warnings.push(`The encoder could not keep up and ${dropped} frames were dropped from the Source; close other work and record again.`);
107
+ return warnings;
108
+ }