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.
@@ -1,88 +1,236 @@
1
1
  import { writeFile } from 'node:fs/promises';
2
2
 
3
- // Capture Chromium's current tab at its device-pixel resolution. Unlike
4
- // Playwright recordVideo, this does not use the 25 fps / 1 Mbps VP8 encoder.
5
- // A full-document navigation ends this recorder; SPA navigation is supported.
6
- export async function startTabCapture(page, options) {
3
+ /** The title the demo page wears for an instant, so Chromium hands its tab to the recorder. */
4
+ const CAPTURE_TITLE = '__cuetake_capture__';
5
+ /** Chromium flags Capture needs: pick the tab with that title without asking. */
6
+ export const captureArgs = [`--auto-select-tab-capture-source-by-title=${CAPTURE_TITLE}`];
7
+ /** The recorder's page, answered by its own route so it is a secure context that loads nothing. */
8
+ const RECORDER_URL = 'https://recorder.cuetake.invalid/';
9
+
10
+ const captures = new WeakMap(), counting = new WeakSet();
11
+ let nextKey = 0;
12
+
13
+ /**
14
+ * Counts the page's animation frames in its top document, sending their times to Node a few times a
15
+ * second and as the document goes away. A still page sends few Source frames, but its animation frames
16
+ * keep the display rate while the browser keeps up, so a shortfall means the machine fell behind.
17
+ */
18
+ function countAnimationFrames() {
19
+ if (window !== window.top || window.__cuetakeAnimationFrames) return;
20
+ window.__cuetakeAnimationFrames = true;
21
+ let times = [];
22
+ const flush = () => { if (!times.length) return; const sent = times; times = []; try { window.__cuetakePaint?.(sent)?.catch?.(() => {}); } catch {} };
23
+ const animate = now => { times.push(performance.timeOrigin + now); requestAnimationFrame(animate); };
24
+ requestAnimationFrame(animate);
25
+ setInterval(flush, 250);
26
+ addEventListener('pagehide', flush);
27
+ }
28
+
29
+ /**
30
+ * Opens the page that records every Tab of a Take, in a window of its own beside `page`, the first Tab.
31
+ * Chromium on macOS starts a capture only from the page in front, and a recorder that were a tab of the
32
+ * Tabs' window would hide the tab it starts on, which then paints no first frame for a second or more; it
33
+ * would also give that window a tab strip, which leaves each tab less room than the viewport, and tab
34
+ * capture records only that room.
35
+ */
36
+ export async function openRecorder(page) {
37
+ const context = page.context(), own = await context.newCDPSession(page), browser = await context.browser().newBrowserCDPSession();
38
+ try {
39
+ const { targetInfo } = await own.send('Target.getTargetInfo');
40
+ const [recorder] = await Promise.all([context.waitForEvent('page'), browser.send('Target.createTarget', { url: 'about:blank', newWindow: true, browserContextId: targetInfo.browserContextId })]);
41
+ try {
42
+ await recorder.route(RECORDER_URL, route => route.fulfill({ contentType: 'text/html', body: '<!doctype html><title>CueTake recorder</title>' }));
43
+ await recorder.goto(RECORDER_URL);
44
+ return recorder;
45
+ } catch (error) { await recorder.close().catch(() => {}); throw error; }
46
+ } finally { await Promise.all([own.detach(), browser.detach()].map(detached => detached.catch(() => {}))); }
47
+ }
48
+
49
+ /**
50
+ * Notes each main-frame navigation of the page, from its request until the new document has loaded,
51
+ * with when the page took its new address (`commit`), for startTabCapture. A Tab is watched from the
52
+ * moment it opens, so a popup's first navigations are noted before its capture starts.
53
+ */
54
+ export function watchNavigations(page) {
55
+ const state = { paints: [], navigations: [] };
56
+ // A redirect, or a navigation started before the last one committed, continues it.
57
+ const onRequest = request => {
58
+ if (!request.isNavigationRequest() || request.frame() !== page.mainFrame()) return;
59
+ const last = state.navigations.at(-1);
60
+ if (last?.end === null && !last.commit) { last.url = request.url(); return; }
61
+ // One that starts after the last committed, such as a script's redirect while loading, is its own.
62
+ if (last?.end === null) last.end = Date.now();
63
+ state.navigations.push({ ms: Date.now(), url: request.url(), end: null });
64
+ };
65
+ // A navigation that fails or turns into a download never loads a document.
66
+ const onEnd = () => { const last = state.navigations.at(-1); if (last?.end === null) last.end = Date.now(); };
67
+ // The page takes its new address when the new document commits, after any redirect. A same-document
68
+ // navigation (pushState, a fragment) also reports here, but finds no navigation waiting for one.
69
+ const onCommit = frame => {
70
+ const last = state.navigations.at(-1);
71
+ if (frame !== page.mainFrame() || last?.end !== null || last.commit) return;
72
+ last.commit = Date.now();
73
+ last.url = frame.url();
74
+ };
75
+ const onFailed = request => { if (request.isNavigationRequest() && request.frame() === page.mainFrame()) onEnd(); };
76
+ page.on('request', onRequest);
77
+ page.on('load', onEnd);
78
+ page.on('requestfailed', onFailed);
79
+ page.on('download', onEnd);
80
+ page.on('framenavigated', onCommit);
81
+ state.detach = () => { page.off('request', onRequest); page.off('load', onEnd); page.off('requestfailed', onFailed); page.off('download', onEnd); page.off('framenavigated', onCommit); };
82
+ captures.set(page, state);
83
+ return state;
84
+ }
85
+
86
+ /**
87
+ * Captures the page's tab at its device-pixel resolution from `recorder` (openRecorder), so the Source
88
+ * keeps recording across full navigations and reloads of the page, whether the tab is in front or not,
89
+ * until it closes. One recorder records several tabs, one stream each. Unlike Playwright recordVideo,
90
+ * this does not use the 25 fps / 1 Mbps VP8 encoder. Its navigations are noted (watchNavigations).
91
+ * Returns the page's address when Capture started as `url`.
92
+ */
93
+ export async function startTabCapture(page, recorder, options) {
94
+ const state = captures.get(page) ?? watchNavigations(page);
95
+ // A page that captured before keeps its binding and init script; only the collection starts over.
96
+ if (!counting.has(page)) {
97
+ counting.add(page);
98
+ await page.exposeBinding('__cuetakePaint', (_, times) => { if (Array.isArray(times)) captures.get(page)?.paints.push(...times); });
99
+ await page.addInitScript(countAnimationFrames);
100
+ }
101
+ const key = String(nextKey++);
102
+ Object.assign(state, { recorder, key });
7
103
  let timeout;
8
104
  try {
9
- return await Promise.race([page.evaluate(async ({ fps, width, height, bitrate }) => {
10
- // The stage names the step a stalled start is waiting on.
11
- window.__cuetakeCaptureStage = 'getDisplayMedia';
12
- const stream = await navigator.mediaDevices.getDisplayMedia({
13
- video: { width: { ideal: width }, height: { ideal: height }, frameRate: { ideal: fps, max: fps } },
14
- audio: false,
15
- preferCurrentTab: true,
16
- });
105
+ await page.evaluate(countAnimationFrames);
17
106
  // Headless Chromium paints only on change, so a settled page sends no frame and play() never
18
107
  // resolves. A near-invisible pixel flickers until recording starts to force paints.
19
- const nudge = Object.assign(document.createElement('div'), { style: 'position:fixed;left:0;top:0;width:1px;height:1px;pointer-events:none;z-index:2147483647' });
20
- document.documentElement.append(nudge);
21
- let flip = false;
22
- const nudging = setInterval(() => { flip = !flip; nudge.style.background = flip ? 'rgba(0,0,0,0.004)' : 'rgba(0,0,0,0.002)'; }, 50);
23
- const stopNudging = () => { clearInterval(nudging); nudge.remove(); };
108
+ const named = await page.evaluate(title => {
109
+ const nudge = Object.assign(document.createElement('div'), { style: 'position:fixed;left:0;top:0;width:1px;height:1px;pointer-events:none;z-index:2147483647' });
110
+ document.documentElement.append(nudge);
111
+ let flip = false;
112
+ const nudging = setInterval(() => { flip = !flip; nudge.style.background = flip ? 'rgba(0,0,0,0.004)' : 'rgba(0,0,0,0.002)'; }, 50);
113
+ window.__cuetakeStopNudging = () => { clearInterval(nudging); nudge.remove(); delete window.__cuetakeStopNudging; };
114
+ const had = Boolean(document.querySelector('title')), old = document.title;
115
+ document.title = title;
116
+ return { had, old };
117
+ }, CAPTURE_TITLE);
118
+ const restore = () => page.evaluate(({ had, old }) => {
119
+ window.__cuetakeStopNudging?.();
120
+ if (had) document.title = old; else document.querySelector('title')?.remove();
121
+ }, named).catch(() => {});
24
122
  try {
25
- const track = stream.getVideoTracks()[0];
26
- window.__cuetakeCaptureStage = 'applyConstraints';
27
- await track.applyConstraints({ width, height, frameRate: fps });
28
- const video = document.createElement('video');
29
- video.srcObject = stream;
30
- video.muted = true;
31
- // Subscribe before play: a static tab may never produce a second frame.
32
- const firstFrame = new Promise(resolve => video.requestVideoFrameCallback(resolve));
33
- window.__cuetakeCaptureStage = 'play';
34
- await video.play();
35
- window.__cuetakeCaptureStage = 'first frame';
36
- await firstFrame;
37
- const mimeType = 'video/webm;codecs=vp9';
38
- if (!MediaRecorder.isTypeSupported(mimeType)) throw new Error('VP9 tab capture unavailable');
39
- const recorder = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: bitrate });
40
- const state = { stream, video, recorder, chunks: [], frames: [], settings: track.getSettings(), error: null };
41
- window.__cuetakeCapture = state;
42
- const tick = (now, metadata) => {
43
- if (recorder.state !== 'recording') return;
44
- state.frames.push({ timeMs: performance.timeOrigin + now - state.startedAtMs, mediaTime: metadata.mediaTime, presentedFrames: metadata.presentedFrames });
45
- video.requestVideoFrameCallback(tick);
46
- };
47
- recorder.ondataavailable = event => { if (event.data.size) state.chunks.push(event.data); };
48
- recorder.onerror = event => { state.error = event.error?.message || 'MediaRecorder error'; };
49
- window.__cuetakeCaptureStage = 'MediaRecorder start';
50
- await new Promise(resolve => {
51
- recorder.onstart = () => { state.startedAtMs = Date.now(); stopNudging(); video.requestVideoFrameCallback(tick); resolve(); };
52
- recorder.start(1000);
53
- });
54
- return { startedAt: new Date(state.startedAtMs).toISOString(), settings: state.settings };
55
- } catch (error) {
56
- stopNudging();
57
- stream.getTracks().forEach(track => track.stop());
58
- throw error;
59
- }
60
- }, options), new Promise((_, reject) => {
61
- timeout = setTimeout(async () => {
62
- const stage = await page.evaluate(() => window.__cuetakeCaptureStage).catch(() => 'unknown');
63
- reject(new Error(`Tab capture did not start within 15 seconds (waiting on: ${stage})`));
64
- }, 15_000);
65
- })]);
66
- } finally { clearTimeout(timeout); }
123
+ // Chromium on macOS starts a capture only from the page in front; the tab comes back after.
124
+ await recorder.bringToFront();
125
+ return await Promise.race([recorder.evaluate(async ({ key, fps, width, height, bitrate }) => {
126
+ // The stage names the step a stalled start is waiting on.
127
+ window.__cuetakeCaptureStage = 'getDisplayMedia';
128
+ const stream = await navigator.mediaDevices.getDisplayMedia({
129
+ video: { width: { ideal: width }, height: { ideal: height }, frameRate: { ideal: fps, max: fps } },
130
+ audio: false,
131
+ selfBrowserSurface: 'exclude',
132
+ });
133
+ try {
134
+ const track = stream.getVideoTracks()[0];
135
+ window.__cuetakeCaptureStage = 'applyConstraints';
136
+ await track.applyConstraints({ width, height, frameRate: fps });
137
+ const video = document.createElement('video');
138
+ video.srcObject = stream;
139
+ video.muted = true;
140
+ // Subscribe before play: a static tab may never produce a second frame.
141
+ const firstFrame = new Promise(resolve => video.requestVideoFrameCallback(resolve));
142
+ window.__cuetakeCaptureStage = 'play';
143
+ await video.play();
144
+ window.__cuetakeCaptureStage = 'first frame';
145
+ await firstFrame;
146
+ const mimeType = 'video/webm;codecs=vp9';
147
+ if (!MediaRecorder.isTypeSupported(mimeType)) throw new Error('VP9 tab capture unavailable');
148
+ const recorder = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: bitrate });
149
+ const state = { stream, video, recorder, chunks: [], frames: [], settings: track.getSettings(), error: null, endedAtMs: null };
150
+ (window.__cuetakeCaptures ??= {})[key] = state;
151
+ // A tab that closes ends its stream, and with it the recording.
152
+ state.stopped = new Promise(resolve => { recorder.onstop = resolve; });
153
+ track.addEventListener('ended', () => { state.endedAtMs ??= Date.now(); });
154
+ const tick = (now, metadata) => {
155
+ if (recorder.state !== 'recording') return;
156
+ state.frames.push({ timeMs: performance.timeOrigin + now - state.startedAtMs, mediaTime: metadata.mediaTime, presentedFrames: metadata.presentedFrames });
157
+ video.requestVideoFrameCallback(tick);
158
+ };
159
+ recorder.ondataavailable = event => { if (event.data.size) state.chunks.push(event.data); };
160
+ recorder.onerror = event => { state.error = event.error?.message || 'MediaRecorder error'; };
161
+ window.__cuetakeCaptureStage = 'MediaRecorder start';
162
+ await new Promise(resolve => {
163
+ recorder.onstart = () => { state.startedAtMs = Date.now(); video.requestVideoFrameCallback(tick); resolve(); };
164
+ recorder.start(1000);
165
+ });
166
+ return { startedAt: new Date(state.startedAtMs).toISOString(), settings: state.settings };
167
+ } catch (error) {
168
+ stream.getTracks().forEach(track => track.stop());
169
+ throw error;
170
+ }
171
+ }, { ...options, key }), new Promise((_, reject) => {
172
+ timeout = setTimeout(async () => {
173
+ const stage = await recorder.evaluate(() => window.__cuetakeCaptureStage).catch(() => 'unknown');
174
+ reject(new Error(`Tab capture did not start within 15 seconds (waiting on: ${stage})`));
175
+ }, 15_000);
176
+ })]).then(started => { state.startedAtMs = Date.parse(started.startedAt); return { ...started, url: page.url() }; });
177
+ } finally { clearTimeout(timeout); await page.bringToFront().catch(() => {}); await restore(); }
178
+ } catch (error) {
179
+ stopListening(page);
180
+ throw error;
181
+ }
182
+ }
183
+
184
+ function stopListening(page) {
185
+ const state = captures.get(page);
186
+ if (!state) return null;
187
+ captures.delete(page);
188
+ state.detach();
189
+ return state;
67
190
  }
