@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
mjs 128 lines 4.39 KB
Raw
1 #!/usr/bin/env node
2 // Renders a story page frame by frame: every animation is paused and seeked, so output is deterministic.
3 // Usage: capture.mjs <story.html> <outDir> [--at <seconds,...>] [--fps 30]
4 import * as NodeModule from "node:module";
5 import * as NodeFS from "node:fs";
6 import * as NodeHttp from "node:http";
7
8 import { findChrome } from "./chrome.mjs";
9 import * as NodePath from "node:path";
10 import * as NodeURL from "node:url";
11
12 const args = process.argv.slice(2);
13 const flag = (name) => {
14 const i = args.indexOf(name);
15 if (i === -1) return undefined;
16 const [, value] = args.splice(i, 2);
17 return value;
18 };
19 const at = flag("--at");
20 const fps = Number(flag("--fps") ?? 30);
21 const [html, outDir] = args;
22 if (!html || !outDir) {
23 console.error("usage: capture.mjs <story.html> <outDir> [--at <seconds,...>] [--fps 30]");
24 process.exit(2);
25 }
26
27 const repoRoot = NodePath.resolve(
28 NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)),
29 "../../../..",
30 );
31 const loadChromium = () => {
32 const require = NodeModule.createRequire(NodePath.join(repoRoot, "scripts/package.json"));
33 try {
34 return require("playwright-core").chromium;
35 } catch {
36 console.error(`playwright-core is not installed in ${repoRoot}. Run \`vp i\` there first.`);
37 process.exit(1);
38 }
39 };
40 const chromium = loadChromium();
41
42 // Served over HTTP, not file://, so the story can reach into its beat iframes.
43 const TYPES = {
44 ".html": "text/html",
45 ".js": "text/javascript",
46 ".css": "text/css",
47 ".svg": "image/svg+xml",
48 ".png": "image/png",
49 ".woff2": "font/woff2",
50 ".woff": "font/woff",
51 ".ttf": "font/ttf",
52 };
53 const root = NodePath.dirname(NodePath.resolve(html));
54 const server = NodeHttp.createServer((req, res) => {
55 const file = NodePath.join(root, decodeURIComponent(new URL(req.url, "http://x").pathname));
56 if (!file.startsWith(root)) return void res.writeHead(403).end();
57 NodeFS.readFile(file, (error, body) => {
58 if (error) return void res.writeHead(404).end();
59 res
60 .writeHead(200, {
61 "content-type": TYPES[NodePath.extname(file)] ?? "application/octet-stream",
62 })
63 .end(body);
64 });
65 }).listen(0, "127.0.0.1");
66 await new Promise((resolve) => server.once("listening", resolve));
67
68 // Every animation in the story and in its beat iframes, paused at `ms`.
69 const seek = (ms) => {
70 const docs = [
71 document,
72 ...[...document.querySelectorAll("iframe")].map((f) => f.contentDocument).filter(Boolean),
73 ];
74 for (const doc of docs)
75 for (const a of doc.getAnimations()) {
76 a.pause();
77 a.currentTime = ms;
78 }
79 };
80
81 if (!at) NodeFS.rmSync(outDir, { recursive: true, force: true });
82 NodeFS.mkdirSync(outDir, { recursive: true });
83 const browser = await chromium.launch({
84 executablePath: findChrome(chromium),
85 args: ["--no-sandbox"],
86 });
87 try {
88 const page = await browser.newPage({
89 viewport: { width: 1600, height: 900 },
90 deviceScaleFactor: 1.2,
91 });
92 const errors = [];
93 page.on("pageerror", (e) => errors.push(e.message));
94 page.on("requestfailed", (r) => errors.push(`failed to load ${r.url()}`));
95 page.on("response", (r) => r.status() >= 400 && errors.push(`${r.status()} ${r.url()}`));
96 await page.goto(`http://127.0.0.1:${server.address().port}/${NodePath.basename(html)}`);
97 await page.evaluate(async () => {
98 await window.Kit?.ready;
99 await document.fonts.ready;
100 window.setup?.();
101 });
102 await page.evaluate(
103 ([seekSource]) => {
104 window.__seek = new Function(`return ${seekSource}`)();
105 window.__seek((window.layoutTime ?? 15) * 1000);
106 window.placeCursor?.();
107 },
108 [seek.toString()],
109 );
110 if (errors.length) throw new Error(`story page errors:\n${errors.join("\n")}`);
111 const total = await page.evaluate(() => window.totalDuration);
112 if (!total) throw new Error("story must set window.totalDuration (Kit.timeline does this)");
113
114 const indices = at
115 ? at.split(",").map((s) => Math.min(Math.round(Number(s) * fps), Math.round(total * fps) - 1))
116 : [...Array(Math.round(total * fps)).keys()];
117 for (const i of indices) {
118 await page.evaluate((t) => window.__seek((window.warp ? window.warp(t) : t) * 1000), i / fps);
119 const name = at
120 ? `t${(i / fps).toFixed(2).padStart(6, "0")}.png`
121 : `f${String(i).padStart(4, "0")}.png`;
122 await page.screenshot({ path: NodePath.join(outDir, name) });
123 }
124 console.log(`${indices.length} frame(s) -> ${outDir} (video length ${total.toFixed(1)}s)`);
125 } finally {
126 await browser.close();
127 server.close();
128 }