Skip to content

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

feat(cli): framefields init, fonts installed with components; component polish

okanasl7f58e5878a2f
diff --git a/.changeset/components-polish-fonts-init.md b/.changeset/components-polish-fonts-init.md
new file mode 100644
index 00000000..893f4609
--- /dev/null
+++ b/.changeset/components-polish-fonts-init.md
@@ -0,0 +1,11 @@
+---
+"framefields": minor
+---
+
+Start projects with `framefields init`, install fonts with components, and polish the component toolkit.
+
+- `npx framefields init [dir]` writes a working project: `package.json` (ES module, scripts, dependencies, `packageManager`, and install-script approvals that let only skia-canvas run its script), `tsconfig.json`, `src/theme.ts` / `film.ts` / `render.ts`, `assets/`, an LFS `.gitattributes`, `.gitignore` and `README.md`. It also installs Inter and JetBrains Mono and runs `git init`. It never overwrites: in an existing project, files only gain what they lack. Options: `--pm`, `--install`, `--emoji`, `--no-fonts`, `--no-git`, `--name`.
+- Fonts come with the components that need them. `framefields add chat-thread` / `captions` installs Noto Color Emoji, and `terminal` / `code-block` install JetBrains Mono. Each font is pinned by size and SHA-256, saved with its OFL license, recorded in `framefields.json` and registered in a generated `fonts.ts` (`await registerFonts()`). `framefields fonts add <emoji|sans|mono>` and `fonts list` install fonts directly, and `--no-fonts` skips them. The package itself ships no fonts.
+- `comp.lint()` reports `missing_emoji_font` when text has emoji but no emoji font is registered, and the render warning now names the fix. `FontManager.hasEmojiFont()` is new.
+- Toolkit: `withDefaults({ fps, canvas, theme, seed })` and `after(node, gap)` (also on the root), a `canvas` base prop, prop typos answered with "did you mean", `partNames` on every node, a `blur` option on motion presets, and shared keyframe, color, layout and surface helpers.
+- Themes gain `mode`, font weights, elevation, springs, `color.shadow` and `syntax`. LowerThird, Toasts, Callout, CardStack and ChatThread surfaces get depth (shadow, lit top edge, sheen), and sliding surfaces get motion blur. ChatThread reactions are emoji text drawn from the color emoji font.
diff --git a/packages/components/REPORT.md b/packages/components/REPORT.md
new file mode 100644
index 00000000..503e0736
--- /dev/null
+++ b/packages/components/REPORT.md
@@ -0,0 +1,522 @@
+# Components review: visuals, DX and code elegance
+
+Date: 2026-10-25 · Scope: the 26 components in `src/` and the shared `core/` (about 25k lines
+with tests), `SPEC.md`, the registry scripts and the render tests in
+`packages/framefields/src/components/`.
+
+The foundations are strong. The contract (root → stage → content, strict zod props, cues in
+the parent's timeline, `holdFirstKeys`) is consistent across all 26 components. Determinism
+is enforced by tests rather than by convention, the tree-shake and registry-typecheck scripts
+catch real problems, and the delivery notes in `SPEC.md` explain why things are the way they
+are. Most of what follows is about the next layer up: a richer look, less ceremony for the
+people calling components, and pulling repeated code into `core/`.
+
+## Status (implemented on `feat/components-dx-elegance`)
+
+| Item | State |
+|---|---|
+| `core/keys.ts`, `core/color.ts`, `core/layout.ts` (§3.1, 3.2, 3.4) | **Done**: local copies removed; `springTrack` moved to `core/bake.ts` |
+| Theme tokens: `mode`, weights, elevation, springs, `syntax`, `color.shadow` (§1.1) | **Done** |
+| `surface()` helpers and depth on LowerThird, Toasts, Callout, CardStack, ChatThread (§1.2) | **Done** |
+| Motion blur on slides (`blur` on motion presets; plates, toasts, cards) (§1.3) | **Done** |
+| CodeBlock syntax colors from the theme, readable on light themes | **Done** |
+| `canvas` base prop + `withDefaults` (§2.3; named `canvas`, since Terminal already has `frame`) | **Done** |
+| Did-you-mean prop errors, instance ids in errors (§2.5) | **Done** |
+| Meta drift test, `partNames`, prop docs in `components.json` (§2.1, 2.2 partly) | **Done**: nine metas fixed. 136 of 303 props have descriptions so far |
+| `after()` chaining helper (§2.7) | **Done** |
+| Gallery contact sheet (§1.5) | **Done**: `pnpm --filter framefields gallery` |
+| ChatThread reactions as emoji text (Noto Color Emoji), replacing the jagged drawn heart | **Done** (from user feedback) |
+| `framefields init` project bootstrapper (package.json, tsconfig, src, assets, LFS, fonts, git) | **Done** |
+| Fonts installed with components: `add` fetches pinned Noto Color Emoji, writes `fonts.ts`; `framefields fonts add`; `missing_emoji_font` lint and render warning | **Done** |
+| Typed parts and cues on `defineComponent` (§2.2) | Open |
+| Prop vocabulary renames with aliases (§2.4) | Open |
+| Examples as code, per-component READMEs, skill section (§2.6) | Open |
+| Splitting large builders into planners (§3.5) | Open |
+| Chat bubble tails, glass variants, Backdrop styles, anticipation (§1.3, 1.4) | Open |
+| The 10 new components (§4) | Open |
+
+## Top recommendations
+
+| # | Change | Area | Effort | Payoff |
+|---|---|---|---|---|
+| 1 | Add `core/keys.ts` (`Track`, `KeyBook`, `ascending`, `valueAt`, `round`) and `core/color.ts`, then delete the 20+ local copies | Elegance | S–M | High: one place for the keyframe rules, and it removes a real divergence (§3.1) |
+| 2 | Add elevation, type scale, weights, springs and `mode` to `Theme` | Visuals | M | High: every surface gets depth and consistent type |
+| 3 | Let parts and cues be typed and declared once, with meta derived from them | DX | M | High: `customize` autocompletes, and meta can't drift from the code |
+| 4 | `withDefaults({ fps, theme, frame })` so fps, theme and frame size are set once per project | DX | S | High: removes the 1920×1080 / 30 fps default trap in vertical and 60 fps work |
+| 5 | A gallery script: every `example` under all three themes into one contact sheet | Visuals + DX | S | High: visual regressions and rough spots become visible at a glance |
+| 6 | Add `.describe()` to props so `components.json` and agents get prop docs | DX | S | Medium–High: docs and agents currently see names and types only |
+
+---
+
+## 1. Visuals
+
+### 1.1 The theme is too thin to carry a look
+
+`Theme` has colors, three fonts, radii, strokes, eases and speeds. Everything else is decided
+inside components:
+
+- **Type scale and weights.** There are 25 `fontWeight: <number>` literals across components,
+ and sizes are local ratios (`roleSize = nameSize * 0.62` in LowerThird, `fs = 30 * s` in
+ ChatThread). Two components side by side don't share a scale.
+- **Elevation.** Only 7 of 26 components use `dropShadow`, each with its own numbers. None use
+ `innerShadow` or `outerGlow`, so plates, toasts, bubbles and cards look flat next to the
+ framed windows.
+- **Springs.** `SPRING` / `POP` are redefined with different constants in
+ [chat-thread/index.ts:51](src/chat-thread/index.ts:51), [toasts/index.ts:39](src/toasts/index.ts:39)
+ and [logo-reveal/index.ts:39](src/logo-reveal/index.ts:39). The `signal` theme can make eases
+ snappier, but it can't change how springy things feel.
+- **Light or dark.** Components work it out from contrast against black and white
+ ([annotate/index.ts:323](src/annotate/index.ts:323), [app-frame/index.ts:126](src/app-frame/index.ts:126),
+ MousePointer). An explicit `theme.mode` is clearer and cheaper.
+- **Hard-coded palettes.** 20 component files contain hex or `rgba()` literals. Some are
+ correct (traffic lights, device bodies), but AppFrame (21) and DeviceFrame (15) carry whole
+ private palettes, and CodeBlock's syntax `type` color (`#4cc9e0`) and Terminal's ANSI colors
+ ignore the theme.
+
+Proposed additions, all optional with the current values as defaults so nothing moves:
+
+```ts
+interface Theme {
+ mode: "dark" | "light";
+ type: {
+ scale: { xs: number; sm: number; md: number; lg: number; xl: number; display: number };
+ weight: { regular: number; medium: number; bold: number; black: number };
+ tracking: { tight: number; normal: number; wide: number };
+ };
+ elevation: { 0: LayerStyleConfig; 1: LayerStyleConfig; 2: LayerStyleConfig; 3: LayerStyleConfig };
+ surface: { sheen: number; edge: string }; // top highlight, 1px inner edge
+ motion: { /* existing */ spring: { soft: Spring; base: Spring; snappy: Spring } };
+ syntax?: Partial<Record<TokenKind, string>>; // CodeBlock / Terminal
+}
+```
+
+### 1.2 Give surfaces depth
+
+A shared `surface(ctx, { elevation, radius, tone })` helper in `core/` would turn a flat box
+into a finished surface: an elevation shadow, a faint top-edge highlight (an inner shadow at
+`angle: -90`), and an optional vertical gradient of 2–3 % lightness. Using it in LowerThird
+plates, Toasts, Callout labels, ChatThread bubbles, CardStack cards and the Selection / Spotlight
+chrome would make them read as one design language. It also gives users one knob
+(`theme.elevation`) instead of `customize` on every part.
+
+### 1.3 Motion polish
+
+- **Motion blur where things travel fast.** MousePointer, FocusZoom and Counter already use
+ `motionBlurShutter`. CardStack's `fly`, Toasts' push-down, LowerThird's plate slide and the
+ `slide-*` / `mask-*` presets would benefit most. A `smear` base prop (`false | true |
+ shutter°`) applied to the stage would cover every component at once.
+- **Consistent overshoot.** `pop` uses `theme.motion.ease.snap`, while bubbles and toasts use
+ their own springs. With spring tokens (1.1), "pop" means the same thing everywhere.
+- **Exit choreography.** LowerThird, TitleCard and TextReveal leave in reverse order with a
+ stagger; Toasts, Callout and ChatThread just fade. A shared `exitStagger(parts, order)` would
+ make the quieter exits match.
+- **Anticipation.** Nothing pulls back before it moves. A 2–3 frame anticipation option on
+ `MotionPreset` (`{ preset: "rise", anticipate: 0.15 }`) is cheap and noticeably more
+ professional.
+
+### 1.4 Per-component notes
+
+| Component | What would lift it |
+|---|---|
+| LowerThird | No logo or avatar slot (noted in M4). Add `logo` (media) and a `glass` plate variant (blurred backdrop plus sheen). |
+| ChatThread | Bubbles have no tail. Add drawn tails (one path per side) and a "read" tick row. Reactions are emoji text, which needs a registered color emoji font such as Noto. |
+| Toasts | Add an optional time-left bar along the bottom edge and a `glass` surface. |
+| Spotlight | `rect` can't be feathered (one matte can't be both rounded and soft). Stacking a blurred copy of the matte, or a second softer ring layer, would give a soft rectangle. |
+| Confetti | Paper doesn't flip, because particles have no per-particle rotation. A small `scaleX` oscillation baked into a sprite sheet (two or three frames of a turning square) would sell the flutter. |
+| CardStack | The sliver at the front card's rounded corners (noted in M8). Clip the strip with the card's own radius at its top edge. |
+| CodeBlock / Terminal | Take syntax and ANSI colors from `theme.syntax`. Add a "focus glow" for the active line (outer glow at low opacity) to go with the dimming. |
+| Backdrop | `mesh / grid / dots / solid` cover the basics. `aurora` (stretched, blurred ribbons), `noise` (domain-warped GPU noise) and `conic` would match current launch-film looks. |
+| DeviceFrame | A 2D body under perspective. Edge lighting (a gradient along the bezel that follows `tilt`) would get much of the 3D feel without a mesh. The real 3D version is proposal B in §4. |
+| Waveform | Add a `glow` (outer glow tied to `level`) and a rounded-cap option for bars. |
+
+### 1.5 Visual QA tooling
+
+The render tests check behaviour (a toast is absent before it arrives, a split shows only its
+side). Nothing shows what the components look like together. A `pnpm gallery` script that
+renders each meta example at 3–5 key frames under `graphite`, `paper` and `signal` into one
+PNG contact sheet would make light-theme gaps, flat surfaces and inconsistent type obvious in
+seconds. Committing the sheet lets a PR diff show visual change.
+
+---
+
+## 2. Developer experience
+
+### 2.1 Props carry no documentation into the schema
+
+There are zero `.describe()` calls in the components. The JSDoc comments inside the zod
+shapes (`/** Stay on screen instead of leaving after hold. */`) help in the editor, but they
+never reach `components.json`, the docs props table §9.7 calls for, or a coding agent reading
+the schema. Moving those comments into `.describe("…")`, and having `build-meta.ts` emit
+`z.toJSONSchema(schema)` per component, makes the agent-first goal (§1.1.5) real.
+
+### 2.2 Parts and cues: typed, and declared once
+
+Today:
+
+- `customize` receives `Record<string, Animatable<LayoutNode>>`
+ ([contract.ts:168](src/core/contract.ts:168)), so `parts.cursor` doesn't autocomplete and a
+ typo is a silent `undefined`.
+- Each of the 26 components declares a cues interface with the same
+ `[name: string]: ReadonlyArray<{ frame: number }>` index signature, then casts its result
+ (`as LowerThirdCues`, 25 times).
+- `meta.ts` lists `parts` and `cues` again as strings, and no test checks them against what
+ `build` actually returns.
+
+Proposal: declare parts and cues on the definition and derive the rest from them.
+
+```ts
+export const lowerThird = defineComponent({
+ name: "LowerThird",
+ parts: ["plate", "edge", "name", "role"] as const,
+ cues: { in: cue(), out: cue() }, // cue<{ index: number }>() for data
+ props: () => ({ … }),
+ build(ctx, props) {
+ …
+ return { children, width, height, duration, parts: { plate, edge }, cues: { in: […], out: […] } };
+ },
+});
+// customize(parts) is typed as Record<"root" | "stage" | "plate" | …, Animatable<LayoutNode>>
+// meta.parts / meta.cues come from the definition: meta.ts keeps summary, tags, example.
+```
+
+Until then, a test in `contract.test.ts` that builds each canonical example and asserts
+`Object.keys(node.cues)` equals `meta.cues` and every `meta.parts` name resolves through
+`node.part()` would stop drift cheaply.
+
+### 2.3 Set fps, theme and frame size once
+
+`fps` defaults to 30 ([contract.ts:336](src/core/contract.ts:336)), and ten frame-sized
+components (Backdrop, Callout, Captions, Confetti, FocusZoom, LowerThird, Selection,
+Spotlight, Toasts, TouchPoint) default to `1920 × 1080 × theme.scale`. In a 60 fps or 1080 × 1920
+vertical project, every call needs `fps`, `width` and `height`, or it silently comes out at
+the wrong speed or size. That is easy to miss for people and agents alike.
+
+Components must stay pure, so the fix is a binding-time default rather than a global:
+
+```ts
+// src/components/defaults.ts (written once by `framefields add`, or by hand)
+export const ui = withDefaults({ fps: 60, theme: themes.paper, frame: [1080, 1920] });
+const Captions = ui(CaptionsBase);
+```
+
+`withDefaults` wraps a bound factory and merges its defaults under the call's props, so purity,
+caching and tree-shaking are unchanged. `BuildContext` gains `frame: { width, height }`, and the
+ten copies of `ctx.requested.width ?? 1920 * s` become `ctx.frame.width`. `framefields add`
+could write this file from the project's composition settings.
+
+### 2.4 Consistent prop vocabulary
+
+The same idea goes by different names:
+
+| Concept | Current names |
+|---|---|
+| The look preset | `style` (Captions, Counter, LogoReveal, MousePointer, TextReveal), `kind` (AppFrame, Backdrop, Meter, Selection, Waveform) |
+| The arrangement | `layout` (LowerThird, LogoReveal, TitleCard) |
+| The behaviour | `mode` (CardStack) |
+| Text size | `fontSize` (8 components), `nameSize` (LowerThird, LogoReveal) |
+| Typing / reading speed | `cps` (Terminal, TextReveal), `readCps` (ChatThread) |
+| Main color override | `color` (11 components), `accent` (6), `palette` (Confetti) |
+
+A short convention in `SPEC.md` §4, applied the next time each component is touched with the
+old name kept as a deprecated alias, would do it: `style` = look, `layout` = arrangement,
+`mode` = behaviour, `kind` only for "what it is" (AppFrame browser vs terminal). Font props
+could become one shared fragment, `font: { family, size, weight }` (`fontFamily` alone appears
+in 13 components), built by a `fontProps()` schema helper next to `targetSchema()`.
+
+### 2.5 Friendlier errors
+
+Errors are already good (prop path plus message, and theme-font errors list the registered
+families). Two cheap wins:
+
+- **Did you mean.** `.strict()` reports `Unrecognized key: "lable"`. Comparing unknown keys
+ against the schema's keys (edit distance ≤ 2) in `bind` gives `lable → label?`.
+- **Name the component instance.** Prefix errors with the `id` when one is given
+ (`Captions#intro: invalid props`), so a composition with five Captions points at the right
+ one.
+
+### 2.6 Examples as code, and docs that travel with the source
+
+- `meta.example` is a string, so it is never typechecked. An `example.ts` per component
+ (default export: a function returning the node) can be typechecked, rendered by the gallery
+ (1.5), and pasted into docs.
+- `SPEC.md` is 1,951 lines combining spec, changelog and decisions, and its status line still
+ says "M0 implemented… no components yet". Each component folder could get a short
+ `README.md` (summary, props table generated from the schema, parts, cues, two recipes) that
+ `framefields add` copies with the source, so users get the docs next to the file they own.
+ SPEC.md then keeps the contract and the history.
+- §9.7 says `framefields-compose/SKILL.md` should gain a generated Components section. It
+ hasn't yet: only the setup skill (`framefields`) mentions components.
+
+### 2.7 Composing timelines
+
+Cues and `span` are the right primitives, but chaining still means arithmetic at the call site
+(`at: title.span.end + 6`). Two tiny helpers would read better:
+
+```ts
+const title = TitleCard({ … });
+const sub = TextReveal({ at: after(title, 6), … }); // span.end + gap
+const sfx = onCues(pointer.cues.clicks, (c) => Layer.audio(click, { startFrame: c.frame }));
+```
+
+---
+
+## 3. Code elegance
+
+### 3.1 A missing `core/keys.ts`
+
+The largest source of repetition is keyframe bookkeeping:
+
+- `ascending()` is defined 8 times (Spotlight, CodeBlock, Terminal, ChatThread, TouchPoint,
+ WordCycle, Meter, CardStack), **with two different behaviours**. Most pop earlier keys while
+ the last one is `>=` the new frame, which silently drops keys if the input isn't already
+ sorted. WordCycle de-duplicates by frame and then sorts. Spotlight's copy returns `[[0, 0]]`
+ for empty input; the others return `[]`. This is the kind of divergence that turns into a
+ bug when someone copies the wrong one.
+- `round()` exists 6 times with precisions of 2, 3 and 4 decimals.
+- `valueAt()` (sample a keyed track) exists in BeforeAfter and WordCycle.
+- Per-node / per-prop accumulators are written three ways: LowerThird's
+ `Map<node, Map<prop, keys>>`, CodeBlock's `Track` class
+ ([code-block/plan.ts:82](src/code-block/plan.ts:82)), and Toasts' `springTrack`, which
+ lives in a component but is re-exported from the package index.
+
+Proposal: one module, unit-tested once.
+
+```ts
+// core/keys.ts
+export class Track { to(start, end, value, ease?): this; set(frame, value): this; keys(): KeyframeTuple[] }
+export class KeyBook { // node × prop → merged, sorted, one animate() per node
+ key(node, prop, keys): this;
+ track(node, prop, initial): Track;
+ apply(): void;
+}
+export function ascending(keys): KeyframeTuple[]; // one rule: later key on the same frame wins, sorted
+export function valueAt(keys, frame): number; // matches the renderer, eases included
+export const round = (v: number, places = 3) => …;
+```
+
+`springTrack` moves to `core/bake.ts` beside `springKeys`. LowerThird's 25-line accumulator
+and its `prop as "x"` cast ([lower-third/index.ts:448](src/lower-third/index.ts:448)) become
+`book.key(node, "y", …)` and `book.apply()`.
+
+### 3.2 Color helpers
+
+There are five hex parsers: `tint` (CodeBlock), a transparent-stop helper (Backdrop),
+`withAlpha` (Selection), `mix` (Waveform) and `luminance` (theme). They disagree on non-hex
+input. CodeBlock and Selection return the color unchanged, Waveform returns the first color,
+and Backdrop returns `rgba(0,0,0,0)`. That last one means a theme using `rgb()` or `oklch()`
+gets gradients that fade through black. A `core/color.ts` with `parse`, `withAlpha`, `mix`,
+`transparent(c)`, `isLight` and the existing `contrastRatio`, accepting hex, `rgb[a]()` and
+named colors, fixes the inconsistency and replaces the light/dark contrast checks in Annotate,
+AppFrame and MousePointer.
+
+### 3.3 `noUncheckedIndexedAccess` noise
+
+Installed copies typecheck under strict user settings (good), but the cost is about 68
+`as KeyframeTuple` / `as number` casts like `(out[out.length - 1] as KeyframeTuple)[0]`. Small
+helpers (`last(arr)`, `pairs(arr)` for neighbouring keys), plus `for…of` / `entries()`, remove
+most of them. The keyed props would also benefit from `LayerAnimation.keys` accepting
+`AnimatableProp` (a string union) instead of needing the `as "x"` cast.
+
+### 3.4 Shared layout helpers
+
+`safeArea()` is duplicated in Captions and LowerThird, and the frame-size default is
+duplicated ten times (2.3). A `core/layout.ts` with `safeArea(frame, area)`,
+`anchorIn(rect, anchor)` and `fitText(measure, text, maxWidth)` covers them and gives future
+components (Timeline, StatCard, BentoGrid) the same footing.
+
+### 3.5 Big `build()` functions
+
+| File | Lines | Has a pure `plan.ts` |
+|---|---|---|
+| text-reveal/index.ts | 1,134 | partly |
+| mouse-pointer/index.ts | 785 | yes |
+| chat-thread/index.ts | 736 | no |
+| captions/index.ts | 659 | parse / phrases |
+| app-frame/index.ts | 599 | no |
+| code-block/index.ts | 557 | yes |
+
+The split that works best here (MousePointer, Terminal, FocusZoom, Counter) is a pure planner
+(props → timeline of plain data, tested without nodes) and a thin builder (timeline → nodes).
+ChatThread (message timing, scroll positions, bubble rects), Toasts (stack solving) and
+CardStack (slot poses per move) would read and test better that way. LowerThird's
+four-way `switch` would read better as a `layouts` table of small functions returning
+`{ plates, extras }`.
+
+### 3.6 Smaller things
+
+- **Hand-maintained lists.** `src/index.ts` (305 lines of re-exports) and the `cases` table in
+ `ids.test.ts` have to be edited for every new component. A test that globs `*/index.ts` and
+ checks each is exported and present in `ids.test.ts` makes forgetting impossible.
+- **Magic ratios.** Geometry such as `padX = nameSize * 0.55` is reasonable but unexplained.
+ CardStack's named `SHRINK` and LowerThird's `CAP_HEIGHT` are the pattern to follow.
+- **Cue data shapes.** Cue payloads vary (`{ frame, index }`, `{ frame, end, text }`,
+ `{ frame, point, target }`). That is fine, but the `end` convention for ranged cues should
+ be written into `Cue`'s type (`RangeCue = Cue & { end: number }`), since `offsetCues` already
+ special-cases it.
+- **FocusZoom** is the only component without an `index.test.ts` (its planner is tested; the
+ builder isn't).
+
+---
+
+## 4. Ten components that would add the most value
+
+Scored with the §6 criteria (demand, leverage, foundation, hard by hand; 1–3 each). Four are
+3D. None overlap the non-goals: charts are wrapped, not rebuilt, and there are no transitions
+or whole-frame looks.
+
+| # | Component | 3D | D | L | F | H | Total |
+|---|---|---|---|---|---|---|---|
+| A | Globe | ✓ | 3 | 3 | 2 | 3 | **11** |
+| B | ProductTurntable | ✓ | 3 | 3 | 2 | 2 | **10** |
+| C | PhysicsPile | ✓ | 2 | 3 | 3 | 3 | **11** |
+| D | ExplodedStack (the `LayerDiagram` backlog item) | ✓ | 2 | 3 | 2 | 3 | **10** |
+| E | Keystrokes | | 3 | 2 | 1 | 2 | 8 |
+| F | Marquee | | 3 | 2 | 2 | 2 | 9 |
+| G | StatCard | | 3 | 2 | 2 | 2 | 9 |
+| H | Timeline | | 2 | 2 | 2 | 3 | 9 |
+| I | BentoGrid | | 3 | 2 | 2 | 2 | 9 |
+| J | Steps | | 2 | 1 | 1 | 2 | 6 |
+
+Suggested waves: **4a** A, C, F, G (the two most distinctive 3D pieces, plus the two most
+reused 2D ones); **4b** B, D, I, E; **4c** H, J.
+
+### A. Globe (3D)
+
+A lit globe with a dotted or flat land mask that rotates to bring each target city to the
+front, draws great-circle arcs between them and pins labels. It's the SaaS "we're global" shot
+and the travel-route explainer.
+
+- **Props:** `stops: { at?, lat, lon, label? }[]`, `arcs: "chain" | "hub" | [from, to][]`,
+ `land: "dots" | "solid" | image`, `atmosphere`, `tilt`, `radius`.
+- **Cues:** `arrivals`, `arcs` (`{ frame, end }`), `pins`.
+- **Engine use:** `Layer3D.sphere` with a land texture or instanced dots, `Path3D` arcs drawn
+ on with `trimEnd`, light from `Lighting.studio`, a fresnel atmosphere as a slightly larger
+ glass sphere. Rotation is solved offline as slerp between stop orientations and baked.
+- **Host additions:** `sphere`, `path3d`, `light`.
+
+### B. ProductTurntable (3D)
+
+Any GLB / GLTF (or a built-in phone or laptop with a video screen slot) on a studio turntable,
+with camera moves chosen by name: `orbit`, `hero` (low push-in), `reveal` (rise from
+silhouette), `inspect` (stops at named angles).
+
+- **Props:** `model: string | "phone" | "laptop"`, `screen?: media`, `shots: { at, move, to? }[]`,
+ `environment`, `floor: "shadow" | "reflect" | false`.
+- **Cues:** `shots`, `settles`.
+- **Engine use:** `Layer.glb` / `Layer.gltf`, `Layer.environment`, a shadow catcher plane,
+ `Layer.camera` keys baked with minimum-jerk easing, the same camera math as FocusZoom.
+ This is DeviceFrame's real 3D version (its M8 deviation).
+- **Host additions:** `model`, `camera`, `environment`.
+
+### C. PhysicsPile (3D)
+
+Words, logos or cards dropped, thrown or poured into a scene, where they collide and settle.
+Example 28 builds this by hand with glass word cards. Frame-exact because Rapier runs
+deterministically on the CPU.
+
+- **Props:** `items: (string | media | { shape })[]`, `emit: "drop" | "throw" | "pour"`,
+ `container: "floor" | "box" | "bowl"`, `material: "glass" | "matte" | "chrome"`, `gravity`,
+ `seed`.
+- **Cues:** `impacts` (`{ frame, index, strength }`, ready for SFX), `settled`.
+- **Engine use:** `Physics.world` simulated offline and baked to per-body transforms,
+ `Layer3D.roundedBox` / `extrudedText` bodies, glass materials. Impacts drive `pulseKeys` for
+ camera shake or sound.
+- **Host additions:** `physics` (step a world and return baked transforms), `roundedBox`.
+ This also builds the bake-from-simulation foundation that a physics CardStack (an M8
+ deviation) could reuse.
+
+### D. ExplodedStack (3D)
+
+The architecture-explainer shot: a stack of plates (layers of a product, a network stack, a
+PCB) that separates in perspective, highlights one layer at a time with a leader-line label,
+and collapses back.
+
+- **Props:** `layers: { label, color?, content?: LayoutNode, height? }[]`,
+ `focus: { at, layer }[]`, `gap`, `camera: "iso" | "front" | "orbit"`.
+- **Cues:** `explode`, `focus`, `collapse`.
+- **Engine use:** `Layer3D.roundedBox` plates with 2D content rendered onto their top faces,
+ the Callout leader logic projected from 3D anchors, depth-of-field blur on unfocused plates.
+- **Host additions:** `roundedBox`, `project(point3d) → [x, y]` for labels.
+
+### E. Keystrokes
+
+On-screen keyboard shortcuts (⌘ K, ⇧ ⌥ P, Ctrl C) as keycaps that press in sync with a
+Terminal, CodeBlock or MousePointer. Every dev-tool demo needs this, and keeping the press
+timing in sync by hand is fiddly.
+
+- **Props:** `combos: { at, keys: string[] }[]`, `style: "caps" | "flat" | "minimal"`,
+ `corner`, `size`.
+- **Cues:** `presses`, `releases`.
+- **Notes:** modifier glyphs (⌘ ⌥ ⇧ ⌃ ⏎ ⌫) are drawn as vector paths, since common fonts lack
+ them (the same lesson as Terminal's drawn spinners). Keycaps use the elevation tokens (1.1)
+ with a 2-frame press-down and spring-back. `fromTerminal(terminal.cues.keys)` maps an
+ existing script to combos.
+
+### F. Marquee
+
+Loop-exact scrolling rows: the "trusted by" logo wall, a ticker of quotes, a band of
+features. The loop period divides the scene, the same as Backdrop.
+
+- **Props:** `rows: (string | media)[][]`, `speed`, `direction` per row, `gap`,
+ `fade: "edges" | false`, `tilt` (perspective band), `pauseOn?: { at, index }[]`.
+- **Cues:** `loops`, `pauses`.
+- **Engine use:** measured text and media widths, a clip with a gradient edge matte, and
+ Backdrop's whole-period loop keys. The fade matte reuses Spotlight's `host.matte`.
+
+### G. StatCard
+
+A KPI tile: label, a Counter value, a delta badge (▲ 12 % in `positive` / `negative`), and an
+optional sparkline that draws on. The most-copied piece in data stories (example 23). It
+*wraps* `Layer.chart`, as §1.2 allows.
+
+- **Props:** `label`, `value`, `from?`, `format`, `delta?`, `spark?: number[]`,
+ `layout: "tile" | "inline" | "hero"`.
+- **Cues:** `counted`, `spark` (`{ frame, end }`).
+- **Composes:** Counter, Meter (optional ring), `Layer.chart` line. Several StatCards drop
+ straight into a BentoGrid.
+
+### H. Timeline
+
+Milestones along a horizontal or vertical line: the line draws on, dots pop as it reaches
+them, dates and labels rise, and the camera pans when the line outgrows the frame. Roadmaps,
+company history, "how it works" steps.
+
+- **Props:** `events: { label, date?, body?, icon? }[]`,
+ `orientation: "horizontal" | "vertical"`, `pace` (frames per event or `"even"`),
+ `follow: boolean`.
+- **Cues:** `reached` (`{ frame, index }`).
+- **Engine use:** `drawOn` for the line, the per-event pacing that Annotate already does by
+ stroke length, and FocusZoom's view-rect solver for `follow`.
+
+### I. BentoGrid
+
+A launch-film feature grid: tiles of different spans assemble in a staggered order, each with
+an icon, title, short body and an optional slot (media, StatCard, any node), then focus moves
+tile to tile.
+
+- **Props:** `tiles: { span: [cols, rows], title, body?, icon?, content? }[]`, `columns`,
+ `gap`, `order: StaggerOrder`, `focus?: { at, tile }[]`.
+- **Cues:** `landed`, `focus`.
+- **Engine use:** grid packing solved offline into rects (so every tile is a valid `Target`
+ for MousePointer / Spotlight), `staggerRanks`, surface elevation, and the `tilt` preset per
+ tile.
+
+### J. Steps
+
+A numbered checklist or onboarding flow: steps appear, the active one is emphasised, a
+connecting line fills, and each completed step turns into a drawn check. Tutorials and setup
+walkthroughs.
+
+- **Props:** `steps: { title, body? }[]`, `active: { at, step }[]` or `every`,
+ `layout: "list" | "row"`.
+- **Cues:** `started`, `completed`.
+- **Composes:** Toasts' drawn check, Meter's fill timing, LowerThird's plate slide. Low
+ leverage on its own, but it's cheap and comes up constantly.
+
+### Host growth these imply
+
+The four 3D components share most of their needs: `sphere`, `roundedBox`, `model`, `camera`,
+`light`, `environment`, `path3d`, `project`, and `physics` for C. Adding them in one
+milestone keeps `host.ts` coherent and lets the tree-shake table budget the 3D path once. An
+`AnimatableNode` for 3D containers already exists in framefields, so these would be thin
+pass-throughs, like `extrudedText`.
diff --git a/packages/components/SPEC.md b/packages/components/SPEC.md
index 6a9cf5c3..d4f72b15 100644
--- a/packages/components/SPEC.md
+++ b/packages/components/SPEC.md
@@ -1,6 +1,6 @@
# framefields components — specification & plan
-Status: **M0 implemented** (foundations; no components yet) · Branch: `feat/components` · Owner: framefields core
+Status: **M9 delivered** (26 components, installed from the registry) · 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.
@@ -1805,7 +1805,7 @@ Deviations from the §8.1 rows:
feathered. Use `ellipse` for a soft light.
- Confetti paper doesn't flip in 3D: GPU particles have no per-particle rotation, so the
flutter comes from curl noise.
-- Emoji need an emoji-capable font; the default theme fonts have none.
+- Emoji need a color emoji font registered (`FontManager.registerEmojiFont`); the theme fonts have none.
## 18. M7 delivery notes
@@ -1949,3 +1949,118 @@ the cap lift it:
- Backdrop's loop bound goes from 120 to 960 keys per track.
- WordCycle no longer throws past 120 keys.
- Selection no longer thins its keys.
+
+## 21. Toolkit polish (2026-10, after the review in `REPORT.md`)
+
+Code shared by many components moved into the toolkit, and the theme gained the tokens
+components had been hard-coding.
+
+- **`core/keys.ts`**: `ascending` (sort; the last key on a frame wins), `supersede`
+ (timeline semantics: a key earlier than the previous one drops the later ones, as
+ springs that retarget need), `valueAt` (eased, like the renderer), `round`, `last`,
+ `Track` (from CodeBlock) and `KeyBook` (keys per node and prop, one `animate()` each).
+ Eight local `ascending` copies had two different behaviours. ChatThread and Spotlight
+ relied on the dropping one and now call `supersede`.
+- **`core/color.ts`**: `parseColor` (hex, `rgb()` / `rgba()`, a few names), `withAlpha`,
+ `transparent`, `mix`, `luminance`, `contrastRatio` (moved from `theme.ts`), `isLight`,
+ `inkOn`. It replaces five hex parsers. Backdrop's turned non-hex colors into
+ transparent black.
+- **`core/layout.ts`**: `safeArea(canvas, area, insets)` with `SAFE_INSETS.titles` /
+ `.captions` (the Captions and LowerThird copies, unchanged numbers).
+- **`core/surface.ts`**: `elevationStyle`, `elevate` and `surfaceFill` (a 5 % top sheen on
+ dark themes). They're used by LowerThird, Toasts, Callout, CardStack and ChatThread
+ bubbles. A light top edge is a white inner shadow at 270° with a `normal` blend: the
+ default multiply blend makes a light color invisible, and 90° shades the bottom edge.
+- **Theme:** `mode`, `color.shadow`, `weight`, `elevation`, `motion.spring`
+ (settle / base / pop) and `syntax`. `defineTheme` derives `mode` (and the matching
+ elevation) from a new `bg` when the input gives no mode. Font weights in components
+ read `theme.weight`. CodeBlock's number and type colors deepen on light themes.
+- **Contract:** a `canvas` base prop (`ctx.canvas`, default 1920 × 1080 × scale) replaces
+ ten copies of that default. MousePointer's `area` defaults to it. (It's named `canvas`
+ because Terminal and CodeBlock already have a `frame` prop.) Unknown-prop errors suggest
+ the nearest prop (`"lable" → "label"`) and name the instance (`Probe#intro`). Motion
+ presets take `blur` (stage motion blur; on for `slide-*`). Nodes expose `partNames`.
+ `withDefaults({ fps, canvas, theme, seed })` wraps factories, and `after(node, gap)`
+ chains from a component's end. Both are on the framefields root too.
+- **Meta stays true:** `meta.test.ts` builds every case in `test/cases.ts` (shared with
+ `ids.test.ts`) and checks that cue names equal `meta.cues` and that every part matches
+ `meta.parts` (`<n>` patterns). It found nine components whose metas listed only `-0`
+ examples or missed a part. `build-meta.ts` writes each component's props (type, default,
+ required, JSDoc description) into `components.json`, and the base props into
+ `base-props.json`.
+- **ChatThread reactions are text.** The drawn heart is gone: filled paths aren't
+ anti-aliased, so a small one looked jagged. Every reaction is now a text node, and emoji
+ draw in color from the registered emoji font (`FontManager.registerEmojiFont`, e.g. Noto
+ Color Emoji; framefields ships none). `"heart"` is shorthand for ❤️. A lone emoji is set
+ at 0.74 em, because emoji draw past their advance. `m5.render.test.ts` checks the heart
+ draws in color.
+- **Gallery:** `pnpm --filter framefields gallery [Name …]` renders a set of components
+ under every theme into `renders/gallery/` with an `index.html` contact sheet.
+- **Budgets:** the shared contract grew (suggestions, canvas, blur), so MousePointer goes
+ 66 → 68 KB, TextReveal 58 → 60 KB and FocusZoom 40 → 42 KB.
+
+## 22. Fonts installed with components
+
+Components that draw with fonts beyond the theme's declare them in `meta.ts`
+(`fonts: [{ font: "emoji", why }]`, kept on the registry item). ChatThread and Captions
+ask for `emoji`.
+
+- **`framefields add`** collects the fonts its components ask for and installs each one
+ once (`cli/fonts.ts`). The catalog pins every file by URL, size and SHA-256, with its
+ license next to it. `emoji` is Noto Color Emoji v2.051 (10,673,480 bytes, OFL-1.1, the
+ same bytes as `packages/renderer/src/assets/NotoColorEmoji.ttf`). A download that doesn't
+ match its pin writes nothing. Fonts go to `assets/fonts/` (`--fonts-dir`) and are
+ recorded under `fonts` in `framefields.json`. A role already listed there counts as
+ installed, so pointing `fonts.emoji` at another file keeps it. A different file at the
+ target path needs `--overwrite`. `--no-fonts` skips the download and says how to install
+ later. Inside a Git repo whose `.gitattributes` doesn't send `.ttf` to LFS, `add` suggests
+ `git lfs track`.
+- **`<components>/fonts.ts`** is generated from `framefields.json`: `registerFonts()` calls
+ `FontManager.registerEmojiFont(asset(…))` with paths relative to the file
+ (`new URL(path, import.meta.url)`, so Node and the browser preview both resolve them). It's
+ rewritten when fonts change, but a `fonts.ts` without the generated marker line is the
+ user's and is left alone (the registration lines are printed instead).
+- **`framefields fonts add <role…>` / `fonts list`** do the same for projects that use
+ emoji in plain `Layer.text`.
+- **Lint:** `lintComposition(config, { emojiFont })` reports `missing_emoji_font` (a
+ warning naming the text layers and the fix) when `emojiFont` is false and any text or span
+ has emoji, using the renderer's emoji test. `Composition.lint()` passes
+ `FontManager.hasEmojiFont()`, and each composition's first `renderFrame` / `renderVideo`
+ prints the same warning once. Callers that don't know about fonts (omitting `emojiFont`)
+ aren't told.
+- The package still ships no fonts: a font in the npm tarball would cost every install
+ 10 MB, used or not.
+
+## 23. `framefields init`
+
+`npx framefields init [dir]` (`src/cli/init.ts`, templates in `src/cli/templates.ts`) writes
+the project layout the setup skill describes, so a project starts the same way every time:
+
+- `package.json`: `type: "module"`, the scripts (`typecheck`, `frames`, `grid`, `preview`,
+ `render`), `framefields` at this package's version, the dev tools, `packageManager` from
+ `npm_config_user_agent` (or `--pm`), and the install-script approvals. Only skia-canvas
+ runs its script; sharp, webgpu, onnxruntime-node, node-av, esbuild and protobufjs are
+ denied (protobufjs was missing from the skill's list, and pnpm warned about it).
+- `tsconfig.json`, `src/theme.ts`, `src/film.ts`, `src/render.ts`, `README.md`,
+ `assets/footage/`, `.gitignore`, the LFS `.gitattributes`, `framefields.json`. `render.ts`
+ drops a `--` argument, because `npm run frames -- 0 30` needs it and pnpm passes it
+ through.
+- **Fonts:** the catalog gained `sans` (Inter) and `mono` (JetBrains Mono), the families
+ the built-in themes name. Both are pinned to google/fonts commit `e7db6ca` and match the
+ repo's `assets/fonts` byte for byte. Their entries register as text families
+ (`FontManager.register({ family, source })`), and Terminal and CodeBlock declare `mono`.
+ `init` installs both (`--no-fonts` skips them, `--emoji` adds emoji), and the generated
+ `src/components/fonts.ts`, which `theme.ts` calls, is the project's one registration
+ point.
+- **Never overwrites.** Existing files are reported `unchanged`. `package.json` gains only
+ missing fields, scripts and dependencies (one listed in either dependency block counts as
+ present), and `.gitignore` / `.gitattributes` gain only missing lines. A
+ `"type": "commonjs"` package is refused with the fix.
+- **Git:** `git init` when the folder isn't in a repository (`--no-git` skips it), and a
+ note to run `git lfs install`, or to install Git LFS when `git lfs` is missing.
+ `--install` runs the package manager's install, and prints the next steps either way.
+- **Tests:** `init.test.ts` covers a new project, a merge into an existing one (twice:
+ the second run changes nothing), CommonJS, emoji / no-git / install with bun, failures,
+ and the package-manager detection. It also checks that every TypeScript template parses.
+ End to end, `init --pm pnpm --install` in an empty folder, then `pnpm typecheck` and
+ `pnpm frames -- 0 45`, renders the title in Inter with a silent install.
diff --git a/packages/components/scripts/build-meta.test.ts b/packages/components/scripts/build-meta.test.ts
index b2b57fb1..99a50025 100644
--- a/packages/components/scripts/build-meta.test.ts
+++ b/packages/components/scripts/build-meta.test.ts
@@ -2,7 +2,7 @@ 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";
+import { baseProps, collectMeta } from "./build-meta.js";
const meta = (name: string) =>
`export default ${JSON.stringify({ name, summary: "s", tags: [], parts: [], cues: [], example: "", since: "M1" })};`;
@@ -34,4 +34,19 @@ describe("collectMeta", () => {
collectMeta(fixture({ a: meta("Same"), b: meta("Same") })),
).rejects.toThrow(/Duplicate/);
});
+
+ it("documents each component's props from its schema and JSDoc", async () => {
+ const lower = (await collectMeta()).find((m) => m.name === "LowerThird");
+ const props = new Map(lower?.props?.map((p) => [p.name, p]));
+ expect(props.get("name")).toMatchObject({ type: "string", required: true });
+ expect(props.get("layout")).toMatchObject({
+ type: '"bar" | "stacked" | "tag" | "line"',
+ default: "bar",
+ required: false,
+ });
+ expect(props.get("stay")?.description).toMatch(/Stay on screen/);
+ const base = new Map(baseProps().map((p) => [p.name, p]));
+ expect(base.get("canvas")?.description).toMatch(/Composition size/);
+ expect(base.get("at")?.type).toBe("number");
+ });
});
diff --git a/packages/components/scripts/build-meta.ts b/packages/components/scripts/build-meta.ts
index 63487956..ff27eff3 100644
--- a/packages/components/scripts/build-meta.ts
+++ b/packages/components/scripts/build-meta.ts
@@ -1,18 +1,27 @@
/**
* Collects every component's `meta.ts` (default export) into
- * `dist/components.json`: the list docs and the skills generator read.
+ * `dist/components.json`: the list docs and the skills generator read. Each
+ * entry also carries its props (type, default, description: see
+ * `props-doc.ts`); the props every component shares go to
+ * `dist/base-props.json`.
* 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 { z } from "zod";
+import { basePropsSchema } from "../src/core/contract.js";
import type { ComponentMeta } from "../src/core/meta.js";
+import { type PropDoc, propComments, propDocs } from "./props-doc.js";
+
+/** A component's meta plus its documented props. */
+export type CollectedMeta = ComponentMeta & { props?: PropDoc[] };
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[] = [];
+export async function collectMeta(src = SRC): Promise<CollectedMeta[]> {
+ const metas: CollectedMeta[] = [];
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");
@@ -23,7 +32,15 @@ export async function collectMeta(src = SRC): Promise<ComponentMeta[]> {
default?: ComponentMeta;
};
if (!mod.default) throw new Error(`${file} has no default export`);
- metas.push(mod.default);
+ const index = join(src, entry.name, "index.ts");
+ metas.push(
+ existsSync(index)
+ ? {
+ ...mod.default,
+ props: await componentProps(index, mod.default.name),
+ }
+ : mod.default,
+ );
}
const names = new Set<string>();
for (const m of metas) {
@@ -34,6 +51,35 @@ export async function collectMeta(src = SRC): Promise<ComponentMeta[]> {
return metas.sort((a, b) => a.name.localeCompare(b.name));
}
+/** Props of the definition `index` exports under `name`. */
+async function componentProps(index: string, name: string): Promise<PropDoc[]> {
+ const mod = (await import(pathToFileURL(index).href)) as Record<
+ string,
+ unknown
+ >;
+ const definition = Object.values(mod).find(
+ (v): v is { name: string; props: () => Record<string, z.ZodType> } =>
+ typeof v === "object" &&
+ v !== null &&
+ (v as { name?: unknown }).name === name &&
+ typeof (v as { props?: unknown }).props === "function",
+ );
+ if (!definition)
+ throw new Error(`${index} exports no definition named ${name}`);
+ return propDocs(definition.props(), propComments(index));
+}
+
+/** The props every component accepts. */
+export function baseProps(): PropDoc[] {
+ return propDocs(
+ basePropsSchema().shape as Record<string, z.ZodType>,
+ propComments(
+ fileURLToPath(new URL("../src/core/contract.ts", import.meta.url)),
+ "BaseProps",
+ ),
+ );
+}
+
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
const metas = await collectMeta();
const out = fileURLToPath(new URL("../dist", import.meta.url));
@@ -42,5 +88,9 @@ if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
join(out, "components.json"),
`${JSON.stringify(metas, null, "\t")}\n`,
);
+ writeFileSync(
+ join(out, "base-props.json"),
+ `${JSON.stringify(baseProps(), null, "\t")}\n`,
+ );
console.log(`components.json: ${metas.length} component(s)`);
}
diff --git a/packages/components/scripts/build-registry.ts b/packages/components/scripts/build-registry.ts
index 8d4f70d4..b0c2379f 100644
--- a/packages/components/scripts/build-registry.ts
+++ b/packages/components/scripts/build-registry.ts
@@ -14,7 +14,7 @@
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
-import type { ComponentMeta } from "../src/core/meta.js";
+import type { ComponentMeta, FontNeed } from "../src/core/meta.js";
import { collectMeta } from "./build-meta.js";
const SRC = fileURLToPath(new URL("../src", import.meta.url));
@@ -41,6 +41,8 @@ export interface RegistryEntry
export interface RegistryItem extends RegistryEntry {
parts: readonly string[];
cues: readonly string[];
+ /** Fonts to install with it (`framefields add` fetches them). */
+ fonts?: readonly FontNeed[];
files: RegistryFile[];
}
@@ -183,6 +185,7 @@ export function registryItem(
example: meta.example,
parts: meta.parts,
cues: meta.cues,
+ ...(meta.fonts && { fonts: meta.fonts }),
registryDependencies: [...deps].sort(),
files,
};
diff --git a/packages/components/scripts/props-doc.ts b/packages/components/scripts/props-doc.ts
new file mode 100644
index 00000000..cf90e69b
--- /dev/null
+++ b/packages/components/scripts/props-doc.ts
@@ -0,0 +1,138 @@
+/**
+ * A component's props as documentation: name, a short type, default and
+ * whether it's required come from its zod schema; the description comes from
+ * the JSDoc comment above the prop in `index.ts` (zod drops comments, so the
+ * source is read with the TypeScript parser).
+ */
+import { readFileSync } from "node:fs";
+import ts from "typescript";
+import { z } from "zod";
+
+export interface PropDoc {
+ name: string;
+ /** A TypeScript-like summary: `number`, `"bar" | "tag"`, `string[]` … */
+ type: string;
+ required: boolean;
+ default?: unknown;
+ description?: string;
+}
+
+interface JsonSchema {
+ type?: string | string[];
+ enum?: unknown[];
+ const?: unknown;
+ items?: JsonSchema;
+ anyOf?: JsonSchema[];
+ oneOf?: JsonSchema[];
+ properties?: Record<string, JsonSchema>;
+ default?: unknown;
+}
+
+/** Docs for every prop in `shape`, in declaration order. */
+export function propDocs(
+ shape: Record<string, z.ZodType>,
+ descriptions: Record<string, string> = {},
+): PropDoc[] {
+ return Object.entries(shape).map(([name, schema]) => {
+ const json = z.toJSONSchema(schema, {
+ unrepresentable: "any",
+ io: "input",
+ }) as JsonSchema;
+ const doc: PropDoc = {
+ name,
+ type: typeOf(json),
+ required: !schema.safeParse(undefined).success,
+ };
+ if (json.default !== undefined) doc.default = json.default;
+ const description = descriptions[name] ?? schema.description;
+ if (description) doc.description = description;
+ return doc;
+ });
+}
+
+function typeOf(s: JsonSchema, depth = 0): string {
+ if (s.const !== undefined) return JSON.stringify(s.const);
+ if (s.enum) return s.enum.map((v) => JSON.stringify(v)).join(" | ");
+ const union = s.anyOf ?? s.oneOf;
+ if (union)
+ return [...new Set(union.map((u) => typeOf(u, depth + 1)))].join(" | ");
+ const t = Array.isArray(s.type) ? s.type.join(" | ") : s.type;
+ if (t === "integer") return "number";
+ if (t === "array")
+ return s.items ? `${wrap(typeOf(s.items, depth + 1))}[]` : "unknown[]";
+ if (t === "object") {
+ if (!s.properties || depth > 0) return "object";
+ const keys = Object.keys(s.properties);
+ return `{ ${keys.join(", ")} }`;
+ }
+ return t ?? "unknown";
+}
+
+const wrap = (t: string) => (t.includes(" ") ? `(${t})` : t);
+
+/**
+ * JSDoc text above each prop of the `props: () => ({ … })` object in a
+ * component's source (or of the members of interface `iface`), by prop name.
+ */
+export function propComments(
+ file: string,
+ iface?: string,
+): Record<string, string> {
+ const source = ts.createSourceFile(
+ file,
+ readFileSync(file, "utf8"),
+ ts.ScriptTarget.Latest,
+ true,
+ );
+ const out: Record<string, string> = {};
+ const visit = (node: ts.Node) => {
+ if (iface && ts.isInterfaceDeclaration(node) && node.name.text === iface) {
+ for (const member of node.members) {
+ const text = jsDoc(member, source);
+ if (text && member.name) out[member.name.getText(source)] = text;
+ }
+ return;
+ }
+ if (
+ !iface &&
+ ts.isPropertyAssignment(node) &&
+ node.name.getText(source) === "props" &&
+ ts.isArrowFunction(node.initializer)
+ ) {
+ let body: ts.Node = node.initializer.body;
+ while (ts.isParenthesizedExpression(body)) body = body.expression;
+ if (ts.isObjectLiteralExpression(body)) {
+ for (const prop of body.properties) {
+ const text = jsDoc(prop, source);
+ if (text && prop.name) out[prop.name.getText(source)] = text;
+ }
+ return;
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ return out;
+}
+
+function jsDoc(node: ts.Node, source: ts.SourceFile): string | undefined {
+ const ranges = ts.getLeadingCommentRanges(
+ source.getFullText(),
+ node.getFullStart(),
+ );
+ const last = ranges?.filter((r) =>
+ source
+ .getFullText()
+ .slice(r.pos, r.pos + 3)
+ .startsWith("/**"),
+ );
+ const range = last?.[last.length - 1];
+ if (!range) return undefined;
+ return source
+ .getFullText()
+ .slice(range.pos + 3, range.end - 2)
+ .split("\n")
+ .map((l) => l.replace(/^\s*\*\s?/, "").trim())
+ .filter(Boolean)
+ .join(" ");
+}
diff --git a/packages/components/src/annotate/index.ts b/packages/components/src/annotate/index.ts
index e70e7516..ba95d42d 100644
--- a/packages/components/src/annotate/index.ts
+++ b/packages/components/src/annotate/index.ts
@@ -32,7 +32,7 @@ import {
resolveTarget,
type Target,
} from "../core/targets.js";
-import { contrastRatio, themeFrames } from "../core/theme.js";
+import { themeFrames } from "../core/theme.js";
import { scaleFrames } from "../core/timing.js";
export const MARKS = [
@@ -319,9 +319,7 @@ export const annotate = /* @__PURE__ */ defineComponent({
const drawn = Math.max(...windows.map((w) => w.end));
// ── Nodes ────────────────────────────────────────────────────────
- const lightBg =
- (contrastRatio(theme.color.bg, "#000000") ?? 0) >
- (contrastRatio(theme.color.bg, "#ffffff") ?? 0);
+ const lightBg = theme.mode === "light";
// The shapes' box must hold every stroke, or the renderer clips it.
const margin = pad * 4 + strokeW * 4;
const extentX = Math.max(b.x + b.width, ...reach.map((p) => p[0])) + margin;
diff --git a/packages/components/src/app-frame/index.ts b/packages/components/src/app-frame/index.ts
index 93a414d8..8619b74a 100644
--- a/packages/components/src/app-frame/index.ts
+++ b/packages/components/src/app-frame/index.ts
@@ -14,7 +14,6 @@ import { z } from "zod";
import { defineComponent } from "../core/contract.js";
import type { Animatable } from "../core/host.js";
import type { Vec2 } from "../core/path.js";
-import { contrastRatio } from "../core/theme.js";
const KINDS = ["window", "browser", "terminal", "minimal"] as const;
export type AppFrameKind = (typeof KINDS)[number];
@@ -122,8 +121,7 @@ export const appFrame = /* @__PURE__ */ defineComponent({
const height = ctx.requested.height ?? 900 * s;
const dark =
props.appearance === "dark" ||
- (props.appearance === undefined &&
- (contrastRatio(theme.color.bg, "#000000") ?? 1) < 4);
+ (props.appearance === undefined && theme.mode === "dark");
const pal = dark ? PALETTES.dark : PALETTES.light;
const radius = props.radius ?? 14 * s;
const hasTabs = props.kind === "browser" && (props.tabs?.length ?? 0) > 0;
@@ -228,7 +226,7 @@ export const appFrame = /* @__PURE__ */ defineComponent({
align: "center",
fontFamily: props.kind === "terminal" ? theme.font.mono : font,
fontSize: 13 * s,
- fontWeight: 500,
+ fontWeight: theme.weight.medium,
fill: pal.muted,
}),
);
@@ -404,7 +402,7 @@ function tabStrip(
const m = host.measure(label, {
fontFamily: o.font,
fontSize,
- fontWeight: 500,
+ fontWeight: ctx.theme.weight.medium,
});
const w = Math.min(240 * o.s, Math.max(120 * o.s, m.width + 40 * o.s));
out.push(
@@ -426,7 +424,7 @@ function tabStrip(
width: w - 28 * o.s,
fontFamily: o.font,
fontSize,
- fontWeight: 500,
+ fontWeight: ctx.theme.weight.medium,
fill: active ? o.pal.text : o.pal.muted,
}),
],
diff --git a/packages/components/src/backdrop/index.ts b/packages/components/src/backdrop/index.ts
index 29db26f9..893afdcb 100644
--- a/packages/components/src/backdrop/index.ts
+++ b/packages/components/src/backdrop/index.ts
@@ -8,7 +8,7 @@
* between extremes), so a loop costs a few keys per axis.
*
* Coordinates are the frame's: the root covers the video (default
- * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.
+ * the composition `canvas`, or the given width / height) from 0, 0.
*/
import {
type KeyframeTuple,
@@ -16,8 +16,10 @@ import {
type LayoutNode,
} from "@framefields/compositions/program";
import { z } from "zod";
+import { transparent } from "../core/color.js";
import { defineComponent } from "../core/contract.js";
import type { Animatable } from "../core/host.js";
+import { round } from "../core/keys.js";
export const BACKDROP_KINDS = ["mesh", "grid", "dots", "solid"] as const;
export type BackdropKind = (typeof BACKDROP_KINDS)[number];
@@ -58,8 +60,8 @@ export const backdrop = /* @__PURE__ */ defineComponent({
build(ctx, props) {
const { host, theme, fps } = ctx;
const s = theme.scale;
- const W = ctx.requested.width ?? 1920 * s;
- const H = ctx.requested.height ?? 1080 * s;
+ const W = ctx.requested.width ?? ctx.canvas.width;
+ const H = ctx.requested.height ?? ctx.canvas.height;
const c = theme.color;
const loop = props.loop ?? fps * 10;
const colors = props.colors ?? [c.accent, c.accent2, c.highlight];
@@ -311,23 +313,6 @@ export const backdrop = /* @__PURE__ */ defineComponent({
},
});
-const round = (v: number) => Math.round(v * 1000) / 1000;
-
-/** `#rrggbb` / `#rgb` at alpha 0 (same hue, so the fade has no dark fringe). */
-function transparent(color: string): string {
- const hex = color.trim().replace(/^#/, "");
- const full =
- hex.length === 3
- ? hex
- .split("")
- .map((h) => h + h)
- .join("")
- : hex.slice(0, 6);
- if (!/^[0-9a-f]{6}$/i.test(full)) return "rgba(0,0,0,0)";
- const n = Number.parseInt(full, 16);
- return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},0)`;
-}
-
/**
* Keys for `centre + amplitude × cos(2π · cycles · f / loop + phase)` over
* `span` frames (whole loops): the value at every loop start, and at each
diff --git a/packages/components/src/backdrop/meta.ts b/packages/components/src/backdrop/meta.ts
index 3e86ecba..08cb24c5 100644
--- a/packages/components/src/backdrop/meta.ts
+++ b/packages/components/src/backdrop/meta.ts
@@ -8,8 +8,8 @@ export default defineMeta({
parts: [
"surface",
"background",
- "blob-0",
- "blob-0-x",
+ "blob-<n>",
+ "blob-<n>-x",
"pattern",
"pattern-lit",
"glow-matte",
diff --git a/packages/components/src/before-after/index.ts b/packages/components/src/before-after/index.ts
index 119cff0e..95a8f887 100644
--- a/packages/components/src/before-after/index.ts
+++ b/packages/components/src/before-after/index.ts
@@ -12,8 +12,8 @@ import {
import { z } from "zod";
import { bakeSamples } from "../core/bake.js";
import { defineComponent } from "../core/contract.js";
-import { evaluateEase } from "../core/ease.js";
import type { Animatable } from "../core/host.js";
+import { round, valueAt } from "../core/keys.js";
import { scaleFrames } from "../core/timing.js";
export interface BeforeAfterCues {
@@ -249,7 +249,7 @@ export const beforeAfter = /* @__PURE__ */ defineComponent({
const m = host.measure(text, {
fontFamily: theme.font.body,
fontSize: fs,
- fontWeight: 600,
+ fontWeight: theme.weight.semibold,
});
const w = m.width + pad * 2;
const h = m.height + pad * 0.9;
@@ -282,7 +282,7 @@ export const beforeAfter = /* @__PURE__ */ defineComponent({
y: pad * 0.45,
fontFamily: theme.font.body,
fontSize: fs,
- fontWeight: 600,
+ fontWeight: theme.weight.semibold,
fill: "#ffffff",
}),
],
@@ -313,23 +313,3 @@ export const beforeAfter = /* @__PURE__ */ defineComponent({
};
},
});
-
-const round = (v: number) => Math.round(v * 1000) / 1000;
-
-/** The split keys' value at frame `f` (each segment eased by its end key). */
-function valueAt(keys: readonly KeyframeTuple[], f: number): number {
- const first = keys[0] as KeyframeTuple;
- if (f <= (first[0] as number)) return first[1] as number;
- for (let i = 0; i < keys.length - 1; i++) {
- const [f0, v0] = keys[i] as KeyframeTuple;
- const [f1, v1, e] = keys[i + 1] as KeyframeTuple;
- if (f >= (f0 as number) && f <= (f1 as number)) {
- const t = evaluateEase(
- e as string | undefined,
- (f - (f0 as number)) / Math.max(1, (f1 as number) - (f0 as number)),
- );
- return (v0 as number) + ((v1 as number) - (v0 as number)) * t;
- }
- }
- return keys[keys.length - 1]?.[1] as number;
-}
diff --git a/packages/components/src/callout/index.ts b/packages/components/src/callout/index.ts
index 0a1503f6..f1033214 100644
--- a/packages/components/src/callout/index.ts
+++ b/packages/components/src/callout/index.ts
@@ -5,7 +5,7 @@
* snapped).
*
* Coordinates are the frame's: the root covers the video (default
- * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.
+ * the composition `canvas`, or the given width / height) from 0, 0.
*/
import {
LayerAnimation,
@@ -18,6 +18,7 @@ import { evaluateEase } from "../core/ease.js";
import type { Animatable } from "../core/host.js";
import type { Vec2 } from "../core/path.js";
import { targetSchema } from "../core/schemas.js";
+import { elevate, surfaceFill } from "../core/surface.js";
import { resolveTarget, targetPoint } from "../core/targets.js";
import { themeFrames } from "../core/theme.js";
@@ -74,8 +75,8 @@ export const callout = /* @__PURE__ */ defineComponent({
build(ctx, props) {
const { host, theme, fps } = ctx;
const s = theme.scale;
- const W = ctx.requested.width ?? 1920 * s;
- const H = ctx.requested.height ?? 1080 * s;
+ const W = ctx.requested.width ?? ctx.canvas.width;
+ const H = ctx.requested.height ?? ctx.canvas.height;
const fs = props.fontSize ?? 26 * s;
const fontFamily = props.fontFamily ?? theme.font.body;
const color = props.color ?? theme.color.accent;
@@ -97,7 +98,11 @@ export const callout = /* @__PURE__ */ defineComponent({
const padX = fs * 0.6;
const padY = fs * 0.42;
const titleM = props.title
- ? host.measure(props.title, { fontFamily, fontSize: fs, fontWeight: 700 })
+ ? host.measure(props.title, {
+ fontFamily,
+ fontSize: fs,
+ fontWeight: theme.weight.bold,
+ })
: null;
const textM = host.measure(props.text, {
fontFamily,
@@ -260,7 +265,7 @@ export const callout = /* @__PURE__ */ defineComponent({
y: padY,
fontFamily,
fontSize: fs,
- fontWeight: 700,
+ fontWeight: theme.weight.bold,
fill: theme.color.ink,
}),
);
@@ -282,12 +287,13 @@ export const callout = /* @__PURE__ */ defineComponent({
y: frames[0]?.label[1] ?? 0,
width: lw,
height: lh,
- background: theme.color.raised,
+ background: surfaceFill(theme.color.raised, theme),
borderRadius: theme.radius.md,
borderColor: color,
borderWidth: Math.max(1.5, 1.5 * s),
children: labelKids,
});
+ elevate(host, label, theme, "low");
const rise = 10 * s;
label.animate(
LayerAnimation.create()
diff --git a/packages/components/src/captions/index.ts b/packages/components/src/captions/index.ts
index aa3bfc54..d6776ed7 100644
--- a/packages/components/src/captions/index.ts
+++ b/packages/components/src/captions/index.ts
@@ -5,7 +5,7 @@
* keyed plates, timed to the word's own frame.
*
* Coordinates are the frame's: the root covers the video (default
- * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.
+ * the composition `canvas`, or the given width / height) from 0, 0.
*/
import {
type KeyframeTuple,
@@ -15,6 +15,7 @@ import {
} from "@framefields/compositions/program";
import { z } from "zod";
import { audioLevelsSchema } from "../core/audio.js";
+import { contrastRatio } from "../core/color.js";
import { defineComponent } from "../core/contract.js";
import type { Rect } from "../core/draw.js";
import {
@@ -27,8 +28,9 @@ import {
windowExpression,
} from "../core/glyphs.js";
import type { Animatable } from "../core/host.js";
+import { SAFE_INSETS, safeArea } from "../core/layout.js";
import { type MeasureOptions, rangeRects } from "../core/text.js";
-import { contrastRatio, themeFrames } from "../core/theme.js";
+import { themeFrames } from "../core/theme.js";
import { parseTranscript, type Word } from "./parse.js";
import { buildPhrases, type GroupOptions, type Phrase } from "./phrases.js";
@@ -80,19 +82,6 @@ const BASE_GROUP: GroupOptions = {
minGap: 0.6,
};
-/** The area captions stay inside: clear of edges and, in portrait, platform overlays. */
-function safeArea(
- W: number,
- H: number,
- area: "portrait" | "landscape" | Rect | undefined,
-): Rect {
- if (area && typeof area === "object") return area;
- const portrait = area ? area === "portrait" : H > W;
- return portrait
- ? { x: W * 0.08, y: H * 0.12, width: W * 0.84, height: H * 0.66 }
- : { x: W * 0.1, y: H * 0.08, width: W * 0.8, height: H * 0.82 };
-}
-
export const captions = /* @__PURE__ */ defineComponent({
name: "Captions",
props: () => ({
@@ -174,8 +163,8 @@ export const captions = /* @__PURE__ */ defineComponent({
defaults: { enter: false, exit: false },
build(ctx, props) {
const { host, theme, fps } = ctx;
- const W = ctx.requested.width ?? 1920 * theme.scale;
- const H = ctx.requested.height ?? 1080 * theme.scale;
+ const W = ctx.requested.width ?? ctx.canvas.width;
+ const H = ctx.requested.height ?? ctx.canvas.height;
const style = props.style;
// ── Words ─────────────────────────────────────────────────────────
@@ -206,7 +195,11 @@ export const captions = /* @__PURE__ */ defineComponent({
...GROUP[style],
...stripUndefined(props.group),
};
- const safe = safeArea(W, H, props.placement.safeArea);
+ const safe = safeArea(
+ { width: W, height: H },
+ props.placement.safeArea,
+ SAFE_INSETS.captions,
+ );
const fontFamily = props.fontFamily ?? theme.font.display;
const weight = props.fontWeight ?? (style === "clean" ? undefined : 800);
const measureAt = (text: string, size: number, width?: number) =>
diff --git a/packages/components/src/captions/meta.ts b/packages/components/src/captions/meta.ts
index 8082545e..96c353b5 100644
--- a/packages/components/src/captions/meta.ts
+++ b/packages/components/src/captions/meta.ts
@@ -16,4 +16,5 @@ export default defineMeta({
cues: ["words", "phrases"],
example: `Captions({ transcript: srt, style: "karaoke", emphasis: ["faster"] })`,
since: "M3",
+ fonts: [{ font: "emoji", why: "Social captions often carry emoji." }],
});
diff --git a/packages/components/src/card-stack/index.ts b/packages/components/src/card-stack/index.ts
index 79175365..a8261a69 100644
--- a/packages/components/src/card-stack/index.ts
+++ b/packages/components/src/card-stack/index.ts
@@ -20,6 +20,8 @@ import {
import { z } from "zod";
import { defineComponent } from "../core/contract.js";
import type { Animatable } from "../core/host.js";
+import { ascending, round } from "../core/keys.js";
+import { elevate, surfaceFill } from "../core/surface.js";
import { themeFrames } from "../core/theme.js";
export interface CardStackCues {
@@ -313,6 +315,8 @@ export const cardStack = /* @__PURE__ */ defineComponent({
height: ch,
anchorX: 0.5,
anchorY: 0,
+ // Blur only shows on fast moves: the card leaving, not the step forward.
+ motionBlurShutter: 60,
children: [clip],
});
const anim = LayerAnimation.create()
@@ -326,15 +330,7 @@ export const cardStack = /* @__PURE__ */ defineComponent({
if (tracks.rotateX.some((k) => k[1] !== 0))
anim.keys("rotateX", ascending(tracks.rotateX));
node.animate(anim);
- host.style(node, {
- dropShadow: {
- color: "#000000",
- opacity: 0.35,
- angle: 90,
- distance: 12 * s,
- size: 34 * s,
- },
- });
+ elevate(host, node, theme, "mid");
parts[`card-${c}`] = node;
parts[`card-${c}-clip`] = clip;
nodes.push(node);
@@ -372,23 +368,12 @@ export const cardStack = /* @__PURE__ */ defineComponent({
},
});
-const round = (v: number) => Math.round(v * 1000) / 1000;
-
const isSimple = (card: unknown): card is SimpleCard =>
typeof card === "object" &&
card !== null &&
"title" in card &&
!("kind" in card);
-/** Later keys on a shared frame win; frames ascend. */
-function ascending(keys: KeyframeTuple[]): KeyframeTuple[] {
- const byFrame = new Map<number, KeyframeTuple>();
- for (const k of keys) byFrame.set(k[0] as number, k);
- return [...byFrame.values()].sort(
- (a, b) => (a[0] as number) - (b[0] as number),
- );
-}
-
/** A card drawn from the theme: optional image on top, title, body, accent bar. */
function simpleCard(
ctx: Parameters<(typeof cardStack)["build"]>[0],
@@ -433,7 +418,7 @@ function simpleCard(
width: w - pad * 2,
fontFamily: theme.font.display,
fontSize: 40 * s,
- fontWeight: 700,
+ fontWeight: theme.weight.bold,
fill: theme.color.ink,
}),
);
@@ -457,7 +442,7 @@ function simpleCard(
y: 0,
width: w,
height: h,
- background: theme.color.raised,
+ background: surfaceFill(theme.color.raised, theme),
borderRadius: theme.radius.lg,
borderColor: theme.color.line,
borderWidth: Math.max(1, s),
diff --git a/packages/components/src/card-stack/meta.ts b/packages/components/src/card-stack/meta.ts
index 65cc6e26..791cdf06 100644
--- a/packages/components/src/card-stack/meta.ts
+++ b/packages/components/src/card-stack/meta.ts
@@ -14,7 +14,7 @@ export default defineMeta({
"features",
"3d",
],
- parts: ["card-0", "card-0-clip", "tilt"],
+ parts: ["card-<n>", "card-<n>-clip", "tilt"],
cues: ["changes"],
example: `CardStack({ cards: [{ title: "Fast" }, { title: "Typed" }, { title: "Yours" }] })`,
since: "M8",
diff --git a/packages/components/src/chat-thread/index.test.ts b/packages/components/src/chat-thread/index.test.ts
index 1c96dac0..8c4eceb7 100644
--- a/packages/components/src/chat-thread/index.test.ts
+++ b/packages/components/src/chat-thread/index.test.ts
@@ -37,7 +37,7 @@ describe("ChatThread", () => {
expect(find(c, "c-bubble-1")?.x).toBeLessThan(100);
});
- it("respects explicit times, draws hearts, and needs text or an image", () => {
+ it("respects explicit times, sets reactions as text, and needs text or an image", () => {
const c = make()({
id: "c",
messages: [
@@ -47,8 +47,13 @@ describe("ChatThread", () => {
});
expect(c.cues.messages.map((m) => m.frame)).toEqual([50, 90]);
expect(
- find(make()({ id: "c", messages }), "c-reaction-2-heart"),
- ).toBeDefined();
+ find(make()({ id: "c", messages }), "c-reaction-2-text"),
+ ).toMatchObject({ text: "❤️" });
+ const word = make()({
+ id: "w",
+ messages: [{ from: "a", text: "x", reaction: "heart" }],
+ });
+ expect(find(word, "w-reaction-0-text")).toMatchObject({ text: "❤️" });
expect(() => make()({ messages: [{ from: "a" }] })).toThrow(
/needs `text` or `image`/,
);
diff --git a/packages/components/src/chat-thread/index.ts b/packages/components/src/chat-thread/index.ts
index 1f603f27..32f87058 100644
--- a/packages/components/src/chat-thread/index.ts
+++ b/packages/components/src/chat-thread/index.ts
@@ -13,6 +13,8 @@ import { z } from "zod";
import { springKeys } from "../core/bake.js";
import { defineComponent } from "../core/contract.js";
import type { Animatable } from "../core/host.js";
+import { supersede } from "../core/keys.js";
+import { surfaceFill } from "../core/surface.js";
import { rangeRects } from "../core/text.js";
export interface ChatThreadCues {
@@ -37,7 +39,11 @@ function messageSchema() {
.default(4 / 3),
/** Frame it lands. Default: after the previous one has been read. */
at: z.number().int().min(0).optional(),
- /** A reaction pinned to the bubble (an emoji or short text). */
+ /**
+ * A reaction pinned to the bubble: an emoji or short text (`"heart"`
+ * means ❤️). Emoji draw from the color emoji font `framefields add`
+ * installs (`registerFonts()` in the generated `fonts.ts`).
+ */
reaction: z.string().optional(),
/** A small timestamp under the bubble. */
time: z.string().optional(),
@@ -48,10 +54,6 @@ function messageSchema() {
});
}
-const SPRING = { stiffness: 260, damping: 20 };
-/** Livelier, for reactions. */
-const POP = { stiffness: 320, damping: 14 };
-
export const chatThread = /* @__PURE__ */ defineComponent({
name: "ChatThread",
props: () => ({
@@ -89,6 +91,8 @@ export const chatThread = /* @__PURE__ */ defineComponent({
defaults: { enter: false, exit: false },
build(ctx, props) {
const { host, theme, fps } = ctx;
+ // Bubbles overshoot a little; reactions bounce.
+ const { base: spring, pop } = theme.motion.spring;
const s = theme.scale;
const W = ctx.requested.width ?? 720 * s;
const H = ctx.requested.height ?? 960 * s;
@@ -304,7 +308,10 @@ export const chatThread = /* @__PURE__ */ defineComponent({
y: slot.y,
width: slot.width,
height: slot.height,
- background: m.image && !m.text ? "rgba(0,0,0,0)" : colorOf(m.from),
+ background:
+ m.image && !m.text
+ ? "rgba(0,0,0,0)"
+ : surfaceFill(colorOf(m.from), theme),
borderRadius: radius,
// Springs grow from the corner the bubble comes from.
anchorX: slot.right ? 1 : 0,
@@ -314,11 +321,11 @@ export const chatThread = /* @__PURE__ */ defineComponent({
if (morph)
bubble.animate(
LayerAnimation.create()
- .keys("width", springKeys(at, typingW, slot.width, fps, SPRING))
- .keys("height", springKeys(at, typingH, slot.height, fps, SPRING))
+ .keys("width", springKeys(at, typingW, slot.width, fps, spring))
+ .keys("height", springKeys(at, typingH, slot.height, fps, spring))
.keys(
"borderRadius",
- springKeys(at, typingH / 2, radius, fps, SPRING),
+ springKeys(at, typingH / 2, radius, fps, spring),
)
.keys("opacity", [
[0, 0],
@@ -331,8 +338,8 @@ export const chatThread = /* @__PURE__ */ defineComponent({
const [scale, lift] = slot.right ? [0.86, fs * 1.1] : [0.6, fs * 0.5];
bubble.animate(
LayerAnimation.create()
- .keys("scale", springKeys(at, scale, 1, fps, SPRING))
- .keys("y", springKeys(at, slot.y + lift, slot.y, fps, SPRING))
+ .keys("scale", springKeys(at, scale, 1, fps, spring))
+ .keys("y", springKeys(at, slot.y + lift, slot.y, fps, spring))
.keys("opacity", [
[at, 0],
[at + fade, 1, "power2.out"],
@@ -389,16 +396,18 @@ export const chatThread = /* @__PURE__ */ defineComponent({
);
}
if (m.reaction) {
- // Hearts are drawn, so they show without an emoji font; anything
- // else is text (emoji need one registered).
- const heart = /^(❤️?|♥️?|heart)$/u.test(m.reaction.trim());
- const rfs = fs * 0.9;
- const rm = measure(m.reaction, rfs);
+ // Text, so emoji draw from the registered color emoji font
+ // (installed with this component; see `fonts.ts`).
+ const reaction = m.reaction.trim() === "heart" ? "❤️" : m.reaction;
+ // Emoji draw a little past their advance, so a lone one is set
+ // smaller to keep the pill's margin.
+ const emojiOnly = !/[\p{L}\p{N}]/u.test(reaction);
+ const rfs = fs * (emojiOnly ? 0.74 : 0.9);
+ const rm = measure(reaction, rfs);
const rh = fs * 1.5;
- const rw = heart ? rh : Math.max(rh, rm.width + fs * 0.6);
+ const rw = Math.max(rh, rm.width + fs * 0.6);
const rAt = at + Math.round(fps * 0.6);
const border = Math.max(2, fs * 0.1);
- const hs = rh * 0.46;
// On the outer top corner, like a tapback.
const pill = host.box({
id: ctx.partId(`reaction-${slot.index}`),
@@ -414,33 +423,21 @@ export const chatThread = /* @__PURE__ */ defineComponent({
anchorX: 0.5,
anchorY: 1,
children: [
- heart
- ? host.shape("path", {
- id: ctx.partId(`reaction-${slot.index}-heart`),
- position: "absolute",
- x: (rw - hs) / 2,
- y: (rh - hs * 0.92) / 2 + hs * 0.04,
- width: hs,
- height: hs * 0.92,
- d: heartPath(hs),
- fillType: "solid",
- fillColor: theme.color.negative,
- })
- : host.text(m.reaction, {
- id: ctx.partId(`reaction-${slot.index}-text`),
- position: "absolute",
- x: (rw - rm.width) / 2,
- y: (rh - rm.height) / 2,
- fontFamily,
- fontSize: rfs,
- fill: theme.color.ink,
- }),
+ host.text(reaction, {
+ id: ctx.partId(`reaction-${slot.index}-text`),
+ position: "absolute",
+ x: (rw - rm.width) / 2,
+ y: (rh - rm.height) / 2,
+ fontFamily,
+ fontSize: rfs,
+ fill: theme.color.ink,
+ }),
],
});
pill.animate(
LayerAnimation.create()
- .keys("scale", springKeys(rAt, 0, 1, fps, POP))
- .keys("rotation", springKeys(rAt, -24, 0, fps, POP))
+ .keys("scale", springKeys(rAt, 0, 1, fps, pop))
+ .keys("rotation", springKeys(rAt, -24, 0, fps, pop))
.keys("opacity", [
[0, 0],
[rAt, 1, "hold"],
@@ -493,8 +490,8 @@ export const chatThread = /* @__PURE__ */ defineComponent({
}
node.animate(
LayerAnimation.create()
- .keys("y", ascending(keys))
- .keys("opacity", ascending(glow)),
+ .keys("y", supersede(keys))
+ .keys("opacity", supersede(glow)),
);
return node;
});
@@ -513,7 +510,7 @@ export const chatThread = /* @__PURE__ */ defineComponent({
});
bubble.animate(
LayerAnimation.create()
- .keys("scale", springKeys(w.frame, 0.5, 1, fps, SPRING))
+ .keys("scale", springKeys(w.frame, 0.5, 1, fps, spring))
.keys("opacity", [
[0, 0],
[w.frame, 1, "hold"],
@@ -564,7 +561,7 @@ export const chatThread = /* @__PURE__ */ defineComponent({
const m = host.measure(letters, {
fontFamily,
fontSize: ifs,
- fontWeight: 600,
+ fontWeight: theme.weight.semibold,
});
return host.box({
...base,
@@ -577,7 +574,7 @@ export const chatThread = /* @__PURE__ */ defineComponent({
y: (size - m.height) / 2,
fontFamily,
fontSize: ifs,
- fontWeight: 600,
+ fontWeight: theme.weight.semibold,
fill: ink(from),
}),
],
@@ -609,7 +606,7 @@ export const chatThread = /* @__PURE__ */ defineComponent({
let current = startY;
for (const [f, to] of stops.slice(1)) {
if (to === current) continue;
- y.push(...springKeys(f, current, to, fps, SPRING));
+ y.push(...springKeys(f, current, to, fps, spring));
current = to;
}
const node = avatar(
@@ -620,8 +617,8 @@ export const chatThread = /* @__PURE__ */ defineComponent({
);
node.animate(
LayerAnimation.create()
- .keys("y", ascending(y))
- .keys("scale", springKeys(start, 0.4, 1, fps, SPRING))
+ .keys("y", supersede(y))
+ .keys("scale", springKeys(start, 0.4, 1, fps, spring))
.keys("opacity", [
[0, 0],
[start, 0],
@@ -663,7 +660,7 @@ export const chatThread = /* @__PURE__ */ defineComponent({
height: Math.max(H, y + pad),
children: content,
});
- column.animate(LayerAnimation.keys("y", ascending(scroll)));
+ column.animate(LayerAnimation.keys("y", supersede(scroll)));
const viewport = host.box({
id: ctx.partId("viewport"),
position: "absolute",
@@ -709,28 +706,3 @@ function initials(name: string): string {
first(words[0]) + (words.length > 1 ? first(words[words.length - 1]) : "")
).toUpperCase();
}
-
-/** A heart `size` wide, top-left at 0, 0 (two lobes and a point). */
-function heartPath(size: number): string {
- const w = size;
- const h = size * 0.92;
- return [
- `M${w / 2} ${h}`,
- `C${w * 0.18} ${h * 0.72} 0 ${h * 0.5} 0 ${h * 0.28}`,
- `C0 ${h * 0.1} ${w * 0.14} 0 ${w * 0.28} 0`,
- `C${w * 0.39} 0 ${w * 0.47} ${h * 0.07} ${w / 2} ${h * 0.16}`,
- `C${w * 0.53} ${h * 0.07} ${w * 0.61} 0 ${w * 0.72} 0`,
- `C${w * 0.86} 0 ${w} ${h * 0.1} ${w} ${h * 0.28}`,
- `C${w} ${h * 0.5} ${w * 0.82} ${h * 0.72} ${w / 2} ${h} Z`,
- ].join(" ");
-}
-
-function ascending(keys: KeyframeTuple[]): KeyframeTuple[] {
- const out: KeyframeTuple[] = [];
- for (const k of [...keys].sort((a, b) => a[0] - b[0])) {
- while (out.length > 0 && (out[out.length - 1] as KeyframeTuple)[0] >= k[0])
- out.pop();
- out.push(k);
- }
- return out;
-}
diff --git a/packages/components/src/chat-thread/meta.ts b/packages/components/src/chat-thread/meta.ts
index af95ab27..35fa6a38 100644
--- a/packages/components/src/chat-thread/meta.ts
+++ b/packages/components/src/chat-thread/meta.ts
@@ -16,4 +16,7 @@ export default defineMeta({
cues: ["messages", "typing"],
example: `ChatThread({ messages: [{ from: "me", text: "Shipped?" }, { from: "sam", text: "Live!", reaction: "🎉" }] })`,
since: "M5",
+ fonts: [
+ { font: "emoji", why: "Reactions (❤️ 🎉 👍) and messages are often emoji." },
+ ],
});
diff --git a/packages/components/src/code-block/index.ts b/packages/components/src/code-block/index.ts
index 0fa301ef..76a32cb4 100644
--- a/packages/components/src/code-block/index.ts
+++ b/packages/components/src/code-block/index.ts
@@ -13,11 +13,13 @@ import {
} from "@framefields/compositions/program";
import { z } from "zod";
import { appFrame } from "../app-frame/index.js";
+import { withAlpha } from "../core/color.js";
import { bind, defineComponent } from "../core/contract.js";
import type { Animatable } from "../core/host.js";
+import { ascending, Track } from "../core/keys.js";
import { type Theme, themeFrames } from "../core/theme.js";
import { typingFrames } from "../core/typing.js";
-import { diffLines, expandTabs, focusSet, Track } from "./plan.js";
+import { diffLines, expandTabs, focusSet } from "./plan.js";
import {
CODE_LANGS,
type Token,
@@ -44,34 +46,26 @@ export interface CodeBlockCues {
diff: ReadonlyArray<{ frame: number; end: number }>;
}
-/** Token colours from theme tokens. */
+/** Token colours from theme tokens, then `theme.syntax` on top. */
function palette(theme: Theme): Record<TokenKind, string> {
const c = theme.color;
+ const light = theme.mode === "light";
return {
plain: c.ink,
keyword: c.accent2,
string: c.positive,
- number: c.highlight,
+ // The highlight yellow and a bright teal wash out on light grounds.
+ number: light ? "#a65a00" : c.highlight,
comment: c.muted,
function: c.accent,
- type: "#4cc9e0",
+ type: light ? "#0e7c91" : "#4cc9e0",
property: c.ink,
punctuation: c.muted,
operator: c.muted,
+ ...theme.syntax,
};
}
-/** `#rrggbb` (or `#rgb`) at `alpha`, for washes and bands. */
-function tint(color: string, alpha: number): string {
- const m = color.trim().match(/^#([\da-f]{3}|[\da-f]{6})$/i);
- if (!m?.[1]) return color;
- const h = m[1].length === 3 ? [...m[1]].map((c) => c + c).join("") : m[1];
- const [r, g, b] = [0, 2, 4].map((i) =>
- Number.parseInt(h.slice(i, i + 2), 16),
- );
- return `rgba(${r},${g},${b},${alpha})`;
-}
-
function tokenSchema() {
return z.array(
z.array(
@@ -355,7 +349,7 @@ export const codeBlock = /* @__PURE__ */ defineComponent({
y: rowY(row),
width: W - pad * 0.8,
height: lh,
- background: tint(color, 0.22),
+ background: withAlpha(color, 0.22),
borderRadius: theme.radius.sm,
});
fade(box, 0)
@@ -445,7 +439,7 @@ export const codeBlock = /* @__PURE__ */ defineComponent({
y: rowY(0),
width: W - pad * 0.8,
height: lh,
- background: tint(theme.color.accent, 0.14),
+ background: withAlpha(theme.color.accent, 0.14),
borderRadius: theme.radius.sm,
});
const bandY = new Track(rowY(0));
@@ -544,14 +538,3 @@ export const codeBlock = /* @__PURE__ */ defineComponent({
};
},
});
-
-/** Keys must ascend: a later key at the same frame replaces the earlier one. */
-function ascending(keys: KeyframeTuple[]): KeyframeTuple[] {
- const out: KeyframeTuple[] = [];
- for (const k of keys) {
- while (out.length > 0 && (out[out.length - 1] as KeyframeTuple)[0] >= k[0])
- out.pop();
- out.push(k);
- }
- return out;
-}
diff --git a/packages/components/src/code-block/meta.ts b/packages/components/src/code-block/meta.ts
index 3afbe436..f7fa5677 100644
--- a/packages/components/src/code-block/meta.ts
+++ b/packages/components/src/code-block/meta.ts
@@ -9,4 +9,5 @@ export default defineMeta({
cues: ["keystrokes", "lines", "focus", "diff"],
example: `CodeBlock({ code, lang: "ts", focus: [{ at: 60, lines: [3] }] })`,
since: "M4",
+ fonts: [{ font: "mono", why: "Monospace text for code." }],
});
diff --git a/packages/components/src/code-block/plan.test.ts b/packages/components/src/code-block/plan.test.ts
index 6fb0c67c..4ed4643f 100644
--- a/packages/components/src/code-block/plan.test.ts
+++ b/packages/components/src/code-block/plan.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
-import { diffLines, expandTabs, focusSet, Track } from "./plan.js";
+import { Track } from "../core/keys.js";
+import { diffLines, expandTabs, focusSet } from "./plan.js";
describe("CodeBlock plan", () => {
it("keeps the longest common run of lines, ignoring indentation", () => {
diff --git a/packages/components/src/code-block/plan.ts b/packages/components/src/code-block/plan.ts
index caa5759e..d09c8672 100644
--- a/packages/components/src/code-block/plan.ts
+++ b/packages/components/src/code-block/plan.ts
@@ -2,7 +2,6 @@
* CodeBlock planning, kept pure: tab expansion, the line diff, focus ranges,
* and opacity tracks built from timed transitions.
*/
-import type { KeyframeTuple } from "@framefields/compositions/program";
export function expandTabs(code: string, size: number): string {
return code.replace(/\t/g, " ".repeat(size));
@@ -77,46 +76,3 @@ export function focusSet(
: lines;
return new Set(list.map((l) => l - 1).filter((l) => l >= 0 && l < count));
}
-
-/** A value track built from transitions: each eases from wherever the value is to `to`. */
-export class Track {
- private changes: Array<{
- start: number;
- end: number;
- to: number;
- ease: string;
- }> = [];
-
- constructor(private readonly initial: number) {}
-
- to(start: number, end: number, value: number, ease = "power2.out"): this {
- this.changes.push({ start, end: Math.max(start, end), to: value, ease });
- return this;
- }
-
- /** Ascending keyframes; a change that starts mid-transition starts from its target. */
- keys(): KeyframeTuple[] {
- const keys: KeyframeTuple[] = [[0, this.initial]];
- let value = this.initial;
- for (const c of [...this.changes].sort((x, y) => x.start - y.start)) {
- const last = keys[keys.length - 1] as KeyframeTuple;
- const start = Math.max(c.start, last[0] + (c.end === c.start ? 1 : 0));
- if (start > last[0]) keys.push([start, value]);
- const end = Math.max(c.end, start);
- if (end === start) keys[keys.length - 1] = [start, c.to, "hold"];
- else keys.push([end, c.to, c.ease]);
- value = c.to;
- }
- // Drop duplicate frames (a later key wins).
- const out: KeyframeTuple[] = [];
- for (const k of keys) {
- while (
- out.length > 0 &&
- (out[out.length - 1] as KeyframeTuple)[0] >= k[0]
- )
- out.pop();
- out.push(k);
- }
- return out;
- }
-}
diff --git a/packages/components/src/confetti/index.ts b/packages/components/src/confetti/index.ts
index 700a3216..b546f224 100644
--- a/packages/components/src/confetti/index.ts
+++ b/packages/components/src/confetti/index.ts
@@ -5,7 +5,7 @@
* come straight from another component's cues.
*
* Coordinates are the frame's: the root covers the video (default
- * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.
+ * the composition `canvas`, or the given width / height) from 0, 0.
*/
import type { LayoutNode } from "@framefields/compositions/program";
import { z } from "zod";
@@ -57,8 +57,8 @@ export const confetti = /* @__PURE__ */ defineComponent({
build(ctx, props) {
const { host, theme, fps } = ctx;
const s = theme.scale;
- const W = ctx.requested.width ?? 1920 * s;
- const H = ctx.requested.height ?? 1080 * s;
+ const W = ctx.requested.width ?? ctx.canvas.width;
+ const H = ctx.requested.height ?? ctx.canvas.height;
const c = theme.color;
const palette = props.palette ?? [
c.accent,
diff --git a/packages/components/src/core/audio.ts b/packages/components/src/core/audio.ts
index 458445a0..9f46307a 100644
--- a/packages/components/src/core/audio.ts
+++ b/packages/components/src/core/audio.ts
@@ -5,6 +5,7 @@
* serialises as JSON.
*/
import { z } from "zod";
+import { round } from "./keys.js";
/** A track's spectrum and loudness per frame, every value 0–1. */
export interface AudioLevels {
@@ -85,7 +86,6 @@ function percentile(values: readonly number[], p: number): number {
const db = (v: number) => 20 * Math.log10(v + 1e-9);
const clamp01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v);
-const round = (v: number) => Math.round(v * 1000) / 1000;
/** Band edges in Hz, log-spaced. */
export function bandEdges(
diff --git a/packages/components/src/core/bake.ts b/packages/components/src/core/bake.ts
index f6d28ba9..ec51623e 100644
--- a/packages/components/src/core/bake.ts
+++ b/packages/components/src/core/bake.ts
@@ -134,3 +134,40 @@ export function springKeys(
);
return bakeSamples(values, start, { tolerance });
}
+
+/**
+ * Per-frame values (frames 0…`length`) that spring to each new target from
+ * wherever they are: a retarget mid-flight starts from the current value
+ * (velocity isn't carried over). Bake with `bakeSamples` or bind as a signal.
+ */
+export function springTrack(
+ changes: ReadonlyArray<readonly [frame: number, target: number]>,
+ initial: number,
+ length: number,
+ fps: number,
+ options: { stiffness: number; damping: number } = {
+ stiffness: 230,
+ damping: 24,
+ },
+): number[] {
+ const sorted = [...changes].sort((a, b) => a[0] - b[0]);
+ const out = new Array<number>(length + 1);
+ let from = initial;
+ let to = initial;
+ let since = 0;
+ let k = 0;
+ for (let f = 0; f <= length; f++) {
+ while (
+ k < sorted.length &&
+ (sorted[k] as readonly [number, number])[0] <= f
+ ) {
+ // Restart from the current value toward the new target.
+ from = from + (to - from) * springAt((f - since) / fps, options);
+ to = (sorted[k] as readonly [number, number])[1];
+ since = (sorted[k] as readonly [number, number])[0];
+ k++;
+ }
+ out[f] = from + (to - from) * springAt((f - since) / fps, options);
+ }
+ return out;
+}
diff --git a/packages/components/src/core/color.test.ts b/packages/components/src/core/color.test.ts
new file mode 100644
index 00000000..4822cd64
--- /dev/null
+++ b/packages/components/src/core/color.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+import {
+ contrastRatio,
+ inkOn,
+ isLight,
+ mix,
+ parseColor,
+ transparent,
+ withAlpha,
+} from "./color.js";
+
+describe("color", () => {
+ it("parses hex, rgb() and names", () => {
+ expect(parseColor("#fff")).toEqual([255, 255, 255, 1]);
+ expect(parseColor("#11223380")).toEqual([17, 34, 51, 128 / 255]);
+ expect(parseColor("rgb(10, 20, 30)")).toEqual([10, 20, 30, 1]);
+ expect(parseColor("rgba(10,20,30,0.5)")).toEqual([10, 20, 30, 0.5]);
+ expect(parseColor("rgb(10 20 30 / 50%)")).toEqual([10, 20, 30, 0.5]);
+ expect(parseColor("white")).toEqual([255, 255, 255, 1]);
+ expect(parseColor("oklch(0.7 0.1 200)")).toBeNull();
+ });
+
+ it("fades and mixes, passing unknown formats through", () => {
+ expect(withAlpha("#5b8cff", 0.2)).toBe("rgba(91,140,255,0.2)");
+ expect(withAlpha("var(--x)", 0.2)).toBe("var(--x)");
+ expect(mix("#000000", "#ffffff", 0.5)).toBe("#808080");
+ expect(mix("oklch(1 0 0)", "#fff", 0.5)).toBe("oklch(1 0 0)");
+ });
+
+ it("keeps the hue when fading rgb() to transparent", () => {
+ expect(transparent("rgb(255, 0, 0)")).toBe("rgba(255,0,0,0)");
+ expect(transparent("#00f")).toBe("rgba(0,0,255,0)");
+ expect(transparent("oklch(1 0 0)")).toBe("rgba(0,0,0,0)");
+ });
+
+ it("judges lightness and picks readable ink", () => {
+ expect(contrastRatio("#000", "#fff")).toBeCloseTo(21, 5);
+ expect(isLight("#f4f1ea")).toBe(true);
+ expect(isLight("#0d0e11")).toBe(false);
+ expect(inkOn("#ffd23f")).toBe("#0b0c0e");
+ expect(inkOn("#1f5fe0")).toBe("#ffffff");
+ });
+});
diff --git a/packages/components/src/core/color.ts b/packages/components/src/core/color.ts
new file mode 100644
index 00000000..1f3fc69b
--- /dev/null
+++ b/packages/components/src/core/color.ts
@@ -0,0 +1,116 @@
+/**
+ * Color math for components: parse, fade, mix and judge lightness. Accepts
+ * `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` / `rgba()` (comma or
+ * space syntax) and `white` / `black` / `transparent`. Anything else (a
+ * gradient, `oklch()`, a CSS variable) passes through untouched where a
+ * function returns a color, and counts as unknown where it returns a number.
+ */
+
+/** Red, green, blue (0–255) and alpha (0–1). */
+export type Rgba = [r: number, g: number, b: number, a: number];
+
+const NAMED: Record<string, Rgba> = {
+ white: [255, 255, 255, 1],
+ black: [0, 0, 0, 1],
+ transparent: [0, 0, 0, 0],
+};
+
+/** The color's channels, or null when the format isn't one listed above. */
+export function parseColor(color: string): Rgba | null {
+ const c = color.trim().toLowerCase();
+ const named = NAMED[c];
+ if (named) return [...named];
+ const hex = c.match(/^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/);
+ if (hex?.[1]) {
+ const h =
+ hex[1].length <= 4 ? [...hex[1]].map((x) => x + x).join("") : hex[1];
+ const byte = (i: number) => Number.parseInt(h.slice(i, i + 2), 16);
+ return [byte(0), byte(2), byte(4), h.length === 8 ? byte(6) / 255 : 1];
+ }
+ const fn = c.match(/^rgba?\(([^)]*)\)$/);
+ if (fn?.[1]) {
+ const parts = fn[1].split(/[\s,/]+/).filter(Boolean);
+ if (parts.length !== 3 && parts.length !== 4) return null;
+ const num = (p: string, max: number) =>
+ p.endsWith("%") ? (Number.parseFloat(p) / 100) * max : Number(p);
+ const [r, g, b] = parts.slice(0, 3).map((p) => num(p, 255));
+ const a = parts[3] === undefined ? 1 : num(parts[3], 1);
+ if ([r, g, b, a].some((v) => v === undefined || Number.isNaN(v)))
+ return null;
+ return [r as number, g as number, b as number, a];
+ }
+ return null;
+}
+
+const css = ([r, g, b, a]: Rgba) =>
+ `rgba(${Math.round(r)},${Math.round(g)},${Math.round(b)},${+a.toFixed(3)})`;
+
+/** `color` at `alpha` (replacing its own); unknown formats pass through. */
+export function withAlpha(color: string, alpha: number): string {
+ const c = parseColor(color);
+ return c ? css([c[0], c[1], c[2], alpha]) : color;
+}
+
+/**
+ * `color` fully transparent, keeping its hue, so a gradient fading to it has
+ * no dark fringe. Unknown formats give plain `rgba(0,0,0,0)`.
+ */
+export function transparent(color: string): string {
+ const c = parseColor(color);
+ return css(c ? [c[0], c[1], c[2], 0] : [0, 0, 0, 0]);
+}
+
+/** Mix `a` toward `b` by `t` (0 → a, 1 → b): `#rrggbb` when both are opaque. */
+export function mix(a: string, b: string, t: number): string {
+ const x = parseColor(a);
+ const y = parseColor(b);
+ if (!x || !y) return a;
+ const m = x.map((v, k) => v + ((y[k] as number) - v) * t) as Rgba;
+ if (m[3] < 1) return css(m);
+ return `#${m
+ .slice(0, 3)
+ .map((v) => Math.round(v).toString(16).padStart(2, "0"))
+ .join("")}`;
+}
+
+/** WCAG relative luminance (0 black … 1 white), or null for unknown formats. */
+export function luminance(color: string): number | null {
+ const c = parseColor(color);
+ if (!c) return null;
+ const channel = (v: number) => {
+ const s = v / 255;
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
+ };
+ return (
+ 0.2126 * channel(c[0]) + 0.7152 * channel(c[1]) + 0.0722 * channel(c[2])
+ );
+}
+
+/** WCAG contrast ratio of two colors, or null when either is unknown. */
+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);
+}
+
+/**
+ * True when black text reads better than white on `color` (luminance above
+ * ~0.18). Unknown formats count as dark.
+ */
+export function isLight(color: string): boolean {
+ return (luminance(color) ?? 0) > 0.179;
+}
+
+/** Whichever of `light` / `dark` ink reads better on `background`. */
+export function inkOn(
+ background: string,
+ light = "#ffffff",
+ dark = "#0b0c0e",
+): string {
+ return (contrastRatio(light, background) ?? 0) >=
+ (contrastRatio(dark, background) ?? 0)
+ ? light
+ : dark;
+}
diff --git a/packages/components/src/core/contract.test.ts b/packages/components/src/core/contract.test.ts
index b8c5bd64..8e94fa37 100644
--- a/packages/components/src/core/contract.test.ts
+++ b/packages/components/src/core/contract.test.ts
@@ -3,7 +3,14 @@ import { describe, expect, it } from "vitest";
import { z } from "zod";
import { fakeHost } from "../test/fake-host.js";
import { probe } from "../test/probe.js";
-import { bind, defineComponent, pulseKeys } from "./contract.js";
+import {
+ bind,
+ defineComponent,
+ after as endPlus,
+ pulseKeys,
+ withDefaults,
+} from "./contract.js";
+import { themes } from "./theme.js";
const make = () => bind(fakeHost(), probe);
@@ -227,4 +234,65 @@ describe("first keys", () => {
[44, 1],
]);
});
+
+ it("suggests the prop a typo meant, and names the instance", () => {
+ const Probe = make();
+ expect(() => Probe({ lable: "x" } as never)).toThrow(
+ /did you mean "lable" → "label"\?/,
+ );
+ expect(() => Probe({ id: "intro", at: -1 })).toThrow(
+ /^Probe#intro: invalid props/,
+ );
+ });
+
+ it("hands the canvas to the build, defaulting to 1920 × 1080 × scale", () => {
+ let seen: unknown;
+ const Spy = bind(
+ fakeHost(),
+ defineComponent({
+ name: "Spy",
+ props: () => ({ n: z.number().optional() }),
+ build(ctx) {
+ seen = ctx.canvas;
+ return { children: [], width: 1, height: 1, duration: 1, cues: {} };
+ },
+ }),
+ );
+ Spy({});
+ expect(seen).toEqual({ width: 1920, height: 1080 });
+ Spy({ theme: { scale: 2 } });
+ expect(seen).toEqual({ width: 3840, height: 2160 });
+ Spy({ canvas: { width: 1080, height: 1920 } });
+ expect(seen).toEqual({ width: 1080, height: 1920 });
+ });
+
+ it("withDefaults sets project props once; calls still win", () => {
+ const ui = withDefaults({ fps: 60, theme: themes.paper, seed: 7 });
+ const Probe = ui(make());
+ const node = Probe({ id: "d" });
+ const plate = node.part("plate") as unknown as { background: string };
+ expect(plate.background).toBe(themes.paper.color.accent);
+ // A partial theme merges over the default theme, not over graphite.
+ const tinted = Probe({ id: "e", theme: { color: { accent: "#123456" } } });
+ expect(tinted.part("plate")).toMatchObject({
+ background: "#123456",
+ borderRadius: themes.paper.radius.md,
+ });
+ expect(() => Probe({ fps: 24 })).not.toThrow();
+ });
+
+ it("after() chains from a component's end", () => {
+ const node = make()({ at: 30 });
+ expect(endPlus(node, 6)).toBe(51);
+ expect(() => endPlus({ span: { end: Number.POSITIVE_INFINITY } })).toThrow(
+ /open-ended/,
+ );
+ });
+
+ it("puts the stage's motion blur on when its enter or exit asks", () => {
+ const blurred = make()({ enter: "slide-left" });
+ expect(blurred.part("stage")).toMatchObject({ motionBlurShutter: 90 });
+ const plain = make()({ enter: "rise" });
+ expect(plain.part("stage")).not.toHaveProperty("motionBlurShutter");
+ });
});
diff --git a/packages/components/src/core/contract.ts b/packages/components/src/core/contract.ts
index a593772d..e7c6f4d7 100644
--- a/packages/components/src/core/contract.ts
+++ b/packages/components/src/core/contract.ts
@@ -12,6 +12,7 @@ import type {
} from "@framefields/compositions/program";
import { z } from "zod";
import type { Animatable, Host } from "./host.js";
+import type { CanvasSize } from "./layout.js";
import {
enterAnimation,
exitAnimation,
@@ -105,6 +106,7 @@ function motionPresetSchema() {
ease: z.string().optional(),
distance: z.number().optional(),
delay: z.number().int().min(0).optional(),
+ blur: z.union([z.boolean(), z.number().min(0).max(360)]).optional(),
}),
]);
}
@@ -135,6 +137,10 @@ function buildBaseProps() {
.optional(),
seed: z.number().int().optional(),
fps: z.number().positive().optional(),
+ canvas: z
+ .object({ width: z.number().positive(), height: z.number().positive() })
+ .strict()
+ .optional(),
customize:
fn<(parts: Record<string, Animatable<LayoutNode>>) => void>().optional(),
});
@@ -164,6 +170,11 @@ export interface BaseProps {
seed?: number;
/** Composition frame rate: theme speeds and real-time inputs scale by it. Default 30. */
fps?: number;
+ /**
+ * Composition size, for components that cover the frame (captions,
+ * backdrops, spotlights …). Default 1920 × 1080 × `theme.scale`.
+ */
+ canvas?: CanvasSize;
/** Receives every built part before the component returns. */
customize?: (parts: Record<string, Animatable<LayoutNode>>) => void;
}
@@ -190,6 +201,8 @@ export interface BuildContext {
};
/** Frames the finished state holds (base `hold`, or the component's default). */
hold: number;
+ /** The composition size (base `canvas`, or 1920 × 1080 × theme scale). */
+ canvas: CanvasSize;
}
/** Where the root ended up: what a component's `api` can rely on. */
@@ -288,11 +301,58 @@ export interface ComponentExtras<C extends Cues> {
readonly span: { start: number; end: number; duration: number };
/** A named part (`root`, `stage`, and the component's own). */
part(name: string): Animatable<LayoutNode> | undefined;
+ /** Every name `part()` and `customize` answer to. */
+ readonly partNames: readonly string[];
}
export type ComponentNode<C extends Cues> = Animatable<BoxNode> &
ComponentExtras<C>;
+/** Base props a project usually sets once: see {@link withDefaults}. */
+export type ProjectDefaults = Pick<BaseProps, "fps" | "canvas" | "seed"> & {
+ theme?: ThemeInput | Theme;
+};
+
+/**
+ * Wrap component factories so every call starts from the project's frame
+ * rate, canvas, theme and seed. Props given at the call win; a call's
+ * partial `theme` merges over the default theme, not over `graphite`.
+ *
+ * ```ts
+ * const ui = withDefaults({ fps: 60, canvas: { width: 1080, height: 1920 }, theme: themes.paper });
+ * const Captions = ui(CaptionsBase);
+ * ```
+ */
+export function withDefaults(defaults: ProjectDefaults) {
+ const base = defaults.theme ? defineTheme(defaults.theme) : undefined;
+ return <P extends BaseProps, R>(factory: (props: P) => R) =>
+ (props: P): R =>
+ factory({
+ ...defaults,
+ ...props,
+ theme:
+ props.theme && base
+ ? defineTheme(props.theme, base)
+ : (props.theme ?? base),
+ });
+}
+
+/**
+ * The frame `gap` frames after `node` ends: `at: after(title, 6)`. Throws
+ * for open-ended components, which have no end until given a `duration`.
+ */
+export function after(
+ node: { readonly span: { end: number } },
+ gap = 0,
+): number {
+ if (!Number.isFinite(node.span.end)) {
+ throw new Error(
+ "after(): this component is open-ended (it stays until its parent ends). Give it a `duration`, or use its cues.",
+ );
+ }
+ return node.span.end + gap;
+}
+
const kebab = (name: string) =>
name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
@@ -314,10 +374,22 @@ export function bind<
schema ??= basePropsSchema().extend(definition.props()).strict();
const parsed = schema.safeParse(input ?? {});
if (!parsed.success) {
+ const known = Object.keys(schema.shape);
const issues = parsed.error.issues
- .map((i) => ` - ${i.path.join(".") || "(props)"}: ${i.message}`)
+ .map((i) => {
+ const where = i.path.join(".") || "(props)";
+ const hint =
+ i.code === "unrecognized_keys" && i.path.length === 0
+ ? suggest(i.keys, known)
+ : "";
+ return ` - ${where}: ${i.message}${hint}`;
+ })
.join("\n");
- throw new Error(`${definition.name}: invalid props\n${issues}`);
+ const who =
+ typeof input?.id === "string"
+ ? `${definition.name}#${input.id}`
+ : definition.name;
+ throw new Error(`${who}: invalid props\n${issues}`);
}
return assemble(
host,
@@ -327,6 +399,35 @@ export function bind<
};
}
+/** ` (did you mean "label"?)` for keys one or two edits from a known prop. */
+function suggest(keys: readonly string[], known: readonly string[]): string {
+ const hints = keys.flatMap((key) => {
+ let best: string | undefined;
+ let bestD = 3;
+ for (const k of known) {
+ const d = editDistance(key.toLowerCase(), k.toLowerCase());
+ if (d < bestD) [best, bestD] = [k, d];
+ }
+ return best ? [`"${key}" → "${best}"`] : [];
+ });
+ return hints.length > 0 ? ` (did you mean ${hints.join(", ")}?)` : "";
+}
+
+function editDistance(a: string, b: string): number {
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
+ for (let i = 1; i <= a.length; i++) {
+ const row = [i];
+ for (let j = 1; j <= b.length; j++)
+ row[j] = Math.min(
+ (prev[j] as number) + 1,
+ (row[j - 1] as number) + 1,
+ (prev[j - 1] as number) + (a[i - 1] === b[j - 1] ? 0 : 1),
+ );
+ prev = row;
+ }
+ return prev[b.length] as number;
+}
+
function assemble<S extends z.ZodRawShape, C extends Cues, E extends object>(
host: Host,
definition: ComponentDefinition<S, C, E>,
@@ -353,6 +454,10 @@ function assemble<S extends z.ZodRawShape, C extends Cues, E extends object>(
at: props.at ?? 0,
},
hold,
+ canvas: props.canvas ?? {
+ width: 1920 * theme.scale,
+ height: 1080 * theme.scale,
+ },
};
const built = definition.build(ctx, props);
@@ -390,6 +495,7 @@ function assemble<S extends z.ZodRawShape, C extends Cues, E extends object>(
const width = props.width ?? built.width;
const height = props.height ?? built.height;
+ const blur = Math.max(enter?.blur ?? 0, exit?.blur ?? 0);
const stage = host.box({
id: ctx.partId("stage"),
position: "absolute",
@@ -397,6 +503,7 @@ function assemble<S extends z.ZodRawShape, C extends Cues, E extends object>(
y: 0,
width,
height,
+ ...(blur > 0 && { motionBlurShutter: blur }),
children: built.children,
});
const size = { width, height };
@@ -450,6 +557,7 @@ function assemble<S extends z.ZodRawShape, C extends Cues, E extends object>(
enumerable: false,
},
part: { value: (name: string) => parts[name], enumerable: false },
+ partNames: { value: Object.keys(parts), enumerable: false },
});
if (built.api) {
const api = built.api({
diff --git a/packages/components/src/core/host.ts b/packages/components/src/core/host.ts
index 3a88346f..04d55eed 100644
--- a/packages/components/src/core/host.ts
+++ b/packages/components/src/core/host.ts
@@ -38,9 +38,13 @@ export interface LayerStyleConfig {
innerShadow?: {
color?: string;
opacity?: number;
+ /** Degrees, as for drop shadows: 90 shades the bottom inside edge, 270 the top. */
angle?: number;
distance?: number;
size?: number;
+ choke?: number;
+ /** Default `"multiply"` (a light color then does nothing: use `"normal"` or `"screen"`). */
+ blendMode?: string;
};
stroke?: {
size?: number;
diff --git a/packages/components/src/core/keys.test.ts b/packages/components/src/core/keys.test.ts
new file mode 100644
index 00000000..cb481365
--- /dev/null
+++ b/packages/components/src/core/keys.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from "vitest";
+import {
+ ascending,
+ KeyBook,
+ last,
+ round,
+ supersede,
+ Track,
+ valueAt,
+} from "./keys.js";
+
+describe("keys", () => {
+ it("ascending sorts and lets the last key on a frame win", () => {
+ expect(
+ ascending([
+ [10, 1],
+ [0, 0],
+ [10, 2, "power2.out"],
+ [5, 3],
+ ]),
+ ).toEqual([
+ [0, 0],
+ [5, 3],
+ [10, 2, "power2.out"],
+ ]);
+ });
+
+ it("supersede drops planned keys a retarget lands before", () => {
+ expect(
+ supersede([
+ [0, 0],
+ [20, 10],
+ [30, 10],
+ [12, 4],
+ [25, 0],
+ ]),
+ ).toEqual([
+ [0, 0],
+ [12, 4],
+ [25, 0],
+ ]);
+ });
+
+ it("valueAt follows eases and holds like the renderer", () => {
+ const keys = [
+ [0, 0],
+ [10, 10],
+ [20, 0, "hold"],
+ ] as const;
+ expect(valueAt(keys, -5)).toBe(0);
+ expect(valueAt(keys, 5)).toBe(5);
+ expect(valueAt(keys, 15)).toBe(10);
+ expect(valueAt(keys, 20)).toBe(0);
+ expect(valueAt(keys, 99)).toBe(0);
+ expect(
+ valueAt(
+ [
+ [0, 0],
+ [10, 1, "power2.in"],
+ ],
+ 5,
+ ),
+ ).toBeLessThan(0.5);
+ expect(valueAt([], 3)).toBe(0);
+ });
+
+ it("round and last", () => {
+ expect(round(1.23456)).toBe(1.235);
+ expect(round(1.23456, 1)).toBe(1.2);
+ expect(last([1, 2, 3])).toBe(3);
+ expect(last([])).toBeUndefined();
+ });
+
+ it("Track eases between changes and steps on set()", () => {
+ expect(new Track(0).to(10, 20, 1).set(30, 0).keys()).toEqual([
+ [0, 0],
+ [10, 0],
+ [20, 1, "power2.out"],
+ [30, 0, "hold"],
+ ]);
+ });
+
+ it("KeyBook merges keys per node and prop and animates once", () => {
+ const calls: unknown[] = [];
+ const node = { animate: (a: unknown) => calls.push(a) };
+ new KeyBook<typeof node>()
+ .key(node, "y", [[10, 5]])
+ .key(node, "opacity", [[0, 0]])
+ .key(node, "y", [[0, 0]])
+ .apply();
+ expect(calls).toHaveLength(1);
+ const tracks = (
+ calls[0] as {
+ tracks: Array<{ prop: string; keyframes: Array<{ frame: number }> }>;
+ }
+ ).tracks;
+ const y = tracks.find((t) => t.prop === "y");
+ expect(y?.keyframes.map((k) => k.frame)).toEqual([0, 10]);
+ expect(tracks.map((t) => t.prop).sort()).toEqual(["opacity", "y"]);
+ });
+});
diff --git a/packages/components/src/core/keys.ts b/packages/components/src/core/keys.ts
new file mode 100644
index 00000000..43f1c6a9
--- /dev/null
+++ b/packages/components/src/core/keys.ts
@@ -0,0 +1,134 @@
+/**
+ * Keyframe bookkeeping shared by every component: ordering, sampling, and
+ * builders that collect keys per node and prop before animating once.
+ */
+import {
+ type AnimatableProp,
+ type KeyframeTuple,
+ LayerAnimation,
+} from "@framefields/compositions/program";
+import { evaluateEase } from "./ease.js";
+
+/** Round to `places` decimals (default 3): keeps baked keys short and stable. */
+export const round = (v: number, places = 3): number => {
+ const k = 10 ** places;
+ return Math.round(v * k) / k;
+};
+
+/** The last element, or `undefined`. */
+export const last = <T>(list: readonly T[]): T | undefined =>
+ list[list.length - 1];
+
+/**
+ * Keys in ascending frame order; of several keys on one frame, the one given
+ * last wins. Input order is otherwise free.
+ */
+export function ascending(keys: readonly KeyframeTuple[]): KeyframeTuple[] {
+ const byFrame = new Map<number, KeyframeTuple>();
+ for (const k of keys) byFrame.set(k[0], k);
+ return [...byFrame.values()].sort((a, b) => a[0] - b[0]);
+}
+
+/**
+ * Keys written as a timeline where each key supersedes what came before at
+ * or after its frame: a key earlier than the previous one drops the later
+ * ones (a retarget cancels the planned rest of a move).
+ */
+export function supersede(keys: readonly KeyframeTuple[]): KeyframeTuple[] {
+ const out: KeyframeTuple[] = [];
+ for (const k of keys) {
+ while (out.length > 0 && (last(out) as KeyframeTuple)[0] >= k[0]) out.pop();
+ out.push(k);
+ }
+ return out;
+}
+
+/**
+ * A numeric track's value at `frame`, the way the renderer evaluates it:
+ * each segment eased by its end key's ease, `hold` stepping on the key.
+ */
+export function valueAt(keys: readonly KeyframeTuple[], frame: number): number {
+ const first = keys[0];
+ if (!first) return 0;
+ if (frame <= first[0]) return first[1] as number;
+ for (let i = 1; i < keys.length; i++) {
+ const [f0, v0] = keys[i - 1] as KeyframeTuple;
+ const [f1, v1, ease] = keys[i] as KeyframeTuple;
+ if (frame > f1) continue;
+ if (ease === "hold") return frame === f1 ? (v1 as number) : (v0 as number);
+ const t = evaluateEase(
+ typeof ease === "string" ? ease : undefined,
+ (frame - f0) / Math.max(1, f1 - f0),
+ );
+ return (v0 as number) + ((v1 as number) - (v0 as number)) * t;
+ }
+ return (last(keys) as KeyframeTuple)[1] as number;
+}
+
+/** A value track built from transitions: each eases from wherever the value is to `to`. */
+export class Track {
+ private changes: Array<{
+ start: number;
+ end: number;
+ to: number;
+ ease: string;
+ }> = [];
+
+ constructor(private readonly initial: number) {}
+
+ to(start: number, end: number, value: number, ease = "power2.out"): this {
+ this.changes.push({ start, end: Math.max(start, end), to: value, ease });
+ return this;
+ }
+
+ /** Jump to `value` on `frame` (a hold key). */
+ set(frame: number, value: number): this {
+ return this.to(frame, frame, value);
+ }
+
+ /** Ascending keyframes; a change that starts mid-transition starts from its target. */
+ keys(): KeyframeTuple[] {
+ const keys: KeyframeTuple[] = [[0, this.initial]];
+ let value = this.initial;
+ for (const c of [...this.changes].sort((x, y) => x.start - y.start)) {
+ const prev = last(keys) as KeyframeTuple;
+ const start = Math.max(c.start, prev[0] + (c.end === c.start ? 1 : 0));
+ if (start > prev[0]) keys.push([start, value]);
+ const end = Math.max(c.end, start);
+ if (end === start) keys[keys.length - 1] = [start, c.to, "hold"];
+ else keys.push([end, c.to, c.ease]);
+ value = c.to;
+ }
+ return supersede(keys);
+ }
+}
+
+/**
+ * Keys collected per node and prop from anywhere in a build, merged into one
+ * ascending track each and applied with one `animate()` per node.
+ */
+export class KeyBook<N extends { animate(...anims: unknown[]): unknown }> {
+ private readonly book = new Map<N, Map<string, KeyframeTuple[]>>();
+
+ /** Append keys for `node`'s `prop` (merged with any already given). */
+ key(
+ node: N,
+ prop: AnimatableProp | (string & {}),
+ keys: KeyframeTuple[],
+ ): this {
+ const byProp = this.book.get(node) ?? new Map<string, KeyframeTuple[]>();
+ this.book.set(node, byProp);
+ byProp.set(prop, [...(byProp.get(prop) ?? []), ...keys]);
+ return this;
+ }
+
+ /** Animate every node once with its merged tracks. */
+ apply(): void {
+ for (const [node, byProp] of this.book) {
+ const anim = LayerAnimation.create();
+ for (const [prop, keys] of byProp)
+ anim.keys(prop as AnimatableProp, ascending(keys));
+ node.animate(anim);
+ }
+ }
+}
diff --git a/packages/components/src/core/layout.test.ts b/packages/components/src/core/layout.test.ts
new file mode 100644
index 00000000..2531558a
--- /dev/null
+++ b/packages/components/src/core/layout.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from "vitest";
+import { SAFE_INSETS, safeArea } from "./layout.js";
+
+describe("safeArea", () => {
+ it("picks the orientation from the canvas", () => {
+ const r = safeArea({ width: 1000, height: 500 });
+ expect([r.x, r.y, r.width, r.height].map(Math.round)).toEqual([
+ 60, 40, 880, 410,
+ ]);
+ const portrait = safeArea({ width: 1000, height: 2000 });
+ expect(portrait.y + portrait.height).toBeCloseTo(2000 * 0.76);
+ });
+
+ it("takes a forced orientation, insets, or a rect", () => {
+ const rect = { x: 1, y: 2, width: 3, height: 4 };
+ expect(safeArea({ width: 10, height: 10 }, rect)).toBe(rect);
+ expect(
+ safeArea({ width: 1000, height: 500 }, "landscape", SAFE_INSETS.captions)
+ .x,
+ ).toBe(100);
+ });
+});
diff --git a/packages/components/src/core/layout.ts b/packages/components/src/core/layout.ts
new file mode 100644
index 00000000..d95a8fc2
--- /dev/null
+++ b/packages/components/src/core/layout.ts
@@ -0,0 +1,60 @@
+/**
+ * Frame-level layout: the canvas a component covers and the safe area inside
+ * it that text and plates keep to.
+ */
+import type { Rect } from "./draw.js";
+
+/** The composition size a full-frame component covers. */
+export interface CanvasSize {
+ width: number;
+ height: number;
+}
+
+/** Margins as shares of the frame: left / right `x`, `top`, `bottom`. */
+export interface SafeInsets {
+ x: number;
+ top: number;
+ bottom: number;
+}
+
+/**
+ * Safe-area margins by use. Portrait leaves room for the captions, buttons
+ * and handles that short-form platforms draw over the bottom and right.
+ */
+export const SAFE_INSETS = {
+ /** Titles, plates, lower thirds. */
+ titles: {
+ landscape: { x: 0.06, top: 0.08, bottom: 0.1 },
+ portrait: { x: 0.08, top: 0.1, bottom: 0.24 },
+ },
+ /** Subtitles: narrower lines, the same bottom clearance. */
+ captions: {
+ landscape: { x: 0.1, top: 0.08, bottom: 0.1 },
+ portrait: { x: 0.08, top: 0.12, bottom: 0.22 },
+ },
+} as const satisfies Record<
+ string,
+ { landscape: SafeInsets; portrait: SafeInsets }
+>;
+
+/**
+ * The rect inside `canvas` that content keeps to. `area` forces an
+ * orientation or gives the rect itself; by default a frame taller than it is
+ * wide counts as portrait.
+ */
+export function safeArea(
+ canvas: CanvasSize,
+ area?: "portrait" | "landscape" | Rect,
+ insets: { landscape: SafeInsets; portrait: SafeInsets } = SAFE_INSETS.titles,
+): Rect {
+ if (area && typeof area === "object") return area;
+ const { width: W, height: H } = canvas;
+ const portrait = area ? area === "portrait" : H > W;
+ const i = portrait ? insets.portrait : insets.landscape;
+ return {
+ x: W * i.x,
+ y: H * i.top,
+ width: W * (1 - 2 * i.x),
+ height: H * (1 - i.top - i.bottom),
+ };
+}
diff --git a/packages/components/src/core/meta.ts b/packages/components/src/core/meta.ts
index 3caea4ab..3ed5986d 100644
--- a/packages/components/src/core/meta.ts
+++ b/packages/components/src/core/meta.ts
@@ -18,6 +18,21 @@ export interface ComponentMeta {
example: string;
/** Spec milestone that introduced it. */
since: string;
+ /**
+ * Fonts it draws with beyond the theme's families. `framefields add`
+ * installs each one into the project (pinned, hash-checked) and registers
+ * it in the generated `fonts.ts`.
+ */
+ fonts?: readonly FontNeed[];
+}
+
+/** Fonts `framefields add` knows how to install, by role. */
+export type FontRole = "emoji" | "sans" | "mono";
+
+export interface FontNeed {
+ font: FontRole;
+ /** Why, shown when `add` installs it. */
+ why: string;
}
export function defineMeta(meta: ComponentMeta): ComponentMeta {
diff --git a/packages/components/src/core/motion.test.ts b/packages/components/src/core/motion.test.ts
index 1ebcc832..9130667b 100644
--- a/packages/components/src/core/motion.test.ts
+++ b/packages/components/src/core/motion.test.ts
@@ -34,6 +34,18 @@ describe("motion presets", () => {
).toThrow(/Unknown motion preset/);
});
+ it("blurs slides by default, and anything on request", () => {
+ const g = themes.graphite;
+ expect(resolveMotion("slide-left", "enter", g)?.blur).toBe(90);
+ expect(resolveMotion("rise", "enter", g)?.blur).toBe(0);
+ expect(resolveMotion({ preset: "rise", blur: 45 }, "enter", g)?.blur).toBe(
+ 45,
+ );
+ expect(
+ resolveMotion({ preset: "slide-up", blur: false }, "enter", g)?.blur,
+ ).toBe(0);
+ });
+
it("enters from an offset and settles at zero", () => {
const m = resolveMotion(
{ preset: "rise", duration: 10, delay: 2 },
diff --git a/packages/components/src/core/motion.ts b/packages/components/src/core/motion.ts
index d1cfed63..de66ce28 100644
--- a/packages/components/src/core/motion.ts
+++ b/packages/components/src/core/motion.ts
@@ -52,6 +52,11 @@ export interface MotionOptions {
distance?: number;
/** Frames to wait after the window starts (enter) or before it ends (exit). */
delay?: number;
+ /**
+ * Motion blur while the stage moves: `true` (90° shutter), a shutter
+ * angle in degrees, or `false`. Default on for `slide-*`, off otherwise.
+ */
+ blur?: boolean | number;
}
export type MotionPreset =
@@ -64,6 +69,8 @@ export interface ResolvedMotion {
ease: string;
distance: number;
delay: number;
+ /** Shutter angle in degrees; 0 = no motion blur. */
+ blur: number;
}
/** Normalise a preset (or `false`) against a theme and fps. */
@@ -97,9 +104,13 @@ export function resolveMotion(
distance:
o.distance ?? (o.preset.startsWith("slide-") ? 120 : 40) * theme.scale,
delay: Math.max(0, Math.round(o.delay ?? 0)),
+ blur: shutter(o.blur ?? o.preset.startsWith("slide-")),
};
}
+const shutter = (blur: boolean | number) =>
+ blur === true ? 90 : blur === false ? 0 : Math.max(0, Math.min(360, blur));
+
/** The box a mask preset slides through. */
export interface MotionSize {
width: number;
diff --git a/packages/components/src/core/surface.ts b/packages/components/src/core/surface.ts
new file mode 100644
index 00000000..b51262be
--- /dev/null
+++ b/packages/components/src/core/surface.ts
@@ -0,0 +1,66 @@
+/**
+ * Surfaces: the look shared by plates, cards, toasts and bubbles. A surface
+ * sits at an elevation from the theme (a soft shadow, plus a lit top edge on
+ * dark themes) and can carry a faint top-to-bottom sheen.
+ */
+import type { LayoutNode } from "@framefields/compositions/program";
+import { mix } from "./color.js";
+import type { Animatable, Host, LayerStyleConfig } from "./host.js";
+import type { Theme } from "./theme.js";
+
+export type ElevationLevel = keyof Theme["elevation"];
+
+/** Layer styles for `level`: a drop shadow and, when the theme asks, a top-edge highlight. */
+export function elevationStyle(
+ theme: Theme,
+ level: ElevationLevel,
+): LayerStyleConfig {
+ const e = theme.elevation[level];
+ const s = theme.scale;
+ return {
+ ...(e.opacity > 0 && {
+ dropShadow: {
+ color: theme.color.shadow,
+ opacity: e.opacity,
+ angle: 90,
+ distance: e.distance * s,
+ size: e.size * s,
+ },
+ }),
+ ...(e.edge > 0 && {
+ innerShadow: {
+ color: "#ffffff",
+ opacity: e.edge,
+ angle: 270,
+ distance: Math.max(1, s),
+ size: 0,
+ blendMode: "normal",
+ },
+ }),
+ };
+}
+
+/** Put `node` at `level` (or leave it flat for `false`); returns it. */
+export function elevate<T extends Animatable<LayoutNode>>(
+ host: Host,
+ node: T,
+ theme: Theme,
+ level: ElevationLevel | false,
+): T {
+ if (level === false) return node;
+ const style = elevationStyle(theme, level);
+ return Object.keys(style).length > 0 ? host.style(node, style) : node;
+}
+
+/**
+ * A background for a surface of `color`: a vertical sheen a few percent
+ * lighter at the top on dark themes (light themes stay flat, where a
+ * lighter top reads as a glare). Non-hex / non-rgb colors pass through.
+ */
+export function surfaceFill(color: string, theme: Theme, sheen = 0.05): string {
+ if (theme.mode === "light" || sheen <= 0) return color;
+ const top = mix(color, "#ffffff", sheen);
+ return top === color
+ ? color
+ : `linear-gradient(180deg, ${top} 0%, ${color} 100%)`;
+}
diff --git a/packages/components/src/core/theme.test.ts b/packages/components/src/core/theme.test.ts
index 727703ea..4c2a5e79 100644
--- a/packages/components/src/core/theme.test.ts
+++ b/packages/components/src/core/theme.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
-import { contrastRatio, defineTheme, themeFrames, themes } from "./theme.js";
+import { contrastRatio } from "./color.js";
+import { defineTheme, themeFrames, themes } from "./theme.js";
describe("theme", () => {
it("merges partials over graphite", () => {
diff --git a/packages/components/src/core/theme.ts b/packages/components/src/core/theme.ts
index 8f94d746..0ec23e9e 100644
--- a/packages/components/src/core/theme.ts
+++ b/packages/components/src/core/theme.ts
@@ -2,9 +2,32 @@
* Design tokens every component reads instead of hard-coded colors, fonts and
* timings. `defineTheme` deep-merges a partial theme over `themes.graphite`.
*/
+import { contrastRatio, isLight } from "./color.js";
import { scaleFrames } from "./timing.js";
+/** A spring, as `springKeys` / `springAt` take it. */
+export interface Spring {
+ stiffness: number;
+ damping: number;
+}
+
+/**
+ * How far a surface sits above what's behind it: a soft drop shadow, plus a
+ * faint highlight along its top edge so it reads as a lit object.
+ */
+export interface Elevation {
+ /** Shadow opacity, 0–1. */
+ opacity: number;
+ /** Shadow offset (straight down) and blur, px at theme scale 1. */
+ distance: number;
+ size: number;
+ /** Opacity of the 1 px top-edge highlight, 0–1 (0: none). */
+ edge: number;
+}
+
export interface Theme {
+ /** Whether `bg` is dark or light; components pick shadows and chrome by it. */
+ mode: "dark" | "light";
color: {
bg: string;
surface: string;
@@ -17,19 +40,48 @@ export interface Theme {
positive: string;
negative: string;
highlight: string;
+ /** Shadow color (elevation). */
+ shadow: string;
};
font: { display: string; body: string; mono: string; hand?: string };
+ /** Font weights by role, so one theme can swap a heavier or lighter family. */
+ weight: {
+ regular: number;
+ medium: number;
+ semibold: number;
+ bold: number;
+ heavy: number;
+ };
radius: { sm: number; md: number; lg: number; pill: number };
stroke: { hair: number; base: number; bold: number };
+ /** Surfaces: `low` (chips, tags), `mid` (cards, toasts), `high` (windows, modals). */
+ elevation: { low: Elevation; mid: Elevation; high: Elevation };
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 };
+ /** `settle` lands without overshoot, `base` overshoots a little, `pop` bounces. */
+ spring: { settle: Spring; base: Spring; pop: Spring };
};
+ /** Code token colors (CodeBlock); unset kinds use the built-in palette. */
+ syntax?: Partial<Record<SyntaxKind, string>>;
/** 1 = designed for 1080p. 2 for 4K, 0.5 for 540p. */
scale: number;
}
+/** Token kinds CodeBlock colors. */
+export type SyntaxKind =
+ | "plain"
+ | "keyword"
+ | "string"
+ | "number"
+ | "comment"
+ | "function"
+ | "type"
+ | "property"
+ | "punctuation"
+ | "operator";
+
export type ThemeInput = DeepPartial<Theme>;
type DeepPartial<T> = {
@@ -44,6 +96,31 @@ const motion: Theme["motion"] = {
snap: "back.out(1.6)",
},
speed: { fast: 8, base: 16, slow: 30 },
+ spring: {
+ settle: { stiffness: 230, damping: 24 },
+ base: { stiffness: 260, damping: 20 },
+ pop: { stiffness: 320, damping: 14 },
+ },
+};
+
+const weight: Theme["weight"] = {
+ regular: 400,
+ medium: 500,
+ semibold: 600,
+ bold: 700,
+ heavy: 800,
+};
+
+/** Dark grounds need deeper shadows, and a lit top edge to separate surfaces. */
+const darkElevation: Theme["elevation"] = {
+ low: { opacity: 0.32, distance: 3, size: 10, edge: 0.07 },
+ mid: { opacity: 0.4, distance: 10, size: 30, edge: 0.08 },
+ high: { opacity: 0.5, distance: 22, size: 60, edge: 0.1 },
+};
+const lightElevation: Theme["elevation"] = {
+ low: { opacity: 0.1, distance: 2, size: 8, edge: 0 },
+ mid: { opacity: 0.14, distance: 8, size: 26, edge: 0 },
+ high: { opacity: 0.2, distance: 18, size: 54, edge: 0 },
};
const shape = {
@@ -61,6 +138,7 @@ const fonts: Theme["font"] = {
export const themes = {
/** Dark neutral: product demos, dev tools. */
graphite: {
+ mode: "dark",
color: {
bg: "#0d0e11",
surface: "#16181d",
@@ -73,14 +151,18 @@ export const themes = {
positive: "#3ecf8e",
negative: "#ff5c5c",
highlight: "#ffd23f",
+ shadow: "#000000",
},
font: fonts,
+ weight,
...shape,
+ elevation: darkElevation,
motion,
scale: 1,
},
/** Light editorial: explainers, documentaries. */
paper: {
+ mode: "light",
color: {
bg: "#f4f1ea",
surface: "#fffdf8",
@@ -93,14 +175,18 @@ export const themes = {
positive: "#1f8a4c",
negative: "#c8282d",
highlight: "#ffe066",
+ shadow: "#3b2f1e",
},
font: fonts,
+ weight,
...shape,
+ elevation: lightElevation,
motion,
scale: 1,
},
/** High contrast, saturated accent: social clips. */
signal: {
+ mode: "dark",
color: {
bg: "#000000",
surface: "#111111",
@@ -113,13 +199,21 @@ export const themes = {
positive: "#00e676",
negative: "#ff1744",
highlight: "#c6ff00",
+ shadow: "#000000",
},
font: fonts,
+ weight,
...shape,
+ elevation: darkElevation,
motion: {
...motion,
ease: { ...motion.ease, enter: "back.out(1.8)" },
speed: { fast: 6, base: 12, slow: 24 },
+ spring: {
+ settle: { stiffness: 300, damping: 26 },
+ base: { stiffness: 340, damping: 22 },
+ pop: { stiffness: 400, damping: 14 },
+ },
},
scale: 1,
},
@@ -136,6 +230,12 @@ export function defineTheme(
base: Theme = themes.graphite,
): Theme {
const theme = merge(base, input) as Theme;
+ // A new background without a mode says which one it is.
+ if (input.mode === undefined && input.color?.bg !== undefined) {
+ theme.mode = isLight(theme.color.bg) ? "light" : "dark";
+ if (input.elevation === undefined)
+ theme.elevation = theme.mode === "light" ? lightElevation : darkElevation;
+ }
const ratio = contrastRatio(theme.color.ink, theme.color.surface);
if (ratio !== null && ratio < 4.5) {
throw new Error(
@@ -172,29 +272,3 @@ function merge(base: unknown, over: unknown): unknown {
}
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/device-frame/meta.ts b/packages/components/src/device-frame/meta.ts
index bf597740..8d099258 100644
--- a/packages/components/src/device-frame/meta.ts
+++ b/packages/components/src/device-frame/meta.ts
@@ -25,6 +25,7 @@ export default defineMeta({
"base",
"shadow",
"tilt",
+ "overlay",
],
cues: [],
example: `DeviceFrame({ device: "phone", content: "assets/app.mp4" })`,
diff --git a/packages/components/src/focus-zoom/index.ts b/packages/components/src/focus-zoom/index.ts
index 9640fd6b..64fd88f7 100644
--- a/packages/components/src/focus-zoom/index.ts
+++ b/packages/components/src/focus-zoom/index.ts
@@ -111,9 +111,9 @@ export const focusZoom = /* @__PURE__ */ defineComponent({
}),
defaults: { enter: false, exit: false },
build(ctx, props) {
- const { host, theme, fps } = ctx;
- const W = ctx.requested.width ?? 1920 * theme.scale;
- const H = ctx.requested.height ?? 1080 * theme.scale;
+ const { host, fps } = ctx;
+ const W = ctx.requested.width ?? ctx.canvas.width;
+ const H = ctx.requested.height ?? ctx.canvas.height;
// By default the push starts early enough to run at its natural pace.
const lead =
props.lead ?? Math.round((0.55 + 0.75 * props.smoothing) * fps) + 2;
diff --git a/packages/components/src/ids.test.ts b/packages/components/src/ids.test.ts
index 48782001..824c9cdc 100644
--- a/packages/components/src/ids.test.ts
+++ b/packages/components/src/ids.test.ts
@@ -1,32 +1,5 @@
import { describe, expect, it } from "vitest";
-import { annotate } from "./annotate/index.js";
-import { appFrame } from "./app-frame/index.js";
-import { backdrop } from "./backdrop/index.js";
-import { beforeAfter } from "./before-after/index.js";
-import { callout } from "./callout/index.js";
-import { captions } from "./captions/index.js";
-import { cardStack } from "./card-stack/index.js";
-import { chatThread } from "./chat-thread/index.js";
-import { codeBlock } from "./code-block/index.js";
-import { confetti } from "./confetti/index.js";
-import { bind } from "./core/contract.js";
-import { counter } from "./counter/index.js";
-import { deviceFrame } from "./device-frame/index.js";
-import { focusZoom } from "./focus-zoom/index.js";
-import { logoReveal } from "./logo-reveal/index.js";
-import { lowerThird } from "./lower-third/index.js";
-import { meter } from "./meter/index.js";
-import { mousePointer } from "./mouse-pointer/index.js";
-import { selection } from "./selection/index.js";
-import { spotlight } from "./spotlight/index.js";
-import { terminal } from "./terminal/index.js";
-import { fakeHost } from "./test/fake-host.js";
-import { textReveal } from "./text-reveal/index.js";
-import { titleCard } from "./title-card/index.js";
-import { toasts } from "./toasts/index.js";
-import { touchPoint } from "./touch-point/index.js";
-import { waveform } from "./waveform/index.js";
-import { wordCycle } from "./word-cycle/index.js";
+import { cases } from "./test/cases.js";
/**
* The renderer keys layout and motion by node id: two nodes with one id
@@ -43,376 +16,6 @@ function ids(node: unknown, out: string[] = []): string[] {
if (n.matte) ids(n.matte.node, out);
return out;
}
-const words = "one two three four"
- .split(" ")
- .map((text, i) => ({ text, start: i * 0.4, end: i * 0.4 + 0.3 }));
-const text = {
- kind: "text",
- id: "t",
- text: "mark these words",
- x: 0,
- y: 0,
- width: 200,
- fontSize: 20,
- fontFamily: "Inter",
-};
-
-const cases: Array<[string, () => unknown]> = [
- [
- "MousePointer",
- () =>
- bind(
- fakeHost(),
- mousePointer,
- )({
- path: [{ to: [10, 10] }, { to: [200, 100], click: 2 }],
- trail: {},
- label: "Hi",
- }),
- ],
- [
- "AppFrame",
- () =>
- bind(
- fakeHost(),
- appFrame,
- )({
- kind: "browser",
- url: { text: "a.dev", typeAt: 4 },
- tabs: ["a", "b"],
- }),
- ],
- [
- "FocusZoom",
- () =>
- bind(
- fakeHost(),
- focusZoom,
- )({ content: [], shots: [{ at: 0, target: [100, 100] }] }),
- ],
- ...(
- [
- "rise",
- "slam",
- "scramble",
- "mask",
- "wipe",
- "type",
- "stream",
- "scatter",
- ] as const
- ).map(
- (style) =>
- [
- `TextReveal ${style}`,
- () =>
- bind(
- fakeHost(),
- textReveal,
- )({
- text: "aa bb cc",
- style,
- exitStyle: style === "mask" ? "mask" : "rise",
- width: 60,
- }),
- ] as [string, () => unknown],
- ),
- [
- "Counter",
- () =>
- bind(
- fakeHost(),
- counter,
- )({ to: 12345.5, format: "$,.2f", values: undefined }),
- ],
- [
- "Annotate",
- () =>
- bind(
- fakeHost(),
- annotate,
- )({
- target: { text, match: "these words" },
- mark: "highlight",
- label: "x",
- }),
- ],
- [
- "Annotate arrow",
- () =>
- bind(
- fakeHost(),
- annotate,
- )({ target: [100, 100], mark: "arrow", from: [10, 10] }),
- ],
- ...(["karaoke", "highlight", "pill", "gradient", "bold"] as const).map(
- (style) =>
- [
- `Captions ${style}`,
- () =>
- bind(
- fakeHost(),
- captions,
- )({ words, style, behind: { video: "v.mp4" } }),
- ] as [string, () => unknown],
- ),
- [
- "Terminal",
- () =>
- bind(
- fakeHost(),
- terminal,
- )({
- script: [
- { cmd: "ls" },
- { spinner: "a", for: 10 },
- { progress: "p", for: 10 },
- { output: ["x", "y"] },
- { clear: true },
- ],
- }),
- ],
- [
- "CodeBlock",
- () =>
- bind(
- fakeHost(),
- codeBlock,
- )({
- code: "a\nb\nc",
- typing: true,
- focus: [{ at: 5, lines: [1] }],
- diff: { to: "a\n c\nd", at: 40 },
- frame: true,
- }),
- ],
- ...(["center", "left", "stack", "split"] as const).map(
- (layout) =>
- [
- `TitleCard ${layout}`,
- () =>
- bind(
- fakeHost(),
- titleCard,
- )({
- kicker: "k",
- title: "Title",
- subtitle: "s",
- layout,
- exitStyle: "rise",
- }),
- ] as [string, () => unknown],
- ),
- ...(["bar", "stacked", "tag", "line"] as const).map(
- (layout) =>
- [
- `LowerThird ${layout}`,
- () =>
- bind(
- fakeHost(),
- lowerThird,
- )({ name: "Ada", role: "Engineer", layout }),
- ] as [string, () => unknown],
- ),
- ...(["ring", "arc", "bar", "segments", "stars"] as const).map(
- (kind) =>
- [
- `Meter ${kind}`,
- () =>
- bind(
- fakeHost(),
- meter,
- )({ value: kind === "stars" ? 3.5 : 60, kind, label: "L" }),
- ] as [string, () => unknown],
- ),
- [
- "ChatThread",
- () =>
- bind(
- fakeHost(),
- chatThread,
- )({
- messages: [
- { from: "me", text: "a", reaction: "❤️" },
- { from: "b", text: "c", time: "1:00" },
- { from: "c", image: "x.png" },
- ],
- }),
- ],
- [
- "Toasts",
- () =>
- bind(
- fakeHost(),
- toasts,
- )({
- items: [
- { at: 0, title: "a", body: "b", kind: "success" },
- { at: 10, title: "c", kind: "error" },
- ],
- }),
- ],
- [
- "Callout",
- () =>
- bind(fakeHost(), callout)({ target: [100, 100], title: "t", text: "x" }),
- ],
- [
- "Spotlight",
- () =>
- bind(
- fakeHost(),
- spotlight,
- )({
- targets: [
- { at: 0, target: [10, 10] },
- { at: 20, target: "full" },
- ],
- shape: "ellipse",
- }),
- ],
- [
- "Confetti",
- () =>
- bind(
- fakeHost(),
- confetti,
- )({
- bursts: [
- { at: 0, origin: [10, 10] },
- { at: 5, origin: [90, 10] },
- ],
- }),
- ],
- ...(["slide", "pop", "draw", "rise"] as const).map(
- (style) =>
- [
- `LogoReveal ${style}`,
- () =>
- bind(
- fakeHost(),
- logoReveal,
- )({
- mark: { d: "M0 0L1 1Z", viewBox: [1, 1] },
- name: "ab",
- tagline: "t",
- style,
- }),
- ] as [string, () => unknown],
- ),
- ...(["mesh", "grid", "dots", "solid"] as const).map(
- (kind) =>
- [`Backdrop ${kind}`, () => bind(fakeHost(), backdrop)({ kind })] as [
- string,
- () => unknown,
- ],
- ),
- ...(["bars", "mirror", "dots", "radial"] as const).map(
- (kind) =>
- [
- `Waveform ${kind}`,
- () =>
- bind(
- fakeHost(),
- waveform,
- )({
- audio: {
- fps: 30,
- frames: 2,
- bands: [
- [0, 1],
- [1, 0],
- ],
- level: [0, 1],
- beats: [],
- },
- kind,
- bars: 4,
- }),
- ] as [string, () => unknown],
- ),
- ...(["roll", "fade", "slide", "type"] as const).map(
- (transition) =>
- [
- `WordCycle ${transition}`,
- () =>
- bind(
- fakeHost(),
- wordCycle,
- )({
- text: "a {} b",
- words: ["x", "yy", "zzz"],
- transition,
- slot: "pill",
- }),
- ] as [string, () => unknown],
- ),
- ...(["phone", "tablet", "laptop"] as const).map(
- (device) =>
- [
- `DeviceFrame ${device}`,
- () =>
- bind(fakeHost(), deviceFrame)({ device, content: "a.mp4", tilt: {} }),
- ] as [string, () => unknown],
- ),
- [
- "TouchPoint",
- () =>
- bind(
- fakeHost(),
- touchPoint,
- )({
- touches: [
- { to: [10, 10], tap: 2 },
- { to: [20, 20], press: 20 },
- { to: [30, 30], swipe: [30, 300] },
- ],
- }),
- ],
- [
- "BeforeAfter",
- () => bind(fakeHost(), beforeAfter)({ before: "a.mp4", after: "b.mp4" }),
- ],
- [
- "Selection text",
- () =>
- bind(
- fakeHost(),
- selection,
- )({ target: { text }, drag: { frame: 0, end: 10 } }),
- ],
- [
- "Selection marquee",
- () =>
- bind(
- fakeHost(),
- selection,
- )({
- kind: "marquee",
- drag: { frame: 0, end: 10 },
- items: [[5, 5], { x: 0, y: 0, width: 9, height: 9 }],
- }),
- ],
- ...(["cycle", "deal"] as const).map(
- (mode) =>
- [
- `CardStack ${mode}`,
- () =>
- bind(
- fakeHost(),
- cardStack,
- )({
- cards: [
- { title: "a", body: "b", image: "i.png" },
- { title: "c" },
- { title: "d" },
- ],
- mode,
- }),
- ] as [string, () => unknown],
- ),
-];
-
describe("node ids", () => {
for (const [name, build] of cases)
it(`${name} emits unique ids`, () => {
diff --git a/packages/components/src/index.ts b/packages/components/src/index.ts
index f72e2a9d..aa19c579 100644
--- a/packages/components/src/index.ts
+++ b/packages/components/src/index.ts
@@ -73,8 +73,21 @@ export {
springAt,
springKeys,
springSettleFrames,
+ springTrack,
} from "./core/bake.js";
export {
+ contrastRatio,
+ inkOn,
+ isLight,
+ luminance,
+ mix,
+ parseColor,
+ type Rgba,
+ transparent,
+ withAlpha,
+} from "./core/color.js";
+export {
+ after,
type BaseProps,
type BuildContext,
type BuildResult,
@@ -90,9 +103,11 @@ export {
defineComponent,
offsetCues,
type Placement,
+ type ProjectDefaults,
type PropsOf,
type PulseOptions,
pulseKeys,
+ withDefaults,
} from "./core/contract.js";
export {
type ArrowCurve,
@@ -132,7 +147,27 @@ export type {
MediaOptions,
ParticleOptions,
} from "./core/host.js";
-export { type ComponentMeta, defineMeta } from "./core/meta.js";
+export {
+ ascending,
+ KeyBook,
+ last,
+ round,
+ supersede,
+ Track,
+ valueAt,
+} from "./core/keys.js";
+export {
+ type CanvasSize,
+ SAFE_INSETS,
+ type SafeInsets,
+ safeArea,
+} from "./core/layout.js";
+export {
+ type ComponentMeta,
+ defineMeta,
+ type FontNeed,
+ type FontRole,
+} from "./core/meta.js";
export {
enterAnimation,
exitAnimation,
@@ -154,6 +189,12 @@ export {
type Vec2,
} from "./core/path.js";
export { hashRng, hashString, type Rng, rng } from "./core/rng.js";
+export {
+ type ElevationLevel,
+ elevate,
+ elevationStyle,
+ surfaceFill,
+} from "./core/surface.js";
export {
type Anchor,
anchorPoint,
@@ -178,8 +219,10 @@ export {
wordRanges,
} from "./core/text.js";
export {
- contrastRatio,
defineTheme,
+ type Elevation,
+ type Spring,
+ type SyntaxKind,
type Theme,
type ThemeInput,
type ThemeName,
@@ -275,7 +318,6 @@ export {
titleCard,
} from "./title-card/index.js";
export {
- springTrack,
TOAST_CORNERS,
TOAST_KINDS,
type ToastCorner,
diff --git a/packages/components/src/logo-reveal/index.ts b/packages/components/src/logo-reveal/index.ts
index 20eae828..34444216 100644
--- a/packages/components/src/logo-reveal/index.ts
+++ b/packages/components/src/logo-reveal/index.ts
@@ -36,7 +36,6 @@ export interface LogoRevealCues {
glint: ReadonlyArray<{ frame: number }>;
}
-const POP = { stiffness: 260, damping: 14 };
const SWING = { stiffness: 120, damping: 14 };
export const logoReveal = /* @__PURE__ */ defineComponent({
@@ -254,7 +253,15 @@ export const logoReveal = /* @__PURE__ */ defineComponent({
const anim = LayerAnimation.create();
const scale: KeyframeTuple[] = [];
if (style === "slide" || style === "pop")
- scale.push(...(springKeys(0, 0, 1, fps, POP) as KeyframeTuple[]));
+ scale.push(
+ ...(springKeys(
+ 0,
+ 0,
+ 1,
+ fps,
+ theme.motion.spring.pop,
+ ) as KeyframeTuple[]),
+ );
if (glints) {
// A small bump as the light passes.
if (scale.length === 0) scale.push([0, 1]);
diff --git a/packages/components/src/lower-third/index.ts b/packages/components/src/lower-third/index.ts
index 125743a1..573ac4c5 100644
--- a/packages/components/src/lower-third/index.ts
+++ b/packages/components/src/lower-third/index.ts
@@ -4,17 +4,17 @@
* through their own box, and leave on their own after `hold`.
*
* Coordinates are the frame's: the root covers the video (default
- * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.
+ * the composition `canvas`, or the given width / height) from 0, 0.
*/
-import {
- type KeyframeTuple,
- LayerAnimation,
- type LayoutNode,
-} from "@framefields/compositions/program";
+import type { LayoutNode } from "@framefields/compositions/program";
import { z } from "zod";
+import { parseColor } from "../core/color.js";
import { defineComponent } from "../core/contract.js";
import type { Rect } from "../core/draw.js";
import type { Animatable } from "../core/host.js";
+import { KeyBook } from "../core/keys.js";
+import { safeArea } from "../core/layout.js";
+import { elevate, surfaceFill } from "../core/surface.js";
import { themeFrames } from "../core/theme.js";
export const LOWER_THIRD_LAYOUTS = ["bar", "stacked", "tag", "line"] as const;
@@ -31,18 +31,6 @@ export interface LowerThirdCues {
out: ReadonlyArray<{ frame: number }>;
}
-function safeArea(
- W: number,
- H: number,
- area: "portrait" | "landscape" | Rect | undefined,
-): Rect {
- if (area && typeof area === "object") return area;
- const portrait = area ? area === "portrait" : H > W;
- return portrait
- ? { x: W * 0.08, y: H * 0.1, width: W * 0.84, height: H * 0.66 }
- : { x: W * 0.06, y: H * 0.08, width: W * 0.88, height: H * 0.82 };
-}
-
export const lowerThird = /* @__PURE__ */ defineComponent({
name: "LowerThird",
props: () => ({
@@ -72,9 +60,9 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
build(ctx, props) {
const { host, theme, fps } = ctx;
const s = theme.scale;
- const W = ctx.requested.width ?? 1920 * s;
- const H = ctx.requested.height ?? 1080 * s;
- const safe = safeArea(W, H, props.safeArea);
+ const W = ctx.requested.width ?? ctx.canvas.width;
+ const H = ctx.requested.height ?? ctx.canvas.height;
+ const safe = safeArea({ width: W, height: H }, props.safeArea);
const fontFamily = props.fontFamily ?? theme.font.display;
const nameSize = props.nameSize ?? 44 * s;
const roleSize = nameSize * 0.62;
@@ -88,13 +76,13 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
const nameM = host.measure(props.name, {
fontFamily,
fontSize: nameSize,
- fontWeight: 700,
+ fontWeight: theme.weight.bold,
});
const roleM = props.role
? host.measure(props.role, {
fontFamily,
fontSize: roleSize,
- fontWeight: 500,
+ fontWeight: theme.weight.medium,
})
: null;
const padX = nameSize * 0.55;
@@ -102,19 +90,8 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
const children: LayoutNode[] = [];
const parts: Record<string, Animatable<LayoutNode>> = {};
/** Keys per node and prop, merged into one track each at the end. */
- const tracks = new Map<
- Animatable<LayoutNode>,
- Map<string, KeyframeTuple[]>
- >();
- const key = (
- node: Animatable<LayoutNode>,
- prop: string,
- keys: KeyframeTuple[],
- ) => {
- const byProp = tracks.get(node) ?? new Map<string, KeyframeTuple[]>();
- tracks.set(node, byProp);
- byProp.set(prop, [...(byProp.get(prop) ?? []), ...keys]);
- };
+ const book = new KeyBook<Animatable<LayoutNode>>();
+ const key = book.key.bind(book);
const text = (
id: string,
@@ -155,8 +132,10 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
y: 0,
width: rect.width,
height: rect.height,
- background,
+ background: surfaceFill(background, theme),
borderRadius: radius,
+ // The slide is fast: a little smear sells it.
+ motionBlurShutter: 90,
});
const travel = rect.width * (right ? 1 : -1);
const slide = Math.round(base * 1.1);
@@ -184,6 +163,8 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
borderRadius: radius,
children: [fill, ...content],
});
+ // A clear plate (the `line` layout) has nothing to lift.
+ if (parseColor(background)?.[3] !== 0) elevate(host, clip, theme, "low");
children.push(clip);
parts[id] = clip;
return {
@@ -212,7 +193,15 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
const rect = { x: xFor(w), y: bottom - h, width: w, height: h };
const tx = right ? padX : padX + edge;
const content = [
- text("name", props.name, nameSize, 700, theme.color.ink, tx, padY),
+ text(
+ "name",
+ props.name,
+ nameSize,
+ theme.weight.bold,
+ theme.color.ink,
+ tx,
+ padY,
+ ),
];
if (props.role && roleM)
content.push(
@@ -220,7 +209,7 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
"role",
props.role,
roleSize,
- 500,
+ theme.weight.medium,
theme.color.muted,
tx,
padY + nameM.height * 0.95,
@@ -270,7 +259,7 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
"name",
props.name,
nameSize,
- 700,
+ theme.weight.bold,
theme.color.ink,
padX,
padY,
@@ -296,7 +285,7 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
"role",
props.role,
roleSize,
- 600,
+ theme.weight.semibold,
theme.color.bg,
padX * 0.8,
padY * 0.6,
@@ -326,13 +315,17 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
fontSize: nameSize,
fill: theme.color.ink,
spans: [
- { text: props.name, fontWeight: 700, fill: theme.color.ink },
+ {
+ text: props.name,
+ fontWeight: theme.weight.bold,
+ fill: theme.color.ink,
+ },
...(props.role
? [
{
text: `${sep}${props.role}`,
fontSize: roleSize,
- fontWeight: 500,
+ fontWeight: theme.weight.medium,
fill: theme.color.muted,
// Centred on the name's capitals, not on its baseline: one
// line in a pill reads as aligned when the caps share a middle.
@@ -385,7 +378,15 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
children.push(accentLine);
parts.line = accentLine;
const content = [
- text("name", props.name, nameSize, 700, theme.color.ink, tx, 0),
+ text(
+ "name",
+ props.name,
+ nameSize,
+ theme.weight.bold,
+ theme.color.ink,
+ tx,
+ 0,
+ ),
];
if (props.role && roleM)
content.push(
@@ -393,7 +394,7 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
"role",
props.role,
roleSize,
- 500,
+ theme.weight.medium,
theme.color.muted,
tx,
nameM.height,
@@ -441,15 +442,7 @@ export const lowerThird = /* @__PURE__ */ defineComponent({
[outAt + afterHold, 0, "power2.in"],
]);
}
- for (const [node, byProp] of tracks) {
- const a = LayerAnimation.create();
- for (const [prop, keys] of byProp)
- a.keys(
- prop as "x",
- [...keys].sort((x, y) => x[0] - y[0]),
- );
- node.animate(a);
- }
+ book.apply();
return {
children,
diff --git a/packages/components/src/meta.test.ts b/packages/components/src/meta.test.ts
new file mode 100644
index 00000000..58670537
--- /dev/null
+++ b/packages/components/src/meta.test.ts
@@ -0,0 +1,56 @@
+import { readdirSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+import type { ComponentMeta } from "./core/meta.js";
+import { cases } from "./test/cases.js";
+
+/**
+ * `meta.ts` is what docs and agents read: its cue and part names must match
+ * what the component builds. Patterns like `line-<n>` stand for any suffix.
+ */
+const SRC = new URL(".", import.meta.url).pathname;
+const folders = readdirSync(SRC, { withFileTypes: true })
+ .filter((e) => e.isDirectory() && e.name !== "core" && e.name !== "test")
+ .map((e) => e.name);
+const metas = new Map<string, ComponentMeta>();
+for (const folder of folders) {
+ const mod = (await import(`./${folder}/meta.ts`)) as {
+ default: ComponentMeta;
+ };
+ metas.set(mod.default.name, mod.default);
+}
+
+const nameOf = (label: string) => label.split(" ")[0] as string;
+const pattern = (part: string) =>
+ new RegExp(`^${part.replace(/<[a-z]+>/g, "[\\w-]+")}$`);
+
+interface Built {
+ cues: Record<string, unknown>;
+ partNames: readonly string[];
+}
+
+describe("component meta", () => {
+ it("every component folder has a case in test/cases.ts", () => {
+ const covered = new Set(cases.map(([label]) => nameOf(label)));
+ expect([...metas.keys()].filter((n) => !covered.has(n))).toEqual([]);
+ });
+
+ for (const [label, build] of cases) {
+ const meta = metas.get(nameOf(label));
+ it(`${label}: cues match meta.cues`, () => {
+ expect(meta).toBeDefined();
+ const node = build() as Built;
+ expect(Object.keys(node.cues).sort()).toEqual(
+ [...(meta?.cues ?? [])].sort(),
+ );
+ });
+ it(`${label}: every part is named in meta.parts`, () => {
+ const node = build() as Built;
+ const listed = (meta?.parts ?? []).map(pattern);
+ const unlisted = node.partNames.filter(
+ (p) =>
+ p !== "root" && p !== "stage" && !listed.some((re) => re.test(p)),
+ );
+ expect(unlisted).toEqual([]);
+ });
+ }
+});
diff --git a/packages/components/src/meter/index.ts b/packages/components/src/meter/index.ts
index 526fab9a..1ee2be18 100644
--- a/packages/components/src/meter/index.ts
+++ b/packages/components/src/meter/index.ts
@@ -11,6 +11,7 @@ import { z } from "zod";
import { bakeSamples } from "../core/bake.js";
import { bind, defineComponent } from "../core/contract.js";
import type { Animatable } from "../core/host.js";
+import { ascending } from "../core/keys.js";
import { toPathData, type Vec2 } from "../core/path.js";
import { themeFrames } from "../core/theme.js";
import { counter } from "../counter/index.js";
@@ -131,7 +132,7 @@ export const meter = /* @__PURE__ */ defineComponent({
ease,
fontFamily,
fontSize: size,
- fontWeight: 700,
+ fontWeight: theme.weight.bold,
align,
x: 0,
y: 0,
@@ -437,13 +438,3 @@ export const meter = /* @__PURE__ */ defineComponent({
};
},
});
-
-function ascending(keys: KeyframeTuple[]): KeyframeTuple[] {
- const out: KeyframeTuple[] = [];
- for (const k of [...keys].sort((a, b) => a[0] - b[0])) {
- while (out.length > 0 && (out[out.length - 1] as KeyframeTuple)[0] >= k[0])
- out.pop();
- out.push(k);
- }
- return out;
-}
diff --git a/packages/components/src/mouse-pointer/index.ts b/packages/components/src/mouse-pointer/index.ts
index f650d78c..d638736a 100644
--- a/packages/components/src/mouse-pointer/index.ts
+++ b/packages/components/src/mouse-pointer/index.ts
@@ -13,12 +13,12 @@ import {
} from "@framefields/compositions/program";
import { z } from "zod";
import { bakeSamples } from "../core/bake.js";
+import { contrastRatio } from "../core/color.js";
import { defineComponent } from "../core/contract.js";
import type { Animatable } from "../core/host.js";
import { transformPathData, type Vec2 } from "../core/path.js";
import { targetSchema } from "../core/schemas.js";
import { resolveTarget, type Target, targetPoint } from "../core/targets.js";
-import { contrastRatio } from "../core/theme.js";
import {
CURSOR_STYLES,
type CursorStyle,
@@ -160,10 +160,10 @@ export const mousePointer = /* @__PURE__ */ defineComponent({
from: z.union([z.enum(EDGES), targetSchema()]).optional(),
/** Leave to off-frame on this edge (or to a point) instead of fading away. */
to: z.union([z.enum(EDGES), targetSchema()]).optional(),
- /** The frame the pointer lives in (for edges). Default 1920 × 1080. */
+ /** The frame the pointer lives in (for edges). Default: the composition `canvas`. */
area: z
.object({ width: z.number().positive(), height: z.number().positive() })
- .default({ width: 1920, height: 1080 }),
+ .optional(),
}),
defaults: { enter: false, exit: false },
build(ctx, props) {
@@ -172,7 +172,7 @@ export const mousePointer = /* @__PURE__ */ defineComponent({
const k = size / 24;
const accent = props.accent ?? theme.color.accent;
const outlineWidth = props.outlineWidth ?? size / 16;
- const { width: W, height: H } = props.area;
+ const { width: W, height: H } = props.area ?? ctx.canvas;
const resolvePoint = (target: Target): { point: PointAt; id?: string } => {
const resolved = resolveTarget(target, { measure: host.measure, fps });
@@ -304,7 +304,7 @@ export const mousePointer = /* @__PURE__ */ defineComponent({
: host.measure(labelText, {
fontFamily: theme.font.body,
fontSize: labelFont,
- fontWeight: 600,
+ fontWeight: theme.weight.semibold,
});
const labelPadX = Math.round(labelFont * 0.62);
const labelH = Math.round(labelFont * 1.8);
@@ -419,7 +419,7 @@ export const mousePointer = /* @__PURE__ */ defineComponent({
y: Math.round((labelH - labelMetrics.lineHeight) / 2),
fontFamily: theme.font.body,
fontSize: labelFont,
- fontWeight: 600,
+ fontWeight: theme.weight.semibold,
fill: ink,
}),
],
diff --git a/packages/components/src/selection/index.ts b/packages/components/src/selection/index.ts
index a53f738e..cee7a1ea 100644
--- a/packages/components/src/selection/index.ts
+++ b/packages/components/src/selection/index.ts
@@ -5,7 +5,7 @@
* covers.
*
* Coordinates are the frame's: the root covers the video (default
- * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.
+ * the composition `canvas`, or the given width / height) from 0, 0.
*/
import {
type KeyframeTuple,
@@ -14,10 +14,12 @@ import {
} from "@framefields/compositions/program";
import { z } from "zod";
import { bakeSamples } from "../core/bake.js";
+import { withAlpha } from "../core/color.js";
import { defineComponent } from "../core/contract.js";
import type { Rect } from "../core/draw.js";
import { evaluateEase } from "../core/ease.js";
import type { Animatable } from "../core/host.js";
+import { round as roundTo } from "../core/keys.js";
import type { Vec2 } from "../core/path.js";
import { targetSchema } from "../core/schemas.js";
import {
@@ -87,8 +89,8 @@ export const selection = /* @__PURE__ */ defineComponent({
build(ctx, props) {
const { host, theme, fps } = ctx;
const s = theme.scale;
- const W = ctx.requested.width ?? 1920 * s;
- const H = ctx.requested.height ?? 1080 * s;
+ const W = ctx.requested.width ?? ctx.canvas.width;
+ const H = ctx.requested.height ?? ctx.canvas.height;
const color = props.color ?? theme.color.accent;
const at0 = ctx.requested.at;
const drag = props.drag ?? props.pointer?.cues?.drags?.[0];
@@ -319,14 +321,4 @@ export const selection = /* @__PURE__ */ defineComponent({
},
});
-const round = (v: number) => Math.round(v * 100) / 100;
-
-/** `#rrggbb` / `#rgb` at alpha `a`; other colours pass through. */
-function withAlpha(color: string, a: number): string {
- const hex = color.trim().replace(/^#/, "");
- const full =
- hex.length === 3 ? hex.replace(/./g, (x) => x + x) : hex.slice(0, 6);
- if (!/^[0-9a-f]{6}$/i.test(full)) return color;
- const n = Number.parseInt(full, 16);
- return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`;
-}
+const round = (v: number) => roundTo(v, 2);
diff --git a/packages/components/src/selection/meta.ts b/packages/components/src/selection/meta.ts
index 71cff562..f2808af4 100644
--- a/packages/components/src/selection/meta.ts
+++ b/packages/components/src/selection/meta.ts
@@ -13,7 +13,7 @@ export default defineMeta({
"ui",
"pointer",
],
- parts: ["line-0", "marquee", "item-0"],
+ parts: ["line-<n>", "marquee", "item-<n>"],
cues: ["selected", "items"],
example: `Selection({ target: { text: paragraph, match: "the key line" }, pointer })`,
since: "M8",
diff --git a/packages/components/src/spotlight/index.ts b/packages/components/src/spotlight/index.ts
index 51da918a..985472eb 100644
--- a/packages/components/src/spotlight/index.ts
+++ b/packages/components/src/spotlight/index.ts
@@ -4,7 +4,7 @@
* target rects; a `"full"` step lifts the dim.
*
* Coordinates are the frame's: the root covers the video (default
- * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.
+ * the composition `canvas`, or the given width / height) from 0, 0.
*/
import {
type KeyframeTuple,
@@ -16,6 +16,7 @@ import { bakeSamples } from "../core/bake.js";
import { defineComponent } from "../core/contract.js";
import type { Rect } from "../core/draw.js";
import type { Animatable } from "../core/host.js";
+import { supersede } from "../core/keys.js";
import { targetSchema } from "../core/schemas.js";
import { boundsOf, resolveTarget } from "../core/targets.js";
import { themeFrames } from "../core/theme.js";
@@ -58,8 +59,8 @@ export const spotlight = /* @__PURE__ */ defineComponent({
build(ctx, props) {
const { host, theme, fps } = ctx;
const s = theme.scale;
- const W = ctx.requested.width ?? 1920 * s;
- const H = ctx.requested.height ?? 1080 * s;
+ const W = ctx.requested.width ?? ctx.canvas.width;
+ const H = ctx.requested.height ?? ctx.canvas.height;
const glide =
props.glide ?? Math.round(themeFrames(theme, "base", fps) * 1.6);
const ease = theme.motion.ease.move;
@@ -170,10 +171,10 @@ export const spotlight = /* @__PURE__ */ defineComponent({
});
hole.animate(
LayerAnimation.create()
- .keys("x", ascending(keys.x))
- .keys("y", ascending(keys.y))
- .keys("width", ascending(keys.width))
- .keys("height", ascending(keys.height)),
+ .keys("x", track(keys.x))
+ .keys("y", track(keys.y))
+ .keys("width", track(keys.width))
+ .keys("height", track(keys.height)),
);
const shade = host.box({
id: ctx.partId("dim"),
@@ -185,7 +186,7 @@ export const spotlight = /* @__PURE__ */ defineComponent({
background: props.color,
opacity: 0,
});
- shade.animate(LayerAnimation.keys("opacity", ascending(dimKeys)));
+ shade.animate(LayerAnimation.keys("opacity", track(dimKeys)));
host.matte(shade, hole, "alpha-inverted");
const parts: Record<string, Animatable<LayoutNode>> = { dim: shade, hole };
@@ -203,12 +204,6 @@ export const spotlight = /* @__PURE__ */ defineComponent({
},
});
-function ascending(keys: KeyframeTuple[]): KeyframeTuple[] {
- const out: KeyframeTuple[] = [];
- for (const k of keys) {
- while (out.length > 0 && (out[out.length - 1] as KeyframeTuple)[0] >= k[0])
- out.pop();
- out.push(k);
- }
- return out.length > 0 ? out : [[0, 0]];
-}
+/** Retargeting keys, or a single 0 key when nothing was keyed. */
+const track = (keys: KeyframeTuple[]): KeyframeTuple[] =>
+ keys.length > 0 ? supersede(keys) : [[0, 0]];
diff --git a/packages/components/src/terminal/index.ts b/packages/components/src/terminal/index.ts
index 06c13bc9..1ae1f7d7 100644
--- a/packages/components/src/terminal/index.ts
+++ b/packages/components/src/terminal/index.ts
@@ -14,6 +14,7 @@ import { z } from "zod";
import { appFrame } from "../app-frame/index.js";
import { bind, defineComponent } from "../core/contract.js";
import type { Animatable } from "../core/host.js";
+import { ascending } from "../core/keys.js";
import { toPathData, type Vec2 } from "../core/path.js";
import type { Theme } from "../core/theme.js";
import { counter } from "../counter/index.js";
@@ -148,7 +149,7 @@ export const terminal = /* @__PURE__ */ defineComponent({
fill: sp.color
? (colors[sp.color] ?? theme.color.ink)
: theme.color.ink,
- ...(sp.bold && { fontWeight: 700 }),
+ ...(sp.bold && { fontWeight: theme.weight.bold }),
}));
// ── Lines ─────────────────────────────────────────────────────────
@@ -450,14 +451,3 @@ export const terminal = /* @__PURE__ */ defineComponent({
};
},
});
-
-/** Keys must ascend: a later key at the same frame replaces the earlier one. */
-function ascending(keys: KeyframeTuple[]): KeyframeTuple[] {
- const out: KeyframeTuple[] = [];
- for (const k of keys) {
- while (out.length > 0 && (out[out.length - 1] as KeyframeTuple)[0] >= k[0])
- out.pop();
- out.push(k);
- }
- return out.length > 0 ? out : [[0, 0]];
-}
diff --git a/packages/components/src/terminal/meta.ts b/packages/components/src/terminal/meta.ts
index 2435941d..ddf6ff63 100644
--- a/packages/components/src/terminal/meta.ts
+++ b/packages/components/src/terminal/meta.ts
@@ -9,4 +9,5 @@ export default defineMeta({
cues: ["keystrokes", "submits", "outputs", "done"],
example: `Terminal({ script: [{ cmd: "pnpm add framefields" }, { spinner: "Installing", for: 40, done: "1 package added" }] })`,
since: "M3",
+ fonts: [{ font: "mono", why: "Monospace text for the shell." }],
});
diff --git a/packages/components/src/test/cases.ts b/packages/components/src/test/cases.ts
new file mode 100644
index 00000000..458a319b
--- /dev/null
+++ b/packages/components/src/test/cases.ts
@@ -0,0 +1,403 @@
+/**
+ * One build of every component (and its main variants) on the fake host,
+ * shared by the cross-component tests: unique ids, meta in sync.
+ */
+import { annotate } from "../annotate/index.js";
+import { appFrame } from "../app-frame/index.js";
+import { backdrop } from "../backdrop/index.js";
+import { beforeAfter } from "../before-after/index.js";
+import { callout } from "../callout/index.js";
+import { captions } from "../captions/index.js";
+import { cardStack } from "../card-stack/index.js";
+import { chatThread } from "../chat-thread/index.js";
+import { codeBlock } from "../code-block/index.js";
+import { confetti } from "../confetti/index.js";
+import { bind } from "../core/contract.js";
+import { counter } from "../counter/index.js";
+import { deviceFrame } from "../device-frame/index.js";
+import { focusZoom } from "../focus-zoom/index.js";
+import { logoReveal } from "../logo-reveal/index.js";
+import { lowerThird } from "../lower-third/index.js";
+import { meter } from "../meter/index.js";
+import { mousePointer } from "../mouse-pointer/index.js";
+import { selection } from "../selection/index.js";
+import { spotlight } from "../spotlight/index.js";
+import { terminal } from "../terminal/index.js";
+import { textReveal } from "../text-reveal/index.js";
+import { titleCard } from "../title-card/index.js";
+import { toasts } from "../toasts/index.js";
+import { touchPoint } from "../touch-point/index.js";
+import { waveform } from "../waveform/index.js";
+import { wordCycle } from "../word-cycle/index.js";
+import { fakeHost } from "./fake-host.js";
+
+const words = "one two three four"
+ .split(" ")
+ .map((text, i) => ({ text, start: i * 0.4, end: i * 0.4 + 0.3 }));
+const text = {
+ kind: "text",
+ id: "t",
+ text: "mark these words",
+ x: 0,
+ y: 0,
+ width: 200,
+ fontSize: 20,
+ fontFamily: "Inter",
+};
+
+/** Every component, built with its options switched on. Name: `<Component>[ variant]`. */
+export const cases: Array<[string, () => unknown]> = [
+ [
+ "MousePointer",
+ () =>
+ bind(
+ fakeHost(),
+ mousePointer,
+ )({
+ path: [{ to: [10, 10] }, { to: [200, 100], click: 2 }],
+ trail: {},
+ label: "Hi",
+ }),
+ ],
+ [
+ "AppFrame",
+ () =>
+ bind(
+ fakeHost(),
+ appFrame,
+ )({
+ kind: "browser",
+ url: { text: "a.dev", typeAt: 4 },
+ tabs: ["a", "b"],
+ }),
+ ],
+ [
+ "FocusZoom",
+ () =>
+ bind(
+ fakeHost(),
+ focusZoom,
+ )({ content: [], shots: [{ at: 0, target: [100, 100] }] }),
+ ],
+ ...(
+ [
+ "rise",
+ "slam",
+ "scramble",
+ "mask",
+ "wipe",
+ "type",
+ "stream",
+ "scatter",
+ ] as const
+ ).map(
+ (style) =>
+ [
+ `TextReveal ${style}`,
+ () =>
+ bind(
+ fakeHost(),
+ textReveal,
+ )({
+ text: "aa bb cc",
+ style,
+ exitStyle: style === "mask" ? "mask" : "rise",
+ width: 60,
+ }),
+ ] as [string, () => unknown],
+ ),
+ [
+ "Counter",
+ () =>
+ bind(
+ fakeHost(),
+ counter,
+ )({ to: 12345.5, format: "$,.2f", values: undefined }),
+ ],
+ [
+ "Annotate",
+ () =>
+ bind(
+ fakeHost(),
+ annotate,
+ )({
+ target: { text, match: "these words" },
+ mark: "highlight",
+ label: "x",
+ }),
+ ],
+ [
+ "Annotate arrow",
+ () =>
+ bind(
+ fakeHost(),
+ annotate,
+ )({ target: [100, 100], mark: "arrow", from: [10, 10] }),
+ ],
+ ...(["karaoke", "highlight", "pill", "gradient", "bold"] as const).map(
+ (style) =>
+ [
+ `Captions ${style}`,
+ () =>
+ bind(
+ fakeHost(),
+ captions,
+ )({ words, style, behind: { video: "v.mp4" } }),
+ ] as [string, () => unknown],
+ ),
+ [
+ "Terminal",
+ () =>
+ bind(
+ fakeHost(),
+ terminal,
+ )({
+ script: [
+ { cmd: "ls" },
+ { spinner: "a", for: 10 },
+ { progress: "p", for: 10 },
+ { output: ["x", "y"] },
+ { clear: true },
+ ],
+ }),
+ ],
+ [
+ "CodeBlock",
+ () =>
+ bind(
+ fakeHost(),
+ codeBlock,
+ )({
+ code: "a\nb\nc",
+ typing: true,
+ focus: [{ at: 5, lines: [1] }],
+ diff: { to: "a\n c\nd", at: 40 },
+ frame: true,
+ }),
+ ],
+ ...(["center", "left", "stack", "split"] as const).map(
+ (layout) =>
+ [
+ `TitleCard ${layout}`,
+ () =>
+ bind(
+ fakeHost(),
+ titleCard,
+ )({
+ kicker: "k",
+ title: "Title",
+ subtitle: "s",
+ layout,
+ exitStyle: "rise",
+ }),
+ ] as [string, () => unknown],
+ ),
+ ...(["bar", "stacked", "tag", "line"] as const).map(
+ (layout) =>
+ [
+ `LowerThird ${layout}`,
+ () =>
+ bind(
+ fakeHost(),
+ lowerThird,
+ )({ name: "Ada", role: "Engineer", layout }),
+ ] as [string, () => unknown],
+ ),
+ ...(["ring", "arc", "bar", "segments", "stars"] as const).map(
+ (kind) =>
+ [
+ `Meter ${kind}`,
+ () =>
+ bind(
+ fakeHost(),
+ meter,
+ )({ value: kind === "stars" ? 3.5 : 60, kind, label: "L" }),
+ ] as [string, () => unknown],
+ ),
+ [
+ "ChatThread",
+ () =>
+ bind(
+ fakeHost(),
+ chatThread,
+ )({
+ messages: [
+ { from: "me", text: "a", reaction: "❤️" },
+ { from: "b", text: "c", time: "1:00" },
+ { from: "c", image: "x.png" },
+ ],
+ }),
+ ],
+ [
+ "Toasts",
+ () =>
+ bind(
+ fakeHost(),
+ toasts,
+ )({
+ items: [
+ { at: 0, title: "a", body: "b", kind: "success" },
+ { at: 10, title: "c", kind: "error" },
+ ],
+ }),
+ ],
+ [
+ "Callout",
+ () =>
+ bind(fakeHost(), callout)({ target: [100, 100], title: "t", text: "x" }),
+ ],
+ [
+ "Spotlight",
+ () =>
+ bind(
+ fakeHost(),
+ spotlight,
+ )({
+ targets: [
+ { at: 0, target: [10, 10] },
+ { at: 20, target: "full" },
+ ],
+ shape: "ellipse",
+ }),
+ ],
+ [
+ "Confetti",
+ () =>
+ bind(
+ fakeHost(),
+ confetti,
+ )({
+ bursts: [
+ { at: 0, origin: [10, 10] },
+ { at: 5, origin: [90, 10] },
+ ],
+ }),
+ ],
+ ...(["slide", "pop", "draw", "rise"] as const).map(
+ (style) =>
+ [
+ `LogoReveal ${style}`,
+ () =>
+ bind(
+ fakeHost(),
+ logoReveal,
+ )({
+ mark: { d: "M0 0L1 1Z", viewBox: [1, 1] },
+ name: "ab",
+ tagline: "t",
+ style,
+ }),
+ ] as [string, () => unknown],
+ ),
+ ...(["mesh", "grid", "dots", "solid"] as const).map(
+ (kind) =>
+ [`Backdrop ${kind}`, () => bind(fakeHost(), backdrop)({ kind })] as [
+ string,
+ () => unknown,
+ ],
+ ),
+ ...(["bars", "mirror", "dots", "radial"] as const).map(
+ (kind) =>
+ [
+ `Waveform ${kind}`,
+ () =>
+ bind(
+ fakeHost(),
+ waveform,
+ )({
+ audio: {
+ fps: 30,
+ frames: 2,
+ bands: [
+ [0, 1],
+ [1, 0],
+ ],
+ level: [0, 1],
+ beats: [],
+ },
+ kind,
+ bars: 4,
+ }),
+ ] as [string, () => unknown],
+ ),
+ ...(["roll", "fade", "slide", "type"] as const).map(
+ (transition) =>
+ [
+ `WordCycle ${transition}`,
+ () =>
+ bind(
+ fakeHost(),
+ wordCycle,
+ )({
+ text: "a {} b",
+ words: ["x", "yy", "zzz"],
+ transition,
+ slot: "pill",
+ }),
+ ] as [string, () => unknown],
+ ),
+ ...(["phone", "tablet", "laptop"] as const).map(
+ (device) =>
+ [
+ `DeviceFrame ${device}`,
+ () =>
+ bind(fakeHost(), deviceFrame)({ device, content: "a.mp4", tilt: {} }),
+ ] as [string, () => unknown],
+ ),
+ [
+ "TouchPoint",
+ () =>
+ bind(
+ fakeHost(),
+ touchPoint,
+ )({
+ touches: [
+ { to: [10, 10], tap: 2 },
+ { to: [20, 20], press: 20 },
+ { to: [30, 30], swipe: [30, 300] },
+ ],
+ }),
+ ],
+ [
+ "BeforeAfter",
+ () => bind(fakeHost(), beforeAfter)({ before: "a.mp4", after: "b.mp4" }),
+ ],
+ [
+ "Selection text",
+ () =>
+ bind(
+ fakeHost(),
+ selection,
+ )({ target: { text }, drag: { frame: 0, end: 10 } }),
+ ],
+ [
+ "Selection marquee",
+ () =>
+ bind(
+ fakeHost(),
+ selection,
+ )({
+ kind: "marquee",
+ drag: { frame: 0, end: 10 },
+ items: [[5, 5], { x: 0, y: 0, width: 9, height: 9 }],
+ }),
+ ],
+ ...(["cycle", "deal"] as const).map(
+ (mode) =>
+ [
+ `CardStack ${mode}`,
+ () =>
+ bind(
+ fakeHost(),
+ cardStack,
+ )({
+ cards: [
+ { title: "a", body: "b", image: "i.png" },
+ { title: "c" },
+ { title: "d" },
+ ],
+ mode,
+ }),
+ ] as [string, () => unknown],
+ ),
+];
diff --git a/packages/components/src/text-reveal/index.ts b/packages/components/src/text-reveal/index.ts
index 2c616fc8..855bb5c9 100644
--- a/packages/components/src/text-reveal/index.ts
+++ b/packages/components/src/text-reveal/index.ts
@@ -27,6 +27,7 @@ import {
type UnitSchedule,
} from "../core/glyphs.js";
import type { Animatable } from "../core/host.js";
+import { round as roundTo } from "../core/keys.js";
import {
findRange,
lineShift,
@@ -805,7 +806,7 @@ export const textReveal = /* @__PURE__ */ defineComponent({
// ── Helpers ──────────────────────────────────────────────────────────
-const round = (v: number) => Math.round(v * 10000) / 10000;
+const round = (v: number) => roundTo(v, 4);
const list = (values: readonly number[]) => `[${values.map(round).join(",")}]`;
/** 1 for characters inside an emphasis match, else 0 (null when nothing matches). */
diff --git a/packages/components/src/text-reveal/meta.ts b/packages/components/src/text-reveal/meta.ts
index 865ed446..a1cbdbd5 100644
--- a/packages/components/src/text-reveal/meta.ts
+++ b/packages/components/src/text-reveal/meta.ts
@@ -5,7 +5,7 @@ export default defineMeta({
summary:
"Headlines and body copy that animate in and out by character, word or line: rise, blur, track, mask, slam, scatter, scramble, type, stream, wipe and flip, each ending on exactly the static text.",
tags: ["text", "typography", "kinetic type", "title", "reveal", "typewriter"],
- parts: ["text", "shake", "caret", "matte", "reels", "line-<n>"],
+ parts: ["text", "shake", "caret", "matte", "reels", "units", "line-<n>"],
cues: ["units", "revealed", "exitStart", "keystrokes"],
example: `TextReveal({ text: "Ship it faster", style: "rise", emphasis: ["faster"] })`,
since: "M2",
diff --git a/packages/components/src/title-card/index.ts b/packages/components/src/title-card/index.ts
index c4f2d387..a8f3cd76 100644
--- a/packages/components/src/title-card/index.ts
+++ b/packages/components/src/title-card/index.ts
@@ -89,7 +89,7 @@ export const titleCard = /* @__PURE__ */ defineComponent({
? host.measure(kickerText, {
fontFamily,
fontSize: kickerSize,
- fontWeight: 600,
+ fontWeight: theme.weight.semibold,
letterSpacing: kickerSize * 0.16,
})
: null;
@@ -164,7 +164,7 @@ export const titleCard = /* @__PURE__ */ defineComponent({
align,
fontFamily,
fontSize: size,
- fontWeight: 700,
+ fontWeight: theme.weight.bold,
emphasis: props.emphasis,
theme,
seed: ctx.seed,
@@ -183,7 +183,7 @@ export const titleCard = /* @__PURE__ */ defineComponent({
...place.kicker,
fontFamily,
fontSize: kickerSize,
- fontWeight: 600,
+ fontWeight: theme.weight.semibold,
letterSpacing: kickerSize * 0.16,
fill: theme.color.accent,
theme,
@@ -291,7 +291,7 @@ export const titleCard = /* @__PURE__ */ defineComponent({
align,
fontFamily,
fontSize: size,
- fontWeight: 700,
+ fontWeight: theme.weight.bold,
emphasis: props.emphasis,
theme,
seed: ctx.seed,
diff --git a/packages/components/src/toasts/index.test.ts b/packages/components/src/toasts/index.test.ts
index 3dfa84c6..b6d6cdcb 100644
--- a/packages/components/src/toasts/index.test.ts
+++ b/packages/components/src/toasts/index.test.ts
@@ -1,7 +1,8 @@
import { describe, expect, it } from "vitest";
+import { springTrack } from "../core/bake.js";
import { bind } from "../core/contract.js";
import { fakeHost } from "../test/fake-host.js";
-import { springTrack, toasts } from "./index.js";
+import { toasts } from "./index.js";
describe("springTrack", () => {
it("springs to each target and lands on it", () => {
diff --git a/packages/components/src/toasts/index.ts b/packages/components/src/toasts/index.ts
index a6a3760c..903aa2c4 100644
--- a/packages/components/src/toasts/index.ts
+++ b/packages/components/src/toasts/index.ts
@@ -5,17 +5,18 @@
* The stack is solved offline and every move is a baked spring.
*
* Coordinates are the frame's: the root covers the video (default
- * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.
+ * the composition `canvas`, or the given width / height) from 0, 0.
*/
import {
LayerAnimation,
type LayoutNode,
} from "@framefields/compositions/program";
import { z } from "zod";
-import { bakeSamples, springAt } from "../core/bake.js";
+import { bakeSamples, springTrack } from "../core/bake.js";
import { defineComponent } from "../core/contract.js";
import type { Animatable } from "../core/host.js";
import { toPathData, type Vec2 } from "../core/path.js";
+import { elevate, surfaceFill } from "../core/surface.js";
import type { Theme } from "../core/theme.js";
export const TOAST_CORNERS = [
@@ -36,38 +37,6 @@ export interface ToastsCues {
dismissals: ReadonlyArray<{ frame: number; index: number }>;
}
-const SPRING = { stiffness: 230, damping: 24 };
-
-/** Per-frame values that spring to each new target from wherever they are. */
-export function springTrack(
- changes: ReadonlyArray<readonly [frame: number, target: number]>,
- initial: number,
- length: number,
- fps: number,
- options = SPRING,
-): number[] {
- const sorted = [...changes].sort((a, b) => a[0] - b[0]);
- const out = new Array<number>(length + 1);
- let from = initial;
- let to = initial;
- let since = 0;
- let k = 0;
- for (let f = 0; f <= length; f++) {
- while (
- k < sorted.length &&
- (sorted[k] as readonly [number, number])[0] <= f
- ) {
- // Restart from the current value toward the new target.
- from = from + (to - from) * springAt((f - since) / fps, options);
- to = (sorted[k] as readonly [number, number])[1];
- since = (sorted[k] as readonly [number, number])[0];
- k++;
- }
- out[f] = from + (to - from) * springAt((f - since) / fps, options);
- }
- return out;
-}
-
/** A small icon per kind: a coloured disc with a drawn mark. */
function icon(
kind: ToastKind,
@@ -150,8 +119,8 @@ export const toasts = /* @__PURE__ */ defineComponent({
build(ctx, props) {
const { host, theme, fps } = ctx;
const s = theme.scale;
- const W = ctx.requested.width ?? 1920 * s;
- const H = ctx.requested.height ?? 1080 * s;
+ const W = ctx.requested.width ?? ctx.canvas.width;
+ const H = ctx.requested.height ?? ctx.canvas.height;
const tw = props.toastWidth ?? 440 * s;
const margin = props.margin ?? 36 * s;
const fontFamily = props.fontFamily ?? theme.font.body;
@@ -176,7 +145,7 @@ export const toasts = /* @__PURE__ */ defineComponent({
const titleM = host.measure(item.title, {
fontFamily,
fontSize: titleFs,
- fontWeight: 600,
+ fontWeight: theme.weight.semibold,
width: textW,
});
const bodyM = item.body
@@ -239,12 +208,14 @@ export const toasts = /* @__PURE__ */ defineComponent({
for (const t of items) {
const ys = yChanges.get(t.index) ?? [[t.at, margin]];
const firstY = ys[0]?.[1] ?? margin;
- const yTrack = springTrack(ys, firstY, length, fps);
+ const settle = theme.motion.spring.settle;
+ const yTrack = springTrack(ys, firstY, length, fps, settle);
const scaleTrack = springTrack(
scaleChanges.get(t.index) ?? [],
1,
length,
fps,
+ settle,
);
const fade = fadeChanges.get(t.index) ?? [];
// Slide in from the edge; slide back out when dismissed.
@@ -302,7 +273,7 @@ export const toasts = /* @__PURE__ */ defineComponent({
width: textW,
fontFamily,
fontSize: titleFs,
- fontWeight: 600,
+ fontWeight: theme.weight.semibold,
fill: theme.color.ink,
}),
];
@@ -326,23 +297,16 @@ export const toasts = /* @__PURE__ */ defineComponent({
y: firstY,
width: tw,
height: t.height,
- background: theme.color.raised,
+ background: surfaceFill(theme.color.raised, theme),
borderRadius: theme.radius.md,
borderColor: theme.color.line,
borderWidth: Math.max(1, s),
anchorX: 0.5,
anchorY: top ? 0 : 1,
+ motionBlurShutter: 60,
children: kids,
});
- host.style(card, {
- dropShadow: {
- color: "#000000",
- opacity: 0.35,
- angle: 90,
- distance: 10 * s,
- size: 30 * s,
- },
- });
+ elevate(host, card, theme, "mid");
const from = Math.max(0, t.at - 1);
const slice = (v: number[]) => v.slice(from);
card.animate(
diff --git a/packages/components/src/toolkit.ts b/packages/components/src/toolkit.ts
index a4d1104b..e8fc8624 100644
--- a/packages/components/src/toolkit.ts
+++ b/packages/components/src/toolkit.ts
@@ -8,16 +8,20 @@
export * from "./core/audio.js";
export * from "./core/bake.js";
+export * from "./core/color.js";
export * from "./core/contract.js";
export * from "./core/draw.js";
export * from "./core/ease.js";
export * from "./core/glyphs.js";
export * from "./core/host.js";
+export * from "./core/keys.js";
+export * from "./core/layout.js";
export * from "./core/meta.js";
export * from "./core/motion.js";
export * from "./core/path.js";
export * from "./core/rng.js";
export * from "./core/schemas.js";
+export * from "./core/surface.js";
export * from "./core/targets.js";
export * from "./core/text.js";
export * from "./core/theme.js";
diff --git a/packages/components/src/touch-point/index.ts b/packages/components/src/touch-point/index.ts
index f5cd3217..86cb961f 100644
--- a/packages/components/src/touch-point/index.ts
+++ b/packages/components/src/touch-point/index.ts
@@ -5,7 +5,7 @@
* lifted, so nothing travels: each touch is its own disc.
*
* Coordinates are the frame's: the root covers the video (default
- * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.
+ * the composition `canvas`, or the given width / height) from 0, 0.
*/
import {
type KeyframeTuple,
@@ -15,6 +15,7 @@ import {
import { z } from "zod";
import { defineComponent } from "../core/contract.js";
import type { Animatable } from "../core/host.js";
+import { ascending } from "../core/keys.js";
import { dist, type Vec2 } from "../core/path.js";
import { targetSchema } from "../core/schemas.js";
import { resolveTarget, type Target, targetPoint } from "../core/targets.js";
@@ -79,8 +80,8 @@ export const touchPoint = /* @__PURE__ */ defineComponent({
build(ctx, props) {
const { host, theme, fps } = ctx;
const s = theme.scale;
- const W = ctx.requested.width ?? 1920 * s;
- const H = ctx.requested.height ?? 1080 * s;
+ const W = ctx.requested.width ?? ctx.canvas.width;
+ const H = ctx.requested.height ?? ctx.canvas.height;
const size = props.size ?? 64 * s;
const f = (n: number) => scaleFrames(n, fps);
const pointOf = (t: Target, at: number) =>
@@ -345,12 +346,3 @@ export function planTouches(
return out;
});
}
-
-/** Later keys on a shared frame win; frames ascend. */
-function ascending(keys: KeyframeTuple[]): KeyframeTuple[] {
- const byFrame = new Map<number, KeyframeTuple>();
- for (const k of keys) byFrame.set(k[0] as number, k);
- return [...byFrame.values()].sort(
- (a, b) => (a[0] as number) - (b[0] as number),
- );
-}
diff --git a/packages/components/src/touch-point/meta.ts b/packages/components/src/touch-point/meta.ts
index bd128c17..9f75b00c 100644
--- a/packages/components/src/touch-point/meta.ts
+++ b/packages/components/src/touch-point/meta.ts
@@ -5,7 +5,7 @@ export default defineMeta({
summary:
"Fingers on glass: taps, double taps, long presses and swipes as soft discs with ripples, for mobile demos in a DeviceFrame.",
tags: ["touch", "tap", "swipe", "mobile", "gesture", "demo", "phone"],
- parts: ["touch-0", "touch-0-ripple-0", "touch-0-trail-0"],
+ parts: ["touch-<n>", "touch-<n>-ripple-<k>", "touch-<n>-trail-<k>"],
cues: ["taps", "presses", "swipes", "touches"],
example: `TouchPoint({ touches: [{ to: phone.at(196, 700) }, { to: phone.at(196, 600), swipe: phone.at(196, 200) }] })`,
since: "M8",
diff --git a/packages/components/src/waveform/index.ts b/packages/components/src/waveform/index.ts
index 7abfcc31..e217e24d 100644
--- a/packages/components/src/waveform/index.ts
+++ b/packages/components/src/waveform/index.ts
@@ -14,6 +14,7 @@ import {
resampleBands,
smoothRelease,
} from "../core/audio.js";
+import { mix } from "../core/color.js";
import { defineComponent } from "../core/contract.js";
import type { Animatable } from "../core/host.js";
@@ -222,24 +223,3 @@ export const waveform = /* @__PURE__ */ defineComponent({
};
},
});
-
-/** Mix two `#rrggbb` colours (`t` 0 → a, 1 → b); other formats: `a`. */
-function mix(a: string, b: string, t: number): string {
- const rgb = (c: string) => {
- const h = c.replace(/^#/, "");
- const full = h.length === 3 ? h.replace(/./g, (x) => x + x) : h.slice(0, 6);
- return /^[0-9a-f]{6}$/i.test(full)
- ? [0, 2, 4].map((k) => Number.parseInt(full.slice(k, k + 2), 16))
- : null;
- };
- const x = rgb(a);
- const y = rgb(b);
- if (!x || !y) return a;
- return `#${x
- .map((v, k) =>
- Math.round(v + ((y[k] as number) - v) * t)
- .toString(16)
- .padStart(2, "0"),
- )
- .join("")}`;
-}
diff --git a/packages/components/src/waveform/meta.ts b/packages/components/src/waveform/meta.ts
index 6ee75158..532274de 100644
--- a/packages/components/src/waveform/meta.ts
+++ b/packages/components/src/waveform/meta.ts
@@ -13,7 +13,7 @@ export default defineMeta({
"music",
"visualizer",
],
- parts: ["bar-0", "spoke-0"],
+ parts: ["bar-<n>", "spoke-<n>"],
cues: ["beats"],
example: `Waveform({ audio: await analyzeAudio("voice.wav", { fps: 30 }), kind: "mirror" })`,
since: "M7",
diff --git a/packages/components/src/word-cycle/index.ts b/packages/components/src/word-cycle/index.ts
index 07d739c2..b6c87feb 100644
--- a/packages/components/src/word-cycle/index.ts
+++ b/packages/components/src/word-cycle/index.ts
@@ -11,6 +11,7 @@ import {
import { z } from "zod";
import { defineComponent } from "../core/contract.js";
import type { Animatable } from "../core/host.js";
+import { ascending, round, valueAt } from "../core/keys.js";
import { themeFrames } from "../core/theme.js";
export const WORD_TRANSITIONS = ["roll", "fade", "slide", "type"] as const;
@@ -338,30 +339,3 @@ export const wordCycle = /* @__PURE__ */ defineComponent({
};
},
});
-
-const round = (v: number) => Math.round(v * 1000) / 1000;
-
-/** Later keys on a shared frame win; frames ascend. */
-function ascending(keys: KeyframeTuple[]): KeyframeTuple[] {
- const byFrame = new Map<number, KeyframeTuple>();
- for (const k of keys) byFrame.set(k[0] as number, k);
- return [...byFrame.values()].sort(
- (a, b) => (a[0] as number) - (b[0] as number),
- );
-}
-
-/** A keyed track's value at `f` (linear between keys, `hold` steps). */
-function valueAt(keys: readonly KeyframeTuple[], f: number): number {
- const first = keys[0] as KeyframeTuple;
- if (f <= (first[0] as number)) return first[1] as number;
- for (let i = 0; i < keys.length - 1; i++) {
- const [f0, v0] = keys[i] as KeyframeTuple;
- const [f1, v1, e] = keys[i + 1] as KeyframeTuple;
- if (f >= (f0 as number) && f <= (f1 as number)) {
- if (e === "hold") return f === f1 ? (v1 as number) : (v0 as number);
- const t = (f - (f0 as number)) / ((f1 as number) - (f0 as number));
- return (v0 as number) + ((v1 as number) - (v0 as number)) * t;
- }
- }
- return keys[keys.length - 1]?.[1] as number;
-}
diff --git a/packages/components/src/word-cycle/meta.ts b/packages/components/src/word-cycle/meta.ts
index 99755b2f..efcd864c 100644
--- a/packages/components/src/word-cycle/meta.ts
+++ b/packages/components/src/word-cycle/meta.ts
@@ -12,7 +12,7 @@ export default defineMeta({
"launch",
"typography",
],
- parts: ["before", "slot", "word-0", "after", "pill", "underline"],
+ parts: ["before", "slot", "word-<n>", "after", "pill", "underline"],
cues: ["changes"],
example: `WordCycle({ text: "Make videos {}", words: ["faster", "together", "in code"] })`,
since: "M7",
diff --git a/packages/compositions/src/program/lint.test.ts b/packages/compositions/src/program/lint.test.ts
index 1730678a..a4e90e6d 100644
--- a/packages/compositions/src/program/lint.test.ts
+++ b/packages/compositions/src/program/lint.test.ts
@@ -196,4 +196,38 @@ describe("lintComposition", () => {
]),
).toEqual([]);
});
+
+ it("flags emoji in text only when no emoji font is registered", () => {
+ const text = (id: string, t: string, spans?: unknown[]) => ({
+ id,
+ kind: "text",
+ text: t,
+ fill: "#ffffff",
+ ...(spans && { spans }),
+ });
+ const layout = [
+ {
+ id: "box",
+ kind: "box",
+ children: [
+ text("plain", "Ship it"),
+ text("rocket", "Ship it 🚀"),
+ text("span", "x", [{ text: "❤️" }]),
+ ],
+ },
+ ];
+ const lint = (emojiFont?: boolean) =>
+ lintComposition({ ...base, layout: layout as never }, { emojiFont });
+ const missing = lint(false).filter((d) => d.code === "missing_emoji_font");
+ expect(missing).toHaveLength(1);
+ expect(missing[0]).toMatchObject({
+ severity: "warning",
+ layerId: "rocket",
+ });
+ expect(missing[0]?.message).toMatch(/2 text layers 'rocket', 'span'/);
+ expect(missing[0]?.message).toMatch(/framefields fonts add emoji/);
+ expect(lint(true).map((d) => d.code)).not.toContain("missing_emoji_font");
+ // Callers that don't know about fonts aren't told.
+ expect(lint().map((d) => d.code)).not.toContain("missing_emoji_font");
+ });
});
diff --git a/packages/compositions/src/program/lint.ts b/packages/compositions/src/program/lint.ts
index f091d5e0..4cfae954 100644
--- a/packages/compositions/src/program/lint.ts
+++ b/packages/compositions/src/program/lint.ts
@@ -32,6 +32,30 @@ const COLOR_PROPS = [
*/
export const LARGE_ANIMATION_KEYFRAMES = 2000;
+/**
+ * Characters layout draws from the color emoji font (the renderer's own
+ * test, `emojiGraphemes` in webgpu-renderers).
+ */
+const EMOJI =
+ /(\p{Extended_Pictographic}|\p{Emoji_Presentation}|[\u2600-\u27BF])/u;
+
+/** The text a text node draws: its string and its spans'. */
+function textOf(node: AnyNode): string {
+ const spans = (node.spans as Array<{ text?: unknown }> | undefined) ?? [];
+ return [node.text, ...spans.map((s) => s.text)]
+ .filter((t): t is string => typeof t === "string")
+ .join("");
+}
+
+export interface LintOptions {
+ /**
+ * Whether a color emoji font is registered (framefields'
+ * `FontManager.hasEmojiFont()`). When false, text with emoji is flagged:
+ * the emoji would draw nothing. Unknown (omitted): not checked.
+ */
+ emojiFont?: boolean;
+}
+
/** Contrast below this makes text hard to read (WCAG large-text minimum). */
const MIN_TEXT_CONTRAST = 3;
@@ -72,6 +96,7 @@ export function lintComposition(
config: Pick<CompositorProgramConfig, "width" | "height" | "layout"> & {
backgroundColor?: string;
},
+ options: LintOptions = {},
): RenderDiagnostic[] {
const out: RenderDiagnostic[] = [];
const push = (
@@ -88,9 +113,16 @@ export function lintComposition(
let has3D = false;
const pbrNodes: string[] = [];
const shadowLights: string[] = [];
+ const emojiText: string[] = [];
const visit = (node: AnyNode, backdrop: string | null, atRoot: boolean) => {
const id = String(node.id ?? "?");
+ if (
+ options.emojiFont === false &&
+ node.kind === "text" &&
+ EMOJI.test(textOf(node))
+ )
+ emojiText.push(id);
for (const prop of COLOR_PROPS) {
const v = node[prop];
@@ -277,6 +309,18 @@ export function lintComposition(
const rootBackdrop = solidColor(config.backgroundColor) ?? null;
visitLevel(config.layout as AnyNode[], rootBackdrop, true);
+ if (emojiText.length > 0) {
+ const shown = emojiText
+ .slice(0, 3)
+ .map((id) => `'${id}'`)
+ .join(", ");
+ push(
+ "warning",
+ "missing_emoji_font",
+ `${emojiText.length === 1 ? "Text" : `${emojiText.length} text layers`} ${shown}${emojiText.length > 3 ? ", …" : ""} ${emojiText.length === 1 ? "has" : "have"} emoji, but no emoji font is registered, so the emoji draw nothing. Run \`npx framefields fonts add emoji\` and call the generated \`registerFonts()\`, or \`FontManager.registerEmojiFont(path)\` with a color emoji font.`,
+ emojiText[0],
+ );
+ }
if (hasEnvironment && ambientLights.length > 0) {
push(
"info",
diff --git a/packages/framefields/package.json b/packages/framefields/package.json
index d89ec6db..15dbf022 100644
--- a/packages/framefields/package.json
+++ b/packages/framefields/package.json
@@ -88,6 +88,7 @@
"scripts": {
"build": "tsdown && node ../../scripts/sync-readme.mjs && node scripts/check-dts-bundle.mjs && node scripts/check-components-treeshake.mjs && node scripts/check-registry-types.mjs",
"dev": "tsdown --watch",
+ "gallery": "tsx --conditions=development scripts/components-gallery.ts",
"clean": "rm -rf dist .turbo",
"prepack": "node ../../scripts/sync-readme.mjs",
"test": "vitest run --passWithNoTests"
diff --git a/packages/framefields/scripts/check-components-treeshake.mjs b/packages/framefields/scripts/check-components-treeshake.mjs
index 742ea7b4..cfebc782 100644
--- a/packages/framefields/scripts/check-components-treeshake.mjs
+++ b/packages/framefields/scripts/check-components-treeshake.mjs
@@ -60,10 +60,10 @@ const CARDS = "Expected a layer or { title";
/** Each component (by factory): a string only its module has, and what it may compose. */
const COMPONENTS = {
- MousePointer: { own: POINTER, uses: [], budget: 66_000 },
+ MousePointer: { own: POINTER, uses: [], budget: 68_000 },
AppFrame: { own: FRAME, uses: [], budget: 45_000 },
- FocusZoom: { own: CAMERA, uses: [], budget: 40_000 },
- TextReveal: { own: REVEAL, uses: [GLYPHS], budget: 58_000 },
+ FocusZoom: { own: CAMERA, uses: [], budget: 42_000 },
+ TextReveal: { own: REVEAL, uses: [GLYPHS], budget: 60_000 },
Counter: { own: COUNTER, uses: [], budget: 45_000 },
Annotate: { own: ANNOTATE, uses: [], budget: 50_000 },
Captions: { own: CAPTIONS, uses: [GLYPHS], budget: 55_000 },
diff --git a/packages/framefields/scripts/components-gallery.ts b/packages/framefields/scripts/components-gallery.ts
new file mode 100644
index 00000000..0b94cddc
--- /dev/null
+++ b/packages/framefields/scripts/components-gallery.ts
@@ -0,0 +1,219 @@
+/**
+ * Component gallery: renders each component's settled frame under every
+ * built-in theme into `renders/gallery/<theme>/<name>.png`, plus an
+ * `index.html` contact sheet that lays them side by side. Use it to review
+ * how components look together, and how a change looks across themes.
+ *
+ * pnpm --filter framefields gallery [Name …] (e.g. `gallery ChatThread`)
+ */
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { themes } from "../src/components/index.js";
+import * as C from "../src/components/testing.js";
+import { FontManager } from "../src/fonts/index.js";
+import { Composition } from "../src/index.js";
+
+type ThemeName = keyof typeof themes;
+
+interface Shot {
+ name: string;
+ /** Frame to render: something settled, mid-story. */
+ frame: number;
+ build(theme: (typeof themes)[ThemeName]): Parameters<Composition["add"]>[0];
+}
+
+const W = 1280;
+const H = 720;
+const canvas = { width: W, height: H };
+const code = `import { Composition } from "framefields";
+
+export function intro(fps = 30) {
+ const comp = new Composition({ fps });
+ return comp.add(title("Ship it faster"));
+}`;
+
+const SHOTS: Shot[] = [
+ {
+ name: "LowerThird",
+ frame: 40,
+ build: (theme) =>
+ ["bar", "stacked", "tag", "line"].map((layout, i) =>
+ C.LowerThird({
+ theme,
+ canvas: { width: W / 2, height: H / 2 },
+ x: (i % 2) * (W / 2),
+ y: Math.floor(i / 2) * (H / 2),
+ name: "Ada Lovelace",
+ role: "Engineer, Analytical Engine",
+ layout: layout as "bar",
+ stay: true,
+ }),
+ ),
+ },
+ {
+ name: "Toasts",
+ frame: 90,
+ build: (theme) =>
+ C.Toasts({
+ theme,
+ canvas,
+ items: [
+ {
+ at: 0,
+ title: "Deployed to production",
+ body: "v2.6.0 is live",
+ kind: "success",
+ },
+ { at: 20, title: "3 new comments", body: "On “Launch film”" },
+ { at: 40, title: "Render queue is busy", kind: "warning" },
+ ],
+ }),
+ },
+ {
+ name: "CardStack",
+ frame: 20,
+ build: (theme) =>
+ C.CardStack({
+ theme,
+ x: (W - 960) / 2,
+ y: 40,
+ cards: [
+ { title: "Fast", body: "Renders on the GPU, frame-exact." },
+ { title: "Typed", body: "Props checked as you write them." },
+ { title: "Yours", body: "Components install as source." },
+ ],
+ }),
+ },
+ {
+ name: "Callout",
+ frame: 60,
+ build: (theme) => [
+ C.Callout({
+ theme,
+ canvas,
+ target: [520, 420],
+ title: "New",
+ text: "Faster renderer",
+ }),
+ C.Callout({
+ theme,
+ canvas,
+ target: [900, 220],
+ text: "Typed props",
+ side: "left",
+ }),
+ ],
+ },
+ {
+ name: "ChatThread",
+ frame: 220,
+ build: (theme) =>
+ C.ChatThread({
+ theme,
+ x: (W - 640) / 2,
+ y: 20,
+ width: 640,
+ height: 680,
+ me: "me",
+ participants: { me: { name: "Me" }, sam: { name: "Sam" } },
+ messages: [
+ { from: "me", text: "Is the launch film rendered?" },
+ {
+ from: "sam",
+ text: "Rendering now, the new cards look great",
+ reaction: "❤️",
+ },
+ { from: "me", text: "Ship it 🚀" },
+ ],
+ }),
+ },
+ {
+ name: "CodeBlock",
+ frame: 10,
+ build: (theme) =>
+ C.CodeBlock({ theme, x: 120, y: 120, code, lang: "ts", frame: true }),
+ },
+ {
+ name: "TitleCard",
+ frame: 60,
+ build: (theme) =>
+ C.TitleCard({
+ theme,
+ canvas,
+ kicker: "Chapter one",
+ title: "Ship it faster",
+ subtitle: "What changed in 2.6",
+ }),
+ },
+ {
+ name: "Meter",
+ frame: 60,
+ build: (theme) => [
+ C.Meter({
+ theme,
+ value: 72,
+ kind: "ring",
+ label: "Coverage",
+ x: 200,
+ y: 160,
+ size: 320,
+ }),
+ C.Meter({ theme, value: 3.5, kind: "stars", x: 640, y: 300, size: 440 }),
+ ],
+ },
+];
+
+async function main() {
+ const only = new Set(process.argv.slice(2));
+ await FontManager.register("assets/fonts/Inter.ttf");
+ await FontManager.register("assets/fonts/JetBrainsMono.ttf");
+ // Emoji (chat reactions, captions) draw from a color emoji font.
+ await FontManager.registerEmojiFont(
+ "../renderer/src/assets/NotoColorEmoji.ttf",
+ );
+ const out = resolve("../../renders/gallery");
+ const names = Object.keys(themes) as ThemeName[];
+ const shots = SHOTS.filter((s) => only.size === 0 || only.has(s.name));
+ for (const themeName of names) {
+ const theme = themes[themeName];
+ mkdirSync(join(out, themeName), { recursive: true });
+ for (const shot of shots) {
+ const comp = new Composition({
+ width: W,
+ height: H,
+ fps: 30,
+ durationMs: 12_000,
+ backgroundColor: theme.color.bg,
+ });
+ comp.add(shot.build(theme));
+ const png = await comp.renderFrame({ frame: shot.frame });
+ writeFileSync(join(out, themeName, `${shot.name}.png`), png);
+ console.log(`${themeName}/${shot.name}.png`);
+ }
+ }
+ writeFileSync(join(out, "index.html"), sheet(names, shots));
+ console.log(`gallery: ${join(out, "index.html")}`);
+}
+
+function sheet(names: ThemeName[], shots: Shot[]): string {
+ const rows = shots
+ .map(
+ (s) =>
+ `<h2>${s.name}</h2><div class="row">${names
+ .map(
+ (t) =>
+ `<figure><img src="${t}/${s.name}.png"><figcaption>${t}</figcaption></figure>`,
+ )
+ .join("")}</div>`,
+ )
+ .join("\n");
+ return `<!doctype html><meta charset="utf-8"><title>Component gallery</title>
+<style>body{font:14px system-ui;margin:24px;background:#888}h2{margin:24px 0 8px}
+.row{display:grid;grid-template-columns:repeat(${names.length},1fr);gap:12px}
+img{width:100%;display:block;border-radius:6px}figure{margin:0}figcaption{opacity:.7;margin-top:4px}</style>
+${rows}`;
+}
+
+await main();
+// The GPU device keeps the event loop alive once rendering is done.
+process.exit(0);
diff --git a/packages/framefields/src/cli.ts b/packages/framefields/src/cli.ts
index 67868846..729533ad 100644
--- a/packages/framefields/src/cli.ts
+++ b/packages/framefields/src/cli.ts
@@ -2,35 +2,76 @@
/**
* The `framefields` command.
*
- * npx framefields add <name...> copy components into this project
- * npx framefields list the components you can add
+ * npx framefields init [dir] start a project (or add framefields to one)
+ * npx framefields add <name...> copy components into this project
+ * npx framefields list the components you can add
+ * npx framefields fonts add <role...> install fonts (emoji)
+ * npx framefields fonts list the fonts you can install
*/
import { readFileSync } from "node:fs";
-import { relative } from "node:path";
+import { relative, resolve } from "node:path";
import { parseArgs } from "node:util";
-import { add } from "./cli/add.js";
+import { type AddReport, add } from "./cli/add.js";
+import { readConfig } from "./cli/config.js";
+import {
+ FONTS,
+ type FontSpec,
+ installFont,
+ lfsHint,
+ writeFontsModule,
+} from "./cli/fonts.js";
+import {
+ type InitReport,
+ init,
+ PACKAGE_MANAGERS,
+ type PackageManager,
+ shownPath,
+} from "./cli/init.js";
import { openRegistry } from "./cli/registry.js";
const HELP = `Usage: framefields <command> [options]
Commands:
+ init [dir] Start a framefields project in dir (default: here), or add
+ framefields to the project there: package.json, tsconfig,
+ src/theme.ts, film.ts, render.ts, assets/, .gitignore,
+ LFS .gitattributes, and the themes' fonts. Never
+ overwrites; existing files only gain what they lack.
add <name...> Copy components' source into this project (and the
components they build on). The code is yours to edit.
list List the components you can add.
+ fonts add <role...>
+ Install fonts (pinned, hash-checked, with their license)
+ and register them in the generated <components>/fonts.ts.
+ fonts list List the fonts you can install.
+
+Options for init:
+ --name <name> Package name (default: the folder's name).
+ --pm <manager> npm, pnpm, yarn or bun (default: the one running this).
+ --install Install dependencies afterwards.
+ --emoji Also install the color emoji font.
+ --no-fonts Skip Inter and JetBrains Mono.
+ --no-git Don't run \`git init\`.
Options for add:
--all Add every component.
--dir <path> Components directory (default: from framefields.json,
else src/components or components). Saved the first time.
--overwrite Replace files you have changed.
+ --no-fonts Don't install the fonts components ask for (emoji).
+
+Options for add and fonts add:
+ --fonts-dir <path> Where downloaded fonts go (default assets/fonts).
-Options for both:
+Options for add and list:
--registry <src> A registry folder or http(s) URL instead of the one
shipped with this version of framefields.
-h, --help Show this help.
-Example:
+Examples:
+ npx framefields init my-film --install
npx framefields add mouse-pointer focus-zoom
+ npx framefields fonts add emoji
`;
async function main(argv: string[]): Promise<number> {
@@ -41,6 +82,13 @@ async function main(argv: string[]): Promise<number> {
all: { type: "boolean" },
dir: { type: "string" },
overwrite: { type: "boolean" },
+ "no-fonts": { type: "boolean" },
+ "fonts-dir": { type: "string" },
+ name: { type: "string" },
+ pm: { type: "string" },
+ install: { type: "boolean" },
+ emoji: { type: "boolean" },
+ "no-git": { type: "boolean" },
registry: { type: "string" },
help: { type: "boolean", short: "h" },
},
@@ -51,6 +99,36 @@ async function main(argv: string[]): Promise<number> {
return command || values.help ? 0 : 1;
}
const cwd = process.cwd();
+ const log = (line: string) => process.stdout.write(`${line}\n`);
+ if (command === "fonts") return fonts(names, cwd, values, log);
+ if (command === "init") {
+ if (names.length > 1) {
+ process.stderr.write(
+ "init takes one folder: `framefields init my-film`.\n",
+ );
+ return 1;
+ }
+ if (values.pm && !PACKAGE_MANAGERS.includes(values.pm as PackageManager)) {
+ process.stderr.write(
+ `--pm must be one of ${PACKAGE_MANAGERS.join(", ")}.\n`,
+ );
+ return 1;
+ }
+ const report = await init({
+ cwd,
+ dir: names[0],
+ name: values.name,
+ packageManager: values.pm as PackageManager | undefined,
+ userAgent: process.env.npm_config_user_agent,
+ fonts: !values["no-fonts"],
+ emoji: values.emoji,
+ git: !values["no-git"],
+ install: values.install,
+ onDownload,
+ });
+ logInit(report, cwd, log);
+ return 0;
+ }
const registry = openRegistry(values.registry, cwd);
if (command === "list") {
@@ -79,13 +157,16 @@ async function main(argv: string[]): Promise<number> {
registry,
dir: values.dir,
overwrite: values.overwrite,
+ fonts: !values["no-fonts"],
+ fontsDir: values["fonts-dir"],
+ onDownload,
});
- const log = (line: string) => process.stdout.write(`${line}\n`);
for (const f of report.written) log(` wrote ${f}`);
for (const f of report.unchanged) log(` unchanged ${f}`);
for (const f of report.skipped)
log(` skipped ${f} (yours differs; --overwrite replaces it)`);
if (report.configWritten) log(" wrote framefields.json");
+ logFonts(report, cwd, log);
const extra = report.components.filter((c) => !wanted.includes(c.name));
if (extra.length > 0)
log(`\nWith what they build on: ${extra.map((c) => c.name).join(", ")}.`);
@@ -98,6 +179,135 @@ async function main(argv: string[]): Promise<number> {
return 0;
}
+const onDownload = (spec: FontSpec) =>
+ process.stdout.write(
+ ` fetching ${spec.file} (${(spec.font.bytes / 1e6).toFixed(1)} MB, ${spec.license.id})\n`,
+ );
+
+/** What `add` did about fonts, and how to use them. */
+function logFonts(report: AddReport, cwd: string, log: (s: string) => void) {
+ for (const f of report.fonts)
+ log(
+ ` ${f.status === "installed" ? "font " : "font ok "} ${f.path} (${f.role}, for ${f.by}: ${f.why})`,
+ );
+ for (const f of report.fontsSkipped)
+ log(
+ ` no font ${f.role} for ${f.by} (--no-fonts): ${f.why} Install later with \`framefields fonts add ${f.role}\`.`,
+ );
+ if (report.fontsModule) logFontsModule(report.fontsModule, log);
+ const installed = report.fonts.find((f) => f.status === "installed");
+ const hint = installed && lfsHint(cwd, installed.path);
+ if (hint) log(`\n${hint}`);
+ if (report.fonts.some((f) => f.status !== "configured") && report.fontsModule)
+ log(
+ `\nRegister them once before rendering: \`await registerFonts()\` from ${report.fontsModule.path.replace(/\.ts$/, ".js")}.`,
+ );
+}
+
+function logFontsModule(
+ m: NonNullable<AddReport["fontsModule"]>,
+ log: (s: string) => void,
+) {
+ if (m.status === "written") log(` wrote ${m.path}`);
+ else if (m.status === "unchanged") log(` unchanged ${m.path}`);
+ else
+ log(
+ ` skipped ${m.path} (not generated by framefields). Register the fonts yourself:\n${m.calls.map((c) => ` ${c}`).join("\n")}`,
+ );
+}
+
+/** `framefields fonts add <role...>` and `framefields fonts list`. */
+async function fonts(
+ [sub, ...roles]: string[],
+ cwd: string,
+ values: { overwrite?: boolean; "fonts-dir"?: string; dir?: string },
+ log: (s: string) => void,
+): Promise<number> {
+ if (sub === "list") {
+ const { config } = readConfig(cwd);
+ for (const [role, spec] of Object.entries(FONTS))
+ log(
+ `${role.padEnd(6)} ${spec.label}${config.fonts?.[role] ? ` (installed: ${config.fonts[role]})` : ""}`,
+ );
+ return 0;
+ }
+ if (sub !== "add" || roles.length === 0) {
+ process.stderr.write(
+ `Usage: framefields fonts add <role...> (roles: ${Object.keys(FONTS).join(", ")})\n framefields fonts list\n`,
+ );
+ return 1;
+ }
+ const unknown = roles.filter((r) => !FONTS[r]);
+ if (unknown.length > 0) {
+ process.stderr.write(
+ `Unknown font ${unknown.map((r) => `"${r}"`).join(", ")}. Fonts framefields can install: ${Object.keys(FONTS).join(", ")}.\n`,
+ );
+ return 1;
+ }
+ const { config, saved } = readConfig(cwd);
+ const installs = [];
+ for (const role of roles)
+ installs.push(
+ await installFont(role, {
+ cwd,
+ dir: values["fonts-dir"],
+ overwrite: values.overwrite,
+ onDownload,
+ }),
+ );
+ for (const f of installs)
+ log(
+ ` ${f.status === "installed" ? "font " : "font ok "} ${f.path} (${f.role})`,
+ );
+ if (!saved) log(" wrote framefields.json");
+ const module = writeFontsModule(
+ cwd,
+ resolve(cwd, values.dir ?? config.components),
+ );
+ logFontsModule(module, log);
+ const installed = installs.find((f) => f.status === "installed");
+ const hint = installed && lfsHint(cwd, installed.path);
+ if (hint) log(`\n${hint}`);
+ log(
+ `\nRegister them once before rendering: \`await registerFonts()\` from ${module.path.replace(/\.ts$/, ".js")}.`,
+ );
+ return 0;
+}
+
+function logInit(report: InitReport, cwd: string, log: (s: string) => void) {
+ const at = shownPath(cwd, report.root);
+ for (const f of report.written) log(` wrote ${f}`);
+ for (const f of report.merged)
+ log(` merged ${f} (added what it lacked)`);
+ for (const f of report.unchanged) log(` unchanged ${f}`);
+ for (const f of report.fonts)
+ log(
+ ` ${f.status === "installed" ? "font " : "font ok "} ${f.path} (${f.role})`,
+ );
+ logFontsModule(report.fontsModule, log);
+ if (report.git === "initialized")
+ log(" git initialized a repository");
+ if (report.git === "unavailable")
+ log(" git not found: skipped `git init`");
+ if (report.lfs === false)
+ log(
+ "\nGit LFS isn't installed. Footage and fonts are tracked with it: install it (https://git-lfs.com), then run `git lfs install` once.",
+ );
+ else if (report.lfs)
+ log("\nRun `git lfs install` once on this machine if you haven't yet.");
+ const steps = [
+ ...(at === "." ? [] : [`cd ${/\s/.test(at) ? JSON.stringify(at) : at}`]),
+ ...(report.installed ? [] : [`${report.packageManager} install`]),
+ `${report.runScript("frames")} -- 0 30 60`,
+ ];
+ log(
+ `\n${report.name} is ready. Next:\n${steps.map((s) => ` ${s}`).join("\n")}`,
+ );
+ log(
+ "\nThen edit src/film.ts, and run `npx framefields list` for ready-made components.",
+ );
+}
+
/** Installed components import `framefields`; say so if the project lacks it. */
function warnIfMissingFramefields(cwd: string, log: (s: string) => void) {
try {
diff --git a/packages/framefields/src/cli/add.ts b/packages/framefields/src/cli/add.ts
index fe76a8cd..c9ba6645 100644
--- a/packages/framefields/src/cli/add.ts
+++ b/packages/framefields/src/cli/add.ts
@@ -5,37 +5,23 @@
* plus any component it builds on, which is installed alongside it.
*
* Where they go is remembered in `framefields.json` at the project root.
+ * Components that draw with fonts beyond the theme's (emoji) get them
+ * installed too, plus a generated `fonts.ts` that registers them.
*/
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join, relative, resolve } from "node:path";
+import { readConfig, writeConfig } from "./config.js";
+import {
+ type Fetch,
+ type FontInstall,
+ type FontSpec,
+ type FontsModule,
+ installFont,
+ writeFontsModule,
+} from "./fonts.js";
import type { Registry, RegistryItem } from "./registry.js";
-export const CONFIG_FILE = "framefields.json";
-
-export interface ProjectConfig {
- /** Components directory, relative to the project root. */
- components: string;
-}
-
-/** The project's config, or the default it would get: `src/components` when there is a `src`. */
-export function readConfig(cwd: string): {
- config: ProjectConfig;
- saved: boolean;
-} {
- const file = join(cwd, CONFIG_FILE);
- if (existsSync(file)) {
- const config = JSON.parse(
- readFileSync(file, "utf8"),
- ) as Partial<ProjectConfig>;
- if (typeof config.components !== "string")
- throw new Error(`${CONFIG_FILE}: "components" must be a directory path`);
- return { config: config as ProjectConfig, saved: true };
- }
- const components = existsSync(join(cwd, "src"))
- ? "src/components"
- : "components";
- return { config: { components }, saved: false };
-}
+export { CONFIG_FILE, type ProjectConfig, readConfig } from "./config.js";
export interface AddOptions {
cwd: string;
@@ -44,6 +30,16 @@ export interface AddOptions {
dir?: string;
/** Replace files that differ from the registry's. */
overwrite?: boolean;
+ /** Install the fonts components ask for (default true). */
+ fonts?: boolean;
+ /** Folder for downloaded fonts. Default `assets/fonts`. */
+ fontsDir?: string;
+ /** For tests; default the global `fetch`. */
+ fetch?: Fetch;
+ /** For tests; default the built-in font catalog. */
+ fontCatalog?: Record<string, FontSpec>;
+ /** Called before a font download starts. */
+ onDownload?: (spec: FontSpec) => void;
}
export interface AddReport {
@@ -55,6 +51,12 @@ export interface AddReport {
/** Files left alone because they differ and `overwrite` is off. */
skipped: string[];
configWritten: boolean;
+ /** Fonts the components asked for, and what happened to each. */
+ fonts: Array<FontInstall & { why: string; by: string }>;
+ /** Fonts asked for but not installed (`fonts: false`), with why. */
+ fontsSkipped: Array<{ role: string; why: string; by: string }>;
+ /** The generated `fonts.ts`, when any font is installed. */
+ fontsModule?: FontsModule;
}
/** Resolve `names` (and what they import) and write their files. */
@@ -93,6 +95,8 @@ export async function add(
unchanged: [],
skipped: [],
configWritten: false,
+ fonts: [],
+ fontsSkipped: [],
};
for (const item of order) {
for (const file of item.files) {
@@ -114,11 +118,31 @@ export async function add(
}
}
if (!saved) {
- writeFileSync(
- join(cwd, CONFIG_FILE),
- `${JSON.stringify({ components: relative(cwd, dir) || "." }, null, "\t")}\n`,
- );
+ writeConfig(cwd, { components: relative(cwd, dir) || "." });
report.configWritten = true;
}
+
+ // One install per font, credited to the first component that asks.
+ const needs = new Map<string, { why: string; by: string }>();
+ for (const item of order)
+ for (const f of item.fonts ?? [])
+ if (!needs.has(f.font)) needs.set(f.font, { why: f.why, by: item.name });
+ for (const [role, need] of needs) {
+ if (options.fonts === false) {
+ report.fontsSkipped.push({ role, ...need });
+ continue;
+ }
+ const done = await installFont(role, {
+ cwd,
+ dir: options.fontsDir,
+ overwrite: options.overwrite,
+ fetch: options.fetch,
+ catalog: options.fontCatalog,
+ onDownload: options.onDownload,
+ });
+ report.fonts.push({ ...done, ...need });
+ }
+ if (report.fonts.length > 0 || readConfig(cwd).config.fonts)
+ report.fontsModule = writeFontsModule(cwd, dir, options.fontCatalog);
return report;
}
diff --git a/packages/framefields/src/cli/config.ts b/packages/framefields/src/cli/config.ts
new file mode 100644
index 00000000..69a0c6e4
--- /dev/null
+++ b/packages/framefields/src/cli/config.ts
@@ -0,0 +1,53 @@
+/**
+ * `framefields.json` at the project root: where installed components live,
+ * and which fonts `framefields add` / `framefields fonts add` installed.
+ */
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+export const CONFIG_FILE = "framefields.json";
+
+export interface ProjectConfig {
+ /** Components directory, relative to the project root. */
+ components: string;
+ /**
+ * Font files by role (`emoji`), relative to the project root. A role
+ * set here counts as installed: point it at your own font to use that.
+ */
+ fonts?: Partial<Record<string, string>>;
+}
+
+/** The project's config, or the default it would get: `src/components` when there is a `src`. */
+export function readConfig(cwd: string): {
+ config: ProjectConfig;
+ saved: boolean;
+} {
+ const file = join(cwd, CONFIG_FILE);
+ if (existsSync(file)) {
+ const config = JSON.parse(
+ readFileSync(file, "utf8"),
+ ) as Partial<ProjectConfig>;
+ if (typeof config.components !== "string")
+ throw new Error(`${CONFIG_FILE}: "components" must be a directory path`);
+ if (
+ config.fonts !== undefined &&
+ (typeof config.fonts !== "object" ||
+ Object.values(config.fonts).some((v) => typeof v !== "string"))
+ )
+ throw new Error(
+ `${CONFIG_FILE}: "fonts" must map roles to font file paths, e.g. { "emoji": "assets/fonts/NotoColorEmoji.ttf" }`,
+ );
+ return { config: config as ProjectConfig, saved: true };
+ }
+ const components = existsSync(join(cwd, "src"))
+ ? "src/components"
+ : "components";
+ return { config: { components }, saved: false };
+}
+
+export function writeConfig(cwd: string, config: ProjectConfig): void {
+ writeFileSync(
+ join(cwd, CONFIG_FILE),
+ `${JSON.stringify(config, null, "\t")}\n`,
+ );
+}
diff --git a/packages/framefields/src/cli/fonts.test.ts b/packages/framefields/src/cli/fonts.test.ts
new file mode 100644
index 00000000..6cf7b50a
--- /dev/null
+++ b/packages/framefields/src/cli/fonts.test.ts
@@ -0,0 +1,324 @@
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { add } from "./add.js";
+import { CONFIG_FILE, readConfig } from "./config.js";
+import {
+ type Fetch,
+ FONTS,
+ FONTS_MODULE_MARKER,
+ type FontSpec,
+ installFont,
+ lfsHint,
+ writeFontsModule,
+} from "./fonts.js";
+import { openRegistry, type RegistryItem } from "./registry.js";
+
+const bytes = (text: string) => new TextEncoder().encode(text);
+const hash = (b: Uint8Array) => createHash("sha256").update(b).digest("hex");
+const FONT = bytes("fake emoji font");
+const LICENSE = bytes("SIL Open Font License 1.1");
+const pin = (url: string, b: Uint8Array) => ({
+ url,
+ sha256: hash(b),
+ bytes: b.length,
+});
+const CATALOG: Record<string, FontSpec> = {
+ emoji: {
+ label: "test emoji",
+ file: "Emoji.ttf",
+ font: pin("https://fonts.test/Emoji.ttf", FONT),
+ license: {
+ ...pin("https://fonts.test/LICENSE", LICENSE),
+ id: "OFL-1.1",
+ file: "Emoji-OFL.txt",
+ },
+ register: { emoji: true },
+ },
+};
+
+/** A fetch serving `files`, counting requests. */
+function server(files: Record<string, Uint8Array>) {
+ const calls: string[] = [];
+ const get: Fetch = async (url) => {
+ calls.push(url);
+ const body = files[url];
+ return {
+ ok: body !== undefined,
+ status: body ? 200 : 404,
+ statusText: body ? "OK" : "Not Found",
+ arrayBuffer: async () =>
+ (body ?? new Uint8Array()).slice().buffer as ArrayBuffer,
+ };
+ };
+ return { get, calls };
+}
+const good = () =>
+ server({
+ "https://fonts.test/Emoji.ttf": FONT,
+ "https://fonts.test/LICENSE": LICENSE,
+ });
+
+let cwd: string;
+beforeEach(() => {
+ cwd = mkdtempSync(join(tmpdir(), "framefields-fonts-test-"));
+});
+afterEach(() => rmSync(cwd, { recursive: true, force: true }));
+
+describe("installFont", () => {
+ it("downloads, verifies and records the pinned font with its license", async () => {
+ const { get } = good();
+ const done = await installFont("emoji", {
+ cwd,
+ fetch: get,
+ catalog: CATALOG,
+ });
+ expect(done).toEqual({
+ role: "emoji",
+ path: "assets/fonts/Emoji.ttf",
+ status: "installed",
+ });
+ expect(readFileSync(join(cwd, "assets/fonts/Emoji.ttf"))).toEqual(
+ Buffer.from(FONT),
+ );
+ expect(readFileSync(join(cwd, "assets/fonts/Emoji-OFL.txt"), "utf8")).toBe(
+ "SIL Open Font License 1.1",
+ );
+ expect(readConfig(cwd).config.fonts).toEqual({
+ emoji: "assets/fonts/Emoji.ttf",
+ });
+ });
+
+ it("doesn't download again when the font is there or configured", async () => {
+ const first = good();
+ await installFont("emoji", { cwd, fetch: first.get, catalog: CATALOG });
+ const again = good();
+ expect(
+ (await installFont("emoji", { cwd, fetch: again.get, catalog: CATALOG }))
+ .status,
+ ).toBe("configured");
+ expect(again.calls).toEqual([]);
+ // The pinned file without a config entry: recorded, not fetched.
+ rmSync(join(cwd, CONFIG_FILE));
+ const third = good();
+ expect(
+ (await installFont("emoji", { cwd, fetch: third.get, catalog: CATALOG }))
+ .status,
+ ).toBe("present");
+ expect(third.calls).toEqual([]);
+ });
+
+ it("keeps the user's own font named in framefields.json", async () => {
+ mkdirSync(join(cwd, "fonts"));
+ writeFileSync(join(cwd, "fonts/Mine.ttf"), "mine");
+ writeFileSync(
+ join(cwd, CONFIG_FILE),
+ JSON.stringify({
+ components: "components",
+ fonts: { emoji: "fonts/Mine.ttf" },
+ }),
+ );
+ const { get, calls } = good();
+ expect(
+ await installFont("emoji", { cwd, fetch: get, catalog: CATALOG }),
+ ).toMatchObject({ status: "configured", path: "fonts/Mine.ttf" });
+ expect(calls).toEqual([]);
+ });
+
+ it("writes nothing when a download doesn't match its pin", async () => {
+ const { get } = server({
+ "https://fonts.test/Emoji.ttf": bytes("tampered"),
+ "https://fonts.test/LICENSE": LICENSE,
+ });
+ await expect(
+ installFont("emoji", { cwd, fetch: get, catalog: CATALOG }),
+ ).rejects.toThrow(/isn't the pinned file .*Nothing was written/);
+ expect(existsSync(join(cwd, "assets"))).toBe(false);
+ expect(existsSync(join(cwd, CONFIG_FILE))).toBe(false);
+ });
+
+ it("won't replace a different file at the target without overwrite", async () => {
+ mkdirSync(join(cwd, "assets/fonts"), { recursive: true });
+ writeFileSync(join(cwd, "assets/fonts/Emoji.ttf"), "other");
+ const { get } = good();
+ await expect(
+ installFont("emoji", { cwd, fetch: get, catalog: CATALOG }),
+ ).rejects.toThrow(/--overwrite/);
+ await installFont("emoji", {
+ cwd,
+ fetch: get,
+ catalog: CATALOG,
+ overwrite: true,
+ });
+ expect(readFileSync(join(cwd, "assets/fonts/Emoji.ttf"))).toEqual(
+ Buffer.from(FONT),
+ );
+ });
+
+ it("names the fonts it knows when asked for another", async () => {
+ await expect(installFont("klingon", { cwd })).rejects.toThrow(
+ /Fonts framefields can install: emoji/,
+ );
+ });
+});
+
+describe("fonts.ts", () => {
+ it("registers every installed font relative to itself", async () => {
+ await installFont("emoji", { cwd, fetch: good().get, catalog: CATALOG });
+ const m = writeFontsModule(cwd, join(cwd, "src/components"), CATALOG);
+ expect(m).toMatchObject({
+ path: "src/components/fonts.ts",
+ status: "written",
+ });
+ const text = readFileSync(join(cwd, "src/components/fonts.ts"), "utf8");
+ expect(text.startsWith(FONTS_MODULE_MARKER)).toBe(true);
+ expect(text).toContain(
+ '\tawait FontManager.registerEmojiFont(\n\t\tasset("../../assets/fonts/Emoji.ttf"),\n\t);',
+ );
+ expect(
+ writeFontsModule(cwd, join(cwd, "src/components"), CATALOG).status,
+ ).toBe("unchanged");
+ });
+
+ it("leaves a fonts.ts it didn't generate alone", () => {
+ mkdirSync(join(cwd, "components"));
+ writeFileSync(join(cwd, "components/fonts.ts"), "// mine\n");
+ expect(writeFontsModule(cwd, join(cwd, "components"), CATALOG).status).toBe(
+ "skipped",
+ );
+ expect(readFileSync(join(cwd, "components/fonts.ts"), "utf8")).toBe(
+ "// mine\n",
+ );
+ });
+});
+
+describe("framefields add with fonts", () => {
+ const item = (name: string, fonts?: RegistryItem["fonts"]): RegistryItem => ({
+ name,
+ title: name,
+ summary: "",
+ tags: [],
+ example: "",
+ parts: [],
+ cues: [],
+ registryDependencies: [],
+ ...(fonts && { fonts }),
+ files: [{ path: `${name}/index.ts`, content: `${name}\n` }],
+ });
+ function registry() {
+ const dir = join(cwd, ".registry");
+ mkdirSync(dir);
+ const items = [
+ item("chat-thread", [{ font: "emoji", why: "Reactions are emoji." }]),
+ item("captions", [{ font: "emoji", why: "Captions carry emoji." }]),
+ item("counter"),
+ ];
+ writeFileSync(join(dir, "index.json"), JSON.stringify(items));
+ for (const i of items)
+ writeFileSync(join(dir, `${i.name}.json`), JSON.stringify(i));
+ return openRegistry(dir);
+ }
+
+ it("installs a requested font once and writes fonts.ts", async () => {
+ const { get, calls } = good();
+ const report = await add(["chat-thread", "captions"], {
+ cwd,
+ registry: registry(),
+ fetch: get,
+ fontCatalog: CATALOG,
+ });
+ expect(report.fonts).toEqual([
+ {
+ role: "emoji",
+ path: "assets/fonts/Emoji.ttf",
+ status: "installed",
+ why: "Reactions are emoji.",
+ by: "chat-thread",
+ },
+ ]);
+ expect(calls).toHaveLength(2); // font + license, once
+ expect(report.fontsModule?.path).toBe("components/fonts.ts");
+ expect(readConfig(cwd).config).toEqual({
+ components: "components",
+ fonts: { emoji: "assets/fonts/Emoji.ttf" },
+ });
+ });
+
+ it("skips fonts with fonts: false, and needs none for plain components", async () => {
+ const reg = registry();
+ const plain = await add(["counter"], { cwd, registry: reg });
+ expect(plain.fonts).toEqual([]);
+ expect(plain.fontsModule).toBeUndefined();
+ const skipped = await add(["chat-thread"], {
+ cwd,
+ registry: reg,
+ fonts: false,
+ });
+ expect(skipped.fontsSkipped).toEqual([
+ { role: "emoji", why: "Reactions are emoji.", by: "chat-thread" },
+ ]);
+ expect(existsSync(join(cwd, "assets"))).toBe(false);
+ });
+});
+
+describe("the pinned catalog", () => {
+ it("pins Noto Color Emoji by size and SHA-256, with its OFL license", () => {
+ const e = FONTS.emoji as FontSpec;
+ expect(e.font.url).toMatch(
+ /noto-emoji\/v2\.051\/fonts\/NotoColorEmoji\.ttf$/,
+ );
+ expect(e.font.sha256).toMatch(/^[0-9a-f]{64}$/);
+ expect(e.license.id).toBe("OFL-1.1");
+ });
+
+ it("matches the emoji font the repo renders with", () => {
+ const local = readFileSync(
+ new URL(
+ "../../../renderer/src/assets/NotoColorEmoji.ttf",
+ import.meta.url,
+ ),
+ );
+ expect(local.length).toBe(FONTS.emoji?.font.bytes);
+ expect(hash(local)).toBe(FONTS.emoji?.font.sha256);
+ });
+});
+
+describe("the themes' fonts", () => {
+ it.each([
+ ["sans", "Inter", "Inter.ttf"],
+ ["mono", "JetBrains Mono", "JetBrainsMono.ttf"],
+ ])("%s is the repo's own %s, registered under that family", (role, family, file) => {
+ const spec = FONTS[role] as FontSpec;
+ expect(spec.register).toEqual({ family });
+ expect(spec.license.id).toBe("OFL-1.1");
+ const local = readFileSync(
+ new URL(`../../../../assets/fonts/${file}`, import.meta.url),
+ );
+ expect(local.length).toBe(spec.font.bytes);
+ expect(hash(local)).toBe(spec.font.sha256);
+ });
+});
+
+describe("lfsHint", () => {
+ it("suggests LFS in a Git repo that doesn't track fonts", () => {
+ expect(lfsHint(cwd, "assets/fonts/Emoji.ttf")).toBeNull();
+ mkdirSync(join(cwd, ".git"));
+ expect(lfsHint(cwd, "assets/fonts/Emoji.ttf")).toMatch(
+ /git lfs track "assets\/fonts\/\*\*\/\*\.ttf"/,
+ );
+ writeFileSync(
+ join(cwd, ".gitattributes"),
+ "assets/fonts/**/*.ttf filter=lfs diff=lfs merge=lfs -text\n",
+ );
+ expect(lfsHint(cwd, "assets/fonts/Emoji.ttf")).toBeNull();
+ });
+});
diff --git a/packages/framefields/src/cli/fonts.ts b/packages/framefields/src/cli/fonts.ts
new file mode 100644
index 00000000..1e25b333
--- /dev/null
+++ b/packages/framefields/src/cli/fonts.ts
@@ -0,0 +1,322 @@
+/**
+ * Fonts the CLI installs into a project: a catalog of pinned files (URL,
+ * size, SHA-256, license), the installer `framefields add` and
+ * `framefields fonts add` share, and the generated `fonts.ts` module that
+ * registers whatever is installed.
+ *
+ * framefields ships no fonts in its package (a color emoji font alone is
+ * ~10 MB); they're fetched when a project needs one, verified byte for byte,
+ * and saved with their license next to them.
+ */
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, join, posix, relative, resolve, sep } from "node:path";
+import { readConfig, writeConfig } from "./config.js";
+
+/** A downloadable file, pinned by size and hash. */
+interface PinnedFile {
+ url: string;
+ sha256: string;
+ bytes: number;
+}
+
+export interface FontSpec {
+ /** What it's for, in a sentence: shown by `fonts list`. */
+ label: string;
+ /** File name it's saved under. */
+ file: string;
+ font: PinnedFile;
+ license: PinnedFile & {
+ /** SPDX id. */
+ id: string;
+ /** File name it's saved under, next to the font. */
+ file: string;
+ };
+ /**
+ * How it registers: as the color emoji font, or as a text family under
+ * this name (the name themes use: `Inter`, `JetBrains Mono`).
+ */
+ register: { emoji: true } | { family: string };
+}
+
+const NOTO_EMOJI =
+ "https://raw.githubusercontent.com/googlefonts/noto-emoji/v2.051";
+/** google/fonts at one commit: Inter and JetBrains Mono. */
+const GOOGLE_FONTS =
+ "https://raw.githubusercontent.com/google/fonts/e7db6ca603fd4862010383ff17ffd6cc4ffac1c0";
+
+/** Installable fonts by role. */
+export const FONTS: Record<string, FontSpec> = {
+ emoji: {
+ label: "Noto Color Emoji 2.051: color emoji in any text (🎉 ❤️ 👍)",
+ file: "NotoColorEmoji.ttf",
+ font: {
+ url: `${NOTO_EMOJI}/fonts/NotoColorEmoji.ttf`,
+ sha256:
+ "72a635cb3d2f3524c51620cdde406b217204e8a6a06c6a096ff8ed4b5fd6e27b",
+ bytes: 10_673_480,
+ },
+ license: {
+ id: "OFL-1.1",
+ file: "NotoColorEmoji-OFL.txt",
+ url: `${NOTO_EMOJI}/fonts/LICENSE`,
+ sha256:
+ "6a73f9541c2de74158c0e7cf6b0a58ef774f5a780bf191f2d7ec9cc53efe2bf2",
+ bytes: 4_301,
+ },
+ register: { emoji: true },
+ },
+ sans: googleFont({
+ label: "Inter 4: the built-in themes' display and body face",
+ file: "Inter.ttf",
+ family: "Inter",
+ path: "ofl/inter/Inter%5Bopsz,wght%5D.ttf",
+ sha256: "29160a80ff49ddcab2c97711247e08b1fab27a484a329ce8b813d820dc559031",
+ bytes: 876_576,
+ license: {
+ path: "ofl/inter/OFL.txt",
+ sha256:
+ "5b9321a4298cfeb6b34354164a1c3afc3db114569984c502b9b35d988fd58c57",
+ bytes: 4_377,
+ },
+ }),
+ mono: googleFont({
+ label: "JetBrains Mono 2: the built-in themes' code and terminal face",
+ file: "JetBrainsMono.ttf",
+ family: "JetBrains Mono",
+ path: "ofl/jetbrainsmono/JetBrainsMono%5Bwght%5D.ttf",
+ sha256: "48715a42ec242c21e9f02692891e147d022299a52e48d5e413e1a942193ffeda",
+ bytes: 187_208,
+ license: {
+ path: "ofl/jetbrainsmono/OFL.txt",
+ sha256:
+ "b2fe5e8987594e9ffd1d2ca52a2f5d73eb8335243893c5d6254b5ad69269591d",
+ bytes: 4_399,
+ },
+ }),
+};
+
+/** google/fonts, pinned to one commit. */
+function googleFont(o: {
+ label: string;
+ file: string;
+ family: string;
+ path: string;
+ sha256: string;
+ bytes: number;
+ license: { path: string; sha256: string; bytes: number };
+}): FontSpec {
+ const at = (path: string) => `${GOOGLE_FONTS}/${path}`;
+ return {
+ label: o.label,
+ file: o.file,
+ font: { url: at(o.path), sha256: o.sha256, bytes: o.bytes },
+ license: {
+ url: at(o.license.path),
+ sha256: o.license.sha256,
+ bytes: o.license.bytes,
+ id: "OFL-1.1",
+ file: o.file.replace(/\.ttf$/, "-OFL.txt"),
+ },
+ register: { family: o.family },
+ };
+}
+
+/** Where fonts go when `framefields.json` names no place: the setup skill's layout. */
+export const DEFAULT_FONTS_DIR = "assets/fonts";
+
+export type Fetch = (url: string) => Promise<{
+ ok: boolean;
+ status: number;
+ statusText: string;
+ arrayBuffer(): Promise<ArrayBuffer>;
+}>;
+
+export interface FontInstallOptions {
+ cwd: string;
+ /** Folder for new font files, relative to `cwd`. Default `assets/fonts`. */
+ dir?: string;
+ /** Replace a different file already at the target path. */
+ overwrite?: boolean;
+ /** For tests; default the global `fetch`. */
+ fetch?: Fetch;
+ /** For tests; default {@link FONTS}. */
+ catalog?: Record<string, FontSpec>;
+ /** Called before a download starts (for progress messages). */
+ onDownload?: (spec: FontSpec) => void;
+}
+
+export interface FontInstall {
+ role: string;
+ /** Relative to the project root. */
+ path: string;
+ /**
+ * `installed`: downloaded now. `present`: the pinned file was already
+ * there. `configured`: `framefields.json` already names a font for the role.
+ */
+ status: "installed" | "present" | "configured";
+}
+
+const sha256 = (bytes: Uint8Array) =>
+ createHash("sha256").update(bytes).digest("hex");
+
+/** A project-relative path with forward slashes, as `framefields.json` keeps it. */
+const projectPath = (cwd: string, path: string) =>
+ relative(cwd, path).split(sep).join(posix.sep);
+
+/** Install the font for `role` into the project and record it in `framefields.json`. */
+export async function installFont(
+ role: string,
+ options: FontInstallOptions,
+): Promise<FontInstall> {
+ const catalog = options.catalog ?? FONTS;
+ const spec = catalog[role];
+ if (!spec)
+ throw new Error(
+ `Unknown font "${role}". Fonts framefields can install: ${Object.keys(catalog).join(", ")}.`,
+ );
+ const { cwd } = options;
+ const { config } = readConfig(cwd);
+ const configured = config.fonts?.[role];
+ if (configured && existsSync(resolve(cwd, configured)))
+ return { role, path: configured, status: "configured" };
+
+ const target = resolve(cwd, options.dir ?? DEFAULT_FONTS_DIR, spec.file);
+ const path = projectPath(cwd, target);
+ let status: FontInstall["status"] = "present";
+ const current = existsSync(target) ? readFileSync(target) : null;
+ if (!current || sha256(current) !== spec.font.sha256) {
+ if (current && !options.overwrite)
+ throw new Error(
+ `${path} exists but isn't the pinned ${spec.file}. Pass --overwrite to replace it, or point "fonts.${role}" in framefields.json at it to keep using yours.`,
+ );
+ options.onDownload?.(spec);
+ const get = options.fetch ?? (fetch as unknown as Fetch);
+ const [font, license] = await Promise.all([
+ download(spec.font, get),
+ download(spec.license, get),
+ ]);
+ mkdirSync(dirname(target), { recursive: true });
+ writeFileSync(target, font);
+ writeFileSync(join(dirname(target), spec.license.file), license);
+ status = "installed";
+ }
+ writeConfig(cwd, {
+ ...config,
+ fonts: { ...config.fonts, [role]: path },
+ });
+ return { role, path, status };
+}
+
+async function download(file: PinnedFile, get: Fetch): Promise<Uint8Array> {
+ let res: Awaited<ReturnType<Fetch>>;
+ try {
+ res = await get(file.url);
+ } catch (error) {
+ throw new Error(
+ `Couldn't download ${file.url} (${error instanceof Error ? error.message : String(error)}). Check the connection, or download it yourself and point framefields.json "fonts" at it.`,
+ );
+ }
+ if (!res.ok) throw new Error(`${file.url}: ${res.status} ${res.statusText}`);
+ const bytes = new Uint8Array(await res.arrayBuffer());
+ const hash = sha256(bytes);
+ if (bytes.length !== file.bytes || hash !== file.sha256)
+ throw new Error(
+ `${file.url} isn't the pinned file (got ${bytes.length} bytes, sha256 ${hash}; expected ${file.bytes}, ${file.sha256}). Nothing was written.`,
+ );
+ return bytes;
+}
+
+/** First line of the generated module: files without it are the user's and left alone. */
+export const FONTS_MODULE_MARKER =
+ "// Generated by framefields from framefields.json.";
+
+export interface FontsModule {
+ /** Relative to the project root. */
+ path: string;
+ /** `skipped`: the file exists without the marker, so it's the user's. */
+ status: "written" | "unchanged" | "skipped";
+ /** The registration calls, one line each, for printing when `skipped`. */
+ calls: string[];
+}
+
+/**
+ * Write `<components>/fonts.ts`, which registers every font in
+ * `framefields.json`. Call it once before building or rendering:
+ * `await registerFonts()`.
+ */
+export function writeFontsModule(
+ cwd: string,
+ componentsDir: string,
+ catalog: Record<string, FontSpec> = FONTS,
+): FontsModule {
+ const { config } = readConfig(cwd);
+ const target = join(componentsDir, "fonts.ts");
+ const path = projectPath(cwd, target);
+ const fonts = Object.entries(config.fonts ?? {})
+ .filter(([role]) => catalog[role])
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([role, file]) => {
+ const from = relative(componentsDir, resolve(cwd, file as string))
+ .split(sep)
+ .join(posix.sep);
+ const url = from.startsWith(".") ? from : `./${from}`;
+ return { register: (catalog[role] as FontSpec).register, url };
+ });
+ const call = (r: FontSpec["register"], source: string) =>
+ "family" in r
+ ? `register({ family: ${JSON.stringify(r.family)}, source: ${source} })`
+ : `registerEmojiFont(${source})`;
+ const calls = fonts.map(
+ (f) => `await FontManager.${call(f.register, `asset("${f.url}")`)};`,
+ );
+ const content = `${FONTS_MODULE_MARKER}
+// \`framefields add\` and \`framefields fonts add\` rewrite it when fonts
+// change; register any other fonts in your own code.
+import { FontManager } from "framefields";
+
+/** A path next to this file as a URL: works in Node and in the browser preview. */
+const asset = (path: string) => new URL(path, import.meta.url).href;
+
+/**
+ * Register the fonts this project installed with framefields. Call it
+ * once, before building any text or rendering:
+ *
+ * \`\`\`ts
+ * await registerFonts();
+ * \`\`\`
+ */
+export async function registerFonts(): Promise<void> {
+${fonts
+ // Wrapped the way Biome / Prettier would at 80 columns.
+ .map((f) =>
+ "family" in f.register
+ ? `\tawait FontManager.register({\n\t\tfamily: ${JSON.stringify(f.register.family)},\n\t\tsource: asset("${f.url}"),\n\t});`
+ : `\tawait FontManager.registerEmojiFont(\n\t\tasset("${f.url}"),\n\t);`,
+ )
+ .join("\n")}
+}
+`;
+ if (existsSync(target)) {
+ const current = readFileSync(target, "utf8");
+ if (current === content) return { path, status: "unchanged", calls };
+ if (!current.startsWith(FONTS_MODULE_MARKER))
+ return { path, status: "skipped", calls };
+ }
+ mkdirSync(componentsDir, { recursive: true });
+ writeFileSync(target, content);
+ return { path, status: "written", calls };
+}
+
+/**
+ * A hint when fonts land in a Git repo whose `.gitattributes` doesn't send
+ * them to LFS (a 10 MB binary bloats every clone), or null.
+ */
+export function lfsHint(cwd: string, fontPath: string): string | null {
+ if (!existsSync(join(cwd, ".git"))) return null;
+ const attrs = join(cwd, ".gitattributes");
+ const text = existsSync(attrs) ? readFileSync(attrs, "utf8") : "";
+ if (/\.ttf\b[^\n]*filter=lfs/.test(text)) return null;
+ const dir = posix.dirname(fontPath);
+ return `Fonts are large binaries: track them with Git LFS, e.g. \`git lfs track "${dir}/**/*.ttf"\`.`;
+}
diff --git a/packages/framefields/src/cli/init.test.ts b/packages/framefields/src/cli/init.test.ts
new file mode 100644
index 00000000..2936c575
--- /dev/null
+++ b/packages/framefields/src/cli/init.test.ts
@@ -0,0 +1,296 @@
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import ts from "typescript";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { readConfig } from "./config.js";
+import type { Fetch, FontSpec } from "./fonts.js";
+import {
+ detectPackageManager,
+ type InitOptions,
+ init,
+ packageName,
+ type Runner,
+} from "./init.js";
+import { FILM_TS, GITATTRIBUTES, RENDER_TS, THEME_TS } from "./templates.js";
+
+const bytes = (t: string) => new TextEncoder().encode(t);
+const hash = (b: Uint8Array) => createHash("sha256").update(b).digest("hex");
+/** A fake catalog entry plus the files a fake server serves for it. */
+function fake(role: string, register: FontSpec["register"]) {
+ const font = bytes(`${role} font`);
+ const license = bytes(`${role} license`);
+ const spec: FontSpec = {
+ label: role,
+ file: `${role}.ttf`,
+ font: {
+ url: `https://f.test/${role}.ttf`,
+ sha256: hash(font),
+ bytes: font.length,
+ },
+ license: {
+ url: `https://f.test/${role}.txt`,
+ sha256: hash(license),
+ bytes: license.length,
+ id: "OFL-1.1",
+ file: `${role}-OFL.txt`,
+ },
+ register,
+ };
+ return {
+ spec,
+ files: { [spec.font.url]: font, [spec.license.url]: license },
+ };
+}
+const sans = fake("sans", { family: "Inter" });
+const mono = fake("mono", { family: "JetBrains Mono" });
+const emoji = fake("emoji", { emoji: true });
+const catalog = { sans: sans.spec, mono: mono.spec, emoji: emoji.spec };
+const served: Record<string, Uint8Array> = {
+ ...sans.files,
+ ...mono.files,
+ ...emoji.files,
+};
+const fetchFake: Fetch = async (url) => ({
+ ok: url in served,
+ status: url in served ? 200 : 404,
+ statusText: "",
+ arrayBuffer: async () =>
+ (served[url] ?? new Uint8Array()).slice().buffer as ArrayBuffer,
+});
+
+/** A runner that records commands; `git rev-parse` says "not a repo". */
+function runner(codes: Partial<Record<string, number>> = {}) {
+ const calls: string[] = [];
+ const run: Runner = async (command, args) => {
+ const line = [command, ...args].join(" ");
+ calls.push(line);
+ return codes[line] ?? (line.startsWith("git rev-parse") ? 128 : 0);
+ };
+ return { run, calls };
+}
+
+let cwd: string;
+beforeEach(() => {
+ cwd = mkdtempSync(join(tmpdir(), "framefields-init-test-"));
+});
+afterEach(() => rmSync(cwd, { recursive: true, force: true }));
+
+const opts = (extra: Partial<InitOptions> = {}): InitOptions => ({
+ cwd,
+ framefieldsVersion: "2.6.0",
+ fetch: fetchFake,
+ fontCatalog: catalog,
+ run: runner().run,
+ ...extra,
+});
+const read = (path: string) => readFileSync(join(cwd, path), "utf8");
+const json = (path: string) => JSON.parse(read(path));
+
+describe("framefields init", () => {
+ it("scaffolds a project that installs and renders as the setup skill says", async () => {
+ const { run, calls } = runner();
+ const report = await init(
+ opts({
+ dir: "My Film",
+ run,
+ userAgent: "pnpm/10.13.1 npm/? node/v22.12.0",
+ }),
+ );
+ const root = (p: string) => join("My Film", p);
+ expect(report.name).toBe("my-film");
+ expect(report.packageManager).toBe("pnpm");
+ const pkg = json(root("package.json"));
+ expect(pkg).toMatchObject({
+ name: "my-film",
+ private: true,
+ type: "module",
+ packageManager: "[email protected]",
+ dependencies: { framefields: "^2.6.0" },
+ allowScripts: { "skia-canvas": true, sharp: false },
+ pnpm: { onlyBuiltDependencies: ["skia-canvas"] },
+ trustedDependencies: ["skia-canvas"],
+ });
+ expect(Object.keys(pkg.scripts)).toEqual([
+ "typecheck",
+ "frames",
+ "grid",
+ "preview",
+ "render",
+ ]);
+ expect(Object.keys(pkg.devDependencies).sort()).toEqual([
+ "@types/node",
+ "tsx",
+ "typescript",
+ ]);
+ expect(read(root("src/film.ts"))).toBe(FILM_TS);
+ expect(existsSync(join(cwd, root("assets/footage/.gitkeep")))).toBe(true);
+ expect(read(root(".gitattributes"))).toContain(GITATTRIBUTES[0]);
+ expect(read(root(".gitignore"))).toContain("output/");
+ expect(read(root("README.md"))).toContain("pnpm frames -- 0 30 60");
+ // The themes' fonts, recorded and registered where theme.ts imports them.
+ expect(report.fonts.map((f) => [f.role, f.path, f.status])).toEqual([
+ ["sans", "assets/fonts/sans.ttf", "installed"],
+ ["mono", "assets/fonts/mono.ttf", "installed"],
+ ]);
+ expect(readConfig(join(cwd, "My Film")).config).toEqual({
+ components: "src/components",
+ fonts: { sans: "assets/fonts/sans.ttf", mono: "assets/fonts/mono.ttf" },
+ });
+ const fontsTs = read(root("src/components/fonts.ts"));
+ expect(fontsTs).toContain('family: "Inter",');
+ expect(fontsTs).toContain('source: asset("../../assets/fonts/sans.ttf"),');
+ expect(read(root("src/theme.ts"))).toContain(
+ 'from "./components/fonts.js"',
+ );
+ expect(calls).toEqual([
+ "git rev-parse --is-inside-work-tree",
+ "git init -q",
+ "git lfs version",
+ ]);
+ expect(report.git).toBe("initialized");
+ expect(report.installed).toBe(false);
+ });
+
+ it("merges into an existing project without replacing anything", async () => {
+ writeFileSync(
+ join(cwd, "package.json"),
+ JSON.stringify({
+ name: "existing",
+ scripts: { render: "node mine.js", test: "vitest" },
+ dependencies: { framefields: "^2.0.0" },
+ devDependencies: { tsx: "^4.0.0" },
+ pnpm: { onlyBuiltDependencies: ["esbuild"] },
+ }),
+ );
+ mkdirSync(join(cwd, "src"));
+ writeFileSync(join(cwd, "src/film.ts"), "// mine\n");
+ writeFileSync(join(cwd, ".gitignore"), "dist/\noutput/");
+ const report = await init(opts({ fonts: false }));
+ const pkg = json("package.json");
+ expect(pkg.type).toBe("module");
+ expect(pkg.scripts).toMatchObject({
+ render: "node mine.js",
+ test: "vitest",
+ frames: "tsx src/render.ts frames",
+ });
+ expect(pkg.dependencies.framefields).toBe("^2.0.0");
+ expect(pkg.devDependencies).toMatchObject({
+ tsx: "^4.0.0",
+ typescript: "^5.8.3",
+ });
+ expect(pkg.pnpm.onlyBuiltDependencies).toEqual(["esbuild", "skia-canvas"]);
+ expect(read("src/film.ts")).toBe("// mine\n");
+ expect(read(".gitignore")).toBe(
+ "dist/\noutput/\nnode_modules/\nscratch/\n.DS_Store\n",
+ );
+ expect(report.merged).toEqual(["package.json", ".gitignore"]);
+ expect(report.unchanged).toContain("src/film.ts");
+ expect(report.fonts).toEqual([]);
+ // theme.ts imports fonts.ts, so it exists even with no fonts.
+ expect(read("src/components/fonts.ts")).toContain(
+ "export async function registerFonts",
+ );
+
+ const again = await init(opts({ fonts: false }));
+ expect(again.written).toEqual([]);
+ expect(again.merged).toEqual([]);
+ });
+
+ it("refuses CommonJS packages", async () => {
+ writeFileSync(
+ join(cwd, "package.json"),
+ JSON.stringify({ type: "commonjs" }),
+ );
+ await expect(init(opts())).rejects.toThrow(/"type": "module"/);
+ });
+
+ it("adds emoji on request, skips git when asked, and installs with the chosen manager", async () => {
+ const { run, calls } = runner();
+ const report = await init(
+ opts({
+ run,
+ emoji: true,
+ git: false,
+ install: true,
+ packageManager: "bun",
+ }),
+ );
+ expect(report.fonts.map((f) => f.role)).toEqual(["sans", "mono", "emoji"]);
+ expect(calls).toEqual(["bun install"]);
+ expect(report.installed).toBe(true);
+ expect(json("package.json").packageManager).toBeUndefined();
+ expect(report.runScript("frames")).toBe("bun run frames");
+ });
+
+ it("reports an existing repository and a failed install", async () => {
+ const { run } = runner({
+ "git rev-parse --is-inside-work-tree": 0,
+ "git lfs version": 1,
+ "npm install": 1,
+ });
+ await expect(init(opts({ run, install: true }))).rejects.toThrow(
+ /`npm install` failed .*files are written/,
+ );
+ const report = await init(
+ opts({
+ run: runner({
+ "git rev-parse --is-inside-work-tree": 0,
+ "git lfs version": 1,
+ }).run,
+ }),
+ );
+ expect(report.git).toBe("existing");
+ expect(report.lfs).toBe(false);
+ });
+});
+
+describe("helpers", () => {
+ it("detects the package manager from its user agent", () => {
+ expect(
+ detectPackageManager("npm/11.4.2 node/v22.12.0 darwin arm64"),
+ ).toEqual({
+ name: "npm",
+ version: "11.4.2",
+ });
+ expect(detectPackageManager("yarn/4.9.1 npm/? node/v22")?.name).toBe(
+ "yarn",
+ );
+ expect(detectPackageManager(undefined)).toBeNull();
+ });
+
+ it("makes folder names npm-safe", () => {
+ expect(packageName("My Film!")).toBe("my-film");
+ expect(packageName("__")).toBe("framefields-film");
+ });
+});
+
+describe("templates", () => {
+ it.each([
+ ["theme.ts", THEME_TS],
+ ["film.ts", FILM_TS],
+ ["render.ts", RENDER_TS],
+ ])("%s is valid TypeScript", (file, source) => {
+ const out = ts.transpileModule(source, {
+ fileName: file,
+ reportDiagnostics: true,
+ compilerOptions: {
+ module: ts.ModuleKind.NodeNext,
+ target: ts.ScriptTarget.ES2022,
+ },
+ });
+ expect(
+ out.diagnostics?.map((d) =>
+ ts.flattenDiagnosticMessageText(d.messageText, "\n"),
+ ),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/framefields/src/cli/init.ts b/packages/framefields/src/cli/init.ts
new file mode 100644
index 00000000..3918d73f
--- /dev/null
+++ b/packages/framefields/src/cli/init.ts
@@ -0,0 +1,371 @@
+/**
+ * `framefields init [dir]`: a new framefields project, or framefields added
+ * to an existing one. Writes the layout the setup skill describes
+ * (`package.json` with the install-script approvals framefields needs,
+ * `tsconfig.json`, `src/theme.ts` / `film.ts` / `render.ts`, `assets/`,
+ * LFS `.gitattributes`, `.gitignore`), installs the themes' fonts and keeps
+ * them registered in `src/components/fonts.ts`.
+ *
+ * It never overwrites: files that exist are left alone, and `package.json`,
+ * `.gitignore` and `.gitattributes` gain only what they're missing.
+ */
+import { spawn } from "node:child_process";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { basename, dirname, join, relative, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { readConfig, writeConfig } from "./config.js";
+import {
+ type Fetch,
+ type FontInstall,
+ type FontSpec,
+ type FontsModule,
+ installFont,
+ writeFontsModule,
+} from "./fonts.js";
+import {
+ FILM_TS,
+ GITATTRIBUTES,
+ GITIGNORE,
+ packageFields,
+ RENDER_TS,
+ readme,
+ THEME_TS,
+ TSCONFIG,
+} from "./templates.js";
+
+export const PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"] as const;
+export type PackageManager = (typeof PACKAGE_MANAGERS)[number];
+
+/** Runs a command; resolves with its exit code (127 when it can't start). */
+export type Runner = (
+ command: string,
+ args: string[],
+ options: { cwd: string; quiet?: boolean },
+) => Promise<number>;
+
+export interface InitOptions {
+ /** Where the command runs. */
+ cwd: string;
+ /** The project folder, relative to `cwd`. Default `.`. */
+ dir?: string;
+ /** Package name. Default: the folder's name, made npm-safe. */
+ name?: string;
+ /** Default: the one running the command (`npm_config_user_agent`), else npm. */
+ packageManager?: PackageManager;
+ /** `npm_config_user_agent`, for detecting the package manager and its version. */
+ userAgent?: string;
+ /** Install the themes' fonts, Inter and JetBrains Mono (default true). */
+ fonts?: boolean;
+ /** Also install the color emoji font. */
+ emoji?: boolean;
+ /** `git init` when the folder isn't in a repository yet (default true). */
+ git?: boolean;
+ /** Run the package manager's install afterwards (default false). */
+ install?: boolean;
+ /** framefields version for `dependencies`. Default: this package's. */
+ framefieldsVersion?: string;
+ /** For tests. */
+ run?: Runner;
+ fetch?: Fetch;
+ fontCatalog?: Record<string, FontSpec>;
+ onDownload?: (spec: FontSpec) => void;
+}
+
+export interface InitReport {
+ /** The project folder (absolute). */
+ root: string;
+ name: string;
+ packageManager: PackageManager;
+ /** Paths relative to `root`. */
+ written: string[];
+ /** Existing files that gained missing entries. */
+ merged: string[];
+ /** Existing files left as they were. */
+ unchanged: string[];
+ fonts: FontInstall[];
+ fontsModule: FontsModule;
+ git: "initialized" | "existing" | "skipped" | "unavailable";
+ /** Whether `git lfs` is available (null when Git was skipped). */
+ lfs: boolean | null;
+ installed: boolean;
+ /** `npm run frames` / `pnpm frames` …, for next-step messages. */
+ runScript(script: string): string;
+}
+
+/** The package manager in `npm_config_user_agent` (`pnpm/10.13.1 npm/? node/v22 …`). */
+export function detectPackageManager(
+ userAgent: string | undefined,
+): { name: PackageManager; version?: string } | null {
+ const m = userAgent?.match(/^(npm|pnpm|yarn|bun)\/(\d[\w.+-]*)/);
+ if (!m) return null;
+ return { name: m[1] as PackageManager, version: m[2] };
+}
+
+const runScriptFor = (pm: PackageManager) => (script: string) =>
+ pm === "npm" || pm === "bun" ? `${pm} run ${script}` : `${pm} ${script}`;
+
+/** `My Film!` → `my-film`. */
+export function packageName(folder: string): string {
+ const name = folder
+ .toLowerCase()
+ .replace(/[^a-z0-9._~-]+/g, "-")
+ .replace(/^[-._]+|[-._]+$/g, "");
+ return name || "framefields-film";
+}
+
+export async function init(options: InitOptions): Promise<InitReport> {
+ const root = resolve(options.cwd, options.dir ?? ".");
+ mkdirSync(root, { recursive: true });
+ const detected = detectPackageManager(options.userAgent);
+ const pm = options.packageManager ?? detected?.name ?? "npm";
+ const pmVersion = detected?.name === pm ? detected.version : undefined;
+ const run = options.run ?? spawnRunner;
+ const report: InitReport = {
+ root,
+ name: "",
+ packageManager: pm,
+ written: [],
+ merged: [],
+ unchanged: [],
+ fonts: [],
+ fontsModule: { path: "", status: "unchanged", calls: [] },
+ git: "skipped",
+ lfs: null,
+ installed: false,
+ runScript: runScriptFor(pm),
+ };
+ const fields = packageFields({
+ framefieldsVersion: options.framefieldsVersion ?? ownVersion(),
+ ...(pmVersion && { packageManager: `${pm}@${pmVersion}` }),
+ });
+
+ // package.json: written whole, or merged without replacing anything.
+ const pkgPath = join(root, "package.json");
+ if (existsSync(pkgPath)) {
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as Record<
+ string,
+ unknown
+ >;
+ if (pkg.type === "commonjs")
+ throw new Error(
+ 'package.json has "type": "commonjs". framefields projects are ES modules: set "type": "module" (and convert any require() files) first.',
+ );
+ report.name =
+ typeof pkg.name === "string" ? pkg.name : packageName(basename(root));
+ const merged = mergePackage(pkg, fields);
+ record(report, "package.json", writeIfChanged(pkgPath, merged, pkg));
+ } else {
+ report.name = options.name ?? packageName(basename(root));
+ writeJson(pkgPath, {
+ name: report.name,
+ version: "0.0.0",
+ private: true,
+ ...fields,
+ });
+ report.written.push("package.json");
+ }
+
+ const files: Array<[string, string]> = [
+ ["tsconfig.json", TSCONFIG],
+ ["src/theme.ts", THEME_TS],
+ ["src/film.ts", FILM_TS],
+ ["src/render.ts", RENDER_TS],
+ ["assets/footage/.gitkeep", ""],
+ ["README.md", readme(report.name, report.runScript)],
+ ];
+ for (const [path, content] of files) {
+ const target = join(root, path);
+ if (existsSync(target)) report.unchanged.push(path);
+ else {
+ mkdirSync(dirname(target), { recursive: true });
+ writeFileSync(target, content);
+ report.written.push(path);
+ }
+ }
+ for (const [path, lines] of [
+ [".gitignore", GITIGNORE],
+ [".gitattributes", GITATTRIBUTES],
+ ] as const)
+ record(report, path, appendLines(join(root, path), lines));
+
+ // framefields.json, then fonts (recorded there) and their module.
+ const { config, saved } = readConfig(root);
+ if (!saved) {
+ writeConfig(root, config);
+ report.written.push("framefields.json");
+ }
+ const roles = [
+ ...(options.fonts === false ? [] : ["sans", "mono"]),
+ ...(options.emoji ? ["emoji"] : []),
+ ];
+ for (const role of roles)
+ report.fonts.push(
+ await installFont(role, {
+ cwd: root,
+ fetch: options.fetch,
+ catalog: options.fontCatalog,
+ onDownload: options.onDownload,
+ }),
+ );
+ // theme.ts imports it, so it's written even with no fonts installed.
+ report.fontsModule = writeFontsModule(
+ root,
+ resolve(root, readConfig(root).config.components),
+ options.fontCatalog,
+ );
+
+ if (options.git !== false) {
+ const inside = await run("git", ["rev-parse", "--is-inside-work-tree"], {
+ cwd: root,
+ quiet: true,
+ });
+ if (inside === 0) report.git = "existing";
+ else if (
+ (await run("git", ["init", "-q"], { cwd: root, quiet: true })) === 0
+ )
+ report.git = "initialized";
+ else report.git = "unavailable";
+ if (report.git !== "unavailable")
+ report.lfs =
+ (await run("git", ["lfs", "version"], { cwd: root, quiet: true })) ===
+ 0;
+ }
+
+ if (options.install) {
+ const code = await run(pm, ["install"], { cwd: root });
+ if (code !== 0)
+ throw new Error(
+ `\`${pm} install\` failed (exit ${code}). The project files are written; fix the error and run it again.`,
+ );
+ report.installed = true;
+ }
+ return report;
+}
+
+/** Add every field of `fields` the package lacks; existing values win. */
+function mergePackage(
+ pkg: Record<string, unknown>,
+ fields: ReturnType<typeof packageFields>,
+): Record<string, unknown> {
+ const out: Record<string, unknown> = { ...pkg };
+ const obj = (v: unknown) =>
+ v && typeof v === "object" && !Array.isArray(v)
+ ? (v as Record<string, unknown>)
+ : {};
+ const union = (a: unknown, b: readonly string[]) => [
+ ...new Set([...(Array.isArray(a) ? (a as string[]) : []), ...b]),
+ ];
+ out.type ??= fields.type;
+ if (fields.packageManager) out.packageManager ??= fields.packageManager;
+ for (const key of [
+ "scripts",
+ "dependencies",
+ "devDependencies",
+ "allowScripts",
+ ] as const) {
+ const theirs = obj(pkg[key]);
+ // A dependency listed in either block counts as present.
+ const present =
+ key === "dependencies" || key === "devDependencies"
+ ? { ...obj(pkg.dependencies), ...obj(pkg.devDependencies) }
+ : theirs;
+ const missing = Object.entries(fields[key]).filter(
+ ([k]) => !(k in present),
+ );
+ if (missing.length > 0)
+ out[key] = { ...theirs, ...Object.fromEntries(missing) };
+ }
+ const pnpm = obj(pkg.pnpm);
+ out.pnpm = {
+ ...pnpm,
+ onlyBuiltDependencies: union(
+ pnpm.onlyBuiltDependencies,
+ fields.pnpm.onlyBuiltDependencies,
+ ),
+ ignoredBuiltDependencies: union(
+ pnpm.ignoredBuiltDependencies,
+ fields.pnpm.ignoredBuiltDependencies,
+ ),
+ };
+ out.trustedDependencies = union(
+ pkg.trustedDependencies,
+ fields.trustedDependencies,
+ );
+ return out;
+}
+
+function writeJson(path: string, value: unknown) {
+ writeFileSync(path, `${JSON.stringify(value, null, "\t")}\n`);
+}
+
+function writeIfChanged(
+ path: string,
+ next: Record<string, unknown>,
+ prev: Record<string, unknown>,
+): boolean {
+ if (JSON.stringify(next) === JSON.stringify(prev)) return false;
+ writeJson(path, next);
+ return true;
+}
+
+/** Create `path` with `lines` ("written"), or append the ones it lacks (true if any). */
+function appendLines(
+ path: string,
+ lines: readonly string[],
+): "written" | boolean {
+ if (!existsSync(path)) {
+ writeFileSync(path, `${lines.join("\n")}\n`);
+ return "written";
+ }
+ const text = readFileSync(path, "utf8");
+ const have = new Set(text.split(/\r?\n/).map((l) => l.trim()));
+ const missing = lines.filter((l) => !have.has(l));
+ if (missing.length === 0) return false;
+ writeFileSync(
+ path,
+ `${text}${text.endsWith("\n") || text === "" ? "" : "\n"}${missing.join("\n")}\n`,
+ );
+ return true;
+}
+
+/** File it under written (new), merged (changed) or unchanged. */
+function record(report: InitReport, path: string, result: "written" | boolean) {
+ if (result === "written") report.written.push(path);
+ else if (result) report.merged.push(path);
+ else report.unchanged.push(path);
+}
+
+/** This package's version, from the nearest `package.json` named framefields. */
+function ownVersion(): string {
+ let dir = dirname(fileURLToPath(import.meta.url));
+ for (;;) {
+ const file = join(dir, "package.json");
+ if (existsSync(file)) {
+ const pkg = JSON.parse(readFileSync(file, "utf8")) as {
+ name?: string;
+ version?: string;
+ };
+ if (pkg.name === "framefields" && pkg.version) return pkg.version;
+ }
+ const up = dirname(dir);
+ if (up === dir) throw new Error("Can't find framefields' own package.json");
+ dir = up;
+ }
+}
+
+const spawnRunner: Runner = (command, args, { cwd, quiet }) =>
+ new Promise((done) => {
+ const child = spawn(command, args, {
+ cwd,
+ stdio: quiet ? "ignore" : "inherit",
+ // Windows needs a shell to find npm.cmd / pnpm.cmd.
+ shell: process.platform === "win32",
+ });
+ child.on("error", () => done(127));
+ child.on("close", (code) => done(code ?? 1));
+ });
+
+/** Where the project is, as the user would `cd` to it. */
+export function shownPath(cwd: string, root: string): string {
+ return relative(cwd, root) || ".";
+}
diff --git a/packages/framefields/src/cli/registry.ts b/packages/framefields/src/cli/registry.ts
index bd728560..24ff2c19 100644
--- a/packages/framefields/src/cli/registry.ts
+++ b/packages/framefields/src/cli/registry.ts
@@ -22,6 +22,8 @@ export interface RegistryEntry {
export interface RegistryItem extends RegistryEntry {
parts: readonly string[];
cues: readonly string[];
+ /** Fonts to install with it, by role (see `cli/fonts.ts`). */
+ fonts?: ReadonlyArray<{ font: string; why: string }>;
/** Paths relative to the components directory. */
files: Array<{ path: string; content: string }>;
}
diff --git a/packages/framefields/src/cli/templates.ts b/packages/framefields/src/cli/templates.ts
new file mode 100644
index 00000000..b145ef73
--- /dev/null
+++ b/packages/framefields/src/cli/templates.ts
@@ -0,0 +1,237 @@
+/**
+ * The files `framefields init` writes: the project layout the framefields
+ * setup skill describes. `film.ts` only builds; `render.ts` renders frames,
+ * a grid, the live preview or the video; `theme.ts` holds the numbers.
+ */
+
+/**
+ * Packages with install scripts. framefields needs exactly one (skia-canvas
+ * downloads its native binary); the others work without theirs.
+ */
+const ALLOWED_SCRIPTS = ["skia-canvas"];
+const DENIED_SCRIPTS = [
+ "sharp",
+ "webgpu",
+ "onnxruntime-node",
+ "node-av",
+ "esbuild",
+ "protobufjs",
+];
+
+/** Dev tools the scripts use, at versions the scaffold is tested with. */
+export const DEV_DEPENDENCIES: Record<string, string> = {
+ "@types/node": "^24.1.0",
+ tsx: "^4.20.3",
+ typescript: "^5.8.3",
+};
+
+export const SCRIPTS: Record<string, string> = {
+ typecheck: "tsc --noEmit -p .",
+ frames: "tsx src/render.ts frames",
+ grid: "tsx src/render.ts grid",
+ preview: "tsx src/render.ts preview",
+ render: "tsx src/render.ts",
+};
+
+/**
+ * The `package.json` fields a framefields project needs. npm reads
+ * `allowScripts`, pnpm its `pnpm` block, bun `trustedDependencies`.
+ */
+export function packageFields(o: {
+ framefieldsVersion: string;
+ packageManager?: string;
+}) {
+ return {
+ type: "module",
+ ...(o.packageManager && { packageManager: o.packageManager }),
+ scripts: SCRIPTS,
+ dependencies: { framefields: `^${o.framefieldsVersion}` },
+ devDependencies: DEV_DEPENDENCIES,
+ allowScripts: Object.fromEntries([
+ ...ALLOWED_SCRIPTS.map((p) => [p, true]),
+ ...DENIED_SCRIPTS.map((p) => [p, false]),
+ ]),
+ pnpm: {
+ onlyBuiltDependencies: ALLOWED_SCRIPTS,
+ ignoredBuiltDependencies: DENIED_SCRIPTS,
+ },
+ trustedDependencies: ALLOWED_SCRIPTS,
+ };
+}
+
+export const TSCONFIG = `${JSON.stringify(
+ {
+ compilerOptions: {
+ module: "NodeNext",
+ moduleResolution: "NodeNext",
+ target: "ES2022",
+ strict: true,
+ skipLibCheck: true,
+ noEmit: true,
+ types: ["node"],
+ },
+ include: ["src/**/*"],
+ },
+ null,
+ "\t",
+)}\n`;
+
+/** Lines `init` makes sure `.gitignore` has. */
+export const GITIGNORE = ["node_modules/", "output/", "scratch/", ".DS_Store"];
+
+/** Media, LUTs and fonts go to Git LFS; renders stay out of Git. */
+export const GITATTRIBUTES = [
+ "assets/**/*.mp4 filter=lfs diff=lfs merge=lfs -text",
+ "assets/**/*.mov filter=lfs diff=lfs merge=lfs -text",
+ "assets/**/*.webm filter=lfs diff=lfs merge=lfs -text",
+ "assets/**/*.mp3 filter=lfs diff=lfs merge=lfs -text",
+ "assets/**/*.wav filter=lfs diff=lfs merge=lfs -text",
+ "assets/**/*.cube filter=lfs diff=lfs merge=lfs -text",
+ "assets/**/*.lottie filter=lfs diff=lfs merge=lfs -text",
+ "assets/fonts/**/*.ttf filter=lfs diff=lfs merge=lfs -text",
+ "assets/fonts/**/*.otf filter=lfs diff=lfs merge=lfs -text",
+];
+
+export const THEME_TS = `import { registerFonts as registerInstalledFonts } from "./components/fonts.js";
+
+export const W = 1920;
+export const H = 1080;
+export const FPS = 30;
+export const INK = "#0E0D0C";
+export const PAPER = "#EEE9E0";
+/** Installed by \`framefields init\` (assets/fonts), registered below. */
+export const SANS = "Inter";
+export const MONO = "JetBrains Mono";
+
+/**
+ * Register the film's fonts. Fonts framefields installed
+ * (\`npx framefields fonts add <role>\`) come from the generated
+ * components/fonts.ts; register any others here with \`FontManager.register\`.
+ */
+export async function registerFonts(): Promise<void> {
+ await registerInstalledFonts();
+}
+`;
+
+export const FILM_TS = `import { Composition, Layer, LayerAnimation } from "framefields";
+import { FPS, H, INK, PAPER, registerFonts, SANS, W } from "./theme.js";
+
+const DURATION = 3 * FPS; // frames
+
+/** Builds the film. Only builds: no rendering or writes, so tests, the preview and renders share it. */
+export async function buildFilm(): Promise<Composition> {
+ // Fonts must be registered before any text layer is built.
+ await registerFonts();
+
+ const film = new Composition({
+ width: W,
+ height: H,
+ fps: FPS,
+ durationMs: (DURATION / FPS) * 1000,
+ backgroundColor: INK,
+ });
+
+ film.add(
+ Layer.text("Hello, framefields", {
+ id: "title",
+ position: "absolute",
+ x: 0,
+ y: H / 2 - 60,
+ width: W,
+ height: 120,
+ fontFamily: SANS,
+ fontSize: 96,
+ fontWeight: 700,
+ fill: PAPER,
+ align: "center",
+ }).animate(
+ LayerAnimation.create()
+ .fadeIn(0, 20, "power2.out")
+ .fromTo("y", H / 2 - 20, H / 2 - 60, {
+ start: 0,
+ end: 30,
+ ease: "expo.out",
+ }),
+ ),
+ );
+
+ return film;
+}
+`;
+
+export const RENDER_TS = `import fs from "node:fs/promises";
+import path from "node:path";
+import { HeadlessMediaRenderer, startPreview } from "framefields";
+import { buildFilm } from "./film.js";
+
+const OUT = path.resolve(import.meta.dirname, "../output");
+// \`npm run frames -- 0 30\` needs the \`--\`; pnpm passes it through: drop it.
+const [mode = "video", ...args] = process.argv
+ .slice(2)
+ .filter((a) => a !== "--");
+
+if (mode === "preview") {
+ // The page runs film.ts itself and renders it with WebGPU in the browser.
+ const session = await startPreview({
+ entry: new URL("./film.ts", import.meta.url),
+ export: "buildFilm",
+ });
+ console.log(\`Preview at \${session.url}\`);
+ await session.closed; // until its tab closes or the next preview replaces it
+ process.exit(0);
+}
+
+const film = await buildFilm();
+await fs.mkdir(OUT, { recursive: true });
+
+if (mode === "frames") {
+ const renderer = new HeadlessMediaRenderer();
+ for (const frame of (args.length ? args : ["0"]).map(Number)) {
+ const png = await film.renderFrame({ frame, renderer });
+ const file = path.join(OUT, \`f\${String(frame).padStart(4, "0")}.png\`);
+ await fs.writeFile(file, png);
+ console.log(\`Wrote \${path.relative(process.cwd(), file)}\`);
+ }
+} else if (mode === "grid") {
+ const png = await film.renderFrameGrid({
+ frames: args.length ? args.map(Number) : [0, 10, 20, 30, 45, 60, 75, 89],
+ columns: 4,
+ cellWidth: 480,
+ showLabels: true,
+ });
+ await fs.writeFile(path.join(OUT, "grid.png"), png);
+ console.log("Wrote output/grid.png");
+} else {
+ const result = await film.renderVideo({
+ outputPath: path.join(OUT, "output.mp4"),
+ quality: "high",
+ });
+ await result.cleanup?.();
+ console.log(\`Exported \${result.filePath}\`);
+}
+
+// Native GPU and encoder threads keep Node alive; always exit explicitly.
+process.exit(0);
+`;
+
+export function readme(name: string, run: (script: string) => string): string {
+ return `# ${name}
+
+A film built with [framefields](https://www.npmjs.com/package/framefields).
+
+\`\`\`bash
+${run("typecheck")}
+${run("frames")} -- 0 30 60 # PNGs in output/
+${run("grid")} # a contact sheet of the motion
+${run("preview")} # play it in the browser
+${run("render")} # output/output.mp4
+\`\`\`
+
+- \`src/film.ts\` builds the composition, \`src/theme.ts\` holds sizes, colors and fonts,
+ \`src/render.ts\` renders it.
+- \`npx framefields list\` shows ready-made components; \`npx framefields add <name>\` copies
+ one into \`src/components/\`.
+- Footage, audio and fonts live in \`assets/\` and are tracked with Git LFS
+ (\`git lfs install\` once per machine, \`git lfs pull\` after cloning).
+`;
+}
diff --git a/packages/framefields/src/components/m5.render.test.ts b/packages/framefields/src/components/m5.render.test.ts
index 9fb6c360..6c483415 100644
--- a/packages/framefields/src/components/m5.render.test.ts
+++ b/packages/framefields/src/components/m5.render.test.ts
@@ -12,6 +12,9 @@ import { ChatThread, Confetti, Spotlight, Toasts } from "./testing.js";
*/
beforeAll(async () => {
await FontManager.register("assets/fonts/Inter.ttf");
+ await FontManager.registerEmojiFont(
+ "../renderer/src/assets/NotoColorEmoji.ttf",
+ );
});
function comp(
nodes: Parameters<Composition["add"]>[0],
@@ -58,6 +61,39 @@ describe("ChatThread (render)", () => {
});
});
+describe("ChatThread reactions (render)", () => {
+ /** Clearly red pixels: the Noto heart (no theme colour is this red). */
+ const reds = (data: Uint8ClampedArray) => {
+ let n = 0;
+ for (let i = 0; i < data.length; i += 4)
+ if (
+ (data[i] as number) > 180 &&
+ (data[i + 1] as number) < 90 &&
+ (data[i + 2] as number) < 90
+ )
+ n++;
+ return n;
+ };
+ it("draws an emoji reaction from the color emoji font", async () => {
+ const thread = (reaction?: string) =>
+ ChatThread({
+ width: 960,
+ height: 540,
+ messages: [
+ { from: "me", text: "Shipped?", at: 0 },
+ { from: "sam", text: "Yes!", at: 10, reaction },
+ ],
+ });
+ const withHeart = await frame(comp(thread("❤️")), 120);
+ const without = await frame(comp(thread()), 120);
+ expect(reds(without.pixels)).toBe(0);
+ expect(reds(withHeart.pixels)).toBeGreaterThan(40);
+ // "heart" is shorthand for the same emoji.
+ const word = await frame(comp(thread("heart")), 120);
+ expect(computeMse(word.pixels, withHeart.pixels)).toBe(0);
+ });
+});
+
describe("Toasts (render)", () => {
it("is empty before the first toast arrives", async () => {
const t = Toasts({
diff --git a/packages/framefields/src/emoji-font-lint.test.ts b/packages/framefields/src/emoji-font-lint.test.ts
new file mode 100644
index 00000000..129191b6
--- /dev/null
+++ b/packages/framefields/src/emoji-font-lint.test.ts
@@ -0,0 +1,63 @@
+/**
+ * Without a color emoji font, emoji in text draw nothing. `lint()` says so
+ * (naming the layers), and so does rendering: the font preloader warns
+ * once, pointing at `framefields fonts add emoji`, with no per-emoji noise.
+ */
+import { fileURLToPath } from "node:url";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { Composition, FontManager, Layer } from "./index.js";
+
+beforeAll(async () => {
+ await FontManager.register("assets/fonts/Inter.ttf");
+});
+afterEach(() => vi.restoreAllMocks());
+
+const comp = (text: string) => {
+ const c = new Composition({
+ width: 200,
+ height: 80,
+ fps: 30,
+ durationFrames: 1,
+ backgroundColor: "#000000",
+ });
+ c.add(
+ Layer.text(text, {
+ id: "t",
+ fontFamily: "Inter",
+ fontSize: 20,
+ fill: "#fff",
+ }),
+ );
+ return c;
+};
+const flagged = (c: Composition) =>
+ c.lint().some((d) => d.code === "missing_emoji_font");
+
+describe("missing emoji font", () => {
+ it("is flagged by lint and warned once on render, until a font is registered", async () => {
+ expect(FontManager.hasEmojiFont()).toBe(false);
+ expect(flagged(comp("plain"))).toBe(false);
+ const c = comp("Ship it 🚀");
+ expect(flagged(c)).toBe(true);
+
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ await c.renderFrame({ frame: 0 });
+ await c.renderFrame({ frame: 0 });
+ const said = warn.mock.calls.map((args) => String(args[0]));
+ expect(
+ said.filter((m) => m.includes("framefields fonts add emoji")),
+ ).toHaveLength(1);
+ expect(said.filter((m) => m.includes("not preloaded"))).toEqual([]);
+
+ await FontManager.registerEmojiFont(
+ fileURLToPath(
+ new URL(
+ "../../renderer/src/assets/NotoColorEmoji.ttf",
+ import.meta.url,
+ ),
+ ),
+ );
+ expect(FontManager.hasEmojiFont()).toBe(true);
+ expect(flagged(comp("Ship it 🚀"))).toBe(false);
+ });
+});
diff --git a/packages/framefields/src/fonts/manager.ts b/packages/framefields/src/fonts/manager.ts
index a4411165..2a82d215 100644
--- a/packages/framefields/src/fonts/manager.ts
+++ b/packages/framefields/src/fonts/manager.ts
@@ -252,6 +252,11 @@ export class FontManager {
SlugFontCache.setEmojiFont(buffer, filePath);
}
+ /** Whether a color emoji font is registered (or set to load from a path / URL). */
+ public static hasEmojiFont(): boolean {
+ return SlugFontCache.hasEmojiFont();
+ }
+
/**
* Measures text with the real font, exactly as `Layer.text` lays it out:
* box size, line count, per-glyph positions and caret offsets. Use it to
diff --git a/packages/framefields/src/index.ts b/packages/framefields/src/index.ts
index 4f53d4c5..56d7ec53 100644
--- a/packages/framefields/src/index.ts
+++ b/packages/framefields/src/index.ts
@@ -2120,7 +2120,9 @@ export class Composition {
* never change. `renderVideo({ qa })` includes these automatically.
*/
public lint(): RenderDiagnostic[] {
- return lintComposition(this.toSpec());
+ return lintComposition(this.toSpec(), {
+ emojiFont: FontManager.hasEmojiFont(),
+ });
}
}
@@ -3389,6 +3391,7 @@ export type Effect<TConfig extends object = Record<string, unknown>> =
export {
type Anchor,
type AudioLevels,
+ after,
type BaseProps,
type Cue,
type Cues,
@@ -3399,6 +3402,7 @@ export {
type Theme,
type ThemeInput,
themes,
+ withDefaults,
} from "@framefields/components/toolkit";
export {
analyzeAudio,
diff --git a/packages/renderers/src/preload-fonts.ts b/packages/renderers/src/preload-fonts.ts
index 09ee969f..5df2b28e 100644
--- a/packages/renderers/src/preload-fonts.ts
+++ b/packages/renderers/src/preload-fonts.ts
@@ -66,7 +66,7 @@ export async function preloadCompositionFonts(
if (!SlugFontCache.hasEmojiFont() && !warnedNoEmojiFont) {
warnedNoEmojiFont = true;
console.warn(
- "[framefields] Text uses emoji but no emoji font is registered, so exports draw nothing for them. Register a color emoji font (e.g. Noto Color Emoji) with FontManager.registerEmojiFont(path).",
+ "[framefields] Text uses emoji but no emoji font is registered, so exports draw nothing for them. Run `npx framefields fonts add emoji` and call the generated `registerFonts()`, or register a color emoji font (e.g. Noto Color Emoji) with FontManager.registerEmojiFont(path). `comp.lint()` names the layers (missing_emoji_font).",
);
}
for (const [key, fontSize] of emoji) {
diff --git a/packages/webgpu-renderers/src/nodes/paragraph.ts b/packages/webgpu-renderers/src/nodes/paragraph.ts
index a8e8da70..8ae0ed79 100644
--- a/packages/webgpu-renderers/src/nodes/paragraph.ts
+++ b/packages/webgpu-renderers/src/nodes/paragraph.ts
@@ -141,9 +141,11 @@ function getOrCreateEmojiTexture(
typeof globalThis.document === "undefined";
if (isNode) {
- console.warn(
- `[getOrCreateEmojiTexture] Emoji "${char}" not preloaded. Returning fallback dummy texture.`,
- );
+ // With no emoji font at all, the preloader has already said so once.
+ if (SlugFontCache.hasEmojiFont())
+ console.warn(
+ `[getOrCreateEmojiTexture] Emoji "${char}" not preloaded. Returning fallback dummy texture.`,
+ );
tex = device.createTexture({
label: `Emoji-Dummy-${char}`,
size: [1, 1],
diff --git a/plugins/framefields/skills/framefields/SKILL.md b/plugins/framefields/skills/framefields/SKILL.md
index a1be0d96..4fab7b81 100644
--- a/plugins/framefields/skills/framefields/SKILL.md
+++ b/plugins/framefields/skills/framefields/SKILL.md
@@ -30,6 +30,14 @@ This skill takes a project from nothing to a verified first render. For anything
## 2. Install
+**Fastest path: `npx framefields init`.** It writes everything in sections 2 and 3 for you: `package.json` (with the install-script approvals below, scripts, dependencies, `packageManager`), `tsconfig.json`, `src/theme.ts` / `film.ts` / `render.ts`, `assets/`, the LFS `.gitattributes` and `.gitignore`. It also downloads Inter and JetBrains Mono (pinned, with their OFL licenses), registers them in the generated `src/components/fonts.ts` that `theme.ts` calls, and runs `git init`.
+
+```bash
+npx framefields init my-film --install # a new project; or `init` inside an existing one
+```
+
+In an existing project it never overwrites: existing files are left alone, and `package.json`, `.gitignore` and `.gitattributes` only gain what they lack (a `"type": "commonjs"` package is refused). Options: `--pm npm|pnpm|yarn|bun` (default: the one running it), `--emoji` (also the color emoji font), `--no-fonts`, `--no-git`, `--name`. Then go to section 4. The rest of this section and section 3 describe what it writes, for doing it by hand or merging into an unusual setup.
+
Use the package manager the project already uses (look for `pnpm-lock.yaml`, `yarn.lock`, `bun.lock`, or `package-lock.json`).
**Write `package.json` before installing.** npm 11, pnpm 10, and bun block dependency install scripts unless the project approves them, and framefields needs exactly one: `skia-canvas` downloads its native binary in its install script. Without it, `import "framefields"` fails with `Cannot find module '.../skia.node'`. The other packages that ship install scripts work without them, so deny them to keep installs quiet and skip downloads framefields never uses.
@@ -47,11 +55,12 @@ For a new project, create `package.json` with all three blocks. In an existing p
"webgpu": false,
"onnxruntime-node": false,
"node-av": false,
- "esbuild": false
+ "esbuild": false,
+ "protobufjs": false
},
"pnpm": {
"onlyBuiltDependencies": ["skia-canvas"],
- "ignoredBuiltDependencies": ["sharp", "webgpu", "onnxruntime-node", "node-av", "esbuild"]
+ "ignoredBuiltDependencies": ["sharp", "webgpu", "onnxruntime-node", "node-av", "esbuild", "protobufjs"]
},
"trustedDependencies": ["skia-canvas"]
}
@@ -372,6 +381,7 @@ framefields has a registry of parametric motion components: a mouse pointer with
```bash
npx framefields list # every component, one line each
npx framefields add mouse-pointer focus-zoom # writes src/components/<name>/
+npx framefields fonts add emoji # color emoji (chat-thread and captions add it themselves)
```
```typescript
@@ -390,7 +400,9 @@ film.add(pointer);
- **Before writing a common motion piece by hand, run `npx framefields list`.** A component already handles timing, theme, cues and edge cases, and the copy is the project's to adjust.
- Files go to `src/components` (or `components` when there is no `src`); the folder is saved in `framefields.json`, and `--dir` changes it on first use. Components that build on others bring them along (`terminal` adds `app-frame` and `counter`).
- Installed code imports only `framefields` and `framefields/components` (the shared toolkit), so it always matches the installed framefields version. After upgrading framefields, `npx framefields add <name> --overwrite` refreshes a component; without the flag, files you changed are left alone and reported as `skipped`.
-- Every component takes the base props (`x`, `y`, `width`, `height`, `at`, `duration`, `hold`, `theme`, `enter`, `exit`, `seed`) and returns a normal box layer with `cues` (frames of its events), `span` and `parts` (inner layers to animate or style). Time is in frames.
+- **Fonts come with the components that need them.** `chat-thread` and `captions` ask for a color emoji font. `add` downloads Noto Color Emoji (pinned by SHA-256, ~10.7 MB, saved with its OFL license) into `assets/fonts/`, records it under `fonts` in `framefields.json`, and writes `src/components/fonts.ts`. Call its `registerFonts()` once before building or rendering, next to the `FontManager.register` calls. `--no-fonts` skips the download, `npx framefields fonts add emoji` installs it later (or for plain `Layer.text`), and pointing `fonts.emoji` in `framefields.json` at another font keeps yours. Track `assets/fonts/**` with Git LFS.
+- **Emoji without an emoji font draw nothing.** `comp.lint()` reports `missing_emoji_font`, and the first render prints the same warning. Fix it with the command above, not by removing the emoji.
+- Every component takes the base props (`x`, `y`, `width`, `height`, `at`, `duration`, `hold`, `theme`, `enter`, `exit`, `seed`, `fps`, `canvas`) and returns a normal box layer with `cues` (frames of its events), `span` and `parts` (inner layers to animate or style). Time is in frames.
- Each installed `index.ts` documents what the component does at the top and defines its props in its schema; `npx framefields list` gives one-line summaries. Props are validated when the component is built, and a wrong one throws with the reason.
## 9. Report engine issues