68
191
 
192
+ /**
193
+ * Seconds since the tab's capture started of each animation frame's second, and of each navigation, from its
194
+ * request until its document loaded (or Capture stopped), with when it committed, if it did. A navigation
195
+ * noted before the capture started, such as a popup's first, has negative times.
196
+ */
197
+ export function captureSeconds({ paints, navigations, startedAtMs }, stoppedAtMs) {
198
+ const pageFrames = [];
199
+ for (const ms of paints) {
200
+ if (ms < startedAtMs || ms >= stoppedAtMs) continue;
201
+ const second = Math.floor((ms - startedAtMs) / 1000);
202
+ pageFrames[second] = (pageFrames[second] ?? 0) + 1;
203
+ }
204
+ const t = ms => Math.round(Math.min(ms, stoppedAtMs) - startedAtMs) / 1000;
205
+ return {
206
+ pageFrames: Array.from(pageFrames, n => n ?? 0),
207
+ navigations: navigations.filter(n => n.ms < stoppedAtMs).map(n => ({ t: t(n.ms), end: t(n.end ?? stoppedAtMs), url: n.url, ...(n.commit && n.commit < stoppedAtMs && { commit: t(n.commit) }) })),
208
+ };
209
+ }
210
+
211
+ /** Stops capturing the page's tab, or reads what it recorded until it closed, and writes the Source and its stats. */
69
212
  export async function stopTabCapture(page, outputPath) {
70
- const result = await page.evaluate(async () => {
71
- const state = window.__cuetakeCapture;
72
- if (!state) throw new Error('Tab recorder lost: full-document navigation is unsupported in hd-tab mode');
73
- const stoppedAtMs = Date.now();
74
- await new Promise(resolve => { state.recorder.onstop = resolve; state.recorder.stop(); });
75
- state.stream.getTracks().forEach(track => track.stop());
76
- state.video.srcObject = null;
77
- if (state.error) throw new Error(state.error);
78
- const bytes = new Uint8Array(await new Blob(state.chunks).arrayBuffer());
79
- let binary = '';
80
- for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
81
- const stats = { settings: state.settings, duration: (stoppedAtMs - state.startedAtMs) / 1000, frames: state.frames };
82
- delete window.__cuetakeCapture;
83
- return { data: btoa(binary), stats };
84
- });
85
- await writeFile(outputPath, Buffer.from(result.data, 'base64'));
86
- await writeFile(outputPath.replace(/\.webm$/, '-capture.json'), JSON.stringify(result.stats, null, 2));
87
- return result.stats;
213
+ const state = captures.get(page);
214
+ if (!state) throw new Error('This page is not being captured');
215
+ try {
216
+ // Animation frames the page counted before the stop arrive before its answer to an evaluate.
217
+ await page.evaluate(() => 0).catch(() => {});
218
+ const result = await state.recorder.evaluate(async key => {
219
+ const state = window.__cuetakeCaptures[key];
220
+ const stoppedAtMs = state.endedAtMs ?? Date.now();
221
+ if (state.recorder.state !== 'inactive') state.recorder.stop();
222
+ await state.stopped;
223
+ state.stream.getTracks().forEach(track => track.stop());
224
+ state.video.srcObject = null;
225
+ if (state.error) throw new Error(state.error);
226
+ const bytes = new Uint8Array(await new Blob(state.chunks).arrayBuffer());
227
+ let binary = '';
228
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
229
+ delete window.__cuetakeCaptures[key];
230
+ return { data: btoa(binary), stoppedAtMs, stats: { settings: state.settings, duration: (stoppedAtMs - state.startedAtMs) / 1000, frames: state.frames } };
231
+ }, state.key);
232
+ const stats = { ...result.stats, ...captureSeconds(state, result.stoppedAtMs) };
233
+ await writeFile(outputPath, Buffer.from(result.data, 'base64'));
234
+ return stats;
235
+ } finally { stopListening(page); }
88
236
  }
