Skip to content
Source
Sign inSign up
fuko/rive-preview-player
Open History to see the last commit

rive-video-preview.mjs

326 lines13.2 KB

1#!/usr/bin/env node
2// rive-video-preview — a scrubbable, audio-capable preview player for Rive CLI projects.
3import { spawn } from 'node:child_process';
4import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
5import os from 'node:os';
6import path from 'node:path';
7import { DEFAULT_FEEDBACK_DAYS, FeedbackStore } from '../lib/feedback.mjs';
8import { STATE_DIR, findRunning, stateFile } from '../lib/registry.mjs';
9import { PreviewServer } from '../lib/server.mjs';
10​
11const HELP = `rive-video-preview — scrubbable video-style preview for Rive CLI projects
12​
13usage:
14 rive-video-preview [project-dir | file.riv] [options]
15 rive-video-preview wait-feedback [project-dir | file.riv] [--timeout <time>] [--no-mark-read]
16 wait for "Send to agent", print the feedback, exit
17 rive-video-preview mcp [project-dir] run the MCP server (stdio) for coding agents
18 rive-video-preview prune-feedback [project-dir | file.riv] [--days <n>] [--dry-run]
19 delete feedback bundles read over n days ago
20​
21 The project dir defaults to the current directory. It builds the project with
22 \`rive . --once\`, opens a player window, and rebuilds on every save. It keeps
23 running until stopped (Ctrl-C or --stop). Running it again for the same
24 project reuses the running player instead of starting a second one.
25​
26options:
27 --at <time> jump the player to a time: 12.5, 12.5s, 1:02.250, f741 (frame)
28 --artboard <name> artboard to show (default: the file's default)
29 --animation <name> animation to play (default: the one the state machine starts)
30 --port <n> port to serve on (default: first free from 4810)
31 --no-open don't open a window; just print the URL
32 --browser open in the default browser instead of a Chrome app window
33 --no-watch don't rebuild on file changes
34 --keep-feedback don't delete old feedback bundles
35 --feedback-days <n> delete bundles an agent read over n days ago (default 14)
36 --stop stop the player running for this project
37 --status print whether a player is running for this project
38 -h, --help show this help
39​
40player keys:
41 space play/pause · ←/→ frame · shift+←/→ 1s · home/end · i/o in/out · x clear range
42 c copy timecode · shift+c copy range · g go to time · l loop · m mute · f fullscreen · ? help
43 s screenshot this frame · shift+s drag (or type) a box to highlight a region (esc cancels)
44 n screenshots & notes panel
45 click a sound effect to set its volume · drag or ↑/↓ moves it between tracks (up to 3) · a hides tracks
46​
47feedback for agents:
48 Screenshots and notes are kept in <project>/.rive-preview/. "Send to agent" writes a
49 bundle to .rive-preview/feedback/<time>/ (feedback.md + PNGs; a region shot also records
50 its box in artboard units). To be woken by it, an agent runs
51 \`rive-video-preview wait-feedback .\` as a background command: it exits with the
52 feedback as soon as the user sends it (see wait-feedback --help). The player shows
53 the user whether an agent is listening. The MCP server serves the same bundles
54 through get_feedback / wait_for_feedback. Register it with, e.g.:
55 claude mcp add rive-preview -- rive-video-preview mcp
56 On start and after each send, bundles an agent read over 14 days ago are deleted
57 (unread bundles and drafts are never touched). Change it with --feedback-days, turn it
58 off with --keep-feedback, or set RIVE_PREVIEW_FEEDBACK_DAYS=<n> or =off.
59`;
60​
61function parseArgs(argv) {
62 const opts = { open: true, watch: true, browser: false };
63 const positional = [];
64 for (let i = 0; i < argv.length; i++) {
65 const a = argv[i];
66 const [flag, inline] = a.startsWith('--') && a.includes('=') ? [a.slice(0, a.indexOf('=')), a.slice(a.indexOf('=') + 1)] : [a, undefined];
67 const value = () => {
68 if (inline !== undefined) return inline;
69 const v = argv[++i];
70 if (v === undefined) fail(`${flag} needs a value`);
71 return v;
72 };
73 switch (flag) {
74 case '-h':
75 case '--help':
76 opts.help = true;
77 break;
78 case '--at':
79 opts.at = value();
80 break;
81 case '--artboard':
82 opts.artboard = value();
83 break;
84 case '--animation':
85 opts.animation = value();
86 break;
87 case '--port':
88 opts.port = Number(value());
89 break;
90 case '--no-open':
91 opts.open = false;
92 break;
93 case '--browser':
94 opts.browser = true;
95 break;
96 case '--no-watch':
97 opts.watch = false;
98 break;
99 case '--keep-feedback':
100 opts.keepFeedback = true;
101 break;
102 case '--feedback-days':
103 opts.feedbackDays = parseDays(value(), flag);
104 break;
105 case '--stop':
106 opts.stop = true;
107 break;
108 case '--status':
109 opts.status = true;
110 break;
111 default:
112 if (a.startsWith('-')) fail(`unknown option ${a}`);
113 positional.push(a);
114 }
115 }
116 if (positional.length > 1) fail('expected at most one project dir or .riv file');
117 opts.target = path.resolve(positional[0] ?? '.');
118 return opts;
120​
121function parseDays(v, what) {
122 const n = Number(v);
123 if (String(v).trim() === '' || !Number.isFinite(n) || n < 0) fail(`${what} must be a number of days (0 or more), got "${v}"`);
124 return n;
126​
127/** Days after which read bundles are pruned, or null to keep them: flags, then the env var, then 14. */
128function feedbackDays(opts) {
129 if (opts.keepFeedback) return null;
130 if (opts.feedbackDays != null) return opts.feedbackDays;
131 const env = process.env.RIVE_PREVIEW_FEEDBACK_DAYS?.trim();
132 if (env && /^(off|keep|never)$/i.test(env)) return null;
133 const n = Number(env);
134 if (env && Number.isFinite(n) && n >= 0) return n;
135 if (env) console.error(`rive-video-preview: ignoring RIVE_PREVIEW_FEEDBACK_DAYS="${env}" (expected a number of days or "off")`);
136 return DEFAULT_FEEDBACK_DAYS;
138​
139async function pruneFeedbackCommand(argv) {
140 let days;
141 let dryRun = false;
142 const positional = [];
143 for (let i = 0; i < argv.length; i++) {
144 const a = argv[i];
145 if (a === '--dry-run') dryRun = true;
146 else if (a === '--days') days = parseDays(argv[++i] ?? '', '--days');
147 else if (a.startsWith('--days=')) days = parseDays(a.slice(7), '--days');
148 else if (a === '-h' || a === '--help') return void process.stdout.write(HELP);
149 else if (a.startsWith('-')) fail(`unknown option ${a}`);
150 else positional.push(a);
151 }
152 if (positional.length > 1) fail('expected at most one project dir or .riv file');
153 const target = path.resolve(positional[0] ?? '.');
154 if (!existsSync(target)) fail(`${target} does not exist`);
155 if (!statSync(target).isDirectory() && !target.endsWith('.riv')) fail('expected a Rive project directory or a .riv file');
156 // An explicit prune still runs when the env var says "off"; only a number from it is used.
157 days ??= feedbackDays({}) ?? DEFAULT_FEEDBACK_DAYS;
158 const store = new FeedbackStore(target);
159 const ids = await store.prune({ olderThanDays: days, dryRun });
160 const s = ids.length === 1 ? '' : 's';
161 if (!ids.length) console.log(`no feedback bundles read over ${days} days ago in ${store.sentDir}`);
162 else console.log(`${dryRun ? 'would remove' : 'removed'} ${ids.length} feedback bundle${s} read over ${days} days ago from ${store.sentDir}:\n${ids.map((id) => ` ${id}`).join('\n')}`);
164​
165function fail(msg) {
166 console.error(`rive-video-preview: ${msg}\nrun with --help for usage`);
167 process.exit(1);
169​
170function log(msg) {
171 const ts = new Date().toTimeString().slice(0, 8);
172 for (const line of String(msg).split('\n')) console.log(`[${ts}] ${line}`);
174​
175async function freePort(start) {
176 const net = await import('node:net');
177 for (let p = start; p < start + 100; p++) {
178 const ok = await new Promise((resolve) => {
179 const s = net.createServer();
180 s.once('error', () => resolve(false));
181 s.listen(p, '127.0.0.1', () => s.close(() => resolve(true)));
182 });
183 if (ok) return p;
184 }
185 throw new Error('no free port found');
187​
188// ---------------------------------------------------------------- window
189function playerUrl(port, opts) {
190 const params = new URLSearchParams();
191 if (opts.at) params.set('t', opts.at);
192 if (opts.artboard) params.set('artboard', opts.artboard);
193 if (opts.animation) params.set('animation', opts.animation);
194 const hash = params.toString();
195 return `http://127.0.0.1:${port}/${hash ? '#' + hash : ''}`;
197​
198function windowSize(meta, opts) {
199 const abs = meta?.artboards || [];
200 const ab = abs.find((a) => a.name === opts.artboard) || abs.find((a) => a.name === meta?.defaultArtboard) || abs[0];
201 const aspect = ab && ab.width > 0 && ab.height > 0 ? ab.width / ab.height : 16 / 9;
202 const chrome = 168; // timeline + controls
203 let stageH = aspect < 1 ? 820 : Math.round(1120 / aspect);
204 let w = Math.round(stageH * aspect);
205 if (w < 720) w = 720;
206 return { w, h: stageH + chrome };
208​
209function chromePath() {
210 const candidates = [
211 '/Applications/Google Chrome.app',
212 path.join(os.homedir(), 'Applications/Google Chrome.app'),
213 '/Applications/Chromium.app',
214 '/Applications/Brave Browser.app',
215 '/Applications/Microsoft Edge.app',
216 ];
217 return candidates.find((c) => existsSync(c));
219​
220function openWindow(url, size, opts) {
221 const detached = { stdio: 'ignore', detached: true };
222 if (process.platform === 'darwin') {
223 const chrome = !opts.browser && chromePath();
224 if (chrome) {
225 spawn('open', ['-na', chrome, '--args', `--app=${url}`, `--window-size=${size.w},${size.h}`], detached).unref();
226 } else {
227 spawn('open', [url], detached).unref();
228 }
229 } else if (process.platform === 'win32') {
230 spawn('cmd', ['/c', 'start', '', url], detached).unref();
231 } else {
232 spawn('xdg-open', [url], detached).unref();
233 }
235​
236// ---------------------------------------------------------------- main
237async function main() {
238 if (process.argv[2] === 'mcp') {
239 const { runMcp } = await import('../lib/mcp.mjs');
240 return runMcp(process.argv.slice(3));
241 }
242 if (process.argv[2] === 'wait-feedback') {
243 const { runWaitFeedback } = await import('../lib/wait-feedback.mjs');
244 return runWaitFeedback(process.argv.slice(3));
245 }
246 if (process.argv[2] === 'prune-feedback') return pruneFeedbackCommand(process.argv.slice(3));
247 const opts = parseArgs(process.argv.slice(2));
248 if (opts.help) {
249 process.stdout.write(HELP);
250 return;
251 }
252 if (!existsSync(opts.target)) fail(`${opts.target} does not exist`);
253​
254 let mode;
255 if (statSync(opts.target).isDirectory()) {
256 if (!existsSync(path.join(opts.target, 'rive.yaml'))) fail(`${opts.target} has no rive.yaml — not a Rive CLI project`);
257 mode = 'project';
258 } else if (opts.target.endsWith('.riv')) {
259 mode = 'riv';
260 } else {
261 fail('expected a Rive project directory or a .riv file');
262 }
263​
264 const running = await findRunning(opts.target);
265​
266 if (opts.status) {
267 console.log(running ? `running at http://127.0.0.1:${running.port}/ (pid ${running.pid}, ${running.clients} window(s) open)` : 'not running');
268 return;
269 }
270 if (opts.stop) {
271 if (!running) return console.log('not running');
272 process.kill(running.pid, 'SIGTERM');
273 console.log(`stopped player (pid ${running.pid})`);
274 return;
275 }
276​
277 if (running) {
278 const url = playerUrl(running.port, opts);
279 if (running.clients > 0 && opts.at) {
280 await fetch(`http://127.0.0.1:${running.port}/api/seek`, { method: 'POST', body: JSON.stringify({ at: opts.at }) });
281 console.log(`player already running at http://127.0.0.1:${running.port}/ — jumped to ${opts.at}`);
282 } else if (running.clients > 0) {
283 console.log(`player already running at http://127.0.0.1:${running.port}/ (${running.clients} window(s) open; it live-reloads on save)`);
284 } else {
285 if (opts.open) openWindow(url, { w: 900, h: 900 }, opts);
286 console.log(`player already running; opened ${url}`);
287 }
288 return;
289 }
290​
291 if (mode === 'project' && !spawnSyncCheck()) fail('the `rive` CLI was not found on PATH');
292​
293 const server = new PreviewServer({ target: opts.target, mode, watch: opts.watch, log, feedbackDays: feedbackDays(opts) });
294 const port = opts.port || (await freePort(4810));
295 await server.listen(port);
296 mkdirSync(STATE_DIR, { recursive: true });
297 const sf = stateFile(opts.target);
298 writeFileSync(sf, JSON.stringify({ pid: process.pid, port, target: opts.target }));
299 const cleanup = () => {
300 try {
301 const st = JSON.parse(readFileSync(sf, 'utf8'));
302 if (st.pid === process.pid) rmSync(sf, { force: true });
303 } catch {}
304 };
305 process.on('exit', cleanup);
306 for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => process.exit(0));
307​
308 const url = playerUrl(port, opts);
309 log(`rive-video-preview: ${opts.target}`);
310 await server.pruneFeedback();
311 await server.rebuild('initial');
312 server.startWatching();
313 log(`player: ${url}`);
314 if (opts.open) openWindow(url, windowSize(server.meta, opts), opts);
315 log(opts.watch ? 'watching for changes (Ctrl-C to stop)' : 'serving (Ctrl-C to stop)');
317​
318function spawnSyncCheck() {
319 const dirs = (process.env.PATH || '').split(path.delimiter);
320 return dirs.some((d) => existsSync(path.join(d, process.platform === 'win32' ? 'rive.exe' : 'rive')));
322​
323main().catch((err) => {
324 console.error(err?.stack || String(err));
325 process.exit(1);
326});