Code-first video & image, rendered natively on WebGPU.
feat(components): M0 foundations for framefields components
okanasl06956653e746
diff --git a/.changeset/components-foundations.md b/.changeset/components-foundations.mdnew file mode 100644index 00000000..c3728484--- /dev/null+++ b/.changeset/components-foundations.md@@ -0,0 +1,10 @@+---+"framefields": minor+---++Add the foundations of framefields components (`framefields/components`).++- `bindComponent(defineComponent({ ... }))` turns a component definition into a factory that returns an ordinary box layer, plus `cues` (moments it produced, in the parent's frames), `span` (its window) and `part(name)`. Props are validated strictly, every component has `enter` / `exit` motion presets, a `theme`, a `seed` and a `customize` hook, and the produced spec stays plain JSON.+- Themes: `themes.graphite`, `themes.paper`, `themes.signal` and `defineTheme(partial)`, contrast-checked.+- `pulseKeys(cues, …)` turns a component's cues into keyframes on any other layer.+- An authoring toolkit at `framefields/components`: frame timing and stagger orders, seeded randomness, eases, spring and curve baking to keyframes, Catmull-Rom and arc-length paths, draw-on and hand-drawn strokes (wobble, boil, arrows), text range geometry from real font measurement, and targets (points, rects, nodes, text matches, tracked objects).diff --git a/packages/components/SPEC.md b/packages/components/SPEC.mdnew file mode 100644index 00000000..665eb228--- /dev/null+++ b/packages/components/SPEC.md@@ -0,0 +1,1016 @@+# framefields components — specification & plan++Status: **M0 implemented** (foundations; no components yet) · Branch: `feat/components` · Owner: framefields core++This document defines what the framefields component library is, how it plugs into the+SDK, which components ship first and why, and the exact contract every component follows.+It is the source of truth for implementation; anything not covered here is a decision to+raise before writing code.++---++## 1. What we are building++A library of **ready-made, parametric motion components**: the recurring pieces of product+films, explainers, launch videos and social clips that today every project rebuilds by hand+(cursors, captions, counters, code terminals, annotations, title cards …).++Our own example films are the evidence. They each hand-roll the same helpers: an odometer+(`examples/23_data_story/src/motion.ts`), pop-in and fade presets, star / heart / blob path+generators (`examples/29_capabilities_reel/src/kit.ts`), beat rings, headers and scene+wrappers (`examples/23_data_story/src/ui.ts`). The component library turns those into one+tested, documented, versioned API.++### 1.1 Goals++1. **One import, zero setup.** `import { MousePointer, Captions } from "framefields"`. No+ second package to install, no registration step, no runtime to mount.+2. **Pay only for what you use.** Every component is a standalone named ESM export in a+ `sideEffects: false` module graph. Importing one component never pulls another.+3. **Native, not embedded.** A component is a function that returns an ordinary framefields+ layer tree. Everything the SDK can do to a layer (`.animate()`, effects, mattes, 3D,+ physics bodies, vision pinning, blend modes) works on a component.+4. **Exact by construction.** Components measure real glyphs with the registered fonts,+ resolve timing on the integer frame clock, and use seeded randomness. Same props → same+ pixels, on every machine, in any frame order.+5. **Agent-first.** Every component ships a typed props schema, a one-paragraph summary,+ tags and a canonical example, so a coding agent can discover, validate and use it+ without reading source.++### 1.2 Non-goals++- **Scene transitions.** They already exist as `Transition.*` for `Layer.sequence`. New+ transitions are contributed there, not as components.+- **Charts.** `Layer.chart` covers line / area / bar / scatter / candlestick / pie / donut.+ Components may *wrap* a chart (e.g. a stat card), never re-implement one.+- **Whole-frame looks and VFX.** `Styles.*`, `Layer.vfx` and the effect nodes own those.+- **A visual editor or template marketplace.** This is a code library.+- **HTML / DOM rendering.** Components build native nodes only.++### 1.3 How we differ from snippet catalogs++A catalog of copy-paste snippets gives you one fixed animation per entry and leaves you to+wire its timing to everything else. We go the other way:++| Snippet catalogs | framefields components |+|---|---|+| Many one-off entries, one look each | Few deep components, each with `style` variants |+| Timing lives inside the snippet | Timing is input (`at`, beats, word timings) **and** output (`cues`) |+| Positions guessed in CSS | Targets resolved from measured text, layout rects or tracked objects |+| Randomness at runtime | Seeded, frame-exact, replayable |+| Copy, then edit the source | Typed props, `theme`, and a `customize` hook over the built parts |+| Flat, 2D | Can use GPU effects, particles, physics, vision mattes and 3D |++---++## 2. Design principles++1. **Props in, layer tree out.** A component is a pure function. It never touches the+ `Composition`, never registers globals, never reads the clock or `Math.random`.+2. **Cues out.** Every component reports *when* its meaningful moments happen (clicks,+ keystrokes, words, landings) as integer frames. Sound design, particles, camera moves+ and other components sync to those cues instead of to re-typed magic numbers.+3. **Few components, many styles.** Prefer one `TextReveal` with ten `style`s over ten+ reveal components. Variants share the timing, staggering and measurement logic and stay+ consistent with each other.+4. **Targets, not coordinates.** Anything that points at something (cursor, annotation,+ zoom, callout) accepts a `Target`: a point, a rect, a measured text range, a node, or a+ vision-tracked object.+5. **Theme tokens, not hex codes.** Colors, fonts, radii and motion come from a `Theme`.+ Every token can be overridden per instance.+6. **Escape hatches everywhere.** `customize(parts)` exposes every built sub-node, so users+ never fork a component to change one detail.+7. **Plain data.** The produced tree is plain program JSON. Cues and helpers ride on+ non-enumerable properties (the same way `.animate()` does today), so `toJSON()`,+ linting, previews and server rendering are unaffected.++---++## 3. Package architecture++### 3.1 Import story++```ts+// The default: straight from the SDK root.+import { Composition, Layer, MousePointer, Captions } from "framefields";++// 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";+```++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.++### 3.2 Where the code lives++```+packages/components/ @framefields/components (internal, bundled into framefields)+ SPEC.md this document+ package.json private, sideEffects: false+ src/+ index.ts named re-exports only: no registries, no top-level calls+ core/+ contract.ts defineComponent, ComponentNode, BaseProps, cue helpers+ host.ts Host interface (what framefields injects, §3.3)+ timing.ts frame math, beats, stagger orders, windows+ theme.ts Theme type, defineTheme, built-in themes+ targets.ts Target union + resolution to points / rects / signals+ text.ts word / line / glyph boxes from measured text+ motion.ts enter / exit presets, springs baked to keyframes+ path.ts waypoints, Catmull-Rom, arc length, Path3D interop+ draw.ts draw-on strokes, hand-drawn wobble + boil+ rng.ts seeded PRNG (splitmix32) + hash-by-key+ bake.ts per-frame samples → simplified keyframes+ mouse-pointer/+ index.ts the factory+ plan.ts pure planner: props → timeline (unit tested)+ styles.ts the cursor glyph library+ meta.ts summary, tags, schema, example+ mouse-pointer.test.ts planner unit tests against a fake host+ captions/ … same shape for every component+packages/framefields/+ src/components/index.ts binds the host, re-exports every component+ src/components/*.render.test.ts frame-grid golden tests (real GPU)+```++### 3.3 Layering: the host++framefields bundles every `@framefields/*` package into itself (`noExternal` in+`tsdown.config.ts`). The component package therefore **must not depend on `framefields`**,+or the build graph becomes circular. Components depend only on lower layers+(`@framefields/core`, `@framefields/compositions/program`) and receive everything else+through a small injected **host**:++```ts+// packages/components/src/core/host.ts+export interface Host {+ box(options: Partial<BoxNode>): Animatable<BoxNode>;+ flex(options: Partial<FlexNode>): Animatable<FlexNode>;+ text(content: string, options?: Partial<TextNode>): Animatable<TextNode>;+ shape(type: ShapeType, options?: Partial<ShapeNode>): Animatable<ShapeNode>;+ measure: MeasureFn; // FontManager.measure+ fonts(): readonly string[]; // registered families, for error messages+ autoId(prefix: string): string; // stable ids, like Layer.* ids+}+```++The host grows with the components that need it: effect constructors (motion blur, blur)+arrive with M1 (`MousePointer`, `FocusZoom`), particles with `Confetti`, subject cut-outs+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+drop:++```ts+// packages/framefields/src/components/index.ts+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.++**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+package types nodes structurally (`Animatable<T> = T & { animate(...): unknown }`), and+`bindComponent` in framefields restores the real types: a bound component returns+`AnimatableNode<BoxNode> & ComponentExtras<C>`.++**Tests follow the same rule.** The components package runs pure unit tests against a fake+host. Anything that renders lives in `packages/framefields/src/components/` so there is no+`framefields ↔ components` dependency cycle for turbo.++### 3.4 Versioning++`@framefields/components` is internal (`private: true`) and ships inside `framefields`, so+there is one version to reason about. Changesets for component work target `framefields`.++---++## 4. The component contract++### 4.1 Signature++```ts+const node = Component(props); // → ComponentNode<Cues>+comp.add(node); // it is a normal layer+node.animate(LayerAnimation.create().fadeOut(...)) // and behaves like one+node.cues.clicks // plus the moments it produced+```++```ts+export type ComponentNode<C extends Cues = Cues> = AnimatableNode<BoxNode> & {+ /** Moments the component produced, in composition-local frames of its parent. */+ readonly cues: C;+ /** The component's own window: first visible frame, last visible frame, length. */+ readonly span: { start: number; end: number; duration: number };+ /** A named sub-node (same objects `customize` receives). */+ part(name: string): AnimatableNode<LayoutNode> | undefined;+};+```++The root is always a `box` (absolute when `x`/`y` are given, otherwise in flow), carrying+`startFrame` = `at` and `durationFrames` = the resolved duration.++### 4.2 Base props (every component)++| Prop | Type | Default | Meaning |+|---|---|---|---|+| `id` | `string` | auto | Root id; parts get `<id>-<part>` ids. |+| `at` | `number` | `0` | Start frame (in the parent's local timeline). |+| `duration` | `number` | natural | Override the window. Natural = derived from content (script length, word timings …) + `hold`. |+| `hold` | `number` | per component | Frames the finished state stays on screen before `exit`. |+| `enter` / `exit` | `MotionPreset \| false` | per component | Whole-component entrance / exit (§5.4). |+| `x`, `y`, `width`, `height`, `position` | layout | — | Placement of the root box, same semantics as `Layer.box`. |+| `theme` | `Theme \| Partial<Theme>` | `themes.graphite` | Tokens (§5.2). Partial themes merge over the default. |+| `seed` | `number` | `1` | Every random choice derives from it. |+| `fps` | `number` | `30` | The composition's frame rate. Theme speeds (authored at 30 fps) and real-time inputs scale by it. |+| `customize` | `(parts) => void` | — | Receives every built sub-node before return. |++Rules:++- **All times are integer frames.** Inputs that are naturally in seconds (word timings,+ typing speed in chars/sec) use the `fps` prop; the result is rounded once, in one place+ (`timing.ts`).+- **Props are strict.** Unknown props are an error (a typo like `lable` fails loudly).+- **Structure.** The root box carries placement and the window; a `stage` box inside it+ (absolute at 0, 0, the component's measured size) carries `enter` / `exit`, so preset+ offsets never fight the root's layout, in flow or absolute. Every component reports its+ measured `width` / `height`, which the root takes unless overridden.+- **Natural duration is always computable** without rendering, so `Layer.sequence` and+ `computeDuration()` can size scenes around components.+- **Validation is eager.** Props are parsed with the component's zod schema at call time.+ Errors name the prop, the bad value and the fix (e.g. an unregistered font lists the+ registered ones).++### 4.3 Cues++Cues are plain arrays of integer frames, optionally with data:++```ts+type Cue<D = {}> = { frame: number } & D;+// MousePointer+cues.clicks // Cue<{ point: [number, number]; target?: string }>[]+cues.presses // Cue[] ; cues.releases ; cues.arrivals+```++Cue frames are in the **parent's** timeline (they already include `at`), so they can be+used directly as `startFrame` for sibling layers:++```ts+const pointer = MousePointer({ at: 30, path: [...] });+const clicks = pointer.cues.clicks.map((c) =>+ Layer.audio("assets/sfx/click.wav", { startFrame: c.frame, durationFrames: 12 }),+);+comp.add([pointer, ...clicks]);+```++Helpers in `core/contract.ts`: `cueSignal(cues, { decay })` turns cues into a pulse+`Signal` (for `.signal("scale", …)`, particle `rate`, physics impulses), and+`cueKeys(cues, shape)` turns cues into keyframes on another layer.++### 4.4 Parts and `customize`++Each component documents its part names (e.g. MousePointer: `root`, `motion`, `cursor`,+`glyph`, `hover`, `trail`, `label`, `ripples`). `customize` runs after the tree is built and+before cues are frozen. It may add animations or effects, change styling, or add children.+Removing parts is unsupported.++### 4.5 Metadata (agent and docs surface)++```ts+// <component>/meta.ts+export const meta = defineMeta({+ name: "MousePointer",+ summary: "An animated pointer that travels between targets, clicks, drags and hovers.",+ tags: ["pointer", "cursor", "demo", "ui", "interaction"],+ schema: MousePointerProps, // zod+ parts: ["root", "motion", "cursor", "glyph", "hover", "trail", "label", "ripples"],+ cues: ["clicks", "presses", "releases", "arrivals", "drags"],+ example: `MousePointer({ path: [{ to: [400, 300] }, { to: [900, 520], click: true }] })`,+});+```++`scripts/build-meta.ts` (part of the package build) collects every `<component>/meta.ts`+default export into `dist/components.json`, read by the skills generator and the docs+gallery. A component folder without a `meta.ts`, or two components with one name, fails+the build.++---++## 5. Shared core++Built in milestone M0 (§10). Every Wave 1 component depends on most of it, which is why the+first wave is chosen to exercise all of it.++### 5.1 Timing (`core/timing.ts`)++- `toFrames(sec, fps)`, `toSeconds`, `beats(n, beatFrames)`, `scaleFrames(framesAt30, fps)` → integers, rounded once.+- `staggerOrder(n, order, seed)` for `"forward" | "reverse" | "center" | "edges" | "random"`,+ as `staggerOffsets` / `staggerRanks`.+- `FrameWindow` arithmetic: `frameSpan`, `within`, `cover`, `chain(...)`.+- `quantize(frame, grid)`: optional quantisation for every component's cue-producing+ times (`quantize: beatFrames` base prop on components that schedule events).++### 5.2 Theme (`core/theme.ts`)++```ts+interface Theme {+ color: {+ bg: string; surface: string; raised: string; line: string;+ ink: string; muted: string; accent: string; accent2: string;+ positive: string; negative: string; highlight: string;+ };+ font: { display: string; body: string; mono: string; hand?: string };+ radius: { sm: number; md: number; lg: number; pill: number };+ stroke: { hair: number; base: number; bold: number };+ motion: {+ ease: { enter: string; exit: string; move: string; snap: string };+ speed: { fast: number; base: number; slow: number }; // frames at 30 fps, scaled by fps+ };+ scale: number; // 1 = designed for 1080p; 2 for 4K, 0.5 for 540p+}+```++- `defineTheme(partial)` deep-merges over `themes.graphite`.+- Built-ins: `themes.graphite` (dark neutral), `themes.paper` (light editorial),+ `themes.signal` (high-contrast, saturated accent for social).+- Built-in themes reference the font families `Inter` and `JetBrains Mono`; fonts are+ never bundled. When a theme font isn't registered, the error says which families are.+- Color tokens are validated with `Color.contrast`: `ink` on `surface` must be ≥ 4.5.+- `motion.speed` is defined at 30 fps and rescaled to the composition fps, so a theme feels+ the same at 24, 30 and 60 fps.++### 5.3 Targets (`core/targets.ts`)++```ts+type Target =+ | [x: number, y: number] // a point+ | { x: number; y: number; width: number; height: number } // a rect+ | { node: AnimatableNode<LayoutNode> | string; anchor?: Anchor }+ | { text: AnimatableNode<TextNode>; match?: string | RegExp; range?: [number, number]; nth?: number }+ | { track: ObjectTrackSignals; anchor?: ObjectAnchorName } // vision-tracked, moves per frame+ | ((frame: number) => [number, number]); // escape hatch+```++Resolution returns either a static `Rect` or a per-frame `RectSignal`. Components that+accept targets must handle both (static targets bake to keyframes; dynamic targets bind+signals).++- **Text targets** use `FontManager.measure(...).glyphs` on the text node's own props to+ return one rect per line the range spans (so an underline under a wrapped phrase becomes+ two strokes).+- **Node targets** need absolute geometry. Nodes with numeric `x`/`y`/`width`/`height`+ resolve directly. Flex children need the layout pass: see open question Q3.+- **Anchor** names: `center`, `top`, `bottom`, `left`, `right`, `top-left` … plus `tip`+ (the point a pointer should land on: centre for buttons, the left edge mid-height for+ text fields).++### 5.4 Motion presets (`core/motion.ts`)++Named entrances/exits used by every component's `enter` / `exit`:+`fade`, `rise`, `drop`, `scale`, `pop` (overshoot), `slide-{left,right,up,down}`,+`tilt` (3D perspective settle), `none`. `blur` (needs the blur effect on the host) and+`mask-{up,down,left,right}` (needs a matte) arrive with `TextReveal` in M2. Each preset accepts `{ duration, ease, distance, delay }` overrides and reads+defaults from `theme.motion`.++Springs are evaluated in closed form and **baked to keyframes** with `bake.ts`+(tolerance-simplified), so the output stays plain JSON and seeks exactly. `core/ease.ts`+evaluates exactly the ease names the keyframe schema accepts (`power1-3`, `sine`, `circ`,+`expo`, `back`, `elastic`, `bounce`, `cubic`, `hold`, `none`/`linear`), so a curve+baked offline matches the same ease keyed directly.++### 5.5 Paths and waypoints (`core/path.ts`)++Carries over the design in the pending `@framefields/components` changeset:+`Waypoint`, `EASE` + `evaluateEase`, `buildPointerPath` (centripetal Catmull-Rom with+per-segment timing), arc-length reparametrisation, `positionOnPathAtFrame`, and interop+with `Path3D` / `LayerAnimation.followPath`.++### 5.6 Strokes and the hand-drawn look (`core/draw.ts`)++- `drawOn(shape, { start, duration, ease })` keyframes `trimEnd` 0 → 1.+- `wobble(d, { amount, seed })`: perturbs a path's points with seeded low-frequency noise.+- `boil({ every, variants, seed })`: pre-computes `variants` wobbled versions of a path and+ keys `d` between them every `every` frames with `hold` interpolation, so a mark "lives"+ like hand-drawn animation, deterministically.+- Path generators: `roughEllipse`, `roughRect`, `underlineStroke`, `squiggle`, `bracket`,+ `arrowPath` (straight / arc / swoop, with a separate head that lands on the tip).++### 5.7 Randomness (`core/rng.ts`)++`rng(seed)` (splitmix32) and `hashRng(seed, key)` so the n-th word of a caption gets the same+random tilt whether or not earlier words change. `Math.random` is banned in the package by+a biome rule.++---++## 6. How the first components were chosen++Each candidate was scored 1–3 on four criteria:++- **Demand:** how often it appears in product demos, launch films, explainers and social+ clips (our examples, user projects, common video formats).+- **Leverage:** how much it gains from what framefields does that others can't: measured+ GPU text, frame-exact timing, effects, particles, physics, vision, 3D.+- **Foundation:** how much shared core it forces us to build properly, which later+ components then reuse.+- **Hard by hand:** how error-prone it is for a person or an agent to get right with raw+ layers (measurement, timing math, sync).++| Candidate | Demand | Leverage | Foundation | Hard by hand | Total | Wave |+|---|---|---|---|---|---|---|+| MousePointer | 3 | 2 | 3 (paths, targets, cues) | 3 | **11** | 1 |+| FocusZoom | 3 | 3 (motion blur, signals) | 2 (bake, targets) | 3 | **11** | 1 |+| Captions | 3 | 3 (vision cut-out, audio pulse) | 3 (text boxes, fps timing) | 3 | **12** | 1 |+| TextReveal | 3 | 3 (GPU glyph animators) | 3 (stagger, text, motion) | 2 | **11** | 1 |+| Counter | 3 | 2 | 2 | 3 | **10** | 1 |+| Annotate | 2 | 2 | 3 (draw, text targets) | 3 | **10** | 1 |+| AppFrame | 3 | 2 | 2 (slots, rects for targets) | 2 | **9** | 1 |+| Terminal | 3 | 2 | 2 (mono measure, scroll) | 3 | **10** | 1 |+| CodeBlock | 3 | 2 | 1 | 3 | 9 | 2 |+| ChatThread | 2 | 2 | 1 | 2 | 7 | 2 |+| Callout | 2 | 3 (tracked objects) | 1 | 2 | 8 | 2 |+| Spotlight | 2 | 2 | 1 | 2 | 7 | 2 |+| Confetti | 2 | 3 (GPU particles, physics) | 1 | 1 | 7 | 2 |+| Meter | 2 | 1 | 1 | 2 | 6 | 2 |+| TitleCard / LowerThird | 3 | 1 | 1 | 1 | 6 | 2 |+| Toasts | 2 | 1 | 1 | 2 | 6 | 2 |++Wave 1 is the eight components with the highest totals. Together they cover the two most+common film types (the **product demo** and the **talking-head / social clip**) end to+end, and they exercise every shared core module.++---++## 7. Wave 1: detailed specifications++Common to all: base props (§4.2), parts, cues, a `meta`, unit tests for the planner and a+frame-grid golden test (§9). Prop tables list only component-specific props.++---++### 7.1 `MousePointer`++An animated pointer that travels between targets, presses, clicks, drags and changes shape+over hover regions. The anchor of every screen-demo film. The detailed design already+exists in the pending changeset `.changeset/components-mouse-pointer.md`; this section+records it as the target and lists what Wave 1 adds.++**Props**++| Prop | Type | Default | Notes |+|---|---|---|---|+| `path` | `Waypoint[]` \| `Path3D` | required | `Waypoint = { to: Target; at?: number; dwell?: number; click?: boolean \| ClickOptions; press?: number; drag?: Target; hover?: CursorStyle }`. `at` omitted → derived from distance and `speed`. |+| `style` | `CursorStyle` | `"arrow"` | `arrow`, `triangle`, `chevron`, `dot`, `ring`, `target`, `crosshair`, `plus`, `ibeam`, `caret`, `square`, `diamond`, `sparkle`, `hand`. |+| `size` | `number` | `28 × theme.scale` | All styles normalised to one visual size. |+| `color` / `accent` / `outline` | color | theme | Fill, secondary, and outline. |+| `outlineMode` | `"each" \| "union"` | `"union"` | Union dilates the whole silhouette so overlapping parts read as one cursor. |+| `motion` | `"natural" \| "swift" \| "lazy" \| "linear"` | `"natural"` | Travel feel: ease shape, slight overshoot, arc bias. |+| `speed` | `number` | `1400` px/s | Used when `at` is omitted. |+| `drift` | `number \| false` | `2` px | Idle micro-motion while dwelling (seeded). |+| `autoOrient` | `boolean` | `false` | Rotate along travel (for `dot`/`triangle` styles). |+| `trail` | `false \| { length, fade, width }` | `false` | Fading trail. |+| `feedback` | `"press" \| "bounce" \| "pulse" \| false` | `"press"` | Per-click glyph response. |+| `ripple` | `"ring" \| "fill" \| "pulse" \| false` | `"ring"` | Click ripple. |+| `hoverRegions` | `{ target: Target; style: CursorStyle }[]` | `[]` | Style swaps while inside a region, resolved from the motion solution so they are exact. |+| `label` | `string \| { text, color }` | — | **New.** Name tag that rides beside the pointer: AI-agent and multiplayer pointers. |+| `motionBlur` | `boolean \| number` | `false` | **New.** Adds `MotionBlur` on the motion part, strength scaled by speed. |+| `shadow` | `boolean` | `true` | **New.** Soft drop shadow via layer style. |+| `from` / `to` | `"left" \| "right" \| "top" \| "bottom" \| Target` | — | **New.** Enter from / exit to off-frame. |++**Parts:** `root`, `motion`, `cursor`, `glyph`, `hover`, `trail`, `label`, `ripples`.+**Cues:** `arrivals`, `presses`, `releases`, `clicks` (with `point`, `target` id), `drags`+(`{ start, end, from, to }`).++**Implementation notes**++- Planner (`plan.ts`) is pure: waypoints → per-segment windows, positions, press/hover+ intervals, cues. All tests run on the planner.+- Travel is keyframes (baked arc-length samples), never per-frame signals, unless a target+ is dynamic (`track`), in which case the segment binds signals.+- Glyphs are built from `rect` / `circle` / `polygon` / `star` primitives; the classic arrow+ is one `path`.++**Acceptance**++- Click cue frames equal the frames on which the glyph is fully pressed (golden test reads+ the press scale at that frame).+- A pointer whose path visits a `text` target lands on the first glyph's mid-height,+ within 0.5 px of the measured position.+- 14 styles × 3 sizes render in one frame grid without clipping; union outline shows no+ seams at 4× zoom.++---++### 7.2 `FocusZoom`++A virtual camera over 2D content (a screen recording, an `AppFrame`, any layer tree) that+pushes in on what matters and eases back out, the auto-zoom look of polished product+demos. It can follow a `MousePointer` automatically.++```ts+const screen = AppFrame({ kind: "browser", url: "app.acme.dev", content: Layer.video("rec.mp4") });+const pointer = MousePointer({ path: [...] });+comp.add(FocusZoom({ content: [screen, pointer], follow: pointer, maxZoom: 2.2 }));+```++**Props**++| Prop | Type | Default | Notes |+|---|---|---|---|+| `content` | `LayoutNode \| LayoutNode[]` | required | What the camera films. Laid out at full size; the camera transforms one wrapper box. |+| `shots` | `Shot[]` | — | Manual: `{ at, target: Target \| "full", zoom?, hold?, ease? }`. |+| `follow` | `ComponentNode<PointerCues>` | — | Auto: derive shots from the pointer's cues (push in `lead` frames before each click cluster, trail the pointer between, release after `idle` frames). |+| `zoom` / `maxZoom` | `number` | `1.8` / `2.5` | Default and ceiling. |+| `lead` | `number` | `theme.motion.speed.base` | Frames the push-in starts before the event. |+| `idle` | `number` | `45` | Frames without events before easing back to full. |+| `smoothing` | `number` | `0.85` | Critically damped follow (0 = rigid, 1 = very loose). |+| `padding` | `number` | `48` | Kept around a target rect when framing it. |+| `clamp` | `boolean` | `true` | Never reveal outside the content bounds. |+| `smear` | `false \| "subtle" \| "standard" \| "heavy"` | `"subtle"` | Motion blur scaled by camera speed. |+| `focus` | `false \| { dim: number; feather: number }` | `false` | Optional dimming outside the framed region. |++**Parts:** `root` (clip box), `camera` (the transformed wrapper), `focus`.+**Cues:** `shots` (`{ start, settled, end, target }`), `pushIns`, `releases`.++**Implementation notes**++- The camera path is solved offline: target rects per frame → desired (scale, tx, ty) →+ damped follow → clamped → **baked to keyframes** with tolerance simplification. Dynamic+ targets fall back to signals.+- Zoom is applied as `scale` + `x`/`y` on the wrapper with `overflow: "hidden"` on the root,+ so text stays vector-sharp (re-rasterised, not upscaled).+- Smear uses `host.effects.motionBlur` with strength bound to the camera's speed.++**Acceptance**++- With `follow`, every click cue happens while the camera is settled (velocity < 1 px/frame)+ and the click point lies inside the central 60 % of the frame.+- `clamp: true`: no frame shows the root background outside the content (golden check on+ corner pixels).+- A 1080p UI zoomed 2.5× has text edges as sharp as the same UI rendered natively at 2.5×+ (SSIM ≥ 0.98 against the reference).++---++### 7.3 `Captions`++Word-timed captions for talking-head and social video, with the styles people actually+publish, exact word highlighting, and options only a GPU compositor with vision can do:+captions tucked behind the speaker, and words that pulse with the voice.++```ts+Captions({+ fps: 30,+ words, // [{ text: "Ship", start: 0.42, end: 0.61 }, …] (seconds)+ style: "karaoke",+ emphasis: ["faster", /\d+%/],+ behind: { video: "assets/talk.mp4" },+ pulse: voiceEnvelope, // Signal from the voice track+});+```++**Props**++| Prop | Type | Default | Notes |+|---|---|---|---|+| `fps` | `number` | required | For converting word times. |+| `words` | `Word[]` | required* | `{ text, start, end }` in seconds. *Or `transcript`. |+| `transcript` | `string` | — | SRT, WebVTT, or word-level JSON (`{ word \| text, start, end }[]`). Cue-level formats are split into words with times distributed by measured width. |+| `style` | `CaptionStyle` | `"karaoke"` | See below. |+| `group` | `{ maxChars?, maxWords?, maxLines?, breakOnPunctuation?, minGap? }` | `{ maxChars: 28, maxLines: 2 }` | Phrase builder; never splits mid-word; prefers punctuation and pauses ≥ `minGap` s. |+| `emphasis` | `(string \| RegExp)[] \| ((word, i) => boolean)` | `[]` | Emphasised words get `theme.color.accent`, a weight or size bump per style. |+| `case` | `"as-is" \| "upper" \| "lower"` | `"as-is"` | |+| `placement` | `{ anchor: "bottom" \| "center" \| "top"; safeArea?: "portrait" \| "landscape" \| Rect; offset? }` | `bottom`, auto safe area | Portrait safe area keeps clear of platform UI overlays. |+| `avoid` | `Target[]` | `[]` | Move a phrase up/down when it would overlap a target, e.g. a tracked face. |+| `behind` | `{ video: string; mode?: "person" \| "subject" }` | — | Renders a vision cut-out of the clip **above** the captions, so text passes behind the speaker. |+| `pulse` | `Signal \| false` | `false` | Active word scale = `1 + pulse × 0.08`. |+| `font`, `fontSize`, `weight` | text props | theme `display`, auto | `fontSize` auto-fits the safe-area width at `maxChars`. |++**Styles (`CaptionStyle`)**++| Style | Look |+|---|---|+| `clean` | Broadcast subtitles: phrase fades in, no per-word animation, optional backing plate. |+| `karaoke` | Whole phrase visible in `muted`; each word fills with `ink` as it is spoken. |+| `highlight` | A rounded marker slides behind the active word and resizes to it. |+| `pop` | Words appear as they are spoken with a small overshoot scale. |+| `bold` | One or two words at a time, very large and centred, alternating entrance directions. |+| `outline` | Heavy stroked type (stroke via layer style), active word in accent. |+| `pill` | Phrase on a pill plate; active word gets an inner accent pill. |+| `gradient` | Active word filled with an accent gradient; others in `ink`. |++**Implementation notes**++- **No node per word for colour changes.** Each phrase is two text layers (base colour and+ active colour); the active layer is matted by per-word rects measured with+ `FontManager.measure(...).glyphs`, keyed open at each word's start frame. This is exact,+ cheap, and keeps kerning identical between the two layers.+- Phrase layout is measured once; `highlight` and `pill` plates are shapes keyed between+ word rects.+- `behind` uses `host.cutout(video, { mode: "matte" })` stacked above the caption layers.+- Phrase builder, transcript parsers and auto font sizing are pure and unit tested.++**Cues:** `words` (`{ frame, end, index, text, emphasised }`), `phrases`+(`{ start, end, text }`).++**Acceptance**++- The active-colour edge for a word appears on `round(word.start × fps)` exactly+ (frame-grid test on a synthetic 3-word transcript).+- Two-line phrases never exceed the safe area at any `fontSize` produced by auto-fit.+- With `behind`, pixels inside the person matte show the person, not the text (golden).+- SRT, VTT and word-JSON fixtures produce the same phrases for the same content.++---++### 7.4 `TextReveal`++Headline and body text that animates in (and optionally out) by character, word or line.+One component, one timing model, many looks.++**Props**++| Prop | Type | Default | Notes |+|---|---|---|---|+| `text` | `string \| TextSpan[]` | required | Rich spans supported (`rich`, `accent`, `bold` …). |+| `style` | `RevealStyle` | `"rise"` | See below. |+| `by` | `"char" \| "word" \| "line"` | per style | Unit of animation. |+| `stagger` | `number` | per style | Frames between units. |+| `order` | `"forward" \| "reverse" \| "center" \| "edges" \| "random"` | `"forward"` | `random` uses `seed`. |+| `unitDuration` | `number` | `theme.motion.speed.base` | Frames for one unit's move. |+| `exitStyle` | `RevealStyle \| false` | `false` | Plays mirrored after `hold`. |+| text props | `fontFamily`, `fontSize`, `fontWeight`, `fill`, `align`, `lineHeight`, `letterSpacing`, `width`, `direction` | theme | Passed to the underlying text node(s). RTL respected. |++**Styles (`RevealStyle`)**++| Style | What happens | Engine |+|---|---|---|+| `rise` | Units lift from below with a fade | `TextAnimator` |+| `blur` | Units resolve from blur and slight scale | `TextAnimator` |+| `track` | Letter-spacing closes in from wide | `letterSpacing` keys |+| `mask` | Each line slides up through its own line box | per-line text + matte |+| `slam` | Units scale down into place with a short landing shake | `TextAnimator` + root keys |+| `scatter` | Glyphs gather from seeded scattered positions/rotations | `TextAnimator` + seeded offsets |+| `scramble` | Each character cycles seeded glyphs, then locks, left to right | per-char glyph reels (see notes) |+| `type` | Typewriter with a blinking caret, seeded human rhythm | `typewriter` + caret shape at `caretX` |+| `stream` | Words arrive in uneven bursts and ink from `muted` to `ink` | `TextAnimator` colour + seeded burst timing |+| `wipe` | A soft feathered front crosses the line with a trailing blur | gradient matte + blur |+| `flip` | Units rotate in around X in 3D | `TextAnimator.flip3D` |++**Implementation notes**++- Prefer GPU glyph animators (`TextAnimator`) over splitting text into nodes. Split only+ where a style needs per-unit geometry (`mask`, `scramble`).+- `scramble` needs no content keyframes: each character is a masked vertical **reel** of+ seeded glyphs moved with `stepped(2)` and landing on the real glyph, all widths fixed to+ the final glyph's advance so the line never jitters.+- `type` and `stream` place the caret from `measure().caretX(i)`, so the caret sits exactly+ after the last revealed glyph in any font.++**Cues:** `units` (`{ frame, settled, index, text }`), `revealed`, `exitStart`, and for+`type`/`stream`: `keystrokes`.++**Acceptance**++- Every style renders the final frame pixel-identical to a static `Layer.text` with the+ same props (the reveal never leaves residue or kerning changes).+- `scramble` with the same seed produces identical frames across runs; a different seed+ changes intermediate frames only.+- Arabic text with `by: "word"` reveals right to left.++---++### 7.5 `Counter`++Numbers that change in a way viewers trust: odometer reels, smooth counts, prices,+percentages, scoreboards.++**Props**++| Prop | Type | Default | Notes |+|---|---|---|---|+| `from` / `to` | `number` | `0` / required | Or `values`. |+| `values` | `[frame: number, value: number, ease?: string][]` | — | Multi-step counts (e.g. 0 → 120 → 87). |+| `format` | `string \| Intl.NumberFormatOptions \| ((n) => string)` | `",d"` | d3-format strings, same as `Layer.chart` axes. |+| `prefix` / `suffix` | `string \| TextSpan[]` | — | Styled separately (e.g. smaller `%`). |+| `style` | `"roll" \| "count" \| "flip"` | `"roll"` | `roll` = per-digit reels; `count` = plain digits; `flip` = split-flap (Wave 2). |+| `duration`, `ease` | | `speed.slow × 2`, `theme.motion.ease.move` | |+| `digitStagger` | `number` | `2` | Higher places settle later (roll only). |+| `motionBlur` | `boolean` | `true` (roll) | Vertical blur on fast reels. |+| `signal` | `Signal` | — | Drive the value live from audio, physics or data. |+| `tabular` | `boolean` | `true` | Fixed digit advance (max measured digit width) so nothing shifts. |+| text props | | theme `display` | |++**Implementation notes**++- `roll`: one masked reel per digit position (0–9 stacked, repeated for multi-turn spins);+ the reel `y` is keyed from the value trajectory so a digit spins `floor(Δ / 10^place)`+ full turns plus the remainder, the way a mechanical counter does.+- Growing digit counts (`999 → 1,000`) animate the width and slide new places in from the+ left; separators are placed by the formatter, not hard-coded.+- `count`: a single text node whose content is keyed per frame with hold interpolation.+ Depends on Q2; falls back to `roll` with zero blur until then.++**Cues:** `settled`, `milestones` (crossings of `milestoneEvery` units, e.g. for tick+sounds).++**Acceptance**++- Final frame equals a static `Layer.text(format(to))` pixel for pixel.+- `0 → 1,000,000` over 60 frames never shows an intermediate frame wider than the final+ width.+- `values` with a decrease (`120 → 87`) spins reels downward.++---++### 7.6 `Annotate`++Marks that draw on to point at something: underline a word, circle a number, strike a+claim, box a region, draw an arrow. Clean geometric or hand-drawn.++**Props**++| Prop | Type | Default | Notes |+|---|---|---|---|+| `target` | `Target` | required | Text ranges produce one mark per line. |+| `mark` | `"underline" \| "circle" \| "box" \| "highlight" \| "strike" \| "cross" \| "bracket" \| "arrow" \| "squiggle"` | `"underline"` | |+| `from` | `Target` | — | Arrow start (arrows point *to* `target`). |+| `curve` | `"straight" \| "arc" \| "swoop"` | `"arc"` | Arrows and connectors. |+| `color`, `width` | | `theme.color.highlight`, `theme.stroke.bold` | |+| `hand` | `false \| { wobble?: number; boil?: number; seed? }` | `{ wobble: 0.6, boil: 4 }` | `boil` = frames between re-poses; `0` = still. |+| `texture` | `"ink" \| "marker" \| "pencil"` | `"marker"` | Marker = round caps + multiply blend; pencil = thin, grainy (FilmGrain-masked). |+| `drawDuration` | `number` | `speed.base` | |+| `label` | `string \| { text; side?; font? }` | — | Note placed beside the mark with a short connector; font defaults to `theme.font.hand` then `body`. |+| `padding` | `number` | `8` | Space between target and mark. |++**Implementation notes**++- Every mark is a `Layer.shape("path")` with `trimEnd` keyed for the draw-on; highlight is a+ filled swash path behind the text (inserted as a sibling below the target).+- Hand-drawn = `wobble` once + `boil` variants keyed on `d` with hold interpolation (shape+ morphing already supports differing point counts).+- Arrow heads are separate paths that appear when the shaft's trim reaches 92 %, with a+ small stretch-and-settle.++**Cues:** `drawn` (mark complete), `labelIn`.++**Acceptance**++- Underline on a phrase that wraps to two lines produces two strokes aligned to each+ line's baseline + `padding` (± 0.5 px).+- `boil: 4` changes the path exactly every 4 frames and repeats with the same seed.++---++### 7.7 `AppFrame`++Window chrome around any content: the container for UI recordings and mock interfaces, and+the coordinate system other components target.++**Props**++| Prop | Type | Default | Notes |+|---|---|---|---|+| `kind` | `"window" \| "browser" \| "terminal" \| "minimal"` | `"window"` | Traffic-light window, browser with URL bar and tabs, terminal title bar, or bare rounded frame. |+| `content` | `LayoutNode \| LayoutNode[] \| string` | required | A string is treated as a media path (`Layer.video`/`image` by extension). |+| `fit` | `"cover" \| "contain" \| "fill"` | `"cover"` | For media content. |+| `title` | `string` | — | |+| `url` | `string \| { text; typeAt?: number }` | — | Browser: optionally types the URL and plays a load bar. |+| `tabs` | `string[]` | — | Browser tabs; the first is active. |+| `appearance` | `"dark" \| "light"` | from theme | |+| `elevation` | `0–3` | `2` | Shadow depth via layer style. |+| `tilt` | `false \| { rotateX, rotateY }` | `false` | 3D presentation angle (perspective root). |++**API additions on the returned node:** `contentRect` (absolute rect of the content slot)+and `at(x, y)` (maps content-local coordinates to composition coordinates), so pointers and+zooms can target positions inside a recording: `MousePointer({ path: [{ to: frame.at(812, 140) }] })`.++**Parts:** `root`, `chrome`, `titlebar`, `controls`, `urlbar`, `tabs`, `content`, `shadow`.+**Cues:** `urlTyped`, `loaded`.++**Acceptance**++- `contentRect` matches the rendered content bounds exactly at every `kind`.+- Light and dark appearances pass `comp.lint()` contrast checks.++---++### 7.8 `Terminal`++A scripted shell session: commands typed with a human rhythm, output streaming in,+spinners resolving, the view scrolling, all on cue. The default terminal look is built in;+`frame: true` wraps it in `AppFrame({ kind: "terminal" })`.++```ts+Terminal({+ script: [+ { cmd: "pnpm add framefields" },+ { spinner: "Resolving packages", for: 40, done: "✔ 1 package added" },+ { cmd: "pnpm render", output: ["Rendering 900 frames…", "{green}✔{/} out/film.mp4 (12.4 s)"] },+ ],+ rows: 14,+});+```++**Props**++| Prop | Type | Default | Notes |+|---|---|---|---|+| `script` | `Step[]` | required | `Step = { cmd } \| { output } \| { spinner; for; done? } \| { progress: label; for } \| { pause } \| { clear: true }`. |+| `prompt` | `string \| TextSpan[]` | `"❯ "` | Per-step override allowed. |+| `cps` | `number` | `18` | Typing speed (chars/sec), seeded jitter ±30 %, pauses after spaces and punctuation. |+| `outputRate` | `number \| "instant"` | `40` lines/sec | |+| `rows` / `cols` | `number` | `16` / auto | Viewport; overflow auto-scrolls. |+| `fps` | `number` | required | For `cps` / `outputRate`. |+| `markup` | `boolean` | `true` | `{green}…{/}`-style colour markup mapped to a 16-colour palette from theme. |+| `frame` | `boolean \| AppFrameProps` | `true` | |+| `caret` | `"block" \| "bar" \| "underline"` | `"block"` | Blinks while idle, solid while typing. |++**Implementation notes**++- One text node per visible line; a line's content is final and its reveal uses+ `typewriter` keys; scrolling animates the line container's `y` by whole line heights.+- Caret position from `measure().caretX`; mono advance validated (warn when the font isn't+ monospaced).+- Spinners are a single glyph slot keyed through braille frames with `hold` interpolation.++**Cues:** `keystrokes` (per typed character, for typing sounds), `submits` (Enter per+command), `outputs` (`{ start, end, step }`), `done`.++**Acceptance**++- Same script + seed → identical keystroke cues and frames.+- Scrolling never cuts a line in half at rest; during scroll, lines leave through the+ viewport mask.+- 200-line output with `rows: 16` keeps ≤ 18 text nodes visible on any frame.++---++## 8. Waves 2 and 3++Specified at summary level now; each gets a full section (like §7) before its milestone+starts.++### 8.1 Wave 2++| Component | Summary | Key props | Notable framefields use |+|---|---|---|---|+| `CodeBlock` | Syntax-highlighted code with line focus, typing, and diffs that move unchanged lines to their new places. | `code`, `lang`, `tokens?` (bring your own highlighter), `focus: [lines]`, `diff: { to, at }`, `typing` | Measured mono layout; lines keyed between positions so diffs read as motion. Ships a small built-in tokenizer for ts/js/json/bash/python/css; anything else via `tokens`. |+| `ChatThread` | A messaging conversation: bubbles from either side, typing indicator, reactions, timestamps, auto-scroll. | `messages: { from, text \| media, at? }[]`, `participants`, `appearance` | Bubble sizes from measured text; spring entries baked; typing dots between messages. |+| `Callout` | A label with a leader line pinned to a point or a moving tracked object; stays inside the frame. | `target`, `text`, `side: "auto" \| …`, `elbow` | Dynamic targets bind to vision `track` signals; auto side picks the free quadrant per frame. |+| `Spotlight` | Dims the frame except a feathered region that glides between targets. | `targets: { at, target }[]`, `dim`, `feather`, `shape` | Inverted alpha matte + blur; region keyed between target rects. |+| `Confetti` | Celebration bursts with paper, ribbons and sparkles that fall and settle. | `bursts: { at, origin, count }[]`, `palette`, `gravity`, `floor` | GPU particles; optional physics floor; bursts can come straight from `cues`. |+| `Meter` | Progress and score visuals: ring, bar, arc gauge, star rating, each with an optional `Counter`. | `value`, `max`, `kind`, `segments`, `label` | Conic gradients, `trimEnd` arcs, fractional star fill via matte. |+| `TitleCard` | Kicker, headline, rule and sub-line in tested layouts (`center`, `left`, `split`, `stack`). | `kicker`, `title`, `subtitle`, `layout` | Built from `TextReveal` + `Annotate` (rule) for consistent motion. |+| `LowerThird` | Name and role bar for interviews and talks, several layouts, safe-area aware. | `name`, `role`, `layout`, `side` | Measured plate width; enter/exit presets. |+| `Toasts` | Notifications arriving into a stack that pushes down and compresses as it grows. | `items: { at, title, body, icon? }[]`, `max`, `corner` | Stack layout solved offline; spring settle baked. |++### 8.2 Wave 3 candidates++`TouchPoint` (mobile taps, long-presses and swipes) · `Selection` (marquee and text+selection driven by a `MousePointer`) · `WordCycle` (one slot in a sentence cycles through+alternatives while the rest reflows) · `DeviceFrame` (phone, tablet, laptop bezels with a+screen slot; 2D and 3D) · `Backdrop` (mesh gradient, grid, dot field, grain; loop-exact) ·+`BeforeAfter` (split view with a draggable divider) · `CardStack` (depth-stacked cards that+shuffle forward) · `LogoReveal` (extruded / glass / chrome wordmark reveal on `Layer3D`) ·+`LayerDiagram` (exploded 3D plates with labels for architecture explainers) · `Avatars`+(overlapping avatar group with count) · `SocialPost` (post / follow card mock-ups).++Wave 3 is re-scored with the §6 criteria after Wave 2 ships, using what users actually+ask for.++---++## 9. Quality bar++A component is **done** when all of the following pass in CI.++### 9.1 Unit tests (components package, fake host)++Planners, parsers, phrase builders, path math, stagger orders, bake simplification. No+GPU. Target ≥ 90 % line coverage on `core/` and every `plan.ts`.++### 9.2 Render tests (framefields package, real GPU)++`packages/framefields/src/components/<name>.render.test.ts` renders a `renderFrameGrid` of+the canonical example and compares to a committed golden with the existing tolerance+helpers. Every acceptance criterion in §7 that mentions a frame is a test here.++### 9.3 Determinism++Each render test also renders its frames in reverse order and in a shuffled order, and+asserts identical output. Each component with randomness renders twice with the same seed+(identical) and once with another seed (different).++### 9.4 Plain data++`JSON.parse(JSON.stringify(component))` validates against the program schema+(`builder-schema-conformance` style), and `comp.lint()` reports nothing for the canonical+example under every built-in theme.++### 9.5 Tree-shaking++`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.++Each new component adds a case importing only itself, with every other component's marker+forbidden.++### 9.6 Budgets++| Component | Max nodes on any frame (canonical example) | Max build time |+|---|---|---|+| MousePointer | 24 | 20 ms |+| FocusZoom | content + 3 | 50 ms (500-frame solve) |+| Captions | 6 per visible phrase | 30 ms per minute of speech |+| TextReveal | 4 + 2 per line (`mask`, `scramble`: + 1 per char) | 10 ms |+| Counter | 3 + 1 per digit | 5 ms |+| Annotate | 4 per line of target | 5 ms |+| AppFrame | 14 + content | 5 ms |+| Terminal | rows + 6 | 20 ms |++### 9.7 Docs and skills++- Docs page per component: summary, live gallery stills, props table generated from the+ schema, parts, cues, recipes.+- `plugins/framefields/skills/framefields-compose/SKILL.md` gains a **Components** section+ (a table generated from `components.json` plus the cue-sync pattern). The skill-md check+ test keeps it in sync.+- One example film per milestone (§10) under `examples/`.++---++## 10. Delivery plan++Each milestone ends with a changeset for `framefields` (minor), docs, and its example film.++| Milestone | Scope | Exit criteria |+|---|---|---|+| **M0 · Foundations** ✅ | Package scaffold; host binding in framefields (`./components` export, root re-exports, tsdown entry, `bindComponent`); `core/*` modules (§5); test harness (fake host, GPU render test, determinism); tree-shake check; `components.json` collector. | Done: a test-only `Probe` component passes §9.1–9.5 (§12). |+| **M1 · Pointer & camera** | `MousePointer` (rebuilt to the existing changeset design plus the Wave 1 additions), `FocusZoom`, `AppFrame`. | Example `30_product_demo`: a screen recording in a browser frame, pointer with clicks and auto-zoom, click SFX placed from cues. |+| **M2 · Type** | `TextReveal`, `Counter`, `Annotate`. | Example `31_type_and_numbers`: every reveal style, counters, annotations on wrapped text; all §7.4–7.6 acceptance tests green. |+| **M3 · Speech & shell** | `Captions` (incl. transcript parsers and `behind`), `Terminal`. | Example `32_talking_head_social` (portrait, captions behind the speaker, audio pulse) and a terminal segment in a dev-tool launch cut. |+| **M4 · Wave 2a** | `CodeBlock`, `TitleCard`, `LowerThird`, `Meter`. | Full specs written first (§8 → §7 format). |+| **M5 · Wave 2b** | `ChatThread`, `Callout`, `Spotlight`, `Confetti`, `Toasts`. | As above. |+| **M6 · Re-score** | Rank Wave 3 against usage and requests. | Updated §8.2. |++Housekeeping before M1: `.changeset/components-mouse-pointer.md` and the+`packages/components` lockfile entry describe a package that is not on disk. Either restore+that implementation as the M1 starting point or retarget the changeset to `framefields`+when M1 lands.++---++## 11. Open questions++| # | Question | Status |+|---|---|---|+| Q1 | Root re-export or `framefields/components` only? | **Decided (M0):** components and user-facing types at the root, full toolkit at the subpath (§3.1). |+| Q2 | Is text `content` keyframeable with hold interpolation? | **Answered:** yes, `text` is an animatable prop (`.keys("text", …)`, which `FontManager.measure().caretX` is documented to pair with). `Counter` `count` style and `TextReveal` `type` / `stream` use it directly. |+| Q3 | Node targets inside flex layouts need resolved geometry at build time. | **Partly answered:** `computeLayoutSync(yoga, { layout, viewport, measure })` already exists in `@framefields/compositions/program`. M1 adds a `host.layout(root)` backed by it; until then node targets require absolute nodes and the error says so. |+| 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. |+| 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++What landed:++- `packages/components`: `core/` (rng, ease, timing, theme, bake, motion, path, draw,+ text, targets, host, contract, meta), 50 unit tests on a fake host+ (`src/test/fake-host.ts`, fixed-advance text measurement) including package rules+ (no `Math.random` / clock reads; `index.ts` is re-exports only), and the meta collector.+- `packages/framefields`: `src/components/host.ts`, `src/components/index.ts`+ (`bindComponent`, toolkit re-exports), the `./components` export and tsdown entry, root+ re-exports, the tree-shake check, and `contract.render.test.ts` (GPU): enter motion,+ in-flow placement, frame-exact cues for siblings, schema + lint, and identical pixels in+ any frame order.++Deviations from the original plan, all reflected above: no `AnimatableNode` type move+(§3.3), a narrower root export (§3.1), an added `fps` base prop (§4.2), `blur` / `mask`+presets moved to M2 (§5.4), and a baseline-relative tree-shake check (§9.5). The probe+component lives in tests only, so there was nothing to delete.diff --git a/packages/components/package.json b/packages/components/package.jsonnew file mode 100644index 00000000..0aa31f32--- /dev/null+++ b/packages/components/package.json@@ -0,0 +1,43 @@+{+ "name": "@framefields/components",+ "version": "2.4.3",+ "private": true,+ "description": "Parametric motion components for framefields. Internal: bundled into and exported from `framefields`.",+ "type": "module",+ "sideEffects": false,+ "license": "Apache-2.0",+ "module": "./dist/index.mjs",+ "types": "./dist/index.d.mts",+ "exports": {+ ".": {+ "types": "./dist/index.d.mts",+ "development": "./src/index.ts",+ "import": "./dist/index.mjs",+ "default": "./dist/index.mjs"+ }+ },+ "files": [+ "dist/**"+ ],+ "scripts": {+ "build": "tsdown && tsx scripts/build-meta.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"+ },+ "dependencies": {+ "@framefields/compositions": "workspace:*",+ "@framefields/core": "workspace:*",+ "zod": "^4.3.6"+ },+ "devDependencies": {+ "@framefields/tsconfig": "workspace:*",+ "@types/node": "^24.1.0",+ "tsdown": "^0.19.0",+ "tsx": "^4.20.3",+ "typescript": "^5.8.3",+ "vitest": "^4.1.11"+ }+}diff --git a/packages/components/scripts/build-meta.test.ts b/packages/components/scripts/build-meta.test.tsnew file mode 100644index 00000000..b2b57fb1--- /dev/null+++ b/packages/components/scripts/build-meta.test.ts@@ -0,0 +1,37 @@+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { collectMeta } from "./build-meta.js";++const meta = (name: string) =>+ `export default ${JSON.stringify({ name, summary: "s", tags: [], parts: [], cues: [], example: "", since: "M1" })};`;++function fixture(components: Record<string, string | null>) {+ const dir = mkdtempSync(join(tmpdir(), "ff-meta-"));+ mkdirSync(join(dir, "core"));+ for (const [folder, source] of Object.entries(components)) {+ mkdirSync(join(dir, folder));+ if (source !== null) writeFileSync(join(dir, folder, "meta.ts"), source);+ }+ return dir;+}++describe("collectMeta", () => {+ it("is empty before any component exists", async () => {+ expect(await collectMeta()).toEqual(expect.any(Array));+ });++ it("collects, sorts, and rejects missing or duplicate metas", async () => {+ const ok = await collectMeta(+ fixture({ zeta: meta("Zeta"), alpha: meta("Alpha") }),+ );+ expect(ok.map((m) => m.name)).toEqual(["Alpha", "Zeta"]);+ await expect(collectMeta(fixture({ broken: null }))).rejects.toThrow(+ /no meta.ts/,+ );+ await expect(+ collectMeta(fixture({ a: meta("Same"), b: meta("Same") })),+ ).rejects.toThrow(/Duplicate/);+ });+});diff --git a/packages/components/scripts/build-meta.ts b/packages/components/scripts/build-meta.tsnew file mode 100644index 00000000..63487956--- /dev/null+++ b/packages/components/scripts/build-meta.ts@@ -0,0 +1,46 @@+/**+ * Collects every component's `meta.ts` (default export) into+ * `dist/components.json`: the list docs and the skills generator read.+ * Run with `pnpm --filter @framefields/components meta` (also part of build).+ */+import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import type { ComponentMeta } from "../src/core/meta.js";++const SRC = fileURLToPath(new URL("../src", import.meta.url));+const NOT_COMPONENTS = new Set(["core", "test"]);++export async function collectMeta(src = SRC): Promise<ComponentMeta[]> {+ const metas: ComponentMeta[] = [];+ for (const entry of readdirSync(src, { withFileTypes: true })) {+ if (!entry.isDirectory() || NOT_COMPONENTS.has(entry.name)) continue;+ const file = join(src, entry.name, "meta.ts");+ if (!existsSync(file)) {+ throw new Error(`Component folder "${entry.name}" has no meta.ts`);+ }+ const mod = (await import(pathToFileURL(file).href)) as {+ default?: ComponentMeta;+ };+ if (!mod.default) throw new Error(`${file} has no default export`);+ metas.push(mod.default);+ }+ const names = new Set<string>();+ for (const m of metas) {+ if (names.has(m.name))+ throw new Error(`Duplicate component name "${m.name}"`);+ names.add(m.name);+ }+ return metas.sort((a, b) => a.name.localeCompare(b.name));+}++if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {+ const metas = await collectMeta();+ const out = fileURLToPath(new URL("../dist", import.meta.url));+ mkdirSync(out, { recursive: true });+ writeFileSync(+ join(out, "components.json"),+ `${JSON.stringify(metas, null, "\t")}\n`,+ );+ console.log(`components.json: ${metas.length} component(s)`);+}diff --git a/packages/components/src/core/bake.test.ts b/packages/components/src/core/bake.test.tsnew file mode 100644index 00000000..d52f1cbd--- /dev/null+++ b/packages/components/src/core/bake.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from "vitest";+import {+ bakeFunction,+ bakeSamples,+ springAt,+ springSettleFrames,+} from "./bake.js";++const lerpKeys = (keys: [number, number][], f: number) => {+ for (let i = 0; i < keys.length - 1; i++) {+ const [f0, v0] = keys[i]!;+ const [f1, v1] = keys[i + 1]!;+ if (f >= f0 && f <= f1) return v0 + ((v1 - v0) * (f - f0)) / (f1 - f0);+ }+ return keys[keys.length - 1]![1];+};++describe("bake", () => {+ it("collapses lines to their endpoints", () => {+ expect(bakeSamples([0, 1, 2, 3, 4], 10)).toEqual([+ [10, 0],+ [14, 4],+ ]);+ });++ it("keeps every sample within tolerance", () => {+ const fn = (f: number) => Math.sin(f / 30) * 20;+ const keys = bakeFunction(fn, 0, 120, { tolerance: 0.5 });+ expect(keys.length).toBeLessThan(30);+ for (let f = 0; f <= 120; f++) {+ expect(Math.abs(lerpKeys(keys, f) - fn(f))).toBeLessThanOrEqual(+ 0.5 + 1e-9,+ );+ }+ for (const [frame] of keys) expect(Number.isInteger(frame)).toBe(true);+ });++ it("evaluates springs in closed form", () => {+ expect(springAt(0)).toBe(0);+ expect(springAt(5)).toBeCloseTo(1, 4);+ const bouncy = Array.from({ length: 60 }, (_, f) =>+ springAt(f / 30, { stiffness: 200, damping: 8 }),+ );+ expect(Math.max(...bouncy)).toBeGreaterThan(1.2);+ expect(springAt(0.3, { damping: 28.28 })).toBeLessThan(1); // ~critical: no overshoot+ const over = Array.from({ length: 90 }, (_, f) =>+ springAt(f / 30, { damping: 80 }),+ );+ expect(Math.max(...over)).toBeLessThanOrEqual(1);+ expect(springSettleFrames(30)).toBeGreaterThan(10);+ expect(springSettleFrames(30)).toBeLessThan(60);+ });+});diff --git a/packages/components/src/core/bake.ts b/packages/components/src/core/bake.tsnew file mode 100644index 00000000..553690bf--- /dev/null+++ b/packages/components/src/core/bake.ts@@ -0,0 +1,117 @@+/**+ * Turn per-frame values into a few linear keyframes. Components solve motion+ * offline (springs, camera follow, arc-length travel) and bake it, so the+ * output stays plain keyframe JSON that seeks exactly.+ */++/** `[frame, value]`: a linear keyframe, as `LayerAnimation.keys` takes it. */+export type BakedKey = [frame: number, value: number];++export interface BakeOptions {+ /** Max deviation (in the value's units) of the simplified curve. Default 0.25. */+ tolerance?: number;+}++/**+ * Simplify `values` (one per frame, starting at `startFrame`) to linear keys+ * whose interpolation stays within `tolerance` of every sample+ * (Ramer–Douglas–Peucker on the frame/value polyline). First and last+ * samples are always kept.+ */+export function bakeSamples(+ values: readonly number[],+ startFrame = 0,+ options: BakeOptions = {},+): BakedKey[] {+ const tolerance = options.tolerance ?? 0.25;+ if (values.length === 0) return [];+ if (values.length === 1) return [[startFrame, values[0] as number]];++ const keep = new Uint8Array(values.length);+ keep[0] = 1;+ keep[values.length - 1] = 1;+ const stack: Array<[number, number]> = [[0, values.length - 1]];+ while (stack.length > 0) {+ const [a, b] = stack.pop() as [number, number];+ const va = values[a] as number;+ const vb = values[b] as number;+ let worst = -1;+ let worstErr = tolerance;+ for (let i = a + 1; i < b; i++) {+ const t = (i - a) / (b - a);+ const err = Math.abs((values[i] as number) - (va + (vb - va) * t));+ if (err > worstErr) {+ worstErr = err;+ worst = i;+ }+ }+ if (worst !== -1) {+ keep[worst] = 1;+ stack.push([a, worst], [worst, b]);+ }+ }++ const out: BakedKey[] = [];+ for (let i = 0; i < values.length; i++) {+ if (keep[i]) out.push([startFrame + i, values[i] as number]);+ }+ return out;+}++/** Sample `fn` on every frame in [start, end] and bake it. */+export function bakeFunction(+ fn: (frame: number) => number,+ start: number,+ end: number,+ options?: BakeOptions,+): BakedKey[] {+ const values: number[] = [];+ for (let f = start; f <= end; f++) values.push(fn(f));+ return bakeSamples(values, start, options);+}++/**+ * Damped spring from 0 to 1 in closed form: `stiffness` (k), `damping` (c),+ * `mass` (m), sampled in seconds. Under-damped springs overshoot.+ */+export function springAt(+ seconds: number,+ { stiffness = 170, damping = 26, mass = 1 } = {},+): number {+ if (seconds <= 0) return 0;+ const w0 = Math.sqrt(stiffness / mass);+ const zeta = damping / (2 * Math.sqrt(stiffness * mass));+ if (zeta < 1) {+ const wd = w0 * Math.sqrt(1 - zeta * zeta);+ return (+ 1 -+ Math.exp(-zeta * w0 * seconds) *+ (Math.cos(wd * seconds) + ((zeta * w0) / wd) * Math.sin(wd * seconds))+ );+ }+ if (zeta === 1) {+ return 1 - Math.exp(-w0 * seconds) * (1 + w0 * seconds);+ }+ const r1 = -w0 * (zeta - Math.sqrt(zeta * zeta - 1));+ const r2 = -w0 * (zeta + Math.sqrt(zeta * zeta - 1));+ const c2 = r1 / (r1 - r2);+ const c1 = 1 - c2;+ return 1 - (c1 * Math.exp(r1 * seconds) + c2 * Math.exp(r2 * seconds));+}++/**+ * Frames until a spring stays within `epsilon` of rest, at `fps`; capped at+ * `max` frames.+ */+export function springSettleFrames(+ fps: number,+ options?: Parameters<typeof springAt>[1],+ epsilon = 0.001,+ max = 600,+): number {+ let last = 0;+ for (let f = 0; f <= max; f++) {+ if (Math.abs(1 - springAt(f / fps, options)) > epsilon) last = f;+ }+ return Math.min(max, last + 1);+}diff --git a/packages/components/src/core/contract.test.ts b/packages/components/src/core/contract.test.tsnew file mode 100644index 00000000..aaa9f3d9--- /dev/null+++ b/packages/components/src/core/contract.test.ts@@ -0,0 +1,131 @@+import { describe, expect, it } from "vitest";+import { fakeHost } from "../test/fake-host.js";+import { probe } from "../test/probe.js";+import { bind, pulseKeys } from "./contract.js";++const make = () => bind(fakeHost(), probe);++describe("component contract", () => {+ it("builds root → stage → content with the natural window", () => {+ const Probe = make();+ const node = Probe({ at: 30, x: 100, y: 50 });+ expect(node).toMatchObject({+ kind: "box",+ id: "probe-auto-1",+ position: "absolute",+ x: 100,+ y: 50,+ width: 100,+ height: 100,+ startFrame: 30,+ durationFrames: 15, // natural 10 + hold 5, no exit+ });+ const stage = node.part("stage")!;+ expect(stage).toMatchObject({+ id: "probe-auto-1-stage",+ position: "absolute",+ x: 0,+ y: 0,+ });+ expect(+ (stage as { children: Array<{ id: string }> }).children.map((c) => c.id),+ ).toEqual(["probe-auto-1-plate", "probe-auto-1-label"]);+ expect(node.span).toEqual({ start: 30, end: 45, duration: 15 });+ });++ it("puts cues on the parent's timeline", () => {+ const node = make()({ at: 30, ticks: [2, 7] });+ expect(node.cues.landed).toEqual([{ frame: 40 }]);+ expect(node.cues.ticks.map((c) => c.frame)).toEqual([32, 37]);+ });++ it("keeps extras off the JSON", () => {+ const node = make()({ id: "p" });+ const json = JSON.parse(JSON.stringify(node));+ expect(json).not.toHaveProperty("cues");+ expect(json).not.toHaveProperty("span");+ expect(json).not.toHaveProperty("part");+ expect(json.children[0].id).toBe("p-stage");+ });++ it("applies enter by default and exit when asked, extending the window", () => {+ const node = make()({ exit: { preset: "fade", duration: 6 } });+ expect(node.durationFrames).toBe(21);+ const tracks =+ (+ node.part("stage") as {+ animation?: { tracks: Array<{ prop: string }> };+ }+ ).animation?.tracks ?? [];+ expect(tracks.map((t) => t.prop).sort()).toEqual([+ "opacity",+ "opacity",+ "y",+ ]);+ const none = make()({ enter: false });+ expect(+ (none.part("stage") as { animation?: unknown }).animation,+ ).toBeUndefined();+ });++ it("respects explicit duration, size, flow placement and theme", () => {+ const node = make()({+ duration: 90,+ width: 300,+ position: "relative",+ theme: { color: { accent: "#123456" } },+ });+ expect(node.durationFrames).toBe(90);+ expect(node.width).toBe(300);+ expect(node.position).toBe("relative");+ expect(node.x).toBeUndefined();+ expect(node.part("plate")).toMatchObject({ background: "#123456" });+ });++ it("is deterministic per seed", () => {+ const a = make()({ ticks: [1, 2], seed: 3 }).cues.ticks;+ const b = make()({ ticks: [1, 2], seed: 3 }).cues.ticks;+ const c = make()({ ticks: [1, 2], seed: 4 }).cues.ticks;+ expect(a).toEqual(b);+ expect(a).not.toEqual(c);+ });++ it("hands every part to customize", () => {+ const seen: string[] = [];+ make()({+ customize: (parts) => {+ seen.push(...Object.keys(parts));+ (parts.plate as { background?: string }).background = "#fff";+ },+ });+ expect(seen.sort()).toEqual(["label", "plate", "root", "stage"]);+ });++ it("rejects bad and unknown props with a readable message", () => {+ const Probe = make();+ expect(() => Probe({ at: -1 })).toThrow(/Probe: invalid props\n {2}- at:/);+ expect(() => Probe({ lable: "x" } as never)).toThrow(/lable/);+ expect(() => Probe({ enter: "spin" as never })).toThrow(/enter/);+ expect(() => Probe({ at: 1.5 })).toThrow(/at/);+ });+});++describe("pulseKeys", () => {+ it("pulses at each cue", () => {+ expect(+ pulseKeys([{ frame: 10 }, 30], {+ rest: 1,+ peak: 1.2,+ attack: 2,+ release: 6,+ }),+ ).toEqual([+ [8, 1],+ [10, 1.2],+ [16, 1, "power2.out"],+ [28, 1],+ [30, 1.2],+ [36, 1, "power2.out"],+ ]);+ });+});diff --git a/packages/components/src/core/contract.ts b/packages/components/src/core/contract.tsnew file mode 100644index 00000000..7dd2f3ef--- /dev/null+++ b/packages/components/src/core/contract.ts@@ -0,0 +1,349 @@+/**+ * The component contract: props in (validated), a layer tree out, plus the+ * moments it produced (`cues`), its window (`span`) and named parts.+ *+ * Every component is a root box (placement, window) holding a `stage` box+ * (enter / exit motion) holding the component's own content.+ */+import type {+ BoxNode,+ KeyframeTuple,+ LayoutNode,+} from "@framefields/compositions/program";+import { z } from "zod";+import type { Animatable, Host } from "./host.js";+import {+ enterAnimation,+ exitAnimation,+ MOTION_PRESETS,+ type MotionPreset,+ resolveMotion,+} from "./motion.js";+import { hashRng, type Rng } from "./rng.js";+import { defineTheme, type Theme, type ThemeInput } from "./theme.js";++// ── Cues ──────────────────────────────────────────────────────────────++/** A moment a component produced, as an integer frame (plus data). */+export type Cue<D extends object = object> = { frame: number } & D;++/** A component's cues by name. */+export type Cues = Record<string, readonly Cue[]>;++/** Shift every cue's `frame` (and `end`, when present) by `offset`. */+export function offsetCues<C extends Cues>(cues: C, offset: number): C {+ const out: Record<string, Cue[]> = {};+ for (const [name, list] of Object.entries(cues)) {+ out[name] = list.map((c) => {+ const shifted: Record<string, unknown> = {+ ...c,+ frame: c.frame + offset,+ };+ if (typeof (c as { end?: unknown }).end === "number") {+ shifted.end = (c as unknown as { end: number }).end + offset;+ }+ return shifted as Cue;+ });+ }+ return out as unknown as C;+}++export interface PulseOptions {+ /** Value between pulses. Default 0. */+ rest?: number;+ /** Value at the cue frame. Default 1. */+ peak?: number;+ /** Frames before the cue the rise starts. Default 0 (instant). */+ attack?: number;+ /** Frames after the cue to fall back to rest. Default 8. */+ release?: number;+ ease?: string;+}++/**+ * Keyframes that pulse at each cue: rest → peak on the cue → rest. Use them+ * on any prop: `LayerAnimation.keys("scale", pulseKeys(pointer.cues.clicks, { rest: 1, peak: 1.1 }))`.+ * Frames are as given, so cues from a sibling component line up when both+ * share a parent.+ */+export function pulseKeys(+ cues: readonly (Cue | number)[],+ {+ rest = 0,+ peak = 1,+ attack = 0,+ release = 8,+ ease = "power2.out",+ }: PulseOptions = {},+): KeyframeTuple[] {+ const frames = cues+ .map((c) => (typeof c === "number" ? c : c.frame))+ .sort((a, b) => a - b);+ const keys = new Map<number, KeyframeTuple>();+ for (const f of frames) {+ const from = Math.max(0, f - attack);+ if (!keys.has(from)) keys.set(from, [from, rest]);+ keys.set(f, [f, peak]);+ keys.set(f + release, [f + release, rest, ease]);+ }+ return [...keys.values()].sort((a, b) => a[0] - b[0]);+}++// ── Props ─────────────────────────────────────────────────────────────++const fn = <T>() =>+ z.custom<T>((v) => typeof v === "function", {+ message: "Expected a function",+ });++const MotionPresetSchema = z.union([+ z.enum(MOTION_PRESETS as [string, ...string[]]),+ z.object({+ preset: z.enum(MOTION_PRESETS as [string, ...string[]]),+ duration: z.number().int().positive().optional(),+ ease: z.string().optional(),+ distance: z.number().optional(),+ delay: z.number().int().min(0).optional(),+ }),+]);++/** Props every component accepts. */+export const BasePropsSchema = z.object({+ id: z.string().min(1).optional(),+ at: z.number().int().min(0).optional(),+ duration: z.number().int().positive().optional(),+ hold: z.number().int().min(0).optional(),+ enter: z.union([MotionPresetSchema, z.literal(false)]).optional(),+ exit: z.union([MotionPresetSchema, z.literal(false)]).optional(),+ x: z.number().optional(),+ y: z.number().optional(),+ width: z.number().positive().optional(),+ height: z.number().positive().optional(),+ position: z.enum(["absolute", "relative"]).optional(),+ theme: z+ .custom<ThemeInput>((v) => typeof v === "object" && v !== null)+ .optional(),+ seed: z.number().int().optional(),+ fps: z.number().positive().optional(),+ customize:+ fn<(parts: Record<string, Animatable<LayoutNode>>) => void>().optional(),+});++export interface BaseProps {+ /** Root id; parts get `<id>-<part>`. */+ id?: string;+ /** Start frame in the parent's timeline. Default 0. */+ at?: number;+ /** Whole window in frames. Default: natural length + hold (+ exit). */+ duration?: number;+ /** Frames the finished state holds before the exit. */+ hold?: number;+ /** Entrance of the whole component, or `false`. */+ enter?: MotionPreset | false;+ /** Exit of the whole component, or `false`. */+ exit?: MotionPreset | false;+ x?: number;+ y?: number;+ width?: number;+ height?: number;+ position?: "absolute" | "relative";+ /** Tokens; partial themes merge over the default. */+ theme?: ThemeInput | Theme;+ /** Every random choice derives from it. Default 1. */+ seed?: number;+ /** Composition frame rate: theme speeds and real-time inputs scale by it. Default 30. */+ fps?: number;+ /** Receives every built part before the component returns. */+ customize?: (parts: Record<string, Animatable<LayoutNode>>) => void;+}++// ── Definition ────────────────────────────────────────────────────────++export interface BuildContext {+ host: Host;+ theme: Theme;+ fps: number;+ seed: number;+ /** The component's root id. */+ id: string;+ /** `<id>-<part>`. */+ partId(part: string): string;+ /** A seeded stream for `key`, stable across unrelated prop changes. */+ rng(key: string | number): Rng;+}++export interface BuildResult<C extends Cues> {+ /** The component's content, laid out inside a box of `width` × `height`. */+ children: LayoutNode[];+ width: number;+ height: number;+ /** Natural length in frames: when the content's own animation settles. */+ duration: number;+ /** Cues in the component's local frames (0 = component start). */+ cues: C;+ /** Named sub-nodes, exposed to `customize` and `part()`. */+ parts?: Record<string, Animatable<LayoutNode>>;+}++export interface ComponentDefaults {+ enter?: MotionPreset | false;+ exit?: MotionPreset | false;+ hold?: number;+}++export interface ComponentDefinition<S extends z.ZodRawShape, C extends Cues> {+ /** PascalCase name, as exported. */+ name: string;+ /** Zod shape of the component's own props (base props are added). */+ props: S;+ defaults?: ComponentDefaults;+ build(ctx: BuildContext, props: z.output<z.ZodObject<S>>): BuildResult<C>;+}++export function defineComponent<S extends z.ZodRawShape, C extends Cues>(+ definition: ComponentDefinition<S, C>,+): ComponentDefinition<S, C> {+ return definition;+}++/** Props a component accepts: its own (input types) plus the base props. */+export type PropsOf<D> =+ D extends ComponentDefinition<infer S, Cues>+ ? z.input<z.ZodObject<S>> & BaseProps+ : never;++export type CuesOf<D> =+ D extends ComponentDefinition<z.ZodRawShape, infer C> ? C : never;++/** What every component adds to its root node. */+export interface ComponentExtras<C extends Cues> {+ /** Moments the component produced, in the parent's timeline. */+ readonly cues: C;+ /** The component's window in the parent's timeline. */+ readonly span: { start: number; end: number; duration: number };+ /** A named part (`root`, `stage`, and the component's own). */+ part(name: string): Animatable<LayoutNode> | undefined;+}++export type ComponentNode<C extends Cues> = Animatable<BoxNode> &+ ComponentExtras<C>;++const kebab = (name: string) =>+ name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();++/**+ * Bind a definition to a host, producing the user-facing factory. framefields+ * calls this once per component behind a PURE annotation, so bundlers drop+ * the ones nobody imports.+ */+export function bind<S extends z.ZodRawShape, C extends Cues>(+ host: Host,+ definition: ComponentDefinition<S, C>,+): (props: z.input<z.ZodObject<S>> & BaseProps) => ComponentNode<C> {+ let schema: z.ZodObject | undefined;+ return (input) => {+ schema ??= BasePropsSchema.extend(definition.props).strict();+ const parsed = schema.safeParse(input ?? {});+ if (!parsed.success) {+ const issues = parsed.error.issues+ .map((i) => ` - ${i.path.join(".") || "(props)"}: ${i.message}`)+ .join("\n");+ throw new Error(`${definition.name}: invalid props\n${issues}`);+ }+ return assemble(+ host,+ definition,+ parsed.data as BaseProps & z.output<z.ZodObject<S>>,+ );+ };+}++function assemble<S extends z.ZodRawShape, C extends Cues>(+ host: Host,+ definition: ComponentDefinition<S, C>,+ props: BaseProps & z.output<z.ZodObject<S>>,+): ComponentNode<C> {+ const theme = defineTheme(props.theme ?? {});+ const fps = props.fps ?? 30;+ const seed = props.seed ?? 1;+ const id = props.id ?? host.autoId(kebab(definition.name));+ const ctx: BuildContext = {+ host,+ theme,+ fps,+ seed,+ id,+ partId: (part) => `${id}-${part}`,+ rng: (key) => hashRng(seed, key),+ };++ const built = definition.build(ctx, props);+ const defaults = definition.defaults ?? {};+ const enter = resolveMotion(+ props.enter === undefined ? defaults.enter : props.enter,+ "enter",+ theme,+ fps,+ );+ const exit = resolveMotion(+ props.exit === undefined ? defaults.exit : props.exit,+ "exit",+ theme,+ fps,+ );+ const hold = props.hold ?? defaults.hold ?? 0;+ const duration =+ props.duration ??+ Math.max(+ 1,+ built.duration + hold + (exit ? exit.duration + exit.delay : 0),+ );+ const width = props.width ?? built.width;+ const height = props.height ?? built.height;++ const stage = host.box({+ id: ctx.partId("stage"),+ position: "absolute",+ x: 0,+ y: 0,+ width,+ height,+ children: built.children,+ });+ if (enter) stage.animate(enterAnimation(enter, 0));+ if (exit) stage.animate(exitAnimation(exit, duration));++ const absolute = props.x !== undefined || props.y !== undefined;+ const root = host.box({+ id,+ ...(absolute+ ? { position: "absolute" as const, x: props.x ?? 0, y: props.y ?? 0 }+ : props.position+ ? { position: props.position }+ : {}),+ width,+ height,+ startFrame: props.at ?? 0,+ durationFrames: duration,+ children: [stage],+ });++ const parts: Record<string, Animatable<LayoutNode>> = {+ ...built.parts,+ root,+ stage,+ };+ props.customize?.(parts);++ const start = props.at ?? 0;+ const cues = offsetCues(built.cues, start);+ Object.defineProperties(root, {+ cues: { value: cues, enumerable: false },+ span: {+ value: { start, end: start + duration, duration },+ enumerable: false,+ },+ part: { value: (name: string) => parts[name], enumerable: false },+ });+ return root as ComponentNode<C>;+}diff --git a/packages/components/src/core/draw.test.ts b/packages/components/src/core/draw.test.tsnew file mode 100644index 00000000..557e677b--- /dev/null+++ b/packages/components/src/core/draw.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from "vitest";+import {+ arrowPaths,+ boilKeys,+ boxPath,+ drawOnKeys,+ ellipsePath,+ linePath,+ squigglePath,+ wobblePoints,+} from "./draw.js";++const rect = { x: 100, y: 100, width: 200, height: 60 };++describe("draw", () => {+ it("keys a draw-on", () => {+ expect(drawOnKeys(10, 12)).toEqual([+ [10, 0],+ [22, 1, "power2.inOut"],+ ]);+ });++ it("is clean without wobble and seeded with it", () => {+ expect(linePath([0, 0], [100, 0])).toBe("M0 0 L100 0");+ const a = ellipsePath(rect, { wobble: 3, seed: 4 });+ expect(ellipsePath(rect, { wobble: 3, seed: 4 })).toBe(a);+ expect(ellipsePath(rect, { wobble: 3, seed: 5 })).not.toBe(a);+ expect(ellipsePath(rect, { wobble: 3, seed: 4 }, 1)).not.toBe(a);+ });++ it("wobbles smoothly within the amount", () => {+ const pts = Array.from(+ { length: 40 },+ (_, i) => [i * 10, 0] as [number, number],+ );+ const w = wobblePoints(pts, { wobble: 4, seed: 2 });+ for (let i = 0; i < pts.length; i++) {+ expect(Math.abs(w[i]![1])).toBeLessThanOrEqual(4);+ if (i > 0) expect(Math.abs(w[i]![1] - w[i - 1]![1])).toBeLessThan(2);+ }+ });++ it("frames rects with padding", () => {+ expect(boxPath(rect, { padding: 10 })).toBe(+ "M90 90 L310 90 L310 170 L90 170 Z",+ );+ expect(ellipsePath(rect)).toMatch(/^M300 130/);+ });++ it("builds arrows whose head meets the tip", () => {+ const { shaft, head } = arrowPaths([0, 0], [200, 100], { curve: "arc" });+ expect(shaft.startsWith("M0 0")).toBe(true);+ expect(shaft.endsWith("L200 100")).toBe(true);+ expect(head).toContain("200 100");+ expect(squigglePath([0, 0], [120, 0], { amplitude: 5 })).toMatch(/^M0 0/);+ });++ it("boils between poses with hold keys", () => {+ const keys = boilKeys((v) => `pose-${v}`, {+ start: 0,+ end: 12,+ every: 4,+ variants: 3,+ });+ expect(keys).toEqual([+ [0, "pose-0", "hold"],+ [4, "pose-1", "hold"],+ [8, "pose-2", "hold"],+ [12, "pose-0", "hold"],+ ]);+ expect(boilKeys((v) => `p${v}`, { start: 5, end: 50, every: 0 })).toEqual([+ [5, "p0"],+ ]);+ });+});diff --git a/packages/components/src/core/draw.ts b/packages/components/src/core/draw.tsnew file mode 100644index 00000000..f04f2c54--- /dev/null+++ b/packages/components/src/core/draw.ts@@ -0,0 +1,269 @@+/**+ * Strokes that draw on, and the hand-drawn look: seeded wobble plus "boil"+ * (re-posing the stroke every few frames, like drawn animation).+ */+import type { KeyframeTuple } from "@framefields/compositions/program";+import { catmullRom, toPathData, type Vec2 } from "./path.js";+import { hashRng } from "./rng.js";++export interface Rect {+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface HandOptions {+ /** Wobble amount in px at theme scale 1. 0 = clean geometry. */+ wobble?: number;+ seed?: number;+}++/** Keys for `trimEnd` 0 → 1 between `start` and `start + duration`. */+export function drawOnKeys(+ start: number,+ duration: number,+ ease = "power2.inOut",+): KeyframeTuple[] {+ return [+ [start, 0],+ [start + Math.max(1, duration), 1, ease],+ ];+}++/**+ * Perturb points with seeded, low-frequency noise: neighbouring points move+ * together, so lines bend instead of jittering.+ */+export function wobblePoints(+ points: readonly Vec2[],+ { wobble = 0, seed = 1 }: HandOptions = {},+ variant = 0,+): Vec2[] {+ if (wobble <= 0 || points.length === 0)+ return points.map((p) => [p[0], p[1]]);+ const r = hashRng(seed, `wobble:${variant}`);+ // A few control offsets, interpolated across the stroke.+ const controls = Math.max(2, Math.min(8, Math.ceil(points.length / 6)));+ const ox = Array.from({ length: controls }, () => r.spread(wobble));+ const oy = Array.from({ length: controls }, () => r.spread(wobble));+ const sample = (arr: number[], t: number) => {+ const f = t * (arr.length - 1);+ const i = Math.min(arr.length - 2, Math.floor(f));+ const k = f - i;+ const s = k * k * (3 - 2 * k);+ return arr[i]! * (1 - s) + arr[i + 1]! * s;+ };+ return points.map((p, i) => {+ const t = points.length === 1 ? 0 : i / (points.length - 1);+ return [p[0] + sample(ox, t), p[1] + sample(oy, t)];+ });+}++/** An ellipse around `rect` (+ padding); hand-drawn ellipses overshoot their start. */+export function ellipsePath(+ rect: Rect,+ {+ padding = 0,+ wobble = 0,+ seed = 1,+ }: HandOptions & { padding?: number } = {},+ variant = 0,+): string {+ const cx = rect.x + rect.width / 2;+ const cy = rect.y + rect.height / 2;+ const rx = rect.width / 2 + padding;+ const ry = rect.height / 2 + padding;+ const r = hashRng(seed, `ellipse:${variant}`);+ const start = wobble > 0 ? -Math.PI * 0.6 + r.spread(0.3) : 0;+ const sweep = wobble > 0 ? Math.PI * 2 * 1.08 : Math.PI * 2;+ const steps = 64;+ const points: Vec2[] = [];+ for (let i = 0; i <= steps; i++) {+ const a = start + (sweep * i) / steps;+ // Hand-drawn loops spiral slightly so the overshoot doesn't retrace.+ const grow = wobble > 0 ? 1 + (i / steps - 0.5) * 0.06 : 1;+ points.push([cx + Math.cos(a) * rx * grow, cy + Math.sin(a) * ry * grow]);+ }+ return toPathData(+ wobblePoints(points, { wobble, seed }, variant),+ wobble <= 0,+ );+}++/** A rectangle around `rect` (+ padding). */+export function boxPath(+ rect: Rect,+ {+ padding = 0,+ wobble = 0,+ seed = 1,+ }: HandOptions & { padding?: number } = {},+ variant = 0,+): string {+ const x0 = rect.x - padding;+ const y0 = rect.y - padding;+ const x1 = rect.x + rect.width + padding;+ const y1 = rect.y + rect.height + padding;+ const corners: Vec2[] = [+ [x0, y0],+ [x1, y0],+ [x1, y1],+ [x0, y1],+ [x0, y0],+ ];+ if (wobble <= 0) return toPathData(corners.slice(0, 4), true);+ const points: Vec2[] = [];+ for (let i = 0; i < 4; i++) {+ const a = corners[i]!;+ const b = corners[i + 1]!;+ for (let s = 0; s < 8; s++) {+ const t = s / 8;+ points.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);+ }+ }+ // Overshoot past the first corner, the way a pen closes a box.+ points.push([x0 + (x1 - x0) * 0.08, y0]);+ return toPathData(wobblePoints(points, { wobble, seed }, variant));+}++/** A horizontal stroke from `from` to `to`. */+export function linePath(+ from: Vec2,+ to: Vec2,+ { wobble = 0, seed = 1 }: HandOptions = {},+ variant = 0,+): string {+ const steps = wobble > 0 ? 16 : 1;+ const points: Vec2[] = [];+ for (let i = 0; i <= steps; i++) {+ const t = i / steps;+ points.push([+ from[0] + (to[0] - from[0]) * t,+ from[1] + (to[1] - from[1]) * t,+ ]);+ }+ return toPathData(wobblePoints(points, { wobble, seed }, variant));+}++/** A wavy line from `from` to `to`, `waves` crests of `amplitude` px. */+export function squigglePath(+ from: Vec2,+ to: Vec2,+ {+ amplitude = 6,+ waves,+ wobble = 0,+ seed = 1,+ }: HandOptions & { amplitude?: number; waves?: number } = {},+ variant = 0,+): string {+ const length = Math.hypot(to[0] - from[0], to[1] - from[1]);+ const n = waves ?? Math.max(2, Math.round(length / 28));+ const angle = Math.atan2(to[1] - from[1], to[0] - from[0]);+ const nx = -Math.sin(angle);+ const ny = Math.cos(angle);+ const steps = n * 8;+ const points: Vec2[] = [];+ for (let i = 0; i <= steps; i++) {+ const t = i / steps;+ const off = Math.sin(t * n * Math.PI * 2) * amplitude;+ points.push([+ from[0] + (to[0] - from[0]) * t + nx * off,+ from[1] + (to[1] - from[1]) * t + ny * off,+ ]);+ }+ return toPathData(wobblePoints(points, { wobble, seed }, variant));+}++export type ArrowCurve = "straight" | "arc" | "swoop";++export interface ArrowGeometry {+ /** The shaft, drawn from `from` to just before `to`. */+ shaft: string;+ /** The head, two strokes meeting at `to`. */+ head: string;+}++/** An arrow from `from` to `to` with a separate head path. */+export function arrowPaths(+ from: Vec2,+ to: Vec2,+ {+ curve = "arc",+ headSize = 18,+ wobble = 0,+ seed = 1,+ }: HandOptions & { curve?: ArrowCurve; headSize?: number } = {},+ variant = 0,+): ArrowGeometry {+ const dx = to[0] - from[0];+ const dy = to[1] - from[1];+ const length = Math.hypot(dx, dy) || 1;+ const nx = -dy / length;+ const ny = dx / length;+ const bend = curve === "straight" ? 0 : curve === "arc" ? 0.18 : 0.35;+ const controls: Vec2[] =+ curve === "swoop"+ ? [+ from,+ [+ from[0] + dx * 0.3 + nx * length * bend,+ from[1] + dy * 0.3 + ny * length * bend,+ ],+ [+ from[0] + dx * 0.75 - nx * length * bend * 0.4,+ from[1] + dy * 0.75 - ny * length * bend * 0.4,+ ],+ to,+ ]+ : [+ from,+ [+ from[0] + dx * 0.5 + nx * length * bend,+ from[1] + dy * 0.5 + ny * length * bend,+ ],+ to,+ ];+ const points = bend === 0 ? [from, to] : catmullRom(controls, 12);+ const wobbled = wobblePoints(points, { wobble, seed }, variant);+ const tail = wobbled[wobbled.length - 2] ?? from;+ const angle = Math.atan2(to[1] - tail[1], to[0] - tail[0]);+ const wing = (side: 1 | -1): Vec2 => [+ to[0] - Math.cos(angle + side * 0.5) * headSize,+ to[1] - Math.sin(angle + side * 0.5) * headSize,+ ];+ const left = wing(1);+ const right = wing(-1);+ return {+ shaft: toPathData(wobbled),+ head: `${toPathData([left, to])} ${toPathData([to, right]).replace(/^M/, "L")}`,+ };+}++/**+ * Hand-drawn "boil": `d` keys that switch between `variants` poses every+ * `every` frames with hold interpolation, from `start` to `end`.+ * `makePath(variant)` must be deterministic for a variant index.+ */+export function boilKeys(+ makePath: (variant: number) => string,+ {+ start,+ end,+ every,+ variants = 3,+ }: { start: number; end: number; every: number; variants?: number },+): KeyframeTuple[] {+ const poses = Array.from({ length: Math.max(1, variants) }, (_, i) =>+ makePath(i),+ );+ if (every <= 0 || poses.length === 1) return [[start, poses[0]!]];+ const keys: KeyframeTuple[] = [];+ let i = 0;+ for (let f = start; f <= end; f += every) {+ keys.push([f, poses[i % poses.length]!, "hold"]);+ i++;+ }+ return keys;+}diff --git a/packages/components/src/core/ease.test.ts b/packages/components/src/core/ease.test.tsnew file mode 100644index 00000000..c22df65b--- /dev/null+++ b/packages/components/src/core/ease.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from "vitest";+import { ease, evaluateEase } from "./ease.js";++describe("ease", () => {+ it("hits the endpoints for every base and direction", () => {+ for (const base of [+ "none",+ "power1",+ "power2",+ "power3",+ "sine",+ "circ",+ "expo",+ "back",+ "elastic",+ "bounce",+ "cubic",+ ]) {+ for (const dir of ["in", "out", "inOut"]) {+ const f = ease(`${base}.${dir}`);+ expect(f(0)).toBeCloseTo(0, 5);+ expect(f(1)).toBeCloseTo(1, 5);+ }+ }+ });++ it("matches known values", () => {+ expect(evaluateEase("power2.out", 0.5)).toBeCloseTo(0.875, 6);+ expect(evaluateEase("power2.in", 0.5)).toBeCloseTo(0.125, 6);+ expect(evaluateEase("linear", 0.3)).toBeCloseTo(0.3, 6);+ expect(evaluateEase(undefined, 0.3)).toBeCloseTo(0.3, 6);+ });++ it("overshoots for back.out and holds for hold", () => {+ const back = ease("back.out(1.7)");+ const peak = Math.max(+ ...Array.from({ length: 101 }, (_, i) => back(i / 100)),+ );+ expect(peak).toBeGreaterThan(1.05);+ expect(evaluateEase("hold", 0.99)).toBe(0);+ expect(evaluateEase("hold", 1)).toBe(1);+ });++ it("rejects names the keyframe schema doesn't accept", () => {+ expect(() => ease("power4.out")).toThrow(/Unknown ease/);+ expect(() => ease("power2.sideways")).toThrow(/direction/);+ });+});diff --git a/packages/components/src/core/ease.ts b/packages/components/src/core/ease.tsnew file mode 100644index 00000000..62abfad5--- /dev/null+++ b/packages/components/src/core/ease.ts@@ -0,0 +1,93 @@+/**+ * Ease evaluation for planning and baking. Accepts exactly the eases the+ * keyframe schema accepts (`"power2.out"`, `"back.out(1.7)"`,+ * `"elastic.out(1, 0.3)"`, `"hold"` …; `"spring"` is renderer-only), so a+ * curve a component bakes looks like the same ease keyed directly.+ */++export type EaseFn = (t: number) => number;++const clamp01 = (t: number) => (t < 0 ? 0 : t > 1 ? 1 : t);++/** The "in" form of each base curve; `out` and `inOut` derive from it. */+const BASES: Record<string, (params: number[]) => EaseFn> = {+ none: () => (x) => x,+ linear: () => (x) => x,+ power1: () => (x) => x * x,+ power2: () => (x) => x * x * x,+ cubic: () => (x) => x * x * x,+ power3: () => (x) => x ** 4,+ sine: () => (x) => 1 - Math.cos((x * Math.PI) / 2),+ circ: () => (x) => 1 - Math.sqrt(Math.max(0, 1 - x * x)),+ expo: () => (x) => (x === 0 ? 0 : 2 ** (10 * (x - 1))),+ back:+ ([overshoot = 1.70158]) =>+ (x) =>+ (overshoot + 1) * x * x * x - overshoot * x * x,+ elastic: ([amplitude = 1, period = 0.3]) => {+ const a = Math.max(1, amplitude);+ const s = (period / (2 * Math.PI)) * Math.asin(1 / a);+ return (x) =>+ x === 0 || x === 1+ ? x+ : -(+ a *+ 2 ** (10 * (x - 1)) *+ Math.sin(((x - 1 - s) * (2 * Math.PI)) / period)+ );+ },+ bounce: () => (x) => 1 - bounceOut(1 - x),+};++function bounceOut(x: number): number {+ const n1 = 7.5625;+ const d1 = 2.75;+ if (x < 1 / d1) return n1 * x * x;+ if (x < 2 / d1) return n1 * (x - 1.5 / d1) ** 2 + 0.75;+ if (x < 2.5 / d1) return n1 * (x - 2.25 / d1) ** 2 + 0.9375;+ return n1 * (x - 2.625 / d1) ** 2 + 0.984375;+}++const cache = new Map<string, EaseFn>();++/** Parse an ease name into a function on [0, 1]. Unknown names throw. */+export function ease(name: string | undefined): EaseFn {+ if (!name) return (t) => clamp01(t);+ const cached = cache.get(name);+ if (cached) return cached;++ const match = name+ .trim()+ .match(/^([a-zA-Z0-9]+)(?:\.([a-zA-Z]+))?(?:\(([^)]*)\))?$/);+ if (!match) throw new Error(`Unknown ease "${name}"`);+ const base = (match[1] ?? "").toLowerCase();+ const dir = (match[2] ?? "out").toLowerCase();+ const params = (match[3] ?? "")+ .split(",")+ .map((s) => Number.parseFloat(s))+ .filter((n) => !Number.isNaN(n));++ let fn: EaseFn;+ if (base === "hold") {+ fn = (t) => (t >= 1 ? 1 : 0);+ } else {+ const make = BASES[base];+ if (!make) throw new Error(`Unknown ease "${name}"`);+ const easeIn = make(params);+ if (dir === "in") fn = (t) => easeIn(clamp01(t));+ else if (dir === "inout")+ fn = (t) => {+ const s = clamp01(t);+ return s < 0.5 ? easeIn(s * 2) / 2 : 1 - easeIn((1 - s) * 2) / 2;+ };+ else if (dir === "out") fn = (t) => 1 - easeIn(1 - clamp01(t));+ else throw new Error(`Unknown ease direction in "${name}"`);+ }+ cache.set(name, fn);+ return fn;+}++/** `ease(name)(t)` in one call. */+export function evaluateEase(name: string | undefined, t: number): number {+ return ease(name)(t);+}diff --git a/packages/components/src/core/host.ts b/packages/components/src/core/host.tsnew file mode 100644index 00000000..46321da5--- /dev/null+++ b/packages/components/src/core/host.ts@@ -0,0 +1,36 @@+/**+ * The host: what framefields injects into components. framefields bundles+ * this package, so components can't import from it without a cycle; instead+ * framefields binds each component to an object implementing `Host`.+ *+ * Types here are structural on purpose: framefields' real `AnimatableNode`+ * satisfies `Animatable`, and its binding restores the full types for users.+ */+import type {+ BoxNode,+ FlexNode,+ ShapeNode,+ ShapeType,+ TextNode,+} from "@framefields/compositions/program";+import type { MeasureFn } from "./text.js";++/** The part of framefields' `AnimatableNode` components rely on. */+export interface AnimatableMethods {+ animate(...anims: unknown[]): unknown;+}++export type Animatable<T> = T & AnimatableMethods;++export interface Host {+ box(options: Partial<BoxNode>): Animatable<BoxNode>;+ flex(options: Partial<FlexNode>): Animatable<FlexNode>;+ text(content: string, options?: Partial<TextNode>): Animatable<TextNode>;+ shape(type: ShapeType, options?: Partial<ShapeNode>): Animatable<ShapeNode>;+ /** `FontManager.measure`. */+ measure: MeasureFn;+ /** Registered font families. */+ fonts(): readonly string[];+ /** A default id: stable per run (a counter per prefix), like `Layer.*` ids. */+ autoId(prefix: string): string;+}diff --git a/packages/components/src/core/meta.ts b/packages/components/src/core/meta.tsnew file mode 100644index 00000000..3caea4ab--- /dev/null+++ b/packages/components/src/core/meta.ts@@ -0,0 +1,33 @@+/**+ * Component metadata: the discovery surface for docs and coding agents.+ * Each component's `meta.ts` default-exports one; `scripts/build-meta.ts`+ * collects them into `components.json`.+ */++export interface ComponentMeta {+ /** PascalCase export name. */+ name: string;+ /** One sentence: what it is and when to use it. */+ summary: string;+ tags: readonly string[];+ /** Named parts `customize` and `part()` expose (besides `root`, `stage`). */+ parts: readonly string[];+ /** Cue names on `node.cues`. */+ cues: readonly string[];+ /** A minimal, runnable call. */+ example: string;+ /** Spec milestone that introduced it. */+ since: string;+}++export function defineMeta(meta: ComponentMeta): ComponentMeta {+ if (!/^[A-Z][A-Za-z0-9]+$/.test(meta.name)) {+ throw new Error(`Component name must be PascalCase: "${meta.name}"`);+ }+ if (meta.summary.length > 200) {+ throw new Error(+ `${meta.name}: summary must be one sentence (≤ 200 chars).`,+ );+ }+ return meta;+}diff --git a/packages/components/src/core/motion.test.ts b/packages/components/src/core/motion.test.tsnew file mode 100644index 00000000..1ebcc832--- /dev/null+++ b/packages/components/src/core/motion.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from "vitest";+import { enterAnimation, exitAnimation, resolveMotion } from "./motion.js";+import { themes } from "./theme.js";++const keysOf = (+ anim: {+ tracks: Array<{+ prop: string;+ keyframes: Array<{ frame: number; value: unknown }>;+ }>;+ },+ prop: string,+) =>+ anim.tracks+ .find((t) => t.prop === prop)+ ?.keyframes.map((k) => [k.frame, k.value]);++describe("motion presets", () => {+ it("resolves defaults from the theme and fps", () => {+ const m = resolveMotion("rise", "enter", themes.graphite, 60);+ expect(m).toMatchObject({+ preset: "rise",+ duration: 32,+ ease: "expo.out",+ distance: 40,+ });+ expect(resolveMotion("pop", "enter", themes.graphite)?.ease).toBe(+ themes.graphite.motion.ease.snap,+ );+ expect(resolveMotion(false, "enter", themes.graphite)).toBeNull();+ expect(resolveMotion("none", "enter", themes.graphite)).toBeNull();+ expect(() =>+ resolveMotion("spin" as never, "enter", themes.graphite),+ ).toThrow(/Unknown motion preset/);+ });++ it("enters from an offset and settles at zero", () => {+ const m = resolveMotion(+ { preset: "rise", duration: 10, delay: 2 },+ "enter",+ themes.graphite,+ )!;+ const anim = enterAnimation(m);+ expect(keysOf(anim, "y")).toEqual([+ [2, 40],+ [12, 0],+ ]);+ expect(keysOf(anim, "opacity")).toEqual([+ [2, 0],+ [12, 1],+ ]);+ });++ it("exits the way it would have entered", () => {+ const m = resolveMotion(+ { preset: "rise", duration: 10 },+ "exit",+ themes.graphite,+ )!;+ const anim = exitAnimation(m, 100);+ expect(keysOf(anim, "y")).toEqual([+ [90, 0],+ [100, -40],+ ]);+ const slide = resolveMotion(+ { preset: "slide-left", duration: 10 },+ "exit",+ themes.graphite,+ )!;+ expect(keysOf(exitAnimation(slide, 50), "x")).toEqual([+ [40, 0],+ [50, -120],+ ]);+ });+});diff --git a/packages/components/src/core/motion.ts b/packages/components/src/core/motion.tsnew file mode 100644index 00000000..a78b5c4d--- /dev/null+++ b/packages/components/src/core/motion.ts@@ -0,0 +1,203 @@+/**+ * Named entrances and exits shared by every component's `enter` / `exit`.+ * A preset becomes plain keyframes on the component's `stage` part, which is+ * pinned at (0, 0) inside the root, so offsets never fight the root's layout.+ */+import { LayerAnimation } from "@framefields/compositions/program";+import type { Theme } from "./theme.js";+import { scaleFrames } from "./timing.js";++export type MotionPresetName =+ | "none"+ | "fade"+ | "rise"+ | "drop"+ | "scale"+ | "pop"+ | "slide-left"+ | "slide-right"+ | "slide-up"+ | "slide-down"+ | "tilt";++export const MOTION_PRESETS: readonly MotionPresetName[] = [+ "none",+ "fade",+ "rise",+ "drop",+ "scale",+ "pop",+ "slide-left",+ "slide-right",+ "slide-up",+ "slide-down",+ "tilt",+];++export interface MotionOptions {+ /** Frames; default the theme's `base` speed. */+ duration?: number;+ ease?: string;+ /** Travel in px; default 40 (rise / drop) or 120 (slides) × theme.scale. */+ distance?: number;+ /** Frames to wait after the window starts (enter) or before it ends (exit). */+ delay?: number;+}++export type MotionPreset =+ | MotionPresetName+ | ({ preset: MotionPresetName } & MotionOptions);++export interface ResolvedMotion {+ preset: MotionPresetName;+ duration: number;+ ease: string;+ distance: number;+ delay: number;+}++/** Normalise a preset (or `false`) against a theme and fps. */+export function resolveMotion(+ input: MotionPreset | false | undefined,+ kind: "enter" | "exit",+ theme: Theme,+ fps = 30,+): ResolvedMotion | null {+ if (input === false || input === undefined) return null;+ const o = typeof input === "string" ? { preset: input } : input;+ if (o.preset === "none") return null;+ if (!MOTION_PRESETS.includes(o.preset)) {+ throw new Error(+ `Unknown motion preset "${o.preset}". Use one of: ${MOTION_PRESETS.join(", ")}.`,+ );+ }+ return {+ preset: o.preset,+ duration: Math.max(+ 1,+ Math.round(o.duration ?? scaleFrames(theme.motion.speed.base, fps)),+ ),+ ease:+ o.ease ??+ (o.preset === "pop"+ ? theme.motion.ease.snap+ : kind === "enter"+ ? theme.motion.ease.enter+ : theme.motion.ease.exit),+ distance:+ o.distance ?? (o.preset.startsWith("slide-") ? 120 : 40) * theme.scale,+ delay: Math.max(0, Math.round(o.delay ?? 0)),+ };+}++/** Offset (dx, dy) a translating preset starts from (enter) or ends at (exit). */+function offsetOf(m: ResolvedMotion): [number, number] {+ switch (m.preset) {+ case "rise":+ case "slide-up":+ return [0, m.distance];+ case "drop":+ case "slide-down":+ return [0, -m.distance];+ case "slide-left":+ return [m.distance, 0];+ case "slide-right":+ return [-m.distance, 0];+ default:+ return [0, 0];+ }+}++/**+ * Keyframes for an entrance that ends settled at frame `at + delay + duration`+ * (local frames of the animated node).+ */+export function enterAnimation(m: ResolvedMotion, at = 0): LayerAnimation {+ const s = at + m.delay;+ const e = s + m.duration;+ const anim = LayerAnimation.create();+ anim.keys("opacity", [+ [s, 0],+ [e, 1, m.ease],+ ]);+ const [dx, dy] = offsetOf(m);+ if (dx !== 0)+ anim.keys("x", [+ [s, dx],+ [e, 0, m.ease],+ ]);+ if (dy !== 0)+ anim.keys("y", [+ [s, dy],+ [e, 0, m.ease],+ ]);+ if (m.preset === "scale")+ anim.keys("scale", [+ [s, 0.92],+ [e, 1, m.ease],+ ]);+ if (m.preset === "pop")+ anim.keys("scale", [+ [s, 0.6],+ [e, 1, m.ease],+ ]);+ if (m.preset === "tilt") {+ anim.keys("perspective", [[s, 1200]]);+ anim.keys("rotateX", [+ [s, 28],+ [e, 0, m.ease],+ ]);+ anim.keys("translateZ", [+ [s, -160],+ [e, 0, m.ease],+ ]);+ }+ return anim;+}++/**+ * Keyframes for an exit that finishes at local frame `end - delay`.+ */+export function exitAnimation(m: ResolvedMotion, end: number): LayerAnimation {+ const e = end - m.delay;+ const s = Math.max(0, e - m.duration);+ const anim = LayerAnimation.create();+ anim.keys("opacity", [+ [s, 1],+ [e, 0, m.ease],+ ]);+ const [dx, dy] = offsetOf(m);+ // Exits leave the way entrances arrive: rise exits upward, and so on.+ if (dx !== 0)+ anim.keys("x", [+ [s, 0],+ [e, -dx, m.ease],+ ]);+ if (dy !== 0)+ anim.keys("y", [+ [s, 0],+ [e, -dy, m.ease],+ ]);+ if (m.preset === "scale")+ anim.keys("scale", [+ [s, 1],+ [e, 0.92, m.ease],+ ]);+ if (m.preset === "pop")+ anim.keys("scale", [+ [s, 1],+ [e, 0.6, m.ease],+ ]);+ if (m.preset === "tilt") {+ anim.keys("perspective", [[s, 1200]]);+ anim.keys("rotateX", [+ [s, 0],+ [e, -28, m.ease],+ ]);+ anim.keys("translateZ", [+ [s, 0],+ [e, -160, m.ease],+ ]);+ }+ return anim;+}diff --git a/packages/components/src/core/path.test.ts b/packages/components/src/core/path.test.tsnew file mode 100644index 00000000..792d9f27--- /dev/null+++ b/packages/components/src/core/path.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";+import { arcPath, catmullRom, toPathData } from "./path.js";++describe("path", () => {+ it("passes through every control point", () => {+ const pts: [number, number][] = [+ [0, 0],+ [100, 50],+ [200, 0],+ [300, 80],+ ];+ const curve = catmullRom(pts, 8);+ for (const p of pts) {+ expect(+ curve.some((c) => Math.hypot(c[0] - p[0], c[1] - p[1]) < 1e-6),+ ).toBe(true);+ }+ });++ it("samples by arc length", () => {+ const path = arcPath([+ [0, 0],+ [100, 0],+ [100, 100],+ ]);+ expect(path.length).toBe(200);+ expect(path.at(0.25)).toEqual([50, 0]);+ expect(path.at(0.75)).toEqual([100, 50]);+ expect(path.at(2)).toEqual([100, 100]);+ expect(path.angleAt(0.1)).toBeCloseTo(0);+ expect(path.angleAt(0.9)).toBeCloseTo(Math.PI / 2);+ });++ it("writes compact path data", () => {+ expect(+ toPathData(+ [+ [0, 0],+ [1.234, 5],+ ],+ true,+ ),+ ).toBe("M0 0 L1.23 5 Z");+ });+});diff --git a/packages/components/src/core/path.ts b/packages/components/src/core/path.tsnew file mode 100644index 00000000..40460865--- /dev/null+++ b/packages/components/src/core/path.ts@@ -0,0 +1,114 @@+/**+ * 2D path math: smooth curves through points, arc-length sampling, and SVG+ * path strings. Used for pointer travel, camera moves and drawn marks.+ */++export type Vec2 = [x: number, y: number];++export const dist = (a: Vec2, b: Vec2): number =>+ Math.hypot(b[0] - a[0], b[1] - a[1]);+export const lerp2 = (a: Vec2, b: Vec2, t: number): Vec2 => [+ a[0] + (b[0] - a[0]) * t,+ a[1] + (b[1] - a[1]) * t,+];++/**+ * Centripetal Catmull-Rom through `points`, flattened to a polyline with+ * `steps` samples per segment. Centripetal (alpha 0.5) never loops or cusps+ * between close points, which matters for pointer paths.+ */+export function catmullRom(points: readonly Vec2[], steps = 16): Vec2[] {+ if (points.length < 2) return points.map((p) => [p[0], p[1]] as Vec2);+ const out: Vec2[] = [[points[0]![0], points[0]![1]]];+ for (let i = 0; i < points.length - 1; i++) {+ const p0 = points[Math.max(0, i - 1)]!;+ const p1 = points[i]!;+ const p2 = points[i + 1]!;+ const p3 = points[Math.min(points.length - 1, i + 2)]!;+ for (let s = 1; s <= steps; s++) {+ out.push(catmullRomPoint(p0, p1, p2, p3, s / steps));+ }+ }+ return out;+}++function catmullRomPoint(+ p0: Vec2,+ p1: Vec2,+ p2: Vec2,+ p3: Vec2,+ t: number,+): Vec2 {+ const knot = (a: Vec2, b: Vec2) => Math.max(1e-6, Math.sqrt(dist(a, b)));+ const t0 = 0;+ const t1 = t0 + knot(p0, p1);+ const t2 = t1 + knot(p1, p2);+ const t3 = t2 + knot(p2, p3);+ const u = t1 + (t2 - t1) * t;+ const mix = (a: Vec2, b: Vec2, ta: number, tb: number): Vec2 =>+ tb === ta ? a : lerp2(a, b, (u - ta) / (tb - ta));+ const a1 = mix(p0, p1, t0, t1);+ const a2 = mix(p1, p2, t1, t2);+ const a3 = mix(p2, p3, t2, t3);+ const b1 = mix(a1, a2, t0, t2);+ const b2 = mix(a2, a3, t1, t3);+ return mix(b1, b2, t1, t2);+}++/** A polyline with a cumulative arc-length table, sampled by distance. */+export interface ArcPath {+ readonly points: readonly Vec2[];+ readonly length: number;+ /** Point at `u` ∈ [0, 1] of the total length. */+ at(u: number): Vec2;+ /** Unit tangent direction (radians) at `u`. */+ angleAt(u: number): number;+}++export function arcPath(points: readonly Vec2[]): ArcPath {+ if (points.length === 0) throw new Error("arcPath: no points");+ const cumulative = [0];+ for (let i = 1; i < points.length; i++) {+ cumulative.push(cumulative[i - 1]! + dist(points[i - 1]!, points[i]!));+ }+ const length = cumulative[cumulative.length - 1]!;+ const segmentAt = (u: number): [number, number] => {+ if (points.length === 1 || length === 0) return [0, 0];+ const d = Math.min(1, Math.max(0, u)) * length;+ let lo = 0;+ let hi = cumulative.length - 1;+ while (hi - lo > 1) {+ const mid = (lo + hi) >> 1;+ if (cumulative[mid]! <= d) lo = mid;+ else hi = mid;+ }+ const seg = cumulative[hi]! - cumulative[lo]!;+ return [lo, seg > 0 ? (d - cumulative[lo]!) / seg : 0];+ };+ return {+ points,+ length,+ at(u) {+ const [i, t] = segmentAt(u);+ if (points.length === 1) return [points[0]![0], points[0]![1]];+ return lerp2(points[i]!, points[Math.min(i + 1, points.length - 1)]!, t);+ },+ angleAt(u) {+ const [i] = segmentAt(u);+ const a = points[Math.min(i, points.length - 2)] ?? points[0]!;+ const b = points[Math.min(i + 1, points.length - 1)]!;+ return Math.atan2(b[1] - a[1], b[0] - a[0]);+ },+ };+}++/** SVG path data for a polyline (optionally closed). Rounded to 0.01 px. */+export function toPathData(points: readonly Vec2[], closed = false): string {+ if (points.length === 0) return "";+ const r = (n: number) => Math.round(n * 100) / 100;+ const [first, ...rest] = points;+ const parts = [`M${r(first![0])} ${r(first![1])}`];+ for (const p of rest) parts.push(`L${r(p[0])} ${r(p[1])}`);+ if (closed) parts.push("Z");+ return parts.join(" ");+}diff --git a/packages/components/src/core/rng.test.ts b/packages/components/src/core/rng.test.tsnew file mode 100644index 00000000..22476086--- /dev/null+++ b/packages/components/src/core/rng.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest";+import { hashRng, hashString, rng } from "./rng.js";++describe("rng", () => {+ it("is deterministic per seed", () => {+ const a = rng(42);+ const b = rng(42);+ const seqA = Array.from({ length: 5 }, () => a.next());+ const seqB = Array.from({ length: 5 }, () => b.next());+ expect(seqA).toEqual(seqB);+ expect(rng(43).next()).not.toBe(seqA[0]);+ });++ it("stays in range and is roughly uniform", () => {+ const r = rng(7);+ const buckets = new Array(10).fill(0);+ for (let i = 0; i < 10000; i++) {+ const v = r.next();+ expect(v).toBeGreaterThanOrEqual(0);+ expect(v).toBeLessThan(1);+ buckets[Math.floor(v * 10)]++;+ }+ for (const b of buckets) expect(b).toBeGreaterThan(850);+ const ints = new Set(Array.from({ length: 200 }, () => r.int(1, 3)));+ expect([...ints].sort()).toEqual([1, 2, 3]);+ });++ it("keys streams independently", () => {+ expect(hashRng(1, "word-3").next()).toBe(hashRng(1, "word-3").next());+ expect(hashRng(1, "word-3").next()).not.toBe(hashRng(1, "word-4").next());+ expect(hashRng(1, "a").next()).not.toBe(hashRng(2, "a").next());+ expect(hashString("abc")).toBe(hashString("abc"));+ });+});diff --git a/packages/components/src/core/rng.ts b/packages/components/src/core/rng.tsnew file mode 100644index 00000000..9f329543--- /dev/null+++ b/packages/components/src/core/rng.ts@@ -0,0 +1,60 @@+/**+ * Seeded randomness. Components never call `Math.random`: every random choice+ * derives from the `seed` prop, so the same props give the same frames.+ */++export interface Rng {+ /** Uniform in [0, 1). */+ next(): number;+ /** Uniform in [min, max). */+ range(min: number, max: number): number;+ /** Integer in [min, max] (inclusive). */+ int(min: number, max: number): number;+ /** One element of `items`. */+ pick<T>(items: readonly T[]): T;+ /** Uniform in [-amount, amount). */+ spread(amount: number): number;+}++/** splitmix32: tiny, fast, and well distributed for animation jitter. */+export function rng(seed: number): Rng {+ let state = seed >>> 0;+ const next = (): number => {+ state = (state + 0x9e3779b9) >>> 0;+ let z = state;+ z = Math.imul(z ^ (z >>> 16), 0x85ebca6b) >>> 0;+ z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35) >>> 0;+ z = (z ^ (z >>> 16)) >>> 0;+ return z / 0x100000000;+ };+ return {+ next,+ range: (min, max) => min + (max - min) * next(),+ int: (min, max) => min + Math.floor(next() * (max - min + 1)),+ pick: (items) => {+ if (items.length === 0) throw new Error("rng.pick: empty list");+ return items[Math.floor(next() * items.length)] as never;+ },+ spread: (amount) => (next() * 2 - 1) * amount,+ };+}++/** FNV-1a 32-bit hash of a string. */+export function hashString(value: string): number {+ let h = 0x811c9dc5;+ for (let i = 0; i < value.length; i++) {+ h ^= value.charCodeAt(i);+ h = Math.imul(h, 0x01000193) >>> 0;+ }+ return h >>> 0;+}++/**+ * A stream keyed by `key` under `seed`: the n-th word of a caption gets the+ * same jitter whether or not earlier words change.+ */+export function hashRng(seed: number, key: string | number): Rng {+ return rng(+ (Math.imul(seed >>> 0, 0x9e3779b1) ^ hashString(String(key))) >>> 0,+ );+}diff --git a/packages/components/src/core/targets.test.ts b/packages/components/src/core/targets.test.tsnew file mode 100644index 00000000..19cdfc05--- /dev/null+++ b/packages/components/src/core/targets.test.ts@@ -0,0 +1,124 @@+import { describe, expect, it } from "vitest";+import { fakeMeasure } from "../test/fake-host.js";+import {+ anchorPoint,+ boundsOf,+ resolveTarget,+ targetPoint,+} from "./targets.js";+import { findRange, rangeRects, wordRanges } from "./text.js";++const ctx = { measure: fakeMeasure };++describe("text geometry", () => {+ it("finds words and ranges", () => {+ expect(+ wordRanges(" ship it fast").map((w) => [w.text, w.start, w.end]),+ ).toEqual([+ ["ship", 2, 6],+ ["it", 7, 9],+ ["fast", 11, 15],+ ]);+ expect(findRange("a b a b", "b", 1)).toEqual([6, 7]);+ expect(findRange("price 120%", /\d+%/)).toEqual([6, 10]);+ expect(findRange("abc", "z")).toBeNull();+ });++ it("returns one rect per line a range spans", () => {+ // 20px font → 10px glyphs, 24px lines; width 100 fits 10 glyphs,+ // so "brave" wraps to line 2.+ const text = "hello brave new world";+ const options = { fontFamily: "Inter", fontSize: 20, width: 100 };+ const m = fakeMeasure(text, options);+ const rects = rangeRects(m, 0, 11, options); // "hello brave"+ expect(rects).toEqual([+ { x: 0, y: 0, width: 50, height: 24 },+ { x: 0, y: 24, width: 50, height: 24 },+ ]);+ });++ it("shifts centred lines", () => {+ const options = {+ fontFamily: "Inter",+ fontSize: 20,+ width: 200,+ align: "center" as const,+ };+ const m = fakeMeasure("abcd", options);+ expect(rangeRects(m, 0, 4, options)[0]).toMatchObject({ x: 80, width: 40 });+ });+});++describe("targets", () => {+ it("resolves points and rects", () => {+ expect(resolveTarget([10, 20])).toEqual({+ kind: "static",+ anchor: "center",+ rects: [{ x: 10, y: 20, width: 0, height: 0 }],+ });+ const r = { x: 0, y: 0, width: 10, height: 10 };+ expect(targetPoint(resolveTarget(r))).toEqual([5, 5]);+ });++ it("resolves absolute nodes and refuses flowed ones", () => {+ const node = { id: "btn", x: 100, y: 50, width: 80, height: 40 };+ expect(targetPoint(resolveTarget({ node, anchor: "top-left" }))).toEqual([+ 100, 50,+ ]);+ expect(() => resolveTarget({ node: { id: "flow" } })).toThrow(+ /absolute geometry/,+ );+ });++ it("resolves text matches to glyph boxes in composition space", () => {+ const text = {+ id: "t",+ x: 200,+ y: 300,+ text: "Ship faster today",+ fontFamily: "Inter",+ fontSize: 20,+ };+ const resolved = resolveTarget({ text, match: "faster" }, ctx);+ expect(resolved.kind).toBe("static");+ if (resolved.kind !== "static") return;+ expect(resolved.rects).toEqual([{ x: 250, y: 300, width: 60, height: 24 }]);+ expect(targetPoint(resolved, 0, true)).toEqual([250, 312]);+ expect(() => resolveTarget({ text, match: "slower" }, ctx)).toThrow(+ /not found/,+ );+ });++ it("samples tracked objects per frame", () => {+ const sig = (f: (frame: number) => number) => ({+ get: (c?: { frame: number }) => f(c?.frame ?? 0),+ });+ const track = {+ x: sig((f) => f * 2),+ y: sig(() => 10),+ width: sig(() => 20),+ height: sig(() => 20),+ };+ const resolved = resolveTarget({ track });+ expect(resolved.kind).toBe("dynamic");+ expect(targetPoint(resolved, 5)).toEqual([20, 20]);+ expect(+ targetPoint(+ resolveTarget((f) => [f, f]),+ 7,+ ),+ ).toEqual([7, 7]);+ });++ it("computes bounds and anchors", () => {+ expect(+ boundsOf([+ { x: 0, y: 0, width: 10, height: 10 },+ { x: 20, y: 5, width: 5, height: 10 },+ ]),+ ).toEqual({ x: 0, y: 0, width: 25, height: 15 });+ expect(+ anchorPoint({ x: 0, y: 0, width: 10, height: 20 }, "bottom-right"),+ ).toEqual([10, 20]);+ });+});diff --git a/packages/components/src/core/targets.ts b/packages/components/src/core/targets.tsnew file mode 100644index 00000000..43980688--- /dev/null+++ b/packages/components/src/core/targets.ts@@ -0,0 +1,318 @@+/**+ * Targets: what a pointer lands on, an annotation marks, a camera frames.+ * Static targets resolve to rects at build time; tracked objects and+ * functions resolve to per-frame rects.+ */+import type { Rect } from "./draw.js";+import type { Vec2 } from "./path.js";+import {+ findRange,+ type MeasureFn,+ type MeasureOptions,+ rangeRects,+} from "./text.js";++export type Anchor =+ | "center"+ | "top"+ | "bottom"+ | "left"+ | "right"+ | "top-left"+ | "top-right"+ | "bottom-left"+ | "bottom-right"+ /** Where a pointer should land: the centre, or mid-left for text. */+ | "tip";++/** A node as targets read it: absolute numeric geometry, or text. */+export interface TargetNode {+ id?: string;+ kind?: string;+ x?: unknown;+ y?: unknown;+ width?: unknown;+ height?: unknown;+ text?: unknown;+ content?: unknown;+ [key: string]: unknown;+}++/** The frame context signals are read with. */+export interface FrameContextLike {+ frame: number;+ fps: number;+ time: number;+ duration: number;+ durationMs: number;+ progress: number;+ deltaTime: number;+}++/** A per-frame value: a signal (what tracked objects expose) or a function. */+export type FrameValue =+ | { get(ctx?: FrameContextLike): number }+ | ((frame: number) => number);++export interface TrackedObjectLike {+ x: FrameValue;+ y: FrameValue;+ width: FrameValue;+ height: FrameValue;+}++export type Target =+ | Vec2+ | Rect+ | { node: TargetNode; anchor?: Anchor }+ | {+ text: TargetNode;+ match?: string | RegExp;+ range?: [number, number];+ nth?: number;+ anchor?: Anchor;+ }+ | { track: TrackedObjectLike; anchor?: Anchor }+ | ((frame: number) => Vec2 | Rect);++export interface TargetContext {+ measure?: MeasureFn;+ /** Frame rate signals are sampled at (tracked targets). Default 30. */+ fps?: number;+ /** Font defaults for text nodes that don't set them. */+ textDefaults?: Partial<MeasureOptions>;+}++export type ResolvedTarget =+ | { kind: "static"; rects: Rect[]; anchor: Anchor }+ | { kind: "dynamic"; at: (frame: number) => Rect; anchor: Anchor };++const isVec2 = (t: unknown): t is Vec2 =>+ Array.isArray(t) && t.length === 2 && t.every((n) => typeof n === "number");++const isRect = (t: unknown): t is Rect =>+ typeof t === "object" &&+ t !== null &&+ ["x", "y", "width", "height"].every(+ (k) => typeof (t as Record<string, unknown>)[k] === "number",+ );++const num = (v: unknown): number | undefined =>+ typeof v === "number" && Number.isFinite(v) ? v : undefined;++function frameValue(v: FrameValue, frame: number, fps: number): number {+ if (typeof v === "function") return v(frame);+ if (v && typeof v.get === "function") {+ const time = frame / fps;+ return v.get({+ frame,+ fps,+ time,+ duration: 0,+ durationMs: 0,+ progress: 0,+ deltaTime: 1 / fps,+ });+ }+ throw new Error(+ "Tracked target values must be signals or (frame) => number.",+ );+}++/** Resolve a target to rects (static) or a per-frame rect (dynamic). */+export function resolveTarget(+ target: Target,+ ctx: TargetContext = {},+): ResolvedTarget {+ if (typeof target === "function") {+ return {+ kind: "dynamic",+ anchor: "center",+ at: (frame) => {+ const v = target(frame);+ return isVec2(v) ? { x: v[0], y: v[1], width: 0, height: 0 } : v;+ },+ };+ }+ if (isVec2(target)) {+ return {+ kind: "static",+ anchor: "center",+ rects: [{ x: target[0], y: target[1], width: 0, height: 0 }],+ };+ }+ if (isRect(target))+ return { kind: "static", anchor: "center", rects: [target] };++ if ("track" in target) {+ const t = target.track;+ const fps = ctx.fps ?? 30;+ return {+ kind: "dynamic",+ anchor: target.anchor ?? "center",+ at: (frame) => ({+ x: frameValue(t.x, frame, fps),+ y: frameValue(t.y, frame, fps),+ width: frameValue(t.width, frame, fps),+ height: frameValue(t.height, frame, fps),+ }),+ };+ }++ if ("text" in target) {+ return {+ kind: "static",+ anchor: target.anchor ?? "tip",+ rects: textRects(target, ctx),+ };+ }++ const node = target.node;+ const rect = nodeRect(node);+ if (!rect) {+ throw new Error(+ `Target node "${node.id ?? "?"}" has no absolute geometry. Give it numeric x, y, width and height, or target a rect.`,+ );+ }+ return { kind: "static", anchor: target.anchor ?? "center", rects: [rect] };+}++function nodeRect(node: TargetNode): Rect | null {+ const x = num(node.x);+ const y = num(node.y);+ const width = num(node.width);+ const height = num(node.height);+ if (+ x === undefined ||+ y === undefined ||+ width === undefined ||+ height === undefined+ ) {+ return null;+ }+ return { x, y, width, height };+}++function textRects(+ target: Extract<Target, { text: TargetNode }>,+ ctx: TargetContext,+): Rect[] {+ const node = target.text;+ const content =+ typeof node.text === "string"+ ? node.text+ : typeof node.content === "string"+ ? node.content+ : null;+ if (content === null)+ throw new Error("Text target node has no string content.");+ const x = num(node.x);+ const y = num(node.y);+ if (x === undefined || y === undefined) {+ throw new Error(+ `Text target "${node.id ?? "?"}" needs numeric x and y so its glyphs can be placed.`,+ );+ }+ if (!ctx.measure) throw new Error("Text targets need a measure function.");+ const fontFamily =+ (node.fontFamily as string | undefined) ?? ctx.textDefaults?.fontFamily;+ if (!fontFamily) throw new Error("Text target has no fontFamily.");+ const options: MeasureOptions = {+ ...ctx.textDefaults,+ fontFamily,+ fontSize: num(node.fontSize) ?? ctx.textDefaults?.fontSize,+ fontWeight:+ (node.fontWeight as string | number | undefined) ??+ ctx.textDefaults?.fontWeight,+ letterSpacing: num(node.letterSpacing) ?? ctx.textDefaults?.letterSpacing,+ lineHeight: num(node.lineHeight) ?? ctx.textDefaults?.lineHeight,+ width: num(node.width),+ align: alignOf(node.align),+ direction: node.direction as MeasureOptions["direction"],+ };+ const range =+ target.range ??+ (target.match !== undefined+ ? findRange(content, target.match, target.nth ?? 0)+ : [0, content.length]);+ if (!range) {+ throw new Error(+ `Text target: "${String(target.match)}" not found in "${content}".`,+ );+ }+ const metrics = ctx.measure(content, options);+ const rects = rangeRects(metrics, range[0], range[1], options);+ if (rects.length === 0)+ throw new Error("Text target range covers no glyphs.");+ return rects.map((r) => ({ ...r, x: r.x + x, y: r.y + y }));+}++/** Text node alignment (start / center / end, or left / right) as measure reads it. */+function alignOf(align: unknown): MeasureOptions["align"] {+ if (align === "center") return "center";+ if (align === "end" || align === "right") return "right";+ return "left";+}++/** The union rect of `rects`. */+export function boundsOf(rects: readonly Rect[]): Rect {+ if (rects.length === 0) return { x: 0, y: 0, width: 0, height: 0 };+ let x0 = Number.POSITIVE_INFINITY;+ let y0 = Number.POSITIVE_INFINITY;+ let x1 = Number.NEGATIVE_INFINITY;+ let y1 = Number.NEGATIVE_INFINITY;+ for (const r of rects) {+ x0 = Math.min(x0, r.x);+ y0 = Math.min(y0, r.y);+ x1 = Math.max(x1, r.x + r.width);+ y1 = Math.max(y1, r.y + r.height);+ }+ return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };+}++/** The point of `rect` named by `anchor`. `tip` on text = start of the first line, mid-height. */+export function anchorPoint(+ rect: Rect,+ anchor: Anchor = "center",+ isText = false,+): Vec2 {+ const { x, y, width: w, height: h } = rect;+ switch (anchor) {+ case "tip":+ return isText ? [x, y + h / 2] : [x + w / 2, y + h / 2];+ case "center":+ return [x + w / 2, y + h / 2];+ case "top":+ return [x + w / 2, y];+ case "bottom":+ return [x + w / 2, y + h];+ case "left":+ return [x, y + h / 2];+ case "right":+ return [x + w, y + h / 2];+ case "top-left":+ return [x, y];+ case "top-right":+ return [x + w, y];+ case "bottom-left":+ return [x, y + h];+ case "bottom-right":+ return [x + w, y + h];+ }+}++/** The point a resolved target names at `frame` (static targets ignore frame). */+export function targetPoint(+ resolved: ResolvedTarget,+ frame = 0,+ isText = false,+): Vec2 {+ if (resolved.kind === "dynamic")+ return anchorPoint(resolved.at(frame), resolved.anchor, isText);+ const first = resolved.rects[0] as Rect;+ return anchorPoint(+ resolved.anchor === "tip" ? first : boundsOf(resolved.rects),+ resolved.anchor,+ isText,+ );+}diff --git a/packages/components/src/core/text.ts b/packages/components/src/core/text.tsnew file mode 100644index 00000000..a0097870--- /dev/null+++ b/packages/components/src/core/text.ts@@ -0,0 +1,144 @@+/**+ * Geometry of text from real font measurement: word ranges, and the boxes a+ * character range covers (one per line it spans). Positions are relative to+ * the text box's top-left.+ */+import type { Rect } from "./draw.js";++/** The subset of `FontManager.measure` options components pass. */+export interface MeasureOptions {+ fontFamily: string;+ fontSize?: number;+ fontWeight?: string | number;+ letterSpacing?: number;+ lineHeight?: number;+ width?: number;+ align?: "left" | "center" | "right";+ direction?: "ltr" | "rtl" | "auto";+}++export interface GlyphBox {+ char: string;+ index: number;+ x: number;+ width: number;+ line: number;+ rtl?: boolean;+}++/** The subset of `FontManager.measure` results components read. */+export interface Metrics {+ width: number;+ height: number;+ lines: number;+ lineHeight: number;+ glyphs: GlyphBox[];+ caretX(count: number): number;+}++export type MeasureFn = (text: string, options: MeasureOptions) => Metrics;++export interface WordRange {+ text: string;+ /** Index of the first character (code units). */+ start: number;+ /** Index after the last character. */+ end: number;+ index: number;+}++/** Whitespace-separated words with their character ranges. */+export function wordRanges(text: string): WordRange[] {+ const out: WordRange[] = [];+ for (const m of text.matchAll(/\S+/g)) {+ const start = m.index ?? 0;+ out.push({+ text: m[0],+ start,+ end: start + m[0].length,+ index: out.length,+ });+ }+ return out;+}++/** Character range of the `nth` match of `match` in `text`, or null. */+export function findRange(+ text: string,+ match: string | RegExp,+ nth = 0,+): [number, number] | null {+ if (typeof match === "string") {+ let from = 0;+ for (let i = 0; ; i++) {+ const at = text.indexOf(match, from);+ if (at < 0) return null;+ if (i === nth) return [at, at + match.length];+ from = at + Math.max(1, match.length);+ }+ }+ const flags = match.flags.includes("g") ? match.flags : `${match.flags}g`;+ let i = 0;+ for (const m of text.matchAll(new RegExp(match.source, flags))) {+ if (i === nth) return [m.index ?? 0, (m.index ?? 0) + m[0].length];+ i++;+ }+ return null;+}++/**+ * Per-line x offset that `align` adds inside a box of `options.width`+ * (measurement itself lays every line out from the left edge).+ */+function lineShift(+ metrics: Metrics,+ line: number,+ options: MeasureOptions,+): number {+ if (!options.width || !options.align || options.align === "left") return 0;+ let min = Number.POSITIVE_INFINITY;+ let max = Number.NEGATIVE_INFINITY;+ for (const g of metrics.glyphs) {+ if (g.line !== line || g.char.trim() === "") continue;+ min = Math.min(min, g.x);+ max = Math.max(max, g.x + g.width);+ }+ if (!Number.isFinite(min)) return 0;+ const free = options.width - (max - min);+ return (options.align === "center" ? free / 2 : free) - min;+}++/**+ * The boxes characters [start, end) cover: one rect per line, spanning the+ * glyphs' advances, `lineHeight` tall. Whitespace at a line's ends is+ * excluded.+ */+export function rangeRects(+ metrics: Metrics,+ start: number,+ end: number,+ options: MeasureOptions,+): Rect[] {+ const byLine = new Map<number, { min: number; max: number }>();+ for (const g of metrics.glyphs) {+ if (g.index < start || g.index >= end || g.char.trim() === "") continue;+ const box = byLine.get(g.line) ?? {+ min: Number.POSITIVE_INFINITY,+ max: Number.NEGATIVE_INFINITY,+ };+ box.min = Math.min(box.min, g.x);+ box.max = Math.max(box.max, g.x + g.width - (options.letterSpacing ?? 0));+ byLine.set(g.line, box);+ }+ return [...byLine.entries()]+ .sort(([a], [b]) => a - b)+ .map(([line, box]) => {+ const shift = lineShift(metrics, line, options);+ return {+ x: box.min + shift,+ y: line * metrics.lineHeight,+ width: box.max - box.min,+ height: metrics.lineHeight,+ };+ });+}diff --git a/packages/components/src/core/theme.test.ts b/packages/components/src/core/theme.test.tsnew file mode 100644index 00000000..727703ea--- /dev/null+++ b/packages/components/src/core/theme.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vitest";+import { contrastRatio, defineTheme, themeFrames, themes } from "./theme.js";++describe("theme", () => {+ it("merges partials over graphite", () => {+ const t = defineTheme({+ color: { accent: "#ff0000" },+ font: { display: "Space Grotesk" },+ });+ expect(t.color.accent).toBe("#ff0000");+ expect(t.color.ink).toBe(themes.graphite.color.ink);+ expect(t.font.display).toBe("Space Grotesk");+ expect(t.font.mono).toBe("JetBrains Mono");+ });++ it("built-in themes pass contrast", () => {+ for (const theme of Object.values(themes)) {+ expect(+ contrastRatio(theme.color.ink, theme.color.surface),+ ).toBeGreaterThanOrEqual(4.5);+ expect(() => defineTheme(theme)).not.toThrow();+ }+ });++ it("rejects unreadable ink", () => {+ expect(() =>+ defineTheme({ color: { ink: "#222", surface: "#1a1a1a" } }),+ ).toThrow(/contrast/);+ // Non-hex colors can't be checked and are allowed.+ expect(() =>+ defineTheme({ color: { ink: "oklch(0.2 0 0)" } }),+ ).not.toThrow();+ });++ it("scales speeds by fps", () => {+ expect(themeFrames(themes.graphite, "base", 30)).toBe(16);+ expect(themeFrames(themes.graphite, "base", 60)).toBe(32);+ });+});diff --git a/packages/components/src/core/theme.ts b/packages/components/src/core/theme.tsnew file mode 100644index 00000000..8f94d746--- /dev/null+++ b/packages/components/src/core/theme.ts@@ -0,0 +1,200 @@+/**+ * Design tokens every component reads instead of hard-coded colors, fonts and+ * timings. `defineTheme` deep-merges a partial theme over `themes.graphite`.+ */+import { scaleFrames } from "./timing.js";++export interface Theme {+ color: {+ bg: string;+ surface: string;+ raised: string;+ line: string;+ ink: string;+ muted: string;+ accent: string;+ accent2: string;+ positive: string;+ negative: string;+ highlight: string;+ };+ font: { display: string; body: string; mono: string; hand?: string };+ radius: { sm: number; md: number; lg: number; pill: number };+ stroke: { hair: number; base: number; bold: number };+ motion: {+ ease: { enter: string; exit: string; move: string; snap: string };+ /** Durations in frames at 30 fps; see {@link themeFrames}. */+ speed: { fast: number; base: number; slow: number };+ };+ /** 1 = designed for 1080p. 2 for 4K, 0.5 for 540p. */+ scale: number;+}++export type ThemeInput = DeepPartial<Theme>;++type DeepPartial<T> = {+ [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];+};++const motion: Theme["motion"] = {+ ease: {+ enter: "expo.out",+ exit: "power2.in",+ move: "power3.inOut",+ snap: "back.out(1.6)",+ },+ speed: { fast: 8, base: 16, slow: 30 },+};++const shape = {+ radius: { sm: 6, md: 12, lg: 24, pill: 999 },+ stroke: { hair: 1, base: 2, bold: 4 },+};++const fonts: Theme["font"] = {+ display: "Inter",+ body: "Inter",+ mono: "JetBrains Mono",+};++/** Built-in themes. Fonts are never bundled: register the families you use. */+export const themes = {+ /** Dark neutral: product demos, dev tools. */+ graphite: {+ color: {+ bg: "#0d0e11",+ surface: "#16181d",+ raised: "#1f2229",+ line: "#2b2f38",+ ink: "#f3f4f6",+ muted: "#8b909c",+ accent: "#5b8cff",+ accent2: "#b07cff",+ positive: "#3ecf8e",+ negative: "#ff5c5c",+ highlight: "#ffd23f",+ },+ font: fonts,+ ...shape,+ motion,+ scale: 1,+ },+ /** Light editorial: explainers, documentaries. */+ paper: {+ color: {+ bg: "#f4f1ea",+ surface: "#fffdf8",+ raised: "#ffffff",+ line: "#dcd6c8",+ ink: "#1a1814",+ muted: "#6b665c",+ accent: "#e0451f",+ accent2: "#1f5fe0",+ positive: "#1f8a4c",+ negative: "#c8282d",+ highlight: "#ffe066",+ },+ font: fonts,+ ...shape,+ motion,+ scale: 1,+ },+ /** High contrast, saturated accent: social clips. */+ signal: {+ color: {+ bg: "#000000",+ surface: "#111111",+ raised: "#1c1c1c",+ line: "#333333",+ ink: "#ffffff",+ muted: "#a3a3a3",+ accent: "#c6ff00",+ accent2: "#ff2e88",+ positive: "#00e676",+ negative: "#ff1744",+ highlight: "#c6ff00",+ },+ font: fonts,+ ...shape,+ motion: {+ ...motion,+ ease: { ...motion.ease, enter: "back.out(1.8)" },+ speed: { fast: 6, base: 12, slow: 24 },+ },+ scale: 1,+ },+} as const satisfies Record<string, Theme>;++export type ThemeName = keyof typeof themes;++/**+ * Merge a partial theme over a base (default `themes.graphite`). Throws when+ * `ink` on `surface` falls below WCAG 4.5:1 and both are hex colors.+ */+export function defineTheme(+ input: ThemeInput | Theme = {},+ base: Theme = themes.graphite,+): Theme {+ const theme = merge(base, input) as Theme;+ const ratio = contrastRatio(theme.color.ink, theme.color.surface);+ if (ratio !== null && ratio < 4.5) {+ throw new Error(+ `Theme contrast too low: ink ${theme.color.ink} on surface ${theme.color.surface} is ${ratio.toFixed(2)}:1 (needs 4.5:1).`,+ );+ }+ return theme;+}++/** A theme's duration token in frames at `fps`. */+export function themeFrames(+ theme: Theme,+ speed: keyof Theme["motion"]["speed"],+ fps = 30,+): number {+ return scaleFrames(theme.motion.speed[speed], fps);+}++function merge(base: unknown, over: unknown): unknown {+ if (over === undefined) return base;+ if (+ base === null ||+ over === null ||+ typeof base !== "object" ||+ typeof over !== "object" ||+ Array.isArray(base) ||+ Array.isArray(over)+ ) {+ return over;+ }+ const out: Record<string, unknown> = { ...(base as Record<string, unknown>) };+ for (const [key, value] of Object.entries(over as Record<string, unknown>)) {+ out[key] = merge(out[key], value);+ }+ return out;+}++/** WCAG contrast ratio of two hex colors, or null when either isn't hex. */+export function contrastRatio(a: string, b: string): number | null {+ const la = luminance(a);+ const lb = luminance(b);+ if (la === null || lb === null) return null;+ const [hi, lo] = la > lb ? [la, lb] : [lb, la];+ return (hi + 0.05) / (lo + 0.05);+}++function luminance(hex: string): number | null {+ const m = hex.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);+ if (!m?.[1]) return null;+ const h =+ m[1].length === 3+ ? m[1]+ .split("")+ .map((c) => c + c)+ .join("")+ : m[1];+ const channel = (i: number) => {+ const c = Number.parseInt(h.slice(i, i + 2), 16) / 255;+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * channel(0) + 0.7152 * channel(2) + 0.0722 * channel(4);+}diff --git a/packages/components/src/core/timing.test.ts b/packages/components/src/core/timing.test.tsnew file mode 100644index 00000000..7048ce80--- /dev/null+++ b/packages/components/src/core/timing.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest";+import {+ beats,+ chain,+ cover,+ quantize,+ scaleFrames,+ staggerOffsets,+ toFrames,+} from "./timing.js";++describe("timing", () => {+ it("converts and rounds once", () => {+ expect(toFrames(1.51, 30)).toBe(45);+ expect(beats(2.5, 18)).toBe(45);+ expect(quantize(23, 9)).toBe(27);+ expect(quantize(23.4, undefined)).toBe(23);+ expect(scaleFrames(16, 60)).toBe(32);+ expect(scaleFrames(16, 24)).toBe(13);+ expect(() => toFrames(1, 0)).toThrow(/fps/);+ });++ it("staggers in every order", () => {+ expect(staggerOffsets(4, 3)).toEqual([0, 3, 6, 9]);+ expect(staggerOffsets(4, 3, "reverse")).toEqual([9, 6, 3, 0]);+ expect(staggerOffsets(5, 2, "center")).toEqual([4, 2, 0, 2, 4]);+ expect(staggerOffsets(5, 2, "edges")).toEqual([0, 2, 4, 2, 0]);+ const random = staggerOffsets(6, 1, "random", 9);+ expect([...random].sort((a, b) => a - b)).toEqual([0, 1, 2, 3, 4, 5]);+ expect(staggerOffsets(6, 1, "random", 9)).toEqual(random);+ expect(staggerOffsets(0, 3)).toEqual([]);+ });++ it("chains and covers windows", () => {+ const w = chain([10, 5, 20], 4, 2);+ expect(w).toEqual([+ { start: 4, end: 14 },+ { start: 16, end: 21 },+ { start: 23, end: 43 },+ ]);+ expect(cover(w)).toEqual({ start: 4, end: 43 });+ });+});diff --git a/packages/components/src/core/timing.ts b/packages/components/src/core/timing.tsnew file mode 100644index 00000000..0851d0f2--- /dev/null+++ b/packages/components/src/core/timing.ts@@ -0,0 +1,142 @@+/**+ * Frame math. Component times are integer frames (the SDK convention);+ * real-world inputs (seconds, beats, chars/sec) are rounded once, here.+ */+import { rng } from "./rng.js";++/** Seconds → whole frames. */+export function toFrames(seconds: number, fps: number): number {+ assertFps(fps);+ return Math.round(seconds * fps);+}++/** Whole frames → seconds. */+export function toSeconds(frames: number, fps: number): number {+ assertFps(fps);+ return frames / fps;+}++/** `n` beats of `beatFrames` each, as whole frames. */+export function beats(n: number, beatFrames: number): number {+ return Math.round(n * beatFrames);+}++/** Snap a frame to the nearest multiple of `grid` (no-op when grid ≤ 0). */+export function quantize(frame: number, grid: number | undefined): number {+ if (!grid || grid <= 0) return Math.round(frame);+ return Math.round(Math.round(frame / grid) * grid);+}++/**+ * Speeds in themes are authored at 30 fps; this rescales them so motion+ * lasts the same time at any frame rate.+ */+export function scaleFrames(framesAt30: number, fps: number): number {+ assertFps(fps);+ return Math.max(1, Math.round((framesAt30 * fps) / 30));+}++export type StaggerOrder =+ | "forward"+ | "reverse"+ | "center"+ | "edges"+ | "random";++/**+ * Start offset (frames) for each of `count` units, `stagger` frames apart,+ * in the given order. `random` is a seeded shuffle of the forward offsets.+ */+export function staggerOffsets(+ count: number,+ stagger: number,+ order: StaggerOrder = "forward",+ seed = 1,+): number[] {+ if (count <= 0) return [];+ const rank = staggerRanks(count, order, seed);+ return rank.map((r) => Math.round(r * stagger));+}++/** The position (0 = first) at which each unit starts, by order. */+export function staggerRanks(+ count: number,+ order: StaggerOrder,+ seed = 1,+): number[] {+ const idx = Array.from({ length: count }, (_, i) => i);+ const center = (count - 1) / 2;+ switch (order) {+ case "forward":+ return idx;+ case "reverse":+ return idx.map((i) => count - 1 - i);+ case "center":+ return idx.map((i) => Math.abs(i - center));+ case "edges":+ return idx.map((i) => center - Math.abs(i - center));+ case "random": {+ const r = rng(seed);+ const shuffled = [...idx];+ for (let i = shuffled.length - 1; i > 0; i--) {+ const j = Math.floor(r.next() * (i + 1));+ [shuffled[i], shuffled[j]] = [+ shuffled[j] as number,+ shuffled[i] as number,+ ];+ }+ const ranks = new Array<number>(count);+ shuffled.forEach((unit, position) => {+ ranks[unit] = position;+ });+ return ranks;+ }+ }+}++/** A closed frame range. */+export interface FrameWindow {+ start: number;+ end: number;+}++export const frameSpan = (start: number, duration: number): FrameWindow => ({+ start,+ end: start + Math.max(0, duration),+});++export const within = (frame: number, w: FrameWindow): boolean =>+ frame >= w.start && frame <= w.end;++/** The smallest window that covers all of `windows`. */+export function cover(windows: readonly FrameWindow[]): FrameWindow {+ if (windows.length === 0) return { start: 0, end: 0 };+ let start = Number.POSITIVE_INFINITY;+ let end = Number.NEGATIVE_INFINITY;+ for (const w of windows) {+ start = Math.min(start, w.start);+ end = Math.max(end, w.end);+ }+ return { start, end };+}++/** Lay out durations back to back from `start`, with `gap` frames between. */+export function chain(+ durations: readonly number[],+ start = 0,+ gap = 0,+): FrameWindow[] {+ const out: FrameWindow[] = [];+ let cursor = start;+ for (const d of durations) {+ out.push(frameSpan(cursor, d));+ cursor += d + gap;+ }+ return out;+}++function assertFps(fps: number): void {+ if (!(fps > 0) || !Number.isFinite(fps)) {+ throw new Error(`fps must be a positive number, got ${fps}`);+ }+}diff --git a/packages/components/src/index.ts b/packages/components/src/index.tsnew file mode 100644index 00000000..90f2dd57--- /dev/null+++ b/packages/components/src/index.ts@@ -0,0 +1,113 @@+/**+ * `@framefields/components`: parametric motion components, bundled into and+ * exported from `framefields`. Named re-exports only: no registries and no+ * top-level calls, so every export tree-shakes on its own.+ */++export {+ type BakedKey,+ type BakeOptions,+ bakeFunction,+ bakeSamples,+ springAt,+ springSettleFrames,+} from "./core/bake.js";+export {+ type BaseProps,+ BasePropsSchema,+ type BuildContext,+ type BuildResult,+ bind,+ type ComponentDefaults,+ type ComponentDefinition,+ type ComponentExtras,+ type ComponentNode,+ type Cue,+ type Cues,+ type CuesOf,+ defineComponent,+ offsetCues,+ type PropsOf,+ type PulseOptions,+ pulseKeys,+} from "./core/contract.js";+export {+ type ArrowCurve,+ type ArrowGeometry,+ arrowPaths,+ boilKeys,+ boxPath,+ drawOnKeys,+ ellipsePath,+ type HandOptions,+ linePath,+ type Rect,+ squigglePath,+ wobblePoints,+} from "./core/draw.js";+export { type EaseFn, ease, evaluateEase } from "./core/ease.js";+export type { Animatable, AnimatableMethods, Host } from "./core/host.js";+export { type ComponentMeta, defineMeta } from "./core/meta.js";+export {+ enterAnimation,+ exitAnimation,+ MOTION_PRESETS,+ type MotionOptions,+ type MotionPreset,+ type MotionPresetName,+ type ResolvedMotion,+ resolveMotion,+} from "./core/motion.js";+export {+ type ArcPath,+ arcPath,+ catmullRom,+ dist,+ lerp2,+ toPathData,+ type Vec2,+} from "./core/path.js";+export { hashRng, hashString, type Rng, rng } from "./core/rng.js";+export {+ type Anchor,+ anchorPoint,+ boundsOf,+ type ResolvedTarget,+ resolveTarget,+ type Target,+ type TargetContext,+ targetPoint,+} from "./core/targets.js";+export {+ findRange,+ type MeasureFn,+ type MeasureOptions,+ type Metrics,+ rangeRects,+ type WordRange,+ wordRanges,+} from "./core/text.js";+export {+ contrastRatio,+ defineTheme,+ type Theme,+ type ThemeInput,+ type ThemeName,+ themeFrames,+ themes,+} from "./core/theme.js";+export {+ beats,+ chain,+ cover,+ type FrameWindow,+ frameSpan,+ quantize,+ type StaggerOrder,+ scaleFrames,+ staggerOffsets,+ staggerRanks,+ toFrames,+ toSeconds,+ within,+} from "./core/timing.js";diff --git a/packages/components/src/purity.test.ts b/packages/components/src/purity.test.tsnew file mode 100644index 00000000..466e2344--- /dev/null+++ b/packages/components/src/purity.test.ts@@ -0,0 +1,40 @@+/**+ * Package-wide rules the spec relies on: seeded randomness only, and an+ * index made of re-exports so every export tree-shakes on its own.+ */+import { readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++const SRC = new URL(".", import.meta.url).pathname;++function sources(dir: string): string[] {+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {+ const p = join(dir, e.name);+ if (e.isDirectory()) return e.name === "test" ? [] : sources(p);+ return e.name.endsWith(".ts") && !e.name.endsWith(".test.ts") ? [p] : [];+ });+}++describe("package rules", () => {+ it("never uses Math.random or wall-clock time", () => {+ for (const file of sources(SRC)) {+ const code = readFileSync(file, "utf8")+ .replace(/\/\*[\s\S]*?\*\//g, "")+ .replace(/\/\/.*$/gm, "");+ expect(code, file).not.toMatch(/Math\.random|Date\.now|performance\.now/);+ }+ });++ it("index.ts only re-exports", () => {+ const code = readFileSync(join(SRC, "index.ts"), "utf8")+ .replace(/\/\*[\s\S]*?\*\//g, "")+ .replace(/\/\/.*$/gm, "");+ const statements = code+ .split(/;\s*/)+ .map((s) => s.trim())+ .filter(Boolean);+ for (const s of statements)+ expect(s).toMatch(/^export (type )?\{[\s\S]*\} from "\.\/[^"]+"$/);+ });+});diff --git a/packages/components/src/test/fake-host.ts b/packages/components/src/test/fake-host.tsnew file mode 100644index 00000000..d2435e94--- /dev/null+++ b/packages/components/src/test/fake-host.ts@@ -0,0 +1,115 @@+/**+ * A host for unit tests: builds plain nodes (no GPU, no fonts) and measures+ * text with a fixed advance per character, so geometry is easy to predict.+ */+import type { LayoutNode } from "@framefields/compositions/program";+import type { Animatable, Host } from "../core/host.js";+import type { MeasureOptions, Metrics } from "../core/text.js";++type Tracks = { tracks: Array<{ prop: string; keyframes: unknown[] }> };++function animatable<T extends object>(+ node: T,+): Animatable<T> & { animation?: Tracks } {+ const target = node as Animatable<T> & { animation?: Tracks };+ Object.defineProperty(target, "animate", {+ value: (...anims: unknown[]) => {+ const incoming = anims.flat().flatMap((a) => (a as Tracks).tracks ?? []);+ target.animation = {+ tracks: [...(target.animation?.tracks ?? []), ...incoming],+ };+ return target;+ },+ enumerable: false,+ });+ return target;+}++/** Every glyph is `fontSize × 0.5` wide; lines are `fontSize × 1.2` tall. */+export function fakeMeasure(text: string, options: MeasureOptions): Metrics {+ const fontSize = options.fontSize ?? 48;+ const advance = fontSize * 0.5 + (options.letterSpacing ?? 0);+ const lineHeight =+ options.lineHeight !== undefined && options.lineHeight < 10+ ? options.lineHeight * fontSize+ : (options.lineHeight ?? fontSize * 1.2);+ const glyphs: Metrics["glyphs"] = [];+ let line = 0;+ let x = 0;+ for (let i = 0; i < text.length; i++) {+ const char = text[i] as string;+ if (char === "\n") {+ line++;+ x = 0;+ continue;+ }+ if (+ options.width !== undefined &&+ x + advance > options.width &&+ char !== " "+ ) {+ // Wrap at the previous space (word wrap), or here.+ const lastSpace = glyphs.findLastIndex(+ (g) => g.line === line && g.char === " ",+ );+ line++;+ if (lastSpace >= 0) {+ let nx = 0;+ for (const g of glyphs.slice(lastSpace + 1)) {+ g.line = line;+ g.x = nx;+ nx += advance;+ }+ x = nx;+ } else x = 0;+ }+ glyphs.push({ char, index: i, x, width: advance, line });+ x += advance;+ }+ const lines = line + 1;+ const width = Math.max(0, ...glyphs.map((g) => g.x + g.width));+ return {+ width,+ height: lines * lineHeight,+ lines,+ lineHeight,+ glyphs,+ caretX: (count) => {+ const before = glyphs.filter((g) => g.index < count);+ const last = before[before.length - 1];+ return last ? last.x + last.width : 0;+ },+ };+}++export function fakeHost(): Host & { created: LayoutNode[] } {+ const created: LayoutNode[] = [];+ const counters = new Map<string, number>();+ const make = <T extends object>(node: T) => {+ created.push(node as unknown as LayoutNode);+ return animatable(node);+ };+ return {+ created,+ box: (o) =>+ make({ kind: "box", id: o.id ?? "box", children: [], ...o }) as never,+ flex: (o) =>+ make({ kind: "flex", id: o.id ?? "flex", children: [], ...o }) as never,+ text: (content, o = {}) =>+ make({ kind: "text", id: o.id ?? "text", text: content, ...o }) as never,+ shape: (type, o = {}) =>+ make({+ kind: "shape",+ id: o.id ?? "shape",+ shapeType: type,+ ...o,+ }) as never,+ measure: fakeMeasure,+ fonts: () => ["Inter", "JetBrains Mono"],+ autoId: (prefix) => {+ const n = (counters.get(prefix) ?? 0) + 1;+ counters.set(prefix, n);+ return `${prefix}-auto-${n}`;+ },+ };+}diff --git a/packages/components/src/test/probe.ts b/packages/components/src/test/probe.tsnew file mode 100644index 00000000..595ee0c8--- /dev/null+++ b/packages/components/src/test/probe.ts@@ -0,0 +1,48 @@+/**+ * A minimal component for testing the contract: a plate with a label that+ * "lands" at frame 10 and produces one cue per tick.+ */+import { z } from "zod";+import { defineComponent } from "../core/contract.js";++export const probe = defineComponent({+ name: "Probe",+ props: {+ label: z.string().default("probe"),+ ticks: z.array(z.number().int().min(0)).default([]),+ size: z.number().positive().default(100),+ },+ defaults: { enter: "rise", hold: 5 },+ build(ctx, props) {+ const plate = ctx.host.box({+ id: ctx.partId("plate"),+ position: "absolute",+ x: 0,+ y: 0,+ width: props.size,+ height: props.size,+ background: ctx.theme.color.accent,+ borderRadius: ctx.theme.radius.md,+ });+ const label = ctx.host.text(props.label, {+ id: ctx.partId("label"),+ fontFamily: ctx.theme.font.body,+ fill: ctx.theme.color.ink,+ });+ return {+ children: [plate, label],+ width: props.size,+ height: props.size,+ duration: 10,+ cues: {+ landed: [{ frame: 10 }],+ ticks: props.ticks.map((frame, i) => ({+ frame,+ index: i,+ jitter: ctx.rng(i).next(),+ })),+ },+ parts: { plate, label },+ };+ },+});diff --git a/packages/components/tsconfig.json b/packages/components/tsconfig.jsonnew file mode 100644index 00000000..0874bd96--- /dev/null+++ b/packages/components/tsconfig.json@@ -0,0 +1,11 @@+{+ "extends": "@framefields/tsconfig/base.json",+ "compilerOptions": {+ "moduleResolution": "bundler",+ "module": "ESNext",+ "lib": ["ES2022", "ESNext", "DOM"],+ "types": ["node"],+ "noEmit": true+ },+ "include": ["src/**/*", "scripts/**/*"]+}diff --git a/packages/components/tsdown.config.ts b/packages/components/tsdown.config.tsnew file mode 100644index 00000000..b2285023--- /dev/null+++ b/packages/components/tsdown.config.ts@@ -0,0 +1,11 @@+import { defineConfig } from "tsdown";++export default defineConfig({+ entry: ["src/index.ts"],+ format: ["esm"],+ dts: true,+ clean: true,+ sourcemap: true,+ treeshake: true,+ external: [/^@framefields\//, "zod"],+});diff --git a/packages/components/vitest.config.ts b/packages/components/vitest.config.tsnew file mode 100644index 00000000..5b693075--- /dev/null+++ b/packages/components/vitest.config.ts@@ -0,0 +1,8 @@+import { defineConfig } from "vitest/config";++export default defineConfig({+ test: {+ environment: "node",+ include: ["src/**/*.test.ts", "scripts/**/*.test.ts"],+ },+});diff --git a/packages/framefields/package.json b/packages/framefields/package.jsonindex af8f1518..d8a6a44d 100644--- a/packages/framefields/package.json+++ b/packages/framefields/package.json@@ -66,6 +66,12 @@"import": "./dist/fonts/index.mjs","default": "./dist/fonts/index.mjs"},+ "./components": {+ "types": "./dist/components/index.d.mts",+ "development": "./src/components/index.ts",+ "import": "./dist/components/index.mjs",+ "default": "./dist/components/index.mjs"+ },"./preview": {"types": "./dist/preview/index.d.mts","development": "./src/preview/index.ts",@@ -77,7 +83,7 @@"dist/**"],"scripts": {- "build": "tsdown && node ../../scripts/sync-readme.mjs && node scripts/check-dts-bundle.mjs",+ "build": "tsdown && node ../../scripts/sync-readme.mjs && node scripts/check-dts-bundle.mjs && node scripts/check-components-treeshake.mjs","dev": "tsdown --watch","clean": "rm -rf dist .turbo","prepack": "node ../../scripts/sync-readme.mjs",@@ -116,6 +122,7 @@"devDependencies": {"@framefields/ai": "workspace:*","@framefields/client-utils": "workspace:*",+ "@framefields/components": "workspace:*","@framefields/compositions": "workspace:*","@framefields/core": "workspace:*","@framefields/node-audio-compressor": "workspace:*",diff --git a/packages/framefields/scripts/check-components-treeshake.mjs b/packages/framefields/scripts/check-components-treeshake.mjsnew file mode 100644index 00000000..504be2b5--- /dev/null+++ b/packages/framefields/scripts/check-components-treeshake.mjs@@ -0,0 +1,66 @@+// 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.+import { fileURLToPath } from "node:url";+import { build } from "esbuild";++const root = fileURLToPath(new URL("../dist/index.mjs", import.meta.url));+const components = fileURLToPath(+ new URL("../dist/components/index.mjs", import.meta.url),+);++// Strings that only exist in one module each.+const CONTRACT = "invalid props";+const STROKES = "wobble:";+const TARGETS = "has no absolute geometry";+const MOTION = "Unknown motion preset";++/** [names imported, 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],+];++async function bundle(contents) {+ const result = await build({+ stdin: { contents, resolveDir: process.cwd(), loader: "js" },+ bundle: true,+ write: false,+ format: "esm",+ platform: "node",+ packages: "external",+ logLevel: "silent",+ });+ return result.outputFiles[0].text;+}++const baseline = `import { Layer } from ${JSON.stringify(root)};\nconsole.log(Layer);`;+const base = await bundle(baseline);++const failures = [];+for (const [names, forbidden, budget] of cases) {+ const code = await bundle(+ `${baseline}\nimport { ${names.join(", ")} } from ${JSON.stringify(components)};\nconsole.log(${names.join(", ")});`,+ );+ const label = `import { ${names.join(", ")} }`;+ for (const marker of forbidden) {+ if (code.includes(marker) && !base.includes(marker)) {+ failures.push(`${label} kept code containing "${marker}"`);+ }+ }+ const added = code.length - base.length;+ if (added > budget)+ failures.push(`${label} added ${added} bytes (budget ${budget})`);+}++if (failures.length > 0) {+ console.error(+ `framefields/components does not tree-shake:\n ${failures.join("\n ")}`,+ );+ process.exit(1);+}+console.log(`framefields/components tree-shakes (${cases.length} cases)`);diff --git a/packages/framefields/src/components/contract.render.test.ts b/packages/framefields/src/components/contract.render.test.tsnew file mode 100644index 00000000..d3aede14--- /dev/null+++ b/packages/framefields/src/components/contract.render.test.ts@@ -0,0 +1,135 @@+import { defineComponent } from "@framefields/components";+import { describe, expect, it } from "vitest";+import { z } from "zod";+import { Composition, CompositorProgramSchema, Layer } from "../index.js";+import { decodePngPixels, getPixel } from "../test-utils/pixels.js";+import { bindComponent } from "./index.js";++/**+ * Render tests for the component contract (spec §9.2–9.4) with a probe+ * component: a red plate that rises in and reports one cue at frame 10.+ */+const Probe = bindComponent(+ defineComponent({+ name: "Probe",+ props: {+ color: z.string().default("#ff0000"),+ size: z.number().default(100),+ },+ defaults: { enter: { preset: "rise", duration: 10 }, hold: 20 },+ build(ctx, props) {+ const plate = ctx.host.box({+ id: ctx.partId("plate"),+ position: "absolute",+ x: 0,+ y: 0,+ width: props.size,+ height: props.size,+ background: props.color,+ });+ return {+ children: [plate],+ width: props.size,+ height: props.size,+ duration: 10,+ cues: { landed: [{ frame: 10 }] },+ parts: { plate },+ };+ },+ }),+);++const W = 200;+const H = 200;++function scene(build: () => Parameters<Composition["add"]>[0]) {+ const comp = new Composition({+ width: W,+ height: H,+ fps: 30,+ durationMs: 2000,+ backgroundColor: "#000000",+ });+ comp.add(build());+ return comp;+}++async function frame(comp: Composition, n: number) {+ return decodePngPixels(await comp.renderFrame({ frame: n }));+}++describe("component contract (render)", () => {+ it("enters with the preset and settles at its placement", async () => {+ const comp = scene(() => Probe({ at: 0, x: 50, y: 50 }));+ const start = await frame(comp, 0);+ expect(getPixel(start, 100, 100).r).toBeLessThan(10); // opacity 0+ // expo.out at 1/10: half way, so 20 px low and half faded in.+ const mid = await frame(comp, 1);+ expect(getPixel(mid, 100, 60).r).toBeLessThan(10);+ expect(getPixel(mid, 100, 120).r).toBeGreaterThan(100);+ expect(getPixel(mid, 100, 120).r).toBeLessThan(160);+ const settled = await frame(comp, 15);+ expect(getPixel(settled, 100, 52).r).toBeGreaterThan(240);+ expect(getPixel(settled, 45, 100).r).toBeLessThan(10);+ expect(getPixel(settled, 155, 100).r).toBeLessThan(10);+ });++ it("places itself in flow when it has no x / y", async () => {+ const comp = scene(() =>+ Layer.flex({+ width: W,+ height: H,+ padding: 50,+ children: [Probe({ enter: false })],+ }),+ );+ const img = await frame(comp, 0);+ expect(getPixel(img, 52, 52).r).toBeGreaterThan(240);+ expect(getPixel(img, 48, 48).r).toBeLessThan(10);+ });++ it("reports cues a sibling can start on, frame-exactly", async () => {+ const comp = scene(() => {+ const probe = Probe({ at: 5, x: 0, y: 0, enter: false });+ const landed = probe.cues.landed[0]!.frame;+ expect(landed).toBe(15);+ return [+ probe,+ Layer.box({+ position: "absolute",+ x: 150,+ y: 150,+ width: 40,+ height: 40,+ background: "#00ff00",+ startFrame: landed,+ durationFrames: 10,+ }),+ ];+ });+ expect(getPixel(await frame(comp, 14), 170, 170).g).toBeLessThan(10);+ expect(getPixel(await frame(comp, 15), 170, 170).g).toBeGreaterThan(240);+ });++ it("produces a spec that validates and lints clean", () => {+ const comp = scene(() => Probe({ x: 10, y: 10, exit: "fade" }));+ const result = CompositorProgramSchema.safeParse(comp.toSpec());+ expect(result.success, JSON.stringify(result.error?.issues)).toBe(true);+ expect(comp.lint().filter((d) => d.severity === "error")).toEqual([]);+ });++ it("renders the same pixels in any frame order", async () => {+ const frames = [0, 3, 6, 9, 12, 30];+ const comp = scene(() => Probe({ x: 50, y: 50, exit: "fade" }));+ const forward = new Map<number, Uint8ClampedArray>();+ for (const n of frames) forward.set(n, (await frame(comp, n)).pixels);+ const again = scene(() => Probe({ x: 50, y: 50, exit: "fade" }));+ for (const n of [...frames].reverse()) {+ expect(+ Buffer.from((await frame(again, n)).pixels).equals(+ Buffer.from(forward.get(n)!),+ ),+ ).toBe(true);+ }+ });+});diff --git a/packages/framefields/src/components/host.ts b/packages/framefields/src/components/host.tsnew file mode 100644index 00000000..f6954d13--- /dev/null+++ b/packages/framefields/src/components/host.ts@@ -0,0 +1,19 @@+/**+ * The host framefields injects into `@framefields/components`: 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 } from "@framefields/components";+import { FontManager } from "../fonts/index.js";+import { autoId } from "../ids.js";+import { Layer } from "../index.js";++export const host: Host = {+ box: (options) => Layer.box(options),+ flex: (options) => Layer.flex(options),+ text: (content, options) => Layer.text(content, options),+ shape: (type, options) => Layer.shape(type, options),+ measure: (text, options) => FontManager.measure(text, options),+ fonts: () => FontManager.getAll().map((f) => f.family),+ autoId,+};diff --git a/packages/framefields/src/components/index.ts b/packages/framefields/src/components/index.tsnew file mode 100644index 00000000..d0a0e58d--- /dev/null+++ b/packages/framefields/src/components/index.ts@@ -0,0 +1,129 @@+/**+ * `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).+ *+ * Each component is bound to the framefields host with a PURE call, so+ * bundlers drop every component that isn't imported.+ */++import {+ type BaseProps,+ bind,+ type ComponentDefinition,+ type ComponentExtras,+ type Cues,+} from "@framefields/components";+import type { BoxNode } from "@framefields/compositions/program";+import type { z } from "zod";+import type { AnimatableNode } from "../index.js";+import { host } from "./host.js";++/** A component's root: a normal framefields box layer plus cues, span and parts. */+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`.+ */+export function bindComponent<S extends z.ZodRawShape, C extends Cues>(+ definition: ComponentDefinition<S, C>,+): (props: z.input<z.ZodObject<S>> & BaseProps) => ComponentNode<C> {+ return bind(host, definition) as never;+}++export {+ type Anchor,+ type ArcPath,+ type ArrowCurve,+ type ArrowGeometry,+ anchorPoint,+ arcPath,+ arrowPaths,+ type BakedKey,+ type BakeOptions,+ type BaseProps,+ BasePropsSchema,+ type BuildContext,+ type BuildResult,+ bakeFunction,+ bakeSamples,+ beats,+ boilKeys,+ boundsOf,+ boxPath,+ type ComponentDefaults,+ type ComponentDefinition,+ type ComponentExtras,+ type ComponentMeta,+ type Cue,+ type Cues,+ type CuesOf,+ catmullRom,+ chain,+ contrastRatio,+ cover,+ defineComponent,+ defineMeta,+ defineTheme,+ dist,+ drawOnKeys,+ type EaseFn,+ ease,+ ellipsePath,+ enterAnimation,+ evaluateEase,+ exitAnimation,+ type FrameWindow,+ findRange,+ frameSpan,+ type HandOptions,+ hashRng,+ hashString,+ lerp2,+ linePath,+ type MeasureOptions,+ type Metrics,+ MOTION_PRESETS,+ type MotionOptions,+ type MotionPreset,+ type MotionPresetName,+ offsetCues,+ type PropsOf,+ type PulseOptions,+ pulseKeys,+ quantize,+ type Rect,+ type ResolvedMotion,+ type ResolvedTarget,+ type Rng,+ rangeRects,+ resolveMotion,+ resolveTarget,+ rng,+ type StaggerOrder,+ scaleFrames,+ springAt,+ springSettleFrames,+ squigglePath,+ staggerOffsets,+ staggerRanks,+ type Target,+ type TargetContext,+ type Theme,+ type ThemeInput,+ type ThemeName,+ targetPoint,+ themeFrames,+ themes,+ toFrames,+ toPathData,+ toSeconds,+ type Vec2,+ type WordRange,+ within,+ wobblePoints,+ wordRanges,+} from "@framefields/components";diff --git a/packages/framefields/src/index.ts b/packages/framefields/src/index.tsindex 73f097c4..a69eab34 100644--- a/packages/framefields/src/index.ts+++ b/packages/framefields/src/index.ts@@ -3380,3 +3380,23 @@ 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`.+export {+ type Anchor,+ type BaseProps,+ type Cue,+ type Cues,+ defineTheme,+ type MotionPreset,+ pulseKeys,+ type Target,+ type Theme,+ type ThemeInput,+ themes,+} from "@framefields/components";+export {+ bindComponent,+ type ComponentNode,+} from "./components/index.js";diff --git a/packages/framefields/tsdown.config.ts b/packages/framefields/tsdown.config.tsindex 78f7a1a3..b03d24d4 100644--- a/packages/framefields/tsdown.config.ts+++ b/packages/framefields/tsdown.config.ts@@ -10,6 +10,7 @@ export default defineConfig({"src/renderer/index.ts","src/fonts/index.ts","src/preview/index.ts",+ "src/components/index.ts",],format: ["esm"],clean: true,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 62e9ed9e..a9a4ef0b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2632,6 +2632,37 @@ importers:specifier: ^5.8.3version: 5.8.3+ packages/components:+ dependencies:+ '@framefields/compositions':+ specifier: workspace:*+ version: link:../compositions+ '@framefields/core':+ specifier: workspace:*+ version: link:../core+ zod:+ specifier: ^4.3.6+ version: 4.3.6+ devDependencies:+ '@framefields/tsconfig':+ specifier: workspace:*+ version: link:../tsconfig+ '@types/node':+ specifier: ^24.1.0+ version: 24.10.14+ tsdown:+ specifier: ^0.19.0+ version: 0.19.0([email protected])([email protected])+ tsx:+ specifier: ^4.20.3+ version: 4.21.0+ typescript:+ specifier: ^5.8.3+ version: 5.9.3+ vitest:+ specifier: ^4.1.11+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+packages/compositions:dependencies:'@framefields/node-sdk':@@ -2790,6 +2821,9 @@ importers:'@framefields/client-utils':specifier: workspace:*version: link:../client-utils+ '@framefields/components':+ specifier: workspace:*+ version: link:../components'@framefields/compositions':specifier: workspace:*version: link:../compositions