package/src/tabs.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Tabs, shared by Node and the render page. Pure functions, no imports.
3
+ *
4
+ * A Take shows one Tab or more: the start page and each page the demo opened (ADR 0008). A Tab the
5
+ * size of the viewport is a tab of the same window; any other is a popup window over the Tab that
6
+ * opened it. Each Tab's input is in its own CSS pixels; the window's are those of the viewport, which
7
+ * the camera and the Cursor use.
8
+ *
9
+ * Tabs are the Timeline's `{ id, opener, opened, closed, viewport, start }`, times in Source seconds.
10
+ */
11
+
12
+ /** Whether a Tab is drawn as a popup window rather than as a tab of the window. */
13
+ export const isPopup = (tab, viewport) => tab.viewport.width !== viewport.width || tab.viewport.height !== viewport.height;
14
+
15
+ /**
16
+ * Where each Tab's CSS pixels sit in the window's, as `{ x, y, scale }` by Tab id. A popup's page is
17
+ * centered over its opener's page and scaled down to fit it, unless the Edit's `placement` ([{ tab, x,
18
+ * y }], in the opener's CSS pixels) names where; the popups it opened move with it.
19
+ */
20
+ export function windowMaps(tabs, viewport, placement = []) {
21
+ const byId = new Map(tabs.map(tab => [tab.id, tab])), maps = new Map();
22
+ const mapOf = (tab, depth = 0) => {
23
+ if (maps.has(tab.id)) return maps.get(tab.id);
24
+ let map = { x: 0, y: 0, scale: 1 };
25
+ const opener = byId.get(tab.opener);
26
+ if (isPopup(tab, viewport) && opener && depth < 32) {
27
+ const outer = mapOf(opener, depth + 1), room = opener.viewport, { width, height } = tab.viewport;
28
+ const scale = Math.min(1, room.width / width, room.height / height);
29
+ const placed = placement.find(p => p.tab === tab.id);
30
+ const x = placed?.x ?? (room.width - width * scale) / 2, y = placed?.y ?? (room.height - height * scale) / 2;
31
+ map = { x: outer.x + x * outer.scale, y: outer.y + y * outer.scale, scale: scale * outer.scale };
32
+ }
33
+ maps.set(tab.id, map);
34
+ return map;
35
+ };
36
+ for (const tab of tabs) mapOf(tab);
37
+ return maps;
38
+ }
39
+
40
+ /**
41
+ * What the Final shows of the Tabs through the Take. `at(t)` lists, at Final time `t`, what to draw in
42
+ * order, each as `{ tab, popup, opacity, scale }`: the tab the window shows (two while one fades into
43
+ * the next), then each popup window over it, opener first. The window shows the Tab in front, or, while
44
+ * a popup is in front, the tab beneath it; the popups between them show over it. `cuts` are the Final
45
+ * times the window starts showing another tab, where the camera cuts to wide.
46
+ *
47
+ * Tabs switch in Source time (the Timeline's `front` events; the first Tab is in front until one) and
48
+ * their transitions keep their pace in Final time: `style` is the Edit's `tabs`, whose `transition` is
49
+ * 'cut' or `{ fade }` seconds, and whose `popupAnimation` (`{ duration, scale }`, or false) scales and
50
+ * fades a popup window in as it comes to show and out as it goes.
51
+ */
52
+ export function tabTrack({ tabs, events = [], viewport }, style, map) {
53
+ const byId = new Map(tabs.map(tab => [tab.id, tab]));
54
+ const popup = id => byId.has(id) && isPopup(byId.get(id), viewport);
55
+ // The Tabs shown with `front` in front: the tab beneath it, then the popups up to it.
56
+ const stackOf = front => {
57
+ const chain = [front];
58
+ for (let id = front; popup(id) && byId.has(byId.get(id).opener) && chain.length < 32;) chain.unshift(id = byId.get(id).opener);
59
+ return chain;
60
+ };
61
+ const fronts = events.filter(event => event.type === 'front').toSorted((a, b) => a.t - b.t);
62
+ const states = [{ t: 0, stack: stackOf(tabs[0]?.id ?? 0) }, ...fronts.map(event => ({ t: map.outputAt(event.t), stack: stackOf(event.tab) }))];
63
+ // Each time the window shows another tab, with the one it showed before.
64
+ const switches = states.flatMap((state, i) => i && state.stack[0] !== states[i - 1].stack[0] ? [{ t: state.t, before: states[i - 1].stack[0] }] : []);
65
+ // Each popup's spans of the Final while it shows: [from, until), until Infinity while still showing.
66
+ const spans = new Map();
67
+ states.forEach((state, i) => {
68
+ const until = states[i + 1]?.t ?? Infinity;
69
+ for (const id of state.stack.slice(1)) {
70
+ const list = spans.get(id) ?? [], last = list.at(-1);
71
+ if (last && last.until === state.t) last.until = until; else list.push({ from: state.t, until });
72
+ spans.set(id, list);
73
+ }
74
+ });
75
+ const depth = id => stackOf(id).length;
76
+ const fade = typeof style?.transition === 'object' ? style.transition.fade ?? 0 : 0;
77
+ const animation = style?.popupAnimation || null, duration = animation?.duration ?? 0, smallest = animation?.scale ?? 1;
78
+ return {
79
+ cuts: switches.map(({ t }) => t),
80
+ at(t) {
81
+ const k = states.findLastIndex(state => state.t <= t), shown = [];
82
+ const switched = switches.findLast(({ t: at }) => at <= t);
83
+ if (fade > 0 && switched && t - switched.t < fade) {
84
+ shown.push({ tab: switched.before, popup: false, opacity: 1, scale: 1 }, { tab: states[k].stack[0], popup: false, opacity: (t - switched.t) / fade, scale: 1 });
85
+ } else shown.push({ tab: states[k].stack[0], popup: false, opacity: 1, scale: 1 });
86
+ const popups = [];
87
+ for (const [id, list] of spans) for (const { from, until } of list) {
88
+ const progress = duration > 0 ? Math.min(1, (t - from) / duration, (until + duration - t) / duration) : t < until ? 1 : 0;
89
+ if (t >= from && progress > 0) popups.push({ tab: id, popup: true, opacity: progress, scale: smallest + (1 - smallest) * progress, from });
90
+ }
91
+ popups.sort((a, b) => depth(a.tab) - depth(b.tab) || a.from - b.from);
92
+ return [...shown, ...popups.map(({ from, ...drawn }) => drawn)];
93
+ },
94
+ };
95
+ }
96
+
97
+ /**
98
+ * The Timeline's pointer path and events, and the camera's targets, moved from each Tab's CSS pixels
99
+ * to the window's by `maps` (windowMaps). A sample or item without a `tab` is the first Tab's.
100
+ */
101
+ export function inWindow({ pointer = [], events = [] }, targets = [], maps) {
102
+ const mapOf = tab => maps.get(tab ?? 0) ?? { x: 0, y: 0, scale: 1 };
103
+ const point = (m, p) => p && { ...p, x: m.x + p.x * m.scale, y: m.y + p.y * m.scale };
104
+ const box = (m, b) => b && { x: m.x + b.x * m.scale, y: m.y + b.y * m.scale, width: b.width * m.scale, height: b.height * m.scale };
105
+ const placed = item => {
106
+ const m = mapOf(item.tab), moved = { ...item };
107
+ if (typeof item.x === 'number') Object.assign(moved, point(m, { x: item.x, y: item.y }));
108
+ for (const key of ['from', 'to']) if (item[key]) moved[key] = point(m, item[key]);
109
+ if (item.box) moved.box = box(m, item.box);
110
+ return moved;
111
+ };
112
+ return {
113
+ pointer: pointer.map(([t, x, y, tab]) => { const m = mapOf(tab); return [t, m.x + x * m.scale, m.y + y * m.scale]; }),
114
+ events: events.map(placed),
115
+ targets: targets.map(placed),
116
+ };
117
+ }
118
+
119
+ /** A point in one Tab's CSS pixels as it sits in another's, through the window (`maps`: windowMaps). */
120
+ export function carried(point, from, to, maps) {
121
+ const a = maps.get(from), b = maps.get(to);
122
+ return { x: (a.x + point.x * a.scale - b.x) / b.scale, y: (a.y + point.y * a.scale - b.y) / b.scale };
123
+ }
124
+
125
+ /** Whether a Tab's page sees the pointer at `point`, which it does only over its viewport. */
126
+ export const seenBy = (point, viewport) => point.x >= 0 && point.y >= 0 && point.x < viewport.width && point.y < viewport.height;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The time map between the Final and the Source, shared by Node and the render page. Pure functions,
3
+ * no imports.
4
+ *
5
+ * Every time in the Timeline and the Edit is Source time: seconds since Capture started. The Edit's
6
+ * `fastForward` spans (`{ start, end, rate }`, Source seconds) play `rate` times faster in the Final;
7
+ * the rest plays as recorded. A span eases to its rate and back inside itself, over about `EASE`
8
+ * seconds of the Final each way, so the page never jumps to speed and the moments around the span stay
9
+ * as recorded.
10
+ */
11
+
12
+ const EASE = 0.3; // seconds of the Final a span takes to reach its rate, and to leave it
13
+ const BADGE_IN = 0.15, BADGE_OUT = 0.2; // seconds of the Final a fast-forward badge takes to appear and to go
14
+ const EPSILON = 0.005;
15
+
16
+ // A ramp's speed rises from 1 to `rate` as smoothstep(u); `rise(u)` is that share integrated over u.
17
+ const rise = u => u * u * u - u * u * u * u / 2;
18
+
19
+ /** What stops the spans from playing: a rate below 1, an empty span, or spans that overlap. Each problem names its span. */
20
+ export function fastForwardProblems(spans = []) {
21
+ const problems = [], sorted = [...spans].sort((a, b) => a.start - b.start);
22
+ const name = span => `The fast-forward ${typeof span.start === 'number' ? `from ${span.start.toFixed(2)} s` : JSON.stringify(span)}`;
23
+ for (const [i, span] of sorted.entries()) {
24
+ if (!(typeof span.start === 'number' && typeof span.end === 'number' && span.end > span.start)) problems.push(`${name(span)} needs a start before its end, in seconds`);
25
+ if (!(typeof span.rate === 'number' && span.rate >= 1)) problems.push(`${name(span)} needs a rate of at least 1`);
26
+ const next = sorted[i + 1];
27
+ if (next && next.start < span.end - EPSILON) problems.push(`${name(span)} overlaps the one from ${next.start.toFixed(2)} s`);
28
+ }
29
+ return problems;
30
+ }
31
+
32
+ /**
33
+ * The map for a Source `duration` seconds long: the Final's `duration`, `sourceAt(t)` for a moment of
34
+ * the Final, `outputAt(s)` for a moment of the Source, and each span's place in the Final as
35
+ * `spans: [{ start, end, rate }]`. Spans are clipped to the Source; invalid ones stop it.
36
+ */
37
+ export function timeMap(spans = [], duration) {
38
+ const problems = fastForwardProblems(spans);
39
+ if (problems.length) throw new Error(`The fast-forward spans do not fit: ${problems.join('; ')}`);
40
+ // Pieces of the Final in order, each `seconds` long from Final time `t` and Source time `s`.
41
+ const pieces = [];
42
+ let t = 0, s = 0;
43
+ const add = (seconds, source, at, rate = 1) => { if (seconds > 0) pieces.push({ t, s, seconds, at, rate }); t += seconds; s += source; };
44
+ const shown = [];
45
+ const clipped = spans.map(span => ({ ...span, start: Math.max(0, span.start), end: Math.min(duration, span.end) })).filter(span => span.end > span.start);
46
+ for (const { start, end, rate } of clipped.sort((a, b) => a.start - b.start)) {
47
+ add(start - s, start - s, u => u);
48
+ const from = t, length = end - start, ease = Math.min(EASE, length / (1 + rate)), steady = length - ease * (1 + rate);
49
+ add(ease, ease * (1 + rate) / 2, u => u + (rate - 1) * ease * rise(u / ease), null);
50
+ add(steady / rate, steady, u => u * rate, rate);
51
+ add(ease, ease * (1 + rate) / 2, u => rate * u - (rate - 1) * ease * rise(u / ease), null);
52
+ s = end; // no drift from the ramps' arithmetic
53
+ shown.push({ start: from, end: t, rate });
54
+ }
55
+ add(Math.max(0, duration - s), Math.max(0, duration - s), u => u);
56
+ if (!pieces.length) pieces.push({ t: 0, s: 0, seconds: 0, at: u => u, rate: 1 });
57
+ const last = (list, key, value) => list.findLast(piece => piece[key] <= value) ?? list[0];
58
+ return {
59
+ duration: t,
60
+ spans: shown,
61
+ sourceAt(time) {
62
+ const piece = last(pieces, 't', time), u = Math.min(Math.max(time - piece.t, 0), piece.seconds);
63
+ // Past the last piece, or before the first, the Final plays the Source as recorded.
64
+ return piece.s + piece.at(u) + (time - piece.t - u);
65
+ },
66
+ outputAt(source) {
67
+ const piece = last(pieces, 's', source), offset = source - piece.s;
68
+ if (piece.rate !== null || offset <= 0) return piece.t + offset / (piece.rate ?? 1);
69
+ // A ramp: its Source time rises monotonically, so halve the interval until it pins `offset`.
70
+ let low = 0, high = piece.seconds;
71
+ if (piece.at(high) <= offset) return piece.t + high + (offset - piece.at(high));
72
+ for (let i = 0; i < 48; i++) { const mid = (low + high) / 2; if (piece.at(mid) < offset) low = mid; else high = mid; }
73
+ return piece.t + (low + high) / 2;
74
+ },
75
+ };
76
+ }
77
+
78
+ /** The fast-forward badge at Final time `t`: the index of the span showing, its rate and the badge's opacity, or null. */
79
+ export function badgeAt(map, t) {
80
+ const index = map.spans.findIndex(span => t >= span.start && t < span.end);
81
+ if (index < 0) return null;
82
+ const { start, end, rate } = map.spans[index];
83
+ return { index, rate, opacity: Math.max(0, Math.min(1, (t - start) / BADGE_IN, (end - t) / BADGE_OUT)) };
84
+ }
85
+
86
+ /** `items` with the times named by `keys` moved from the Source to the Final, as Shortcuts and camera targets are. */
87
+ export const retimed = (items, map, keys = ['t']) => items.map(item => {
88
+ const moved = { ...item };
89
+ for (const key of keys) if (typeof item[key] === 'number') moved[key] = map.outputAt(item[key]);
90
+ return moved;
91
+ });
92
+
93
+ /**
94
+ * Lines placed in the Final: each `start` moved to Final time. A Line still speaking while the Final
95
+ * fast-forwards is a problem naming it, since speech cannot play faster with the picture.
96
+ */
97
+ export function linesInFinal(lines, map) {
98
+ const problems = [], seconds = s => `${s.toFixed(2)} s`;
99
+ const placed = lines.map(line => {
100
+ const start = map.outputAt(line.start), stops = start + (line.duration ?? 0);
101
+ const span = map.spans.find(span => start < span.end - EPSILON && stops > span.start + EPSILON);
102
+ if (span) problems.push(`Line '${line.id}' is spoken from ${seconds(start)} to ${seconds(stops)} of the Final, while it fast-forwards from ${seconds(span.start)} to ${seconds(span.end)}; move the Line out of it or shorten the fast-forward`);
103
+ return { ...line, start };
104
+ });
105
+ return { lines: placed, problems };
106
+ }
@@ -0,0 +1,62 @@
1
+ import fs from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { basename, dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { authProfileFiles } from './auth.js';
6
+ import { globalLookFiles } from './look.js';
7
+ import { uninstallBrowser } from './environment.js';
8
+
9
+ const PACKAGE_DIR = fileURLToPath(new URL('..', import.meta.url)).replace(/[\\/]$/, '');
10
+
11
+ /**
12
+ * The npx folders made for CueTake alone, in any version. The one this CLI runs from is
13
+ * `<cache>/_npx/<hash>/node_modules/cuetake`; npx folders that also hold other packages are not CueTake's.
14
+ */
15
+ export async function npxFolders({ cache = process.env.npm_config_cache || join(homedir(), '.npm'), packageDir = PACKAGE_DIR } = {}) {
16
+ const own = dirname(dirname(packageDir)), roots = new Set([join(cache, '_npx')]);
17
+ if (basename(dirname(own)) === '_npx' && basename(packageDir) === 'cuetake') roots.add(dirname(own));
18
+ const found = [];
19
+ for (const root of roots) {
20
+ const names = await fs.readdir(root).catch(error => { if (['ENOENT', 'ENOTDIR'].includes(error.code)) return []; throw error; });
21
+ for (const name of names) {
22
+ const manifest = await fs.readFile(join(root, name, 'package.json'), 'utf8').then(JSON.parse, () => null);
23
+ if (manifest && Object.keys(manifest.dependencies ?? {}).join() === 'cuetake') found.push(join(root, name));
24
+ }
25
+ }
26
+ return found.sort();
27
+ }
28
+
29
+ /**
30
+ * Removes what CueTake put on this machine outside the user's projects: its npx folders and, through
31
+ * Playwright, the browser unless another Playwright installation still uses it. Auth profiles and global
32
+ * Looks are the user's and go only when asked. Take folders and local Looks are never touched.
33
+ */
34
+ export async function uninstall({ auth = false, looks = false, dryRun = false, removeBrowser = uninstallBrowser } = {}) {
35
+ const npx = await npxFolders(), profiles = await authProfileFiles(), globalLooks = await globalLookFiles();
36
+ const removed = [], kept = [];
37
+ const remove = async (item, paths) => {
38
+ for (const path of paths) {
39
+ if (!dryRun) await fs.rm(path, { recursive: true, force: true });
40
+ removed.push({ item, path });
41
+ }
42
+ };
43
+ const own = dirname(dirname(PACKAGE_DIR));
44
+ // Old CueTake versions go first so Playwright no longer counts their claim on the browser.
45
+ await remove('npx cache', npx.filter(path => path !== own));
46
+ const browser = await removeBrowser({ dryRun });
47
+ if (browser.existed && dryRun) removed.push({ item: 'browser', path: browser.path, note: 'kept if another Playwright installation still uses it' });
48
+ else if (browser.removed) removed.push({ item: 'browser', path: browser.path });
49
+ else if (browser.existed) kept.push({ item: 'browser', path: browser.path, reason: 'another Playwright installation still uses it' });
50
+ for (const [item, flag, wanted, { dir, paths }] of [['Auth profile', '--auth', auth, profiles], ['global Look', '--looks', looks, globalLooks]]) {
51
+ if (wanted) await remove(item, paths);
52
+ else if (paths.length) kept.push({ item, path: dir, count: paths.length, reason: `pass ${flag} to remove` });
53
+ if (wanted && !dryRun) await fs.rmdir(dir).catch(() => {});
54
+ }
55
+ // This CLI's own npx folder goes last, once nothing else needs its files.
56
+ await remove('npx cache', npx.filter(path => path === own));
57
+ if (!dryRun) await fs.rmdir(join(homedir(), '.local/share/cuetake')).catch(() => {});
58
+ return {
59
+ dryRun, [dryRun ? 'wouldRemove' : 'removed']: removed, kept,
60
+ note: 'Take folders and local Looks (.cuetake/looks) stay in your projects. The skill is removed by the tool that installed it.',
61
+ };
62
+ }