Skip to content

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

feat(components): M4 code block, title card, lower third, meter

okanasl7eb76d6ec287
diff --git a/packages/components/SPEC.md b/packages/components/SPEC.md
index 9882a351..2c5a2052 100644
--- a/packages/components/SPEC.md
+++ b/packages/components/SPEC.md
@@ -864,6 +864,161 @@ command), `outputs` (`{ start, end, step }`), `done`.
---
+### 7.9 `CodeBlock`
+
+Code on screen that reads like an editor and moves like an explanation: syntax colours,
+typing, a focus band that walks the lines being discussed, and diffs where unchanged
+lines glide to their new places while removed lines fold away and new ones arrive.
+
+```ts
+CodeBlock({
+ code: before,
+ lang: "ts",
+ typing: { cps: 30 },
+ focus: [{ at: 90, lines: { from: 3, to: 5 } }, { at: 150, lines: [8] }],
+ diff: { to: after, at: 210 },
+ frame: { title: "render.ts" },
+});
+```
+
+**Props**
+
+| Prop | Type | Default | Notes |
+|---|---|---|---|
+| `code` | `string` | required | Tabs expand to `tabSize` spaces. |
+| `lang` | `"ts" \| "js" \| "json" \| "bash" \| "python" \| "css" \| "plain"` | `"ts"` | Built-in tokenizer. |
+| `tokens` | `Array<Array<{ text; kind?; color? }>>` | — | One array per line: bring your own highlighter (shiki, prism …). Overrides `lang`. |
+| `typing` | `boolean \| { cps?, at? }` | `false` | Types the code line by line, seeded rhythm, caret. |
+| `focus` | `{ at; lines: number[] \| { from, to } }[]` | `[]` | 1-based lines. Other lines dim; a band glides to the focused lines. `lines: []` clears. |
+| `diff` | `{ to: string; at: number; duration? }` | — | Line diff (LCS): kept lines move, removed lines fade with a red wash, added lines slide in with a green wash. |
+| `lineNumbers` | `boolean` | `true` | Renumbered across a diff. |
+| `tabSize` | `number` | `2` | |
+| `frame` | `boolean \| { title? }` | `false` | `true` wraps it in an `AppFrame` window; otherwise a rounded surface plate. |
+| text props | `fontFamily`, `fontSize` | theme `mono`, 24 × scale | Line height 1.5. |
+
+**Token colours** come from the theme: keyword `accent2`, string `positive`, number
+`highlight`, comment `muted`, function `accent`, type a cyan, punctuation and operators a
+dimmed ink, everything else `ink`.
+
+**Implementation notes**
+
+- One text node per line with coloured spans; line numbers are their own right-aligned
+ nodes. The block's size is fixed up front from the longest line and the larger line count
+ (before and after a diff), so nothing reflows.
+- Typing keys each line's reveal count with `core/typing.ts` rhythm; a line appears when
+ its first key lands.
+- Focus dims with per-line opacity keys; the band is a box keyed between line spans.
+- Diff matching is a longest common subsequence on trimmed line text, so re-indented
+ lines count as kept and glide (their text swaps in the same frame they start moving).
+
+**Cues:** `keystrokes` (`{ frame, line }`), `lines` (each line's first frame), `focus`
+(`{ frame, lines }`), `diff` (`{ frame, end }`).
+
+**Acceptance**
+
+- Every token of the built-in tokenizer fixtures gets the expected kind (unit tests per lang).
+- After a diff settles, the frame equals a `CodeBlock` of `to` with no diff (render test).
+- Kept lines are on screen in every frame of the diff (they move, never blink).
+
+---
+
+### 7.10 `TitleCard`
+
+Kicker, headline, rule and sub-line in layouts that are designed, not assembled: the
+headline reveals with `TextReveal`, the kicker tracks in, the rule draws, the sub-line
+rises, on one shared timeline.
+
+**Props**
+
+| Prop | Type | Default | Notes |
+|---|---|---|---|
+| `title` | `string` | required | `\n` for a forced break. |
+| `kicker`, `subtitle` | `string` | — | Kicker is upper-case, tracked, accent coloured. |
+| `layout` | `"center" \| "left" \| "stack" \| "split"` | `"center"` | `stack`: left-aligned with a vertical accent bar. `split`: headline left, kicker and sub-line right of a vertical rule. |
+| `reveal` | `RevealStyle` | `"rise"` | Headline style (any `TextReveal` style). |
+| `emphasis` | `(string \| RegExp)[]` | `[]` | Headline words in the accent colour. |
+| `rule` | `boolean` | `true` | |
+| `exitStyle` | `ExitStyle \| false` | `false` | Headline exit; kicker, rule and sub-line fade with it. |
+| `width` | `number` | `1600 × scale` | Headline wraps inside it. |
+| `titleSize`, `fontFamily` | | `120 × scale`, theme `display` | Kicker and sub-line scale from `titleSize`. |
+
+**Cues:** `revealed` (headline at rest), `settled` (every part at rest), `exitStart`.
+
+**Acceptance**
+
+- The settled frame is identical in any render order; each layout keeps every part inside
+ `width` (unit test on the measured geometry).
+
+---
+
+### 7.11 `LowerThird`
+
+The name-and-role bar of interviews and talks. Safe-area aware, measured to its text, and
+it leaves on its own after `hold`.
+
+**Props**
+
+| Prop | Type | Default | Notes |
+|---|---|---|---|
+| `name` | `string` | required | |
+| `role` | `string` | — | |
+| `layout` | `"bar" \| "stacked" \| "tag" \| "line"` | `"bar"` | `bar`: plate with an accent edge; `stacked`: name plate over a smaller accent role plate; `tag`: one pill, name · role; `line`: no plate, an accent line draws up beside the text. |
+| `side` | `"left" \| "right"` | `"left"` | |
+| `safeArea` | `"landscape" \| "portrait" \| Rect` | from the frame's aspect | Placed at the safe area's bottom corner. |
+| `stay` | `boolean` | `false` | Stay on screen instead of leaving after `hold`. |
+| `accent`, `plate` | colours | theme `accent`, `surface` | |
+| `nameSize` | `number` | `44 × scale` | Role is 0.62 × that. |
+
+Root covers the frame (`width` / `height`, default 1920 × 1080 × scale) from 0, 0.
+Default `hold`: 3 seconds.
+
+**Cues:** `in` (fully on screen), `out` (starts leaving; empty with `stay`).
+
+**Acceptance**
+
+- The plate is exactly the measured text width plus padding for any name (unit test).
+- With `side: "right"`, the plate's right edge sits on the safe area's right edge.
+
+---
+
+### 7.12 `Meter`
+
+Progress and scores: a ring, an arc gauge, a bar, lit segments or a star rating, filling
+on the same value timeline as an optional `Counter`.
+
+**Props**
+
+| Prop | Type | Default | Notes |
+|---|---|---|---|
+| `value` / `values` | `number` / `[frame, value, ease?][]` | required | Like `Counter`. |
+| `from`, `max` | `number` | `0`, `100` (`5` for stars) | |
+| `kind` | `"ring" \| "arc" \| "bar" \| "segments" \| "stars"` | `"ring"` | |
+| `segments` | `number` | `10` (stars: `max`) | Cells for `segments`, stars for `stars`. |
+| `size` | `number` | ring / arc 260, bar 640, segments 640, stars 300 (× scale) | Width (bar, segments, stars) or diameter. |
+| `thickness` | `number` | per kind | |
+| `counter` | `boolean` | `true` (not for stars) | A `Counter` in the middle (ring, arc) or beside (bar, segments). |
+| `format`, `suffix` | as `Counter` | `",d"`, `"%"` when `max` is 100 | |
+| `label` | `string` | — | Small caption under (ring, arc) or above (bar). |
+| `color`, `track` | colours | theme `accent`, `line` | |
+| `countDuration`, `ease` | | as `Counter` | Fill and number share them exactly. |
+
+**Implementation notes**
+
+- Ring and arc fills are stroked arc paths with `trimEnd` keyed on the value timeline;
+ the arc spans 240° with round caps. Bars key their fill width.
+- Segments light up (colour and a small pop) on the frame the value crosses each cell.
+- Stars are clipped boxes over filled star shapes, so fractional ratings fill a star partway.
+
+**Cues:** `settled`, `crossings` (`{ frame, segment }` for segments and stars).
+
+**Acceptance**
+
+- The fill fraction equals `(value − from) / (max − from)` at every key frame (unit test on
+ the keys), and the counter shows the same value on those frames.
+- 3.5 stars fill exactly three stars and half of the fourth (render test).
+
+---
+
## 8. Waves 2 and 3
Specified at summary level now; each gets a full section (like §7) before its milestone
@@ -873,14 +1028,14 @@ starts.
| Component | Summary | Key props | Notable framefields use |
|---|---|---|---|
-| `CodeBlock` | Syntax-highlighted code with line focus, typing, and diffs that move unchanged lines to their new places. | `code`, `lang`, `tokens?` (bring your own highlighter), `focus: [lines]`, `diff: { to, at }`, `typing` | Measured mono layout; lines keyed between positions so diffs read as motion. Ships a small built-in tokenizer for ts/js/json/bash/python/css; anything else via `tokens`. |
+| `CodeBlock` | Specified in §7.9 (M4). | | |
| `ChatThread` | A messaging conversation: bubbles from either side, typing indicator, reactions, timestamps, auto-scroll. | `messages: { from, text \| media, at? }[]`, `participants`, `appearance` | Bubble sizes from measured text; spring entries baked; typing dots between messages. |
| `Callout` | A label with a leader line pinned to a point or a moving tracked object; stays inside the frame. | `target`, `text`, `side: "auto" \| …`, `elbow` | Dynamic targets bind to vision `track` signals; auto side picks the free quadrant per frame. |
| `Spotlight` | Dims the frame except a feathered region that glides between targets. | `targets: { at, target }[]`, `dim`, `feather`, `shape` | Inverted alpha matte + blur; region keyed between target rects. |
| `Confetti` | Celebration bursts with paper, ribbons and sparkles that fall and settle. | `bursts: { at, origin, count }[]`, `palette`, `gravity`, `floor` | GPU particles; optional physics floor; bursts can come straight from `cues`. |
-| `Meter` | Progress and score visuals: ring, bar, arc gauge, star rating, each with an optional `Counter`. | `value`, `max`, `kind`, `segments`, `label` | Conic gradients, `trimEnd` arcs, fractional star fill via matte. |
-| `TitleCard` | Kicker, headline, rule and sub-line in tested layouts (`center`, `left`, `split`, `stack`). | `kicker`, `title`, `subtitle`, `layout` | Built from `TextReveal` + `Annotate` (rule) for consistent motion. |
-| `LowerThird` | Name and role bar for interviews and talks, several layouts, safe-area aware. | `name`, `role`, `layout`, `side` | Measured plate width; enter/exit presets. |
+| `Meter` | Specified in §7.12 (M4). | | |
+| `TitleCard` | Specified in §7.10 (M4). | | |
+| `LowerThird` | Specified in §7.11 (M4). | | |
| `Toasts` | Notifications arriving into a stack that pushes down and compresses as it grows. | `items: { at, title, body, icon? }[]`, `max`, `corner` | Stack layout solved offline; spring settle baked. |
### 8.2 Wave 3 candidates
@@ -937,8 +1092,10 @@ root's own top-level code is outside this check), and for each case asserts:
targets, motion …), and
- the bytes added over the baseline stay inside a budget.
-Each new component adds a case importing only itself, with every other component's marker
-forbidden.
+Each component is a row in the script's `COMPONENTS` table: a marker string only its module
+has, and the components it composes (Terminal composes AppFrame and Counter, CodeBlock
+composes AppFrame, TitleCard composes TextReveal, Meter composes Counter). The check imports
+each component alone and forbids every other marker except those.
### 9.6 Budgets
@@ -952,6 +1109,10 @@ forbidden.
| Annotate | 4 per line of target | 5 ms |
| AppFrame | 14 + content | 5 ms |
| Terminal | rows + 6 | 20 ms |
+| CodeBlock | 2 per line + 4 | 10 ms |
+| TitleCard | 8 | 10 ms |
+| LowerThird | 8 | 2 ms |
+| Meter | 6 (segments / stars: 3 per cell) | 5 ms |
### 9.7 Docs and skills
@@ -974,7 +1135,7 @@ Each milestone ends with a changeset for `framefields` (minor), docs, and its ex
| **M1 · Pointer & camera** ✅ | `MousePointer` (rebuilt to the existing changeset design plus the Wave 1 additions), `FocusZoom`, `AppFrame`. | Example `30_product_demo`: a screen recording in a browser frame, pointer with clicks and auto-zoom, click SFX placed from cues. |
| **M2 · Type** ✅ | `TextReveal`, `Counter`, `Annotate`. | All §7.4–7.6 acceptance tests green (§14). No example film for M2 or later milestones: examples stop at `30_product_demo`. |
| **M3 · Speech & shell** ✅ | `Captions` (incl. transcript parsers and `behind`), `Terminal`. | §7.3 / §7.8 acceptance tests green (§15); no example film. |
-| **M4 · Wave 2a** | `CodeBlock`, `TitleCard`, `LowerThird`, `Meter`. | Full specs written first (§8 → §7 format). |
+| **M4 · Wave 2a** ✅ | `CodeBlock`, `TitleCard`, `LowerThird`, `Meter`. | Specs in §7.9–7.12; acceptance tests green (§16); no example film. |
| **M5 · Wave 2b** | `ChatThread`, `Callout`, `Spotlight`, `Confetti`, `Toasts`. | As above. |
| **M6 · Re-score** | Rank Wave 3 against usage and requests. | Updated §8.2. |
@@ -1131,3 +1292,42 @@ Deviations from §7.3 / §7.8:
mono fonts (the bundled JetBrains Mono included) lack `❯`, `✔` and braille. A done line's
leading `✔` / `✓` is replaced by the drawn check. The monospace check (warn when not
mono) is not implemented.
+
+## 16. M4 delivery notes
+
+What landed: `CodeBlock`, `TitleCard`, `LowerThird`, `Meter` (§7.9–7.12), unit tests for
+each, a cross-cutting **unique node id** test over every component (`src/ids.test.ts`), and
+`m4.render.test.ts` (a settled diff renders exactly like the new code; 3.5 stars fill three
+and a half; title cards render identically in any frame order).
+
+How it is built:
+
+- **CodeBlock:** a small regex tokenizer per language (keyword sets built on first use),
+ one text node per line with coloured spans, line numbers as separate nodes. All opacity
+ changes per node (typing, focus, diff) go through one `Track`, so they merge into a single
+ ascending keyframe track. Diffs use an LCS on trimmed lines; removed lines finish leaving
+ before added lines on the same row arrive.
+- **TitleCard:** kicker, headline and sub-line are composed `TextReveal`s; the rule and the
+ `stack` accent bar are keyed boxes (crisper than a stroked mark for a straight rule, so not
+ `Annotate`). With `exitStyle` the headline is built with its hold lined up to the card's,
+ and the other parts fade with it.
+- **LowerThird:** each plate is a clipping box whose background slides in from the side
+ and whose text rises a beat later; leaving reverses it. Keys are merged per node and prop.
+ `tag` is one text node with spans (name bold, role a size down).
+- **Meter:** ring / arc fills are stroked arc paths with `trimEnd` keyed on exactly the
+ value's keyframes and eases, so the composed `Counter` and the fill agree on every key
+ frame. Segments light (with a pop) on the frame the value crosses them; stars fill through
+ widening clip boxes.
+
+Found on the way:
+
+- **Duplicate ids share geometry and keyframes in the renderer.** CodeBlock's diff washes
+ had the same ids as the added lines and took their layout. Ids are now unique, and
+ `ids.test.ts` guards every component.
+
+Deviations from §7.9–7.12:
+
+- CodeBlock line numbers use the muted colour (no extra opacity), and `focus.lines` takes
+ a list or `{ from, to }` (a two-number list was ambiguous).
+- TitleCard's rule is a box, not an `Annotate` mark.
+- LowerThird has no logo slot yet.
diff --git a/packages/components/src/code-block/index.test.ts b/packages/components/src/code-block/index.test.ts
new file mode 100644
index 00000000..13e646cc
--- /dev/null
+++ b/packages/components/src/code-block/index.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from "vitest";
+import { bind } from "../core/contract.js";
+import { fakeHost } from "../test/fake-host.js";
+import { codeBlock } from "./index.js";
+
+const make = () => bind(fakeHost(), codeBlock);
+type Node = {
+ id?: string;
+ children?: Node[];
+ spans?: Array<{ text: string; fill: string }>;
+ animation?: {
+ tracks: Array<{
+ prop: string;
+ keyframes: Array<{ frame: number; value: number }>;
+ }>;
+ };
+};
+const find = (n: unknown, id: string): Node | undefined => {
+ const node = n as Node;
+ if (node.id === id) return node;
+ for (const c of node.children ?? []) {
+ const hit = find(c, id);
+ if (hit) return hit;
+ }
+ return undefined;
+};
+const track = (n: Node | undefined, prop: string) =>
+ n?.animation?.tracks.find((t) => t.prop === prop)?.keyframes ?? [];
+
+describe("CodeBlock", () => {
+ it("colours tokens from the theme", () => {
+ const c = make()({ id: "c", code: 'const a = "x";' });
+ const spans = find(c, "c-line-0")?.spans ?? [];
+ expect(spans.find((s) => s.text.includes("const"))?.fill).toBe("#b07cff");
+ expect(spans.find((s) => s.text.includes('"x"'))?.fill).toBe("#3ecf8e");
+ });
+
+ it("sizes for the larger of before and after, so nothing reflows", () => {
+ const small = make()({ code: "a" });
+ const grown = make()({
+ code: "a",
+ diff: { to: "a\nbbbbbbbbbb\nc", at: 10 },
+ });
+ const size = (n: unknown) => n as { width: number; height: number };
+ expect(size(grown).height).toBeGreaterThan(size(small).height);
+ expect(size(grown).width).toBeGreaterThan(size(small).width);
+ });
+
+ it("moves kept lines, removes and adds the rest, and cues it", () => {
+ const c = make()({
+ id: "c",
+ code: "a\nb\nc",
+ diff: { to: "c\nd", at: 30, duration: 20 },
+ });
+ expect(c.cues.diff).toEqual([{ frame: 30, end: 50 }]);
+ // "c" moves from row 2 to row 0.
+ const ys = track(find(c, "c-line-2"), "y").map((k) => k.frame);
+ expect(ys).toEqual([30, 50]);
+ expect(find(c, "c-added-1")).toBeDefined();
+ const gone = track(find(c, "c-line-0"), "opacity");
+ expect(gone[gone.length - 1]?.value).toBe(0);
+ });
+
+ it("types code with key cues, skipping indentation", () => {
+ const c = make()({ code: "ab\n c", typing: true });
+ expect(c.cues.keystrokes.map((k) => k.line)).toEqual([1, 1, 2]);
+ expect(c.cues.lines[1]?.frame).toBeGreaterThan(
+ c.cues.keystrokes[1]?.frame ?? 0,
+ );
+ });
+
+ it("dims unfocused lines and cues focus steps", () => {
+ const c = make()({
+ id: "c",
+ code: "a\nb\nc",
+ focus: [{ at: 10, lines: { from: 2, to: 3 } }],
+ });
+ expect(c.cues.focus).toEqual([{ frame: 10, lines: [2, 3] }]);
+ const dim = track(find(c, "c-line-0"), "opacity");
+ expect(dim[dim.length - 1]?.value).toBeCloseTo(0.32, 5);
+ const lit = track(find(c, "c-line-1"), "opacity");
+ expect(lit[lit.length - 1]?.value).toBe(1);
+ });
+});
diff --git a/packages/components/src/code-block/index.ts b/packages/components/src/code-block/index.ts
new file mode 100644
index 00000000..0fa301ef
--- /dev/null
+++ b/packages/components/src/code-block/index.ts
@@ -0,0 +1,557 @@
+/**
+ * CodeBlock: code that reads like an editor and moves like an explanation.
+ * Syntax colours, typing, a focus band that walks the lines being
+ * discussed, and diffs where kept lines glide to their new places while
+ * removed lines fold away and new ones arrive.
+ */
+import {
+ type AnimatableProp,
+ type KeyframeTuple,
+ LayerAnimation,
+ type LayoutNode,
+ type TextSpan,
+} from "@framefields/compositions/program";
+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 { type Theme, themeFrames } from "../core/theme.js";
+import { typingFrames } from "../core/typing.js";
+import { diffLines, expandTabs, focusSet, Track } from "./plan.js";
+import {
+ CODE_LANGS,
+ type Token,
+ type TokenKind,
+ tokenize,
+} from "./tokenize.js";
+
+export {
+ CODE_LANGS,
+ type CodeLang,
+ type Token,
+ type TokenKind,
+} from "./tokenize.js";
+
+export interface CodeBlockCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ /** Every typed character (`typing`): for key sounds. */
+ keystrokes: ReadonlyArray<{ frame: number; line: number }>;
+ /** Each line's first frame on screen (1-based `line`). */
+ lines: ReadonlyArray<{ frame: number; line: number }>;
+ /** Each focus step. */
+ focus: ReadonlyArray<{ frame: number; lines: number[] }>;
+ /** The diff, start to settle. */
+ diff: ReadonlyArray<{ frame: number; end: number }>;
+}
+
+/** Token colours from theme tokens. */
+function palette(theme: Theme): Record<TokenKind, string> {
+ const c = theme.color;
+ return {
+ plain: c.ink,
+ keyword: c.accent2,
+ string: c.positive,
+ number: c.highlight,
+ comment: c.muted,
+ function: c.accent,
+ type: "#4cc9e0",
+ property: c.ink,
+ punctuation: c.muted,
+ operator: c.muted,
+ };
+}
+
+/** `#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(
+ z
+ .object({
+ text: z.string(),
+ kind: z
+ .enum([
+ "plain",
+ "keyword",
+ "string",
+ "number",
+ "comment",
+ "function",
+ "type",
+ "property",
+ "punctuation",
+ "operator",
+ ])
+ .optional(),
+ color: z.string().optional(),
+ })
+ .strict(),
+ ),
+ );
+}
+
+export const codeBlock = /* @__PURE__ */ defineComponent({
+ name: "CodeBlock",
+ props: () => ({
+ code: z.string(),
+ lang: z.enum(CODE_LANGS).default("ts"),
+ /** Your own highlighter's output, one token list per line (overrides `lang`). */
+ tokens: tokenSchema().optional(),
+ typing: z
+ .union([
+ z.boolean(),
+ z
+ .object({
+ cps: z.number().positive().optional(),
+ at: z.number().int().min(0).optional(),
+ })
+ .strict(),
+ ])
+ .default(false),
+ /** 1-based lines, as a list or `{ from, to }`; `[]` clears. */
+ focus: z
+ .array(
+ z
+ .object({
+ at: z.number().int().min(0),
+ lines: z.union([
+ z.array(z.number().int().positive()),
+ z
+ .object({
+ from: z.number().int().positive(),
+ to: z.number().int().positive(),
+ })
+ .strict(),
+ ]),
+ })
+ .strict(),
+ )
+ .default([]),
+ diff: z
+ .object({
+ to: z.string(),
+ at: z.number().int().min(0),
+ duration: z.number().int().positive().optional(),
+ })
+ .strict()
+ .optional(),
+ lineNumbers: z.boolean().default(true),
+ tabSize: z.number().int().positive().default(2),
+ /** Wrap in an AppFrame window (with a title such as the file name). */
+ frame: z
+ .union([z.boolean(), z.object({ title: z.string().optional() }).strict()])
+ .default(false),
+ fontFamily: z.string().optional(),
+ fontSize: z.number().positive().optional(),
+ }),
+ defaults: { enter: false, exit: false },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const s = theme.scale;
+ const fs = props.fontSize ?? 24 * s;
+ const fontFamily = props.fontFamily ?? theme.font.mono;
+ const LINE_HEIGHT = 1.5;
+ const m = host.measure("M", {
+ fontFamily,
+ fontSize: fs,
+ lineHeight: LINE_HEIGHT,
+ });
+ const adv = m.width;
+ const lh = m.lineHeight;
+ const colors = palette(theme);
+
+ const before = expandTabs(props.code, props.tabSize).split("\n");
+ const after = props.diff
+ ? expandTabs(props.diff.to, props.tabSize).split("\n")
+ : null;
+ const tokensOf = (lines: string[], own?: Token[][]) =>
+ own ?? tokenize(lines.join("\n"), props.lang);
+ const beforeTokens = tokensOf(
+ before,
+ props.tokens as Token[][] | undefined,
+ );
+ const afterTokens = after ? tokensOf(after) : null;
+
+ // Fixed size up front: the widest line and the most lines, before and after.
+ const rows = Math.max(before.length, after?.length ?? 0);
+ const cols = Math.max(
+ 1,
+ ...before.map((l) => l.length),
+ ...(after ?? []).map((l) => l.length),
+ );
+ const pad = fs;
+ const gutter = props.lineNumbers ? (String(rows).length + 2) * adv : 0;
+ const W = pad * 2 + gutter + cols * adv;
+ const H = pad * 2 + rows * lh;
+ const rowY = (i: number) => pad + i * lh;
+ const textX = pad + gutter;
+
+ const spans = (line: Token[]): TextSpan[] =>
+ line.map((t) => ({
+ text: t.text,
+ fill: t.color ?? colors[t.kind ?? "plain"],
+ }));
+ const lineNode = (id: string, tokens: Token[], text: string, row: number) =>
+ host.text(text || " ", {
+ id: ctx.partId(id),
+ position: "absolute",
+ x: textX,
+ y: rowY(row),
+ fontFamily,
+ fontSize: fs,
+ lineHeight: LINE_HEIGHT,
+ fill: colors.plain,
+ ...(text && { spans: spans(tokens) }),
+ });
+ const numberNode = (id: string, n: number, row: number) =>
+ host.text(String(n), {
+ id: ctx.partId(id),
+ position: "absolute",
+ x: pad,
+ y: rowY(row),
+ width: gutter - adv * 1.5,
+ align: "end",
+ fontFamily,
+ fontSize: fs,
+ lineHeight: LINE_HEIGHT,
+ fill: theme.color.muted,
+ });
+
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+ const rowsLayer: LayoutNode[] = [];
+ const washes: LayoutNode[] = [];
+ const opacity = new Map<LayoutNode, Track>();
+ const fade = (node: LayoutNode, initial = 1) => {
+ let t = opacity.get(node);
+ if (!t) {
+ t = new Track(initial);
+ opacity.set(node, t);
+ }
+ return t;
+ };
+ const animations = new Map<LayoutNode, LayerAnimation>();
+ const animOf = (node: LayoutNode) => {
+ let a = animations.get(node);
+ if (!a) {
+ a = LayerAnimation.create();
+ animations.set(node, a);
+ }
+ return a;
+ };
+
+ const beforeNodes = before.map((text, i) =>
+ lineNode(`line-${i}`, beforeTokens[i] ?? [], text, i),
+ );
+ const beforeNumbers = props.lineNumbers
+ ? before.map((_, i) => numberNode(`number-${i}`, i + 1, i))
+ : [];
+ rowsLayer.push(...beforeNumbers, ...beforeNodes);
+
+ // ── Typing ────────────────────────────────────────────────────────
+ const keystrokes: Array<{ frame: number; line: number }> = [];
+ const lineCues: Array<{ frame: number; line: number }> = before.map(
+ (_, i) => ({ frame: 0, line: i + 1 }),
+ );
+ let end = 0;
+ if (props.typing !== false) {
+ const o = props.typing === true ? {} : props.typing;
+ const r = ctx.rng("typing");
+ let t = o.at ?? 0;
+ const caretKeys: { x: KeyframeTuple[]; y: KeyframeTuple[] } = {
+ x: [],
+ y: [],
+ };
+ before.forEach((text, i) => {
+ const indent = text.length - text.trimStart().length;
+ const node = beforeNodes[i] as Animatable<LayoutNode>;
+ const number = beforeNumbers[i];
+ lineCues[i] = { frame: Math.round(t), line: i + 1 };
+ if (number) fade(number, 0).to(Math.round(t), Math.round(t), 1);
+ caretKeys.x.push([Math.round(t), textX + indent * adv, "hold"]);
+ caretKeys.y.push([Math.round(t), rowY(i), "hold"]);
+ // Indentation appears with the line (editors auto-indent).
+ const typed = text.slice(indent);
+ const frames = typed
+ ? typingFrames(typed, o.cps ?? 28, fps, r, Math.round(t))
+ : [];
+ const count = (c: number) =>
+ text.length > 1 && c <= 1 ? c / text.length : c;
+ const keys: KeyframeTuple[] = [[0, 0]];
+ if (indent > 0 || !typed)
+ keys.push([
+ Math.round(t),
+ count(Math.max(indent, typed ? indent : 1)),
+ "hold",
+ ]);
+ frames.forEach((f, k) => {
+ keys.push([f, count(indent + k + 1), "hold"]);
+ keystrokes.push({ frame: f, line: i + 1 });
+ caretKeys.x.push([f, textX + (indent + k + 1) * adv, "hold"]);
+ caretKeys.y.push([f, rowY(i), "hold"]);
+ });
+ animOf(node).keys("text" as AnimatableProp, ascending(keys));
+ t = (frames[frames.length - 1] ?? t) + Math.round(fps * 0.18);
+ });
+ end = Math.round(t);
+ const caret = host.box({
+ id: ctx.partId("caret"),
+ position: "absolute",
+ x: textX,
+ y: rowY(0),
+ width: Math.max(2, fs * 0.09),
+ height: lh,
+ background: theme.color.accent,
+ });
+ const half = Math.max(1, Math.round(fps * 0.5));
+ const blink: KeyframeTuple[] = [[0, 1]];
+ for (
+ let f = end + half, on = false;
+ f < end + half * 6;
+ f += half, on = !on
+ )
+ blink.push([f, on ? 1 : 0, "hold"]);
+ blink.push([end + half * 6, 0, "hold"]);
+ caret.animate(
+ LayerAnimation.create()
+ .keys("x", ascending(caretKeys.x))
+ .keys("y", ascending(caretKeys.y))
+ .keys("opacity", blink),
+ );
+ parts.caret = caret;
+ rowsLayer.push(caret);
+ }
+
+ // ── Diff ──────────────────────────────────────────────────────────
+ const diffCue: Array<{ frame: number; end: number }> = [];
+ let afterNodes: LayoutNode[] = beforeNodes;
+ if (props.diff && after && afterTokens) {
+ const T = props.diff.at;
+ const D =
+ props.diff.duration ??
+ Math.round(themeFrames(theme, "slow", fps) * 1.2);
+ const move = theme.motion.ease.move;
+ const plan = diffLines(before, after);
+ afterNodes = new Array<LayoutNode>(after.length);
+ const wash = (
+ id: string,
+ row: number,
+ color: string,
+ from: number,
+ to: number,
+ ) => {
+ const box = host.box({
+ id: ctx.partId(id),
+ position: "absolute",
+ x: pad * 0.4,
+ y: rowY(row),
+ width: W - pad * 0.8,
+ height: lh,
+ background: tint(color, 0.22),
+ borderRadius: theme.radius.sm,
+ });
+ fade(box, 0)
+ .to(from, from + 4, 1)
+ .to(to - 10, to, 0, "power2.in");
+ washes.push(box);
+ };
+ for (const [i, j] of plan.kept) {
+ const node = beforeNodes[i] as Animatable<LayoutNode>;
+ let moving: LayoutNode = node;
+ if ((before[i] as string) !== (after[j] as string)) {
+ // Re-indented: the new text takes over as it starts to move.
+ const next = lineNode(
+ `line-${i}-to-${j}`,
+ afterTokens[j] ?? [],
+ after[j] as string,
+ i,
+ );
+ fade(next, 0).to(T, T, 1);
+ fade(node).to(T, T, 0);
+ rowsLayer.push(next);
+ moving = next;
+ }
+ if (i !== j)
+ animOf(moving).keys("y", [
+ [T, rowY(i)],
+ [T + D, rowY(j), move],
+ ]);
+ afterNodes[j] = moving;
+ }
+ for (const i of plan.removed) {
+ const node = beforeNodes[i] as LayoutNode;
+ fade(node).to(T, T + Math.round(D * 0.38), 0, "power2.in");
+ animOf(node).keys("x", [
+ [T, textX],
+ [T + Math.round(D * 0.38), textX - fs * 0.6, "power2.in"],
+ ]);
+ wash(
+ `wash-removed-${i}`,
+ i,
+ theme.color.negative,
+ T,
+ T + Math.round(D * 0.6),
+ );
+ }
+ for (const j of plan.added) {
+ const node = lineNode(
+ `added-${j}`,
+ afterTokens[j] ?? [],
+ after[j] as string,
+ j,
+ );
+ const from = T + Math.round(D * 0.48);
+ fade(node, 0).to(from, T + D, 1);
+ animOf(node).keys("x", [
+ [from, textX + fs * 0.8],
+ [T + D, textX, theme.motion.ease.enter],
+ ]);
+ wash(
+ `wash-added-${j}`,
+ j,
+ theme.color.positive,
+ from,
+ T + D + Math.round(fps * 0.8),
+ );
+ rowsLayer.push(node);
+ afterNodes[j] = node;
+ }
+ if (props.lineNumbers) {
+ for (const n of beforeNumbers) fade(n).to(T, T + 6, 0);
+ after.forEach((_, j) => {
+ const n = numberNode(`number-after-${j}`, j + 1, j);
+ fade(n, 0).to(T + Math.round(D * 0.5), T + D, 1);
+ rowsLayer.push(n);
+ });
+ }
+ diffCue.push({ frame: T, end: T + D });
+ end = Math.max(end, T + D + Math.round(fps * 0.8));
+ }
+
+ // ── Focus ─────────────────────────────────────────────────────────
+ const focusCues: Array<{ frame: number; lines: number[] }> = [];
+ const band = host.box({
+ id: ctx.partId("band"),
+ position: "absolute",
+ x: pad * 0.4,
+ y: rowY(0),
+ width: W - pad * 0.8,
+ height: lh,
+ background: tint(theme.color.accent, 0.14),
+ borderRadius: theme.radius.sm,
+ });
+ const bandY = new Track(rowY(0));
+ const bandH = new Track(lh);
+ const bandOn = new Track(0);
+ const glide = Math.max(4, themeFrames(theme, "base", fps) / 2);
+ for (const step of [...props.focus].sort((a, b) => a.at - b.at)) {
+ const afterDiff = props.diff !== undefined && step.at >= props.diff.at;
+ const nodes = afterDiff ? afterNodes : beforeNodes;
+ const set = focusSet(step.lines, nodes.length);
+ const f = step.at;
+ nodes.forEach((node, i) => {
+ fade(node).to(f, f + glide, set.size === 0 || set.has(i) ? 1 : 0.32);
+ });
+ if (set.size > 0) {
+ const lo = Math.min(...set);
+ const hi = Math.max(...set);
+ bandY.to(f, f + glide, rowY(lo) - lh * 0.1, theme.motion.ease.move);
+ bandH.to(
+ f,
+ f + glide,
+ (hi - lo + 1) * lh + lh * 0.2,
+ theme.motion.ease.move,
+ );
+ bandOn.to(f, f + glide, 1);
+ } else bandOn.to(f, f + glide, 0);
+ focusCues.push({ frame: f, lines: [...set].map((i) => i + 1) });
+ end = Math.max(end, f + glide);
+ }
+ band.animate(
+ LayerAnimation.create()
+ .keys("y", bandY.keys())
+ .keys("height", bandH.keys())
+ .keys("opacity", bandOn.keys()),
+ );
+ parts.band = band;
+
+ for (const [node, track] of opacity)
+ animOf(node).keys("opacity", track.keys());
+ for (const [node, anim] of animations)
+ (node as Animatable<LayoutNode>).animate(anim);
+
+ const inner = host.box({
+ id: ctx.partId("code"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ overflow: "hidden",
+ ...(props.frame === false && {
+ background: theme.color.surface,
+ borderRadius: theme.radius.lg,
+ }),
+ children: [band, ...washes, ...rowsLayer],
+ });
+ parts.code = inner;
+
+ let root: LayoutNode = inner;
+ let height = H;
+ if (props.frame !== false) {
+ const o = props.frame === true ? {} : props.frame;
+ const bar = 46 * s;
+ const frameNode = bind(
+ host,
+ appFrame,
+ )({
+ id: ctx.partId("window"),
+ kind: "window",
+ width: W,
+ height: H + bar,
+ content: [inner],
+ contentBackground: theme.color.surface,
+ enter: false,
+ theme,
+ ...(o.title !== undefined && { title: o.title }),
+ });
+ parts.window = frameNode;
+ root = frameNode;
+ height = H + bar;
+ }
+
+ return {
+ children: [root],
+ width: W,
+ height,
+ duration: Math.max(1, end),
+ openEnded: true,
+ cues: {
+ keystrokes,
+ lines: lineCues,
+ focus: focusCues,
+ diff: diffCue,
+ } as CodeBlockCues,
+ parts,
+ };
+ },
+});
+
+/** 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
new file mode 100644
index 00000000..3afbe436
--- /dev/null
+++ b/packages/components/src/code-block/meta.ts
@@ -0,0 +1,12 @@
+import { defineMeta } from "../core/meta.js";
+
+export default defineMeta({
+ name: "CodeBlock",
+ summary:
+ "Code that reads like an editor and moves like an explanation: syntax colours, typing, a focus band that walks the lines, and diffs where kept lines glide to their new places.",
+ tags: ["code", "syntax", "diff", "developer", "tutorial", "typing"],
+ parts: ["code", "line-<n>", "number-<n>", "band", "caret", "window"],
+ cues: ["keystrokes", "lines", "focus", "diff"],
+ example: `CodeBlock({ code, lang: "ts", focus: [{ at: 60, lines: [3] }] })`,
+ since: "M4",
+});
diff --git a/packages/components/src/code-block/plan.test.ts b/packages/components/src/code-block/plan.test.ts
new file mode 100644
index 00000000..6fb0c67c
--- /dev/null
+++ b/packages/components/src/code-block/plan.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vitest";
+import { diffLines, expandTabs, focusSet, Track } from "./plan.js";
+
+describe("CodeBlock plan", () => {
+ it("keeps the longest common run of lines, ignoring indentation", () => {
+ const d = diffLines(["a", "b", "c", "d"], ["a", " c", "x", "d"]);
+ expect(d.kept).toEqual([
+ [0, 0],
+ [2, 1],
+ [3, 3],
+ ]);
+ expect(d.removed).toEqual([1]);
+ expect(d.added).toEqual([2]);
+ });
+
+ it("reads focus lines as a list or a range, 1-based, inside the code", () => {
+ expect([...focusSet([1, 3], 5)]).toEqual([0, 2]);
+ expect([...focusSet({ from: 2, to: 4 }, 5)]).toEqual([1, 2, 3]);
+ expect([...focusSet([9], 5)]).toEqual([]);
+ expect(expandTabs("\tx", 2)).toBe(" x");
+ });
+
+ it("builds ascending tracks from transitions", () => {
+ const keys = new Track(1).to(10, 16, 0.3).to(30, 30, 1).keys();
+ expect(keys).toEqual([
+ [0, 1],
+ [10, 1],
+ [16, 0.3, "power2.out"],
+ [30, 1, "hold"],
+ ]);
+ });
+});
diff --git a/packages/components/src/code-block/plan.ts b/packages/components/src/code-block/plan.ts
new file mode 100644
index 00000000..caa5759e
--- /dev/null
+++ b/packages/components/src/code-block/plan.ts
@@ -0,0 +1,122 @@
+/**
+ * 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));
+}
+
+export interface LineDiff {
+ /** [old index, new index] of lines that stay (in order). */
+ kept: Array<[number, number]>;
+ removed: number[];
+ added: number[];
+}
+
+/**
+ * Longest common subsequence on trimmed lines: re-indented lines count as
+ * kept, so they glide instead of being deleted and re-added.
+ */
+export function diffLines(
+ a: readonly string[],
+ b: readonly string[],
+): LineDiff {
+ const A = a.map((l) => l.trim());
+ const B = b.map((l) => l.trim());
+ const n = A.length;
+ const m = B.length;
+ const lcs = Array.from({ length: n + 1 }, () =>
+ new Array<number>(m + 1).fill(0),
+ );
+ for (let i = n - 1; i >= 0; i--)
+ for (let j = m - 1; j >= 0; j--)
+ (lcs[i] as number[])[j] =
+ A[i] === B[j]
+ ? ((lcs[i + 1] as number[])[j + 1] as number) + 1
+ : Math.max(
+ (lcs[i + 1] as number[])[j] as number,
+ (lcs[i] as number[])[j + 1] as number,
+ );
+ const kept: Array<[number, number]> = [];
+ let i = 0;
+ let j = 0;
+ while (i < n && j < m) {
+ if (A[i] === B[j]) {
+ kept.push([i, j]);
+ i++;
+ j++;
+ } else if (
+ ((lcs[i + 1] as number[])[j] as number) >=
+ ((lcs[i] as number[])[j + 1] as number)
+ )
+ i++;
+ else j++;
+ }
+ const keptA = new Set(kept.map(([x]) => x));
+ const keptB = new Set(kept.map(([, y]) => y));
+ return {
+ kept,
+ removed: a.map((_, k) => k).filter((k) => !keptA.has(k)),
+ added: b.map((_, k) => k).filter((k) => !keptB.has(k)),
+ };
+}
+
+/** 1-based lines, as a list or `{ from, to }` → 0-based indices inside the code. */
+export function focusSet(
+ lines: readonly number[] | { from: number; to: number },
+ count: number,
+): Set<number> {
+ const list =
+ "from" in lines
+ ? Array.from(
+ { length: Math.max(0, lines.to - lines.from + 1) },
+ (_, k) => lines.from + k,
+ )
+ : 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/code-block/tokenize.test.ts b/packages/components/src/code-block/tokenize.test.ts
new file mode 100644
index 00000000..a6429b16
--- /dev/null
+++ b/packages/components/src/code-block/tokenize.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from "vitest";
+import { type Token, tokenize } from "./tokenize.js";
+
+const kinds = (line: Token[] | undefined) =>
+ (line ?? []).filter((t) => t.text.trim()).map((t) => [t.text.trim(), t.kind]);
+
+describe("tokenizer", () => {
+ it("ts: keywords, calls, types, strings, numbers, comments", () => {
+ const [line] = tokenize(
+ "const comp = new Composition({ fps: 30 }); // go",
+ "ts",
+ );
+ expect(kinds(line)).toEqual([
+ ["const", "keyword"],
+ ["comp", "plain"],
+ ["=", "operator"],
+ ["new", "keyword"],
+ ["Composition", "function"],
+ ["({", "punctuation"],
+ ["fps", "plain"],
+ [":", "punctuation"],
+ ["30", "number"],
+ ["});", "punctuation"],
+ ["// go", "comment"],
+ ]);
+ expect(kinds(tokenize('x.render("a")', "ts")[0])).toContainEqual([
+ "render",
+ "function",
+ ]);
+ expect(kinds(tokenize("a.b", "ts")[0])).toContainEqual(["b", "property"]);
+ });
+
+ it("carries block comments and template strings across lines", () => {
+ const lines = tokenize("/* one\ntwo */ x\nconst s = `a\nb`;", "ts");
+ expect(kinds(lines[1])[0]).toEqual(["two */", "comment"]);
+ expect(kinds(lines[1])[1]).toEqual(["x", "plain"]);
+ expect(kinds(lines[3])[0]).toEqual(["b`", "string"]);
+ });
+
+ it("json keys are properties, values are strings / numbers / keywords", () => {
+ expect(
+ kinds(tokenize('{ "a": "b", "n": 2, "t": true }', "json")[0]),
+ ).toEqual([
+ ["{", "punctuation"],
+ ['"a"', "property"],
+ [":", "punctuation"],
+ ['"b"', "string"],
+ [",", "punctuation"],
+ ['"n"', "property"],
+ [":", "punctuation"],
+ ["2", "number"],
+ [",", "punctuation"],
+ ['"t"', "property"],
+ [":", "punctuation"],
+ ["true", "keyword"],
+ ["}", "punctuation"],
+ ]);
+ });
+
+ it("bash: programs, flags, variables", () => {
+ expect(
+ kinds(tokenize('pnpm add -D framefields | grep "x" # note', "bash")[0]),
+ ).toEqual([
+ ["pnpm", "function"],
+ ["add", "plain"],
+ ["-D", "property"],
+ ["framefields", "plain"],
+ ["|", "operator"],
+ ["grep", "function"],
+ ['"x"', "string"],
+ ["# note", "comment"],
+ ]);
+ expect(kinds(tokenize("echo $HOME", "bash")[0])).toEqual([
+ ["echo", "keyword"],
+ ["$HOME", "type"],
+ ]);
+ });
+
+ it("python and css", () => {
+ expect(
+ kinds(tokenize('def go(x): return f"{x}" # hi', "python")[0]),
+ ).toEqual([
+ ["def", "keyword"],
+ ["go", "function"],
+ ["(", "punctuation"],
+ ["x", "plain"],
+ ["):", "punctuation"],
+ ["return", "keyword"],
+ ['f"{x}"', "string"],
+ ["# hi", "comment"],
+ ]);
+ expect(
+ kinds(tokenize(".a { color: #fff; margin: 4px }", "css")[0]),
+ ).toContainEqual(["color", "property"]);
+ expect(
+ kinds(tokenize(".a { color: #fff; margin: 4px }", "css")[0]),
+ ).toContainEqual(["#fff", "number"]);
+ });
+});
diff --git a/packages/components/src/code-block/tokenize.ts b/packages/components/src/code-block/tokenize.ts
new file mode 100644
index 00000000..f4cd3039
--- /dev/null
+++ b/packages/components/src/code-block/tokenize.ts
@@ -0,0 +1,239 @@
+/**
+ * A small syntax tokenizer for code on screen: enough to colour ts / js,
+ * json, bash, python and css the way an editor would. Anything else comes
+ * from the user's own highlighter through `tokens`.
+ */
+
+export const CODE_LANGS = [
+ "ts",
+ "js",
+ "json",
+ "bash",
+ "python",
+ "css",
+ "plain",
+] as const;
+export type CodeLang = (typeof CODE_LANGS)[number];
+
+export type TokenKind =
+ | "plain"
+ | "keyword"
+ | "string"
+ | "number"
+ | "comment"
+ | "function"
+ | "type"
+ | "property"
+ | "punctuation"
+ | "operator";
+
+export interface Token {
+ text: string;
+ kind?: TokenKind;
+ /** An explicit colour wins over `kind`. */
+ color?: string;
+}
+
+const words = (list: string) => new Set(list.split(/\s+/));
+
+let keywordSets: Record<CodeLang, Set<string>> | undefined;
+
+/** Keyword sets, built on first use (never at import: that would ship to every bundle). */
+function keywords(lang: CodeLang): Set<string> {
+ keywordSets ??= buildKeywords();
+ return keywordSets[lang];
+}
+
+const buildKeywords = (): Record<CodeLang, Set<string>> => ({
+ ts: words(
+ "const let var function return if else for while do switch case break continue new class extends import from export default async await try catch finally throw typeof instanceof in of interface type enum implements public private protected readonly static as satisfies keyof declare true false null undefined this void yield",
+ ),
+ js: words(
+ "const let var function return if else for while do switch case break continue new class extends import from export default async await try catch finally throw typeof instanceof in of static true false null undefined this void yield",
+ ),
+ python: words(
+ "def class return if elif else for while in not and or import from as with try except finally raise lambda pass break continue None True False self yield async await is global nonlocal",
+ ),
+ bash: words(
+ "if then else elif fi for do done case esac function export return in while until local echo cd source exit set unset",
+ ),
+ json: words("true false null"),
+ css: words("important"),
+ plain: new Set(),
+});
+
+interface Rule {
+ re: RegExp;
+ kind:
+ | TokenKind
+ | ((match: string, rest: string, before: string) => TokenKind);
+}
+
+const C_LIKE: Rule[] = [
+ { re: /\/\/.*/y, kind: "comment" },
+ { re: /\/\*.*?(\*\/|$)/y, kind: "comment" },
+ { re: /`(?:[^`\\]|\\.)*(`|$)/y, kind: "string" },
+ { re: /"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?/y, kind: "string" },
+ {
+ re: /\b\d[\d_]*(\.\d+)?([eE][+-]?\d+)?n?\b|\b0x[\da-fA-F]+\b/y,
+ kind: "number",
+ },
+];
+
+/** Identifier kinds shared by most languages. */
+function ident(lang: CodeLang) {
+ return (word: string, rest: string, before: string): TokenKind => {
+ if (keywords(lang).has(word)) return "keyword";
+ if (/^\s*\(/.test(rest)) return "function";
+ if (/^[A-Z]/.test(word)) return "type";
+ if (/\.\s*$/.test(before)) return "property";
+ return "plain";
+ };
+}
+
+function rulesFor(lang: CodeLang): Rule[] {
+ const id = { re: /[A-Za-z_$][\w$]*/y, kind: ident(lang) };
+ const punct = { re: /[{}()[\];,.:]/y, kind: "punctuation" as const };
+ const op = { re: /[=+\-*/%<>!&|?^~@]+/y, kind: "operator" as const };
+ switch (lang) {
+ case "ts":
+ case "js":
+ return [...C_LIKE, id, punct, op];
+ case "json":
+ return [
+ {
+ re: /"(?:[^"\\]|\\.)*"/y,
+ kind: (_m, rest) => (/^\s*:/.test(rest) ? "property" : "string"),
+ },
+ C_LIKE[4] as Rule,
+ id,
+ punct,
+ ];
+ case "python":
+ return [
+ { re: /#.*/y, kind: "comment" },
+ { re: /("""|''').*?(\1|$)/y, kind: "string" },
+ {
+ re: /[rbfRBF]?("(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?)/y,
+ kind: "string",
+ },
+ C_LIKE[4] as Rule,
+ { re: /@[\w.]+/y, kind: "function" },
+ id,
+ punct,
+ op,
+ ];
+ case "bash":
+ return [
+ { re: /#.*/y, kind: "comment" },
+ { re: /"(?:[^"\\]|\\.)*"?|'[^']*'?/y, kind: "string" },
+ { re: /\$\{?[\w@#?*]+\}?/y, kind: "type" },
+ { re: /--?[\w-]+/y, kind: "property" },
+ { re: /\b\d+\b/y, kind: "number" },
+ {
+ re: /[A-Za-z_][\w./-]*/y,
+ // The first word of a command is the program.
+ kind: (word, _rest, before) => {
+ if (keywords("bash").has(word)) return "keyword";
+ const b = before.trimEnd();
+ return b === "" || /[|;&(]$/.test(b) ? "function" : "plain";
+ },
+ },
+ { re: /[|&;<>()=]+/y, kind: "operator" },
+ ];
+ case "css":
+ return [
+ { re: /\/\*.*?(\*\/|$)/y, kind: "comment" },
+ { re: /"[^"]*"?|'[^']*'?/y, kind: "string" },
+ { re: /@[\w-]+/y, kind: "keyword" },
+ { re: /#[\da-fA-F]{3,8}\b/y, kind: "number" },
+ { re: /-?\d*\.?\d+(px|em|rem|%|vh|vw|s|ms|deg|fr)?/y, kind: "number" },
+ {
+ re: /[\w-]+/y,
+ kind: (_w, rest) =>
+ /^\s*:(?!:)/.test(rest)
+ ? "property"
+ : /^\s*\(/.test(rest)
+ ? "function"
+ : "plain",
+ },
+ { re: /[{}();:,>+~]/y, kind: "punctuation" },
+ ];
+ case "plain":
+ return [];
+ }
+}
+
+/**
+ * Tokens per line. Block comments, template literals and triple-quoted
+ * strings carry across lines.
+ */
+export function tokenize(code: string, lang: CodeLang): Token[][] {
+ const lines = code.split("\n");
+ if (lang === "plain") return lines.map((l) => (l ? [{ text: l }] : []));
+ const rules = rulesFor(lang);
+ /** The closing delimiter of a construct still open from a previous line. */
+ let open: { close: RegExp; kind: TokenKind } | null = null;
+
+ return lines.map((line) => {
+ const out: Token[] = [];
+ const push = (text: string, kind: TokenKind) => {
+ const last = out[out.length - 1];
+ if (last && last.kind === kind) last.text += text;
+ else out.push({ text, kind });
+ };
+ let i = 0;
+ if (open) {
+ const m = open.close.exec(line);
+ const end = m ? m.index + m[0].length : line.length;
+ push(line.slice(0, end), open.kind);
+ i = end;
+ if (m) open = null;
+ }
+ while (i < line.length) {
+ const ws = /\s+/y;
+ ws.lastIndex = i;
+ const space = ws.exec(line);
+ if (space) {
+ push(space[0], "plain");
+ i += space[0].length;
+ continue;
+ }
+ let matched = false;
+ for (const rule of rules) {
+ rule.re.lastIndex = i;
+ const m = rule.re.exec(line);
+ if (!m || m[0].length === 0) continue;
+ const text = m[0];
+ const kind =
+ typeof rule.kind === "function"
+ ? rule.kind(text, line.slice(i + text.length), line.slice(0, i))
+ : rule.kind;
+ push(text, kind);
+ // A construct that runs off the end of the line continues on the next.
+ if (kind === "comment" && text.startsWith("/*") && !text.endsWith("*/"))
+ open = { close: /\*\//, kind };
+ else if (
+ kind === "string" &&
+ text.startsWith("`") &&
+ (text.length === 1 || !text.endsWith("`"))
+ )
+ open = { close: /(?<!\\)`/, kind };
+ else if (
+ kind === "string" &&
+ /^("""|''')/.test(text) &&
+ (text.length < 6 || !text.endsWith(text.slice(0, 3)))
+ )
+ open = { close: new RegExp(text.slice(0, 3)), kind };
+ i += text.length;
+ matched = true;
+ break;
+ }
+ if (!matched) {
+ push(line[i] as string, "plain");
+ i++;
+ }
+ }
+ return out;
+ });
+}
diff --git a/packages/components/src/ids.test.ts b/packages/components/src/ids.test.ts
new file mode 100644
index 00000000..ed47cb14
--- /dev/null
+++ b/packages/components/src/ids.test.ts
@@ -0,0 +1,223 @@
+import { describe, expect, it } from "vitest";
+import { annotate } from "./annotate/index.js";
+import { appFrame } from "./app-frame/index.js";
+import { captions } from "./captions/index.js";
+import { codeBlock } from "./code-block/index.js";
+import { bind } from "./core/contract.js";
+import { counter } from "./counter/index.js";
+import { focusZoom } from "./focus-zoom/index.js";
+import { lowerThird } from "./lower-third/index.js";
+import { meter } from "./meter/index.js";
+import { mousePointer } from "./mouse-pointer/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";
+
+/**
+ * The renderer keys layout and motion by node id: two nodes with one id
+ * share geometry and keyframes. No component may emit a duplicate.
+ */
+function ids(node: unknown, out: string[] = []): string[] {
+ const n = node as {
+ id?: string;
+ children?: unknown[];
+ matte?: { node: unknown };
+ };
+ if (n.id) out.push(n.id);
+ for (const c of n.children ?? []) ids(c, out);
+ 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],
+ ),
+];
+
+describe("node ids", () => {
+ for (const [name, build] of cases)
+ it(`${name} emits unique ids`, () => {
+ const list = ids(build());
+ const dupes = list.filter((id, i) => list.indexOf(id) !== i);
+ expect(dupes).toEqual([]);
+ });
+});
diff --git a/packages/components/src/index.ts b/packages/components/src/index.ts
index 04af8b5d..026ec0d2 100644
--- a/packages/components/src/index.ts
+++ b/packages/components/src/index.ts
@@ -23,6 +23,15 @@ export {
captions,
type Word,
} from "./captions/index.js";
+export {
+ CODE_LANGS,
+ type CodeBlockCues,
+ type CodeLang,
+ codeBlock,
+ type Token,
+ type TokenKind,
+} from "./code-block/index.js";
+export { tokenize } from "./code-block/tokenize.js";
export {
type BakedKey,
type BakeOptions,
@@ -164,6 +173,18 @@ export {
type Followable,
focusZoom,
} from "./focus-zoom/index.js";
+export {
+ LOWER_THIRD_LAYOUTS,
+ type LowerThirdCues,
+ type LowerThirdLayout,
+ lowerThird,
+} from "./lower-third/index.js";
+export {
+ METER_KINDS,
+ type MeterCues,
+ type MeterKind,
+ meter,
+} from "./meter/index.js";
export {
CURSOR_STYLES,
type CursorStyle,
@@ -186,3 +207,9 @@ export {
type TextRevealCues,
textReveal,
} from "./text-reveal/index.js";
+export {
+ TITLE_LAYOUTS,
+ type TitleCardCues,
+ type TitleLayout,
+ titleCard,
+} from "./title-card/index.js";
diff --git a/packages/components/src/lower-third/index.test.ts b/packages/components/src/lower-third/index.test.ts
new file mode 100644
index 00000000..3ec73489
--- /dev/null
+++ b/packages/components/src/lower-third/index.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest";
+import { bind } from "../core/contract.js";
+import { fakeHost } from "../test/fake-host.js";
+import { lowerThird } from "./index.js";
+
+const make = () => bind(fakeHost(), lowerThird);
+type Node = {
+ id?: string;
+ x?: number;
+ y?: number;
+ width?: number;
+ children?: Node[];
+};
+const find = (n: unknown, id: string): Node | undefined => {
+ const node = n as Node;
+ if (node.id === id) return node;
+ for (const c of node.children ?? []) {
+ const hit = find(c, id);
+ if (hit) return hit;
+ }
+ return undefined;
+};
+
+describe("LowerThird", () => {
+ it("measures the plate to the text plus padding", () => {
+ // Fake measure: 0.5 em per glyph. Name 44 px → 22 px a glyph.
+ const short = find(make()({ id: "l", name: "Ada" }), "l-plate");
+ const long = find(make()({ id: "l", name: "Ada Lovelace" }), "l-plate");
+ expect((long?.width ?? 0) - (short?.width ?? 0)).toBeCloseTo(9 * 22, 5);
+ });
+
+ it("sits on the safe area's right edge on the right side", () => {
+ const plate = find(
+ make()({ id: "l", name: "Ada", role: "Engineer", side: "right" }),
+ "l-plate",
+ );
+ expect((plate?.x ?? 0) + (plate?.width ?? 0)).toBeCloseTo(1920 * 0.94, 5);
+ });
+
+ it("leaves on its own after the hold, or stays", () => {
+ const l = make()({ name: "Ada", hold: 30 });
+ const inAt = l.cues.in[0]?.frame ?? 0;
+ expect(l.cues.out[0]?.frame).toBe(inAt + 30);
+ expect(l.span.duration).toBeGreaterThan(inAt + 30);
+ const stays = make()({ name: "Ada", stay: true });
+ expect(stays.span.end).toBe(Number.POSITIVE_INFINITY);
+ expect(stays.cues.out).toEqual([]);
+ });
+});
diff --git a/packages/components/src/lower-third/index.ts b/packages/components/src/lower-third/index.ts
new file mode 100644
index 00000000..3c6c428b
--- /dev/null
+++ b/packages/components/src/lower-third/index.ts
@@ -0,0 +1,463 @@
+/**
+ * LowerThird: the name-and-role bar of interviews and talks. Plates are
+ * measured to their text, placed in the safe area's bottom corner, slide in
+ * 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.
+ */
+import {
+ type KeyframeTuple,
+ LayerAnimation,
+ type LayoutNode,
+} from "@framefields/compositions/program";
+import { z } from "zod";
+import { defineComponent } from "../core/contract.js";
+import type { Rect } from "../core/draw.js";
+import type { Animatable } from "../core/host.js";
+import { themeFrames } from "../core/theme.js";
+
+export const LOWER_THIRD_LAYOUTS = ["bar", "stacked", "tag", "line"] as const;
+export type LowerThirdLayout = (typeof LOWER_THIRD_LAYOUTS)[number];
+
+export interface LowerThirdCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ /** Fully on screen. */
+ in: ReadonlyArray<{ frame: number }>;
+ /** Starts to leave (empty with `stay`). */
+ 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: () => ({
+ name: z.string().min(1),
+ role: z.string().optional(),
+ layout: z.enum(LOWER_THIRD_LAYOUTS).default("bar"),
+ side: z.enum(["left", "right"]).default("left"),
+ safeArea: z
+ .union([
+ z.enum(["portrait", "landscape"]),
+ z.object({
+ x: z.number(),
+ y: z.number(),
+ width: z.number(),
+ height: z.number(),
+ }),
+ ])
+ .optional(),
+ /** Stay on screen instead of leaving after `hold`. */
+ stay: z.boolean().default(false),
+ accent: z.string().optional(),
+ plate: z.string().optional(),
+ nameSize: z.number().positive().optional(),
+ fontFamily: z.string().optional(),
+ }),
+ defaults: { enter: false, exit: false, hold: 90 },
+ 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 fontFamily = props.fontFamily ?? theme.font.display;
+ const nameSize = props.nameSize ?? 44 * s;
+ const roleSize = nameSize * 0.62;
+ const accent = props.accent ?? theme.color.accent;
+ const plateColor = props.plate ?? theme.color.surface;
+ const right = props.side === "right";
+ const base = themeFrames(theme, "base", fps);
+ const fast = themeFrames(theme, "fast", fps);
+ const enter = theme.motion.ease.enter;
+
+ const nameM = host.measure(props.name, {
+ fontFamily,
+ fontSize: nameSize,
+ fontWeight: 700,
+ });
+ const roleM = props.role
+ ? host.measure(props.role, {
+ fontFamily,
+ fontSize: roleSize,
+ fontWeight: 500,
+ })
+ : null;
+ const padX = nameSize * 0.55;
+ const padY = nameSize * 0.36;
+ 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 text = (
+ id: string,
+ content: string,
+ size: number,
+ weight: number,
+ fill: string,
+ x: number,
+ y: number,
+ ) =>
+ host.text(content, {
+ id: ctx.partId(id),
+ position: "absolute",
+ x,
+ y,
+ fontFamily,
+ fontSize: size,
+ fontWeight: weight,
+ fill,
+ });
+
+ /**
+ * A plate that slides in through its own box: the background travels
+ * in from the side, its text rises a beat later. Returns the timing.
+ */
+ const plate = (
+ id: string,
+ rect: Rect,
+ background: string,
+ radius: number,
+ content: Array<Animatable<LayoutNode>>,
+ at: number,
+ ) => {
+ const fill = host.box({
+ id: ctx.partId(`${id}-fill`),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: rect.width,
+ height: rect.height,
+ background,
+ borderRadius: radius,
+ });
+ const travel = rect.width * (right ? 1 : -1);
+ const slide = Math.round(base * 1.1);
+ key(fill, "x", [
+ [at, travel],
+ [at + slide, 0, enter],
+ ]);
+ const textAt = at + Math.round(fast * 0.7);
+ for (const node of content) {
+ const y0 = (node as unknown as { y: number }).y;
+ key(node, "y", [
+ [textAt, y0 + rect.height * 0.5],
+ [textAt + base, y0, enter],
+ ]);
+ key(node, "opacity", [
+ [textAt, 0],
+ [textAt + Math.round(base * 0.6), 1, "power2.out"],
+ ]);
+ }
+ const clip = host.box({
+ id: ctx.partId(id),
+ position: "absolute",
+ ...rect,
+ overflow: "hidden",
+ borderRadius: radius,
+ children: [fill, ...content],
+ });
+ children.push(clip);
+ parts[id] = clip;
+ return {
+ clip,
+ fill,
+ content,
+ travel,
+ settled: Math.max(at + slide, textAt + base),
+ };
+ };
+
+ // ── Layouts ───────────────────────────────────────────────────────
+ const bottom = safe.y + safe.height;
+ const xFor = (width: number) =>
+ right ? safe.x + safe.width - width : safe.x;
+ const plates: Array<ReturnType<typeof plate>> = [];
+ let accentLine: Animatable<LayoutNode> | null = null;
+ const lineW = Math.max(3, nameSize * 0.09);
+
+ switch (props.layout) {
+ case "bar": {
+ const edge = Math.max(4, nameSize * 0.14);
+ const innerW = Math.max(nameM.width, roleM?.width ?? 0);
+ const h = padY * 2 + nameM.height + (roleM ? roleM.height * 0.95 : 0);
+ const w = innerW + padX * 2 + edge;
+ 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),
+ ];
+ if (props.role && roleM)
+ content.push(
+ text(
+ "role",
+ props.role,
+ roleSize,
+ 500,
+ theme.color.muted,
+ tx,
+ padY + nameM.height * 0.95,
+ ),
+ );
+ const p = plate("plate", rect, plateColor, theme.radius.sm, content, 0);
+ const strip = host.box({
+ id: ctx.partId("edge"),
+ position: "absolute",
+ x: right ? rect.x + rect.width - edge : rect.x,
+ y: rect.y + rect.height,
+ width: edge,
+ height: 0,
+ background: accent,
+ borderRadius: theme.radius.sm,
+ });
+ const grow = Math.round(base * 0.8);
+ key(strip, "height", [
+ [0, 0],
+ [grow, rect.height, enter],
+ ]);
+ key(strip, "y", [
+ [0, rect.y + rect.height],
+ [grow, rect.y, enter],
+ ]);
+ children.push(strip);
+ parts.edge = strip;
+ plates.push(p);
+ break;
+ }
+ case "stacked": {
+ const nameW = nameM.width + padX * 2;
+ const nameH = nameM.height + padY * 2;
+ const roleH = roleM ? roleM.height + padY * 1.2 : 0;
+ const roleW = roleM ? roleM.width + padX * 1.6 : 0;
+ const inset = nameSize * 0.4;
+ const total = nameH + (roleM ? roleH * 0.9 : 0);
+ const top = bottom - total;
+ plates.push(
+ plate(
+ "name-plate",
+ { x: xFor(nameW), y: top, width: nameW, height: nameH },
+ plateColor,
+ theme.radius.sm,
+ [
+ text(
+ "name",
+ props.name,
+ nameSize,
+ 700,
+ theme.color.ink,
+ padX,
+ padY,
+ ),
+ ],
+ 0,
+ ),
+ );
+ if (props.role && roleM)
+ plates.push(
+ plate(
+ "role-plate",
+ {
+ x: right ? xFor(roleW) - inset : xFor(roleW) + inset,
+ y: top + nameH - roleH * 0.1,
+ width: roleW,
+ height: roleH,
+ },
+ accent,
+ theme.radius.sm,
+ [
+ text(
+ "role",
+ props.role,
+ roleSize,
+ 600,
+ theme.color.bg,
+ padX * 0.8,
+ padY * 0.6,
+ ),
+ ],
+ Math.round(fast * 0.8),
+ ),
+ );
+ break;
+ }
+ case "tag": {
+ // One line, one node: bold name, a dot, the role a size down.
+ const sep = " · ";
+ const sepW = props.role
+ ? host.measure(sep, { fontFamily, fontSize: roleSize }).width
+ : 0;
+ const h = nameM.height + padY * 1.4;
+ const w = nameM.width + (roleM ? sepW + roleM.width : 0) + h;
+ const line = host.text(
+ props.role ? `${props.name}${sep}${props.role}` : props.name,
+ {
+ id: ctx.partId("name"),
+ position: "absolute",
+ x: h / 2,
+ y: padY * 0.7,
+ fontFamily,
+ fontSize: nameSize,
+ fill: theme.color.ink,
+ spans: [
+ { text: props.name, fontWeight: 700, fill: theme.color.ink },
+ ...(props.role
+ ? [
+ {
+ text: `${sep}${props.role}`,
+ fontSize: roleSize,
+ fontWeight: 500,
+ fill: theme.color.muted,
+ },
+ ]
+ : []),
+ ],
+ },
+ );
+ plates.push(
+ plate(
+ "tag",
+ { x: xFor(w), y: bottom - h, width: w, height: h },
+ plateColor,
+ theme.radius.pill,
+ [line],
+ 0,
+ ),
+ );
+ break;
+ }
+ case "line": {
+ const innerW = Math.max(nameM.width, roleM?.width ?? 0);
+ const h = nameM.height + (roleM ? roleM.height : 0);
+ const gap = nameSize * 0.4;
+ const w = innerW + gap + lineW;
+ const x = xFor(w);
+ const lineX = right ? x + w - lineW : x;
+ const tx = right ? 0 : lineW + gap;
+ accentLine = host.box({
+ id: ctx.partId("line"),
+ position: "absolute",
+ x: lineX,
+ y: bottom,
+ width: lineW,
+ height: 0,
+ background: accent,
+ borderRadius: lineW / 2,
+ });
+ const grow = Math.round(base * 1.1);
+ key(accentLine, "height", [
+ [0, 0],
+ [grow, h, enter],
+ ]);
+ key(accentLine, "y", [
+ [0, bottom],
+ [grow, bottom - h, enter],
+ ]);
+ children.push(accentLine);
+ parts.line = accentLine;
+ const content = [
+ text("name", props.name, nameSize, 700, theme.color.ink, tx, 0),
+ ];
+ if (props.role && roleM)
+ content.push(
+ text(
+ "role",
+ props.role,
+ roleSize,
+ 500,
+ theme.color.muted,
+ tx,
+ nameM.height,
+ ),
+ );
+ // No plate: the text rises through a clear box.
+ plates.push(
+ plate(
+ "text",
+ { x, y: bottom - h, width: w, height: h },
+ "rgba(0,0,0,0)",
+ 0,
+ content,
+ Math.round(fast * 0.6),
+ ),
+ );
+ break;
+ }
+ }
+
+ const settled = Math.max(...plates.map((p) => p.settled));
+ // ── Out: text first, then the plates slide back the way they came ──
+ let afterHold = 0;
+ const outAt = settled + ctx.hold;
+ if (!props.stay) {
+ const fadeOut = Math.round(fast * 0.9);
+ const slide = Math.round(base * 0.9);
+ plates.forEach((p, k) => {
+ const at = outAt + k * Math.round(fast * 0.4);
+ for (const node of p.content)
+ key(node, "opacity", [
+ [at, 1],
+ [at + fadeOut, 0, "power2.in"],
+ ]);
+ key(p.fill, "x", [
+ [at + fadeOut - 2, 0],
+ [at + fadeOut - 2 + slide, p.travel, theme.motion.ease.exit],
+ ]);
+ afterHold = Math.max(afterHold, at + fadeOut - 2 + slide - outAt);
+ });
+ for (const node of [accentLine, parts.edge])
+ if (node)
+ key(node, "opacity", [
+ [outAt, 1],
+ [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);
+ }
+
+ return {
+ children,
+ width: W,
+ height: H,
+ duration: settled,
+ openEnded: props.stay,
+ afterHold,
+ origin: [0, 0],
+ cues: {
+ in: [{ frame: settled }],
+ out: props.stay ? [] : [{ frame: outAt }],
+ } as LowerThirdCues,
+ parts,
+ };
+ },
+});
diff --git a/packages/components/src/lower-third/meta.ts b/packages/components/src/lower-third/meta.ts
new file mode 100644
index 00000000..51ee185c
--- /dev/null
+++ b/packages/components/src/lower-third/meta.ts
@@ -0,0 +1,12 @@
+import { defineMeta } from "../core/meta.js";
+
+export default defineMeta({
+ name: "LowerThird",
+ summary:
+ "The name-and-role bar of interviews and talks: measured plates in the safe area that slide in and leave on their own.",
+ tags: ["lower third", "name", "interview", "talk", "caption", "broadcast"],
+ parts: ["plate", "edge", "name-plate", "role-plate", "tag", "line", "text"],
+ cues: ["in", "out"],
+ example: `LowerThird({ name: "Ada Lovelace", role: "Engineer" })`,
+ since: "M4",
+});
diff --git a/packages/components/src/meter/index.test.ts b/packages/components/src/meter/index.test.ts
new file mode 100644
index 00000000..b1d4ab35
--- /dev/null
+++ b/packages/components/src/meter/index.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from "vitest";
+import { bind } from "../core/contract.js";
+import { fakeHost } from "../test/fake-host.js";
+import { meter } from "./index.js";
+
+const make = () => bind(fakeHost(), meter);
+type Node = {
+ id?: string;
+ children?: Node[];
+ animation?: {
+ tracks: Array<{
+ prop: string;
+ keyframes: Array<{
+ frame: number;
+ value: number;
+ ease?: { name: string };
+ }>;
+ }>;
+ };
+};
+const find = (n: unknown, id: string): Node | undefined => {
+ const node = n as Node;
+ if (node.id === id) return node;
+ for (const c of node.children ?? []) {
+ const hit = find(c, id);
+ if (hit) return hit;
+ }
+ return undefined;
+};
+const track = (n: Node | undefined, prop: string) =>
+ n?.animation?.tracks.find((t) => t.prop === prop)?.keyframes ?? [];
+
+describe("Meter", () => {
+ it("fills to (value − from) / (max − from) on the value's own keys", () => {
+ const m = make()({
+ id: "m",
+ values: [
+ [0, 0],
+ [30, 50, "power2.out"],
+ [60, 25],
+ ],
+ });
+ const keys = track(find(m, "m-fill"), "trimEnd");
+ expect(keys.map((k) => [k.frame, k.value])).toEqual([
+ [0, 0],
+ [30, 0.5],
+ [60, 0.25],
+ ]);
+ expect(keys[1]?.ease?.name).toBe("power2");
+ expect(find(m, "m-counter")).toBeDefined();
+ });
+
+ it("bars fill their width; segments light as the value crosses them", () => {
+ const bar = make()({
+ id: "m",
+ value: 40,
+ kind: "bar",
+ size: 500,
+ countDuration: 30,
+ });
+ expect(track(find(bar, "m-fill"), "width").map((k) => k.value)).toEqual([
+ 0, 200,
+ ]);
+ const seg = make()({
+ value: 35,
+ kind: "segments",
+ segments: 10,
+ countDuration: 30,
+ });
+ expect(seg.cues.crossings.map((c) => c.segment)).toEqual([0, 1, 2]);
+ });
+
+ it("fills 3.5 stars as three and a half", () => {
+ const m = make()({
+ id: "m",
+ value: 3.5,
+ kind: "stars",
+ size: 300,
+ countDuration: 30,
+ });
+ const width = (k: number) => {
+ const keys = track(find(m, `m-star-${k}-clip`), "width");
+ return keys[keys.length - 1]?.value ?? 0;
+ };
+ const cell = (300 - 300 * 0.03 * 4) / 5;
+ expect(width(2)).toBeCloseTo(cell, 3);
+ expect(width(3)).toBeCloseTo(cell / 2, 3);
+ expect(width(4)).toBe(0);
+ expect(m.cues.crossings).toHaveLength(3);
+ });
+
+ it("needs a value", () => {
+ expect(() => make()({})).toThrow(/give `value`/);
+ });
+});
diff --git a/packages/components/src/meter/index.ts b/packages/components/src/meter/index.ts
new file mode 100644
index 00000000..2a14e727
--- /dev/null
+++ b/packages/components/src/meter/index.ts
@@ -0,0 +1,435 @@
+/**
+ * Meter: progress and scores as a ring, an arc gauge, a bar, lit segments or
+ * a star rating, filling on the same value timeline as its `Counter`.
+ */
+import {
+ type KeyframeTuple,
+ LayerAnimation,
+ type LayoutNode,
+} from "@framefields/compositions/program";
+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 { toPathData, type Vec2 } from "../core/path.js";
+import { themeFrames } from "../core/theme.js";
+import { counter } from "../counter/index.js";
+import { type ValueKey, valueAt } from "../counter/plan.js";
+
+export const METER_KINDS = ["ring", "arc", "bar", "segments", "stars"] as const;
+export type MeterKind = (typeof METER_KINDS)[number];
+
+export interface MeterCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ /** The fill (and counter) is at rest. */
+ settled: ReadonlyArray<{ frame: number }>;
+ /** Each segment or star completing (fills only; empties are not cued). */
+ crossings: ReadonlyArray<{ frame: number; segment: number }>;
+}
+
+/** Points along a circular arc, angles in degrees (0 = right, clockwise). */
+function arcPoints(c: Vec2, r: number, from: number, to: number): Vec2[] {
+ const steps = Math.max(8, Math.ceil(Math.abs(to - from) / 6));
+ return Array.from({ length: steps + 1 }, (_, k) => {
+ const a = ((from + ((to - from) * k) / steps) * Math.PI) / 180;
+ return [c[0] + Math.cos(a) * r, c[1] + Math.sin(a) * r] as Vec2;
+ });
+}
+
+/** A five-point star inside a `size` box. */
+function starPath(size: number): string {
+ const c = size / 2;
+ const pts: Vec2[] = Array.from({ length: 10 }, (_, k) => {
+ const r = k % 2 === 0 ? size * 0.5 : size * 0.21;
+ const a = -Math.PI / 2 + (k * Math.PI) / 5;
+ return [c + Math.cos(a) * r, c + Math.sin(a) * r * 1.02 + size * 0.03];
+ });
+ return toPathData(pts, true);
+}
+
+export const meter = /* @__PURE__ */ defineComponent({
+ name: "Meter",
+ props: () => ({
+ value: z.number().optional(),
+ /** Multi-step values: `[frame, value, ease?]`, frames ascending. */
+ values: z
+ .array(
+ z.union([
+ z.tuple([z.number().int().min(0), z.number()]),
+ z.tuple([z.number().int().min(0), z.number(), z.string()]),
+ ]),
+ )
+ .min(1)
+ .optional(),
+ from: z.number().default(0),
+ /** Default 100 (5 for stars). */
+ max: z.number().optional(),
+ kind: z.enum(METER_KINDS).default("ring"),
+ /** Cells for `segments` (default 10), stars for `stars` (default `max`). */
+ segments: z.number().int().positive().optional(),
+ /** Width (bar, segments, stars) or diameter (ring, arc). */
+ size: z.number().positive().optional(),
+ thickness: z.number().positive().optional(),
+ counter: z.boolean().optional(),
+ format: z.string().default(",d"),
+ suffix: z.string().optional(),
+ label: z.string().optional(),
+ color: z.string().optional(),
+ track: z.string().optional(),
+ countDuration: z.number().int().positive().optional(),
+ ease: z.string().optional(),
+ fontFamily: z.string().optional(),
+ }),
+ defaults: { enter: false, exit: false },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const s = theme.scale;
+ const kind = props.kind;
+ const max = props.max ?? (kind === "stars" ? 5 : 100);
+ const from = props.from;
+ const ease = props.ease ?? theme.motion.ease.move;
+ const color = props.color ?? theme.color.accent;
+ const trackColor = props.track ?? theme.color.line;
+ const fontFamily = props.fontFamily ?? theme.font.display;
+ if (props.value === undefined && !props.values)
+ throw new Error("Meter: give `value` (or `values`).");
+ const keys: ValueKey[] = props.values
+ ? props.values.map((v) => [...v] as unknown as ValueKey)
+ : [
+ [0, from],
+ [
+ props.countDuration ?? themeFrames(theme, "slow", fps) * 2,
+ props.value as number,
+ ease,
+ ],
+ ];
+ const last = (keys[keys.length - 1] as ValueKey)[0];
+ const fraction = (v: number) =>
+ Math.max(0, Math.min(1, (v - from) / (max - from || 1)));
+ /** Keys of `f(fraction)`, on exactly the value's keyframes and eases. */
+ const fillKeys = (f: (x: number) => number): KeyframeTuple[] =>
+ keys.map((k, i) =>
+ i === 0
+ ? [k[0], f(fraction(k[1]))]
+ : [k[0], f(fraction(k[1])), k[2] ?? ease],
+ );
+ const perFrame = Array.from({ length: last + 1 }, (_, t) =>
+ valueAt(keys, t, ease),
+ );
+
+ const showCounter = props.counter ?? kind !== "stars";
+ const suffix = props.suffix ?? (max === 100 ? "%" : "");
+ const makeCounter = bind(host, counter);
+ const number = (size: number, align: "start" | "center" | "end") =>
+ makeCounter({
+ id: ctx.partId("counter"),
+ values: keys.map((k) => [...k]) as never,
+ format: props.format,
+ suffix,
+ affixScale: 0.6,
+ digitStagger: 0,
+ ease,
+ fontFamily,
+ fontSize: size,
+ fontWeight: 700,
+ align,
+ x: 0,
+ y: 0,
+ theme,
+ fps,
+ });
+ const label = (text: string, size: number) =>
+ host.text(text, {
+ id: ctx.partId("label"),
+ position: "absolute",
+ fontFamily,
+ fontSize: size,
+ fill: theme.color.muted,
+ });
+
+ const children: LayoutNode[] = [];
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+ const crossings: Array<{ frame: number; segment: number }> = [];
+ let W = 0;
+ let H = 0;
+
+ const stroke = (
+ id: string,
+ d: string,
+ w: number,
+ h: number,
+ paint: string,
+ thickness: number,
+ ) =>
+ host.shape("path", {
+ id: ctx.partId(id),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: w,
+ height: h,
+ d,
+ fillType: "none",
+ strokeColor: paint,
+ strokeWidth: thickness,
+ strokeLineCap: "round",
+ });
+
+ switch (kind) {
+ case "ring":
+ case "arc": {
+ const D = props.size ?? 260 * s;
+ const T = props.thickness ?? D * (kind === "ring" ? 0.085 : 0.1);
+ const r = (D - T) / 2;
+ const c: Vec2 = [D / 2, D / 2];
+ // Ring: a full turn from the top. Arc: 240° from lower left, over the top.
+ const [a0, a1] = kind === "ring" ? [-90, 269.9] : [150, 390];
+ const path = toPathData(arcPoints(c, r, a0, a1));
+ W = D;
+ H = kind === "ring" ? D : D * 0.86;
+ const track = stroke("track", path, W, H, trackColor, T);
+ const fill = stroke("fill", path, W, H, color, T);
+ fill.animate(
+ LayerAnimation.keys(
+ "trimEnd",
+ fillKeys((x) => x),
+ ),
+ );
+ children.push(track, fill);
+ parts.track = track;
+ parts.fill = fill;
+ if (showCounter) {
+ const n = number(D * (kind === "ring" ? 0.24 : 0.22), "center");
+ const nn = n as unknown as {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ };
+ nn.x = (W - nn.width) / 2;
+ nn.y =
+ (kind === "ring" ? D / 2 : D * 0.48) -
+ nn.height / 2 -
+ (props.label ? D * 0.04 : 0);
+ children.push(n);
+ parts.counter = n;
+ if (props.label) {
+ const size = D * 0.075;
+ const m = host.measure(props.label, { fontFamily, fontSize: size });
+ const l = label(props.label, size);
+ Object.assign(l, { x: (W - m.width) / 2, y: nn.y + nn.height });
+ children.push(l);
+ parts.label = l;
+ }
+ }
+ break;
+ }
+ case "bar": {
+ const w = props.size ?? 640 * s;
+ const T = props.thickness ?? 16 * s;
+ const top = props.label ? 34 * s : 0;
+ const track = host.box({
+ id: ctx.partId("track"),
+ position: "absolute",
+ x: 0,
+ y: top,
+ width: w,
+ height: T,
+ background: trackColor,
+ borderRadius: T / 2,
+ });
+ const fill = host.box({
+ id: ctx.partId("fill"),
+ position: "absolute",
+ x: 0,
+ y: top,
+ width: 0,
+ height: T,
+ background: color,
+ borderRadius: T / 2,
+ });
+ fill.animate(
+ LayerAnimation.keys(
+ "width",
+ fillKeys((x) => x * w),
+ ),
+ );
+ children.push(track, fill);
+ parts.track = track;
+ parts.fill = fill;
+ W = w;
+ H = top + T;
+ if (props.label) {
+ const l = label(props.label, 24 * s);
+ Object.assign(l, { x: 0, y: 0 });
+ children.push(l);
+ parts.label = l;
+ }
+ if (showCounter) {
+ const n = number(Math.max(T * 2.2, 30 * s), "end");
+ const nn = n as unknown as {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ };
+ nn.x = w + 18 * s;
+ nn.y = top + T / 2 - nn.height / 2;
+ W = nn.x + nn.width;
+ H = Math.max(H, nn.y + nn.height);
+ children.push(n);
+ parts.counter = n;
+ }
+ break;
+ }
+ case "segments":
+ case "stars": {
+ const n = props.segments ?? (kind === "stars" ? Math.round(max) : 10);
+ const w = props.size ?? (kind === "stars" ? 300 : 640) * s;
+ const gap = kind === "stars" ? w * 0.03 : w * 0.012;
+ const cell = (w - gap * (n - 1)) / n;
+ const h = kind === "stars" ? cell : (props.thickness ?? 22 * s);
+ // How full each cell is, per frame.
+ const fill = (k: number) =>
+ perFrame.map((v) => Math.max(0, Math.min(1, fraction(v) * n - k)));
+ for (let k = 0; k < n; k++) {
+ const x = k * (cell + gap);
+ const amount = fill(k);
+ const full = amount.findIndex((a) => a >= 1);
+ if (full >= 0) crossings.push({ frame: full, segment: k });
+ if (kind === "segments") {
+ const base = host.box({
+ id: ctx.partId(`cell-${k}`),
+ position: "absolute",
+ x,
+ y: 0,
+ width: cell,
+ height: h,
+ background: trackColor,
+ borderRadius: Math.min(h, cell) * 0.25,
+ });
+ const lit = host.box({
+ id: ctx.partId(`lit-${k}`),
+ position: "absolute",
+ x,
+ y: 0,
+ width: cell,
+ height: h,
+ background: color,
+ borderRadius: Math.min(h, cell) * 0.25,
+ opacity: 0,
+ });
+ // Lights on the frame the value reaches the cell, with a small pop.
+ const on = amount.map((a) => (a >= 1 ? 1 : 0));
+ const opacity: KeyframeTuple[] = [[0, on[0] ?? 0]];
+ const scale: KeyframeTuple[] = [[0, 1]];
+ on.forEach((v, t) => {
+ if (t > 0 && v !== on[t - 1]) {
+ opacity.push([t, v, "hold"]);
+ if (v === 1) scale.push([t, 1.18], [t + 6, 1, "power2.out"]);
+ }
+ });
+ lit.animate(
+ LayerAnimation.create()
+ .keys("opacity", opacity)
+ .keys("scale", ascending(scale)),
+ );
+ children.push(base, lit);
+ } else {
+ const d = starPath(cell);
+ const base = host.shape("path", {
+ id: ctx.partId(`star-${k}`),
+ position: "absolute",
+ x,
+ y: 0,
+ width: cell,
+ height: cell,
+ d,
+ fillType: "solid",
+ fillColor: trackColor,
+ });
+ const star = host.shape("path", {
+ id: ctx.partId(`star-${k}-fill`),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: cell,
+ height: cell,
+ d,
+ fillType: "solid",
+ fillColor: color,
+ });
+ // Fractional ratings fill a star partway: a clip that widens.
+ const clip = host.box({
+ id: ctx.partId(`star-${k}-clip`),
+ position: "absolute",
+ x,
+ y: 0,
+ width: 0,
+ height: cell,
+ overflow: "hidden",
+ children: [star],
+ });
+ clip.animate(
+ LayerAnimation.keys(
+ "width",
+ bakeSamples(
+ amount.map((a) => a * cell),
+ 0,
+ { tolerance: 0.2 },
+ ),
+ ),
+ );
+ children.push(base, clip);
+ }
+ }
+ W = w;
+ H = h;
+ if (showCounter) {
+ const c = number(Math.max(h * 1.4, 30 * s), "end");
+ const cc = c as unknown as {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ };
+ cc.x = w + 18 * s;
+ cc.y = h / 2 - cc.height / 2;
+ W = cc.x + cc.width;
+ H = Math.max(H, cc.y + cc.height);
+ children.push(c);
+ parts.counter = c;
+ }
+ break;
+ }
+ }
+
+ const settled = Math.max(
+ last,
+ (
+ parts.counter as unknown as {
+ cues?: { settled: Array<{ frame: number }> };
+ }
+ )?.cues?.settled[0]?.frame ?? 0,
+ );
+ return {
+ children,
+ width: W,
+ height: H,
+ duration: settled + 1,
+ openEnded: true,
+ cues: { settled: [{ frame: settled }], crossings } as MeterCues,
+ parts,
+ };
+ },
+});
+
+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/meter/meta.ts b/packages/components/src/meter/meta.ts
new file mode 100644
index 00000000..79c857c4
--- /dev/null
+++ b/packages/components/src/meter/meta.ts
@@ -0,0 +1,12 @@
+import { defineMeta } from "../core/meta.js";
+
+export default defineMeta({
+ name: "Meter",
+ summary:
+ "Progress and scores as a ring, arc gauge, bar, lit segments or star rating, filling on the same timeline as its counter.",
+ tags: ["progress", "gauge", "score", "rating", "stat", "data"],
+ parts: ["track", "fill", "counter", "label", "cell-<n>", "star-<n>"],
+ cues: ["settled", "crossings"],
+ example: `Meter({ value: 72, kind: "ring", label: "Coverage" })`,
+ since: "M4",
+});
diff --git a/packages/components/src/title-card/index.test.ts b/packages/components/src/title-card/index.test.ts
new file mode 100644
index 00000000..60159cd6
--- /dev/null
+++ b/packages/components/src/title-card/index.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+import { bind } from "../core/contract.js";
+import { fakeHost } from "../test/fake-host.js";
+import { TITLE_LAYOUTS, titleCard } from "./index.js";
+
+const make = () => bind(fakeHost(), titleCard);
+type Node = { id?: string; x?: number; width?: number; children?: Node[] };
+
+describe("TitleCard", () => {
+ it("keeps every part inside its width, in every layout", () => {
+ for (const layout of TITLE_LAYOUTS) {
+ const card = make()({
+ kicker: "Chapter one",
+ title: "A headline that wraps across the card",
+ subtitle: "and a sub-line",
+ layout,
+ width: 900,
+ titleSize: 60,
+ });
+ const parts = ((card as unknown as Node).children?.[0]?.children ??
+ []) as Node[];
+ for (const p of parts) {
+ expect(p.x ?? 0).toBeGreaterThanOrEqual(0);
+ expect((p.x ?? 0) + (p.width ?? 0)).toBeLessThanOrEqual(900 + 1e-6);
+ }
+ }
+ });
+
+ it("reveals the headline, then settles, then stays", () => {
+ const card = make()({ kicker: "k", title: "Title", subtitle: "s" });
+ const revealed = card.cues.revealed[0]?.frame ?? 0;
+ expect(revealed).toBeGreaterThan(0);
+ expect(card.cues.settled[0]?.frame).toBeGreaterThanOrEqual(revealed);
+ expect(card.span.end).toBe(Number.POSITIVE_INFINITY);
+ });
+
+ it("plays out after the hold when asked", () => {
+ const card = make()({
+ title: "Title",
+ subtitle: "s",
+ exitStyle: "rise",
+ hold: 20,
+ });
+ const settled = card.cues.settled[0]?.frame ?? 0;
+ expect(card.cues.exitStart[0]?.frame).toBe(settled + 20);
+ expect(card.span.duration).toBeGreaterThan(settled + 20);
+ });
+});
diff --git a/packages/components/src/title-card/index.ts b/packages/components/src/title-card/index.ts
new file mode 100644
index 00000000..c4f2d387
--- /dev/null
+++ b/packages/components/src/title-card/index.ts
@@ -0,0 +1,328 @@
+/**
+ * TitleCard: kicker, headline, rule and sub-line in designed layouts, on
+ * one timeline. The text parts are `TextReveal`s (the headline in any reveal
+ * style), the rule draws, and the whole card can play out.
+ */
+import {
+ LayerAnimation,
+ type LayoutNode,
+} from "@framefields/compositions/program";
+import { z } from "zod";
+import { bind, defineComponent } from "../core/contract.js";
+import type { Animatable } from "../core/host.js";
+import { themeFrames } from "../core/theme.js";
+import {
+ EXIT_STYLES,
+ REVEAL_STYLES,
+ textReveal,
+} from "../text-reveal/index.js";
+
+export const TITLE_LAYOUTS = ["center", "left", "stack", "split"] as const;
+export type TitleLayout = (typeof TITLE_LAYOUTS)[number];
+
+export interface TitleCardCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ /** The headline is at rest. */
+ revealed: ReadonlyArray<{ frame: number }>;
+ /** Every part is at rest. */
+ settled: ReadonlyArray<{ frame: number }>;
+ /** The card starts to play out (empty without `exitStyle`). */
+ exitStart: ReadonlyArray<{ frame: number }>;
+}
+
+export const titleCard = /* @__PURE__ */ defineComponent({
+ name: "TitleCard",
+ props: () => ({
+ title: z.string().min(1),
+ kicker: z.string().optional(),
+ subtitle: z.string().optional(),
+ layout: z.enum(TITLE_LAYOUTS).default("center"),
+ /** The headline's reveal style. */
+ reveal: z.enum(REVEAL_STYLES).default("rise"),
+ emphasis: z.array(z.union([z.string(), z.instanceof(RegExp)])).default([]),
+ rule: z.boolean().default(true),
+ exitStyle: z.union([z.enum(EXIT_STYLES), z.literal(false)]).default(false),
+ titleSize: z.number().positive().optional(),
+ fontFamily: z.string().optional(),
+ }),
+ defaults: { enter: false, exit: false, hold: 45 },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const s = theme.scale;
+ const W = ctx.requested.width ?? 1600 * s;
+ const size = props.titleSize ?? 120 * s;
+ const kickerSize = Math.max(16 * s, size * 0.22);
+ const subSize = Math.max(20 * s, size * 0.34);
+ const fontFamily = props.fontFamily ?? theme.font.display;
+ const reveal = bind(host, textReveal);
+ const fast = themeFrames(theme, "fast", fps);
+ const base = themeFrames(theme, "base", fps);
+ const layout = props.layout;
+ const centered = layout === "center";
+ const align = centered ? "center" : "start";
+
+ // Columns: split puts the headline left, the rest right of a rule.
+ const bar = layout === "stack" ? Math.max(4 * s, size * 0.06) : 0;
+ const barGap = layout === "stack" ? size * 0.32 : 0;
+ const titleW = layout === "split" ? W * 0.56 : W - bar - barGap;
+ const sideX = W * 0.62;
+ const sideW = W - sideX;
+ const left = bar + barGap;
+
+ const measure = (
+ text: string,
+ fontSize: number,
+ width: number,
+ weight?: number,
+ ) =>
+ host.measure(text, {
+ fontFamily,
+ fontSize,
+ fontWeight: weight,
+ width,
+ align: centered ? "center" : "left",
+ });
+ const titleM = measure(props.title, size, titleW, 700);
+ const kickerText = props.kicker?.toUpperCase();
+ // Measured with its tracking, so a centred kicker is really centred.
+ const kickerM = kickerText
+ ? host.measure(kickerText, {
+ fontFamily,
+ fontSize: kickerSize,
+ fontWeight: 600,
+ letterSpacing: kickerSize * 0.16,
+ })
+ : null;
+ const subM = props.subtitle
+ ? measure(
+ props.subtitle,
+ subSize,
+ layout === "split" ? sideW : centered ? W * 0.8 : titleW,
+ )
+ : null;
+
+ const gap = size * 0.28;
+ const ruleW =
+ layout === "split" ? Math.max(2, 3 * s) : Math.min(W * 0.12, 160 * s);
+ const ruleH = layout === "split" ? 0 : Math.max(3, 4 * s);
+ const ruleGap = props.rule && layout !== "split" ? gap : 0;
+
+ // ── Vertical layout ───────────────────────────────────────────────
+ let y = 0;
+ const place: Record<
+ "kicker" | "title" | "rule" | "subtitle",
+ { x: number; y: number }
+ > = {
+ kicker: { x: 0, y: 0 },
+ title: { x: 0, y: 0 },
+ rule: { x: 0, y: 0 },
+ subtitle: { x: 0, y: 0 },
+ };
+ let height: number;
+ if (layout === "split") {
+ place.title = { x: 0, y: 0 };
+ const side =
+ (kickerM ? kickerM.height + gap * 0.6 : 0) + (subM?.height ?? 0);
+ const top = Math.max(0, (titleM.height - side) / 2);
+ place.kicker = { x: sideX, y: top };
+ place.subtitle = {
+ x: sideX,
+ y: top + (kickerM ? kickerM.height + gap * 0.6 : 0),
+ };
+ place.rule = { x: W * 0.59, y: 0 };
+ height = Math.max(titleM.height, side);
+ } else {
+ if (kickerM) {
+ place.kicker = { x: centered ? (W - kickerM.width) / 2 : left, y };
+ y += kickerM.height + gap * 0.5;
+ }
+ place.title = { x: centered ? 0 : left, y };
+ y += titleM.height;
+ if (props.rule) {
+ y += ruleGap * 0.6;
+ place.rule = { x: centered ? (W - ruleW) / 2 : left, y };
+ y += ruleH + ruleGap * 0.6;
+ } else y += gap * 0.5;
+ if (subM) {
+ place.subtitle = { x: centered ? W * 0.1 : left, y };
+ y += subM.height;
+ }
+ height = y;
+ }
+
+ // ── Timeline ──────────────────────────────────────────────────────
+ const children: LayoutNode[] = [];
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+ const titleAt = kickerText ? Math.round(fast * 1.2) : 0;
+ const title = reveal({
+ id: ctx.partId("title"),
+ text: props.title,
+ style: props.reveal,
+ at: titleAt,
+ ...place.title,
+ width: titleW,
+ align,
+ fontFamily,
+ fontSize: size,
+ fontWeight: 700,
+ emphasis: props.emphasis,
+ theme,
+ seed: ctx.seed,
+ fps,
+ });
+ const revealed = title.cues.revealed[0]?.frame ?? titleAt;
+ const followAt = Math.max(titleAt, revealed - Math.round(base * 0.6));
+
+ let settled = revealed;
+ const fadeable: Array<Animatable<LayoutNode>> = [];
+ if (kickerText && kickerM) {
+ const kicker = reveal({
+ id: ctx.partId("kicker"),
+ text: kickerText,
+ style: "track",
+ ...place.kicker,
+ fontFamily,
+ fontSize: kickerSize,
+ fontWeight: 600,
+ letterSpacing: kickerSize * 0.16,
+ fill: theme.color.accent,
+ theme,
+ fps,
+ });
+ children.push(kicker);
+ parts.kicker = kicker;
+ fadeable.push(kicker);
+ settled = Math.max(settled, kicker.cues.revealed[0]?.frame ?? 0);
+ }
+ children.push(title);
+ parts.title = title;
+
+ if (props.rule) {
+ const draw = Math.round(base * 1.3);
+ const rule = host.box({
+ id: ctx.partId("rule"),
+ position: "absolute",
+ ...place.rule,
+ width: layout === "split" ? ruleW : 0,
+ height: layout === "split" ? 0 : ruleH,
+ background: theme.color.accent,
+ borderRadius: ruleH / 2,
+ });
+ const along = layout === "split" ? "height" : "width";
+ const full = layout === "split" ? height : ruleW;
+ rule.animate(
+ LayerAnimation.keys(along, [
+ [followAt, 0],
+ [followAt + draw, full, theme.motion.ease.enter],
+ ]),
+ );
+ // Centred rules grow from the middle.
+ if (centered)
+ rule.animate(
+ LayerAnimation.keys("x", [
+ [followAt, W / 2],
+ [followAt + draw, place.rule.x, theme.motion.ease.enter],
+ ]),
+ );
+ children.push(rule);
+ parts.rule = rule;
+ fadeable.push(rule);
+ settled = Math.max(settled, followAt + draw);
+ }
+ if (layout === "stack") {
+ const draw = Math.round(base * 1.5);
+ const accentBar = host.box({
+ id: ctx.partId("bar"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: bar,
+ height: 0,
+ background: theme.color.accent,
+ borderRadius: bar / 2,
+ });
+ accentBar.animate(
+ LayerAnimation.keys("height", [
+ [0, 0],
+ [draw, height, theme.motion.ease.enter],
+ ]),
+ );
+ children.push(accentBar);
+ parts.bar = accentBar;
+ fadeable.push(accentBar);
+ settled = Math.max(settled, draw);
+ }
+ if (props.subtitle && subM) {
+ const sub = reveal({
+ id: ctx.partId("subtitle"),
+ text: props.subtitle,
+ style: "rise",
+ by: "line",
+ at: followAt + Math.round(fast * 0.5),
+ ...place.subtitle,
+ width: layout === "split" ? sideW : centered ? W * 0.8 : titleW,
+ align,
+ fontFamily,
+ fontSize: subSize,
+ fill: theme.color.muted,
+ theme,
+ fps,
+ });
+ children.push(sub);
+ parts.subtitle = sub;
+ fadeable.push(sub);
+ settled = Math.max(settled, sub.cues.revealed[0]?.frame ?? 0);
+ }
+
+ // ── Exit ──────────────────────────────────────────────────────────
+ let afterHold = 0;
+ const exitStart = settled + ctx.hold;
+ if (props.exitStyle !== false) {
+ // Rebuild the headline with its exit lined up to the card's.
+ const leaving = reveal({
+ id: ctx.partId("title"),
+ text: props.title,
+ style: props.reveal,
+ exitStyle: props.exitStyle,
+ hold: exitStart - revealed,
+ at: titleAt,
+ ...place.title,
+ width: titleW,
+ align,
+ fontFamily,
+ fontSize: size,
+ fontWeight: 700,
+ emphasis: props.emphasis,
+ theme,
+ seed: ctx.seed,
+ fps,
+ });
+ children[children.indexOf(title)] = leaving;
+ parts.title = leaving;
+ afterHold = Math.max(1, leaving.span.end - exitStart);
+ const out = Math.min(afterHold, Math.round(base * 0.8));
+ for (const node of fadeable)
+ node.animate(
+ LayerAnimation.keys("opacity", [
+ [exitStart, 1],
+ [exitStart + out, 0, theme.motion.ease.exit],
+ ]),
+ );
+ }
+
+ return {
+ children,
+ width: W,
+ height,
+ duration: settled,
+ openEnded: true,
+ afterHold,
+ cues: {
+ revealed: [{ frame: revealed }],
+ settled: [{ frame: settled }],
+ exitStart: props.exitStyle === false ? [] : [{ frame: exitStart }],
+ } as TitleCardCues,
+ parts,
+ };
+ },
+});
diff --git a/packages/components/src/title-card/meta.ts b/packages/components/src/title-card/meta.ts
new file mode 100644
index 00000000..99b97c8b
--- /dev/null
+++ b/packages/components/src/title-card/meta.ts
@@ -0,0 +1,12 @@
+import { defineMeta } from "../core/meta.js";
+
+export default defineMeta({
+ name: "TitleCard",
+ summary:
+ "Kicker, headline, rule and sub-line in designed layouts (center, left, stack, split), the headline in any reveal style, on one timeline.",
+ tags: ["title", "headline", "typography", "opener", "chapter"],
+ parts: ["kicker", "title", "rule", "bar", "subtitle"],
+ cues: ["revealed", "settled", "exitStart"],
+ example: `TitleCard({ kicker: "Chapter one", title: "Ship it faster", subtitle: "What changed in 2.5" })`,
+ since: "M4",
+});
diff --git a/packages/framefields/scripts/check-components-treeshake.mjs b/packages/framefields/scripts/check-components-treeshake.mjs
index 1022e915..e4fc113c 100644
--- a/packages/framefields/scripts/check-components-treeshake.mjs
+++ b/packages/framefields/scripts/check-components-treeshake.mjs
@@ -25,6 +25,27 @@ const ANNOTATE = "Moving targets arrive with Callout";
const GLYPHS = "L[k+1]-L[k]";
const CAPTIONS = "give `words` or a `transcript`";
const SHELL = "spinner-";
+const CODE = "satisfies keyof declare";
+const TITLE = "kicker";
+const LOWER = "role-plate";
+const METER = "Meter: give `value`";
+
+/** Each component: a string only its module has, and what it may compose. */
+const COMPONENTS = {
+ MousePointer: { own: POINTER, uses: [], budget: 60_000 },
+ AppFrame: { own: FRAME, uses: [], budget: 45_000 },
+ FocusZoom: { own: CAMERA, uses: [], budget: 40_000 },
+ TextReveal: { own: REVEAL, uses: [GLYPHS], budget: 55_000 },
+ Counter: { own: COUNTER, uses: [], budget: 45_000 },
+ Annotate: { own: ANNOTATE, uses: [], budget: 50_000 },
+ Captions: { own: CAPTIONS, uses: [GLYPHS], budget: 55_000 },
+ Terminal: { own: SHELL, uses: [FRAME, COUNTER], budget: 80_000 },
+ CodeBlock: { own: CODE, uses: [FRAME], budget: 70_000 },
+ TitleCard: { own: TITLE, uses: [REVEAL, GLYPHS], budget: 70_000 },
+ LowerThird: { own: LOWER, uses: [], budget: 45_000 },
+ Meter: { own: METER, uses: [COUNTER], budget: 55_000 },
+};
+const OWN = Object.values(COMPONENTS).map((c) => c.own);
/** [names imported, markers that must not survive, max added bytes]. */
const cases = [
@@ -32,44 +53,12 @@ const cases = [
[["boxPath", "ellipsePath"], [CONTRACT, TARGETS, MOTION], 6_000],
[["resolveTarget", "targetPoint"], [CONTRACT, STROKES, MOTION], 10_000],
[["staggerOffsets", "toFrames"], [CONTRACT, STROKES, TARGETS, MOTION], 3_000],
- // Each component alone: none of the others.
- [
- ["MousePointer"],
- [FRAME, CAMERA, REVEAL, COUNTER, ANNOTATE, GLYPHS, CAPTIONS, SHELL],
- 60_000,
- ],
- [
- ["AppFrame"],
- [POINTER, CAMERA, REVEAL, COUNTER, ANNOTATE, GLYPHS, CAPTIONS, SHELL],
- 45_000,
- ],
- [
- ["FocusZoom"],
- [POINTER, FRAME, REVEAL, COUNTER, ANNOTATE, GLYPHS, CAPTIONS, SHELL],
- 40_000,
- ],
- [
- ["TextReveal"],
- [POINTER, FRAME, CAMERA, COUNTER, ANNOTATE, CAPTIONS, SHELL],
- 55_000,
- ],
- [
- ["Counter"],
- [POINTER, FRAME, CAMERA, REVEAL, ANNOTATE, GLYPHS, CAPTIONS, SHELL],
- 45_000,
- ],
- [
- ["Annotate"],
- [POINTER, FRAME, CAMERA, REVEAL, COUNTER, GLYPHS, CAPTIONS, SHELL],
- 50_000,
- ],
- [
- ["Captions"],
- [POINTER, FRAME, CAMERA, REVEAL, COUNTER, ANNOTATE, SHELL],
- 55_000,
- ],
- // Terminal composes AppFrame and Counter on purpose.
- [["Terminal"], [POINTER, CAMERA, REVEAL, ANNOTATE, GLYPHS, CAPTIONS], 80_000],
+ // Each component alone: none of the others, except what it composes.
+ ...Object.entries(COMPONENTS).map(([name, c]) => [
+ [name],
+ [...OWN, GLYPHS].filter((m) => m !== c.own && !c.uses.includes(m)),
+ c.budget,
+ ]),
];
async function bundle(contents) {
@@ -91,20 +80,7 @@ const base = await bundle(baseline);
const failures = [];
// Using framefields without components must carry none of them: component
// modules may not build anything (schemas, glyphs) at import time.
-for (const marker of [
- CONTRACT,
- STROKES,
- TARGETS,
- POINTER,
- FRAME,
- CAMERA,
- REVEAL,
- COUNTER,
- ANNOTATE,
- GLYPHS,
- CAPTIONS,
- SHELL,
-]) {
+for (const marker of [CONTRACT, STROKES, TARGETS, GLYPHS, ...OWN]) {
if (base.includes(marker))
failures.push(`import { Layer } alone kept component code ("${marker}")`);
}
diff --git a/packages/framefields/src/components/index.ts b/packages/framefields/src/components/index.ts
index 996d2b9b..6e559082 100644
--- a/packages/framefields/src/components/index.ts
+++ b/packages/framefields/src/components/index.ts
@@ -17,11 +17,15 @@ import {
type ComponentExtras,
type Cues,
captions,
+ codeBlock,
counter,
focusZoom,
+ lowerThird,
+ meter,
mousePointer,
terminal,
textReveal,
+ titleCard,
} from "@framefields/components";
import type { BoxNode } from "@framefields/compositions/program";
import type { z } from "zod";
@@ -70,6 +74,18 @@ export const Captions = /* @__PURE__ */ bindComponent(captions);
/** A scripted shell session: typed commands, streaming output, spinners, progress and scrolling. */
export const Terminal = /* @__PURE__ */ bindComponent(terminal);
+/** Code on screen: syntax colours, typing, a focus band and diffs where kept lines glide. */
+export const CodeBlock = /* @__PURE__ */ bindComponent(codeBlock);
+
+/** Kicker, headline, rule and sub-line in designed layouts, on one timeline. */
+export const TitleCard = /* @__PURE__ */ bindComponent(titleCard);
+
+/** A name-and-role bar for interviews and talks that slides in and leaves on its own. */
+export const LowerThird = /* @__PURE__ */ bindComponent(lowerThird);
+
+/** Progress and scores: ring, arc, bar, segments or stars, filling with its counter. */
+export const Meter = /* @__PURE__ */ bindComponent(meter);
+
export {
type Anchor,
type AnnotateCues,
@@ -97,6 +113,9 @@ export {
CAPTION_STYLES,
type CaptionStyle,
type CaptionsCues,
+ CODE_LANGS,
+ type CodeBlockCues,
+ type CodeLang,
type ComponentDefaults,
type ComponentDefinition,
type ComponentExtras,
@@ -141,12 +160,18 @@ export {
type HandOptions,
hashRng,
hashString,
+ LOWER_THIRD_LAYOUTS,
+ type LowerThirdCues,
+ type LowerThirdLayout,
lerp2,
linePath,
lineShift,
MARKS,
type Mark,
+ METER_KINDS,
type MeasureOptions,
+ type MeterCues,
+ type MeterKind,
type Metrics,
MOTION_PRESETS,
type MotionOptions,
@@ -189,10 +214,16 @@ export {
type Theme,
type ThemeInput,
type ThemeName,
+ TITLE_LAYOUTS,
+ type TitleCardCues,
+ type TitleLayout,
+ type Token,
+ type TokenKind,
targetPoint,
themeFrames,
themes,
toFrames,
+ tokenize,
toPathData,
toSeconds,
typingFrames,
diff --git a/packages/framefields/src/components/m4.render.test.ts b/packages/framefields/src/components/m4.render.test.ts
new file mode 100644
index 00000000..6559b7cc
--- /dev/null
+++ b/packages/framefields/src/components/m4.render.test.ts
@@ -0,0 +1,97 @@
+import { beforeAll, describe, expect, it } from "vitest";
+import { FontManager } from "../fonts/index.js";
+import { Composition } from "../index.js";
+import { computeMse, decodePngPixels, getPixel } from "../test-utils/pixels.js";
+import { CodeBlock, Meter, TitleCard } from "./index.js";
+
+/**
+ * Render tests for the M4 components (spec §7.9–7.12): a settled diff is the
+ * new code, fractional stars fill partway, frames don't depend on order.
+ */
+beforeAll(async () => {
+ await FontManager.register("assets/fonts/Inter.ttf");
+ await FontManager.register("assets/fonts/JetBrainsMono.ttf");
+});
+function comp(nodes: Parameters<Composition["add"]>[0]) {
+ const c = new Composition({
+ width: 960,
+ height: 540,
+ fps: 30,
+ durationMs: 8000,
+ backgroundColor: "#0d0e11",
+ });
+ c.add(nodes);
+ return c;
+}
+const frame = async (c: Composition, n: number) =>
+ decodePngPixels(await c.renderFrame({ frame: n }));
+
+describe("CodeBlock (render)", () => {
+ it("a settled diff looks exactly like the new code", async () => {
+ const before = "const a = 1;\nconst b = 2;\nlog(a + b);";
+ const after = "const a = 1;\n log(a);\nconst c = 3;\nlog(a + b);";
+ const diffed = CodeBlock({
+ code: before,
+ diff: { to: after, at: 5, duration: 20 },
+ x: 40,
+ y: 40,
+ });
+ const end = (diffed.cues.diff[0]?.end ?? 0) + 40;
+ const got = await frame(comp(diffed), end);
+ const want = await frame(
+ comp(CodeBlock({ code: after, x: 40, y: 40 })),
+ end,
+ );
+ expect(computeMse(got.pixels, want.pixels)).toBeLessThan(0.05);
+ });
+});
+
+describe("Meter (render)", () => {
+ it("3.5 stars fill three stars and half of the fourth", async () => {
+ const m = Meter({
+ value: 3.5,
+ kind: "stars",
+ size: 500,
+ x: 0,
+ y: 100,
+ countDuration: 10,
+ });
+ const img = await frame(comp(m), 30);
+ const cell = (500 - 500 * 0.03 * 4) / 5;
+ const at = (k: number, f: number) =>
+ getPixel(img, k * (cell + 500 * 0.03) + cell * f, 100 + cell * 0.55);
+ const accent = (p: { b: number; r: number }) => p.b > 200 && p.r < 150;
+ expect(accent(at(2, 0.5))).toBe(true);
+ expect(accent(at(3, 0.3))).toBe(true);
+ expect(accent(at(3, 0.7))).toBe(false);
+ expect(accent(at(4, 0.5))).toBe(false);
+ });
+});
+
+describe("TitleCard (render)", () => {
+ it("renders the same frames in any order", async () => {
+ const build = () =>
+ comp(
+ TitleCard({
+ kicker: "Chapter",
+ title: "Ship it",
+ subtitle: "faster",
+ x: 80,
+ y: 80,
+ width: 800,
+ }),
+ );
+ const frames = [6, 20, 60];
+ const forward = await Promise.all(frames.map((f) => frame(build(), f)));
+ const c = build();
+ for (const [i, f] of [...frames].reverse().entries()) {
+ const img = await frame(c, f);
+ expect(
+ computeMse(
+ img.pixels,
+ (forward[frames.length - 1 - i] as typeof img).pixels,
+ ),
+ ).toBe(0);
+ }
+ });
+});
diff --git a/packages/framefields/src/index.ts b/packages/framefields/src/index.ts
index 944465c7..55e21542 100644
--- a/packages/framefields/src/index.ts
+++ b/packages/framefields/src/index.ts
@@ -3408,6 +3408,9 @@ export {
type CaptionStyle,
Captions,
type CaptionsCues,
+ CodeBlock,
+ type CodeBlockCues,
+ type CodeLang,
type ComponentNode,
Counter,
type CounterCues,
@@ -3418,6 +3421,12 @@ export {
type FocusZoomApi,
type FocusZoomCues,
type Followable,
+ LowerThird,
+ type LowerThirdCues,
+ type LowerThirdLayout,
+ Meter,
+ type MeterCues,
+ type MeterKind,
MousePointer,
type MousePointerApi,
type MousePointerCues,
@@ -3428,5 +3437,8 @@ export {
TextReveal,
type TextRevealApi,
type TextRevealCues,
+ TitleCard,
+ type TitleCardCues,
+ type TitleLayout,
type Waypoint,
} from "./components/index.js";