Skip to content

Code-first video & image, rendered natively on WebGPU.

bulk misc

okanasl5c257c236709
diff --git a/.agent/rules/general-information.md b/.agent/rules/general-information.md
index 120d426a..aabb5564 100644
--- a/.agent/rules/general-information.md
+++ b/.agent/rules/general-information.md
@@ -26,7 +26,7 @@ Gitframes is a code-first video engine on native WebGPU (Dawn) in Node, with no
- `packages/gitframes`: the public SDK. `Composition`, `Layer.*`, `LayerAnimation`, `Signal`, effect classes (`src/effects/classes.ts`), `FontManager`, `renderFrameGrid` (`src/renderer/framegrid.ts`). `src/index.ts` is large and is the export surface.
- `packages/compositions`: layout (Yoga, `utils/layout/resolve-layout.ts`), program schema (`program/schema.ts`), animation and evaluator, `to-virtual-media`.
-- `packages/webgpu-renderers`: WGSL shaders, 2D/3D pipelines, Slug text, audio DSP, ChartGPU bridge.
+- `packages/webgpu-renderers`: WGSL shaders, 2D/3D pipelines, Slug text, audio DSP.
- `packages/renderer`: headless Node renderer (Dawn, WebCodecs/mediabunny, `HeadlessMediaRenderer`).
- `packages/core`: shared types, `Effect` base, signals. Other packages: `renderers`, `media`, `node-sdk` (node authoring: `shared/` + `renderer/`), `server-utils`, `client-utils`, `tensor-webgpu`, `vision`, `tsconfig`.
- `nodes/node-*` (59): one VFX/audio/layout node each. Layout: `src/shared/` (config and schema), `src/renderers/` (WebGPU), `src/index.ts`. Only `node-compositor` has a `SKILL.md`; update it when Compositor behavior changes (`packages/compositions/src/program/skillmd-check.test.ts` guards it).
diff --git a/.changeset/chart-d3.md b/.changeset/chart-d3.md
new file mode 100644
index 00000000..c7bedecd
--- /dev/null
+++ b/.changeset/chart-d3.md
@@ -0,0 +1,7 @@
+---
+"gitframes": minor
+---
+
+`Layer.chart` is rebuilt on d3 and no longer depends on `chartgpu`, which removes about 130 MB from every install. Charts are now ordinary nodes: bars are boxes, lines, areas and slices are path shapes, and labels are text in the composition's own fonts. They support line, area, bar (grouped or stacked), scatter, candlestick, pie and donut, with a built-in reveal (`animate: { start, duration, stagger, ease }`).
+
+Breaking for chart users: `Layer.chart` takes the new `ChartOptions` (`type`, `series`/`data`, `categories`, `xAxis`/`yAxis`, `legend`, `valueLabels`, …) instead of ChartGPU options, and returns a box. The `"chart"` node kind, the `ChartGPUOptions`/`Chart*Schema` exports, the `progress`/`drawProgress`/`chartProgress` animatable props and `LayerAnimation.drawProgress()`/`chartProgress()` are removed.
diff --git a/.changeset/launch-docs-sharp.md b/.changeset/launch-docs-sharp.md
new file mode 100644
index 00000000..a711c5ee
--- /dev/null
+++ b/.changeset/launch-docs-sharp.md
@@ -0,0 +1,5 @@
+---
+"gitframes": patch
+---
+
+Require `sharp` ^0.35.0, so fresh installs no longer pull the libvips/libheif versions flagged by `npm audit`. Fix the README samples that did not compile against the published types (quickstart animation, 3D camera orbit and carousel, `ColorBalance`). The setup skill's `tsconfig.json` now sets `"types": ["node"]` so `typecheck` passes on TypeScript 6+, and its `package.json` also denies the `esbuild` install script that `tsx` brings in, so installs finish without warnings.
diff --git a/.changeset/preview-review.md b/.changeset/preview-review.md
new file mode 100644
index 00000000..79494f54
--- /dev/null
+++ b/.changeset/preview-review.md
@@ -0,0 +1,7 @@
+---
+"gitframes": minor
+---
+
+Add a live preview before rendering. `startPreview({ entry, export })` (also from `gitframes/preview`) serves a localhost player for a composition, with the mixed soundtrack and a timeline with the audio waveform. The page loads the module that builds the composition, bundled with the engine by esbuild, and renders every frame with WebGPU in the browser, so nothing is streamed from the server. The server serves that bundle, the project's files (by absolute path, with byte ranges for video), and the soundtrack mixed by the export engine. Extruded 3D text (`Layer3D.extrudedText`) renders in the browser too. Glyph outlines used to go through skia's path `simplify`, which is Node-only; without skia they are read from fontkit, and overlapping contours (common in variable fonts) are sorted into outlines and holes by winding. Node output is unchanged. Build-time Node code in the composition (`node:path`, `import.meta.url`, synchronous `fs` reads) runs in the browser through shims. Playback never drops frames. Frames are rendered ahead, in order, into a buffer on the GPU and shown at the film's frame rate, on the soundtrack's clock. Playback starts once 3 seconds (or the rest of the film) are ready, and holds with a spinner to refill whenever rendering falls behind. The timeline shows the buffered range. `startPreview` returns a session (`url`, `close()`, `closed`). The server shuts itself down a few seconds after the last tab closes (`idleCloseMs`). A reload doesn't trigger this. Each project gets a fixed port, so running the preview again replaces the running one and an open tab reloads into the new version by itself. No Electron. `esbuild` is a new dependency.
+
+Rendering consecutive frames is about 3× faster. The compositor no longer re-hashes every keyframe on each frame. `renderFrame` also accepts a stable `renderId`, which lets compiled timelines be reused between frames as `renderVideo` already does, and `format: "rgba"`, which returns raw pixels and skips PNG encoding. The new `renderAudio()` returns the composition's mixed soundtrack as PCM. The compositor also reuses the previous frame's layout when no layout input changed (the tree, the viewport, media sizes, and animated `width`, `height`, `gap`, `padding`, `fontSize` and `letterSpacing`). Before, it re-ran Yoga over the whole film's tree on every frame.
diff --git a/.changeset/vision-frame-cache.md b/.changeset/vision-frame-cache.md
new file mode 100644
index 00000000..edd81281
--- /dev/null
+++ b/.changeset/vision-frame-cache.md
@@ -0,0 +1,7 @@
+---
+"gitframes": minor
+---
+
+Vision effects are faster, in export and in the preview. The matte modes (`matte`, `mask`, `crop`) composite on the GPU: only the 8-bit mask is uploaded, instead of building the cut-out at full resolution on the CPU. That CPU path also kept a new full-frame texture for every frame rendered; the new path keeps two per node. Vision results are cached per source frame, keyed by node, source and inference settings, with run-length-encoded masks, so replays, scrubbing back and later renders in the same process skip inference. A frame found in the cache is cut out from its own pixels, without the usual one-frame delay. The preview analyses frames ahead of the playhead while paused, so tracked shots play at full frame rate. Background keying (`keyBackground`) runs about 10× faster with the same output: flood fills use typed-array queues and a foreground map computed once, and the edge blur reads memory in order. The preview page is served cross-origin isolated, so onnxruntime-web runs its CPU operations on several threads.
+
+Vision effects also run in the browser preview, on onnxruntime-web with WebGPU. `@gitframes/vision` adds `setDefaultSessionProvider()`, which the player uses to switch to that runtime. Cached models are read asynchronously. The texture cache now holds evicted textures until the frame being recorded has been submitted, which fixes "Destroyed texture used in a submit" when a frame's recording spans a mid-frame GPU readback. Its pruning also evicts the least recently used textures first, as documented.
diff --git a/.gitignore b/.gitignore
index 54f51051..26c1ffa5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -52,6 +52,7 @@ assets/soundfonts/
# ...except the brand assets and showcase stills the README links to, and the plugin icon
!assets/brand/*.png
!assets/showcase/*.jpg
+!assets/showcase/*.png
!plugins/gitframes/assets/*.png
# Vision Tracking Caches
diff --git a/README.md b/README.md
index bbe03bc2..194ffb91 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,7 @@
> **⚠️ Beta:** gitframes is under active development. APIs may change between releases and some features may be incomplete or unstable.
-Gitframes is built for coding agents. It packs the work people usually split across three desktop apps (Photoshop-grade compositing and VFX, After Effects-style motion, typography and keyframing, and Blender-style 3D scenes, cameras and models) into one npm package whose engine is about 10 MB. Your agent writes a TypeScript composition, checks frames, and renders an MP4, and nobody has to install or license a multi-gigabyte creative suite.
+Gitframes is built for coding agents. It packs the work people usually split across three desktop apps (Photoshop-grade compositing and VFX, After Effects-style motion, typography and keyframing, and Blender-style 3D scenes, cameras and models) into one lightweight npm package. Your agent writes a TypeScript composition, checks frames, and renders an MP4, and nobody has to install or license a multi-gigabyte creative suite.
**Code-first video as pure software engineering** — no headless browser, no DOM reflow, no screenshot pipeline.
Renders directly on GPU hardware via Dawn / WebGPU / Metal / Vulkan in Node.js and modern WebGPU browsers.
@@ -73,9 +73,10 @@ Every frame of these films is rendered by gitframes from TypeScript in [`example
- [2. Photoshop-Grade WebGPU 2D VFX](#2-photoshop-grade-webgpu-2d-vfx-50-shaders)
- [3. Unified 3D Scene Graph, Camera & Mesh Shading](#3-unified-3d-scene-graph-camera--mesh-shading)
- [4. Audio Layers, Procedural SFX & Reactive Signals](#4-audio-layers-procedural-sfx--reactive-signals)
- - [5. WebGPU ChartGPU Bridge](#5-webgpu-chartgpu-bridge)
+ - [5. Animated Charts](#5-animated-charts)
- [6. On-Device Vision & Tracking](#6-on-device-vision--tracking)
- [7. Headless Conformance & FrameGrid Testing](#7-headless-conformance--framegrid-testing)
+ - [8. Live Preview in the Browser](#8-live-preview-in-the-browser)
- [Monorepo Architecture](#monorepo-architecture)
- [Quickstart Guide](#quickstart-guide)
- [1. Basic Composition & Kinetic Auto-Layout](#1-basic-composition--kinetic-auto-layout)
@@ -127,7 +128,7 @@ Developers generating video programmatically commonly weigh **Remotion** (React/
| **3D Graphics & Depth** | **Native 3D scene graph** — LookAt/Turntable camera, multiplane, skinning (OBJ/FBX/glTF), SSAO, PCSS, DoF | None built-in (embed Three.js/Fiber inside React DOM) | Minimal 2.5D layers; no unified mesh pipeline |
| **Motion Blur & Physics** | Physical 180° shutter velocity buffers in MRT + closed-form spring kinematics | CSS transitions / JS interpolation; synthetic blur hacks | Frame interpolation or manual multipass |
| **Audio Engine & DSP** | Native audio DSP & procedural SFX (multi-track mixing, beat grids, reactive signals) | `<Audio>` playback; basic volume curves | Basic static audio playback |
-| **Live Charting & Telemetry** | **ChartGPU bridge** — GPU-rendered line, bar, OHLC, area charts into GPU textures | DOM chart libraries (Recharts, Chart.js) | Custom canvas draw operations |
+| **Charts & Data Viz** | **`Layer.chart`** — line, area, bar, scatter, candlestick, pie and donut charts built from native vector nodes, with staggered reveal animations | DOM chart libraries (Recharts, Chart.js) | Custom canvas draw operations |
| **AI & Computer Vision** | **On-device ONNX vision** — COCO-80 detection + instance masks (RTMDet-Ins), COCO-17 pose (RTMO), person mattes (Selfie Segmenter); WebGPU tensor conditioning (Canny, depth-to-normals, optical flow, deflicker) | External pre-rendered assets; no native GPU tensor conditioning | External pre-rendered assets |
| **Headless Verification** | **FrameGrid contact sheets**, single-frame snapshots, Skia MSE pixel-invariant assertions | Playwright/Puppeteer visual snapshots | Manual frame inspection / canvas diffing |
| **Docker / Cloud Portability** | **Compact** (~500 MB slim image with native GPU/Vulkan drivers) | **Heavy** (~2–3 GB with Chromium, fonts, X11/Mesa) | Moderate container size |
@@ -164,10 +165,29 @@ A comprehensive suite of professional image/video shader nodes in [`nodes/`](nod
- **Multi-track mixing** — master tracks headlessly with `mixAudioTracks` and `encodeStereoWav`.
- **Reactive signals** — drive transforms, scale, borders, or shader uniforms from tempo signals (`Signal.builder`) or audio analysis.
-### 5. WebGPU ChartGPU Bridge
-Through native [`ChartGPU`](packages/webgpu-renderers/src/chartgpu/chartgpu-bridge.ts) integration:
-- Render real-time financial, scientific, and metric charts (line, bar, OHLC/candlestick, area, scatter) directly onto offscreen GPU textures.
-- Composite live charts into 3D perspective cards, flex layouts, or HUD overlays — no canvas DOM elements.
+### 5. Animated Charts
+[`Layer.chart`](packages/gitframes/src/chart.ts) builds line, area, bar (grouped or stacked), scatter, candlestick, pie and donut charts. [d3](https://d3js.org) computes the scales, ticks and geometry; every bar, line, slice and label is an ordinary box, path or text node:
+- Labels use the composition's registered fonts and the same GPU text renderer as the rest of the film.
+- A built-in reveal draws lines on, grows bars from the baseline and staggers points and slices (`animate: { start, duration, stagger, ease }`, or `animate: false`).
+- The chart is one box, so it positions, animates, grades and tilts into 3D like any other layer.
+
+```typescript
+Layer.chart(
+ {
+ type: "bar",
+ width: 900,
+ height: 480,
+ categories: ["Q1", "Q2", "Q3", "Q4"],
+ series: [
+ { name: "Revenue", data: [12, 19, 24, 31] },
+ { name: "Costs", data: [8, 11, 13, 15] },
+ ],
+ yAxis: { format: "$,.0f" },
+ animate: { start: 10, duration: 30 },
+ },
+ { position: "absolute", x: 120, y: 200 },
+);
+```
### 6. On-Device Vision & Tracking
[`@gitframes/vision`](packages/vision) runs ONNX models via `onnxruntime-node` (CPU) or `onnxruntime-web` (WebGPU) and wires every result into the same reactive signal surface the rest of Gitframes consumes.
@@ -239,6 +259,24 @@ Project normalized landmarks to screen space with a configurable camera FOV, the
- **Pixel-sampling invariant assertions** — test compositions in Vitest with `skia-canvas` to verify shader math, font coverage, and Mean Squared Error (MSE) temporal deltas.
- **FrameGrid contact sheets** — `comp.renderFrameGrid(...)` outputs sequential-frame contact sheets for instant review of easing, kinetic type, and transitions.
+### 8. Live Preview in the Browser
+- **Runs your composition, not a video** — `startPreview({ entry, export })` serves a localhost WebGPU player that loads the composition's own module and renders every frame live in the browser. Nothing is streamed: the server only hands over the bundle, the project's assets, and the soundtrack mixed by the export engine.
+- **Timeline, waveform & frame stepping** — play/pause, scrub, step frame by frame, and read resolution, FPS, duration, and audio status at a glance.
+- **One stable URL per project** — the port is derived from the working directory, so re-running the preview replaces the running server and any open tab reloads into the new version by itself. Close the tab and the server shuts down about five seconds later.
+
+```typescript
+import { startPreview } from "gitframes";
+
+const session = await startPreview(
+ { entry: new URL("./film.ts", import.meta.url), export: "buildFilm" },
+ { title: "gitframes film" },
+);
+console.log(`Preview at ${session.url}`);
+await session.closed; // serves until its tab closes or a newer preview takes over
+```
+
+<img src="assets/showcase/prw-ss.png" alt="gitframes live preview player: WebGPU rendering, waveform timeline, frame stepping, and audio status at 127.0.0.1:41133" width="100%">
+
---
## Monorepo Architecture
@@ -352,8 +390,13 @@ import { Composition, Layer, Layer3D, CameraAnimation, Light } from "gitframes";
const comp = new Composition({ width: 1920, height: 1080, fps: 60, durationFrames: 300 });
// 1. LookAt 3D camera with a continuous orbit
-const cameraAnim = CameraAnimation.create()
- .orbit({ fromAzimuth: -30, toAzimuth: 30, elevation: 15, radius: 1200, start: 0, end: 300 });
+const cameraAnim = CameraAnimation.camera().orbit({
+ azimuth: { from: -30, to: 30 },
+ elevation: { from: 15, to: 15 },
+ radius: { to: 1200 },
+ start: 0,
+ end: 300,
+});
comp.add(
Layer.camera({ x: 960, y: 540, z: -1000, targetX: 960, targetY: 540, targetZ: 0 }).animate(cameraAnim)
@@ -379,7 +422,7 @@ comp.add(
comp.add(
Layer3D.carousel({
radius: 400,
- cards: [
+ items: [
Layer.box({ width: 280, height: 180, background: "#1e293b", borderRadius: 16 }),
Layer.box({ width: 280, height: 180, background: "#334155", borderRadius: 16 }),
Layer.box({ width: 280, height: 180, background: "#0f172a", borderRadius: 16 }),
@@ -438,7 +481,12 @@ const comp = new Composition({ width: 1920, height: 1080, fps: 60 });
// Whole-composition cinematic grade + film emulsion
comp.apply(new Vignette({ strength: 0.28, radius: 0.85 }));
comp.apply(new FilmGrain({ strength: 0.06, size: 1.5, animated: true }));
-comp.apply(new ColorBalance({ shadows: [0, 2, 6], highlights: [4, 1, -2] }));
+comp.apply(
+ new ColorBalance({
+ shadows: { cyanRed: 0, magentaGreen: 2, yellowBlue: 6 },
+ highlights: { cyanRed: 4, magentaGreen: 1, yellowBlue: -2 },
+ }),
+);
```
---
diff --git a/apps/renderer-service/package.json b/apps/renderer-service/package.json
index e881ff4f..46e2279f 100644
--- a/apps/renderer-service/package.json
+++ b/apps/renderer-service/package.json
@@ -25,7 +25,7 @@
"@gitframes/server-utils": "workspace:*",
"@hono/node-server": "^1.19.11",
"dotenv": "^17.0.1",
- "hono": "^4.12.5",
+ "hono": "^4.13.7",
"inversify": "^7.11.0",
"reflect-metadata": "^0.2.2",
"zod": "^4.3.6"
diff --git a/assets/showcase/prw-ss.png b/assets/showcase/prw-ss.png
new file mode 100644
index 00000000..6e13e0ab
Binary files /dev/null and b/assets/showcase/prw-ss.png differ
diff --git a/examples/19_gitframes_film/src/render.ts b/examples/19_gitframes_film/src/render.ts
index 405e421f..bcbefeb2 100644
--- a/examples/19_gitframes_film/src/render.ts
+++ b/examples/19_gitframes_film/src/render.ts
@@ -1,16 +1,29 @@
/**
* pnpm render → output/gitframes-film.mp4 (30 s, 1080p30, with score)
+ * pnpm render preview → live player on localhost; stops when its tab closes
* pnpm render frames 0 45 90 → output/frames/f0000.png … for quick visual checks
*/
import fs from "node:fs/promises";
import path from "node:path";
-import { HeadlessMediaRenderer } from "gitframes";
+import { HeadlessMediaRenderer, startPreview } from "gitframes";
import { buildFilm } from "./film.js";
import { HERE } from "./theme.js";
const OUT = path.resolve(HERE, "../output");
const [mode = "video", ...args] = process.argv.slice(2);
+if (mode === "preview") {
+ // The page runs film.ts itself and renders with WebGPU in the browser.
+ const session = await startPreview(
+ { entry: new URL("./film.ts", import.meta.url), export: "buildFilm" },
+ { title: "gitframes film" },
+ );
+ console.log(`Preview at ${session.url}`);
+ // Serves until its tab closes, or the next `pnpm render preview` takes over.
+ await session.closed;
+ process.exit(0);
+}
+
const film = await buildFilm();
await fs.mkdir(OUT, { recursive: true });
diff --git a/examples/21_full_circle/src/render.ts b/examples/21_full_circle/src/render.ts
index a2fb8869..db083579 100644
--- a/examples/21_full_circle/src/render.ts
+++ b/examples/21_full_circle/src/render.ts
@@ -1,16 +1,29 @@
/**
* pnpm render → output/full-circle.mp4 (with score)
+ * pnpm render preview → live player on localhost; stops when its tab closes
* pnpm render frames 0 140 637 → output/frames/f0000.png … for visual checks
* pnpm render sheet 0 1080 24 → output/frames/ every 24th frame from 0 to 1080
*/
import fs from "node:fs/promises";
import path from "node:path";
-import { HeadlessMediaRenderer } from "gitframes";
+import { HeadlessMediaRenderer, startPreview } from "gitframes";
import { buildFilm } from "./film.js";
import { OUTPUT } from "./paths.js";
const [mode = "video", ...args] = process.argv.slice(2);
+if (mode === "preview") {
+ // The page runs film.ts itself and renders with WebGPU in the browser.
+ const session = await startPreview(
+ { entry: new URL("./film.ts", import.meta.url), export: "buildFilm" },
+ { title: "Full circle" },
+ );
+ console.log(`Preview at ${session.url}`);
+ // Serves until its tab closes, or the next `pnpm render preview` takes over.
+ await session.closed;
+ process.exit(0);
+}
+
const film = await buildFilm();
await fs.mkdir(path.join(OUTPUT, "frames"), { recursive: true });
diff --git a/examples/22_gitframes_launch/src/render.ts b/examples/22_gitframes_launch/src/render.ts
index 16cfbb20..b929a882 100644
--- a/examples/22_gitframes_launch/src/render.ts
+++ b/examples/22_gitframes_launch/src/render.ts
@@ -1,16 +1,29 @@
/**
* pnpm render → output/gitframes-launch.mp4 (with the score) + QA report; exits 1 if QA fails
+ * pnpm render preview → live player on localhost; stops when its tab closes, re-running replaces it
* pnpm render frames 0 80 320 → output/frames/f0000.png … for visual checks
* pnpm render sheet 0 320 20 → every 20th frame from 0 to 320, plus a contact sheet
* pnpm render:src … → any of the above, run on the engine's source (no package builds)
*/
import fs from "node:fs/promises";
import path from "node:path";
-import { formatQaReport, HeadlessMediaRenderer } from "gitframes";
+import { formatQaReport, HeadlessMediaRenderer, startPreview } from "gitframes";
import { buildFilm } from "./film.js";
import { OUTPUT } from "./paths.js";
const [mode = "video", ...args] = process.argv.slice(2);
+
+if (mode === "preview") {
+ // The page runs film.ts itself and renders with WebGPU in the browser.
+ const session = await startPreview(
+ { entry: new URL("./film.ts", import.meta.url), export: "buildFilm" },
+ { title: "gitframes launch" },
+ );
+ console.log(`Preview at ${session.url}`);
+ // Serves until its tab closes, or the next `pnpm render preview` takes over.
+ await session.closed;
+ process.exit(0);
+}
const film = await buildFilm();
await fs.mkdir(path.join(OUTPUT, "frames"), { recursive: true });
diff --git a/examples/23_data_story/README.md b/examples/23_data_story/README.md
new file mode 100644
index 00000000..b617f363
--- /dev/null
+++ b/examples/23_data_story/README.md
@@ -0,0 +1,85 @@
+# 23 — Data Story
+
+A 30-second report where the data keeps moving. Revenue bars morph through three fiscal years, a
+live feed slides a ten-second window over a stream of users, a donut and its share bars re-divide
+month by month as search overtakes direct, the newest candle ticks while the price rolls, and the
+outro's bars never sit still. Every chart is `Layer.chart`; counters roll on gsap-baked odometers;
+accents breathe on signals. Light theme: the tokens are in `theme.ts` (page, text, muted, chart text
+and grid, data hues, and darker text variants of cyan and green for numbers on white).
+
+Nothing to download or generate: fonts come from the repo's `assets/fonts`.
+
+```bash
+pnpm render grid # output/grid.png, a 16-frame contact sheet
+pnpm render frames 230 400
+pnpm render # output/data-story.mp4
+pnpm render:src grid # same, on the engine's source (no package builds)
+pnpm test
+```
+
+## Changing data: `morph` (`morph.ts`)
+
+Build the same chart once per data state, with the same options and **fixed axes** (`yAxis.min` /
+`max`), so every state has the same node ids. `morph` takes the first state's tree and, wherever a
+node's `x`, `y`, `width`, `height` or `rotation` differs between states, keys it to ease from one
+state to the next. The keys go after the chart's own reveal; overlapping them is an error.
+
+```ts
+const view = morph(
+ YEARS.map((y) => ({ at: y.at, node: yearView(y) })), // Layer.chart + overlays per year
+ { duration: 30, ease: "power3.inOut" },
+);
+```
+
+Overlays built from chart geometry ride along for free: the revenue ring around the best bar, the
+live feed's halo and level line, the market's ring around the newest candle. A layer with its own
+`startFrame` is keyed on its own clock.
+
+Two things can't be keyframed, so they're built differently:
+
+- **Lines** (`live.ts`): a path's `d` doesn't animate, so the live line is drawn with rotated boxes
+ between the chart's points (`segment()`), which morph like everything else.
+- **Donut slices** (`donut.ts`): each slice is the same full circle, stroked and trimmed to its share.
+ `trimStart`/`trimEnd` animate, so slices grow, shrink and slide round the ring. Round caps with a
+ one-stroke gap keep the joins clean.
+- **Numbers** don't change text; they roll on odometers.
+
+## Scenes
+
+| Scene | Data | What moves |
+| --- | --- | --- |
+| Revenue | three fiscal years, 8 months × revenue/costs | bars, best-month ring and caption; the year rolls 2023 → 2025 |
+| Live | a stream of users, 10-sample window, a new sample every 11 frames | points, segment line, halo, level line; the latest value rolls; a LIVE dot blinks |
+| Mix | four months of channel shares | donut slices and share bars re-divide; the search share and month roll |
+| Market | 24 sessions, then 7 live ticks on the newest candle | candles stream in; the live candle, its ring and the price line move; the price rolls |
+| Outro | 9 states of a 16-bar level meter | every bar |
+
+## gsap and signals
+
+**gsap** (`motion.ts`). gitframes evaluates every `ease` string with gsap, so single moves are plain
+keyframes. gsap is used directly where one tween isn't enough:
+
+- `odometer()` rolls a "0…9" strip per digit in a clipped cell. The first value rolls in with a
+ stagger (rightmost digits spin longest); every later value rolls each strip to its new digit. It's
+ one gsap timeline, scrubbed frame by frame and written out as keyframes by `bake()`.
+- `envelope()` is `gsap.parseEase`, so signal curves use the same easing vocabulary.
+
+**Signals** (`signals.ts`) are per-frame functions registered on the composition by name and bound
+with `LayerAnimation.signal(prop, name, { multiplier, offset })`:
+
+| Signal | Shape | Drives |
+| --- | --- | --- |
+| `pulse` | 1 on every beat (100 BPM), decaying along `expo.out` | the rings, the live halo, the LIVE dot |
+| `breathe` | 0 → 1 → 0 over four beats, `sine.inOut` | the backdrop glows |
+
+Pass the signal's **name** to `.signal()` after `comp.addSignal`, not the signal object, and remember
+signal functions see the **composition** frame.
+
+## Layout
+
+- `timeline.ts` — scene windows in frames; `film.ts` mounts them over the backdrop.
+- `scenes/` — title, revenue, live, mix, market, outro. Each scene is a full-frame box on its own
+ clock (children key from frame 0) that lifts out over its last ten frames (`ui.ts`).
+- `film.test.ts` — the spec validates, scenes tile the film, signals are bound by registered name,
+ `morph` keys only what changes and respects layer clocks, the revenue bars, live window and donut
+ settle on their last states, and the rendered August bar grows 2023 → 2025 by the right ratio.
diff --git a/examples/23_data_story/package.json b/examples/23_data_story/package.json
new file mode 100644
index 00000000..3ea52c31
--- /dev/null
+++ b/examples/23_data_story/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "@gitframes/example-23-data-story",
+ "version": "1.4.3",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "render": "tsx src/render.ts",
+ "render:src": "tsx --tsconfig tsconfig.dev.json --conditions=development src/render.ts",
+ "test": "vitest run",
+ "typecheck": "tsc --noEmit -p ."
+ },
+ "dependencies": {
+ "gitframes": "workspace:*",
+ "gsap": "^3.15.0"
+ },
+ "devDependencies": {
+ "@gitframes/tsconfig": "workspace:*",
+ "@types/node": "^24.1.0",
+ "skia-canvas": "^3.0.8",
+ "tsx": "^4.20.3",
+ "typescript": "^5.8.3",
+ "vitest": "^4.1.5"
+ }
+}
diff --git a/examples/23_data_story/src/chart-geometry.ts b/examples/23_data_story/src/chart-geometry.ts
new file mode 100644
index 00000000..1fffbf8b
--- /dev/null
+++ b/examples/23_data_story/src/chart-geometry.ts
@@ -0,0 +1,41 @@
+/**
+ * Layer.chart returns ordinary nodes with predictable ids
+ * (`<id>-bar-<series>-<i>`, `<id>-point-<series>-<i>`, `<id>-slice-<i>`), so a
+ * scene can read a bar's or point's geometry and anchor its own overlays to it.
+ */
+import type { LayoutNode } from "gitframes";
+
+export interface Box {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+type Node = LayoutNode & Partial<Box> & { children?: LayoutNode[] };
+
+export function findNode(root: LayoutNode, id: string): Node {
+ const walk = (n: Node): Node | undefined => {
+ if (n.id === id) return n;
+ for (const c of n.children ?? []) {
+ const hit = walk(c as Node);
+ if (hit) return hit;
+ }
+ return undefined;
+ };
+ const hit = walk(root as Node);
+ if (!hit) throw new Error(`No node "${id}" in chart "${root.id}"`);
+ return hit;
+}
+
+/** A chart child's box in the chart's parent coordinates. */
+export function boxOf(chart: LayoutNode, id: string): Box {
+ const c = chart as Node;
+ const n = findNode(chart, id);
+ return {
+ x: (c.x ?? 0) + (n.x ?? 0),
+ y: (c.y ?? 0) + (n.y ?? 0),
+ width: Number(n.width ?? 0),
+ height: Number(n.height ?? 0),
+ };
+}
diff --git a/examples/23_data_story/src/donut.ts b/examples/23_data_story/src/donut.ts
new file mode 100644
index 00000000..10bde237
--- /dev/null
+++ b/examples/23_data_story/src/donut.ts
@@ -0,0 +1,103 @@
+/**
+ * A donut whose shares change over time. Each slice is the same full circle,
+ * stroked and trimmed to its share: `trimStart`/`trimEnd` are animatable where
+ * a path's `d` isn't, so slices can grow, shrink and slide around the ring.
+ * Round caps with a gap of one stroke width between slices keep the joins clean.
+ */
+import { Layer, LayerAnimation, type LayoutNode } from "gitframes";
+
+export interface DonutSlice {
+ label: string;
+ color: string;
+}
+
+export interface DonutOptions {
+ id: string;
+ /** Centre in scene coordinates. */
+ cx: number;
+ cy: number;
+ radius: number;
+ thickness: number;
+ slices: readonly DonutSlice[];
+ /** Shares per state (any scale; each row is normalised), and when each state starts. */
+ states: readonly { at: number; values: readonly number[] }[];
+ /** Frames the first sweep takes; later changes take `change`. */
+ reveal?: number;
+ change?: number;
+}
+
+export function liveDonut(o: DonutOptions): LayoutNode {
+ const r = o.radius;
+ const t = o.thickness;
+ const m = t / 2 + 4;
+ const size = 2 * (r + m);
+ const c = r + m;
+ // One full circle from 12 o'clock, clockwise.
+ const d = `M${c},${c - r} A${r},${r} 0 1 1 ${c},${c + r} A${r},${r} 0 1 1 ${c},${c - r}`;
+ const gap = t / (2 * Math.PI * r) + 0.004;
+ const reveal = o.reveal ?? 30;
+ const change = o.change ?? 24;
+
+ const spans = o.states.map(({ values }) => {
+ const total = values.reduce((a, b) => a + b, 0) || 1;
+ let cum = 0;
+ return values.map((v) => {
+ const start = cum / total;
+ cum += v;
+ return {
+ start: start + gap / 2,
+ end: Math.max(start + gap / 2 + 0.001, cum / total - gap / 2),
+ };
+ });
+ });
+
+ const slices = o.slices.map((slice, i) => {
+ const first = spans[0][i];
+ const at = o.states[0].at + i * 4;
+ const anim = LayerAnimation.create()
+ .keys("trimStart", [
+ [at, first.start],
+ ...o.states
+ .slice(1)
+ .flatMap((s, k) => [
+ [s.at, spans[k][i].start] as const,
+ [s.at + change, spans[k + 1][i].start, "power3.inOut"] as const,
+ ]),
+ ])
+ .keys("trimEnd", [
+ [at, first.start],
+ [at + reveal, first.end, "expo.out"],
+ ...o.states
+ .slice(1)
+ .flatMap((s, k) => [
+ [s.at, spans[k][i].end] as const,
+ [s.at + change, spans[k + 1][i].end, "power3.inOut"] as const,
+ ]),
+ ]);
+ return Layer.shape("path", {
+ id: `${o.id}-slice-${i}`,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: size,
+ height: size,
+ d,
+ fillType: "none",
+ strokeColor: slice.color,
+ strokeWidth: t,
+ strokeLineCap: "round",
+ trimStart: first.start,
+ trimEnd: first.start,
+ }).animate(anim);
+ });
+
+ return Layer.box({
+ id: o.id,
+ position: "absolute",
+ x: o.cx - c,
+ y: o.cy - c,
+ width: size,
+ height: size,
+ children: slices,
+ });
+}
diff --git a/examples/23_data_story/src/film.test.ts b/examples/23_data_story/src/film.test.ts
new file mode 100644
index 00000000..7dcfbe5c
--- /dev/null
+++ b/examples/23_data_story/src/film.test.ts
@@ -0,0 +1,171 @@
+import { CompositorProgramSchema, type LayoutNode } from "gitframes";
+import { Canvas, loadImage } from "skia-canvas";
+import { describe, expect, it } from "vitest";
+import { boxOf, findNode } from "./chart-geometry.js";
+import { buildFilm } from "./film.js";
+import { morph } from "./morph.js";
+import { liveScene, userStream, WINDOW } from "./scenes/live.js";
+import { MONTHLY, mixScene } from "./scenes/mix.js";
+import { revenueScene, YEARS } from "./scenes/revenue.js";
+import { BREATHE, breatheAt, PULSE, pulseAt } from "./signals.js";
+import { BEAT } from "./theme.js";
+import { DURATION, REVENUE, SCENES } from "./timeline.js";
+
+type Tracked = LayoutNode & { children?: LayoutNode[] };
+
+function walk(nodes: LayoutNode[], visit: (n: Tracked) => void): void {
+ for (const n of nodes as Tracked[]) {
+ visit(n);
+ walk(n.children ?? [], visit);
+ }
+}
+
+/** The value a keyframe track settles on. */
+function lastKey(node: LayoutNode, prop: string): number | undefined {
+ const track = node.animation?.tracks.find((t) => t.prop === prop);
+ return track?.keyframes[track.keyframes.length - 1]?.value as
+ | number
+ | undefined;
+}
+
+describe("timeline", () => {
+ it("scenes tile the film with no gaps or overlaps", () => {
+ expect(SCENES[0].from).toBe(0);
+ for (let i = 1; i < SCENES.length; i++)
+ expect(SCENES[i].from).toBe(SCENES[i - 1].to);
+ expect(SCENES[SCENES.length - 1].to).toBe(DURATION);
+ });
+});
+
+describe("signals", () => {
+ it("pulse hits 1 on every beat and decays along expo.out", () => {
+ for (const beat of [0, BEAT, 7 * BEAT])
+ expect(pulseAt(beat)).toBeCloseTo(1, 5);
+ expect(pulseAt(Math.round(BEAT / 2))).toBeLessThan(0.1);
+ });
+
+ it("breathe stays in 0..1 and swells over four beats", () => {
+ const values = Array.from({ length: BEAT * 4 }, (_, f) => breatheAt(f));
+ expect(Math.min(...values)).toBeGreaterThanOrEqual(0);
+ expect(Math.max(...values)).toBeLessThanOrEqual(1);
+ expect(breatheAt(BEAT * 2)).toBeCloseTo(1, 5);
+ });
+});
+
+describe("morph", () => {
+ it("keys only what changes, and settles on the last state", () => {
+ const box = (h: number) =>
+ ({
+ id: "b",
+ kind: "box",
+ x: 0,
+ y: 100 - h,
+ width: 10,
+ height: h,
+ }) as LayoutNode;
+ const node = morph([
+ { at: 0, node: box(10) },
+ { at: 30, node: box(40) },
+ { at: 60, node: box(20) },
+ ]);
+ const props = node.animation?.tracks.map((t) => t.prop).sort();
+ expect(props).toEqual(["height", "y"]);
+ expect(lastKey(node, "height")).toBe(20);
+ expect(lastKey(node, "y")).toBe(80);
+ });
+
+ it("keys layers with their own startFrame on their own clock", () => {
+ const ring = (y: number) =>
+ ({ id: "r", kind: "box", y, startFrame: 40 }) as LayoutNode;
+ const node = morph([
+ { at: 0, node: ring(10) },
+ { at: 70, node: ring(50) },
+ ]);
+ const frames = node.animation?.tracks[0]?.keyframes.map((k) => k.frame);
+ expect(frames).toEqual([30, 54]);
+ });
+
+ it("eases each revenue bar to its final year", () => {
+ const scene = revenueScene();
+ const final = YEARS[YEARS.length - 1];
+ const tallest = findNode(scene, "revenue-chart-bar-0-7");
+ const ratio = (lastKey(tallest, "height") ?? 0) / (final.revenue[7] ?? 1);
+ // Same axis every year, so height is proportional to value.
+ const jan = findNode(scene, "revenue-chart-bar-0-0");
+ expect((lastKey(jan, "height") ?? 0) / final.revenue[0]).toBeCloseTo(
+ ratio,
+ 1,
+ );
+ });
+
+ it("slides the live window one sample per tick", () => {
+ const values = userStream();
+ const scene = liveScene();
+ const now = findNode(scene, `live-chart-point-0-${WINDOW - 1}`);
+ const y = now.animation?.tracks.find((t) => t.prop === "y");
+ // One change per tick, two keys each.
+ expect(y?.keyframes.length).toBeGreaterThanOrEqual(
+ 2 * (values.length - WINDOW) - 2,
+ );
+ });
+
+ it("re-trims the donut to each month's shares", () => {
+ const scene = mixScene();
+ const search = findNode(scene, "mix-donut-slice-1");
+ const end = lastKey(search, "trimEnd") ?? 0;
+ const start = lastKey(search, "trimStart") ?? 0;
+ const last = MONTHLY[MONTHLY.length - 1].shares;
+ const share = last[1] / last.reduce((a, b) => a + b, 0);
+ expect(end - start).toBeGreaterThan(share - 0.06);
+ expect(end - start).toBeLessThan(share);
+ });
+});
+
+describe("film", () => {
+ it("builds a spec its schema accepts", async () => {
+ const film = await buildFilm();
+ const result = CompositorProgramSchema.safeParse(film.toSpec());
+ expect(result.success ? [] : result.error.issues.slice(0, 5)).toEqual([]);
+ });
+
+ it("binds signals by registered name", async () => {
+ const film = await buildFilm();
+ expect(Object.keys(film.signals).sort()).toEqual([BREATHE, PULSE].sort());
+ const bound: string[] = [];
+ walk(film.toSpec().layout as LayoutNode[], (n) => {
+ for (const t of n.animation?.tracks ?? []) {
+ if (t.source?.type === "signal") bound.push(t.source.inputHandleId);
+ }
+ });
+ expect(bound.length).toBeGreaterThan(0);
+ for (const name of bound) expect(film.signals).toHaveProperty(name);
+ });
+
+ it("renders the revenue bars at each year's height", async () => {
+ const film = await buildFilm();
+ const scene = revenueScene();
+ const bar = boxOf(
+ findNode(scene, "revenue-chart"),
+ "revenue-chart-bar-0-7",
+ );
+ const ink = async (frame: number) => {
+ const img = await loadImage(await film.renderFrame({ frame }));
+ const canvas = new Canvas(img.width, img.height);
+ const ctx = canvas.getContext("2d");
+ ctx.drawImage(img, 0, 0);
+ // Count bar-coloured pixels up the bar's centre column.
+ const x = Math.round(bar.x + bar.width / 2);
+ let n = 0;
+ for (let y = 260; y < 990; y++) {
+ const [r, g, b] = ctx.getImageData(x, y, 1, 1).data;
+ if (b > 200 && r > 70 && r < 130 && g < 130) n++;
+ }
+ return n;
+ };
+ const y2023 = await ink(REVENUE.from + YEARS[1].at - 2);
+ const y2025 = await ink(REVENUE.from + YEARS[2].at + 40);
+ // Aug revenue grew from $21k to $36k on a fixed axis.
+ expect(y2025 / y2023).toBeGreaterThan(1.5);
+ expect(y2025 / y2023).toBeLessThan(1.9);
+ }, 120_000);
+});
diff --git a/examples/23_data_story/src/film.ts b/examples/23_data_story/src/film.ts
new file mode 100644
index 00000000..50a2ce63
--- /dev/null
+++ b/examples/23_data_story/src/film.ts
@@ -0,0 +1,51 @@
+import { Composition, Layer, LayerAnimation } from "gitframes";
+import { liveScene } from "./scenes/live.js";
+import { marketScene } from "./scenes/market.js";
+import { mixScene } from "./scenes/mix.js";
+import { outroScene } from "./scenes/outro.js";
+import { revenueScene } from "./scenes/revenue.js";
+import { titleScene } from "./scenes/title.js";
+import { registerSignals } from "./signals.js";
+import { ACCENT, BG, FPS, H, registerFonts, W } from "./theme.js";
+import { DURATION } from "./timeline.js";
+import { backdrop } from "./ui.js";
+
+export async function buildFilm(): Promise<Composition> {
+ await registerFonts();
+ const film = new Composition({
+ width: W,
+ height: H,
+ fps: FPS,
+ durationMs: (DURATION / FPS) * 1000,
+ backgroundColor: BG,
+ });
+ // Signals first: layers bind to them by name.
+ registerSignals(film);
+
+ film.add([
+ ...backdrop(),
+ titleScene(),
+ revenueScene(),
+ liveScene(),
+ mixScene(),
+ marketScene(),
+ outroScene(),
+ // A hairline progress bar along the bottom edge, linear over the whole film.
+ Layer.box({
+ id: "progress",
+ position: "absolute",
+ x: 0,
+ y: H - 4,
+ width: 0,
+ height: 4,
+ background: ACCENT,
+ }).animate(
+ LayerAnimation.create().fromTo("width", 0, W, {
+ start: 0,
+ end: DURATION,
+ ease: "none",
+ }),
+ ),
+ ]);
+ return film;
+}
diff --git a/examples/23_data_story/src/gsap.ts b/examples/23_data_story/src/gsap.ts
new file mode 100644
index 00000000..f7b45a05
--- /dev/null
+++ b/examples/23_data_story/src/gsap.ts
@@ -0,0 +1,9 @@
+/**
+ * gsap ships CommonJS to Node, where its default import is the module object
+ * and the gsap instance sits on `.default`. Resolve it once here.
+ */
+import gsapModule from "gsap";
+
+type Gsap = typeof gsapModule;
+export const gsap: Gsap =
+ (gsapModule as Gsap & { default?: Gsap }).default ?? gsapModule;
diff --git a/examples/23_data_story/src/morph.ts b/examples/23_data_story/src/morph.ts
new file mode 100644
index 00000000..3fad9ed6
--- /dev/null
+++ b/examples/23_data_story/src/morph.ts
@@ -0,0 +1,117 @@
+/**
+ * Data that changes over time. Build the same chart once per data state (same
+ * options, same fixed axes, so every state has the same node ids), then
+ * `morph` the states into one tree: wherever a node's geometry differs between
+ * states, it gets keyframes that ease it from one state to the next.
+ *
+ * Bars, candles, points, rings and labels morph this way. Path `d` and text
+ * content can't be keyframed, so changing lines are drawn as segment boxes
+ * (`segments`) and changing numbers roll on odometers.
+ */
+import { LayerAnimation, type LayoutNode } from "gitframes";
+
+export interface DataState {
+ /** Scene frame the morph into this state starts (ignored for the first state). */
+ at: number;
+ node: LayoutNode;
+}
+
+export interface MorphOptions {
+ /** Frames each transition takes. */
+ duration?: number;
+ ease?: string;
+ props?: readonly string[];
+}
+
+type Node = LayoutNode & Record<string, unknown> & { children?: LayoutNode[] };
+
+const GEOMETRY = ["x", "y", "width", "height", "rotation"] as const;
+
+function index(root: LayoutNode): Map<string, Node> {
+ const out = new Map<string, Node>();
+ const walk = (n: Node) => {
+ out.set(n.id, n);
+ for (const c of n.children ?? []) walk(c as Node);
+ };
+ walk(root as Node);
+ return out;
+}
+
+/** Appends keyframes to `prop`'s keyframe track, creating it if needed. */
+export function appendKeys(
+ node: LayoutNode,
+ prop: string,
+ keys: readonly (readonly [number, number, string?])[],
+): void {
+ const fresh = LayerAnimation.create().keys(prop as never, keys).tracks[0];
+ const tracks = node.animation?.tracks ?? [];
+ const existing = tracks.find(
+ (t) => t.prop === prop && (!t.source || t.source.type === "keyframe"),
+ );
+ if (!existing) {
+ node.animation = { ...node.animation, tracks: [...tracks, fresh] };
+ return;
+ }
+ const last = existing.keyframes[existing.keyframes.length - 1]?.frame ?? -1;
+ const first = fresh.keyframes[0]?.frame ?? 0;
+ if (first <= last)
+ throw new Error(
+ `morph: "${node.id}" ${prop} keys at ${first} overlap its animation (ends ${last})`,
+ );
+ existing.keyframes.push(
+ ...fresh.keyframes.map((k, i) => ({
+ ...k,
+ id: `morph_${prop}_${i}_f${k.frame}`,
+ })),
+ );
+}
+
+/** The first state's tree, keyed to ease through every later state. */
+export function morph(
+ states: readonly DataState[],
+ options: MorphOptions = {},
+): LayoutNode {
+ const duration = options.duration ?? 24;
+ const ease = options.ease ?? "power3.inOut";
+ const props = options.props ?? GEOMETRY;
+ const [base, ...rest] = states;
+ const maps = states.map((s) => index(s.node));
+
+ for (const [id, node] of maps[0]) {
+ // A layer with its own startFrame reads keyframes on its own clock.
+ const clock = typeof node.startFrame === "number" ? node.startFrame : 0;
+ for (const prop of props) {
+ const values = maps.map((m) => m.get(id)?.[prop]);
+ if (!values.every((v) => typeof v === "number")) continue;
+ const nums = values as number[];
+ if (nums.every((v) => Math.abs(v - nums[0]) < 0.01)) continue;
+ const keys: [number, number, string?][] = [];
+ rest.forEach((state, k) => {
+ const from = nums[k];
+ const to = nums[k + 1];
+ if (Math.abs(to - from) < 0.01) return;
+ // Back-to-back changes: the last one already ends where this one starts.
+ const at = state.at - clock;
+ if (keys[keys.length - 1]?.[0] !== at) keys.push([at, from]);
+ keys.push([at + duration, to, ease]);
+ });
+ if (keys.length) appendKeys(node, prop, keys);
+ }
+ }
+ return base.node;
+}
+
+/** A straight line between two points, as a rotated box: something `morph` can move. */
+export function segment(
+ from: { x: number; y: number },
+ to: { x: number; y: number },
+ thickness: number,
+): { x: number; y: number; width: number; height: number; rotation: number } {
+ return {
+ x: from.x,
+ y: from.y - thickness / 2,
+ width: Math.hypot(to.x - from.x, to.y - from.y),
+ height: thickness,
+ rotation: (Math.atan2(to.y - from.y, to.x - from.x) * 180) / Math.PI,
+ };
+}
diff --git a/examples/23_data_story/src/motion.ts b/examples/23_data_story/src/motion.ts
new file mode 100644
index 00000000..f36b4c13
--- /dev/null
+++ b/examples/23_data_story/src/motion.ts
@@ -0,0 +1,213 @@
+/**
+ * Motion helpers built on gsap.
+ *
+ * gitframes already evaluates every `ease` string with gsap, so single moves
+ * are plain `fromTo` calls. gsap is used directly for what keyframes can't say
+ * on their own:
+ *
+ * - `bake` scrubs a paused gsap timeline frame by frame and writes the values
+ * out as keyframes, so multi-step choreography (staggers, overlaps, labels)
+ * is authored the gsap way and still renders deterministically.
+ * - `envelope` turns a gsap ease into a curve that signal functions can sample.
+ */
+import { Layer, LayerAnimation, type LayoutNode } from "gitframes";
+import { gsap } from "./gsap.js";
+import { FPS, MONO, TEXT } from "./theme.js";
+
+/** A gsap ease as a plain (t: 0..1) => value function. */
+export const envelope = (ease: string): ((t: number) => number) =>
+ gsap.parseEase(ease);
+
+/** Frame → gsap timeline seconds. */
+export const sec = (frames: number) => frames / FPS;
+
+/**
+ * Samples `props` of `target` while scrubbing `tl` from frame `from` to `to`
+ * and returns the samples as keyframes. Sampling every `step` frames keeps a
+ * long move under the 128-keyframes-per-layer budget; the engine interpolates
+ * linearly in between.
+ */
+export function bake<T extends Record<string, number>>(
+ tl: gsap.core.Timeline,
+ target: T,
+ props: readonly (keyof T & string)[],
+ from: number,
+ to: number,
+ step = 2,
+): LayerAnimation {
+ const keys: Record<string, [number, number, string][]> = {};
+ for (const p of props) keys[p] = [];
+ for (let f = from; ; f = Math.min(to, f + step)) {
+ tl.totalTime(sec(f), false);
+ for (const p of props) keys[p].push([f, target[p], "none"]);
+ if (f >= to) break;
+ }
+ const anim = LayerAnimation.create();
+ for (const p of props) anim.keys(p as never, dropFlatRuns(keys[p]));
+ return anim;
+}
+
+/** Collapses runs of equal samples to their ends: holds cost two keys, not twenty. */
+function dropFlatRuns(
+ keys: [number, number, string][],
+): [number, number, string][] {
+ return keys.filter(
+ (k, i) =>
+ i === 0 ||
+ i === keys.length - 1 ||
+ Math.abs(k[1] - keys[i - 1][1]) > 1e-3 ||
+ Math.abs(k[1] - keys[i + 1][1]) > 1e-3,
+ );
+}
+
+export interface OdometerOptions {
+ id: string;
+ x: number;
+ y: number;
+ /** Glyph size; each digit cell is `size * 0.62` wide and `size * 1.2` tall. */
+ size: number;
+ /** Frame the first value starts rolling in, relative to the parent scene (string form). */
+ at?: number;
+ color?: string;
+ /** Frames between neighbouring digits starting their first roll. */
+ stagger?: number;
+ /** Frames the first roll takes. */
+ duration?: number;
+ /** Frames each later change takes. */
+ change?: number;
+}
+
+/** A value the counter rolls to at frame `at`. Every value has the same length. */
+export interface OdometerState {
+ at: number;
+ value: string;
+}
+
+/**
+ * A rolling-digit counter. Each digit is a "0…9" strip in a clipped cell. The
+ * first value rolls in from zero with a stagger, so the rightmost digits spin
+ * longest the way a mechanical counter settles; every later value rolls each
+ * strip straight to its new digit. It is all one gsap timeline, and `bake`
+ * writes it out as keyframes. Non-digit characters ("+", "%", "$", ",", ".")
+ * sit still.
+ */
+export function odometer(
+ values: string | readonly OdometerState[],
+ o: OdometerOptions,
+): LayoutNode {
+ const states =
+ typeof values === "string" ? [{ at: o.at ?? 0, value: values }] : values;
+ const first = states[0];
+ const cellW = Math.round(o.size * 0.62);
+ const cellH = Math.round(o.size * 1.2);
+ const color = o.color ?? TEXT;
+ const stagger = o.stagger ?? 3;
+ const duration = o.duration ?? 36;
+ const change = o.change ?? 14;
+ const width = first.value.length;
+ if (states.some((s) => s.value.length !== width))
+ throw new Error(`odometer ${o.id}: every value needs ${width} characters`);
+
+ const digits = [...first.value]
+ .map((ch, i) => ({ ch, i }))
+ .filter((d) => /\d/.test(d.ch));
+ const strips = digits.map(() => ({ y: 0 }));
+ const tl = gsap.timeline({ paused: true });
+ let end = first.at;
+ digits.forEach((d, k) => {
+ // Extra turns on the first roll: two for the rightmost digits, fewer to the left.
+ const band = Math.max(0, 2 - Math.floor((digits.length - 1 - k) / 2)) * 10;
+ const roll = duration + k * stagger;
+ tl.to(
+ strips[k],
+ {
+ y: -(Number(d.ch) + band) * cellH,
+ duration: sec(roll),
+ ease: "power4.out",
+ },
+ sec(first.at + k * stagger),
+ );
+ end = Math.max(end, first.at + k * stagger + roll);
+ for (const state of states.slice(1)) {
+ const digit = Number(state.value[d.i]);
+ tl.to(
+ strips[k],
+ {
+ y: -(digit + band) * cellH,
+ duration: sec(change),
+ ease: "power3.out",
+ },
+ sec(state.at),
+ );
+ end = Math.max(end, state.at + change);
+ }
+ });
+
+ const reel = Array.from({ length: 30 }, (_, n) => n % 10).join("\n");
+ const children = [...first.value].map((ch, i) => {
+ const cell = {
+ position: "absolute" as const,
+ x: i * cellW,
+ y: 0,
+ width: cellW,
+ height: cellH,
+ };
+ const k = digits.findIndex((d) => d.i === i);
+ if (k < 0) {
+ return Layer.text(ch, {
+ id: `${o.id}-glyph-${i}`,
+ ...cell,
+ fontFamily: MONO,
+ fontSize: o.size,
+ fontWeight: 700,
+ lineHeight: cellH,
+ fill: color,
+ align: "center",
+ verticalAlign: "middle",
+ });
+ }
+ return Layer.box({
+ id: `${o.id}-cell-${i}`,
+ ...cell,
+ overflow: "hidden",
+ children: [
+ Layer.text(reel, {
+ id: `${o.id}-strip-${i}`,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: cellW,
+ height: cellH * 30,
+ fontFamily: MONO,
+ fontSize: o.size,
+ fontWeight: 700,
+ lineHeight: cellH,
+ fill: color,
+ align: "center",
+ }).animate(bake(tl, strips[k], ["y"], Math.max(0, first.at - 1), end)),
+ ],
+ });
+ });
+
+ return Layer.box({
+ id: o.id,
+ position: "absolute",
+ x: o.x,
+ y: o.y,
+ width: cellW * width,
+ height: cellH,
+ children,
+ }).animate(
+ LayerAnimation.create()
+ .fromTo("opacity", 0, 1, {
+ start: Math.max(0, first.at - 8),
+ end: first.at + 2,
+ ease: "power2.out",
+ })
+ .fromTo("y", o.y + 24, o.y, {
+ start: Math.max(0, first.at - 8),
+ end: first.at + 10,
+ ease: "expo.out",
+ }),
+ );
+}
diff --git a/examples/23_data_story/src/render.ts b/examples/23_data_story/src/render.ts
new file mode 100644
index 00000000..46e9baf6
--- /dev/null
+++ b/examples/23_data_story/src/render.ts
@@ -0,0 +1,67 @@
+/**
+ * pnpm render → output/data-story.mp4
+ * pnpm render frames 60 180 → output/frames/f0060.png …
+ * pnpm render grid → output/grid.png, a contact sheet of the whole film
+ * pnpm render preview → live player on localhost; stops when its tab closes, re-running replaces it
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { HeadlessMediaRenderer, startPreview } from "gitframes";
+import { buildFilm } from "./film.js";
+import { OUTPUT } from "./theme.js";
+import { DURATION } from "./timeline.js";
+
+const [mode = "video", ...args] = process.argv.slice(2);
+
+if (mode === "preview") {
+ // The page runs film.ts itself and renders with WebGPU in the browser.
+ const session = await startPreview(
+ { entry: new URL("./film.ts", import.meta.url), export: "buildFilm" },
+ { title: "Data story" },
+ );
+ console.log(`Preview at ${session.url}`);
+ // Serves until its tab closes, or the next `pnpm render preview` takes over.
+ await session.closed;
+ process.exit(0);
+}
+const film = await buildFilm();
+await fs.mkdir(path.join(OUTPUT, "frames"), { recursive: true });
+
+if (mode === "frames") {
+ const renderer = new HeadlessMediaRenderer();
+ for (const frame of args.map(Number)) {
+ const file = path.join(
+ OUTPUT,
+ "frames",
+ `f${String(frame).padStart(4, "0")}.png`,
+ );
+ await fs.writeFile(file, await film.renderFrame({ frame, renderer }));
+ console.log(file);
+ }
+} else if (mode === "grid") {
+ const frames = Array.from({ length: 16 }, (_, i) =>
+ Math.round((i * (DURATION - 1)) / 15),
+ );
+ const file = path.join(OUTPUT, "grid.png");
+ await fs.writeFile(
+ file,
+ await film.renderFrameGrid({
+ frames,
+ columns: 4,
+ cellWidth: 480,
+ showLabels: true,
+ }),
+ );
+ console.log(file);
+} else {
+ const started = Date.now();
+ const result = await film.renderVideo({
+ outputPath: path.join(OUTPUT, "data-story.mp4"),
+ quality: "high",
+ });
+ await result.cleanup?.().catch(() => {});
+ console.log(
+ `${result.filePath} (${((Date.now() - started) / 1000).toFixed(1)} s)`,
+ );
+}
+process.exit(0);
diff --git a/examples/23_data_story/src/scenes/live.ts b/examples/23_data_story/src/scenes/live.ts
new file mode 100644
index 00000000..1e953851
--- /dev/null
+++ b/examples/23_data_story/src/scenes/live.ts
@@ -0,0 +1,205 @@
+import { Layer, LayerAnimation, type LayoutNode } from "gitframes";
+import { boxOf } from "../chart-geometry.js";
+import { type DataState, morph, segment } from "../morph.js";
+import { odometer } from "../motion.js";
+import { PULSE } from "../signals.js";
+import {
+ CHART_H,
+ CHART_TEXT,
+ CHART_Y,
+ CYAN,
+ CYAN_TEXT,
+ GRID,
+ MARGIN,
+ MONO,
+ RED,
+ SANS,
+ TEXT,
+ W,
+} from "../theme.js";
+import { LIVE } from "../timeline.js";
+import { header, scene } from "../ui.js";
+
+export const WINDOW = 10;
+export const TICKS = 11;
+/** First new sample, and frames between samples. */
+const FIRST_TICK = 48;
+const TICK = 11;
+const LINE = 4;
+
+/** A deterministic stream of concurrent users that trends up with noise. */
+export function userStream(count = WINDOW + TICKS): number[] {
+ let seed = 11;
+ const rand = () => {
+ seed = (seed * 16807) % 2147483647;
+ return seed / 2147483647;
+ };
+ const out: number[] = [];
+ let v = 38_000;
+ for (let i = 0; i < count; i++) {
+ v += (rand() - 0.36) * 7_500;
+ out.push(Math.round(Math.min(66_000, Math.max(33_000, v))));
+ }
+ return out;
+}
+
+const SLOTS = Array.from({ length: WINDOW }, (_, i) =>
+ i === WINDOW - 1 ? "now" : `-${WINDOW - 1 - i}s`,
+);
+
+/** The window of samples visible at state `k`, as points, segments, halo and level line. */
+function windowView(values: number[], k: number): LayoutNode {
+ const chart = Layer.chart(
+ {
+ type: "line",
+ width: W - 2 * MARGIN,
+ height: CHART_H,
+ categories: SLOTS,
+ series: [
+ {
+ name: "Users",
+ data: values.slice(k, k + WINDOW),
+ color: CYAN,
+ strokeWidth: 0,
+ pointRadius: 6,
+ },
+ ],
+ yAxis: {
+ min: 30_000,
+ max: 50_000,
+ format: (v) => `${Number(v) / 1000}k`,
+ ticks: 4,
+ },
+ legend: false,
+ fontFamily: SANS,
+ fontSize: 24,
+ textColor: CHART_TEXT,
+ gridColor: GRID,
+ animate: { start: 8, duration: 18, stagger: 2 },
+ },
+ { id: "live-chart", position: "absolute", x: MARGIN, y: CHART_Y },
+ );
+ const pts = SLOTS.map((_, i) => {
+ const b = boxOf(chart, `live-chart-point-0-${i}`);
+ return { x: b.x + b.width / 2, y: b.y + b.height / 2 };
+ });
+ const last = pts[pts.length - 1];
+ const segs = pts.slice(1).map((p, j) => {
+ const s = segment(pts[j], p, LINE);
+ const node = Layer.box({
+ id: `live-seg-${j}`,
+ position: "absolute",
+ ...s,
+ background: CYAN,
+ borderRadius: LINE / 2,
+ anchorX: 0,
+ anchorY: 0.5,
+ });
+ // The line draws on left to right; only the first state's reveal is used.
+ const at = 10 + j * 2;
+ return node.animate(
+ LayerAnimation.create().fromTo("width", 0, s.width, {
+ start: at,
+ end: at + 5,
+ }),
+ );
+ });
+ return Layer.box({
+ id: "live-view",
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: CHART_Y + CHART_H,
+ children: [
+ // The latest level, across the plot.
+ Layer.box({
+ id: "live-level",
+ position: "absolute",
+ x: pts[0].x,
+ y: last.y - 1,
+ width: last.x - pts[0].x,
+ height: 2,
+ background: "rgba(8, 145, 178, 0.28)",
+ }),
+ chart,
+ ...segs,
+ Layer.shape("circle", {
+ id: "live-halo",
+ position: "absolute",
+ x: last.x - 22,
+ y: last.y - 22,
+ width: 44,
+ height: 44,
+ fillColor: "rgba(34, 211, 238, 0.35)",
+ startFrame: FIRST_TICK - 10,
+ }).animate(
+ LayerAnimation.create().signal("opacity", PULSE, {
+ multiplier: 0.9,
+ offset: 0.1,
+ }),
+ ),
+ ],
+ });
+}
+
+/**
+ * A live feed: a ten-second window over a stream of samples. Every tick the
+ * window slides one sample, and every point, segment, the halo on the newest
+ * sample and the level line ease to the new numbers; the latest value rolls on
+ * an odometer and a LIVE dot blinks on the beat.
+ */
+export function liveScene(): LayoutNode {
+ const values = userStream();
+ const states: DataState[] = Array.from({ length: TICKS + 1 }, (_, k) => ({
+ at: FIRST_TICK + (k - 1) * TICK,
+ node: windowView(values, k),
+ }));
+ const view = morph(states, { duration: 9, ease: "power2.out" });
+
+ const latest = (k: number) => values[k + WINDOW - 1].toLocaleString("en-US");
+ const size = 76;
+ return scene("live", LIVE.from, LIVE.to, [
+ ...header("live", "02 · ACTIVE USERS", "Live, and climbing."),
+ view,
+ odometer(
+ states.map((s, k) => ({ at: k === 0 ? 20 : s.at, value: latest(k) })),
+ {
+ id: "live-readout",
+ x: W - MARGIN - Math.round(size * 0.62) * 6,
+ y: 104,
+ size,
+ color: CYAN_TEXT,
+ change: 9,
+ },
+ ),
+ Layer.shape("circle", {
+ id: "live-dot",
+ position: "absolute",
+ x: W - MARGIN - 150,
+ y: 214,
+ width: 14,
+ height: 14,
+ fillColor: RED,
+ }).animate(
+ LayerAnimation.create().signal("opacity", PULSE, {
+ multiplier: 0.85,
+ offset: 0.15,
+ }),
+ ),
+ Layer.text("LIVE", {
+ id: "live-badge",
+ position: "absolute",
+ x: W - MARGIN - 126,
+ y: 204,
+ width: 126,
+ height: 32,
+ fontFamily: MONO,
+ fontSize: 22,
+ fontWeight: 700,
+ letterSpacing: 4,
+ fill: TEXT,
+ align: "end",
+ }),
+ ]);
+}
diff --git a/examples/23_data_story/src/scenes/market.ts b/examples/23_data_story/src/scenes/market.ts
new file mode 100644
index 00000000..b68e8e19
--- /dev/null
+++ b/examples/23_data_story/src/scenes/market.ts
@@ -0,0 +1,183 @@
+import {
+ type ChartCandle,
+ Layer,
+ LayerAnimation,
+ type LayoutNode,
+} from "gitframes";
+import { boxOf } from "../chart-geometry.js";
+import { morph } from "../morph.js";
+import { odometer } from "../motion.js";
+import {
+ CHART_H,
+ CHART_TEXT,
+ CHART_Y,
+ EASE_IN,
+ GREEN,
+ GREEN_TEXT,
+ GRID,
+ MARGIN,
+ MONO,
+ MUTED,
+ RED,
+ SANS,
+ W,
+} from "../theme.js";
+import { MARKET } from "../timeline.js";
+import { beatRing, header, riseAt, scene } from "../ui.js";
+
+/** 24 sessions of a deterministic random walk that ends on its high. */
+export function sessions(count = 24): ChartCandle[] {
+ let seed = 7;
+ const rand = () => {
+ seed = (seed * 16807) % 2147483647;
+ return seed / 2147483647;
+ };
+ const out: ChartCandle[] = [];
+ let close = 128;
+ for (let i = 0; i < count; i++) {
+ const open = close;
+ const drift = i === count - 1 ? 7 : (rand() - 0.42) * 9;
+ close = Math.round((open + drift) * 100) / 100;
+ out.push({
+ x: `${i + 1}`,
+ open,
+ close,
+ high: Math.max(open, close) + rand() * 3,
+ low: Math.min(open, close) - rand() * 3,
+ });
+ }
+ return out;
+}
+
+/** The live candle's close at each tick after the stream lands. */
+export const TICKS = [0, 1.4, -0.8, 2.1, 1.2, 3.0, 2.2, 3.6];
+const FIRST_TICK = 96;
+const TICK = 10;
+
+/** The session as of one tick: the last candle's close (and high) moved by `delta`. */
+function tickView(base: ChartCandle[], delta: number): LayoutNode {
+ const data = base.map((c, i) => {
+ if (i !== base.length - 1) return c;
+ const close = Math.round((c.close + delta) * 100) / 100;
+ return { ...c, close, high: Math.max(c.high, close + 0.6) };
+ });
+ const chart = Layer.chart(
+ {
+ type: "candlestick",
+ width: W - 2 * MARGIN,
+ height: CHART_H,
+ data,
+ upColor: GREEN,
+ downColor: RED,
+ yAxis: { min: 110, max: 160, format: (v) => `$${v}`, ticks: 5 },
+ xAxis: { show: false },
+ fontFamily: SANS,
+ fontSize: 24,
+ textColor: CHART_TEXT,
+ gridColor: GRID,
+ animate: { start: 10, duration: 10, stagger: 3 },
+ },
+ {
+ id: "market-chart",
+ position: "absolute",
+ x: MARGIN,
+ y: CHART_Y,
+ anchorX: 0.5,
+ anchorY: 1,
+ },
+ ).animate(
+ LayerAnimation.create()
+ .fromTo("scale", 0.94, 1, { start: 0, end: 36, ease: EASE_IN })
+ .fromTo("opacity", 0, 1, { start: 0, end: 12 }),
+ );
+ const last = boxOf(chart, `market-chart-candle-0-${data.length - 1}-body`);
+ const plotLeft = MARGIN + 70;
+ const pad = 10;
+ return Layer.box({
+ id: "market-view",
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: CHART_Y + CHART_H,
+ children: [
+ // The last price, across the plot.
+ Layer.box({
+ id: "market-level",
+ position: "absolute",
+ x: plotLeft,
+ y: last.y - 1,
+ width: last.x - plotLeft,
+ height: 2,
+ background: "rgba(34, 197, 94, 0.35)",
+ startFrame: FIRST_TICK - 8,
+ }),
+ chart,
+ beatRing(
+ "market-ring",
+ last.x - pad,
+ last.y - pad,
+ last.width + 2 * pad,
+ last.height + 2 * pad,
+ FIRST_TICK - 8,
+ GREEN,
+ ),
+ ],
+ });
+}
+
+/**
+ * The session streams in candle by candle, then goes live: every tick the
+ * newest candle's close moves, and its body, wick, ring and the price line
+ * follow while the price rolls on an odometer.
+ */
+export function marketScene(): LayoutNode {
+ const data = sessions();
+ const view = morph(
+ TICKS.map((delta, k) => ({
+ at: FIRST_TICK + (k - 1) * TICK,
+ node: tickView(data, delta),
+ })),
+ { duration: 7, ease: "power2.out" },
+ );
+ const close = data[data.length - 1].close;
+ const size = 76;
+ return scene("market", MARKET.from, MARKET.to, [
+ ...header(
+ "market",
+ "04 · THE MARKET NOTICED",
+ "GFRM is trading at a high.",
+ ),
+ view,
+ odometer(
+ TICKS.map((delta, k) => ({
+ at: k === 0 ? 58 : FIRST_TICK + (k - 1) * TICK,
+ value: `$${(close + delta).toFixed(2)}`,
+ })),
+ {
+ id: "market-price",
+ x: W - MARGIN - Math.round(size * 0.62) * 7,
+ y: 104,
+ size,
+ color: GREEN_TEXT,
+ change: 7,
+ duration: 20,
+ stagger: 2,
+ },
+ ),
+ Layer.text("GFRM · LAST", {
+ id: "market-price-caption",
+ position: "absolute",
+ x: W - MARGIN - 400,
+ y: 204,
+ width: 400,
+ height: 32,
+ fontFamily: MONO,
+ fontSize: 22,
+ fontWeight: 600,
+ letterSpacing: 3,
+ fill: MUTED,
+ align: "end",
+ }).animate(riseAt(60, 204, 16)),
+ ]);
+}
diff --git a/examples/23_data_story/src/scenes/mix.ts b/examples/23_data_story/src/scenes/mix.ts
new file mode 100644
index 00000000..534a1508
--- /dev/null
+++ b/examples/23_data_story/src/scenes/mix.ts
@@ -0,0 +1,157 @@
+import { Layer, type LayoutNode } from "gitframes";
+import { liveDonut } from "../donut.js";
+import { morph } from "../morph.js";
+import { odometer } from "../motion.js";
+import {
+ ACCENT,
+ AMBER,
+ CHART_H,
+ CHART_TEXT,
+ CHART_Y,
+ CYAN,
+ CYAN_TEXT,
+ GRID,
+ MARGIN,
+ MONO,
+ MUTED,
+ PINK,
+ SANS,
+ W,
+} from "../theme.js";
+import { MIX } from "../timeline.js";
+import { header, riseAt, scene } from "../ui.js";
+
+export const CHANNELS = [
+ { label: "Direct", color: ACCENT },
+ { label: "Search", color: CYAN },
+ { label: "Social", color: AMBER },
+ { label: "Email", color: PINK },
+];
+
+/** Share of traffic per channel, month by month: search overtakes direct. */
+export const MONTHLY = [
+ { month: "01", at: 0, shares: [46, 24, 18, 12] },
+ { month: "02", at: 70, shares: [41, 29, 18, 12] },
+ { month: "03", at: 108, shares: [37, 33, 19, 11] },
+ { month: "04", at: 146, shares: [33, 38, 18, 11] },
+];
+
+const DONUT = {
+ cx: MARGIN + 300,
+ cy: CHART_Y + CHART_H / 2 + 10,
+ radius: 230,
+ thickness: 58,
+};
+const BARS_X = MARGIN + 900;
+
+/** One month's share bars; each channel is its own series so it keeps its colour. */
+function sharesView(shares: number[]): LayoutNode {
+ return Layer.chart(
+ {
+ type: "bar",
+ stacked: true,
+ width: W - MARGIN - BARS_X,
+ height: CHART_H,
+ categories: CHANNELS.map((c) => c.label),
+ series: CHANNELS.map((c, i) => ({
+ name: c.label,
+ color: c.color,
+ data: CHANNELS.map((_, j) => (j === i ? shares[i] : 0)),
+ })),
+ yAxis: { min: 0, max: 50, ticks: 5, format: (v) => `${v}%` },
+ legend: false,
+ fontFamily: SANS,
+ fontSize: 24,
+ textColor: CHART_TEXT,
+ gridColor: GRID,
+ cornerRadius: 10,
+ // Stacked series reveal in turn; this one is done by frame 67, before the first change.
+ animate: { start: 16, duration: 16, stagger: 2, ease: "back.out(1.6)" },
+ },
+ { id: "mix-bars", position: "absolute", x: BARS_X, y: CHART_Y },
+ );
+}
+
+/**
+ * Four months of traffic mix. The donut's slices and the share bars ease to
+ * each month's numbers together, the search share rolls in the donut's hole,
+ * and the month counter ticks over.
+ */
+export function mixScene(): LayoutNode {
+ const bars = morph(
+ MONTHLY.map((m) => ({ at: m.at, node: sharesView(m.shares) })),
+ { duration: 22, ease: "power3.inOut" },
+ );
+ const donut = liveDonut({
+ id: "mix-donut",
+ ...DONUT,
+ slices: CHANNELS,
+ states: MONTHLY.map((m) => ({
+ at: m.at === 0 ? 10 : m.at,
+ values: m.shares,
+ })),
+ change: 22,
+ });
+ const shareSize = 92;
+ const searchShare = odometer(
+ MONTHLY.map((m) => ({
+ at: m.at === 0 ? 20 : m.at,
+ value: `${m.shares[1]}%`,
+ })),
+ {
+ id: "mix-search",
+ x: DONUT.cx - (Math.round(shareSize * 0.62) * 3) / 2,
+ y: DONUT.cy - 70,
+ size: shareSize,
+ color: CYAN_TEXT,
+ change: 26,
+ duration: 26,
+ },
+ );
+ const monthSize = 76;
+ return scene("mix", MIX.from, MIX.to, [
+ ...header("mix", "03 · WHERE THEY COME FROM", "Search overtakes direct."),
+ donut,
+ searchShare,
+ Layer.text("SEARCH", {
+ id: "mix-search-label",
+ position: "absolute",
+ x: DONUT.cx - 120,
+ y: DONUT.cy + 44,
+ width: 240,
+ height: 30,
+ fontFamily: MONO,
+ fontSize: 22,
+ fontWeight: 700,
+ letterSpacing: 4,
+ fill: MUTED,
+ align: "center",
+ }).animate(riseAt(24, DONUT.cy + 44, 16)),
+ bars,
+ odometer(
+ MONTHLY.map((m) => ({ at: m.at === 0 ? 14 : m.at, value: m.month })),
+ {
+ id: "mix-month",
+ x: W - MARGIN - Math.round(monthSize * 0.62) * 2,
+ y: 104,
+ size: monthSize,
+ color: CYAN_TEXT,
+ change: 22,
+ },
+ ),
+ Layer.text("MONTH", {
+ id: "mix-month-caption",
+ position: "absolute",
+ x: W - MARGIN - 400,
+ y: 204,
+ width: 400,
+ height: 32,
+ fontFamily: MONO,
+ fontSize: 22,
+ fontWeight: 600,
+ letterSpacing: 3,
+ fill: MUTED,
+ align: "end",
+ }).animate(riseAt(20, 204, 16)),
+ ]);
+}
diff --git a/examples/23_data_story/src/scenes/outro.ts b/examples/23_data_story/src/scenes/outro.ts
new file mode 100644
index 00000000..f2973ea7
--- /dev/null
+++ b/examples/23_data_story/src/scenes/outro.ts
@@ -0,0 +1,89 @@
+import { Layer, type LayoutNode } from "gitframes";
+import { morph } from "../morph.js";
+import {
+ ACCENT,
+ CYAN_TEXT,
+ DISPLAY,
+ H,
+ MARGIN,
+ MONO,
+ TEXT,
+ W,
+} from "../theme.js";
+import { OUTRO } from "../timeline.js";
+import { riseAt, scene } from "../ui.js";
+
+const BARS = 16;
+const STATES = 9;
+const EQ_H = 420;
+
+/** Bar heights at state `k`: two drifting waves, like a level meter. */
+export function levels(k: number): number[] {
+ return Array.from({ length: BARS }, (_, i) => {
+ const v =
+ 0.55 +
+ 0.3 * Math.sin(i * 0.7 + k * 1.3) +
+ 0.15 * Math.sin(i * 1.9 - k * 2.1);
+ return Math.round(Math.max(0.08, Math.min(1, v)) * 100);
+ });
+}
+
+function eqView(k: number): LayoutNode {
+ return Layer.chart(
+ {
+ type: "bar",
+ width: W,
+ height: EQ_H,
+ padding: 0,
+ categories: Array.from({ length: BARS }, (_, i) => `${i}`),
+ series: [{ data: levels(k), color: ACCENT }],
+ yAxis: { min: 0, max: 100, show: false, grid: false },
+ xAxis: { show: false },
+ legend: false,
+ cornerRadius: 10,
+ animate: { start: 0, duration: 12, stagger: 1 },
+ },
+ { id: "outro-eq", position: "absolute", x: 0, y: H - EQ_H, opacity: 0.3 },
+ );
+}
+
+/** The point of the film, over a bar chart whose data never sits still. */
+export function outroScene(): LayoutNode {
+ const eq = morph(
+ Array.from({ length: STATES }, (_, k) => ({
+ at: 30 + (k - 1) * 7,
+ node: eqView(k),
+ })),
+ { duration: 7, ease: "sine.inOut" },
+ );
+ return scene("outro", OUTRO.from, OUTRO.to, [
+ eq,
+ Layer.text("Every bar is a node.", {
+ id: "outro-line",
+ position: "absolute",
+ x: MARGIN,
+ y: 300,
+ width: W - 2 * MARGIN,
+ height: 140,
+ fontFamily: DISPLAY,
+ fontSize: 96,
+ fontWeight: 800,
+ fill: TEXT,
+ align: "center",
+ }).animate(riseAt(6, 300, 60, 30)),
+ Layer.text("Layer.chart · d3 · signals · gsap", {
+ id: "outro-stack",
+ position: "absolute",
+ x: MARGIN,
+ y: 460,
+ width: W - 2 * MARGIN,
+ height: 40,
+ fontFamily: MONO,
+ fontSize: 30,
+ fontWeight: 600,
+ letterSpacing: 2,
+ fill: CYAN_TEXT,
+ align: "center",
+ }).animate(riseAt(18, 460, 30)),
+ ]);
+}
diff --git a/examples/23_data_story/src/scenes/revenue.ts b/examples/23_data_story/src/scenes/revenue.ts
new file mode 100644
index 00000000..afa88139
--- /dev/null
+++ b/examples/23_data_story/src/scenes/revenue.ts
@@ -0,0 +1,148 @@
+import { Layer, type LayoutNode } from "gitframes";
+import { boxOf } from "../chart-geometry.js";
+import { morph } from "../morph.js";
+import { odometer } from "../motion.js";
+import {
+ ACCENT,
+ CHART_H,
+ CHART_TEXT,
+ CHART_Y,
+ CYAN,
+ CYAN_TEXT,
+ GRID,
+ MARGIN,
+ MONO,
+ MUTED,
+ SANS,
+ W,
+} from "../theme.js";
+import { REVENUE } from "../timeline.js";
+import { beatRing, header, note, riseAt, scene } from "../ui.js";
+
+export const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug"];
+
+export interface FiscalYear {
+ year: string;
+ /** Scene frame the chart starts morphing to this year. */
+ at: number;
+ revenue: number[];
+ costs: number[];
+}
+
+export const YEARS: FiscalYear[] = [
+ {
+ year: "2023",
+ at: 0,
+ revenue: [8, 11, 9, 14, 16, 15, 18, 21],
+ costs: [7, 9, 8, 11, 12, 12, 13, 15],
+ },
+ {
+ year: "2024",
+ at: 76,
+ revenue: [10, 15, 12, 18, 22, 20, 25, 29],
+ costs: [8, 10, 9, 13, 12, 15, 14, 17],
+ },
+ {
+ year: "2025",
+ at: 136,
+ revenue: [12, 19, 14, 22, 28, 25, 31, 36],
+ costs: [8, 11, 9, 15, 13, 17, 16, 19],
+ },
+];
+
+/** One year's chart, ring and caption. Every year has the same axes and node ids. */
+function yearView(y: FiscalYear): LayoutNode {
+ const chart = Layer.chart(
+ {
+ type: "bar",
+ width: W - 2 * MARGIN,
+ height: CHART_H,
+ categories: MONTHS,
+ series: [
+ { name: "Revenue", data: y.revenue, color: ACCENT },
+ { name: "Costs", data: y.costs, color: CYAN },
+ ],
+ yAxis: { min: 0, max: 40, format: (v) => `$${v}k`, ticks: 4 },
+ fontFamily: SANS,
+ fontSize: 24,
+ textColor: CHART_TEXT,
+ gridColor: GRID,
+ cornerRadius: 8,
+ animate: { start: 10, duration: 28, ease: "back.out(1.4)" },
+ },
+ { id: "revenue-chart", position: "absolute", x: MARGIN, y: CHART_Y },
+ );
+ const best = y.revenue.indexOf(Math.max(...y.revenue));
+ const bar = boxOf(chart, `revenue-chart-bar-0-${best}`);
+ const pad = 10;
+ return Layer.box({
+ id: "revenue-view",
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: CHART_Y + CHART_H,
+ children: [
+ chart,
+ beatRing(
+ "revenue-ring",
+ bar.x - pad,
+ bar.y - pad,
+ bar.width + 2 * pad,
+ bar.height + 2 * pad,
+ 48,
+ ),
+ note(
+ "revenue-note",
+ `Best month: ${MONTHS[best]}`,
+ bar.x - pad - 500,
+ bar.y + 8,
+ 46,
+ 480,
+ "end",
+ ),
+ ],
+ });
+}
+
+/**
+ * Three fiscal years of the same chart, morphed into each other: bars, the
+ * best-month ring and its caption ease to each year's numbers while the year
+ * rolls over on an odometer.
+ */
+export function revenueScene(): LayoutNode {
+ const view = morph(
+ YEARS.map((y) => ({ at: y.at, node: yearView(y) })),
+ { duration: 30, ease: "power3.inOut" },
+ );
+ const size = 76;
+ return scene("revenue", REVENUE.from, REVENUE.to, [
+ ...header("revenue", "01 · REVENUE", "Three years, one direction."),
+ view,
+ odometer(
+ YEARS.map((y, i) => ({ at: i === 0 ? 14 : y.at, value: y.year })),
+ {
+ id: "revenue-year",
+ x: W - MARGIN - Math.round(size * 0.62) * 4,
+ y: 104,
+ size,
+ color: CYAN_TEXT,
+ change: 24,
+ },
+ ),
+ Layer.text("FISCAL YEAR", {
+ id: "revenue-year-caption",
+ position: "absolute",
+ x: W - MARGIN - 400,
+ y: 204,
+ width: 400,
+ height: 32,
+ fontFamily: MONO,
+ fontSize: 22,
+ fontWeight: 600,
+ letterSpacing: 3,
+ fill: MUTED,
+ align: "end",
+ }).animate(riseAt(20, 204, 16)),
+ ]);
+}
diff --git a/examples/23_data_story/src/scenes/title.ts b/examples/23_data_story/src/scenes/title.ts
new file mode 100644
index 00000000..fcb8505c
--- /dev/null
+++ b/examples/23_data_story/src/scenes/title.ts
@@ -0,0 +1,84 @@
+import { Layer, LayerAnimation, type LayoutNode } from "gitframes";
+import { odometer } from "../motion.js";
+import {
+ ACCENT,
+ CYAN_TEXT,
+ DISPLAY,
+ EASE_IN,
+ MARGIN,
+ MONO,
+ MUTED,
+ SANS,
+ TEXT,
+} from "../theme.js";
+import { TITLE } from "../timeline.js";
+import { riseAt, scene } from "../ui.js";
+
+/** "Growth, in motion." with the headline number rolling in on an odometer. */
+export function titleScene(): LayoutNode {
+ const numberY = 560;
+ const size = 170;
+ return scene("title", TITLE.from, TITLE.to, [
+ Layer.text("GITFRAMES ANALYTICS · Q3 REPORT", {
+ id: "title-kicker",
+ position: "absolute",
+ x: MARGIN,
+ y: 300,
+ width: 1200,
+ height: 32,
+ fontFamily: MONO,
+ fontSize: 24,
+ fontWeight: 600,
+ letterSpacing: 5,
+ fill: CYAN_TEXT,
+ }).animate(riseAt(4, 300)),
+ Layer.text("Growth, in motion.", {
+ id: "title-headline",
+ position: "absolute",
+ x: MARGIN,
+ y: 344,
+ width: 1700,
+ height: 150,
+ fontFamily: DISPLAY,
+ fontSize: 112,
+ fontWeight: 800,
+ fill: TEXT,
+ }).animate(riseAt(8, 344, 70, 30)),
+ Layer.box({
+ id: "title-rule",
+ position: "absolute",
+ x: MARGIN,
+ y: 534,
+ height: 6,
+ width: 0,
+ borderRadius: 3,
+ background: ACCENT,
+ }).animate(
+ LayerAnimation.create().fromTo("width", 0, 560, {
+ start: 16,
+ end: 46,
+ ease: EASE_IN,
+ }),
+ ),
+ odometer("+142%", {
+ id: "title-odometer",
+ x: MARGIN - 8,
+ y: numberY,
+ size,
+ at: 22,
+ stagger: 4,
+ }),
+ Layer.text("year-over-year active users", {
+ id: "title-caption",
+ position: "absolute",
+ x: MARGIN + Math.round(size * 0.62) * 5 + 28,
+ y: numberY + 120,
+ width: 700,
+ height: 44,
+ fontFamily: SANS,
+ fontSize: 34,
+ fontWeight: 500,
+ fill: MUTED,
+ }).animate(riseAt(44, numberY + 120, 24)),
+ ]);
+}
diff --git a/examples/23_data_story/src/signals.ts b/examples/23_data_story/src/signals.ts
new file mode 100644
index 00000000..483653dd
--- /dev/null
+++ b/examples/23_data_story/src/signals.ts
@@ -0,0 +1,45 @@
+/**
+ * The film's signals. Each is a per-frame function registered on the
+ * composition under a name; layers bind to them with
+ * `LayerAnimation.signal(prop, name, { multiplier, offset })`, which sets the
+ * prop to `value × multiplier + offset` every frame.
+ *
+ * Register before binding: `.signal()` resolves signals by name, so pass the
+ * name, not the signal object.
+ *
+ * Signal functions see the composition frame (`ctx.frame`), not the layer's
+ * local frame, so anything tied to a scene takes that scene's start.
+ */
+import { type Composition, Signal } from "gitframes";
+import { envelope } from "./motion.js";
+import { BEAT } from "./theme.js";
+
+export const PULSE = "pulse";
+export const BREATHE = "breathe";
+
+const hit = envelope("expo.out");
+const swell = envelope("sine.inOut");
+
+/** 1 on every beat, falling off along gsap's expo.out: a kick-drum envelope. */
+export function pulseAt(frame: number): number {
+ const phase = (((frame % BEAT) + BEAT) % BEAT) / BEAT;
+ return 1 - hit(phase);
+}
+
+/** A slow 0 → 1 → 0 swell over four beats, eased with sine.inOut. */
+export function breatheAt(frame: number): number {
+ const period = BEAT * 4;
+ const t = (((frame % period) + period) % period) / period;
+ return swell(t < 0.5 ? t * 2 : 2 - t * 2);
+}
+
+export function registerSignals(comp: Composition): void {
+ comp.addSignal(
+ PULSE,
+ Signal.builder({ type: "custom", fn: (ctx) => pulseAt(ctx.frame) }),
+ );
+ comp.addSignal(
+ BREATHE,
+ Signal.builder({ type: "custom", fn: (ctx) => breatheAt(ctx.frame) }),
+ );
+}
diff --git a/examples/23_data_story/src/theme.ts b/examples/23_data_story/src/theme.ts
new file mode 100644
index 00000000..7597f4b0
--- /dev/null
+++ b/examples/23_data_story/src/theme.ts
@@ -0,0 +1,62 @@
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { FontManager } from "gitframes";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FONTS = path.resolve(HERE, "../../../assets/fonts");
+export const OUTPUT = path.resolve(HERE, "../output");
+
+export const W = 1920;
+export const H = 1080;
+export const FPS = 30;
+
+/** The tempo the accents breathe to: one beat every 18 frames at 30 fps. */
+export const BPM = 100;
+export const BEAT = Math.round((FPS * 60) / BPM);
+
+/** Light theme: a paper-white page, ink text, saturated data colours. */
+export const BG = "#f7f8fb";
+export const TEXT = "#0f172a";
+export const MUTED = "#64748b";
+/** Axis labels, legends. */
+export const CHART_TEXT = "#475569";
+export const GRID = "rgba(15, 23, 42, 0.08)";
+
+export const ACCENT = "#6366f1";
+/** Data colours for bars, slices and lines. */
+export const CYAN = "#22d3ee";
+export const AMBER = "#f59e0b";
+export const PINK = "#ec4899";
+export const GREEN = "#22c55e";
+export const RED = "#ef4444";
+/** The same hues, dark enough for text on the light page. */
+export const CYAN_TEXT = "#0891b2";
+export const GREEN_TEXT = "#15803d";
+
+export const SANS = "Inter";
+export const DISPLAY = "Syne";
+export const MONO = "JetBrains Mono";
+
+/** Every scene lays out on the same frame: header top-left, chart below. */
+export const MARGIN = 120;
+export const HEADER_Y = 92;
+export const CHART_Y = 300;
+export const CHART_H = H - CHART_Y - 90;
+
+export const EASE_IN = "expo.out";
+export const EASE_OUT = "power3.in";
+
+export async function registerFonts(): Promise<void> {
+ await FontManager.register({
+ family: SANS,
+ source: path.join(FONTS, "Inter.ttf"),
+ });
+ await FontManager.register({
+ family: DISPLAY,
+ source: path.join(FONTS, "Syne.ttf"),
+ });
+ await FontManager.register({
+ family: MONO,
+ source: path.join(FONTS, "JetBrainsMono.ttf"),
+ });
+}
diff --git a/examples/23_data_story/src/timeline.ts b/examples/23_data_story/src/timeline.ts
new file mode 100644
index 00000000..99a36b49
--- /dev/null
+++ b/examples/23_data_story/src/timeline.ts
@@ -0,0 +1,10 @@
+/** Scene windows in composition frames (30 fps). Each scene owns [from, to). */
+export const TITLE = { from: 0, to: 90 } as const;
+export const REVENUE = { from: 90, to: 270 } as const;
+export const LIVE = { from: 270, to: 450 } as const;
+export const MIX = { from: 450, to: 630 } as const;
+export const MARKET = { from: 630, to: 810 } as const;
+export const OUTRO = { from: 810, to: 900 } as const;
+
+export const SCENES = [TITLE, REVENUE, LIVE, MIX, MARKET, OUTRO];
+export const DURATION = OUTRO.to;
diff --git a/examples/23_data_story/src/ui.ts b/examples/23_data_story/src/ui.ts
new file mode 100644
index 00000000..474ba39c
--- /dev/null
+++ b/examples/23_data_story/src/ui.ts
@@ -0,0 +1,216 @@
+import { Layer, LayerAnimation, type LayoutNode } from "gitframes";
+import { BREATHE, PULSE } from "./signals.js";
+import {
+ ACCENT,
+ CYAN_TEXT,
+ DISPLAY,
+ EASE_IN,
+ EASE_OUT,
+ H,
+ HEADER_Y,
+ MARGIN,
+ MONO,
+ MUTED,
+ SANS,
+ TEXT,
+ W,
+} from "./theme.js";
+
+/**
+ * A full-frame scene on its own clock: children key their animation from
+ * frame 0 = `from`. The whole scene lifts out over its last ten frames.
+ */
+export function scene(
+ id: string,
+ from: number,
+ to: number,
+ children: LayoutNode[],
+): LayoutNode {
+ const len = to - from;
+ return Layer.box({
+ id,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ startFrame: from,
+ durationFrames: len,
+ children,
+ }).animate(
+ LayerAnimation.create()
+ .fromTo("opacity", 1, 0, { start: len - 10, end: len, ease: EASE_OUT })
+ .fromTo("y", 0, -40, { start: len - 10, end: len, ease: EASE_OUT }),
+ );
+}
+
+/** Kicker line + display headline, top-left. */
+export function header(
+ id: string,
+ kicker: string,
+ title: string,
+ at = 0,
+): LayoutNode[] {
+ return [
+ Layer.text(kicker, {
+ id: `${id}-kicker`,
+ position: "absolute",
+ x: MARGIN,
+ y: HEADER_Y,
+ width: 1200,
+ height: 32,
+ fontFamily: MONO,
+ fontSize: 22,
+ fontWeight: 600,
+ letterSpacing: 4,
+ fill: CYAN_TEXT,
+ }).animate(riseAt(at, HEADER_Y)),
+ Layer.text(title, {
+ id: `${id}-title`,
+ position: "absolute",
+ x: MARGIN,
+ y: HEADER_Y + 44,
+ width: W - 2 * MARGIN,
+ height: 96,
+ fontFamily: DISPLAY,
+ fontSize: 76,
+ fontWeight: 700,
+ fill: TEXT,
+ }).animate(riseAt(at + 4, HEADER_Y + 44)),
+ ];
+}
+
+/** `rise` for absolutely placed nodes, whose `y` keyframes are absolute too. */
+export function riseAt(
+ at: number,
+ y: number,
+ dy = 40,
+ duration = 24,
+): LayerAnimation {
+ return LayerAnimation.create()
+ .fromTo("opacity", 0, 1, {
+ start: at,
+ end: at + Math.round(duration * 0.6),
+ ease: "power2.out",
+ })
+ .fromTo("y", y + dy, y, { start: at, end: at + duration, ease: EASE_IN });
+}
+
+/** A small caption in the chart's voice. */
+export function note(
+ id: string,
+ text: string,
+ x: number,
+ y: number,
+ at: number,
+ width = 520,
+ align: "start" | "end" = "start",
+): LayoutNode {
+ return Layer.text(text, {
+ id,
+ position: "absolute",
+ x,
+ y,
+ width,
+ height: 36,
+ fontFamily: SANS,
+ fontSize: 26,
+ fontWeight: 500,
+ fill: MUTED,
+ align,
+ }).animate(riseAt(at, y, 24));
+}
+
+/**
+ * A glowing ring that breathes on the beat: its opacity follows the `pulse`
+ * signal, so it flashes on each beat and decays along expo.out.
+ */
+export function beatRing(
+ id: string,
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ at: number,
+ color = ACCENT,
+): LayoutNode {
+ return Layer.box({
+ id,
+ position: "absolute",
+ x,
+ y,
+ width,
+ height,
+ borderRadius: 14,
+ borderWidth: 3,
+ borderColor: color,
+ background: "transparent",
+ startFrame: at,
+ }).animate(
+ LayerAnimation.create().signal("opacity", PULSE, {
+ multiplier: 0.75,
+ offset: 0.25,
+ }),
+ );
+}
+
+/**
+ * The ambient backdrop behind every scene: two soft radial glows whose opacity
+ * swells with the `breathe` signal, and a faint baseline grid.
+ */
+export function backdrop(): LayoutNode[] {
+ const glow = (
+ id: string,
+ x: number,
+ y: number,
+ size: number,
+ color: string,
+ mult: number,
+ ) =>
+ Layer.shape("circle", {
+ id,
+ position: "absolute",
+ x: x - size / 2,
+ y: y - size / 2,
+ width: size,
+ height: size,
+ fillType: "radial",
+ fillColor: color,
+ gradientEndColor: "rgba(247, 248, 251, 0)",
+ }).animate(
+ LayerAnimation.create().signal("opacity", BREATHE, {
+ multiplier: mult,
+ offset: 0.12,
+ }),
+ );
+ const rules = Array.from({ length: 13 }, (_, i) =>
+ Layer.box({
+ id: `bg-rule-${i}`,
+ position: "absolute",
+ x: Math.round((W / 12) * i),
+ y: 0,
+ width: 1,
+ height: H,
+ background: "rgba(15, 23, 42, 0.035)",
+ }),
+ );
+ return [
+ glow(
+ "bg-glow-a",
+ W * 0.82,
+ H * 0.18,
+ 1300,
+ "rgba(99, 102, 241, 0.35)",
+ 0.18,
+ ),
+ glow(
+ "bg-glow-b",
+ W * 0.12,
+ H * 0.95,
+ 1100,
+ "rgba(34, 211, 238, 0.35)",
+ 0.14,
+ ),
+ ...rules,
+ ];
+}
diff --git a/examples/23_data_story/tsconfig.dev.json b/examples/23_data_story/tsconfig.dev.json
new file mode 100644
index 00000000..8c05246f
--- /dev/null
+++ b/examples/23_data_story/tsconfig.dev.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig.json",
+ "include": [
+ "src/**/*",
+ "../../nodes/**/*",
+ "../../packages/**/*",
+ "../../node_modules/@gitframes/**/*"
+ ]
+}
diff --git a/examples/23_data_story/tsconfig.json b/examples/23_data_story/tsconfig.json
new file mode 100644
index 00000000..1bf5206d
--- /dev/null
+++ b/examples/23_data_story/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "extends": "@gitframes/tsconfig/base.json",
+ "compilerOptions": {
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "target": "ES2022",
+ "noEmit": true
+ },
+ "include": ["src/**/*"]
+}
diff --git a/nodes/node-compositor/SKILL.md b/nodes/node-compositor/SKILL.md
index cd924912..769fee29 100644
--- a/nodes/node-compositor/SKILL.md
+++ b/nodes/node-compositor/SKILL.md
@@ -67,7 +67,7 @@ This node uses **Variable Inputs**. You can add dynamically named input handles
### Layout Node Schema
Common fields (every node):
- **`id`** (string, required): Unique node id — also keys the timeline.
-- **`kind`** (string, required): `"flex"` | `"block"` | `"box"` | `"text"` | `"media"` | `"shape"` | `"chart"`.
+- **`kind`** (string, required): `"flex"` | `"block"` | `"box"` | `"text"` | `"media"` | `"shape"`.
- **`inputHandleId`** (string, optional): Graph binding — which connected input this node renders (for text/media nodes).
> [!WARNING]
> Do not place a handle label in `inputHandleId` when updating an existing live Compositor. The renderer may treat the media as unbound and produce a blank layer. Use the actual dynamic input handle ID returned from the live Compositor node.
@@ -131,10 +131,7 @@ Per-kind fields:
- Fill: `fillType` (`"solid"` | `"linear"` | `"radial"` | `"none"`), `fillColor`, `gradientEndColor`, `gradientAngle`.
- Stroke: `strokeColor`, `strokeWidth`, `strokeDashArray`, `strokeDashOffset`, `strokeLineCap` (`"butt"` | `"round"` | `"square"`), `strokeLineJoin` (`"miter"` | `"round"` | `"bevel"`), `strokeAlign` (`"inside"` | `"center"` | `"outside"`).
- Trim Paths: `trimStart` (0..1), `trimEnd` (0..1), `trimOffset` (rotation/offset).
-- **`chart`**: High-performance GPU-accelerated animated chart rendered headlessly with ChartGPU:
- - `chartOptions` (ChartGPUOptions, required): Options specifying theme, axes, and series (`line`, `area`, `bar`, `candlestick`, `ohlc`, `pie`, `heatmap`, `band`, `errorBar`, `impulse`, `pointCloud3d`, `surface3d`).
- - `progress` / `drawProgress` (number, 0–1, default 1): Timeline reveal progress for progressive write-on animations.
- - Supports 3D homography projection (`rotateX`, `rotateY`, `perspective`), border radius clipping, directional motion blur, and signal reactivity.
+- **Charts**: there is no chart node kind. `Layer.chart` in the `gitframes` SDK expands a chart into `box`, `shape` (`"path"`/`"circle"`) and `text` nodes, so a program document describes a chart with those kinds.
- **`media`**: `inputHandleId` (string, required — must match a connected input handle).
- **Standard Media (`Video`, `Image`, `GIF`, `SVG`, `Lottie`)**: `fit` (`"cover"` | `"contain"` | `"fill"` | `"none"`, default `"contain"`), `volume` (0–1), `muted`, `borderRadius`, `borderColor`, `borderWidth`.
- **Captions & Subtitles (`Caption` DataType)**: When bound to a `Caption` input (SRT source), `kind: "media"` renders time-synchronized subtitle cues:
diff --git a/nodes/node-compositor/package.json b/nodes/node-compositor/package.json
index 45d6961c..ac8e0d96 100644
--- a/nodes/node-compositor/package.json
+++ b/nodes/node-compositor/package.json
@@ -37,7 +37,6 @@
"@gitframes/renderers": "workspace:*",
"@gitframes/tensor-webgpu": "workspace:*",
"@gitframes/webgpu-renderers": "workspace:*",
- "chartgpu": "^0.4.0",
"gsap": "^3.15.0",
"zod": "^4.3.6"
},
diff --git a/nodes/node-compositor/src/renderers/webgpu-renderer.ts b/nodes/node-compositor/src/renderers/webgpu-renderer.ts
index 132d3d1d..93195117 100644
--- a/nodes/node-compositor/src/renderers/webgpu-renderer.ts
+++ b/nodes/node-compositor/src/renderers/webgpu-renderer.ts
@@ -25,7 +25,6 @@ import {
type Color,
type DrawMesh3DOpts,
type DrawQuad3DOpts,
- drawChartNode,
type ExtrudedTextGeometryOptions,
type GPUMeshBuffers,
generateExtrudedTextGeometry,
@@ -60,6 +59,39 @@ import {
Transform3DMath,
} from "./transform3d.js";
+// Layout depends on the document tree (whose `children` array keeps its
+// identity between frames), the viewport, media sizes and the few layout
+// props a timeline can animate. A film's tree holds every scene, so
+// re-running Yoga each frame is costly when none of those changed.
+const LAYOUT_PROPS = [
+ "width",
+ "height",
+ "gap",
+ "padding",
+ "fontSize",
+ "letterSpacing",
+] as const;
+const layoutMemo = new WeakMap<
+ object,
+ { key: string; rects: Record<string, Rect> }
+>();
+
+function layoutKey(
+ width: number,
+ height: number,
+ targetsById: Record<string, any>,
+ mediaDims: Map<string, { width: number; height: number }>,
+): string {
+ const parts: unknown[] = [width, height];
+ for (const id in targetsById) {
+ const t = targetsById[id];
+ for (const k of LAYOUT_PROPS)
+ if (t[k] !== undefined) parts.push(id, k, t[k]);
+ }
+ for (const [id, d] of mediaDims) parts.push(id, d.width, d.height);
+ return JSON.stringify(parts);
+}
+
const compositorHomographyWgsl = `
struct HomographyUniforms {
matrix_row0 : vec4<f32>,
@@ -727,58 +759,74 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {
if (!node.children.length) node.children = undefined;
return node;
};
- const layoutRoots: LayoutNode[] = (virtualMedia.children ?? [])
- .map(frameResolveNode)
- .filter((node: any) => node?.kind !== "camera" && node?.kind !== "light");
- const { rects } = await computeLayout({
- layout: layoutRoots,
- viewport: { width: nativeWidth, height: nativeHeight },
- measure: (node, constraintWidth) => {
- if (node.kind === "text") {
- const textStyle = {
- fontSize: node.fontSize ?? 48,
- fontWeight: node.fontWeight,
- fontFamily: node.fontFamily,
- letterSpacing: node.letterSpacing,
- lineHeight: node.lineHeight,
- padding: node.padding,
- };
+ const layoutRoots = (): LayoutNode[] =>
+ (virtualMedia.children ?? [])
+ .map(frameResolveNode)
+ .filter(
+ (node: any) => node?.kind !== "camera" && node?.kind !== "light",
+ );
+ const memoTree = virtualMedia.children as object | undefined;
+ const memoKey = layoutKey(
+ nativeWidth,
+ nativeHeight,
+ targetsById,
+ mediaDims,
+ );
+ const memo = memoTree ? layoutMemo.get(memoTree) : undefined;
+ const { rects } =
+ memo?.key === memoKey
+ ? memo
+ : await computeLayout({
+ layout: layoutRoots(),
+ viewport: { width: nativeWidth, height: nativeHeight },
+ measure: (node, constraintWidth) => {
+ if (node.kind === "text") {
+ const textStyle = {
+ fontSize: node.fontSize ?? 48,
+ fontWeight: node.fontWeight,
+ fontFamily: node.fontFamily,
+ letterSpacing: node.letterSpacing,
+ lineHeight: node.lineHeight,
+ padding: node.padding,
+ };
- if (constraintWidth !== undefined) {
- const isAuto = typeof node.width !== "number";
- const wrapped = measureText(node.text ?? "", {
- ...textStyle,
- width: isAuto ? undefined : constraintWidth,
- keepNaturalWidth: true,
- });
- return {
- width: isAuto
- ? Math.ceil(wrapped.width)
- : Math.min(constraintWidth, Math.ceil(wrapped.width)),
- height: Math.ceil(wrapped.height),
- };
- }
+ if (constraintWidth !== undefined) {
+ const isAuto = typeof node.width !== "number";
+ const wrapped = measureText(node.text ?? "", {
+ ...textStyle,
+ width: isAuto ? undefined : constraintWidth,
+ keepNaturalWidth: true,
+ });
+ return {
+ width: isAuto
+ ? Math.ceil(wrapped.width)
+ : Math.min(constraintWidth, Math.ceil(wrapped.width)),
+ height: Math.ceil(wrapped.height),
+ };
+ }
- const natural = measureText(node.text ?? "", textStyle);
- if (typeof node.width !== "number") {
- return {
- width: Math.ceil(natural.width),
- height: Math.ceil(natural.height),
- };
- }
- const wrapped = measureText(node.text ?? "", {
- ...textStyle,
- width: node.width,
+ const natural = measureText(node.text ?? "", textStyle);
+ if (typeof node.width !== "number") {
+ return {
+ width: Math.ceil(natural.width),
+ height: Math.ceil(natural.height),
+ };
+ }
+ const wrapped = measureText(node.text ?? "", {
+ ...textStyle,
+ width: node.width,
+ });
+ return {
+ width: Math.ceil(wrapped.width),
+ height: Math.ceil(wrapped.height),
+ };
+ }
+ if (node.kind === "media") return mediaDims.get(node.id) ?? null;
+ return null;
+ },
});
- return {
- width: Math.ceil(wrapped.width),
- height: Math.ceil(wrapped.height),
- };
- }
- if (node.kind === "media") return mediaDims.get(node.id) ?? null;
- return null;
- },
- });
+ if (memoTree && memo?.key !== memoKey)
+ layoutMemo.set(memoTree, { key: memoKey, rects });
// 4. 3D Camera and Multiplane Setup
const allNodeOps = collectNodeOps(virtualMedia.children ?? []);
// A film can cut between cameras: the active one is the camera whose
@@ -3177,41 +3225,6 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {
);
shapePass.end();
- } else if (kind === "chart") {
- const chartOptions = lop.chartOptions;
- if (chartOptions) {
- const progress =
- typeof target?.progress === "number"
- ? target.progress
- : typeof target?.drawProgress === "number"
- ? target.drawProgress
- : typeof target?.chartProgress === "number"
- ? target.chartProgress
- : typeof lop.drawProgress === "number"
- ? lop.drawProgress
- : typeof lop.progress === "number"
- ? lop.progress
- : 1.0;
-
- const chartPass = ctx.renderer.beginFrame(
- encoder,
- localView,
- { r: 0, g: 0, b: 0, a: 0 },
- texW,
- texH,
- "load",
- );
-
- await drawChartNode(ctx, chartPass, {
- nodeId: lop.id,
- chartOptions,
- dstRect: { x: 0, y: 0, width: layerW, height: layerH },
- progress,
- opacity: 1.0,
- });
-
- chartPass.end();
- }
}
// Temporal De-flickering & Optical Flow Warping
diff --git a/nodes/node-compositor/src/shared/compiler.test.ts b/nodes/node-compositor/src/shared/compiler.test.ts
index c011fda8..d2c34e8f 100644
--- a/nodes/node-compositor/src/shared/compiler.test.ts
+++ b/nodes/node-compositor/src/shared/compiler.test.ts
@@ -1,6 +1,11 @@
+import gsapModule from "gsap";
import { afterEach, describe, expect, it, vi } from "vitest";
import { compileLayerTimeline, compileTimeline } from "./compiler.js";
+const gsap: any = (gsapModule as any).timeline
+ ? gsapModule
+ : (gsapModule as any).default || gsapModule;
+
describe("Compositor GSAP Compiler", () => {
it("should compile a 2-keyframe fromTo tween correctly", () => {
const virtualMedia = {
@@ -1178,3 +1183,127 @@ describe("keyframe tail truncation (review M8)", () => {
});
});
+describe("Compositor timeline cache lifecycle", () => {
+ /**
+ * A stand-in for a real signal (Signal.fromArray / ProgrammaticSignal): its
+ * per-frame cache fields mutate on every get(), which is exactly what made
+ * the old content hash change every frame.
+ */
+ function mutableSignal() {
+ return {
+ _cachedFrame: -1,
+ _cachedValue: 0,
+ get(ctx?: { frame?: number }): number {
+ const f = ctx?.frame ?? 0;
+ if (this._cachedFrame === f) return this._cachedValue;
+ this._cachedFrame = f;
+ this._cachedValue = f % 2 === 0 ? 0 : 1;
+ return this._cachedValue;
+ },
+ };
+ }
+
+ function vmWithSignal(signals: Record<string, unknown>) {
+ return {
+ metadata: { width: 1920, height: 1080, durationMs: 2000 },
+ operation: { op: "Compositor", signals },
+ children: [
+ {
+ operation: {
+ op: "CompositorLayer",
+ id: "sig-node",
+ x: 0,
+ y: 0,
+ scale: 1,
+ durationFrames: 48,
+ animation: {
+ tracks: [
+ {
+ id: "t_sig",
+ prop: "opacity" as const,
+ source: {
+ type: "signal" as const,
+ inputHandleId: "gate",
+ multiplier: 1,
+ offset: 0,
+ channel: "primary",
+ },
+ },
+ ],
+ },
+ },
+ },
+ ],
+ } as any;
+ }
+
+ it("reuses one compiled timeline for a live signal across frames", () => {
+ const signal = mutableSignal();
+ const vm = vmWithSignal({ gate: signal });
+
+ const first = compileTimeline("signal-cache", vm, {
+ fps: 24,
+ durationSec: 2,
+ });
+ // Advance the signal exactly as the next frame's evaluation would — its
+ // cached frame/value now differ from the values at the first compile.
+ signal.get({ frame: 7 });
+ const second = compileTimeline("signal-cache", vm, {
+ fps: 24,
+ durationSec: 2,
+ });
+
+ expect(second.tl).toBe(first.tl);
+ });
+
+ it("reuses the timeline when the operation is shallow-copied per frame", () => {
+ // drawCompositionTree bakes signal values into a fresh copy of the
+ // operation every frame; children keep their identity.
+ const vm = vmWithSignal({ gate: [0, 1, 0] });
+ const first = compileTimeline("shallow-copy", vm, {
+ fps: 24,
+ durationSec: 2,
+ });
+ const second = compileTimeline(
+ "shallow-copy",
+ { ...vm, operation: { ...vm.operation, gate: 1 } },
+ { fps: 24, durationSec: 2 },
+ );
+
+ expect(second.tl).toBe(first.tl);
+ });
+
+ it("still busts the cache when plain (non-signal) signal data changes", () => {
+ const vm = vmWithSignal({ gate: [0, 1, 0] });
+ const first = compileTimeline("plain-signal", vm, {
+ fps: 24,
+ durationSec: 2,
+ });
+
+ vm.operation.signals.gate = [1, 0, 1];
+ const second = compileTimeline("plain-signal", vm, {
+ fps: 24,
+ durationSec: 2,
+ });
+
+ expect(second.tl).not.toBe(first.tl);
+ });
+
+ it("kills evicted timelines so gsap's global timeline stays bounded", () => {
+ const count = () =>
+ gsap.globalTimeline.getChildren(true, false, true).length;
+
+ const vm = vmWithSignal({ gate: mutableSignal() });
+ compileTimeline("kill-cap-0", vm, { fps: 24, durationSec: 2 });
+ const before = count();
+
+ // Far more compiled ids than the cache capacity: each insert past the
+ // cap must evict AND kill, or the global timeline grows one per compile.
+ for (let i = 0; i < 120; i++) {
+ compileTimeline(`kill-cap-${i}`, vm, { fps: 24, durationSec: 2 });
+ }
+
+ expect(count() - before).toBeLessThanOrEqual(50);
+ });
+});
+
diff --git a/nodes/node-compositor/src/shared/compiler.ts b/nodes/node-compositor/src/shared/compiler.ts
index d692699f..7e51eb54 100644
--- a/nodes/node-compositor/src/shared/compiler.ts
+++ b/nodes/node-compositor/src/shared/compiler.ts
@@ -47,8 +47,6 @@ export interface LayerStub {
translateZ?: number;
backfaceVisibility?: "visible" | "hidden";
transformStyle?: "flat" | "preserve-3d";
- drawProgress?: number;
- chartProgress?: number;
// 3D Layer Props
is3D?: boolean;
z?: number;
@@ -99,7 +97,6 @@ export interface LayerStub {
[key: string]: unknown;
}
-
export type CompilerVirtualMedia = {
metadata?: Partial<VirtualMediaData["metadata"]>;
operation?: Partial<VirtualMediaData["operation"]> & Record<string, any>;
@@ -123,6 +120,29 @@ export interface CompileResult {
// concurrently without cloning `tl` + stubs first.
const cache = new Map<string, { cacheTime: number; value: CompileResult }>();
+// L1: hashing the layer ops stringifies every keyframe of every layer, which
+// costs tens of ms per frame on a full film. Programs are rebuilt (not mutated)
+// when a composition changes, so that hash is memoized on the children array:
+// the operation itself is shallow-copied each frame to bake in signal values,
+// but `children` keeps its identity. Signals are cheap to key and may be plain
+// data mutated in place, so they are re-keyed on every call.
+const nodesHashMemo = new WeakMap<
+ object,
+ {
+ width: number;
+ height: number;
+ fps: number;
+ durationSec: number;
+ hash: string;
+ }
+>();
+
+/** Entries untouched for this long are dropped (and their timeline killed). */
+const CACHE_TTL_MS = 10000;
+/** Max compiled timelines retained per cache. */
+const TIMELINE_CACHE_MAX = 50;
+const LAYER_TIMELINE_CACHE_MAX = 50;
+
function fnv1a(str: string): string {
let hash = 2166136261;
for (let i = 0; i < str.length; i++) {
@@ -133,6 +153,69 @@ function fnv1a(str: string): string {
return (hash >>> 0).toString(16);
}
+// Signal objects carry per-frame caches (last frame, last value), so hashing
+// their contents gives a new key every frame: the timeline would recompile
+// each frame and the cache would never hit. Key live signals by identity.
+const signalIds = new WeakMap<object, number>();
+let nextSignalId = 0;
+
+function signalsKey(signals: unknown): string {
+ if (!signals || typeof signals !== "object") return stableStringify(signals);
+ return Object.keys(signals)
+ .sort()
+ .map((name) => {
+ const s = (signals as Record<string, unknown>)[name];
+ if (
+ s &&
+ typeof s === "object" &&
+ typeof (s as { get?: unknown }).get === "function"
+ ) {
+ let id = signalIds.get(s);
+ if (id === undefined) {
+ id = nextSignalId++;
+ signalIds.set(s, id);
+ }
+ return `${JSON.stringify(name)}:#${id}`;
+ }
+ return `${JSON.stringify(name)}:${stableStringify(s)}`;
+ })
+ .join(",");
+}
+
+/**
+ * Paused gsap timelines stay attached to gsap's global timeline until killed,
+ * so anything dropped from a cache must be killed or it is never collected.
+ */
+function release(value: { tl: gsap.core.Timeline }): void {
+ value.tl.kill();
+}
+
+/**
+ * Make room for one insertion: drop and kill TTL-expired entries, then evict
+ * the least-recently-used entry if the cache is at capacity. Every dropped
+ * timeline MUST be killed — see `release`.
+ */
+function evictForInsert<T extends { tl: gsap.core.Timeline }>(
+ cache: Map<string, { cacheTime: number; value: T }>,
+ maxSize: number,
+): void {
+ const now = Date.now();
+ for (const [key, entry] of cache.entries()) {
+ if (now - entry.cacheTime > CACHE_TTL_MS) {
+ cache.delete(key);
+ release(entry.value);
+ }
+ }
+ if (cache.size >= maxSize) {
+ const oldestKey = cache.keys().next().value;
+ if (oldestKey !== undefined) {
+ const oldest = cache.get(oldestKey);
+ cache.delete(oldestKey);
+ if (oldest) release(oldest.value);
+ }
+ }
+}
+
function stableStringify(obj: any): string {
if (obj === null) return "null";
if (obj === undefined) return "undefined";
@@ -153,8 +236,9 @@ function stableStringify(obj: any): string {
export function getCachedTimeline(cacheKey: string): CompileResult | undefined {
const entry = cache.get(cacheKey);
if (entry) {
- if (Date.now() - entry.cacheTime > 10000) {
+ if (Date.now() - entry.cacheTime > CACHE_TTL_MS) {
cache.delete(cacheKey);
+ release(entry.value);
return undefined;
}
entry.cacheTime = Date.now();
@@ -166,19 +250,8 @@ export function getCachedTimeline(cacheKey: string): CompileResult | undefined {
}
export function setCachedTimeline(cacheKey: string, value: CompileResult) {
- const now = Date.now();
- for (const [key, entry] of cache.entries()) {
- if (now - entry.cacheTime > 10000) {
- cache.delete(key);
- }
- }
- if (cache.size >= 50) {
- const oldestKey = cache.keys().next().value;
- if (oldestKey !== undefined) {
- cache.delete(oldestKey);
- }
- }
- cache.set(cacheKey, { cacheTime: now, value });
+ evictForInsert(cache, TIMELINE_CACHE_MAX);
+ cache.set(cacheKey, { cacheTime: Date.now(), value });
}
export function mappedEase(
@@ -490,20 +563,13 @@ function warnTruncationOnce(cacheKey: string, truncations: TruncationInfo[]) {
);
}
-export function compileTimeline(
- renderId: string,
- virtualMedia: CompilerVirtualMedia | null | undefined,
- options: { fps: number; durationSec: number },
-): CompileResult {
- const fps = options.fps;
- const durationSec = options.durationSec;
- const width = virtualMedia?.metadata?.width ?? 1920;
- const height = virtualMedia?.metadata?.height ?? 1080;
-
- // Collect node ops from the render tree (pre-order: parents first).
- const nodeOps = collectNodeOps((virtualMedia?.children as any) ?? []);
-
- // LRU cache check
+function hashNodes(
+ nodeOps: CompilerNodeVM[],
+ width: number,
+ height: number,
+ fps: number,
+ durationSec: number,
+): string {
const irHashInput = stableStringify({
nodes: nodeOps.map((vm) => {
const lop = (vm?.operation || {}) as any;
@@ -535,8 +601,6 @@ export function compileTimeline(
translateZ: lop.translateZ,
backfaceVisibility: lop.backfaceVisibility,
transformStyle: lop.transformStyle,
- drawProgress: lop.drawProgress,
- chartProgress: lop.chartProgress,
is3D: lop.is3D,
z: lop.z,
scaleZ: lop.scaleZ,
@@ -593,9 +657,50 @@ export function compileTimeline(
height,
fps,
durationSec,
- signals: (virtualMedia as any)?.operation?.signals ?? (virtualMedia as any)?.signals,
});
- const irHash = fnv1a(irHashInput);
+ return fnv1a(irHashInput);
+}
+
+export function compileTimeline(
+ renderId: string,
+ virtualMedia: CompilerVirtualMedia | null | undefined,
+ options: { fps: number; durationSec: number },
+): CompileResult {
+ const fps = options.fps;
+ const durationSec = options.durationSec;
+ const width = virtualMedia?.metadata?.width ?? 1920;
+ const height = virtualMedia?.metadata?.height ?? 1080;
+
+ // Collect node ops from the render tree (pre-order: parents first).
+ const nodeOps = collectNodeOps((virtualMedia?.children as any) ?? []);
+
+ // LRU cache check
+ const memoKey = virtualMedia?.children as object | undefined;
+ const memo = memoKey ? nodesHashMemo.get(memoKey) : undefined;
+ let nodesHash: string;
+ if (
+ memo &&
+ memo.width === width &&
+ memo.height === height &&
+ memo.fps === fps &&
+ memo.durationSec === durationSec
+ ) {
+ nodesHash = memo.hash;
+ } else {
+ nodesHash = hashNodes(nodeOps, width, height, fps, durationSec);
+ if (memoKey) {
+ nodesHashMemo.set(memoKey, {
+ width,
+ height,
+ fps,
+ durationSec,
+ hash: nodesHash,
+ });
+ }
+ }
+ const irHash = fnv1a(
+ `${nodesHash}|${signalsKey((virtualMedia as any)?.operation?.signals ?? (virtualMedia as any)?.signals)}`,
+ );
const cacheKey = `${renderId}_${irHash}`;
const cached = getCachedTimeline(cacheKey);
@@ -618,8 +723,14 @@ export function compileTimeline(
id: layerId,
inputHandleId: lop.inputHandleId || `layer_${index}`,
trackId: layerId,
- x: lop.kind === "camera" || lop.kind === "light" ? (lop.x ?? lop.cameraX) : (lop.x ?? 0),
- y: lop.kind === "camera" || lop.kind === "light" ? (lop.y ?? lop.cameraY) : (lop.y ?? 0),
+ x:
+ lop.kind === "camera" || lop.kind === "light"
+ ? (lop.x ?? lop.cameraX)
+ : (lop.x ?? 0),
+ y:
+ lop.kind === "camera" || lop.kind === "light"
+ ? (lop.y ?? lop.cameraY)
+ : (lop.y ?? 0),
scale: lop.scale ?? 1,
rotation: lop.rotation ?? 0,
opacity: lop.opacity ?? 1,
@@ -637,8 +748,6 @@ export function compileTimeline(
translateZ: lop.translateZ ?? 0,
backfaceVisibility: lop.backfaceVisibility ?? "visible",
transformStyle: lop.transformStyle ?? "flat",
- drawProgress: lop.drawProgress ?? 1,
- chartProgress: lop.chartProgress ?? 1,
fontSize: lop.fontSize,
text: 1,
fill: lop.fill,
@@ -657,7 +766,11 @@ export function compileTimeline(
typewriter: lop.typewriter,
marquee: lop.marquee,
// 3D Layer Props
- is3D: lop.is3D ?? (lop.kind === "camera" || lop.kind === "light" || lop.kind === "model3d" ? true : false),
+ is3D:
+ lop.is3D ??
+ (lop.kind === "camera" || lop.kind === "light" || lop.kind === "model3d"
+ ? true
+ : false),
z: lop.z ?? (lop.kind === "camera" ? (lop.z ?? -1500) : 0),
scaleZ: lop.scaleZ ?? 1,
twoSided: lop.twoSided ?? true,
@@ -709,7 +822,6 @@ export function compileTimeline(
decay: lop.decay,
};
-
for (const track of lop.animation?.tracks ?? []) {
const source = track.source ?? { type: "keyframe" };
if (source.type !== "keyframe") {
@@ -853,11 +965,12 @@ export function compileLayerTimeline(
const cached = layerTimelineCache.get(cacheKey);
if (cached) {
- if (Date.now() - cached.cacheTime <= 10000) {
+ if (Date.now() - cached.cacheTime <= CACHE_TTL_MS) {
cached.cacheTime = Date.now();
return cached.value;
}
layerTimelineCache.delete(cacheKey);
+ release(cached.value);
}
const tl = gsap.timeline({ paused: true, smoothChildTiming: false });
@@ -877,6 +990,7 @@ export function compileLayerTimeline(
tl.seek(0);
const result = { tl, stub };
+ evictForInsert(layerTimelineCache, LAYER_TIMELINE_CACHE_MAX);
layerTimelineCache.set(cacheKey, { cacheTime: Date.now(), value: result });
return result;
}
diff --git a/nodes/node-layer-style/package.json b/nodes/node-layer-style/package.json
index 6fda41af..b39f14b7 100644
--- a/nodes/node-layer-style/package.json
+++ b/nodes/node-layer-style/package.json
@@ -38,7 +38,7 @@
"@types/node": "^24.1.0",
"tsdown": "^0.19.0",
"typescript": "^5.8.3",
- "vitest": "^3.1.1",
+ "vitest": "^4.1.11",
"webgpu": "^0.4.0"
},
"publishConfig": {
diff --git a/nodes/node-vision/src/renderers/frame-cache.ts b/nodes/node-vision/src/renderers/frame-cache.ts
new file mode 100644
index 00000000..e442dafe
--- /dev/null
+++ b/nodes/node-vision/src/renderers/frame-cache.ts
@@ -0,0 +1,149 @@
+/**
+ * Per-frame vision results, so a frame is analysed once. A source frame gives
+ * the same detections and masks for the same model and settings, so replays,
+ * scrubbing back and later renders in the same process reuse them instead of
+ * running inference again.
+ *
+ * Masks are run-length encoded: they are long flat runs with soft edges, so a
+ * frame-sized mask shrinks from megabytes to tens of kilobytes.
+ */
+import type {
+ InstanceMask,
+ SegmentationResult,
+ TrackedObject,
+} from "@gitframes/vision";
+
+type DetectedObject = SegmentationResult["detections"][number];
+
+/** A frame-sized 0..255 mask as (value, run length) pairs. */
+export interface RleMask {
+ readonly width: number;
+ readonly height: number;
+ readonly values: Uint8Array;
+ readonly lengths: Uint32Array;
+}
+
+let scratchValues = new Uint8Array(0);
+let scratchLengths = new Uint32Array(0);
+
+export function encodeMask(
+ mask: Uint8Array,
+ width: number,
+ height: number,
+): RleMask {
+ // One pass into reused worst-case buffers; masks are flat almost
+ // everywhere, so the copies at the end are small.
+ if (scratchValues.length < mask.length) {
+ scratchValues = new Uint8Array(mask.length);
+ scratchLengths = new Uint32Array(mask.length);
+ }
+ const values = scratchValues;
+ const lengths = scratchLengths;
+ let runs = 0;
+ let start = 0;
+ for (let i = 1; i <= mask.length; i++) {
+ if (i === mask.length || mask[i] !== mask[start]) {
+ values[runs] = mask[start];
+ lengths[runs] = i - start;
+ runs++;
+ start = i;
+ }
+ }
+ return {
+ width,
+ height,
+ values: values.slice(0, runs),
+ lengths: lengths.slice(0, runs),
+ };
+}
+
+export function decodeMask(rle: RleMask): Uint8Array {
+ const out = new Uint8Array(rle.width * rle.height);
+ let at = 0;
+ for (let r = 0; r < rle.values.length; r++) {
+ const end = at + rle.lengths[r];
+ if (rle.values[r] !== 0) out.fill(rle.values[r], at, end);
+ at = end;
+ }
+ return out;
+}
+
+function rleBytes(rle: RleMask): number {
+ return rle.values.byteLength + rle.lengths.byteLength;
+}
+
+export interface CachedInstanceMask extends Omit<InstanceMask, "mask"> {
+ readonly rle: RleMask;
+}
+
+export interface VisionFrameResult {
+ readonly detections: readonly DetectedObject[];
+ readonly objects: readonly TrackedObject[];
+ /** Instance masks, kept only when a vision bundle reads them back. */
+ readonly masks: readonly CachedInstanceMask[] | null;
+ /** The composited subject (after hold and background keying); null = none. */
+ readonly subject: { readonly mask: CachedInstanceMask } | null;
+ /** Background-key threshold the subject was grown with. */
+ readonly keyThreshold?: number;
+}
+
+export function toCachedMask(mask: InstanceMask): CachedInstanceMask {
+ const { mask: data, ...rest } = mask;
+ return { ...rest, rle: encodeMask(data, mask.width, mask.height) };
+}
+
+export function fromCachedMask(mask: CachedInstanceMask): InstanceMask {
+ const { rle, ...rest } = mask;
+ return { ...rest, mask: decodeMask(rle) };
+}
+
+function resultBytes(result: VisionFrameResult): number {
+ let bytes =
+ 512 + result.detections.length * 128 + result.objects.length * 256;
+ for (const m of result.masks ?? []) bytes += rleBytes(m.rle);
+ if (result.subject) bytes += rleBytes(result.subject.mask.rle);
+ return bytes;
+}
+
+/** Results by source (node + inference settings) and frame, least recently used out first. */
+export class VisionFrameCache {
+ private readonly entries = new Map<string, VisionFrameResult>();
+ private bytes = 0;
+
+ constructor(private readonly maxBytes = 256 * 1024 * 1024) {}
+
+ get(source: string, frame: number): VisionFrameResult | undefined {
+ const key = `${source}#${frame}`;
+ const hit = this.entries.get(key);
+ if (hit) {
+ this.entries.delete(key);
+ this.entries.set(key, hit);
+ }
+ return hit;
+ }
+
+ set(source: string, frame: number, result: VisionFrameResult): void {
+ const key = `${source}#${frame}`;
+ const old = this.entries.get(key);
+ if (old) {
+ this.bytes -= resultBytes(old);
+ this.entries.delete(key);
+ }
+ this.entries.set(key, result);
+ this.bytes += resultBytes(result);
+ for (const [k, v] of this.entries) {
+ if (this.bytes <= this.maxBytes) break;
+ this.entries.delete(k);
+ this.bytes -= resultBytes(v);
+ }
+ }
+
+ clear(): void {
+ this.entries.clear();
+ this.bytes = 0;
+ }
+
+ get size(): number {
+ return this.entries.size;
+ }
+}
diff --git a/nodes/node-vision/src/renderers/matte-compositor.ts b/nodes/node-vision/src/renderers/matte-compositor.ts
new file mode 100644
index 00000000..10835e41
--- /dev/null
+++ b/nodes/node-vision/src/renderers/matte-compositor.ts
@@ -0,0 +1,189 @@
+/// <reference types="webgpu" />
+/**
+ * GPU composite for the mask-family modes: the picture times the subject mask,
+ * in one full-screen pass. Replaces building the RGBA result on the CPU and
+ * uploading it; only the 8-bit mask goes to the GPU.
+ *
+ * - matte: picture × mask (premultiplied, so the background is transparent)
+ * - mask: white silhouette (rgb = mask, a = 1)
+ * - crop: matte, with the subject's bounding box stretched to the frame
+ */
+
+const WGSL = /* wgsl */ `
+struct Params {
+ mode: u32, // 0 matte, 1 mask, 2 crop
+ _pad: u32,
+ cropMin: vec2<f32>, // uv of the subject bounds (crop)
+ cropMax: vec2<f32>,
+ _pad2: vec2<f32>,
+};
+
+@group(0) @binding(0) var<uniform> params: Params;
+@group(0) @binding(1) var picture: texture_2d<f32>;
+@group(0) @binding(2) var mask: texture_2d<f32>;
+@group(0) @binding(3) var samp: sampler;
+
+struct VSOut {
+ @builtin(position) pos: vec4<f32>,
+ @location(0) uv: vec2<f32>,
+};
+
+@vertex fn vs(@builtin(vertex_index) i: u32) -> VSOut {
+ var p = array<vec2<f32>, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));
+ var out: VSOut;
+ out.pos = vec4(p[i], 0.0, 1.0);
+ out.uv = vec2(p[i].x * 0.5 + 0.5, 0.5 - p[i].y * 0.5);
+ return out;
+}
+
+@fragment fn fs(in: VSOut) -> @location(0) vec4<f32> {
+ var uv = in.uv;
+ if (params.mode == 2u) {
+ uv = mix(params.cropMin, params.cropMax, uv);
+ }
+ let m = textureSampleLevel(mask, samp, uv, 0.0).r;
+ if (params.mode == 1u) {
+ return vec4(m, m, m, 1.0);
+ }
+ return textureSampleLevel(picture, samp, uv, 0.0) * m;
+}
+`;
+
+export type MatteMode = "matte" | "mask" | "crop";
+
+export interface MatteBounds {
+ x0: number;
+ y0: number;
+ x1: number;
+ y1: number;
+}
+
+export class MatteCompositor {
+ private readonly pipeline: GPURenderPipeline;
+ private readonly sampler: GPUSampler;
+ private readonly uniforms: GPUBuffer[] = [];
+ private uniformIndex = 0;
+ /** One 8-bit mask texture per node, rewritten each frame. */
+ private readonly masks = new Map<string, GPUTexture>();
+
+ constructor(
+ private readonly device: GPUDevice,
+ format: GPUTextureFormat,
+ ) {
+ const module = device.createShaderModule({
+ label: "vision_matte_composite",
+ code: WGSL,
+ });
+ this.pipeline = device.createRenderPipeline({
+ label: "vision_matte_composite",
+ layout: "auto",
+ vertex: { module, entryPoint: "vs" },
+ fragment: { module, entryPoint: "fs", targets: [{ format }] },
+ primitive: { topology: "triangle-list" },
+ });
+ this.sampler = device.createSampler({
+ magFilter: "linear",
+ minFilter: "linear",
+ });
+ }
+
+ /** Uploads a frame-sized 0..255 mask for `key` and returns its texture. */
+ uploadMask(
+ key: string,
+ mask: Uint8Array,
+ width: number,
+ height: number,
+ ): GPUTexture {
+ let tex = this.masks.get(key);
+ if (!tex || tex.width !== width || tex.height !== height) {
+ tex?.destroy();
+ tex = this.device.createTexture({
+ label: `vision_mask_${key}`,
+ size: [width, height],
+ format: "r8unorm",
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
+ });
+ this.masks.set(key, tex);
+ }
+ const aligned = Math.ceil(width / 256) * 256;
+ let bytes = mask;
+ if (aligned !== width) {
+ bytes = new Uint8Array(aligned * height);
+ for (let y = 0; y < height; y++) {
+ bytes.set(mask.subarray(y * width, (y + 1) * width), y * aligned);
+ }
+ }
+ this.device.queue.writeTexture(
+ { texture: tex },
+ bytes.buffer,
+ { offset: bytes.byteOffset, bytesPerRow: aligned, rowsPerImage: height },
+ { width, height },
+ );
+ return tex;
+ }
+
+ /** Clears `target` and draws `picture` through `mask` into it. */
+ draw(
+ encoder: GPUCommandEncoder,
+ target: GPUTextureView,
+ picture: GPUTexture,
+ mask: GPUTexture,
+ mode: MatteMode,
+ bounds?: MatteBounds,
+ ): void {
+ const w = mask.width;
+ const h = mask.height;
+ const data = new Float32Array(8);
+ const view = new Uint32Array(data.buffer);
+ view[0] = mode === "matte" ? 0 : mode === "mask" ? 1 : 2;
+ if (mode === "crop" && bounds) {
+ data[2] = bounds.x0 / w;
+ data[3] = bounds.y0 / h;
+ data[4] = (bounds.x1 + 1) / w;
+ data[5] = (bounds.y1 + 1) / h;
+ } else {
+ data[2] = 0;
+ data[3] = 0;
+ data[4] = 1;
+ data[5] = 1;
+ if (mode === "crop") view[0] = 0;
+ }
+ // A small ring of uniform buffers: several vision nodes may draw in one frame.
+ if (this.uniformIndex >= this.uniforms.length) {
+ this.uniforms.push(
+ this.device.createBuffer({
+ size: data.byteLength,
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
+ }),
+ );
+ }
+ const uniform = this.uniforms[this.uniformIndex];
+ this.uniformIndex = (this.uniformIndex + 1) % 16;
+ this.device.queue.writeBuffer(uniform, 0, data);
+
+ const bindGroup = this.device.createBindGroup({
+ layout: this.pipeline.getBindGroupLayout(0),
+ entries: [
+ { binding: 0, resource: { buffer: uniform } },
+ { binding: 1, resource: picture.createView() },
+ { binding: 2, resource: mask.createView() },
+ { binding: 3, resource: this.sampler },
+ ],
+ });
+ const pass = encoder.beginRenderPass({
+ label: "vision_matte_composite",
+ colorAttachments: [
+ {
+ view: target,
+ loadOp: "clear",
+ storeOp: "store",
+ clearValue: { r: 0, g: 0, b: 0, a: 0 },
+ },
+ ],
+ });
+ pass.setPipeline(this.pipeline);
+ pass.setBindGroup(0, bindGroup);
+ pass.draw(3);
+ pass.end();
+ }
+}
diff --git a/nodes/node-vision/src/renderers/webgpu-renderer.ts b/nodes/node-vision/src/renderers/webgpu-renderer.ts
index c695589e..83b0898b 100644
--- a/nodes/node-vision/src/renderers/webgpu-renderer.ts
+++ b/nodes/node-vision/src/renderers/webgpu-renderer.ts
@@ -2,24 +2,36 @@
import type { WebGPUNodeRenderer } from "@gitframes/node-sdk";
import {
type InstanceMask,
- type MaskBounds,
maskBounds,
matchPoseToTracks,
mergeSubjectMask,
type PersonMatte,
type PoseResult,
PoseSkeletonRenderer,
- SegmentationTexturePool,
TemporalObjectTracker,
type TrackedObject,
type VisionBundle,
VisionRunner,
} from "@gitframes/vision";
import type { VisionOperation } from "../shared/config.js";
+import {
+ fromCachedMask,
+ toCachedMask,
+ VisionFrameCache,
+} from "./frame-cache.js";
+import { MatteCompositor } from "./matte-compositor.js";
let sharedRunner: { key: string; runner: VisionRunner } | null = null;
let sharedSkeletonRenderer: PoseSkeletonRenderer | null = null;
-let sharedTexturePool: SegmentationTexturePool | null = null;
+let sharedCompositor: MatteCompositor | null = null;
+let sharedCompositorFormat: GPUTextureFormat | null = null;
+/** Analysed frames, shared by every vision node in the process. */
+const frameCache = new VisionFrameCache();
+/** The frame each node's child texture holds (drawn on its last call). */
+const heldFrameByNode = new Map<string, number>();
+/** Per node: a copy of the held frame, and the composited matte. */
+const heldTextures = new Map<string, GPUTexture>();
+const matteTextures = new Map<string, GPUTexture>();
/** One tracker per vision node — track ids must not mix across nodes/sources. */
const objectTrackers = new Map<string, TemporalObjectTracker>();
@@ -47,6 +59,119 @@ const lastSubjectByNode = new Map<
>();
const SUBJECT_HOLD_FRAMES = 3;
+/** A per-node texture shaped like `like`, recreated when the size changes. */
+function nodeTexture(
+ textures: Map<string, GPUTexture>,
+ device: GPUDevice,
+ key: string,
+ like: GPUTexture,
+ usage: number,
+ label: string,
+): GPUTexture {
+ let tex = textures.get(key);
+ if (
+ !tex ||
+ tex.width !== like.width ||
+ tex.height !== like.height ||
+ tex.format !== like.format
+ ) {
+ tex?.destroy();
+ tex = device.createTexture({
+ size: [like.width, like.height],
+ format: like.format,
+ usage,
+ label,
+ });
+ textures.set(key, tex);
+ }
+ return tex;
+}
+
+const heldTexture = (device: GPUDevice, key: string, like: GPUTexture) =>
+ nodeTexture(
+ heldTextures,
+ device,
+ key,
+ like,
+ GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_BINDING,
+ "vision_held_frame",
+ );
+
+const matteTexture = (device: GPUDevice, key: string, like: GPUTexture) =>
+ nodeTexture(
+ matteTextures,
+ device,
+ key,
+ like,
+ GPUTextureUsage.RENDER_ATTACHMENT |
+ GPUTextureUsage.TEXTURE_BINDING |
+ GPUTextureUsage.COPY_SRC,
+ "vision_matte",
+ );
+
+/** Everything that decides a frame's results besides the frame itself. */
+function cacheSource(
+ nodeKey: string,
+ child: unknown,
+ op: VisionOperation,
+ width: number,
+ height: number,
+): string {
+ const c = child as { id?: unknown; operation?: { id?: unknown } } | undefined;
+ return JSON.stringify([
+ nodeKey,
+ c?.operation?.id ?? c?.id ?? null,
+ width,
+ height,
+ op.mode ?? "passthrough",
+ op.variant,
+ op.confidence,
+ op.classes,
+ op.maskThreshold,
+ op.featherRadius,
+ op.matteSource,
+ op.keyBackground === true,
+ op.maxMissedFrames,
+ ]);
+}
+
+/** The background-key threshold at `frame` (it may be animated). */
+function backgroundKeyThreshold(
+ op: VisionOperation,
+ frame: number,
+ fps: number,
+): number {
+ const raw = (op as Record<string, unknown>).backgroundKeyThreshold;
+ if (typeof raw === "number") return raw;
+ if (typeof (raw as { get?: unknown })?.get === "function") {
+ return Number(
+ (raw as { get: (ctx?: unknown) => unknown }).get({ frame, fps }),
+ );
+ }
+ if (typeof (raw as { _value?: unknown })?._value === "number") {
+ return Number((raw as { _value: number })._value);
+ }
+ return 70;
+}
+
+/**
+ * The model's subject, or the last one through brief misses: a transient miss
+ * then holds the silhouette instead of flashing the raw plate.
+ */
+function selectSubject(
+ selected: InstanceMask | undefined,
+ nodeKey: string,
+ frame: number,
+): InstanceMask | undefined {
+ if (selected) {
+ lastSubjectByNode.set(nodeKey, { mask: selected, frame });
+ return selected;
+ }
+ const last = lastSubjectByNode.get(nodeKey);
+ if (last && frame - last.frame <= SUBJECT_HOLD_FRAMES) return last.mask;
+ return undefined;
+}
+
/**
* Lazy shared runner — `create()` is a pure constructor (zero I/O); the first frame that
* requests a task triggers that task's model download at inference time (never at init).
@@ -137,38 +262,52 @@ function fillInternalHoles(
width: number,
height: number,
): void {
- const exterior = new Uint8Array(width * height);
- const queue: number[] = [];
-
- const tryPushBg = (x: number, y: number) => {
- if (x < 0 || y < 0 || x >= width || y >= height) return;
- const idx = y * width + x;
- if (exterior[idx] || mask[idx] > 0) return;
- exterior[idx] = 1;
- queue.push(idx);
+ // Flood the background in from the border; whatever it cannot reach is a hole.
+ const n = width * height;
+ const exterior = new Uint8Array(n);
+ const queue = new Int32Array(n);
+ let tail = 0;
+ const seed = (i: number) => {
+ if (exterior[i] || mask[i] > 0) return;
+ exterior[i] = 1;
+ queue[tail++] = i;
};
-
for (let x = 0; x < width; x++) {
- tryPushBg(x, 0);
- tryPushBg(x, height - 1);
+ seed(x);
+ seed((height - 1) * width + x);
}
for (let y = 0; y < height; y++) {
- tryPushBg(0, y);
- tryPushBg(width - 1, y);
+ seed(y * width);
+ seed(y * width + width - 1);
}
let head = 0;
- while (head < queue.length) {
- const idx = queue[head++];
- const x = idx % width;
- const y = (idx / width) | 0;
- tryPushBg(x + 1, y);
- tryPushBg(x - 1, y);
- tryPushBg(x, y + 1);
- tryPushBg(x, y - 1);
+ while (head < tail) {
+ const i = queue[head++];
+ const x = i % width;
+ let j = i + 1;
+ if (x + 1 < width && !exterior[j] && mask[j] === 0) {
+ exterior[j] = 1;
+ queue[tail++] = j;
+ }
+ j = i - 1;
+ if (x > 0 && !exterior[j] && mask[j] === 0) {
+ exterior[j] = 1;
+ queue[tail++] = j;
+ }
+ j = i + width;
+ if (j < n && !exterior[j] && mask[j] === 0) {
+ exterior[j] = 1;
+ queue[tail++] = j;
+ }
+ j = i - width;
+ if (j >= 0 && !exterior[j] && mask[j] === 0) {
+ exterior[j] = 1;
+ queue[tail++] = j;
+ }
}
- for (let i = 0; i < mask.length; i++) {
+ for (let i = 0; i < n; i++) {
if (mask[i] === 0 && exterior[i] === 0) {
mask[i] = 255;
}
@@ -202,18 +341,20 @@ function smoothMaskBoundary(
}
}
- // Vertical box filter
- for (let x = 0; x < width; x++) {
- let sum = 0;
- for (let k = -radius; k <= radius; k++) {
- const y = Math.max(0, Math.min(height - 1, k));
- sum += temp[y * width + x];
- }
- for (let y = 0; y < height; y++) {
- out[y * width + x] = Math.round(sum / div);
- const yOut = Math.max(0, y - radius);
- const yIn = Math.min(height - 1, y + radius + 1);
- sum += temp[yIn * width + x] - temp[yOut * width + x];
+ // Vertical box filter, a running sum per column walked row by row
+ // (in memory order).
+ const sums = new Float64Array(width);
+ for (let k = -radius; k <= radius; k++) {
+ const row = Math.max(0, Math.min(height - 1, k)) * width;
+ for (let x = 0; x < width; x++) sums[x] += temp[row + x];
+ }
+ for (let y = 0; y < height; y++) {
+ const row = y * width;
+ const rowOut = Math.max(0, y - radius) * width;
+ const rowIn = Math.min(height - 1, y + radius + 1) * width;
+ for (let x = 0; x < width; x++) {
+ out[row + x] = Math.round(sums[x] / div);
+ sums[x] += temp[rowIn + x] - temp[rowOut + x];
}
}
@@ -232,7 +373,7 @@ function growMaskIntoForeground(
let br = 0;
let bg = 0;
let bb = 0;
- let n = 0;
+ let count = 0;
const sample = (x: number, y: number) => {
const i = y * width + x;
if (mask[i]) return;
@@ -240,7 +381,7 @@ function growMaskIntoForeground(
br += pixels[p];
bg += pixels[p + 1];
bb += pixels[p + 2];
- n++;
+ count++;
};
for (let x = 0; x < width; x += 4) {
sample(x, 0);
@@ -250,48 +391,60 @@ function growMaskIntoForeground(
sample(0, y);
sample(width - 1, y);
}
- if (n === 0) return mask;
- br /= n;
- bg /= n;
- bb /= n;
-
- const isForeground = (i: number): boolean => {
- const p = i * 4;
- return (
+ if (count === 0) return mask;
+ br /= count;
+ bg /= count;
+ bb /= count;
+
+ // Pixels that stand out from the backdrop, decided once per pixel.
+ const n = width * height;
+ const fg = new Uint8Array(n);
+ for (let i = 0, p = 0; i < n; i++, p += 4) {
+ fg[i] =
Math.max(
Math.abs(pixels[p] - br),
Math.abs(pixels[p + 1] - bg),
Math.abs(pixels[p + 2] - bb),
) > threshold
- );
- };
+ ? 1
+ : 0;
+ }
- const queue: number[] = [];
- for (let i = 0; i < mask.length; i++) {
+ // Each pixel enters the queue at most once: seeds are the masked pixels,
+ // later pushes are pixels just raised to 255.
+ const queue = new Int32Array(n);
+ let tail = 0;
+ for (let i = 0; i < n; i++) {
if (mask[i] > 0) {
- if (isForeground(i)) {
- mask[i] = 255;
- }
- queue.push(i);
+ if (fg[i]) mask[i] = 255;
+ queue[tail++] = i;
}
}
let head = 0;
- while (head < queue.length) {
+ while (head < tail) {
const i = queue[head++];
const x = i % width;
- const y = (i / width) | 0;
- const tryPush = (nx: number, ny: number) => {
- if (nx < 0 || ny < 0 || nx >= width || ny >= height) return;
- const ni = ny * width + nx;
- if (mask[ni] === 255 || !isForeground(ni)) return;
- mask[ni] = 255;
- queue.push(ni);
- };
- tryPush(x + 1, y);
- tryPush(x - 1, y);
- tryPush(x, y + 1);
- tryPush(x, y - 1);
+ let j = i + 1;
+ if (x + 1 < width && mask[j] !== 255 && fg[j]) {
+ mask[j] = 255;
+ queue[tail++] = j;
+ }
+ j = i - 1;
+ if (x > 0 && mask[j] !== 255 && fg[j]) {
+ mask[j] = 255;
+ queue[tail++] = j;
+ }
+ j = i + width;
+ if (j < n && mask[j] !== 255 && fg[j]) {
+ mask[j] = 255;
+ queue[tail++] = j;
+ }
+ j = i - width;
+ if (j >= 0 && mask[j] !== 255 && fg[j]) {
+ mask[j] = 255;
+ queue[tail++] = j;
+ }
}
fillInternalHoles(mask, width, height);
@@ -395,9 +548,67 @@ export const VisionWebGPURenderer: WebGPUNodeRenderer = async (args) => {
}
}
- // 2. Read back the PREVIOUS frame's child pixels for inference.
+ const frameIdx = props.frame ?? 0;
+ const fps = props.fps ?? 24;
+ const mode = op.mode ?? "passthrough";
+ const isMatteMode = mode === "mask" || mode === "matte" || mode === "crop";
+ const visionBundle =
+ (op.visionBundle as VisionBundle | undefined) ??
+ ((virtualMedia as Record<string, unknown>).visionBundle as
+ | VisionBundle
+ | undefined);
+ const wantsDetection =
+ op.enableDetection !== false || mode === "boxes" || mode === "tracking";
+ const wantsSegmentation =
+ op.enableSegmentation === true ||
+ (isMatteMode && op.matteSource !== "selfie");
+ const wantsSelfie =
+ op.enableMatte === true || (isMatteMode && op.matteSource === "selfie");
+ const wantsPose = op.enablePose === true || mode === "skeleton";
+
+ // 2. Results are cached per source frame (selfie mattes and poses are not,
+ // so nodes that need them always run inference). A frame analysed before
+ // is composited with its own pixels; otherwise inference runs on the
+ // frame the child texture still holds, one frame behind.
+ const cacheable =
+ !wantsSelfie && !wantsPose && (wantsDetection || wantsSegmentation);
+ const source = cacheable
+ ? cacheSource(nodeKeyStr, childMedia, op, targetWidth, targetHeight)
+ : "";
+ const keyThresholdAt = (frame: number) =>
+ op.keyBackground === true
+ ? backgroundKeyThreshold(op, frame, fps)
+ : undefined;
+ const lookup = (frame: number | undefined) => {
+ if (!cacheable || frame === undefined) return undefined;
+ const hit = frameCache.get(source, frame);
+ if (!hit || hit.keyThreshold !== keyThresholdAt(frame)) return undefined;
+ // Results cached without instance masks can't feed a bundle that wants them.
+ if (wantsSegmentation && visionBundle && !hit.masks) return undefined;
+ return hit;
+ };
+ const heldFrame = hasPreviousFrame
+ ? heldFrameByNode.get(nodeKeyStr)
+ : undefined;
+ let cached = lookup(frameIdx);
+ const exact = cached !== undefined;
+ if (!cached) cached = lookup(heldFrame);
+
+ // Keep the held frame's picture on the GPU: the matte of that frame is
+ // composited from it after the child texture is redrawn below.
+ let heldTex: GPUTexture | undefined;
+ if (isMatteMode && hasPreviousFrame && !exact) {
+ heldTex = heldTexture(ctx.device, nodeKeyStr, childTex);
+ encoder.copyTextureToTexture({ texture: childTex }, { texture: heldTex }, [
+ targetWidth,
+ targetHeight,
+ 1,
+ ]);
+ }
+
+ // 3. Read back the held frame's pixels, only when it still needs inference.
let framePixels: Uint8ClampedArray | null = null;
- if (hasPreviousFrame) {
+ if (hasPreviousFrame && !cached) {
const bytesPerPixel = 4;
const unalignedBytesPerRow = targetWidth * bytesPerPixel;
const bytesPerRow = Math.ceil(unalignedBytesPerRow / 256) * 256;
@@ -439,7 +650,7 @@ export const VisionWebGPURenderer: WebGPUNodeRenderer = async (args) => {
stagingBuffer.destroy();
}
- // 3. Draw THIS frame's child into the persistent texture (recorded into the
+ // 4. Draw THIS frame's child into the persistent texture (recorded into the
// shared encoder, submitted at end of frame, read back next call).
const childView = childTex.createView();
const clearPass = ctx.renderer.beginFrame(
@@ -460,112 +671,130 @@ export const VisionWebGPURenderer: WebGPUNodeRenderer = async (args) => {
targetWidth,
targetHeight,
);
+ heldFrameByNode.set(nodeKeyStr, frameIdx);
- // 4. Inference on the previous frame's pixels (models download lazily on first
- // use of each task). Results are therefore one frame behind the plate.
- const frameIdx = props.frame ?? 0;
- const fps = props.fps ?? 24;
- const mode = op.mode ?? "passthrough";
- const isMatteMode = mode === "mask" || mode === "matte" || mode === "crop";
- const visionBundle =
- (op.visionBundle as VisionBundle | undefined) ??
- ((virtualMedia as Record<string, unknown>).visionBundle as
- | VisionBundle
- | undefined);
- const runner = getSharedRunner(op);
- const image = framePixels
- ? { data: framePixels, width: targetWidth, height: targetHeight }
- : null;
-
- // detect + segment share one RTMDet-Ins pass per frame inside the runner.
- // Tracked objects are kept locally (like masks below) so `boxes` / `tracking`
- // draw even without an attached visionBundle.
+ // 5. Results: from the cache, or inference on the held frame's pixels
+ // (models download lazily on first use of each task).
let frameObjects: readonly TrackedObject[] = [];
- if (
- image &&
- (op.enableDetection !== false || mode === "boxes" || mode === "tracking")
- ) {
- const detections = await runner.detect(image);
- const tracker = getObjectTracker(nodeKeyStr, op);
- if (frameIdx === 0) {
- tracker.reset();
- }
- frameObjects = tracker.update(detections, frameIdx, fps);
- visionBundle?.setObjectResult(frameIdx, {
- objects: frameObjects,
- rawDetections: detections,
- });
- }
-
- // Decoded masks are kept locally so mask-family modes render even without an
- // attached visionBundle (the round-trip through the bundle is for signal DX).
let frameMasks: readonly InstanceMask[] = [];
- if (
- image &&
- (op.enableSegmentation === true ||
- (isMatteMode && op.matteSource !== "selfie"))
- ) {
- const segRes = await runner.segment(image);
- frameMasks = assignMasksToTracks(segRes.masks, frameObjects);
- visionBundle?.setMaskResult(frameIdx, frameMasks);
- }
-
let personMatte: PersonMatte | undefined;
- if (
- image &&
- (op.enableMatte === true || (isMatteMode && op.matteSource === "selfie"))
- ) {
- personMatte = await runner.matte(image);
- visionBundle?.setMatteResult(frameIdx, personMatte);
- }
-
let currentPoseRes: PoseResult | undefined;
- if (image && (op.enablePose === true || mode === "skeleton")) {
- const poseRes = await runner.pose(image);
- const normalized = normalizePoseKeypoints(
- poseRes,
- image.width,
- image.height,
- );
- currentPoseRes = {
- people: matchPoseToTracks(normalized.people, frameObjects),
+ let subject: InstanceMask | undefined;
+
+ if (cached) {
+ frameObjects = cached.objects;
+ if (wantsDetection) {
+ visionBundle?.setObjectResult(frameIdx, {
+ objects: cached.objects,
+ rawDetections: cached.detections,
+ });
+ }
+ if (wantsSegmentation && visionBundle && cached.masks) {
+ frameMasks = cached.masks.map(fromCachedMask);
+ visionBundle.setMaskResult(frameIdx, frameMasks);
+ }
+ if (cached.subject) {
+ subject = fromCachedMask(cached.subject.mask);
+ lastSubjectByNode.set(nodeKeyStr, { mask: subject, frame: frameIdx });
+ }
+ } else if (framePixels) {
+ const runner = getSharedRunner(op);
+ const image = {
+ data: framePixels,
+ width: targetWidth,
+ height: targetHeight,
};
- visionBundle?.setPoseResult(frameIdx, currentPoseRes);
- }
- // 5. Output to destination texture based on mode
+ // detect + segment share one RTMDet-Ins pass per frame inside the runner.
+ // Tracked objects are kept locally (like masks below) so `boxes` /
+ // `tracking` draw even without an attached visionBundle.
+ let detections: Awaited<ReturnType<VisionRunner["detect"]>> = [];
+ if (wantsDetection) {
+ detections = await runner.detect(image);
+ const tracker = getObjectTracker(nodeKeyStr, op);
+ if (frameIdx === 0) {
+ tracker.reset();
+ }
+ frameObjects = tracker.update(detections, frameIdx, fps);
+ visionBundle?.setObjectResult(frameIdx, {
+ objects: frameObjects,
+ rawDetections: detections,
+ });
+ }
- // Mask-family modes composite from CPU pixels we already hold (frame + masks)
- if (isMatteMode) {
- if (!sharedTexturePool) {
- sharedTexturePool = new SegmentationTexturePool(ctx.device);
+ // Decoded masks are kept locally so mask-family modes render even without
+ // an attached visionBundle (the round-trip through the bundle is for signal DX).
+ if (wantsSegmentation) {
+ const segRes = await runner.segment(image);
+ frameMasks = assignMasksToTracks(segRes.masks, frameObjects);
+ visionBundle?.setMaskResult(frameIdx, frameMasks);
}
- const selected =
- op.matteSource === "selfie"
- ? personMatteAsMask(personMatte)
- : mergeSubjectMask(
- frameMasks.length > 0
- ? frameMasks
- : (visionBundle?.getMaskResult(frameIdx) ?? []),
- );
- let subject: InstanceMask | undefined;
- const lastSubjectEntry = lastSubjectByNode.get(nodeKeyStr);
- const lastSubjectMask = lastSubjectEntry?.mask ?? null;
- const lastSubjectFrame =
- lastSubjectEntry?.frame ?? Number.NEGATIVE_INFINITY;
-
- if (selected) {
- subject = selected;
- lastSubjectByNode.set(nodeKeyStr, { mask: selected, frame: frameIdx });
- } else if (
- lastSubjectMask &&
- frameIdx - lastSubjectFrame <= SUBJECT_HOLD_FRAMES
- ) {
- // Hold the last silhouette through brief model misses; otherwise stay
- // transparent rather than flashing the raw plate over the smoke.
- subject = lastSubjectMask;
+
+ if (wantsSelfie) {
+ personMatte = await runner.matte(image);
+ visionBundle?.setMatteResult(frameIdx, personMatte);
+ }
+
+ if (wantsPose) {
+ const poseRes = await runner.pose(image);
+ const normalized = normalizePoseKeypoints(
+ poseRes,
+ image.width,
+ image.height,
+ );
+ currentPoseRes = {
+ people: matchPoseToTracks(normalized.people, frameObjects),
+ };
+ visionBundle?.setPoseResult(frameIdx, currentPoseRes);
+ }
+
+ if (isMatteMode) {
+ subject = selectSubject(
+ op.matteSource === "selfie"
+ ? personMatteAsMask(personMatte)
+ : mergeSubjectMask(
+ frameMasks.length > 0
+ ? frameMasks
+ : (visionBundle?.getMaskResult(frameIdx) ?? []),
+ ),
+ nodeKeyStr,
+ frameIdx,
+ );
+ // Opt-in: grow the subject into connected pixels that stand out from
+ // the backdrop (catches edges the model's soft mask leaves behind).
+ const threshold = keyThresholdAt(heldFrame ?? frameIdx);
+ if (subject && threshold !== undefined) {
+ subject = {
+ ...subject,
+ mask: growMaskIntoForeground(
+ subject.mask,
+ subject.width,
+ subject.height,
+ framePixels,
+ threshold,
+ op.featherRadius,
+ ),
+ };
+ }
+ }
+
+ if (cacheable && heldFrame !== undefined) {
+ frameCache.set(source, heldFrame, {
+ detections,
+ objects: frameObjects,
+ masks: visionBundle ? frameMasks.map(toCachedMask) : null,
+ subject: subject ? { mask: toCachedMask(subject) } : null,
+ keyThreshold: keyThresholdAt(heldFrame),
+ });
}
- if (!subject || !framePixels) {
+ }
+
+ // 6. Output to destination texture based on mode
+
+ // Mask-family modes: the picture the results belong to, cut out on the GPU.
+ if (isMatteMode) {
+ const picture = exact ? childTex : heldTex;
+ if (!subject || !picture) {
const outPass = ctx.renderer.beginFrame(
encoder,
targetView,
@@ -578,49 +807,26 @@ export const VisionWebGPURenderer: WebGPUNodeRenderer = async (args) => {
return;
}
- // Opt-in: grow the subject into connected pixels that stand out from the
- // backdrop (catches edges the model's soft mask leaves behind).
- if (op.keyBackground === true) {
- const rawThreshold = (op as Record<string, unknown>)
- .backgroundKeyThreshold;
- const threshold =
- typeof rawThreshold === "number"
- ? rawThreshold
- : typeof (rawThreshold as { get?: unknown })?.get === "function"
- ? Number(
- (rawThreshold as { get: (ctx?: unknown) => unknown }).get({
- frame: frameIdx,
- fps: props.fps ?? 30,
- }),
- )
- : typeof (rawThreshold as { _value?: unknown })?._value === "number"
- ? Number((rawThreshold as { _value: number })._value)
- : 70;
- const grownMask = growMaskIntoForeground(
- subject.mask,
- subject.width,
- subject.height,
- framePixels,
- threshold,
- op.featherRadius,
- );
- subject = {
- ...subject,
- mask: grownMask,
- };
+ if (!sharedCompositor || sharedCompositorFormat !== ctx.renderer.format) {
+ sharedCompositor = new MatteCompositor(ctx.device, ctx.renderer.format);
+ sharedCompositorFormat = ctx.renderer.format;
}
-
- const maskTex = uploadComposite(
- sharedTexturePool,
- mode,
- subject,
- framePixels,
- targetWidth,
- targetHeight,
- frameIdx,
+ const maskTex = sharedCompositor.uploadMask(
nodeKeyStr,
+ subject.mask,
+ subject.width,
+ subject.height,
+ );
+ const matteTex = matteTexture(ctx.device, nodeKeyStr, childTex);
+ sharedCompositor.draw(
+ encoder,
+ matteTex.createView(),
+ picture,
+ maskTex,
+ mode,
+ mode === "crop" ? (maskBounds(subject) ?? undefined) : undefined,
);
- visionBundle?.setStencilTexture(maskTex);
+ visionBundle?.setStencilTexture(matteTex);
const outPass = ctx.renderer.beginFrame(
encoder,
@@ -630,7 +836,7 @@ export const VisionWebGPURenderer: WebGPUNodeRenderer = async (args) => {
targetHeight,
"clear",
);
- ctx.renderer.drawTexture(outPass, maskTex, {
+ ctx.renderer.drawTexture(outPass, matteTex, {
x: 0,
y: 0,
width: targetWidth,
@@ -773,90 +979,6 @@ export const VisionWebGPURenderer: WebGPUNodeRenderer = async (args) => {
outPass.end();
};
-/**
- * Builds the RGBA output bytes for mask-family modes from pixels we already hold:
- * - mask: white silhouette (r=g=b=mask, a=255)
- * - matte: child pixels × subject mask (isolate)
- * - crop: matte, fitted to the subject bounding box
- */
-function uploadComposite(
- pool: SegmentationTexturePool,
- mode: "mask" | "matte" | "crop",
- subject: InstanceMask,
- framePixels: Uint8ClampedArray,
- width: number,
- height: number,
- frameIdx: number,
- nodeKeyStr = "default",
-): GPUTexture {
- const mask = subject.mask;
- const out = new Uint8Array(width * height * 4);
-
- for (let i = 0; i < mask.length; i++) {
- const a = mask[i];
- const px = i * 4;
- if (mode === "mask") {
- out[px] = a;
- out[px + 1] = a;
- out[px + 2] = a;
- out[px + 3] = 255;
- } else {
- // matte & crop: premultiply child RGBA by the subject mask so the
- // background is genuinely transparent (composites over smoke/plates)
- const alpha = (framePixels[px + 3] * a) >> 8;
- out[px] = (framePixels[px] * alpha) >> 8;
- out[px + 1] = (framePixels[px + 1] * alpha) >> 8;
- out[px + 2] = (framePixels[px + 2] * alpha) >> 8;
- out[px + 3] = alpha;
- }
- }
-
- const key = `vision_composite_${nodeKeyStr}_${mode}_${frameIdx}`;
- const tex = pool.uploadMask(key, out, width, height);
-
- if (mode === "crop") {
- // Punch in: stretch the subject's bounds to fill the frame.
- const box = maskBounds(subject);
- if (box) {
- return pool.uploadMask(
- `vision_crop_${nodeKeyStr}_${frameIdx}`,
- cropToBounds(out, width, height, box),
- width,
- height,
- );
- }
- }
-
- return tex;
-}
-
-/** Nearest-neighbour resample of `bounds` inside an RGBA frame up to the full frame. */
-function cropToBounds(
- rgba: Uint8Array,
- width: number,
- height: number,
- bounds: MaskBounds,
-): Uint8Array {
- const cropW = bounds.x1 - bounds.x0 + 1;
- const cropH = bounds.y1 - bounds.y0 + 1;
- const crop = new Uint8Array(width * height * 4);
- for (let y = 0; y < height; y++) {
- const srcY =
- bounds.y0 + Math.min(cropH - 1, Math.floor((y / height) * cropH));
- for (let x = 0; x < width; x++) {
- const srcX =
- bounds.x0 + Math.min(cropW - 1, Math.floor((x / width) * cropW));
- const src = (srcY * width + srcX) * 4;
- const dst = (y * width + x) * 4;
- crop[dst] = rgba[src];
- crop[dst + 1] = rgba[src + 1];
- crop[dst + 2] = rgba[src + 2];
- crop[dst + 3] = rgba[src + 3];
- }
- }
- return crop;
-}
-
/** Adapts a Selfie Segmenter matte to the instance-mask shape the composite path takes. */
function personMatteAsMask(
matte: PersonMatte | undefined,
diff --git a/package.json b/package.json
index 7fd9795e..f790cfe9 100644
--- a/package.json
+++ b/package.json
@@ -174,7 +174,16 @@
"hono@>=4.12.0 <4.12.34": ">=4.12.34",
"nanoid@>=4.0.0 <5.1.16": ">=5.1.16",
"nanoid@<3.3.16": ">=3.3.16",
- "nanoid@<3.3.17": ">=3.3.17"
+ "nanoid@<3.3.17": ">=3.3.17",
+ "undici@>=7.0.0 <7.29.1": ">=7.29.1 <8.0.0",
+ "js-yaml@<3.15.2": "^3.15.2",
+ "js-yaml@>=4.0.0 <4.3.2": "^4.3.2",
+ "smol-toml@<1.7.1": "^1.7.1",
+ "hono@<4.13.7": ">=4.13.7",
+ "fflate@<0.8.3": "^0.8.3",
+ "sharp@<0.35.4": "^0.35.4",
+ "vitest@<4.1.11": "^4.1.11",
+ "@vitest/mocker@<4.1.11": "^4.1.11"
},
"onlyBuiltDependencies": [
"@swc/core",
diff --git a/packages/compositions/src/program/animation.ts b/packages/compositions/src/program/animation.ts
index acdc9b56..56716a54 100644
--- a/packages/compositions/src/program/animation.ts
+++ b/packages/compositions/src/program/animation.ts
@@ -536,28 +536,6 @@ export class LayerAnimation implements LayerAnimationSpec {
});
}
- /**
- * Animates chart write-on draw progress from fromVal to toVal.
- */
- public drawProgress(
- fromVal = 0,
- toVal = 1,
- options: FromToOptions = {},
- ): this {
- return this.fromTo("drawProgress", fromVal, toVal, options);
- }
-
- /**
- * Animates chartProgress from fromVal to toVal.
- */
- public chartProgress(
- fromVal = 0,
- toVal = 1,
- options: FromToOptions = {},
- ): this {
- return this.fromTo("chartProgress", fromVal, toVal, options);
- }
-
/**
* Slides in Y coordinate from fromY to toY.
*/
diff --git a/packages/compositions/src/program/schema.test.ts b/packages/compositions/src/program/schema.test.ts
index 7c14629f..a6348904 100644
--- a/packages/compositions/src/program/schema.test.ts
+++ b/packages/compositions/src/program/schema.test.ts
@@ -924,69 +924,6 @@ describe("validateLayoutProgram (E-code pre-parse scan)", () => {
expect(parsedInvalid.success).toBe(false);
});
- it("parses valid chart layout node with chartOptions and drawProgress animation", () => {
- const doc = {
- width: 1920,
- height: 1080,
- layout: [
- {
- id: "chart-1",
- kind: "chart",
- chartOptions: {
- theme: "dark",
- xAxis: { type: "category" },
- yAxis: { type: "value" },
- series: [
- {
- type: "line",
- data: [
- [0, 10],
- [1, 25],
- [2, 50],
- ],
- lineStyle: {
- color: "#3b82f6",
- width: 3,
- },
- areaStyle: {
- gradient: {
- direction: "vertical",
- stops: [
- { offset: 0, color: "rgba(59, 130, 246, 0.5)" },
- { offset: 1, color: "rgba(59, 130, 246, 0.0)" },
- ],
- },
- },
- },
- ],
- },
- animation: {
- tracks: [
- {
- id: "t-draw-progress",
- prop: "drawProgress",
- keyframes: [
- { id: "kf0", frame: 0, value: 0 },
- { id: "kf1", frame: 30, value: 1 },
- ],
- },
- ],
- },
- },
- ],
- };
-
- const parsed = CompositorProgramSchema.safeParse(doc);
- expect(parsed.success).toBe(true);
- if (parsed.success) {
- const chartNode = parsed.data.layout[0] as any;
- expect(chartNode.kind).toBe("chart");
- expect(chartNode.chartOptions.series[0].type).toBe("line");
- expect(chartNode.chartOptions.series[0].lineStyle.width).toBe(3);
- expect(chartNode.animation.tracks[0].prop).toBe("drawProgress");
- }
- });
-
it("accepts a per-node effect chain on media and box nodes", () => {
const doc = {
width: 1080,
diff --git a/packages/compositions/src/program/schema.ts b/packages/compositions/src/program/schema.ts
index b62861f8..0233eb81 100644
--- a/packages/compositions/src/program/schema.ts
+++ b/packages/compositions/src/program/schema.ts
@@ -110,10 +110,6 @@ export const AnimatablePropSchema = z.enum([
"translateZ",
"perspectiveOriginX",
"perspectiveOriginY",
- // Chart properties
- "progress",
- "drawProgress",
- "chartProgress",
// 3D Camera & Scene properties
"cameraX",
"cameraY",
@@ -438,10 +434,7 @@ const animationInvariants = (
} else if (
(track.prop === "volume" ||
track.prop === "trimStart" ||
- track.prop === "trimEnd" ||
- track.prop === "progress" ||
- track.prop === "drawProgress" ||
- track.prop === "chartProgress") &&
+ track.prop === "trimEnd") &&
((kf.value as number) < 0 || (kf.value as number) > 1)
) {
ctx.addIssue({
@@ -950,13 +943,6 @@ export interface ShapeNode extends CompositionNodeBase {
trimOffset?: number;
}
-export interface ChartNode extends CompositionNodeBase {
- kind: "chart";
- chartOptions: ChartGPUOptions;
- progress?: number;
- drawProgress?: number;
-}
-
export const CameraLensSchema = z
.object({
focalLength: z.number().min(5).max(500).default(50),
@@ -1154,7 +1140,6 @@ export type LayoutNode =
| TextNode
| MediaNode
| ShapeNode
- | ChartNode
| CameraNode
| LightNode
| Model3DNode;
@@ -1399,179 +1384,12 @@ export const ShapeNodeSchema: z.ZodType<ShapeNode> = z
})
.strict() as unknown as z.ZodType<ShapeNode>;
-export const ChartSeriesTypeSchema = z.enum([
- "line",
- "area",
- "bar",
- "candlestick",
- "ohlc",
- "pie",
- "heatmap",
- "band",
- "errorBar",
- "impulse",
- "pointCloud3d",
- "surface3d",
-]);
-export type ChartSeriesType = z.infer<typeof ChartSeriesTypeSchema>;
-
export const ColorStopSchema = z.object({
offset: z.number().min(0).max(1),
color: z.string(),
});
export type ColorStop = z.infer<typeof ColorStopSchema>;
-export const ChartLineStyleSchema = z
- .object({
- color: z.string().default("#3b82f6"),
- width: z.number().min(0.5).default(2),
- smooth: z.boolean().default(true),
- dash: z.array(z.number()).optional(),
- opacity: z.number().min(0).max(1).default(1),
- })
- .strict();
-export type ChartLineStyle = z.infer<typeof ChartLineStyleSchema>;
-
-export const ChartAreaStyleSchema = z
- .object({
- color: z.string().optional(),
- gradient: z
- .object({
- direction: z.enum(["vertical", "horizontal"]).default("vertical"),
- stops: z.array(ColorStopSchema).min(2),
- })
- .optional(),
- opacity: z.number().min(0).max(1).default(0.35),
- })
- .strict();
-export type ChartAreaStyle = z.infer<typeof ChartAreaStyleSchema>;
-
-export const ChartPointStyleSchema = z
- .object({
- show: z.boolean().default(false),
- size: z.number().min(1).default(4),
- color: z.string().optional(),
- shape: z.enum(["circle", "square", "diamond"]).default("circle"),
- })
- .strict();
-export type ChartPointStyle = z.infer<typeof ChartPointStyleSchema>;
-
-export const ChartDataPoint2DSchema = z.union([
- z.tuple([z.number(), z.number()]),
- z.object({ x: z.number(), y: z.number() }),
-]);
-export type ChartDataPoint2D = z.infer<typeof ChartDataPoint2DSchema>;
-
-export const ChartDataPointOHLCSchema = z.union([
- z.tuple([z.number(), z.number(), z.number(), z.number(), z.number()]),
- z.object({
- timestamp: z.number(),
- open: z.number(),
- high: z.number(),
- low: z.number(),
- close: z.number(),
- }),
-]);
-export type ChartDataPointOHLC = z.infer<typeof ChartDataPointOHLCSchema>;
-
-export const ChartSeriesSchema = z
- .object({
- id: z.string().optional(),
- name: z.string().optional(),
- type: ChartSeriesTypeSchema.default("line"),
- data: z.union([
- z.array(ChartDataPoint2DSchema),
- z.array(ChartDataPointOHLCSchema),
- z.array(z.number()),
- ]),
- lineStyle: ChartLineStyleSchema.optional(),
- areaStyle: ChartAreaStyleSchema.optional(),
- itemStyle: ChartPointStyleSchema.optional(),
- yAxisIndex: z.number().int().min(0).default(0),
- visible: z.boolean().default(true),
- progress: z.number().min(0).max(1).default(1),
- })
- .strict();
-export type ChartSeries = z.infer<typeof ChartSeriesSchema>;
-
-export const ChartAxisSchema = z
- .object({
- id: z.string().optional(),
- type: z.enum(["value", "category", "time", "log"]).default("value"),
- show: z.boolean().default(true),
- min: z.number().optional(),
- max: z.number().optional(),
- grid: z
- .object({
- show: z.boolean().default(true),
- color: z.string().default("rgba(255, 255, 255, 0.08)"),
- width: z.number().default(1),
- dash: z.array(z.number()).optional(),
- })
- .optional(),
- line: z
- .object({
- show: z.boolean().default(true),
- color: z.string().default("rgba(255, 255, 255, 0.2)"),
- width: z.number().default(1),
- })
- .optional(),
- ticks: z
- .object({
- show: z.boolean().default(true),
- count: z.number().int().min(2).max(50).optional(),
- })
- .optional(),
- labels: z
- .object({
- show: z.boolean().default(true),
- fontFamily: z.string().default("Inter, sans-serif"),
- fontSize: z.number().default(11),
- color: z.string().default("rgba(255, 255, 255, 0.6)"),
- format: z.string().optional(),
- })
- .optional(),
- })
- .strict();
-export type ChartAxis = z.infer<typeof ChartAxisSchema>;
-
-export const ChartGPUOptionsSchema = z
- .object({
- theme: z.enum(["dark", "light"]).default("dark"),
- backgroundColor: z.string().default("transparent"),
- padding: z
- .object({
- top: z.number().default(20),
- right: z.number().default(20),
- bottom: z.number().default(30),
- left: z.number().default(40),
- })
- .default({ top: 20, right: 20, bottom: 30, left: 40 }),
- xAxis: ChartAxisSchema.default({ type: "category", show: true }),
- yAxis: z
- .union([ChartAxisSchema, z.array(ChartAxisSchema)])
- .default({ type: "value", show: true }),
- series: z.array(ChartSeriesSchema).min(1),
- drawProgress: z.number().min(0).max(1).default(1),
- samples: z.union([z.literal(1), z.literal(4)]).default(4),
- })
- .strict();
-/** Chart options as authored: fields with schema defaults may be left out. */
-export type ChartGPUOptions = z.input<typeof ChartGPUOptionsSchema>;
-
-export const ChartNodeSchema: z.ZodType<ChartNode> = z
- .object({
- ...BaseNodeFields,
- kind: z.literal("chart"),
- chartOptions: ChartGPUOptionsSchema,
- progress: z.number().min(0).max(1).default(1),
- drawProgress: z.number().min(0).max(1).default(1),
- })
- .strict() as unknown as z.ZodType<ChartNode>;
-
-export const CompositionChartNodeSchema = ChartNodeSchema;
-export type CompositionChartNode = ChartNode;
-
export const Model3DNodeSchema: z.ZodType<Model3DNode> = z
.object({
...BaseNodeFields,
@@ -1616,7 +1434,6 @@ export const LayoutNodeSchema = z.lazy(() =>
TextNodeSchema,
MediaNodeSchema,
ShapeNodeSchema,
- ChartNodeSchema,
CameraNodeSchema,
LightNodeSchema,
Model3DNodeSchema,
diff --git a/packages/compositions/src/program/validate.ts b/packages/compositions/src/program/validate.ts
index 5f13e76d..e12f38a3 100644
--- a/packages/compositions/src/program/validate.ts
+++ b/packages/compositions/src/program/validate.ts
@@ -29,7 +29,6 @@ const KIND_SET = new Set([
"text",
"media",
"shape",
- "chart",
]);
const MAX_NODES = 512;
const MAX_DEPTH = 64;
@@ -111,7 +110,7 @@ export function validateLayoutProgram(raw: unknown): ProgramValidationResult {
issue(
"E1201",
[...path, "kind"],
- `Unknown layout node kind '${String(kind)}'. Expected one of: flex, block, box, text, media, shape, chart.`,
+ `Unknown layout node kind '${String(kind)}'. Expected one of: flex, block, box, text, media, shape.`,
),
);
}
diff --git a/packages/gitframes/README.md b/packages/gitframes/README.md
index 06d2544c..3745b464 100644
--- a/packages/gitframes/README.md
+++ b/packages/gitframes/README.md
@@ -25,7 +25,7 @@ pnpm add gitframes
## Quickstart
```typescript
-import { Composition, Layer, LayerAnimation, FontManager } from "gitframes";
+import { Composition, Layer, LayerAnimation } from "gitframes";
// 1. Create a 1080p, 60 FPS composition
const comp = new Composition({
@@ -52,8 +52,8 @@ comp.add(
fontFamily: "Inter",
align: "center",
y: 480,
- }).withAnimation(
- new LayerAnimation()
+ }).animate(
+ LayerAnimation.create()
.fadeIn(0, 30, "power2.out")
.fromTo("y", 520, 480, { start: 0, end: 30, ease: "power3.out" })
)
@@ -69,6 +69,7 @@ comp.add(
- **Unified 3D Scene Graph**: Position 2D surfaces in 3D coordinate space with 3D cameras, lights, and OBJ/FBX/glTF models.
- **Audio DSP & SFX**: Procedural sound effects (impact, whoosh, riser), audio stem analysis, and audio-reactive signals.
- **Headless GPU Video Rendering**: Direct hardware encoding via `@mediabunny/server` / WebCodecs without headless browser overhead.
+- **Live Preview**: `startPreview({ entry, export })` opens a localhost player (soundtrack, waveform timeline, frame stepping). The page runs the composition's own code and renders it with WebGPU in the browser, at or near full frame rate. Re-running it replaces the running preview, and an open tab reloads into the new version.
---
diff --git a/packages/gitframes/package.json b/packages/gitframes/package.json
index b7e27784..2911216a 100644
--- a/packages/gitframes/package.json
+++ b/packages/gitframes/package.json
@@ -65,6 +65,12 @@
"development": "./src/fonts/index.ts",
"import": "./dist/fonts/index.mjs",
"default": "./dist/fonts/index.mjs"
+ },
+ "./preview": {
+ "types": "./dist/preview/index.d.mts",
+ "development": "./src/preview/index.ts",
+ "import": "./dist/preview/index.mjs",
+ "default": "./dist/preview/index.mjs"
}
},
"files": [
@@ -82,9 +88,12 @@
"@mediabunny/server": "^1.51.0",
"@napi-rs/webcodecs": "^1.3.1",
"@resvg/resvg-js": "^2.6.2",
- "chartgpu": "^0.4.0",
+ "d3-format": "^3.1.2",
+ "d3-scale": "^4.0.2",
+ "d3-shape": "^3.2.0",
"dotenv": "^16.4.5",
"earcut": "^3.2.4",
+ "esbuild": "^0.28.1",
"fontkit": "^2.0.4",
"gifuct-js": "^2.1.2",
"gsap": "^3.15.0",
@@ -92,13 +101,14 @@
"nanoid": "^5.1.6",
"onnxruntime-node": "^1.24.0",
"pino": "^10.3.1",
- "sharp": "^0.34.5",
+ "sharp": "^0.35.4",
"skia-canvas": "^3.0.8",
"webgpu": "^0.4.0",
"yoga-layout": "^3.2.1",
"zod": "^4.3.6"
},
"devDependencies": {
+ "@gitframes/client-utils": "workspace:*",
"@gitframes/compositions": "workspace:*",
"@gitframes/core": "workspace:*",
"@gitframes/node-audio-compressor": "workspace:*",
@@ -134,6 +144,7 @@
"@gitframes/node-refine-edge": "workspace:*",
"@gitframes/node-refraction-caustics": "workspace:*",
"@gitframes/node-relight-3d": "workspace:*",
+ "@gitframes/node-sdk": "workspace:*",
"@gitframes/node-selective-color": "workspace:*",
"@gitframes/node-shadows-highlights": "workspace:*",
"@gitframes/node-signal": "workspace:*",
@@ -148,8 +159,11 @@
"@gitframes/renderers": "workspace:*",
"@gitframes/tensor-webgpu": "workspace:*",
"@gitframes/tsconfig": "workspace:*",
- "@gitframes/webgpu-renderers": "workspace:*",
"@gitframes/vision": "workspace:*",
+ "@gitframes/webgpu-renderers": "workspace:*",
+ "@types/d3-format": "^3.0.4",
+ "@types/d3-scale": "^4.0.9",
+ "@types/d3-shape": "^3.2.0",
"@types/fontkit": "^2.0.9",
"@types/node": "^24.1.0",
"tsdown": "^0.19.0",
diff --git a/packages/gitframes/src/builder-schema-conformance.test.ts b/packages/gitframes/src/builder-schema-conformance.test.ts
index 831eef83..6e91ecb1 100644
--- a/packages/gitframes/src/builder-schema-conformance.test.ts
+++ b/packages/gitframes/src/builder-schema-conformance.test.ts
@@ -34,6 +34,42 @@ const builders = {
Layer.carousel3d({ radius: 200, items: [Layer.box(), Layer.box()] }),
plane3d: () => Layer.plane3d({ width: 100, height: 50 }),
prism3d: () => Layer.prism3d({ sides: 6, radius: 50, height: 100 }),
+ barChart: () =>
+ Layer.chart({
+ type: "bar",
+ categories: ["a", "b"],
+ series: [{ data: [1, -2] }, { data: [3, 4] }],
+ valueLabels: true,
+ }),
+ stackedArea: () =>
+ Layer.chart({
+ type: "area",
+ stacked: true,
+ series: [{ data: [1, 2, 3] }, { data: [2, 1, 2] }],
+ }),
+ lineChart: () =>
+ Layer.chart({
+ data: [
+ [0, 1],
+ [1, 3],
+ [2, 2],
+ ],
+ }),
+ scatterChart: () => Layer.chart({ type: "scatter", data: [1, 4, 2] }),
+ candlestickChart: () =>
+ Layer.chart({
+ type: "candlestick",
+ data: [{ x: "d1", open: 1, high: 3, low: 0, close: 2 }],
+ }),
+ donutChart: () =>
+ Layer.chart({
+ type: "donut",
+ data: [
+ { label: "a", value: 1 },
+ { label: "b", value: 2 },
+ ],
+ valueLabels: true,
+ }),
animatedCube: () =>
Layer.cube({ size: 10 }).animate(
LayerAnimation.create().fromTo("scale", 0, 1, { start: 0, end: 24 }),
diff --git a/packages/gitframes/src/chart.test.ts b/packages/gitframes/src/chart.test.ts
new file mode 100644
index 00000000..31249398
--- /dev/null
+++ b/packages/gitframes/src/chart.test.ts
@@ -0,0 +1,201 @@
+/**
+ * Layer.chart builds charts from ordinary nodes: the reveal animation is plain
+ * keyframes, and the rendered pixels come from the same box, path and text
+ * pipelines as every other layer.
+ */
+import { Canvas, loadImage } from "skia-canvas";
+import { describe, expect, it } from "vitest";
+import {
+ type ChartOptions,
+ Composition,
+ FontManager,
+ Layer,
+ type LayoutNode,
+} from "./index.js";
+
+const BG = "#000000";
+
+async function pixels(png: Buffer) {
+ const img = await loadImage(png);
+ const canvas = new Canvas(img.width, img.height);
+ const ctx = canvas.getContext("2d");
+ ctx.drawImage(img, 0, 0);
+ const data = ctx.getImageData(0, 0, img.width, img.height).data;
+ return (x: number, y: number) => {
+ const i = (Math.round(y) * img.width + Math.round(x)) * 4;
+ return [data[i] ?? 0, data[i + 1] ?? 0, data[i + 2] ?? 0];
+ };
+}
+
+function comp(chart: ChartOptions) {
+ const c = new Composition({
+ width: 400,
+ height: 300,
+ fps: 30,
+ durationFrames: 60,
+ backgroundColor: BG,
+ });
+ const node = Layer.chart(
+ { width: 400, height: 300, legend: false, ...chart },
+ { id: "c", position: "absolute", x: 0, y: 0 },
+ );
+ c.add(node);
+ return { c, node };
+}
+
+const find = (node: LayoutNode, id: string): LayoutNode | undefined => {
+ if (node.id === id) return node;
+ for (const child of (node as { children?: LayoutNode[] }).children ?? []) {
+ const hit = find(child, id);
+ if (hit) return hit;
+ }
+ return undefined;
+};
+
+describe("Layer.chart", () => {
+ it("grows bars from the baseline and lands them at their values", async () => {
+ await FontManager.register("assets/fonts/Inter.ttf");
+ const { c, node } = comp({
+ type: "bar",
+ categories: ["a", "b"],
+ data: [10, 5],
+ colors: ["#ff0000"],
+ yAxis: { min: 0, max: 10, show: false, grid: false },
+ xAxis: { show: false },
+ animate: { start: 0, duration: 20 },
+ });
+ const bar = find(node, "c-bar-0-0") as {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ };
+ expect(bar).toBeDefined();
+ const cx = bar.x + bar.width / 2;
+ const nearTop = bar.y + 4;
+ const end = await pixels(await c.renderFrame({ frame: 40 }));
+ expect(end(cx, nearTop)[0]).toBeGreaterThan(200);
+ const start = await pixels(await c.renderFrame({ frame: 0 }));
+ expect(start(cx, nearTop)[0]).toBeLessThan(40);
+ // The half-height bar stops at half the plot height.
+ const half = find(node, "c-bar-0-1") as { height: number };
+ expect(half.height).toBeCloseTo(bar.height / 2, 0);
+ });
+
+ it("draws lines on with trimEnd and renders the stroke", async () => {
+ await FontManager.register("assets/fonts/Inter.ttf");
+ const { c, node } = comp({
+ type: "line",
+ colors: ["#00ff00"],
+ series: [
+ {
+ data: [
+ [0, 5],
+ [1, 5],
+ ],
+ curve: "linear",
+ strokeWidth: 6,
+ },
+ ],
+ yAxis: { min: 0, max: 10, show: false, grid: false },
+ xAxis: { show: false },
+ animate: { duration: 20 },
+ });
+ const line = find(node, "c-line-0") as {
+ animation: { tracks: { prop: string }[] };
+ };
+ expect(line.animation.tracks.map((t) => t.prop)).toEqual(["trimEnd"]);
+ const frame = await pixels(await c.renderFrame({ frame: 59 }));
+ // A horizontal line at y=5 of 0..10 crosses the middle of the plot.
+ let hit = 0;
+ for (let y = 100; y < 200; y++) if (frame(200, y)[1] > 200) hit++;
+ expect(hit).toBeGreaterThan(2);
+ });
+
+ it("renders pie slices in their colours", async () => {
+ await FontManager.register("assets/fonts/Inter.ttf");
+ const { c } = comp({
+ type: "pie",
+ data: [
+ { label: "a", value: 1, color: "#ff0000" },
+ { label: "b", value: 1, color: "#0000ff" },
+ ],
+ animate: false,
+ });
+ const frame = await pixels(await c.renderFrame({ frame: 0 }));
+ // The first slice runs clockwise from 12 o'clock: right half red, left half blue.
+ expect(frame(250, 150)[0]).toBeGreaterThan(200);
+ expect(frame(150, 150)[2]).toBeGreaterThan(200);
+ });
+
+ it("is static with animate: false and has stable, unique ids", () => {
+ const build = () =>
+ Layer.chart(
+ {
+ type: "bar",
+ categories: ["a", "b", "c"],
+ series: [{ data: [1, 2, 3] }, { data: [3, 2, 1] }],
+ valueLabels: true,
+ legend: true,
+ animate: false,
+ },
+ { id: "s" },
+ );
+ const a = build();
+ const ids: string[] = [];
+ const walk = (n: LayoutNode) => {
+ ids.push(n.id);
+ expect(n.animation?.tracks ?? []).toEqual([]);
+ for (const child of (n as { children?: LayoutNode[] }).children ?? [])
+ walk(child);
+ };
+ walk(a);
+ expect(new Set(ids).size).toBe(ids.length);
+ expect(JSON.stringify(build())).toBe(JSON.stringify(a));
+ });
+
+ it("keeps keyframes on whole frames with uneven staggers", () => {
+ const c = new Composition({
+ width: 400,
+ height: 300,
+ fps: 30,
+ durationFrames: 60,
+ });
+ c.add(
+ Layer.chart({
+ type: "line",
+ categories: ["a", "b", "c", "d", "e", "f", "g", "h", "i"],
+ series: [{ data: [1, 3, 2, 5, 4, 6, 5, 8, 7], pointRadius: 4 }],
+ animate: { duration: 31 },
+ }),
+ );
+ const frames: number[] = [];
+ const walk = (n: LayoutNode) => {
+ for (const t of n.animation?.tracks ?? [])
+ for (const kf of t.keyframes) frames.push(kf.frame);
+ for (const child of (n as { children?: LayoutNode[] }).children ?? [])
+ walk(child);
+ };
+ for (const n of c.toSpec().layout as LayoutNode[]) walk(n);
+ expect(frames.length).toBeGreaterThan(0);
+ expect(frames.filter((f) => !Number.isInteger(f))).toEqual([]);
+ });
+
+ it("stacks bars on top of each other", () => {
+ const node = Layer.chart(
+ {
+ type: "bar",
+ stacked: true,
+ categories: ["a"],
+ series: [{ data: [2] }, { data: [3] }],
+ yAxis: { min: 0, max: 5 },
+ animate: false,
+ },
+ { id: "st" },
+ );
+ const lower = find(node, "st-bar-0-0") as { y: number; height: number };
+ const upper = find(node, "st-bar-1-0") as { y: number; height: number };
+ expect(upper.y + upper.height).toBeCloseTo(lower.y, 0);
+ expect(upper.height / lower.height).toBeCloseTo(1.5, 1);
+ });
+});
diff --git a/packages/gitframes/src/chart.ts b/packages/gitframes/src/chart.ts
new file mode 100644
index 00000000..fdd0fa4e
--- /dev/null
+++ b/packages/gitframes/src/chart.ts
@@ -0,0 +1,1143 @@
+/**
+ * Charts built from ordinary layout nodes. d3 does the math (scales, ticks,
+ * line/area/arc geometry, stacking); every bar, line, slice and label is a
+ * regular box, shape or text node, so charts use the composition's fonts and
+ * can be animated, graded and composited like any other layer.
+ */
+import {
+ type BoxNode,
+ LayerAnimation,
+ type LayoutNode,
+} from "@gitframes/compositions/program";
+import { format as d3Format } from "d3-format";
+import {
+ type ScaleBand,
+ type ScaleLinear,
+ type ScaleTime,
+ scaleBand,
+ scaleLinear,
+ scaleUtc,
+} from "d3-scale";
+import {
+ type CurveFactory,
+ curveLinear,
+ curveMonotoneX,
+ curveStepAfter,
+ arc as d3Arc,
+ area as d3Area,
+ line as d3Line,
+ pie as d3Pie,
+ stack as d3Stack,
+ stackOffsetDiverging,
+} from "d3-shape";
+import { autoId } from "./ids.js";
+import { type AnimatableNode, Layer } from "./index.js";
+
+export type ChartType =
+ | "line"
+ | "area"
+ | "bar"
+ | "scatter"
+ | "pie"
+ | "donut"
+ | "candlestick";
+
+export type ChartX = number | string | Date;
+
+/** A plain value (x is its index or `categories[i]`), an `[x, y]` pair, or `{ x, y }`. */
+export type ChartDatum =
+ | number
+ | readonly [ChartX, number]
+ | { x: ChartX; y: number };
+
+export interface ChartCandle {
+ x: ChartX;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+}
+
+/** A pie or donut slice. */
+export interface ChartSlice {
+ label: string;
+ value: number;
+ color?: string;
+}
+
+export interface ChartSeries {
+ name?: string;
+ /** Series type in a combined chart; defaults to the chart's `type`. */
+ type?: Exclude<ChartType, "pie" | "donut">;
+ data: readonly ChartDatum[] | readonly ChartCandle[];
+ color?: string;
+ /** Line width for line and area series. Default 3. */
+ strokeWidth?: number;
+ /** Line and area interpolation. Default "smooth". */
+ curve?: "linear" | "smooth" | "step";
+ /** Dot radius drawn on line points; scatter point radius. 0 hides line dots. */
+ pointRadius?: number;
+}
+
+export interface ChartAxisOptions {
+ /** Show tick labels. Default true. */
+ show?: boolean;
+ /** Draw grid lines across the plot. Default true for y, false for x. */
+ grid?: boolean;
+ min?: number;
+ max?: number;
+ /** Approximate number of ticks. Default 5. */
+ ticks?: number;
+ /** A d3-format specifier such as ",.0f", "$.2s" or ".0%", or a function. */
+ format?: string | ((value: ChartX) => string);
+}
+
+export interface ChartAnimationOptions {
+ /** Frame the reveal starts, relative to the chart's own start. Default 0. */
+ start?: number;
+ /** Frames each element takes to animate in. Default 30. */
+ duration?: number;
+ /** Frames between consecutive bars, points or slices. Default spreads them over `duration`. */
+ stagger?: number;
+ /** Easing for bars, points and slices. Default "power3.out". */
+ ease?: string;
+}
+
+export interface ChartPadding {
+ top?: number;
+ right?: number;
+ bottom?: number;
+ left?: number;
+}
+
+export interface ChartOptions {
+ /** Chart type, and the default for series without their own. Default "line". */
+ type?: ChartType;
+ width?: number;
+ height?: number;
+ series?: readonly ChartSeries[];
+ /** Shorthand for a single series, or the slices of a pie or donut. */
+ data?: readonly ChartDatum[] | readonly ChartCandle[] | readonly ChartSlice[];
+ /** Labels for x positions when data are plain values; slice labels for pie charts. */
+ categories?: readonly string[];
+ /** Stack bar and area series instead of grouping or overlapping them. */
+ stacked?: boolean;
+ colors?: readonly string[];
+ xAxis?: ChartAxisOptions;
+ yAxis?: ChartAxisOptions;
+ /** Space around the plot for axis labels and legend. Computed when omitted. */
+ padding?: number | ChartPadding;
+ fontFamily?: string;
+ /** Axis, legend and value label size. Default 18. */
+ fontSize?: number;
+ /** Axis labels; when set, also the legend and value labels. */
+ textColor?: string;
+ gridColor?: string;
+ background?: string;
+ /** Show the series or slice legend. Default: on for several series and for pies. */
+ legend?: boolean;
+ /** Print values on bars and slices (pie values print as percentages). */
+ valueLabels?: boolean;
+ /** Donut hole as a fraction of the radius. Default 0.6 for "donut". */
+ innerRadius?: number;
+ /** Corner radius of bars and slices. Default 4. */
+ cornerRadius?: number;
+ upColor?: string;
+ downColor?: string;
+ /** Reveal animation, or `false` for a static chart. */
+ animate?: false | ChartAnimationOptions;
+}
+
+export const DEFAULT_CHART_COLORS = [
+ "#6366f1",
+ "#22d3ee",
+ "#f59e0b",
+ "#ec4899",
+ "#10b981",
+ "#8b5cf6",
+ "#f97316",
+ "#3b82f6",
+] as const;
+
+type XScale =
+ | ScaleBand<string>
+ | ScaleLinear<number, number>
+ | ScaleTime<number, number>;
+
+interface Timing {
+ enabled: boolean;
+ start: number;
+ duration: number;
+ stagger: number;
+ ease: string;
+}
+
+interface Point {
+ x: ChartX;
+ y: number;
+}
+
+interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+const isCandle = (d: unknown): d is ChartCandle =>
+ typeof d === "object" && d !== null && "open" in d && "close" in d;
+
+const isSlice = (d: unknown): d is ChartSlice =>
+ typeof d === "object" && d !== null && "label" in d && "value" in d;
+
+function curveOf(curve: ChartSeries["curve"]): CurveFactory {
+ if (curve === "linear") return curveLinear;
+ if (curve === "step") return curveStepAfter;
+ return curveMonotoneX;
+}
+
+function withAlpha(color: string, alpha: number): string {
+ const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim());
+ if (!hex) return color;
+ let h = hex[1];
+ if (h.length === 3) h = [...h].map((c) => c + c).join("");
+ const n = parseInt(h, 16);
+ return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
+}
+
+function fmt(
+ axis: ChartAxisOptions | undefined,
+): ((v: ChartX) => string) | null {
+ if (!axis?.format) return null;
+ if (typeof axis.format === "function") return axis.format;
+ const f = d3Format(axis.format);
+ return (v) => (typeof v === "number" ? f(v) : String(v));
+}
+
+function round(v: number): number {
+ return Math.round(v * 100) / 100;
+}
+
+function fadeIn(t: Timing, delay = 0, duration = t.duration): LayerAnimation {
+ return LayerAnimation.create().fromTo("opacity", 0, 1, {
+ start: t.start + delay,
+ end: t.start + delay + Math.max(1, duration),
+ ease: "power2.out",
+ });
+}
+
+/** Builds the chart as a box of absolutely positioned child nodes. */
+export function buildChart(
+ options: ChartOptions,
+ props: Partial<BoxNode>,
+ defaultFontFamily: string,
+): AnimatableNode<BoxNode> {
+ const id = props.id ?? autoId("chart");
+ const width =
+ options.width ?? (typeof props.width === "number" ? props.width : 960);
+ const height =
+ options.height ?? (typeof props.height === "number" ? props.height : 540);
+ const type = options.type ?? "line";
+ const fontSize = options.fontSize ?? 18;
+ const fontFamily = options.fontFamily ?? defaultFontFamily;
+ const textColor = options.textColor ?? "#94a3b8";
+ // Legend and value labels read a little stronger than axis labels; with a custom
+ // textColor (e.g. dark text on a light background) they use it as is.
+ const strongText = options.textColor ?? "#e2e8f0";
+ const gridColor = options.gridColor ?? "rgba(148, 163, 184, 0.18)";
+ const colors = options.colors?.length ? options.colors : DEFAULT_CHART_COLORS;
+ const radius = options.cornerRadius ?? 4;
+
+ const anim = options.animate === false ? undefined : (options.animate ?? {});
+ const timing: Timing = {
+ enabled: anim !== undefined,
+ start: anim?.start ?? 0,
+ duration: anim?.duration ?? 30,
+ stagger: anim?.stagger ?? -1,
+ ease: anim?.ease ?? "power3.out",
+ };
+
+ const children: LayoutNode[] = [];
+ const label = (
+ text: string,
+ rect: Rect,
+ align: "start" | "center" | "end",
+ extra: { delay?: number; color?: string; weight?: number } = {},
+ key = "",
+ ) => {
+ const node = Layer.text(text, {
+ id: `${id}-label-${key || children.length}`,
+ position: "absolute",
+ x: round(rect.x),
+ y: round(rect.y),
+ width: round(rect.width),
+ height: round(rect.height),
+ fontFamily,
+ fontSize,
+ fontWeight: extra.weight ?? 500,
+ fill: extra.color ?? textColor,
+ align,
+ verticalAlign: "middle",
+ });
+ if (timing.enabled) node.animate(fadeIn(timing, extra.delay ?? 0));
+ children.push(node);
+ };
+
+ const lineHeight = Math.ceil(fontSize * 1.4);
+
+ if (type === "pie" || type === "donut") {
+ buildPie();
+ } else {
+ buildCartesian();
+ }
+
+ // Staggers and fractional durations land between frames; the program schema
+ // wants whole-frame keyframes.
+ for (const child of children) snapKeyframes(child);
+
+ return Layer.box({
+ background: options.background ?? "transparent",
+ ...props,
+ id,
+ width,
+ height,
+ children,
+ });
+
+ // ── pie & donut ─────────────────────────────────────────────────────
+
+ function buildPie(): void {
+ const slices = collectSlices();
+ const total = slices.reduce((s, d) => s + Math.max(0, d.value), 0);
+ const showLegend = options.legend ?? true;
+ const pad = resolvePadding({
+ top: 16,
+ right: showLegend ? legendColumnWidth(slices.map((s) => s.label)) : 16,
+ bottom: 16,
+ left: 16,
+ });
+ const plot = plotRect(pad);
+ const r = Math.max(1, Math.min(plot.width, plot.height) / 2);
+ const inner = r * (options.innerRadius ?? (type === "donut" ? 0.6 : 0));
+ const cx = plot.x + plot.width / 2;
+ const cy = plot.y + plot.height / 2;
+ const m = 4;
+ const arcs = d3Pie<ChartSlice>()
+ .sort(null)
+ .value((d) => Math.max(0, d.value))
+ .padAngle(slices.length > 1 ? 0.012 : 0)(slices);
+ const arcGen = d3Arc<(typeof arcs)[number]>()
+ .innerRadius(inner)
+ .outerRadius(r)
+ .cornerRadius(Math.min(radius, (r - inner) / 2));
+ const step = staggerStep(arcs.length);
+
+ arcs.forEach((a, i) => {
+ const d = arcGen(a);
+ if (!d) return;
+ const color = slices[i].color ?? colors[i % colors.length];
+ const node = Layer.shape("path", {
+ id: `${id}-slice-${i}`,
+ position: "absolute",
+ x: round(cx - r - m),
+ y: round(cy - r - m),
+ width: round(2 * (r + m)),
+ height: round(2 * (r + m)),
+ d: translatePath(d, r + m, r + m),
+ fillColor: color,
+ anchorX: 0.5,
+ anchorY: 0.5,
+ });
+ if (timing.enabled) {
+ const s = timing.start + i * step;
+ node.animate(
+ LayerAnimation.create()
+ .fromTo("opacity", 0, 1, {
+ start: s,
+ end: s + timing.duration * 0.5,
+ })
+ .fromTo("scale", 0.85, 1, {
+ start: s,
+ end: s + timing.duration,
+ ease: timing.ease,
+ }),
+ );
+ }
+ children.push(node);
+
+ if (options.valueLabels && total > 0 && a.value > 0) {
+ const [lx, ly] = d3Arc<(typeof arcs)[number]>()
+ .innerRadius(inner || r * 0.55)
+ .outerRadius(r)
+ .centroid(a);
+ const pct = `${Math.round((a.value / total) * 100)}%`;
+ label(
+ pct,
+ {
+ x: cx + lx - 60,
+ y: cy + ly - lineHeight / 2,
+ width: 120,
+ height: lineHeight,
+ },
+ "center",
+ {
+ delay: i * step + timing.duration * 0.5,
+ color: "#ffffff",
+ weight: 700,
+ },
+ `value-${i}`,
+ );
+ }
+ });
+
+ if (showLegend) {
+ legendColumn(
+ slices.map((s, i) => ({
+ name: s.label,
+ color: s.color ?? colors[i % colors.length],
+ })),
+ { x: plot.x + plot.width + 24, y: plot.y, height: plot.height },
+ );
+ }
+ }
+
+ function collectSlices(): ChartSlice[] {
+ const raw = (options.data ??
+ options.series?.[0]?.data ??
+ []) as readonly unknown[];
+ return raw.map((d, i) => {
+ if (isSlice(d)) return d;
+ const value =
+ typeof d === "number"
+ ? d
+ : Array.isArray(d)
+ ? Number(d[1])
+ : Number((d as Point).y);
+ const name =
+ options.categories?.[i] ??
+ (Array.isArray(d)
+ ? String(d[0])
+ : typeof d === "object" && d
+ ? String((d as Point).x)
+ : `${i + 1}`);
+ return { label: name, value };
+ });
+ }
+
+ // ── cartesian: line, area, bar, scatter, candlestick ───────────────
+
+ function buildCartesian(): void {
+ const series: ChartSeries[] = options.series?.length
+ ? [...options.series]
+ : options.data
+ ? [{ data: options.data as ChartSeries["data"] }]
+ : [];
+ if (series.length === 0) return;
+
+ const typeOf = (s: ChartSeries) =>
+ s.type ?? (type as ChartSeries["type"]) ?? "line";
+ const colorOf = (s: ChartSeries, i: number) =>
+ s.color ?? colors[i % colors.length];
+
+ // Normalise every series to points (candles keep their OHLC values).
+ const points: Point[][] = series.map((s) =>
+ (s.data as readonly unknown[]).map((d, i) => {
+ if (isCandle(d)) return { x: d.x, y: d.close };
+ if (typeof d === "number")
+ return { x: options.categories?.[i] ?? i, y: d };
+ if (Array.isArray(d)) return { x: d[0] as ChartX, y: Number(d[1]) };
+ return { x: (d as Point).x, y: Number((d as Point).y) };
+ }),
+ );
+
+ const anyBand = series.some(
+ (s) => typeOf(s) === "bar" || typeOf(s) === "candlestick",
+ );
+ const allX = points.flat().map((p) => p.x);
+ const xKind: "band" | "time" | "linear" =
+ anyBand || allX.some((x) => typeof x === "string")
+ ? "band"
+ : allX.some((x) => x instanceof Date)
+ ? "time"
+ : "linear";
+
+ // Stacking for bars and areas.
+ const stackable = (s: ChartSeries) =>
+ typeOf(s) === "bar" || typeOf(s) === "area";
+ const stacked = !!options.stacked;
+ const categories = xKind === "band" ? [...new Set(allX.map(String))] : [];
+ const stackRanges = new Map<number, [number, number][]>();
+ if (stacked) {
+ const keys = series.map((_, i) => i).filter((i) => stackable(series[i]));
+ const rows = categories.length
+ ? categories
+ : [...new Set(allX.map((x) => +x))].sort((a, b) => a - b).map(String);
+ const table = rows.map((key) => {
+ const row: Record<string, number> = {};
+ for (const i of keys) {
+ const p = points[i].find(
+ (pt) => String(xKind === "band" ? pt.x : +pt.x) === key,
+ );
+ row[i] = p?.y ?? 0;
+ }
+ return row;
+ });
+ const layers = d3Stack<Record<string, number>>()
+ .keys(keys.map(String))
+ .offset(stackOffsetDiverging)(table);
+ layers.forEach((layer) => {
+ const i = Number(layer.key);
+ stackRanges.set(
+ i,
+ points[i].map((p) => {
+ const idx = rows.indexOf(String(xKind === "band" ? p.x : +p.x));
+ return [layer[idx][0], layer[idx][1]];
+ }),
+ );
+ });
+ }
+
+ // y domain
+ const yValues: number[] = [0];
+ series.forEach((s, i) => {
+ const range = stackRanges.get(i);
+ if (typeOf(s) === "candlestick") {
+ for (const c of s.data as readonly ChartCandle[])
+ yValues.push(c.high, c.low);
+ } else if (range) {
+ for (const [a, b] of range) yValues.push(a, b);
+ } else {
+ for (const p of points[i]) yValues.push(p.y);
+ }
+ });
+ if (
+ series.every(
+ (s) =>
+ typeOf(s) === "candlestick" ||
+ typeOf(s) === "scatter" ||
+ typeOf(s) === "line",
+ )
+ ) {
+ // Line, scatter and price charts don't have to include zero.
+ yValues.shift();
+ }
+
+ const yAxis = options.yAxis ?? {};
+ const xAxis = options.xAxis ?? {};
+ const yTickCount = yAxis.ticks ?? 5;
+ let lo = yAxis.min ?? Math.min(...yValues);
+ let hi = yAxis.max ?? Math.max(...yValues);
+ if (!Number.isFinite(lo) || !Number.isFinite(hi)) [lo, hi] = [0, 1];
+ if (lo === hi) [lo, hi] = [lo - 1, hi + 1];
+ const y = scaleLinear().domain([lo, hi]);
+ if (yAxis.min === undefined || yAxis.max === undefined) y.nice(yTickCount);
+ const yFormat =
+ fmt(yAxis) ?? ((v: ChartX) => y.tickFormat(yTickCount)(v as number));
+ const yTicks = y.ticks(yTickCount);
+
+ const legendItems = series.map((s, i) => ({
+ name: s.name ?? `Series ${i + 1}`,
+ color: colorOf(s, i),
+ }));
+ const showLegend = options.legend ?? series.length > 1;
+ const showY = yAxis.show !== false;
+ const showX = xAxis.show !== false;
+ const yLabelWidth = showY
+ ? Math.max(...yTicks.map((t) => yFormat(t).length)) * fontSize * 0.7 + 20
+ : 0;
+ const pad = resolvePadding({
+ top: (showLegend ? lineHeight + 20 : 0) + Math.ceil(lineHeight / 2),
+ right: 20,
+ bottom: showX ? lineHeight + 14 : 12,
+ left: Math.max(16, Math.ceil(yLabelWidth)),
+ });
+ const plot = plotRect(pad);
+ // Room for value labels above positive bars and below negative ones.
+ const labelRoom = lineHeight + 6;
+ const barValues = options.valueLabels
+ ? series.flatMap((s, i) =>
+ typeOf(s) === "bar" ? points[i].map((p) => p.y) : [],
+ )
+ : [];
+ const topInset = barValues.some((v) => v > 0) ? labelRoom : 0;
+ const bottomInset = barValues.some((v) => v < 0) ? labelRoom : 0;
+ y.range([plot.height - bottomInset, topInset]);
+
+ let x: XScale;
+ if (xKind === "band") {
+ x = scaleBand<string>()
+ .domain(categories)
+ .range([0, plot.width])
+ .paddingInner(anyBand ? 0.28 : 0)
+ .paddingOuter(anyBand ? 0.14 : 0.5);
+ } else if (xKind === "time") {
+ const xs = allX.map((v) => +new Date(v as Date));
+ x = scaleUtc()
+ .domain([Math.min(...xs), Math.max(...xs)])
+ .range([0, plot.width]);
+ } else {
+ const xs = allX.map(Number);
+ x = scaleLinear()
+ .domain([xAxis.min ?? Math.min(...xs), xAxis.max ?? Math.max(...xs)])
+ .range([0, plot.width]);
+ }
+ const xPos = (v: ChartX): number => {
+ if (xKind === "band") {
+ const b = x as ScaleBand<string>;
+ return (b(String(v)) ?? 0) + b.bandwidth() / 2;
+ }
+ if (xKind === "time")
+ return (x as ScaleTime<number, number>)(new Date(v as Date));
+ return (x as ScaleLinear<number, number>)(Number(v));
+ };
+
+ // Grid and y labels.
+ const gridDelay = 0;
+ if (yAxis.grid !== false) {
+ yTicks.forEach((t, i) => {
+ const node = Layer.box({
+ id: `${id}-ygrid-${i}`,
+ position: "absolute",
+ x: plot.x,
+ y: round(plot.y + y(t) - 0.5),
+ width: plot.width,
+ height: 1,
+ background: gridColor,
+ });
+ if (timing.enabled)
+ node.animate(fadeIn(timing, gridDelay, timing.duration / 2));
+ children.push(node);
+ });
+ }
+ if (showY) {
+ yTicks.forEach((t, i) => {
+ label(
+ yFormat(t),
+ {
+ x: 0,
+ y: plot.y + y(t) - lineHeight / 2,
+ width: plot.x - 12,
+ height: lineHeight,
+ },
+ "end",
+ {},
+ `y-${i}`,
+ );
+ });
+ }
+
+ // x labels (and optional vertical grid).
+ const xTicks: { pos: number; text: string }[] = [];
+ const xFormat = fmt(xAxis);
+ if (xKind === "band") {
+ const b = x as ScaleBand<string>;
+ const every = Math.max(
+ 1,
+ Math.ceil(
+ categories.length /
+ Math.max(1, Math.floor(plot.width / (fontSize * 4))),
+ ),
+ );
+ categories.forEach((c, i) => {
+ if (i % every === 0)
+ xTicks.push({
+ pos: (b(c) ?? 0) + b.bandwidth() / 2,
+ text: xFormat ? xFormat(c) : c,
+ });
+ });
+ } else {
+ const s = x as ScaleLinear<number, number>;
+ const count =
+ xAxis.ticks ?? Math.max(2, Math.floor(plot.width / (fontSize * 6)));
+ const tf = s.tickFormat(count);
+ for (const t of s.ticks(count)) {
+ xTicks.push({
+ pos: s(t),
+ text: xFormat ? xFormat(xKind === "time" ? new Date(t) : t) : tf(t),
+ });
+ }
+ }
+ if (xAxis.grid) {
+ xTicks.forEach((t, i) => {
+ const node = Layer.box({
+ id: `${id}-xgrid-${i}`,
+ position: "absolute",
+ x: round(plot.x + t.pos - 0.5),
+ y: plot.y,
+ width: 1,
+ height: plot.height,
+ background: gridColor,
+ });
+ if (timing.enabled)
+ node.animate(fadeIn(timing, gridDelay, timing.duration / 2));
+ children.push(node);
+ });
+ }
+ if (showX) {
+ const slot = Math.max(
+ fontSize * 3,
+ plot.width / Math.max(1, xTicks.length),
+ );
+ xTicks.forEach((t, i) => {
+ label(
+ t.text,
+ {
+ x: plot.x + t.pos - slot / 2,
+ y: plot.y + plot.height + 10,
+ width: slot,
+ height: lineHeight,
+ },
+ "center",
+ {},
+ `x-${i}`,
+ );
+ });
+ }
+
+ // Baseline at zero when it is inside the domain.
+ const [y0, y1] = y.domain();
+ if (y0 <= 0 && y1 >= 0 && anyBand) {
+ const node = Layer.box({
+ id: `${id}-zero`,
+ position: "absolute",
+ x: plot.x,
+ y: round(plot.y + y(0) - 1),
+ width: plot.width,
+ height: 2,
+ background: withAlpha("#94a3b8", 0.45),
+ });
+ if (timing.enabled) node.animate(fadeIn(timing, 0, timing.duration / 2));
+ children.push(node);
+ }
+
+ // Series. Bars first so lines draw on top.
+ const barSeries = series
+ .map((_, i) => i)
+ .filter((i) => typeOf(series[i]) === "bar");
+ const order = [
+ ...barSeries,
+ ...series
+ .map((_, i) => i)
+ .filter((i) => typeOf(series[i]) === "candlestick"),
+ ...series.map((_, i) => i).filter((i) => typeOf(series[i]) === "area"),
+ ...series.map((_, i) => i).filter((i) => typeOf(series[i]) === "line"),
+ ...series.map((_, i) => i).filter((i) => typeOf(series[i]) === "scatter"),
+ ];
+
+ const band = xKind === "band" ? (x as ScaleBand<string>) : null;
+ const bandStep = band ? staggerStep(categories.length) : 0;
+ const categoryIndex = (v: ChartX) =>
+ band ? categories.indexOf(String(v)) : 0;
+
+ order.forEach((si, rank) => {
+ const s = series[si];
+ const color = colorOf(s, si);
+ const kind = typeOf(s);
+ const pts = points[si];
+ const range = stackRanges.get(si);
+
+ if (kind === "bar" && band) {
+ const groupSize = stacked ? 1 : barSeries.length;
+ const groupIdx = stacked ? 0 : barSeries.indexOf(si);
+ const bw = band.bandwidth() / groupSize;
+ const gap = groupSize > 1 ? Math.min(4, bw * 0.12) : 0;
+ pts.forEach((p, i) => {
+ const [lo, hi] = range ? range[i] : [0, p.y];
+ const top = plot.y + y(Math.max(lo, hi));
+ const bottom = plot.y + y(Math.min(lo, hi));
+ const h = Math.max(0, bottom - top);
+ const bx =
+ plot.x + (band(String(p.x)) ?? 0) + groupIdx * bw + gap / 2;
+ const grows = p.y >= 0 ? "up" : "down";
+ const node = Layer.box({
+ id: `${id}-bar-${si}-${i}`,
+ position: "absolute",
+ x: round(bx),
+ y: round(top),
+ width: round(Math.max(1, bw - gap)),
+ height: round(h),
+ background: color,
+ borderRadius: Math.min(radius, (bw - gap) / 2, h / 2),
+ });
+ const delay =
+ categoryIndex(p.x) * bandStep +
+ (stacked ? barSeries.indexOf(si) * timing.duration * 0.6 : 0);
+ if (timing.enabled) {
+ const st = timing.start + delay;
+ const end = st + timing.duration;
+ const a = LayerAnimation.create().fromTo("height", 0, round(h), {
+ start: st,
+ end,
+ ease: timing.ease,
+ });
+ if (grows === "up") {
+ a.fromTo("y", round(top + h), round(top), {
+ start: st,
+ end,
+ ease: timing.ease,
+ });
+ }
+ node.animate(a);
+ }
+ children.push(node);
+ if (options.valueLabels) {
+ const text = yFormat(p.y);
+ const ly = grows === "up" ? top - lineHeight - 4 : top + h + 4;
+ label(
+ text,
+ { x: bx - 30, y: ly, width: bw - gap + 60, height: lineHeight },
+ "center",
+ {
+ delay: delay + timing.duration * 0.6,
+ color: strongText,
+ weight: 600,
+ },
+ `value-${si}-${i}`,
+ );
+ }
+ });
+ return;
+ }
+
+ if (kind === "candlestick" && band) {
+ const up = options.upColor ?? "#22c55e";
+ const down = options.downColor ?? "#ef4444";
+ const bw = band.bandwidth();
+ (s.data as readonly ChartCandle[]).forEach((c, i) => {
+ const col = c.close >= c.open ? up : down;
+ const cxp = plot.x + (band(String(c.x)) ?? 0) + bw / 2;
+ const delay = categoryIndex(c.x) * bandStep;
+ const parts: [string, Rect][] = [
+ [
+ "wick",
+ {
+ x: cxp - Math.max(1, bw * 0.06),
+ y: plot.y + y(c.high),
+ width: Math.max(2, bw * 0.12),
+ height: Math.max(1, y(c.low) - y(c.high)),
+ },
+ ],
+ [
+ "body",
+ {
+ x: cxp - bw / 2,
+ y: plot.y + y(Math.max(c.open, c.close)),
+ width: bw,
+ height: Math.max(2, Math.abs(y(c.open) - y(c.close))),
+ },
+ ],
+ ];
+ for (const [part, r] of parts) {
+ const node = Layer.box({
+ id: `${id}-candle-${si}-${i}-${part}`,
+ position: "absolute",
+ x: round(r.x),
+ y: round(r.y),
+ width: round(r.width),
+ height: round(r.height),
+ background: col,
+ borderRadius:
+ part === "body" ? Math.min(radius / 2, r.width / 2) : 0,
+ });
+ if (timing.enabled) {
+ const st = timing.start + delay;
+ const mid = r.y + r.height / 2;
+ node.animate(
+ LayerAnimation.create()
+ .fromTo("height", 0, round(r.height), {
+ start: st,
+ end: st + timing.duration,
+ ease: timing.ease,
+ })
+ .fromTo("y", round(mid), round(r.y), {
+ start: st,
+ end: st + timing.duration,
+ ease: timing.ease,
+ }),
+ );
+ }
+ children.push(node);
+ }
+ });
+ return;
+ }
+
+ if (kind === "line" || kind === "area") {
+ const sw = s.strokeWidth ?? 3;
+ const m = Math.ceil(sw * 2 + (s.pointRadius ?? 0) + 2);
+ const xy = pts.map((p, i) => ({
+ x: xPos(p.x) + m,
+ top: (range ? y(range[i][1]) : y(p.y)) + m,
+ base:
+ (range
+ ? y(range[i][0])
+ : y(Math.max(y.domain()[0], Math.min(0, y.domain()[1])))) + m,
+ }));
+ const curve = curveOf(s.curve);
+ const frame: Rect = {
+ x: plot.x - m,
+ y: plot.y - m,
+ width: plot.width + 2 * m,
+ height: plot.height + 2 * m,
+ };
+ const delay = rank * (timing.duration / 3);
+
+ if (kind === "area") {
+ const d = d3Area<(typeof xy)[number]>()
+ .x((p) => p.x)
+ .y0((p) => p.base)
+ .y1((p) => p.top)
+ .curve(curve)(xy);
+ if (d) {
+ const node = Layer.shape("path", {
+ id: `${id}-area-${si}`,
+ position: "absolute",
+ ...roundRect(frame),
+ d: roundPath(d),
+ fillType: "linear",
+ fillColor: withAlpha(color, 0.45),
+ gradientEndColor: withAlpha(color, 0.02),
+ gradientAngle: 90,
+ });
+ if (timing.enabled)
+ node.animate(
+ fadeIn(timing, delay + timing.duration * 0.4, timing.duration),
+ );
+ children.push(node);
+ }
+ }
+
+ const d = d3Line<(typeof xy)[number]>()
+ .x((p) => p.x)
+ .y((p) => p.top)
+ .curve(curve)(xy);
+ if (d && sw > 0) {
+ const node = Layer.shape("path", {
+ id: `${id}-line-${si}`,
+ position: "absolute",
+ ...roundRect(frame),
+ d: roundPath(d),
+ fillType: "none",
+ strokeColor: color,
+ strokeWidth: sw,
+ strokeLineCap: "round",
+ strokeLineJoin: "round",
+ });
+ if (timing.enabled) {
+ node.animate(
+ LayerAnimation.create().fromTo("trimEnd", 0, 1, {
+ start: timing.start + delay,
+ end: timing.start + delay + timing.duration * 1.5,
+ ease: "power2.inOut",
+ }),
+ );
+ }
+ children.push(node);
+ }
+
+ if ((s.pointRadius ?? 0) > 0) {
+ dots(
+ si,
+ pts,
+ color,
+ s.pointRadius ?? 0,
+ delay + timing.duration * 0.5,
+ range,
+ );
+ }
+ return;
+ }
+
+ if (kind === "scatter") {
+ dots(
+ si,
+ pts,
+ color,
+ s.pointRadius ?? 6,
+ rank * (timing.duration / 3),
+ range,
+ );
+ }
+ });
+
+ if (showLegend) legendRow(legendItems);
+
+ function dots(
+ si: number,
+ pts: Point[],
+ color: string,
+ r: number,
+ baseDelay: number,
+ range: [number, number][] | undefined,
+ ): void {
+ const step = staggerStep(pts.length);
+ pts.forEach((p, i) => {
+ const py = range ? y(range[i][1]) : y(p.y);
+ const node = Layer.shape("circle", {
+ id: `${id}-point-${si}-${i}`,
+ position: "absolute",
+ x: round(plot.x + xPos(p.x) - r),
+ y: round(plot.y + py - r),
+ width: round(r * 2),
+ height: round(r * 2),
+ fillColor: color,
+ anchorX: 0.5,
+ anchorY: 0.5,
+ });
+ if (timing.enabled) {
+ const st = timing.start + baseDelay + i * step;
+ node.animate(
+ LayerAnimation.create()
+ .fromTo("scale", 0, 1, {
+ start: st,
+ end: st + timing.duration * 0.6,
+ ease: "back.out(2)",
+ })
+ .fromTo("opacity", 0, 1, { start: st, end: st + 6 }),
+ );
+ }
+ children.push(node);
+ });
+ }
+ }
+
+ // ── shared helpers ──────────────────────────────────────────────────
+
+ function staggerStep(count: number): number {
+ if (!timing.enabled || count <= 1) return 0;
+ if (timing.stagger >= 0) return timing.stagger;
+ return Math.min(4, timing.duration / count);
+ }
+
+ function resolvePadding(
+ auto: Required<ChartPadding>,
+ ): Required<ChartPadding> {
+ const p = options.padding;
+ if (typeof p === "number") return { top: p, right: p, bottom: p, left: p };
+ return {
+ top: p?.top ?? auto.top,
+ right: p?.right ?? auto.right,
+ bottom: p?.bottom ?? auto.bottom,
+ left: p?.left ?? auto.left,
+ };
+ }
+
+ function plotRect(p: Required<ChartPadding>): Rect {
+ return {
+ x: p.left,
+ y: p.top,
+ width: Math.max(1, width - p.left - p.right),
+ height: Math.max(1, height - p.top - p.bottom),
+ };
+ }
+
+ function legendColumnWidth(names: string[]): number {
+ const longest = Math.max(0, ...names.map((n) => n.length));
+ return Math.min(width * 0.4, longest * fontSize * 0.6 + fontSize + 48);
+ }
+
+ function legendColumn(
+ items: { name: string; color: string }[],
+ at: { x: number; y: number; height: number },
+ ): void {
+ const rowH = lineHeight + 8;
+ const top = at.y + Math.max(0, (at.height - items.length * rowH) / 2);
+ items.forEach((item, i) => {
+ legendItem(item, at.x, top + i * rowH, i);
+ });
+ }
+
+ function legendRow(items: { name: string; color: string }[]): void {
+ const widths = items.map(
+ (it) => it.name.length * fontSize * 0.6 + fontSize + 28,
+ );
+ const total = widths.reduce((a, b) => a + b, 0);
+ let cursor = Math.max(0, width - total - 20);
+ items.forEach((item, i) => {
+ legendItem(item, cursor, 4, i);
+ cursor += widths[i];
+ });
+ }
+
+ function legendItem(
+ item: { name: string; color: string },
+ lx: number,
+ ly: number,
+ i: number,
+ ): void {
+ const sw = Math.round(fontSize * 0.7);
+ const swatch = Layer.box({
+ id: `${id}-legend-swatch-${i}`,
+ position: "absolute",
+ x: round(lx),
+ y: round(ly + (lineHeight - sw) / 2),
+ width: sw,
+ height: sw,
+ borderRadius: Math.round(sw / 4),
+ background: item.color,
+ });
+ if (timing.enabled) swatch.animate(fadeIn(timing, 0, timing.duration / 2));
+ children.push(swatch);
+ label(
+ item.name,
+ {
+ x: lx + sw + 8,
+ y: ly,
+ width: item.name.length * fontSize * 0.6 + 12,
+ height: lineHeight,
+ },
+ "start",
+ { color: options.textColor ?? "#cbd5e1" },
+ `legend-${i}`,
+ );
+ }
+}
+
+function snapKeyframes(node: LayoutNode): void {
+ for (const track of node.animation?.tracks ?? []) {
+ for (const kf of track.keyframes ?? []) kf.frame = Math.round(kf.frame);
+ }
+ for (const child of (node as { children?: LayoutNode[] }).children ?? []) {
+ snapKeyframes(child);
+ }
+}
+
+function roundRect(r: Rect): Rect {
+ return {
+ x: round(r.x),
+ y: round(r.y),
+ width: round(r.width),
+ height: round(r.height),
+ };
+}
+
+/** Shortens the long float literals d3 emits. */
+function roundPath(d: string): string {
+ return d.replace(/-?\d*\.\d{3,}(?:e-?\d+)?/gi, (n) =>
+ String(round(Number(n))),
+ );
+}
+
+/** Offsets an absolute SVG path (as produced by d3-arc) by dx, dy. */
+function translatePath(d: string, dx: number, dy: number): string {
+ // d3-arc emits M/L/A/Z with absolute coordinates; A has 7 params, of which
+ // the last two are the endpoint.
+ const out: string[] = [];
+ const re = /([MLAZ])([^MLAZ]*)/gi;
+ for (const [, cmd, args] of d.matchAll(re)) {
+ const nums = (args.match(/-?\d*\.?\d+(?:e-?\d+)?/gi) ?? []).map(Number);
+ if (cmd.toUpperCase() === "A") {
+ for (let i = 0; i + 6 < nums.length; i += 7) {
+ nums[i + 5] += dx;
+ nums[i + 6] += dy;
+ }
+ } else if (cmd.toUpperCase() !== "Z") {
+ for (let i = 0; i + 1 < nums.length; i += 2) {
+ nums[i] += dx;
+ nums[i + 1] += dy;
+ }
+ }
+ out.push(cmd + nums.map(round).join(","));
+ }
+ return out.join("");
+}
diff --git a/packages/gitframes/src/chartgpu-conformance.test.ts b/packages/gitframes/src/chartgpu-conformance.test.ts
deleted file mode 100644
index 9aeccbbd..00000000
--- a/packages/gitframes/src/chartgpu-conformance.test.ts
+++ /dev/null
@@ -1,332 +0,0 @@
-import { Canvas, loadImage } from "skia-canvas";
-import { describe, expect, it, vi } from "vitest";
-import {
- ChartGPUEngineBridge,
- type ChartGPUOptions,
- Composition,
- ensureDevice,
- Layer,
- LayerAnimation,
- signal,
-} from "./index.js";
-
-interface DecodedImage {
- width: number;
- height: number;
- pixels: Uint8ClampedArray;
-}
-
-interface PixelRgba {
- r: number;
- g: number;
- b: number;
- a: number;
-}
-
-async function decodePngPixels(pngBuffer: Buffer): Promise<DecodedImage> {
- const img = await loadImage(pngBuffer);
- const canvas = new Canvas(img.width, img.height);
- const ctx = canvas.getContext("2d");
- ctx.drawImage(img, 0, 0);
- const imgData = ctx.getImageData(0, 0, img.width, img.height);
- return {
- width: img.width,
- height: img.height,
- pixels: imgData.data,
- };
-}
-
-function countNonZeroPixels(image: DecodedImage, threshold = 10): number {
- let count = 0;
- for (let i = 0; i < image.pixels.length; i += 4) {
- const a = image.pixels[i + 3] ?? 0;
- const r = image.pixels[i] ?? 0;
- const g = image.pixels[i + 1] ?? 0;
- const b = image.pixels[i + 2] ?? 0;
- if (a > threshold && (r > threshold || g > threshold || b > threshold)) {
- count++;
- }
- }
- return count;
-}
-
-describe("ChartGPU Conformance Test Suite (Headless WebGPU & Compositor Integration)", () => {
- it("1. Shared Device Reuse Test: reuses context device without calling requestDevice", async () => {
- const device = await ensureDevice();
- const createTextureSpy = vi.spyOn(device, "createTexture");
-
- const bridge = new ChartGPUEngineBridge({
- device,
- width: 400,
- height: 200,
- });
-
- // The bridge takes chartgpu's own option type, not the document schema's.
- const testOptions: Parameters<ChartGPUEngineBridge["initialize"]>[0] = {
- theme: "dark",
- series: [
- {
- type: "line",
- data: [
- [0, 10],
- [1, 25],
- [2, 40],
- ],
- },
- ],
- };
-
- await bridge.initialize(testOptions);
- expect(bridge.width).toBe(400);
- expect(bridge.height).toBe(200);
-
- const renderedTex = await bridge.renderFrame(1.0);
- expect(renderedTex).toBeDefined();
- expect(createTextureSpy).toHaveBeenCalled();
-
- bridge.destroy();
- });
-
- it("2. Offscreen Rendering & Pixel Sampling: renders line chart with area gradient into offscreen texture", async () => {
- const comp = new Composition({
- width: 400,
- height: 200,
- fps: 30,
- durationMs: 1000,
- backgroundColor: "#000000",
- });
-
- const lineChartOptions: ChartGPUOptions = {
- theme: "dark",
- backgroundColor: "transparent",
- padding: { top: 10, right: 10, bottom: 10, left: 10 },
- xAxis: { type: "category", show: false },
- yAxis: { type: "value", show: false },
- series: [
- {
- type: "line",
- data: [
- [0, 10],
- [1, 80],
- [2, 30],
- [3, 90],
- [4, 50],
- ],
- lineStyle: {
- color: "#3b82f6",
- width: 3,
- smooth: true,
- },
- areaStyle: {
- color: "#3b82f6",
- gradient: {
- direction: "vertical",
- stops: [
- { offset: 0, color: "rgba(59, 130, 246, 0.8)" },
- { offset: 1, color: "rgba(59, 130, 246, 0.0)" },
- ],
- },
- opacity: 0.6,
- },
- },
- ],
- };
-
- comp.add(
- Layer.chart(lineChartOptions, {
- id: "conformance-chart",
- x: 0,
- y: 0,
- width: 400,
- height: 200,
- }),
- );
-
- const pngBuffer = await comp.renderFrame({ atMs: 0 });
- const decoded = await decodePngPixels(pngBuffer);
-
- expect(decoded.width).toBe(400);
- expect(decoded.height).toBe(200);
-
- const nonZeroCount = countNonZeroPixels(decoded, 10);
- expect(nonZeroCount).toBeGreaterThan(100);
-
- // Verify presence of blue hues from #3b82f6 (R: ~59, G: ~130, B: ~246)
- let hasBlueLineOrAreaPixel = false;
- for (let i = 0; i < decoded.pixels.length; i += 4) {
- const b = decoded.pixels[i + 2] ?? 0;
- const r = decoded.pixels[i] ?? 0;
- if (b > 100 && b > r + 30) {
- hasBlueLineOrAreaPixel = true;
- break;
- }
- }
- expect(hasBlueLineOrAreaPixel).toBe(true);
- });
-
- it("3. Temporal Write-On Progress Delta: frame at progress 0.8 has strictly greater non-zero pixels than progress 0.2", async () => {
- const dataPoints: [number, number][] = [];
- for (let i = 0; i < 50; i++) {
- dataPoints.push([i, Math.sin(i * 0.2) * 40 + 50]);
- }
-
- const chartOptions: ChartGPUOptions = {
- theme: "dark",
- backgroundColor: "transparent",
- xAxis: { type: "category", show: false },
- yAxis: { type: "value", show: false },
- series: [
- {
- type: "line",
- data: dataPoints,
- lineStyle: { color: "#00ff88", width: 2 },
- },
- ],
- };
-
- const comp = new Composition({
- width: 400,
- height: 200,
- fps: 30,
- durationMs: 1000,
- backgroundColor: "#000000",
- });
-
- const chartLayer = Layer.chart(chartOptions, {
- id: "writeon-chart",
- x: 0,
- y: 0,
- width: 400,
- height: 200,
- }).animate(
- LayerAnimation.create().drawProgress(0.2, 0.8, { from: 0, to: 30 }),
- );
-
- comp.add(chartLayer);
-
- const isGreenLinePixel = (px: PixelRgba) => px.g > 100 && px.g > px.r + 30;
- const countGreenPixels = (image: DecodedImage) => {
- let count = 0;
- for (let i = 0; i < image.pixels.length; i += 4) {
- const r = image.pixels[i] ?? 0;
- const g = image.pixels[i + 1] ?? 0;
- const b = image.pixels[i + 2] ?? 0;
- const a = image.pixels[i + 3] ?? 0;
- if (isGreenLinePixel({ r, g, b, a })) {
- count++;
- }
- }
- return count;
- };
-
- const pngEarly = await comp.renderFrame({ frame: 0 });
- const decodedEarly = await decodePngPixels(pngEarly);
- const greenEarly = countGreenPixels(decodedEarly);
-
- const pngLate = await comp.renderFrame({ frame: 20 });
- const decodedLate = await decodePngPixels(pngLate);
- const greenLate = countGreenPixels(decodedLate);
-
- expect(greenLate).toBeGreaterThan(greenEarly);
- });
-
- it("4. 3D Perspective Projection Conformance: tilts chart container with rotateX, rotateY, and perspective", async () => {
- const chartOptions: ChartGPUOptions = {
- theme: "dark",
- backgroundColor: "#1e293b",
- xAxis: { type: "category", show: false },
- yAxis: { type: "value", show: false },
- series: [
- {
- type: "line",
- data: [
- [0, 10],
- [1, 50],
- [2, 20],
- [3, 80],
- ],
- lineStyle: { color: "#f59e0b", width: 4 },
- },
- ],
- };
-
- const compTilted = new Composition({
- width: 400,
- height: 300,
- fps: 30,
- durationMs: 1000,
- backgroundColor: "#000000",
- });
-
- compTilted.add(
- Layer.chart(chartOptions, {
- id: "tilted-chart",
- x: 50,
- y: 50,
- width: 300,
- height: 200,
- rotateX: 20,
- rotateY: -25,
- perspective: 800,
- }),
- );
-
- const pngTilted = await compTilted.renderFrame({ frame: 0 });
- const decodedTilted = await decodePngPixels(pngTilted);
-
- const nonZeroTilted = countNonZeroPixels(decodedTilted, 10);
- expect(nonZeroTilted).toBeGreaterThan(50);
- });
-
- it("5. Reactive Signal Integration: dynamic signal modulates chart progression", async () => {
- const dynProgress = signal(0.1);
-
- const chartOptions: ChartGPUOptions = {
- theme: "dark",
- series: [
- {
- type: "line",
- data: [
- [0, 10],
- [1, 30],
- [2, 60],
- [3, 90],
- ],
- lineStyle: { color: "#ef4444", width: 2 },
- },
- ],
- };
-
- const comp = new Composition({
- width: 400,
- height: 200,
- fps: 30,
- durationMs: 1000,
- backgroundColor: "#000000",
- });
-
- const chartLayer = Layer.chart(chartOptions, {
- id: "signal-chart",
- x: 0,
- y: 0,
- width: 400,
- height: 200,
- progress: dynProgress.value,
- });
- comp.add(chartLayer);
-
- const png1 = await comp.renderFrame({ atMs: 0 });
- const decoded1 = await decodePngPixels(png1);
- const count1 = countNonZeroPixels(decoded1, 10);
-
- // Update reactive signal
- dynProgress.value = 1.0;
- chartLayer.progress = dynProgress.value;
-
- const png2 = await comp.renderFrame({ atMs: 0 });
- const decoded2 = await decodePngPixels(png2);
- const count2 = countNonZeroPixels(decoded2, 10);
-
- expect(count2).toBeGreaterThanOrEqual(count1);
- });
-});
diff --git a/packages/gitframes/src/index.ts b/packages/gitframes/src/index.ts
index bae197be..df87912a 100644
--- a/packages/gitframes/src/index.ts
+++ b/packages/gitframes/src/index.ts
@@ -119,8 +119,6 @@ import {
type AnimationTrack,
type BoxNode,
type CameraNode,
- type ChartGPUOptions,
- type ChartNode,
type CompositorProgramConfig,
type CompositorToProgramOptions,
compositorToProgram,
@@ -174,6 +172,7 @@ import {
TensorPipeline,
} from "@gitframes/tensor-webgpu";
import { inputStore, mediaDecoderCache } from "@gitframes/webgpu-renderers";
+import { buildChart, type ChartOptions } from "./chart.js";
import {
ApplyLUT,
type ApplyLUTProps,
@@ -418,32 +417,11 @@ export {
type CarrierHandoffConfig,
CarrierHandoffConfigSchema,
type CarrierState,
- type ChartAreaStyle,
- ChartAreaStyleSchema,
- type ChartAxis,
- ChartAxisSchema,
- type ChartDataPoint2D,
- ChartDataPoint2DSchema,
- type ChartDataPointOHLC,
- ChartDataPointOHLCSchema,
- type ChartGPUOptions,
- ChartGPUOptionsSchema,
- type ChartLineStyle,
- ChartLineStyleSchema,
- type ChartNode,
- ChartNodeSchema,
- type ChartPointStyle,
- ChartPointStyleSchema,
- type ChartSeries,
- ChartSeriesSchema,
- type ChartSeriesType,
- ChartSeriesTypeSchema,
type ChromaticGlitchConfig,
ChromaticGlitchConfigSchema,
type ColorSignalOptions,
type ColorStop,
ColorStopSchema,
- CompositionChartNodeSchema,
type CompositorProgramConfig,
CompositorProgramSchema,
type CompositorToProgramOptions,
@@ -605,18 +583,10 @@ export {
type BlendMode,
type Bone3D,
Camera3D,
- ChartGPUEngineBridge,
- type ChartNodeProps,
- chartBridgeCache,
- drawChartNode,
EffectPipeline,
ensureDevice,
GlassPipeline,
type GPULightData,
- HeadlessChartCanvasElementMock,
- HeadlessChartContainerMock,
- type HeadlessChartTarget,
- HeadlessGPUCanvasContextMock,
inputStore,
Light3D,
type Light3DOptions,
@@ -645,6 +615,19 @@ export {
shaderStore,
textureCache,
} from "@gitframes/webgpu-renderers";
+export {
+ type ChartAnimationOptions,
+ type ChartAxisOptions,
+ type ChartCandle,
+ type ChartDatum,
+ type ChartOptions,
+ type ChartPadding,
+ type ChartSeries,
+ type ChartSlice,
+ type ChartType,
+ type ChartX,
+ DEFAULT_CHART_COLORS,
+} from "./chart.js";
export {
ApplyLUT,
type ApplyLUTProps,
@@ -2442,16 +2425,17 @@ export const Layer = {
],
});
},
+ /**
+ * A line, area, bar, scatter, candlestick, pie or donut chart. Returns a box
+ * of ordinary nodes (bars are boxes, lines and slices are path shapes,
+ * labels are text), so it positions, animates and composites like any layer.
+ * `props` applies to that box: position, id, timing, effects.
+ */
chart: (
- options: ChartGPUOptions,
- props: Partial<ChartNode> = {},
- ): AnimatableNode<ChartNode> =>
- withAnimation({
- id: props.id ?? autoId("chart"),
- kind: "chart",
- chartOptions: options,
- ...props,
- }),
+ options: ChartOptions,
+ props: Partial<BoxNode> = {},
+ ): AnimatableNode<BoxNode> =>
+ buildChart(options, props, FontManager.getAll()[0]?.family ?? "Inter"),
camera: (options: Partial<CameraNode> = {}): AnimatableNode<CameraNode> =>
withAnimation<CameraNode>({
id: options.id ?? autoId("camera"),
@@ -2654,6 +2638,12 @@ export const Light = {
}),
};
+export {
+ type PreviewOptions,
+ type PreviewSession,
+ type PreviewSource,
+ startPreview,
+} from "./preview/index.js";
export {
type AudioQaStats,
computeGridLayout,
diff --git a/packages/gitframes/src/preview/blit.ts b/packages/gitframes/src/preview/blit.ts
new file mode 100644
index 00000000..51b605ac
--- /dev/null
+++ b/packages/gitframes/src/preview/blit.ts
@@ -0,0 +1,87 @@
+/// <reference lib="dom" />
+/// <reference types="webgpu" />
+/**
+ * Copies one texture onto another of any size, with linear filtering. Kept
+ * apart from the 2D renderer on purpose: buffered frames are shown while the
+ * next frame is being drawn, and the renderer's pools must not be touched then.
+ */
+
+const WGSL = /* wgsl */ `
+@group(0) @binding(0) var src: texture_2d<f32>;
+@group(0) @binding(1) var samp: sampler;
+
+struct VSOut {
+ @builtin(position) pos: vec4<f32>,
+ @location(0) uv: vec2<f32>,
+};
+
+@vertex fn vs(@builtin(vertex_index) i: u32) -> VSOut {
+ var p = array<vec2<f32>, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));
+ var out: VSOut;
+ out.pos = vec4(p[i], 0.0, 1.0);
+ out.uv = vec2(p[i].x * 0.5 + 0.5, 0.5 - p[i].y * 0.5);
+ return out;
+}
+
+@fragment fn fs(in: VSOut) -> @location(0) vec4<f32> {
+ return textureSampleLevel(src, samp, in.uv, 0.0);
+}
+`;
+
+export class Blitter {
+ private readonly pipeline: GPURenderPipeline;
+ private readonly sampler: GPUSampler;
+ private readonly bindGroups = new WeakMap<GPUTexture, GPUBindGroup>();
+
+ constructor(
+ private readonly device: GPUDevice,
+ format: GPUTextureFormat,
+ ) {
+ const module = device.createShaderModule({
+ label: "preview_blit",
+ code: WGSL,
+ });
+ this.pipeline = device.createRenderPipeline({
+ label: "preview_blit",
+ layout: "auto",
+ vertex: { module, entryPoint: "vs" },
+ fragment: { module, entryPoint: "fs", targets: [{ format }] },
+ primitive: { topology: "triangle-list" },
+ });
+ this.sampler = device.createSampler({
+ magFilter: "linear",
+ minFilter: "linear",
+ });
+ }
+
+ /** Draws all of `src` over all of `dst` and submits it. */
+ blit(src: GPUTexture, dst: GPUTexture): void {
+ let bindGroup = this.bindGroups.get(src);
+ if (!bindGroup) {
+ bindGroup = this.device.createBindGroup({
+ layout: this.pipeline.getBindGroupLayout(0),
+ entries: [
+ { binding: 0, resource: src.createView() },
+ { binding: 1, resource: this.sampler },
+ ],
+ });
+ this.bindGroups.set(src, bindGroup);
+ }
+ const encoder = this.device.createCommandEncoder({ label: "preview_blit" });
+ const pass = encoder.beginRenderPass({
+ colorAttachments: [
+ {
+ view: dst.createView(),
+ loadOp: "clear",
+ storeOp: "store",
+ clearValue: { r: 0, g: 0, b: 0, a: 0 },
+ },
+ ],
+ });
+ pass.setPipeline(this.pipeline);
+ pass.setBindGroup(0, bindGroup);
+ pass.draw(3);
+ pass.end();
+ this.device.queue.submit([encoder.finish()]);
+ }
+}
diff --git a/packages/gitframes/src/preview/bundle.ts b/packages/gitframes/src/preview/bundle.ts
new file mode 100644
index 00000000..62cacae4
--- /dev/null
+++ b/packages/gitframes/src/preview/bundle.ts
@@ -0,0 +1,258 @@
+/**
+ * Bundles a project's composition module, the engine and the browser player
+ * into one script, so the page runs the composition code itself and renders
+ * with WebGPU. One bundle, so the user's code and the engine share the same
+ * signal and clock instances.
+ *
+ * Node APIs that compositions commonly use at build time are shimmed: `path`,
+ * `url`, `import.meta.url` (each file keeps its own `file://` URL), and the
+ * synchronous `fs` reads, which fetch the file from the preview server.
+ * Absolute file paths double as URLs on that server, so assets referenced by
+ * path load unchanged. Node-only packages become stubs that throw when used.
+ */
+import fs from "node:fs";
+import { createRequire } from "node:module";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import type { Plugin } from "esbuild";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+// Spelled in two parts so this file survives its own rewrite.
+const META_URL = ["import", "meta", "url"].join(".");
+const require = createRequire(import.meta.url);
+
+/** Packages that only work in Node; the browser never needs them to draw. */
+const NODE_ONLY = [
+ "sharp",
+ "skia-canvas",
+ "node-av",
+ "onnxruntime-node",
+ "@resvg/resvg-js",
+ "@napi-rs/webcodecs",
+ "@mediabunny/server",
+ "@mediabunny/mp3-encoder",
+ "webgpu",
+ "pino",
+ "pino-pretty",
+ "dotenv",
+ "@gitframes/renderer",
+ "esbuild",
+ "@gitframes/server-utils",
+];
+
+// Reported as an ES module so named imports (`import { homedir } from "os"`)
+// read through the proxy instead of being copied off it.
+const STUB = `
+const stub = () => new Proxy(function () {}, {
+ get: (_t, k) => (k === "__esModule" ? true : k === Symbol.toPrimitive ? () => "" : stub()),
+ apply: () => stub(),
+ construct: () => stub(),
+});
+module.exports = stub();
+`;
+
+const SHIMS: Record<string, string> = {
+ path: "path.ts",
+ "path/posix": "path.ts",
+ url: "url.ts",
+ os: "os.ts",
+ fs: "fs.ts",
+ "fs/promises": "fs-promises.ts",
+};
+
+export interface BundleResult {
+ code: string;
+ /** Source files the bundle was built from, to watch for changes. */
+ inputs: string[];
+}
+
+export async function bundlePlayer(options: {
+ /** Module that exports the composition factory. */
+ entry: string;
+ /** Name of the export; a function returning a Composition (or one itself). */
+ exportName: string;
+}): Promise<BundleResult> {
+ const { build } = await import("esbuild");
+ const entry = path.resolve(options.entry);
+ const player = resolveOwn("player");
+ const renderers = builtinRenderersModule();
+ const shimDir = path.join(path.dirname(player), "shims");
+ const vision = visionAssets();
+
+ const plugin: Plugin = {
+ name: "gitframes-preview",
+ setup(b) {
+ b.onResolve({ filter: /^gitframes-preview:entry$/ }, () => ({
+ path: "entry",
+ namespace: "gitframes-preview",
+ }));
+ b.onLoad({ filter: /.*/, namespace: "gitframes-preview" }, () => ({
+ contents: [
+ `import * as mod from ${JSON.stringify(entry)};`,
+ `import { startPlayer } from ${JSON.stringify(player)};`,
+ `import { BUILTIN_NODE_RENDERERS } from ${JSON.stringify(renderers)};`,
+ `startPlayer(mod, ${JSON.stringify(options.exportName)}, {`,
+ " renderers: BUILTIN_NODE_RENDERERS,",
+ // Vision nodes run on onnxruntime-web; its .wasm files come from the server.
+ " loadOrt: async () => {",
+ ' const ort = await import("onnxruntime-web/webgpu");',
+ ` ort.env.wasm.wasmPaths = ${JSON.stringify(`/@fs${vision.ortDir}/`)};`,
+ ' ort.env.logLevel = "error";',
+ " return ort;",
+ " },",
+ "});",
+ ].join("\n"),
+ resolveDir: path.dirname(entry),
+ loader: "ts",
+ }));
+
+ // onnxruntime-web is the vision package's (optional) dependency.
+ b.onResolve({ filter: /^onnxruntime-web(\/|$)/ }, (args) => {
+ if (args.pluginData?.fromVision) return undefined;
+ return b.resolve(args.path, {
+ kind: args.kind,
+ resolveDir: vision.packageDir,
+ pluginData: { fromVision: true },
+ });
+ });
+
+ b.onResolve({ filter: /^(node:)?[a-z_/]+$/ }, (args) => {
+ const name = args.path.replace(/^node:/, "");
+ if (SHIMS[name]) return { path: resolveShim(shimDir, SHIMS[name]) };
+ if (args.path.startsWith("node:") || isBuiltin(name))
+ return { path: name, namespace: "gitframes-stub" };
+ return undefined;
+ });
+ b.onResolve({ filter: /.*/ }, (args) => {
+ const pkg = packageName(args.path);
+ if (pkg && NODE_ONLY.includes(pkg))
+ return { path: args.path, namespace: "gitframes-stub" };
+ return undefined;
+ });
+ b.onLoad({ filter: /.*/, namespace: "gitframes-stub" }, () => ({
+ contents: STUB,
+ loader: "js",
+ }));
+
+ // Each file keeps its own URL, as `fileURLToPath(import.meta.url)`
+ // expects: the expression becomes a constant declared per file.
+ b.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (args) => {
+ if (args.path.includes(`${path.sep}node_modules${path.sep}`))
+ return undefined;
+ const source = await fs.promises.readFile(args.path, "utf8");
+ if (!source.includes(META_URL)) return undefined;
+ return {
+ contents: `const __gitframesFileUrl = ${JSON.stringify(pathToFileURL(args.path).href)};\n${source.replaceAll(META_URL, "__gitframesFileUrl")}`,
+ loader: loaderFor(args.path),
+ };
+ });
+ },
+ };
+
+ const result = await build({
+ entryPoints: ["gitframes-preview:entry"],
+ bundle: true,
+ write: false,
+ format: "esm",
+ platform: "browser",
+ target: "es2022",
+ conditions: ["development", "browser", "import"],
+ mainFields: ["browser", "module", "main"],
+ metafile: true,
+ sourcemap: "inline",
+ logLevel: "silent",
+ define: {
+ "process.env.NODE_ENV": '"development"',
+ // Cached models load from the server, which serves this folder.
+ "process.env.GITFRAMES_MODELS_DIR": JSON.stringify(vision.modelsDir),
+ global: "globalThis",
+ },
+ inject: [resolveShim(shimDir, "process.ts")],
+ plugins: [plugin],
+ });
+
+ const inputs = Object.keys(result.metafile?.inputs ?? {})
+ .filter((p) => !p.includes(":") && !p.includes("node_modules"))
+ .map((p) => path.resolve(p));
+ return { code: result.outputFiles[0].text, inputs };
+}
+
+function resolveOwn(name: string): string {
+ // The player is bundled from source: next to this file in development,
+ // and from the package's src/ when this runs from dist/.
+ for (const dir of [HERE, path.join(HERE, "..", "src", "preview")]) {
+ const file = path.join(dir, `${name}.ts`);
+ if (fs.existsSync(file)) return file;
+ }
+ throw new Error(
+ `[gitframes] The browser preview needs the gitframes sources (src/preview/${name}.ts), which this install does not include.`,
+ );
+}
+
+/**
+ * Where vision models are cached (as `@gitframes/vision` resolves it), and the
+ * onnxruntime-web build that runs them in the browser.
+ */
+export function visionAssets(): {
+ modelsDir: string;
+ packageDir: string;
+ ortDir: string;
+} {
+ const modelsDir = process.env.GITFRAMES_MODELS_DIR
+ ? path.resolve(process.env.GITFRAMES_MODELS_DIR)
+ : path.join(os.homedir(), ".cache", "gitframes", "models");
+ const packageDir = path.dirname(
+ path.dirname(require.resolve("@gitframes/vision")),
+ );
+ let ortDir = "";
+ try {
+ ortDir = path.dirname(
+ createRequire(path.join(packageDir, "package.json")).resolve(
+ "onnxruntime-web",
+ ),
+ );
+ } catch {}
+ return { modelsDir, packageDir, ortDir };
+}
+
+/** The generated list of node renderers, imported by package name. */
+function builtinRenderersModule(): string {
+ const dist = require.resolve("@gitframes/renderer");
+ const file = path.join(
+ path.dirname(dist),
+ "..",
+ "src",
+ "generated",
+ "node-renderers.ts",
+ );
+ if (!fs.existsSync(file))
+ throw new Error(`[gitframes] node renderer list not found at ${file}`);
+ return file;
+}
+
+function resolveShim(dir: string, file: string): string {
+ const ts = path.join(dir, file);
+ if (fs.existsSync(ts)) return ts;
+ return ts.replace(/\.ts$/, ".mjs");
+}
+
+function isBuiltin(name: string): boolean {
+ try {
+ return require("node:module").isBuiltin(name);
+ } catch {
+ return false;
+ }
+}
+
+function packageName(spec: string): string | undefined {
+ if (spec.startsWith(".") || spec.startsWith("/")) return undefined;
+ const parts = spec.split("/");
+ return spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
+}
+
+function loaderFor(file: string): "ts" | "tsx" | "js" | "jsx" {
+ if (file.endsWith(".tsx")) return "tsx";
+ if (file.endsWith(".jsx")) return "jsx";
+ return /\.[cm]?ts$/.test(file) ? "ts" : "js";
+}
diff --git a/packages/gitframes/src/preview/fixtures/comp.ts b/packages/gitframes/src/preview/fixtures/comp.ts
new file mode 100644
index 00000000..9a47e128
--- /dev/null
+++ b/packages/gitframes/src/preview/fixtures/comp.ts
@@ -0,0 +1,4 @@
+// A stand-in composition for the preview tests: size and timing only.
+export default function build() {
+ return { fps: 10, durationMs: 1000, width: 64, height: 36 };
+}
diff --git a/packages/gitframes/src/preview/index.ts b/packages/gitframes/src/preview/index.ts
new file mode 100644
index 00000000..b5e506ea
--- /dev/null
+++ b/packages/gitframes/src/preview/index.ts
@@ -0,0 +1,592 @@
+import { spawn } from "node:child_process";
+import { createHash, randomUUID } from "node:crypto";
+import fs from "node:fs";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import path from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import type { VirtualMediaData } from "@gitframes/core";
+import { encodeStereoWav } from "../audio/index.js";
+import { HeadlessMediaRenderer } from "../renderer/index.js";
+import { bundlePlayer, visionAssets } from "./bundle.js";
+import { previewPage } from "./page.js";
+
+/** Where the composition comes from: the module that builds it. */
+export interface PreviewSource {
+ /** Path or file URL of the module, e.g. `new URL("./film.ts", import.meta.url)`. */
+ entry: string | URL;
+ /**
+ * The export to preview: a function returning a `Composition` (it may be
+ * async), or a `Composition`. Defaults to `"default"`.
+ */
+ export?: string;
+}
+
+/** What the server needs from the composition: its size, timing and soundtrack. */
+interface PreviewTarget {
+ toVirtualMedia?(): VirtualMediaData;
+ toVirtualMediaAsync?(): Promise<VirtualMediaData>;
+ computeDuration?(): Promise<number>;
+ fps?: number;
+ durationMs?: number;
+ width?: number;
+ height?: number;
+}
+
+export interface PreviewOptions {
+ /**
+ * Port to listen on. Defaults to a port derived from the working directory,
+ * so every preview of a project lands on the same URL and an open tab picks
+ * up the next one by itself. A preview already running there is replaced.
+ */
+ port?: number;
+ /** Interface to bind. Defaults to "127.0.0.1" so the preview never leaves the machine. */
+ host?: string;
+ /**
+ * Open the page in the default browser. Defaults to true unless `CI` is set.
+ * Skipped when a tab from an earlier preview reconnects on its own.
+ */
+ open?: boolean;
+ /** Title shown in the page header. */
+ title?: string;
+ /** Mix and play the composition's audio. Defaults to true. */
+ audio?: boolean;
+ /** Optional shared renderer instance, used to mix the soundtrack. */
+ renderer?: HeadlessMediaRenderer;
+ /**
+ * Close the server this many milliseconds after the last open tab goes
+ * away (closed, not reloaded). Defaults to 5000. `false` keeps it serving
+ * until `close()`. Nothing closes before a tab has connected.
+ */
+ idleCloseMs?: number | false;
+ /**
+ * Files the page may load by absolute path (the composition's assets).
+ * Defaults to the repository that holds the entry, or its directory.
+ */
+ root?: string;
+}
+
+export interface PreviewSession {
+ url: string;
+ close(): Promise<void>;
+ /** Resolves when the server stops: `close()`, an idle tab, or a newer preview took over its port. */
+ closed: Promise<void>;
+}
+
+interface PreviewMeta {
+ session: string;
+ title: string;
+ fps: number;
+ frameCount: number;
+ width: number;
+ height: number;
+}
+
+type AudioStatus =
+ | { state: "mixing" }
+ | { state: "ready"; durationSec: number; peaks: number[] }
+ | { state: "none" }
+ | { state: "error"; error: string };
+
+const PEAK_BINS = 1200;
+/** Requests carrying this header come from another preview process, not a page. */
+const TAKEOVER_HEADER = "x-gitframes-preview";
+const PLAYER_PATH = "/@gitframes/player.js";
+
+/**
+ * Serves a localhost player for a composition. The page loads the
+ * composition's own code, bundled with the engine, and renders every frame
+ * with WebGPU in the browser, like the editor's player; nothing is streamed.
+ * The server provides the bundle, the project's files, and the soundtrack,
+ * which it mixes with the export engine.
+ *
+ * The server runs until its tab closes or `close()`. Starting another preview
+ * on the same port (the default for a project) stops this one, and open tabs
+ * reload into it.
+ */
+export async function startPreview(
+ source: PreviewSource,
+ options: PreviewOptions = {},
+): Promise<PreviewSession> {
+ const entry =
+ source.entry instanceof URL || String(source.entry).startsWith("file:")
+ ? fileURLToPath(source.entry)
+ : path.resolve(String(source.entry));
+ const exportName = source.export ?? "default";
+ const root = path.resolve(options.root ?? repoRoot(path.dirname(entry)));
+ // Vision nodes load their cached models and onnxruntime-web's .wasm files.
+ const vision = visionAssets();
+ const roots = [root, vision.modelsDir, vision.ortDir].filter(Boolean);
+ const sseClients = new Set<http.ServerResponse>();
+ const idleCloseMs = options.idleCloseMs ?? 5000;
+ let idleTimer: NodeJS.Timeout | undefined;
+ const title = options.title ?? "gitframes preview";
+ const session = randomUUID();
+
+ const target = await loadTarget(entry, exportName);
+ const meta = await resolveMeta(target, title, session);
+ let bundle: Promise<string> | undefined;
+ const playerBundle = () => {
+ bundle ??= bundlePlayer({ entry, exportName }).then((b) => b.code);
+ bundle.catch(() => {
+ bundle = undefined;
+ });
+ return bundle;
+ };
+
+ // ── Audio: mixed once, by the export engine ──
+ let audio: AudioStatus = {
+ state: options.audio === false ? "none" : "mixing",
+ };
+ let audioWav: Buffer | undefined;
+
+ function broadcast(event: string, data: unknown) {
+ for (const client of sseClients) {
+ client.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ }
+ }
+
+ function setAudio(next: AudioStatus) {
+ audio = next;
+ broadcast("audio", audio);
+ }
+
+ function startAudio() {
+ if (audio.state !== "mixing") return;
+ if (!target.toVirtualMediaAsync && !target.toVirtualMedia) {
+ setAudio({ state: "none" });
+ return;
+ }
+ const renderer = options.renderer ?? new HeadlessMediaRenderer();
+ (async () => {
+ const vm = target.toVirtualMediaAsync
+ ? await target.toVirtualMediaAsync()
+ : (target.toVirtualMedia as () => VirtualMediaData)();
+ return renderer.renderAudio(vm, { fps: meta.fps });
+ })().then(
+ ({ channels, sampleRate }) => {
+ const left = channels[0] ?? new Float32Array(0);
+ const right = channels[1] ?? left;
+ const peaks = computePeaks(left, right, PEAK_BINS);
+ if (left.length === 0 || Math.max(...peaks) < 0.001) {
+ setAudio({ state: "none" });
+ return;
+ }
+ audioWav = encodeStereoWav([left, right], { sampleRate });
+ setAudio({
+ state: "ready",
+ durationSec: left.length / sampleRate,
+ peaks: peaks.map((p) => Math.round(p * 1000) / 1000),
+ });
+ },
+ (err: unknown) => {
+ setAudio({
+ state: "error",
+ error: err instanceof Error ? err.message : String(err),
+ });
+ },
+ );
+ }
+
+ let resolveClosed!: () => void;
+ const closed = new Promise<void>((r) => {
+ resolveClosed = r;
+ });
+ let closing: Promise<void> | undefined;
+ function close(): Promise<void> {
+ closing ??= new Promise<void>((resolve) => {
+ clearTimeout(idleTimer);
+ for (const client of sseClients) client.end();
+ sseClients.clear();
+ server.close(() => {
+ resolve();
+ resolveClosed();
+ });
+ server.closeAllConnections();
+ });
+ return closing;
+ }
+
+ const server = http.createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ // Cross-origin isolation: lets onnxruntime-web use SharedArrayBuffer and
+ // threads for vision models (single-threaded otherwise). "credentialless"
+ // keeps cross-origin assets such as the font stylesheet loading.
+ res.setHeader("cross-origin-opener-policy", "same-origin");
+ res.setHeader("cross-origin-embedder-policy", "credentialless");
+ try {
+ if (req.method === "GET" && url.pathname === "/") {
+ res.writeHead(200, {
+ "content-type": "text/html; charset=utf-8",
+ "cache-control": "no-store",
+ });
+ res.end(previewPage);
+ return;
+ }
+ if (req.method === "GET" && url.pathname === "/meta") {
+ sendJson(res, 200, { ...meta, audio });
+ return;
+ }
+ if (req.method === "GET" && url.pathname === PLAYER_PATH) {
+ let code: string;
+ try {
+ code = await playerBundle();
+ } catch (err) {
+ // Shown on the page: usually an error in the composition's code.
+ const message = err instanceof Error ? err.message : String(err);
+ code = `throw new Error(${JSON.stringify(`Could not build the preview:\n${message}`)});`;
+ }
+ res.writeHead(200, {
+ "content-type": "text/javascript; charset=utf-8",
+ "cache-control": "no-store",
+ });
+ res.end(code);
+ return;
+ }
+ // `fs.existsSync` / `statSync` in the page: a missing file is an
+ // answer here, not a 404 the browser logs as an error.
+ if (req.method === "GET" && url.pathname === "/@gitframes/stat") {
+ const file = path.resolve(url.searchParams.get("path") ?? "");
+ let size = -1;
+ if (roots.some((r) => isInside(r, file))) {
+ size = await fs.promises.stat(file).then(
+ (st) => (st.isFile() ? st.size : -1),
+ () => -1,
+ );
+ }
+ sendJson(res, 200, { exists: size >= 0, size: Math.max(0, size) });
+ return;
+ }
+ if (req.method === "GET" && url.pathname === "/events") {
+ res.writeHead(200, {
+ "content-type": "text/event-stream",
+ "cache-control": "no-store",
+ connection: "keep-alive",
+ });
+ // Reconnect fast: a tab left open finds the next preview's
+ // server within a second of it starting.
+ res.write("retry: 1000\n");
+ res.write(
+ `event: hello\ndata: ${JSON.stringify({ session: meta.session })}\n\n`,
+ );
+ sseClients.add(res);
+ clearTimeout(idleTimer);
+ onClient?.();
+ req.on("close", () => {
+ sseClients.delete(res);
+ // A reload reconnects within a second; a closed tab doesn't.
+ if (sseClients.size === 0 && idleCloseMs !== false && !closing) {
+ idleTimer = setTimeout(() => {
+ if (sseClients.size === 0) void close();
+ }, idleCloseMs);
+ }
+ });
+ return;
+ }
+ // A newer preview of the same project wants this port. The custom
+ // header keeps web pages from triggering it (it forces a CORS preflight).
+ if (
+ req.method === "POST" &&
+ url.pathname === "/takeover" &&
+ req.headers[TAKEOVER_HEADER] === "1"
+ ) {
+ sendJson(res, 200, { ok: true });
+ setImmediate(() => void close());
+ return;
+ }
+ if (req.method === "GET" && url.pathname === "/audio") {
+ if (audio.state !== "ready" || !audioWav) {
+ sendJson(res, 404, { error: `audio is ${audio.state}` });
+ return;
+ }
+ res.writeHead(200, {
+ "content-type": "audio/wav",
+ "content-length": audioWav.length,
+ "cache-control": "no-store",
+ });
+ res.end(audioWav);
+ return;
+ }
+ // The composition's files, by absolute path: what the program
+ // references loads as-is.
+ if (req.method === "GET" || req.method === "HEAD") {
+ // The engine asks for local files under Vite's `/@fs/` prefix.
+ const file = path.resolve(
+ decodeURIComponent(url.pathname.replace(/^\/@fs(?=\/)/, "")),
+ );
+ if (roots.some((r) => isInside(r, file)) && (await isFile(file))) {
+ await sendFile(req, res, file);
+ return;
+ }
+ }
+ sendJson(res, 404, { error: "not found" });
+ } catch (err) {
+ if (!res.headersSent) {
+ sendJson(res, 500, {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ } else {
+ res.end();
+ }
+ }
+ });
+
+ let onClient: (() => void) | undefined;
+ const host = options.host ?? "127.0.0.1";
+ const port = options.port ?? stablePort();
+ const listen = (p: number) =>
+ new Promise<void>((resolve, reject) => {
+ const fail = (err: Error) => {
+ server.off("listening", ok);
+ reject(err);
+ };
+ const ok = () => {
+ server.off("error", fail);
+ resolve();
+ };
+ server.once("error", fail);
+ server.once("listening", ok);
+ server.listen(p, host);
+ });
+ try {
+ await listen(port);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "EADDRINUSE") throw err;
+ // Most likely the previous preview of this project: ask it to step aside.
+ if (await requestTakeover(host, port)) {
+ await listen(port).catch(() => listen(0));
+ } else if (options.port === undefined) {
+ await listen(0);
+ } else {
+ throw err;
+ }
+ }
+ const { port: actualPort } = server.address() as AddressInfo;
+ const url = `http://${host.includes(":") ? `[${host}]` : host}:${actualPort}/`;
+
+ // Build the page's bundle and mix the soundtrack while the browser opens.
+ void playerBundle().catch(() => {});
+ startAudio();
+ if (options.open ?? !process.env.CI) {
+ // A tab from the last preview reconnects within ~1 s and reloads itself;
+ // only open a new one when nobody comes back.
+ const reconnected = await new Promise<boolean>((resolve) => {
+ const timer = setTimeout(() => resolve(false), 2000);
+ onClient = () => {
+ clearTimeout(timer);
+ resolve(true);
+ };
+ if (sseClients.size > 0) onClient();
+ });
+ onClient = undefined;
+ if (!reconnected) openBrowser(url);
+ }
+
+ return { url, closed, close };
+}
+
+async function loadTarget(
+ entry: string,
+ exportName: string,
+): Promise<PreviewTarget> {
+ const mod = (await import(pathToFileURL(entry).href)) as Record<
+ string,
+ unknown
+ >;
+ const exported = mod[exportName];
+ if (exported === undefined) {
+ throw new Error(
+ `[gitframes] ${entry} has no export named "${exportName}" to preview.`,
+ );
+ }
+ return (
+ typeof exported === "function"
+ ? await (exported as () => unknown)()
+ : exported
+ ) as PreviewTarget;
+}
+
+/** The repository holding `dir` (nearest `.git`), else `dir` itself. */
+function repoRoot(dir: string): string {
+ for (let d = dir; ; d = path.dirname(d)) {
+ if (fs.existsSync(path.join(d, ".git"))) return d;
+ if (path.dirname(d) === d) return dir;
+ }
+}
+
+function isInside(root: string, file: string): boolean {
+ const rel = path.relative(root, file);
+ return !!rel && !rel.startsWith("..") && !path.isAbsolute(rel);
+}
+
+async function isFile(file: string): Promise<boolean> {
+ try {
+ return (await fs.promises.stat(file)).isFile();
+ } catch {
+ return false;
+ }
+}
+
+const CONTENT_TYPES: Record<string, string> = {
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".webp": "image/webp",
+ ".gif": "image/gif",
+ ".svg": "image/svg+xml",
+ ".mp4": "video/mp4",
+ ".mov": "video/quicktime",
+ ".webm": "video/webm",
+ ".mp3": "audio/mpeg",
+ ".wav": "audio/wav",
+ ".m4a": "audio/mp4",
+ ".ogg": "audio/ogg",
+ ".ttf": "font/ttf",
+ ".otf": "font/otf",
+ ".woff": "font/woff",
+ ".woff2": "font/woff2",
+ ".json": "application/json",
+ ".js": "text/javascript; charset=utf-8",
+ ".mjs": "text/javascript; charset=utf-8",
+ ".wasm": "application/wasm",
+ ".onnx": "application/octet-stream",
+ ".srt": "text/plain; charset=utf-8",
+ ".txt": "text/plain; charset=utf-8",
+};
+
+/** Serves a file, with byte ranges so video can seek without loading it whole. */
+async function sendFile(
+ req: http.IncomingMessage,
+ res: http.ServerResponse,
+ file: string,
+) {
+ const { size } = await fs.promises.stat(file);
+ const type =
+ CONTENT_TYPES[path.extname(file).toLowerCase()] ??
+ "application/octet-stream";
+ const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range ?? "");
+ let start = 0;
+ let end = size - 1;
+ if (range && (range[1] || range[2])) {
+ if (range[1]) {
+ start = Number(range[1]);
+ if (range[2]) end = Math.min(end, Number(range[2]));
+ } else {
+ start = Math.max(0, size - Number(range[2]));
+ }
+ if (start > end || start >= size) {
+ res.writeHead(416, { "content-range": `bytes */${size}` });
+ res.end();
+ return;
+ }
+ }
+ res.writeHead(range ? 206 : 200, {
+ "content-type": type,
+ "content-length": end - start + 1,
+ "accept-ranges": "bytes",
+ "cache-control": "no-cache",
+ ...(range && { "content-range": `bytes ${start}-${end}/${size}` }),
+ });
+ if (req.method === "HEAD") {
+ res.end();
+ return;
+ }
+ fs.createReadStream(file, { start, end }).pipe(res);
+}
+
+async function resolveMeta(
+ target: PreviewTarget,
+ title: string,
+ session: string,
+): Promise<PreviewMeta> {
+ const fps = target.fps ?? 24;
+ const durationMs =
+ target.durationMs ?? (await target.computeDuration?.()) ?? 5000;
+ return {
+ session,
+ title,
+ fps,
+ frameCount: Math.max(1, Math.round((durationMs / 1000) * fps)),
+ width: target.width ?? 1920,
+ height: target.height ?? 1080,
+ };
+}
+
+/** Same project, same port: 41000–41899, from the working directory. */
+function stablePort(): number {
+ const digest = createHash("sha1").update(process.cwd()).digest();
+ return 41000 + (digest.readUInt16BE(0) % 900);
+}
+
+/** Asks a preview already on `port` to shut down; false if something else is there. */
+async function requestTakeover(host: string, port: number): Promise<boolean> {
+ // A fresh connection (no agent): a pooled keep-alive socket may point at a
+ // server that is already gone.
+ const ok = await new Promise<boolean>((resolve) => {
+ const req = http.request(
+ {
+ host,
+ port,
+ method: "POST",
+ path: "/takeover",
+ agent: false,
+ headers: { [TAKEOVER_HEADER]: "1" },
+ timeout: 1500,
+ },
+ (res) => {
+ res.resume();
+ resolve(res.statusCode === 200);
+ },
+ );
+ req.on("timeout", () => req.destroy());
+ req.on("error", () => resolve(false));
+ req.end();
+ });
+ // Give it a moment to release the socket.
+ if (ok) await new Promise((r) => setTimeout(r, 150));
+ return ok;
+}
+
+/** Max absolute amplitude of both channels per bin, 0..1. */
+function computePeaks(
+ left: Float32Array,
+ right: Float32Array,
+ bins: number,
+): number[] {
+ const peaks = new Array<number>(bins).fill(0);
+ if (left.length === 0) return peaks;
+ const per = left.length / bins;
+ for (let b = 0; b < bins; b++) {
+ const start = Math.floor(b * per);
+ const end = Math.min(left.length, Math.floor((b + 1) * per));
+ let max = 0;
+ for (let i = start; i < end; i++) {
+ const v = Math.max(Math.abs(left[i] ?? 0), Math.abs(right[i] ?? 0));
+ if (v > max) max = v;
+ }
+ peaks[b] = Math.min(1, max);
+ }
+ return peaks;
+}
+
+function sendJson(res: http.ServerResponse, status: number, body: unknown) {
+ res.writeHead(status, {
+ "content-type": "application/json",
+ "cache-control": "no-store",
+ });
+ res.end(JSON.stringify(body));
+}
+
+function openBrowser(url: string) {
+ const [cmd, args] =
+ process.platform === "darwin"
+ ? ["open", [url]]
+ : process.platform === "win32"
+ ? ["cmd", ["/c", "start", "", url]]
+ : ["xdg-open", [url]];
+ try {
+ spawn(cmd, args, { stdio: "ignore", detached: true })
+ .on("error", () => {})
+ .unref();
+ } catch {}
+}
diff --git a/packages/gitframes/src/preview/page.ts b/packages/gitframes/src/preview/page.ts
new file mode 100644
index 00000000..df00bd53
--- /dev/null
+++ b/packages/gitframes/src/preview/page.ts
@@ -0,0 +1,617 @@
+/**
+ * Single-file preview UI served by `startPreview`. No framework, no build step.
+ * The page script avoids template literals so it can live inside this one.
+ */
+export const previewPage = /* html */ `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>gitframes preview</title>
+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 512 512%22%3E%3Cg fill=%22none%22 stroke=%22%233B82F6%22 stroke-linecap=%22round%22%3E%3Cpath d=%22M184 56H86q-30 0-30 30v98M328 56h98q30 0 30 30v98M184 456H86q-30 0-30-30v-98M328 456h98q30 0 30-30v-98%22 stroke-width=%2234%22/%3E%3Cpath d=%22M176 182v148m0-148c0 74 60 74 100 74%22 stroke-width=%2228%22/%3E%3C/g%3E%3Cg fill=%22%233B82F6%22%3E%3Ccircle cx=%22176%22 cy=%22172%22 r=%2232%22/%3E%3Ccircle cx=%22176%22 cy=%22340%22 r=%2232%22/%3E%3Cpath d=%22M284 200l78 56-78 56z%22 stroke=%22%233B82F6%22 stroke-width=%2234%22 stroke-linejoin=%22round%22/%3E%3C/g%3E%3C/svg%3E">
+<link rel="preconnect" href="https://fonts.googleapis.com">
+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
+<style>
+ :root {
+ --bg: #0e0f11; --surface: #16171a; --surface-2: #1d1e22; --surface-3: #26282d;
+ --line: #2a2c31; --line-2: #3a3c43;
+ --ink: #ededf0; --ink-2: #a6a8b0; --ink-3: #74777f;
+ --stage: #060607;
+ --primary-bg: #ededf0; --primary-ink: #0e0f11;
+ --brand: #3b82f6; --focus: #5eaefc; --ok: #4fbf7a; --bad: #f27d8d;
+ --wave: #4b4e57;
+ --radius: 10px;
+ --font: "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
+ color-scheme: dark;
+ }
+ @media (prefers-color-scheme: light) {
+ :root {
+ --bg: #f5f5f6; --surface: #ffffff; --surface-2: #f0f0f2; --surface-3: #e6e6e9;
+ --line: #e2e2e6; --line-2: #cfcfd5;
+ --ink: #15161a; --ink-2: #53555d; --ink-3: #85878f;
+ --stage: #0b0b0c;
+ --primary-bg: #15161a; --primary-ink: #ffffff;
+ --brand: #2563eb; --focus: #1c74cc; --ok: #23874a; --bad: #cf4057;
+ --wave: #c2c3ca;
+ color-scheme: light;
+ }
+ }
+ * { box-sizing: border-box; }
+ html, body { height: 100%; margin: 0; overflow: hidden; background: var(--bg); color: var(--ink); }
+ body {
+ display: flex; flex-direction: column; height: 100dvh;
+ font: 13.5px/1.45 var(--font); -webkit-font-smoothing: antialiased;
+ font-feature-settings: "cv11", "ss03";
+ }
+ button, input { font: inherit; color: inherit; }
+ button { cursor: pointer; }
+ button:focus-visible, input:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
+ .tnum { font-variant-numeric: tabular-nums; }
+ .grow { flex: 1; }
+ .spinner {
+ width: 12px; height: 12px; border-radius: 50%; flex: none;
+ border: 1.5px solid var(--line-2); border-top-color: var(--ink); animation: spin .8s linear infinite;
+ }
+ @keyframes spin { to { transform: rotate(360deg); } }
+ .dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; flex: none; }
+
+ /* ── Top bar ── */
+ .top { flex: none; display: flex; align-items: center; gap: 10px; padding: 0 20px; height: 50px; border-bottom: 1px solid var(--line); min-width: 0; }
+ .logo { width: 22px; height: 22px; flex: none; color: var(--brand); }
+ .sep { width: 1px; height: 18px; background: var(--line-2); flex: none; margin: 0 2px; }
+ .top h1 { font-size: 14px; font-weight: 600; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ .spec { color: var(--ink-3); font-size: 12px; white-space: nowrap; }
+ @media (max-width: 640px) { .spec { display: none; } }
+ .chip {
+ display: inline-flex; align-items: center; gap: 8px; height: 26px; padding: 0 10px; white-space: nowrap;
+ border: 1px solid var(--line); border-radius: 999px; color: var(--ink-2); font-size: 12px; background: var(--surface);
+ }
+ .chip[data-state="ready"] .dot { color: var(--ok); }
+ .chip[data-state="none"] .dot, .chip[data-state="offline"] .dot { color: var(--ink-3); }
+ .chip[data-state="error"] { color: var(--bad); }
+
+ /* ── Player: one screen, no page scroll; the picture takes the space left ── */
+ .player {
+ flex: 1; min-height: 0; display: flex; flex-direction: column; gap: 10px;
+ width: 100%; max-width: 1600px; margin: 0 auto; padding: 16px 20px 20px;
+ }
+ @media (max-width: 640px) { .player { padding: 12px; } }
+ .stage-wrap { flex: 1 1 0; min-height: 96px; container-type: size; display: grid; place-items: center; }
+ .stage {
+ position: relative; background: var(--stage); border-radius: var(--radius); overflow: hidden;
+ box-shadow: 0 0 0 1px var(--line); user-select: none; -webkit-user-select: none;
+ aspect-ratio: var(--ar, 16 / 9); width: min(100cqw, calc(100cqh * var(--ar-n, 1.7778)));
+ }
+ .stage canvas { display: block; width: 100%; height: 100%; }
+ .stage-msg {
+ position: absolute; inset: 0; display: none; place-items: center; padding: 24px; text-align: center;
+ color: #fff; background: rgb(0 0 0 / .72); font-size: 13px; line-height: 1.5; white-space: pre-wrap; overflow: auto;
+ }
+ .stage-msg.on { display: grid; }
+ /* Buffering: a centred spinning arc over the picture, like YouTube's. It
+ fades in after a beat so brief waits don't flash it. */
+ .buffering {
+ position: absolute; left: 50%; top: 50%; width: clamp(36px, 9cqmin, 64px); aspect-ratio: 1;
+ transform: translate(-50%, -50%); pointer-events: none; opacity: 0; visibility: hidden;
+ transition: opacity .15s, visibility 0s .15s; filter: drop-shadow(0 0 3px rgb(0 0 0 / .45));
+ }
+ .buffering.on { opacity: 1; visibility: visible; transition: opacity .2s .25s, visibility 0s .25s; }
+ .buffering svg { width: 100%; height: 100%; animation: yt-rotate 1.4s linear infinite; }
+ .buffering circle {
+ fill: none; stroke: #fff; stroke-width: 3.6; stroke-linecap: round;
+ stroke-dasharray: 1 150; stroke-dashoffset: 0; animation: yt-dash 1.4s ease-in-out infinite;
+ }
+ @keyframes yt-rotate { to { transform: rotate(360deg); } }
+ @keyframes yt-dash {
+ 0% { stroke-dasharray: 1 150; stroke-dashoffset: 0; }
+ 50% { stroke-dasharray: 90 150; stroke-dashoffset: -35; }
+ 100% { stroke-dasharray: 90 150; stroke-dashoffset: -124; }
+ }
+ @media (prefers-reduced-motion: reduce) { .buffering circle, .play-btn .spin circle { animation: none; stroke-dasharray: 70 150; } }
+
+ /* ── Transport ── */
+ .transport { flex: none; display: flex; align-items: center; gap: 4px; flex-wrap: wrap; row-gap: 6px; }
+ .icon-btn {
+ width: 32px; height: 32px; display: inline-grid; place-items: center; border-radius: 8px;
+ border: 0; background: transparent; color: var(--ink-2); flex: none;
+ }
+ .icon-btn:hover:not(:disabled) { background: var(--surface-2); color: var(--ink); }
+ .icon-btn:disabled { opacity: .35; cursor: default; }
+ .icon-btn svg { width: 16px; height: 16px; }
+ .play-btn {
+ width: 36px; height: 36px; border-radius: 50%; border: 0; display: inline-grid; place-items: center; flex: none;
+ background: var(--primary-bg); color: var(--primary-ink); margin: 0 2px;
+ }
+ .play-btn:hover:not(:disabled) { filter: brightness(.9); }
+ .play-btn:disabled { opacity: .4; cursor: default; }
+ .play-btn svg { width: 14px; height: 14px; }
+ .play-btn .spin { display: none; width: 20px; height: 20px; animation: yt-rotate 1.4s linear infinite; }
+ .play-btn .spin circle {
+ fill: none; stroke: currentColor; stroke-width: 5; stroke-linecap: round;
+ stroke-dasharray: 1 150; animation: yt-dash 1.4s ease-in-out infinite;
+ }
+ .play-btn.loading .spin { display: block; }
+ .play-btn.loading svg:not(.spin) { display: none !important; }
+ .timecode { display: flex; align-items: baseline; gap: 5px; margin-left: 8px; font-size: 13px; white-space: nowrap; }
+ .timecode .dim { color: var(--ink-3); }
+ .timecode .frame { color: var(--ink-3); font-size: 11.5px; margin-left: 6px; }
+ input[type="range"].slider { -webkit-appearance: none; appearance: none; width: 72px; height: 4px; border-radius: 2px; background: var(--line-2); margin: 0 8px 0 0; }
+ input[type="range"].slider::-webkit-slider-thumb { -webkit-appearance: none; width: 12px; height: 12px; border-radius: 50%; background: var(--ink); border: 0; }
+ input[type="range"].slider::-moz-range-thumb { width: 12px; height: 12px; border-radius: 50%; background: var(--ink); border: 0; }
+ input[type="range"].slider:disabled { opacity: .35; }
+
+ /* ── Timeline ── */
+ .timeline {
+ flex: none; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface);
+ padding: 0 14px; user-select: none; -webkit-user-select: none; touch-action: none; cursor: pointer;
+ }
+ .tl-inner { position: relative; }
+ .ruler { position: relative; height: 22px; border-bottom: 1px solid var(--line); }
+ /* Rendered ahead of the playhead while playing, like a video's loaded range. */
+ .buffered {
+ position: absolute; top: 20px; height: 3px; border-radius: 2px; background: var(--ink-3);
+ opacity: .55; pointer-events: none; z-index: 2; display: none;
+ }
+ .tick { position: absolute; bottom: 0; width: 1px; height: 4px; background: var(--line-2); }
+ .tick.major { height: 8px; background: var(--ink-3); }
+ .tick span { position: absolute; bottom: 9px; left: 4px; font-size: 10.5px; line-height: 1; color: var(--ink-3); white-space: nowrap; font-variant-numeric: tabular-nums; }
+ .wave-lane { position: relative; height: 48px; }
+ @media (max-height: 600px) { .wave-lane { height: 30px; } }
+ .wave-lane canvas { position: absolute; inset: 0; width: 100%; height: 100%; }
+ .wave-state { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 8px; color: var(--ink-3); font-size: 12px; }
+ .wave-state.shimmer {
+ background: linear-gradient(90deg, transparent 0%, color-mix(in srgb, var(--ink) 6%, transparent) 50%, transparent 100%);
+ background-size: 200% 100%; animation: shimmer 1.4s linear infinite;
+ }
+ @keyframes shimmer { from { background-position: 100% 0; } to { background-position: -100% 0; } }
+ .playhead { position: absolute; top: 0; bottom: 0; width: 0; pointer-events: none; z-index: 3; }
+ .playhead::before { content: ""; position: absolute; top: 0; bottom: 0; left: -0.5px; width: 1px; background: var(--ink); }
+ .playhead::after { content: ""; position: absolute; top: 0; left: -5px; width: 10px; height: 11px; background: var(--ink); clip-path: polygon(0 0, 100% 0, 100% 55%, 50% 100%, 0 55%); }
+ .hover-line { position: absolute; top: 0; bottom: 0; width: 1px; background: var(--line-2); display: none; pointer-events: none; }
+ .hover-time {
+ position: absolute; top: -28px; transform: translateX(-50%); display: none; pointer-events: none;
+ font-size: 11px; line-height: 1; background: var(--surface-3); color: var(--ink); padding: 5px 7px; border-radius: 5px;
+ white-space: nowrap; z-index: 4; font-variant-numeric: tabular-nums;
+ }
+</style>
+</head>
+<body>
+<header class="top">
+ <svg class="logo" viewBox="0 0 512 512" aria-label="gitframes" role="img"><g fill="none" stroke="currentColor" stroke-linecap="round"><path d="M184 56H86q-30 0-30 30v98M328 56h98q30 0 30 30v98M184 456H86q-30 0-30-30v-98M328 456h98q30 0 30-30v-98" stroke-width="34" stroke-linejoin="round"/><path d="M176 182v148m0-148c0 74 60 74 100 74" stroke-width="28"/></g><g fill="currentColor"><circle cx="176" cy="172" r="32"/><circle cx="176" cy="340" r="32"/><path d="M284 200l78 56-78 56z" stroke="currentColor" stroke-width="34" stroke-linejoin="round"/></g></svg>
+ <span class="sep" aria-hidden="true"></span>
+ <h1 id="title">gitframes preview</h1>
+ <span class="grow"></span>
+ <span class="spec tnum" id="spec"></span>
+ <span class="chip" id="chip" data-state="mixing" role="status" aria-live="polite"><span class="spinner"></span><span>Mixing audio</span></span>
+</header>
+
+<main class="player" aria-label="Player">
+ <div class="stage-wrap">
+ <div class="stage" id="stage">
+ <canvas id="canvas" aria-label="Rendered frame"></canvas>
+ <div class="stage-msg" id="stageMsg" role="alert"></div>
+ <div class="buffering" id="buffering" role="status" aria-label="Loading"><svg viewBox="0 0 50 50"><circle cx="25" cy="25" r="20"/></svg></div>
+ </div>
+ </div>
+
+ <div class="transport">
+ <button class="icon-btn" id="prev" title="Previous frame" aria-label="Previous frame">
+ <svg viewBox="0 0 16 16" fill="currentColor"><path d="M3 3h1.6v10H3zM13 3.6v8.8a.6.6 0 0 1-.92.5L5.8 8.5a.6.6 0 0 1 0-1l6.28-4.4a.6.6 0 0 1 .92.5z"/></svg>
+ </button>
+ <button class="play-btn" id="play" title="Play" aria-label="Play" disabled>
+ <svg id="playIcon" viewBox="0 0 16 16" fill="currentColor"><path d="M4.5 2.9v10.2a.7.7 0 0 0 1.06.6l8.1-5.1a.7.7 0 0 0 0-1.2l-8.1-5.1a.7.7 0 0 0-1.06.6z"/></svg>
+ <svg class="spin" viewBox="0 0 50 50" aria-hidden="true"><circle cx="25" cy="25" r="18"/></svg>
+ <svg id="pauseIcon" viewBox="0 0 16 16" fill="currentColor" style="display:none"><rect x="3.5" y="2.5" width="3.2" height="11" rx=".8"/><rect x="9.3" y="2.5" width="3.2" height="11" rx=".8"/></svg>
+ </button>
+ <button class="icon-btn" id="next" title="Next frame" aria-label="Next frame">
+ <svg viewBox="0 0 16 16" fill="currentColor"><path d="M11.4 3H13v10h-1.6zM3 3.6v8.8a.6.6 0 0 0 .92.5l6.28-4.4a.6.6 0 0 0 0-1L3.92 3.1A.6.6 0 0 0 3 3.6z"/></svg>
+ </button>
+ <div class="timecode tnum">
+ <span id="tcNow">0:00.00</span><span class="dim">/</span><span class="dim" id="tcDur">0:00.00</span>
+ <span class="frame" id="tcFrame">frame 0</span>
+ </div>
+ <span class="grow"></span>
+ <button class="icon-btn" id="mute" title="Mute" aria-label="Mute" disabled>
+ <svg id="volIcon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 6h2.2L8 3.2v9.6L4.7 10H2.5z" fill="currentColor" stroke="none"/><path d="M10.6 5.6a3.4 3.4 0 0 1 0 4.8M12.4 3.9a5.8 5.8 0 0 1 0 8.2"/></svg>
+ <svg id="muteIcon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" style="display:none"><path d="M2.5 6h2.2L8 3.2v9.6L4.7 10H2.5z" fill="currentColor" stroke="none"/><path d="M10.5 6l3.5 4M14 6l-3.5 4"/></svg>
+ </button>
+ <input class="slider" type="range" id="volume" min="0" max="1" step="0.01" value="0.9" aria-label="Volume" disabled>
+ </div>
+
+ <div class="timeline" id="timeline" aria-label="Timeline">
+ <div class="tl-inner" id="tlInner">
+ <div class="ruler" id="ruler"></div>
+ <div class="buffered" id="buffered"></div>
+ <div class="wave-lane">
+ <canvas id="wave"></canvas>
+ <div class="wave-state shimmer" id="waveState"><span class="spinner"></span>Mixing audio</div>
+ </div>
+ <div class="hover-line" id="hoverLine"></div>
+ <div class="hover-time" id="hoverTime"></div>
+ <div class="playhead" id="playhead"></div>
+ </div>
+ </div>
+</main>
+
+<script>
+(function () {
+ var $ = function (id) { return document.getElementById(id); };
+ var stage = $("stage"), timeline = $("timeline"), tlInner = $("tlInner");
+
+ var meta = null, session = null, frame = 0, shown = -1, playing = false, playToken = 0;
+ var player = null;
+
+ // ── Helpers ──
+ function fmt(f) {
+ var s = f / meta.fps, m = Math.floor(s / 60);
+ return m + ":" + (s - m * 60).toFixed(2).padStart(5, "0");
+ }
+ function last() { return meta.frameCount - 1; }
+ function clampFrame(f) { return Math.max(0, Math.min(last(), Math.round(f))); }
+ function pct(f) { return meta.frameCount > 1 ? (f / last()) * 100 : 0; }
+ function el(tag, cls, text) {
+ var e = document.createElement(tag);
+ if (cls) e.className = cls;
+ if (text != null) e.textContent = text;
+ return e;
+ }
+ function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
+
+ // ── Frames: drawn in this tab by the composition's own code ──
+ function setTime(f) {
+ frame = f;
+ $("tcNow").textContent = fmt(f);
+ $("tcFrame").textContent = "frame " + f;
+ $("playhead").style.left = pct(f) + "%";
+ }
+ function show(f) {
+ setTime(f);
+ if (!player) return Promise.resolve();
+ $("buffering").classList.add("on");
+ // Calls made while a frame draws collapse to the latest.
+ return player.render(f).then(function (drawn) {
+ shown = drawn;
+ if (!stalled) $("buffering").classList.remove("on");
+ });
+ }
+ function seek(f) {
+ stop();
+ var done = show(clampFrame(f));
+ scheduleWarm();
+ return done;
+ }
+
+ // ── Analysing ahead: while paused, frames after the playhead are drawn
+ // off-screen so vision results are cached before they play ──
+ var warmTimer = null, warmToken = 0, warmed = new Set();
+ function scheduleWarm() {
+ clearTimeout(warmTimer);
+ warmToken++;
+ if (!player || !player.hasVision || playing) return;
+ warmTimer = setTimeout(warmAhead, 1000);
+ }
+ async function warmAhead() {
+ var token = ++warmToken;
+ var end = Math.min(last(), frame + Math.round(meta.fps * 20));
+ for (var f = frame + 1; f <= end && token === warmToken && !playing; f++) {
+ if (warmed.has(f)) continue;
+ if (!(await player.warm(f))) { scheduleWarm(); return; }
+ warmed.add(f);
+ await sleep(0);
+ }
+ }
+ function showError(err) {
+ $("buffering").classList.remove("on");
+ $("stageMsg").textContent = String((err && err.message) || err);
+ $("stageMsg").classList.add("on");
+ }
+
+ // ── Audio ──
+ var audio = { state: "mixing", error: "", buffer: null, peaks: null, ctx: null, gain: null, src: null, muted: false, volume: 0.9 };
+ var AUDIO_LABEL = { mixing: "Mixing audio", loading: "Loading audio", ready: "Audio ready", none: "No audio", error: "Audio failed" };
+ var offline = false;
+
+ function renderChip() {
+ var chip = $("chip"), state, label, busy;
+ if (offline) { state = "offline"; label = "Preview stopped"; busy = false; }
+ else { state = audio.state; label = AUDIO_LABEL[audio.state]; busy = state === "mixing" || state === "loading"; }
+ chip.dataset.state = state;
+ chip.title = offline ? "The preview command isn't running. This tab reconnects when it starts again." : audio.error || "";
+ chip.replaceChildren(el("span", busy ? "spinner" : "dot"), el("span", null, label));
+ }
+ function setAudioStatus(state, error) {
+ audio.state = state;
+ audio.error = error || "";
+ var busy = state === "mixing" || state === "loading", ws = $("waveState");
+ ws.classList.toggle("shimmer", busy);
+ ws.style.display = state === "ready" ? "none" : "flex";
+ ws.replaceChildren();
+ if (busy) ws.append(el("span", "spinner"));
+ ws.append(document.createTextNode(state === "none" ? "No audio in this composition" : state === "error" ? "Audio could not be mixed" : AUDIO_LABEL[state]));
+ var usable = state === "ready" && !!audio.buffer;
+ $("mute").disabled = !usable;
+ $("volume").disabled = !usable;
+ renderChip();
+ drawWave();
+ }
+ function loadAudio(status) {
+ stopClock();
+ audio.buffer = null;
+ audio.peaks = null;
+ if (!status || status.state !== "ready") { setAudioStatus(status ? status.state : "none", status && status.error); return; }
+ audio.peaks = status.peaks;
+ setAudioStatus("loading");
+ if (!audio.ctx) {
+ var Ctx = window.AudioContext || window.webkitAudioContext;
+ audio.ctx = new Ctx();
+ audio.gain = audio.ctx.createGain();
+ audio.gain.connect(audio.ctx.destination);
+ applyVolume();
+ }
+ fetch("/audio")
+ .then(function (r) { if (!r.ok) throw new Error("HTTP " + r.status); return r.arrayBuffer(); })
+ .then(function (data) { return audio.ctx.decodeAudioData(data); })
+ .then(function (buf) { audio.buffer = buf; setAudioStatus("ready"); })
+ .catch(function (err) { setAudioStatus("error", String((err && err.message) || err)); });
+ }
+ function applyVolume() {
+ if (audio.gain) audio.gain.gain.value = audio.muted ? 0 : audio.volume;
+ $("volIcon").style.display = audio.muted ? "none" : "";
+ $("muteIcon").style.display = audio.muted ? "" : "none";
+ $("mute").title = audio.muted ? "Unmute" : "Mute";
+ $("mute").setAttribute("aria-label", audio.muted ? "Unmute" : "Mute");
+ }
+ // The clock for real-time playback: the soundtrack when there is one,
+ // otherwise the wall clock. Audio as master keeps picture and sound in sync.
+ function startClock(f0) {
+ if (audio.buffer && audio.ctx) {
+ audio.ctx.resume();
+ var src = audio.ctx.createBufferSource();
+ src.buffer = audio.buffer;
+ src.connect(audio.gain);
+ var startAt = audio.ctx.currentTime + 0.06, offset = f0 / meta.fps;
+ if (offset < audio.buffer.duration) src.start(startAt, offset);
+ audio.src = src;
+ return function () { return Math.max(0, audio.ctx.currentTime - startAt); };
+ }
+ var t0 = performance.now();
+ return function () { return (performance.now() - t0) / 1000; };
+ }
+ function stopClock() {
+ if (!audio.src) return;
+ try { audio.src.stop(); } catch (e) {}
+ audio.src.disconnect();
+ audio.src = null;
+ }
+
+ // ── Playback ──
+ var stalled = false;
+ // Waiting on frames mid-playback: the play button and the picture both spin.
+ function setStalled(on) {
+ stalled = on;
+ $("play").classList.toggle("loading", on);
+ $("buffering").classList.toggle("on", on);
+ }
+ function setPlayingUi(on) {
+ $("playIcon").style.display = on ? "none" : "";
+ $("pauseIcon").style.display = on ? "" : "none";
+ $("play").title = on ? "Pause" : "Play";
+ $("play").setAttribute("aria-label", on ? "Pause" : "Play");
+ }
+ function play() {
+ if (playing || !player) return;
+ playing = true;
+ clearTimeout(warmTimer);
+ warmToken++;
+ var token = ++playToken;
+ var alive = function () { return playing && token === playToken; };
+ setPlayingUi(true);
+ if (frame >= last()) frame = 0;
+ playRealtime(alive).finally(function () { if (token === playToken && playing) pause(); });
+ }
+ function stop() {
+ playing = false;
+ stopClock();
+ setStalled(false);
+ setPlayingUi(false);
+ }
+ // Pausing settles on exactly the frame the timecode shows.
+ function pause() { stop(); show(frame).then(scheduleWarm); }
+ function togglePlay() { playing ? pause() : play(); }
+
+ // Like a video player: frames are rendered ahead into a buffer, in order,
+ // and every one is shown at the film's frame rate. Playback starts once
+ // three seconds (or the rest of the film) are ready; when rendering falls
+ // behind, the clock and the sound hold until the buffer is full again.
+ var BUFFER_SEC = 3;
+ async function playRealtime(alive) {
+ player.buffer.start(frame);
+ try {
+ while (alive() && frame < last()) {
+ if (!(await fillBuffer(alive))) return;
+ if (!(await runClock(alive))) return;
+ }
+ } finally {
+ player.buffer.stop();
+ $("buffered").style.display = "none";
+ }
+ }
+ function showBufferedRange() {
+ var bar = $("buffered"), end = Math.max(frame, Math.min(last(), player.buffer.end - 1));
+ bar.style.display = "block";
+ bar.style.left = pct(frame) + "%";
+ bar.style.width = Math.max(0, pct(end) - pct(frame)) + "%";
+ }
+ async function fillBuffer(alive) {
+ var need = Math.max(1, Math.min(Math.round(meta.fps * BUFFER_SEC), last() - frame + 1, player.buffer.capacity - 2));
+ if (player.buffer.ahead(frame) >= need) return true;
+ setStalled(true);
+ while (alive() && player.buffer.ahead(frame) < need) {
+ showBufferedRange();
+ await sleep(30);
+ }
+ if (!alive()) return false;
+ setStalled(false);
+ return true;
+ }
+ // Resolves true when the buffer ran dry, false at the end or when stopped.
+ async function runClock(alive) {
+ var f0 = frame, clock = startClock(f0), onScreen = -1;
+ while (alive()) {
+ var due = Math.min(last(), f0 + Math.floor(clock() * meta.fps));
+ if (due !== onScreen) {
+ if (!player.buffer.show(due)) {
+ stopClock();
+ setTime(onScreen >= 0 ? onScreen : f0);
+ return true;
+ }
+ onScreen = shown = due;
+ }
+ setTime(due);
+ showBufferedRange();
+ if (due >= last()) return false;
+ // A timer, not rAF: embedded or occluded views throttle rAF to ~1 Hz.
+ await sleep(4);
+ }
+ return false;
+ }
+
+ // ── Timeline ──
+ function frameAtX(clientX) {
+ var r = tlInner.getBoundingClientRect();
+ return clampFrame(Math.min(1, Math.max(0, (clientX - r.left) / r.width)) * last());
+ }
+ function renderRuler() {
+ var ruler = $("ruler"), width = tlInner.clientWidth || 800, dur = last() / meta.fps;
+ ruler.replaceChildren();
+ if (dur <= 0) return;
+ var steps = [0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600];
+ var major = steps.find(function (s) { return (s / dur) * width >= 80; }) || 1200, minor = major / 5;
+ for (var i = 0; i * minor <= dur + 1e-6; i++) {
+ var t = i * minor, isMajor = i % 5 === 0, x = (t / dur) * width;
+ var tick = el("div", "tick" + (isMajor ? " major" : ""));
+ tick.style.left = (t / dur) * 100 + "%";
+ if (isMajor && x < width - 34) {
+ var m = Math.floor(t / 60), s = Math.round((t - m * 60) * 10) / 10;
+ tick.append(el("span", null, m + ":" + (s < 10 ? "0" : "") + s));
+ }
+ ruler.append(tick);
+ }
+ }
+ function drawWave() {
+ var canvas = $("wave"), dpr = window.devicePixelRatio || 1;
+ var w = canvas.clientWidth, h = canvas.clientHeight;
+ canvas.width = Math.round(w * dpr);
+ canvas.height = Math.round(h * dpr);
+ var ctx = canvas.getContext("2d");
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ ctx.clearRect(0, 0, w, h);
+ var peaks = audio.peaks;
+ if (!peaks || !peaks.length || !meta) return;
+ var videoSec = Math.max(1e-6, last() / meta.fps);
+ var audioSec = audio.buffer ? audio.buffer.duration : videoSec;
+ var spanPx = Math.min(1, audioSec / videoSec) * w, mid = h / 2;
+ ctx.fillStyle = getComputedStyle(document.documentElement).getPropertyValue("--wave").trim();
+ for (var x = 0; x < spanPx; x += 3) {
+ var v = Math.max(peaks[Math.floor((x / spanPx) * peaks.length)] || 0, 0.015);
+ var bh = Math.max(1, Math.sqrt(v) * (h - 8));
+ ctx.fillRect(x, mid - bh / 2, 2, bh);
+ }
+ }
+
+ var dragging = false;
+ timeline.addEventListener("pointerdown", function (e) {
+ if (!meta || e.button !== 0) return;
+ timeline.setPointerCapture(e.pointerId);
+ dragging = true;
+ seek(frameAtX(e.clientX));
+ });
+ timeline.addEventListener("pointermove", function (e) {
+ if (!meta) return;
+ var f = frameAtX(e.clientX), r = tlInner.getBoundingClientRect();
+ var x = Math.min(r.width, Math.max(0, e.clientX - r.left));
+ $("hoverLine").style.display = "block";
+ $("hoverLine").style.left = x + "px";
+ $("hoverTime").style.display = "block";
+ $("hoverTime").style.left = x + "px";
+ $("hoverTime").textContent = fmt(f);
+ if (dragging && f !== frame) seek(f);
+ });
+ timeline.addEventListener("pointerleave", function () {
+ $("hoverLine").style.display = "none";
+ $("hoverTime").style.display = "none";
+ });
+ timeline.addEventListener("pointerup", function () { dragging = false; });
+ timeline.addEventListener("pointercancel", function () { dragging = false; });
+
+ // ── Wiring ──
+ $("play").addEventListener("click", togglePlay);
+ $("prev").addEventListener("click", function () { seek(frame - 1); });
+ $("next").addEventListener("click", function () { seek(frame + 1); });
+ $("mute").addEventListener("click", function () { audio.muted = !audio.muted; applyVolume(); });
+ $("volume").addEventListener("input", function (e) { audio.volume = Number(e.target.value); audio.muted = audio.volume === 0; applyVolume(); });
+
+ function applyMeta(m) {
+ meta = m;
+ document.title = m.title + " · preview";
+ $("title").textContent = m.title;
+ $("spec").textContent = m.width + "×" + m.height + " · " + m.fps + " fps · " + fmt(last());
+ $("tcDur").textContent = fmt(last());
+ stage.style.setProperty("--ar", m.width + " / " + m.height);
+ stage.style.setProperty("--ar-n", String(m.width / m.height));
+ renderRuler();
+ }
+
+ new ResizeObserver(function () {
+ if (!meta) return;
+ renderRuler();
+ drawWave();
+ }).observe(tlInner);
+
+ // When the preview command ends the event stream drops and the browser keeps
+ // retrying. The next preview of this project (same port) says hello with a
+ // new session, and this tab reloads into it.
+ var events = new EventSource("/events");
+ events.addEventListener("hello", function (e) {
+ var s = JSON.parse(e.data).session;
+ if (session && s !== session) { location.reload(); return; }
+ offline = false;
+ renderChip();
+ });
+ events.addEventListener("error", function () {
+ if (!meta) return;
+ if (playing) stop();
+ offline = true;
+ renderChip();
+ });
+ events.addEventListener("audio", function (e) {
+ if (meta) loadAudio(JSON.parse(e.data));
+ });
+
+ fetch("/meta").then(function (r) { return r.json(); }).then(function (m) {
+ session = m.session;
+ applyMeta(m);
+ loadAudio(m.audio);
+ setTime(0);
+ $("buffering").classList.add("on");
+ whenPlayer();
+ });
+
+ // The composition's bundle (loaded below) announces its player.
+ function whenPlayer() {
+ if (!window.gitframesPlayer) return;
+ window.gitframesPlayer.then(function (p) {
+ player = p;
+ $("play").disabled = false;
+ show(frame).then(scheduleWarm);
+ }, showError);
+ }
+ window.addEventListener("gitframes:player", function () { if (meta) whenPlayer(); });
+ window.addEventListener("error", function (e) { if (!player) showError(e.error || e.message); });
+})();
+</script>
+<script type="module" src="/@gitframes/player.js"></script>
+</body>
+</html>
+`;
diff --git a/packages/gitframes/src/preview/player.ts b/packages/gitframes/src/preview/player.ts
new file mode 100644
index 00000000..ecf23ae4
--- /dev/null
+++ b/packages/gitframes/src/preview/player.ts
@@ -0,0 +1,438 @@
+/// <reference lib="dom" />
+/// <reference types="webgpu" />
+/**
+ * The browser side of the preview: runs the project's composition code and
+ * renders its frames with WebGPU straight onto the page's canvas. Bundled
+ * together with the composition module by bundle.ts.
+ */
+import { GetFontAssetUrl } from "@gitframes/client-utils";
+import {
+ compositionStateStore,
+ drawCompositionTree,
+} from "@gitframes/compositions";
+import { updateClockSignals, type VirtualMediaData } from "@gitframes/core";
+import {
+ audioRegistry,
+ type NodeRendererPlugin,
+ registerWebGPURenderer,
+} from "@gitframes/node-sdk";
+import { preloadFont } from "@gitframes/renderers";
+import {
+ type OrtWebModule,
+ setDefaultSessionProvider,
+ WebGPUProvider,
+} from "@gitframes/vision/web";
+import {
+ acquireDevice,
+ BrowserSurfaceProvider,
+ getHeadlessFontPath,
+ getRenderer2D,
+ lutStore,
+ type RenderContextValue,
+ SlugFontCache,
+} from "@gitframes/webgpu-renderers";
+import { Blitter } from "./blit.js";
+
+export interface BuiltinRenderer {
+ ops: readonly string[];
+ load: () => Promise<{ default?: NodeRendererPlugin }>;
+}
+
+export interface PlayerMeta {
+ width: number;
+ height: number;
+ fps: number;
+ frameCount: number;
+ durationMs: number;
+}
+
+export interface PreviewPlayer {
+ meta: PlayerMeta;
+ canvas: HTMLCanvasElement;
+ /** Draws a frame. Calls made while one is drawing collapse to the latest. */
+ render(frame: number): Promise<number>;
+ /** Milliseconds the last frame took to draw. */
+ lastRenderMs: number;
+ /** True when the program runs vision models (worth analysing ahead). */
+ hasVision: boolean;
+ /**
+ * Draws a frame off-screen so per-frame work (vision analysis) is cached
+ * before it plays. Skipped (resolves false) while a frame is being drawn.
+ */
+ warm(frame: number): Promise<boolean>;
+ /** Frames rendered ahead in order, for playback at full frame rate. */
+ buffer: PlaybackBuffer;
+}
+
+export interface PlaybackBuffer {
+ /** Most frames it holds at once. */
+ readonly capacity: number;
+ /** Starts rendering every frame from `frame` on (stops an earlier run). */
+ start(frame: number): void;
+ stop(): void;
+ /** Frames ready in a row from `frame` (0 when `frame` isn't buffered). */
+ ahead(frame: number): number;
+ /** The first frame not rendered yet. */
+ readonly end: number;
+ /** Shows a buffered frame; false when it isn't ready. */
+ show(frame: number): boolean;
+}
+
+type Renderable = {
+ toVirtualMediaAsync?: () => Promise<VirtualMediaData>;
+ toVirtualMedia?: () => VirtualMediaData;
+ fps?: number;
+};
+
+declare global {
+ interface Window {
+ gitframesPlayer?: Promise<PreviewPlayer>;
+ }
+}
+
+export interface PlayerOptions {
+ renderers: readonly BuiltinRenderer[];
+ /** Loads onnxruntime-web for vision nodes. */
+ loadOrt?: () => Promise<unknown>;
+}
+
+export function startPlayer(
+ mod: Record<string, unknown>,
+ exportName: string,
+ options: PlayerOptions,
+): void {
+ const { loadOrt } = options;
+ // Vision nodes create their runners themselves; here they run on WebGPU.
+ if (loadOrt) {
+ setDefaultSessionProvider(
+ () =>
+ new WebGPUProvider({
+ loader: () => loadOrt() as Promise<OrtWebModule>,
+ }),
+ );
+ }
+ window.gitframesPlayer = createPlayer(mod, exportName, options.renderers);
+ // The page listens for this; a failure is shown there.
+ window.dispatchEvent(new Event("gitframes:player"));
+}
+
+async function createPlayer(
+ mod: Record<string, unknown>,
+ exportName: string,
+ renderers: readonly BuiltinRenderer[],
+): Promise<PreviewPlayer> {
+ if (!("gpu" in navigator)) {
+ throw new Error(
+ "This browser has no WebGPU. Use a current Chrome, Edge or Safari.",
+ );
+ }
+ await registerRenderers(renderers);
+
+ const exported = mod[exportName];
+ if (exported === undefined) {
+ throw new Error(`The preview entry has no export named "${exportName}".`);
+ }
+ const target = (
+ typeof exported === "function"
+ ? await (exported as () => unknown)()
+ : exported
+ ) as Renderable;
+ const vm = target.toVirtualMediaAsync
+ ? await target.toVirtualMediaAsync()
+ : target.toVirtualMedia?.();
+ if (!vm) throw new Error(`"${exportName}" is not a composition.`);
+
+ const width = Math.round(vm.metadata?.width ?? 1920);
+ const height = Math.round(vm.metadata?.height ?? 1080);
+ const fps = target.fps ?? (vm.operation as { fps?: number })?.fps ?? 30;
+ const durationMs = vm.metadata?.durationMs ?? 0;
+ const meta: PlayerMeta = {
+ width,
+ height,
+ fps,
+ durationMs,
+ frameCount: Math.max(1, Math.round((durationMs / 1000) * fps)),
+ };
+
+ const device = await acquireDevice();
+ const canvas =
+ (document.getElementById("canvas") as HTMLCanvasElement | null) ??
+ document.createElement("canvas");
+ canvas.width = width % 2 ? width + 1 : width;
+ canvas.height = height % 2 ? height + 1 : height;
+ const surface = new BrowserSurfaceProvider(device, canvas);
+ await preloadFonts(vm, device);
+
+ const renderId = `preview-${Math.random().toString(36).slice(2)}`;
+ let first = true;
+ let drawing: Promise<void> | null = null;
+ let wanted: number | null = null;
+ let waiters: Array<(f: number) => void> = [];
+
+ let offscreen: GPUTexture | undefined;
+
+ async function draw(frame: number, toScreen = true): Promise<void> {
+ const renderer = getRenderer2D(device, surface.colorFormat);
+ const ctx: RenderContextValue = { device, renderer, surface };
+ const w = surface.width;
+ const h = surface.height;
+ const props = {
+ frame,
+ fps,
+ isHeadless: false,
+ renderId,
+ virtualMedia: vm as VirtualMediaData,
+ containerWidth: w,
+ containerHeight: h,
+ isVideoMode: true,
+ };
+ updateClockSignals(frame, fps, durationMs || undefined);
+
+ // Shader, LUT and glyph uploads finish on a pass whose output is dropped.
+ if (first || lutStore.hasPending(device) || SlugFontCache.hasPending()) {
+ first = false;
+ const pre = device.createCommandEncoder();
+ const tex = renderer.getTemporaryTexture(w, h);
+ const view = tex.createView();
+ renderer
+ .beginFrame(pre, view, { r: 0, g: 0, b: 0, a: 0 }, w, h, "clear")
+ .end();
+ await drawCompositionTree(
+ ctx,
+ pre,
+ view,
+ tex,
+ w,
+ h,
+ vm as VirtualMediaData,
+ props,
+ );
+ device.queue.submit([pre.finish()]);
+ await lutStore.awaitAllPending(device);
+ }
+
+ compositionStateStore.setState(renderId, frame, fps, true);
+ const encoder = device.createCommandEncoder();
+ if (!toScreen && !offscreen) {
+ offscreen = device.createTexture({
+ size: [w, h],
+ format: surface.colorFormat,
+ usage:
+ GPUTextureUsage.RENDER_ATTACHMENT |
+ GPUTextureUsage.TEXTURE_BINDING |
+ GPUTextureUsage.COPY_SRC,
+ label: "preview_warm_target",
+ });
+ }
+ const tex =
+ toScreen || !offscreen ? surface.getCurrentTexture() : offscreen;
+ const view = tex.createView();
+ renderer
+ .beginFrame(encoder, view, { r: 0, g: 0, b: 0, a: 0 }, w, h, "clear")
+ .end();
+ await drawCompositionTree(
+ ctx,
+ encoder,
+ view,
+ tex,
+ w,
+ h,
+ vm as VirtualMediaData,
+ props,
+ );
+ device.queue.submit([encoder.finish()]);
+ if (toScreen) surface.present();
+ await device.queue.onSubmittedWorkDone();
+ }
+
+ // One frame at a time. Requests made while a frame draws collapse to the
+ // latest; warm-ups only run when nothing else is drawing.
+ function pump(): void {
+ if (drawing || wanted === null) return;
+ drawing = (async () => {
+ while (wanted !== null) {
+ const f = wanted;
+ wanted = null;
+ const started = performance.now();
+ try {
+ await draw(f);
+ } catch (err) {
+ console.error("[gitframes] frame", f, err);
+ }
+ player.lastRenderMs = performance.now() - started;
+ if (wanted === null) {
+ const ready = waiters;
+ waiters = [];
+ for (const resolve of ready) resolve(f);
+ }
+ }
+ drawing = null;
+ })();
+ }
+
+ // ── Playback buffer: a ring of frames rendered ahead, shown at full rate.
+ // Frames are kept below native size to bound memory (~400 MB at most);
+ // a paused frame is drawn at full resolution.
+ const lastFrame = meta.frameCount - 1;
+ const capacity = Math.ceil(fps * 3.5) + 2;
+ const budget = 400 * 1024 * 1024;
+ const scale = Math.min(
+ 1,
+ Math.sqrt(budget / capacity / 4 / (width * height)),
+ );
+ const even = (n: number) => Math.max(2, Math.round(n / 2) * 2);
+ const ringSize = { w: even(width * scale), h: even(height * scale) };
+ const ring: GPUTexture[] = [];
+ const ringFrames = new Int32Array(capacity).fill(-1);
+ const blitter = new Blitter(device, surface.colorFormat);
+ let bufferToken = 0;
+ let produced = 0;
+ let shown = -1;
+
+ function ringTexture(slot: number): GPUTexture {
+ ring[slot] ??= device.createTexture({
+ size: [ringSize.w, ringSize.h],
+ format: surface.colorFormat,
+ usage:
+ GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
+ label: `preview_buffer_${slot}`,
+ });
+ return ring[slot];
+ }
+
+ async function produce(token: number): Promise<void> {
+ while (token === bufferToken && produced <= lastFrame) {
+ // The slot still holds a frame that hasn't been shown yet.
+ if (produced - capacity > shown) {
+ await new Promise((r) => setTimeout(r, 4));
+ continue;
+ }
+ while (drawing) await drawing;
+ if (token !== bufferToken) return;
+ const frame = produced;
+ const slot = frame % capacity;
+ drawing = draw(frame, false)
+ .then(() => {
+ if (offscreen) blitter.blit(offscreen, ringTexture(slot));
+ })
+ .catch((err: unknown) =>
+ console.error("[gitframes] frame", frame, err),
+ );
+ await drawing;
+ drawing = null;
+ if (token !== bufferToken) return;
+ ringFrames[slot] = frame;
+ produced = frame + 1;
+ pump();
+ }
+ }
+
+ const buffer: PlaybackBuffer = {
+ capacity,
+ get end() {
+ return produced;
+ },
+ start(frame) {
+ const token = ++bufferToken;
+ ringFrames.fill(-1);
+ produced = frame;
+ shown = frame - 1;
+ void produce(token);
+ },
+ stop() {
+ bufferToken++;
+ },
+ ahead(frame) {
+ if (ringFrames[frame % capacity] !== frame) return 0;
+ return produced - frame;
+ },
+ show(frame) {
+ const slot = frame % capacity;
+ if (ringFrames[slot] !== frame) return false;
+ blitter.blit(ringTexture(slot), surface.getCurrentTexture());
+ surface.present();
+ shown = frame;
+ return true;
+ },
+ };
+
+ const player: PreviewPlayer = {
+ meta,
+ canvas,
+ lastRenderMs: 0,
+ hasVision: containsOp(vm as VirtualMediaData, "Vision"),
+ render(frame) {
+ wanted = frame;
+ const done = new Promise<number>((resolve) => waiters.push(resolve));
+ pump();
+ return done;
+ },
+ async warm(frame) {
+ if (drawing || wanted !== null) return false;
+ drawing = draw(frame, false).catch((err: unknown) =>
+ console.warn("[gitframes] warm-up of frame", frame, err),
+ );
+ await drawing;
+ drawing = null;
+ pump();
+ return true;
+ },
+ buffer,
+ };
+ return player;
+}
+
+function containsOp(node: VirtualMediaData, op: string): boolean {
+ if ((node.operation as { op?: string } | undefined)?.op === op) return true;
+ return (node.children ?? []).some((child) => containsOp(child, op));
+}
+
+async function registerRenderers(renderers: readonly BuiltinRenderer[]) {
+ await Promise.all(
+ renderers.map(async ({ ops, load }) => {
+ try {
+ const plugin = (await load()).default;
+ for (const op of ops) {
+ if (plugin?.WebGPURenderer)
+ registerWebGPURenderer(op, plugin.WebGPURenderer);
+ if (plugin?.audioProcessor)
+ audioRegistry.register(op, plugin.audioProcessor);
+ }
+ } catch (err) {
+ console.warn("[gitframes] renderer for", ops[0], "failed to load", err);
+ }
+ }),
+ );
+}
+
+/** Loads every font the program's text uses, for layout and for drawing. */
+async function preloadFonts(vm: VirtualMediaData, device: GPUDevice) {
+ const families = new Set<string>();
+ (function walk(node: VirtualMediaData) {
+ const op = node.operation as Record<string, unknown> | undefined;
+ if (op) {
+ const isText =
+ op.op === "text" ||
+ op.kind === "text" ||
+ op.op === "caption" ||
+ op.kind === "caption" ||
+ typeof op.text === "string";
+ const family = (op.fontFamily as string) || (isText ? "Inter" : "");
+ if (family) families.add(family);
+ }
+ for (const child of node.children ?? []) walk(child);
+ })(vm);
+ await Promise.all(
+ [...families].map(async (family) => {
+ const url = getHeadlessFontPath(family) ?? GetFontAssetUrl(family);
+ await Promise.all([
+ preloadFont(family, url).catch((err: unknown) =>
+ console.warn(`[gitframes] font "${family}"`, err),
+ ),
+ SlugFontCache.preloadSlugFont(device, family, url).catch(
+ (err: unknown) => console.warn(`[gitframes] font "${family}"`, err),
+ ),
+ ]);
+ }),
+ );
+}
diff --git a/packages/gitframes/src/preview/preview.test.ts b/packages/gitframes/src/preview/preview.test.ts
new file mode 100644
index 00000000..3d36c7e0
--- /dev/null
+++ b/packages/gitframes/src/preview/preview.test.ts
@@ -0,0 +1,111 @@
+import http from "node:http";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it } from "vitest";
+import { type PreviewSession, startPreview } from "./index.js";
+
+const entry = new URL("./fixtures/comp.ts", import.meta.url);
+
+describe("startPreview", () => {
+ const sessions: PreviewSession[] = [];
+ const start = async (...args: Parameters<typeof startPreview>) => {
+ const s = await startPreview(...args);
+ sessions.push(s);
+ return s;
+ };
+ afterEach(async () => {
+ await Promise.all(sessions.splice(0).map((s) => s.close()));
+ });
+
+ it("serves meta, the page, and the composition's browser bundle", async () => {
+ const session = await start(
+ { entry },
+ { open: false, port: 0, title: "Test" },
+ );
+
+ const meta = await (await fetch(`${session.url}meta`)).json();
+ expect(meta).toMatchObject({
+ title: "Test",
+ fps: 10,
+ frameCount: 10,
+ width: 64,
+ audio: { state: "none" },
+ });
+
+ const page = await (await fetch(session.url)).text();
+ expect(page).toContain('id="canvas"');
+ expect(page).toContain("/@gitframes/player.js");
+
+ const player = await fetch(`${session.url}@gitframes/player.js`);
+ expect(player.headers.get("content-type")).toContain("javascript");
+ const code = await player.text();
+ expect(code).toContain("startPlayer");
+ expect(code).not.toContain("Could not build the preview");
+ }, 60_000);
+
+ it("serves project files by absolute path, with byte ranges", async () => {
+ const session = await start({ entry }, { open: false, port: 0 });
+ const file = fileURLToPath(entry);
+
+ const whole = await fetch(`${session.url}${file.slice(1)}`);
+ expect(whole.status).toBe(200);
+ expect(await whole.text()).toContain("stand-in composition");
+
+ const part = await fetch(`${session.url}${file.slice(1)}`, {
+ headers: { range: "bytes=0-1" },
+ });
+ expect(part.status).toBe(206);
+ expect(await part.text()).toBe("//");
+
+ expect((await fetch(`${session.url}etc/hosts`)).status).toBe(404);
+
+ const stat = (p: string) =>
+ fetch(`${session.url}@gitframes/stat?path=${encodeURIComponent(p)}`).then(
+ (r) => r.json(),
+ );
+ expect(await stat(file)).toMatchObject({ exists: true });
+ expect(await stat(`${file}.missing`)).toEqual({ exists: false, size: 0 });
+ expect(await stat("/etc/hosts")).toEqual({ exists: false, size: 0 });
+ });
+
+ it("names a missing export", async () => {
+ await expect(
+ startPreview({ entry, export: "film" }, { open: false, port: 0 }),
+ ).rejects.toThrow(/no export named "film"/);
+ });
+
+ it("closes once the last tab has gone, but not on a reload", async () => {
+ const session = await start(
+ { entry },
+ { open: false, port: 0, idleCloseMs: 100 },
+ );
+ let isClosed = false;
+ session.closed.then(() => {
+ isClosed = true;
+ });
+ const connect = () =>
+ new Promise<http.ClientRequest>((resolve) => {
+ const req = http.get(`${session.url}events`, { agent: false }, () =>
+ resolve(req),
+ );
+ });
+ // A reload: the tab drops and is back well inside the grace period.
+ (await connect()).destroy();
+ await new Promise((r) => setTimeout(r, 30));
+ const tab = await connect();
+ await new Promise((r) => setTimeout(r, 200));
+ expect(isClosed).toBe(false);
+ // The tab closes for good.
+ tab.destroy();
+ await session.closed;
+ });
+
+ it("a new preview of the project takes over the port", async () => {
+ const first = await start({ entry }, { open: false, port: 0 });
+ const port = Number(new URL(first.url).port);
+ const second = await start({ entry }, { open: false, port });
+
+ await first.closed;
+ expect(second.url).toBe(first.url);
+ expect((await fetch(`${second.url}meta`)).status).toBe(200);
+ });
+});
diff --git a/packages/gitframes/src/preview/shims/fs-promises.ts b/packages/gitframes/src/preview/shims/fs-promises.ts
new file mode 100644
index 00000000..bcbcd40a
--- /dev/null
+++ b/packages/gitframes/src/preview/shims/fs-promises.ts
@@ -0,0 +1,18 @@
+// `node:fs/promises` for the browser preview bundle; see fs.ts.
+import { promises } from "./fs.js";
+
+export const {
+ readFile,
+ stat,
+ access,
+ readdir,
+ writeFile,
+ appendFile,
+ mkdir,
+ rm,
+ unlink,
+ rename,
+ copyFile,
+ open,
+} = promises;
+export default promises;
diff --git a/packages/gitframes/src/preview/shims/fs.ts b/packages/gitframes/src/preview/shims/fs.ts
new file mode 100644
index 00000000..b918c4ca
--- /dev/null
+++ b/packages/gitframes/src/preview/shims/fs.ts
@@ -0,0 +1,135 @@
+/// <reference lib="dom" />
+/// <reference types="webgpu" />
+// `node:fs` for the browser preview bundle. Reads go to the preview server,
+// which serves files by their absolute path; synchronous reads use a
+// synchronous request, so build-time code like `JSON.parse(readFileSync(…))`
+// runs unchanged. Writes are skipped: the preview never changes the project.
+type Enc =
+ | BufferEncoding
+ | { encoding?: BufferEncoding | null }
+ | null
+ | undefined;
+
+const toUrl = (p: string | URL): string => {
+ const s = String(p);
+ return encodeURI(
+ s.startsWith("file://") ? decodeURIComponent(new URL(s).pathname) : s,
+ );
+};
+const encodingOf = (e: Enc) =>
+ typeof e === "string" ? e : (e?.encoding ?? null);
+
+function enoent(p: unknown): Error {
+ return Object.assign(
+ new Error(`ENOENT: no such file or directory, open '${p}'`),
+ {
+ code: "ENOENT",
+ },
+ );
+}
+
+function request(method: string, p: string | URL): XMLHttpRequest {
+ const xhr = new XMLHttpRequest();
+ xhr.open(method, toUrl(p), false);
+ // Binary-safe text: each byte comes back as one char code.
+ xhr.overrideMimeType("text/plain; charset=x-user-defined");
+ xhr.send();
+ return xhr;
+}
+
+export function readFileSync(p: string | URL, enc?: Enc): string | Uint8Array {
+ const xhr = request("GET", p);
+ if (xhr.status !== 200) throw enoent(p);
+ const raw = xhr.responseText;
+ const bytes = new Uint8Array(raw.length);
+ for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i) & 0xff;
+ return encodingOf(enc) ? new TextDecoder().decode(bytes) : bytes;
+}
+
+function stat(p: string | URL): { exists: boolean; size: number } {
+ const s = String(p);
+ const file = s.startsWith("file://")
+ ? decodeURIComponent(new URL(s).pathname)
+ : s;
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", `/@gitframes/stat?path=${encodeURIComponent(file)}`, false);
+ xhr.send();
+ return xhr.status === 200
+ ? JSON.parse(xhr.responseText)
+ : { exists: false, size: 0 };
+}
+
+export function existsSync(p: string | URL): boolean {
+ try {
+ return stat(p).exists;
+ } catch {
+ return false;
+ }
+}
+
+export function statSync(p: string | URL) {
+ const { exists, size } = stat(p);
+ if (!exists) throw enoent(p);
+ return { size, isFile: () => true, isDirectory: () => false, mtimeMs: 0 };
+}
+
+const skip = (): undefined => undefined;
+const unsupported = (name: string) => () => {
+ throw new Error(`fs.${name} is not available in the browser preview`);
+};
+export const writeFileSync = skip;
+export const mkdirSync = skip;
+export const rmSync = skip;
+export const unlinkSync = skip;
+export const renameSync = skip;
+export const copyFileSync = skip;
+export const appendFileSync = skip;
+export const readdirSync = (): string[] => [];
+export const accessSync = (p: string | URL): void => {
+ if (!existsSync(p)) throw enoent(p);
+};
+export const createReadStream = unsupported("createReadStream");
+export const createWriteStream = unsupported("createWriteStream");
+export const watch = unsupported("watch");
+export const constants = { F_OK: 0, R_OK: 4, W_OK: 2, X_OK: 1 };
+
+const asyncSkip = async (): Promise<undefined> => undefined;
+export const promises = {
+ readFile: async (p: string | URL, enc?: Enc) => {
+ const res = await fetch(toUrl(p));
+ if (!res.ok) throw enoent(p);
+ const bytes = new Uint8Array(await res.arrayBuffer());
+ return encodingOf(enc) ? new TextDecoder().decode(bytes) : bytes;
+ },
+ stat: async (p: string | URL) => statSync(p),
+ access: async (p: string | URL) => accessSync(p),
+ readdir: async (): Promise<string[]> => [],
+ writeFile: asyncSkip,
+ appendFile: asyncSkip,
+ mkdir: asyncSkip,
+ rm: asyncSkip,
+ unlink: asyncSkip,
+ rename: asyncSkip,
+ copyFile: asyncSkip,
+ open: unsupported("promises.open"),
+};
+
+export default {
+ readFileSync,
+ existsSync,
+ statSync,
+ accessSync,
+ readdirSync,
+ writeFileSync,
+ mkdirSync,
+ rmSync,
+ unlinkSync,
+ renameSync,
+ copyFileSync,
+ appendFileSync,
+ createReadStream,
+ createWriteStream,
+ watch,
+ constants,
+ promises,
+};
diff --git a/packages/gitframes/src/preview/shims/os.ts b/packages/gitframes/src/preview/shims/os.ts
new file mode 100644
index 00000000..5a27d5a9
--- /dev/null
+++ b/packages/gitframes/src/preview/shims/os.ts
@@ -0,0 +1,21 @@
+/// <reference lib="dom" />
+// `node:os` for the browser preview bundle.
+export const homedir = (): string => "/";
+export const tmpdir = (): string => "/tmp";
+export const platform = (): string => "browser";
+export const arch = (): string => "wasm";
+export const cpus = (): unknown[] =>
+ Array.from({ length: navigator.hardwareConcurrency || 4 }, () => ({}));
+export const totalmem = (): number => 0;
+export const freemem = (): number => 0;
+export const EOL = "\n";
+export default {
+ homedir,
+ tmpdir,
+ platform,
+ arch,
+ cpus,
+ totalmem,
+ freemem,
+ EOL,
+};
diff --git a/packages/gitframes/src/preview/shims/path.ts b/packages/gitframes/src/preview/shims/path.ts
new file mode 100644
index 00000000..3f64dc42
--- /dev/null
+++ b/packages/gitframes/src/preview/shims/path.ts
@@ -0,0 +1,107 @@
+// `node:path` for the browser preview bundle (POSIX semantics).
+
+export const sep = "/";
+export const delimiter = ":";
+
+export function normalize(p: string): string {
+ if (!p) return ".";
+ const abs = p.startsWith("/");
+ const out: string[] = [];
+ for (const part of p.split("/")) {
+ if (!part || part === ".") continue;
+ if (part === "..") {
+ if (out.length && out[out.length - 1] !== "..") out.pop();
+ else if (!abs) out.push("..");
+ } else out.push(part);
+ }
+ const joined = out.join("/");
+ const trailing = p.endsWith("/") && joined ? "/" : "";
+ return (abs ? "/" : "") + joined + trailing || (abs ? "/" : ".");
+}
+
+export function join(...parts: string[]): string {
+ return normalize(parts.filter(Boolean).join("/"));
+}
+
+export function resolve(...parts: string[]): string {
+ let out = "";
+ for (let i = parts.length - 1; i >= 0 && !out.startsWith("/"); i--) {
+ if (parts[i]) out = out ? `${parts[i]}/${out}` : parts[i];
+ }
+ return normalize(out.startsWith("/") ? out : `/${out}`).replace(
+ /(.)\/$/,
+ "$1",
+ );
+}
+
+export const isAbsolute = (p: string): boolean => p.startsWith("/");
+
+export function dirname(p: string): string {
+ const trimmed = p.replace(/\/+$/, "");
+ const i = trimmed.lastIndexOf("/");
+ if (i < 0) return ".";
+ return i === 0 ? "/" : trimmed.slice(0, i);
+}
+
+export function basename(p: string, ext?: string): string {
+ const base = p.replace(/\/+$/, "").split("/").pop() ?? "";
+ return ext && base.endsWith(ext) ? base.slice(0, -ext.length) : base;
+}
+
+export function extname(p: string): string {
+ const base = basename(p);
+ const i = base.lastIndexOf(".");
+ return i > 0 ? base.slice(i) : "";
+}
+
+export function relative(from: string, to: string): string {
+ const a = resolve(from).split("/").filter(Boolean);
+ const b = resolve(to).split("/").filter(Boolean);
+ let i = 0;
+ while (i < a.length && a[i] === b[i]) i++;
+ return [...a.slice(i).map(() => ".."), ...b.slice(i)].join("/");
+}
+
+export function parse(p: string) {
+ const base = basename(p);
+ const ext = extname(p);
+ return {
+ root: p.startsWith("/") ? "/" : "",
+ dir: dirname(p),
+ base,
+ ext,
+ name: ext ? base.slice(0, -ext.length) : base,
+ };
+}
+
+export function format(o: {
+ dir?: string;
+ base?: string;
+ name?: string;
+ ext?: string;
+}): string {
+ const base = o.base ?? `${o.name ?? ""}${o.ext ?? ""}`;
+ return o.dir ? `${o.dir}/${base}` : base;
+}
+
+export const toNamespacedPath = (p: string): string => p;
+
+const path = {
+ sep,
+ delimiter,
+ normalize,
+ join,
+ resolve,
+ isAbsolute,
+ dirname,
+ basename,
+ extname,
+ relative,
+ parse,
+ format,
+ toNamespacedPath,
+ posix: undefined as unknown,
+};
+path.posix = path;
+export const posix = path;
+export default path;
diff --git a/packages/gitframes/src/preview/shims/process.ts b/packages/gitframes/src/preview/shims/process.ts
new file mode 100644
index 00000000..1c395286
--- /dev/null
+++ b/packages/gitframes/src/preview/shims/process.ts
@@ -0,0 +1,13 @@
+// A minimal `process` for the browser preview bundle. It has no
+// `versions.node`, so code that checks for Node takes its browser path.
+export const process = {
+ env: { NODE_ENV: "development" } as Record<string, string | undefined>,
+ argv: [] as string[],
+ platform: "browser",
+ browser: true,
+ cwd: () => "/",
+ nextTick: (fn: (...a: unknown[]) => void, ...args: unknown[]) =>
+ queueMicrotask(() => fn(...args)),
+ on: () => process,
+ emitWarning: () => undefined,
+};
diff --git a/packages/gitframes/src/preview/shims/url.ts b/packages/gitframes/src/preview/shims/url.ts
new file mode 100644
index 00000000..bb8fb017
--- /dev/null
+++ b/packages/gitframes/src/preview/shims/url.ts
@@ -0,0 +1,8 @@
+// `node:url` for the browser preview bundle.
+export const fileURLToPath = (url: string | URL): string =>
+ decodeURIComponent(new URL(String(url)).pathname);
+export const pathToFileURL = (p: string): URL =>
+ new URL(`file://${encodeURI(p)}`);
+const URLCtor = globalThis.URL;
+export { URLCtor as URL };
+export default { fileURLToPath, pathToFileURL, URL: URLCtor };
diff --git a/packages/gitframes/tsdown.config.ts b/packages/gitframes/tsdown.config.ts
index 54377427..8671a100 100644
--- a/packages/gitframes/tsdown.config.ts
+++ b/packages/gitframes/tsdown.config.ts
@@ -8,6 +8,7 @@ export default defineConfig({
"src/signals/index.ts",
"src/renderer/index.ts",
"src/fonts/index.ts",
+ "src/preview/index.ts",
],
format: ["esm"],
clean: true,
@@ -24,7 +25,7 @@ export default defineConfig({
"onnxruntime-node",
"skia-canvas",
"fontkit",
- "chartgpu",
+ /^d3-/,
"webgpu",
"yoga-layout",
"zod",
diff --git a/packages/media/package.json b/packages/media/package.json
index 616113ae..c9e12755 100644
--- a/packages/media/package.json
+++ b/packages/media/package.json
@@ -43,8 +43,8 @@
"@gitframes/core": "workspace:*",
"@gitframes/server-utils": "workspace:*",
"file-type": "^21.3.0",
- "fflate": "^0.8.2",
- "sharp": "^0.34.5"
+ "fflate": "^0.8.3",
+ "sharp": "^0.35.4"
},
"peerDependencies": {
"inversify": "*"
diff --git a/packages/renderer/package.json b/packages/renderer/package.json
index ba7b8039..c1e57467 100644
--- a/packages/renderer/package.json
+++ b/packages/renderer/package.json
@@ -102,7 +102,7 @@
"@mediabunny/server": "^1.51.0",
"@napi-rs/webcodecs": "^1.3.1",
"mediabunny": "^1.51.0",
- "sharp": "^0.33.5",
+ "sharp": "^0.35.4",
"skia-canvas": "^3.0.8",
"webgpu": "^0.4.0"
},
diff --git a/packages/renderer/src/headless-webgpu-renderer.ts b/packages/renderer/src/headless-webgpu-renderer.ts
index 7c978ed5..6164a0ff 100644
--- a/packages/renderer/src/headless-webgpu-renderer.ts
+++ b/packages/renderer/src/headless-webgpu-renderer.ts
@@ -461,6 +461,11 @@ export class HeadlessWebGPURenderer {
virtualMedia: VirtualMediaData,
frame = 0,
fps = 24,
+ options: {
+ renderId?: string;
+ /** "rgba" skips PNG encoding and returns width*height*4 raw pixels. */
+ format?: "png" | "rgba";
+ } = {},
): Promise<Buffer> {
await HeadlessWebGPURenderer.initialize();
@@ -469,7 +474,10 @@ export class HeadlessWebGPURenderer {
if (!width || !height)
throw new Error(`Invalid dimensions: ${width}x${height}`);
- const renderId = `img-${randomUUID()}`;
+ // A caller rendering consecutive frames (e.g. a scrubbing preview) passes a
+ // stable id so compiled timelines are reused across frames, as renderVideo
+ // does. Never render two frames with the same id concurrently.
+ const renderId = options.renderId ?? `img-${randomUUID()}`;
rendererLogger.debug(
{ renderId, frame, ...renderSemaphore.stats },
@@ -580,6 +588,8 @@ export class HeadlessWebGPURenderer {
pixels.byteLength,
);
+ if (options.format === "rgba") return Buffer.from(pixelsArr);
+
const pngBuffer = await sharp(Buffer.from(pixelsArr), {
raw: { width, height, channels: 4 },
})
@@ -620,7 +630,15 @@ export class HeadlessWebGPURenderer {
*/
public async renderFrame(
source: VirtualMediaData | { toVirtualMedia(): VirtualMediaData },
- options: { atMs?: number; frame?: number; fps?: number } = {},
+ options: {
+ atMs?: number;
+ frame?: number;
+ fps?: number;
+ /** Reuse compiled state across calls; see `renderImage`. */
+ renderId?: string;
+ /** "rgba" returns raw width*height*4 pixels instead of a PNG. */
+ format?: "png" | "rgba";
+ } = {},
): Promise<Buffer> {
const vm =
typeof source === "object" &&
@@ -633,7 +651,35 @@ export class HeadlessWebGPURenderer {
options.atMs !== undefined
? Math.round((options.atMs / 1000) * fps)
: (options.frame ?? 0);
- return this.renderImage(vm, frame, fps);
+ return this.renderImage(vm, frame, fps, {
+ renderId: options.renderId,
+ format: options.format,
+ });
+ }
+
+ /**
+ * Mixes the composition's full audio timeline (clips, effects, synthesized
+ * tracks) to stereo PCM, exactly as `renderVideo` muxes it.
+ */
+ public async renderAudio(
+ virtualMedia: VirtualMediaData,
+ options: { fps?: number; sampleRate?: number } = {},
+ ): Promise<{ channels: Float32Array[]; sampleRate: number }> {
+ await HeadlessWebGPURenderer.initialize();
+ const fps = options.fps ?? (virtualMedia.metadata?.fps || 30);
+ await renderSemaphore.acquire();
+ try {
+ const device = await ensureDevice();
+ return await mixAudioTracks(
+ virtualMedia,
+ fps,
+ options.sampleRate ?? 48_000,
+ device,
+ `aud-${randomUUID()}`,
+ );
+ } finally {
+ renderSemaphore.release();
+ }
}
public async renderLut(
diff --git a/packages/vision/src/model/model-store.ts b/packages/vision/src/model/model-store.ts
index 6b544072..de0443ac 100644
--- a/packages/vision/src/model/model-store.ts
+++ b/packages/vision/src/model/model-store.ts
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto";
-import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
-import { rename, unlink, writeFile } from "node:fs/promises";
+import { existsSync, mkdirSync, statSync } from "node:fs";
+import { readFile, rename, unlink, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import {
@@ -271,8 +271,11 @@ export class VisionModelStore {
}
}
- private readBuffer(key: VisionModelKey, targetPath: string): Uint8Array {
- const fileBuffer = readFileSync(targetPath);
+ private async readBuffer(
+ key: VisionModelKey,
+ targetPath: string,
+ ): Promise<Uint8Array> {
+ const fileBuffer = await readFile(targetPath);
const buffer = new Uint8Array(
fileBuffer.buffer,
fileBuffer.byteOffset,
diff --git a/packages/vision/src/runner/vision-runner.ts b/packages/vision/src/runner/vision-runner.ts
index 66d536ad..00c28339 100644
--- a/packages/vision/src/runner/vision-runner.ts
+++ b/packages/vision/src/runner/vision-runner.ts
@@ -20,7 +20,7 @@ import {
type VisionVariant,
} from "../model/registry.js";
import {
- NodeSessionProvider,
+ createDefaultSessionProvider,
type SessionProvider,
type VisionSession,
type VisionTensor,
@@ -99,7 +99,7 @@ export class VisionRunner {
timeoutMs: options.timeoutMs,
onProgress: options.onProgress,
});
- this._provider = options.provider ?? new NodeSessionProvider();
+ this._provider = options.provider ?? createDefaultSessionProvider();
}
/** Cheap: no downloads, no sessions, no side effects. */
diff --git a/packages/vision/src/runtime/session-provider.ts b/packages/vision/src/runtime/session-provider.ts
index d21ed222..db613870 100644
--- a/packages/vision/src/runtime/session-provider.ts
+++ b/packages/vision/src/runtime/session-provider.ts
@@ -28,6 +28,24 @@ export interface SessionProvider {
createSession(modelBytes: Uint8Array): Promise<VisionSession>;
}
+let defaultProvider: (() => SessionProvider) | undefined;
+
+/**
+ * Sets the provider runners use when none is passed, for hosts that create
+ * runners indirectly (e.g. a browser player rendering vision nodes). `undefined`
+ * restores the default, onnxruntime-node.
+ */
+export function setDefaultSessionProvider(
+ factory: (() => SessionProvider) | undefined,
+): void {
+ defaultProvider = factory;
+}
+
+/** The provider for a runner created without one. */
+export function createDefaultSessionProvider(): SessionProvider {
+ return defaultProvider?.() ?? new NodeSessionProvider();
+}
+
/** onnxruntime-node provider. The native module is imported lazily on first session. */
export class NodeSessionProvider implements SessionProvider {
public readonly kind = "node" as const;
diff --git a/packages/vision/src/runtime/webgpu-provider.ts b/packages/vision/src/runtime/webgpu-provider.ts
index 90ac8889..04e957a9 100644
--- a/packages/vision/src/runtime/webgpu-provider.ts
+++ b/packages/vision/src/runtime/webgpu-provider.ts
@@ -36,6 +36,8 @@ export interface OrtWebModule {
options: {
executionProviders: string[];
graphOptimizationLevel?: "disabled" | "basic" | "extended" | "all";
+ /** 0 verbose … 4 fatal. */
+ logSeverityLevel?: 0 | 1 | 2 | 3 | 4;
},
): Promise<OrtWebSession>;
};
@@ -98,12 +100,16 @@ export class WebGPUProvider implements SessionProvider {
session = await ort.InferenceSession.create(modelBytes, {
executionProviders: [...this._providers],
graphOptimizationLevel: "all",
+ // Errors only: node-placement notes print as console errors otherwise.
+ logSeverityLevel: 3,
});
} catch (err) {
if (!this._wasmFallback || !this._providers.includes("webgpu")) throw err;
session = await ort.InferenceSession.create(modelBytes, {
executionProviders: ["wasm"],
graphOptimizationLevel: "all",
+ // Errors only: node-placement notes print as console errors otherwise.
+ logSeverityLevel: 3,
});
}
diff --git a/packages/webgpu-renderers/package.json b/packages/webgpu-renderers/package.json
index a4334a61..7a75fc56 100644
--- a/packages/webgpu-renderers/package.json
+++ b/packages/webgpu-renderers/package.json
@@ -33,12 +33,11 @@
"@gitframes/core": "workspace:*",
"@lottiefiles/dotlottie-web": "^0.74.0",
"@resvg/resvg-js": "^2.6.2",
- "chartgpu": "^0.4.0",
"earcut": "^3.2.4",
"fontkit": "^2.0.4",
"gifuct-js": "^2.1.2",
"mediabunny": "^1.51.0",
- "sharp": "^0.34.5",
+ "sharp": "^0.35.4",
"skia-canvas": "^3.0.8",
"webgpu": "^0.4.0"
},
@@ -46,7 +45,7 @@
"@gitframes/tsconfig": "workspace:*",
"@types/earcut": "^3.0.0",
"@types/fontkit": "^2.0.9",
- "@vitest/coverage-v8": "^4.1.5",
+ "@vitest/coverage-v8": "^4.1.11",
"tsdown": "^0.19.0",
"typescript": "^5.8.3",
"vitest": "^4.1.5",
diff --git a/packages/webgpu-renderers/src/nodes/chart.test.ts b/packages/webgpu-renderers/src/nodes/chart.test.ts
deleted file mode 100644
index 8bcc823e..00000000
--- a/packages/webgpu-renderers/src/nodes/chart.test.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import type { ChartGPUOptions } from "chartgpu";
-import { describe, expect, it, vi } from "vitest";
-import type { RenderContextValue } from "../render-context.js";
-import {
- ChartGPUEngineBridge,
- chartBridgeCache,
- drawChartNode,
- HeadlessChartCanvasElementMock,
- HeadlessChartContainerMock,
- HeadlessGPUCanvasContextMock,
-} from "./chart.js";
-import type { ChartNodeProps } from "./types.js";
-
-if (typeof globalThis.GPUTextureUsage === "undefined") {
- (globalThis as unknown as { GPUTextureUsage: unknown }).GPUTextureUsage = {
- COPY_SRC: 0x01,
- COPY_DST: 0x02,
- TEXTURE_BINDING: 0x04,
- STORAGE_BINDING: 0x08,
- RENDER_ATTACHMENT: 0x10,
- };
-}
-
-describe("Chart Node & Headless WebGPU Adapter", () => {
- const createMockDevice = () => {
- const mockTexture = {
- destroy: vi.fn(),
- createView: vi.fn().mockReturnValue({}),
- };
- return {
- lost: new Promise(() => {}),
- createTexture: vi.fn().mockReturnValue(mockTexture),
- createBuffer: vi.fn().mockReturnValue({
- destroy: vi.fn(),
- getMappedRange: vi.fn().mockReturnValue(new ArrayBuffer(1024)),
- unmap: vi.fn(),
- }),
- createBindGroupLayout: vi.fn().mockReturnValue({}),
- createBindGroup: vi.fn().mockReturnValue({}),
- createPipelineLayout: vi.fn().mockReturnValue({}),
- createRenderPipeline: vi.fn().mockReturnValue({}),
- createComputePipeline: vi.fn().mockReturnValue({}),
- createShaderModule: vi.fn().mockReturnValue({}),
- createSampler: vi.fn().mockReturnValue({}),
- createCommandEncoder: vi.fn().mockReturnValue({
- beginRenderPass: vi.fn().mockReturnValue({
- setPipeline: vi.fn(),
- setBindGroup: vi.fn(),
- setVertexBuffer: vi.fn(),
- draw: vi.fn(),
- end: vi.fn(),
- }),
- finish: vi.fn().mockReturnValue({}),
- }),
- limits: {
- maxTextureDimension2D: 8192,
- maxBufferSize: 268435456,
- maxStorageBufferBindingSize: 134217728,
- maxUniformBufferBindingSize: 65536,
- minUniformBufferOffsetAlignment: 256,
- minStorageBufferOffsetAlignment: 256,
- maxVertexBuffers: 8,
- maxVertexAttributes: 16,
- maxVertexBufferArrayStride: 2048,
- maxInterStageShaderComponents: 60,
- maxComputeWorkgroupStorageSize: 32768,
- },
- features: new Set(["float32-filterable"]),
- queue: {
- submit: vi.fn(),
- writeTexture: vi.fn(),
- writeBuffer: vi.fn(),
- },
- } as unknown as GPUDevice;
- };
-
- it("HeadlessGPUCanvasContextMock handles configure and getCurrentTexture", () => {
- const mockDevice = createMockDevice();
- const mockTexture = mockDevice.createTexture({
- size: [100, 100],
- format: "rgba8unorm",
- usage: 0,
- });
- const target = {
- device: mockDevice,
- format: "rgba8unorm" as GPUTextureFormat,
- width: 100,
- height: 100,
- currentTexture: mockTexture,
- };
-
- const ctx = new HeadlessGPUCanvasContextMock(target);
- ctx.configure({
- device: mockDevice,
- format: "rgba8unorm",
- });
- expect(ctx.configuredFormat).toBe("rgba8unorm");
- expect(ctx.getCurrentTexture()).toBe(mockTexture);
-
- ctx.unconfigure();
- expect(ctx.configuredFormat).toBeNull();
- });
-
- it("HeadlessChartCanvasElementMock & ContainerMock provide DOM geometry shims", () => {
- const mockDevice = createMockDevice();
- const target = {
- device: mockDevice,
- format: "rgba8unorm" as GPUTextureFormat,
- width: 320,
- height: 240,
- currentTexture: mockDevice.createTexture({
- size: [320, 240],
- format: "rgba8unorm",
- usage: 0,
- }),
- };
-
- const canvas = new HeadlessChartCanvasElementMock(target);
- expect(canvas.width).toBe(320);
- expect(canvas.height).toBe(240);
- const rect = canvas.getBoundingClientRect();
- expect(rect.width).toBe(320);
- expect(rect.height).toBe(240);
-
- const gpuCtx = canvas.getContext("webgpu");
- expect(gpuCtx).toBeInstanceOf(HeadlessGPUCanvasContextMock);
-
- const container = new HeadlessChartContainerMock(320, 240);
- const child = {};
- container.appendChild(child);
- expect(container.children).toContain(child);
- container.removeChild(child);
- expect(container.children).not.toContain(child);
- });
-
- it("ChartGPUEngineBridge initializes and renders frames", async () => {
- const mockDevice = createMockDevice();
- const bridge = new ChartGPUEngineBridge({
- device: mockDevice,
- width: 400,
- height: 200,
- });
-
- expect(bridge.width).toBe(400);
- expect(bridge.height).toBe(200);
- expect(bridge.currentTexture).toBeDefined();
-
- const options = {
- theme: "dark" as const,
- xAxis: { type: "category" as const },
- yAxis: { type: "value" as const },
- series: [
- {
- type: "line" as const,
- data: [
- [0, 10],
- [1, 20],
- [2, 30],
- ],
- },
- ],
- };
-
- await bridge.initialize(options as unknown as ChartGPUOptions);
- const tex = await bridge.renderFrame(0.5);
- expect(tex).toBeDefined();
-
- bridge.destroy();
- });
-
- it("drawChartNode manages bridge cache and calls ctx.renderer.drawTexture", async () => {
- const mockDevice = createMockDevice();
- const mockPass = {} as GPURenderPassEncoder;
- const mockRenderer = {
- drawTexture: vi.fn(),
- };
- const mockCtx = {
- device: mockDevice,
- renderer: mockRenderer,
- } as unknown as RenderContextValue;
-
- const props: ChartNodeProps = {
- nodeId: "test_chart_node",
- dstRect: { x: 10, y: 10, width: 200, height: 100 },
- chartOptions: {
- series: [
- {
- type: "line" as const,
- data: [
- [0, 5],
- [1, 15],
- ],
- },
- ],
- } as unknown as ChartGPUOptions,
- progress: 0.8,
- opacity: 0.9,
- };
-
- await drawChartNode(mockCtx, mockPass, props);
-
- expect(chartBridgeCache.has("test_chart_node")).toBe(true);
- expect(mockRenderer.drawTexture).toHaveBeenCalledWith(
- mockPass,
- expect.anything(),
- props.dstRect,
- expect.objectContaining({ opacity: 0.9 }),
- );
-
- // Clean up
- const bridge = chartBridgeCache.get("test_chart_node");
- bridge?.destroy();
- chartBridgeCache.delete("test_chart_node");
- });
-});
diff --git a/packages/webgpu-renderers/src/nodes/chart.ts b/packages/webgpu-renderers/src/nodes/chart.ts
deleted file mode 100644
index f538f1f7..00000000
--- a/packages/webgpu-renderers/src/nodes/chart.ts
+++ /dev/null
@@ -1,625 +0,0 @@
-import { createRequire } from "node:module";
-import {
- ChartGPU,
- type ChartGPUInstance,
- type ChartGPUOptions,
-} from "chartgpu";
-import type { RenderContextValue } from "../render-context.js";
-import type { ChartNodeProps } from "./types.js";
-
-const nodeRequire =
- typeof import.meta?.url === "string" ? createRequire(import.meta.url) : null;
-
-// ==============================================================================================
-// 1. HEADLESS CANVAS & WEBGPU CONTEXT ADAPTER
-// ==============================================================================================
-
-export interface HeadlessChartTarget {
- readonly device: GPUDevice;
- readonly format: GPUTextureFormat;
- width: number;
- height: number;
- currentTexture: GPUTexture;
-}
-
-export class HeadlessGPUCanvasContextMock {
- private target: HeadlessChartTarget;
- configuredFormat: GPUTextureFormat | null = null;
-
- constructor(target: HeadlessChartTarget) {
- this.target = target;
- }
-
- configure(config: GPUCanvasConfiguration): void {
- this.configuredFormat = config.format;
- }
-
- unconfigure(): void {
- this.configuredFormat = null;
- }
-
- getCurrentTexture(): GPUTexture {
- return this.target.currentTexture;
- }
-}
-
-export interface Headless2DContextFallback {
- save(): void;
- restore(): void;
- setTransform(
- a: number,
- b: number,
- c: number,
- d: number,
- e: number,
- f: number,
- ): void;
- clearRect(x: number, y: number, w: number, h: number): void;
- fillText(text: string, x: number, y: number): void;
- measureText(text: string): { width: number };
-}
-
-export class HeadlessChartCanvasElementMock {
- width: number;
- height: number;
- clientWidth: number;
- clientHeight: number;
- readonly style: Record<string, string> = {
- display: "block",
- width: "100%",
- height: "100%",
- position: "absolute",
- inset: "0",
- };
-
- private gpuContext: HeadlessGPUCanvasContextMock;
- private ctx2d: Headless2DContextFallback | null = null;
-
- constructor(target: HeadlessChartTarget) {
- this.width = target.width;
- this.height = target.height;
- this.clientWidth = target.width;
- this.clientHeight = target.height;
- this.gpuContext = new HeadlessGPUCanvasContextMock(target);
- }
-
- getContext(type: string): unknown {
- if (type === "webgpu") {
- return this.gpuContext;
- }
- if (type === "2d") {
- if (!this.ctx2d) {
- try {
- if (nodeRequire) {
- const { Canvas } = nodeRequire("skia-canvas");
- const skiaCanvas = new Canvas(this.width, this.height);
- this.ctx2d = skiaCanvas.getContext(
- "2d",
- ) as unknown as Headless2DContextFallback;
- }
- } catch {
- // Fall back to lightweight stub
- }
- if (!this.ctx2d) {
- this.ctx2d = {
- save: () => {},
- restore: () => {},
- setTransform: () => {},
- clearRect: () => {},
- fillText: () => {},
- measureText: (text: string) => ({ width: text.length * 7 }),
- };
- }
- }
- return this.ctx2d;
- }
- return null;
- }
-
- getBoundingClientRect(): {
- x: number;
- y: number;
- width: number;
- height: number;
- top: number;
- left: number;
- right: number;
- bottom: number;
- } {
- return {
- x: 0,
- y: 0,
- width: this.clientWidth,
- height: this.clientHeight,
- top: 0,
- left: 0,
- right: this.clientWidth,
- bottom: this.clientHeight,
- };
- }
-
- addEventListener(
- _type: string,
- _listener: unknown,
- _options?: unknown,
- ): void {}
-
- removeEventListener(
- _type: string,
- _listener: unknown,
- _options?: unknown,
- ): void {}
-
- setPointerCapture(_pointerId: number): void {}
-
- releasePointerCapture(_pointerId: number): void {}
-
- hasPointerCapture(_pointerId: number): boolean {
- return false;
- }
-
- remove(): void {}
-}
-
-export class HeadlessChartContainerMock {
- readonly style: Record<string, string> = {
- position: "relative",
- overflow: "hidden",
- };
- children: unknown[] = [];
-
- clientWidth: number;
- clientHeight: number;
-
- constructor(width: number, height: number) {
- this.clientWidth = width;
- this.clientHeight = height;
- }
-
- appendChild(child: unknown): unknown {
- this.children.push(child);
- return child;
- }
-
- removeChild(child: unknown): unknown {
- this.children = this.children.filter((c) => c !== child);
- return child;
- }
-
- getBoundingClientRect(): {
- x: number;
- y: number;
- width: number;
- height: number;
- top: number;
- left: number;
- right: number;
- bottom: number;
- } {
- return {
- x: 0,
- y: 0,
- width: this.clientWidth,
- height: this.clientHeight,
- top: 0,
- left: 0,
- right: this.clientWidth,
- bottom: this.clientHeight,
- };
- }
-}
-
-// ==============================================================================================
-// 2. CHARTGPU ENGINE BRIDGE & TIMELINE CONTROLLER
-// ==============================================================================================
-
-export interface ChartGPUAdapterInitOptions {
- device: GPUDevice;
- adapter?: GPUAdapter;
- width: number;
- height: number;
- dpr?: number;
- colorFormat?: GPUTextureFormat;
-}
-
-let activeCanvasMockForNextCreation: HeadlessChartCanvasElementMock | null =
- null;
-
-export class ChartGPUEngineBridge {
- private chartInstance: ChartGPUInstance | null = null;
- private target: HeadlessChartTarget;
- private containerMock: HeadlessChartContainerMock;
- private canvasMock: HeadlessChartCanvasElementMock;
- private dpr: number;
- private initialOptions: ChartGPUOptions | null = null;
- private ownsTexture: boolean;
- private lastRenderedProgress: number | null = null;
-
- constructor(options: ChartGPUAdapterInitOptions) {
- this.dpr = options.dpr ?? 1.0;
- const texW = Math.max(1, Math.round(options.width * this.dpr));
- const texH = Math.max(1, Math.round(options.height * this.dpr));
-
- const renderAttachment =
- typeof GPUTextureUsage !== "undefined"
- ? GPUTextureUsage.RENDER_ATTACHMENT
- : 0x10;
- const textureBinding =
- typeof GPUTextureUsage !== "undefined"
- ? GPUTextureUsage.TEXTURE_BINDING
- : 0x04;
- const copySrc =
- typeof GPUTextureUsage !== "undefined" ? GPUTextureUsage.COPY_SRC : 0x01;
- const copyDst =
- typeof GPUTextureUsage !== "undefined" ? GPUTextureUsage.COPY_DST : 0x02;
-
- const texture = options.device.createTexture({
- size: [texW, texH],
- format: options.colorFormat ?? "rgba8unorm",
- usage: renderAttachment | textureBinding | copySrc | copyDst,
- });
-
- this.ownsTexture = true;
- this.target = {
- device: options.device,
- format: options.colorFormat ?? "rgba8unorm",
- width: texW,
- height: texH,
- currentTexture: texture,
- };
-
- this.containerMock = new HeadlessChartContainerMock(
- options.width,
- options.height,
- );
- this.canvasMock = new HeadlessChartCanvasElementMock(this.target);
- }
-
- get width(): number {
- return this.target.width;
- }
-
- get height(): number {
- return this.target.height;
- }
-
- get currentTexture(): GPUTexture {
- return this.target.currentTexture;
- }
-
- private setupHeadlessDOM(): void {
- const gEnv = globalThis as unknown as Record<string, unknown>;
-
- if (typeof gEnv.document === "undefined") {
- gEnv.document = {};
- }
- const doc = gEnv.document as Record<string, unknown>;
-
- const originalCreateElement =
- typeof doc.createElement === "function"
- ? (
- doc.createElement as (tag: string, ...args: unknown[]) => unknown
- ).bind(doc)
- : null;
-
- doc.createElement = (tag: string, ...args: unknown[]) => {
- if (tag === "canvas") {
- if (activeCanvasMockForNextCreation) {
- const mock = activeCanvasMockForNextCreation;
- activeCanvasMockForNextCreation = null;
- return mock;
- }
- if (originalCreateElement) {
- try {
- const el = originalCreateElement(tag, ...args);
- if (el) {
- const elObj = el as Record<string, unknown>;
- if (typeof elObj.remove !== "function") elObj.remove = () => {};
- if (typeof elObj.addEventListener !== "function")
- elObj.addEventListener = () => {};
- if (typeof elObj.removeEventListener !== "function")
- elObj.removeEventListener = () => {};
- if (!elObj.style) elObj.style = {};
- return el;
- }
- } catch (_) {}
- }
- return new HeadlessChartCanvasElementMock(this.target);
- }
-
- if (originalCreateElement) {
- try {
- const el = originalCreateElement(tag, ...args);
- if (el) {
- const elObj = el as Record<string, unknown>;
- if (typeof elObj.remove !== "function") elObj.remove = () => {};
- if (typeof elObj.addEventListener !== "function")
- elObj.addEventListener = () => {};
- if (typeof elObj.removeEventListener !== "function")
- elObj.removeEventListener = () => {};
- if (!elObj.style) elObj.style = {};
- return el;
- }
- } catch (_) {}
- }
-
- return {
- style: {},
- appendChild: () => {},
- removeChild: () => {},
- remove: () => {},
- addEventListener: () => {},
- removeEventListener: () => {},
- };
- };
-
- if (typeof doc.createElementNS === "undefined") {
- doc.createElementNS = (_ns: string, _tag: string) => ({
- style: {},
- setAttribute: () => {},
- getAttribute: () => null,
- appendChild: () => {},
- removeChild: () => {},
- remove: () => {},
- addEventListener: () => {},
- removeEventListener: () => {},
- });
- }
-
- if (typeof doc.getElementsByTagName === "undefined") {
- doc.getElementsByTagName = () => [];
- }
-
- if (typeof gEnv.window === "undefined") {
- gEnv.window = globalThis;
- }
- const win = gEnv.window as Record<string, unknown>;
- if (typeof win.devicePixelRatio === "undefined") {
- win.devicePixelRatio = this.dpr;
- }
- if (typeof win.getComputedStyle === "undefined") {
- win.getComputedStyle = () => ({
- position: "relative",
- overflow: "hidden",
- fontFamily: "Inter, sans-serif",
- });
- }
-
- if (typeof globalThis.requestAnimationFrame === "undefined") {
- globalThis.requestAnimationFrame = (
- callback: (time: number) => void,
- ): number => {
- return setTimeout(
- () => callback(performance.now()),
- 16,
- ) as unknown as number;
- };
- }
- if (typeof globalThis.cancelAnimationFrame === "undefined") {
- globalThis.cancelAnimationFrame = (id: number): void => {
- clearTimeout(id as unknown as NodeJS.Timeout);
- };
- }
-
- const g = globalThis as unknown as {
- GPUShaderStage?: unknown;
- GPUBufferUsage?: unknown;
- GPUTextureUsage?: unknown;
- };
- if (typeof g.GPUShaderStage === "undefined") {
- g.GPUShaderStage = {
- VERTEX: 0x1,
- FRAGMENT: 0x2,
- COMPUTE: 0x4,
- };
- }
- if (typeof g.GPUBufferUsage === "undefined") {
- g.GPUBufferUsage = {
- MAP_READ: 0x0001,
- MAP_WRITE: 0x0002,
- COPY_SRC: 0x0004,
- COPY_DST: 0x0008,
- INDEX: 0x0010,
- VERTEX: 0x0020,
- UNIFORM: 0x0040,
- STORAGE: 0x0080,
- INDIRECT: 0x0100,
- QUERY_RESOLVE: 0x0200,
- };
- }
- if (typeof g.GPUTextureUsage === "undefined") {
- g.GPUTextureUsage = {
- COPY_SRC: 0x01,
- COPY_DST: 0x02,
- TEXTURE_BINDING: 0x04,
- STORAGE_BINDING: 0x08,
- RENDER_ATTACHMENT: 0x10,
- };
- }
-
- const preferredFormat = this.target.format ?? "rgba8unorm";
- const navEnv = globalThis as unknown as {
- navigator?: {
- gpu?: {
- requestAdapter?: () => Promise<{
- requestDevice: () => Promise<GPUDevice>;
- }>;
- getPreferredCanvasFormat?: () => GPUTextureFormat;
- };
- };
- };
- if (typeof navEnv.navigator === "undefined") {
- navEnv.navigator = {
- gpu: {
- requestAdapter: async () => ({
- requestDevice: async () => this.target.device,
- }),
- getPreferredCanvasFormat: () => preferredFormat,
- },
- };
- } else if (!navEnv.navigator.gpu) {
- Object.defineProperty(navEnv.navigator, "gpu", {
- value: {
- requestAdapter: async () => ({
- requestDevice: async () => this.target.device,
- }),
- getPreferredCanvasFormat: () => preferredFormat,
- },
- configurable: true,
- writable: true,
- });
- } else {
- Object.defineProperty(navEnv.navigator.gpu, "getPreferredCanvasFormat", {
- value: () => preferredFormat,
- configurable: true,
- writable: true,
- });
- }
- }
-
- async initialize(chartOptions: ChartGPUOptions): Promise<void> {
- const safeOptions: ChartGPUOptions = {
- ...structuredClone(chartOptions),
- animation: false,
- };
- this.initialOptions = safeOptions;
- this.lastRenderedProgress = null;
- this.setupHeadlessDOM();
-
- activeCanvasMockForNextCreation = this.canvasMock;
-
- const createContext = {
- device: this.target.device,
- adapter:
- (this.target.device as unknown as { adapter?: GPUAdapter }).adapter ??
- ({} as GPUAdapter),
- };
-
- try {
- this.chartInstance = await ChartGPU.create(
- this.containerMock as unknown as HTMLElement,
- safeOptions,
- createContext,
- );
- } finally {
- activeCanvasMockForNextCreation = null;
- }
-
- this.chartInstance.setRenderMode("external");
- }
-
- async renderFrame(
- progress = 1.0,
- destinationTexture?: GPUTexture,
- ): Promise<GPUTexture> {
- if (!this.chartInstance) {
- throw new Error(
- "ChartGPUEngineBridge not initialized. Call initialize() first.",
- );
- }
-
- if (destinationTexture) {
- if (
- this.ownsTexture &&
- this.target.currentTexture !== destinationTexture
- ) {
- try {
- this.target.currentTexture.destroy();
- } catch (_) {}
- this.ownsTexture = false;
- }
- this.target.currentTexture = destinationTexture;
- }
-
- // Update series data / clipping according to timeline reveal progress
- if (this.lastRenderedProgress !== progress) {
- this.lastRenderedProgress = progress;
- if (progress < 1 && this.initialOptions?.series) {
- const updatedSeries = this.initialOptions.series.map(
- (s: NonNullable<ChartGPUOptions["series"]>[number]) => {
- if (!Array.isArray(s.data)) return s;
- const visibleCount = Math.max(
- 2,
- Math.round(s.data.length * progress),
- );
- return {
- ...s,
- data: s.data.slice(0, visibleCount),
- };
- },
- );
- this.chartInstance.setOption({
- ...this.initialOptions,
- animation: false,
- series: updatedSeries,
- });
- } else if (this.initialOptions) {
- this.chartInstance.setOption({
- ...this.initialOptions,
- animation: false,
- });
- }
- }
-
- // Render the frame synchronously; ChartGPU submits to device queue
- this.chartInstance.renderFrame();
-
- // Microtask yield ensures deferred GPU queue encode submission is finalized
- await Promise.resolve();
-
- return this.target.currentTexture;
- }
-
- destroy(): void {
- if (this.chartInstance) {
- this.chartInstance.dispose();
- this.chartInstance = null;
- }
- if (this.ownsTexture && this.target.currentTexture) {
- try {
- this.target.currentTexture.destroy();
- } catch (_) {}
- }
- }
-}
-
-// ==============================================================================================
-// 3. BRIDGE CACHING & DRAW NODE IMPLEMENTATION
-// ==============================================================================================
-
-export const chartBridgeCache = new Map<string, ChartGPUEngineBridge>();
-
-export async function drawChartNode(
- ctx: RenderContextValue,
- pass: GPURenderPassEncoder,
- props: ChartNodeProps,
-): Promise<void> {
- const key = props.nodeId ?? "default_chart";
- const rectW = Math.max(1, Math.round(props.dstRect.width));
- const rectH = Math.max(1, Math.round(props.dstRect.height));
-
- let bridge = chartBridgeCache.get(key);
- if (bridge && (bridge.width !== rectW || bridge.height !== rectH)) {
- bridge.destroy();
- chartBridgeCache.delete(key);
- bridge = undefined;
- }
-
- if (!bridge) {
- bridge = new ChartGPUEngineBridge({
- device: ctx.device,
- width: rectW,
- height: rectH,
- });
- await bridge.initialize(props.chartOptions);
- chartBridgeCache.set(key, bridge);
- }
-
- const progress = props.progress ?? props.drawProgress ?? 1.0;
- const chartTexture = await bridge.renderFrame(progress);
-
- ctx.renderer.drawTexture(pass, chartTexture, props.dstRect, {
- opacity: props.opacity ?? 1,
- transform: props.matrix,
- });
-}
diff --git a/packages/webgpu-renderers/src/nodes/index.ts b/packages/webgpu-renderers/src/nodes/index.ts
index e047def3..f62cb8e9 100644
--- a/packages/webgpu-renderers/src/nodes/index.ts
+++ b/packages/webgpu-renderers/src/nodes/index.ts
@@ -1,6 +1,5 @@
export * from "./audio-signal-extractor.js";
export * from "./caption.js";
-export * from "./chart.js";
export * from "./gif.js";
export * from "./image.js";
export * from "./lottie.js";
diff --git a/packages/webgpu-renderers/src/nodes/types.ts b/packages/webgpu-renderers/src/nodes/types.ts
index e53eb052..87f8ed31 100644
--- a/packages/webgpu-renderers/src/nodes/types.ts
+++ b/packages/webgpu-renderers/src/nodes/types.ts
@@ -1,18 +1,6 @@
import type { SignalData, TextSpan } from "@gitframes/core";
-import type { ChartGPUOptions } from "chartgpu";
import type { Rect } from "../renderer2d/index.js";
-export interface ChartNodeProps {
- nodeId?: string;
- chartOptions: ChartGPUOptions;
- dstRect: Rect;
- progress?: number;
- drawProgress?: number;
- opacity?: number;
- matrix?: DOMMatrix;
- isHeadless?: boolean;
-}
-
export interface VideoNodeProps {
nodeId?: string;
frameKey: string;
diff --git a/packages/webgpu-renderers/src/renderer2d/index.ts b/packages/webgpu-renderers/src/renderer2d/index.ts
index 2028d2c2..b751a3db 100644
--- a/packages/webgpu-renderers/src/renderer2d/index.ts
+++ b/packages/webgpu-renderers/src/renderer2d/index.ts
@@ -192,6 +192,9 @@ export class Renderer2D {
this.pathPipeline.resetPools();
if (this.effectPipeline) this.effectPipeline.resetPools();
this.slugPipeline.resetPools();
+ // The previous frame has been submitted: textures evicted while it was
+ // recorded can go once it completes.
+ textureCache.flushRetired(this.device);
textureCache.prune(this.device);
}
diff --git a/packages/webgpu-renderers/src/renderer3d/text-extruder.ts b/packages/webgpu-renderers/src/renderer3d/text-extruder.ts
index 4a183a42..9d9f0dce 100644
--- a/packages/webgpu-renderers/src/renderer3d/text-extruder.ts
+++ b/packages/webgpu-renderers/src/renderer3d/text-extruder.ts
@@ -198,23 +198,44 @@ function processCurveCubic(
}
}
+type Edge = [string, ...number[]];
+
+/**
+ * The glyph outline with overlaps merged (skia's `simplify`), or null where
+ * skia isn't available, as in the browser.
+ */
+function simplifiedEdges(svg: string): Edge[] | null {
+ try {
+ const edges = new Path2D(svg).simplify().edges as unknown;
+ return Array.isArray(edges) ? (edges as Edge[]) : null;
+ } catch {
+ return null;
+ }
+}
+
+interface GlyphContours {
+ contours: Contour[];
+ /** Overlaps merged, so contours never cross. */
+ simplified: boolean;
+}
+
function extractGlyphContours(
glyph: fontkit.Glyph,
glyphX: number,
glyphY: number,
scale: number,
flattening: CurveFlattening,
-): Contour[] {
+): GlyphContours {
const svg = glyph.path?.toSVG();
- if (!svg) return [];
-
- let edges: [string, ...number[]][];
- try {
- const p2d = new Path2D(svg).simplify();
- edges = p2d.edges as [string, ...number[]][];
- } catch {
- return [];
- }
+ if (!svg) return { contours: [], simplified: true };
+
+ // Without skia, read fontkit's own outline: same verbs, but overlapping
+ // contours (common in variable fonts) stay as they are.
+ let edges = simplifiedEdges(svg);
+ const simplified = edges !== null;
+ edges ??= (glyph.path?.commands ?? []).map(
+ (c) => [c.command, ...c.args] as Edge,
+ );
const contours: Contour[] = [];
let curr: Point2D = { x: 0, y: 0 };
@@ -283,7 +304,7 @@ function extractGlyphContours(
}
}
finishCurrent();
- return contours;
+ return { contours, simplified };
}
/** Side-wall segments meeting at more than this angle (30°) keep a hard edge. */
@@ -300,7 +321,11 @@ interface PolygonHierarchy {
* of "O", or the "R" sitting in the counter of "®"), one inside an odd number
* is a hole of the smallest outline around it.
*/
-function organizeGlyphPolygons(glyphContours: Contour[]): PolygonHierarchy[] {
+function organizeGlyphPolygons({
+ contours: glyphContours,
+ simplified,
+}: GlyphContours): PolygonHierarchy[] {
+ if (!simplified) return organizeByWinding(glyphContours);
const contours = glyphContours.map((contour) => ({
contour,
area: Math.abs(computeContourSignedArea(contour)),
@@ -344,6 +369,48 @@ function organizeGlyphPolygons(glyphContours: Contour[]): PolygonHierarchy[] {
return polygons;
}
+/**
+ * For outlines that may overlap: fonts wind filled contours one way and holes
+ * the other, so the winding of the largest contour marks the outlines; each
+ * hole goes to the smallest outline around it. Overlapping outlines become
+ * separate solids, which look the same once extruded.
+ */
+function organizeByWinding(glyphContours: Contour[]): PolygonHierarchy[] {
+ const contours = glyphContours.map((contour) => {
+ const signed = computeContourSignedArea(contour);
+ return { contour, signed, area: Math.abs(signed) };
+ });
+ if (contours.length === 0) return [];
+ contours.sort((a, b) => b.area - a.area);
+ const filled = Math.sign(contours[0]!.signed);
+ const polygons: PolygonHierarchy[] = [];
+ for (const c of contours) {
+ if (Math.sign(c.signed) === filled)
+ polygons.push({ outer: c.contour, holes: [] });
+ }
+ for (const c of contours) {
+ if (Math.sign(c.signed) === filled) continue;
+ const probe = c.contour[0]!;
+ const mid = c.contour[Math.floor(c.contour.length / 2)]!;
+ let home: PolygonHierarchy | undefined;
+ let homeArea = Number.POSITIVE_INFINITY;
+ for (const poly of polygons) {
+ const area = Math.abs(computeContourSignedArea(poly.outer));
+ if (
+ area > c.area &&
+ area < homeArea &&
+ (isPointInsidePolygon(probe, poly.outer) ||
+ isPointInsidePolygon(mid, poly.outer))
+ ) {
+ home = poly;
+ homeArea = area;
+ }
+ }
+ home?.holes.push(c.contour);
+ }
+ return polygons;
+}
+
/**
* A glyph's outlines are flattened and sorted into outlines and holes once per
* font, size and flattening, at the glyph origin; each use gets a translated
diff --git a/packages/webgpu-renderers/src/texture-cache.ts b/packages/webgpu-renderers/src/texture-cache.ts
index b12f7bfe..ddd531d2 100644
--- a/packages/webgpu-renderers/src/texture-cache.ts
+++ b/packages/webgpu-renderers/src/texture-cache.ts
@@ -3,6 +3,13 @@ export class TextureCache {
private refs = new Map<string, number>();
private lruMap = new Map<string, true>(); // insertion order = recency order
public activeKeys = new Set<string>();
+ /**
+ * Evicted textures wait here until the frame being recorded has been
+ * submitted: a command encoder may already reference them, and a frame's
+ * recording can span awaits (decodes, inference) during which they are
+ * evicted. `flushRetired` hands them to the GPU queue for destruction.
+ */
+ private retired: GPUTexture[] = [];
acquire(key: string): GPUTexture | undefined {
const tex = this.textures.get(key);
@@ -71,21 +78,7 @@ export class TextureCache {
evict(key: string, device?: GPUDevice): void {
const tex = this.textures.get(key);
if (tex) {
- try {
- if (device) {
- const toDestroy = tex;
- device.queue
- .onSubmittedWorkDone()
- .then(() => {
- try {
- toDestroy.destroy();
- } catch (_) {}
- })
- .catch(() => {});
- } else {
- tex.destroy();
- }
- } catch (_) {}
+ this.retire(tex, device);
this.textures.delete(key);
}
this.refs.delete(key);
@@ -102,32 +95,17 @@ export class TextureCache {
}
}
- // Evict least recently used inactive textures until inactiveCount <= maxInactive
- const lruKeys = Array.from(this.lruMap.keys());
- for (let i = lruKeys.length - 1; i >= 0; i--) {
+ // Evict least recently used inactive textures (oldest first in the LRU
+ // map) until inactiveCount <= maxInactive.
+ for (const key of Array.from(this.lruMap.keys())) {
if (inactiveCount <= maxInactive) {
break;
}
- const key = lruKeys[i];
const count = this.refs.get(key) ?? 0;
if (count === 0 && !this.activeKeys.has(key)) {
const tex = this.textures.get(key);
if (tex) {
- try {
- if (device) {
- const toDestroy = tex;
- device.queue
- .onSubmittedWorkDone()
- .then(() => {
- try {
- toDestroy.destroy();
- } catch (_) {}
- })
- .catch(() => {});
- } else {
- tex.destroy();
- }
- } catch (_) {}
+ this.retire(tex, device);
this.textures.delete(key);
}
this.refs.delete(key);
@@ -137,12 +115,48 @@ export class TextureCache {
}
}
+ private retire(tex: GPUTexture, device?: GPUDevice): void {
+ if (!device) {
+ try {
+ tex.destroy();
+ } catch (_) {}
+ return;
+ }
+ this.retired.push(tex);
+ }
+
+ /**
+ * Destroys textures retired before the last submit, once the GPU is done
+ * with that work. Call at the start of a frame, after the previous one was
+ * submitted (`Renderer2D.resetPools` does).
+ */
+ flushRetired(device: GPUDevice): void {
+ if (this.retired.length === 0) return;
+ const batch = this.retired;
+ this.retired = [];
+ device.queue
+ .onSubmittedWorkDone()
+ .then(() => {
+ for (const tex of batch) {
+ try {
+ tex.destroy();
+ } catch (_) {}
+ }
+ })
+ .catch(() => {});
+ }
+
private updateLru(key: string): void {
this.lruMap.delete(key);
this.lruMap.set(key, true);
}
destroy(): void {
+ for (const tex of this.retired.splice(0)) {
+ try {
+ tex.destroy();
+ } catch (_) {}
+ }
for (const [_, tex] of this.textures) {
try {
tex.destroy();
diff --git a/plugins/gitframes/skills/gitframes-compose/SKILL.md b/plugins/gitframes/skills/gitframes-compose/SKILL.md
index 36c78e6a..75f77203 100644
--- a/plugins/gitframes/skills/gitframes-compose/SKILL.md
+++ b/plugins/gitframes/skills/gitframes-compose/SKILL.md
@@ -94,7 +94,7 @@ All `Layer.*` builders return `AnimatableNode<T>` instances with chainable `.ani
| `Layer.audio(src, options)` | `"media"` | Audio track layer. Options: `volume`, `startFrame`, `durationFrames`. |
| `Layer.shape(type, options)` | `"shape"` | Parametric vector graphics (`"rect"`, `"circle"`, `"ellipse"`, `"polygon"`, `"star"`, `"arrow"`, `"path"`). Options: `d` (SVG path data with arcs), `strokeWidth`, `strokeColor`, `trimStart`, `trimEnd`. |
| `Layer.caption(src, options)` | `"media"` | SRT-driven synchronized subtitle engine. Bottom-anchored auto-wrapping cues. |
-| `Layer.chart(options)` | `"chart"` | Headless ChartGPU integration. Line, area, candlestick, 3D point cloud, with `drawProgress` animations. |
+| `Layer.chart(options, props)` | `"box"` | Charts built from native nodes (d3 scales and geometry). `type`: `"line" \| "area" \| "bar" \| "scatter" \| "candlestick" \| "pie" \| "donut"`. Options: `width`, `height`, `series: [{ name, data, color, type, curve, pointRadius }]` or `data`, `categories`, `stacked`, `xAxis`/`yAxis` (`min`, `max`, `ticks`, `grid`, `format`: a d3-format string like `"$,.0f"`), `legend`, `valueLabels`, `fontFamily`, `fontSize`, `colors`, `animate: { start, duration, stagger, ease } \| false`. `props` positions the chart box. Children get ids `<id>-bar-<series>-<i>`, `<id>-line-<series>`, `<id>-slice-<i>`. Keep scatter charts to a few hundred points: each point is a node. |
| `Layer.camera(options)` | `"camera"` | 3D scene camera with FOV, lens rack focus, and orbital coordinates. |
| `Layer.light(options)` | `"light"` | 3D lighting primitive (`ambient`, `directional`, `point`, `spot`). |
| `Layer.model(options)` | `"model3d"` | 3D mesh loader (`.gltf`, `.glb`, `.obj`, `.fbx`, `.stl`, `.ply`). Supports skinning and audio deformation compute shaders. |
diff --git a/plugins/gitframes/skills/gitframes-render/SKILL.md b/plugins/gitframes/skills/gitframes-render/SKILL.md
index faf7d31b..5cc4e496 100644
--- a/plugins/gitframes/skills/gitframes-render/SKILL.md
+++ b/plugins/gitframes/skills/gitframes-render/SKILL.md
@@ -111,6 +111,28 @@ describe("Hero Scene Conformance", () => {
---
+### Step 4.5: Show the User Before Exporting (`preview`)
+When a person is in the loop, let them watch the composition before you spend time on the final render. `startPreview` serves a localhost player with the soundtrack, a timeline with the waveform, and frame stepping. The page loads the composition's own code and renders it with WebGPU in the browser, so playback runs at or near full frame rate; the server only serves that code, the project's files, and the soundtrack mixed by the export engine. Point it at the module that builds the composition:
+
+```typescript
+import { startPreview } from "gitframes";
+
+const session = await startPreview(
+ { entry: new URL("./film.ts", import.meta.url), export: "buildFilm" },
+ { title: "Launch film" },
+);
+console.log(`Preview at ${session.url}`);
+await session.closed; // keep the process alive while the user watches
+```
+
+- **The export is a function returning the `Composition`** (it may be async), or a `Composition` itself. The browser calls it, so build-time Node code in it must stay simple: `node:path`, `fileURLToPath(import.meta.url)` and synchronous `fs` reads (JSON, text) work through shims; writes are skipped. Assets referenced by absolute path load from the server, limited to the repository that holds the entry (`root` overrides it).
+- **Run it in the background.** The preview serves until it is stopped. Start the script as a background command with the longest timeout your harness allows, tell the user the URL, and ask for feedback in the chat. Feedback comes from the user, not from the page.
+- **One tab for the whole loop.** The port is fixed per project directory. Running the preview again (after you've made changes) takes over from the one already running, and a tab left open reconnects and reloads into the new version by itself. Don't ask the user to reopen anything. When the user closes the tab, the preview stops by itself about 5 s later (a reload doesn't stop it). If the preview was stopped (tab closed, time limit, or you killed it), just start it again.
+- The browser opens automatically (`open: false`, or `CI`, skips that) unless an open tab reconnects first. It needs WebGPU (current Chrome, Edge or Safari).
+- Audio is the same mix `renderVideo` muxes (`audio: false` skips it). Playback uses the soundtrack as its clock; when a frame takes long (a video seek, a heavy shot), the clock and the sound hold until the picture catches up.
+
+---
+
### Step 5: Full Video Export (`renderVideo`)
Once static frames and motion grids are verified, encode the final MP4/WebM video:
@@ -141,12 +163,20 @@ Production projects structure their `src/render.ts` to support both quick frame
// src/render.ts
import fs from "node:fs/promises";
import path from "node:path";
-import { HeadlessMediaRenderer } from "gitframes";
+import { HeadlessMediaRenderer, startPreview } from "gitframes";
import { buildFilm } from "./film.js";
const OUT = path.resolve(import.meta.dirname, "../output");
const [mode = "video", ...args] = process.argv.slice(2);
+if (mode === "preview") {
+ // The browser runs film.ts itself; no need to build the film here.
+ const session = await startPreview({ entry: new URL("./film.ts", import.meta.url), export: "buildFilm" });
+ console.log(`Preview at ${session.url}`);
+ await session.closed; // serves until its tab closes or the next preview replaces it
+ process.exit(0);
+}
+
const comp = await buildFilm();
await fs.mkdir(OUT, { recursive: true });
@@ -178,6 +208,9 @@ CLI Usage:
# Render specific keyframes for instant review:
tsx src/render.ts frames 0 18 36 72
+# Live player for the user (run in the background; re-run after changes and the open tab reloads):
+tsx src/render.ts preview
+
# Render full master video:
tsx src/render.ts
```
diff --git a/plugins/gitframes/skills/gitframes/SKILL.md b/plugins/gitframes/skills/gitframes/SKILL.md
index a543494a..a1bd75e9 100644
--- a/plugins/gitframes/skills/gitframes/SKILL.md
+++ b/plugins/gitframes/skills/gitframes/SKILL.md
@@ -42,11 +42,12 @@ For a new project, create `package.json` with all three blocks. In an existing p
"sharp": false,
"webgpu": false,
"onnxruntime-node": false,
- "node-av": false
+ "node-av": false,
+ "esbuild": false
},
"pnpm": {
"onlyBuiltDependencies": ["skia-canvas"],
- "ignoredBuiltDependencies": ["sharp", "webgpu", "onnxruntime-node", "node-av"]
+ "ignoredBuiltDependencies": ["sharp", "webgpu", "onnxruntime-node", "node-av", "esbuild"]
},
"trustedDependencies": ["skia-canvas"]
}
@@ -71,7 +72,8 @@ A minimal `tsconfig.json`:
"target": "ES2022",
"strict": true,
"skipLibCheck": true,
- "noEmit": true
+ "noEmit": true,
+ "types": ["node"]
},
"include": ["src/**/*"]
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c71be149..71634ea7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -131,6 +131,15 @@ overrides:
nanoid@>=4.0.0 <5.1.16: '>=5.1.16'
nanoid@<3.3.16: '>=3.3.16'
nanoid@<3.3.17: '>=3.3.17'
+ undici@>=7.0.0 <7.29.1: '>=7.29.1 <8.0.0'
+ js-yaml@<3.15.2: ^3.15.2
+ js-yaml@>=4.0.0 <4.3.2: ^4.3.2
+ smol-toml@<1.7.1: ^1.7.1
+ hono@<4.13.7: '>=4.13.7'
+ fflate@<0.8.3: ^0.8.3
+ sharp@<0.35.4: ^0.35.4
+ vitest@<4.1.11: ^4.1.11
+ '@vitest/mocker@<4.1.11': ^4.1.11
importers:
@@ -186,13 +195,13 @@ importers:
version: link:../../packages/server-utils
'@hono/node-server':
specifier: '>=2.0.5'
- version: 2.0.12([email protected])
+ version: 2.0.12([email protected])
dotenv:
specifier: ^17.0.1
version: 17.3.1
hono:
- specifier: '>=4.12.34'
- version: 4.13.1
+ specifier: ^4.13.7
+ version: 4.13.13
inversify:
specifier: ^7.11.0
version: 7.11.0([email protected])
@@ -216,8 +225,8 @@ importers:
specifier: ^5.8.3
version: 5.9.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
examples/19_gitframes_film:
dependencies:
@@ -241,8 +250,8 @@ importers:
specifier: ^5.8.3
version: 5.9.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
examples/21_full_circle:
dependencies:
@@ -266,8 +275,8 @@ importers:
specifier: ^5.8.3
version: 5.9.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
examples/22_gitframes_launch:
dependencies:
@@ -288,8 +297,36 @@ importers:
specifier: ^5.8.3
version: 5.9.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
+
+ examples/23_data_story:
+ dependencies:
+ gitframes:
+ specifier: workspace:*
+ version: link:../../packages/gitframes
+ gsap:
+ specifier: ^3.15.0
+ version: 3.15.0
+ devDependencies:
+ '@gitframes/tsconfig':
+ specifier: workspace:*
+ version: link:../../packages/tsconfig
+ '@types/node':
+ specifier: ^24.1.0
+ version: 24.10.14
+ skia-canvas:
+ specifier: ^3.0.8
+ version: 3.0.8
+ tsx:
+ specifier: ^4.20.3
+ version: 4.21.0
+ typescript:
+ specifier: ^5.8.3
+ version: 5.9.3
+ vitest:
+ specifier: ^4.1.11
nodes/node-apply-lut:
dependencies:
@@ -350,8 +387,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
nodes/node-audio-delay:
dependencies:
@@ -381,8 +418,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
nodes/node-audio-fade:
dependencies:
@@ -412,8 +449,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
nodes/node-audio-noise-gate:
dependencies:
@@ -443,8 +480,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
nodes/node-audio-parametric-eq:
dependencies:
@@ -474,8 +511,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
nodes/node-audio-reverb:
dependencies:
@@ -505,8 +542,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
nodes/node-audio-signal-extractor:
dependencies:
@@ -536,8 +573,8 @@ importers:
specifier: ^5.8.3
version: 5.9.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -701,8 +738,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -732,8 +769,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -766,8 +803,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -826,9 +863,6 @@ importers:
'@gitframes/webgpu-renderers':
specifier: workspace:*
version: link:../../packages/webgpu-renderers
- chartgpu:
- specifier: ^0.4.0
- version: 0.4.0
gsap:
specifier: ^3.15.0
version: 3.15.0
@@ -849,8 +883,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -1138,8 +1172,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -1256,8 +1290,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^3.1.1
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -1340,8 +1374,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
nodes/node-mask-math:
dependencies:
@@ -1371,8 +1405,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -1579,8 +1613,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -1700,8 +1734,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -1734,8 +1768,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -1768,8 +1802,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -1821,8 +1855,8 @@ importers:
specifier: ^5.8.3
version: 5.9.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -1852,8 +1886,8 @@ importers:
specifier: ^5.8.3
version: 5.9.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
nodes/node-stereo-panning:
dependencies:
@@ -1883,8 +1917,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
nodes/node-svg:
dependencies:
@@ -1908,8 +1942,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
nodes/node-text:
dependencies:
@@ -1961,8 +1995,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -2128,8 +2162,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
webgpu:
specifier: ^0.4.0
version: 0.4.0
@@ -2156,8 +2190,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
packages/gitframes:
dependencies:
@@ -2176,15 +2210,24 @@ importers:
'@resvg/resvg-js':
specifier: ^2.6.2
version: 2.6.2
- chartgpu:
- specifier: ^0.4.0
- version: 0.4.0
+ d3-format:
+ specifier: ^3.1.2
+ version: 3.1.2
+ d3-scale:
+ specifier: ^4.0.2
+ version: 4.0.2
+ d3-shape:
+ specifier: ^3.2.0
+ version: 3.2.0
dotenv:
specifier: ^16.4.5
version: 16.6.1
earcut:
specifier: ^3.2.4
version: 3.2.4
+ esbuild:
+ specifier: ^0.28.1
+ version: 0.28.1
fontkit:
specifier: ^2.0.4
version: 2.0.4
@@ -2207,8 +2250,8 @@ importers:
specifier: ^10.3.1
version: 10.3.1
sharp:
- specifier: '>=0.35.0'
- version: 0.35.3(@types/[email protected])
+ specifier: ^0.35.4
+ version: 0.35.5(@types/[email protected])
skia-canvas:
specifier: ^3.0.8
version: 3.0.8
@@ -2222,6 +2265,9 @@ importers:
specifier: ^4.3.6
version: 4.3.6
devDependencies:
+ '@gitframes/client-utils':
+ specifier: workspace:*
+ version: link:../client-utils
'@gitframes/compositions':
specifier: workspace:*
version: link:../compositions
@@ -2327,6 +2373,9 @@ importers:
'@gitframes/node-relight-3d':
specifier: workspace:*
version: link:../../nodes/node-relight-3d
+ '@gitframes/node-sdk':
+ specifier: workspace:*
+ version: link:../node-sdk
'@gitframes/node-selective-color':
specifier: workspace:*
version: link:../../nodes/node-selective-color
@@ -2375,6 +2424,15 @@ importers:
'@gitframes/webgpu-renderers':
specifier: workspace:*
version: link:../webgpu-renderers
+ '@types/d3-format':
+ specifier: ^3.0.4
+ version: 3.0.4
+ '@types/d3-scale':
+ specifier: ^4.0.9
+ version: 4.0.9
+ '@types/d3-shape':
+ specifier: ^3.2.0
+ version: 3.2.0
'@types/fontkit':
specifier: ^2.0.9
version: 2.0.9
@@ -2388,8 +2446,8 @@ importers:
specifier: ^5.8.3
version: 5.9.3
vitest:
- specifier: 4.1.5
+ specifier: ^4.1.11
packages/media:
dependencies:
@@ -2400,8 +2458,8 @@ importers:
specifier: workspace:*
version: link:../server-utils
fflate:
- specifier: ^0.8.2
- version: 0.8.2
+ specifier: ^0.8.3
+ version: 0.8.3
file-type:
specifier: '>=21.3.2'
version: 22.0.1
@@ -2409,8 +2467,8 @@ importers:
specifier: '*'
version: 7.11.0([email protected])
sharp:
- specifier: '>=0.35.0'
- version: 0.35.3(@types/[email protected])
+ specifier: ^0.35.4
+ version: 0.35.5(@types/[email protected])
devDependencies:
'@gitframes/tsconfig':
specifier: workspace:*
@@ -2428,11 +2486,11 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
vitest-mock-extended:
specifier: ^4.0.0
packages/node-sdk:
dependencies:
@@ -2651,8 +2709,8 @@ importers:
specifier: ^1.51.0
version: 1.51.0
sharp:
- specifier: '>=0.35.0'
- version: 0.35.3(@types/[email protected])
+ specifier: ^0.35.4
+ version: 0.35.5(@types/[email protected])
skia-canvas:
specifier: ^3.0.8
version: 3.0.8
@@ -2676,8 +2734,8 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: 4.1.5
+ specifier: ^4.1.11
packages/renderers:
dependencies:
@@ -2763,8 +2821,8 @@ importers:
specifier: ^5.8.3
version: 5.9.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
packages/tsconfig: {}
@@ -2805,8 +2863,8 @@ importers:
specifier: ^5.8.3
version: 5.9.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
packages/webgpu-renderers:
dependencies:
@@ -2822,9 +2880,6 @@ importers:
'@resvg/resvg-js':
specifier: ^2.6.2
version: 2.6.2
- chartgpu:
- specifier: ^0.4.0
- version: 0.4.0
earcut:
specifier: ^3.2.4
version: 3.2.4
@@ -2838,8 +2893,8 @@ importers:
specifier: ^1.51.0
version: 1.51.0
sharp:
- specifier: '>=0.35.0'
- version: 0.35.3(@types/[email protected])
+ specifier: ^0.35.4
+ version: 0.35.5(@types/[email protected])
skia-canvas:
specifier: ^3.0.8
version: 3.0.8
@@ -2857,8 +2912,8 @@ importers:
specifier: ^2.0.9
version: 2.0.9
'@vitest/coverage-v8':
- specifier: ^4.1.5
- version: 4.1.5([email protected])
+ specifier: ^4.1.11
+ version: 4.1.11([email protected])
tsdown:
specifier: ^0.19.0
@@ -2866,11 +2921,11 @@ importers:
specifier: ^5.8.3
version: 5.8.3
vitest:
- specifier: ^4.1.5
+ specifier: ^4.1.11
vitest-mock-extended:
specifier: ^4.0.0
packages:
@@ -3414,166 +3469,166 @@ packages:
resolution: {integrity: sha512-eWpQYr67tqJLeaSUl0Q+TquuYfUdTibpOJlUMV2FfUP7+KqCC5TufnwnlXL6mobZBJbGAYRd7ZvEBDCbLInjhg==}
engines: {node: '>=20'}
peerDependencies:
- hono: '>=4.12.34'
+ hono: '>=4.13.7'
resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg==}
+ resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [darwin]
- resolution: {integrity: sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w==}
+ resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [darwin]
- resolution: {integrity: sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg==}
+ resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==}
engines: {node: '>=20.9.0'}
os: [freebsd]
- resolution: {integrity: sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg==}
+ resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==}
cpu: [arm64]
os: [darwin]
- resolution: {integrity: sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw==}
+ resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==}
cpu: [x64]
os: [darwin]
- resolution: {integrity: sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA==}
+ resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==}
cpu: [arm64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ==}
+ resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==}
cpu: [arm]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw==}
+ resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w==}
+ resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ==}
+ resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==}
cpu: [s390x]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w==}
+ resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==}
cpu: [x64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw==}
+ resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==}
cpu: [arm64]
os: [linux]
libc: [musl]
- resolution: {integrity: sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ==}
+ resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==}
cpu: [x64]
os: [linux]
libc: [musl]
- resolution: {integrity: sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ==}
+ resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA==}
+ resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==}
engines: {node: '>=20.9.0'}
cpu: [arm]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA==}
+ resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==}
engines: {node: '>=20.9.0'}
cpu: [ppc64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ==}
+ resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==}
engines: {node: '>=20.9.0'}
cpu: [riscv64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw==}
+ resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==}
engines: {node: '>=20.9.0'}
cpu: [s390x]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA==}
+ resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w==}
+ resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
- resolution: {integrity: sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg==}
+ resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [linux]
libc: [musl]
- resolution: {integrity: sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w==}
+ resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==}
engines: {node: '>=20.9.0'}
- resolution: {integrity: sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q==}
+ resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==}
engines: {node: '>=20.9.0'}
cpu: [wasm32]
- resolution: {integrity: sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w==}
+ resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [win32]
- resolution: {integrity: sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw==}
+ resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==}
engines: {node: ^20.9.0}
cpu: [ia32]
os: [win32]
- resolution: {integrity: sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA==}
+ resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [win32]
@@ -4769,8 +4824,20 @@ packages:
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
- '@types/[email protected]':
- resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==}
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
@@ -4790,43 +4857,26 @@ packages:
resolution: {integrity: sha512-qNYerFky3muCmZPq+R+B3cUDRA5OONw/oh6aGGFxx2LOBz6yu8eamKusrhkHnC6rc2fm76+G9z9QoWSB2SaQaw==}
- '@types/[email protected]':
- resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}
-
resolution: {integrity: sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ==}
resolution: {integrity: sha512-OowOUbD1lBCOFIPOZ8xnMIhgqA4sCutMiYOmPHL1PTLt5+y1XA+g2+yC9OOyz8p+deMZqPZLxfMjYIfrKsPeFg==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-38C0/Ddb7HcRG0Z4/DUem8x57d2p9jYgp18mkaYswEOQBGsI1CG4f/hjm0ZCeaJfWhSZ4k7jgs29V1Zom7Ki9A==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw==}
peerDependencies:
- '@vitest/browser': 4.1.5
- vitest: 4.1.5
+ '@vitest/browser': 4.1.11
+ vitest: 4.1.11
peerDependenciesMeta:
'@vitest/browser':
optional: true
- '@vitest/[email protected]':
- resolution: {integrity: sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-PWBaRY5JoKuRnHlUHfpV/KohFylaDZTupcXN1H9vYryNLOnitSw60Mw9IAE2r67NbwwzBw/Cc/8q9BK3kIX8Kw==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==}
- peerDependencies:
- msw: ^2.4.9
- vite: '>=7.3.5'
- peerDependenciesMeta:
- msw:
- optional: true
- vite:
- optional: true
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-/x2EmFC4mT4NNzqvC3fmesuV97w5FC903KPmey4gsnJiMQ3Be1IlDKVaDaG8iqaLFHqJ2FVEkxZk5VmeLjIItw==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==}
peerDependencies:
msw: ^2.4.9
vite: '>=7.3.5'
@@ -4847,38 +4897,23 @@ packages:
vite:
optional: true
- '@vitest/[email protected]':
- resolution: {integrity: sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-7I3q6l5qr03dVfMX2wCo9FxwSJbPdwKjy2uu/YPpU3wfHvIL4QHwVRp57OfGrDFeUJ8/8QdfBKIV12FTtLn00g==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-2D+o7Pr82IEO46YPpoA/YU0neeyr6FTerQb5Ro7BUnBuv6NQtT/kmVnczngiMEBhzgqz2UZYl5gArejsyERDSQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-zypXEt4KH/XgKGPUz4eC2AvErYx0My5hfL8oDb1HzGFpEk1P62bxSohdyOmvz+d9UJwanI68MKwr2EquOaOgMQ==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-2lNOsh6+R2Idnf1TCZqSwYlKN2E/iDlD8sgU59kYVl+OMDmvldO1VDk39smRfpUNwYpNRVn3w4YfuC7KfbBnkQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==}
'@vitest/[email protected]':
resolution: {integrity: sha512-rbto/mF/SGERxEgYOek7Xm6B9b+y+mVoo+f4b2LymYO8zM1b7uB5nHuhVMTP2hxdzgxvGiZYGxGIaMvL5y180Q==}
- '@vitest/[email protected]':
- resolution: {integrity: sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==}
-
- '@vitest/[email protected]':
- resolution: {integrity: sha512-76wdkrmfXfqGjueGgnb45ITPyUi1ycZ4IHgC2bhPDUfWHklY/q3MdLOAB+TF1e6xfl8NxNY0ZYaPCFNWSsw3Ug==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==}
'@webgpu/[email protected]':
resolution: {integrity: sha512-LFiNHHKMvmAEvwVew3JLJmTdShhbdwRFSImUshGhE2mGE8ybQzIo63l5uRp+YKnNx+8Qno8Kf6gN+DKMreIJCA==}
@@ -4993,10 +5028,6 @@ packages:
resolution: {integrity: sha512-PzE5nJZPz72YUAfo8oTp0u3fqqY7IzlTubneAihqDYAUcBk7ryeCmBbdJBEdaH0bptSOe2VT2Zwcb3UaFyaSWw==}
engines: {node: ^18.12.0 || >= 20.9.0}
- resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
engines: {node: '>=18'}
@@ -5004,13 +5035,6 @@ packages:
resolution: {integrity: sha512-PsezH1rqdV9VvyNhxxOW32/d75r01NY7TQCmOqomRo15ZSOKbpTFVsfjghxo6JloQUCGnH4k1LGu0R4yCLlWQQ==}
- resolution: {integrity: sha512-NuqaXxT96u9VMYzluLAxyPY2EPTLs7IO9No9/uXplxUludx+u7A3ZGvgVEGsct/IxeyjkDqgnJmNtJmaqtlTKw==}
-
- resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}
- engines: {node: '>= 16'}
-
resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==}
@@ -5039,6 +5063,42 @@ packages:
resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}
engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}
+ resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==}
engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
@@ -5072,10 +5132,6 @@ packages:
resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}
- engines: {node: '>=6'}
-
resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==}
engines: {node: '>=4.0.0'}
@@ -5156,9 +5212,6 @@ packages:
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
-
resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==}
@@ -5183,10 +5236,6 @@ packages:
resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}
- engines: {node: '>=12.0.0'}
-
resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
engines: {node: '>=12.0.0'}
@@ -5223,8 +5272,8 @@ packages:
picomatch:
optional: true
- resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==}
+ resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}
resolution: {integrity: sha512-ww5Mhre0EE+jmBvOXTmXAbEMuZE7uX4a3+oRCQFNj8w++g3ev913N6tXQz0XTXbueQ5TWQfm6BdaViEHHn8bhA==}
@@ -5326,8 +5375,8 @@ packages:
resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==}
- resolution: {integrity: sha512-kdJoFVv2xmayw6cY09H7AbMJMt8Jn5jdlEdXsP7AGBdF2DIptVlKlOLKXP41yPip4/a3yQPv9gVcJYI8YY04dw==}
+ resolution: {integrity: sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==}
engines: {node: '>=16.9.0'}
@@ -5372,6 +5421,10 @@ packages:
resolution: {integrity: sha512-94smTCQOvigN4d/2R/YDjz8YVG0Sufvv2aAh8P5m42gwhCsDAJqnbNOrxJsrADuAFAA69Q/ptGzxvNcNuIJcvw==}
+ resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-yZDprSSr8TyVeMGI/AOV4ws6gwjX22hj9Z8/oHAVpJORY6WRFTcUzhnZtibBUHEw2U8ArvHcR+i863DplQ3Cwg==}
@@ -5443,15 +5496,12 @@ packages:
resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}
- resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==}
-
- resolution: {integrity: sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==}
+ resolution: {integrity: sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==}
hasBin: true
- resolution: {integrity: sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==}
+ resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==}
hasBin: true
@@ -5620,9 +5670,6 @@ packages:
resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==}
- resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==}
-
resolution: {integrity: sha512-NxVFwLAnrd9i7KUBxC4DrUhmgjzOs+1Qm50D3oF1/oL+r1NpZ4gA7xvG0/zJ8evR7zIKn4vLf7qTNduWFtCrRw==}
engines: {node: 20 || >=22}
@@ -5712,9 +5759,6 @@ packages:
resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==}
-
resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==}
engines: {node: '>=12.20.0'}
@@ -5801,10 +5845,6 @@ packages:
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
- resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}
- engines: {node: '>= 14.16'}
-
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -5995,8 +6035,8 @@ packages:
resolution: {integrity: sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q==}
+ resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==}
engines: {node: '>=20.9.0'}
peerDependencies:
'@types/node': '*'
@@ -6032,8 +6072,8 @@ packages:
resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-dWUG8F5sIIARXih1DTaQAX4SsiTXhInKf1buxdY9DIg4ZYPZK5nGM1VRIYmEbDbsHt7USo99xSLFu5Q1IqTmsg==}
+ resolution: {integrity: sha512-hpd+HLON7HdZXqYchMM/+LaTTbdK0AU3NngIJ4KVyWbY9bfQqdL9cD+4yf6dUoU2Ap4VsU0JkQi6FxAI1B2mXQ==}
engines: {node: '>= 18'}
@@ -6063,12 +6103,6 @@ packages:
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
- resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
-
- resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==}
-
resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==}
@@ -6097,9 +6131,6 @@ packages:
resolution: {integrity: sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==}
engines: {node: '>=14.16'}
- resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==}
-
resolution: {integrity: sha512-M9eUSMT2dCB2cTNPG7UYj6KuK7RJR2SN2+yCV/fTW3xzTCS6EaGZ5pSMgDIjB7r8zSfTGk+dvvn9rTjpVS9Mwg==}
@@ -6147,9 +6178,6 @@ packages:
resolution: {integrity: sha512-9APumHG7r4yOk4X4WlkmE71aZcv1gvin1czO3OQ1U9iJcFA5Ja/ygyb0vPOVHTthFozUYs8CLoLUlM8grb2lTQ==}
engines: {node: '>=20.0.0'}
- resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
-
resolution: {integrity: sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==}
engines: {node: '>=18'}
@@ -6158,22 +6186,10 @@ packages:
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
engines: {node: '>=12.0.0'}
- resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}
- engines: {node: ^18.0.0 || >=20.0.0}
-
- resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==}
- engines: {node: '>=14.0.0'}
-
resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}
engines: {node: '>=14.0.0'}
- resolution: {integrity: sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==}
- engines: {node: '>=14.0.0'}
-
resolution: {integrity: sha512-W99NuU7b1DcG3uJ3v9k9VztCH3WialNbBkBft5wCs8V8mexu0XQqaZEYb9l9RNNzK8+3EJ9PKWB0/RUtTQ/o+Q==}
@@ -6290,8 +6306,8 @@ packages:
resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==}
- resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==}
+ resolution: {integrity: sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==}
engines: {node: '>=20.18.1'}
@@ -6324,11 +6340,6 @@ packages:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
- resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==}
- engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
- hasBin: true
-
resolution: {integrity: sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -6376,50 +6387,22 @@ packages:
resolution: {integrity: sha512-m2FmH8JYfxzZoLsHuhXRY+Pv++a3zd91HYpSz81tpRLEHbtFkEL2QcWvJowucWuNTirzQURKfWbJJSXbYqkTsA==}
peerDependencies:
typescript: 3.x || 4.x || 5.x || 6.x
- vitest: '>=4.1.0'
-
- resolution: {integrity: sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==}
- engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
- hasBin: true
- peerDependencies:
- '@edge-runtime/vm': '*'
- '@types/debug': ^4.1.12
- '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0
- '@vitest/browser': 3.2.7
- '@vitest/ui': 3.2.7
- happy-dom: '*'
- jsdom: '*'
- peerDependenciesMeta:
- '@edge-runtime/vm':
- optional: true
- '@types/debug':
- optional: true
- '@types/node':
- optional: true
- '@vitest/browser':
- optional: true
- '@vitest/ui':
- optional: true
- happy-dom:
- optional: true
- jsdom:
- optional: true
+ vitest: ^4.1.11
- resolution: {integrity: sha512-9Xx1v3/ih3m9hN+SbfkUyy0JAs72ap3r7joc87XL6jwF0jGg6mFBvQ1SrwaX+h8BlkX6Hz9shdd1uo6AF+ZGpg==}
+ resolution: {integrity: sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==}
engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}
hasBin: true
peerDependencies:
'@edge-runtime/vm': '*'
'@opentelemetry/api': ^1.9.0
'@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0
- '@vitest/browser-playwright': 4.1.5
- '@vitest/browser-preview': 4.1.5
- '@vitest/browser-webdriverio': 4.1.5
- '@vitest/coverage-istanbul': 4.1.5
- '@vitest/coverage-v8': 4.1.5
- '@vitest/ui': 4.1.5
+ '@vitest/browser-playwright': 4.1.11
+ '@vitest/browser-preview': 4.1.11
+ '@vitest/browser-webdriverio': 4.1.11
+ '@vitest/coverage-istanbul': 4.1.11
+ '@vitest/coverage-v8': 4.1.11
+ '@vitest/ui': 4.1.11
happy-dom: '*'
jsdom: '*'
vite: '>=7.3.5'
@@ -7210,7 +7193,7 @@ snapshots:
'@changesets/[email protected]':
dependencies:
'@changesets/types': 6.1.0
- js-yaml: 4.3.1
+ js-yaml: 4.3.2
'@changesets/[email protected]':
dependencies:
@@ -7376,114 +7359,114 @@ snapshots:
tweetnacl: 1.0.3
optional: true
dependencies:
- hono: 4.13.1
+ hono: 4.13.13
'@img/[email protected]': {}
optionalDependencies:
- '@img/sharp-libvips-darwin-arm64': 1.3.2
+ '@img/sharp-libvips-darwin-arm64': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-darwin-x64': 1.3.2
+ '@img/sharp-libvips-darwin-x64': 1.3.4
optional: true
dependencies:
- '@img/sharp-wasm32': 0.35.3
+ '@img/sharp-wasm32': 0.35.5
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optionalDependencies:
- '@img/sharp-libvips-linux-arm64': 1.3.2
+ '@img/sharp-libvips-linux-arm64': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linux-arm': 1.3.2
+ '@img/sharp-libvips-linux-arm': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linux-ppc64': 1.3.2
+ '@img/sharp-libvips-linux-ppc64': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linux-riscv64': 1.3.2
+ '@img/sharp-libvips-linux-riscv64': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linux-s390x': 1.3.2
+ '@img/sharp-libvips-linux-s390x': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linux-x64': 1.3.2
+ '@img/sharp-libvips-linux-x64': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linuxmusl-arm64': 1.3.2
+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linuxmusl-x64': 1.3.2
+ '@img/sharp-libvips-linuxmusl-x64': 1.3.4
optional: true
dependencies:
'@emnapi/runtime': 1.11.3
optional: true
dependencies:
- '@img/sharp-wasm32': 0.35.3
+ '@img/sharp-wasm32': 0.35.5
optional: true
optional: true
optional: true
optional: true
@@ -8563,10 +8546,19 @@ snapshots:
'@types/deep-eql': 4.0.2
assertion-error: 2.0.1
- '@types/[email protected]':
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
dependencies:
- '@types/ms': 2.1.0
- optional: true
+ '@types/d3-time': 3.0.4
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-path': 3.1.1
+
+ '@types/[email protected]': {}
'@types/[email protected]': {}
@@ -8584,57 +8576,38 @@ snapshots:
dependencies:
'@types/node': 24.10.14
- '@types/[email protected]':
- optional: true
-
'@types/[email protected]': {}
dependencies:
undici-types: 7.16.0
dependencies:
'@bcoe/v8-coverage': 1.0.2
- '@vitest/utils': 4.1.5
+ '@vitest/utils': 4.1.11
ast-v8-to-istanbul: 1.0.0
istanbul-lib-coverage: 3.2.2
istanbul-lib-report: 3.0.1
istanbul-reports: 3.2.0
magicast: 0.5.2
- obug: 2.1.1
- std-env: 4.1.0
+ obug: 2.2.1
+ std-env: 4.2.0
tinyrainbow: 3.1.0
-
- '@vitest/[email protected]':
- dependencies:
- '@types/chai': 5.2.3
- '@vitest/spy': 3.2.7
- '@vitest/utils': 3.2.7
- chai: 5.3.3
- tinyrainbow: 2.0.0
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
'@standard-schema/spec': 1.1.0
'@types/chai': 5.2.3
- '@vitest/spy': 4.1.5
- '@vitest/utils': 4.1.5
+ '@vitest/spy': 4.1.11
+ '@vitest/utils': 4.1.11
chai: 6.2.2
tinyrainbow: 3.1.0
- dependencies:
- '@vitest/spy': 3.2.7
- estree-walker: 3.0.3
- magic-string: 0.30.21
- optionalDependencies:
-
dependencies:
- '@vitest/spy': 4.1.5
+ '@vitest/spy': 4.1.11
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
@@ -8649,55 +8622,29 @@ snapshots:
optionalDependencies:
- '@vitest/[email protected]':
- dependencies:
- tinyrainbow: 2.0.0
-
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
tinyrainbow: 3.1.0
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- '@vitest/utils': 3.2.7
+ '@vitest/utils': 4.1.11
pathe: 2.0.3
- strip-literal: 3.1.0
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- '@vitest/utils': 4.1.5
- pathe: 2.0.3
-
- '@vitest/[email protected]':
- dependencies:
- '@vitest/pretty-format': 3.2.7
+ '@vitest/pretty-format': 4.1.11
+ '@vitest/utils': 4.1.11
magic-string: 0.30.21
pathe: 2.0.3
- '@vitest/[email protected]':
- dependencies:
- '@vitest/pretty-format': 4.1.5
- '@vitest/utils': 4.1.5
- magic-string: 0.30.21
- pathe: 2.0.3
-
- '@vitest/[email protected]':
- dependencies:
- tinyspy: 4.0.4
-
- '@vitest/[email protected]': {}
+ '@vitest/[email protected]': {}
'@vitest/[email protected]': {}
- '@vitest/[email protected]':
+ '@vitest/[email protected]':
dependencies:
- '@vitest/pretty-format': 3.2.7
- loupe: 3.2.1
- tinyrainbow: 2.0.0
-
- '@vitest/[email protected]':
- dependencies:
- '@vitest/pretty-format': 4.1.5
+ '@vitest/pretty-format': 4.1.11
convert-source-map: 2.0.0
tinyrainbow: 3.1.0
@@ -8808,22 +8755,10 @@ snapshots:
prebuild-install: 7.1.3
optional: true
- dependencies:
- assertion-error: 2.0.1
- check-error: 2.1.3
- deep-eql: 5.0.2
- loupe: 3.2.1
- pathval: 2.0.1
-
-
-
optional: true
@@ -8849,6 +8784,40 @@ snapshots:
mdn-data: 2.27.1
source-map-js: 1.2.1
+ dependencies:
+ internmap: 2.0.3
+
+
+
+ dependencies:
+ d3-color: 3.1.0
+
+
+ dependencies:
+ d3-array: 3.2.4
+ d3-format: 3.1.2
+ d3-interpolate: 3.0.1
+ d3-time: 3.1.0
+ d3-time-format: 4.1.0
+
+ dependencies:
+ d3-path: 3.1.0
+
+ dependencies:
+ d3-time: 3.1.0
+
+ dependencies:
+ d3-array: 3.2.4
+
dependencies:
whatwg-mimetype: 5.0.0
@@ -8877,8 +8846,6 @@ snapshots:
mimic-response: 3.1.0
optional: true
-
optional: true
@@ -8943,8 +8910,6 @@ snapshots:
-
@@ -8987,8 +8952,6 @@ snapshots:
optional: true
-
@@ -9029,7 +8992,7 @@ snapshots:
optionalDependencies:
picomatch: 4.0.7
dependencies:
@@ -9148,7 +9111,7 @@ snapshots:
dependencies:
es-define-property: 1.0.1
@@ -9187,6 +9150,8 @@ snapshots:
optional: true
+
dependencies:
'@inversifyjs/common': 1.5.2
@@ -9250,14 +9215,12 @@ snapshots:
-
dependencies:
argparse: 1.0.10
esprima: 4.0.1
dependencies:
argparse: 2.0.1
@@ -9278,7 +9241,7 @@ snapshots:
saxes: 6.0.0
symbol-tree: 3.2.4
tough-cookie: 6.0.1
- undici: 7.29.0
+ undici: 7.30.0
w3c-xmlserializer: 5.0.0
webidl-conversions: 8.0.1
whatwg-mimetype: 5.0.0
@@ -9313,7 +9276,7 @@ snapshots:
oxc-resolver: 11.19.1
picocolors: 1.1.1
picomatch: 4.0.5
- smol-toml: 1.6.1
+ smol-toml: 1.9.0
strip-json-comments: 5.0.3
unbash: 2.2.0
yaml: 2.8.3
@@ -9422,8 +9385,6 @@ snapshots:
-
@@ -9518,8 +9479,6 @@ snapshots:
-
@@ -9637,8 +9596,6 @@ snapshots:
-
@@ -9746,7 +9703,7 @@ snapshots:
dependencies:
graceful-fs: 4.2.11
- js-yaml: 3.15.1
+ js-yaml: 3.15.2
pify: 4.0.1
strip-bom: 3.0.0
@@ -9899,37 +9856,37 @@ snapshots:
dependencies:
type-fest: 0.20.2
dependencies:
'@img/colour': 1.1.0
detect-libc: 2.1.2
semver: 7.8.5
optionalDependencies:
- '@img/sharp-darwin-arm64': 0.35.3
- '@img/sharp-darwin-x64': 0.35.3
- '@img/sharp-freebsd-wasm32': 0.35.3
- '@img/sharp-libvips-darwin-arm64': 1.3.2
- '@img/sharp-libvips-darwin-x64': 1.3.2
- '@img/sharp-libvips-linux-arm': 1.3.2
- '@img/sharp-libvips-linux-arm64': 1.3.2
- '@img/sharp-libvips-linux-ppc64': 1.3.2
- '@img/sharp-libvips-linux-riscv64': 1.3.2
- '@img/sharp-libvips-linux-s390x': 1.3.2
- '@img/sharp-libvips-linux-x64': 1.3.2
- '@img/sharp-libvips-linuxmusl-arm64': 1.3.2
- '@img/sharp-libvips-linuxmusl-x64': 1.3.2
- '@img/sharp-linux-arm': 0.35.3
- '@img/sharp-linux-arm64': 0.35.3
- '@img/sharp-linux-ppc64': 0.35.3
- '@img/sharp-linux-riscv64': 0.35.3
- '@img/sharp-linux-s390x': 0.35.3
- '@img/sharp-linux-x64': 0.35.3
- '@img/sharp-linuxmusl-arm64': 0.35.3
- '@img/sharp-linuxmusl-x64': 0.35.3
- '@img/sharp-webcontainers-wasm32': 0.35.3
- '@img/sharp-win32-arm64': 0.35.3
- '@img/sharp-win32-ia32': 0.35.3
- '@img/sharp-win32-x64': 0.35.3
+ '@img/sharp-darwin-arm64': 0.35.5
+ '@img/sharp-darwin-x64': 0.35.5
+ '@img/sharp-freebsd-wasm32': 0.35.5
+ '@img/sharp-libvips-darwin-arm64': 1.3.4
+ '@img/sharp-libvips-darwin-x64': 1.3.4
+ '@img/sharp-libvips-linux-arm': 1.3.4
+ '@img/sharp-libvips-linux-arm64': 1.3.4
+ '@img/sharp-libvips-linux-ppc64': 1.3.4
+ '@img/sharp-libvips-linux-riscv64': 1.3.4
+ '@img/sharp-libvips-linux-s390x': 1.3.4
+ '@img/sharp-libvips-linux-x64': 1.3.4
+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.4
+ '@img/sharp-libvips-linuxmusl-x64': 1.3.4
+ '@img/sharp-linux-arm': 0.35.5
+ '@img/sharp-linux-arm64': 0.35.5
+ '@img/sharp-linux-ppc64': 0.35.5
+ '@img/sharp-linux-riscv64': 0.35.5
+ '@img/sharp-linux-s390x': 0.35.5
+ '@img/sharp-linux-x64': 0.35.5
+ '@img/sharp-linuxmusl-arm64': 0.35.5
+ '@img/sharp-linuxmusl-x64': 0.35.5
+ '@img/sharp-webcontainers-wasm32': 0.35.5
+ '@img/sharp-win32-arm64': 0.35.5
+ '@img/sharp-win32-ia32': 0.35.5
+ '@img/sharp-win32-x64': 0.35.5
'@types/node': 24.10.14
@@ -9964,7 +9921,7 @@ snapshots:
dependencies:
@@ -9992,10 +9949,6 @@ snapshots:
-
-
@@ -10022,10 +9975,6 @@ snapshots:
- dependencies:
- js-tokens: 9.0.1
-
dependencies:
anynum: 1.0.1
@@ -10080,8 +10029,6 @@ snapshots:
-
@@ -10089,14 +10036,8 @@ snapshots:
fdir: 6.5.0([email protected])
picomatch: 4.0.7
-
-
-
@@ -10236,7 +10177,7 @@ snapshots:
dependencies:
@@ -10266,28 +10207,6 @@ snapshots:
- dependencies:
- cac: 6.7.14
- debug: 4.4.3
- es-module-lexer: 1.7.0
- pathe: 2.0.3
- transitivePeerDependencies:
- - '@types/node'
- - '@vitejs/devtools'
- - esbuild
- - jiti
- - less
- - sass
- - sass-embedded
- - stylus
- - sugarss
- - supports-color
- - terser
- - tsx
- - yaml
-
dependencies:
lightningcss: 1.33.0
@@ -10304,65 +10223,21 @@ snapshots:
tsx: 4.21.0
yaml: 2.8.3
dependencies:
ts-essentials: 10.2.0([email protected])
typescript: 5.8.3
dependencies:
- '@types/chai': 5.2.3
- '@vitest/expect': 3.2.7
- '@vitest/pretty-format': 3.2.7
- '@vitest/runner': 3.2.7
- '@vitest/snapshot': 3.2.7
- '@vitest/spy': 3.2.7
- '@vitest/utils': 3.2.7
- chai: 5.3.3
- debug: 4.4.3
- expect-type: 1.3.0
- magic-string: 0.30.21
- pathe: 2.0.3
- picomatch: 4.0.5
- std-env: 3.10.0
- tinybench: 2.9.0
- tinyexec: 0.3.2
- tinyglobby: 0.2.17
- tinypool: 1.1.1
- tinyrainbow: 2.0.0
- why-is-node-running: 2.3.0
- optionalDependencies:
- '@types/debug': 4.1.12
- '@types/node': 24.10.14
- jsdom: 29.1.0(@noble/[email protected])([email protected])
- transitivePeerDependencies:
- - '@vitejs/devtools'
- - esbuild
- - jiti
- - less
- - msw
- - sass
- - sass-embedded
- - stylus
- - sugarss
- - supports-color
- - terser
- - tsx
- - yaml
-
- dependencies:
- '@vitest/expect': 4.1.5
- '@vitest/pretty-format': 4.1.5
- '@vitest/runner': 4.1.5
- '@vitest/snapshot': 4.1.5
- '@vitest/spy': 4.1.5
- '@vitest/utils': 4.1.5
+ '@vitest/expect': 4.1.11
+ '@vitest/pretty-format': 4.1.11
+ '@vitest/runner': 4.1.11
+ '@vitest/snapshot': 4.1.11
+ '@vitest/spy': 4.1.11
+ '@vitest/utils': 4.1.11
es-module-lexer: 2.3.2
expect-type: 1.4.0
magic-string: 0.30.21
@@ -10379,7 +10254,7 @@ snapshots:
optionalDependencies:
'@opentelemetry/api': 1.9.0
'@types/node': 24.10.14
- '@vitest/coverage-v8': 4.1.5([email protected])
+ '@vitest/coverage-v8': 4.1.11([email protected])
jsdom: 29.1.0(@noble/[email protected])([email protected])
transitivePeerDependencies:
- msw