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

rive-video-preview.mjs

264 lines9.9 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 { STATE_DIR, findRunning, stateFile } from '../lib/registry.mjs';
8import { PreviewServer } from '../lib/server.mjs';
9​
10const HELP = `rive-video-preview — scrubbable video-style preview for Rive CLI projects
11​
12usage:
13 rive-video-preview [project-dir | file.riv] [options]
14 rive-video-preview wait-feedback [project-dir | file.riv] [--timeout <time>] [--no-mark-read]
15 wait for "Send to agent", print the feedback, exit
16 rive-video-preview mcp [project-dir] run the MCP server (stdio) for coding agents
17​
18 The project dir defaults to the current directory. It builds the project with
19 \`rive . --once\`, opens a player window, and rebuilds on every save. It keeps
20 running until stopped (Ctrl-C or --stop). Running it again for the same
21 project reuses the running player instead of starting a second one.
22​
23options:
24 --at <time> jump the player to a time: 12.5, 12.5s, 1:02.250, f741 (frame)
25 --artboard <name> artboard to show (default: the file's default)
26 --animation <name> animation to play (default: the one the state machine starts)
27 --port <n> port to serve on (default: first free from 4810)
28 --no-open don't open a window; just print the URL
29 --browser open in the default browser instead of a Chrome app window
30 --no-watch don't rebuild on file changes
31 --stop stop the player running for this project
32 --status print whether a player is running for this project
33 -h, --help show this help
34​
35player keys:
36 space play/pause · ←/→ frame · shift+←/→ 1s · home/end · i/o in/out · x clear range
37 c copy timecode · shift+c copy range · g go to time · l loop · m mute · f fullscreen · ? help
38 s screenshot this frame · n screenshots & notes panel
39 click a sound effect to set its volume · drag or ↑/↓ moves it between tracks (up to 3) · a hides tracks
40​
41feedback for agents:
42 Screenshots and notes are kept in <project>/.rive-preview/. "Send to agent" writes a
43 bundle to .rive-preview/feedback/<time>/ (feedback.md + PNGs). To be woken by it, an
44 agent runs \`rive-video-preview wait-feedback .\` as a background command: it exits
45 with the feedback as soon as the user sends it (see wait-feedback --help). The
46 player shows the user whether an agent is listening. The MCP server serves the
47 same bundles through get_feedback / wait_for_feedback. Register it with, e.g.:
48 claude mcp add rive-preview -- rive-video-preview mcp
49`;
50​
51function parseArgs(argv) {
52 const opts = { open: true, watch: true, browser: false };
53 const positional = [];
54 for (let i = 0; i < argv.length; i++) {
55 const a = argv[i];
56 const [flag, inline] = a.startsWith('--') && a.includes('=') ? [a.slice(0, a.indexOf('=')), a.slice(a.indexOf('=') + 1)] : [a, undefined];
57 const value = () => {
58 if (inline !== undefined) return inline;
59 const v = argv[++i];
60 if (v === undefined) fail(`${flag} needs a value`);
61 return v;
62 };
63 switch (flag) {
64 case '-h':
65 case '--help':
66 opts.help = true;
67 break;
68 case '--at':
69 opts.at = value();
70 break;
71 case '--artboard':
72 opts.artboard = value();
73 break;
74 case '--animation':
75 opts.animation = value();
76 break;
77 case '--port':
78 opts.port = Number(value());
79 break;
80 case '--no-open':
81 opts.open = false;
82 break;
83 case '--browser':
84 opts.browser = true;
85 break;
86 case '--no-watch':
87 opts.watch = false;
88 break;
89 case '--stop':
90 opts.stop = true;
91 break;
92 case '--status':
93 opts.status = true;
94 break;
95 default:
96 if (a.startsWith('-')) fail(`unknown option ${a}`);
97 positional.push(a);
98 }
99 }
100 if (positional.length > 1) fail('expected at most one project dir or .riv file');
101 opts.target = path.resolve(positional[0] ?? '.');
102 return opts;
104​
105function fail(msg) {
106 console.error(`rive-video-preview: ${msg}\nrun with --help for usage`);
107 process.exit(1);
109​
110function log(msg) {
111 const ts = new Date().toTimeString().slice(0, 8);
112 for (const line of String(msg).split('\n')) console.log(`[${ts}] ${line}`);
114​
115async function freePort(start) {
116 const net = await import('node:net');
117 for (let p = start; p < start + 100; p++) {
118 const ok = await new Promise((resolve) => {
119 const s = net.createServer();
120 s.once('error', () => resolve(false));
121 s.listen(p, '127.0.0.1', () => s.close(() => resolve(true)));
122 });
123 if (ok) return p;
124 }
125 throw new Error('no free port found');
127​
128// ---------------------------------------------------------------- window
129function playerUrl(port, opts) {
130 const params = new URLSearchParams();
131 if (opts.at) params.set('t', opts.at);
132 if (opts.artboard) params.set('artboard', opts.artboard);
133 if (opts.animation) params.set('animation', opts.animation);
134 const hash = params.toString();
135 return `http://127.0.0.1:${port}/${hash ? '#' + hash : ''}`;
137​
138function windowSize(meta, opts) {
139 const abs = meta?.artboards || [];
140 const ab = abs.find((a) => a.name === opts.artboard) || abs.find((a) => a.name === meta?.defaultArtboard) || abs[0];
141 const aspect = ab && ab.width > 0 && ab.height > 0 ? ab.width / ab.height : 16 / 9;
142 const chrome = 168; // timeline + controls
143 let stageH = aspect < 1 ? 820 : Math.round(1120 / aspect);
144 let w = Math.round(stageH * aspect);
145 if (w < 720) w = 720;
146 return { w, h: stageH + chrome };
148​
149function chromePath() {
150 const candidates = [
151 '/Applications/Google Chrome.app',
152 path.join(os.homedir(), 'Applications/Google Chrome.app'),
153 '/Applications/Chromium.app',
154 '/Applications/Brave Browser.app',
155 '/Applications/Microsoft Edge.app',
156 ];
157 return candidates.find((c) => existsSync(c));
159​
160function openWindow(url, size, opts) {
161 const detached = { stdio: 'ignore', detached: true };
162 if (process.platform === 'darwin') {
163 const chrome = !opts.browser && chromePath();
164 if (chrome) {
165 spawn('open', ['-na', chrome, '--args', `--app=${url}`, `--window-size=${size.w},${size.h}`], detached).unref();
166 } else {
167 spawn('open', [url], detached).unref();
168 }
169 } else if (process.platform === 'win32') {
170 spawn('cmd', ['/c', 'start', '', url], detached).unref();
171 } else {
172 spawn('xdg-open', [url], detached).unref();
173 }
175​
176// ---------------------------------------------------------------- main
177async function main() {
178 if (process.argv[2] === 'mcp') {
179 const { runMcp } = await import('../lib/mcp.mjs');
180 return runMcp(process.argv.slice(3));
181 }
182 if (process.argv[2] === 'wait-feedback') {
183 const { runWaitFeedback } = await import('../lib/wait-feedback.mjs');
184 return runWaitFeedback(process.argv.slice(3));
185 }
186 const opts = parseArgs(process.argv.slice(2));
187 if (opts.help) {
188 process.stdout.write(HELP);
189 return;
190 }
191 if (!existsSync(opts.target)) fail(`${opts.target} does not exist`);
192​
193 let mode;
194 if (statSync(opts.target).isDirectory()) {
195 if (!existsSync(path.join(opts.target, 'rive.yaml'))) fail(`${opts.target} has no rive.yaml — not a Rive CLI project`);
196 mode = 'project';
197 } else if (opts.target.endsWith('.riv')) {
198 mode = 'riv';
199 } else {
200 fail('expected a Rive project directory or a .riv file');
201 }
202​
203 const running = await findRunning(opts.target);
204​
205 if (opts.status) {
206 console.log(running ? `running at http://127.0.0.1:${running.port}/ (pid ${running.pid}, ${running.clients} window(s) open)` : 'not running');
207 return;
208 }
209 if (opts.stop) {
210 if (!running) return console.log('not running');
211 process.kill(running.pid, 'SIGTERM');
212 console.log(`stopped player (pid ${running.pid})`);
213 return;
214 }
215​
216 if (running) {
217 const url = playerUrl(running.port, opts);
218 if (running.clients > 0 && opts.at) {
219 await fetch(`http://127.0.0.1:${running.port}/api/seek`, { method: 'POST', body: JSON.stringify({ at: opts.at }) });
220 console.log(`player already running at http://127.0.0.1:${running.port}/ — jumped to ${opts.at}`);
221 } else if (running.clients > 0) {
222 console.log(`player already running at http://127.0.0.1:${running.port}/ (${running.clients} window(s) open; it live-reloads on save)`);
223 } else {
224 if (opts.open) openWindow(url, { w: 900, h: 900 }, opts);
225 console.log(`player already running; opened ${url}`);
226 }
227 return;
228 }
229​
230 if (mode === 'project' && !spawnSyncCheck()) fail('the `rive` CLI was not found on PATH');
231​
232 const server = new PreviewServer({ target: opts.target, mode, watch: opts.watch, log });
233 const port = opts.port || (await freePort(4810));
234 await server.listen(port);
235 mkdirSync(STATE_DIR, { recursive: true });
236 const sf = stateFile(opts.target);
237 writeFileSync(sf, JSON.stringify({ pid: process.pid, port, target: opts.target }));
238 const cleanup = () => {
239 try {
240 const st = JSON.parse(readFileSync(sf, 'utf8'));
241 if (st.pid === process.pid) rmSync(sf, { force: true });
242 } catch {}
243 };
244 process.on('exit', cleanup);
245 for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => process.exit(0));
246​
247 const url = playerUrl(port, opts);
248 log(`rive-video-preview: ${opts.target}`);
249 await server.rebuild('initial');
250 server.startWatching();
251 log(`player: ${url}`);
252 if (opts.open) openWindow(url, windowSize(server.meta, opts), opts);
253 log(opts.watch ? 'watching for changes (Ctrl-C to stop)' : 'serving (Ctrl-C to stop)');
255​
256function spawnSyncCheck() {
257 const dirs = (process.env.PATH || '').split(path.delimiter);
258 return dirs.some((d) => existsSync(path.join(d, process.platform === 'win32' ? 'rive.exe' : 'rive')));
260​
261main().catch((err) => {
262 console.error(err?.stack || String(err));
263 process.exit(1);
264});