Skip to content

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

feat(components): M1 pointer & camera, M2 type

okanasl510e8035f138
diff --git a/examples/30_product_demo/package.json b/examples/30_product_demo/package.json
new file mode 100644
index 00000000..d38fe0c2
--- /dev/null
+++ b/examples/30_product_demo/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "@framefields/example-30-product-demo",
+ "version": "2.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": {
+ "framefields": "workspace:*"
+ },
+ "devDependencies": {
+ "@framefields/tsconfig": "workspace:*",
+ "@types/node": "^24.1.0",
+ "sharp": "^0.35.4",
+ "tsx": "^4.20.3",
+ "typescript": "^5.8.3",
+ "vitest": "^4.1.5"
+ }
+}
diff --git a/examples/30_product_demo/src/film.test.ts b/examples/30_product_demo/src/film.test.ts
new file mode 100644
index 00000000..11eeae35
--- /dev/null
+++ b/examples/30_product_demo/src/film.test.ts
@@ -0,0 +1,17 @@
+import { CompositorProgramSchema } from "framefields";
+import { describe, expect, it } from "vitest";
+import { buildFilm } from "./film.js";
+
+describe("product demo", () => {
+ it("builds a valid, lint-clean program", async () => {
+ const film = await buildFilm();
+ const result = CompositorProgramSchema.safeParse(film.toSpec());
+ expect(
+ result.success,
+ JSON.stringify(result.error?.issues.slice(0, 3)),
+ ).toBe(true);
+ expect(film.lint().filter((d) => d.severity === "error")).toEqual([]);
+ expect(film.durationMs).toBeGreaterThan(10_000);
+ expect(film.durationMs).toBeLessThan(15_000);
+ }, 60_000);
+});
diff --git a/examples/30_product_demo/src/film.ts b/examples/30_product_demo/src/film.ts
new file mode 100644
index 00000000..c6339419
--- /dev/null
+++ b/examples/30_product_demo/src/film.ts
@@ -0,0 +1,300 @@
+/**
+ * A 13-second product demo: the browser opens on a deploys dashboard, the
+ * pointer ships a build and promotes it, and the camera follows every click.
+ *
+ * Three components carry it: AppFrame (the browser), MousePointer (the
+ * hand), FocusZoom (the camera). Everything that reacts — button presses,
+ * the new row, the toast — keys off the pointer's cues, so moving a
+ * waypoint re-times the whole film.
+ */
+import {
+ AppFrame,
+ Composition,
+ FocusZoom,
+ FontManager,
+ Layer,
+ LayerAnimation,
+ type LayoutNode,
+ MousePointer,
+ type Waypoint,
+} from "framefields";
+import {
+ ACCENT,
+ APP,
+ FONTS,
+ FPS,
+ FRAME,
+ H,
+ INK,
+ MONO,
+ MUTED,
+ NIGHT,
+ SANS,
+ VIOLET,
+ W,
+} from "./theme.js";
+import {
+ DEPLOY_BUTTON,
+ dashboard,
+ PROMOTE_BUTTON,
+ type Timeline,
+} from "./ui.js";
+
+const sec = (s: number) => Math.round(s * FPS);
+
+/** The page behind the window: a cold night sky with a little color under the glass. */
+function backdrop(): LayoutNode[] {
+ return [
+ Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ background: `radial-gradient(ellipse at 50% 0%, #161b2e 0%, ${NIGHT} 62%)`,
+ }),
+ Layer.box({
+ position: "absolute",
+ x: W * 0.12,
+ y: H * 0.18,
+ width: W * 0.76,
+ height: H * 0.9,
+ background: `radial-gradient(ellipse at 50% 50%, ${ACCENT}2e 0%, ${VIOLET}10 40%, transparent 70%)`,
+ }),
+ ];
+}
+
+function lockup(at: number): LayoutNode {
+ const mark = 64;
+ return Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ startFrame: at,
+ children: [
+ Layer.box({
+ position: "absolute",
+ x: W / 2 - mark / 2,
+ y: H / 2 - 120,
+ width: mark,
+ height: mark,
+ borderRadius: 18,
+ background: `linear-gradient(135deg, ${ACCENT}, ${VIOLET})`,
+ children: [
+ Layer.text("N", {
+ position: "absolute",
+ x: 0,
+ y: 12,
+ width: mark,
+ align: "center",
+ fontFamily: SANS,
+ fontSize: 34,
+ fontWeight: 700,
+ fill: "#ffffff",
+ }),
+ ],
+ }).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [12, 1, "power2.out"],
+ ])
+ .keys("scale", [
+ [0, 0.7],
+ [sec(0.7), 1, "back.out(1.8)"],
+ ]),
+ ),
+ Layer.text("Northwind", {
+ position: "absolute",
+ x: 0,
+ y: H / 2 - 30,
+ width: W,
+ align: "center",
+ fontFamily: SANS,
+ fontSize: 64,
+ fontWeight: 650,
+ fill: INK,
+ letterSpacing: -1.5,
+ }).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [6, 0, "hold"],
+ [sec(0.8), 1, "power2.out"],
+ ])
+ .keys("y", [
+ [0, H / 2 - 10],
+ [6, H / 2 - 10, "hold"],
+ [sec(0.9), H / 2 - 30, "expo.out"],
+ ]),
+ ),
+ Layer.text("Ship on a Friday. Sleep on a Friday.", {
+ position: "absolute",
+ x: 0,
+ y: H / 2 + 58,
+ width: W,
+ align: "center",
+ fontFamily: SANS,
+ fontSize: 24,
+ fill: MUTED,
+ }).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [sec(0.5), 0, "hold"],
+ [sec(1.2), 1, "power2.out"],
+ ]),
+ ),
+ Layer.text("northwind.dev", {
+ position: "absolute",
+ x: 0,
+ y: H / 2 + 112,
+ width: W,
+ align: "center",
+ fontFamily: MONO,
+ fontSize: 17,
+ fill: ACCENT,
+ letterSpacing: 1,
+ }).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [sec(0.8), 0, "hold"],
+ [sec(1.5), 1, "power2.out"],
+ ]),
+ ),
+ ],
+ });
+}
+
+export async function buildFilm(): Promise<Composition> {
+ await FontManager.register({ family: SANS, source: `${FONTS}Inter.ttf` });
+ await FontManager.register({
+ family: MONO,
+ source: `${FONTS}JetBrainsMono.ttf`,
+ });
+
+ const frame = AppFrame({
+ id: "browser",
+ kind: "browser",
+ ...FRAME,
+ url: { text: "app.northwind.dev/deploys", typeAt: sec(0.4), cps: 34 },
+ appearance: "dark",
+ contentBackground: APP,
+ elevation: 3,
+ enter: { preset: "tilt", duration: sec(1.2) },
+ });
+ // The page paints as soon as the address is in; the load bar finishes over it.
+ const loaded = (frame.cues.urlTyped[0]?.frame ?? sec(1)) + sec(0.3);
+
+ // Composition coordinates of a content-space rect, and its centre.
+ const rect = (r: { x: number; y: number; width: number; height: number }) => {
+ const [x, y] = frame.at(r.x, r.y);
+ return { x, y, width: r.width, height: r.height };
+ };
+ const centre = (r: { x: number; y: number; width: number; height: number }) =>
+ frame.at(r.x + r.width / 2, r.y + r.height / 2);
+
+ // Pass 1 places the deploy click; the build takes 2.4 s from there, and
+ // the pointer comes back to promote it once it's ready.
+ const enterAt = loaded + sec(0.5);
+ const toDeploy: Waypoint = {
+ to: centre(DEPLOY_BUTTON),
+ click: true,
+ dwell: sec(0.3),
+ };
+ const draft = MousePointer({
+ id: "pointer",
+ at: enterAt,
+ from: "bottom",
+ path: [toDeploy],
+ });
+ const deployClick = draft.cues.clicks[0]?.frame ?? 0;
+ const ready = deployClick + sec(2.4);
+ const promoteArrive = ready + sec(0.7);
+
+ const [px, py] = centre(PROMOTE_BUTTON);
+ const pointer = MousePointer({
+ id: "pointer",
+ at: enterAt,
+ from: "bottom",
+ to: "right",
+ path: [
+ toDeploy,
+ // Watch the build: drift down beside the new row.
+ { to: [px - 180, py + 150], dwell: sec(0.4) },
+ {
+ to: [px, py],
+ at: promoteArrive - enterAt,
+ click: true,
+ dwell: sec(0.9),
+ },
+ ],
+ size: 38,
+ hoverRegions: [
+ { target: rect(DEPLOY_BUTTON), style: "hand" },
+ { target: rect(PROMOTE_BUTTON), style: "hand" },
+ ],
+ fps: FPS,
+ });
+
+ const [deployPress, promotePress] = pointer.cues.presses;
+ const [deployRelease, promoteRelease] = pointer.cues.releases;
+ const t: Timeline = {
+ loaded,
+ deployDown: deployPress?.frame ?? 0,
+ deployUp: deployRelease?.frame ?? 0,
+ deployClick,
+ ready,
+ promoteDown: promotePress?.frame ?? 0,
+ promoteUp: promoteRelease?.frame ?? 0,
+ promoteClick: pointer.cues.clicks[1]?.frame ?? 0,
+ };
+ frame.fill(...dashboard(t));
+
+ const outro = t.promoteClick + sec(2.4);
+ const end = outro + sec(2.8);
+
+ const camera = FocusZoom({
+ id: "camera",
+ content: [...backdrop(), frame, pointer],
+ follow: pointer,
+ bounds: FRAME,
+ zoom: 1.65,
+ padding: 220,
+ idle: sec(1.1),
+ length: end,
+ fps: FPS,
+ });
+ const scene = Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ children: [camera],
+ }).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 1],
+ [outro, 1, "hold"],
+ [outro + sec(0.6), 0, "power2.inOut"],
+ ])
+ .keys("scale", [
+ [0, 1],
+ [outro, 1, "hold"],
+ [outro + sec(0.8), 0.94, "power3.in"],
+ ]),
+ );
+
+ const comp = new Composition({
+ width: W,
+ height: H,
+ fps: FPS,
+ durationMs: (end / FPS) * 1000,
+ backgroundColor: NIGHT,
+ fonts: [`${FONTS}Inter.ttf`, `${FONTS}JetBrainsMono.ttf`],
+ });
+ comp.add([scene, lockup(outro + sec(0.6))]);
+ return comp;
+}
diff --git a/examples/30_product_demo/src/render.ts b/examples/30_product_demo/src/render.ts
new file mode 100644
index 00000000..0b54e3b0
--- /dev/null
+++ b/examples/30_product_demo/src/render.ts
@@ -0,0 +1,57 @@
+/**
+ * pnpm render → output/product-demo.mp4
+ * pnpm render frames 60 180 → output/frames/f0060.png …
+ * pnpm render grid → output/grid.png, a contact sheet of the film
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { HeadlessMediaRenderer } from "framefields";
+import { buildFilm } from "./film.js";
+import { FPS, OUTPUT } from "./theme.js";
+
+const [mode = "video", ...args] = process.argv.slice(2);
+const film = await buildFilm();
+const total = Math.round(((film.durationMs ?? 0) / 1000) * FPS);
+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 =
+ args.length > 0
+ ? args.map(Number)
+ : Array.from({ length: 16 }, (_, i) =>
+ Math.round((i * (total - 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, "product-demo.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/30_product_demo/src/theme.ts b/examples/30_product_demo/src/theme.ts
new file mode 100644
index 00000000..74294d04
--- /dev/null
+++ b/examples/30_product_demo/src/theme.ts
@@ -0,0 +1,34 @@
+/** Tokens for the product demo: one palette, one type scale, one clock. */
+
+export const W = 1920;
+export const H = 1080;
+export const FPS = 30;
+export const OUTPUT = new URL("../output/", import.meta.url).pathname;
+export const FONTS = new URL("../../../assets/fonts/", import.meta.url)
+ .pathname;
+
+export const SANS = "Inter";
+export const MONO = "JetBrains Mono";
+
+/** The page behind the window. */
+export const NIGHT = "#06070a";
+/** App surfaces, darkest to lightest. */
+export const APP = "#0f1013";
+export const PANEL = "#141519";
+export const CARD = "#17181d";
+export const RAISED = "#1f2128";
+export const LINE = "#24262d";
+export const EDGE = "#2c2f37";
+/** Type. */
+export const INK = "#ececf1";
+export const SOFT = "#a9abb5";
+export const MUTED = "#73757f";
+/** Signals. */
+export const ACCENT = "#6d8dff";
+export const ACCENT_DEEP = "#4a6cf0";
+export const VIOLET = "#a07bff";
+export const GREEN = "#3ecf8e";
+export const AMBER = "#f5b44a";
+
+/** The window, in composition px. */
+export const FRAME = { x: 150, y: 64, width: 1620, height: 952 } as const;
diff --git a/examples/30_product_demo/src/ui.ts b/examples/30_product_demo/src/ui.ts
new file mode 100644
index 00000000..2a0210be
--- /dev/null
+++ b/examples/30_product_demo/src/ui.ts
@@ -0,0 +1,828 @@
+/**
+ * The mock app inside the browser: a deploys dashboard built from plain
+ * framefields layers. Geometry is exported so the pointer can aim at it; the
+ * moments it reacts to (clicks, presses) come from the pointer's cues.
+ */
+import { Layer, LayerAnimation, type LayoutNode } from "framefields";
+import {
+ ACCENT,
+ ACCENT_DEEP,
+ AMBER,
+ CARD,
+ EDGE,
+ FPS,
+ FRAME,
+ GREEN,
+ INK,
+ LINE,
+ MONO,
+ MUTED,
+ PANEL,
+ RAISED,
+ SANS,
+ SOFT,
+ VIOLET,
+} from "./theme.js";
+
+/** Content area of the browser (below its 56 px toolbar). */
+export const CW = FRAME.width;
+export const CH = FRAME.height - 56;
+
+const SIDEBAR = 252;
+const PAD = 44;
+const MAIN_X = SIDEBAR + PAD;
+const MAIN_W = CW - MAIN_X - PAD;
+
+export const DEPLOY_BUTTON = {
+ x: CW - PAD - 136,
+ y: 62,
+ width: 136,
+ height: 44,
+};
+const VISIT_BUTTON = {
+ x: DEPLOY_BUTTON.x - 12 - 104,
+ y: 62,
+ width: 104,
+ height: 44,
+};
+
+const STATS_Y = 140;
+const STATS_H = 112;
+const LIST_HEAD_Y = 288;
+export const TABLE = {
+ x: MAIN_X,
+ y: 324,
+ width: MAIN_W,
+ height: CH - 324 - PAD,
+};
+const ROW_H = 68;
+
+/** The Promote button on the new (first) row, in content px. */
+export const PROMOTE_BUTTON = {
+ x: TABLE.x + TABLE.width - 384,
+ y: TABLE.y + (ROW_H - 34) / 2,
+ width: 104,
+ height: 34,
+};
+
+export interface Timeline {
+ /** The page has loaded: content animates in from here. */
+ loaded: number;
+ /** Deploy press / release / click. */
+ deployDown: number;
+ deployUp: number;
+ deployClick: number;
+ /** The build finishes. */
+ ready: number;
+ promoteDown: number;
+ promoteUp: number;
+ promoteClick: number;
+}
+
+const ease = "expo.out";
+const sec = (s: number) => Math.round(s * FPS);
+
+/** Rise-and-fade in at `at` (content frames), offset to the node's `y`. */
+function rise(y: number, at: number, distance = 14, duration = sec(0.6)) {
+ return LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [at, 0, "hold"],
+ [at + duration, 1, ease],
+ ])
+ .keys("y", [
+ [0, y + distance],
+ [at, y + distance, "hold"],
+ [at + duration, y, ease],
+ ]);
+}
+
+/** A press: shrink while the button is down, spring back on release. */
+function press(down: number, up: number) {
+ return LayerAnimation.keys("scale", [
+ [0, 1],
+ [down, 1, "hold"],
+ [down + 3, 0.955, "power2.out"],
+ [up, 0.955, "hold"],
+ [up + sec(0.35), 1, "back.out(2.4)"],
+ ]);
+}
+
+function text(
+ value: string,
+ o: {
+ x: number;
+ y: number;
+ size: number;
+ color?: string;
+ weight?: number;
+ font?: string;
+ width?: number;
+ align?: "start" | "center" | "end";
+ id?: string;
+ },
+) {
+ return Layer.text(value, {
+ ...(o.id && { id: o.id }),
+ position: "absolute",
+ x: o.x,
+ y: o.y,
+ ...(o.width !== undefined && { width: o.width }),
+ ...(o.align && { align: o.align }),
+ fontFamily: o.font ?? SANS,
+ fontSize: o.size,
+ fontWeight: o.weight ?? 400,
+ fill: o.color ?? INK,
+ });
+}
+
+function sidebar(t: Timeline): LayoutNode {
+ const nav = [
+ "Overview",
+ "Deploys",
+ "Domains",
+ "Analytics",
+ "Logs",
+ "Settings",
+ ];
+ const children: LayoutNode[] = [
+ Layer.box({
+ position: "absolute",
+ x: 24,
+ y: 24,
+ width: 30,
+ height: 30,
+ borderRadius: 9,
+ background: `linear-gradient(135deg, ${ACCENT}, ${VIOLET})`,
+ children: [
+ text("N", {
+ x: 0,
+ y: 5,
+ width: 30,
+ align: "center",
+ size: 16,
+ weight: 700,
+ color: "#ffffff",
+ }),
+ ],
+ }),
+ text("Northwind", { x: 66, y: 29, size: 16, weight: 600 }),
+ ];
+ nav.forEach((label, i) => {
+ const y = 96 + i * 42;
+ const active = label === "Deploys";
+ if (active) {
+ children.push(
+ Layer.box({
+ position: "absolute",
+ x: 14,
+ y: y - 9,
+ width: SIDEBAR - 28,
+ height: 38,
+ borderRadius: 10,
+ background: RAISED,
+ }),
+ );
+ }
+ children.push(
+ Layer.shape("circle", {
+ position: "absolute",
+ x: 30,
+ y: y + 5,
+ width: 8,
+ height: 8,
+ fillColor: active ? ACCENT : EDGE,
+ }),
+ text(label, {
+ x: 52,
+ y,
+ size: 15,
+ weight: active ? 600 : 450,
+ color: active ? INK : SOFT,
+ }),
+ );
+ });
+ children.push(
+ Layer.box({
+ position: "absolute",
+ x: 24,
+ y: CH - 64,
+ width: 34,
+ height: 34,
+ borderRadius: 17,
+ background: "linear-gradient(135deg, #f7b267, #f4845f)",
+ children: [
+ text("AL", {
+ x: 0,
+ y: 9,
+ width: 34,
+ align: "center",
+ size: 12,
+ weight: 700,
+ color: "#1a0f08",
+ }),
+ ],
+ }),
+ text("Ada Lovelace", { x: 70, y: CH - 64, size: 14, weight: 600 }),
+ text("Pro plan", { x: 70, y: CH - 44, size: 12.5, color: MUTED }),
+ );
+ return Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: SIDEBAR,
+ height: CH,
+ background: PANEL,
+ children: [
+ ...children,
+ Layer.box({
+ position: "absolute",
+ x: SIDEBAR - 1,
+ y: 0,
+ width: 1,
+ height: CH,
+ background: LINE,
+ }),
+ ],
+ }).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [t.loaded - sec(0.2), 0, "hold"],
+ [t.loaded + sec(0.4), 1, "power2.out"],
+ ]),
+ );
+}
+
+function header(t: Timeline): LayoutNode[] {
+ const at = t.loaded;
+ const deploy = Layer.box({
+ id: "deploy-button",
+ position: "absolute",
+ ...DEPLOY_BUTTON,
+ borderRadius: 11,
+ background: `linear-gradient(180deg, #7d9bff, ${ACCENT_DEEP})`,
+ children: [
+ Layer.shape("path", {
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: DEPLOY_BUTTON.width,
+ height: DEPLOY_BUTTON.height,
+ d: "M31 26 L37 18 L43 26 M37 18 L37 30",
+ fillType: "none",
+ strokeColor: "#ffffff",
+ strokeWidth: 2.2,
+ strokeLineCap: "round",
+ strokeLineJoin: "round",
+ }),
+ text("Deploy", {
+ x: 54,
+ y: 12,
+ size: 15.5,
+ weight: 600,
+ color: "#ffffff",
+ }),
+ ],
+ })
+ .animate(rise(DEPLOY_BUTTON.y, at + sec(0.15)))
+ .animate(press(t.deployDown, t.deployUp));
+ return [
+ text("northwind / web", {
+ x: MAIN_X,
+ y: 34,
+ size: 13.5,
+ color: MUTED,
+ font: MONO,
+ }).animate(rise(34, at)),
+ text("Deploys", { x: MAIN_X, y: 60, size: 32, weight: 650 }).animate(
+ rise(60, at + 2),
+ ),
+ Layer.box({
+ position: "absolute",
+ ...VISIT_BUTTON,
+ borderRadius: 11,
+ borderColor: EDGE,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ background: CARD,
+ children: [
+ text("Visit", {
+ x: 0,
+ y: 12,
+ width: VISIT_BUTTON.width,
+ align: "center",
+ size: 15.5,
+ weight: 500,
+ }),
+ ],
+ }).animate(rise(VISIT_BUTTON.y, at + sec(0.1))),
+ deploy,
+ ];
+}
+
+const SPARKS = [
+ [12, 14, 13, 15, 14, 16, 15, 17, 16, 18, 17, 19],
+ [22, 19, 20, 17, 18, 15, 16, 14, 15, 13, 14, 12],
+ [3, 5, 4, 7, 6, 8, 9, 8, 11, 10, 13, 14],
+];
+
+function sparkline(
+ values: number[],
+ w: number,
+ h: number,
+ color: string,
+): LayoutNode[] {
+ const lo = Math.min(...values);
+ const hi = Math.max(...values);
+ const pts = values.map(
+ (v, i) =>
+ [
+ (i / (values.length - 1)) * w,
+ h - ((v - lo) / (hi - lo || 1)) * h,
+ ] as const,
+ );
+ const line = pts
+ .map(([x, y], i) => `${i ? "L" : "M"}${x.toFixed(1)} ${y.toFixed(1)}`)
+ .join(" ");
+ return [
+ Layer.shape("path", {
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: w,
+ height: h,
+ d: `${line} L${w} ${h} L0 ${h} Z`,
+ fill: `linear-gradient(180deg, ${color}55, ${color}00)`,
+ }),
+ Layer.shape("path", {
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: w,
+ height: h,
+ d: line,
+ fillType: "none",
+ strokeColor: color,
+ strokeWidth: 2,
+ strokeLineCap: "round",
+ strokeLineJoin: "round",
+ }),
+ ];
+}
+
+function stats(t: Timeline): LayoutNode[] {
+ const cards = [
+ {
+ label: "Uptime · 30 days",
+ value: "99.98%",
+ delta: "+0.02%",
+ up: true,
+ color: GREEN,
+ },
+ {
+ label: "p95 latency",
+ value: "182 ms",
+ delta: "−24 ms",
+ up: true,
+ color: ACCENT,
+ },
+ {
+ label: "Deploys today",
+ value: "14",
+ after: "15",
+ delta: "+3 vs avg",
+ up: true,
+ color: VIOLET,
+ },
+ ];
+ const gap = 18;
+ const w = (MAIN_W - gap * 2) / 3;
+ return cards.map((c, i) => {
+ const x = MAIN_X + i * (w + gap);
+ const value = (v: string) =>
+ text(v, { x: 24, y: 48, size: 34, weight: 650 });
+ const values: LayoutNode[] = [value(c.value)];
+ if (c.after) {
+ // The count ticks over when the new build lands.
+ values[0] = value(c.value).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [t.ready, 1],
+ [t.ready + 6, 0, "power2.in"],
+ ])
+ .keys("y", [
+ [t.ready, 48],
+ [t.ready + 8, 30, "power2.in"],
+ ]),
+ );
+ values.push(
+ value(c.after).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [t.ready + 4, 0, "hold"],
+ [t.ready + 14, 1, "power2.out"],
+ ])
+ .keys("y", [
+ [0, 66],
+ [t.ready + 4, 66, "hold"],
+ [t.ready + 18, 48, ease],
+ ]),
+ ),
+ );
+ }
+ return Layer.box({
+ position: "absolute",
+ x,
+ y: STATS_Y,
+ width: w,
+ height: STATS_H,
+ borderRadius: 16,
+ background: CARD,
+ borderColor: LINE,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ overflow: "hidden",
+ children: [
+ text(c.label, { x: 24, y: 22, size: 13.5, color: MUTED, weight: 500 }),
+ ...values,
+ text(c.delta, {
+ x: 24,
+ y: 88 - 4,
+ size: 12.5,
+ color: c.color,
+ weight: 600,
+ }),
+ Layer.box({
+ position: "absolute",
+ x: w - 24 - 150,
+ y: 40,
+ width: 150,
+ height: 44,
+ children: sparkline(SPARKS[i] ?? [], 150, 44, c.color),
+ }),
+ ],
+ }).animate(rise(STATS_Y, t.loaded + sec(0.25) + i * 3));
+ });
+}
+
+interface Row {
+ title: string;
+ meta: string;
+ when: string;
+}
+
+const ROWS: Row[] = [
+ {
+ title: "Tighten cache headers for /assets",
+ meta: "main · a91f3e2 · Ada",
+ when: "2h ago",
+ },
+ {
+ title: "Add regional failover for eu-west",
+ meta: "main · 7c02d18 · Grace",
+ when: "5h ago",
+ },
+ {
+ title: "Upgrade runtime to Node 22",
+ meta: "main · 3be41aa · Linus",
+ when: "yesterday",
+ },
+ {
+ title: "Fix flaky checkout test",
+ meta: "fix/checkout · 0d9e7b5 · Ada",
+ when: "yesterday",
+ },
+ {
+ title: "Ship onboarding v2",
+ meta: "main · 51c8e60 · Margaret",
+ when: "2 days ago",
+ },
+ {
+ title: "Rotate signing keys",
+ meta: "main · c3d9f02 · Grace",
+ when: "3 days ago",
+ },
+ {
+ title: "Initial edge config",
+ meta: "main · 0a11b7e · Linus",
+ when: "last week",
+ },
+];
+
+function pill(label: string, color: string, x: number, y: number, w = 96) {
+ return Layer.box({
+ position: "absolute",
+ x,
+ y,
+ width: w,
+ height: 28,
+ borderRadius: 14,
+ background: `${color}1f`,
+ children: [
+ Layer.shape("circle", {
+ position: "absolute",
+ x: 12,
+ y: 10,
+ width: 8,
+ height: 8,
+ fillColor: color,
+ }),
+ text(label, { x: 26, y: 6, size: 13, weight: 600, color }),
+ ],
+ });
+}
+
+function row(r: Row, y: number, status: LayoutNode, extra: LayoutNode[] = []) {
+ const w = TABLE.width;
+ return Layer.box({
+ position: "absolute",
+ x: 0,
+ y,
+ width: w,
+ height: ROW_H,
+ children: [
+ text(r.title, { x: 24, y: 14, size: 15.5, weight: 550 }),
+ text(r.meta, { x: 24, y: 38, size: 12.5, color: MUTED, font: MONO }),
+ status,
+ ...extra,
+ text(r.when, {
+ x: w - 24 - 110,
+ y: 24,
+ width: 110,
+ align: "end",
+ size: 13.5,
+ color: MUTED,
+ }),
+ Layer.box({
+ position: "absolute",
+ x: 0,
+ y: ROW_H - 1,
+ width: w,
+ height: 1,
+ background: LINE,
+ }),
+ ],
+ });
+}
+
+function table(t: Timeline): LayoutNode {
+ const w = TABLE.width;
+ const statusX = w - 24 - 110 - 18 - 100;
+ const shift = sec(0.55);
+ const arrive = t.deployClick + 4;
+ const rows = ROWS.map((r, i) =>
+ row(
+ r,
+ i * ROW_H,
+ pill("Ready", GREEN, statusX, (ROW_H - 28) / 2, 82),
+ ).animate(
+ LayerAnimation.create()
+ .keys("y", [
+ [0, i * ROW_H],
+ [arrive, i * ROW_H, "hold"],
+ [arrive + shift, (i + 1) * ROW_H, ease],
+ ])
+ .keys("opacity", [
+ [0, 0],
+ [t.loaded + sec(0.4) + i * 2, 0, "hold"],
+ [t.loaded + sec(0.9) + i * 2, 1, "power2.out"],
+ ]),
+ ),
+ );
+
+ // The new deploy: building (amber, breathing) → ready → production.
+ const building = pill(
+ "Building",
+ AMBER,
+ statusX - 14,
+ (ROW_H - 28) / 2,
+ 96,
+ ).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 1],
+ [t.ready, 1, "hold"],
+ [t.ready + 6, 0, "power2.in"],
+ ]),
+ );
+ const ready = pill("Ready", GREEN, statusX, (ROW_H - 28) / 2, 82).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [t.ready + 3, 0, "hold"],
+ [t.ready + 12, 1, "power2.out"],
+ [t.promoteUp + 4, 1, "hold"],
+ [t.promoteUp + 10, 0, "power2.in"],
+ ]),
+ );
+ const promote = Layer.box({
+ id: "promote-button",
+ position: "absolute",
+ x: PROMOTE_BUTTON.x - TABLE.x,
+ y: PROMOTE_BUTTON.y - TABLE.y,
+ width: PROMOTE_BUTTON.width,
+ height: PROMOTE_BUTTON.height,
+ borderRadius: 9,
+ background: RAISED,
+ borderColor: EDGE,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ children: [
+ text("Promote", {
+ x: 0,
+ y: 8,
+ width: PROMOTE_BUTTON.width,
+ align: "center",
+ size: 13.5,
+ weight: 600,
+ }),
+ ],
+ })
+ .animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [t.ready + 8, 0, "hold"],
+ [t.ready + 20, 1, "power2.out"],
+ [t.promoteUp + 4, 1, "hold"],
+ [t.promoteUp + 12, 0, "power2.in"],
+ ]),
+ )
+ .animate(press(t.promoteDown, t.promoteUp));
+ // Promoting swaps the Ready pill for a Production badge in its place.
+ const production = Layer.box({
+ position: "absolute",
+ x: statusX - 20,
+ y: (ROW_H - 28) / 2,
+ width: 122,
+ height: 28,
+ borderRadius: 14,
+ background: `linear-gradient(90deg, ${ACCENT}, ${VIOLET})`,
+ children: [
+ text("Production", {
+ x: 0,
+ y: 6,
+ width: 122,
+ align: "center",
+ size: 13,
+ weight: 650,
+ color: "#ffffff",
+ }),
+ ],
+ }).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [t.promoteUp + 8, 0, "hold"],
+ [t.promoteUp + 16, 1, "power2.out"],
+ ])
+ .keys("scale", [
+ [0, 0.8],
+ [t.promoteUp + 8, 0.8, "hold"],
+ [t.promoteUp + 22, 1, "back.out(2)"],
+ ]),
+ );
+ const fresh = row(
+ {
+ title: "Speed up image pipeline 3×",
+ meta: "main · e47b21c · Ada",
+ when: "just now",
+ },
+ 0,
+ Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: w,
+ height: ROW_H,
+ children: [building, ready],
+ }),
+ [promote, production],
+ ).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [arrive + 4, 0, "hold"],
+ [arrive + shift, 1, "power2.out"],
+ ])
+ .keys("x", [
+ [0, -18],
+ [arrive + 4, -18, "hold"],
+ [arrive + shift, 0, ease],
+ ]),
+ );
+ // A soft highlight sweeps the new row in, then fades.
+ const glow = Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: w,
+ height: ROW_H,
+ background: `linear-gradient(90deg, ${ACCENT}26, ${ACCENT}00 70%)`,
+ }).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [arrive, 0, "hold"],
+ [arrive + 8, 1, "power2.out"],
+ [t.ready + sec(1.4), 0, "power2.inOut"],
+ ]),
+ );
+
+ return Layer.box({
+ position: "absolute",
+ ...TABLE,
+ borderRadius: 16,
+ background: CARD,
+ borderColor: LINE,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ overflow: "hidden",
+ children: [glow, ...rows, fresh],
+ }).animate(rise(TABLE.y, t.loaded + sec(0.35)));
+}
+
+function toast(t: Timeline): LayoutNode {
+ const w = 380;
+ const h = 78;
+ const x = CW - PAD - w;
+ const y = CH - PAD - h;
+ const show = t.promoteUp + sec(0.3);
+ const hide = show + sec(2.6);
+ return Layer.box({
+ position: "absolute",
+ x,
+ y,
+ width: w,
+ height: h,
+ borderRadius: 16,
+ background: RAISED,
+ borderColor: EDGE,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ children: [
+ Layer.shape("circle", {
+ position: "absolute",
+ x: 20,
+ y: 23,
+ width: 32,
+ height: 32,
+ fillColor: `${GREEN}26`,
+ }),
+ Layer.shape("path", {
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: w,
+ height: h,
+ d: "M29 39.5 L34 44.5 L43.5 34",
+ fillType: "none",
+ strokeColor: GREEN,
+ strokeWidth: 2.6,
+ strokeLineCap: "round",
+ strokeLineJoin: "round",
+ }),
+ text("Promoted to production", { x: 68, y: 19, size: 15.5, weight: 600 }),
+ text("e47b21c · live on northwind.dev", {
+ x: 68,
+ y: 43,
+ size: 13,
+ color: MUTED,
+ font: MONO,
+ }),
+ ],
+ }).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [show, 0, "hold"],
+ [show + 10, 1, "power2.out"],
+ [hide, 1, "hold"],
+ [hide + 10, 0, "power2.in"],
+ ])
+ .keys("x", [
+ [0, x + 40],
+ [show, x + 40, "hold"],
+ [show + sec(0.5), x, ease],
+ ])
+ .keys("y", [
+ [0, y],
+ [hide, y, "hold"],
+ [hide + 10, y + 12, "power2.in"],
+ ]),
+ );
+}
+
+/** The whole page, in content px. */
+export function dashboard(t: Timeline): LayoutNode[] {
+ return [
+ sidebar(t),
+ ...header(t),
+ ...stats(t),
+ text("Recent deploys", {
+ x: MAIN_X,
+ y: LIST_HEAD_Y,
+ size: 17,
+ weight: 600,
+ }).animate(rise(LIST_HEAD_Y, t.loaded + sec(0.3))),
+ table(t),
+ toast(t),
+ ];
+}
diff --git a/examples/30_product_demo/tsconfig.dev.json b/examples/30_product_demo/tsconfig.dev.json
new file mode 100644
index 00000000..c5e4355b
--- /dev/null
+++ b/examples/30_product_demo/tsconfig.dev.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig.json",
+ "include": [
+ "src/**/*",
+ "../../nodes/**/*",
+ "../../packages/**/*",
+ "../../node_modules/@framefields/**/*"
+ ]
+}
diff --git a/examples/30_product_demo/tsconfig.json b/examples/30_product_demo/tsconfig.json
new file mode 100644
index 00000000..999801f9
--- /dev/null
+++ b/examples/30_product_demo/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "extends": "@framefields/tsconfig/base.json",
+ "compilerOptions": {
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "target": "ES2022",
+ "noEmit": true
+ },
+ "include": ["src/**/*"]
+}
diff --git a/examples/30_product_demo/vitest.config.ts b/examples/30_product_demo/vitest.config.ts
new file mode 100644
index 00000000..be6fcdda
--- /dev/null
+++ b/examples/30_product_demo/vitest.config.ts
@@ -0,0 +1,6 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: { include: ["src/**/*.test.ts"], pool: "forks" },
+ resolve: { conditions: ["development"] },
+});
diff --git a/packages/components/SPEC.md b/packages/components/SPEC.md
index 665eb228..b7a1414a 100644
--- a/packages/components/SPEC.md
+++ b/packages/components/SPEC.md
@@ -384,8 +384,10 @@ signals).
Named entrances/exits used by every component's `enter` / `exit`:
`fade`, `rise`, `drop`, `scale`, `pop` (overshoot), `slide-{left,right,up,down}`,
-`tilt` (3D perspective settle), `none`. `blur` (needs the blur effect on the host) and
-`mask-{up,down,left,right}` (needs a matte) arrive with `TextReveal` in M2. Each preset accepts `{ duration, ease, distance, delay }` overrides and reads
+`tilt` (3D perspective settle), `none`, and (M2) `mask-{up,down,left,right}`: the stage
+slides its full width or height through the root, which clips (`overflow: hidden`), with no
+fade. A `blur` preset is deferred: framefields' blur is an effect driven by signals, not a
+keyable node prop; `TextReveal` `blur` covers text. Each preset accepts `{ duration, ease, distance, delay }` overrides and reads
defaults from `theme.motion`.
Springs are evaluated in closed form and **baked to keyframes** with `bake.ts`
@@ -969,17 +971,16 @@ Each milestone ends with a changeset for `framefields` (minor), docs, and its ex
| Milestone | Scope | Exit criteria |
|---|---|---|
| **M0 · Foundations** ✅ | Package scaffold; host binding in framefields (`./components` export, root re-exports, tsdown entry, `bindComponent`); `core/*` modules (§5); test harness (fake host, GPU render test, determinism); tree-shake check; `components.json` collector. | Done: a test-only `Probe` component passes §9.1–9.5 (§12). |
-| **M1 · Pointer & camera** | `MousePointer` (rebuilt to the existing changeset design plus the Wave 1 additions), `FocusZoom`, `AppFrame`. | Example `30_product_demo`: a screen recording in a browser frame, pointer with clicks and auto-zoom, click SFX placed from cues. |
-| **M2 · Type** | `TextReveal`, `Counter`, `Annotate`. | Example `31_type_and_numbers`: every reveal style, counters, annotations on wrapped text; all §7.4–7.6 acceptance tests green. |
+| **M1 · Pointer & camera** ✅ | `MousePointer` (rebuilt to the existing changeset design plus the Wave 1 additions), `FocusZoom`, `AppFrame`. | Example `30_product_demo`: a screen recording in a browser frame, pointer with clicks and auto-zoom, click SFX placed from cues. |
+| **M2 · Type** ✅ | `TextReveal`, `Counter`, `Annotate`. | All §7.4–7.6 acceptance tests green (§14). No example film for M2 or later milestones: examples stop at `30_product_demo`. |
| **M3 · Speech & shell** | `Captions` (incl. transcript parsers and `behind`), `Terminal`. | Example `32_talking_head_social` (portrait, captions behind the speaker, audio pulse) and a terminal segment in a dev-tool launch cut. |
| **M4 · Wave 2a** | `CodeBlock`, `TitleCard`, `LowerThird`, `Meter`. | Full specs written first (§8 → §7 format). |
| **M5 · Wave 2b** | `ChatThread`, `Callout`, `Spotlight`, `Confetti`, `Toasts`. | As above. |
| **M6 · Re-score** | Rank Wave 3 against usage and requests. | Updated §8.2. |
-Housekeeping before M1: `.changeset/components-mouse-pointer.md` and the
-`packages/components` lockfile entry describe a package that is not on disk. Either restore
-that implementation as the M1 starting point or retarget the changeset to `framefields`
-when M1 lands.
+Housekeeping (done in M1): the stale `.changeset/components-mouse-pointer.md` described a
+standalone package that never shipped; it is replaced by `framefields` changesets per
+milestone (the components package is private and bundled).
---
@@ -988,8 +989,8 @@ when M1 lands.
| # | Question | Status |
|---|---|---|
| Q1 | Root re-export or `framefields/components` only? | **Decided (M0):** components and user-facing types at the root, full toolkit at the subpath (§3.1). |
-| Q2 | Is text `content` keyframeable with hold interpolation? | **Answered:** yes, `text` is an animatable prop (`.keys("text", …)`, which `FontManager.measure().caretX` is documented to pair with). `Counter` `count` style and `TextReveal` `type` / `stream` use it directly. |
-| Q3 | Node targets inside flex layouts need resolved geometry at build time. | **Partly answered:** `computeLayoutSync(yoga, { layout, viewport, measure })` already exists in `@framefields/compositions/program`. M1 adds a `host.layout(root)` backed by it; until then node targets require absolute nodes and the error says so. |
+| Q2 | Is text `content` keyframeable with hold interpolation? | **Corrected (M1):** the `text` track is a *reveal amount*, not a string: ≤ 1 is a fraction, > 1 a character count (so one character of n is keyed as `1 / n`). Typing (`AppFrame` URLs, `TextReveal` `type`) keys counts with `hold`. Changing strings per frame is not possible, so `Counter` uses digit reels for both styles and `stream` uses glyph animators. |
+| Q3 | Node targets inside flex layouts need resolved geometry at build time. | **Open:** `computeLayoutSync(yoga, …)` exists in `@framefields/compositions/program`, but no `host.layout` was needed for M1/M2: node targets still require absolute nodes and the error says so. `TextReveal.rects(match)` and `AppFrame.at(x, y)` cover the common cases. |
| Q4 | PascalCase factories vs. a namespace? | **Decided:** PascalCase named exports. A namespace object defeats tree-shaking. |
| Q5 | Should built-in themes ship fonts? | **Decided:** no. Fonts stay user-registered. |
| Q6 | Seconds vs. frames for user-facing times. | **Decided:** frames everywhere; `fps` base prop for real-world inputs and theme speeds. |
@@ -1014,3 +1015,78 @@ Deviations from the original plan, all reflected above: no `AnimatableNode` type
(§3.3), a narrower root export (§3.1), an added `fps` base prop (§4.2), `blur` / `mask`
presets moved to M2 (§5.4), and a baseline-relative tree-shake check (§9.5). The probe
component lives in tests only, so there was nothing to delete.
+
+## 13. M1 delivery notes
+
+What landed: `MousePointer`, `AppFrame`, `FocusZoom` (§7.1, §7.2, §7.7), their unit tests
+and `m1.render.test.ts`, the tree-shake cases, and `examples/30_product_demo`.
+
+Decisions and deviations:
+
+- **Props are a factory** (`props: () => zodShape`) and shared schemas (`basePropsSchema()`,
+ `targetSchema()`) and glyph tables are built on first use, so importing a component builds
+ nothing; the tree-shake baseline (§9.5) enforces it.
+- **Contract additions:** `BuildContext.requested` (the user's width / height), `BuildResult`
+ `origin` (components that work in parent coordinates sit at 0, 0), `duration: null`
+ (open-ended containers; an exit then needs an explicit `duration`) and `api` (extra methods
+ on the node: `positionAt`, `contentRect`, `at`, `toScreen` …). Host gained `media` and
+ `style` (layer styles).
+- **MousePointer:** default size 44 px, motion blur via the node's `motionBlurShutter`
+ (45° when `true`), click rests count as pressed so drift never moves a click, and the moving
+ part is a box the size of the glyph (1 × 1 boxes cull their children).
+- **FocusZoom camera:** moves interpolate the *view rectangle* between framings that are
+ clamped beforehand, eased minimum-jerk. Every content point then moves one way on screen,
+ with no sideways wiggle while zooming. Smoothing pan and zoom separately and clamping the
+ result made the view drift sideways mid-zoom. Moves land by `settleBy` (two frames before a
+ cluster's first click); `bounds` keeps a zoomed view inside a region (e.g. the app
+ window); `follow` frames click clusters and does not chase the pointer. Smear presets are
+ 24 / 60 / 140° shutter.
+
+## 14. M2 delivery notes
+
+What landed: `TextReveal`, `Counter`, `Annotate` (§7.4–7.6), `core/glyphs.ts`, mask
+presets, unit tests on the fake host and `m2.render.test.ts` (every glyph style ends
+pixel-identical to the static text; scramble frames identical in any render order; wrapped
+underlines; settled counters hold still).
+
+How it is built:
+
+- **Per-unit GPU schedules (`core/glyphs.ts`).** The renderer's expression selector reads
+ the text node's local `frame` and the unit index (`textIndex` counts every character,
+ spaces included; `wordIndex`; `lineIndex`). A schedule bakes each unit's start and an
+ ease table sampled with `core/ease.ts` into the expression, so cue frames are exact, any
+ order works (`random`, `center` …) and back / elastic overshoot comes through. One text
+ node per paragraph; `evaluateGlyphExpression` mirrors the renderer for unit tests.
+- **Node-based styles** where glyph animators can't do it: `mask` (one clipped node per
+ line), `scramble` (a clipped reel per character), and `slam` (a node per unit: the
+ renderer pivots glyphs on their own boxes, so a word can't scale as one). Both hand over to
+ the paragraph node the frame they settle, so the final frame is still the static text.
+- **`wipe`** is a CSS-gradient box matte (`host.matte`); shape mattes don't mask in the
+ renderer. The front trails blur from a baked front-position table.
+- **Counter:** every digit place is a clipped reel; values are integers in the last shown
+ digit (`99.5` at two decimals is `9950`). `roll` spins like an odometer, capped at
+ `MAX_TURNS` (3) full turns per move plus the remainder, so the landing digit is exact;
+ `count` steps the same reels. Formats: a d3-style subset (`[$][,][.precision][d|f|%]`),
+ `Intl.NumberFormatOptions` (affixes and separators from `formatToParts`), or a function
+ (laid out per character from the right). Places fade in and the number slides to keep
+ `align` as they appear.
+- **Annotate:** strokes draw on in sequence by length; hand-drawn marks boil with `d` hold
+ keys; text ranges give one stroke per line; arrows' boxes include the tail.
+
+Deviations from §7.4–7.6:
+
+- **Lifetime.** New `BuildResult.openEnded`: text, numbers and marks stay on screen after
+ they settle unless an `exit` or `duration` is given (then `hold` applies). New
+ `BuildResult.afterHold` / `BuildContext.hold` let a component play its own exit after the
+ hold (`TextReveal` `exitStyle`).
+- **TextReveal:** rich `TextSpan[]` text is replaced by `emphasis` (words or patterns in the
+ accent colour), which keeps one measured string. `exitStyle` excludes `scramble` and
+ `slam`; `mask` exits only a `mask` reveal. Added `cps` and `caret` for `type` / `stream`,
+ and `rects(match)` on the node (parent coordinates) for `Annotate` and cameras.
+- **Counter:** digits are always tabular (reels need fixed cells), so the final frame
+ matches a tabular layout, not a proportional `Layer.text`. The `duration` / `ease` props
+ are `countDuration` / `ease` (base `duration` is the window); `signal`-driven values and
+ the `flip` style are deferred.
+- **Annotate:** targets must be static (moving targets belong to `Callout`). `hand.wobble`
+ is 0–1 (× 5 px at theme scale), `pencil` has no grain yet, and `highlight` multiplies on
+ light themes and tints on dark ones instead of being inserted under the target.
diff --git a/packages/components/src/annotate/index.test.ts b/packages/components/src/annotate/index.test.ts
new file mode 100644
index 00000000..5235e133
--- /dev/null
+++ b/packages/components/src/annotate/index.test.ts
@@ -0,0 +1,117 @@
+import type { LayoutNode } from "@framefields/compositions/program";
+import { describe, expect, it } from "vitest";
+import { bind } from "../core/contract.js";
+import { fakeHost } from "../test/fake-host.js";
+import { annotate } from "./index.js";
+
+const make = () => bind(fakeHost(), annotate);
+type Node = LayoutNode & {
+ d?: string;
+ strokeWidth?: number;
+ animation?: {
+ tracks: Array<{
+ prop: string;
+ keyframes: Array<{
+ frame: number;
+ value: unknown;
+ ease?: { name: string };
+ }>;
+ }>;
+ };
+};
+const strokes = (n: unknown) =>
+ (
+ (n as { children: Array<{ children: Node[] }> }).children[0]?.children ?? []
+ ).filter((c) => (c.id ?? "").includes("stroke"));
+const keys = (n: Node, prop: string) =>
+ n.animation?.tracks.find((t) => t.prop === prop)?.keyframes ?? [];
+const ys = (d = "") =>
+ [...d.matchAll(/[ML]\s*[-\d.]+\s+([-\d.]+)/g)].map((m) => Number(m[1]));
+
+// Wraps after "aaaa bbbb" at 100 px (10 px glyphs in the fake measure).
+const text = {
+ kind: "text",
+ id: "t",
+ text: "aaaa bbbb cccc",
+ x: 0,
+ y: 0,
+ width: 100,
+ fontSize: 20,
+ fontFamily: "Inter",
+};
+
+describe("Annotate", () => {
+ it("underlines a wrapped phrase with one stroke per line, under each baseline", () => {
+ const a = make()({
+ target: { text, match: "bbbb cccc" },
+ mark: "underline",
+ hand: false,
+ padding: 8,
+ });
+ const s = strokes(a);
+ expect(s).toHaveLength(2);
+ const [y0, y1] = s.map((n) => ys(n.d)[0] as number);
+ // Lines are 24 px tall: baseline ≈ 0.84 of it, plus 40 % of the padding.
+ expect(y0).toBeCloseTo(24 * 0.84 + 3.2, 1);
+ expect((y1 as number) - (y0 as number)).toBeCloseTo(24, 5);
+ });
+
+ it("draws strokes one after another and reports when it's drawn", () => {
+ const a = make()({
+ target: { text, match: "bbbb cccc" },
+ hand: false,
+ drawDuration: 20,
+ });
+ const [first, second] = strokes(a).map((n) => keys(n, "trimEnd"));
+ expect(first?.[0]?.frame).toBe(0);
+ expect(second?.[0]?.frame).toBe(first?.[1]?.frame);
+ expect(a.cues.drawn[0]?.frame).toBe(20);
+ });
+
+ it("boils hand-drawn marks on a fixed beat, the same for the same seed", () => {
+ const make1 = () =>
+ make()({
+ target: { x: 0, y: 0, width: 100, height: 40 },
+ mark: "circle",
+ hand: { wobble: 1, boil: 4 },
+ seed: 3,
+ });
+ const d = keys(strokes(make1())[0] as Node, "d");
+ expect(d.slice(0, 4).map((k) => k.frame)).toEqual([0, 4, 8, 12]);
+ expect(d.every((k) => k.ease?.name === "hold")).toBe(true);
+ expect(d.map((k) => k.value)).toEqual(
+ keys(strokes(make1())[0] as Node, "d").map((k) => k.value),
+ );
+ });
+
+ it("points arrows from `from` and keeps the tail inside its box", () => {
+ const a = make()({
+ target: { x: 100, y: 100, width: 50, height: 50 },
+ mark: "arrow",
+ from: [600, 500],
+ });
+ expect(a.part("head")).toBeDefined();
+ const shaft = a.part("stroke-0") as unknown as {
+ width: number;
+ height: number;
+ };
+ expect(shaft.width).toBeGreaterThan(600);
+ expect(shaft.height).toBeGreaterThan(500);
+ expect(() => make()({ target: [0, 0], mark: "arrow" })).toThrow(
+ /needs `from`/,
+ );
+ });
+
+ it("labels after drawing, stays up, and refuses moving targets", () => {
+ const a = make()({
+ target: { x: 200, y: 200, width: 80, height: 30 },
+ mark: "box",
+ label: "note",
+ });
+ expect(a.cues.labelIn[0]?.frame).toBeLessThanOrEqual(
+ a.cues.drawn[0]?.frame ?? 0,
+ );
+ expect(a.span.end).toBe(Number.POSITIVE_INFINITY);
+ expect(() => make()({ target: () => [0, 0] })).toThrow(/must be static/);
+ });
+});
diff --git a/packages/components/src/annotate/index.ts b/packages/components/src/annotate/index.ts
new file mode 100644
index 00000000..e70e7516
--- /dev/null
+++ b/packages/components/src/annotate/index.ts
@@ -0,0 +1,501 @@
+/**
+ * Annotate: marks that draw on to point at something. Underline a phrase,
+ * circle a number, strike a claim, box a region, draw an arrow; clean
+ * geometry or hand-drawn, with a boil that keeps hand-drawn marks alive.
+ *
+ * Coordinates are the parent's: the root sits at 0, 0, so targets resolve
+ * where they are drawn. Text targets give one mark per line.
+ */
+import {
+ LayerAnimation,
+ type LayoutNode,
+} from "@framefields/compositions/program";
+import { z } from "zod";
+import { defineComponent } from "../core/contract.js";
+import {
+ type ArrowCurve,
+ arrowPaths,
+ boilKeys,
+ boxPath,
+ ellipsePath,
+ linePath,
+ type Rect,
+ squigglePath,
+ wobblePoints,
+} from "../core/draw.js";
+import type { Animatable } from "../core/host.js";
+import { toPathData, type Vec2 } from "../core/path.js";
+import { targetSchema } from "../core/schemas.js";
+import {
+ anchorPoint,
+ boundsOf,
+ resolveTarget,
+ type Target,
+} from "../core/targets.js";
+import { contrastRatio, themeFrames } from "../core/theme.js";
+import { scaleFrames } from "../core/timing.js";
+
+export const MARKS = [
+ "underline",
+ "circle",
+ "box",
+ "highlight",
+ "strike",
+ "cross",
+ "bracket",
+ "arrow",
+ "squiggle",
+] as const;
+export type Mark = (typeof MARKS)[number];
+
+const TEXTURE = {
+ /** Even, confident line. */
+ ink: { width: 1, opacity: 1 },
+ /** Broad felt tip. */
+ marker: { width: 1.5, opacity: 0.94 },
+ /** Thin and light. */
+ pencil: { width: 0.55, opacity: 0.85 },
+} as const;
+
+export interface AnnotateCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ /** The mark is fully drawn. */
+ drawn: ReadonlyArray<{ frame: number }>;
+ /** The label starts to appear (empty without a label). */
+ labelIn: ReadonlyArray<{ frame: number }>;
+}
+
+/** One stroke of a mark: its path for a boil variant, and a length for pacing. */
+interface Stroke {
+ path(variant: number): string;
+ length: number;
+ kind: "line" | "fill" | "head";
+}
+
+export const annotate = /* @__PURE__ */ defineComponent({
+ name: "Annotate",
+ props: () => ({
+ /** What to mark. Rects (e.g. `TextReveal.rects("word")`) give one mark per rect for line marks. */
+ target: z.union([
+ z.array(
+ z.object({
+ x: z.number(),
+ y: z.number(),
+ width: z.number(),
+ height: z.number(),
+ }),
+ ),
+ targetSchema(),
+ ]),
+ mark: z.enum(MARKS).default("underline"),
+ /** Where an arrow starts (it points at `target`). */
+ from: targetSchema().optional(),
+ curve: z.enum(["straight", "arc", "swoop"]).default("arc"),
+ color: z.string().optional(),
+ /** Stroke width before the texture's factor. Default the theme's bold stroke. */
+ width: z.number().positive().optional(),
+ /** `wobble` 0–1 (how loose the hand is); `boil`: frames between re-poses, 0 = still. */
+ hand: z
+ .union([
+ z.literal(false),
+ z
+ .object({
+ wobble: z.number().min(0).max(1).default(0.6),
+ boil: z.number().int().min(0).default(4),
+ seed: z.number().int().optional(),
+ })
+ .strict(),
+ ])
+ .default({ wobble: 0.6, boil: 4 }),
+ texture: z.enum(["ink", "marker", "pencil"]).default("marker"),
+ /** Frames the mark takes to draw. Default the theme's base speed (× 1.5 for arrows). */
+ drawDuration: z.number().int().positive().optional(),
+ label: z
+ .union([
+ z.string(),
+ z
+ .object({
+ text: z.string(),
+ side: z
+ .enum(["auto", "top", "bottom", "left", "right"])
+ .default("auto"),
+ font: z.string().optional(),
+ size: z.number().positive().optional(),
+ })
+ .strict(),
+ ])
+ .optional(),
+ /** Space between the target and the mark. */
+ padding: z.number().min(0).default(8),
+ }),
+ defaults: { enter: false, exit: false, hold: 45 },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const s = theme.scale;
+ const pad = props.padding * s;
+ const hand = props.hand === false ? null : props.hand;
+ const wobble = (hand?.wobble ?? 0) * 5 * s;
+ const seed = hand?.seed ?? ctx.seed;
+ const texture = TEXTURE[props.texture];
+ const strokeW = (props.width ?? theme.stroke.bold * s) * texture.width;
+ const color = props.color ?? theme.color.highlight;
+
+ // ── Geometry ─────────────────────────────────────────────────────
+ const resolve = (t: Target) => {
+ const r = resolveTarget(t, { measure: host.measure, fps });
+ if (r.kind !== "static")
+ throw new Error(
+ "Annotate: targets must be static (points, rects, nodes, text). Moving targets arrive with Callout.",
+ );
+ return r;
+ };
+ const isRects =
+ Array.isArray(props.target) && typeof props.target[0] === "object";
+ const resolved = isRects ? null : resolve(props.target as Target);
+ const rects: Rect[] = isRects
+ ? (props.target as Rect[])
+ : (resolved?.rects ?? []);
+ if (rects.length === 0)
+ throw new Error("Annotate: the target covers nothing.");
+ const isText =
+ isRects ||
+ (typeof props.target === "object" &&
+ props.target !== null &&
+ "text" in (props.target as object));
+ const b = boundsOf(rects);
+ const hw = { wobble, seed };
+
+ const strokes: Stroke[] = [];
+ /** Points outside the target the strokes reach (an arrow's tail). */
+ const reach: Vec2[] = [];
+ const lineAt = (y: (r: Rect) => number, extend: number) =>
+ rects.forEach((r) => {
+ const from: Vec2 = [r.x - extend, y(r)];
+ const to: Vec2 = [r.x + r.width + extend, y(r)];
+ strokes.push({
+ path: (v) => linePath(from, to, hw, v + strokes.length * 7),
+ length: to[0] - from[0],
+ kind: "line",
+ });
+ });
+ // Text rects are a line tall: the baseline sits near 80 % of it.
+ const under = (r: Rect) =>
+ isText ? r.y + r.height * 0.84 + pad * 0.4 : r.y + r.height + pad;
+
+ switch (props.mark) {
+ case "underline":
+ lineAt(under, pad * 0.25);
+ break;
+ case "strike":
+ lineAt((r) => r.y + r.height * (isText ? 0.54 : 0.5), pad * 0.4);
+ break;
+ case "squiggle":
+ rects.forEach((r, i) => {
+ const from: Vec2 = [r.x, under(r)];
+ const to: Vec2 = [r.x + r.width, under(r)];
+ strokes.push({
+ path: (v) =>
+ squigglePath(
+ from,
+ to,
+ { ...hw, amplitude: 4 * s + strokeW * 0.4 },
+ v + i * 7,
+ ),
+ length: r.width * 1.3,
+ kind: "line",
+ });
+ });
+ break;
+ case "highlight":
+ rects.forEach((r, i) => {
+ const y = r.y + r.height * (isText ? 0.56 : 0.5);
+ const from: Vec2 = [r.x - pad * 0.4, y];
+ const to: Vec2 = [r.x + r.width + pad * 0.4, y];
+ strokes.push({
+ path: (v) =>
+ linePath(from, to, { ...hw, wobble: wobble * 0.5 }, v + i * 7),
+ length: to[0] - from[0],
+ kind: "fill",
+ });
+ });
+ break;
+ case "circle":
+ strokes.push({
+ path: (v) => ellipsePath(b, { ...hw, padding: pad * 1.5 }, v),
+ length: Math.PI * (b.width + b.height + pad * 3),
+ kind: "line",
+ });
+ break;
+ case "box":
+ strokes.push({
+ path: (v) => boxPath(b, { ...hw, padding: pad }, v),
+ length: 2 * (b.width + b.height + pad * 4),
+ kind: "line",
+ });
+ break;
+ case "cross": {
+ const x0 = b.x - pad;
+ const y0 = b.y - pad;
+ const x1 = b.x + b.width + pad;
+ const y1 = b.y + b.height + pad;
+ const d = Math.hypot(x1 - x0, y1 - y0);
+ strokes.push(
+ {
+ path: (v) => linePath([x0, y0], [x1, y1], hw, v),
+ length: d,
+ kind: "line",
+ },
+ {
+ path: (v) => linePath([x1, y0], [x0, y1], hw, v + 11),
+ length: d,
+ kind: "line",
+ },
+ );
+ break;
+ }
+ case "bracket": {
+ const x = b.x - pad * 1.5;
+ const lip = Math.min(18 * s, b.height * 0.2);
+ const pts: Vec2[] = [
+ [x + lip, b.y - pad * 0.5],
+ [x, b.y - pad * 0.5],
+ [x, b.y + b.height + pad * 0.5],
+ [x + lip, b.y + b.height + pad * 0.5],
+ ];
+ strokes.push({
+ path: (v) => toPathData(wobblePoints(densify(pts, 6), hw, v)),
+ length: b.height + lip * 2 + pad,
+ kind: "line",
+ });
+ break;
+ }
+ case "arrow": {
+ if (!props.from)
+ throw new Error('Annotate: mark "arrow" needs `from`.');
+ const start = resolve(props.from);
+ const tail = anchorPoint(boundsOf(start.rects), start.anchor);
+ const tip = edgeToward(b, tail, pad);
+ reach.push(tail);
+ const headSize =
+ (14 * s + strokeW * 1.6) * (props.texture === "pencil" ? 0.8 : 1);
+ const geometry = (v: number) =>
+ arrowPaths(
+ tail,
+ tip,
+ { ...hw, curve: props.curve as ArrowCurve, headSize },
+ v,
+ );
+ const length = Math.hypot(tip[0] - tail[0], tip[1] - tail[1]);
+ strokes.push(
+ { path: (v) => geometry(v).shaft, length, kind: "line" },
+ { path: (v) => geometry(v).head, length: headSize * 2, kind: "head" },
+ );
+ break;
+ }
+ }
+
+ // ── Timing ───────────────────────────────────────────────────────
+ const drawFrames =
+ props.drawDuration ??
+ Math.round(
+ themeFrames(theme, "base", fps) * (props.mark === "arrow" ? 1.5 : 1.2),
+ );
+ const bodies = strokes.filter((st) => st.kind !== "head");
+ const total = bodies.reduce((a, st) => a + Math.max(1, st.length), 0);
+ let cursor = 0;
+ const windows: Array<{ start: number; end: number }> = [];
+ for (const st of strokes) {
+ const prev = windows[windows.length - 1];
+ if (st.kind === "head" && prev) {
+ // The head flicks on as the shaft reaches 92 %.
+ const start = Math.round(prev.start + (prev.end - prev.start) * 0.92);
+ windows.push({ start, end: start + Math.max(3, scaleFrames(5, fps)) });
+ continue;
+ }
+ const start = Math.round(cursor);
+ cursor += (drawFrames * Math.max(1, st.length)) / total;
+ windows.push({ start, end: Math.max(start + 2, Math.round(cursor)) });
+ }
+ const drawn = Math.max(...windows.map((w) => w.end));
+
+ // ── Nodes ────────────────────────────────────────────────────────
+ const lightBg =
+ (contrastRatio(theme.color.bg, "#000000") ?? 0) >
+ (contrastRatio(theme.color.bg, "#ffffff") ?? 0);
+ // The shapes' box must hold every stroke, or the renderer clips it.
+ const margin = pad * 4 + strokeW * 4;
+ const extentX = Math.max(b.x + b.width, ...reach.map((p) => p[0])) + margin;
+ const extentY =
+ Math.max(b.y + b.height, ...reach.map((p) => p[1])) + margin;
+ const boil =
+ hand && hand.boil > 0 && wobble > 0 ? scaleFrames(hand.boil, fps) : 0;
+ // Marks stay up: boil through the window, or a while past the hold.
+ const boilEnd =
+ (props as { duration?: number }).duration ??
+ drawn + Math.max(ctx.hold, fps * 6);
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+ const children: LayoutNode[] = [];
+ let maxX = extentX;
+ let maxY = extentY;
+
+ strokes.forEach((st, i) => {
+ const w = windows[i] as { start: number; end: number };
+ const fill = st.kind === "fill";
+ const rect = rects[i] ?? b;
+ const node = host.shape("path", {
+ id: ctx.partId(st.kind === "head" ? "head" : `stroke-${i}`),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: extentX,
+ height: extentY,
+ d: st.path(0),
+ fillType: "none",
+ strokeColor: color,
+ strokeWidth: fill ? rect.height * (isText ? 0.62 : 1) : strokeW,
+ strokeLineCap: fill ? "butt" : "round",
+ strokeLineJoin: "round",
+ trimEnd: 0,
+ opacity: fill ? (lightBg ? 0.9 : 0.38) : texture.opacity,
+ ...(fill && lightBg && { blendMode: "multiply" }),
+ });
+ const anim = LayerAnimation.create().keys("trimEnd", [
+ [w.start, 0],
+ [w.end, 1, st.kind === "head" ? "power2.out" : "power2.inOut"],
+ ]);
+ if (boil > 0)
+ anim.keys(
+ "d",
+ boilKeys(st.path, { start: 0, end: boilEnd, every: boil }),
+ );
+ node.animate(anim);
+ parts[st.kind === "head" ? "head" : `stroke-${i}`] = node;
+ children.push(node);
+ });
+
+ // ── Label ────────────────────────────────────────────────────────
+ let labelIn: number | null = null;
+ if (props.label !== undefined) {
+ const o =
+ typeof props.label === "string"
+ ? { text: props.label, side: "auto" as const }
+ : props.label;
+ const font =
+ ("font" in o && o.font) || theme.font.hand || theme.font.body;
+ const size = ("size" in o && o.size) || 34 * s;
+ const m = host.measure(o.text, { fontFamily: font, fontSize: size });
+ const gap = 10 * s + pad;
+ let x: number;
+ let y: number;
+ if (props.mark === "arrow" && props.from) {
+ const start = resolve(props.from);
+ const tail = anchorPoint(boundsOf(start.rects), start.anchor);
+ const tip = edgeToward(b, tail, pad);
+ const len = Math.hypot(tip[0] - tail[0], tip[1] - tail[1]) || 1;
+ const dx = (tip[0] - tail[0]) / len;
+ const dy = (tip[1] - tail[1]) / len;
+ const reach =
+ Math.abs(dx) * (m.width / 2) +
+ Math.abs(dy) * (m.height / 2) +
+ gap * 0.5;
+ x = tail[0] - dx * reach - m.width / 2;
+ y = tail[1] - dy * reach - m.height / 2;
+ } else {
+ const side =
+ o.side === "auto"
+ ? b.y - gap - m.height >= 0
+ ? "top"
+ : "bottom"
+ : o.side;
+ const top = props.mark === "circle" ? pad * 1.5 : pad;
+ x =
+ side === "left"
+ ? b.x - top - gap - m.width
+ : side === "right"
+ ? b.x + b.width + top + gap
+ : b.x + b.width - m.width;
+ y =
+ side === "top"
+ ? b.y - top - gap - m.height
+ : side === "bottom"
+ ? b.y + b.height + top + gap
+ : b.y + (b.height - m.height) / 2;
+ }
+ const label = host.text(o.text, {
+ id: ctx.partId("label"),
+ position: "absolute",
+ x,
+ y,
+ fontFamily: font,
+ fontSize: size,
+ fill: props.mark === "highlight" ? theme.color.ink : color,
+ });
+ labelIn = Math.max(0, drawn - scaleFrames(4, fps));
+ const intro = scaleFrames(10, fps);
+ label.animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [labelIn, 0],
+ [labelIn + intro, 1, "power2.out"],
+ ])
+ .keys("y", [
+ [labelIn, y + 8 * s],
+ [labelIn + intro, y, theme.motion.ease.enter],
+ ]),
+ );
+ parts.label = label;
+ children.push(label);
+ maxX = Math.max(maxX, x + m.width + 8);
+ maxY = Math.max(maxY, y + m.height + 8);
+ }
+
+ return {
+ children,
+ width: maxX,
+ height: maxY,
+ duration: Math.max(
+ drawn,
+ labelIn === null ? 0 : labelIn + scaleFrames(10, fps),
+ ),
+ openEnded: true,
+ origin: [0, 0],
+ cues: {
+ drawn: [{ frame: drawn }],
+ labelIn: labelIn === null ? [] : [{ frame: labelIn }],
+ } as AnnotateCues,
+ parts,
+ };
+ },
+});
+
+/** Where a mark around `rect` (+ gap) meets the line toward `from`. */
+function edgeToward(rect: Rect, from: Vec2, gap: number): Vec2 {
+ const cx = rect.x + rect.width / 2;
+ const cy = rect.y + rect.height / 2;
+ const dx = from[0] - cx;
+ const dy = from[1] - cy;
+ const hx = rect.width / 2 + gap;
+ const hy = rect.height / 2 + gap;
+ const t = Math.min(
+ dx === 0 ? Number.POSITIVE_INFINITY : hx / Math.abs(dx),
+ dy === 0 ? Number.POSITIVE_INFINITY : hy / Math.abs(dy),
+ );
+ return Number.isFinite(t) ? [cx + dx * t, cy + dy * t] : [cx, cy - hy];
+}
+
+/** Extra points along each segment, so a wobble bends lines instead of corners only. */
+function densify(points: readonly Vec2[], per: number): Vec2[] {
+ const out: Vec2[] = [];
+ points.forEach((p, i) => {
+ const next = points[i + 1];
+ if (!next) {
+ out.push(p);
+ return;
+ }
+ for (let k = 0; k < per; k++) {
+ const t = k / per;
+ out.push([p[0] + (next[0] - p[0]) * t, p[1] + (next[1] - p[1]) * t]);
+ }
+ });
+ return out;
+}
diff --git a/packages/components/src/annotate/meta.ts b/packages/components/src/annotate/meta.ts
new file mode 100644
index 00000000..d6805d12
--- /dev/null
+++ b/packages/components/src/annotate/meta.ts
@@ -0,0 +1,19 @@
+import { defineMeta } from "../core/meta.js";
+
+export default defineMeta({
+ name: "Annotate",
+ summary:
+ "Marks that draw on to point at something: underline, circle, box, highlight, strike, cross, bracket, arrow or squiggle, clean or hand-drawn with a boil, with an optional label.",
+ tags: [
+ "annotation",
+ "underline",
+ "highlight",
+ "arrow",
+ "hand-drawn",
+ "explainer",
+ ],
+ parts: ["stroke-<n>", "head", "label"],
+ cues: ["drawn", "labelIn"],
+ example: `Annotate({ target: { text: headline, match: "faster" }, mark: "circle" })`,
+ since: "M2",
+});
diff --git a/packages/components/src/app-frame/index.test.ts b/packages/components/src/app-frame/index.test.ts
new file mode 100644
index 00000000..ace61a09
--- /dev/null
+++ b/packages/components/src/app-frame/index.test.ts
@@ -0,0 +1,72 @@
+import type { LayoutNode } from "@framefields/compositions/program";
+import { describe, expect, it } from "vitest";
+import { bind } from "../core/contract.js";
+import { fakeHost } from "../test/fake-host.js";
+import { appFrame } from "./index.js";
+
+const make = () => bind(fakeHost(), appFrame);
+const kids = (n: unknown) =>
+ ((n as { children?: LayoutNode[] }).children ?? []) as LayoutNode[];
+
+describe("AppFrame", () => {
+ it("maps content pixels into the parent's coordinates", () => {
+ const f = make()({
+ kind: "browser",
+ x: 100,
+ y: 50,
+ width: 1200,
+ height: 800,
+ });
+ expect(f.contentRect).toEqual({ x: 100, y: 106, width: 1200, height: 744 });
+ expect(f.at(10, 20)).toEqual([110, 126]);
+ const window = make()({ kind: "window", x: 0, y: 0 });
+ expect(window.contentRect.y).toBe(46);
+ const bare = make()({ kind: "minimal", x: 0, y: 0 });
+ expect(bare.contentRect.y).toBe(0);
+ });
+
+ it("is open-ended unless given a duration", () => {
+ const f = make()({});
+ expect(f.durationFrames).toBeUndefined();
+ expect(f.span.end).toBe(Number.POSITIVE_INFINITY);
+ expect(() => make()({ exit: "fade" })).toThrow(/exit needs a known end/);
+ expect(make()({ duration: 90, exit: "fade" }).durationFrames).toBe(90);
+ });
+
+ it("accepts content late with fill()", () => {
+ const f = make()({ x: 0, y: 0 });
+ f.fill({ kind: "box", id: "late" } as LayoutNode);
+ expect(kids(f.part("content")).map((c) => c.id)).toEqual(["late"]);
+ });
+
+ it("types the URL, then loads", () => {
+ const f = make()({
+ kind: "browser",
+ url: { text: "acme.dev", typeAt: 10, cps: 30 },
+ });
+ expect(f.cues.urlTyped).toEqual([{ frame: 18 }]);
+ expect(f.cues.loaded[0]?.frame).toBeGreaterThan(18);
+ expect(f.part("caret")).toBeDefined();
+ });
+
+ it("puts the shadow on its own plate under the clipping chrome", () => {
+ const f = make()({ elevation: 3 });
+ const stage = kids(f.part("stage"));
+ expect(stage.map((c) => c.id.split("-").at(-1))).toEqual([
+ "shadow",
+ "chrome",
+ ]);
+ expect(
+ (f.part("shadow") as unknown as { styles: unknown[] }).styles,
+ ).toHaveLength(1);
+ expect(make()({ elevation: 0 }).part("shadow")).toBeUndefined();
+ });
+
+ it("wraps media paths", () => {
+ const f = make()({ content: "rec.mp4" });
+ expect(kids(f.part("content"))[0]).toMatchObject({
+ kind: "media",
+ source: "rec.mp4",
+ });
+ });
+});
diff --git a/packages/components/src/app-frame/index.ts b/packages/components/src/app-frame/index.ts
new file mode 100644
index 00000000..0db39c49
--- /dev/null
+++ b/packages/components/src/app-frame/index.ts
@@ -0,0 +1,583 @@
+/**
+ * AppFrame: window chrome around any content (a recording, a mock UI, a
+ * still): a desktop window, a browser with a URL bar, a terminal, or a bare
+ * rounded frame. It is also the coordinate system for what points at the
+ * content: `frame.at(x, y)` maps content pixels to the parent's.
+ */
+import {
+ type AnimatableProp,
+ type KeyframeTuple,
+ LayerAnimation,
+ type LayoutNode,
+} from "@framefields/compositions/program";
+import { z } from "zod";
+import { defineComponent } from "../core/contract.js";
+import type { Animatable } from "../core/host.js";
+import type { Vec2 } from "../core/path.js";
+import { contrastRatio } from "../core/theme.js";
+
+const KINDS = ["window", "browser", "terminal", "minimal"] as const;
+export type AppFrameKind = (typeof KINDS)[number];
+
+export interface AppFrameCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ /** The URL finished typing (browser with `url.typeAt`). */
+ urlTyped: ReadonlyArray<{ frame: number }>;
+ /** The load bar finished. */
+ loaded: ReadonlyArray<{ frame: number }>;
+}
+
+export interface AppFrameApi {
+ /** The content area in the parent's coordinates. */
+ readonly contentRect: { x: number; y: number; width: number; height: number };
+ /** Content-local (x, y) → the parent's coordinates. */
+ at(x: number, y: number): Vec2;
+ /** Add layers to the content area (after creation, e.g. once cues are known). */
+ fill(...nodes: LayoutNode[]): AppFrameApi;
+}
+
+/** Chrome palettes, tuned to sit with real app UIs. */
+const PALETTES = {
+ dark: {
+ chrome: "#1b1c20",
+ field: "#26272c",
+ line: "#2e3036",
+ edge: "#3a3c44",
+ text: "#e8e8ec",
+ muted: "#8d8f99",
+ content: "#111215",
+ },
+ light: {
+ chrome: "#f2f2f4",
+ field: "#ffffff",
+ line: "#e1e1e6",
+ edge: "#d4d4da",
+ text: "#1c1c1f",
+ muted: "#7d7e87",
+ content: "#ffffff",
+ },
+} as const;
+
+const LIGHTS = ["#ff5f57", "#febc2e", "#28c840"] as const;
+
+export const appFrame = /* @__PURE__ */ defineComponent({
+ name: "AppFrame",
+ props: () => ({
+ kind: z.enum(KINDS).default("window"),
+ /** What the frame shows: layers (laid out in content pixels) or a media path. */
+ content: z
+ .custom<LayoutNode | LayoutNode[] | string>(
+ (v) =>
+ typeof v === "string" ||
+ Array.isArray(v) ||
+ (typeof v === "object" && v !== null),
+ { message: "Expected a layer, an array of layers, or a media path" },
+ )
+ .optional(),
+ /** How media content fits the content area. */
+ fit: z.enum(["cover", "contain", "fill"]).default("cover"),
+ title: z.string().optional(),
+ /** Browser address. `typeAt` (local frame) types it in and plays a load bar. */
+ url: z
+ .union([
+ z.string(),
+ z
+ .object({
+ text: z.string(),
+ typeAt: z.number().int().min(0).optional(),
+ /** Characters per second while typing. */
+ cps: z.number().positive().default(22),
+ })
+ .strict(),
+ ])
+ .optional(),
+ /** Browser tabs; the first is active. */
+ tabs: z.array(z.string()).optional(),
+ /** Chrome colors. Default: follows the theme background. */
+ appearance: z.enum(["dark", "light"]).optional(),
+ /** Content-area background. Default: the appearance's. */
+ contentBackground: z.string().optional(),
+ /** Shadow depth, 0 (flat) to 3 (floating). */
+ elevation: z.number().int().min(0).max(3).default(2),
+ /** Corner radius in px. Default 14 × theme.scale. */
+ radius: z.number().min(0).optional(),
+ /** Present the frame at a 3D angle. */
+ tilt: z
+ .union([
+ z.literal(false),
+ z
+ .object({
+ rotateX: z.number().default(8),
+ rotateY: z.number().default(-12),
+ })
+ .strict(),
+ ])
+ .default(false),
+ }),
+ defaults: { enter: "rise" },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const s = theme.scale;
+ const width = ctx.requested.width ?? 1440 * s;
+ const height = ctx.requested.height ?? 900 * s;
+ const dark =
+ props.appearance === "dark" ||
+ (props.appearance === undefined &&
+ (contrastRatio(theme.color.bg, "#000000") ?? 1) < 4);
+ const pal = dark ? PALETTES.dark : PALETTES.light;
+ const radius = props.radius ?? 14 * s;
+ const hasTabs = props.kind === "browser" && (props.tabs?.length ?? 0) > 0;
+ const barH =
+ props.kind === "minimal"
+ ? 0
+ : props.kind === "browser"
+ ? (hasTabs ? 92 : 56) * s
+ : props.kind === "terminal"
+ ? 40 * s
+ : 46 * s;
+
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+ const cues = {
+ urlTyped: [] as Array<{ frame: number }>,
+ loaded: [] as Array<{ frame: number }>,
+ };
+ const font = theme.font.body;
+
+ // Content is laid out from the bar down, in content pixels.
+ const build = (W: number, H: number) => {
+ const bar: LayoutNode[] = [];
+ const lightsY = (hasTabs ? 46 * s : barH) / 2;
+ if (props.kind !== "minimal") {
+ LIGHTS.forEach((color, i) => {
+ bar.push(
+ host.shape("circle", {
+ id: ctx.partId(`light-${i}`),
+ position: "absolute",
+ x: 20 * s + i * 20 * s,
+ y: lightsY - 6 * s,
+ width: 12 * s,
+ height: 12 * s,
+ fillColor: color,
+ }),
+ );
+ });
+ }
+
+ if (props.kind === "browser") {
+ const rowY = hasTabs ? 46 * s : 0;
+ const rowH = hasTabs ? barH - 46 * s : barH;
+ if (hasTabs)
+ bar.push(
+ ...tabStrip(ctx, props.tabs ?? [], {
+ x: 92 * s,
+ H: 46 * s,
+ s,
+ pal,
+ font,
+ W,
+ }),
+ );
+ // Back / forward.
+ const navX = hasTabs ? 20 * s : 92 * s;
+ [0, 1].forEach((i) => {
+ const cx = navX + i * 30 * s + 8 * s;
+ const cy = rowY + rowH / 2;
+ const dir = i === 0 ? -1 : 1;
+ bar.push(
+ host.shape("path", {
+ id: ctx.partId(`nav-${i}`),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: barH,
+ d: `M${cx - dir * 3 * s} ${cy - 6 * s} L${cx + dir * 3 * s} ${cy} L${cx - dir * 3 * s} ${cy + 6 * s}`,
+ fillType: "none",
+ fillColor: pal.muted,
+ strokeColor: i === 0 ? pal.muted : pal.edge,
+ strokeWidth: 1.8 * s,
+ strokeLineCap: "round",
+ strokeLineJoin: "round",
+ }),
+ );
+ });
+ if (props.url !== undefined) {
+ bar.push(
+ ...urlField(ctx, props.url, {
+ W,
+ rowY,
+ rowH,
+ s,
+ pal,
+ font,
+ fps,
+ cues,
+ accent: theme.color.accent,
+ parts,
+ }),
+ );
+ }
+ } else if (props.title) {
+ bar.push(
+ host.text(props.title, {
+ id: ctx.partId("title"),
+ position: "absolute",
+ x: 0,
+ y: barH / 2 - 9 * s,
+ width: W,
+ align: "center",
+ fontFamily: props.kind === "terminal" ? theme.font.mono : font,
+ fontSize: 13 * s,
+ fontWeight: 500,
+ fill: pal.muted,
+ }),
+ );
+ }
+
+ const contentChildren: LayoutNode[] =
+ props.content === undefined
+ ? []
+ : typeof props.content === "string"
+ ? [
+ host.media(props.content, {
+ id: ctx.partId("media"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H - barH,
+ fit: props.fit,
+ }),
+ ]
+ : Array.isArray(props.content)
+ ? props.content
+ : [props.content];
+ const content = host.box({
+ id: ctx.partId("content"),
+ position: "absolute",
+ x: 0,
+ y: barH,
+ width: W,
+ height: H - barH,
+ background:
+ props.contentBackground ??
+ (props.kind === "terminal" ? "#0c0c0e" : pal.content),
+ overflow: "hidden",
+ children: contentChildren,
+ });
+ const chrome = host.box({
+ id: ctx.partId("chrome"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ background: props.kind === "terminal" ? "#16161a" : pal.chrome,
+ borderRadius: radius,
+ borderColor: pal.edge,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ overflow: "hidden",
+ children: [
+ ...(barH > 0
+ ? [
+ host.box({
+ id: ctx.partId("bar"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: barH,
+ children: bar,
+ }),
+ host.box({
+ id: ctx.partId("divider"),
+ position: "absolute",
+ x: 0,
+ y: barH - 1,
+ width: W,
+ height: 1,
+ background: pal.line,
+ }),
+ ]
+ : []),
+ content,
+ ],
+ });
+ const children: LayoutNode[] = [];
+ if (props.elevation > 0) {
+ const e = props.elevation;
+ // The shadow lives on its own plate: the chrome clips its content.
+ const plate = host.box({
+ id: ctx.partId("shadow"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ background: pal.chrome,
+ borderRadius: radius,
+ });
+ host.style(plate, {
+ dropShadow: {
+ color: "#000000",
+ opacity: [0, 0.3, 0.45, 0.6][e],
+ angle: 90,
+ distance: [0, 8, 22, 40][e],
+ size: [0, 22, 48, 80][e],
+ spread: 0,
+ },
+ });
+ children.push(plate);
+ parts.shadow = plate;
+ }
+ children.push(chrome);
+ Object.assign(parts, { chrome, content });
+ return { children, content };
+ };
+
+ return {
+ width,
+ height,
+ duration: null,
+ cues: cues as AppFrameCues,
+ parts,
+ children: build(width, height).children,
+ api: (placement): AppFrameApi => {
+ const content = parts.content as Animatable<LayoutNode> & {
+ children?: LayoutNode[];
+ };
+ const rect = {
+ x: placement.x,
+ y: placement.y + barH,
+ width: placement.width,
+ height: placement.height - barH,
+ };
+ const api: AppFrameApi = {
+ contentRect: rect,
+ at: (x, y) => [rect.x + x, rect.y + y],
+ fill: (...nodes) => {
+ content.children = [...(content.children ?? []), ...nodes];
+ return api;
+ },
+ };
+ return api;
+ },
+ };
+ },
+});
+
+function tabStrip(
+ ctx: Parameters<typeof appFrame.build>[0],
+ tabs: string[],
+ o: {
+ x: number;
+ H: number;
+ s: number;
+ pal: (typeof PALETTES)["dark" | "light"];
+ font: string;
+ W: number;
+ },
+): LayoutNode[] {
+ const { host } = ctx;
+ const out: LayoutNode[] = [];
+ let x = o.x;
+ tabs.forEach((label, i) => {
+ const active = i === 0;
+ const fontSize = 12.5 * o.s;
+ const m = host.measure(label, {
+ fontFamily: o.font,
+ fontSize,
+ fontWeight: 500,
+ });
+ const w = Math.min(240 * o.s, Math.max(120 * o.s, m.width + 40 * o.s));
+ out.push(
+ host.box({
+ id: ctx.partId(`tab-${i}`),
+ position: "absolute",
+ x,
+ y: 8 * o.s,
+ width: w,
+ height: o.H - 8 * o.s,
+ background: active ? o.pal.field : "transparent",
+ borderRadius: 9 * o.s,
+ children: [
+ host.text(label, {
+ id: ctx.partId(`tab-${i}-text`),
+ position: "absolute",
+ x: 14 * o.s,
+ y: (o.H - 8 * o.s) / 2 - fontSize * 0.62,
+ width: w - 28 * o.s,
+ fontFamily: o.font,
+ fontSize,
+ fontWeight: 500,
+ fill: active ? o.pal.text : o.pal.muted,
+ }),
+ ],
+ }),
+ );
+ x += w + 4 * o.s;
+ });
+ return out;
+}
+
+function urlField(
+ ctx: Parameters<typeof appFrame.build>[0],
+ url: string | { text: string; typeAt?: number; cps: number },
+ o: {
+ W: number;
+ rowY: number;
+ rowH: number;
+ s: number;
+ pal: (typeof PALETTES)["dark" | "light"];
+ font: string;
+ fps: number;
+ cues: {
+ urlTyped: Array<{ frame: number }>;
+ loaded: Array<{ frame: number }>;
+ };
+ accent: string;
+ parts: Record<string, Animatable<LayoutNode>>;
+ },
+): LayoutNode[] {
+ const { host } = ctx;
+ const text = typeof url === "string" ? url : url.text;
+ const fieldW = Math.min(620 * o.s, o.W * 0.46);
+ const fieldH = 32 * o.s;
+ const fieldX = (o.W - fieldW) / 2;
+ const fieldY = o.rowY + (o.rowH - fieldH) / 2;
+ const fontSize = 13.5 * o.s;
+ const m = host.measure(text, { fontFamily: o.font, fontSize });
+ const lockW = 14 * o.s;
+ const textX = (fieldW - m.width - lockW) / 2 + lockW;
+ const out: LayoutNode[] = [];
+
+ const label = host.text(text, {
+ id: ctx.partId("url"),
+ position: "absolute",
+ x: textX,
+ y: fieldH / 2 - m.lineHeight / 2,
+ fontFamily: o.font,
+ fontSize,
+ fill: o.pal.text,
+ });
+ // A small padlock: shackle + body.
+ const lx = textX - lockW;
+ const ly = fieldH / 2;
+ const lock = host.shape("path", {
+ id: ctx.partId("lock"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: fieldW,
+ height: fieldH,
+ d: `M${lx + 2.2 * o.s} ${ly - 1 * o.s} L${lx + 2.2 * o.s} ${ly - 3.4 * o.s} C${lx + 2.2 * o.s} ${ly - 6.4 * o.s} ${lx + 7.8 * o.s} ${ly - 6.4 * o.s} ${lx + 7.8 * o.s} ${ly - 3.4 * o.s} L${lx + 7.8 * o.s} ${ly - 1 * o.s}`,
+ fillType: "none",
+ fillColor: o.pal.muted,
+ strokeColor: o.pal.muted,
+ strokeWidth: 1.4 * o.s,
+ strokeLineCap: "round",
+ });
+ const lockBody = host.box({
+ id: ctx.partId("lock-body"),
+ position: "absolute",
+ x: lx + 0.6 * o.s,
+ y: ly - 1.4 * o.s,
+ width: 8.8 * o.s,
+ height: 6.6 * o.s,
+ background: o.pal.muted,
+ borderRadius: 1.6 * o.s,
+ });
+ const fieldChildren: LayoutNode[] = [lock, lockBody, label];
+ o.parts.url = label;
+
+ if (typeof url === "object" && url.typeAt !== undefined) {
+ const perChar = Math.max(1, Math.round(o.fps / url.cps));
+ const start = url.typeAt;
+ // The text track is a reveal amount: ≤ 1 is a fraction, > 1 a count.
+ const keys: KeyframeTuple[] = [[0, 0]];
+ for (let i = 1; i <= text.length; i++) {
+ keys.push([start + i * perChar, i === 1 ? 1 / text.length : i, "hold"]);
+ }
+ label.animate(LayerAnimation.keys("text" as AnimatableProp, keys));
+ const typed = start + text.length * perChar;
+ // Caret follows the last typed glyph, then blinks a few times.
+ const caretKeys: KeyframeTuple[] = [[0, textX]];
+ for (let i = 1; i <= text.length; i++)
+ caretKeys.push([start + i * perChar, textX + m.caretX(i), "hold"]);
+ const caret = host.box({
+ id: ctx.partId("caret"),
+ position: "absolute",
+ x: textX,
+ y: fieldH / 2 - fontSize * 0.7,
+ width: 1.6 * o.s,
+ height: fontSize * 1.4,
+ background: o.accent,
+ });
+ const blink: KeyframeTuple[] = [
+ [0, 0],
+ [start, 1, "hold"],
+ ];
+ const half = Math.round(o.fps * 0.5);
+ for (
+ let f = typed + half, on = false;
+ f < typed + half * 6;
+ f += half, on = !on
+ )
+ blink.push([f, on ? 1 : 0, "hold"]);
+ blink.push([typed + half * 6, 0, "hold"]);
+ caret.animate(
+ LayerAnimation.keys("x", caretKeys),
+ LayerAnimation.keys("opacity", blink),
+ );
+ fieldChildren.push(caret);
+ o.parts.caret = caret;
+ o.cues.urlTyped.push({ frame: typed });
+
+ // Load bar along the bottom of the toolbar after "enter".
+ const loadStart = typed + Math.round(o.fps * 0.15);
+ const loadEnd = loadStart + Math.round(o.fps * 0.9);
+ const bar = host.box({
+ id: ctx.partId("load"),
+ position: "absolute",
+ x: 0,
+ y: o.rowY + o.rowH - 2 * o.s,
+ width: 0,
+ height: 2 * o.s,
+ background: o.accent,
+ });
+ bar.animate(
+ LayerAnimation.keys("width", [
+ [0, 0],
+ [loadStart, 0, "hold"],
+ [loadStart + Math.round(o.fps * 0.35), o.W * 0.62, "power2.out"],
+ [loadEnd, o.W, "power3.inOut"],
+ ]),
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [loadStart, 1, "hold"],
+ [loadEnd, 1],
+ [loadEnd + Math.round(o.fps * 0.3), 0, "power2.out"],
+ ]),
+ );
+ out.push(bar);
+ o.parts.load = bar;
+ o.cues.loaded.push({ frame: loadEnd });
+ }
+
+ const field = host.box({
+ id: ctx.partId("url-field"),
+ position: "absolute",
+ x: fieldX,
+ y: fieldY,
+ width: fieldW,
+ height: fieldH,
+ background: o.pal.field,
+ borderRadius: 9 * o.s,
+ overflow: "hidden",
+ children: fieldChildren,
+ });
+ o.parts["url-field"] = field;
+ out.unshift(field);
+ return out;
+}
diff --git a/packages/components/src/app-frame/meta.ts b/packages/components/src/app-frame/meta.ts
new file mode 100644
index 00000000..3976295f
--- /dev/null
+++ b/packages/components/src/app-frame/meta.ts
@@ -0,0 +1,24 @@
+import { defineMeta } from "../core/meta.js";
+
+export default defineMeta({
+ name: "AppFrame",
+ summary:
+ "Window chrome around any content — desktop window, browser with a typed URL, terminal, or bare frame — and the coordinate system for pointing into it.",
+ tags: ["window", "browser", "mockup", "ui", "screen recording", "device"],
+ parts: [
+ "shadow",
+ "chrome",
+ "bar",
+ "divider",
+ "content",
+ "url-field",
+ "url",
+ "caret",
+ "load",
+ "tab-<n>",
+ "light-<n>",
+ ],
+ cues: ["urlTyped", "loaded"],
+ example: `AppFrame({ kind: "browser", url: "acme.dev", content: "assets/recording.mp4" })`,
+ since: "M1",
+});
diff --git a/packages/components/src/core/contract.test.ts b/packages/components/src/core/contract.test.ts
index aaa9f3d9..80345585 100644
--- a/packages/components/src/core/contract.test.ts
+++ b/packages/components/src/core/contract.test.ts
@@ -1,7 +1,8 @@
import { describe, expect, it } from "vitest";
+import { z } from "zod";
import { fakeHost } from "../test/fake-host.js";
import { probe } from "../test/probe.js";
-import { bind, pulseKeys } from "./contract.js";
+import { bind, defineComponent, pulseKeys } from "./contract.js";
const make = () => bind(fakeHost(), probe);
@@ -129,3 +130,57 @@ describe("pulseKeys", () => {
]);
});
});
+
+describe("component lifetimes", () => {
+ const settles = (o: { openEnded?: boolean; afterHold?: number }) =>
+ defineComponent({
+ name: "Settles",
+ props: () => ({ tag: z.string().optional() }),
+ defaults: { hold: 10 },
+ build: (ctx) => ({
+ children: [ctx.host.box({ id: ctx.partId("x") })],
+ width: 100,
+ height: 50,
+ duration: 20,
+ cues: {},
+ ...o,
+ }),
+ });
+
+ it("keeps open-ended components up until an exit is asked for", () => {
+ const host = fakeHost();
+ const up = bind(host, settles({ openEnded: true }))({});
+ expect(up.span.end).toBe(Number.POSITIVE_INFINITY);
+ const out = bind(
+ host,
+ settles({ openEnded: true }),
+ )({ exit: { preset: "fade", duration: 6 } });
+ expect(out.span.duration).toBe(20 + 10 + 6);
+ expect(
+ bind(host, settles({ openEnded: true }))({ duration: 50 }).span.duration,
+ ).toBe(50);
+ });
+
+ it("adds the component's own after-hold exit to the window", () => {
+ const c = bind(fakeHost(), settles({ afterHold: 12 }))({});
+ expect(c.span.duration).toBe(20 + 10 + 12);
+ });
+
+ it("slides mask presets the full size through a clipping root", () => {
+ const c = bind(
+ fakeHost(),
+ settles({}),
+ )({ enter: "mask-up" }) as unknown as {
+ overflow?: string;
+ children: Array<{
+ animation: {
+ tracks: Array<{ prop: string; keyframes: Array<{ value: number }> }>;
+ };
+ }>;
+ };
+ expect(c.overflow).toBe("hidden");
+ const tracks = c.children[0]?.animation.tracks ?? [];
+ expect(tracks.map((t) => t.prop)).toEqual(["y"]);
+ expect(tracks[0]?.keyframes[0]?.value).toBe(50);
+ });
+});
diff --git a/packages/components/src/core/contract.ts b/packages/components/src/core/contract.ts
index 7dd2f3ef..5a70ae97 100644
--- a/packages/components/src/core/contract.ts
+++ b/packages/components/src/core/contract.ts
@@ -96,38 +96,49 @@ const fn = <T>() =>
message: "Expected a function",
});
-const MotionPresetSchema = z.union([
- z.enum(MOTION_PRESETS as [string, ...string[]]),
- z.object({
- preset: z.enum(MOTION_PRESETS as [string, ...string[]]),
+function motionPresetSchema() {
+ return z.union([
+ z.enum(MOTION_PRESETS as [string, ...string[]]),
+ z.object({
+ preset: z.enum(MOTION_PRESETS as [string, ...string[]]),
+ duration: z.number().int().positive().optional(),
+ ease: z.string().optional(),
+ distance: z.number().optional(),
+ delay: z.number().int().min(0).optional(),
+ }),
+ ]);
+}
+
+let baseProps: ReturnType<typeof buildBaseProps> | undefined;
+
+/** Props every component accepts (built on first use). */
+export function basePropsSchema() {
+ baseProps ??= buildBaseProps();
+ return baseProps;
+}
+
+function buildBaseProps() {
+ return z.object({
+ id: z.string().min(1).optional(),
+ at: z.number().int().min(0).optional(),
duration: z.number().int().positive().optional(),
- ease: z.string().optional(),
- distance: z.number().optional(),
- delay: z.number().int().min(0).optional(),
- }),
-]);
-
-/** Props every component accepts. */
-export const BasePropsSchema = z.object({
- id: z.string().min(1).optional(),
- at: z.number().int().min(0).optional(),
- duration: z.number().int().positive().optional(),
- hold: z.number().int().min(0).optional(),
- enter: z.union([MotionPresetSchema, z.literal(false)]).optional(),
- exit: z.union([MotionPresetSchema, z.literal(false)]).optional(),
- x: z.number().optional(),
- y: z.number().optional(),
- width: z.number().positive().optional(),
- height: z.number().positive().optional(),
- position: z.enum(["absolute", "relative"]).optional(),
- theme: z
- .custom<ThemeInput>((v) => typeof v === "object" && v !== null)
- .optional(),
- seed: z.number().int().optional(),
- fps: z.number().positive().optional(),
- customize:
- fn<(parts: Record<string, Animatable<LayoutNode>>) => void>().optional(),
-});
+ hold: z.number().int().min(0).optional(),
+ enter: z.union([motionPresetSchema(), z.literal(false)]).optional(),
+ exit: z.union([motionPresetSchema(), z.literal(false)]).optional(),
+ x: z.number().optional(),
+ y: z.number().optional(),
+ width: z.number().positive().optional(),
+ height: z.number().positive().optional(),
+ position: z.enum(["absolute", "relative"]).optional(),
+ theme: z
+ .custom<ThemeInput>((v) => typeof v === "object" && v !== null)
+ .optional(),
+ seed: z.number().int().optional(),
+ fps: z.number().positive().optional(),
+ customize:
+ fn<(parts: Record<string, Animatable<LayoutNode>>) => void>().optional(),
+ });
+}
export interface BaseProps {
/** Root id; parts get `<id>-<part>`. */
@@ -170,19 +181,59 @@ export interface BuildContext {
partId(part: string): string;
/** A seeded stream for `key`, stable across unrelated prop changes. */
rng(key: string | number): Rng;
+ /** The size the user asked for (base `width` / `height`), if any. */
+ requested: { width?: number; height?: number };
+ /** Frames the finished state holds (base `hold`, or the component's default). */
+ hold: number;
}
-export interface BuildResult<C extends Cues> {
+/** Where the root ended up: what a component's `api` can rely on. */
+export interface Placement {
+ /** The root's x / y in its parent (0, 0 when it sits in flow). */
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ /** True when x / y are real parent coordinates (absolute placement). */
+ absolute: boolean;
+ /** The component's first frame in the parent's timeline. */
+ start: number;
+}
+
+export interface BuildResult<C extends Cues, E extends object = object> {
/** The component's content, laid out inside a box of `width` × `height`. */
children: LayoutNode[];
width: number;
height: number;
- /** Natural length in frames: when the content's own animation settles. */
- duration: number;
+ /**
+ * Natural length in frames: when the content's own animation settles.
+ * `null` = open-ended (containers): the component lasts as long as its
+ * parent unless `duration` is given.
+ */
+ duration: number | null;
+ /**
+ * Stay on screen after `duration` (like `duration: null`) unless an exit
+ * or a `duration` is asked for; then `duration` is the natural length.
+ * For things that settle and should remain: text, numbers, marks.
+ */
+ openEnded?: boolean;
+ /**
+ * Frames the component plays itself after `duration + hold` (its own
+ * exit, e.g. text leaving unit by unit). Added to the window.
+ */
+ afterHold?: number;
/** Cues in the component's local frames (0 = component start). */
cues: C;
/** Named sub-nodes, exposed to `customize` and `part()`. */
parts?: Record<string, Animatable<LayoutNode>>;
+ /**
+ * Absolute position the root takes when the user gives neither `x` / `y`
+ * nor `position` (components that work in their parent's coordinates,
+ * like a pointer or a camera, sit at 0, 0).
+ */
+ origin?: [x: number, y: number];
+ /** Extra methods and values added (non-enumerable) to the returned node. */
+ api?: (placement: Placement) => E;
}
export interface ComponentDefaults {
@@ -191,18 +242,27 @@ export interface ComponentDefaults {
hold?: number;
}
-export interface ComponentDefinition<S extends z.ZodRawShape, C extends Cues> {
+export interface ComponentDefinition<
+ S extends z.ZodRawShape,
+ C extends Cues,
+ E extends object = object,
+> {
/** PascalCase name, as exported. */
name: string;
- /** Zod shape of the component's own props (base props are added). */
- props: S;
+ /**
+ * Zod shape of the component's own props (base props are added). A
+ * factory, called on first use, so importing a component builds nothing.
+ */
+ props: () => S;
defaults?: ComponentDefaults;
- build(ctx: BuildContext, props: z.output<z.ZodObject<S>>): BuildResult<C>;
+ build(ctx: BuildContext, props: z.output<z.ZodObject<S>>): BuildResult<C, E>;
}
-export function defineComponent<S extends z.ZodRawShape, C extends Cues>(
- definition: ComponentDefinition<S, C>,
-): ComponentDefinition<S, C> {
+export function defineComponent<
+ S extends z.ZodRawShape,
+ C extends Cues,
+ E extends object = object,
+>(definition: ComponentDefinition<S, C, E>): ComponentDefinition<S, C, E> {
return definition;
}
@@ -213,13 +273,13 @@ export type PropsOf<D> =
: never;
export type CuesOf<D> =
- D extends ComponentDefinition<z.ZodRawShape, infer C> ? C : never;
+ D extends ComponentDefinition<z.ZodRawShape, infer C, object> ? C : never;
/** What every component adds to its root node. */
export interface ComponentExtras<C extends Cues> {
/** Moments the component produced, in the parent's timeline. */
readonly cues: C;
- /** The component's window in the parent's timeline. */
+ /** The component's window in the parent's timeline (`end` is Infinity when open-ended). */
readonly span: { start: number; end: number; duration: number };
/** A named part (`root`, `stage`, and the component's own). */
part(name: string): Animatable<LayoutNode> | undefined;
@@ -236,13 +296,17 @@ const kebab = (name: string) =>
* calls this once per component behind a PURE annotation, so bundlers drop
* the ones nobody imports.
*/
-export function bind<S extends z.ZodRawShape, C extends Cues>(
+export function bind<
+ S extends z.ZodRawShape,
+ C extends Cues,
+ E extends object = object,
+>(
host: Host,
- definition: ComponentDefinition<S, C>,
-): (props: z.input<z.ZodObject<S>> & BaseProps) => ComponentNode<C> {
+ definition: ComponentDefinition<S, C, E>,
+): (props: z.input<z.ZodObject<S>> & BaseProps) => ComponentNode<C> & E {
let schema: z.ZodObject | undefined;
return (input) => {
- schema ??= BasePropsSchema.extend(definition.props).strict();
+ schema ??= basePropsSchema().extend(definition.props()).strict();
const parsed = schema.safeParse(input ?? {});
if (!parsed.success) {
const issues = parsed.error.issues
@@ -258,15 +322,17 @@ export function bind<S extends z.ZodRawShape, C extends Cues>(
};
}
-function assemble<S extends z.ZodRawShape, C extends Cues>(
+function assemble<S extends z.ZodRawShape, C extends Cues, E extends object>(
host: Host,
- definition: ComponentDefinition<S, C>,
+ definition: ComponentDefinition<S, C, E>,
props: BaseProps & z.output<z.ZodObject<S>>,
-): ComponentNode<C> {
+): ComponentNode<C> & E {
const theme = defineTheme(props.theme ?? {});
const fps = props.fps ?? 30;
const seed = props.seed ?? 1;
const id = props.id ?? host.autoId(kebab(definition.name));
+ const defaults = definition.defaults ?? {};
+ const hold = props.hold ?? defaults.hold ?? 0;
const ctx: BuildContext = {
host,
theme,
@@ -275,10 +341,11 @@ function assemble<S extends z.ZodRawShape, C extends Cues>(
id,
partId: (part) => `${id}-${part}`,
rng: (key) => hashRng(seed, key),
+ requested: { width: props.width, height: props.height },
+ hold,
};
const built = definition.build(ctx, props);
- const defaults = definition.defaults ?? {};
const enter = resolveMotion(
props.enter === undefined ? defaults.enter : props.enter,
"enter",
@@ -291,13 +358,25 @@ function assemble<S extends z.ZodRawShape, C extends Cues>(
theme,
fps,
);
- const hold = props.hold ?? defaults.hold ?? 0;
+ const openEnded =
+ built.duration === null ||
+ (built.openEnded === true && !exit && !built.afterHold);
const duration =
props.duration ??
- Math.max(
- 1,
- built.duration + hold + (exit ? exit.duration + exit.delay : 0),
+ (openEnded || built.duration === null
+ ? null
+ : Math.max(
+ 1,
+ built.duration +
+ hold +
+ (built.afterHold ?? 0) +
+ (exit ? exit.duration + exit.delay : 0),
+ ));
+ if (duration === null && exit) {
+ throw new Error(
+ `${definition.name}: an exit needs a known end. Give \`duration\`, or drop \`exit\`.`,
);
+ }
const width = props.width ?? built.width;
const height = props.height ?? built.height;
@@ -310,21 +389,33 @@ function assemble<S extends z.ZodRawShape, C extends Cues>(
height,
children: built.children,
});
- if (enter) stage.animate(enterAnimation(enter, 0));
- if (exit) stage.animate(exitAnimation(exit, duration));
+ const size = { width, height };
+ if (enter) stage.animate(enterAnimation(enter, 0, size));
+ if (exit && duration !== null)
+ stage.animate(exitAnimation(exit, duration, size));
- const absolute = props.x !== undefined || props.y !== undefined;
+ const origin =
+ props.x === undefined && props.y === undefined && !props.position
+ ? built.origin
+ : undefined;
+ const absolute =
+ props.x !== undefined || props.y !== undefined || origin !== undefined;
+ const rootX = props.x ?? origin?.[0] ?? 0;
+ const rootY = props.y ?? origin?.[1] ?? 0;
const root = host.box({
id,
...(absolute
- ? { position: "absolute" as const, x: props.x ?? 0, y: props.y ?? 0 }
+ ? { position: "absolute" as const, x: rootX, y: rootY }
: props.position
? { position: props.position }
: {}),
width,
height,
+ // Mask presets slide the stage through the root's own box.
+ ...((enter?.preset.startsWith("mask-") ||
+ exit?.preset.startsWith("mask-")) && { overflow: "hidden" as const }),
startFrame: props.at ?? 0,
- durationFrames: duration,
+ ...(duration !== null && { durationFrames: duration }),
children: [stage],
});
@@ -340,10 +431,27 @@ function assemble<S extends z.ZodRawShape, C extends Cues>(
Object.defineProperties(root, {
cues: { value: cues, enumerable: false },
span: {
- value: { start, end: start + duration, duration },
+ value: {
+ start,
+ end: duration === null ? Number.POSITIVE_INFINITY : start + duration,
+ duration: duration ?? Number.POSITIVE_INFINITY,
+ },
enumerable: false,
},
part: { value: (name: string) => parts[name], enumerable: false },
});
- return root as ComponentNode<C>;
+ if (built.api) {
+ const api = built.api({
+ x: absolute ? rootX : 0,
+ y: absolute ? rootY : 0,
+ width,
+ height,
+ absolute,
+ start,
+ });
+ for (const [key, value] of Object.entries(api)) {
+ Object.defineProperty(root, key, { value, enumerable: false });
+ }
+ }
+ return root as ComponentNode<C> & E;
}
diff --git a/packages/components/src/core/draw.ts b/packages/components/src/core/draw.ts
index f04f2c54..cf154991 100644
--- a/packages/components/src/core/draw.ts
+++ b/packages/components/src/core/draw.ts
@@ -113,17 +113,20 @@ export function boxPath(
[x0, y0],
];
if (wobble <= 0) return toPathData(corners.slice(0, 4), true);
- const points: Vec2[] = [];
+ // A pen starts a little along the top edge, goes round, and closes past
+ // where it started.
+ const w = x1 - x0;
+ const points: Vec2[] = [[x0 + w * 0.06, y0]];
for (let i = 0; i < 4; i++) {
const a = corners[i]!;
const b = corners[i + 1]!;
- for (let s = 0; s < 8; s++) {
+ for (let s = 1; s <= 8; s++) {
const t = s / 8;
+ if (i === 0 && a[0] + (b[0] - a[0]) * t < x0 + w * 0.06) continue;
points.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);
}
}
- // Overshoot past the first corner, the way a pen closes a box.
- points.push([x0 + (x1 - x0) * 0.08, y0]);
+ points.push([x0 + w * 0.14, y0 + (y1 - y0) * 0.01]);
return toPathData(wobblePoints(points, { wobble, seed }, variant));
}
diff --git a/packages/components/src/core/glyphs.test.ts b/packages/components/src/core/glyphs.test.ts
new file mode 100644
index 00000000..a800345b
--- /dev/null
+++ b/packages/components/src/core/glyphs.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vitest";
+import { evaluateEase } from "./ease.js";
+import {
+ constantExpression,
+ evaluateGlyphExpression,
+ scheduleExpression,
+} from "./glyphs.js";
+
+const at = (expression: string, frame: number, textIndex = 0) =>
+ evaluateGlyphExpression(expression, {
+ frame,
+ textIndex,
+ wordIndex: textIndex,
+ });
+
+describe("glyph schedules", () => {
+ const schedule = { starts: [0, 10, 20], duration: 10, ease: "power2.out" };
+
+ it("holds each unit pushed until its start, then eases it to rest", () => {
+ const e = scheduleExpression("char", schedule, "enter");
+ expect(at(e, 0, 1)).toBe(1);
+ expect(at(e, 10, 1)).toBe(1);
+ expect(at(e, 15, 1)).toBeCloseTo(1 - evaluateEase("power2.out", 0.5), 4);
+ expect(at(e, 20, 1)).toBe(0);
+ expect(at(e, 400, 2)).toBe(0);
+ });
+
+ it("interpolates between frames (motion-blur sub-samples)", () => {
+ const e = scheduleExpression(
+ "char",
+ { ...schedule, ease: "none" },
+ "enter",
+ );
+ expect(at(e, 12.5, 1)).toBeCloseTo(0.75, 4);
+ });
+
+ it("exits the other way, and scales by per-unit factors", () => {
+ const out = scheduleExpression("word", schedule, "exit");
+ expect(at(out, 0, 0)).toBe(0);
+ expect(at(out, 10, 0)).toBe(1);
+ const f = scheduleExpression("word", schedule, "enter", [0.5, -1, 0.25]);
+ expect(at(f, 0, 1)).toBe(-1);
+ expect(at(f, 0, 2)).toBe(0.25);
+ });
+
+ it("never leaves an index without a schedule (renderer counts may differ)", () => {
+ const e = scheduleExpression("char", schedule, "enter");
+ // Past the table it takes the last unit's schedule.
+ expect(at(e, 25, 9)).toBe(at(e, 25, 2));
+ });
+
+ it("keeps back-eased overshoot (negative weights)", () => {
+ const e = scheduleExpression(
+ "char",
+ { starts: [0], duration: 20, ease: "back.out(1.7)" },
+ "enter",
+ );
+ const min = Math.min(...Array.from({ length: 21 }, (_, f) => at(e, f)));
+ expect(min).toBeLessThan(0);
+ });
+
+ it("constant weights for emphasis", () => {
+ const e = constantExpression("char", [0, 1, 1, 0]);
+ expect([0, 1, 2, 3, 7].map((i) => at(e, 0, i))).toEqual([0, 1, 1, 0, 0]);
+ });
+});
diff --git a/packages/components/src/core/glyphs.ts b/packages/components/src/core/glyphs.ts
new file mode 100644
index 00000000..a055297a
--- /dev/null
+++ b/packages/components/src/core/glyphs.ts
@@ -0,0 +1,134 @@
+/**
+ * Per-unit glyph animation on the GPU, with no node per unit: each unit
+ * (character, word or line) gets its own start frame, and the renderer's
+ * expression selector reads the schedule from a baked table. Timing is
+ * exact (cue frames are where the motion happens) and any ease works,
+ * because the curve is sampled offline with `core/ease.ts`.
+ *
+ * Expression `frame` is the text node's local frame; `textIndex` counts
+ * every character of the string, spaces included.
+ */
+import { evaluateEase } from "./ease.js";
+
+export type GlyphUnit = "char" | "word" | "line";
+
+/** The expression variable that indexes each unit. */
+export const UNIT_INDEX: Record<GlyphUnit, string> = {
+ char: "textIndex",
+ word: "wordIndex",
+ line: "lineIndex",
+};
+
+export interface UnitSchedule {
+ /** Start frame of each unit (indexed like the unit variable). */
+ starts: readonly number[];
+ /** Frames one unit's move takes. */
+ duration: number;
+ ease: string;
+}
+
+/** Glyph properties an animator can push (at weight 1). */
+export interface GlyphProps {
+ x?: number;
+ y?: number;
+ scale?: number;
+ rotation?: number;
+ rotationX?: number;
+ opacity?: number;
+ blur?: number;
+ fillColor?: string;
+}
+
+/** The renderer's advanced text animator, as plain data. */
+export interface GlyphAnimator {
+ name: string;
+ selectors: Array<{
+ type: "expression";
+ expression: string;
+ mode: "add";
+ amount: number;
+ }>;
+ props: GlyphProps;
+}
+
+const num = (v: number) => String(Math.round(v * 10000) / 10000);
+const list = (values: readonly number[]) => `[${values.map(num).join(",")}]`;
+
+/**
+ * The weight expression for a schedule. `enter`: 1 (fully pushed) until the
+ * unit starts, easing to 0 (at rest) by `start + duration`. `exit`: the
+ * reverse, 0 → 1. Optional `factors` scale each unit's weight (seeded
+ * scatter directions, for instance).
+ */
+export function scheduleExpression(
+ unit: GlyphUnit,
+ schedule: UnitSchedule,
+ mode: "enter" | "exit",
+ factors?: readonly number[],
+): string {
+ const n = Math.max(1, Math.round(schedule.duration));
+ const table = Array.from({ length: n + 1 }, (_, k) =>
+ evaluateEase(schedule.ease, k / n),
+ );
+ const idx = UNIT_INDEX[unit];
+ const pick = (arr: string) => `(${arr}[${idx}]??${arr}[${arr}.length-1])`;
+ const weight = mode === "enter" ? "1-v" : "v";
+ const scaled = factors ? `(${weight})*${pick("F")}` : weight;
+ return [
+ `((S,L,F)=>{`,
+ `const t=frame-${pick("S")};`,
+ `const k=floor(t);`,
+ `const v=t<=0?L[0]:t>=${n}?L[${n}]:L[k]+(L[k+1]-L[k])*(t-k);`,
+ `return ${scaled};`,
+ `})(${list(schedule.starts)},${list(table)},${factors ? list(factors) : "0"})`,
+ ].join("");
+}
+
+/** A fixed weight per unit (e.g. 1 for emphasised characters). */
+export function constantExpression(
+ unit: GlyphUnit,
+ weights: readonly number[],
+): string {
+ return `(${list(weights)}[${UNIT_INDEX[unit]}]??0)`;
+}
+
+export function glyphAnimator(
+ name: string,
+ expression: string,
+ props: GlyphProps,
+): GlyphAnimator {
+ return {
+ name,
+ selectors: [{ type: "expression", expression, mode: "add", amount: 1 }],
+ props,
+ };
+}
+
+/**
+ * Evaluate an expression the way the renderer does (same scope names, same
+ * [-1, 1] clamp). For tests and offline checks.
+ */
+export function evaluateGlyphExpression(
+ expression: string,
+ scope: {
+ frame: number;
+ textIndex?: number;
+ wordIndex?: number;
+ lineIndex?: number;
+ },
+): number {
+ const vars = {
+ textIndex: scope.textIndex ?? 0,
+ wordIndex: scope.wordIndex ?? 0,
+ lineIndex: scope.lineIndex ?? 0,
+ frame: scope.frame,
+ floor: Math.floor,
+ clamp: (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v)),
+ abs: Math.abs,
+ min: Math.min,
+ max: Math.max,
+ };
+ const fn = new Function(...Object.keys(vars), `return (${expression});`);
+ const result = Number(fn(...Object.values(vars)));
+ return Number.isFinite(result) ? Math.max(-1, Math.min(1, result)) : 0;
+}
diff --git a/packages/components/src/core/host.ts b/packages/components/src/core/host.ts
index 46321da5..8af5dcea 100644
--- a/packages/components/src/core/host.ts
+++ b/packages/components/src/core/host.ts
@@ -9,12 +9,57 @@
import type {
BoxNode,
FlexNode,
+ LayoutNode,
ShapeNode,
ShapeType,
TextNode,
} from "@framefields/compositions/program";
import type { MeasureFn } from "./text.js";
+/** Photoshop-style layer styles (framefields' `LayerStyle`). Omitted styles are off. */
+export interface LayerStyleConfig {
+ dropShadow?: {
+ color?: string;
+ opacity?: number;
+ /** Light angle in degrees (90 = shadow straight down). */
+ angle?: number;
+ distance?: number;
+ spread?: number;
+ size?: number;
+ blendMode?: string;
+ };
+ outerGlow?: {
+ color?: string;
+ opacity?: number;
+ size?: number;
+ spread?: number;
+ blendMode?: string;
+ };
+ innerShadow?: {
+ color?: string;
+ opacity?: number;
+ angle?: number;
+ distance?: number;
+ size?: number;
+ };
+ stroke?: {
+ size?: number;
+ position?: "inside" | "center" | "outside";
+ color?: string;
+ opacity?: number;
+ };
+}
+
+export interface MediaOptions {
+ id?: string;
+ position?: "absolute" | "relative";
+ x?: number;
+ y?: number;
+ width?: number;
+ height?: number;
+ fit?: "cover" | "contain" | "fill";
+}
+
/** The part of framefields' `AnimatableNode` components rely on. */
export interface AnimatableMethods {
animate(...anims: unknown[]): unknown;
@@ -33,4 +78,13 @@ export interface Host {
fonts(): readonly string[];
/** A default id: stable per run (a counter per prefix), like `Layer.*` ids. */
autoId(prefix: string): string;
+ /** A video or image layer, by file extension. */
+ media(source: string, options: MediaOptions): Animatable<LayoutNode>;
+ /** Attach layer styles (shadow, glow, stroke) to `node`; returns it. */
+ style<T extends Animatable<LayoutNode>>(node: T, config: LayerStyleConfig): T;
+ /**
+ * Mask `node` by `matte`'s alpha (a box: solid or CSS-gradient
+ * background). The matte is laid out like a sibling of `node`; returns `node`.
+ */
+ matte<T extends Animatable<LayoutNode>>(node: T, matte: LayoutNode): T;
}
diff --git a/packages/components/src/core/motion.ts b/packages/components/src/core/motion.ts
index a78b5c4d..d1cfed63 100644
--- a/packages/components/src/core/motion.ts
+++ b/packages/components/src/core/motion.ts
@@ -2,6 +2,8 @@
* Named entrances and exits shared by every component's `enter` / `exit`.
* A preset becomes plain keyframes on the component's `stage` part, which is
* pinned at (0, 0) inside the root, so offsets never fight the root's layout.
+ * Mask presets slide the stage a full width or height through the root,
+ * which clips it.
*/
import { LayerAnimation } from "@framefields/compositions/program";
import type { Theme } from "./theme.js";
@@ -18,7 +20,11 @@ export type MotionPresetName =
| "slide-right"
| "slide-up"
| "slide-down"
- | "tilt";
+ | "tilt"
+ | "mask-up"
+ | "mask-down"
+ | "mask-left"
+ | "mask-right";
export const MOTION_PRESETS: readonly MotionPresetName[] = [
"none",
@@ -32,13 +38,17 @@ export const MOTION_PRESETS: readonly MotionPresetName[] = [
"slide-up",
"slide-down",
"tilt",
+ "mask-up",
+ "mask-down",
+ "mask-left",
+ "mask-right",
];
export interface MotionOptions {
/** Frames; default the theme's `base` speed. */
duration?: number;
ease?: string;
- /** Travel in px; default 40 (rise / drop) or 120 (slides) × theme.scale. */
+ /** Travel in px; default 40 (rise / drop) or 120 (slides) × theme.scale. Masks travel the full size. */
distance?: number;
/** Frames to wait after the window starts (enter) or before it ends (exit). */
delay?: number;
@@ -90,9 +100,25 @@ export function resolveMotion(
};
}
+/** The box a mask preset slides through. */
+export interface MotionSize {
+ width: number;
+ height: number;
+}
+
+const isMask = (m: ResolvedMotion) => m.preset.startsWith("mask-");
+
/** Offset (dx, dy) a translating preset starts from (enter) or ends at (exit). */
-function offsetOf(m: ResolvedMotion): [number, number] {
+function offsetOf(m: ResolvedMotion, size?: MotionSize): [number, number] {
switch (m.preset) {
+ case "mask-up":
+ return [0, size?.height ?? m.distance];
+ case "mask-down":
+ return [0, -(size?.height ?? m.distance)];
+ case "mask-left":
+ return [size?.width ?? m.distance, 0];
+ case "mask-right":
+ return [-(size?.width ?? m.distance), 0];
case "rise":
case "slide-up":
return [0, m.distance];
@@ -112,15 +138,21 @@ function offsetOf(m: ResolvedMotion): [number, number] {
* Keyframes for an entrance that ends settled at frame `at + delay + duration`
* (local frames of the animated node).
*/
-export function enterAnimation(m: ResolvedMotion, at = 0): LayerAnimation {
+export function enterAnimation(
+ m: ResolvedMotion,
+ at = 0,
+ size?: MotionSize,
+): LayerAnimation {
const s = at + m.delay;
const e = s + m.duration;
const anim = LayerAnimation.create();
- anim.keys("opacity", [
- [s, 0],
- [e, 1, m.ease],
- ]);
- const [dx, dy] = offsetOf(m);
+ // Masks reveal by travel alone: no fade.
+ if (!isMask(m))
+ anim.keys("opacity", [
+ [s, 0],
+ [e, 1, m.ease],
+ ]);
+ const [dx, dy] = offsetOf(m, size);
if (dx !== 0)
anim.keys("x", [
[s, dx],
@@ -158,15 +190,20 @@ export function enterAnimation(m: ResolvedMotion, at = 0): LayerAnimation {
/**
* Keyframes for an exit that finishes at local frame `end - delay`.
*/
-export function exitAnimation(m: ResolvedMotion, end: number): LayerAnimation {
+export function exitAnimation(
+ m: ResolvedMotion,
+ end: number,
+ size?: MotionSize,
+): LayerAnimation {
const e = end - m.delay;
const s = Math.max(0, e - m.duration);
const anim = LayerAnimation.create();
- anim.keys("opacity", [
- [s, 1],
- [e, 0, m.ease],
- ]);
- const [dx, dy] = offsetOf(m);
+ if (!isMask(m))
+ anim.keys("opacity", [
+ [s, 1],
+ [e, 0, m.ease],
+ ]);
+ const [dx, dy] = offsetOf(m, size);
// Exits leave the way entrances arrive: rise exits upward, and so on.
if (dx !== 0)
anim.keys("x", [
diff --git a/packages/components/src/core/path.ts b/packages/components/src/core/path.ts
index 40460865..2453ce0e 100644
--- a/packages/components/src/core/path.ts
+++ b/packages/components/src/core/path.ts
@@ -112,3 +112,44 @@ export function toPathData(points: readonly Vec2[], closed = false): string {
if (closed) parts.push("Z");
return parts.join(" ");
}
+
+/**
+ * Scale and offset absolute SVG path data (M, L, H, V, C, S, Q, T, Z):
+ * `x' = x × scale + dx`. Used to size glyphs designed on a small grid.
+ */
+export function transformPathData(
+ d: string,
+ scale: number,
+ dx = 0,
+ dy = 0,
+): string {
+ const r = (n: number) => Math.round(n * 1000) / 1000;
+ const tokens = d.match(/[a-zA-Z]|-?\d*\.?\d+(?:e[-+]?\d+)?/g) ?? [];
+ const out: string[] = [];
+ let command = "";
+ let axis = 0;
+ for (const token of tokens) {
+ if (/[a-zA-Z]/.test(token)) {
+ if (token !== token.toUpperCase() && token.toLowerCase() !== "z") {
+ throw new Error(
+ `transformPathData: relative command "${token}" is not supported`,
+ );
+ }
+ if (token.toUpperCase() === "A") {
+ throw new Error("transformPathData: arcs are not supported");
+ }
+ command = token.toUpperCase();
+ axis = 0;
+ out.push(command);
+ continue;
+ }
+ const n = Number(token);
+ if (command === "H") out.push(String(r(n * scale + dx)));
+ else if (command === "V") out.push(String(r(n * scale + dy)));
+ else {
+ out.push(String(r(n * scale + (axis % 2 === 0 ? dx : dy))));
+ axis++;
+ }
+ }
+ return out.join(" ").replace(/ ?([A-Z]) ?/g, "$1");
+}
diff --git a/packages/components/src/core/schemas.ts b/packages/components/src/core/schemas.ts
new file mode 100644
index 00000000..d69870ae
--- /dev/null
+++ b/packages/components/src/core/schemas.ts
@@ -0,0 +1,24 @@
+/**
+ * Shared prop schemas. Built on first use, never at import: a schema built at
+ * module load is a side effect bundlers must keep, which would ship every
+ * component to anyone importing one.
+ */
+import { z } from "zod";
+import type { Target } from "./targets.js";
+
+let target: z.ZodType<Target> | undefined;
+
+/** Any `Target`: [x, y], a rect, { node }, { text }, { track }, or (frame) => point. */
+export function targetSchema(): z.ZodType<Target> {
+ target ??= z.custom<Target>(
+ (v) =>
+ v !== null &&
+ v !== undefined &&
+ (Array.isArray(v) || typeof v === "object" || typeof v === "function"),
+ {
+ message:
+ "Expected a target: [x, y], a rect, { node }, { text }, { track } or (frame) => point",
+ },
+ );
+ return target;
+}
diff --git a/packages/components/src/core/text.ts b/packages/components/src/core/text.ts
index a0097870..69658475 100644
--- a/packages/components/src/core/text.ts
+++ b/packages/components/src/core/text.ts
@@ -90,7 +90,7 @@ export function findRange(
* Per-line x offset that `align` adds inside a box of `options.width`
* (measurement itself lays every line out from the left edge).
*/
-function lineShift(
+export function lineShift(
metrics: Metrics,
line: number,
options: MeasureOptions,
diff --git a/packages/components/src/counter/index.test.ts b/packages/components/src/counter/index.test.ts
new file mode 100644
index 00000000..b05568f2
--- /dev/null
+++ b/packages/components/src/counter/index.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from "vitest";
+import { bind } from "../core/contract.js";
+import { fakeHost } from "../test/fake-host.js";
+import { counter } from "./index.js";
+
+const make = () => bind(fakeHost(), counter);
+
+describe("Counter", () => {
+ it("settles after the count and the place stagger, then stays", () => {
+ const c = make()({ to: 999, countDuration: 30, digitStagger: 2 });
+ expect(c.cues.settled[0]?.frame).toBe(34);
+ expect(c.span.end).toBe(Number.POSITIVE_INFINITY);
+ });
+
+ it("is as wide as its widest value, so nothing overflows mid-count", () => {
+ // Fake measure: 0.5 em per glyph at 120 px → 60 px digits and separators.
+ const c = make()({ to: 1_000_000, fontSize: 120 });
+ expect(c.width).toBe(9 * 60);
+ });
+
+ it("lays out affixes, separators and decimals", () => {
+ const c = make()({ id: "c", to: 1234.5, format: "$,.2f", fontSize: 20 });
+ // "$" + 6 digits + "," + "." → 9 glyphs of 10 px.
+ expect(c.width).toBe(90);
+ expect(c.part("prefix")).toBeDefined();
+ });
+
+ it("needs a target value and ascending steps", () => {
+ expect(() => make()({})).toThrow(/give `to`/);
+ expect(() =>
+ make()({
+ values: [
+ [10, 1],
+ [5, 2],
+ ],
+ }),
+ ).toThrow(/must ascend/);
+ });
+
+ it("reports milestones in the parent's timeline", () => {
+ const c = make()({
+ at: 100,
+ to: 30,
+ countDuration: 30,
+ milestoneEvery: 10,
+ ease: "none",
+ });
+ expect(c.cues.milestones.map((m) => m.value)).toEqual([10, 20, 30]);
+ expect(c.cues.milestones[0]?.frame).toBeGreaterThan(100);
+ });
+
+ it("lays a formatter function out per character", () => {
+ const c = make()({ to: 42, format: (n) => `${Math.round(n)} pts` });
+ expect(c.cues.settled).toHaveLength(1);
+ });
+});
diff --git a/packages/components/src/counter/index.ts b/packages/components/src/counter/index.ts
new file mode 100644
index 00000000..7411b87a
--- /dev/null
+++ b/packages/components/src/counter/index.ts
@@ -0,0 +1,430 @@
+/**
+ * Counter: numbers that change in a way viewers trust. Every digit place is
+ * a clipped reel that spins like an odometer (`roll`) or steps (`count`);
+ * separators and affixes are laid out by the format, and the number slides
+ * to stay aligned as places appear.
+ */
+import {
+ type KeyframeTuple,
+ LayerAnimation,
+ type LayoutNode,
+} from "@framefields/compositions/program";
+import { z } from "zod";
+import { bakeSamples } from "../core/bake.js";
+import { defineComponent } from "../core/contract.js";
+import type { Animatable } from "../core/host.js";
+import type { MeasureOptions } from "../core/text.js";
+import { themeFrames } from "../core/theme.js";
+import {
+ type CounterFormat,
+ milestones,
+ numberLayout,
+ placesOf,
+ reelPositions,
+ type ValueKey,
+ valueAt,
+} from "./plan.js";
+
+export type { CounterFormat } from "./plan.js";
+
+export interface CounterCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ /** Every reel is at rest on the final value. */
+ settled: ReadonlyArray<{ frame: number }>;
+ /** Crossings of `milestoneEvery` (e.g. for tick sounds). */
+ milestones: ReadonlyArray<{ frame: number; value: number }>;
+}
+
+/** A slot in the number: a digit reel, a separator, or a character column. */
+interface Slot {
+ width: number;
+ /** Visible on each frame. */
+ visible: boolean[];
+ build(x: number): Animatable<LayoutNode>;
+}
+
+const MINUS = "−";
+/** Frames a slot takes to fade, and the number to slide, when places change. */
+const SETTLE = 6;
+
+export const counter = /* @__PURE__ */ defineComponent({
+ name: "Counter",
+ props: () => ({
+ from: z.number().default(0),
+ to: z.number().optional(),
+ /** Multi-step counts: `[frame, value, ease?]`, frames ascending. */
+ values: z
+ .array(
+ z.union([
+ z.tuple([z.number().int().min(0), z.number()]),
+ z.tuple([z.number().int().min(0), z.number(), z.string()]),
+ ]),
+ )
+ .min(1)
+ .optional(),
+ /** `",d"`, `"$,.2f"`, `".1%"`, Intl options, or `(n) => string`. */
+ format: z
+ .union([
+ z.string(),
+ z.custom<(value: number) => string>((v) => typeof v === "function"),
+ z.custom<Intl.NumberFormatOptions>(
+ (v) => typeof v === "object" && v !== null,
+ ),
+ ])
+ .default(",d"),
+ locale: z.string().default("en-US"),
+ prefix: z.string().default(""),
+ suffix: z.string().default(""),
+ /** Affix size relative to the digits (e.g. 0.6 for a small `%`). */
+ affixScale: z.number().min(0.2).max(1).default(1),
+ /** `roll`: odometer reels. `count`: digits step frame by frame. */
+ style: z.enum(["roll", "count"]).default("roll"),
+ /** Frames the count takes (`from` → `to`). Default: twice the theme's slow speed. */
+ countDuration: z.number().int().positive().optional(),
+ ease: z.string().optional(),
+ /** Frames each higher place settles after the one below it (`roll`). */
+ digitStagger: z.number().min(0).default(2),
+ /** Vertical blur on fast reels (`roll`). */
+ motionBlur: z.boolean().default(true),
+ milestoneEvery: z.number().positive().optional(),
+ fontFamily: z.string().optional(),
+ fontSize: z.number().positive().optional(),
+ fontWeight: z.union([z.number(), z.string()]).optional(),
+ fill: z.string().optional(),
+ align: z.enum(["start", "center", "end"]).default("start"),
+ }),
+ defaults: { enter: false, exit: false, hold: 30 },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const fs = props.fontSize ?? 120 * theme.scale;
+ const fontFamily = props.fontFamily ?? theme.font.display;
+ const ease = props.ease ?? theme.motion.ease.move;
+ const roll = props.style === "roll";
+
+ if (props.values === undefined && props.to === undefined)
+ throw new Error("Counter: give `to` (or `values`).");
+ const keys: ValueKey[] = props.values
+ ? props.values.map((v) => [...v] as unknown as ValueKey)
+ : [
+ [0, props.from],
+ [
+ props.countDuration ?? themeFrames(theme, "slow", fps) * 2,
+ props.to as number,
+ ],
+ ];
+ keys.forEach((k, i) => {
+ const prev = keys[i - 1];
+ if (prev && k[0] <= prev[0])
+ throw new Error(
+ `Counter: \`values\` frames must ascend (${prev[0]} then ${k[0]}).`,
+ );
+ });
+
+ const text = (content: string, size: number, id: string, extra = {}) =>
+ host.text(content, {
+ id: ctx.partId(id),
+ position: "absolute",
+ fontFamily,
+ fontSize: size,
+ fill: props.fill ?? theme.color.ink,
+ ...(props.fontWeight !== undefined && { fontWeight: props.fontWeight }),
+ ...extra,
+ });
+ const measureWith = (s: string, size = fs) =>
+ host.measure(s, {
+ fontFamily,
+ fontSize: size,
+ fontWeight: props.fontWeight,
+ } satisfies MeasureOptions);
+ const lh = measureWith("0").lineHeight;
+
+ const layout = numberLayout(props.format as CounterFormat, props.locale);
+ const stagger = roll ? (props.digitStagger * fps) / 30 : 0;
+ const lastKey = (keys[keys.length - 1] as ValueKey)[0];
+ // Reels count in the last shown digit: 99.5 at two decimals is 9950.
+ const scale = layout ? layout.scale * 10 ** layout.decimals : 1;
+ const places = layout
+ ? Math.max(...keys.map((k) => placesOf(k[1] * scale, layout.decimals)))
+ : 1;
+ const settle = Math.round(lastKey + stagger * (places - 1));
+ const values = Array.from({ length: settle + 1 }, (_, f) =>
+ valueAt(keys, f, ease),
+ );
+ const scaled = values.map((v) => Math.round(v * scale));
+
+ // ── Slots, right to left ──────────────────────────────────────────
+ const slots: Slot[] = [];
+ if (layout) {
+ const cellW = Math.max(
+ ...[..."0123456789"].map((d) => measureWith(d).width),
+ );
+ const shows = (place: number) =>
+ scaled.map(
+ (n) =>
+ place <= layout.decimals ||
+ Math.floor(Math.abs(n) / 10 ** place) > 0,
+ );
+ for (let p = 0; p < places; p++) {
+ if (p === layout.decimals && layout.decimals > 0) {
+ const mark = layout.decimalMark;
+ slots.push({
+ width: measureWith(mark).width,
+ visible: scaled.map(() => true),
+ build: (x) => text(mark, fs, "decimal", { x, y: 0 }),
+ });
+ }
+ const q = p - layout.decimals;
+ if (layout.group && q > 0 && q % 3 === 0) {
+ const sep = layout.group;
+ slots.push({
+ width: measureWith(sep).width,
+ visible: shows(p),
+ build: (x) => text(sep, fs, `group-${q}`, { x, y: 0 }),
+ });
+ }
+ const place = p;
+ slots.push({
+ width: cellW,
+ visible: shows(place),
+ build: (x) =>
+ digitCell(
+ place,
+ x,
+ cellW,
+ roll
+ ? reelPositions(keys, place, {
+ scale,
+ stagger,
+ ease,
+ length: settle,
+ })
+ : scaled.map((n) => Math.floor(Math.abs(n) / 10 ** place) % 10),
+ ),
+ });
+ }
+ } else {
+ // A formatter function: one column per character from the right.
+ const format = props.format as (n: number) => string;
+ const strings = values.map((v) => format(v));
+ const columns = Math.max(...strings.map((s) => s.length));
+ for (let c = 0; c < columns; c++) {
+ const chars = strings.map((s) => s[s.length - 1 - c] ?? "");
+ const rows = [...new Set(chars)];
+ const width = Math.max(
+ 0,
+ ...rows.map((r) => (r ? measureWith(r).width : 0)),
+ );
+ const col = c;
+ slots.push({
+ width,
+ visible: chars.map((ch) => ch !== ""),
+ build: (x) => charCell(col, x, width, rows, chars),
+ });
+ }
+ }
+
+ function digitCell(
+ place: number,
+ x: number,
+ width: number,
+ positions: number[],
+ ): Animatable<LayoutNode> {
+ const lo = Math.floor(Math.min(...positions));
+ const hi = Math.ceil(Math.max(...positions));
+ const rows = roll
+ ? Array.from(
+ { length: hi - lo + 1 },
+ (_, k) => (((lo + k) % 10) + 10) % 10,
+ )
+ : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
+ const base = roll ? lo : 0;
+ const ys = positions.map((pos) => -(pos - base) * lh);
+ const reel = text(rows.join("\n"), fs, `reel-${place}`, {
+ x: 0,
+ y: ys[0] ?? 0,
+ width,
+ align: "center",
+ ...(roll && props.motionBlur && { motionBlurShutter: 90 }),
+ });
+ reel.animate(
+ LayerAnimation.keys(
+ "y",
+ roll ? bakeSamples(ys, 0, { tolerance: 0.2 }) : stepKeys(ys),
+ ),
+ );
+ return host.box({
+ id: ctx.partId(`cell-${place}`),
+ position: "absolute",
+ x,
+ y: 0,
+ width,
+ height: lh,
+ overflow: "hidden",
+ children: [reel],
+ });
+ }
+
+ function charCell(
+ column: number,
+ x: number,
+ width: number,
+ rows: string[],
+ chars: string[],
+ ): Animatable<LayoutNode> {
+ const ys = chars.map((ch) => -rows.indexOf(ch) * lh);
+ const reel = text(
+ rows.map((r) => r || " ").join("\n"),
+ fs,
+ `reel-${column}`,
+ {
+ x: 0,
+ y: ys[0] ?? 0,
+ width,
+ align: "center",
+ },
+ );
+ reel.animate(LayerAnimation.keys("y", stepKeys(ys)));
+ return host.box({
+ id: ctx.partId(`cell-${column}`),
+ position: "absolute",
+ x,
+ y: 0,
+ width,
+ height: lh,
+ overflow: "hidden",
+ children: [reel],
+ });
+ }
+
+ // ── Layout over time ──────────────────────────────────────────────
+ const affix = fs * props.affixScale;
+ const affixLh = measureWith("0", affix).lineHeight;
+ const affixY = (lh - affixLh) * 0.78;
+ const prefix = (layout?.prefix ?? "") + props.prefix;
+ const suffix = props.suffix + (layout?.suffix ?? "");
+ const prefixW = prefix ? measureWith(prefix, affix).width : 0;
+ const suffixW = suffix ? measureWith(suffix, affix).width : 0;
+ const negative = scaled.map((n) => n < 0);
+ const minusW = negative.some(Boolean) ? measureWith(MINUS).width : 0;
+
+ const digitsW = slots.reduce((a, s) => a + s.width, 0);
+ const W = prefixW + minusW + digitsW + suffixW;
+ const shown = scaled.map((_, f) =>
+ slots.reduce((a, s) => a + (s.visible[f] ? s.width : 0), 0),
+ );
+ const content = shown.map(
+ (w, f) => prefixW + (negative[f] ? minusW : 0) + w + suffixW,
+ );
+ const af = props.align === "center" ? 0.5 : props.align === "end" ? 1 : 0;
+ const left = content.map((c) => (W - c) * af);
+
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+ let cursor = digitsW;
+ const cells = slots.map((s, i) => {
+ cursor -= s.width;
+ const node = s.build(cursor);
+ node.animate(LayerAnimation.keys("opacity", fadeKeys(s.visible)));
+ parts[`slot-${i}`] = node;
+ return node;
+ });
+ const digits = host.box({
+ id: ctx.partId("digits"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: digitsW,
+ height: lh,
+ children: cells,
+ });
+ const digitsX = shown.map(
+ (w, f) =>
+ (left[f] as number) +
+ prefixW +
+ (negative[f] ? minusW : 0) +
+ w -
+ digitsW,
+ );
+ digits.animate(LayerAnimation.keys("x", slideKeys(digitsX)));
+ parts.digits = digits;
+ const children: LayoutNode[] = [digits];
+
+ if (prefix) {
+ const node = text(prefix, affix, "prefix", { x: 0, y: affixY });
+ node.animate(LayerAnimation.keys("x", slideKeys(left)));
+ parts.prefix = node;
+ children.push(node);
+ }
+ if (minusW > 0) {
+ const node = text(MINUS, fs, "minus", { x: 0, y: 0 });
+ node.animate(
+ LayerAnimation.create()
+ .keys("x", slideKeys(left.map((l) => l + prefixW)))
+ .keys("opacity", fadeKeys(negative)),
+ );
+ parts.minus = node;
+ children.push(node);
+ }
+ if (suffix) {
+ const node = text(suffix, affix, "suffix", { x: 0, y: affixY });
+ node.animate(
+ LayerAnimation.keys("x", slideKeys(digitsX.map((x) => x + digitsW))),
+ );
+ parts.suffix = node;
+ children.push(node);
+ }
+
+ return {
+ children,
+ width: W,
+ height: lh,
+ duration: settle + 1,
+ openEnded: true,
+ cues: {
+ settled: [{ frame: settle }],
+ milestones:
+ props.milestoneEvery === undefined
+ ? []
+ : milestones(values, props.milestoneEvery),
+ } as CounterCues,
+ parts,
+ };
+ },
+});
+
+/** Hold keys at every change of a per-frame series. */
+function stepKeys(series: readonly number[]): KeyframeTuple[] {
+ const keys: KeyframeTuple[] = [[0, series[0] ?? 0]];
+ for (let f = 1; f < series.length; f++)
+ if (series[f] !== series[f - 1])
+ keys.push([f, series[f] as number, "hold"]);
+ return keys;
+}
+
+/** A per-frame target that changes in steps, eased over {@link SETTLE} frames. */
+function slideKeys(series: readonly number[]): KeyframeTuple[] {
+ const keys: KeyframeTuple[] = [[0, series[0] ?? 0]];
+ for (let f = 1; f < series.length; f++) {
+ const prev = series[f - 1] as number;
+ const next = series[f] as number;
+ if (Math.abs(next - prev) < 0.01) continue;
+ const last = keys[keys.length - 1] as KeyframeTuple;
+ if (f - 1 > last[0]) keys.push([f - 1, prev]);
+ keys.push([f - 1 + SETTLE, next, "power2.out"]);
+ }
+ return dedupe(keys);
+}
+
+function fadeKeys(visible: readonly boolean[]): KeyframeTuple[] {
+ return slideKeys(visible.map((v) => (v ? 1 : 0)));
+}
+
+/** Keys must ascend: a later change replaces anything it overlaps. */
+function dedupe(keys: KeyframeTuple[]): KeyframeTuple[] {
+ const out: KeyframeTuple[] = [];
+ for (const k of keys) {
+ while (out.length > 0 && (out[out.length - 1] as KeyframeTuple)[0] >= k[0])
+ out.pop();
+ out.push(k);
+ }
+ return out;
+}
diff --git a/packages/components/src/counter/meta.ts b/packages/components/src/counter/meta.ts
new file mode 100644
index 00000000..fac8d8c8
--- /dev/null
+++ b/packages/components/src/counter/meta.ts
@@ -0,0 +1,12 @@
+import { defineMeta } from "../core/meta.js";
+
+export default defineMeta({
+ name: "Counter",
+ summary:
+ "A number that counts to its value on odometer reels (or stepping digits), with format-aware separators, affixes and multi-step values.",
+ tags: ["number", "counter", "stat", "odometer", "data", "price"],
+ parts: ["digits", "slot-<n>", "prefix", "suffix", "minus"],
+ cues: ["settled", "milestones"],
+ example: `Counter({ to: 12480, format: ",d", prefix: "$" })`,
+ since: "M2",
+});
diff --git a/packages/components/src/counter/plan.test.ts b/packages/components/src/counter/plan.test.ts
new file mode 100644
index 00000000..b4cec590
--- /dev/null
+++ b/packages/components/src/counter/plan.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from "vitest";
+import {
+ MAX_TURNS,
+ milestones,
+ numberLayout,
+ placesOf,
+ reelPositions,
+ valueAt,
+} from "./plan.js";
+
+describe("number layouts", () => {
+ it("reads d3-style strings", () => {
+ expect(numberLayout(",d")).toMatchObject({
+ decimals: 0,
+ group: ",",
+ prefix: "",
+ suffix: "",
+ scale: 1,
+ });
+ expect(numberLayout("$,.2f")).toMatchObject({
+ decimals: 2,
+ group: ",",
+ prefix: "$",
+ });
+ expect(numberLayout(".1%")).toMatchObject({
+ decimals: 1,
+ group: null,
+ suffix: "%",
+ scale: 100,
+ });
+ expect(() => numberLayout("x")).toThrow(/unsupported format/);
+ });
+
+ it("reads Intl options, locale separators and affixes included", () => {
+ const eur = numberLayout({ style: "currency", currency: "EUR" }, "de-DE");
+ expect(eur).toMatchObject({ decimals: 2, group: ".", decimalMark: "," });
+ expect(eur?.suffix.trim()).toBe("€");
+ expect(numberLayout((n) => String(n))).toBeNull();
+ });
+});
+
+describe("value trajectory", () => {
+ it("eases between keys and holds the ends", () => {
+ const keys = [
+ [10, 0],
+ [20, 100, "none"],
+ ] as const;
+ expect(valueAt(keys, 0, "none")).toBe(0);
+ expect(valueAt(keys, 15, "none")).toBe(50);
+ expect(valueAt(keys, 99, "none")).toBe(100);
+ expect(placesOf(1_000_000, 0)).toBe(7);
+ expect(placesOf(5, 2)).toBe(3);
+ });
+});
+
+describe("digit reels", () => {
+ const o = { scale: 1, stagger: 0, ease: "none", length: 30 };
+
+ it("land every place on its final digit", () => {
+ const keys = [
+ [0, 120],
+ [30, 87],
+ ] as const;
+ const units = reelPositions(keys, 0, o);
+ const tens = reelPositions(keys, 1, o);
+ expect((((units[30] as number) % 10) + 10) % 10).toBe(7);
+ expect((((tens[30] as number) % 10) + 10) % 10).toBe(8);
+ });
+
+ it("spin downward when the value falls", () => {
+ const units = reelPositions(
+ [
+ [0, 120],
+ [30, 87],
+ ],
+ 0,
+ o,
+ );
+ for (let f = 1; f <= 30; f++)
+ expect(units[f]).toBeLessThanOrEqual(units[f - 1] as number);
+ });
+
+ it("cap long spins without changing where they land", () => {
+ const units = reelPositions(
+ [
+ [0, 0],
+ [30, 1_000_007],
+ ],
+ 0,
+ o,
+ );
+ expect(units[30]).toBe(MAX_TURNS * 10 + 7);
+ });
+
+ it("settle higher places later", () => {
+ const late = reelPositions(
+ [
+ [0, 0],
+ [30, 99],
+ ],
+ 1,
+ { ...o, stagger: 4, length: 40 },
+ );
+ expect(late[30]).toBeLessThan(9);
+ expect(late[34]).toBe(9);
+ });
+});
+
+describe("milestones", () => {
+ it("fire once per multiple crossed, both ways", () => {
+ expect(milestones([0, 5, 12, 25], 10)).toEqual([
+ { frame: 2, value: 10 },
+ { frame: 3, value: 20 },
+ ]);
+ expect(milestones([25, 15], 10)).toEqual([{ frame: 1, value: 20 }]);
+ });
+});
diff --git a/packages/components/src/counter/plan.ts b/packages/components/src/counter/plan.ts
new file mode 100644
index 00000000..faf5441d
--- /dev/null
+++ b/packages/components/src/counter/plan.ts
@@ -0,0 +1,176 @@
+/**
+ * Counter planning, kept pure: how a format lays a number out (affixes,
+ * separators, fixed decimals), the value over time, and where each digit
+ * reel sits on every frame.
+ */
+import { evaluateEase } from "../core/ease.js";
+
+/** How a known format writes any value: digits are laid out from these. */
+export interface NumberLayout {
+ decimals: number;
+ /** Thousands separator, or null for none. */
+ group: string | null;
+ decimalMark: string;
+ prefix: string;
+ suffix: string;
+ /** 100 for percentages. */
+ scale: number;
+}
+
+export type CounterFormat =
+ | string
+ | Intl.NumberFormatOptions
+ | ((value: number) => string);
+
+/**
+ * A layout for a d3-style format string (`",d"`, `",.2f"`, `".1%"`,
+ * `"$,.0f"`) or Intl options. Functions return null: they are laid out per
+ * character instead.
+ */
+export function numberLayout(
+ format: CounterFormat,
+ locale = "en-US",
+): NumberLayout | null {
+ if (typeof format === "function") return null;
+ if (typeof format === "string") {
+ const m = format.match(/^(\$)?(,)?(?:\.(\d+))?([df%]?)$/);
+ if (!m) {
+ throw new Error(
+ `Counter: unsupported format "${format}". Use [$][,][.precision][d|f|%] (e.g. ",d", "$,.2f", ".1%"), Intl options, or a function.`,
+ );
+ }
+ const type = m[4] ?? "";
+ return {
+ decimals: type === "d" ? 0 : Number(m[3] ?? (type === "%" ? 0 : 0)),
+ group: m[2] ? "," : null,
+ decimalMark: ".",
+ prefix: m[1] ?? "",
+ suffix: type === "%" ? "%" : "",
+ scale: type === "%" ? 100 : 1,
+ };
+ }
+ const nf = new Intl.NumberFormat(locale, format);
+ const resolved = nf.resolvedOptions();
+ const parts = nf.formatToParts(1234567.891);
+ const first = parts.findIndex((p) => p.type === "integer");
+ const lastNumeric = parts.reduce(
+ (at, p, i) =>
+ ["integer", "group", "decimal", "fraction"].includes(p.type) ? i : at,
+ -1,
+ );
+ return {
+ decimals: resolved.maximumFractionDigits ?? 0,
+ group: parts.find((p) => p.type === "group")?.value ?? null,
+ decimalMark: parts.find((p) => p.type === "decimal")?.value ?? ".",
+ prefix: parts
+ .slice(0, first)
+ .map((p) => p.value)
+ .join(""),
+ suffix: parts
+ .slice(lastNumeric + 1)
+ .map((p) => p.value)
+ .join(""),
+ scale: format.style === "percent" ? 100 : 1,
+ };
+}
+
+/** `[frame, value, ease?]`: the value is reached at `frame`. */
+export type ValueKey = readonly [frame: number, value: number, ease?: string];
+
+/** The value at any frame of a piecewise trajectory. */
+export function valueAt(
+ keys: readonly ValueKey[],
+ frame: number,
+ fallbackEase: string,
+): number {
+ const first = keys[0];
+ if (!first) return 0;
+ if (frame <= first[0]) return first[1];
+ for (let i = 1; i < keys.length; i++) {
+ const a = keys[i - 1] as ValueKey;
+ const b = keys[i] as ValueKey;
+ if (frame <= b[0]) {
+ const t = (frame - a[0]) / Math.max(1, b[0] - a[0]);
+ return a[1] + (b[1] - a[1]) * evaluateEase(b[2] ?? fallbackEase, t);
+ }
+ }
+ return (keys[keys.length - 1] as ValueKey)[1];
+}
+
+/** Number of digit places a scaled integer shows (at least `decimals + 1`). */
+export function placesOf(n: number, decimals: number): number {
+ const abs = Math.abs(Math.round(n));
+ return Math.max(
+ decimals + 1,
+ abs === 0 ? 1 : Math.floor(Math.log10(abs)) + 1,
+ );
+}
+
+/** Most turns a reel makes in one move; the rest is a blur nobody can read. */
+export const MAX_TURNS = 3;
+
+/**
+ * Reel position (in digit steps) of place `p` on every frame `0..length`:
+ * each segment moves every place from its old digit to its new one, higher
+ * places later by `stagger × p` frames, spinning the way an odometer does
+ * (capped at {@link MAX_TURNS} turns). `pos mod 10` is the digit shown.
+ */
+export function reelPositions(
+ keys: readonly ValueKey[],
+ place: number,
+ o: { scale: number; stagger: number; ease: string; length: number },
+): number[] {
+ const unit = 10 ** place;
+ const digitsAt = (v: number) =>
+ Math.floor(Math.abs(Math.round(v * o.scale)) / unit);
+ const out = new Array<number>(o.length + 1);
+ let pos = digitsAt(keys[0]?.[1] ?? 0);
+ let free = Number.NEGATIVE_INFINITY;
+ const segments = keys.slice(1).map((b, i) => {
+ const a = keys[i] as ValueKey;
+ const delta = digitsAt(b[1]) - digitsAt(a[1]);
+ const turns = Math.abs(delta);
+ const distance =
+ Math.sign(delta) *
+ (turns <= MAX_TURNS * 10 ? turns : MAX_TURNS * 10 + (turns % 10));
+ // A place never starts a move before finishing its last one.
+ const start = Math.max(a[0] + o.stagger * place, free);
+ const seg = {
+ from: pos,
+ distance,
+ start,
+ end: start + (b[0] - a[0]),
+ ease: b[2] ?? o.ease,
+ };
+ pos += distance;
+ free = seg.end;
+ return seg;
+ });
+ for (let f = 0; f <= o.length; f++) {
+ let p = digitsAt(keys[0]?.[1] ?? 0);
+ for (const s of segments) {
+ if (f <= s.start) break;
+ const t = Math.min(1, (f - s.start) / Math.max(1, s.end - s.start));
+ p = s.from + s.distance * evaluateEase(s.ease, t);
+ }
+ out[f] = p;
+ }
+ return out;
+}
+
+/** Frames where `value` crosses a multiple of `every`, with that multiple. */
+export function milestones(
+ values: readonly number[],
+ every: number,
+): Array<{ frame: number; value: number }> {
+ const out: Array<{ frame: number; value: number }> = [];
+ for (let f = 1; f < values.length; f++) {
+ const a = Math.floor((values[f - 1] as number) / every);
+ const b = Math.floor((values[f] as number) / every);
+ if (a === b) continue;
+ const dir = Math.sign(b - a);
+ for (let k = a + (dir > 0 ? 1 : 0); dir > 0 ? k <= b : k > b; k += dir)
+ out.push({ frame: f, value: k * every });
+ }
+ return out;
+}
diff --git a/packages/components/src/focus-zoom/index.ts b/packages/components/src/focus-zoom/index.ts
new file mode 100644
index 00000000..9640fd6b
--- /dev/null
+++ b/packages/components/src/focus-zoom/index.ts
@@ -0,0 +1,267 @@
+/**
+ * FocusZoom: a camera over 2D content that pushes in on what matters and
+ * eases back out — the auto-zoom of polished product demos. Give it shots,
+ * or let it follow a MousePointer and frame each burst of clicks.
+ */
+import {
+ LayerAnimation,
+ type LayoutNode,
+} from "@framefields/compositions/program";
+import { z } from "zod";
+import { bakeSamples } from "../core/bake.js";
+import { defineComponent } from "../core/contract.js";
+import type { Vec2 } from "../core/path.js";
+import { targetSchema } from "../core/schemas.js";
+import { boundsOf, resolveTarget, targetPoint } from "../core/targets.js";
+import {
+ type ClickEvent,
+ type ShotWindow,
+ shotsFromClicks,
+ solveCamera,
+} from "./plan.js";
+
+/** What `follow` needs from a pointer (a MousePointer node has it). */
+export interface Followable {
+ positionAt(frame: number): Vec2;
+ cues: { clicks: ReadonlyArray<{ frame: number; point: Vec2 }> };
+}
+
+/** A target, or "full" for the whole view. */
+function shotTargetSchema() {
+ return z.union([z.literal("full"), targetSchema()]);
+}
+
+export interface FocusZoomCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ /** One per shot: push starts (`frame`), lands (`settled`), lets go (`end`). */
+ shots: ReadonlyArray<{
+ frame: number;
+ settled: number;
+ end: number;
+ zoom: number;
+ center: Vec2;
+ }>;
+}
+
+export interface FocusZoomApi {
+ /** A content point → where it shows on screen (parent coordinates) at a parent frame. */
+ toScreen(point: Vec2, frame: number): Vec2;
+ /** Camera at a parent frame: the content point at the centre, and the zoom. */
+ cameraAt(frame: number): { center: Vec2; zoom: number };
+}
+
+// Shutter angles. Camera moves scale everything at once, so even a little
+// blur reads strongly: keep the default restrained.
+const SMEAR = { subtle: 24, standard: 60, heavy: 140 } as const;
+
+export const focusZoom = /* @__PURE__ */ defineComponent({
+ name: "FocusZoom",
+ props: () => ({
+ /** What the camera films, laid out at full size in the view's coordinates. */
+ content: z.custom<LayoutNode | LayoutNode[]>(
+ (v) => typeof v === "object" && v !== null,
+ ),
+ /** Manual shots: from `at` until the next shot (or `hold` frames). */
+ shots: z
+ .array(
+ z
+ .object({
+ at: z.number().int().min(0),
+ target: shotTargetSchema(),
+ zoom: z.number().min(1).optional(),
+ hold: z.number().int().positive().optional(),
+ })
+ .strict(),
+ )
+ .optional(),
+ /** Follow a pointer: push in around each burst of clicks. */
+ follow: z
+ .custom<Followable>(
+ (v) =>
+ typeof v === "object" &&
+ v !== null &&
+ typeof (v as Followable).positionAt === "function",
+ {
+ message:
+ "Expected a MousePointer (anything with positionAt and cues.clicks)",
+ },
+ )
+ .optional(),
+ /** Zoom for a shot without its own. */
+ zoom: z.number().min(1).default(1.8),
+ maxZoom: z.number().min(1).default(2.5),
+ /** Frames the push starts before a click (it always lands before the click). Default: about a second. */
+ lead: z.number().int().min(0).optional(),
+ /** Frames without a click before easing back out. */
+ idle: z.number().int().min(0).default(40),
+ /** 0 = quick camera moves, 1 = slow, soft ones. */
+ smoothing: z.number().min(0).max(1).default(0.5),
+ /** Space kept around click points / targets. */
+ padding: z.number().min(0).default(160),
+ /** Never show past the content's edges. */
+ clamp: z.boolean().default(true),
+ /** When zoomed, keep the view inside this region (e.g. the app window). */
+ bounds: shotTargetSchema().optional(),
+ /** Motion blur while the camera moves. */
+ smear: z
+ .union([z.literal(false), z.enum(["subtle", "standard", "heavy"])])
+ .default("subtle"),
+ /** Frames to solve. Default: through the last shot plus its return. */
+ length: z.number().int().positive().optional(),
+ }),
+ defaults: { enter: false, exit: false },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const W = ctx.requested.width ?? 1920 * theme.scale;
+ const H = ctx.requested.height ?? 1080 * theme.scale;
+ // By default the push starts early enough to run at its natural pace.
+ const lead =
+ props.lead ?? Math.round((0.55 + 0.75 * props.smoothing) * fps) + 2;
+
+ const shots: ShotWindow[] = [];
+ if (props.follow) {
+ const pointer = props.follow;
+ // Click frames are in the pointer's parent timeline — the content —
+ // which starts with this component.
+ const clicks: ClickEvent[] = pointer.cues.clicks.map((c) => ({
+ frame: c.frame,
+ point: c.point,
+ }));
+ shots.push(
+ ...shotsFromClicks(clicks, {
+ width: W,
+ height: H,
+ lead,
+ idle: props.idle,
+ zoom: props.zoom,
+ maxZoom: props.maxZoom,
+ padding: props.padding,
+ }),
+ );
+ }
+ const manual = [...(props.shots ?? [])].sort((a, b) => a.at - b.at);
+ manual.forEach((shot, i) => {
+ const next = manual[i + 1];
+ const end =
+ shot.hold !== undefined
+ ? shot.at + shot.hold
+ : (next?.at ?? shot.at + Math.round(fps * 3));
+ if (shot.target === "full") {
+ shots.push({ start: shot.at, end, zoom: 1, center: [W / 2, H / 2] });
+ return;
+ }
+ const resolved = resolveTarget(shot.target, {
+ measure: host.measure,
+ fps,
+ });
+ if (resolved.kind === "dynamic") {
+ shots.push({
+ start: shot.at,
+ end,
+ zoom: shot.zoom ?? props.zoom,
+ center: (f) => targetPoint(resolved, f),
+ });
+ return;
+ }
+ const r = boundsOf(resolved.rects);
+ const fit = Math.min(
+ W / (r.width + props.padding * 2),
+ H / (r.height + props.padding * 2),
+ );
+ const zoom = Math.min(
+ props.maxZoom,
+ shot.zoom ?? Math.max(1, Math.min(props.zoom, fit)),
+ );
+ shots.push({
+ start: shot.at,
+ end,
+ zoom,
+ center: [r.x + r.width / 2, r.y + r.height / 2],
+ });
+ });
+ shots.sort((a, b) => a.start - b.start);
+
+ const lastEnd = Math.max(0, ...shots.map((s) => s.end));
+ const length = props.length ?? lastEnd + Math.round(fps * 1.5) + 1;
+ let bounds:
+ | { x: number; y: number; width: number; height: number }
+ | undefined;
+ if (props.bounds !== undefined && props.bounds !== "full") {
+ const resolved = resolveTarget(props.bounds, {
+ measure: host.measure,
+ fps,
+ });
+ if (resolved.kind !== "static")
+ throw new Error("FocusZoom: `bounds` must be a static target.");
+ bounds = boundsOf(resolved.rects);
+ }
+ const plan = solveCamera({
+ width: W,
+ height: H,
+ length,
+ fps,
+ shots,
+ smoothing: props.smoothing,
+ clamp: props.clamp,
+ bounds,
+ });
+
+ const camera = host.box({
+ id: ctx.partId("camera"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ anchorX: 0,
+ anchorY: 0,
+ ...(props.smear !== false && { motionBlurShutter: SMEAR[props.smear] }),
+ children: Array.isArray(props.content) ? props.content : [props.content],
+ });
+ camera.animate(
+ LayerAnimation.keys("x", bakeSamples(plan.x, 0, { tolerance: 0.15 })),
+ LayerAnimation.keys("y", bakeSamples(plan.y, 0, { tolerance: 0.15 })),
+ LayerAnimation.keys(
+ "scale",
+ bakeSamples(plan.scale, 0, { tolerance: 0.0004 }),
+ ),
+ );
+ const clip = host.box({
+ id: ctx.partId("clip"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ overflow: "hidden",
+ children: [camera],
+ });
+
+ const stateAt = (local: number) =>
+ plan.states[
+ Math.max(0, Math.min(plan.states.length - 1, Math.round(local)))
+ ] ?? { cx: W / 2, cy: H / 2, zoom: 1 };
+ return {
+ children: [clip],
+ width: W,
+ height: H,
+ duration: null,
+ origin: [0, 0],
+ cues: { shots: plan.shots } as FocusZoomCues,
+ parts: { camera, clip },
+ api: (placement): FocusZoomApi => ({
+ toScreen(point, frame) {
+ const s = stateAt(frame - placement.start);
+ return [
+ placement.x + W / 2 + (point[0] - s.cx) * s.zoom,
+ placement.y + H / 2 + (point[1] - s.cy) * s.zoom,
+ ];
+ },
+ cameraAt(frame) {
+ const s = stateAt(frame - placement.start);
+ return { center: [s.cx, s.cy], zoom: s.zoom };
+ },
+ }),
+ };
+ },
+});
diff --git a/packages/components/src/focus-zoom/meta.ts b/packages/components/src/focus-zoom/meta.ts
new file mode 100644
index 00000000..efdb79f8
--- /dev/null
+++ b/packages/components/src/focus-zoom/meta.ts
@@ -0,0 +1,12 @@
+import { defineMeta } from "../core/meta.js";
+
+export default defineMeta({
+ name: "FocusZoom",
+ summary:
+ "A camera over 2D content that pushes in on each burst of pointer clicks (or on given shots) and eases back out, clamped to the content.",
+ tags: ["camera", "zoom", "auto-zoom", "screen recording", "demo", "focus"],
+ parts: ["clip", "camera"],
+ cues: ["shots"],
+ example: `FocusZoom({ content: [frame, pointer], follow: pointer })`,
+ since: "M1",
+});
diff --git a/packages/components/src/focus-zoom/plan.test.ts b/packages/components/src/focus-zoom/plan.test.ts
new file mode 100644
index 00000000..199a42af
--- /dev/null
+++ b/packages/components/src/focus-zoom/plan.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, it } from "vitest";
+import { shotsFromClicks, solveCamera } from "./plan.js";
+
+const base = {
+ width: 1920,
+ height: 1080,
+ fps: 30,
+ smoothing: 0.6,
+ clamp: true,
+};
+
+describe("solveCamera", () => {
+ it("rests at full view without shots", () => {
+ const plan = solveCamera({ ...base, length: 30, shots: [] });
+ expect(plan.scale.every((s) => s === 1)).toBe(true);
+ expect(plan.x.every((x) => x === 0)).toBe(true);
+ });
+
+ it("pushes in, settles on the target, and lets go", () => {
+ const plan = solveCamera({
+ ...base,
+ length: 200,
+ shots: [{ start: 20, end: 120, zoom: 2, center: [1400, 400] }],
+ });
+ const settled = plan.shots[0]?.settled ?? 0;
+ expect(settled).toBeGreaterThan(20);
+ expect(settled).toBeLessThan(80);
+ const s = plan.states[110];
+ expect(s?.zoom).toBeCloseTo(2, 2);
+ expect(s?.cx).toBeCloseTo(1400, 0);
+ expect(plan.states[199]?.zoom).toBeCloseTo(1, 2);
+ // Wrapper transform puts the centre point in the middle of the view.
+ expect((plan.x[110] ?? 0) + 2 * 1400).toBeCloseTo(960, 0);
+ });
+
+ it("never shows past the edges, or past bounds once zoomed", () => {
+ const plan = solveCamera({
+ ...base,
+ length: 120,
+ shots: [{ start: 0, end: 120, zoom: 2, center: [1900, 1060] }],
+ bounds: { x: 100, y: 50, width: 1600, height: 950 },
+ });
+ for (const st of plan.states) {
+ const hw = 960 / st.zoom;
+ const hh = 540 / st.zoom;
+ expect(st.cx + hw).toBeLessThanOrEqual(1920 + 1e-6);
+ expect(st.cy + hh).toBeLessThanOrEqual(1080 + 1e-6);
+ }
+ const last = plan.states[119];
+ expect((last?.cx ?? 0) + 960 / (last?.zoom ?? 1)).toBeLessThanOrEqual(
+ 1700 + 1e-6,
+ );
+ });
+
+ it("never wiggles: a point near a clamped edge moves one way on screen in and out", () => {
+ const plan = solveCamera({
+ ...base,
+ length: 240,
+ shots: [{ start: 30, end: 140, zoom: 1.65, center: [1700, 300] }],
+ bounds: { x: 150, y: 64, width: 1620, height: 952 },
+ });
+ const screenX = plan.states.map((s) => 960 + (1612 - s.cx) * s.zoom);
+ const directionChanges = (from: number, to: number) => {
+ let changes = 0;
+ let last = 0;
+ for (let f = from + 1; f < to; f++) {
+ const d = (screenX[f] ?? 0) - (screenX[f - 1] ?? 0);
+ if (Math.abs(d) < 1e-6) continue;
+ const sign = Math.sign(d);
+ if (last !== 0 && sign !== last) changes++;
+ last = sign;
+ }
+ return changes;
+ };
+ expect(directionChanges(30, 140)).toBe(0);
+ expect(directionChanges(140, 240)).toBe(0);
+ // And zoom itself only ever goes up, then only down.
+ for (let f = 31; f < 140; f++)
+ expect(plan.scale[f] ?? 0).toBeGreaterThanOrEqual(
+ (plan.scale[f - 1] ?? 0) - 1e-9,
+ );
+ for (let f = 141; f < 240; f++)
+ expect(plan.scale[f] ?? 0).toBeLessThanOrEqual(
+ (plan.scale[f - 1] ?? 0) + 1e-9,
+ );
+ });
+});
+
+describe("shotsFromClicks", () => {
+ const o = {
+ width: 1920,
+ height: 1080,
+ lead: 20,
+ idle: 40,
+ zoom: 1.8,
+ maxZoom: 2.5,
+ padding: 160,
+ };
+
+ it("clusters clicks close in time and space", () => {
+ const shots = shotsFromClicks(
+ [
+ { frame: 100, point: [500, 500] },
+ { frame: 130, point: [600, 520] },
+ { frame: 400, point: [1500, 300] },
+ ],
+ o,
+ );
+ expect(shots).toHaveLength(2);
+ expect(shots[0]).toMatchObject({ start: 80, end: 170 });
+ expect(shots[1]).toMatchObject({ start: 380, end: 440 });
+ });
+
+ it("zooms out enough to fit a wide cluster", () => {
+ const [shot] = shotsFromClicks(
+ [
+ { frame: 10, point: [300, 500] },
+ { frame: 20, point: [1100, 500] },
+ ],
+ o,
+ );
+ expect(shot?.zoom).toBeLessThan(1.8);
+ expect(shot?.zoom).toBeGreaterThanOrEqual(1);
+ });
+
+ it("keeps a pushed-in click near the middle of the screen, with the camera still", () => {
+ const shots = shotsFromClicks([{ frame: 60, point: [1500, 300] }], o);
+ const plan = solveCamera({ ...base, length: 160, shots });
+ const s = plan.states[60];
+ const prev = plan.states[59];
+ const screenX = 960 + (1500 - (s?.cx ?? 0)) * (s?.zoom ?? 1);
+ const screenY = 540 + (300 - (s?.cy ?? 0)) * (s?.zoom ?? 1);
+ expect(Math.abs(screenX - 960)).toBeLessThan(1920 * 0.3);
+ expect(Math.abs(screenY - 540)).toBeLessThan(1080 * 0.3);
+ const moved =
+ Math.hypot(
+ (s?.cx ?? 0) - (prev?.cx ?? 0),
+ (s?.cy ?? 0) - (prev?.cy ?? 0),
+ ) * (s?.zoom ?? 1);
+ expect(moved).toBeLessThan(6);
+ });
+});
diff --git a/packages/components/src/focus-zoom/plan.ts b/packages/components/src/focus-zoom/plan.ts
new file mode 100644
index 00000000..fa054cf1
--- /dev/null
+++ b/packages/components/src/focus-zoom/plan.ts
@@ -0,0 +1,252 @@
+/**
+ * The FocusZoom camera solver: which framing each frame wants (shots, or
+ * clusters of pointer clicks), and how the camera moves between framings.
+ *
+ * Moves interpolate the view rectangle — all four edges on one eased curve —
+ * between framings that are already clamped. That keeps every content point
+ * moving one way on screen (no sideways wiggle while zooming), and a convex
+ * blend of two in-bounds views never shows past the bounds, so nothing is
+ * clamped mid-move. Smoothing pan and zoom separately and clamping the result
+ * does neither.
+ */
+import type { Vec2 } from "../core/path.js";
+
+export interface CameraState {
+ /** Content point at the centre of the view. */
+ cx: number;
+ cy: number;
+ zoom: number;
+}
+
+export interface ShotWindow {
+ start: number;
+ end: number;
+ center: Vec2 | ((frame: number) => Vec2);
+ zoom: number;
+ /** The move must have landed by this frame (e.g. the first click). */
+ settleBy?: number;
+}
+
+export interface CameraInput {
+ width: number;
+ height: number;
+ length: number;
+ fps: number;
+ shots: ShotWindow[];
+ /** 0 = quick moves, 1 = slow, soft moves. */
+ smoothing: number;
+ clamp: boolean;
+ /** The region the view must stay inside when zoomed (default: the whole view). */
+ bounds?: { x: number; y: number; width: number; height: number };
+}
+
+export interface CameraPlan {
+ states: CameraState[];
+ /** Wrapper transform per frame (anchor at its top-left). */
+ x: number[];
+ y: number[];
+ scale: number[];
+ shots: Array<{
+ frame: number;
+ settled: number;
+ end: number;
+ zoom: number;
+ center: Vec2;
+ }>;
+}
+
+/** The visible content rectangle: left, top, right, bottom. */
+interface View {
+ x0: number;
+ y0: number;
+ x1: number;
+ y1: number;
+}
+
+/** Minimum-jerk ease: zero velocity and acceleration at both ends. */
+const ease = (t: number) => {
+ const s = Math.min(1, Math.max(0, t));
+ return s * s * s * (10 - 15 * s + 6 * s * s);
+};
+
+export function solveCamera(input: CameraInput): CameraPlan {
+ const { width: W, height: H, fps } = input;
+ const smoothing = Math.min(1, Math.max(0, input.smoothing));
+
+ const toView = (s: CameraState): View => {
+ const hw = W / (2 * s.zoom);
+ const hh = H / (2 * s.zoom);
+ return { x0: s.cx - hw, y0: s.cy - hh, x1: s.cx + hw, y1: s.cy + hh };
+ };
+ const toState = (v: View): CameraState => ({
+ cx: (v.x0 + v.x1) / 2,
+ cy: (v.y0 + v.y1) / 2,
+ zoom: W / (v.x1 - v.x0),
+ });
+ const lerpView = (a: View, b: View, t: number): View => ({
+ x0: a.x0 + (b.x0 - a.x0) * t,
+ y0: a.y0 + (b.y0 - a.y0) * t,
+ x1: a.x1 + (b.x1 - a.x1) * t,
+ y1: a.y1 + (b.y1 - a.y1) * t,
+ });
+
+ /** Clamp a framing (never a frame of motion): inside the view, then the bounds. */
+ const clampState = (s: CameraState): CameraState => {
+ if (!input.clamp) return s;
+ const zoom = Math.max(1, s.zoom);
+ const hw = W / (2 * zoom);
+ const hh = H / (2 * zoom);
+ const fit = (c: number, lo: number, hi: number, half: number) =>
+ hi - lo >= 2 * half
+ ? Math.min(hi - half, Math.max(lo + half, c))
+ : (lo + hi) / 2;
+ let cx = fit(s.cx, 0, W, hw);
+ let cy = fit(s.cy, 0, H, hh);
+ const b = input.bounds;
+ if (b && zoom > 1) {
+ cx = fit(cx, b.x, b.x + b.width, hw);
+ cy = fit(cy, b.y, b.y + b.height, hh);
+ // Bounds never push the view past the content itself.
+ cx = fit(cx, 0, W, hw);
+ cy = fit(cy, 0, H, hh);
+ }
+ return { cx, cy, zoom };
+ };
+
+ const full: CameraState = { cx: W / 2, cy: H / 2, zoom: 1 };
+ const shotAt = (frame: number): number => {
+ let pick = -1;
+ input.shots.forEach((s, i) => {
+ if (frame >= s.start && frame < s.end) pick = i;
+ });
+ return pick;
+ };
+ const framing = (index: number, frame: number): CameraState => {
+ const s = input.shots[index];
+ if (!s) return full;
+ const c = typeof s.center === "function" ? s.center(frame) : s.center;
+ return clampState({ cx: c[0], cy: c[1], zoom: s.zoom });
+ };
+
+ // Move length: a base set by `smoothing`, longer for bigger zoom changes.
+ const moveFrames = (from: View, to: View) => {
+ const ratio = Math.abs(Math.log((to.x1 - to.x0) / (from.x1 - from.x0)));
+ const base = 0.55 + 0.75 * smoothing;
+ const seconds = base * (0.75 + 0.25 * Math.min(1, ratio / Math.LN2));
+ return Math.max(2, Math.round(seconds * fps));
+ };
+ // Holding on a moving target: follow it softly (exponential, so it never
+ // overshoots and never reverses).
+ const follow = 1 - Math.exp(-(8 - 5 * smoothing) / fps);
+
+ let current = toView(framing(shotAt(0), 0));
+ let active = shotAt(0);
+ let move: { from: View; start: number; frames: number } | null = null;
+ const settledAt = new Map<number, number>();
+ const states: CameraState[] = [];
+
+ for (let f = 0; f < input.length; f++) {
+ const index = shotAt(f);
+ const target = toView(framing(index, f));
+ if (index !== active) {
+ const settleBy = input.shots[index]?.settleBy;
+ const natural = moveFrames(current, target);
+ const frames =
+ settleBy === undefined
+ ? natural
+ : Math.max(2, Math.min(natural, settleBy - f));
+ move = { from: current, start: f, frames };
+ active = index;
+ }
+ if (move) {
+ const t = (f - move.start) / move.frames;
+ current = lerpView(move.from, target, ease(t));
+ if (t >= 1) {
+ move = null;
+ if (index >= 0 && !settledAt.has(index)) settledAt.set(index, f);
+ }
+ } else {
+ current = lerpView(current, target, follow);
+ if (index >= 0 && !settledAt.has(index)) settledAt.set(index, f);
+ }
+ states.push(toState(current));
+ }
+
+ const shots = input.shots.map((s, i) => {
+ const c = typeof s.center === "function" ? s.center(s.start) : s.center;
+ return {
+ frame: s.start,
+ settled: settledAt.get(i) ?? s.end,
+ end: s.end,
+ zoom: s.zoom,
+ center: c,
+ };
+ });
+
+ return {
+ states,
+ x: states.map((s) => W / 2 - s.zoom * s.cx),
+ y: states.map((s) => H / 2 - s.zoom * s.cy),
+ scale: states.map((s) => s.zoom),
+ shots,
+ };
+}
+
+export interface ClickEvent {
+ frame: number;
+ point: Vec2;
+}
+
+/**
+ * Shots from pointer clicks: nearby clicks close in time share one push-in
+ * that starts `lead` frames before the first and lets go `idle` frames after
+ * the last, framed on the cluster. The camera doesn't chase the pointer: a
+ * still frame reads calmer and keeps the click where the eye already is.
+ */
+export function shotsFromClicks(
+ clicks: ClickEvent[],
+ o: {
+ width: number;
+ height: number;
+ lead: number;
+ idle: number;
+ zoom: number;
+ maxZoom: number;
+ padding: number;
+ },
+): ShotWindow[] {
+ const sorted = [...clicks].sort((a, b) => a.frame - b.frame);
+ const clusters: ClickEvent[][] = [];
+ for (const c of sorted) {
+ const current = clusters[clusters.length - 1];
+ const last = current?.[current.length - 1];
+ const near =
+ last &&
+ c.frame - last.frame <= o.idle + o.lead &&
+ Math.abs(c.point[0] - last.point[0]) < (o.width / o.zoom) * 0.8 &&
+ Math.abs(c.point[1] - last.point[1]) < (o.height / o.zoom) * 0.8;
+ if (current && near) current.push(c);
+ else clusters.push([c]);
+ }
+ return clusters.map((cluster) => {
+ const xs = cluster.map((c) => c.point[0]);
+ const ys = cluster.map((c) => c.point[1]);
+ const x0 = Math.min(...xs) - o.padding;
+ const x1 = Math.max(...xs) + o.padding;
+ const y0 = Math.min(...ys) - o.padding;
+ const y1 = Math.max(...ys) + o.padding;
+ const fit = Math.min(
+ o.width / Math.max(1, x1 - x0),
+ o.height / Math.max(1, y1 - y0),
+ );
+ const first = cluster[0]?.frame ?? 0;
+ const last = cluster[cluster.length - 1]?.frame ?? first;
+ return {
+ start: Math.max(0, first - o.lead),
+ end: last + o.idle,
+ settleBy: first - 2,
+ zoom: Math.max(1, Math.min(o.zoom, o.maxZoom, fit)),
+ center: [(x0 + x1) / 2, (y0 + y1) / 2] as Vec2,
+ };
+ });
+}
diff --git a/packages/components/src/index.ts b/packages/components/src/index.ts
index 90f2dd57..0265072b 100644
--- a/packages/components/src/index.ts
+++ b/packages/components/src/index.ts
@@ -4,6 +4,18 @@
* top-level calls, so every export tree-shakes on its own.
*/
+export {
+ type AnnotateCues,
+ annotate,
+ MARKS,
+ type Mark,
+} from "./annotate/index.js";
+export {
+ type AppFrameApi,
+ type AppFrameCues,
+ type AppFrameKind,
+ appFrame,
+} from "./app-frame/index.js";
export {
type BakedKey,
type BakeOptions,
@@ -14,9 +26,9 @@ export {
} from "./core/bake.js";
export {
type BaseProps,
- BasePropsSchema,
type BuildContext,
type BuildResult,
+ basePropsSchema,
bind,
type ComponentDefaults,
type ComponentDefinition,
@@ -27,6 +39,7 @@ export {
type CuesOf,
defineComponent,
offsetCues,
+ type Placement,
type PropsOf,
type PulseOptions,
pulseKeys,
@@ -46,7 +59,23 @@ export {
wobblePoints,
} from "./core/draw.js";
export { type EaseFn, ease, evaluateEase } from "./core/ease.js";
-export type { Animatable, AnimatableMethods, Host } from "./core/host.js";
+export {
+ constantExpression,
+ evaluateGlyphExpression,
+ type GlyphAnimator,
+ type GlyphProps,
+ type GlyphUnit,
+ glyphAnimator,
+ scheduleExpression,
+ type UnitSchedule,
+} from "./core/glyphs.js";
+export type {
+ Animatable,
+ AnimatableMethods,
+ Host,
+ LayerStyleConfig,
+ MediaOptions,
+} from "./core/host.js";
export { type ComponentMeta, defineMeta } from "./core/meta.js";
export {
enterAnimation,
@@ -55,6 +84,7 @@ export {
type MotionOptions,
type MotionPreset,
type MotionPresetName,
+ type MotionSize,
type ResolvedMotion,
resolveMotion,
} from "./core/motion.js";
@@ -80,6 +110,7 @@ export {
} from "./core/targets.js";
export {
findRange,
+ lineShift,
type MeasureFn,
type MeasureOptions,
type Metrics,
@@ -111,3 +142,31 @@ export {
toSeconds,
within,
} from "./core/timing.js";
+export {
+ type CounterCues,
+ type CounterFormat,
+ counter,
+} from "./counter/index.js";
+export {
+ type FocusZoomApi,
+ type FocusZoomCues,
+ type Followable,
+ focusZoom,
+} from "./focus-zoom/index.js";
+export {
+ CURSOR_STYLES,
+ type CursorStyle,
+ type MousePointerApi,
+ type MousePointerCues,
+ mousePointer,
+ type Waypoint,
+} from "./mouse-pointer/index.js";
+export {
+ EXIT_STYLES,
+ type ExitStyle,
+ REVEAL_STYLES,
+ type RevealStyle,
+ type TextRevealApi,
+ type TextRevealCues,
+ textReveal,
+} from "./text-reveal/index.js";
diff --git a/packages/components/src/mouse-pointer/glyphs.ts b/packages/components/src/mouse-pointer/glyphs.ts
new file mode 100644
index 00000000..eebf54da
--- /dev/null
+++ b/packages/components/src/mouse-pointer/glyphs.ts
@@ -0,0 +1,176 @@
+/**
+ * Cursor glyphs, drawn on a 24-unit grid and scaled to `size` px. Each glyph
+ * is a few paths painted with the pointer's `color` (fill), `accent`, or as
+ * strokes, plus the hotspot: the grid point that lands on the target.
+ */
+import type { Vec2 } from "../core/path.js";
+
+export const CURSOR_STYLES = [
+ "arrow",
+ "triangle",
+ "chevron",
+ "dot",
+ "ring",
+ "target",
+ "crosshair",
+ "plus",
+ "ibeam",
+ "caret",
+ "square",
+ "diamond",
+ "sparkle",
+ "hand",
+] as const;
+
+export type CursorStyle = (typeof CURSOR_STYLES)[number];
+
+export interface GlyphPart {
+ /** Absolute path data on the 24-unit grid (M L C Z only). */
+ d: string;
+ /** `fill` / `accent` are filled shapes; `stroke` / `accent-stroke` are lines. */
+ paint: "fill" | "accent" | "stroke" | "accent-stroke";
+ /** Line width in grid units, for stroke paints. */
+ width?: number;
+}
+
+export interface Glyph {
+ parts: GlyphPart[];
+ /** The point that lands on the target, in grid units. */
+ hotspot: Vec2;
+ /** Glyphs that read as a direction rotate with travel when `autoOrient` is on. */
+ directional?: boolean;
+}
+
+/** A closed circle as cubic Béziers (no arcs, so it scales with the rest). */
+function circle(cx: number, cy: number, r: number): string {
+ const k = 0.5523 * r;
+ return [
+ `M${cx + r} ${cy}`,
+ `C${cx + r} ${cy + k} ${cx + k} ${cy + r} ${cx} ${cy + r}`,
+ `C${cx - k} ${cy + r} ${cx - r} ${cy + k} ${cx - r} ${cy}`,
+ `C${cx - r} ${cy - k} ${cx - k} ${cy - r} ${cx} ${cy - r}`,
+ `C${cx + k} ${cy - r} ${cx + r} ${cy - k} ${cx + r} ${cy}`,
+ "Z",
+ ].join(" ");
+}
+
+function rect(x0: number, y0: number, x1: number, y1: number): string {
+ return `M${x0} ${y0} L${x1} ${y0} L${x1} ${y1} L${x0} ${y1} Z`;
+}
+
+const CENTER: Vec2 = [12, 12];
+
+let library: Record<CursorStyle, Glyph> | undefined;
+
+/** The glyph for a style (the library is built on first use). */
+export function glyphFor(style: CursorStyle): Glyph {
+ library ??= buildGlyphs();
+ return library[style];
+}
+
+function buildGlyphs(): Record<CursorStyle, Glyph> {
+ return {
+ // The classic pointer: head, notch and tail as one silhouette.
+ arrow: {
+ parts: [
+ {
+ d: "M4 2.5 L4 19.4 L8.3 15.4 L11.2 21.8 L14.3 20.4 L11.5 14.2 L17.4 14.2 Z",
+ paint: "fill",
+ },
+ ],
+ hotspot: [4, 2.5],
+ },
+ // The arrow's head alone: the pure-shape pointer.
+ triangle: {
+ parts: [{ d: "M4 2.5 L4 19.6 L17.6 13.9 Z", paint: "fill" }],
+ hotspot: [4, 2.5],
+ directional: true,
+ },
+ // A notched dart, the modern design-tool pointer.
+ chevron: {
+ parts: [
+ { d: "M4.5 3 L20.2 10.4 L12.7 12.7 L10.4 20.2 Z", paint: "fill" },
+ ],
+ hotspot: [4.5, 3],
+ directional: true,
+ },
+ dot: {
+ parts: [{ d: circle(12, 12, 6), paint: "fill" }],
+ hotspot: CENTER,
+ },
+ ring: {
+ parts: [{ d: circle(12, 12, 7.5), paint: "stroke", width: 2.4 }],
+ hotspot: CENTER,
+ },
+ target: {
+ parts: [
+ { d: circle(12, 12, 8), paint: "stroke", width: 2 },
+ { d: circle(12, 12, 2.6), paint: "accent" },
+ ],
+ hotspot: CENTER,
+ },
+ crosshair: {
+ parts: [
+ { d: rect(11.1, 2.5, 12.9, 8.5), paint: "fill" },
+ { d: rect(11.1, 15.5, 12.9, 21.5), paint: "fill" },
+ { d: rect(2.5, 11.1, 8.5, 12.9), paint: "fill" },
+ { d: rect(15.5, 11.1, 21.5, 12.9), paint: "fill" },
+ { d: circle(12, 12, 1.4), paint: "accent" },
+ ],
+ hotspot: CENTER,
+ },
+ plus: {
+ parts: [
+ { d: rect(10, 4, 14, 20), paint: "fill" },
+ { d: rect(4, 10, 20, 14), paint: "fill" },
+ ],
+ hotspot: CENTER,
+ },
+ ibeam: {
+ parts: [
+ { d: rect(11.2, 4.6, 12.8, 19.4), paint: "fill" },
+ { d: rect(8.8, 3.2, 15.2, 4.9), paint: "fill" },
+ { d: rect(8.8, 19.1, 15.2, 20.8), paint: "fill" },
+ ],
+ hotspot: CENTER,
+ },
+ caret: {
+ parts: [{ d: rect(11, 3, 13, 21), paint: "accent" }],
+ hotspot: CENTER,
+ },
+ square: {
+ parts: [{ d: rect(6, 6, 18, 18), paint: "fill" }],
+ hotspot: CENTER,
+ },
+ diamond: {
+ parts: [{ d: "M12 3.5 L20.5 12 L12 20.5 L3.5 12 Z", paint: "fill" }],
+ hotspot: CENTER,
+ },
+ sparkle: {
+ parts: [
+ {
+ d: "M12 2 C12.8 8.4 15.6 11.2 22 12 C15.6 12.8 12.8 15.6 12 22 C11.2 15.6 8.4 12.8 2 12 C8.4 11.2 11.2 8.4 12 2 Z",
+ paint: "accent",
+ },
+ ],
+ hotspot: CENTER,
+ },
+ // A pointing hand: fingertip is the hotspot.
+ hand: {
+ parts: [
+ {
+ d: [
+ "M7.2 4.6 C7.2 3.5 8.1 2.6 9.2 2.6 C10.3 2.6 11.2 3.5 11.2 4.6",
+ "L11.2 10.1 C11.6 9.7 12.2 9.5 12.9 9.6 C13.6 9.7 14.2 10.2 14.4 10.9",
+ "C14.8 10.5 15.5 10.3 16.2 10.5 C16.9 10.7 17.4 11.3 17.5 12",
+ "C17.9 11.7 18.5 11.6 19.1 11.8 C19.9 12.1 20.4 12.8 20.4 13.7",
+ "L20.4 16.4 C20.4 19.5 17.9 22 14.8 22 L12.4 22 C10.6 22 9 21.1 8 19.6",
+ "L4.8 14.7 C4.3 13.9 4.5 12.9 5.2 12.4 C5.9 11.9 6.8 12 7.2 12.6 Z",
+ ].join(" "),
+ paint: "fill",
+ },
+ ],
+ hotspot: [9.2, 2.8],
+ },
+ };
+}
diff --git a/packages/components/src/mouse-pointer/index.test.ts b/packages/components/src/mouse-pointer/index.test.ts
new file mode 100644
index 00000000..dfac6548
--- /dev/null
+++ b/packages/components/src/mouse-pointer/index.test.ts
@@ -0,0 +1,89 @@
+import type { LayoutNode } from "@framefields/compositions/program";
+import { describe, expect, it } from "vitest";
+import { bind } from "../core/contract.js";
+import { fakeHost } from "../test/fake-host.js";
+import { mousePointer } from "./index.js";
+
+const make = () => bind(fakeHost(), mousePointer);
+
+describe("MousePointer", () => {
+ it("covers its area from 0, 0 and reports cues on the parent's timeline", () => {
+ const p = make()({
+ at: 30,
+ path: [{ to: [100, 100] }, { to: [600, 400], click: true }],
+ });
+ expect(p).toMatchObject({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: 1920,
+ height: 1080,
+ startFrame: 30,
+ });
+ const click = p.cues.clicks[0];
+ expect(click?.frame).toBeGreaterThan(30);
+ expect(click?.point).toEqual([600, 400]);
+ expect(p.positionAt(click?.frame ?? 0)).toEqual([600, 400]);
+ expect(p.span.duration).toBeGreaterThan((click?.frame ?? 0) - 30);
+ });
+
+ it("aims at node centres and text glyphs", () => {
+ const button = { id: "btn", x: 200, y: 300, width: 120, height: 40 };
+ const title = {
+ id: "t",
+ kind: "text",
+ x: 400,
+ y: 100,
+ text: "Ship it",
+ fontFamily: "Inter",
+ fontSize: 20,
+ };
+ const p = make()({
+ path: [
+ { to: { node: button }, click: true },
+ { to: { text: title, match: "it" }, click: true },
+ ],
+ });
+ expect(p.cues.clicks[0]).toMatchObject({
+ point: [260, 320],
+ target: "btn",
+ });
+ // Text lands at the start of the match, mid-line (fixed 10 px glyphs).
+ expect(p.cues.clicks[1]?.point).toEqual([450, 112]);
+ });
+
+ it("builds one glyph per style used, a ripple per click, a trail and a label", () => {
+ const p = make()({
+ path: [
+ { to: [100, 100], click: 2 },
+ { to: [500, 100], cursor: "hand" },
+ ],
+ trail: { length: 3 },
+ label: "Ada",
+ });
+ expect(p.part("glyph-arrow")).toBeDefined();
+ expect(p.part("glyph-hand")).toBeDefined();
+ expect(p.part("label")).toBeDefined();
+ const stage = p.part("stage") as unknown as { children: LayoutNode[] };
+ const ids = stage.children.map((c) => c.id);
+ expect(ids.filter((id) => id.includes("ripple"))).toHaveLength(2);
+ expect(ids.filter((id) => id.includes("trail"))).toHaveLength(3);
+ expect(ids.at(-1)).toMatch(/-motion$/);
+ });
+
+ it("enters from an edge of its area", () => {
+ const p = make()({
+ from: "left",
+ path: [{ to: [500, 300] }],
+ area: { width: 1000, height: 600 },
+ });
+ expect(p.positionAt(0)[0]).toBeLessThan(0);
+ expect(p.positionAt(0)[1]).toBe(300);
+ });
+
+ it("rejects unknown waypoint fields", () => {
+ expect(() =>
+ make()({ path: [{ to: [0, 0], clik: true } as never] }),
+ ).toThrow(/clik/);
+ });
+});
diff --git a/packages/components/src/mouse-pointer/index.ts b/packages/components/src/mouse-pointer/index.ts
new file mode 100644
index 00000000..f650d78c
--- /dev/null
+++ b/packages/components/src/mouse-pointer/index.ts
@@ -0,0 +1,785 @@
+/**
+ * MousePointer: an animated pointer that travels between targets, clicks,
+ * drags and changes shape, with exact cues for everything it does.
+ *
+ * Coordinates are the parent's: the pointer's root covers `area` from 0, 0,
+ * so targets resolve where they are drawn.
+ */
+import {
+ type AnimatableProp,
+ type KeyframeTuple,
+ LayerAnimation,
+ type LayoutNode,
+} from "@framefields/compositions/program";
+import { z } from "zod";
+import { bakeSamples } from "../core/bake.js";
+import { defineComponent } from "../core/contract.js";
+import type { Animatable } from "../core/host.js";
+import { transformPathData, type Vec2 } from "../core/path.js";
+import { targetSchema } from "../core/schemas.js";
+import { resolveTarget, type Target, targetPoint } from "../core/targets.js";
+import { contrastRatio } from "../core/theme.js";
+import {
+ CURSOR_STYLES,
+ type CursorStyle,
+ type Glyph,
+ glyphFor,
+} from "./glyphs.js";
+import {
+ type PlannedWaypoint,
+ type PointAt,
+ type PointerPlan,
+ planPointer,
+} from "./plan.js";
+
+export { CURSOR_STYLES, type CursorStyle } from "./glyphs.js";
+
+const EDGES = ["left", "right", "top", "bottom"] as const;
+type Edge = (typeof EDGES)[number];
+
+/** A waypoint's schema (built on first use). */
+function waypointSchema() {
+ const frames = z.number().int().min(0);
+ return z
+ .object({
+ /** Where to go. */
+ to: targetSchema(),
+ /** Arrival frame (component-local). Default: from distance and `speed`. */
+ at: frames.optional(),
+ /** Frames to rest after arriving (and clicking). */
+ dwell: frames.optional(),
+ /** Click on arrival: `true`, a count (2 = double click), or details. */
+ click: z
+ .union([
+ z.boolean(),
+ z.number().int().min(1).max(3),
+ z.object({
+ count: z.number().int().min(1).max(3).default(1),
+ hold: frames.optional(),
+ }),
+ ])
+ .optional(),
+ /** Press here and drag to this target. */
+ drag: targetSchema().optional(),
+ /** Switch cursor style on arrival, for good. */
+ cursor: z.enum(CURSOR_STYLES).optional(),
+ })
+ .strict();
+}
+
+export type Waypoint = z.input<ReturnType<typeof waypointSchema>>;
+
+export interface MousePointerCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ arrivals: ReadonlyArray<{ frame: number; point: Vec2; index: number }>;
+ presses: ReadonlyArray<{ frame: number; point: Vec2 }>;
+ releases: ReadonlyArray<{ frame: number; point: Vec2 }>;
+ clicks: ReadonlyArray<{
+ frame: number;
+ point: Vec2;
+ index: number;
+ target?: string;
+ }>;
+ drags: ReadonlyArray<{ frame: number; end: number; from: Vec2; to: Vec2 }>;
+}
+
+export interface MousePointerApi {
+ /** Pointer hotspot in the parent's coordinates at a parent-timeline frame. */
+ positionAt(frame: number): Vec2;
+ /** Cursor style showing at a parent-timeline frame. */
+ styleAt(frame: number): CursorStyle;
+}
+
+export const mousePointer = /* @__PURE__ */ defineComponent({
+ name: "MousePointer",
+ props: () => ({
+ /** The performance: where to go, and what to do there. */
+ path: z.array(waypointSchema()).min(1),
+ style: z.enum(CURSOR_STYLES).default("arrow"),
+ /** Glyph size in px (the 24-unit design grid). Default 44 × theme.scale. */
+ size: z.number().positive().optional(),
+ /** Glyph fill. Default near-black, outlined in white: reads on anything. */
+ color: z.string().default("#101114"),
+ /** Secondary color (target dots, sparkles, ripples). Default theme accent. */
+ accent: z.string().optional(),
+ outline: z.union([z.string(), z.literal(false)]).default("#ffffff"),
+ /** Outline width in px. Default size / 16. */
+ outlineWidth: z.number().min(0).optional(),
+ /** `union` outlines the whole silhouette (no seams between parts); `each` outlines parts separately. */
+ outlineMode: z.enum(["union", "each"]).default("union"),
+ motion: z.enum(["natural", "swift", "lazy", "linear"]).default("natural"),
+ /** Travel-time multiplier: 2 = twice as fast. */
+ speed: z.number().positive().default(1),
+ /** Idle drift in px while resting (0 = perfectly still). */
+ drift: z.number().min(0).default(1.5),
+ /** Rotate directional glyphs (triangle, chevron) along travel. */
+ autoOrient: z.boolean().default(false),
+ /** Fading dots behind the pointer while it moves. */
+ trail: z
+ .union([
+ z.literal(false),
+ z.object({
+ length: z.number().int().min(1).max(16).default(6),
+ spacing: z.number().int().min(1).default(1),
+ color: z.string().optional(),
+ }),
+ ])
+ .default(false),
+ /** How the glyph reacts to a press. */
+ feedback: z
+ .enum(["press", "bounce", "pulse"])
+ .or(z.literal(false))
+ .default("press"),
+ /** The mark a click leaves where it lands. */
+ ripple: z
+ .enum(["ring", "fill", "pulse"])
+ .or(z.literal(false))
+ .default("ring"),
+ /** Style swaps while the hotspot is inside a region. */
+ hoverRegions: z
+ .array(
+ z
+ .object({ target: targetSchema(), style: z.enum(CURSOR_STYLES) })
+ .strict(),
+ )
+ .default([]),
+ /** A name tag that rides beside the pointer (agents, collaborators). */
+ label: z
+ .union([
+ z.string(),
+ z.object({ text: z.string(), color: z.string().optional() }).strict(),
+ ])
+ .optional(),
+ /** Velocity motion blur on travel. `true` = a 45° shutter (a hint of blur that keeps the glyph crisp), or an angle. */
+ motionBlur: z
+ .union([z.boolean(), z.number().min(0).max(360)])
+ .default(true),
+ /** Soft drop shadow under the glyph. */
+ shadow: z.boolean().default(true),
+ /** Enter from off-frame on this edge (or from a point) instead of appearing in place. */
+ from: z.union([z.enum(EDGES), targetSchema()]).optional(),
+ /** Leave to off-frame on this edge (or to a point) instead of fading away. */
+ to: z.union([z.enum(EDGES), targetSchema()]).optional(),
+ /** The frame the pointer lives in (for edges). Default 1920 × 1080. */
+ area: z
+ .object({ width: z.number().positive(), height: z.number().positive() })
+ .default({ width: 1920, height: 1080 }),
+ }),
+ defaults: { enter: false, exit: false },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const size = props.size ?? 44 * theme.scale;
+ const k = size / 24;
+ const accent = props.accent ?? theme.color.accent;
+ const outlineWidth = props.outlineWidth ?? size / 16;
+ const { width: W, height: H } = props.area;
+
+ const resolvePoint = (target: Target): { point: PointAt; id?: string } => {
+ const resolved = resolveTarget(target, { measure: host.measure, fps });
+ const isText =
+ typeof target === "object" &&
+ !Array.isArray(target) &&
+ "text" in target;
+ const node =
+ typeof target === "object" && !Array.isArray(target) && "node" in target
+ ? target.node
+ : undefined;
+ const id = typeof node?.id === "string" ? node.id : undefined;
+ if (resolved.kind === "static") {
+ const p = targetPoint(resolved, 0, isText);
+ return { point: () => p, id };
+ }
+ return { point: (frame) => targetPoint(resolved, frame, isText), id };
+ };
+ const edgePoint = (edge: Edge, near: Vec2): Vec2 => {
+ const off = size * 1.5;
+ if (edge === "left") return [-off, near[1]];
+ if (edge === "right") return [W + off, near[1]];
+ if (edge === "top") return [near[0], -off];
+ return [near[0], H + off];
+ };
+
+ const waypoints: PlannedWaypoint[] = props.path.map((wp) => {
+ const { point, id } = resolvePoint(wp.to);
+ const click =
+ wp.click === undefined || wp.click === false
+ ? undefined
+ : wp.click === true
+ ? { count: 1 }
+ : typeof wp.click === "number"
+ ? { count: wp.click }
+ : wp.click;
+ return {
+ point,
+ at: wp.at,
+ dwell: wp.dwell,
+ clicks: click?.count,
+ hold: click && "hold" in click ? click.hold : undefined,
+ drag: wp.drag ? resolvePoint(wp.drag).point : undefined,
+ cursor: wp.cursor,
+ targetId: id,
+ };
+ });
+ const firstPoint = waypoints[0]?.point(0) ?? [0, 0];
+ const lastPoint = waypoints[waypoints.length - 1]?.point(0) ?? firstPoint;
+ const fromPoint =
+ props.from === undefined
+ ? undefined
+ : typeof props.from === "string"
+ ? edgePoint(props.from, firstPoint)
+ : resolvePoint(props.from).point(0);
+ const toPoint =
+ props.to === undefined
+ ? undefined
+ : typeof props.to === "string"
+ ? edgePoint(props.to, lastPoint)
+ : resolvePoint(props.to).point(0);
+
+ const fade = Math.max(1, Math.round((7 * fps) / 30));
+ const plan = planPointer({
+ waypoints,
+ fps,
+ style: props.style,
+ motion: props.motion,
+ speed: props.speed,
+ drift: props.drift,
+ seed: ctx.seed,
+ from: fromPoint,
+ to: toPoint,
+ hoverRegions: props.hoverRegions.map((r) => {
+ const resolved = resolveTarget(r.target, {
+ measure: host.measure,
+ fps,
+ });
+ if (resolved.kind !== "static")
+ throw new Error(
+ "MousePointer: hover regions must be static targets.",
+ );
+ const rects = resolved.rects;
+ const x0 = Math.min(...rects.map((q) => q.x));
+ const y0 = Math.min(...rects.map((q) => q.y));
+ const x1 = Math.max(...rects.map((q) => q.x + q.width));
+ const y1 = Math.max(...rects.map((q) => q.y + q.height));
+ return {
+ rect: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 },
+ style: r.style,
+ };
+ }),
+ appear: fromPoint ? 0 : fade,
+ vanish: toPoint ? 0 : fade,
+ });
+
+ // Visibility: pop in at the start, fade out at the end (unless it
+ // travels on or off frame, which needs no fade).
+ const visibility = (f: number): number => {
+ const inAt = fromPoint ? 1 : smooth(f / fade);
+ const outAt = toPoint ? 1 : 1 - smooth((f - plan.vanishAt) / fade);
+ return Math.max(0, Math.min(inAt, outAt));
+ };
+ const appearScale = (f: number): number => {
+ if (fromPoint) return 1;
+ const t = f / fade;
+ return t >= 1 ? 1 : 0.6 + 0.4 * backOut(Math.max(0, t));
+ };
+ const pressScale = pressProfile(plan, props.feedback);
+
+ // ── Glyph boxes, one per style used ──────────────────────────────
+ const used = [
+ ...new Set([props.style, ...plan.styles.map((w) => w.style)]),
+ ];
+ const margin = Math.ceil(size * 0.4);
+ const box = size + margin * 2;
+
+ // Label geometry first: it sizes the moving box.
+ const labelText =
+ props.label === undefined
+ ? undefined
+ : typeof props.label === "string"
+ ? props.label
+ : props.label.text;
+ const labelFont = Math.round(size * 0.4);
+ const labelMetrics =
+ labelText === undefined
+ ? undefined
+ : host.measure(labelText, {
+ fontFamily: theme.font.body,
+ fontSize: labelFont,
+ fontWeight: 600,
+ });
+ const labelPadX = Math.round(labelFont * 0.62);
+ const labelH = Math.round(labelFont * 1.8);
+ const labelW = labelMetrics
+ ? Math.ceil(labelMetrics.width + labelPadX * 2)
+ : 0;
+ const labelX = Math.round(size * 0.46);
+ const labelY = Math.round(size * 0.6);
+
+ // The moving part is a real box centred on the hotspot (very small
+ // boxes are culled), big enough for the glyph, its shadow and label.
+ const half = Math.ceil(
+ Math.max(
+ box,
+ labelMetrics ? Math.max(labelX + labelW, labelY + labelH) + 24 : 0,
+ ),
+ );
+ const extent = half * 2;
+ const swap = Math.max(1, Math.round((2 * fps) / 30));
+ const glyphBoxes: Array<Animatable<LayoutNode>> = [];
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+
+ for (const style of used) {
+ const glyph = glyphFor(style);
+ const [hx, hy] = glyph.hotspot;
+ const weight = (f: number) => styleWeight(plan, style, f, swap);
+ const opacity = samples(plan.length, (f) => visibility(f) * weight(f));
+ const scale = samples(
+ plan.length,
+ (f) => appearScale(f) * pressScale(f) * (0.9 + 0.1 * weight(f)),
+ );
+ const shapes = glyphShapes(ctx, glyph, style, {
+ k,
+ margin,
+ color: props.color,
+ accent,
+ outline: props.outline === false ? null : props.outline,
+ outlineWidth,
+ mode: props.outlineMode,
+ });
+ const g = host.box({
+ id: ctx.partId(`glyph-${style}`),
+ position: "absolute",
+ x: half - hx * k - margin,
+ y: half - hy * k - margin,
+ width: box,
+ height: box,
+ anchorX: (hx * k + margin) / box,
+ anchorY: (hy * k + margin) / box,
+ children: shapes,
+ });
+ g.animate(
+ track("opacity", bakeSamples(opacity, 0, { tolerance: 0.004 })),
+ );
+ g.animate(track("scale", bakeSamples(scale, 0, { tolerance: 0.002 })));
+ if (props.autoOrient && glyph.directional) {
+ const angles = unwrap(
+ plan.angles.map((a) => (a * 180) / Math.PI + 135),
+ );
+ g.animate(
+ track("rotation", bakeSamples(angles, 0, { tolerance: 0.3 })),
+ );
+ }
+ if (props.shadow) {
+ host.style(g, {
+ dropShadow: {
+ color: "#000000",
+ opacity: 0.34,
+ angle: 90,
+ distance: Math.max(1, k * 1.2),
+ size: k * 4,
+ spread: 0,
+ },
+ });
+ }
+ glyphBoxes.push(g);
+ parts[`glyph-${style}`] = g;
+ }
+ const cursor = host.box({
+ id: ctx.partId("cursor"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: extent,
+ height: extent,
+ children: glyphBoxes,
+ });
+
+ // ── Label ────────────────────────────────────────────────────────
+ const motionChildren: LayoutNode[] = [cursor];
+ if (labelText !== undefined && labelMetrics) {
+ const bg =
+ (typeof props.label === "object" && props.label.color) || accent;
+ // White on a saturated tag reads as a name tag; fall back to dark
+ // ink only when white would be illegible.
+ const ink =
+ (contrastRatio("#ffffff", bg) ?? 0) >= 2.6 ? "#ffffff" : "#0b0c0e";
+ const label = host.box({
+ id: ctx.partId("label"),
+ position: "absolute",
+ x: half + labelX,
+ y: half + labelY,
+ width: labelW,
+ height: labelH,
+ background: bg,
+ borderRadius: labelH / 2,
+ children: [
+ host.text(labelText, {
+ id: ctx.partId("label-text"),
+ position: "absolute",
+ x: labelPadX,
+ y: Math.round((labelH - labelMetrics.lineHeight) / 2),
+ fontFamily: theme.font.body,
+ fontSize: labelFont,
+ fontWeight: 600,
+ fill: ink,
+ }),
+ ],
+ });
+ label.animate(
+ track(
+ "opacity",
+ bakeSamples(samples(plan.length, visibility), 0, {
+ tolerance: 0.004,
+ }),
+ ),
+ );
+ if (props.shadow) {
+ host.style(label, {
+ dropShadow: {
+ color: "#000000",
+ opacity: 0.28,
+ angle: 90,
+ distance: 2,
+ size: 8,
+ },
+ });
+ }
+ motionChildren.push(label);
+ parts.label = label;
+ }
+
+ const motion = host.box({
+ id: ctx.partId("motion"),
+ position: "absolute",
+ x: (plan.positions[0]?.[0] ?? 0) - half,
+ y: (plan.positions[0]?.[1] ?? 0) - half,
+ width: extent,
+ height: extent,
+ ...(props.motionBlur !== false && {
+ motionBlurShutter: props.motionBlur === true ? 45 : props.motionBlur,
+ }),
+ children: motionChildren,
+ });
+ motion.animate(
+ track(
+ "x",
+ bakeSamples(
+ plan.positions.map((p) => p[0] - half),
+ 0,
+ { tolerance: 0.2 },
+ ),
+ ),
+ track(
+ "y",
+ bakeSamples(
+ plan.positions.map((p) => p[1] - half),
+ 0,
+ { tolerance: 0.2 },
+ ),
+ ),
+ );
+
+ // ── Ripples and trail (they stay where they are drawn) ───────────
+ const below: LayoutNode[] = [];
+ if (props.ripple !== false) {
+ plan.cues.clicks.forEach((click, i) => {
+ below.push(
+ ...ripple(
+ ctx,
+ props.ripple as RippleKind,
+ click.point,
+ size,
+ accent,
+ click.frame,
+ i,
+ ),
+ );
+ });
+ }
+ if (props.trail !== false) {
+ const { length, spacing } = props.trail;
+ const color = props.trail.color ?? accent;
+ const dot = Math.max(3, size * 0.22);
+ for (let g = 1; g <= length; g++) {
+ const lag = g * spacing;
+ const at = (f: number): Vec2 =>
+ plan.positions[Math.max(0, f - lag)] ?? [0, 0];
+ const moving = (f: number) => {
+ const a = at(f);
+ const b = at(f - 1);
+ return Math.min(1, Math.hypot(a[0] - b[0], a[1] - b[1]) / 6);
+ };
+ const ghost = host.shape("circle", {
+ id: ctx.partId(`trail-${g}`),
+ position: "absolute",
+ x: (plan.positions[0]?.[0] ?? 0) - dot / 2,
+ y: (plan.positions[0]?.[1] ?? 0) - dot / 2,
+ width: dot,
+ height: dot,
+ fillColor: color,
+ });
+ ghost.animate(
+ track(
+ "x",
+ bakeSamples(
+ samples(plan.length, (f) => at(f)[0] - dot / 2),
+ 0,
+ { tolerance: 0.3 },
+ ),
+ ),
+ track(
+ "y",
+ bakeSamples(
+ samples(plan.length, (f) => at(f)[1] - dot / 2),
+ 0,
+ { tolerance: 0.3 },
+ ),
+ ),
+ track(
+ "opacity",
+ bakeSamples(
+ samples(
+ plan.length,
+ (f) => 0.5 * (1 - g / (length + 1)) * moving(f) * visibility(f),
+ ),
+ 0,
+ { tolerance: 0.01 },
+ ),
+ ),
+ track("scale", [[0, 1 - (0.5 * g) / (length + 1)]]),
+ );
+ below.push(ghost);
+ }
+ }
+
+ Object.assign(parts, { motion, cursor });
+
+ return {
+ children: [...below, motion],
+ width: W,
+ height: H,
+ duration: plan.length,
+ origin: [0, 0],
+ cues: plan.cues as MousePointerCues,
+ parts,
+ api: (placement): MousePointerApi => ({
+ positionAt(frame) {
+ const local = Math.max(
+ 0,
+ Math.min(plan.length - 1, Math.round(frame - placement.start)),
+ );
+ const p = plan.positions[local] ?? [0, 0];
+ return [p[0] + placement.x, p[1] + placement.y];
+ },
+ styleAt(frame) {
+ const local = Math.round(frame - placement.start);
+ return (
+ plan.styles.find((w) => local >= w.start && local <= w.end)
+ ?.style ?? props.style
+ );
+ },
+ }),
+ };
+ },
+});
+
+// ── Helpers ──────────────────────────────────────────────────────────
+
+type RippleKind = "ring" | "fill" | "pulse";
+
+const smooth = (t: number) => {
+ const x = Math.max(0, Math.min(1, t));
+ return x * x * (3 - 2 * x);
+};
+const backOut = (t: number, s = 1.7) =>
+ 1 + (s + 1) * (t - 1) ** 3 + s * (t - 1) ** 2;
+
+function samples(length: number, fn: (frame: number) => number): number[] {
+ return Array.from({ length }, (_, f) => fn(f));
+}
+
+function track(prop: AnimatableProp, keys: ReadonlyArray<KeyframeTuple>) {
+ return LayerAnimation.keys(prop, keys);
+}
+
+/** Make angle samples continuous so rotation never spins the long way round. */
+function unwrap(degrees: number[]): number[] {
+ const out: number[] = [];
+ for (const d of degrees) {
+ const prev = out[out.length - 1];
+ if (prev === undefined) {
+ out.push(d);
+ continue;
+ }
+ let x = d;
+ while (x - prev > 180) x -= 360;
+ while (x - prev < -180) x += 360;
+ out.push(x);
+ }
+ return out;
+}
+
+/** 1 while `style` shows, easing across `swap` frames at each change. */
+function styleWeight(
+ plan: PointerPlan,
+ style: CursorStyle,
+ frame: number,
+ swap: number,
+): number {
+ const win = plan.styles.find((w) => frame >= w.start && frame <= w.end);
+ if (!win) return 0;
+ if (win.style === style) {
+ const sinceStart = win.start === 0 ? swap : frame - win.start;
+ return smooth(Math.min(1, (sinceStart + 1) / (swap + 1)));
+ }
+ // The previous window's style lingers for `swap` frames.
+ const idx = plan.styles.indexOf(win);
+ const prev = plan.styles[idx - 1];
+ if (prev?.style === style && frame - win.start < swap) {
+ return 1 - smooth((frame - win.start + 1) / (swap + 1));
+ }
+ return 0;
+}
+
+/** Glyph scale over time from the press windows. */
+function pressProfile(
+ plan: PointerPlan,
+ feedback: "press" | "bounce" | "pulse" | false,
+): (f: number) => number {
+ if (feedback === false) return () => 1;
+ const low = feedback === "bounce" ? 0.76 : feedback === "pulse" ? 1.16 : 0.84;
+ return (f) => {
+ for (const w of plan.presses) {
+ if (f < w.down || f > w.released + 30) continue;
+ if (f <= w.pressed)
+ return (
+ 1 + (low - 1) * smooth((f - w.down) / Math.max(1, w.pressed - w.down))
+ );
+ if (f <= w.up) return low;
+ const t = (f - w.up) / Math.max(1, w.released - w.up);
+ if (feedback === "bounce") return 1 + (low - 1) * elasticDecay(t);
+ if (t >= 1) return 1;
+ return low + (1 - low) * backOut(t, 2.2);
+ }
+ return 1;
+ };
+}
+
+const elasticDecay = (t: number) =>
+ t >= 3 ? 0 : Math.exp(-3.2 * t) * Math.cos(t * Math.PI * 2.4);
+
+interface GlyphPaint {
+ k: number;
+ margin: number;
+ color: string;
+ accent: string;
+ outline: string | null;
+ outlineWidth: number;
+ mode: "union" | "each";
+}
+
+/** Outline layers (all first, so overlaps merge) then fills. */
+function glyphShapes(
+ ctx: Parameters<typeof mousePointer.build>[0],
+ glyph: Glyph,
+ style: string,
+ paint: GlyphPaint,
+): LayoutNode[] {
+ const { k, margin } = paint;
+ const geometry = {
+ position: "absolute" as const,
+ x: 0,
+ y: 0,
+ width: 24 * k + margin * 2,
+ height: 24 * k + margin * 2,
+ };
+ const outlines: LayoutNode[] = [];
+ const fills: LayoutNode[] = [];
+ glyph.parts.forEach((part, i) => {
+ const d = transformPathData(part.d, k, margin, margin);
+ const stroke = part.paint === "stroke" || part.paint === "accent-stroke";
+ const colorOf =
+ part.paint === "accent" || part.paint === "accent-stroke"
+ ? paint.accent
+ : paint.color;
+ const lineWidth = (part.width ?? 0) * k;
+ if (paint.outline) {
+ const o = ctx.host.shape("path", {
+ id: ctx.partId(`glyph-${style}-outline-${i}`),
+ ...geometry,
+ d,
+ fillType: stroke ? "none" : "solid",
+ fillColor: paint.outline,
+ strokeColor: paint.outline,
+ strokeWidth: lineWidth + paint.outlineWidth * 2,
+ strokeLineJoin: "round",
+ strokeLineCap: "round",
+ strokeAlign: "center",
+ });
+ (paint.mode === "union" ? outlines : fills).push(o);
+ }
+ fills.push(
+ ctx.host.shape("path", {
+ id: ctx.partId(`glyph-${style}-${i}`),
+ ...geometry,
+ d,
+ ...(stroke
+ ? {
+ fillType: "none" as const,
+ fillColor: colorOf,
+ strokeColor: colorOf,
+ strokeWidth: lineWidth,
+ strokeLineCap: "round" as const,
+ }
+ : { fillColor: colorOf }),
+ }),
+ );
+ });
+ return [...outlines, ...fills];
+}
+
+function ripple(
+ ctx: Parameters<typeof mousePointer.build>[0],
+ kind: RippleKind,
+ at: Vec2,
+ size: number,
+ accent: string,
+ frame: number,
+ index: number,
+): LayoutNode[] {
+ const radius = size * 0.95;
+ const life = Math.round((18 * ctx.fps) / 30);
+ const make = (delay: number, n: number) => {
+ const ring = ctx.host.shape("circle", {
+ id: ctx.partId(`ripple-${index}-${n}`),
+ position: "absolute",
+ x: at[0] - radius,
+ y: at[1] - radius,
+ width: radius * 2,
+ height: radius * 2,
+ startFrame: frame + delay,
+ durationFrames: life,
+ ...(kind === "fill"
+ ? { fillColor: accent }
+ : {
+ fillType: "none" as const,
+ fillColor: accent,
+ strokeColor: accent,
+ strokeWidth: Math.max(1.5, size / 16),
+ }),
+ });
+ ring.animate(
+ track("scale", [
+ [0, 0.2],
+ [life - 2, 1, "expo.out"],
+ ]),
+ track("opacity", [
+ [0, kind === "fill" ? 0.35 : 0.9],
+ [life - 1, 0, "sine.in"],
+ ]),
+ );
+ return ring;
+ };
+ return kind === "pulse"
+ ? [make(0, 0), make(Math.round((5 * ctx.fps) / 30), 1)]
+ : [make(0, 0)];
+}
diff --git a/packages/components/src/mouse-pointer/meta.ts b/packages/components/src/mouse-pointer/meta.ts
new file mode 100644
index 00000000..116e8030
--- /dev/null
+++ b/packages/components/src/mouse-pointer/meta.ts
@@ -0,0 +1,19 @@
+import { defineMeta } from "../core/meta.js";
+
+export default defineMeta({
+ name: "MousePointer",
+ summary:
+ "An animated pointer that travels between targets, clicks, drags and changes shape, reporting every click as a cue.",
+ tags: ["pointer", "cursor", "demo", "ui", "interaction", "screen recording"],
+ parts: [
+ "motion",
+ "cursor",
+ "glyph-<style>",
+ "label",
+ "trail-<n>",
+ "ripple-<n>-<m>",
+ ],
+ cues: ["arrivals", "presses", "releases", "clicks", "drags"],
+ example: `MousePointer({ path: [{ to: [400, 300] }, { to: [900, 520], click: true }] })`,
+ since: "M1",
+});
diff --git a/packages/components/src/mouse-pointer/plan.test.ts b/packages/components/src/mouse-pointer/plan.test.ts
new file mode 100644
index 00000000..91bf08c6
--- /dev/null
+++ b/packages/components/src/mouse-pointer/plan.test.ts
@@ -0,0 +1,148 @@
+import { describe, expect, it } from "vitest";
+import { type PlanInput, planPointer, travelFrames } from "./plan.js";
+
+const at = (x: number, y: number) => () => [x, y] as [number, number];
+
+function input(over: Partial<PlanInput> = {}): PlanInput {
+ return {
+ waypoints: [{ point: at(100, 100) }, { point: at(900, 500), clicks: 1 }],
+ fps: 30,
+ style: "arrow",
+ motion: "natural",
+ speed: 1,
+ drift: 0,
+ seed: 1,
+ hoverRegions: [],
+ appear: 7,
+ vanish: 7,
+ ...over,
+ };
+}
+
+describe("planPointer", () => {
+ it("travels by Fitts' law: longer moves take longer, never linearly", () => {
+ const short = travelFrames(100, 30, "natural", 1);
+ const long = travelFrames(1000, 30, "natural", 1);
+ expect(long).toBeGreaterThan(short);
+ expect(long).toBeLessThan(short * 3);
+ expect(travelFrames(500, 30, "natural", 2)).toBeLessThan(
+ travelFrames(500, 30, "natural", 1),
+ );
+ });
+
+ it("lands exactly on the target and clicks after settling", () => {
+ const plan = planPointer(input());
+ const arrival = plan.cues.arrivals[1]?.frame ?? -1;
+ expect(plan.positions[arrival]).toEqual([900, 500]);
+ const click = plan.cues.clicks[0];
+ expect(click?.frame).toBe(arrival + 4 + 3); // settle + press
+ expect(click?.point).toEqual([900, 500]);
+ // Still on the target the whole time the button is down.
+ const press = plan.presses[0];
+ for (let f = press?.down ?? 0; f <= (press?.released ?? 0); f++) {
+ expect(plan.positions[f]).toEqual([900, 500]);
+ }
+ });
+
+ it("bends travel off the straight line, and overshoots a hair on natural landings", () => {
+ // Largest distance from the straight line through (100,100) → (900,500).
+ const deviation = (positions: Array<[number, number]>) =>
+ Math.max(
+ ...positions.map(
+ ([x, y]) =>
+ Math.abs(400 * x - 800 * y + 40000) / Math.hypot(800, 400),
+ ),
+ );
+ const end = (p: ReturnType<typeof planPointer>) =>
+ p.cues.arrivals[1]?.frame ?? 0;
+ const natural = planPointer(input());
+ expect(
+ deviation(natural.positions.slice(0, end(natural) + 1)),
+ ).toBeGreaterThan(15);
+ const linear = planPointer(input({ motion: "linear" }));
+ expect(deviation(linear.positions.slice(0, end(linear) + 1))).toBeLessThan(
+ 0.01,
+ );
+ });
+
+ it("double clicks and drags", () => {
+ const plan = planPointer(
+ input({
+ waypoints: [
+ { point: at(0, 0), clicks: 2 },
+ { point: at(400, 0), drag: at(400, 300) },
+ ],
+ }),
+ );
+ expect(plan.cues.clicks).toHaveLength(2);
+ const [a, b] = plan.cues.clicks;
+ expect((b?.frame ?? 0) - (a?.frame ?? 0)).toBeGreaterThan(5);
+ expect(plan.cues.drags).toHaveLength(1);
+ const drag = plan.cues.drags[0];
+ expect(drag?.from).toEqual([400, 0]);
+ expect(drag?.to).toEqual([400, 300]);
+ expect(plan.positions[drag?.end ?? 0]).toEqual([400, 300]);
+ expect(plan.presses).toHaveLength(3);
+ });
+
+ it("honours explicit arrival frames and refuses impossible ones", () => {
+ const plan = planPointer(
+ input({
+ waypoints: [{ point: at(0, 0) }, { point: at(500, 0), at: 90 }],
+ }),
+ );
+ expect(plan.cues.arrivals[1]?.frame).toBe(90);
+ expect(() =>
+ planPointer(
+ input({
+ waypoints: [
+ { point: at(0, 0), dwell: 30 },
+ { point: at(500, 0), at: 10 },
+ ],
+ }),
+ ),
+ ).toThrow(/busy until/);
+ });
+
+ it("enters and leaves through edges without fading", () => {
+ const plan = planPointer(
+ input({ from: [-60, 500], to: [1980, 300], appear: 0, vanish: 0 }),
+ );
+ expect(plan.positions[0]).toEqual([-60, 500]);
+ expect(plan.positions[plan.length - 1]).toEqual([1980, 300]);
+ expect(plan.shown).toBe(0);
+ });
+
+ it("swaps styles inside hover regions and on waypoint cursors", () => {
+ const plan = planPointer(
+ input({
+ hoverRegions: [
+ { rect: { x: 850, y: 450, width: 100, height: 100 }, style: "hand" },
+ ],
+ }),
+ );
+ const arrival = plan.cues.arrivals[1]?.frame ?? 0;
+ const win = plan.styles.find((w) => arrival >= w.start && arrival <= w.end);
+ expect(win?.style).toBe("hand");
+ expect(plan.styles[0]?.style).toBe("arrow");
+ const switched = planPointer(
+ input({
+ waypoints: [
+ { point: at(0, 0) },
+ { point: at(300, 0), cursor: "ibeam" },
+ ],
+ }),
+ );
+ expect(switched.styles.at(-1)?.style).toBe("ibeam");
+ });
+
+ it("is deterministic per seed, and drift never moves a click", () => {
+ const a = planPointer(input({ drift: 2, seed: 4 }));
+ const b = planPointer(input({ drift: 2, seed: 4 }));
+ const c = planPointer(input({ drift: 2, seed: 5 }));
+ expect(a.positions).toEqual(b.positions);
+ expect(a.positions).not.toEqual(c.positions);
+ const click = a.cues.clicks[0];
+ expect(a.positions[click?.frame ?? 0]).toEqual([900, 500]);
+ });
+});
diff --git a/packages/components/src/mouse-pointer/plan.ts b/packages/components/src/mouse-pointer/plan.ts
new file mode 100644
index 00000000..e5b9b4df
--- /dev/null
+++ b/packages/components/src/mouse-pointer/plan.ts
@@ -0,0 +1,504 @@
+/**
+ * The pointer planner: waypoints in, a frame-by-frame performance out
+ * (position, press state, cursor style, cues). Pure and deterministic; the
+ * component turns the result into keyframes.
+ *
+ * Timing per waypoint: travel → arrive → (settle, press, release)×clicks or
+ * a press-drag-release → dwell → leave for the next one.
+ */
+import { evaluateEase } from "../core/ease.js";
+import { dist, type Vec2 } from "../core/path.js";
+import { hashRng } from "../core/rng.js";
+import type { CursorStyle } from "./glyphs.js";
+
+export type MotionFeel = "natural" | "swift" | "lazy" | "linear";
+
+/** A point that may move (tracked targets) — sampled per frame. */
+export type PointAt = (frame: number) => Vec2;
+
+export interface PlannedWaypoint {
+ point: PointAt;
+ /** Arrival frame; derived from distance when omitted. */
+ at?: number;
+ /** Frames to rest after the action. */
+ dwell?: number;
+ /** Clicks on arrival. */
+ clicks?: number;
+ /** Frames the button stays down per click. */
+ hold?: number;
+ /** Press here and drag to this point. */
+ drag?: PointAt;
+ /** Cursor style from this waypoint on. */
+ cursor?: CursorStyle;
+ /** Id of the target, reported on click cues. */
+ targetId?: string;
+}
+
+export interface HoverRegion {
+ rect: { x: number; y: number; width: number; height: number };
+ style: CursorStyle;
+}
+
+export interface PlanInput {
+ waypoints: PlannedWaypoint[];
+ fps: number;
+ style: CursorStyle;
+ motion: MotionFeel;
+ /** Travel-time multiplier: 2 = twice as fast. */
+ speed: number;
+ /** Idle drift amplitude in px (0 = still). */
+ drift: number;
+ seed: number;
+ /** Start off-frame here and travel to the first waypoint. */
+ from?: Vec2;
+ /** End by travelling here (off-frame) after the last waypoint. */
+ to?: Vec2;
+ hoverRegions: HoverRegion[];
+ /** Frames the pointer takes to appear / vanish (0 = instant). */
+ appear: number;
+ vanish: number;
+}
+
+export interface PressWindow {
+ /** Button starts going down. */
+ down: number;
+ /** Fully pressed: the click lands. */
+ pressed: number;
+ /** Button starts coming up. */
+ up: number;
+ /** Fully released. */
+ released: number;
+}
+
+export interface StyleWindow {
+ style: CursorStyle;
+ start: number;
+ end: number;
+}
+
+export interface PointerPlan {
+ /** Frames planned: positions has one entry per frame in [0, length). */
+ length: number;
+ positions: Vec2[];
+ /** Travel direction per frame (radians), held while still. */
+ angles: number[];
+ presses: PressWindow[];
+ styles: StyleWindow[];
+ /** When the pointer is fully visible, and when it starts vanishing. */
+ shown: number;
+ vanishAt: number;
+ cues: {
+ arrivals: Array<{ frame: number; point: Vec2; index: number }>;
+ presses: Array<{ frame: number; point: Vec2 }>;
+ releases: Array<{ frame: number; point: Vec2 }>;
+ clicks: Array<{
+ frame: number;
+ point: Vec2;
+ index: number;
+ target?: string;
+ }>;
+ drags: Array<{ frame: number; end: number; from: Vec2; to: Vec2 }>;
+ };
+}
+
+// Press timing (frames at 30 fps; scaled by fps).
+const SETTLE = 4;
+const PRESS = 3;
+const HOLD = 2;
+const RELEASE = 5;
+const CLICK_GAP = 3;
+const DWELL = 14;
+
+/** Travel time for a distance, from Fitts' law: quick hops, long sweeps that still feel human. */
+export function travelFrames(
+ distance: number,
+ fps: number,
+ feel: MotionFeel,
+ speed: number,
+): number {
+ const seconds = 0.2 + 0.13 * Math.log2(1 + distance / 24);
+ const scale = feel === "lazy" ? 1.4 : feel === "swift" ? 0.8 : 1;
+ return Math.max(
+ 4,
+ Math.round((seconds * scale * fps) / Math.max(0.05, speed)),
+ );
+}
+
+/** Progress along the curve for t ∈ [0, 1]: quick start, long soft landing. */
+function progress(feel: MotionFeel, t: number): number {
+ switch (feel) {
+ case "linear":
+ return t;
+ case "lazy":
+ return evaluateEase("sine.inOut", t);
+ case "swift":
+ return minimumJerk(t);
+ case "natural":
+ // Skewed minimum-jerk: peak speed early, like a real hand.
+ return minimumJerk(t ** 0.78);
+ }
+}
+
+const minimumJerk = (t: number) => t * t * t * (10 - 15 * t + 6 * t * t);
+
+/** Quadratic Bézier point. */
+function quad(a: Vec2, c: Vec2, b: Vec2, u: number): Vec2 {
+ const v = 1 - u;
+ return [
+ v * v * a[0] + 2 * v * u * c[0] + u * u * b[0],
+ v * v * a[1] + 2 * v * u * c[1] + u * u * b[1],
+ ];
+}
+
+export function planPointer(input: PlanInput): PointerPlan {
+ const { fps, seed } = input;
+ const f = (framesAt30: number) =>
+ Math.max(1, Math.round((framesAt30 * fps) / 30));
+ if (input.waypoints.length === 0)
+ throw new Error("MousePointer: `path` needs at least one waypoint.");
+
+ type Segment =
+ | {
+ kind: "travel";
+ start: number;
+ end: number;
+ from: PointAt;
+ to: PointAt;
+ index: number;
+ pressed: boolean;
+ }
+ | {
+ kind: "rest";
+ start: number;
+ end: number;
+ at: PointAt;
+ pressed: boolean;
+ };
+ const segments: Segment[] = [];
+ const presses: PressWindow[] = [];
+ const cues: PointerPlan["cues"] = {
+ arrivals: [],
+ presses: [],
+ releases: [],
+ clicks: [],
+ drags: [],
+ };
+ const styleChanges: Array<{ frame: number; style: CursorStyle }> = [
+ { frame: 0, style: input.style },
+ ];
+
+ let cursor = 0; // the next free frame
+ let here: PointAt = input.from
+ ? constant(input.from)
+ : (input.waypoints[0]?.point ?? constant([0, 0]));
+ const appear = Math.max(0, input.appear);
+
+ input.waypoints.forEach((wp, index) => {
+ const isFirst = index === 0;
+ const needsTravel = !(isFirst && !input.from);
+ let arrival: number;
+ if (needsTravel) {
+ const from = here;
+ const startFrame = cursor;
+ const d = dist(from(startFrame), wp.point(startFrame));
+ const natural =
+ startFrame + travelFrames(d, fps, input.motion, input.speed);
+ arrival = wp.at ?? natural;
+ if (arrival < startFrame + 2) {
+ throw new Error(
+ `MousePointer: waypoint ${index} arrives at frame ${arrival}, but the pointer is busy until ${startFrame}. Leave at least 2 frames to travel.`,
+ );
+ }
+ segments.push({
+ kind: "travel",
+ start: startFrame,
+ end: arrival,
+ from,
+ to: wp.point,
+ index,
+ pressed: false,
+ });
+ } else {
+ arrival = wp.at ?? 0;
+ if (arrival > 0)
+ segments.push({
+ kind: "rest",
+ start: 0,
+ end: arrival,
+ at: wp.point,
+ pressed: false,
+ });
+ }
+ here = wp.point;
+ cues.arrivals.push({ frame: arrival, point: wp.point(arrival), index });
+ if (wp.cursor) styleChanges.push({ frame: arrival, style: wp.cursor });
+
+ let t = Math.max(arrival, isFirst ? appear : arrival);
+ if (t > arrival)
+ segments.push({
+ kind: "rest",
+ start: arrival,
+ end: t,
+ at: wp.point,
+ pressed: false,
+ });
+
+ const press = (at: number, hold: number, click: boolean): PressWindow => {
+ const w = {
+ down: at,
+ pressed: at + f(PRESS),
+ up: at + f(PRESS) + hold,
+ released: at + f(PRESS) + hold + f(RELEASE),
+ };
+ presses.push(w);
+ cues.presses.push({ frame: w.down, point: here(w.down) });
+ cues.releases.push({ frame: w.up, point: here(w.up) });
+ if (click)
+ cues.clicks.push({
+ frame: w.pressed,
+ point: here(w.pressed),
+ index,
+ target: wp.targetId,
+ });
+ return w;
+ };
+
+ if (wp.drag) {
+ const settle = t + f(SETTLE);
+ segments.push({
+ kind: "rest",
+ start: t,
+ end: settle,
+ at: wp.point,
+ pressed: false,
+ });
+ const down = settle;
+ const pressedAt = down + f(PRESS);
+ segments.push({
+ kind: "rest",
+ start: down,
+ end: pressedAt,
+ at: wp.point,
+ pressed: true,
+ });
+ const from = wp.point;
+ const to = wp.drag;
+ const d = dist(from(pressedAt), to(pressedAt));
+ const dragEnd =
+ pressedAt +
+ Math.round(travelFrames(d, fps, input.motion, input.speed) * 1.25);
+ segments.push({
+ kind: "travel",
+ start: pressedAt,
+ end: dragEnd,
+ from,
+ to,
+ index,
+ pressed: true,
+ });
+ here = to;
+ const up = dragEnd + f(SETTLE);
+ segments.push({
+ kind: "rest",
+ start: dragEnd,
+ end: up,
+ at: to,
+ pressed: true,
+ });
+ presses.push({ down, pressed: pressedAt, up, released: up + f(RELEASE) });
+ cues.presses.push({ frame: down, point: from(down) });
+ cues.drags.push({
+ frame: pressedAt,
+ end: dragEnd,
+ from: from(pressedAt),
+ to: to(dragEnd),
+ });
+ cues.releases.push({ frame: up, point: to(up) });
+ t = up + f(RELEASE);
+ segments.push({
+ kind: "rest",
+ start: up,
+ end: t,
+ at: to,
+ pressed: false,
+ });
+ } else if (wp.clicks && wp.clicks > 0) {
+ t += f(SETTLE);
+ for (let c = 0; c < wp.clicks; c++) {
+ const w = press(t, wp.hold ?? f(HOLD), true);
+ t = w.released + (c < wp.clicks - 1 ? f(CLICK_GAP) : 0);
+ }
+ // Pressed: no idle drift may nudge the pointer mid-click.
+ segments.push({
+ kind: "rest",
+ start: arrival,
+ end: t,
+ at: wp.point,
+ pressed: true,
+ });
+ }
+
+ const dwellEnd = t + (wp.dwell ?? f(DWELL));
+ segments.push({
+ kind: "rest",
+ start: t,
+ end: dwellEnd,
+ at: here,
+ pressed: false,
+ });
+ cursor = dwellEnd;
+ });
+
+ if (input.to) {
+ const from = here;
+ const exitPoint = constant(input.to);
+ const d = dist(from(cursor), input.to);
+ const end = cursor + travelFrames(d, fps, input.motion, input.speed);
+ segments.push({
+ kind: "travel",
+ start: cursor,
+ end,
+ from,
+ to: exitPoint,
+ index: input.waypoints.length,
+ pressed: false,
+ });
+ cursor = end;
+ }
+ const vanishAt = cursor;
+ const length = cursor + (input.to ? 0 : Math.max(0, input.vanish)) + 1;
+
+ // Curve shape per travel segment: a seeded sideways bend, the way a hand
+ // arcs instead of drawing rulers.
+ const bendOf = (index: number) => {
+ if (input.motion === "linear") return 0;
+ const r = hashRng(seed, `bend:${index}`);
+ const amount =
+ input.motion === "lazy"
+ ? r.range(0.1, 0.18)
+ : input.motion === "swift"
+ ? r.range(0.03, 0.07)
+ : r.range(0.05, 0.11);
+ return r.next() < 0.5 ? -amount : amount;
+ };
+
+ const positions: Vec2[] = [];
+ const angles: number[] = [];
+ const driftRng = hashRng(seed, "drift");
+ const [ph0, ph1, ph2, ph3] = [0, 1, 2, 3].map(() =>
+ driftRng.range(0, Math.PI * 2),
+ ) as [number, number, number, number];
+ let lastAngle = -Math.PI / 4;
+
+ for (let frame = 0; frame < length; frame++) {
+ const seg = findSegment(segments, frame);
+ let p: Vec2;
+ let moving = false;
+ if (!seg) {
+ p = here(frame);
+ } else if (seg.kind === "travel") {
+ const t =
+ seg.end > seg.start ? (frame - seg.start) / (seg.end - seg.start) : 1;
+ const a = seg.from(seg.start);
+ const b = seg.to(frame);
+ const len = dist(a, b);
+ const bend = bendOf(seg.index) * len;
+ const mid: Vec2 = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
+ const nx = len > 0 ? -(b[1] - a[1]) / len : 0;
+ const ny = len > 0 ? (b[0] - a[0]) / len : 0;
+ const control: Vec2 = [mid[0] + nx * bend, mid[1] + ny * bend];
+ const u = progress(input.motion, Math.min(1, Math.max(0, t)));
+ p = quad(a, control, b, u);
+ // A natural landing overshoots a hair past the target and settles.
+ if (input.motion === "natural" && len > 60) {
+ const over = Math.min(6, len * 0.012);
+ const k = Math.max(0, (t - 0.62) / 0.38);
+ const bump = Math.sin(Math.PI * Math.min(1, k));
+ p = [
+ p[0] + ((b[0] - a[0]) / len) * over * bump,
+ p[1] + ((b[1] - a[1]) / len) * over * bump,
+ ];
+ }
+ moving = t > 0 && t < 1;
+ } else {
+ p = seg.at(frame);
+ // Idle drift while resting, never while the button is down.
+ if (!seg.pressed && input.drift > 0) {
+ const ramp = Math.min(
+ 1,
+ (frame - seg.start) / 8,
+ (seg.end - frame) / 8,
+ );
+ if (ramp > 0) {
+ const s = frame / fps;
+ const dx =
+ Math.sin(s * 1.7 + ph0) * 0.6 + Math.sin(s * 0.9 + ph1) * 0.4;
+ const dy =
+ Math.sin(s * 1.3 + ph2) * 0.6 + Math.sin(s * 0.7 + ph3) * 0.4;
+ p = [p[0] + dx * input.drift * ramp, p[1] + dy * input.drift * ramp];
+ }
+ }
+ }
+ const prev = positions[frame - 1];
+ if (moving && prev && dist(prev, p) > 0.5)
+ lastAngle = Math.atan2(p[1] - prev[1], p[0] - prev[0]);
+ positions.push(p);
+ angles.push(lastAngle);
+ }
+
+ return {
+ length,
+ positions,
+ angles,
+ presses,
+ styles: styleWindows(positions, styleChanges, input.hoverRegions),
+ shown: appear,
+ vanishAt,
+ cues,
+ };
+}
+
+function constant(p: Vec2): PointAt {
+ return () => p;
+}
+
+function findSegment<T extends { start: number; end: number }>(
+ segments: T[],
+ frame: number,
+): T | undefined {
+ // Later segments win on shared frames (a rest that starts where travel ends).
+ let found: T | undefined;
+ for (const s of segments) if (frame >= s.start && frame <= s.end) found = s;
+ return found;
+}
+
+/** Style per frame (base style changes + hover regions), as windows. */
+function styleWindows(
+ positions: Vec2[],
+ changes: Array<{ frame: number; style: CursorStyle }>,
+ regions: HoverRegion[],
+): StyleWindow[] {
+ const sorted = [...changes].sort((a, b) => a.frame - b.frame);
+ const windows: StyleWindow[] = [];
+ let base = sorted[0]?.style ?? "arrow";
+ let next = 1;
+ for (let frame = 0; frame < positions.length; frame++) {
+ while (next < sorted.length && (sorted[next]?.frame ?? Infinity) <= frame) {
+ base = sorted[next]?.style ?? base;
+ next++;
+ }
+ const p = positions[frame] as Vec2;
+ const region = regions.find(
+ (r) =>
+ p[0] >= r.rect.x &&
+ p[0] <= r.rect.x + r.rect.width &&
+ p[1] >= r.rect.y &&
+ p[1] <= r.rect.y + r.rect.height,
+ );
+ const style = region?.style ?? base;
+ const last = windows[windows.length - 1];
+ if (last && last.style === style) last.end = frame;
+ else windows.push({ style, start: frame, end: frame });
+ }
+ return windows;
+}
diff --git a/packages/components/src/test/fake-host.ts b/packages/components/src/test/fake-host.ts
index d2435e94..d3b713a0 100644
--- a/packages/components/src/test/fake-host.ts
+++ b/packages/components/src/test/fake-host.ts
@@ -106,6 +106,19 @@ export function fakeHost(): Host & { created: LayoutNode[] } {
}) as never,
measure: fakeMeasure,
fonts: () => ["Inter", "JetBrains Mono"],
+ media: (source, o) =>
+ make({ kind: "media", id: o.id ?? "media", source, ...o }) as never,
+ style: (node, config) => {
+ (node as unknown as { styles?: unknown[] }).styles = [
+ ...((node as unknown as { styles?: unknown[] }).styles ?? []),
+ config,
+ ];
+ return node;
+ },
+ matte: (node, matte) => {
+ (node as unknown as { matte?: unknown }).matte = { node: matte };
+ return node;
+ },
autoId: (prefix) => {
const n = (counters.get(prefix) ?? 0) + 1;
counters.set(prefix, n);
diff --git a/packages/components/src/test/probe.ts b/packages/components/src/test/probe.ts
index 595ee0c8..9d9acd4c 100644
--- a/packages/components/src/test/probe.ts
+++ b/packages/components/src/test/probe.ts
@@ -7,11 +7,11 @@ import { defineComponent } from "../core/contract.js";
export const probe = defineComponent({
name: "Probe",
- props: {
+ props: () => ({
label: z.string().default("probe"),
ticks: z.array(z.number().int().min(0)).default([]),
size: z.number().positive().default(100),
- },
+ }),
defaults: { enter: "rise", hold: 5 },
build(ctx, props) {
const plate = ctx.host.box({
diff --git a/packages/components/src/text-reveal/index.test.ts b/packages/components/src/text-reveal/index.test.ts
new file mode 100644
index 00000000..41083d37
--- /dev/null
+++ b/packages/components/src/text-reveal/index.test.ts
@@ -0,0 +1,161 @@
+import type { LayoutNode } from "@framefields/compositions/program";
+import { describe, expect, it } from "vitest";
+import { bind } from "../core/contract.js";
+import { evaluateGlyphExpression, type GlyphAnimator } from "../core/glyphs.js";
+import { fakeHost } from "../test/fake-host.js";
+import { textReveal } from "./index.js";
+
+const make = () => bind(fakeHost(), textReveal);
+
+type Node = LayoutNode & {
+ animators?: GlyphAnimator[];
+ animation?: {
+ tracks: Array<{
+ prop: string;
+ keyframes: Array<{
+ frame: number;
+ value: unknown;
+ ease?: { name: string };
+ }>;
+ }>;
+ };
+ children?: Node[];
+};
+const find = (root: unknown, id: string): Node | undefined => {
+ const n = root as Node;
+ if (n.id === id) return n;
+ for (const c of n.children ?? []) {
+ const hit = find(c, id);
+ if (hit) return hit;
+ }
+ return undefined;
+};
+/** A track as `[frame, value, ease?]` tuples. */
+const track = (n: Node | undefined, prop: string) =>
+ (n?.animation?.tracks.find((t) => t.prop === prop)?.keyframes ?? []).map(
+ (k) => (k.ease ? [k.frame, k.value, k.ease.name] : [k.frame, k.value]),
+ );
+const weight = (a: GlyphAnimator, frame: number, i: number) =>
+ evaluateGlyphExpression(a.selectors[0]?.expression ?? "0", {
+ frame,
+ textIndex: i,
+ wordIndex: i,
+ lineIndex: i,
+ });
+
+describe("TextReveal", () => {
+ it("rises word by word and rests exactly on the static text", () => {
+ const t = make()({ id: "t", text: "Ship it faster", fontSize: 40 });
+ expect(t.cues.units.map((u) => u.text)).toEqual(["Ship", "it", "faster"]);
+ const revealed = t.cues.revealed[0]?.frame ?? 0;
+ expect(revealed).toBe(Math.max(...t.cues.units.map((u) => u.settled)));
+ const enter = find(t, "t-text")?.animators?.find((a) => a.name === "enter");
+ expect(enter?.props).toMatchObject({ opacity: 0 });
+ // Every unit fully pushed at frame 0, at rest once revealed.
+ for (const i of [0, 1, 2]) {
+ expect(weight(enter as GlyphAnimator, 0, i)).toBe(1);
+ expect(weight(enter as GlyphAnimator, revealed, i)).toBe(0);
+ }
+ });
+
+ it("stays on screen unless an exit is asked for", () => {
+ const still = make()({ text: "Hello" });
+ expect(still.span.end).toBe(Number.POSITIVE_INFINITY);
+ const faded = make()({ text: "Hello", exit: "fade", hold: 10 });
+ expect(faded.span.end).toBeLessThan(Number.POSITIVE_INFINITY);
+ });
+
+ it("plays its own exit after the hold", () => {
+ const t = make()({ id: "t", text: "one two", exitStyle: "rise", hold: 20 });
+ const revealed = t.cues.revealed[0]?.frame ?? 0;
+ const exitStart = t.cues.exitStart[0]?.frame ?? 0;
+ expect(exitStart).toBe(revealed + 20);
+ const exit = find(t, "t-text")?.animators?.find((a) => a.name === "exit");
+ expect(exit?.props.y).toBeLessThan(0);
+ expect(weight(exit as GlyphAnimator, exitStart, 0)).toBe(0);
+ expect(weight(exit as GlyphAnimator, t.span.duration, 1)).toBe(1);
+ expect(t.span.duration).toBeGreaterThan(exitStart);
+ });
+
+ it("types with key cues, a caret, and count keys", () => {
+ const t = make()({ id: "t", text: "ab c", style: "type" });
+ expect(t.cues.keystrokes).toHaveLength(3);
+ const keys = track(find(t, "t-text"), "text");
+ expect(keys[keys.length - 1]?.[1]).toBe(4);
+ // One character is a fraction (1 would mean "all of it").
+ expect(keys.map((k) => k[1])).toContain(0.25);
+ expect(keys.map((k) => k[1])).not.toContain(1);
+ expect(find(t, "t-caret")).toBeDefined();
+ });
+
+ it("masks line by line, and only a split text can exit by mask", () => {
+ const t = make()({
+ id: "t",
+ text: "aaaa bbbb cccc",
+ style: "mask",
+ width: 100,
+ fontSize: 20,
+ });
+ expect(t.cues.units).toHaveLength(2);
+ expect(find(t, "t-line-0")).toBeDefined();
+ expect(find(t, "t-line-1")).toBeDefined();
+ expect(() =>
+ make()({ text: "x", style: "rise", exitStyle: "mask" }),
+ ).toThrow(/needs style "mask"/);
+ });
+
+ it("scrambles deterministically and hands over to the real text", () => {
+ const a = make()({ id: "t", text: "CODE", style: "scramble", seed: 7 });
+ const b = make()({ id: "t", text: "CODE", style: "scramble", seed: 7 });
+ const c = make()({ id: "t", text: "CODE", style: "scramble", seed: 8 });
+ const reel = (n: unknown) =>
+ (find(n, "t-reel-0") as { text?: string })?.text;
+ expect(reel(a)).toBe(reel(b));
+ expect(reel(a)).not.toBe(reel(c));
+ expect(reel(a)?.endsWith("C")).toBe(true);
+ const done = a.cues.revealed[0]?.frame ?? 0;
+ expect(track(find(a, "t-text"), "opacity")).toEqual([
+ [0, 0],
+ [done, 1, "hold"],
+ ]);
+ });
+
+ it("slams words as their own nodes, then shows the paragraph", () => {
+ const t = make()({ id: "t", text: "big bold words", style: "slam" });
+ expect(find(t, "t-unit-2")).toBeDefined();
+ const landed = Math.max(...t.cues.units.map((u) => u.settled));
+ // At rest once the landing shake has died out.
+ expect(t.cues.revealed[0]?.frame).toBeGreaterThan(landed);
+ expect(track(find(t, "t-text"), "opacity")).toContainEqual([
+ landed,
+ 1,
+ "hold",
+ ]);
+ });
+
+ it("colours emphasis and exposes rects in parent coordinates", () => {
+ const t = make()({
+ id: "t",
+ text: "go faster now",
+ emphasis: ["faster"],
+ x: 100,
+ y: 50,
+ fontSize: 20,
+ });
+ const em = find(t, "t-text")?.animators?.[0];
+ expect(em?.name).toBe("emphasis");
+ expect(weight(em as GlyphAnimator, 0, 3)).toBe(1);
+ expect(weight(em as GlyphAnimator, 0, 0)).toBe(0);
+ // 10 px per glyph in the fake measure: "faster" starts at index 3.
+ expect(t.rects("faster")[0]).toMatchObject({ x: 130, y: 50, width: 60 });
+ });
+
+ it("fails loudly on unknown fonts and props", () => {
+ expect(() => make()({ text: "x", fontFamily: "Nope" })).toThrow(
+ /not registered. Registered: Inter/,
+ );
+ expect(() => make()({ text: "x", styel: "rise" } as never)).toThrow(
+ /invalid props/,
+ );
+ });
+});
diff --git a/packages/components/src/text-reveal/index.ts b/packages/components/src/text-reveal/index.ts
new file mode 100644
index 00000000..58c2d6b3
--- /dev/null
+++ b/packages/components/src/text-reveal/index.ts
@@ -0,0 +1,1126 @@
+/**
+ * TextReveal: headlines and body copy that animate in (and out) by
+ * character, word or line. One timing model, many looks. Glyph styles run on
+ * the GPU through baked per-unit schedules, so a paragraph stays one text
+ * node and its final frame is exactly the static text.
+ */
+import {
+ type AnimatableProp,
+ type KeyframeTuple,
+ LayerAnimation,
+ type LayoutNode,
+ type TextNode,
+} from "@framefields/compositions/program";
+import { z } from "zod";
+import { bakeSamples } from "../core/bake.js";
+import { defineComponent } from "../core/contract.js";
+import type { Rect } from "../core/draw.js";
+import { evaluateEase } from "../core/ease.js";
+import {
+ constantExpression,
+ type GlyphAnimator,
+ type GlyphProps,
+ type GlyphUnit,
+ glyphAnimator,
+ scheduleExpression,
+ type UnitSchedule,
+} from "../core/glyphs.js";
+import type { Animatable } from "../core/host.js";
+import {
+ findRange,
+ lineShift,
+ type MeasureOptions,
+ type Metrics,
+ rangeRects,
+} from "../core/text.js";
+import { type Theme, themeFrames } from "../core/theme.js";
+import { scaleFrames } from "../core/timing.js";
+import {
+ burstStarts,
+ indexedStarts,
+ scrambleSet,
+ typingFrames,
+ unitStarts,
+ unitsOf,
+} from "./plan.js";
+
+export const REVEAL_STYLES = [
+ "rise",
+ "blur",
+ "track",
+ "mask",
+ "slam",
+ "scatter",
+ "scramble",
+ "type",
+ "stream",
+ "wipe",
+ "flip",
+] as const;
+export type RevealStyle = (typeof REVEAL_STYLES)[number];
+
+/** Styles that can also play out (`exitStyle`). */
+export const EXIT_STYLES = [
+ "rise",
+ "blur",
+ "track",
+ "mask",
+ "scatter",
+ "type",
+ "stream",
+ "wipe",
+ "flip",
+] as const;
+export type ExitStyle = (typeof EXIT_STYLES)[number];
+
+const ORDERS = ["forward", "reverse", "center", "edges", "random"] as const;
+
+interface StyleDefaults {
+ by: GlyphUnit;
+ /** Frames between units at 30 fps. */
+ stagger: number;
+ speed: keyof Theme["motion"]["speed"];
+ /** Multiplier on the speed token. */
+ length: number;
+ ease: string;
+}
+
+const STYLE: Record<RevealStyle, StyleDefaults> = {
+ rise: {
+ by: "word",
+ stagger: 3,
+ speed: "base",
+ length: 1.4,
+ ease: "expo.out",
+ },
+ blur: {
+ by: "char",
+ stagger: 1.2,
+ speed: "slow",
+ length: 1,
+ ease: "power3.out",
+ },
+ track: {
+ by: "line",
+ stagger: 0,
+ speed: "slow",
+ length: 1.5,
+ ease: "expo.out",
+ },
+ mask: {
+ by: "line",
+ stagger: 5,
+ speed: "base",
+ length: 1.5,
+ ease: "expo.out",
+ },
+ slam: { by: "word", stagger: 7, speed: "fast", length: 1, ease: "power3.in" },
+ scatter: {
+ by: "char",
+ stagger: 0.8,
+ speed: "slow",
+ length: 1.2,
+ ease: "expo.out",
+ },
+ scramble: {
+ by: "char",
+ stagger: 1.5,
+ speed: "base",
+ length: 1,
+ ease: "none",
+ },
+ type: { by: "char", stagger: 0, speed: "fast", length: 1, ease: "none" },
+ stream: {
+ by: "word",
+ stagger: 6,
+ speed: "slow",
+ length: 1,
+ ease: "power2.out",
+ },
+ wipe: {
+ by: "line",
+ stagger: 0,
+ speed: "slow",
+ length: 1.4,
+ ease: "power2.inOut",
+ },
+ flip: {
+ by: "char",
+ stagger: 1.5,
+ speed: "base",
+ length: 1.2,
+ ease: "back.out(1.4)",
+ },
+};
+
+/** What each glyph style pushes at full weight (font-size units, degrees). */
+function glyphFrom(style: RevealStyle, fs: number, exit: boolean): GlyphProps {
+ switch (style) {
+ case "rise":
+ return { y: (exit ? -0.32 : 0.42) * fs, opacity: 0 };
+ case "blur":
+ return { blur: 0.16 * fs, scale: 1.18, opacity: 0 };
+ case "flip":
+ return { rotationX: exit ? -90 : 90, opacity: 0 };
+ default:
+ return { opacity: 0 };
+ }
+}
+
+export interface TextRevealCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ /** Per unit: starts moving (`frame`) and comes to rest (`settled`). */
+ units: ReadonlyArray<{
+ frame: number;
+ settled: number;
+ index: number;
+ text: string;
+ }>;
+ /** The whole text is at rest. */
+ revealed: ReadonlyArray<{ frame: number }>;
+ /** The exit starts (empty without `exitStyle`). */
+ exitStart: ReadonlyArray<{ frame: number }>;
+ /** Each typed character (`type`) or arriving word (`stream`): for key sounds. */
+ keystrokes: ReadonlyArray<{ frame: number; index: number }>;
+}
+
+export interface TextRevealApi {
+ /**
+ * Rects (parent coordinates) that a match covers, one per line: hand
+ * them to `Annotate` or a camera. Without `match`, the whole text.
+ */
+ rects(match?: string | RegExp, nth?: number): Rect[];
+}
+
+type TextProps = Partial<
+ Pick<
+ TextNode,
+ | "fontFamily"
+ | "fontSize"
+ | "fontWeight"
+ | "fill"
+ | "align"
+ | "lineHeight"
+ | "letterSpacing"
+ | "direction"
+ | "width"
+ >
+>;
+
+const ALIGN = { start: "left", center: "center", end: "right" } as const;
+
+export const textReveal = /* @__PURE__ */ defineComponent({
+ name: "TextReveal",
+ props: () => ({
+ text: z.string().min(1),
+ style: z.enum(REVEAL_STYLES).default("rise"),
+ /** Unit of animation. Default per style. */
+ by: z.enum(["char", "word", "line"]).optional(),
+ /** Frames between units. Default per style. */
+ stagger: z.number().min(0).optional(),
+ order: z.enum(ORDERS).default("forward"),
+ /** Frames one unit's move takes. Default per style, from the theme. */
+ unitDuration: z.number().int().positive().optional(),
+ ease: z.string().optional(),
+ /** Play out after `hold`, unit by unit. */
+ exitStyle: z.union([z.enum(EXIT_STYLES), z.literal(false)]).default(false),
+ /** Typing speed for `type`, characters a second. */
+ cps: z.number().positive().default(24),
+ /** Caret for `type` and `stream`. */
+ caret: z.boolean().default(true),
+ /** Words or patterns drawn in the theme's accent. */
+ emphasis: z.array(z.union([z.string(), z.instanceof(RegExp)])).default([]),
+ accent: z.string().optional(),
+ fontFamily: z.string().optional(),
+ fontSize: z.number().positive().optional(),
+ fontWeight: z.union([z.number(), z.string()]).optional(),
+ fill: z.string().optional(),
+ align: z.enum(["start", "center", "end"]).default("start"),
+ lineHeight: z.number().positive().optional(),
+ letterSpacing: z.number().optional(),
+ direction: z.enum(["ltr", "rtl", "auto"]).optional(),
+ }),
+ defaults: { enter: false, exit: false, hold: 30 },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const text = props.text;
+ const fs = props.fontSize ?? 96 * theme.scale;
+ const fontFamily = props.fontFamily ?? theme.font.display;
+ const registered = host.fonts();
+ if (registered.length > 0 && !registered.includes(fontFamily)) {
+ throw new Error(
+ `TextReveal: font "${fontFamily}" is not registered. Registered: ${registered.join(", ")}.`,
+ );
+ }
+ const wrap = ctx.requested.width;
+ const textProps: TextProps = {
+ fontFamily,
+ fontSize: fs,
+ fill: props.fill ?? theme.color.ink,
+ align: props.align,
+ ...(props.fontWeight !== undefined && { fontWeight: props.fontWeight }),
+ ...(props.lineHeight !== undefined && { lineHeight: props.lineHeight }),
+ ...(props.letterSpacing !== undefined && {
+ letterSpacing: props.letterSpacing,
+ }),
+ ...(props.direction !== undefined && { direction: props.direction }),
+ ...(wrap !== undefined && { width: wrap }),
+ };
+ const measureOptions: MeasureOptions = {
+ fontFamily,
+ fontSize: fs,
+ fontWeight: props.fontWeight,
+ letterSpacing: props.letterSpacing,
+ lineHeight: props.lineHeight,
+ width: wrap,
+ align: ALIGN[props.align],
+ direction: props.direction,
+ };
+ const m = host.measure(text, measureOptions);
+ const W = wrap ?? m.width;
+ const H = m.height;
+
+ const style = STYLE[props.style];
+ const by: GlyphUnit = props.by ?? style.by;
+ // Stagger stays fractional: units may start between frames.
+ const perFps = (v: number) => (v * fps) / 30;
+ const stagger = perFps(props.stagger ?? style.stagger);
+ const duration =
+ props.unitDuration ??
+ Math.max(
+ 1,
+ Math.round(themeFrames(theme, style.speed, fps) * style.length),
+ );
+ const ease = props.ease ?? style.ease;
+
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+ const children: LayoutNode[] = [];
+ const animators: GlyphAnimator[] = [];
+ const keystrokes: Array<{ frame: number; index: number }> = [];
+ let unitCues: TextRevealCues["units"] = [];
+ let revealed = 0;
+
+ // Emphasis is static colour, first in the stack so streaming ink mixes over it.
+ const emphasised = emphasisWeights(text, props.emphasis);
+ if (emphasised) {
+ animators.push(
+ glyphAnimator("emphasis", constantExpression("char", emphasised), {
+ fillColor: props.accent ?? theme.color.accent,
+ }),
+ );
+ }
+
+ const units = unitsOf(text, by, m);
+ const schedule = (starts: number[], dur = duration, e = ease) => ({
+ starts: indexedStarts(text, by, units, starts),
+ duration: dur,
+ ease: e,
+ });
+ const cuesFor = (starts: number[], dur: number) =>
+ units.map((u, i) => ({
+ frame: Math.round(starts[i] ?? 0),
+ settled: Math.round((starts[i] ?? 0) + dur),
+ index: u.index,
+ text: u.text,
+ }));
+
+ // Tracking widens a line: unwrapped text gets a box with room for it,
+ // placed so `align` holds while it grows.
+ const tracks =
+ wrap === undefined &&
+ (props.style === "track" || props.exitStyle === "track");
+ const room = tracks ? 0.5 * fs * Math.max(0, text.length - 1) : 0;
+ const shift =
+ props.align === "center" ? 0.5 : props.align === "end" ? 1 : 0;
+ const textNode = host.text(text, {
+ ...textProps,
+ ...(tracks && { width: W + room }),
+ id: ctx.partId("text"),
+ position: "absolute",
+ x: -room * shift,
+ y: 0,
+ });
+ parts.text = textNode;
+ // What carries the glyphs: the text node, or a wrapper around it (null when lines are split).
+ let main: LayoutNode | null = textNode;
+ let lines: MaskLine[] = [];
+ let sweep: ReturnType<typeof wipeMatte> | null = null;
+
+ // ── Enter ────────────────────────────────────────────────────────
+ switch (props.style) {
+ case "rise":
+ case "blur":
+ case "flip": {
+ const starts = unitStarts(units.length, stagger, props.order, ctx.seed);
+ animators.push(
+ glyphAnimator(
+ "enter",
+ scheduleExpression(by, schedule(starts), "enter"),
+ glyphFrom(props.style, fs, false),
+ ),
+ );
+ unitCues = cuesFor(starts, duration);
+ break;
+ }
+ case "slam": {
+ // Each unit is its own node so it scales around its own centre;
+ // the paragraph takes over the frame the last one lands.
+ const starts = unitStarts(units.length, stagger, props.order, ctx.seed);
+ unitCues = cuesFor(starts, duration);
+ const { width: _w, align: _a, ...unitProps } = textProps;
+ const pieces = units.map((u, i) => {
+ const rect = rangeRects(m, u.start, u.end, measureOptions)[0];
+ const s = starts[i] ?? 0;
+ const accented =
+ emphasised?.slice(u.start, u.end).every((v) => v === 1) ?? false;
+ const piece = host.text(u.text, {
+ ...unitProps,
+ ...(accented && { fill: props.accent ?? theme.color.accent }),
+ id: ctx.partId(`unit-${i}`),
+ position: "absolute",
+ x: rect?.x ?? 0,
+ y: rect?.y ?? 0,
+ });
+ piece.animate(
+ LayerAnimation.create()
+ .keys("scale", [
+ [s, 2.4],
+ [s + duration, 1, ease],
+ ])
+ .keys("opacity", [
+ [s, 0],
+ [s + Math.max(1, Math.round(duration * 0.45)), 1],
+ ]),
+ );
+ return piece;
+ });
+ const landed = Math.max(0, ...unitCues.map((u) => u.settled));
+ const group = host.box({
+ id: ctx.partId("units"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ children: pieces,
+ });
+ group.animate(
+ LayerAnimation.keys("opacity", [
+ [0, 1],
+ [landed, 0, "hold"],
+ ]),
+ );
+ textNode.animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [landed, 1, "hold"],
+ ]),
+ );
+ // A short landing shake as each unit hits.
+ const shake = host.box({
+ id: ctx.partId("shake"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ children: [group, textNode],
+ });
+ shake.animate(...slamShake(unitCues, fs, ctx.rng("slam")));
+ parts.units = group;
+ parts.shake = shake;
+ main = shake;
+ break;
+ }
+ case "scatter": {
+ const starts = unitStarts(units.length, stagger, props.order, ctx.seed);
+ const sched = schedule(starts);
+ const per = (key: string) => {
+ const q = ctx.rng(key);
+ return Array.from({ length: text.length }, () => q.spread(1));
+ };
+ const rx = per("scatter-x");
+ const ry = per("scatter-y");
+ const rr = per("scatter-r");
+ animators.push(
+ glyphAnimator("enter-x", scheduleExpression(by, sched, "enter", rx), {
+ x: 1.1 * fs,
+ }),
+ glyphAnimator("enter-y", scheduleExpression(by, sched, "enter", ry), {
+ y: 0.9 * fs,
+ }),
+ glyphAnimator("enter-r", scheduleExpression(by, sched, "enter", rr), {
+ rotation: 120,
+ }),
+ glyphAnimator("enter", scheduleExpression(by, sched, "enter"), {
+ opacity: 0,
+ blur: 0.06 * fs,
+ }),
+ );
+ unitCues = cuesFor(starts, duration);
+ break;
+ }
+ case "stream": {
+ const words = unitsOf(text, "word", m);
+ const step = scaleFrames(1, fps);
+ const starts = burstStarts(
+ words.length,
+ perFps(props.stagger ?? style.stagger),
+ step,
+ ctx.rng("stream"),
+ );
+ const fade = Math.max(2, themeFrames(theme, "fast", fps));
+ const ink = props.unitDuration ?? themeFrames(theme, "slow", fps);
+ animators.push(
+ glyphAnimator(
+ "enter",
+ scheduleExpression(
+ "word",
+ { starts, duration: fade, ease: "power2.out" },
+ "enter",
+ ),
+ { opacity: 0, y: 0.08 * fs },
+ ),
+ glyphAnimator(
+ "ink",
+ scheduleExpression(
+ "word",
+ { starts, duration: ink, ease: "sine.inOut" },
+ "enter",
+ ),
+ { fillColor: theme.color.muted },
+ ),
+ );
+ unitCues = words.map((w, i) => ({
+ frame: starts[i] ?? 0,
+ settled: (starts[i] ?? 0) + ink,
+ index: w.index,
+ text: w.text,
+ }));
+ words.forEach((w, i) => {
+ keystrokes.push({ frame: starts[i] ?? 0, index: w.index });
+ });
+ if (props.caret) {
+ const ends = words.map((w) => w.end);
+ const caret = buildCaret(ctx, m, measureOptions, fs, {
+ at: starts,
+ counts: ends,
+ until: (starts[starts.length - 1] ?? 0) + ink,
+ shape: "block",
+ });
+ children.push(caret);
+ parts.caret = caret;
+ }
+ break;
+ }
+ case "type": {
+ const frames = typingFrames(text, props.cps, fps, ctx.rng("type"));
+ textNode.animate(
+ LayerAnimation.keys(
+ "text" as AnimatableProp,
+ countKeys(text.length, frames),
+ ),
+ );
+ frames.forEach((f, i) => {
+ if (!/\s/.test(text[i] ?? ""))
+ keystrokes.push({ frame: f, index: i });
+ });
+ unitCues = keystrokes.map((k) => ({
+ frame: k.frame,
+ settled: k.frame,
+ index: k.index,
+ text: text[k.index] ?? "",
+ }));
+ revealed = (frames[frames.length - 1] ?? 0) + 1;
+ if (props.caret) {
+ const caret = buildCaret(ctx, m, measureOptions, fs, {
+ at: frames,
+ counts: frames.map((_, i) => i + 1),
+ until: revealed + ctx.hold,
+ shape: "bar",
+ });
+ children.push(caret);
+ parts.caret = caret;
+ }
+ break;
+ }
+ case "track": {
+ const ls = props.letterSpacing ?? 0;
+ const wide = ls + 0.5 * fs;
+ const fade = Math.round(duration * 0.5);
+ const keys: KeyframeTuple[] = [
+ [0, wide],
+ [duration, ls, ease],
+ ];
+ const anim = LayerAnimation.create()
+ .keys("letterSpacing", keys)
+ .keys("opacity", [
+ [0, 0],
+ [fade, 1, "power2.out"],
+ ]);
+ textNode.animate(anim);
+ unitCues = [{ frame: 0, settled: duration, index: 0, text }];
+ break;
+ }
+ case "mask": {
+ lines = maskLines(ctx, text, m, measureOptions, textProps, fs);
+ const starts = unitStarts(lines.length, stagger, props.order, ctx.seed);
+ lines.forEach((line, i) => {
+ const s = starts[i] ?? 0;
+ line.text.animate(
+ LayerAnimation.keys("y", [
+ [s, line.restY + line.travel],
+ [s + duration, line.restY, ease],
+ ]),
+ );
+ children.push(line.clip);
+ parts[`line-${i}`] = line.clip;
+ });
+ unitCues = lines.map((l, i) => ({
+ frame: Math.round(starts[i] ?? 0),
+ settled: Math.round((starts[i] ?? 0) + duration),
+ index: i,
+ text: l.content,
+ }));
+ main = null;
+ break;
+ }
+ case "wipe": {
+ const w = wipeMatte(ctx, W, H, fs, "hidden");
+ sweep = w;
+ w.matte.animate(
+ LayerAnimation.keys("x", [
+ [0, w.hidden],
+ [duration, w.shown, ease],
+ ]),
+ );
+ host.matte(textNode, w.matte);
+ parts.matte = w.matte;
+ // The front trails a little blur over the glyphs it is uncovering.
+ const xs = glyphCenters(text, m, measureOptions);
+ const front = Array.from({ length: duration + 1 }, (_, f) =>
+ w.front(
+ w.hidden + (w.shown - w.hidden) * evaluateEase(ease, f / duration),
+ ),
+ );
+ animators.push(
+ glyphAnimator(
+ "wipe-blur",
+ `((X,T)=>{const f=clamp(frame,0,${duration});const k=floor(f);const front=T[k]+((T[k+1]??T[k])-T[k])*(f-k);return clamp(1-(front-(X[textIndex]??0))/${round(w.feather)},0,1);})(${list(xs)},${list(front)})`,
+ { blur: 0.12 * fs },
+ ),
+ );
+ unitCues = [{ frame: 0, settled: duration, index: 0, text }];
+ break;
+ }
+ case "scramble": {
+ const result = scramble(ctx, text, m, measureOptions, textProps, {
+ stagger,
+ cycle: duration,
+ order: props.order,
+ });
+ children.push(result.reels);
+ parts.reels = result.reels;
+ // The real text takes over the moment the last glyph locks.
+ textNode.animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [result.done, 1, "hold"],
+ ]),
+ );
+ unitCues = result.cues;
+ break;
+ }
+ }
+
+ if (unitCues.length > 0 && props.style !== "type")
+ revealed = Math.max(...unitCues.map((u) => u.settled));
+ // The text is at rest only once the last landing shake dies out.
+ if (props.style === "slam") revealed += SHAKE.length - 1;
+
+ // ── Exit ─────────────────────────────────────────────────────────
+ let afterHold = 0;
+ const exitStart = revealed + ctx.hold;
+ if (props.exitStyle !== false) {
+ const out = props.exitStyle;
+ const outStyle = STYLE[out];
+ const outBy: GlyphUnit = props.by ?? outStyle.by;
+ const outUnits = unitsOf(text, outBy, m);
+ const outStagger = perFps((props.stagger ?? outStyle.stagger) * 0.5);
+ const outDur = Math.max(
+ 1,
+ Math.round(
+ themeFrames(theme, outStyle.speed, fps) * outStyle.length * 0.75,
+ ),
+ );
+ const outEase = theme.motion.ease.exit;
+ const starts = unitStarts(
+ outUnits.length,
+ outStagger,
+ props.order,
+ ctx.seed,
+ exitStart,
+ );
+ const sched: UnitSchedule = {
+ starts: indexedStarts(text, outBy, outUnits, starts),
+ duration: outDur,
+ ease: outEase,
+ };
+ afterHold = Math.round(Math.max(...starts) - exitStart + outDur);
+ switch (out) {
+ case "rise":
+ case "blur":
+ case "flip":
+ case "scatter":
+ case "stream":
+ animators.push(
+ glyphAnimator(
+ "exit",
+ scheduleExpression(outBy, sched, "exit"),
+ out === "scatter"
+ ? { y: -0.6 * fs, opacity: 0, blur: 0.06 * fs }
+ : glyphFrom(out, fs, true),
+ ),
+ );
+ break;
+ case "type": {
+ // Backspace, twice as fast as typing.
+ const per = Math.max(1, Math.round(fps / (props.cps * 2)));
+ const keys: KeyframeTuple[] = [];
+ for (
+ let c = text.length - 1, f = exitStart + per;
+ c >= 0;
+ c--, f += per
+ )
+ keys.push([f, c === 1 ? 1 / text.length : c, "hold"]);
+ textNode.animate(LayerAnimation.keys("text" as AnimatableProp, keys));
+ afterHold = per * text.length + 1;
+ break;
+ }
+ case "track": {
+ const ls = props.letterSpacing ?? 0;
+ textNode.animate(
+ LayerAnimation.create()
+ .keys("letterSpacing", [
+ [exitStart, ls],
+ [exitStart + outDur, ls + 0.4 * fs, outEase],
+ ])
+ .keys("opacity", [
+ [exitStart, 1],
+ [exitStart + outDur, 0, outEase],
+ ]),
+ );
+ afterHold = outDur;
+ break;
+ }
+ case "wipe": {
+ if (!sweep) {
+ sweep = wipeMatte(ctx, W, H, fs, "shown");
+ host.matte(textNode, sweep.matte);
+ parts.matte = sweep.matte;
+ }
+ sweep.matte.animate(
+ LayerAnimation.keys("x", [
+ [exitStart, sweep.shown],
+ [exitStart + outDur, sweep.gone, outEase],
+ ]),
+ );
+ afterHold = outDur;
+ break;
+ }
+ case "mask": {
+ if (lines.length === 0)
+ throw new Error(
+ 'TextReveal: exitStyle "mask" needs style "mask" (it splits the lines).',
+ );
+ const outStarts = unitStarts(
+ lines.length,
+ outStagger,
+ props.order,
+ ctx.seed,
+ exitStart,
+ );
+ lines.forEach((line, i) => {
+ const s = outStarts[i] ?? exitStart;
+ line.text.animate(
+ LayerAnimation.keys("y", [
+ [s, line.restY],
+ [s + outDur, line.restY - line.travel, outEase],
+ ]),
+ );
+ });
+ afterHold = Math.round(Math.max(...outStarts) - exitStart + outDur);
+ break;
+ }
+ }
+ }
+
+ if (animators.length > 0)
+ (textNode as unknown as { animators: GlyphAnimator[] }).animators =
+ animators;
+ if (main) children.unshift(main);
+
+ return {
+ children,
+ width: W,
+ height: H,
+ duration: Math.max(1, revealed),
+ openEnded: true,
+ afterHold,
+ cues: {
+ units: unitCues,
+ revealed: [{ frame: revealed }],
+ exitStart: props.exitStyle === false ? [] : [{ frame: exitStart }],
+ keystrokes,
+ } as TextRevealCues,
+ parts,
+ api: (placement): TextRevealApi => ({
+ rects(match, nth = 0) {
+ const range =
+ match === undefined
+ ? [0, text.length]
+ : findRange(text, match, nth);
+ if (!range)
+ throw new Error(
+ `TextReveal.rects: "${String(match)}" not found in "${text}".`,
+ );
+ return rangeRects(m, range[0], range[1], measureOptions).map((q) => ({
+ ...q,
+ x: q.x + placement.x,
+ y: q.y + placement.y,
+ }));
+ },
+ }),
+ };
+ },
+});
+
+// ── Helpers ──────────────────────────────────────────────────────────
+
+const round = (v: number) => Math.round(v * 10000) / 10000;
+const list = (values: readonly number[]) => `[${values.map(round).join(",")}]`;
+
+/** 1 for characters inside an emphasis match, else 0 (null when nothing matches). */
+function emphasisWeights(
+ text: string,
+ patterns: ReadonlyArray<string | RegExp>,
+): number[] | null {
+ if (patterns.length === 0) return null;
+ const w = new Array<number>(text.length).fill(0);
+ for (const p of patterns) {
+ for (let nth = 0; ; nth++) {
+ const range = findRange(text, p, nth);
+ if (!range || range[1] <= range[0]) break;
+ for (let i = range[0]; i < range[1]; i++) w[i] = 1;
+ }
+ }
+ return w.some((v) => v > 0) ? w : null;
+}
+
+/** Text-reveal count keys: ≤ 1 is a fraction, > 1 a character count. */
+function countKeys(length: number, frames: readonly number[]): KeyframeTuple[] {
+ const keys: KeyframeTuple[] = [[0, 0]];
+ frames.forEach((f, i) => {
+ const c = i + 1;
+ keys.push([f, c === 1 ? 1 / length : c, "hold"]);
+ });
+ return keys;
+}
+
+/** Landing shake, per frame after a unit lands (× 0.045 em). */
+const SHAKE = [0, 1, -0.55, 0.3, -0.12, 0];
+
+function slamShake(
+ units: ReadonlyArray<{ settled: number }>,
+ fs: number,
+ r: { spread(n: number): number },
+): LayerAnimation[] {
+ const end = Math.max(0, ...units.map((u) => u.settled)) + 8;
+ const xs = new Array<number>(end + 1).fill(0);
+ const ys = new Array<number>(end + 1).fill(0);
+ const a = 0.045 * fs;
+ const profile = SHAKE;
+ for (const u of units) {
+ const dx = r.spread(1);
+ profile.forEach((p, k) => {
+ const f = u.settled + k;
+ if (f <= end) {
+ xs[f] = (xs[f] ?? 0) + a * p * dx;
+ ys[f] = (ys[f] ?? 0) + a * p * 0.6;
+ }
+ });
+ }
+ return [
+ // Tight tolerance: the text must come to rest exactly where it belongs.
+ LayerAnimation.keys("x", bakeSamples(xs, 0, { tolerance: 0.005 })),
+ LayerAnimation.keys("y", bakeSamples(ys, 0, { tolerance: 0.005 })),
+ ];
+}
+
+interface Ctx {
+ host: import("../core/host.js").Host;
+ theme: Theme;
+ fps: number;
+ seed: number;
+ partId(part: string): string;
+ rng(key: string | number): import("../core/rng.js").Rng;
+}
+
+/** Where the caret sits after `count` characters: x, and the line's top. */
+function caretAt(
+ count: number,
+ m: Metrics,
+ options: MeasureOptions,
+): [number, number] {
+ let last: Metrics["glyphs"][number] | undefined;
+ for (const g of m.glyphs)
+ if (g.index < count && (!last || g.index > last.index)) last = g;
+ if (!last) return [lineShift(m, 0, options), 0];
+ const shift = lineShift(m, last.line, options);
+ return [
+ shift + last.x + last.width - (options.letterSpacing ?? 0),
+ last.line * m.lineHeight,
+ ];
+}
+
+function buildCaret(
+ ctx: Ctx,
+ m: Metrics,
+ options: MeasureOptions,
+ fs: number,
+ o: {
+ at: readonly number[];
+ counts: readonly number[];
+ until: number;
+ shape: "bar" | "block";
+ },
+): Animatable<LayoutNode> {
+ const w = o.shape === "bar" ? Math.max(2, 0.06 * fs) : 0.42 * fs;
+ const h = o.shape === "bar" ? 1.05 * fs : 0.42 * fs;
+ const dy =
+ o.shape === "bar" ? (m.lineHeight - h) / 2 : m.lineHeight * 0.52 - h / 2;
+ const gap = o.shape === "bar" ? 0.04 * fs : 0.18 * fs;
+ const [x0, y0] = caretAt(0, m, options);
+ const xs: KeyframeTuple[] = [[0, x0 + (o.shape === "bar" ? 0 : -w)]];
+ const ys: KeyframeTuple[] = [[0, y0 + dy]];
+ o.at.forEach((f, i) => {
+ const [x, y] = caretAt(o.counts[i] ?? 0, m, options);
+ xs.push([f, x + gap, "hold"]);
+ ys.push([f, y + dy, "hold"]);
+ });
+ const caret = ctx.host.box({
+ id: ctx.partId("caret"),
+ position: "absolute",
+ x: x0,
+ y: y0 + dy,
+ width: w,
+ height: h,
+ background: ctx.theme.color.accent,
+ borderRadius: o.shape === "bar" ? w / 2 : w * 0.18,
+ });
+ // Solid while text arrives, then a few blinks, then gone.
+ const last = o.at[o.at.length - 1] ?? 0;
+ const half = Math.max(1, Math.round(ctx.fps * 0.5));
+ const blink: KeyframeTuple[] = [[0, 1]];
+ let on = false;
+ for (let f = last + half; f < o.until; f += half, on = !on)
+ blink.push([f, on ? 1 : 0, "hold"]);
+ blink.push([Math.max(last + 1, o.until), 0, "hold"]);
+ caret.animate(
+ LayerAnimation.create().keys("x", xs).keys("y", ys).keys("opacity", blink),
+ );
+ return caret;
+}
+
+/** Centre x of every character (spaces included), wrapped and aligned. */
+function glyphCenters(
+ text: string,
+ m: Metrics,
+ options: MeasureOptions,
+): number[] {
+ const xs = new Array<number>(text.length).fill(0);
+ for (const g of m.glyphs)
+ xs[g.index] = lineShift(m, g.line, options) + g.x + g.width / 2;
+ return xs;
+}
+
+/**
+ * A soft-edged matte for `wipe`: transparent → opaque → opaque → transparent,
+ * `feather` px ramps. `hidden` / `shown` / `gone` are its x for each phase.
+ */
+function wipeMatte(
+ ctx: Ctx,
+ W: number,
+ H: number,
+ fs: number,
+ initial: "hidden" | "shown",
+) {
+ const feather = Math.max(24, 0.9 * fs);
+ const pad = fs * 0.5;
+ const total = W + feather * 2;
+ const a = ((feather / total) * 100).toFixed(3);
+ const b = (((feather + W) / total) * 100).toFixed(3);
+ const hidden = -total;
+ const shown = -feather;
+ const matte = ctx.host.box({
+ id: ctx.partId("matte"),
+ position: "absolute",
+ x: initial === "hidden" ? hidden : shown,
+ y: -pad,
+ width: total,
+ height: H + pad * 2,
+ background: `linear-gradient(90deg, rgba(255,255,255,0) 0%, #ffffff ${a}%, #ffffff ${b}%, rgba(255,255,255,0) 100%)`,
+ });
+ return {
+ matte,
+ feather,
+ total,
+ hidden,
+ shown,
+ gone: W + feather,
+ /** Where visibility reaches zero, for a matte at `x`. */
+ front: (x: number) => x + total,
+ };
+}
+
+interface MaskLine {
+ clip: Animatable<LayoutNode>;
+ text: Animatable<TextNode>;
+ content: string;
+ restY: number;
+ travel: number;
+}
+
+/** One clipped text node per measured line, each at its wrapped position. */
+function maskLines(
+ ctx: Ctx,
+ text: string,
+ m: Metrics,
+ options: MeasureOptions,
+ textProps: TextProps,
+ fs: number,
+): MaskLine[] {
+ const pad = Math.round(fs * 0.18);
+ const { width: _w, align: _a, ...lineProps } = textProps;
+ return unitsOf(text, "line", m).map((u, i) => {
+ const first = m.glyphs.find(
+ (g) => g.index >= u.start && !/\s/.test(g.char),
+ );
+ const x = lineShift(m, i, options) + (first?.x ?? 0);
+ const content = text.slice(u.start, u.end).trim();
+ const lineText = ctx.host.text(content, {
+ ...lineProps,
+ id: ctx.partId(`line-${i}-text`),
+ position: "absolute",
+ x,
+ y: pad,
+ });
+ const clip = ctx.host.box({
+ id: ctx.partId(`line-${i}`),
+ position: "absolute",
+ x: 0,
+ y: i * m.lineHeight - pad,
+ width: Math.max(m.width, options.width ?? 0) + fs,
+ height: m.lineHeight + pad * 2,
+ overflow: "hidden",
+ children: [lineText],
+ });
+ return {
+ clip,
+ text: lineText,
+ content,
+ restY: pad,
+ travel: m.lineHeight + pad,
+ };
+ });
+}
+
+/**
+ * Scramble: each character is a clipped vertical reel of seeded glyphs that
+ * steps every couple of frames and lands on the real glyph. Reels are as
+ * wide as the real glyph's advance, so the line never jitters.
+ */
+function scramble(
+ ctx: Ctx,
+ text: string,
+ m: Metrics,
+ options: MeasureOptions,
+ textProps: TextProps,
+ o: { stagger: number; cycle: number; order: (typeof ORDERS)[number] },
+) {
+ const units = unitsOf(text, "char", m);
+ const starts = unitStarts(units.length, o.stagger, o.order, ctx.seed);
+ const step = Math.max(1, scaleFrames(2, ctx.fps));
+ const { width: _w, align: _a, letterSpacing: _l, ...glyphProps } = textProps;
+ const reels: LayoutNode[] = [];
+ const cues: Array<{
+ frame: number;
+ settled: number;
+ index: number;
+ text: string;
+ }> = [];
+ let done = 0;
+ units.forEach((u, i) => {
+ const g = m.glyphs.find((q) => q.index === u.start);
+ if (!g) return;
+ const appear = Math.round((starts[i] ?? 0) * 0.5);
+ const lock = Math.round((starts[i] ?? 0) + o.cycle);
+ const r = ctx.rng(`scramble:${u.start}`);
+ const set = scrambleSet(u.text);
+ const count = Math.max(1, Math.floor((lock - appear) / step));
+ const glyphs = Array.from({ length: count }, () => r.pick([...set]));
+ glyphs.push(u.text);
+ const advance = g.width - (options.letterSpacing ?? 0);
+ const reel = ctx.host.text(glyphs.join("\n"), {
+ ...glyphProps,
+ id: ctx.partId(`reel-${u.start}`),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: advance,
+ align: "center",
+ });
+ const ys: KeyframeTuple[] = [[0, 0]];
+ for (let k = 1; k < count; k++)
+ ys.push([appear + k * step, -k * m.lineHeight, "hold"]);
+ ys.push([lock, -count * m.lineHeight, "hold"]);
+ reel.animate(
+ LayerAnimation.create()
+ .keys("y", ys)
+ .keys("opacity", [
+ [appear, 0],
+ [appear + 3, 1],
+ ]),
+ );
+ reels.push(
+ ctx.host.box({
+ id: ctx.partId(`cell-${u.start}`),
+ position: "absolute",
+ x: lineShift(m, g.line, options) + g.x,
+ y: g.line * m.lineHeight,
+ width: advance,
+ height: m.lineHeight,
+ overflow: "hidden",
+ children: [reel],
+ }),
+ );
+ cues.push({ frame: appear, settled: lock, index: u.index, text: u.text });
+ done = Math.max(done, lock);
+ });
+ const group = ctx.host.box({
+ id: ctx.partId("reels"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: m.width,
+ height: m.height,
+ children: reels,
+ });
+ group.animate(
+ LayerAnimation.keys("opacity", [
+ [0, 1],
+ [done, 0, "hold"],
+ ]),
+ );
+ return { reels: group, cues, done };
+}
diff --git a/packages/components/src/text-reveal/meta.ts b/packages/components/src/text-reveal/meta.ts
new file mode 100644
index 00000000..865ed446
--- /dev/null
+++ b/packages/components/src/text-reveal/meta.ts
@@ -0,0 +1,12 @@
+import { defineMeta } from "../core/meta.js";
+
+export default defineMeta({
+ name: "TextReveal",
+ summary:
+ "Headlines and body copy that animate in and out by character, word or line: rise, blur, track, mask, slam, scatter, scramble, type, stream, wipe and flip, each ending on exactly the static text.",
+ tags: ["text", "typography", "kinetic type", "title", "reveal", "typewriter"],
+ parts: ["text", "shake", "caret", "matte", "reels", "line-<n>"],
+ cues: ["units", "revealed", "exitStart", "keystrokes"],
+ example: `TextReveal({ text: "Ship it faster", style: "rise", emphasis: ["faster"] })`,
+ since: "M2",
+});
diff --git a/packages/components/src/text-reveal/plan.test.ts b/packages/components/src/text-reveal/plan.test.ts
new file mode 100644
index 00000000..c860a7dd
--- /dev/null
+++ b/packages/components/src/text-reveal/plan.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vitest";
+import { rng } from "../core/rng.js";
+import { fakeMeasure } from "../test/fake-host.js";
+import {
+ burstStarts,
+ indexedStarts,
+ scrambleSet,
+ typingFrames,
+ unitsOf,
+} from "./plan.js";
+
+const m = (text: string, width?: number) =>
+ fakeMeasure(text, { fontFamily: "Inter", fontSize: 20, width });
+
+describe("TextReveal units", () => {
+ it("splits by character (skipping spaces), word and measured line", () => {
+ const text = "ab cd ef";
+ expect(
+ unitsOf(text, "char", m(text))
+ .map((u) => u.text)
+ .join(""),
+ ).toBe("abcdef");
+ expect(unitsOf(text, "word", m(text)).map((u) => u.text)).toEqual([
+ "ab",
+ "cd",
+ "ef",
+ ]);
+ // 10 px per glyph: 50 px fits "ab cd", then wraps.
+ expect(unitsOf(text, "line", m(text, 50)).map((u) => u.text)).toEqual([
+ "ab cd",
+ "ef",
+ ]);
+ });
+
+ it("indexes a character schedule by string position; spaces take the next unit's start", () => {
+ const text = "ab cd";
+ const units = unitsOf(text, "char", m(text));
+ expect(indexedStarts(text, "char", units, [0, 1, 2, 3])).toEqual([
+ 0, 1, 2, 2, 3,
+ ]);
+ expect(
+ indexedStarts(text, "word", unitsOf(text, "word", m(text)), [0, 5]),
+ ).toEqual([0, 5]);
+ });
+});
+
+describe("typing rhythm", () => {
+ it("is seeded, strictly increasing, and pauses after punctuation", () => {
+ const text = "Hi. Go now";
+ const a = typingFrames(text, 20, 30, rng(3));
+ expect(typingFrames(text, 20, 30, rng(3))).toEqual(a);
+ expect(typingFrames(text, 20, 30, rng(4))).not.toEqual(a);
+ for (let i = 1; i < a.length; i++)
+ expect(a[i]).toBeGreaterThan(a[i - 1] as number);
+ const gap = (i: number) => (a[i] as number) - (a[i - 1] as number);
+ // The keystroke after "." waits much longer than one inside a word.
+ expect(gap(3)).toBeGreaterThan(gap(1) * 2);
+ });
+});
+
+describe("streaming bursts", () => {
+ it("gives every word a start, ascending, with uneven gaps", () => {
+ const starts = burstStarts(12, 6, 1, rng(1));
+ expect(starts).toHaveLength(12);
+ for (let i = 1; i < starts.length; i++)
+ expect(starts[i]).toBeGreaterThanOrEqual(starts[i - 1] as number);
+ const gaps = new Set(
+ starts.slice(1).map((s, i) => s - (starts[i] as number)),
+ );
+ expect(gaps.size).toBeGreaterThan(2);
+ });
+});
+
+describe("scramble glyphs", () => {
+ it("keep the character's case or class", () => {
+ expect(scrambleSet("A")).toMatch(/^ABC/);
+ expect(scrambleSet("q")).toMatch(/^abc/);
+ expect(scrambleSet("7")).toMatch(/^0123/);
+ });
+});
diff --git a/packages/components/src/text-reveal/plan.ts b/packages/components/src/text-reveal/plan.ts
new file mode 100644
index 00000000..3ad07e7d
--- /dev/null
+++ b/packages/components/src/text-reveal/plan.ts
@@ -0,0 +1,154 @@
+/**
+ * TextReveal timing, kept pure: which characters form each unit, when each
+ * unit starts, the typing rhythm and the streaming bursts.
+ */
+import type { GlyphUnit } from "../core/glyphs.js";
+import type { Rng } from "../core/rng.js";
+import { type Metrics, wordRanges } from "../core/text.js";
+import { type StaggerOrder, staggerRanks } from "../core/timing.js";
+
+export interface Unit {
+ index: number;
+ text: string;
+ /** Character range [start, end). */
+ start: number;
+ end: number;
+}
+
+const isSpace = (c: string) => /\s/.test(c);
+
+/** The units text animates by. Characters skip whitespace; lines follow measured wrapping. */
+export function unitsOf(text: string, by: GlyphUnit, metrics: Metrics): Unit[] {
+ if (by === "char") {
+ const out: Unit[] = [];
+ for (let i = 0; i < text.length; i++) {
+ const c = text[i] as string;
+ if (!isSpace(c))
+ out.push({ index: out.length, text: c, start: i, end: i + 1 });
+ }
+ return out;
+ }
+ if (by === "word") {
+ return wordRanges(text).map((w) => ({
+ index: w.index,
+ text: w.text,
+ start: w.start,
+ end: w.end,
+ }));
+ }
+ const lines = new Map<number, { start: number; end: number }>();
+ for (const g of metrics.glyphs) {
+ const line = lines.get(g.line) ?? {
+ start: Number.POSITIVE_INFINITY,
+ end: 0,
+ };
+ line.start = Math.min(line.start, g.index);
+ line.end = Math.max(line.end, g.index + 1);
+ lines.set(g.line, line);
+ }
+ return [...lines.entries()]
+ .sort(([a], [b]) => a - b)
+ .map(([, r], index) => ({
+ index,
+ text: text.slice(r.start, r.end).trim(),
+ start: r.start,
+ end: r.end,
+ }));
+}
+
+/** Start frame per unit: rank in `order` × `stagger` (fractional frames allowed). */
+export function unitStarts(
+ count: number,
+ stagger: number,
+ order: StaggerOrder,
+ seed: number,
+ offset = 0,
+): number[] {
+ return staggerRanks(count, order, seed).map((r) => offset + r * stagger);
+}
+
+/**
+ * The schedule indexed the way the renderer indexes `by`: per character
+ * (spaces take the next unit's start, so they never lag) or per word / line.
+ */
+export function indexedStarts(
+ text: string,
+ by: GlyphUnit,
+ units: readonly Unit[],
+ starts: readonly number[],
+): number[] {
+ if (by !== "char") return [...starts];
+ const out = new Array<number>(text.length).fill(0);
+ let next = starts[starts.length - 1] ?? 0;
+ for (let u = units.length - 1, i = text.length - 1; i >= 0; i--) {
+ const unit = units[u];
+ if (unit && unit.start === i) {
+ next = starts[u] ?? next;
+ u--;
+ }
+ out[i] = next;
+ }
+ return out;
+}
+
+/**
+ * Keystroke frames for typing at `cps` characters a second: seeded ±30 %
+ * jitter, a beat after spaces, a longer one after punctuation. Frame `k[i]`
+ * is when character `i` appears.
+ */
+export function typingFrames(
+ text: string,
+ cps: number,
+ fps: number,
+ r: Rng,
+ start = 0,
+): number[] {
+ const per = fps / cps;
+ const out: number[] = [];
+ let t = start;
+ for (let i = 0; i < text.length; i++) {
+ const prev = text[i - 1] ?? "";
+ let gap = i === 0 ? 0 : per * (1 + r.spread(0.3));
+ if (prev === " ") gap += per * 0.6;
+ if (/[.,!?;:]/.test(prev)) gap += per * 3;
+ t += gap;
+ out.push(Math.max(start, Math.round(t)));
+ }
+ // Two characters never land on one frame.
+ for (let i = 1; i < out.length; i++)
+ out[i] = Math.max(out[i] as number, (out[i - 1] as number) + 1);
+ return out;
+}
+
+/**
+ * Streaming: words arrive in seeded bursts of 1–3, one frame apart inside a
+ * burst, with an uneven pause between bursts (`gap` frames ± 50 %).
+ */
+export function burstStarts(
+ count: number,
+ gap: number,
+ step: number,
+ r: Rng,
+ start = 0,
+): number[] {
+ const out: number[] = [];
+ let t = start;
+ while (out.length < count) {
+ const size = r.int(1, 3);
+ for (let i = 0; i < size && out.length < count; i++) {
+ out.push(Math.round(t));
+ t += step;
+ }
+ t += gap * (0.5 + r.next());
+ }
+ return out;
+}
+
+/** Glyphs a scrambling character cycles through: same case or class, plus a few symbols. */
+export function scrambleSet(char: string): string {
+ const symbols = "#%&*+=/<>?$";
+ if (/[A-Z]/.test(char)) return `ABCDEFGHIJKLMNOPQRSTUVWXYZ${symbols}`;
+ if (/[a-z]/.test(char)) return `abcdefghijklmnopqrstuvwxyz${symbols}`;
+ if (/[0-9]/.test(char)) return `0123456789${symbols}`;
+ return `${symbols}ABCDEFGHJKMNPRSTUVWXYZ`;
+}
diff --git a/packages/framefields/scripts/check-components-treeshake.mjs b/packages/framefields/scripts/check-components-treeshake.mjs
index 504be2b5..4fdb6459 100644
--- a/packages/framefields/scripts/check-components-treeshake.mjs
+++ b/packages/framefields/scripts/check-components-treeshake.mjs
@@ -16,6 +16,13 @@ const CONTRACT = "invalid props";
const STROKES = "wobble:";
const TARGETS = "has no absolute geometry";
const MOTION = "Unknown motion preset";
+const POINTER = "hover regions must be static targets";
+const FRAME = "Expected a layer, an array of layers, or a media path";
+const CAMERA = "must be a static target.";
+const REVEAL = "is not registered. Registered:";
+const COUNTER = "Counter: unsupported format";
+const ANNOTATE = "Moving targets arrive with Callout";
+const GLYPHS = "L[k+1]-L[k]";
/** [names imported, markers that must not survive, max added bytes]. */
const cases = [
@@ -23,6 +30,17 @@ const cases = [
[["boxPath", "ellipsePath"], [CONTRACT, TARGETS, MOTION], 6_000],
[["resolveTarget", "targetPoint"], [CONTRACT, STROKES, MOTION], 10_000],
[["staggerOffsets", "toFrames"], [CONTRACT, STROKES, TARGETS, MOTION], 3_000],
+ // Each component alone: none of the others.
+ [
+ ["MousePointer"],
+ [FRAME, CAMERA, REVEAL, COUNTER, ANNOTATE, GLYPHS],
+ 60_000,
+ ],
+ [["AppFrame"], [POINTER, CAMERA, REVEAL, COUNTER, ANNOTATE, GLYPHS], 45_000],
+ [["FocusZoom"], [POINTER, FRAME, REVEAL, COUNTER, ANNOTATE, GLYPHS], 40_000],
+ [["TextReveal"], [POINTER, FRAME, CAMERA, COUNTER, ANNOTATE], 55_000],
+ [["Counter"], [POINTER, FRAME, CAMERA, REVEAL, ANNOTATE, GLYPHS], 45_000],
+ [["Annotate"], [POINTER, FRAME, CAMERA, REVEAL, COUNTER, GLYPHS], 50_000],
];
async function bundle(contents) {
@@ -42,13 +60,30 @@ const baseline = `import { Layer } from ${JSON.stringify(root)};\nconsole.log(La
const base = await bundle(baseline);
const failures = [];
+// Using framefields without components must carry none of them: component
+// modules may not build anything (schemas, glyphs) at import time.
+for (const marker of [
+ CONTRACT,
+ STROKES,
+ TARGETS,
+ POINTER,
+ FRAME,
+ CAMERA,
+ REVEAL,
+ COUNTER,
+ ANNOTATE,
+ GLYPHS,
+]) {
+ if (base.includes(marker))
+ failures.push(`import { Layer } alone kept component code ("${marker}")`);
+}
for (const [names, forbidden, budget] of cases) {
const code = await bundle(
`${baseline}\nimport { ${names.join(", ")} } from ${JSON.stringify(components)};\nconsole.log(${names.join(", ")});`,
);
const label = `import { ${names.join(", ")} }`;
for (const marker of forbidden) {
- if (code.includes(marker) && !base.includes(marker)) {
+ if (code.includes(marker)) {
failures.push(`${label} kept code containing "${marker}"`);
}
}
diff --git a/packages/framefields/src/components/contract.render.test.ts b/packages/framefields/src/components/contract.render.test.ts
index d3aede14..1174404a 100644
--- a/packages/framefields/src/components/contract.render.test.ts
+++ b/packages/framefields/src/components/contract.render.test.ts
@@ -12,10 +12,10 @@ import { bindComponent } from "./index.js";
const Probe = bindComponent(
defineComponent({
name: "Probe",
- props: {
+ props: () => ({
color: z.string().default("#ff0000"),
size: z.number().default(100),
- },
+ }),
defaults: { enter: { preset: "rise", duration: 10 }, hold: 20 },
build(ctx, props) {
const plate = ctx.host.box({
diff --git a/packages/framefields/src/components/host.ts b/packages/framefields/src/components/host.ts
index f6954d13..42c11fb0 100644
--- a/packages/framefields/src/components/host.ts
+++ b/packages/framefields/src/components/host.ts
@@ -3,10 +3,25 @@
* factories, real font measurement and stable ids. `Layer` is read inside
* each call, never at module load, so importing this file has no effects.
*/
-import type { Host } from "@framefields/components";
+import type { Host, LayerStyleConfig } from "@framefields/components";
+import { LayerStyle } from "../effects/index.js";
import { FontManager } from "../fonts/index.js";
import { autoId } from "../ids.js";
-import { Layer } from "../index.js";
+import { type AnimatableNode, Layer } from "../index.js";
+
+const IMAGE = /\.(png|jpe?g|webp|gif|avif|tiff?|bmp)(\?.*)?$/i;
+
+/** Every style the config names is switched on. */
+function layerStyle(config: LayerStyleConfig): LayerStyle {
+ const on = <T extends object>(s: T | undefined) =>
+ s ? { ...s, enabled: true } : undefined;
+ return new LayerStyle({
+ ...(config.dropShadow && { dropShadow: on(config.dropShadow) }),
+ ...(config.outerGlow && { outerGlow: on(config.outerGlow) }),
+ ...(config.innerShadow && { innerShadow: on(config.innerShadow) }),
+ ...(config.stroke && { stroke: on(config.stroke) }),
+ } as ConstructorParameters<typeof LayerStyle>[0]);
+}
export const host: Host = {
box: (options) => Layer.box(options),
@@ -16,4 +31,16 @@ export const host: Host = {
measure: (text, options) => FontManager.measure(text, options),
fonts: () => FontManager.getAll().map((f) => f.family),
autoId,
+ media: (source, options) =>
+ IMAGE.test(source)
+ ? Layer.image(source, options)
+ : Layer.video(source, { muted: true, ...options }),
+ style: (node, config) => {
+ (node as unknown as AnimatableNode).withEffect(layerStyle(config));
+ return node;
+ },
+ matte: (node, matte) => {
+ (node as unknown as AnimatableNode).withMatte(matte, "alpha");
+ return node;
+ },
};
diff --git a/packages/framefields/src/components/index.ts b/packages/framefields/src/components/index.ts
index d0a0e58d..032da361 100644
--- a/packages/framefields/src/components/index.ts
+++ b/packages/framefields/src/components/index.ts
@@ -9,11 +9,17 @@
*/
import {
+ annotate,
+ appFrame,
type BaseProps,
bind,
type ComponentDefinition,
type ComponentExtras,
type Cues,
+ counter,
+ focusZoom,
+ mousePointer,
+ textReveal,
} from "@framefields/components";
import type { BoxNode } from "@framefields/compositions/program";
import type { z } from "zod";
@@ -28,14 +34,40 @@ export type ComponentNode<C extends Cues = Cues> = AnimatableNode<BoxNode> &
* Bind a component definition to framefields, producing its factory. Use it
* for your own components built with `defineComponent`.
*/
-export function bindComponent<S extends z.ZodRawShape, C extends Cues>(
- definition: ComponentDefinition<S, C>,
-): (props: z.input<z.ZodObject<S>> & BaseProps) => ComponentNode<C> {
+export function bindComponent<
+ S extends z.ZodRawShape,
+ C extends Cues,
+ E extends object = object,
+>(
+ definition: ComponentDefinition<S, C, E>,
+): (props: z.input<z.ZodObject<S>> & BaseProps) => ComponentNode<C> & E {
return bind(host, definition) as never;
}
+/** An animated pointer that travels, clicks, drags and changes shape, with a cue for every click. */
+export const MousePointer = /* @__PURE__ */ bindComponent(mousePointer);
+
+/** Window chrome (desktop window, browser, terminal) around any content; `at(x, y)` points into it. */
+export const AppFrame = /* @__PURE__ */ bindComponent(appFrame);
+
+/** A camera over 2D content that pushes in on clicks or shots and eases back out. */
+export const FocusZoom = /* @__PURE__ */ bindComponent(focusZoom);
+
+/** Text that animates in and out by character, word or line, ending on exactly the static text. */
+export const TextReveal = /* @__PURE__ */ bindComponent(textReveal);
+
+/** A number that counts to its value on odometer reels, format-aware. */
+export const Counter = /* @__PURE__ */ bindComponent(counter);
+
+/** Marks that draw on to point at something: underline, circle, arrow, highlight … hand-drawn or clean. */
+export const Annotate = /* @__PURE__ */ bindComponent(annotate);
+
export {
type Anchor,
+ type AnnotateCues,
+ type AppFrameApi,
+ type AppFrameCues,
+ type AppFrameKind,
type ArcPath,
type ArrowCurve,
type ArrowGeometry,
@@ -45,11 +77,11 @@ export {
type BakedKey,
type BakeOptions,
type BaseProps,
- BasePropsSchema,
type BuildContext,
type BuildResult,
bakeFunction,
bakeSamples,
+ basePropsSchema,
beats,
boilKeys,
boundsOf,
@@ -58,11 +90,16 @@ export {
type ComponentDefinition,
type ComponentExtras,
type ComponentMeta,
+ type CounterCues,
+ type CounterFormat,
+ CURSOR_STYLES,
type Cue,
type Cues,
type CuesOf,
+ type CursorStyle,
catmullRom,
chain,
+ constantExpression,
contrastRatio,
cover,
defineComponent,
@@ -71,33 +108,52 @@ export {
dist,
drawOnKeys,
type EaseFn,
+ EXIT_STYLES,
+ type ExitStyle,
ease,
ellipsePath,
enterAnimation,
evaluateEase,
+ evaluateGlyphExpression,
exitAnimation,
+ type FocusZoomApi,
+ type FocusZoomCues,
+ type Followable,
type FrameWindow,
findRange,
frameSpan,
+ type GlyphAnimator,
+ type GlyphProps,
+ type GlyphUnit,
+ glyphAnimator,
type HandOptions,
hashRng,
hashString,
lerp2,
linePath,
+ lineShift,
+ MARKS,
+ type Mark,
type MeasureOptions,
type Metrics,
MOTION_PRESETS,
type MotionOptions,
type MotionPreset,
type MotionPresetName,
+ type MotionSize,
+ type MousePointerApi,
+ type MousePointerCues,
offsetCues,
+ type Placement,
type PropsOf,
type PulseOptions,
pulseKeys,
quantize,
+ REVEAL_STYLES,
type Rect,
type ResolvedMotion,
type ResolvedTarget,
+ type RevealStyle,
type Rng,
rangeRects,
resolveMotion,
@@ -105,6 +161,7 @@ export {
rng,
type StaggerOrder,
scaleFrames,
+ scheduleExpression,
springAt,
springSettleFrames,
squigglePath,
@@ -112,6 +169,8 @@ export {
staggerRanks,
type Target,
type TargetContext,
+ type TextRevealApi,
+ type TextRevealCues,
type Theme,
type ThemeInput,
type ThemeName,
@@ -121,7 +180,9 @@ export {
toFrames,
toPathData,
toSeconds,
+ type UnitSchedule,
type Vec2,
+ type Waypoint,
type WordRange,
within,
wobblePoints,
diff --git a/packages/framefields/src/components/m1.render.test.ts b/packages/framefields/src/components/m1.render.test.ts
new file mode 100644
index 00000000..56af6a70
--- /dev/null
+++ b/packages/framefields/src/components/m1.render.test.ts
@@ -0,0 +1,130 @@
+import { describe, expect, it } from "vitest";
+import { Composition, Layer } from "../index.js";
+import { decodePngPixels, getPixel } from "../test-utils/pixels.js";
+import { AppFrame, FocusZoom, MousePointer } from "./index.js";
+
+/**
+ * Render tests for the M1 components (spec §7.1, §7.2, §7.7): what the
+ * components promise in numbers (cues, rects, toScreen) must match pixels.
+ */
+const W = 640;
+const H = 360;
+
+function comp(
+ nodes: Parameters<Composition["add"]>[0],
+ background = "#ffffff",
+) {
+ const c = new Composition({
+ width: W,
+ height: H,
+ fps: 30,
+ durationMs: 4000,
+ backgroundColor: background,
+ });
+ c.add(nodes);
+ return c;
+}
+const frame = async (c: Composition, n: number) =>
+ decodePngPixels(await c.renderFrame({ frame: n }));
+const dark = (p: { r: number; g: number; b: number }) => p.r + p.g + p.b < 120;
+
+describe("MousePointer (render)", () => {
+ it("is on its target, pressed, on the click frame", async () => {
+ const pointer = MousePointer({
+ path: [{ to: [120, 120] }, { to: [420, 200], click: true }],
+ area: { width: W, height: H },
+ shadow: false,
+ ripple: false,
+ });
+ const click = pointer.cues.clicks[0]?.frame ?? 0;
+ const img = await frame(comp(pointer), click);
+ // Inside the arrow, just below and right of the hotspot (glyph is ~44 px).
+ expect(dark(getPixel(img, 424, 214))).toBe(true);
+ // Up-left of the hotspot is outside the arrow.
+ expect(dark(getPixel(img, 410, 190))).toBe(false);
+ // Nothing where it started.
+ expect(dark(getPixel(img, 124, 134))).toBe(false);
+ });
+
+ it("leaves a ripple ring where it clicked", async () => {
+ const pointer = MousePointer({
+ path: [{ to: [300, 180], click: true }],
+ area: { width: W, height: H },
+ accent: "#ff0000",
+ shadow: false,
+ });
+ const click = pointer.cues.clicks[0]?.frame ?? 0;
+ const img = await frame(comp(pointer), click + 10);
+ // Somewhere on the ring left of the click point is red.
+ const reds = Array.from({ length: 50 }, (_, i) =>
+ getPixel(img, 300 - 20 - i, 180),
+ ).filter((p) => p.r > 200 && p.g < 140 && p.b < 140);
+ expect(reds.length).toBeGreaterThan(0);
+ });
+});
+
+describe("AppFrame (render)", () => {
+ it("draws content exactly in contentRect", async () => {
+ const f = AppFrame({
+ kind: "window",
+ x: 40,
+ y: 30,
+ width: 560,
+ height: 300,
+ contentBackground: "#00ff00",
+ elevation: 0,
+ enter: false,
+ });
+ const r = f.contentRect;
+ const img = await frame(comp(f, "#000000"), 0);
+ const inside = getPixel(img, r.x + r.width / 2, r.y + r.height / 2);
+ expect(inside.g).toBeGreaterThan(240);
+ expect(inside.r).toBeLessThan(20);
+ // The title bar above the content is chrome, not content.
+ const bar = getPixel(img, r.x + r.width / 2, r.y - 10);
+ expect(bar.g).toBeLessThan(100);
+ // Content placed with at() lands where at() says.
+ f.fill(
+ Layer.box({
+ position: "absolute",
+ x: 100,
+ y: 100,
+ width: 20,
+ height: 20,
+ background: "#ff00ff",
+ }),
+ );
+ const [mx, my] = f.at(110, 110);
+ const img2 = await frame(comp(f, "#000000"), 0);
+ const m = getPixel(img2, mx, my);
+ expect(m.r).toBeGreaterThan(240);
+ expect(m.b).toBeGreaterThan(240);
+ });
+});
+
+describe("FocusZoom (render)", () => {
+ it("draws content where toScreen says, zoomed", async () => {
+ const target = { x: 500, y: 90, width: 40, height: 40 };
+ const camera = FocusZoom({
+ width: W,
+ height: H,
+ content: [
+ Layer.box({ position: "absolute", ...target, background: "#ff0000" }),
+ ],
+ shots: [{ at: 0, target, zoom: 2 }],
+ smear: false,
+ length: 90,
+ });
+ const settled = camera.cues.shots[0]?.settled ?? 0;
+ expect(settled).toBeLessThan(60);
+ const n = settled + 10;
+ expect(camera.cameraAt(n).zoom).toBeCloseTo(2, 1);
+ const [sx, sy] = camera.toScreen([target.x + 20, target.y + 20], n);
+ const img = await frame(comp(camera, "#000000"), n);
+ const hit = getPixel(img, sx, sy);
+ expect(hit.r).toBeGreaterThan(240);
+ // Zoomed 2×: the square is ~80 px wide on screen.
+ expect(getPixel(img, sx + 34, sy).r).toBeGreaterThan(200);
+ expect(getPixel(img, sx + 46, sy).r).toBeLessThan(40);
+ });
+});
diff --git a/packages/framefields/src/components/m2.render.test.ts b/packages/framefields/src/components/m2.render.test.ts
new file mode 100644
index 00000000..3f1085bc
--- /dev/null
+++ b/packages/framefields/src/components/m2.render.test.ts
@@ -0,0 +1,136 @@
+import { beforeAll, describe, expect, it } from "vitest";
+import { FontManager } from "../fonts/index.js";
+import { Composition, Layer, themes } from "../index.js";
+import { computeMse, decodePngPixels, getPixel } from "../test-utils/pixels.js";
+import { Annotate, Counter, TextReveal } from "./index.js";
+
+/**
+ * Render tests for the M2 components (spec §7.4–7.6): reveals end on exactly
+ * the static text, frames don't depend on render order, marks land where the
+ * text is.
+ */
+const W = 960;
+const H = 320;
+
+beforeAll(async () => {
+ await FontManager.register("assets/fonts/Inter.ttf");
+});
+
+function comp(
+ nodes: Parameters<Composition["add"]>[0],
+ background = "#0d0e11",
+) {
+ const c = new Composition({
+ width: W,
+ height: H,
+ fps: 30,
+ durationMs: 6000,
+ backgroundColor: background,
+ });
+ c.add(nodes);
+ return c;
+}
+const frame = async (c: Composition, n: number) =>
+ decodePngPixels(await c.renderFrame({ frame: n }));
+
+describe("TextReveal (render)", () => {
+ const text = "Ship it faster";
+ const placed = { x: 40, y: 100, fontSize: 80 };
+ const reference = () =>
+ Layer.text(text, {
+ position: "absolute",
+ ...placed,
+ fontFamily: "Inter",
+ fill: themes.graphite.color.ink,
+ align: "start",
+ });
+
+ for (const style of [
+ "rise",
+ "blur",
+ "slam",
+ "scramble",
+ "type",
+ "wipe",
+ "flip",
+ "stream",
+ ] as const) {
+ it(`${style} ends on exactly the static text`, async () => {
+ const node = TextReveal({ text, style, caret: false, ...placed });
+ const end = (node.cues.revealed[0]?.frame ?? 0) + 2;
+ const got = await frame(comp(node), end);
+ const want = await frame(comp(reference()), end);
+ expect(computeMse(got.pixels, want.pixels)).toBeLessThan(0.05);
+ });
+ }
+
+ it("is not there before its units start", async () => {
+ const node = TextReveal({ text, style: "rise", ...placed, at: 10 });
+ const img = await frame(comp(node), 5);
+ const empty = await frame(comp([]), 5);
+ expect(computeMse(img.pixels, empty.pixels)).toBe(0);
+ });
+
+ it("renders the same frame in any order (scramble)", async () => {
+ const build = () =>
+ comp(TextReveal({ text, style: "scramble", seed: 4, ...placed }));
+ const frames = [3, 9, 15];
+ const forward = await Promise.all(frames.map((f) => frame(build(), f)));
+ const c = build();
+ const backward: Awaited<ReturnType<typeof frame>>[] = [];
+ for (const f of [...frames].reverse()) backward.unshift(await frame(c, f));
+ forward.forEach((img, i) => {
+ expect(computeMse(img.pixels, (backward[i] as typeof img).pixels)).toBe(
+ 0,
+ );
+ });
+ });
+});
+
+describe("Counter (render)", () => {
+ it("holds still once settled", async () => {
+ const node = Counter({ to: 48210, x: 40, y: 60, fontSize: 120 });
+ const settled = node.cues.settled[0]?.frame ?? 0;
+ const c = comp(node);
+ const a = await frame(c, settled + 1);
+ const b = await frame(c, settled + 30);
+ expect(computeMse(a.pixels, b.pixels)).toBe(0);
+ // Digits are drawn (bright ink in the number's band).
+ let ink = 0;
+ for (let x = 40; x < 500; x += 3) if (getPixel(a, x, 130).r > 180) ink++;
+ expect(ink).toBeGreaterThan(5);
+ });
+});
+
+describe("Annotate (render)", () => {
+ it("underlines each line of a wrapped phrase", async () => {
+ const head = Layer.text("mark these words", {
+ position: "absolute",
+ x: 40,
+ y: 40,
+ width: 380,
+ fontSize: 64,
+ fontFamily: "Inter",
+ fill: "#1a1814",
+ });
+ const mark = Annotate({
+ target: { text: head, match: "these words" },
+ color: "#ff0000",
+ hand: false,
+ });
+ const lines = mark.cues.drawn[0]?.frame ?? 0;
+ const img = await frame(comp([head, mark], "#ffffff"), lines + 2);
+ const redRows = new Set<number>();
+ for (let y = 40; y < 260; y++)
+ for (let x = 40; x < 420; x += 4) {
+ const p = getPixel(img, x, y);
+ if (p.r > 200 && p.g < 90 && p.b < 90) redRows.add(Math.round(y / 20));
+ }
+ // Two separate bands of red: one under each line.
+ const bands = [...redRows].sort((a, b) => a - b);
+ expect(bands.length).toBeGreaterThanOrEqual(2);
+ expect(
+ (bands[bands.length - 1] as number) - (bands[0] as number),
+ ).toBeGreaterThanOrEqual(2);
+ });
+});
diff --git a/packages/framefields/src/index.ts b/packages/framefields/src/index.ts
index a69eab34..d19bb783 100644
--- a/packages/framefields/src/index.ts
+++ b/packages/framefields/src/index.ts
@@ -3397,6 +3397,29 @@ export {
themes,
} from "@framefields/components";
export {
+ Annotate,
+ type AnnotateCues,
+ AppFrame,
+ type AppFrameApi,
+ type AppFrameCues,
+ type AppFrameKind,
bindComponent,
type ComponentNode,
+ Counter,
+ type CounterCues,
+ type CounterFormat,
+ CURSOR_STYLES,
+ type CursorStyle,
+ FocusZoom,
+ type FocusZoomApi,
+ type FocusZoomCues,
+ type Followable,
+ MousePointer,
+ type MousePointerApi,
+ type MousePointerCues,
+ type RevealStyle,
+ TextReveal,
+ type TextRevealApi,
+ type TextRevealCues,
+ type Waypoint,
} from "./components/index.js";
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a9a4ef0b..498e06f9 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -451,6 +451,31 @@ importers:
specifier: ^5.8.3
version: 5.9.3
+ examples/30_product_demo:
+ dependencies:
+ framefields:
+ specifier: workspace:*
+ version: link:../../packages/framefields
+ devDependencies:
+ '@framefields/tsconfig':
+ specifier: workspace:*
+ version: link:../../packages/tsconfig
+ '@types/node':
+ specifier: ^24.1.0
+ version: 24.10.14
+ sharp:
+ specifier: ^0.35.4
+ version: 0.35.5(@types/[email protected])
+ 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:
'@framefields/core':