Code-first video & image, rendered natively on WebGPU.
feat(components): M5 chat thread, toasts, callout, spotlight, confetti
okanaslf70e520610c1
diff --git a/packages/components/SPEC.md b/packages/components/SPEC.mdindex 2c5a2052..64482bab 100644--- a/packages/components/SPEC.md+++ b/packages/components/SPEC.md@@ -1136,7 +1136,7 @@ Each milestone ends with a changeset for `framefields` (minor), docs, and its ex| **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`. | Specs in §7.9–7.12; acceptance tests green (§16); no example film. |-| **M5 · Wave 2b** | `ChatThread`, `Callout`, `Spotlight`, `Confetti`, `Toasts`. | As above. |+| **M5 · Wave 2b** ✅ | `ChatThread`, `Callout`, `Spotlight`, `Confetti`, `Toasts`. | Built from the §8.1 rows; behaviour and acceptance in §17; no example film. || **M6 · Re-score** | Rank Wave 3 against usage and requests. | Updated §8.2. |Housekeeping (done in M1): the stale `.changeset/components-mouse-pointer.md` described a@@ -1331,3 +1331,55 @@ Deviations from §7.9–7.12: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.++## 17. M5 delivery notes++What landed: `ChatThread`, `Toasts`, `Callout`, `Spotlight`, `Confetti` (from the §8.1+rows), unit tests for each, the components in `ids.test.ts`, and `m5.render.test.ts` (a+reply is invisible until it lands; toasts are absent before they arrive; the spotlight's hole+is lit and the rest dimmed; confetti frames identical in any render order).++**A contract-wide fix.** Before a track's first keyframe the renderer draws the node's base+value, not the first key's. Every component meant "hold the first key" (a bubble hidden until+it lands, a second underline undrawn until its turn, a label waiting for its cue), so the+contract now pins each track's first value at frame 0 for the whole built tree+(`holdFirstKeys`, skipping repeating tracks). This fixed latent early-visibility in earlier+components too; every M1–M4 test still passes unchanged.++How they are built:++- **ChatThread** (`messages`, `me`, `participants`, `names`, `typing`, `readCps`): timing+ from reading speed, with typing dots (a bouncing wave) before the other side's replies.+ Bubbles are measured (wrapping past 74 % of the width), spring in from their corner+ (`core/bake.ts` `springKeys`), and the column scrolls to keep the newest in view. It also+ supports names for group chats, timestamps, image messages and reactions; a heart reaction+ is drawn, other reactions are text.+- **Toasts** (`items`, `corner`, `max`): the stack is solved at every arrival and dismissal+ (newest at the edge, older ones pushed away, each a little smaller, faded beyond `max`), and+ every toast springs between its targets (`springTrack`: a retarget starts from the current+ value). Kinds draw their own icon: success, info, warning, error.+- **Callout** (`target`, `text`, `title`, `side`, `elbow`, `dot`, `length`): the leader is+ one or two rotated boxes (keyed numbers, not a morphing path), the label hangs off its end,+ is clamped inside the frame, and `auto` picks the open quadrant. Moving targets are followed+ for `length` frames; the side decision eases, so a target crossing the middle swings its+ label across instead of snapping.+- **Spotlight** (`targets`, `dim`, `shape`, `feather`, `glide`, `follow`): a full-frame dim+ layer masked by an **inverted** matte (`host.matte(…, "alpha-inverted")`) whose hole glides+ between padded target rects; `"full"` lifts the dim. `ellipse` is a soft pool+ (radial-gradient hole); `rect` is a crisp rounded rectangle.+- **Confetti** (`bursts`, `palette`, `gravity`, `floor`, `ribbons`, `sparkles`): GPU particles+ via `host.particles`, with one square-paper system per palette colour per origin (bursts+ sharing an origin share systems), spark streaks for ribbons, and additive soft glints.+ Curl noise reads as flutter, and a floor lets pieces bounce and settle. Each system is+ seeded from `seed`.++Deviations from the §8.1 rows:++- ChatThread's `appearance` comes from the theme (no separate prop).+- Callout binds dynamic targets as baked frames over `length`, not live vision signals, and+ has no per-frame quadrant switching beyond the eased side choice.+- Spotlight's `rect` shape has no feathered edge: one matte can't be both rounded-rect and+ feathered. Use `ellipse` for a soft light.+- Confetti paper doesn't flip in 3D: GPU particles have no per-particle rotation, so the+ flutter comes from curl noise.+- Emoji need an emoji-capable font; the default theme fonts have none.diff --git a/packages/components/src/annotate/index.test.ts b/packages/components/src/annotate/index.test.tsindex 5235e133..c19aa9d7 100644--- a/packages/components/src/annotate/index.test.ts+++ b/packages/components/src/annotate/index.test.ts@@ -64,7 +64,8 @@ describe("Annotate", () => {});const [first, second] = strokes(a).map((n) => keys(n, "trimEnd"));expect(first?.[0]?.frame).toBe(0);- expect(second?.[0]?.frame).toBe(first?.[1]?.frame);+ // Key 0 is the hold from frame 0; the stroke starts drawing when the first ends.+ expect(second?.[1]?.frame).toBe(first?.[1]?.frame);expect(a.cues.drawn[0]?.frame).toBe(20);});diff --git a/packages/components/src/callout/index.test.ts b/packages/components/src/callout/index.test.tsnew file mode 100644index 00000000..40f24ffe--- /dev/null+++ b/packages/components/src/callout/index.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from "vitest";+import { bind } from "../core/contract.js";+import { fakeHost } from "../test/fake-host.js";+import { callout } from "./index.js";++const make = () => bind(fakeHost(), callout);+type Node = {+ id?: string;+ x?: number;+ y?: number;+ width?: number;+ height?: number;+ children?: Node[];+ 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 last = (n: Node | undefined, prop: string) => {+ const k = n?.animation?.tracks.find((t) => t.prop === prop)?.keyframes ?? [];+ return k[k.length - 1]?.value ?? 0;+};++describe("Callout", () => {+ it("opens toward the free side and stays inside the frame", () => {+ const left = make()({+ id: "c",+ target: [100, 900],+ text: "near the left bottom",+ });+ const label = find(left, "c-label");+ expect(last(label, "x")).toBeGreaterThan(100);+ expect(last(label, "y")).toBeLessThan(900);+ const corner = make()({+ id: "c",+ target: [1900, 20],+ text: "a long label pinned at the corner",+ side: "top-right",+ });+ const l2 = find(corner, "c-label");+ expect(last(l2, "x") + (l2?.width ?? 0)).toBeLessThanOrEqual(1920);+ expect(last(l2, "y")).toBeGreaterThanOrEqual(0);+ });++ it("follows a moving target for `length` frames", () => {+ const c = make()({+ id: "c",+ target: (f: number) => [200 + f * 5, 500],+ text: "moving",+ length: 60,+ });+ expect(c.span.duration).toBe(60);+ expect(last(find(c, "c-dot"), "x")).toBeCloseTo(200 + 60 * 5 - 7, 0);+ });+});diff --git a/packages/components/src/callout/index.ts b/packages/components/src/callout/index.tsnew file mode 100644index 00000000..0a1503f6--- /dev/null+++ b/packages/components/src/callout/index.ts@@ -0,0 +1,333 @@+/**+ * Callout: a label with a leader line pinned to a point, a node, text, or a+ * moving tracked object. It picks the open side, keeps the label inside the+ * frame, and follows moving targets smoothly (decisions are eased, never+ * snapped).+ *+ * Coordinates are the frame's: the root covers the video (default+ * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.+ */+import {+ LayerAnimation,+ type LayoutNode,+} from "@framefields/compositions/program";+import { z } from "zod";+import { bakeSamples, springAt } from "../core/bake.js";+import { defineComponent } from "../core/contract.js";+import { evaluateEase } from "../core/ease.js";+import type { Animatable } from "../core/host.js";+import type { Vec2 } from "../core/path.js";+import { targetSchema } from "../core/schemas.js";+import { resolveTarget, targetPoint } from "../core/targets.js";+import { themeFrames } from "../core/theme.js";++export const CALLOUT_SIDES = [+ "auto",+ "top",+ "bottom",+ "left",+ "right",+ "top-left",+ "top-right",+ "bottom-left",+ "bottom-right",+] as const;+export type CalloutSide = (typeof CALLOUT_SIDES)[number];++export interface CalloutCues {+ [name: string]: ReadonlyArray<{ frame: number }>;+ /** Fully drawn. */+ in: ReadonlyArray<{ frame: number }>;+}++const DIRECTION: Record<Exclude<CalloutSide, "auto">, Vec2> = {+ top: [0, -1],+ bottom: [0, 1],+ left: [-1, 0],+ right: [1, 0],+ "top-left": [-1, -1],+ "top-right": [1, -1],+ "bottom-left": [-1, 1],+ "bottom-right": [1, 1],+};++export const callout = /* @__PURE__ */ defineComponent({+ name: "Callout",+ props: () => ({+ target: targetSchema(),+ text: z.string().min(1),+ /** A bolder first line above `text`. */+ title: z.string().optional(),+ side: z.enum(CALLOUT_SIDES).default("auto"),+ /** Leader length (px). */+ distance: z.number().positive().optional(),+ /** A bend: out on the diagonal, then level into the label. */+ elbow: z.boolean().default(true),+ dot: z.boolean().default(true),+ color: z.string().optional(),+ /** Frames to follow a moving target. Default 6 seconds. */+ length: z.number().int().positive().optional(),+ 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 W = ctx.requested.width ?? 1920 * s;+ const H = ctx.requested.height ?? 1080 * s;+ const fs = props.fontSize ?? 26 * s;+ const fontFamily = props.fontFamily ?? theme.font.body;+ const color = props.color ?? theme.color.accent;+ const reach = props.distance ?? 120 * s;+ const margin = 24 * s;+ const thick = Math.max(2, 2.5 * s);+ const dotR = 7 * s;++ const resolved = resolveTarget(props.target, {+ measure: host.measure,+ fps,+ });+ const moving = resolved.kind === "dynamic";+ const base = themeFrames(theme, "base", fps);+ const intro = Math.round(base * 1.8);+ const length = moving ? (props.length ?? fps * 6) : intro + 1;++ // ── Label size ────────────────────────────────────────────────────+ const padX = fs * 0.6;+ const padY = fs * 0.42;+ const titleM = props.title+ ? host.measure(props.title, { fontFamily, fontSize: fs, fontWeight: 700 })+ : null;+ const textM = host.measure(props.text, {+ fontFamily,+ fontSize: fs * (props.title ? 0.85 : 1),+ });+ const lw = Math.max(titleM?.width ?? 0, textM.width) + padX * 2;+ const lh = (titleM?.height ?? 0) + textM.height + padY * 2;++ // ── Geometry per frame ────────────────────────────────────────────+ const sideAt = (p: Vec2): Vec2 =>+ props.side === "auto"+ ? [p[0] < W / 2 ? 1 : -1, p[1] < H * 0.4 ? 1 : -1]+ : DIRECTION[props.side];+ // Side decisions ease over a few frames, so a target crossing the+ // middle swings its label across instead of snapping.+ let dir: Vec2 | null = null;+ const follow = 1 - Math.exp(-6 / fps);+ const frames = Array.from({ length: length + 1 }, (_, f) => {+ const anchor = targetPoint(resolved, f);+ const want = sideAt(anchor);+ dir = dir+ ? [+ dir[0] + (want[0] - dir[0]) * follow,+ dir[1] + (want[1] - dir[1]) * follow,+ ]+ : want;+ const [dx, dy] = dir;+ const diagonal = props.elbow && Math.abs(dx) > 0.01;+ const bend: Vec2 = diagonal+ ? [anchor[0] + dx * reach * 0.55, anchor[1] + dy * reach * 0.55]+ : [anchor[0] + dx * reach, anchor[1] + dy * reach];+ const end: Vec2 = diagonal+ ? [bend[0] + Math.sign(dx) * reach * 0.45 * Math.abs(dx), bend[1]]+ : bend;+ // The label hangs off the leader's end, on its side.+ let lx =+ Math.abs(dx) < 0.5 ? end[0] - lw / 2 : dx > 0 ? end[0] : end[0] - lw;+ let ly =+ Math.abs(dx) < 0.5 ? (dy > 0 ? end[1] : end[1] - lh) : end[1] - lh / 2;+ // Stay inside the frame.+ lx = Math.min(W - margin - lw, Math.max(margin, lx));+ ly = Math.min(H - margin - lh, Math.max(margin, ly));+ const join: Vec2 =+ Math.abs(dx) < 0.5+ ? [lx + lw / 2, dy > 0 ? ly : ly + lh]+ : [dx > 0 ? lx : lx + lw, ly + lh / 2];+ return {+ anchor,+ bend: diagonal ? bend : join,+ end: join,+ label: [lx, ly] as Vec2,+ };+ });++ // ── Intro: dot pops, leader draws, label arrives ──────────────────+ const draw = (f: number, from: number, to: number) =>+ evaluateEase(+ theme.motion.ease.move,+ Math.min(1, Math.max(0, (f - from) / Math.max(1, to - from))),+ );+ const seg1 = [Math.round(base * 0.3), Math.round(base * 1.0)] as const;+ const seg2 = [seg1[1], Math.round(base * 1.4)] as const;+ const labelAt = Math.round(base * 1.1);++ const segment = (+ id: string,+ pick: (k: (typeof frames)[number]) => [Vec2, Vec2],+ window: readonly [number, number],+ ) => {+ const xs: number[] = [];+ const ys: number[] = [];+ const ws: number[] = [];+ const rs: number[] = [];+ frames.forEach((k, f) => {+ const [a, b] = pick(k);+ const len = Math.hypot(b[0] - a[0], b[1] - a[1]);+ xs.push(a[0]);+ ys.push(a[1] - thick / 2);+ ws.push(len * draw(f, window[0], window[1]));+ rs.push((Math.atan2(b[1] - a[1], b[0] - a[0]) * 180) / Math.PI);+ });+ const node = host.box({+ id: ctx.partId(id),+ position: "absolute",+ x: xs[0] ?? 0,+ y: ys[0] ?? 0,+ width: 0,+ height: thick,+ background: color,+ borderRadius: thick / 2,+ anchorX: 0,+ anchorY: 0.5,+ });+ node.animate(+ LayerAnimation.create()+ .keys("x", bakeSamples(xs, 0, { tolerance: 0.2 }))+ .keys("y", bakeSamples(ys, 0, { tolerance: 0.2 }))+ .keys("width", bakeSamples(ws, 0, { tolerance: 0.2 }))+ .keys("rotation", bakeSamples(rs, 0, { tolerance: 0.05 })),+ );+ return node;+ };++ const parts: Record<string, Animatable<LayoutNode>> = {};+ const children: LayoutNode[] = [];+ const leader1 = segment("leader", (k) => [k.anchor, k.bend], seg1);+ children.push(leader1);+ parts.leader = leader1;+ if (props.elbow) {+ const leader2 = segment("leader-2", (k) => [k.bend, k.end], seg2);+ children.push(leader2);+ parts["leader-2"] = leader2;+ }+ if (props.dot) {+ const dot = host.box({+ id: ctx.partId("dot"),+ position: "absolute",+ x: (frames[0]?.anchor[0] ?? 0) - dotR,+ y: (frames[0]?.anchor[1] ?? 0) - dotR,+ width: dotR * 2,+ height: dotR * 2,+ background: color,+ borderRadius: dotR,+ borderColor: theme.color.bg,+ borderWidth: Math.max(2, 2 * s),+ });+ const pop = Array.from({ length: Math.min(length, intro) + 1 }, (_, f) =>+ springAt(f / fps, { stiffness: 320, damping: 16 }),+ );+ dot.animate(+ LayerAnimation.create()+ .keys(+ "x",+ bakeSamples(+ frames.map((k) => k.anchor[0] - dotR),+ 0,+ { tolerance: 0.2 },+ ),+ )+ .keys(+ "y",+ bakeSamples(+ frames.map((k) => k.anchor[1] - dotR),+ 0,+ { tolerance: 0.2 },+ ),+ )+ .keys("scale", bakeSamples(pop, 0, { tolerance: 0.005 })),+ );+ children.push(dot);+ parts.dot = dot;+ }+ const labelKids: LayoutNode[] = [];+ if (props.title && titleM)+ labelKids.push(+ host.text(props.title, {+ id: ctx.partId("title"),+ position: "absolute",+ x: padX,+ y: padY,+ fontFamily,+ fontSize: fs,+ fontWeight: 700,+ fill: theme.color.ink,+ }),+ );+ labelKids.push(+ host.text(props.text, {+ id: ctx.partId("text"),+ position: "absolute",+ x: padX,+ y: padY + (titleM?.height ?? 0),+ fontFamily,+ fontSize: fs * (props.title ? 0.85 : 1),+ fill: props.title ? theme.color.muted : theme.color.ink,+ }),+ );+ const label = host.box({+ id: ctx.partId("label"),+ position: "absolute",+ x: frames[0]?.label[0] ?? 0,+ y: frames[0]?.label[1] ?? 0,+ width: lw,+ height: lh,+ background: theme.color.raised,+ borderRadius: theme.radius.md,+ borderColor: color,+ borderWidth: Math.max(1.5, 1.5 * s),+ children: labelKids,+ });+ const rise = 10 * s;+ label.animate(+ LayerAnimation.create()+ .keys(+ "x",+ bakeSamples(+ frames.map((k) => k.label[0]),+ 0,+ { tolerance: 0.2 },+ ),+ )+ .keys(+ "y",+ bakeSamples(+ frames.map(+ (k, f) =>+ k.label[1] + rise * (1 - draw(f, labelAt, labelAt + base)),+ ),+ 0,+ { tolerance: 0.2 },+ ),+ )+ .keys("opacity", [+ [0, 0],+ [labelAt, 0],+ [labelAt + Math.round(base * 0.7), 1, "power2.out"],+ ]),+ );+ children.push(label);+ parts.label = label;++ return {+ children,+ width: W,+ height: H,+ duration: moving ? length : intro,+ openEnded: !moving,+ origin: [0, 0],+ cues: { in: [{ frame: labelAt + base }] } as CalloutCues,+ parts,+ };+ },+});diff --git a/packages/components/src/callout/meta.ts b/packages/components/src/callout/meta.tsnew file mode 100644index 00000000..a608e592--- /dev/null+++ b/packages/components/src/callout/meta.ts@@ -0,0 +1,19 @@+import { defineMeta } from "../core/meta.js";++export default defineMeta({+ name: "Callout",+ summary:+ "A label with a leader line pinned to a point, node, text or a moving tracked object; picks the open side and stays inside the frame.",+ tags: [+ "callout",+ "label",+ "leader line",+ "annotation",+ "tracking",+ "explainer",+ ],+ parts: ["leader", "leader-2", "dot", "label"],+ cues: ["in"],+ example: `Callout({ target: [820, 410], title: "New", text: "Faster renderer" })`,+ since: "M5",+});diff --git a/packages/components/src/chat-thread/index.test.ts b/packages/components/src/chat-thread/index.test.tsnew file mode 100644index 00000000..a2f26b98--- /dev/null+++ b/packages/components/src/chat-thread/index.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from "vitest";+import { bind } from "../core/contract.js";+import { fakeHost } from "../test/fake-host.js";+import { chatThread } from "./index.js";++const make = () => bind(fakeHost(), chatThread);+type Node = { id?: string; x?: 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;+};+const messages = [+ { from: "me", text: "Shipped?" },+ { from: "sam", text: "Yes, all of it." },+ { from: "me", text: "Nice", reaction: "❤️" },+];++describe("ChatThread", () => {+ it("lands the other side's replies after their typing dots", () => {+ const c = make()({ messages });+ expect(c.cues.typing).toHaveLength(1);+ expect(c.cues.messages[1]?.frame).toBe(c.cues.typing[0]?.end);+ for (let i = 1; i < c.cues.messages.length; i++)+ expect(c.cues.messages[i]?.frame).toBeGreaterThan(+ c.cues.messages[i - 1]?.frame ?? 0,+ );+ });++ it("puts me on the right, others on the left", () => {+ const c = make()({ id: "c", messages, width: 720 });+ expect(find(c, "c-bubble-0")?.x).toBeGreaterThan(360);+ expect(find(c, "c-bubble-1")?.x).toBeLessThan(100);+ });++ it("respects explicit times, draws hearts, and needs text or an image", () => {+ const c = make()({+ id: "c",+ messages: [+ { from: "a", text: "x", at: 50 },+ { from: "b", text: "y", at: 90 },+ ],+ });+ expect(c.cues.messages.map((m) => m.frame)).toEqual([50, 90]);+ expect(+ find(make()({ id: "c", messages }), "c-reaction-2-heart"),+ ).toBeDefined();+ expect(() => make()({ messages: [{ from: "a" }] })).toThrow(+ /needs `text` or `image`/,+ );+ });+});diff --git a/packages/components/src/chat-thread/index.ts b/packages/components/src/chat-thread/index.tsnew file mode 100644index 00000000..5bd46d3d--- /dev/null+++ b/packages/components/src/chat-thread/index.ts@@ -0,0 +1,525 @@+/**+ * ChatThread: a messaging conversation. Bubbles arrive from either side+ * with a spring, the other side types first (three bouncing dots), and the+ * thread scrolls to keep the newest message in view. Names, timestamps,+ * reactions and images included.+ */+import {+ type KeyframeTuple,+ LayerAnimation,+ type LayoutNode,+} from "@framefields/compositions/program";+import { z } from "zod";+import { springKeys } from "../core/bake.js";+import { defineComponent } from "../core/contract.js";+import type { Animatable } from "../core/host.js";+import { rangeRects } from "../core/text.js";++export interface ChatThreadCues {+ [name: string]: ReadonlyArray<{ frame: number }>;+ /** Each message as it lands. */+ messages: ReadonlyArray<{ frame: number; index: number; from: string }>;+ /** Each typing indicator, shown to removed. */+ typing: ReadonlyArray<{ frame: number; end: number; from: string }>;+}++function messageSchema() {+ return z+ .object({+ from: z.string(),+ text: z.string().optional(),+ /** An image (path or URL) instead of, or above, text. */+ image: z.string().optional(),+ /** Image width / height. */+ aspect: z+ .number()+ .positive()+ .default(4 / 3),+ /** Frame it lands. Default: after the previous one has been read. */+ at: z.number().int().min(0).optional(),+ /** A reaction pinned to the bubble (an emoji or short text). */+ reaction: z.string().optional(),+ /** A small timestamp under the bubble. */+ time: z.string().optional(),+ })+ .strict()+ .refine((m) => m.text !== undefined || m.image !== undefined, {+ message: "A message needs `text` or `image`.",+ });+}++const SPRING = { stiffness: 260, damping: 20 };++export const chatThread = /* @__PURE__ */ defineComponent({+ name: "ChatThread",+ props: () => ({+ messages: z.array(messageSchema()).min(1),+ /** Who is "me" (right side, accent bubbles). Default the first sender. */+ me: z.string().optional(),+ /** Display names and bubble colours per sender. */+ participants: z+ .record(+ z.string(),+ z+ .object({ name: z.string().optional(), color: z.string().optional() })+ .strict(),+ )+ .default({}),+ /** Names above the first bubble of each run (default: when more than two people talk). */+ names: z.boolean().optional(),+ /** Others type before they send. */+ typing: z.boolean().default(true),+ /** Reading speed between messages, characters a second. */+ readCps: z.number().positive().default(28),+ 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 W = ctx.requested.width ?? 720 * s;+ const H = ctx.requested.height ?? 960 * s;+ const fs = props.fontSize ?? 30 * s;+ const fontFamily = props.fontFamily ?? theme.font.body;+ const me = props.me ?? props.messages[0]?.from ?? "me";+ const senders = [...new Set(props.messages.map((m) => m.from))];+ const showNames = props.names ?? senders.length > 2;+ const pad = fs * 0.8;+ const padX = fs * 0.62;+ const padY = fs * 0.42;+ const maxW = W * 0.74;+ const radius = fs * 0.9;+ const smallFs = fs * 0.62;++ // ── Timing ────────────────────────────────────────────────────────+ const landed: number[] = [];+ const typingWindows: Array<{+ frame: number;+ end: number;+ from: string;+ index: number;+ }> = [];+ let t = Math.round(fps * 0.2);+ props.messages.forEach((m, i) => {+ const prev = props.messages[i - 1];+ if (prev && m.at === undefined) {+ const read = ((prev.text?.length ?? 12) / props.readCps) * fps;+ t += Math.round(Math.min(fps * 2.5, Math.max(fps * 0.5, read)));+ }+ let at = m.at ?? t;+ if (props.typing && m.from !== me && m.at === undefined) {+ const typingFor = Math.round(+ Math.min(2.2, Math.max(0.7, (m.text?.length ?? 10) / 14)) * fps,+ );+ typingWindows.push({+ frame: at,+ end: at + typingFor,+ from: m.from,+ index: i,+ });+ at += typingFor;+ }+ landed.push(at);+ t = at;+ });++ // ── Layout (top to bottom) ────────────────────────────────────────+ const measure = (text: string, size: number, width?: number) =>+ host.measure(text, {+ fontFamily,+ fontSize: size,+ ...(width !== undefined && { width }),+ });+ interface Slot {+ index: number;+ y: number;+ width: number;+ height: number;+ right: boolean;+ nameY?: number;+ timeY?: number;+ textH: number;+ imageH: number;+ }+ const slots: Slot[] = [];+ let y = pad;+ props.messages.forEach((m, i) => {+ const prev = props.messages[i - 1];+ const right = m.from === me;+ const newRun = !prev || prev.from !== m.from;+ if (prev) y += newRun ? fs * 0.75 : fs * 0.22;+ let nameY: number | undefined;+ if (showNames && newRun && !right) {+ nameY = y;+ y += measure("Ag", smallFs).height + fs * 0.12;+ }+ const inner = maxW - padX * 2;+ let textW = 0;+ let textH = 0;+ if (m.text) {+ const one = measure(m.text, fs);+ if (one.width <= inner) {+ textW = one.width;+ textH = one.height;+ } else {+ const wrapped = measure(m.text, fs, inner);+ textW = Math.max(+ ...rangeRects(wrapped, 0, m.text.length, {+ fontFamily,+ fontSize: fs,+ width: inner,+ }).map((r) => r.width),+ );+ textH = wrapped.height;+ }+ }+ const imageW = m.image ? maxW : 0;+ const imageH = m.image ? imageW / m.aspect : 0;+ const width = m.image ? maxW : textW + padX * 2;+ const height = imageH + (m.text ? textH + padY * 2 : 0);+ slots.push({ index: i, y, width, height, right, nameY, textH, imageH });+ y += height;+ if (m.time) {+ (slots[slots.length - 1] as Slot).timeY = y + fs * 0.12;+ y += measure(m.time, smallFs * 0.9).height + fs * 0.12;+ }+ });++ // ── Nodes ─────────────────────────────────────────────────────────+ const parts: Record<string, Animatable<LayoutNode>> = {};+ const content: LayoutNode[] = [];+ const colorOf = (from: string) =>+ props.participants[from]?.color ??+ (from === me ? theme.color.accent : theme.color.raised);+ const ink = (from: string) =>+ from === me && !props.participants[from]?.color+ ? "#ffffff"+ : theme.color.ink;+ const entry = (node: Animatable<LayoutNode>, at: number, baseY: number) =>+ node.animate(+ LayerAnimation.create()+ .keys("scale", springKeys(at, 0.6, 1, fps, SPRING))+ .keys("y", springKeys(at, baseY + fs * 0.5, baseY, fps, SPRING))+ .keys("opacity", [+ [at, 0],+ [at + Math.max(2, Math.round(fps * 0.12)), 1, "power2.out"],+ ]),+ );++ slots.forEach((slot) => {+ const m = props.messages[slot.index] as (typeof props.messages)[number];+ const at = landed[slot.index] as number;+ const x = slot.right ? W - pad - slot.width : pad;+ const children: LayoutNode[] = [];+ if (m.image) {+ children.push(+ host.box({+ id: ctx.partId(`image-${slot.index}`),+ position: "absolute",+ x: 0,+ y: 0,+ width: slot.width,+ height: slot.imageH,+ overflow: "hidden",+ borderRadius: radius,+ children: [+ host.media(m.image, {+ id: ctx.partId(`media-${slot.index}`),+ position: "absolute",+ x: 0,+ y: 0,+ width: slot.width,+ height: slot.imageH,+ fit: "cover",+ }),+ ],+ }),+ );+ }+ if (m.text)+ children.push(+ host.text(m.text, {+ id: ctx.partId(`text-${slot.index}`),+ position: "absolute",+ x: padX,+ y: slot.imageH + padY,+ width: slot.width - padX * 2 + 1,+ fontFamily,+ fontSize: fs,+ fill: ink(m.from),+ }),+ );+ const bubble = host.box({+ id: ctx.partId(`bubble-${slot.index}`),+ position: "absolute",+ x,+ y: slot.y,+ width: slot.width,+ height: slot.height,+ background: m.image && !m.text ? "rgba(0,0,0,0)" : colorOf(m.from),+ borderRadius: radius,+ // Springs grow from the corner the bubble comes from.+ anchorX: slot.right ? 1 : 0,+ anchorY: 1,+ children,+ });+ entry(bubble, at, slot.y);+ content.push(bubble);+ parts[`bubble-${slot.index}`] = bubble;++ const small = (+ id: string,+ text: string,+ size: number,+ tx: number,+ ty: number,+ ) => {+ const node = host.text(text, {+ id: ctx.partId(id),+ position: "absolute",+ x: tx,+ y: ty,+ fontFamily,+ fontSize: size,+ fill: theme.color.muted,+ });+ node.animate(+ LayerAnimation.keys("opacity", [+ [0, 0],+ [at, 0],+ [at + Math.round(fps * 0.25), 1, "power2.out"],+ ]),+ );+ content.push(node);+ };+ if (slot.nameY !== undefined)+ small(+ `name-${slot.index}`,+ props.participants[m.from]?.name ?? m.from,+ smallFs,+ x + padX * 0.5,+ slot.nameY,+ );+ if (slot.timeY !== undefined && m.time) {+ const tw = measure(m.time, smallFs * 0.9).width;+ small(+ `time-${slot.index}`,+ m.time,+ smallFs * 0.9,+ slot.right ? x + slot.width - tw - padX * 0.3 : x + padX * 0.3,+ slot.timeY,+ );+ }+ if (m.reaction) {+ // Hearts are drawn (most fonts have no emoji); anything else is text.+ const heart = /^(❤️?|♥️?|heart)$/u.test(m.reaction.trim());+ const rm = measure(heart ? "M" : m.reaction, fs * 0.7);+ const rh = rm.height + fs * 0.16;+ const rw = heart ? rh * 1.3 : rm.width + fs * 0.5;+ const rAt = at + Math.round(fps * 0.6);+ const pill = host.box({+ id: ctx.partId(`reaction-${slot.index}`),+ position: "absolute",+ x: slot.right ? x - rw * 0.35 : x + slot.width - rw * 0.65,+ y: slot.y + slot.height - rh * 0.45,+ width: rw,+ height: rh,+ background: theme.color.surface,+ borderRadius: rh / 2,+ borderColor: theme.color.bg,+ borderWidth: Math.max(2, fs * 0.08),+ children: [+ heart+ ? host.shape("path", {+ id: ctx.partId(`reaction-${slot.index}-heart`),+ position: "absolute",+ x: (rw - rh * 0.56) / 2,+ y: rh * 0.24,+ width: rh * 0.56,+ height: rh * 0.52,+ d: heartPath(rh * 0.56),+ fillType: "solid",+ fillColor: theme.color.negative,+ })+ : host.text(m.reaction, {+ id: ctx.partId(`reaction-${slot.index}-text`),+ position: "absolute",+ x: fs * 0.25,+ y: fs * 0.08,+ fontFamily,+ fontSize: fs * 0.7,+ fill: theme.color.ink,+ }),+ ],+ });+ pill.animate(+ LayerAnimation.create()+ .keys(+ "scale",+ springKeys(rAt, 0, 1, fps, { stiffness: 320, damping: 14 }),+ )+ .keys("opacity", [+ [0, 0],+ [rAt, 1, "hold"],+ ]),+ );+ content.push(pill);+ }+ });++ // Typing indicators sit where the message will land.+ const dot = fs * 0.24;+ typingWindows.forEach((w, k) => {+ const slot = slots[w.index] as Slot;+ const bw = dot * 3 + dot * 1.1 * 2 + padX * 2;+ const bh = Math.max(fs + padY * 2 - fs * 0.3, dot + padY * 2);+ const dots: LayoutNode[] = [0, 1, 2].map((d) => {+ const node = host.box({+ id: ctx.partId(`typing-${k}-dot-${d}`),+ position: "absolute",+ x: padX + d * dot * 2.1,+ y: (bh - dot) / 2,+ width: dot,+ height: dot,+ background: theme.color.muted,+ borderRadius: dot / 2,+ });+ // A wave through the dots, one bounce every 0.6 s.+ const period = Math.round(fps * 0.6);+ const keys: KeyframeTuple[] = [[0, (bh - dot) / 2]];+ for (+ let f = w.frame + d * Math.round(period / 5);+ f < w.end;+ f += period+ )+ keys.push(+ [f, (bh - dot) / 2],+ [+ f + Math.round(period / 4),+ (bh - dot) / 2 - dot * 0.7,+ "sine.out",+ ],+ [f + Math.round(period / 2), (bh - dot) / 2, "sine.in"],+ );+ node.animate(LayerAnimation.keys("y", ascending(keys)));+ return node;+ });+ const bubble = host.box({+ id: ctx.partId(`typing-${k}`),+ position: "absolute",+ x: pad,+ y: slot.y,+ width: bw,+ height: bh,+ background: colorOf(w.from),+ borderRadius: bh / 2,+ anchorX: 0,+ anchorY: 1,+ children: dots,+ });+ bubble.animate(+ LayerAnimation.create()+ .keys("scale", springKeys(w.frame, 0.5, 1, fps, SPRING))+ .keys("opacity", [+ [0, 0],+ [w.frame, 1, "hold"],+ [w.end, 0, "hold"],+ ]),+ );+ content.push(bubble);+ });++ // ── Scroll: keep the newest bubble (or typing dots) in view ───────+ const events = [+ ...slots.map((sl) => ({+ frame: landed[sl.index] as number,+ bottom: sl.y + sl.height + (sl.timeY !== undefined ? fs : 0),+ })),+ ...typingWindows.map((w) => ({+ frame: w.frame,+ bottom: (slots[w.index] as Slot).y + fs * 1.6,+ })),+ ].sort((a, b) => a.frame - b.frame);+ const scroll: KeyframeTuple[] = [[0, 0]];+ let top = 0;+ const glide = Math.round(fps * 0.35);+ for (const e of events) {+ const want = Math.min(0, H - pad - e.bottom);+ if (want >= top) continue;+ const last = scroll[scroll.length - 1] as KeyframeTuple;+ if (e.frame > last[0]) scroll.push([e.frame, top]);+ scroll.push([Math.max(e.frame, last[0]) + glide, want, "power3.out"]);+ top = want;+ }+ const column = host.box({+ id: ctx.partId("column"),+ position: "absolute",+ x: 0,+ y: 0,+ width: W,+ height: Math.max(H, y + pad),+ children: content,+ });+ column.animate(LayerAnimation.keys("y", ascending(scroll)));+ const viewport = host.box({+ id: ctx.partId("viewport"),+ position: "absolute",+ x: 0,+ y: 0,+ width: W,+ height: H,+ overflow: "hidden",+ children: [column],+ });+ parts.column = column;+ parts.viewport = viewport;++ const lastAt = Math.max(...landed);+ return {+ children: [viewport],+ width: W,+ height: H,+ duration: lastAt + Math.round(fps * 0.8),+ openEnded: true,+ cues: {+ messages: landed.map((frame, index) => ({+ frame,+ index,+ from: props.messages[index]?.from ?? "",+ })),+ typing: typingWindows.map(({ frame, end, from }) => ({+ frame,+ end,+ from,+ })),+ } as ChatThreadCues,+ parts,+ };+ },+});++/** A heart `size` wide, top-left at 0, 0 (two lobes and a point). */+function heartPath(size: number): string {+ const w = size;+ const h = size * 0.92;+ return [+ `M${w / 2} ${h}`,+ `C${w * 0.18} ${h * 0.72} 0 ${h * 0.5} 0 ${h * 0.28}`,+ `C0 ${h * 0.1} ${w * 0.14} 0 ${w * 0.28} 0`,+ `C${w * 0.39} 0 ${w * 0.47} ${h * 0.07} ${w / 2} ${h * 0.16}`,+ `C${w * 0.53} ${h * 0.07} ${w * 0.61} 0 ${w * 0.72} 0`,+ `C${w * 0.86} 0 ${w} ${h * 0.1} ${w} ${h * 0.28}`,+ `C${w} ${h * 0.5} ${w * 0.82} ${h * 0.72} ${w / 2} ${h} Z`,+ ].join(" ");+}++function ascending(keys: KeyframeTuple[]): KeyframeTuple[] {+ const out: KeyframeTuple[] = [];+ for (const k of [...keys].sort((a, b) => a[0] - b[0])) {+ while (out.length > 0 && (out[out.length - 1] as KeyframeTuple)[0] >= k[0])+ out.pop();+ out.push(k);+ }+ return out;+}diff --git a/packages/components/src/chat-thread/meta.ts b/packages/components/src/chat-thread/meta.tsnew file mode 100644index 00000000..d67ffbf8--- /dev/null+++ b/packages/components/src/chat-thread/meta.ts@@ -0,0 +1,12 @@+import { defineMeta } from "../core/meta.js";++export default defineMeta({+ name: "ChatThread",+ summary:+ "A messaging conversation: bubbles that spring in from either side, typing dots before replies, names, timestamps, reactions, images and auto-scroll.",+ tags: ["chat", "messages", "conversation", "social", "ui", "demo"],+ parts: ["viewport", "column", "bubble-<n>", "typing-<n>", "reaction-<n>"],+ cues: ["messages", "typing"],+ example: `ChatThread({ messages: [{ from: "me", text: "Shipped?" }, { from: "sam", text: "Live!", reaction: "🎉" }] })`,+ since: "M5",+});diff --git a/packages/components/src/code-block/index.test.ts b/packages/components/src/code-block/index.test.tsindex 13e646cc..45245bd7 100644--- a/packages/components/src/code-block/index.test.ts+++ b/packages/components/src/code-block/index.test.ts@@ -55,7 +55,7 @@ describe("CodeBlock", () => {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(ys).toEqual([0, 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);diff --git a/packages/components/src/confetti/index.test.ts b/packages/components/src/confetti/index.test.tsnew file mode 100644index 00000000..af167c0a--- /dev/null+++ b/packages/components/src/confetti/index.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from "vitest";+import { bind } from "../core/contract.js";+import { fakeHost } from "../test/fake-host.js";+import { confetti } from "./index.js";++type Node = {+ id?: string;+ kind?: string;+ children?: Node[];+ color?: unknown;+ seed?: number;+ floor?: number;+ emitter?: {+ x: number;+ y: number;+ bursts: Array<{ frame: number; count: number }>;+ };+};+const systems = (n: unknown): Node[] => {+ const out: Node[] = [];+ const walk = (x: Node) => {+ if (x.kind === "particles") out.push(x);+ for (const c of x.children ?? []) walk(c);+ };+ walk(n as Node);+ return out;+};++describe("Confetti", () => {+ it("one paper system per colour, plus ribbons and sparkles, sharing an origin", () => {+ const c = bind(+ fakeHost(),+ confetti,+ )({+ bursts: [+ { at: 10, origin: [500, 900] },+ { at: 40, origin: [500, 900] },+ ],+ palette: ["#f00", "#0f0"],+ });+ const all = systems(c);+ expect(all).toHaveLength(4);+ expect(all[0]?.emitter?.bursts.map((b) => b.frame)).toEqual([10, 40]);+ expect(new Set(all.map((s) => s.seed)).size).toBe(4);+ expect(c.cues.bursts.map((b) => b.origin)).toEqual([+ [500, 900],+ [500, 900],+ ]);+ });++ it("separate origins get their own systems; a floor lands them", () => {+ const c = bind(+ fakeHost(),+ confetti,+ )({+ bursts: [+ { at: 0, origin: [100, 900] },+ { at: 0, origin: [1800, 900] },+ ],+ palette: ["#f00"],+ ribbons: false,+ sparkles: false,+ floor: true,+ height: 1000,+ });+ const all = systems(c);+ expect(all).toHaveLength(2);+ expect(all[0]?.floor).toBeCloseTo(994, 5);+ });+});diff --git a/packages/components/src/confetti/index.ts b/packages/components/src/confetti/index.tsnew file mode 100644index 00000000..700a3216--- /dev/null+++ b/packages/components/src/confetti/index.ts@@ -0,0 +1,199 @@+/**+ * Confetti: celebration bursts of paper, ribbons and sparkles that arc up,+ * flutter down and, with a floor, settle. Simulated on the GPU (one particle+ * system per palette colour and origin), deterministic per seed; bursts can+ * come straight from another component's cues.+ *+ * Coordinates are the frame's: the root covers the video (default+ * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.+ */+import type { LayoutNode } from "@framefields/compositions/program";+import { z } from "zod";+import { defineComponent } from "../core/contract.js";+import type { Animatable, ParticleOptions } from "../core/host.js";+import type { Vec2 } from "../core/path.js";+import { targetSchema } from "../core/schemas.js";+import { resolveTarget, targetPoint } from "../core/targets.js";++export interface ConfettiCues {+ [name: string]: ReadonlyArray<{ frame: number }>;+ bursts: ReadonlyArray<{ frame: number; origin: Vec2 }>;+}++export const confetti = /* @__PURE__ */ defineComponent({+ name: "Confetti",+ props: () => ({+ bursts: z+ .array(+ z+ .object({+ at: z.number().int().min(0),+ /** Where it bursts from: a point, rect, node or text. */+ origin: targetSchema(),+ /** Paper pieces in this burst. */+ count: z.number().int().positive().default(140),+ /** Launch direction, degrees (−90 = up). */+ direction: z.number().default(-90),+ /** Cone width, degrees. */+ spread: z.number().min(0).max(360).default(70),+ /** Launch strength multiplier. */+ power: z.number().positive().default(1),+ })+ .strict(),+ )+ .min(1),+ /** Paper colours. Default: the theme's accents. */+ palette: z.array(z.string()).min(1).optional(),+ /** px/s². */+ gravity: z.number().min(0).optional(),+ /** A floor that pieces land on: `true` for the frame's bottom, or a y. */+ floor: z.union([z.boolean(), z.number()]).default(false),+ /** Fine streamers among the paper. */+ ribbons: z.boolean().default(true),+ /** A flash of glints at each burst. */+ sparkles: z.boolean().default(true),+ }),+ defaults: { enter: false, exit: false },+ 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 c = theme.color;+ const palette = props.palette ?? [+ c.accent,+ c.accent2,+ c.highlight,+ c.positive,+ c.negative,+ ];+ const gravity = props.gravity ?? 1500 * s;+ const floor =+ props.floor === false+ ? undefined+ : props.floor === true+ ? H - 6 * s+ : props.floor;+ const lifetime: [number, number] =+ floor === undefined ? [2.6, 4] : [5, 6.5];++ // Bursts that share an origin share systems.+ const origins = new Map<+ string,+ { point: Vec2; bursts: Array<(typeof props.bursts)[number]> }+ >();+ const cues: Array<{ frame: number; origin: Vec2 }> = [];+ for (const b of props.bursts) {+ const point = targetPoint(+ resolveTarget(b.origin, { measure: host.measure, fps }),+ b.at,+ );+ const key = `${point[0].toFixed(1)},${point[1].toFixed(1)},${b.direction},${b.spread},${b.power}`;+ const entry = origins.get(key) ?? { point, bursts: [] };+ entry.bursts.push(b);+ origins.set(key, entry);+ cues.push({ frame: b.at, origin: point });+ }++ const parts: Record<string, Animatable<LayoutNode>> = {};+ const children: LayoutNode[] = [];+ let n = 0;+ const system = (+ name: string,+ o: Omit<ParticleOptions, "x" | "y" | "width" | "height" | "id" | "seed">,+ ) => {+ const node = host.particles({+ id: ctx.partId(name),+ x: 0,+ y: 0,+ width: W,+ height: H,+ seed: ctx.seed * 101 + n++,+ ...o,+ });+ parts[name] = node;+ children.push(node);+ };++ [...origins.values()].forEach(({ point, bursts }, o) => {+ const first = bursts[0] as (typeof bursts)[number];+ const emitter = (share: number) => ({+ shape: "point" as const,+ x: point[0],+ y: point[1],+ rate: 0,+ bursts: bursts.map((b) => ({+ frame: b.at,+ count: Math.max(1, Math.round(b.count * share)),+ })),+ });+ const total = Math.max(...bursts.map((b) => b.count));+ const launch = {+ direction: first.direction,+ spread: first.spread,+ speed: [1100 * s * first.power, 2100 * s * first.power] as [+ number,+ number,+ ],+ gravity,+ drag: 1.1,+ // Paper wanders as it falls: curl noise reads as flutter.+ noise: { strength: 260 * s, scale: 0.004 / s, speed: 1.4 },+ lifetime,+ ...(floor !== undefined && { floor, bounce: 0.08 }),+ };+ palette.forEach((color, k) => {+ system(`paper-${o}-${k}`, {+ ...launch,+ max: Math.ceil(total / palette.length) * bursts.length + 8,+ emitter: emitter(1 / palette.length),+ shape: "square",+ size: [13 * s, 11 * s],+ sizeJitter: 0.45,+ fade: [0.01, floor === undefined ? 0.25 : 0.12],+ color,+ });+ });+ if (props.ribbons)+ system(`ribbons-${o}`, {+ ...launch,+ max: Math.ceil(total * 0.2) * bursts.length + 8,+ emitter: emitter(0.2),+ shape: "spark",+ stretch: 0.03,+ size: [5 * s, 4 * s],+ sizeJitter: 0.3,+ fade: [0.01, 0.3],+ color: palette.slice(0, 3),+ });+ if (props.sparkles)+ system(`sparkles-${o}`, {+ max: 80 * bursts.length,+ emitter: emitter(0.35),+ direction: first.direction,+ spread: Math.min(360, first.spread * 1.6),+ speed: [300 * s, 900 * s],+ gravity: gravity * 0.15,+ drag: 2.4,+ lifetime: [0.35, 0.8],+ shape: "soft",+ size: [14 * s, 0],+ sizeJitter: 0.5,+ fade: [0, 0.5],+ blend: "add",+ color: ["#ffffff", c.highlight],+ });+ });++ const last = Math.max(...props.bursts.map((b) => b.at));+ return {+ children,+ width: W,+ height: H,+ duration: last + Math.ceil(lifetime[1] * fps),+ origin: [0, 0],+ cues: { bursts: cues } as ConfettiCues,+ parts,+ };+ },+});diff --git a/packages/components/src/confetti/meta.ts b/packages/components/src/confetti/meta.tsnew file mode 100644index 00000000..8fcce2fb--- /dev/null+++ b/packages/components/src/confetti/meta.ts@@ -0,0 +1,12 @@+import { defineMeta } from "../core/meta.js";++export default defineMeta({+ name: "Confetti",+ summary:+ "Celebration bursts of paper, ribbons and sparkles on the GPU that arc up, flutter down and can settle on a floor; bursts can follow cues.",+ tags: ["confetti", "celebration", "particles", "burst", "success", "party"],+ parts: ["paper-<o>-<n>", "ribbons-<o>", "sparkles-<o>"],+ cues: ["bursts"],+ example: `Confetti({ bursts: [{ at: 30, origin: [960, 900] }], floor: true })`,+ since: "M5",+});diff --git a/packages/components/src/core/bake.ts b/packages/components/src/core/bake.tsindex 553690bf..f6d28ba9 100644--- a/packages/components/src/core/bake.ts+++ b/packages/components/src/core/bake.ts@@ -115,3 +115,22 @@ export function springSettleFrames(}return Math.min(max, last + 1);}++/**+ * A spring from `from` to `to` starting at frame `start`, baked to linear+ * keys (within `tolerance`, default 0.2 % of the distance).+ */+export function springKeys(+ start: number,+ from: number,+ to: number,+ fps: number,+ options?: Parameters<typeof springAt>[1],+ tolerance = Math.max(1e-4, Math.abs(to - from) * 0.002),+): BakedKey[] {+ const frames = springSettleFrames(fps, options);+ const values = Array.from({ length: frames + 1 }, (_, f) =>+ f === frames ? to : from + (to - from) * springAt(f / fps, options),+ );+ return bakeSamples(values, start, { tolerance });+}diff --git a/packages/components/src/core/contract.test.ts b/packages/components/src/core/contract.test.tsindex 80345585..b8c5bd64 100644--- a/packages/components/src/core/contract.test.ts+++ b/packages/components/src/core/contract.test.ts@@ -1,3 +1,4 @@+import { LayerAnimation } from "@framefields/compositions/program";import { describe, expect, it } from "vitest";import { z } from "zod";import { fakeHost } from "../test/fake-host.js";@@ -184,3 +185,46 @@ describe("component lifetimes", () => {expect(tracks[0]?.keyframes[0]?.value).toBe(50);});});++describe("first keys", () => {+ it("hold from frame 0 in every track of the tree (the renderer shows base values before them)", () => {+ const late = defineComponent({+ name: "Late",+ props: () => ({ tag: z.string().optional() }),+ build: (ctx) => {+ const child = ctx.host.box({ id: ctx.partId("child") });+ child.animate(+ LayerAnimation.keys("opacity", [+ [40, 0],+ [44, 1],+ ]),+ );+ return {+ children: [child],+ width: 10,+ height: 10,+ duration: 50,+ cues: {},+ };+ },+ });+ const node = bind(fakeHost(), late)({ id: "l" }) as unknown as {+ children: Array<{+ children: Array<{+ animation: {+ tracks: Array<{+ keyframes: Array<{ frame: number; value: number }>;+ }>;+ };+ }>;+ }>;+ };+ const keys =+ node.children[0]?.children[0]?.animation.tracks[0]?.keyframes ?? [];+ expect(keys.map((k) => [k.frame, k.value])).toEqual([+ [0, 0],+ [40, 0],+ [44, 1],+ ]);+ });+});diff --git a/packages/components/src/core/contract.ts b/packages/components/src/core/contract.tsindex 5a70ae97..f434bbf3 100644--- a/packages/components/src/core/contract.ts+++ b/packages/components/src/core/contract.ts@@ -425,6 +425,7 @@ function assemble<S extends z.ZodRawShape, C extends Cues, E extends object>(stage,};props.customize?.(parts);+ holdFirstKeys(root);const start = props.at ?? 0;const cues = offsetCues(built.cues, start);@@ -455,3 +456,35 @@ function assemble<S extends z.ZodRawShape, C extends Cues, E extends object>(}return root as ComponentNode<C> & E;}++interface KeyedNode {+ animation?: {+ tracks?: Array<{+ repeat?: number;+ keyframes?: Array<{ id: string; frame: number; value: unknown }>;+ }>;+ };+ children?: unknown[];+ matte?: { node?: unknown };+}++/**+ * Before a track's first keyframe the renderer shows the node's base value,+ * not the first key's. Components always mean "hold the first key" (a+ * bubble invisible until it lands, a stroke undrawn until it starts), so+ * every track in the tree gets its first value pinned at frame 0.+ */+export function holdFirstKeys(node: unknown): void {+ const n = node as KeyedNode;+ for (const track of n.animation?.tracks ?? []) {+ const first = track.keyframes?.[0];+ if (!first || first.frame <= 0 || track.repeat) continue;+ track.keyframes?.unshift({+ id: `${first.id}-hold`,+ frame: 0,+ value: first.value,+ });+ }+ for (const child of n.children ?? []) holdFirstKeys(child);+ if (n.matte?.node) holdFirstKeys(n.matte.node);+}diff --git a/packages/components/src/core/host.ts b/packages/components/src/core/host.tsindex a09ab79e..d372555f 100644--- a/packages/components/src/core/host.ts+++ b/packages/components/src/core/host.ts@@ -84,14 +84,65 @@ export interface Host {style<T extends Animatable<LayoutNode>>(node: T, config: LayerStyleConfig): T;/*** Mask `node` by `matte`'s alpha (a box: solid or CSS-gradient- * background). The matte is laid out like a sibling of `node`; returns `node`.+ * background), or by its inverse (`"alpha-inverted"`: show `node`+ * everywhere the matte is not). The matte is laid out like a sibling of+ * `node`; returns `node`.*/- matte<T extends Animatable<LayoutNode>>(node: T, matte: LayoutNode): T;+ matte<T extends Animatable<LayoutNode>>(+ node: T,+ matte: LayoutNode,+ mode?: "alpha" | "alpha-inverted",+ ): T;/*** A video showing only its person / subject (vision segmentation), the* rest transparent: stacked over captions so text passes behind them.*/cutout(source: string, options: CutoutOptions): Animatable<LayoutNode>;+ /** A GPU particle system layer. */+ particles(options: ParticleOptions): Animatable<LayoutNode>;+}++/** A GPU particle system (framefields' `Layer.particles`), as plain data. */+export interface ParticleOptions {+ id?: string;+ x: number;+ y: number;+ width: number;+ height: number;+ seed?: number;+ /** Most particles alive at once. */+ max?: number;+ emitter: {+ shape: "point";+ x: number;+ y: number;+ /** Particles a second (0 for bursts only). */+ rate: number;+ bursts: Array<{ frame: number; count: number }>;+ };+ /** Seconds each particle lives. */+ lifetime?: [number, number];+ /** Launch speed, px/s. */+ speed?: [number, number];+ /** Degrees, 0 = right, -90 = up. */+ direction?: number;+ spread?: number;+ /** px/s², down. */+ gravity?: number;+ drag?: number;+ noise?: { strength: number; scale: number; speed: number };+ /** A floor line (layer px) particles bounce on and settle. */+ floor?: number;+ bounce?: number;+ /** px at birth → death. */+ size?: [number, number];+ sizeJitter?: number;+ fade?: [number, number];+ shape?: "circle" | "soft" | "square" | "spark";+ stretch?: number;+ blend?: "normal" | "add" | "screen";+ color?: string | string[];+ opacity?: number;}export interface CutoutOptions extends MediaOptions {diff --git a/packages/components/src/ids.test.ts b/packages/components/src/ids.test.tsindex ed47cb14..1456b2c4 100644--- a/packages/components/src/ids.test.ts+++ b/packages/components/src/ids.test.ts@@ -1,18 +1,23 @@import { describe, expect, it } from "vitest";import { annotate } from "./annotate/index.js";import { appFrame } from "./app-frame/index.js";+import { callout } from "./callout/index.js";import { captions } from "./captions/index.js";+import { chatThread } from "./chat-thread/index.js";import { codeBlock } from "./code-block/index.js";+import { confetti } from "./confetti/index.js";import { bind } from "./core/contract.js";import { counter } from "./counter/index.js";import { 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 { spotlight } from "./spotlight/index.js";import { terminal } from "./terminal/index.js";import { fakeHost } from "./test/fake-host.js";import { textReveal } from "./text-reveal/index.js";import { titleCard } from "./title-card/index.js";+import { toasts } from "./toasts/index.js";/*** The renderer keys layout and motion by node id: two nodes with one id@@ -211,6 +216,65 @@ const cases: Array<[string, () => unknown]> = [)({ value: kind === "stars" ? 3.5 : 60, kind, label: "L" }),] as [string, () => unknown],),+ [+ "ChatThread",+ () =>+ bind(+ fakeHost(),+ chatThread,+ )({+ messages: [+ { from: "me", text: "a", reaction: "❤️" },+ { from: "b", text: "c", time: "1:00" },+ { from: "c", image: "x.png" },+ ],+ }),+ ],+ [+ "Toasts",+ () =>+ bind(+ fakeHost(),+ toasts,+ )({+ items: [+ { at: 0, title: "a", body: "b", kind: "success" },+ { at: 10, title: "c", kind: "error" },+ ],+ }),+ ],+ [+ "Callout",+ () =>+ bind(fakeHost(), callout)({ target: [100, 100], title: "t", text: "x" }),+ ],+ [+ "Spotlight",+ () =>+ bind(+ fakeHost(),+ spotlight,+ )({+ targets: [+ { at: 0, target: [10, 10] },+ { at: 20, target: "full" },+ ],+ shape: "ellipse",+ }),+ ],+ [+ "Confetti",+ () =>+ bind(+ fakeHost(),+ confetti,+ )({+ bursts: [+ { at: 0, origin: [10, 10] },+ { at: 5, origin: [90, 10] },+ ],+ }),+ ],];describe("node ids", () => {diff --git a/packages/components/src/index.ts b/packages/components/src/index.tsindex 026ec0d2..7715d21e 100644--- a/packages/components/src/index.ts+++ b/packages/components/src/index.ts@@ -16,6 +16,12 @@ export {type AppFrameKind,appFrame,} from "./app-frame/index.js";+export {+ CALLOUT_SIDES,+ type CalloutCues,+ type CalloutSide,+ callout,+} from "./callout/index.js";export {CAPTION_STYLES,type CaptionStyle,@@ -23,6 +29,7 @@ export {captions,type Word,} from "./captions/index.js";+export { type ChatThreadCues, chatThread } from "./chat-thread/index.js";export {CODE_LANGS,type CodeBlockCues,@@ -32,12 +39,14 @@ export {type TokenKind,} from "./code-block/index.js";export { tokenize } from "./code-block/tokenize.js";+export { type ConfettiCues, confetti } from "./confetti/index.js";export {type BakedKey,type BakeOptions,bakeFunction,bakeSamples,springAt,+ springKeys,springSettleFrames,} from "./core/bake.js";export {@@ -94,6 +103,7 @@ export type {Host,LayerStyleConfig,MediaOptions,+ ParticleOptions,} from "./core/host.js";export { type ComponentMeta, defineMeta } from "./core/meta.js";export {@@ -193,6 +203,7 @@ export {mousePointer,type Waypoint,} from "./mouse-pointer/index.js";+export { type SpotlightCues, spotlight } from "./spotlight/index.js";export {type TerminalCues,type TerminalStep,@@ -213,3 +224,12 @@ export {type TitleLayout,titleCard,} from "./title-card/index.js";+export {+ springTrack,+ TOAST_CORNERS,+ TOAST_KINDS,+ type ToastCorner,+ type ToastKind,+ type ToastsCues,+ toasts,+} from "./toasts/index.js";diff --git a/packages/components/src/spotlight/index.test.ts b/packages/components/src/spotlight/index.test.tsnew file mode 100644index 00000000..bb0495c4--- /dev/null+++ b/packages/components/src/spotlight/index.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";+import { bind } from "../core/contract.js";+import { fakeHost } from "../test/fake-host.js";+import { spotlight } from "./index.js";++const make = () => bind(fakeHost(), spotlight);+type Node = {+ id?: string;+ children?: Node[];+ matte?: { node: Node; mode: string };+ animation?: {+ tracks: Array<{+ prop: string;+ keyframes: Array<{ frame: number; value: number }>;+ }>;+ };+};+const keys = (n: Node | undefined, prop: string) =>+ (n?.animation?.tracks.find((t) => t.prop === prop)?.keyframes ?? []).map(+ (k) => [k.frame, k.value],+ );++describe("Spotlight", () => {+ it("dims through an inverted matte whose hole glides between targets", () => {+ const s = make()({+ id: "s",+ glide: 10,+ targets: [+ {+ at: 0,+ target: { x: 100, y: 100, width: 50, height: 50 },+ padding: 0,+ },+ {+ at: 30,+ target: { x: 400, y: 200, width: 50, height: 50 },+ padding: 0,+ },+ ],+ });+ const dim = ((s as unknown as Node).children?.[0]?.children ??+ [])[0] as Node;+ expect(dim.matte?.mode).toBe("alpha-inverted");+ expect(keys(dim.matte?.node, "x")).toEqual([+ [0, 100],+ [30, 100],+ [40, 400],+ ]);+ expect(keys(dim, "opacity").at(-1)).toEqual([10, 0.68]);+ expect(s.cues.moves).toEqual([+ { frame: 0, end: 10 },+ { frame: 30, end: 40 },+ ]);+ });++ it('lifts the dim on "full"', () => {+ const s = make()({+ glide: 8,+ targets: [+ { at: 0, target: [10, 10] },+ { at: 40, target: "full" },+ ],+ });+ const dim = ((s as unknown as Node).children?.[0]?.children ??+ [])[0] as Node;+ expect(keys(dim, "opacity").at(-1)).toEqual([48, 0]);+ });+});diff --git a/packages/components/src/spotlight/index.ts b/packages/components/src/spotlight/index.tsnew file mode 100644index 00000000..51da918a--- /dev/null+++ b/packages/components/src/spotlight/index.ts@@ -0,0 +1,214 @@+/**+ * Spotlight: dims the frame except a region that glides between targets.+ * The dim layer is masked by an inverted matte (the hole), keyed between+ * target rects; a `"full"` step lifts the dim.+ *+ * Coordinates are the frame's: the root covers the video (default+ * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.+ */+import {+ type KeyframeTuple,+ LayerAnimation,+ type LayoutNode,+} from "@framefields/compositions/program";+import { z } from "zod";+import { bakeSamples } from "../core/bake.js";+import { defineComponent } from "../core/contract.js";+import type { Rect } from "../core/draw.js";+import type { Animatable } from "../core/host.js";+import { targetSchema } from "../core/schemas.js";+import { boundsOf, resolveTarget } from "../core/targets.js";+import { themeFrames } from "../core/theme.js";++export interface SpotlightCues {+ [name: string]: ReadonlyArray<{ frame: number }>;+ /** Each move of the light, start to settle. */+ moves: ReadonlyArray<{ frame: number; end: number }>;+}++export const spotlight = /* @__PURE__ */ defineComponent({+ name: "Spotlight",+ props: () => ({+ /** Where the light goes and when; `"full"` lifts the dim. */+ targets: z+ .array(+ z+ .object({+ at: z.number().int().min(0),+ target: z.union([z.literal("full"), targetSchema()]),+ padding: z.number().min(0).optional(),+ })+ .strict(),+ )+ .min(1),+ /** How dark the rest gets, 0–1. */+ dim: z.number().min(0).max(1).default(0.68),+ color: z.string().default("#000000"),+ /** `rect`: rounded, crisp. `ellipse`: soft-edged pool of light. */+ shape: z.enum(["rect", "ellipse"]).default("rect"),+ radius: z.number().min(0).optional(),+ /** Soft edge of the ellipse, px. */+ feather: z.number().min(0).optional(),+ /** Frames each move takes. */+ glide: z.number().int().positive().optional(),+ /** Frames to follow a moving target before the next step. Default 6 seconds. */+ follow: z.number().int().positive().optional(),+ }),+ defaults: { enter: false, exit: false },+ 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 glide =+ props.glide ?? Math.round(themeFrames(theme, "base", fps) * 1.6);+ const ease = theme.motion.ease.move;+ const feather = props.feather ?? 60 * s;+ const ellipse = props.shape === "ellipse";+ const steps = [...props.targets].sort((a, b) => a.at - b.at);++ // The hole's rect at each step (moving targets: one per frame until the next step).+ const keys = {+ x: [] as KeyframeTuple[],+ y: [] as KeyframeTuple[],+ width: [] as KeyframeTuple[],+ height: [] as KeyframeTuple[],+ };+ const dimKeys: KeyframeTuple[] = [[0, 0]];+ const moves: Array<{ frame: number; end: number }> = [];+ let lit = false;+ let current: Rect | null = null;+ const grow = (r: Rect, pad: number): Rect => {+ // An ellipse needs room around the rect to contain it, plus its soft edge.+ const k = ellipse ? Math.SQRT2 : 1;+ const w = r.width * k + pad * 2 + (ellipse ? feather * 2 : 0);+ const h = r.height * k + pad * 2 + (ellipse ? feather * 2 : 0);+ return {+ x: r.x + r.width / 2 - w / 2,+ y: r.y + r.height / 2 - h / 2,+ width: w,+ height: h,+ };+ };+ const put = (f: number, r: Rect, ease_?: string) => {+ for (const k of ["x", "y", "width", "height"] as const)+ keys[k].push(ease_ ? [f, r[k], ease_] : [f, r[k]]);+ };++ steps.forEach((step, i) => {+ const next = steps[i + 1]?.at ?? step.at + (props.follow ?? fps * 6);+ if (step.target === "full") {+ if (lit)+ dimKeys.push(+ [step.at, props.dim],+ [step.at + glide, 0, "power2.inOut"],+ );+ lit = false;+ return;+ }+ const pad = step.padding ?? 16 * s;+ const resolved = resolveTarget(step.target, {+ measure: host.measure,+ fps,+ });+ const rectAt = (f: number) =>+ grow(+ resolved.kind === "static"+ ? boundsOf(resolved.rects)+ : resolved.at(f),+ pad,+ );+ const first = rectAt(step.at + glide);+ if (!current) {+ // The first light appears where it lands, as the dim comes up.+ put(step.at, first);+ } else {+ put(step.at, current);+ put(step.at + glide, first, ease);+ }+ if (!lit)+ dimKeys.push(+ [step.at, 0],+ [step.at + glide, props.dim, "power2.inOut"],+ );+ lit = true;+ moves.push({ frame: step.at, end: step.at + glide });+ current = first;+ if (resolved.kind === "dynamic") {+ // Ride the moving target until the next step.+ const from = step.at + glide;+ const samples = Array.from(+ { length: Math.max(1, next - from) },+ (_, k) => rectAt(from + k),+ );+ for (const k of ["x", "y", "width", "height"] as const)+ for (const [f, v] of bakeSamples(+ samples.map((r) => r[k]),+ from,+ { tolerance: 0.4 },+ ).slice(1))+ keys[k].push([f, v]);+ current = samples[samples.length - 1] ?? first;+ }+ });++ const start = current ?? { x: W / 2, y: H / 2, width: 0, height: 0 };+ const firstKey = (k: "x" | "y" | "width" | "height") =>+ (keys[k][0]?.[1] as number | undefined) ?? start[k];+ const radius = props.radius ?? 18 * s;+ const hole = host.box({+ id: ctx.partId("hole"),+ position: "absolute",+ x: firstKey("x"),+ y: firstKey("y"),+ width: firstKey("width"),+ height: firstKey("height"),+ background: ellipse+ ? `radial-gradient(closest-side, #ffffff ${Math.max(0, 100 - (feather / Math.max(1, Math.min(firstKey("width"), firstKey("height")) / 2)) * 100).toFixed(1)}%, rgba(255,255,255,0) 100%)`+ : "#ffffff",+ ...(!ellipse && { borderRadius: radius }),+ });+ hole.animate(+ LayerAnimation.create()+ .keys("x", ascending(keys.x))+ .keys("y", ascending(keys.y))+ .keys("width", ascending(keys.width))+ .keys("height", ascending(keys.height)),+ );+ const shade = host.box({+ id: ctx.partId("dim"),+ position: "absolute",+ x: 0,+ y: 0,+ width: W,+ height: H,+ background: props.color,+ opacity: 0,+ });+ shade.animate(LayerAnimation.keys("opacity", ascending(dimKeys)));+ host.matte(shade, hole, "alpha-inverted");+ const parts: Record<string, Animatable<LayoutNode>> = { dim: shade, hole };++ const lastStep = steps[steps.length - 1] as (typeof steps)[number];+ return {+ children: [shade],+ width: W,+ height: H,+ duration: lastStep.at + glide,+ openEnded: true,+ origin: [0, 0],+ cues: { moves } as SpotlightCues,+ parts,+ };+ },+});++function ascending(keys: KeyframeTuple[]): KeyframeTuple[] {+ const out: KeyframeTuple[] = [];+ for (const k of keys) {+ while (out.length > 0 && (out[out.length - 1] as KeyframeTuple)[0] >= k[0])+ out.pop();+ out.push(k);+ }+ return out.length > 0 ? out : [[0, 0]];+}diff --git a/packages/components/src/spotlight/meta.ts b/packages/components/src/spotlight/meta.tsnew file mode 100644index 00000000..42649e52--- /dev/null+++ b/packages/components/src/spotlight/meta.ts@@ -0,0 +1,12 @@+import { defineMeta } from "../core/meta.js";++export default defineMeta({+ name: "Spotlight",+ summary:+ "Dims the frame except a region that glides between targets, as a crisp rounded rect or a soft pool of light.",+ tags: ["spotlight", "focus", "dim", "highlight", "tutorial", "ui"],+ parts: ["dim", "hole"],+ cues: ["moves"],+ example: `Spotlight({ targets: [{ at: 0, target: button }, { at: 60, target: menu }] })`,+ since: "M5",+});diff --git a/packages/components/src/test/fake-host.ts b/packages/components/src/test/fake-host.tsindex bf355c39..daf95f3c 100644--- a/packages/components/src/test/fake-host.ts+++ b/packages/components/src/test/fake-host.ts@@ -123,8 +123,10 @@ export function fakeHost(): Host & { created: LayoutNode[] } {cutout: o.mode ?? "person",...o,}) as never,- matte: (node, matte) => {- (node as unknown as { matte?: unknown }).matte = { node: matte };+ particles: (o) =>+ make({ kind: "particles", ...o, id: o.id ?? "particles" }) as never,+ matte: (node, matte, mode = "alpha") => {+ (node as unknown as { matte?: unknown }).matte = { node: matte, mode };return node;},autoId: (prefix) => {diff --git a/packages/components/src/toasts/index.test.ts b/packages/components/src/toasts/index.test.tsnew file mode 100644index 00000000..3dfa84c6--- /dev/null+++ b/packages/components/src/toasts/index.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from "vitest";+import { bind } from "../core/contract.js";+import { fakeHost } from "../test/fake-host.js";+import { springTrack, toasts } from "./index.js";++describe("springTrack", () => {+ it("springs to each target and lands on it", () => {+ const v = springTrack(+ [+ [10, 100],+ [60, 0],+ ],+ 0,+ 120,+ 30,+ );+ expect(v[9]).toBe(0);+ expect(v[55]).toBeCloseTo(100, 0);+ expect(v[120]).toBeCloseTo(0, 0);+ // A retarget starts from where the value is, so nothing jumps.+ const mid = springTrack(+ [+ [0, 100],+ [5, 0],+ ],+ 0,+ 20,+ 30,+ );+ expect(Math.abs((mid[5] as number) - (mid[4] as number))).toBeLessThan(30);+ });+});++describe("Toasts", () => {+ it("cues arrivals and dismissals and leaves when the last one goes", () => {+ const t = bind(+ fakeHost(),+ toasts,+ )({+ items: [+ { at: 0, title: "a" },+ { at: 20, title: "b", duration: 30 },+ ],+ });+ expect(t.cues.arrivals.map((a) => a.frame)).toEqual([0, 20]);+ expect(t.cues.dismissals.map((d) => d.frame)).toEqual([120, 50]);+ expect(t.span.duration).toBeGreaterThan(120);+ });++ it("rejects unknown kinds", () => {+ expect(() =>+ bind(+ fakeHost(),+ toasts,+ )({ items: [{ at: 0, title: "a", kind: "nope" as never }] }),+ ).toThrow(/invalid props/);+ });+});diff --git a/packages/components/src/toasts/index.ts b/packages/components/src/toasts/index.tsnew file mode 100644index 00000000..a6a3760c--- /dev/null+++ b/packages/components/src/toasts/index.ts@@ -0,0 +1,385 @@+/**+ * Toasts: notifications arriving in a corner stack. The newest sits at the+ * edge, older ones are pushed away and compress as the stack grows, and+ * each one slides out when it is dismissed while the rest close the gap.+ * The stack is solved offline and every move is a baked spring.+ *+ * Coordinates are the frame's: the root covers the video (default+ * 1920 × 1080 × theme scale, or the given width / height) from 0, 0.+ */+import {+ LayerAnimation,+ type LayoutNode,+} from "@framefields/compositions/program";+import { z } from "zod";+import { bakeSamples, springAt } from "../core/bake.js";+import { defineComponent } from "../core/contract.js";+import type { Animatable } from "../core/host.js";+import { toPathData, type Vec2 } from "../core/path.js";+import type { Theme } from "../core/theme.js";++export const TOAST_CORNERS = [+ "top-right",+ "top-left",+ "bottom-right",+ "bottom-left",+ "top-center",+ "bottom-center",+] as const;+export type ToastCorner = (typeof TOAST_CORNERS)[number];+export const TOAST_KINDS = ["info", "success", "warning", "error"] as const;+export type ToastKind = (typeof TOAST_KINDS)[number];++export interface ToastsCues {+ [name: string]: ReadonlyArray<{ frame: number }>;+ arrivals: ReadonlyArray<{ frame: number; index: number }>;+ dismissals: ReadonlyArray<{ frame: number; index: number }>;+}++const SPRING = { stiffness: 230, damping: 24 };++/** Per-frame values that spring to each new target from wherever they are. */+export function springTrack(+ changes: ReadonlyArray<readonly [frame: number, target: number]>,+ initial: number,+ length: number,+ fps: number,+ options = SPRING,+): number[] {+ const sorted = [...changes].sort((a, b) => a[0] - b[0]);+ const out = new Array<number>(length + 1);+ let from = initial;+ let to = initial;+ let since = 0;+ let k = 0;+ for (let f = 0; f <= length; f++) {+ while (+ k < sorted.length &&+ (sorted[k] as readonly [number, number])[0] <= f+ ) {+ // Restart from the current value toward the new target.+ from = from + (to - from) * springAt((f - since) / fps, options);+ to = (sorted[k] as readonly [number, number])[1];+ since = (sorted[k] as readonly [number, number])[0];+ k++;+ }+ out[f] = from + (to - from) * springAt((f - since) / fps, options);+ }+ return out;+}++/** A small icon per kind: a coloured disc with a drawn mark. */+function icon(+ kind: ToastKind,+ size: number,+ theme: Theme,+): { color: string; mark: string } {+ const p = (pts: Vec2[]) =>+ toPathData(pts.map(([x, y]) => [x * size, y * size] as Vec2));+ switch (kind) {+ case "success":+ return {+ color: theme.color.positive,+ mark: p([+ [0.28, 0.52],+ [0.44, 0.67],+ [0.73, 0.36],+ ]),+ };+ case "error":+ return {+ color: theme.color.negative,+ mark: `${p([+ [0.33, 0.33],+ [0.67, 0.67],+ ])} ${p([+ [0.67, 0.33],+ [0.33, 0.67],+ ])}`,+ };+ case "warning":+ return {+ color: theme.color.highlight,+ mark: `${p([+ [0.5, 0.27],+ [0.5, 0.56],+ ])} ${p([+ [0.5, 0.72],+ [0.5, 0.73],+ ])}`,+ };+ case "info":+ return {+ color: theme.color.accent,+ mark: `${p([+ [0.5, 0.27],+ [0.5, 0.28],+ ])} ${p([+ [0.5, 0.44],+ [0.5, 0.73],+ ])}`,+ };+ }+}++export const toasts = /* @__PURE__ */ defineComponent({+ name: "Toasts",+ props: () => ({+ items: z+ .array(+ z+ .object({+ at: z.number().int().min(0),+ title: z.string(),+ body: z.string().optional(),+ kind: z.enum(TOAST_KINDS).default("info"),+ /** Frames on screen. Default 4 seconds. */+ duration: z.number().int().positive().optional(),+ })+ .strict(),+ )+ .min(1),+ corner: z.enum(TOAST_CORNERS).default("top-right"),+ /** Most toasts shown at once; older ones fade into the stack. */+ max: z.number().int().positive().default(3),+ toastWidth: z.number().positive().optional(),+ margin: z.number().min(0).optional(),+ fontFamily: z.string().optional(),+ }),+ defaults: { enter: false, exit: false },+ 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 tw = props.toastWidth ?? 440 * s;+ const margin = props.margin ?? 36 * s;+ const fontFamily = props.fontFamily ?? theme.font.body;+ const titleFs = 22 * s;+ const bodyFs = 19 * s;+ const pad = 18 * s;+ const iconSize = 30 * s;+ const gap = 12 * s;+ const top = props.corner.startsWith("top");+ const side = props.corner.endsWith("right")+ ? 1+ : props.corner.endsWith("left")+ ? -1+ : 0;+ const x =+ side === 1 ? W - margin - tw : side === -1 ? margin : (W - tw) / 2;++ // ── Sizes ─────────────────────────────────────────────────────────+ const textX = pad + iconSize + pad * 0.8;+ const textW = tw - textX - pad;+ const items = props.items.map((item, index) => {+ const titleM = host.measure(item.title, {+ fontFamily,+ fontSize: titleFs,+ fontWeight: 600,+ width: textW,+ });+ const bodyM = item.body+ ? host.measure(item.body, {+ fontFamily,+ fontSize: bodyFs,+ width: textW,+ })+ : null;+ const height =+ Math.max(iconSize, titleM.height + (bodyM ? bodyM.height + 4 * s : 0)) ++ pad * 2;+ return {+ ...item,+ index,+ height,+ titleH: titleM.height,+ end: item.at + (item.duration ?? fps * 4),+ };+ });++ // ── The stack at every event ──────────────────────────────────────+ const events = [...new Set(items.flatMap((t) => [t.at, t.end]))].sort(+ (a, b) => a - b,+ );+ const exitFrames = Math.round(fps * 0.5);+ const length =+ Math.max(...items.map((t) => t.end)) + exitFrames + Math.round(fps * 0.4);+ const yChanges = new Map<number, Array<[number, number]>>();+ const scaleChanges = new Map<number, Array<[number, number]>>();+ const fadeChanges = new Map<number, Array<[number, number]>>();+ const push = (+ m: Map<number, Array<[number, number]>>,+ i: number,+ f: number,+ v: number,+ ) => {+ const list = m.get(i) ?? [];+ list.push([f, v]);+ m.set(i, list);+ };+ for (const f of events) {+ const live = items+ .filter((t) => t.at <= f && f < t.end)+ .sort((a, b) => b.at - a.at || b.index - a.index);+ let offset = 0;+ live.forEach((t, k) => {+ // Older toasts tuck in: smaller, closer, and gone past `max`.+ const scale = 1 - Math.min(k, props.max) * 0.035;+ const y = top ? margin + offset : H - margin - offset - t.height;+ push(yChanges, t.index, f, y);+ push(scaleChanges, t.index, f, scale);+ push(fadeChanges, t.index, f, k < props.max ? 1 : 0);+ offset += t.height * scale + gap * scale;+ });+ }++ const parts: Record<string, Animatable<LayoutNode>> = {};+ const children: LayoutNode[] = [];+ for (const t of items) {+ const ys = yChanges.get(t.index) ?? [[t.at, margin]];+ const firstY = ys[0]?.[1] ?? margin;+ const yTrack = springTrack(ys, firstY, length, fps);+ const scaleTrack = springTrack(+ scaleChanges.get(t.index) ?? [],+ 1,+ length,+ fps,+ );+ const fade = fadeChanges.get(t.index) ?? [];+ // Slide in from the edge; slide back out when dismissed.+ const away = side === 0 ? 0 : side * (tw + margin);+ const xTrack = springTrack(+ [+ [t.at, 0],+ [t.end, away],+ ],+ away,+ length,+ fps,+ { stiffness: 200, damping: 26 },+ );+ const opacity = springTrack(+ [[t.at, 1], ...fade.filter(([f]) => f > t.at), [t.end, 0]],+ 0,+ length,+ fps,+ { stiffness: 300, damping: 40 },+ ).map((v) => Math.max(0, Math.min(1, v)));+ const glyph = icon(t.kind, iconSize, theme);+ const disc = host.box({+ id: ctx.partId(`toast-${t.index}-icon`),+ position: "absolute",+ x: pad,+ y: pad,+ width: iconSize,+ height: iconSize,+ background: glyph.color,+ borderRadius: iconSize / 2,+ });+ const mark = host.shape("path", {+ id: ctx.partId(`toast-${t.index}-mark`),+ position: "absolute",+ x: pad,+ y: pad,+ width: iconSize,+ height: iconSize,+ d: glyph.mark,+ fillType: "none",+ strokeColor: "#ffffff",+ strokeWidth: iconSize * 0.11,+ strokeLineCap: "round",+ strokeLineJoin: "round",+ });+ const kids: LayoutNode[] = [+ disc,+ mark,+ host.text(t.title, {+ id: ctx.partId(`toast-${t.index}-title`),+ position: "absolute",+ x: textX,+ y: pad,+ width: textW,+ fontFamily,+ fontSize: titleFs,+ fontWeight: 600,+ fill: theme.color.ink,+ }),+ ];+ if (t.body)+ kids.push(+ host.text(t.body, {+ id: ctx.partId(`toast-${t.index}-body`),+ position: "absolute",+ x: textX,+ y: pad + t.titleH + 4 * s,+ width: textW,+ fontFamily,+ fontSize: bodyFs,+ fill: theme.color.muted,+ }),+ );+ const card = host.box({+ id: ctx.partId(`toast-${t.index}`),+ position: "absolute",+ x,+ y: firstY,+ width: tw,+ height: t.height,+ background: theme.color.raised,+ borderRadius: theme.radius.md,+ borderColor: theme.color.line,+ borderWidth: Math.max(1, s),+ anchorX: 0.5,+ anchorY: top ? 0 : 1,+ children: kids,+ });+ host.style(card, {+ dropShadow: {+ color: "#000000",+ opacity: 0.35,+ angle: 90,+ distance: 10 * s,+ size: 30 * s,+ },+ });+ const from = Math.max(0, t.at - 1);+ const slice = (v: number[]) => v.slice(from);+ card.animate(+ LayerAnimation.create()+ .keys("y", bakeSamples(slice(yTrack), from, { tolerance: 0.3 }))+ .keys(+ "x",+ bakeSamples(+ slice(xTrack).map((d) => x + d),+ from,+ { tolerance: 0.3 },+ ),+ )+ .keys(+ "scale",+ bakeSamples(slice(scaleTrack), from, { tolerance: 0.001 }),+ )+ .keys("opacity", [+ ...(from > 0 ? [[0, 0] as [number, number]] : []),+ ...bakeSamples(slice(opacity), from, { tolerance: 0.01 }),+ ]),+ );+ parts[`toast-${t.index}`] = card;+ children.push(card);+ }++ return {+ children,+ width: W,+ height: H,+ duration: length,+ origin: [0, 0],+ cues: {+ arrivals: items.map((t) => ({ frame: t.at, index: t.index })),+ dismissals: items.map((t) => ({ frame: t.end, index: t.index })),+ } as ToastsCues,+ parts,+ };+ },+});diff --git a/packages/components/src/toasts/meta.ts b/packages/components/src/toasts/meta.tsnew file mode 100644index 00000000..1de731cb--- /dev/null+++ b/packages/components/src/toasts/meta.ts@@ -0,0 +1,12 @@+import { defineMeta } from "../core/meta.js";++export default defineMeta({+ name: "Toasts",+ summary:+ "Notifications arriving into a corner stack that pushes older ones away and compresses as it grows; each slides out when dismissed.",+ tags: ["toast", "notification", "alert", "ui", "stack", "demo"],+ parts: ["toast-<n>"],+ cues: ["arrivals", "dismissals"],+ example: `Toasts({ items: [{ at: 0, title: "Deployed", kind: "success" }, { at: 40, title: "3 new comments" }] })`,+ since: "M5",+});diff --git a/packages/framefields/scripts/check-components-treeshake.mjs b/packages/framefields/scripts/check-components-treeshake.mjsindex e4fc113c..18bfdcff 100644--- a/packages/framefields/scripts/check-components-treeshake.mjs+++ b/packages/framefields/scripts/check-components-treeshake.mjs@@ -29,6 +29,11 @@ const CODE = "satisfies keyof declare";const TITLE = "kicker";const LOWER = "role-plate";const METER = "Meter: give `value`";+const CHAT = "A message needs `text` or `image`.";+const TOAST = "bottom-center";+const CALLOUT = "leader-2";+const SPOT = "radial-gradient(closest-side, #ffffff ";+const CONFETTI = "sparkles-";/** Each component: a string only its module has, and what it may compose. */const COMPONENTS = {@@ -44,6 +49,11 @@ const COMPONENTS = {TitleCard: { own: TITLE, uses: [REVEAL, GLYPHS], budget: 70_000 },LowerThird: { own: LOWER, uses: [], budget: 45_000 },Meter: { own: METER, uses: [COUNTER], budget: 55_000 },+ ChatThread: { own: CHAT, uses: [], budget: 50_000 },+ Toasts: { own: TOAST, uses: [], budget: 45_000 },+ Callout: { own: CALLOUT, uses: [], budget: 50_000 },+ Spotlight: { own: SPOT, uses: [], budget: 45_000 },+ Confetti: { own: CONFETTI, uses: [], budget: 45_000 },};const OWN = Object.values(COMPONENTS).map((c) => c.own);diff --git a/packages/framefields/src/components/host.ts b/packages/framefields/src/components/host.tsindex bce5628d..4c50d26a 100644--- a/packages/framefields/src/components/host.ts+++ b/packages/framefields/src/components/host.ts@@ -54,8 +54,9 @@ export const host: Host = {featherRadius: 0.04,keyBackground: true,}),- matte: (node, matte) => {- (node as unknown as AnimatableNode).withMatte(matte, "alpha");+ particles: (options) => Layer.particles(options),+ matte: (node, matte, mode = "alpha") => {+ (node as unknown as AnimatableNode).withMatte(matte, mode);return node;},};diff --git a/packages/framefields/src/components/index.ts b/packages/framefields/src/components/index.tsindex 6e559082..f4463c41 100644--- a/packages/framefields/src/components/index.ts+++ b/packages/framefields/src/components/index.ts@@ -16,16 +16,21 @@ import {type ComponentDefinition,type ComponentExtras,type Cues,+ callout,captions,+ chatThread,codeBlock,+ confetti,counter,focusZoom,lowerThird,meter,mousePointer,+ spotlight,terminal,textReveal,titleCard,+ toasts,} from "@framefields/components";import type { BoxNode } from "@framefields/compositions/program";import type { z } from "zod";@@ -86,6 +91,21 @@ export const LowerThird = /* @__PURE__ */ bindComponent(lowerThird);/** Progress and scores: ring, arc, bar, segments or stars, filling with its counter. */export const Meter = /* @__PURE__ */ bindComponent(meter);+/** A messaging conversation: springy bubbles, typing dots, reactions and auto-scroll. */+export const ChatThread = /* @__PURE__ */ bindComponent(chatThread);++/** Notifications arriving into a corner stack that compresses as it grows. */+export const Toasts = /* @__PURE__ */ bindComponent(toasts);++/** A label with a leader line pinned to a point or a moving tracked object. */+export const Callout = /* @__PURE__ */ bindComponent(callout);++/** Dims the frame except a region that glides between targets. */+export const Spotlight = /* @__PURE__ */ bindComponent(spotlight);++/** GPU confetti bursts: paper, ribbons and sparkles that fall and can settle. */+export const Confetti = /* @__PURE__ */ bindComponent(confetti);+export {type Anchor,type AnnotateCues,@@ -110,9 +130,13 @@ export {boilKeys,boundsOf,boxPath,+ CALLOUT_SIDES,CAPTION_STYLES,+ type CalloutCues,+ type CalloutSide,type CaptionStyle,type CaptionsCues,+ type ChatThreadCues,CODE_LANGS,type CodeBlockCues,type CodeLang,@@ -120,6 +144,7 @@ export {type ComponentDefinition,type ComponentExtras,type ComponentMeta,+ type ConfettiCues,type CounterCues,type CounterFormat,CURSOR_STYLES,@@ -181,6 +206,7 @@ export {type MousePointerApi,type MousePointerCues,offsetCues,+ type ParticleOptions,type Placement,type PropsOf,type PulseOptions,@@ -196,11 +222,14 @@ export {resolveMotion,resolveTarget,rng,+ type SpotlightCues,type StaggerOrder,scaleFrames,scheduleExpression,springAt,+ springKeys,springSettleFrames,+ springTrack,squigglePath,staggerOffsets,staggerRanks,@@ -217,6 +246,11 @@ export {TITLE_LAYOUTS,type TitleCardCues,type TitleLayout,+ TOAST_CORNERS,+ TOAST_KINDS,+ type ToastCorner,+ type ToastKind,+ type ToastsCues,type Token,type TokenKind,targetPoint,diff --git a/packages/framefields/src/components/m5.render.test.ts b/packages/framefields/src/components/m5.render.test.tsnew file mode 100644index 00000000..f174a48d--- /dev/null+++ b/packages/framefields/src/components/m5.render.test.ts@@ -0,0 +1,126 @@+import { beforeAll, describe, expect, it } from "vitest";+import { FontManager } from "../fonts/index.js";+import { Composition, Layer } from "../index.js";+import { computeMse, decodePngPixels, getPixel } from "../test-utils/pixels.js";+import { ChatThread, Confetti, Spotlight, Toasts } from "./index.js";++/**+ * Render tests for the M5 components: nothing shows before its time (the+ * renderer draws base values before a track's first key, so components pin+ * first keys at frame 0), the spotlight's hole is lit and the rest dimmed,+ * and particle frames don't depend on render order.+ */+beforeAll(async () => {+ await FontManager.register("assets/fonts/Inter.ttf");+});+function comp(+ nodes: Parameters<Composition["add"]>[0],+ background = "#0d0e11",+) {+ const c = new Composition({+ width: 960,+ height: 540,+ fps: 30,+ durationMs: 8000,+ backgroundColor: background,+ });+ c.add(nodes);+ return c;+}+const frame = async (c: Composition, n: number) =>+ decodePngPixels(await c.renderFrame({ frame: n }));++describe("ChatThread (render)", () => {+ it("shows a reply only once it lands", async () => {+ const chat = ChatThread({+ width: 960,+ height: 540,+ messages: [+ { from: "me", text: "Shipped?", at: 0 },+ { from: "sam", text: "Yes!", at: 60 },+ ],+ });+ const c = comp(chat);+ const before = await frame(c, 30);+ const empty = await frame(+ comp(+ ChatThread({+ width: 960,+ height: 540,+ messages: [{ from: "me", text: "Shipped?", at: 0 }],+ }),+ ),+ 30,+ );+ expect(computeMse(before.pixels, empty.pixels)).toBe(0);+ const after = await frame(c, 90);+ expect(computeMse(after.pixels, empty.pixels)).toBeGreaterThan(0);+ });+});++describe("Toasts (render)", () => {+ it("is empty before the first toast arrives", async () => {+ const t = Toasts({+ width: 960,+ height: 540,+ items: [{ at: 30, title: "Saved", kind: "success" }],+ });+ const img = await frame(comp(t), 10);+ const empty = await frame(comp([]), 10);+ expect(computeMse(img.pixels, empty.pixels)).toBe(0);+ });+});++describe("Spotlight (render)", () => {+ it("keeps the target lit and dims the rest", async () => {+ const target = { x: 300, y: 200, width: 200, height: 120 };+ const c = comp(+ [+ Layer.box({+ position: "absolute",+ x: 0,+ y: 0,+ width: 960,+ height: 540,+ background: "#ffffff",+ }),+ Spotlight({+ width: 960,+ height: 540,+ glide: 6,+ targets: [{ at: 0, target, padding: 10 }],+ }),+ ],+ "#ffffff",+ );+ const img = await frame(c, 20);+ expect(getPixel(img, 400, 260).r).toBeGreaterThan(240);+ expect(getPixel(img, 80, 80).r).toBeLessThan(110);+ });+});++describe("Confetti (render)", () => {+ it("renders the same frame in any order", async () => {+ const build = () =>+ comp(+ Confetti({+ width: 960,+ height: 540,+ bursts: [{ at: 2, origin: [480, 500], count: 80 }],+ floor: true,+ }),+ );+ const frames = [8, 30, 70];+ 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.tsindex 55e21542..08914347 100644--- a/packages/framefields/src/index.ts+++ b/packages/framefields/src/index.ts@@ -3405,13 +3405,19 @@ export {type AppFrameKind,bindComponent,CAPTION_STYLES,+ Callout,+ type CalloutCues,type CaptionStyle,Captions,type CaptionsCues,+ ChatThread,+ type ChatThreadCues,CodeBlock,type CodeBlockCues,type CodeLang,type ComponentNode,+ Confetti,+ type ConfettiCues,Counter,type CounterCues,type CounterFormat,@@ -3431,6 +3437,8 @@ export {type MousePointerApi,type MousePointerCues,type RevealStyle,+ Spotlight,+ type SpotlightCues,Terminal,type TerminalCues,type TerminalStep,@@ -3440,5 +3448,7 @@ export {TitleCard,type TitleCardCues,type TitleLayout,+ Toasts,+ type ToastsCues,type Waypoint,} from "./components/index.js";