Skip to content

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

feat(components): install components with `npx framefields add`

okanaslce6d2d6167cf
diff --git a/README.md b/README.md
index 2d440870..147922e0 100644
--- a/README.md
+++ b/README.md
@@ -157,6 +157,31 @@ process.exit(0);
---
+## Components
+
+Ready-made motion pieces you own: a mouse pointer with clicks and drags, a camera that zooms to them, window and device frames, word-timed captions, text reveals, counters, terminals, code blocks, title cards, lower thirds, logo reveals, backdrops, audio waveforms and more. Like a shadcn registry, `framefields add` copies a component's source into your project instead of hiding it in the package, so you can change any curve, glyph or layout.
+
+```bash
+npx framefields list # every component, one line each
+npx framefields add mouse-pointer focus-zoom # writes src/components/<name>/
+```
+
+```typescript
+import { MousePointer } from "./components/mouse-pointer/index.js";
+
+const pointer = MousePointer({
+ path: [{ to: [400, 300] }, { to: [960, 540], click: true }],
+});
+comp.add(pointer);
+
+// Every event is a cue: key a button press or a click sound to it.
+const clickAt = pointer.cues.clicks[0].frame;
+```
+
+Installed components import only `framefields` and the shared toolkit in `framefields/components`, and bring along any component they build on. Files you've edited are never overwritten unless you pass `--overwrite`.
+
+---
+
## AI Gateway
Framefields provides built-in access to the [**AI Gateway**](https://framefields.dev/models), allowing agents and developers to generate cinematic video, images, music, and voiceovers directly from code using hundreds of hosted models. Explore the full model catalog in the [**AI Gateway**](https://framefields.dev/models) or read the integration guide in the [**documentation**](https://framefields.dev/docs/guides/ai/).
diff --git a/examples/30_product_demo/framefields.json b/examples/30_product_demo/framefields.json
new file mode 100644
index 00000000..f76e2d00
--- /dev/null
+++ b/examples/30_product_demo/framefields.json
@@ -0,0 +1,3 @@
+{
+ "components": "src/components"
+}
diff --git a/examples/30_product_demo/src/components/app-frame/index.ts b/examples/30_product_demo/src/components/app-frame/index.ts
new file mode 100644
index 00000000..7cf7da08
--- /dev/null
+++ b/examples/30_product_demo/src/components/app-frame/index.ts
@@ -0,0 +1,608 @@
+/**
+ * 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,
+ contrastRatio,
+ 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 &&
+ (contrastRatio(theme.color.bg, "#000000") ?? 1) < 4);
+ const pal = dark ? PALETTES.dark : PALETTES.light;
+ const radius = props.radius ?? 14 * s;
+ const hasTabs = props.kind === "browser" && (props.tabs?.length ?? 0) > 0;
+ const barH =
+ props.kind === "minimal"
+ ? 0
+ : props.kind === "browser"
+ ? (hasTabs ? 92 : 56) * s
+ : props.kind === "terminal"
+ ? 40 * s
+ : 46 * s;
+
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+ const cues = {
+ urlTyped: [] as Array<{ frame: number }>,
+ loaded: [] as Array<{ frame: number }>,
+ };
+ const font = theme.font.body;
+
+ // Content is laid out from the bar down, in content pixels.
+ const build = (W: number, H: number) => {
+ const bar: LayoutNode[] = [];
+ const lightsY = (hasTabs ? 46 * s : barH) / 2;
+ if (props.kind !== "minimal") {
+ LIGHTS.forEach((color, i) => {
+ bar.push(
+ host.shape("circle", {
+ id: ctx.partId(`light-${i}`),
+ position: "absolute",
+ x: 20 * s + i * 20 * s,
+ y: lightsY - 6 * s,
+ width: 12 * s,
+ height: 12 * s,
+ fillColor: color,
+ }),
+ );
+ });
+ }
+
+ if (props.kind === "browser") {
+ const rowY = hasTabs ? 46 * s : 0;
+ const rowH = hasTabs ? barH - 46 * s : barH;
+ if (hasTabs)
+ bar.push(
+ ...tabStrip(ctx, props.tabs ?? [], {
+ x: 92 * s,
+ H: 46 * s,
+ s,
+ pal,
+ font,
+ W,
+ }),
+ );
+ // Back / forward.
+ const navX = hasTabs ? 20 * s : 92 * s;
+ [0, 1].forEach((i) => {
+ const cx = navX + i * 30 * s + 8 * s;
+ const cy = rowY + rowH / 2;
+ const dir = i === 0 ? -1 : 1;
+ bar.push(
+ host.shape("path", {
+ id: ctx.partId(`nav-${i}`),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: barH,
+ d: `M${cx - dir * 3 * s} ${cy - 6 * s} L${cx + dir * 3 * s} ${cy} L${cx - dir * 3 * s} ${cy + 6 * s}`,
+ fillType: "none",
+ fillColor: pal.muted,
+ strokeColor: i === 0 ? pal.muted : pal.edge,
+ strokeWidth: 1.8 * s,
+ strokeLineCap: "round",
+ strokeLineJoin: "round",
+ }),
+ );
+ });
+ if (props.url !== undefined) {
+ bar.push(
+ ...urlField(ctx, props.url, {
+ W,
+ rowY,
+ rowH,
+ s,
+ pal,
+ font,
+ fps,
+ cues,
+ accent: theme.color.accent,
+ parts,
+ }),
+ );
+ }
+ } else if (props.title) {
+ bar.push(
+ host.text(props.title, {
+ id: ctx.partId("title"),
+ position: "absolute",
+ x: 0,
+ y: barH / 2 - 9 * s,
+ width: W,
+ align: "center",
+ fontFamily: props.kind === "terminal" ? theme.font.mono : font,
+ fontSize: 13 * s,
+ fontWeight: 500,
+ fill: pal.muted,
+ }),
+ );
+ }
+
+ const contentChildren: LayoutNode[] =
+ props.content === undefined
+ ? []
+ : typeof props.content === "string"
+ ? [
+ host.media(props.content, {
+ id: ctx.partId("media"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H - barH,
+ fit: props.fit,
+ }),
+ ]
+ : Array.isArray(props.content)
+ ? props.content
+ : [props.content];
+ const content = host.box({
+ id: ctx.partId("content"),
+ position: "absolute",
+ x: 0,
+ y: barH,
+ width: W,
+ height: H - barH,
+ background:
+ props.contentBackground ??
+ (props.kind === "terminal" ? "#0c0c0e" : pal.content),
+ overflow: "hidden",
+ children: contentChildren,
+ });
+ const chrome = host.box({
+ id: ctx.partId("chrome"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ background: props.kind === "terminal" ? "#16161a" : pal.chrome,
+ borderRadius: radius,
+ borderColor: pal.edge,
+ borderWidth: 1,
+ strokeAlign: "inside",
+ overflow: "hidden",
+ children: [
+ ...(barH > 0
+ ? [
+ host.box({
+ id: ctx.partId("bar"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: barH,
+ children: bar,
+ }),
+ host.box({
+ id: ctx.partId("divider"),
+ position: "absolute",
+ x: 0,
+ y: barH - 1,
+ width: W,
+ height: 1,
+ background: pal.line,
+ }),
+ ]
+ : []),
+ content,
+ ],
+ });
+ const children: LayoutNode[] = [];
+ if (props.elevation > 0) {
+ const e = props.elevation;
+ // The shadow lives on its own plate: the chrome clips its content.
+ const plate = host.box({
+ id: ctx.partId("shadow"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ background: pal.chrome,
+ borderRadius: radius,
+ });
+ host.style(plate, {
+ dropShadow: {
+ color: "#000000",
+ opacity: [0, 0.3, 0.45, 0.6][e],
+ angle: 90,
+ distance: [0, 8, 22, 40][e],
+ size: [0, 22, 48, 80][e],
+ spread: 0,
+ },
+ });
+ children.push(plate);
+ parts.shadow = plate;
+ }
+ children.push(chrome);
+ Object.assign(parts, { chrome, content });
+ return { children, content };
+ };
+
+ return {
+ width,
+ height,
+ duration: null,
+ cues: cues as AppFrameCues,
+ parts,
+ children: 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: 500,
+ });
+ const w = Math.min(240 * o.s, Math.max(120 * o.s, m.width + 40 * o.s));
+ out.push(
+ host.box({
+ id: ctx.partId(`tab-${i}`),
+ position: "absolute",
+ x,
+ y: 8 * o.s,
+ width: w,
+ height: o.H - 8 * o.s,
+ background: active ? o.pal.field : "transparent",
+ borderRadius: 9 * o.s,
+ children: [
+ host.text(label, {
+ id: ctx.partId(`tab-${i}-text`),
+ position: "absolute",
+ x: 14 * o.s,
+ y: (o.H - 8 * o.s) / 2 - fontSize * 0.62,
+ width: w - 28 * o.s,
+ fontFamily: o.font,
+ fontSize,
+ fontWeight: 500,
+ fill: active ? o.pal.text : o.pal.muted,
+ }),
+ ],
+ }),
+ );
+ x += w + 4 * o.s;
+ });
+ return out;
+}
+
+function urlField(
+ ctx: Parameters<typeof appFrame.build>[0],
+ url: string | { text: string; typeAt?: number; cps: number },
+ o: {
+ W: number;
+ rowY: number;
+ rowH: number;
+ s: number;
+ pal: (typeof PALETTES)["dark" | "light"];
+ font: string;
+ fps: number;
+ cues: {
+ urlTyped: Array<{ frame: number }>;
+ loaded: Array<{ frame: number }>;
+ };
+ accent: string;
+ parts: Record<string, Animatable<LayoutNode>>;
+ },
+): LayoutNode[] {
+ const { host } = ctx;
+ const text = typeof url === "string" ? url : url.text;
+ const fieldW = Math.min(620 * o.s, o.W * 0.46);
+ const fieldH = 32 * o.s;
+ const fieldX = (o.W - fieldW) / 2;
+ const fieldY = o.rowY + (o.rowH - fieldH) / 2;
+ const fontSize = 13.5 * o.s;
+ const m = host.measure(text, { fontFamily: o.font, fontSize });
+ const lockW = 14 * o.s;
+ const textX = (fieldW - m.width - lockW) / 2 + lockW;
+ const out: LayoutNode[] = [];
+
+ const label = host.text(text, {
+ id: ctx.partId("url"),
+ position: "absolute",
+ x: textX,
+ y: fieldH / 2 - m.lineHeight / 2,
+ fontFamily: o.font,
+ fontSize,
+ fill: o.pal.text,
+ });
+ // A small padlock: shackle + body.
+ const lx = textX - lockW;
+ const ly = fieldH / 2;
+ const lock = host.shape("path", {
+ id: ctx.partId("lock"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: fieldW,
+ height: fieldH,
+ d: `M${lx + 2.2 * o.s} ${ly - 1 * o.s} L${lx + 2.2 * o.s} ${ly - 3.4 * o.s} C${lx + 2.2 * o.s} ${ly - 6.4 * o.s} ${lx + 7.8 * o.s} ${ly - 6.4 * o.s} ${lx + 7.8 * o.s} ${ly - 3.4 * o.s} L${lx + 7.8 * o.s} ${ly - 1 * o.s}`,
+ fillType: "none",
+ fillColor: o.pal.muted,
+ strokeColor: o.pal.muted,
+ strokeWidth: 1.4 * o.s,
+ strokeLineCap: "round",
+ });
+ const lockBody = host.box({
+ id: ctx.partId("lock-body"),
+ position: "absolute",
+ x: lx + 0.6 * o.s,
+ y: ly - 1.4 * o.s,
+ width: 8.8 * o.s,
+ height: 6.6 * o.s,
+ background: o.pal.muted,
+ borderRadius: 1.6 * o.s,
+ });
+ const fieldChildren: LayoutNode[] = [lock, lockBody, label];
+ o.parts.url = label;
+
+ if (typeof url === "object" && url.typeAt !== undefined) {
+ const perChar = Math.max(1, Math.round(o.fps / url.cps));
+ const start = url.typeAt;
+ // The text track is a reveal amount: ≤ 1 is a fraction, > 1 a count.
+ const keys: KeyframeTuple[] = [[0, 0]];
+ for (let i = 1; i <= text.length; i++) {
+ keys.push([start + i * perChar, i === 1 ? 1 / text.length : i, "hold"]);
+ }
+ label.animate(LayerAnimation.keys("text" as AnimatableProp, keys));
+ const typed = start + text.length * perChar;
+ // Caret follows the last typed glyph, then blinks a few times.
+ const caretKeys: KeyframeTuple[] = [[0, textX]];
+ for (let i = 1; i <= text.length; i++)
+ caretKeys.push([start + i * perChar, textX + m.caretX(i), "hold"]);
+ const caret = host.box({
+ id: ctx.partId("caret"),
+ position: "absolute",
+ x: textX,
+ y: fieldH / 2 - fontSize * 0.7,
+ width: 1.6 * o.s,
+ height: fontSize * 1.4,
+ background: o.accent,
+ });
+ const blink: KeyframeTuple[] = [
+ [0, 0],
+ [start, 1, "hold"],
+ ];
+ const half = Math.round(o.fps * 0.5);
+ for (
+ let f = typed + half, on = false;
+ f < typed + half * 6;
+ f += half, on = !on
+ )
+ blink.push([f, on ? 1 : 0, "hold"]);
+ blink.push([typed + half * 6, 0, "hold"]);
+ caret.animate(
+ LayerAnimation.keys("x", caretKeys),
+ LayerAnimation.keys("opacity", blink),
+ );
+ fieldChildren.push(caret);
+ o.parts.caret = caret;
+ o.cues.urlTyped.push({ frame: typed });
+
+ // Load bar along the bottom of the toolbar after "enter".
+ const loadStart = typed + Math.round(o.fps * 0.15);
+ const loadEnd = loadStart + Math.round(o.fps * 0.9);
+ const bar = host.box({
+ id: ctx.partId("load"),
+ position: "absolute",
+ x: 0,
+ y: o.rowY + o.rowH - 2 * o.s,
+ width: 0,
+ height: 2 * o.s,
+ background: o.accent,
+ });
+ bar.animate(
+ LayerAnimation.keys("width", [
+ [0, 0],
+ [loadStart, 0, "hold"],
+ [loadStart + Math.round(o.fps * 0.35), o.W * 0.62, "power2.out"],
+ [loadEnd, o.W, "power3.inOut"],
+ ]),
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [loadStart, 1, "hold"],
+ [loadEnd, 1],
+ [loadEnd + Math.round(o.fps * 0.3), 0, "power2.out"],
+ ]),
+ );
+ out.push(bar);
+ o.parts.load = bar;
+ o.cues.loaded.push({ frame: loadEnd });
+ }
+
+ const field = host.box({
+ id: ctx.partId("url-field"),
+ position: "absolute",
+ x: fieldX,
+ y: fieldY,
+ width: fieldW,
+ height: fieldH,
+ background: o.pal.field,
+ borderRadius: 9 * o.s,
+ overflow: "hidden",
+ children: fieldChildren,
+ });
+ o.parts["url-field"] = field;
+ out.unshift(field);
+ return out;
+}
+
+/**
+ * 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/30_product_demo/src/components/focus-zoom/index.ts b/examples/30_product_demo/src/components/focus-zoom/index.ts
new file mode 100644
index 00000000..caf21cb3
--- /dev/null
+++ b/examples/30_product_demo/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, theme, fps } = ctx;
+ const W = ctx.requested.width ?? 1920 * theme.scale;
+ const H = ctx.requested.height ?? 1080 * theme.scale;
+ // By default the push starts early enough to run at its natural pace.
+ const lead =
+ props.lead ?? Math.round((0.55 + 0.75 * props.smoothing) * fps) + 2;
+
+ const shots: ShotWindow[] = [];
+ if (props.follow) {
+ const pointer = props.follow;
+ // Click frames are in the pointer's parent timeline — the content —
+ // which starts with this component.
+ const clicks: ClickEvent[] = pointer.cues.clicks.map((c) => ({
+ frame: c.frame,
+ point: c.point,
+ }));
+ shots.push(
+ ...shotsFromClicks(clicks, {
+ width: W,
+ height: H,
+ lead,
+ idle: props.idle,
+ zoom: props.zoom,
+ maxZoom: props.maxZoom,
+ padding: props.padding,
+ }),
+ );
+ }
+ const manual = [...(props.shots ?? [])].sort((a, b) => a.at - b.at);
+ manual.forEach((shot, i) => {
+ const next = manual[i + 1];
+ const end =
+ shot.hold !== undefined
+ ? shot.at + shot.hold
+ : (next?.at ?? shot.at + Math.round(fps * 3));
+ if (shot.target === "full") {
+ shots.push({ start: shot.at, end, zoom: 1, center: [W / 2, H / 2] });
+ return;
+ }
+ const resolved = resolveTarget(shot.target, {
+ measure: host.measure,
+ fps,
+ });
+ if (resolved.kind === "dynamic") {
+ shots.push({
+ start: shot.at,
+ end,
+ zoom: shot.zoom ?? props.zoom,
+ center: (f) => targetPoint(resolved, f),
+ });
+ return;
+ }
+ const r = boundsOf(resolved.rects);
+ const fit = Math.min(
+ W / (r.width + props.padding * 2),
+ H / (r.height + props.padding * 2),
+ );
+ const zoom = Math.min(
+ props.maxZoom,
+ shot.zoom ?? Math.max(1, Math.min(props.zoom, fit)),
+ );
+ shots.push({
+ start: shot.at,
+ end,
+ zoom,
+ center: [r.x + r.width / 2, r.y + r.height / 2],
+ });
+ });
+ shots.sort((a, b) => a.start - b.start);
+
+ const lastEnd = Math.max(0, ...shots.map((s) => s.end));
+ const length = props.length ?? lastEnd + Math.round(fps * 1.5) + 1;
+ let bounds:
+ | { x: number; y: number; width: number; height: number }
+ | undefined;
+ if (props.bounds !== undefined && props.bounds !== "full") {
+ const resolved = resolveTarget(props.bounds, {
+ measure: host.measure,
+ fps,
+ });
+ if (resolved.kind !== "static")
+ throw new Error("FocusZoom: `bounds` must be a static target.");
+ bounds = boundsOf(resolved.rects);
+ }
+ const plan = solveCamera({
+ width: W,
+ height: H,
+ length,
+ fps,
+ shots,
+ smoothing: props.smoothing,
+ clamp: props.clamp,
+ bounds,
+ });
+
+ const camera = host.box({
+ id: ctx.partId("camera"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ anchorX: 0,
+ anchorY: 0,
+ ...(props.smear !== false && { motionBlurShutter: SMEAR[props.smear] }),
+ children: Array.isArray(props.content) ? props.content : [props.content],
+ });
+ camera.animate(
+ LayerAnimation.keys("x", bakeSamples(plan.x, 0, { tolerance: 0.15 })),
+ LayerAnimation.keys("y", bakeSamples(plan.y, 0, { tolerance: 0.15 })),
+ LayerAnimation.keys(
+ "scale",
+ bakeSamples(plan.scale, 0, { tolerance: 0.0004 }),
+ ),
+ );
+ const clip = host.box({
+ id: ctx.partId("clip"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ overflow: "hidden",
+ children: [camera],
+ });
+
+ const stateAt = (local: number) =>
+ plan.states[
+ Math.max(0, Math.min(plan.states.length - 1, Math.round(local)))
+ ] ?? { cx: W / 2, cy: H / 2, zoom: 1 };
+ return {
+ children: [clip],
+ width: W,
+ height: H,
+ duration: null,
+ origin: [0, 0],
+ cues: { shots: plan.shots } as FocusZoomCues,
+ parts: { camera, clip },
+ api: (placement): FocusZoomApi => ({
+ toScreen(point, frame) {
+ const s = stateAt(frame - placement.start);
+ return [
+ placement.x + W / 2 + (point[0] - s.cx) * s.zoom,
+ placement.y + H / 2 + (point[1] - s.cy) * s.zoom,
+ ];
+ },
+ cameraAt(frame) {
+ const s = stateAt(frame - placement.start);
+ return { center: [s.cx, s.cy], zoom: s.zoom };
+ },
+ }),
+ };
+ },
+});
+
+/**
+ * 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/30_product_demo/src/components/focus-zoom/plan.ts b/examples/30_product_demo/src/components/focus-zoom/plan.ts
new file mode 100644
index 00000000..aa2863e6
--- /dev/null
+++ b/examples/30_product_demo/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/30_product_demo/src/components/mouse-pointer/glyphs.ts b/examples/30_product_demo/src/components/mouse-pointer/glyphs.ts
new file mode 100644
index 00000000..5013bfe2
--- /dev/null
+++ b/examples/30_product_demo/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/30_product_demo/src/components/mouse-pointer/index.ts b/examples/30_product_demo/src/components/mouse-pointer/index.ts
new file mode 100644
index 00000000..15df4728
--- /dev/null
+++ b/examples/30_product_demo/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 1920 × 1080. */
+ area: z
+ .object({ width: z.number().positive(), height: z.number().positive() })
+ .default({ width: 1920, height: 1080 }),
+ }),
+ defaults: { enter: false, exit: false },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const size = props.size ?? 44 * theme.scale;
+ const k = size / 24;
+ const accent = props.accent ?? theme.color.accent;
+ const outlineWidth = props.outlineWidth ?? size / 16;
+ const { width: W, height: H } = props.area;
+
+ const resolvePoint = (target: Target): { point: PointAt; id?: string } => {
+ const resolved = resolveTarget(target, { measure: host.measure, fps });
+ const isText =
+ typeof target === "object" &&
+ !Array.isArray(target) &&
+ "text" in target;
+ const node =
+ typeof target === "object" && !Array.isArray(target) && "node" in target
+ ? target.node
+ : undefined;
+ const id = typeof node?.id === "string" ? node.id : undefined;
+ if (resolved.kind === "static") {
+ const p = targetPoint(resolved, 0, isText);
+ return { point: () => p, id };
+ }
+ return { point: (frame) => targetPoint(resolved, frame, isText), id };
+ };
+ const edgePoint = (edge: Edge, near: Vec2): Vec2 => {
+ const off = size * 1.5;
+ if (edge === "left") return [-off, near[1]];
+ if (edge === "right") return [W + off, near[1]];
+ if (edge === "top") return [near[0], -off];
+ return [near[0], H + off];
+ };
+
+ const waypoints: PlannedWaypoint[] = props.path.map((wp) => {
+ const { point, id } = resolvePoint(wp.to);
+ const click =
+ wp.click === undefined || wp.click === false
+ ? undefined
+ : wp.click === true
+ ? { count: 1 }
+ : typeof wp.click === "number"
+ ? { count: wp.click }
+ : wp.click;
+ return {
+ point,
+ at: wp.at,
+ dwell: wp.dwell,
+ clicks: click?.count,
+ hold: click && "hold" in click ? click.hold : undefined,
+ drag: wp.drag ? resolvePoint(wp.drag).point : undefined,
+ cursor: wp.cursor,
+ targetId: id,
+ };
+ });
+ const firstPoint = waypoints[0]?.point(0) ?? [0, 0];
+ const lastPoint = waypoints[waypoints.length - 1]?.point(0) ?? firstPoint;
+ const fromPoint =
+ props.from === undefined
+ ? undefined
+ : typeof props.from === "string"
+ ? edgePoint(props.from, firstPoint)
+ : resolvePoint(props.from).point(0);
+ const toPoint =
+ props.to === undefined
+ ? undefined
+ : typeof props.to === "string"
+ ? edgePoint(props.to, lastPoint)
+ : resolvePoint(props.to).point(0);
+
+ const fade = Math.max(1, Math.round((7 * fps) / 30));
+ const plan = planPointer({
+ waypoints,
+ fps,
+ style: props.style,
+ motion: props.motion,
+ speed: props.speed,
+ drift: props.drift,
+ seed: ctx.seed,
+ from: fromPoint,
+ to: toPoint,
+ hoverRegions: props.hoverRegions.map((r) => {
+ const resolved = resolveTarget(r.target, {
+ measure: host.measure,
+ fps,
+ });
+ if (resolved.kind !== "static")
+ throw new Error(
+ "MousePointer: hover regions must be static targets.",
+ );
+ const rects = resolved.rects;
+ const x0 = Math.min(...rects.map((q) => q.x));
+ const y0 = Math.min(...rects.map((q) => q.y));
+ const x1 = Math.max(...rects.map((q) => q.x + q.width));
+ const y1 = Math.max(...rects.map((q) => q.y + q.height));
+ return {
+ rect: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 },
+ style: r.style,
+ };
+ }),
+ appear: fromPoint ? 0 : fade,
+ vanish: toPoint ? 0 : fade,
+ });
+
+ // Visibility: pop in at the start, fade out at the end (unless it
+ // travels on or off frame, which needs no fade).
+ const visibility = (f: number): number => {
+ const inAt = fromPoint ? 1 : smooth(f / fade);
+ const outAt = toPoint ? 1 : 1 - smooth((f - plan.vanishAt) / fade);
+ return Math.max(0, Math.min(inAt, outAt));
+ };
+ const appearScale = (f: number): number => {
+ if (fromPoint) return 1;
+ const t = f / fade;
+ return t >= 1 ? 1 : 0.6 + 0.4 * backOut(Math.max(0, t));
+ };
+ const pressScale = pressProfile(plan, props.feedback);
+
+ // ── Glyph boxes, one per style used ──────────────────────────────
+ const used = [
+ ...new Set([props.style, ...plan.styles.map((w) => w.style)]),
+ ];
+ const margin = Math.ceil(size * 0.4);
+ const box = size + margin * 2;
+
+ // Label geometry first: it sizes the moving box.
+ const labelText =
+ props.label === undefined
+ ? undefined
+ : typeof props.label === "string"
+ ? props.label
+ : props.label.text;
+ const labelFont = Math.round(size * 0.4);
+ const labelMetrics =
+ labelText === undefined
+ ? undefined
+ : host.measure(labelText, {
+ fontFamily: theme.font.body,
+ fontSize: labelFont,
+ fontWeight: 600,
+ });
+ const labelPadX = Math.round(labelFont * 0.62);
+ const labelH = Math.round(labelFont * 1.8);
+ const labelW = labelMetrics
+ ? Math.ceil(labelMetrics.width + labelPadX * 2)
+ : 0;
+ const labelX = Math.round(size * 0.46);
+ const labelY = Math.round(size * 0.6);
+
+ // The moving part is a real box centred on the hotspot (very small
+ // boxes are culled), big enough for the glyph, its shadow and label.
+ const half = Math.ceil(
+ Math.max(
+ box,
+ labelMetrics ? Math.max(labelX + labelW, labelY + labelH) + 24 : 0,
+ ),
+ );
+ const extent = half * 2;
+ const swap = Math.max(1, Math.round((2 * fps) / 30));
+ const glyphBoxes: Array<Animatable<LayoutNode>> = [];
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+
+ for (const style of used) {
+ const glyph = glyphFor(style);
+ const [hx, hy] = glyph.hotspot;
+ const weight = (f: number) => styleWeight(plan, style, f, swap);
+ const opacity = samples(plan.length, (f) => visibility(f) * weight(f));
+ const scale = samples(
+ plan.length,
+ (f) => appearScale(f) * pressScale(f) * (0.9 + 0.1 * weight(f)),
+ );
+ const shapes = glyphShapes(ctx, glyph, style, {
+ k,
+ margin,
+ color: props.color,
+ accent,
+ outline: props.outline === false ? null : props.outline,
+ outlineWidth,
+ mode: props.outlineMode,
+ });
+ const g = host.box({
+ id: ctx.partId(`glyph-${style}`),
+ position: "absolute",
+ x: half - hx * k - margin,
+ y: half - hy * k - margin,
+ width: box,
+ height: box,
+ anchorX: (hx * k + margin) / box,
+ anchorY: (hy * k + margin) / box,
+ children: shapes,
+ });
+ g.animate(
+ track("opacity", bakeSamples(opacity, 0, { tolerance: 0.004 })),
+ );
+ g.animate(track("scale", bakeSamples(scale, 0, { tolerance: 0.002 })));
+ if (props.autoOrient && glyph.directional) {
+ const angles = unwrap(
+ plan.angles.map((a) => (a * 180) / Math.PI + 135),
+ );
+ g.animate(
+ track("rotation", bakeSamples(angles, 0, { tolerance: 0.3 })),
+ );
+ }
+ if (props.shadow) {
+ host.style(g, {
+ dropShadow: {
+ color: "#000000",
+ opacity: 0.34,
+ angle: 90,
+ distance: Math.max(1, k * 1.2),
+ size: k * 4,
+ spread: 0,
+ },
+ });
+ }
+ glyphBoxes.push(g);
+ parts[`glyph-${style}`] = g;
+ }
+ const cursor = host.box({
+ id: ctx.partId("cursor"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: extent,
+ height: extent,
+ children: glyphBoxes,
+ });
+
+ // ── Label ────────────────────────────────────────────────────────
+ const motionChildren: LayoutNode[] = [cursor];
+ if (labelText !== undefined && labelMetrics) {
+ const bg =
+ (typeof props.label === "object" && props.label.color) || accent;
+ // White on a saturated tag reads as a name tag; fall back to dark
+ // ink only when white would be illegible.
+ const ink =
+ (contrastRatio("#ffffff", bg) ?? 0) >= 2.6 ? "#ffffff" : "#0b0c0e";
+ const label = host.box({
+ id: ctx.partId("label"),
+ position: "absolute",
+ x: half + labelX,
+ y: half + labelY,
+ width: labelW,
+ height: labelH,
+ background: bg,
+ borderRadius: labelH / 2,
+ children: [
+ host.text(labelText, {
+ id: ctx.partId("label-text"),
+ position: "absolute",
+ x: labelPadX,
+ y: Math.round((labelH - labelMetrics.lineHeight) / 2),
+ fontFamily: theme.font.body,
+ fontSize: labelFont,
+ fontWeight: 600,
+ fill: ink,
+ }),
+ ],
+ });
+ label.animate(
+ track(
+ "opacity",
+ bakeSamples(samples(plan.length, visibility), 0, {
+ tolerance: 0.004,
+ }),
+ ),
+ );
+ if (props.shadow) {
+ host.style(label, {
+ dropShadow: {
+ color: "#000000",
+ opacity: 0.28,
+ angle: 90,
+ distance: 2,
+ size: 8,
+ },
+ });
+ }
+ motionChildren.push(label);
+ parts.label = label;
+ }
+
+ const motion = host.box({
+ id: ctx.partId("motion"),
+ position: "absolute",
+ x: (plan.positions[0]?.[0] ?? 0) - half,
+ y: (plan.positions[0]?.[1] ?? 0) - half,
+ width: extent,
+ height: extent,
+ ...(props.motionBlur !== false && {
+ motionBlurShutter: props.motionBlur === true ? 45 : props.motionBlur,
+ }),
+ children: motionChildren,
+ });
+ motion.animate(
+ track(
+ "x",
+ bakeSamples(
+ plan.positions.map((p) => p[0] - half),
+ 0,
+ { tolerance: 0.2 },
+ ),
+ ),
+ track(
+ "y",
+ bakeSamples(
+ plan.positions.map((p) => p[1] - half),
+ 0,
+ { tolerance: 0.2 },
+ ),
+ ),
+ );
+
+ // ── Ripples and trail (they stay where they are drawn) ───────────
+ const below: LayoutNode[] = [];
+ if (props.ripple !== false) {
+ plan.cues.clicks.forEach((click, i) => {
+ below.push(
+ ...ripple(
+ ctx,
+ props.ripple as RippleKind,
+ click.point,
+ size,
+ accent,
+ click.frame,
+ i,
+ ),
+ );
+ });
+ }
+ if (props.trail !== false) {
+ const { length, spacing } = props.trail;
+ const color = props.trail.color ?? accent;
+ const dot = Math.max(3, size * 0.22);
+ for (let g = 1; g <= length; g++) {
+ const lag = g * spacing;
+ const at = (f: number): Vec2 =>
+ plan.positions[Math.max(0, f - lag)] ?? [0, 0];
+ const moving = (f: number) => {
+ const a = at(f);
+ const b = at(f - 1);
+ return Math.min(1, Math.hypot(a[0] - b[0], a[1] - b[1]) / 6);
+ };
+ const ghost = host.shape("circle", {
+ id: ctx.partId(`trail-${g}`),
+ position: "absolute",
+ x: (plan.positions[0]?.[0] ?? 0) - dot / 2,
+ y: (plan.positions[0]?.[1] ?? 0) - dot / 2,
+ width: dot,
+ height: dot,
+ fillColor: color,
+ });
+ ghost.animate(
+ track(
+ "x",
+ bakeSamples(
+ samples(plan.length, (f) => at(f)[0] - dot / 2),
+ 0,
+ { tolerance: 0.3 },
+ ),
+ ),
+ track(
+ "y",
+ bakeSamples(
+ samples(plan.length, (f) => at(f)[1] - dot / 2),
+ 0,
+ { tolerance: 0.3 },
+ ),
+ ),
+ track(
+ "opacity",
+ bakeSamples(
+ samples(
+ plan.length,
+ (f) => 0.5 * (1 - g / (length + 1)) * moving(f) * visibility(f),
+ ),
+ 0,
+ { tolerance: 0.01 },
+ ),
+ ),
+ track("scale", [[0, 1 - (0.5 * g) / (length + 1)]]),
+ );
+ below.push(ghost);
+ }
+ }
+
+ Object.assign(parts, { motion, cursor });
+
+ return {
+ children: [...below, motion],
+ width: W,
+ height: H,
+ duration: plan.length,
+ origin: [0, 0],
+ cues: plan.cues as MousePointerCues,
+ parts,
+ api: (placement): MousePointerApi => ({
+ positionAt(frame) {
+ const local = Math.max(
+ 0,
+ Math.min(plan.length - 1, Math.round(frame - placement.start)),
+ );
+ const p = plan.positions[local] ?? [0, 0];
+ return [p[0] + placement.x, p[1] + placement.y];
+ },
+ styleAt(frame) {
+ const local = Math.round(frame - placement.start);
+ return (
+ plan.styles.find((w) => local >= w.start && local <= w.end)
+ ?.style ?? props.style
+ );
+ },
+ }),
+ };
+ },
+});
+
+// ── Helpers ──────────────────────────────────────────────────────────
+
+type RippleKind = "ring" | "fill" | "pulse";
+
+const smooth = (t: number) => {
+ const x = Math.max(0, Math.min(1, t));
+ return x * x * (3 - 2 * x);
+};
+const backOut = (t: number, s = 1.7) =>
+ 1 + (s + 1) * (t - 1) ** 3 + s * (t - 1) ** 2;
+
+function samples(length: number, fn: (frame: number) => number): number[] {
+ return Array.from({ length }, (_, f) => fn(f));
+}
+
+function track(prop: AnimatableProp, keys: ReadonlyArray<KeyframeTuple>) {
+ return LayerAnimation.keys(prop, keys);
+}
+
+/** Make angle samples continuous so rotation never spins the long way round. */
+function unwrap(degrees: number[]): number[] {
+ const out: number[] = [];
+ for (const d of degrees) {
+ const prev = out[out.length - 1];
+ if (prev === undefined) {
+ out.push(d);
+ continue;
+ }
+ let x = d;
+ while (x - prev > 180) x -= 360;
+ while (x - prev < -180) x += 360;
+ out.push(x);
+ }
+ return out;
+}
+
+/** 1 while `style` shows, easing across `swap` frames at each change. */
+function styleWeight(
+ plan: PointerPlan,
+ style: CursorStyle,
+ frame: number,
+ swap: number,
+): number {
+ const win = plan.styles.find((w) => frame >= w.start && frame <= w.end);
+ if (!win) return 0;
+ if (win.style === style) {
+ const sinceStart = win.start === 0 ? swap : frame - win.start;
+ return smooth(Math.min(1, (sinceStart + 1) / (swap + 1)));
+ }
+ // The previous window's style lingers for `swap` frames.
+ const idx = plan.styles.indexOf(win);
+ const prev = plan.styles[idx - 1];
+ if (prev?.style === style && frame - win.start < swap) {
+ return 1 - smooth((frame - win.start + 1) / (swap + 1));
+ }
+ return 0;
+}
+
+/** Glyph scale over time from the press windows. */
+function pressProfile(
+ plan: PointerPlan,
+ feedback: "press" | "bounce" | "pulse" | false,
+): (f: number) => number {
+ if (feedback === false) return () => 1;
+ const low = feedback === "bounce" ? 0.76 : feedback === "pulse" ? 1.16 : 0.84;
+ return (f) => {
+ for (const w of plan.presses) {
+ if (f < w.down || f > w.released + 30) continue;
+ if (f <= w.pressed)
+ return (
+ 1 + (low - 1) * smooth((f - w.down) / Math.max(1, w.pressed - w.down))
+ );
+ if (f <= w.up) return low;
+ const t = (f - w.up) / Math.max(1, w.released - w.up);
+ if (feedback === "bounce") return 1 + (low - 1) * elasticDecay(t);
+ if (t >= 1) return 1;
+ return low + (1 - low) * backOut(t, 2.2);
+ }
+ return 1;
+ };
+}
+
+const elasticDecay = (t: number) =>
+ t >= 3 ? 0 : Math.exp(-3.2 * t) * Math.cos(t * Math.PI * 2.4);
+
+interface GlyphPaint {
+ k: number;
+ margin: number;
+ color: string;
+ accent: string;
+ outline: string | null;
+ outlineWidth: number;
+ mode: "union" | "each";
+}
+
+/** Outline layers (all first, so overlaps merge) then fills. */
+function glyphShapes(
+ ctx: Parameters<typeof mousePointer.build>[0],
+ glyph: Glyph,
+ style: string,
+ paint: GlyphPaint,
+): LayoutNode[] {
+ const { k, margin } = paint;
+ const geometry = {
+ position: "absolute" as const,
+ x: 0,
+ y: 0,
+ width: 24 * k + margin * 2,
+ height: 24 * k + margin * 2,
+ };
+ const outlines: LayoutNode[] = [];
+ const fills: LayoutNode[] = [];
+ glyph.parts.forEach((part, i) => {
+ const d = transformPathData(part.d, k, margin, margin);
+ const stroke = part.paint === "stroke" || part.paint === "accent-stroke";
+ const colorOf =
+ part.paint === "accent" || part.paint === "accent-stroke"
+ ? paint.accent
+ : paint.color;
+ const lineWidth = (part.width ?? 0) * k;
+ if (paint.outline) {
+ const o = ctx.host.shape("path", {
+ id: ctx.partId(`glyph-${style}-outline-${i}`),
+ ...geometry,
+ d,
+ fillType: stroke ? "none" : "solid",
+ fillColor: paint.outline,
+ strokeColor: paint.outline,
+ strokeWidth: lineWidth + paint.outlineWidth * 2,
+ strokeLineJoin: "round",
+ strokeLineCap: "round",
+ strokeAlign: "center",
+ });
+ (paint.mode === "union" ? outlines : fills).push(o);
+ }
+ fills.push(
+ ctx.host.shape("path", {
+ id: ctx.partId(`glyph-${style}-${i}`),
+ ...geometry,
+ d,
+ ...(stroke
+ ? {
+ fillType: "none" as const,
+ fillColor: colorOf,
+ strokeColor: colorOf,
+ strokeWidth: lineWidth,
+ strokeLineCap: "round" as const,
+ }
+ : { fillColor: colorOf }),
+ }),
+ );
+ });
+ return [...outlines, ...fills];
+}
+
+function ripple(
+ ctx: Parameters<typeof mousePointer.build>[0],
+ kind: RippleKind,
+ at: Vec2,
+ size: number,
+ accent: string,
+ frame: number,
+ index: number,
+): LayoutNode[] {
+ const radius = size * 0.95;
+ const life = Math.round((18 * ctx.fps) / 30);
+ const make = (delay: number, n: number) => {
+ const ring = ctx.host.shape("circle", {
+ id: ctx.partId(`ripple-${index}-${n}`),
+ position: "absolute",
+ x: at[0] - radius,
+ y: at[1] - radius,
+ width: radius * 2,
+ height: radius * 2,
+ startFrame: frame + delay,
+ durationFrames: life,
+ ...(kind === "fill"
+ ? { fillColor: accent }
+ : {
+ fillType: "none" as const,
+ fillColor: accent,
+ strokeColor: accent,
+ strokeWidth: Math.max(1.5, size / 16),
+ }),
+ });
+ ring.animate(
+ track("scale", [
+ [0, 0.2],
+ [life - 2, 1, "expo.out"],
+ ]),
+ track("opacity", [
+ [0, kind === "fill" ? 0.35 : 0.9],
+ [life - 1, 0, "sine.in"],
+ ]),
+ );
+ return ring;
+ };
+ return kind === "pulse"
+ ? [make(0, 0), make(Math.round((5 * ctx.fps) / 30), 1)]
+ : [make(0, 0)];
+}
+
+/**
+ * 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/30_product_demo/src/components/mouse-pointer/plan.ts b/examples/30_product_demo/src/components/mouse-pointer/plan.ts
new file mode 100644
index 00000000..b4d051ef
--- /dev/null
+++ b/examples/30_product_demo/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/30_product_demo/src/film.ts b/examples/30_product_demo/src/film.ts
index c6339419..88ea5988 100644
--- a/examples/30_product_demo/src/film.ts
+++ b/examples/30_product_demo/src/film.ts
@@ -2,22 +2,25 @@
* A 13-second product demo: the browser opens on a deploys dashboard, the
* pointer ships a build and promotes it, and the camera follows every click.
*
- * Three components carry it: AppFrame (the browser), MousePointer (the
+ * Three components carry it, added with `npx framefields add app-frame
+ * mouse-pointer focus-zoom`: AppFrame (the browser), MousePointer (the
* hand), FocusZoom (the camera). Everything that reacts — button presses,
* the new row, the toast — keys off the pointer's cues, so moving a
* waypoint re-times the whole film.
*/
import {
- AppFrame,
Composition,
- FocusZoom,
FontManager,
Layer,
LayerAnimation,
type LayoutNode,
+} from "framefields";
+import { AppFrame } from "./components/app-frame/index.js";
+import { FocusZoom } from "./components/focus-zoom/index.js";
+import {
MousePointer,
type Waypoint,
-} from "framefields";
+} from "./components/mouse-pointer/index.js";
import {
ACCENT,
APP,
diff --git a/packages/components/SPEC.md b/packages/components/SPEC.md
index f6f61fc8..414886ec 100644
--- a/packages/components/SPEC.md
+++ b/packages/components/SPEC.md
@@ -90,32 +90,41 @@ wire its timing to everything else. We go the other way:
### 3.1 Import story
-```ts
-// The default: straight from the SDK root.
-import { Composition, Layer, MousePointer, Captions } from "framefields";
+Components are **not in the package**. Like a shadcn registry, `framefields add` copies a
+component's source into the project, where it is the user's code to read and change:
-// Same exports from a dedicated subpath, for consumers that want an explicit boundary
-// (the browser preview engine, bundle-size-sensitive builds).
-import { MousePointer } from "framefields/components";
+```sh
+npx framefields add mouse-pointer focus-zoom # writes src/components/<name>/…
+npx framefields list # what can be added
```
-Components are exported from both paths. The root exports only the user-facing pieces
-(the components, `themes`, `defineTheme`, `pulseKeys`, `bindComponent` and the `Target` /
-`Cue` / `ComponentNode` / `Theme` types). The subpath adds the authoring toolkit (timing,
-paths, strokes, targets, baking, motion presets, `defineComponent`), which would otherwise
-crowd the root namespace (`span`, for one, is already the rich-text helper there).
-There are **no** per-component subpaths for users:
-ESM named exports plus `sideEffects: false` let bundlers drop everything that isn't
-imported, and a CI check (§9.5) enforces that this stays true.
+```ts
+import { Composition, Layer } from "framefields";
+import { MousePointer } from "./components/mouse-pointer/index.js";
+```
+
+Installed source imports only two things: `framefields` (layers, animation) and
+`framefields/components`, the **toolkit** every component is built from (timing, paths,
+strokes, targets, baking, motion presets, themes, `defineComponent`, `bindComponent`, and
+framefields' own `z`, so schemas share its zod instance). A component that builds on
+another (Terminal on AppFrame and Counter) imports it relatively, and `add` installs it
+alongside. The root keeps the pieces users touch around components: `themes`,
+`defineTheme`, `pulseKeys`, `bindComponent`, `analyzeAudio` and the `Target` / `Cue` /
+`ComponentNode` / `Theme` / `AudioLevels` types.
+
+Why copy instead of export: motion components are where users most want to change the
+details (a curve, a glyph, a layout), and owning the file beats a growing props surface.
+The toolkit stays a dependency, so fixes to the shared math still arrive with upgrades.
### 3.2 Where the code lives
```
-packages/components/ @framefields/components (internal, bundled into framefields)
+packages/components/ @framefields/components (internal)
SPEC.md this document
package.json private, sideEffects: false
src/
- index.ts named re-exports only: no registries, no top-level calls
+ index.ts everything, for tests (named re-exports, no top-level calls)
+ toolkit.ts core/* only: what `framefields/components` re-exports
core/
contract.ts defineComponent, ComponentNode, BaseProps, cue helpers
host.ts Host interface (what framefields injects, §3.3)
@@ -135,9 +144,13 @@ packages/components/ @framefields/components (internal, bundled
meta.ts summary, tags, schema, example
mouse-pointer.test.ts planner unit tests against a fake host
captions/ … same shape for every component
+ scripts/build-registry.ts component folders → dist/registry (what `add` installs)
packages/framefields/
- src/components/index.ts binds the host, re-exports every component
+ src/components/index.ts the toolkit: re-exports toolkit.ts, binds the host
+ src/components/testing.ts test-only: every component bound from source
src/components/*.render.test.ts frame-grid golden tests (real GPU)
+ src/cli.ts, src/cli/* the `framefields` command (`add`, `list`)
+ dist/registry/ copied from the components build; shipped
```
### 3.3 Layering: the host
@@ -167,22 +180,16 @@ with `Captions`. Each addition is one method here and one line in
`packages/framefields/src/components/host.ts`, which reads `Layer` lazily inside each call
so importing it has no effects.
-framefields binds it once per component, as pure top-level expressions that bundlers can
+Each installed component binds itself in its last line, a pure expression bundlers can
drop:
```ts
-// packages/framefields/src/components/index.ts
+// src/components/mouse-pointer/index.ts (as `framefields add` writes it)
export const MousePointer = /* @__PURE__ */ bindComponent(mousePointer);
-export const Captions = /* @__PURE__ */ bindComponent(captions);
-// …
```
-`bindComponent` (exported from both paths) is also how users bind components they write
-with `defineComponent`.
-
-The root `src/index.ts` adds `export * from "./components/index.js"`, `tsdown.config.ts`
-gains the `src/components/index.ts` entry, and `package.json` gains the `./components`
-export.
+`bindComponent` (from `framefields` or `framefields/components`) is also how users bind
+components they write with `defineComponent`.
**Types without a type move.** The full `AnimatableNode` type depends on effect, vision and
tensor types that live in framefields, so it can't move down cheaply. Instead the component
@@ -194,10 +201,21 @@ package types nodes structurally (`Animatable<T> = T & { animate(...): unknown }
host. Anything that renders lives in `packages/framefields/src/components/` so there is no
`framefields ↔ components` dependency cycle for turbo.
-### 3.4 Versioning
+### 3.4 Versioning and the registry
+
+`@framefields/components` is internal (`private: true`). Its build writes
+`dist/registry/`: `index.json` (name, factory, summary, tags, example, dependencies) and one
+`<name>.json` per component with its files. The rewrite is import-only: `../core/*` and
+`zod` fold into one `framefields/components` import, `@framefields/compositions/program`
+becomes `framefields`, sibling components stay relative, and the folder's `index.ts` gains
+its bound factory. Tests and `meta.ts` stay behind; the meta travels as item fields.
-`@framefields/components` is internal (`private: true`) and ships inside `framefields`, so
-there is one version to reason about. Changesets for component work target `framefields`.
+The framefields build copies that folder into its own `dist/registry`, so `npx framefields
+add` installs code written against exactly the installed toolkit: one version to reason
+about. `--registry <folder | url>` reads another registry of the same shape.
+`framefields.json` at the project root remembers where components go (default
+`src/components` when there is a `src`, else `components`). `add` never replaces a file the
+user changed unless given `--overwrite`.
---
@@ -1464,21 +1482,30 @@ asserts identical output. Each component with randomness renders twice with the
(`builder-schema-conformance` style), and `comp.lint()` reports nothing for the canonical
example under every built-in theme.
-### 9.5 Tree-shaking
+### 9.5 Tree-shaking and installability
`packages/framefields/scripts/check-components-treeshake.mjs` runs at the end of the
-framefields build. It bundles the built `dist` with esbuild the way a user's bundler would,
-on top of a baseline that already imports `Layer` (every project does; the framefields
-root's own top-level code is outside this check), and for each case asserts:
-
-- no marker string survives from a module the import must not pull (contract, strokes,
- targets, motion …), and
-- the bytes added over the baseline stay inside a budget.
+framefields build. It bundles with esbuild the way a user's bundler would, on top of a
+baseline that already imports `Layer` (every project does; the framefields root's own
+top-level code is outside this check), and asserts:
+
+- no component's code is anywhere in the built `dist` (components ship only as registry
+ data);
+- each toolkit import carries no marker string from a module it must not pull (contract,
+ strokes, targets, motion …) and stays inside a byte budget;
+- each registry component, installed the way `add` writes it and bundled against the dist,
+ carries its own marker, none of the others except what it composes, and stays inside its
+ budget.
Each component is a row in the script's `COMPONENTS` table: a marker string only its module
has, and the components it composes (Terminal composes AppFrame and Counter, CodeBlock
-composes AppFrame, TitleCard composes TextReveal, Meter composes Counter). The check imports
-each component alone and forbids every other marker except those.
+composes AppFrame, TitleCard composes TextReveal, Meter composes Counter). A registry
+component without a row fails the check.
+
+`scripts/check-registry-types.mjs` then installs every component into a scratch project that
+links the package as `framefields` and typechecks it under NodeNext and bundler resolution,
+with `strict`, `noUncheckedIndexedAccess` and `verbatimModuleSyntax`: settings user projects
+commonly turn on, which the monorepo's own config does not.
### 9.6 Budgets
@@ -1532,6 +1559,7 @@ Each milestone ends with a changeset for `framefields` (minor), docs, and its ex
| **M6 · Re-score** ✅ | Rank Wave 3 against usage and requests. | Updated §8.2 (no telemetry yet: evidence from the example films and engine features). |
| **M7 · Wave 3a** ✅ | `LogoReveal`, `Backdrop`, `Waveform`, `WordCycle` (+ `Captions` `pulse` via audio levels). | Specs in §7.13–7.16; acceptance tests green (§18); no example film. |
| **M8 · Wave 3b** ✅ | `DeviceFrame` + `TouchPoint`, `BeforeAfter`, `Selection`, `CardStack`. | Specs in §7.17–7.21; acceptance tests green (§19); no example film. |
+| **M9 · Registry** ✅ | Components leave the package: `npx framefields add` / `list` install source from a registry shipped in `dist/registry` (§3.1, §3.4). | Every component installs, typechecks under strict user settings and tree-shakes from its installed copy (§9.5); `30_product_demo` uses installed copies (§20). |
Housekeeping (done in M1): the stale `.changeset/components-mouse-pointer.md` described a
standalone package that never shipped; it is replaced by `framefields` changesets per
@@ -1543,13 +1571,13 @@ milestone (the components package is private and bundled).
| # | Question | Status |
|---|---|---|
-| Q1 | Root re-export or `framefields/components` only? | **Decided (M0):** components and user-facing types at the root, full toolkit at the subpath (§3.1). |
+| Q1 | Root re-export or `framefields/components` only? | **Superseded (M9):** components are installed with `framefields add`; the root keeps user-facing types and helpers, the subpath the full toolkit (§3.1). |
| Q2 | Is text `content` keyframeable with hold interpolation? | **Corrected (M1):** the `text` track is a *reveal amount*, not a string: ≤ 1 is a fraction, > 1 a character count (so one character of n is keyed as `1 / n`). Typing (`AppFrame` URLs, `TextReveal` `type`) keys counts with `hold`. Changing strings per frame is not possible, so `Counter` uses digit reels for both styles and `stream` uses glyph animators. |
| Q3 | Node targets inside flex layouts need resolved geometry at build time. | **Open:** `computeLayoutSync(yoga, …)` exists in `@framefields/compositions/program`, but no `host.layout` was needed for M1/M2: node targets still require absolute nodes and the error says so. `TextReveal.rects(match)` and `AppFrame.at(x, y)` cover the common cases. |
| Q4 | PascalCase factories vs. a namespace? | **Decided:** PascalCase named exports. A namespace object defeats tree-shaking. |
| Q5 | Should built-in themes ship fonts? | **Decided:** no. Fonts stay user-registered. |
| Q6 | Seconds vs. frames for user-facing times. | **Decided:** frames everywhere; `fps` base prop for real-world inputs and theme speeds. |
-| Q7 | Per-component deep import paths for users? | **Decided:** no, unless the §9.5 check ever fails. |
+| Q7 | Per-component deep import paths for users? | **Moot (M9):** installed components are files in the project. |
| Q8 | The framefields root chunk keeps ~1 MB of top-level code for any import. | Outside components; worth a separate pass over framefields' module-level side effects (schemas, registries) if browser bundle size starts to matter. |
## 12. M0 delivery notes
@@ -1875,3 +1903,37 @@ Follow-up engine fix: 3D models inside 2D containers ignored the containers' off
are laid out in flow, so their layout rect never reflected their `x` / `y`). The compositor
now maps a model's own `x` / `y` through its parent's matrix (`model-parent-offset.render.test.ts`),
so LogoReveal's extruded names need no compensation and can sit anywhere in the tree.
+
+## 20. M9 delivery notes
+
+Components moved out of the package into a registry that `framefields add` installs from.
+
+- **Toolkit.** `@framefields/components/toolkit` re-exports `core/*`; `framefields/components`
+ re-exports it plus `bindComponent`, `analyzeAudio` and framefields' `z`. The toolkit names
+ installed code needed that weren't public before (`Host`, `TargetNode`, `Animatable`,
+ `targetSchema`, `transformPathData`, `rendererChars` …) are now public.
+- **Root.** The 26 factories and their component-specific types (`Waypoint`, `CursorStyle`,
+ `CAPTION_STYLES` …) left the root; they come with the installed files.
+- **CLI.** `framefields add <name…> [--all] [--dir] [--overwrite] [--registry]` and
+ `framefields list`, in `src/cli.ts` (bin `framefields`). Dependencies install first and
+ once; identical files report `unchanged`; files the user edited are `skipped` unless
+ `--overwrite`; unknown names fail before anything is written.
+- **Tests.** Render tests import `src/components/testing.ts`, which binds every component
+ from source (the installed copy differs only in import paths, which
+ `build-registry.test.ts` and `check-registry-types.mjs` cover).
+- **Example.** `30_product_demo` installed AppFrame, MousePointer and FocusZoom with the
+ command and imports them from `src/components`.
+
+Found by typechecking installed copies under user-style settings:
+
+- `noUncheckedIndexedAccess` errors in DeviceFrame (shadow table) and TextReveal
+ (`rects` range); fixed in source.
+- Inline type imports (`import("../core/host.js").Host`) needed rewriting too.
+- A type-bundler slip: when the short alias it picks for a chunk export equals a name the
+ chunk already declares (framefields' `Ai` interface), it emits `type fn as Ai`, and
+ consumers get "cannot be used as a value". Which export it hits shifts between builds,
+ so `scripts/fix-dts-aliases.mjs` (run after the build) drops `type` from any export the
+ chunk declares as a function, const, class or enum.
+
+Budgets: MousePointer 62 → 66 KB and TextReveal 55 → 58 KB. Installed copies are bundled
+from TypeScript source rather than the package's prebuilt output, which costs about 2 KB.
diff --git a/packages/components/package.json b/packages/components/package.json
index 0aa31f32..799810ab 100644
--- a/packages/components/package.json
+++ b/packages/components/package.json
@@ -2,7 +2,7 @@
"name": "@framefields/components",
"version": "2.4.3",
"private": true,
- "description": "Parametric motion components for framefields. Internal: bundled into and exported from `framefields`.",
+ "description": "Parametric motion components for framefields. Internal: the toolkit ships in `framefields/components`; components ship as a registry that `framefields add` copies into projects.",
"type": "module",
"sideEffects": false,
"license": "Apache-2.0",
@@ -14,18 +14,25 @@
"development": "./src/index.ts",
"import": "./dist/index.mjs",
"default": "./dist/index.mjs"
+ },
+ "./toolkit": {
+ "types": "./dist/toolkit.d.mts",
+ "development": "./src/toolkit.ts",
+ "import": "./dist/toolkit.mjs",
+ "default": "./dist/toolkit.mjs"
}
},
"files": [
"dist/**"
],
"scripts": {
- "build": "tsdown && tsx scripts/build-meta.ts",
+ "build": "tsdown && tsx scripts/build-meta.ts && tsx scripts/build-registry.ts",
"dev": "tsdown --watch",
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist",
"test": "vitest run",
"typecheck": "tsc --noEmit",
- "meta": "tsx scripts/build-meta.ts"
+ "meta": "tsx scripts/build-meta.ts",
+ "registry": "tsx scripts/build-registry.ts"
},
"dependencies": {
"@framefields/compositions": "workspace:*",
diff --git a/packages/components/scripts/build-registry.test.ts b/packages/components/scripts/build-registry.test.ts
new file mode 100644
index 00000000..3984e235
--- /dev/null
+++ b/packages/components/scripts/build-registry.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from "vitest";
+import { buildRegistry, rewriteImports } from "./build-registry.js";
+
+describe("rewriteImports", () => {
+ it("folds core and zod into one toolkit import and program into framefields", () => {
+ const source = `/** Doc. */
+import {
+ type KeyframeTuple,
+ LayerAnimation,
+} from "@framefields/compositions/program";
+import { z } from "zod";
+import { bakeSamples } from "../core/bake.js";
+import type { Animatable } from "../core/host.js";
+import { counter } from "../counter/index.js";
+import { valueAt } from "../counter/plan.js";
+import { plan } from "./plan.js";
+
+type H = import("../core/host.js").Host;
+`;
+ const { content, siblings } = rewriteImports(source, "x/index.ts", [
+ "bindComponent",
+ ]);
+ expect(content).toBe(`/** Doc. */
+import { type KeyframeTuple, LayerAnimation } from "framefields";
+import {
+ type Animatable,
+ bakeSamples,
+ bindComponent,
+ z,
+} from "framefields/components";
+import { counter } from "../counter/index.js";
+import { valueAt } from "../counter/plan.js";
+import { plan } from "./plan.js";
+
+type H = import("framefields/components").Host;
+`);
+ expect(siblings).toEqual(["counter"]);
+ });
+
+ it("refuses imports it cannot rewrite", () => {
+ expect(() =>
+ rewriteImports('import { x } from "@framefields/core";\n', "x/index.ts"),
+ ).toThrow('cannot rewrite import from "@framefields/core"');
+ });
+});
+
+describe("buildRegistry", () => {
+ it("every component installs from framefields alone, plus the components it names", async () => {
+ const items = await buildRegistry();
+ expect(items.length).toBeGreaterThanOrEqual(26);
+ const names = new Set(items.map((i) => i.name));
+ for (const item of items) {
+ for (const d of item.registryDependencies)
+ expect(names.has(d)).toBe(true);
+ for (const f of item.files) {
+ expect(f.path.startsWith(`${item.name}/`)).toBe(true);
+ expect(f.path).not.toMatch(/\.test\.ts$|\/meta\.ts$/);
+ for (const m of f.content.matchAll(/from "([^"]+)"/g)) {
+ const from = m[1] as string;
+ const ok =
+ from === "framefields" ||
+ from === "framefields/components" ||
+ from.startsWith("./") ||
+ item.registryDependencies.some((d) => from.startsWith(`../${d}/`));
+ expect(ok, `${f.path} imports ${from}`).toBe(true);
+ }
+ }
+ const index = item.files.find((f) => f.path === `${item.name}/index.ts`);
+ expect(index?.content).toContain(
+ `export const ${item.title} = /* @__PURE__ */ bindComponent(`,
+ );
+ }
+ });
+});
diff --git a/packages/components/scripts/build-registry.ts b/packages/components/scripts/build-registry.ts
new file mode 100644
index 00000000..8d4f70d4
--- /dev/null
+++ b/packages/components/scripts/build-registry.ts
@@ -0,0 +1,241 @@
+/**
+ * Builds the component registry `framefields add` installs from: one JSON
+ * item per component folder, holding its source rewritten for a user's
+ * project, plus an index of them all. Written to `dist/registry/`, which
+ * the `framefields` build ships inside its own dist.
+ *
+ * The rewrite is import-only: `../core/*` and `zod` become one import from
+ * `framefields/components` (the toolkit, which re-exports framefields' own
+ * zod so schemas share its instance), `@framefields/compositions/program`
+ * becomes `framefields`, and sibling components stay relative and become
+ * registry dependencies. The folder's `index.ts` gains the bound factory.
+ * Tests and `meta.ts` are left out; the meta travels as item fields.
+ */
+import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import type { ComponentMeta } from "../src/core/meta.js";
+import { collectMeta } from "./build-meta.js";
+
+const SRC = fileURLToPath(new URL("../src", import.meta.url));
+const NOT_COMPONENTS = new Set(["core", "test"]);
+export const TOOLKIT = "framefields/components";
+export const RUNTIME = "framefields";
+
+export interface RegistryFile {
+ /** Relative to the components directory, e.g. `counter/plan.ts`. */
+ path: string;
+ content: string;
+}
+
+export interface RegistryEntry
+ extends Pick<ComponentMeta, "summary" | "tags" | "example"> {
+ /** Folder name, what `framefields add` takes: `logo-reveal`. */
+ name: string;
+ /** The factory the item exports: `LogoReveal`. */
+ title: string;
+ /** Other registry items it imports, installed with it. */
+ registryDependencies: string[];
+}
+
+export interface RegistryItem extends RegistryEntry {
+ parts: readonly string[];
+ cues: readonly string[];
+ files: RegistryFile[];
+}
+
+const IMPORT = /^import\s+(type\s+)?\{([^}]*)\}\s+from\s+"([^"]+)";[ \t]*\n/gm;
+const SIBLING = /^\.\.\/([a-z0-9-]+)\/[a-z0-9-]+\.js$/;
+
+/** Rewrite one source file's imports; returns the sibling folders it reads. */
+export function rewriteImports(
+ source: string,
+ file: string,
+ extra: string[] = [],
+): { content: string; siblings: string[] } {
+ const toolkit = new Set<string>(extra);
+ const runtime = new Set<string>();
+ const siblings = new Set<string>();
+ let first: number | undefined;
+ let runtimeAt: number | undefined;
+ const kept = source.replace(
+ IMPORT,
+ (whole, typeOnly: string | undefined, names: string, from: string, at) => {
+ const specs = names
+ .split(",")
+ .map((n) => n.trim())
+ .filter(Boolean)
+ .map((n) => (typeOnly && !n.startsWith("type ") ? `type ${n}` : n));
+ const sibling = SIBLING.exec(from)?.[1];
+ if (sibling && sibling !== "core") siblings.add(sibling);
+ let into: Set<string> | undefined;
+ if (from.startsWith("../core/") || from === "zod") into = toolkit;
+ else if (from === "@framefields/compositions/program") into = runtime;
+ else if (from.startsWith("@framefields/"))
+ throw new Error(`${file}: cannot rewrite import from "${from}"`);
+ if (!into) return whole;
+ for (const s of specs) into.add(s);
+ // The merged imports go where the first rewritten one was.
+ if (first === undefined) first = at as number;
+ if (into === runtime && runtimeAt === undefined) runtimeAt = at as number;
+ return "\0";
+ },
+ );
+ const block = [
+ runtime.size > 0 ? importLine(runtime, RUNTIME) : "",
+ toolkit.size > 0 ? importLine(toolkit, TOOLKIT) : "",
+ ].join("");
+ let content: string;
+ if (first === undefined) {
+ // Nothing to replace: the new import goes after the last existing one.
+ const lastImport = [...source.matchAll(IMPORT)].at(-1);
+ const end = lastImport ? (lastImport.index ?? 0) + lastImport[0].length : 0;
+ content = source.slice(0, end) + block + source.slice(end);
+ } else {
+ let placed = false;
+ content = kept.replace(/\0/g, () => {
+ if (placed) return "";
+ placed = true;
+ return block;
+ });
+ }
+ // Inline type imports: `import("../core/host.js").Host`.
+ content = content.replace(
+ /import\("\.\.\/core\/[a-z]+\.js"\)/g,
+ `import("${TOOLKIT}")`,
+ );
+ if (/["']\.\.\/core\//.test(content))
+ throw new Error(`${file}: a "../core/" reference survived the rewrite`);
+ return { content, siblings: [...siblings] };
+}
+
+function importLine(names: Set<string>, from: string): string {
+ const sorted = [...names].sort((a, b) => {
+ const x = a.replace(/^type /, "");
+ const y = b.replace(/^type /, "");
+ return (
+ x.localeCompare(y, "en", { sensitivity: "base" }) || (x < y ? -1 : 1)
+ );
+ });
+ // All types: `import type { A, B }`, as the linter wants it.
+ const typeOnly = sorted.every((n) => n.startsWith("type "));
+ const specs = typeOnly ? sorted.map((n) => n.slice(5)) : sorted;
+ const head = typeOnly ? "import type" : "import";
+ const one = `${head} { ${specs.join(", ")} } from "${from}";\n`;
+ if (one.length <= 81) return one;
+ return `${head} {\n${specs.map((n) => `\t${n},\n`).join("")}} from "${from}";\n`;
+}
+
+/** A JSDoc block wrapped at 80 columns. */
+function docComment(text: string): string {
+ if (text.length <= 74) return `/** ${text} */\n`;
+ const lines: string[] = [];
+ let line = "";
+ for (const word of text.split(" ")) {
+ if (line && line.length + word.length + 1 > 77) {
+ lines.push(line);
+ line = word;
+ } else line = line ? `${line} ${word}` : word;
+ }
+ lines.push(line);
+ return `/**\n${lines.map((l) => ` * ${l}\n`).join("")} */\n`;
+}
+
+/** `LogoReveal` → `logoReveal`: the definition each folder exports. */
+const definitionName = (title: string) =>
+ title.charAt(0).toLowerCase() + title.slice(1);
+
+/** One component folder as a registry item. */
+export function registryItem(
+ src: string,
+ name: string,
+ meta: ComponentMeta,
+): RegistryItem {
+ const dir = join(src, name);
+ const def = definitionName(meta.name);
+ const files: RegistryFile[] = [];
+ const deps = new Set<string>();
+ for (const f of readdirSync(dir).sort()) {
+ if (!f.endsWith(".ts") || f.endsWith(".test.ts") || f === "meta.ts")
+ continue;
+ const source = readFileSync(join(dir, f), "utf8");
+ const isIndex = f === "index.ts";
+ if (isIndex && !new RegExp(`export const ${def}\\b`).test(source))
+ throw new Error(`${name}/index.ts does not export \`${def}\``);
+ const { content, siblings } = rewriteImports(
+ source,
+ `${name}/${f}`,
+ isIndex ? ["bindComponent"] : [],
+ );
+ for (const s of siblings) deps.add(s);
+ files.push({
+ path: `${name}/${f}`,
+ content: isIndex
+ ? `${content.trimEnd()}\n\n${docComment(meta.summary)}export const ${meta.name} = /* @__PURE__ */ bindComponent(${def});\n`
+ : content,
+ });
+ }
+ return {
+ name,
+ title: meta.name,
+ summary: meta.summary,
+ tags: meta.tags,
+ example: meta.example,
+ parts: meta.parts,
+ cues: meta.cues,
+ registryDependencies: [...deps].sort(),
+ files,
+ };
+}
+
+/** Every component folder under `src`, sorted by name. */
+export async function buildRegistry(src = SRC): Promise<RegistryItem[]> {
+ await collectMeta(src); // every folder has a meta, names are unique
+ const items: RegistryItem[] = [];
+ for (const entry of readdirSync(src, { withFileTypes: true })) {
+ if (!entry.isDirectory() || NOT_COMPONENTS.has(entry.name)) continue;
+ const mod = (await import(
+ pathToFileURL(join(src, entry.name, "meta.ts")).href
+ )) as { default: ComponentMeta };
+ items.push(registryItem(src, entry.name, mod.default));
+ }
+ const names = new Set(items.map((i) => i.name));
+ for (const item of items)
+ for (const d of item.registryDependencies)
+ if (!names.has(d))
+ throw new Error(
+ `${item.name} imports "${d}", which is not a component`,
+ );
+ return items.sort((a, b) => a.name.localeCompare(b.name));
+}
+
+/** Write `index.json` and one `<name>.json` per item into `out`. */
+export function writeRegistry(items: RegistryItem[], out: string): void {
+ mkdirSync(out, { recursive: true });
+ const index: RegistryEntry[] = items.map(
+ ({ name, title, summary, tags, example, registryDependencies }) => ({
+ name,
+ title,
+ summary,
+ tags,
+ example,
+ registryDependencies,
+ }),
+ );
+ writeFileSync(
+ join(out, "index.json"),
+ `${JSON.stringify(index, null, "\t")}\n`,
+ );
+ for (const item of items)
+ writeFileSync(
+ join(out, `${item.name}.json`),
+ `${JSON.stringify(item, null, "\t")}\n`,
+ );
+}
+
+if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
+ const items = await buildRegistry();
+ const out = fileURLToPath(new URL("../dist/registry", import.meta.url));
+ writeRegistry(items, out);
+ console.log(`registry: ${items.length} component(s)`);
+}
diff --git a/packages/components/src/device-frame/index.ts b/packages/components/src/device-frame/index.ts
index 8d42e3f9..c3945599 100644
--- a/packages/components/src/device-frame/index.ts
+++ b/packages/components/src/device-frame/index.ts
@@ -32,6 +32,14 @@ const POINTS: Record<Device, [number, number]> = {
laptop: [1440, 900],
};
+/** Drop shadow per elevation: [opacity, distance, size] at scale 1. */
+const SHADOWS = [
+ [0, 0, 0],
+ [0.3, 10, 26],
+ [0.45, 26, 56],
+ [0.6, 46, 90],
+] as const;
+
const FINISHES = {
graphite: { body: "#2c2e33", edge: "#55585f", button: "#3a3d43" },
silver: { body: "#d8dade", edge: "#f2f3f5", button: "#c4c7cd" },
@@ -165,13 +173,14 @@ export const deviceFrame = /* @__PURE__ */ defineComponent({
background: finish.body,
borderRadius: bodyR,
});
+ const [opacity, distance, size] = SHADOWS[e] ?? SHADOWS[0];
host.style(plate, {
dropShadow: {
color: "#000000",
- opacity: [0, 0.3, 0.45, 0.6][e],
+ opacity,
angle: 90,
- distance: [0, 10, 26, 46][e] * s,
- size: [0, 26, 56, 90][e] * s,
+ distance: distance * s,
+ size: size * s,
spread: 0,
},
});
diff --git a/packages/components/src/text-reveal/index.ts b/packages/components/src/text-reveal/index.ts
index e63e9b2f..2c616fc8 100644
--- a/packages/components/src/text-reveal/index.ts
+++ b/packages/components/src/text-reveal/index.ts
@@ -784,7 +784,7 @@ export const textReveal = /* @__PURE__ */ defineComponent({
parts,
api: (placement): TextRevealApi => ({
rects(match, nth = 0) {
- const range =
+ const range: [number, number] | null =
match === undefined
? [0, text.length]
: findRange(text, match, nth);
diff --git a/packages/components/src/toolkit.ts b/packages/components/src/toolkit.ts
new file mode 100644
index 00000000..a4d1104b
--- /dev/null
+++ b/packages/components/src/toolkit.ts
@@ -0,0 +1,25 @@
+/**
+ * The component toolkit: everything a component's source imports besides
+ * `framefields` itself. Components are not in the package; `framefields add`
+ * copies their source into the user's project, and that source reads this
+ * barrel through `framefields/components`. Named exports only, no top-level
+ * calls, so each export tree-shakes on its own.
+ */
+
+export * from "./core/audio.js";
+export * from "./core/bake.js";
+export * from "./core/contract.js";
+export * from "./core/draw.js";
+export * from "./core/ease.js";
+export * from "./core/glyphs.js";
+export * from "./core/host.js";
+export * from "./core/meta.js";
+export * from "./core/motion.js";
+export * from "./core/path.js";
+export * from "./core/rng.js";
+export * from "./core/schemas.js";
+export * from "./core/targets.js";
+export * from "./core/text.js";
+export * from "./core/theme.js";
+export * from "./core/timing.js";
+export * from "./core/typing.js";
diff --git a/packages/components/tsdown.config.ts b/packages/components/tsdown.config.ts
index b2285023..85635b51 100644
--- a/packages/components/tsdown.config.ts
+++ b/packages/components/tsdown.config.ts
@@ -1,7 +1,7 @@
import { defineConfig } from "tsdown";
export default defineConfig({
- entry: ["src/index.ts"],
+ entry: ["src/index.ts", "src/toolkit.ts"],
format: ["esm"],
dts: true,
clean: true,
diff --git a/packages/framefields/package.json b/packages/framefields/package.json
index d8a6a44d..3c600358 100644
--- a/packages/framefields/package.json
+++ b/packages/framefields/package.json
@@ -29,6 +29,9 @@
"sideEffects": false,
"main": "./dist/index.mjs",
"types": "./dist/index.d.mts",
+ "bin": {
+ "framefields": "./dist/cli.mjs"
+ },
"exports": {
".": {
"types": "./dist/index.d.mts",
@@ -83,7 +86,7 @@
"dist/**"
],
"scripts": {
- "build": "tsdown && node ../../scripts/sync-readme.mjs && node scripts/check-dts-bundle.mjs && node scripts/check-components-treeshake.mjs",
+ "build": "tsdown && node ../../scripts/sync-readme.mjs && node scripts/check-dts-bundle.mjs && node scripts/check-components-treeshake.mjs && node scripts/check-registry-types.mjs",
"dev": "tsdown --watch",
"clean": "rm -rf dist .turbo",
"prepack": "node ../../scripts/sync-readme.mjs",
diff --git a/packages/framefields/scripts/check-components-treeshake.mjs b/packages/framefields/scripts/check-components-treeshake.mjs
index 9bd775b4..64592c3a 100644
--- a/packages/framefields/scripts/check-components-treeshake.mjs
+++ b/packages/framefields/scripts/check-components-treeshake.mjs
@@ -1,8 +1,21 @@
-// Fails the build when an import from `framefields/components` drags in code
-// it doesn't use (spec §9.5). Bundles the built dist the way a user's bundler
-// would, on top of a baseline that already uses `Layer` (every framefields
-// project does), and checks what the import adds: no marker strings from
-// modules it must not pull, and a size budget.
+// Fails the build when components leak into the package or don't tree-shake
+// (spec §9.5). Components are not in framefields: `framefields add` copies
+// them from dist/registry. So: the dist carries no component code; each
+// toolkit import pulls only what it uses; and each registry component,
+// installed the way `add` writes it and bundled against the dist the way a
+// user's bundler would, carries itself and what it builds on, within budget.
+// Sizes are what an import adds on top of a baseline that already uses
+// `Layer` (every framefields project does).
+import {
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { build } from "esbuild";
@@ -10,6 +23,7 @@ const root = fileURLToPath(new URL("../dist/index.mjs", import.meta.url));
const components = fileURLToPath(
new URL("../dist/components/index.mjs", import.meta.url),
);
+const registry = fileURLToPath(new URL("../dist/registry", import.meta.url));
// Strings that only exist in one module each.
const CONTRACT = "invalid props";
@@ -44,12 +58,12 @@ const SPLIT = "before-clip";
const SELECT = "Selection: give";
const CARDS = "Expected a layer or { title";
-/** Each component: a string only its module has, and what it may compose. */
+/** Each component (by factory): a string only its module has, and what it may compose. */
const COMPONENTS = {
- MousePointer: { own: POINTER, uses: [], budget: 62_000 },
+ MousePointer: { own: POINTER, uses: [], budget: 66_000 },
AppFrame: { own: FRAME, uses: [], budget: 45_000 },
FocusZoom: { own: CAMERA, uses: [], budget: 40_000 },
- TextReveal: { own: REVEAL, uses: [GLYPHS], budget: 55_000 },
+ TextReveal: { own: REVEAL, uses: [GLYPHS], budget: 58_000 },
Counter: { own: COUNTER, uses: [], budget: 45_000 },
Annotate: { own: ANNOTATE, uses: [], budget: 50_000 },
Captions: { own: CAPTIONS, uses: [GLYPHS], budget: 55_000 },
@@ -75,23 +89,48 @@ const COMPONENTS = {
};
const OWN = Object.values(COMPONENTS).map((c) => c.own);
-/** [names imported, markers that must not survive, max added bytes]. */
+/** Toolkit imports: [names, markers that must not survive, max added bytes]. */
const cases = [
[["themes", "defineTheme"], [CONTRACT, STROKES, TARGETS, MOTION], 3_000],
[["boxPath", "ellipsePath"], [CONTRACT, TARGETS, MOTION], 6_000],
[["resolveTarget", "targetPoint"], [CONTRACT, STROKES, MOTION], 10_000],
[["staggerOffsets", "toFrames"], [CONTRACT, STROKES, TARGETS, MOTION], 3_000],
- // Each component alone: none of the others, except what it composes.
- ...Object.entries(COMPONENTS).map(([name, c]) => [
- [name],
- [...OWN, GLYPHS].filter((m) => m !== c.own && !c.uses.includes(m)),
- c.budget,
- ]),
];
-async function bundle(contents) {
+// Install every registry component into a scratch folder, as `add` would.
+const installed = mkdtempSync(join(tmpdir(), "framefields-registry-"));
+const index = JSON.parse(readFileSync(join(registry, "index.json"), "utf8"));
+for (const entry of index) {
+ const item = JSON.parse(
+ readFileSync(join(registry, `${entry.name}.json`), "utf8"),
+ );
+ for (const file of item.files) {
+ mkdirSync(dirname(join(installed, file.path)), { recursive: true });
+ writeFileSync(join(installed, file.path), file.content);
+ }
+}
+const listed = new Set(index.map((e) => e.title));
+for (const name of Object.keys(COMPONENTS))
+ if (!listed.has(name)) throw new Error(`${name} is not in the registry`);
+for (const name of listed)
+ if (!(name in COMPONENTS))
+ throw new Error(
+ `${name} has no row in COMPONENTS: add its marker and budget`,
+ );
+
+/** Installed component sources resolve `framefields` to the built dist. */
+const toDist = {
+ name: "framefields-dist",
+ setup(b) {
+ b.onResolve({ filter: /^framefields(\/components)?$/ }, (args) => ({
+ path: args.path === "framefields" ? root : components,
+ }));
+ },
+};
+async function bundle(contents, resolveDir = process.cwd()) {
const result = await build({
- stdin: { contents, resolveDir: process.cwd(), loader: "js" },
+ stdin: { contents, resolveDir, loader: "ts" },
+ plugins: [toDist],
bundle: true,
write: false,
format: "esm",
@@ -106,17 +145,35 @@ const baseline = `import { Layer } from ${JSON.stringify(root)};\nconsole.log(La
const base = await bundle(baseline);
const failures = [];
-// Using framefields without components must carry none of them: component
-// modules may not build anything (schemas, glyphs) at import time.
+// Using framefields without components must carry none of the toolkit:
+// toolkit modules may not build anything (schemas, glyphs) at import time.
for (const marker of [CONTRACT, STROKES, TARGETS, GLYPHS, ...OWN]) {
if (base.includes(marker))
failures.push(`import { Layer } alone kept component code ("${marker}")`);
}
+// No component ships in the package itself.
+const walk = (dir) =>
+ readdirSync(dir, { withFileTypes: true }).flatMap((e) =>
+ e.isDirectory()
+ ? e.name === "registry" || e.name === "preview-engine"
+ ? []
+ : walk(join(dir, e.name))
+ : e.name.endsWith(".mjs")
+ ? [join(dir, e.name)]
+ : [],
+ );
+const dist = fileURLToPath(new URL("../dist", import.meta.url));
+for (const file of walk(dist)) {
+ const code = readFileSync(file, "utf8");
+ for (const [name, c] of Object.entries(COMPONENTS))
+ if (code.includes(c.own))
+ failures.push(`${file.slice(dist.length + 1)} contains ${name}`);
+}
for (const [names, forbidden, budget] of cases) {
const code = await bundle(
`${baseline}\nimport { ${names.join(", ")} } from ${JSON.stringify(components)};\nconsole.log(${names.join(", ")});`,
);
- const label = `import { ${names.join(", ")} }`;
+ const label = `import { ${names.join(", ")} } from "framefields/components"`;
for (const marker of forbidden) {
if (code.includes(marker)) {
failures.push(`${label} kept code containing "${marker}"`);
@@ -127,10 +184,31 @@ for (const [names, forbidden, budget] of cases) {
failures.push(`${label} added ${added} bytes (budget ${budget})`);
}
-if (failures.length > 0) {
- console.error(
- `framefields/components does not tree-shake:\n ${failures.join("\n ")}`,
+// Each installed component alone: none of the others, except what it composes.
+for (const entry of index) {
+ const c = COMPONENTS[entry.title];
+ const forbidden = [...OWN, GLYPHS].filter(
+ (m) => m !== c.own && !c.uses.includes(m),
);
+ const code = await bundle(
+ `${baseline}\nimport { ${entry.title} } from "./${entry.name}/index.js";\nconsole.log(${entry.title});`,
+ installed,
+ );
+ const label = `framefields add ${entry.name}`;
+ if (!code.includes(c.own)) failures.push(`${label}: lost its own code`);
+ for (const marker of forbidden)
+ if (code.includes(marker))
+ failures.push(`${label} kept code containing "${marker}"`);
+ const added = code.length - base.length;
+ if (added > c.budget)
+ failures.push(`${label} added ${added} bytes (budget ${c.budget})`);
+}
+rmSync(installed, { recursive: true, force: true });
+
+if (failures.length > 0) {
+ console.error(`Components do not tree-shake:\n ${failures.join("\n ")}`);
process.exit(1);
}
-console.log(`framefields/components tree-shakes (${cases.length} cases)`);
+console.log(
+ `components tree-shake (${cases.length} toolkit imports, ${index.length} installed components)`,
+);
diff --git a/packages/framefields/scripts/check-registry-types.mjs b/packages/framefields/scripts/check-registry-types.mjs
new file mode 100644
index 00000000..d8a7b302
--- /dev/null
+++ b/packages/framefields/scripts/check-registry-types.mjs
@@ -0,0 +1,76 @@
+// Fails the build when a registry component, installed the way
+// `framefields add` writes it, does not typecheck against the built dist.
+// Installs all of them into a scratch project that links this package as
+// `framefields`, then runs tsc under NodeNext and bundler resolution with
+// strict settings users commonly turn on.
+import { execFileSync } from "node:child_process";
+import {
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const pkg = fileURLToPath(new URL("..", import.meta.url));
+const registry = join(pkg, "dist/registry");
+const tsc = createRequire(import.meta.url).resolve("typescript/bin/tsc");
+
+const project = mkdtempSync(join(tmpdir(), "framefields-add-"));
+mkdirSync(join(project, "node_modules"));
+symlinkSync(pkg, join(project, "node_modules/framefields"), "dir");
+writeFileSync(join(project, "package.json"), '{ "type": "module" }\n');
+for (const entry of JSON.parse(
+ readFileSync(join(registry, "index.json"), "utf8"),
+)) {
+ const item = JSON.parse(
+ readFileSync(join(registry, `${entry.name}.json`), "utf8"),
+ );
+ for (const file of item.files) {
+ const target = join(project, "src/components", file.path);
+ mkdirSync(dirname(target), { recursive: true });
+ writeFileSync(target, file.content);
+ }
+}
+
+const strict = {
+ strict: true,
+ noEmit: true,
+ skipLibCheck: true,
+ target: "ES2022",
+ noUncheckedIndexedAccess: true,
+ verbatimModuleSyntax: true,
+ isolatedModules: true,
+};
+const failures = [];
+for (const [label, resolution] of [
+ ["NodeNext", { module: "NodeNext", moduleResolution: "NodeNext" }],
+ ["bundler", { module: "ESNext", moduleResolution: "Bundler" }],
+]) {
+ writeFileSync(
+ join(project, "tsconfig.json"),
+ JSON.stringify({
+ compilerOptions: { ...strict, ...resolution },
+ include: ["src"],
+ }),
+ );
+ try {
+ execFileSync(process.execPath, [tsc, "-p", project], { encoding: "utf8" });
+ } catch (error) {
+ failures.push(`${label}:\n${error.stdout}`);
+ }
+}
+rmSync(project, { recursive: true, force: true });
+
+if (failures.length > 0) {
+ console.error(
+ `Installed components do not typecheck:\n${failures.join("\n")}`,
+ );
+ process.exit(1);
+}
+console.log("installed components typecheck (NodeNext, bundler)");
diff --git a/packages/framefields/scripts/fix-dts-aliases.mjs b/packages/framefields/scripts/fix-dts-aliases.mjs
new file mode 100644
index 00000000..60a7acb4
--- /dev/null
+++ b/packages/framefields/scripts/fix-dts-aliases.mjs
@@ -0,0 +1,39 @@
+// Repairs a type-bundler slip in dist/*.d.mts: when the short alias it
+// picks for a chunk export equals a name already declared in that chunk
+// (framefields' own `Ai` interface, say), it can emit the export as
+// `type fn as Ai`, and consumers then get "cannot be used as a value".
+// A name the chunk declares as a function, const, class or enum is a value,
+// so its `type` modifier is dropped.
+import { readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+export function fixDtsAliases(dir = "dist") {
+ const fixed = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const file = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ fixed.push(...fixDtsAliases(file));
+ continue;
+ }
+ if (!entry.name.endsWith(".d.mts")) continue;
+ const code = readFileSync(file, "utf8");
+ const out = code.replace(
+ /\btype ([A-Za-z_$][\w$]*) as ([\w$]+)/g,
+ (whole, name, alias) => {
+ const value = new RegExp(
+ `declare (?:function|const|let|var|class|enum|abstract class) ${name.replace(/\$/g, "\\$")}\\b`,
+ );
+ if (!value.test(code)) return whole;
+ fixed.push(`${file}: ${name} as ${alias}`);
+ return `${name} as ${alias}`;
+ },
+ );
+ if (out !== code) writeFileSync(file, out);
+ }
+ return fixed;
+}
+
+if (import.meta.url === `file://${process.argv[1]}`) {
+ for (const f of fixDtsAliases())
+ console.log(`fixed type-only value export ${f}`);
+}
diff --git a/packages/framefields/src/cli.ts b/packages/framefields/src/cli.ts
new file mode 100644
index 00000000..67868846
--- /dev/null
+++ b/packages/framefields/src/cli.ts
@@ -0,0 +1,125 @@
+#!/usr/bin/env node
+/**
+ * The `framefields` command.
+ *
+ * npx framefields add <name...> copy components into this project
+ * npx framefields list the components you can add
+ */
+import { readFileSync } from "node:fs";
+import { relative } from "node:path";
+import { parseArgs } from "node:util";
+import { add } from "./cli/add.js";
+import { openRegistry } from "./cli/registry.js";
+
+const HELP = `Usage: framefields <command> [options]
+
+Commands:
+ add <name...> Copy components' source into this project (and the
+ components they build on). The code is yours to edit.
+ list List the components you can add.
+
+Options for add:
+ --all Add every component.
+ --dir <path> Components directory (default: from framefields.json,
+ else src/components or components). Saved the first time.
+ --overwrite Replace files you have changed.
+
+Options for both:
+ --registry <src> A registry folder or http(s) URL instead of the one
+ shipped with this version of framefields.
+ -h, --help Show this help.
+
+Example:
+ npx framefields add mouse-pointer focus-zoom
+`;
+
+async function main(argv: string[]): Promise<number> {
+ const { values, positionals } = parseArgs({
+ args: argv,
+ allowPositionals: true,
+ options: {
+ all: { type: "boolean" },
+ dir: { type: "string" },
+ overwrite: { type: "boolean" },
+ registry: { type: "string" },
+ help: { type: "boolean", short: "h" },
+ },
+ });
+ const [command, ...names] = positionals;
+ if (values.help || !command) {
+ process.stdout.write(HELP);
+ return command || values.help ? 0 : 1;
+ }
+ const cwd = process.cwd();
+ const registry = openRegistry(values.registry, cwd);
+
+ if (command === "list") {
+ const index = await registry.index();
+ const width = Math.max(...index.map((e) => e.name.length));
+ for (const e of index)
+ process.stdout.write(`${e.name.padEnd(width)} ${e.summary}\n`);
+ return 0;
+ }
+ if (command !== "add") {
+ process.stderr.write(`Unknown command "${command}".\n\n${HELP}`);
+ return 1;
+ }
+
+ const wanted = values.all
+ ? (await registry.index()).map((e) => e.name)
+ : names;
+ if (wanted.length === 0) {
+ process.stderr.write(
+ "Name the components to add, e.g. `framefields add mouse-pointer`.\nRun `framefields list` to see them all.\n",
+ );
+ return 1;
+ }
+ const report = await add(wanted, {
+ cwd,
+ registry,
+ dir: values.dir,
+ overwrite: values.overwrite,
+ });
+ const log = (line: string) => process.stdout.write(`${line}\n`);
+ for (const f of report.written) log(` wrote ${f}`);
+ for (const f of report.unchanged) log(` unchanged ${f}`);
+ for (const f of report.skipped)
+ log(` skipped ${f} (yours differs; --overwrite replaces it)`);
+ if (report.configWritten) log(" wrote framefields.json");
+ const extra = report.components.filter((c) => !wanted.includes(c.name));
+ if (extra.length > 0)
+ log(`\nWith what they build on: ${extra.map((c) => c.name).join(", ")}.`);
+ warnIfMissingFramefields(cwd, log);
+ const first = report.components.find((c) => wanted.includes(c.name));
+ if (first)
+ log(
+ `\nimport { ${first.title} } from "./${first.name}/index.js"; // from ${relative(cwd, report.dir) || "."}`,
+ );
+ return 0;
+}
+
+/** Installed components import `framefields`; say so if the project lacks it. */
+function warnIfMissingFramefields(cwd: string, log: (s: string) => void) {
+ try {
+ const pkg = JSON.parse(readFileSync(`${cwd}/package.json`, "utf8")) as {
+ dependencies?: Record<string, string>;
+ devDependencies?: Record<string, string>;
+ };
+ if (!pkg.dependencies?.framefields && !pkg.devDependencies?.framefields)
+ log(
+ "\nThese components import `framefields`: add it with `npm i framefields`.",
+ );
+ } catch {
+ // No package.json: nothing to check.
+ }
+}
+
+main(process.argv.slice(2)).then(
+ (code) => process.exit(code),
+ (error: unknown) => {
+ process.stderr.write(
+ `framefields: ${error instanceof Error ? error.message : String(error)}\n`,
+ );
+ process.exit(1);
+ },
+);
diff --git a/packages/framefields/src/cli/add.test.ts b/packages/framefields/src/cli/add.test.ts
new file mode 100644
index 00000000..b9a9f56d
--- /dev/null
+++ b/packages/framefields/src/cli/add.test.ts
@@ -0,0 +1,125 @@
+import {
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { add, CONFIG_FILE, readConfig } from "./add.js";
+import { openRegistry, type RegistryItem } from "./registry.js";
+
+const item = (
+ name: string,
+ files: Record<string, string>,
+ registryDependencies: string[] = [],
+): RegistryItem => ({
+ name,
+ title: name,
+ summary: `${name} summary`,
+ tags: [],
+ example: "",
+ parts: [],
+ cues: [],
+ registryDependencies,
+ files: Object.entries(files).map(([path, content]) => ({ path, content })),
+});
+
+let tmp: string;
+let cwd: string;
+let registryDir: string;
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "framefields-add-test-"));
+ cwd = join(tmp, "project");
+ registryDir = join(tmp, "registry");
+ mkdirSync(cwd);
+ mkdirSync(registryDir);
+ const items = [
+ item("counter", {
+ "counter/index.ts": "counter\n",
+ "counter/plan.ts": "plan\n",
+ }),
+ item("meter", { "meter/index.ts": "meter\n" }, ["counter"]),
+ item("terminal", { "terminal/index.ts": "terminal\n" }, [
+ "counter",
+ "meter",
+ ]),
+ ];
+ writeFileSync(join(registryDir, "index.json"), JSON.stringify(items));
+ for (const i of items)
+ writeFileSync(join(registryDir, `${i.name}.json`), JSON.stringify(i));
+});
+afterEach(() => rmSync(tmp, { recursive: true, force: true }));
+
+describe("framefields add", () => {
+ it("installs dependencies first, once each, and remembers the folder", async () => {
+ mkdirSync(join(cwd, "src"));
+ const report = await add(["terminal", "meter"], {
+ cwd,
+ registry: openRegistry(registryDir),
+ });
+ expect(report.components.map((c) => c.name)).toEqual([
+ "counter",
+ "meter",
+ "terminal",
+ ]);
+ expect(report.written).toEqual([
+ "src/components/counter/index.ts",
+ "src/components/counter/plan.ts",
+ "src/components/meter/index.ts",
+ "src/components/terminal/index.ts",
+ ]);
+ expect(
+ readFileSync(join(cwd, "src/components/counter/plan.ts"), "utf8"),
+ ).toBe("plan\n");
+ expect(report.configWritten).toBe(true);
+ expect(readConfig(cwd)).toEqual({
+ config: { components: "src/components" },
+ saved: true,
+ });
+ });
+
+ it("uses `components` without a src folder, and --dir once saved", async () => {
+ expect(readConfig(cwd).config.components).toBe("components");
+ await add(["counter"], {
+ cwd,
+ registry: openRegistry(registryDir),
+ dir: "lib/fx",
+ });
+ expect(JSON.parse(readFileSync(join(cwd, CONFIG_FILE), "utf8"))).toEqual({
+ components: "lib/fx",
+ });
+ const again = await add(["meter"], {
+ cwd,
+ registry: openRegistry(registryDir),
+ });
+ expect(again.written).toEqual(["lib/fx/meter/index.ts"]);
+ expect(again.unchanged).toEqual([
+ "lib/fx/counter/index.ts",
+ "lib/fx/counter/plan.ts",
+ ]);
+ expect(again.configWritten).toBe(false);
+ });
+
+ it("leaves edited files alone unless told to overwrite", async () => {
+ const registry = openRegistry(registryDir);
+ await add(["counter"], { cwd, registry });
+ const file = join(cwd, "components/counter/index.ts");
+ writeFileSync(file, "my edits\n");
+ const kept = await add(["counter"], { cwd, registry });
+ expect(kept.skipped).toEqual(["components/counter/index.ts"]);
+ expect(readFileSync(file, "utf8")).toBe("my edits\n");
+ const replaced = await add(["counter"], { cwd, registry, overwrite: true });
+ expect(replaced.written).toEqual(["components/counter/index.ts"]);
+ expect(readFileSync(file, "utf8")).toBe("counter\n");
+ });
+
+ it("rejects unknown names before writing anything", async () => {
+ await expect(
+ add(["counter", "nope"], { cwd, registry: openRegistry(registryDir) }),
+ ).rejects.toThrow('Unknown component "nope"');
+ expect(() => readFileSync(join(cwd, CONFIG_FILE))).toThrow();
+ });
+});
diff --git a/packages/framefields/src/cli/add.ts b/packages/framefields/src/cli/add.ts
new file mode 100644
index 00000000..fe76a8cd
--- /dev/null
+++ b/packages/framefields/src/cli/add.ts
@@ -0,0 +1,124 @@
+/**
+ * `framefields add`: copy components' source into a project, the way a
+ * shadcn-style registry does. The code becomes the project's own; it
+ * imports only `framefields` and `framefields/components` (the toolkit),
+ * plus any component it builds on, which is installed alongside it.
+ *
+ * Where they go is remembered in `framefields.json` at the project root.
+ */
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, join, relative, resolve } from "node:path";
+import type { Registry, RegistryItem } from "./registry.js";
+
+export const CONFIG_FILE = "framefields.json";
+
+export interface ProjectConfig {
+ /** Components directory, relative to the project root. */
+ components: string;
+}
+
+/** The project's config, or the default it would get: `src/components` when there is a `src`. */
+export function readConfig(cwd: string): {
+ config: ProjectConfig;
+ saved: boolean;
+} {
+ const file = join(cwd, CONFIG_FILE);
+ if (existsSync(file)) {
+ const config = JSON.parse(
+ readFileSync(file, "utf8"),
+ ) as Partial<ProjectConfig>;
+ if (typeof config.components !== "string")
+ throw new Error(`${CONFIG_FILE}: "components" must be a directory path`);
+ return { config: config as ProjectConfig, saved: true };
+ }
+ const components = existsSync(join(cwd, "src"))
+ ? "src/components"
+ : "components";
+ return { config: { components }, saved: false };
+}
+
+export interface AddOptions {
+ cwd: string;
+ registry: Registry;
+ /** Components directory; saved to `framefields.json` if there is none yet. */
+ dir?: string;
+ /** Replace files that differ from the registry's. */
+ overwrite?: boolean;
+}
+
+export interface AddReport {
+ dir: string;
+ /** Components in install order (dependencies first). */
+ components: RegistryItem[];
+ written: string[];
+ unchanged: string[];
+ /** Files left alone because they differ and `overwrite` is off. */
+ skipped: string[];
+ configWritten: boolean;
+}
+
+/** Resolve `names` (and what they import) and write their files. */
+export async function add(
+ names: string[],
+ options: AddOptions,
+): Promise<AddReport> {
+ const { cwd, registry } = options;
+ const index = await registry.index();
+ const known = new Set(index.map((e) => e.name));
+ for (const n of names)
+ if (!known.has(n))
+ throw new Error(
+ `Unknown component "${n}". Run \`framefields list\` to see them all.`,
+ );
+
+ // Depth-first, dependencies before dependants.
+ const order: RegistryItem[] = [];
+ const seen = new Set<string>();
+ const visit = async (name: string) => {
+ if (seen.has(name)) return;
+ seen.add(name);
+ const item = await registry.item(name);
+ for (const d of item.registryDependencies) await visit(d);
+ order.push(item);
+ };
+ for (const n of names) await visit(n);
+
+ const { config, saved } = readConfig(cwd);
+ const rel = options.dir ?? config.components;
+ const dir = resolve(cwd, rel);
+ const report: AddReport = {
+ dir,
+ components: order,
+ written: [],
+ unchanged: [],
+ skipped: [],
+ configWritten: false,
+ };
+ for (const item of order) {
+ for (const file of item.files) {
+ const target = join(dir, file.path);
+ const shown = relative(cwd, target);
+ if (existsSync(target)) {
+ if (readFileSync(target, "utf8") === file.content) {
+ report.unchanged.push(shown);
+ continue;
+ }
+ if (!options.overwrite) {
+ report.skipped.push(shown);
+ continue;
+ }
+ }
+ mkdirSync(dirname(target), { recursive: true });
+ writeFileSync(target, file.content);
+ report.written.push(shown);
+ }
+ }
+ if (!saved) {
+ writeFileSync(
+ join(cwd, CONFIG_FILE),
+ `${JSON.stringify({ components: relative(cwd, dir) || "." }, null, "\t")}\n`,
+ );
+ report.configWritten = true;
+ }
+ return report;
+}
diff --git a/packages/framefields/src/cli/registry.ts b/packages/framefields/src/cli/registry.ts
new file mode 100644
index 00000000..bd728560
--- /dev/null
+++ b/packages/framefields/src/cli/registry.ts
@@ -0,0 +1,72 @@
+/**
+ * Reading a component registry: the one shipped in this package's dist, a
+ * local folder, or one served over http(s). A registry is `index.json` (the
+ * entries) plus `<name>.json` per component (entry, meta and files).
+ */
+import { existsSync, readFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+export interface RegistryEntry {
+ /** What `framefields add` takes: `logo-reveal`. */
+ name: string;
+ /** The factory the component exports: `LogoReveal`. */
+ title: string;
+ summary: string;
+ tags: readonly string[];
+ example: string;
+ /** Other components it imports, installed with it. */
+ registryDependencies: string[];
+}
+
+export interface RegistryItem extends RegistryEntry {
+ parts: readonly string[];
+ cues: readonly string[];
+ /** Paths relative to the components directory. */
+ files: Array<{ path: string; content: string }>;
+}
+
+export interface Registry {
+ /** Where it was read from, for messages. */
+ source: string;
+ index(): Promise<RegistryEntry[]>;
+ item(name: string): Promise<RegistryItem>;
+}
+
+/** The registry shipped next to this module in dist (`dist/registry`). */
+export function bundledRegistryPath(): string {
+ return fileURLToPath(new URL("./registry/", import.meta.url));
+}
+
+/** `source`: a folder or an http(s) URL. Default: the bundled registry. */
+export function openRegistry(source?: string, cwd = process.cwd()): Registry {
+ const from =
+ source ?? process.env.FRAMEFIELDS_REGISTRY ?? bundledRegistryPath();
+ if (/^https?:\/\//.test(from)) {
+ const base = from.endsWith("/") ? from : `${from}/`;
+ const get = async <T>(file: string): Promise<T> => {
+ const res = await fetch(new URL(file, base));
+ if (!res.ok)
+ throw new Error(
+ `${new URL(file, base)}: ${res.status} ${res.statusText}`,
+ );
+ return (await res.json()) as T;
+ };
+ return {
+ source: base,
+ index: () => get("index.json"),
+ item: (name) => get(`${name}.json`),
+ };
+ }
+ const dir = resolve(cwd, from);
+ const read = <T>(file: string): T => {
+ const path = join(dir, file);
+ if (!existsSync(path)) throw new Error(`No ${file} in registry ${dir}`);
+ return JSON.parse(readFileSync(path, "utf8")) as T;
+ };
+ return {
+ source: dir,
+ index: async () => read("index.json"),
+ item: async (name) => read(`${name}.json`),
+ };
+}
diff --git a/packages/framefields/src/components/audio.ts b/packages/framefields/src/components/audio.ts
index d5c81b92..6f422386 100644
--- a/packages/framefields/src/components/audio.ts
+++ b/packages/framefields/src/components/audio.ts
@@ -7,7 +7,7 @@ import {
type AnalyzeOptions,
type AudioLevels,
analyzeChannels,
-} from "@framefields/components";
+} from "@framefields/components/toolkit";
import { decodeAudioSource } from "@framefields/compositions";
export async function analyzeAudio(
diff --git a/packages/framefields/src/components/contract.render.test.ts b/packages/framefields/src/components/contract.render.test.ts
index 1174404a..8f9ff7db 100644
--- a/packages/framefields/src/components/contract.render.test.ts
+++ b/packages/framefields/src/components/contract.render.test.ts
@@ -1,4 +1,4 @@
-import { defineComponent } from "@framefields/components";
+import { defineComponent } from "@framefields/components/toolkit";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { Composition, CompositorProgramSchema, Layer } from "../index.js";
diff --git a/packages/framefields/src/components/host.ts b/packages/framefields/src/components/host.ts
index 85d45e8a..6cf0343d 100644
--- a/packages/framefields/src/components/host.ts
+++ b/packages/framefields/src/components/host.ts
@@ -1,9 +1,9 @@
/**
- * The host framefields injects into `@framefields/components`: the `Layer`
+ * The host framefields injects into component builds: the `Layer`
* factories, real font measurement and stable ids. `Layer` is read inside
* each call, never at module load, so importing this file has no effects.
*/
-import type { Host, LayerStyleConfig } from "@framefields/components";
+import type { Host, LayerStyleConfig } from "@framefields/components/toolkit";
import { frameArraySignal } from "@framefields/core";
import { FilmGrain, LayerStyle } from "../effects/index.js";
import { FontManager } from "../fonts/index.js";
diff --git a/packages/framefields/src/components/index.ts b/packages/framefields/src/components/index.ts
index fcda7f2a..15abd015 100644
--- a/packages/framefields/src/components/index.ts
+++ b/packages/framefields/src/components/index.ts
@@ -1,46 +1,20 @@
/**
- * `framefields/components`: the component library and the toolkit for
- * building components. Components are also exported from the `framefields`
- * root; this subpath adds the authoring toolkit (timing, paths, strokes,
- * targets, baking).
+ * `framefields/components`: the toolkit components are built from. The
+ * components themselves are not in the package: `npx framefields add <name>`
+ * copies their source into your project, where it imports this toolkit
+ * (timing, paths, strokes, targets, baking, themes) and `bindComponent`.
*
- * Each component is bound to the framefields host with a PURE call, so
- * bundlers drop every component that isn't imported.
+ * Named exports with no top-level calls, so bundlers keep only what a
+ * project's components use.
*/
-import {
- annotate,
- appFrame,
- type BaseProps,
- backdrop,
- beforeAfter,
- bind,
- type ComponentDefinition,
- type ComponentExtras,
- type Cues,
- callout,
- captions,
- cardStack,
- chatThread,
- codeBlock,
- confetti,
- counter,
- deviceFrame,
- focusZoom,
- logoReveal,
- lowerThird,
- meter,
- mousePointer,
- selection,
- spotlight,
- terminal,
- textReveal,
- titleCard,
- toasts,
- touchPoint,
- waveform,
- wordCycle,
-} from "@framefields/components";
+import type {
+ BaseProps,
+ ComponentDefinition,
+ ComponentExtras,
+ Cues,
+} from "@framefields/components/toolkit";
+import { bind } from "@framefields/components/toolkit";
import type { BoxNode } from "@framefields/compositions/program";
import type { z } from "zod";
import type { AnimatableNode } from "../index.js";
@@ -51,8 +25,9 @@ export type ComponentNode<C extends Cues = Cues> = AnimatableNode<BoxNode> &
ComponentExtras<C>;
/**
- * Bind a component definition to framefields, producing its factory. Use it
- * for your own components built with `defineComponent`.
+ * Bind a component definition to framefields, producing its factory. Every
+ * installed component ends with one of these; use it for your own
+ * components built with `defineComponent` too.
*/
export function bindComponent<
S extends z.ZodRawShape,
@@ -64,287 +39,7 @@ export function bindComponent<
return bind(host, definition) as never;
}
-/** An animated pointer that travels, clicks, drags and changes shape, with a cue for every click. */
-export const MousePointer = /* @__PURE__ */ bindComponent(mousePointer);
-
-/** Window chrome (desktop window, browser, terminal) around any content; `at(x, y)` points into it. */
-export const AppFrame = /* @__PURE__ */ bindComponent(appFrame);
-
-/** A camera over 2D content that pushes in on clicks or shots and eases back out. */
-export const FocusZoom = /* @__PURE__ */ bindComponent(focusZoom);
-
-/** Text that animates in and out by character, word or line, ending on exactly the static text. */
-export const TextReveal = /* @__PURE__ */ bindComponent(textReveal);
-
-/** A number that counts to its value on odometer reels, format-aware. */
-export const Counter = /* @__PURE__ */ bindComponent(counter);
-
-/** Marks that draw on to point at something: underline, circle, arrow, highlight … hand-drawn or clean. */
-export const Annotate = /* @__PURE__ */ bindComponent(annotate);
-
-/** Word-timed captions in published styles, each word on its exact frame, optionally behind the speaker. */
-export const Captions = /* @__PURE__ */ bindComponent(captions);
-
-/** A scripted shell session: typed commands, streaming output, spinners, progress and scrolling. */
-export const Terminal = /* @__PURE__ */ bindComponent(terminal);
-
-/** Code on screen: syntax colours, typing, a focus band and diffs where kept lines glide. */
-export const CodeBlock = /* @__PURE__ */ bindComponent(codeBlock);
-
-/** Kicker, headline, rule and sub-line in designed layouts, on one timeline. */
-export const TitleCard = /* @__PURE__ */ bindComponent(titleCard);
-
-/** A name-and-role bar for interviews and talks that slides in and leaves on its own. */
-export const LowerThird = /* @__PURE__ */ bindComponent(lowerThird);
-
-/** Progress and scores: ring, arc, bar, segments or stars, filling with its counter. */
-export const Meter = /* @__PURE__ */ bindComponent(meter);
-
-/** A messaging conversation: springy bubbles, typing dots, reactions and auto-scroll. */
-export const ChatThread = /* @__PURE__ */ bindComponent(chatThread);
-
-/** Notifications arriving into a corner stack that compresses as it grows. */
-export const Toasts = /* @__PURE__ */ bindComponent(toasts);
-
-/** A label with a leader line pinned to a point or a moving tracked object. */
-export const Callout = /* @__PURE__ */ bindComponent(callout);
-
-/** Dims the frame except a region that glides between targets. */
-export const Spotlight = /* @__PURE__ */ bindComponent(spotlight);
-
-/** GPU confetti bursts: paper, ribbons and sparkles that fall and can settle. */
-export const Confetti = /* @__PURE__ */ bindComponent(confetti);
-
-/** The end-card lockup: mark and wordmark in one move, drawn, popped or wiped, with a glint. */
-export const LogoReveal = /* @__PURE__ */ bindComponent(logoReveal);
-
-/** A drifting mesh gradient, grid or dot field with vignette and grain, looping exactly. */
-export const Backdrop = /* @__PURE__ */ bindComponent(backdrop);
-
-/** An audiogram: bars, mirrored bars, dots or a ring bound to a track's analysed spectrum. */
-export const Waveform = /* @__PURE__ */ bindComponent(waveform);
-
-/** One slot in a line cycles through words; the line glides to fit each one. */
-export const WordCycle = /* @__PURE__ */ bindComponent(wordCycle);
-
-export {
- type AnalyzeOptions,
- type Anchor,
- type AnnotateCues,
- type AppFrameApi,
- type AppFrameCues,
- type AppFrameKind,
- type ArcPath,
- type ArrowCurve,
- type ArrowGeometry,
- type AudioLevels,
- analyzeChannels,
- anchorPoint,
- arcPath,
- arrowPaths,
- audioLevelsSchema,
- BACKDROP_KINDS,
- type BackdropCues,
- type BackdropKind,
- type BakedKey,
- type BakeOptions,
- type BaseProps,
- type BeforeAfterCues,
- type BuildContext,
- type BuildResult,
- bakeFunction,
- bakeSamples,
- bandEdges,
- basePropsSchema,
- beats,
- boilKeys,
- boundsOf,
- boxPath,
- CALLOUT_SIDES,
- CAPTION_STYLES,
- type CalloutCues,
- type CalloutSide,
- type CaptionStyle,
- type CaptionsCues,
- type CardStackCues,
- type ChatThreadCues,
- CODE_LANGS,
- type CodeBlockCues,
- type CodeLang,
- type ComponentDefaults,
- type ComponentDefinition,
- type ComponentExtras,
- type ComponentMeta,
- type ConfettiCues,
- type CounterCues,
- type CounterFormat,
- CURSOR_STYLES,
- type Cue,
- type Cues,
- type CuesOf,
- type CursorStyle,
- type CutoutOptions,
- catmullRom,
- chain,
- constantExpression,
- contrastRatio,
- cosineKeys,
- cover,
- DEVICES,
- type Device,
- type DeviceFrameApi,
- type DeviceFrameCues,
- defineComponent,
- defineMeta,
- defineTheme,
- dist,
- drawOnKeys,
- type EaseFn,
- EXIT_STYLES,
- type ExitStyle,
- type ExtrudedTextOptions,
- ease,
- ellipsePath,
- enterAnimation,
- evaluateEase,
- evaluateGlyphExpression,
- exitAnimation,
- type FocusZoomApi,
- type FocusZoomCues,
- type Followable,
- type FrameWindow,
- findRange,
- frameSpan,
- type GlyphAnimator,
- type GlyphProps,
- type GlyphUnit,
- type GrainOptions,
- glyphAnimator,
- type HandOptions,
- hashRng,
- hashString,
- LOGO_LAYOUTS,
- LOGO_STYLES,
- LOWER_THIRD_LAYOUTS,
- type LogoLayout,
- type LogoRevealCues,
- type LogoStyle,
- type LowerThirdCues,
- type LowerThirdLayout,
- lerp2,
- linePath,
- lineShift,
- MARKS,
- type Mark,
- METER_KINDS,
- type MeasureOptions,
- type MeterCues,
- type MeterKind,
- type Metrics,
- MOTION_PRESETS,
- type MotionOptions,
- type MotionPreset,
- type MotionPresetName,
- type MotionSize,
- type MousePointerApi,
- type MousePointerCues,
- offsetCues,
- type ParticleOptions,
- type Placement,
- type PlannedTouch,
- type PropsOf,
- type PulseOptions,
- planTouches,
- pulseKeys,
- quantize,
- REVEAL_STYLES,
- type Rect,
- type ResolvedMotion,
- type ResolvedTarget,
- type RevealStyle,
- type Rng,
- rangeRects,
- resampleBands,
- resolveMotion,
- resolveTarget,
- rng,
- type SelectionCues,
- type SelectionPointer,
- type SpotlightCues,
- type StaggerOrder,
- scaleFrames,
- scheduleExpression,
- slideKeys,
- smoothRelease,
- springAt,
- springKeys,
- springSettleFrames,
- springTrack,
- squigglePath,
- staggerOffsets,
- staggerRanks,
- stepExpression,
- type Target,
- type TargetContext,
- type TerminalCues,
- type TerminalStep,
- type TextLayout,
- type TextRevealApi,
- type TextRevealCues,
- type Theme,
- type ThemeInput,
- type ThemeName,
- TITLE_LAYOUTS,
- type TitleCardCues,
- type TitleLayout,
- TOAST_CORNERS,
- TOAST_KINDS,
- type ToastCorner,
- type ToastKind,
- type ToastsCues,
- type Token,
- type TokenKind,
- type TouchPointCues,
- targetPoint,
- textLayout,
- themeFrames,
- themes,
- toFrames,
- tokenize,
- toPathData,
- toSeconds,
- typingFrames,
- type UnitSchedule,
- type Vec2,
- WAVEFORM_KINDS,
- type WaveformCues,
- type WaveformKind,
- type Waypoint,
- WORD_SLOTS,
- WORD_TRANSITIONS,
- type Word,
- type WordCycleCues,
- type WordRange,
- type WordSlot,
- type WordTransition,
- windowExpression,
- within,
- wobblePoints,
- wordRanges,
-} from "@framefields/components";
-/** A phone, tablet or laptop around a screen; content in device points, `at(x, y)` for touches. */
-export const DeviceFrame = /* @__PURE__ */ bindComponent(deviceFrame);
-
-/** Taps, long presses and swipes as soft discs with ripples, for mobile demos. */
-export const TouchPoint = /* @__PURE__ */ bindComponent(touchPoint);
-
-/** Two versions of one picture split by a moving divider, with a grip and labels. */
-export const BeforeAfter = /* @__PURE__ */ bindComponent(beforeAfter);
-
-/** A text selection or marquee that follows a MousePointer drag. */
-export const Selection = /* @__PURE__ */ bindComponent(selection);
-
-/** Cards in a depth stack that shuffle forward or are dealt onto the pile. */
-export const CardStack = /* @__PURE__ */ bindComponent(cardStack);
-
+export * from "@framefields/components/toolkit";
+/** framefields' own zod, so component schemas share its instance. */
+export { z } from "zod";
export { analyzeAudio } from "./audio.js";
diff --git a/packages/framefields/src/components/m1.render.test.ts b/packages/framefields/src/components/m1.render.test.ts
index 56af6a70..b19be1ca 100644
--- a/packages/framefields/src/components/m1.render.test.ts
+++ b/packages/framefields/src/components/m1.render.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { Composition, Layer } from "../index.js";
import { decodePngPixels, getPixel } from "../test-utils/pixels.js";
-import { AppFrame, FocusZoom, MousePointer } from "./index.js";
+import { AppFrame, FocusZoom, MousePointer } from "./testing.js";
/**
* Render tests for the M1 components (spec §7.1, §7.2, §7.7): what the
diff --git a/packages/framefields/src/components/m2.render.test.ts b/packages/framefields/src/components/m2.render.test.ts
index 3f1085bc..3ec8b35d 100644
--- a/packages/framefields/src/components/m2.render.test.ts
+++ b/packages/framefields/src/components/m2.render.test.ts
@@ -2,7 +2,7 @@ import { beforeAll, describe, expect, it } from "vitest";
import { FontManager } from "../fonts/index.js";
import { Composition, Layer, themes } from "../index.js";
import { computeMse, decodePngPixels, getPixel } from "../test-utils/pixels.js";
-import { Annotate, Counter, TextReveal } from "./index.js";
+import { Annotate, Counter, TextReveal } from "./testing.js";
/**
* Render tests for the M2 components (spec §7.4–7.6): reveals end on exactly
diff --git a/packages/framefields/src/components/m3.render.test.ts b/packages/framefields/src/components/m3.render.test.ts
index 3d0f1acb..90356e5d 100644
--- a/packages/framefields/src/components/m3.render.test.ts
+++ b/packages/framefields/src/components/m3.render.test.ts
@@ -2,7 +2,7 @@ import { beforeAll, describe, expect, it } from "vitest";
import { FontManager } from "../fonts/index.js";
import { Composition } from "../index.js";
import { computeMse, decodePngPixels } from "../test-utils/pixels.js";
-import { Captions, Terminal } from "./index.js";
+import { Captions, Terminal } from "./testing.js";
/**
* Render tests for the M3 components (spec §7.3, §7.8): word colour changes
diff --git a/packages/framefields/src/components/m4.render.test.ts b/packages/framefields/src/components/m4.render.test.ts
index 6559b7cc..c862cf4c 100644
--- a/packages/framefields/src/components/m4.render.test.ts
+++ b/packages/framefields/src/components/m4.render.test.ts
@@ -2,7 +2,7 @@ import { beforeAll, describe, expect, it } from "vitest";
import { FontManager } from "../fonts/index.js";
import { Composition } from "../index.js";
import { computeMse, decodePngPixels, getPixel } from "../test-utils/pixels.js";
-import { CodeBlock, Meter, TitleCard } from "./index.js";
+import { CodeBlock, Meter, TitleCard } from "./testing.js";
/**
* Render tests for the M4 components (spec §7.9–7.12): a settled diff is the
diff --git a/packages/framefields/src/components/m5.render.test.ts b/packages/framefields/src/components/m5.render.test.ts
index f174a48d..9fb6c360 100644
--- a/packages/framefields/src/components/m5.render.test.ts
+++ b/packages/framefields/src/components/m5.render.test.ts
@@ -2,7 +2,7 @@ import { beforeAll, describe, expect, it } from "vitest";
import { FontManager } from "../fonts/index.js";
import { Composition, Layer } from "../index.js";
import { computeMse, decodePngPixels, getPixel } from "../test-utils/pixels.js";
-import { ChatThread, Confetti, Spotlight, Toasts } from "./index.js";
+import { ChatThread, Confetti, Spotlight, Toasts } from "./testing.js";
/**
* Render tests for the M5 components: nothing shows before its time (the
diff --git a/packages/framefields/src/components/m7.render.test.ts b/packages/framefields/src/components/m7.render.test.ts
index c3cdafc7..4a557094 100644
--- a/packages/framefields/src/components/m7.render.test.ts
+++ b/packages/framefields/src/components/m7.render.test.ts
@@ -1,4 +1,4 @@
-import type { AudioLevels } from "@framefields/components";
+import type { AudioLevels } from "@framefields/components/toolkit";
import { beforeAll, describe, expect, it } from "vitest";
import { FontManager } from "../fonts/index.js";
import { Composition } from "../index.js";
@@ -9,7 +9,7 @@ import {
LogoReveal,
Waveform,
WordCycle,
-} from "./index.js";
+} from "./testing.js";
/**
* Render tests for the M7 components: the lockup's name waits behind the
diff --git a/packages/framefields/src/components/m8.render.test.ts b/packages/framefields/src/components/m8.render.test.ts
index cafc98b3..74078f20 100644
--- a/packages/framefields/src/components/m8.render.test.ts
+++ b/packages/framefields/src/components/m8.render.test.ts
@@ -8,7 +8,7 @@ import {
DeviceFrame,
Selection,
TouchPoint,
-} from "./index.js";
+} from "./testing.js";
/**
* Render tests for the M8 components: device content fills exactly the
diff --git a/packages/framefields/src/components/testing.ts b/packages/framefields/src/components/testing.ts
new file mode 100644
index 00000000..add83afb
--- /dev/null
+++ b/packages/framefields/src/components/testing.ts
@@ -0,0 +1,61 @@
+/**
+ * Test-only: every registry component bound to framefields from its source,
+ * so render tests exercise the code `framefields add` installs (which
+ * differs only in its import paths). Not a build entry; not shipped.
+ */
+import {
+ annotate,
+ appFrame,
+ backdrop,
+ beforeAfter,
+ callout,
+ captions,
+ cardStack,
+ chatThread,
+ codeBlock,
+ confetti,
+ counter,
+ deviceFrame,
+ focusZoom,
+ logoReveal,
+ lowerThird,
+ meter,
+ mousePointer,
+ selection,
+ spotlight,
+ terminal,
+ textReveal,
+ titleCard,
+ toasts,
+ touchPoint,
+ waveform,
+ wordCycle,
+} from "@framefields/components";
+import { bindComponent } from "./index.js";
+
+export const Annotate = bindComponent(annotate);
+export const AppFrame = bindComponent(appFrame);
+export const Backdrop = bindComponent(backdrop);
+export const BeforeAfter = bindComponent(beforeAfter);
+export const Callout = bindComponent(callout);
+export const Captions = bindComponent(captions);
+export const CardStack = bindComponent(cardStack);
+export const ChatThread = bindComponent(chatThread);
+export const CodeBlock = bindComponent(codeBlock);
+export const Confetti = bindComponent(confetti);
+export const Counter = bindComponent(counter);
+export const DeviceFrame = bindComponent(deviceFrame);
+export const FocusZoom = bindComponent(focusZoom);
+export const LogoReveal = bindComponent(logoReveal);
+export const LowerThird = bindComponent(lowerThird);
+export const Meter = bindComponent(meter);
+export const MousePointer = bindComponent(mousePointer);
+export const Selection = bindComponent(selection);
+export const Spotlight = bindComponent(spotlight);
+export const Terminal = bindComponent(terminal);
+export const TextReveal = bindComponent(textReveal);
+export const TitleCard = bindComponent(titleCard);
+export const Toasts = bindComponent(toasts);
+export const TouchPoint = bindComponent(touchPoint);
+export const Waveform = bindComponent(waveform);
+export const WordCycle = bindComponent(wordCycle);
diff --git a/packages/framefields/src/index.ts b/packages/framefields/src/index.ts
index b8a9ef68..61c6be22 100644
--- a/packages/framefields/src/index.ts
+++ b/packages/framefields/src/index.ts
@@ -3381,10 +3381,12 @@ export const Effect = Object.assign(CoreEffect, effectFactories, {
export type Effect<TConfig extends object = Record<string, unknown>> =
CoreEffect<TConfig>;
-// Components: the factories and the types users touch. The authoring toolkit
-// (timing, paths, strokes, baking) lives at `framefields/components`.
+// Components: `npx framefields add <name>` copies a component's source into
+// the project. The root carries what users touch around them; the authoring
+// toolkit (timing, paths, strokes, baking) lives at `framefields/components`.
export {
type Anchor,
+ type AudioLevels,
type BaseProps,
type Cue,
type Cues,
@@ -3395,84 +3397,9 @@ export {
type Theme,
type ThemeInput,
themes,
-} from "@framefields/components";
+} from "@framefields/components/toolkit";
export {
- Annotate,
- type AnnotateCues,
- AppFrame,
- type AppFrameApi,
- type AppFrameCues,
- type AppFrameKind,
- type AudioLevels,
analyzeAudio,
- Backdrop,
- type BackdropCues,
- type BackdropKind,
- BeforeAfter,
- type BeforeAfterCues,
bindComponent,
- CAPTION_STYLES,
- Callout,
- type CalloutCues,
- type CaptionStyle,
- Captions,
- type CaptionsCues,
- CardStack,
- type CardStackCues,
- ChatThread,
- type ChatThreadCues,
- CodeBlock,
- type CodeBlockCues,
- type CodeLang,
type ComponentNode,
- Confetti,
- type ConfettiCues,
- Counter,
- type CounterCues,
- type CounterFormat,
- CURSOR_STYLES,
- type CursorStyle,
- DeviceFrame,
- type DeviceFrameApi,
- FocusZoom,
- type FocusZoomApi,
- type FocusZoomCues,
- type Followable,
- LogoReveal,
- type LogoRevealCues,
- type LogoStyle,
- LowerThird,
- type LowerThirdCues,
- type LowerThirdLayout,
- Meter,
- type MeterCues,
- type MeterKind,
- MousePointer,
- type MousePointerApi,
- type MousePointerCues,
- type RevealStyle,
- Selection,
- type SelectionCues,
- Spotlight,
- type SpotlightCues,
- Terminal,
- type TerminalCues,
- type TerminalStep,
- TextReveal,
- type TextRevealApi,
- type TextRevealCues,
- TitleCard,
- type TitleCardCues,
- type TitleLayout,
- Toasts,
- type ToastsCues,
- TouchPoint,
- type TouchPointCues,
- Waveform,
- type WaveformCues,
- type WaveformKind,
- type Waypoint,
- WordCycle,
- type WordCycleCues,
- type WordTransition,
} from "./components/index.js";
diff --git a/packages/framefields/tsdown.config.ts b/packages/framefields/tsdown.config.ts
index b03d24d4..2986e3ca 100644
--- a/packages/framefields/tsdown.config.ts
+++ b/packages/framefields/tsdown.config.ts
@@ -1,4 +1,6 @@
+import { cpSync, existsSync } from "node:fs";
import { defineConfig } from "tsdown";
+import { fixDtsAliases } from "./scripts/fix-dts-aliases.mjs";
import { buildEngine } from "./src/preview/bundle.ts";
export default defineConfig({
@@ -11,11 +13,22 @@ export default defineConfig({
"src/fonts/index.ts",
"src/preview/index.ts",
"src/components/index.ts",
+ "src/cli.ts",
],
format: ["esm"],
clean: true,
- // The live preview's browser engine, shipped prebuilt in dist/preview-engine.
- onSuccess: () => buildEngine("dist/preview-engine"),
+ onSuccess: async () => {
+ // The live preview's browser engine, shipped prebuilt in dist/preview-engine.
+ await buildEngine("dist/preview-engine");
+ // The component registry `framefields add` installs from.
+ const registry = "../components/dist/registry";
+ if (!existsSync(registry))
+ throw new Error(
+ `${registry} is missing: build @framefields/components first`,
+ );
+ cpSync(registry, "dist/registry", { recursive: true });
+ fixDtsAliases("dist");
+ },
dts: { resolve: [/^@framefields\//] },
target: "es2022",
noExternal: [/^@framefields\//],
diff --git a/plugins/framefields/skills/framefields/SKILL.md b/plugins/framefields/skills/framefields/SKILL.md
index 753a7bc8..a1be0d96 100644
--- a/plugins/framefields/skills/framefields/SKILL.md
+++ b/plugins/framefields/skills/framefields/SKILL.md
@@ -1,6 +1,6 @@
---
name: framefields
-description: Start a new framefields video project, or add framefields to an existing Node.js project. Use when the user wants to make a video with framefields and the project has no framefields setup yet, or asks how to install framefields, scaffold a composition and render script, get from an empty folder to a first MP4, or generate images, video, music or voice for a film with AI models (`ai` from framefields, the framefields AI gateway). Hands off to framefields-compose, framefields-effects, and framefields-render for the details.
+description: Start a new framefields video project, or add framefields to an existing Node.js project. Use when the user wants to make a video with framefields and the project has no framefields setup yet, or asks how to install framefields, scaffold a composition and render script, get from an empty folder to a first MP4, generate images, video, music or voice for a film with AI models (`ai` from framefields, the framefields AI gateway), or add ready-made components (pointers, captions, title cards, device frames …) with `npx framefields add`. Hands off to framefields-compose, framefields-effects, and framefields-render for the details.
---
# framefields
@@ -15,6 +15,7 @@ This skill takes a project from nothing to a verified first render. For anything
| Scenes, layout, typography, animation, beat grids, film structure | `framefields-compose` |
| Post-processing, color grading, VFX, on-device vision (tracking, cutouts, pose) | `framefields-effects` |
| Frame inspection, frame grids, pixel tests, video export and QA | `framefields-render` |
+| Ready-made components (`npx framefields add`) | this skill, section 8 |
| Generating images, video, music, voice with AI models (`ai`) | this skill, section 6 |
| Autonomous agent payments & runway checks | this skill, section 7 |
| Reporting bugs or engine defects to GitHub | this skill, section 9 |
@@ -364,6 +365,34 @@ Coding agents interacting with the AI gateway can discover endpoints, inspect cr
Once the first render works, move to the specialist skills: `framefields-compose` for splitting the film into scene modules on a beat grid, `framefields-effects` for grading, grain, and vision-driven effects, and `framefields-render` for tests and delivery checks. Keep `theme.ts` as the single source of sizes, colors, fonts, and timing as the project grows.
+### Ready-made components
+
+framefields has a registry of parametric motion components: a mouse pointer with clicks and drags, a camera that zooms to clicks, window and device frames, word-timed captions, text reveals, counters, annotations, a terminal, code blocks, title cards, lower thirds, meters, chat threads, toasts, callouts, spotlights, confetti, logo reveals, backdrops, audio waveforms, word cycles, touches, before/after splits, selections and card stacks. They are not in the npm package: `framefields add` copies their source into the project, where it is ordinary project code to read and change.
+
+```bash
+npx framefields list # every component, one line each
+npx framefields add mouse-pointer focus-zoom # writes src/components/<name>/
+```
+
+```typescript
+import { MousePointer } from "./components/mouse-pointer/index.js";
+
+const pointer = MousePointer({
+ path: [
+ { to: [400, 300], at: 0 },
+ { to: [960, 540], at: 30, click: true },
+ ],
+});
+film.add(pointer);
+// pointer.cues.clicks[0].frame: key a button press or a sound to the click.
+```
+
+- **Before writing a common motion piece by hand, run `npx framefields list`.** A component already handles timing, theme, cues and edge cases, and the copy is the project's to adjust.
+- Files go to `src/components` (or `components` when there is no `src`); the folder is saved in `framefields.json`, and `--dir` changes it on first use. Components that build on others bring them along (`terminal` adds `app-frame` and `counter`).
+- Installed code imports only `framefields` and `framefields/components` (the shared toolkit), so it always matches the installed framefields version. After upgrading framefields, `npx framefields add <name> --overwrite` refreshes a component; without the flag, files you changed are left alone and reported as `skipped`.
+- Every component takes the base props (`x`, `y`, `width`, `height`, `at`, `duration`, `hold`, `theme`, `enter`, `exit`, `seed`) and returns a normal box layer with `cues` (frames of its events), `span` and `parts` (inner layers to animate or style). Time is in frames.
+- Each installed `index.ts` documents what the component does at the top and defines its props in its schema; `npx framefields list` gives one-line summaries. Props are validated when the component is built, and a wrong one throws with the reason.
+
## 9. Report engine issues
When you encounter an unexpected crash, native WebGPU / Dawn failure, WGSL shader compilation error, compositor schema validation defect, or behavior bug in `framefields` itself (distinguishable from project-level configuration or asset errors):