Skip to content

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

feat(examples): add 32_relay product film

okanasl0474d076d027
diff --git a/examples/32_relay/.gitignore b/examples/32_relay/.gitignore
new file mode 100644
index 00000000..3fc482b6
--- /dev/null
+++ b/examples/32_relay/.gitignore
@@ -0,0 +1,2 @@
+# UI SFX sounds, fetched by `pnpm assets` (src/sfx.ts pins them).
+assets/sfx/
diff --git a/examples/32_relay/assets/audio.json b/examples/32_relay/assets/audio.json
new file mode 100644
index 00000000..fee00bdd
--- /dev/null
+++ b/examples/32_relay/assets/audio.json
@@ -0,0 +1,53 @@
+{
+ "voice": {
+ "ask": {
+ "text": "A client asks a simple question.",
+ "prompt": "Warm, clear and conversational, at an easy natural pace with no long pauses, like a founder showing a friend their product. Read the following: 'A client asks a simple question.'",
+ "heard": "A client asks a simple question",
+ "seconds": 2.179
+ },
+ "inbox": {
+ "text": "In Relay, it becomes a task in one click.",
+ "prompt": "Warm, clear and conversational, at an easy natural pace with no long pauses, like a founder showing a friend their product. Read the following: 'In Relay, it becomes a task in one click.'",
+ "heard": "In Relay, it becomes a task in one click",
+ "seconds": 3.001542
+ },
+ "owner": {
+ "text": "An owner.",
+ "prompt": "Warm, clear and conversational, at an easy natural pace with no long pauses, like a founder showing a friend their product. Read the following: 'An owner.'",
+ "heard": "An owner",
+ "seconds": 0.76
+ },
+ "deadline": {
+ "text": "A deadline.",
+ "prompt": "Warm, clear and conversational, at an easy natural pace with no long pauses, like a founder showing a friend their product. Read the following: 'A deadline.'",
+ "heard": "A deadline",
+ "seconds": 1
+ },
+ "step": {
+ "text": "And a clear next step.",
+ "prompt": "Warm, clear and conversational, at an easy natural pace with no long pauses, like a founder showing a friend their product. Read the following: 'And a clear next step.'",
+ "heard": "And a clear next step",
+ "seconds": 1.495
+ },
+ "board": {
+ "text": "Maya sees it on the board, ready to start.",
+ "prompt": "Warm, clear and conversational, at an easy natural pace with no long pauses, like a founder showing a friend their product. Read the following: 'Maya sees it on the board, ready to start.'",
+ "heard": "Maya sees it on the board ready to start",
+ "seconds": 3.03275
+ },
+ "close": {
+ "text": "Relay. Keep client work moving.",
+ "prompt": "Warm, clear and conversational, at an easy natural pace with no long pauses, like a founder showing a friend their product. Read the following: 'Relay. Keep client work moving.'",
+ "heard": "Relay. Keep client work moving.",
+ "seconds": 3.14
+ }
+ },
+ "music": {
+ "seconds": 26.81
+ },
+ "click": {
+ "seconds": 0.12,
+ "brightness": 0.388
+ }
+}
diff --git a/examples/32_relay/framefields.json b/examples/32_relay/framefields.json
new file mode 100644
index 00000000..f76e2d00
--- /dev/null
+++ b/examples/32_relay/framefields.json
@@ -0,0 +1,3 @@
+{
+ "components": "src/components"
+}
diff --git a/examples/32_relay/package.json b/examples/32_relay/package.json
new file mode 100644
index 00000000..7dcc485e
--- /dev/null
+++ b/examples/32_relay/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "@framefields/example-32-relay",
+ "version": "2.9.3",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "assets": "tsx src/fetch-sfx.ts",
+ "audio": "tsx src/generate-audio.ts",
+ "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",
+ "tsx": "^4.20.3",
+ "typescript": "^5.8.3",
+ "vitest": "^4.1.5"
+ }
+}
diff --git a/examples/32_relay/src/audio.ts b/examples/32_relay/src/audio.ts
new file mode 100644
index 00000000..9acad2c1
--- /dev/null
+++ b/examples/32_relay/src/audio.ts
@@ -0,0 +1,95 @@
+/**
+ * The film's generated sound, all from the framefields AI gateway with Seed
+ * Audio 1.0: a narrator, a music bed and the mouse click. `pnpm audio` makes
+ * the files (media stays out of git) and records what it measured in
+ * assets/audio.json, which is committed so the film can be timed without them.
+ */
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { ASSETS } from "./theme.js";
+
+export const AUDIO_MODEL = "seed-audio/1.0";
+export const TRANSCRIBER = "elevenlabs/speech-to-text/scribe-v2";
+
+/** Read most naturally of the presets tried: accurate, about 2.9 words a second. */
+export const VOICE = "cedric_en_zh";
+export const DIRECTION =
+ "Warm, clear and conversational, at an easy natural pace with no long pauses, like a founder showing a friend their product.";
+export const voicePrompt = (text: string) =>
+ `${DIRECTION} Read the following: '${text}'`;
+
+/** The narration, in the order it is heard. */
+export const LINES = {
+ ask: "A client asks a simple question.",
+ inbox: "In Relay, it becomes a task in one click.",
+ owner: "An owner.",
+ deadline: "A deadline.",
+ step: "And a clear next step.",
+ board: "Maya sees it on the board, ready to start.",
+ close: "Relay. Keep client work moving.",
+} as const;
+
+export type LineId = keyof typeof LINES;
+export const LINE_IDS = Object.keys(LINES) as LineId[];
+
+/**
+ * Music, laid out on the film's sections. The gateway turns away Seed Audio
+ * prompts with nothing to say (every music-only prompt fails its content
+ * check), so the music is a scene that ends on one spoken word, `MUSIC_CUE`,
+ * and is cut off just before it.
+ */
+export const MUSIC_SECONDS = 26;
+export const MUSIC_CUE = "Relay.";
+export const MUSIC_PROMPT = `A bright, quiet design studio in the morning.
+Music: a calm, optimistic, minimal product film underscore at 96 BPM in D major. Warm felt piano, a soft plucked synth arpeggio, round sub bass and light brushed percussion.
+Total duration: 0:30.
+[0:00-0:03] Music only: the piano motif alone.
+[0:03-0:14] Music only: a gentle pulse enters with the plucked arpeggio and brushed percussion.
+[0:14-0:20] Music only: it lifts as the sub bass and a warm pad join.
+[0:20-0:${MUSIC_SECONDS}] Music only: it resolves on one sustained final chord that rings out softly.
+[0:27-0:30] A calm male narrator says: "${MUSIC_CUE}"`;
+
+export const CLICK_PROMPT = `Generate sound effects only. No voice, no music.
+One single crisp click of a computer mouse button, recorded close and dry in a quiet room, then silence.`;
+
+export interface AudioManifest {
+ voice: Record<
+ LineId,
+ {
+ text: string;
+ /** What Seed Audio was asked, so a changed direction is read again. */
+ prompt: string;
+ /** What the transcriber heard, which must match `text` word for word. */
+ heard: string;
+ /** Trimmed to the speech: 60 ms before the first word, 300 ms after the last. */
+ seconds: number;
+ }
+ >;
+ /** Everything before the spoken cue. */
+ music: { seconds: number };
+ click: {
+ seconds: number;
+ /** Share of the click's energy above 1.5 kHz: a click is bright, a thump is not. */
+ brightness: number;
+ };
+}
+
+/** Where the first word starts in a trimmed line. */
+export const VOICE_LEAD = 0.06;
+
+export const MANIFEST = path.join(ASSETS, "audio.json");
+export const voicePath = (id: LineId) =>
+ path.join(ASSETS, "voice", `${id}.wav`);
+export const MUSIC_PATH = path.join(ASSETS, "music.wav");
+export const CLICK_PATH = path.join(ASSETS, "sfx", "click.wav");
+
+export function readManifest(): AudioManifest {
+ return JSON.parse(readFileSync(MANIFEST, "utf8")) as AudioManifest;
+}
+
+/** Generated files not on disk yet. */
+export function missingAudio(): string[] {
+ return [...LINE_IDS.map(voicePath), MUSIC_PATH, CLICK_PATH]
+ .filter((file) => !existsSync(file))
+ .map((file) => path.relative(ASSETS, file));
+}
diff --git a/examples/32_relay/src/components/app-frame/index.ts b/examples/32_relay/src/components/app-frame/index.ts
new file mode 100644
index 00000000..2915fb1b
--- /dev/null
+++ b/examples/32_relay/src/components/app-frame/index.ts
@@ -0,0 +1,606 @@
+/**
+ * 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";
+import {
+ type Animatable,
+ bindComponent,
+ defineComponent,
+ type Vec2,
+ z,
+} from "framefields/components";
+
+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 && theme.mode === "dark");
+ 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: theme.weight.medium,
+ 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: props.tilt
+ ? [
+ // The presentation angle: a perspective box round the whole frame.
+ host.box({
+ id: ctx.partId("tilt"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width,
+ height,
+ perspective: 1800 * s,
+ rotateX: props.tilt.rotateX,
+ rotateY: props.tilt.rotateY,
+ children: build(width, height).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: ctx.theme.weight.medium,
+ });
+ 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: ctx.theme.weight.medium,
+ 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;
+}
+
+/**
+ * Window chrome around any content — desktop window, browser with a typed URL,
+ * terminal, or bare frame — and the coordinate system for pointing into it.
+ */
+export const AppFrame = /* @__PURE__ */ bindComponent(appFrame);
diff --git a/examples/32_relay/src/components/focus-zoom/index.ts b/examples/32_relay/src/components/focus-zoom/index.ts
new file mode 100644
index 00000000..a805394c
--- /dev/null
+++ b/examples/32_relay/src/components/focus-zoom/index.ts
@@ -0,0 +1,275 @@
+/**
+ * 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";
+import {
+ bakeSamples,
+ bindComponent,
+ boundsOf,
+ defineComponent,
+ resolveTarget,
+ targetPoint,
+ targetSchema,
+ type Vec2,
+ z,
+} from "framefields/components";
+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, fps } = ctx;
+ const W = ctx.requested.width ?? ctx.canvas.width;
+ const H = ctx.requested.height ?? ctx.canvas.height;
+ // 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 };
+ },
+ }),
+ };
+ },
+});
+
+/**
+ * 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.
+ */
+export const FocusZoom = /* @__PURE__ */ bindComponent(focusZoom);
diff --git a/examples/32_relay/src/components/focus-zoom/plan.ts b/examples/32_relay/src/components/focus-zoom/plan.ts
new file mode 100644
index 00000000..aa2863e6
--- /dev/null
+++ b/examples/32_relay/src/components/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 "framefields/components";
+
+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/examples/32_relay/src/components/mouse-pointer/glyphs.ts b/examples/32_relay/src/components/mouse-pointer/glyphs.ts
new file mode 100644
index 00000000..5013bfe2
--- /dev/null
+++ b/examples/32_relay/src/components/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 "framefields/components";
+
+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/examples/32_relay/src/components/mouse-pointer/index.ts b/examples/32_relay/src/components/mouse-pointer/index.ts
new file mode 100644
index 00000000..bbb9f80e
--- /dev/null
+++ b/examples/32_relay/src/components/mouse-pointer/index.ts
@@ -0,0 +1,797 @@
+/**
+ * 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";
+import {
+ type Animatable,
+ bakeSamples,
+ bindComponent,
+ contrastRatio,
+ defineComponent,
+ resolveTarget,
+ type Target,
+ targetPoint,
+ targetSchema,
+ transformPathData,
+ type Vec2,
+ z,
+} from "framefields/components";
+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: the composition `canvas`. */
+ area: z
+ .object({ width: z.number().positive(), height: z.number().positive() })
+ .optional(),
+ }),
+ 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 ?? ctx.canvas;
+
+ 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: theme.weight.semibold,
+ });
+ 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: theme.weight.semibold,
+ 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)];
+}
+
+/**
+ * An animated pointer that travels between targets, clicks, drags and changes
+ * shape, reporting every click as a cue.
+ */
+export const MousePointer = /* @__PURE__ */ bindComponent(mousePointer);
diff --git a/examples/32_relay/src/components/mouse-pointer/plan.ts b/examples/32_relay/src/components/mouse-pointer/plan.ts
new file mode 100644
index 00000000..b4d051ef
--- /dev/null
+++ b/examples/32_relay/src/components/mouse-pointer/plan.ts
@@ -0,0 +1,502 @@
+/**
+ * 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 { dist, evaluateEase, hashRng, type Vec2 } from "framefields/components";
+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/examples/32_relay/src/fetch-sfx.ts b/examples/32_relay/src/fetch-sfx.ts
new file mode 100644
index 00000000..1a063e83
--- /dev/null
+++ b/examples/32_relay/src/fetch-sfx.ts
@@ -0,0 +1,38 @@
+/**
+ * pnpm assets → assets/sfx/{panel,complete}.mp3
+ *
+ * Downloads the pinned UI SFX sounds listed in sfx.ts and checks each one's
+ * SHA-256. Idempotent: a file already on disk with the right hash is kept.
+ */
+import { createHash } from "node:crypto";
+import fs from "node:fs/promises";
+import path from "node:path";
+import { SFX, type SfxName, sfxPath, sfxUrl } from "./sfx.js";
+
+const sha256 = (data: Uint8Array) =>
+ createHash("sha256").update(data).digest("hex");
+
+async function fetchSound(name: SfxName): Promise<void> {
+ const file = sfxPath(name);
+ const { sha256: expected } = SFX[name];
+ const existing = await fs.readFile(file).catch(() => null);
+ if (existing && sha256(existing) === expected) {
+ console.log(`kept ${path.basename(file)}`);
+ return;
+ }
+ const url = sfxUrl(name);
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
+ const data = new Uint8Array(await res.arrayBuffer());
+ const actual = sha256(data);
+ if (actual !== expected)
+ throw new Error(
+ `${url}: SHA-256 ${actual}, expected ${expected}. Not written.`,
+ );
+ await fs.mkdir(path.dirname(file), { recursive: true });
+ await fs.writeFile(file, data);
+ console.log(`wrote ${path.basename(file)} (${SFX[name].source})`);
+}
+
+await Promise.all((Object.keys(SFX) as SfxName[]).map(fetchSound));
+process.exit(0);
diff --git a/examples/32_relay/src/film.test.ts b/examples/32_relay/src/film.test.ts
new file mode 100644
index 00000000..6399d797
--- /dev/null
+++ b/examples/32_relay/src/film.test.ts
@@ -0,0 +1,57 @@
+import { CompositorProgramSchema } from "framefields";
+import { describe, expect, it } from "vitest";
+import { buildRelay } from "./film.js";
+import { cardLands, checklistItemAt } from "./ui/timeline.js";
+
+describe("relay", () => {
+ it("builds a valid, lint-clean 25-second program", async () => {
+ const { film } = await buildRelay();
+ 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).toBe(25_000);
+ }, 60_000);
+
+ it("holds the camera still through every click", async () => {
+ const { camera, clicks } = await buildRelay();
+ expect(clicks).toHaveLength(8);
+ for (const frame of clicks) {
+ // From just before the press until the button is back up.
+ const before = camera.cameraAt(frame - 7);
+ const after = camera.cameraAt(frame + 7);
+ expect(after.zoom, `zoom at click ${frame}`).toBeCloseTo(before.zoom, 3);
+ expect(
+ Math.hypot(
+ after.center[0] - before.center[0],
+ after.center[1] - before.center[1],
+ ),
+ `pan at click ${frame}`,
+ ).toBeLessThan(0.5);
+ }
+ }, 60_000);
+
+ it("speaks each line on its beat, one at a time, inside the film", async () => {
+ const { lines, timeline: t, film } = await buildRelay();
+ const end = Math.round(((film.durationMs ?? 0) / 1000) * 30);
+ lines.forEach((line, i) => {
+ const next = lines[i + 1];
+ if (next)
+ expect(
+ next.start - line.end,
+ `${line.id} → ${next.id}`,
+ ).toBeGreaterThanOrEqual(6);
+ else expect(line.end, line.id).toBeLessThanOrEqual(end - 15);
+ });
+ const at = Object.fromEntries(lines.map((l) => [l.id, l]));
+ // The three promises are said as the modal delivers them…
+ expect(at.owner?.start).toBe(t.maya.at + 2);
+ expect(at.deadline?.start).toBe(t.friday.at + 2);
+ expect(at.step?.start).toBe(checklistItemAt(t, 0));
+ // …and the board line once the card has landed, done before it leaves.
+ expect(at.board?.start).toBeGreaterThan(cardLands(t));
+ expect(at.board?.end).toBeLessThanOrEqual(t.sceneOut);
+ }, 60_000);
+});
diff --git a/examples/32_relay/src/film.ts b/examples/32_relay/src/film.ts
new file mode 100644
index 00000000..4d663a0b
--- /dev/null
+++ b/examples/32_relay/src/film.ts
@@ -0,0 +1,455 @@
+/**
+ * Relay, a 25-second product film: a client asks "Can we ship the homepage
+ * update Friday?", and one pointer turns the message into an assigned,
+ * scheduled task that lands on the project board.
+ *
+ * 0–3 s the request, under "From request to ready."; it flies into the inbox
+ * 3–8 s select the message, Create task: the task modal opens
+ * 8–14 s Maya, Friday, a checklist: "An owner. A deadline. A clear next step."
+ * 14–20 s back out to the board: the modal shrinks into its card in Ready
+ * 20–25 s the card becomes the mark: Relay. Keep client work moving.
+ *
+ * AppFrame is the window, MousePointer the hand, FocusZoom the camera (added
+ * with `framefields add app-frame mouse-pointer focus-zoom`). The UI reacts
+ * to the pointer's cues, so moving a beat re-times everything after it, the
+ * narration included. Voice, music and click are generated (audio.ts).
+ */
+import { Composition, FontManager, Layer, LayerAnimation } from "framefields";
+import {
+ CLICK_PATH,
+ LINE_IDS,
+ type LineId,
+ MUSIC_PATH,
+ readManifest,
+ voicePath,
+} from "./audio.js";
+import { AppFrame } from "./components/app-frame/index.js";
+import { FocusZoom } from "./components/focus-zoom/index.js";
+import {
+ MousePointer,
+ type Waypoint,
+} from "./components/mouse-pointer/index.js";
+import { SFX, type SfxName, sfxPath } from "./sfx.js";
+import {
+ ACCENT,
+ APP,
+ FONTS,
+ FPS,
+ FRAME,
+ H,
+ SANS,
+ SHADOW,
+ sec,
+ W,
+ WALL,
+ WALL_LIGHT,
+} from "./theme.js";
+import { captions, endCard, handover, opening } from "./titles.js";
+import { relayApp } from "./ui/app.js";
+import { DUE_OPTIONS, FRIDAY, TEAM } from "./ui/data.js";
+import { CARD_RADIUS } from "./ui/handoffs.js";
+import { centre, type Rect } from "./ui/kit.js";
+import {
+ ADD_CHECKLIST,
+ ASSIGNEE_FIELD,
+ COLUMN_W,
+ CREATE_BUTTON,
+ cardSlot,
+ columnX,
+ DUE_FIELD,
+ inModal,
+ LIST_TOP,
+ LIST_X,
+ MODAL,
+ menuUnder,
+ optionIn,
+ PANE_W,
+ PANE_X,
+ READY,
+ REQUEST_ROW,
+ SAVE_BUTTON,
+} from "./ui/layout.js";
+import {
+ type Click,
+ cardLands,
+ checklistItemAt,
+ modalIn,
+ type Timeline,
+} from "./ui/timeline.js";
+
+/** The storyboard's fixed marks. */
+const WINDOW_IN = sec(2.1);
+const FLY = sec(2.6);
+const LANDED = sec(3.45);
+const POINTER_IN = sec(3.2);
+const END_CARD = sec(20);
+/** The card leaves the board for the end card. */
+const SCENE_OUT = END_CARD - sec(0.8);
+const END = sec(25);
+
+/**
+ * MousePointer's click, at 30 fps: it settles 4 frames after arriving,
+ * presses for 3 (the click lands) and is fully released 7 frames later.
+ */
+const CLICK_LANDS = 7;
+const RELEASED = 14;
+
+interface Beat {
+ to: [number, number];
+ /** Composition frame the click lands (or the pointer arrives, for a rest). */
+ at: number;
+ /** Frames on the way from the previous beat (the first comes in from the edge). */
+ travel?: number;
+ click?: boolean;
+ /** Frames to rest after the last beat. */
+ rest?: number;
+}
+
+/** Waypoints that leave each beat in time to make the next one. */
+function perform(enter: number, beats: Beat[]): Waypoint[] {
+ const arrival = (b: Beat) => b.at - (b.click ? CLICK_LANDS : 0);
+ return beats.map((b, i) => {
+ const next = beats[i + 1];
+ const free = arrival(b) + (b.click ? RELEASED - CLICK_LANDS : 0);
+ const dwell = next
+ ? arrival(next) - (next.travel ?? 0) - free
+ : (b.rest ?? 0);
+ if (dwell < 0)
+ throw new Error(
+ `Beat ${i + 1} cannot leave in time for beat ${i + 2}: ${-dwell} frames short.`,
+ );
+ return {
+ to: b.to,
+ at: arrival(b) - enter,
+ dwell,
+ ...(b.click && { click: true }),
+ };
+ });
+}
+
+const clickAt = (
+ cues: {
+ presses: ReadonlyArray<{ frame: number }>;
+ clicks: ReadonlyArray<{ frame: number }>;
+ releases: ReadonlyArray<{ frame: number }>;
+ },
+ i: number,
+): Click => ({
+ down: cues.presses[i]?.frame ?? 0,
+ at: cues.clicks[i]?.frame ?? 0,
+ up: cues.releases[i]?.frame ?? 0,
+});
+
+function sound(file: string, frame: number, seconds: number, volume: number) {
+ return Layer.audio(file, {
+ startFrame: frame,
+ durationFrames: Math.ceil(seconds * FPS) + 2,
+ volume,
+ });
+}
+
+const cue = (name: SfxName, frame: number, volume: number) =>
+ sound(sfxPath(name), frame, SFX[name].seconds, volume);
+
+/** Where each line of narration starts: on the beat it describes. */
+function lineStarts(t: Timeline): Record<LineId, number> {
+ return {
+ ask: sec(0.5),
+ inbox: LANDED - 2,
+ owner: t.maya.at + 2,
+ deadline: t.friday.at + 2,
+ step: checklistItemAt(t, 0),
+ board: cardLands(t) + 4,
+ close: END_CARD + sec(0.7),
+ };
+}
+
+export interface Line {
+ id: LineId;
+ start: number;
+ end: number;
+}
+
+/** Music level between lines, and under them. */
+const BED = 0.5;
+const DUCKED = 0.22;
+/** Lines closer than this keep the music down between them. */
+const BRIDGE = 18;
+
+/** The music's volume: down under every line, and out by the end. */
+function ducking(lines: Line[]): Array<[number, number, string?]> {
+ const keys: Array<[number, number, string?]> = [
+ [0, 0],
+ [6, BED, "power2.out"],
+ ];
+ let i = 0;
+ while (i < lines.length) {
+ const start = lines[i]?.start ?? 0;
+ let end = lines[i]?.end ?? 0;
+ while (i + 1 < lines.length && (lines[i + 1]?.start ?? 0) - end < BRIDGE)
+ end = lines[++i]?.end ?? end;
+ keys.push(
+ [start - 6, BED, "hold"],
+ [start, DUCKED, "power2.out"],
+ [end, DUCKED, "hold"],
+ [end + 12, BED, "power2.inOut"],
+ );
+ i++;
+ }
+ keys.push([END - sec(1.6), BED, "hold"], [END, 0, "power2.in"]);
+ return keys;
+}
+
+export interface Relay {
+ film: Composition;
+ timeline: Timeline;
+ /** The camera, for asking where it looks at a frame. */
+ camera: ReturnType<typeof FocusZoom>;
+ /** Every click, in composition frames. */
+ clicks: number[];
+ /** The narration, in composition frames. */
+ lines: Line[];
+}
+
+export async function buildRelay(): Promise<Relay> {
+ await FontManager.register({ family: SANS, source: `${FONTS}Inter.ttf` });
+ const theme = { color: { bg: WALL, accent: ACCENT, shadow: SHADOW } };
+
+ const frame = AppFrame({
+ id: "relay-window",
+ kind: "window",
+ ...FRAME,
+ appearance: "light",
+ contentBackground: APP,
+ elevation: 2,
+ theme,
+ enter: {
+ preset: "rise",
+ duration: sec(0.9),
+ delay: WINDOW_IN,
+ distance: 60,
+ },
+ });
+ // Content rects → the stage the camera films.
+ const stage = (r: Rect): Rect => {
+ const [x, y] = frame.at(r.x, r.y);
+ return { x, y, width: r.width, height: r.height };
+ };
+ const aim = (r: Rect) => frame.at(...centre(r));
+ const assignees = menuUnder(ASSIGNEE_FIELD, TEAM.length);
+ const dates = menuUnder(DUE_FIELD, DUE_OPTIONS.length);
+ const maya = inModal(optionIn(assignees, 0));
+ const friday = inModal(optionIn(dates, FRIDAY));
+ const newCard = cardSlot(READY, 0);
+
+ const targets = {
+ request: stage(REQUEST_ROW),
+ create: stage(CREATE_BUTTON),
+ assignee: stage(inModal(ASSIGNEE_FIELD)),
+ maya: stage(maya),
+ due: stage(inModal(DUE_FIELD)),
+ friday: stage(friday),
+ checklist: stage(inModal(ADD_CHECKLIST)),
+ save: stage(inModal(SAVE_BUTTON)),
+ card: stage(newCard),
+ };
+ const pointer = MousePointer({
+ id: "pointer",
+ at: POINTER_IN,
+ from: "bottom",
+ to: "right",
+ size: 32,
+ accent: ACCENT,
+ fps: FPS,
+ hoverRegions: Object.values(targets).map((target) => ({
+ target,
+ style: "hand" as const,
+ })),
+ path: perform(POINTER_IN, [
+ {
+ to: frame.at(LIST_X + 300, LIST_TOP + 52),
+ at: sec(4.25),
+ click: true,
+ },
+ { to: aim(CREATE_BUTTON), at: sec(6.2), travel: 22, click: true },
+ {
+ to: aim(inModal(ASSIGNEE_FIELD)),
+ at: sec(8.25),
+ travel: 20,
+ click: true,
+ },
+ { to: aim(maya), at: sec(9.2), travel: 12, click: true },
+ { to: aim(inModal(DUE_FIELD)), at: sec(10.45), travel: 14, click: true },
+ { to: aim(friday), at: sec(11.45), travel: 14, click: true },
+ {
+ to: aim(inModal(ADD_CHECKLIST)),
+ at: sec(13.05),
+ travel: 18,
+ click: true,
+ },
+ { to: aim(inModal(SAVE_BUTTON)), at: sec(14.3), travel: 16, click: true },
+ {
+ to: frame.at(newCard.x + 236, newCard.y + 30),
+ at: sec(16.2),
+ travel: 30,
+ rest: SCENE_OUT - sec(16.2),
+ },
+ ]),
+ });
+
+ const cues = pointer.cues;
+ const t: Timeline = {
+ windowIn: WINDOW_IN,
+ landed: LANDED,
+ select: clickAt(cues, 0),
+ create: clickAt(cues, 1),
+ assignee: clickAt(cues, 2),
+ mayaHover: (cues.arrivals[3]?.frame ?? 0) - 3,
+ maya: clickAt(cues, 3),
+ due: clickAt(cues, 4),
+ fridayHover: (cues.arrivals[5]?.frame ?? 0) - 3,
+ friday: clickAt(cues, 5),
+ checklist: clickAt(cues, 6),
+ save: clickAt(cues, 7),
+ sceneOut: SCENE_OUT,
+ };
+ frame.fill(...relayApp(t));
+
+ // The camera: in on each control while it's used, and still from the press
+ // until the control has sprung back. A move starts once the click settles.
+ const settled = (c: Click) => c.up + sec(0.2);
+ const camera = FocusZoom({
+ id: "camera",
+ content: [frame, pointer],
+ bounds: FRAME,
+ length: END_CARD,
+ fps: FPS,
+ shots: [
+ {
+ at: settled(t.select),
+ target: stage({ x: PANE_X, y: 0, width: PANE_W, height: 420 }),
+ zoom: 1.6,
+ },
+ {
+ at: modalIn(t) + 8,
+ target: stage(
+ inModal({ x: 0, y: 28, width: MODAL.width, height: 560 }),
+ ),
+ zoom: 1.7,
+ },
+ {
+ at: settled(t.friday),
+ target: stage(
+ inModal({ x: 0, y: 300, width: MODAL.width, height: 340 }),
+ ),
+ zoom: 1.7,
+ },
+ { at: settled(t.save), target: "full" },
+ {
+ at: cardLands(t) + sec(0.8),
+ target: stage({
+ x: columnX(READY) - 40,
+ y: 0,
+ width: COLUMN_W + 80,
+ height: 560,
+ }),
+ zoom: 1.6,
+ // Held until the card has handed over to the end card.
+ hold: END_CARD - (cardLands(t) + sec(0.8)),
+ },
+ ],
+ });
+ const scene = Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ children: [camera],
+ }).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 1],
+ [SCENE_OUT, 1, "hold"],
+ [SCENE_OUT + sec(0.6), 0, "power2.inOut"],
+ ]),
+ );
+ // The new card, where the camera shows it as it leaves for the end card.
+ const card = stage(newCard);
+ const [left, top] = camera.toScreen([card.x, card.y], SCENE_OUT);
+ const [right, bottom] = camera.toScreen(
+ [card.x + card.width, card.y + card.height],
+ SCENE_OUT,
+ );
+ const onScreen = {
+ x: left,
+ y: top,
+ width: right - left,
+ height: bottom - top,
+ };
+ const zoomed = camera.cameraAt(SCENE_OUT).zoom;
+
+ const comp = new Composition({
+ width: W,
+ height: H,
+ fps: FPS,
+ durationMs: (END / FPS) * 1000,
+ backgroundColor: WALL,
+ fonts: [`${FONTS}Inter.ttf`],
+ });
+ comp.add([
+ Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ background: `radial-gradient(ellipse at 50% 30%, ${WALL_LIGHT} 0%, ${WALL} 75%)`,
+ }),
+ scene,
+ ...opening(FLY, LANDED, targets.request),
+ captions(
+ ["An owner.", "A deadline.", "A clear next step."],
+ [t.maya.at + 3, t.friday.at + 3, checklistItemAt(t, 0)],
+ modalIn(t) + sec(1),
+ t.save.down,
+ ),
+ ...handover(onScreen, CARD_RADIUS * zoomed, SCENE_OUT, END_CARD),
+ endCard(END_CARD, END - END_CARD),
+ ]);
+
+ // Narration on its beats, music ducked under it, and sparse cues: a click
+ // as each press lands, the modal opening, the card landing.
+ const audio = readManifest();
+ const starts = lineStarts(t);
+ const lines = LINE_IDS.map((id) => ({
+ id,
+ start: starts[id],
+ end: starts[id] + Math.round(audio.voice[id].seconds * FPS),
+ }));
+ for (const line of lines)
+ comp.addAudio(
+ sound(voicePath(line.id), line.start, audio.voice[line.id].seconds, 1),
+ );
+ comp.addAudio(
+ Layer.audio(MUSIC_PATH, {
+ startFrame: 0,
+ durationFrames: END,
+ volume: BED,
+ }).animate(LayerAnimation.keys("volume", ducking(lines))),
+ );
+ for (const c of cues.clicks)
+ comp.addAudio(sound(CLICK_PATH, c.frame, audio.click.seconds, 0.6));
+ comp.addAudio(cue("panel", modalIn(t), 0.6));
+ comp.addAudio(cue("complete", cardLands(t), 0.8));
+ return {
+ film: comp,
+ timeline: t,
+ camera,
+ clicks: cues.clicks.map((c) => c.frame),
+ lines,
+ };
+}
+
+export async function buildFilm(): Promise<Composition> {
+ return (await buildRelay()).film;
+}
diff --git a/examples/32_relay/src/generate-audio.ts b/examples/32_relay/src/generate-audio.ts
new file mode 100644
index 00000000..e727c653
--- /dev/null
+++ b/examples/32_relay/src/generate-audio.ts
@@ -0,0 +1,367 @@
+/**
+ * pnpm audio → assets/voice/<line>.wav, assets/music.wav, assets/sfx/click.wav,
+ * and what was measured in assets/audio.json
+ * pnpm audio cost → print the estimate, no calls
+ *
+ * Seed Audio 1.0 reads each line of the narration, plays the music bed and
+ * makes the click. Scribe v2 checks that every line was read as written and
+ * finds its first and last word, so each line is trimmed to its speech and
+ * the film can start it exactly where it belongs. Idempotent: delete a file
+ * to make it again. Raw takes are kept in assets/takes/.
+ */
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync } from "node:fs";
+import fs from "node:fs/promises";
+import path from "node:path";
+import { ai } from "framefields";
+import {
+ AUDIO_MODEL,
+ type AudioManifest,
+ CLICK_PATH,
+ CLICK_PROMPT,
+ LINE_IDS,
+ LINES,
+ type LineId,
+ MANIFEST,
+ MUSIC_CUE,
+ MUSIC_PATH,
+ MUSIC_PROMPT,
+ MUSIC_SECONDS,
+ TRANSCRIBER,
+ VOICE,
+ VOICE_LEAD,
+ voicePath,
+ voicePrompt,
+} from "./audio.js";
+import { ASSETS } from "./theme.js";
+
+/** USD per minute of audio, from the gateway's published rates (November 2026). */
+const RATE = { [AUDIO_MODEL]: 0.234375, [TRANSCRIBER]: 0.01 };
+const SAMPLE_RATE = 48000;
+const MAX_TAKES = 4;
+const TAKES = path.join(ASSETS, "takes");
+/** Kept after a line's last word, faded over its second half. */
+const VOICE_TAIL = 0.3;
+const CLICK_SECONDS = 0.12;
+/** Longest silence allowed between two words of a sentence; a full stop may hold twice as long. */
+const MAX_PAUSE = 0.45;
+/** A click puts at least this share of its energy above 1.5 kHz. */
+const MIN_BRIGHTNESS = 0.25;
+
+/** A take's file, named by what was asked for, so a changed prompt is made afresh. */
+const takePath = (kind: string, input: Record<string, unknown>, take: number) =>
+ path.join(
+ TAKES,
+ `${kind}-${createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 8)}-${take}.wav`,
+ );
+
+let spent = 0;
+const bill = (model: keyof typeof RATE, seconds: number) => {
+ spent += (RATE[model] * seconds) / 60;
+};
+
+async function generate(
+ input: Record<string, unknown>,
+ dest: string,
+): Promise<void> {
+ const { data } = await ai.subscribe<{ audio: { url: string } }>(AUDIO_MODEL, {
+ input: { output_format: "wav", sample_rate: SAMPLE_RATE, ...input },
+ });
+ const res = await fetch(data.audio.url);
+ if (!res.ok) throw new Error(`GET ${data.audio.url} → ${res.status}`);
+ await fs.mkdir(path.dirname(dest), { recursive: true });
+ await fs.writeFile(dest, Buffer.from(await res.arrayBuffer()));
+ bill(AUDIO_MODEL, duration(dest));
+}
+
+interface Word {
+ text: string;
+ start: number;
+ end: number;
+}
+
+async function transcribe(file: string): Promise<Word[]> {
+ const audio = new Blob([await fs.readFile(file)], { type: "audio/wav" });
+ const { data } = await ai.subscribe<{
+ words: Array<Word & { type: string }>;
+ }>(TRANSCRIBER, {
+ input: {
+ audio_url: audio,
+ language_code: "eng",
+ keyterms: ["Relay", "Maya"],
+ tag_audio_events: false,
+ },
+ });
+ bill(TRANSCRIBER, duration(file));
+ return data.words
+ .filter((w) => w.type === "word")
+ .map(({ text, start, end }) => ({ text: text.trim(), start, end }));
+}
+
+function duration(file: string): number {
+ const out = execFileSync("ffprobe", [
+ "-v",
+ "error",
+ "-show_entries",
+ "format=duration",
+ "-of",
+ "csv=p=0",
+ file,
+ ]);
+ return Number(out.toString().trim());
+}
+
+/** Mono float samples at the film's rate. */
+function decode(file: string): Float32Array {
+ const raw = execFileSync(
+ "ffmpeg",
+ [
+ "-v",
+ "error",
+ "-i",
+ file,
+ "-ac",
+ "1",
+ "-ar",
+ `${SAMPLE_RATE}`,
+ "-f",
+ "f32le",
+ "pipe:1",
+ ],
+ { maxBuffer: 1 << 28 },
+ );
+ return new Float32Array(raw.buffer, raw.byteOffset, raw.byteLength / 4);
+}
+
+/** Cuts `from`–`to` seconds of `src` through `filters` into a 48 kHz mono WAV. */
+function cut(
+ src: string,
+ dest: string,
+ from: number,
+ to: number,
+ filters: string[],
+) {
+ mkdirSync(path.dirname(dest), { recursive: true });
+ execFileSync("ffmpeg", [
+ "-v",
+ "error",
+ "-y",
+ "-ss",
+ from.toFixed(3),
+ "-to",
+ to.toFixed(3),
+ "-i",
+ src,
+ "-af",
+ filters.join(","),
+ "-ar",
+ `${SAMPLE_RATE}`,
+ "-ac",
+ "1",
+ dest,
+ ]);
+}
+
+/** The longest gap between words, counting a gap after a full stop at half its length. */
+function longestPause(heard: Word[]): number {
+ let longest = 0;
+ for (let i = 1; i < heard.length; i++) {
+ const before = heard[i - 1];
+ const word = heard[i];
+ if (!before || !word) continue;
+ const gap = word.start - before.end;
+ longest = Math.max(longest, before.text.endsWith(".") ? gap / 2 : gap);
+ }
+ return longest;
+}
+
+const words = (s: string) =>
+ s
+ .toLowerCase()
+ .replace(/[^a-z' ]/g, " ")
+ .split(/\s+/)
+ .filter(Boolean)
+ .join(" ");
+
+async function voiceLine(id: LineId): Promise<AudioManifest["voice"][LineId]> {
+ const text = LINES[id];
+ for (let take = 1; take <= MAX_TAKES; take++) {
+ const input = { prompt: voicePrompt(text), voice: VOICE };
+ const raw = takePath(`voice-${id}`, input, take);
+ if (!existsSync(raw)) await generate(input, raw);
+ const heard = await transcribe(raw);
+ const said = heard.map((w) => w.text).join(" ");
+ const first = heard[0];
+ const last = heard.at(-1);
+ // Same words, no question where the script states something, no long pauses.
+ const asks = said.includes("?") && !text.includes("?");
+ const pause = longestPause(heard);
+ if (
+ !first ||
+ !last ||
+ words(said) !== words(text) ||
+ asks ||
+ pause > MAX_PAUSE
+ ) {
+ console.log(
+ `voice ${id} take ${take} heard "${said}" (longest pause ${pause.toFixed(2)} s), retrying`,
+ );
+ continue;
+ }
+ const from = Math.max(0, first.start - VOICE_LEAD);
+ const to = Math.min(duration(raw), last.end + VOICE_TAIL);
+ const length = to - from;
+ cut(raw, voicePath(id), from, to, [
+ "afade=t=in:d=0.01",
+ `afade=t=out:st=${(length - VOICE_TAIL / 2).toFixed(3)}:d=${(VOICE_TAIL / 2).toFixed(3)}`,
+ "loudnorm=I=-16:TP=-1.5:LRA=11",
+ ]);
+ const seconds = duration(voicePath(id));
+ console.log(`voice ${id} ${seconds.toFixed(2)} s "${said}"`);
+ return { text, prompt: input.prompt, heard: said, seconds };
+ }
+ throw new Error(
+ `No take of "${text}" was read as written in ${MAX_TAKES} tries.`,
+ );
+}
+
+async function music(): Promise<AudioManifest["music"]> {
+ const input = { prompt: MUSIC_PROMPT, multilingual: true };
+ for (let take = 1; take <= MAX_TAKES; take++) {
+ const raw = takePath("music", input, take);
+ if (!existsSync(raw)) await generate(input, raw);
+ const heard = await transcribe(raw);
+ const cue = heard[0];
+ if (
+ heard.length !== 1 ||
+ !cue ||
+ words(cue.text) !== words(MUSIC_CUE) ||
+ cue.start < MUSIC_SECONDS
+ ) {
+ console.log(
+ `music take ${take} heard "${heard.map((w) => `${w.text}@${w.start.toFixed(1)}`).join(" ")}", retrying`,
+ );
+ continue;
+ }
+ const end = cue.start - 0.25;
+ cut(raw, MUSIC_PATH, 0, end, [
+ `afade=t=out:st=${(end - 0.5).toFixed(3)}:d=0.5`,
+ "loudnorm=I=-18:TP=-2:LRA=11",
+ ]);
+ const seconds = duration(MUSIC_PATH);
+ console.log(`music ${seconds.toFixed(1)} s before the cue`);
+ return { seconds };
+ }
+ throw new Error(
+ `No music take held its cue past ${MUSIC_SECONDS} s in ${MAX_TAKES} tries.`,
+ );
+}
+
+/** Share of energy above ~1.5 kHz, through a one-pole high-pass. */
+function brightness(x: Float32Array): number {
+ const rc = 1 / (2 * Math.PI * 1500);
+ const a = rc / (rc + 1 / SAMPLE_RATE);
+ let y = 0;
+ let high = 0;
+ let all = 0;
+ for (let i = 1; i < x.length; i++) {
+ y = a * (y + (x[i] ?? 0) - (x[i - 1] ?? 0));
+ high += y * y;
+ all += (x[i] ?? 0) ** 2;
+ }
+ return all > 0 ? high / all : 0;
+}
+
+/** The loudest transient of a take: where it starts and how far it can be raised. */
+function strike(x: Float32Array): { onset: number; gainDb: number } {
+ let peak = 0;
+ for (let i = 1; i < x.length; i++)
+ if (Math.abs(x[i] ?? 0) > Math.abs(x[peak] ?? 0)) peak = i;
+ const level = Math.abs(x[peak] ?? 0);
+ let onset = peak;
+ const earliest = Math.max(0, peak - Math.round(0.02 * SAMPLE_RATE));
+ for (let i = peak; i >= earliest; i--)
+ if (Math.abs(x[i] ?? 0) > level * 0.1) onset = i;
+ return { onset: onset / SAMPLE_RATE, gainDb: -3 - 20 * Math.log10(level) };
+}
+
+async function click(): Promise<AudioManifest["click"]> {
+ for (let take = 1; take <= MAX_TAKES; take++) {
+ const input = { prompt: CLICK_PROMPT };
+ const raw = takePath("click", input, take);
+ if (!existsSync(raw)) await generate(input, raw);
+ const { onset, gainDb } = strike(decode(raw));
+ const from = Math.max(0, onset - 0.002);
+ cut(raw, CLICK_PATH, from, from + CLICK_SECONDS, [
+ `afade=t=out:st=${(CLICK_SECONDS / 2).toFixed(3)}:d=${(CLICK_SECONDS / 2).toFixed(3)}`,
+ `volume=${gainDb.toFixed(2)}dB`,
+ ]);
+ const bright = brightness(decode(CLICK_PATH));
+ if (bright < MIN_BRIGHTNESS) {
+ console.log(
+ `click take ${take} is a thump (${(bright * 100).toFixed(0)} % above 1.5 kHz), retrying`,
+ );
+ continue;
+ }
+ console.log(`click ${(bright * 100).toFixed(0)} % above 1.5 kHz`);
+ return {
+ seconds: duration(CLICK_PATH),
+ brightness: Number(bright.toFixed(3)),
+ };
+ }
+ throw new Error(`No click take was bright enough in ${MAX_TAKES} tries.`);
+}
+
+async function readPartial(): Promise<Partial<AudioManifest>> {
+ if (!existsSync(MANIFEST)) return {};
+ return JSON.parse(
+ await fs.readFile(MANIFEST, "utf8"),
+ ) as Partial<AudioManifest>;
+}
+
+async function save(manifest: Partial<AudioManifest>): Promise<void> {
+ await fs.writeFile(MANIFEST, `${JSON.stringify(manifest, null, "\t")}\n`);
+}
+
+async function main(): Promise<void> {
+ process.loadEnvFile(new URL("../../../.env", import.meta.url).pathname);
+ if (!process.env.FRAMEFIELDS_API_KEY)
+ throw new Error("FRAMEFIELDS_API_KEY missing from the repo root .env");
+ const manifest = await readPartial();
+ const voice: Partial<AudioManifest["voice"]> = {};
+ for (const id of LINE_IDS) {
+ const kept = manifest.voice?.[id];
+ if (kept?.prompt === voicePrompt(LINES[id]) && existsSync(voicePath(id))) {
+ voice[id] = kept;
+ continue;
+ }
+ voice[id] = await voiceLine(id);
+ await save({ ...manifest, voice: voice as AudioManifest["voice"] });
+ }
+ manifest.voice = voice as AudioManifest["voice"];
+ if (!manifest.music || !existsSync(MUSIC_PATH)) {
+ manifest.music = await music();
+ await save(manifest);
+ }
+ if (!manifest.click || !existsSync(CLICK_PATH)) {
+ manifest.click = await click();
+ await save(manifest);
+ }
+ console.log(`spent ~$${spent.toFixed(3)}`);
+}
+
+if (process.argv[2] === "cost") {
+ const speech = Object.values(LINES).join(" ").split(" ").length / 2.9;
+ const generated = speech + MUSIC_SECONDS + 5;
+ const usd =
+ (RATE[AUDIO_MODEL] * generated +
+ RATE[TRANSCRIBER] * (speech + MUSIC_SECONDS)) /
+ 60;
+ console.log(
+ `estimate $${usd.toFixed(2)} per pass (${speech.toFixed(0)} s of speech, ${MUSIC_SECONDS} s of music, a click), up to ${MAX_TAKES}× with retries`,
+ );
+} else {
+ await main();
+}
+process.exit(0);
diff --git a/examples/32_relay/src/render.ts b/examples/32_relay/src/render.ts
new file mode 100644
index 00000000..60a8682a
--- /dev/null
+++ b/examples/32_relay/src/render.ts
@@ -0,0 +1,66 @@
+/**
+ * pnpm render → output/relay.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 { missingAudio } from "./audio.js";
+import { buildFilm } from "./film.js";
+import { missingSfx } from "./sfx.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: 20 }, (_, i) =>
+ Math.round((i * (total - 1)) / 19),
+ );
+ 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 missing = [...missingSfx(), ...missingAudio()];
+ if (missing.length > 0) {
+ console.error(
+ `Missing sounds (${missing.join(", ")}). Run \`pnpm assets\` and \`pnpm audio\` first.`,
+ );
+ process.exit(1);
+ }
+ const started = Date.now();
+ const result = await film.renderVideo({
+ outputPath: path.join(OUTPUT, "relay.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/32_relay/src/sfx.ts b/examples/32_relay/src/sfx.ts
new file mode 100644
index 00000000..f861d240
--- /dev/null
+++ b/examples/32_relay/src/sfx.ts
@@ -0,0 +1,40 @@
+/**
+ * The interface's two cues: a panel opening and a completion. They come from
+ * UI SFX (github.com/romainsimon/uisfx), "soft" pack, whose audio is CC0-1.0.
+ * Each is pinned to a commit and checked by SHA-256; `pnpm assets` fetches
+ * them into assets/sfx/ (media stays out of git). The library's presses are
+ * all low, pitched blips, so the mouse click is generated instead (audio.ts).
+ */
+import { existsSync } from "node:fs";
+import path from "node:path";
+import { ASSETS } from "./theme.js";
+
+export const UISFX_COMMIT = "9950fe66f993a6660dab9c2651dcbcd899ffd83b";
+
+export const SFX = {
+ panel: {
+ source: "soft/open.mp3",
+ sha256: "e7cd24beb3a6a873afb05df2dae5eb128dc6e5d47680892b57dd2ccde7799d00",
+ seconds: 0.49,
+ },
+ complete: {
+ source: "soft/complete.mp3",
+ sha256: "e314e373c1c06f7aa943caea003993c1ce89702a22501c067b7beb079c48e777",
+ seconds: 0.98,
+ },
+} as const;
+
+export type SfxName = keyof typeof SFX;
+
+export const sfxPath = (name: SfxName) =>
+ path.join(ASSETS, "sfx", `${name}.mp3`);
+
+export const sfxUrl = (name: SfxName) =>
+ `https://raw.githubusercontent.com/romainsimon/uisfx/${UISFX_COMMIT}/packages/uisfx/sounds/${SFX[name].source}`;
+
+/** Sounds not on disk yet. */
+export function missingSfx(): SfxName[] {
+ return (Object.keys(SFX) as SfxName[]).filter(
+ (name) => !existsSync(sfxPath(name)),
+ );
+}
diff --git a/examples/32_relay/src/theme.ts b/examples/32_relay/src/theme.ts
new file mode 100644
index 00000000..bcd5365d
--- /dev/null
+++ b/examples/32_relay/src/theme.ts
@@ -0,0 +1,43 @@
+/**
+ * Tokens for the Relay film: one accent, two weights, an 8 px spacing grid,
+ * and one clock. Everything on screen reads from here.
+ */
+
+export const W = 1920;
+export const H = 1080;
+export const FPS = 30;
+export const OUTPUT = new URL("../output/", import.meta.url).pathname;
+export const ASSETS = new URL("../assets/", import.meta.url).pathname;
+export const FONTS = new URL("../../../assets/fonts/", import.meta.url)
+ .pathname;
+
+/** Seconds → frames. */
+export const sec = (s: number) => Math.round(s * FPS);
+/** The spacing grid. */
+export const space = (n: number) => n * 8;
+
+export const SANS = "Inter";
+export const REGULAR = 400;
+export const SEMIBOLD = 600;
+
+/** The one accent, and its tint for selected and new things. */
+export const ACCENT = "#3d4fe0";
+export const ACCENT_TINT = "#eceefc";
+/** The wall behind the window. */
+export const WALL = "#e7e4dd";
+export const WALL_LIGHT = "#f3f1ec";
+/** App surfaces. */
+export const APP = "#ffffff";
+export const SIDEBAR = "#f6f5f2";
+export const SUBTLE = "#f1efeb";
+export const LINE = "#e7e5e0";
+export const EDGE = "#d9d6cf";
+/** Type. */
+export const INK = "#18181b";
+export const SOFT = "#4f4f57";
+export const MUTED = "#76767e";
+/** Shadow color for raised surfaces. */
+export const SHADOW = "#2a2620";
+
+/** The window on the stage, in composition px. */
+export const FRAME = { x: 150, y: 82, width: 1620, height: 916 } as const;
diff --git a/examples/32_relay/src/titles.ts b/examples/32_relay/src/titles.ts
new file mode 100644
index 00000000..d8f4e647
--- /dev/null
+++ b/examples/32_relay/src/titles.ts
@@ -0,0 +1,290 @@
+/**
+ * Everything that sits on the glass rather than in the app: the opening
+ * line with the client's request, the captions while the task takes shape,
+ * and the end card.
+ */
+import {
+ FontManager,
+ Layer,
+ LayerAnimation,
+ type LayoutNode,
+ TextAnimator,
+} from "framefields";
+import { APP, H, INK, REGULAR, SANS, SEMIBOLD, SOFT, sec, W } from "./theme.js";
+import { MARK_RADIUS, relayMark } from "./ui/brand.js";
+import { shell } from "./ui/handoffs.js";
+import { messageRow, REQUEST_MESSAGE } from "./ui/inbox.js";
+import { type Rect, raise, shown, text } from "./ui/kit.js";
+import { LIST_W, ROW_H } from "./ui/layout.js";
+
+const ARRIVE = "power3.inOut";
+
+/**
+ * A line whose words rise out of a soft blur one after another, starting at
+ * `at` (local frame); `extra` adds more keys (an exit) to the line.
+ */
+function kinetic(
+ value: string,
+ o: { y: number; size: number; strong?: boolean; color?: string; at: number },
+ extra?: LayerAnimation,
+) {
+ const sweep = LayerAnimation.create().kineticSweep(
+ -1,
+ 1,
+ o.at,
+ o.at + 20,
+ "power2.inOut",
+ );
+ return Layer.text(value, {
+ position: "absolute",
+ x: 0,
+ y: o.y,
+ width: W,
+ align: "center",
+ fontFamily: SANS,
+ fontSize: o.size,
+ fontWeight: o.strong ? SEMIBOLD : REGULAR,
+ fill: o.color ?? INK,
+ animators: [
+ // Word progress runs 1 → 0 as the sweep passes, so an "in" curve is
+ // what makes each word decelerate into place.
+ TextAnimator.waveRise({
+ unit: "word",
+ y: o.size * 0.4,
+ rotationX: 0,
+ opacity: 0,
+ blur: 8,
+ easing: "expo.in",
+ }),
+ ],
+ }).animate(extra ? LayerAnimation.merge(sweep, extra) : sweep);
+}
+
+/**
+ * "From request to ready." over the request, shown twice its inbox size;
+ * at `fly` it shrinks into its row (`row`, on the stage) and lands at `landed`.
+ */
+export function opening(fly: number, landed: number, row: Rect): LayoutNode[] {
+ const k = 2;
+ const x = (W - LIST_W * k) / 2;
+ const y = 452;
+ const cardIn = sec(0.45);
+ const headline = kinetic(
+ "From request to ready.",
+ { y: 312, size: 76, strong: true, at: sec(0.15) },
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 1],
+ [fly - 26, 1, "hold"],
+ [fly - 12, 0, "power2.inOut"],
+ ])
+ .keys("y", [
+ [0, 312],
+ [fly - 26, 312, "hold"],
+ [fly - 12, 296, "power2.in"],
+ ]),
+ );
+ const card = raise(
+ Layer.box({
+ position: "absolute",
+ x,
+ y,
+ width: LIST_W,
+ height: ROW_H,
+ anchorX: 0,
+ anchorY: 0,
+ borderRadius: 12,
+ background: APP,
+ children: messageRow(REQUEST_MESSAGE, true),
+ }),
+ "popover",
+ ).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [cardIn, 0, "hold"],
+ [cardIn + 12, 1, "power2.out"],
+ [landed, 1, "hold"],
+ [landed + 5, 0, "power2.out"],
+ ])
+ .keys("x", [
+ [0, x],
+ [fly, x, "hold"],
+ [landed, row.x, ARRIVE],
+ ])
+ .keys("y", [
+ [0, y + 24],
+ [cardIn, y + 24, "hold"],
+ [cardIn + sec(0.7), y, "expo.out"],
+ [fly, y, "hold"],
+ [landed, row.y, ARRIVE],
+ ])
+ .keys("scale", [
+ [0, k],
+ [fly, k, "hold"],
+ [landed, 1, ARRIVE],
+ ]),
+ );
+ return [headline, card];
+}
+
+/**
+ * One line, three promises, each lighting up as the modal delivers it:
+ * dim until its frame in `lights`, then full white.
+ */
+export function captions(
+ phrases: string[],
+ lights: number[],
+ open: number,
+ close: number,
+): LayoutNode {
+ const size = 30;
+ const gap = 14;
+ const padX = 32;
+ const height = 64;
+ const widths = phrases.map(
+ (p) =>
+ FontManager.measure(p, {
+ fontFamily: SANS,
+ fontSize: size,
+ fontWeight: SEMIBOLD,
+ }).width,
+ );
+ const width =
+ widths.reduce((a, b) => a + b, 0) + gap * (phrases.length - 1) + 2 * padX;
+ const y = H - 56 - height;
+ let cursor = padX;
+ const words = phrases.map((p, i) => {
+ const node = text(p, {
+ x: cursor,
+ y: 15,
+ size,
+ strong: true,
+ color: "#ffffff",
+ }).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0.38],
+ [lights[i] ?? 0, 0.38, "hold"],
+ [(lights[i] ?? 0) + 8, 1, "power2.out"],
+ ]),
+ );
+ cursor += (widths[i] ?? 0) + gap;
+ return node;
+ });
+ return Layer.box({
+ position: "absolute",
+ x: (W - width) / 2,
+ y,
+ width,
+ height,
+ borderRadius: height / 2,
+ background: INK,
+ children: words,
+ }).animate(
+ shown(open, close, 8),
+ LayerAnimation.keys("y", [
+ [0, y + 14],
+ [open, y + 14, "hold"],
+ [open + sec(0.5), y, "expo.out"],
+ ]),
+ );
+}
+
+const MARK = 112;
+const NAME_SIZE = 112;
+const MARK_GAP = 32;
+const MARK_TOP = 404;
+
+/** Where the end card's mark sits, so the board's card can land on it. */
+export function endMark(): Rect {
+ const name = FontManager.measure("Relay", {
+ fontFamily: SANS,
+ fontSize: NAME_SIZE,
+ fontWeight: SEMIBOLD,
+ });
+ return {
+ x: (W - (MARK + MARK_GAP + name.width)) / 2,
+ y: MARK_TOP,
+ width: MARK,
+ height: MARK,
+ };
+}
+
+/**
+ * The new card leaves the board and becomes the mark: a shell from the card
+ * on screen (`card`, corner radius `radius`) to the end card's mark, turning
+ * to the accent on the way. It lands at `until`, when the end card starts.
+ */
+export function handover(
+ card: Rect,
+ radius: number,
+ at: number,
+ until: number,
+): LayoutNode[] {
+ return shell(
+ {
+ from: card,
+ to: endMark(),
+ radius: [radius, MARK * MARK_RADIUS],
+ at,
+ until,
+ ease: "power3.inOut",
+ },
+ "card",
+ "to",
+ );
+}
+
+/**
+ * "Relay. Keep client work moving." The mark is there from the first frame
+ * (the card has just become it): its dot appears and its arrow draws as the
+ * name slides out beside it and the line rises underneath.
+ */
+export function endCard(at: number, length: number): LayoutNode {
+ const mark = endMark();
+ const name = FontManager.measure("Relay", {
+ fontFamily: SANS,
+ fontSize: NAME_SIZE,
+ fontWeight: SEMIBOLD,
+ });
+ const nameX = mark.x + MARK + MARK_GAP;
+ const nameY = MARK_TOP + (MARK - name.height) / 2;
+ return Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ startFrame: at,
+ durationFrames: length,
+ children: [
+ relayMark({ x: mark.x, y: mark.y, size: MARK, drawAt: 4 }),
+ Layer.text("Relay", {
+ position: "absolute",
+ x: nameX,
+ y: nameY,
+ fontFamily: SANS,
+ fontSize: NAME_SIZE,
+ fontWeight: SEMIBOLD,
+ fill: INK,
+ letterSpacing: -2,
+ }).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [sec(0.45), 1, "power2.out"],
+ ])
+ .keys("x", [
+ [0, nameX - 28],
+ [sec(0.8), nameX, "expo.out"],
+ ]),
+ ),
+ kinetic("Keep client work moving.", {
+ y: MARK_TOP + MARK + 52,
+ size: 40,
+ color: SOFT,
+ at: sec(0.4),
+ }),
+ ],
+ });
+}
diff --git a/examples/32_relay/src/ui/app.ts b/examples/32_relay/src/ui/app.ts
new file mode 100644
index 00000000..7bd7f2ad
--- /dev/null
+++ b/examples/32_relay/src/ui/app.ts
@@ -0,0 +1,12 @@
+/** The whole Relay window content, in content px, keyed to the timeline. */
+import type { LayoutNode } from "framefields";
+import { board } from "./board.js";
+import { handoffs } from "./handoffs.js";
+import { inbox } from "./inbox.js";
+import { sidebar } from "./sidebar.js";
+import { taskModal } from "./task-modal.js";
+import type { Timeline } from "./timeline.js";
+
+export function relayApp(t: Timeline): LayoutNode[] {
+ return [inbox(t), board(t), sidebar(t), ...taskModal(t), ...handoffs(t)];
+}
diff --git a/examples/32_relay/src/ui/board.ts b/examples/32_relay/src/ui/board.ts
new file mode 100644
index 00000000..ae8efed4
--- /dev/null
+++ b/examples/32_relay/src/ui/board.ts
@@ -0,0 +1,250 @@
+/**
+ * The project board: four columns of cards. The new task lands at the top
+ * of Ready, the cards under it make room, and the column count ticks over.
+ */
+import {
+ FontManager,
+ Layer,
+ LayerAnimation,
+ type LayoutNode,
+} from "framefields";
+import {
+ ACCENT,
+ ACCENT_TINT,
+ APP,
+ LINE,
+ MUTED,
+ SANS,
+ SEMIBOLD,
+ SOFT,
+ SUBTLE,
+ sec,
+ space,
+} from "../theme.js";
+import { AVA, type Card, COLUMNS, LEO, MAYA, NEW_CARD } from "./data.js";
+import { CARD_RADIUS } from "./handoffs.js";
+import { avatar, during, fade, icon, raise, rise, rule, text } from "./kit.js";
+import {
+ BOARD_X,
+ CARD_H,
+ CARD_W,
+ CH,
+ COLUMN_W,
+ COLUMNS_Y,
+ CW,
+ cardSlot,
+ columnX,
+ READY,
+ SIDEBAR_W,
+} from "./layout.js";
+import { boardIn, cardLands, type Timeline } from "./timeline.js";
+
+/** A card; `contents` animates what is on it, apart from the card itself. */
+function card(c: Card, x: number, y: number, contents?: LayerAnimation) {
+ const children: LayoutNode[] = [
+ text(c.title, { x: space(2), y: space(2), size: 15, strong: true }),
+ avatar(c.owner, { x: space(2), y: 56, size: 24 }),
+ icon("calendar", { x: 50, y: 61, size: 15 }),
+ text(c.due, { x: 70, y: 60, size: 13, color: SOFT }),
+ icon("checklist", { x: CARD_W - space(2) - 48, y: 61, size: 15 }),
+ text(`${c.done}/${c.total}`, {
+ x: CARD_W - space(2) - 28,
+ y: 60,
+ width: 28,
+ align: "end",
+ size: 13,
+ color: SOFT,
+ }),
+ ];
+ return raise(
+ Layer.box({
+ position: "absolute",
+ x,
+ y,
+ width: CARD_W,
+ height: CARD_H,
+ borderRadius: CARD_RADIUS,
+ background: APP,
+ borderColor: LINE,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ children: contents
+ ? [
+ Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: CARD_W,
+ height: CARD_H,
+ children,
+ }).animate(contents),
+ ]
+ : children,
+ }),
+ "card",
+ );
+}
+
+function header(): LayoutNode[] {
+ const tabs = ["Board", "List", "Timeline"];
+ const nodes: LayoutNode[] = [
+ text("Brightline website", { x: BOARD_X, y: 22, size: 22, strong: true }),
+ ];
+ [MAYA, LEO, AVA].forEach((p, i) => {
+ nodes.push(
+ Layer.box({
+ position: "absolute",
+ x: CW - space(4) - 28 - (2 - i) * 22 - 2,
+ y: 22,
+ width: 32,
+ height: 32,
+ borderRadius: 16,
+ background: APP,
+ children: [avatar(p, { x: 2, y: 2, size: 28 })],
+ }),
+ );
+ });
+ let x = BOARD_X;
+ tabs.forEach((label, i) => {
+ const width = FontManager.measure(label, {
+ fontFamily: SANS,
+ fontSize: 15,
+ fontWeight: SEMIBOLD,
+ }).width;
+ nodes.push(
+ text(label, {
+ x,
+ y: 76,
+ size: 15,
+ strong: i === 0,
+ color: i === 0 ? undefined : MUTED,
+ }),
+ );
+ if (i === 0)
+ nodes.push(
+ Layer.box({
+ position: "absolute",
+ x,
+ y: 102,
+ width,
+ height: 2,
+ background: ACCENT,
+ }),
+ );
+ x += width + space(3);
+ });
+ nodes.push(rule(SIDEBAR_W, 104, CW - SIDEBAR_W, { color: LINE }));
+ return nodes;
+}
+
+/** A column's header count; Ready's ticks over when the new card lands. */
+function count(column: number, x: number, t: Timeline): LayoutNode[] {
+ const n = COLUMNS[column]?.cards.length ?? 0;
+ const label = (v: number) =>
+ text(String(v), { x, y: COLUMNS_Y + 15, size: 14, color: MUTED });
+ if (column !== READY) return [label(n)];
+ return [
+ label(n).animate(fade(cardLands(t) - 4, 4, 1, 0)),
+ label(n + 1).animate(fade(cardLands(t), 6)),
+ ];
+}
+
+function columns(t: Timeline): LayoutNode[] {
+ const nodes: LayoutNode[] = [];
+ const makeRoom = cardLands(t) - sec(0.35);
+ COLUMNS.forEach((col, i) => {
+ const x = columnX(i);
+ const nameWidth = FontManager.measure(col.name, {
+ fontFamily: SANS,
+ fontSize: 14,
+ fontWeight: SEMIBOLD,
+ }).width;
+ nodes.push(
+ Layer.box({
+ position: "absolute",
+ x,
+ y: COLUMNS_Y,
+ width: COLUMN_W,
+ height: CH - COLUMNS_Y - space(3),
+ borderRadius: 12,
+ background: SUBTLE,
+ }),
+ text(col.name, {
+ x: x + space(2),
+ y: COLUMNS_Y + 15,
+ size: 14,
+ strong: true,
+ }),
+ ...count(i, x + space(2) + nameWidth + space(1), t),
+ );
+ col.cards.forEach((c, j) => {
+ const slot = cardSlot(i, j);
+ const node = card(c, slot.x, slot.y);
+ if (i === READY) {
+ const below = cardSlot(i, j + 1).y;
+ node.animate(
+ LayerAnimation.keys("y", [
+ [0, slot.y],
+ [makeRoom + j * 2, slot.y, "hold"],
+ [makeRoom + j * 2 + sec(0.45), below, "expo.out"],
+ ]),
+ );
+ }
+ nodes.push(node);
+ });
+ });
+ return nodes;
+}
+
+/**
+ * The new task: the modal's shell lands in Ready's first slot and becomes
+ * this card, ringed in the accent for a moment. It empties again when it
+ * leaves for the end card.
+ */
+function newCard(t: Timeline): LayoutNode[] {
+ const slot = cardSlot(READY, 0);
+ const at = cardLands(t);
+ const ring = Layer.box({
+ position: "absolute",
+ x: slot.x - 3,
+ y: slot.y - 3,
+ width: slot.width + 6,
+ height: slot.height + 6,
+ borderRadius: CARD_RADIUS + 3,
+ background: ACCENT_TINT,
+ borderColor: ACCENT,
+ borderWidth: 2,
+ strokeAlign: "inside",
+ }).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [at, 0, "hold"],
+ [at + 6, 1, "power2.out"],
+ [at + sec(2.4), 1, "hold"],
+ [at + sec(3.2), 0, "power2.inOut"],
+ ]),
+ );
+ const contents = LayerAnimation.keys("opacity", [
+ [0, 0],
+ [at, 0, "hold"],
+ [at + 8, 1, "power2.out"],
+ [t.sceneOut - 8, 1, "hold"],
+ [t.sceneOut - 2, 0, "power2.in"],
+ ]);
+ const node = card(NEW_CARD, slot.x, slot.y, contents).animate(
+ during(at, t.sceneOut),
+ );
+ return [ring, node];
+}
+
+/** The board view, arriving as the modal closes. */
+export function board(t: Timeline): LayoutNode {
+ return Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: CW,
+ height: CH,
+ children: [...header(), ...columns(t), ...newCard(t)],
+ }).animate(rise(0, boardIn(t), 10, sec(0.5)));
+}
diff --git a/examples/32_relay/src/ui/brand.ts b/examples/32_relay/src/ui/brand.ts
new file mode 100644
index 00000000..6bfcb971
--- /dev/null
+++ b/examples/32_relay/src/ui/brand.ts
@@ -0,0 +1,63 @@
+/**
+ * Relay's mark: a request (the dot) handed on (the arrow), white on the
+ * accent. On the end card the dot appears and the arrow draws itself on.
+ */
+import { Layer, LayerAnimation, type LayoutNode } from "framefields";
+import { transformPathData } from "framefields/components";
+import { ACCENT } from "../theme.js";
+import { dot, fade } from "./kit.js";
+
+/** Corner radius, as a share of the mark's size. */
+export const MARK_RADIUS = 0.28;
+const ARROW = "M10.5 12 L17.5 12 M14 8.5 L17.5 12 L14 15.5";
+
+export function relayMark(o: {
+ x: number;
+ y: number;
+ size: number;
+ /** Draw the arrow on from this frame (local); drawn from the start otherwise. */
+ drawAt?: number;
+ id?: string;
+}): LayoutNode {
+ const k = o.size / 24;
+ const arrow = Layer.shape("path", {
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: o.size,
+ height: o.size,
+ d: transformPathData(ARROW, k),
+ fillType: "none",
+ strokeColor: "#ffffff",
+ strokeWidth: 2.4 * k,
+ strokeLineCap: "round",
+ strokeLineJoin: "round",
+ });
+ const request = dot({
+ x: 5 * k,
+ y: 9.6 * k,
+ size: 4.8 * k,
+ color: "#ffffff",
+ });
+ if (o.drawAt !== undefined) {
+ request.animate(fade(o.drawAt - 4, 6));
+ arrow.animate(
+ LayerAnimation.keys("trimEnd", [
+ [0, 0],
+ [o.drawAt, 0, "hold"],
+ [o.drawAt + 18, 1, "power3.inOut"],
+ ]),
+ );
+ }
+ return Layer.box({
+ ...(o.id && { id: o.id }),
+ position: "absolute",
+ x: o.x,
+ y: o.y,
+ width: o.size,
+ height: o.size,
+ borderRadius: o.size * MARK_RADIUS,
+ background: ACCENT,
+ children: [request, arrow],
+ });
+}
diff --git a/examples/32_relay/src/ui/data.ts b/examples/32_relay/src/ui/data.ts
new file mode 100644
index 00000000..13d518c1
--- /dev/null
+++ b/examples/32_relay/src/ui/data.ts
@@ -0,0 +1,216 @@
+/** The fictional studio, its client and its work. */
+import type { Person } from "./kit.js";
+
+const person = (name: string, tone: string): Person => ({
+ name,
+ initials: name
+ .split(" ")
+ .map((w) => w[0])
+ .join(""),
+ tone,
+});
+
+export const DANA = person("Dana Ortiz", "#e9e2d6");
+export const MAYA = person("Maya Chen", "#dfe0e6");
+export const LEO = person("Leo Park", "#e4e0da");
+export const AVA = person("Ava Brooks", "#ece6df");
+export const SAM = person("Sam Rivera", "#e2ded6");
+
+export const TEAM = [
+ { person: MAYA, role: "Design" },
+ { person: LEO, role: "Development" },
+ { person: AVA, role: "Content" },
+];
+
+export const REQUEST = {
+ from: DANA,
+ client: "Brightline",
+ email: "[email protected]",
+ time: "9:41 AM",
+ subject: "Homepage update",
+ question: "Can we ship the homepage update Friday?",
+};
+
+export interface Message {
+ from: Person;
+ client: string;
+ time: string;
+ preview: string;
+}
+
+/** The rest of the inbox, already read. */
+export const MESSAGES: Message[] = [
+ {
+ from: person("Priya Shah", "#e6e1d9"),
+ client: "Northwind",
+ time: "8:12 AM",
+ preview: "Final logo files are in the shared folder.",
+ },
+ {
+ from: person("Tom Becker", "#dfdcd5"),
+ client: "Atlas",
+ time: "Yesterday",
+ preview: "Thursday works for the kickoff call.",
+ },
+ {
+ from: person("Lena Park", "#e8e3dc"),
+ client: "Brightline",
+ time: "Yesterday",
+ preview: "Added you to the analytics dashboard.",
+ },
+ {
+ from: person("Marco Ruiz", "#e1ddd6"),
+ client: "Northwind",
+ time: "Mon",
+ preview: "Invoice paid, thanks. See you next sprint.",
+ },
+ {
+ from: person("Iris Novak", "#e9e5df"),
+ client: "Atlas",
+ time: "Mon",
+ preview: "Can you share the onboarding checklist?",
+ },
+ {
+ from: person("Owen Hart", "#dedad3"),
+ client: "Brightline",
+ time: "Fri",
+ preview: "Love the new pricing page draft.",
+ },
+ {
+ from: person("Nora Lane", "#e5e0d8"),
+ client: "Northwind",
+ time: "Fri",
+ preview: "Brand guidelines v2 attached.",
+ },
+ {
+ from: person("Theo Grant", "#e2ded8"),
+ client: "Atlas",
+ time: "Thu",
+ preview: "Feedback on the welcome emails.",
+ },
+];
+
+export const BODY = [
+ "Hi team,",
+ "The new homepage copy and screenshots are approved on our side.",
+ REQUEST.question,
+ "",
+ "Thanks,",
+ "Dana",
+];
+
+export const DUE_OPTIONS = [
+ { label: "Today", date: "Wed, Nov 5" },
+ { label: "Tomorrow", date: "Thu, Nov 6" },
+ { label: "Friday", date: "Fri, Nov 7" },
+ { label: "Next week", date: "Mon, Nov 10" },
+];
+export const FRIDAY = 2;
+
+export const CHECKLIST = [
+ "Final copy review",
+ "Swap hero screenshots",
+ "QA on mobile",
+];
+
+export const PROJECTS = [
+ "Brightline website",
+ "Northwind rebrand",
+ "Atlas onboarding",
+];
+
+export interface Card {
+ title: string;
+ owner: Person;
+ due: string;
+ done: number;
+ total: number;
+}
+
+export const NEW_CARD: Card = {
+ title: "Homepage update",
+ owner: MAYA,
+ due: "Fri, Nov 7",
+ done: 0,
+ total: CHECKLIST.length,
+};
+
+export const COLUMNS: Array<{ name: string; cards: Card[] }> = [
+ {
+ name: "Backlog",
+ cards: [
+ {
+ title: "Blog template refresh",
+ owner: AVA,
+ due: "Nov 18",
+ done: 0,
+ total: 4,
+ },
+ {
+ title: "Footer link audit",
+ owner: LEO,
+ due: "Nov 20",
+ done: 0,
+ total: 2,
+ },
+ {
+ title: "Cookie banner copy",
+ owner: AVA,
+ due: "Nov 21",
+ done: 0,
+ total: 1,
+ },
+ ],
+ },
+ {
+ name: "Ready",
+ cards: [
+ {
+ title: "Pricing page tweaks",
+ owner: LEO,
+ due: "Nov 12",
+ done: 0,
+ total: 2,
+ },
+ {
+ title: "Case study layout",
+ owner: MAYA,
+ due: "Nov 14",
+ done: 1,
+ total: 4,
+ },
+ ],
+ },
+ {
+ name: "In progress",
+ cards: [
+ {
+ title: "Contact form fixes",
+ owner: LEO,
+ due: "Nov 6",
+ done: 2,
+ total: 3,
+ },
+ {
+ title: "New team photos",
+ owner: AVA,
+ due: "Nov 10",
+ done: 1,
+ total: 2,
+ },
+ ],
+ },
+ {
+ name: "Done",
+ cards: [
+ { title: "Analytics setup", owner: LEO, due: "Nov 3", done: 3, total: 3 },
+ {
+ title: "Hero illustration",
+ owner: MAYA,
+ due: "Nov 4",
+ done: 2,
+ total: 2,
+ },
+ ],
+ },
+];
diff --git a/examples/32_relay/src/ui/handoffs.ts b/examples/32_relay/src/ui/handoffs.ts
new file mode 100644
index 00000000..c56794a0
--- /dev/null
+++ b/examples/32_relay/src/ui/handoffs.ts
@@ -0,0 +1,101 @@
+/**
+ * The task as one surface: Create task grows into the modal, and the saved
+ * modal shrinks into its card on the board. Each handoff is an empty shell
+ * carried from one rect to the other while the views around it change; the
+ * real surface takes over on the frame the shell arrives.
+ */
+import { Layer, LayerAnimation, type LayoutNode } from "framefields";
+import { ACCENT, APP, LINE, space } from "../theme.js";
+import { during, type Reshape, raise, reshape, shrink } from "./kit.js";
+import { CREATE_BUTTON, cardSlot, MODAL, READY } from "./layout.js";
+import {
+ cardLands,
+ handOff,
+ modalIn,
+ modalOpen,
+ type Timeline,
+} from "./timeline.js";
+
+export const MODAL_RADIUS = 14;
+export const CARD_RADIUS = 10;
+/** Create task is still held down (at 96 %) when the modal starts to grow. */
+const PRESSED = 0.96;
+
+/**
+ * A white shell carried along `m`. With `from` set, it starts as an accent
+ * surface (a primary button) that turns white over its first frames; with
+ * `to`, it ends as one.
+ */
+export function shell(
+ m: Reshape,
+ level: "card" | "popover" | "modal",
+ accent?: "from" | "to",
+): LayoutNode[] {
+ const box = (background: string) =>
+ Layer.box({
+ position: "absolute",
+ ...m.from,
+ borderRadius: m.radius[0],
+ background,
+ ...(background === APP && {
+ borderColor: LINE,
+ borderWidth: 1,
+ strokeAlign: "inside" as const,
+ }),
+ }).animate(reshape(m));
+ const nodes: LayoutNode[] = [
+ raise(box(APP), level).animate(during(m.at, m.until)),
+ ];
+ if (accent === "from")
+ nodes.push(
+ box(ACCENT).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [m.at - 1, 0, "hold"],
+ [m.at, 1, "hold"],
+ [m.at + 5, 0, "power2.out"],
+ ]),
+ ),
+ );
+ if (accent === "to")
+ nodes.push(
+ box(ACCENT).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [m.at + 4, 0, "hold"],
+ [m.at + 14, 1, "power2.inOut"],
+ [m.until, 1, "hold"],
+ [m.until + 1, 0, "hold"],
+ ]),
+ ),
+ );
+ return nodes;
+}
+
+/** Create task → the modal, then the saved modal → its card in Ready. */
+export function handoffs(t: Timeline): LayoutNode[] {
+ return [
+ ...shell(
+ {
+ from: shrink(CREATE_BUTTON, PRESSED),
+ to: MODAL,
+ radius: [space(1), MODAL_RADIUS],
+ at: modalIn(t),
+ until: modalOpen(t),
+ ease: "power3.out",
+ },
+ "modal",
+ "from",
+ ),
+ ...shell(
+ {
+ from: MODAL,
+ to: cardSlot(READY, 0),
+ radius: [MODAL_RADIUS, CARD_RADIUS],
+ at: handOff(t),
+ until: cardLands(t),
+ },
+ "popover",
+ ),
+ ];
+}
diff --git a/examples/32_relay/src/ui/inbox.ts b/examples/32_relay/src/ui/inbox.ts
new file mode 100644
index 00000000..7367f215
--- /dev/null
+++ b/examples/32_relay/src/ui/inbox.ts
@@ -0,0 +1,321 @@
+/**
+ * The inbox: the message list and the reading pane. The new request lands
+ * in the first row; selecting it opens the message with "Create task".
+ */
+import {
+ FontManager,
+ Layer,
+ LayerAnimation,
+ type LayoutNode,
+} from "framefields";
+import {
+ ACCENT,
+ ACCENT_TINT,
+ APP,
+ EDGE,
+ INK,
+ LINE,
+ MUTED,
+ SANS,
+ SEMIBOLD,
+ SOFT,
+ sec,
+ space,
+} from "../theme.js";
+import { BODY, MESSAGES, type Message, REQUEST } from "./data.js";
+import { avatar, dot, fade, icon, press, rise, rule, text } from "./kit.js";
+import {
+ CH,
+ CREATE_BUTTON,
+ LIST_TOP,
+ LIST_W,
+ LIST_X,
+ PANE_W,
+ PANE_X,
+ REPLY_BUTTON,
+ ROW_H,
+} from "./layout.js";
+import { boardIn, type Timeline } from "./timeline.js";
+
+/**
+ * A message row's content, in row px (LIST_W × ROW_H). Unread rows carry
+ * the accent dot until `readAt`.
+ */
+export function messageRow(
+ m: Message,
+ unread: boolean,
+ readAt?: number,
+): LayoutNode[] {
+ const nameWidth = FontManager.measure(m.from.name, {
+ fontFamily: SANS,
+ fontSize: 15,
+ fontWeight: SEMIBOLD,
+ }).width;
+ const nodes: LayoutNode[] = [
+ avatar(m.from, { x: space(3), y: 18, size: 36 }),
+ text(m.from.name, { x: 72, y: 18, size: 15, strong: true }),
+ text(m.client, {
+ x: 72 + nameWidth + space(1),
+ y: 18,
+ size: 15,
+ color: MUTED,
+ }),
+ text(m.time, {
+ x: LIST_W - space(3) - 120,
+ y: 20,
+ width: 120,
+ align: "end",
+ size: 13,
+ color: MUTED,
+ }),
+ text(m.preview, {
+ x: 72,
+ y: 48,
+ size: 15,
+ color: unread ? INK : SOFT,
+ }),
+ rule(space(3), ROW_H - 1, LIST_W - space(6), { color: LINE }),
+ ];
+ if (unread) {
+ const mark = dot({ x: 9, y: 32, size: 8, color: ACCENT });
+ if (readAt !== undefined) mark.animate(fade(readAt, 6, 1, 0));
+ nodes.push(mark);
+ }
+ return nodes;
+}
+
+export const REQUEST_MESSAGE: Message = {
+ from: REQUEST.from,
+ client: REQUEST.client,
+ time: REQUEST.time,
+ preview: REQUEST.question,
+};
+
+function list(t: Timeline): LayoutNode {
+ // Older mail moves down a row to make room as the request flies in.
+ const shiftFrom = t.landed - sec(0.6);
+ const older = Layer.box({
+ position: "absolute",
+ x: 0,
+ y: LIST_TOP,
+ width: LIST_W,
+ height: MESSAGES.length * ROW_H,
+ children: MESSAGES.map((m, i) =>
+ Layer.box({
+ position: "absolute",
+ x: 0,
+ y: i * ROW_H,
+ width: LIST_W,
+ height: ROW_H,
+ children: messageRow(m, false),
+ }),
+ ),
+ }).animate(
+ LayerAnimation.keys("y", [
+ [0, LIST_TOP],
+ [shiftFrom, LIST_TOP, "hold"],
+ [shiftFrom + sec(0.5), LIST_TOP + ROW_H, "expo.out"],
+ ]),
+ );
+
+ const selected = Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: LIST_W,
+ height: ROW_H,
+ background: ACCENT_TINT,
+ children: [
+ Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: 3,
+ height: ROW_H,
+ background: ACCENT,
+ }),
+ ],
+ }).animate(fade(t.select.at, 4));
+ const request = Layer.box({
+ id: "request-row",
+ position: "absolute",
+ x: 0,
+ y: LIST_TOP,
+ width: LIST_W,
+ height: ROW_H,
+ background: APP,
+ children: [selected, ...messageRow(REQUEST_MESSAGE, true, t.select.at)],
+ }).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [t.landed - 1, 0, "hold"],
+ [t.landed, 1],
+ ]),
+ );
+
+ return Layer.box({
+ position: "absolute",
+ x: LIST_X,
+ y: 0,
+ width: LIST_W,
+ height: CH,
+ background: APP,
+ overflow: "hidden",
+ children: [
+ older,
+ request,
+ Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: LIST_W,
+ height: LIST_TOP,
+ background: APP,
+ children: [
+ text("Inbox", { x: space(3), y: 22, size: 22, strong: true }),
+ text("All clients", {
+ x: LIST_W - space(3) - 160,
+ y: 28,
+ width: 160,
+ align: "end",
+ size: 14,
+ color: MUTED,
+ }),
+ rule(0, LIST_TOP - 1, LIST_W, { color: LINE }),
+ ],
+ }),
+ rule(LIST_W - 1, 0, CH, { vertical: true, color: LINE }),
+ ],
+ });
+}
+
+function button(
+ label: string,
+ r: { x: number; y: number; width: number; height: number },
+ primary: boolean,
+ glyph: "plus" | "reply",
+) {
+ return Layer.box({
+ position: "absolute",
+ ...r,
+ borderRadius: space(1),
+ background: primary ? ACCENT : APP,
+ ...(!primary && {
+ borderColor: EDGE,
+ borderWidth: 1,
+ strokeAlign: "inside" as const,
+ }),
+ children: [
+ icon(glyph, {
+ x: space(2),
+ y: 11,
+ size: 18,
+ color: primary ? "#ffffff" : SOFT,
+ weight: 2,
+ }),
+ text(label, {
+ x: space(5),
+ y: 10,
+ size: 15,
+ strong: primary,
+ color: primary ? "#ffffff" : INK,
+ }),
+ ],
+ });
+}
+
+function message(t: Timeline): LayoutNode {
+ const at = t.select.at + 2;
+ const x = space(5);
+ const lines = BODY.map((line, i) =>
+ text(line, {
+ x,
+ y: 232 + i * 30,
+ size: 17,
+ color: line === REQUEST.question ? INK : SOFT,
+ }),
+ );
+ return Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: PANE_W,
+ height: CH,
+ children: [
+ text(`${REQUEST.client} · Website`, {
+ x,
+ y: 26,
+ size: 14,
+ color: MUTED,
+ }),
+ button(
+ "Reply",
+ { ...REPLY_BUTTON, x: REPLY_BUTTON.x - PANE_X },
+ false,
+ "reply",
+ ),
+ button(
+ "Create task",
+ { ...CREATE_BUTTON, x: CREATE_BUTTON.x - PANE_X },
+ true,
+ "plus",
+ ).animate(press(t.create.down, t.create.up)),
+ rule(0, 72, PANE_W, { color: LINE }),
+ avatar(REQUEST.from, { x, y: 104, size: 44 }),
+ text(REQUEST.from.name, { x: x + 60, y: 105, size: 17, strong: true }),
+ text(REQUEST.email, { x: x + 60, y: 129, size: 14, color: MUTED }),
+ text(REQUEST.time, {
+ x: PANE_W - space(5) - 120,
+ y: 108,
+ width: 120,
+ align: "end",
+ size: 14,
+ color: MUTED,
+ }),
+ text(REQUEST.subject, { x, y: 176, size: 28, strong: true }),
+ ...lines,
+ ],
+ }).animate(rise(0, at, 10, sec(0.4)));
+}
+
+function readingPane(t: Timeline): LayoutNode {
+ const empty = Layer.box({
+ position: "absolute",
+ x: 0,
+ y: CH / 2 - 48,
+ width: PANE_W,
+ height: 96,
+ children: [
+ icon("inbox", { x: PANE_W / 2 - 16, y: 0, size: 32, color: EDGE }),
+ text("Select a message to read it", {
+ x: 0,
+ y: 52,
+ width: PANE_W,
+ align: "center",
+ size: 15,
+ color: MUTED,
+ }),
+ ],
+ }).animate(fade(t.select.at, 4, 1, 0));
+ return Layer.box({
+ position: "absolute",
+ x: PANE_X,
+ y: 0,
+ width: PANE_W,
+ height: CH,
+ background: APP,
+ children: [empty, message(t)],
+ });
+}
+
+/** List and reading pane; they make way for the board when the task is saved. */
+export function inbox(t: Timeline): LayoutNode {
+ return Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: PANE_X + PANE_W,
+ height: CH,
+ children: [list(t), readingPane(t)],
+ }).animate(fade(boardIn(t) - 4, 10, 1, 0));
+}
diff --git a/examples/32_relay/src/ui/kit.ts b/examples/32_relay/src/ui/kit.ts
new file mode 100644
index 00000000..01f66a35
--- /dev/null
+++ b/examples/32_relay/src/ui/kit.ts
@@ -0,0 +1,307 @@
+/**
+ * The handful of primitives every Relay screen is built from: text in the
+ * two weights, line icons, initials avatars, raised surfaces and the shared
+ * motions (rise, fade, press).
+ */
+import {
+ type AnimatableNode,
+ Layer,
+ LayerAnimation,
+ LayerStyle,
+ type LayoutNode,
+} from "framefields";
+import { transformPathData } from "framefields/components";
+import {
+ INK,
+ MUTED,
+ REGULAR,
+ SANS,
+ SEMIBOLD,
+ SHADOW,
+ SUBTLE,
+ sec,
+} from "../theme.js";
+
+export interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export const centre = (r: Rect): [number, number] => [
+ r.x + r.width / 2,
+ r.y + r.height / 2,
+];
+
+/** `r` moved by (dx, dy). */
+export const offset = (r: Rect, dx: number, dy: number): Rect => ({
+ ...r,
+ x: r.x + dx,
+ y: r.y + dy,
+});
+
+export interface TextOptions {
+ x: number;
+ y: number;
+ size: number;
+ color?: string;
+ strong?: boolean;
+ width?: number;
+ align?: "start" | "center" | "end";
+ lineHeight?: number;
+ id?: string;
+}
+
+/** Text in one of the film's two weights. */
+export function text(value: string, o: TextOptions) {
+ 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 }),
+ ...(o.lineHeight !== undefined && { lineHeight: o.lineHeight }),
+ fontFamily: SANS,
+ fontSize: o.size,
+ fontWeight: o.strong ? SEMIBOLD : REGULAR,
+ fill: o.color ?? INK,
+ });
+}
+
+/** Line icons on a 24-unit grid. */
+const ICONS = {
+ inbox:
+ "M3 13 L7.5 13 L9.5 16 L14.5 16 L16.5 13 L21 13 M3 13 L6 5 L18 5 L21 13 L21 19 L3 19 Z",
+ tasks: "M3 12 A9 9 0 1 0 21 12 A9 9 0 1 0 3 12 Z M8 12.5 L11 15.5 L16.5 9.5",
+ calendar:
+ "M4 6 L20 6 L20 20 L4 20 Z M4 10.5 L20 10.5 M8.5 3 L8.5 7 M15.5 3 L15.5 7",
+ search: "M4 11 A7 7 0 1 0 18 11 A7 7 0 1 0 4 11 Z M16 16 L21 21",
+ plus: "M12 5 L12 19 M5 12 L19 12",
+ chevron: "M7 10 L12 15 L17 10",
+ close: "M6 6 L18 18 M18 6 L6 18",
+ reply: "M9.5 14.5 L4 9 L9.5 3.5 M4 9 L14 9 A6 6 0 0 1 20 15 L20 20",
+ quote:
+ "M14 7 L17 7 A5 5 0 0 1 17 17 L14 17 M10 17 L7 17 A5 5 0 0 1 7 7 L10 7 M8.5 12 L15.5 12",
+ checklist:
+ "M3.5 7 L5.5 9 L9 5 M12.5 7 L20.5 7 M3.5 15 L5.5 17 L9 13 M12.5 15 L20.5 15",
+ user: "M8 8 A4 4 0 1 0 16 8 A4 4 0 1 0 8 8 Z M4 20.5 C4.5 16.5 8 14.5 12 14.5 C16 14.5 19.5 16.5 20 20.5",
+ folder: "M3 6.5 L9.5 6.5 L11.5 9 L21 9 L21 19 L3 19 Z",
+ status: "M3 12 A9 9 0 1 0 21 12 A9 9 0 1 0 3 12 Z M12 7 L12 12 L15.5 14",
+ tick: "M5 12.5 L10 17 L19 7.5",
+} as const;
+
+export type IconName = keyof typeof ICONS;
+
+export function icon(
+ name: IconName,
+ o: { x: number; y: number; size?: number; color?: string; weight?: number },
+) {
+ const size = o.size ?? 18;
+ const k = size / 24;
+ return Layer.shape("path", {
+ position: "absolute",
+ x: o.x,
+ y: o.y,
+ width: size,
+ height: size,
+ d: transformPathData(ICONS[name], k),
+ fillType: "none",
+ strokeColor: o.color ?? MUTED,
+ strokeWidth: (o.weight ?? 1.8) * k,
+ strokeLineCap: "round",
+ strokeLineJoin: "round",
+ });
+}
+
+/** A filled dot: a fully rounded box, drawn at screen resolution under any zoom. */
+export function dot(o: { x: number; y: number; size: number; color: string }) {
+ return Layer.box({
+ position: "absolute",
+ x: o.x,
+ y: o.y,
+ width: o.size,
+ height: o.size,
+ borderRadius: o.size / 2,
+ background: o.color,
+ });
+}
+
+export interface Person {
+ name: string;
+ initials: string;
+ /** Avatar ground: warm neutrals, so the accent stays the only color. */
+ tone: string;
+}
+
+export function avatar(p: Person, o: { x: number; y: number; size: number }) {
+ return Layer.box({
+ position: "absolute",
+ x: o.x,
+ y: o.y,
+ width: o.size,
+ height: o.size,
+ borderRadius: o.size / 2,
+ background: p.tone,
+ children: [
+ text(p.initials, {
+ x: 0,
+ y: o.size * 0.29,
+ width: o.size,
+ align: "center",
+ size: o.size * 0.38,
+ strong: true,
+ color: INK,
+ }),
+ ],
+ });
+}
+
+/** How far a surface floats: a soft shadow straight down. */
+const ELEVATION = {
+ card: { opacity: 0.08, distance: 2, size: 8 },
+ popover: { opacity: 0.16, distance: 10, size: 28 },
+ modal: { opacity: 0.22, distance: 24, size: 64 },
+} as const;
+
+export function raise<T extends AnimatableNode>(
+ node: T,
+ level: keyof typeof ELEVATION,
+): T {
+ const e = ELEVATION[level];
+ node.withEffect(
+ new LayerStyle({
+ dropShadow: {
+ enabled: true,
+ color: SHADOW,
+ opacity: e.opacity,
+ angle: 90,
+ distance: e.distance,
+ size: e.size,
+ },
+ }),
+ );
+ return node;
+}
+
+/** A 1 px rule. */
+export function rule(
+ x: number,
+ y: number,
+ length: number,
+ o: { vertical?: boolean; color?: string } = {},
+): LayoutNode {
+ return Layer.box({
+ position: "absolute",
+ x,
+ y,
+ width: o.vertical ? 1 : length,
+ height: o.vertical ? length : 1,
+ background: o.color ?? SUBTLE,
+ });
+}
+
+export const EASE = "expo.out";
+
+/** Fade from `from` to `to` over `duration`, starting at `at`. */
+export function fade(at: number, duration = sec(0.3), from = 0, to = 1) {
+ return LayerAnimation.keys("opacity", [
+ [0, from],
+ [at, from, "hold"],
+ [at + duration, to, "power2.out"],
+ ]);
+}
+
+/** Rise into place at `y`, fading in, from `at`. */
+export function rise(
+ y: number,
+ at: number,
+ distance = 12,
+ duration = sec(0.5),
+) {
+ return LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [at, 0, "hold"],
+ [at + duration, 1, "power2.out"],
+ ])
+ .keys("y", [
+ [0, y + distance],
+ [at, y + distance, "hold"],
+ [at + duration, y, EASE],
+ ]);
+}
+
+/** Visible from `at` (in) to `out`, fading both ways. */
+export function shown(at: number, out: number, duration = sec(0.2)) {
+ return LayerAnimation.keys("opacity", [
+ [0, 0],
+ [at, 0, "hold"],
+ [at + duration, 1, "power2.out"],
+ [out, 1, "hold"],
+ [out + duration, 0, "power2.in"],
+ ]);
+}
+
+/** Shown only from `from` up to `to`: a hard cut in and out, for a surface handed between views. */
+export function during(from: number, to: number) {
+ return LayerAnimation.keys("opacity", [
+ [0, 0],
+ [from - 1, 0, "hold"],
+ [from, 1, "hold"],
+ [to, 1, "hold"],
+ [to + 1, 0, "hold"],
+ ]);
+}
+
+/** `r` scaled by `k` about its centre. */
+export const shrink = (r: Rect, k: number): Rect => ({
+ x: r.x + (r.width * (1 - k)) / 2,
+ y: r.y + (r.height * (1 - k)) / 2,
+ width: r.width * k,
+ height: r.height * k,
+});
+
+export interface Reshape {
+ from: Rect;
+ to: Rect;
+ /** Corner radius at each end. */
+ radius: [number, number];
+ at: number;
+ until: number;
+ ease?: string;
+}
+
+/** Carries a box from one rect (and corner radius) to another. */
+export function reshape(m: Reshape) {
+ const ease = m.ease ?? "power3.inOut";
+ const track = (
+ prop: "x" | "y" | "width" | "height" | "borderRadius",
+ a: number,
+ b: number,
+ ) =>
+ LayerAnimation.keys(prop, [
+ [0, a],
+ [m.at, a, "hold"],
+ [m.until, b, ease],
+ ]);
+ return LayerAnimation.merge(
+ track("x", m.from.x, m.to.x),
+ track("y", m.from.y, m.to.y),
+ track("width", m.from.width, m.to.width),
+ track("height", m.from.height, m.to.height),
+ track("borderRadius", m.radius[0], m.radius[1]),
+ );
+}
+
+/** A press: shrink while the button is down, spring back on release. */
+export function press(down: number, up: number) {
+ return LayerAnimation.keys("scale", [
+ [0, 1],
+ [down, 1, "hold"],
+ [down + 3, 0.96, "power2.out"],
+ [up, 0.96, "hold"],
+ [up + sec(0.3), 1, "back.out(2.2)"],
+ ]);
+}
diff --git a/examples/32_relay/src/ui/layout.ts b/examples/32_relay/src/ui/layout.ts
new file mode 100644
index 00000000..ec379ccd
--- /dev/null
+++ b/examples/32_relay/src/ui/layout.ts
@@ -0,0 +1,137 @@
+/**
+ * Where everything sits inside the app window, in content px (the area below
+ * the title bar). The film aims the pointer and the camera at these rects.
+ */
+import { FRAME, space } from "../theme.js";
+import type { Rect } from "./kit.js";
+
+/** Height of the window's title bar (AppFrame, kind "window"). */
+export const TITLE_BAR = 46;
+export const CW = FRAME.width;
+export const CH = FRAME.height - TITLE_BAR;
+
+export const SIDEBAR_W = 248;
+/** Sidebar rows: nav and projects share one rhythm. */
+export const NAV_ROW = 40;
+export const NAV_Y = 116;
+export const PROJECTS_Y = 280;
+
+// ── Inbox ────────────────────────────────────────────────────────────────
+
+export const LIST_X = SIDEBAR_W;
+export const LIST_W = 480;
+export const LIST_TOP = 72;
+export const ROW_H = 96;
+export const PANE_X = LIST_X + LIST_W;
+export const PANE_W = CW - PANE_X;
+
+/** The new request: the inbox's first row. */
+export const REQUEST_ROW: Rect = {
+ x: LIST_X,
+ y: LIST_TOP,
+ width: LIST_W,
+ height: ROW_H,
+};
+
+export const CREATE_BUTTON: Rect = {
+ x: CW - space(4) - 152,
+ y: space(2),
+ width: 152,
+ height: 40,
+};
+export const REPLY_BUTTON: Rect = {
+ x: CREATE_BUTTON.x - space(1.5) - 96,
+ y: space(2),
+ width: 96,
+ height: 40,
+};
+
+// ── New task modal (modal-local rects; MODAL places them) ────────────────
+
+export const MODAL: Rect = {
+ x: SIDEBAR_W + (CW - SIDEBAR_W - 640) / 2,
+ y: (CH - 700) / 2,
+ width: 640,
+ height: 700,
+};
+/** A modal-local rect in content px. */
+export const inModal = (r: Rect): Rect => ({
+ ...r,
+ x: MODAL.x + r.x,
+ y: MODAL.y + r.y,
+});
+
+const FIELD_X = 160;
+const FIELD_W = 280;
+const FIELD_H = 40;
+const PROP_Y = 212;
+const PROP_STEP = 52;
+export const propertyY = (i: number) => PROP_Y + i * PROP_STEP;
+const field = (i: number): Rect => ({
+ x: FIELD_X,
+ y: propertyY(i),
+ width: FIELD_W,
+ height: FIELD_H,
+});
+export const ASSIGNEE_FIELD = field(0);
+export const DUE_FIELD = field(1);
+export const PROJECT_FIELD = field(2);
+export const STATUS_FIELD = field(3);
+
+export const OPTION_H = 44;
+/** A menu under a field, `count` options tall. */
+export const menuUnder = (f: Rect, count: number): Rect => ({
+ x: f.x,
+ y: f.y + f.height + space(0.5),
+ width: f.width,
+ height: count * OPTION_H + space(1),
+});
+export const optionIn = (menu: Rect, i: number): Rect => ({
+ x: menu.x + space(0.5),
+ y: menu.y + space(0.5) + i * OPTION_H,
+ width: menu.width - space(1),
+ height: OPTION_H,
+});
+
+export const CHECKLIST_Y = 440;
+export const CHECK_ROW = 44;
+export const ADD_CHECKLIST: Rect = {
+ x: space(4),
+ y: CHECKLIST_Y + 32,
+ width: 168,
+ height: 40,
+};
+export const FOOTER_Y = 628;
+export const SAVE_BUTTON: Rect = {
+ x: MODAL.width - space(4) - 152,
+ y: FOOTER_Y + space(2),
+ width: 152,
+ height: 40,
+};
+export const CANCEL_BUTTON: Rect = {
+ x: SAVE_BUTTON.x - space(1.5) - 96,
+ y: SAVE_BUTTON.y,
+ width: 96,
+ height: 40,
+};
+
+// ── Board ────────────────────────────────────────────────────────────────
+
+export const BOARD_X = SIDEBAR_W + space(4);
+export const COLUMNS_Y = 128;
+export const COLUMN_GAP = space(2);
+export const COLUMN_W = (CW - BOARD_X - space(4) - 3 * COLUMN_GAP) / 4;
+export const columnX = (i: number) => BOARD_X + i * (COLUMN_W + COLUMN_GAP);
+export const CARDS_Y = COLUMNS_Y + 48;
+export const CARD_H = 96;
+export const CARD_GAP = space(1.5);
+export const CARD_W = COLUMN_W - space(3);
+export const READY = 1;
+
+/** A card's slot in a column, in content px. */
+export const cardSlot = (column: number, i: number): Rect => ({
+ x: columnX(column) + space(1.5),
+ y: CARDS_Y + i * (CARD_H + CARD_GAP),
+ width: CARD_W,
+ height: CARD_H,
+});
diff --git a/examples/32_relay/src/ui/sidebar.ts b/examples/32_relay/src/ui/sidebar.ts
new file mode 100644
index 00000000..b6de70da
--- /dev/null
+++ b/examples/32_relay/src/ui/sidebar.ts
@@ -0,0 +1,207 @@
+/**
+ * The sidebar: workspace, search, the three places you work from, and the
+ * client projects. The highlight walks from Inbox to the project when the
+ * task is saved.
+ */
+import { Layer, LayerAnimation, type LayoutNode } from "framefields";
+import {
+ ACCENT,
+ APP,
+ EDGE,
+ INK,
+ LINE,
+ MUTED,
+ SIDEBAR,
+ SOFT,
+ sec,
+ space,
+} from "../theme.js";
+import { relayMark } from "./brand.js";
+import { PROJECTS, SAM } from "./data.js";
+import { avatar, type IconName, icon, rule, text } from "./kit.js";
+import { CH, NAV_ROW, NAV_Y, PROJECTS_Y, SIDEBAR_W } from "./layout.js";
+import { boardIn, type Timeline } from "./timeline.js";
+
+const NAV: Array<{ label: string; icon: IconName }> = [
+ { label: "Inbox", icon: "inbox" },
+ { label: "My tasks", icon: "tasks" },
+ { label: "Calendar", icon: "calendar" },
+];
+
+const ROW_X = space(1);
+const ROW_W = SIDEBAR_W - space(2);
+const ROW_H = 36;
+const HIGHLIGHT = "#ebe8e1";
+
+/** Label color: active (ink) between `from` and `to`, soft otherwise. */
+function activeFill(from: number | null, to: number | null) {
+ const keys: Array<[number, string, string?]> = [[0, from === 0 ? INK : SOFT]];
+ if (from !== null && from > 0) {
+ keys.push([from, SOFT, "hold"], [from + 8, INK, "power2.out"]);
+ }
+ if (to !== null) {
+ keys.push([to, INK, "hold"], [to + 8, SOFT, "power2.out"]);
+ }
+ return LayerAnimation.keys("fill", keys);
+}
+
+function row(
+ label: string,
+ y: number,
+ glyph: LayoutNode,
+ fill: LayerAnimation,
+): LayoutNode[] {
+ return [
+ glyph,
+ text(label, { x: space(6), y: y + 9, size: 15, color: SOFT }).animate(fill),
+ ];
+}
+
+/** The unread badge: one new request when it lands, cleared once it's read. */
+function unreadBadge(t: Timeline): LayoutNode {
+ const size = 20;
+ return Layer.box({
+ position: "absolute",
+ x: ROW_X + ROW_W - space(1.5) - size,
+ y: NAV_Y + (ROW_H - size) / 2,
+ width: size,
+ height: size,
+ borderRadius: size / 2,
+ background: ACCENT,
+ children: [
+ text("1", {
+ x: 0,
+ y: 2,
+ width: size,
+ align: "center",
+ size: 12,
+ strong: true,
+ color: "#ffffff",
+ }),
+ ],
+ }).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [t.landed, 0, "hold"],
+ [t.landed + 4, 1, "power2.out"],
+ [t.select.at, 1, "hold"],
+ [t.select.at + 6, 0, "power2.in"],
+ ])
+ .keys("scale", [
+ [0, 0.6],
+ [t.landed, 0.6, "hold"],
+ [t.landed + sec(0.35), 1, "back.out(2.4)"],
+ ]),
+ );
+}
+
+export function sidebar(t: Timeline): LayoutNode {
+ const switchAt = boardIn(t);
+ const projectY = PROJECTS_Y;
+ const children: LayoutNode[] = [
+ Layer.box({
+ position: "absolute",
+ x: ROW_X,
+ y: NAV_Y,
+ width: ROW_W,
+ height: ROW_H,
+ borderRadius: space(1),
+ background: HIGHLIGHT,
+ }).animate(
+ LayerAnimation.keys("y", [
+ [0, NAV_Y],
+ [switchAt, NAV_Y, "hold"],
+ [switchAt + sec(0.45), projectY, "expo.inOut"],
+ ]),
+ ),
+ relayMark({ x: space(2.5), y: space(2.5), size: 28 }),
+ text("Fieldwork", { x: 60, y: 25, size: 15, strong: true }),
+ icon("chevron", { x: 140, y: 27, size: 16 }),
+ Layer.box({
+ position: "absolute",
+ x: space(2),
+ y: 64,
+ width: SIDEBAR_W - space(4),
+ height: 36,
+ borderRadius: space(1),
+ background: APP,
+ borderColor: LINE,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ children: [
+ icon("search", { x: 12, y: 10, size: 16 }),
+ text("Search", { x: 36, y: 9, size: 14, color: MUTED }),
+ text("⌘K", {
+ x: SIDEBAR_W - space(4) - 12 - 40,
+ y: 10,
+ width: 40,
+ align: "end",
+ size: 13,
+ color: MUTED,
+ }),
+ ],
+ }),
+ ];
+
+ NAV.forEach((item, i) => {
+ const y = NAV_Y + i * NAV_ROW;
+ children.push(
+ ...row(
+ item.label,
+ y,
+ icon(item.icon, { x: space(2.5), y: y + 9, size: 18 }),
+ activeFill(i === 0 ? 0 : null, i === 0 ? switchAt : null),
+ ),
+ );
+ });
+ children.push(unreadBadge(t));
+
+ children.push(
+ text("Projects", {
+ x: space(2.5),
+ y: PROJECTS_Y - 32,
+ size: 13,
+ strong: true,
+ color: MUTED,
+ }),
+ );
+ PROJECTS.forEach((name, i) => {
+ const y = PROJECTS_Y + i * NAV_ROW;
+ children.push(
+ ...row(
+ name,
+ y,
+ Layer.box({
+ position: "absolute",
+ x: space(2.5) + 3,
+ y: y + 12,
+ width: 12,
+ height: 12,
+ borderRadius: 4,
+ borderColor: EDGE,
+ borderWidth: 1.5,
+ strokeAlign: "inside",
+ }),
+ activeFill(i === 0 ? switchAt : null, null),
+ ),
+ );
+ });
+
+ children.push(
+ avatar(SAM, { x: space(2), y: CH - 56, size: 32 }),
+ text(SAM.name, { x: 60, y: CH - 56, size: 14, strong: true }),
+ text("Account lead", { x: 60, y: CH - 36, size: 13, color: MUTED }),
+ rule(SIDEBAR_W - 1, 0, CH, { vertical: true, color: LINE }),
+ );
+
+ return Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: SIDEBAR_W,
+ height: CH,
+ background: SIDEBAR,
+ children,
+ });
+}
diff --git a/examples/32_relay/src/ui/task-modal.ts b/examples/32_relay/src/ui/task-modal.ts
new file mode 100644
index 00000000..0340eb44
--- /dev/null
+++ b/examples/32_relay/src/ui/task-modal.ts
@@ -0,0 +1,453 @@
+/**
+ * The "New task" modal, drafted from the request: title and source filled
+ * in, then an owner, a due date and a checklist, and Create task.
+ */
+import {
+ type AnimatableNode,
+ Layer,
+ LayerAnimation,
+ type LayoutNode,
+} from "framefields";
+import {
+ ACCENT,
+ APP,
+ EDGE,
+ INK,
+ LINE,
+ MUTED,
+ SOFT,
+ SUBTLE,
+ sec,
+ space,
+} from "../theme.js";
+import { CHECKLIST, DUE_OPTIONS, FRIDAY, MAYA, REQUEST, TEAM } from "./data.js";
+import { MODAL_RADIUS } from "./handoffs.js";
+import {
+ avatar,
+ dot,
+ during,
+ fade,
+ type IconName,
+ icon,
+ press,
+ type Rect,
+ raise,
+ rise,
+ rule,
+ shown,
+ text,
+} from "./kit.js";
+import {
+ ADD_CHECKLIST,
+ ASSIGNEE_FIELD,
+ CANCEL_BUTTON,
+ CH,
+ CHECK_ROW,
+ CHECKLIST_Y,
+ CW,
+ DUE_FIELD,
+ FOOTER_Y,
+ MODAL,
+ menuUnder,
+ optionIn,
+ PROJECT_FIELD,
+ propertyY,
+ SAVE_BUTTON,
+ STATUS_FIELD,
+} from "./layout.js";
+import {
+ checklistItemAt,
+ handOff,
+ modalIn,
+ modalOpen,
+ modalOut,
+ type Timeline,
+} from "./timeline.js";
+
+const PAD = space(4);
+
+/** A field box; `focus` rings it in the accent while its menu is open. */
+function field(
+ r: Rect,
+ content: LayoutNode[],
+ focus?: { from: number; to: number },
+): LayoutNode[] {
+ const nodes: LayoutNode[] = [
+ Layer.box({
+ position: "absolute",
+ ...r,
+ borderRadius: space(1),
+ background: APP,
+ borderColor: EDGE,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ children: content,
+ }),
+ ];
+ if (focus)
+ nodes.push(
+ Layer.box({
+ position: "absolute",
+ ...r,
+ borderRadius: space(1),
+ borderColor: ACCENT,
+ borderWidth: 2,
+ strokeAlign: "inside",
+ }).animate(shown(focus.from, focus.to, 3)),
+ );
+ return nodes;
+}
+
+/** Field content that swaps from `before` to `after` at `at`. */
+function swap(before: LayoutNode[], after: LayoutNode[], at: number) {
+ const group = (children: LayoutNode[]) =>
+ Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: 280,
+ height: 40,
+ children,
+ });
+ return [
+ group(before).animate(fade(at, 4, 1, 0)),
+ group(after).animate(fade(at, 6)),
+ ];
+}
+
+function property(i: number, label: string, glyph: IconName): LayoutNode[] {
+ const y = propertyY(i);
+ return [
+ icon(glyph, { x: PAD, y: y + 11, size: 18 }),
+ text(label, { x: PAD + 28, y: y + 10, size: 15, color: SOFT }),
+ ];
+}
+
+function properties(t: Timeline): LayoutNode[] {
+ const chosen = t.maya.at + 2;
+ const dated = t.friday.at + 2;
+ const friday = DUE_OPTIONS[FRIDAY]?.date ?? "";
+ return [
+ ...property(0, "Assignee", "user"),
+ ...field(
+ ASSIGNEE_FIELD,
+ swap(
+ [
+ icon("user", { x: 12, y: 11, size: 18 }),
+ text("Unassigned", { x: 40, y: 10, size: 15, color: MUTED }),
+ icon("chevron", { x: 280 - 30, y: 12, size: 16 }),
+ ],
+ [
+ avatar(MAYA, { x: 10, y: 8, size: 24 }),
+ text(MAYA.name, { x: 42, y: 10, size: 15 }),
+ ],
+ chosen,
+ ),
+ { from: t.assignee.at, to: chosen },
+ ),
+ ...property(1, "Due date", "calendar"),
+ ...field(
+ DUE_FIELD,
+ swap(
+ [
+ icon("calendar", { x: 12, y: 11, size: 18 }),
+ text("No due date", { x: 40, y: 10, size: 15, color: MUTED }),
+ icon("chevron", { x: 280 - 30, y: 12, size: 16 }),
+ ],
+ [
+ icon("calendar", { x: 12, y: 11, size: 18, color: INK }),
+ text(friday, { x: 40, y: 10, size: 15 }),
+ ],
+ dated,
+ ),
+ { from: t.due.at, to: dated },
+ ),
+ ...property(2, "Project", "folder"),
+ ...field(PROJECT_FIELD, [
+ icon("folder", { x: 12, y: 11, size: 18 }),
+ text("Brightline website", { x: 40, y: 10, size: 15 }),
+ ]),
+ ...property(3, "Status", "status"),
+ ...field(STATUS_FIELD, [
+ dot({ x: 16, y: 16, size: 8, color: ACCENT }),
+ text("Ready", { x: 40, y: 10, size: 15 }),
+ ]),
+ ];
+}
+
+function checklist(t: Timeline): LayoutNode[] {
+ const first = checklistItemAt(t, 0);
+ const items = CHECKLIST.map((label, i) => {
+ const y = ADD_CHECKLIST.y + i * CHECK_ROW;
+ return Layer.box({
+ position: "absolute",
+ x: PAD,
+ y,
+ width: MODAL.width - 2 * PAD,
+ height: 40,
+ children: [
+ Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 11,
+ width: 18,
+ height: 18,
+ borderRadius: 5,
+ borderColor: EDGE,
+ borderWidth: 1.5,
+ strokeAlign: "inside",
+ }),
+ text(label, { x: 30, y: 10, size: 15 }),
+ ],
+ }).animate(rise(y, checklistItemAt(t, i), 8, sec(0.35)));
+ });
+ const add = Layer.box({
+ position: "absolute",
+ ...ADD_CHECKLIST,
+ borderRadius: space(1),
+ borderColor: EDGE,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ background: APP,
+ children: [
+ icon("plus", { x: 12, y: 11, size: 18, color: SOFT }),
+ text("Add checklist", { x: 38, y: 10, size: 15, color: SOFT }),
+ ],
+ })
+ .animate(press(t.checklist.down, t.checklist.up))
+ .animate(fade(t.checklist.up, 4, 1, 0));
+ return [
+ text("Checklist", { x: PAD, y: CHECKLIST_Y, size: 15, strong: true }),
+ text(`0 of ${CHECKLIST.length}`, {
+ x: MODAL.width - PAD - 120,
+ y: CHECKLIST_Y + 1,
+ width: 120,
+ align: "end",
+ size: 14,
+ color: MUTED,
+ }).animate(fade(first, 8)),
+ add,
+ ...items,
+ ];
+}
+
+function footer(t: Timeline): LayoutNode[] {
+ return [
+ rule(0, FOOTER_Y, MODAL.width, { color: LINE }),
+ Layer.box({
+ position: "absolute",
+ ...CANCEL_BUTTON,
+ borderRadius: space(1),
+ borderColor: EDGE,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ children: [
+ text("Cancel", {
+ x: 0,
+ y: 10,
+ width: CANCEL_BUTTON.width,
+ align: "center",
+ size: 15,
+ }),
+ ],
+ }),
+ Layer.box({
+ position: "absolute",
+ ...SAVE_BUTTON,
+ borderRadius: space(1),
+ background: ACCENT,
+ children: [
+ text("Create task", {
+ x: 0,
+ y: 10,
+ width: SAVE_BUTTON.width,
+ align: "center",
+ size: 15,
+ strong: true,
+ color: "#ffffff",
+ }),
+ ],
+ }).animate(press(t.save.down, t.save.up)),
+ ];
+}
+
+/** A menu of options under a field, open from `open` until `close`. */
+function menu(
+ r: Rect,
+ rows: Array<(o: Rect) => LayoutNode[]>,
+ hover: { index: number; from: number },
+ open: number,
+ close: number,
+): AnimatableNode {
+ const local = (o: Rect): Rect => ({ ...o, x: o.x - r.x, y: o.y - r.y });
+ const highlight = local(optionIn(r, hover.index));
+ return raise(
+ Layer.box({
+ position: "absolute",
+ ...r,
+ anchorY: 0,
+ borderRadius: 10,
+ background: APP,
+ borderColor: LINE,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ children: [
+ Layer.box({
+ position: "absolute",
+ ...highlight,
+ borderRadius: 6,
+ background: SUBTLE,
+ }).animate(fade(hover.from, 4)),
+ ...rows.flatMap((row, i) => row(local(optionIn(r, i)))),
+ ],
+ }),
+ "popover",
+ ).animate(
+ shown(open, close, 4),
+ // Unfolds from under its field.
+ LayerAnimation.create()
+ .keys("y", [
+ [0, r.y - 6],
+ [open, r.y - 6, "hold"],
+ [open + sec(0.25), r.y, "expo.out"],
+ ])
+ .keys("scale", [
+ [0, 0.94],
+ [open, 0.94, "hold"],
+ [open + sec(0.3), 1, "expo.out"],
+ ]),
+ );
+}
+
+function menus(t: Timeline): LayoutNode[] {
+ const assignees = menuUnder(ASSIGNEE_FIELD, TEAM.length);
+ const dates = menuUnder(DUE_FIELD, DUE_OPTIONS.length);
+ return [
+ menu(
+ assignees,
+ TEAM.map(({ person, role }) => (o: Rect) => [
+ avatar(person, { x: o.x + 10, y: o.y + 8, size: 28 }),
+ text(person.name, { x: o.x + 48, y: o.y + 12, size: 15 }),
+ text(role, {
+ x: o.x + o.width - 12 - 110,
+ y: o.y + 13,
+ width: 110,
+ align: "end",
+ size: 13,
+ color: MUTED,
+ }),
+ ]),
+ { index: 0, from: t.mayaHover },
+ t.assignee.at + 1,
+ t.maya.at + 4,
+ ),
+ menu(
+ dates,
+ DUE_OPTIONS.map(({ label, date }) => (o: Rect) => [
+ text(label, { x: o.x + 12, y: o.y + 12, size: 15 }),
+ text(date, {
+ x: o.x + o.width - 12 - 120,
+ y: o.y + 13,
+ width: 120,
+ align: "end",
+ size: 13,
+ color: MUTED,
+ }),
+ ]),
+ { index: FRIDAY, from: t.fridayHover },
+ t.due.at + 1,
+ t.friday.at + 4,
+ ),
+ ];
+}
+
+/**
+ * The scrim over the app and the modal on top, both in content px. The
+ * modal's shell is handed to it by Create task and handed on to the board
+ * (handoffs.ts); its contents fade in once it has grown and out once saved.
+ */
+export function taskModal(t: Timeline): LayoutNode[] {
+ const open = modalIn(t);
+ const close = modalOut(t);
+ const scrim = Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: CW,
+ height: CH,
+ background: "#18181b",
+ }).animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [open, 0, "hold"],
+ [open + sec(0.3), 0.24, "power2.out"],
+ [close, 0.24, "hold"],
+ [close + sec(0.4), 0, "power2.inOut"],
+ ]),
+ );
+ const grown = modalOpen(t);
+ const contents = Layer.box({
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: MODAL.width,
+ height: MODAL.height,
+ children: [
+ text("New task", { x: PAD, y: 25, size: 20, strong: true }),
+ icon("close", { x: MODAL.width - PAD - 20, y: 26, size: 20 }),
+ rule(0, 72, MODAL.width, { color: LINE }),
+ text(REQUEST.subject, { x: PAD, y: 92, size: 26, strong: true }),
+ Layer.box({
+ position: "absolute",
+ x: PAD,
+ y: 136,
+ width: MODAL.width - 2 * PAD,
+ height: 52,
+ borderRadius: 10,
+ background: SUBTLE,
+ children: [
+ icon("quote", { x: 16, y: 16, size: 20 }),
+ text(`${REQUEST.from.name.split(" ")[0]}: “${REQUEST.question}”`, {
+ x: 48,
+ y: 16,
+ size: 15,
+ color: SOFT,
+ }),
+ ],
+ }),
+ ...properties(t),
+ ...checklist(t),
+ ...footer(t),
+ ...menus(t),
+ ],
+ }).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [0, 0],
+ [grown - 2, 0, "hold"],
+ [grown + 6, 1, "power2.out"],
+ [close, 1, "hold"],
+ [close + 4, 0, "power2.in"],
+ ])
+ .keys("y", [
+ [0, 10],
+ [grown - 2, 10, "hold"],
+ [grown + sec(0.4), 0, "expo.out"],
+ ]),
+ );
+ const modal = raise(
+ Layer.box({
+ id: "task-modal",
+ position: "absolute",
+ ...MODAL,
+ borderRadius: MODAL_RADIUS,
+ background: APP,
+ borderColor: LINE,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ children: [contents],
+ }),
+ "modal",
+ ).animate(during(grown, handOff(t)));
+ return [scrim, modal];
+}
diff --git a/examples/32_relay/src/ui/timeline.ts b/examples/32_relay/src/ui/timeline.ts
new file mode 100644
index 00000000..28d6e099
--- /dev/null
+++ b/examples/32_relay/src/ui/timeline.ts
@@ -0,0 +1,53 @@
+/**
+ * The moments the interface reacts to, in composition frames. The film reads
+ * the clicks off the pointer's cues, so moving a waypoint re-times the UI.
+ */
+import { sec } from "../theme.js";
+
+export interface Click {
+ /** The button goes down. */
+ down: number;
+ /** Fully pressed: the click lands. */
+ at: number;
+ /** The button comes back up. */
+ up: number;
+}
+
+export interface Timeline {
+ /** The window starts to rise in. */
+ windowIn: number;
+ /** The request lands in the inbox's first row. */
+ landed: number;
+ select: Click;
+ create: Click;
+ assignee: Click;
+ /** The pointer reaches Maya in the menu. */
+ mayaHover: number;
+ maya: Click;
+ due: Click;
+ fridayHover: number;
+ friday: Click;
+ checklist: Click;
+ save: Click;
+ /** The board hands its new card over to the end card. */
+ sceneOut: number;
+}
+
+/**
+ * Derived moments every view agrees on. The task is one surface the whole
+ * way: Create task grows into the modal, and the modal, once saved, shrinks
+ * into its card on the board.
+ */
+export const modalIn = (t: Timeline) => t.create.at + 2;
+/** The modal has finished growing out of the button. */
+export const modalOpen = (t: Timeline) => modalIn(t) + sec(0.5);
+/** The modal's contents clear once Create task is released… */
+export const modalOut = (t: Timeline) => t.save.up + 2;
+/** …and its empty shell starts for the board. */
+export const handOff = (t: Timeline) => modalOut(t) + 4;
+export const boardIn = (t: Timeline) => t.save.up + 4;
+/** The shell lands as the new card in Ready. */
+export const cardLands = (t: Timeline) => handOff(t) + sec(0.8);
+/** Each checklist item, in order. */
+export const checklistItemAt = (t: Timeline, i: number) =>
+ t.checklist.up + 2 + i * 6;
diff --git a/examples/32_relay/tsconfig.dev.json b/examples/32_relay/tsconfig.dev.json
new file mode 100644
index 00000000..c5e4355b
--- /dev/null
+++ b/examples/32_relay/tsconfig.dev.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig.json",
+ "include": [
+ "src/**/*",
+ "../../nodes/**/*",
+ "../../packages/**/*",
+ "../../node_modules/@framefields/**/*"
+ ]
+}
diff --git a/examples/32_relay/tsconfig.json b/examples/32_relay/tsconfig.json
new file mode 100644
index 00000000..999801f9
--- /dev/null
+++ b/examples/32_relay/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/32_relay/vitest.config.ts b/examples/32_relay/vitest.config.ts
new file mode 100644
index 00000000..be6fcdda
--- /dev/null
+++ b/examples/32_relay/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/pnpm-lock.yaml b/pnpm-lock.yaml
index 50aa5431..c163355a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -498,6 +498,28 @@ importers:
specifier: ^4.1.11
+ examples/32_relay:
+ 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
+ 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':