Production-ready animations, transitions, backgrounds, and scenes for Remotion
TypeScript ai-agentsclaude-codedemo-videomcpmcp-servermodel-context-protocolmotion-designproduct-demoreactremotionshadcnvideo
feat: motion graphics category and September components (#287)
KapishDima7b1e6dadf212
diff --git a/app/(home)/components/hero-badge.tsx b/app/(home)/components/hero-badge.tsxindex 2cfe99e7..f5011613 100644--- a/app/(home)/components/hero-badge.tsx+++ b/app/(home)/components/hero-badge.tsx@@ -5,7 +5,7 @@ import Link from "next/link";import { Badge } from "@/components/ui/badge";import { useTrackEvent } from "@/lib/analytics";-const HERO_BADGE_HREF = "/changelog#2026-09-11-template-refinements";+const HERO_BADGE_HREF = "/changelog#2026-09-26-motion-graphics";export function HeroBadge() {const trackEvent = useTrackEvent();@@ -19,7 +19,7 @@ export function HeroBadge() {href={HERO_BADGE_HREF}onClick={() =>trackEvent("cta_clicked", {- cta: "hero_templates_badge",+ cta: "hero_motion_graphics_badge",destination: HERO_BADGE_HREF,})}@@ -27,7 +27,7 @@ export function HeroBadge() {}><span className="font-semibold text-foreground">Introducing</span>- <span className="text-foreground">Remocn Templates</span>+ <span className="text-foreground">Motion Graphics</span><ArrowRightclassName="size-3 transition-transform group-hover:translate-x-0.5"aria-hidden="true"diff --git a/app/(home)/showcases/components/showcases-hero.tsx b/app/(home)/showcases/components/showcases-hero.tsxindex 56156346..6c7ac8c4 100644--- a/app/(home)/showcases/components/showcases-hero.tsx+++ b/app/(home)/showcases/components/showcases-hero.tsx@@ -34,7 +34,11 @@ export function ShowcasesHero() {render={<Link href="/docs/getting-started/introduction" />}>Start building- <ArrowRight className="size-4" aria-hidden="true" />+ <ArrowRight+ data-icon="inline-end"+ className="size-4"+ aria-hidden="true"+ /></Button></FadeUp></div>diff --git a/bun.lock b/bun.lockindex 8ca13468..9fab16b1 100644--- a/bun.lock+++ b/bun.lock@@ -1821,8 +1821,6 @@"fumadocs-mdx/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.7", "@esbuild/android-arm": "0.27.7", "@esbuild/android-arm64": "0.27.7", "@esbuild/android-x64": "0.27.7", "@esbuild/darwin-arm64": "0.27.7", "@esbuild/darwin-x64": "0.27.7", "@esbuild/freebsd-arm64": "0.27.7", "@esbuild/freebsd-x64": "0.27.7", "@esbuild/linux-arm": "0.27.7", "@esbuild/linux-arm64": "0.27.7", "@esbuild/linux-ia32": "0.27.7", "@esbuild/linux-loong64": "0.27.7", "@esbuild/linux-mips64el": "0.27.7", "@esbuild/linux-ppc64": "0.27.7", "@esbuild/linux-riscv64": "0.27.7", "@esbuild/linux-s390x": "0.27.7", "@esbuild/linux-x64": "0.27.7", "@esbuild/netbsd-arm64": "0.27.7", "@esbuild/netbsd-x64": "0.27.7", "@esbuild/openbsd-arm64": "0.27.7", "@esbuild/openbsd-x64": "0.27.7", "@esbuild/openharmony-arm64": "0.27.7", "@esbuild/sunos-x64": "0.27.7", "@esbuild/win32-arm64": "0.27.7", "@esbuild/win32-ia32": "0.27.7", "@esbuild/win32-x64": "0.27.7" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w=="],- "fumadocs-mdx/zod": ["[email protected]", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="],-"fumadocs-ui/motion": ["[email protected]", "", { "dependencies": { "framer-motion": "^12.38.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-uYfXzeHlgThchzwz5Te47dlv5JOUC7OB4rjJ/7XTUgtBZD8CchMN8qEJ4ZVsUmTyYA44zjV0fBwsiktRuFnn+w=="],"is-inside-container/is-docker": ["[email protected]", "", { "bin": { "is-docker": "cli.js" } }, "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ=="],diff --git a/config/mega-menu.ts b/config/mega-menu.tsindex f9dbd750..033f0cb0 100644--- a/config/mega-menu.ts+++ b/config/mega-menu.ts@@ -32,6 +32,11 @@ const COMPONENT_CATEGORIES: MegaMenuItem[] = [preview: "grain-dissolve",},{ label: "Effects", href: "/docs/effects", preview: "tv-power-off" },+ {+ label: "Motion Graphics",+ href: "/docs/motion-graphics",+ preview: "bauhaus-build",+ },{label: "Filters",href: "/docs/filters/getting-started/introduction",diff --git a/config/site.ts b/config/site.tsindex 5689ecfe..8c2b7eac 100644--- a/config/site.ts+++ b/config/site.ts@@ -64,16 +64,20 @@ export const NAV_LINKS: NavLink[] = [* tag another menu item — no component changes needed. See `withNewBadges`.*/export const NEW_BADGE_PATHS = new Set<string>([- "/docs/typography/inline-word-roll",- "/docs/typography/shader-text-reveal",- "/docs/transitions/shader-seam",- "/docs/transitions/shader-spiral-pass",- "/docs/shaders/components/shader-light-tunnel",- "/docs/typography/type-fossil",- "/docs/typography/kinetic-morph-text",- "/docs/effects/cursor-gravity",- "/docs/effects/radial-burst",- "/docs/ui-blocks/search-reveal",+ "/docs/motion-graphics/bauhaus-build",+ "/docs/motion-graphics/mondrian-split",+ "/docs/motion-graphics/truchet-flip",+ "/docs/motion-graphics/trim-burst",+ "/docs/motion-graphics/speed-lines",+ "/docs/motion-graphics/squiggle",+ "/docs/effects/keystroke",+ "/docs/ui-blocks/code-morph",+ "/docs/ai/agent-run",+ "/docs/typography/selection-snap",+ "/docs/typography/echo-stack",+ "/docs/typography/type-wall",+ "/docs/typography/ring-text",+ "/docs/typography/period-drop",]);export type FooterGroup = {diff --git a/content/changelog/2026-09-25-showreel-type.mdx b/content/changelog/2026-09-25-showreel-type.mdxnew file mode 100644index 00000000..bd805bb8--- /dev/null+++ b/content/changelog/2026-09-25-showreel-type.mdx@@ -0,0 +1,18 @@+---+title: Showreel type+date: 2026-09-25+---++Five typography pieces pulled from a code-built motion showreel: heavy words on flat color fields that snap, echo, repeat, spin and land. Each one isolates a single trick and works with any text.++<ChangelogPreview name="type-wall" />++### New components++- [Selection Snap](/docs/typography/selection-snap) — a thin word snaps into a design-tool selection while its weight runs from Thin to Black on a variable font, then handles pop in and a size badge counts up.+- [Echo Stack](/docs/typography/echo-stack) — the word focuses in while outline copies unfold above and below it and keep drifting, looping without a seam.+- [Type Wall](/docs/typography/type-wall) — rows of one word fill the frame in heavy, narrow and outline faces, running in alternating directions at seeded speeds around an accent band.+- [Ring Text](/docs/typography/ring-text) — a phrase runs around a tilted 3D band that spins, readable on the near side and mirrored on the far side, with the band closing to fit any text.+- [Period Drop](/docs/typography/period-drop) — the word rises out of its line, then a colored dot falls, bounces twice with squash and stretch, and settles as the period.++<ChangelogPreview name="period-drop" />diff --git a/content/changelog/2026-09-26-motion-graphics.mdx b/content/changelog/2026-09-26-motion-graphics.mdxnew file mode 100644index 00000000..f249fe28--- /dev/null+++ b/content/changelog/2026-09-26-motion-graphics.mdx@@ -0,0 +1,22 @@+---+title: Motion graphics+date: 2026-09-26+---++A new Motion Graphics category: flat geometry built the way motion designers build shape layers. Three openers borrow from Bauhaus, De Stijl and Truchet tiles, and three small accents fire on a click, a landing or a beat, as often as a video needs them. Alongside them come three pieces that show a product at work: the keys behind a shortcut, a code change, and an AI agent answering.++<ChangelogPreview name="bauhaus-build" />++### New components++- [Bauhaus Build](/docs/motion-graphics/bauhaus-build) — flat circles, arcs, squares and bars tumble corner over corner on a hidden grid into a frieze, then rebuild around an open band for the title.+- [Mondrian Split](/docs/motion-graphics/mondrian-split) — black lines cut the frame into a seeded De Stijl grid, primaries wipe into the cells, the grid reflows like rubber, and one cell pushes its own lines out to become the next scene.+- [Truchet Flip](/docs/motion-graphics/truchet-flip) — quarter-circle tiles snap a quarter turn as a wave crosses the grid, rerouting the lines until they settle into rings, a calm field or a circle.+- [Trim Burst](/docs/motion-graphics/trim-burst) — short strokes shoot out of a point like Trim Paths, each start chasing its end until the stroke zips shut in flight.+- [Speed Lines](/docs/motion-graphics/speed-lines) — streaks trail a flying element at its real speed and die as it lands with a squash and a small bounce, or radial lines snap onto an impact point.+- [Squiggle](/docs/motion-graphics/squiggle) — a line draws itself along a course as a wave that swims forward and calms, in wave, zigzag, loop or coil shapes.+- [Keystroke](/docs/effects/keystroke) — physical keycaps press a shortcut in real order, the modifiers held while the letter taps, on the same frame as the UI it triggers.+- [Code Morph](/docs/ui-blocks/code-morph) — Magic Move for code: surviving tokens glide to their new line and column while removed code dissolves and new code fades in.+- [Agent Run](/docs/ai/agent-run) — a brand-neutral AI agent run where tool calls resolve against a real-seconds timer and the markdown answer streams in bursts.++<ChangelogPreview name="agent-run" />diff --git a/content/changelog/2026-09-26-vector-type.mdx b/content/changelog/2026-09-26-vector-type.mdxnew file mode 100644index 00000000..12a6e291--- /dev/null+++ b/content/changelog/2026-09-26-vector-type.mdx@@ -0,0 +1,18 @@+---+title: Vector type+date: 2026-09-26+---++Five typography pieces built the way a motion designer builds type in After Effects. Two work on the real glyph outlines of any font file: a trim path around every contour, and a font editor's anchors and handles pulling the curves into shape. Three work on live text: striped type, text riding a path, and a repeater.++<ChangelogPreview name="glyph-anatomy" />++### New components++- [Outline Trace](/docs/typography/outline-trace) — every contour draws itself as a stroke, letter by letter, then the fill wipes up inside each letter and the stroke fades into it. Overlapping contours in variable-font instances stay hidden.+- [Glyph Anatomy](/docs/typography/glyph-anatomy) — metric guides draw across, anchors pop along each contour, and Bézier handles pull straight segments into curves before the glyphs fill and the scaffolding fades.+- [Stripe Type](/docs/typography/stripe-type) — the word is cut into IBM-style bands that slide in from alternating sides and lock, stay striped or close into solid type, and pass on through on the exit.+- [Path Ride](/docs/typography/path-ride) — a line draws itself along any SVG path with the text riding behind its head, then the curve pulls taut and the text settles on a straight, centered baseline.+- [Type Repeater](/docs/typography/type-repeater) — copies of a word unfold into a tunnel, a spiral or a fan behind it, breathe, and fold back into the word.++<ChangelogPreview name="path-ride" />diff --git a/content/docs/ai/agent-run.mdx b/content/docs/ai/agent-run.mdxnew file mode 100644index 00000000..99d291ec--- /dev/null+++ b/content/docs/ai/agent-run.mdx@@ -0,0 +1,219 @@+---+title: Agent Run+description: A brand-neutral AI agent run that thinks, calls tools against a real-seconds timer and streams a markdown answer in bursts+component: agent-run+vibe: tech+length: 310+useWhen:+ - "A product demo needs the beat after the prompt, where an AI agent plans, calls tools and lands on a specific answer."+ - "The video should prove real work happened, with tool calls resolving one by one while a timer counts real seconds."+ - "The AI feature is your own, so the interface must stay brand-neutral with one accent color."+ - "The reply is a short markdown answer with a heading, bullets, a small code block or citations that must read clearly on the final frame."+avoidWhen:+ - "The scene is a prompt being typed into a recognizable chat product — use `claude-chat` or `chat-gpt` instead."+ - "The agent is a coding CLI in a terminal — use `claude-code` or `terminal-simulator`."+ - "Only a code snippet should appear or change, with no chat around it — use `code-morph` or `glass-code-block`."+ - "A single line should type itself out with no interface around it — use `typewriter`."+---++<ComponentPreview name="agent-run" />++<InstallBlock name="agent-run" />++## Usage++`AgentRun` is the part of an AI product video that happens after the prompt.+The panel shows the prompt someone just sent, a `Thinking` status over a+short plan, then tool calls that resolve one after another while the header+timer counts real seconds. Then the answer streams in as markdown, in bursts.+It is brand-neutral: neutral surfaces, one accent for the running spinners and+the citation chips, and a light or dark theme.++```tsx+import { Backdrop } from "@/components/remocn/backdrop";+import { AgentRun } from "@/components/remocn/agent-run";++export const AgentScene = () => (+ <Backdrop+ fill={{ type: "color", value: "#ececea" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <AgentRun />+ </Backdrop>+);+```++The component paints no background and centers its panel in the parent.+Sizes are reference pixels at a 720px-tall frame. They scale by+`height / 720`, capped so the 800px panel and its margins fit the width. The+panel height follows the frame, so square and vertical compositions show more+of the run at once. Everything derives from the Remotion frame and the seed,+so seeking and rendering are deterministic.++The component uses the system font stack. If your project loads Inter and+JetBrains Mono, for example with `@remotion/google-fonts`, it picks them up.++### Your own run++Pass a `run`: the prompt, a short plan, the tool steps with their real+durations in seconds, and the answer as markdown. The answer supports these:++- `#` and `##` headings+- paragraphs+- `-` bullets+- `**bold**` and inline code+- `[n]` citations+- fenced code blocks++`getAgentRunDuration(run)` returns the composition length. If you also pass+`seed`, `compression` or `speed` to the component, pass the same values as the+second argument.++```tsx+import { Composition } from "remotion";+import { Backdrop } from "@/components/remocn/backdrop";+import {+ AgentRun,+ type AgentRunScript,+ getAgentRunDuration,+} from "@/components/remocn/agent-run";++const run: AgentRunScript = {+ title: "Pro plan churn",+ prompt: "Which Pro accounts are likely to churn this month?",+ plan: [+ "Pull weekly active seats for every Pro account",+ "Compare them with renewal dates and support load",+ ],+ steps: [+ {+ icon: "database",+ name: "Run SQL",+ detail: "active seats by account, last 60 days",+ duration: 2.6,+ },+ {+ icon: "book",+ name: "Read 9 sources",+ duration: 1.8,+ sources: [+ "CRM notes",+ "Support tickets",+ "Renewal calendar",+ "billing.example.com",+ "Usage report",+ "QBR decks",+ "Churn survey",+ "Seat audit",+ "Pricing page",+ ],+ },+ ],+ answer: [+ "## 14 Pro accounts are at risk",+ "",+ "Active seats fell below 40% on 14 accounts that renew within 30 days [1].",+ "",+ "- 9 of them opened a billing ticket this month [2]",+ "- 3 lost the admin who set up their workspace",+ "",+ "**Next:** send the list to account managers today.",+ ].join("\n"),+};++const ChurnScene = () => (+ <Backdrop+ fill={{ type: "color", value: "#0a0a0a" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <AgentRun run={run} theme="dark" accentColor="#22c55e" />+ </Backdrop>+);++export const RemotionRoot = () => (+ <Composition+ id="ChurnScene"+ component={ChurnScene}+ durationInFrames={getAgentRunDuration(run)}+ fps={30}+ width={1280}+ height={720}+ />+);+```++## Timing++At 30 fps with the default run, `seed={1}`, `compression={3}` and `speed={1}`:++| Frames | Beat |+| --- | --- |+| 0–14 | The panel fades up 14px, and the prompt bubble follows at 4–14 |+| 16 | The run starts: the timer reads 0.0s and `Thinking` fades in with its shimmer |+| 30–48 | The three plan lines stream in bursts |+| 56–64 | `Thinking` settles into `Thought for 4s` as the timer passes 4.0s |+| 61–75 | Query analytics runs, and its spinner closes into a check beside `1.4s` |+| 80–103 | Run SQL, 2.3s on the timer |+| 108–120 | Search logs, 1.1s |+| 125–157 | Read 12 sources, 3.2s; five source chips and a `+7` chip pop in at 129–148 |+| 165–178 | The heading streams in body style, then takes heading style when its line completes at 170 |+| 177–257 | The paragraph with its citations, then three bullets; the column starts gliding up at 201 |+| 262–275 | The code panel opens on its fence and four lines stream inside |+| 280–294 | The fix line lands, and the run ends at 294 with the timer at 27.7s |+| 294–310 | The header spinner closes into a check and the last chunk finishes fading; the column has glided 279px up |+| 310–355 | The docs preview holds the finished answer |++The answer arrives in chunks of 1–6 tokens that land on whole frames, 1–4+frames apart. Now and then a pause adds 4–7 more frames, and each new markdown+block starts on a fresh chunk after a 2–4 frame beat. Each chunk fades in over+5 frames. So the text comes in bursts, never at a constant rate per+character. `seed` changes the rhythm but not the content.++Every line's position is fixed in advance, and content only grows at the+bottom. The column follows it with overlapping smoothstep glides of 24 frames,+each starting 16 frames before its content arrives. A glide is three quarters+done when its line lands, so a burst of new lines lands in view and nothing+jumps.++`compression` sets how many real seconds pass per video second. A tool call+lasts `duration / compression` on screen, clamped to 12–120 frames. The timer+always advances by the step's real `duration`, so the rows and the header+agree. `agentRunLength` is 310, the component's own motion for the default+run. `getAgentRunDuration(run, { seed, compression, speed })` adds a 45-frame+hold and scales the motion by `speed`.++<PropsTable title="Props"+ rows={[+ { name: "run", type: "AgentRunScript", default: "defaultAgentRun", description: "The prompt, plan, tool steps and markdown answer; see the tables below" },+ { name: "theme", type: '"light" | "dark"', default: '"light"', description: "Neutral panel theme" },+ { name: "accentColor", type: "string", default: '"#2563eb"', description: "The one accent, used for running spinners and citation chips; any CSS color" },+ { name: "compression", type: "number", default: "3", description: "Real seconds per video second, clamped to 0.25–20; tool calls last duration / compression on screen, clamped to 12–120 frames" },+ { name: "seed", type: "number", default: "1", description: "Seeds the chunk sizes, intervals and pauses of the plan and answer streams" },+ { name: "speed", type: "number", default: "1", description: "Playback multiplier; 0 freezes the first frame" },+ { name: "className", type: "string", description: "Optional class name on the full-frame root" },+ ]}+/>++<PropsTable title="AgentRunScript"+ rows={[+ { name: "title", type: "string", description: "Thread title in the panel header" },+ { name: "prompt", type: "string", description: "The message the user sent, shown as the bubble" },+ { name: "plan", type: "string[]", description: "Two or three short plan lines that stream under Thinking" },+ { name: "steps", type: "AgentRunStep[]", description: "Tool calls, run one after another" },+ { name: "answer", type: "string", description: "Markdown answer with # and ## headings, paragraphs, - bullets, bold, inline code, [n] citations and fenced code" },+ ]}+/>++<PropsTable title="AgentRunStep"+ rows={[+ { name: "name", type: "string", description: "Tool name, such as Run SQL" },+ { name: "detail", type: "string", description: "Short argument shown muted after the name" },+ { name: "duration", type: "number", description: "Real seconds; the timer advances by exactly this much during the step" },+ { name: "icon", type: '"chart" | "database" | "search" | "book" | "globe" | "terminal" | "file"', default: '"book" with sources, else "terminal"', description: "Lucide icon for the row" },+ { name: "sources", type: "string[]", description: "Source labels; chips pop in during the step and the rest collapse into a +N chip" },+ ]}+/>diff --git a/content/docs/ai/index.mdx b/content/docs/ai/index.mdxindex ec3a3be9..bb1549be 100644--- a/content/docs/ai/index.mdx+++ b/content/docs/ai/index.mdx@@ -1,9 +1,9 @@---title: AI-description: Animated AI tool interfaces — chat composers and CLI welcome screens that type a prompt+description: Animated AI tool interfaces — chat composers and CLI welcome screens that type a prompt, and an agent run that streams the answer----Recreations of the interfaces people open every day to talk to AI — chat composers and coding-agent CLIs. Each one types a prompt on the timeline and shares the same `useTypewriter` hook and `caret` primitive.+Recreations of the interfaces people open every day to talk to AI. The chat composers and coding-agent CLIs type a prompt on the timeline and share the same `useTypewriter` hook and `caret` primitive. Agent Run is brand-neutral and shows what happens after Enter — tool calls and a streamed answer.## Chat composers@@ -48,3 +48,16 @@ Recreations of the interfaces people open every day to talk to AI — chat compo},]}/>++## Agent runs++<ComponentCardGrid+ items={[+ {+ name: "AgentRun",+ description: "Brand-neutral agent run — tool calls resolve against a real-seconds timer, then the markdown answer streams in bursts",+ status: "stable",+ href: "/docs/ai/agent-run",+ },+ ]}+/>diff --git a/content/docs/ai/meta.json b/content/docs/ai/meta.jsonindex 1176f634..96e885e4 100644--- a/content/docs/ai/meta.json+++ b/content/docs/ai/meta.json@@ -7,7 +7,8 @@"chat-gpt","v0","claude-code",- "opencode"+ "opencode",+ "agent-run"],"icon": "ArtificialIntelligence04Icon"}diff --git a/content/docs/effects/index.mdx b/content/docs/effects/index.mdxindex 7b24a194..8dfd94d3 100644--- a/content/docs/effects/index.mdx+++ b/content/docs/effects/index.mdx@@ -7,6 +7,12 @@ Drop-in effect overlays you compose on top of any scene — fire them on a frame<ComponentCardGriditems={[+ {+ name: "Keystroke",+ description: "Physical keycaps that press a shortcut in real order and spring back, on the frame the UI reacts",+ status: "stable",+ href: "/docs/effects/keystroke",+ },{name: "Cursor Gravity",description: "A soft triangular cursor extracts a hidden button from the screen edge with elastic tugs",diff --git a/content/docs/effects/keystroke.mdx b/content/docs/effects/keystroke.mdxnew file mode 100644index 00000000..da79fe99--- /dev/null+++ b/content/docs/effects/keystroke.mdx@@ -0,0 +1,174 @@+---+title: Keystroke+description: Physical keycaps that press, hold and spring back in real order, a shortcut overlay for keyboard-first product demos+component: keystroke+vibe: tech+length: 166+useWhen:+ - "A product demo shows a keyboard-first flow, such as a command palette, an editor or a triage queue, and the viewer should see the keys behind each action."+ - "A shortcut should land on the same frame as the UI it triggers, so the keystroke and a remocn-ui state step share one frame number."+ - "A launch or changelog video introduces new shortcuts and should show them as real keys, with the modifiers held while the letter taps."+avoidWhen:+ - "The interaction is pointing and clicking rather than pressing shortcuts — use `simulated-cursor`."+ - "The viewer should read text being typed into a field or a terminal, not individual shortcuts — use `typewriter`."+ - "The shortcut only needs to appear as a static hint next to a menu item — use `command-menu`."+---++<ComponentPreview name="keystroke" />++<InstallBlock name="keystroke" />++## Usage++`Keystroke` is the keyboard counterpart of `simulated-cursor`. For each+shortcut, physical keycaps rise in near the bottom of the frame and press in+real order. The modifiers go down first and stay down while the letter taps,+then come up after it. Each keytop sinks into its base, so the side wall+shortens and the contact shadow tightens. On release it springs back with a small+overshoot, and the legend of a key that is down turns the accent color. The+caps leave together after an idle hold. When the next shortcut arrives, the+previous one slides back and dims before it leaves.++```tsx+import { Backdrop } from "@/components/remocn/backdrop";+import { Keystroke } from "@/components/remocn/keystroke";++export const ShortcutOverlay = () => (+ <Backdrop+ fill={{ type: "color", value: "#e9e9e5" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <Keystroke />+ </Backdrop>+);+```++The component paints no background, so it composites over any scene.+`theme="light"` draws off-white caps on a light-gray wall, and `theme="dark"`+draws graphite caps. `platform="mac"` draws the glyphs ⌘ ⌥ ⇧ ⌃ ↩ ⌫ ⎋ ⇥, and+`platform="windows"` writes Ctrl, Alt, Shift and Enter on wider caps. `x` and+`y` place the center of the row as fractions of the frame. `size` is the+keycap height in reference pixels at 720p and scales with the composition+height, so the caps look the same at 1080p and 4K. In a vertical video, pass a+smaller `size`.++### Your own shortcuts++Each step is `{ at, keys, hold }`. `at` is the frame the shortcut fires: the+frame its last key bottoms out. It uses the same Sequence-local frames as the+`at` of a remocn-ui step, so a keystroke and the UI it opens can share one+number. Everything before the click is scheduled backward from `at`.++```tsx+import { Backdrop } from "@/components/remocn/backdrop";+import { CommandMenu } from "@/components/remocn/command-menu";+import { Keystroke } from "@/components/remocn/keystroke";+import { useCurrentState } from "@/lib/remocn-ui";++const OPEN = 24;+const CLOSE = 96;++export const PaletteDemo = () => {+ const state = useCurrentState(+ [+ { at: OPEN, state: "opened" },+ { at: CLOSE, state: "closed" },+ ],+ "closed",+ );++ return (+ <Backdrop+ fill={{ type: "color", value: "#f4f4f2" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <CommandMenu state={state} />+ <Keystroke+ steps={[+ { at: OPEN, keys: "mod+k" },+ { at: CLOSE, keys: "esc" },+ ]}+ />+ </Backdrop>+ );+};+```++`keys` is a combo joined with `+` (`"mod+k"`, `"shift+mod+p"`, `"enter"`) or a+sequence of combos separated by spaces (`"g i"` presses G, then I). A sequence+fires on its last key, and a subtle "then" joins its chords. `mod` is ⌘ on mac+and Ctrl on windows. The other modifiers are `shift`, `alt`/`option`,+`ctrl`/`control`, `cmd`/`meta` (Win on windows) and `fn`. They are always+drawn and pressed in the platform's standard order. Named keys include `enter`, `esc`, `tab`,+`space`, `backspace`, `delete`, the arrows (`up`, `down`, `left`, `right`),+`f1` to `f24`, and `plus` for a plus key. Any other single character is drawn+as its uppercase letter.++## Timing++At 30 fps with `speed={1}` and the default steps, `mod+k` on 20, `g i` on 78+and `shift+mod+p` on 114:++| Frames | Motion |+| --- | --- |+| 0–7 | Empty frame |+| 7–18 | ⌘ and K rise in and settle |+| 14–20 | ⌘ goes down, then K; ⌘K fires on 20 |+| 28–41 | K springs up on 28, ⌘ on 31 |+| 48–58 | G rises in while ⌘K slides back and dims; G fires on 58 |+| 61–69 | ⌘K leaves |+| 66–76 | G springs up |+| 68–78 | "then" and I rise in, the row re-centers and G dims; G then I fires on 78 |+| 86–96 | I springs up |+| 98–114 | ⇧, ⌘ and P rise in as G then I slides back, then go down 3 frames apart; ⇧⌘P fires on 114 |+| 116–124 | G then I leaves |+| 122–138 | P, ⌘ and ⇧ spring up in reverse order |+| 158–166 | ⇧⌘P leaves after its linger |+| 166–180 | Empty hold |++Each key takes 3 frames to go down. Keys in a combo start 3 frames apart and+come up 3 frames apart, last down first up. The chord stays down for its+`hold` (8 frames by default). The release lands exactly on rest 10 frames+later. The caps start rising before `at`: 10 frames for a single key, 13 for a+two-key combo, 16 for three, and 30 for `g i`. `getKeystrokeLeadIn(keys, hold)`+returns that lead-in, so leave at least that much before the first `at` in a+Sequence. After the last key comes up, a group waits `linger` frames (30 by+default), then leaves over 8 frames. A group pushed back by a newer one leaves+sooner, 18 frames after the push. If its keys are still down at the push, the+18 frames count from its last key-up instead, so its release still plays. At+most two groups hold the screen: a third arrival sends the oldest off at once.++`keystrokeLength` is 166, the frame the default content has left.+`getKeystrokeDuration({ steps, linger, speed, fps })` returns the frames your+own steps need, plus a 14-frame tail. `at`, `hold` and `linger` are frames of+your composition, exactly like remocn-ui `at`. The press and release motion+keeps the same timing in seconds at any frame rate.++<PropsTable title="Props"+ rows={[+ { name: "steps", type: "KeystrokeStep[]", default: "three-step flow", description: "Shortcuts in order, each { at, keys, hold? }; the default is ⌘K, G then I, ⇧⌘P" },+ { name: "platform", type: '"mac" | "windows"', default: '"mac"', description: "Resolves mod to ⌘ or Ctrl and draws glyph or word legends" },+ { name: "theme", type: '"light" | "dark"', default: '"light"', description: "Off-white caps on a light-gray wall, or graphite caps" },+ { name: "accent", type: "string", default: '"#0a84ff"', description: "Legend color of a key while it is down" },+ { name: "x", type: "number", default: "0.5", description: "Row center as a fraction of the frame width" },+ { name: "y", type: "number", default: "0.86", description: "Row center as a fraction of the frame height" },+ { name: "size", type: "number", default: "64", description: "Keycap height and 1u key width in reference px at 720p, clamped to 8–400" },+ { name: "linger", type: "number", default: "30", description: "Frames the caps stay after the last key comes up, before they leave" },+ { name: "speed", type: "number", default: "1", description: "Playback multiplier applied to the frame, like remocn-ui; 0 never fires" },+ { name: "className", type: "string", description: "Optional class name on the full-frame root" },+ ]}+/>++### KeystrokeStep++<PropsTable+ rows={[+ { name: "at", type: "number", required: true, description: "Sequence-local frame the shortcut fires, when its last key bottoms out" },+ { name: "keys", type: "string", required: true, description: "A combo such as \"shift+mod+p\", or chords separated by spaces such as \"g i\"" },+ { name: "hold", type: "number", default: "8", description: "Frames the chord stays down after it fires" },+ ]}+/>diff --git a/content/docs/effects/meta.json b/content/docs/effects/meta.jsonindex 0d73f2ca..11b40e12 100644--- a/content/docs/effects/meta.json+++ b/content/docs/effects/meta.json@@ -3,6 +3,7 @@"defaultOpen": true,"pages": ["index",+ "keystroke","cursor-gravity","radial-burst","tv-power-off",diff --git a/content/docs/meta.json b/content/docs/meta.jsonindex 34610cdc..8ecc715a 100644--- a/content/docs/meta.json+++ b/content/docs/meta.json@@ -16,6 +16,7 @@"social","templates","effects",+ "motion-graphics","compositions"]}diff --git a/content/docs/motion-graphics/bauhaus-build.mdx b/content/docs/motion-graphics/bauhaus-build.mdxnew file mode 100644index 00000000..aeeb0a67--- /dev/null+++ b/content/docs/motion-graphics/bauhaus-build.mdx@@ -0,0 +1,182 @@+---+title: Bauhaus Build+description: Flat shapes tumble corner over corner into a Bauhaus frieze, then rebuild around an open band that hands off to a title+component: bauhaus-build+vibe: playful+length: 125+useWhen:+ - "A launch or chapter opener should build an abstract geometric poster and end on an open band for the title."+ - "The brand wants a Bauhaus look made of flat circles, arcs, squares and bars, in its own palette or in classic red, yellow and blue."+ - "Shapes should travel into place with a visible hinged tumble rather than fading or sliding in."+avoidWhen:+ - "The opener should burst and clear the whole frame instead of leaving shapes around the title — use `radial-burst`."+ - "The motion should be a pattern of tiles turning in place rather than a composed poster — use `truchet-flip`."+ - "The graphic should become the cut into the next scene instead of framing a title — use `mondrian-split`."+---++<ComponentPreview name="bauhaus-build" />++<InstallBlock name="bauhaus-build" />++## Usage++`BauhausBuild` assembles an abstract Bauhaus poster from nine flat pieces: a+large circle, two quarter circles, a semicircle, two squares, two bars and a+small circle. They arrive one at a time on a six-frame beat and build a frieze+across the middle of an invisible square grid. After a short hold the frieze+splits. Every piece makes one more quarter turn, and together they settle+above and below an empty center band. That band is the handoff field for your+title.++Pieces never slide or fade into place. Each one travels by tumbling over its+corners like a hinged tile. It makes a chain of quarter turns, each about the+grid corner on its leading edge, and rolls cell by cell until it lands+exactly in its slot. A new piece unfolds out of its first hinge point, which+can lie outside the poster, so some pieces roll in from the margins. The last+quarter turn overshoots by 4.5° and settles back.++The component draws no background, text, or fonts. Put a `Backdrop` in the+paper color behind it, with no padding, so the grid centers on the whole+frame.++```tsx+import { Backdrop } from "@/components/remocn/backdrop";+import { BauhausBuild } from "@/components/remocn/bauhaus-build";++export const Opener = () => (+ <Backdrop+ fill={{ type: "color", value: "#f1eee7" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <BauhausBuild />+ </Backdrop>+);+```++### Title handoff++`getBauhausBuildField` returns the open band in composition pixels. The band+spans the full frame width and the middle third of the poster, and it stays+vertically centered at every aspect ratio. Pass it the same `scale` as the+component. The band is clear from `bauhausBuildTimeline.clear` (frame 116 at+30 fps) and stays clear while the handoff holds.++```tsx+import { Sequence, useVideoConfig } from "remotion";+import { Backdrop } from "@/components/remocn/backdrop";+import {+ BauhausBuild,+ bauhausBuildTimeline,+ getBauhausBuildField,+} from "@/components/remocn/bauhaus-build";++export const Opener = () => {+ const { width, height } = useVideoConfig();+ const field = getBauhausBuildField({ width, height });++ return (+ <Backdrop+ fill={{ type: "color", value: "#f1eee7" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <BauhausBuild />+ <Sequence from={bauhausBuildTimeline.clear}>+ <div+ style={{+ position: "absolute",+ left: field.x,+ top: field.y,+ width: field.width,+ height: field.height,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ textAlign: "center",+ color: "#1c1a17",+ fontFamily: "Helvetica, Arial, sans-serif",+ fontSize: field.unit * 1.25,+ fontWeight: 700,+ lineHeight: 1.1,+ }}+ >+ Form follows function+ </div>+ </Sequence>+ </Backdrop>+ );+};+```++## Timing++At 30 fps and `speed={1}`:++| Frames | Motion |+| --- | --- |+| 0–22 | The first pieces unfold out of grid points and start tumbling toward their slots |+| 22–75 | Nine landings, one every six frames, each with a 4.5° overshoot that settles |+| 75–90 | Hold on the frieze |+| 90–125 | The frieze splits in a three-frame cascade. Paired pieces swing apart about shared corners, and the bars tip into rules above and below the band |+| 125–150 | Hold on the handoff. The band has been clear since frame 116 |++- `bauhausBuildLength` is 125, the frame where the last piece settles.+- `getBauhausBuildDuration({ speed, loop })` returns the preview length,+ including the final hold: 150 frames at `speed={1}`, or 300 with `loop`.+- At another speed or frame rate, divide these frames by `speed` and multiply+ by `fps / 30`.+- `loop` plays the whole sequence forward, then backward. The pieces tumble+ back out and fold into their hinge points, so the cycle repeats without a+ cut. Played backward, each landing overshoot becomes a small anticipation.++## Palette and variants++Each piece has a color role. The default is one warm accent and three+neutrals on a paper backdrop. Set the roles to red, yellow and blue for the+classic Bauhaus look:++```tsx+<Backdrop+ fill={{ type: "color", value: "#efe9dc" }}+ padding={0}+ radius={0}+ shadow=""+>+ <BauhausBuild+ inkColor="#161616"+ accentColor="#d7362b"+ secondaryColor="#f2b930"+ tertiaryColor="#1f4f9e"+ />+</Backdrop>+```++- `seed` mirrors the composition: 1 is the authored layout, 2 mirrors it+ horizontally, 3 vertically, 4 both ways, and then the cycle repeats. Every+ seed also reshuffles the arrival order. The band stays in the middle for+ every seed, so `getBauhausBuildField` does not need one.+- `scale` sets the size of the square poster. At 1 it fills 80% of the+ shorter side, and the range is 0.5–1.25. The composition keeps its+ proportions at 16:9, 1:1 and 9:16.+- `getBauhausBuildState(time, options)` returns every piece's pose in grid+ modules (position, rotation, hinge and scale), the poster's `originX`,+ `originY` and `unit` in pixels, and the seed's `flipX` and `flipY`, so other+ layers can follow the same grid. `time` counts frames at 30 fps and+ `speed={1}`.++<PropsTable title="Props"+ rows={[+ { name: "scale", type: "number", default: "1", description: "Poster size; 1 fills 80% of the shorter side, clamped to 0.5–1.25" },+ { name: "seed", type: "number", default: "1", description: "Mirror variant, cycling every four seeds, and arrival order" },+ { name: "inkColor", type: "string", default: '"#1c1a17"', description: "Large quarter circle, pillar bar and small circle" },+ { name: "accentColor", type: "string", default: '"#e4572e"', description: "Large circle and small square" },+ { name: "secondaryColor", type: "string", default: '"#cbbc9f"', description: "Semicircle and small quarter circle" },+ { name: "tertiaryColor", type: "string", default: '"#7e776b"', description: "Post bar and square block" },+ { name: "speed", type: "number", default: "1", description: "Playback multiplier; 0 freezes the empty first frame" },+ { name: "loop", type: "boolean", default: "false", description: "Plays the sequence forward and back so it repeats seamlessly every 300 frames" },+ { name: "className", type: "string", description: "Optional class name on the full-frame root" },+ ]}+/>diff --git a/content/docs/motion-graphics/index.mdx b/content/docs/motion-graphics/index.mdxnew file mode 100644index 00000000..cc425978--- /dev/null+++ b/content/docs/motion-graphics/index.mdx@@ -0,0 +1,47 @@+---+title: Motion Graphics+description: Flat geometric motion-graphics pieces for openers, section breaks, and pattern beds+---++Brand-agnostic geometry built the way motion designers build shape layers — drop one over any scene, recolor it, and let it play out.++<ComponentCardGrid+ items={[+ {+ name: "Bauhaus Build",+ description: "Flat Bauhaus shapes tumble corner over corner into a frieze, then rebuild around an open title band",+ status: "stable",+ href: "/docs/motion-graphics/bauhaus-build",+ },+ {+ name: "Mondrian Split",+ description: "A De Stijl grid builds itself, reflows like rubber, and one cell takes over the frame",+ status: "stable",+ href: "/docs/motion-graphics/mondrian-split",+ },+ {+ name: "Truchet Flip",+ description: "A pattern bed — quarter-circle tiles snap a quarter turn as a wave passes and the lines reconnect into rings",+ status: "stable",+ href: "/docs/motion-graphics/truchet-flip",+ },+ {+ name: "Trim Burst",+ description: "A punctuation accent — short strokes shoot out from a point, and each start chases its end until the stroke zips shut in flight",+ status: "stable",+ href: "/docs/motion-graphics/trim-burst",+ },+ {+ name: "Speed Lines",+ description: "Streaks trail a flying element at its real speed, it lands with a squash and a small bounce, or radial lines snap onto an impact point",+ status: "stable",+ href: "/docs/motion-graphics/speed-lines",+ },+ {+ name: "Squiggle",+ description: "A line accent — a wave draws itself along a course, swims forward as it goes, calms, and erases toward the end",+ status: "stable",+ href: "/docs/motion-graphics/squiggle",+ },+ ]}+/>diff --git a/content/docs/motion-graphics/meta.json b/content/docs/motion-graphics/meta.jsonnew file mode 100644index 00000000..732f938d--- /dev/null+++ b/content/docs/motion-graphics/meta.json@@ -0,0 +1,14 @@+{+ "title": "Motion Graphics",+ "defaultOpen": true,+ "pages": [+ "index",+ "bauhaus-build",+ "mondrian-split",+ "truchet-flip",+ "trim-burst",+ "speed-lines",+ "squiggle"+ ],+ "icon": "GeometricShapes01Icon"+}diff --git a/content/docs/motion-graphics/mondrian-split.mdx b/content/docs/motion-graphics/mondrian-split.mdxnew file mode 100644index 00000000..dd5ffbab--- /dev/null+++ b/content/docs/motion-graphics/mondrian-split.mdx@@ -0,0 +1,142 @@+---+title: Mondrian Split+description: Black lines cut the frame into a De Stijl grid, primaries fill the cells, the grid reflows like rubber, and one cell grows until it is the frame+component: mondrian-split+vibe: playful+length: 133+useWhen:+ - "A launch, section break, or product intro needs a bold, flat geometric opener that ends on a clean color field for the title."+ - "The next scene should appear inside the composition and then take over the frame, so the cut reads as part of the artwork."+ - "An editorial or design-led brand wants a De Stijl look in its own palette, line weight, and composition seed."+avoidWhen:+ - "The opener should feel round and energetic rather than rectilinear — use `radial-burst`."+ - "Both scenes should stay whole on screen while the cut happens, with no graphic interlude — use `slide-swap` or `whip-pan`."+ - "The old picture itself should break into blocks and set down as the new one — use `grid-wave`."+---++<ComponentPreview name="mondrian-split" />++<InstallBlock name="mondrian-split" />++## Usage++`MondrianSplit` is a De Stijl composition that builds itself and then becomes+the cut. Black lines cut the frame one at a time, each one splitting a single+cell, until the frame is a balanced grid of a few large planes and several+small ones. A few cells wipe in with primaries. After a short hold, lines slide+to new positions and every cell they touch stretches or shrinks with them, like+a rubber grid. The lines around the expanding cell only ever slide inward, so+it is squeezed just before it takes over. Then that cell, the largest plane by+default, pushes its own lines out past the frame edges until it is the frame.++```tsx+import { Backdrop } from "@/components/remocn/backdrop";+import { MondrianSplit } from "@/components/remocn/mondrian-split";++export const Opener = () => (+ <Backdrop+ fill={{ type: "color", value: "#f3efe6" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <MondrianSplit />+ </Backdrop>+);+```++The component paints no background: open cells show whatever is behind it, so+the backdrop supplies the paper. Without children the expanding cell is a flat+`fieldColor` field, and the last frame is a clean color for the title that+follows. The grid is built in composition pixels and cut across its long side,+so it recomposes for 16:9, 1:1 and 9:16 instead of stretching. Every value+comes from the Remotion frame and the seed, so seeking and rendering are+deterministic.++### Carry the next scene++Pass the next scene as children. It appears inside the expanding cell as that+cell fills, stays framed by the cell while the grid reflows, and owns the frame+once the lines are gone. The scene is clipped, never scaled. Children see the+same frame as the component, so keep the scene inside `MondrianSplit` for as+long as it should play.++```tsx+import { Backdrop } from "@/components/remocn/backdrop";+import { MondrianSplit } from "@/components/remocn/mondrian-split";++export const Handoff = () => (+ <Backdrop+ fill={{ type: "color", value: "#f3efe6" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <MondrianSplit seed={12} splits={9}>+ <ProductScene />+ </MondrianSplit>+ </Backdrop>+);+```++Place it over the outgoing scene instead of a backdrop and the open cells keep+showing that scene while the expanding cell carries the next one in.++## Timing++At 30 fps with the default seven splits and `speed={1}`:++| Frames | Motion |+| --- | --- |+| 0–3 | Empty frame |+| 3–43 | Seven lines cut the frame one at a time, five frames apart |+| 40–53 | Blue and yellow wipe into two cells |+| 50–62 | The expanding cell fills with `fieldColor`; children are revealed here |+| 62–76 | Hold on the finished composition |+| 76–106 | Three lines slide to new positions, dragging every cell they bound and squeezing the expanding cell |+| 102–133 | The expanding cell's lines pull in, then push out past the frame edges |+| 133–145 | Hold on the field or the next scene |++`mondrianSplitLength` is 133 frames, the point where the expanding cell covers+the frame. `getMondrianSplitDuration({ speed, splits })` adds the 12-frame hold+and returns frames at 30 fps; multiply by `fps / 30` for another frame rate.+More splits lengthen the build, so use `getMondrianSplitTimeline({ splits })`+to place a title against the reveal or the end.++## Variations++`seed` picks the composition, and raising `splits` refines the same grid+rather than replacing it. `expandCell` ranks cells by size: `0` expands the+largest plane, higher values hand the frame over from a smaller cell. Set+`fieldColor="transparent"` to push the grid off and hand back to whatever is+behind it.++```tsx+<MondrianSplit+ seed={21}+ splits={10}+ lineWeight={10}+ expandCell={2}+ redColor="#e4572e"+ yellowColor="#f3c63f"+ blueColor="#2e5aa7"+ fieldColor="#121212"+/>+```++<PropsTable title="Props"+ rows={[+ { name: "children", type: "React.ReactNode", description: "Scene shown inside the expanding cell from the moment it fills. It shares the component's frame and is all that remains after the push" },+ { name: "seed", type: "number", default: "7", description: "Composition seed; every seed gives a different balanced grid" },+ { name: "splits", type: "number", default: "7", description: "Number of lines, clamped to 3–12, so the grid has one more cell than this" },+ { name: "lineWeight", type: "number", default: "14", description: "Line thickness at a 720px reference on the shorter side, clamped to 2–48" },+ { name: "expandCell", type: "number", default: "0", description: "Which cell takes over the frame, ranked by size: 0 is the largest, 1 the next, and so on" },+ { name: "lineColor", type: "string", default: '"#121212"', description: "Line color" },+ { name: "redColor", type: "string", default: '"#d62d20"', description: "Fill for the red slot" },+ { name: "yellowColor", type: "string", default: '"#f4c20d"', description: "Fill for the yellow slot" },+ { name: "blueColor", type: "string", default: '"#1f4e9e"', description: "Fill for the blue slot" },+ { name: "fieldColor", type: "string", default: '"#d62d20"', description: "Expanding cell and final frame color, painted under children; transparent hands back to the backdrop" },+ { name: "speed", type: "number", default: "1", description: "Playback multiplier; 0 freezes the empty first frame" },+ { name: "className", type: "string", description: "Optional class name on the full-frame root" },+ ]}+/>diff --git a/content/docs/motion-graphics/speed-lines.mdx b/content/docs/motion-graphics/speed-lines.mdxnew file mode 100644index 00000000..b1c56118--- /dev/null+++ b/content/docs/motion-graphics/speed-lines.mdx@@ -0,0 +1,217 @@+---+title: Speed Lines+description: Parallel streaks trail an element at its real speed and die as it lands with a squash and a small bounce, or radial lines snap onto one point for a manga impact frame+component: speed-lines+vibe: playful+length: 31+useWhen:+ - "An element should make a sharp entrance, such as a card, logo, or number that flies in fast, stretches with its speed, and lands with weight, overshooting a little and squashing on impact, while streaks trail it and die as it lands."+ - "A landing, a number hitting its final value, or a strong beat needs a brief manga-style impact frame of lines converging on one point."+ - "A flat, recolorable accent should repeat many times in one video without shaders, blur, or images."+avoidWhen:+ - "The landing needs a small burst of strokes popping outward from the point rather than lines converging from the frame edges — use `trim-burst`."+ - "The whole scene should change with a fast camera move rather than one element flying in — use `whip-pan`."+ - "The element should be circled by hand rather than hit with motion — use `scribble-circle`."+---++<ComponentPreview name="speed-lines" />++<InstallBlock name="speed-lines" />++## Usage++`SpeedLines` is a motion accent with two modes. In `trail` mode it wraps an+element and flies its center from `from` to `to`. The element leaves from rest,+peaks mid-flight and crosses the target still moving at 45% of its top speed.+A damped spring catches it there: it overshoots by 3.5% of the flight, swings+back once with a small echo and settles exactly on `to`. `bounce` sets how much+momentum carries into the landing, and `bounce={0}` stops it dead on the+target.++The element also changes shape with its motion. While it moves, it stretches+along its path in proportion to its speed, up to 1.3×, and narrows across it,+so its area stays the same. Past the target it squashes, down to 0.8× along the+path and wider across, and rounds out again as the spring pulls it back.+`squash` scales the deformation, and `squash={0}` keeps the element rigid.++Short parallel streaks shoot past behind it. The element's real velocity drives+them, as the difference between this frame's position and the previous+frame's, bounce included. Streaks exist only while the element is fast, each+one's length is proportional to the speed, and they run parallel to the path.+Each spawns at a seeded lane across the element's width and slides back like+air rushing past. As the element brakes, every streak shortens. The last ones+die on the frame after contact, so the overshoot and the swing back draw none.++```tsx+import { Backdrop } from "@/components/remocn/backdrop";+import { SpeedLines } from "@/components/remocn/speed-lines";++export const Entrance = () => (+ <Backdrop+ fill={{ type: "color", value: "#002fa7" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <SpeedLines+ from={{ x: -0.25, y: 0.5 }}+ to={{ x: 0.5, y: 0.5 }}+ spread={80}+ >+ <div+ style={{+ padding: "20px 36px",+ borderRadius: 20,+ background: "#ffffff",+ color: "#002fa7",+ fontFamily: "Inter, sans-serif",+ fontSize: 40,+ fontWeight: 600,+ }}+ >+ Shipped+ </div>+ </SpeedLines>+ </Backdrop>+);+```++The component fills its parent and paints no background, so it composites over+any scene. Put it in a full-frame layer. Set `spread` to the element's size+across the direction of travel, so the streaks leave from behind its silhouette.+Without children, trail mode flies a disc of diameter `spread`, as in the+preview. Sizes are reference px at 720p and scale with the composition height.+Everything derives from the frame and the seed, so seeking and rendering are+deterministic.++The squash and stretch scale the element around its own center, turned to the+direction of travel, so it works for any `from` and `to` and the element never+drifts off its landing point. It deforms children too, text included. For a+text-heavy card, lower `squash` to about 0.25.++### On a landing++`focus` is an impact frame. Radial lines rush in from the edges of the frame,+snap onto the point `x`, `y` three frames later, hold for about five frames,+then retract and vanish. They never come closer to the point than `spread`.+`getSpeedLinesTimeline` returns `impact`: the contact frame of a trail, where+the element crosses `to` and the spring takes over, and the snap frame of a+focus. Start the focus that many frames early, and its lines converge while the+card flies in and snap on the frame it lands, as the card starts to squash.+The focus layer comes first, so its rays pass behind the card.++```tsx+import { Sequence } from "remotion";+import { Backdrop } from "@/components/remocn/backdrop";+import {+ getSpeedLinesTimeline,+ SpeedLines,+} from "@/components/remocn/speed-lines";++const ENTER = 20;+const LAND = ENTER + getSpeedLinesTimeline().impact;+const FOCUS = getSpeedLinesTimeline({ mode: "focus" }).impact;++export const RevenueBeat = () => (+ <Backdrop+ fill={{ type: "color", value: "#0a0a0a" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <Sequence from={LAND - FOCUS}>+ <SpeedLines mode="focus" x={0.5} y={0.5} spread={160} />+ </Sequence>+ <Sequence from={ENTER}>+ <SpeedLines+ from={{ x: -0.3, y: 0.5 }}+ to={{ x: 0.5, y: 0.5 }}+ spread={120}+ >+ <div+ style={{+ padding: "28px 44px",+ borderRadius: 24,+ background: "#fafafa",+ color: "#0a0a0a",+ fontFamily: "Inter, sans-serif",+ fontSize: 64,+ fontWeight: 600,+ fontVariantNumeric: "tabular-nums",+ }}+ >+ $128k+ </div>+ </SpeedLines>+ </Sequence>+ </Backdrop>+);+```++For a smaller landing, put `trim-burst` on the same point at `LAND` instead of+the focus.++## Timing++At 30 fps and `speed={1}`, trail mode with the default `duration={14}`,+`bounce={0.5}`, `squash={0.5}` and a 960 px flight:++| Frames | Motion |+| --- | --- |+| 0 | The element waits at `from`; no streaks yet |+| 0–4 | Launch; streaks appear once the element passes 5 px per frame, and it stretches as it speeds up |+| 4–11 | Cruise up to 93 px per frame, stretched up to 1.25× along the path; streaks reach 1.6 frames of travel |+| 11–14 | Braking; the stretch eases and every streak shortens with the speed |+| 14 | Contact with `to` (`impact`) at 45% of the top speed; streaks are gone from frame 15 |+| 16 | Overshoot peak, 34 px (3.5%) past the target, squashed to 0.83× along the path and 1.21× across |+| 16–21 | Swings back through the target and rounds out |+| 22 | Echo, 3 px short of the target |+| 26–31 | Visually at rest from 26, exactly on `to` at 31 (`end`) |++Focus mode:++| Frames | Motion |+| --- | --- |+| 0–3 | Rays rush in from the frame edges and accelerate |+| 3 | Impact: every ray snaps to its closest point, 1–1.6× `spread` away |+| 3–8 | Hold; the inner ends ease back out by up to 12% |+| 8–13 | Rays retract to the edges in a seeded order and vanish |++- `speedLinesLength` is 31, the frame where the default trail settles exactly.+- `getSpeedLinesTimeline({ mode, duration, bounce })` returns `impact` and+ `end`. For a trail, `impact` is `duration` and `end` adds the landing: 6+ frames at `bounce={0}`, 17 at the default and 29 at `bounce={1}`. For a+ focus, they are 3 and 13.+- `bounce` sets the overshoot: 1.1% of the flight at 0, 3.5% at 0.5 and 7.2% at+ 1, which also swings back 14 px short of the target. The overshoot grows with+ the arrival speed, so a shorter `duration` lands harder: 8.3% at 6 frames,+ 1.2% at 40.+- `getSpeedLinesDuration({ mode, duration, bounce, delay, speed })` returns the+ preview length, which adds a 24-frame hold: 55 frames for trail and 37 for+ focus.+- `delay` counts composition frames before the motion and is not scaled by+ `speed`. At another speed or frame rate, divide the motion frames by `speed`+ and multiply by `fps / 30`. A higher `speed` also draws longer streaks,+ because the element really moves faster.++<PropsTable title="Props"+ rows={[+ { name: "mode", type: '"trail" | "focus"', default: '"trail"', description: "Streaks behind a moving element, or an impact frame of converging lines" },+ { name: "from", type: "{ x: number; y: number }", default: "{ x: -0.25, y: 0.5 }", description: "Trail start of the element's center as fractions of the composition; off-screen values are fine" },+ { name: "to", type: "{ x: number; y: number }", default: "{ x, y }", description: "Trail landing point; falls back to the x, y point" },+ { name: "x", type: "number", default: "0.5", description: "Accent point as a fraction of the width: the focus center, and the trail landing point when to is not set" },+ { name: "y", type: "number", default: "0.5", description: "Accent point as a fraction of the height" },+ { name: "count", type: "number", default: "12", description: "Streaks spawned per flight in trail, about a third alive at once; rays in focus. Clamped to 1–64" },+ { name: "weight", type: "number", default: "2", description: "Stroke width in reference px, clamped to 0.5–12; caps are round" },+ { name: "spread", type: "number", default: "96", description: "Trail: width of the streak band across the path, and the fallback disc diameter. Focus: the closest the rays come to the point. Reference px, clamped to 8–480" },+ { name: "duration", type: "number", default: "14", description: "Trail frames from launch to contact at 30 fps, clamped to 4–120; the landing adds 6–29 frames depending on bounce" },+ { name: "bounce", type: "number", default: "0.5", description: "Momentum carried into the landing, 0–1. At 0 the element stops dead on the target; at 0.5 it overshoots 3.5% of the flight and swings back once; at 1 it overshoots 7.2% with a visible echo" },+ { name: "squash", type: "number", default: "0.5", description: "Squash and stretch, 0–1. The element stretches along its path with its speed, up to 1.3×, and squashes past the target, down to 0.8×, keeping its area. 0 keeps it rigid" },+ { name: "color", type: "string", default: '"#ffffff"', description: "Streaks, rays and the fallback disc" },+ { name: "seed", type: "number", default: "1", description: "Seeds streak timing, lanes and lengths, and ray angles and radii" },+ { name: "delay", type: "number", default: "0", description: "Composition frames before the motion starts; not scaled by speed" },+ { name: "speed", type: "number", default: "1", description: "Playback multiplier; 0 freezes the first frame" },+ { name: "children", type: "ReactNode", description: "The element trail moves and deforms, or places on the focus point; without it, trail flies a disc, and null draws the streaks alone" },+ { name: "className", type: "string", description: "Optional class name on the full-frame root" },+ ]}+/>diff --git a/content/docs/motion-graphics/squiggle.mdx b/content/docs/motion-graphics/squiggle.mdxnew file mode 100644index 00000000..7a5ec623--- /dev/null+++ b/content/docs/motion-graphics/squiggle.mdx@@ -0,0 +1,170 @@+---+title: Squiggle+description: A flat line draws itself along a straight course while its wave swims forward and calms, then erases toward the end+component: squiggle+vibe: clean+length: 66+useWhen:+ - "A word, a number, or a button needs a live underline or accent on the frame it lands, such as a click, a count finishing, or a beat."+ - "Two elements should be connected, or two parts of a video separated, by a line that draws itself with energy instead of a static rule."+ - "A flat vector accent in one brand color is needed many times per video, with no assets, fonts, or texture."+avoidWhen:+ - "The underline should look hand-drawn, with ink grain and stop-motion poses — use `ink-underline`."+ - "The moment needs short lines bursting out of a point, like a click or a pop, rather than one line along a course — use `trim-burst`."+ - "The accent should convey speed, with streaks rushing past an element — use `speed-lines`."+ - "The element should be circled rather than underlined or linked — use `scribble-circle`."+---++<ComponentPreview name="squiggle" />++<InstallBlock name="squiggle" />++## Usage++`Squiggle` draws one flat line along a straight course. The course starts at+`x, y`, given as fractions of the composition, and runs `length` reference px+at `angle`. The line is a traveling wave, and its shape is recomputed on every+frame. While the head runs out, the crests swim forward along the line and+the amplitude relaxes from lively to calm. After a short hold, the tail erases+toward the end point. Both ends stay pinned to the course, so the line leaves+its start and meets its end along the course direction.++```tsx+import { Backdrop } from "@/components/remocn/backdrop";+import { Squiggle } from "@/components/remocn/squiggle";++export const Accent = () => (+ <Backdrop+ fill={{ type: "color", value: "#002fa7" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <Squiggle />+ </Backdrop>+);+```++The component is an overlay. Its root fills the parent box, paints no+background, and ignores the pointer, so it composites over any scene. Sizes+are reference px at a 720px-tall composition and scale with `height / 720`,+like `confetti`, so the same props look the same at 720p, 1080p and 4K. Every+value derives from the Remotion frame, so seeking and rendering are+deterministic.++### On a moment++Put the squiggle in a `Sequence` that starts on the event frame, next to the+element it accents. Here the beat to stress is frame 18. The line fires on+that frame, draws under the word, and stays. Positions are fractions of the+frame and the length is in reference px, so convert the word's box with the+composition size.++```tsx+import { AbsoluteFill, Sequence, useVideoConfig } from "remotion";+import { Backdrop } from "@/components/remocn/backdrop";+import { Squiggle } from "@/components/remocn/squiggle";++const WORD = { left: 530, top: 290, width: 220, height: 88 };++export const Headline = () => {+ const { width, height } = useVideoConfig();++ return (+ <Backdrop+ fill={{ type: "color", value: "#002fa7" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <AbsoluteFill>+ <div+ style={{+ position: "absolute",+ left: WORD.left,+ top: WORD.top,+ width: WORD.width,+ lineHeight: `${WORD.height}px`,+ textAlign: "center",+ color: "#fafafa",+ fontSize: 72,+ fontWeight: 600,+ }}+ >+ faster+ </div>+ </AbsoluteFill>+ <Sequence from={18}>+ <Squiggle+ x={WORD.left / width}+ y={(WORD.top + WORD.height + 10) / height}+ length={(WORD.width * 720) / height}+ erase={false}+ />+ </Sequence>+ </Backdrop>+ );+};+```++To link two elements, start at the first one. Set `angle` to+`Math.atan2(dy, dx) * 180 / Math.PI`, and pass the distance between them,+converted to reference px, as `length`. To stagger several accents inside one+`Sequence`, give them different `delay` values.++## Timing++At 30 fps with `speed={1}` and the default props:++| Frames | Motion |+| --- | --- |+| 0 | Nothing is drawn |+| 0–24 | The head runs out along the line on an ease-out, with 16% drawn on frame 1 and 80% by frame 8 |+| 0–36 | The wave swims forward 1.5 cycles and the amplitude eases from `amplitude` to `amplitude × (1 − settle)` |+| 36–48 | The settled line holds still for `hold` frames |+| 48–66 | The tail erases toward the end point on an ease-in-out, and the pattern drifts another half cycle |+| 66–80 | The preview stays empty, then loops |++The head moves along the arc length, so a loop or a coil takes as long to draw+as a plain wave. The crests start at about 6 px per frame and slow to rest by+frame 36, after the head has landed. The amplitude only ever decreases, so the+line never overshoots its calm shape.++`squiggleLength` is 66, the frame where the tail reaches the end point. With+`erase={false}` the motion ends at frame 36 and the line stays.+`getSquiggleTimeline({ hold, erase })` returns every beat.+`getSquiggleDuration({ speed, delay, hold, erase })` returns the preview+length, the motion plus a short rest before the loop: 80 frames by default+and 60 without the erase. `delay` counts composition frames before the draw+starts and does not scale with `speed`. `hold` is part of the motion and does.+For another frame rate, multiply the beat frames by `fps / 30`.++## Variations++`shape="zigzag"` draws sharp corners with miter joins. `shape="loops"` turns+the wave into a cursive chain of loops, and `shape="coil"` into a spring seen+from the side. Both sit on the left of the drawing direction, so they stand+above a line drawn left to right. To hang them below, draw from the other end+with `angle={180}`. As the phase swims, the loops roll forward like a wheel+and the coil crawls like a turning screw. `settle={0}` keeps the lively+height to the end, and `settle={1}` calms any shape into a straight line.++<PropsTable title="Props"+ rows={[+ { name: "shape", type: '"wave" | "zigzag" | "loops" | "coil"', default: '"wave"', description: "Smooth sine, sharp triangle, cursive loop chain, or a spring seen from the side" },+ { name: "x", type: "number", default: "0.375", description: "Start of the course as a 0..1 fraction of the composition width; the default centers the default line on a 16:9 frame" },+ { name: "y", type: "number", default: "0.5", description: "Start of the course as a 0..1 fraction of the composition height" },+ { name: "length", type: "number", default: "320", description: "Course length in reference px at a 720px-tall composition" },+ { name: "angle", type: "number", default: "0", description: "Course direction in degrees; 0 runs right and positive values turn clockwise" },+ { name: "amplitude", type: "number", default: "14", description: "Half-height of the wave when the draw starts, in reference px" },+ { name: "wavelength", type: "number", default: "48", description: "Course distance of one cycle in reference px, at least 8" },+ { name: "weight", type: "number", default: "3", description: "Stroke width in reference px, with round caps" },+ { name: "color", type: "string", default: '"#ffffff"', description: "Stroke color" },+ { name: "settle", type: "number", default: "0.5", description: "Share of the amplitude that calms away, from 0 to 1; 1 settles into a straight line" },+ { name: "hold", type: "number", default: "12", description: "Frames at 30 fps that the settled line rests before the erase" },+ { name: "erase", type: "boolean", default: "true", description: "Erases the line toward its end point after the hold; false keeps it on screen" },+ { name: "delay", type: "number", default: "0", description: "Composition frames before the head leaves the start point" },+ { name: "speed", type: "number", default: "1", description: "Playback multiplier; 0 freezes before anything is drawn" },+ { name: "className", type: "string", description: "Optional class name on the full-frame root" },+ ]}+/>diff --git a/content/docs/motion-graphics/trim-burst.mdx b/content/docs/motion-graphics/trim-burst.mdxnew file mode 100644index 00000000..88f2ffe2--- /dev/null+++ b/content/docs/motion-graphics/trim-burst.mdx@@ -0,0 +1,177 @@+---+title: Trim Burst+description: Short strokes shoot out from a point and vanish in flight, each start chasing its end, to punctuate a click, a landing number or a beat+component: trim-burst+vibe: clean+length: 18+useWhen:+ - "A click, tap or toggle needs a quick punctuation mark, a ring of strokes that zips out from the point and is gone in about half a second."+ - "A number, badge or icon lands and the moment deserves a small flat accent around it, with the strokes born just outside the element."+ - "The same accent fires many times in one video, so it has to stay thin, one color and transparent over any scene."+avoidWhen:+ - "The moment is a celebration that should shower the frame with color — use `confetti`."+ - "The burst is the main event, an opener that takes over the frame and clears it for a title — use `radial-burst`."+ - "The lines should trail a moving element or converge on a point from the frame edges rather than burst out of it — use `speed-lines`."+ - "One line should draw itself along a course, like a live underline or a connector — use `squiggle`."+ - "The emphasis should look hand-drawn on paper rather than clean vector — use `scribble-circle`."+---++<ComponentPreview name="trim-burst" />++<InstallBlock name="trim-burst" />++## Usage++`TrimBurst` is a punctuation accent. A ring of short straight strokes shoots+out from a point and vanishes in flight. Each stroke is animated like Trim+Paths in After Effects, with its own curve for each end. The end, the outer+point, shoots out on a fast ease-out and brakes hard at its final distance.+The start, the inner point, holds for about three frames, then chases the end+on a smoother ease-in-out and catches up. So the stroke grows, travels near+full length, and shrinks to nothing at its outer distance. Lengths, angles and+launch times vary slightly per stroke from `seed`, so the ring never reads as+a rigid asterisk.++```tsx+import { Backdrop } from "@/components/remocn/backdrop";+import { TrimBurst } from "@/components/remocn/trim-burst";++export const Accent = () => (+ <Backdrop+ fill={{ type: "color", value: "#002fa7" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <TrimBurst />+ </Backdrop>+);+```++The component fills its parent, paints no background, and draws into one SVG,+so it composites over any scene. `x` and `y` place the burst center as+fractions of the composition. `innerRadius`, `reach`, `strokeLength` and+`weight` are pixels at a 720px-tall composition and scale with the height. The+same props look the same at 720p, 1080p and 4K. Everything derives from the+Remotion frame and the seed, so seeking and rendering are deterministic.++### On a moment++Start the burst on the event frame: put it in a `Sequence` that begins there+and center it on the element it punctuates. Set `innerRadius` just outside the+element so the strokes are born at its edge. Here a badge springs in and+reaches full size around frame 6, and the burst fires on that frame.+`trimBurstLength` covers the whole burst at the default `jitter` and `speed`,+so it is a safe `Sequence` duration.++```tsx+import { Sequence, spring, useCurrentFrame, useVideoConfig } from "remotion";+import { Backdrop } from "@/components/remocn/backdrop";+import { TrimBurst, trimBurstLength } from "@/components/remocn/trim-burst";++const LAND = 6;++const Badge = () => {+ const frame = useCurrentFrame();+ const { fps, height } = useVideoConfig();+ const size = 72 * (height / 720);+ const scale = spring({ frame, fps, config: { damping: 14, stiffness: 160 } });++ return (+ <div+ style={{+ position: "absolute",+ left: "70%",+ top: "40%",+ width: size,+ height: size,+ borderRadius: "50%",+ background: "#ffffff",+ transform: `translate(-50%, -50%) scale(${scale})`,+ }}+ />+ );+};++export const BadgeLanding = () => (+ <Backdrop+ fill={{ type: "color", value: "#002fa7" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <Badge />+ <Sequence from={LAND} durationInFrames={trimBurstLength}>+ <TrimBurst x={0.7} y={0.4} innerRadius={48} reach={40} />+ </Sequence>+ </Backdrop>+);+```++The badge is 72px wide and overshoots to about 81px, so an `innerRadius` of 48+keeps every stroke clear of it. `left` and `top` use the same fractions as `x`+and `y`, so the burst stays centered on the badge at any composition size.++## Timing++At 30 fps, `speed={1}` and the defaults:++| Frames | Motion |+| --- | --- |+| 0 | Nothing is drawn; every stroke still sits on the inner radius |+| 0–3 | Strokes launch one after another in a seeded order |+| 1–7 | Each end covers 36% of its reach one frame after launch and 60% after two, while its start holds near the inner radius, so the stroke grows |+| 4–9 | Strokes run near full length and travel outward as the ends brake and the starts pick up speed |+| 7–18 | Each start zips into its braking tip, and the stroke vanishes at the outer distance |+| 18–42 | The docs preview holds an empty frame before it loops |++A stroke lives 15 frames. Its start holds for about three frames, then+follows its own ease-in-out: it moves fastest around frame 9 and lands on the+end at frame 15, the frame the end arrives. At the defaults the stroke peaks+at about 77% of `reach` near frame 5 and travels near that length for a few+frames before it shrinks.++`strokeLength` is a soft cap on that length. On their own, the two curves open+a stroke to about 85% of `reach`, so the default of 56 only trims the peak. Set+`strokeLength` well below that, for short dashes on a long `reach`, and the+start is pulled along behind the end: each stroke travels as a dash of that+length, then its start zips it shut.++`trimBurstLength` is 18: the 15-frame stroke plus a launch spread of+`6 × jitter` frames. `getTrimBurstTimeline({ jitter, count })` returns those+parts. `getTrimBurstDuration({ speed, jitter, count, delay })` returns the+preview length, which adds a 24-frame empty hold. `delay` counts composition+frames before the burst fires. `speed` scales the motion, so at `speed={2}`+the burst lasts 9 frames. For another frame rate, multiply by `fps / 30`.++## Variations++`spread` below 360 turns the ring into a fan centered on `rotation`, measured+clockwise from 12 o'clock. For example, `spread={100}` with `count={5}` fans+five strokes upward over a number. `dots` adds a small dot just past each tip.+It pops 4 frames after its stroke launches, overshoots by 7%, and shrinks to+nothing as the stroke closes. `jitter={0}` gives a rigid ring that launches all+at once, and `jitter={1}` spreads the launches over 6 frames. `cap="butt"`+gives the strokes flat ends.++<PropsTable title="Props"+ rows={[+ { name: "x", type: "number", default: "0.5", description: "Burst center as a fraction of the composition width" },+ { name: "y", type: "number", default: "0.5", description: "Burst center as a fraction of the composition height" },+ { name: "count", type: "number", default: "8", description: "Number of strokes, rounded and clamped to 1–32" },+ { name: "innerRadius", type: "number", default: "16", description: "Distance from the center where strokes are born, in px at 720p; set it just outside the element" },+ { name: "reach", type: "number", default: "64", description: "How far each end travels past the inner radius, in px at 720p" },+ { name: "strokeLength", type: "number", default: "56", description: "Soft cap on the stroke length in px at 720p; the free chase peaks near 85% of reach, and lower values turn strokes into short dashes that travel before they zip shut" },+ { name: "weight", type: "number", default: "2", description: "Stroke width in px at 720p, clamped to 0.25–24" },+ { name: "rotation", type: "number", default: "0", description: "Direction of the first stroke, or the center of a fan, in degrees clockwise from 12 o'clock" },+ { name: "spread", type: "number", default: "360", description: "360 for a full ring, or the angle of a fan centered on rotation" },+ { name: "jitter", type: "number", default: "0.5", description: "Seeded variation from 0 to 1; offsets each angle by up to a quarter of the spacing, shortens strokes by up to 45% and spreads launches over up to 6 frames" },+ { name: "dots", type: "boolean", default: "false", description: "Adds a small dot just past each tip that pops and shrinks with its stroke" },+ { name: "cap", type: '"round" | "butt"', default: '"round"', description: "Stroke line cap" },+ { name: "color", type: "string", default: '"#ffffff"', description: "Stroke and dot color" },+ { name: "seed", type: "number", default: "1", description: "Seeds the per-stroke angles, lengths and launch order" },+ { name: "delay", type: "number", default: "0", description: "Composition frames to wait before the burst fires" },+ { name: "speed", type: "number", default: "1", description: "Playback multiplier; 0 never fires" },+ { name: "className", type: "string", description: "Optional class name on the full-frame root" },+ ]}+/>diff --git a/content/docs/motion-graphics/truchet-flip.mdx b/content/docs/motion-graphics/truchet-flip.mdxnew file mode 100644index 00000000..70ce360c--- /dev/null+++ b/content/docs/motion-graphics/truchet-flip.mdx@@ -0,0 +1,128 @@+---+title: Truchet Flip+description: Quarter-circle tiles snap a quarter turn as a wave crosses the grid, reconnecting the lines until they settle into rings, a calm field, or a circle+component: truchet-flip+vibe: clean+length: 102+useWhen:+ - "A scene needs a flat geometric pattern bed that moves by one rule, each tile turning a quarter as a wave passes and the lines reconnecting across the frame."+ - "An intro, section break, or title card should settle into a centered structure such as concentric rings or a circle made of small rings."+ - "A seamless background loop is needed in any brand color, with no shaders, images, or fonts."+avoidWhen:+ - "The moment calls for a one-shot abstract burst that clears the frame for a title — use `radial-burst`."+ - "The background should feel soft and organic rather than drawn with lines — use `shader-mesh-gradient`."+ - "The pattern should carry the cut into the next scene rather than sit behind it — use `grid-wave`."+---++<ComponentPreview name="truchet-flip" />++<InstallBlock name="truchet-flip" />++## Usage++`TruchetFlip` fills the frame with Truchet tiles. Each tile holds two+quarter-circle arcs on opposite corners, and every arc ends on an edge+midpoint, so neighboring tiles join into continuous lines. A wave crosses the+grid, and each tile it reaches snaps a quarter turn with a small overshoot.+The lines reconnect behind the wave, and mazes form and dissolve. Two passes+run through the seeded maze. A final pass then turns only the tiles that+differ from the target, and the pattern settles into a circle at the center,+ringed by concentric wavy loops.++```tsx+import { Backdrop } from "@/components/remocn/backdrop";+import { TruchetFlip } from "@/components/remocn/truchet-flip";++export const PatternBed = () => (+ <Backdrop+ fill={{ type: "color", value: "#002fa7" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <TruchetFlip />+ </Backdrop>+);+```++The component paints no background, so it composites over any scene; the+backdrop supplies the color. Tile size fits the shorter side of the+composition, and a tile corner sits exactly on the frame center, so the rings+stay centered at 16:9, 1:1 and 9:16. Everything is flat SVG geometry derived+from the Remotion frame and the seed, so seeking and rendering are+deterministic.++## Timing++At 30 fps, `speed={1}` and the default two passes:++| Frames | Motion |+| --- | --- |+| 0–6 | The seeded maze holds still |+| 6–48 | First pass turns every tile a quarter, clockwise, outward from the center |+| 30–72 | Second pass follows and turns every tile back |+| 60–102 | Resolve pass turns only the tiles that differ from the target |+| 102–120 | The resolved pattern holds |++Each turn takes 12 frames. The tile reaches its new angle on frame 4,+overshoots by about 6°, and lands exactly on the quarter by frame 12. The wave+needs 30 frames to cross the grid, so neighboring tiles start a few frames+apart and several are always mid-turn. A title placed over the animation can+enter around frame 96, as the last tiles settle.++`truchetFlipLength` is 102, the frame where the last tile settles with the+default two passes. `getTruchetFlipTimeline({ passes }).settled` gives that+frame for any pass count. `getTruchetFlipDuration({ speed, passes, loop })`+returns the preview duration at 30 fps, hold included. Each pass beyond the+first adds 24 frames. With `passes={0}` the maze resolves directly: the last+tile settles on frame 48 and the preview runs 66 frames. For another frame+rate, multiply by `fps / 30` and round up.++Set `loop` for a background. The resolved pattern holds for 24 frames, then a+return pass turns the changed tiles back to the opening maze. The 168-frame+cycle ends on the opening maze, so it repeats without a seam.++## Variations++`waveMode="diagonal"` sweeps from the top-left corner to the bottom-right, and+`waveMode="random"` turns tiles in a seeded shuffle. `resolve="field"` aligns+every tile into parallel wavy diagonals. `resolve="silhouette"` closes the+tiles inside a centered circle into small rings and wraps the field around+them. `variant="filled"` draws the arcs as quarter discs, and `secondaryColor`+colors alternate tiles for a two-tone checker.++```tsx+<Backdrop+ fill={{ type: "color", value: "#f1eee7" }}+ padding={0}+ radius={0}+ shadow=""+>+ <TruchetFlip+ tiles={14}+ weight={0.14}+ waveMode="diagonal"+ resolve="silhouette"+ color="#171717"+ secondaryColor="#d97757"+ loop+ />+</Backdrop>+```++<PropsTable title="Props"+ rows={[+ { name: "tiles", type: "number", default: "10", description: "Tiles across the shorter side, clamped to 4–24 and rounded; sets the tile size" },+ { name: "weight", type: "number", default: "0.2", description: "Stroke width as a fraction of the tile size, clamped to 0.04–0.34; ignored by the filled variant" },+ { name: "passes", type: "number", default: "2", description: "Full passes that turn every tile before the resolve pass, clamped to 0–4 and rounded" },+ { name: "waveMode", type: '"radial" | "diagonal" | "random"', default: '"radial"', description: "Turn order: outward from the center, a top-left to bottom-right sweep, or a seeded shuffle" },+ { name: "resolve", type: '"rings" | "field" | "silhouette"', default: '"rings"', description: "Structure the last pass settles into: concentric loops, parallel diagonals, or small rings inside a centered circle" },+ { name: "variant", type: '"stroke" | "filled"', default: '"stroke"', description: "Arcs as butt-capped strokes, or as filled quarter discs" },+ { name: "color", type: "string", default: '"#ffffff"', description: "Line or disc color" },+ { name: "secondaryColor", type: "string", default: "color", description: "Color of alternate tiles in a checkerboard; matches color for a single tone" },+ { name: "seed", type: "number", default: "1", description: "Seeds the opening maze and the random wave order" },+ { name: "speed", type: "number", default: "1", description: "Playback multiplier; 0 freezes the opening maze" },+ { name: "loop", type: "boolean", default: "false", description: "Adds a return pass so the cycle ends on its first frame" },+ { name: "className", type: "string", description: "Optional class name on the full-frame root" },+ ]}+/>diff --git a/content/docs/typography/echo-stack.mdx b/content/docs/typography/echo-stack.mdxnew file mode 100644index 00000000..b3d6ede1--- /dev/null+++ b/content/docs/typography/echo-stack.mdx@@ -0,0 +1,137 @@+---+title: Echo Stack+description: A word focuses in at the center while outline copies of it unfold above and below and keep drifting, like the one clear line on a spinning drum+component: echo-stack+vibe: premium+length: 26+useWhen:+ - "A one-word statement (a value, a promise) should hold the screen for a while and still feel alive."+ - "You want repetition to add weight to a word without adding any other text."+ - "A beat in a sequence of single words, where each word gets the same treatment and only the text changes."+avoidWhen:+ - "The word should just appear and stay still — use `focus-blur-resolve`."+ - "The repeats should run sideways as a strip of text — use `infinite-marquee`."+ - "The screen should fill with rows of text rather than a column around one word — use `type-wall`."+---++<ComponentPreview name="echo-stack" />++<InstallBlock name="echo-stack" />++## Usage++```tsx+// src/Root.tsx+import { AbsoluteFill, Composition } from "remotion";+import { EchoStack } from "@/components/remocn/echo-stack";++const Beat = () => (+ <AbsoluteFill style={{ backgroundColor: "#0a0a0a" }}>+ <EchoStack text="Bold." />+ </AbsoluteFill>+);++export const RemotionRoot = () => (+ <Composition+ id="EchoStack"+ component={Beat}+ durationInFrames={120}+ fps={30}+ width={1280}+ height={720}+ />+);+```++The word focuses in over 14 frames. From frame 8 the echoes unfold out of it:+the column starts compressed and opens to its full pitch by frame 26. After+that the column keeps scrolling one row every `cycle` frames in `direction`,+and loops without a seam. Echoes are hidden while they pass behind the word+and fade out toward the edges, so only about `echoes` rows show on each side.++The echo outline is built from the filled glyphs with an SVG filter rather than+a text stroke. Variable fonts keep overlapping contours inside letters like M+and K, and a text stroke draws them. The component paints no background and+centers the word in its parent. Sizes scale with `height / 720`.++<PropsTable title="Props"+ rows={[+ {+ name: "text",+ type: "string",+ default: "\"Bold.\"",+ description: "The word at the center",+ },+ {+ name: "fontSize",+ type: "number",+ default: "170",+ description: "Font size in reference px at 720p",+ },+ {+ name: "fontWeight",+ type: "number",+ default: "800",+ description: "Font weight",+ },+ {+ name: "fontFamily",+ type: "string",+ default: "Inter",+ description: "Font family",+ },+ {+ name: "color",+ type: "string",+ default: "\"#fafafa\"",+ description: "Color of the main word",+ },+ {+ name: "echoColor",+ type: "string",+ default: "same as color",+ description: "Outline color of the echoes",+ },+ {+ name: "echoes",+ type: "number",+ default: "3",+ description: "Echo rows on each side before they fade out",+ },+ {+ name: "echoOpacity",+ type: "number",+ default: "0.35",+ description: "Opacity of the nearest echo",+ },+ {+ name: "strokeWidth",+ type: "number",+ default: "1.5",+ description: "Echo outline width in reference px",+ },+ {+ name: "direction",+ type: "\"up\" | \"down\"",+ default: "\"up\"",+ description: "Which way the column drifts",+ },+ {+ name: "cycle",+ type: "number",+ default: "60",+ description: "Frames for the column to move one row",+ },+ {+ name: "speed",+ type: "number",+ default: "1",+ description: "Timeline speed multiplier",+ },+ {+ name: "className",+ type: "string",+ description: "Optional className passed to the wrapper",+ },+ ]}+/>diff --git a/content/docs/typography/glyph-anatomy.mdx b/content/docs/typography/glyph-anatomy.mdxnew file mode 100644index 00000000..ab1a7110--- /dev/null+++ b/content/docs/typography/glyph-anatomy.mdx@@ -0,0 +1,120 @@+---+title: Glyph Anatomy+description: A word builds as in a font editor, with metric guides, anchors along each contour and Bézier handles that pull straight segments into curves before the glyphs fill+component: glyph-anatomy+vibe: tech+length: 66+useWhen:+ - "A product for designers, a type or a design tool, should show its craft: the letters are built from points and curves on screen."+ - "A title should feel constructed and precise, with the scaffolding visible for a moment before the clean word."+ - "You want to show how a letter is made, for a talk, a course or a type specimen."+avoidWhen:+ - "The outline should simply draw itself without points or handles — use `outline-trace`."+ - "The design-tool feel should come from a selection box around the word instead of its construction — use `selection-snap`."+ - "The word only needs a quiet reveal — use `soft-blur-in`."+---++<ComponentPreview name="glyph-anatomy" />++<InstallBlock name="glyph-anatomy" />++## Usage++```tsx+// src/Root.tsx+import { AbsoluteFill, Composition } from "remotion";+import { GlyphAnatomy } from "@/components/remocn/glyph-anatomy";++const Title = () => (+ <AbsoluteFill style={{ backgroundColor: "#0a0a0a" }}>+ <GlyphAnatomy text="Glyph" />+ </AbsoluteFill>+);++export const RemotionRoot = () => (+ <Composition+ id="GlyphAnatomy"+ component={Title}+ durationInFrames={96}+ fps={30}+ width={1280}+ height={720}+ />+);+```++Four guides draw across first: cap height, x-height, baseline and descender,+read from the font's own metrics. Then, letter by letter two frames apart,+anchors pop along each contour in drawing order. While they appear the+outline runs straight from anchor to anchor. Handles grow out of the anchors+next and pull each segment into its curve, overshooting a little before they+settle. The glyphs fill in around frame 40 and the points, handles and guides+fade out, leaving the clean word. `keepPoints` keeps the scaffolding.++TrueType fonts describe curves with quadratics; the component converts them to+cubics so every curve shows one handle on each end, as in Figma or Glyphs.+Static instances of variable fonts keep overlapping contours, and they show in+the outline the way they would in a font editor.++`fontUrl` defaults to Inter ExtraBold from Google Fonts' static CDN and accepts+any `.ttf`, `.otf` or `.woff` file. The labels use Inter from+`@remotion/google-fonts`. The word centers in its parent and sizes scale with+`height / 720`.++<PropsTable title="Props"+ rows={[+ {+ name: "text",+ type: "string",+ default: "\"Glyph\"",+ description: "The word to build. Short words show the construction best",+ },+ {+ name: "fontUrl",+ type: "string",+ default: "Inter ExtraBold (gstatic ttf)",+ description: "URL of a .ttf, .otf or .woff file the outlines are parsed from",+ },+ {+ name: "fontSize",+ type: "number",+ default: "200",+ description: "Font size in reference px at 720p",+ },+ {+ name: "color",+ type: "string",+ default: "\"#fafafa\"",+ description: "Outline and fill color",+ },+ {+ name: "guideColor",+ type: "string",+ default: "\"#0d99ff\"",+ description: "Guides, anchor borders and handles",+ },+ {+ name: "guides",+ type: "boolean",+ default: "true",+ description: "Draw the metric guides with their labels",+ },+ {+ name: "keepPoints",+ type: "boolean",+ default: "false",+ description: "Keep anchors, handles and guides after the fill",+ },+ {+ name: "speed",+ type: "number",+ default: "1",+ description: "Timeline speed multiplier",+ },+ {+ name: "className",+ type: "string",+ description: "Optional className passed to the wrapper",+ },+ ]}+/>diff --git a/content/docs/typography/index.mdx b/content/docs/typography/index.mdxindex d1e94b7e..66f6bfd6 100644--- a/content/docs/typography/index.mdx+++ b/content/docs/typography/index.mdx@@ -230,3 +230,81 @@ Word-by-word builds with motion and momentum.},]}/>++## Showreel++Heavy display type that snaps, echoes and spins on flat color fields.++<ComponentCardGrid+ items={[+ {+ name: "Selection Snap",+ description: "A thin word snaps into a design-tool selection while it goes from Thin to Black",+ status: "stable",+ href: "/docs/typography/selection-snap",+ },+ {+ name: "Echo Stack",+ description: "A word focuses in while outline copies drift above and below it",+ status: "stable",+ href: "/docs/typography/echo-stack",+ },+ {+ name: "Type Wall",+ description: "Rows of one word fill the frame in alternating directions and faces",+ status: "stable",+ href: "/docs/typography/type-wall",+ },+ {+ name: "Ring Text",+ description: "Text runs around a tilted 3D band that spins",+ status: "stable",+ href: "/docs/typography/ring-text",+ },+ {+ name: "Period Drop",+ description: "A dot falls, bounces with squash and stretch, and settles as the period",+ status: "stable",+ href: "/docs/typography/period-drop",+ },+ ]}+/>++## Vector type++Type built the way a motion designer builds it: trim paths on real glyph outlines, a font editor's points and handles, striped type, text on a path and a repeater.++<ComponentCardGrid+ items={[+ {+ name: "Outline Trace",+ description: "Every glyph contour draws itself as a stroke, then the fill wipes up inside each letter",+ status: "stable",+ href: "/docs/typography/outline-trace",+ },+ {+ name: "Glyph Anatomy",+ description: "Anchors and Bézier handles pull straight segments into curves before the word fills",+ status: "stable",+ href: "/docs/typography/glyph-anatomy",+ },+ {+ name: "Stripe Type",+ description: "Horizontal bands slide in from alternating sides and lock into a striped word",+ status: "stable",+ href: "/docs/typography/stripe-type",+ },+ {+ name: "Path Ride",+ description: "Text rides a self-drawing curve, then the curve pulls taut into a straight line",+ status: "stable",+ href: "/docs/typography/path-ride",+ },+ {+ name: "Type Repeater",+ description: "Copies of a word unfold into a tunnel, a spiral or a fan, then fold back",+ status: "stable",+ href: "/docs/typography/type-repeater",+ },+ ]}+/>diff --git a/content/docs/typography/meta.json b/content/docs/typography/meta.jsonindex bbccfaf1..221291fa 100644--- a/content/docs/typography/meta.json+++ b/content/docs/typography/meta.json@@ -63,7 +63,17 @@"perspective-squeeze","extrude-pop","chromatic-wave",- "stretch-in"+ "stretch-in",+ "selection-snap",+ "echo-stack",+ "type-wall",+ "ring-text",+ "period-drop",+ "outline-trace",+ "glyph-anatomy",+ "stripe-type",+ "path-ride",+ "type-repeater"],"icon": "TextFontIcon"}diff --git a/content/docs/typography/outline-trace.mdx b/content/docs/typography/outline-trace.mdxnew file mode 100644index 00000000..6bb0016d--- /dev/null+++ b/content/docs/typography/outline-trace.mdx@@ -0,0 +1,132 @@+---+title: Outline Trace+description: Every glyph contour draws itself as a stroke, letter by letter, then the fill wipes up inside each letter and the stroke fades into it+component: outline-trace+vibe: premium+length: 44+useWhen:+ - "A title should be drawn rather than revealed, like a trim path running around the real letterforms."+ - "You want a crafted, vector-native entrance for a brand word or a headline in any font you can point to."+ - "An outline-only look is wanted: set `fill` off and the drawn contours stay."+avoidWhen:+ - "The text should look handwritten, stroke by stroke in a script face — use `handwrite`."+ - "The letters should fly in and deform rather than be drawn — use `stretch-in`."+ - "The build should show the construction points and handles of a font editor — use `glyph-anatomy`."+---++<ComponentPreview name="outline-trace" />++<InstallBlock name="outline-trace" />++## Usage++```tsx+// src/Root.tsx+import { AbsoluteFill, Composition } from "remotion";+import { OutlineTrace } from "@/components/remocn/outline-trace";++const Title = () => (+ <AbsoluteFill style={{ backgroundColor: "#ff4d1a" }}>+ <OutlineTrace text="Outline" color="#111111" />+ </AbsoluteFill>+);++export const RemotionRoot = () => (+ <Composition+ id="OutlineTrace"+ component={Title}+ durationInFrames={75}+ fps={30}+ width={1280}+ height={720}+ />+);+```++The letters are geometry parsed out of the font file with `opentype.js`, so the+stroke runs along the actual contours. Each letter starts `stagger` frames+after the previous one. Its outer contours draw over 18 frames; counters, such+as the hole in an a or an e, start four frames later. When the outline has+closed, the fill rises from the bottom of the letter and the stroke fades into+it, so the resting word is exactly the glyphs. `keepStroke` leaves the stroke+on top of the fill, and `fill={false}` keeps the drawn outline only.++Static instances of variable fonts, including the default Inter, keep+overlapping contours inside some letters (the bar of a t crosses its stem). A+mask hides the part of the stroke that runs inside the letter's filled shape,+so those overlaps never draw.++`fontUrl` defaults to Inter ExtraBold from Google Fonts' static CDN. Point it+at any `.ttf`, `.otf` or `.woff` file; `.woff2` is not supported. The render+is held until the font has loaded. The word centers in its parent and sizes+scale with `height / 720`.++<PropsTable title="Props"+ rows={[+ {+ name: "text",+ type: "string",+ default: "\"Outline\"",+ description: "The text to draw",+ },+ {+ name: "fontUrl",+ type: "string",+ default: "Inter ExtraBold (gstatic ttf)",+ description: "URL of a .ttf, .otf or .woff file the outlines are parsed from",+ },+ {+ name: "fontSize",+ type: "number",+ default: "150",+ description: "Font size in reference px at 720p",+ },+ {+ name: "color",+ type: "string",+ default: "\"#fafafa\"",+ description: "Fill color",+ },+ {+ name: "strokeColor",+ type: "string",+ default: "same as color",+ description: "Stroke color",+ },+ {+ name: "strokeWidth",+ type: "number",+ default: "2.5",+ description: "Stroke width in reference px",+ },+ {+ name: "stagger",+ type: "number",+ default: "3",+ description: "Frames between letters",+ },+ {+ name: "fill",+ type: "boolean",+ default: "true",+ description: "Fill the letters after the outline draws",+ },+ {+ name: "keepStroke",+ type: "boolean",+ default: "false",+ description: "Keep the stroke on top of the fill",+ },+ {+ name: "speed",+ type: "number",+ default: "1",+ description: "Timeline speed multiplier",+ },+ {+ name: "className",+ type: "string",+ description: "Optional className passed to the wrapper",+ },+ ]}+/>diff --git a/content/docs/typography/path-ride.mdx b/content/docs/typography/path-ride.mdxnew file mode 100644index 00000000..804d26f2--- /dev/null+++ b/content/docs/typography/path-ride.mdx@@ -0,0 +1,128 @@+---+title: Path Ride+description: A line draws itself along a curve with the text riding behind its head, then the curve pulls taut and the text settles on a straight, centered baseline+component: path-ride+vibe: playful+length: 70+useWhen:+ - "A tagline or a short phrase should travel across the frame before it settles, leading the eye from one side to the other."+ - "You want text on a path, with each letter turned to the curve, and a clean readable line at the end."+ - "The motion should follow a custom route: pass any SVG path in 1280×720 space."+avoidWhen:+ - "The line should be an accent on its own, with no text riding it — use `squiggle`."+ - "The text should loop around a closed ring — use `ring-text`."+ - "The text should scroll in a straight strip — use `infinite-marquee`."+---++<ComponentPreview name="path-ride" />++<InstallBlock name="path-ride" />++## Usage++```tsx+// src/Root.tsx+import { AbsoluteFill, Composition } from "remotion";+import { PathRide } from "@/components/remocn/path-ride";++const Tagline = () => (+ <AbsoluteFill style={{ backgroundColor: "#ff4d1a" }}>+ <PathRide+ text="Follow the line"+ color="#111111"+ lineColor="#fafafa"+ path="M 120 560 C 360 120 560 120 640 360 S 920 600 1160 160"+ />+ </AbsoluteFill>+);++export const RemotionRoot = () => (+ <Composition+ id="PathRide"+ component={Tagline}+ durationInFrames={96}+ fps={30}+ width={1280}+ height={720}+ />+);+```++The line draws along `path` over 40 frames with a dot at its head. The text+trails the head, last letter first, and every letter stands on the curve,+turned to its tangent and lifted clear of the line. Letters fade in over their+first half-em on the curve.++From frame 50 the curve pulls taut: every point of the path moves toward a+straight baseline, where arc length maps one to one onto x, so the text keeps+its spacing while the line and the letters straighten together. The line then+erases from its tail, and by frame 70 the text rests alone, centered on the+frame.++`path` is an SVG path in a 1280×720 reference frame, centered and scaled to the+composition; positions are sampled along it once. Letter widths and the+baseline are measured from the loaded font. Sizes scale with `height / 720`.++<PropsTable title="Props"+ rows={[+ {+ name: "text",+ type: "string",+ default: "\"Follow the line\"",+ description: "The text that rides the line",+ },+ {+ name: "path",+ type: "string",+ default: "S-curve across the frame",+ description: "SVG path data in 1280×720 reference space. It should be longer than the text",+ },+ {+ name: "fontSize",+ type: "number",+ default: "44",+ description: "Font size in reference px at 720p",+ },+ {+ name: "fontWeight",+ type: "number",+ default: "700",+ description: "Font weight",+ },+ {+ name: "fontFamily",+ type: "string",+ default: "Inter",+ description: "Font family",+ },+ {+ name: "color",+ type: "string",+ default: "\"#fafafa\"",+ description: "Text color",+ },+ {+ name: "lineColor",+ type: "string",+ default: "\"#D97757\"",+ description: "Line and head dot color",+ },+ {+ name: "lineWidth",+ type: "number",+ default: "3",+ description: "Line width in reference px",+ },+ {+ name: "speed",+ type: "number",+ default: "1",+ description: "Timeline speed multiplier",+ },+ {+ name: "className",+ type: "string",+ description: "Optional className passed to the wrapper",+ },+ ]}+/>diff --git a/content/docs/typography/period-drop.mdx b/content/docs/typography/period-drop.mdxnew file mode 100644index 00000000..918e420a--- /dev/null+++ b/content/docs/typography/period-drop.mdx@@ -0,0 +1,116 @@+---+title: Period Drop+description: A word rises out of its line, then a colored dot falls from above the frame, bounces with squash and stretch, and settles as the period+component: period-drop+vibe: playful+length: 47+useWhen:+ - "An end card or a logo lockup should land with one physical, memorable beat."+ - "A brand word should finish with a colored period, as in a wordmark."+ - "A statement needs a full stop that the viewer actually sees arrive."+avoidWhen:+ - "The lockup is a row of brand marks rather than a word — use `logo-enter`."+ - "The word should only rise out of its line, with no accent — use `mask-reveal-up`."+ - "The ending should be quiet, without any bounce — use `soft-blur-in`."+---++<ComponentPreview name="period-drop" />++<InstallBlock name="period-drop" />++## Usage++```tsx+// src/Root.tsx+import { AbsoluteFill, Composition } from "remotion";+import { PeriodDrop } from "@/components/remocn/period-drop";++const EndCard = () => (+ <AbsoluteFill style={{ backgroundColor: "#0a0a0a" }}>+ <PeriodDrop text="remocn" dotColor="#ff4d1a" />+ </AbsoluteFill>+);++export const RemotionRoot = () => (+ <Composition+ id="PeriodDrop"+ component={EndCard}+ durationInFrames={75}+ fps={30}+ width={1280}+ height={720}+ />+);+```++Each letter rises out of a clip at its line over 12 frames, two frames apart.+At frame 20 the dot drops from above the frame and lands at frame 32 on the+baseline right after the last letter. It bounces twice, each time leaving at+0.35 of its previous speed, and comes to rest at frame 47.++The dot stretches with its speed in flight and squashes on each impact, keeping+its area. The stretch tops out at 1.3× and the squash at 0.78×; later impacts+squash less. That is well past the 2–4% squash the motion principles suggest+for UI, on purpose: the bounce is the effect.++The dot is an inline element after the word, so it lands wherever the word+ends without measuring it. The component paints no background and centers the+word in its parent. Sizes scale with `height / 720`.++<PropsTable title="Props"+ rows={[+ {+ name: "text",+ type: "string",+ default: "\"remocn\"",+ description: "The word before the period",+ },+ {+ name: "fontSize",+ type: "number",+ default: "160",+ description: "Font size in reference px at 720p",+ },+ {+ name: "fontWeight",+ type: "number",+ default: "800",+ description: "Font weight",+ },+ {+ name: "fontFamily",+ type: "string",+ default: "Inter",+ description: "Font family",+ },+ {+ name: "color",+ type: "string",+ default: "\"#fafafa\"",+ description: "Word color",+ },+ {+ name: "dotColor",+ type: "string",+ default: "\"#D97757\"",+ description: "Color of the period",+ },+ {+ name: "dotSize",+ type: "number",+ default: "0.2",+ description: "Period diameter in em",+ },+ {+ name: "speed",+ type: "number",+ default: "1",+ description: "Timeline speed multiplier",+ },+ {+ name: "className",+ type: "string",+ description: "Optional className passed to the wrapper",+ },+ ]}+/>diff --git a/content/docs/typography/ring-text.mdx b/content/docs/typography/ring-text.mdxnew file mode 100644index 00000000..082eaed9--- /dev/null+++ b/content/docs/typography/ring-text.mdx@@ -0,0 +1,140 @@+---+title: Ring Text+description: Text runs around a tilted 3D band that spins, reading on the near side and mirrored on the far side+component: ring-text+vibe: playful+length: sustained+useWhen:+ - "A headline needs a dimensional object next to it, and the object itself should carry a short phrase."+ - "A tagline, a feature name or a slogan should loop continuously in a compact spot."+ - "You want a badge-like accent that reads as 3D without any 3D library or assets."+avoidWhen:+ - "The phrase should scroll flat across the frame — use `infinite-marquee`."+ - "The text should pop out of the plane as a solid extruded word — use `extrude-pop`."+ - "The motion should be ribbons bursting outward rather than a steady ring — use `radial-burst`."+---++<ComponentPreview name="ring-text" />++<InstallBlock name="ring-text" />++## Usage++```tsx+// src/Root.tsx+import { AbsoluteFill, Composition } from "remotion";+import { RingText } from "@/components/remocn/ring-text";++const Ring = () => (+ <AbsoluteFill style={{ backgroundColor: "#d4ff1f" }}>+ <RingText text="Type in motion" color="#d4ff1f" band="#0a0a0a" />+ </AbsoluteFill>+);++export const RemotionRoot = () => (+ <Composition+ id="RingText"+ component={Ring}+ durationInFrames={180}+ fps={30}+ width={1280}+ height={720}+ />+);+```++Every character sits on its own panel, placed around the ring with+`rotateY(θ) translateZ(radius)`, and the panel background forms the band. The+text and separator repeat as many times as fit the circumference, and the+remainder is spread as letter spacing so the band closes without a gap. A+phrase longer than one lap grows the radius instead.++The ring is viewed from above: the near side reads left to right, and the far+side shows the letters mirrored and dimmed. It turns once every `period`+frames, and its tilt sways by six degrees. It arrives scaled down, spinning+fast, and settles into its cruise speed by frame 30.++The ring is centered in its parent; place it with a wrapper. Sizes scale with+`height / 720`.++<PropsTable title="Props"+ rows={[+ {+ name: "text",+ type: "string",+ default: "\"Type in motion\"",+ description: "The phrase around the ring",+ },+ {+ name: "separator",+ type: "string",+ default: "\"•\"",+ description: "Glyph between repeats. An empty string leaves a space",+ },+ {+ name: "radius",+ type: "number",+ default: "210",+ description: "Ring radius in reference px. Long text grows it",+ },+ {+ name: "fontSize",+ type: "number",+ default: "40",+ description: "Font size in reference px. The band is 1.5em tall",+ },+ {+ name: "fontWeight",+ type: "number",+ default: "800",+ description: "Font weight",+ },+ {+ name: "fontFamily",+ type: "string",+ default: "Inter",+ description: "Font family",+ },+ {+ name: "color",+ type: "string",+ default: "\"#fafafa\"",+ description: "Letter color",+ },+ {+ name: "band",+ type: "string",+ default: "\"#0a0a0a\"",+ description: "Band color",+ },+ {+ name: "tilt",+ type: "number",+ default: "38",+ description: "Degrees the ring leans toward the camera",+ },+ {+ name: "roll",+ type: "number",+ default: "-16",+ description: "Degrees the ring is rotated in the frame",+ },+ {+ name: "period",+ type: "number",+ default: "240",+ description: "Frames for one full turn",+ },+ {+ name: "speed",+ type: "number",+ default: "1",+ description: "Timeline speed multiplier",+ },+ {+ name: "className",+ type: "string",+ description: "Optional className passed to the wrapper",+ },+ ]}+/>diff --git a/content/docs/typography/selection-snap.mdx b/content/docs/typography/selection-snap.mdxnew file mode 100644index 00000000..5f15ed80--- /dev/null+++ b/content/docs/typography/selection-snap.mdx@@ -0,0 +1,122 @@+---+title: Selection Snap+description: A thin word in a loose viewfinder snaps into a design-tool selection while it goes from Thin to Black, pops its handles and counts up a size badge+component: selection-snap+vibe: tech+length: 38+useWhen:+ - "A single word should read as something being designed: a design tool, a component library, a type or layout feature."+ - "You want a weight change to carry the beat — the word grows from Thin to Black inside the frame instead of just appearing."+ - "The title needs a precise, UI-flavored accent (selection box, handles, a W × H readout) without building any interface chrome."+avoidWhen:+ - "The word should enter with physical motion rather than change in place — use `stretch-in`."+ - "A plain, quiet reveal is enough and the design-tool look would distract — use `soft-blur-in`."+ - "The text is a full sentence; the selection frames one short word and reads poorly around a line — use `kinetic-center-build`."+---++<ComponentPreview name="selection-snap" />++<InstallBlock name="selection-snap" />++## Usage++```tsx+// src/Root.tsx+import { AbsoluteFill, Composition } from "remotion";+import { SelectionSnap } from "@/components/remocn/selection-snap";++const Title = () => (+ <AbsoluteFill style={{ backgroundColor: "#0a0a0a" }}>+ <SelectionSnap text="Frame" accent="#ff4d1a" selectionColor="#3d5afe" />+ </AbsoluteFill>+);++export const RemotionRoot = () => (+ <Composition+ id="SelectionSnap"+ component={Title}+ durationInFrames={75}+ fps={30}+ width={1280}+ height={720}+ />+);+```++The word starts at `fromWeight` inside four corner brackets. Around frame 14+the frame snaps tight with a small overshoot while the weight runs to+`toWeight` and the color turns to `accent`. The bracket arms grow along the+edges until they close into a one-pixel box, the eight handles pop in corners+first, and the badge counts up to the snapped box size in reference px.++The weight is continuous because Inter from `@remotion/google-fonts` is one+variable file: the component drives `font-variation-settings`. The box is a+wrapper around the text, so it follows the word as it widens. With a static+`fontFamily` the weight steps through the faces you load instead of gliding.++The component paints no background and centers the word in its parent. Sizes+are reference px at a 720px-tall composition and scale with `height / 720`.++<PropsTable title="Props"+ rows={[+ {+ name: "text",+ type: "string",+ default: "\"Frame\"",+ description: "The word inside the selection. One short word reads best",+ },+ {+ name: "fontSize",+ type: "number",+ default: "150",+ description: "Font size in reference px at 720p",+ },+ {+ name: "fontFamily",+ type: "string",+ default: "Inter",+ description: "Font family. Use a variable font for a continuous weight change",+ },+ {+ name: "fromWeight / toWeight",+ type: "number",+ default: "100 / 900",+ description: "Weight before and after the snap",+ },+ {+ name: "color",+ type: "string",+ default: "\"#fafafa\"",+ description: "Text color before the snap",+ },+ {+ name: "accent",+ type: "string",+ default: "\"#D97757\"",+ description: "Text color after the snap",+ },+ {+ name: "selectionColor",+ type: "string",+ default: "\"#0d99ff\"",+ description: "Brackets, box, handle borders and badge",+ },+ {+ name: "badge",+ type: "boolean",+ default: "true",+ description: "Show the W × H badge under the box",+ },+ {+ name: "speed",+ type: "number",+ default: "1",+ description: "Timeline speed multiplier",+ },+ {+ name: "className",+ type: "string",+ description: "Optional className passed to the wrapper",+ },+ ]}+/>diff --git a/content/docs/typography/stripe-type.mdx b/content/docs/typography/stripe-type.mdxnew file mode 100644index 00000000..2b67a8b2--- /dev/null+++ b/content/docs/typography/stripe-type.mdx@@ -0,0 +1,136 @@+---+title: Stripe Type+description: A word cut into horizontal bands, as in the IBM logo, slides together from alternating sides and locks, then can pass on through+component: stripe-type+vibe: tech+length: 30+useWhen:+ - "A bold word needs a graphic, engineered entrance on a flat field, such as a product name or a section title."+ - "You want the striped-logo look as the resting state, or as a transition into solid type with `settle` set to solid."+ - "A word should enter and leave in one move: the bands arrive from alternating sides and exit through the other."+avoidWhen:+ - "The word should split along its letters rather than in horizontal bands — use `typed-split-wipe`."+ - "The whole frame should fill with moving rows of type — use `type-wall`."+ - "A soft, quiet entrance fits better — use `mask-reveal-up`."+---++<ComponentPreview name="stripe-type" />++<InstallBlock name="stripe-type" />++## Usage++```tsx+// src/Root.tsx+import { AbsoluteFill, Composition } from "remotion";+import { StripeType } from "@/components/remocn/stripe-type";++const Title = () => (+ <AbsoluteFill style={{ backgroundColor: "#2b3bff" }}>+ <StripeType text="Launch" />+ </AbsoluteFill>+);++export const RemotionRoot = () => (+ <Composition+ id="StripeType"+ component={Title}+ durationInFrames={100}+ fps={30}+ width={1280}+ height={720}+ />+);+```++The bands cover the word's ink, from the top of its tallest letter to the+bottom of its lowest, measured from the loaded font. With `stripes` bands and+a `gap` share of each pitch left empty, the first band starts at the top and+the last ends at the bottom. Each band is a copy of the text clipped to its+strip.++Band 0 enters from the left, band 1 from the right, and so on, two frames+apart, each over 16 frames with an expo ease. The word is whole at frame 30+for eight bands. `settle="solid"` closes the gaps over the next ten frames.+With `exit`, after `hold` frames the bands carry on in the direction they came+from and leave through the other side. `getStripeTypeDuration` gives the+length for any set of props.++The component paints no background and centers the word in its parent. Sizes+scale with `height / 720`.++<PropsTable title="Props"+ rows={[+ {+ name: "text",+ type: "string",+ default: "\"Launch\"",+ description: "The word to stripe",+ },+ {+ name: "fontSize",+ type: "number",+ default: "180",+ description: "Font size in reference px at 720p",+ },+ {+ name: "fontWeight",+ type: "number",+ default: "800",+ description: "Font weight. Heavy weights stripe best",+ },+ {+ name: "fontFamily",+ type: "string",+ default: "Inter",+ description: "Font family",+ },+ {+ name: "color",+ type: "string",+ default: "\"#fafafa\"",+ description: "Text color",+ },+ {+ name: "stripes",+ type: "number",+ default: "8",+ description: "Number of bands",+ },+ {+ name: "gap",+ type: "number",+ default: "0.35",+ description: "Share of each band pitch left empty",+ },+ {+ name: "settle",+ type: "\"striped\" | \"solid\"",+ default: "\"striped\"",+ description: "Keep the gaps, or close them into solid type",+ },+ {+ name: "exit",+ type: "boolean",+ default: "true",+ description: "Let the bands pass on through after the hold",+ },+ {+ name: "hold",+ type: "number",+ default: "30",+ description: "Frames the word rests before the exit",+ },+ {+ name: "speed",+ type: "number",+ default: "1",+ description: "Timeline speed multiplier",+ },+ {+ name: "className",+ type: "string",+ description: "Optional className passed to the wrapper",+ },+ ]}+/>diff --git a/content/docs/typography/type-repeater.mdx b/content/docs/typography/type-repeater.mdxnew file mode 100644index 00000000..c3df652c--- /dev/null+++ b/content/docs/typography/type-repeater.mdx@@ -0,0 +1,132 @@+---+title: Type Repeater+description: An After Effects style repeater on a word, where copies unfold into a tunnel, a spiral or a fan behind it, breathe, then fold back into the word+component: type-repeater+vibe: playful+length: 90+useWhen:+ - "One word should hit hard for a beat, with repetition giving it depth and energy around a still, readable center."+ - "You want a motion-graphics flourish for a title card, a section break or a loop."+ - "A single word needs a backdrop made from itself, in the word's color stepping to an accent."+avoidWhen:+ - "The repeats should stack in a quiet vertical column above and below the word — use `echo-stack`."+ - "The whole frame should fill with scrolling rows of the word — use `type-wall`."+ - "The word should be carried by a spinning 3D band — use `ring-text`."+---++<ComponentPreview name="type-repeater" />++<InstallBlock name="type-repeater" />++## Usage++```tsx+// src/Root.tsx+import { AbsoluteFill, Composition } from "remotion";+import { TypeRepeater } from "@/components/remocn/type-repeater";++const Beat = () => (+ <AbsoluteFill style={{ backgroundColor: "#ff4d1a" }}>+ <TypeRepeater text="Repeat" mode="tunnel" color="#111111" accent="#fafafa" />+ </AbsoluteFill>+);++export const RemotionRoot = () => (+ <Composition+ id="TypeRepeater"+ component={Beat}+ durationInFrames={100}+ fps={30}+ width={1280}+ height={720}+ />+);+```++Copy 0 is the word itself and never moves. Every further copy gets one more+step of the mode's transform, scaled by the spread:++- `tunnel` grows each copy by 1.2× around the center, a zoom tunnel behind the+ word.+- `spiral` grows each copy by 1.1× and turns it 12°.+- `fan` turns copies 11° to alternating sides around a pivot below the word.++The word comes in over ten frames. The spread opens over frames 10 to 34 with+a small overshoot, breathes by 6% until frame 70, and folds back to zero by+frame 90. Copies step from `color` toward `accent` and fade with their index.+With `outline` on, the copies are outlines built from their filled glyphs by+an SVG filter, which keeps the variable font's overlapping contours out of+sight.++The component paints no background and centers the word in its parent. Sizes+scale with `height / 720`.++<PropsTable title="Props"+ rows={[+ {+ name: "text",+ type: "string",+ default: "\"Repeat\"",+ description: "The word to repeat",+ },+ {+ name: "mode",+ type: "\"tunnel\" | \"spiral\" | \"fan\"",+ default: "\"tunnel\"",+ description: "The repeater transform",+ },+ {+ name: "copies",+ type: "number",+ default: "12",+ description: "Number of copies including the word",+ },+ {+ name: "fontSize",+ type: "number",+ default: "110",+ description: "Font size in reference px at 720p",+ },+ {+ name: "fontWeight",+ type: "number",+ default: "800",+ description: "Font weight",+ },+ {+ name: "fontFamily",+ type: "string",+ default: "Inter",+ description: "Font family",+ },+ {+ name: "color",+ type: "string",+ default: "\"#fafafa\"",+ description: "Color of the word and the first copies",+ },+ {+ name: "accent",+ type: "string",+ default: "\"#D97757\"",+ description: "Color the last copy steps to",+ },+ {+ name: "outline",+ type: "boolean",+ default: "true",+ description: "Draw the copies as outlines",+ },+ {+ name: "speed",+ type: "number",+ default: "1",+ description: "Timeline speed multiplier",+ },+ {+ name: "className",+ type: "string",+ description: "Optional className passed to the wrapper",+ },+ ]}+/>diff --git a/content/docs/typography/type-wall.mdx b/content/docs/typography/type-wall.mdxnew file mode 100644index 00000000..8c2b8197--- /dev/null+++ b/content/docs/typography/type-wall.mdx@@ -0,0 +1,119 @@+---+title: Type Wall+description: Rows of one word fill the frame, run in alternating directions at different speeds in heavy, narrow and outline faces, with an accent band through the middle+component: type-wall+vibe: playful+length: sustained+useWhen:+ - "A loud full-screen beat for one word, such as a section title, a manifesto word or a transition card."+ - "A busy, graphic backdrop behind a short overlay that should read as pure energy."+ - "You want kinetic poster typography that runs for as long as the scene needs."+avoidWhen:+ - "One strip of scrolling text is enough, as a ticker or a separator — use `infinite-marquee`."+ - "The rows should recede in perspective rather than fill the frame flat — use `perspective-marquee`."+ - "A single word should stay readable at the center with quieter repeats — use `echo-stack`."+---++<ComponentPreview name="type-wall" />++<InstallBlock name="type-wall" />++## Usage++```tsx+// src/Root.tsx+import { AbsoluteFill, Composition } from "remotion";+import { TypeWall } from "@/components/remocn/type-wall";++const Wall = () => (+ <AbsoluteFill style={{ backgroundColor: "#2b3bff" }}>+ <TypeWall text="MOTION" accent="#ff4d1a" accentText="#111111" />+ </AbsoluteFill>+);++export const RemotionRoot = () => (+ <Composition+ id="TypeWall"+ component={Wall}+ durationInFrames={150}+ fps={30}+ width={1280}+ height={720}+ />+);+```++Rows are `fontSize` tall and stack without gaps from the center row outward+until the frame is covered. Faces alternate between heavy Inter, narrow Anton+and outline Inter; Anton is scaled so its capitals match Inter's cap height.+The center row runs on the `accent` band. Neighbors run in opposite+directions, and each row gets its own speed and starting phase from `seed`, so+the wall never lines up into columns.++On the way in, each row wipes open from the side it enters and streams a few+tokens past before it slows to cruise, staggered two frames per row from the+center outward. The band grows from the middle over frames 6 to 20. After+that the wall runs for as long as the sequence lasts.++The wall is the one component of this set that defaults to capitals: the+effect is a wall of type. Each row loops by moving whole tokens, so it never+measures text. The component fills its parent and paints no background+outside the band.++<PropsTable title="Props"+ rows={[+ {+ name: "text",+ type: "string",+ default: "\"MOTION\"",+ description: "The word repeated in every row",+ },+ {+ name: "separator",+ type: "string",+ default: "\"·\"",+ description: "Glyph between repeats",+ },+ {+ name: "fontSize",+ type: "number",+ default: "64",+ description: "Row height in reference px at 720p",+ },+ {+ name: "color",+ type: "string",+ default: "\"#fafafa\"",+ description: "Text and outline color",+ },+ {+ name: "accent",+ type: "string",+ default: "\"#D97757\"",+ description: "Band behind the center row",+ },+ {+ name: "accentText",+ type: "string",+ default: "\"#0a0a0a\"",+ description: "Text color on the band",+ },+ {+ name: "seed",+ type: "number",+ default: "7",+ description: "Seed for each row's speed and phase",+ },+ {+ name: "speed",+ type: "number",+ default: "1",+ description: "Timeline speed multiplier",+ },+ {+ name: "className",+ type: "string",+ description: "Optional className passed to the wrapper",+ },+ ]}+/>diff --git a/content/docs/ui-blocks/code-morph.mdx b/content/docs/ui-blocks/code-morph.mdxnew file mode 100644index 00000000..f665a029--- /dev/null+++ b/content/docs/ui-blocks/code-morph.mdx@@ -0,0 +1,190 @@+---+title: Code Morph+description: A code panel morphs between versions of a file, with surviving tokens gliding to their new line and column while removed code dissolves and new code fades in+component: code-morph+vibe: tech+length: 114+useWhen:+ - "A launch or product demo needs to show an API getting simpler, with the before and after code in one panel and the surviving tokens visibly traveling to their new places."+ - "A refactor, a new SDK call, or a config change should read as one continuous edit instead of a hard cut between two screenshots."+ - "A walkthrough builds one file up in two to four steps, with each change landing on a highlighted line."+avoidWhen:+ - "The code should simply appear line by line, with no before and after — use `glass-code-block`."+ - "The code should be typed out character by character — use `terminal-simulator` or `typewriter`."+ - "The camera should scan a long file while it reveals — use `glass-code-walk`."+---++<ComponentPreview name="code-morph" />++<InstallBlock name="code-morph" />++## Usage++`CodeMorph` works like Keynote's Magic Move for code. A flat editor panel+shows one version of a file, then morphs into the next. A token-level diff+pairs every token that survives the edit. Each survivor is one element that+glides from its old line and column to its new ones, so the eye can follow it.+In the default content, `"/api/invoices"` lifts out of `fetch(...)` and lands+inside `useSWR(...)`. Removed code blurs out first, the survivors travel, and+new tokens fade in line by line. The panel is sized once to fit every version+and never moves, so code that did not change stays exactly where it was. The+changed lines hold a short accent highlight.++```tsx+import { Backdrop } from "@/components/remocn/backdrop";+import { CodeMorph } from "@/components/remocn/code-morph";++export const ApiSimplification = () => (+ <Backdrop+ fill={{ type: "color", value: "#f1eee7" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <CodeMorph />+ </Backdrop>+);+```++The component paints only the panel, so it composites over any scene. The+backdrop supplies the color. Sizes are reference pixels at 1280×720 and scale+with the composition, and a panel that would not fit shrinks as a whole.+Token positions come from the monospace grid, not from DOM measurement.+Everything derives from the Remotion frame, so seeking and rendering are+deterministic.++### Your own code++Pass the versions as `steps`. Each `at` is the frame, at 30 fps, where the+morph into that version starts. The first version shows from frame 0.+Indentation shared by every line is removed, so template literals can stay+indented. The panel takes its height from the tallest version and its width+from the longest line, so a shorter version leaves empty editor space below+it. Keep each version to about 16 lines at the default size. Longer files+shrink the whole panel.++```tsx+import { Composition } from "remotion";+import { Backdrop } from "@/components/remocn/backdrop";+import {+ CodeMorph,+ type CodeMorphStep,+ getCodeMorphDuration,+} from "@/components/remocn/code-morph";++const steps: CodeMorphStep[] = [+ {+ at: 0,+ code: `+ import { defineConfig } from "vite";+ import react from "@vitejs/plugin-react";++ export default defineConfig({+ plugins: [react()],+ });+ `,+ },+ {+ at: 45,+ code: `+ import { defineConfig } from "vite";+ import react from "@vitejs/plugin-react";+ import tailwindcss from "@tailwindcss/vite";++ export default defineConfig({+ plugins: [react(), tailwindcss()],+ });+ `,+ },+ {+ at: 110,+ code: `+ import { defineConfig } from "vite";+ import react from "@vitejs/plugin-react";+ import tailwindcss from "@tailwindcss/vite";++ export default defineConfig({+ plugins: [react(), tailwindcss()],+ server: { port: 3000 },+ });+ `,+ },+];++const ViteSetup = () => (+ <Backdrop+ fill={{ type: "color", value: "#0a0a0a" }}+ padding={0}+ radius={0}+ shadow=""+ >+ <CodeMorph+ steps={steps}+ filename="vite.config.ts"+ theme="light"+ accentColor="#22c55e"+ />+ </Backdrop>+);++export const RemotionRoot = () => (+ <Composition+ id="ViteSetup"+ component={ViteSetup}+ durationInFrames={getCodeMorphDuration({ steps })}+ fps={30}+ width={1280}+ height={720}+ />+);+```++Identical tokens are matched in reading order, words first. Punctuation+survives only when it stays with the words on its line. Closing brackets+follow their opening bracket, and a line that only moved travels as one block.+Everything else fades out or in.++## Timing++At 30 fps, `speed={1}` and the default content:++| Frames | Motion |+| --- | --- |+| 0–48 | The 16-line version holds |+| 48–64 | Removed tokens fade, blur and shrink slightly, top line first |+| 54–80 | Surviving tokens glide to their new line and column; each destination line starts one frame after the line above |+| 58–78 | Line numbers 9–16 fade out behind the last line to move; the panel keeps its size |+| 68–84 | New tokens fade in line by line |+| 68–100 | Lines 1, 4, 6 and 7 rise to an accent highlight and hold it |+| 100–114 | The highlight fades |+| 114–138 | The new version holds |++A morph lasts `morphDuration` frames, 36 by default, and its phases scale with+it. In a 36-frame morph, removed tokens leave over frames 0–16, survivors glide+over 6–32, and new tokens arrive over 20–36. Nothing overshoots: the code lands+exactly on the grid. The highlight keeps its own timing: 8 frames up, 24 held+and 14 down. If a step's `at` comes before the previous morph has finished, it+waits for that morph, so two morphs never overlap.++`codeMorphLength` is 114, the frame where the default highlight fades out.+`getCodeMorphTimeline({ steps, morphDuration, highlight })` returns every+morph's `start`, `end` and highlight frames, plus `settled`.+`getCodeMorphDuration({ steps, morphDuration, highlight, speed })` returns the+composition length with a 24-frame hold, 138 by default. For another frame+rate, multiply by `fps / 30` and round up.++<PropsTable title="Props"+ rows={[+ { name: "steps", type: "{ at: number; code: string }[]", default: "Invoices before and after", description: "Versions of the file in order. at is the 30 fps frame where the morph into that version starts; the first version shows from frame 0" },+ { name: "morphDuration", type: "number", default: "36", description: "Frames from the first removed token leaving to the last new token settling, clamped to 12–120; the phases scale with it" },+ { name: "highlight", type: "boolean", default: "true", description: "Hold an accent band on the lines each morph changed" },+ { name: "fontSize", type: "number", default: "20", description: "Code size in reference px at 720p, clamped to 10–40; the panel shrinks as a whole if it would not fit" },+ { name: "lineNumbers", type: "boolean", default: "true", description: "Show right-aligned line numbers in a gutter" },+ { name: "filename", type: "string", default: '"invoices.tsx"', description: "Label of the file tab; an empty string hides the tab" },+ { name: "windowDots", type: "boolean", default: "true", description: "Show three neutral window dots in the header" },+ { name: "theme", type: '"dark" | "light"', default: '"dark"', description: "Panel and syntax palette" },+ { name: "accentColor", type: "string", default: '"#0ea5e9"', description: "Strings, numbers and the changed-line highlight" },+ { name: "speed", type: "number", default: "1", description: "Playback multiplier; 0 freezes the first version" },+ { name: "className", type: "string", description: "Optional class name on the full-frame root" },+ ]}+/>diff --git a/content/docs/ui-blocks/index.mdx b/content/docs/ui-blocks/index.mdxindex 3d45c586..16d7f668 100644--- a/content/docs/ui-blocks/index.mdx+++ b/content/docs/ui-blocks/index.mdx@@ -15,6 +15,12 @@ Larger blocks built from primitives, the actual surfaces your viewers will recogstatus: "stable",href: "/docs/ui-blocks/glass-code-block",},+ {+ name: "CodeMorph",+ description: "Keynote-style Magic Move for code, with surviving tokens gliding to their new line and column",+ status: "stable",+ href: "/docs/ui-blocks/code-morph",+ },{name: "TerminalSimulator",description: "CLI build simulation with chunked log output and step-function scrolling",diff --git a/content/docs/ui-blocks/meta.json b/content/docs/ui-blocks/meta.jsonindex 7348e572..45cecc92 100644--- a/content/docs/ui-blocks/meta.json+++ b/content/docs/ui-blocks/meta.json@@ -6,6 +6,7 @@"search-reveal","glass-code-block","glass-code-walk",+ "code-morph","terminal-simulator","terminal-cursor-zoom","animated-line-chart",diff --git a/docs/plans/2026-09-24-bauhaus-build-design.md b/docs/plans/2026-09-24-bauhaus-build-design.mdnew file mode 100644index 00000000..a62092b2--- /dev/null+++ b/docs/plans/2026-09-24-bauhaus-build-design.md@@ -0,0 +1,335 @@+# Bauhaus Build++Part of the new Motion Graphics category (`content/docs/motion-graphics/`):+brand-agnostic, flat geometric motion in the spirit of After Effects+shape-layer work. The closest sibling is `radial-burst`. This component+follows its structure: pure exported timeline, pose and geometry helpers; one+self-contained file that imports only from `remotion`; a length constant; a+duration helper.++## Direction++An abstract opener in the Bauhaus tradition. Nine flat primitives arrive one+at a time on a steady beat. There is a large circle, two quarter circles, a+semicircle, two squares, two bars and a small circle. They assemble into a+balanced, asymmetric composition on an invisible square grid: a frieze across+the middle of the poster, with a few satellites above and below. After a short+hold, the frieze splits. Every piece makes one more quarter turn into a+second composition: two friezes, above and below a clear central band. That+band is the handoff field for the title. Then it holds.++Pieces never slide or crossfade. Every move is a chain of hinged quarter+turns about a grid corner, so each tile visibly rolls across the grid, cell by+cell, and lands in its slot. There is no text, logo, image, font or+background. The component is transparent and overlays any scene.++## Palette++One accent and neutrals by default. Each piece has a color role, and every+role is a prop.++| Role | Prop | Default | Pieces |+| --- | --- | --- | --- |+| Ink | `inkColor` | `#1c1a17` | quarter circle `hill`, bar `pillar`, small circle `dot` |+| Accent | `accentColor` | `#e4572e` | large circle `sun`, small square `tile` |+| Secondary | `secondaryColor` | `#cbbc9f` (stone) | semicircle `dome`, small quarter circle `fan` |+| Tertiary | `tertiaryColor` | `#7e776b` (warm grey) | bar `post`, square `block` |+| Paper | backdrop only | `#f1eee7` | `previewBackdrop`, docs `<Backdrop>` |++The three neutral tones (ink, grey, stone) give depth through flat shading+alone. The classic Bauhaus look only needs a prop change: accent red+`#d7362b`, secondary yellow `#f2b930`, tertiary blue `#1f4f9e`, ink+`#161616` on paper `#efe9dc`. The composition places each role so it reads in+both palettes. In the handoff the accent pair and the secondary pair sit+diagonally opposite each other, and the tertiary pair anchors the lower+frieze.++There are no glows, blurs, gradients, shadows or strokes. Overlap happens only+at a few tangent contacts.++## Controls++| Prop | Default | Range | Meaning |+| --- | --- | --- | --- |+| `scale` | 1 | 0.5–1.25 | Poster size; 1 fills 80% of the shorter side |+| `seed` | 1 | 1–24 slider, any integer works | Mirror variant and arrival order |+| `inkColor` | `#1c1a17` | color | Ink role |+| `accentColor` | `#e4572e` | color | Accent role |+| `secondaryColor` | `#cbbc9f` | color | Secondary role |+| `tertiaryColor` | `#7e776b` | color | Tertiary role |+| `speed` | 1 | shared | Scales time; 0 freezes the empty first frame |+| `loop` | false | boolean | Boomerang: plays forward, then back to empty |++`seed` cycles through four mirror variants: seed 1 is the authored layout,+2 mirrors it horizontally, 3 vertically, 4 both, then the cycle repeats. Every+seed also reshuffles the arrival order through `random()`. Both mirrors keep+the band in the middle, so the handoff field is the same for every seed.++## Grid and geometry++The poster is a 12 × 12 module square, centered in the frame. Its side is+`min(width, height) × 0.8 × scale`, with `scale` clamped to 0.5–1.25, and+`unit = side / 12`. It fits 16:9, 1:1 and 9:16 the same way. Entry hinge+points may lie in the margin. Nothing needs to clear the frame because pieces+arrive by unfolding and, in loop mode, leave by folding.++Each piece has a local box of `width × height` modules. Its shape is drawn in+that box at turn 0.++- `square`, `bar`: the full box (bars are 4 × 1).+- `circle`: inscribed disk.+- `semicircle`: half disk on the bottom edge (diameter = box side). Its flat+ edge ends are two corners of the box.+- `quarter`: quarter disk centered on the bottom-left corner, radius = box+ side. Three box corners touch the shape: the center and both arc ends.++A rest pose is `{ turn, x, y }`: quarter turns clockwise and the footprint's+top-left module. Odd turns swap the footprint's width and height. The rest+transform is `rotate(turn × 90°)`, then a translation that maps the rotated+box onto the footprint.++### Composition A, the build++Cells whose center falls inside a shape:++```+row 0 . . . . . . . . . . . .+row 1 . . d . . . . . . . . . d dome, flat edge on the right+row 2 . . d . . . . . . . . .+row 3 . . . . . . . . . . . o o dot, on top of the post+row 4 . . H H . P . S S . . Q H hill, right angle at bottom-right+row 5 . H H H . P S S S S . Q P pillar, S sun (tangent to P)+row 6 H H H H . P S S S S . Q Q post+row 7 H H H H t P . S S . . Q t tile, tucked into the gap+row 8 . . . . . . . . . . . .+row 9 . . . . . . . . . . . .+row 10 . . . . . . b b f f . . b block, f fan (right angle top-right)+row 11 . . . . . . b b . f . .+```++### Composition B, the handoff++```+row 0 . . . . . . . S S . . .+row 1 . . . . . . S S S S . .+row 2 . . . d d . S S S S . . dome sits on the pillar, now a rule+row 3 . . P P P P . S S . o . top edge of the band+row 4 . . . . . . . . . . . .+row 5 . . . . . . . . . . . . open band, full poster width+row 6 . . . . . . . . . . . .+row 7 . . . . . . . . . . . .+row 8 H H H H t . . . Q Q Q Q post fell into the lower rule+row 9 H H H H . . . . . . . . hill, right angle at top-right+row 10 . H H H b b . . . . . f+row 11 . . H H b b . . . . f f+```++| Piece | Shape, size | Role | Slot A | Entry moves | Rebuild | Handoff B | Cue |+| --- | --- | --- | --- | --- | --- | --- | --- |+| hill | quarter 4 | ink | turn 3 at (0, 4) | `D- R+` | `D-` | turn 2 at (0, 8) | 0 |+| tile | square 1 | accent | (4, 7) | `U+ U+ U+ U+` | `D+` | (4, 8) | 3 |+| pillar | bar 4 × 1 | ink | turn 1 at (5, 4) | `R+ R+` | `U+` | turn 2 at (2, 3) | 6 |+| sun | circle 4 | accent | (6, 4) | `U+ U+` | `U-` | (6, 0) | 9 |+| dome | semicircle 2 | secondary | turn 3 at (1, 1) | `R+ D-` | `R+` | turn 0 at (3, 1) | 12 |+| post | bar 4 × 1 | tertiary | turn 1 at (11, 4) | `D+ D+` | `D-` | turn 0 at (8, 8) | 15 |+| dot | circle 1 | ink | (11, 3) | `D- D- D- D-` | `L-` | (10, 3) | 18 |+| block | square 2 | tertiary | (6, 10) | `U+ U+ U+` | `L+` | (4, 10) | 21 |+| fan | quarter 2 | secondary | turn 2 at (8, 10) | `L- L+ L+` | `R+` | turn 3 at (10, 10) | 24 |++The handoff poses are not stored. They are computed by rolling each slot+through its rebuild moves. The start poses are computed by unrolling the slot+through the inverse entry moves. Every path is exact by construction.++No piece rebuilds by undoing its last entry turn: the rebuild hinge is always+a different corner from the landing hinge. The hill opens like a fan out of+its right angle on the poster's left edge, rolls in over its arc end and later+drops below the band. The pillar cartwheels in from the left and later tips+up into the top rule. The sun rises from below the poster and later keeps+rising into the top zone.++## The corner tumble++A move is a direction and a spin: `U`, `D`, `L` or `R`, followed by `+`+(clockwise) or `-` (counterclockwise). The direction picks the leading edge,+the side of the footprint facing the destination. The spin picks which of that+edge's two corners is the hinge:++| Move | Hinge corner |+| --- | --- |+| `R+` / `R-` | bottom-right / top-right |+| `L+` / `L-` | top-left / bottom-left |+| `D+` / `D-` | bottom-left / bottom-right |+| `U+` / `U-` | top-right / top-left |++A quarter turn rotates the footprint 90° about the hinge `P`. Rest poses stay+on integer modules because a quarter turn is exact:+`(dx, dy) → (−dy, dx)` clockwise and `(dy, −dx)` counterclockwise. The new+footprint shares `P`, lies entirely beyond the old leading edge and has its+turn advanced by the spin. A square moves one box per turn. A bar cartwheels+end over end, alternating between 4 × 1 and 1 × 4. Round pieces pivot about a+corner of their bounding square. For semicircles and quarter circles every+authored hinge, the unfold included, is a flat-edge end or the right-angle+corner, so the hinge always touches the shape. Only the two full circles+swing about a bounding-square corner off their body.++Between rest poses, a local point `p` is drawn at++```+world(p) = P + s · R(θ) · (R(φ) · p + t − P)+θ = spin · 90° · progress+```++where `R(φ)` and `t` are the rest transform of the pose the turn starts from,+and `s` is the unfold scale (1 except on the first entry turn). In SVG this is+`translate(X Y) rotate(φ + θ) scale(s · unit)` with+`(X, Y) = P + s · R(θ)(t − P)`. The hinge corner maps onto `P` for every+progress and scale. The piece is always a rigid rotation about a fixed grid+corner, so it cannot slide. After each quarter turn the next move hinges on a+different corner of the piece.++Timing per quarter turn is heavier for larger pieces, like a pendulum:+`T = 5 · √(max(width, height))` frames at 30 fps. That gives 5 frames for 1 ×+1 pieces, 7.07 for 2 × 2, and 10 for the 4 × 4 pieces and the bars.++- Travel turns ease in and out, `bezier(0.62, 0, 0.3, 1)`, from rest to rest.+ They never pass 90°.+- The landing turn swings to `1.05` of a quarter turn (4.5° past the slot)+ with the same curve over `T`. It then settles back to exactly 90° over+ `0.5 T` with `bezier(0.45, 0, 0.55, 1)`. The overshoot is capped at 4.5°+ and has zero velocity at the peak and at rest.+- Unfold: the first entry turn also scales the piece from 0 to 1 about the+ hinge, `s = 1 − (1 − τ / T)³`. The piece grows out of a grid point as it+ swings, so nothing pops in. Once the preceding turns are done, the slot is+ one exact quarter turn away.++## Build++Entry paths are 2 to 4 turns: 2 for the 4-module pieces and the dome, 3 for+the other 2 × 2 pieces, 4 for 1 × 1. Travel takes 20 to 21.2 frames, or 14.1+for the dome. Arrival slot `j` lands (ends its swing) at `22 + 6j`: 22, 28,+... 70. Its first turn starts at `22 + 6j − turns · T`. Only the sun and the+post can arrive first, so no turn starts before frame 2 and frame 0 is empty.+The last piece settles by 75.++Entry paths cross empty grid wherever possible. Where one entry sweeps over+another piece's slot, that piece must arrive later. Each piece lists these+prerequisites in `after`:++- `pillar` after `sun`: the sun rises past the pillar's foot.+- `block` after `sun`: the sun rises through the block's slot.+- `tile` after `pillar`: the pillar cartwheels across the tile's slot.+- `hill` after `tile`: the tile rolls up the gap past the hill's corner.+- `dome` after `pillar`: the dome sits on the pillar's rule in the handoff, so+ it must paint above the rule when the rule lands.+- `dot` after `post`: the post lies across the dot's slot before standing.+- `fan` after `block`: the block's landing leans over the fan's slot.++The arrival order is a seeded topological sort. Among the pieces whose+prerequisites have landed, the one with the smallest+`random("bauhaus-build-{seed}-order-{id}")` goes next. Pieces render in+arrival order, so a moving piece is always above the pieces already landed.+Across seeds 1–40 the only contacts in the build are sub-module grazes, where+a landing overshoot leans into a tangent neighbor by at most 0.17 module (the+pillar against the sun).++## Rebuild++The rebuild starts at frame 90. Each piece makes one quarter turn at `90 ++cue`, on a steady 3-frame cascade that runs left to right across the frieze:++1. `hill` (0) and `tile` (3) swing down about the same grid corner (4, 8),+ the hill's right angle. The hill turns counterclockwise on the left; the+ tile turns clockwise on the right. They open like a pair of doors.+2. `pillar` (6) and `sun` (9) do the same about (6, 4). The pillar tips up+ and left into the upper rule, and the sun rises into the top zone.+3. `dome` (12) rolls over the end of its flat edge onto the new rule.+4. `post` (15) tips down-left into the lower rule. Its dot (18) rolls off the+ top, onto the band's top edge next to the sun.+5. `block` (21) and `fan` (24) split apart along the bottom edge.++The order is fixed so that most sweeps cross space their neighbors have+already left. The last turn ends at `90 + 24 + 1.5 · 7.07 = 124.6`. That+makes `bauhausBuildLength = 125`.++Three contacts remain, all structural to the two compositions. The tile is+wedged between the hill and the pillar, so its swing clips the foot of the+still-standing pillar (up to 0.36 module, about two frames). The pillar+cannot leave first, because its own swing crosses the tile. The rule's+landing overshoot lifts about 0.24 module under the dome, which sits on the+rule in the handoff and paints above it. The block's landing overshoot leans+0.15 module into the hill's arc.++## Timeline at 30 fps, speed 1++| Frames | Motion |+| --- | --- |+| 0–2 | Empty |+| 2–22 | The first pieces unfold from grid points and tumble toward their slots |+| 22–75 | Nine landings, one every six frames (22 … 70), each settling with a 4.5° overshoot |+| 75–90 | Hold on the frieze |+| 90–125 | Rebuild cascade: one quarter turn per piece, 3 frames apart; the band clears by about frame 116 |+| 125–150 | Hold on the handoff (`durationInFrames` 150) |++`getBauhausBuildDuration({ speed, loop })` returns `ceil(150 / speed)`, or+`ceil(300 / speed)` with `loop`. Speed 0 returns 1.++## Loop++`loop` plays the sequence as a boomerang with a 300-frame period. Time folds+back at 150, so the rebuild runs backward (B to A). Then the build runs+backward: the pieces leave in reverse arrival order and fold into their hinge+points. The frame is empty again at 300. Played backward, the landing+overshoot becomes a small anticipation before each exit tumble. The cycle is+seamless and reuses the forward paths exactly, so it adds no new contacts.++## Handoff and usage++The open band spans modules 4 to 8 vertically: the middle third of the+poster, across its full width. It is centered in the frame at every aspect+ratio. At 1280 × 720 and scale 1 it is 192 px tall. No piece rests outside+the poster, so on every aspect ratio the band continues across the full frame+width.++- `getBauhausBuildField({ width, height, scale })` returns the band in+ composition pixels: `{ x: 0, y, width, height, unit }`. It needs no seed,+ because both mirrors keep the band in place.+- `bauhausBuildTimeline.clear` is frame 116. From then on no shape enters the+ band. The post leaves it around frame 113, and the dot's overshoot dip+ settles by 115.5.++Put the title in the field from that frame, over a paper `<Backdrop>` with+no padding. The band stays clear for as long as the handoff holds, which is+indefinitely without `loop`.++```tsx+<Backdrop fill={{ type: "color", value: "#f1eee7" }} padding={0} radius={0} shadow="">+ <BauhausBuild />+ <Sequence from={bauhausBuildTimeline.clear}>+ <Title field={getBauhausBuildField({ width, height })} />+ </Sequence>+</Backdrop>+```++## Verification (bun:test)++- Timeline: frames 0 and 0.5 are empty for every seed; each arrival unfolds+ from scale 0 and lands on its beat with the 4.5° lean; the frieze holds+ between 75 and 90; the handoff is at rest from 125 onward; durations follow+ `speed` and `loop`.+- Tumble invariants: every step hinges on a leading-edge corner that both+ footprints share. The new footprint lies beyond the leading edge. The turn+ advances by the spin. Consecutive steps hinge on different corners of the+ piece, including the step from the landing turn into the rebuild turn. The+ hinge stays fixed at every progress and unfold scale. A turn at+ full progress equals the next rest pose exactly. Travel turns never exceed+ 90°, and the landing overshoot is present and capped.+- Compositions: all slots lie inside the poster, and no two rest footprints+ overlap in A or B. Every handoff footprint stays out of the band. Sampled+ points of every shape stay out of the band from the clear frame to the+ end. The field helper is full width and vertically centered at every+ aspect ratio and scale.+- Determinism: the same frame and seed give identical output in any sampling+ order. Seeds respect every arrival prerequisite and cycle the four mirrors.+ The loop is periodic and palindromic.+- Config defaults equal `bauhausBuildDefaults`, the object the component+ destructures from.diff --git a/docs/plans/2026-09-24-mondrian-split-design.md b/docs/plans/2026-09-24-mondrian-split-design.mdnew file mode 100644index 00000000..029ae37c--- /dev/null+++ b/docs/plans/2026-09-24-mondrian-split-design.md@@ -0,0 +1,249 @@+# Mondrian Split++First piece of the new Motion Graphics category: brand-agnostic, flat geometric+motion in the spirit of After Effects shape-layer work. Closest sibling is+`radial-burst`; this one follows its structure (pure exported helpers, one+self-contained file importing only `remotion` and `react`, a length constant and+a duration helper).++## Direction++A De Stijl composition that builds itself, rebalances, and then becomes the+cut. Black lines cut across the frame one at a time and recursively split it+into rectangles. A few cells fill with primaries; the rest stay open paper.+After a short hold the lines slide to new positions and the whole grid reflows+like rubber. Then one cell pushes its own lines out past the frame edges until+it is the frame.++With `children`, that cell carries the next scene from the moment it fills, so+the incoming scene is already part of the painting before it takes over. The+component is transparent, so it can sit over the outgoing scene: open cells keep+showing it while the expanding cell carries the next one. Without children the+cell is a flat `fieldColor` field, which makes it an opener or a clean hand-off+to a color.++The grid is the only thing that moves. Cells are never animated on their own:+every frame, every cell and every fill is derived from the current line+positions. No crossfades, no opacity, no scaling of content.++## Palette++Classic De Stijl, every color a prop:++| Role | Prop | Default |+| --- | --- | --- |+| Lines | `lineColor` | `#121212` |+| Red slot | `redColor` | `#d62d20` |+| Yellow slot | `yellowColor` | `#f4c20d` |+| Blue slot | `blueColor` | `#1f4e9e` |+| Expanding cell | `fieldColor` | `#d62d20` |+| Paper | backdrop only | `#f3efe6` |++The component paints no background. Paper comes from `previewBackdrop` in the+config and from a `<Backdrop>` in docs examples. Open cells are transparent.+Flat fills only: no glow, blur, gradient or shadow. Depth is never implied.++## Controls++| Prop | Default | Range | Meaning |+| --- | --- | --- | --- |+| `seed` | 7 | 1–99 | Composition; every seed is a different balanced grid |+| `splits` | 7 | 3–12 | Number of lines, so `splits + 1` cells |+| `lineWeight` | 14 | 4–32 | Line thickness at a 720px reference (shorter side) |+| `expandCell` | 0 | 0–12 | Which cell takes over, ranked by size; 0 is the largest |+| colors | see palette | | |+| `speed` | 1 | shared | Scales time; 0 freezes the blank first frame |++`children` and `className` complete the API.++## Timeline at 30 fps, default props++Phase frames depend only on `splits` (not on the seed), so+`getMondrianSplitTimeline({ splits })` and `getMondrianSplitDuration` are exact+for every seed.++| Frames | Beat |+| --- | --- |+| 0–3 | Blank paper |+| 3–43 | Seven lines, one every 5 frames, each drawn in 10 frames with an expo ease-out |+| 40–53 | Colored cells wipe in one by one, 4 frames apart, 9 frames each |+| 50–62 | The expanding cell fills last (12 frames); children are revealed here |+| 62–76 | Hold on the finished composition |+| 76–106 | Three lines slide, 5 frames apart, 20 frames each, with a 3.5% overshoot settle |+| 102–133 | The expanding cell's sides push out, 3 frames apart, 22 frames each |+| 133–145 | Tail hold on the field or the next scene |++General formula with `n = splits` and `c = clamp(round(0.3 n), 1, 5)` colored+cells:++- line `i` starts at `3 + 5i`+- `fill = 3 + 5(n - 1) + 7`, colored cell `k` starts at `fill + 4k`+- `field = fill + 4(c - 1) + 6`+- `reflow = field + 12 + 14`, move `k` starts at `reflow + 5k`+- `expand = reflow + 10 + 20 - 4` (overlaps the last settle by 4 frames)+- `end = expand + 9 + 22` = `mondrianSplitLength` (133 at defaults)+- config duration = `end + 12` = 145 at defaults++## Geometry++Everything is computed in composition pixels, so the grid adapts to 16:9, 1:1+and 9:16 instead of being stretched. `unit = min(width, height) / 720`; line+weight scales with it.++Seeded guillotine subdivision (`random()` from remotion with keys that include+the step and attempt, so raising `splits` refines the same composition instead+of replacing it):++1. The root line splits the frame across its long side (75% of seeds; square+ frames pick either) at 30–40% or 60–70%.+2. The larger half is split the other way so one part keeps 60–76% of it. That+ part becomes the protected anchor: a large cell that is never subdivided, so+ every seed has one dominant plane and a band of smaller cells.+3. Remaining splits pick a non-anchor cell weighted by `area^1.2`, cut across+ its long side (random when nearly square) at 28–45% or 55–72%.+4. A new line within 4.5% of the shorter side of any parallel line snaps onto+ it, so segments line up into long Mondrian lines. Positions that would land+ close to, but not on, another parallel line are rejected. Every cell keeps+ at least `max(10% of the shorter side, 3 × weight)` per side.+5. A deterministic fallback pass guarantees the requested count whenever any+ cell is still large enough to split.++Collinear segments form a track. A track is what slides in the reflow, so a+long line made of several segments moves as one line.++Each line draws from the end that touches the older boundary (frame edges are+oldest) toward the newer one, so a line never starts from a point that is not+drawn yet.++Colors: `c` non-expanding cells take slots blue, yellow, red, blue, yellow.+Candidates are scored by a seeded roll, a penalty for touching the expanding+cell, and a small penalty for size. No two touching cells share a slot, and red+never touches the expanding cell, which is red by default. Fills play in+diagonal reading order, then the expanding cell last.++Wipes are one consistent move: along the cell's long side, starting from the+edge nearer the frame center and growing outward, using an in-out curve+`bezier(0.7, 0, 0.2, 1)`.++## How the signature motion is computed++### Rubber reflow++Lines carry absolute positions. Each node of the split tree knows which lines+bound its four sides. A line's legal range is the gap between the lines that+bound its own node on its axis, and the lines that use it as a boundary must+stay on their side. The gap is `max(7% of the shorter side, 2.5 × weight)`.++Up to three tracks move, chosen by total length with a seeded weight, so the+long structural lines move first. For each track in turn:++- its interval is the intersection of the constraints of all of its segments,+ using the reserved sweep of tracks that were already chosen (the full range+ they will occupy during their slide, including overshoot), not only their end+ positions;+- a track that borders the expanding cell only slides inward, squeezing that+ cell, and stays put when there is no room for it. Other tracks pick a side+ with a seeded roll weighted by room. So the reflow never grows the takeover+ cell before its push: across seeds it goes into the expansion at 19–44% of+ the frame (about 29% typical). Before this rule the default seed pre-grew it+ from 50% to 72–79% during the reflow, which left the finale little to do;+- the target is 60–95% of the free room, at most 20% of the axis and at least+ 6% of the shorter side;+- a target within 7.5% of the shorter side of another parallel line's settled+ position snaps onto the nearest such line, or the track is skipped when that+ alignment is out of range. The radius is wider than the 4.5% used while+ building, so a sliding line never stops just short of lining up (before this,+ 6–9% of moves did, including two on the default seed);+- the sweep `[min(from, to), max(from, to)]` plus 4.5% overshoot margin is+ reserved.++Because every chosen range is reserved before the next track is chosen, the+grid is valid at every frame for any timing and any overlap, and cells can never+invert.++Every frame, positions are `position + (to - from) × slide(progress)`, where+`slide` rises with `bezier(0.65, 0, 0.3, 1)` to 103.5% at 72% of the move and+settles back with `bezier(0.4, 0, 0.6, 1)`. The tree is then laid out again from+the root: each child box is the parent box cut at the current line position.+Cells, fills and the endpoints of perpendicular lines are all read from that+layout, so everything a line touches stretches or shrinks with it in lockstep.++### Line-driven expansion++The expanding cell `[c0, c1]` on x (same on y) gets current edges+`L = mix(c0, -m, e_left)` and `R = mix(c1, W + m, e_right)` where `m = weight ++4% of the shorter side` is an overscan margin beyond the frame. The whole+picture goes through a separable piecewise-linear map per axis:++- `[−m, c0]` maps onto `[−m, L]`+- `[c0, c1]` maps onto `[L, R]`+- `[c1, W + m]` maps onto `[R, W + m]`++The cell's bounding lines are exactly at `L` and `R`, so they are what slides+out. Everything between them and the frame edge is compressed toward the+overscan anchor like rubber, and at `e = 1` it has collapsed onto the anchor+beyond the frame. The maps are monotonic, so nothing crosses. At the end the+cell is `[−m, W + m] × [−m, H + m]`, no line or other cell has any visible+extent, and only the field and children remain.++Per side, `e` is a 22-frame curve: a 3.5% wind-up inward over the first 22% with+an in-out ease (only on sides bounded by a line, so an edge that touches the+frame never opens a gap), then `t^2.5` acceleration out. The wind-up is capped+at 20% of the cell's own extent per side, so two opposite pull-ins take at most+40% of it and a narrow cell on a very wide frame (2560×720) never folds shut or+drops its children. The sides start 3 frames apart, ordered by travel from+shortest to longest, so the longest push finishes the motion.++## Handoff and usage++- Opener: no children, `fieldColor` set to the title background. Put the title+ in a `Sequence` that starts near `getMondrianSplitTimeline().end`.+- Transition: pass the next scene as children. Children share the component's+ frame; the reveal starts at `timeline.field`. Keep the next scene inside the+ component for as long as it should play, since after the push the component+ renders only the field and children.+- Overlay: place over the outgoing scene. Open cells keep showing it.+- `getMondrianSplitDuration({ speed, splits })` includes the 12-frame tail and+ returns frames at 30 fps.++Children are rendered in a full-frame layer clipped with a percentage+`clip-path: inset()` to the current field rectangle, between the fills SVG and+the lines SVG, so lines always sit on top. Both SVGs use+`preserveAspectRatio="none"` so the geometry and the percentage clip stay in+the same space inside any container.++## Exports++- `MondrianSplit`, `MondrianSplitProps`+- `mondrianSplitDefaults`, `mondrianSplitLength`+- `getMondrianSplitTimeline`, `getMondrianSplitDuration`+- `getMondrianSplitLayout` (the seeded composition: split tree, lines with+ their track ids, target, fills, moves, per-side push start and wind-up) and+ `getMondrianSplitState` (per-frame lines, fills, field, cells)+- `getMondrianSplitClip` (the children `clip-path` for a field rectangle)+- types: `MondrianSplitLayout`, `MondrianSplitState`, `MondrianSplitOptions`,+ `MondrianSplitBox`, `MondrianSplitRect`, `MondrianSplitAxis`,+ `MondrianSplitSlot`, `MondrianSplitSide`++## Tests++Timeline boundaries (blank start, one line after frame 3, all lines drawn when+fills start, all fills done at the reflow, the frame fully covered with no lines+at the end and after), duration and speed, layout validity across seeds and+aspect ratios (exact count, tiling, minimum cell size, largest cell as the+default target, slot rules), the rubber invariants (every cell edge is a frame+edge or a current line position at every reflow frame, a moving line is+bordered on both sides by the same cells throughout its slide, fills stay glued+to their cells, every sliding line lands on another line or clearly away from+all of them, the reflow only ever squeezes the expanding cell, the expanding+cell stays bounded by its own lines while they push out, stays open through its+wind-up on a 2560×720 frame, and only grows after the wind-up), determinism,+and config defaults matching the component defaults.++## Integration left to the lead++Not touched by this change: `registry/remocn/registry.json`,+`registry/__index__.tsx`, the manifest, `registry-artifacts/`, the new+`content/docs/motion-graphics/meta.json` and `index.mdx`, changelog. The docs+page carries `component: mondrian-split`, so the docs gate needs the registry+entry and the section `meta.json` before it passes.diff --git a/docs/plans/2026-09-24-truchet-flip-design.md b/docs/plans/2026-09-24-truchet-flip-design.mdnew file mode 100644index 00000000..473f8634--- /dev/null+++ b/docs/plans/2026-09-24-truchet-flip-design.md@@ -0,0 +1,142 @@+# Truchet Flip++Direction: a flat, rule-driven pattern piece. It opens the new Motion Graphics+category (`content/docs/motion-graphics/`). The frame is tiled with Truchet+(Smith) tiles. Each tile carries two quarter-circle arcs, centered on opposite+corners. A wave crosses the grid, and each tile snaps a quarter turn when the+wave reaches it. Neighboring arcs share edge midpoints, so each turn changes+which ends connect. Lines run on across the frame, mazes form and dissolve,+and a final pass settles the grid into a chosen structure. No text, logo,+images, fonts, or shaders. It fits between a background loop and a pattern+stinger for a title.++## Palette++The default is one tone: white linework (`color`, `#ffffff`) on a transparent+background. `secondaryColor` colors alternate tiles in a checkerboard. It+defaults to `color`, so the lines stay unbroken until the user changes it. The+component paints no background. The docs preview puts it on flat International+Klein Blue (`#002fa7`) via `previewBackdrop`. The docs examples use a+`<Backdrop>`. Nothing glows, blurs, or uses a gradient. Any depth comes from+the arcs overlapping.++## Controls++| Prop | Default | Range | Meaning |+| --- | --- | --- | --- |+| `tiles` | 10 | 4–24 | Tiles across the shorter side; tile size is `min(w, h) / tiles` |+| `weight` | 0.2 | 0.04–0.34 | Stroke width as a fraction of the tile size |+| `passes` | 2 | 0–4 | Full flip passes before the resolve pass |+| `waveMode` | `radial` | `radial`, `diagonal`, `random` | Order in which tiles turn |+| `resolve` | `rings` | `rings`, `field`, `silhouette` | Structure the last pass settles into |+| `variant` | `stroke` | `stroke`, `filled` | Arcs as butt-capped strokes, or as filled quarter discs |+| `color` | `#ffffff` | color | Line or disc color |+| `secondaryColor` | `color` | color | Alternate (checkerboard) tiles |+| `seed` | 1 | integer | Opening maze and random wave order |+| `speed` | 1 | shared | Scales time; 0 freezes the opening maze |+| `loop` | false | boolean | Adds a return pass so the last frame matches the first |++## Timeline (30 fps, speed 1, two passes)++| Frames | Beat |+| --- | --- |+| 0–6 | Seeded maze holds still so the eye can read it |+| 6–48 | Pass 1: the wave reaches the last tile at 36; every tile turns +90° |+| 30–72 | Pass 2 follows 24 frames behind; every tile turns −90°, back again |+| 60–102 | Resolve pass (30-frame beat after pass 2) turns only tiles that differ from the target |+| 102–120 | Hold on the resolved structure |+| 126–168 | `loop` only: after a 24-frame hold, a return pass restores the opening maze |++Constants: lead 6, wave spread 30, snap window 12, pass gap 24, resolve gap+30, hold 18, loop hold 24. `truchetFlipLength` is 102. That is the frame where+the last tile settles, and it excludes the lead and tail holds.+`getTruchetFlipDuration({ speed, passes, loop })` returns the preview+duration: 120 by default and 168 with `loop`. Each pass beyond the first adds+24 frames. `passes={0}` resolves at frame 48 and the preview is 66 frames. All+passes share one delay field, so any tile's flips are 24 frames apart. That is+more than the 12-frame snap, so a tile never turns twice at once.++## Geometry++The grid is anchored with a vertex exactly at the frame center. Tile size+comes from the shorter side, so 16:9, 1:1 and 9:16 all show `tiles` across the+short side. Columns and rows extend by `ceil(half / size)` on each side, so+edge tiles are cut off by the frame and nothing ever shows empty. Tile `(col,+row)` spans `[col, col + 1] × [row, row + 1]` in grid units from the center+vertex.++Each tile renders one `<path>` in tile-local coordinates, centered on the+origin. The path is orientation A: arcs of radius `size / 2` centered on the+top-left and bottom-right corners. A per-tile `translate(x y) rotate(angle)`+turns it. At 0° (and 180°) the tile is A: one arc joins the top and left edge+midpoints, the other joins bottom and right. At 90° (and 270°) it is B: top+joins right, and bottom joins left. Every arc ends at an edge midpoint with its+tangent perpendicular to the edge. Neighbors therefore meet with matching+tangents and read as one continuous line. Strokes use butt caps, and each arc+runs 0.75px (at 720p) past the midpoint. The overlap hides antialiasing seams+without the round-cap bumps that would show on two-tone joins. The filled+variant draws the same two corners as quarter discs, pushed 0.75px out past+their straight edges for the same reason.++Tiles go into two `<g>` layers (primary and alternate color). The default+grid is 180 paths. The densest setting (24 across, 16:9) is about 1,050.++## Signature motion++The rule: when the wave reaches a tile, it turns a quarter.++- Wave order: each tile gets one delay `d ∈ [0, 30]`. Radial scales it by the+ distance from the center vertex to the tile center. The four central tiles+ get 0 and the corner tiles 30, about 3.4 frames per ring at the default+ density. Diagonal scales it by `col + row`, top-left to bottom-right, so the+ front runs parallel to the field lines. Random ranks tiles by+ `random("truchet-flip-{seed}-wave-{col}-{row}")` and spaces the ranks evenly,+ so the same number of tiles start every frame.+- Snap: `snap(t)` is a closed-form underdamped spring step response with+ damping ratio 0.65. Its frequency is tuned so it first reaches 90° at frame+ 4. It peaks at about 96.1° near frame 5.5, a 6.8% overshoot; the highest+ whole-frame sample is 95.8° on frame 6. From frame 8 a smoothstep taper+ brings the ringing to exactly 90° by frame 12. After that it clamps to 1,+ before 0 it clamps to 0. Per frame (deg): 0, 17.9, 49.4, 75.2, 90.0, 95.6,+ 95.8, 93.9, 91.8, 90.4, 89.9, 89.9, 90.+- Angle: `90 × (initial + Σ direction × snap(time − waveStart − d))`. Flip+ directions alternate by wave (+, −, +, …). The count of flips alone decides+ the orientation. Outside the snap windows every angle is an exact multiple+ of 90°, so the arcs always meet at rest.+- Resolve pass: tile `(col, row)` turns only if `(initial + passes) mod 2`+ differs from its target. Targets:+ - `rings` uses orientation A in the top-left and bottom-right quadrants and+ B in the other two. Curves close into a full circle around the center+ vertex, then concentric loops of 12, 20, 28 … arcs, with semicircular caps+ on the axes and wavy diagonal sides, until the frame edge cuts the outer+ loops open.+ - `field` sets every tile to A, giving parallel wavy diagonals.+ - `silhouette` covers tiles whose center lies within `0.38 × tiles` of the+ center. Inside, it uses a checkerboard (A on even `col + row`), which closes+ every curve into a small circle around an even vertex. Outside, it uses the+ field. Field lines U-turn around the disc, so a circle made of circles+ appears.+- Loop: the return pass turns tiles whose target differs from their opening+ orientation. Every tile then flips an even number of times per cycle. The+ tile is symmetric under 180°, so the frame at the cycle end matches frame 0.++Determinism: every value derives from `useCurrentFrame()`, `useVideoConfig()`,+props, and remotion `random()` with string seeds. Time is `frame × 30 / fps ×+speed`, taken modulo the cycle when looping. The grid is memoized on its inputs+only. Nothing accumulates between frames, so any frame renders correctly when+seeked directly.++## Handoff and usage++Place it full-frame over a `<Backdrop>` or any scene background. As a stinger,+start a title near frame 96, as the resolve settles. The rings and the+silhouette leave a clear focal point at the center. As a background, set+`loop` and repeat the 168-frame cycle. `passes={0}` resolves straight from the+maze in 66 frames. `variant="filled"` with a contrasting `secondaryColor` gives+two-tone quarter-disc pinwheels.++Files: `registry/remocn/truchet-flip/index.tsx`, `config.ts`,+`__tests__/truchet-flip.test.ts`, and+`content/docs/motion-graphics/truchet-flip.mdx`. The lead integrates+registry.json, the preview index, the manifest, navigation, and the changelog+after the user approves the preview.diff --git a/docs/plans/2026-09-25-agent-run-design.md b/docs/plans/2026-09-25-agent-run-design.mdnew file mode 100644index 00000000..b9336632--- /dev/null+++ b/docs/plans/2026-09-25-agent-run-design.md@@ -0,0 +1,404 @@+# Agent Run++Direction: the part of an AI product video that happens after the prompt. A+brand-neutral chat panel shows the prompt someone just sent. A Thinking status+shimmers while a short plan streams. Tool calls run one after another, each+spinner closing into a check at the step's end. Then the answer streams in as+markdown, in bursts. A small timer in the header counts real elapsed seconds+through the run. It lives in the AI category (`content/docs/ai/`) next to the+branded composers (`claude-chat`, `chat-gpt`, `v0`, `claude-code`,+`opencode`). Those type the prompt. This one shows what happens after Enter,+so a demo can cut from a composer straight into it.++It is a product piece. It follows the quality bar in+`skills/remocn/references/anatomy.md` section 3: the product is large and+legible, the content is real and specific, there is one accent, and there is+no wall of text.++## Look++- A single panel, like a modern AI app: a flat surface, a 1px border, radius+ 18, and one small neutral shadow (`0 1px 2px`). There is no gradient, glow,+ blur, glass or sparkle icon anywhere. The root paints nothing: the panel is+ the artwork. The docs preview puts it on a flat `#ececea` field via+ `previewBackdrop`, and the docs examples use a `<Backdrop>`.+- Header, 48px, with a 1px divider under it. The thread title sits on the+ left, and the timer on the right. While running, the timer is an accent+ spinner plus `8.4s` in tabular numerals. When the run ends, it is a muted+ check and the final time.+- Scrolling column (736px wide, 32px side padding), in order:+ - The prompt, as a right-aligned user bubble.+ - The status row: `Thinking` with a restrained shimmer, then+ `Thought for 4s`.+ - The plan, as a numbered list in muted text behind a 2px left rule.+ - The tool calls, in one bordered card split by 1px dividers.+ - The answer.+- Type: body 16/26, prompt 16/24, plan 15/24, tool rows 15px, meta 13px,+ code 14/22 mono, and headings at 20/30 (`##`) or 22/32 (`#`). The fonts are+ system stacks: `Inter, Geist, ui-sans-serif, system-ui, …` and+ `"JetBrains Mono", "Geist Mono", ui-monospace, …`. The file may import only+ from `remotion` and `react`, so it loads no font. A project that loads Inter+ or JetBrains Mono gets them automatically.+- Color: two neutral themes, `light` and `dark`, plus one `accentColor`+ (default `#2563eb`).+ - The light theme uses a `#ffffff` panel, `#1c1c1a` text, `#63635e` muted+ text and `#f3f3f1` surfaces.+ - The dark theme uses a `#161616` panel, `#ececea` text, `#a2a29d` muted+ text and `#212120` surfaces.+ - The accent marks only the active state (running spinners) and the+ citation chips. The chip tint is+ `color-mix(in srgb, accent 12%, transparent)`, or 22% on dark, so any CSS+ color works. On dark, citation text mixes the accent 62% toward white to+ stay readable.+ - Done checks, the plan and the thinking shimmer are neutral.+ - Code has two tones and no extra hues: punctuation and comments are subtle,+ strings muted, and everything else is the foreground.++## Sizing rule++Every size is a reference px at a 720px-tall frame. The 800px panel renders+at reference size and is scaled by++`unit = min(height / 720, width / 880)`++880 is the panel plus a 40px margin on each side. At 16:9 this is exactly+`height / 720`, like confetti and the motion-graphics accents, and the same+as `claude-chat`'s `min(width / 1280, height / 720)`. The width cap keeps the+panel inside square and vertical frames. The panel height adapts to the+frame: `clamp(height / unit − 80, 360, 960)`.++| Frame | unit | Panel height | Scroll viewport |+| --- | --- | --- | --- |+| 1280×720 | 1 | 640 | 590 |+| 1920×1080 | 1.5 | 640 | 590 |+| 1080×1080 | 1.227 | 800 | 750 |+| 1080×1920 | 1.227 | 960 | 910 |++At 9:16 the whole default run fits without scrolling. The panel is centered+in its parent.++## Props++| Prop | Default | Meaning |+| --- | --- | --- |+| `run` | `defaultAgentRun` | `{ title?, prompt, plan?, steps?, answer }`, the whole script |+| `theme` | `"light"` | `"light"` or `"dark"` panel |+| `accentColor` | `#2563eb` | Running spinners and citation chips |+| `compression` | 3 | Real seconds per video second, clamped to 0.25–20; tool calls last `duration / compression` on screen |+| `seed` | 1 | Seeds the chunk sizes, intervals and pauses of the plan and answer streams |+| `speed` | 1 | Shared playback multiplier (0 freezes the first frame) |+| `className` | none | Class on the full-frame root |++A step is `{ name, detail?, duration, icon?, sources? }`. `duration` is real+seconds. `icon` is one of `chart`, `database`, `search`, `book`, `globe`,+`terminal` or `file`. The geometry is copied from lucide (`chart-column`,+`database`, `search`, `book-open`, `globe`, `terminal`, `file-text`). The code+panel's `copy` and the chips' `globe` and `file-text` come from the same+source. With no icon, a step with `sources` gets `book` and any other step+gets `terminal`. `sources` is a list of source labels. The row shows as many+chips as fit on one line, at most 6, then a `+N` chip. A label that looks+like a domain gets the globe icon; any other label gets the file icon.++The answer is a small markdown subset:++- `#` and `##` headings (`###` renders as `##`)+- paragraphs, split by blank lines+- `-` or `*` bullets+- inline `` `code` `` and `**bold**`+- `[n]` citations+- fenced code blocks with an optional language (an unclosed fence runs to+ the end)++Anything else renders as plain text.++The controls are `theme` (select), `accentColor`, `compression` (1–8, step+0.5) and `seed` (1–99). Number controls carry `hiddenFromList: false`, and+`speed` comes from the shared controls. `run` is not a scalar, so the preview+uses the default script.++## Real time and video time++The run is a chain of segments. Each has a video span (30 fps frames) and a+real span (seconds):++| Segment | Video frames | Real seconds |+| --- | --- | --- |+| Think (run start → plan done + 8) | from the plan stream | `frames × compression / 30` |+| Gap before each tool | 5 | `5 × compression / 30` |+| Tool call | `clamp(round(duration × 30 / compression), 12, 120)` | `duration` |+| Gap before the answer | 8 | `8 × compression / 30` |+| Answer stream | from the chunk schedule | `frames × compression / 30` |++The header timer is the piecewise-linear real time at the current frame. It+starts at 0.0 when the run starts and freezes at the total when the last+answer chunk lands. Every tool row therefore spans exactly its `duration` on+the timer, and the row's label shows the same number. At `compression` 3 the+default steps (1.4, 2.3, 1.1 and 3.2s) play in 14, 23, 12 and 32 frames. The+1.1s step would be 11 frames, and the 12-frame floor holds it long enough to+read its spinner. The 120-frame cap keeps a very long call from stalling the+video, and inside a clamped span the timer simply runs at the rate that lands+on the real duration.++## Timeline (30 fps, speed 1, default run, seed 1)++| Frames | Beat |+| --- | --- |+| 0–14 | The panel fades up 14px on an expo ease-out; the prompt bubble fades up 8px over 4–14 |+| 16 | The run starts: the timer shows 0.0s and `Thinking` fades in over 6 frames with its shimmer |+| 30–48 | The plan streams in 8 chunks (plan lines start at 30, 39 and 44) |+| 56–64 | Think ends at 56 (4.0s on the timer); `Thinking` crossfades to `Thought for 4s` and rises 4px |+| 61–75 | Query analytics: the row opens over 61–69, the spinner turns, and at 75 it closes; the check draws 78–85, and `1.4s` fades in over 77–83 |+| 80–103 | Run SQL (2.3s) opens while the previous check is still drawing |+| 108–120 | Search logs (1.1s, held at the 12-frame floor) |+| 125–157 | Read 12 sources (3.2s); the chips pop at 129, 133, 137, 141 and 144, and `+7` pops at 148 |+| 165–170 | The heading streams in body style behind a muted `## ` |+| 170–178 | Its newline arrives, so it takes heading style and morphs to 20px semibold as the marker collapses |+| 177–213 | The paragraph streams; citation `1` pops at 201 and `2` at 213 |+| 201 | The column starts gliding up, 16 frames ahead of the first line that needs room |+| 217–257 | The three bullets pop at 217, 233 and 244 and stream |+| 262–275 | The code panel opens on its fence at 262; its four lines open at 263, 265, 268 and 272 |+| 280–294 | `**Fix:** add the attribute and ship 4.12.1 today.` lands; the column comes to rest at 279px by 288, and the run ends at 294 with the timer at 27.7s |+| 294–304 | The header spinner closes into a check |+| 310 | `agentRunLength`: the last chunk fade, pop and glide have settled |+| 310–355 | The docs preview holds the finished answer (`durationInFrames` 355) |++`getAgentRunDuration(run, { seed, compression, speed })` returns+`ceil(settled / speed) + 45`, where `settled = runEnd + 16`. So the default is+355, 200 at `speed` 2, 514 at `compression` 1 and 45 at `speed` 0.+`agentRunLength` (310) is the docs `length`.++## Signature motion: bursty streaming++The plan and the answer both stream through one chunk engine. The engine+works on the raw markdown source and is seeded with remotion `random()` using+string keys `agent-run-{seed}-{plan|answer}-{size|gap|pause|hold|block}-{n}`.++1. Tokenize: a hand-written scanner splits the source roughly the way a BPE+ tokenizer does. A token is a word with its leading spaces, a group of up+ to three digits, one punctuation mark, a run of trailing spaces, or one+ newline. The default answer has 157 tokens over 458 characters, and the+ plan has 27.+2. Chunk sizes: each chunk takes 1–6 tokens, weighted 8/16/22/22/17/15%+ (mean 3.7). A chunk that reaches a blank line stops right after it. So+ every block starts on a fresh chunk, and a chunk can be just the `\n\n`+ that completes a block.+3. Intervals: the gap before each chunk is 1–4 whole frames, weighted+ 42/33/16/9%. With probability 6% a short pause of 4–7 frames is added. A+ chunk that opens a new block waits 2–4 extra frames, so the heading,+ paragraph, list, code fence and closing line arrive as separate beats. On+ seed 1 the 50 answer chunks land over 129 frames. Gaps span 1–8 frames,+ 80 of the 129 frames reveal nothing, and the busiest frame reveals 29+ characters.+4. Reveal: at time `t` the stream shows the raw source up to the end of the+ last chunk that has arrived. Each chunk fades from 0 to 1 over 5 frames on+ an ease-out cubic, so it shows at 49% on its arrival frame, then 78%, 94%+ and 99%. Text therefore arrives in irregular bursts at irregular moments,+ never at a constant rate per character.++The markdown renders progressively from the same revealed offset:++- Heading: the line streams in body style, 16px regular, behind a muted+ `## ` marker. Its box is already the heading's final 30px height, so+ nothing below it will ever shift. When its newline arrives, the heading+ style applies:+ - The weight eases from 400 to 600 on the same curve. A variable font+ interpolates it; static weights step once, mid-morph, while the text+ grows.+ - The text scales from 0.8 × 20px (the same 16px on screen) to 1 × 20px,+ anchored left.+ - The marker fades and its width collapses.++ This takes 8 frames on the house expo ease-out `cubic-bezier(0.16, 1, 0.3, 1)`.+- Bullets: an item's 6px dot pops as soon as its `-` arrives, on a back-out+ curve (`s = 1.7`). Per frame it goes 0.49, 0.82, 1.01, 1.09, 1.10, 1.06,+ 1.02, 1. Its text streams after it.+- Inline code and bold are styled from their first character. The markers+ never show.+- Citations: `[n]` stays hidden until its closing bracket arrives. Then an+ accent chip fades in over 4 frames and scales 0.6 → about 1.05 → 1 over 8+ frames (back-out, `s = 2`).+- Code block: the panel opens as soon as its three backticks arrive. It grows+ from 0 to its 54px header-and-padding height over 8 frames on the expo+ ease-out, and the language label streams in the header. Each code line+ opens its 22px row over 5 frames as its first token arrives, then streams+ inside. So the panel's bottom edge moves smoothly and never steps.++Wrapping is decided up front, so a word never jumps lines while it streams.+Each block wraps its final text greedily at word boundaries against an+estimated width. The estimate sums per-character em widths from a small class+table:++| Characters | em |+| --- | --- |+| narrow punctuation, `i l j I` | 0.3 |+| `f t r ( ) [ ] { } / \ -` | 0.44 |+| `< > = + ~ # $ & →` | 0.68 |+| digits | 0.66 |+| capitals | 0.74 |+| `m w …` | 0.9 |+| `M W @ % —` | 1.0 |+| everything else | 0.62 |++Inline code is 0.6em mono at 0.875 of the size plus 10px of padding, and a+citation chip counts as 20px. The table runs a few percent wider than Inter+semibold, measured from the font's advance widths. So a line in Inter, SF,+Segoe or Roboto never overflows, and the text column has 56px of slack even+for a wider fallback. Body text wraps at 680px (658px for bullets), headings+wrap at their own size, the plan at 640px and the prompt bubble at 520px.+Lines render with `white-space: pre` at those breaks. The default answer+lays out as heading 1 line, paragraph 2, bullets 1 + 1 + 1, code 4 and the+closing line 1. The content is 829px tall.++Calm column: every element has a fixed position from that static layout.+Content only ever grows at the bottom, so nothing already on screen reflows.+Each time a new line, row or panel appears at time `tᵢ`, the scroll target+steps to `max(target, bottomᵢ + 40 − viewport)`. The column offset is the sum+of those steps, each spread over a 24-frame smoothstep that starts 16 frames+before its content lands:++`scroll(t) = Σ Δᵢ × smoothstep((t − tᵢ + 16) / 24)`++Every step is known in advance, so the glide can begin before the text+arrives. It is monotonic and continuous, and it never jumps. At 16:9 the+default run scrolls 279px, all of it during the answer, peaking at 8.9px per+frame as the code block opens. A step is three quarters done when its content+lands. So even when a burst lands several lines within a few frames, the+newest line box stays at least 29px inside the viewport on seed 1 (16:9 and+1:1), and at least 23px on every seed from 1 to 99. With a 12-frame lead a+step is only half done on arrival, and on some seeds a burst leaves the newest+line up to 10px below the fold. A 16-frame glide that starts on arrival would+leave up to 65px of new text below the fold for 18 frames and peak at 11.7px+per frame.++Tool rows:++- A row's height opens from 0 to 40 (74 with a chips line, plus a 1px+ divider) over 8 frames on the expo ease-out, and its content fades in over+ 6.+- The spinner is a lucide-sized circle (r 10, stroke 2) over a faint track.+ An accent arc of 28% turns at a constant 12° per frame; spinning is a+ constant drift, so linear is fine.+- At the step's compressed end, the arc sweeps to a full circle over 8 frames+ on the expo ease-out.+- Meanwhile the turn decelerates linearly to rest, 48° more, and the accent+ crossfades to the muted done color on a smoothstep.+- The check (`m9 12 2 2 4-4` from lucide `circle-check`) draws in with an+ ease-out cubic from frame 3 to frame 10 of the resolve. The duration label+ fades in over frames 2–8.+- Source chips pop into the reserved line one after another. The first+ starts 4 frames into the step, and the `+N` chip pops at 70% of it. Each+ fades in over 4 frames and scales 0.8 → about 1.02 → 1 over 8 frames.+- The next row opens 5 frames after a resolve, while its check is still+ drawing.++The header timer uses the same spinner and resolves when the run ends.++Thinking shimmer: `Thinking` is drawn per character. A soft band three+characters wide sweeps left to right once every 30 frames. It takes each+character from 45% to full opacity with a `(1 − d²)²` falloff. It is a+constant drift in the neutral foreground, with no gradient text and no+accent. When the think segment ends, the label crossfades to `Thought for 4s`+over 8 frames on the expo ease-out, rising 4px.++Nothing visible moves linearly except the spinners and the shimmer.+Overlapping action comes from:++- chunk fades that overlap+- the next tool row opening under a check that is still drawing+- chips that pop one after another+- the column that starts gliding ahead of the text++Every overshoot is small and only marks an arrival: a bullet peaks at 1.10, a+citation at 1.05 and a chip at 1.02.++## Determinism++Every value derives from `useCurrentFrame()`, `useVideoConfig()`, the props+and seeded `random()`. Time is `frame × 30 / fps × speed`. The parse, the+wrap layout, the chunk schedules, the segment table and the scroll steps are+pure functions of the run, seed, compression and frame size. The component+memoizes them on those inputs (`getAgentRunModel`). The per-frame state+(`getAgentRunState`) is a pure function of time and that model. Nothing+accumulates between frames, so any frame renders correctly when seeked+directly. Frame `2n` at 60 fps and frame `2n` at `speed` 0.5 both equal frame+`n` at 30 fps.++## Default content++- Title: `Checkout conversion drop`+- Prompt: `Why did checkout conversion drop last week?`+- Plan:+ 1. `Compare the checkout funnel with the week before`+ 2. `Break the drop down by browser and step`+ 3. `Check what shipped and what the error logs say`+- Tools:+ 1. `chart` Query analytics · `checkout funnel, last 7 days vs prior 7` ·+ 1.4s+ 2. `database` Run SQL · `conversion by browser and step` · 2.3s+ 3. `search` Search logs · `Apple Pay errors on Safari` · 1.1s+ 4. `book` Read 12 sources · 3.2s. Its sources are `Checkout funnel`,+ `Browser report`, `Release 4.12`, `PR #2186`, `webkit.org`,+ `developer.mozilla.org`, `Payments runbook`, `Error log`,+ `Incident notes`, `Apple Pay guide`, `Support tickets` and+ `Status page`. The first five show as chips, then `+7`.+- Answer:++ ```md+ ## Apple Pay broke on Safari in release 4.12++ Checkout conversion fell from 3.4% to 2.7% last week, a 21% drop [1]. All of it comes from the payment step on Safari, 41% of checkouts [2].++ - Safari conversion halved, from 3.5% to 1.8%+ - Chrome and Firefox held steady at 3.3%+ - 4.12 moved the card form into an iframe without `allow="payment"` [3]++ ~~~tsx+ <iframe+ src={cardFormUrl}+ allow="payment"+ />+ ~~~++ **Fix:** add the attribute and ship 4.12.1 today.+ ```++ (The real default uses a backtick fence.)++The numbers add up. Safari carries 41% of checkouts and falls from 3.5% to+1.8%, while the rest hold at 3.3%. That takes the blend from 3.38% to 2.69%,+which is the 3.4% → 2.7% drop, or −21%. Apple Pay inside a cross-origin+iframe needs `allow="payment"`, so the fix is specific and real.++## Exports++- Components and data: `AgentRun`, `defaultAgentRun`, `agentRunDefaults`,+ `agentRunLength` and `AGENT_RUN_THEMES`.+- Timeline: `getAgentRunDuration`, `getAgentRunTimeline`, `getAgentRunTime`+ and `getAgentRunElapsed`.+- Streaming: `tokenizeAgentRun`, `getAgentRunChunks`, `getAgentRunReveal` and+ `getAgentRunArrival`.+- Parsing and layout: `parseAgentRunMarkdown`, `wrapAgentRunInline`,+ `estimateAgentRunWidth`, `getAgentRunCodePieces`, `fitAgentRunChips` and+ `getAgentRunLayout`.+- Frame and state: `getAgentRunFrame`, `getAgentRunGrowth`,+ `getAgentRunScrollSteps`, `getAgentRunScroll`, `getAgentRunModel`,+ `getAgentRunState`, `getAgentRunSpinner` and `getAgentRunShimmer`.+- Display: `getAgentRunPalette` and `formatAgentRunSeconds`.+- Types: `AgentRunScript`, `AgentRunStep`, `AgentRunProps` and the rest.++## Handoff and usage++Cut to it right after a composer (`claude-chat`, `chat-gpt`) sends its prompt,+or use it as the product-reveal beat of a demo. Pass your own `run`: the+steps, their real durations and the answer. The timeline, timer and duration+follow from them. `getAgentRunDuration(run, { seed, compression, speed })`+sizes the `Sequence`. Raise `compression` to shorten long tool calls. Keep the+answer to a heading, a short paragraph, a few bullets and one small code+block. The panel scrolls, but a legible answer is short.++Files: `registry/remocn/agent-run/index.tsx`, `config.ts`,+`__tests__/agent-run.test.ts` and `content/docs/ai/agent-run.mdx`. The lead+integrates registry.json, the preview index, the manifest, navigation+(`content/docs/ai/meta.json`, the AI index cards) and the changelog after the+user approves the preview. The docs cite `code-morph` in `avoidWhen`, so that+sibling must be in the registry before the docs gate runs.diff --git a/docs/plans/2026-09-25-code-morph-design.md b/docs/plans/2026-09-25-code-morph-design.mdnew file mode 100644index 00000000..3e5051fc--- /dev/null+++ b/docs/plans/2026-09-25-code-morph-design.md@@ -0,0 +1,340 @@+# Code Morph++Direction: Keynote Magic Move for code, as a product piece in UI Blocks+(`content/docs/ui-blocks/`), next to `glass-code-block` and `glass-code-walk`.+A flat editor panel shows one version of a file, then morphs into the next.+Tokens that exist in both versions keep their identity: each one is a single+element that glides from its old line and column to its new ones. Removed code+dissolves first, the survivors travel, and new code fades in last. The panel+keeps one size that fits every version, so code that did not change never+moves. After each morph, the changed lines hold a brief accent highlight. The+default content sells an API simplification: 16 lines of `useState` ++`useEffect` + `fetch` boilerplate collapse into an 8-line component built on+one data hook. The line that carries the story is `"/api/invoices"`. It lifts+out of the `fetch(...)` call on line 8 and lands inside `useSWR(...)` on line+4, and the eye can follow it the whole way.++The component is the product surface itself: large, legible, real code, one+accent. It has no typing, no cursor, no camera, and no glass.++## Look++- Panel: solid fill, 1px border, 14px radius, `overflow: hidden`. No shadow,+ glow, blur halo, gradient, or backdrop blur. The panel is artwork, so it is+ filled. The root around it is transparent.+- Header, 42px, shown when `windowDots` is on or `filename` is not empty.+ It holds three neutral window dots (11px, 7px apart; no traffic-light+ colors, so the accent stays the only hue) and a filename tab. The tab is+ filled with the panel color, has a 1px border on three sides and 8px top+ corners, and covers the header divider so it reads as the open file.+- Code: the `glass-code-block` mono stack, with a fallback inside the+ `var()`: `var(--font-geist-mono, ui-monospace), ui-monospace,+ SFMono-Regular, Menlo, Consolas, monospace`. The original+ `var(--font-geist-mono), …` invalidates the whole `font-family` declaration+ in projects that do not define the variable, and the text then falls back+ to the inherited, often proportional font. That breaks a column grid, so the+ fallback is required here. Ligatures are off.+- Syntax palette: neutral tones plus the accent.++| Role | Dark | Light |+| --- | --- | --- |+| Panel | `#111113` | `#ffffff` |+| Header | `#0c0c0e` | `#f7f7f8` |+| Border, divider | `#27272a` | `#e4e4e7` |+| Window dots | `#3f3f46` | `#d4d4d8` |+| Tab label | `#e4e4e7` | `#27272a` |+| Line numbers | `#52525b` | `#b4b4bb` |+| Function and type names | `#fafafa` | `#09090b` |+| Identifiers | `#d4d4d8` | `#3f3f46` |+| Keywords | `#a1a1aa` | `#71717a` |+| Punctuation | `#71717a` | `#909098` |+| Comments | `#5b5b63` | `#a1a1aa` |+| Strings, numbers | accent mixed 80% with white | accent mixed 70% with black |+| Changed-line band | accent at 16% | accent at 12% |++Strings use `color-mix(in oklab, accent, white or black)`, so any accent stays+legible on either panel. The band spans the full panel width, with a 2px+solid accent bar at the left edge.++## Props++| Prop | Default | Range | Meaning |+| --- | --- | --- | --- |+| `steps` | before/after below | `{ at, code }[]` | Versions in order; `at` is the 30 fps frame where the morph into that version starts |+| `morphDuration` | 36 | 12–120 | Frames from the first removed token leaving to the last new token settling |+| `highlight` | true | boolean | Accent band on changed lines after each morph |+| `fontSize` | 20 | 10–40 | Code size in reference px |+| `lineNumbers` | true | boolean | Gutter with right-aligned line numbers |+| `filename` | `"invoices.tsx"` | string | Tab label; empty hides the tab |+| `windowDots` | true | boolean | Three neutral dots in the header |+| `theme` | `"dark"` | `dark`, `light` | Panel and syntax palette |+| `accentColor` | `#0ea5e9` | color | Strings, numbers, highlight band and bar |+| `speed` | 1 | shared | Time multiplier; 0 freezes the first version |+| `className` | none | string | Class on the full-frame root |++Steps are sorted by `at`. The first version shows from frame 0 whatever its+`at`. Code is normalized: CRLF becomes LF, tabs become two spaces, trailing+spaces go, leading and trailing blank lines are dropped, and the common+indentation is removed. Template literals indented inside JSX therefore work.+If a step's `at` falls before the previous morph has finished, that morph+starts when the previous one ends, so morphs never overlap.++## Sizing rule++Every size is in reference px at a 1280×720 frame, scaled by++`unit = min(width / 1280, height / 720) × fit`++At 16:9 this is the `confetti` rule, `height / 720`. The width term keeps the+panel inside 1:1 and 9:16 frames, which the pure height rule would overflow,+because a code panel is wide. `fit = min(1, 1152 / panelWidth, 640 /+panelHeight)` shrinks the whole panel when the longest line or the tallest+version would not fit inside 64px side and 40px top/bottom margins. For+fitting only, `panelWidth` estimates the mono advance as 0.6em. `fit` depends+on the largest version, so it stays constant for the whole animation. The+default panel is about 854×580 at 720p and needs no fit.++Positions use no DOM measurement. A token at `(line, col)` sits at+`translate(col ch, line × lineHeight px)`, where `ch` is the CSS unit, the+advance of the panel's own mono font, and `lineHeight = 1.55 × fontSize`.+The panel width is `calc((gutter + maxColumns) ch + 50px)` at unit 1. It is+fixed at the longest line of any version. Its height, `42 + 20 + 22 + rows ×+lineHeight`, is fixed the same way at the tallest version. The panel is+centered in the frame and never moves or resizes. A panel that resized while+staying centered would drift every unchanged line by half the height change,+124px in the default. `"/api/invoices"` would then end at the same screen+height it started from, and its lift would read as a hop. Magic Move only reads+when motion means change, so the frame holds still. A shorter version leaves+empty editor space below it, as a real editor does.++## Default content++Before (16 lines):++```tsx+import { useEffect, useState } from "react";++export function Invoices() {+ const [invoices, setInvoices] = useState([]);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ fetch("/api/invoices")+ .then((res) => res.json())+ .then(setInvoices)+ .finally(() => setLoading(false));+ }, []);++ if (loading) return <Spinner />;+ return <InvoiceTable rows={invoices} />;+}+```++After (8 lines), at frame 48:++```tsx+import useSWR from "swr";++export function Invoices() {+ const { data, isLoading } = useSWR("/api/invoices", fetcher);++ if (isLoading) return <Spinner />;+ return <InvoiceTable rows={data} />;+}+```++What the diff pairs (lines 1-based):++- Static: `import`, `export function Invoices() {`, `const`.+- Line 1: `from` and `;` slide 17 and 19 columns left as the named imports+ leave.+- Line 4: `,` and `=` slide 3 and 4 columns left. `(` and `"/api/invoices"`+ fly up 4 lines and right 27 columns out of `fetch(...)` on line 8. The+ closing `)` flies too, landing 9 columns further right after the new+ `, fetcher`.+- The `if` line and the `return` line rise 8 lines as whole blocks. The part+ after `isLoading` shifts 2 columns right, and the part after `data` shifts+ 4 columns left.+- The closing `}` rises from line 16 to line 8.+- Removed (73 tokens): the React named imports and `"react"`, the rest of+ both `useState` lines, the whole effect, `loading` and `invoices`. Added (12+ tokens): `useSWR`, `"swr"`, `{ data, isLoading }`, `useSWR`, `, fetcher`,+ `;`, `isLoading`, `data`. Surviving: 33 tokens, 25 of them moving in 11+ blocks.+- Highlighted after the morph: lines 1, 4, 6 and 7. Lines 3 and 8 are exact+ copies of old lines, so they get no band.++## Timeline (30 fps, speed 1, default content)++| Frames | Beat |+| --- | --- |+| 0–48 | The 16-line version holds |+| 48–64 | Removed tokens fade, blur to 3.5px and shrink to 92%, top line first, 0.4 frames apart |+| 54–80 | Survivors glide; the five destination lines start 1 frame apart (54, 55, 56, 57, 58), each over 22 frames |+| 58–78 | Line numbers 9–16 fade, timed with the last moving line; the panel keeps its size |+| 68–84 | New tokens fade in over 12 frames, per destination line at 68, 69.3, 70.7, 72 |+| 68–76 | Changed-line bands rise |+| 76–100 | Bands hold |+| 100–114 | Bands fade (`codeMorphLength` = 114) |+| 114–138 | Hold (`getCodeMorphDuration()` = 138) |++Phase constants are defined at a 36-frame morph and scale with+`morphDuration` (value × morphDuration / 36):++| Phase | Start | Spread | Duration |+| --- | --- | --- | --- |+| Exit | 0 | 4 (per source line) | 12 |+| Move | 6 | 4 (cascade by destination line) | 22 |+| Enter | 20 | 4 (per destination line) | 12 |++The highlight does not scale. It rises over 8 frames from the enter start,+holds 24 and falls over 14. If the next morph starts first, the fall begins+at that morph's start. The timeline helper returns every morph's `start`,+`end`, `highlightStart`, `fallStart` and `highlightEnd`. `settled` is the last+highlight end, or the last morph end when `highlight` is off (84 for the+default). `duration` adds a 24-frame hold. `codeMorphLength = settled` of the+default content = 114.++## Signature motion++### Tokenizer++A hand scanner (no regex over the whole file) splits each normalized line into+tokens with `(line, col)`, where `col` counts code points. Whitespace is not a+token; the column grid carries it. Token kinds:++- `comment`: `// …` to line end, `/* … */` (may span lines).+- `string`: `"…"`, `'…'`, and template literals (may span lines). A string is+ one token.+- `number`: decimal, hex, binary, octal, exponent, bigint.+- word: `[A-Za-z_$]` plus Latin and Greek letters, then word characters. It+ is a `keyword` if it is in the TS/JS keyword set and not after `.` or `?.`.+ Otherwise it is a `function` if the next token is `(`, a `type` if+ capitalized, and `text` otherwise.+- `punct`: the longest operator from `=== !== **= ... &&= ||= ??= => == != <=+ >= && || ?? ?. ++ -- += -= *= /= %= ** </ />`, else one code point.++Comments, strings, numbers and words are word tokens; the rest is punctuation.++### Diff: five passes++Positions only break ties and veto stray punctuation. Identity comes from+identical text.++1. Anchors (patience style). Word texts that occur exactly once in both+ versions are candidate pairs. The longest increasing subsequence of their+ new indices, taken in old order, gives the anchors. Each anchor's+ displacement predicts where its neighbors go.+2. Words. A weighted LCS over the word tokens pairs identical texts. Each+ pair is worth `W − cost`, where `W = (min(n, m) + 1) × 1000` and cost ≤+ 1000. So the pair count always wins, and cost only decides between equal+ counts, such as which of two `const` statements survives. `cost(i, j)` is+ the smaller of the costs against the nearest guide before and after token+ `i` in old order; a missing side is ignored, and with no guide at all the+ prediction is "no move". Against a guide `(a, b)`:+ - Expected line: `line_i + (line_b − line_a)`.+ - Column offset, when `i` shares the guide's old line: the smaller of the+ left-anchored offset (expected column `col_i + (col_b − col_a)`) and the+ right-anchored one (same distance from the line end in both versions).+ Otherwise it is `|col_j − col_i|`.+ - Cost: `10 × |line offset| + 0.5 × |column offset|`.+ The right-anchored option keeps trailing `]`, `)` and `;` attached to the+ line end when a call gains an argument.+3. Punctuation. The word pairs cut both sequences into aligned gaps. Inside+ each gap, a weighted LCS pairs identical punctuation worth `12 − cost`.+ Here the cost uses the gap's bounding word pairs as the guides. A pair is+ kept only when that value is positive. So punctuation survives only when+ it stays with its line: at most one line off, and within 24 columns of+ where its neighbors predict. Commas and parens never fly across the file on+ their own.+4. Bracket partners. `(`, `[` and `{` are matched to their closers in each+ version. When a paired opener's closer is paired elsewhere, or not at all,+ it is re-paired with the closer of the opener's partner. A closing `});`+ therefore follows its call down when a line is inserted above it, instead+ of pairing with the new line's `}`.+5. Line moves. A new line whose tokens are all unpaired takes a removed line+ with the same tokens at the same relative columns, the nearest one first,+ provided it holds at least one word. Swapped or reordered lines then+ travel past each other, which an order-preserving LCS cannot do.++Both LCS tables are filled from the end and traced forward. At equal value the+trace prefers a match, then skipping an old token. `fromTo` and `toFrom` are+exact inverses, and the result is deterministic. It preserves order except for+pass 5; the default content involves no line moves.++### Choreography of one morph (τ = frames since the morph start, D = morphDuration)++- Exit (unpaired old tokens): `delay = 4·D/36 × rank(source line)`, where+ rank runs 0–1 over the distinct lines that lose tokens.+ `q = (τ − delay) / (12·D/36)`, `e = easeOutCubic(q)`. Opacity `1 − e`, scale+ `1 − 0.08e` about the token center, blur `3.5e` reference px. A token is+ dropped once `q ≥ 1`.+- Move (paired tokens whose line or column changes):+ `delay = 4·D/36 × rank(destination line)`, and+ `p = (τ − 6·D/36 − delay) / (22·D/36)`. Vertical progress is+ `E(p / 0.92)` and horizontal progress is `E((p − 0.08) / 0.92)`, with+ `E = cubic-bezier(0.6, 0, 0.2, 1)` clamped to 0–1. So a token that changes+ both line and column rises slightly ahead of its slide and travels a gentle+ arc instead of a diagonal. `line = line₀ + Δline × vertical` and+ `col = col₀ + Δcol × horizontal`. Timing depends only on the destination+ line and the path only on the displacement. So tokens from one source line+ with the same offset move rigidly together as a block, and a destination+ line assembles at once. Nothing overshoots: code lands exactly on the grid.+ Paired tokens that do not move render in place.+- Enter (unpaired new tokens): `delay = 4·D/36 × rank(destination line)` and+ `q = (τ − 20·D/36 − delay) / (12·D/36)`. Opacity `e`, scale `0.96 + 0.04e`,+ blur `3.5(1 − e)`. Hidden until `q > 0`.+- Gutter rows: `lines = n₀ + (n₁ − n₀) × E(pp / 0.92)` is the line count the+ gutter numbers. `pp` uses the move window with the largest cascade delay+ when shrinking and no delay when growing. Line numbers beyond the smaller+ count fade with that progress, so they follow the slowest line up and lead+ the fastest line down. A number never vanishes from a row that still holds+ moving code, and it appears before code lands on its row.+- Changed lines: a new line is highlighted unless every token on it is a+ survivor from one old line whose tokens all land on it, meaning an exact+ copy, moved or re-indented. Band opacity is+ `easeOutQuad((t − highlightStart) / 8) × (1 − smoothstep((t − fallStart) / 14))`.+ The previous morph's bands keep fading at their rows during the next morph.++Every phase ends by τ = D. At τ = 0 the render equals the old version at rest,+and at τ = D it equals the new version at rest, so the hand-off at both ends+is seamless.++## Rendering++The root is `position: absolute; inset: 0`, transparent, and centers the+panel. Inside the panel, in order: header (dots, divider, tab), highlight+bands and bars, then a content origin at the top-left padding. That origin+holds the line numbers (`digits` ch wide, right-aligned, 2ch gap; digits =+max(2, digits of the tallest version)) and the code layer, offset by the+gutter in `ch`. Every token is one absolutely positioned `white-space: pre`+span with `transform: translate(col ch, y px) scale(s)`. It carries opacity,+and a `filter: blur()` only while blurring. Paint order is leaving tokens,+then survivors, then arrivals. Survivors are keyed by their+destination token, so after a morph the resting elements are the same ones+that travelled. The default morph peaks at 106 spans on its first frame: 73+leaving and 33 surviving. The rest state of the new version is 45.++## Determinism++Every value derives from `useCurrentFrame()`, `useVideoConfig()` and props.+Time is `frame × 30 / fps × speed`. There is no randomness at all: staggers+come from line ranks, so no seed is needed. The tokenizer, diff and layout are+pure and memoized on their inputs only. The per-frame state is a pure function+of time and layout. There is no React state, CSS animation or transition, and+nothing accumulates across frames, so any frame renders correctly when seeked+to directly.++## Handoff and usage++Put it full-frame over a `<Backdrop>`. The docs preview uses `#f1eee7` via+`previewBackdrop`, and the dark panel sits on warm paper. Feed your own+versions through `steps`. `getCodeMorphDuration({ steps, morphDuration,+highlight, speed })` gives the composition length, 24-frame hold included.+Three or more steps chain: each morph starts at its `at` or when the previous+one ends, whichever is later.++Files: `registry/remocn/code-morph/index.tsx`, `config.ts`,+`__tests__/code-morph.test.ts`, and `content/docs/ui-blocks/code-morph.mdx`.+The lead integrates registry.json, the preview index, the manifest,+navigation, and the changelog after the user approves the preview.diff --git a/docs/plans/2026-09-25-keystroke-design.md b/docs/plans/2026-09-25-keystroke-design.mdnew file mode 100644index 00000000..1fea2788--- /dev/null+++ b/docs/plans/2026-09-25-keystroke-design.md@@ -0,0 +1,300 @@+# Keystroke++Direction: an on-screen keystroke overlay for videos of keyboard-first+products: command palettes, shortcuts, editors. It works like a tasteful+KeyCastr. For each shortcut, physical keycaps appear, press in real order,+spring back, and leave after an idle hold. It is the keyboard counterpart of+`simulated-cursor` and lives in Effects (`content/docs/effects/`). Effects are+drop-in overlays composed on top of any scene. The keycaps are the only+artwork: no panel, no labels, no captions. The product UI underneath shows+what the shortcut did.++The timeline mirrors the remocn-ui steps shape. A step is+`{ at, keys, hold? }`, and `at` is the frame the shortcut fires, the frame the+last key bottoms out. A remocn-ui step on the same frame (`{ at, state }`)+reacts exactly on the click, so one frame number drives both the keystroke+and the UI it triggers. Everything that leads up to the click is scheduled+backward from `at`: the caps rising in, the modifiers going down, and the+earlier chords of a sequence.++## Look++Each key is a keycap drawn flat, as a keytop on a base, viewed slightly from+the front:++- Base (side wall): a rounded rectangle in the wall color. It spans the cap+ from `travel` down to the bottom edge, so it only ever shows below the+ keytop.+- Keytop: a rounded rectangle in the cap color with a hairline edge (1px at+ 720p, scaled with the frame). It is `size × 0.84` tall and sits on top of+ the base, so a `size × 0.16` wall shows under it at rest. Pressing moves it+ down by up to `travel` (`size × 0.12`), leaving a `size × 0.04` wall.+- Contact shadow: one small, neutral box shadow under the base. It is+ `size × 0.07` down with a `size × 0.11` blur at rest (4.5px and 7px at the+ default size) and tightens to `size × 0.02` down with a `size × 0.03` blur+ at full press. No spread and no color, well inside the house shadow limits.+- Legend: crisp and centered on the keytop. Single characters are uppercase,+ `size × 0.4`, weight 500. Words are `size × 0.26`, weight 500. Mac glyphs are+ lucide icons drawn at `size × 0.36` with stroke 2, so they render the same on+ every machine.+- Corner radius `size × 0.16` on both keytop and base.++No gradients, glows, glass, or blur halos. The root paints no background. The+docs preview puts the overlay on a flat light gray (`#e9e9e5`) via+`previewBackdrop`, and the docs examples use a `<Backdrop>`.++Palettes (`theme`):++| Token | light | dark |+| --- | --- | --- |+| Keytop | `#fcfcfb` off-white | `#38393e` graphite |+| Keytop edge | `#dfdfda` | `#48494f` |+| Wall | `#cfcfca` light gray | `#1f2023` |+| Legend | `#1d1d1f` | `#f5f5f7` |+| Separator | `#8e8e89` | `#9d9da4` |+| Contact shadow | `rgba(20, 20, 16, 0.18)` | `rgba(0, 0, 0, 0.5)` |++One accent (`accent`, default `#0a84ff`, the macOS system blue) marks the+keys that are down. A legend mixes toward the accent in proportion to its+key's depth (`color-mix(in srgb, accent p%, legend)` with+`p = floor(depth × 100)`, so the settling tail of a release stays neutral).+It turns fully accent at the bottom and back to neutral as the key comes up.+The accent never fills a surface. `#0a84ff` reaches about 3.5:1 on the light+keytop and 3.2:1 on the graphite keytop, enough for large legends in both+themes.++Widths come in keyboard units (`u = size`):++| Key | mac | windows |+| --- | --- | --- |+| Letters, digits, punctuation, arrows | 1 | 1 |+| Command, option, control | 1 (⌘ ⌥ ⌃) | word |+| Shift | 1.5 (⇧) | word |+| Return / enter | 1.5 (↩) | word |+| Delete / backspace | 1.25 (⌫) | word |+| Tab | 1.25 (⇥) | word |+| Escape | 1 (⎋) | word |+| Caps lock | 1.5 (⇪) | word |+| Space | 2.5 (␣) | 2.5 |+| Other words (`fn`, `F5`, `Home`) | word, min 1 | word, min 1.25 |++A word key is `ceil_to_quarter(chars × 0.156 + 0.48)` units wide. That is+`chars × 0.6em` of the `size × 0.26` word font plus `size × 0.24` padding on+each side. On windows the minimum is 1.25, so every word-labelled key reads as+wide: Ctrl 1.25, Alt 1.25, Shift 1.5, Enter 1.5, Backspace 2, Space 2.5. Caps+in a chord sit `size × 0.14` apart. Chords in a sequence are joined by a+subtle separator: the word "then" in the separator color, `size × 0.25`,+centered in a `size × 0.95` slot.++## Key grammar++`keys` is a combo (`"mod+k"`, `"shift+mod+p"`, `"enter"`) or a sequence of+chords separated by spaces (`"g i"`: press g, then i). Tokens are+case-insensitive. `"mod++"` or `"mod+plus"` gives a plus key.++- `mod` resolves by `platform`: command on mac, Ctrl on windows.+- `cmd`, `command`, `meta`, `win` are command on mac and Win on windows.+ `ctrl`, `control`, `alt`, `option`, `opt`, `shift`, `fn` are the other+ modifiers.+- `enter`/`return`, `esc`/`escape`, `tab`, `space`, `backspace`,+ `delete`/`del`, `capslock`, `up`/`down`/`left`/`right` (and `arrowup` …),+ `home`, `end`, `pageup`, `pagedown`, `f1`–`f24` are named keys.+ `plus`, `minus`, `comma`, `period`, `slash`, `backslash`, `semicolon`,+ `quote`, `backquote`, `bracketleft`, `bracketright`, `equal` map to their+ characters.+- Anything else is one character (uppercased) or a word legend.+- Modifiers are shown and pressed in the platform's standard order: fn ⌃ ⌥ ⇧ ⌘+ on mac, and Fn Win Ctrl Alt Shift on windows. Duplicates collapse. The other+ keys follow in the order written, and the last key is the trigger.++Mac legends: ⌘ `command`, ⌥ `option`, ⇧ `arrow-big-up`, ⌃ `chevron-up`,+↩ `corner-down-left`, ⌫ `delete`, ⎋ `circle-arrow-out-up-left`,+⇥ `arrow-right-to-line`, ␣ `space`, ⇪ `arrow-big-up-dash`, and the four+`arrow-*` icons. All geometry is copied from the lucide-react `__iconNode`+arrays. Windows legends are words: Ctrl, Alt, Shift, Win, Enter, Esc, Tab,+Space, Backspace, Delete, Caps Lock, Fn. Windows arrows use the same icons.++## Props++| Prop | Default | Range | Meaning |+| --- | --- | --- | --- |+| `steps` | three-step flow | `KeystrokeStep[]` | `{ at, keys, hold? }`; `at` is the Sequence-local frame the shortcut fires |+| `platform` | `mac` | `mac`, `windows` | Resolves `mod` and picks glyph or word legends |+| `theme` | `light` | `light`, `dark` | Off-white caps on a light-gray wall, or graphite caps |+| `accent` | `#0a84ff` | color | Legend color of keys that are down |+| `x` | 0.5 | fraction | Row center, fraction of the composition width |+| `y` | 0.86 | fraction | Row center, fraction of the composition height |+| `size` | 64 | 8–400 ref px | Height of a keycap and width of a 1u key at 720p |+| `linger` | 30 | 0–600 frames | Idle hold after the last key comes up, before the caps leave |+| `speed` | 1 | shared | Scales time; 0 never fires |+| `className` | – | – | Class on the full-frame root |++`hold` on a step is how long the chord stays down: the frames the trigger+stays at the bottom after it fires. The default is 8. `at`, `hold` and+`linger` are composition frames, exactly like remocn-ui `at`. The playhead is+`frame × speed`, so a keystroke and a remocn-ui step with the same `at` and+`speed` always land on the same frame. The internal motion (press, release,+rise) is authored in 30 fps frames and converted with `30 / fps`, so it takes+the same time in seconds at any frame rate.++The docs customizer exposes `platform`, `theme`, `accent`, `x`, `y`, `size`,+`linger` and the shared `speed`. `steps` is an array, so it is not a control.+Number controls carry `hiddenFromList: false`.++## Sizing rule++Every size is in reference px at a 720px-tall composition and is multiplied+by `unit = height / 720`, like confetti and the motion-graphics accents. The+default 64px keycap is 96px at 1080p. Position is a fraction (`x`, `y`), so the+anchor stays put at any aspect ratio. The group anchor is positioned with+percentages of the root, so it also works inside a padded container. In a+9:16 frame, `unit` is 2.67. A four-key windows combo then spans most of the+width, so portrait videos should pass a smaller `size`.++## Timeline (30 fps, speed 1, default content)++Default steps: `{ at: 20, keys: "mod+k" }` (open the command menu),+`{ at: 78, keys: "g i" }` (go to inbox, a two-key sequence), and+`{ at: 114, keys: "shift+mod+p" }` (open the command palette). On mac they+read ⌘K, G then I, ⇧⌘P. On windows they read Ctrl K, G then I,+Ctrl Shift P.++| Frames | Beat |+| --- | --- |+| 0–7 | Empty frame |+| 7–18 | ⌘ rises in on 7 and K on 8; each settles 10 frames later |+| 14–17 | ⌘ goes down |+| 17–20 | K goes down; ⌘K fires on 20 (the command menu opens here) |+| 28–41 | K comes up on 28 and ⌘ on 31, each with a small overshoot; settled by 41 |+| 48–58 | G rises in; ⌘K slides back to the second slot, scales to 0.86 and dims |+| 55–58 | G goes down; fires on 58 |+| 61–69 | ⌘K leaves (its linger ran out) |+| 66–76 | G comes up |+| 68–78 | "then" and I rise in while the row re-centers; G dims to 0.45 over 72–78 |+| 75–78 | I goes down; G then I fires on 78 |+| 86–96 | I comes up |+| 98–110 | ⇧, ⌘, P rise in on 98, 99 and 100; G then I slides back |+| 105–114 | ⇧ down on 105, ⌘ on 108, P on 111; fires on 114 |+| 116–124 | G then I leaves (its brief hold in the second slot ended) |+| 122–138 | P comes up on 122, ⌘ on 125, ⇧ on 128; settled by 138 |+| 158–166 | ⇧⌘P leaves after a 30-frame linger |+| 166–180 | Empty hold (preview only) |++`keystrokeLength` is 166, the frame the last group has left. The preview+duration is `getKeystrokeDuration()`, 180. That is the motion end divided by+`speed` plus a 14-frame tail, all converted to composition frames.++## Signature motion++### Per-chord schedule++For a chord of `n` keys `k0 … k(n−1)` that fires on `F`, with hold `h`:++- Key `i` starts down on `F − 3 − 3 × (n − 1 − i)`, so the keys go down 3+ frames apart, modifiers first. Each press takes 3 frames, and the trigger+ bottoms out exactly on `F`.+- The trigger starts back up on `F + h`. Key `i` starts up on+ `F + h + 3 × (n − 1 − i)`. The keys come up in reverse, last down first up,+ so for ⌘K it is ⌘ down, K down, K up, ⌘ up. The modifiers stay down while+ the letter taps.+- The chord's caps start rising 7 frames before its first key goes down+ (`enter = F − 10 − 3 × (n − 1)`). Cap `i` rises 1 frame after cap `i − 1`,+ for a little overlap.++A sequence chains its chords. The next chord starts rising 2 frames after the+previous chord's last key starts up. The step's `at` is the fire frame of the+last chord, because a sequence shortcut fires on its last key. The lead-in+from the first rise to `at` is+`Σ (10 + 3(n_j − 1)) + Σ_{j<last} (h + 3(n_j − 1) + 2)`: 10 frames for a+single key, 13 for a two-key combo, 16 for three, and 30 for `g i`.++### Depth++`depth(t)` is 0 at rest and 1 at the bottom:++- Press, frames `0–3` after the key's press start: smoothstep+ `u²(3 − 2u)`. Per frame that is 0, 0.26, 0.74, 1. The first and last+ frames ease, and nothing moves linearly.+- Hold: exactly 1.+- Release: `1 − settle(t)`. `settle` is a closed-form underdamped spring step+ response, like `truchet-flip`'s snap, with damping ratio 0.46. Its frequency+ is tuned to first reach rest on frame 3. It overshoots to about 0.196 above+ rest near frame 4.6. From frame 6 a smoothstep taper removes the ringing,+ so it lands exactly on rest on frame 10. Per frame: 1, 0.774, 0.35, 0,+ −0.173, −0.188, −0.12, −0.032, 0.009, 0.006, 0. The overshoot is capped by+ construction. At the default size it lifts the keytop about 1.5px above+ rest.++Depth drives four things at once:++- keytop `translateY = depth × travel`+- visible wall `= wall − depth × travel`, from 10.2px down to 2.6px at 64+- contact shadow offset and blur, which tighten+- legend color, which mixes toward the accent (`clamp(depth, 0, 1)`)++### Enter and leave++- Rise: a cap starts `size × 0.42` below its rest line and follows the same+ spring shape with damping 0.65. It first reaches rest on frame 4, peaks+ 6.8% past rest near frame 5.5, and tapers from frame 7 to land exactly on+ frame 10. Per frame: 0, 0.199, 0.549, 0.835, 1, 1.062, 1.064, 1.043,+ 1.015, 1.001, 1. Opacity eases in over the first 4 frames.+- Row re-center: a group is centered on its visible width. When a later chord+ of a sequence starts rising, the visible width eases from the old width to+ the new one over 10 frames with an ease-out cubic+ (`cubic-bezier(0.33, 1, 0.68, 1)`, 27% after one frame, 49% after two). The+ earlier caps slide left by half of the new chord's width while the new caps+ rise into the gap. The house EXPO curve covers 49% in the first frame and+ reads as a jump for a layout shift, so it is not used here.+- Dim: the earlier chords of a sequence fade to 0.45 opacity over the 6+ frames before the next chord fires (smoothstep).+- Leave: all caps of a group leave together. Over 8 frames, opacity falls+ with an ease-in (quad), the group drifts `size × 0.22` with an ease-in+ (cubic), and it scales to 0.96. A group still in front sinks down, the+ reverse of its rise. A group already pushed back drifts up, away from the+ newer group.++### Stack++Groups are ordered by the frame they start rising. When a newer group starts+rising, every group still on screen is pushed back one slot over 10 frames+(the same ease-out cubic). A slot is `size × 1.09` higher, the row scales by+0.86 around its center, and the group's opacity drops to 0.55. The pushed row's bottom then+sits `size × 0.16` above the front row. A group leaves at the earliest of:++1. its last key-up plus `linger` (the idle hold),+2. 18 frames after it is first pushed back (it only stacks briefly). If its+ keys are still down at the push, the 18 frames count from its last key-up+ instead, so a long `hold` or a tight pair of steps does not fade a group+ out with its keys held; its release plays in the back slot,+3. the moment a second newer group starts rising.++At most two groups hold the screen, newest in front. When steps are so dense+that a third group arrives, the oldest is already leaving: it fades while it+drifts up to a third slot. With the default content, never more than two are+visible. A group that has already left is never pushed.++## Determinism++Every value is a pure function of the frame, `useVideoConfig()` and the+props. Time is `frame × speed × 30 / fps` in 30 fps frames, and step times are+`at × 30 / fps`. There is no randomness. The parsed timeline (key legends,+chord schedules, stack exits) depends only on `steps`, `platform`, `linger`+and `fps`, and is memoized on them. Nothing accumulates across frames, so any+frame renders the same when seeked to directly. Steps are validated: those+with a non-finite `at` or no parsable key are dropped, `hold` falls back to 8+and is clamped to 0–600, and numeric props fall back to their defaults.++## Handoff and usage++Put `Keystroke` last in the scene, over the product UI. Give each shortcut the+same `at` as the remocn-ui step it triggers, for example+`{ at: 20, keys: "mod+k" }` next to `{ at: 20, state: "opened" }` on+`command-menu`. Leave at least the lead-in (13 frames for a two-key combo)+before the first `at` of a Sequence. For a separate caption or a click, pair+it with `simulated-cursor`.++Files: `registry/remocn/keystroke/index.tsx`, `config.ts`,+`__tests__/keystroke.test.ts`, and `content/docs/effects/keystroke.mdx`. The+lead integrates registry.json, the preview index, the manifest, navigation+and the changelog after the user approves the preview.diff --git a/docs/plans/2026-09-25-showreel-type-design.md b/docs/plans/2026-09-25-showreel-type-design.mdnew file mode 100644index 00000000..77d927b6--- /dev/null+++ b/docs/plans/2026-09-25-showreel-type-design.md@@ -0,0 +1,178 @@+# Showreel type++Five typography components taken from a code-built motion showreel: heavy+grotesk words that move on the beat against flat fields. Each one isolates a+single typographic trick from that reel and makes it reusable in any video.++| Component | Beat from the reel | Kind |+| --- | --- | --- |+| `selection-snap` | "FRAME" inside a design-tool selection | Entrance |+| `echo-stack` | "BOLD." on a drum of outline copies | Entrance + ambient drift |+| `type-wall` | A wall of "MOTION" rows | Sustained backdrop |+| `ring-text` | "TYPE IN MOTION" on a spinning 3D band | Sustained accent |+| `period-drop` | "CLAUDE." with a dropped period | End card |++## Shared decisions++- **DOM text, not glyph outlines.** Text stays text and the browser lays it+ out. The selection box in `selection-snap` is a wrapper around the word, so+ it follows the word's width while the weight grows. The dot in+ `period-drop` is an inline element after the word, so it lands where the+ word ends. Only three things are measured, with canvas `measureText` after+ the font has loaded: the final word size shown on the badge, the baseline+ inside a line box, and character advances around the ring.+- **Inter, variable.** `@remotion/google-fonts/Inter` serves one variable+ woff2 (`wght` 100–900) for every weight, so `font-variation-settings:+ "wght" N` gives continuous weight. `type-wall` also loads Anton for its+ narrow rows; neither the Google build of Inter nor Archivo has a `wdth`+ axis. Every component takes `fontFamily` to swap the face.+- **Units.** Sizes are reference px at a 720px-tall composition and scale by+ `unit = height / 720`, like `squiggle`.+- **Time.** `t = frame × 30 / fps × speed`, so the timelines below are in+ 30fps frames at `speed = 1`. Every component takes `speed`.+- **Pure timelines.** Each file exports pure `get…` functions of `t` that the+ component renders from and the tests assert against.+- **Colors.** Components paint no background. Defaults come from the house+ palette: text `#fafafa`, accent `#D97757`. The site previews use the+ reel's fields and accents (orange `#ff4d1a`, electric blue `#2b3bff`,+ lime `#d4ff1f`) through config defaults and `previewBackdrop`.+- **Case.** Sentence-case default text everywhere except `type-wall`, where+ a wall of capitals is the effect.++## selection-snap++A thin word sits in a loose viewfinder. The frame snaps tight around it as a+design-tool selection while the word goes from Thin to Black and takes the+accent color. Handles pop on, and a dimension badge counts up to the word's+size.++Timeline:++| Frames | Beat |+| --- | --- |+| 0–8 | Word (weight `fromWeight`) and four corner brackets fade in; brackets settle from 1.06× |+| 14–28 | Snap: padding goes from loose (1.1em × 0.9em) to tight (0.12em × 0) with a small overshoot, `Easing.bezier(0.34, 1.3, 0.64, 1)` |+| 14–30 | Weight `fromWeight → toWeight`, ease-in-out cubic |+| 18–30 | Color `color → accent` |+| 16–26 | Bracket arms grow along the edges until they meet: the frame becomes a 1px box |+| 24–32 | Eight handles pop in, corners first, 1-frame stagger |+| 24–32 | Badge pops in below the box: scale 0.6 → 1, 8px rise |+| 24–38 | Badge numbers count from the loose size to the tight size, ease-out cubic |++Length 38. The box is the word's wrapper (`display: inline-block`,+`line-height: 1`), so its width tracks the text at every weight. The badge+reads `W × H` in reference px; the final width is measured on canvas at+`toWeight`. Selection color defaults to `#0d99ff`.++Props: `text` ("Frame"), `fontSize` (150), `fontFamily`, `fromWeight` (100),+`toWeight` (900), `color`, `accent`, `selectionColor`, `badge` (true),+`speed`.++## echo-stack++The word lands in focus at the center while outline copies of it unfold above+and below and keep drifting vertically, like the one clear line on a spinning+drum.++- Main word: 0–14 blur 12px → 0, opacity 0 → 1, scale 1.04 → 1, ease-out+ cubic.+- Echo rows: `echoes` per side on a pitch of 1.05em. Every row is an outline+ copy, built from the filled glyphs by an SVG erode filter; a text stroke would draw the overlapping contours inside variable-font letters such as M and K. The column scrolls one+ pitch every `cycle` frames (60) in `direction`, wrapping seamlessly.+- Echo opacity is computed per row from its distance `d` to the center, in+ pitches: 0 below 0.55 (hidden behind the main word), up to 1 at 1, then+ down to 0 at `echoes + 0.5`, times `echoOpacity` (0.35).+- Unfold: 8–26 the pitch grows from 0.6 to 1 and the echo opacity ramps in.++Length 26; the drift continues after it.++Props: `text` ("Bold."), `fontSize` (170), `fontWeight` (800), `fontFamily`,+`color`, `echoColor`, `echoes` (3), `echoOpacity` (0.35), `strokeWidth`+(1.5), `direction` ("up"), `cycle` (60), `speed`.++## type-wall++Rows of one word fill the frame. Neighbors run in opposite directions at+different speeds, and the faces alternate: Inter Black, Anton, outline Inter.+The center row runs on an accent band.++- Rows are `fontSize` tall with no gap, laid out from the vertical center+ (row 0) outward until the frame is covered.+- Each row repeats `"TEXT · "` enough times to cover the width twice and+ loops by translating a whole number of tokens, in percent, so no width+ measurement is needed. Speed is in tokens per second: `0.22 ×` a seeded+ factor in `[0.7, 1.3]`. Even rows run left, odd rows run right.+- Outline rows use the same erode filter as `echo-stack`.+- Entrance: each row slides in from its own side, ease-out cubic over 20+ frames, staggered 2 frames per row away from the center. The accent band+ grows from the center over 6–20.++Length `sustained`.++Props: `text` ("MOTION"), `separator` ("·"), `fontSize` (64), `color`,+`accent`, `accentText`, `seed` (7), `speed`.++## ring-text++The text runs around a tilted band that spins. Each character is a panel+placed with `rotateY(θ) translateZ(R)`, and the band color is the panel+background. On the far side the letters read mirrored and the band darkens+with the cosine of its angle to the camera.++- `radius` (210 ref px) sets the ring. The text plus separator repeats as+ many times as fits the circumference, and the remainder is spread as+ letter spacing so the band closes without a seam. Advances are measured+ on canvas.+- Pose: `rotateZ(roll)` (−16°), `rotateX(−(tilt + wobble))` with `tilt` 38°+ and a 6° wobble over 150 frames, then `rotateY(−φ)`. The negative tilt+ views the ring from above, so the near side is at the bottom. Opacity sits+ on the perspective wrapper: on the preserve-3d ring it would flatten it.+ Only the letters dim on the far side; shading the band per panel shows the+ seams, and every panel bleeds 1.5px into its neighbors for the same reason.+- Spin: one turn per `period` frames (240). Entrance 0–30: scale 0.85 → 1,+ opacity in, and an extra 90° that decays with ease-out cubic, so the ring+ arrives spinning fast and settles to its cruise speed.++Length `sustained`.++Props: `text` ("Type in motion"), `separator` ("•"), `radius`, `fontSize`+(40), `fontWeight` (800), `fontFamily`, `color`, `band`, `tilt`, `roll`,+`period`, `speed`.++## period-drop++The word rises out of its baseline, then a colored dot falls from above the+frame, lands where the period goes, bounces twice with squash and stretch,+and settles as the period.++- Word: each letter rises from under a clip at its line box, 12 frames,+ ease-out quart, 2-frame stagger.+- Dot: an inline-block circle after the last letter, `dotSize` (0.2em),+ resting on the baseline.+- Fall from `0.62 × height` above the rest point, starting at frame 20,+ gravity-shaped over 12 frames. Bounces with restitution 0.35: the first+ lasts 8.4 frames and rises 12% of the drop, the second lasts 2.9 frames.+ The last touch is at 43.3.+- Stretch in flight with speed: `scaleY` up to 1.3. Impact squash decays over+ about 3 frames: `scaleX` up to 1.3, `scaleY` down to 0.78, origin bottom.+ Both are capped. This is past the 2–4% squash in the motion principles on+ purpose: the bounce is the effect, as with `speed-lines` (1.3 × 0.8).++Length 47: the last impact's squash has decayed below 0.5% there and snaps+to rest.++Props: `text` ("remocn"), `fontSize` (160), `fontWeight` (800),+`fontFamily`, `color`, `dotColor`, `dotSize`, `speed`.++## Integration++- Pages under `content/docs/typography/` with `component`, `vibe`, `length`,+ `useWhen`, `avoidWhen`; `avoidWhen` names existing replacements+ (`stretch-in`, `infinite-marquee`, `perspective-marquee`, `soft-blur-in`,+ `mask-reveal-up`, …). Added to `meta.json` and the typography index.+- `registry/remocn/registry.json` entries with `remotion` and+ `@remotion/google-fonts`; `registry/__index__.tsx` loaders; `config.ts`+ per component; tests in `__tests__`.+- One changelog entry for the five components.+- `bun run registry:build`, `bun run manifest:build`, tests, typecheck and+ lint; rendered frames checked before pushing.diff --git a/docs/plans/2026-09-25-speed-lines-design.md b/docs/plans/2026-09-25-speed-lines-design.mdnew file mode 100644index 00000000..5af2e5a4--- /dev/null+++ b/docs/plans/2026-09-25-speed-lines-design.md@@ -0,0 +1,304 @@+# Speed Lines++Direction: a flat motion accent in the Motion Graphics category+(`content/docs/motion-graphics/`), the first of the accents block with+`trim-burst` and `squiggle`. Accents are small, event-driven shape-layer+elements that get dropped many times per video: on an entrance, a landing, a+beat. Speed Lines has two modes.++- `trail` (default) wraps its children and flies them from `from` to `to` on a+ fast ease that arrives hard. Short parallel streaks shoot past behind the+ element. The element's real velocity drives them, so they exist only while it+ is fast and die as it lands.+- `focus` is a manga impact frame. Radial lines rush in from the frame edges,+ snap onto a point on the impact frame, hold for about five frames, then+ retract and vanish.++It pairs with `trim-burst`: streaks while the element flies, then a burst or a+focus frame where it lands. No text, images, fonts, glows, blur, or gradients.+It is clean vector with smooth motion, the counterpart of the hand-drawn+`ink-underline` and `ink-arrow`.++## Palette++One color, `color` (`#ffffff` by default), on a transparent background. Streaks,+rays and the fallback disc all use it. The component paints no background. The+docs preview puts it on flat International Klein Blue (`#002fa7`) via+`previewBackdrop`, the same field as `truchet-flip`. The docs examples use a+`<Backdrop>`.++## Props++| Prop | Default | Range | Meaning |+| --- | --- | --- | --- |+| `mode` | `trail` | `trail`, `focus` | Streaks behind a moving element, or an impact frame |+| `from` | `{ x: -0.25, y: 0.5 }` | any finite | Trail start of the element's center, as fractions of the composition (off-screen allowed) |+| `to` | `{ x, y }` | any finite | Trail landing point; falls back to the `x`, `y` point |+| `x`, `y` | 0.5, 0.5 | any finite | The accent point: where focus converges, and where trail lands without `to` |+| `count` | 12 | 1–64 | Streaks spawned per flight (trail) or rays (focus) |+| `weight` | 2 | 0.5–12 | Stroke width in reference px |+| `spread` | 96 | 8–480 | Width of the streak band (trail) or inner radius (focus), reference px |+| `duration` | 14 | 4–120 | Trail frames from launch to contact at 30 fps |+| `color` | `#ffffff` | color | Streaks, rays and fallback disc |+| `seed` | 1 | number | Streak timing, lanes and lengths; ray angles and radii |+| `delay` | 0 | ≥ 0 | Composition frames before the motion starts; not scaled by `speed` (same as `trim-burst` and `squiggle`) |+| `speed` | 1 | shared | Scales motion time; 0 freezes the first frame |++Reference px are px at a 720-px-tall composition, scaled by `height / 720` (the+`confetti` convention). The same props look the same at 720p, 1080p and 4K.+`from`, `to`, `x`, `y` are fractions of the composition.++Children are centered on the moving point in trail mode and on `x`, `y` in+focus mode. Without children, trail mode flies a disc of diameter `spread` in+`color`. This fallback keeps the preview self-contained, like `cursor-gravity`'s+default content. Focus mode draws no fallback.++## Timeline (30 fps, speed 1)++Time: `t = max(0, frame − delay) × 30 / fps × speed`. Everything below is in+`t`.++### Trail (default `duration` 14)++This is the original hard-stop landing, which is now `bounce={0}`. The current+default landing is in "Revision: inertial landing" at the end.++The element's center moves along `P(t) = from + (to − from) × ease(t)`. The+default flight goes from `(-0.25, 0.5)` to `(0.5, 0.5)`, 960 px at 1280×720.++| Frame | Progress | Speed (px/frame) | Beat |+| --- | --- | --- | --- |+| 0 | 0% | 0 | At `from`; no streaks |+| 1–4 | 1.3–17.4% | 12 → 68 | Launch; the first streaks appear once speed passes 5 |+| 5–10 | 25.7–74.0% | 80 → 96 → 90 | Cruise; the default disc enters the frame on 6; longest streaks around 8 |+| 11–13 | 82.6–96.0% | 82 → 57 | Braking; streaks visibly shorten |+| 14 | 100% | 39 | Contact (`impact`); streaks at ~40% of their cruise length |+| 15 | 101.1% | 11 | Recoil peak, 1.1% past the target; streaks die |+| 16–20 | 100.8% → 100% | −3 → 0 | Settles back exactly onto `to` (`end`) |++`speedLinesLength` is 20, the frame where trail settles at the default+duration. `getSpeedLinesTimeline({ duration })` returns `{ mode, impact, end }`.+For any duration, `impact` is `duration` (contact) and `end` is+`duration + 6`.++### Focus++| Frame | Beat |+| --- | --- |+| 0 | Nothing drawn |+| 0–3 | Rush: each ray starts at a seeded 0–1 frame offset. Its inner end runs in from the frame edge on an ease-in and accelerates into the snap |+| 3 | Impact (`impact`): every ray snaps to its inner radius, the closest point it ever reaches |+| 3–8 | Hold: inner ends relax outward by up to 12% (exponential, time constant 1.5 frames) |+| 8–13 | Retract: each ray releases at 8 plus a seeded 0–1.5 frames. Its inner end accelerates back out to the edge over 3.5 frames and the ray vanishes |+| 13 | Last ray gone (`end`) |++Take a horizontal ray at the default center with rest radius 96, rush start 0+and release 8. Its outer end sits at 642 (the 640 px edge plus the stroke+width), so its length per frame (px) is 0, 61, 243, 546, 540, 538, 536, 535,+535, 491, 360, 142, 0. `getSpeedLinesTimeline({ mode: "focus" })` is+`{ impact: 3, end: 13 }`. To land the snap on a beat, start the focus Sequence+`impact` frames before it.++### Preview++The preview adds a 24-frame hold: 44 frames for trail and 37 for focus.+`getSpeedLinesDuration({ mode, duration, delay, speed })` returns+`ceil(delay + (motion + 24) / speed)`. At speed 0 it returns 1.++## Signature motion++### Trail: the travel curve++`ease(t)` is one pure function of time, with `w = t / duration`:++- Flight (`w ≤ 1`): speed follows a skewed parabola, `v(w) = c·w·(1 − κw)`, so+ `ease = c(w²/2 − κw³/3)`. `κ = (1 + √0.7)/2 ≈ 0.9183` sets the contact speed+ to 30% of the peak (the hard arrival). `c ≈ 5.1576` normalizes `ease(1) = 1`.+ Peak speed is 1.40× the average, at `w ≈ 0.54`.+- Recoil (`0 < s = t − duration < 6`): a critically damped response carries the+ contact velocity past the target. It adds `(V₁/duration)·s·e^(−s)`, where+ `V₁ = c(1 − κ) ≈ 0.4212`. The peak comes at s = 1, 0.42/duration of the+ distance (1.1% at the default). A smoothstep taper over s = 3–6 lands it+ exactly on 1. Velocity is continuous at contact.++### Trail: velocity drives the streaks++- Velocity comes from the same `P(t)`, as a finite difference between this+ frame and the previous one:+ `V = (P(t(frame)) − P(t(frame − 1))) × fps / 30`. The unit is px per 1/30 s,+ so a higher `speed` means faster motion and longer streaks. Before the start,+ `P` clamps to `from`, so frame 0 has zero velocity.+- The direction is `d = unit(to − from)`, with normal `n = (−d.y, d.x)`. The+ forward speed is `s = V · d`. Recoil and settle move backward or barely at+ all, so they never draw streaks.+- Gate: `g = smoothstep((s − 5u) / (14u − 5u))`, with `u = height / 720`. Below+ 5 reference px/frame no streak exists. Above 14, length is exactly+ proportional to speed.+- Each streak `i` of `count` gets seeded values from `random("speed-lines-{seed}-{i}-…")`:+ - Spawn time, stratified over flight progress 4%–80% with jitter:+ `w_i = 0.04 + 0.76 (i + r) / count`.+ - Lane, a golden-ratio sequence with jitter across the band:+ `lane_i = frac(h + 0.618034 i + (r − 0.5) / (2·count))`, offset+ `o_i = spread·u·(lane_i − 0.5)`.+ Consecutive spawns land far apart, so the streaks never clump into a+ pattern.+ - Length factor `l_i ∈ [0.5, 1]` and setback `b_i ∈ [0, 0.35]·spread·u`+ behind the center, so the streak emerges from behind the element.+- Life is `max(3, 0.3 × duration)` frames (4.2 at the default); `a` is the+ age as a fraction of it.+ - Reach: `L = 1.6 · l_i · s · g`. That is the distance the element covers in+ 1.6 frames, a motion-blur shutter. It is proportional to the current speed.+ - Trim draw: the back end extends backward, ease-out quad over the first+ 40% of life.+ - Trim erase: the front end chases it backward, smoothstep over 35%–100%.+ - Drift: the streak slides back by 15% of the distance the element covered+ since the spawn. That is air rushing past.+ - Endpoints, measured behind the center along `−d` at lateral offset+ `o_i`: front `b_i + drift + L·erase(a)`, back `b_i + drift + L·draw(a)`.+- Streaks shorter than half the stroke width are dropped, so no dots are left.+ All streaks are parallel to `d`, behind the element, inside the band, and+ proportional to speed. When the element brakes, `s` falls, every reach+ shortens, and at contact plus one frame the gate closes. The streaks die with+ the motion. At cruise the default flight keeps about 4–5 streaks alive, with+ a reach of 77–154 px each.++### Focus: converge, snap, retract++Center `C = (x·W, y·H)`. Ray `i` of `count`:++- Angle: `θ_i = 2π (h + (i + 0.6 (r − 0.5)) / count)`, evenly spaced with ±30%+ jitter and a seeded rotation `h`.+- Rest radius: `r_i = spread·u·(1 + 0.6 r')`, 1.0–1.6× `spread`. Nothing is+ ever drawn closer to the point than `spread`.+- Outer radius: `R_i` is the distance from `C` to the frame boundary along+ `θ_i`, plus the stroke width, so the round cap stays off-screen. If `C` lies+ outside the frame, `R_i` is the distance to the farthest corner.+- Inner radius `ρ_i(t)`:+ - Rush: `R_i + (r_i − R_i) q²` for `t0_i ≤ t < 3`, with `t0_i ∈ [0, 1]`.+ - Hold: `r_i (1 + 0.12 (1 − e^(−(t − 3)/1.5)))`.+ - Retract: `ρ + (R_i − ρ) q²` from the release `8 + 1.5 r''`, over 3.5 frames.+- Each ray is the segment `C + [ρ_i, R_i]·(cos θ_i, sin θ_i)`. Rays meet only+ near the point and never cross it, so the shape reads as concentration lines,+ not a star.++## Rendering++- Root: `position: absolute; inset: 0; pointer-events: none`. It is+ transparent, with an optional `className`.+- One `<svg>` with `viewBox 0 0 W H` and `aria-hidden`. All streaks or rays are+ one `<path>` of `M … L …` subpaths, with `stroke = color`, `stroke-width =+ weight·u` and round caps. In trail mode without children, one `<circle>` for+ the fallback disc follows the path.+- Children sit in one absolutely positioned wrapper at the point, as a+ percentage of the box, translated by −50%/−50% so their center is on the+ point. They render after the SVG, so streaks pass behind them.+- Per frame: one path, at most one circle, one wrapper. Rays and streaks are+ capped at 64.++## Determinism++Every value derives from `useCurrentFrame()`, `useVideoConfig()`, props, and+remotion `random()` with string seeds. There is no React state, no memoized or+accumulated value, and no CSS animation. Velocity is a finite difference of the+pure position function, so any frame renders identically when seeked directly.++## Placing it over a scene++- As an entrance, put the element inside `SpeedLines` in a full-frame layer+ within the `Sequence` where the entrance starts. Set `from` off-screen and+ `to` at the resting place, and set `spread` to the element's size across the+ direction of travel. The element stays on `to` after the motion.+- For a landing, `getSpeedLinesTimeline({ duration }).impact` is the contact+ frame. Start a `focus` on the same point+ `getSpeedLinesTimeline({ mode: "focus" }).impact` frames earlier, so its lines+ snap on the contact. A `trim-burst` goes on the contact frame itself.+ - Set the focus `spread` to about the element's half-diagonal, so the rays+ stop short of it.+ - Render the focus layer before the element's layer, so its rays pass behind+ the element.++Files: `registry/remocn/speed-lines/index.tsx`, `config.ts`,+`__tests__/speed-lines.test.ts`, and+`content/docs/motion-graphics/speed-lines.mdx`. The lead integrates+registry.json, the preview index, the manifest, navigation, and the changelog+after the user approves the preview.++## Revision: inertial landing++Review feedback: in trail mode the element stopped dead. The 1.1% recoil read+as an abrupt stop, with no sense of momentum. The trail landing is now a damped+spring, and the element squashes and stretches with its motion. Two props+control this, `bounce` and `squash`, both 0–1 with a default of 0.5. Focus mode+is unchanged, and it ignores both props.++### The landing spring++- Flight: the curve keeps its form, `ease = c(w²/2 − κw³/3)`. The contact+ ratio now carries momentum: `L = 0.3 + 0.3·bounce` of the top speed, with+ `κ = (1 + √(1 − L))/2` and `c = 1/(1/2 − κ/3)`. That is 45% at the default.+- Landing, with `s = t − duration`:+ `ease = 1 + (V/duration)·(sin(ω_d s)/ω_d)·e^(−σs)·(1 − taper(s))`. Here+ `V = c(1 − κ)` is the contact velocity per unit of `w`, so velocity is+ continuous at contact. This is the impulse response of a damped spring+ started from the target at the arrival speed.+- Damping comes from the echo. The echo is the swing back past the target, and+ it is `r = 0.2·bounce` of the overshoot. With `δ = −ln r`, the damping ratio+ is `ζ = δ/√(π² + δ²)`, and `ζ = 1` when `bounce` is 0.+- The spring softens as `bounce` grows: `ω₀ = 1/(1 + 1.2·bounce)` rad per+ frame, `σ = ζω₀` and `ω_d = ω₀√(1 − ζ²)`.+- Settle: `settle = ceil(6/σ)`. A smoothstep over the second half tapers the+ tail to exactly 1, so the element comes to rest exactly on `to`, and+ `end = duration + settle`.+- At `bounce` 0: `L = 0.3`, `ζ = 1`, `ω₀ = 1` and `ω_d → 0`, so the landing term+ becomes `s·e^(−s)` with a taper over 3–6. That is the old curve exactly.++| `bounce` | Contact speed | Overshoot (960 px) | Peak | Echo | `end` |+| --- | --- | --- | --- | --- | --- |+| 0 | 30% | 10.6 px, 1.1% | 15.0 | none | 20 |+| 0.5 | 45% | 34.0 px, 3.5% | 15.9 | −3.4 px at 22.1 | 31 |+| 1 | 60% | 69.3 px, 7.2% | 16.7 | −13.9 px at 24.5 | 43 |++Frames are at the default `duration` of 14. The overshoot scales with the+arrival speed, so the same spring gives 8.3% at `duration` 6 and 1.2% at 40.+At the default, the element is visually at rest (under 0.5 px off) from frame+26. `speedLinesLength` is 31, and the preview is 55 frames.++### Squash and stretch++- Strain `ε` is the log of the scale along the path: `along = e^ε`,+ `across = e^(−ε)`. Their product is exactly 1, so the element keeps its area.+- `ε = S·tanh(q·k_s·v/S) − Q·tanh(q·k_q·p/Q)`, clamped to `[−Q, S]`:+ - `S = ln 1.3` and `Q = ln 1.25` are the caps: 1.3× stretch and 0.8× squash.+ - `q` is `squash`, `k_s = 0.007` and `k_q = 0.018`.+ - `v` is the speed, `|dP/dt|` in reference px per frame. It is a central+ difference of the same `ease`.+ - `p` is the distance past the target in reference px, `max(0, ease − 1)`+ times the flight length.+- For small speeds, `along ≈ 1 + q·k_s·v`, the linear smear. The stretch+ saturates smoothly at 1.3.+- The squash term is the spring's own displacement. It peaks with the+ overshoot and recovers exactly as the spring returns the element. It is+ one-sided, so the element never stretches while it stands still at the echo.+ Stretch only ever comes from real speed, so the landing reads as weight+ rather than rubber.+- Orientation: `θ = atan2(to − from)` in px. Children get+ `translate(-50%, -50%) rotate(θ) scale(along, across) rotate(−θ)` with+ `transform-origin: 50% 50%`. The fallback disc is an `<ellipse>` with radii+ `r·along` and `r·across`, rotated by `θ` about its center. Both deform about+ the moving center, so the element never slides off its path or its landing+ point.+- Default at 30 fps:+ - Cruise, frames 5–11: 1.25 × 0.80.+ - Contact, frame 14: 1.14.+ - Frame 15: 0.88.+ - Frame 16: 0.83 × 1.21. That is the squash peak, on the overshoot peak.+ - Round again by frame 20, and at most 1.015 on the swing back.++### Streaks through the landing++Velocity is still the finite difference of the same `P(t)`, so it now includes+the overshoot and the rebound. The gate is the speed gate times+`1 − smoothstep(t − duration)`, so streaks shrink over the frame after contact+and are gone from `duration + 1`. The rebound moves backward, where `s = V · d`+is negative, so it never draws streaks. The echo's second forward swing comes+after the contact gate has closed.diff --git a/docs/plans/2026-09-25-squiggle-design.md b/docs/plans/2026-09-25-squiggle-design.mdnew file mode 100644index 00000000..b512d918--- /dev/null+++ b/docs/plans/2026-09-25-squiggle-design.md@@ -0,0 +1,171 @@+# Squiggle++Direction: a live line accent from the Motion Graphics accents block, built+the way an After Effects shape layer is built: one stroked path, a trim-path+head and tail, and a wave modifier with animated phase and size. A flat+vector line draws itself along a straight course. It starts at `x, y` and+runs `length` px at `angle`. Its shape is a traveling wave, recomputed every+frame. The phase swims forward while the head extends, and the amplitude eases+from lively to calm. After a hold the tail can erase in the drawing direction,+or the line can stay. It underlines a word, separates two parts of a video,+connects two elements, or adds energy next to a number. It is the clean,+smooth counterpart of the hand-drawn `ink-underline` and `ink-arrow`. It has+no stop-motion poses, grain, or pressure taper.++## Palette++One color, `#ffffff` by default, on a transparent background. The component+paints no background and no fill, only a single stroke. The docs preview puts+it on flat International Klein Blue (`#002fa7`) via `previewBackdrop`. This is+the category's field, shared with `truchet-flip`, `trim-burst`, and+`speed-lines`. The docs examples use a `<Backdrop>`. There are no glows,+blurs, gradients, or sparkle shapes. Caps are round. Joins are round, except+on `zigzag`, which uses miter joins so the corners stay sharp.++## Controls++Every size is in reference px at a 720px-tall composition and scales by+`height / 720`, like `confetti`. Position is a 0..1 fraction of the+composition.++| Prop | Default | Range | Meaning |+| --- | --- | --- | --- |+| `shape` | `wave` | `wave`, `zigzag`, `loops`, `coil` | Smooth sine, sharp triangle, cursive loop chain, spring from the side |+| `x` | 0.375 | 0..1 | Start of the course, fraction of the width |+| `y` | 0.5 | 0..1 | Start of the course, fraction of the height |+| `length` | 320 | ≥ 0 | Straight course length, reference px |+| `angle` | 0 | degrees | Course direction; 0 runs right, positive turns clockwise |+| `amplitude` | 14 | ≥ 0 | Half-height of the band at the start of the draw, reference px |+| `wavelength` | 48 | ≥ 8 | Course distance of one cycle, reference px |+| `weight` | 3 | ≥ 0 | Stroke width, reference px |+| `color` | `#ffffff` | color | Stroke color |+| `settle` | 0.5 | 0..1 | Share of the amplitude that calms away; rest = `amplitude × (1 − settle)` |+| `hold` | 12 | ≥ 0 | Frames the settled line rests before the erase |+| `erase` | true | boolean | Tail erases toward the end point; false keeps the line |+| `delay` | 0 | ≥ 0 | Composition frames before the head leaves the start point |+| `speed` | 1 | shared | Scales motion time; 0 freezes at the first frame, nothing drawn |++`x` defaults to 0.375, not the family's 0.5. The course starts at `x, y`, so+the default 320px line spans 480–800 on a 1280×720 frame, centered. With+`x={0.5}` it would start at the center and fill only the right half.++## Timeline (30 fps, speed 1, defaults)++| Frames | Beat |+| --- | --- |+| 0 | Nothing drawn |+| 0–24 | Head runs out along arc length, ease-out quart: 15.7% on frame 1, 51.8% on 4, 80.2% on 8, 93.8% on 12, 98.8% on 16 |+| 0–36 | Swim: phase travels 1.5 cycles, ease-out cubic (1.06 cycles by frame 12). Calm: amplitude eases from 1 to 0.5 of `amplitude`, ease-in-out sine (0.875 at 12, 0.625 at 24) |+| 36–48 | `hold`: the settled line rests, perfectly still |+| 48–66 | Erase: the tail runs from the start to the end point, ease-in-out cubic, while the phase drifts another 0.5 cycle |+| 66 | Nothing drawn |+| 66–80 | Preview only: empty frames before the loop |++Constants: draw 24, settle 36, erase 18, swim 1.5 cycles, exit swim 0.5+cycles, preview tail 14 frames (24 when `erase` is off). The erase starts at+`36 + hold`. `squiggleLength` is 66, the frame where the tail reaches the end+point. With `erase={false}` the motion ends at 36 and the line stays.+`getSquiggleDuration({ speed, delay, hold, erase })` gives the preview length:+`ceil(delay + (end + tail) / speed)`, 80 by default and 60 without the erase.+Time is `max(0, frame − delay) × 30 / fps × speed`, so `delay` is in+composition frames and does not scale with `speed`. `hold` is a timeline beat+and does.++## Geometry++Course: `S = (x·W, y·H)`, direction `u = (cos a, sin a)`, normal+`n = (−sin a, cos a)`, which points down the screen at `a = 0`. The length is+`L = length · unit`, with `unit = H / 720`. The end point is `E = S + L·u`.+Wave number `k = 2π / λ`, phase angle `θ(s) = k·s − 2π·phase`.++Each point on the course, `s ∈ [0, L]`, is displaced by an offset along `u`+and across `n`. The offset is multiplied by an envelope+`w(s) = smoothstep(s / T) · smoothstep((L − s) / T)`, with taper+`T = min(λ, L / 3)`. Both ends therefore stay pinned to `S` and `E` and leave+along the course tangent, and the pattern grows out of the start and sinks+into the end as it travels.++- `wave`: across `c·sin θ`.+- `zigzag`: across `c·tri(θ)` with `tri = (2/π)·asin(sin θ)`. Built from exact+ corner vertices at `θ = π/2 + mπ`, enveloped at each corner, so every+ segment is straight and every corner sharp.+- `loops`: along `−r·sin θ`, across `−c·cos θ`, a prolate trochoid, which is+ the path of a point on a rolling wheel. `r = 2.4 / k`. The loops sit on+ the `−n` side, above a left-to-right line, with swoops between them. At the+ defaults a loop is 16 px wide and 21 px tall when lively, and 10.5 px tall at+ rest. Swimming phase makes the loops roll forward.+- `coil`: the same trochoid with `r = 4.2 / k`, the side projection of a+ tilted helix. The loops are about 42 px wide and nearly touch (6 px gap).+ Swimming phase reads as a spinning spring crawling forward, like a screw+ thread.++`c` is the current amplitude. For `loops` and `coil` the along reach `r` is+gated by `smoothstep(c / (3·unit))`. When the height calms to nothing, the+loops unfurl into a straight line instead of a path that doubles back on+itself, which would make the trim stutter.++Sampling: smooth shapes use 32 / 64 / 80 samples per cycle+(`wave` / `loops` / `coil`) × `max(1, unit)`, plus both end points. The grid+rides the phase: samples sit at fixed phase angles, `s = offset + j·step`+with `offset = (λ·phase) mod step`. Every crest is therefore drawn by the same+polygon on every frame and glides without faceting shimmer. There are at least+24 points and at most 4000. The zigzag uses about 2 points per cycle. At the+defaults the full path has about 215 (wave), 15 (zigzag), 430 (loops), or 535+(coil) points in one `<path>`. Coordinates are rounded to 0.01 px, and+consecutive duplicates are dropped.++Cusps: where the envelope carries `w·reach·k` through 1, a loop shrinks+through a cusp into the wave. This is the expected wave-to-loop transition.+It happens only in the taper zones near the pinned ends, where loops are born+and dissolve as the phase swims.++## Signature motion++The shape is recomputed from `phase(t)` and `c(t)` on every frame. It is+never a static path revealed by a dash offset.++- Head: `head(t) = 1 − (1 − t/24)^4` of the current total arc length. The+ visible path runs from `tail × total` to `head × total`, measured on the+ polyline and cut with interpolated end points. When the shape changes, the+ total changes with it, and the head stays on the curve, as AE Trim Paths+ would.+- Swim: `phase(t) = 1.5 · (1 − (1 − t/36)^3)` cycles, plus+ `0.5 · tail(t)` during the erase. Crests travel toward the head at about+ 6 px/frame at first. That is far slower than the head, which covers about+ 75 px of arc on frame 1 (477 px total at full amplitude). The head outruns+ the pattern, and the pattern visibly flows forward behind it. By frame 12,+ when 94% of the line is out, the crests have moved 1.06 wavelengths. After+ the head lands, the flow carries on and slows to a stop at frame 36. This is+ the follow-through.+- Calm: `c(t) = amplitude · unit · (1 − settle · (1 − cos(π·t/36)) / 2)`. The+ line is drawn at full energy and relaxes after it is out. There is no+ overshoot, and the amplitude only ever decreases.+- Erase: `tail(t) = easeInOutCubic((t − eraseStart) / 18)`, the same direction+ as the draw. The start end slides toward `E` while the pinned end stays. A+ line that stays (`erase={false}`) keeps its settled shape.+- Motion is never linear. The head is ease-out quart, the swim ease-out cubic,+ the calm ease-in-out sine, and the tail ease-in-out cubic.++Determinism: every value derives from `useCurrentFrame()`,+`useVideoConfig()`, and props. There is no randomness, so there is no seed.+Nothing accumulates between frames, so any frame renders correctly when+seeked to directly.++## Placement over a scene++The component is an overlay. Its root is `position: absolute; inset: 0`,+transparent, with `pointer-events: none`, and it holds one SVG whose viewBox is+the composition size. Drop it in a `<Sequence from={eventFrame}>` next to the+element it accents, so the head leaves the start point on the frame of the+click, the count landing, or the beat. Positions are fractions of the+composition: under a word whose box is at `left, top, width, height` px, use+`x = left / W`, `y = (top + height + gap) / H`, and+`length = width · 720 / H`. To link two elements, start at one, set+`angle = atan2(dy, dx)` in degrees, and use the distance as the length. Stagger+several accents inside one Sequence with `delay`. For an underline that should+stay, use `erase={false}`.++Files: `registry/remocn/squiggle/index.tsx`, `config.ts`,+`__tests__/squiggle.test.ts`, and `content/docs/motion-graphics/squiggle.mdx`.+The lead integrates registry.json, the preview index, the manifest,+navigation, and the changelog after the user approves the preview.diff --git a/docs/plans/2026-09-25-trim-burst-design.md b/docs/plans/2026-09-25-trim-burst-design.mdnew file mode 100644index 00000000..571ac8b5--- /dev/null+++ b/docs/plans/2026-09-25-trim-burst-design.md@@ -0,0 +1,195 @@+# Trim Burst++Direction: a punctuation accent built the way a motion designer builds a+shape-layer burst in After Effects. It is a ring of short straight strokes,+each animated with Trim Paths. The end (the outer point) shoots out and brakes+hard at its final distance. The start (the inner point) waits, then chases it.+The stroke grows, travels, and shrinks to nothing at its outer distance. The+whole burst lives 18 frames at 30 fps. Lengths, angles and launch times vary a+little per stroke from a seed, so the ring never reads as a rigid asterisk.++It opens the accents block of the Motion Graphics category+(`content/docs/motion-graphics/`), next to `speed-lines` and `squiggle`. Accents+are small, event-driven elements that get dropped many times per video: on a+click, a number landing, an icon appearing, a beat. They are not full-frame+stingers. No text, images, fonts, shaders, glows or sparkle shapes.++## Palette++One color, white (`#ffffff`) by default, on a transparent background. The+component paints no background and no full-frame fill. The docs preview puts+it on flat International Klein Blue (`#002fa7`) via `previewBackdrop`, the+same field as `truchet-flip`. The docs examples use a `<Backdrop>`. Strokes are+flat: no blur, glow, gradient or shadow.++## Shared accent conventions++- Overlay: the root is `position: absolute; inset: 0; pointer-events: none`+ and holds one SVG with `viewBox="0 0 width height"` from `useVideoConfig()`.+- Position: `x` and `y` are 0..1 fractions of the composition, like confetti's+ `originX` and `originY`. The default is 0.5, 0.5.+- Size: every size prop is in reference px at a 720px-tall composition and is+ multiplied by `unit = height / 720`. The same props look the same at 720p,+ 1080p and 4K.+- Timing: the motion starts at frame 0 of the enclosing `Sequence`. `delay`+ shifts it in composition frames. `speed` scales time. `trimBurstLength` is 18.+- Style: `color`, `weight` for the stroke width, round caps by default, `seed`+ for all randomness.++## Controls++| Prop | Default | Range | Meaning |+| --- | --- | --- | --- |+| `x` | 0.5 | fraction | Burst center, fraction of the composition width |+| `y` | 0.5 | fraction | Burst center, fraction of the composition height |+| `count` | 8 | 1–32, rounded | Number of strokes |+| `innerRadius` | 16 | ≥ 0 ref px | Distance from the center where strokes are born; set it just outside an element |+| `reach` | 64 | ≥ 0 ref px | How far each end travels from the inner radius |+| `strokeLength` | 56 | ≥ 1 ref px | Soft cap on the stroke length; below about 85% of `reach` strokes turn into traveling dashes |+| `weight` | 2 | 0.25–24 ref px | Stroke width |+| `rotation` | 0 | degrees | Direction of the first stroke, clockwise from 12 o'clock |+| `spread` | 360 | 0–360° | Full ring, or a fan of this angle centered on `rotation` |+| `jitter` | 0.5 | 0–1 | Amount of seeded variation in angle, length and launch time |+| `dots` | false | boolean | Adds a small dot beyond each tip that pops and shrinks |+| `cap` | `round` | `round`, `butt` | Stroke line cap |+| `color` | `#ffffff` | color | Stroke and dot color |+| `seed` | 1 | integer | Seeds the per-stroke variation |+| `delay` | 0 | frames | Composition frames to wait before the burst fires |+| `speed` | 1 | shared | Scales time; 0 never fires |++The docs customizer exposes all of them. Number controls carry+`hiddenFromList: false`. `speed` comes from the shared controls.++## Timeline (30 fps, speed 1, defaults)++Per stroke, in frames since that stroke's launch, for a stroke at full scale+(`reach` 64, `strokeLength` 56). Distances are measured from the inner radius.++| Frame | End | Start | Visible length | Beat |+| --- | --- | --- | --- | --- |+| 0 | 0 | 0 | 0 | Launch; nothing drawn |+| 1 | 23.0 | 0.0 | 23.0 | The end shoots out; the start holds |+| 2 | 38.5 | 0.6 | 37.9 | The stroke grows; the start still holds |+| 3 | 48.1 | 2.6 | 45.5 | The start's own curve begins |+| 4–6 | 54.1 → 60.1 | 5.5 → 12.0 | 48.6 → 49.2 → 48.1 | Travels near full length; the end brakes as the start picks up |+| 7–8 | 61.7 → 62.6 | 16.6 → 23.4 | 45.0 → 39.3 | The start gains on the braking end |+| 9–14 | 63.2 → 64.0 | 32.2 → 63.2 | 31.1 → 0.8 | The zip: the start races into the nearly still tip |+| 15 | 64 | 64 | 0 | Gone at the outer distance |++The start's velocity is one smooth hump: 0.6, 2.0, 2.8, 3.1, 3.4, 4.6 and 6.7+px per frame on frames 2 to 8, a top speed of about 9.5 px per frame near+frame 9.3, then down to 0.8 on frame 15. The stroke peaks at 49.2, 77% of the+reach, near frame 4.9.++Burst level: launches are spread over frames 0–3 (`6 × jitter`) in a seeded+order. The first strokes show on frame 1, and the last launch shows on frame+4. Strokes grow through about frame 7, run near full length between about+frames 4 and 9, and zip shut between about frames 7 and 18. The last stroke is+gone on frame 18. That is `trimBurstLength`. The docs preview holds the empty+frame for 24 more frames, so `durationInFrames` is 42.++`getTrimBurstTimeline({ jitter, count })` returns+`{ life: 15, lag: 3, stagger, length }` with `stagger = 6 × jitter` and+`length = life + stagger`. A single stroke (`count` 1) has no stagger.+`getTrimBurstDuration({ speed, jitter, count, delay })` returns the preview+length: `ceil(delay + length / speed) + 24`. The hold is not scaled by speed,+so fast previews still pause between bursts.++## Signature motion++Trim Paths with two independent curves per stroke, plus a soft leash that caps+the stroke length.++- End (outer point): `end(t) = reach × EXPO(t / 15)`, with EXPO the house+ ease-out `cubic-bezier(0.16, 1, 0.3, 1)`. It covers 36% of the reach after one+ frame and 60% after two, then decelerates hard and lands exactly on the reach+ at frame 15.+- Start (inner point), own curve: `own(t) = reach × IN_OUT((t − 3) / 12)`, with+ IN_OUT the smoother `cubic-bezier(0.45, 0, 0.55, 1)`. It stays at 0 until frame+ 3, then accelerates and lands on the reach at frame 15, the same frame as the+ end.+- Leash: the free gap `g = end − own` grows to about 85% of the reach near+ frame 4.9. A p-norm soft minimum caps the visible length at `strokeLength`:+ `length = g / (1 + (g / strokeLength)^6)^(1/6)` and `start = end − length`. The+ soft minimum is smooth, never exceeds `min(g, strokeLength)`, and reaches+ about 99% of `strokeLength` while `g` is well past it.+- The default keeps the leash off the signature. With `strokeLength` 56 on a+ `reach` of 64 (0.875) it only trims the peak, from 54.5 to 49.2. The start+ stays within 3 px of the inner radius through frame 3 and rides one smooth+ ease-in-out hump, so the preview shows the real two-curve chase. A first+ draft defaulted `strokeLength` to 32, half the reach. There the leash owned+ the middle of the motion: from frame 3 to 7 the start moved at the end's+ speed, a rigid dash sliding on one curve, which is the generic look this+ component exists to avoid.+- Below about 85% of the reach the leash takes over on purpose. The start is+ pulled along `strokeLength` behind the end, so the stroke travels as a dash+ on the end's curve until the start's own ease-in-out overtakes and zips it+ shut. A short stroke cannot cover a long reach any other way, so this stays+ an opt-in for short dashes rather than the default.+- Shrink: at frame 15 both curves are exactly 1, so the length is exactly 0 at+ the outer distance.+- Width: the drawn width is `min(weight, length)`. A round cap cannot leave a+ full-size dot behind as the stroke closes. It shrinks to a point instead.+ Segments shorter than 0.001px are not drawn.++The curves are pure functions of time. Nothing moves linearly, and the+end-start chase gives overlapping action inside every stroke. The seeded+launch spread gives overlapping action across the ring.++Per-stroke variation, all from remotion `random()` with string keys+`trim-burst-{seed}-{kind}-{index}`:++- Angle: the base angle is `rotation + i × 360 / count` for a full ring, or+ evenly across `spread` for a fan. It is offset by up to+ `±0.25 × jitter × step`, where `step` is the spacing, capped at 45°. That is+ ±5.6° at the defaults.+- Scale: `1 − 0.45 × jitter × r`. It multiplies both `reach` and+ `strokeLength`, so default strokes run 77.5–100% of full size and no stroke+ passes `innerRadius + reach`.+- Launch: strokes are ranked by a seeded key, and rank `k` launches at+ `6 × jitter × k / (count − 1)`. The first stroke launches at 0 and the last+ at exactly `6 × jitter`, so the timeline length is exact.++`jitter` 0 gives a perfectly regular ring that launches all at once.++Dots (optional): each stroke gets a dot of radius `1.25 × weight`. It sits on+the stroke's line, `2 × weight` past the end point plus its own radius, so it+rides just ahead of the tip. It pops from frame 4 with a back-out curve+(`s = 1.4`, a 7% overshoot, peak near frame 6.4) and is back to 1 at frame 8.+Then it shrinks with a cubic ease-in to exactly 0 at frame 15, in step with+the stroke closing. Dots never outlive the burst.++## Determinism++Every value derives from `useCurrentFrame()`, `useVideoConfig()`, props and+seeded `random()`. Time is `max(0, frame − delay) × 30 / fps × speed`, in+30 fps frames. The stroke layout (angles, scales, launches) is a pure function+of `count`, `rotation`, `spread`, `jitter` and `seed`, memoized on those props+only. Nothing accumulates between frames, so any frame renders correctly when+seeked directly.++## Geometry and rendering++The center is `(x × width, y × height)`. A stroke at angle `θ` (clockwise from+up) runs along `(sin θ, −cos θ)` from `innerRadius + start` to+`innerRadius + end`, all times `unit`. One `<g>` holds the `<line>` elements+with the stroke color and cap. A second `<g>` holds the dot `<circle>`s. The+defaults draw at most 8 lines per frame, and never more than 64 elements. The+SVG keeps `overflow: visible`, so a burst near an edge is clipped only by the+composition.++## Handoff and usage++Drop it into the `Sequence` that starts on the event frame, over the element+it punctuates. Set `x`/`y` to the element's center as fractions of the frame.+Set `innerRadius` just outside the element's radius in reference px, so strokes+are born at its edge. `trimBurstLength` can be the `Sequence` duration. Keep+the defaults for clicks and small beats. For an icon or a number landing, open+`innerRadius` and shorten `reach`. `spread` below 360 fans the strokes, for+example 90° above a number. `dots` adds a second beat at the tips. Drop+`strokeLength` well below `reach` only for short dashes that travel.++Files: `registry/remocn/trim-burst/index.tsx`, `config.ts`,+`__tests__/trim-burst.test.ts`, and `content/docs/motion-graphics/trim-burst.mdx`.+The lead integrates registry.json, the preview index, the manifest, navigation+and the changelog after the user approves the preview.diff --git a/docs/plans/2026-09-26-vector-type-design.md b/docs/plans/2026-09-26-vector-type-design.mdnew file mode 100644index 00000000..378d1119--- /dev/null+++ b/docs/plans/2026-09-26-vector-type-design.md@@ -0,0 +1,169 @@+# Vector type++Five typography components built the way a motion designer builds type in+After Effects: trim paths on glyph outlines, a font editor's points and+handles, striped type, text on a path, and a repeater. Two of them work on+real glyph contours; three are DOM text.++| Component | Technique | Source |+| --- | --- | --- |+| `outline-trace` | Trim path on every contour, then a fill wipe | Glyph outlines |+| `glyph-anatomy` | Anchors and Bézier handles pull the curves into shape | Glyph outlines |+| `stripe-type` | IBM-style bands slide in from alternating sides | DOM text |+| `path-ride` | Text rides a self-drawing curve, then straightens | DOM text |+| `type-repeater` | Repeater copies fan, spiral or tunnel out and collapse | DOM text |++## Shared decisions++- **Glyph outlines** come from `opentype.js` and a `fontUrl` (`.ttf`, `.otf`+ or `.woff`; not `.woff2`). The default is the static Inter 800 TTF from+ Google Fonts. Glyphs are looked up per character with `charToGlyph` and+ kerned with `getKerningValue`: `stringToGlyphs` and `getPath` run GSUB+ shaping, and Inter's contextual lookups make `opentype.js` throw. Render is+ held with `delayRender` until the file is parsed, like `stretch-in`.+- **DOM components** load Inter through `@remotion/google-fonts`, as in the+ showreel set.+- **Units and time.** Sizes are reference px at a 720px-tall composition,+ scaled by `height / 720`. `t = frame × 30 / fps × speed`.+- **Pure timelines** exported from each file and asserted by tests. Tests+ never touch the network: glyph math is tested on synthetic path commands.+- **Colors.** House palette defaults (`#fafafa`, accent `#D97757`, selection+ `#0d99ff`); the site previews use the reel's fields through config+ defaults and `previewBackdrop`. Sentence-case default text.++## outline-trace++Every contour draws itself as a stroke, letter by letter. When a letter's+outer contour closes, its fill wipes up from the bottom and the stroke fades+into it.++- Contours per glyph are split from the path commands. A contour whose+ bounding box sits inside another contour of the same glyph is a counter.+- Letter `i` starts at `i × stagger` (3). Outer contours draw over 18+ frames, counters start 4 frames later and draw over 14, ease-in-out cubic,+ via `stroke-dasharray` / `stroke-dashoffset` on the contour length.+- Fill: a clip rect rises over the glyph box from `start + 14` for 12+ frames, ease-out cubic. Unless `keepStroke`, the stroke fades over the same+ window, so the resting letters are the exact glyphs.+- `fill={false}` keeps the drawn outline only.+- Static instances of variable fonts keep overlapping contours (the bar of a+ t crosses its stem). Each letter's stroke is masked by its own fill eroded+ by half the stroke width, so strokes inside the silhouette never show.++Length for the default "Outline": `6 × 3 + 26 = 44`.++Props: `text`, `fontUrl`, `fontSize` (150), `color`, `strokeColor`,+`strokeWidth` (2.5), `stagger` (3), `fill` (true), `keepStroke` (false),+`speed`.++## glyph-anatomy++The word is built as in a font editor. Metric guides draw across, anchors+appear along each contour, handles grow out of them and pull the straight+segments into curves, then the glyph fills and the scaffolding fades.++- TrueType quadratics are converted to cubics+ (`c1 = p0 + ⅔(q − p0)`, `c2 = p2 + ⅔(q − p2)`), so handles read like Figma+ or Glyphs: each curve has one handle on each end.+- Handle position = `anchor + (target − anchor) × k`. At `k = 0` both handles+ sit on their anchors and the curve is its chord; `k` runs to 1 with a+ back-eased overshoot, per segment, staggered along the contour.+- Guides: baseline, x-height and cap height from the font's `OS/2` table,+ each a hairline drawn left to right with a small label.++Timeline, letter offset `o = 2i`:++| Frames | Beat |+| --- | --- |+| 0–12 | Guides draw in, 3 frames apart |+| 8+o – 22+o | Anchors pop along each contour in path order |+| 18+o – 40+o | Handles grow and pull the curves into shape |+| 40+o – 50+o | Fill fades in |+| 46+o – 58+o | Anchors, handles and guides fade out (unless `keepPoints`) |++Length for the default "Glyph": `58 + 8 = 66`.++Props: `text`, `fontUrl`, `fontSize` (200), `color`, `guideColor`,+`guides` (true), `keepPoints` (false), `speed`.++## stripe-type++The word is cut into horizontal bands with gaps, as in the IBM logo. Bands+slide in from alternating sides and lock into the word.++- Bands span the word's ink box (measured on canvas), not the line box.+ With `n` bands and gap share `g`, pitch `p = H / (n − g)` and band height+ `p (1 − g)`, so the first band starts at the ink top and the last ends at+ the ink bottom.+- Each band is a copy of the text clipped with `clip-path: inset()`.+- Entrance: band `k` enters from the left when even and the right when odd,+ 2 frames after band `k − 1`, over 16 frames with ease-out expo, from+ fully off the frame.+- `settle: "solid"` closes the gaps over the next 10 frames.+- `exit` lets the bands pass on through in the same staggered order after+ `hold` frames.++Length 30 for 8 bands (entrance); `getStripeTypeDuration` gives the preview.++Props: `text` ("Launch"), `fontSize` (180), `fontWeight` (800), `fontFamily`, `color`,+`stripes` (8), `gap` (0.35), `settle` ("striped"), `exit` (true), `hold`+(30), `speed`.++## path-ride++A line draws itself along a curve and the text rides behind its head,+each letter standing on the curve and turned to its tangent. Then the line+erases from its tail and the letters step off the curve onto a straight,+centered baseline.++- `path` is an SVG path in 1280×720 reference space, centered and scaled by+ `unit`. The default is an S-curve across the frame.+- Head: `L × easeInOutCubic(t / 40)`. Letter `j` sits at arc length+ `head − 0.3em − (T − c_j)`, where `T` is the text width and `c_j` the+ letter's center, so the last letter leads. Letters fade in over their+ first half-em on the curve.+- Letters stand on the curve: the baseline point is lifted along the normal+ by the line width plus 0.08em.+- Straighten: the path itself pulls taut over 50–68. Every point moves+ toward a straight baseline where arc length maps one to one onto x, and+ the tangent blends toward horizontal, so the line and the letters on it+ straighten together and the text keeps its spacing. (Moving each letter+ to its slot on its own made the word fall apart mid-move.) The path is+ sampled once (400 points) and the line is drawn as the pulled polyline.+ The tail erases over 52–70.++Length 70.++Props: `text`, `path`, `fontSize` (44), `fontWeight` (700), `fontFamily`,+`color`, `lineColor`, `lineWidth` (3), `speed`.++## type-repeater++An After Effects repeater on a word: copy `i` gets `i` steps of rotation and+scale. The copies unfold from the word, breathe, then collapse back into it.++- `mode`:+ - `tunnel` (default): `scale(1.2^(i × s))` around the center.+ - `spiral`: `rotate(i × 12° × s)`, `scale(1.1^(i × s))` around the center.+ - `fan`: `rotate(±⌈i/2⌉ × 11° × s)` to alternating sides around a pivot+ 2.6em below the word.+ Shrinking copies, as first drafted, hid behind the word or clumped into+ it; growing copies read as depth.+- Spread `s`: 10–34 from 0 to 1, back-eased; 34–70 breathes ±6%; 70–90+ back to 0, ease-in-out cubic.+- Copy 0 is the word in `color`; later copies step toward `accent` and fade+ with their index. `outline` draws the copies with the erode filter from+ `echo-stack`; it is on by default.++Length 90.++Props: `text`, `copies` (12), `mode`, `fontSize` (110), `fontWeight` (800),+`fontFamily`, `color`, `accent`, `outline` (true), `speed`.++## Integration++Pages in `content/docs/typography/`, `meta.json` and a "Vector type" section+on the typography index, `registry.json` entries (`opentype.js` and+`@remotion/paths` where used), preview loaders in `registry/__index__.tsx`,+a config and tests per component, one changelog entry, `registry:build`,+`manifest:build`, and rendered frames checked before pushing.diff --git a/lib/analytics.ts b/lib/analytics.tsindex 35bf1186..95b50c8e 100644--- a/lib/analytics.ts+++ b/lib/analytics.ts@@ -13,6 +13,7 @@ export type CtaId =| "hero_start"| "hero_showcases"| "hero_saas_typography_badge"+ | "hero_motion_graphics_badge"| "hero_templates_badge"| "how_it_works_setup"| "final_cta"diff --git a/registry-artifacts/agent-run.json b/registry-artifacts/agent-run.jsonnew file mode 100644index 00000000..53b60e75--- /dev/null+++ b/registry-artifacts/agent-run.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "agent-run",+ "title": "Agent Run",+ "description": "Animated brand-neutral AI agent run — a Thinking status and short plan, tool calls whose spinners close into checks while a timer counts real seconds, then a markdown answer with citations and a code block that streams in irregular token bursts. Light/dark themes.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/agent-run/index.tsx",+ "content": "\"use client\";\n\nimport { type CSSProperties, useMemo } from \"react\";\nimport { Easing, random, useCurrentFrame, useVideoConfig } from \"remotion\";\n\nexport type AgentRunTheme = \"light\" | \"dark\";\n\nexport type AgentRunIcon =\n | \"chart\"\n | \"database\"\n | \"search\"\n | \"book\"\n | \"globe\"\n | \"terminal\"\n | \"file\";\n\nexport interface AgentRunStep {\n name: string;\n detail?: string;\n duration: number;\n icon?: AgentRunIcon;\n sources?: readonly string[];\n}\n\nexport interface AgentRunScript {\n title?: string;\n prompt: string;\n plan?: readonly string[];\n steps?: readonly AgentRunStep[];\n answer: string;\n}\n\nexport interface AgentRunProps {\n run?: AgentRunScript;\n theme?: AgentRunTheme;\n accentColor?: string;\n compression?: number;\n seed?: number;\n speed?: number;\n className?: string;\n}\n\nexport interface AgentRunOptions {\n seed?: number;\n compression?: number;\n width?: number;\n height?: number;\n}\n\nexport interface AgentRunPlayback {\n fps?: number;\n speed?: number;\n}\n\nexport const defaultAgentRun: AgentRunScript = {\n title: \"Checkout conversion drop\",\n prompt: \"Why did checkout conversion drop last week?\",\n plan: [\n \"Compare the checkout funnel with the week before\",\n \"Break the drop down by browser and step\",\n \"Check what shipped and what the error logs say\",\n ],\n steps: [\n {\n icon: \"chart\",\n name: \"Query analytics\",\n detail: \"checkout funnel, last 7 days vs prior 7\",\n duration: 1.4,\n },\n {\n icon: \"database\",\n name: \"Run SQL\",\n detail: \"conversion by browser and step\",\n duration: 2.3,\n },\n {\n icon: \"search\",\n name: \"Search logs\",\n detail: \"Apple Pay errors on Safari\",\n duration: 1.1,\n },\n {\n icon: \"book\",\n name: \"Read 12 sources\",\n duration: 3.2,\n sources: [\n \"Checkout funnel\",\n \"Browser report\",\n \"Release 4.12\",\n \"PR #2186\",\n \"webkit.org\",\n \"developer.mozilla.org\",\n \"Payments runbook\",\n \"Error log\",\n \"Incident notes\",\n \"Apple Pay guide\",\n \"Support tickets\",\n \"Status page\",\n ],\n },\n ],\n answer: [\n \"## Apple Pay broke on Safari in release 4.12\",\n \"\",\n \"Checkout conversion fell from 3.4% to 2.7% last week, a 21% drop [1]. All of it comes from the payment step on Safari, 41% of checkouts [2].\",\n \"\",\n \"- Safari conversion halved, from 3.5% to 1.8%\",\n \"- Chrome and Firefox held steady at 3.3%\",\n '- 4.12 moved the card form into an iframe without `allow=\"payment\"` [3]',\n \"\",\n \"```tsx\",\n \"<iframe\",\n \" src={cardFormUrl}\",\n ' allow=\"payment\"',\n \"/>\",\n \"```\",\n \"\",\n \"**Fix:** add the attribute and ship 4.12.1 today.\",\n ].join(\"\\n\"),\n};\n\nexport const agentRunDefaults: Required<Omit<AgentRunProps, \"className\">> = {\n run: defaultAgentRun,\n theme: \"light\",\n accentColor: \"#2563eb\",\n compression: 3,\n seed: 1,\n speed: 1,\n};\n\nconst PANEL_IN = 14;\nconst PANEL_RISE = 14;\nconst BUBBLE_AT = 4;\nconst BUBBLE_IN = 10;\nconst BUBBLE_RISE = 8;\nconst RUN_START = 16;\nconst STATUS_IN = 6;\nconst THINK_LEAD = 14;\nconst THINK_TAIL = 8;\nconst SWAP = 8;\nconst SWAP_RISE = 4;\nconst TOOL_GAP = 5;\nconst TOOL_MIN = 12;\nconst TOOL_MAX = 120;\nconst ANSWER_GAP = 8;\nconst ROW_IN = 8;\nconst ROW_FADE = 6;\nconst LABEL_DELAY = 2;\nconst LABEL_FADE = 6;\nconst SPIN = 12;\nconst ARC = 0.28;\nconst RESOLVE = 8;\nconst CHECK_FROM = 3;\nconst CHECK_TO = 10;\nconst CHIP_LEAD = 4;\nconst CHIP_SPAN = 0.7;\nconst FADE = 5;\nconst MORPH = 8;\nconst POP = 8;\nconst CODE_OPEN = 8;\nconst LINE_GROW = 5;\nconst SCROLL = 24;\nconst SCROLL_LEAD = 16;\nconst SETTLE = 16;\nconst HOLD = 45;\nconst SHIMMER_PERIOD = 30;\nconst SHIMMER_BAND = 3;\nconst SHIMMER_BASE = 0.45;\nconst DOT_BACK = 1.7;\nconst CITE_BACK = 2;\nconst CHIP_BACK = 1.7;\nconst MIN_COMPRESSION = 0.25;\nconst MAX_COMPRESSION = 20;\n\nconst SIZE_WEIGHTS = [8, 16, 22, 22, 17, 15];\nconst GAP_WEIGHTS = [42, 33, 16, 9];\nconst PAUSE_CHANCE = 0.06;\nconst PAUSE_MIN = 4;\nconst PAUSE_SPREAD = 4;\nconst BLOCK_MIN = 2;\nconst BLOCK_SPREAD = 3;\n\nconst REF_HEIGHT = 720;\nconst PANEL_W = 800;\nconst MARGIN_X = 40;\nconst MARGIN_Y = 40;\nconst MIN_PANEL_H = 360;\nconst MAX_PANEL_H = 960;\nconst HEADER_H = 48;\nconst PAD_X = 32;\nconst PAD_TOP = 24;\nconst SAFE = 40;\nconst COLUMN = PANEL_W - 2 * PAD_X;\nconst MEASURE = 680;\nconst BODY_SIZE = 16;\nconst BODY_LINE = 26;\nconst BUBBLE_SIZE = 16;\nconst BUBBLE_LINE = 24;\nconst BUBBLE_PAD_Y = 10;\nconst BUBBLE_PAD_X = 16;\nconst BUBBLE_WIDTH = 520;\nconst BUBBLE_GAP = 22;\nconst STATUS_H = 22;\nconst STATUS_GAP = 10;\nconst PLAN_SIZE = 15;\nconst PLAN_LINE = 24;\nconst PLAN_GAP = 4;\nconst PLAN_INDENT = 36;\nconst PLAN_WIDTH = 640;\nconst PLAN_AFTER = 20;\nconst ROW_H = 40;\nconst CHIPS_H = 34;\nconst TOOLS_AFTER = 24;\nconst ITEM_INDENT = 22;\nconst ITEM_GAP = 4;\nconst BLOCK_GAP = 12;\nconst HEADING_GAP = 8;\nconst CODE_GAP = 14;\nconst CODE_SIZE = 14;\nconst CODE_LINE = 22;\nconst CODE_HEAD = 34;\nconst CODE_PAD = 10;\nconst CHIP_SIZE = 12.5;\nconst CHIP_GAP = 6;\nconst CHIP_MAX = 6;\nconst CHIP_ROOM = COLUMN - 2 - 40 - 14;\nconst CIRCLE = 2 * Math.PI * 10;\nconst CHECK_LENGTH = 6 * Math.SQRT2;\n\nconst HEADINGS: Record<1 | 2, { size: number; line: number }> = {\n 1: { size: 22, line: 32 },\n 2: { size: 20, line: 30 },\n};\n\nconst SANS =\n 'Inter, \"Geist\", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif';\nconst MONO =\n '\"JetBrains Mono\", \"Geist Mono\", ui-monospace, SFMono-Regular, Menlo, Consolas, \"Liberation Mono\", monospace';\n\nconst EXPO = Easing.bezier(0.16, 1, 0.3, 1);\n\nconst finite = (value: number | undefined, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst progress = (value: number) =>\n Number.isNaN(value) ? 0 : clamp(value, 0, 1);\nconst round = (value: number) => Math.round(value * 1000) / 1000;\nconst expo = (value: number) => EXPO(progress(value));\nconst easeOut = (value: number) => 1 - (1 - progress(value)) ** 3;\nconst smoothstep = (value: number) => {\n const t = progress(value);\n return t * t * (3 - 2 * t);\n};\nconst backOut = (value: number, overshoot: number) => {\n const t = progress(value) - 1;\n return 1 + (overshoot + 1) * t ** 3 + overshoot * t ** 2;\n};\nconst rateOf = (speed: number | undefined) =>\n Math.max(0, finite(speed, agentRunDefaults.speed));\nconst seedOf = (seed: number | undefined) =>\n finite(seed, agentRunDefaults.seed);\nconst compressionOf = (compression: number | undefined) =>\n clamp(\n finite(compression, agentRunDefaults.compression),\n MIN_COMPRESSION,\n MAX_COMPRESSION,\n );\n\nexport function formatAgentRunSeconds(seconds: number) {\n const value = Math.max(0, finite(seconds, 0));\n if (value < 60) return `${value.toFixed(1)}s`;\n const minutes = Math.floor(value / 60);\n const rest = Math.floor(value - minutes * 60);\n return `${minutes}m ${String(rest).padStart(2, \"0\")}s`;\n}\n\nconst isLetter = (code: number) =>\n (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code >= 192;\nconst isDigit = (code: number) => code >= 48 && code <= 57;\n\nexport function tokenizeAgentRun(text: string): number[] {\n const ends: number[] = [];\n let index = 0;\n while (index < text.length) {\n if (text[index] === \"\\n\") {\n index += 1;\n ends.push(index);\n continue;\n }\n while (\n index < text.length &&\n (text[index] === \" \" || text[index] === \"\\t\")\n ) {\n index += 1;\n }\n if (index < text.length && text[index] !== \"\\n\") {\n const code = text.charCodeAt(index);\n if (isLetter(code)) {\n while (index < text.length && isLetter(text.charCodeAt(index))) {\n index += 1;\n }\n } else if (isDigit(code)) {\n const stop = Math.min(text.length, index + 3);\n while (index < stop && isDigit(text.charCodeAt(index))) {\n index += 1;\n }\n } else {\n index += 1;\n }\n }\n ends.push(index);\n }\n return ends;\n}\n\nexport interface AgentRunChunk {\n index: number;\n at: number;\n start: number;\n end: number;\n tokens: number;\n block: boolean;\n}\n\nfunction pick(weights: readonly number[], value: number) {\n const total = weights.reduce((sum, weight) => sum + weight, 0);\n let cursor = value * total;\n for (const [index, weight] of weights.entries()) {\n if (cursor < weight) return index;\n cursor -= weight;\n }\n return weights.length - 1;\n}\n\nexport function getAgentRunChunks(\n text: string,\n seed = agentRunDefaults.seed,\n stream = \"answer\",\n): AgentRunChunk[] {\n const ends = tokenizeAgentRun(text);\n const startOf = (token: number) => (token > 0 ? ends[token - 1] : 0);\n const isNewline = (token: number) =>\n token < ends.length && text[startOf(token)] === \"\\n\";\n const key = `agent-run-${seedOf(seed)}-${stream}`;\n const chunks: AgentRunChunk[] = [];\n let token = 0;\n let at = 0;\n let block = false;\n while (token < ends.length) {\n const index = chunks.length;\n const size = pick(SIZE_WEIGHTS, random(`${key}-size-${index}`)) + 1;\n let stop = Math.min(ends.length, token + size);\n let cut = false;\n for (let cursor = token; cursor < stop; cursor++) {\n if (isNewline(cursor) && isNewline(cursor + 1)) {\n stop = cursor + 2;\n cut = true;\n break;\n }\n }\n if (!cut && isNewline(stop - 1) && isNewline(stop)) {\n stop += 1;\n cut = true;\n }\n while (cut && isNewline(stop)) stop += 1;\n if (index > 0) {\n at += pick(GAP_WEIGHTS, random(`${key}-gap-${index}`)) + 1;\n if (random(`${key}-pause-${index}`) < PAUSE_CHANCE) {\n const hold = random(`${key}-hold-${index}`) * PAUSE_SPREAD;\n at += PAUSE_MIN + Math.floor(hold);\n }\n if (block) {\n const extra = random(`${key}-block-${index}`) * BLOCK_SPREAD;\n at += BLOCK_MIN + Math.floor(extra);\n }\n }\n chunks.push({\n index,\n at,\n start: startOf(token),\n end: ends[stop - 1],\n tokens: stop - token,\n block,\n });\n block = cut;\n token = stop;\n }\n return chunks;\n}\n\nfunction lastArrival(chunks: readonly AgentRunChunk[]) {\n return chunks.length > 0 ? chunks[chunks.length - 1].at : 0;\n}\n\nfunction chunkIndexAt(chunks: readonly AgentRunChunk[], offset: number) {\n let low = 0;\n let high = chunks.length - 1;\n let found = chunks.length;\n while (low <= high) {\n const middle = (low + high) >> 1;\n if (chunks[middle].end > offset) {\n found = middle;\n high = middle - 1;\n } else {\n low = middle + 1;\n }\n }\n return found;\n}\n\nexport function getAgentRunArrival(\n chunks: readonly AgentRunChunk[],\n offset: number,\n) {\n const index = chunkIndexAt(chunks, offset);\n return index < chunks.length ? chunks[index].at : Number.POSITIVE_INFINITY;\n}\n\nexport function getAgentRunReveal(\n chunks: readonly AgentRunChunk[],\n local: number,\n) {\n let low = 0;\n let high = chunks.length - 1;\n let revealed = 0;\n while (low <= high) {\n const middle = (low + high) >> 1;\n if (chunks[middle].at <= local) {\n revealed = chunks[middle].end;\n low = middle + 1;\n } else {\n high = middle - 1;\n }\n }\n return revealed;\n}\n\nexport type AgentRunInlineKind = \"text\" | \"bold\" | \"code\" | \"cite\";\n\nexport interface AgentRunInline {\n kind: AgentRunInlineKind;\n text: string;\n raw: number;\n end: number;\n}\n\nexport interface AgentRunCodeLine {\n text: string;\n raw: number;\n}\n\nexport type AgentRunBlock =\n | {\n kind: \"heading\";\n level: 1 | 2;\n raw: number;\n body: number;\n end: number;\n inline: AgentRunInline[];\n }\n | { kind: \"paragraph\"; raw: number; end: number; inline: AgentRunInline[] }\n | {\n kind: \"item\";\n raw: number;\n body: number;\n end: number;\n inline: AgentRunInline[];\n }\n | {\n kind: \"code\";\n raw: number;\n open: number;\n end: number;\n lang: string;\n langRaw: number;\n lines: AgentRunCodeLine[];\n };\n\nfunction parseInline(source: string, base: number): AgentRunInline[] {\n const out: AgentRunInline[] = [];\n let text = \"\";\n let textStart = 0;\n const flush = (at: number) => {\n if (text.length > 0) {\n out.push({ kind: \"text\", text, raw: base + textStart, end: base + at });\n }\n text = \"\";\n };\n let index = 0;\n while (index < source.length) {\n if (source.startsWith(\"**\", index)) {\n const close = source.indexOf(\"**\", index + 2);\n if (close > index + 2) {\n flush(index);\n out.push({\n kind: \"bold\",\n text: source.slice(index + 2, close),\n raw: base + index + 2,\n end: base + close + 2,\n });\n index = close + 2;\n textStart = index;\n continue;\n }\n }\n if (source[index] === \"`\") {\n const close = source.indexOf(\"`\", index + 1);\n if (close > index + 1) {\n flush(index);\n out.push({\n kind: \"code\",\n text: source.slice(index + 1, close),\n raw: base + index + 1,\n end: base + close + 1,\n });\n index = close + 1;\n textStart = index;\n continue;\n }\n }\n if (source[index] === \"[\") {\n const match = /^\\[(\\d{1,3})\\]/.exec(source.slice(index));\n if (match) {\n flush(index);\n out.push({\n kind: \"cite\",\n text: match[1],\n raw: base + index,\n end: base + index + match[0].length,\n });\n index += match[0].length;\n textStart = index;\n continue;\n }\n }\n if (text.length === 0) textStart = index;\n text += source[index];\n index += 1;\n }\n flush(index);\n return out;\n}\n\nconst HEADING_LINE = /^(#{1,3})[ \\t]+(.*)$/;\nconst ITEM_LINE = /^[-*][ \\t]+(.*)$/;\n\nfunction isStructural(line: string) {\n return (\n line.startsWith(\"```\") || HEADING_LINE.test(line) || ITEM_LINE.test(line)\n );\n}\n\nexport function parseAgentRunMarkdown(markdown: string): AgentRunBlock[] {\n const lines: AgentRunCodeLine[] = [];\n let offset = 0;\n for (const text of markdown.split(\"\\n\")) {\n lines.push({ text, raw: offset });\n offset += text.length + 1;\n }\n const blocks: AgentRunBlock[] = [];\n let index = 0;\n while (index < lines.length) {\n const line = lines[index];\n if (line.text.trim() === \"\") {\n index += 1;\n continue;\n }\n if (line.text.startsWith(\"```\")) {\n const rest = line.text.slice(3);\n const body: AgentRunCodeLine[] = [];\n let cursor = index + 1;\n while (cursor < lines.length && !lines[cursor].text.startsWith(\"```\")) {\n body.push(lines[cursor]);\n cursor += 1;\n }\n const closed = cursor < lines.length;\n const last = closed ? lines[cursor] : (body[body.length - 1] ?? line);\n blocks.push({\n kind: \"code\",\n raw: line.raw,\n open: line.raw + 3,\n end: last.raw + last.text.length,\n lang: rest.trim(),\n langRaw: line.raw + 3 + (rest.length - rest.trimStart().length),\n lines: body,\n });\n index = closed ? cursor + 1 : cursor;\n continue;\n }\n const heading = HEADING_LINE.exec(line.text);\n if (heading) {\n const body = line.raw + line.text.length - heading[2].length;\n blocks.push({\n kind: \"heading\",\n level: heading[1].length === 1 ? 1 : 2,\n raw: line.raw,\n body,\n end: line.raw + line.text.length,\n inline: parseInline(heading[2], body),\n });\n index += 1;\n continue;\n }\n const item = ITEM_LINE.exec(line.text);\n if (item) {\n const body = line.raw + line.text.length - item[1].length;\n blocks.push({\n kind: \"item\",\n raw: line.raw,\n body,\n end: line.raw + line.text.length,\n inline: parseInline(item[1], body),\n });\n index += 1;\n continue;\n }\n let cursor = index;\n while (\n cursor < lines.length &&\n lines[cursor].text.trim() !== \"\" &&\n (cursor === index || !isStructural(lines[cursor].text))\n ) {\n cursor += 1;\n }\n const last = lines[cursor - 1];\n const end = last.raw + last.text.length;\n const source = markdown.slice(line.raw, end).replace(/\\n/g, \" \");\n blocks.push({\n kind: \"paragraph\",\n raw: line.raw,\n end,\n inline: parseInline(source, line.raw),\n });\n index = cursor;\n }\n return blocks;\n}\n\nconst NARROW = \" .,:;'!|iljI`\";\nconst THIN = \"ftr()[]{}/\\\\-\";\nconst SYMBOL = \"<>=+~#$&→\";\nconst WIDE = \"mw…\";\nconst WIDEST = \"MW@%—\";\n\nfunction charWidth(char: string) {\n if (NARROW.includes(char)) return 0.3;\n if (THIN.includes(char)) return 0.44;\n if (WIDEST.includes(char)) return 1;\n if (WIDE.includes(char)) return 0.9;\n if (SYMBOL.includes(char)) return 0.68;\n if (char >= \"0\" && char <= \"9\") return 0.66;\n if (char >= \"A\" && char <= \"Z\") return 0.74;\n return 0.62;\n}\n\nexport function estimateAgentRunWidth(\n text: string,\n size: number,\n mono = false,\n) {\n let em = 0;\n for (const char of text) em += mono ? 0.6 : charWidth(char);\n return em * size;\n}\n\nexport type AgentRunPieceKind =\n | AgentRunInlineKind\n | \"punct\"\n | \"string\"\n | \"comment\";\n\nexport interface AgentRunPiece {\n kind: AgentRunPieceKind;\n text: string;\n raw: number;\n end: number;\n}\n\nexport interface AgentRunTextLine {\n y: number;\n height: number;\n raw: number;\n pieces: AgentRunPiece[];\n}\n\nfunction pieceWidth(piece: AgentRunPiece, size: number) {\n if (piece.kind === \"cite\") {\n return 20 + 7 * Math.max(0, piece.text.length - 1);\n }\n if (piece.kind === \"code\") {\n return estimateAgentRunWidth(piece.text, size * 0.875, true) + 10;\n }\n return estimateAgentRunWidth(piece.text, size);\n}\n\ninterface Atom {\n pieces: AgentRunPiece[];\n width: number;\n space: boolean;\n}\n\nfunction atomsOf(inline: readonly AgentRunInline[], size: number): Atom[] {\n const atoms: Atom[] = [];\n let word: AgentRunPiece[] = [];\n let wordWidth = 0;\n const add = (piece: AgentRunPiece) => {\n word.push(piece);\n wordWidth += pieceWidth(piece, size);\n };\n const close = () => {\n if (word.length > 0) {\n atoms.push({ pieces: word, width: wordWidth, space: false });\n }\n word = [];\n wordWidth = 0;\n };\n for (const segment of inline) {\n if (segment.kind === \"cite\" || segment.kind === \"code\") {\n add({ ...segment });\n continue;\n }\n let index = 0;\n while (index < segment.text.length) {\n const space = segment.text[index] === \" \";\n let stop = index;\n while (\n stop < segment.text.length &&\n (segment.text[stop] === \" \") === space\n ) {\n stop += 1;\n }\n const piece: AgentRunPiece = {\n kind: segment.kind,\n text: segment.text.slice(index, stop),\n raw: segment.raw + index,\n end: segment.raw + stop,\n };\n if (space) {\n close();\n atoms.push({\n pieces: [piece],\n width: pieceWidth(piece, size),\n space: true,\n });\n } else {\n add(piece);\n }\n index = stop;\n }\n }\n close();\n return atoms;\n}\n\nfunction mergePieces(pieces: readonly AgentRunPiece[]) {\n const merged: AgentRunPiece[] = [];\n for (const piece of pieces) {\n const last = merged.at(-1);\n const text = piece.kind === \"text\" || piece.kind === \"bold\";\n if (text && last?.kind === piece.kind && last.end === piece.raw) {\n merged[merged.length - 1] = {\n ...last,\n text: last.text + piece.text,\n end: piece.end,\n };\n } else {\n merged.push({ ...piece });\n }\n }\n return merged;\n}\n\nexport function wrapAgentRunInline(\n inline: readonly AgentRunInline[],\n size: number,\n maxWidth: number,\n): AgentRunPiece[][] {\n const lines: AgentRunPiece[][] = [];\n let line: AgentRunPiece[] = [];\n let width = 0;\n let pending: Atom | undefined;\n for (const atom of atomsOf(inline, size)) {\n if (atom.space) {\n if (line.length > 0) pending = atom;\n continue;\n }\n const gap = pending ? pending.width : 0;\n if (line.length > 0 && width + gap + atom.width > maxWidth) {\n lines.push(line);\n line = [...atom.pieces];\n width = atom.width;\n } else {\n if (pending && line.length > 0) {\n line.push(...pending.pieces);\n width += gap;\n }\n line.push(...atom.pieces);\n width += atom.width;\n }\n pending = undefined;\n }\n if (line.length > 0) lines.push(line);\n return lines.map(mergePieces);\n}\n\nfunction plainInline(text: string, raw: number): AgentRunInline[] {\n return text.length > 0\n ? [{ kind: \"text\", text, raw, end: raw + text.length }]\n : [];\n}\n\nfunction textLines(\n pieces: AgentRunPiece[][],\n lineHeight: number,\n raw: number,\n): AgentRunTextLine[] {\n if (pieces.length === 0) {\n return [{ y: 0, height: lineHeight, raw, pieces: [] }];\n }\n return pieces.map((line, index) => ({\n y: index * lineHeight,\n height: lineHeight,\n raw: line[0]?.raw ?? raw,\n pieces: line,\n }));\n}\n\nconst PUNCT = \"<>{}()[]/=;,.:+-*&|!?\";\n\nexport function getAgentRunCodePieces(line: AgentRunCodeLine): AgentRunPiece[] {\n const pieces: AgentRunPiece[] = [];\n const push = (kind: AgentRunPieceKind, from: number, to: number) => {\n if (to <= from) return;\n const last = pieces.at(-1);\n if (last?.kind === kind && last.end === line.raw + from) {\n pieces[pieces.length - 1] = {\n ...last,\n text: last.text + line.text.slice(from, to),\n end: line.raw + to,\n };\n return;\n }\n pieces.push({\n kind,\n text: line.text.slice(from, to),\n raw: line.raw + from,\n end: line.raw + to,\n });\n };\n let index = 0;\n while (index < line.text.length) {\n const char = line.text[index];\n if (line.text.startsWith(\"//\", index)) {\n push(\"comment\", index, line.text.length);\n break;\n }\n if (char === '\"' || char === \"'\" || char === \"`\") {\n const close = line.text.indexOf(char, index + 1);\n const stop = close === -1 ? line.text.length : close + 1;\n push(\"string\", index, stop);\n index = stop;\n continue;\n }\n if (PUNCT.includes(char)) {\n push(\"punct\", index, index + 1);\n index += 1;\n continue;\n }\n push(\"text\", index, index + 1);\n index += 1;\n }\n return pieces;\n}\n\nexport function getAgentRunFrame(width?: number, height?: number) {\n const frameWidth = Math.max(1, finite(width, 1280));\n const frameHeight = Math.max(1, finite(height, 720));\n const scale = Math.min(\n frameHeight / REF_HEIGHT,\n frameWidth / (PANEL_W + 2 * MARGIN_X),\n );\n const panelHeight = clamp(\n frameHeight / scale - 2 * MARGIN_Y,\n MIN_PANEL_H,\n MAX_PANEL_H,\n );\n return {\n width: frameWidth,\n height: frameHeight,\n unit: round(scale),\n panelWidth: PANEL_W,\n panelHeight: round(panelHeight),\n viewport: round(panelHeight - HEADER_H - 2),\n };\n}\n\nexport type AgentRunFrame = ReturnType<typeof getAgentRunFrame>;\n\nexport interface AgentRunSegment {\n kind: \"think\" | \"gap\" | \"tool\" | \"answer\";\n from: number;\n to: number;\n realFrom: number;\n real: number;\n}\n\nexport interface AgentRunToolSpan {\n index: number;\n start: number;\n end: number;\n span: number;\n duration: number;\n realStart: number;\n}\n\nfunction planTextOf(run: AgentRunScript) {\n return (run.plan ?? []).join(\"\\n\");\n}\n\nexport function getAgentRunTimeline(\n run: AgentRunScript = defaultAgentRun,\n options: AgentRunOptions = {},\n) {\n const seed = seedOf(options.seed);\n const compression = compressionOf(options.compression);\n const perFrame = compression / 30;\n const planText = planTextOf(run);\n const planChunks =\n planText.length > 0 ? getAgentRunChunks(planText, seed, \"plan\") : [];\n const planStart = RUN_START + THINK_LEAD;\n const planEnd = planStart + lastArrival(planChunks);\n const thinkEnd = planEnd + THINK_TAIL;\n const segments: AgentRunSegment[] = [];\n let real = 0;\n const push = (\n kind: AgentRunSegment[\"kind\"],\n from: number,\n to: number,\n seconds: number,\n ) => {\n segments.push({ kind, from, to, realFrom: real, real: seconds });\n real += seconds;\n };\n push(\"think\", RUN_START, thinkEnd, (thinkEnd - RUN_START) * perFrame);\n const thinkSeconds = real;\n const tools: AgentRunToolSpan[] = [];\n let cursor = thinkEnd;\n for (const [index, step] of (run.steps ?? []).entries()) {\n push(\"gap\", cursor, cursor + TOOL_GAP, TOOL_GAP * perFrame);\n cursor += TOOL_GAP;\n const duration = Math.max(0, finite(step.duration, 0));\n const span = clamp(Math.round(duration / perFrame), TOOL_MIN, TOOL_MAX);\n const realStart = real;\n push(\"tool\", cursor, cursor + span, duration);\n tools.push({\n index,\n start: cursor,\n end: cursor + span,\n span,\n duration,\n realStart,\n });\n cursor += span;\n }\n push(\"gap\", cursor, cursor + ANSWER_GAP, ANSWER_GAP * perFrame);\n const answerStart = cursor + ANSWER_GAP;\n const answerChunks = getAgentRunChunks(run.answer, seed, \"answer\");\n const answerEnd = answerStart + lastArrival(answerChunks);\n push(\"answer\", answerStart, answerEnd, (answerEnd - answerStart) * perFrame);\n return {\n compression,\n runStart: RUN_START,\n planStart,\n planEnd,\n thinkEnd,\n thinkSeconds,\n tools,\n answerStart,\n answerEnd,\n runEnd: answerEnd,\n settled: answerEnd + SETTLE,\n realTotal: real,\n segments,\n planChunks,\n answerChunks,\n };\n}\n\nexport type AgentRunTimeline = ReturnType<typeof getAgentRunTimeline>;\n\nexport const agentRunLength = getAgentRunTimeline().settled;\n\nexport function getAgentRunDuration(\n run: AgentRunScript = defaultAgentRun,\n options: AgentRunOptions & Pick<AgentRunPlayback, \"speed\"> = {},\n) {\n const rate = rateOf(options.speed);\n if (rate === 0) return HOLD;\n const { settled } = getAgentRunTimeline(run, options);\n return Math.ceil(round(settled / rate)) + HOLD;\n}\n\nexport function getAgentRunTime(\n frame: number,\n playback: AgentRunPlayback = {},\n) {\n const fps = Math.max(1, finite(playback.fps, 30));\n return Math.max(0, finite(frame, 0)) * (30 / fps) * rateOf(playback.speed);\n}\n\nexport function getAgentRunElapsed(time: number, timeline: AgentRunTimeline) {\n if (!(time > timeline.runStart)) return 0;\n for (const segment of timeline.segments) {\n if (segment.to > segment.from && time < segment.to) {\n const share = (time - segment.from) / (segment.to - segment.from);\n return segment.realFrom + share * segment.real;\n }\n }\n return timeline.realTotal;\n}\n\nexport interface AgentRunChipLayout {\n label: string;\n icon: \"globe\" | \"file\";\n}\n\nexport interface AgentRunRowLayout {\n index: number;\n y: number;\n height: number;\n divider: boolean;\n icon: AgentRunIcon;\n name: string;\n detail: string;\n duration: string;\n chips: AgentRunChipLayout[];\n more: number;\n}\n\nexport interface AgentRunPlanItemLayout {\n index: number;\n y: number;\n raw: number;\n lines: AgentRunTextLine[];\n}\n\nexport interface AgentRunPlanSection {\n y: number;\n height: number;\n items: AgentRunPlanItemLayout[];\n}\n\nexport interface AgentRunToolsSection {\n y: number;\n height: number;\n rows: AgentRunRowLayout[];\n}\n\nexport type AgentRunBlockLayout =\n | {\n kind: \"heading\";\n index: number;\n y: number;\n height: number;\n level: 1 | 2;\n raw: number;\n end: number;\n mark: string;\n markWidth: number;\n lines: AgentRunTextLine[];\n }\n | {\n kind: \"paragraph\" | \"item\";\n index: number;\n y: number;\n height: number;\n raw: number;\n lines: AgentRunTextLine[];\n }\n | {\n kind: \"code\";\n index: number;\n y: number;\n height: number;\n raw: number;\n open: number;\n lang: string;\n langRaw: number;\n lines: AgentRunTextLine[];\n };\n\nconst DOMAIN = /^[a-z0-9-]+(\\.[a-z0-9-]+)+(\\/\\S*)?$/i;\n\nfunction chipWidth(label: string) {\n return 7 + 12 + 5 + estimateAgentRunWidth(label, CHIP_SIZE) + 9 + 2;\n}\n\nfunction moreWidth(count: number) {\n return 9 + estimateAgentRunWidth(`+${count}`, CHIP_SIZE) + 9 + 2;\n}\n\nexport function fitAgentRunChips(sources: readonly string[]) {\n const chips: AgentRunChipLayout[] = [];\n let used = 0;\n for (const [index, label] of sources.entries()) {\n if (chips.length >= CHIP_MAX) break;\n const width = chipWidth(label) + (chips.length > 0 ? CHIP_GAP : 0);\n const rest = sources.length - index - 1;\n const reserve = rest > 0 ? CHIP_GAP + moreWidth(rest) : 0;\n if (used + width + reserve > CHIP_ROOM) break;\n chips.push({ label, icon: DOMAIN.test(label) ? \"globe\" : \"file\" });\n used += width;\n }\n return { chips, more: sources.length - chips.length };\n}\n\nconst lineText = (line: readonly AgentRunPiece[]) =>\n line.map((piece) => piece.text).join(\"\");\n\nfunction blockGap(\n previous: AgentRunBlock[\"kind\"] | undefined,\n next: AgentRunBlock[\"kind\"],\n) {\n if (previous === undefined) return 0;\n if (previous === \"item\" && next === \"item\") return ITEM_GAP;\n if (previous === \"code\" || next === \"code\") return CODE_GAP;\n if (previous === \"heading\") return HEADING_GAP;\n return BLOCK_GAP;\n}\n\nexport function getAgentRunLayout(run: AgentRunScript = defaultAgentRun) {\n let y = PAD_TOP;\n const prompt = plainInline(run.prompt, 0);\n const wrappedPrompt = wrapAgentRunInline(prompt, BUBBLE_SIZE, BUBBLE_WIDTH);\n const promptLines = wrappedPrompt.map(lineText);\n const bubble = {\n y,\n height: Math.max(1, promptLines.length) * BUBBLE_LINE + 2 * BUBBLE_PAD_Y,\n lines: promptLines,\n };\n y += bubble.height + BUBBLE_GAP;\n const status = { y, height: STATUS_H };\n y += STATUS_H;\n let plan: AgentRunPlanSection | null = null;\n const planLines = run.plan ?? [];\n if (planLines.length > 0) {\n y += STATUS_GAP;\n const items: AgentRunPlanItemLayout[] = [];\n let cursor = 0;\n let raw = 0;\n for (const [index, text] of planLines.entries()) {\n if (index > 0) cursor += PLAN_GAP;\n const inline = plainInline(text, raw);\n const wrapped = wrapAgentRunInline(inline, PLAN_SIZE, PLAN_WIDTH);\n const lines = textLines(wrapped, PLAN_LINE, raw);\n items.push({ index, y: cursor, raw, lines });\n cursor += lines.length * PLAN_LINE;\n raw += text.length + 1;\n }\n plan = { y, height: cursor, items };\n y += cursor;\n }\n let tools: AgentRunToolsSection | null = null;\n const steps = run.steps ?? [];\n if (steps.length > 0) {\n y += PLAN_AFTER;\n const rows: AgentRunRowLayout[] = [];\n let cursor = 0;\n for (const [index, step] of steps.entries()) {\n const sources = step.sources ?? [];\n const fit = fitAgentRunChips(sources);\n const height =\n ROW_H + (index > 0 ? 1 : 0) + (sources.length > 0 ? CHIPS_H : 0);\n rows.push({\n index,\n y: cursor,\n height,\n divider: index > 0,\n icon: step.icon ?? (sources.length > 0 ? \"book\" : \"terminal\"),\n name: step.name,\n detail: step.detail ?? \"\",\n duration: formatAgentRunSeconds(finite(step.duration, 0)),\n chips: fit.chips,\n more: fit.more,\n });\n cursor += height;\n }\n tools = { y, height: cursor + 2, rows };\n y += cursor + 2;\n }\n const parsed = parseAgentRunMarkdown(run.answer);\n const blocks: AgentRunBlockLayout[] = [];\n if (parsed.length > 0) y += tools ? TOOLS_AFTER : PLAN_AFTER;\n let previous: AgentRunBlock[\"kind\"] | undefined;\n for (const [index, block] of parsed.entries()) {\n y += blockGap(previous, block.kind);\n previous = block.kind;\n if (block.kind === \"heading\") {\n const spec = HEADINGS[block.level];\n const wrapped = wrapAgentRunInline(block.inline, spec.size, MEASURE);\n const lines = textLines(wrapped, spec.line, block.body);\n const mark = run.answer.slice(block.raw, block.body);\n blocks.push({\n kind: \"heading\",\n index,\n y,\n height: lines.length * spec.line,\n level: block.level,\n raw: block.raw,\n end: block.end,\n mark,\n markWidth: round(estimateAgentRunWidth(mark, BODY_SIZE)),\n lines,\n });\n y += lines.length * spec.line;\n continue;\n }\n if (block.kind === \"code\") {\n const lines = block.lines.map((line, row) => ({\n y: row * CODE_LINE,\n height: CODE_LINE,\n raw: line.raw,\n pieces: getAgentRunCodePieces(line),\n }));\n const height = CODE_HEAD + 2 * CODE_PAD + lines.length * CODE_LINE;\n blocks.push({\n kind: \"code\",\n index,\n y,\n height,\n raw: block.raw,\n open: block.open,\n lang: block.lang,\n langRaw: block.langRaw,\n lines,\n });\n y += height;\n continue;\n }\n const width = block.kind === \"item\" ? MEASURE - ITEM_INDENT : MEASURE;\n const body = block.kind === \"item\" ? block.body : block.raw;\n const wrapped = wrapAgentRunInline(block.inline, BODY_SIZE, width);\n const lines = textLines(wrapped, BODY_LINE, body);\n blocks.push({\n kind: block.kind,\n index,\n y,\n height: lines.length * BODY_LINE,\n raw: block.raw,\n lines,\n });\n y += lines.length * BODY_LINE;\n }\n return { bubble, status, plan, tools, blocks, height: y };\n}\n\nexport type AgentRunLayout = ReturnType<typeof getAgentRunLayout>;\n\nexport interface AgentRunScrollStep {\n at: number;\n delta: number;\n}\n\nexport function getAgentRunGrowth(\n layout: AgentRunLayout,\n timeline: AgentRunTimeline,\n) {\n const events: { at: number; bottom: number }[] = [\n { at: BUBBLE_AT, bottom: layout.bubble.y + layout.bubble.height },\n { at: RUN_START, bottom: layout.status.y + layout.status.height },\n ];\n const { plan, tools } = layout;\n if (plan) {\n for (const item of plan.items) {\n for (const line of item.lines) {\n const at = getAgentRunArrival(timeline.planChunks, line.raw);\n events.push({\n at: timeline.planStart + at,\n bottom: plan.y + item.y + line.y + line.height,\n });\n }\n }\n }\n if (tools) {\n for (const row of tools.rows) {\n const span = timeline.tools[row.index];\n events.push({ at: span.start, bottom: tools.y + row.y + row.height + 2 });\n }\n }\n const arrival = (offset: number) =>\n timeline.answerStart + getAgentRunArrival(timeline.answerChunks, offset);\n for (const block of layout.blocks) {\n if (block.kind === \"code\") {\n events.push({\n at: arrival(block.open - 1),\n bottom: block.y + CODE_HEAD + 2 * CODE_PAD,\n });\n for (const line of block.lines) {\n events.push({\n at: arrival(line.raw),\n bottom: block.y + CODE_HEAD + 2 * CODE_PAD + line.y + line.height,\n });\n }\n continue;\n }\n for (const [row, line] of block.lines.entries()) {\n const start = row === 0 ? block.raw : line.raw;\n events.push({\n at: arrival(start),\n bottom: block.y + line.y + line.height,\n });\n }\n }\n return events\n .filter((event) => Number.isFinite(event.at))\n .sort((a, b) => a.at - b.at);\n}\n\nexport function getAgentRunScrollSteps(\n layout: AgentRunLayout,\n timeline: AgentRunTimeline,\n viewport: number,\n): AgentRunScrollStep[] {\n const steps: AgentRunScrollStep[] = [];\n let target = 0;\n for (const event of getAgentRunGrowth(layout, timeline)) {\n const next = Math.max(target, event.bottom + SAFE - viewport);\n if (next > target) {\n steps.push({ at: event.at, delta: round(next - target) });\n }\n target = next;\n }\n return steps;\n}\n\nexport function getAgentRunScroll(\n time: number,\n steps: readonly AgentRunScrollStep[],\n) {\n let total = 0;\n for (const step of steps) {\n const since = time - step.at + SCROLL_LEAD;\n if (since <= 0) break;\n total += step.delta * smoothstep(since / SCROLL);\n }\n return total;\n}\n\nexport function getAgentRunModel(\n run: AgentRunScript = defaultAgentRun,\n options: AgentRunOptions = {},\n) {\n const stage = getAgentRunFrame(options.width, options.height);\n const timeline = getAgentRunTimeline(run, options);\n const layout = getAgentRunLayout(run);\n const scroll = getAgentRunScrollSteps(layout, timeline, stage.viewport);\n return { run, stage, timeline, layout, scroll };\n}\n\nexport type AgentRunModel = ReturnType<typeof getAgentRunModel>;\n\nexport interface AgentRunSpinnerState {\n angle: number;\n arc: number;\n done: number;\n check: number;\n resolved: boolean;\n}\n\nexport function getAgentRunSpinner(\n time: number,\n start: number,\n end: number,\n): AgentRunSpinnerState {\n const spinning = clamp(time - start, 0, Math.max(0, end - start));\n const since = time - end;\n const settle = progress(since / RESOLVE);\n const coast = SPIN * RESOLVE * (settle - (settle * settle) / 2);\n return {\n angle: round(spinning * SPIN + coast - 90),\n arc: round(ARC + (1 - ARC) * expo(since / RESOLVE)),\n done: round(smoothstep(since / RESOLVE)),\n check: round(easeOut((since - CHECK_FROM) / (CHECK_TO - CHECK_FROM))),\n resolved: since >= 0,\n };\n}\n\nexport function getAgentRunShimmer(time: number, length: number) {\n const cycle = (time - RUN_START) / SHIMMER_PERIOD;\n const phase = cycle - Math.floor(cycle);\n const center = -SHIMMER_BAND + phase * (length + 2 * SHIMMER_BAND);\n return Array.from({ length }, (_, index) => {\n const distance = Math.abs(index + 0.5 - center) / SHIMMER_BAND;\n const band = distance < 1 ? (1 - distance * distance) ** 2 : 0;\n return round(SHIMMER_BASE + (1 - SHIMMER_BASE) * band);\n });\n}\n\nexport interface AgentRunFragment {\n text: string;\n opacity: number;\n}\n\nexport interface AgentRunSpan {\n kind: AgentRunPieceKind;\n fragments: AgentRunFragment[];\n opacity: number;\n scale: number;\n}\n\nexport interface AgentRunLineState {\n key: string;\n y: number;\n height: number;\n spans: AgentRunSpan[];\n}\n\nconst fadeOf = (since: number) => round(easeOut((since + 1) / FADE));\n\nfunction spansOf(\n pieces: readonly AgentRunPiece[],\n chunks: readonly AgentRunChunk[],\n local: number,\n revealed: number,\n): AgentRunSpan[] {\n const spans: AgentRunSpan[] = [];\n for (const piece of pieces) {\n if (piece.kind === \"cite\") {\n if (revealed < piece.end) continue;\n const since = local - getAgentRunArrival(chunks, piece.end - 1);\n spans.push({\n kind: \"cite\",\n fragments: [{ text: piece.text, opacity: 1 }],\n opacity: round(easeOut((since + 1) / 4)),\n scale: round(0.6 + 0.4 * backOut((since + 1) / POP, CITE_BACK)),\n });\n continue;\n }\n const visible = clamp(revealed - piece.raw, 0, piece.text.length);\n if (visible === 0) continue;\n const fragments: AgentRunFragment[] = [];\n let offset = 0;\n while (offset < visible) {\n const index = chunkIndexAt(chunks, piece.raw + offset);\n const chunk = chunks[index];\n const stop = chunk ? Math.min(visible, chunk.end - piece.raw) : visible;\n const opacity = chunk ? fadeOf(local - chunk.at) : 1;\n const text = piece.text.slice(offset, stop);\n const last = fragments.at(-1);\n if (last?.opacity === 1 && opacity === 1) {\n fragments[fragments.length - 1] = { text: last.text + text, opacity };\n } else {\n fragments.push({ text, opacity });\n }\n offset = Math.max(stop, offset + 1);\n }\n spans.push({ kind: piece.kind, fragments, opacity: 1, scale: 1 });\n }\n return spans;\n}\n\nexport type AgentRunBlockState =\n | {\n kind: \"heading\";\n key: string;\n y: number;\n level: 1 | 2;\n styled: boolean;\n morph: number;\n mark: string;\n markWidth: number;\n lines: AgentRunLineState[];\n }\n | { kind: \"paragraph\"; key: string; y: number; lines: AgentRunLineState[] }\n | {\n kind: \"item\";\n key: string;\n y: number;\n dot: number;\n dotOpacity: number;\n lines: AgentRunLineState[];\n }\n | {\n kind: \"code\";\n key: string;\n y: number;\n height: number;\n opacity: number;\n lang: string;\n lines: AgentRunLineState[];\n };\n\nfunction blockState(\n block: AgentRunBlockLayout,\n text: string,\n chunks: readonly AgentRunChunk[],\n local: number,\n revealed: number,\n): AgentRunBlockState | null {\n const key = `block-${block.index}`;\n const lineStates = (from: number) => {\n const lines: AgentRunLineState[] = [];\n for (const [row, line] of block.lines.entries()) {\n if (revealed <= (row === 0 ? from : line.raw)) break;\n lines.push({\n key: `${key}-line-${row}`,\n y: line.y,\n height: line.height,\n spans: spansOf(line.pieces, chunks, local, revealed),\n });\n }\n return lines;\n };\n if (block.kind === \"code\") {\n if (revealed < block.open) return null;\n const since = local - getAgentRunArrival(chunks, block.open - 1);\n let height = expo((since + 1) / CODE_OPEN) * (CODE_HEAD + 2 * CODE_PAD);\n const lines: AgentRunLineState[] = [];\n for (const [row, line] of block.lines.entries()) {\n if (revealed <= line.raw) break;\n const grown = local - getAgentRunArrival(chunks, line.raw);\n height += expo((grown + 1) / LINE_GROW) * CODE_LINE;\n lines.push({\n key: `${key}-line-${row}`,\n y: line.y,\n height: line.height,\n spans: spansOf(line.pieces, chunks, local, revealed),\n });\n }\n const langShown = clamp(revealed - block.langRaw, 0, block.lang.length);\n return {\n kind: \"code\",\n key,\n y: block.y,\n height: round(height),\n opacity: round(easeOut((since + 1) / 4)),\n lang: block.lang.slice(0, langShown),\n lines,\n };\n }\n if (revealed <= block.raw) return null;\n if (block.kind === \"heading\") {\n const complete =\n revealed > block.end ||\n (block.end >= text.length && revealed >= block.end);\n const completeAt = getAgentRunArrival(\n chunks,\n Math.min(block.end, text.length - 1),\n );\n const morph = complete ? round(expo((local - completeAt) / MORPH)) : 0;\n const markShown = clamp(revealed - block.raw, 0, block.mark.length);\n return {\n kind: \"heading\",\n key,\n y: block.y,\n level: block.level,\n styled: complete,\n morph,\n mark: block.mark.slice(0, markShown),\n markWidth: block.markWidth,\n lines: lineStates(block.raw),\n };\n }\n if (block.kind === \"item\") {\n const since = local - getAgentRunArrival(chunks, block.raw);\n return {\n kind: \"item\",\n key,\n y: block.y,\n dot: round(backOut((since + 1) / POP, DOT_BACK)),\n dotOpacity: round(easeOut((since + 1) / 3)),\n lines: lineStates(block.raw),\n };\n }\n return { kind: \"paragraph\", key, y: block.y, lines: lineStates(block.raw) };\n}\n\nexport interface AgentRunPlanItemState {\n key: string;\n index: number;\n y: number;\n numberOpacity: number;\n lines: AgentRunLineState[];\n}\n\nfunction planState(\n plan: AgentRunPlanSection,\n chunks: readonly AgentRunChunk[],\n local: number,\n) {\n const revealed = getAgentRunReveal(chunks, local);\n const items: AgentRunPlanItemState[] = [];\n let rule = 0;\n for (const item of plan.items) {\n if (revealed <= item.raw) break;\n const lines: AgentRunLineState[] = [];\n for (const [row, line] of item.lines.entries()) {\n if (revealed <= (row === 0 ? item.raw : line.raw)) break;\n const since = local - getAgentRunArrival(chunks, line.raw);\n const grown = line.height * expo((since + 1) / LINE_GROW);\n rule = Math.max(rule, item.y + line.y + grown);\n lines.push({\n key: `plan-${item.index}-line-${row}`,\n y: line.y,\n height: line.height,\n spans: spansOf(line.pieces, chunks, local, revealed),\n });\n }\n const numbered = local - getAgentRunArrival(chunks, item.raw);\n items.push({\n key: `plan-${item.index}`,\n index: item.index,\n y: item.y,\n numberOpacity: fadeOf(numbered),\n lines,\n });\n }\n return { y: plan.y, rule: round(rule), items };\n}\n\nfunction chipPops(count: number, since: number, span: number) {\n const spread = Math.max(0, CHIP_SPAN * span - CHIP_LEAD);\n const step = count > 1 ? spread / (count - 1) : 0;\n return Array.from({ length: count }, (_, index) => {\n const age = since - CHIP_LEAD - index * step;\n return {\n visible: age >= 0,\n opacity: round(easeOut((age + 1) / 4)),\n scale: round(0.8 + 0.2 * backOut((age + 1) / POP, CHIP_BACK)),\n };\n });\n}\n\nfunction toolsState(\n tools: AgentRunToolsSection,\n timeline: AgentRunTimeline,\n time: number,\n) {\n let height = 2;\n const rows = tools.rows\n .filter((row) => time >= timeline.tools[row.index].start)\n .map((row) => {\n const span = timeline.tools[row.index];\n const since = time - span.start;\n const open = expo(since / ROW_IN);\n height += row.height * open;\n const pops = chipPops(\n row.chips.length + (row.more > 0 ? 1 : 0),\n since,\n span.span,\n );\n const more = pops[row.chips.length];\n return {\n key: `tool-${row.index}`,\n index: row.index,\n y: row.y,\n height: round(row.height * open),\n divider: row.divider,\n icon: row.icon,\n name: row.name,\n detail: row.detail,\n duration: row.duration,\n content: round(easeOut((since - 1) / ROW_FADE)),\n spinner: getAgentRunSpinner(time, span.start, span.end),\n label: round(easeOut((time - span.end - LABEL_DELAY) / LABEL_FADE)),\n chips: row.chips.map((chip, index) => ({ ...chip, ...pops[index] })),\n more: row.more > 0 && more ? { count: row.more, ...more } : null,\n sources: row.chips.length + row.more > 0,\n };\n });\n return { y: tools.y, height: round(height), rows };\n}\n\nexport function getAgentRunState(\n frame: number,\n model: AgentRunModel = getAgentRunModel(),\n playback: AgentRunPlayback = {},\n) {\n const time = getAgentRunTime(frame, playback);\n const { run, stage, timeline, layout } = model;\n const elapsed = getAgentRunElapsed(time, timeline);\n const planLocal = time - timeline.planStart;\n const answerLocal = time - timeline.answerStart;\n const answerRevealed = getAgentRunReveal(timeline.answerChunks, answerLocal);\n const running = time - RUN_START;\n const swap =\n time >= timeline.thinkEnd ? expo((time - timeline.thinkEnd) / SWAP) : 0;\n const thinking = \"Thinking\";\n const blocks: AgentRunBlockState[] = [];\n for (const block of layout.blocks) {\n const next = blockState(\n block,\n run.answer,\n timeline.answerChunks,\n answerLocal,\n answerRevealed,\n );\n if (next) blocks.push(next);\n }\n return {\n time,\n elapsed,\n scroll: round(getAgentRunScroll(time, model.scroll)),\n panel: {\n width: stage.panelWidth,\n height: stage.panelHeight,\n viewport: stage.viewport,\n unit: stage.unit,\n opacity: round(easeOut((time + 1) / PANEL_IN)),\n lift: round(PANEL_RISE * (1 - expo(time / PANEL_IN))),\n },\n header: {\n title: run.title ?? \"\",\n label: formatAgentRunSeconds(elapsed),\n opacity: round(easeOut((running + 1) / STATUS_IN)),\n spinner: getAgentRunSpinner(time, RUN_START, timeline.runEnd),\n done: time >= timeline.runEnd,\n },\n bubble: {\n y: layout.bubble.y,\n height: layout.bubble.height,\n lines: layout.bubble.lines,\n opacity: round(easeOut((time - BUBBLE_AT + 1) / BUBBLE_IN)),\n lift: round(BUBBLE_RISE * (1 - expo((time - BUBBLE_AT) / BUBBLE_IN))),\n },\n status: {\n y: layout.status.y,\n visible: running >= 0,\n opacity: round(easeOut((running + 1) / STATUS_IN)),\n thinking,\n shimmer: getAgentRunShimmer(time, thinking.length),\n thought: `Thought for ${Math.max(1, Math.round(timeline.thinkSeconds))}s`,\n swap: round(swap),\n lift: round(SWAP_RISE * (1 - swap)),\n },\n plan: layout.plan\n ? planState(layout.plan, timeline.planChunks, planLocal)\n : null,\n tools: layout.tools ? toolsState(layout.tools, timeline, time) : null,\n blocks,\n revealed: {\n plan: getAgentRunReveal(timeline.planChunks, planLocal),\n answer: answerRevealed,\n },\n };\n}\n\nexport type AgentRunState = ReturnType<typeof getAgentRunState>;\n\ninterface AgentRunSurface {\n panel: string;\n border: string;\n divider: string;\n fg: string;\n muted: string;\n subtle: string;\n surface: string;\n surfaceBorder: string;\n code: string;\n track: string;\n shadow: string;\n}\n\nexport interface AgentRunPalette extends AgentRunSurface {\n accent: string;\n accentTint: string;\n accentText: string;\n}\n\nexport const AGENT_RUN_THEMES: Record<AgentRunTheme, AgentRunSurface> = {\n light: {\n panel: \"#ffffff\",\n border: \"#e4e4e0\",\n divider: \"#ededea\",\n fg: \"#1c1c1a\",\n muted: \"#63635e\",\n subtle: \"#9a9a94\",\n surface: \"#f3f3f1\",\n surfaceBorder: \"#e7e7e3\",\n code: \"#f8f8f6\",\n track: \"#e3e3df\",\n shadow: \"0 1px 2px rgba(28, 28, 26, 0.06)\",\n },\n dark: {\n panel: \"#161616\",\n border: \"#2b2b2a\",\n divider: \"#232322\",\n fg: \"#ececea\",\n muted: \"#a2a29d\",\n subtle: \"#6d6d68\",\n surface: \"#212120\",\n surfaceBorder: \"#2e2e2d\",\n code: \"#1c1c1b\",\n track: \"#343433\",\n shadow: \"0 1px 2px rgba(0, 0, 0, 0.5)\",\n },\n};\n\nexport function getAgentRunPalette(\n theme = agentRunDefaults.theme,\n accentColor = agentRunDefaults.accentColor,\n): AgentRunPalette {\n const dark = theme === \"dark\";\n const tint = dark ? 22 : 12;\n return {\n ...AGENT_RUN_THEMES[dark ? \"dark\" : \"light\"],\n accent: accentColor,\n accentTint: `color-mix(in srgb, ${accentColor} ${tint}%, transparent)`,\n accentText: dark\n ? `color-mix(in srgb, ${accentColor} 62%, #ffffff)`\n : accentColor,\n };\n}\n\ntype IconNode =\n | { tag: \"path\"; d: string }\n | { tag: \"circle\"; cx: number; cy: number; r: number }\n | { tag: \"ellipse\"; cx: number; cy: number; rx: number; ry: number }\n | {\n tag: \"rect\";\n x: number;\n y: number;\n width: number;\n height: number;\n rx: number;\n };\n\ntype IconName = AgentRunIcon | \"copy\";\n\nconst ICONS: Record<IconName, readonly IconNode[]> = {\n chart: [\n { tag: \"path\", d: \"M3 3v16a2 2 0 0 0 2 2h16\" },\n { tag: \"path\", d: \"M18 17V9\" },\n { tag: \"path\", d: \"M13 17V5\" },\n { tag: \"path\", d: \"M8 17v-3\" },\n ],\n database: [\n { tag: \"ellipse\", cx: 12, cy: 5, rx: 9, ry: 3 },\n { tag: \"path\", d: \"M3 5V19A9 3 0 0 0 21 19V5\" },\n { tag: \"path\", d: \"M3 12A9 3 0 0 0 21 12\" },\n ],\n search: [\n { tag: \"path\", d: \"m21 21-4.34-4.34\" },\n { tag: \"circle\", cx: 11, cy: 11, r: 8 },\n ],\n book: [\n { tag: \"path\", d: \"M12 7v14\" },\n {\n tag: \"path\",\n d: \"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z\",\n },\n ],\n globe: [\n { tag: \"circle\", cx: 12, cy: 12, r: 10 },\n { tag: \"path\", d: \"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\" },\n { tag: \"path\", d: \"M2 12h20\" },\n ],\n terminal: [\n { tag: \"path\", d: \"M12 19h8\" },\n { tag: \"path\", d: \"m4 17 6-6-6-6\" },\n ],\n file: [\n {\n tag: \"path\",\n d: \"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z\",\n },\n { tag: \"path\", d: \"M14 2v5a1 1 0 0 0 1 1h5\" },\n { tag: \"path\", d: \"M10 9H8\" },\n { tag: \"path\", d: \"M16 13H8\" },\n { tag: \"path\", d: \"M16 17H8\" },\n ],\n copy: [\n { tag: \"rect\", x: 8, y: 8, width: 14, height: 14, rx: 2 },\n {\n tag: \"path\",\n d: \"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\",\n },\n ],\n};\n\nfunction Icon({\n name,\n size,\n color,\n}: {\n name: IconName;\n size: number;\n color: string;\n}) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke={color}\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n style={{ display: \"block\", flexShrink: 0 }}\n >\n {ICONS[name].map((node, index) => {\n if (node.tag === \"path\") return <path key={index} d={node.d} />;\n if (node.tag === \"circle\") {\n return <circle key={index} cx={node.cx} cy={node.cy} r={node.r} />;\n }\n if (node.tag === \"ellipse\") {\n return (\n <ellipse\n key={index}\n cx={node.cx}\n cy={node.cy}\n rx={node.rx}\n ry={node.ry}\n />\n );\n }\n return (\n <rect\n key={index}\n x={node.x}\n y={node.y}\n width={node.width}\n height={node.height}\n rx={node.rx}\n />\n );\n })}\n </svg>\n );\n}\n\nfunction Spinner({\n state,\n size,\n palette,\n}: {\n state: AgentRunSpinnerState;\n size: number;\n palette: AgentRunPalette;\n}) {\n const active = 1 - state.done;\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n style={{ display: \"block\", flexShrink: 0 }}\n >\n <circle cx={12} cy={12} r={10} stroke={palette.track} opacity={active} />\n <circle\n cx={12}\n cy={12}\n r={10}\n stroke={palette.accent}\n opacity={active}\n strokeDasharray={`${round(state.arc * CIRCLE)} ${round(CIRCLE)}`}\n transform={`rotate(${state.angle} 12 12)`}\n />\n <circle\n cx={12}\n cy={12}\n r={10}\n stroke={palette.muted}\n opacity={state.done}\n />\n <path\n d=\"m9 12 2 2 4-4\"\n stroke={palette.muted}\n strokeDasharray={round(CHECK_LENGTH)}\n strokeDashoffset={round(CHECK_LENGTH * (1 - state.check))}\n opacity={state.check > 0 ? 1 : 0}\n />\n </svg>\n );\n}\n\nfunction spanStyle(\n span: AgentRunSpan,\n palette: AgentRunPalette,\n): CSSProperties {\n if (span.kind === \"bold\") return { fontWeight: 600 };\n if (span.kind === \"code\") {\n return {\n fontFamily: MONO,\n fontSize: \"0.875em\",\n padding: \"1px 5px\",\n borderRadius: 5,\n background: palette.surface,\n border: `1px solid ${palette.surfaceBorder}`,\n };\n }\n if (span.kind === \"cite\") {\n return {\n display: \"inline-flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n minWidth: 18,\n height: 18,\n padding: \"0 5px\",\n marginLeft: 2,\n borderRadius: 9,\n boxSizing: \"border-box\",\n background: palette.accentTint,\n color: palette.accentText,\n fontSize: 11.5,\n fontWeight: 600,\n lineHeight: \"18px\",\n fontVariantNumeric: \"tabular-nums\",\n verticalAlign: \"middle\",\n opacity: span.opacity,\n transform: `scale(${span.scale})`,\n };\n }\n if (span.kind === \"punct\" || span.kind === \"comment\") {\n return { color: palette.subtle };\n }\n if (span.kind === \"string\") return { color: palette.muted };\n return {};\n}\n\nfunction renderSpans(spans: readonly AgentRunSpan[], palette: AgentRunPalette) {\n return spans.map((span, index) => (\n <span key={index} style={spanStyle(span, palette)}>\n {span.fragments.map((fragment, part) => (\n <span\n key={part}\n style={\n fragment.opacity < 1 ? { opacity: fragment.opacity } : undefined\n }\n >\n {fragment.text}\n </span>\n ))}\n </span>\n ));\n}\n\nfunction AnswerBlock({\n block,\n palette,\n}: {\n block: AgentRunBlockState;\n palette: AgentRunPalette;\n}) {\n if (block.kind === \"code\") {\n return (\n <div\n style={{\n position: \"absolute\",\n top: block.y,\n left: 0,\n width: COLUMN,\n height: block.height,\n opacity: block.opacity,\n overflow: \"hidden\",\n boxSizing: \"border-box\",\n border: `1px solid ${palette.surfaceBorder}`,\n borderRadius: 10,\n background: palette.code,\n }}\n >\n <div\n style={{\n height: CODE_HEAD,\n boxSizing: \"border-box\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n padding: \"0 12px 0 16px\",\n borderBottom: `1px solid ${palette.divider}`,\n fontFamily: MONO,\n fontSize: 12.5,\n color: palette.muted,\n }}\n >\n <span>{block.lang}</span>\n <Icon name=\"copy\" size={14} color={palette.subtle} />\n </div>\n {block.lines.map((line) => (\n <div\n key={line.key}\n style={{\n position: \"absolute\",\n top: CODE_HEAD + CODE_PAD - 1 + line.y,\n left: 16,\n height: line.height,\n lineHeight: `${line.height}px`,\n fontFamily: MONO,\n fontSize: CODE_SIZE,\n whiteSpace: \"pre\",\n color: palette.fg,\n }}\n >\n {renderSpans(line.spans, palette)}\n </div>\n ))}\n </div>\n );\n }\n if (block.kind === \"heading\") {\n const spec = HEADINGS[block.level];\n const from = BODY_SIZE / spec.size;\n const scale = block.styled ? from + (1 - from) * block.morph : 1;\n return (\n <div>\n {block.lines.map((line, index) => (\n <div\n key={line.key}\n style={{\n position: \"absolute\",\n top: block.y + line.y,\n left: 0,\n height: line.height,\n display: \"flex\",\n alignItems: \"center\",\n whiteSpace: \"pre\",\n }}\n >\n {index === 0 && block.mark.length > 0 && block.morph < 1 ? (\n <span\n style={{\n maxWidth: block.markWidth * (1 - block.morph),\n overflow: \"hidden\",\n flexShrink: 0,\n opacity: 1 - block.morph,\n fontSize: BODY_SIZE,\n color: palette.subtle,\n }}\n >\n {block.mark}\n </span>\n ) : null}\n <span\n style={{\n fontSize: block.styled ? spec.size : BODY_SIZE,\n fontWeight: Math.round(400 + 200 * block.morph),\n lineHeight: 1.25,\n transform: `scale(${round(scale)})`,\n transformOrigin: \"0 50%\",\n }}\n >\n {renderSpans(line.spans, palette)}\n </span>\n </div>\n ))}\n </div>\n );\n }\n const indent = block.kind === \"item\" ? ITEM_INDENT : 0;\n return (\n <div>\n {block.kind === \"item\" ? (\n <div\n style={{\n position: \"absolute\",\n top: block.y + BODY_LINE / 2 - 3,\n left: 5,\n width: 6,\n height: 6,\n borderRadius: 3,\n background: palette.fg,\n opacity: block.dotOpacity,\n transform: `scale(${block.dot})`,\n }}\n />\n ) : null}\n {block.lines.map((line) => (\n <div\n key={line.key}\n style={{\n position: \"absolute\",\n top: block.y + line.y,\n left: indent,\n height: line.height,\n lineHeight: `${line.height}px`,\n whiteSpace: \"pre\",\n }}\n >\n {renderSpans(line.spans, palette)}\n </div>\n ))}\n </div>\n );\n}\n\nfunction Header({\n header,\n palette,\n}: {\n header: AgentRunState[\"header\"];\n palette: AgentRunPalette;\n}) {\n return (\n <div\n style={{\n height: HEADER_H,\n boxSizing: \"border-box\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n gap: 16,\n padding: `0 ${PAD_X}px`,\n borderBottom: `1px solid ${palette.divider}`,\n }}\n >\n <span\n style={{\n minWidth: 0,\n fontSize: 14,\n fontWeight: 500,\n whiteSpace: \"nowrap\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n }}\n >\n {header.title}\n </span>\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: 7,\n flexShrink: 0,\n opacity: header.opacity,\n }}\n >\n <Spinner state={header.spinner} size={14} palette={palette} />\n <span\n style={{\n minWidth: 38,\n fontSize: 13,\n color: palette.muted,\n fontVariantNumeric: \"tabular-nums\",\n textAlign: \"right\",\n }}\n >\n {header.label}\n </span>\n </div>\n </div>\n );\n}\n\nfunction Bubble({\n bubble,\n palette,\n}: {\n bubble: AgentRunState[\"bubble\"];\n palette: AgentRunPalette;\n}) {\n return (\n <div\n style={{\n position: \"absolute\",\n top: bubble.y,\n right: 0,\n padding: `${BUBBLE_PAD_Y}px ${BUBBLE_PAD_X}px`,\n borderRadius: 18,\n background: palette.surface,\n fontSize: BUBBLE_SIZE,\n lineHeight: `${BUBBLE_LINE}px`,\n whiteSpace: \"pre\",\n opacity: bubble.opacity,\n transform: `translateY(${bubble.lift}px)`,\n }}\n >\n {bubble.lines.map((line, index) => (\n <div key={index}>{line}</div>\n ))}\n </div>\n );\n}\n\nfunction Status({\n status,\n palette,\n}: {\n status: AgentRunState[\"status\"];\n palette: AgentRunPalette;\n}) {\n if (!status.visible) return null;\n return (\n <div\n style={{\n position: \"absolute\",\n top: status.y,\n left: 0,\n width: COLUMN,\n height: STATUS_H,\n fontSize: 15,\n fontWeight: 500,\n lineHeight: `${STATUS_H}px`,\n whiteSpace: \"pre\",\n opacity: status.opacity,\n }}\n >\n {status.swap < 1 ? (\n <span\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n opacity: 1 - status.swap,\n }}\n >\n {status.shimmer.map((level, index) => (\n <span key={index} style={{ opacity: level }}>\n {status.thinking[index]}\n </span>\n ))}\n </span>\n ) : null}\n {status.swap > 0 ? (\n <span\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n color: palette.muted,\n opacity: status.swap,\n transform: `translateY(${status.lift}px)`,\n }}\n >\n {status.thought}\n </span>\n ) : null}\n </div>\n );\n}\n\nfunction Plan({\n plan,\n palette,\n}: {\n plan: NonNullable<AgentRunState[\"plan\"]>;\n palette: AgentRunPalette;\n}) {\n return (\n <div\n style={{\n position: \"absolute\",\n top: plan.y,\n left: 0,\n width: COLUMN,\n fontSize: PLAN_SIZE,\n color: palette.muted,\n }}\n >\n <div\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n width: 2,\n height: plan.rule,\n borderRadius: 1,\n background: palette.track,\n }}\n />\n {plan.items.map((item) => (\n <div key={item.key}>\n <span\n style={{\n position: \"absolute\",\n top: item.y,\n left: 14,\n lineHeight: `${PLAN_LINE}px`,\n color: palette.subtle,\n fontVariantNumeric: \"tabular-nums\",\n opacity: item.numberOpacity,\n }}\n >\n {`${item.index + 1}.`}\n </span>\n {item.lines.map((line) => (\n <div\n key={line.key}\n style={{\n position: \"absolute\",\n top: item.y + line.y,\n left: PLAN_INDENT,\n height: line.height,\n lineHeight: `${line.height}px`,\n whiteSpace: \"pre\",\n }}\n >\n {renderSpans(line.spans, palette)}\n </div>\n ))}\n </div>\n ))}\n </div>\n );\n}\n\nfunction chipStyle(\n palette: AgentRunPalette,\n pop: { opacity: number; scale: number },\n padding: string,\n): CSSProperties {\n return {\n display: \"inline-flex\",\n alignItems: \"center\",\n gap: 5,\n height: 24,\n boxSizing: \"border-box\",\n padding,\n borderRadius: 7,\n border: `1px solid ${palette.surfaceBorder}`,\n background: palette.surface,\n fontSize: CHIP_SIZE,\n color: palette.muted,\n fontVariantNumeric: \"tabular-nums\",\n whiteSpace: \"nowrap\",\n opacity: pop.opacity,\n transform: `scale(${pop.scale})`,\n };\n}\n\ntype AgentRunRowState = NonNullable<AgentRunState[\"tools\"]>[\"rows\"][number];\n\nfunction ToolRow({\n row,\n palette,\n}: {\n row: AgentRunRowState;\n palette: AgentRunPalette;\n}) {\n const chips = row.chips.filter((chip) => chip.visible);\n return (\n <div\n style={{\n position: \"absolute\",\n top: row.y,\n left: 0,\n right: 0,\n height: row.height,\n overflow: \"hidden\",\n boxSizing: \"border-box\",\n borderTop: row.divider ? `1px solid ${palette.divider}` : undefined,\n }}\n >\n <div\n style={{\n height: ROW_H,\n display: \"flex\",\n alignItems: \"center\",\n gap: 10,\n padding: \"0 14px\",\n opacity: row.content,\n }}\n >\n <Icon name={row.icon} size={16} color={palette.muted} />\n <span\n style={{\n flexShrink: 0,\n fontSize: 15,\n fontWeight: 500,\n whiteSpace: \"nowrap\",\n }}\n >\n {row.name}\n </span>\n <span\n style={{\n flex: 1,\n minWidth: 0,\n fontSize: 15,\n color: palette.muted,\n whiteSpace: \"nowrap\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n }}\n >\n {row.detail}\n </span>\n <span\n style={{\n fontSize: 13,\n color: palette.muted,\n fontVariantNumeric: \"tabular-nums\",\n opacity: row.label,\n }}\n >\n {row.duration}\n </span>\n <Spinner state={row.spinner} size={16} palette={palette} />\n </div>\n {row.sources ? (\n <div\n style={{\n display: \"flex\",\n gap: CHIP_GAP,\n height: CHIPS_H,\n padding: \"0 14px 0 40px\",\n opacity: row.content,\n }}\n >\n {chips.map((chip, index) => (\n <span\n key={`${index}-${chip.label}`}\n style={chipStyle(palette, chip, \"0 9px 0 7px\")}\n >\n <Icon name={chip.icon} size={12} color={palette.subtle} />\n {chip.label}\n </span>\n ))}\n {row.more?.visible ? (\n <span style={chipStyle(palette, row.more, \"0 9px\")}>\n {`+${row.more.count}`}\n </span>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n}\n\nfunction Tools({\n tools,\n palette,\n}: {\n tools: NonNullable<AgentRunState[\"tools\"]>;\n palette: AgentRunPalette;\n}) {\n if (tools.rows.length === 0) return null;\n return (\n <div\n style={{\n position: \"absolute\",\n top: tools.y,\n left: 0,\n width: COLUMN,\n height: tools.height,\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n border: `1px solid ${palette.surfaceBorder}`,\n borderRadius: 12,\n }}\n >\n {tools.rows.map((row) => (\n <ToolRow key={row.key} row={row} palette={palette} />\n ))}\n </div>\n );\n}\n\nexport function AgentRun({\n run = agentRunDefaults.run,\n theme = agentRunDefaults.theme,\n accentColor = agentRunDefaults.accentColor,\n compression = agentRunDefaults.compression,\n seed = agentRunDefaults.seed,\n speed = agentRunDefaults.speed,\n className,\n}: AgentRunProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const model = useMemo(\n () => getAgentRunModel(run, { seed, compression, width, height }),\n [run, seed, compression, width, height],\n );\n const state = getAgentRunState(frame, model, { fps, speed });\n const palette = getAgentRunPalette(theme, accentColor);\n const { panel } = state;\n\n return (\n <div className={className} style={{ position: \"absolute\", inset: 0 }}>\n <div\n style={{\n position: \"absolute\",\n left: \"50%\",\n top: \"50%\",\n width: panel.width,\n height: panel.height,\n translate: \"-50% -50%\",\n scale: `${panel.unit}`,\n }}\n >\n <div\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n opacity: panel.opacity,\n transform: `translateY(${panel.lift}px)`,\n background: palette.panel,\n border: `1px solid ${palette.border}`,\n borderRadius: 18,\n boxShadow: palette.shadow,\n color: palette.fg,\n fontFamily: SANS,\n fontSize: BODY_SIZE,\n WebkitFontSmoothing: \"antialiased\",\n }}\n >\n <Header header={state.header} palette={palette} />\n <div\n style={{\n position: \"relative\",\n height: panel.viewport,\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n position: \"absolute\",\n top: 0,\n left: PAD_X,\n width: COLUMN,\n transform: `translateY(${-state.scroll}px)`,\n }}\n >\n <Bubble bubble={state.bubble} palette={palette} />\n <Status status={state.status} palette={palette} />\n {state.plan ? <Plan plan={state.plan} palette={palette} /> : null}\n {state.tools ? (\n <Tools tools={state.tools} palette={palette} />\n ) : null}\n {state.blocks.map((block) => (\n <AnswerBlock key={block.key} block={block} palette={palette} />\n ))}\n </div>\n </div>\n </div>\n </div>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/agent-run.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/bauhaus-build.json b/registry-artifacts/bauhaus-build.jsonnew file mode 100644index 00000000..6cc01c85--- /dev/null+++ b/registry-artifacts/bauhaus-build.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "bauhaus-build",+ "title": "Bauhaus Build",+ "description": "Flat Bauhaus circles, arcs, squares and bars tumble corner over corner on a hidden grid into an asymmetric frieze, then rebuild into two friezes around an open band for the title.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/bauhaus-build/index.tsx",+ "content": "\"use client\";\n\nimport { Easing, random, useCurrentFrame, useVideoConfig } from \"remotion\";\n\nexport type BauhausShape =\n | \"circle\"\n | \"square\"\n | \"semicircle\"\n | \"quarter\"\n | \"bar\";\n\nexport type BauhausRole = \"ink\" | \"accent\" | \"secondary\" | \"tertiary\";\n\nexport type TumbleDirection = \"U\" | \"D\" | \"L\" | \"R\";\n\nexport type TumbleMove = `${TumbleDirection}${\"+\" | \"-\"}`;\n\nexport interface BauhausPose {\n turn: number;\n x: number;\n y: number;\n}\n\nexport interface BauhausPoint {\n x: number;\n y: number;\n}\n\nexport interface BauhausFootprint {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n}\n\nexport interface BauhausPiece {\n id: string;\n shape: BauhausShape;\n width: number;\n height: number;\n role: BauhausRole;\n slot: BauhausPose;\n enter: readonly TumbleMove[];\n rebuild: readonly TumbleMove[];\n cue: number;\n after: readonly string[];\n}\n\nexport interface BauhausStep {\n move: TumbleMove;\n from: BauhausPose;\n to: BauhausPose;\n pivot: BauhausPoint;\n spin: 1 | -1;\n}\n\nexport interface BauhausFrame {\n x: number;\n y: number;\n rotation: number;\n scale: number;\n pivot: BauhausPoint | null;\n}\n\nexport interface BauhausPieceFrame extends BauhausFrame {\n id: string;\n shape: BauhausShape;\n role: BauhausRole;\n width: number;\n height: number;\n visible: boolean;\n}\n\nexport interface BauhausBuildProps {\n scale?: number;\n seed?: number;\n inkColor?: string;\n accentColor?: string;\n secondaryColor?: string;\n tertiaryColor?: string;\n speed?: number;\n loop?: boolean;\n className?: string;\n}\n\ninterface TumbleRule {\n direction: TumbleDirection;\n spin: 1 | -1;\n reverse: TumbleMove;\n}\n\nexport const bauhausBuildDefaults = {\n scale: 1,\n seed: 1,\n inkColor: \"#1c1a17\",\n accentColor: \"#e4572e\",\n secondaryColor: \"#cbbc9f\",\n tertiaryColor: \"#7e776b\",\n speed: 1,\n loop: false,\n};\n\nexport const bauhausBuildGrid = 12;\nexport const bauhausBuildBand = { top: 4, bottom: 8 };\nexport const bauhausBuildLength = 125;\nexport const bauhausBuildTimeline = {\n lead: 22,\n beat: 6,\n rebuild: 90,\n clear: 116,\n duration: 150,\n};\n\nexport const bauhausBuildPieces: readonly BauhausPiece[] = [\n {\n id: \"hill\",\n shape: \"quarter\",\n width: 4,\n height: 4,\n role: \"ink\",\n slot: { turn: 3, x: 0, y: 4 },\n enter: [\"D-\", \"R+\"],\n rebuild: [\"D-\"],\n cue: 0,\n after: [\"tile\"],\n },\n {\n id: \"tile\",\n shape: \"square\",\n width: 1,\n height: 1,\n role: \"accent\",\n slot: { turn: 0, x: 4, y: 7 },\n enter: [\"U+\", \"U+\", \"U+\", \"U+\"],\n rebuild: [\"D+\"],\n cue: 3,\n after: [\"pillar\"],\n },\n {\n id: \"pillar\",\n shape: \"bar\",\n width: 4,\n height: 1,\n role: \"ink\",\n slot: { turn: 1, x: 5, y: 4 },\n enter: [\"R+\", \"R+\"],\n rebuild: [\"U+\"],\n cue: 6,\n after: [\"sun\"],\n },\n {\n id: \"sun\",\n shape: \"circle\",\n width: 4,\n height: 4,\n role: \"accent\",\n slot: { turn: 0, x: 6, y: 4 },\n enter: [\"U+\", \"U+\"],\n rebuild: [\"U-\"],\n cue: 9,\n after: [],\n },\n {\n id: \"dome\",\n shape: \"semicircle\",\n width: 2,\n height: 2,\n role: \"secondary\",\n slot: { turn: 3, x: 1, y: 1 },\n enter: [\"R+\", \"D-\"],\n rebuild: [\"R+\"],\n cue: 12,\n after: [\"pillar\"],\n },\n {\n id: \"post\",\n shape: \"bar\",\n width: 4,\n height: 1,\n role: \"tertiary\",\n slot: { turn: 1, x: 11, y: 4 },\n enter: [\"D+\", \"D+\"],\n rebuild: [\"D-\"],\n cue: 15,\n after: [],\n },\n {\n id: \"dot\",\n shape: \"circle\",\n width: 1,\n height: 1,\n role: \"ink\",\n slot: { turn: 0, x: 11, y: 3 },\n enter: [\"D-\", \"D-\", \"D-\", \"D-\"],\n rebuild: [\"L-\"],\n cue: 18,\n after: [\"post\"],\n },\n {\n id: \"block\",\n shape: \"square\",\n width: 2,\n height: 2,\n role: \"tertiary\",\n slot: { turn: 0, x: 6, y: 10 },\n enter: [\"U+\", \"U+\", \"U+\"],\n rebuild: [\"L+\"],\n cue: 21,\n after: [\"sun\"],\n },\n {\n id: \"fan\",\n shape: \"quarter\",\n width: 2,\n height: 2,\n role: \"secondary\",\n slot: { turn: 2, x: 8, y: 10 },\n enter: [\"L-\", \"L+\", \"L+\"],\n rebuild: [\"R+\"],\n cue: 24,\n after: [\"block\"],\n },\n];\n\nconst TURN = 5;\nconst FILL = 0.8;\nconst OVERSHOOT = 0.05;\nconst SETTLE = 0.5;\n\nconst MOVES: Record<TumbleMove, TumbleRule> = {\n \"U+\": { direction: \"U\", spin: 1, reverse: \"D-\" },\n \"U-\": { direction: \"U\", spin: -1, reverse: \"D+\" },\n \"D+\": { direction: \"D\", spin: 1, reverse: \"U-\" },\n \"D-\": { direction: \"D\", spin: -1, reverse: \"U+\" },\n \"L+\": { direction: \"L\", spin: 1, reverse: \"R-\" },\n \"L-\": { direction: \"L\", spin: -1, reverse: \"R+\" },\n \"R+\": { direction: \"R\", spin: 1, reverse: \"L-\" },\n \"R-\": { direction: \"R\", spin: -1, reverse: \"L+\" },\n};\n\nconst finite = (value: number, fallback: number) =>\n Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min = 0, max = 1) =>\n Math.min(max, Math.max(min, value));\nconst swing = Easing.bezier(0.62, 0, 0.3, 1);\nconst settle = Easing.bezier(0.45, 0, 0.55, 1);\n\nfunction seedKey(seed: number) {\n return Number.isFinite(seed) ? Math.round(seed) : 1;\n}\n\nexport function getBauhausFootprint(\n piece: Pick<BauhausPiece, \"width\" | \"height\">,\n pose: BauhausPose,\n): BauhausFootprint {\n const odd = pose.turn % 2 !== 0;\n return {\n x0: pose.x,\n y0: pose.y,\n x1: pose.x + (odd ? piece.height : piece.width),\n y1: pose.y + (odd ? piece.width : piece.height),\n };\n}\n\nexport function getTumblePivot(\n box: BauhausFootprint,\n move: TumbleMove,\n): BauhausPoint {\n const { direction, spin } = MOVES[move];\n const clockwise = spin === 1;\n switch (direction) {\n case \"R\":\n return { x: box.x1, y: clockwise ? box.y1 : box.y0 };\n case \"L\":\n return { x: box.x0, y: clockwise ? box.y0 : box.y1 };\n case \"D\":\n return { x: clockwise ? box.x0 : box.x1, y: box.y1 };\n default:\n return { x: clockwise ? box.x1 : box.x0, y: box.y0 };\n }\n}\n\nconst quarterTurn = (\n point: BauhausPoint,\n pivot: BauhausPoint,\n spin: 1 | -1,\n): BauhausPoint => ({\n x: pivot.x - spin * (point.y - pivot.y),\n y: pivot.y + spin * (point.x - pivot.x),\n});\n\nexport function tumble(\n piece: Pick<BauhausPiece, \"width\" | \"height\">,\n pose: BauhausPose,\n move: TumbleMove,\n): BauhausStep {\n const { spin } = MOVES[move];\n const box = getBauhausFootprint(piece, pose);\n const pivot = getTumblePivot(box, move);\n const a = quarterTurn({ x: box.x0, y: box.y0 }, pivot, spin);\n const b = quarterTurn({ x: box.x1, y: box.y1 }, pivot, spin);\n return {\n move,\n from: pose,\n to: {\n turn: (pose.turn + spin + 4) % 4,\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n },\n pivot,\n spin,\n };\n}\n\nexport function getBauhausPaths(piece: BauhausPiece) {\n const walk = (from: BauhausPose, moves: readonly TumbleMove[]) => {\n const steps: BauhausStep[] = [];\n let pose = from;\n for (const move of moves) {\n const step = tumble(piece, pose, move);\n steps.push(step);\n pose = step.to;\n }\n return steps;\n };\n let start = piece.slot;\n for (let index = piece.enter.length - 1; index >= 0; index--) {\n start = tumble(piece, start, MOVES[piece.enter[index]].reverse).to;\n }\n const rebuild = walk(piece.slot, piece.rebuild);\n return {\n start,\n enter: walk(start, piece.enter),\n rebuild,\n handoff: rebuild.at(-1)?.to ?? piece.slot,\n };\n}\n\nfunction getRestOffset(\n piece: Pick<BauhausPiece, \"width\" | \"height\">,\n turn: number,\n): BauhausPoint {\n switch (turn) {\n case 1:\n return { x: piece.height, y: 0 };\n case 2:\n return { x: piece.width, y: piece.height };\n case 3:\n return { x: 0, y: piece.width };\n default:\n return { x: 0, y: 0 };\n }\n}\n\nexport function getBauhausPoseFrame(\n piece: Pick<BauhausPiece, \"width\" | \"height\">,\n pose: BauhausPose,\n): BauhausFrame {\n const offset = getRestOffset(piece, pose.turn);\n return {\n x: pose.x + offset.x,\n y: pose.y + offset.y,\n rotation: pose.turn * 90,\n scale: 1,\n pivot: null,\n };\n}\n\nexport function getBauhausStepFrame(\n piece: Pick<BauhausPiece, \"width\" | \"height\">,\n step: BauhausStep,\n progress: number,\n grow = 1,\n): BauhausFrame {\n const rest = getBauhausPoseFrame(piece, step.from);\n const angle = (step.spin * progress * Math.PI) / 2;\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n const dx = rest.x - step.pivot.x;\n const dy = rest.y - step.pivot.y;\n return {\n x: step.pivot.x + grow * (dx * cos - dy * sin),\n y: step.pivot.y + grow * (dx * sin + dy * cos),\n rotation: rest.rotation + step.spin * progress * 90,\n scale: grow,\n pivot: step.pivot,\n };\n}\n\nexport function getTumbleDuration(\n piece: Pick<BauhausPiece, \"width\" | \"height\">,\n) {\n return TURN * Math.sqrt(Math.max(piece.width, piece.height));\n}\n\nexport function getTumbleProgress(\n elapsed: number,\n duration: number,\n landing: boolean,\n) {\n const t = clamp(elapsed / duration);\n if (!landing) return swing(t);\n if (elapsed <= duration) return (1 + OVERSHOOT) * swing(t);\n const back = clamp((elapsed - duration) / (duration * SETTLE));\n return 1 + OVERSHOOT * (1 - settle(back));\n}\n\nexport function getUnfoldScale(progress: number) {\n return 1 - (1 - clamp(progress)) ** 3;\n}\n\nfunction getPathFrame(\n piece: BauhausPiece,\n steps: readonly BauhausStep[],\n elapsed: number,\n unfold: boolean,\n): BauhausFrame {\n const duration = getTumbleDuration(piece);\n const last = steps.length - 1;\n const index = Math.min(last, Math.max(0, Math.floor(elapsed / duration)));\n const local = elapsed - index * duration;\n const landing = index === last;\n const step = steps[index];\n if (landing && local >= duration * (1 + SETTLE)) {\n return getBauhausPoseFrame(piece, step.to);\n }\n const grow = unfold && index === 0 ? getUnfoldScale(local / duration) : 1;\n const progress = getTumbleProgress(local, duration, landing);\n return getBauhausStepFrame(piece, step, progress, grow);\n}\n\nfunction getPieceMotion(\n piece: BauhausPiece,\n arrival: number,\n time: number,\n): BauhausFrame {\n const { lead, beat, rebuild } = bauhausBuildTimeline;\n const paths = getBauhausPaths(piece);\n const cue = rebuild + piece.cue;\n if (time >= cue && paths.rebuild.length > 0) {\n return getPathFrame(piece, paths.rebuild, time - cue, false);\n }\n if (paths.enter.length === 0) {\n return getBauhausPoseFrame(piece, piece.slot);\n }\n const travel = paths.enter.length * getTumbleDuration(piece);\n const start = lead + arrival * beat - travel;\n if (time < start) {\n return { ...getBauhausPoseFrame(piece, paths.start), scale: 0 };\n }\n return getPathFrame(piece, paths.enter, time - start, true);\n}\n\nexport function getBauhausBuildDuration({\n speed = bauhausBuildDefaults.speed,\n loop = bauhausBuildDefaults.loop,\n}: Pick<BauhausBuildProps, \"speed\" | \"loop\"> = {}) {\n const rate = finite(speed, 1);\n const frames = bauhausBuildTimeline.duration * (loop ? 2 : 1);\n return rate <= 0 ? 1 : Math.max(1, Math.ceil(frames / rate));\n}\n\nexport function getBauhausBuildOrder(seed = bauhausBuildDefaults.seed) {\n const key = seedKey(seed);\n const rank = (piece: BauhausPiece) =>\n random(`bauhaus-build-${key}-order-${piece.id}`);\n const placed: BauhausPiece[] = [];\n const waiting = [...bauhausBuildPieces];\n while (waiting.length > 0) {\n const ready = waiting.filter((piece) =>\n piece.after.every((id) => placed.some((done) => done.id === id)),\n );\n const next = ready.reduce((best, piece) =>\n rank(piece) < rank(best) ? piece : best,\n );\n placed.push(next);\n waiting.splice(waiting.indexOf(next), 1);\n }\n return placed;\n}\n\nexport function getBauhausBuildVariant(seed = bauhausBuildDefaults.seed) {\n const index = (((seedKey(seed) - 1) % 4) + 4) % 4;\n return { flipX: index % 2 === 1, flipY: index >= 2 };\n}\n\nfunction getPoster(scale: number, width: number, height: number) {\n const w = Math.max(1, finite(width, 1280));\n const h = Math.max(1, finite(height, 720));\n const size = Math.min(w, h) * FILL * clamp(finite(scale, 1), 0.5, 1.25);\n return { w, h, size, originX: (w - size) / 2, originY: (h - size) / 2 };\n}\n\nexport function getBauhausBuildField({\n scale = bauhausBuildDefaults.scale,\n width = 1280,\n height = 720,\n}: Pick<BauhausBuildProps, \"scale\"> & {\n width?: number;\n height?: number;\n} = {}) {\n const poster = getPoster(scale, width, height);\n const unit = poster.size / bauhausBuildGrid;\n return {\n x: 0,\n y: poster.originY + bauhausBuildBand.top * unit,\n width: poster.w,\n height: (bauhausBuildBand.bottom - bauhausBuildBand.top) * unit,\n unit,\n };\n}\n\nexport function getBauhausBuildState(\n time: number,\n {\n seed = bauhausBuildDefaults.seed,\n scale = bauhausBuildDefaults.scale,\n loop = bauhausBuildDefaults.loop,\n width = 1280,\n height = 720,\n }: Pick<BauhausBuildProps, \"seed\" | \"scale\" | \"loop\"> & {\n width?: number;\n height?: number;\n } = {},\n) {\n const { size, originX, originY } = getPoster(scale, width, height);\n const { duration } = bauhausBuildTimeline;\n const elapsed = Math.max(0, finite(time, 0));\n const folded = elapsed % (duration * 2);\n const local = loop ? Math.min(folded, duration * 2 - folded) : elapsed;\n const pieces = getBauhausBuildOrder(seed).map((piece, arrival) => {\n const motion = getPieceMotion(piece, arrival, local);\n const frame: BauhausPieceFrame = {\n id: piece.id,\n shape: piece.shape,\n role: piece.role,\n width: piece.width,\n height: piece.height,\n ...motion,\n visible: motion.scale > 0.001,\n };\n return frame;\n });\n return {\n time: local,\n size,\n unit: size / bauhausBuildGrid,\n originX,\n originY,\n ...getBauhausBuildVariant(seed),\n pieces,\n };\n}\n\nexport function getBauhausShapePath(\n shape: BauhausShape,\n width: number,\n height: number,\n) {\n const r = width / 2;\n switch (shape) {\n case \"circle\":\n return `M 0 ${r} A ${r} ${r} 0 1 1 ${width} ${r} A ${r} ${r} 0 1 1 0 ${r} Z`;\n case \"semicircle\":\n return `M 0 ${height} A ${r} ${r} 0 0 1 ${width} ${height} Z`;\n case \"quarter\":\n return `M 0 ${height} L 0 0 A ${width} ${height} 0 0 1 ${width} ${height} Z`;\n default:\n return `M 0 0 H ${width} V ${height} H 0 Z`;\n }\n}\n\nexport function BauhausBuild({\n scale = bauhausBuildDefaults.scale,\n seed = bauhausBuildDefaults.seed,\n inkColor = bauhausBuildDefaults.inkColor,\n accentColor = bauhausBuildDefaults.accentColor,\n secondaryColor = bauhausBuildDefaults.secondaryColor,\n tertiaryColor = bauhausBuildDefaults.tertiaryColor,\n speed = bauhausBuildDefaults.speed,\n loop = bauhausBuildDefaults.loop,\n className,\n}: BauhausBuildProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const time = frame * (30 / fps) * Math.max(0, finite(speed, 1));\n const state = getBauhausBuildState(time, {\n seed,\n scale,\n loop,\n width,\n height,\n });\n const fills: Record<BauhausRole, string> = {\n ink: inkColor,\n accent: accentColor,\n secondary: secondaryColor,\n tertiary: tertiaryColor,\n };\n const mirror = `translate(${state.flipX ? width : 0} ${state.flipY ? height : 0}) scale(${state.flipX ? -1 : 1} ${state.flipY ? -1 : 1})`;\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n role=\"img\"\n aria-label=\"Geometric Bauhaus composition\"\n style={{ display: \"block\" }}\n >\n <g transform={mirror}>\n {state.pieces.map((piece) =>\n piece.visible ? (\n <path\n key={piece.id}\n d={getBauhausShapePath(piece.shape, piece.width, piece.height)}\n fill={fills[piece.role]}\n transform={`translate(${state.originX + piece.x * state.unit} ${state.originY + piece.y * state.unit}) rotate(${piece.rotation}) scale(${piece.scale * state.unit})`}\n />\n ) : null,\n )}\n </g>\n </svg>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/bauhaus-build.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/code-morph.json b/registry-artifacts/code-morph.jsonnew file mode 100644index 00000000..2030e3aa--- /dev/null+++ b/registry-artifacts/code-morph.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "code-morph",+ "title": "Code Morph",+ "description": "A flat code editor that morphs between versions of a file, gliding each surviving token to its new line and column while removed code dissolves and new code fades in.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/code-morph/index.tsx",+ "content": "\"use client\";\n\nimport { useMemo } from \"react\";\nimport { Easing, useCurrentFrame, useVideoConfig } from \"remotion\";\n\nexport type CodeMorphTheme = \"dark\" | \"light\";\n\nexport type CodeMorphKind =\n | \"keyword\"\n | \"string\"\n | \"number\"\n | \"comment\"\n | \"function\"\n | \"type\"\n | \"text\"\n | \"punct\";\n\nexport type CodeMorphRole = \"rest\" | \"stay\" | \"move\" | \"exit\" | \"enter\";\n\nexport interface CodeMorphStep {\n at: number;\n code: string;\n}\n\nexport interface CodeMorphProps {\n steps?: CodeMorphStep[];\n morphDuration?: number;\n highlight?: boolean;\n fontSize?: number;\n lineNumbers?: boolean;\n filename?: string;\n windowDots?: boolean;\n theme?: CodeMorphTheme;\n accentColor?: string;\n speed?: number;\n className?: string;\n}\n\ntype Paint = \"theme\" | \"accentColor\" | \"className\";\n\nexport interface CodeMorphOptions extends Omit<CodeMorphProps, Paint> {\n width?: number;\n height?: number;\n fps?: number;\n}\n\nexport interface CodeMorphToken {\n text: string;\n kind: CodeMorphKind;\n line: number;\n col: number;\n word: boolean;\n}\n\nexport interface CodeMorphDiff {\n fromTo: number[];\n toFrom: number[];\n}\n\nexport interface CodeMorphRenderToken {\n key: string;\n text: string;\n kind: CodeMorphKind;\n role: CodeMorphRole;\n line: number;\n col: number;\n opacity: number;\n scale: number;\n blur: number;\n}\n\nexport interface CodeMorphRow {\n key: string;\n row: number;\n opacity: number;\n}\n\nexport interface CodeMorphState {\n time: number;\n version: number;\n morphing: boolean;\n progress: number;\n lines: number;\n tokens: CodeMorphRenderToken[];\n lineNumbers: CodeMorphRow[];\n highlights: CodeMorphRow[];\n}\n\nconst BEFORE = `import { useEffect, useState } from \"react\";\n\nexport function Invoices() {\n const [invoices, setInvoices] = useState([]);\n const [loading, setLoading] = useState(true);\n\n useEffect(() => {\n fetch(\"/api/invoices\")\n .then((res) => res.json())\n .then(setInvoices)\n .finally(() => setLoading(false));\n }, []);\n\n if (loading) return <Spinner />;\n return <InvoiceTable rows={invoices} />;\n}`;\n\nconst AFTER = `import useSWR from \"swr\";\n\nexport function Invoices() {\n const { data, isLoading } = useSWR(\"/api/invoices\", fetcher);\n\n if (isLoading) return <Spinner />;\n return <InvoiceTable rows={data} />;\n}`;\n\nexport const codeMorphDefaults: Required<Omit<CodeMorphProps, \"className\">> = {\n steps: [\n { at: 0, code: BEFORE },\n { at: 48, code: AFTER },\n ],\n morphDuration: 36,\n highlight: true,\n fontSize: 20,\n lineNumbers: true,\n filename: \"invoices.tsx\",\n windowDots: true,\n theme: \"dark\",\n accentColor: \"#0ea5e9\",\n speed: 1,\n};\n\nconst FONT_MONO =\n \"var(--font-geist-mono, ui-monospace), ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\";\nconst REFERENCE_WIDTH = 1280;\nconst REFERENCE_HEIGHT = 720;\nconst MAX_WIDTH = 1152;\nconst MAX_HEIGHT = 640;\nconst ADVANCE = 0.6;\nconst LEADING = 1.55;\nconst HEADER = 42;\nconst PAD_TOP = 20;\nconst PAD_BOTTOM = 22;\nconst PAD_LEFT = 22;\nconst PAD_RIGHT = 28;\nconst GUTTER_GAP = 2;\nconst RADIUS = 14;\nconst DOT = 11;\nconst DOT_GAP = 7;\nconst DOT_LEFT = 16;\nconst DOTS = [0, 1, 2];\nconst TAB_OFFSET = 14;\nconst TAB_AFTER_DOTS = DOT_LEFT + 3 * DOT + 2 * DOT_GAP + TAB_OFFSET;\nconst TAB_LEFT = 10;\nconst TAB_TOP = 8;\nconst TAB_PAD = 14;\nconst TAB_RADIUS = 8;\nconst TAB_FONT = 13;\nconst BAR = 2;\nconst BLUR = 3.5;\nconst SHRINK = 0.08;\nconst GROW_FROM = 0.96;\nconst BASE = 36;\nconst EXIT_SPREAD = 4;\nconst EXIT_DURATION = 12;\nconst MOVE_START = 6;\nconst MOVE_DURATION = 22;\nconst CASCADE = 4;\nconst ENTER_START = 20;\nconst ENTER_SPREAD = 4;\nconst ENTER_DURATION = 12;\nconst ARC = 0.08;\nconst RISE = 8;\nconst SHOW = 24;\nconst FALL = 14;\nconst HOLD = 24;\nconst MIN_MORPH = 12;\nconst MAX_MORPH = 120;\nconst MIN_FONT = 10;\nconst MAX_FONT = 40;\nconst LINE_COST = 10;\nconst COLUMN_COST = 0.5;\nconst MAX_COST = 1000;\nconst PUNCT_VALUE = 12;\nconst TAB = \" \";\n\nconst KEYWORDS = new Set([\n \"abstract\",\n \"as\",\n \"async\",\n \"await\",\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"declare\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"enum\",\n \"export\",\n \"extends\",\n \"false\",\n \"finally\",\n \"for\",\n \"from\",\n \"function\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"interface\",\n \"keyof\",\n \"let\",\n \"namespace\",\n \"new\",\n \"null\",\n \"of\",\n \"private\",\n \"protected\",\n \"public\",\n \"readonly\",\n \"return\",\n \"satisfies\",\n \"static\",\n \"super\",\n \"switch\",\n \"this\",\n \"throw\",\n \"true\",\n \"try\",\n \"type\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"while\",\n \"yield\",\n]);\n\nconst OPERATORS = [\n \"===\",\n \"!==\",\n \"**=\",\n \"...\",\n \"&&=\",\n \"||=\",\n \"??=\",\n \"=>\",\n \"==\",\n \"!=\",\n \"<=\",\n \">=\",\n \"&&\",\n \"||\",\n \"??\",\n \"?.\",\n \"++\",\n \"--\",\n \"+=\",\n \"-=\",\n \"*=\",\n \"/=\",\n \"%=\",\n \"**\",\n \"</\",\n \"/>\",\n];\n\nconst NUMBER =\n /0[xXbBoO][\\dA-Fa-f_]+n?|\\d[\\d_]*(?:\\.\\d[\\d_]*)?(?:[eE][+-]?\\d+)?n?/y;\nconst WORD =\n /[A-Za-z_$\\u00c0-\\u024f\\u0370-\\u03ff][\\w$\\u00c0-\\u024f\\u0370-\\u03ff]*/y;\nconst SPACE = /\\s/;\nconst CAPITAL = /^[A-Z]/;\nconst OPENERS = new Set([\"(\", \"[\", \"{\"]);\nconst CLOSERS = new Map([\n [\")\", \"(\"],\n [\"]\", \"[\"],\n [\"}\", \"{\"],\n]);\n\nconst glide = Easing.bezier(0.6, 0, 0.2, 1);\n\ninterface CodeMorphPalette {\n panel: string;\n chrome: string;\n border: string;\n dot: string;\n label: string;\n gutter: string;\n keyword: string;\n function: string;\n type: string;\n text: string;\n punct: string;\n comment: string;\n mix: string;\n share: number;\n band: number;\n}\n\nconst PALETTES: Record<CodeMorphTheme, CodeMorphPalette> = {\n dark: {\n panel: \"#111113\",\n chrome: \"#0c0c0e\",\n border: \"#27272a\",\n dot: \"#3f3f46\",\n label: \"#e4e4e7\",\n gutter: \"#52525b\",\n keyword: \"#a1a1aa\",\n function: \"#fafafa\",\n type: \"#fafafa\",\n text: \"#d4d4d8\",\n punct: \"#71717a\",\n comment: \"#5b5b63\",\n mix: \"#ffffff\",\n share: 80,\n band: 0.16,\n },\n light: {\n panel: \"#ffffff\",\n chrome: \"#f7f7f8\",\n border: \"#e4e4e7\",\n dot: \"#d4d4d8\",\n label: \"#27272a\",\n gutter: \"#b4b4bb\",\n keyword: \"#71717a\",\n function: \"#09090b\",\n type: \"#09090b\",\n text: \"#3f3f46\",\n punct: \"#909098\",\n comment: \"#a1a1aa\",\n mix: \"#000000\",\n share: 70,\n band: 0.12,\n },\n};\n\ntype Open = \"comment\" | \"string\" | null;\ntype Lexeme = \"comment\" | \"string\" | \"number\" | \"word\" | \"punct\";\ntype Pair = [number, number];\n\ninterface Piece {\n start: number;\n end: number;\n lexeme: Lexeme;\n}\n\ninterface Lexed {\n text: string;\n lexeme: Lexeme;\n line: number;\n col: number;\n}\n\nconst finite = (value: number | undefined, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst unit01 = (value: number) => clamp(value, 0, 1);\nconst easeOut = (value: number) => 1 - (1 - unit01(value)) ** 3;\nconst easeOutQuad = (value: number) => 1 - (1 - unit01(value)) ** 2;\nconst phase = (value: number, morph: number) => (value * morph) / BASE;\nconst range = (start: number, end: number) =>\n Array.from({ length: Math.max(0, end - start) }, (_, k) => start + k);\n\nfunction smoothstep(value: number) {\n const t = unit01(value);\n return t * t * (3 - 2 * t);\n}\n\nexport function normalizeCodeMorphCode(code: string) {\n const lines = code\n .replace(/\\r\\n?/g, \"\\n\")\n .replace(/\\t/g, TAB)\n .split(\"\\n\")\n .map((line) => line.trimEnd());\n let start = 0;\n while (start < lines.length && lines[start] === \"\") start += 1;\n let end = lines.length;\n while (end > start && lines[end - 1] === \"\") end -= 1;\n const body = lines.slice(start, end);\n const indents = body\n .filter((line) => line !== \"\")\n .map((line) => line.length - line.trimStart().length);\n const cut = indents.length > 0 ? Math.min(...indents) : 0;\n return body.map((line) => line.slice(cut)).join(\"\\n\");\n}\n\nfunction closing(line: string, from: number, quote: string) {\n let index = from;\n while (index < line.length) {\n const char = line[index];\n if (char === quote) return index;\n index += char === \"\\\\\" ? 2 : 1;\n }\n return -1;\n}\n\nfunction matchAt(pattern: RegExp, line: string, index: number) {\n pattern.lastIndex = index;\n const match = pattern.exec(line);\n return match ? match[0] : \"\";\n}\n\nfunction scanLine(line: string, open: Open): { pieces: Piece[]; open: Open } {\n const pieces: Piece[] = [];\n const emit = (start: number, end: number, lexeme: Lexeme) => {\n pieces.push({ start, end, lexeme });\n return end;\n };\n let index = 0;\n if (open !== null) {\n const comment = open === \"comment\";\n const end = comment ? line.indexOf(\"*/\") : closing(line, 0, \"`\");\n if (end === -1) {\n emit(0, line.length, open);\n return { pieces, open };\n }\n index = emit(0, end + (comment ? 2 : 1), open);\n }\n while (index < line.length) {\n const char = line[index];\n if (SPACE.test(char)) {\n index += 1;\n continue;\n }\n if (line.startsWith(\"//\", index)) {\n emit(index, line.length, \"comment\");\n break;\n }\n if (line.startsWith(\"/*\", index)) {\n const end = line.indexOf(\"*/\", index + 2);\n if (end === -1) {\n emit(index, line.length, \"comment\");\n return { pieces, open: \"comment\" };\n }\n index = emit(index, end + 2, \"comment\");\n continue;\n }\n if (char === '\"' || char === \"'\" || char === \"`\") {\n const end = closing(line, index + 1, char);\n if (end === -1 && char === \"`\") {\n emit(index, line.length, \"string\");\n return { pieces, open: \"string\" };\n }\n index = emit(index, end === -1 ? line.length : end + 1, \"string\");\n continue;\n }\n const number = matchAt(NUMBER, line, index);\n if (number !== \"\") {\n index = emit(index, index + number.length, \"number\");\n continue;\n }\n const word = matchAt(WORD, line, index);\n if (word !== \"\") {\n index = emit(index, index + word.length, \"word\");\n continue;\n }\n const operator = OPERATORS.find((item) => line.startsWith(item, index));\n const glyph = String.fromCodePoint(line.codePointAt(index) ?? 0);\n index = emit(index, index + (operator ?? glyph).length, \"punct\");\n }\n return { pieces, open: null };\n}\n\nfunction columnsOf(line: string) {\n const columns: number[] = [];\n let index = 0;\n let column = 0;\n for (const char of line) {\n for (let unit = 0; unit < char.length; unit += 1) {\n columns[index + unit] = column;\n }\n index += char.length;\n column += 1;\n }\n columns[index] = column;\n return columns;\n}\n\nfunction kindOf(lexed: Lexed[], index: number): CodeMorphKind {\n const { lexeme, text } = lexed[index];\n if (lexeme !== \"word\") return lexeme;\n const previous = index > 0 ? lexed[index - 1].text : \"\";\n const next = index + 1 < lexed.length ? lexed[index + 1].text : \"\";\n const member = previous === \".\" || previous === \"?.\";\n if (!member && KEYWORDS.has(text)) return \"keyword\";\n if (next === \"(\") return \"function\";\n if (CAPITAL.test(text)) return \"type\";\n return \"text\";\n}\n\nfunction versionOf(source: string) {\n const code = normalizeCodeMorphCode(source);\n const lines = code.split(\"\\n\");\n const lexed: Lexed[] = [];\n let open: Open = null;\n let columns = 0;\n for (const [line, text] of lines.entries()) {\n const map = columnsOf(text);\n columns = Math.max(columns, map[text.length]);\n const scanned = scanLine(text, open);\n open = scanned.open;\n for (const piece of scanned.pieces) {\n let start = piece.start;\n let end = piece.end;\n while (start < end && SPACE.test(text[start])) start += 1;\n while (end > start && SPACE.test(text[end - 1])) end -= 1;\n if (end === start) continue;\n const slice = text.slice(start, end);\n const col = map[start];\n lexed.push({ text: slice, lexeme: piece.lexeme, line, col });\n }\n }\n const tokens: CodeMorphToken[] = lexed.map((item, index) => {\n const kind = kindOf(lexed, index);\n const { text, line, col } = item;\n return { text, kind, line, col, word: kind !== \"punct\" };\n });\n return { code, tokens, lines: lines.length, columns };\n}\n\ntype CodeMorphVersion = ReturnType<typeof versionOf>;\n\nexport function tokenizeCodeMorph(code: string) {\n return versionOf(code).tokens;\n}\n\ninterface Sides {\n from: CodeMorphToken[];\n to: CodeMorphToken[];\n fromWidths: Map<number, number>;\n toWidths: Map<number, number>;\n}\n\nfunction widthsOf(tokens: CodeMorphToken[]) {\n const widths = new Map<number, number>();\n for (const token of tokens) {\n const end = token.col + Array.from(token.text).length;\n widths.set(token.line, Math.max(widths.get(token.line) ?? 0, end));\n }\n return widths;\n}\n\ninterface Shift {\n line: number;\n lines: number;\n cols: number;\n}\n\nfunction shiftOf(sides: Sides, pair: Pair): Shift {\n const anchor = sides.from[pair[0]];\n const landed = sides.to[pair[1]];\n return {\n line: anchor.line,\n lines: landed.line - anchor.line,\n cols: landed.col - anchor.col,\n };\n}\n\nconst STILL: Shift = { line: -1, lines: 0, cols: 0 };\n\nfunction expectedCost(sides: Sides, i: number, j: number, shift: Shift) {\n const source = sides.from[i];\n const target = sides.to[j];\n const lineOff = Math.abs(target.line - (source.line + shift.lines));\n if (source.line !== shift.line) {\n const colOff = Math.abs(target.col - source.col);\n return lineOff * LINE_COST + colOff * COLUMN_COST;\n }\n const left = source.col + shift.cols;\n const tail = (sides.fromWidths.get(source.line) ?? 0) - source.col;\n const right = (sides.toWidths.get(target.line) ?? 0) - tail;\n const colOff = Math.min(\n Math.abs(target.col - left),\n Math.abs(target.col - right),\n );\n return lineOff * LINE_COST + colOff * COLUMN_COST;\n}\n\nfunction costOf(\n sides: Sides,\n i: number,\n j: number,\n before: Shift | null,\n after: Shift | null,\n) {\n if (before === null && after === null) {\n return Math.min(MAX_COST, expectedCost(sides, i, j, STILL));\n }\n const via = (shift: Shift | null) =>\n shift === null ? MAX_COST : expectedCost(sides, i, j, shift);\n return Math.min(MAX_COST, via(before), via(after));\n}\n\nfunction align(\n sources: number[],\n targets: number[],\n value: (i: number, j: number) => number,\n): Pair[] {\n const rows = sources.length;\n const cols = targets.length;\n if (rows === 0 || cols === 0) return [];\n const width = cols + 1;\n const worth = new Float64Array(rows * cols);\n for (let a = 0; a < rows; a += 1) {\n for (let b = 0; b < cols; b += 1) {\n worth[a * cols + b] = value(sources[a], targets[b]);\n }\n }\n const table = new Float64Array((rows + 1) * width);\n const at = (a: number, b: number) => table[a * width + b];\n for (let a = rows - 1; a >= 0; a -= 1) {\n for (let b = cols - 1; b >= 0; b -= 1) {\n const gain = worth[a * cols + b];\n const skip = Math.max(at(a + 1, b), at(a, b + 1));\n const take = gain > 0 ? at(a + 1, b + 1) + gain : 0;\n table[a * width + b] = Math.max(skip, take);\n }\n }\n const pairs: Pair[] = [];\n let p = 0;\n let q = 0;\n while (p < rows && q < cols) {\n const gain = worth[p * cols + q];\n if (gain > 0 && at(p, q) === at(p + 1, q + 1) + gain) {\n pairs.push([sources[p], targets[q]]);\n p += 1;\n q += 1;\n } else if (at(p, q) === at(p + 1, q)) {\n p += 1;\n } else {\n q += 1;\n }\n }\n return pairs;\n}\n\nfunction increasing(candidates: Pair[]): Pair[] {\n const length: number[] = [];\n const previous: number[] = [];\n let best = -1;\n for (const [k, [, j]] of candidates.entries()) {\n length[k] = 1;\n previous[k] = -1;\n for (let p = 0; p < k; p += 1) {\n if (candidates[p][1] < j && length[p] + 1 > length[k]) {\n length[k] = length[p] + 1;\n previous[k] = p;\n }\n }\n if (best === -1 || length[k] > length[best]) best = k;\n }\n const chain: Pair[] = [];\n for (let k = best; k !== -1; k = previous[k]) chain.push(candidates[k]);\n return chain.reverse();\n}\n\nfunction anchorsOf(from: CodeMorphToken[], to: CodeMorphToken[]) {\n const fromCount = new Map<string, number>();\n const toCount = new Map<string, number>();\n const toIndex = new Map<string, number>();\n for (const token of from) {\n if (token.word) {\n fromCount.set(token.text, (fromCount.get(token.text) ?? 0) + 1);\n }\n }\n for (const [j, token] of to.entries()) {\n if (!token.word) continue;\n toCount.set(token.text, (toCount.get(token.text) ?? 0) + 1);\n toIndex.set(token.text, j);\n }\n const candidates: Pair[] = [];\n for (const [i, token] of from.entries()) {\n const j = toIndex.get(token.text);\n const unique =\n fromCount.get(token.text) === 1 && toCount.get(token.text) === 1;\n if (token.word && unique && j !== undefined) candidates.push([i, j]);\n }\n return increasing(candidates);\n}\n\nfunction guidesOf(sides: Sides, pairs: Pair[]) {\n const size = sides.from.length;\n const before: (Shift | null)[] = [];\n const after: (Shift | null)[] = [];\n let last: Shift | null = null;\n let cursor = 0;\n for (let i = 0; i < size; i += 1) {\n while (cursor < pairs.length && pairs[cursor][0] <= i) {\n last = shiftOf(sides, pairs[cursor]);\n cursor += 1;\n }\n before.push(last);\n }\n let next: Shift | null = null;\n cursor = pairs.length - 1;\n for (let i = size - 1; i >= 0; i -= 1) {\n while (cursor >= 0 && pairs[cursor][0] >= i) {\n next = shiftOf(sides, pairs[cursor]);\n cursor -= 1;\n }\n after[i] = next;\n }\n return { before, after };\n}\n\nfunction partnersOf(tokens: CodeMorphToken[]) {\n const partner = tokens.map(() => -1);\n const stack: number[] = [];\n for (const [index, token] of tokens.entries()) {\n if (token.kind !== \"punct\") continue;\n if (OPENERS.has(token.text)) {\n stack.push(index);\n continue;\n }\n const opener = CLOSERS.get(token.text);\n if (opener === undefined) continue;\n let depth = stack.length - 1;\n while (depth >= 0 && tokens[stack[depth]].text !== opener) depth -= 1;\n if (depth < 0) continue;\n partner[stack[depth]] = index;\n partner[index] = stack[depth];\n stack.length = depth;\n }\n return partner;\n}\n\nfunction linesOf(tokens: CodeMorphToken[]) {\n const lines = new Map<number, number[]>();\n for (const [index, token] of tokens.entries()) {\n const list = lines.get(token.line);\n if (list) list.push(index);\n else lines.set(token.line, [index]);\n }\n return lines;\n}\n\nfunction signatureOf(tokens: CodeMorphToken[], indices: number[]) {\n const base = tokens[indices[0]].col;\n const shape = indices.map((i) => [tokens[i].col - base, tokens[i].text]);\n return JSON.stringify(shape);\n}\n\nexport function diffCodeMorphTokens(\n from: CodeMorphToken[],\n to: CodeMorphToken[],\n): CodeMorphDiff {\n const sides: Sides = {\n from,\n to,\n fromWidths: widthsOf(from),\n toWidths: widthsOf(to),\n };\n const guides = guidesOf(sides, anchorsOf(from, to));\n const fromWords = range(0, from.length).filter((i) => from[i].word);\n const toWords = range(0, to.length).filter((j) => to[j].word);\n const weight = (Math.min(fromWords.length, toWords.length) + 1) * MAX_COST;\n const words = align(fromWords, toWords, (i, j) => {\n if (from[i].text !== to[j].text) return 0;\n return weight - costOf(sides, i, j, guides.before[i], guides.after[i]);\n });\n const fromTo = from.map(() => -1);\n const toFrom = to.map(() => -1);\n const link = ([i, j]: Pair) => {\n fromTo[i] = j;\n toFrom[j] = i;\n };\n const bounds: Pair[] = [[-1, -1], ...words, [from.length, to.length]];\n for (let k = 0; k + 1 < bounds.length; k += 1) {\n const [a0, b0] = bounds[k];\n const [a1, b1] = bounds[k + 1];\n const inner = k + 2 < bounds.length;\n const before = k > 0 ? shiftOf(sides, bounds[k]) : null;\n const after = inner ? shiftOf(sides, bounds[k + 1]) : null;\n const sources = range(a0 + 1, a1).filter((i) => !from[i].word);\n const targets = range(b0 + 1, b1).filter((j) => !to[j].word);\n const found = align(sources, targets, (i, j) => {\n if (from[i].text !== to[j].text) return 0;\n return PUNCT_VALUE - costOf(sides, i, j, before, after);\n });\n for (const pair of found) link(pair);\n if (inner) link(bounds[k + 1]);\n }\n const fromPartner = partnersOf(from);\n const toPartner = partnersOf(to);\n for (const [i, token] of from.entries()) {\n const j = fromTo[i];\n if (j < 0 || !OPENERS.has(token.text)) continue;\n const close = fromPartner[i];\n const target = toPartner[j];\n if (close < 0 || target < 0 || fromTo[close] === target) continue;\n if (fromTo[close] >= 0) toFrom[fromTo[close]] = -1;\n if (toFrom[target] >= 0) fromTo[toFrom[target]] = -1;\n link([close, target]);\n }\n const fromLines = linesOf(from);\n const pool = new Map<string, number[]>();\n for (const [line, indices] of fromLines) {\n const removed = indices.every((i) => fromTo[i] < 0);\n if (!removed || !indices.some((i) => from[i].word)) continue;\n const key = signatureOf(from, indices);\n const list = pool.get(key);\n if (list) list.push(line);\n else pool.set(key, [line]);\n }\n for (const [line, indices] of linesOf(to)) {\n if (!indices.every((j) => toFrom[j] < 0)) continue;\n const list = pool.get(signatureOf(to, indices));\n if (list === undefined || list.length === 0) continue;\n let best = 0;\n for (const [k, candidate] of list.entries()) {\n if (Math.abs(candidate - line) < Math.abs(list[best] - line)) best = k;\n }\n const [source] = list.splice(best, 1);\n const origin = fromLines.get(source) ?? [];\n for (const [k, j] of indices.entries()) link([origin[k], j]);\n }\n return { fromTo, toFrom };\n}\n\nfunction ranks(lines: number[]) {\n const distinct = Array.from(new Set(lines)).sort((a, b) => a - b);\n const map = new Map<number, number>();\n const last = distinct.length - 1;\n for (const [index, line] of distinct.entries()) {\n map.set(line, last > 0 ? index / last : 0);\n }\n return map;\n}\n\nfunction changedLines(\n from: CodeMorphVersion,\n to: CodeMorphVersion,\n diff: CodeMorphDiff,\n) {\n const sizes = new Map<number, number>();\n for (const token of from.tokens) {\n sizes.set(token.line, (sizes.get(token.line) ?? 0) + 1);\n }\n const members = new Map<number, number[]>();\n for (const [j, token] of to.tokens.entries()) {\n const list = members.get(token.line);\n if (list) list.push(j);\n else members.set(token.line, [j]);\n }\n const changed: number[] = [];\n for (const [line, indices] of members) {\n const sources = indices.map((j) => diff.toFrom[j]);\n const origin = sources[0] >= 0 ? from.tokens[sources[0]].line : -1;\n const inLine = (i: number) => i >= 0 && from.tokens[i].line === origin;\n const copied = sources.every(inLine);\n if (!(copied && sizes.get(origin) === indices.length)) changed.push(line);\n }\n return changed.sort((a, b) => a - b);\n}\n\nfunction morphOf(from: CodeMorphVersion, to: CodeMorphVersion) {\n const diff = diffCodeMorphTokens(from.tokens, to.tokens);\n const leaving: number[] = [];\n const moving: number[] = [];\n const entering: number[] = [];\n for (const [i, token] of from.tokens.entries()) {\n if (diff.fromTo[i] < 0) leaving.push(token.line);\n }\n for (const [j, token] of to.tokens.entries()) {\n const i = diff.toFrom[j];\n if (i < 0) {\n entering.push(token.line);\n continue;\n }\n const source = from.tokens[i];\n if (source.line !== token.line || source.col !== token.col) {\n moving.push(token.line);\n }\n }\n return {\n diff,\n exitRank: ranks(leaving),\n moveRank: ranks(moving),\n enterRank: ranks(entering),\n changed: changedLines(from, to, diff),\n };\n}\n\nfunction stepsOf(steps: CodeMorphStep[] | undefined) {\n const source = Array.isArray(steps) ? steps : codeMorphDefaults.steps;\n const ordered = source\n .map((step, index) => ({\n index,\n at: Math.max(0, finite(step.at, 0)),\n code: typeof step.code === \"string\" ? step.code : \"\",\n }))\n .sort((a, b) => a.at - b.at || a.index - b.index);\n return ordered.length > 0 ? ordered : [{ index: 0, at: 0, code: \"\" }];\n}\n\nexport function getCodeMorphLayout(options: CodeMorphOptions = {}) {\n const width = Math.max(1, finite(options.width, REFERENCE_WIDTH));\n const height = Math.max(1, finite(options.height, REFERENCE_HEIGHT));\n const requested = finite(options.fontSize, codeMorphDefaults.fontSize);\n const size = clamp(requested, MIN_FONT, MAX_FONT);\n const lineNumbers = options.lineNumbers !== false;\n const windowDots = options.windowDots !== false;\n const filename = (options.filename ?? codeMorphDefaults.filename).trim();\n const versions = stepsOf(options.steps).map((step) => versionOf(step.code));\n const morphs: ReturnType<typeof morphOf>[] = [];\n for (let index = 1; index < versions.length; index += 1) {\n morphs.push(morphOf(versions[index - 1], versions[index]));\n }\n const rows = Math.max(...versions.map((version) => version.lines));\n const columns = Math.max(...versions.map((version) => version.columns));\n const digits = lineNumbers ? Math.max(2, String(rows).length) : 0;\n const gutter = lineNumbers ? digits + GUTTER_GAP : 0;\n const header = windowDots || filename !== \"\" ? HEADER : 0;\n const leading = size * LEADING;\n const panelWidth = PAD_LEFT + PAD_RIGHT + (gutter + columns) * ADVANCE * size;\n const panelHeight = header + PAD_TOP + PAD_BOTTOM + rows * leading;\n const fit = Math.min(1, MAX_WIDTH / panelWidth, MAX_HEIGHT / panelHeight);\n const scale = Math.min(width / REFERENCE_WIDTH, height / REFERENCE_HEIGHT);\n const unit = scale * fit;\n return {\n width,\n height,\n unit,\n fit,\n fontSize: size * unit,\n lineHeight: leading * unit,\n header: header * unit,\n padTop: PAD_TOP * unit,\n padBottom: PAD_BOTTOM * unit,\n padLeft: PAD_LEFT * unit,\n padRight: PAD_RIGHT * unit,\n rows,\n columns,\n digits,\n gutter,\n lineNumbers,\n windowDots,\n filename,\n versions,\n morphs,\n };\n}\n\nexport type CodeMorphLayout = ReturnType<typeof getCodeMorphLayout>;\n\nexport function getCodeMorphTimeline(options: CodeMorphOptions = {}) {\n const requested = finite(\n options.morphDuration,\n codeMorphDefaults.morphDuration,\n );\n const morph = clamp(requested, MIN_MORPH, MAX_MORPH);\n const highlight = options.highlight !== false;\n const steps = stepsOf(options.steps).map((step) => step.at);\n const starts: number[] = [];\n let ready = 0;\n for (const at of steps.slice(1)) {\n const start = Math.max(at, ready);\n starts.push(start);\n ready = start + morph;\n }\n const morphs = starts.map((start, index) => {\n const highlightStart = start + phase(ENTER_START, morph);\n const natural = highlightStart + RISE + SHOW;\n const next = index + 1 < starts.length ? starts[index + 1] : natural;\n const fallStart = Math.min(natural, next);\n return {\n from: index,\n to: index + 1,\n start,\n end: start + morph,\n highlightStart,\n fallStart,\n highlightEnd: fallStart + FALL,\n };\n });\n let settled = 0;\n if (morphs.length > 0) {\n const last = morphs[morphs.length - 1];\n settled = highlight ? Math.max(last.end, last.highlightEnd) : last.end;\n }\n return { morph, highlight, steps, morphs, settled, duration: settled + HOLD };\n}\n\nexport type CodeMorphTimeline = ReturnType<typeof getCodeMorphTimeline>;\n\nexport const codeMorphLength = getCodeMorphTimeline().settled;\n\nexport function getCodeMorphDuration(options: CodeMorphOptions = {}) {\n const speed = Math.max(0, finite(options.speed, codeMorphDefaults.speed));\n if (speed === 0) return 1;\n const { duration } = getCodeMorphTimeline(options);\n return Math.max(1, Math.ceil(duration / speed));\n}\n\nexport function getCodeMorphTime(\n frame: number,\n options: CodeMorphOptions = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, codeMorphDefaults.speed));\n return Math.max(0, finite(frame, 0)) * (30 / fps) * speed;\n}\n\nfunction rowsOf(count: number, opacity: (row: number) => number) {\n return Array.from({ length: count }, (_, row) => ({\n key: `${row}`,\n row,\n opacity: opacity(row),\n }));\n}\n\nfunction restingTokens(layout: CodeMorphLayout, version: number) {\n const { tokens } = layout.versions[version];\n return tokens.map(\n (token, j): CodeMorphRenderToken => ({\n key: `${version}:${j}`,\n text: token.text,\n kind: token.kind,\n role: \"rest\",\n line: token.line,\n col: token.col,\n opacity: 1,\n scale: 1,\n blur: 0,\n }),\n );\n}\n\nfunction morphFrame(\n layout: CodeMorphLayout,\n index: number,\n local: number,\n morph: number,\n) {\n const data = layout.morphs[index];\n const from = layout.versions[index];\n const to = layout.versions[index + 1];\n const blur = BLUR * layout.unit;\n const tokens: CodeMorphRenderToken[] = [];\n for (const [i, token] of from.tokens.entries()) {\n if (data.diff.fromTo[i] >= 0) continue;\n const rank = data.exitRank.get(token.line) ?? 0;\n const delay = phase(EXIT_SPREAD, morph) * rank;\n const progress = (local - delay) / phase(EXIT_DURATION, morph);\n if (progress >= 1) continue;\n const eased = easeOut(progress);\n tokens.push({\n key: `${index}>${i}`,\n text: token.text,\n kind: token.kind,\n role: \"exit\",\n line: token.line,\n col: token.col,\n opacity: 1 - eased,\n scale: 1 - SHRINK * eased,\n blur: blur * eased,\n });\n }\n const travel = (delay: number) =>\n (local - phase(MOVE_START, morph) - delay) / phase(MOVE_DURATION, morph);\n for (const [j, token] of to.tokens.entries()) {\n const i = data.diff.toFrom[j];\n if (i < 0) continue;\n const source = from.tokens[i];\n const still = source.line === token.line && source.col === token.col;\n const rank = data.moveRank.get(token.line) ?? 0;\n const progress = travel(phase(CASCADE, morph) * rank);\n const vertical = glide(unit01(progress / (1 - ARC)));\n const horizontal = glide(unit01((progress - ARC) / (1 - ARC)));\n tokens.push({\n key: `${index + 1}:${j}`,\n text: token.text,\n kind: token.kind,\n role: still ? \"stay\" : \"move\",\n line: source.line + (token.line - source.line) * vertical,\n col: source.col + (token.col - source.col) * horizontal,\n opacity: 1,\n scale: 1,\n blur: 0,\n });\n }\n for (const [j, token] of to.tokens.entries()) {\n if (data.diff.toFrom[j] >= 0) continue;\n const rank = data.enterRank.get(token.line) ?? 0;\n const start = phase(ENTER_START + ENTER_SPREAD * rank, morph);\n const progress = (local - start) / phase(ENTER_DURATION, morph);\n if (progress <= 0) continue;\n const eased = easeOut(progress);\n tokens.push({\n key: `${index + 1}:${j}`,\n text: token.text,\n kind: token.kind,\n role: \"enter\",\n line: token.line,\n col: token.col,\n opacity: eased,\n scale: GROW_FROM + (1 - GROW_FROM) * eased,\n blur: blur * (1 - eased),\n });\n }\n const shrinking = to.lines < from.lines;\n const lag = shrinking ? phase(CASCADE, morph) : 0;\n const grown = glide(unit01(travel(lag) / (1 - ARC)));\n const lines = from.lines + (to.lines - from.lines) * grown;\n const shared = Math.min(from.lines, to.lines);\n const lineNumbers = rowsOf(Math.max(from.lines, to.lines), (row) => {\n if (row < shared) return 1;\n return shrinking ? 1 - grown : grown;\n });\n return { tokens, lines, lineNumbers };\n}\n\nfunction highlightsAt(\n time: number,\n timeline: CodeMorphTimeline,\n layout: CodeMorphLayout,\n active: number,\n) {\n const rows: CodeMorphRow[] = [];\n if (!timeline.highlight) return rows;\n for (const index of [active - 1, active]) {\n if (index < 0) continue;\n const morph = timeline.morphs[index];\n const rise = easeOutQuad((time - morph.highlightStart) / RISE);\n const fall = smoothstep((time - morph.fallStart) / FALL);\n const opacity = rise * (1 - fall);\n if (opacity <= 0) continue;\n for (const row of layout.morphs[index].changed) {\n rows.push({ key: `${index}:${row}`, row, opacity });\n }\n }\n return rows;\n}\n\nexport function getCodeMorphState(\n frame: number,\n options: CodeMorphOptions = {},\n layout: CodeMorphLayout = getCodeMorphLayout(options),\n): CodeMorphState {\n const timeline = getCodeMorphTimeline(options);\n const time = getCodeMorphTime(frame, options);\n let active = -1;\n for (const [index, morph] of timeline.morphs.entries()) {\n if (morph.start <= time) active = index;\n }\n const highlights = highlightsAt(time, timeline, layout, active);\n if (active === -1) {\n const lines = layout.versions[0].lines;\n return {\n time,\n version: 0,\n morphing: false,\n progress: 0,\n lines,\n tokens: restingTokens(layout, 0),\n lineNumbers: rowsOf(lines, () => 1),\n highlights,\n };\n }\n const local = time - timeline.morphs[active].start;\n if (local >= timeline.morph) {\n const version = active + 1;\n const lines = layout.versions[version].lines;\n return {\n time,\n version,\n morphing: false,\n progress: 1,\n lines,\n tokens: restingTokens(layout, version),\n lineNumbers: rowsOf(lines, () => 1),\n highlights,\n };\n }\n const motion = morphFrame(layout, active, local, timeline.morph);\n return {\n time,\n version: active + 1,\n morphing: true,\n progress: local / timeline.morph,\n lines: motion.lines,\n tokens: motion.tokens,\n lineNumbers: motion.lineNumbers,\n highlights,\n };\n}\n\nfunction transformOf(token: CodeMorphRenderToken, lineHeight: number) {\n const move = `translate(${token.col}ch, ${token.line * lineHeight}px)`;\n return token.scale === 1 ? move : `${move} scale(${token.scale})`;\n}\n\nexport function CodeMorph({\n steps = codeMorphDefaults.steps,\n morphDuration = codeMorphDefaults.morphDuration,\n highlight = codeMorphDefaults.highlight,\n fontSize = codeMorphDefaults.fontSize,\n lineNumbers = codeMorphDefaults.lineNumbers,\n filename = codeMorphDefaults.filename,\n windowDots = codeMorphDefaults.windowDots,\n theme = codeMorphDefaults.theme,\n accentColor = codeMorphDefaults.accentColor,\n speed = codeMorphDefaults.speed,\n className,\n}: CodeMorphProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const layout = useMemo(() => {\n const shape = { steps, fontSize, lineNumbers, filename, windowDots };\n return getCodeMorphLayout({ ...shape, width, height });\n }, [steps, fontSize, lineNumbers, filename, windowDots, width, height]);\n const motion = { steps, morphDuration, highlight, speed, fps };\n const state = getCodeMorphState(frame, motion, layout);\n const palette = theme === \"light\" ? PALETTES.light : PALETTES.dark;\n const unit = layout.unit;\n const hairline = Math.max(1, unit);\n const edge = `${hairline}px solid ${palette.border}`;\n const top = layout.header + layout.padTop;\n const blend = `${palette.share}%, ${palette.mix}`;\n const accentText = `color-mix(in oklab, ${accentColor} ${blend})`;\n const colorOf = (kind: CodeMorphKind) =>\n kind === \"string\" || kind === \"number\" ? accentText : palette[kind];\n const panelColumns = `${layout.gutter + layout.columns}ch`;\n const panelPadding = layout.padLeft + layout.padRight;\n const codeLeft = `${layout.gutter}ch`;\n const tabLeft = (layout.windowDots ? TAB_AFTER_DOTS : TAB_LEFT) * unit;\n const tabRadius = TAB_RADIUS * unit;\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n >\n <div\n style={{\n position: \"relative\",\n flexShrink: 0,\n boxSizing: \"content-box\",\n width: `calc(${panelColumns} + ${panelPadding}px)`,\n height: top + layout.rows * layout.lineHeight + layout.padBottom,\n background: palette.panel,\n color: palette.text,\n border: edge,\n borderRadius: RADIUS * unit,\n overflow: \"hidden\",\n fontFamily: FONT_MONO,\n fontSize: layout.fontSize,\n lineHeight: `${layout.lineHeight}px`,\n fontVariantLigatures: \"none\",\n fontKerning: \"none\",\n }}\n >\n {layout.header > 0 ? (\n <div\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n right: 0,\n height: layout.header,\n background: palette.chrome,\n }}\n >\n <div\n style={{\n position: \"absolute\",\n left: 0,\n right: 0,\n bottom: 0,\n height: hairline,\n background: palette.border,\n }}\n />\n {layout.windowDots\n ? DOTS.map((dot) => (\n <div\n key={dot}\n style={{\n position: \"absolute\",\n left: (DOT_LEFT + dot * (DOT + DOT_GAP)) * unit,\n top: ((HEADER - DOT) / 2) * unit,\n width: DOT * unit,\n height: DOT * unit,\n borderRadius: \"50%\",\n background: palette.dot,\n }}\n />\n ))\n : null}\n {layout.filename !== \"\" ? (\n <div\n style={{\n position: \"absolute\",\n left: tabLeft,\n bottom: 0,\n height: (HEADER - TAB_TOP) * unit,\n boxSizing: \"border-box\",\n display: \"flex\",\n alignItems: \"center\",\n padding: `0 ${TAB_PAD * unit}px`,\n background: palette.panel,\n borderTop: edge,\n borderLeft: edge,\n borderRight: edge,\n borderRadius: `${tabRadius}px ${tabRadius}px 0 0`,\n color: palette.label,\n fontSize: TAB_FONT * unit,\n lineHeight: 1,\n whiteSpace: \"pre\",\n }}\n >\n {layout.filename}\n </div>\n ) : null}\n </div>\n ) : null}\n {state.highlights.map((band) => (\n <div\n key={band.key}\n style={{\n position: \"absolute\",\n left: 0,\n right: 0,\n top: top + band.row * layout.lineHeight,\n height: layout.lineHeight,\n }}\n >\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n background: accentColor,\n opacity: band.opacity * palette.band,\n }}\n />\n <div\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n bottom: 0,\n width: BAR * unit,\n background: accentColor,\n opacity: band.opacity,\n }}\n />\n </div>\n ))}\n <div style={{ position: \"absolute\", left: layout.padLeft, top }}>\n {layout.lineNumbers\n ? state.lineNumbers.map((row) => (\n <div\n key={row.key}\n style={{\n position: \"absolute\",\n left: 0,\n top: row.row * layout.lineHeight,\n width: `${layout.digits}ch`,\n textAlign: \"right\",\n whiteSpace: \"pre\",\n color: palette.gutter,\n opacity: row.opacity,\n }}\n >\n {row.row + 1}\n </div>\n ))\n : null}\n <div style={{ position: \"absolute\", left: codeLeft, top: 0 }}>\n {state.tokens.map((token) => (\n <span\n key={token.key}\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n display: \"block\",\n whiteSpace: \"pre\",\n color: colorOf(token.kind),\n opacity: token.opacity,\n transform: transformOf(token, layout.lineHeight),\n filter: token.blur > 0 ? `blur(${token.blur}px)` : undefined,\n }}\n >\n {token.text}\n </span>\n ))}\n </div>\n </div>\n </div>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/code-morph.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/echo-stack.json b/registry-artifacts/echo-stack.jsonnew file mode 100644index 00000000..848388d9--- /dev/null+++ b/registry-artifacts/echo-stack.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "echo-stack",+ "title": "Echo Stack",+ "description": "A word focuses in at the center while outline copies of it unfold above and below and keep drifting, like the one clear line on a spinning drum.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/echo-stack/index.tsx",+ "content": "\"use client\";\n\nimport { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { useId } from \"react\";\nimport { Easing, interpolate, useCurrentFrame, useVideoConfig } from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\nexport type EchoStackDirection = \"up\" | \"down\";\n\nexport interface EchoStackProps {\n text?: string;\n fontSize?: number;\n fontWeight?: number;\n fontFamily?: string;\n color?: string;\n echoColor?: string;\n echoes?: number;\n echoOpacity?: number;\n strokeWidth?: number;\n direction?: EchoStackDirection;\n cycle?: number;\n speed?: number;\n className?: string;\n}\n\nexport const echoStackDefaults = {\n text: \"Bold.\",\n fontSize: 170,\n fontWeight: 800,\n fontFamily: INTER,\n color: \"#fafafa\",\n echoColor: \"\",\n echoes: 3,\n echoOpacity: 0.35,\n strokeWidth: 1.5,\n direction: \"up\",\n cycle: 60,\n speed: 1,\n} satisfies Required<Omit<EchoStackProps, \"className\">>;\n\n/** Frame where the entrance has finished; the drift keeps running after it. */\nexport const echoStackLength = 26;\n\n/** Distance between echo rows, in em. */\nexport const echoStackPitch = 1.05;\n\n/** Echoes closer to the center than this, in pitches, hide behind the word. */\nconst HIDDEN = 0.55;\nconst MAIN = [0, 14] as const;\nconst UNFOLD = [8, 26] as const;\nconst FADE_IN = [8, 24] as const;\nconst START_SPREAD = 0.6;\nconst MAX_BLUR = 12;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutCubic = Easing.out(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\nfunction smoothstep(x: number) {\n const c = Math.min(1, Math.max(0, x));\n return c * c * (3 - 2 * c);\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nexport function getEchoStackTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\n/** The main word focusing in. Blur is in reference px. */\nexport function getEchoStackMain(t: number) {\n const k = interpolate(t, [...MAIN], [0, 1], {\n ...CLAMP,\n easing: easeOutCubic,\n });\n return { blur: MAX_BLUR * (1 - k), opacity: k, scale: 1.04 - 0.04 * k };\n}\n\n/** Echo visibility at a distance from the center, in pitches, before `echoOpacity`. */\nexport function getEchoStackFade(distance: number, echoes: number) {\n const d = Math.abs(distance);\n if (d < HIDDEN) return 0;\n if (d < 1) return smoothstep((d - HIDDEN) / (1 - HIDDEN));\n const reach = Math.max(1, echoes + 0.5);\n return Math.max(0, 1 - (d - 1) / (reach - 1));\n}\n\nexport interface EchoStackRow {\n /** Signed distance from the center in pitches, negative above. */\n offset: number;\n /** Row position in pitches after the unfold, negative above. */\n position: number;\n opacity: number;\n}\n\nexport function getEchoStackRows(\n t: number,\n options: {\n echoes?: number;\n echoOpacity?: number;\n cycle?: number;\n direction?: EchoStackDirection;\n } = {},\n): EchoStackRow[] {\n const echoes = Math.max(0, Math.round(finite(options.echoes, 3)));\n const echoOpacity = Math.max(0, finite(options.echoOpacity, 0.35));\n const cycle = Math.max(1, finite(options.cycle, 60));\n const sign = options.direction === \"down\" ? 1 : -1;\n const phase = sign * ((t / cycle) % 1);\n const spread = interpolate(t, [...UNFOLD], [START_SPREAD, 1], {\n ...CLAMP,\n easing: easeOutCubic,\n });\n const fadeIn = interpolate(t, [...FADE_IN], [0, 1], {\n ...CLAMP,\n easing: easeOutCubic,\n });\n const rows: EchoStackRow[] = [];\n const reach = echoes + 2;\n for (let k = -reach; k <= reach; k++) {\n const offset = k + phase;\n const opacity = echoOpacity * fadeIn * getEchoStackFade(offset, echoes);\n if (opacity <= 0) continue;\n rows.push({ offset, position: offset * spread, opacity });\n }\n return rows;\n}\n\nexport function EchoStack({\n text = echoStackDefaults.text,\n fontSize = echoStackDefaults.fontSize,\n fontWeight = echoStackDefaults.fontWeight,\n fontFamily = echoStackDefaults.fontFamily,\n color = echoStackDefaults.color,\n echoColor = echoStackDefaults.echoColor,\n echoes = echoStackDefaults.echoes,\n echoOpacity = echoStackDefaults.echoOpacity,\n strokeWidth = echoStackDefaults.strokeWidth,\n direction = echoStackDefaults.direction,\n cycle = echoStackDefaults.cycle,\n speed = echoStackDefaults.speed,\n className,\n}: EchoStackProps) {\n const frame = useCurrentFrame();\n const { fps, height } = useVideoConfig();\n const unit = height / 720;\n const size = fontSize * unit;\n const t = getEchoStackTime(frame, { fps, speed });\n const main = getEchoStackMain(t);\n const rows = getEchoStackRows(t, { echoes, echoOpacity, cycle, direction });\n const pitch = echoStackPitch * size;\n const outlineId = `echo-stack-${useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`;\n\n const type = {\n fontFamily,\n fontSize: size,\n lineHeight: 1,\n fontWeight,\n fontVariationSettings: `\"wght\" ${fontWeight}`,\n whiteSpace: \"pre\",\n } as const;\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n }}\n >\n {/* Outline from the filled silhouette: the variable font's overlapping\n contours would show through a text stroke. */}\n <svg width={0} height={0} style={{ position: \"absolute\" }} aria-hidden>\n <defs>\n <filter id={outlineId}>\n <feMorphology\n in=\"SourceAlpha\"\n operator=\"erode\"\n radius={strokeWidth * unit}\n result=\"inner\"\n />\n <feComposite\n in=\"SourceAlpha\"\n in2=\"inner\"\n operator=\"out\"\n result=\"ring\"\n />\n <feFlood floodColor={echoColor || color} />\n <feComposite in2=\"ring\" operator=\"in\" />\n </filter>\n </defs>\n </svg>\n <div style={{ position: \"relative\" }}>\n {rows.map((row, i) => (\n <div\n key={i}\n aria-hidden\n style={{\n ...type,\n position: \"absolute\",\n left: \"50%\",\n top: \"50%\",\n color: echoColor || color,\n filter: `url(#${outlineId})`,\n opacity: row.opacity,\n transform: `translate(-50%, calc(-50% + ${row.position * pitch}px))`,\n }}\n >\n {text}\n </div>\n ))}\n <div\n style={{\n ...type,\n position: \"relative\",\n color,\n opacity: main.opacity,\n filter:\n main.blur > 0.05 ? `blur(${main.blur * unit}px)` : undefined,\n transform: `scale(${main.scale})`,\n }}\n >\n {text}\n </div>\n </div>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/echo-stack.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/elements/bauhaus-build.json b/registry-artifacts/elements/bauhaus-build.jsonnew file mode 100644index 00000000..2a2cff9a--- /dev/null+++ b/registry-artifacts/elements/bauhaus-build.json@@ -0,0 +1,14 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [],+ "dimensions": null,+ "displayName": "Bauhaus Build",+ "durationInFrames": 125,+ "installationMode": "component-owned-sequence",+ "slug": "bauhaus-build",+ "sourceCode": "import { Easing, Interactive, Sequence, random, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\nimport { forwardRef, useImperativeHandle, useRef, type ComponentProps } from \"react\";\n\ntype BauhausShape =\n | \"circle\"\n | \"square\"\n | \"semicircle\"\n | \"quarter\"\n | \"bar\";\n\ntype BauhausRole = \"ink\" | \"accent\" | \"secondary\" | \"tertiary\";\n\ntype TumbleDirection = \"U\" | \"D\" | \"L\" | \"R\";\n\ntype TumbleMove = `${TumbleDirection}${\"+\" | \"-\"}`;\n\ninterface BauhausPose {\n turn: number;\n x: number;\n y: number;\n}\n\ninterface BauhausPoint {\n x: number;\n y: number;\n}\n\ninterface BauhausFootprint {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n}\n\ninterface BauhausPiece {\n id: string;\n shape: BauhausShape;\n width: number;\n height: number;\n role: BauhausRole;\n slot: BauhausPose;\n enter: readonly TumbleMove[];\n rebuild: readonly TumbleMove[];\n cue: number;\n after: readonly string[];\n}\n\ninterface BauhausStep {\n move: TumbleMove;\n from: BauhausPose;\n to: BauhausPose;\n pivot: BauhausPoint;\n spin: 1 | -1;\n}\n\ninterface BauhausFrame {\n x: number;\n y: number;\n rotation: number;\n scale: number;\n pivot: BauhausPoint | null;\n}\n\ninterface BauhausPieceFrame extends BauhausFrame {\n id: string;\n shape: BauhausShape;\n role: BauhausRole;\n width: number;\n height: number;\n visible: boolean;\n}\n\ninterface BauhausBuildProps {\n scale?: number;\n seed?: number;\n inkColor?: string;\n accentColor?: string;\n secondaryColor?: string;\n tertiaryColor?: string;\n speed?: number;\n loop?: boolean;\n className?: string;\n}\n\ninterface TumbleRule {\n direction: TumbleDirection;\n spin: 1 | -1;\n reverse: TumbleMove;\n}\n\nconst bauhausBuildDefaults = {\n scale: 1,\n seed: 1,\n inkColor: \"#1c1a17\",\n accentColor: \"#e4572e\",\n secondaryColor: \"#cbbc9f\",\n tertiaryColor: \"#7e776b\",\n speed: 1,\n loop: false,\n};\n\nconst bauhausBuildGrid = 12;\nconst bauhausBuildBand = { top: 4, bottom: 8 };\nconst bauhausBuildLength = 125;\nconst bauhausBuildTimeline = {\n lead: 22,\n beat: 6,\n rebuild: 90,\n clear: 116,\n duration: 150,\n};\n\nconst bauhausBuildPieces: readonly BauhausPiece[] = [\n {\n id: \"hill\",\n shape: \"quarter\",\n width: 4,\n height: 4,\n role: \"ink\",\n slot: { turn: 3, x: 0, y: 4 },\n enter: [\"D-\", \"R+\"],\n rebuild: [\"D-\"],\n cue: 0,\n after: [\"tile\"],\n },\n {\n id: \"tile\",\n shape: \"square\",\n width: 1,\n height: 1,\n role: \"accent\",\n slot: { turn: 0, x: 4, y: 7 },\n enter: [\"U+\", \"U+\", \"U+\", \"U+\"],\n rebuild: [\"D+\"],\n cue: 3,\n after: [\"pillar\"],\n },\n {\n id: \"pillar\",\n shape: \"bar\",\n width: 4,\n height: 1,\n role: \"ink\",\n slot: { turn: 1, x: 5, y: 4 },\n enter: [\"R+\", \"R+\"],\n rebuild: [\"U+\"],\n cue: 6,\n after: [\"sun\"],\n },\n {\n id: \"sun\",\n shape: \"circle\",\n width: 4,\n height: 4,\n role: \"accent\",\n slot: { turn: 0, x: 6, y: 4 },\n enter: [\"U+\", \"U+\"],\n rebuild: [\"U-\"],\n cue: 9,\n after: [],\n },\n {\n id: \"dome\",\n shape: \"semicircle\",\n width: 2,\n height: 2,\n role: \"secondary\",\n slot: { turn: 3, x: 1, y: 1 },\n enter: [\"R+\", \"D-\"],\n rebuild: [\"R+\"],\n cue: 12,\n after: [\"pillar\"],\n },\n {\n id: \"post\",\n shape: \"bar\",\n width: 4,\n height: 1,\n role: \"tertiary\",\n slot: { turn: 1, x: 11, y: 4 },\n enter: [\"D+\", \"D+\"],\n rebuild: [\"D-\"],\n cue: 15,\n after: [],\n },\n {\n id: \"dot\",\n shape: \"circle\",\n width: 1,\n height: 1,\n role: \"ink\",\n slot: { turn: 0, x: 11, y: 3 },\n enter: [\"D-\", \"D-\", \"D-\", \"D-\"],\n rebuild: [\"L-\"],\n cue: 18,\n after: [\"post\"],\n },\n {\n id: \"block\",\n shape: \"square\",\n width: 2,\n height: 2,\n role: \"tertiary\",\n slot: { turn: 0, x: 6, y: 10 },\n enter: [\"U+\", \"U+\", \"U+\"],\n rebuild: [\"L+\"],\n cue: 21,\n after: [\"sun\"],\n },\n {\n id: \"fan\",\n shape: \"quarter\",\n width: 2,\n height: 2,\n role: \"secondary\",\n slot: { turn: 2, x: 8, y: 10 },\n enter: [\"L-\", \"L+\", \"L+\"],\n rebuild: [\"R+\"],\n cue: 24,\n after: [\"block\"],\n },\n];\n\nconst TURN = 5;\nconst FILL = 0.8;\nconst OVERSHOOT = 0.05;\nconst SETTLE = 0.5;\n\nconst MOVES: Record<TumbleMove, TumbleRule> = {\n \"U+\": { direction: \"U\", spin: 1, reverse: \"D-\" },\n \"U-\": { direction: \"U\", spin: -1, reverse: \"D+\" },\n \"D+\": { direction: \"D\", spin: 1, reverse: \"U-\" },\n \"D-\": { direction: \"D\", spin: -1, reverse: \"U+\" },\n \"L+\": { direction: \"L\", spin: 1, reverse: \"R-\" },\n \"L-\": { direction: \"L\", spin: -1, reverse: \"R+\" },\n \"R+\": { direction: \"R\", spin: 1, reverse: \"L-\" },\n \"R-\": { direction: \"R\", spin: -1, reverse: \"L+\" },\n};\n\nconst finite = (value: number, fallback: number) =>\n Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min = 0, max = 1) =>\n Math.min(max, Math.max(min, value));\nconst swing = Easing.bezier(0.62, 0, 0.3, 1);\nconst settle = Easing.bezier(0.45, 0, 0.55, 1);\n\nfunction seedKey(seed: number) {\n return Number.isFinite(seed) ? Math.round(seed) : 1;\n}\n\nfunction getBauhausFootprint(\n piece: Pick<BauhausPiece, \"width\" | \"height\">,\n pose: BauhausPose,\n): BauhausFootprint {\n const odd = pose.turn % 2 !== 0;\n return {\n x0: pose.x,\n y0: pose.y,\n x1: pose.x + (odd ? piece.height : piece.width),\n y1: pose.y + (odd ? piece.width : piece.height),\n };\n}\n\nfunction getTumblePivot(\n box: BauhausFootprint,\n move: TumbleMove,\n): BauhausPoint {\n const { direction, spin } = MOVES[move];\n const clockwise = spin === 1;\n switch (direction) {\n case \"R\":\n return { x: box.x1, y: clockwise ? box.y1 : box.y0 };\n case \"L\":\n return { x: box.x0, y: clockwise ? box.y0 : box.y1 };\n case \"D\":\n return { x: clockwise ? box.x0 : box.x1, y: box.y1 };\n default:\n return { x: clockwise ? box.x1 : box.x0, y: box.y0 };\n }\n}\n\nconst quarterTurn = (\n point: BauhausPoint,\n pivot: BauhausPoint,\n spin: 1 | -1,\n): BauhausPoint => ({\n x: pivot.x - spin * (point.y - pivot.y),\n y: pivot.y + spin * (point.x - pivot.x),\n});\n\nfunction tumble(\n piece: Pick<BauhausPiece, \"width\" | \"height\">,\n pose: BauhausPose,\n move: TumbleMove,\n): BauhausStep {\n const { spin } = MOVES[move];\n const box = getBauhausFootprint(piece, pose);\n const pivot = getTumblePivot(box, move);\n const a = quarterTurn({ x: box.x0, y: box.y0 }, pivot, spin);\n const b = quarterTurn({ x: box.x1, y: box.y1 }, pivot, spin);\n return {\n move,\n from: pose,\n to: {\n turn: (pose.turn + spin + 4) % 4,\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n },\n pivot,\n spin,\n };\n}\n\nfunction getBauhausPaths(piece: BauhausPiece) {\n const walk = (from: BauhausPose, moves: readonly TumbleMove[]) => {\n const steps: BauhausStep[] = [];\n let pose = from;\n for (const move of moves) {\n const step = tumble(piece, pose, move);\n steps.push(step);\n pose = step.to;\n }\n return steps;\n };\n let start = piece.slot;\n for (let index = piece.enter.length - 1; index >= 0; index--) {\n start = tumble(piece, start, MOVES[piece.enter[index]].reverse).to;\n }\n const rebuild = walk(piece.slot, piece.rebuild);\n return {\n start,\n enter: walk(start, piece.enter),\n rebuild,\n handoff: rebuild.at(-1)?.to ?? piece.slot,\n };\n}\n\nfunction getRestOffset(\n piece: Pick<BauhausPiece, \"width\" | \"height\">,\n turn: number,\n): BauhausPoint {\n switch (turn) {\n case 1:\n return { x: piece.height, y: 0 };\n case 2:\n return { x: piece.width, y: piece.height };\n case 3:\n return { x: 0, y: piece.width };\n default:\n return { x: 0, y: 0 };\n }\n}\n\nfunction getBauhausPoseFrame(\n piece: Pick<BauhausPiece, \"width\" | \"height\">,\n pose: BauhausPose,\n): BauhausFrame {\n const offset = getRestOffset(piece, pose.turn);\n return {\n x: pose.x + offset.x,\n y: pose.y + offset.y,\n rotation: pose.turn * 90,\n scale: 1,\n pivot: null,\n };\n}\n\nfunction getBauhausStepFrame(\n piece: Pick<BauhausPiece, \"width\" | \"height\">,\n step: BauhausStep,\n progress: number,\n grow = 1,\n): BauhausFrame {\n const rest = getBauhausPoseFrame(piece, step.from);\n const angle = (step.spin * progress * Math.PI) / 2;\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n const dx = rest.x - step.pivot.x;\n const dy = rest.y - step.pivot.y;\n return {\n x: step.pivot.x + grow * (dx * cos - dy * sin),\n y: step.pivot.y + grow * (dx * sin + dy * cos),\n rotation: rest.rotation + step.spin * progress * 90,\n scale: grow,\n pivot: step.pivot,\n };\n}\n\nfunction getTumbleDuration(\n piece: Pick<BauhausPiece, \"width\" | \"height\">,\n) {\n return TURN * Math.sqrt(Math.max(piece.width, piece.height));\n}\n\nfunction getTumbleProgress(\n elapsed: number,\n duration: number,\n landing: boolean,\n) {\n const t = clamp(elapsed / duration);\n if (!landing) return swing(t);\n if (elapsed <= duration) return (1 + OVERSHOOT) * swing(t);\n const back = clamp((elapsed - duration) / (duration * SETTLE));\n return 1 + OVERSHOOT * (1 - settle(back));\n}\n\nfunction getUnfoldScale(progress: number) {\n return 1 - (1 - clamp(progress)) ** 3;\n}\n\nfunction getPathFrame(\n piece: BauhausPiece,\n steps: readonly BauhausStep[],\n elapsed: number,\n unfold: boolean,\n): BauhausFrame {\n const duration = getTumbleDuration(piece);\n const last = steps.length - 1;\n const index = Math.min(last, Math.max(0, Math.floor(elapsed / duration)));\n const local = elapsed - index * duration;\n const landing = index === last;\n const step = steps[index];\n if (landing && local >= duration * (1 + SETTLE)) {\n return getBauhausPoseFrame(piece, step.to);\n }\n const grow = unfold && index === 0 ? getUnfoldScale(local / duration) : 1;\n const progress = getTumbleProgress(local, duration, landing);\n return getBauhausStepFrame(piece, step, progress, grow);\n}\n\nfunction getPieceMotion(\n piece: BauhausPiece,\n arrival: number,\n time: number,\n): BauhausFrame {\n const { lead, beat, rebuild } = bauhausBuildTimeline;\n const paths = getBauhausPaths(piece);\n const cue = rebuild + piece.cue;\n if (time >= cue && paths.rebuild.length > 0) {\n return getPathFrame(piece, paths.rebuild, time - cue, false);\n }\n if (paths.enter.length === 0) {\n return getBauhausPoseFrame(piece, piece.slot);\n }\n const travel = paths.enter.length * getTumbleDuration(piece);\n const start = lead + arrival * beat - travel;\n if (time < start) {\n return { ...getBauhausPoseFrame(piece, paths.start), scale: 0 };\n }\n return getPathFrame(piece, paths.enter, time - start, true);\n}\n\nfunction getBauhausBuildDuration({\n speed = bauhausBuildDefaults.speed,\n loop = bauhausBuildDefaults.loop,\n}: Pick<BauhausBuildProps, \"speed\" | \"loop\"> = {}) {\n const rate = finite(speed, 1);\n const frames = bauhausBuildTimeline.duration * (loop ? 2 : 1);\n return rate <= 0 ? 1 : Math.max(1, Math.ceil(frames / rate));\n}\n\nfunction getBauhausBuildOrder(seed = bauhausBuildDefaults.seed) {\n const key = seedKey(seed);\n const rank = (piece: BauhausPiece) =>\n random(`bauhaus-build-${key}-order-${piece.id}`);\n const placed: BauhausPiece[] = [];\n const waiting = [...bauhausBuildPieces];\n while (waiting.length > 0) {\n const ready = waiting.filter((piece) =>\n piece.after.every((id) => placed.some((done) => done.id === id)),\n );\n const next = ready.reduce((best, piece) =>\n rank(piece) < rank(best) ? piece : best,\n );\n placed.push(next);\n waiting.splice(waiting.indexOf(next), 1);\n }\n return placed;\n}\n\nfunction getBauhausBuildVariant(seed = bauhausBuildDefaults.seed) {\n const index = (((seedKey(seed) - 1) % 4) + 4) % 4;\n return { flipX: index % 2 === 1, flipY: index >= 2 };\n}\n\nfunction getPoster(scale: number, width: number, height: number) {\n const w = Math.max(1, finite(width, 1280));\n const h = Math.max(1, finite(height, 720));\n const size = Math.min(w, h) * FILL * clamp(finite(scale, 1), 0.5, 1.25);\n return { w, h, size, originX: (w - size) / 2, originY: (h - size) / 2 };\n}\n\nfunction getBauhausBuildField({\n scale = bauhausBuildDefaults.scale,\n width = 1280,\n height = 720,\n}: Pick<BauhausBuildProps, \"scale\"> & {\n width?: number;\n height?: number;\n} = {}) {\n const poster = getPoster(scale, width, height);\n const unit = poster.size / bauhausBuildGrid;\n return {\n x: 0,\n y: poster.originY + bauhausBuildBand.top * unit,\n width: poster.w,\n height: (bauhausBuildBand.bottom - bauhausBuildBand.top) * unit,\n unit,\n };\n}\n\nfunction getBauhausBuildState(\n time: number,\n {\n seed = bauhausBuildDefaults.seed,\n scale = bauhausBuildDefaults.scale,\n loop = bauhausBuildDefaults.loop,\n width = 1280,\n height = 720,\n }: Pick<BauhausBuildProps, \"seed\" | \"scale\" | \"loop\"> & {\n width?: number;\n height?: number;\n } = {},\n) {\n const { size, originX, originY } = getPoster(scale, width, height);\n const { duration } = bauhausBuildTimeline;\n const elapsed = Math.max(0, finite(time, 0));\n const folded = elapsed % (duration * 2);\n const local = loop ? Math.min(folded, duration * 2 - folded) : elapsed;\n const pieces = getBauhausBuildOrder(seed).map((piece, arrival) => {\n const motion = getPieceMotion(piece, arrival, local);\n const frame: BauhausPieceFrame = {\n id: piece.id,\n shape: piece.shape,\n role: piece.role,\n width: piece.width,\n height: piece.height,\n ...motion,\n visible: motion.scale > 0.001,\n };\n return frame;\n });\n return {\n time: local,\n size,\n unit: size / bauhausBuildGrid,\n originX,\n originY,\n ...getBauhausBuildVariant(seed),\n pieces,\n };\n}\n\nfunction getBauhausShapePath(\n shape: BauhausShape,\n width: number,\n height: number,\n) {\n const r = width / 2;\n switch (shape) {\n case \"circle\":\n return `M 0 ${r} A ${r} ${r} 0 1 1 ${width} ${r} A ${r} ${r} 0 1 1 0 ${r} Z`;\n case \"semicircle\":\n return `M 0 ${height} A ${r} ${r} 0 0 1 ${width} ${height} Z`;\n case \"quarter\":\n return `M 0 ${height} L 0 0 A ${width} ${height} 0 0 1 ${width} ${height} Z`;\n default:\n return `M 0 0 H ${width} V ${height} H 0 Z`;\n }\n}\n\nfunction BauhausBuildBase({\n scale = bauhausBuildDefaults.scale,\n seed = bauhausBuildDefaults.seed,\n inkColor = bauhausBuildDefaults.inkColor,\n accentColor = bauhausBuildDefaults.accentColor,\n secondaryColor = bauhausBuildDefaults.secondaryColor,\n tertiaryColor = bauhausBuildDefaults.tertiaryColor,\n speed = bauhausBuildDefaults.speed,\n loop = bauhausBuildDefaults.loop,\n className,\n}: BauhausBuildProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const time = frame * (30 / fps) * Math.max(0, finite(speed, 1));\n const state = getBauhausBuildState(time, {\n seed,\n scale,\n loop,\n width,\n height,\n });\n const fills: Record<BauhausRole, string> = {\n ink: inkColor,\n accent: accentColor,\n secondary: secondaryColor,\n tertiary: tertiaryColor,\n };\n const mirror = `translate(${state.flipX ? width : 0} ${state.flipY ? height : 0}) scale(${state.flipX ? -1 : 1} ${state.flipY ? -1 : 1})`;\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n role=\"img\"\n aria-label=\"Geometric Bauhaus composition\"\n style={{ display: \"block\" }}\n >\n <g transform={mirror}>\n {state.pieces.map((piece) =>\n piece.visible ? (\n <path\n key={piece.id}\n d={getBauhausShapePath(piece.shape, piece.width, piece.height)}\n fill={fills[piece.role]}\n transform={`translate(${state.originX + piece.x * state.unit} ${state.originY + piece.y * state.unit}) rotate(${piece.rotation}) scale(${piece.scale * state.unit})`}\n />\n ) : null,\n )}\n </g>\n </svg>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n scale: {\n type: \"number\",\n default: 1,\n min: 0.5,\n max: 1.25,\n step: 0.05,\n description: \"Scale\",\n hiddenFromList: false,\n },\n seed: {\n type: \"number\",\n default: 1,\n min: 1,\n max: 24,\n step: 1,\n description: \"Seed\",\n hiddenFromList: false,\n },\n inkColor: {\n type: \"color\",\n default: \"#1c1a17\",\n description: \"Ink\",\n },\n accentColor: {\n type: \"color\",\n default: \"#e4572e\",\n description: \"Accent\",\n },\n secondaryColor: {\n type: \"color\",\n default: \"#cbbc9f\",\n description: \"Secondary\",\n },\n tertiaryColor: {\n type: \"color\",\n default: \"#7e776b\",\n description: \"Tertiary\",\n },\n loop: {\n type: \"boolean\",\n default: false,\n description: \"Loop animation\",\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"scale\",\"seed\",\"inkColor\",\"accentColor\",\"secondaryColor\",\"tertiaryColor\",\"loop\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n scale: 1,\n seed: 1,\n inkColor: \"#1c1a17\",\n accentColor: \"#e4572e\",\n secondaryColor: \"#cbbc9f\",\n tertiaryColor: \"#7e776b\",\n loop: false,\n speed: 1,\n};\n\ntype BauhausBuildElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof BauhausBuildBase>;\n\nconst BauhausBuildInner = forwardRef<\n HTMLDivElement,\n BauhausBuildElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<BauhausBuild>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <BauhausBuildBase\n {...(componentProps as unknown as ComponentProps<typeof BauhausBuildBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const BauhausBuild = Interactive.withSchema({\n Component: BauhausBuildInner,\n componentName: \"<BauhausBuild>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 125+}diff --git a/registry-artifacts/elements/echo-stack.json b/registry-artifacts/elements/echo-stack.jsonnew file mode 100644index 00000000..43e2f992--- /dev/null+++ b/registry-artifacts/elements/echo-stack.json@@ -0,0 +1,19 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [+ {+ "name": "@remotion/google-fonts",+ "version": null+ }+ ],+ "dimensions": null,+ "displayName": "Echo Stack",+ "durationInFrames": 26,+ "installationMode": "component-owned-sequence",+ "slug": "echo-stack",+ "sourceCode": "import { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { forwardRef, useId, useImperativeHandle, useRef, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, interpolate, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\ntype EchoStackDirection = \"up\" | \"down\";\n\ninterface EchoStackProps {\n text?: string;\n fontSize?: number;\n fontWeight?: number;\n fontFamily?: string;\n color?: string;\n echoColor?: string;\n echoes?: number;\n echoOpacity?: number;\n strokeWidth?: number;\n direction?: EchoStackDirection;\n cycle?: number;\n speed?: number;\n className?: string;\n}\n\nconst echoStackDefaults = {\n text: \"Bold.\",\n fontSize: 170,\n fontWeight: 800,\n fontFamily: INTER,\n color: \"#fafafa\",\n echoColor: \"\",\n echoes: 3,\n echoOpacity: 0.35,\n strokeWidth: 1.5,\n direction: \"up\",\n cycle: 60,\n speed: 1,\n} satisfies Required<Omit<EchoStackProps, \"className\">>;\n\n/** Frame where the entrance has finished; the drift keeps running after it. */\nconst echoStackLength = 26;\n\n/** Distance between echo rows, in em. */\nconst echoStackPitch = 1.05;\n\n/** Echoes closer to the center than this, in pitches, hide behind the word. */\nconst HIDDEN = 0.55;\nconst MAIN = [0, 14] as const;\nconst UNFOLD = [8, 26] as const;\nconst FADE_IN = [8, 24] as const;\nconst START_SPREAD = 0.6;\nconst MAX_BLUR = 12;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutCubic = Easing.out(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\nfunction smoothstep(x: number) {\n const c = Math.min(1, Math.max(0, x));\n return c * c * (3 - 2 * c);\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nfunction getEchoStackTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\n/** The main word focusing in. Blur is in reference px. */\nfunction getEchoStackMain(t: number) {\n const k = interpolate(t, [...MAIN], [0, 1], {\n ...CLAMP,\n easing: easeOutCubic,\n });\n return { blur: MAX_BLUR * (1 - k), opacity: k, scale: 1.04 - 0.04 * k };\n}\n\n/** Echo visibility at a distance from the center, in pitches, before `echoOpacity`. */\nfunction getEchoStackFade(distance: number, echoes: number) {\n const d = Math.abs(distance);\n if (d < HIDDEN) return 0;\n if (d < 1) return smoothstep((d - HIDDEN) / (1 - HIDDEN));\n const reach = Math.max(1, echoes + 0.5);\n return Math.max(0, 1 - (d - 1) / (reach - 1));\n}\n\ninterface EchoStackRow {\n /** Signed distance from the center in pitches, negative above. */\n offset: number;\n /** Row position in pitches after the unfold, negative above. */\n position: number;\n opacity: number;\n}\n\nfunction getEchoStackRows(\n t: number,\n options: {\n echoes?: number;\n echoOpacity?: number;\n cycle?: number;\n direction?: EchoStackDirection;\n } = {},\n): EchoStackRow[] {\n const echoes = Math.max(0, Math.round(finite(options.echoes, 3)));\n const echoOpacity = Math.max(0, finite(options.echoOpacity, 0.35));\n const cycle = Math.max(1, finite(options.cycle, 60));\n const sign = options.direction === \"down\" ? 1 : -1;\n const phase = sign * ((t / cycle) % 1);\n const spread = interpolate(t, [...UNFOLD], [START_SPREAD, 1], {\n ...CLAMP,\n easing: easeOutCubic,\n });\n const fadeIn = interpolate(t, [...FADE_IN], [0, 1], {\n ...CLAMP,\n easing: easeOutCubic,\n });\n const rows: EchoStackRow[] = [];\n const reach = echoes + 2;\n for (let k = -reach; k <= reach; k++) {\n const offset = k + phase;\n const opacity = echoOpacity * fadeIn * getEchoStackFade(offset, echoes);\n if (opacity <= 0) continue;\n rows.push({ offset, position: offset * spread, opacity });\n }\n return rows;\n}\n\nfunction EchoStackBase({\n text = echoStackDefaults.text,\n fontSize = echoStackDefaults.fontSize,\n fontWeight = echoStackDefaults.fontWeight,\n fontFamily = echoStackDefaults.fontFamily,\n color = echoStackDefaults.color,\n echoColor = echoStackDefaults.echoColor,\n echoes = echoStackDefaults.echoes,\n echoOpacity = echoStackDefaults.echoOpacity,\n strokeWidth = echoStackDefaults.strokeWidth,\n direction = echoStackDefaults.direction,\n cycle = echoStackDefaults.cycle,\n speed = echoStackDefaults.speed,\n className,\n}: EchoStackProps) {\n const frame = useCurrentFrame();\n const { fps, height } = useVideoConfig();\n const unit = height / 720;\n const size = fontSize * unit;\n const t = getEchoStackTime(frame, { fps, speed });\n const main = getEchoStackMain(t);\n const rows = getEchoStackRows(t, { echoes, echoOpacity, cycle, direction });\n const pitch = echoStackPitch * size;\n const outlineId = `echo-stack-${useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`;\n\n const type = {\n fontFamily,\n fontSize: size,\n lineHeight: 1,\n fontWeight,\n fontVariationSettings: `\"wght\" ${fontWeight}`,\n whiteSpace: \"pre\",\n } as const;\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n }}\n >\n {/* Outline from the filled silhouette: the variable font's overlapping\n contours would show through a text stroke. */}\n <svg width={0} height={0} style={{ position: \"absolute\" }} aria-hidden>\n <defs>\n <filter id={outlineId}>\n <feMorphology\n in=\"SourceAlpha\"\n operator=\"erode\"\n radius={strokeWidth * unit}\n result=\"inner\"\n />\n <feComposite\n in=\"SourceAlpha\"\n in2=\"inner\"\n operator=\"out\"\n result=\"ring\"\n />\n <feFlood floodColor={echoColor || color} />\n <feComposite in2=\"ring\" operator=\"in\" />\n </filter>\n </defs>\n </svg>\n <div style={{ position: \"relative\" }}>\n {rows.map((row, i) => (\n <div\n key={i}\n aria-hidden\n style={{\n ...type,\n position: \"absolute\",\n left: \"50%\",\n top: \"50%\",\n color: echoColor || color,\n filter: `url(#${outlineId})`,\n opacity: row.opacity,\n transform: `translate(-50%, calc(-50% + ${row.position * pitch}px))`,\n }}\n >\n {text}\n </div>\n ))}\n <div\n style={{\n ...type,\n position: \"relative\",\n color,\n opacity: main.opacity,\n filter:\n main.blur > 0.05 ? `blur(${main.blur * unit}px)` : undefined,\n transform: `scale(${main.scale})`,\n }}\n >\n {text}\n </div>\n </div>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n text: {\n type: \"text-content\",\n default: \"Bold.\",\n description: \"Text\",\n },\n color: {\n type: \"color\",\n default: \"#fafafa\",\n description: \"Text color\",\n },\n echoColor: {\n type: \"color\",\n default: \"#fafafa\",\n description: \"Echo color\",\n },\n direction: {\n type: \"enum\",\n default: \"up\",\n variants: {\n up: {},\n down: {},\n },\n description: \"Direction\",\n },\n fontSize: {\n type: \"number\",\n default: 170,\n min: 60,\n max: 300,\n step: 2,\n description: \"Font size\",\n hiddenFromList: false,\n },\n echoes: {\n type: \"number\",\n default: 3,\n min: 1,\n max: 6,\n step: 1,\n description: \"Echoes per side\",\n hiddenFromList: false,\n },\n echoOpacity: {\n type: \"number\",\n default: 0.35,\n min: 0.05,\n max: 1,\n step: 0.05,\n description: \"Echo opacity\",\n hiddenFromList: false,\n },\n cycle: {\n type: \"number\",\n default: 60,\n min: 15,\n max: 240,\n step: 5,\n description: \"Frames per row\",\n hiddenFromList: false,\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"text\",\"color\",\"echoColor\",\"direction\",\"fontSize\",\"echoes\",\"echoOpacity\",\"cycle\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n text: \"Bold.\",\n color: \"#fafafa\",\n echoColor: \"#fafafa\",\n direction: \"up\",\n fontSize: 170,\n echoes: 3,\n echoOpacity: 0.35,\n cycle: 60,\n speed: 1,\n};\n\ntype EchoStackElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof EchoStackBase>;\n\nconst EchoStackInner = forwardRef<\n HTMLDivElement,\n EchoStackElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<EchoStack>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <EchoStackBase\n {...(componentProps as unknown as ComponentProps<typeof EchoStackBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const EchoStack = Interactive.withSchema({\n Component: EchoStackInner,\n componentName: \"<EchoStack>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 26+}diff --git a/registry-artifacts/elements/glyph-anatomy.json b/registry-artifacts/elements/glyph-anatomy.jsonnew file mode 100644index 00000000..1c5eaf2a--- /dev/null+++ b/registry-artifacts/elements/glyph-anatomy.json@@ -0,0 +1,23 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [+ {+ "name": "opentype.js",+ "version": "2.0.0"+ },+ {+ "name": "@remotion/google-fonts",+ "version": null+ }+ ],+ "dimensions": null,+ "displayName": "Glyph Anatomy",+ "durationInFrames": 66,+ "installationMode": "component-owned-sequence",+ "slug": "glyph-anatomy",+ "sourceCode": "import { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { parse, type Font } from \"opentype.js\";\nimport { forwardRef, useEffect, useImperativeHandle, useRef, useState, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, continueRender, delayRender, interpolate, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"500\"],\n subsets: [\"latin\"],\n});\n\ninterface GlyphAnatomyProps {\n text?: string;\n fontUrl?: string;\n fontSize?: number;\n color?: string;\n guideColor?: string;\n guides?: boolean;\n keepPoints?: boolean;\n speed?: number;\n className?: string;\n}\n\n/** Static Inter ExtraBold (800) from Google Fonts. */\nconst interExtraBoldTtf =\n \"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuDyYMZg.ttf\";\n\nconst glyphAnatomyDefaults = {\n text: \"Glyph\",\n fontUrl: interExtraBoldTtf,\n fontSize: 200,\n color: \"#fafafa\",\n guideColor: \"#0d99ff\",\n guides: true,\n keepPoints: false,\n speed: 1,\n} satisfies Required<Omit<GlyphAnatomyProps, \"className\">>;\n\n/** Beats on the 30 fps clock. Letter beats shift by `letterStagger × i`. */\nconst glyphAnatomyTiming = {\n guideStart: 0,\n guideStagger: 3,\n guideDraw: 10,\n anchors: [8, 22],\n anchorPop: 4,\n pull: [18, 40],\n pullDuration: 8,\n fill: [40, 50],\n fade: [46, 58],\n letterStagger: 2,\n} as const;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutCubic = Easing.out(Easing.cubic);\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\nconst popEase = Easing.out(Easing.back(1.7));\nconst pullEase = Easing.out(Easing.back(1.6));\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nfunction getGlyphAnatomyTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\ninterface Point {\n x: number;\n y: number;\n}\n\ninterface AnatomySegment {\n from: Point;\n to: Point;\n /** Cubic handles; absent on straight segments. */\n c1?: Point;\n c2?: Point;\n}\n\ninterface PathCommand {\n type: string;\n x?: number;\n y?: number;\n x1?: number;\n y1?: number;\n x2?: number;\n y2?: number;\n}\n\nconst lerp = (a: Point, b: Point, k: number): Point => ({\n x: a.x + (b.x - a.x) * k,\n y: a.y + (b.y - a.y) * k,\n});\n\n/**\n * Turns glyph path commands into contours of explicit segments. Quadratic\n * curves become cubics (handles at ⅔ toward the control point), so every\n * curve shows one handle on each end, as in Figma or Glyphs.\n */\nfunction getAnatomyContours(\n commands: readonly PathCommand[],\n): AnatomySegment[][] {\n const contours: AnatomySegment[][] = [];\n let segments: AnatomySegment[] = [];\n let start: Point | null = null;\n let at: Point | null = null;\n const close = () => {\n if (start && at && (at.x !== start.x || at.y !== start.y)) {\n segments.push({ from: at, to: start });\n }\n if (segments.length > 0) contours.push(segments);\n segments = [];\n start = null;\n at = null;\n };\n for (const c of commands) {\n const to = { x: c.x ?? 0, y: c.y ?? 0 };\n if (c.type === \"M\") {\n close();\n start = to;\n at = to;\n } else if (!at) {\n } else if (c.type === \"L\") {\n segments.push({ from: at, to });\n at = to;\n } else if (c.type === \"Q\") {\n const q = { x: c.x1 ?? 0, y: c.y1 ?? 0 };\n segments.push({\n from: at,\n to,\n c1: lerp(at, q, 2 / 3),\n c2: lerp(to, q, 2 / 3),\n });\n at = to;\n } else if (c.type === \"C\") {\n segments.push({\n from: at,\n to,\n c1: { x: c.x1 ?? 0, y: c.y1 ?? 0 },\n c2: { x: c.x2 ?? 0, y: c.y2 ?? 0 },\n });\n at = to;\n } else if (c.type === \"Z\") {\n close();\n }\n }\n close();\n return contours;\n}\n\n/**\n * How far each handle has travelled from its anchor to its place, 0 → 1 with\n * overshoot. At 0 the curve is its chord.\n */\nfunction getGlyphAnatomyPull(t: number, order: number, total: number) {\n const { pull, pullDuration } = glyphAnatomyTiming;\n const span = pull[1] - pull[0] - pullDuration;\n const start = pull[0] + (total > 1 ? (span * order) / (total - 1) : 0);\n return interpolate(t, [start, start + pullDuration], [0, 1], {\n ...CLAMP,\n easing: pullEase,\n });\n}\n\n/** Scale of anchor `order` of `total` popping in along the letter's path. */\nfunction getGlyphAnatomyAnchor(t: number, order: number, total: number) {\n const { anchors, anchorPop } = glyphAnatomyTiming;\n const span = anchors[1] - anchors[0] - anchorPop;\n const start = anchors[0] + (total > 1 ? (span * order) / (total - 1) : 0);\n return Math.max(\n 0,\n interpolate(t, [start, start + anchorPop], [0, 1], {\n ...CLAMP,\n easing: popEase,\n }),\n );\n}\n\n/** Letter-level fades: outline in, fill in, scaffolding out. */\nfunction getGlyphAnatomyLetter(t: number) {\n const { anchors, fill, fade } = glyphAnatomyTiming;\n return {\n outline: interpolate(t, [anchors[0], anchors[0] + 4], [0, 1], CLAMP),\n fill: interpolate(t, [...fill], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n scaffold: interpolate(t, [...fade], [1, 0], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n };\n}\n\n/** Draw progress of guide `index`, 0..1. */\nfunction getGlyphAnatomyGuide(t: number, index: number) {\n const { guideStart, guideStagger, guideDraw } = glyphAnatomyTiming;\n const start = guideStart + guideStagger * index;\n return interpolate(t, [start, start + guideDraw], [0, 1], {\n ...CLAMP,\n easing: easeOutCubic,\n });\n}\n\n/** Frame where the scaffolding of the last of `count` letters has faded. */\nfunction getGlyphAnatomyLength(count: number) {\n const { fade, letterStagger } = glyphAnatomyTiming;\n return fade[1] + letterStagger * Math.max(0, count - 1);\n}\n\n/** Path data for a contour with each handle pulled `k(segment)` of the way. */\nfunction getAnatomyPath(\n segments: readonly AnatomySegment[],\n pullOf: (index: number) => number,\n) {\n if (segments.length === 0) return \"\";\n const f = (p: Point) => `${p.x.toFixed(2)} ${p.y.toFixed(2)}`;\n let d = `M${f(segments[0].from)}`;\n segments.forEach((s, i) => {\n if (s.c1 && s.c2) {\n const k = pullOf(i);\n d += `C${f(lerp(s.from, s.c1, k))} ${f(lerp(s.to, s.c2, k))} ${f(s.to)}`;\n } else {\n d += `L${f(s.to)}`;\n }\n });\n return `${d}Z`;\n}\n\ninterface AnatomyLetter {\n contours: AnatomySegment[][];\n}\n\nfunction layout(font: Font, text: string, fontSize: number) {\n const scale = fontSize / font.unitsPerEm;\n // Per-character lookup: full shaping runs GSUB lookups that opentype.js\n // does not support in every font.\n const glyphs = Array.from(text).map((char) => font.charToGlyph(char));\n let x = 0;\n const letters: AnatomyLetter[] = glyphs.map((glyph, i) => {\n if (i > 0) x += font.getKerningValue(glyphs[i - 1], glyph) * scale;\n const contours = getAnatomyContours(glyph.getPath(x, 0, fontSize).commands);\n x += (glyph.advanceWidth ?? 0) * scale;\n return { contours };\n });\n const os2 = font.tables.os2 as\n | { sCapHeight?: number; sxHeight?: number }\n | undefined;\n const em = (v: number | undefined, fallback: number) =>\n ((v ?? fallback * font.unitsPerEm) * fontSize) / font.unitsPerEm;\n return {\n letters,\n width: x,\n capHeight: em(os2?.sCapHeight, 0.7),\n xHeight: em(os2?.sxHeight, 0.5),\n descender: (-font.descender * fontSize) / font.unitsPerEm,\n };\n}\n\nconst fontCache = new Map<string, Promise<Font>>();\n\nfunction loadAnatomyFont(url: string) {\n let pending = fontCache.get(url);\n if (!pending) {\n pending = fetch(url)\n .then((res) => res.arrayBuffer())\n .then((buffer) => parse(buffer));\n fontCache.set(url, pending);\n pending.catch(() => fontCache.delete(url));\n }\n return pending;\n}\n\nfunction useAnatomyFont(url: string) {\n const [font, setFont] = useState<Font | null>(null);\n\n useEffect(() => {\n const handle = delayRender(`glyph-anatomy: loading ${url}`);\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n continueRender(handle);\n };\n loadAnatomyFont(url).then((parsed) => {\n if (!released) setFont(parsed);\n release();\n }, release);\n return release;\n }, [url]);\n\n return font;\n}\n\nfunction GlyphAnatomyBase({\n text = glyphAnatomyDefaults.text,\n fontUrl = glyphAnatomyDefaults.fontUrl,\n fontSize = glyphAnatomyDefaults.fontSize,\n color = glyphAnatomyDefaults.color,\n guideColor = glyphAnatomyDefaults.guideColor,\n guides = glyphAnatomyDefaults.guides,\n keepPoints = glyphAnatomyDefaults.keepPoints,\n speed = glyphAnatomyDefaults.speed,\n className,\n}: GlyphAnatomyProps) {\n const frame = useCurrentFrame();\n const { fps, width, height } = useVideoConfig();\n const font = useAnatomyFont(fontUrl);\n if (!font) return null;\n\n const unit = height / 720;\n const t = getGlyphAnatomyTime(frame, { fps, speed });\n const word = layout(font, text, fontSize);\n const originX = (width - word.width * unit) / 2;\n const baseline = (height + word.capHeight * unit) / 2;\n const hair = 1.25;\n const anchorSize = 6;\n const handleRadius = 2.6;\n const margin = 0.3 * fontSize;\n // Guides fade with the last letter's scaffolding.\n const lastStart =\n glyphAnatomyTiming.letterStagger * Math.max(0, word.letters.length - 1);\n const scaffoldAll = keepPoints\n ? 1\n : getGlyphAnatomyLetter(t - lastStart).scaffold;\n\n const guideLines = [\n { label: \"Cap height\", y: -word.capHeight },\n { label: \"x-height\", y: -word.xHeight },\n { label: \"Baseline\", y: 0 },\n { label: \"Descender\", y: word.descender },\n ];\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n style={{ display: \"block\" }}\n >\n <g transform={`translate(${originX} ${baseline}) scale(${unit})`}>\n {guides\n ? guideLines.map((guide, i) => {\n const draw = getGlyphAnatomyGuide(t, i);\n if (draw <= 0) return null;\n const length = word.width + 2 * margin;\n return (\n <g key={guide.label} opacity={0.7 * scaffoldAll}>\n <line\n x1={-margin}\n x2={-margin + length * draw}\n y1={guide.y}\n y2={guide.y}\n stroke={guideColor}\n strokeWidth={hair * 0.8}\n />\n <text\n x={-margin}\n y={guide.y - 5}\n fill={guideColor}\n fontFamily={INTER}\n fontSize={11}\n fontWeight={500}\n opacity={draw}\n >\n {guide.label}\n </text>\n </g>\n );\n })\n : null}\n {word.letters.map((letter, i) => {\n const lt = t - glyphAnatomyTiming.letterStagger * i;\n const state = getGlyphAnatomyLetter(lt);\n const scaffold = keepPoints ? 1 : state.scaffold;\n const curves = letter.contours.flatMap((segments, c) =>\n segments.flatMap((s, k) => (s.c1 ? [`${c}:${k}`] : [])),\n );\n const curveOrder = new Map(curves.map((key, n) => [key, n]));\n const anchors = letter.contours.flatMap((segments) =>\n segments.map((s) => s.from),\n );\n const pullOf = (c: number) => (k: number) =>\n getGlyphAnatomyPull(\n lt,\n curveOrder.get(`${c}:${k}`) ?? 0,\n curves.length,\n );\n const paths = letter.contours.map((segments, c) =>\n getAnatomyPath(segments, pullOf(c)),\n );\n let anchorIndex = 0;\n return (\n <g key={i}>\n {state.fill > 0 ? (\n <path d={paths.join(\"\")} fill={color} opacity={state.fill} />\n ) : null}\n {state.outline > 0 && scaffold > 0 ? (\n <g opacity={scaffold}>\n {paths.map((d, c) => (\n <path\n key={c}\n d={d}\n fill=\"none\"\n stroke={color}\n strokeWidth={hair}\n opacity={state.outline}\n />\n ))}\n {letter.contours.map((segments, c) =>\n segments.map((s, k) => {\n if (!s.c1 || !s.c2) return null;\n const pull = pullOf(c)(k);\n if (pull <= 0) return null;\n const h1 = lerp(s.from, s.c1, pull);\n const h2 = lerp(s.to, s.c2, pull);\n return (\n <g key={`${c}-${k}`}>\n <line\n x1={s.from.x}\n y1={s.from.y}\n x2={h1.x}\n y2={h1.y}\n stroke={guideColor}\n strokeWidth={hair * 0.8}\n />\n <line\n x1={s.to.x}\n y1={s.to.y}\n x2={h2.x}\n y2={h2.y}\n stroke={guideColor}\n strokeWidth={hair * 0.8}\n />\n <circle\n cx={h1.x}\n cy={h1.y}\n r={handleRadius}\n fill={guideColor}\n />\n <circle\n cx={h2.x}\n cy={h2.y}\n r={handleRadius}\n fill={guideColor}\n />\n </g>\n );\n }),\n )}\n {letter.contours.map((segments, c) =>\n segments.map((s, k) => {\n const scale = getGlyphAnatomyAnchor(\n lt,\n anchorIndex++,\n anchors.length,\n );\n if (scale <= 0) return null;\n const size = anchorSize * scale;\n return (\n <rect\n key={`${c}-${k}`}\n x={s.from.x - size / 2}\n y={s.from.y - size / 2}\n width={size}\n height={size}\n fill=\"#ffffff\"\n stroke={guideColor}\n strokeWidth={hair}\n />\n );\n }),\n )}\n </g>\n ) : null}\n </g>\n );\n })}\n </g>\n </svg>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n text: {\n type: \"text-content\",\n default: \"Glyph\",\n description: \"Text\",\n },\n color: {\n type: \"color\",\n default: \"#fafafa\",\n description: \"Glyph color\",\n },\n guideColor: {\n type: \"color\",\n default: \"#0d99ff\",\n description: \"Points\",\n },\n fontSize: {\n type: \"number\",\n default: 200,\n min: 80,\n max: 320,\n step: 2,\n description: \"Font size\",\n hiddenFromList: false,\n },\n guides: {\n type: \"boolean\",\n default: true,\n description: \"Guides\",\n },\n keepPoints: {\n type: \"boolean\",\n default: false,\n description: \"Keep points\",\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"text\",\"color\",\"guideColor\",\"fontSize\",\"guides\",\"keepPoints\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n text: \"Glyph\",\n color: \"#fafafa\",\n guideColor: \"#0d99ff\",\n fontSize: 200,\n guides: true,\n keepPoints: false,\n speed: 1,\n};\n\ntype GlyphAnatomyElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof GlyphAnatomyBase>;\n\nconst GlyphAnatomyInner = forwardRef<\n HTMLDivElement,\n GlyphAnatomyElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<GlyphAnatomy>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <GlyphAnatomyBase\n {...(componentProps as unknown as ComponentProps<typeof GlyphAnatomyBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const GlyphAnatomy = Interactive.withSchema({\n Component: GlyphAnatomyInner,\n componentName: \"<GlyphAnatomy>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 66+}diff --git a/registry-artifacts/elements/keystroke.json b/registry-artifacts/elements/keystroke.jsonnew file mode 100644index 00000000..10f7f321--- /dev/null+++ b/registry-artifacts/elements/keystroke.json@@ -0,0 +1,14 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [],+ "dimensions": null,+ "displayName": "Keystroke",+ "durationInFrames": 166,+ "installationMode": "component-owned-sequence",+ "slug": "keystroke",+ "sourceCode": "import { forwardRef, useImperativeHandle, useMemo, useRef, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\ntype KeystrokePlatform = \"mac\" | \"windows\";\ntype KeystrokeTheme = \"light\" | \"dark\";\ntype KeystrokeIcon =\n | \"command\"\n | \"option\"\n | \"shift\"\n | \"control\"\n | \"return\"\n | \"delete\"\n | \"escape\"\n | \"tab\"\n | \"space\"\n | \"capsLock\"\n | \"up\"\n | \"down\"\n | \"left\"\n | \"right\";\n\ninterface KeystrokeStep {\n at: number;\n keys: string;\n hold?: number;\n}\n\ninterface KeystrokeProps {\n steps?: readonly KeystrokeStep[];\n platform?: KeystrokePlatform;\n theme?: KeystrokeTheme;\n accent?: string;\n x?: number;\n y?: number;\n size?: number;\n linger?: number;\n speed?: number;\n className?: string;\n}\n\ninterface KeystrokeOptions extends Omit<KeystrokeProps, \"className\"> {\n width?: number;\n height?: number;\n fps?: number;\n}\n\ntype KeystrokeLegend =\n | { kind: \"icon\"; icon: KeystrokeIcon }\n | { kind: \"char\"; text: string }\n | { kind: \"word\"; text: string };\n\ninterface KeystrokeKey {\n name: string;\n label: string;\n legend: KeystrokeLegend;\n units: number;\n modifier: boolean;\n}\n\ntype KeystrokeChord = KeystrokeKey[];\n\ninterface KeystrokeKeyTiming {\n press: number;\n release: number;\n}\n\ninterface KeystrokeChordTiming {\n enter: number;\n fire: number;\n keys: KeystrokeKeyTiming[];\n}\n\ninterface KeystrokeLayout {\n caps: { chord: number; index: number; x: number; width: number }[];\n separators: { chord: number; x: number; width: number }[];\n widths: number[];\n}\n\ninterface KeystrokeGroup {\n index: number;\n step: number;\n keys: string;\n label: string;\n chords: KeystrokeChord[];\n timing: KeystrokeChordTiming[];\n layout: KeystrokeLayout;\n at: number;\n hold: number;\n enter: number;\n lastRelease: number;\n pushes: number[];\n exit: number;\n end: number;\n}\n\ninterface KeystrokePalette {\n cap: string;\n edge: string;\n wall: string;\n ink: string;\n separator: string;\n shadow: string;\n}\n\ntype Unset = \"steps\" | \"className\";\ntype Modifier = \"fn\" | \"ctrl\" | \"alt\" | \"shift\" | \"meta\";\ntype Named =\n | \"enter\"\n | \"escape\"\n | \"tab\"\n | \"space\"\n | \"backspace\"\n | \"delete\"\n | \"capsLock\"\n | \"up\"\n | \"down\"\n | \"left\"\n | \"right\"\n | \"home\"\n | \"end\"\n | \"pageUp\"\n | \"pageDown\";\ntype IconShape = { box: string; paths: readonly string[] };\ntype IconSpec = { label: string; icon: KeystrokeIcon; units: number };\ntype NamedSpec = IconSpec | { label: string; word: string; units: number };\ntype Draft = Omit<\n KeystrokeGroup,\n \"index\" | \"label\" | \"layout\" | \"pushes\" | \"exit\" | \"end\"\n>;\n\nconst keystrokeDefaults: Required<Omit<KeystrokeProps, Unset>> = {\n platform: \"mac\",\n theme: \"light\",\n accent: \"#0a84ff\",\n x: 0.5,\n y: 0.86,\n size: 64,\n linger: 30,\n speed: 1,\n};\n\nconst keystrokeDefaultSteps: readonly KeystrokeStep[] = [\n { at: 20, keys: \"mod+k\" },\n { at: 78, keys: \"g i\" },\n { at: 114, keys: \"shift+mod+p\" },\n];\n\nconst keystrokePalettes: Record<KeystrokeTheme, KeystrokePalette> = {\n light: {\n cap: \"#fcfcfb\",\n edge: \"#dfdfda\",\n wall: \"#cfcfca\",\n ink: \"#1d1d1f\",\n separator: \"#8e8e89\",\n shadow: \"rgba(20, 20, 16, 0.18)\",\n },\n dark: {\n cap: \"#38393e\",\n edge: \"#48494f\",\n wall: \"#1f2023\",\n ink: \"#f5f5f7\",\n separator: \"#9d9da4\",\n shadow: \"rgba(0, 0, 0, 0.5)\",\n },\n};\n\nconst PRESS = 3;\nconst PRESS_GAP = 3;\nconst RELEASE_GAP = 3;\nconst LEAD = 7;\nconst STAGGER = 1;\nconst BEAT = 2;\nconst HOLD = 8;\nconst RELEASE = 10;\nconst RELEASE_RISE = 3;\nconst RELEASE_TAPER = 6;\nconst RELEASE_DAMPING = 0.46;\nconst ENTER = 10;\nconst ENTER_RISE = 4;\nconst ENTER_TAPER = 7;\nconst ENTER_DAMPING = 0.65;\nconst FADE_IN = 4;\nconst SLIDE = 10;\nconst DIM = 6;\nconst DIM_OPACITY = 0.45;\nconst PUSH = 10;\nconst BRIEF = 18;\nconst EXIT = 8;\nconst TAIL = 14;\nconst MAX_FRAMES = 600;\nconst MIN_SIZE = 8;\nconst MAX_SIZE = 400;\nconst WALL = 0.16;\nconst TRAVEL = 0.12;\nconst RADIUS = 0.16;\nconst RISE = 0.42;\nconst KEY_GAP = 0.14;\nconst SEPARATOR = 0.95;\nconst CHAR_FONT = 0.4;\nconst WORD_FONT = 0.26;\nconst ICON_SIZE = 0.36;\nconst SEPARATOR_FONT = 0.25;\nconst WORD_CHAR = 0.6 * WORD_FONT;\nconst WORD_PAD = 0.24;\nconst WINDOWS_WORD = 1.25;\nconst SLOT_RISE = 1.09;\nconst SLOT_SCALE = 0.86;\nconst SLOT_OPACITY = 0.55;\nconst EXIT_DRIFT = 0.22;\nconst EXIT_SCALE = 0.04;\nconst SHADOW_Y = 0.07;\nconst SHADOW_Y_PRESSED = 0.02;\nconst SHADOW_BLUR = 0.11;\nconst SHADOW_BLUR_PRESSED = 0.03;\nconst GLIDE = Easing.bezier(0.33, 1, 0.68, 1);\nconst FONT_FAMILY =\n 'var(--font-geist-sans, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Inter, Roboto, Helvetica, Arial, sans-serif)';\n\nconst ICONS: Record<KeystrokeIcon, IconShape> = {\n command: {\n box: \"0 0 24 24\",\n paths: [\n \"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3\",\n ],\n },\n option: { box: \"0 0 24 24\", paths: [\"M3 3h6l6 18h6\", \"M14 3h7\"] },\n shift: {\n box: \"0 0 24 24\",\n paths: [\n \"M9 19a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1v-6a1 1 0 0 1 1-1h3.293a.707.707 0 0 0 .5-1.207l-7.086-7.086a1 1 0 0 0-1.414 0l-7.086 7.086a.707.707 0 0 0 .5 1.207H8a1 1 0 0 1 1 1z\",\n ],\n },\n control: { box: \"0 0 24 24\", paths: [\"m18 15-6-6-6 6\"] },\n return: {\n box: \"0 0 24 24\",\n paths: [\"M20 4v7a4 4 0 0 1-4 4H4\", \"m9 10-5 5 5 5\"],\n },\n delete: {\n box: \"0 0 24 24\",\n paths: [\n \"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z\",\n \"m12 9 6 6\",\n \"m18 9-6 6\",\n ],\n },\n escape: {\n box: \"0 0 24 24\",\n paths: [\"M2 8V2h6\", \"m2 2 10 10\", \"M12 2A10 10 0 1 1 2 12\"],\n },\n tab: {\n box: \"0 0 24 24\",\n paths: [\"M17 12H3\", \"m11 18 6-6-6-6\", \"M21 5v14\"],\n },\n space: {\n box: \"0 6 24 24\",\n paths: [\"M22 17v1c0 .5-.5 1-1 1H3c-.5 0-1-.5-1-1v-1\"],\n },\n capsLock: {\n box: \"0 0 24 24\",\n paths: [\n \"M14 16a1 1 0 0 0 1-1v-2a1 1 0 0 1 1-1h3.293a.707.707 0 0 0 .5-1.207l-6.939-6.939a1.207 1.207 0 0 0-1.708 0l-6.94 6.94a.707.707 0 0 0 .5 1.206H8a1 1 0 0 1 1 1v2a1 1 0 0 0 1 1z\",\n \"M9 20h6\",\n ],\n },\n up: { box: \"0 0 24 24\", paths: [\"m5 12 7-7 7 7\", \"M12 19V5\"] },\n down: { box: \"0 0 24 24\", paths: [\"M12 5v14\", \"m19 12-7 7-7-7\"] },\n left: { box: \"0 0 24 24\", paths: [\"m12 19-7-7 7-7\", \"M19 12H5\"] },\n right: { box: \"0 0 24 24\", paths: [\"M5 12h14\", \"m12 5 7 7-7 7\"] },\n};\n\nconst MODIFIERS = new Map<string, Modifier>([\n [\"fn\", \"fn\"],\n [\"ctrl\", \"ctrl\"],\n [\"control\", \"ctrl\"],\n [\"alt\", \"alt\"],\n [\"option\", \"alt\"],\n [\"opt\", \"alt\"],\n [\"shift\", \"shift\"],\n [\"cmd\", \"meta\"],\n [\"command\", \"meta\"],\n [\"meta\", \"meta\"],\n [\"win\", \"meta\"],\n [\"super\", \"meta\"],\n]);\n\nconst MODIFIER_ORDER: Record<KeystrokePlatform, readonly Modifier[]> = {\n mac: [\"fn\", \"ctrl\", \"alt\", \"shift\", \"meta\"],\n windows: [\"fn\", \"meta\", \"ctrl\", \"alt\", \"shift\"],\n};\n\nconst MAC_MODIFIERS: Record<Exclude<Modifier, \"fn\">, IconSpec> = {\n ctrl: { label: \"Control\", icon: \"control\", units: 1 },\n alt: { label: \"Option\", icon: \"option\", units: 1 },\n shift: { label: \"Shift\", icon: \"shift\", units: 1.5 },\n meta: { label: \"Command\", icon: \"command\", units: 1 },\n};\n\nconst WINDOWS_MODIFIERS: Record<Modifier, string> = {\n fn: \"Fn\",\n ctrl: \"Ctrl\",\n alt: \"Alt\",\n shift: \"Shift\",\n meta: \"Win\",\n};\n\nconst NAMED = new Map<string, Named>([\n [\"enter\", \"enter\"],\n [\"return\", \"enter\"],\n [\"esc\", \"escape\"],\n [\"escape\", \"escape\"],\n [\"tab\", \"tab\"],\n [\"space\", \"space\"],\n [\"backspace\", \"backspace\"],\n [\"delete\", \"delete\"],\n [\"del\", \"delete\"],\n [\"capslock\", \"capsLock\"],\n [\"up\", \"up\"],\n [\"arrowup\", \"up\"],\n [\"down\", \"down\"],\n [\"arrowdown\", \"down\"],\n [\"left\", \"left\"],\n [\"arrowleft\", \"left\"],\n [\"right\", \"right\"],\n [\"arrowright\", \"right\"],\n [\"home\", \"home\"],\n [\"end\", \"end\"],\n [\"pageup\", \"pageUp\"],\n [\"pgup\", \"pageUp\"],\n [\"pagedown\", \"pageDown\"],\n [\"pgdn\", \"pageDown\"],\n]);\n\nconst CHARACTERS = new Map<string, string>([\n [\"plus\", \"+\"],\n [\"minus\", \"-\"],\n [\"comma\", \",\"],\n [\"period\", \".\"],\n [\"slash\", \"/\"],\n [\"backslash\", \"\\\\\"],\n [\"semicolon\", \";\"],\n [\"quote\", \"'\"],\n [\"backquote\", \"`\"],\n [\"bracketleft\", \"[\"],\n [\"bracketright\", \"]\"],\n [\"equal\", \"=\"],\n]);\n\nconst ARROWS: Record<\"up\" | \"down\" | \"left\" | \"right\", IconSpec> = {\n up: { label: \"Up Arrow\", icon: \"up\", units: 1 },\n down: { label: \"Down Arrow\", icon: \"down\", units: 1 },\n left: { label: \"Left Arrow\", icon: \"left\", units: 1 },\n right: { label: \"Right Arrow\", icon: \"right\", units: 1 },\n};\n\nconst NAMED_KEYS: Record<KeystrokePlatform, Record<Named, NamedSpec>> = {\n mac: {\n enter: { label: \"Return\", icon: \"return\", units: 1.5 },\n escape: { label: \"Escape\", icon: \"escape\", units: 1 },\n tab: { label: \"Tab\", icon: \"tab\", units: 1.25 },\n space: { label: \"Space\", icon: \"space\", units: 2.5 },\n backspace: { label: \"Delete\", icon: \"delete\", units: 1.25 },\n delete: { label: \"Delete\", icon: \"delete\", units: 1.25 },\n capsLock: { label: \"Caps Lock\", icon: \"capsLock\", units: 1.5 },\n ...ARROWS,\n home: { label: \"Home\", word: \"home\", units: 1 },\n end: { label: \"End\", word: \"end\", units: 1 },\n pageUp: { label: \"Page Up\", word: \"page up\", units: 1 },\n pageDown: { label: \"Page Down\", word: \"page down\", units: 1 },\n },\n windows: {\n enter: { label: \"Enter\", word: \"Enter\", units: WINDOWS_WORD },\n escape: { label: \"Esc\", word: \"Esc\", units: WINDOWS_WORD },\n tab: { label: \"Tab\", word: \"Tab\", units: WINDOWS_WORD },\n space: { label: \"Space\", word: \"Space\", units: 2.5 },\n backspace: { label: \"Backspace\", word: \"Backspace\", units: WINDOWS_WORD },\n delete: { label: \"Delete\", word: \"Delete\", units: WINDOWS_WORD },\n capsLock: { label: \"Caps Lock\", word: \"Caps Lock\", units: WINDOWS_WORD },\n ...ARROWS,\n home: { label: \"Home\", word: \"Home\", units: WINDOWS_WORD },\n end: { label: \"End\", word: \"End\", units: WINDOWS_WORD },\n pageUp: { label: \"Page Up\", word: \"PgUp\", units: WINDOWS_WORD },\n pageDown: { label: \"Page Down\", word: \"PgDn\", units: WINDOWS_WORD },\n },\n};\n\nconst finite = (value: number | undefined, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst within = (\n value: number | undefined,\n fallback: number,\n min: number,\n max: number,\n) => clamp(finite(value, fallback), min, max);\nconst round = (value: number) => Math.round(value * 1000) / 1000 + 0;\nconst smoothstep = (value: number) => {\n const t = clamp(value, 0, 1);\n return t * t * (3 - 2 * t);\n};\nconst fpsOf = (fps: number | undefined) => Math.max(1, finite(fps, 30));\nconst rateOf = (speed: number | undefined) =>\n Math.max(0, finite(speed, keystrokeDefaults.speed));\nconst platformOf = (value: string | undefined): KeystrokePlatform =>\n value === \"windows\" ? value : \"mac\";\nconst themeOf = (value: string | undefined): KeystrokeTheme =>\n value === \"dark\" ? value : \"light\";\nconst accentOf = (value: string | undefined) =>\n typeof value === \"string\" && value.trim() !== \"\"\n ? value.trim()\n : keystrokeDefaults.accent;\nconst modOf = (platform: KeystrokePlatform): Modifier =>\n platform === \"mac\" ? \"meta\" : \"ctrl\";\n\nfunction eased(frames: number, duration: number, curve: (t: number) => number) {\n if (Number.isNaN(frames) || frames <= 0) return 0;\n if (frames >= duration) return 1;\n return curve(frames / duration);\n}\n\nfunction settle(rise: number, damping: number, taper: number, end: number) {\n const frequency = (Math.PI - Math.acos(damping)) / rise;\n const ratio = damping / Math.sqrt(1 - damping ** 2);\n return (frames: number) => {\n if (Number.isNaN(frames) || frames <= 0) return 0;\n if (frames >= end) return 1;\n const phase = frequency * frames;\n const decay = Math.exp(-ratio * phase);\n const ring = decay * (Math.cos(phase) + ratio * Math.sin(phase));\n return 1 - ring * (1 - smoothstep((frames - taper) / (end - taper)));\n };\n}\n\nconst riseCurve = settle(ENTER_RISE, ENTER_DAMPING, ENTER_TAPER, ENTER);\nconst releaseCurve = settle(\n RELEASE_RISE,\n RELEASE_DAMPING,\n RELEASE_TAPER,\n RELEASE,\n);\n\nfunction getKeystrokePress(frames: number) {\n return eased(frames, PRESS, smoothstep);\n}\n\nfunction getKeystrokeRelease(frames: number) {\n return releaseCurve(frames);\n}\n\nfunction getKeystrokeRise(frames: number) {\n return riseCurve(frames);\n}\n\nfunction getKeystrokeDepth(time: number, timing: KeystrokeKeyTiming) {\n if (Number.isNaN(time) || time <= timing.press) return 0;\n if (time < timing.release) return getKeystrokePress(time - timing.press);\n const bottom = getKeystrokePress(timing.release - timing.press);\n return bottom * (1 - getKeystrokeRelease(time - timing.release));\n}\n\nfunction getKeystrokeWordUnits(text: string, min = 1) {\n const raw = Array.from(text).length * WORD_CHAR + 2 * WORD_PAD;\n return Math.max(min, Math.ceil(raw * 4 - 1e-9) / 4);\n}\n\nfunction wordKey(\n name: string,\n label: string,\n text: string,\n platform: KeystrokePlatform,\n modifier: boolean,\n min = 1,\n): KeystrokeKey {\n const floor = platform === \"windows\" ? Math.max(min, WINDOWS_WORD) : min;\n const units = getKeystrokeWordUnits(text, floor);\n return { name, label, legend: { kind: \"word\", text }, units, modifier };\n}\n\nfunction modifierKey(\n modifier: Modifier,\n platform: KeystrokePlatform,\n): KeystrokeKey {\n if (platform === \"windows\") {\n const word = WINDOWS_MODIFIERS[modifier];\n return wordKey(modifier, word, word, platform, true);\n }\n if (modifier === \"fn\") return wordKey(\"fn\", \"Fn\", \"fn\", platform, true);\n const { label, icon, units } = MAC_MODIFIERS[modifier];\n return {\n name: modifier,\n label,\n legend: { kind: \"icon\", icon },\n units,\n modifier: true,\n };\n}\n\nfunction namedKey(named: Named, platform: KeystrokePlatform): KeystrokeKey {\n const spec = NAMED_KEYS[platform][named];\n if (\"word\" in spec) {\n return wordKey(named, spec.label, spec.word, platform, false, spec.units);\n }\n return {\n name: named,\n label: spec.label,\n legend: { kind: \"icon\", icon: spec.icon },\n units: spec.units,\n modifier: false,\n };\n}\n\nfunction keyOf(part: string, platform: KeystrokePlatform): KeystrokeKey {\n const name = part.toLowerCase();\n const named = NAMED.get(name);\n if (named) return namedKey(named, platform);\n const character =\n CHARACTERS.get(name) ?? (Array.from(part).length === 1 ? part : undefined);\n if (character !== undefined) {\n const text = character.toUpperCase();\n return {\n name: character.toLowerCase(),\n label: text,\n legend: { kind: \"char\", text },\n units: 1,\n modifier: false,\n };\n }\n const fkey = /^f([1-9]|1\\d|2[0-4])$/.exec(name);\n if (fkey) {\n const text = `F${fkey[1]}`;\n return wordKey(name, text, text, platform, false);\n }\n const text = `${part.charAt(0).toUpperCase()}${part.slice(1)}`;\n return wordKey(name, text, text, platform, false);\n}\n\nfunction splitChord(token: string) {\n const parts = token.split(\"+\");\n const names: string[] = [];\n for (const [index, part] of parts.entries()) {\n if (part !== \"\") names.push(part);\n else if (index === parts.length - 1 && parts[index - 1] === \"\") {\n names.push(\"+\");\n }\n }\n return names;\n}\n\nfunction parseChord(token: string, platform: KeystrokePlatform) {\n const held = new Set<Modifier>();\n const keys: KeystrokeKey[] = [];\n for (const part of splitChord(token)) {\n const name = part.toLowerCase();\n const modifier = name === \"mod\" ? modOf(platform) : MODIFIERS.get(name);\n if (modifier) held.add(modifier);\n else keys.push(keyOf(part, platform));\n }\n const modifiers = MODIFIER_ORDER[platform]\n .filter((modifier) => held.has(modifier))\n .map((modifier) => modifierKey(modifier, platform));\n return [...modifiers, ...keys];\n}\n\nfunction parseKeystrokeKeys(\n keys: string,\n platform?: KeystrokePlatform,\n): KeystrokeChord[] {\n if (typeof keys !== \"string\") return [];\n const target = platformOf(platform);\n return keys\n .trim()\n .split(/\\s+/)\n .filter((token) => token !== \"\")\n .map((token) => parseChord(token, target))\n .filter((chord) => chord.length > 0);\n}\n\nfunction getKeystrokeLayout(\n chords: readonly KeystrokeChord[],\n): KeystrokeLayout {\n const layout: KeystrokeLayout = { caps: [], separators: [], widths: [] };\n let cursor = 0;\n for (const [chord, keys] of chords.entries()) {\n if (chord > 0) {\n layout.separators.push({ chord, x: round(cursor), width: SEPARATOR });\n cursor += SEPARATOR;\n }\n for (const [index, key] of keys.entries()) {\n if (index > 0) cursor += KEY_GAP;\n layout.caps.push({ chord, index, x: round(cursor), width: key.units });\n cursor += key.units;\n }\n layout.widths.push(round(cursor));\n }\n return layout;\n}\n\nfunction schedule(chords: readonly KeystrokeChord[], hold: number) {\n const timing: KeystrokeChordTiming[] = [];\n let enter = 0;\n for (const chord of chords) {\n const last = chord.length - 1;\n const fire = enter + LEAD + PRESS_GAP * last + PRESS;\n const keys = chord.map((_, index) => ({\n press: fire - PRESS - PRESS_GAP * (last - index),\n release: fire + hold + RELEASE_GAP * (last - index),\n }));\n timing.push({ enter, fire, keys });\n enter = fire + hold + RELEASE_GAP * last + BEAT;\n }\n return timing;\n}\n\nfunction getKeystrokeLeadIn(keys: string, hold = HOLD) {\n const chords = parseKeystrokeKeys(keys);\n if (chords.length === 0) return 0;\n const timing = schedule(chords, within(hold, HOLD, 0, MAX_FRAMES));\n return timing[timing.length - 1].fire - timing[0].enter;\n}\n\nfunction getKeystrokeTimeline(\n options: Pick<KeystrokeOptions, \"steps\" | \"platform\" | \"linger\" | \"fps\"> = {},\n) {\n const platform = platformOf(options.platform);\n const scale = 30 / fpsOf(options.fps);\n const lingerFrames = within(\n options.linger,\n keystrokeDefaults.linger,\n 0,\n MAX_FRAMES,\n );\n const linger = lingerFrames * scale;\n const steps = options.steps ?? keystrokeDefaultSteps;\n const drafts: Draft[] = [];\n for (const [step, entry] of steps.entries()) {\n if (typeof entry.at !== \"number\" || !Number.isFinite(entry.at)) continue;\n const chords = parseKeystrokeKeys(entry.keys, platform);\n if (chords.length === 0) continue;\n const at = entry.at * scale;\n const hold = within(entry.hold, HOLD, 0, MAX_FRAMES) * scale;\n const planned = schedule(chords, hold);\n const offset = at - planned[planned.length - 1].fire;\n const timing = planned.map((chord) => ({\n enter: round(chord.enter + offset),\n fire: round(chord.fire + offset),\n keys: chord.keys.map((key) => ({\n press: round(key.press + offset),\n release: round(key.release + offset),\n })),\n }));\n const releases = timing.flatMap((chord) =>\n chord.keys.map((key) => key.release),\n );\n drafts.push({\n step,\n keys: entry.keys,\n chords,\n timing,\n at: round(at),\n hold: round(hold),\n enter: timing[0].enter,\n lastRelease: Math.max(...releases),\n });\n }\n drafts.sort((a, b) => a.enter - b.enter || a.at - b.at || a.step - b.step);\n const groups = drafts.map((draft, index): KeystrokeGroup => {\n const pushes: number[] = [];\n let exit = Math.max(draft.enter, draft.lastRelease + linger);\n for (const newer of drafts.slice(index + 1)) {\n if (newer.enter >= exit + EXIT) break;\n const at = Math.max(newer.enter, draft.enter);\n const brief = Math.max(at, draft.lastRelease) + BRIEF;\n pushes.push(at);\n exit = Math.min(exit, pushes.length === 1 ? brief : at);\n if (pushes.length === 2) break;\n }\n exit = round(Math.max(exit, draft.enter));\n const label = draft.chords\n .map((chord) => chord.map((key) => key.label).join(\" \"))\n .join(\" then \");\n return {\n ...draft,\n index,\n label,\n layout: getKeystrokeLayout(draft.chords),\n pushes,\n exit,\n end: round(exit + EXIT),\n };\n });\n const end = groups.reduce((latest, group) => Math.max(latest, group.end), 0);\n return { platform, linger: round(linger), groups, end };\n}\n\ntype KeystrokeTimeline = ReturnType<typeof getKeystrokeTimeline>;\n\nconst keystrokeLength = getKeystrokeTimeline().end;\n\nfunction getKeystrokeDuration(\n options: Pick<KeystrokeOptions, \"steps\" | \"linger\" | \"speed\" | \"fps\"> = {},\n) {\n const fps = fpsOf(options.fps);\n const rate = rateOf(options.speed);\n const { end } = getKeystrokeTimeline(options);\n const motion = rate === 0 ? 0 : (end * fps) / 30 / rate;\n return Math.ceil(round(motion)) + Math.round((TAIL * fps) / 30);\n}\n\nfunction getKeystrokeTime(\n frame: number,\n options: Pick<KeystrokeOptions, \"fps\" | \"speed\"> = {},\n) {\n const elapsed = Math.max(0, finite(frame, 0));\n return (elapsed * rateOf(options.speed) * 30) / fpsOf(options.fps);\n}\n\nfunction getKeystrokeMetrics(size: number, unit = 1) {\n return {\n size: round(size),\n height: round(size),\n wall: round(size * WALL),\n travel: round(size * TRAVEL),\n keytop: round(size * (1 - WALL)),\n radius: round(size * RADIUS),\n rise: round(size * RISE),\n border: round(Math.max(1, unit)),\n charFont: round(size * CHAR_FONT),\n wordFont: round(size * WORD_FONT),\n icon: round(size * ICON_SIZE),\n separatorFont: round(size * SEPARATOR_FONT),\n };\n}\n\ntype KeystrokeMetrics = ReturnType<typeof getKeystrokeMetrics>;\n\nfunction legendColor(ink: string, accent: string, amount: number) {\n const share = Math.floor(clamp(amount, 0, 1) * 100);\n if (share <= 0) return ink;\n if (share >= 100) return accent;\n return `color-mix(in srgb, ${accent} ${share}%, ${ink})`;\n}\n\nfunction fadeIn(frames: number) {\n return eased(frames, FADE_IN, (t) => 1 - (1 - t) ** 2);\n}\n\nfunction groupState(\n group: KeystrokeGroup,\n time: number,\n metrics: KeystrokeMetrics,\n palette: KeystrokePalette,\n accent: string,\n) {\n const { size } = metrics;\n const slot = group.pushes.reduce(\n (sum, at) => sum + eased(time - at, PUSH, GLIDE),\n 0,\n );\n const leaving = clamp((time - group.exit) / EXIT, 0, 1);\n const pushedAway = group.pushes.some((at) => at <= group.exit);\n const drift = (pushedAway ? -1 : 1) * EXIT_DRIFT * size * leaving ** 3;\n const dimmed = 1 - (1 - SLOT_OPACITY) * Math.min(1, slot);\n const last = group.chords.length - 1;\n let visible = group.layout.widths[0];\n for (let chord = 1; chord <= last; chord++) {\n const added = group.layout.widths[chord] - group.layout.widths[chord - 1];\n visible += added * eased(time - group.timing[chord].enter, SLIDE, GLIDE);\n }\n const left = -visible / 2;\n const caps = group.layout.caps.flatMap((cap) => {\n const timing = group.timing[cap.chord];\n const enter = timing.enter + cap.index * STAGGER;\n if (time <= enter) return [];\n const key = group.chords[cap.chord][cap.index];\n const depth = getKeystrokeDepth(time, timing.keys[cap.index]);\n const landing =\n group.timing.at(cap.chord + 1)?.fire ?? Number.POSITIVE_INFINITY;\n const dim = smoothstep((time - (landing - DIM)) / DIM);\n const lean = clamp(depth, -1, 1);\n const shadowY = SHADOW_Y - (SHADOW_Y - SHADOW_Y_PRESSED) * lean;\n const shadowBlur = SHADOW_BLUR - (SHADOW_BLUR - SHADOW_BLUR_PRESSED) * lean;\n return [\n {\n id: `${cap.chord}-${cap.index}`,\n chord: cap.chord,\n index: cap.index,\n key,\n x: round((left + cap.x) * size),\n y: round((1 - getKeystrokeRise(time - enter)) * metrics.rise),\n width: round(cap.width * size),\n opacity: round(fadeIn(time - enter) * (1 - (1 - DIM_OPACITY) * dim)),\n depth: round(depth),\n lift: round(depth * metrics.travel),\n wall: round(metrics.wall - depth * metrics.travel),\n shadowY: round(shadowY * size),\n shadowBlur: round(shadowBlur * size),\n color: legendColor(palette.ink, accent, clamp(depth, 0, 1)),\n },\n ];\n });\n const separators = group.layout.separators.flatMap((separator) => {\n const enter = group.timing[separator.chord].enter;\n if (time <= enter) return [];\n return [\n {\n id: `then-${separator.chord}`,\n chord: separator.chord,\n x: round((left + separator.x) * size),\n y: round((1 - getKeystrokeRise(time - enter)) * metrics.rise),\n width: round(separator.width * size),\n opacity: round(fadeIn(time - enter)),\n },\n ];\n });\n return {\n id: `${group.step}`,\n index: group.index,\n step: group.step,\n keys: group.keys,\n label: group.label,\n slot: round(slot),\n width: round(visible * size),\n y: round(-slot * SLOT_RISE * size + drift),\n scale: round((1 - (1 - SLOT_SCALE) * slot) * (1 - EXIT_SCALE * leaving)),\n opacity: round(dimmed * (1 - leaving ** 2)),\n caps,\n separators,\n };\n}\n\nfunction getKeystrokeState(\n frame: number,\n options: KeystrokeOptions = {},\n timeline: KeystrokeTimeline = getKeystrokeTimeline(options),\n) {\n const width = Math.max(1, finite(options.width, 1280));\n const height = Math.max(1, finite(options.height, 720));\n const unit = height / 720;\n const reference = within(\n options.size,\n keystrokeDefaults.size,\n MIN_SIZE,\n MAX_SIZE,\n );\n const metrics = getKeystrokeMetrics(reference * unit, unit);\n const time = getKeystrokeTime(frame, options);\n const x = finite(options.x, keystrokeDefaults.x);\n const y = finite(options.y, keystrokeDefaults.y);\n const theme = themeOf(options.theme);\n const palette = keystrokePalettes[theme];\n const accent = accentOf(options.accent);\n const groups = timeline.groups\n .filter((group) => time > group.enter && time < group.end)\n .map((group) => groupState(group, time, metrics, palette, accent));\n return {\n width,\n height,\n unit,\n time: round(time),\n x,\n y,\n originX: round(x * width),\n originY: round(y * height),\n theme,\n palette,\n accent,\n metrics,\n groups,\n };\n}\n\ntype KeystrokeState = ReturnType<typeof getKeystrokeState>;\n\nfunction Legend({\n legend,\n metrics,\n}: {\n legend: KeystrokeLegend;\n metrics: KeystrokeMetrics;\n}) {\n if (legend.kind === \"icon\") {\n const icon = ICONS[legend.icon];\n return (\n <svg\n width={metrics.icon}\n height={metrics.icon}\n viewBox={icon.box}\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n style={{ display: \"block\" }}\n >\n {icon.paths.map((d) => (\n <path key={d} d={d} />\n ))}\n </svg>\n );\n }\n const fontSize = legend.kind === \"word\" ? metrics.wordFont : metrics.charFont;\n return (\n <span\n style={{ fontSize, fontWeight: 500, lineHeight: 1, whiteSpace: \"nowrap\" }}\n >\n {legend.text}\n </span>\n );\n}\n\nfunction KeystrokeBase({\n steps = keystrokeDefaultSteps,\n platform = keystrokeDefaults.platform,\n theme = keystrokeDefaults.theme,\n accent = keystrokeDefaults.accent,\n x = keystrokeDefaults.x,\n y = keystrokeDefaults.y,\n size = keystrokeDefaults.size,\n linger = keystrokeDefaults.linger,\n speed = keystrokeDefaults.speed,\n className,\n}: KeystrokeProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const timeline = useMemo(\n () => getKeystrokeTimeline({ steps, platform, linger, fps }),\n [steps, platform, linger, fps],\n );\n const state = getKeystrokeState(\n frame,\n { width, height, fps, theme, accent, x, y, size, speed },\n timeline,\n );\n const { metrics, palette } = state;\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n overflow: \"hidden\",\n pointerEvents: \"none\",\n fontFamily: FONT_FAMILY,\n }}\n >\n {state.groups.map((group) => (\n <div\n key={group.id}\n style={{\n position: \"absolute\",\n left: `${state.x * 100}%`,\n top: `${state.y * 100}%`,\n width: 0,\n height: 0,\n opacity: group.opacity,\n transform: `translateY(${group.y}px) scale(${group.scale})`,\n transformOrigin: \"0 0\",\n }}\n >\n {group.separators.map((separator) => (\n <div\n key={separator.id}\n style={{\n position: \"absolute\",\n left: separator.x,\n top: separator.y - metrics.height / 2,\n width: separator.width,\n height: metrics.keytop,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n opacity: separator.opacity,\n color: palette.separator,\n fontSize: metrics.separatorFont,\n fontWeight: 500,\n lineHeight: 1,\n whiteSpace: \"nowrap\",\n }}\n >\n then\n </div>\n ))}\n {group.caps.map((cap) => (\n <div\n key={cap.id}\n style={{\n position: \"absolute\",\n left: cap.x,\n top: cap.y - metrics.height / 2,\n width: cap.width,\n height: metrics.height,\n opacity: cap.opacity,\n }}\n >\n <div\n style={{\n position: \"absolute\",\n left: 0,\n right: 0,\n top: metrics.travel,\n bottom: 0,\n borderRadius: metrics.radius,\n background: palette.wall,\n boxShadow: `0 ${cap.shadowY}px ${cap.shadowBlur}px ${palette.shadow}`,\n }}\n />\n <div\n style={{\n position: \"absolute\",\n left: 0,\n right: 0,\n top: 0,\n height: metrics.keytop,\n boxSizing: \"border-box\",\n borderRadius: metrics.radius,\n border: `${metrics.border}px solid ${palette.edge}`,\n background: palette.cap,\n color: cap.color,\n transform: `translateY(${cap.lift}px)`,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n >\n <Legend legend={cap.key.legend} metrics={metrics} />\n </div>\n </div>\n ))}\n </div>\n ))}\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n platform: {\n type: \"enum\",\n default: \"mac\",\n variants: {\n mac: {},\n windows: {},\n },\n description: \"Platform\",\n },\n theme: {\n type: \"enum\",\n default: \"light\",\n variants: {\n light: {},\n dark: {},\n },\n description: \"Theme\",\n },\n accent: {\n type: \"color\",\n default: \"#0a84ff\",\n description: \"Accent\",\n },\n size: {\n type: \"number\",\n default: 64,\n min: 32,\n max: 128,\n step: 1,\n description: \"Key size\",\n hiddenFromList: false,\n },\n linger: {\n type: \"number\",\n default: 30,\n min: 0,\n max: 90,\n step: 1,\n description: \"Linger\",\n hiddenFromList: false,\n },\n x: {\n type: \"number\",\n default: 0.5,\n min: 0,\n max: 1,\n step: 0.01,\n description: \"Center x\",\n hiddenFromList: false,\n },\n y: {\n type: \"number\",\n default: 0.86,\n min: 0,\n max: 1,\n step: 0.01,\n description: \"Center y\",\n hiddenFromList: false,\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"platform\",\"theme\",\"accent\",\"size\",\"linger\",\"x\",\"y\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n platform: \"mac\",\n theme: \"light\",\n accent: \"#0a84ff\",\n size: 64,\n linger: 30,\n x: 0.5,\n y: 0.86,\n speed: 1,\n};\n\ntype KeystrokeElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof KeystrokeBase>;\n\nconst KeystrokeInner = forwardRef<\n HTMLDivElement,\n KeystrokeElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<Keystroke>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <KeystrokeBase\n {...(componentProps as unknown as ComponentProps<typeof KeystrokeBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const Keystroke = Interactive.withSchema({\n Component: KeystrokeInner,\n componentName: \"<Keystroke>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 166+}diff --git a/registry-artifacts/elements/mondrian-split.json b/registry-artifacts/elements/mondrian-split.jsonnew file mode 100644index 00000000..02b75bce--- /dev/null+++ b/registry-artifacts/elements/mondrian-split.json@@ -0,0 +1,14 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [],+ "dimensions": null,+ "displayName": "Mondrian Split",+ "durationInFrames": 133,+ "installationMode": "component-owned-sequence",+ "slug": "mondrian-split",+ "sourceCode": "import { forwardRef, useImperativeHandle, useMemo, useRef, type CSSProperties, type ComponentProps, type ReactNode } from \"react\";\nimport { Easing, Interactive, Sequence, random, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\ntype MondrianSplitAxis = \"x\" | \"y\";\ntype MondrianSplitSlot = \"red\" | \"yellow\" | \"blue\";\ntype MondrianSplitSide = \"left\" | \"top\" | \"right\" | \"bottom\";\n\ninterface MondrianSplitProps {\n children?: ReactNode;\n seed?: number;\n splits?: number;\n lineWeight?: number;\n expandCell?: number;\n lineColor?: string;\n redColor?: string;\n yellowColor?: string;\n blueColor?: string;\n fieldColor?: string;\n speed?: number;\n className?: string;\n}\n\ntype MondrianSplitOptions = Pick<\n MondrianSplitProps,\n \"seed\" | \"splits\" | \"lineWeight\" | \"expandCell\"\n> & {\n width?: number;\n height?: number;\n};\n\ninterface MondrianSplitBox {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n}\n\ninterface MondrianSplitRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\ninterface GridNode {\n box: MondrianSplitBox;\n bounds: Record<MondrianSplitSide, number>;\n line: number;\n}\n\ninterface GridCut {\n axis: MondrianSplitAxis;\n position: number;\n node: number;\n}\n\ninterface GridMove {\n track: number;\n from: number;\n to: number;\n start: number;\n}\n\ninterface GridWipe {\n axis: MondrianSplitAxis;\n fromEnd: boolean;\n}\n\nconst mondrianSplitDefaults = {\n seed: 7,\n splits: 7,\n lineWeight: 14,\n expandCell: 0,\n lineColor: \"#121212\",\n redColor: \"#d62d20\",\n yellowColor: \"#f4c20d\",\n blueColor: \"#1f4e9e\",\n fieldColor: \"#d62d20\",\n};\n\nconst LINE_START = 3;\nconst LINE_GAP = 5;\nconst LINE_DRAW = 10;\nconst FILL_LAG = 7;\nconst FILL_GAP = 4;\nconst FILL_WIPE = 9;\nconst FIELD_LAG = 6;\nconst FIELD_WIPE = 12;\nconst HOLD = 14;\nconst TRACK_COUNT = 3;\nconst TRACK_GAP = 5;\nconst TRACK_SLIDE = 20;\nconst EXPAND_LEAD = 4;\nconst SIDE_GAP = 3;\nconst SIDE_PUSH = 22;\nconst TAIL = 12;\nconst SLIDE_PEAK = 0.72;\nconst SLIDE_OVER = 0.035;\nconst RESERVE = 0.045;\nconst WIND = 0.22;\nconst DIP = 0.035;\nconst DIP_SHARE = 0.2;\nconst SIDES: MondrianSplitSide[] = [\"left\", \"top\", \"right\", \"bottom\"];\nconst SLOTS: MondrianSplitSlot[] = [\"blue\", \"yellow\", \"red\", \"blue\", \"yellow\"];\nconst FALLBACK_CUTS = [0.38, 0.62, 0.3, 0.7, 0.5];\n\nconst drawEase = Easing.bezier(0.16, 1, 0.3, 1);\nconst wipeEase = Easing.bezier(0.7, 0, 0.2, 1);\nconst riseEase = Easing.bezier(0.65, 0, 0.3, 1);\nconst settleEase = Easing.bezier(0.4, 0, 0.6, 1);\nconst windEase = Easing.bezier(0.45, 0, 0.55, 1);\nconst pushEase = Easing.poly(2.5);\nconst layer: CSSProperties = { position: \"absolute\", inset: 0 };\n\nconst finite = (value: number, fallback: number) =>\n Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst mix = (from: number, to: number, amount: number) =>\n from + (to - from) * amount;\nconst progress = (time: number, start: number, duration: number) =>\n clamp((time - start) / duration, 0, 1);\nconst other = (axis: MondrianSplitAxis): MondrianSplitAxis =>\n axis === \"x\" ? \"y\" : \"x\";\nconst lowEdge = (box: MondrianSplitBox, axis: MondrianSplitAxis) =>\n axis === \"x\" ? box.x0 : box.y0;\nconst extent = (box: MondrianSplitBox, axis: MondrianSplitAxis) =>\n axis === \"x\" ? box.x1 - box.x0 : box.y1 - box.y0;\nconst area = (box: MondrianSplitBox) => extent(box, \"x\") * extent(box, \"y\");\nconst splitCount = (splits: number) =>\n Math.round(clamp(finite(splits, mondrianSplitDefaults.splits), 3, 12));\nconst coloredCount = (count: number) => clamp(Math.round(count * 0.3), 1, 5);\n\nconst touches = (a: MondrianSplitBox, b: MondrianSplitBox) => {\n const overlapX = Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0);\n const overlapY = Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0);\n const beside = Math.abs(a.x1 - b.x0) < 0.5 || Math.abs(b.x1 - a.x0) < 0.5;\n const stacked = Math.abs(a.y1 - b.y0) < 0.5 || Math.abs(b.y1 - a.y0) < 0.5;\n return (beside && overlapY > 0.5) || (stacked && overlapX > 0.5);\n};\n\nconst choose = (weights: readonly number[], roll: number) => {\n let remaining = roll * weights.reduce((sum, value) => sum + value, 0);\n for (let index = 0; index < weights.length; index++) {\n remaining -= weights[index];\n if (remaining <= 0) return index;\n }\n return weights.length - 1;\n};\n\nconst slide = (amount: number) => {\n if (amount >= 1) return 1;\n if (amount <= SLIDE_PEAK) {\n return (1 + SLIDE_OVER) * riseEase(amount / SLIDE_PEAK);\n }\n const settle = settleEase((amount - SLIDE_PEAK) / (1 - SLIDE_PEAK));\n return mix(1 + SLIDE_OVER, 1, settle);\n};\n\nconst push = (amount: number, dip: number) => {\n if (amount >= 1) return 1;\n if (amount <= 0) return 0;\n if (amount < WIND) return -dip * windEase(amount / WIND);\n return mix(-dip, 1, pushEase((amount - WIND) / (1 - WIND)));\n};\n\nconst stretch = (\n from0: number,\n from1: number,\n to0: number,\n to1: number,\n min: number,\n max: number,\n) => {\n if (from0 === to0 && from1 === to1) return (value: number) => value;\n return (value: number) => {\n if (value <= from0) {\n return min + (value - min) * ((to0 - min) / (from0 - min));\n }\n if (value >= from1) {\n return max - (max - value) * ((max - to1) / (max - from1));\n }\n return to0 + (value - from0) * ((to1 - to0) / (from1 - from0));\n };\n};\n\nconst wipe = (\n box: MondrianSplitBox,\n { axis, fromEnd }: GridWipe,\n amount: number,\n): MondrianSplitRect => {\n const width = box.x1 - box.x0;\n const height = box.y1 - box.y0;\n if (axis === \"x\") {\n const span = width * amount;\n return {\n x: fromEnd ? box.x1 - span : box.x0,\n y: box.y0,\n width: span,\n height,\n };\n }\n const span = height * amount;\n return {\n x: box.x0,\n y: fromEnd ? box.y1 - span : box.y0,\n width,\n height: span,\n };\n};\n\nconst inFrame = (rect: MondrianSplitRect, width: number, height: number) =>\n rect.width > 0.01 &&\n rect.height > 0.01 &&\n rect.x < width &&\n rect.y < height &&\n rect.x + rect.width > 0 &&\n rect.y + rect.height > 0;\n\nconst placeBoxes = (\n cuts: readonly Pick<GridCut, \"axis\" | \"node\">[],\n positions: readonly number[],\n width: number,\n height: number,\n) => {\n const boxes: MondrianSplitBox[] = [{ x0: 0, y0: 0, x1: width, y1: height }];\n for (let id = 0; id < cuts.length; id++) {\n const { axis, node } = cuts[id];\n const box = boxes[node];\n const at = positions[id];\n boxes.push(\n axis === \"x\" ? { ...box, x1: at } : { ...box, y1: at },\n axis === \"x\" ? { ...box, x0: at } : { ...box, y0: at },\n );\n }\n return boxes;\n};\n\nconst percent = (value: number, size: number) =>\n `${(clamp(value / size, 0, 1) * 100).toFixed(4)}%`;\n\nfunction getMondrianSplitTimeline({\n splits = mondrianSplitDefaults.splits,\n}: Pick<MondrianSplitProps, \"splits\"> = {}) {\n const count = splitCount(splits);\n const fill = LINE_START + (count - 1) * LINE_GAP + FILL_LAG;\n const field = fill + (coloredCount(count) - 1) * FILL_GAP + FIELD_LAG;\n const reflow = field + FIELD_WIPE + HOLD;\n const settled = reflow + (TRACK_COUNT - 1) * TRACK_GAP + TRACK_SLIDE;\n const expand = settled - EXPAND_LEAD;\n const end = expand + (SIDES.length - 1) * SIDE_GAP + SIDE_PUSH;\n return { lines: LINE_START, fill, field, reflow, expand, end };\n}\n\nconst mondrianSplitLength = getMondrianSplitTimeline().end;\n\nfunction getMondrianSplitDuration({\n speed = 1,\n splits = mondrianSplitDefaults.splits,\n}: Pick<MondrianSplitProps, \"speed\" | \"splits\"> = {}) {\n const rate = Math.max(0, finite(speed, 1));\n const frames = getMondrianSplitTimeline({ splits }).end + TAIL;\n return rate === 0 ? 1 : Math.max(1, Math.ceil(frames / rate));\n}\n\nfunction getMondrianSplitLayout({\n seed = mondrianSplitDefaults.seed,\n splits = mondrianSplitDefaults.splits,\n lineWeight = mondrianSplitDefaults.lineWeight,\n expandCell = mondrianSplitDefaults.expandCell,\n width = 1280,\n height = 720,\n}: MondrianSplitOptions = {}) {\n const w = Math.max(1, finite(width, 1280));\n const h = Math.max(1, finite(height, 720));\n const short = Math.min(w, h);\n const weight = clamp(finite(lineWeight, 14), 2, 48) * (short / 720);\n const count = splitCount(splits);\n const timeline = getMondrianSplitTimeline({ splits: count });\n const salt = Math.round(finite(seed, mondrianSplitDefaults.seed));\n const roll = (name: string) => random(`mondrian-split-${salt}-${name}`);\n const minSide = Math.max(short * 0.1, weight * 3);\n const snap = short * 0.045;\n const align = short * 0.075;\n const gap = Math.max(short * 0.07, weight * 2.5);\n const minMove = short * 0.06;\n const overscan = weight + short * 0.04;\n const nodes: GridNode[] = [\n {\n box: { x0: 0, y0: 0, x1: w, y1: h },\n bounds: { left: -1, top: -1, right: -1, bottom: -1 },\n line: -1,\n },\n ];\n const cuts: GridCut[] = [];\n\n const lean = (\n box: MondrianSplitBox,\n ratio: number,\n name: string,\n ): MondrianSplitAxis => {\n const wide = extent(box, \"x\");\n const tall = extent(box, \"y\");\n if (wide > tall * ratio) return \"x\";\n if (tall > wide * ratio) return \"y\";\n return roll(name) < 0.5 ? \"x\" : \"y\";\n };\n\n const cut = (node: number, axis: MondrianSplitAxis, position: number) => {\n const id = cuts.length;\n const { box, bounds: edges } = nodes[node];\n const vertical = axis === \"x\";\n nodes[node].line = id;\n cuts.push({ axis, position, node });\n nodes.push(\n {\n box: vertical ? { ...box, x1: position } : { ...box, y1: position },\n bounds: vertical ? { ...edges, right: id } : { ...edges, bottom: id },\n line: -1,\n },\n {\n box: vertical ? { ...box, x0: position } : { ...box, y0: position },\n bounds: vertical ? { ...edges, left: id } : { ...edges, top: id },\n line: -1,\n },\n );\n };\n\n const snapTo = (axis: MondrianSplitAxis, position: number) => {\n let best = position;\n let distance = snap;\n for (const line of cuts) {\n const offset = Math.abs(line.position - position);\n if (line.axis === axis && offset < distance) {\n best = line.position;\n distance = offset;\n }\n }\n return best;\n };\n\n const nearMiss = (axis: MondrianSplitAxis, position: number) =>\n cuts.some(\n (line) =>\n line.axis === axis &&\n line.position !== position &&\n Math.abs(line.position - position) < snap,\n );\n\n const tryCut = (\n node: number,\n axis: MondrianSplitAxis,\n fraction: number,\n strict: boolean,\n ) => {\n const { box } = nodes[node];\n const low = lowEdge(box, axis);\n const length = extent(box, axis);\n if (length < minSide * 2) return false;\n const position = clamp(\n snapTo(axis, low + length * fraction),\n low + minSide,\n low + length - minSide,\n );\n if (strict && nearMiss(axis, position)) return false;\n cut(node, axis, position);\n return true;\n };\n\n let anchor = -1;\n const longAxis = lean(nodes[0].box, 1.05, \"square\");\n const rootAxis = roll(\"root-axis\") < 0.75 ? longAxis : other(longAxis);\n const rootFraction =\n roll(\"root-side\") < 0.5\n ? mix(0.3, 0.4, roll(\"root-at\"))\n : mix(0.6, 0.7, roll(\"root-at\"));\n if (tryCut(0, rootAxis, rootFraction, false)) {\n const share = mix(0.6, 0.76, roll(\"anchor-at\"));\n const anchorLow = roll(\"anchor-side\") < 0.5;\n const big = rootFraction < 0.5 ? 2 : 1;\n if (tryCut(big, other(rootAxis), anchorLow ? share : 1 - share, false)) {\n anchor = anchorLow ? nodes.length - 2 : nodes.length - 1;\n }\n }\n\n const splittable = (index: number) => {\n const { box, line } = nodes[index];\n return (\n line === -1 &&\n index !== anchor &&\n Math.max(extent(box, \"x\"), extent(box, \"y\")) >= minSide * 2\n );\n };\n\n const budget = count * 24;\n for (let attempt = 0; cuts.length < count && attempt < budget; attempt++) {\n const tag = `${cuts.length}-${attempt}`;\n const pool = nodes.flatMap((_, index) =>\n splittable(index) ? [index] : [],\n );\n if (pool.length === 0) break;\n const weights = pool.map((index) => area(nodes[index].box) ** 1.2);\n const node = pool[choose(weights, roll(`${tag}-cell`))];\n const { box } = nodes[node];\n const preferred = lean(box, 1.25, `${tag}-axis`);\n const fits = extent(box, preferred) >= minSide * 2;\n const at = roll(`${tag}-at`);\n const fraction = at < 0.5 ? 0.28 + at * 0.34 : 0.55 + (at - 0.5) * 0.34;\n tryCut(node, fits ? preferred : other(preferred), fraction, true);\n }\n\n const byPriority = (a: number, b: number) =>\n Number(a === anchor) - Number(b === anchor) ||\n area(nodes[b].box) - area(nodes[a].box);\n const fallback = () => {\n const pool = nodes.flatMap((node, index) =>\n node.line === -1 ? [index] : [],\n );\n pool.sort(byPriority);\n for (const strict of [true, false]) {\n for (const node of pool) {\n const { box } = nodes[node];\n const first: MondrianSplitAxis =\n extent(box, \"x\") >= extent(box, \"y\") ? \"x\" : \"y\";\n for (const axis of [first, other(first)]) {\n for (const fraction of FALLBACK_CUTS) {\n if (tryCut(node, axis, fraction, strict)) return true;\n }\n }\n }\n }\n return false;\n };\n while (cuts.length < count) {\n if (!fallback()) break;\n }\n\n const trackKeys: string[] = [];\n const lines = cuts.map((draft, id) => {\n const key = `${draft.axis}:${draft.position}`;\n if (!trackKeys.includes(key)) trackKeys.push(key);\n const { bounds } = nodes[draft.node];\n const vertical = draft.axis === \"x\";\n const near = vertical ? bounds.top : bounds.left;\n const far = vertical ? bounds.bottom : bounds.right;\n return {\n id,\n axis: draft.axis,\n position: draft.position,\n node: draft.node,\n track: trackKeys.indexOf(key),\n lowBound: vertical ? bounds.left : bounds.top,\n highBound: vertical ? bounds.right : bounds.bottom,\n fromEnd: near === far ? roll(`draw-${id}`) < 0.5 : far < near,\n start: LINE_START + id * LINE_GAP,\n };\n });\n\n const leaves = nodes.flatMap((node, index) =>\n node.line === -1 ? [index] : [],\n );\n const ranked = [...leaves].sort(\n (a, b) => area(nodes[b].box) - area(nodes[a].box) || a - b,\n );\n const pick = clamp(Math.round(finite(expandCell, 0)), 0, ranked.length - 1);\n const target = ranked[pick];\n const targetBox = nodes[target].box;\n\n const others = leaves.filter((index) => index !== target);\n const largest = Math.max(1, ...others.map((index) => area(nodes[index].box)));\n const candidates = others\n .map((index) => ({\n index,\n score:\n roll(`fill-${index}`) +\n (touches(nodes[index].box, targetBox) ? 0.45 : 0) +\n (0.3 * area(nodes[index].box)) / largest,\n }))\n .sort((a, b) => a.score - b.score);\n const painted: { index: number; slot: MondrianSplitSlot }[] = [];\n const quota = Math.min(coloredCount(count), candidates.length);\n for (let order = 0; order < quota; order++) {\n const slot = SLOTS[order];\n const free = candidates.filter(\n ({ index }) => !painted.some((cell) => cell.index === index),\n );\n const clean = free.find(\n ({ index }) =>\n !painted.some(\n (cell) =>\n cell.slot === slot &&\n touches(nodes[cell.index].box, nodes[index].box),\n ) && !(slot === \"red\" && touches(nodes[index].box, targetBox)),\n );\n const choice = clean ?? free[0];\n if (choice) painted.push({ index: choice.index, slot });\n }\n\n const wipeOf = (index: number): GridWipe => {\n const { box } = nodes[index];\n const axis = extent(box, \"x\") >= extent(box, \"y\") ? \"x\" : \"y\";\n const middle = axis === \"x\" ? box.x0 + box.x1 : box.y0 + box.y1;\n return { axis, fromEnd: middle < (axis === \"x\" ? w : h) };\n };\n const diagonal = (index: number) => {\n const { box } = nodes[index];\n return (box.x0 + box.x1) / w + (box.y0 + box.y1) / h;\n };\n const fills = [...painted]\n .sort((a, b) => diagonal(a.index) - diagonal(b.index))\n .map((cell, order) => ({\n node: cell.index,\n slot: cell.slot,\n ...wipeOf(cell.index),\n start: timeline.fill + order * FILL_GAP,\n }));\n const field = { node: target, ...wipeOf(target), start: timeline.field };\n\n const tracks = trackKeys.map((_, track) => {\n const members = lines.filter((line) => line.track === track);\n return {\n track,\n axis: members[0].axis,\n position: members[0].position,\n length: members.reduce(\n (sum, line) => sum + extent(nodes[line.node].box, other(line.axis)),\n 0,\n ),\n };\n });\n const reserveLow = lines.map((line) => line.position);\n const reserveHigh = lines.map((line) => line.position);\n const limits = (track: number) => {\n let low = Number.NEGATIVE_INFINITY;\n let high = Number.POSITIVE_INFINITY;\n for (const line of lines) {\n if (line.track === track) {\n const size = line.axis === \"x\" ? w : h;\n const floor = line.lowBound === -1 ? 0 : reserveHigh[line.lowBound];\n const ceiling =\n line.highBound === -1 ? size : reserveLow[line.highBound];\n low = Math.max(low, floor + gap);\n high = Math.min(high, ceiling - gap);\n } else {\n if (line.lowBound !== -1 && lines[line.lowBound].track === track) {\n high = Math.min(high, reserveLow[line.id] - gap);\n }\n if (line.highBound !== -1 && lines[line.highBound].track === track) {\n low = Math.max(low, reserveHigh[line.id] + gap);\n }\n }\n }\n return { low, high };\n };\n const moves: GridMove[] = [];\n const settledAt = (track: number, position: number) =>\n moves.find((move) => move.track === track)?.to ?? position;\n const borders = (side: MondrianSplitSide, track: number) => {\n const id = nodes[target].bounds[side];\n return id !== -1 && lines[id].track === track;\n };\n const inward = (track: number) => {\n if (borders(\"left\", track) || borders(\"top\", track)) return 1;\n if (borders(\"right\", track) || borders(\"bottom\", track)) return -1;\n return 0;\n };\n const heading = (track: number, down: number, up: number) => {\n const squeeze = inward(track);\n if (squeeze !== 0) {\n return (squeeze > 0 ? up : down) >= minMove ? squeeze : 0;\n }\n if (down < minMove) return up >= minMove ? 1 : 0;\n if (up < minMove) return -1;\n return roll(`track-way-${track}`) < up / (up + down) ? 1 : -1;\n };\n const order = tracks\n .map((track) => ({\n ...track,\n weight: track.length * (0.6 + 0.8 * roll(`track-${track.track}`)),\n }))\n .sort((a, b) => b.weight - a.weight);\n for (const track of order) {\n if (moves.length >= TRACK_COUNT) break;\n const { low, high } = limits(track.track);\n const down = (track.position - low) / (1 + RESERVE);\n const up = (high - track.position) / (1 + RESERVE);\n const direction = heading(track.track, down, up);\n if (direction === 0) continue;\n const span = track.axis === \"x\" ? w : h;\n const room = Math.min(direction > 0 ? up : down, span * 0.2);\n const stride = mix(0.6, 0.95, roll(`track-far-${track.track}`));\n const reach = track.position + direction * Math.max(minMove, room * stride);\n const nearest = tracks\n .filter((rival) => rival.axis === track.axis)\n .filter((rival) => rival.track !== track.track)\n .map((rival) => settledAt(rival.track, rival.position))\n .reduce(\n (best, position) =>\n Math.abs(position - reach) < Math.abs(best - reach) ? position : best,\n Number.POSITIVE_INFINITY,\n );\n const to = Math.abs(nearest - reach) < align ? nearest : reach;\n const margin = Math.abs(to - track.position) * RESERVE;\n if (\n Math.abs(to - track.position) < minMove ||\n to - margin < low ||\n to + margin > high\n ) {\n continue;\n }\n for (const line of lines) {\n if (line.track === track.track) {\n reserveLow[line.id] = Math.min(track.position, to) - margin;\n reserveHigh[line.id] = Math.max(track.position, to) + margin;\n }\n }\n moves.push({\n track: track.track,\n from: track.position,\n to,\n start: timeline.reflow + moves.length * TRACK_GAP,\n });\n }\n\n const settled = lines.map((line) => settledAt(line.track, line.position));\n const home = placeBoxes(lines, settled, w, h)[target];\n const travel: Record<MondrianSplitSide, number> = {\n left: home.x0 + overscan,\n top: home.y0 + overscan,\n right: w + overscan - home.x1,\n bottom: h + overscan - home.y1,\n };\n const ranking = [...SIDES].sort((a, b) => travel[a] - travel[b]);\n const side = (name: MondrianSplitSide) => {\n const across = name === \"left\" || name === \"right\" ? \"x\" : \"y\";\n const share = (extent(home, across) * DIP_SHARE) / travel[name];\n return {\n start: timeline.expand + ranking.indexOf(name) * SIDE_GAP,\n dip: nodes[target].bounds[name] === -1 ? 0 : Math.min(DIP, share),\n };\n };\n\n return {\n width: w,\n height: h,\n weight,\n minSide,\n gap,\n minMove,\n align,\n overscan,\n timeline,\n nodes,\n lines,\n leaves,\n target,\n fills,\n field,\n moves,\n sides: {\n left: side(\"left\"),\n top: side(\"top\"),\n right: side(\"right\"),\n bottom: side(\"bottom\"),\n },\n };\n}\n\ntype MondrianSplitLayout = ReturnType<typeof getMondrianSplitLayout>;\n\nfunction getMondrianSplitState(\n frame: number,\n layout: MondrianSplitLayout = getMondrianSplitLayout(),\n) {\n const time = Math.max(0, finite(frame, 0));\n const { width, height, weight, overscan } = layout;\n const positions = layout.lines.map((line) => {\n const move = layout.moves.find((item) => item.track === line.track);\n if (!move) return line.position;\n const amount = slide(progress(time, move.start, TRACK_SLIDE));\n return line.position + (move.to - move.from) * amount;\n });\n const boxes = placeBoxes(layout.lines, positions, width, height);\n const home = boxes[layout.target];\n const reach = (name: MondrianSplitSide) => {\n const { start, dip } = layout.sides[name];\n return push(progress(time, start, SIDE_PUSH), dip);\n };\n const mapX = stretch(\n home.x0,\n home.x1,\n mix(home.x0, -overscan, reach(\"left\")),\n mix(home.x1, width + overscan, reach(\"right\")),\n -overscan,\n width + overscan,\n );\n const mapY = stretch(\n home.y0,\n home.y1,\n mix(home.y0, -overscan, reach(\"top\")),\n mix(home.y1, height + overscan, reach(\"bottom\")),\n -overscan,\n height + overscan,\n );\n const project = (box: MondrianSplitBox): MondrianSplitBox => ({\n x0: mapX(box.x0),\n y0: mapY(box.y0),\n x1: mapX(box.x1),\n y1: mapY(box.y1),\n });\n\n const lines = layout.lines.flatMap((line) => {\n const drawn = drawEase(progress(time, line.start, LINE_DRAW));\n if (drawn <= 0) return [];\n const box = boxes[line.node];\n const vertical = line.axis === \"x\";\n const low = vertical ? box.y0 : box.x0;\n const high = vertical ? box.y1 : box.x1;\n const along = vertical ? mapY : mapX;\n const start = along(line.fromEnd ? high - (high - low) * drawn : low);\n const end = along(line.fromEnd ? high : low + (high - low) * drawn);\n const position = (vertical ? mapX : mapY)(positions[line.id]);\n const half = weight / 2;\n const length = end - start;\n const rect: MondrianSplitRect = vertical\n ? { x: position - half, y: start, width: weight, height: length }\n : { x: start, y: position - half, width: length, height: weight };\n return inFrame(rect, width, height)\n ? [{ id: line.id, axis: line.axis, position, drawn, ...rect }]\n : [];\n });\n\n const fills = layout.fills.flatMap((fill) => {\n const amount = wipeEase(progress(time, fill.start, FILL_WIPE));\n if (amount <= 0) return [];\n const rect = wipe(project(boxes[fill.node]), fill, amount);\n return inFrame(rect, width, height)\n ? [{ id: fill.node, slot: fill.slot, ...rect }]\n : [];\n });\n\n const reveal = wipeEase(progress(time, layout.field.start, FIELD_WIPE));\n const field = reveal > 0 ? wipe(project(home), layout.field, reveal) : null;\n\n return {\n time,\n lines,\n fills,\n field: field && inFrame(field, width, height) ? field : null,\n cells: layout.leaves.map((id) => ({ id, ...project(boxes[id]) })),\n };\n}\n\ntype MondrianSplitState = ReturnType<typeof getMondrianSplitState>;\n\nfunction getMondrianSplitClip(\n field: MondrianSplitRect | null,\n width: number,\n height: number,\n) {\n if (!field) return \"inset(50%)\";\n const top = percent(field.y, height);\n const right = percent(width - field.x - field.width, width);\n const bottom = percent(height - field.y - field.height, height);\n const left = percent(field.x, width);\n return `inset(${top} ${right} ${bottom} ${left})`;\n}\n\nfunction MondrianSplitBase({\n children,\n seed = mondrianSplitDefaults.seed,\n splits = mondrianSplitDefaults.splits,\n lineWeight = mondrianSplitDefaults.lineWeight,\n expandCell = mondrianSplitDefaults.expandCell,\n lineColor = mondrianSplitDefaults.lineColor,\n redColor = mondrianSplitDefaults.redColor,\n yellowColor = mondrianSplitDefaults.yellowColor,\n blueColor = mondrianSplitDefaults.blueColor,\n fieldColor = mondrianSplitDefaults.fieldColor,\n speed = 1,\n className,\n}: MondrianSplitProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const layout = useMemo(\n () =>\n getMondrianSplitLayout({\n seed,\n splits,\n lineWeight,\n expandCell,\n width,\n height,\n }),\n [seed, splits, lineWeight, expandCell, width, height],\n );\n const time = frame * (30 / fps) * Math.max(0, finite(speed, 1));\n const state = getMondrianSplitState(time, layout);\n const palette: Record<MondrianSplitSlot, string> = {\n red: redColor,\n yellow: yellowColor,\n blue: blueColor,\n };\n const viewBox = `0 0 ${width} ${height}`;\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={viewBox}\n preserveAspectRatio=\"none\"\n aria-hidden=\"true\"\n style={layer}\n >\n {state.fills.map((fill) => (\n <rect\n key={fill.id}\n x={fill.x}\n y={fill.y}\n width={fill.width}\n height={fill.height}\n fill={palette[fill.slot]}\n />\n ))}\n {state.field ? (\n <rect\n x={state.field.x}\n y={state.field.y}\n width={state.field.width}\n height={state.field.height}\n fill={fieldColor}\n />\n ) : null}\n </svg>\n {children == null ? null : (\n <div\n style={{\n ...layer,\n clipPath: getMondrianSplitClip(state.field, width, height),\n }}\n >\n {children}\n </div>\n )}\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={viewBox}\n preserveAspectRatio=\"none\"\n role=\"img\"\n aria-label=\"De Stijl grid\"\n style={layer}\n >\n {state.lines.map((line) => (\n <rect\n key={line.id}\n x={line.x}\n y={line.y}\n width={line.width}\n height={line.height}\n fill={lineColor}\n />\n ))}\n </svg>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n seed: {\n type: \"number\",\n default: 7,\n min: 1,\n max: 99,\n step: 1,\n description: \"Seed\",\n hiddenFromList: false,\n },\n splits: {\n type: \"number\",\n default: 7,\n min: 3,\n max: 12,\n step: 1,\n description: \"Splits\",\n hiddenFromList: false,\n },\n lineWeight: {\n type: \"number\",\n default: 14,\n min: 4,\n max: 32,\n step: 1,\n description: \"Line weight\",\n hiddenFromList: false,\n },\n expandCell: {\n type: \"number\",\n default: 0,\n min: 0,\n max: 12,\n step: 1,\n description: \"Expanding cell (0 is the largest)\",\n hiddenFromList: false,\n },\n lineColor: {\n type: \"color\",\n default: \"#121212\",\n description: \"Lines\",\n },\n redColor: {\n type: \"color\",\n default: \"#d62d20\",\n description: \"Red\",\n },\n yellowColor: {\n type: \"color\",\n default: \"#f4c20d\",\n description: \"Yellow\",\n },\n blueColor: {\n type: \"color\",\n default: \"#1f4e9e\",\n description: \"Blue\",\n },\n fieldColor: {\n type: \"color\",\n default: \"#d62d20\",\n description: \"Expanding cell color\",\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"seed\",\"splits\",\"lineWeight\",\"expandCell\",\"lineColor\",\"redColor\",\"yellowColor\",\"blueColor\",\"fieldColor\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n seed: 7,\n splits: 7,\n lineWeight: 14,\n expandCell: 0,\n lineColor: \"#121212\",\n redColor: \"#d62d20\",\n yellowColor: \"#f4c20d\",\n blueColor: \"#1f4e9e\",\n fieldColor: \"#d62d20\",\n speed: 1,\n};\n\ntype MondrianSplitElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof MondrianSplitBase>;\n\nconst MondrianSplitInner = forwardRef<\n HTMLDivElement,\n MondrianSplitElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<MondrianSplit>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <MondrianSplitBase\n {...(componentProps as unknown as ComponentProps<typeof MondrianSplitBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const MondrianSplit = Interactive.withSchema({\n Component: MondrianSplitInner,\n componentName: \"<MondrianSplit>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 133+}diff --git a/registry-artifacts/elements/outline-trace.json b/registry-artifacts/elements/outline-trace.jsonnew file mode 100644index 00000000..71a79ea3--- /dev/null+++ b/registry-artifacts/elements/outline-trace.json@@ -0,0 +1,19 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [+ {+ "name": "opentype.js",+ "version": "2.0.0"+ }+ ],+ "dimensions": null,+ "displayName": "Outline Trace",+ "durationInFrames": 44,+ "installationMode": "component-owned-sequence",+ "slug": "outline-trace",+ "sourceCode": "import { parse, type Font } from \"opentype.js\";\nimport { forwardRef, useEffect, useId, useImperativeHandle, useRef, useState, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, continueRender, delayRender, interpolate, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\ninterface OutlineTraceProps {\n text?: string;\n fontUrl?: string;\n fontSize?: number;\n color?: string;\n strokeColor?: string;\n strokeWidth?: number;\n stagger?: number;\n fill?: boolean;\n keepStroke?: boolean;\n speed?: number;\n className?: string;\n}\n\n/** Static Inter ExtraBold (800) from Google Fonts. */\nconst interExtraBoldTtf =\n \"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuDyYMZg.ttf\";\n\nconst outlineTraceDefaults = {\n text: \"Outline\",\n fontUrl: interExtraBoldTtf,\n fontSize: 150,\n color: \"#fafafa\",\n strokeColor: \"\",\n strokeWidth: 2.5,\n stagger: 3,\n fill: true,\n keepStroke: false,\n speed: 1,\n} satisfies Required<Omit<OutlineTraceProps, \"className\">>;\n\n/** Per-letter beats on the 30 fps clock, relative to the letter's start. */\nconst outlineTraceTiming = {\n outer: [0, 18],\n counter: [4, 18],\n fill: [14, 26],\n} as const;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\nconst easeOutCubic = Easing.out(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nfunction getOutlineTraceTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\ninterface OutlineTraceLetterState {\n /** Trim progress of the outer contours, 0..1. */\n outer: number;\n /** Trim progress of the counters, 0..1. */\n counter: number;\n /** Share of the glyph box the fill has risen through, 0..1. */\n fill: number;\n}\n\nfunction getOutlineTraceLetter(\n t: number,\n index: number,\n stagger = outlineTraceDefaults.stagger,\n): OutlineTraceLetterState {\n const u = t - index * Math.max(0, finite(stagger, 3));\n const { outer, counter, fill } = outlineTraceTiming;\n return {\n outer: interpolate(u, [...outer], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n counter: interpolate(u, [...counter], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n fill: interpolate(u, [...fill], [0, 1], { ...CLAMP, easing: easeOutCubic }),\n };\n}\n\n/** Frame where the last of `count` letters has filled. */\nfunction getOutlineTraceLength(\n count: number,\n stagger = outlineTraceDefaults.stagger,\n) {\n const last = Math.max(0, count - 1) * Math.max(0, finite(stagger, 3));\n return Math.ceil(last + outlineTraceTiming.fill[1]);\n}\n\ninterface PathCommand {\n type: string;\n x?: number;\n y?: number;\n x1?: number;\n y1?: number;\n x2?: number;\n y2?: number;\n}\n\ninterface Box {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n}\n\ninterface OutlineContour {\n d: string;\n box: Box;\n /** True for a hole inside another contour of the same glyph. */\n counter: boolean;\n}\n\nconst fmt = (n: number) => Number(n.toFixed(2));\n\n/**\n * Splits glyph path commands into closed contours and marks the counters:\n * contours whose box lies inside another contour's box.\n */\nfunction getOutlineContours(commands: readonly PathCommand[]) {\n const raw: { d: string; box: Box }[] = [];\n let d = \"\";\n let box: Box | null = null;\n const grow = (x = 0, y = 0) => {\n if (!box) box = { x0: x, y0: y, x1: x, y1: y };\n else {\n box.x0 = Math.min(box.x0, x);\n box.y0 = Math.min(box.y0, y);\n box.x1 = Math.max(box.x1, x);\n box.y1 = Math.max(box.y1, y);\n }\n };\n const close = () => {\n if (d && box) raw.push({ d: `${d}Z`, box });\n d = \"\";\n box = null;\n };\n for (const c of commands) {\n if (c.type === \"M\") {\n close();\n d = `M${fmt(c.x ?? 0)} ${fmt(c.y ?? 0)}`;\n grow(c.x, c.y);\n } else if (c.type === \"L\") {\n d += `L${fmt(c.x ?? 0)} ${fmt(c.y ?? 0)}`;\n grow(c.x, c.y);\n } else if (c.type === \"Q\") {\n d += `Q${fmt(c.x1 ?? 0)} ${fmt(c.y1 ?? 0)} ${fmt(c.x ?? 0)} ${fmt(c.y ?? 0)}`;\n grow(c.x1, c.y1);\n grow(c.x, c.y);\n } else if (c.type === \"C\") {\n d += `C${fmt(c.x1 ?? 0)} ${fmt(c.y1 ?? 0)} ${fmt(c.x2 ?? 0)} ${fmt(c.y2 ?? 0)} ${fmt(c.x ?? 0)} ${fmt(c.y ?? 0)}`;\n grow(c.x1, c.y1);\n grow(c.x2, c.y2);\n grow(c.x, c.y);\n } else if (c.type === \"Z\") {\n close();\n }\n }\n close();\n const inside = (a: Box, b: Box) =>\n a !== b && a.x0 >= b.x0 && a.y0 >= b.y0 && a.x1 <= b.x1 && a.y1 <= b.y1;\n return raw.map(\n (c): OutlineContour => ({\n ...c,\n counter: raw.some((other) => inside(c.box, other.box)),\n }),\n );\n}\n\ninterface OutlineGlyph {\n contours: OutlineContour[];\n box: Box | null;\n}\n\n/**\n * Lays out `text` in reference px with the baseline at y = 0. Glyphs are\n * looked up per character: full shaping runs GSUB lookups that opentype.js\n * does not support in every font.\n */\nfunction layoutOutlineGlyphs(\n font: Font,\n text: string,\n fontSize: number,\n) {\n const scale = fontSize / font.unitsPerEm;\n const glyphs = Array.from(text).map((char) => font.charToGlyph(char));\n let x = 0;\n const letters: OutlineGlyph[] = glyphs.map((glyph, i) => {\n if (i > 0) x += font.getKerningValue(glyphs[i - 1], glyph) * scale;\n const contours = getOutlineContours(glyph.getPath(x, 0, fontSize).commands);\n x += (glyph.advanceWidth ?? 0) * scale;\n const box = contours.reduce<Box | null>(\n (acc, c) =>\n acc\n ? {\n x0: Math.min(acc.x0, c.box.x0),\n y0: Math.min(acc.y0, c.box.y0),\n x1: Math.max(acc.x1, c.box.x1),\n y1: Math.max(acc.y1, c.box.y1),\n }\n : { ...c.box },\n null,\n );\n return { contours, box };\n });\n const os2 = font.tables.os2 as { sCapHeight?: number } | undefined;\n const capHeight =\n ((os2?.sCapHeight ?? font.unitsPerEm * 0.7) * fontSize) / font.unitsPerEm;\n return { letters, width: x, capHeight };\n}\n\nconst fontCache = new Map<string, Promise<Font>>();\n\nfunction loadOutlineFont(url: string) {\n let pending = fontCache.get(url);\n if (!pending) {\n pending = fetch(url)\n .then((res) => res.arrayBuffer())\n .then((buffer) => parse(buffer));\n fontCache.set(url, pending);\n pending.catch(() => fontCache.delete(url));\n }\n return pending;\n}\n\nfunction useOutlineFont(url: string) {\n const [font, setFont] = useState<Font | null>(null);\n\n useEffect(() => {\n const handle = delayRender(`outline-trace: loading ${url}`);\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n continueRender(handle);\n };\n loadOutlineFont(url).then((parsed) => {\n if (!released) setFont(parsed);\n release();\n }, release);\n return release;\n }, [url]);\n\n return font;\n}\n\nfunction OutlineTraceBase({\n text = outlineTraceDefaults.text,\n fontUrl = outlineTraceDefaults.fontUrl,\n fontSize = outlineTraceDefaults.fontSize,\n color = outlineTraceDefaults.color,\n strokeColor = outlineTraceDefaults.strokeColor,\n strokeWidth = outlineTraceDefaults.strokeWidth,\n stagger = outlineTraceDefaults.stagger,\n fill = outlineTraceDefaults.fill,\n keepStroke = outlineTraceDefaults.keepStroke,\n speed = outlineTraceDefaults.speed,\n className,\n}: OutlineTraceProps) {\n const frame = useCurrentFrame();\n const { fps, width, height } = useVideoConfig();\n const id = `outline-trace-${useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`;\n const font = useOutlineFont(fontUrl);\n if (!font) return null;\n\n const unit = height / 720;\n const t = getOutlineTraceTime(frame, { fps, speed });\n const layout = layoutOutlineGlyphs(font, text, fontSize);\n const originX = (width - layout.width * unit) / 2;\n const baseline = (height + layout.capHeight * unit) / 2;\n const stroke = strokeColor || color;\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n style={{ display: \"block\" }}\n >\n <g transform={`translate(${originX} ${baseline}) scale(${unit})`}>\n <filter id={`${id}-erode`}>\n <feMorphology operator=\"erode\" radius={strokeWidth / 2} />\n </filter>\n {layout.letters.map((letter, i) => {\n if (!letter.box) return null;\n const state = getOutlineTraceLetter(t, i, stagger);\n const box = letter.box;\n const tall = box.y1 - box.y0 + 2 * strokeWidth;\n const rise = tall * (fill ? state.fill : 0);\n const strokeOpacity = fill && !keepStroke ? 1 - state.fill : 1;\n const whole = letter.contours.map((c) => c.d).join(\"\");\n const margin = 4 * strokeWidth;\n return (\n <g key={i}>\n {/* Static instances of variable fonts keep overlapping\n contours (the bar of a t crosses its stem). The mask hides\n stroke that runs inside the glyph's filled silhouette. */}\n <mask\n id={`${id}-mask-${i}`}\n maskUnits=\"userSpaceOnUse\"\n x={box.x0 - margin}\n y={box.y0 - margin}\n width={box.x1 - box.x0 + 2 * margin}\n height={box.y1 - box.y0 + 2 * margin}\n >\n <rect\n x={box.x0 - margin}\n y={box.y0 - margin}\n width={box.x1 - box.x0 + 2 * margin}\n height={box.y1 - box.y0 + 2 * margin}\n fill=\"#ffffff\"\n />\n <path d={whole} fill=\"#000000\" filter={`url(#${id}-erode)`} />\n </mask>\n {fill && state.fill > 0 ? (\n <>\n <clipPath id={`${id}-${i}`}>\n <rect\n x={box.x0 - strokeWidth}\n y={box.y1 + strokeWidth - rise}\n width={box.x1 - box.x0 + 2 * strokeWidth}\n height={rise}\n />\n </clipPath>\n <path\n d={whole}\n fill={color}\n clipPath={`url(#${id}-${i})`}\n />\n </>\n ) : null}\n {strokeOpacity > 0 ? (\n <g mask={`url(#${id}-mask-${i})`}>\n {letter.contours.map((contour, k) => {\n const progress = contour.counter\n ? state.counter\n : state.outer;\n if (progress <= 0) return null;\n return (\n <path\n key={k}\n d={contour.d}\n pathLength={1}\n fill=\"none\"\n stroke={stroke}\n strokeWidth={strokeWidth}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeDasharray=\"1 1\"\n strokeDashoffset={1 - progress}\n opacity={strokeOpacity}\n />\n );\n })}\n </g>\n ) : null}\n </g>\n );\n })}\n </g>\n </svg>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n text: {\n type: \"text-content\",\n default: \"Outline\",\n description: \"Text\",\n },\n color: {\n type: \"color\",\n default: \"#111111\",\n description: \"Fill\",\n },\n strokeColor: {\n type: \"color\",\n default: \"#111111\",\n description: \"Stroke\",\n },\n fontSize: {\n type: \"number\",\n default: 150,\n min: 60,\n max: 300,\n step: 2,\n description: \"Font size\",\n hiddenFromList: false,\n },\n strokeWidth: {\n type: \"number\",\n default: 2.5,\n min: 0.5,\n max: 8,\n step: 0.5,\n description: \"Stroke width\",\n hiddenFromList: false,\n },\n stagger: {\n type: \"number\",\n default: 3,\n min: 0,\n max: 12,\n step: 1,\n description: \"Letter stagger\",\n hiddenFromList: false,\n },\n fill: {\n type: \"boolean\",\n default: true,\n description: \"Fill\",\n },\n keepStroke: {\n type: \"boolean\",\n default: false,\n description: \"Keep stroke\",\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"text\",\"color\",\"strokeColor\",\"fontSize\",\"strokeWidth\",\"stagger\",\"fill\",\"keepStroke\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n text: \"Outline\",\n color: \"#111111\",\n strokeColor: \"#111111\",\n fontSize: 150,\n strokeWidth: 2.5,\n stagger: 3,\n fill: true,\n keepStroke: false,\n speed: 1,\n};\n\ntype OutlineTraceElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof OutlineTraceBase>;\n\nconst OutlineTraceInner = forwardRef<\n HTMLDivElement,\n OutlineTraceElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<OutlineTrace>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <OutlineTraceBase\n {...(componentProps as unknown as ComponentProps<typeof OutlineTraceBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const OutlineTrace = Interactive.withSchema({\n Component: OutlineTraceInner,\n componentName: \"<OutlineTrace>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 44+}diff --git a/registry-artifacts/elements/path-ride.json b/registry-artifacts/elements/path-ride.jsonnew file mode 100644index 00000000..973b20e3--- /dev/null+++ b/registry-artifacts/elements/path-ride.json@@ -0,0 +1,23 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [+ {+ "name": "@remotion/google-fonts",+ "version": null+ },+ {+ "name": "@remotion/paths",+ "version": null+ }+ ],+ "dimensions": null,+ "displayName": "Path Ride",+ "durationInFrames": 70,+ "installationMode": "component-owned-sequence",+ "slug": "path-ride",+ "sourceCode": "import { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { getLength, getPointAtLength, getTangentAtLength } from \"@remotion/paths\";\nimport { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, continueRender, delayRender, interpolate, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\ninterface PathRideProps {\n text?: string;\n path?: string;\n fontSize?: number;\n fontWeight?: number;\n fontFamily?: string;\n color?: string;\n lineColor?: string;\n lineWidth?: number;\n speed?: number;\n className?: string;\n}\n\n/** An S-curve across a 1280×720 frame. */\nconst pathRideDefaultPath =\n \"M 120 560 C 360 120 560 120 640 360 S 920 600 1160 160\";\n\nconst pathRideDefaults = {\n text: \"Follow the line\",\n path: pathRideDefaultPath,\n fontSize: 44,\n fontWeight: 700,\n fontFamily: INTER,\n color: \"#fafafa\",\n lineColor: \"#D97757\",\n lineWidth: 3,\n speed: 1,\n} satisfies Required<Omit<PathRideProps, \"className\">>;\n\n/** Beats on the 30 fps clock. */\nconst pathRideTiming = {\n draw: [0, 40],\n straighten: [50, 68],\n erase: [52, 70],\n} as const;\n\n/** Gap between the head and the last letter, in em. */\nconst LEAD = 0.3;\n/** Letters fade in over this much arc length, in em. */\nconst FADE_IN = 0.5;\n/** Extra lift of the baseline above the line, in em. */\nconst LIFT = 0.08;\n/** Samples along the path; the line and the letters read positions from them. */\nconst SAMPLES = 400;\nconst MEASURE_SIZE = 100;\n/** Inter's baseline and cap height in a `line-height: 1` box, until measured. */\nconst INTER_METRICS = { baseline: 0.8637, capHeight: 0.7275 };\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nfunction getPathRideTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\n/** Arc length drawn so far. */\nfunction getPathRideHead(t: number, length: number) {\n return interpolate(t, [...pathRideTiming.draw], [0, length], {\n ...CLAMP,\n easing: easeInOutCubic,\n });\n}\n\n/** Arc length erased from the start. */\nfunction getPathRideTail(t: number, length: number) {\n return interpolate(t, [...pathRideTiming.erase], [0, length], {\n ...CLAMP,\n easing: easeInOutCubic,\n });\n}\n\n/** How far the curve has pulled straight, 0..1. */\nfunction getPathRideStraighten(t: number) {\n return interpolate(t, [...pathRideTiming.straighten], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n });\n}\n\n/** Frame where the line has erased and the text rests on its baseline. */\nconst pathRideLength = Math.max(\n pathRideTiming.straighten[1],\n pathRideTiming.erase[1],\n);\n\n/** Letter centers from the text start, and the total width. */\nfunction getPathRideCenters(advances: readonly number[]) {\n let x = 0;\n const centers = advances.map((a) => {\n const c = x + a / 2;\n x += a;\n return c;\n });\n return { centers, width: x };\n}\n\n/**\n * Arc length of a letter's center: it trails the head by the lead plus the\n * text after it, so the last letter follows the head most closely.\n */\nfunction getPathRideArc(\n head: number,\n center: number,\n width: number,\n fontSize: number,\n) {\n return head - LEAD * fontSize - (width - center);\n}\n\n/** Opacity of a letter from how far onto the curve it has come. */\nfunction getPathRideFade(arc: number, fontSize: number) {\n return Math.min(1, Math.max(0, arc / (FADE_IN * fontSize)));\n}\n\ninterface Point {\n x: number;\n y: number;\n}\n\ninterface PathSamples {\n length: number;\n points: Point[];\n tangents: Point[];\n}\n\n/** Points and unit tangents at evenly spaced arc lengths along `path`. */\nfunction samplePath(path: string, count = SAMPLES): PathSamples {\n const length = getLength(path);\n const n = Math.max(2, Math.round(count));\n const points: Point[] = [];\n const tangents: Point[] = [];\n for (let i = 0; i < n; i++) {\n const at = (length * i) / (n - 1);\n // Both can come back null on a degenerate path; reuse the last sample.\n const p = getPointAtLength(path, at) ?? points[i - 1] ?? { x: 0, y: 0 };\n const tangent = getTangentAtLength(path, at) ??\n tangents[i - 1] ?? { x: 1, y: 0 };\n points.push({ x: p.x, y: p.y });\n tangents.push({ x: tangent.x, y: tangent.y });\n }\n return { length, points, tangents };\n}\n\n/** Position and unit tangent at arc length `s`, clamped to the path. */\nfunction getPathSample(samples: PathSamples, s: number) {\n const n = samples.points.length;\n const u = samples.length > 0 ? (s / samples.length) * (n - 1) : 0;\n const i = Math.min(n - 2, Math.max(0, Math.floor(u)));\n const f = Math.min(1, Math.max(0, u - i));\n const a = samples.points[i];\n const b = samples.points[i + 1];\n const ta = samples.tangents[i];\n const tb = samples.tangents[i + 1];\n const tx = ta.x + (tb.x - ta.x) * f;\n const ty = ta.y + (tb.y - ta.y) * f;\n const norm = Math.hypot(tx, ty) || 1;\n return {\n x: a.x + (b.x - a.x) * f,\n y: a.y + (b.y - a.y) * f,\n tx: tx / norm,\n ty: ty / norm,\n };\n}\n\ninterface PathRideStraight {\n /** Arc length that lands on the text's left edge. */\n start: number;\n /** Reference x of the text's left edge on the straight baseline. */\n left: number;\n /** Reference y of the straight baseline. */\n baseline: number;\n}\n\ninterface PathRidePose {\n x: number;\n y: number;\n angle: number;\n}\n\n/**\n * A point of the path pulled `k` of the way from the curve to the straight\n * baseline, lifted `lift` along its normal. Arc length maps to x one to one,\n * so the text keeps its spacing while the curve pulls taut.\n */\nfunction getPathRidePoint(\n samples: PathSamples,\n s: number,\n k: number,\n straight: PathRideStraight,\n lift = 0,\n): PathRidePose {\n const p = getPathSample(samples, s);\n const x = p.x + (straight.left + (s - straight.start) - p.x) * k;\n const y = p.y + (straight.baseline - p.y) * k;\n const tx = p.tx + (1 - p.tx) * k;\n const ty = p.ty * (1 - k);\n const norm = Math.hypot(tx, ty) || 1;\n return {\n x: x + (ty / norm) * lift,\n y: y - (tx / norm) * lift,\n angle: Math.atan2(ty, tx),\n };\n}\n\n/** Polyline of the pulled path between two arc lengths. */\nfunction getPathRideLine(\n samples: PathSamples,\n from: number,\n to: number,\n k: number,\n straight: PathRideStraight,\n) {\n if (to <= from) return \"\";\n const step = samples.length / (samples.points.length - 1);\n const stops = [from];\n for (let s = Math.ceil(from / step) * step; s < to; s += step) {\n if (s > from) stops.push(s);\n }\n stops.push(to);\n return stops\n .map((s, i) => {\n const p = getPathRidePoint(samples, s, k, straight);\n return `${i === 0 ? \"M\" : \"L\"}${p.x.toFixed(2)} ${p.y.toFixed(2)}`;\n })\n .join(\"\");\n}\n\nfunction useMetrics(text: string, font: string, fallback: number) {\n const chars = Array.from(text);\n const key = chars.join(\"\");\n const [metrics, setMetrics] = useState<{\n advances: number[];\n baseline: number;\n capHeight: number;\n } | null>(null);\n\n useEffect(() => {\n const handle = delayRender(\"path-ride: measuring the text\");\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n continueRender(handle);\n };\n const measure = () => {\n if (released) return;\n const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n if (ctx) {\n ctx.font = font;\n const m = ctx.measureText(\"H\");\n const ascent = m.fontBoundingBoxAscent / MEASURE_SIZE;\n const descent = m.fontBoundingBoxDescent / MEASURE_SIZE;\n setMetrics({\n advances: Array.from(key).map(\n (c) => ctx.measureText(c).width / MEASURE_SIZE,\n ),\n baseline:\n ascent > 0\n ? (1 - (ascent + descent)) / 2 + ascent\n : INTER_METRICS.baseline,\n capHeight:\n m.actualBoundingBoxAscent > 0\n ? m.actualBoundingBoxAscent / MEASURE_SIZE\n : INTER_METRICS.capHeight,\n });\n }\n release();\n };\n document.fonts.load(font, key).then(measure, measure);\n return release;\n }, [key, font]);\n\n return (\n metrics ?? {\n advances: chars.map(() => fallback),\n baseline: INTER_METRICS.baseline,\n capHeight: INTER_METRICS.capHeight,\n }\n );\n}\n\nfunction PathRideBase({\n text = pathRideDefaults.text,\n path = pathRideDefaults.path,\n fontSize = pathRideDefaults.fontSize,\n fontWeight = pathRideDefaults.fontWeight,\n fontFamily = pathRideDefaults.fontFamily,\n color = pathRideDefaults.color,\n lineColor = pathRideDefaults.lineColor,\n lineWidth = pathRideDefaults.lineWidth,\n speed = pathRideDefaults.speed,\n className,\n}: PathRideProps) {\n const frame = useCurrentFrame();\n const { fps, width, height } = useVideoConfig();\n const unit = height / 720;\n const t = getPathRideTime(frame, { fps, speed });\n const metrics = useMetrics(\n text,\n `${fontWeight} ${MEASURE_SIZE}px ${fontFamily}`,\n 0.55,\n );\n const samples = useMemo(() => samplePath(path), [path]);\n const chars = Array.from(text);\n const advances = metrics.advances.map((a) => a * fontSize);\n const { centers, width: textWidth } = getPathRideCenters(advances);\n const length = samples.length;\n const head = getPathRideHead(t, length);\n const tail = getPathRideTail(t, length);\n const k = getPathRideStraighten(t);\n const lift = lineWidth / 2 + LIFT * fontSize;\n // The line settles `lift` below the text so the capitals center on the frame.\n const straight: PathRideStraight = {\n start: getPathRideArc(length, 0, textWidth, fontSize),\n left: 640 - textWidth / 2,\n baseline: 360 + (metrics.capHeight * fontSize) / 2 + lift,\n };\n const tip = getPathRidePoint(samples, head, k, straight);\n const tipOpacity = interpolate(\n head,\n [0, length * 0.02, length * 0.98, length],\n [0, 1, 1, 0],\n CLAMP,\n );\n // Reference space (1280×720, y down) mapped onto the composition.\n const toX = (x: number) => width / 2 + (x - 640) * unit;\n const toY = (y: number) => height / 2 + (y - 360) * unit;\n const size = fontSize * unit;\n const line = getPathRideLine(samples, tail, head, k, straight);\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n style={{ position: \"absolute\", inset: 0 }}\n >\n <g\n transform={`translate(${toX(0)} ${toY(0)}) scale(${unit})`}\n fill=\"none\"\n >\n {line ? (\n <path\n d={line}\n stroke={lineColor}\n strokeWidth={lineWidth}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n ) : null}\n {tipOpacity > 0 ? (\n <circle\n cx={tip.x}\n cy={tip.y}\n r={lineWidth * 1.6}\n fill={lineColor}\n opacity={tipOpacity}\n />\n ) : null}\n </g>\n </svg>\n {chars.map((char, j) => {\n const arc = getPathRideArc(head, centers[j], textWidth, fontSize);\n const fade = getPathRideFade(arc, fontSize);\n if (fade <= 0) return null;\n const pose = getPathRidePoint(samples, arc, k, straight, lift);\n return (\n <span\n key={j}\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n fontFamily,\n fontSize: size,\n lineHeight: 1,\n fontWeight,\n fontVariationSettings: `\"wght\" ${fontWeight}`,\n color,\n whiteSpace: \"pre\",\n opacity: fade,\n transformOrigin: \"0 0\",\n transform: `translate(${toX(pose.x)}px, ${toY(pose.y)}px) rotate(${pose.angle}rad) translate(-50%, ${-metrics.baseline * size}px)`,\n }}\n >\n {char}\n </span>\n );\n })}\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n text: {\n type: \"text-content\",\n default: \"Follow the line\",\n description: \"Text\",\n },\n path: {\n type: \"text-content\",\n default: \"M 120 560 C 360 120 560 120 640 360 S 920 600 1160 160\",\n description: \"Path (1280×720)\",\n },\n color: {\n type: \"color\",\n default: \"#111111\",\n description: \"Text color\",\n },\n lineColor: {\n type: \"color\",\n default: \"#fafafa\",\n description: \"Line color\",\n },\n fontSize: {\n type: \"number\",\n default: 44,\n min: 16,\n max: 120,\n step: 1,\n description: \"Font size\",\n hiddenFromList: false,\n },\n fontWeight: {\n type: \"number\",\n default: 700,\n min: 100,\n max: 900,\n step: 50,\n description: \"Weight\",\n hiddenFromList: false,\n },\n lineWidth: {\n type: \"number\",\n default: 3,\n min: 1,\n max: 12,\n step: 0.5,\n description: \"Line width\",\n hiddenFromList: false,\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"text\",\"path\",\"color\",\"lineColor\",\"fontSize\",\"fontWeight\",\"lineWidth\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n text: \"Follow the line\",\n path: \"M 120 560 C 360 120 560 120 640 360 S 920 600 1160 160\",\n color: \"#111111\",\n lineColor: \"#fafafa\",\n fontSize: 44,\n fontWeight: 700,\n lineWidth: 3,\n speed: 1,\n};\n\ntype PathRideElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof PathRideBase>;\n\nconst PathRideInner = forwardRef<\n HTMLDivElement,\n PathRideElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<PathRide>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <PathRideBase\n {...(componentProps as unknown as ComponentProps<typeof PathRideBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const PathRide = Interactive.withSchema({\n Component: PathRideInner,\n componentName: \"<PathRide>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 70+}diff --git a/registry-artifacts/elements/period-drop.json b/registry-artifacts/elements/period-drop.jsonnew file mode 100644index 00000000..a7c63d07--- /dev/null+++ b/registry-artifacts/elements/period-drop.json@@ -0,0 +1,19 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [+ {+ "name": "@remotion/google-fonts",+ "version": null+ }+ ],+ "dimensions": null,+ "displayName": "Period Drop",+ "durationInFrames": 47,+ "installationMode": "component-owned-sequence",+ "slug": "period-drop",+ "sourceCode": "import { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { Easing, Interactive, Sequence, interpolate, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\nimport { forwardRef, useImperativeHandle, useRef, type ComponentProps } from \"react\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\ninterface PeriodDropProps {\n text?: string;\n fontSize?: number;\n fontWeight?: number;\n fontFamily?: string;\n color?: string;\n dotColor?: string;\n dotSize?: number;\n speed?: number;\n className?: string;\n}\n\nconst periodDropDefaults = {\n text: \"remocn\",\n fontSize: 160,\n fontWeight: 800,\n fontFamily: INTER,\n color: \"#fafafa\",\n dotColor: \"#D97757\",\n dotSize: 0.2,\n speed: 1,\n} satisfies Required<Omit<PeriodDropProps, \"className\">>;\n\n/** Frame where the dot has come to rest, squash included. */\nconst periodDropLength = 47;\n\n/** Timeline constants on the 30 fps clock. */\nconst periodDropTiming = {\n riseFrames: 12,\n riseStagger: 2,\n dropStart: 20,\n fallFrames: 12,\n restitution: 0.35,\n bounces: 2,\n /** Drop height as a share of the composition height. */\n dropHeight: 0.62,\n /** `scaleY` at full speed. */\n stretch: 0.3,\n /** `scaleY` lost at a full-speed impact. */\n squash: 0.22,\n /** Frames for an impact squash to decay by 1/e. */\n recover: 1.1,\n} as const;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutQuart = Easing.out(Easing.poly(4));\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nfunction getPeriodDropTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\n/** How far letter `index` still sits below its line, 1 → 0. */\nfunction getPeriodDropRise(t: number, index: number) {\n const start = periodDropTiming.riseStagger * index;\n return interpolate(t, [start, start + periodDropTiming.riseFrames], [1, 0], {\n ...CLAMP,\n easing: easeOutQuart,\n });\n}\n\n/** Frames at which the dot touches the line: the landing, then each bounce. */\nfunction getPeriodDropImpacts() {\n const { dropStart, fallFrames, restitution, bounces } = periodDropTiming;\n const impacts = [dropStart + fallFrames];\n for (let n = 1; n <= bounces; n++) {\n impacts.push(impacts[n - 1] + 2 * restitution ** n * fallFrames);\n }\n return impacts;\n}\n\ninterface PeriodDropDot {\n visible: boolean;\n /** Height above the rest point as a share of the drop, 0 at rest, −1 at the start. */\n y: number;\n scaleX: number;\n scaleY: number;\n}\n\n/**\n * The dot's fall and bounces. Heights are shares of the drop height, time is\n * in 30 fps frames. Gravity is set by the fall: `g = 2 / fall²`, so the\n * landing speed is `2 / fall`. Each bounce leaves at `restitution` times the\n * previous speed, and the squash of each impact scales with it.\n */\nfunction getPeriodDropDot(t: number): PeriodDropDot {\n const { dropStart, fallFrames, restitution, stretch, squash, recover } =\n periodDropTiming;\n if (t < dropStart) return { visible: false, y: -1, scaleX: 1, scaleY: 1 };\n const g = 2 / (fallFrames * fallFrames);\n const landing = g * fallFrames;\n const impacts = getPeriodDropImpacts();\n\n let y = 0;\n let speed = 0;\n let deform = 0;\n if (t < impacts[0]) {\n const u = t - dropStart;\n y = -1 + 0.5 * g * u * u;\n speed = g * u;\n deform = speed / landing;\n } else {\n let n = impacts.length - 1;\n while (n > 0 && t < impacts[n]) n--;\n const tau = t - impacts[n];\n const bounce = n + 1;\n const launch =\n bounce < impacts.length ? restitution ** bounce * landing : 0;\n const flight = launch > 0 ? (2 * launch) / g : 0;\n if (tau < flight) {\n y = -(launch * tau - 0.5 * g * tau * tau);\n speed = Math.abs(launch - g * tau);\n }\n const impact = restitution ** n;\n const decay = Math.exp(-tau / recover);\n deform = -impact * decay + (1 - decay) * (speed / landing);\n }\n // Snap the last imperceptible wobble so the dot rests exactly.\n if (Math.abs(deform) < 0.005) deform = 0;\n\n const scaleY =\n deform >= 0 ? 1 + stretch * deform : 1 + squash * Math.max(-1, deform);\n return { visible: true, y: Math.min(0, y), scaleX: 1 / scaleY, scaleY };\n}\n\nfunction PeriodDropBase({\n text = periodDropDefaults.text,\n fontSize = periodDropDefaults.fontSize,\n fontWeight = periodDropDefaults.fontWeight,\n fontFamily = periodDropDefaults.fontFamily,\n color = periodDropDefaults.color,\n dotColor = periodDropDefaults.dotColor,\n dotSize = periodDropDefaults.dotSize,\n speed = periodDropDefaults.speed,\n className,\n}: PeriodDropProps) {\n const frame = useCurrentFrame();\n const { fps, height } = useVideoConfig();\n const unit = height / 720;\n const t = getPeriodDropTime(frame, { fps, speed });\n const dot = getPeriodDropDot(t);\n const drop = periodDropTiming.dropHeight * height;\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n fontFamily,\n fontSize: fontSize * unit,\n lineHeight: 1,\n fontWeight,\n fontVariationSettings: `\"wght\" ${fontWeight}`,\n color,\n whiteSpace: \"pre\",\n }}\n >\n {Array.from(text).map((char, i) => (\n <span\n key={i}\n style={{\n display: \"inline-block\",\n overflow: \"hidden\",\n // Extend the clip below the line box so descenders survive.\n paddingBottom: \"0.15em\",\n marginBottom: \"-0.15em\",\n verticalAlign: \"top\",\n }}\n >\n <span\n style={{\n display: \"inline-block\",\n transform: `translateY(${getPeriodDropRise(t, i) * 115}%)`,\n }}\n >\n {char}\n </span>\n </span>\n ))}\n <span\n style={{\n display: \"inline-block\",\n width: `${dotSize}em`,\n height: `${dotSize}em`,\n marginLeft: \"0.04em\",\n borderRadius: \"50%\",\n background: dotColor,\n visibility: dot.visible ? \"visible\" : \"hidden\",\n transformOrigin: \"50% 100%\",\n transform: `translateY(${dot.y * drop}px) scale(${dot.scaleX}, ${dot.scaleY})`,\n }}\n />\n </div>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n text: {\n type: \"text-content\",\n default: \"remocn\",\n description: \"Text\",\n },\n color: {\n type: \"color\",\n default: \"#fafafa\",\n description: \"Text color\",\n },\n dotColor: {\n type: \"color\",\n default: \"#ff4d1a\",\n description: \"Dot color\",\n },\n fontSize: {\n type: \"number\",\n default: 160,\n min: 60,\n max: 280,\n step: 2,\n description: \"Font size\",\n hiddenFromList: false,\n },\n fontWeight: {\n type: \"number\",\n default: 800,\n min: 100,\n max: 900,\n step: 50,\n description: \"Weight\",\n hiddenFromList: false,\n },\n dotSize: {\n type: \"number\",\n default: 0.2,\n min: 0.08,\n max: 0.5,\n step: 0.01,\n description: \"Dot size (em)\",\n hiddenFromList: false,\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"text\",\"color\",\"dotColor\",\"fontSize\",\"fontWeight\",\"dotSize\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n text: \"remocn\",\n color: \"#fafafa\",\n dotColor: \"#ff4d1a\",\n fontSize: 160,\n fontWeight: 800,\n dotSize: 0.2,\n speed: 1,\n};\n\ntype PeriodDropElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof PeriodDropBase>;\n\nconst PeriodDropInner = forwardRef<\n HTMLDivElement,\n PeriodDropElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<PeriodDrop>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <PeriodDropBase\n {...(componentProps as unknown as ComponentProps<typeof PeriodDropBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const PeriodDrop = Interactive.withSchema({\n Component: PeriodDropInner,\n componentName: \"<PeriodDrop>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 47+}diff --git a/registry-artifacts/elements/ring-text.json b/registry-artifacts/elements/ring-text.jsonnew file mode 100644index 00000000..c84cfd8f--- /dev/null+++ b/registry-artifacts/elements/ring-text.json@@ -0,0 +1,19 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [+ {+ "name": "@remotion/google-fonts",+ "version": null+ }+ ],+ "dimensions": null,+ "displayName": "Ring Text",+ "durationInFrames": 180,+ "installationMode": "component-owned-sequence",+ "slug": "ring-text",+ "sourceCode": "import { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { forwardRef, useEffect, useImperativeHandle, useRef, useState, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, continueRender, delayRender, interpolate, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\ninterface RingTextProps {\n text?: string;\n separator?: string;\n radius?: number;\n fontSize?: number;\n fontWeight?: number;\n fontFamily?: string;\n color?: string;\n band?: string;\n tilt?: number;\n roll?: number;\n period?: number;\n speed?: number;\n className?: string;\n}\n\nconst ringTextDefaults = {\n text: \"Type in motion\",\n separator: \"•\",\n radius: 210,\n fontSize: 40,\n fontWeight: 800,\n fontFamily: INTER,\n color: \"#fafafa\",\n band: \"#0a0a0a\",\n tilt: 38,\n roll: -16,\n period: 240,\n speed: 1,\n} satisfies Required<Omit<RingTextProps, \"className\">>;\n\n/** Frame where the entrance has settled into the cruise spin. */\nconst ringTextLength = 30;\n\n/** Band height, in em. */\nconst ringBandHeight = 1.5;\n\nconst ENTRANCE = 30;\nconst FADE = 12;\nconst START_SCALE = 0.85;\n/** Extra turn, in degrees, that decays over the entrance. */\nconst ENTRANCE_SPIN = 90;\nconst WOBBLE = 6;\nconst WOBBLE_PERIOD = 150;\n/** Letters on the far side of the ring dim to this opacity. */\nconst BACK_OPACITY = 0.55;\n/** Advance per character, in em, until the face is measured. */\nconst FALLBACK_ADVANCE = 0.6;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutCubic = Easing.out(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nfunction getRingTextTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\n/** The characters of one lap: the text, a space, the separator, a space. */\nfunction getRingTextToken(text: string, separator: string) {\n return Array.from(separator ? `${text} ${separator} ` : `${text} `);\n}\n\ninterface RingTextPanel {\n /** Index into the token. */\n char: number;\n /** Panel center around the ring, radians. */\n angle: number;\n /** Panel width, reference px. */\n width: number;\n}\n\ninterface RingTextLayout {\n radius: number;\n repeats: number;\n /** Extra space added to every character so the band closes, reference px. */\n spacing: number;\n panels: RingTextPanel[];\n}\n\n/**\n * Repeats the token as many times as fits the circumference and spreads the\n * remainder as letter spacing. A token longer than the ring grows the radius.\n */\nfunction getRingTextLayout(\n advances: readonly number[],\n radius: number,\n): RingTextLayout {\n const tokenWidth = advances.reduce((sum, a) => sum + Math.max(0, a), 0);\n const count = advances.length;\n if (count === 0 || tokenWidth <= 0) {\n return { radius, repeats: 0, spacing: 0, panels: [] };\n }\n const circumference = Math.max(2 * Math.PI * Math.max(0, radius), tokenWidth);\n const repeats = Math.max(1, Math.floor(circumference / tokenWidth));\n const spacing = (circumference - repeats * tokenWidth) / (repeats * count);\n const panels: RingTextPanel[] = [];\n let travelled = 0;\n for (let r = 0; r < repeats; r++) {\n for (let char = 0; char < count; char++) {\n const width = Math.max(0, advances[char]) + spacing;\n panels.push({\n char,\n angle: (2 * Math.PI * (travelled + width / 2)) / circumference,\n width,\n });\n travelled += width;\n }\n }\n return {\n radius: circumference / (2 * Math.PI),\n repeats,\n spacing,\n panels,\n };\n}\n\n/** Ring pose at `t`: spin in degrees, tilt with its wobble, entrance scale and opacity. */\nfunction getRingTextPose(\n t: number,\n options: { period?: number; tilt?: number } = {},\n) {\n const period = Math.max(1, finite(options.period, ringTextDefaults.period));\n const tilt = finite(options.tilt, ringTextDefaults.tilt);\n const settle = easeOutCubic(Math.min(1, Math.max(0, t / ENTRANCE)));\n return {\n spin: (360 * t) / period + ENTRANCE_SPIN * settle,\n tilt: tilt + WOBBLE * Math.sin((2 * Math.PI * t) / WOBBLE_PERIOD),\n scale: START_SCALE + (1 - START_SCALE) * settle,\n opacity: interpolate(t, [0, FADE], [0, 1], CLAMP),\n };\n}\n\n/** Letter opacity from how squarely its panel faces the camera. */\nfunction getRingTextShade(angle: number, spinDegrees: number) {\n const facing = Math.cos(angle - (spinDegrees * Math.PI) / 180);\n return BACK_OPACITY + ((1 - BACK_OPACITY) * (facing + 1)) / 2;\n}\n\nfunction useAdvances(chars: readonly string[], font: string, fallback: number) {\n const key = chars.join(\"\");\n const [advances, setAdvances] = useState<number[] | null>(null);\n\n useEffect(() => {\n const handle = delayRender(\"ring-text: measuring the characters\");\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n continueRender(handle);\n };\n const measure = () => {\n if (released) return;\n const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n if (ctx) {\n ctx.font = font;\n setAdvances(Array.from(key).map((c) => ctx.measureText(c).width));\n }\n release();\n };\n document.fonts.load(font, key).then(measure, measure);\n return release;\n }, [key, font]);\n\n return advances ?? chars.map(() => fallback);\n}\n\nfunction RingTextBase({\n text = ringTextDefaults.text,\n separator = ringTextDefaults.separator,\n radius = ringTextDefaults.radius,\n fontSize = ringTextDefaults.fontSize,\n fontWeight = ringTextDefaults.fontWeight,\n fontFamily = ringTextDefaults.fontFamily,\n color = ringTextDefaults.color,\n band = ringTextDefaults.band,\n tilt = ringTextDefaults.tilt,\n roll = ringTextDefaults.roll,\n period = ringTextDefaults.period,\n speed = ringTextDefaults.speed,\n className,\n}: RingTextProps) {\n const frame = useCurrentFrame();\n const { fps, height } = useVideoConfig();\n const unit = height / 720;\n const t = getRingTextTime(frame, { fps, speed });\n const chars = getRingTextToken(text, separator);\n const advances = useAdvances(\n chars,\n `${fontWeight} ${fontSize}px ${fontFamily}`,\n FALLBACK_ADVANCE * fontSize,\n );\n const layout = getRingTextLayout(advances, radius);\n const pose = getRingTextPose(t, { period, tilt });\n const bandHeight = ringBandHeight * fontSize * unit;\n // Adjacent flat panels meet at an angle and their antialiased edges let the\n // background through; bleeding each panel into its neighbors hides the seam.\n const bleed = 1.5 * Math.max(1, unit);\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n perspective: 1600 * unit,\n // Opacity lives here: on the preserve-3d ring it would flatten it.\n opacity: pose.opacity,\n }}\n >\n <div\n style={{\n position: \"relative\",\n width: 0,\n height: 0,\n transformStyle: \"preserve-3d\",\n // Negative tilt views the ring from above: the near side is at the\n // bottom and reads left to right, the far side shows it mirrored.\n transform: `scale(${pose.scale}) rotateZ(${roll}deg) rotateX(${-pose.tilt}deg) rotateY(${-pose.spin}deg)`,\n }}\n >\n {layout.panels.map((panel, i) => {\n const width = panel.width * unit;\n return (\n <div\n key={i}\n style={{\n position: \"absolute\",\n left: -width / 2 - bleed,\n top: -bandHeight / 2,\n width: width + 2 * bleed,\n height: bandHeight,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n background: band,\n color,\n fontFamily,\n fontSize: fontSize * unit,\n lineHeight: 1,\n fontWeight,\n fontVariationSettings: `\"wght\" ${fontWeight}`,\n whiteSpace: \"pre\",\n backfaceVisibility: \"visible\",\n transform: `rotateY(${panel.angle}rad) translateZ(${layout.radius * unit}px)`,\n }}\n >\n {/* Only the letter dims: shading the band per panel would show\n every seam between panels. */}\n <span\n style={{\n opacity: getRingTextShade(panel.angle, pose.spin),\n }}\n >\n {chars[panel.char]}\n </span>\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n text: {\n type: \"text-content\",\n default: \"Type in motion\",\n description: \"Text\",\n },\n separator: {\n type: \"text-content\",\n default: \"•\",\n description: \"Separator\",\n },\n color: {\n type: \"color\",\n default: \"#d4ff1f\",\n description: \"Text color\",\n },\n band: {\n type: \"color\",\n default: \"#0a0a0a\",\n description: \"Band color\",\n },\n radius: {\n type: \"number\",\n default: 210,\n min: 80,\n max: 340,\n step: 5,\n description: \"Radius\",\n hiddenFromList: false,\n },\n fontSize: {\n type: \"number\",\n default: 40,\n min: 16,\n max: 90,\n step: 1,\n description: \"Font size\",\n hiddenFromList: false,\n },\n tilt: {\n type: \"number\",\n default: 38,\n min: 0,\n max: 80,\n step: 1,\n description: \"Tilt\",\n hiddenFromList: false,\n },\n roll: {\n type: \"number\",\n default: -16,\n min: -60,\n max: 60,\n step: 1,\n description: \"Roll\",\n hiddenFromList: false,\n },\n period: {\n type: \"number\",\n default: 240,\n min: 60,\n max: 900,\n step: 10,\n description: \"Frames per turn\",\n hiddenFromList: false,\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"text\",\"separator\",\"color\",\"band\",\"radius\",\"fontSize\",\"tilt\",\"roll\",\"period\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n text: \"Type in motion\",\n separator: \"•\",\n color: \"#d4ff1f\",\n band: \"#0a0a0a\",\n radius: 210,\n fontSize: 40,\n tilt: 38,\n roll: -16,\n period: 240,\n speed: 1,\n};\n\ntype RingTextElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof RingTextBase>;\n\nconst RingTextInner = forwardRef<\n HTMLDivElement,\n RingTextElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<RingText>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <RingTextBase\n {...(componentProps as unknown as ComponentProps<typeof RingTextBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const RingText = Interactive.withSchema({\n Component: RingTextInner,\n componentName: \"<RingText>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 180+}diff --git a/registry-artifacts/elements/selection-snap.json b/registry-artifacts/elements/selection-snap.jsonnew file mode 100644index 00000000..fa3d2724--- /dev/null+++ b/registry-artifacts/elements/selection-snap.json@@ -0,0 +1,19 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [+ {+ "name": "@remotion/google-fonts",+ "version": null+ }+ ],+ "dimensions": null,+ "displayName": "Selection Snap",+ "durationInFrames": 38,+ "installationMode": "component-owned-sequence",+ "slug": "selection-snap",+ "sourceCode": "import { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { forwardRef, useEffect, useImperativeHandle, useRef, useState, type CSSProperties, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, continueRender, delayRender, interpolate, interpolateColors, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\ninterface SelectionSnapProps {\n text?: string;\n fontSize?: number;\n fontFamily?: string;\n fromWeight?: number;\n toWeight?: number;\n color?: string;\n accent?: string;\n selectionColor?: string;\n badge?: boolean;\n speed?: number;\n className?: string;\n}\n\nconst selectionSnapDefaults = {\n text: \"Frame\",\n fontSize: 150,\n fontFamily: INTER,\n fromWeight: 100,\n toWeight: 900,\n color: \"#fafafa\",\n accent: \"#D97757\",\n selectionColor: \"#0d99ff\",\n badge: true,\n speed: 1,\n} satisfies Required<Omit<SelectionSnapProps, \"className\">>;\n\n/** Frame on the 30 fps timeline where every channel has come to rest. */\nconst selectionSnapLength = 38;\n\n/** Padding around the word, in em: the loose viewfinder and the snapped box. */\nconst selectionSnapPadding = {\n loose: { x: 1.1, y: 0.9 },\n tight: { x: 0.12, y: 0 },\n} as const;\n\n/** Corners first, then edge midpoints, as fractions of the box. */\nconst selectionSnapHandles = [\n [0, 0],\n [1, 0],\n [1, 1],\n [0, 1],\n [0.5, 0],\n [1, 0.5],\n [0.5, 1],\n [0, 0.5],\n] as const;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutCubic = Easing.out(Easing.cubic);\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\nconst snapEase = Easing.bezier(0.34, 1.3, 0.64, 1);\nconst popEase = Easing.out(Easing.back(1.7));\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Back-eased 0 → 1 over `duration` frames from `start`, never below 0. */\nfunction pop(t: number, start: number, duration: number) {\n return Math.max(\n 0,\n interpolate(t, [start, start + duration], [0, 1], {\n ...CLAMP,\n easing: popEase,\n }),\n );\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nfunction getSelectionSnapTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\ninterface SelectionSnapState {\n /** Word and brackets fading in, 0..1. */\n intro: number;\n /** Viewfinder settle scale. */\n bracketScale: number;\n /** Loose (0) to tight (1) padding. Overshoots past 1 on the snap. */\n snap: number;\n /** Weight progress, 0..1. */\n weight: number;\n /** Color progress toward the accent, 0..1. */\n tint: number;\n /** Bracket arms growing along the edges; 1 closes them into a box. */\n edges: number;\n /** Scale of each handle, in `selectionSnapHandles` order. */\n handles: number[];\n /** Badge entrance, 0..1 with overshoot. */\n badge: number;\n /** Badge readout progress, 0..1. */\n count: number;\n}\n\nfunction getSelectionSnapState(t: number): SelectionSnapState {\n return {\n intro: interpolate(t, [0, 8], [0, 1], { ...CLAMP, easing: easeOutCubic }),\n bracketScale: interpolate(t, [0, 8], [1.06, 1], {\n ...CLAMP,\n easing: easeOutCubic,\n }),\n snap: interpolate(t, [14, 28], [0, 1], { ...CLAMP, easing: snapEase }),\n weight: interpolate(t, [14, 30], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n tint: interpolate(t, [18, 30], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n edges: interpolate(t, [16, 26], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n handles: selectionSnapHandles.map((_, i) => pop(t, 24 + i, 5)),\n badge: pop(t, 24, 8),\n count: interpolate(t, [24, 38], [0, 1], { ...CLAMP, easing: easeOutCubic }),\n };\n}\n\n/** Padding in em for a snap progress. */\nfunction getSelectionSnapPadding(snap: number) {\n const { loose, tight } = selectionSnapPadding;\n return {\n x: loose.x + (tight.x - loose.x) * snap,\n y: loose.y + (tight.y - loose.y) * snap,\n };\n}\n\n/** Size of the snapped box in reference px, from the word's final width. */\nfunction getSelectionSnapSize(textWidth: number, fontSize: number) {\n const { tight } = selectionSnapPadding;\n return {\n width: Math.round(textWidth + 2 * tight.x * fontSize),\n height: Math.round(fontSize * (1 + 2 * tight.y)),\n };\n}\n\nfunction useTextWidth(text: string, font: string) {\n const [width, setWidth] = useState<number | null>(null);\n\n useEffect(() => {\n const handle = delayRender(\"selection-snap: measuring the word\");\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n continueRender(handle);\n };\n const measure = () => {\n if (released) return;\n const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n if (ctx) {\n ctx.font = font;\n setWidth(ctx.measureText(text).width);\n }\n release();\n };\n document.fonts.load(font, text).then(measure, measure);\n return release;\n }, [text, font]);\n\n return width;\n}\n\nfunction SelectionSnapBase({\n text = selectionSnapDefaults.text,\n fontSize = selectionSnapDefaults.fontSize,\n fontFamily = selectionSnapDefaults.fontFamily,\n fromWeight = selectionSnapDefaults.fromWeight,\n toWeight = selectionSnapDefaults.toWeight,\n color = selectionSnapDefaults.color,\n accent = selectionSnapDefaults.accent,\n selectionColor = selectionSnapDefaults.selectionColor,\n badge = selectionSnapDefaults.badge,\n speed = selectionSnapDefaults.speed,\n className,\n}: SelectionSnapProps) {\n const frame = useCurrentFrame();\n const { fps, height } = useVideoConfig();\n const unit = height / 720;\n const t = getSelectionSnapTime(frame, { fps, speed });\n const state = getSelectionSnapState(t);\n\n const size = fontSize * unit;\n const pad = getSelectionSnapPadding(state.snap);\n const weight = fromWeight + (toWeight - fromWeight) * state.weight;\n const stroke = Math.max(1, 1.5 * unit);\n const arm = 0.16 * size;\n const handleSize = 9 * unit;\n const finalWidth = useTextWidth(\n text,\n `${toWeight} ${fontSize}px ${fontFamily}`,\n );\n const readout =\n finalWidth === null ? null : getSelectionSnapSize(finalWidth, fontSize);\n\n // Percentages resolve against the box width for `width` and its height for\n // `height`, so one expression grows every arm to its edge's midpoint.\n const along = `calc(${arm}px + (50% - ${arm}px) * ${state.edges})`;\n const arms: CSSProperties[] = [\n { top: 0, left: 0, width: along, height: stroke },\n { top: 0, right: 0, width: along, height: stroke },\n { bottom: 0, left: 0, width: along, height: stroke },\n { bottom: 0, right: 0, width: along, height: stroke },\n { top: 0, left: 0, width: stroke, height: along },\n { bottom: 0, left: 0, width: stroke, height: along },\n { top: 0, right: 0, width: stroke, height: along },\n { bottom: 0, right: 0, width: stroke, height: along },\n ];\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n position: \"relative\",\n display: \"inline-block\",\n padding: `${pad.y * size}px ${pad.x * size}px`,\n }}\n >\n <span\n style={{\n display: \"block\",\n whiteSpace: \"pre\",\n fontFamily,\n fontSize: size,\n lineHeight: 1,\n fontWeight: Math.round(weight / 100) * 100,\n fontVariationSettings: `\"wght\" ${weight.toFixed(2)}`,\n color: interpolateColors(state.tint, [0, 1], [color, accent]),\n opacity: state.intro,\n }}\n >\n {text}\n </span>\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n opacity: state.intro,\n transform: `scale(${state.bracketScale})`,\n }}\n >\n {arms.map((style, i) => (\n <div\n key={i}\n style={{\n position: \"absolute\",\n background: selectionColor,\n ...style,\n }}\n />\n ))}\n {selectionSnapHandles.map(([x, y], i) => (\n <div\n key={`${x}-${y}`}\n style={{\n position: \"absolute\",\n left: `${x * 100}%`,\n top: `${y * 100}%`,\n width: handleSize,\n height: handleSize,\n boxSizing: \"border-box\",\n background: \"#ffffff\",\n border: `${stroke}px solid ${selectionColor}`,\n transform: `translate(-50%, -50%) scale(${state.handles[i]})`,\n }}\n />\n ))}\n </div>\n {badge && readout ? (\n <div\n style={{\n position: \"absolute\",\n left: \"50%\",\n top: `calc(100% + ${12 * unit}px)`,\n padding: `${3 * unit}px ${7 * unit}px`,\n borderRadius: 4 * unit,\n background: selectionColor,\n color: \"#ffffff\",\n fontFamily: INTER,\n fontSize: 14 * unit,\n lineHeight: 1.2,\n fontWeight: 600,\n fontVariationSettings: '\"wght\" 600',\n fontVariantNumeric: \"tabular-nums\",\n whiteSpace: \"nowrap\",\n opacity: Math.min(1, state.badge),\n transform: `translate(-50%, ${(1 - state.badge) * 8 * unit}px) scale(${0.6 + 0.4 * state.badge})`,\n transformOrigin: \"50% 0\",\n }}\n >\n {Math.round(readout.width * state.count)} ×{\" \"}\n {Math.round(readout.height * state.count)}\n </div>\n ) : null}\n </div>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n text: {\n type: \"text-content\",\n default: \"Frame\",\n description: \"Text\",\n },\n color: {\n type: \"color\",\n default: \"#fafafa\",\n description: \"Start color\",\n },\n accent: {\n type: \"color\",\n default: \"#ff4d1a\",\n description: \"Accent\",\n },\n selectionColor: {\n type: \"color\",\n default: \"#3d5afe\",\n description: \"Selection\",\n },\n fontSize: {\n type: \"number\",\n default: 150,\n min: 60,\n max: 260,\n step: 2,\n description: \"Font size\",\n hiddenFromList: false,\n },\n fromWeight: {\n type: \"number\",\n default: 100,\n min: 100,\n max: 900,\n step: 50,\n description: \"From weight\",\n hiddenFromList: false,\n },\n toWeight: {\n type: \"number\",\n default: 900,\n min: 100,\n max: 900,\n step: 50,\n description: \"To weight\",\n hiddenFromList: false,\n },\n badge: {\n type: \"boolean\",\n default: true,\n description: \"Size badge\",\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"text\",\"color\",\"accent\",\"selectionColor\",\"fontSize\",\"fromWeight\",\"toWeight\",\"badge\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n text: \"Frame\",\n color: \"#fafafa\",\n accent: \"#ff4d1a\",\n selectionColor: \"#3d5afe\",\n fontSize: 150,\n fromWeight: 100,\n toWeight: 900,\n badge: true,\n speed: 1,\n};\n\ntype SelectionSnapElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof SelectionSnapBase>;\n\nconst SelectionSnapInner = forwardRef<\n HTMLDivElement,\n SelectionSnapElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<SelectionSnap>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <SelectionSnapBase\n {...(componentProps as unknown as ComponentProps<typeof SelectionSnapBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const SelectionSnap = Interactive.withSchema({\n Component: SelectionSnapInner,\n componentName: \"<SelectionSnap>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 38+}diff --git a/registry-artifacts/elements/speed-lines.json b/registry-artifacts/elements/speed-lines.jsonnew file mode 100644index 00000000..e246b2b4--- /dev/null+++ b/registry-artifacts/elements/speed-lines.json@@ -0,0 +1,14 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [],+ "dimensions": null,+ "displayName": "Speed Lines",+ "durationInFrames": 31,+ "installationMode": "component-owned-sequence",+ "slug": "speed-lines",+ "sourceCode": "import { forwardRef, useImperativeHandle, useRef, type ComponentProps, type ReactNode } from \"react\";\nimport { Interactive, Sequence, random, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\ntype SpeedLinesMode = \"trail\" | \"focus\";\n\ninterface SpeedLinesPoint {\n x: number;\n y: number;\n}\n\ninterface SpeedLinesProps {\n mode?: SpeedLinesMode;\n from?: SpeedLinesPoint;\n to?: SpeedLinesPoint;\n x?: number;\n y?: number;\n count?: number;\n weight?: number;\n spread?: number;\n duration?: number;\n bounce?: number;\n squash?: number;\n color?: string;\n seed?: number;\n delay?: number;\n speed?: number;\n children?: ReactNode;\n className?: string;\n}\n\ntype Paint = \"color\" | \"children\" | \"className\";\ntype Unset = \"to\" | \"children\" | \"className\";\n\ninterface SpeedLinesOptions extends Omit<SpeedLinesProps, Paint> {\n width?: number;\n height?: number;\n fps?: number;\n}\n\ninterface SpeedLinesSegment {\n index: number;\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n length: number;\n}\n\ninterface SpeedLinesStreak extends SpeedLinesSegment {\n offset: number;\n reach: number;\n}\n\ninterface SpeedLinesRay extends SpeedLinesSegment {\n angle: number;\n rest: number;\n inner: number;\n outer: number;\n}\n\ninterface SpeedLinesRayTiming {\n rest: number;\n outer: number;\n start?: number;\n release?: number;\n}\n\nconst speedLinesDefaults: Required<Omit<SpeedLinesProps, Unset>> = {\n mode: \"trail\",\n from: { x: -0.25, y: 0.5 },\n x: 0.5,\n y: 0.5,\n count: 12,\n weight: 2,\n spread: 96,\n duration: 14,\n bounce: 0.5,\n squash: 0.5,\n color: \"#ffffff\",\n seed: 1,\n delay: 0,\n speed: 1,\n};\n\nconst REFERENCE = 720;\nconst LANDING = 0.3;\nconst CARRY = 0.3;\nconst ECHO = 0.2;\nconst SOFTEN = 1.2;\nconst SETTLE = 6;\nconst STRETCH = Math.log(1.3);\nconst SQUASH = Math.log(1.25);\nconst STRETCH_GAIN = 0.007;\nconst SQUASH_GAIN = 0.018;\nconst PROBE = 1e-3;\nconst CENTER = \"translate(-50%, -50%)\";\nconst HOLD = 24;\nconst SPAWN_START = 0.04;\nconst SPAWN_END = 0.8;\nconst LIFE = 0.3;\nconst MIN_LIFE = 3;\nconst DRAW = 0.4;\nconst ERASE = 0.35;\nconst SHUTTER = 1.6;\nconst DRIFT = 0.15;\nconst SETBACK = 0.35;\nconst SLOW = 5;\nconst FAST = 14;\nconst GOLDEN = (Math.sqrt(5) - 1) / 2;\nconst IMPACT = 3;\nconst RUSH_JITTER = 1;\nconst RELAX = 0.12;\nconst RELAX_RATE = 1.5;\nconst RELEASE = 8;\nconst RELEASE_JITTER = 1.5;\nconst RETRACT = 3.5;\nconst FOCUS_END = RELEASE + RELEASE_JITTER + RETRACT;\nconst ANGLE_JITTER = 0.6;\nconst RADIUS_JITTER = 0.6;\nconst MAX_COUNT = 64;\nconst MIN_WEIGHT = 0.5;\nconst MAX_WEIGHT = 12;\nconst MIN_SPREAD = 8;\nconst MAX_SPREAD = 480;\nconst MIN_DURATION = 4;\nconst MAX_DURATION = 120;\n\nconst finite = (value: number | undefined, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst round = (value: number) => Math.round(value * 100) / 100;\nconst fine = (value: number) => Math.round(value * 10000) / 10000;\nconst fraction = (value: number) => value - Math.floor(value);\nconst modeOf = (value: string | undefined): SpeedLinesMode =>\n value === \"focus\" ? \"focus\" : \"trail\";\nconst travelOf = (value: number | undefined) =>\n clamp(finite(value, speedLinesDefaults.duration), MIN_DURATION, MAX_DURATION);\n\nfunction smoothstep(value: number) {\n const t = clamp(value, 0, 1);\n return t * t * (3 - 2 * t);\n}\n\nfunction easeOut(value: number) {\n const t = clamp(value, 0, 1);\n return 1 - (1 - t) * (1 - t);\n}\n\nfunction pointOf(\n value: SpeedLinesPoint | undefined,\n fallback: SpeedLinesPoint,\n) {\n return { x: finite(value?.x, fallback.x), y: finite(value?.y, fallback.y) };\n}\n\nfunction key(seed: number, index: number, name: string) {\n return random(`speed-lines-${seed}-${index}-${name}`);\n}\n\nfunction settingsOf(options: SpeedLinesOptions) {\n const height = Math.max(1, finite(options.height, 720));\n const x = finite(options.x, speedLinesDefaults.x);\n const y = finite(options.y, speedLinesDefaults.y);\n const count = finite(options.count, speedLinesDefaults.count);\n const weight = finite(options.weight, speedLinesDefaults.weight);\n const spread = finite(options.spread, speedLinesDefaults.spread);\n return {\n mode: modeOf(options.mode),\n width: Math.max(1, finite(options.width, 1280)),\n height,\n fps: Math.max(1, finite(options.fps, 30)),\n unit: height / REFERENCE,\n from: pointOf(options.from, speedLinesDefaults.from),\n to: pointOf(options.to, { x, y }),\n x,\n y,\n count: Math.round(clamp(count, 1, MAX_COUNT)),\n weight: clamp(weight, MIN_WEIGHT, MAX_WEIGHT),\n spread: clamp(spread, MIN_SPREAD, MAX_SPREAD),\n duration: travelOf(options.duration),\n bounce: clamp(finite(options.bounce, speedLinesDefaults.bounce), 0, 1),\n squash: clamp(finite(options.squash, speedLinesDefaults.squash), 0, 1),\n seed: finite(options.seed, speedLinesDefaults.seed),\n delay: Math.max(0, finite(options.delay, speedLinesDefaults.delay)),\n speed: Math.max(0, finite(options.speed, speedLinesDefaults.speed)),\n };\n}\n\ntype Settings = ReturnType<typeof settingsOf>;\n\nfunction directionOf(settings: Settings) {\n const { from, to, width, height } = settings;\n const dx = (to.x - from.x) * width;\n const dy = (to.y - from.y) * height;\n const distance = Math.hypot(dx, dy);\n if (distance < 1e-6) return { dx: 1, dy: 0, distance: 0 };\n return { dx: dx / distance, dy: dy / distance, distance };\n}\n\nfunction along(position: number, size: number, step: number) {\n if (step > 1e-9) return (size - position) / step;\n if (step < -1e-9) return -position / step;\n return Number.POSITIVE_INFINITY;\n}\n\nfunction exitDistance(\n cx: number,\n cy: number,\n cos: number,\n sin: number,\n width: number,\n height: number,\n) {\n const inside = cx >= 0 && cx <= width && cy >= 0 && cy <= height;\n if (!inside) {\n const reachX = Math.max(Math.abs(cx), Math.abs(width - cx));\n const reachY = Math.max(Math.abs(cy), Math.abs(height - cy));\n return Math.hypot(reachX, reachY);\n }\n return Math.min(along(cx, width, cos), along(cy, height, sin));\n}\n\nfunction springOf(bounce: number) {\n const landing = LANDING + CARRY * bounce;\n const kappa = (1 + Math.sqrt(1 - landing)) / 2;\n const gain = 1 / (0.5 - kappa / 3);\n const echo = ECHO * bounce;\n const decrement = -Math.log(echo);\n const damping = echo > 0 ? decrement / Math.hypot(Math.PI, decrement) : 1;\n const natural = 1 / (1 + SOFTEN * bounce);\n const decay = damping * natural;\n return {\n kappa,\n gain,\n contact: gain * (1 - kappa),\n decay,\n ring: natural * Math.sqrt(1 - damping * damping),\n settle: Math.ceil(SETTLE / decay),\n };\n}\n\nfunction easeOf(time: number, travel: number, bounce: number) {\n if (time <= 0) return 0;\n const { kappa, gain, contact, decay, ring, settle } = springOf(bounce);\n if (time < travel) {\n const w = time / travel;\n return gain * ((w * w) / 2 - (kappa * w * w * w) / 3);\n }\n const since = time - travel;\n if (since >= settle) return 1;\n const taper = smoothstep((2 * since) / settle - 1);\n const wave = ring > 1e-9 ? Math.sin(ring * since) / ring : since;\n const envelope = Math.exp(-decay * since) * (1 - taper);\n return 1 + (contact / travel) * wave * envelope;\n}\n\nfunction getSpeedLinesTimeline(options: SpeedLinesOptions = {}) {\n const { mode, duration, bounce } = settingsOf(options);\n if (mode === \"focus\") return { mode, impact: IMPACT, end: FOCUS_END };\n return { mode, impact: duration, end: duration + springOf(bounce).settle };\n}\n\ntype SpeedLinesTimeline = ReturnType<typeof getSpeedLinesTimeline>;\n\nconst speedLinesLength = getSpeedLinesTimeline().end;\n\nfunction getSpeedLinesDuration(options: SpeedLinesOptions = {}) {\n const { delay, speed } = settingsOf(options);\n if (speed === 0) return 1;\n const { end } = getSpeedLinesTimeline(options);\n return Math.max(1, Math.ceil(delay + (end + HOLD) / speed));\n}\n\nfunction getSpeedLinesTime(\n frame: number,\n options: SpeedLinesOptions = {},\n) {\n const { fps, delay, speed } = settingsOf(options);\n const elapsed = Math.max(0, finite(frame, 0) - delay);\n return elapsed * (30 / fps) * speed;\n}\n\nfunction getSpeedLinesEase(\n time: number,\n options: SpeedLinesOptions = {},\n) {\n const { duration, bounce } = settingsOf(options);\n return easeOf(finite(time, 0), duration, bounce);\n}\n\nfunction positionAt(time: number, settings: Settings) {\n const { mode, from, to, width, height, duration, bounce } = settings;\n if (mode === \"focus\") {\n return { x: settings.x * width, y: settings.y * height, progress: 1 };\n }\n const progress = easeOf(time, duration, bounce);\n const startX = from.x * width;\n const startY = from.y * height;\n return {\n x: startX + (to.x * width - startX) * progress,\n y: startY + (to.y * height - startY) * progress,\n progress,\n };\n}\n\nfunction getSpeedLinesPosition(\n time: number,\n options: SpeedLinesOptions = {},\n) {\n const { x, y } = positionAt(finite(time, 0), settingsOf(options));\n return { x, y };\n}\n\nfunction shapeAt(time: number, settings: Settings) {\n const { mode, duration, bounce, squash, unit, speed } = settings;\n if (mode === \"focus\") return { rotation: 0, along: 1, across: 1 };\n const { dx, dy, distance } = directionOf(settings);\n const rotation = (Math.atan2(dy, dx) * 180) / Math.PI;\n if (squash === 0 || distance === 0 || time <= 0) {\n return { rotation, along: 1, across: 1 };\n }\n const span = distance / unit;\n const ahead = easeOf(time + PROBE, duration, bounce);\n const behind = easeOf(time - PROBE, duration, bounce);\n const rate = (Math.abs(ahead - behind) / (2 * PROBE)) * span * speed;\n const landed = time > duration ? easeOf(time, duration, bounce) - 1 : 0;\n const past = Math.max(0, landed) * span;\n const stretch = STRETCH * Math.tanh((squash * STRETCH_GAIN * rate) / STRETCH);\n const compression =\n SQUASH * Math.tanh((squash * SQUASH_GAIN * past) / SQUASH);\n const strain = clamp(stretch - compression, -SQUASH, STRETCH);\n return { rotation, along: Math.exp(strain), across: Math.exp(-strain) };\n}\n\nfunction getSpeedLinesShape(\n time: number,\n options: SpeedLinesOptions = {},\n) {\n return shapeAt(finite(time, 0), settingsOf(options));\n}\n\ntype SpeedLinesShape = ReturnType<typeof getSpeedLinesShape>;\n\nfunction getSpeedLinesVelocity(\n frame: number,\n options: SpeedLinesOptions = {},\n) {\n const settings = settingsOf(options);\n const current = finite(frame, 0);\n const now = positionAt(getSpeedLinesTime(current, options), settings);\n const before = positionAt(getSpeedLinesTime(current - 1, options), settings);\n const scale = settings.fps / 30;\n const x = (now.x - before.x) * scale;\n const y = (now.y - before.y) * scale;\n const { dx, dy } = directionOf(settings);\n return { x, y, forward: x * dx + y * dy };\n}\n\nfunction streakSeeds(settings: Settings) {\n const { seed, count, spread, unit } = settings;\n const band = spread * unit;\n const phase = random(`speed-lines-${seed}-lanes`);\n return Array.from({ length: count }, (_, index) => {\n const jitter = (key(seed, index, \"lane\") - 0.5) / (2 * count);\n const lane = fraction(phase + GOLDEN * index + jitter);\n const slot = (index + key(seed, index, \"spawn\")) / count;\n return {\n index,\n spawn: SPAWN_START + (SPAWN_END - SPAWN_START) * slot,\n offset: band * (lane - 0.5),\n factor: 0.5 + 0.5 * key(seed, index, \"length\"),\n setback: SETBACK * band * key(seed, index, \"setback\"),\n };\n });\n}\n\nfunction getSpeedLinesStreaks(\n frame: number,\n options: SpeedLinesOptions = {},\n): SpeedLinesStreak[] {\n const settings = settingsOf(options);\n if (settings.mode !== \"trail\") return [];\n const time = getSpeedLinesTime(frame, options);\n const { dx, dy, distance } = directionOf(settings);\n if (distance === 0 || time <= 0) return [];\n const { forward } = getSpeedLinesVelocity(frame, options);\n const { unit, duration, bounce, weight } = settings;\n const fast = smoothstep((forward - SLOW * unit) / ((FAST - SLOW) * unit));\n const gate = fast * (1 - smoothstep(time - duration));\n if (gate <= 0) return [];\n const center = positionAt(time, settings);\n const progress = time / duration;\n const life = Math.max(MIN_LIFE, LIFE * duration) / duration;\n const minimum = 0.5 * weight * unit;\n const streaks: SpeedLinesStreak[] = [];\n for (const streak of streakSeeds(settings)) {\n const age = (progress - streak.spawn) / life;\n if (age <= 0 || age >= 1) continue;\n const reach = SHUTTER * streak.factor * forward * gate;\n const drawn = easeOut(age / DRAW);\n const erased = smoothstep((age - ERASE) / (1 - ERASE));\n const length = reach * (drawn - erased);\n if (length < minimum) continue;\n const spawned = easeOf(streak.spawn * duration, duration, bounce);\n const since = Math.max(0, (center.progress - spawned) * distance);\n const base = streak.setback + DRIFT * since;\n const front = base + reach * erased;\n const back = base + reach * drawn;\n const laneX = center.x - dy * streak.offset;\n const laneY = center.y + dx * streak.offset;\n streaks.push({\n index: streak.index,\n offset: streak.offset,\n reach,\n x1: round(laneX - dx * front),\n y1: round(laneY - dy * front),\n x2: round(laneX - dx * back),\n y2: round(laneY - dy * back),\n length,\n });\n }\n return streaks;\n}\n\nfunction getSpeedLinesRadius(time: number, ray: SpeedLinesRayTiming) {\n const { rest, outer, start = 0, release = RELEASE } = ray;\n const t = finite(time, 0);\n if (t <= start) return outer;\n if (t < IMPACT) {\n const q = (t - start) / (IMPACT - start);\n return outer + (rest - outer) * q * q;\n }\n const settle = (at: number) =>\n rest * (1 + RELAX * (1 - Math.exp(-(at - IMPACT) / RELAX_RATE)));\n if (t < release) return settle(t);\n const held = settle(release);\n const q = clamp((t - release) / RETRACT, 0, 1);\n return outer - (outer - held) * (1 - q * q);\n}\n\nfunction getSpeedLinesRays(\n frame: number,\n options: SpeedLinesOptions = {},\n): SpeedLinesRay[] {\n const settings = settingsOf(options);\n if (settings.mode !== \"focus\") return [];\n const time = getSpeedLinesTime(frame, options);\n if (time <= 0 || time >= FOCUS_END) return [];\n const { seed, count, spread, weight, unit, width, height } = settings;\n const cx = settings.x * width;\n const cy = settings.y * height;\n const minimum = 0.5 * weight * unit;\n const rotation = random(`speed-lines-${seed}-rotation`);\n const rays: SpeedLinesRay[] = [];\n for (let index = 0; index < count; index++) {\n const jitter = ANGLE_JITTER * (key(seed, index, \"angle\") - 0.5);\n const angle = 2 * Math.PI * (rotation + (index + jitter) / count);\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n const reach = RADIUS_JITTER * key(seed, index, \"radius\");\n const rest = spread * unit * (1 + reach);\n const outer = exitDistance(cx, cy, cos, sin, width, height) + weight * unit;\n const inner = getSpeedLinesRadius(time, {\n rest,\n outer,\n start: RUSH_JITTER * key(seed, index, \"rush\"),\n release: RELEASE + RELEASE_JITTER * key(seed, index, \"release\"),\n });\n const length = outer - inner;\n if (length < minimum) continue;\n rays.push({\n index,\n angle,\n rest,\n inner,\n outer,\n x1: round(cx + cos * inner),\n y1: round(cy + sin * inner),\n x2: round(cx + cos * outer),\n y2: round(cy + sin * outer),\n length,\n });\n }\n return rays;\n}\n\nfunction getSpeedLinesState(\n frame: number,\n options: SpeedLinesOptions = {},\n) {\n const settings = settingsOf(options);\n const time = getSpeedLinesTime(frame, options);\n const point = positionAt(time, settings);\n const shape = shapeAt(time, settings);\n const rotation = round(shape.rotation);\n const scale = `scale(${fine(shape.along)}, ${fine(shape.across)})`;\n const streaks = getSpeedLinesStreaks(frame, options);\n const rays = getSpeedLinesRays(frame, options);\n const path = [...streaks, ...rays]\n .map(({ x1, y1, x2, y2 }) => `M ${x1} ${y1} L ${x2} ${y2}`)\n .join(\" \");\n return {\n mode: settings.mode,\n width: settings.width,\n height: settings.height,\n unit: settings.unit,\n time,\n x: point.x,\n y: point.y,\n left: (point.x / settings.width) * 100,\n top: (point.y / settings.height) * 100,\n radius: (settings.spread * settings.unit) / 2,\n strokeWidth: settings.weight * settings.unit,\n rotation,\n along: shape.along,\n across: shape.across,\n transform:\n shape.along === 1\n ? CENTER\n : `${CENTER} rotate(${rotation}deg) ${scale} rotate(${-rotation}deg)`,\n streaks,\n rays,\n path,\n };\n}\n\ntype SpeedLinesState = ReturnType<typeof getSpeedLinesState>;\n\nfunction SpeedLinesBase({\n mode = speedLinesDefaults.mode,\n from = speedLinesDefaults.from,\n to,\n x = speedLinesDefaults.x,\n y = speedLinesDefaults.y,\n count = speedLinesDefaults.count,\n weight = speedLinesDefaults.weight,\n spread = speedLinesDefaults.spread,\n duration = speedLinesDefaults.duration,\n bounce = speedLinesDefaults.bounce,\n squash = speedLinesDefaults.squash,\n color = speedLinesDefaults.color,\n seed = speedLinesDefaults.seed,\n delay = speedLinesDefaults.delay,\n speed = speedLinesDefaults.speed,\n children,\n className,\n}: SpeedLinesProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const state = getSpeedLinesState(frame, {\n mode,\n from,\n to,\n x,\n y,\n count,\n weight,\n spread,\n duration,\n bounce,\n squash,\n seed,\n delay,\n speed,\n width,\n height,\n fps,\n });\n const fallback = state.mode === \"trail\" && children === undefined;\n const placed = children !== undefined && children !== null;\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, pointerEvents: \"none\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n aria-hidden=\"true\"\n style={{ position: \"absolute\", inset: 0, display: \"block\" }}\n >\n {state.path ? (\n <path\n d={state.path}\n fill=\"none\"\n stroke={color}\n strokeWidth={state.strokeWidth}\n strokeLinecap=\"round\"\n />\n ) : null}\n {fallback ? (\n <ellipse\n cx={state.x}\n cy={state.y}\n rx={state.radius * state.along}\n ry={state.radius * state.across}\n transform={`rotate(${state.rotation} ${state.x} ${state.y})`}\n fill={color}\n />\n ) : null}\n </svg>\n {placed ? (\n <div\n style={{\n position: \"absolute\",\n left: `${state.left}%`,\n top: `${state.top}%`,\n width: \"max-content\",\n transform: state.transform,\n transformOrigin: \"50% 50%\",\n }}\n >\n {children}\n </div>\n ) : null}\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n mode: {\n type: \"enum\",\n default: \"trail\",\n variants: {\n trail: {},\n focus: {},\n },\n description: \"Mode\",\n },\n count: {\n type: \"number\",\n default: 12,\n min: 3,\n max: 32,\n step: 1,\n description: \"Lines\",\n hiddenFromList: false,\n },\n weight: {\n type: \"number\",\n default: 2,\n min: 1,\n max: 8,\n step: 0.5,\n description: \"Stroke weight\",\n hiddenFromList: false,\n },\n spread: {\n type: \"number\",\n default: 96,\n min: 16,\n max: 320,\n step: 4,\n description: \"Spread\",\n hiddenFromList: false,\n },\n duration: {\n type: \"number\",\n default: 14,\n min: 6,\n max: 40,\n step: 1,\n description: \"Travel frames\",\n hiddenFromList: false,\n },\n bounce: {\n type: \"number\",\n default: 0.5,\n min: 0,\n max: 1,\n step: 0.05,\n description: \"Bounce\",\n hiddenFromList: false,\n },\n squash: {\n type: \"number\",\n default: 0.5,\n min: 0,\n max: 1,\n step: 0.05,\n description: \"Squash\",\n hiddenFromList: false,\n },\n x: {\n type: \"number\",\n default: 0.5,\n min: 0,\n max: 1,\n step: 0.01,\n description: \"Point x\",\n hiddenFromList: false,\n },\n y: {\n type: \"number\",\n default: 0.5,\n min: 0,\n max: 1,\n step: 0.01,\n description: \"Point y\",\n hiddenFromList: false,\n },\n delay: {\n type: \"number\",\n default: 0,\n min: 0,\n max: 60,\n step: 1,\n description: \"Delay\",\n hiddenFromList: false,\n },\n color: {\n type: \"color\",\n default: \"#ffffff\",\n description: \"Line color\",\n },\n seed: {\n type: \"number\",\n default: 1,\n min: 1,\n step: 1,\n description: \"Seed\",\n hiddenFromList: false,\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"mode\",\"count\",\"weight\",\"spread\",\"duration\",\"bounce\",\"squash\",\"x\",\"y\",\"delay\",\"color\",\"seed\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n mode: \"trail\",\n count: 12,\n weight: 2,\n spread: 96,\n duration: 14,\n bounce: 0.5,\n squash: 0.5,\n x: 0.5,\n y: 0.5,\n delay: 0,\n color: \"#ffffff\",\n seed: 1,\n speed: 1,\n};\n\ntype SpeedLinesElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof SpeedLinesBase>;\n\nconst SpeedLinesInner = forwardRef<\n HTMLDivElement,\n SpeedLinesElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<SpeedLines>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <SpeedLinesBase\n {...(componentProps as unknown as ComponentProps<typeof SpeedLinesBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const SpeedLines = Interactive.withSchema({\n Component: SpeedLinesInner,\n componentName: \"<SpeedLines>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 31+}diff --git a/registry-artifacts/elements/squiggle.json b/registry-artifacts/elements/squiggle.jsonnew file mode 100644index 00000000..1695424d--- /dev/null+++ b/registry-artifacts/elements/squiggle.json@@ -0,0 +1,14 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [],+ "dimensions": null,+ "displayName": "Squiggle",+ "durationInFrames": 66,+ "installationMode": "component-owned-sequence",+ "slug": "squiggle",+ "sourceCode": "import { Interactive, Sequence, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\nimport { forwardRef, useImperativeHandle, useRef, type ComponentProps } from \"react\";\n\ntype SquiggleShape = \"wave\" | \"zigzag\" | \"loops\" | \"coil\";\ntype SquiggleJoin = \"miter\" | \"round\";\n\ninterface SquiggleProps {\n shape?: SquiggleShape;\n x?: number;\n y?: number;\n length?: number;\n angle?: number;\n amplitude?: number;\n wavelength?: number;\n weight?: number;\n color?: string;\n settle?: number;\n hold?: number;\n erase?: boolean;\n delay?: number;\n speed?: number;\n className?: string;\n}\n\ntype Paint = \"color\" | \"className\";\n\ninterface SquiggleOptions extends Omit<SquiggleProps, Paint> {\n width?: number;\n height?: number;\n fps?: number;\n}\n\ninterface SquigglePoint {\n x: number;\n y: number;\n}\n\ninterface SquiggleCurveInput {\n shape: SquiggleShape;\n length: number;\n wavelength: number;\n amplitude: number;\n phase: number;\n unit?: number;\n}\n\nconst squiggleDefaults: Required<Omit<SquiggleProps, \"className\">> = {\n shape: \"wave\",\n x: 0.375,\n y: 0.5,\n length: 320,\n angle: 0,\n amplitude: 14,\n wavelength: 48,\n weight: 3,\n color: \"#ffffff\",\n settle: 0.5,\n hold: 12,\n erase: true,\n delay: 0,\n speed: 1,\n};\n\ntype SmoothShape = Exclude<SquiggleShape, \"zigzag\">;\n\nconst DRAW = 24;\nconst SETTLE = 36;\nconst ERASE = 18;\nconst SWIM = 1.5;\nconst EXIT_SWIM = 0.5;\nconst TAIL = 14;\nconst REST = 24;\nconst MIN_WAVELENGTH = 8;\nconst LOOP_FLOOR = 3;\nconst MIN_POINTS = 24;\nconst MAX_POINTS = 4000;\nconst EPSILON = 0.01;\nconst SAMPLES: Record<SmoothShape, number> = { wave: 32, loops: 64, coil: 80 };\nconst REACH: Record<SmoothShape, number> = { wave: 0, loops: 2.4, coil: 4.2 };\n\nconst finite = (value: number | undefined, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst round = (value: number) => Math.round(value * 100) / 100;\nconst rateOf = (speed: number | undefined) =>\n Math.max(0, finite(speed, squiggleDefaults.speed));\nconst shapeOf = (value: string | undefined): SquiggleShape =>\n value === \"zigzag\" || value === \"loops\" || value === \"coil\" ? value : \"wave\";\nconst joinOf = (shape: SquiggleShape): SquiggleJoin =>\n shape === \"zigzag\" ? \"miter\" : \"round\";\nconst easeOutQuart = (t: number) => 1 - (1 - t) ** 4;\nconst easeOutCubic = (t: number) => 1 - (1 - t) ** 3;\nconst easeInOutCubic = (t: number) =>\n t < 0.5 ? 4 * t ** 3 : 1 - (-2 * t + 2) ** 3 / 2;\nconst easeInOutSine = (t: number) => (1 - Math.cos(Math.PI * t)) / 2;\n\nfunction smoothstep(value: number) {\n const t = clamp(value, 0, 1);\n return t * t * (3 - 2 * t);\n}\n\nfunction getSquiggleTimeline(\n options: Pick<SquiggleOptions, \"hold\" | \"erase\"> = {},\n) {\n const hold = Math.max(0, finite(options.hold, squiggleDefaults.hold));\n const erase = options.erase !== false;\n const eraseStart = SETTLE + hold;\n const eraseEnd = eraseStart + ERASE;\n const end = erase ? eraseEnd : SETTLE;\n return {\n draw: DRAW,\n settle: SETTLE,\n hold,\n erase,\n eraseStart,\n eraseEnd,\n end,\n duration: end + (erase ? TAIL : REST),\n };\n}\n\ntype SquiggleTimeline = ReturnType<typeof getSquiggleTimeline>;\n\nconst squiggleLength = getSquiggleTimeline().end;\n\nfunction getSquiggleDuration(\n options: Pick<SquiggleOptions, \"hold\" | \"erase\" | \"speed\" | \"delay\"> = {},\n) {\n const rate = rateOf(options.speed);\n if (rate === 0) return 1;\n const delay = Math.max(0, finite(options.delay, squiggleDefaults.delay));\n const { duration } = getSquiggleTimeline(options);\n return Math.max(1, Math.ceil(delay + duration / rate));\n}\n\nfunction getSquiggleTime(\n frame: number,\n options: Pick<SquiggleOptions, \"fps\" | \"speed\" | \"delay\"> = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const delay = Math.max(0, finite(options.delay, squiggleDefaults.delay));\n const elapsed = Math.max(0, finite(frame, 0) - delay);\n return (elapsed * 30 * rateOf(options.speed)) / fps;\n}\n\nfunction getSquiggleHead(time: number) {\n if (!(time > 0)) return 0;\n return easeOutQuart(Math.min(1, time / DRAW));\n}\n\nfunction getSquiggleTail(\n time: number,\n timeline: SquiggleTimeline = getSquiggleTimeline(),\n) {\n if (!timeline.erase) return 0;\n const progress = (time - timeline.eraseStart) / ERASE;\n if (!(progress > 0)) return 0;\n return easeInOutCubic(Math.min(1, progress));\n}\n\nfunction getSquiggleCalm(time: number) {\n if (!(time > 0)) return 0;\n return easeInOutSine(Math.min(1, time / SETTLE));\n}\n\nfunction getSquigglePhase(\n time: number,\n timeline: SquiggleTimeline = getSquiggleTimeline(),\n) {\n const swim = time > 0 ? easeOutCubic(Math.min(1, time / SETTLE)) : 0;\n return SWIM * swim + EXIT_SWIM * getSquiggleTail(time, timeline);\n}\n\nfunction getSquiggleEnvelope(\n s: number,\n length: number,\n wavelength: number,\n) {\n const taper = Math.min(wavelength, length / 3);\n if (!(taper > 0)) return 0;\n return smoothstep(s / taper) * smoothstep((length - s) / taper);\n}\n\nfunction getZigzagCurve(\n length: number,\n wavelength: number,\n amplitude: number,\n shift: number,\n) {\n const k = (2 * Math.PI) / wavelength;\n const points: SquigglePoint[] = [{ x: 0, y: 0 }];\n const first = Math.floor(-(Math.PI / 2 + shift) / Math.PI) + 1;\n for (let m = first; points.length < MAX_POINTS - 1; m++) {\n const s = (Math.PI / 2 + m * Math.PI + shift) / k;\n if (s >= length) break;\n if (s <= 0) continue;\n const side = m % 2 === 0 ? 1 : -1;\n const w = getSquiggleEnvelope(s, length, wavelength);\n points.push({ x: s, y: side * amplitude * w });\n }\n points.push({ x: length, y: 0 });\n return points;\n}\n\nfunction getSquiggleCurve(input: SquiggleCurveInput) {\n const shape = shapeOf(input.shape);\n const length = Math.max(0, finite(input.length, 0));\n const wavelength = Math.max(1e-3, finite(input.wavelength, 1));\n const amplitude = Math.max(0, finite(input.amplitude, 0));\n const unit = Math.max(1e-3, finite(input.unit, 1));\n const shift = 2 * Math.PI * finite(input.phase, 0);\n if (shape === \"zigzag\") {\n return getZigzagCurve(length, wavelength, amplitude, shift);\n }\n const k = (2 * Math.PI) / wavelength;\n const gate = smoothstep(amplitude / (LOOP_FLOOR * unit));\n const reach = (REACH[shape] / k) * gate;\n const fine = wavelength / (SAMPLES[shape] * Math.max(1, unit));\n const coarsest = Math.max(length / MIN_POINTS, 1e-6);\n const step = clamp(fine, length / (MAX_POINTS - 2), coarsest);\n const sample = (s: number): SquigglePoint => {\n const w = getSquiggleEnvelope(s, length, wavelength);\n const theta = k * s - shift;\n if (shape === \"wave\") return { x: s, y: amplitude * w * Math.sin(theta) };\n const along = s - reach * w * Math.sin(theta);\n return { x: along, y: -amplitude * w * Math.cos(theta) };\n };\n const offset = (((shift / k) % step) + step) % step;\n const points = [sample(0)];\n for (let j = 0; points.length < MAX_POINTS - 1; j++) {\n const s = offset + j * step;\n if (s >= length) break;\n if (s > 0) points.push(sample(s));\n }\n points.push(sample(length));\n return points;\n}\n\nfunction getSquiggleTrim(\n points: readonly SquigglePoint[],\n tail: number,\n head: number,\n) {\n const lengths = [0];\n for (let i = 1; i < points.length; i++) {\n const a = points[i - 1];\n const b = points[i];\n lengths.push(lengths[i - 1] + Math.hypot(b.x - a.x, b.y - a.y));\n }\n const last = points.length - 1;\n const total = last > 0 ? lengths[last] : 0;\n const from = clamp(finite(tail, 0), 0, 1) * total;\n const to = clamp(finite(head, 0), 0, 1) * total;\n const trimmed: SquigglePoint[] = [];\n if (last < 1 || !(to - from > EPSILON)) return { total, points: trimmed };\n const pointAt = (distance: number, index: number): SquigglePoint => {\n const a = points[index - 1];\n const b = points[index];\n const span = lengths[index] - lengths[index - 1];\n const t = span > 0 ? (distance - lengths[index - 1]) / span : 0;\n return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };\n };\n let index = 1;\n while (index < last && lengths[index] < from) index++;\n trimmed.push(pointAt(from, index));\n while (index < last && lengths[index] < to) {\n trimmed.push(points[index]);\n index++;\n }\n trimmed.push(pointAt(to, index));\n return { total, points: trimmed };\n}\n\nfunction getSquigglePath(points: readonly SquigglePoint[]) {\n let path = \"\";\n let previous = \"\";\n for (const point of points) {\n const pair = `${round(point.x)} ${round(point.y)}`;\n if (pair === previous) continue;\n path += `${path === \"\" ? \"M\" : \"L\"}${pair}`;\n previous = pair;\n }\n return path;\n}\n\nfunction getSquiggleState(frame: number, options: SquiggleOptions = {}) {\n const width = Math.max(1, finite(options.width, 1280));\n const height = Math.max(1, finite(options.height, 720));\n const unit = height / 720;\n const shape = shapeOf(options.shape);\n const timeline = getSquiggleTimeline(options);\n const time = getSquiggleTime(frame, options);\n const head = getSquiggleHead(time);\n const tail = getSquiggleTail(time, timeline);\n const phase = getSquigglePhase(time, timeline);\n const settle = clamp(finite(options.settle, squiggleDefaults.settle), 0, 1);\n const lively = finite(options.amplitude, squiggleDefaults.amplitude);\n const calm = 1 - settle * getSquiggleCalm(time);\n const amplitude = Math.max(0, lively) * unit * calm;\n const length = Math.max(0, finite(options.length, squiggleDefaults.length));\n const course = length * unit;\n const cycle = finite(options.wavelength, squiggleDefaults.wavelength);\n const wavelength = Math.max(MIN_WAVELENGTH, cycle) * unit;\n const weight = Math.max(0, finite(options.weight, squiggleDefaults.weight));\n const angle = finite(options.angle, squiggleDefaults.angle);\n const radians = (angle * Math.PI) / 180;\n const cos = Math.cos(radians);\n const sin = Math.sin(radians);\n const start = {\n x: finite(options.x, squiggleDefaults.x) * width,\n y: finite(options.y, squiggleDefaults.y) * height,\n };\n const end = { x: start.x + course * cos, y: start.y + course * sin };\n const drawn = head - tail > 0;\n const curve: SquigglePoint[] = drawn\n ? getSquiggleCurve({\n shape,\n length: course,\n wavelength,\n amplitude,\n phase,\n unit,\n })\n : [];\n const placed = curve.map((point) => ({\n x: start.x + point.x * cos - point.y * sin,\n y: start.y + point.x * sin + point.y * cos,\n }));\n const trim = getSquiggleTrim(placed, tail, head);\n const path = getSquigglePath(trim.points);\n return {\n width,\n height,\n unit,\n shape,\n time,\n timeline,\n head,\n tail,\n phase,\n amplitude,\n wavelength,\n length: course,\n strokeWidth: round(weight * unit),\n join: joinOf(shape),\n start,\n end,\n total: trim.total,\n points: trim.points,\n path,\n visible: path.includes(\"L\"),\n };\n}\n\ntype SquiggleState = ReturnType<typeof getSquiggleState>;\n\nfunction SquiggleBase({\n shape = squiggleDefaults.shape,\n x = squiggleDefaults.x,\n y = squiggleDefaults.y,\n length = squiggleDefaults.length,\n angle = squiggleDefaults.angle,\n amplitude = squiggleDefaults.amplitude,\n wavelength = squiggleDefaults.wavelength,\n weight = squiggleDefaults.weight,\n color = squiggleDefaults.color,\n settle = squiggleDefaults.settle,\n hold = squiggleDefaults.hold,\n erase = squiggleDefaults.erase,\n delay = squiggleDefaults.delay,\n speed = squiggleDefaults.speed,\n className,\n}: SquiggleProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const state = getSquiggleState(frame, {\n shape,\n x,\n y,\n length,\n angle,\n amplitude,\n wavelength,\n weight,\n settle,\n hold,\n erase,\n delay,\n speed,\n width,\n height,\n fps,\n });\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, pointerEvents: \"none\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n role=\"img\"\n aria-label=\"SquiggleBase line\"\n style={{ display: \"block\" }}\n >\n {state.visible ? (\n <path\n d={state.path}\n fill=\"none\"\n stroke={color}\n strokeWidth={state.strokeWidth}\n strokeLinecap=\"round\"\n strokeLinejoin={state.join}\n />\n ) : null}\n </svg>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n shape: {\n type: \"enum\",\n default: \"wave\",\n variants: {\n wave: {},\n zigzag: {},\n loops: {},\n coil: {},\n },\n description: \"Shape\",\n },\n color: {\n type: \"color\",\n default: \"#ffffff\",\n description: \"Line color\",\n },\n weight: {\n type: \"number\",\n default: 3,\n min: 1,\n max: 12,\n step: 0.5,\n description: \"Stroke weight\",\n hiddenFromList: false,\n },\n amplitude: {\n type: \"number\",\n default: 14,\n min: 0,\n max: 60,\n step: 1,\n description: \"Amplitude\",\n hiddenFromList: false,\n },\n wavelength: {\n type: \"number\",\n default: 48,\n min: 12,\n max: 160,\n step: 2,\n description: \"Wavelength\",\n hiddenFromList: false,\n },\n length: {\n type: \"number\",\n default: 320,\n min: 40,\n max: 1200,\n step: 10,\n description: \"Length\",\n hiddenFromList: false,\n },\n angle: {\n type: \"number\",\n default: 0,\n min: -180,\n max: 180,\n step: 5,\n description: \"Angle\",\n hiddenFromList: false,\n },\n x: {\n type: \"number\",\n default: 0.375,\n min: 0,\n max: 1,\n step: 0.005,\n description: \"Start x\",\n hiddenFromList: false,\n },\n y: {\n type: \"number\",\n default: 0.5,\n min: 0,\n max: 1,\n step: 0.005,\n description: \"Start y\",\n hiddenFromList: false,\n },\n settle: {\n type: \"number\",\n default: 0.5,\n min: 0,\n max: 1,\n step: 0.05,\n description: \"Settle\",\n hiddenFromList: false,\n },\n hold: {\n type: \"number\",\n default: 12,\n min: 0,\n max: 90,\n step: 1,\n description: \"Hold\",\n hiddenFromList: false,\n },\n erase: {\n type: \"boolean\",\n default: true,\n description: \"Erase\",\n },\n delay: {\n type: \"number\",\n default: 0,\n min: 0,\n max: 60,\n step: 1,\n description: \"Delay\",\n hiddenFromList: false,\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"shape\",\"color\",\"weight\",\"amplitude\",\"wavelength\",\"length\",\"angle\",\"x\",\"y\",\"settle\",\"hold\",\"erase\",\"delay\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n shape: \"wave\",\n color: \"#ffffff\",\n weight: 3,\n amplitude: 14,\n wavelength: 48,\n length: 320,\n angle: 0,\n x: 0.375,\n y: 0.5,\n settle: 0.5,\n hold: 12,\n erase: true,\n delay: 0,\n speed: 1,\n};\n\ntype SquiggleElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof SquiggleBase>;\n\nconst SquiggleInner = forwardRef<\n HTMLDivElement,\n SquiggleElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<Squiggle>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <SquiggleBase\n {...(componentProps as unknown as ComponentProps<typeof SquiggleBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const Squiggle = Interactive.withSchema({\n Component: SquiggleInner,\n componentName: \"<Squiggle>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 66+}diff --git a/registry-artifacts/elements/stripe-type.json b/registry-artifacts/elements/stripe-type.jsonnew file mode 100644index 00000000..eb8820ad--- /dev/null+++ b/registry-artifacts/elements/stripe-type.json@@ -0,0 +1,19 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [+ {+ "name": "@remotion/google-fonts",+ "version": null+ }+ ],+ "dimensions": null,+ "displayName": "Stripe Type",+ "durationInFrames": 30,+ "installationMode": "component-owned-sequence",+ "slug": "stripe-type",+ "sourceCode": "import { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { forwardRef, useEffect, useImperativeHandle, useRef, useState, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, continueRender, delayRender, interpolate, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\ntype StripeTypeSettle = \"striped\" | \"solid\";\n\ninterface StripeTypeProps {\n text?: string;\n fontSize?: number;\n fontWeight?: number;\n fontFamily?: string;\n color?: string;\n stripes?: number;\n gap?: number;\n settle?: StripeTypeSettle;\n exit?: boolean;\n hold?: number;\n speed?: number;\n className?: string;\n}\n\nconst stripeTypeDefaults = {\n text: \"Launch\",\n fontSize: 180,\n fontWeight: 800,\n fontFamily: INTER,\n color: \"#fafafa\",\n stripes: 8,\n gap: 0.35,\n settle: \"striped\",\n exit: true,\n hold: 30,\n speed: 1,\n} satisfies Required<Omit<StripeTypeProps, \"className\">>;\n\n/** Beats on the 30 fps clock. */\nconst stripeTypeTiming = {\n stagger: 2,\n travel: 16,\n close: 10,\n /** Frames of empty screen after the exit in the preview. */\n tail: 10,\n} as const;\n\n/** Ink box of Inter in a `line-height: 1` box, in em from the top, until measured. */\nconst INTER_INK = { top: 0.136, bottom: 0.864 + 0.24 };\nconst MEASURE_SIZE = 100;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\n// Expo-shaped curves that land exactly on 0 and 1 (Easing.exp stops 2⁻¹⁰ short).\nconst easeOutExpo = Easing.bezier(0.16, 1, 0.3, 1);\nconst easeInExpo = Easing.bezier(0.7, 0, 0.84, 0);\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nfunction getStripeTypeTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\nfunction stripeCount(stripes: number | undefined) {\n return Math.max(1, Math.round(finite(stripes, stripeTypeDefaults.stripes)));\n}\n\ninterface StripeBand {\n /** Top of the band as a share of the ink box height. */\n top: number;\n /** Bottom of the band as a share of the ink box height. */\n bottom: number;\n}\n\n/**\n * Bands over the ink box. With `n` bands and gap share `g` the pitch is\n * `1 / (n − g)`: the first band starts at the top, the last ends at the\n * bottom.\n */\nfunction getStripeBands(stripes: number, gap: number): StripeBand[] {\n const n = stripeCount(stripes);\n const g = Math.min(0.95, Math.max(0, finite(gap, 0)));\n const pitch = 1 / (n - g);\n return Array.from({ length: n }, (_, k) => ({\n top: k * pitch,\n bottom: k * pitch + pitch * (1 - g),\n }));\n}\n\ninterface StripeTypeTimeline {\n /** Frame where the last band has locked. */\n entered: number;\n /** Frame where the gaps have closed (equals `entered` when striped). */\n settled: number;\n exitStart: number;\n exitEnd: number;\n /** Frames the preview needs. */\n duration: number;\n}\n\nfunction getStripeTypeTimeline(\n options: Pick<StripeTypeProps, \"stripes\" | \"settle\" | \"exit\" | \"hold\"> = {},\n): StripeTypeTimeline {\n const n = stripeCount(options.stripes);\n const { stagger, travel, close, tail } = stripeTypeTiming;\n const entered = stagger * (n - 1) + travel;\n const settled = options.settle === \"solid\" ? entered + close : entered;\n const hold = Math.max(0, finite(options.hold, stripeTypeDefaults.hold));\n const exitStart = settled + hold;\n const exitEnd = exitStart + stagger * (n - 1) + travel;\n const exit = options.exit !== false;\n return {\n entered,\n settled,\n exitStart,\n exitEnd,\n duration: exit ? exitEnd + tail : settled + hold,\n };\n}\n\n/** Preview length for the given options and speed. */\nfunction getStripeTypeDuration(\n options: Pick<\n StripeTypeProps,\n \"stripes\" | \"settle\" | \"exit\" | \"hold\" | \"speed\"\n > = {},\n) {\n const speed = finite(options.speed, 1);\n if (speed <= 0) return 1;\n return Math.ceil(getStripeTypeTimeline(options).duration / speed);\n}\n\n/**\n * Horizontal offset of band `k` as a share of its travel distance: −1 or 1\n * off the frame, 0 locked. Even bands enter from the left, odd from the right,\n * and on the exit each band passes on through the other side.\n */\nfunction getStripeBandOffset(\n t: number,\n k: number,\n options: Pick<StripeTypeProps, \"stripes\" | \"settle\" | \"exit\" | \"hold\"> = {},\n) {\n const { stagger, travel } = stripeTypeTiming;\n const timeline = getStripeTypeTimeline(options);\n const side = k % 2 === 0 ? -1 : 1;\n const inStart = stagger * k;\n const enter = interpolate(t, [inStart, inStart + travel], [1, 0], {\n ...CLAMP,\n easing: easeOutExpo,\n });\n // `|| 0` folds −0 into 0 for a locked band.\n if (options.exit === false) return side * enter || 0;\n const outStart = timeline.exitStart + stagger * k;\n const leave = interpolate(t, [outStart, outStart + travel], [0, 1], {\n ...CLAMP,\n easing: easeInExpo,\n });\n return side * enter - side * leave || 0;\n}\n\n/** Gap share over time: the set gap, closing to 0 when `settle` is solid. */\nfunction getStripeGap(\n t: number,\n gap: number,\n options: Pick<StripeTypeProps, \"stripes\" | \"settle\"> = {},\n) {\n if (options.settle !== \"solid\") return gap;\n const { entered, settled } = getStripeTypeTimeline(options);\n return interpolate(t, [entered, settled], [gap, 0], {\n ...CLAMP,\n easing: easeInOutCubic,\n });\n}\n\n/** Ink box of the word in its `line-height: 1` box, and its width, in em. */\nfunction useInkBox(text: string, font: string) {\n const [ink, setInk] = useState<{\n top: number;\n bottom: number;\n width: number;\n } | null>(null);\n\n useEffect(() => {\n const handle = delayRender(\"stripe-type: measuring the word\");\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n continueRender(handle);\n };\n const measure = () => {\n if (released) return;\n const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n if (ctx) {\n ctx.font = font;\n const m = ctx.measureText(text);\n const ascent = m.fontBoundingBoxAscent / MEASURE_SIZE;\n const descent = m.fontBoundingBoxDescent / MEASURE_SIZE;\n const baseline = (1 - (ascent + descent)) / 2 + ascent;\n if (ascent > 0) {\n setInk({\n top: baseline - m.actualBoundingBoxAscent / MEASURE_SIZE,\n bottom: baseline + m.actualBoundingBoxDescent / MEASURE_SIZE,\n width: m.width / MEASURE_SIZE,\n });\n }\n }\n release();\n };\n document.fonts.load(font, text).then(measure, measure);\n return release;\n }, [text, font]);\n\n return ink;\n}\n\nfunction StripeTypeBase({\n text = stripeTypeDefaults.text,\n fontSize = stripeTypeDefaults.fontSize,\n fontWeight = stripeTypeDefaults.fontWeight,\n fontFamily = stripeTypeDefaults.fontFamily,\n color = stripeTypeDefaults.color,\n stripes = stripeTypeDefaults.stripes,\n gap = stripeTypeDefaults.gap,\n settle = stripeTypeDefaults.settle,\n exit = stripeTypeDefaults.exit,\n hold = stripeTypeDefaults.hold,\n speed = stripeTypeDefaults.speed,\n className,\n}: StripeTypeProps) {\n const frame = useCurrentFrame();\n const { fps, width, height } = useVideoConfig();\n const unit = height / 720;\n const size = fontSize * unit;\n const t = getStripeTypeTime(frame, { fps, speed });\n const measured = useInkBox(\n text,\n `${fontWeight} ${MEASURE_SIZE}px ${fontFamily}`,\n );\n const ink = measured ?? {\n ...INTER_INK,\n width: 0.6 * Array.from(text).length,\n };\n const options = { stripes, settle, exit, hold };\n const bands = getStripeBands(stripes, getStripeGap(t, gap, options));\n const inkHeight = ink.bottom - ink.top;\n // Far enough that a band starting on either side is fully off the frame.\n const travel = (width + ink.width * size) / 2 + 0.2 * size;\n\n const type = {\n fontFamily,\n fontSize: size,\n lineHeight: 1,\n fontWeight,\n fontVariationSettings: `\"wght\" ${fontWeight}`,\n color,\n whiteSpace: \"pre\",\n } as const;\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n }}\n >\n <div style={{ position: \"relative\" }}>\n <div aria-hidden style={{ ...type, visibility: \"hidden\" }}>\n {text}\n </div>\n {bands.map((band, k) => {\n const top = (ink.top + band.top * inkHeight) * 100;\n // Each band reaches a pixel into the next gap, so closed gaps leave\n // no antialiased seam between bands.\n const bleed = k < bands.length - 1 ? Math.max(1, unit) / size : 0;\n const bottom =\n (1 - (ink.top + band.bottom * inkHeight) - bleed) * 100;\n const offset = getStripeBandOffset(t, k, options);\n return (\n <div\n key={k}\n aria-hidden={k > 0}\n style={{\n ...type,\n position: \"absolute\",\n inset: 0,\n clipPath: `inset(${top}% -1% ${bottom}% -1%)`,\n transform: `translateX(${offset * travel}px)`,\n }}\n >\n {text}\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n text: {\n type: \"text-content\",\n default: \"Launch\",\n description: \"Text\",\n },\n color: {\n type: \"color\",\n default: \"#fafafa\",\n description: \"Text color\",\n },\n settle: {\n type: \"enum\",\n default: \"striped\",\n variants: {\n striped: {},\n solid: {},\n },\n description: \"Settle\",\n },\n fontSize: {\n type: \"number\",\n default: 180,\n min: 60,\n max: 320,\n step: 2,\n description: \"Font size\",\n hiddenFromList: false,\n },\n fontWeight: {\n type: \"number\",\n default: 800,\n min: 100,\n max: 900,\n step: 50,\n description: \"Weight\",\n hiddenFromList: false,\n },\n stripes: {\n type: \"number\",\n default: 8,\n min: 2,\n max: 16,\n step: 1,\n description: \"Stripes\",\n hiddenFromList: false,\n },\n gap: {\n type: \"number\",\n default: 0.35,\n min: 0,\n max: 0.8,\n step: 0.05,\n description: \"Gap\",\n hiddenFromList: false,\n },\n hold: {\n type: \"number\",\n default: 30,\n min: 0,\n max: 120,\n step: 5,\n description: \"Hold\",\n hiddenFromList: false,\n },\n exit: {\n type: \"boolean\",\n default: true,\n description: \"Exit\",\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"text\",\"color\",\"settle\",\"fontSize\",\"fontWeight\",\"stripes\",\"gap\",\"hold\",\"exit\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n text: \"Launch\",\n color: \"#fafafa\",\n settle: \"striped\",\n fontSize: 180,\n fontWeight: 800,\n stripes: 8,\n gap: 0.35,\n hold: 30,\n exit: true,\n speed: 1,\n};\n\ntype StripeTypeElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof StripeTypeBase>;\n\nconst StripeTypeInner = forwardRef<\n HTMLDivElement,\n StripeTypeElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<StripeType>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <StripeTypeBase\n {...(componentProps as unknown as ComponentProps<typeof StripeTypeBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const StripeType = Interactive.withSchema({\n Component: StripeTypeInner,\n componentName: \"<StripeType>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 30+}diff --git a/registry-artifacts/elements/trim-burst.json b/registry-artifacts/elements/trim-burst.jsonnew file mode 100644index 00000000..4ab8457c--- /dev/null+++ b/registry-artifacts/elements/trim-burst.json@@ -0,0 +1,14 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [],+ "dimensions": null,+ "displayName": "Trim Burst",+ "durationInFrames": 18,+ "installationMode": "component-owned-sequence",+ "slug": "trim-burst",+ "sourceCode": "import { forwardRef, useImperativeHandle, useMemo, useRef, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, random, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\ntype TrimBurstCap = \"round\" | \"butt\";\n\ninterface TrimBurstProps {\n x?: number;\n y?: number;\n count?: number;\n innerRadius?: number;\n reach?: number;\n strokeLength?: number;\n weight?: number;\n rotation?: number;\n spread?: number;\n jitter?: number;\n dots?: boolean;\n cap?: TrimBurstCap;\n color?: string;\n seed?: number;\n delay?: number;\n speed?: number;\n className?: string;\n}\n\ntype Paint = \"color\" | \"className\";\n\ninterface TrimBurstOptions extends Omit<TrimBurstProps, Paint> {\n width?: number;\n height?: number;\n fps?: number;\n}\n\ninterface TrimBurstStroke {\n index: number;\n angle: number;\n scale: number;\n launch: number;\n}\n\ninterface TrimBurstTrim {\n start: number;\n end: number;\n length: number;\n}\n\ninterface TrimBurstLine {\n index: number;\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n width: number;\n}\n\ninterface TrimBurstDot {\n index: number;\n cx: number;\n cy: number;\n r: number;\n}\n\nconst trimBurstDefaults: Required<Omit<TrimBurstProps, \"className\">> = {\n x: 0.5,\n y: 0.5,\n count: 8,\n innerRadius: 16,\n reach: 64,\n strokeLength: 56,\n weight: 2,\n rotation: 0,\n spread: 360,\n jitter: 0.5,\n dots: false,\n cap: \"round\",\n color: \"#ffffff\",\n seed: 1,\n delay: 0,\n speed: 1,\n};\n\nconst LIFE = 15;\nconst LAG = 3;\nconst STAGGER = 6;\nconst HOLD = 24;\nconst LEASH = 6;\nconst WOBBLE = 0.25;\nconst MAX_STEP = 45;\nconst SHRINK = 0.45;\nconst DOT_START = 4;\nconst DOT_POP = 4;\nconst DOT_BACK = 1.4;\nconst DOT_RADIUS = 1.25;\nconst DOT_GAP = 2;\nconst MAX_COUNT = 32;\nconst MAX_SIZE = 2000;\nconst MIN_STROKE = 1;\nconst MIN_WEIGHT = 0.25;\nconst MAX_WEIGHT = 24;\nconst VISIBLE = 0.001;\nconst END_EASE = Easing.bezier(0.16, 1, 0.3, 1);\nconst START_EASE = Easing.bezier(0.45, 0, 0.55, 1);\n\nconst finite = (value: number | undefined, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst within = (\n value: number | undefined,\n fallback: number,\n min: number,\n max: number,\n) => clamp(finite(value, fallback), min, max);\nconst round = (value: number) => Math.round(value * 1000) / 1000;\nconst rateOf = (speed: number | undefined) =>\n Math.max(0, finite(speed, trimBurstDefaults.speed));\nconst delayOf = (delay: number | undefined) =>\n Math.max(0, finite(delay, trimBurstDefaults.delay));\nconst countOf = (count: number | undefined) =>\n Math.round(within(count, trimBurstDefaults.count, 1, MAX_COUNT));\nconst jitterOf = (jitter: number | undefined) =>\n within(jitter, trimBurstDefaults.jitter, 0, 1);\nconst capOf = (cap: string | undefined): TrimBurstCap =>\n cap === \"butt\" ? cap : \"round\";\n\nfunction getTrimBurstTimeline(\n options: Pick<TrimBurstOptions, \"count\" | \"jitter\"> = {},\n) {\n const count = countOf(options.count);\n const stagger = count > 1 ? STAGGER * jitterOf(options.jitter) : 0;\n return { life: LIFE, lag: LAG, stagger, length: LIFE + stagger };\n}\n\ntype TrimBurstTimeline = ReturnType<typeof getTrimBurstTimeline>;\n\nconst trimBurstLength = getTrimBurstTimeline().length;\n\nfunction getTrimBurstDuration(\n options: Pick<TrimBurstOptions, \"count\" | \"jitter\" | \"delay\" | \"speed\"> = {},\n) {\n const rate = rateOf(options.speed);\n const { length } = getTrimBurstTimeline(options);\n const motion = rate === 0 ? 0 : length / rate;\n return Math.ceil(round(delayOf(options.delay) + motion)) + HOLD;\n}\n\nfunction getTrimBurstTime(\n frame: number,\n options: Pick<TrimBurstOptions, \"fps\" | \"delay\" | \"speed\"> = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const elapsed = Math.max(0, finite(frame, 0) - delayOf(options.delay));\n return elapsed * (30 / fps) * rateOf(options.speed);\n}\n\nfunction getTrimBurstEndProgress(time: number) {\n if (Number.isNaN(time) || time <= 0) return 0;\n if (time >= LIFE) return 1;\n return END_EASE(time / LIFE);\n}\n\nfunction getTrimBurstStartProgress(time: number) {\n if (Number.isNaN(time) || time <= LAG) return 0;\n if (time >= LIFE) return 1;\n return START_EASE((time - LAG) / (LIFE - LAG));\n}\n\nfunction getTrimBurstLeash(gap: number, strokeLength: number) {\n if (!(gap > 0 && strokeLength > 0)) return 0;\n return gap / (1 + (gap / strokeLength) ** LEASH) ** (1 / LEASH);\n}\n\nfunction getTrimBurstTrim(\n time: number,\n reach: number,\n strokeLength: number,\n): TrimBurstTrim {\n const distance = Math.max(0, finite(reach, 0));\n const end = distance * getTrimBurstEndProgress(time);\n const own = distance * getTrimBurstStartProgress(time);\n const length = getTrimBurstLeash(end - own, strokeLength);\n return { start: end - length, end, length };\n}\n\nfunction getTrimBurstDotScale(time: number) {\n if (Number.isNaN(time) || time <= DOT_START || time >= LIFE) return 0;\n const pop = Math.min(1, (time - DOT_START) / DOT_POP) - 1;\n const grow = 1 + (DOT_BACK + 1) * pop ** 3 + DOT_BACK * pop ** 2;\n const settle = DOT_START + DOT_POP;\n const shrink = clamp((time - settle) / (LIFE - settle), 0, 1);\n return grow * (1 - shrink ** 3);\n}\n\nfunction getTrimBurstStrokes(\n options: Pick<\n TrimBurstOptions,\n \"count\" | \"rotation\" | \"spread\" | \"jitter\" | \"seed\"\n > = {},\n): TrimBurstStroke[] {\n const count = countOf(options.count);\n const rotation = finite(options.rotation, trimBurstDefaults.rotation);\n const spread = within(options.spread, trimBurstDefaults.spread, 0, 360);\n const jitter = jitterOf(options.jitter);\n const seed = finite(options.seed, trimBurstDefaults.seed);\n const fan = spread < 360 && count > 1;\n const step = fan ? spread / (count - 1) : 360 / count;\n const first = fan ? rotation - spread / 2 : rotation;\n const wobble = WOBBLE * jitter * Math.min(step, MAX_STEP);\n const { stagger } = getTrimBurstTimeline({ count, jitter });\n const keys = Array.from({ length: count }, (_, index) =>\n random(`trim-burst-${seed}-order-${index}`),\n );\n const order = keys.map((_, index) => index);\n order.sort((a, b) => keys[a] - keys[b]);\n const ranks: number[] = [];\n for (const [position, index] of order.entries()) ranks[index] = position;\n return keys.map((_, index) => {\n const turn = random(`trim-burst-${seed}-angle-${index}`) * 2 - 1;\n const shrink = random(`trim-burst-${seed}-scale-${index}`);\n return {\n index,\n angle: first + index * step + turn * wobble,\n scale: 1 - SHRINK * jitter * shrink,\n launch: count > 1 ? (stagger * ranks[index]) / (count - 1) : 0,\n };\n });\n}\n\nfunction getTrimBurstState(\n frame: number,\n options: TrimBurstOptions = {},\n strokes: TrimBurstStroke[] = getTrimBurstStrokes(options),\n) {\n const fallback = trimBurstDefaults;\n const width = Math.max(1, finite(options.width, 1280));\n const height = Math.max(1, finite(options.height, 720));\n const unit = height / 720;\n const time = getTrimBurstTime(frame, options);\n const originX = finite(options.x, fallback.x) * width;\n const originY = finite(options.y, fallback.y) * height;\n const inner = within(options.innerRadius, fallback.innerRadius, 0, MAX_SIZE);\n const reach = within(options.reach, fallback.reach, 0, MAX_SIZE);\n const strokeLength = within(\n options.strokeLength,\n fallback.strokeLength,\n MIN_STROKE,\n MAX_SIZE,\n );\n const size = within(options.weight, fallback.weight, MIN_WEIGHT, MAX_WEIGHT);\n const offset = inner * unit;\n const weight = size * unit;\n const gap = DOT_GAP * weight;\n const radius = DOT_RADIUS * weight;\n const lines: TrimBurstLine[] = [];\n const dots: TrimBurstDot[] = [];\n for (const stroke of strokes) {\n const local = time - stroke.launch;\n const trim = getTrimBurstTrim(\n local,\n reach * unit * stroke.scale,\n strokeLength * unit * stroke.scale,\n );\n const angle = (stroke.angle * Math.PI) / 180;\n const dx = Math.sin(angle);\n const dy = -Math.cos(angle);\n const along = (distance: number) => ({\n x: round(originX + dx * (offset + distance)),\n y: round(originY + dy * (offset + distance)),\n });\n if (trim.length > VISIBLE) {\n const from = along(trim.start);\n const to = along(trim.end);\n lines.push({\n index: stroke.index,\n x1: from.x,\n y1: from.y,\n x2: to.x,\n y2: to.y,\n width: round(Math.min(weight, trim.length)),\n });\n }\n const pop = options.dots === true ? getTrimBurstDotScale(local) : 0;\n if (pop > 0) {\n const center = along(trim.end + gap + radius);\n dots.push({\n index: stroke.index,\n cx: center.x,\n cy: center.y,\n r: round(radius * pop),\n });\n }\n }\n return {\n width,\n height,\n unit,\n time,\n originX,\n originY,\n weight,\n cap: capOf(options.cap),\n lines,\n dots,\n };\n}\n\ntype TrimBurstState = ReturnType<typeof getTrimBurstState>;\n\nfunction TrimBurstBase({\n x = trimBurstDefaults.x,\n y = trimBurstDefaults.y,\n count = trimBurstDefaults.count,\n innerRadius = trimBurstDefaults.innerRadius,\n reach = trimBurstDefaults.reach,\n strokeLength = trimBurstDefaults.strokeLength,\n weight = trimBurstDefaults.weight,\n rotation = trimBurstDefaults.rotation,\n spread = trimBurstDefaults.spread,\n jitter = trimBurstDefaults.jitter,\n dots = trimBurstDefaults.dots,\n cap = trimBurstDefaults.cap,\n color = trimBurstDefaults.color,\n seed = trimBurstDefaults.seed,\n delay = trimBurstDefaults.delay,\n speed = trimBurstDefaults.speed,\n className,\n}: TrimBurstProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const strokes = useMemo(\n () => getTrimBurstStrokes({ count, rotation, spread, jitter, seed }),\n [count, rotation, spread, jitter, seed],\n );\n const state = getTrimBurstState(\n frame,\n {\n width,\n height,\n fps,\n x,\n y,\n innerRadius,\n reach,\n strokeLength,\n weight,\n dots,\n cap,\n delay,\n speed,\n },\n strokes,\n );\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, pointerEvents: \"none\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n role=\"img\"\n aria-label=\"Trim burst\"\n style={{ display: \"block\", overflow: \"visible\" }}\n >\n <g fill=\"none\" stroke={color} strokeLinecap={state.cap}>\n {state.lines.map((line) => (\n <line\n key={line.index}\n x1={line.x1}\n y1={line.y1}\n x2={line.x2}\n y2={line.y2}\n strokeWidth={line.width}\n />\n ))}\n </g>\n <g fill={color}>\n {state.dots.map((dot) => (\n <circle key={dot.index} cx={dot.cx} cy={dot.cy} r={dot.r} />\n ))}\n </g>\n </svg>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n count: {\n type: \"number\",\n default: 8,\n min: 1,\n max: 24,\n step: 1,\n description: \"Strokes\",\n hiddenFromList: false,\n },\n innerRadius: {\n type: \"number\",\n default: 16,\n min: 0,\n max: 160,\n step: 1,\n description: \"Inner radius\",\n hiddenFromList: false,\n },\n reach: {\n type: \"number\",\n default: 64,\n min: 8,\n max: 240,\n step: 1,\n description: \"Reach\",\n hiddenFromList: false,\n },\n strokeLength: {\n type: \"number\",\n default: 56,\n min: 4,\n max: 200,\n step: 1,\n description: \"Stroke length\",\n hiddenFromList: false,\n },\n weight: {\n type: \"number\",\n default: 2,\n min: 0.5,\n max: 8,\n step: 0.5,\n description: \"Stroke weight\",\n hiddenFromList: false,\n },\n rotation: {\n type: \"number\",\n default: 0,\n min: -180,\n max: 180,\n step: 1,\n description: \"Rotation\",\n hiddenFromList: false,\n },\n spread: {\n type: \"number\",\n default: 360,\n min: 15,\n max: 360,\n step: 5,\n description: \"Spread\",\n hiddenFromList: false,\n },\n jitter: {\n type: \"number\",\n default: 0.5,\n min: 0,\n max: 1,\n step: 0.05,\n description: \"Jitter\",\n hiddenFromList: false,\n },\n dots: {\n type: \"boolean\",\n default: false,\n description: \"Tip dots\",\n },\n cap: {\n type: \"enum\",\n default: \"round\",\n variants: {\n round: {},\n butt: {},\n },\n description: \"Caps\",\n },\n color: {\n type: \"color\",\n default: \"#ffffff\",\n description: \"Line color\",\n },\n seed: {\n type: \"number\",\n default: 1,\n min: 1,\n max: 99,\n step: 1,\n description: \"Seed\",\n hiddenFromList: false,\n },\n delay: {\n type: \"number\",\n default: 0,\n min: 0,\n max: 30,\n step: 1,\n description: \"Delay\",\n hiddenFromList: false,\n },\n x: {\n type: \"number\",\n default: 0.5,\n min: 0,\n max: 1,\n step: 0.01,\n description: \"Center x\",\n hiddenFromList: false,\n },\n y: {\n type: \"number\",\n default: 0.5,\n min: 0,\n max: 1,\n step: 0.01,\n description: \"Center y\",\n hiddenFromList: false,\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"count\",\"innerRadius\",\"reach\",\"strokeLength\",\"weight\",\"rotation\",\"spread\",\"jitter\",\"dots\",\"cap\",\"color\",\"seed\",\"delay\",\"x\",\"y\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n count: 8,\n innerRadius: 16,\n reach: 64,\n strokeLength: 56,\n weight: 2,\n rotation: 0,\n spread: 360,\n jitter: 0.5,\n dots: false,\n cap: \"round\",\n color: \"#ffffff\",\n seed: 1,\n delay: 0,\n x: 0.5,\n y: 0.5,\n speed: 1,\n};\n\ntype TrimBurstElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof TrimBurstBase>;\n\nconst TrimBurstInner = forwardRef<\n HTMLDivElement,\n TrimBurstElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<TrimBurst>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <TrimBurstBase\n {...(componentProps as unknown as ComponentProps<typeof TrimBurstBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const TrimBurst = Interactive.withSchema({\n Component: TrimBurstInner,\n componentName: \"<TrimBurst>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 18+}diff --git a/registry-artifacts/elements/truchet-flip.json b/registry-artifacts/elements/truchet-flip.jsonnew file mode 100644index 00000000..cd5e3079--- /dev/null+++ b/registry-artifacts/elements/truchet-flip.json@@ -0,0 +1,14 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [],+ "dimensions": null,+ "displayName": "Truchet Flip",+ "durationInFrames": 102,+ "installationMode": "component-owned-sequence",+ "slug": "truchet-flip",+ "sourceCode": "import { forwardRef, useImperativeHandle, useMemo, useRef, type ComponentProps } from \"react\";\nimport { Interactive, Sequence, random, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\ntype TruchetFlipWaveMode = \"radial\" | \"diagonal\" | \"random\";\ntype TruchetFlipResolve = \"rings\" | \"field\" | \"silhouette\";\ntype TruchetFlipVariant = \"stroke\" | \"filled\";\ntype TruchetFlipOrientation = 0 | 1;\n\ninterface TruchetFlipProps {\n tiles?: number;\n weight?: number;\n passes?: number;\n waveMode?: TruchetFlipWaveMode;\n resolve?: TruchetFlipResolve;\n variant?: TruchetFlipVariant;\n color?: string;\n secondaryColor?: string;\n seed?: number;\n speed?: number;\n loop?: boolean;\n className?: string;\n}\n\ntype Paint = \"color\" | \"secondaryColor\" | \"className\";\ntype Unset = \"secondaryColor\" | \"className\";\n\ninterface TruchetFlipOptions extends Omit<TruchetFlipProps, Paint> {\n width?: number;\n height?: number;\n fps?: number;\n}\n\ninterface TruchetFlipTile {\n col: number;\n row: number;\n x: number;\n y: number;\n alternate: boolean;\n initial: TruchetFlipOrientation;\n target: TruchetFlipOrientation;\n delay: number;\n}\n\nconst truchetFlipDefaults: Required<Omit<TruchetFlipProps, Unset>> = {\n tiles: 10,\n weight: 0.2,\n passes: 2,\n waveMode: \"radial\",\n resolve: \"rings\",\n variant: \"stroke\",\n color: \"#ffffff\",\n seed: 1,\n speed: 1,\n loop: false,\n};\n\nconst LEAD = 6;\nconst SPREAD = 30;\nconst SNAP = 12;\nconst SNAP_SETTLE = 8;\nconst SNAP_RISE = 4;\nconst SNAP_DAMPING = 0.65;\nconst GAP = 24;\nconst RESOLVE_GAP = 30;\nconst HOLD = 18;\nconst LOOP_HOLD = 24;\nconst MAX_PASSES = 4;\nconst MIN_TILES = 4;\nconst MAX_TILES = 24;\nconst MIN_WEIGHT = 0.04;\nconst MAX_WEIGHT = 0.34;\nconst SILHOUETTE = 0.38;\nconst OVERLAP = 0.75;\nconst SNAP_FREQUENCY = (Math.PI - Math.acos(SNAP_DAMPING)) / SNAP_RISE;\nconst SNAP_RATIO = SNAP_DAMPING / Math.sqrt(1 - SNAP_DAMPING ** 2);\n\nconst finite = (value: number | undefined, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst round = (value: number) => Math.round(value * 1000) / 1000;\nconst isOdd = (value: number) => Math.abs(value % 2) === 1;\nconst turn = (wave: number) => (wave % 2 === 0 ? 1 : -1);\nconst rateOf = (speed: number | undefined) =>\n Math.max(0, finite(speed, truchetFlipDefaults.speed));\nconst waveOf = (value: string | undefined): TruchetFlipWaveMode =>\n value === \"diagonal\" || value === \"random\" ? value : \"radial\";\nconst resolveOf = (value: string | undefined): TruchetFlipResolve =>\n value === \"field\" || value === \"silhouette\" ? value : \"rings\";\nconst variantOf = (value: string | undefined): TruchetFlipVariant =>\n value === \"filled\" ? value : \"stroke\";\n\nfunction smoothstep(value: number) {\n const t = clamp(value, 0, 1);\n return t * t * (3 - 2 * t);\n}\n\nfunction mazeKey(seed: number, col: number, row: number) {\n return random(`truchet-flip-${seed}-${col}-${row}`);\n}\n\nfunction waveKey(seed: number, col: number, row: number) {\n return random(`truchet-flip-${seed}-wave-${col}-${row}`);\n}\n\nfunction getTruchetFlipSnap(frames: number) {\n if (Number.isNaN(frames) || frames <= 0) return 0;\n if (frames >= SNAP) return 1;\n const phase = SNAP_FREQUENCY * frames;\n const decay = Math.exp(-SNAP_RATIO * phase);\n const ring = decay * (Math.cos(phase) + SNAP_RATIO * Math.sin(phase));\n const settle = smoothstep((frames - SNAP_SETTLE) / (SNAP - SNAP_SETTLE));\n return 1 - ring * (1 - settle);\n}\n\nfunction getTruchetFlipTimeline(options: TruchetFlipOptions = {}) {\n const requested = finite(options.passes, truchetFlipDefaults.passes);\n const passes = Math.round(clamp(requested, 0, MAX_PASSES));\n const starts = Array.from({ length: passes }, (_, i) => LEAD + i * GAP);\n const lastPass = LEAD + Math.max(0, passes - 1) * GAP;\n const resolveStart = passes === 0 ? LEAD : lastPass + RESOLVE_GAP;\n const settled = resolveStart + SPREAD + SNAP;\n const returnStart = settled + LOOP_HOLD;\n const loop = options.loop === true;\n const duration = loop ? returnStart + SPREAD + SNAP : settled + HOLD;\n return {\n passes,\n starts,\n resolveStart,\n settled,\n returnStart,\n loop,\n duration,\n };\n}\n\ntype TruchetFlipTimeline = ReturnType<typeof getTruchetFlipTimeline>;\n\nconst truchetFlipLength = getTruchetFlipTimeline().settled;\n\nfunction getTruchetFlipDuration(options: TruchetFlipOptions = {}) {\n const rate = rateOf(options.speed);\n const { duration } = getTruchetFlipTimeline(options);\n return rate === 0 ? 1 : Math.max(1, Math.ceil(duration / rate));\n}\n\nfunction getTruchetFlipTime(\n frame: number,\n options: TruchetFlipOptions = {},\n) {\n const scale = 30 / Math.max(1, finite(options.fps, 30));\n const time = Math.max(0, finite(frame, 0)) * scale * rateOf(options.speed);\n const { duration, loop } = getTruchetFlipTimeline(options);\n return loop ? time % duration : time;\n}\n\nfunction getTruchetFlipTarget(\n resolve: TruchetFlipResolve,\n col: number,\n row: number,\n tiles = truchetFlipDefaults.tiles,\n): TruchetFlipOrientation {\n if (resolve === \"field\") return 0;\n if (resolve === \"silhouette\") {\n const inside = Math.hypot(col + 0.5, row + 0.5) < tiles * SILHOUETTE;\n return inside && isOdd(col + row) ? 1 : 0;\n }\n const left = col < 0;\n const above = row < 0;\n return left === above ? 0 : 1;\n}\n\nfunction getTruchetFlipGrid(options: TruchetFlipOptions = {}) {\n const width = Math.max(1, finite(options.width, 1280));\n const height = Math.max(1, finite(options.height, 720));\n const requested = finite(options.tiles, truchetFlipDefaults.tiles);\n const count = Math.round(clamp(requested, MIN_TILES, MAX_TILES));\n const size = Math.min(width, height) / count;\n const halfCols = Math.ceil(width / 2 / size - 1e-6);\n const halfRows = Math.ceil(height / 2 / size - 1e-6);\n const seed = finite(options.seed, truchetFlipDefaults.seed);\n const mode = waveOf(options.waveMode);\n const resolve = resolveOf(options.resolve);\n const cells: { col: number; row: number }[] = [];\n for (let row = -halfRows; row < halfRows; row++) {\n for (let col = -halfCols; col < halfCols; col++) cells.push({ col, row });\n }\n const ranks: number[] = [];\n if (mode === \"random\") {\n const keys = cells.map(({ col, row }) => waveKey(seed, col, row));\n const order = keys.map((_, index) => index);\n order.sort((a, b) => keys[a] - keys[b]);\n for (const [position, index] of order.entries()) ranks[index] = position;\n }\n const shift = halfCols + halfRows;\n const diagonals = 2 * (shift - 1);\n const nearest = Math.hypot(0.5, 0.5);\n const farthest = Math.hypot(halfCols - 0.5, halfRows - 0.5);\n const delayOf = (col: number, row: number, index: number) => {\n if (mode === \"random\") {\n return (SPREAD * ranks[index]) / (cells.length - 1);\n }\n if (mode === \"diagonal\") {\n return (SPREAD * (col + row + shift)) / diagonals;\n }\n const distance = Math.hypot(col + 0.5, row + 0.5) - nearest;\n return (SPREAD * distance) / Math.max(1e-6, farthest - nearest);\n };\n const tiles: TruchetFlipTile[] = cells.map(({ col, row }, index) => ({\n col,\n row,\n x: round(width / 2 + (col + 0.5) * size),\n y: round(height / 2 + (row + 0.5) * size),\n alternate: isOdd(col + row),\n initial: mazeKey(seed, col, row) < 0.5 ? 0 : 1,\n target: getTruchetFlipTarget(resolve, col, row, count),\n delay: round(clamp(delayOf(col, row, index), 0, SPREAD)),\n }));\n return {\n width,\n height,\n count,\n size,\n unit: Math.min(width, height) / 720,\n tiles,\n };\n}\n\ntype TruchetFlipGrid = ReturnType<typeof getTruchetFlipGrid>;\n\nfunction getTruchetFlipAngle(\n tile: TruchetFlipTile,\n time: number,\n timeline: TruchetFlipTimeline,\n) {\n let turns = 0;\n for (const [wave, start] of timeline.starts.entries()) {\n turns += turn(wave) * getTruchetFlipSnap(time - start - tile.delay);\n }\n const reached = (tile.initial + timeline.passes) % 2;\n if (reached !== tile.target) {\n const since = time - timeline.resolveStart - tile.delay;\n turns += turn(timeline.passes) * getTruchetFlipSnap(since);\n }\n if (timeline.loop && tile.target !== tile.initial) {\n const since = time - timeline.returnStart - tile.delay;\n turns += turn(timeline.passes + 1) * getTruchetFlipSnap(since);\n }\n return (tile.initial + turns) * 90;\n}\n\nfunction getTruchetFlipTilePath(\n size: number,\n variant: TruchetFlipVariant = \"stroke\",\n overlap = OVERLAP,\n) {\n const half = Math.max(0, finite(size, 0)) / 2;\n const pad = clamp(finite(overlap, OVERLAP), 0, half / 4);\n const radius = `${round(half)} ${round(half)}`;\n const point = (x: number, y: number) => `${round(x)} ${round(y)}`;\n if (variant === \"filled\") {\n const reach = Math.sqrt(half * half - pad * pad);\n const sector = (cx: number, cy: number, side: number) => {\n const corner = point(cx - side * pad, cy - side * pad);\n const start = point(cx + side * reach, cy - side * pad);\n const end = point(cx - side * pad, cy + side * reach);\n return `M ${corner} L ${start} A ${radius} 0 0 1 ${end} Z`;\n };\n return `${sector(-half, -half, 1)} ${sector(half, half, -1)}`;\n }\n const bend = half > 0 ? pad / half : 0;\n const cos = half * Math.cos(bend);\n const sin = half * Math.sin(bend);\n const arc = (cx: number, cy: number, side: number) => {\n const start = point(cx + side * cos, cy - side * sin);\n const end = point(cx - side * sin, cy + side * cos);\n return `M ${start} A ${radius} 0 0 1 ${end}`;\n };\n return `${arc(-half, -half, 1)} ${arc(half, half, -1)}`;\n}\n\nfunction getTruchetFlipState(\n frame: number,\n options: TruchetFlipOptions = {},\n grid: TruchetFlipGrid = getTruchetFlipGrid(options),\n) {\n const timeline = getTruchetFlipTimeline(options);\n const time = getTruchetFlipTime(frame, options);\n const variant = variantOf(options.variant);\n const requested = finite(options.weight, truchetFlipDefaults.weight);\n const weight = clamp(requested, MIN_WEIGHT, MAX_WEIGHT);\n return {\n ...grid,\n time,\n timeline,\n variant,\n strokeWidth: round(grid.size * weight),\n path: getTruchetFlipTilePath(grid.size, variant, OVERLAP * grid.unit),\n tiles: grid.tiles.map((tile) => {\n const angle = getTruchetFlipAngle(tile, time, timeline);\n const rotation = round(angle);\n const transform = `translate(${tile.x} ${tile.y}) rotate(${rotation})`;\n return { ...tile, angle, transform };\n }),\n };\n}\n\nfunction TruchetFlipBase({\n tiles = truchetFlipDefaults.tiles,\n weight = truchetFlipDefaults.weight,\n passes = truchetFlipDefaults.passes,\n waveMode = truchetFlipDefaults.waveMode,\n resolve = truchetFlipDefaults.resolve,\n variant = truchetFlipDefaults.variant,\n color = truchetFlipDefaults.color,\n secondaryColor,\n seed = truchetFlipDefaults.seed,\n speed = truchetFlipDefaults.speed,\n loop = truchetFlipDefaults.loop,\n className,\n}: TruchetFlipProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const grid = useMemo(() => {\n const layout = { width, height, tiles, seed, waveMode, resolve };\n return getTruchetFlipGrid(layout);\n }, [width, height, tiles, seed, waveMode, resolve]);\n const motion = { fps, weight, passes, variant, speed, loop };\n const state = getTruchetFlipState(frame, motion, grid);\n const filled = state.variant === \"filled\";\n const primary = state.tiles.filter((tile) => !tile.alternate);\n const alternate = state.tiles.filter((tile) => tile.alternate);\n const layers = [\n { key: \"primary\", paint: color, tiles: primary },\n { key: \"alternate\", paint: secondaryColor ?? color, tiles: alternate },\n ];\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n role=\"img\"\n aria-label=\"Truchet tile pattern\"\n style={{ display: \"block\" }}\n >\n {layers.map((layer) => (\n <g\n key={layer.key}\n fill={filled ? layer.paint : \"none\"}\n stroke={filled ? \"none\" : layer.paint}\n strokeWidth={filled ? undefined : state.strokeWidth}\n >\n {layer.tiles.map((tile) => (\n <path\n key={`${tile.col}:${tile.row}`}\n d={state.path}\n transform={tile.transform}\n />\n ))}\n </g>\n ))}\n </svg>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n tiles: {\n type: \"number\",\n default: 10,\n min: 4,\n max: 24,\n step: 1,\n description: \"Tiles across\",\n hiddenFromList: false,\n },\n weight: {\n type: \"number\",\n default: 0.2,\n min: 0.04,\n max: 0.34,\n step: 0.01,\n description: \"Stroke weight\",\n hiddenFromList: false,\n },\n passes: {\n type: \"number\",\n default: 2,\n min: 0,\n max: 4,\n step: 1,\n description: \"Passes\",\n hiddenFromList: false,\n },\n waveMode: {\n type: \"enum\",\n default: \"radial\",\n variants: {\n radial: {},\n diagonal: {},\n random: {},\n },\n description: \"Wave\",\n },\n resolve: {\n type: \"enum\",\n default: \"rings\",\n variants: {\n rings: {},\n field: {},\n silhouette: {},\n },\n description: \"Resolve to\",\n },\n variant: {\n type: \"enum\",\n default: \"stroke\",\n variants: {\n stroke: {},\n filled: {},\n },\n description: \"Variant\",\n },\n color: {\n type: \"color\",\n default: \"#ffffff\",\n description: \"Line color\",\n },\n secondaryColor: {\n type: \"color\",\n default: \"#ffffff\",\n description: \"Alternate tiles\",\n },\n seed: {\n type: \"number\",\n default: 1,\n min: 1,\n step: 1,\n description: \"Seed\",\n hiddenFromList: false,\n },\n loop: {\n type: \"boolean\",\n default: false,\n description: \"Loop\",\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"tiles\",\"weight\",\"passes\",\"waveMode\",\"resolve\",\"variant\",\"color\",\"secondaryColor\",\"seed\",\"loop\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n tiles: 10,\n weight: 0.2,\n passes: 2,\n waveMode: \"radial\",\n resolve: \"rings\",\n variant: \"stroke\",\n color: \"#ffffff\",\n secondaryColor: \"#ffffff\",\n seed: 1,\n loop: false,\n speed: 1,\n};\n\ntype TruchetFlipElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof TruchetFlipBase>;\n\nconst TruchetFlipInner = forwardRef<\n HTMLDivElement,\n TruchetFlipElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<TruchetFlip>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <TruchetFlipBase\n {...(componentProps as unknown as ComponentProps<typeof TruchetFlipBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const TruchetFlip = Interactive.withSchema({\n Component: TruchetFlipInner,\n componentName: \"<TruchetFlip>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 102+}diff --git a/registry-artifacts/elements/type-repeater.json b/registry-artifacts/elements/type-repeater.jsonnew file mode 100644index 00000000..9cc7bed7--- /dev/null+++ b/registry-artifacts/elements/type-repeater.json@@ -0,0 +1,19 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [+ {+ "name": "@remotion/google-fonts",+ "version": null+ }+ ],+ "dimensions": null,+ "displayName": "Type Repeater",+ "durationInFrames": 90,+ "installationMode": "component-owned-sequence",+ "slug": "type-repeater",+ "sourceCode": "import { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { forwardRef, useId, useImperativeHandle, useRef, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, interpolate, interpolateColors, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\ntype TypeRepeaterMode = \"fan\" | \"spiral\" | \"tunnel\";\n\ninterface TypeRepeaterProps {\n text?: string;\n copies?: number;\n mode?: TypeRepeaterMode;\n fontSize?: number;\n fontWeight?: number;\n fontFamily?: string;\n color?: string;\n accent?: string;\n outline?: boolean;\n speed?: number;\n className?: string;\n}\n\nconst typeRepeaterDefaults = {\n text: \"Repeat\",\n copies: 12,\n mode: \"tunnel\",\n fontSize: 110,\n fontWeight: 800,\n fontFamily: INTER,\n color: \"#fafafa\",\n accent: \"#D97757\",\n outline: true,\n speed: 1,\n} satisfies Required<Omit<TypeRepeaterProps, \"className\">>;\n\n/** Beats on the 30 fps clock. */\nconst typeRepeaterTiming = {\n intro: [0, 10],\n unfold: [10, 34],\n breathe: [34, 70],\n collapse: [70, 90],\n} as const;\n\n/** Frame where the copies have folded back into the word. */\nconst typeRepeaterLength = typeRepeaterTiming.collapse[1];\n\n/**\n * Per-copy steps for each mode. `fan` alternates sides around a pivot below\n * the word; `spiral` and `tunnel` grow each copy outward behind it.\n */\nconst typeRepeaterModes = {\n fan: { rotate: 11, scale: 1, pivot: 2.6, symmetric: true },\n spiral: { rotate: 12, scale: 1.1, pivot: 0, symmetric: false },\n tunnel: { rotate: 0, scale: 1.2, pivot: 0, symmetric: false },\n} as const satisfies Record<\n TypeRepeaterMode,\n { rotate: number; scale: number; pivot: number; symmetric: boolean }\n>;\n\nconst BREATHE = 0.06;\nconst FADE = 0.85;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutCubic = Easing.out(Easing.cubic);\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\nconst unfoldEase = Easing.out(Easing.back(1.4));\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nfunction getTypeRepeaterTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\n/** How far the copies have spread, 0 (one word) to about 1. */\nfunction getTypeRepeaterSpread(t: number) {\n const { unfold, breathe, collapse } = typeRepeaterTiming;\n if (t < breathe[0]) {\n return interpolate(t, [...unfold], [0, 1], {\n ...CLAMP,\n easing: unfoldEase,\n });\n }\n if (t < breathe[1]) {\n const phase = (t - breathe[0]) / (breathe[1] - breathe[0]);\n return 1 + BREATHE * Math.sin(2 * Math.PI * phase);\n }\n return interpolate(t, [...collapse], [1, 0], {\n ...CLAMP,\n easing: easeInOutCubic,\n });\n}\n\n/** Entrance of the front word, 0..1. */\nfunction getTypeRepeaterIntro(t: number) {\n return interpolate(t, [...typeRepeaterTiming.intro], [0, 1], {\n ...CLAMP,\n easing: easeOutCubic,\n });\n}\n\ninterface TypeRepeaterCopy {\n rotate: number;\n scale: number;\n opacity: number;\n /** 0 for the word's color, 1 for the accent. */\n tint: number;\n}\n\n/** Transform and fade of copy `index` (0 is the word itself). */\nfunction getTypeRepeaterCopy(\n index: number,\n copies: number,\n spread: number,\n mode: TypeRepeaterMode,\n): TypeRepeaterCopy {\n const step = typeRepeaterModes[mode] ?? typeRepeaterModes.spiral;\n const n = Math.max(1, Math.round(copies));\n const steps = step.symmetric ? Math.ceil(index / 2) : index;\n const side = step.symmetric && index % 2 === 0 ? -1 : 1;\n const reach = steps * spread;\n return {\n rotate: side * step.rotate * reach || 0,\n scale: step.scale ** reach,\n opacity:\n index === 0\n ? 1\n : (1 - (FADE * index) / n) * Math.min(1, Math.max(0, spread * 4)),\n tint: n > 1 ? index / (n - 1) : 0,\n };\n}\n\nfunction TypeRepeaterBase({\n text = typeRepeaterDefaults.text,\n copies = typeRepeaterDefaults.copies,\n mode = typeRepeaterDefaults.mode,\n fontSize = typeRepeaterDefaults.fontSize,\n fontWeight = typeRepeaterDefaults.fontWeight,\n fontFamily = typeRepeaterDefaults.fontFamily,\n color = typeRepeaterDefaults.color,\n accent = typeRepeaterDefaults.accent,\n outline = typeRepeaterDefaults.outline,\n speed = typeRepeaterDefaults.speed,\n className,\n}: TypeRepeaterProps) {\n const frame = useCurrentFrame();\n const { fps, height } = useVideoConfig();\n const outlineId = `type-repeater-${useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`;\n const unit = height / 720;\n const size = fontSize * unit;\n const t = getTypeRepeaterTime(frame, { fps, speed });\n const spread = getTypeRepeaterSpread(t);\n const intro = getTypeRepeaterIntro(t);\n const count = Math.max(1, Math.round(finite(copies, 12)));\n const pivot = (typeRepeaterModes[mode] ?? typeRepeaterModes.spiral).pivot;\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n }}\n >\n {outline ? (\n // Outline from the filled silhouette: the variable font's overlapping\n // contours would show through a text stroke.\n <svg width={0} height={0} style={{ position: \"absolute\" }} aria-hidden>\n <defs>\n <filter id={outlineId}>\n <feMorphology\n in=\"SourceAlpha\"\n operator=\"erode\"\n radius={1.5 * unit}\n result=\"inner\"\n />\n <feComposite in=\"SourceGraphic\" in2=\"inner\" operator=\"out\" />\n </filter>\n </defs>\n </svg>\n ) : null}\n <div\n style={{\n position: \"relative\",\n opacity: intro,\n transform: `scale(${0.9 + 0.1 * intro})`,\n }}\n >\n {Array.from({ length: count }, (_, i) => count - 1 - i).map((i) => {\n const copy = getTypeRepeaterCopy(i, count, spread, mode);\n if (copy.opacity <= 0) return null;\n return (\n <div\n key={i}\n aria-hidden={i > 0}\n style={{\n position: i === 0 ? \"relative\" : \"absolute\",\n inset: i === 0 ? undefined : 0,\n fontFamily,\n fontSize: size,\n lineHeight: 1,\n fontWeight,\n fontVariationSettings: `\"wght\" ${fontWeight}`,\n whiteSpace: \"pre\",\n color: interpolateColors(copy.tint, [0, 1], [color, accent]),\n opacity: copy.opacity,\n filter: outline && i > 0 ? `url(#${outlineId})` : undefined,\n transformOrigin: `50% calc(50% + ${pivot}em)`,\n transform: `rotate(${copy.rotate}deg) scale(${copy.scale})`,\n }}\n >\n {text}\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n text: {\n type: \"text-content\",\n default: \"Repeat\",\n description: \"Text\",\n },\n mode: {\n type: \"enum\",\n default: \"tunnel\",\n variants: {\n tunnel: {},\n spiral: {},\n fan: {},\n },\n description: \"Mode\",\n },\n color: {\n type: \"color\",\n default: \"#111111\",\n description: \"Word color\",\n },\n accent: {\n type: \"color\",\n default: \"#fafafa\",\n description: \"Last copy\",\n },\n copies: {\n type: \"number\",\n default: 12,\n min: 2,\n max: 24,\n step: 1,\n description: \"Copies\",\n hiddenFromList: false,\n },\n fontSize: {\n type: \"number\",\n default: 110,\n min: 40,\n max: 240,\n step: 2,\n description: \"Font size\",\n hiddenFromList: false,\n },\n fontWeight: {\n type: \"number\",\n default: 800,\n min: 100,\n max: 900,\n step: 50,\n description: \"Weight\",\n hiddenFromList: false,\n },\n outline: {\n type: \"boolean\",\n default: true,\n description: \"Outline copies\",\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"text\",\"mode\",\"color\",\"accent\",\"copies\",\"fontSize\",\"fontWeight\",\"outline\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n text: \"Repeat\",\n mode: \"tunnel\",\n color: \"#111111\",\n accent: \"#fafafa\",\n copies: 12,\n fontSize: 110,\n fontWeight: 800,\n outline: true,\n speed: 1,\n};\n\ntype TypeRepeaterElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof TypeRepeaterBase>;\n\nconst TypeRepeaterInner = forwardRef<\n HTMLDivElement,\n TypeRepeaterElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<TypeRepeater>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <TypeRepeaterBase\n {...(componentProps as unknown as ComponentProps<typeof TypeRepeaterBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const TypeRepeater = Interactive.withSchema({\n Component: TypeRepeaterInner,\n componentName: \"<TypeRepeater>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 90+}diff --git a/registry-artifacts/elements/type-wall.json b/registry-artifacts/elements/type-wall.jsonnew file mode 100644index 00000000..48ccc493--- /dev/null+++ b/registry-artifacts/elements/type-wall.json@@ -0,0 +1,19 @@+{+ "type": "remotion-element",+ "version": 1,+ "element": {+ "dependencies": [+ {+ "name": "@remotion/google-fonts",+ "version": null+ }+ ],+ "dimensions": null,+ "displayName": "Type Wall",+ "durationInFrames": 150,+ "installationMode": "component-owned-sequence",+ "slug": "type-wall",+ "sourceCode": "import { loadFont as loadAnton } from \"@remotion/google-fonts/Anton\";\nimport { loadFont as loadInter } from \"@remotion/google-fonts/Inter\";\nimport { forwardRef, useId, useImperativeHandle, useRef, type ComponentProps } from \"react\";\nimport { Easing, Interactive, Sequence, interpolate, random, useCurrentFrame, useVideoConfig, type InteractiveBaseProps, type InteractiveTransformProps, type InteractivitySchema, type SequenceControls } from \"remotion\";\n\nconst { fontFamily: INTER } = loadInter(\"normal\", {\n weights: [\"900\"],\n subsets: [\"latin\"],\n});\nconst { fontFamily: ANTON } = loadAnton(\"normal\", {\n weights: [\"400\"],\n subsets: [\"latin\"],\n});\n\ntype TypeWallStyle = \"solid\" | \"narrow\" | \"outline\";\n\ninterface TypeWallProps {\n text?: string;\n separator?: string;\n fontSize?: number;\n color?: string;\n accent?: string;\n accentText?: string;\n seed?: number;\n speed?: number;\n className?: string;\n}\n\nconst typeWallDefaults = {\n text: \"MOTION\",\n separator: \"·\",\n fontSize: 64,\n color: \"#fafafa\",\n accent: \"#D97757\",\n accentText: \"#0a0a0a\",\n seed: 7,\n speed: 1,\n} satisfies Required<Omit<TypeWallProps, \"className\">>;\n\n/** Row faces away from the center, the accent row always solid. */\nconst typeWallStyles: readonly TypeWallStyle[] = [\n \"solid\",\n \"narrow\",\n \"outline\",\n];\n\n/** Anton sized so its capitals match Inter's cap height (0.7275 / 0.8594 em). */\nconst NARROW_SCALE = 0.7275 / 0.8594;\n/** Tokens per second at speed 1, before each row's seeded factor. */\nconst TOKENS_PER_SECOND = 0.22;\nconst ENTRANCE = 20;\nconst STAGGER = 2;\n/** Tokens a row streams past on its way in, on top of its cruise. */\nconst ENTRANCE_BURST = 2.5;\nconst BAND = [6, 20] as const;\n/** Lower bound on a token's width per character, in em, for the repeat count. */\nconst MIN_CHAR_WIDTH = 0.4;\nconst MAX_TOKENS = 48;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutCubic = Easing.out(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\nfunction fract(x: number) {\n return x - Math.floor(x);\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nfunction getTypeWallTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\n/** Row indices from the top of the frame to the bottom; row 0 is centered. */\nfunction getTypeWallRows(height: number, rowHeight: number) {\n const reach = Math.ceil((height / 2 - rowHeight / 2) / rowHeight) + 1;\n const rows: number[] = [];\n for (let k = -reach; k <= reach; k++) rows.push(k);\n return rows;\n}\n\nfunction getTypeWallStyle(row: number): TypeWallStyle {\n if (row === 0) return \"solid\";\n const n = typeWallStyles.length;\n return typeWallStyles[((row % n) + n) % n];\n}\n\n/** −1 runs left, 1 runs right. The accent row runs left. */\nfunction getTypeWallDirection(row: number) {\n return Math.abs(row) % 2 === 0 ? -1 : 1;\n}\n\n/** Cruise speed in tokens per frame and the row's starting phase. */\nfunction getTypeWallMotion(row: number, seed: number) {\n const factor = 0.7 + 0.6 * random(`type-wall-${seed}-speed-${row}`);\n return {\n velocity: (TOKENS_PER_SECOND * factor) / 30,\n phase: random(`type-wall-${seed}-phase-${row}`),\n };\n}\n\ninterface TypeWallRowState {\n direction: number;\n /** Translation of the token strip in tokens, always in [−1, 0). */\n shift: number;\n /** Share of the row revealed from its entering side, 0..1. */\n reveal: number;\n}\n\nfunction getTypeWallRow(\n t: number,\n row: number,\n seed = typeWallDefaults.seed,\n): TypeWallRowState {\n const direction = getTypeWallDirection(row);\n const { velocity, phase } = getTypeWallMotion(row, seed);\n const e = easeOutCubic(\n Math.min(1, Math.max(0, (t - STAGGER * Math.abs(row)) / ENTRANCE)),\n );\n const travel = phase + velocity * t + ENTRANCE_BURST * e;\n // Leftward rows slide the strip left; rightward rows run it from −1 up to 0.\n const shift = direction < 0 ? -fract(travel) : fract(travel) - 1;\n return { direction, shift: shift || 0, reveal: e };\n}\n\n/** The accent band growing from the center, 0..1. */\nfunction getTypeWallBand(t: number) {\n return interpolate(t, [...BAND], [0, 1], { ...CLAMP, easing: easeOutCubic });\n}\n\n/** Frame where the slowest (outermost) row has finished entering. */\nfunction getTypeWallEntranceEnd(height: number, rowHeight: number) {\n const rows = getTypeWallRows(height, rowHeight);\n return ENTRANCE + STAGGER * Math.max(...rows.map(Math.abs));\n}\n\n/** How many tokens a strip needs to cover the width twice over. */\nfunction getTypeWallTokenCount(\n width: number,\n fontSize: number,\n token: string,\n) {\n const tokenWidth =\n Math.max(1, Array.from(token).length) * MIN_CHAR_WIDTH * fontSize;\n return Math.min(MAX_TOKENS, Math.ceil(width / tokenWidth) + 2);\n}\n\nfunction TypeWallBase({\n text = typeWallDefaults.text,\n separator = typeWallDefaults.separator,\n fontSize = typeWallDefaults.fontSize,\n color = typeWallDefaults.color,\n accent = typeWallDefaults.accent,\n accentText = typeWallDefaults.accentText,\n seed = typeWallDefaults.seed,\n speed = typeWallDefaults.speed,\n className,\n}: TypeWallProps) {\n const frame = useCurrentFrame();\n const { fps, width, height } = useVideoConfig();\n const unit = height / 720;\n const rowHeight = Math.max(8, fontSize * unit);\n const t = getTypeWallTime(frame, { fps, speed });\n const rows = getTypeWallRows(height, rowHeight);\n const token = `${text} ${separator} `;\n const band = getTypeWallBand(t);\n const outlineId = `type-wall-${useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`;\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n {/* Outline from the filled silhouette: the variable font's overlapping\n contours would show through a text stroke. */}\n <svg width={0} height={0} style={{ position: \"absolute\" }} aria-hidden>\n <defs>\n <filter id={outlineId}>\n <feMorphology\n in=\"SourceAlpha\"\n operator=\"erode\"\n radius={1.5 * unit}\n result=\"inner\"\n />\n <feComposite\n in=\"SourceAlpha\"\n in2=\"inner\"\n operator=\"out\"\n result=\"ring\"\n />\n <feFlood floodColor={color} />\n <feComposite in2=\"ring\" operator=\"in\" />\n </filter>\n </defs>\n </svg>\n {rows.map((row) => {\n const style = getTypeWallStyle(row);\n const state = getTypeWallRow(t, row, seed);\n const narrow = style === \"narrow\";\n const size = narrow ? rowHeight * NARROW_SCALE : rowHeight;\n const count = getTypeWallTokenCount(width, size, token);\n const onBand = row === 0;\n const hidden = `${(1 - state.reveal) * 100}%`;\n return (\n <div\n key={row}\n style={{\n position: \"absolute\",\n left: 0,\n right: 0,\n top: height / 2 + (row - 0.5) * rowHeight,\n height: rowHeight,\n clipPath:\n state.direction < 0\n ? `inset(0 0 0 ${hidden})`\n : `inset(0 ${hidden} 0 0)`,\n }}\n >\n {onBand ? (\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n background: accent,\n transform: `scaleX(${band})`,\n }}\n />\n ) : null}\n <div\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n width: \"max-content\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n whiteSpace: \"pre\",\n fontFamily: narrow ? ANTON : INTER,\n fontSize: size,\n lineHeight: 1,\n fontWeight: narrow ? 400 : 900,\n color: onBand ? accentText : color,\n filter: style === \"outline\" ? `url(#${outlineId})` : undefined,\n transform: `translateX(${(state.shift * 100) / count}%)`,\n }}\n >\n {Array.from({ length: count }, (_, i) => (\n <span key={i}>{token}</span>\n ))}\n </div>\n </div>\n );\n })}\n </div>\n );\n}\n\nconst elementSchema = {\n ...Interactive.baseSchema,\n text: {\n type: \"text-content\",\n default: \"MOTION\",\n description: \"Text\",\n },\n separator: {\n type: \"text-content\",\n default: \"·\",\n description: \"Separator\",\n },\n color: {\n type: \"color\",\n default: \"#fafafa\",\n description: \"Text color\",\n },\n accent: {\n type: \"color\",\n default: \"#ff4d1a\",\n description: \"Band color\",\n },\n accentText: {\n type: \"color\",\n default: \"#111111\",\n description: \"Band text\",\n },\n fontSize: {\n type: \"number\",\n default: 64,\n min: 24,\n max: 180,\n step: 2,\n description: \"Row height\",\n hiddenFromList: false,\n },\n seed: {\n type: \"number\",\n default: 7,\n min: 0,\n max: 99,\n step: 1,\n description: \"Seed\",\n hiddenFromList: false,\n },\n speed: {\n type: \"number\",\n default: 1,\n min: 0.25,\n max: 4,\n step: 0.25,\n description: \"Speed\",\n hiddenFromList: false,\n },\n ...Interactive.transformSchema,\n} as const satisfies InteractivitySchema;\n\nconst ELEMENT_PROP_KEYS = new Set([\"text\",\"separator\",\"color\",\"accent\",\"accentText\",\"fontSize\",\"seed\",\"speed\"]);\n\nconst ELEMENT_PROP_DEFAULTS: Record<string, unknown> = {\n text: \"MOTION\",\n separator: \"·\",\n color: \"#fafafa\",\n accent: \"#ff4d1a\",\n accentText: \"#111111\",\n fontSize: 64,\n seed: 7,\n speed: 1,\n};\n\ntype TypeWallElementProps = InteractiveBaseProps &\n InteractiveTransformProps &\n ComponentProps<typeof TypeWallBase>;\n\nconst TypeWallInner = forwardRef<\n HTMLDivElement,\n TypeWallElementProps & { readonly controls: SequenceControls | undefined }\n>(({ controls, name, style, ...rest }, ref) => {\n const outlineRef = useRef<HTMLDivElement>(null);\n useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);\n const componentProps: Record<string, unknown> = { ...ELEMENT_PROP_DEFAULTS };\n const sequenceProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (ELEMENT_PROP_KEYS.has(key)) {\n if (value !== undefined) componentProps[key] = value;\n } else {\n sequenceProps[key] = value;\n }\n }\n return (\n <Sequence\n layout=\"none\"\n {...sequenceProps}\n controls={controls}\n name={name ?? \"<TypeWall>\"}\n outlineRef={outlineRef}\n >\n <div\n ref={outlineRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n <TypeWallBase\n {...(componentProps as unknown as ComponentProps<typeof TypeWallBase>)}\n />\n </div>\n </Sequence>\n );\n});\n\nexport const TypeWall = Interactive.withSchema({\n Component: TypeWallInner,\n componentName: \"<TypeWall>\",\n componentIdentity: null,\n schema: elementSchema,\n supportsEffects: false,\n});\n"+ },+ "durationInFrames": 150+}diff --git a/registry-artifacts/glyph-anatomy.json b/registry-artifacts/glyph-anatomy.jsonnew file mode 100644index 00000000..8b8c3858--- /dev/null+++ b/registry-artifacts/glyph-anatomy.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "glyph-anatomy",+ "title": "Glyph Anatomy",+ "description": "A word builds as in a font editor, with metric guides, anchors along each contour and Bézier handles that pull straight segments into curves before the glyphs fill.",+ "dependencies": ["remotion", "opentype.js", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/glyph-anatomy/index.tsx",+ "content": "\"use client\";\n\nimport { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { type Font, parse } from \"opentype.js\";\nimport { useEffect, useState } from \"react\";\nimport {\n continueRender,\n delayRender,\n Easing,\n interpolate,\n useCurrentFrame,\n useVideoConfig,\n} from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"500\"],\n subsets: [\"latin\"],\n});\n\nexport interface GlyphAnatomyProps {\n text?: string;\n fontUrl?: string;\n fontSize?: number;\n color?: string;\n guideColor?: string;\n guides?: boolean;\n keepPoints?: boolean;\n speed?: number;\n className?: string;\n}\n\n/** Static Inter ExtraBold (800) from Google Fonts. */\nexport const interExtraBoldTtf =\n \"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuDyYMZg.ttf\";\n\nexport const glyphAnatomyDefaults = {\n text: \"Glyph\",\n fontUrl: interExtraBoldTtf,\n fontSize: 200,\n color: \"#fafafa\",\n guideColor: \"#0d99ff\",\n guides: true,\n keepPoints: false,\n speed: 1,\n} satisfies Required<Omit<GlyphAnatomyProps, \"className\">>;\n\n/** Beats on the 30 fps clock. Letter beats shift by `letterStagger × i`. */\nexport const glyphAnatomyTiming = {\n guideStart: 0,\n guideStagger: 3,\n guideDraw: 10,\n anchors: [8, 22],\n anchorPop: 4,\n pull: [18, 40],\n pullDuration: 8,\n fill: [40, 50],\n fade: [46, 58],\n letterStagger: 2,\n} as const;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutCubic = Easing.out(Easing.cubic);\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\nconst popEase = Easing.out(Easing.back(1.7));\nconst pullEase = Easing.out(Easing.back(1.6));\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nexport function getGlyphAnatomyTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\nexport interface Point {\n x: number;\n y: number;\n}\n\nexport interface AnatomySegment {\n from: Point;\n to: Point;\n /** Cubic handles; absent on straight segments. */\n c1?: Point;\n c2?: Point;\n}\n\nexport interface PathCommand {\n type: string;\n x?: number;\n y?: number;\n x1?: number;\n y1?: number;\n x2?: number;\n y2?: number;\n}\n\nconst lerp = (a: Point, b: Point, k: number): Point => ({\n x: a.x + (b.x - a.x) * k,\n y: a.y + (b.y - a.y) * k,\n});\n\n/**\n * Turns glyph path commands into contours of explicit segments. Quadratic\n * curves become cubics (handles at ⅔ toward the control point), so every\n * curve shows one handle on each end, as in Figma or Glyphs.\n */\nexport function getAnatomyContours(\n commands: readonly PathCommand[],\n): AnatomySegment[][] {\n const contours: AnatomySegment[][] = [];\n let segments: AnatomySegment[] = [];\n let start: Point | null = null;\n let at: Point | null = null;\n const close = () => {\n if (start && at && (at.x !== start.x || at.y !== start.y)) {\n segments.push({ from: at, to: start });\n }\n if (segments.length > 0) contours.push(segments);\n segments = [];\n start = null;\n at = null;\n };\n for (const c of commands) {\n const to = { x: c.x ?? 0, y: c.y ?? 0 };\n if (c.type === \"M\") {\n close();\n start = to;\n at = to;\n } else if (!at) {\n } else if (c.type === \"L\") {\n segments.push({ from: at, to });\n at = to;\n } else if (c.type === \"Q\") {\n const q = { x: c.x1 ?? 0, y: c.y1 ?? 0 };\n segments.push({\n from: at,\n to,\n c1: lerp(at, q, 2 / 3),\n c2: lerp(to, q, 2 / 3),\n });\n at = to;\n } else if (c.type === \"C\") {\n segments.push({\n from: at,\n to,\n c1: { x: c.x1 ?? 0, y: c.y1 ?? 0 },\n c2: { x: c.x2 ?? 0, y: c.y2 ?? 0 },\n });\n at = to;\n } else if (c.type === \"Z\") {\n close();\n }\n }\n close();\n return contours;\n}\n\n/**\n * How far each handle has travelled from its anchor to its place, 0 → 1 with\n * overshoot. At 0 the curve is its chord.\n */\nexport function getGlyphAnatomyPull(t: number, order: number, total: number) {\n const { pull, pullDuration } = glyphAnatomyTiming;\n const span = pull[1] - pull[0] - pullDuration;\n const start = pull[0] + (total > 1 ? (span * order) / (total - 1) : 0);\n return interpolate(t, [start, start + pullDuration], [0, 1], {\n ...CLAMP,\n easing: pullEase,\n });\n}\n\n/** Scale of anchor `order` of `total` popping in along the letter's path. */\nexport function getGlyphAnatomyAnchor(t: number, order: number, total: number) {\n const { anchors, anchorPop } = glyphAnatomyTiming;\n const span = anchors[1] - anchors[0] - anchorPop;\n const start = anchors[0] + (total > 1 ? (span * order) / (total - 1) : 0);\n return Math.max(\n 0,\n interpolate(t, [start, start + anchorPop], [0, 1], {\n ...CLAMP,\n easing: popEase,\n }),\n );\n}\n\n/** Letter-level fades: outline in, fill in, scaffolding out. */\nexport function getGlyphAnatomyLetter(t: number) {\n const { anchors, fill, fade } = glyphAnatomyTiming;\n return {\n outline: interpolate(t, [anchors[0], anchors[0] + 4], [0, 1], CLAMP),\n fill: interpolate(t, [...fill], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n scaffold: interpolate(t, [...fade], [1, 0], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n };\n}\n\n/** Draw progress of guide `index`, 0..1. */\nexport function getGlyphAnatomyGuide(t: number, index: number) {\n const { guideStart, guideStagger, guideDraw } = glyphAnatomyTiming;\n const start = guideStart + guideStagger * index;\n return interpolate(t, [start, start + guideDraw], [0, 1], {\n ...CLAMP,\n easing: easeOutCubic,\n });\n}\n\n/** Frame where the scaffolding of the last of `count` letters has faded. */\nexport function getGlyphAnatomyLength(count: number) {\n const { fade, letterStagger } = glyphAnatomyTiming;\n return fade[1] + letterStagger * Math.max(0, count - 1);\n}\n\n/** Path data for a contour with each handle pulled `k(segment)` of the way. */\nexport function getAnatomyPath(\n segments: readonly AnatomySegment[],\n pullOf: (index: number) => number,\n) {\n if (segments.length === 0) return \"\";\n const f = (p: Point) => `${p.x.toFixed(2)} ${p.y.toFixed(2)}`;\n let d = `M${f(segments[0].from)}`;\n segments.forEach((s, i) => {\n if (s.c1 && s.c2) {\n const k = pullOf(i);\n d += `C${f(lerp(s.from, s.c1, k))} ${f(lerp(s.to, s.c2, k))} ${f(s.to)}`;\n } else {\n d += `L${f(s.to)}`;\n }\n });\n return `${d}Z`;\n}\n\ninterface AnatomyLetter {\n contours: AnatomySegment[][];\n}\n\nfunction layout(font: Font, text: string, fontSize: number) {\n const scale = fontSize / font.unitsPerEm;\n // Per-character lookup: full shaping runs GSUB lookups that opentype.js\n // does not support in every font.\n const glyphs = Array.from(text).map((char) => font.charToGlyph(char));\n let x = 0;\n const letters: AnatomyLetter[] = glyphs.map((glyph, i) => {\n if (i > 0) x += font.getKerningValue(glyphs[i - 1], glyph) * scale;\n const contours = getAnatomyContours(glyph.getPath(x, 0, fontSize).commands);\n x += (glyph.advanceWidth ?? 0) * scale;\n return { contours };\n });\n const os2 = font.tables.os2 as\n | { sCapHeight?: number; sxHeight?: number }\n | undefined;\n const em = (v: number | undefined, fallback: number) =>\n ((v ?? fallback * font.unitsPerEm) * fontSize) / font.unitsPerEm;\n return {\n letters,\n width: x,\n capHeight: em(os2?.sCapHeight, 0.7),\n xHeight: em(os2?.sxHeight, 0.5),\n descender: (-font.descender * fontSize) / font.unitsPerEm,\n };\n}\n\nconst fontCache = new Map<string, Promise<Font>>();\n\nfunction loadAnatomyFont(url: string) {\n let pending = fontCache.get(url);\n if (!pending) {\n pending = fetch(url)\n .then((res) => res.arrayBuffer())\n .then((buffer) => parse(buffer));\n fontCache.set(url, pending);\n pending.catch(() => fontCache.delete(url));\n }\n return pending;\n}\n\nfunction useAnatomyFont(url: string) {\n const [font, setFont] = useState<Font | null>(null);\n\n useEffect(() => {\n const handle = delayRender(`glyph-anatomy: loading ${url}`);\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n continueRender(handle);\n };\n loadAnatomyFont(url).then((parsed) => {\n if (!released) setFont(parsed);\n release();\n }, release);\n return release;\n }, [url]);\n\n return font;\n}\n\nexport function GlyphAnatomy({\n text = glyphAnatomyDefaults.text,\n fontUrl = glyphAnatomyDefaults.fontUrl,\n fontSize = glyphAnatomyDefaults.fontSize,\n color = glyphAnatomyDefaults.color,\n guideColor = glyphAnatomyDefaults.guideColor,\n guides = glyphAnatomyDefaults.guides,\n keepPoints = glyphAnatomyDefaults.keepPoints,\n speed = glyphAnatomyDefaults.speed,\n className,\n}: GlyphAnatomyProps) {\n const frame = useCurrentFrame();\n const { fps, width, height } = useVideoConfig();\n const font = useAnatomyFont(fontUrl);\n if (!font) return null;\n\n const unit = height / 720;\n const t = getGlyphAnatomyTime(frame, { fps, speed });\n const word = layout(font, text, fontSize);\n const originX = (width - word.width * unit) / 2;\n const baseline = (height + word.capHeight * unit) / 2;\n const hair = 1.25;\n const anchorSize = 6;\n const handleRadius = 2.6;\n const margin = 0.3 * fontSize;\n // Guides fade with the last letter's scaffolding.\n const lastStart =\n glyphAnatomyTiming.letterStagger * Math.max(0, word.letters.length - 1);\n const scaffoldAll = keepPoints\n ? 1\n : getGlyphAnatomyLetter(t - lastStart).scaffold;\n\n const guideLines = [\n { label: \"Cap height\", y: -word.capHeight },\n { label: \"x-height\", y: -word.xHeight },\n { label: \"Baseline\", y: 0 },\n { label: \"Descender\", y: word.descender },\n ];\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n style={{ display: \"block\" }}\n >\n <g transform={`translate(${originX} ${baseline}) scale(${unit})`}>\n {guides\n ? guideLines.map((guide, i) => {\n const draw = getGlyphAnatomyGuide(t, i);\n if (draw <= 0) return null;\n const length = word.width + 2 * margin;\n return (\n <g key={guide.label} opacity={0.7 * scaffoldAll}>\n <line\n x1={-margin}\n x2={-margin + length * draw}\n y1={guide.y}\n y2={guide.y}\n stroke={guideColor}\n strokeWidth={hair * 0.8}\n />\n <text\n x={-margin}\n y={guide.y - 5}\n fill={guideColor}\n fontFamily={INTER}\n fontSize={11}\n fontWeight={500}\n opacity={draw}\n >\n {guide.label}\n </text>\n </g>\n );\n })\n : null}\n {word.letters.map((letter, i) => {\n const lt = t - glyphAnatomyTiming.letterStagger * i;\n const state = getGlyphAnatomyLetter(lt);\n const scaffold = keepPoints ? 1 : state.scaffold;\n const curves = letter.contours.flatMap((segments, c) =>\n segments.flatMap((s, k) => (s.c1 ? [`${c}:${k}`] : [])),\n );\n const curveOrder = new Map(curves.map((key, n) => [key, n]));\n const anchors = letter.contours.flatMap((segments) =>\n segments.map((s) => s.from),\n );\n const pullOf = (c: number) => (k: number) =>\n getGlyphAnatomyPull(\n lt,\n curveOrder.get(`${c}:${k}`) ?? 0,\n curves.length,\n );\n const paths = letter.contours.map((segments, c) =>\n getAnatomyPath(segments, pullOf(c)),\n );\n let anchorIndex = 0;\n return (\n <g key={i}>\n {state.fill > 0 ? (\n <path d={paths.join(\"\")} fill={color} opacity={state.fill} />\n ) : null}\n {state.outline > 0 && scaffold > 0 ? (\n <g opacity={scaffold}>\n {paths.map((d, c) => (\n <path\n key={c}\n d={d}\n fill=\"none\"\n stroke={color}\n strokeWidth={hair}\n opacity={state.outline}\n />\n ))}\n {letter.contours.map((segments, c) =>\n segments.map((s, k) => {\n if (!s.c1 || !s.c2) return null;\n const pull = pullOf(c)(k);\n if (pull <= 0) return null;\n const h1 = lerp(s.from, s.c1, pull);\n const h2 = lerp(s.to, s.c2, pull);\n return (\n <g key={`${c}-${k}`}>\n <line\n x1={s.from.x}\n y1={s.from.y}\n x2={h1.x}\n y2={h1.y}\n stroke={guideColor}\n strokeWidth={hair * 0.8}\n />\n <line\n x1={s.to.x}\n y1={s.to.y}\n x2={h2.x}\n y2={h2.y}\n stroke={guideColor}\n strokeWidth={hair * 0.8}\n />\n <circle\n cx={h1.x}\n cy={h1.y}\n r={handleRadius}\n fill={guideColor}\n />\n <circle\n cx={h2.x}\n cy={h2.y}\n r={handleRadius}\n fill={guideColor}\n />\n </g>\n );\n }),\n )}\n {letter.contours.map((segments, c) =>\n segments.map((s, k) => {\n const scale = getGlyphAnatomyAnchor(\n lt,\n anchorIndex++,\n anchors.length,\n );\n if (scale <= 0) return null;\n const size = anchorSize * scale;\n return (\n <rect\n key={`${c}-${k}`}\n x={s.from.x - size / 2}\n y={s.from.y - size / 2}\n width={size}\n height={size}\n fill=\"#ffffff\"\n stroke={guideColor}\n strokeWidth={hair}\n />\n );\n }),\n )}\n </g>\n ) : null}\n </g>\n );\n })}\n </g>\n </svg>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/glyph-anatomy.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/keystroke.json b/registry-artifacts/keystroke.jsonnew file mode 100644index 00000000..e35c01cf--- /dev/null+++ b/registry-artifacts/keystroke.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "keystroke",+ "title": "Keystroke",+ "description": "Physical keycaps rise in for each shortcut, press in real order with the modifiers held while the letter taps, spring back with a small capped overshoot, and leave after an idle hold, firing on the same frames as the remocn-ui steps they trigger.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/keystroke/index.tsx",+ "content": "\"use client\";\n\nimport { useMemo } from \"react\";\nimport { Easing, useCurrentFrame, useVideoConfig } from \"remotion\";\n\nexport type KeystrokePlatform = \"mac\" | \"windows\";\nexport type KeystrokeTheme = \"light\" | \"dark\";\nexport type KeystrokeIcon =\n | \"command\"\n | \"option\"\n | \"shift\"\n | \"control\"\n | \"return\"\n | \"delete\"\n | \"escape\"\n | \"tab\"\n | \"space\"\n | \"capsLock\"\n | \"up\"\n | \"down\"\n | \"left\"\n | \"right\";\n\nexport interface KeystrokeStep {\n at: number;\n keys: string;\n hold?: number;\n}\n\nexport interface KeystrokeProps {\n steps?: readonly KeystrokeStep[];\n platform?: KeystrokePlatform;\n theme?: KeystrokeTheme;\n accent?: string;\n x?: number;\n y?: number;\n size?: number;\n linger?: number;\n speed?: number;\n className?: string;\n}\n\nexport interface KeystrokeOptions extends Omit<KeystrokeProps, \"className\"> {\n width?: number;\n height?: number;\n fps?: number;\n}\n\nexport type KeystrokeLegend =\n | { kind: \"icon\"; icon: KeystrokeIcon }\n | { kind: \"char\"; text: string }\n | { kind: \"word\"; text: string };\n\nexport interface KeystrokeKey {\n name: string;\n label: string;\n legend: KeystrokeLegend;\n units: number;\n modifier: boolean;\n}\n\nexport type KeystrokeChord = KeystrokeKey[];\n\nexport interface KeystrokeKeyTiming {\n press: number;\n release: number;\n}\n\nexport interface KeystrokeChordTiming {\n enter: number;\n fire: number;\n keys: KeystrokeKeyTiming[];\n}\n\nexport interface KeystrokeLayout {\n caps: { chord: number; index: number; x: number; width: number }[];\n separators: { chord: number; x: number; width: number }[];\n widths: number[];\n}\n\nexport interface KeystrokeGroup {\n index: number;\n step: number;\n keys: string;\n label: string;\n chords: KeystrokeChord[];\n timing: KeystrokeChordTiming[];\n layout: KeystrokeLayout;\n at: number;\n hold: number;\n enter: number;\n lastRelease: number;\n pushes: number[];\n exit: number;\n end: number;\n}\n\nexport interface KeystrokePalette {\n cap: string;\n edge: string;\n wall: string;\n ink: string;\n separator: string;\n shadow: string;\n}\n\ntype Unset = \"steps\" | \"className\";\ntype Modifier = \"fn\" | \"ctrl\" | \"alt\" | \"shift\" | \"meta\";\ntype Named =\n | \"enter\"\n | \"escape\"\n | \"tab\"\n | \"space\"\n | \"backspace\"\n | \"delete\"\n | \"capsLock\"\n | \"up\"\n | \"down\"\n | \"left\"\n | \"right\"\n | \"home\"\n | \"end\"\n | \"pageUp\"\n | \"pageDown\";\ntype IconShape = { box: string; paths: readonly string[] };\ntype IconSpec = { label: string; icon: KeystrokeIcon; units: number };\ntype NamedSpec = IconSpec | { label: string; word: string; units: number };\ntype Draft = Omit<\n KeystrokeGroup,\n \"index\" | \"label\" | \"layout\" | \"pushes\" | \"exit\" | \"end\"\n>;\n\nexport const keystrokeDefaults: Required<Omit<KeystrokeProps, Unset>> = {\n platform: \"mac\",\n theme: \"light\",\n accent: \"#0a84ff\",\n x: 0.5,\n y: 0.86,\n size: 64,\n linger: 30,\n speed: 1,\n};\n\nexport const keystrokeDefaultSteps: readonly KeystrokeStep[] = [\n { at: 20, keys: \"mod+k\" },\n { at: 78, keys: \"g i\" },\n { at: 114, keys: \"shift+mod+p\" },\n];\n\nexport const keystrokePalettes: Record<KeystrokeTheme, KeystrokePalette> = {\n light: {\n cap: \"#fcfcfb\",\n edge: \"#dfdfda\",\n wall: \"#cfcfca\",\n ink: \"#1d1d1f\",\n separator: \"#8e8e89\",\n shadow: \"rgba(20, 20, 16, 0.18)\",\n },\n dark: {\n cap: \"#38393e\",\n edge: \"#48494f\",\n wall: \"#1f2023\",\n ink: \"#f5f5f7\",\n separator: \"#9d9da4\",\n shadow: \"rgba(0, 0, 0, 0.5)\",\n },\n};\n\nconst PRESS = 3;\nconst PRESS_GAP = 3;\nconst RELEASE_GAP = 3;\nconst LEAD = 7;\nconst STAGGER = 1;\nconst BEAT = 2;\nconst HOLD = 8;\nconst RELEASE = 10;\nconst RELEASE_RISE = 3;\nconst RELEASE_TAPER = 6;\nconst RELEASE_DAMPING = 0.46;\nconst ENTER = 10;\nconst ENTER_RISE = 4;\nconst ENTER_TAPER = 7;\nconst ENTER_DAMPING = 0.65;\nconst FADE_IN = 4;\nconst SLIDE = 10;\nconst DIM = 6;\nconst DIM_OPACITY = 0.45;\nconst PUSH = 10;\nconst BRIEF = 18;\nconst EXIT = 8;\nconst TAIL = 14;\nconst MAX_FRAMES = 600;\nconst MIN_SIZE = 8;\nconst MAX_SIZE = 400;\nconst WALL = 0.16;\nconst TRAVEL = 0.12;\nconst RADIUS = 0.16;\nconst RISE = 0.42;\nconst KEY_GAP = 0.14;\nconst SEPARATOR = 0.95;\nconst CHAR_FONT = 0.4;\nconst WORD_FONT = 0.26;\nconst ICON_SIZE = 0.36;\nconst SEPARATOR_FONT = 0.25;\nconst WORD_CHAR = 0.6 * WORD_FONT;\nconst WORD_PAD = 0.24;\nconst WINDOWS_WORD = 1.25;\nconst SLOT_RISE = 1.09;\nconst SLOT_SCALE = 0.86;\nconst SLOT_OPACITY = 0.55;\nconst EXIT_DRIFT = 0.22;\nconst EXIT_SCALE = 0.04;\nconst SHADOW_Y = 0.07;\nconst SHADOW_Y_PRESSED = 0.02;\nconst SHADOW_BLUR = 0.11;\nconst SHADOW_BLUR_PRESSED = 0.03;\nconst GLIDE = Easing.bezier(0.33, 1, 0.68, 1);\nconst FONT_FAMILY =\n 'var(--font-geist-sans, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Inter, Roboto, Helvetica, Arial, sans-serif)';\n\nconst ICONS: Record<KeystrokeIcon, IconShape> = {\n command: {\n box: \"0 0 24 24\",\n paths: [\n \"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3\",\n ],\n },\n option: { box: \"0 0 24 24\", paths: [\"M3 3h6l6 18h6\", \"M14 3h7\"] },\n shift: {\n box: \"0 0 24 24\",\n paths: [\n \"M9 19a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1v-6a1 1 0 0 1 1-1h3.293a.707.707 0 0 0 .5-1.207l-7.086-7.086a1 1 0 0 0-1.414 0l-7.086 7.086a.707.707 0 0 0 .5 1.207H8a1 1 0 0 1 1 1z\",\n ],\n },\n control: { box: \"0 0 24 24\", paths: [\"m18 15-6-6-6 6\"] },\n return: {\n box: \"0 0 24 24\",\n paths: [\"M20 4v7a4 4 0 0 1-4 4H4\", \"m9 10-5 5 5 5\"],\n },\n delete: {\n box: \"0 0 24 24\",\n paths: [\n \"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z\",\n \"m12 9 6 6\",\n \"m18 9-6 6\",\n ],\n },\n escape: {\n box: \"0 0 24 24\",\n paths: [\"M2 8V2h6\", \"m2 2 10 10\", \"M12 2A10 10 0 1 1 2 12\"],\n },\n tab: {\n box: \"0 0 24 24\",\n paths: [\"M17 12H3\", \"m11 18 6-6-6-6\", \"M21 5v14\"],\n },\n space: {\n box: \"0 6 24 24\",\n paths: [\"M22 17v1c0 .5-.5 1-1 1H3c-.5 0-1-.5-1-1v-1\"],\n },\n capsLock: {\n box: \"0 0 24 24\",\n paths: [\n \"M14 16a1 1 0 0 0 1-1v-2a1 1 0 0 1 1-1h3.293a.707.707 0 0 0 .5-1.207l-6.939-6.939a1.207 1.207 0 0 0-1.708 0l-6.94 6.94a.707.707 0 0 0 .5 1.206H8a1 1 0 0 1 1 1v2a1 1 0 0 0 1 1z\",\n \"M9 20h6\",\n ],\n },\n up: { box: \"0 0 24 24\", paths: [\"m5 12 7-7 7 7\", \"M12 19V5\"] },\n down: { box: \"0 0 24 24\", paths: [\"M12 5v14\", \"m19 12-7 7-7-7\"] },\n left: { box: \"0 0 24 24\", paths: [\"m12 19-7-7 7-7\", \"M19 12H5\"] },\n right: { box: \"0 0 24 24\", paths: [\"M5 12h14\", \"m12 5 7 7-7 7\"] },\n};\n\nconst MODIFIERS = new Map<string, Modifier>([\n [\"fn\", \"fn\"],\n [\"ctrl\", \"ctrl\"],\n [\"control\", \"ctrl\"],\n [\"alt\", \"alt\"],\n [\"option\", \"alt\"],\n [\"opt\", \"alt\"],\n [\"shift\", \"shift\"],\n [\"cmd\", \"meta\"],\n [\"command\", \"meta\"],\n [\"meta\", \"meta\"],\n [\"win\", \"meta\"],\n [\"super\", \"meta\"],\n]);\n\nconst MODIFIER_ORDER: Record<KeystrokePlatform, readonly Modifier[]> = {\n mac: [\"fn\", \"ctrl\", \"alt\", \"shift\", \"meta\"],\n windows: [\"fn\", \"meta\", \"ctrl\", \"alt\", \"shift\"],\n};\n\nconst MAC_MODIFIERS: Record<Exclude<Modifier, \"fn\">, IconSpec> = {\n ctrl: { label: \"Control\", icon: \"control\", units: 1 },\n alt: { label: \"Option\", icon: \"option\", units: 1 },\n shift: { label: \"Shift\", icon: \"shift\", units: 1.5 },\n meta: { label: \"Command\", icon: \"command\", units: 1 },\n};\n\nconst WINDOWS_MODIFIERS: Record<Modifier, string> = {\n fn: \"Fn\",\n ctrl: \"Ctrl\",\n alt: \"Alt\",\n shift: \"Shift\",\n meta: \"Win\",\n};\n\nconst NAMED = new Map<string, Named>([\n [\"enter\", \"enter\"],\n [\"return\", \"enter\"],\n [\"esc\", \"escape\"],\n [\"escape\", \"escape\"],\n [\"tab\", \"tab\"],\n [\"space\", \"space\"],\n [\"backspace\", \"backspace\"],\n [\"delete\", \"delete\"],\n [\"del\", \"delete\"],\n [\"capslock\", \"capsLock\"],\n [\"up\", \"up\"],\n [\"arrowup\", \"up\"],\n [\"down\", \"down\"],\n [\"arrowdown\", \"down\"],\n [\"left\", \"left\"],\n [\"arrowleft\", \"left\"],\n [\"right\", \"right\"],\n [\"arrowright\", \"right\"],\n [\"home\", \"home\"],\n [\"end\", \"end\"],\n [\"pageup\", \"pageUp\"],\n [\"pgup\", \"pageUp\"],\n [\"pagedown\", \"pageDown\"],\n [\"pgdn\", \"pageDown\"],\n]);\n\nconst CHARACTERS = new Map<string, string>([\n [\"plus\", \"+\"],\n [\"minus\", \"-\"],\n [\"comma\", \",\"],\n [\"period\", \".\"],\n [\"slash\", \"/\"],\n [\"backslash\", \"\\\\\"],\n [\"semicolon\", \";\"],\n [\"quote\", \"'\"],\n [\"backquote\", \"`\"],\n [\"bracketleft\", \"[\"],\n [\"bracketright\", \"]\"],\n [\"equal\", \"=\"],\n]);\n\nconst ARROWS: Record<\"up\" | \"down\" | \"left\" | \"right\", IconSpec> = {\n up: { label: \"Up Arrow\", icon: \"up\", units: 1 },\n down: { label: \"Down Arrow\", icon: \"down\", units: 1 },\n left: { label: \"Left Arrow\", icon: \"left\", units: 1 },\n right: { label: \"Right Arrow\", icon: \"right\", units: 1 },\n};\n\nconst NAMED_KEYS: Record<KeystrokePlatform, Record<Named, NamedSpec>> = {\n mac: {\n enter: { label: \"Return\", icon: \"return\", units: 1.5 },\n escape: { label: \"Escape\", icon: \"escape\", units: 1 },\n tab: { label: \"Tab\", icon: \"tab\", units: 1.25 },\n space: { label: \"Space\", icon: \"space\", units: 2.5 },\n backspace: { label: \"Delete\", icon: \"delete\", units: 1.25 },\n delete: { label: \"Delete\", icon: \"delete\", units: 1.25 },\n capsLock: { label: \"Caps Lock\", icon: \"capsLock\", units: 1.5 },\n ...ARROWS,\n home: { label: \"Home\", word: \"home\", units: 1 },\n end: { label: \"End\", word: \"end\", units: 1 },\n pageUp: { label: \"Page Up\", word: \"page up\", units: 1 },\n pageDown: { label: \"Page Down\", word: \"page down\", units: 1 },\n },\n windows: {\n enter: { label: \"Enter\", word: \"Enter\", units: WINDOWS_WORD },\n escape: { label: \"Esc\", word: \"Esc\", units: WINDOWS_WORD },\n tab: { label: \"Tab\", word: \"Tab\", units: WINDOWS_WORD },\n space: { label: \"Space\", word: \"Space\", units: 2.5 },\n backspace: { label: \"Backspace\", word: \"Backspace\", units: WINDOWS_WORD },\n delete: { label: \"Delete\", word: \"Delete\", units: WINDOWS_WORD },\n capsLock: { label: \"Caps Lock\", word: \"Caps Lock\", units: WINDOWS_WORD },\n ...ARROWS,\n home: { label: \"Home\", word: \"Home\", units: WINDOWS_WORD },\n end: { label: \"End\", word: \"End\", units: WINDOWS_WORD },\n pageUp: { label: \"Page Up\", word: \"PgUp\", units: WINDOWS_WORD },\n pageDown: { label: \"Page Down\", word: \"PgDn\", units: WINDOWS_WORD },\n },\n};\n\nconst finite = (value: number | undefined, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst within = (\n value: number | undefined,\n fallback: number,\n min: number,\n max: number,\n) => clamp(finite(value, fallback), min, max);\nconst round = (value: number) => Math.round(value * 1000) / 1000 + 0;\nconst smoothstep = (value: number) => {\n const t = clamp(value, 0, 1);\n return t * t * (3 - 2 * t);\n};\nconst fpsOf = (fps: number | undefined) => Math.max(1, finite(fps, 30));\nconst rateOf = (speed: number | undefined) =>\n Math.max(0, finite(speed, keystrokeDefaults.speed));\nconst platformOf = (value: string | undefined): KeystrokePlatform =>\n value === \"windows\" ? value : \"mac\";\nconst themeOf = (value: string | undefined): KeystrokeTheme =>\n value === \"dark\" ? value : \"light\";\nconst accentOf = (value: string | undefined) =>\n typeof value === \"string\" && value.trim() !== \"\"\n ? value.trim()\n : keystrokeDefaults.accent;\nconst modOf = (platform: KeystrokePlatform): Modifier =>\n platform === \"mac\" ? \"meta\" : \"ctrl\";\n\nfunction eased(frames: number, duration: number, curve: (t: number) => number) {\n if (Number.isNaN(frames) || frames <= 0) return 0;\n if (frames >= duration) return 1;\n return curve(frames / duration);\n}\n\nfunction settle(rise: number, damping: number, taper: number, end: number) {\n const frequency = (Math.PI - Math.acos(damping)) / rise;\n const ratio = damping / Math.sqrt(1 - damping ** 2);\n return (frames: number) => {\n if (Number.isNaN(frames) || frames <= 0) return 0;\n if (frames >= end) return 1;\n const phase = frequency * frames;\n const decay = Math.exp(-ratio * phase);\n const ring = decay * (Math.cos(phase) + ratio * Math.sin(phase));\n return 1 - ring * (1 - smoothstep((frames - taper) / (end - taper)));\n };\n}\n\nconst riseCurve = settle(ENTER_RISE, ENTER_DAMPING, ENTER_TAPER, ENTER);\nconst releaseCurve = settle(\n RELEASE_RISE,\n RELEASE_DAMPING,\n RELEASE_TAPER,\n RELEASE,\n);\n\nexport function getKeystrokePress(frames: number) {\n return eased(frames, PRESS, smoothstep);\n}\n\nexport function getKeystrokeRelease(frames: number) {\n return releaseCurve(frames);\n}\n\nexport function getKeystrokeRise(frames: number) {\n return riseCurve(frames);\n}\n\nexport function getKeystrokeDepth(time: number, timing: KeystrokeKeyTiming) {\n if (Number.isNaN(time) || time <= timing.press) return 0;\n if (time < timing.release) return getKeystrokePress(time - timing.press);\n const bottom = getKeystrokePress(timing.release - timing.press);\n return bottom * (1 - getKeystrokeRelease(time - timing.release));\n}\n\nexport function getKeystrokeWordUnits(text: string, min = 1) {\n const raw = Array.from(text).length * WORD_CHAR + 2 * WORD_PAD;\n return Math.max(min, Math.ceil(raw * 4 - 1e-9) / 4);\n}\n\nfunction wordKey(\n name: string,\n label: string,\n text: string,\n platform: KeystrokePlatform,\n modifier: boolean,\n min = 1,\n): KeystrokeKey {\n const floor = platform === \"windows\" ? Math.max(min, WINDOWS_WORD) : min;\n const units = getKeystrokeWordUnits(text, floor);\n return { name, label, legend: { kind: \"word\", text }, units, modifier };\n}\n\nfunction modifierKey(\n modifier: Modifier,\n platform: KeystrokePlatform,\n): KeystrokeKey {\n if (platform === \"windows\") {\n const word = WINDOWS_MODIFIERS[modifier];\n return wordKey(modifier, word, word, platform, true);\n }\n if (modifier === \"fn\") return wordKey(\"fn\", \"Fn\", \"fn\", platform, true);\n const { label, icon, units } = MAC_MODIFIERS[modifier];\n return {\n name: modifier,\n label,\n legend: { kind: \"icon\", icon },\n units,\n modifier: true,\n };\n}\n\nfunction namedKey(named: Named, platform: KeystrokePlatform): KeystrokeKey {\n const spec = NAMED_KEYS[platform][named];\n if (\"word\" in spec) {\n return wordKey(named, spec.label, spec.word, platform, false, spec.units);\n }\n return {\n name: named,\n label: spec.label,\n legend: { kind: \"icon\", icon: spec.icon },\n units: spec.units,\n modifier: false,\n };\n}\n\nfunction keyOf(part: string, platform: KeystrokePlatform): KeystrokeKey {\n const name = part.toLowerCase();\n const named = NAMED.get(name);\n if (named) return namedKey(named, platform);\n const character =\n CHARACTERS.get(name) ?? (Array.from(part).length === 1 ? part : undefined);\n if (character !== undefined) {\n const text = character.toUpperCase();\n return {\n name: character.toLowerCase(),\n label: text,\n legend: { kind: \"char\", text },\n units: 1,\n modifier: false,\n };\n }\n const fkey = /^f([1-9]|1\\d|2[0-4])$/.exec(name);\n if (fkey) {\n const text = `F${fkey[1]}`;\n return wordKey(name, text, text, platform, false);\n }\n const text = `${part.charAt(0).toUpperCase()}${part.slice(1)}`;\n return wordKey(name, text, text, platform, false);\n}\n\nfunction splitChord(token: string) {\n const parts = token.split(\"+\");\n const names: string[] = [];\n for (const [index, part] of parts.entries()) {\n if (part !== \"\") names.push(part);\n else if (index === parts.length - 1 && parts[index - 1] === \"\") {\n names.push(\"+\");\n }\n }\n return names;\n}\n\nfunction parseChord(token: string, platform: KeystrokePlatform) {\n const held = new Set<Modifier>();\n const keys: KeystrokeKey[] = [];\n for (const part of splitChord(token)) {\n const name = part.toLowerCase();\n const modifier = name === \"mod\" ? modOf(platform) : MODIFIERS.get(name);\n if (modifier) held.add(modifier);\n else keys.push(keyOf(part, platform));\n }\n const modifiers = MODIFIER_ORDER[platform]\n .filter((modifier) => held.has(modifier))\n .map((modifier) => modifierKey(modifier, platform));\n return [...modifiers, ...keys];\n}\n\nexport function parseKeystrokeKeys(\n keys: string,\n platform?: KeystrokePlatform,\n): KeystrokeChord[] {\n if (typeof keys !== \"string\") return [];\n const target = platformOf(platform);\n return keys\n .trim()\n .split(/\\s+/)\n .filter((token) => token !== \"\")\n .map((token) => parseChord(token, target))\n .filter((chord) => chord.length > 0);\n}\n\nexport function getKeystrokeLayout(\n chords: readonly KeystrokeChord[],\n): KeystrokeLayout {\n const layout: KeystrokeLayout = { caps: [], separators: [], widths: [] };\n let cursor = 0;\n for (const [chord, keys] of chords.entries()) {\n if (chord > 0) {\n layout.separators.push({ chord, x: round(cursor), width: SEPARATOR });\n cursor += SEPARATOR;\n }\n for (const [index, key] of keys.entries()) {\n if (index > 0) cursor += KEY_GAP;\n layout.caps.push({ chord, index, x: round(cursor), width: key.units });\n cursor += key.units;\n }\n layout.widths.push(round(cursor));\n }\n return layout;\n}\n\nfunction schedule(chords: readonly KeystrokeChord[], hold: number) {\n const timing: KeystrokeChordTiming[] = [];\n let enter = 0;\n for (const chord of chords) {\n const last = chord.length - 1;\n const fire = enter + LEAD + PRESS_GAP * last + PRESS;\n const keys = chord.map((_, index) => ({\n press: fire - PRESS - PRESS_GAP * (last - index),\n release: fire + hold + RELEASE_GAP * (last - index),\n }));\n timing.push({ enter, fire, keys });\n enter = fire + hold + RELEASE_GAP * last + BEAT;\n }\n return timing;\n}\n\nexport function getKeystrokeLeadIn(keys: string, hold = HOLD) {\n const chords = parseKeystrokeKeys(keys);\n if (chords.length === 0) return 0;\n const timing = schedule(chords, within(hold, HOLD, 0, MAX_FRAMES));\n return timing[timing.length - 1].fire - timing[0].enter;\n}\n\nexport function getKeystrokeTimeline(\n options: Pick<KeystrokeOptions, \"steps\" | \"platform\" | \"linger\" | \"fps\"> = {},\n) {\n const platform = platformOf(options.platform);\n const scale = 30 / fpsOf(options.fps);\n const lingerFrames = within(\n options.linger,\n keystrokeDefaults.linger,\n 0,\n MAX_FRAMES,\n );\n const linger = lingerFrames * scale;\n const steps = options.steps ?? keystrokeDefaultSteps;\n const drafts: Draft[] = [];\n for (const [step, entry] of steps.entries()) {\n if (typeof entry.at !== \"number\" || !Number.isFinite(entry.at)) continue;\n const chords = parseKeystrokeKeys(entry.keys, platform);\n if (chords.length === 0) continue;\n const at = entry.at * scale;\n const hold = within(entry.hold, HOLD, 0, MAX_FRAMES) * scale;\n const planned = schedule(chords, hold);\n const offset = at - planned[planned.length - 1].fire;\n const timing = planned.map((chord) => ({\n enter: round(chord.enter + offset),\n fire: round(chord.fire + offset),\n keys: chord.keys.map((key) => ({\n press: round(key.press + offset),\n release: round(key.release + offset),\n })),\n }));\n const releases = timing.flatMap((chord) =>\n chord.keys.map((key) => key.release),\n );\n drafts.push({\n step,\n keys: entry.keys,\n chords,\n timing,\n at: round(at),\n hold: round(hold),\n enter: timing[0].enter,\n lastRelease: Math.max(...releases),\n });\n }\n drafts.sort((a, b) => a.enter - b.enter || a.at - b.at || a.step - b.step);\n const groups = drafts.map((draft, index): KeystrokeGroup => {\n const pushes: number[] = [];\n let exit = Math.max(draft.enter, draft.lastRelease + linger);\n for (const newer of drafts.slice(index + 1)) {\n if (newer.enter >= exit + EXIT) break;\n const at = Math.max(newer.enter, draft.enter);\n const brief = Math.max(at, draft.lastRelease) + BRIEF;\n pushes.push(at);\n exit = Math.min(exit, pushes.length === 1 ? brief : at);\n if (pushes.length === 2) break;\n }\n exit = round(Math.max(exit, draft.enter));\n const label = draft.chords\n .map((chord) => chord.map((key) => key.label).join(\" \"))\n .join(\" then \");\n return {\n ...draft,\n index,\n label,\n layout: getKeystrokeLayout(draft.chords),\n pushes,\n exit,\n end: round(exit + EXIT),\n };\n });\n const end = groups.reduce((latest, group) => Math.max(latest, group.end), 0);\n return { platform, linger: round(linger), groups, end };\n}\n\nexport type KeystrokeTimeline = ReturnType<typeof getKeystrokeTimeline>;\n\nexport const keystrokeLength = getKeystrokeTimeline().end;\n\nexport function getKeystrokeDuration(\n options: Pick<KeystrokeOptions, \"steps\" | \"linger\" | \"speed\" | \"fps\"> = {},\n) {\n const fps = fpsOf(options.fps);\n const rate = rateOf(options.speed);\n const { end } = getKeystrokeTimeline(options);\n const motion = rate === 0 ? 0 : (end * fps) / 30 / rate;\n return Math.ceil(round(motion)) + Math.round((TAIL * fps) / 30);\n}\n\nexport function getKeystrokeTime(\n frame: number,\n options: Pick<KeystrokeOptions, \"fps\" | \"speed\"> = {},\n) {\n const elapsed = Math.max(0, finite(frame, 0));\n return (elapsed * rateOf(options.speed) * 30) / fpsOf(options.fps);\n}\n\nexport function getKeystrokeMetrics(size: number, unit = 1) {\n return {\n size: round(size),\n height: round(size),\n wall: round(size * WALL),\n travel: round(size * TRAVEL),\n keytop: round(size * (1 - WALL)),\n radius: round(size * RADIUS),\n rise: round(size * RISE),\n border: round(Math.max(1, unit)),\n charFont: round(size * CHAR_FONT),\n wordFont: round(size * WORD_FONT),\n icon: round(size * ICON_SIZE),\n separatorFont: round(size * SEPARATOR_FONT),\n };\n}\n\nexport type KeystrokeMetrics = ReturnType<typeof getKeystrokeMetrics>;\n\nfunction legendColor(ink: string, accent: string, amount: number) {\n const share = Math.floor(clamp(amount, 0, 1) * 100);\n if (share <= 0) return ink;\n if (share >= 100) return accent;\n return `color-mix(in srgb, ${accent} ${share}%, ${ink})`;\n}\n\nfunction fadeIn(frames: number) {\n return eased(frames, FADE_IN, (t) => 1 - (1 - t) ** 2);\n}\n\nfunction groupState(\n group: KeystrokeGroup,\n time: number,\n metrics: KeystrokeMetrics,\n palette: KeystrokePalette,\n accent: string,\n) {\n const { size } = metrics;\n const slot = group.pushes.reduce(\n (sum, at) => sum + eased(time - at, PUSH, GLIDE),\n 0,\n );\n const leaving = clamp((time - group.exit) / EXIT, 0, 1);\n const pushedAway = group.pushes.some((at) => at <= group.exit);\n const drift = (pushedAway ? -1 : 1) * EXIT_DRIFT * size * leaving ** 3;\n const dimmed = 1 - (1 - SLOT_OPACITY) * Math.min(1, slot);\n const last = group.chords.length - 1;\n let visible = group.layout.widths[0];\n for (let chord = 1; chord <= last; chord++) {\n const added = group.layout.widths[chord] - group.layout.widths[chord - 1];\n visible += added * eased(time - group.timing[chord].enter, SLIDE, GLIDE);\n }\n const left = -visible / 2;\n const caps = group.layout.caps.flatMap((cap) => {\n const timing = group.timing[cap.chord];\n const enter = timing.enter + cap.index * STAGGER;\n if (time <= enter) return [];\n const key = group.chords[cap.chord][cap.index];\n const depth = getKeystrokeDepth(time, timing.keys[cap.index]);\n const landing =\n group.timing.at(cap.chord + 1)?.fire ?? Number.POSITIVE_INFINITY;\n const dim = smoothstep((time - (landing - DIM)) / DIM);\n const lean = clamp(depth, -1, 1);\n const shadowY = SHADOW_Y - (SHADOW_Y - SHADOW_Y_PRESSED) * lean;\n const shadowBlur = SHADOW_BLUR - (SHADOW_BLUR - SHADOW_BLUR_PRESSED) * lean;\n return [\n {\n id: `${cap.chord}-${cap.index}`,\n chord: cap.chord,\n index: cap.index,\n key,\n x: round((left + cap.x) * size),\n y: round((1 - getKeystrokeRise(time - enter)) * metrics.rise),\n width: round(cap.width * size),\n opacity: round(fadeIn(time - enter) * (1 - (1 - DIM_OPACITY) * dim)),\n depth: round(depth),\n lift: round(depth * metrics.travel),\n wall: round(metrics.wall - depth * metrics.travel),\n shadowY: round(shadowY * size),\n shadowBlur: round(shadowBlur * size),\n color: legendColor(palette.ink, accent, clamp(depth, 0, 1)),\n },\n ];\n });\n const separators = group.layout.separators.flatMap((separator) => {\n const enter = group.timing[separator.chord].enter;\n if (time <= enter) return [];\n return [\n {\n id: `then-${separator.chord}`,\n chord: separator.chord,\n x: round((left + separator.x) * size),\n y: round((1 - getKeystrokeRise(time - enter)) * metrics.rise),\n width: round(separator.width * size),\n opacity: round(fadeIn(time - enter)),\n },\n ];\n });\n return {\n id: `${group.step}`,\n index: group.index,\n step: group.step,\n keys: group.keys,\n label: group.label,\n slot: round(slot),\n width: round(visible * size),\n y: round(-slot * SLOT_RISE * size + drift),\n scale: round((1 - (1 - SLOT_SCALE) * slot) * (1 - EXIT_SCALE * leaving)),\n opacity: round(dimmed * (1 - leaving ** 2)),\n caps,\n separators,\n };\n}\n\nexport function getKeystrokeState(\n frame: number,\n options: KeystrokeOptions = {},\n timeline: KeystrokeTimeline = getKeystrokeTimeline(options),\n) {\n const width = Math.max(1, finite(options.width, 1280));\n const height = Math.max(1, finite(options.height, 720));\n const unit = height / 720;\n const reference = within(\n options.size,\n keystrokeDefaults.size,\n MIN_SIZE,\n MAX_SIZE,\n );\n const metrics = getKeystrokeMetrics(reference * unit, unit);\n const time = getKeystrokeTime(frame, options);\n const x = finite(options.x, keystrokeDefaults.x);\n const y = finite(options.y, keystrokeDefaults.y);\n const theme = themeOf(options.theme);\n const palette = keystrokePalettes[theme];\n const accent = accentOf(options.accent);\n const groups = timeline.groups\n .filter((group) => time > group.enter && time < group.end)\n .map((group) => groupState(group, time, metrics, palette, accent));\n return {\n width,\n height,\n unit,\n time: round(time),\n x,\n y,\n originX: round(x * width),\n originY: round(y * height),\n theme,\n palette,\n accent,\n metrics,\n groups,\n };\n}\n\nexport type KeystrokeState = ReturnType<typeof getKeystrokeState>;\n\nfunction Legend({\n legend,\n metrics,\n}: {\n legend: KeystrokeLegend;\n metrics: KeystrokeMetrics;\n}) {\n if (legend.kind === \"icon\") {\n const icon = ICONS[legend.icon];\n return (\n <svg\n width={metrics.icon}\n height={metrics.icon}\n viewBox={icon.box}\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n style={{ display: \"block\" }}\n >\n {icon.paths.map((d) => (\n <path key={d} d={d} />\n ))}\n </svg>\n );\n }\n const fontSize = legend.kind === \"word\" ? metrics.wordFont : metrics.charFont;\n return (\n <span\n style={{ fontSize, fontWeight: 500, lineHeight: 1, whiteSpace: \"nowrap\" }}\n >\n {legend.text}\n </span>\n );\n}\n\nexport function Keystroke({\n steps = keystrokeDefaultSteps,\n platform = keystrokeDefaults.platform,\n theme = keystrokeDefaults.theme,\n accent = keystrokeDefaults.accent,\n x = keystrokeDefaults.x,\n y = keystrokeDefaults.y,\n size = keystrokeDefaults.size,\n linger = keystrokeDefaults.linger,\n speed = keystrokeDefaults.speed,\n className,\n}: KeystrokeProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const timeline = useMemo(\n () => getKeystrokeTimeline({ steps, platform, linger, fps }),\n [steps, platform, linger, fps],\n );\n const state = getKeystrokeState(\n frame,\n { width, height, fps, theme, accent, x, y, size, speed },\n timeline,\n );\n const { metrics, palette } = state;\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n overflow: \"hidden\",\n pointerEvents: \"none\",\n fontFamily: FONT_FAMILY,\n }}\n >\n {state.groups.map((group) => (\n <div\n key={group.id}\n style={{\n position: \"absolute\",\n left: `${state.x * 100}%`,\n top: `${state.y * 100}%`,\n width: 0,\n height: 0,\n opacity: group.opacity,\n transform: `translateY(${group.y}px) scale(${group.scale})`,\n transformOrigin: \"0 0\",\n }}\n >\n {group.separators.map((separator) => (\n <div\n key={separator.id}\n style={{\n position: \"absolute\",\n left: separator.x,\n top: separator.y - metrics.height / 2,\n width: separator.width,\n height: metrics.keytop,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n opacity: separator.opacity,\n color: palette.separator,\n fontSize: metrics.separatorFont,\n fontWeight: 500,\n lineHeight: 1,\n whiteSpace: \"nowrap\",\n }}\n >\n then\n </div>\n ))}\n {group.caps.map((cap) => (\n <div\n key={cap.id}\n style={{\n position: \"absolute\",\n left: cap.x,\n top: cap.y - metrics.height / 2,\n width: cap.width,\n height: metrics.height,\n opacity: cap.opacity,\n }}\n >\n <div\n style={{\n position: \"absolute\",\n left: 0,\n right: 0,\n top: metrics.travel,\n bottom: 0,\n borderRadius: metrics.radius,\n background: palette.wall,\n boxShadow: `0 ${cap.shadowY}px ${cap.shadowBlur}px ${palette.shadow}`,\n }}\n />\n <div\n style={{\n position: \"absolute\",\n left: 0,\n right: 0,\n top: 0,\n height: metrics.keytop,\n boxSizing: \"border-box\",\n borderRadius: metrics.radius,\n border: `${metrics.border}px solid ${palette.edge}`,\n background: palette.cap,\n color: cap.color,\n transform: `translateY(${cap.lift}px)`,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n >\n <Legend legend={cap.key.legend} metrics={metrics} />\n </div>\n </div>\n ))}\n </div>\n ))}\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/keystroke.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/mondrian-split.json b/registry-artifacts/mondrian-split.jsonnew file mode 100644index 00000000..7ad749c8--- /dev/null+++ b/registry-artifacts/mondrian-split.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "mondrian-split",+ "title": "Mondrian Split",+ "description": "Black lines cut the frame into a seeded De Stijl grid, primaries wipe into its cells, the grid reflows like rubber, and one cell pushes its own lines out past the edges to become a clean color field or the next scene.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/mondrian-split/index.tsx",+ "content": "\"use client\";\n\nimport { type CSSProperties, type ReactNode, useMemo } from \"react\";\nimport { Easing, random, useCurrentFrame, useVideoConfig } from \"remotion\";\n\nexport type MondrianSplitAxis = \"x\" | \"y\";\nexport type MondrianSplitSlot = \"red\" | \"yellow\" | \"blue\";\nexport type MondrianSplitSide = \"left\" | \"top\" | \"right\" | \"bottom\";\n\nexport interface MondrianSplitProps {\n children?: ReactNode;\n seed?: number;\n splits?: number;\n lineWeight?: number;\n expandCell?: number;\n lineColor?: string;\n redColor?: string;\n yellowColor?: string;\n blueColor?: string;\n fieldColor?: string;\n speed?: number;\n className?: string;\n}\n\nexport type MondrianSplitOptions = Pick<\n MondrianSplitProps,\n \"seed\" | \"splits\" | \"lineWeight\" | \"expandCell\"\n> & {\n width?: number;\n height?: number;\n};\n\nexport interface MondrianSplitBox {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n}\n\nexport interface MondrianSplitRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\ninterface GridNode {\n box: MondrianSplitBox;\n bounds: Record<MondrianSplitSide, number>;\n line: number;\n}\n\ninterface GridCut {\n axis: MondrianSplitAxis;\n position: number;\n node: number;\n}\n\ninterface GridMove {\n track: number;\n from: number;\n to: number;\n start: number;\n}\n\ninterface GridWipe {\n axis: MondrianSplitAxis;\n fromEnd: boolean;\n}\n\nexport const mondrianSplitDefaults = {\n seed: 7,\n splits: 7,\n lineWeight: 14,\n expandCell: 0,\n lineColor: \"#121212\",\n redColor: \"#d62d20\",\n yellowColor: \"#f4c20d\",\n blueColor: \"#1f4e9e\",\n fieldColor: \"#d62d20\",\n};\n\nconst LINE_START = 3;\nconst LINE_GAP = 5;\nconst LINE_DRAW = 10;\nconst FILL_LAG = 7;\nconst FILL_GAP = 4;\nconst FILL_WIPE = 9;\nconst FIELD_LAG = 6;\nconst FIELD_WIPE = 12;\nconst HOLD = 14;\nconst TRACK_COUNT = 3;\nconst TRACK_GAP = 5;\nconst TRACK_SLIDE = 20;\nconst EXPAND_LEAD = 4;\nconst SIDE_GAP = 3;\nconst SIDE_PUSH = 22;\nconst TAIL = 12;\nconst SLIDE_PEAK = 0.72;\nconst SLIDE_OVER = 0.035;\nconst RESERVE = 0.045;\nconst WIND = 0.22;\nconst DIP = 0.035;\nconst DIP_SHARE = 0.2;\nconst SIDES: MondrianSplitSide[] = [\"left\", \"top\", \"right\", \"bottom\"];\nconst SLOTS: MondrianSplitSlot[] = [\"blue\", \"yellow\", \"red\", \"blue\", \"yellow\"];\nconst FALLBACK_CUTS = [0.38, 0.62, 0.3, 0.7, 0.5];\n\nconst drawEase = Easing.bezier(0.16, 1, 0.3, 1);\nconst wipeEase = Easing.bezier(0.7, 0, 0.2, 1);\nconst riseEase = Easing.bezier(0.65, 0, 0.3, 1);\nconst settleEase = Easing.bezier(0.4, 0, 0.6, 1);\nconst windEase = Easing.bezier(0.45, 0, 0.55, 1);\nconst pushEase = Easing.poly(2.5);\nconst layer: CSSProperties = { position: \"absolute\", inset: 0 };\n\nconst finite = (value: number, fallback: number) =>\n Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst mix = (from: number, to: number, amount: number) =>\n from + (to - from) * amount;\nconst progress = (time: number, start: number, duration: number) =>\n clamp((time - start) / duration, 0, 1);\nconst other = (axis: MondrianSplitAxis): MondrianSplitAxis =>\n axis === \"x\" ? \"y\" : \"x\";\nconst lowEdge = (box: MondrianSplitBox, axis: MondrianSplitAxis) =>\n axis === \"x\" ? box.x0 : box.y0;\nconst extent = (box: MondrianSplitBox, axis: MondrianSplitAxis) =>\n axis === \"x\" ? box.x1 - box.x0 : box.y1 - box.y0;\nconst area = (box: MondrianSplitBox) => extent(box, \"x\") * extent(box, \"y\");\nconst splitCount = (splits: number) =>\n Math.round(clamp(finite(splits, mondrianSplitDefaults.splits), 3, 12));\nconst coloredCount = (count: number) => clamp(Math.round(count * 0.3), 1, 5);\n\nconst touches = (a: MondrianSplitBox, b: MondrianSplitBox) => {\n const overlapX = Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0);\n const overlapY = Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0);\n const beside = Math.abs(a.x1 - b.x0) < 0.5 || Math.abs(b.x1 - a.x0) < 0.5;\n const stacked = Math.abs(a.y1 - b.y0) < 0.5 || Math.abs(b.y1 - a.y0) < 0.5;\n return (beside && overlapY > 0.5) || (stacked && overlapX > 0.5);\n};\n\nconst choose = (weights: readonly number[], roll: number) => {\n let remaining = roll * weights.reduce((sum, value) => sum + value, 0);\n for (let index = 0; index < weights.length; index++) {\n remaining -= weights[index];\n if (remaining <= 0) return index;\n }\n return weights.length - 1;\n};\n\nconst slide = (amount: number) => {\n if (amount >= 1) return 1;\n if (amount <= SLIDE_PEAK) {\n return (1 + SLIDE_OVER) * riseEase(amount / SLIDE_PEAK);\n }\n const settle = settleEase((amount - SLIDE_PEAK) / (1 - SLIDE_PEAK));\n return mix(1 + SLIDE_OVER, 1, settle);\n};\n\nconst push = (amount: number, dip: number) => {\n if (amount >= 1) return 1;\n if (amount <= 0) return 0;\n if (amount < WIND) return -dip * windEase(amount / WIND);\n return mix(-dip, 1, pushEase((amount - WIND) / (1 - WIND)));\n};\n\nconst stretch = (\n from0: number,\n from1: number,\n to0: number,\n to1: number,\n min: number,\n max: number,\n) => {\n if (from0 === to0 && from1 === to1) return (value: number) => value;\n return (value: number) => {\n if (value <= from0) {\n return min + (value - min) * ((to0 - min) / (from0 - min));\n }\n if (value >= from1) {\n return max - (max - value) * ((max - to1) / (max - from1));\n }\n return to0 + (value - from0) * ((to1 - to0) / (from1 - from0));\n };\n};\n\nconst wipe = (\n box: MondrianSplitBox,\n { axis, fromEnd }: GridWipe,\n amount: number,\n): MondrianSplitRect => {\n const width = box.x1 - box.x0;\n const height = box.y1 - box.y0;\n if (axis === \"x\") {\n const span = width * amount;\n return {\n x: fromEnd ? box.x1 - span : box.x0,\n y: box.y0,\n width: span,\n height,\n };\n }\n const span = height * amount;\n return {\n x: box.x0,\n y: fromEnd ? box.y1 - span : box.y0,\n width,\n height: span,\n };\n};\n\nconst inFrame = (rect: MondrianSplitRect, width: number, height: number) =>\n rect.width > 0.01 &&\n rect.height > 0.01 &&\n rect.x < width &&\n rect.y < height &&\n rect.x + rect.width > 0 &&\n rect.y + rect.height > 0;\n\nconst placeBoxes = (\n cuts: readonly Pick<GridCut, \"axis\" | \"node\">[],\n positions: readonly number[],\n width: number,\n height: number,\n) => {\n const boxes: MondrianSplitBox[] = [{ x0: 0, y0: 0, x1: width, y1: height }];\n for (let id = 0; id < cuts.length; id++) {\n const { axis, node } = cuts[id];\n const box = boxes[node];\n const at = positions[id];\n boxes.push(\n axis === \"x\" ? { ...box, x1: at } : { ...box, y1: at },\n axis === \"x\" ? { ...box, x0: at } : { ...box, y0: at },\n );\n }\n return boxes;\n};\n\nconst percent = (value: number, size: number) =>\n `${(clamp(value / size, 0, 1) * 100).toFixed(4)}%`;\n\nexport function getMondrianSplitTimeline({\n splits = mondrianSplitDefaults.splits,\n}: Pick<MondrianSplitProps, \"splits\"> = {}) {\n const count = splitCount(splits);\n const fill = LINE_START + (count - 1) * LINE_GAP + FILL_LAG;\n const field = fill + (coloredCount(count) - 1) * FILL_GAP + FIELD_LAG;\n const reflow = field + FIELD_WIPE + HOLD;\n const settled = reflow + (TRACK_COUNT - 1) * TRACK_GAP + TRACK_SLIDE;\n const expand = settled - EXPAND_LEAD;\n const end = expand + (SIDES.length - 1) * SIDE_GAP + SIDE_PUSH;\n return { lines: LINE_START, fill, field, reflow, expand, end };\n}\n\nexport const mondrianSplitLength = getMondrianSplitTimeline().end;\n\nexport function getMondrianSplitDuration({\n speed = 1,\n splits = mondrianSplitDefaults.splits,\n}: Pick<MondrianSplitProps, \"speed\" | \"splits\"> = {}) {\n const rate = Math.max(0, finite(speed, 1));\n const frames = getMondrianSplitTimeline({ splits }).end + TAIL;\n return rate === 0 ? 1 : Math.max(1, Math.ceil(frames / rate));\n}\n\nexport function getMondrianSplitLayout({\n seed = mondrianSplitDefaults.seed,\n splits = mondrianSplitDefaults.splits,\n lineWeight = mondrianSplitDefaults.lineWeight,\n expandCell = mondrianSplitDefaults.expandCell,\n width = 1280,\n height = 720,\n}: MondrianSplitOptions = {}) {\n const w = Math.max(1, finite(width, 1280));\n const h = Math.max(1, finite(height, 720));\n const short = Math.min(w, h);\n const weight = clamp(finite(lineWeight, 14), 2, 48) * (short / 720);\n const count = splitCount(splits);\n const timeline = getMondrianSplitTimeline({ splits: count });\n const salt = Math.round(finite(seed, mondrianSplitDefaults.seed));\n const roll = (name: string) => random(`mondrian-split-${salt}-${name}`);\n const minSide = Math.max(short * 0.1, weight * 3);\n const snap = short * 0.045;\n const align = short * 0.075;\n const gap = Math.max(short * 0.07, weight * 2.5);\n const minMove = short * 0.06;\n const overscan = weight + short * 0.04;\n const nodes: GridNode[] = [\n {\n box: { x0: 0, y0: 0, x1: w, y1: h },\n bounds: { left: -1, top: -1, right: -1, bottom: -1 },\n line: -1,\n },\n ];\n const cuts: GridCut[] = [];\n\n const lean = (\n box: MondrianSplitBox,\n ratio: number,\n name: string,\n ): MondrianSplitAxis => {\n const wide = extent(box, \"x\");\n const tall = extent(box, \"y\");\n if (wide > tall * ratio) return \"x\";\n if (tall > wide * ratio) return \"y\";\n return roll(name) < 0.5 ? \"x\" : \"y\";\n };\n\n const cut = (node: number, axis: MondrianSplitAxis, position: number) => {\n const id = cuts.length;\n const { box, bounds: edges } = nodes[node];\n const vertical = axis === \"x\";\n nodes[node].line = id;\n cuts.push({ axis, position, node });\n nodes.push(\n {\n box: vertical ? { ...box, x1: position } : { ...box, y1: position },\n bounds: vertical ? { ...edges, right: id } : { ...edges, bottom: id },\n line: -1,\n },\n {\n box: vertical ? { ...box, x0: position } : { ...box, y0: position },\n bounds: vertical ? { ...edges, left: id } : { ...edges, top: id },\n line: -1,\n },\n );\n };\n\n const snapTo = (axis: MondrianSplitAxis, position: number) => {\n let best = position;\n let distance = snap;\n for (const line of cuts) {\n const offset = Math.abs(line.position - position);\n if (line.axis === axis && offset < distance) {\n best = line.position;\n distance = offset;\n }\n }\n return best;\n };\n\n const nearMiss = (axis: MondrianSplitAxis, position: number) =>\n cuts.some(\n (line) =>\n line.axis === axis &&\n line.position !== position &&\n Math.abs(line.position - position) < snap,\n );\n\n const tryCut = (\n node: number,\n axis: MondrianSplitAxis,\n fraction: number,\n strict: boolean,\n ) => {\n const { box } = nodes[node];\n const low = lowEdge(box, axis);\n const length = extent(box, axis);\n if (length < minSide * 2) return false;\n const position = clamp(\n snapTo(axis, low + length * fraction),\n low + minSide,\n low + length - minSide,\n );\n if (strict && nearMiss(axis, position)) return false;\n cut(node, axis, position);\n return true;\n };\n\n let anchor = -1;\n const longAxis = lean(nodes[0].box, 1.05, \"square\");\n const rootAxis = roll(\"root-axis\") < 0.75 ? longAxis : other(longAxis);\n const rootFraction =\n roll(\"root-side\") < 0.5\n ? mix(0.3, 0.4, roll(\"root-at\"))\n : mix(0.6, 0.7, roll(\"root-at\"));\n if (tryCut(0, rootAxis, rootFraction, false)) {\n const share = mix(0.6, 0.76, roll(\"anchor-at\"));\n const anchorLow = roll(\"anchor-side\") < 0.5;\n const big = rootFraction < 0.5 ? 2 : 1;\n if (tryCut(big, other(rootAxis), anchorLow ? share : 1 - share, false)) {\n anchor = anchorLow ? nodes.length - 2 : nodes.length - 1;\n }\n }\n\n const splittable = (index: number) => {\n const { box, line } = nodes[index];\n return (\n line === -1 &&\n index !== anchor &&\n Math.max(extent(box, \"x\"), extent(box, \"y\")) >= minSide * 2\n );\n };\n\n const budget = count * 24;\n for (let attempt = 0; cuts.length < count && attempt < budget; attempt++) {\n const tag = `${cuts.length}-${attempt}`;\n const pool = nodes.flatMap((_, index) =>\n splittable(index) ? [index] : [],\n );\n if (pool.length === 0) break;\n const weights = pool.map((index) => area(nodes[index].box) ** 1.2);\n const node = pool[choose(weights, roll(`${tag}-cell`))];\n const { box } = nodes[node];\n const preferred = lean(box, 1.25, `${tag}-axis`);\n const fits = extent(box, preferred) >= minSide * 2;\n const at = roll(`${tag}-at`);\n const fraction = at < 0.5 ? 0.28 + at * 0.34 : 0.55 + (at - 0.5) * 0.34;\n tryCut(node, fits ? preferred : other(preferred), fraction, true);\n }\n\n const byPriority = (a: number, b: number) =>\n Number(a === anchor) - Number(b === anchor) ||\n area(nodes[b].box) - area(nodes[a].box);\n const fallback = () => {\n const pool = nodes.flatMap((node, index) =>\n node.line === -1 ? [index] : [],\n );\n pool.sort(byPriority);\n for (const strict of [true, false]) {\n for (const node of pool) {\n const { box } = nodes[node];\n const first: MondrianSplitAxis =\n extent(box, \"x\") >= extent(box, \"y\") ? \"x\" : \"y\";\n for (const axis of [first, other(first)]) {\n for (const fraction of FALLBACK_CUTS) {\n if (tryCut(node, axis, fraction, strict)) return true;\n }\n }\n }\n }\n return false;\n };\n while (cuts.length < count) {\n if (!fallback()) break;\n }\n\n const trackKeys: string[] = [];\n const lines = cuts.map((draft, id) => {\n const key = `${draft.axis}:${draft.position}`;\n if (!trackKeys.includes(key)) trackKeys.push(key);\n const { bounds } = nodes[draft.node];\n const vertical = draft.axis === \"x\";\n const near = vertical ? bounds.top : bounds.left;\n const far = vertical ? bounds.bottom : bounds.right;\n return {\n id,\n axis: draft.axis,\n position: draft.position,\n node: draft.node,\n track: trackKeys.indexOf(key),\n lowBound: vertical ? bounds.left : bounds.top,\n highBound: vertical ? bounds.right : bounds.bottom,\n fromEnd: near === far ? roll(`draw-${id}`) < 0.5 : far < near,\n start: LINE_START + id * LINE_GAP,\n };\n });\n\n const leaves = nodes.flatMap((node, index) =>\n node.line === -1 ? [index] : [],\n );\n const ranked = [...leaves].sort(\n (a, b) => area(nodes[b].box) - area(nodes[a].box) || a - b,\n );\n const pick = clamp(Math.round(finite(expandCell, 0)), 0, ranked.length - 1);\n const target = ranked[pick];\n const targetBox = nodes[target].box;\n\n const others = leaves.filter((index) => index !== target);\n const largest = Math.max(1, ...others.map((index) => area(nodes[index].box)));\n const candidates = others\n .map((index) => ({\n index,\n score:\n roll(`fill-${index}`) +\n (touches(nodes[index].box, targetBox) ? 0.45 : 0) +\n (0.3 * area(nodes[index].box)) / largest,\n }))\n .sort((a, b) => a.score - b.score);\n const painted: { index: number; slot: MondrianSplitSlot }[] = [];\n const quota = Math.min(coloredCount(count), candidates.length);\n for (let order = 0; order < quota; order++) {\n const slot = SLOTS[order];\n const free = candidates.filter(\n ({ index }) => !painted.some((cell) => cell.index === index),\n );\n const clean = free.find(\n ({ index }) =>\n !painted.some(\n (cell) =>\n cell.slot === slot &&\n touches(nodes[cell.index].box, nodes[index].box),\n ) && !(slot === \"red\" && touches(nodes[index].box, targetBox)),\n );\n const choice = clean ?? free[0];\n if (choice) painted.push({ index: choice.index, slot });\n }\n\n const wipeOf = (index: number): GridWipe => {\n const { box } = nodes[index];\n const axis = extent(box, \"x\") >= extent(box, \"y\") ? \"x\" : \"y\";\n const middle = axis === \"x\" ? box.x0 + box.x1 : box.y0 + box.y1;\n return { axis, fromEnd: middle < (axis === \"x\" ? w : h) };\n };\n const diagonal = (index: number) => {\n const { box } = nodes[index];\n return (box.x0 + box.x1) / w + (box.y0 + box.y1) / h;\n };\n const fills = [...painted]\n .sort((a, b) => diagonal(a.index) - diagonal(b.index))\n .map((cell, order) => ({\n node: cell.index,\n slot: cell.slot,\n ...wipeOf(cell.index),\n start: timeline.fill + order * FILL_GAP,\n }));\n const field = { node: target, ...wipeOf(target), start: timeline.field };\n\n const tracks = trackKeys.map((_, track) => {\n const members = lines.filter((line) => line.track === track);\n return {\n track,\n axis: members[0].axis,\n position: members[0].position,\n length: members.reduce(\n (sum, line) => sum + extent(nodes[line.node].box, other(line.axis)),\n 0,\n ),\n };\n });\n const reserveLow = lines.map((line) => line.position);\n const reserveHigh = lines.map((line) => line.position);\n const limits = (track: number) => {\n let low = Number.NEGATIVE_INFINITY;\n let high = Number.POSITIVE_INFINITY;\n for (const line of lines) {\n if (line.track === track) {\n const size = line.axis === \"x\" ? w : h;\n const floor = line.lowBound === -1 ? 0 : reserveHigh[line.lowBound];\n const ceiling =\n line.highBound === -1 ? size : reserveLow[line.highBound];\n low = Math.max(low, floor + gap);\n high = Math.min(high, ceiling - gap);\n } else {\n if (line.lowBound !== -1 && lines[line.lowBound].track === track) {\n high = Math.min(high, reserveLow[line.id] - gap);\n }\n if (line.highBound !== -1 && lines[line.highBound].track === track) {\n low = Math.max(low, reserveHigh[line.id] + gap);\n }\n }\n }\n return { low, high };\n };\n const moves: GridMove[] = [];\n const settledAt = (track: number, position: number) =>\n moves.find((move) => move.track === track)?.to ?? position;\n const borders = (side: MondrianSplitSide, track: number) => {\n const id = nodes[target].bounds[side];\n return id !== -1 && lines[id].track === track;\n };\n const inward = (track: number) => {\n if (borders(\"left\", track) || borders(\"top\", track)) return 1;\n if (borders(\"right\", track) || borders(\"bottom\", track)) return -1;\n return 0;\n };\n const heading = (track: number, down: number, up: number) => {\n const squeeze = inward(track);\n if (squeeze !== 0) {\n return (squeeze > 0 ? up : down) >= minMove ? squeeze : 0;\n }\n if (down < minMove) return up >= minMove ? 1 : 0;\n if (up < minMove) return -1;\n return roll(`track-way-${track}`) < up / (up + down) ? 1 : -1;\n };\n const order = tracks\n .map((track) => ({\n ...track,\n weight: track.length * (0.6 + 0.8 * roll(`track-${track.track}`)),\n }))\n .sort((a, b) => b.weight - a.weight);\n for (const track of order) {\n if (moves.length >= TRACK_COUNT) break;\n const { low, high } = limits(track.track);\n const down = (track.position - low) / (1 + RESERVE);\n const up = (high - track.position) / (1 + RESERVE);\n const direction = heading(track.track, down, up);\n if (direction === 0) continue;\n const span = track.axis === \"x\" ? w : h;\n const room = Math.min(direction > 0 ? up : down, span * 0.2);\n const stride = mix(0.6, 0.95, roll(`track-far-${track.track}`));\n const reach = track.position + direction * Math.max(minMove, room * stride);\n const nearest = tracks\n .filter((rival) => rival.axis === track.axis)\n .filter((rival) => rival.track !== track.track)\n .map((rival) => settledAt(rival.track, rival.position))\n .reduce(\n (best, position) =>\n Math.abs(position - reach) < Math.abs(best - reach) ? position : best,\n Number.POSITIVE_INFINITY,\n );\n const to = Math.abs(nearest - reach) < align ? nearest : reach;\n const margin = Math.abs(to - track.position) * RESERVE;\n if (\n Math.abs(to - track.position) < minMove ||\n to - margin < low ||\n to + margin > high\n ) {\n continue;\n }\n for (const line of lines) {\n if (line.track === track.track) {\n reserveLow[line.id] = Math.min(track.position, to) - margin;\n reserveHigh[line.id] = Math.max(track.position, to) + margin;\n }\n }\n moves.push({\n track: track.track,\n from: track.position,\n to,\n start: timeline.reflow + moves.length * TRACK_GAP,\n });\n }\n\n const settled = lines.map((line) => settledAt(line.track, line.position));\n const home = placeBoxes(lines, settled, w, h)[target];\n const travel: Record<MondrianSplitSide, number> = {\n left: home.x0 + overscan,\n top: home.y0 + overscan,\n right: w + overscan - home.x1,\n bottom: h + overscan - home.y1,\n };\n const ranking = [...SIDES].sort((a, b) => travel[a] - travel[b]);\n const side = (name: MondrianSplitSide) => {\n const across = name === \"left\" || name === \"right\" ? \"x\" : \"y\";\n const share = (extent(home, across) * DIP_SHARE) / travel[name];\n return {\n start: timeline.expand + ranking.indexOf(name) * SIDE_GAP,\n dip: nodes[target].bounds[name] === -1 ? 0 : Math.min(DIP, share),\n };\n };\n\n return {\n width: w,\n height: h,\n weight,\n minSide,\n gap,\n minMove,\n align,\n overscan,\n timeline,\n nodes,\n lines,\n leaves,\n target,\n fills,\n field,\n moves,\n sides: {\n left: side(\"left\"),\n top: side(\"top\"),\n right: side(\"right\"),\n bottom: side(\"bottom\"),\n },\n };\n}\n\nexport type MondrianSplitLayout = ReturnType<typeof getMondrianSplitLayout>;\n\nexport function getMondrianSplitState(\n frame: number,\n layout: MondrianSplitLayout = getMondrianSplitLayout(),\n) {\n const time = Math.max(0, finite(frame, 0));\n const { width, height, weight, overscan } = layout;\n const positions = layout.lines.map((line) => {\n const move = layout.moves.find((item) => item.track === line.track);\n if (!move) return line.position;\n const amount = slide(progress(time, move.start, TRACK_SLIDE));\n return line.position + (move.to - move.from) * amount;\n });\n const boxes = placeBoxes(layout.lines, positions, width, height);\n const home = boxes[layout.target];\n const reach = (name: MondrianSplitSide) => {\n const { start, dip } = layout.sides[name];\n return push(progress(time, start, SIDE_PUSH), dip);\n };\n const mapX = stretch(\n home.x0,\n home.x1,\n mix(home.x0, -overscan, reach(\"left\")),\n mix(home.x1, width + overscan, reach(\"right\")),\n -overscan,\n width + overscan,\n );\n const mapY = stretch(\n home.y0,\n home.y1,\n mix(home.y0, -overscan, reach(\"top\")),\n mix(home.y1, height + overscan, reach(\"bottom\")),\n -overscan,\n height + overscan,\n );\n const project = (box: MondrianSplitBox): MondrianSplitBox => ({\n x0: mapX(box.x0),\n y0: mapY(box.y0),\n x1: mapX(box.x1),\n y1: mapY(box.y1),\n });\n\n const lines = layout.lines.flatMap((line) => {\n const drawn = drawEase(progress(time, line.start, LINE_DRAW));\n if (drawn <= 0) return [];\n const box = boxes[line.node];\n const vertical = line.axis === \"x\";\n const low = vertical ? box.y0 : box.x0;\n const high = vertical ? box.y1 : box.x1;\n const along = vertical ? mapY : mapX;\n const start = along(line.fromEnd ? high - (high - low) * drawn : low);\n const end = along(line.fromEnd ? high : low + (high - low) * drawn);\n const position = (vertical ? mapX : mapY)(positions[line.id]);\n const half = weight / 2;\n const length = end - start;\n const rect: MondrianSplitRect = vertical\n ? { x: position - half, y: start, width: weight, height: length }\n : { x: start, y: position - half, width: length, height: weight };\n return inFrame(rect, width, height)\n ? [{ id: line.id, axis: line.axis, position, drawn, ...rect }]\n : [];\n });\n\n const fills = layout.fills.flatMap((fill) => {\n const amount = wipeEase(progress(time, fill.start, FILL_WIPE));\n if (amount <= 0) return [];\n const rect = wipe(project(boxes[fill.node]), fill, amount);\n return inFrame(rect, width, height)\n ? [{ id: fill.node, slot: fill.slot, ...rect }]\n : [];\n });\n\n const reveal = wipeEase(progress(time, layout.field.start, FIELD_WIPE));\n const field = reveal > 0 ? wipe(project(home), layout.field, reveal) : null;\n\n return {\n time,\n lines,\n fills,\n field: field && inFrame(field, width, height) ? field : null,\n cells: layout.leaves.map((id) => ({ id, ...project(boxes[id]) })),\n };\n}\n\nexport type MondrianSplitState = ReturnType<typeof getMondrianSplitState>;\n\nexport function getMondrianSplitClip(\n field: MondrianSplitRect | null,\n width: number,\n height: number,\n) {\n if (!field) return \"inset(50%)\";\n const top = percent(field.y, height);\n const right = percent(width - field.x - field.width, width);\n const bottom = percent(height - field.y - field.height, height);\n const left = percent(field.x, width);\n return `inset(${top} ${right} ${bottom} ${left})`;\n}\n\nexport function MondrianSplit({\n children,\n seed = mondrianSplitDefaults.seed,\n splits = mondrianSplitDefaults.splits,\n lineWeight = mondrianSplitDefaults.lineWeight,\n expandCell = mondrianSplitDefaults.expandCell,\n lineColor = mondrianSplitDefaults.lineColor,\n redColor = mondrianSplitDefaults.redColor,\n yellowColor = mondrianSplitDefaults.yellowColor,\n blueColor = mondrianSplitDefaults.blueColor,\n fieldColor = mondrianSplitDefaults.fieldColor,\n speed = 1,\n className,\n}: MondrianSplitProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const layout = useMemo(\n () =>\n getMondrianSplitLayout({\n seed,\n splits,\n lineWeight,\n expandCell,\n width,\n height,\n }),\n [seed, splits, lineWeight, expandCell, width, height],\n );\n const time = frame * (30 / fps) * Math.max(0, finite(speed, 1));\n const state = getMondrianSplitState(time, layout);\n const palette: Record<MondrianSplitSlot, string> = {\n red: redColor,\n yellow: yellowColor,\n blue: blueColor,\n };\n const viewBox = `0 0 ${width} ${height}`;\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={viewBox}\n preserveAspectRatio=\"none\"\n aria-hidden=\"true\"\n style={layer}\n >\n {state.fills.map((fill) => (\n <rect\n key={fill.id}\n x={fill.x}\n y={fill.y}\n width={fill.width}\n height={fill.height}\n fill={palette[fill.slot]}\n />\n ))}\n {state.field ? (\n <rect\n x={state.field.x}\n y={state.field.y}\n width={state.field.width}\n height={state.field.height}\n fill={fieldColor}\n />\n ) : null}\n </svg>\n {children == null ? null : (\n <div\n style={{\n ...layer,\n clipPath: getMondrianSplitClip(state.field, width, height),\n }}\n >\n {children}\n </div>\n )}\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={viewBox}\n preserveAspectRatio=\"none\"\n role=\"img\"\n aria-label=\"De Stijl grid\"\n style={layer}\n >\n {state.lines.map((line) => (\n <rect\n key={line.id}\n x={line.x}\n y={line.y}\n width={line.width}\n height={line.height}\n fill={lineColor}\n />\n ))}\n </svg>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/mondrian-split.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/outline-trace.json b/registry-artifacts/outline-trace.jsonnew file mode 100644index 00000000..2f063649--- /dev/null+++ b/registry-artifacts/outline-trace.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "outline-trace",+ "title": "Outline Trace",+ "description": "Every glyph contour draws itself as a stroke, letter by letter, then the fill wipes up inside each letter and the stroke fades into it.",+ "dependencies": ["remotion", "opentype.js"],+ "files": [+ {+ "path": "registry/remocn/outline-trace/index.tsx",+ "content": "\"use client\";\n\nimport { type Font, parse } from \"opentype.js\";\nimport { useEffect, useId, useState } from \"react\";\nimport {\n continueRender,\n delayRender,\n Easing,\n interpolate,\n useCurrentFrame,\n useVideoConfig,\n} from \"remotion\";\n\nexport interface OutlineTraceProps {\n text?: string;\n fontUrl?: string;\n fontSize?: number;\n color?: string;\n strokeColor?: string;\n strokeWidth?: number;\n stagger?: number;\n fill?: boolean;\n keepStroke?: boolean;\n speed?: number;\n className?: string;\n}\n\n/** Static Inter ExtraBold (800) from Google Fonts. */\nexport const interExtraBoldTtf =\n \"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuDyYMZg.ttf\";\n\nexport const outlineTraceDefaults = {\n text: \"Outline\",\n fontUrl: interExtraBoldTtf,\n fontSize: 150,\n color: \"#fafafa\",\n strokeColor: \"\",\n strokeWidth: 2.5,\n stagger: 3,\n fill: true,\n keepStroke: false,\n speed: 1,\n} satisfies Required<Omit<OutlineTraceProps, \"className\">>;\n\n/** Per-letter beats on the 30 fps clock, relative to the letter's start. */\nexport const outlineTraceTiming = {\n outer: [0, 18],\n counter: [4, 18],\n fill: [14, 26],\n} as const;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\nconst easeOutCubic = Easing.out(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nexport function getOutlineTraceTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\nexport interface OutlineTraceLetterState {\n /** Trim progress of the outer contours, 0..1. */\n outer: number;\n /** Trim progress of the counters, 0..1. */\n counter: number;\n /** Share of the glyph box the fill has risen through, 0..1. */\n fill: number;\n}\n\nexport function getOutlineTraceLetter(\n t: number,\n index: number,\n stagger = outlineTraceDefaults.stagger,\n): OutlineTraceLetterState {\n const u = t - index * Math.max(0, finite(stagger, 3));\n const { outer, counter, fill } = outlineTraceTiming;\n return {\n outer: interpolate(u, [...outer], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n counter: interpolate(u, [...counter], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n fill: interpolate(u, [...fill], [0, 1], { ...CLAMP, easing: easeOutCubic }),\n };\n}\n\n/** Frame where the last of `count` letters has filled. */\nexport function getOutlineTraceLength(\n count: number,\n stagger = outlineTraceDefaults.stagger,\n) {\n const last = Math.max(0, count - 1) * Math.max(0, finite(stagger, 3));\n return Math.ceil(last + outlineTraceTiming.fill[1]);\n}\n\nexport interface PathCommand {\n type: string;\n x?: number;\n y?: number;\n x1?: number;\n y1?: number;\n x2?: number;\n y2?: number;\n}\n\nexport interface Box {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n}\n\nexport interface OutlineContour {\n d: string;\n box: Box;\n /** True for a hole inside another contour of the same glyph. */\n counter: boolean;\n}\n\nconst fmt = (n: number) => Number(n.toFixed(2));\n\n/**\n * Splits glyph path commands into closed contours and marks the counters:\n * contours whose box lies inside another contour's box.\n */\nexport function getOutlineContours(commands: readonly PathCommand[]) {\n const raw: { d: string; box: Box }[] = [];\n let d = \"\";\n let box: Box | null = null;\n const grow = (x = 0, y = 0) => {\n if (!box) box = { x0: x, y0: y, x1: x, y1: y };\n else {\n box.x0 = Math.min(box.x0, x);\n box.y0 = Math.min(box.y0, y);\n box.x1 = Math.max(box.x1, x);\n box.y1 = Math.max(box.y1, y);\n }\n };\n const close = () => {\n if (d && box) raw.push({ d: `${d}Z`, box });\n d = \"\";\n box = null;\n };\n for (const c of commands) {\n if (c.type === \"M\") {\n close();\n d = `M${fmt(c.x ?? 0)} ${fmt(c.y ?? 0)}`;\n grow(c.x, c.y);\n } else if (c.type === \"L\") {\n d += `L${fmt(c.x ?? 0)} ${fmt(c.y ?? 0)}`;\n grow(c.x, c.y);\n } else if (c.type === \"Q\") {\n d += `Q${fmt(c.x1 ?? 0)} ${fmt(c.y1 ?? 0)} ${fmt(c.x ?? 0)} ${fmt(c.y ?? 0)}`;\n grow(c.x1, c.y1);\n grow(c.x, c.y);\n } else if (c.type === \"C\") {\n d += `C${fmt(c.x1 ?? 0)} ${fmt(c.y1 ?? 0)} ${fmt(c.x2 ?? 0)} ${fmt(c.y2 ?? 0)} ${fmt(c.x ?? 0)} ${fmt(c.y ?? 0)}`;\n grow(c.x1, c.y1);\n grow(c.x2, c.y2);\n grow(c.x, c.y);\n } else if (c.type === \"Z\") {\n close();\n }\n }\n close();\n const inside = (a: Box, b: Box) =>\n a !== b && a.x0 >= b.x0 && a.y0 >= b.y0 && a.x1 <= b.x1 && a.y1 <= b.y1;\n return raw.map(\n (c): OutlineContour => ({\n ...c,\n counter: raw.some((other) => inside(c.box, other.box)),\n }),\n );\n}\n\nexport interface OutlineGlyph {\n contours: OutlineContour[];\n box: Box | null;\n}\n\n/**\n * Lays out `text` in reference px with the baseline at y = 0. Glyphs are\n * looked up per character: full shaping runs GSUB lookups that opentype.js\n * does not support in every font.\n */\nexport function layoutOutlineGlyphs(\n font: Font,\n text: string,\n fontSize: number,\n) {\n const scale = fontSize / font.unitsPerEm;\n const glyphs = Array.from(text).map((char) => font.charToGlyph(char));\n let x = 0;\n const letters: OutlineGlyph[] = glyphs.map((glyph, i) => {\n if (i > 0) x += font.getKerningValue(glyphs[i - 1], glyph) * scale;\n const contours = getOutlineContours(glyph.getPath(x, 0, fontSize).commands);\n x += (glyph.advanceWidth ?? 0) * scale;\n const box = contours.reduce<Box | null>(\n (acc, c) =>\n acc\n ? {\n x0: Math.min(acc.x0, c.box.x0),\n y0: Math.min(acc.y0, c.box.y0),\n x1: Math.max(acc.x1, c.box.x1),\n y1: Math.max(acc.y1, c.box.y1),\n }\n : { ...c.box },\n null,\n );\n return { contours, box };\n });\n const os2 = font.tables.os2 as { sCapHeight?: number } | undefined;\n const capHeight =\n ((os2?.sCapHeight ?? font.unitsPerEm * 0.7) * fontSize) / font.unitsPerEm;\n return { letters, width: x, capHeight };\n}\n\nconst fontCache = new Map<string, Promise<Font>>();\n\nfunction loadOutlineFont(url: string) {\n let pending = fontCache.get(url);\n if (!pending) {\n pending = fetch(url)\n .then((res) => res.arrayBuffer())\n .then((buffer) => parse(buffer));\n fontCache.set(url, pending);\n pending.catch(() => fontCache.delete(url));\n }\n return pending;\n}\n\nfunction useOutlineFont(url: string) {\n const [font, setFont] = useState<Font | null>(null);\n\n useEffect(() => {\n const handle = delayRender(`outline-trace: loading ${url}`);\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n continueRender(handle);\n };\n loadOutlineFont(url).then((parsed) => {\n if (!released) setFont(parsed);\n release();\n }, release);\n return release;\n }, [url]);\n\n return font;\n}\n\nexport function OutlineTrace({\n text = outlineTraceDefaults.text,\n fontUrl = outlineTraceDefaults.fontUrl,\n fontSize = outlineTraceDefaults.fontSize,\n color = outlineTraceDefaults.color,\n strokeColor = outlineTraceDefaults.strokeColor,\n strokeWidth = outlineTraceDefaults.strokeWidth,\n stagger = outlineTraceDefaults.stagger,\n fill = outlineTraceDefaults.fill,\n keepStroke = outlineTraceDefaults.keepStroke,\n speed = outlineTraceDefaults.speed,\n className,\n}: OutlineTraceProps) {\n const frame = useCurrentFrame();\n const { fps, width, height } = useVideoConfig();\n const id = `outline-trace-${useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`;\n const font = useOutlineFont(fontUrl);\n if (!font) return null;\n\n const unit = height / 720;\n const t = getOutlineTraceTime(frame, { fps, speed });\n const layout = layoutOutlineGlyphs(font, text, fontSize);\n const originX = (width - layout.width * unit) / 2;\n const baseline = (height + layout.capHeight * unit) / 2;\n const stroke = strokeColor || color;\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n style={{ display: \"block\" }}\n >\n <g transform={`translate(${originX} ${baseline}) scale(${unit})`}>\n <filter id={`${id}-erode`}>\n <feMorphology operator=\"erode\" radius={strokeWidth / 2} />\n </filter>\n {layout.letters.map((letter, i) => {\n if (!letter.box) return null;\n const state = getOutlineTraceLetter(t, i, stagger);\n const box = letter.box;\n const tall = box.y1 - box.y0 + 2 * strokeWidth;\n const rise = tall * (fill ? state.fill : 0);\n const strokeOpacity = fill && !keepStroke ? 1 - state.fill : 1;\n const whole = letter.contours.map((c) => c.d).join(\"\");\n const margin = 4 * strokeWidth;\n return (\n <g key={i}>\n {/* Static instances of variable fonts keep overlapping\n contours (the bar of a t crosses its stem). The mask hides\n stroke that runs inside the glyph's filled silhouette. */}\n <mask\n id={`${id}-mask-${i}`}\n maskUnits=\"userSpaceOnUse\"\n x={box.x0 - margin}\n y={box.y0 - margin}\n width={box.x1 - box.x0 + 2 * margin}\n height={box.y1 - box.y0 + 2 * margin}\n >\n <rect\n x={box.x0 - margin}\n y={box.y0 - margin}\n width={box.x1 - box.x0 + 2 * margin}\n height={box.y1 - box.y0 + 2 * margin}\n fill=\"#ffffff\"\n />\n <path d={whole} fill=\"#000000\" filter={`url(#${id}-erode)`} />\n </mask>\n {fill && state.fill > 0 ? (\n <>\n <clipPath id={`${id}-${i}`}>\n <rect\n x={box.x0 - strokeWidth}\n y={box.y1 + strokeWidth - rise}\n width={box.x1 - box.x0 + 2 * strokeWidth}\n height={rise}\n />\n </clipPath>\n <path\n d={whole}\n fill={color}\n clipPath={`url(#${id}-${i})`}\n />\n </>\n ) : null}\n {strokeOpacity > 0 ? (\n <g mask={`url(#${id}-mask-${i})`}>\n {letter.contours.map((contour, k) => {\n const progress = contour.counter\n ? state.counter\n : state.outer;\n if (progress <= 0) return null;\n return (\n <path\n key={k}\n d={contour.d}\n pathLength={1}\n fill=\"none\"\n stroke={stroke}\n strokeWidth={strokeWidth}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeDasharray=\"1 1\"\n strokeDashoffset={1 - progress}\n opacity={strokeOpacity}\n />\n );\n })}\n </g>\n ) : null}\n </g>\n );\n })}\n </g>\n </svg>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/outline-trace.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/path-ride.json b/registry-artifacts/path-ride.jsonnew file mode 100644index 00000000..83318d3e--- /dev/null+++ b/registry-artifacts/path-ride.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "path-ride",+ "title": "Path Ride",+ "description": "A line draws itself along a curve with the text riding behind its head, then the curve pulls taut and the text settles on a straight, centered baseline.",+ "dependencies": ["remotion", "@remotion/google-fonts", "@remotion/paths"],+ "files": [+ {+ "path": "registry/remocn/path-ride/index.tsx",+ "content": "\"use client\";\n\nimport { loadFont } from \"@remotion/google-fonts/Inter\";\nimport {\n getLength,\n getPointAtLength,\n getTangentAtLength,\n} from \"@remotion/paths\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport {\n continueRender,\n delayRender,\n Easing,\n interpolate,\n useCurrentFrame,\n useVideoConfig,\n} from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\nexport interface PathRideProps {\n text?: string;\n path?: string;\n fontSize?: number;\n fontWeight?: number;\n fontFamily?: string;\n color?: string;\n lineColor?: string;\n lineWidth?: number;\n speed?: number;\n className?: string;\n}\n\n/** An S-curve across a 1280×720 frame. */\nexport const pathRideDefaultPath =\n \"M 120 560 C 360 120 560 120 640 360 S 920 600 1160 160\";\n\nexport const pathRideDefaults = {\n text: \"Follow the line\",\n path: pathRideDefaultPath,\n fontSize: 44,\n fontWeight: 700,\n fontFamily: INTER,\n color: \"#fafafa\",\n lineColor: \"#D97757\",\n lineWidth: 3,\n speed: 1,\n} satisfies Required<Omit<PathRideProps, \"className\">>;\n\n/** Beats on the 30 fps clock. */\nexport const pathRideTiming = {\n draw: [0, 40],\n straighten: [50, 68],\n erase: [52, 70],\n} as const;\n\n/** Gap between the head and the last letter, in em. */\nconst LEAD = 0.3;\n/** Letters fade in over this much arc length, in em. */\nconst FADE_IN = 0.5;\n/** Extra lift of the baseline above the line, in em. */\nconst LIFT = 0.08;\n/** Samples along the path; the line and the letters read positions from them. */\nconst SAMPLES = 400;\nconst MEASURE_SIZE = 100;\n/** Inter's baseline and cap height in a `line-height: 1` box, until measured. */\nconst INTER_METRICS = { baseline: 0.8637, capHeight: 0.7275 };\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nexport function getPathRideTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\n/** Arc length drawn so far. */\nexport function getPathRideHead(t: number, length: number) {\n return interpolate(t, [...pathRideTiming.draw], [0, length], {\n ...CLAMP,\n easing: easeInOutCubic,\n });\n}\n\n/** Arc length erased from the start. */\nexport function getPathRideTail(t: number, length: number) {\n return interpolate(t, [...pathRideTiming.erase], [0, length], {\n ...CLAMP,\n easing: easeInOutCubic,\n });\n}\n\n/** How far the curve has pulled straight, 0..1. */\nexport function getPathRideStraighten(t: number) {\n return interpolate(t, [...pathRideTiming.straighten], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n });\n}\n\n/** Frame where the line has erased and the text rests on its baseline. */\nexport const pathRideLength = Math.max(\n pathRideTiming.straighten[1],\n pathRideTiming.erase[1],\n);\n\n/** Letter centers from the text start, and the total width. */\nexport function getPathRideCenters(advances: readonly number[]) {\n let x = 0;\n const centers = advances.map((a) => {\n const c = x + a / 2;\n x += a;\n return c;\n });\n return { centers, width: x };\n}\n\n/**\n * Arc length of a letter's center: it trails the head by the lead plus the\n * text after it, so the last letter follows the head most closely.\n */\nexport function getPathRideArc(\n head: number,\n center: number,\n width: number,\n fontSize: number,\n) {\n return head - LEAD * fontSize - (width - center);\n}\n\n/** Opacity of a letter from how far onto the curve it has come. */\nexport function getPathRideFade(arc: number, fontSize: number) {\n return Math.min(1, Math.max(0, arc / (FADE_IN * fontSize)));\n}\n\nexport interface Point {\n x: number;\n y: number;\n}\n\nexport interface PathSamples {\n length: number;\n points: Point[];\n tangents: Point[];\n}\n\n/** Points and unit tangents at evenly spaced arc lengths along `path`. */\nexport function samplePath(path: string, count = SAMPLES): PathSamples {\n const length = getLength(path);\n const n = Math.max(2, Math.round(count));\n const points: Point[] = [];\n const tangents: Point[] = [];\n for (let i = 0; i < n; i++) {\n const at = (length * i) / (n - 1);\n // Both can come back null on a degenerate path; reuse the last sample.\n const p = getPointAtLength(path, at) ?? points[i - 1] ?? { x: 0, y: 0 };\n const tangent = getTangentAtLength(path, at) ??\n tangents[i - 1] ?? { x: 1, y: 0 };\n points.push({ x: p.x, y: p.y });\n tangents.push({ x: tangent.x, y: tangent.y });\n }\n return { length, points, tangents };\n}\n\n/** Position and unit tangent at arc length `s`, clamped to the path. */\nexport function getPathSample(samples: PathSamples, s: number) {\n const n = samples.points.length;\n const u = samples.length > 0 ? (s / samples.length) * (n - 1) : 0;\n const i = Math.min(n - 2, Math.max(0, Math.floor(u)));\n const f = Math.min(1, Math.max(0, u - i));\n const a = samples.points[i];\n const b = samples.points[i + 1];\n const ta = samples.tangents[i];\n const tb = samples.tangents[i + 1];\n const tx = ta.x + (tb.x - ta.x) * f;\n const ty = ta.y + (tb.y - ta.y) * f;\n const norm = Math.hypot(tx, ty) || 1;\n return {\n x: a.x + (b.x - a.x) * f,\n y: a.y + (b.y - a.y) * f,\n tx: tx / norm,\n ty: ty / norm,\n };\n}\n\nexport interface PathRideStraight {\n /** Arc length that lands on the text's left edge. */\n start: number;\n /** Reference x of the text's left edge on the straight baseline. */\n left: number;\n /** Reference y of the straight baseline. */\n baseline: number;\n}\n\nexport interface PathRidePose {\n x: number;\n y: number;\n angle: number;\n}\n\n/**\n * A point of the path pulled `k` of the way from the curve to the straight\n * baseline, lifted `lift` along its normal. Arc length maps to x one to one,\n * so the text keeps its spacing while the curve pulls taut.\n */\nexport function getPathRidePoint(\n samples: PathSamples,\n s: number,\n k: number,\n straight: PathRideStraight,\n lift = 0,\n): PathRidePose {\n const p = getPathSample(samples, s);\n const x = p.x + (straight.left + (s - straight.start) - p.x) * k;\n const y = p.y + (straight.baseline - p.y) * k;\n const tx = p.tx + (1 - p.tx) * k;\n const ty = p.ty * (1 - k);\n const norm = Math.hypot(tx, ty) || 1;\n return {\n x: x + (ty / norm) * lift,\n y: y - (tx / norm) * lift,\n angle: Math.atan2(ty, tx),\n };\n}\n\n/** Polyline of the pulled path between two arc lengths. */\nexport function getPathRideLine(\n samples: PathSamples,\n from: number,\n to: number,\n k: number,\n straight: PathRideStraight,\n) {\n if (to <= from) return \"\";\n const step = samples.length / (samples.points.length - 1);\n const stops = [from];\n for (let s = Math.ceil(from / step) * step; s < to; s += step) {\n if (s > from) stops.push(s);\n }\n stops.push(to);\n return stops\n .map((s, i) => {\n const p = getPathRidePoint(samples, s, k, straight);\n return `${i === 0 ? \"M\" : \"L\"}${p.x.toFixed(2)} ${p.y.toFixed(2)}`;\n })\n .join(\"\");\n}\n\nfunction useMetrics(text: string, font: string, fallback: number) {\n const chars = Array.from(text);\n const key = chars.join(\"\");\n const [metrics, setMetrics] = useState<{\n advances: number[];\n baseline: number;\n capHeight: number;\n } | null>(null);\n\n useEffect(() => {\n const handle = delayRender(\"path-ride: measuring the text\");\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n continueRender(handle);\n };\n const measure = () => {\n if (released) return;\n const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n if (ctx) {\n ctx.font = font;\n const m = ctx.measureText(\"H\");\n const ascent = m.fontBoundingBoxAscent / MEASURE_SIZE;\n const descent = m.fontBoundingBoxDescent / MEASURE_SIZE;\n setMetrics({\n advances: Array.from(key).map(\n (c) => ctx.measureText(c).width / MEASURE_SIZE,\n ),\n baseline:\n ascent > 0\n ? (1 - (ascent + descent)) / 2 + ascent\n : INTER_METRICS.baseline,\n capHeight:\n m.actualBoundingBoxAscent > 0\n ? m.actualBoundingBoxAscent / MEASURE_SIZE\n : INTER_METRICS.capHeight,\n });\n }\n release();\n };\n document.fonts.load(font, key).then(measure, measure);\n return release;\n }, [key, font]);\n\n return (\n metrics ?? {\n advances: chars.map(() => fallback),\n baseline: INTER_METRICS.baseline,\n capHeight: INTER_METRICS.capHeight,\n }\n );\n}\n\nexport function PathRide({\n text = pathRideDefaults.text,\n path = pathRideDefaults.path,\n fontSize = pathRideDefaults.fontSize,\n fontWeight = pathRideDefaults.fontWeight,\n fontFamily = pathRideDefaults.fontFamily,\n color = pathRideDefaults.color,\n lineColor = pathRideDefaults.lineColor,\n lineWidth = pathRideDefaults.lineWidth,\n speed = pathRideDefaults.speed,\n className,\n}: PathRideProps) {\n const frame = useCurrentFrame();\n const { fps, width, height } = useVideoConfig();\n const unit = height / 720;\n const t = getPathRideTime(frame, { fps, speed });\n const metrics = useMetrics(\n text,\n `${fontWeight} ${MEASURE_SIZE}px ${fontFamily}`,\n 0.55,\n );\n const samples = useMemo(() => samplePath(path), [path]);\n const chars = Array.from(text);\n const advances = metrics.advances.map((a) => a * fontSize);\n const { centers, width: textWidth } = getPathRideCenters(advances);\n const length = samples.length;\n const head = getPathRideHead(t, length);\n const tail = getPathRideTail(t, length);\n const k = getPathRideStraighten(t);\n const lift = lineWidth / 2 + LIFT * fontSize;\n // The line settles `lift` below the text so the capitals center on the frame.\n const straight: PathRideStraight = {\n start: getPathRideArc(length, 0, textWidth, fontSize),\n left: 640 - textWidth / 2,\n baseline: 360 + (metrics.capHeight * fontSize) / 2 + lift,\n };\n const tip = getPathRidePoint(samples, head, k, straight);\n const tipOpacity = interpolate(\n head,\n [0, length * 0.02, length * 0.98, length],\n [0, 1, 1, 0],\n CLAMP,\n );\n // Reference space (1280×720, y down) mapped onto the composition.\n const toX = (x: number) => width / 2 + (x - 640) * unit;\n const toY = (y: number) => height / 2 + (y - 360) * unit;\n const size = fontSize * unit;\n const line = getPathRideLine(samples, tail, head, k, straight);\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n style={{ position: \"absolute\", inset: 0 }}\n >\n <g\n transform={`translate(${toX(0)} ${toY(0)}) scale(${unit})`}\n fill=\"none\"\n >\n {line ? (\n <path\n d={line}\n stroke={lineColor}\n strokeWidth={lineWidth}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n ) : null}\n {tipOpacity > 0 ? (\n <circle\n cx={tip.x}\n cy={tip.y}\n r={lineWidth * 1.6}\n fill={lineColor}\n opacity={tipOpacity}\n />\n ) : null}\n </g>\n </svg>\n {chars.map((char, j) => {\n const arc = getPathRideArc(head, centers[j], textWidth, fontSize);\n const fade = getPathRideFade(arc, fontSize);\n if (fade <= 0) return null;\n const pose = getPathRidePoint(samples, arc, k, straight, lift);\n return (\n <span\n key={j}\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n fontFamily,\n fontSize: size,\n lineHeight: 1,\n fontWeight,\n fontVariationSettings: `\"wght\" ${fontWeight}`,\n color,\n whiteSpace: \"pre\",\n opacity: fade,\n transformOrigin: \"0 0\",\n transform: `translate(${toX(pose.x)}px, ${toY(pose.y)}px) rotate(${pose.angle}rad) translate(-50%, ${-metrics.baseline * size}px)`,\n }}\n >\n {char}\n </span>\n );\n })}\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/path-ride.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/period-drop.json b/registry-artifacts/period-drop.jsonnew file mode 100644index 00000000..dfc8e5b6--- /dev/null+++ b/registry-artifacts/period-drop.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "period-drop",+ "title": "Period Drop",+ "description": "A word rises out of its line, then a colored dot falls from above the frame, bounces with squash and stretch, and settles as the period.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/period-drop/index.tsx",+ "content": "\"use client\";\n\nimport { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { Easing, interpolate, useCurrentFrame, useVideoConfig } from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\nexport interface PeriodDropProps {\n text?: string;\n fontSize?: number;\n fontWeight?: number;\n fontFamily?: string;\n color?: string;\n dotColor?: string;\n dotSize?: number;\n speed?: number;\n className?: string;\n}\n\nexport const periodDropDefaults = {\n text: \"remocn\",\n fontSize: 160,\n fontWeight: 800,\n fontFamily: INTER,\n color: \"#fafafa\",\n dotColor: \"#D97757\",\n dotSize: 0.2,\n speed: 1,\n} satisfies Required<Omit<PeriodDropProps, \"className\">>;\n\n/** Frame where the dot has come to rest, squash included. */\nexport const periodDropLength = 47;\n\n/** Timeline constants on the 30 fps clock. */\nexport const periodDropTiming = {\n riseFrames: 12,\n riseStagger: 2,\n dropStart: 20,\n fallFrames: 12,\n restitution: 0.35,\n bounces: 2,\n /** Drop height as a share of the composition height. */\n dropHeight: 0.62,\n /** `scaleY` at full speed. */\n stretch: 0.3,\n /** `scaleY` lost at a full-speed impact. */\n squash: 0.22,\n /** Frames for an impact squash to decay by 1/e. */\n recover: 1.1,\n} as const;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutQuart = Easing.out(Easing.poly(4));\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nexport function getPeriodDropTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\n/** How far letter `index` still sits below its line, 1 → 0. */\nexport function getPeriodDropRise(t: number, index: number) {\n const start = periodDropTiming.riseStagger * index;\n return interpolate(t, [start, start + periodDropTiming.riseFrames], [1, 0], {\n ...CLAMP,\n easing: easeOutQuart,\n });\n}\n\n/** Frames at which the dot touches the line: the landing, then each bounce. */\nexport function getPeriodDropImpacts() {\n const { dropStart, fallFrames, restitution, bounces } = periodDropTiming;\n const impacts = [dropStart + fallFrames];\n for (let n = 1; n <= bounces; n++) {\n impacts.push(impacts[n - 1] + 2 * restitution ** n * fallFrames);\n }\n return impacts;\n}\n\nexport interface PeriodDropDot {\n visible: boolean;\n /** Height above the rest point as a share of the drop, 0 at rest, −1 at the start. */\n y: number;\n scaleX: number;\n scaleY: number;\n}\n\n/**\n * The dot's fall and bounces. Heights are shares of the drop height, time is\n * in 30 fps frames. Gravity is set by the fall: `g = 2 / fall²`, so the\n * landing speed is `2 / fall`. Each bounce leaves at `restitution` times the\n * previous speed, and the squash of each impact scales with it.\n */\nexport function getPeriodDropDot(t: number): PeriodDropDot {\n const { dropStart, fallFrames, restitution, stretch, squash, recover } =\n periodDropTiming;\n if (t < dropStart) return { visible: false, y: -1, scaleX: 1, scaleY: 1 };\n const g = 2 / (fallFrames * fallFrames);\n const landing = g * fallFrames;\n const impacts = getPeriodDropImpacts();\n\n let y = 0;\n let speed = 0;\n let deform = 0;\n if (t < impacts[0]) {\n const u = t - dropStart;\n y = -1 + 0.5 * g * u * u;\n speed = g * u;\n deform = speed / landing;\n } else {\n let n = impacts.length - 1;\n while (n > 0 && t < impacts[n]) n--;\n const tau = t - impacts[n];\n const bounce = n + 1;\n const launch =\n bounce < impacts.length ? restitution ** bounce * landing : 0;\n const flight = launch > 0 ? (2 * launch) / g : 0;\n if (tau < flight) {\n y = -(launch * tau - 0.5 * g * tau * tau);\n speed = Math.abs(launch - g * tau);\n }\n const impact = restitution ** n;\n const decay = Math.exp(-tau / recover);\n deform = -impact * decay + (1 - decay) * (speed / landing);\n }\n // Snap the last imperceptible wobble so the dot rests exactly.\n if (Math.abs(deform) < 0.005) deform = 0;\n\n const scaleY =\n deform >= 0 ? 1 + stretch * deform : 1 + squash * Math.max(-1, deform);\n return { visible: true, y: Math.min(0, y), scaleX: 1 / scaleY, scaleY };\n}\n\nexport function PeriodDrop({\n text = periodDropDefaults.text,\n fontSize = periodDropDefaults.fontSize,\n fontWeight = periodDropDefaults.fontWeight,\n fontFamily = periodDropDefaults.fontFamily,\n color = periodDropDefaults.color,\n dotColor = periodDropDefaults.dotColor,\n dotSize = periodDropDefaults.dotSize,\n speed = periodDropDefaults.speed,\n className,\n}: PeriodDropProps) {\n const frame = useCurrentFrame();\n const { fps, height } = useVideoConfig();\n const unit = height / 720;\n const t = getPeriodDropTime(frame, { fps, speed });\n const dot = getPeriodDropDot(t);\n const drop = periodDropTiming.dropHeight * height;\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n fontFamily,\n fontSize: fontSize * unit,\n lineHeight: 1,\n fontWeight,\n fontVariationSettings: `\"wght\" ${fontWeight}`,\n color,\n whiteSpace: \"pre\",\n }}\n >\n {Array.from(text).map((char, i) => (\n <span\n key={i}\n style={{\n display: \"inline-block\",\n overflow: \"hidden\",\n // Extend the clip below the line box so descenders survive.\n paddingBottom: \"0.15em\",\n marginBottom: \"-0.15em\",\n verticalAlign: \"top\",\n }}\n >\n <span\n style={{\n display: \"inline-block\",\n transform: `translateY(${getPeriodDropRise(t, i) * 115}%)`,\n }}\n >\n {char}\n </span>\n </span>\n ))}\n <span\n style={{\n display: \"inline-block\",\n width: `${dotSize}em`,\n height: `${dotSize}em`,\n marginLeft: \"0.04em\",\n borderRadius: \"50%\",\n background: dotColor,\n visibility: dot.visible ? \"visible\" : \"hidden\",\n transformOrigin: \"50% 100%\",\n transform: `translateY(${dot.y * drop}px) scale(${dot.scaleX}, ${dot.scaleY})`,\n }}\n />\n </div>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/period-drop.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/registry.json b/registry-artifacts/registry.jsonindex bf4e8ea3..1fe57bf7 100644--- a/registry-artifacts/registry.json+++ b/registry-artifacts/registry.json@@ -2306,6 +2306,272 @@],"type": "registry:component"},+ {+ "name": "truchet-flip",+ "title": "Truchet Flip",+ "description": "Quarter-circle Truchet tiles snap a quarter turn as a wave crosses the grid, rerouting continuous lines until they settle into concentric loops, a calm field, or a circle of small rings.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/truchet-flip/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/truchet-flip.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "mondrian-split",+ "title": "Mondrian Split",+ "description": "Black lines cut the frame into a seeded De Stijl grid, primaries wipe into its cells, the grid reflows like rubber, and one cell pushes its own lines out past the edges to become a clean color field or the next scene.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/mondrian-split/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/mondrian-split.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "bauhaus-build",+ "title": "Bauhaus Build",+ "description": "Flat Bauhaus circles, arcs, squares and bars tumble corner over corner on a hidden grid into an asymmetric frieze, then rebuild into two friezes around an open band for the title.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/bauhaus-build/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/bauhaus-build.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "squiggle",+ "title": "Squiggle",+ "description": "A flat line draws itself along a straight course as a traveling wave whose crests swim forward and calm down as the head runs out, in wave, zigzag, loop or coil shapes, then erases toward its end point.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/squiggle/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/squiggle.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "speed-lines",+ "title": "Speed Lines",+ "description": "Parallel streaks trail an element as it flies in at its real speed, the element stretching with that speed and landing with a squash and a small bounce as the streaks die, or radial lines rush in from the frame edges and snap onto one point for a manga-style impact frame.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/speed-lines/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/speed-lines.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "trim-burst",+ "title": "Trim Burst",+ "description": "A ring of short straight strokes shoots out from a point like Trim Paths: each end races ahead on a hard-braking ease-out while its start holds, then chases it on a smoother ease-in-out, so every stroke grows, travels and zips shut at its outer distance.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/trim-burst/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/trim-burst.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "keystroke",+ "title": "Keystroke",+ "description": "Physical keycaps rise in for each shortcut, press in real order with the modifiers held while the letter taps, spring back with a small capped overshoot, and leave after an idle hold, firing on the same frames as the remocn-ui steps they trigger.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/keystroke/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/keystroke.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "code-morph",+ "title": "Code Morph",+ "description": "A flat code editor that morphs between versions of a file, gliding each surviving token to its new line and column while removed code dissolves and new code fades in.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/code-morph/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/code-morph.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "agent-run",+ "title": "Agent Run",+ "description": "Animated brand-neutral AI agent run — a Thinking status and short plan, tool calls whose spinners close into checks while a timer counts real seconds, then a markdown answer with citations and a code block that streams in irregular token bursts. Light/dark themes.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/agent-run/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/agent-run.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "selection-snap",+ "title": "Selection Snap",+ "description": "A thin word in a loose viewfinder snaps into a design-tool selection while it goes from Thin to Black, pops its handles and counts up a size badge.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/selection-snap/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/selection-snap.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "echo-stack",+ "title": "Echo Stack",+ "description": "A word focuses in at the center while outline copies of it unfold above and below and keep drifting, like the one clear line on a spinning drum.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/echo-stack/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/echo-stack.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "type-wall",+ "title": "Type Wall",+ "description": "Rows of one word fill the frame, run in alternating directions at different speeds in heavy, narrow and outline faces, with an accent band through the middle.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/type-wall/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/type-wall.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "ring-text",+ "title": "Ring Text",+ "description": "Text runs around a tilted 3D band that spins, reading on the near side and mirrored on the far side.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/ring-text/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/ring-text.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "period-drop",+ "title": "Period Drop",+ "description": "A word rises out of its line, then a colored dot falls from above the frame, bounces with squash and stretch, and settles as the period.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/period-drop/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/period-drop.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "outline-trace",+ "title": "Outline Trace",+ "description": "Every glyph contour draws itself as a stroke, letter by letter, then the fill wipes up inside each letter and the stroke fades into it.",+ "dependencies": ["remotion", "opentype.js"],+ "files": [+ {+ "path": "registry/remocn/outline-trace/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/outline-trace.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "glyph-anatomy",+ "title": "Glyph Anatomy",+ "description": "A word builds as in a font editor, with metric guides, anchors along each contour and Bézier handles that pull straight segments into curves before the glyphs fill.",+ "dependencies": ["remotion", "opentype.js", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/glyph-anatomy/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/glyph-anatomy.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "stripe-type",+ "title": "Stripe Type",+ "description": "A word cut into horizontal bands, as in the IBM logo, slides together from alternating sides and locks, then can pass on through.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/stripe-type/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/stripe-type.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "path-ride",+ "title": "Path Ride",+ "description": "A line draws itself along a curve with the text riding behind its head, then the curve pulls taut and the text settles on a straight, centered baseline.",+ "dependencies": ["remotion", "@remotion/google-fonts", "@remotion/paths"],+ "files": [+ {+ "path": "registry/remocn/path-ride/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/path-ride.tsx"+ }+ ],+ "type": "registry:component"+ },+ {+ "name": "type-repeater",+ "title": "Type Repeater",+ "description": "An After Effects style repeater on a word, where copies unfold into a tunnel, a spiral or a fan behind it, breathe, then fold back into the word.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/type-repeater/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/type-repeater.tsx"+ }+ ],+ "type": "registry:component"+ },{"name": "remocn-ui","title": "remocn UI Core",diff --git a/registry-artifacts/ring-text.json b/registry-artifacts/ring-text.jsonnew file mode 100644index 00000000..314af16a--- /dev/null+++ b/registry-artifacts/ring-text.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "ring-text",+ "title": "Ring Text",+ "description": "Text runs around a tilted 3D band that spins, reading on the near side and mirrored on the far side.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/ring-text/index.tsx",+ "content": "\"use client\";\n\nimport { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { useEffect, useState } from \"react\";\nimport {\n continueRender,\n delayRender,\n Easing,\n interpolate,\n useCurrentFrame,\n useVideoConfig,\n} from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\nexport interface RingTextProps {\n text?: string;\n separator?: string;\n radius?: number;\n fontSize?: number;\n fontWeight?: number;\n fontFamily?: string;\n color?: string;\n band?: string;\n tilt?: number;\n roll?: number;\n period?: number;\n speed?: number;\n className?: string;\n}\n\nexport const ringTextDefaults = {\n text: \"Type in motion\",\n separator: \"•\",\n radius: 210,\n fontSize: 40,\n fontWeight: 800,\n fontFamily: INTER,\n color: \"#fafafa\",\n band: \"#0a0a0a\",\n tilt: 38,\n roll: -16,\n period: 240,\n speed: 1,\n} satisfies Required<Omit<RingTextProps, \"className\">>;\n\n/** Frame where the entrance has settled into the cruise spin. */\nexport const ringTextLength = 30;\n\n/** Band height, in em. */\nexport const ringBandHeight = 1.5;\n\nconst ENTRANCE = 30;\nconst FADE = 12;\nconst START_SCALE = 0.85;\n/** Extra turn, in degrees, that decays over the entrance. */\nconst ENTRANCE_SPIN = 90;\nconst WOBBLE = 6;\nconst WOBBLE_PERIOD = 150;\n/** Letters on the far side of the ring dim to this opacity. */\nconst BACK_OPACITY = 0.55;\n/** Advance per character, in em, until the face is measured. */\nconst FALLBACK_ADVANCE = 0.6;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutCubic = Easing.out(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nexport function getRingTextTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\n/** The characters of one lap: the text, a space, the separator, a space. */\nexport function getRingTextToken(text: string, separator: string) {\n return Array.from(separator ? `${text} ${separator} ` : `${text} `);\n}\n\nexport interface RingTextPanel {\n /** Index into the token. */\n char: number;\n /** Panel center around the ring, radians. */\n angle: number;\n /** Panel width, reference px. */\n width: number;\n}\n\nexport interface RingTextLayout {\n radius: number;\n repeats: number;\n /** Extra space added to every character so the band closes, reference px. */\n spacing: number;\n panels: RingTextPanel[];\n}\n\n/**\n * Repeats the token as many times as fits the circumference and spreads the\n * remainder as letter spacing. A token longer than the ring grows the radius.\n */\nexport function getRingTextLayout(\n advances: readonly number[],\n radius: number,\n): RingTextLayout {\n const tokenWidth = advances.reduce((sum, a) => sum + Math.max(0, a), 0);\n const count = advances.length;\n if (count === 0 || tokenWidth <= 0) {\n return { radius, repeats: 0, spacing: 0, panels: [] };\n }\n const circumference = Math.max(2 * Math.PI * Math.max(0, radius), tokenWidth);\n const repeats = Math.max(1, Math.floor(circumference / tokenWidth));\n const spacing = (circumference - repeats * tokenWidth) / (repeats * count);\n const panels: RingTextPanel[] = [];\n let travelled = 0;\n for (let r = 0; r < repeats; r++) {\n for (let char = 0; char < count; char++) {\n const width = Math.max(0, advances[char]) + spacing;\n panels.push({\n char,\n angle: (2 * Math.PI * (travelled + width / 2)) / circumference,\n width,\n });\n travelled += width;\n }\n }\n return {\n radius: circumference / (2 * Math.PI),\n repeats,\n spacing,\n panels,\n };\n}\n\n/** Ring pose at `t`: spin in degrees, tilt with its wobble, entrance scale and opacity. */\nexport function getRingTextPose(\n t: number,\n options: { period?: number; tilt?: number } = {},\n) {\n const period = Math.max(1, finite(options.period, ringTextDefaults.period));\n const tilt = finite(options.tilt, ringTextDefaults.tilt);\n const settle = easeOutCubic(Math.min(1, Math.max(0, t / ENTRANCE)));\n return {\n spin: (360 * t) / period + ENTRANCE_SPIN * settle,\n tilt: tilt + WOBBLE * Math.sin((2 * Math.PI * t) / WOBBLE_PERIOD),\n scale: START_SCALE + (1 - START_SCALE) * settle,\n opacity: interpolate(t, [0, FADE], [0, 1], CLAMP),\n };\n}\n\n/** Letter opacity from how squarely its panel faces the camera. */\nexport function getRingTextShade(angle: number, spinDegrees: number) {\n const facing = Math.cos(angle - (spinDegrees * Math.PI) / 180);\n return BACK_OPACITY + ((1 - BACK_OPACITY) * (facing + 1)) / 2;\n}\n\nfunction useAdvances(chars: readonly string[], font: string, fallback: number) {\n const key = chars.join(\"\");\n const [advances, setAdvances] = useState<number[] | null>(null);\n\n useEffect(() => {\n const handle = delayRender(\"ring-text: measuring the characters\");\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n continueRender(handle);\n };\n const measure = () => {\n if (released) return;\n const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n if (ctx) {\n ctx.font = font;\n setAdvances(Array.from(key).map((c) => ctx.measureText(c).width));\n }\n release();\n };\n document.fonts.load(font, key).then(measure, measure);\n return release;\n }, [key, font]);\n\n return advances ?? chars.map(() => fallback);\n}\n\nexport function RingText({\n text = ringTextDefaults.text,\n separator = ringTextDefaults.separator,\n radius = ringTextDefaults.radius,\n fontSize = ringTextDefaults.fontSize,\n fontWeight = ringTextDefaults.fontWeight,\n fontFamily = ringTextDefaults.fontFamily,\n color = ringTextDefaults.color,\n band = ringTextDefaults.band,\n tilt = ringTextDefaults.tilt,\n roll = ringTextDefaults.roll,\n period = ringTextDefaults.period,\n speed = ringTextDefaults.speed,\n className,\n}: RingTextProps) {\n const frame = useCurrentFrame();\n const { fps, height } = useVideoConfig();\n const unit = height / 720;\n const t = getRingTextTime(frame, { fps, speed });\n const chars = getRingTextToken(text, separator);\n const advances = useAdvances(\n chars,\n `${fontWeight} ${fontSize}px ${fontFamily}`,\n FALLBACK_ADVANCE * fontSize,\n );\n const layout = getRingTextLayout(advances, radius);\n const pose = getRingTextPose(t, { period, tilt });\n const bandHeight = ringBandHeight * fontSize * unit;\n // Adjacent flat panels meet at an angle and their antialiased edges let the\n // background through; bleeding each panel into its neighbors hides the seam.\n const bleed = 1.5 * Math.max(1, unit);\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n perspective: 1600 * unit,\n // Opacity lives here: on the preserve-3d ring it would flatten it.\n opacity: pose.opacity,\n }}\n >\n <div\n style={{\n position: \"relative\",\n width: 0,\n height: 0,\n transformStyle: \"preserve-3d\",\n // Negative tilt views the ring from above: the near side is at the\n // bottom and reads left to right, the far side shows it mirrored.\n transform: `scale(${pose.scale}) rotateZ(${roll}deg) rotateX(${-pose.tilt}deg) rotateY(${-pose.spin}deg)`,\n }}\n >\n {layout.panels.map((panel, i) => {\n const width = panel.width * unit;\n return (\n <div\n key={i}\n style={{\n position: \"absolute\",\n left: -width / 2 - bleed,\n top: -bandHeight / 2,\n width: width + 2 * bleed,\n height: bandHeight,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n background: band,\n color,\n fontFamily,\n fontSize: fontSize * unit,\n lineHeight: 1,\n fontWeight,\n fontVariationSettings: `\"wght\" ${fontWeight}`,\n whiteSpace: \"pre\",\n backfaceVisibility: \"visible\",\n transform: `rotateY(${panel.angle}rad) translateZ(${layout.radius * unit}px)`,\n }}\n >\n {/* Only the letter dims: shading the band per panel would show\n every seam between panels. */}\n <span\n style={{\n opacity: getRingTextShade(panel.angle, pose.spin),\n }}\n >\n {chars[panel.char]}\n </span>\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/ring-text.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/selection-snap.json b/registry-artifacts/selection-snap.jsonnew file mode 100644index 00000000..7818e6ec--- /dev/null+++ b/registry-artifacts/selection-snap.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "selection-snap",+ "title": "Selection Snap",+ "description": "A thin word in a loose viewfinder snaps into a design-tool selection while it goes from Thin to Black, pops its handles and counts up a size badge.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/selection-snap/index.tsx",+ "content": "\"use client\";\n\nimport { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { type CSSProperties, useEffect, useState } from \"react\";\nimport {\n continueRender,\n delayRender,\n Easing,\n interpolate,\n interpolateColors,\n useCurrentFrame,\n useVideoConfig,\n} from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\nexport interface SelectionSnapProps {\n text?: string;\n fontSize?: number;\n fontFamily?: string;\n fromWeight?: number;\n toWeight?: number;\n color?: string;\n accent?: string;\n selectionColor?: string;\n badge?: boolean;\n speed?: number;\n className?: string;\n}\n\nexport const selectionSnapDefaults = {\n text: \"Frame\",\n fontSize: 150,\n fontFamily: INTER,\n fromWeight: 100,\n toWeight: 900,\n color: \"#fafafa\",\n accent: \"#D97757\",\n selectionColor: \"#0d99ff\",\n badge: true,\n speed: 1,\n} satisfies Required<Omit<SelectionSnapProps, \"className\">>;\n\n/** Frame on the 30 fps timeline where every channel has come to rest. */\nexport const selectionSnapLength = 38;\n\n/** Padding around the word, in em: the loose viewfinder and the snapped box. */\nexport const selectionSnapPadding = {\n loose: { x: 1.1, y: 0.9 },\n tight: { x: 0.12, y: 0 },\n} as const;\n\n/** Corners first, then edge midpoints, as fractions of the box. */\nexport const selectionSnapHandles = [\n [0, 0],\n [1, 0],\n [1, 1],\n [0, 1],\n [0.5, 0],\n [1, 0.5],\n [0.5, 1],\n [0, 0.5],\n] as const;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutCubic = Easing.out(Easing.cubic);\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\nconst snapEase = Easing.bezier(0.34, 1.3, 0.64, 1);\nconst popEase = Easing.out(Easing.back(1.7));\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Back-eased 0 → 1 over `duration` frames from `start`, never below 0. */\nfunction pop(t: number, start: number, duration: number) {\n return Math.max(\n 0,\n interpolate(t, [start, start + duration], [0, 1], {\n ...CLAMP,\n easing: popEase,\n }),\n );\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nexport function getSelectionSnapTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\nexport interface SelectionSnapState {\n /** Word and brackets fading in, 0..1. */\n intro: number;\n /** Viewfinder settle scale. */\n bracketScale: number;\n /** Loose (0) to tight (1) padding. Overshoots past 1 on the snap. */\n snap: number;\n /** Weight progress, 0..1. */\n weight: number;\n /** Color progress toward the accent, 0..1. */\n tint: number;\n /** Bracket arms growing along the edges; 1 closes them into a box. */\n edges: number;\n /** Scale of each handle, in `selectionSnapHandles` order. */\n handles: number[];\n /** Badge entrance, 0..1 with overshoot. */\n badge: number;\n /** Badge readout progress, 0..1. */\n count: number;\n}\n\nexport function getSelectionSnapState(t: number): SelectionSnapState {\n return {\n intro: interpolate(t, [0, 8], [0, 1], { ...CLAMP, easing: easeOutCubic }),\n bracketScale: interpolate(t, [0, 8], [1.06, 1], {\n ...CLAMP,\n easing: easeOutCubic,\n }),\n snap: interpolate(t, [14, 28], [0, 1], { ...CLAMP, easing: snapEase }),\n weight: interpolate(t, [14, 30], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n tint: interpolate(t, [18, 30], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n edges: interpolate(t, [16, 26], [0, 1], {\n ...CLAMP,\n easing: easeInOutCubic,\n }),\n handles: selectionSnapHandles.map((_, i) => pop(t, 24 + i, 5)),\n badge: pop(t, 24, 8),\n count: interpolate(t, [24, 38], [0, 1], { ...CLAMP, easing: easeOutCubic }),\n };\n}\n\n/** Padding in em for a snap progress. */\nexport function getSelectionSnapPadding(snap: number) {\n const { loose, tight } = selectionSnapPadding;\n return {\n x: loose.x + (tight.x - loose.x) * snap,\n y: loose.y + (tight.y - loose.y) * snap,\n };\n}\n\n/** Size of the snapped box in reference px, from the word's final width. */\nexport function getSelectionSnapSize(textWidth: number, fontSize: number) {\n const { tight } = selectionSnapPadding;\n return {\n width: Math.round(textWidth + 2 * tight.x * fontSize),\n height: Math.round(fontSize * (1 + 2 * tight.y)),\n };\n}\n\nfunction useTextWidth(text: string, font: string) {\n const [width, setWidth] = useState<number | null>(null);\n\n useEffect(() => {\n const handle = delayRender(\"selection-snap: measuring the word\");\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n continueRender(handle);\n };\n const measure = () => {\n if (released) return;\n const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n if (ctx) {\n ctx.font = font;\n setWidth(ctx.measureText(text).width);\n }\n release();\n };\n document.fonts.load(font, text).then(measure, measure);\n return release;\n }, [text, font]);\n\n return width;\n}\n\nexport function SelectionSnap({\n text = selectionSnapDefaults.text,\n fontSize = selectionSnapDefaults.fontSize,\n fontFamily = selectionSnapDefaults.fontFamily,\n fromWeight = selectionSnapDefaults.fromWeight,\n toWeight = selectionSnapDefaults.toWeight,\n color = selectionSnapDefaults.color,\n accent = selectionSnapDefaults.accent,\n selectionColor = selectionSnapDefaults.selectionColor,\n badge = selectionSnapDefaults.badge,\n speed = selectionSnapDefaults.speed,\n className,\n}: SelectionSnapProps) {\n const frame = useCurrentFrame();\n const { fps, height } = useVideoConfig();\n const unit = height / 720;\n const t = getSelectionSnapTime(frame, { fps, speed });\n const state = getSelectionSnapState(t);\n\n const size = fontSize * unit;\n const pad = getSelectionSnapPadding(state.snap);\n const weight = fromWeight + (toWeight - fromWeight) * state.weight;\n const stroke = Math.max(1, 1.5 * unit);\n const arm = 0.16 * size;\n const handleSize = 9 * unit;\n const finalWidth = useTextWidth(\n text,\n `${toWeight} ${fontSize}px ${fontFamily}`,\n );\n const readout =\n finalWidth === null ? null : getSelectionSnapSize(finalWidth, fontSize);\n\n // Percentages resolve against the box width for `width` and its height for\n // `height`, so one expression grows every arm to its edge's midpoint.\n const along = `calc(${arm}px + (50% - ${arm}px) * ${state.edges})`;\n const arms: CSSProperties[] = [\n { top: 0, left: 0, width: along, height: stroke },\n { top: 0, right: 0, width: along, height: stroke },\n { bottom: 0, left: 0, width: along, height: stroke },\n { bottom: 0, right: 0, width: along, height: stroke },\n { top: 0, left: 0, width: stroke, height: along },\n { bottom: 0, left: 0, width: stroke, height: along },\n { top: 0, right: 0, width: stroke, height: along },\n { bottom: 0, right: 0, width: stroke, height: along },\n ];\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n position: \"relative\",\n display: \"inline-block\",\n padding: `${pad.y * size}px ${pad.x * size}px`,\n }}\n >\n <span\n style={{\n display: \"block\",\n whiteSpace: \"pre\",\n fontFamily,\n fontSize: size,\n lineHeight: 1,\n fontWeight: Math.round(weight / 100) * 100,\n fontVariationSettings: `\"wght\" ${weight.toFixed(2)}`,\n color: interpolateColors(state.tint, [0, 1], [color, accent]),\n opacity: state.intro,\n }}\n >\n {text}\n </span>\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n opacity: state.intro,\n transform: `scale(${state.bracketScale})`,\n }}\n >\n {arms.map((style, i) => (\n <div\n key={i}\n style={{\n position: \"absolute\",\n background: selectionColor,\n ...style,\n }}\n />\n ))}\n {selectionSnapHandles.map(([x, y], i) => (\n <div\n key={`${x}-${y}`}\n style={{\n position: \"absolute\",\n left: `${x * 100}%`,\n top: `${y * 100}%`,\n width: handleSize,\n height: handleSize,\n boxSizing: \"border-box\",\n background: \"#ffffff\",\n border: `${stroke}px solid ${selectionColor}`,\n transform: `translate(-50%, -50%) scale(${state.handles[i]})`,\n }}\n />\n ))}\n </div>\n {badge && readout ? (\n <div\n style={{\n position: \"absolute\",\n left: \"50%\",\n top: `calc(100% + ${12 * unit}px)`,\n padding: `${3 * unit}px ${7 * unit}px`,\n borderRadius: 4 * unit,\n background: selectionColor,\n color: \"#ffffff\",\n fontFamily: INTER,\n fontSize: 14 * unit,\n lineHeight: 1.2,\n fontWeight: 600,\n fontVariationSettings: '\"wght\" 600',\n fontVariantNumeric: \"tabular-nums\",\n whiteSpace: \"nowrap\",\n opacity: Math.min(1, state.badge),\n transform: `translate(-50%, ${(1 - state.badge) * 8 * unit}px) scale(${0.6 + 0.4 * state.badge})`,\n transformOrigin: \"50% 0\",\n }}\n >\n {Math.round(readout.width * state.count)} ×{\" \"}\n {Math.round(readout.height * state.count)}\n </div>\n ) : null}\n </div>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/selection-snap.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/speed-lines.json b/registry-artifacts/speed-lines.jsonnew file mode 100644index 00000000..de997e9c--- /dev/null+++ b/registry-artifacts/speed-lines.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "speed-lines",+ "title": "Speed Lines",+ "description": "Parallel streaks trail an element as it flies in at its real speed, the element stretching with that speed and landing with a squash and a small bounce as the streaks die, or radial lines rush in from the frame edges and snap onto one point for a manga-style impact frame.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/speed-lines/index.tsx",+ "content": "\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { random, useCurrentFrame, useVideoConfig } from \"remotion\";\n\nexport type SpeedLinesMode = \"trail\" | \"focus\";\n\nexport interface SpeedLinesPoint {\n x: number;\n y: number;\n}\n\nexport interface SpeedLinesProps {\n mode?: SpeedLinesMode;\n from?: SpeedLinesPoint;\n to?: SpeedLinesPoint;\n x?: number;\n y?: number;\n count?: number;\n weight?: number;\n spread?: number;\n duration?: number;\n bounce?: number;\n squash?: number;\n color?: string;\n seed?: number;\n delay?: number;\n speed?: number;\n children?: ReactNode;\n className?: string;\n}\n\ntype Paint = \"color\" | \"children\" | \"className\";\ntype Unset = \"to\" | \"children\" | \"className\";\n\nexport interface SpeedLinesOptions extends Omit<SpeedLinesProps, Paint> {\n width?: number;\n height?: number;\n fps?: number;\n}\n\nexport interface SpeedLinesSegment {\n index: number;\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n length: number;\n}\n\nexport interface SpeedLinesStreak extends SpeedLinesSegment {\n offset: number;\n reach: number;\n}\n\nexport interface SpeedLinesRay extends SpeedLinesSegment {\n angle: number;\n rest: number;\n inner: number;\n outer: number;\n}\n\nexport interface SpeedLinesRayTiming {\n rest: number;\n outer: number;\n start?: number;\n release?: number;\n}\n\nexport const speedLinesDefaults: Required<Omit<SpeedLinesProps, Unset>> = {\n mode: \"trail\",\n from: { x: -0.25, y: 0.5 },\n x: 0.5,\n y: 0.5,\n count: 12,\n weight: 2,\n spread: 96,\n duration: 14,\n bounce: 0.5,\n squash: 0.5,\n color: \"#ffffff\",\n seed: 1,\n delay: 0,\n speed: 1,\n};\n\nconst REFERENCE = 720;\nconst LANDING = 0.3;\nconst CARRY = 0.3;\nconst ECHO = 0.2;\nconst SOFTEN = 1.2;\nconst SETTLE = 6;\nconst STRETCH = Math.log(1.3);\nconst SQUASH = Math.log(1.25);\nconst STRETCH_GAIN = 0.007;\nconst SQUASH_GAIN = 0.018;\nconst PROBE = 1e-3;\nconst CENTER = \"translate(-50%, -50%)\";\nconst HOLD = 24;\nconst SPAWN_START = 0.04;\nconst SPAWN_END = 0.8;\nconst LIFE = 0.3;\nconst MIN_LIFE = 3;\nconst DRAW = 0.4;\nconst ERASE = 0.35;\nconst SHUTTER = 1.6;\nconst DRIFT = 0.15;\nconst SETBACK = 0.35;\nconst SLOW = 5;\nconst FAST = 14;\nconst GOLDEN = (Math.sqrt(5) - 1) / 2;\nconst IMPACT = 3;\nconst RUSH_JITTER = 1;\nconst RELAX = 0.12;\nconst RELAX_RATE = 1.5;\nconst RELEASE = 8;\nconst RELEASE_JITTER = 1.5;\nconst RETRACT = 3.5;\nconst FOCUS_END = RELEASE + RELEASE_JITTER + RETRACT;\nconst ANGLE_JITTER = 0.6;\nconst RADIUS_JITTER = 0.6;\nconst MAX_COUNT = 64;\nconst MIN_WEIGHT = 0.5;\nconst MAX_WEIGHT = 12;\nconst MIN_SPREAD = 8;\nconst MAX_SPREAD = 480;\nconst MIN_DURATION = 4;\nconst MAX_DURATION = 120;\n\nconst finite = (value: number | undefined, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst round = (value: number) => Math.round(value * 100) / 100;\nconst fine = (value: number) => Math.round(value * 10000) / 10000;\nconst fraction = (value: number) => value - Math.floor(value);\nconst modeOf = (value: string | undefined): SpeedLinesMode =>\n value === \"focus\" ? \"focus\" : \"trail\";\nconst travelOf = (value: number | undefined) =>\n clamp(finite(value, speedLinesDefaults.duration), MIN_DURATION, MAX_DURATION);\n\nfunction smoothstep(value: number) {\n const t = clamp(value, 0, 1);\n return t * t * (3 - 2 * t);\n}\n\nfunction easeOut(value: number) {\n const t = clamp(value, 0, 1);\n return 1 - (1 - t) * (1 - t);\n}\n\nfunction pointOf(\n value: SpeedLinesPoint | undefined,\n fallback: SpeedLinesPoint,\n) {\n return { x: finite(value?.x, fallback.x), y: finite(value?.y, fallback.y) };\n}\n\nfunction key(seed: number, index: number, name: string) {\n return random(`speed-lines-${seed}-${index}-${name}`);\n}\n\nfunction settingsOf(options: SpeedLinesOptions) {\n const height = Math.max(1, finite(options.height, 720));\n const x = finite(options.x, speedLinesDefaults.x);\n const y = finite(options.y, speedLinesDefaults.y);\n const count = finite(options.count, speedLinesDefaults.count);\n const weight = finite(options.weight, speedLinesDefaults.weight);\n const spread = finite(options.spread, speedLinesDefaults.spread);\n return {\n mode: modeOf(options.mode),\n width: Math.max(1, finite(options.width, 1280)),\n height,\n fps: Math.max(1, finite(options.fps, 30)),\n unit: height / REFERENCE,\n from: pointOf(options.from, speedLinesDefaults.from),\n to: pointOf(options.to, { x, y }),\n x,\n y,\n count: Math.round(clamp(count, 1, MAX_COUNT)),\n weight: clamp(weight, MIN_WEIGHT, MAX_WEIGHT),\n spread: clamp(spread, MIN_SPREAD, MAX_SPREAD),\n duration: travelOf(options.duration),\n bounce: clamp(finite(options.bounce, speedLinesDefaults.bounce), 0, 1),\n squash: clamp(finite(options.squash, speedLinesDefaults.squash), 0, 1),\n seed: finite(options.seed, speedLinesDefaults.seed),\n delay: Math.max(0, finite(options.delay, speedLinesDefaults.delay)),\n speed: Math.max(0, finite(options.speed, speedLinesDefaults.speed)),\n };\n}\n\ntype Settings = ReturnType<typeof settingsOf>;\n\nfunction directionOf(settings: Settings) {\n const { from, to, width, height } = settings;\n const dx = (to.x - from.x) * width;\n const dy = (to.y - from.y) * height;\n const distance = Math.hypot(dx, dy);\n if (distance < 1e-6) return { dx: 1, dy: 0, distance: 0 };\n return { dx: dx / distance, dy: dy / distance, distance };\n}\n\nfunction along(position: number, size: number, step: number) {\n if (step > 1e-9) return (size - position) / step;\n if (step < -1e-9) return -position / step;\n return Number.POSITIVE_INFINITY;\n}\n\nfunction exitDistance(\n cx: number,\n cy: number,\n cos: number,\n sin: number,\n width: number,\n height: number,\n) {\n const inside = cx >= 0 && cx <= width && cy >= 0 && cy <= height;\n if (!inside) {\n const reachX = Math.max(Math.abs(cx), Math.abs(width - cx));\n const reachY = Math.max(Math.abs(cy), Math.abs(height - cy));\n return Math.hypot(reachX, reachY);\n }\n return Math.min(along(cx, width, cos), along(cy, height, sin));\n}\n\nfunction springOf(bounce: number) {\n const landing = LANDING + CARRY * bounce;\n const kappa = (1 + Math.sqrt(1 - landing)) / 2;\n const gain = 1 / (0.5 - kappa / 3);\n const echo = ECHO * bounce;\n const decrement = -Math.log(echo);\n const damping = echo > 0 ? decrement / Math.hypot(Math.PI, decrement) : 1;\n const natural = 1 / (1 + SOFTEN * bounce);\n const decay = damping * natural;\n return {\n kappa,\n gain,\n contact: gain * (1 - kappa),\n decay,\n ring: natural * Math.sqrt(1 - damping * damping),\n settle: Math.ceil(SETTLE / decay),\n };\n}\n\nfunction easeOf(time: number, travel: number, bounce: number) {\n if (time <= 0) return 0;\n const { kappa, gain, contact, decay, ring, settle } = springOf(bounce);\n if (time < travel) {\n const w = time / travel;\n return gain * ((w * w) / 2 - (kappa * w * w * w) / 3);\n }\n const since = time - travel;\n if (since >= settle) return 1;\n const taper = smoothstep((2 * since) / settle - 1);\n const wave = ring > 1e-9 ? Math.sin(ring * since) / ring : since;\n const envelope = Math.exp(-decay * since) * (1 - taper);\n return 1 + (contact / travel) * wave * envelope;\n}\n\nexport function getSpeedLinesTimeline(options: SpeedLinesOptions = {}) {\n const { mode, duration, bounce } = settingsOf(options);\n if (mode === \"focus\") return { mode, impact: IMPACT, end: FOCUS_END };\n return { mode, impact: duration, end: duration + springOf(bounce).settle };\n}\n\nexport type SpeedLinesTimeline = ReturnType<typeof getSpeedLinesTimeline>;\n\nexport const speedLinesLength = getSpeedLinesTimeline().end;\n\nexport function getSpeedLinesDuration(options: SpeedLinesOptions = {}) {\n const { delay, speed } = settingsOf(options);\n if (speed === 0) return 1;\n const { end } = getSpeedLinesTimeline(options);\n return Math.max(1, Math.ceil(delay + (end + HOLD) / speed));\n}\n\nexport function getSpeedLinesTime(\n frame: number,\n options: SpeedLinesOptions = {},\n) {\n const { fps, delay, speed } = settingsOf(options);\n const elapsed = Math.max(0, finite(frame, 0) - delay);\n return elapsed * (30 / fps) * speed;\n}\n\nexport function getSpeedLinesEase(\n time: number,\n options: SpeedLinesOptions = {},\n) {\n const { duration, bounce } = settingsOf(options);\n return easeOf(finite(time, 0), duration, bounce);\n}\n\nfunction positionAt(time: number, settings: Settings) {\n const { mode, from, to, width, height, duration, bounce } = settings;\n if (mode === \"focus\") {\n return { x: settings.x * width, y: settings.y * height, progress: 1 };\n }\n const progress = easeOf(time, duration, bounce);\n const startX = from.x * width;\n const startY = from.y * height;\n return {\n x: startX + (to.x * width - startX) * progress,\n y: startY + (to.y * height - startY) * progress,\n progress,\n };\n}\n\nexport function getSpeedLinesPosition(\n time: number,\n options: SpeedLinesOptions = {},\n) {\n const { x, y } = positionAt(finite(time, 0), settingsOf(options));\n return { x, y };\n}\n\nfunction shapeAt(time: number, settings: Settings) {\n const { mode, duration, bounce, squash, unit, speed } = settings;\n if (mode === \"focus\") return { rotation: 0, along: 1, across: 1 };\n const { dx, dy, distance } = directionOf(settings);\n const rotation = (Math.atan2(dy, dx) * 180) / Math.PI;\n if (squash === 0 || distance === 0 || time <= 0) {\n return { rotation, along: 1, across: 1 };\n }\n const span = distance / unit;\n const ahead = easeOf(time + PROBE, duration, bounce);\n const behind = easeOf(time - PROBE, duration, bounce);\n const rate = (Math.abs(ahead - behind) / (2 * PROBE)) * span * speed;\n const landed = time > duration ? easeOf(time, duration, bounce) - 1 : 0;\n const past = Math.max(0, landed) * span;\n const stretch = STRETCH * Math.tanh((squash * STRETCH_GAIN * rate) / STRETCH);\n const compression =\n SQUASH * Math.tanh((squash * SQUASH_GAIN * past) / SQUASH);\n const strain = clamp(stretch - compression, -SQUASH, STRETCH);\n return { rotation, along: Math.exp(strain), across: Math.exp(-strain) };\n}\n\nexport function getSpeedLinesShape(\n time: number,\n options: SpeedLinesOptions = {},\n) {\n return shapeAt(finite(time, 0), settingsOf(options));\n}\n\nexport type SpeedLinesShape = ReturnType<typeof getSpeedLinesShape>;\n\nexport function getSpeedLinesVelocity(\n frame: number,\n options: SpeedLinesOptions = {},\n) {\n const settings = settingsOf(options);\n const current = finite(frame, 0);\n const now = positionAt(getSpeedLinesTime(current, options), settings);\n const before = positionAt(getSpeedLinesTime(current - 1, options), settings);\n const scale = settings.fps / 30;\n const x = (now.x - before.x) * scale;\n const y = (now.y - before.y) * scale;\n const { dx, dy } = directionOf(settings);\n return { x, y, forward: x * dx + y * dy };\n}\n\nfunction streakSeeds(settings: Settings) {\n const { seed, count, spread, unit } = settings;\n const band = spread * unit;\n const phase = random(`speed-lines-${seed}-lanes`);\n return Array.from({ length: count }, (_, index) => {\n const jitter = (key(seed, index, \"lane\") - 0.5) / (2 * count);\n const lane = fraction(phase + GOLDEN * index + jitter);\n const slot = (index + key(seed, index, \"spawn\")) / count;\n return {\n index,\n spawn: SPAWN_START + (SPAWN_END - SPAWN_START) * slot,\n offset: band * (lane - 0.5),\n factor: 0.5 + 0.5 * key(seed, index, \"length\"),\n setback: SETBACK * band * key(seed, index, \"setback\"),\n };\n });\n}\n\nexport function getSpeedLinesStreaks(\n frame: number,\n options: SpeedLinesOptions = {},\n): SpeedLinesStreak[] {\n const settings = settingsOf(options);\n if (settings.mode !== \"trail\") return [];\n const time = getSpeedLinesTime(frame, options);\n const { dx, dy, distance } = directionOf(settings);\n if (distance === 0 || time <= 0) return [];\n const { forward } = getSpeedLinesVelocity(frame, options);\n const { unit, duration, bounce, weight } = settings;\n const fast = smoothstep((forward - SLOW * unit) / ((FAST - SLOW) * unit));\n const gate = fast * (1 - smoothstep(time - duration));\n if (gate <= 0) return [];\n const center = positionAt(time, settings);\n const progress = time / duration;\n const life = Math.max(MIN_LIFE, LIFE * duration) / duration;\n const minimum = 0.5 * weight * unit;\n const streaks: SpeedLinesStreak[] = [];\n for (const streak of streakSeeds(settings)) {\n const age = (progress - streak.spawn) / life;\n if (age <= 0 || age >= 1) continue;\n const reach = SHUTTER * streak.factor * forward * gate;\n const drawn = easeOut(age / DRAW);\n const erased = smoothstep((age - ERASE) / (1 - ERASE));\n const length = reach * (drawn - erased);\n if (length < minimum) continue;\n const spawned = easeOf(streak.spawn * duration, duration, bounce);\n const since = Math.max(0, (center.progress - spawned) * distance);\n const base = streak.setback + DRIFT * since;\n const front = base + reach * erased;\n const back = base + reach * drawn;\n const laneX = center.x - dy * streak.offset;\n const laneY = center.y + dx * streak.offset;\n streaks.push({\n index: streak.index,\n offset: streak.offset,\n reach,\n x1: round(laneX - dx * front),\n y1: round(laneY - dy * front),\n x2: round(laneX - dx * back),\n y2: round(laneY - dy * back),\n length,\n });\n }\n return streaks;\n}\n\nexport function getSpeedLinesRadius(time: number, ray: SpeedLinesRayTiming) {\n const { rest, outer, start = 0, release = RELEASE } = ray;\n const t = finite(time, 0);\n if (t <= start) return outer;\n if (t < IMPACT) {\n const q = (t - start) / (IMPACT - start);\n return outer + (rest - outer) * q * q;\n }\n const settle = (at: number) =>\n rest * (1 + RELAX * (1 - Math.exp(-(at - IMPACT) / RELAX_RATE)));\n if (t < release) return settle(t);\n const held = settle(release);\n const q = clamp((t - release) / RETRACT, 0, 1);\n return outer - (outer - held) * (1 - q * q);\n}\n\nexport function getSpeedLinesRays(\n frame: number,\n options: SpeedLinesOptions = {},\n): SpeedLinesRay[] {\n const settings = settingsOf(options);\n if (settings.mode !== \"focus\") return [];\n const time = getSpeedLinesTime(frame, options);\n if (time <= 0 || time >= FOCUS_END) return [];\n const { seed, count, spread, weight, unit, width, height } = settings;\n const cx = settings.x * width;\n const cy = settings.y * height;\n const minimum = 0.5 * weight * unit;\n const rotation = random(`speed-lines-${seed}-rotation`);\n const rays: SpeedLinesRay[] = [];\n for (let index = 0; index < count; index++) {\n const jitter = ANGLE_JITTER * (key(seed, index, \"angle\") - 0.5);\n const angle = 2 * Math.PI * (rotation + (index + jitter) / count);\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n const reach = RADIUS_JITTER * key(seed, index, \"radius\");\n const rest = spread * unit * (1 + reach);\n const outer = exitDistance(cx, cy, cos, sin, width, height) + weight * unit;\n const inner = getSpeedLinesRadius(time, {\n rest,\n outer,\n start: RUSH_JITTER * key(seed, index, \"rush\"),\n release: RELEASE + RELEASE_JITTER * key(seed, index, \"release\"),\n });\n const length = outer - inner;\n if (length < minimum) continue;\n rays.push({\n index,\n angle,\n rest,\n inner,\n outer,\n x1: round(cx + cos * inner),\n y1: round(cy + sin * inner),\n x2: round(cx + cos * outer),\n y2: round(cy + sin * outer),\n length,\n });\n }\n return rays;\n}\n\nexport function getSpeedLinesState(\n frame: number,\n options: SpeedLinesOptions = {},\n) {\n const settings = settingsOf(options);\n const time = getSpeedLinesTime(frame, options);\n const point = positionAt(time, settings);\n const shape = shapeAt(time, settings);\n const rotation = round(shape.rotation);\n const scale = `scale(${fine(shape.along)}, ${fine(shape.across)})`;\n const streaks = getSpeedLinesStreaks(frame, options);\n const rays = getSpeedLinesRays(frame, options);\n const path = [...streaks, ...rays]\n .map(({ x1, y1, x2, y2 }) => `M ${x1} ${y1} L ${x2} ${y2}`)\n .join(\" \");\n return {\n mode: settings.mode,\n width: settings.width,\n height: settings.height,\n unit: settings.unit,\n time,\n x: point.x,\n y: point.y,\n left: (point.x / settings.width) * 100,\n top: (point.y / settings.height) * 100,\n radius: (settings.spread * settings.unit) / 2,\n strokeWidth: settings.weight * settings.unit,\n rotation,\n along: shape.along,\n across: shape.across,\n transform:\n shape.along === 1\n ? CENTER\n : `${CENTER} rotate(${rotation}deg) ${scale} rotate(${-rotation}deg)`,\n streaks,\n rays,\n path,\n };\n}\n\nexport type SpeedLinesState = ReturnType<typeof getSpeedLinesState>;\n\nexport function SpeedLines({\n mode = speedLinesDefaults.mode,\n from = speedLinesDefaults.from,\n to,\n x = speedLinesDefaults.x,\n y = speedLinesDefaults.y,\n count = speedLinesDefaults.count,\n weight = speedLinesDefaults.weight,\n spread = speedLinesDefaults.spread,\n duration = speedLinesDefaults.duration,\n bounce = speedLinesDefaults.bounce,\n squash = speedLinesDefaults.squash,\n color = speedLinesDefaults.color,\n seed = speedLinesDefaults.seed,\n delay = speedLinesDefaults.delay,\n speed = speedLinesDefaults.speed,\n children,\n className,\n}: SpeedLinesProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const state = getSpeedLinesState(frame, {\n mode,\n from,\n to,\n x,\n y,\n count,\n weight,\n spread,\n duration,\n bounce,\n squash,\n seed,\n delay,\n speed,\n width,\n height,\n fps,\n });\n const fallback = state.mode === \"trail\" && children === undefined;\n const placed = children !== undefined && children !== null;\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, pointerEvents: \"none\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n aria-hidden=\"true\"\n style={{ position: \"absolute\", inset: 0, display: \"block\" }}\n >\n {state.path ? (\n <path\n d={state.path}\n fill=\"none\"\n stroke={color}\n strokeWidth={state.strokeWidth}\n strokeLinecap=\"round\"\n />\n ) : null}\n {fallback ? (\n <ellipse\n cx={state.x}\n cy={state.y}\n rx={state.radius * state.along}\n ry={state.radius * state.across}\n transform={`rotate(${state.rotation} ${state.x} ${state.y})`}\n fill={color}\n />\n ) : null}\n </svg>\n {placed ? (\n <div\n style={{\n position: \"absolute\",\n left: `${state.left}%`,\n top: `${state.top}%`,\n width: \"max-content\",\n transform: state.transform,\n transformOrigin: \"50% 50%\",\n }}\n >\n {children}\n </div>\n ) : null}\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/speed-lines.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/squiggle.json b/registry-artifacts/squiggle.jsonnew file mode 100644index 00000000..adef81f2--- /dev/null+++ b/registry-artifacts/squiggle.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "squiggle",+ "title": "Squiggle",+ "description": "A flat line draws itself along a straight course as a traveling wave whose crests swim forward and calm down as the head runs out, in wave, zigzag, loop or coil shapes, then erases toward its end point.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/squiggle/index.tsx",+ "content": "\"use client\";\n\nimport { useCurrentFrame, useVideoConfig } from \"remotion\";\n\nexport type SquiggleShape = \"wave\" | \"zigzag\" | \"loops\" | \"coil\";\nexport type SquiggleJoin = \"miter\" | \"round\";\n\nexport interface SquiggleProps {\n shape?: SquiggleShape;\n x?: number;\n y?: number;\n length?: number;\n angle?: number;\n amplitude?: number;\n wavelength?: number;\n weight?: number;\n color?: string;\n settle?: number;\n hold?: number;\n erase?: boolean;\n delay?: number;\n speed?: number;\n className?: string;\n}\n\ntype Paint = \"color\" | \"className\";\n\nexport interface SquiggleOptions extends Omit<SquiggleProps, Paint> {\n width?: number;\n height?: number;\n fps?: number;\n}\n\nexport interface SquigglePoint {\n x: number;\n y: number;\n}\n\nexport interface SquiggleCurveInput {\n shape: SquiggleShape;\n length: number;\n wavelength: number;\n amplitude: number;\n phase: number;\n unit?: number;\n}\n\nexport const squiggleDefaults: Required<Omit<SquiggleProps, \"className\">> = {\n shape: \"wave\",\n x: 0.375,\n y: 0.5,\n length: 320,\n angle: 0,\n amplitude: 14,\n wavelength: 48,\n weight: 3,\n color: \"#ffffff\",\n settle: 0.5,\n hold: 12,\n erase: true,\n delay: 0,\n speed: 1,\n};\n\ntype SmoothShape = Exclude<SquiggleShape, \"zigzag\">;\n\nconst DRAW = 24;\nconst SETTLE = 36;\nconst ERASE = 18;\nconst SWIM = 1.5;\nconst EXIT_SWIM = 0.5;\nconst TAIL = 14;\nconst REST = 24;\nconst MIN_WAVELENGTH = 8;\nconst LOOP_FLOOR = 3;\nconst MIN_POINTS = 24;\nconst MAX_POINTS = 4000;\nconst EPSILON = 0.01;\nconst SAMPLES: Record<SmoothShape, number> = { wave: 32, loops: 64, coil: 80 };\nconst REACH: Record<SmoothShape, number> = { wave: 0, loops: 2.4, coil: 4.2 };\n\nconst finite = (value: number | undefined, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst round = (value: number) => Math.round(value * 100) / 100;\nconst rateOf = (speed: number | undefined) =>\n Math.max(0, finite(speed, squiggleDefaults.speed));\nconst shapeOf = (value: string | undefined): SquiggleShape =>\n value === \"zigzag\" || value === \"loops\" || value === \"coil\" ? value : \"wave\";\nconst joinOf = (shape: SquiggleShape): SquiggleJoin =>\n shape === \"zigzag\" ? \"miter\" : \"round\";\nconst easeOutQuart = (t: number) => 1 - (1 - t) ** 4;\nconst easeOutCubic = (t: number) => 1 - (1 - t) ** 3;\nconst easeInOutCubic = (t: number) =>\n t < 0.5 ? 4 * t ** 3 : 1 - (-2 * t + 2) ** 3 / 2;\nconst easeInOutSine = (t: number) => (1 - Math.cos(Math.PI * t)) / 2;\n\nfunction smoothstep(value: number) {\n const t = clamp(value, 0, 1);\n return t * t * (3 - 2 * t);\n}\n\nexport function getSquiggleTimeline(\n options: Pick<SquiggleOptions, \"hold\" | \"erase\"> = {},\n) {\n const hold = Math.max(0, finite(options.hold, squiggleDefaults.hold));\n const erase = options.erase !== false;\n const eraseStart = SETTLE + hold;\n const eraseEnd = eraseStart + ERASE;\n const end = erase ? eraseEnd : SETTLE;\n return {\n draw: DRAW,\n settle: SETTLE,\n hold,\n erase,\n eraseStart,\n eraseEnd,\n end,\n duration: end + (erase ? TAIL : REST),\n };\n}\n\nexport type SquiggleTimeline = ReturnType<typeof getSquiggleTimeline>;\n\nexport const squiggleLength = getSquiggleTimeline().end;\n\nexport function getSquiggleDuration(\n options: Pick<SquiggleOptions, \"hold\" | \"erase\" | \"speed\" | \"delay\"> = {},\n) {\n const rate = rateOf(options.speed);\n if (rate === 0) return 1;\n const delay = Math.max(0, finite(options.delay, squiggleDefaults.delay));\n const { duration } = getSquiggleTimeline(options);\n return Math.max(1, Math.ceil(delay + duration / rate));\n}\n\nexport function getSquiggleTime(\n frame: number,\n options: Pick<SquiggleOptions, \"fps\" | \"speed\" | \"delay\"> = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const delay = Math.max(0, finite(options.delay, squiggleDefaults.delay));\n const elapsed = Math.max(0, finite(frame, 0) - delay);\n return (elapsed * 30 * rateOf(options.speed)) / fps;\n}\n\nexport function getSquiggleHead(time: number) {\n if (!(time > 0)) return 0;\n return easeOutQuart(Math.min(1, time / DRAW));\n}\n\nexport function getSquiggleTail(\n time: number,\n timeline: SquiggleTimeline = getSquiggleTimeline(),\n) {\n if (!timeline.erase) return 0;\n const progress = (time - timeline.eraseStart) / ERASE;\n if (!(progress > 0)) return 0;\n return easeInOutCubic(Math.min(1, progress));\n}\n\nexport function getSquiggleCalm(time: number) {\n if (!(time > 0)) return 0;\n return easeInOutSine(Math.min(1, time / SETTLE));\n}\n\nexport function getSquigglePhase(\n time: number,\n timeline: SquiggleTimeline = getSquiggleTimeline(),\n) {\n const swim = time > 0 ? easeOutCubic(Math.min(1, time / SETTLE)) : 0;\n return SWIM * swim + EXIT_SWIM * getSquiggleTail(time, timeline);\n}\n\nexport function getSquiggleEnvelope(\n s: number,\n length: number,\n wavelength: number,\n) {\n const taper = Math.min(wavelength, length / 3);\n if (!(taper > 0)) return 0;\n return smoothstep(s / taper) * smoothstep((length - s) / taper);\n}\n\nfunction getZigzagCurve(\n length: number,\n wavelength: number,\n amplitude: number,\n shift: number,\n) {\n const k = (2 * Math.PI) / wavelength;\n const points: SquigglePoint[] = [{ x: 0, y: 0 }];\n const first = Math.floor(-(Math.PI / 2 + shift) / Math.PI) + 1;\n for (let m = first; points.length < MAX_POINTS - 1; m++) {\n const s = (Math.PI / 2 + m * Math.PI + shift) / k;\n if (s >= length) break;\n if (s <= 0) continue;\n const side = m % 2 === 0 ? 1 : -1;\n const w = getSquiggleEnvelope(s, length, wavelength);\n points.push({ x: s, y: side * amplitude * w });\n }\n points.push({ x: length, y: 0 });\n return points;\n}\n\nexport function getSquiggleCurve(input: SquiggleCurveInput) {\n const shape = shapeOf(input.shape);\n const length = Math.max(0, finite(input.length, 0));\n const wavelength = Math.max(1e-3, finite(input.wavelength, 1));\n const amplitude = Math.max(0, finite(input.amplitude, 0));\n const unit = Math.max(1e-3, finite(input.unit, 1));\n const shift = 2 * Math.PI * finite(input.phase, 0);\n if (shape === \"zigzag\") {\n return getZigzagCurve(length, wavelength, amplitude, shift);\n }\n const k = (2 * Math.PI) / wavelength;\n const gate = smoothstep(amplitude / (LOOP_FLOOR * unit));\n const reach = (REACH[shape] / k) * gate;\n const fine = wavelength / (SAMPLES[shape] * Math.max(1, unit));\n const coarsest = Math.max(length / MIN_POINTS, 1e-6);\n const step = clamp(fine, length / (MAX_POINTS - 2), coarsest);\n const sample = (s: number): SquigglePoint => {\n const w = getSquiggleEnvelope(s, length, wavelength);\n const theta = k * s - shift;\n if (shape === \"wave\") return { x: s, y: amplitude * w * Math.sin(theta) };\n const along = s - reach * w * Math.sin(theta);\n return { x: along, y: -amplitude * w * Math.cos(theta) };\n };\n const offset = (((shift / k) % step) + step) % step;\n const points = [sample(0)];\n for (let j = 0; points.length < MAX_POINTS - 1; j++) {\n const s = offset + j * step;\n if (s >= length) break;\n if (s > 0) points.push(sample(s));\n }\n points.push(sample(length));\n return points;\n}\n\nexport function getSquiggleTrim(\n points: readonly SquigglePoint[],\n tail: number,\n head: number,\n) {\n const lengths = [0];\n for (let i = 1; i < points.length; i++) {\n const a = points[i - 1];\n const b = points[i];\n lengths.push(lengths[i - 1] + Math.hypot(b.x - a.x, b.y - a.y));\n }\n const last = points.length - 1;\n const total = last > 0 ? lengths[last] : 0;\n const from = clamp(finite(tail, 0), 0, 1) * total;\n const to = clamp(finite(head, 0), 0, 1) * total;\n const trimmed: SquigglePoint[] = [];\n if (last < 1 || !(to - from > EPSILON)) return { total, points: trimmed };\n const pointAt = (distance: number, index: number): SquigglePoint => {\n const a = points[index - 1];\n const b = points[index];\n const span = lengths[index] - lengths[index - 1];\n const t = span > 0 ? (distance - lengths[index - 1]) / span : 0;\n return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };\n };\n let index = 1;\n while (index < last && lengths[index] < from) index++;\n trimmed.push(pointAt(from, index));\n while (index < last && lengths[index] < to) {\n trimmed.push(points[index]);\n index++;\n }\n trimmed.push(pointAt(to, index));\n return { total, points: trimmed };\n}\n\nexport function getSquigglePath(points: readonly SquigglePoint[]) {\n let path = \"\";\n let previous = \"\";\n for (const point of points) {\n const pair = `${round(point.x)} ${round(point.y)}`;\n if (pair === previous) continue;\n path += `${path === \"\" ? \"M\" : \"L\"}${pair}`;\n previous = pair;\n }\n return path;\n}\n\nexport function getSquiggleState(frame: number, options: SquiggleOptions = {}) {\n const width = Math.max(1, finite(options.width, 1280));\n const height = Math.max(1, finite(options.height, 720));\n const unit = height / 720;\n const shape = shapeOf(options.shape);\n const timeline = getSquiggleTimeline(options);\n const time = getSquiggleTime(frame, options);\n const head = getSquiggleHead(time);\n const tail = getSquiggleTail(time, timeline);\n const phase = getSquigglePhase(time, timeline);\n const settle = clamp(finite(options.settle, squiggleDefaults.settle), 0, 1);\n const lively = finite(options.amplitude, squiggleDefaults.amplitude);\n const calm = 1 - settle * getSquiggleCalm(time);\n const amplitude = Math.max(0, lively) * unit * calm;\n const length = Math.max(0, finite(options.length, squiggleDefaults.length));\n const course = length * unit;\n const cycle = finite(options.wavelength, squiggleDefaults.wavelength);\n const wavelength = Math.max(MIN_WAVELENGTH, cycle) * unit;\n const weight = Math.max(0, finite(options.weight, squiggleDefaults.weight));\n const angle = finite(options.angle, squiggleDefaults.angle);\n const radians = (angle * Math.PI) / 180;\n const cos = Math.cos(radians);\n const sin = Math.sin(radians);\n const start = {\n x: finite(options.x, squiggleDefaults.x) * width,\n y: finite(options.y, squiggleDefaults.y) * height,\n };\n const end = { x: start.x + course * cos, y: start.y + course * sin };\n const drawn = head - tail > 0;\n const curve: SquigglePoint[] = drawn\n ? getSquiggleCurve({\n shape,\n length: course,\n wavelength,\n amplitude,\n phase,\n unit,\n })\n : [];\n const placed = curve.map((point) => ({\n x: start.x + point.x * cos - point.y * sin,\n y: start.y + point.x * sin + point.y * cos,\n }));\n const trim = getSquiggleTrim(placed, tail, head);\n const path = getSquigglePath(trim.points);\n return {\n width,\n height,\n unit,\n shape,\n time,\n timeline,\n head,\n tail,\n phase,\n amplitude,\n wavelength,\n length: course,\n strokeWidth: round(weight * unit),\n join: joinOf(shape),\n start,\n end,\n total: trim.total,\n points: trim.points,\n path,\n visible: path.includes(\"L\"),\n };\n}\n\nexport type SquiggleState = ReturnType<typeof getSquiggleState>;\n\nexport function Squiggle({\n shape = squiggleDefaults.shape,\n x = squiggleDefaults.x,\n y = squiggleDefaults.y,\n length = squiggleDefaults.length,\n angle = squiggleDefaults.angle,\n amplitude = squiggleDefaults.amplitude,\n wavelength = squiggleDefaults.wavelength,\n weight = squiggleDefaults.weight,\n color = squiggleDefaults.color,\n settle = squiggleDefaults.settle,\n hold = squiggleDefaults.hold,\n erase = squiggleDefaults.erase,\n delay = squiggleDefaults.delay,\n speed = squiggleDefaults.speed,\n className,\n}: SquiggleProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const state = getSquiggleState(frame, {\n shape,\n x,\n y,\n length,\n angle,\n amplitude,\n wavelength,\n weight,\n settle,\n hold,\n erase,\n delay,\n speed,\n width,\n height,\n fps,\n });\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, pointerEvents: \"none\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n role=\"img\"\n aria-label=\"Squiggle line\"\n style={{ display: \"block\" }}\n >\n {state.visible ? (\n <path\n d={state.path}\n fill=\"none\"\n stroke={color}\n strokeWidth={state.strokeWidth}\n strokeLinecap=\"round\"\n strokeLinejoin={state.join}\n />\n ) : null}\n </svg>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/squiggle.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/stripe-type.json b/registry-artifacts/stripe-type.jsonnew file mode 100644index 00000000..37037f68--- /dev/null+++ b/registry-artifacts/stripe-type.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "stripe-type",+ "title": "Stripe Type",+ "description": "A word cut into horizontal bands, as in the IBM logo, slides together from alternating sides and locks, then can pass on through.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/stripe-type/index.tsx",+ "content": "\"use client\";\n\nimport { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { useEffect, useState } from \"react\";\nimport {\n continueRender,\n delayRender,\n Easing,\n interpolate,\n useCurrentFrame,\n useVideoConfig,\n} from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\nexport type StripeTypeSettle = \"striped\" | \"solid\";\n\nexport interface StripeTypeProps {\n text?: string;\n fontSize?: number;\n fontWeight?: number;\n fontFamily?: string;\n color?: string;\n stripes?: number;\n gap?: number;\n settle?: StripeTypeSettle;\n exit?: boolean;\n hold?: number;\n speed?: number;\n className?: string;\n}\n\nexport const stripeTypeDefaults = {\n text: \"Launch\",\n fontSize: 180,\n fontWeight: 800,\n fontFamily: INTER,\n color: \"#fafafa\",\n stripes: 8,\n gap: 0.35,\n settle: \"striped\",\n exit: true,\n hold: 30,\n speed: 1,\n} satisfies Required<Omit<StripeTypeProps, \"className\">>;\n\n/** Beats on the 30 fps clock. */\nexport const stripeTypeTiming = {\n stagger: 2,\n travel: 16,\n close: 10,\n /** Frames of empty screen after the exit in the preview. */\n tail: 10,\n} as const;\n\n/** Ink box of Inter in a `line-height: 1` box, in em from the top, until measured. */\nconst INTER_INK = { top: 0.136, bottom: 0.864 + 0.24 };\nconst MEASURE_SIZE = 100;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\n// Expo-shaped curves that land exactly on 0 and 1 (Easing.exp stops 2⁻¹⁰ short).\nconst easeOutExpo = Easing.bezier(0.16, 1, 0.3, 1);\nconst easeInExpo = Easing.bezier(0.7, 0, 0.84, 0);\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nexport function getStripeTypeTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\nfunction stripeCount(stripes: number | undefined) {\n return Math.max(1, Math.round(finite(stripes, stripeTypeDefaults.stripes)));\n}\n\nexport interface StripeBand {\n /** Top of the band as a share of the ink box height. */\n top: number;\n /** Bottom of the band as a share of the ink box height. */\n bottom: number;\n}\n\n/**\n * Bands over the ink box. With `n` bands and gap share `g` the pitch is\n * `1 / (n − g)`: the first band starts at the top, the last ends at the\n * bottom.\n */\nexport function getStripeBands(stripes: number, gap: number): StripeBand[] {\n const n = stripeCount(stripes);\n const g = Math.min(0.95, Math.max(0, finite(gap, 0)));\n const pitch = 1 / (n - g);\n return Array.from({ length: n }, (_, k) => ({\n top: k * pitch,\n bottom: k * pitch + pitch * (1 - g),\n }));\n}\n\nexport interface StripeTypeTimeline {\n /** Frame where the last band has locked. */\n entered: number;\n /** Frame where the gaps have closed (equals `entered` when striped). */\n settled: number;\n exitStart: number;\n exitEnd: number;\n /** Frames the preview needs. */\n duration: number;\n}\n\nexport function getStripeTypeTimeline(\n options: Pick<StripeTypeProps, \"stripes\" | \"settle\" | \"exit\" | \"hold\"> = {},\n): StripeTypeTimeline {\n const n = stripeCount(options.stripes);\n const { stagger, travel, close, tail } = stripeTypeTiming;\n const entered = stagger * (n - 1) + travel;\n const settled = options.settle === \"solid\" ? entered + close : entered;\n const hold = Math.max(0, finite(options.hold, stripeTypeDefaults.hold));\n const exitStart = settled + hold;\n const exitEnd = exitStart + stagger * (n - 1) + travel;\n const exit = options.exit !== false;\n return {\n entered,\n settled,\n exitStart,\n exitEnd,\n duration: exit ? exitEnd + tail : settled + hold,\n };\n}\n\n/** Preview length for the given options and speed. */\nexport function getStripeTypeDuration(\n options: Pick<\n StripeTypeProps,\n \"stripes\" | \"settle\" | \"exit\" | \"hold\" | \"speed\"\n > = {},\n) {\n const speed = finite(options.speed, 1);\n if (speed <= 0) return 1;\n return Math.ceil(getStripeTypeTimeline(options).duration / speed);\n}\n\n/**\n * Horizontal offset of band `k` as a share of its travel distance: −1 or 1\n * off the frame, 0 locked. Even bands enter from the left, odd from the right,\n * and on the exit each band passes on through the other side.\n */\nexport function getStripeBandOffset(\n t: number,\n k: number,\n options: Pick<StripeTypeProps, \"stripes\" | \"settle\" | \"exit\" | \"hold\"> = {},\n) {\n const { stagger, travel } = stripeTypeTiming;\n const timeline = getStripeTypeTimeline(options);\n const side = k % 2 === 0 ? -1 : 1;\n const inStart = stagger * k;\n const enter = interpolate(t, [inStart, inStart + travel], [1, 0], {\n ...CLAMP,\n easing: easeOutExpo,\n });\n // `|| 0` folds −0 into 0 for a locked band.\n if (options.exit === false) return side * enter || 0;\n const outStart = timeline.exitStart + stagger * k;\n const leave = interpolate(t, [outStart, outStart + travel], [0, 1], {\n ...CLAMP,\n easing: easeInExpo,\n });\n return side * enter - side * leave || 0;\n}\n\n/** Gap share over time: the set gap, closing to 0 when `settle` is solid. */\nexport function getStripeGap(\n t: number,\n gap: number,\n options: Pick<StripeTypeProps, \"stripes\" | \"settle\"> = {},\n) {\n if (options.settle !== \"solid\") return gap;\n const { entered, settled } = getStripeTypeTimeline(options);\n return interpolate(t, [entered, settled], [gap, 0], {\n ...CLAMP,\n easing: easeInOutCubic,\n });\n}\n\n/** Ink box of the word in its `line-height: 1` box, and its width, in em. */\nfunction useInkBox(text: string, font: string) {\n const [ink, setInk] = useState<{\n top: number;\n bottom: number;\n width: number;\n } | null>(null);\n\n useEffect(() => {\n const handle = delayRender(\"stripe-type: measuring the word\");\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n continueRender(handle);\n };\n const measure = () => {\n if (released) return;\n const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n if (ctx) {\n ctx.font = font;\n const m = ctx.measureText(text);\n const ascent = m.fontBoundingBoxAscent / MEASURE_SIZE;\n const descent = m.fontBoundingBoxDescent / MEASURE_SIZE;\n const baseline = (1 - (ascent + descent)) / 2 + ascent;\n if (ascent > 0) {\n setInk({\n top: baseline - m.actualBoundingBoxAscent / MEASURE_SIZE,\n bottom: baseline + m.actualBoundingBoxDescent / MEASURE_SIZE,\n width: m.width / MEASURE_SIZE,\n });\n }\n }\n release();\n };\n document.fonts.load(font, text).then(measure, measure);\n return release;\n }, [text, font]);\n\n return ink;\n}\n\nexport function StripeType({\n text = stripeTypeDefaults.text,\n fontSize = stripeTypeDefaults.fontSize,\n fontWeight = stripeTypeDefaults.fontWeight,\n fontFamily = stripeTypeDefaults.fontFamily,\n color = stripeTypeDefaults.color,\n stripes = stripeTypeDefaults.stripes,\n gap = stripeTypeDefaults.gap,\n settle = stripeTypeDefaults.settle,\n exit = stripeTypeDefaults.exit,\n hold = stripeTypeDefaults.hold,\n speed = stripeTypeDefaults.speed,\n className,\n}: StripeTypeProps) {\n const frame = useCurrentFrame();\n const { fps, width, height } = useVideoConfig();\n const unit = height / 720;\n const size = fontSize * unit;\n const t = getStripeTypeTime(frame, { fps, speed });\n const measured = useInkBox(\n text,\n `${fontWeight} ${MEASURE_SIZE}px ${fontFamily}`,\n );\n const ink = measured ?? {\n ...INTER_INK,\n width: 0.6 * Array.from(text).length,\n };\n const options = { stripes, settle, exit, hold };\n const bands = getStripeBands(stripes, getStripeGap(t, gap, options));\n const inkHeight = ink.bottom - ink.top;\n // Far enough that a band starting on either side is fully off the frame.\n const travel = (width + ink.width * size) / 2 + 0.2 * size;\n\n const type = {\n fontFamily,\n fontSize: size,\n lineHeight: 1,\n fontWeight,\n fontVariationSettings: `\"wght\" ${fontWeight}`,\n color,\n whiteSpace: \"pre\",\n } as const;\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n }}\n >\n <div style={{ position: \"relative\" }}>\n <div aria-hidden style={{ ...type, visibility: \"hidden\" }}>\n {text}\n </div>\n {bands.map((band, k) => {\n const top = (ink.top + band.top * inkHeight) * 100;\n // Each band reaches a pixel into the next gap, so closed gaps leave\n // no antialiased seam between bands.\n const bleed = k < bands.length - 1 ? Math.max(1, unit) / size : 0;\n const bottom =\n (1 - (ink.top + band.bottom * inkHeight) - bleed) * 100;\n const offset = getStripeBandOffset(t, k, options);\n return (\n <div\n key={k}\n aria-hidden={k > 0}\n style={{\n ...type,\n position: \"absolute\",\n inset: 0,\n clipPath: `inset(${top}% -1% ${bottom}% -1%)`,\n transform: `translateX(${offset * travel}px)`,\n }}\n >\n {text}\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/stripe-type.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/trim-burst.json b/registry-artifacts/trim-burst.jsonnew file mode 100644index 00000000..4fd71106--- /dev/null+++ b/registry-artifacts/trim-burst.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "trim-burst",+ "title": "Trim Burst",+ "description": "A ring of short straight strokes shoots out from a point like Trim Paths: each end races ahead on a hard-braking ease-out while its start holds, then chases it on a smoother ease-in-out, so every stroke grows, travels and zips shut at its outer distance.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/trim-burst/index.tsx",+ "content": "\"use client\";\n\nimport { useMemo } from \"react\";\nimport { Easing, random, useCurrentFrame, useVideoConfig } from \"remotion\";\n\nexport type TrimBurstCap = \"round\" | \"butt\";\n\nexport interface TrimBurstProps {\n x?: number;\n y?: number;\n count?: number;\n innerRadius?: number;\n reach?: number;\n strokeLength?: number;\n weight?: number;\n rotation?: number;\n spread?: number;\n jitter?: number;\n dots?: boolean;\n cap?: TrimBurstCap;\n color?: string;\n seed?: number;\n delay?: number;\n speed?: number;\n className?: string;\n}\n\ntype Paint = \"color\" | \"className\";\n\nexport interface TrimBurstOptions extends Omit<TrimBurstProps, Paint> {\n width?: number;\n height?: number;\n fps?: number;\n}\n\nexport interface TrimBurstStroke {\n index: number;\n angle: number;\n scale: number;\n launch: number;\n}\n\nexport interface TrimBurstTrim {\n start: number;\n end: number;\n length: number;\n}\n\nexport interface TrimBurstLine {\n index: number;\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n width: number;\n}\n\nexport interface TrimBurstDot {\n index: number;\n cx: number;\n cy: number;\n r: number;\n}\n\nexport const trimBurstDefaults: Required<Omit<TrimBurstProps, \"className\">> = {\n x: 0.5,\n y: 0.5,\n count: 8,\n innerRadius: 16,\n reach: 64,\n strokeLength: 56,\n weight: 2,\n rotation: 0,\n spread: 360,\n jitter: 0.5,\n dots: false,\n cap: \"round\",\n color: \"#ffffff\",\n seed: 1,\n delay: 0,\n speed: 1,\n};\n\nconst LIFE = 15;\nconst LAG = 3;\nconst STAGGER = 6;\nconst HOLD = 24;\nconst LEASH = 6;\nconst WOBBLE = 0.25;\nconst MAX_STEP = 45;\nconst SHRINK = 0.45;\nconst DOT_START = 4;\nconst DOT_POP = 4;\nconst DOT_BACK = 1.4;\nconst DOT_RADIUS = 1.25;\nconst DOT_GAP = 2;\nconst MAX_COUNT = 32;\nconst MAX_SIZE = 2000;\nconst MIN_STROKE = 1;\nconst MIN_WEIGHT = 0.25;\nconst MAX_WEIGHT = 24;\nconst VISIBLE = 0.001;\nconst END_EASE = Easing.bezier(0.16, 1, 0.3, 1);\nconst START_EASE = Easing.bezier(0.45, 0, 0.55, 1);\n\nconst finite = (value: number | undefined, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst within = (\n value: number | undefined,\n fallback: number,\n min: number,\n max: number,\n) => clamp(finite(value, fallback), min, max);\nconst round = (value: number) => Math.round(value * 1000) / 1000;\nconst rateOf = (speed: number | undefined) =>\n Math.max(0, finite(speed, trimBurstDefaults.speed));\nconst delayOf = (delay: number | undefined) =>\n Math.max(0, finite(delay, trimBurstDefaults.delay));\nconst countOf = (count: number | undefined) =>\n Math.round(within(count, trimBurstDefaults.count, 1, MAX_COUNT));\nconst jitterOf = (jitter: number | undefined) =>\n within(jitter, trimBurstDefaults.jitter, 0, 1);\nconst capOf = (cap: string | undefined): TrimBurstCap =>\n cap === \"butt\" ? cap : \"round\";\n\nexport function getTrimBurstTimeline(\n options: Pick<TrimBurstOptions, \"count\" | \"jitter\"> = {},\n) {\n const count = countOf(options.count);\n const stagger = count > 1 ? STAGGER * jitterOf(options.jitter) : 0;\n return { life: LIFE, lag: LAG, stagger, length: LIFE + stagger };\n}\n\nexport type TrimBurstTimeline = ReturnType<typeof getTrimBurstTimeline>;\n\nexport const trimBurstLength = getTrimBurstTimeline().length;\n\nexport function getTrimBurstDuration(\n options: Pick<TrimBurstOptions, \"count\" | \"jitter\" | \"delay\" | \"speed\"> = {},\n) {\n const rate = rateOf(options.speed);\n const { length } = getTrimBurstTimeline(options);\n const motion = rate === 0 ? 0 : length / rate;\n return Math.ceil(round(delayOf(options.delay) + motion)) + HOLD;\n}\n\nexport function getTrimBurstTime(\n frame: number,\n options: Pick<TrimBurstOptions, \"fps\" | \"delay\" | \"speed\"> = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const elapsed = Math.max(0, finite(frame, 0) - delayOf(options.delay));\n return elapsed * (30 / fps) * rateOf(options.speed);\n}\n\nexport function getTrimBurstEndProgress(time: number) {\n if (Number.isNaN(time) || time <= 0) return 0;\n if (time >= LIFE) return 1;\n return END_EASE(time / LIFE);\n}\n\nexport function getTrimBurstStartProgress(time: number) {\n if (Number.isNaN(time) || time <= LAG) return 0;\n if (time >= LIFE) return 1;\n return START_EASE((time - LAG) / (LIFE - LAG));\n}\n\nexport function getTrimBurstLeash(gap: number, strokeLength: number) {\n if (!(gap > 0 && strokeLength > 0)) return 0;\n return gap / (1 + (gap / strokeLength) ** LEASH) ** (1 / LEASH);\n}\n\nexport function getTrimBurstTrim(\n time: number,\n reach: number,\n strokeLength: number,\n): TrimBurstTrim {\n const distance = Math.max(0, finite(reach, 0));\n const end = distance * getTrimBurstEndProgress(time);\n const own = distance * getTrimBurstStartProgress(time);\n const length = getTrimBurstLeash(end - own, strokeLength);\n return { start: end - length, end, length };\n}\n\nexport function getTrimBurstDotScale(time: number) {\n if (Number.isNaN(time) || time <= DOT_START || time >= LIFE) return 0;\n const pop = Math.min(1, (time - DOT_START) / DOT_POP) - 1;\n const grow = 1 + (DOT_BACK + 1) * pop ** 3 + DOT_BACK * pop ** 2;\n const settle = DOT_START + DOT_POP;\n const shrink = clamp((time - settle) / (LIFE - settle), 0, 1);\n return grow * (1 - shrink ** 3);\n}\n\nexport function getTrimBurstStrokes(\n options: Pick<\n TrimBurstOptions,\n \"count\" | \"rotation\" | \"spread\" | \"jitter\" | \"seed\"\n > = {},\n): TrimBurstStroke[] {\n const count = countOf(options.count);\n const rotation = finite(options.rotation, trimBurstDefaults.rotation);\n const spread = within(options.spread, trimBurstDefaults.spread, 0, 360);\n const jitter = jitterOf(options.jitter);\n const seed = finite(options.seed, trimBurstDefaults.seed);\n const fan = spread < 360 && count > 1;\n const step = fan ? spread / (count - 1) : 360 / count;\n const first = fan ? rotation - spread / 2 : rotation;\n const wobble = WOBBLE * jitter * Math.min(step, MAX_STEP);\n const { stagger } = getTrimBurstTimeline({ count, jitter });\n const keys = Array.from({ length: count }, (_, index) =>\n random(`trim-burst-${seed}-order-${index}`),\n );\n const order = keys.map((_, index) => index);\n order.sort((a, b) => keys[a] - keys[b]);\n const ranks: number[] = [];\n for (const [position, index] of order.entries()) ranks[index] = position;\n return keys.map((_, index) => {\n const turn = random(`trim-burst-${seed}-angle-${index}`) * 2 - 1;\n const shrink = random(`trim-burst-${seed}-scale-${index}`);\n return {\n index,\n angle: first + index * step + turn * wobble,\n scale: 1 - SHRINK * jitter * shrink,\n launch: count > 1 ? (stagger * ranks[index]) / (count - 1) : 0,\n };\n });\n}\n\nexport function getTrimBurstState(\n frame: number,\n options: TrimBurstOptions = {},\n strokes: TrimBurstStroke[] = getTrimBurstStrokes(options),\n) {\n const fallback = trimBurstDefaults;\n const width = Math.max(1, finite(options.width, 1280));\n const height = Math.max(1, finite(options.height, 720));\n const unit = height / 720;\n const time = getTrimBurstTime(frame, options);\n const originX = finite(options.x, fallback.x) * width;\n const originY = finite(options.y, fallback.y) * height;\n const inner = within(options.innerRadius, fallback.innerRadius, 0, MAX_SIZE);\n const reach = within(options.reach, fallback.reach, 0, MAX_SIZE);\n const strokeLength = within(\n options.strokeLength,\n fallback.strokeLength,\n MIN_STROKE,\n MAX_SIZE,\n );\n const size = within(options.weight, fallback.weight, MIN_WEIGHT, MAX_WEIGHT);\n const offset = inner * unit;\n const weight = size * unit;\n const gap = DOT_GAP * weight;\n const radius = DOT_RADIUS * weight;\n const lines: TrimBurstLine[] = [];\n const dots: TrimBurstDot[] = [];\n for (const stroke of strokes) {\n const local = time - stroke.launch;\n const trim = getTrimBurstTrim(\n local,\n reach * unit * stroke.scale,\n strokeLength * unit * stroke.scale,\n );\n const angle = (stroke.angle * Math.PI) / 180;\n const dx = Math.sin(angle);\n const dy = -Math.cos(angle);\n const along = (distance: number) => ({\n x: round(originX + dx * (offset + distance)),\n y: round(originY + dy * (offset + distance)),\n });\n if (trim.length > VISIBLE) {\n const from = along(trim.start);\n const to = along(trim.end);\n lines.push({\n index: stroke.index,\n x1: from.x,\n y1: from.y,\n x2: to.x,\n y2: to.y,\n width: round(Math.min(weight, trim.length)),\n });\n }\n const pop = options.dots === true ? getTrimBurstDotScale(local) : 0;\n if (pop > 0) {\n const center = along(trim.end + gap + radius);\n dots.push({\n index: stroke.index,\n cx: center.x,\n cy: center.y,\n r: round(radius * pop),\n });\n }\n }\n return {\n width,\n height,\n unit,\n time,\n originX,\n originY,\n weight,\n cap: capOf(options.cap),\n lines,\n dots,\n };\n}\n\nexport type TrimBurstState = ReturnType<typeof getTrimBurstState>;\n\nexport function TrimBurst({\n x = trimBurstDefaults.x,\n y = trimBurstDefaults.y,\n count = trimBurstDefaults.count,\n innerRadius = trimBurstDefaults.innerRadius,\n reach = trimBurstDefaults.reach,\n strokeLength = trimBurstDefaults.strokeLength,\n weight = trimBurstDefaults.weight,\n rotation = trimBurstDefaults.rotation,\n spread = trimBurstDefaults.spread,\n jitter = trimBurstDefaults.jitter,\n dots = trimBurstDefaults.dots,\n cap = trimBurstDefaults.cap,\n color = trimBurstDefaults.color,\n seed = trimBurstDefaults.seed,\n delay = trimBurstDefaults.delay,\n speed = trimBurstDefaults.speed,\n className,\n}: TrimBurstProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const strokes = useMemo(\n () => getTrimBurstStrokes({ count, rotation, spread, jitter, seed }),\n [count, rotation, spread, jitter, seed],\n );\n const state = getTrimBurstState(\n frame,\n {\n width,\n height,\n fps,\n x,\n y,\n innerRadius,\n reach,\n strokeLength,\n weight,\n dots,\n cap,\n delay,\n speed,\n },\n strokes,\n );\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, pointerEvents: \"none\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n role=\"img\"\n aria-label=\"Trim burst\"\n style={{ display: \"block\", overflow: \"visible\" }}\n >\n <g fill=\"none\" stroke={color} strokeLinecap={state.cap}>\n {state.lines.map((line) => (\n <line\n key={line.index}\n x1={line.x1}\n y1={line.y1}\n x2={line.x2}\n y2={line.y2}\n strokeWidth={line.width}\n />\n ))}\n </g>\n <g fill={color}>\n {state.dots.map((dot) => (\n <circle key={dot.index} cx={dot.cx} cy={dot.cy} r={dot.r} />\n ))}\n </g>\n </svg>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/trim-burst.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/truchet-flip.json b/registry-artifacts/truchet-flip.jsonnew file mode 100644index 00000000..cd2ac5cb--- /dev/null+++ b/registry-artifacts/truchet-flip.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "truchet-flip",+ "title": "Truchet Flip",+ "description": "Quarter-circle Truchet tiles snap a quarter turn as a wave crosses the grid, rerouting continuous lines until they settle into concentric loops, a calm field, or a circle of small rings.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "registry/remocn/truchet-flip/index.tsx",+ "content": "\"use client\";\n\nimport { useMemo } from \"react\";\nimport { random, useCurrentFrame, useVideoConfig } from \"remotion\";\n\nexport type TruchetFlipWaveMode = \"radial\" | \"diagonal\" | \"random\";\nexport type TruchetFlipResolve = \"rings\" | \"field\" | \"silhouette\";\nexport type TruchetFlipVariant = \"stroke\" | \"filled\";\nexport type TruchetFlipOrientation = 0 | 1;\n\nexport interface TruchetFlipProps {\n tiles?: number;\n weight?: number;\n passes?: number;\n waveMode?: TruchetFlipWaveMode;\n resolve?: TruchetFlipResolve;\n variant?: TruchetFlipVariant;\n color?: string;\n secondaryColor?: string;\n seed?: number;\n speed?: number;\n loop?: boolean;\n className?: string;\n}\n\ntype Paint = \"color\" | \"secondaryColor\" | \"className\";\ntype Unset = \"secondaryColor\" | \"className\";\n\nexport interface TruchetFlipOptions extends Omit<TruchetFlipProps, Paint> {\n width?: number;\n height?: number;\n fps?: number;\n}\n\nexport interface TruchetFlipTile {\n col: number;\n row: number;\n x: number;\n y: number;\n alternate: boolean;\n initial: TruchetFlipOrientation;\n target: TruchetFlipOrientation;\n delay: number;\n}\n\nexport const truchetFlipDefaults: Required<Omit<TruchetFlipProps, Unset>> = {\n tiles: 10,\n weight: 0.2,\n passes: 2,\n waveMode: \"radial\",\n resolve: \"rings\",\n variant: \"stroke\",\n color: \"#ffffff\",\n seed: 1,\n speed: 1,\n loop: false,\n};\n\nconst LEAD = 6;\nconst SPREAD = 30;\nconst SNAP = 12;\nconst SNAP_SETTLE = 8;\nconst SNAP_RISE = 4;\nconst SNAP_DAMPING = 0.65;\nconst GAP = 24;\nconst RESOLVE_GAP = 30;\nconst HOLD = 18;\nconst LOOP_HOLD = 24;\nconst MAX_PASSES = 4;\nconst MIN_TILES = 4;\nconst MAX_TILES = 24;\nconst MIN_WEIGHT = 0.04;\nconst MAX_WEIGHT = 0.34;\nconst SILHOUETTE = 0.38;\nconst OVERLAP = 0.75;\nconst SNAP_FREQUENCY = (Math.PI - Math.acos(SNAP_DAMPING)) / SNAP_RISE;\nconst SNAP_RATIO = SNAP_DAMPING / Math.sqrt(1 - SNAP_DAMPING ** 2);\n\nconst finite = (value: number | undefined, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\nconst round = (value: number) => Math.round(value * 1000) / 1000;\nconst isOdd = (value: number) => Math.abs(value % 2) === 1;\nconst turn = (wave: number) => (wave % 2 === 0 ? 1 : -1);\nconst rateOf = (speed: number | undefined) =>\n Math.max(0, finite(speed, truchetFlipDefaults.speed));\nconst waveOf = (value: string | undefined): TruchetFlipWaveMode =>\n value === \"diagonal\" || value === \"random\" ? value : \"radial\";\nconst resolveOf = (value: string | undefined): TruchetFlipResolve =>\n value === \"field\" || value === \"silhouette\" ? value : \"rings\";\nconst variantOf = (value: string | undefined): TruchetFlipVariant =>\n value === \"filled\" ? value : \"stroke\";\n\nfunction smoothstep(value: number) {\n const t = clamp(value, 0, 1);\n return t * t * (3 - 2 * t);\n}\n\nfunction mazeKey(seed: number, col: number, row: number) {\n return random(`truchet-flip-${seed}-${col}-${row}`);\n}\n\nfunction waveKey(seed: number, col: number, row: number) {\n return random(`truchet-flip-${seed}-wave-${col}-${row}`);\n}\n\nexport function getTruchetFlipSnap(frames: number) {\n if (Number.isNaN(frames) || frames <= 0) return 0;\n if (frames >= SNAP) return 1;\n const phase = SNAP_FREQUENCY * frames;\n const decay = Math.exp(-SNAP_RATIO * phase);\n const ring = decay * (Math.cos(phase) + SNAP_RATIO * Math.sin(phase));\n const settle = smoothstep((frames - SNAP_SETTLE) / (SNAP - SNAP_SETTLE));\n return 1 - ring * (1 - settle);\n}\n\nexport function getTruchetFlipTimeline(options: TruchetFlipOptions = {}) {\n const requested = finite(options.passes, truchetFlipDefaults.passes);\n const passes = Math.round(clamp(requested, 0, MAX_PASSES));\n const starts = Array.from({ length: passes }, (_, i) => LEAD + i * GAP);\n const lastPass = LEAD + Math.max(0, passes - 1) * GAP;\n const resolveStart = passes === 0 ? LEAD : lastPass + RESOLVE_GAP;\n const settled = resolveStart + SPREAD + SNAP;\n const returnStart = settled + LOOP_HOLD;\n const loop = options.loop === true;\n const duration = loop ? returnStart + SPREAD + SNAP : settled + HOLD;\n return {\n passes,\n starts,\n resolveStart,\n settled,\n returnStart,\n loop,\n duration,\n };\n}\n\nexport type TruchetFlipTimeline = ReturnType<typeof getTruchetFlipTimeline>;\n\nexport const truchetFlipLength = getTruchetFlipTimeline().settled;\n\nexport function getTruchetFlipDuration(options: TruchetFlipOptions = {}) {\n const rate = rateOf(options.speed);\n const { duration } = getTruchetFlipTimeline(options);\n return rate === 0 ? 1 : Math.max(1, Math.ceil(duration / rate));\n}\n\nexport function getTruchetFlipTime(\n frame: number,\n options: TruchetFlipOptions = {},\n) {\n const scale = 30 / Math.max(1, finite(options.fps, 30));\n const time = Math.max(0, finite(frame, 0)) * scale * rateOf(options.speed);\n const { duration, loop } = getTruchetFlipTimeline(options);\n return loop ? time % duration : time;\n}\n\nexport function getTruchetFlipTarget(\n resolve: TruchetFlipResolve,\n col: number,\n row: number,\n tiles = truchetFlipDefaults.tiles,\n): TruchetFlipOrientation {\n if (resolve === \"field\") return 0;\n if (resolve === \"silhouette\") {\n const inside = Math.hypot(col + 0.5, row + 0.5) < tiles * SILHOUETTE;\n return inside && isOdd(col + row) ? 1 : 0;\n }\n const left = col < 0;\n const above = row < 0;\n return left === above ? 0 : 1;\n}\n\nexport function getTruchetFlipGrid(options: TruchetFlipOptions = {}) {\n const width = Math.max(1, finite(options.width, 1280));\n const height = Math.max(1, finite(options.height, 720));\n const requested = finite(options.tiles, truchetFlipDefaults.tiles);\n const count = Math.round(clamp(requested, MIN_TILES, MAX_TILES));\n const size = Math.min(width, height) / count;\n const halfCols = Math.ceil(width / 2 / size - 1e-6);\n const halfRows = Math.ceil(height / 2 / size - 1e-6);\n const seed = finite(options.seed, truchetFlipDefaults.seed);\n const mode = waveOf(options.waveMode);\n const resolve = resolveOf(options.resolve);\n const cells: { col: number; row: number }[] = [];\n for (let row = -halfRows; row < halfRows; row++) {\n for (let col = -halfCols; col < halfCols; col++) cells.push({ col, row });\n }\n const ranks: number[] = [];\n if (mode === \"random\") {\n const keys = cells.map(({ col, row }) => waveKey(seed, col, row));\n const order = keys.map((_, index) => index);\n order.sort((a, b) => keys[a] - keys[b]);\n for (const [position, index] of order.entries()) ranks[index] = position;\n }\n const shift = halfCols + halfRows;\n const diagonals = 2 * (shift - 1);\n const nearest = Math.hypot(0.5, 0.5);\n const farthest = Math.hypot(halfCols - 0.5, halfRows - 0.5);\n const delayOf = (col: number, row: number, index: number) => {\n if (mode === \"random\") {\n return (SPREAD * ranks[index]) / (cells.length - 1);\n }\n if (mode === \"diagonal\") {\n return (SPREAD * (col + row + shift)) / diagonals;\n }\n const distance = Math.hypot(col + 0.5, row + 0.5) - nearest;\n return (SPREAD * distance) / Math.max(1e-6, farthest - nearest);\n };\n const tiles: TruchetFlipTile[] = cells.map(({ col, row }, index) => ({\n col,\n row,\n x: round(width / 2 + (col + 0.5) * size),\n y: round(height / 2 + (row + 0.5) * size),\n alternate: isOdd(col + row),\n initial: mazeKey(seed, col, row) < 0.5 ? 0 : 1,\n target: getTruchetFlipTarget(resolve, col, row, count),\n delay: round(clamp(delayOf(col, row, index), 0, SPREAD)),\n }));\n return {\n width,\n height,\n count,\n size,\n unit: Math.min(width, height) / 720,\n tiles,\n };\n}\n\nexport type TruchetFlipGrid = ReturnType<typeof getTruchetFlipGrid>;\n\nexport function getTruchetFlipAngle(\n tile: TruchetFlipTile,\n time: number,\n timeline: TruchetFlipTimeline,\n) {\n let turns = 0;\n for (const [wave, start] of timeline.starts.entries()) {\n turns += turn(wave) * getTruchetFlipSnap(time - start - tile.delay);\n }\n const reached = (tile.initial + timeline.passes) % 2;\n if (reached !== tile.target) {\n const since = time - timeline.resolveStart - tile.delay;\n turns += turn(timeline.passes) * getTruchetFlipSnap(since);\n }\n if (timeline.loop && tile.target !== tile.initial) {\n const since = time - timeline.returnStart - tile.delay;\n turns += turn(timeline.passes + 1) * getTruchetFlipSnap(since);\n }\n return (tile.initial + turns) * 90;\n}\n\nexport function getTruchetFlipTilePath(\n size: number,\n variant: TruchetFlipVariant = \"stroke\",\n overlap = OVERLAP,\n) {\n const half = Math.max(0, finite(size, 0)) / 2;\n const pad = clamp(finite(overlap, OVERLAP), 0, half / 4);\n const radius = `${round(half)} ${round(half)}`;\n const point = (x: number, y: number) => `${round(x)} ${round(y)}`;\n if (variant === \"filled\") {\n const reach = Math.sqrt(half * half - pad * pad);\n const sector = (cx: number, cy: number, side: number) => {\n const corner = point(cx - side * pad, cy - side * pad);\n const start = point(cx + side * reach, cy - side * pad);\n const end = point(cx - side * pad, cy + side * reach);\n return `M ${corner} L ${start} A ${radius} 0 0 1 ${end} Z`;\n };\n return `${sector(-half, -half, 1)} ${sector(half, half, -1)}`;\n }\n const bend = half > 0 ? pad / half : 0;\n const cos = half * Math.cos(bend);\n const sin = half * Math.sin(bend);\n const arc = (cx: number, cy: number, side: number) => {\n const start = point(cx + side * cos, cy - side * sin);\n const end = point(cx - side * sin, cy + side * cos);\n return `M ${start} A ${radius} 0 0 1 ${end}`;\n };\n return `${arc(-half, -half, 1)} ${arc(half, half, -1)}`;\n}\n\nexport function getTruchetFlipState(\n frame: number,\n options: TruchetFlipOptions = {},\n grid: TruchetFlipGrid = getTruchetFlipGrid(options),\n) {\n const timeline = getTruchetFlipTimeline(options);\n const time = getTruchetFlipTime(frame, options);\n const variant = variantOf(options.variant);\n const requested = finite(options.weight, truchetFlipDefaults.weight);\n const weight = clamp(requested, MIN_WEIGHT, MAX_WEIGHT);\n return {\n ...grid,\n time,\n timeline,\n variant,\n strokeWidth: round(grid.size * weight),\n path: getTruchetFlipTilePath(grid.size, variant, OVERLAP * grid.unit),\n tiles: grid.tiles.map((tile) => {\n const angle = getTruchetFlipAngle(tile, time, timeline);\n const rotation = round(angle);\n const transform = `translate(${tile.x} ${tile.y}) rotate(${rotation})`;\n return { ...tile, angle, transform };\n }),\n };\n}\n\nexport function TruchetFlip({\n tiles = truchetFlipDefaults.tiles,\n weight = truchetFlipDefaults.weight,\n passes = truchetFlipDefaults.passes,\n waveMode = truchetFlipDefaults.waveMode,\n resolve = truchetFlipDefaults.resolve,\n variant = truchetFlipDefaults.variant,\n color = truchetFlipDefaults.color,\n secondaryColor,\n seed = truchetFlipDefaults.seed,\n speed = truchetFlipDefaults.speed,\n loop = truchetFlipDefaults.loop,\n className,\n}: TruchetFlipProps) {\n const frame = useCurrentFrame();\n const { width, height, fps } = useVideoConfig();\n const grid = useMemo(() => {\n const layout = { width, height, tiles, seed, waveMode, resolve };\n return getTruchetFlipGrid(layout);\n }, [width, height, tiles, seed, waveMode, resolve]);\n const motion = { fps, weight, passes, variant, speed, loop };\n const state = getTruchetFlipState(frame, motion, grid);\n const filled = state.variant === \"filled\";\n const primary = state.tiles.filter((tile) => !tile.alternate);\n const alternate = state.tiles.filter((tile) => tile.alternate);\n const layers = [\n { key: \"primary\", paint: color, tiles: primary },\n { key: \"alternate\", paint: secondaryColor ?? color, tiles: alternate },\n ];\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n <svg\n width=\"100%\"\n height=\"100%\"\n viewBox={`0 0 ${width} ${height}`}\n role=\"img\"\n aria-label=\"Truchet tile pattern\"\n style={{ display: \"block\" }}\n >\n {layers.map((layer) => (\n <g\n key={layer.key}\n fill={filled ? layer.paint : \"none\"}\n stroke={filled ? \"none\" : layer.paint}\n strokeWidth={filled ? undefined : state.strokeWidth}\n >\n {layer.tiles.map((tile) => (\n <path\n key={`${tile.col}:${tile.row}`}\n d={state.path}\n transform={tile.transform}\n />\n ))}\n </g>\n ))}\n </svg>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/truchet-flip.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/type-repeater.json b/registry-artifacts/type-repeater.jsonnew file mode 100644index 00000000..85827004--- /dev/null+++ b/registry-artifacts/type-repeater.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "type-repeater",+ "title": "Type Repeater",+ "description": "An After Effects style repeater on a word, where copies unfold into a tunnel, a spiral or a fan behind it, breathe, then fold back into the word.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/type-repeater/index.tsx",+ "content": "\"use client\";\n\nimport { loadFont } from \"@remotion/google-fonts/Inter\";\nimport { useId } from \"react\";\nimport {\n Easing,\n interpolate,\n interpolateColors,\n useCurrentFrame,\n useVideoConfig,\n} from \"remotion\";\n\nconst { fontFamily: INTER } = loadFont(\"normal\", {\n weights: [\"100\", \"900\"],\n subsets: [\"latin\"],\n});\n\nexport type TypeRepeaterMode = \"fan\" | \"spiral\" | \"tunnel\";\n\nexport interface TypeRepeaterProps {\n text?: string;\n copies?: number;\n mode?: TypeRepeaterMode;\n fontSize?: number;\n fontWeight?: number;\n fontFamily?: string;\n color?: string;\n accent?: string;\n outline?: boolean;\n speed?: number;\n className?: string;\n}\n\nexport const typeRepeaterDefaults = {\n text: \"Repeat\",\n copies: 12,\n mode: \"tunnel\",\n fontSize: 110,\n fontWeight: 800,\n fontFamily: INTER,\n color: \"#fafafa\",\n accent: \"#D97757\",\n outline: true,\n speed: 1,\n} satisfies Required<Omit<TypeRepeaterProps, \"className\">>;\n\n/** Beats on the 30 fps clock. */\nexport const typeRepeaterTiming = {\n intro: [0, 10],\n unfold: [10, 34],\n breathe: [34, 70],\n collapse: [70, 90],\n} as const;\n\n/** Frame where the copies have folded back into the word. */\nexport const typeRepeaterLength = typeRepeaterTiming.collapse[1];\n\n/**\n * Per-copy steps for each mode. `fan` alternates sides around a pivot below\n * the word; `spiral` and `tunnel` grow each copy outward behind it.\n */\nexport const typeRepeaterModes = {\n fan: { rotate: 11, scale: 1, pivot: 2.6, symmetric: true },\n spiral: { rotate: 12, scale: 1.1, pivot: 0, symmetric: false },\n tunnel: { rotate: 0, scale: 1.2, pivot: 0, symmetric: false },\n} as const satisfies Record<\n TypeRepeaterMode,\n { rotate: number; scale: number; pivot: number; symmetric: boolean }\n>;\n\nconst BREATHE = 0.06;\nconst FADE = 0.85;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutCubic = Easing.out(Easing.cubic);\nconst easeInOutCubic = Easing.inOut(Easing.cubic);\nconst unfoldEase = Easing.out(Easing.back(1.4));\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nexport function getTypeRepeaterTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\n/** How far the copies have spread, 0 (one word) to about 1. */\nexport function getTypeRepeaterSpread(t: number) {\n const { unfold, breathe, collapse } = typeRepeaterTiming;\n if (t < breathe[0]) {\n return interpolate(t, [...unfold], [0, 1], {\n ...CLAMP,\n easing: unfoldEase,\n });\n }\n if (t < breathe[1]) {\n const phase = (t - breathe[0]) / (breathe[1] - breathe[0]);\n return 1 + BREATHE * Math.sin(2 * Math.PI * phase);\n }\n return interpolate(t, [...collapse], [1, 0], {\n ...CLAMP,\n easing: easeInOutCubic,\n });\n}\n\n/** Entrance of the front word, 0..1. */\nexport function getTypeRepeaterIntro(t: number) {\n return interpolate(t, [...typeRepeaterTiming.intro], [0, 1], {\n ...CLAMP,\n easing: easeOutCubic,\n });\n}\n\nexport interface TypeRepeaterCopy {\n rotate: number;\n scale: number;\n opacity: number;\n /** 0 for the word's color, 1 for the accent. */\n tint: number;\n}\n\n/** Transform and fade of copy `index` (0 is the word itself). */\nexport function getTypeRepeaterCopy(\n index: number,\n copies: number,\n spread: number,\n mode: TypeRepeaterMode,\n): TypeRepeaterCopy {\n const step = typeRepeaterModes[mode] ?? typeRepeaterModes.spiral;\n const n = Math.max(1, Math.round(copies));\n const steps = step.symmetric ? Math.ceil(index / 2) : index;\n const side = step.symmetric && index % 2 === 0 ? -1 : 1;\n const reach = steps * spread;\n return {\n rotate: side * step.rotate * reach || 0,\n scale: step.scale ** reach,\n opacity:\n index === 0\n ? 1\n : (1 - (FADE * index) / n) * Math.min(1, Math.max(0, spread * 4)),\n tint: n > 1 ? index / (n - 1) : 0,\n };\n}\n\nexport function TypeRepeater({\n text = typeRepeaterDefaults.text,\n copies = typeRepeaterDefaults.copies,\n mode = typeRepeaterDefaults.mode,\n fontSize = typeRepeaterDefaults.fontSize,\n fontWeight = typeRepeaterDefaults.fontWeight,\n fontFamily = typeRepeaterDefaults.fontFamily,\n color = typeRepeaterDefaults.color,\n accent = typeRepeaterDefaults.accent,\n outline = typeRepeaterDefaults.outline,\n speed = typeRepeaterDefaults.speed,\n className,\n}: TypeRepeaterProps) {\n const frame = useCurrentFrame();\n const { fps, height } = useVideoConfig();\n const outlineId = `type-repeater-${useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`;\n const unit = height / 720;\n const size = fontSize * unit;\n const t = getTypeRepeaterTime(frame, { fps, speed });\n const spread = getTypeRepeaterSpread(t);\n const intro = getTypeRepeaterIntro(t);\n const count = Math.max(1, Math.round(finite(copies, 12)));\n const pivot = (typeRepeaterModes[mode] ?? typeRepeaterModes.spiral).pivot;\n\n return (\n <div\n className={className}\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n }}\n >\n {outline ? (\n // Outline from the filled silhouette: the variable font's overlapping\n // contours would show through a text stroke.\n <svg width={0} height={0} style={{ position: \"absolute\" }} aria-hidden>\n <defs>\n <filter id={outlineId}>\n <feMorphology\n in=\"SourceAlpha\"\n operator=\"erode\"\n radius={1.5 * unit}\n result=\"inner\"\n />\n <feComposite in=\"SourceGraphic\" in2=\"inner\" operator=\"out\" />\n </filter>\n </defs>\n </svg>\n ) : null}\n <div\n style={{\n position: \"relative\",\n opacity: intro,\n transform: `scale(${0.9 + 0.1 * intro})`,\n }}\n >\n {Array.from({ length: count }, (_, i) => count - 1 - i).map((i) => {\n const copy = getTypeRepeaterCopy(i, count, spread, mode);\n if (copy.opacity <= 0) return null;\n return (\n <div\n key={i}\n aria-hidden={i > 0}\n style={{\n position: i === 0 ? \"relative\" : \"absolute\",\n inset: i === 0 ? undefined : 0,\n fontFamily,\n fontSize: size,\n lineHeight: 1,\n fontWeight,\n fontVariationSettings: `\"wght\" ${fontWeight}`,\n whiteSpace: \"pre\",\n color: interpolateColors(copy.tint, [0, 1], [color, accent]),\n opacity: copy.opacity,\n filter: outline && i > 0 ? `url(#${outlineId})` : undefined,\n transformOrigin: `50% calc(50% + ${pivot}em)`,\n transform: `rotate(${copy.rotate}deg) scale(${copy.scale})`,\n }}\n >\n {text}\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/type-repeater.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry-artifacts/type-wall.json b/registry-artifacts/type-wall.jsonnew file mode 100644index 00000000..f85468b5--- /dev/null+++ b/registry-artifacts/type-wall.json@@ -0,0 +1,16 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "type-wall",+ "title": "Type Wall",+ "description": "Rows of one word fill the frame, run in alternating directions at different speeds in heavy, narrow and outline faces, with an accent band through the middle.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "registry/remocn/type-wall/index.tsx",+ "content": "\"use client\";\n\nimport { loadFont as loadAnton } from \"@remotion/google-fonts/Anton\";\nimport { loadFont as loadInter } from \"@remotion/google-fonts/Inter\";\nimport { useId } from \"react\";\nimport {\n Easing,\n interpolate,\n random,\n useCurrentFrame,\n useVideoConfig,\n} from \"remotion\";\n\nconst { fontFamily: INTER } = loadInter(\"normal\", {\n weights: [\"900\"],\n subsets: [\"latin\"],\n});\nconst { fontFamily: ANTON } = loadAnton(\"normal\", {\n weights: [\"400\"],\n subsets: [\"latin\"],\n});\n\nexport type TypeWallStyle = \"solid\" | \"narrow\" | \"outline\";\n\nexport interface TypeWallProps {\n text?: string;\n separator?: string;\n fontSize?: number;\n color?: string;\n accent?: string;\n accentText?: string;\n seed?: number;\n speed?: number;\n className?: string;\n}\n\nexport const typeWallDefaults = {\n text: \"MOTION\",\n separator: \"·\",\n fontSize: 64,\n color: \"#fafafa\",\n accent: \"#D97757\",\n accentText: \"#0a0a0a\",\n seed: 7,\n speed: 1,\n} satisfies Required<Omit<TypeWallProps, \"className\">>;\n\n/** Row faces away from the center, the accent row always solid. */\nexport const typeWallStyles: readonly TypeWallStyle[] = [\n \"solid\",\n \"narrow\",\n \"outline\",\n];\n\n/** Anton sized so its capitals match Inter's cap height (0.7275 / 0.8594 em). */\nconst NARROW_SCALE = 0.7275 / 0.8594;\n/** Tokens per second at speed 1, before each row's seeded factor. */\nconst TOKENS_PER_SECOND = 0.22;\nconst ENTRANCE = 20;\nconst STAGGER = 2;\n/** Tokens a row streams past on its way in, on top of its cruise. */\nconst ENTRANCE_BURST = 2.5;\nconst BAND = [6, 20] as const;\n/** Lower bound on a token's width per character, in em, for the repeat count. */\nconst MIN_CHAR_WIDTH = 0.4;\nconst MAX_TOKENS = 48;\n\nconst CLAMP = {\n extrapolateLeft: \"clamp\",\n extrapolateRight: \"clamp\",\n} as const;\n\nconst easeOutCubic = Easing.out(Easing.cubic);\n\nfunction finite(value: number | undefined, fallback: number) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\nfunction fract(x: number) {\n return x - Math.floor(x);\n}\n\n/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */\nexport function getTypeWallTime(\n frame: number,\n options: { fps?: number; speed?: number } = {},\n) {\n const fps = Math.max(1, finite(options.fps, 30));\n const speed = Math.max(0, finite(options.speed, 1));\n return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;\n}\n\n/** Row indices from the top of the frame to the bottom; row 0 is centered. */\nexport function getTypeWallRows(height: number, rowHeight: number) {\n const reach = Math.ceil((height / 2 - rowHeight / 2) / rowHeight) + 1;\n const rows: number[] = [];\n for (let k = -reach; k <= reach; k++) rows.push(k);\n return rows;\n}\n\nexport function getTypeWallStyle(row: number): TypeWallStyle {\n if (row === 0) return \"solid\";\n const n = typeWallStyles.length;\n return typeWallStyles[((row % n) + n) % n];\n}\n\n/** −1 runs left, 1 runs right. The accent row runs left. */\nexport function getTypeWallDirection(row: number) {\n return Math.abs(row) % 2 === 0 ? -1 : 1;\n}\n\n/** Cruise speed in tokens per frame and the row's starting phase. */\nexport function getTypeWallMotion(row: number, seed: number) {\n const factor = 0.7 + 0.6 * random(`type-wall-${seed}-speed-${row}`);\n return {\n velocity: (TOKENS_PER_SECOND * factor) / 30,\n phase: random(`type-wall-${seed}-phase-${row}`),\n };\n}\n\nexport interface TypeWallRowState {\n direction: number;\n /** Translation of the token strip in tokens, always in [−1, 0). */\n shift: number;\n /** Share of the row revealed from its entering side, 0..1. */\n reveal: number;\n}\n\nexport function getTypeWallRow(\n t: number,\n row: number,\n seed = typeWallDefaults.seed,\n): TypeWallRowState {\n const direction = getTypeWallDirection(row);\n const { velocity, phase } = getTypeWallMotion(row, seed);\n const e = easeOutCubic(\n Math.min(1, Math.max(0, (t - STAGGER * Math.abs(row)) / ENTRANCE)),\n );\n const travel = phase + velocity * t + ENTRANCE_BURST * e;\n // Leftward rows slide the strip left; rightward rows run it from −1 up to 0.\n const shift = direction < 0 ? -fract(travel) : fract(travel) - 1;\n return { direction, shift: shift || 0, reveal: e };\n}\n\n/** The accent band growing from the center, 0..1. */\nexport function getTypeWallBand(t: number) {\n return interpolate(t, [...BAND], [0, 1], { ...CLAMP, easing: easeOutCubic });\n}\n\n/** Frame where the slowest (outermost) row has finished entering. */\nexport function getTypeWallEntranceEnd(height: number, rowHeight: number) {\n const rows = getTypeWallRows(height, rowHeight);\n return ENTRANCE + STAGGER * Math.max(...rows.map(Math.abs));\n}\n\n/** How many tokens a strip needs to cover the width twice over. */\nexport function getTypeWallTokenCount(\n width: number,\n fontSize: number,\n token: string,\n) {\n const tokenWidth =\n Math.max(1, Array.from(token).length) * MIN_CHAR_WIDTH * fontSize;\n return Math.min(MAX_TOKENS, Math.ceil(width / tokenWidth) + 2);\n}\n\nexport function TypeWall({\n text = typeWallDefaults.text,\n separator = typeWallDefaults.separator,\n fontSize = typeWallDefaults.fontSize,\n color = typeWallDefaults.color,\n accent = typeWallDefaults.accent,\n accentText = typeWallDefaults.accentText,\n seed = typeWallDefaults.seed,\n speed = typeWallDefaults.speed,\n className,\n}: TypeWallProps) {\n const frame = useCurrentFrame();\n const { fps, width, height } = useVideoConfig();\n const unit = height / 720;\n const rowHeight = Math.max(8, fontSize * unit);\n const t = getTypeWallTime(frame, { fps, speed });\n const rows = getTypeWallRows(height, rowHeight);\n const token = `${text} ${separator} `;\n const band = getTypeWallBand(t);\n const outlineId = `type-wall-${useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`;\n\n return (\n <div\n className={className}\n style={{ position: \"absolute\", inset: 0, overflow: \"hidden\" }}\n >\n {/* Outline from the filled silhouette: the variable font's overlapping\n contours would show through a text stroke. */}\n <svg width={0} height={0} style={{ position: \"absolute\" }} aria-hidden>\n <defs>\n <filter id={outlineId}>\n <feMorphology\n in=\"SourceAlpha\"\n operator=\"erode\"\n radius={1.5 * unit}\n result=\"inner\"\n />\n <feComposite\n in=\"SourceAlpha\"\n in2=\"inner\"\n operator=\"out\"\n result=\"ring\"\n />\n <feFlood floodColor={color} />\n <feComposite in2=\"ring\" operator=\"in\" />\n </filter>\n </defs>\n </svg>\n {rows.map((row) => {\n const style = getTypeWallStyle(row);\n const state = getTypeWallRow(t, row, seed);\n const narrow = style === \"narrow\";\n const size = narrow ? rowHeight * NARROW_SCALE : rowHeight;\n const count = getTypeWallTokenCount(width, size, token);\n const onBand = row === 0;\n const hidden = `${(1 - state.reveal) * 100}%`;\n return (\n <div\n key={row}\n style={{\n position: \"absolute\",\n left: 0,\n right: 0,\n top: height / 2 + (row - 0.5) * rowHeight,\n height: rowHeight,\n clipPath:\n state.direction < 0\n ? `inset(0 0 0 ${hidden})`\n : `inset(0 ${hidden} 0 0)`,\n }}\n >\n {onBand ? (\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n background: accent,\n transform: `scaleX(${band})`,\n }}\n />\n ) : null}\n <div\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n width: \"max-content\",\n height: \"100%\",\n display: \"flex\",\n alignItems: \"center\",\n whiteSpace: \"pre\",\n fontFamily: narrow ? ANTON : INTER,\n fontSize: size,\n lineHeight: 1,\n fontWeight: narrow ? 400 : 900,\n color: onBand ? accentText : color,\n filter: style === \"outline\" ? `url(#${outlineId})` : undefined,\n transform: `translateX(${(state.shift * 100) / count}%)`,\n }}\n >\n {Array.from({ length: count }, (_, i) => (\n <span key={i}>{token}</span>\n ))}\n </div>\n </div>\n );\n })}\n </div>\n );\n}\n",+ "type": "registry:component",+ "target": "components/remocn/type-wall.tsx"+ }+ ],+ "type": "registry:component"+}diff --git a/registry/__index__.tsx b/registry/__index__.tsxindex 7b0d954b..f8833537 100644--- a/registry/__index__.tsx+++ b/registry/__index__.tsx@@ -590,6 +590,106 @@ const registry: Record<string, RegistryEntry> = {(m) => m.stretchInConfig,),},+ "selection-snap": {+ load: () =>+ import("@/registry/remocn/selection-snap").then((m) => ({+ default: m.SelectionSnap,+ })),+ loadConfig: () =>+ import("@/registry/remocn/selection-snap/config").then(+ (m) => m.selectionSnapConfig,+ ),+ },+ "echo-stack": {+ load: () =>+ import("@/registry/remocn/echo-stack").then((m) => ({+ default: m.EchoStack,+ })),+ loadConfig: () =>+ import("@/registry/remocn/echo-stack/config").then(+ (m) => m.echoStackConfig,+ ),+ },+ "type-wall": {+ load: () =>+ import("@/registry/remocn/type-wall").then((m) => ({+ default: m.TypeWall,+ })),+ loadConfig: () =>+ import("@/registry/remocn/type-wall/config").then(+ (m) => m.typeWallConfig,+ ),+ },+ "ring-text": {+ load: () =>+ import("@/registry/remocn/ring-text").then((m) => ({+ default: m.RingText,+ })),+ loadConfig: () =>+ import("@/registry/remocn/ring-text/config").then(+ (m) => m.ringTextConfig,+ ),+ },+ "period-drop": {+ load: () =>+ import("@/registry/remocn/period-drop").then((m) => ({+ default: m.PeriodDrop,+ })),+ loadConfig: () =>+ import("@/registry/remocn/period-drop/config").then(+ (m) => m.periodDropConfig,+ ),+ },+ "outline-trace": {+ load: () =>+ import("@/registry/remocn/outline-trace").then((m) => ({+ default: m.OutlineTrace,+ })),+ loadConfig: () =>+ import("@/registry/remocn/outline-trace/config").then(+ (m) => m.outlineTraceConfig,+ ),+ },+ "glyph-anatomy": {+ load: () =>+ import("@/registry/remocn/glyph-anatomy").then((m) => ({+ default: m.GlyphAnatomy,+ })),+ loadConfig: () =>+ import("@/registry/remocn/glyph-anatomy/config").then(+ (m) => m.glyphAnatomyConfig,+ ),+ },+ "stripe-type": {+ load: () =>+ import("@/registry/remocn/stripe-type").then((m) => ({+ default: m.StripeType,+ })),+ loadConfig: () =>+ import("@/registry/remocn/stripe-type/config").then(+ (m) => m.stripeTypeConfig,+ ),+ },+ "path-ride": {+ load: () =>+ import("@/registry/remocn/path-ride").then((m) => ({+ default: m.PathRide,+ })),+ loadConfig: () =>+ import("@/registry/remocn/path-ride/config").then(+ (m) => m.pathRideConfig,+ ),+ },+ "type-repeater": {+ load: () =>+ import("@/registry/remocn/type-repeater").then((m) => ({+ default: m.TypeRepeater,+ })),+ loadConfig: () =>+ import("@/registry/remocn/type-repeater/config").then(+ (m) => m.typeRepeaterConfig,+ ),+ },"chromatic-wave": {load: () =>import("@/registry/remocn/chromatic-wave").then((m) => ({@@ -690,6 +790,16 @@ const registry: Record<string, RegistryEntry> = {(m) => m.glassCodeWalkConfig,),},+ "code-morph": {+ load: () =>+ import("@/registry/remocn/code-morph").then((m) => ({+ default: m.CodeMorph,+ })),+ loadConfig: () =>+ import("@/registry/remocn/code-morph/config").then(+ (m) => m.codeMorphConfig,+ ),+ },"shader-mesh-gradient": {load: () =>import("@/registry/remocn/shader-mesh-gradient").then((m) => ({@@ -880,6 +990,16 @@ const registry: Record<string, RegistryEntry> = {(m) => m.simulatedCursorConfig,),},+ keystroke: {+ load: () =>+ import("@/registry/remocn/keystroke").then((m) => ({+ default: m.Keystroke,+ })),+ loadConfig: () =>+ import("@/registry/remocn/keystroke/config").then(+ (m) => m.keystrokeConfig,+ ),+ },"swirl-dissolve": {load: () =>import("@/components/docs/examples/swirl-dissolve-example").then((m) => ({@@ -2376,6 +2496,64 @@ const registry: Record<string, RegistryEntry> = {(m) => m.radialBurstConfig,),},+ "bauhaus-build": {+ load: () =>+ import("@/registry/remocn/bauhaus-build").then((m) => ({+ default: m.BauhausBuild,+ })),+ loadConfig: () =>+ import("@/registry/remocn/bauhaus-build/config").then(+ (m) => m.bauhausBuildConfig,+ ),+ },+ "mondrian-split": {+ load: () =>+ import("@/registry/remocn/mondrian-split").then((m) => ({+ default: m.MondrianSplit,+ })),+ loadConfig: () =>+ import("@/registry/remocn/mondrian-split/config").then(+ (m) => m.mondrianSplitConfig,+ ),+ },+ "truchet-flip": {+ load: () =>+ import("@/registry/remocn/truchet-flip").then((m) => ({+ default: m.TruchetFlip,+ })),+ loadConfig: () =>+ import("@/registry/remocn/truchet-flip/config").then(+ (m) => m.truchetFlipConfig,+ ),+ },+ "trim-burst": {+ load: () =>+ import("@/registry/remocn/trim-burst").then((m) => ({+ default: m.TrimBurst,+ })),+ loadConfig: () =>+ import("@/registry/remocn/trim-burst/config").then(+ (m) => m.trimBurstConfig,+ ),+ },+ "speed-lines": {+ load: () =>+ import("@/registry/remocn/speed-lines").then((m) => ({+ default: m.SpeedLines,+ })),+ loadConfig: () =>+ import("@/registry/remocn/speed-lines/config").then(+ (m) => m.speedLinesConfig,+ ),+ },+ squiggle: {+ load: () =>+ import("@/registry/remocn/squiggle").then((m) => ({+ default: m.Squiggle,+ })),+ loadConfig: () =>+ import("@/registry/remocn/squiggle/config").then((m) => m.squiggleConfig),+ },confetti: {load: () =>import("@/registry/remocn/confetti").then((m) => ({@@ -2529,6 +2707,16 @@ const registry: Record<string, RegistryEntry> = {loadConfig: () =>import("@/registry/remocn/opencode/config").then((m) => m.opencodeConfig),},+ "agent-run": {+ load: () =>+ import("@/registry/remocn/agent-run").then((m) => ({+ default: m.AgentRun,+ })),+ loadConfig: () =>+ import("@/registry/remocn/agent-run/config").then(+ (m) => m.agentRunConfig,+ ),+ },button: {load: () =>import("@/registry/remocn-ui/button").then((m) => ({diff --git a/registry/__manifest__.ts b/registry/__manifest__.tsindex b64cdb1a..cd64752f 100644--- a/registry/__manifest__.ts+++ b/registry/__manifest__.ts@@ -35,6 +35,23 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "agent-run": {+ durationInFrames: 355,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#ececea",+ },+ defaults: {+ theme: "light",+ accentColor: "#2563eb",+ compression: 3,+ seed: 1,+ speed: 1,+ },+ },"alert-dialog": {durationInFrames: 120,fps: 30,@@ -136,6 +153,26 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {shadow: "0 20px 60px rgba(0,0,0,0.4)",},},+ "bauhaus-build": {+ durationInFrames: 150,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#f1eee7",+ },+ defaults: {+ scale: 1,+ seed: 1,+ inkColor: "#1c1a17",+ accentColor: "#e4572e",+ secondaryColor: "#cbbc9f",+ tertiaryColor: "#7e776b",+ loop: false,+ speed: 1,+ },+ },"blur-in": {durationInFrames: 120,fps: 30,@@ -436,6 +473,27 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "code-morph": {+ durationInFrames: 138,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#f1eee7",+ },+ defaults: {+ filename: "invoices.tsx",+ theme: "dark",+ accentColor: "#0ea5e9",+ morphDuration: 36,+ fontSize: 20,+ highlight: true,+ lineNumbers: true,+ windowDots: true,+ speed: 1,+ },+ },combobox: {durationInFrames: 120,fps: 30,@@ -710,6 +768,27 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "echo-stack": {+ durationInFrames: 120,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#0a0a0a",+ },+ defaults: {+ text: "Bold.",+ color: "#fafafa",+ echoColor: "#fafafa",+ direction: "up",+ fontSize: 170,+ echoes: 3,+ echoOpacity: 0.35,+ cycle: 60,+ speed: 1,+ },+ },"ecosystem-constellation": {durationInFrames: 240,fps: 30,@@ -938,6 +1017,25 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "glyph-anatomy": {+ durationInFrames: 96,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#0a0a0a",+ },+ defaults: {+ text: "Glyph",+ color: "#fafafa",+ guideColor: "#0d99ff",+ fontSize: 200,+ guides: true,+ keepPoints: false,+ speed: 1,+ },+ },"gooey-morph": {durationInFrames: 120,fps: 30,@@ -2685,6 +2783,26 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ keystroke: {+ durationInFrames: 180,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#e9e9e5",+ },+ defaults: {+ platform: "mac",+ theme: "light",+ accent: "#0a84ff",+ size: 64,+ linger: 30,+ x: 0.5,+ y: 0.86,+ speed: 1,+ },+ },"kinetic-center-build": {durationInFrames: 60,fps: 30,@@ -2903,6 +3021,28 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "mondrian-split": {+ durationInFrames: 145,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#f3efe6",+ },+ defaults: {+ seed: 7,+ splits: 7,+ lineWeight: 14,+ expandCell: 0,+ lineColor: "#121212",+ redColor: "#d62d20",+ yellowColor: "#f4c20d",+ blueColor: "#1f4e9e",+ fieldColor: "#d62d20",+ speed: 1,+ },+ },"number-wheel": {durationInFrames: 112,fps: 30,@@ -2967,6 +3107,27 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "outline-trace": {+ durationInFrames: 75,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#ff4d1a",+ },+ defaults: {+ text: "Outline",+ color: "#111111",+ strokeColor: "#111111",+ fontSize: 150,+ strokeWidth: 2.5,+ stagger: 3,+ fill: true,+ keepStroke: false,+ speed: 1,+ },+ },"page-turn": {durationInFrames: 128,fps: 30,@@ -3037,6 +3198,26 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "path-ride": {+ durationInFrames: 96,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#ff4d1a",+ },+ defaults: {+ text: "Follow the line",+ path: "M 120 560 C 360 120 560 120 640 360 S 920 600 1160 160",+ color: "#111111",+ lineColor: "#fafafa",+ fontSize: 44,+ fontWeight: 700,+ lineWidth: 3,+ speed: 1,+ },+ },"per-character-rise": {durationInFrames: 60,fps: 30,@@ -3073,6 +3254,25 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "period-drop": {+ durationInFrames: 75,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#0a0a0a",+ },+ defaults: {+ text: "remocn",+ color: "#fafafa",+ dotColor: "#ff4d1a",+ fontSize: 160,+ fontWeight: 800,+ dotSize: 0.2,+ speed: 1,+ },+ },"perlin-dissolve": {durationInFrames: 116,fps: 30,@@ -3312,6 +3512,28 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "ring-text": {+ durationInFrames: 180,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#d4ff1f",+ },+ defaults: {+ text: "Type in motion",+ separator: "•",+ color: "#d4ff1f",+ band: "#0a0a0a",+ radius: 210,+ fontSize: 40,+ tilt: 38,+ roll: -16,+ period: 240,+ speed: 1,+ },+ },"ripple-zoom": {durationInFrames: 116,fps: 30,@@ -3507,6 +3729,27 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "selection-snap": {+ durationInFrames: 75,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#0a0a0a",+ },+ defaults: {+ text: "Frame",+ color: "#fafafa",+ accent: "#ff4d1a",+ selectionColor: "#3d5afe",+ fontSize: 150,+ fromWeight: 100,+ toWeight: 900,+ badge: true,+ speed: 1,+ },+ },"shader-caustics": {durationInFrames: 150,fps: 30,@@ -4125,6 +4368,31 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "speed-lines": {+ durationInFrames: 55,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#002fa7",+ },+ defaults: {+ mode: "trail",+ count: 12,+ weight: 2,+ spread: 96,+ duration: 14,+ bounce: 0.5,+ squash: 0.5,+ x: 0.5,+ y: 0.5,+ delay: 0,+ color: "#ffffff",+ seed: 1,+ speed: 1,+ },+ },spinner: {durationInFrames: 120,fps: 30,@@ -4191,6 +4459,32 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ squiggle: {+ durationInFrames: 80,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#002fa7",+ },+ defaults: {+ shape: "wave",+ color: "#ffffff",+ weight: 3,+ amplitude: 14,+ wavelength: 48,+ length: 320,+ angle: 0,+ x: 0.375,+ y: 0.5,+ settle: 0.5,+ hold: 12,+ erase: true,+ delay: 0,+ speed: 1,+ },+ },stage: {durationInFrames: 300,fps: 30,@@ -4274,6 +4568,28 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "stripe-type": {+ durationInFrames: 100,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#2b3bff",+ },+ defaults: {+ text: "Launch",+ color: "#fafafa",+ settle: "striped",+ fontSize: 180,+ fontWeight: 800,+ stripes: 8,+ gap: 0.35,+ hold: 30,+ exit: true,+ speed: 1,+ },+ },"sustained-glitch": {durationInFrames: 120,fps: 30,@@ -4459,6 +4775,57 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "trim-burst": {+ durationInFrames: 42,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#002fa7",+ },+ defaults: {+ count: 8,+ innerRadius: 16,+ reach: 64,+ strokeLength: 56,+ weight: 2,+ rotation: 0,+ spread: 360,+ jitter: 0.5,+ dots: false,+ cap: "round",+ color: "#ffffff",+ seed: 1,+ delay: 0,+ x: 0.5,+ y: 0.5,+ speed: 1,+ },+ },+ "truchet-flip": {+ durationInFrames: 120,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#002fa7",+ },+ defaults: {+ tiles: 10,+ weight: 0.2,+ passes: 2,+ waveMode: "radial",+ resolve: "rings",+ variant: "stroke",+ color: "#ffffff",+ secondaryColor: "#ffffff",+ seed: 1,+ loop: false,+ speed: 1,+ },+ },"tv-power-off": {durationInFrames: 62,fps: 30,@@ -4494,6 +4861,47 @@ export const previewManifest: Record<string, PreviewManifestEntry> = {speed: 1,},},+ "type-repeater": {+ durationInFrames: 100,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#ff4d1a",+ },+ defaults: {+ text: "Repeat",+ mode: "tunnel",+ color: "#111111",+ accent: "#fafafa",+ copies: 12,+ fontSize: 110,+ fontWeight: 800,+ outline: true,+ speed: 1,+ },+ },+ "type-wall": {+ durationInFrames: 150,+ fps: 30,+ compositionWidth: 1280,+ compositionHeight: 720,+ previewBackdrop: {+ type: "color",+ value: "#2b3bff",+ },+ defaults: {+ text: "MOTION",+ separator: "·",+ color: "#fafafa",+ accent: "#ff4d1a",+ accentText: "#111111",+ fontSize: 64,+ seed: 7,+ speed: 1,+ },+ },"typed-split-wipe": {durationInFrames: 75,fps: 30,diff --git a/registry/remocn/agent-run/__tests__/agent-run.test.ts b/registry/remocn/agent-run/__tests__/agent-run.test.tsnew file mode 100644index 00000000..928962b2--- /dev/null+++ b/registry/remocn/agent-run/__tests__/agent-run.test.ts@@ -0,0 +1,640 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ type AgentRunModel,+ agentRunDefaults,+ agentRunLength,+ defaultAgentRun,+ estimateAgentRunWidth,+ fitAgentRunChips,+ formatAgentRunSeconds,+ getAgentRunArrival,+ getAgentRunChunks,+ getAgentRunDuration,+ getAgentRunElapsed,+ getAgentRunFrame,+ getAgentRunGrowth,+ getAgentRunLayout,+ getAgentRunModel,+ getAgentRunReveal,+ getAgentRunScroll,+ getAgentRunShimmer,+ getAgentRunSpinner,+ getAgentRunState,+ getAgentRunTimeline,+ parseAgentRunMarkdown,+ tokenizeAgentRun,+} from "..";+import { agentRunConfig } from "../config";++const ANSWER = defaultAgentRun.answer;++function tokensIn(text: string, start: number, end: number) {+ const tokens: string[] = [];+ let previous = 0;+ for (const stop of tokenizeAgentRun(text)) {+ if (stop > start && stop <= end) tokens.push(text.slice(previous, stop));+ previous = stop;+ }+ return tokens;+}++function blockAt(model: AgentRunModel, frame: number, index: number) {+ const state = getAgentRunState(frame, model);+ return state.blocks.find((block) => block.key === `block-${index}`);+}++function headingAt(model: AgentRunModel, frame: number) {+ for (const block of getAgentRunState(frame, model).blocks) {+ if (block.kind === "heading") return block;+ }+ return undefined;+}++function codeAt(model: AgentRunModel, frame: number) {+ for (const block of getAgentRunState(frame, model).blocks) {+ if (block.kind === "code") return block;+ }+ return undefined;+}++describe("agent run timeline", () => {+ it("chains the prompt, the thinking, the tools and the answer", () => {+ const timeline = getAgentRunTimeline();+ expect(timeline.runStart).toBe(16);+ expect(timeline.planStart).toBe(30);+ expect(timeline.planEnd).toBe(48);+ expect(timeline.thinkEnd).toBe(timeline.planEnd + 8);+ expect(timeline.tools.map((tool) => [tool.start, tool.end])).toEqual([+ [61, 75],+ [80, 103],+ [108, 120],+ [125, 157],+ ]);+ let cursor = timeline.thinkEnd;+ for (const tool of timeline.tools) {+ expect(tool.start).toBe(cursor + 5);+ expect(tool.end - tool.start).toBe(tool.span);+ cursor = tool.end;+ }+ expect(timeline.answerStart).toBe(cursor + 8);+ expect(timeline.answerStart).toBe(165);+ expect(timeline.answerEnd).toBe(294);+ expect(timeline.runEnd).toBe(timeline.answerEnd);+ expect(timeline.settled).toBe(timeline.answerEnd + 16);+ expect(agentRunLength).toBe(310);+ });++ it("sizes the preview from the run, the speed and the compression", () => {+ expect(getAgentRunDuration()).toBe(355);+ expect(getAgentRunDuration()).toBe(agentRunConfig.durationInFrames);+ expect(getAgentRunDuration(undefined, { speed: 2 })).toBe(200);+ expect(getAgentRunDuration(undefined, { speed: 0.5 })).toBe(665);+ expect(getAgentRunDuration(undefined, { speed: 0 })).toBe(45);+ expect(getAgentRunDuration(undefined, { compression: 1 })).toBe(514);+ const resolve = agentRunConfig.getDurationInFrames;+ expect(resolve?.({ speed: 2, seed: 1, compression: 3 })).toBe(200);+ expect(resolve?.({ compression: 1 })).toBe(514);+ });++ it("compresses tool calls into video time and clamps the extremes", () => {+ const spans = (compression: number) => {+ const { tools } = getAgentRunTimeline(defaultAgentRun, { compression });+ return tools.map((tool) => tool.span);+ };+ expect(spans(1)).toEqual([42, 69, 33, 96]);+ expect(spans(3)).toEqual([14, 23, 12, 32]);+ expect(spans(6)).toEqual([12, 12, 12, 16]);+ expect(spans(0.1)).toEqual([120, 120, 120, 120]);+ expect(spans(Number.NaN)).toEqual(spans(3));+ });++ it("still runs without a plan, tools or an answer", () => {+ const bare = { prompt: "Summarize the launch notes", answer: "" };+ const timeline = getAgentRunTimeline(bare);+ expect(timeline.thinkEnd).toBe(16 + 14 + 8);+ expect(timeline.tools).toEqual([]);+ expect(timeline.answerStart).toBe(timeline.thinkEnd + 8);+ expect(timeline.answerEnd).toBe(timeline.answerStart);+ const model = getAgentRunModel(bare);+ expect(model.layout.plan).toBeNull();+ expect(model.layout.tools).toBeNull();+ const state = getAgentRunState(80, model);+ expect(state.blocks).toEqual([]);+ expect(state.header.done).toBe(true);+ });+});++describe("agent run timer", () => {+ it("lands every tool row on its real duration", () => {+ const timeline = getAgentRunTimeline();+ expect(getAgentRunElapsed(0, timeline)).toBe(0);+ expect(getAgentRunElapsed(timeline.runStart, timeline)).toBe(0);+ for (const tool of timeline.tools) {+ const start = getAgentRunElapsed(tool.start, timeline);+ const end = getAgentRunElapsed(tool.end, timeline);+ expect(start).toBeCloseTo(tool.realStart, 6);+ expect(end - start).toBeCloseTo(tool.duration, 6);+ }+ const thinking = timeline.thinkEnd - timeline.runStart;+ const thought = getAgentRunElapsed(timeline.thinkEnd, timeline);+ expect(thought).toBeCloseTo(thinking * 0.1, 6);+ expect(timeline.realTotal).toBeCloseTo(27.7, 6);+ const late = getAgentRunElapsed(timeline.runEnd + 120, timeline);+ expect(late).toBeCloseTo(timeline.realTotal, 6);+ });++ it("ticks forward only and freezes when the run ends", () => {+ const timeline = getAgentRunTimeline();+ let previous = 0;+ for (let frame = 0; frame <= 400; frame += 0.5) {+ const elapsed = getAgentRunElapsed(frame, timeline);+ expect(elapsed).toBeGreaterThanOrEqual(previous);+ previous = elapsed;+ }+ const model = getAgentRunModel();+ const done = getAgentRunState(timeline.runEnd + 20, model);+ expect(done.header.label).toBe("27.7s");+ expect(done.header.done).toBe(true);+ expect(done.status.thought).toBe("Thought for 4s");+ const durations = done.tools?.rows.map((row) => row.duration);+ expect(durations).toEqual(["1.4s", "2.3s", "1.1s", "3.2s"]);+ });++ it("formats seconds for the timer and the rows", () => {+ expect(formatAgentRunSeconds(0)).toBe("0.0s");+ expect(formatAgentRunSeconds(1.44)).toBe("1.4s");+ expect(formatAgentRunSeconds(59.9)).toBe("59.9s");+ expect(formatAgentRunSeconds(75)).toBe("1m 15s");+ expect(formatAgentRunSeconds(Number.NaN)).toBe("0.0s");+ expect(formatAgentRunSeconds(-3)).toBe("0.0s");+ });+});++describe("agent run thinking status", () => {+ it("sweeps a restrained, periodic shimmer across the label", () => {+ for (let time = 16; time < 46; time++) {+ const levels = getAgentRunShimmer(time, 8);+ expect(levels).toHaveLength(8);+ expect(Math.min(...levels)).toBeGreaterThanOrEqual(0.45);+ expect(Math.max(...levels)).toBeLessThanOrEqual(1);+ expect(getAgentRunShimmer(time + 30, 8)).toEqual(levels);+ }+ const peaks = [20, 26, 32].map((time) => {+ const levels = getAgentRunShimmer(time, 8);+ return levels.indexOf(Math.max(...levels));+ });+ expect(peaks).toEqual([0, 1, 4]);+ });+});++describe("agent run bursty streaming", () => {+ it("tokenizes words, digit groups, punctuation and newlines", () => {+ const ends = tokenizeAgentRun("Fix 4.12\n\nNow 12345");+ expect(ends).toEqual([3, 5, 6, 8, 9, 10, 13, 17, 19]);+ expect(tokenizeAgentRun("")).toEqual([]);+ });++ it("delivers 1 to 6 tokens per chunk on whole, irregular frames", () => {+ const chunks = getAgentRunChunks(ANSWER, 1);+ expect(chunks[0].at).toBe(0);+ expect(chunks[0].start).toBe(0);+ expect(chunks[chunks.length - 1].end).toBe(ANSWER.length);+ const sizes = new Set<number>();+ const gaps = new Set<number>();+ for (const [index, chunk] of chunks.entries()) {+ const tokens = tokensIn(ANSWER, chunk.start, chunk.end);+ const words = tokens.filter((token) => token !== "\n");+ expect(tokens.length).toBe(chunk.tokens);+ expect(tokens.length).toBeGreaterThan(0);+ expect(words.length).toBeLessThanOrEqual(6);+ if (words.length > 0) sizes.add(words.length);+ if (index === 0) continue;+ const gap = chunk.at - chunks[index - 1].at;+ expect(chunk.start).toBe(chunks[index - 1].end);+ expect(Number.isInteger(gap)).toBe(true);+ expect(gap).toBeGreaterThanOrEqual(1);+ expect(gap).toBeLessThanOrEqual(15);+ gaps.add(gap);+ }+ expect(sizes.size).toBeGreaterThanOrEqual(5);+ expect(gaps.size).toBeGreaterThanOrEqual(5);+ expect(Math.max(...gaps)).toBeGreaterThanOrEqual(5);+ });++ it("never reveals text at a constant rate", () => {+ const chunks = getAgentRunChunks(ANSWER, 1);+ const deltas: number[] = [];+ for (let local = 1; local <= chunks[chunks.length - 1].at; local++) {+ const now = getAgentRunReveal(chunks, local);+ deltas.push(now - getAgentRunReveal(chunks, local - 1));+ }+ const idle = deltas.filter((delta) => delta === 0).length;+ const bursts = new Set(deltas.filter((delta) => delta > 0));+ expect(idle).toBeGreaterThan(deltas.length / 4);+ expect(bursts.size).toBeGreaterThanOrEqual(10);+ expect(Math.max(...deltas)).toBeGreaterThanOrEqual(20);+ expect(deltas.every((delta) => delta >= 0)).toBe(true);+ expect(getAgentRunReveal(chunks, -1)).toBe(0);+ expect(getAgentRunReveal(chunks, 9999)).toBe(ANSWER.length);+ });++ it("starts every markdown block on a fresh chunk after a short beat", () => {+ const chunks = getAgentRunChunks(ANSWER, 1);+ let blocks = 0;+ for (const [index, chunk] of chunks.entries()) {+ const body = ANSWER.slice(chunk.start, chunk.end);+ if (!body.includes("\n\n")) continue;+ expect(body).toMatch(/\n\n+$/);+ const next = chunks[index + 1];+ if (next === undefined) continue;+ expect(next.block).toBe(true);+ expect(next.at - chunk.at).toBeGreaterThanOrEqual(3);+ blocks += 1;+ }+ expect(blocks).toBe(4);+ });++ it("reseeds the rhythm without touching the content", () => {+ const first = getAgentRunChunks(ANSWER, 1);+ expect(getAgentRunChunks(ANSWER, 1)).toEqual(first);+ const other = getAgentRunChunks(ANSWER, 2);+ const firstTimes = first.map((chunk) => chunk.at);+ expect(other.map((chunk) => chunk.at)).not.toEqual(firstTimes);+ expect(other[other.length - 1].end).toBe(ANSWER.length);+ const layout = getAgentRunLayout();+ const reseeded = getAgentRunModel(defaultAgentRun, { seed: 2 });+ expect(reseeded.layout).toEqual(layout);+ });+});++describe("agent run progressive markdown", () => {+ const model = getAgentRunModel();+ const { timeline } = model;+ const arrival = (raw: number) =>+ timeline.answerStart + getAgentRunArrival(timeline.answerChunks, raw);++ it("parses the supported markdown subset", () => {+ const source = [+ "# Weekly summary",+ "",+ "Some **bold** and `code` [2].",+ "",+ "* one",+ "- two",+ "",+ "```sql",+ "select 1;",+ ].join("\n");+ const blocks = parseAgentRunMarkdown(source);+ expect(blocks.map((block) => block.kind)).toEqual([+ "heading",+ "paragraph",+ "item",+ "item",+ "code",+ ]);+ const [heading, paragraph, , , code] = blocks;+ expect(heading.kind === "heading" && heading.level).toBe(1);+ const inline = paragraph.kind === "paragraph" ? paragraph.inline : [];+ expect(inline.map((part) => [part.kind, part.text])).toEqual([+ ["text", "Some "],+ ["bold", "bold"],+ ["text", " and "],+ ["code", "code"],+ ["text", " "],+ ["cite", "2"],+ ["text", "."],+ ]);+ expect(code.kind === "code" && code.lang).toBe("sql");+ const lines =+ code.kind === "code" ? code.lines.map((line) => line.text) : [];+ expect(lines).toEqual(["select 1;"]);+ });++ it("styles the heading only once its line completes", () => {+ const [heading] = parseAgentRunMarkdown(ANSWER);+ const done = arrival(heading.end);+ expect(done).toBe(170);+ expect(headingAt(model, timeline.answerStart - 1)).toBeUndefined();+ for (let frame = timeline.answerStart; frame < done; frame++) {+ const block = headingAt(model, frame);+ expect(block?.styled).toBe(false);+ expect(block?.morph).toBe(0);+ expect(block?.mark).toBe("## ");+ }+ expect(headingAt(model, done)?.styled).toBe(true);+ expect(headingAt(model, done)?.morph).toBe(0);+ expect(headingAt(model, done + 3)?.morph).toBeGreaterThan(0.8);+ expect(headingAt(model, done + 8)?.morph).toBe(1);+ });++ it("pops each bullet as its item starts", () => {+ const items = parseAgentRunMarkdown(ANSWER)+ .map((block, index) => ({ block, index }))+ .filter(({ block }) => block.kind === "item");+ const starts = items.map(({ block }) => arrival(block.raw));+ expect(starts).toEqual([217, 233, 244]);+ for (const [row, { index }] of items.entries()) {+ const start = starts[row];+ expect(blockAt(model, start - 1, index)).toBeUndefined();+ let peak = 0;+ for (let frame = start; frame < start + 8; frame++) {+ const block = blockAt(model, frame, index);+ const dot = block?.kind === "item" ? block.dot : 0;+ if (frame === start) {+ expect(dot).toBeGreaterThan(0);+ expect(dot).toBeLessThan(1);+ }+ peak = Math.max(peak, dot);+ }+ expect(peak).toBeGreaterThan(1.05);+ expect(peak).toBeLessThan(1.12);+ const settled = blockAt(model, start + 7, index);+ expect(settled?.kind === "item" && settled.dot).toBe(1);+ }+ });++ it("opens the code panel on its fence and streams its lines inside", () => {+ expect(codeAt(model, 261)).toBeUndefined();+ const opened = codeAt(model, 262);+ expect(opened?.lines).toHaveLength(0);+ expect(opened?.lang).toBe("tsx");+ expect(opened?.height).toBeGreaterThan(0);+ const linesAt = (frame: number) => codeAt(model, frame)?.lines.length;+ expect([263, 265, 268, 272].map(linesAt)).toEqual([1, 2, 3, 4]);+ let previous = 0;+ for (let frame = 262; frame <= 290; frame++) {+ const height = codeAt(model, frame)?.height ?? 0;+ expect(height).toBeGreaterThanOrEqual(previous);+ previous = height;+ }+ expect(previous).toBe(142);+ });++ it("shows a citation chip only when its bracket closes", () => {+ const lineAt = (frame: number) => {+ const block = blockAt(model, frame, 1);+ return block?.kind === "paragraph" ? block.lines[0].spans : [];+ };+ const cites = (frame: number) =>+ lineAt(frame).filter((span) => span.kind === "cite");+ expect(cites(200)).toHaveLength(0);+ expect(cites(201)).toHaveLength(1);+ expect(cites(201)[0].opacity).toBeGreaterThan(0);+ expect(cites(210)[0].scale).toBe(1);+ const text = lineAt(200)+ .flatMap((span) => span.fragments.map((part) => part.text))+ .join("");+ expect(text).not.toContain("[");+ });++ it("fades each arriving chunk in over a few frames", () => {+ const opacities = (frame: number) => {+ const values: number[] = [];+ for (const block of getAgentRunState(frame, model).blocks) {+ for (const line of block.lines) {+ for (const span of line.spans) {+ for (const part of span.fragments) values.push(part.opacity);+ }+ }+ }+ return values;+ };+ const { answerStart, answerEnd, settled } = timeline;+ for (let frame = answerStart; frame <= answerEnd; frame++) {+ const values = opacities(frame);+ expect(values.every((value) => value > 0 && value <= 1)).toBe(true);+ }+ const arriving = opacities(answerStart);+ expect(arriving.some((value) => value < 1)).toBe(true);+ const rested = opacities(settled);+ expect(rested.every((value) => value === 1)).toBe(true);+ });+});++describe("agent run tool rows", () => {+ const model = getAgentRunModel();+ const { timeline } = model;++ const rows = (frame: number) => getAgentRunState(frame, model).tools?.rows;++ it("resolves each spinner into a check at the step's end", () => {+ for (const tool of timeline.tools) {+ const hidden = rows(tool.start - 1)?.map((row) => row.index) ?? [];+ expect(hidden).not.toContain(tool.index);+ const running = rows(tool.end - 1)?.[tool.index];+ expect(running?.spinner.resolved).toBe(false);+ expect(running?.spinner.check).toBe(0);+ expect(running?.label).toBe(0);+ const resolved = rows(tool.end + 10)?.[tool.index];+ expect(resolved?.spinner.resolved).toBe(true);+ expect(resolved?.spinner.arc).toBe(1);+ expect(resolved?.spinner.done).toBe(1);+ expect(resolved?.spinner.check).toBe(1);+ expect(resolved?.label).toBe(1);+ }+ });++ it("spins at a constant rate and coasts to rest as it closes", () => {+ const running = getAgentRunSpinner(10, 0, 20);+ expect(running).toEqual({+ angle: 30,+ arc: 0.28,+ done: 0,+ check: 0,+ resolved: false,+ });+ const end = getAgentRunSpinner(20, 0, 20);+ expect(end.angle).toBe(150);+ expect(getAgentRunSpinner(28, 0, 20).angle).toBe(198);+ expect(getAgentRunSpinner(60, 0, 20).angle).toBe(198);+ expect(getAgentRunSpinner(30, 0, 20).check).toBe(1);+ });++ it("pops the source chips in order inside the read step", () => {+ const read = timeline.tools[3];+ const rowAt = (frame: number) => rows(frame)?.[3];+ const first = rowAt(read.start);+ expect(first?.chips.map((chip) => chip.label)).toEqual([+ "Checkout funnel",+ "Browser report",+ "Release 4.12",+ "PR #2186",+ "webkit.org",+ ]);+ expect(first?.more?.count).toBe(7);+ const early = rowAt(read.start + 3)?.chips.some((chip) => chip.visible);+ expect(early).toBe(false);+ let previous = 0;+ for (let frame = read.start; frame <= read.end; frame++) {+ const row = rowAt(frame);+ const shown = row?.chips.filter((chip) => chip.visible).length ?? 0;+ expect(shown).toBeGreaterThanOrEqual(previous);+ previous = shown;+ }+ const full = rowAt(read.start + Math.ceil(0.7 * read.span) + 1);+ expect(full?.chips.every((chip) => chip.visible)).toBe(true);+ expect(full?.more?.visible).toBe(true);+ });++ it("fits source chips on one line with a +N chip", () => {+ const sources = defaultAgentRun.steps?.[3].sources ?? [];+ expect(fitAgentRunChips(sources).chips).toHaveLength(5);+ expect(fitAgentRunChips(sources).more).toBe(7);+ expect(fitAgentRunChips(["docs.example.com"]).chips).toEqual([+ { label: "docs.example.com", icon: "globe" },+ ]);+ const many = fitAgentRunChips(["a", "b", "c", "d", "e", "f", "g", "h"]);+ expect(many.chips).toHaveLength(6);+ expect(many.more).toBe(2);+ });+});++describe("agent run calm column", () => {+ it("scrolls forward gently and keeps new text above the fold", () => {+ for (const [width, height] of [+ [1280, 720],+ [1080, 1080],+ ]) {+ const model = getAgentRunModel(defaultAgentRun, { width, height });+ const growth = getAgentRunGrowth(model.layout, model.timeline);+ let previous = 0;+ for (let frame = 0; frame <= agentRunLength + 20; frame++) {+ const scroll = getAgentRunScroll(frame, model.scroll);+ expect(scroll).toBeGreaterThanOrEqual(previous - 1e-9);+ expect(scroll - previous).toBeLessThan(10);+ previous = scroll;+ const bottoms = growth+ .filter((event) => event.at <= frame)+ .map((event) => event.bottom);+ const bottom = Math.max(0, ...bottoms);+ expect(bottom).toBeLessThanOrEqual(scroll + model.stage.viewport);+ }+ const rest = model.layout.height + 40 - model.stage.viewport;+ expect(getAgentRunScroll(10_000, model.scroll)).toBeCloseTo(rest, 3);+ }+ });++ it("keeps a burst's newest line above the fold on every seed", () => {+ let margin = Number.POSITIVE_INFINITY;+ for (let seed = 1; seed <= 99; seed++) {+ const model = getAgentRunModel(defaultAgentRun, { seed });+ const growth = getAgentRunGrowth(model.layout, model.timeline);+ let bottom = 0;+ let next = 0;+ for (let frame = 0; frame <= model.timeline.settled; frame++) {+ while (next < growth.length && growth[next].at <= frame) {+ bottom = Math.max(bottom, growth[next].bottom);+ next += 1;+ }+ const scroll = getAgentRunScroll(frame, model.scroll);+ margin = Math.min(margin, scroll + model.stage.viewport - bottom);+ }+ }+ expect(margin).toBeGreaterThanOrEqual(16);+ });++ it("does not scroll when the whole run fits the panel", () => {+ const model = getAgentRunModel(defaultAgentRun, {+ width: 1080,+ height: 1920,+ });+ expect(model.scroll).toEqual([]);+ expect(getAgentRunState(300, model).scroll).toBe(0);+ });++ it("scales the panel by height and caps it by width", () => {+ const frame = (width: number, height: number) => {+ const { unit, panelHeight, viewport } = getAgentRunFrame(width, height);+ return [unit, panelHeight, viewport];+ };+ expect(frame(1280, 720)).toEqual([1, 640, 590]);+ expect(frame(1920, 1080)).toEqual([1.5, 640, 590]);+ expect(frame(1080, 1080)).toEqual([1.227, 800, 750]);+ expect(frame(1080, 1920)).toEqual([1.227, 960, 910]);+ expect(frame(Number.NaN, Number.NaN)).toEqual([1, 640, 590]);+ });+});++describe("agent run layout", () => {+ const layout = getAgentRunLayout();++ it("lays out the default answer in short, legible lines", () => {+ expect(layout.blocks.map((block) => block.lines.length)).toEqual([+ 1, 2, 1, 1, 1, 4, 1,+ ]);+ expect(layout.height).toBe(829);+ for (const block of layout.blocks) {+ if (block.kind === "code") continue;+ const size = block.kind === "heading" ? 20 : 16;+ const limit = block.kind === "item" ? 658 : 680;+ for (const line of block.lines) {+ const text = line.pieces+ .filter((piece) => piece.kind === "text" || piece.kind === "bold")+ .map((piece) => piece.text)+ .join("");+ expect(estimateAgentRunWidth(text, size)).toBeLessThanOrEqual(limit);+ }+ }+ });++ it("keeps every character of the answer across the wrapped lines", () => {+ const paragraph = layout.blocks[1];+ const shown = paragraph.lines+ .map((line) => line.pieces.map((piece) => piece.text).join(""))+ .join(" ");+ expect(shown).toBe(+ "Checkout conversion fell from 3.4% to 2.7% last week, a 21% drop 1. All of it comes from the payment step on Safari, 41% of checkouts 2.",+ );+ const lines = layout.blocks.flatMap((block) => block.lines);+ expect(lines.every((line) => line.pieces.length > 0)).toBe(true);+ });+});++describe("agent run determinism", () => {+ const model = getAgentRunModel();++ it("renders any frame identically in any sampling order", () => {+ const frames = [0, 12, 40, 90, 170, 230, 266, 300, 400];+ const forward = frames.map((frame) => getAgentRunState(frame, model));+ const backward = [...frames]+ .reverse()+ .map((frame) => getAgentRunState(frame, model))+ .reverse();+ expect(backward).toEqual(forward);+ expect(getAgentRunState(230, getAgentRunModel())).toEqual(forward[5]);+ });++ it("maps other frame rates and speeds onto the 30 fps timeline", () => {+ const base = getAgentRunState(180, model);+ expect(getAgentRunState(360, model, { fps: 60 })).toEqual(base);+ expect(getAgentRunState(360, model, { speed: 0.5 })).toEqual(base);+ const frozen = getAgentRunState(200, model, { speed: 0 });+ expect(frozen).toEqual(getAgentRunState(0, model));+ });+});++describe("agent run config", () => {+ it("matches the component defaults", () => {+ const controls = resolveControls("agent-run", agentRunConfig.controls);+ expect(getDefaults(controls)).toEqual({+ theme: agentRunDefaults.theme,+ accentColor: agentRunDefaults.accentColor,+ compression: agentRunDefaults.compression,+ seed: agentRunDefaults.seed,+ speed: agentRunDefaults.speed,+ });+ const theme = controls.theme;+ expect(theme.type === "select" ? theme.options : []).toEqual([+ "light",+ "dark",+ ]);+ const compression = controls.compression;+ const range =+ compression.type === "number" ? [compression.min, compression.max] : [];+ expect(range).toEqual([1, 8]);+ expect(agentRunConfig.componentName).toBe("AgentRun");+ expect(agentRunConfig.importPath).toBe("@/components/remocn/agent-run");+ });+});diff --git a/registry/remocn/agent-run/config.ts b/registry/remocn/agent-run/config.tsnew file mode 100644index 00000000..a333b144--- /dev/null+++ b/registry/remocn/agent-run/config.ts@@ -0,0 +1,51 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";+import { getAgentRunDuration } from ".";++const numberOf = (value: unknown) =>+ typeof value === "number" ? value : undefined;++function durationOf(values: Record<string, unknown>) {+ return getAgentRunDuration(undefined, {+ seed: numberOf(values.seed),+ compression: numberOf(values.compression),+ speed: numberOf(values.speed),+ });+}++export const agentRunConfig: ComponentConfig = {+ componentName: "AgentRun",+ importPath: "@/components/remocn/agent-run",+ controls: {+ theme: {+ type: "enum",+ default: "light",+ variants: { light: {}, dark: {} },+ description: "Theme",+ },+ accentColor: { type: "color", default: "#2563eb", description: "Accent" },+ compression: {+ type: "number",+ default: 3,+ min: 1,+ max: 8,+ step: 0.5,+ description: "Compression",+ hiddenFromList: false,+ },+ seed: {+ type: "number",+ default: 1,+ min: 1,+ max: 99,+ step: 1,+ description: "Seed",+ hiddenFromList: false,+ },+ },+ durationInFrames: 355,+ getDurationInFrames: durationOf,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#ececea" },+};diff --git a/registry/remocn/agent-run/index.tsx b/registry/remocn/agent-run/index.tsxnew file mode 100644index 00000000..ccae11ee--- /dev/null+++ b/registry/remocn/agent-run/index.tsx@@ -0,0 +1,2637 @@+"use client";++import { type CSSProperties, useMemo } from "react";+import { Easing, random, useCurrentFrame, useVideoConfig } from "remotion";++export type AgentRunTheme = "light" | "dark";++export type AgentRunIcon =+ | "chart"+ | "database"+ | "search"+ | "book"+ | "globe"+ | "terminal"+ | "file";++export interface AgentRunStep {+ name: string;+ detail?: string;+ duration: number;+ icon?: AgentRunIcon;+ sources?: readonly string[];+}++export interface AgentRunScript {+ title?: string;+ prompt: string;+ plan?: readonly string[];+ steps?: readonly AgentRunStep[];+ answer: string;+}++export interface AgentRunProps {+ run?: AgentRunScript;+ theme?: AgentRunTheme;+ accentColor?: string;+ compression?: number;+ seed?: number;+ speed?: number;+ className?: string;+}++export interface AgentRunOptions {+ seed?: number;+ compression?: number;+ width?: number;+ height?: number;+}++export interface AgentRunPlayback {+ fps?: number;+ speed?: number;+}++export const defaultAgentRun: AgentRunScript = {+ title: "Checkout conversion drop",+ prompt: "Why did checkout conversion drop last week?",+ plan: [+ "Compare the checkout funnel with the week before",+ "Break the drop down by browser and step",+ "Check what shipped and what the error logs say",+ ],+ steps: [+ {+ icon: "chart",+ name: "Query analytics",+ detail: "checkout funnel, last 7 days vs prior 7",+ duration: 1.4,+ },+ {+ icon: "database",+ name: "Run SQL",+ detail: "conversion by browser and step",+ duration: 2.3,+ },+ {+ icon: "search",+ name: "Search logs",+ detail: "Apple Pay errors on Safari",+ duration: 1.1,+ },+ {+ icon: "book",+ name: "Read 12 sources",+ duration: 3.2,+ sources: [+ "Checkout funnel",+ "Browser report",+ "Release 4.12",+ "PR #2186",+ "webkit.org",+ "developer.mozilla.org",+ "Payments runbook",+ "Error log",+ "Incident notes",+ "Apple Pay guide",+ "Support tickets",+ "Status page",+ ],+ },+ ],+ answer: [+ "## Apple Pay broke on Safari in release 4.12",+ "",+ "Checkout conversion fell from 3.4% to 2.7% last week, a 21% drop [1]. All of it comes from the payment step on Safari, 41% of checkouts [2].",+ "",+ "- Safari conversion halved, from 3.5% to 1.8%",+ "- Chrome and Firefox held steady at 3.3%",+ '- 4.12 moved the card form into an iframe without `allow="payment"` [3]',+ "",+ "```tsx",+ "<iframe",+ " src={cardFormUrl}",+ ' allow="payment"',+ "/>",+ "```",+ "",+ "**Fix:** add the attribute and ship 4.12.1 today.",+ ].join("\n"),+};++export const agentRunDefaults: Required<Omit<AgentRunProps, "className">> = {+ run: defaultAgentRun,+ theme: "light",+ accentColor: "#2563eb",+ compression: 3,+ seed: 1,+ speed: 1,+};++const PANEL_IN = 14;+const PANEL_RISE = 14;+const BUBBLE_AT = 4;+const BUBBLE_IN = 10;+const BUBBLE_RISE = 8;+const RUN_START = 16;+const STATUS_IN = 6;+const THINK_LEAD = 14;+const THINK_TAIL = 8;+const SWAP = 8;+const SWAP_RISE = 4;+const TOOL_GAP = 5;+const TOOL_MIN = 12;+const TOOL_MAX = 120;+const ANSWER_GAP = 8;+const ROW_IN = 8;+const ROW_FADE = 6;+const LABEL_DELAY = 2;+const LABEL_FADE = 6;+const SPIN = 12;+const ARC = 0.28;+const RESOLVE = 8;+const CHECK_FROM = 3;+const CHECK_TO = 10;+const CHIP_LEAD = 4;+const CHIP_SPAN = 0.7;+const FADE = 5;+const MORPH = 8;+const POP = 8;+const CODE_OPEN = 8;+const LINE_GROW = 5;+const SCROLL = 24;+const SCROLL_LEAD = 16;+const SETTLE = 16;+const HOLD = 45;+const SHIMMER_PERIOD = 30;+const SHIMMER_BAND = 3;+const SHIMMER_BASE = 0.45;+const DOT_BACK = 1.7;+const CITE_BACK = 2;+const CHIP_BACK = 1.7;+const MIN_COMPRESSION = 0.25;+const MAX_COMPRESSION = 20;++const SIZE_WEIGHTS = [8, 16, 22, 22, 17, 15];+const GAP_WEIGHTS = [42, 33, 16, 9];+const PAUSE_CHANCE = 0.06;+const PAUSE_MIN = 4;+const PAUSE_SPREAD = 4;+const BLOCK_MIN = 2;+const BLOCK_SPREAD = 3;++const REF_HEIGHT = 720;+const PANEL_W = 800;+const MARGIN_X = 40;+const MARGIN_Y = 40;+const MIN_PANEL_H = 360;+const MAX_PANEL_H = 960;+const HEADER_H = 48;+const PAD_X = 32;+const PAD_TOP = 24;+const SAFE = 40;+const COLUMN = PANEL_W - 2 * PAD_X;+const MEASURE = 680;+const BODY_SIZE = 16;+const BODY_LINE = 26;+const BUBBLE_SIZE = 16;+const BUBBLE_LINE = 24;+const BUBBLE_PAD_Y = 10;+const BUBBLE_PAD_X = 16;+const BUBBLE_WIDTH = 520;+const BUBBLE_GAP = 22;+const STATUS_H = 22;+const STATUS_GAP = 10;+const PLAN_SIZE = 15;+const PLAN_LINE = 24;+const PLAN_GAP = 4;+const PLAN_INDENT = 36;+const PLAN_WIDTH = 640;+const PLAN_AFTER = 20;+const ROW_H = 40;+const CHIPS_H = 34;+const TOOLS_AFTER = 24;+const ITEM_INDENT = 22;+const ITEM_GAP = 4;+const BLOCK_GAP = 12;+const HEADING_GAP = 8;+const CODE_GAP = 14;+const CODE_SIZE = 14;+const CODE_LINE = 22;+const CODE_HEAD = 34;+const CODE_PAD = 10;+const CHIP_SIZE = 12.5;+const CHIP_GAP = 6;+const CHIP_MAX = 6;+const CHIP_ROOM = COLUMN - 2 - 40 - 14;+const CIRCLE = 2 * Math.PI * 10;+const CHECK_LENGTH = 6 * Math.SQRT2;++const HEADINGS: Record<1 | 2, { size: number; line: number }> = {+ 1: { size: 22, line: 32 },+ 2: { size: 20, line: 30 },+};++const SANS =+ 'Inter, "Geist", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';+const MONO =+ '"JetBrains Mono", "Geist Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace';++const EXPO = Easing.bezier(0.16, 1, 0.3, 1);++const finite = (value: number | undefined, fallback: number) =>+ typeof value === "number" && Number.isFinite(value) ? value : fallback;+const clamp = (value: number, min: number, max: number) =>+ Math.min(max, Math.max(min, value));+const progress = (value: number) =>+ Number.isNaN(value) ? 0 : clamp(value, 0, 1);+const round = (value: number) => Math.round(value * 1000) / 1000;+const expo = (value: number) => EXPO(progress(value));+const easeOut = (value: number) => 1 - (1 - progress(value)) ** 3;+const smoothstep = (value: number) => {+ const t = progress(value);+ return t * t * (3 - 2 * t);+};+const backOut = (value: number, overshoot: number) => {+ const t = progress(value) - 1;+ return 1 + (overshoot + 1) * t ** 3 + overshoot * t ** 2;+};+const rateOf = (speed: number | undefined) =>+ Math.max(0, finite(speed, agentRunDefaults.speed));+const seedOf = (seed: number | undefined) =>+ finite(seed, agentRunDefaults.seed);+const compressionOf = (compression: number | undefined) =>+ clamp(+ finite(compression, agentRunDefaults.compression),+ MIN_COMPRESSION,+ MAX_COMPRESSION,+ );++export function formatAgentRunSeconds(seconds: number) {+ const value = Math.max(0, finite(seconds, 0));+ if (value < 60) return `${value.toFixed(1)}s`;+ const minutes = Math.floor(value / 60);+ const rest = Math.floor(value - minutes * 60);+ return `${minutes}m ${String(rest).padStart(2, "0")}s`;+}++const isLetter = (code: number) =>+ (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code >= 192;+const isDigit = (code: number) => code >= 48 && code <= 57;++export function tokenizeAgentRun(text: string): number[] {+ const ends: number[] = [];+ let index = 0;+ while (index < text.length) {+ if (text[index] === "\n") {+ index += 1;+ ends.push(index);+ continue;+ }+ while (+ index < text.length &&+ (text[index] === " " || text[index] === "\t")+ ) {+ index += 1;+ }+ if (index < text.length && text[index] !== "\n") {+ const code = text.charCodeAt(index);+ if (isLetter(code)) {+ while (index < text.length && isLetter(text.charCodeAt(index))) {+ index += 1;+ }+ } else if (isDigit(code)) {+ const stop = Math.min(text.length, index + 3);+ while (index < stop && isDigit(text.charCodeAt(index))) {+ index += 1;+ }+ } else {+ index += 1;+ }+ }+ ends.push(index);+ }+ return ends;+}++export interface AgentRunChunk {+ index: number;+ at: number;+ start: number;+ end: number;+ tokens: number;+ block: boolean;+}++function pick(weights: readonly number[], value: number) {+ const total = weights.reduce((sum, weight) => sum + weight, 0);+ let cursor = value * total;+ for (const [index, weight] of weights.entries()) {+ if (cursor < weight) return index;+ cursor -= weight;+ }+ return weights.length - 1;+}++export function getAgentRunChunks(+ text: string,+ seed = agentRunDefaults.seed,+ stream = "answer",+): AgentRunChunk[] {+ const ends = tokenizeAgentRun(text);+ const startOf = (token: number) => (token > 0 ? ends[token - 1] : 0);+ const isNewline = (token: number) =>+ token < ends.length && text[startOf(token)] === "\n";+ const key = `agent-run-${seedOf(seed)}-${stream}`;+ const chunks: AgentRunChunk[] = [];+ let token = 0;+ let at = 0;+ let block = false;+ while (token < ends.length) {+ const index = chunks.length;+ const size = pick(SIZE_WEIGHTS, random(`${key}-size-${index}`)) + 1;+ let stop = Math.min(ends.length, token + size);+ let cut = false;+ for (let cursor = token; cursor < stop; cursor++) {+ if (isNewline(cursor) && isNewline(cursor + 1)) {+ stop = cursor + 2;+ cut = true;+ break;+ }+ }+ if (!cut && isNewline(stop - 1) && isNewline(stop)) {+ stop += 1;+ cut = true;+ }+ while (cut && isNewline(stop)) stop += 1;+ if (index > 0) {+ at += pick(GAP_WEIGHTS, random(`${key}-gap-${index}`)) + 1;+ if (random(`${key}-pause-${index}`) < PAUSE_CHANCE) {+ const hold = random(`${key}-hold-${index}`) * PAUSE_SPREAD;+ at += PAUSE_MIN + Math.floor(hold);+ }+ if (block) {+ const extra = random(`${key}-block-${index}`) * BLOCK_SPREAD;+ at += BLOCK_MIN + Math.floor(extra);+ }+ }+ chunks.push({+ index,+ at,+ start: startOf(token),+ end: ends[stop - 1],+ tokens: stop - token,+ block,+ });+ block = cut;+ token = stop;+ }+ return chunks;+}++function lastArrival(chunks: readonly AgentRunChunk[]) {+ return chunks.length > 0 ? chunks[chunks.length - 1].at : 0;+}++function chunkIndexAt(chunks: readonly AgentRunChunk[], offset: number) {+ let low = 0;+ let high = chunks.length - 1;+ let found = chunks.length;+ while (low <= high) {+ const middle = (low + high) >> 1;+ if (chunks[middle].end > offset) {+ found = middle;+ high = middle - 1;+ } else {+ low = middle + 1;+ }+ }+ return found;+}++export function getAgentRunArrival(+ chunks: readonly AgentRunChunk[],+ offset: number,+) {+ const index = chunkIndexAt(chunks, offset);+ return index < chunks.length ? chunks[index].at : Number.POSITIVE_INFINITY;+}++export function getAgentRunReveal(+ chunks: readonly AgentRunChunk[],+ local: number,+) {+ let low = 0;+ let high = chunks.length - 1;+ let revealed = 0;+ while (low <= high) {+ const middle = (low + high) >> 1;+ if (chunks[middle].at <= local) {+ revealed = chunks[middle].end;+ low = middle + 1;+ } else {+ high = middle - 1;+ }+ }+ return revealed;+}++export type AgentRunInlineKind = "text" | "bold" | "code" | "cite";++export interface AgentRunInline {+ kind: AgentRunInlineKind;+ text: string;+ raw: number;+ end: number;+}++export interface AgentRunCodeLine {+ text: string;+ raw: number;+}++export type AgentRunBlock =+ | {+ kind: "heading";+ level: 1 | 2;+ raw: number;+ body: number;+ end: number;+ inline: AgentRunInline[];+ }+ | { kind: "paragraph"; raw: number; end: number; inline: AgentRunInline[] }+ | {+ kind: "item";+ raw: number;+ body: number;+ end: number;+ inline: AgentRunInline[];+ }+ | {+ kind: "code";+ raw: number;+ open: number;+ end: number;+ lang: string;+ langRaw: number;+ lines: AgentRunCodeLine[];+ };++function parseInline(source: string, base: number): AgentRunInline[] {+ const out: AgentRunInline[] = [];+ let text = "";+ let textStart = 0;+ const flush = (at: number) => {+ if (text.length > 0) {+ out.push({ kind: "text", text, raw: base + textStart, end: base + at });+ }+ text = "";+ };+ let index = 0;+ while (index < source.length) {+ if (source.startsWith("**", index)) {+ const close = source.indexOf("**", index + 2);+ if (close > index + 2) {+ flush(index);+ out.push({+ kind: "bold",+ text: source.slice(index + 2, close),+ raw: base + index + 2,+ end: base + close + 2,+ });+ index = close + 2;+ textStart = index;+ continue;+ }+ }+ if (source[index] === "`") {+ const close = source.indexOf("`", index + 1);+ if (close > index + 1) {+ flush(index);+ out.push({+ kind: "code",+ text: source.slice(index + 1, close),+ raw: base + index + 1,+ end: base + close + 1,+ });+ index = close + 1;+ textStart = index;+ continue;+ }+ }+ if (source[index] === "[") {+ const match = /^\[(\d{1,3})\]/.exec(source.slice(index));+ if (match) {+ flush(index);+ out.push({+ kind: "cite",+ text: match[1],+ raw: base + index,+ end: base + index + match[0].length,+ });+ index += match[0].length;+ textStart = index;+ continue;+ }+ }+ if (text.length === 0) textStart = index;+ text += source[index];+ index += 1;+ }+ flush(index);+ return out;+}++const HEADING_LINE = /^(#{1,3})[ \t]+(.*)$/;+const ITEM_LINE = /^[-*][ \t]+(.*)$/;++function isStructural(line: string) {+ return (+ line.startsWith("```") || HEADING_LINE.test(line) || ITEM_LINE.test(line)+ );+}++export function parseAgentRunMarkdown(markdown: string): AgentRunBlock[] {+ const lines: AgentRunCodeLine[] = [];+ let offset = 0;+ for (const text of markdown.split("\n")) {+ lines.push({ text, raw: offset });+ offset += text.length + 1;+ }+ const blocks: AgentRunBlock[] = [];+ let index = 0;+ while (index < lines.length) {+ const line = lines[index];+ if (line.text.trim() === "") {+ index += 1;+ continue;+ }+ if (line.text.startsWith("```")) {+ const rest = line.text.slice(3);+ const body: AgentRunCodeLine[] = [];+ let cursor = index + 1;+ while (cursor < lines.length && !lines[cursor].text.startsWith("```")) {+ body.push(lines[cursor]);+ cursor += 1;+ }+ const closed = cursor < lines.length;+ const last = closed ? lines[cursor] : (body[body.length - 1] ?? line);+ blocks.push({+ kind: "code",+ raw: line.raw,+ open: line.raw + 3,+ end: last.raw + last.text.length,+ lang: rest.trim(),+ langRaw: line.raw + 3 + (rest.length - rest.trimStart().length),+ lines: body,+ });+ index = closed ? cursor + 1 : cursor;+ continue;+ }+ const heading = HEADING_LINE.exec(line.text);+ if (heading) {+ const body = line.raw + line.text.length - heading[2].length;+ blocks.push({+ kind: "heading",+ level: heading[1].length === 1 ? 1 : 2,+ raw: line.raw,+ body,+ end: line.raw + line.text.length,+ inline: parseInline(heading[2], body),+ });+ index += 1;+ continue;+ }+ const item = ITEM_LINE.exec(line.text);+ if (item) {+ const body = line.raw + line.text.length - item[1].length;+ blocks.push({+ kind: "item",+ raw: line.raw,+ body,+ end: line.raw + line.text.length,+ inline: parseInline(item[1], body),+ });+ index += 1;+ continue;+ }+ let cursor = index;+ while (+ cursor < lines.length &&+ lines[cursor].text.trim() !== "" &&+ (cursor === index || !isStructural(lines[cursor].text))+ ) {+ cursor += 1;+ }+ const last = lines[cursor - 1];+ const end = last.raw + last.text.length;+ const source = markdown.slice(line.raw, end).replace(/\n/g, " ");+ blocks.push({+ kind: "paragraph",+ raw: line.raw,+ end,+ inline: parseInline(source, line.raw),+ });+ index = cursor;+ }+ return blocks;+}++const NARROW = " .,:;'!|iljI`";+const THIN = "ftr()[]{}/\\-";+const SYMBOL = "<>=+~#$&→";+const WIDE = "mw…";+const WIDEST = "MW@%—";++function charWidth(char: string) {+ if (NARROW.includes(char)) return 0.3;+ if (THIN.includes(char)) return 0.44;+ if (WIDEST.includes(char)) return 1;+ if (WIDE.includes(char)) return 0.9;+ if (SYMBOL.includes(char)) return 0.68;+ if (char >= "0" && char <= "9") return 0.66;+ if (char >= "A" && char <= "Z") return 0.74;+ return 0.62;+}++export function estimateAgentRunWidth(+ text: string,+ size: number,+ mono = false,+) {+ let em = 0;+ for (const char of text) em += mono ? 0.6 : charWidth(char);+ return em * size;+}++export type AgentRunPieceKind =+ | AgentRunInlineKind+ | "punct"+ | "string"+ | "comment";++export interface AgentRunPiece {+ kind: AgentRunPieceKind;+ text: string;+ raw: number;+ end: number;+}++export interface AgentRunTextLine {+ y: number;+ height: number;+ raw: number;+ pieces: AgentRunPiece[];+}++function pieceWidth(piece: AgentRunPiece, size: number) {+ if (piece.kind === "cite") {+ return 20 + 7 * Math.max(0, piece.text.length - 1);+ }+ if (piece.kind === "code") {+ return estimateAgentRunWidth(piece.text, size * 0.875, true) + 10;+ }+ return estimateAgentRunWidth(piece.text, size);+}++interface Atom {+ pieces: AgentRunPiece[];+ width: number;+ space: boolean;+}++function atomsOf(inline: readonly AgentRunInline[], size: number): Atom[] {+ const atoms: Atom[] = [];+ let word: AgentRunPiece[] = [];+ let wordWidth = 0;+ const add = (piece: AgentRunPiece) => {+ word.push(piece);+ wordWidth += pieceWidth(piece, size);+ };+ const close = () => {+ if (word.length > 0) {+ atoms.push({ pieces: word, width: wordWidth, space: false });+ }+ word = [];+ wordWidth = 0;+ };+ for (const segment of inline) {+ if (segment.kind === "cite" || segment.kind === "code") {+ add({ ...segment });+ continue;+ }+ let index = 0;+ while (index < segment.text.length) {+ const space = segment.text[index] === " ";+ let stop = index;+ while (+ stop < segment.text.length &&+ (segment.text[stop] === " ") === space+ ) {+ stop += 1;+ }+ const piece: AgentRunPiece = {+ kind: segment.kind,+ text: segment.text.slice(index, stop),+ raw: segment.raw + index,+ end: segment.raw + stop,+ };+ if (space) {+ close();+ atoms.push({+ pieces: [piece],+ width: pieceWidth(piece, size),+ space: true,+ });+ } else {+ add(piece);+ }+ index = stop;+ }+ }+ close();+ return atoms;+}++function mergePieces(pieces: readonly AgentRunPiece[]) {+ const merged: AgentRunPiece[] = [];+ for (const piece of pieces) {+ const last = merged.at(-1);+ const text = piece.kind === "text" || piece.kind === "bold";+ if (text && last?.kind === piece.kind && last.end === piece.raw) {+ merged[merged.length - 1] = {+ ...last,+ text: last.text + piece.text,+ end: piece.end,+ };+ } else {+ merged.push({ ...piece });+ }+ }+ return merged;+}++export function wrapAgentRunInline(+ inline: readonly AgentRunInline[],+ size: number,+ maxWidth: number,+): AgentRunPiece[][] {+ const lines: AgentRunPiece[][] = [];+ let line: AgentRunPiece[] = [];+ let width = 0;+ let pending: Atom | undefined;+ for (const atom of atomsOf(inline, size)) {+ if (atom.space) {+ if (line.length > 0) pending = atom;+ continue;+ }+ const gap = pending ? pending.width : 0;+ if (line.length > 0 && width + gap + atom.width > maxWidth) {+ lines.push(line);+ line = [...atom.pieces];+ width = atom.width;+ } else {+ if (pending && line.length > 0) {+ line.push(...pending.pieces);+ width += gap;+ }+ line.push(...atom.pieces);+ width += atom.width;+ }+ pending = undefined;+ }+ if (line.length > 0) lines.push(line);+ return lines.map(mergePieces);+}++function plainInline(text: string, raw: number): AgentRunInline[] {+ return text.length > 0+ ? [{ kind: "text", text, raw, end: raw + text.length }]+ : [];+}++function textLines(+ pieces: AgentRunPiece[][],+ lineHeight: number,+ raw: number,+): AgentRunTextLine[] {+ if (pieces.length === 0) {+ return [{ y: 0, height: lineHeight, raw, pieces: [] }];+ }+ return pieces.map((line, index) => ({+ y: index * lineHeight,+ height: lineHeight,+ raw: line[0]?.raw ?? raw,+ pieces: line,+ }));+}++const PUNCT = "<>{}()[]/=;,.:+-*&|!?";++export function getAgentRunCodePieces(line: AgentRunCodeLine): AgentRunPiece[] {+ const pieces: AgentRunPiece[] = [];+ const push = (kind: AgentRunPieceKind, from: number, to: number) => {+ if (to <= from) return;+ const last = pieces.at(-1);+ if (last?.kind === kind && last.end === line.raw + from) {+ pieces[pieces.length - 1] = {+ ...last,+ text: last.text + line.text.slice(from, to),+ end: line.raw + to,+ };+ return;+ }+ pieces.push({+ kind,+ text: line.text.slice(from, to),+ raw: line.raw + from,+ end: line.raw + to,+ });+ };+ let index = 0;+ while (index < line.text.length) {+ const char = line.text[index];+ if (line.text.startsWith("//", index)) {+ push("comment", index, line.text.length);+ break;+ }+ if (char === '"' || char === "'" || char === "`") {+ const close = line.text.indexOf(char, index + 1);+ const stop = close === -1 ? line.text.length : close + 1;+ push("string", index, stop);+ index = stop;+ continue;+ }+ if (PUNCT.includes(char)) {+ push("punct", index, index + 1);+ index += 1;+ continue;+ }+ push("text", index, index + 1);+ index += 1;+ }+ return pieces;+}++export function getAgentRunFrame(width?: number, height?: number) {+ const frameWidth = Math.max(1, finite(width, 1280));+ const frameHeight = Math.max(1, finite(height, 720));+ const scale = Math.min(+ frameHeight / REF_HEIGHT,+ frameWidth / (PANEL_W + 2 * MARGIN_X),+ );+ const panelHeight = clamp(+ frameHeight / scale - 2 * MARGIN_Y,+ MIN_PANEL_H,+ MAX_PANEL_H,+ );+ return {+ width: frameWidth,+ height: frameHeight,+ unit: round(scale),+ panelWidth: PANEL_W,+ panelHeight: round(panelHeight),+ viewport: round(panelHeight - HEADER_H - 2),+ };+}++export type AgentRunFrame = ReturnType<typeof getAgentRunFrame>;++export interface AgentRunSegment {+ kind: "think" | "gap" | "tool" | "answer";+ from: number;+ to: number;+ realFrom: number;+ real: number;+}++export interface AgentRunToolSpan {+ index: number;+ start: number;+ end: number;+ span: number;+ duration: number;+ realStart: number;+}++function planTextOf(run: AgentRunScript) {+ return (run.plan ?? []).join("\n");+}++export function getAgentRunTimeline(+ run: AgentRunScript = defaultAgentRun,+ options: AgentRunOptions = {},+) {+ const seed = seedOf(options.seed);+ const compression = compressionOf(options.compression);+ const perFrame = compression / 30;+ const planText = planTextOf(run);+ const planChunks =+ planText.length > 0 ? getAgentRunChunks(planText, seed, "plan") : [];+ const planStart = RUN_START + THINK_LEAD;+ const planEnd = planStart + lastArrival(planChunks);+ const thinkEnd = planEnd + THINK_TAIL;+ const segments: AgentRunSegment[] = [];+ let real = 0;+ const push = (+ kind: AgentRunSegment["kind"],+ from: number,+ to: number,+ seconds: number,+ ) => {+ segments.push({ kind, from, to, realFrom: real, real: seconds });+ real += seconds;+ };+ push("think", RUN_START, thinkEnd, (thinkEnd - RUN_START) * perFrame);+ const thinkSeconds = real;+ const tools: AgentRunToolSpan[] = [];+ let cursor = thinkEnd;+ for (const [index, step] of (run.steps ?? []).entries()) {+ push("gap", cursor, cursor + TOOL_GAP, TOOL_GAP * perFrame);+ cursor += TOOL_GAP;+ const duration = Math.max(0, finite(step.duration, 0));+ const span = clamp(Math.round(duration / perFrame), TOOL_MIN, TOOL_MAX);+ const realStart = real;+ push("tool", cursor, cursor + span, duration);+ tools.push({+ index,+ start: cursor,+ end: cursor + span,+ span,+ duration,+ realStart,+ });+ cursor += span;+ }+ push("gap", cursor, cursor + ANSWER_GAP, ANSWER_GAP * perFrame);+ const answerStart = cursor + ANSWER_GAP;+ const answerChunks = getAgentRunChunks(run.answer, seed, "answer");+ const answerEnd = answerStart + lastArrival(answerChunks);+ push("answer", answerStart, answerEnd, (answerEnd - answerStart) * perFrame);+ return {+ compression,+ runStart: RUN_START,+ planStart,+ planEnd,+ thinkEnd,+ thinkSeconds,+ tools,+ answerStart,+ answerEnd,+ runEnd: answerEnd,+ settled: answerEnd + SETTLE,+ realTotal: real,+ segments,+ planChunks,+ answerChunks,+ };+}++export type AgentRunTimeline = ReturnType<typeof getAgentRunTimeline>;++export const agentRunLength = getAgentRunTimeline().settled;++export function getAgentRunDuration(+ run: AgentRunScript = defaultAgentRun,+ options: AgentRunOptions & Pick<AgentRunPlayback, "speed"> = {},+) {+ const rate = rateOf(options.speed);+ if (rate === 0) return HOLD;+ const { settled } = getAgentRunTimeline(run, options);+ return Math.ceil(round(settled / rate)) + HOLD;+}++export function getAgentRunTime(+ frame: number,+ playback: AgentRunPlayback = {},+) {+ const fps = Math.max(1, finite(playback.fps, 30));+ return Math.max(0, finite(frame, 0)) * (30 / fps) * rateOf(playback.speed);+}++export function getAgentRunElapsed(time: number, timeline: AgentRunTimeline) {+ if (!(time > timeline.runStart)) return 0;+ for (const segment of timeline.segments) {+ if (segment.to > segment.from && time < segment.to) {+ const share = (time - segment.from) / (segment.to - segment.from);+ return segment.realFrom + share * segment.real;+ }+ }+ return timeline.realTotal;+}++export interface AgentRunChipLayout {+ label: string;+ icon: "globe" | "file";+}++export interface AgentRunRowLayout {+ index: number;+ y: number;+ height: number;+ divider: boolean;+ icon: AgentRunIcon;+ name: string;+ detail: string;+ duration: string;+ chips: AgentRunChipLayout[];+ more: number;+}++export interface AgentRunPlanItemLayout {+ index: number;+ y: number;+ raw: number;+ lines: AgentRunTextLine[];+}++export interface AgentRunPlanSection {+ y: number;+ height: number;+ items: AgentRunPlanItemLayout[];+}++export interface AgentRunToolsSection {+ y: number;+ height: number;+ rows: AgentRunRowLayout[];+}++export type AgentRunBlockLayout =+ | {+ kind: "heading";+ index: number;+ y: number;+ height: number;+ level: 1 | 2;+ raw: number;+ end: number;+ mark: string;+ markWidth: number;+ lines: AgentRunTextLine[];+ }+ | {+ kind: "paragraph" | "item";+ index: number;+ y: number;+ height: number;+ raw: number;+ lines: AgentRunTextLine[];+ }+ | {+ kind: "code";+ index: number;+ y: number;+ height: number;+ raw: number;+ open: number;+ lang: string;+ langRaw: number;+ lines: AgentRunTextLine[];+ };++const DOMAIN = /^[a-z0-9-]+(\.[a-z0-9-]+)+(\/\S*)?$/i;++function chipWidth(label: string) {+ return 7 + 12 + 5 + estimateAgentRunWidth(label, CHIP_SIZE) + 9 + 2;+}++function moreWidth(count: number) {+ return 9 + estimateAgentRunWidth(`+${count}`, CHIP_SIZE) + 9 + 2;+}++export function fitAgentRunChips(sources: readonly string[]) {+ const chips: AgentRunChipLayout[] = [];+ let used = 0;+ for (const [index, label] of sources.entries()) {+ if (chips.length >= CHIP_MAX) break;+ const width = chipWidth(label) + (chips.length > 0 ? CHIP_GAP : 0);+ const rest = sources.length - index - 1;+ const reserve = rest > 0 ? CHIP_GAP + moreWidth(rest) : 0;+ if (used + width + reserve > CHIP_ROOM) break;+ chips.push({ label, icon: DOMAIN.test(label) ? "globe" : "file" });+ used += width;+ }+ return { chips, more: sources.length - chips.length };+}++const lineText = (line: readonly AgentRunPiece[]) =>+ line.map((piece) => piece.text).join("");++function blockGap(+ previous: AgentRunBlock["kind"] | undefined,+ next: AgentRunBlock["kind"],+) {+ if (previous === undefined) return 0;+ if (previous === "item" && next === "item") return ITEM_GAP;+ if (previous === "code" || next === "code") return CODE_GAP;+ if (previous === "heading") return HEADING_GAP;+ return BLOCK_GAP;+}++export function getAgentRunLayout(run: AgentRunScript = defaultAgentRun) {+ let y = PAD_TOP;+ const prompt = plainInline(run.prompt, 0);+ const wrappedPrompt = wrapAgentRunInline(prompt, BUBBLE_SIZE, BUBBLE_WIDTH);+ const promptLines = wrappedPrompt.map(lineText);+ const bubble = {+ y,+ height: Math.max(1, promptLines.length) * BUBBLE_LINE + 2 * BUBBLE_PAD_Y,+ lines: promptLines,+ };+ y += bubble.height + BUBBLE_GAP;+ const status = { y, height: STATUS_H };+ y += STATUS_H;+ let plan: AgentRunPlanSection | null = null;+ const planLines = run.plan ?? [];+ if (planLines.length > 0) {+ y += STATUS_GAP;+ const items: AgentRunPlanItemLayout[] = [];+ let cursor = 0;+ let raw = 0;+ for (const [index, text] of planLines.entries()) {+ if (index > 0) cursor += PLAN_GAP;+ const inline = plainInline(text, raw);+ const wrapped = wrapAgentRunInline(inline, PLAN_SIZE, PLAN_WIDTH);+ const lines = textLines(wrapped, PLAN_LINE, raw);+ items.push({ index, y: cursor, raw, lines });+ cursor += lines.length * PLAN_LINE;+ raw += text.length + 1;+ }+ plan = { y, height: cursor, items };+ y += cursor;+ }+ let tools: AgentRunToolsSection | null = null;+ const steps = run.steps ?? [];+ if (steps.length > 0) {+ y += PLAN_AFTER;+ const rows: AgentRunRowLayout[] = [];+ let cursor = 0;+ for (const [index, step] of steps.entries()) {+ const sources = step.sources ?? [];+ const fit = fitAgentRunChips(sources);+ const height =+ ROW_H + (index > 0 ? 1 : 0) + (sources.length > 0 ? CHIPS_H : 0);+ rows.push({+ index,+ y: cursor,+ height,+ divider: index > 0,+ icon: step.icon ?? (sources.length > 0 ? "book" : "terminal"),+ name: step.name,+ detail: step.detail ?? "",+ duration: formatAgentRunSeconds(finite(step.duration, 0)),+ chips: fit.chips,+ more: fit.more,+ });+ cursor += height;+ }+ tools = { y, height: cursor + 2, rows };+ y += cursor + 2;+ }+ const parsed = parseAgentRunMarkdown(run.answer);+ const blocks: AgentRunBlockLayout[] = [];+ if (parsed.length > 0) y += tools ? TOOLS_AFTER : PLAN_AFTER;+ let previous: AgentRunBlock["kind"] | undefined;+ for (const [index, block] of parsed.entries()) {+ y += blockGap(previous, block.kind);+ previous = block.kind;+ if (block.kind === "heading") {+ const spec = HEADINGS[block.level];+ const wrapped = wrapAgentRunInline(block.inline, spec.size, MEASURE);+ const lines = textLines(wrapped, spec.line, block.body);+ const mark = run.answer.slice(block.raw, block.body);+ blocks.push({+ kind: "heading",+ index,+ y,+ height: lines.length * spec.line,+ level: block.level,+ raw: block.raw,+ end: block.end,+ mark,+ markWidth: round(estimateAgentRunWidth(mark, BODY_SIZE)),+ lines,+ });+ y += lines.length * spec.line;+ continue;+ }+ if (block.kind === "code") {+ const lines = block.lines.map((line, row) => ({+ y: row * CODE_LINE,+ height: CODE_LINE,+ raw: line.raw,+ pieces: getAgentRunCodePieces(line),+ }));+ const height = CODE_HEAD + 2 * CODE_PAD + lines.length * CODE_LINE;+ blocks.push({+ kind: "code",+ index,+ y,+ height,+ raw: block.raw,+ open: block.open,+ lang: block.lang,+ langRaw: block.langRaw,+ lines,+ });+ y += height;+ continue;+ }+ const width = block.kind === "item" ? MEASURE - ITEM_INDENT : MEASURE;+ const body = block.kind === "item" ? block.body : block.raw;+ const wrapped = wrapAgentRunInline(block.inline, BODY_SIZE, width);+ const lines = textLines(wrapped, BODY_LINE, body);+ blocks.push({+ kind: block.kind,+ index,+ y,+ height: lines.length * BODY_LINE,+ raw: block.raw,+ lines,+ });+ y += lines.length * BODY_LINE;+ }+ return { bubble, status, plan, tools, blocks, height: y };+}++export type AgentRunLayout = ReturnType<typeof getAgentRunLayout>;++export interface AgentRunScrollStep {+ at: number;+ delta: number;+}++export function getAgentRunGrowth(+ layout: AgentRunLayout,+ timeline: AgentRunTimeline,+) {+ const events: { at: number; bottom: number }[] = [+ { at: BUBBLE_AT, bottom: layout.bubble.y + layout.bubble.height },+ { at: RUN_START, bottom: layout.status.y + layout.status.height },+ ];+ const { plan, tools } = layout;+ if (plan) {+ for (const item of plan.items) {+ for (const line of item.lines) {+ const at = getAgentRunArrival(timeline.planChunks, line.raw);+ events.push({+ at: timeline.planStart + at,+ bottom: plan.y + item.y + line.y + line.height,+ });+ }+ }+ }+ if (tools) {+ for (const row of tools.rows) {+ const span = timeline.tools[row.index];+ events.push({ at: span.start, bottom: tools.y + row.y + row.height + 2 });+ }+ }+ const arrival = (offset: number) =>+ timeline.answerStart + getAgentRunArrival(timeline.answerChunks, offset);+ for (const block of layout.blocks) {+ if (block.kind === "code") {+ events.push({+ at: arrival(block.open - 1),+ bottom: block.y + CODE_HEAD + 2 * CODE_PAD,+ });+ for (const line of block.lines) {+ events.push({+ at: arrival(line.raw),+ bottom: block.y + CODE_HEAD + 2 * CODE_PAD + line.y + line.height,+ });+ }+ continue;+ }+ for (const [row, line] of block.lines.entries()) {+ const start = row === 0 ? block.raw : line.raw;+ events.push({+ at: arrival(start),+ bottom: block.y + line.y + line.height,+ });+ }+ }+ return events+ .filter((event) => Number.isFinite(event.at))+ .sort((a, b) => a.at - b.at);+}++export function getAgentRunScrollSteps(+ layout: AgentRunLayout,+ timeline: AgentRunTimeline,+ viewport: number,+): AgentRunScrollStep[] {+ const steps: AgentRunScrollStep[] = [];+ let target = 0;+ for (const event of getAgentRunGrowth(layout, timeline)) {+ const next = Math.max(target, event.bottom + SAFE - viewport);+ if (next > target) {+ steps.push({ at: event.at, delta: round(next - target) });+ }+ target = next;+ }+ return steps;+}++export function getAgentRunScroll(+ time: number,+ steps: readonly AgentRunScrollStep[],+) {+ let total = 0;+ for (const step of steps) {+ const since = time - step.at + SCROLL_LEAD;+ if (since <= 0) break;+ total += step.delta * smoothstep(since / SCROLL);+ }+ return total;+}++export function getAgentRunModel(+ run: AgentRunScript = defaultAgentRun,+ options: AgentRunOptions = {},+) {+ const stage = getAgentRunFrame(options.width, options.height);+ const timeline = getAgentRunTimeline(run, options);+ const layout = getAgentRunLayout(run);+ const scroll = getAgentRunScrollSteps(layout, timeline, stage.viewport);+ return { run, stage, timeline, layout, scroll };+}++export type AgentRunModel = ReturnType<typeof getAgentRunModel>;++export interface AgentRunSpinnerState {+ angle: number;+ arc: number;+ done: number;+ check: number;+ resolved: boolean;+}++export function getAgentRunSpinner(+ time: number,+ start: number,+ end: number,+): AgentRunSpinnerState {+ const spinning = clamp(time - start, 0, Math.max(0, end - start));+ const since = time - end;+ const settle = progress(since / RESOLVE);+ const coast = SPIN * RESOLVE * (settle - (settle * settle) / 2);+ return {+ angle: round(spinning * SPIN + coast - 90),+ arc: round(ARC + (1 - ARC) * expo(since / RESOLVE)),+ done: round(smoothstep(since / RESOLVE)),+ check: round(easeOut((since - CHECK_FROM) / (CHECK_TO - CHECK_FROM))),+ resolved: since >= 0,+ };+}++export function getAgentRunShimmer(time: number, length: number) {+ const cycle = (time - RUN_START) / SHIMMER_PERIOD;+ const phase = cycle - Math.floor(cycle);+ const center = -SHIMMER_BAND + phase * (length + 2 * SHIMMER_BAND);+ return Array.from({ length }, (_, index) => {+ const distance = Math.abs(index + 0.5 - center) / SHIMMER_BAND;+ const band = distance < 1 ? (1 - distance * distance) ** 2 : 0;+ return round(SHIMMER_BASE + (1 - SHIMMER_BASE) * band);+ });+}++export interface AgentRunFragment {+ text: string;+ opacity: number;+}++export interface AgentRunSpan {+ kind: AgentRunPieceKind;+ fragments: AgentRunFragment[];+ opacity: number;+ scale: number;+}++export interface AgentRunLineState {+ key: string;+ y: number;+ height: number;+ spans: AgentRunSpan[];+}++const fadeOf = (since: number) => round(easeOut((since + 1) / FADE));++function spansOf(+ pieces: readonly AgentRunPiece[],+ chunks: readonly AgentRunChunk[],+ local: number,+ revealed: number,+): AgentRunSpan[] {+ const spans: AgentRunSpan[] = [];+ for (const piece of pieces) {+ if (piece.kind === "cite") {+ if (revealed < piece.end) continue;+ const since = local - getAgentRunArrival(chunks, piece.end - 1);+ spans.push({+ kind: "cite",+ fragments: [{ text: piece.text, opacity: 1 }],+ opacity: round(easeOut((since + 1) / 4)),+ scale: round(0.6 + 0.4 * backOut((since + 1) / POP, CITE_BACK)),+ });+ continue;+ }+ const visible = clamp(revealed - piece.raw, 0, piece.text.length);+ if (visible === 0) continue;+ const fragments: AgentRunFragment[] = [];+ let offset = 0;+ while (offset < visible) {+ const index = chunkIndexAt(chunks, piece.raw + offset);+ const chunk = chunks[index];+ const stop = chunk ? Math.min(visible, chunk.end - piece.raw) : visible;+ const opacity = chunk ? fadeOf(local - chunk.at) : 1;+ const text = piece.text.slice(offset, stop);+ const last = fragments.at(-1);+ if (last?.opacity === 1 && opacity === 1) {+ fragments[fragments.length - 1] = { text: last.text + text, opacity };+ } else {+ fragments.push({ text, opacity });+ }+ offset = Math.max(stop, offset + 1);+ }+ spans.push({ kind: piece.kind, fragments, opacity: 1, scale: 1 });+ }+ return spans;+}++export type AgentRunBlockState =+ | {+ kind: "heading";+ key: string;+ y: number;+ level: 1 | 2;+ styled: boolean;+ morph: number;+ mark: string;+ markWidth: number;+ lines: AgentRunLineState[];+ }+ | { kind: "paragraph"; key: string; y: number; lines: AgentRunLineState[] }+ | {+ kind: "item";+ key: string;+ y: number;+ dot: number;+ dotOpacity: number;+ lines: AgentRunLineState[];+ }+ | {+ kind: "code";+ key: string;+ y: number;+ height: number;+ opacity: number;+ lang: string;+ lines: AgentRunLineState[];+ };++function blockState(+ block: AgentRunBlockLayout,+ text: string,+ chunks: readonly AgentRunChunk[],+ local: number,+ revealed: number,+): AgentRunBlockState | null {+ const key = `block-${block.index}`;+ const lineStates = (from: number) => {+ const lines: AgentRunLineState[] = [];+ for (const [row, line] of block.lines.entries()) {+ if (revealed <= (row === 0 ? from : line.raw)) break;+ lines.push({+ key: `${key}-line-${row}`,+ y: line.y,+ height: line.height,+ spans: spansOf(line.pieces, chunks, local, revealed),+ });+ }+ return lines;+ };+ if (block.kind === "code") {+ if (revealed < block.open) return null;+ const since = local - getAgentRunArrival(chunks, block.open - 1);+ let height = expo((since + 1) / CODE_OPEN) * (CODE_HEAD + 2 * CODE_PAD);+ const lines: AgentRunLineState[] = [];+ for (const [row, line] of block.lines.entries()) {+ if (revealed <= line.raw) break;+ const grown = local - getAgentRunArrival(chunks, line.raw);+ height += expo((grown + 1) / LINE_GROW) * CODE_LINE;+ lines.push({+ key: `${key}-line-${row}`,+ y: line.y,+ height: line.height,+ spans: spansOf(line.pieces, chunks, local, revealed),+ });+ }+ const langShown = clamp(revealed - block.langRaw, 0, block.lang.length);+ return {+ kind: "code",+ key,+ y: block.y,+ height: round(height),+ opacity: round(easeOut((since + 1) / 4)),+ lang: block.lang.slice(0, langShown),+ lines,+ };+ }+ if (revealed <= block.raw) return null;+ if (block.kind === "heading") {+ const complete =+ revealed > block.end ||+ (block.end >= text.length && revealed >= block.end);+ const completeAt = getAgentRunArrival(+ chunks,+ Math.min(block.end, text.length - 1),+ );+ const morph = complete ? round(expo((local - completeAt) / MORPH)) : 0;+ const markShown = clamp(revealed - block.raw, 0, block.mark.length);+ return {+ kind: "heading",+ key,+ y: block.y,+ level: block.level,+ styled: complete,+ morph,+ mark: block.mark.slice(0, markShown),+ markWidth: block.markWidth,+ lines: lineStates(block.raw),+ };+ }+ if (block.kind === "item") {+ const since = local - getAgentRunArrival(chunks, block.raw);+ return {+ kind: "item",+ key,+ y: block.y,+ dot: round(backOut((since + 1) / POP, DOT_BACK)),+ dotOpacity: round(easeOut((since + 1) / 3)),+ lines: lineStates(block.raw),+ };+ }+ return { kind: "paragraph", key, y: block.y, lines: lineStates(block.raw) };+}++export interface AgentRunPlanItemState {+ key: string;+ index: number;+ y: number;+ numberOpacity: number;+ lines: AgentRunLineState[];+}++function planState(+ plan: AgentRunPlanSection,+ chunks: readonly AgentRunChunk[],+ local: number,+) {+ const revealed = getAgentRunReveal(chunks, local);+ const items: AgentRunPlanItemState[] = [];+ let rule = 0;+ for (const item of plan.items) {+ if (revealed <= item.raw) break;+ const lines: AgentRunLineState[] = [];+ for (const [row, line] of item.lines.entries()) {+ if (revealed <= (row === 0 ? item.raw : line.raw)) break;+ const since = local - getAgentRunArrival(chunks, line.raw);+ const grown = line.height * expo((since + 1) / LINE_GROW);+ rule = Math.max(rule, item.y + line.y + grown);+ lines.push({+ key: `plan-${item.index}-line-${row}`,+ y: line.y,+ height: line.height,+ spans: spansOf(line.pieces, chunks, local, revealed),+ });+ }+ const numbered = local - getAgentRunArrival(chunks, item.raw);+ items.push({+ key: `plan-${item.index}`,+ index: item.index,+ y: item.y,+ numberOpacity: fadeOf(numbered),+ lines,+ });+ }+ return { y: plan.y, rule: round(rule), items };+}++function chipPops(count: number, since: number, span: number) {+ const spread = Math.max(0, CHIP_SPAN * span - CHIP_LEAD);+ const step = count > 1 ? spread / (count - 1) : 0;+ return Array.from({ length: count }, (_, index) => {+ const age = since - CHIP_LEAD - index * step;+ return {+ visible: age >= 0,+ opacity: round(easeOut((age + 1) / 4)),+ scale: round(0.8 + 0.2 * backOut((age + 1) / POP, CHIP_BACK)),+ };+ });+}++function toolsState(+ tools: AgentRunToolsSection,+ timeline: AgentRunTimeline,+ time: number,+) {+ let height = 2;+ const rows = tools.rows+ .filter((row) => time >= timeline.tools[row.index].start)+ .map((row) => {+ const span = timeline.tools[row.index];+ const since = time - span.start;+ const open = expo(since / ROW_IN);+ height += row.height * open;+ const pops = chipPops(+ row.chips.length + (row.more > 0 ? 1 : 0),+ since,+ span.span,+ );+ const more = pops[row.chips.length];+ return {+ key: `tool-${row.index}`,+ index: row.index,+ y: row.y,+ height: round(row.height * open),+ divider: row.divider,+ icon: row.icon,+ name: row.name,+ detail: row.detail,+ duration: row.duration,+ content: round(easeOut((since - 1) / ROW_FADE)),+ spinner: getAgentRunSpinner(time, span.start, span.end),+ label: round(easeOut((time - span.end - LABEL_DELAY) / LABEL_FADE)),+ chips: row.chips.map((chip, index) => ({ ...chip, ...pops[index] })),+ more: row.more > 0 && more ? { count: row.more, ...more } : null,+ sources: row.chips.length + row.more > 0,+ };+ });+ return { y: tools.y, height: round(height), rows };+}++export function getAgentRunState(+ frame: number,+ model: AgentRunModel = getAgentRunModel(),+ playback: AgentRunPlayback = {},+) {+ const time = getAgentRunTime(frame, playback);+ const { run, stage, timeline, layout } = model;+ const elapsed = getAgentRunElapsed(time, timeline);+ const planLocal = time - timeline.planStart;+ const answerLocal = time - timeline.answerStart;+ const answerRevealed = getAgentRunReveal(timeline.answerChunks, answerLocal);+ const running = time - RUN_START;+ const swap =+ time >= timeline.thinkEnd ? expo((time - timeline.thinkEnd) / SWAP) : 0;+ const thinking = "Thinking";+ const blocks: AgentRunBlockState[] = [];+ for (const block of layout.blocks) {+ const next = blockState(+ block,+ run.answer,+ timeline.answerChunks,+ answerLocal,+ answerRevealed,+ );+ if (next) blocks.push(next);+ }+ return {+ time,+ elapsed,+ scroll: round(getAgentRunScroll(time, model.scroll)),+ panel: {+ width: stage.panelWidth,+ height: stage.panelHeight,+ viewport: stage.viewport,+ unit: stage.unit,+ opacity: round(easeOut((time + 1) / PANEL_IN)),+ lift: round(PANEL_RISE * (1 - expo(time / PANEL_IN))),+ },+ header: {+ title: run.title ?? "",+ label: formatAgentRunSeconds(elapsed),+ opacity: round(easeOut((running + 1) / STATUS_IN)),+ spinner: getAgentRunSpinner(time, RUN_START, timeline.runEnd),+ done: time >= timeline.runEnd,+ },+ bubble: {+ y: layout.bubble.y,+ height: layout.bubble.height,+ lines: layout.bubble.lines,+ opacity: round(easeOut((time - BUBBLE_AT + 1) / BUBBLE_IN)),+ lift: round(BUBBLE_RISE * (1 - expo((time - BUBBLE_AT) / BUBBLE_IN))),+ },+ status: {+ y: layout.status.y,+ visible: running >= 0,+ opacity: round(easeOut((running + 1) / STATUS_IN)),+ thinking,+ shimmer: getAgentRunShimmer(time, thinking.length),+ thought: `Thought for ${Math.max(1, Math.round(timeline.thinkSeconds))}s`,+ swap: round(swap),+ lift: round(SWAP_RISE * (1 - swap)),+ },+ plan: layout.plan+ ? planState(layout.plan, timeline.planChunks, planLocal)+ : null,+ tools: layout.tools ? toolsState(layout.tools, timeline, time) : null,+ blocks,+ revealed: {+ plan: getAgentRunReveal(timeline.planChunks, planLocal),+ answer: answerRevealed,+ },+ };+}++export type AgentRunState = ReturnType<typeof getAgentRunState>;++interface AgentRunSurface {+ panel: string;+ border: string;+ divider: string;+ fg: string;+ muted: string;+ subtle: string;+ surface: string;+ surfaceBorder: string;+ code: string;+ track: string;+ shadow: string;+}++export interface AgentRunPalette extends AgentRunSurface {+ accent: string;+ accentTint: string;+ accentText: string;+}++export const AGENT_RUN_THEMES: Record<AgentRunTheme, AgentRunSurface> = {+ light: {+ panel: "#ffffff",+ border: "#e4e4e0",+ divider: "#ededea",+ fg: "#1c1c1a",+ muted: "#63635e",+ subtle: "#9a9a94",+ surface: "#f3f3f1",+ surfaceBorder: "#e7e7e3",+ code: "#f8f8f6",+ track: "#e3e3df",+ shadow: "0 1px 2px rgba(28, 28, 26, 0.06)",+ },+ dark: {+ panel: "#161616",+ border: "#2b2b2a",+ divider: "#232322",+ fg: "#ececea",+ muted: "#a2a29d",+ subtle: "#6d6d68",+ surface: "#212120",+ surfaceBorder: "#2e2e2d",+ code: "#1c1c1b",+ track: "#343433",+ shadow: "0 1px 2px rgba(0, 0, 0, 0.5)",+ },+};++export function getAgentRunPalette(+ theme = agentRunDefaults.theme,+ accentColor = agentRunDefaults.accentColor,+): AgentRunPalette {+ const dark = theme === "dark";+ const tint = dark ? 22 : 12;+ return {+ ...AGENT_RUN_THEMES[dark ? "dark" : "light"],+ accent: accentColor,+ accentTint: `color-mix(in srgb, ${accentColor} ${tint}%, transparent)`,+ accentText: dark+ ? `color-mix(in srgb, ${accentColor} 62%, #ffffff)`+ : accentColor,+ };+}++type IconNode =+ | { tag: "path"; d: string }+ | { tag: "circle"; cx: number; cy: number; r: number }+ | { tag: "ellipse"; cx: number; cy: number; rx: number; ry: number }+ | {+ tag: "rect";+ x: number;+ y: number;+ width: number;+ height: number;+ rx: number;+ };++type IconName = AgentRunIcon | "copy";++const ICONS: Record<IconName, readonly IconNode[]> = {+ chart: [+ { tag: "path", d: "M3 3v16a2 2 0 0 0 2 2h16" },+ { tag: "path", d: "M18 17V9" },+ { tag: "path", d: "M13 17V5" },+ { tag: "path", d: "M8 17v-3" },+ ],+ database: [+ { tag: "ellipse", cx: 12, cy: 5, rx: 9, ry: 3 },+ { tag: "path", d: "M3 5V19A9 3 0 0 0 21 19V5" },+ { tag: "path", d: "M3 12A9 3 0 0 0 21 12" },+ ],+ search: [+ { tag: "path", d: "m21 21-4.34-4.34" },+ { tag: "circle", cx: 11, cy: 11, r: 8 },+ ],+ book: [+ { tag: "path", d: "M12 7v14" },+ {+ tag: "path",+ d: "M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",+ },+ ],+ globe: [+ { tag: "circle", cx: 12, cy: 12, r: 10 },+ { tag: "path", d: "M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20" },+ { tag: "path", d: "M2 12h20" },+ ],+ terminal: [+ { tag: "path", d: "M12 19h8" },+ { tag: "path", d: "m4 17 6-6-6-6" },+ ],+ file: [+ {+ tag: "path",+ d: "M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",+ },+ { tag: "path", d: "M14 2v5a1 1 0 0 0 1 1h5" },+ { tag: "path", d: "M10 9H8" },+ { tag: "path", d: "M16 13H8" },+ { tag: "path", d: "M16 17H8" },+ ],+ copy: [+ { tag: "rect", x: 8, y: 8, width: 14, height: 14, rx: 2 },+ {+ tag: "path",+ d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",+ },+ ],+};++function Icon({+ name,+ size,+ color,+}: {+ name: IconName;+ size: number;+ color: string;+}) {+ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ stroke={color}+ strokeWidth={2}+ strokeLinecap="round"+ strokeLinejoin="round"+ style={{ display: "block", flexShrink: 0 }}+ >+ {ICONS[name].map((node, index) => {+ if (node.tag === "path") return <path key={index} d={node.d} />;+ if (node.tag === "circle") {+ return <circle key={index} cx={node.cx} cy={node.cy} r={node.r} />;+ }+ if (node.tag === "ellipse") {+ return (+ <ellipse+ key={index}+ cx={node.cx}+ cy={node.cy}+ rx={node.rx}+ ry={node.ry}+ />+ );+ }+ return (+ <rect+ key={index}+ x={node.x}+ y={node.y}+ width={node.width}+ height={node.height}+ rx={node.rx}+ />+ );+ })}+ </svg>+ );+}++function Spinner({+ state,+ size,+ palette,+}: {+ state: AgentRunSpinnerState;+ size: number;+ palette: AgentRunPalette;+}) {+ const active = 1 - state.done;+ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ strokeWidth={2}+ strokeLinecap="round"+ strokeLinejoin="round"+ style={{ display: "block", flexShrink: 0 }}+ >+ <circle cx={12} cy={12} r={10} stroke={palette.track} opacity={active} />+ <circle+ cx={12}+ cy={12}+ r={10}+ stroke={palette.accent}+ opacity={active}+ strokeDasharray={`${round(state.arc * CIRCLE)} ${round(CIRCLE)}`}+ transform={`rotate(${state.angle} 12 12)`}+ />+ <circle+ cx={12}+ cy={12}+ r={10}+ stroke={palette.muted}+ opacity={state.done}+ />+ <path+ d="m9 12 2 2 4-4"+ stroke={palette.muted}+ strokeDasharray={round(CHECK_LENGTH)}+ strokeDashoffset={round(CHECK_LENGTH * (1 - state.check))}+ opacity={state.check > 0 ? 1 : 0}+ />+ </svg>+ );+}++function spanStyle(+ span: AgentRunSpan,+ palette: AgentRunPalette,+): CSSProperties {+ if (span.kind === "bold") return { fontWeight: 600 };+ if (span.kind === "code") {+ return {+ fontFamily: MONO,+ fontSize: "0.875em",+ padding: "1px 5px",+ borderRadius: 5,+ background: palette.surface,+ border: `1px solid ${palette.surfaceBorder}`,+ };+ }+ if (span.kind === "cite") {+ return {+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ minWidth: 18,+ height: 18,+ padding: "0 5px",+ marginLeft: 2,+ borderRadius: 9,+ boxSizing: "border-box",+ background: palette.accentTint,+ color: palette.accentText,+ fontSize: 11.5,+ fontWeight: 600,+ lineHeight: "18px",+ fontVariantNumeric: "tabular-nums",+ verticalAlign: "middle",+ opacity: span.opacity,+ transform: `scale(${span.scale})`,+ };+ }+ if (span.kind === "punct" || span.kind === "comment") {+ return { color: palette.subtle };+ }+ if (span.kind === "string") return { color: palette.muted };+ return {};+}++function renderSpans(spans: readonly AgentRunSpan[], palette: AgentRunPalette) {+ return spans.map((span, index) => (+ <span key={index} style={spanStyle(span, palette)}>+ {span.fragments.map((fragment, part) => (+ <span+ key={part}+ style={+ fragment.opacity < 1 ? { opacity: fragment.opacity } : undefined+ }+ >+ {fragment.text}+ </span>+ ))}+ </span>+ ));+}++function AnswerBlock({+ block,+ palette,+}: {+ block: AgentRunBlockState;+ palette: AgentRunPalette;+}) {+ if (block.kind === "code") {+ return (+ <div+ style={{+ position: "absolute",+ top: block.y,+ left: 0,+ width: COLUMN,+ height: block.height,+ opacity: block.opacity,+ overflow: "hidden",+ boxSizing: "border-box",+ border: `1px solid ${palette.surfaceBorder}`,+ borderRadius: 10,+ background: palette.code,+ }}+ >+ <div+ style={{+ height: CODE_HEAD,+ boxSizing: "border-box",+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ padding: "0 12px 0 16px",+ borderBottom: `1px solid ${palette.divider}`,+ fontFamily: MONO,+ fontSize: 12.5,+ color: palette.muted,+ }}+ >+ <span>{block.lang}</span>+ <Icon name="copy" size={14} color={palette.subtle} />+ </div>+ {block.lines.map((line) => (+ <div+ key={line.key}+ style={{+ position: "absolute",+ top: CODE_HEAD + CODE_PAD - 1 + line.y,+ left: 16,+ height: line.height,+ lineHeight: `${line.height}px`,+ fontFamily: MONO,+ fontSize: CODE_SIZE,+ whiteSpace: "pre",+ color: palette.fg,+ }}+ >+ {renderSpans(line.spans, palette)}+ </div>+ ))}+ </div>+ );+ }+ if (block.kind === "heading") {+ const spec = HEADINGS[block.level];+ const from = BODY_SIZE / spec.size;+ const scale = block.styled ? from + (1 - from) * block.morph : 1;+ return (+ <div>+ {block.lines.map((line, index) => (+ <div+ key={line.key}+ style={{+ position: "absolute",+ top: block.y + line.y,+ left: 0,+ height: line.height,+ display: "flex",+ alignItems: "center",+ whiteSpace: "pre",+ }}+ >+ {index === 0 && block.mark.length > 0 && block.morph < 1 ? (+ <span+ style={{+ maxWidth: block.markWidth * (1 - block.morph),+ overflow: "hidden",+ flexShrink: 0,+ opacity: 1 - block.morph,+ fontSize: BODY_SIZE,+ color: palette.subtle,+ }}+ >+ {block.mark}+ </span>+ ) : null}+ <span+ style={{+ fontSize: block.styled ? spec.size : BODY_SIZE,+ fontWeight: Math.round(400 + 200 * block.morph),+ lineHeight: 1.25,+ transform: `scale(${round(scale)})`,+ transformOrigin: "0 50%",+ }}+ >+ {renderSpans(line.spans, palette)}+ </span>+ </div>+ ))}+ </div>+ );+ }+ const indent = block.kind === "item" ? ITEM_INDENT : 0;+ return (+ <div>+ {block.kind === "item" ? (+ <div+ style={{+ position: "absolute",+ top: block.y + BODY_LINE / 2 - 3,+ left: 5,+ width: 6,+ height: 6,+ borderRadius: 3,+ background: palette.fg,+ opacity: block.dotOpacity,+ transform: `scale(${block.dot})`,+ }}+ />+ ) : null}+ {block.lines.map((line) => (+ <div+ key={line.key}+ style={{+ position: "absolute",+ top: block.y + line.y,+ left: indent,+ height: line.height,+ lineHeight: `${line.height}px`,+ whiteSpace: "pre",+ }}+ >+ {renderSpans(line.spans, palette)}+ </div>+ ))}+ </div>+ );+}++function Header({+ header,+ palette,+}: {+ header: AgentRunState["header"];+ palette: AgentRunPalette;+}) {+ return (+ <div+ style={{+ height: HEADER_H,+ boxSizing: "border-box",+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ gap: 16,+ padding: `0 ${PAD_X}px`,+ borderBottom: `1px solid ${palette.divider}`,+ }}+ >+ <span+ style={{+ minWidth: 0,+ fontSize: 14,+ fontWeight: 500,+ whiteSpace: "nowrap",+ overflow: "hidden",+ textOverflow: "ellipsis",+ }}+ >+ {header.title}+ </span>+ <div+ style={{+ display: "flex",+ alignItems: "center",+ gap: 7,+ flexShrink: 0,+ opacity: header.opacity,+ }}+ >+ <Spinner state={header.spinner} size={14} palette={palette} />+ <span+ style={{+ minWidth: 38,+ fontSize: 13,+ color: palette.muted,+ fontVariantNumeric: "tabular-nums",+ textAlign: "right",+ }}+ >+ {header.label}+ </span>+ </div>+ </div>+ );+}++function Bubble({+ bubble,+ palette,+}: {+ bubble: AgentRunState["bubble"];+ palette: AgentRunPalette;+}) {+ return (+ <div+ style={{+ position: "absolute",+ top: bubble.y,+ right: 0,+ padding: `${BUBBLE_PAD_Y}px ${BUBBLE_PAD_X}px`,+ borderRadius: 18,+ background: palette.surface,+ fontSize: BUBBLE_SIZE,+ lineHeight: `${BUBBLE_LINE}px`,+ whiteSpace: "pre",+ opacity: bubble.opacity,+ transform: `translateY(${bubble.lift}px)`,+ }}+ >+ {bubble.lines.map((line, index) => (+ <div key={index}>{line}</div>+ ))}+ </div>+ );+}++function Status({+ status,+ palette,+}: {+ status: AgentRunState["status"];+ palette: AgentRunPalette;+}) {+ if (!status.visible) return null;+ return (+ <div+ style={{+ position: "absolute",+ top: status.y,+ left: 0,+ width: COLUMN,+ height: STATUS_H,+ fontSize: 15,+ fontWeight: 500,+ lineHeight: `${STATUS_H}px`,+ whiteSpace: "pre",+ opacity: status.opacity,+ }}+ >+ {status.swap < 1 ? (+ <span+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ opacity: 1 - status.swap,+ }}+ >+ {status.shimmer.map((level, index) => (+ <span key={index} style={{ opacity: level }}>+ {status.thinking[index]}+ </span>+ ))}+ </span>+ ) : null}+ {status.swap > 0 ? (+ <span+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ color: palette.muted,+ opacity: status.swap,+ transform: `translateY(${status.lift}px)`,+ }}+ >+ {status.thought}+ </span>+ ) : null}+ </div>+ );+}++function Plan({+ plan,+ palette,+}: {+ plan: NonNullable<AgentRunState["plan"]>;+ palette: AgentRunPalette;+}) {+ return (+ <div+ style={{+ position: "absolute",+ top: plan.y,+ left: 0,+ width: COLUMN,+ fontSize: PLAN_SIZE,+ color: palette.muted,+ }}+ >+ <div+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ width: 2,+ height: plan.rule,+ borderRadius: 1,+ background: palette.track,+ }}+ />+ {plan.items.map((item) => (+ <div key={item.key}>+ <span+ style={{+ position: "absolute",+ top: item.y,+ left: 14,+ lineHeight: `${PLAN_LINE}px`,+ color: palette.subtle,+ fontVariantNumeric: "tabular-nums",+ opacity: item.numberOpacity,+ }}+ >+ {`${item.index + 1}.`}+ </span>+ {item.lines.map((line) => (+ <div+ key={line.key}+ style={{+ position: "absolute",+ top: item.y + line.y,+ left: PLAN_INDENT,+ height: line.height,+ lineHeight: `${line.height}px`,+ whiteSpace: "pre",+ }}+ >+ {renderSpans(line.spans, palette)}+ </div>+ ))}+ </div>+ ))}+ </div>+ );+}++function chipStyle(+ palette: AgentRunPalette,+ pop: { opacity: number; scale: number },+ padding: string,+): CSSProperties {+ return {+ display: "inline-flex",+ alignItems: "center",+ gap: 5,+ height: 24,+ boxSizing: "border-box",+ padding,+ borderRadius: 7,+ border: `1px solid ${palette.surfaceBorder}`,+ background: palette.surface,+ fontSize: CHIP_SIZE,+ color: palette.muted,+ fontVariantNumeric: "tabular-nums",+ whiteSpace: "nowrap",+ opacity: pop.opacity,+ transform: `scale(${pop.scale})`,+ };+}++type AgentRunRowState = NonNullable<AgentRunState["tools"]>["rows"][number];++function ToolRow({+ row,+ palette,+}: {+ row: AgentRunRowState;+ palette: AgentRunPalette;+}) {+ const chips = row.chips.filter((chip) => chip.visible);+ return (+ <div+ style={{+ position: "absolute",+ top: row.y,+ left: 0,+ right: 0,+ height: row.height,+ overflow: "hidden",+ boxSizing: "border-box",+ borderTop: row.divider ? `1px solid ${palette.divider}` : undefined,+ }}+ >+ <div+ style={{+ height: ROW_H,+ display: "flex",+ alignItems: "center",+ gap: 10,+ padding: "0 14px",+ opacity: row.content,+ }}+ >+ <Icon name={row.icon} size={16} color={palette.muted} />+ <span+ style={{+ flexShrink: 0,+ fontSize: 15,+ fontWeight: 500,+ whiteSpace: "nowrap",+ }}+ >+ {row.name}+ </span>+ <span+ style={{+ flex: 1,+ minWidth: 0,+ fontSize: 15,+ color: palette.muted,+ whiteSpace: "nowrap",+ overflow: "hidden",+ textOverflow: "ellipsis",+ }}+ >+ {row.detail}+ </span>+ <span+ style={{+ fontSize: 13,+ color: palette.muted,+ fontVariantNumeric: "tabular-nums",+ opacity: row.label,+ }}+ >+ {row.duration}+ </span>+ <Spinner state={row.spinner} size={16} palette={palette} />+ </div>+ {row.sources ? (+ <div+ style={{+ display: "flex",+ gap: CHIP_GAP,+ height: CHIPS_H,+ padding: "0 14px 0 40px",+ opacity: row.content,+ }}+ >+ {chips.map((chip, index) => (+ <span+ key={`${index}-${chip.label}`}+ style={chipStyle(palette, chip, "0 9px 0 7px")}+ >+ <Icon name={chip.icon} size={12} color={palette.subtle} />+ {chip.label}+ </span>+ ))}+ {row.more?.visible ? (+ <span style={chipStyle(palette, row.more, "0 9px")}>+ {`+${row.more.count}`}+ </span>+ ) : null}+ </div>+ ) : null}+ </div>+ );+}++function Tools({+ tools,+ palette,+}: {+ tools: NonNullable<AgentRunState["tools"]>;+ palette: AgentRunPalette;+}) {+ if (tools.rows.length === 0) return null;+ return (+ <div+ style={{+ position: "absolute",+ top: tools.y,+ left: 0,+ width: COLUMN,+ height: tools.height,+ boxSizing: "border-box",+ overflow: "hidden",+ border: `1px solid ${palette.surfaceBorder}`,+ borderRadius: 12,+ }}+ >+ {tools.rows.map((row) => (+ <ToolRow key={row.key} row={row} palette={palette} />+ ))}+ </div>+ );+}++export function AgentRun({+ run = agentRunDefaults.run,+ theme = agentRunDefaults.theme,+ accentColor = agentRunDefaults.accentColor,+ compression = agentRunDefaults.compression,+ seed = agentRunDefaults.seed,+ speed = agentRunDefaults.speed,+ className,+}: AgentRunProps) {+ const frame = useCurrentFrame();+ const { width, height, fps } = useVideoConfig();+ const model = useMemo(+ () => getAgentRunModel(run, { seed, compression, width, height }),+ [run, seed, compression, width, height],+ );+ const state = getAgentRunState(frame, model, { fps, speed });+ const palette = getAgentRunPalette(theme, accentColor);+ const { panel } = state;++ return (+ <div className={className} style={{ position: "absolute", inset: 0 }}>+ <div+ style={{+ position: "absolute",+ left: "50%",+ top: "50%",+ width: panel.width,+ height: panel.height,+ translate: "-50% -50%",+ scale: `${panel.unit}`,+ }}+ >+ <div+ style={{+ position: "relative",+ width: "100%",+ height: "100%",+ boxSizing: "border-box",+ overflow: "hidden",+ opacity: panel.opacity,+ transform: `translateY(${panel.lift}px)`,+ background: palette.panel,+ border: `1px solid ${palette.border}`,+ borderRadius: 18,+ boxShadow: palette.shadow,+ color: palette.fg,+ fontFamily: SANS,+ fontSize: BODY_SIZE,+ WebkitFontSmoothing: "antialiased",+ }}+ >+ <Header header={state.header} palette={palette} />+ <div+ style={{+ position: "relative",+ height: panel.viewport,+ overflow: "hidden",+ }}+ >+ <div+ style={{+ position: "absolute",+ top: 0,+ left: PAD_X,+ width: COLUMN,+ transform: `translateY(${-state.scroll}px)`,+ }}+ >+ <Bubble bubble={state.bubble} palette={palette} />+ <Status status={state.status} palette={palette} />+ {state.plan ? <Plan plan={state.plan} palette={palette} /> : null}+ {state.tools ? (+ <Tools tools={state.tools} palette={palette} />+ ) : null}+ {state.blocks.map((block) => (+ <AnswerBlock key={block.key} block={block} palette={palette} />+ ))}+ </div>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/registry/remocn/bauhaus-build/__tests__/bauhaus-build.test.ts b/registry/remocn/bauhaus-build/__tests__/bauhaus-build.test.tsnew file mode 100644index 00000000..eceac78f--- /dev/null+++ b/registry/remocn/bauhaus-build/__tests__/bauhaus-build.test.ts@@ -0,0 +1,540 @@+import { describe, expect, it } from "bun:test";+import {+ bauhausBuildBand,+ bauhausBuildDefaults,+ bauhausBuildGrid,+ bauhausBuildLength,+ bauhausBuildPieces,+ bauhausBuildTimeline,+ getBauhausBuildDuration,+ getBauhausBuildField,+ getBauhausBuildOrder,+ getBauhausBuildState,+ getBauhausBuildVariant,+ getBauhausFootprint,+ getBauhausPaths,+ getBauhausPoseFrame,+ getBauhausShapePath,+ getBauhausStepFrame,+ getTumbleDuration,+ getTumbleProgress,+ getUnfoldScale,+} from "..";+import { bauhausBuildConfig } from "../config";++type Frame = ReturnType<typeof getBauhausPoseFrame>;+type Box = ReturnType<typeof getBauhausFootprint>;+type Piece = (typeof bauhausBuildPieces)[number];++interface Point {+ x: number;+ y: number;+}++const radians = (degrees: number) => (degrees * Math.PI) / 180;++const toWorld = (frame: Frame, point: Point): Point => {+ const cos = Math.cos(radians(frame.rotation)) * frame.scale;+ const sin = Math.sin(radians(frame.rotation)) * frame.scale;+ return {+ x: frame.x + point.x * cos - point.y * sin,+ y: frame.y + point.x * sin + point.y * cos,+ };+};++const toLocal = (frame: Frame, point: Point): Point => {+ const cos = Math.cos(radians(frame.rotation)) / frame.scale;+ const sin = Math.sin(radians(frame.rotation)) / frame.scale;+ const dx = point.x - frame.x;+ const dy = point.y - frame.y;+ return { x: dx * cos + dy * sin, y: dy * cos - dx * sin };+};++const lean = (a: number, b: number) => Math.abs(((a - b + 540) % 360) - 180);++const near = (a: Point, b: Point) =>+ Math.abs(a.x - b.x) < 1e-6 && Math.abs(a.y - b.y) < 1e-6;++const corners = (box: Box): Point[] => [+ { x: box.x0, y: box.y0 },+ { x: box.x1, y: box.y0 },+ { x: box.x1, y: box.y1 },+ { x: box.x0, y: box.y1 },+];++const localCorners = (piece: { width: number; height: number }) =>+ corners({ x0: 0, y0: 0, x1: piece.width, y1: piece.height });++const areaOf = (box: Box) => (box.x1 - box.x0) * (box.y1 - box.y0);++const overlaps = (a: Box, b: Box) =>+ a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1;++const pathsOf = (piece: Piece) => {+ const paths = getBauhausPaths(piece);+ return [paths.enter, paths.rebuild];+};++const specOf = (id: string) => {+ const piece = bauhausBuildPieces.find((candidate) => candidate.id === id);+ if (!piece) throw new Error(`missing piece ${id}`);+ return piece;+};++const pieceAt = (time: number, id: string, seed = 1) => {+ const frame = getBauhausBuildState(time, { seed }).pieces.find(+ (candidate) => candidate.id === id,+ );+ if (!frame) throw new Error(`missing frame ${id}`);+ return frame;+};++const insideShape = (piece: Piece, { x, y }: Point) => {+ const { width, height } = piece;+ const r = width / 2;+ if (x < 0 || y < 0 || x > width || y > height) return false;+ switch (piece.shape) {+ case "circle":+ return (x - r) ** 2 + (y - r) ** 2 <= r * r;+ case "semicircle":+ return (x - r) ** 2 + (y - height) ** 2 <= r * r;+ case "quarter":+ return x ** 2 + (y - height) ** 2 <= width * width;+ default:+ return true;+ }+};++const samplesOf = (piece: Piece) => {+ const points: Point[] = [];+ for (let i = 0; i <= piece.width * 6; i++) {+ for (let j = 0; j <= piece.height * 6; j++) {+ const point = { x: i / 6, y: j / 6 };+ if (insideShape(piece, point)) points.push(point);+ }+ }+ return points;+};++describe("bauhaus build timeline", () => {+ it("opens on an empty frame for every seed", () => {+ for (let seed = 1; seed <= 12; seed++) {+ for (const time of [0, 0.5]) {+ const { pieces } = getBauhausBuildState(time, { seed });+ expect(pieces.some((piece) => piece.visible)).toBe(false);+ }+ }+ });++ it("unfolds each arrival from its hinge and lands it on the six-frame beat", () => {+ const { lead, beat } = bauhausBuildTimeline;+ for (const seed of [1, 2, 5, 9]) {+ for (const [arrival, piece] of getBauhausBuildOrder(seed).entries()) {+ const duration = getTumbleDuration(piece);+ const land = lead + arrival * beat;+ const start = land - piece.enter.length * duration;+ expect(start).toBeGreaterThan(0.5);+ expect(pieceAt(start - 0.01, piece.id, seed).visible).toBe(false);+ const unfolding = pieceAt(start + 0.01, piece.id, seed);+ expect(unfolding.scale).toBeGreaterThan(0);+ expect(unfolding.scale).toBeLessThan(0.05);+ const grown = pieceAt(start + duration, piece.id, seed);+ expect(grown.scale).toBeCloseTo(1, 6);+ const rest = getBauhausPoseFrame(piece, piece.slot);+ const landing = pieceAt(land, piece.id, seed);+ expect(landing.pivot).not.toBeNull();+ expect(lean(landing.rotation, rest.rotation)).toBeCloseTo(4.5, 6);+ const settled = pieceAt(land + duration / 2 + 0.01, piece.id, seed);+ expect(settled).toMatchObject(rest);+ }+ }+ });++ it("holds the frieze from the last landing until the rebuild", () => {+ const settled = getBauhausBuildState(75.01).pieces;+ expect(getBauhausBuildState(89.99).pieces).toEqual(settled);+ for (const frame of settled) {+ const piece = specOf(frame.id);+ expect(frame).toMatchObject(getBauhausPoseFrame(piece, piece.slot));+ }+ });++ it("ends on the handoff at the documented length and holds it", () => {+ const moving = getBauhausBuildState(bauhausBuildLength - 1).pieces;+ expect(moving.some((frame) => frame.pivot !== null)).toBe(true);+ for (const time of [bauhausBuildLength, 150, 1000]) {+ for (const frame of getBauhausBuildState(time).pieces) {+ const piece = specOf(frame.id);+ const handoff = getBauhausPaths(piece).handoff;+ expect(frame).toMatchObject(getBauhausPoseFrame(piece, handoff));+ expect(frame.visible).toBe(true);+ }+ }+ });++ it("adjusts the preview duration with speed and loop", () => {+ expect(getBauhausBuildDuration()).toBe(150);+ expect(bauhausBuildConfig.durationInFrames).toBe(150);+ expect(bauhausBuildConfig.getDurationInFrames?.({ speed: 0.5 })).toBe(300);+ expect(getBauhausBuildDuration({ speed: 2 })).toBe(75);+ expect(getBauhausBuildDuration({ speed: 0 })).toBe(1);+ expect(getBauhausBuildDuration({ loop: true })).toBe(300);+ expect(getBauhausBuildDuration({ loop: true, speed: 2 })).toBe(150);+ });+});++describe("bauhaus build corner tumble", () => {+ it("hinges each quarter turn on a leading-edge corner and lands beyond it", () => {+ for (const piece of bauhausBuildPieces) {+ for (const path of pathsOf(piece)) {+ for (const step of path) {+ const from = getBauhausFootprint(piece, step.from);+ const to = getBauhausFootprint(piece, step.to);+ expect(corners(from)).toContainEqual(step.pivot);+ expect(corners(to)).toContainEqual(step.pivot);+ expect(step.to.turn).toBe((step.from.turn + step.spin + 4) % 4);+ expect(areaOf(to)).toBe(areaOf(from));+ switch (step.move.charAt(0)) {+ case "R":+ expect(step.pivot.x).toBe(from.x1);+ expect(to.x0).toBe(from.x1);+ break;+ case "L":+ expect(step.pivot.x).toBe(from.x0);+ expect(to.x1).toBe(from.x0);+ break;+ case "D":+ expect(step.pivot.y).toBe(from.y1);+ expect(to.y0).toBe(from.y1);+ break;+ default:+ expect(step.pivot.y).toBe(from.y0);+ expect(to.y1).toBe(from.y0);+ }+ }+ }+ }+ });++ it("moves the hinge to another corner after every quarter turn, into the rebuild too", () => {+ for (const piece of bauhausBuildPieces) {+ const paths = getBauhausPaths(piece);+ const hinges = [...paths.enter, ...paths.rebuild].map((step) => {+ const rest = getBauhausPoseFrame(piece, step.from);+ const local = toLocal(rest, step.pivot);+ return `${Math.round(local.x)},${Math.round(local.y)}`;+ });+ for (let index = 1; index < hinges.length; index++) {+ expect(hinges[index]).not.toBe(hinges[index - 1]);+ }+ }+ });++ it("hinges arcs and half disks on a point of the shape", () => {+ for (const piece of bauhausBuildPieces) {+ if (piece.shape === "circle") continue;+ const paths = getBauhausPaths(piece);+ for (const step of [...paths.enter, ...paths.rebuild]) {+ const rest = getBauhausPoseFrame(piece, step.from);+ const local = toLocal(rest, step.pivot);+ const hinge = { x: Math.round(local.x), y: Math.round(local.y) };+ expect(insideShape(piece, hinge)).toBe(true);+ }+ }+ });++ it("turns rigidly about a fixed hinge at every progress and unfold scale", () => {+ for (const piece of bauhausBuildPieces) {+ for (const path of pathsOf(piece)) {+ for (const step of path) {+ const rest = getBauhausPoseFrame(piece, step.from);+ const hinge = toLocal(rest, step.pivot);+ for (const progress of [0, 0.25, 0.5, 0.8, 1, 1.05]) {+ for (const grow of [0.2, 1]) {+ const frame = getBauhausStepFrame(piece, step, progress, grow);+ const point = toWorld(frame, hinge);+ expect(point.x).toBeCloseTo(step.pivot.x, 9);+ expect(point.y).toBeCloseTo(step.pivot.y, 9);+ }+ }+ }+ }+ }+ });++ it("lands exactly on the next rest pose after a full quarter turn", () => {+ for (const piece of bauhausBuildPieces) {+ const paths = getBauhausPaths(piece);+ expect(paths.enter.at(-1)?.to).toEqual(piece.slot);+ expect(paths.start).not.toEqual(piece.slot);+ for (const path of pathsOf(piece)) {+ for (const step of path) {+ const turned = getBauhausStepFrame(piece, step, 1);+ const rest = getBauhausPoseFrame(piece, step.to);+ expect(turned.x).toBeCloseTo(rest.x, 9);+ expect(turned.y).toBeCloseTo(rest.y, 9);+ expect(lean(turned.rotation, rest.rotation)).toBeCloseTo(0, 9);+ }+ }+ }+ });++ it("overshoots only on the landing turn, by at most 4.5 degrees", () => {+ for (const piece of bauhausBuildPieces) {+ const duration = getTumbleDuration(piece);+ let peak = 0;+ for (let sample = 0; sample <= 300; sample++) {+ const elapsed = (duration * 1.5 * sample) / 300;+ const travel = getTumbleProgress(elapsed, duration, false);+ expect(travel).toBeLessThanOrEqual(1);+ peak = Math.max(peak, getTumbleProgress(elapsed, duration, true));+ }+ expect(peak).toBeGreaterThan(1);+ expect((peak - 1) * 90).toBeLessThanOrEqual(4.5 + 1e-9);+ expect(getTumbleProgress(0, duration, true)).toBe(0);+ const settled = getTumbleProgress(duration * 1.5, duration, true);+ expect(settled).toBeCloseTo(1, 12);+ }+ expect(getUnfoldScale(0)).toBe(0);+ expect(getUnfoldScale(1)).toBe(1);+ expect(getUnfoldScale(0.5)).toBeGreaterThan(getUnfoldScale(0.25));+ });++ it("weighs larger pieces with slower quarter turns", () => {+ expect(getTumbleDuration(specOf("tile"))).toBe(5);+ expect(getTumbleDuration(specOf("block"))).toBeCloseTo(7.071, 3);+ expect(getTumbleDuration(specOf("sun"))).toBe(10);+ expect(getTumbleDuration(specOf("pillar"))).toBe(10);+ });++ it("hinges every moving frame on a corner of the piece at a grid point", () => {+ for (const seed of [1, 2, 3, 4]) {+ for (let time = 0; time <= 150; time += 0.5) {+ for (const frame of getBauhausBuildState(time, { seed }).pieces) {+ const pivot = frame.pivot;+ if (pivot && frame.scale > 0.05) {+ const local = toLocal(frame, pivot);+ const hinged = localCorners(frame).some((c) => near(c, local));+ expect(hinged).toBe(true);+ expect(Number.isInteger(pivot.x)).toBe(true);+ expect(Number.isInteger(pivot.y)).toBe(true);+ }+ }+ }+ }+ });+});++describe("bauhaus build compositions", () => {+ const slots = bauhausBuildPieces.map((piece) =>+ getBauhausFootprint(piece, piece.slot),+ );+ const handoffs = bauhausBuildPieces.map((piece) =>+ getBauhausFootprint(piece, getBauhausPaths(piece).handoff),+ );++ it("keeps both compositions inside the poster without overlaps", () => {+ for (const boxes of [slots, handoffs]) {+ for (const [index, box] of boxes.entries()) {+ expect(box.x0).toBeGreaterThanOrEqual(0);+ expect(box.y0).toBeGreaterThanOrEqual(0);+ expect(box.x1).toBeLessThanOrEqual(bauhausBuildGrid);+ expect(box.y1).toBeLessThanOrEqual(bauhausBuildGrid);+ for (const other of boxes.slice(index + 1)) {+ expect(overlaps(box, other)).toBe(false);+ }+ }+ }+ });++ it("builds a frieze across the band, then opens the band for the handoff", () => {+ const { top, bottom } = bauhausBuildBand;+ const inBand = (box: Box) => box.y0 < bottom && box.y1 > top;+ expect(slots.filter(inBand).length).toBeGreaterThanOrEqual(5);+ expect(handoffs.filter(inBand)).toEqual([]);+ });++ it("matches the designed handoff layout", () => {+ const handoff = (id: string) => getBauhausPaths(specOf(id)).handoff;+ expect(handoff("hill")).toEqual({ turn: 2, x: 0, y: 8 });+ expect(handoff("tile")).toEqual({ turn: 1, x: 4, y: 8 });+ expect(handoff("pillar")).toEqual({ turn: 2, x: 2, y: 3 });+ expect(handoff("sun")).toEqual({ turn: 3, x: 6, y: 0 });+ expect(handoff("dome")).toEqual({ turn: 0, x: 3, y: 1 });+ expect(handoff("post")).toEqual({ turn: 0, x: 8, y: 8 });+ expect(handoff("dot")).toEqual({ turn: 3, x: 10, y: 3 });+ expect(handoff("block")).toEqual({ turn: 1, x: 4, y: 10 });+ expect(handoff("fan")).toEqual({ turn: 3, x: 10, y: 10 });+ });++ it("keeps the band clear of every shape from the clear frame onward", () => {+ const { top, bottom } = bauhausBuildBand;+ const { clear, duration } = bauhausBuildTimeline;+ const samples = new Map<string, Point[]>(+ bauhausBuildPieces.map((piece) => [piece.id, samplesOf(piece)]),+ );+ const intruders: string[] = [];+ for (const seed of [1, 2]) {+ for (let time = clear; time <= duration; time += 0.5) {+ for (const frame of getBauhausBuildState(time, { seed }).pieces) {+ const inside = (samples.get(frame.id) ?? []).some((sample) => {+ const { y } = toWorld(frame, sample);+ return y > top + 0.02 && y < bottom - 0.02;+ });+ if (inside) intruders.push(`${frame.id} at ${time}`);+ }+ }+ }+ expect(intruders).toEqual([]);+ });++ it("opens the frieze on a three-frame cascade of paired hinges", () => {+ const cues = bauhausBuildPieces.map((piece) => piece.cue);+ expect(cues).toEqual(cues.map((_, index) => index * 3));+ for (const [a, b] of [+ ["hill", "tile"],+ ["pillar", "sun"],+ ]) {+ const first = getBauhausPaths(specOf(a)).rebuild[0];+ const second = getBauhausPaths(specOf(b)).rebuild[0];+ expect(first.pivot).toEqual(second.pivot);+ expect(first.spin).toBe(-second.spin);+ }+ });+});++describe("bauhaus build seed and determinism", () => {+ it("returns identical output for the same frame and seed in any order", () => {+ const options = { seed: 3, loop: true };+ for (const time of [0, 12, 40, 76, 101, 118, 400]) {+ const first = getBauhausBuildState(time, options);+ getBauhausBuildState(1000, { seed: 7 });+ getBauhausBuildState(time + 50, { seed: 3 });+ expect(getBauhausBuildState(time, options)).toEqual(first);+ }+ });++ it("reshuffles the arrival order without breaking a hinge prerequisite", () => {+ const orders = new Set<string>();+ for (let seed = 1; seed <= 40; seed++) {+ const order = getBauhausBuildOrder(seed).map((piece) => piece.id);+ expect(new Set(order).size).toBe(bauhausBuildPieces.length);+ for (const piece of bauhausBuildPieces) {+ for (const before of piece.after) {+ expect(order.indexOf(before)).toBeLessThan(order.indexOf(piece.id));+ }+ }+ const rendered = getBauhausBuildState(60, { seed }).pieces;+ expect(rendered.map((frame) => frame.id)).toEqual(order);+ orders.add(order.join(" "));+ }+ expect(orders.size).toBeGreaterThan(10);+ });++ it("cycles through four mirror variants", () => {+ const variants = [1, 2, 3, 4, 5].map(getBauhausBuildVariant);+ expect(variants).toEqual([+ { flipX: false, flipY: false },+ { flipX: true, flipY: false },+ { flipX: false, flipY: true },+ { flipX: true, flipY: true },+ { flipX: false, flipY: false },+ ]);+ });+});++describe("bauhaus build framing and loop", () => {+ it("fits the poster to the shorter side on wide, square and tall frames", () => {+ for (const [width, height] of [+ [1280, 720],+ [1080, 1080],+ [720, 1280],+ ]) {+ const state = getBauhausBuildState(0, { width, height });+ const short = Math.min(width, height);+ expect(state.size).toBeCloseTo(short * 0.8, 9);+ expect(state.unit * bauhausBuildGrid).toBeCloseTo(state.size, 9);+ expect(state.originX * 2 + state.size).toBeCloseTo(width, 9);+ expect(state.originY * 2 + state.size).toBeCloseTo(height, 9);+ const large = getBauhausBuildState(0, { width, height, scale: 9 });+ expect(large.size).toBeCloseTo(short, 9);+ const small = getBauhausBuildState(0, { width, height, scale: 0 });+ expect(small.size).toBeCloseTo(short * 0.4, 9);+ }+ });++ it("reports the open band as a centered, full-width title field", () => {+ for (const [width, height] of [+ [1280, 720],+ [1080, 1080],+ [720, 1280],+ ]) {+ for (const scale of [0.5, 1, 1.25]) {+ const field = getBauhausBuildField({ width, height, scale });+ const state = getBauhausBuildState(0, { width, height, scale });+ expect(field.x).toBe(0);+ expect(field.width).toBe(width);+ expect(field.y + field.height / 2).toBeCloseTo(height / 2, 9);+ expect(field.height).toBeCloseTo(state.size / 3, 9);+ expect(field.unit).toBeCloseTo(state.unit, 9);+ }+ }+ const field = getBauhausBuildField();+ expect(field.y).toBeCloseTo(264, 9);+ expect(field.height).toBeCloseTo(192, 9);+ });++ it("plays forward and back so the loop repeats seamlessly", () => {+ const cycle = bauhausBuildTimeline.duration * 2;+ for (const time of [0, 13, 45, 90, 118, 150]) {+ const forward = getBauhausBuildState(time, { loop: true }).pieces;+ const back = getBauhausBuildState(cycle - time, { loop: true }).pieces;+ const next = getBauhausBuildState(time + cycle, { loop: true }).pieces;+ expect(back).toEqual(forward);+ expect(next).toEqual(forward);+ }+ const empty = getBauhausBuildState(cycle, { loop: true }).pieces;+ expect(empty.some((frame) => frame.visible)).toBe(false);+ });++ it("draws closed, finite shapes", () => {+ for (const piece of bauhausBuildPieces) {+ const path = getBauhausShapePath(piece.shape, piece.width, piece.height);+ expect(path.startsWith("M ")).toBe(true);+ expect(path.endsWith(" Z")).toBe(true);+ expect(path).not.toMatch(/NaN|Infinity|undefined/);+ }+ });+});++describe("bauhausBuildConfig", () => {+ const defaultOf = (name: string) => {+ const control = bauhausBuildConfig.controls[name];+ return "default" in control ? control.default : null;+ };++ it("matches the component defaults", () => {+ const expected = Object.entries(bauhausBuildDefaults).filter(+ ([name]) => name !== "speed",+ );+ for (const [name, value] of expected) {+ expect(defaultOf(name)).toBe(value);+ }+ expect(Object.keys(bauhausBuildConfig.controls).sort()).toEqual(+ expected.map(([name]) => name).sort(),+ );+ expect(bauhausBuildDefaults.speed).toBe(1);+ });++ it("exposes number controls in the customizer list", () => {+ for (const control of Object.values(bauhausBuildConfig.controls)) {+ if (control.type === "number") {+ expect(control.hiddenFromList).toBe(false);+ }+ }+ expect(bauhausBuildConfig.previewBackdrop).toEqual({+ type: "color",+ value: "#f1eee7",+ });+ });+});diff --git a/registry/remocn/bauhaus-build/config.ts b/registry/remocn/bauhaus-build/config.tsnew file mode 100644index 00000000..b88880dc--- /dev/null+++ b/registry/remocn/bauhaus-build/config.ts@@ -0,0 +1,50 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";+import { getBauhausBuildDuration } from ".";++export const bauhausBuildConfig: ComponentConfig = {+ componentName: "BauhausBuild",+ importPath: "@/components/remocn/bauhaus-build",+ controls: {+ scale: {+ type: "number",+ default: 1,+ min: 0.5,+ max: 1.25,+ step: 0.05,+ description: "Scale",+ hiddenFromList: false,+ },+ seed: {+ type: "number",+ default: 1,+ min: 1,+ max: 24,+ step: 1,+ description: "Seed",+ hiddenFromList: false,+ },+ inkColor: { type: "color", default: "#1c1a17", description: "Ink" },+ accentColor: {+ type: "color",+ default: "#e4572e",+ description: "Accent",+ },+ secondaryColor: {+ type: "color",+ default: "#cbbc9f",+ description: "Secondary",+ },+ tertiaryColor: {+ type: "color",+ default: "#7e776b",+ description: "Tertiary",+ },+ loop: { type: "boolean", default: false, description: "Loop animation" },+ },+ durationInFrames: 150,+ getDurationInFrames: (values) => getBauhausBuildDuration(values),+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#f1eee7" },+};diff --git a/registry/remocn/bauhaus-build/index.tsx b/registry/remocn/bauhaus-build/index.tsxnew file mode 100644index 00000000..3e8ebf64--- /dev/null+++ b/registry/remocn/bauhaus-build/index.tsx@@ -0,0 +1,630 @@+"use client";++import { Easing, random, useCurrentFrame, useVideoConfig } from "remotion";++export type BauhausShape =+ | "circle"+ | "square"+ | "semicircle"+ | "quarter"+ | "bar";++export type BauhausRole = "ink" | "accent" | "secondary" | "tertiary";++export type TumbleDirection = "U" | "D" | "L" | "R";++export type TumbleMove = `${TumbleDirection}${"+" | "-"}`;++export interface BauhausPose {+ turn: number;+ x: number;+ y: number;+}++export interface BauhausPoint {+ x: number;+ y: number;+}++export interface BauhausFootprint {+ x0: number;+ y0: number;+ x1: number;+ y1: number;+}++export interface BauhausPiece {+ id: string;+ shape: BauhausShape;+ width: number;+ height: number;+ role: BauhausRole;+ slot: BauhausPose;+ enter: readonly TumbleMove[];+ rebuild: readonly TumbleMove[];+ cue: number;+ after: readonly string[];+}++export interface BauhausStep {+ move: TumbleMove;+ from: BauhausPose;+ to: BauhausPose;+ pivot: BauhausPoint;+ spin: 1 | -1;+}++export interface BauhausFrame {+ x: number;+ y: number;+ rotation: number;+ scale: number;+ pivot: BauhausPoint | null;+}++export interface BauhausPieceFrame extends BauhausFrame {+ id: string;+ shape: BauhausShape;+ role: BauhausRole;+ width: number;+ height: number;+ visible: boolean;+}++export interface BauhausBuildProps {+ scale?: number;+ seed?: number;+ inkColor?: string;+ accentColor?: string;+ secondaryColor?: string;+ tertiaryColor?: string;+ speed?: number;+ loop?: boolean;+ className?: string;+}++interface TumbleRule {+ direction: TumbleDirection;+ spin: 1 | -1;+ reverse: TumbleMove;+}++export const bauhausBuildDefaults = {+ scale: 1,+ seed: 1,+ inkColor: "#1c1a17",+ accentColor: "#e4572e",+ secondaryColor: "#cbbc9f",+ tertiaryColor: "#7e776b",+ speed: 1,+ loop: false,+};++export const bauhausBuildGrid = 12;+export const bauhausBuildBand = { top: 4, bottom: 8 };+export const bauhausBuildLength = 125;+export const bauhausBuildTimeline = {+ lead: 22,+ beat: 6,+ rebuild: 90,+ clear: 116,+ duration: 150,+};++export const bauhausBuildPieces: readonly BauhausPiece[] = [+ {+ id: "hill",+ shape: "quarter",+ width: 4,+ height: 4,+ role: "ink",+ slot: { turn: 3, x: 0, y: 4 },+ enter: ["D-", "R+"],+ rebuild: ["D-"],+ cue: 0,+ after: ["tile"],+ },+ {+ id: "tile",+ shape: "square",+ width: 1,+ height: 1,+ role: "accent",+ slot: { turn: 0, x: 4, y: 7 },+ enter: ["U+", "U+", "U+", "U+"],+ rebuild: ["D+"],+ cue: 3,+ after: ["pillar"],+ },+ {+ id: "pillar",+ shape: "bar",+ width: 4,+ height: 1,+ role: "ink",+ slot: { turn: 1, x: 5, y: 4 },+ enter: ["R+", "R+"],+ rebuild: ["U+"],+ cue: 6,+ after: ["sun"],+ },+ {+ id: "sun",+ shape: "circle",+ width: 4,+ height: 4,+ role: "accent",+ slot: { turn: 0, x: 6, y: 4 },+ enter: ["U+", "U+"],+ rebuild: ["U-"],+ cue: 9,+ after: [],+ },+ {+ id: "dome",+ shape: "semicircle",+ width: 2,+ height: 2,+ role: "secondary",+ slot: { turn: 3, x: 1, y: 1 },+ enter: ["R+", "D-"],+ rebuild: ["R+"],+ cue: 12,+ after: ["pillar"],+ },+ {+ id: "post",+ shape: "bar",+ width: 4,+ height: 1,+ role: "tertiary",+ slot: { turn: 1, x: 11, y: 4 },+ enter: ["D+", "D+"],+ rebuild: ["D-"],+ cue: 15,+ after: [],+ },+ {+ id: "dot",+ shape: "circle",+ width: 1,+ height: 1,+ role: "ink",+ slot: { turn: 0, x: 11, y: 3 },+ enter: ["D-", "D-", "D-", "D-"],+ rebuild: ["L-"],+ cue: 18,+ after: ["post"],+ },+ {+ id: "block",+ shape: "square",+ width: 2,+ height: 2,+ role: "tertiary",+ slot: { turn: 0, x: 6, y: 10 },+ enter: ["U+", "U+", "U+"],+ rebuild: ["L+"],+ cue: 21,+ after: ["sun"],+ },+ {+ id: "fan",+ shape: "quarter",+ width: 2,+ height: 2,+ role: "secondary",+ slot: { turn: 2, x: 8, y: 10 },+ enter: ["L-", "L+", "L+"],+ rebuild: ["R+"],+ cue: 24,+ after: ["block"],+ },+];++const TURN = 5;+const FILL = 0.8;+const OVERSHOOT = 0.05;+const SETTLE = 0.5;++const MOVES: Record<TumbleMove, TumbleRule> = {+ "U+": { direction: "U", spin: 1, reverse: "D-" },+ "U-": { direction: "U", spin: -1, reverse: "D+" },+ "D+": { direction: "D", spin: 1, reverse: "U-" },+ "D-": { direction: "D", spin: -1, reverse: "U+" },+ "L+": { direction: "L", spin: 1, reverse: "R-" },+ "L-": { direction: "L", spin: -1, reverse: "R+" },+ "R+": { direction: "R", spin: 1, reverse: "L-" },+ "R-": { direction: "R", spin: -1, reverse: "L+" },+};++const finite = (value: number, fallback: number) =>+ Number.isFinite(value) ? value : fallback;+const clamp = (value: number, min = 0, max = 1) =>+ Math.min(max, Math.max(min, value));+const swing = Easing.bezier(0.62, 0, 0.3, 1);+const settle = Easing.bezier(0.45, 0, 0.55, 1);++function seedKey(seed: number) {+ return Number.isFinite(seed) ? Math.round(seed) : 1;+}++export function getBauhausFootprint(+ piece: Pick<BauhausPiece, "width" | "height">,+ pose: BauhausPose,+): BauhausFootprint {+ const odd = pose.turn % 2 !== 0;+ return {+ x0: pose.x,+ y0: pose.y,+ x1: pose.x + (odd ? piece.height : piece.width),+ y1: pose.y + (odd ? piece.width : piece.height),+ };+}++export function getTumblePivot(+ box: BauhausFootprint,+ move: TumbleMove,+): BauhausPoint {+ const { direction, spin } = MOVES[move];+ const clockwise = spin === 1;+ switch (direction) {+ case "R":+ return { x: box.x1, y: clockwise ? box.y1 : box.y0 };+ case "L":+ return { x: box.x0, y: clockwise ? box.y0 : box.y1 };+ case "D":+ return { x: clockwise ? box.x0 : box.x1, y: box.y1 };+ default:+ return { x: clockwise ? box.x1 : box.x0, y: box.y0 };+ }+}++const quarterTurn = (+ point: BauhausPoint,+ pivot: BauhausPoint,+ spin: 1 | -1,+): BauhausPoint => ({+ x: pivot.x - spin * (point.y - pivot.y),+ y: pivot.y + spin * (point.x - pivot.x),+});++export function tumble(+ piece: Pick<BauhausPiece, "width" | "height">,+ pose: BauhausPose,+ move: TumbleMove,+): BauhausStep {+ const { spin } = MOVES[move];+ const box = getBauhausFootprint(piece, pose);+ const pivot = getTumblePivot(box, move);+ const a = quarterTurn({ x: box.x0, y: box.y0 }, pivot, spin);+ const b = quarterTurn({ x: box.x1, y: box.y1 }, pivot, spin);+ return {+ move,+ from: pose,+ to: {+ turn: (pose.turn + spin + 4) % 4,+ x: Math.min(a.x, b.x),+ y: Math.min(a.y, b.y),+ },+ pivot,+ spin,+ };+}++export function getBauhausPaths(piece: BauhausPiece) {+ const walk = (from: BauhausPose, moves: readonly TumbleMove[]) => {+ const steps: BauhausStep[] = [];+ let pose = from;+ for (const move of moves) {+ const step = tumble(piece, pose, move);+ steps.push(step);+ pose = step.to;+ }+ return steps;+ };+ let start = piece.slot;+ for (let index = piece.enter.length - 1; index >= 0; index--) {+ start = tumble(piece, start, MOVES[piece.enter[index]].reverse).to;+ }+ const rebuild = walk(piece.slot, piece.rebuild);+ return {+ start,+ enter: walk(start, piece.enter),+ rebuild,+ handoff: rebuild.at(-1)?.to ?? piece.slot,+ };+}++function getRestOffset(+ piece: Pick<BauhausPiece, "width" | "height">,+ turn: number,+): BauhausPoint {+ switch (turn) {+ case 1:+ return { x: piece.height, y: 0 };+ case 2:+ return { x: piece.width, y: piece.height };+ case 3:+ return { x: 0, y: piece.width };+ default:+ return { x: 0, y: 0 };+ }+}++export function getBauhausPoseFrame(+ piece: Pick<BauhausPiece, "width" | "height">,+ pose: BauhausPose,+): BauhausFrame {+ const offset = getRestOffset(piece, pose.turn);+ return {+ x: pose.x + offset.x,+ y: pose.y + offset.y,+ rotation: pose.turn * 90,+ scale: 1,+ pivot: null,+ };+}++export function getBauhausStepFrame(+ piece: Pick<BauhausPiece, "width" | "height">,+ step: BauhausStep,+ progress: number,+ grow = 1,+): BauhausFrame {+ const rest = getBauhausPoseFrame(piece, step.from);+ const angle = (step.spin * progress * Math.PI) / 2;+ const cos = Math.cos(angle);+ const sin = Math.sin(angle);+ const dx = rest.x - step.pivot.x;+ const dy = rest.y - step.pivot.y;+ return {+ x: step.pivot.x + grow * (dx * cos - dy * sin),+ y: step.pivot.y + grow * (dx * sin + dy * cos),+ rotation: rest.rotation + step.spin * progress * 90,+ scale: grow,+ pivot: step.pivot,+ };+}++export function getTumbleDuration(+ piece: Pick<BauhausPiece, "width" | "height">,+) {+ return TURN * Math.sqrt(Math.max(piece.width, piece.height));+}++export function getTumbleProgress(+ elapsed: number,+ duration: number,+ landing: boolean,+) {+ const t = clamp(elapsed / duration);+ if (!landing) return swing(t);+ if (elapsed <= duration) return (1 + OVERSHOOT) * swing(t);+ const back = clamp((elapsed - duration) / (duration * SETTLE));+ return 1 + OVERSHOOT * (1 - settle(back));+}++export function getUnfoldScale(progress: number) {+ return 1 - (1 - clamp(progress)) ** 3;+}++function getPathFrame(+ piece: BauhausPiece,+ steps: readonly BauhausStep[],+ elapsed: number,+ unfold: boolean,+): BauhausFrame {+ const duration = getTumbleDuration(piece);+ const last = steps.length - 1;+ const index = Math.min(last, Math.max(0, Math.floor(elapsed / duration)));+ const local = elapsed - index * duration;+ const landing = index === last;+ const step = steps[index];+ if (landing && local >= duration * (1 + SETTLE)) {+ return getBauhausPoseFrame(piece, step.to);+ }+ const grow = unfold && index === 0 ? getUnfoldScale(local / duration) : 1;+ const progress = getTumbleProgress(local, duration, landing);+ return getBauhausStepFrame(piece, step, progress, grow);+}++function getPieceMotion(+ piece: BauhausPiece,+ arrival: number,+ time: number,+): BauhausFrame {+ const { lead, beat, rebuild } = bauhausBuildTimeline;+ const paths = getBauhausPaths(piece);+ const cue = rebuild + piece.cue;+ if (time >= cue && paths.rebuild.length > 0) {+ return getPathFrame(piece, paths.rebuild, time - cue, false);+ }+ if (paths.enter.length === 0) {+ return getBauhausPoseFrame(piece, piece.slot);+ }+ const travel = paths.enter.length * getTumbleDuration(piece);+ const start = lead + arrival * beat - travel;+ if (time < start) {+ return { ...getBauhausPoseFrame(piece, paths.start), scale: 0 };+ }+ return getPathFrame(piece, paths.enter, time - start, true);+}++export function getBauhausBuildDuration({+ speed = bauhausBuildDefaults.speed,+ loop = bauhausBuildDefaults.loop,+}: Pick<BauhausBuildProps, "speed" | "loop"> = {}) {+ const rate = finite(speed, 1);+ const frames = bauhausBuildTimeline.duration * (loop ? 2 : 1);+ return rate <= 0 ? 1 : Math.max(1, Math.ceil(frames / rate));+}++export function getBauhausBuildOrder(seed = bauhausBuildDefaults.seed) {+ const key = seedKey(seed);+ const rank = (piece: BauhausPiece) =>+ random(`bauhaus-build-${key}-order-${piece.id}`);+ const placed: BauhausPiece[] = [];+ const waiting = [...bauhausBuildPieces];+ while (waiting.length > 0) {+ const ready = waiting.filter((piece) =>+ piece.after.every((id) => placed.some((done) => done.id === id)),+ );+ const next = ready.reduce((best, piece) =>+ rank(piece) < rank(best) ? piece : best,+ );+ placed.push(next);+ waiting.splice(waiting.indexOf(next), 1);+ }+ return placed;+}++export function getBauhausBuildVariant(seed = bauhausBuildDefaults.seed) {+ const index = (((seedKey(seed) - 1) % 4) + 4) % 4;+ return { flipX: index % 2 === 1, flipY: index >= 2 };+}++function getPoster(scale: number, width: number, height: number) {+ const w = Math.max(1, finite(width, 1280));+ const h = Math.max(1, finite(height, 720));+ const size = Math.min(w, h) * FILL * clamp(finite(scale, 1), 0.5, 1.25);+ return { w, h, size, originX: (w - size) / 2, originY: (h - size) / 2 };+}++export function getBauhausBuildField({+ scale = bauhausBuildDefaults.scale,+ width = 1280,+ height = 720,+}: Pick<BauhausBuildProps, "scale"> & {+ width?: number;+ height?: number;+} = {}) {+ const poster = getPoster(scale, width, height);+ const unit = poster.size / bauhausBuildGrid;+ return {+ x: 0,+ y: poster.originY + bauhausBuildBand.top * unit,+ width: poster.w,+ height: (bauhausBuildBand.bottom - bauhausBuildBand.top) * unit,+ unit,+ };+}++export function getBauhausBuildState(+ time: number,+ {+ seed = bauhausBuildDefaults.seed,+ scale = bauhausBuildDefaults.scale,+ loop = bauhausBuildDefaults.loop,+ width = 1280,+ height = 720,+ }: Pick<BauhausBuildProps, "seed" | "scale" | "loop"> & {+ width?: number;+ height?: number;+ } = {},+) {+ const { size, originX, originY } = getPoster(scale, width, height);+ const { duration } = bauhausBuildTimeline;+ const elapsed = Math.max(0, finite(time, 0));+ const folded = elapsed % (duration * 2);+ const local = loop ? Math.min(folded, duration * 2 - folded) : elapsed;+ const pieces = getBauhausBuildOrder(seed).map((piece, arrival) => {+ const motion = getPieceMotion(piece, arrival, local);+ const frame: BauhausPieceFrame = {+ id: piece.id,+ shape: piece.shape,+ role: piece.role,+ width: piece.width,+ height: piece.height,+ ...motion,+ visible: motion.scale > 0.001,+ };+ return frame;+ });+ return {+ time: local,+ size,+ unit: size / bauhausBuildGrid,+ originX,+ originY,+ ...getBauhausBuildVariant(seed),+ pieces,+ };+}++export function getBauhausShapePath(+ shape: BauhausShape,+ width: number,+ height: number,+) {+ const r = width / 2;+ switch (shape) {+ case "circle":+ return `M 0 ${r} A ${r} ${r} 0 1 1 ${width} ${r} A ${r} ${r} 0 1 1 0 ${r} Z`;+ case "semicircle":+ return `M 0 ${height} A ${r} ${r} 0 0 1 ${width} ${height} Z`;+ case "quarter":+ return `M 0 ${height} L 0 0 A ${width} ${height} 0 0 1 ${width} ${height} Z`;+ default:+ return `M 0 0 H ${width} V ${height} H 0 Z`;+ }+}++export function BauhausBuild({+ scale = bauhausBuildDefaults.scale,+ seed = bauhausBuildDefaults.seed,+ inkColor = bauhausBuildDefaults.inkColor,+ accentColor = bauhausBuildDefaults.accentColor,+ secondaryColor = bauhausBuildDefaults.secondaryColor,+ tertiaryColor = bauhausBuildDefaults.tertiaryColor,+ speed = bauhausBuildDefaults.speed,+ loop = bauhausBuildDefaults.loop,+ className,+}: BauhausBuildProps) {+ const frame = useCurrentFrame();+ const { width, height, fps } = useVideoConfig();+ const time = frame * (30 / fps) * Math.max(0, finite(speed, 1));+ const state = getBauhausBuildState(time, {+ seed,+ scale,+ loop,+ width,+ height,+ });+ const fills: Record<BauhausRole, string> = {+ ink: inkColor,+ accent: accentColor,+ secondary: secondaryColor,+ tertiary: tertiaryColor,+ };+ const mirror = `translate(${state.flipX ? width : 0} ${state.flipY ? height : 0}) scale(${state.flipX ? -1 : 1} ${state.flipY ? -1 : 1})`;++ return (+ <div+ className={className}+ style={{ position: "absolute", inset: 0, overflow: "hidden" }}+ >+ <svg+ width="100%"+ height="100%"+ viewBox={`0 0 ${width} ${height}`}+ role="img"+ aria-label="Geometric Bauhaus composition"+ style={{ display: "block" }}+ >+ <g transform={mirror}>+ {state.pieces.map((piece) =>+ piece.visible ? (+ <path+ key={piece.id}+ d={getBauhausShapePath(piece.shape, piece.width, piece.height)}+ fill={fills[piece.role]}+ transform={`translate(${state.originX + piece.x * state.unit} ${state.originY + piece.y * state.unit}) rotate(${piece.rotation}) scale(${piece.scale * state.unit})`}+ />+ ) : null,+ )}+ </g>+ </svg>+ </div>+ );+}diff --git a/registry/remocn/code-morph/__tests__/code-morph.test.ts b/registry/remocn/code-morph/__tests__/code-morph.test.tsnew file mode 100644index 00000000..4e4e6eff--- /dev/null+++ b/registry/remocn/code-morph/__tests__/code-morph.test.ts@@ -0,0 +1,662 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ type CodeMorphRenderToken,+ type CodeMorphStep,+ type CodeMorphToken,+ codeMorphDefaults,+ codeMorphLength,+ diffCodeMorphTokens,+ getCodeMorphDuration,+ getCodeMorphLayout,+ getCodeMorphState,+ getCodeMorphTime,+ getCodeMorphTimeline,+ normalizeCodeMorphCode,+ tokenizeCodeMorph,+} from "..";+import { codeMorphConfig } from "../config";++const VITE: CodeMorphStep[] = [+ {+ at: 0,+ code: [+ "export default defineConfig({",+ " plugins: [react()],",+ "});",+ ].join("\n"),+ },+ {+ at: 45,+ code: [+ 'import tailwindcss from "@tailwindcss/vite";',+ "",+ "export default defineConfig({",+ " plugins: [react(), tailwindcss()],",+ "});",+ ].join("\n"),+ },+ {+ at: 110,+ code: [+ 'import tailwindcss from "@tailwindcss/vite";',+ "",+ "export default defineConfig({",+ " plugins: [react(), tailwindcss()],",+ " server: { port: 3000 },",+ "});",+ ].join("\n"),+ },+];++const SWAP: CodeMorphStep[] = [+ {+ at: 0,+ code: [+ 'const owner = load("owner");',+ 'const team = load("team");',+ "render(owner, team);",+ ].join("\n"),+ },+ {+ at: 30,+ code: [+ 'const team = load("team");',+ 'const owner = load("owner");',+ "render(owner, team);",+ ].join("\n"),+ },+];++const frames = (first: number, last: number, step = 1) =>+ Array.from(+ { length: Math.floor((last - first) / step) + 1 },+ (_, i) => first + i * step,+ );++const placed = (tokens: CodeMorphRenderToken[]) =>+ tokens.map((token) => `${token.text}@${token.line}:${token.col}`).sort();++const keysOf = (tokens: CodeMorphRenderToken[]) =>+ tokens.map((token) => token.key).sort();++const indexOf = (token: CodeMorphRenderToken) =>+ Number(token.key.slice(token.key.indexOf(":") + 1));++const spot = (token: CodeMorphToken) => [token.line, token.col];++describe("code morph timeline", () => {+ it("settles the default morph at the documented length", () => {+ const timeline = getCodeMorphTimeline();+ expect(codeMorphLength).toBe(114);+ expect(timeline.morph).toBe(36);+ expect(timeline.steps).toEqual([0, 48]);+ expect(timeline.morphs).toEqual([+ {+ from: 0,+ to: 1,+ start: 48,+ end: 84,+ highlightStart: 68,+ fallStart: 100,+ highlightEnd: 114,+ },+ ]);+ expect(timeline.settled).toBe(codeMorphLength);+ expect(timeline.duration).toBe(138);+ expect(getCodeMorphDuration()).toBe(codeMorphConfig.durationInFrames);+ });++ it("scales the preview duration with speed, morph and highlight", () => {+ expect(getCodeMorphDuration({ highlight: false })).toBe(108);+ expect(getCodeMorphDuration({ speed: 2 })).toBe(69);+ expect(getCodeMorphDuration({ speed: 0.5 })).toBe(276);+ expect(getCodeMorphDuration({ speed: 0 })).toBe(1);+ expect(getCodeMorphDuration({ morphDuration: 60 })).toBe(152);+ expect(getCodeMorphDuration({ morphDuration: 1 })).toBe(125);+ expect(getCodeMorphDuration({ morphDuration: 999 })).toBe(192);+ expect(getCodeMorphDuration({ morphDuration: Number.NaN })).toBe(138);+ const resolve = codeMorphConfig.getDurationInFrames;+ const values = { morphDuration: 60, highlight: false, speed: 2 };+ expect(resolve?.(values)).toBe(66);+ expect(resolve?.({ morphDuration: "slow", speed: "fast" })).toBe(138);+ });++ it("chains steps in order and never overlaps two morphs", () => {+ const overlap: CodeMorphStep[] = [+ { at: 0, code: "a" },+ { at: 48, code: "b" },+ { at: 60, code: "c" },+ ];+ const chained = getCodeMorphTimeline({ steps: overlap });+ const windows = chained.morphs.map((morph) => [morph.start, morph.end]);+ expect(windows).toEqual([+ [48, 84],+ [84, 120],+ ]);+ expect(chained.morphs[0].fallStart).toBe(84);+ expect(chained.morphs[0].highlightEnd).toBe(98);+ expect(chained.settled).toBe(150);+ const unsorted: CodeMorphStep[] = [+ { at: 90, code: "c" },+ { at: 0, code: "a" },+ { at: 30, code: "b" },+ ];+ const sorted = getCodeMorphTimeline({ steps: unsorted });+ expect(sorted.steps).toEqual([0, 30, 90]);+ expect(sorted.morphs.map((morph) => morph.start)).toEqual([30, 90]);+ const lone: CodeMorphStep[] = [{ at: 10, code: "a" }];+ const single = getCodeMorphTimeline({ steps: lone });+ expect(single.morphs).toEqual([]);+ expect(single.settled).toBe(0);+ expect(getCodeMorphDuration({ steps: lone })).toBe(24);+ });++ it("maps frames through speed and frame rate", () => {+ expect(getCodeMorphTime(10)).toBe(10);+ expect(getCodeMorphTime(10, { fps: 60 })).toBe(5);+ expect(getCodeMorphTime(10, { speed: 2 })).toBe(20);+ expect(getCodeMorphTime(10, { speed: 0 })).toBe(0);+ expect(getCodeMorphTime(-4)).toBe(0);+ expect(getCodeMorphTime(Number.NaN)).toBe(0);+ });+});++describe("code morph tokenizer", () => {+ it("splits a line into colored tokens on the column grid", () => {+ const tokens = tokenizeCodeMorph(+ ' const total = sum(items, "usd") + 42; // cents',+ );+ const summary = tokens.map((token) => [token.text, token.kind, token.col]);+ expect(summary).toEqual([+ ["const", "keyword", 0],+ ["total", "text", 6],+ ["=", "punct", 12],+ ["sum", "function", 14],+ ["(", "punct", 17],+ ["items", "text", 18],+ [",", "punct", 23],+ ['"usd"', "string", 25],+ [")", "punct", 30],+ ["+", "punct", 32],+ ["42", "number", 34],+ [";", "punct", 36],+ ["// cents", "comment", 38],+ ]);+ expect(tokens.every((token) => token.line === 0)).toBe(true);+ expect(tokens.filter((token) => token.word)).toHaveLength(7);+ });++ it("keeps JSX, members and operators apart", () => {+ const jsx = tokenizeCodeMorph("return <InvoiceTable rows={data} />;");+ expect(jsx.map((token) => token.text)).toEqual([+ "return",+ "<",+ "InvoiceTable",+ "rows",+ "=",+ "{",+ "data",+ "}",+ "/>",+ ";",+ ]);+ expect(jsx[2].kind).toBe("type");+ const chain = tokenizeCodeMorph("res?.json().finally(done) ?? 0x1f;");+ expect(chain.map((token) => token.text)).toEqual([+ "res",+ "?.",+ "json",+ "(",+ ")",+ ".",+ "finally",+ "(",+ "done",+ ")",+ "??",+ "0x1f",+ ";",+ ]);+ expect(chain[6].kind).toBe("function");+ expect(chain[11].kind).toBe("number");+ });++ it("normalizes indentation, tabs and blank edges", () => {+ const code = "\n\n const a = 1;\r\n\t return a; \n\n";+ expect(normalizeCodeMorphCode(code)).toBe("const a = 1;\nreturn a;");+ const tokens = tokenizeCodeMorph("\tif (ready) {\n\t\tstart();\n\t}");+ const grid = tokens.map((token) => [token.text, token.line, token.col]);+ expect(grid).toEqual([+ ["if", 0, 0],+ ["(", 0, 3],+ ["ready", 0, 4],+ [")", 0, 9],+ ["{", 0, 11],+ ["start", 1, 2],+ ["(", 1, 7],+ [")", 1, 8],+ [";", 1, 9],+ ["}", 2, 0],+ ]);+ });++ it("carries comments and template strings across lines", () => {+ const tokens = tokenizeCodeMorph(+ "const note = `line one\nline two`; /* keep\nthis */ done();",+ );+ const kinds = tokens.map((token) => [token.text, token.kind, token.line]);+ expect(kinds).toEqual([+ ["const", "keyword", 0],+ ["note", "text", 0],+ ["=", "punct", 0],+ ["`line one", "string", 0],+ ["line two`", "string", 1],+ [";", "punct", 1],+ ["/* keep", "comment", 1],+ ["this */", "comment", 2],+ ["done", "function", 2],+ ["(", "punct", 2],+ [")", "punct", 2],+ [";", "punct", 2],+ ]);+ });++ it("counts columns in code points", () => {+ const tokens = tokenizeCodeMorph('const label = "\u{1f680} ship"; go();');+ const columns = tokens.map((token) => token.col);+ expect(columns).toEqual([0, 6, 12, 14, 22, 24, 26, 27, 28]);+ });+});++describe("code morph diff", () => {+ const layout = getCodeMorphLayout();+ const [from, to] = layout.versions;+ const { diff, changed } = layout.morphs[0];++ it("pairs identical code one to one in place", () => {+ const tokens = tokenizeCodeMorph(codeMorphDefaults.steps[0].code);+ const same = diffCodeMorphTokens(tokens, tokens);+ expect(same.fromTo).toEqual(tokens.map((_, index) => index));+ expect(same.toFrom).toEqual(tokens.map((_, index) => index));+ const empty = diffCodeMorphTokens([], tokens);+ expect(empty.toFrom.every((index) => index === -1)).toBe(true);+ });++ it("returns inverse maps between identical tokens", () => {+ let pairs = 0;+ for (const [i, j] of diff.fromTo.entries()) {+ if (j < 0) continue;+ pairs += 1;+ expect(diff.toFrom[j]).toBe(i);+ expect(to.tokens[j].text).toBe(from.tokens[i].text);+ }+ for (const [j, i] of diff.toFrom.entries()) {+ if (i >= 0) expect(diff.fromTo[i]).toBe(j);+ }+ expect(from.tokens).toHaveLength(106);+ expect(to.tokens).toHaveLength(45);+ expect(pairs).toBe(33);+ const paired = diff.toFrom.filter((i) => i >= 0);+ expect(paired).toEqual([...paired].sort((a, b) => a - b));+ });++ it("lifts the endpoint out of fetch and into the hook", () => {+ const j = to.tokens.findIndex((token) => token.text === '"/api/invoices"');+ expect(spot(from.tokens[diff.toFrom[j]])).toEqual([7, 10]);+ expect(spot(to.tokens[j])).toEqual([3, 37]);+ const brace = from.tokens[diff.toFrom[to.tokens.length - 1]];+ expect(brace.text).toBe("}");+ expect(spot(brace)).toEqual([15, 0]);+ const signature = to.tokens.filter((token) => token.line === 2);+ expect(signature).toHaveLength(6);+ for (const token of signature) {+ const i = diff.toFrom[to.tokens.indexOf(token)];+ expect(i).toBeGreaterThanOrEqual(0);+ expect(spot(from.tokens[i])).toEqual([2, token.col]);+ }+ });++ it("adds and removes only what the refactor changed", () => {+ const added = to.tokens+ .filter((_, j) => diff.toFrom[j] < 0)+ .map((token) => token.text);+ expect(added).toEqual([+ "useSWR",+ '"swr"',+ "{",+ "data",+ "isLoading",+ "}",+ "useSWR",+ ",",+ "fetcher",+ ";",+ "isLoading",+ "data",+ ]);+ expect(changed).toEqual([0, 3, 5, 6]);+ });++ it("never lets punctuation fly away from its line's words", () => {+ const shifts = (word: boolean) => {+ const out = new Set<number>();+ for (const [j, i] of diff.toFrom.entries()) {+ if (i >= 0 && to.tokens[j].word === word) {+ out.add(to.tokens[j].line - from.tokens[i].line);+ }+ }+ return out;+ };+ const words = shifts(true);+ for (const shift of shifts(false)) expect(words.has(shift)).toBe(true);+ });++ it("keeps trailing brackets on the line end and closers with openers", () => {+ const grown = getCodeMorphLayout({ steps: VITE });+ const [first, second, third] = grown.versions;+ const [growth, server] = grown.morphs;+ const bracket = second.tokens.findIndex((token) => token.text === "]");+ expect(spot(first.tokens[growth.diff.toFrom[bracket]])).toEqual([1, 19]);+ expect(spot(second.tokens[bracket])).toEqual([3, 34]);+ const brace = third.tokens.length - 3;+ expect(third.tokens[brace].text).toBe("}");+ expect(spot(second.tokens[server.diff.toFrom[brace]])).toEqual([4, 0]);+ expect(spot(third.tokens[brace])).toEqual([5, 0]);+ expect(growth.changed).toEqual([0, 3]);+ expect(server.changed).toEqual([4]);+ });++ it("lets swapped lines travel past each other", () => {+ const swap = getCodeMorphLayout({ steps: SWAP });+ const [a, b] = swap.versions;+ const { toFrom } = swap.morphs[0].diff;+ expect(toFrom.every((i) => i >= 0)).toBe(true);+ const moves = b.tokens.map((token, j) => {+ const source = a.tokens[toFrom[j]];+ return `${source.line}>${token.line}`;+ });+ expect(moves.filter((move) => move === "1>0")).toHaveLength(8);+ expect(moves.filter((move) => move === "0>1")).toHaveLength(8);+ expect(swap.morphs[0].changed).toEqual([]);+ });+});++describe("code morph signature motion", () => {+ const layout = getCodeMorphLayout();+ const [from, to] = layout.versions;+ const { diff } = layout.morphs[0];+ const morphFrames = frames(48, 83.75, 0.25);++ it("starts from the old version at rest", () => {+ const rest = getCodeMorphState(47);+ const start = getCodeMorphState(48);+ expect(rest.morphing).toBe(false);+ expect(start.morphing).toBe(true);+ expect(placed(start.tokens)).toEqual(placed(rest.tokens));+ for (const token of start.tokens) {+ expect([token.opacity, token.scale, token.blur]).toEqual([1, 1, 0]);+ }+ });++ it("lands exactly on the new version at rest", () => {+ const end = getCodeMorphState(83.9);+ const rest = getCodeMorphState(84);+ expect(end.morphing).toBe(true);+ expect(rest.morphing).toBe(false);+ expect(rest.version).toBe(1);+ expect(placed(end.tokens)).toEqual(placed(rest.tokens));+ expect(keysOf(end.tokens)).toEqual(keysOf(rest.tokens));+ for (const token of end.tokens) {+ expect(token.opacity).toBeGreaterThan(0.9999);+ }+ });++ it("renders every surviving token as exactly one element", () => {+ for (const frame of morphFrames) {+ const { tokens } = getCodeMorphState(frame);+ const keys = tokens.map((token) => token.key);+ expect(new Set(keys).size).toBe(keys.length);+ const moving = tokens.filter((token) => token.role === "move");+ const staying = tokens.filter((token) => token.role === "stay");+ expect(moving).toHaveLength(25);+ expect(staying).toHaveLength(8);+ }+ });++ it("holds unchanged code perfectly still", () => {+ for (const frame of morphFrames) {+ for (const token of getCodeMorphState(frame, {}, layout).tokens) {+ if (token.role !== "stay") continue;+ const target = to.tokens[indexOf(token)];+ expect([token.line, token.col]).toEqual(spot(target));+ }+ }+ });++ it("carries the endpoint on an arc that rises before it slides", () => {+ const path = frames(48, 84).map((frame) => {+ const { tokens } = getCodeMorphState(frame);+ const token = tokens.find((item) => item.text === '"/api/invoices"');+ return token ? [token.line, token.col] : [Number.NaN, Number.NaN];+ });+ expect(path[0]).toEqual([7, 10]);+ expect(path[path.length - 1]).toEqual([3, 37]);+ for (let i = 1; i < path.length; i++) {+ expect(path[i][0]).toBeLessThanOrEqual(path[i - 1][0]);+ expect(path[i][1]).toBeGreaterThanOrEqual(path[i - 1][1]);+ expect(path[i][0]).toBeGreaterThanOrEqual(3);+ expect(path[i][1]).toBeLessThanOrEqual(37);+ }+ const [line, col] = path[16];+ expect((7 - line) / 4).toBeGreaterThan((col - 10) / 27 + 0.2);+ });++ it("moves tokens that share a line and an offset as one block", () => {+ let blocks = 0;+ for (const frame of morphFrames) {+ const offsets = new Map<string, string>();+ for (const token of getCodeMorphState(frame, {}, layout).tokens) {+ if (token.role !== "move") continue;+ const j = indexOf(token);+ const source = from.tokens[diff.toFrom[j]];+ const target = to.tokens[j];+ const dLine = target.line - source.line;+ const dCol = target.col - source.col;+ const block = `${source.line}|${dLine}|${dCol}`;+ const line = (token.line - source.line).toFixed(9);+ const col = (token.col - source.col).toFixed(9);+ const seen = offsets.get(block);+ if (seen === undefined) offsets.set(block, `${line}|${col}`);+ else expect(`${line}|${col}`).toBe(seen);+ }+ blocks = Math.max(blocks, offsets.size);+ }+ expect(blocks).toBe(11);+ });++ it("clears removed code first and fades new code in last", () => {+ const at = (frame: number) => getCodeMorphState(frame).tokens;+ const has = (frame: number, role: string) =>+ at(frame).some((token) => token.role === role);+ for (const token of at(54)) {+ expect(Number.isInteger(token.line)).toBe(true);+ expect(Number.isInteger(token.col)).toBe(true);+ }+ expect(has(63.75, "exit")).toBe(true);+ expect(has(64, "exit")).toBe(false);+ expect(has(68, "enter")).toBe(false);+ expect(has(68.25, "enter")).toBe(true);+ const exits = new Map<string, CodeMorphRenderToken>();+ const enters = new Map<string, CodeMorphRenderToken>();+ for (const frame of morphFrames) {+ for (const token of at(frame)) {+ if (token.role === "exit") {+ const last = exits.get(token.key);+ expect(token.scale).toBeGreaterThanOrEqual(0.92);+ expect(token.scale).toBeLessThanOrEqual(1);+ expect(token.blur).toBeLessThanOrEqual(3.5);+ if (last) {+ expect(token.opacity).toBeLessThanOrEqual(last.opacity);+ expect(token.blur).toBeGreaterThanOrEqual(last.blur);+ }+ exits.set(token.key, token);+ }+ if (token.role === "enter") {+ const last = enters.get(token.key);+ expect(token.scale).toBeGreaterThanOrEqual(0.96);+ expect(token.scale).toBeLessThanOrEqual(1);+ if (last) {+ expect(token.opacity).toBeGreaterThanOrEqual(last.opacity);+ expect(token.blur).toBeLessThanOrEqual(last.blur);+ }+ enters.set(token.key, token);+ }+ }+ }+ expect(exits.size).toBe(73);+ expect(enters.size).toBe(12);+ });++ it("fades surplus line numbers behind the slowest line", () => {+ expect(getCodeMorphState(58).lines).toBe(16);+ expect(getCodeMorphState(84).lines).toBe(8);+ let previous = 16;+ for (const frame of morphFrames) {+ const state = getCodeMorphState(frame);+ expect(state.lines).toBeLessThanOrEqual(previous);+ previous = state.lines;+ for (const token of state.tokens) {+ if (token.role === "exit") continue;+ expect(token.line + 1).toBeLessThanOrEqual(state.lines + 1e-9);+ }+ }+ const middle = getCodeMorphState(70);+ const rows = middle.lineNumbers.map((row) => row.opacity);+ expect(rows).toHaveLength(16);+ expect(rows.slice(0, 8).every((opacity) => opacity === 1)).toBe(true);+ const faded = 1 - (16 - middle.lines) / 8;+ for (const opacity of rows.slice(8)) expect(opacity).toBeCloseTo(faded, 9);+ });++ it("numbers new lines ahead of code that moves down", () => {+ const grown = getCodeMorphLayout({ steps: VITE });+ expect(grown.versions.map((version) => version.lines)).toEqual([3, 5, 6]);+ expect(grown.rows).toBe(6);+ for (const frame of frames(0, 200, 0.5)) {+ const state = getCodeMorphState(frame, { steps: VITE }, grown);+ for (const token of state.tokens) {+ if (token.role === "exit") continue;+ expect(token.line + 1).toBeLessThanOrEqual(state.lines + 1e-9);+ }+ }+ expect(getCodeMorphState(200, { steps: VITE }, grown).version).toBe(2);+ });++ it("holds a brief accent band on the changed lines", () => {+ const rows = (frame: number, highlight = true) =>+ getCodeMorphState(frame, { highlight }).highlights;+ expect(rows(68)).toEqual([]);+ expect(rows(80).map((band) => band.row)).toEqual([0, 3, 5, 6]);+ for (const frame of [76, 84, 100]) {+ expect(rows(frame).every((band) => band.opacity === 1)).toBe(true);+ }+ expect(rows(72)[0].opacity).toBeGreaterThan(rows(70)[0].opacity);+ expect(rows(108)[0].opacity).toBeLessThan(rows(104)[0].opacity);+ expect(rows(114)).toEqual([]);+ expect(rows(80, false)).toEqual([]);+ });+});++describe("code morph determinism", () => {+ it("renders any frame identically in any sampling order", () => {+ const sample = (frame: number) => getCodeMorphState(frame, { steps: VITE });+ const list = [0, 47, 52.5, 66, 81, 118, 150, 199];+ const forward = list.map(sample);+ const backward = [...list].reverse().map(sample).reverse();+ expect(backward).toEqual(forward);+ expect(sample(66)).toEqual(forward[3]);+ const again = getCodeMorphLayout({ steps: VITE });+ expect(again).toEqual(getCodeMorphLayout({ steps: VITE }));+ });++ it("maps other frame rates and speeds onto the 30 fps timeline", () => {+ const base = getCodeMorphState(60).tokens;+ expect(getCodeMorphState(120, { fps: 60 }).tokens).toEqual(base);+ expect(getCodeMorphState(120, { speed: 0.5 }).tokens).toEqual(base);+ const frozen = getCodeMorphState(500, { speed: 0 });+ expect(frozen.version).toBe(0);+ expect(frozen.tokens).toEqual(getCodeMorphState(0).tokens);+ });+});++describe("code morph layout", () => {+ it("sizes the default panel in reference pixels at 720p", () => {+ const layout = getCodeMorphLayout();+ expect(layout.unit).toBe(1);+ expect(layout.fit).toBe(1);+ expect(layout.fontSize).toBe(20);+ expect(layout.lineHeight).toBe(31);+ expect(layout.header).toBe(42);+ expect([layout.rows, layout.columns]).toEqual([16, 63]);+ expect([layout.digits, layout.gutter]).toEqual([2, 4]);+ expect(layout.versions.map((version) => version.lines)).toEqual([16, 8]);+ expect(layout.filename).toBe("invoices.tsx");+ });++ it("scales with the composition and fits narrow frames", () => {+ const full = getCodeMorphLayout({ width: 1920, height: 1080 });+ const tall = getCodeMorphLayout({ width: 1080, height: 1920 });+ const square = getCodeMorphLayout({ width: 1080, height: 1080 });+ expect(full.unit).toBe(1.5);+ expect(tall.unit).toBe(0.84375);+ expect(square.unit).toBe(0.84375);+ const code = `const url = "${"x".repeat(136)}";`;+ const long = getCodeMorphLayout({ steps: [{ at: 0, code }] });+ expect(long.fit).toBeLessThan(1);+ const estimate = 50 + (long.gutter + long.columns) * 0.6 * 20;+ expect(estimate * long.fit).toBeCloseTo(1152, 6);+ });++ it("drops the chrome and the gutter on request", () => {+ const bare = getCodeMorphLayout({+ lineNumbers: false,+ windowDots: false,+ filename: " ",+ });+ expect([bare.header, bare.gutter, bare.digits]).toEqual([0, 0, 0]);+ expect(bare.filename).toBe("");+ const tab = getCodeMorphLayout({ windowDots: false });+ expect(tab.header).toBe(42);+ });+});++describe("code morph config", () => {+ it("matches the component defaults", () => {+ const controls = resolveControls("code-morph", codeMorphConfig.controls);+ expect(getDefaults(controls)).toEqual({+ filename: codeMorphDefaults.filename,+ theme: codeMorphDefaults.theme,+ accentColor: codeMorphDefaults.accentColor,+ morphDuration: codeMorphDefaults.morphDuration,+ fontSize: codeMorphDefaults.fontSize,+ highlight: codeMorphDefaults.highlight,+ lineNumbers: codeMorphDefaults.lineNumbers,+ windowDots: codeMorphDefaults.windowDots,+ speed: codeMorphDefaults.speed,+ });+ const theme = controls.theme;+ const options = theme.type === "select" ? theme.options : [];+ expect(options).toEqual(["dark", "light"]);+ const range = (key: string) => {+ const control = controls[key];+ return control.type === "number" ? [control.min, control.max] : [];+ };+ expect(range("morphDuration")).toEqual([12, 90]);+ expect(range("fontSize")).toEqual([12, 32]);+ expect(codeMorphConfig.previewBackdrop).toEqual({+ type: "color",+ value: "#f1eee7",+ });+ });+});diff --git a/registry/remocn/code-morph/config.ts b/registry/remocn/code-morph/config.tsnew file mode 100644index 00000000..a7209640--- /dev/null+++ b/registry/remocn/code-morph/config.ts@@ -0,0 +1,71 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";+import { getCodeMorphDuration } from ".";++const numberOf = (value: unknown) =>+ typeof value === "number" ? value : undefined;++function durationOf(values: Record<string, unknown>) {+ return getCodeMorphDuration({+ morphDuration: numberOf(values.morphDuration),+ highlight: values.highlight !== false,+ speed: numberOf(values.speed),+ });+}++export const codeMorphConfig: ComponentConfig = {+ componentName: "CodeMorph",+ importPath: "@/components/remocn/code-morph",+ controls: {+ filename: {+ type: "text-content",+ default: "invoices.tsx",+ description: "Filename",+ },+ theme: {+ type: "enum",+ default: "dark",+ variants: { dark: {}, light: {} },+ description: "Theme",+ },+ accentColor: { type: "color", default: "#0ea5e9", description: "Accent" },+ morphDuration: {+ type: "number",+ default: 36,+ min: 12,+ max: 90,+ step: 1,+ description: "Morph frames",+ hiddenFromList: false,+ },+ fontSize: {+ type: "number",+ default: 20,+ min: 12,+ max: 32,+ step: 1,+ description: "Font size",+ hiddenFromList: false,+ },+ highlight: {+ type: "boolean",+ default: true,+ description: "Highlight changes",+ },+ lineNumbers: {+ type: "boolean",+ default: true,+ description: "Line numbers",+ },+ windowDots: {+ type: "boolean",+ default: true,+ description: "Window dots",+ },+ },+ durationInFrames: 138,+ getDurationInFrames: durationOf,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#f1eee7" },+};diff --git a/registry/remocn/code-morph/index.tsx b/registry/remocn/code-morph/index.tsxnew file mode 100644index 00000000..5e9c3bdf--- /dev/null+++ b/registry/remocn/code-morph/index.tsx@@ -0,0 +1,1406 @@+"use client";++import { useMemo } from "react";+import { Easing, useCurrentFrame, useVideoConfig } from "remotion";++export type CodeMorphTheme = "dark" | "light";++export type CodeMorphKind =+ | "keyword"+ | "string"+ | "number"+ | "comment"+ | "function"+ | "type"+ | "text"+ | "punct";++export type CodeMorphRole = "rest" | "stay" | "move" | "exit" | "enter";++export interface CodeMorphStep {+ at: number;+ code: string;+}++export interface CodeMorphProps {+ steps?: CodeMorphStep[];+ morphDuration?: number;+ highlight?: boolean;+ fontSize?: number;+ lineNumbers?: boolean;+ filename?: string;+ windowDots?: boolean;+ theme?: CodeMorphTheme;+ accentColor?: string;+ speed?: number;+ className?: string;+}++type Paint = "theme" | "accentColor" | "className";++export interface CodeMorphOptions extends Omit<CodeMorphProps, Paint> {+ width?: number;+ height?: number;+ fps?: number;+}++export interface CodeMorphToken {+ text: string;+ kind: CodeMorphKind;+ line: number;+ col: number;+ word: boolean;+}++export interface CodeMorphDiff {+ fromTo: number[];+ toFrom: number[];+}++export interface CodeMorphRenderToken {+ key: string;+ text: string;+ kind: CodeMorphKind;+ role: CodeMorphRole;+ line: number;+ col: number;+ opacity: number;+ scale: number;+ blur: number;+}++export interface CodeMorphRow {+ key: string;+ row: number;+ opacity: number;+}++export interface CodeMorphState {+ time: number;+ version: number;+ morphing: boolean;+ progress: number;+ lines: number;+ tokens: CodeMorphRenderToken[];+ lineNumbers: CodeMorphRow[];+ highlights: CodeMorphRow[];+}++const BEFORE = `import { useEffect, useState } from "react";++export function Invoices() {+ const [invoices, setInvoices] = useState([]);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ fetch("/api/invoices")+ .then((res) => res.json())+ .then(setInvoices)+ .finally(() => setLoading(false));+ }, []);++ if (loading) return <Spinner />;+ return <InvoiceTable rows={invoices} />;+}`;++const AFTER = `import useSWR from "swr";++export function Invoices() {+ const { data, isLoading } = useSWR("/api/invoices", fetcher);++ if (isLoading) return <Spinner />;+ return <InvoiceTable rows={data} />;+}`;++export const codeMorphDefaults: Required<Omit<CodeMorphProps, "className">> = {+ steps: [+ { at: 0, code: BEFORE },+ { at: 48, code: AFTER },+ ],+ morphDuration: 36,+ highlight: true,+ fontSize: 20,+ lineNumbers: true,+ filename: "invoices.tsx",+ windowDots: true,+ theme: "dark",+ accentColor: "#0ea5e9",+ speed: 1,+};++const FONT_MONO =+ "var(--font-geist-mono, ui-monospace), ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";+const REFERENCE_WIDTH = 1280;+const REFERENCE_HEIGHT = 720;+const MAX_WIDTH = 1152;+const MAX_HEIGHT = 640;+const ADVANCE = 0.6;+const LEADING = 1.55;+const HEADER = 42;+const PAD_TOP = 20;+const PAD_BOTTOM = 22;+const PAD_LEFT = 22;+const PAD_RIGHT = 28;+const GUTTER_GAP = 2;+const RADIUS = 14;+const DOT = 11;+const DOT_GAP = 7;+const DOT_LEFT = 16;+const DOTS = [0, 1, 2];+const TAB_OFFSET = 14;+const TAB_AFTER_DOTS = DOT_LEFT + 3 * DOT + 2 * DOT_GAP + TAB_OFFSET;+const TAB_LEFT = 10;+const TAB_TOP = 8;+const TAB_PAD = 14;+const TAB_RADIUS = 8;+const TAB_FONT = 13;+const BAR = 2;+const BLUR = 3.5;+const SHRINK = 0.08;+const GROW_FROM = 0.96;+const BASE = 36;+const EXIT_SPREAD = 4;+const EXIT_DURATION = 12;+const MOVE_START = 6;+const MOVE_DURATION = 22;+const CASCADE = 4;+const ENTER_START = 20;+const ENTER_SPREAD = 4;+const ENTER_DURATION = 12;+const ARC = 0.08;+const RISE = 8;+const SHOW = 24;+const FALL = 14;+const HOLD = 24;+const MIN_MORPH = 12;+const MAX_MORPH = 120;+const MIN_FONT = 10;+const MAX_FONT = 40;+const LINE_COST = 10;+const COLUMN_COST = 0.5;+const MAX_COST = 1000;+const PUNCT_VALUE = 12;+const TAB = " ";++const KEYWORDS = new Set([+ "abstract",+ "as",+ "async",+ "await",+ "break",+ "case",+ "catch",+ "class",+ "const",+ "continue",+ "debugger",+ "declare",+ "default",+ "delete",+ "do",+ "else",+ "enum",+ "export",+ "extends",+ "false",+ "finally",+ "for",+ "from",+ "function",+ "if",+ "implements",+ "import",+ "in",+ "instanceof",+ "interface",+ "keyof",+ "let",+ "namespace",+ "new",+ "null",+ "of",+ "private",+ "protected",+ "public",+ "readonly",+ "return",+ "satisfies",+ "static",+ "super",+ "switch",+ "this",+ "throw",+ "true",+ "try",+ "type",+ "typeof",+ "undefined",+ "var",+ "void",+ "while",+ "yield",+]);++const OPERATORS = [+ "===",+ "!==",+ "**=",+ "...",+ "&&=",+ "||=",+ "??=",+ "=>",+ "==",+ "!=",+ "<=",+ ">=",+ "&&",+ "||",+ "??",+ "?.",+ "++",+ "--",+ "+=",+ "-=",+ "*=",+ "/=",+ "%=",+ "**",+ "</",+ "/>",+];++const NUMBER =+ /0[xXbBoO][\dA-Fa-f_]+n?|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?n?/y;+const WORD =+ /[A-Za-z_$\u00c0-\u024f\u0370-\u03ff][\w$\u00c0-\u024f\u0370-\u03ff]*/y;+const SPACE = /\s/;+const CAPITAL = /^[A-Z]/;+const OPENERS = new Set(["(", "[", "{"]);+const CLOSERS = new Map([+ [")", "("],+ ["]", "["],+ ["}", "{"],+]);++const glide = Easing.bezier(0.6, 0, 0.2, 1);++interface CodeMorphPalette {+ panel: string;+ chrome: string;+ border: string;+ dot: string;+ label: string;+ gutter: string;+ keyword: string;+ function: string;+ type: string;+ text: string;+ punct: string;+ comment: string;+ mix: string;+ share: number;+ band: number;+}++const PALETTES: Record<CodeMorphTheme, CodeMorphPalette> = {+ dark: {+ panel: "#111113",+ chrome: "#0c0c0e",+ border: "#27272a",+ dot: "#3f3f46",+ label: "#e4e4e7",+ gutter: "#52525b",+ keyword: "#a1a1aa",+ function: "#fafafa",+ type: "#fafafa",+ text: "#d4d4d8",+ punct: "#71717a",+ comment: "#5b5b63",+ mix: "#ffffff",+ share: 80,+ band: 0.16,+ },+ light: {+ panel: "#ffffff",+ chrome: "#f7f7f8",+ border: "#e4e4e7",+ dot: "#d4d4d8",+ label: "#27272a",+ gutter: "#b4b4bb",+ keyword: "#71717a",+ function: "#09090b",+ type: "#09090b",+ text: "#3f3f46",+ punct: "#909098",+ comment: "#a1a1aa",+ mix: "#000000",+ share: 70,+ band: 0.12,+ },+};++type Open = "comment" | "string" | null;+type Lexeme = "comment" | "string" | "number" | "word" | "punct";+type Pair = [number, number];++interface Piece {+ start: number;+ end: number;+ lexeme: Lexeme;+}++interface Lexed {+ text: string;+ lexeme: Lexeme;+ line: number;+ col: number;+}++const finite = (value: number | undefined, fallback: number) =>+ typeof value === "number" && Number.isFinite(value) ? value : fallback;+const clamp = (value: number, min: number, max: number) =>+ Math.min(max, Math.max(min, value));+const unit01 = (value: number) => clamp(value, 0, 1);+const easeOut = (value: number) => 1 - (1 - unit01(value)) ** 3;+const easeOutQuad = (value: number) => 1 - (1 - unit01(value)) ** 2;+const phase = (value: number, morph: number) => (value * morph) / BASE;+const range = (start: number, end: number) =>+ Array.from({ length: Math.max(0, end - start) }, (_, k) => start + k);++function smoothstep(value: number) {+ const t = unit01(value);+ return t * t * (3 - 2 * t);+}++export function normalizeCodeMorphCode(code: string) {+ const lines = code+ .replace(/\r\n?/g, "\n")+ .replace(/\t/g, TAB)+ .split("\n")+ .map((line) => line.trimEnd());+ let start = 0;+ while (start < lines.length && lines[start] === "") start += 1;+ let end = lines.length;+ while (end > start && lines[end - 1] === "") end -= 1;+ const body = lines.slice(start, end);+ const indents = body+ .filter((line) => line !== "")+ .map((line) => line.length - line.trimStart().length);+ const cut = indents.length > 0 ? Math.min(...indents) : 0;+ return body.map((line) => line.slice(cut)).join("\n");+}++function closing(line: string, from: number, quote: string) {+ let index = from;+ while (index < line.length) {+ const char = line[index];+ if (char === quote) return index;+ index += char === "\\" ? 2 : 1;+ }+ return -1;+}++function matchAt(pattern: RegExp, line: string, index: number) {+ pattern.lastIndex = index;+ const match = pattern.exec(line);+ return match ? match[0] : "";+}++function scanLine(line: string, open: Open): { pieces: Piece[]; open: Open } {+ const pieces: Piece[] = [];+ const emit = (start: number, end: number, lexeme: Lexeme) => {+ pieces.push({ start, end, lexeme });+ return end;+ };+ let index = 0;+ if (open !== null) {+ const comment = open === "comment";+ const end = comment ? line.indexOf("*/") : closing(line, 0, "`");+ if (end === -1) {+ emit(0, line.length, open);+ return { pieces, open };+ }+ index = emit(0, end + (comment ? 2 : 1), open);+ }+ while (index < line.length) {+ const char = line[index];+ if (SPACE.test(char)) {+ index += 1;+ continue;+ }+ if (line.startsWith("//", index)) {+ emit(index, line.length, "comment");+ break;+ }+ if (line.startsWith("/*", index)) {+ const end = line.indexOf("*/", index + 2);+ if (end === -1) {+ emit(index, line.length, "comment");+ return { pieces, open: "comment" };+ }+ index = emit(index, end + 2, "comment");+ continue;+ }+ if (char === '"' || char === "'" || char === "`") {+ const end = closing(line, index + 1, char);+ if (end === -1 && char === "`") {+ emit(index, line.length, "string");+ return { pieces, open: "string" };+ }+ index = emit(index, end === -1 ? line.length : end + 1, "string");+ continue;+ }+ const number = matchAt(NUMBER, line, index);+ if (number !== "") {+ index = emit(index, index + number.length, "number");+ continue;+ }+ const word = matchAt(WORD, line, index);+ if (word !== "") {+ index = emit(index, index + word.length, "word");+ continue;+ }+ const operator = OPERATORS.find((item) => line.startsWith(item, index));+ const glyph = String.fromCodePoint(line.codePointAt(index) ?? 0);+ index = emit(index, index + (operator ?? glyph).length, "punct");+ }+ return { pieces, open: null };+}++function columnsOf(line: string) {+ const columns: number[] = [];+ let index = 0;+ let column = 0;+ for (const char of line) {+ for (let unit = 0; unit < char.length; unit += 1) {+ columns[index + unit] = column;+ }+ index += char.length;+ column += 1;+ }+ columns[index] = column;+ return columns;+}++function kindOf(lexed: Lexed[], index: number): CodeMorphKind {+ const { lexeme, text } = lexed[index];+ if (lexeme !== "word") return lexeme;+ const previous = index > 0 ? lexed[index - 1].text : "";+ const next = index + 1 < lexed.length ? lexed[index + 1].text : "";+ const member = previous === "." || previous === "?.";+ if (!member && KEYWORDS.has(text)) return "keyword";+ if (next === "(") return "function";+ if (CAPITAL.test(text)) return "type";+ return "text";+}++function versionOf(source: string) {+ const code = normalizeCodeMorphCode(source);+ const lines = code.split("\n");+ const lexed: Lexed[] = [];+ let open: Open = null;+ let columns = 0;+ for (const [line, text] of lines.entries()) {+ const map = columnsOf(text);+ columns = Math.max(columns, map[text.length]);+ const scanned = scanLine(text, open);+ open = scanned.open;+ for (const piece of scanned.pieces) {+ let start = piece.start;+ let end = piece.end;+ while (start < end && SPACE.test(text[start])) start += 1;+ while (end > start && SPACE.test(text[end - 1])) end -= 1;+ if (end === start) continue;+ const slice = text.slice(start, end);+ const col = map[start];+ lexed.push({ text: slice, lexeme: piece.lexeme, line, col });+ }+ }+ const tokens: CodeMorphToken[] = lexed.map((item, index) => {+ const kind = kindOf(lexed, index);+ const { text, line, col } = item;+ return { text, kind, line, col, word: kind !== "punct" };+ });+ return { code, tokens, lines: lines.length, columns };+}++type CodeMorphVersion = ReturnType<typeof versionOf>;++export function tokenizeCodeMorph(code: string) {+ return versionOf(code).tokens;+}++interface Sides {+ from: CodeMorphToken[];+ to: CodeMorphToken[];+ fromWidths: Map<number, number>;+ toWidths: Map<number, number>;+}++function widthsOf(tokens: CodeMorphToken[]) {+ const widths = new Map<number, number>();+ for (const token of tokens) {+ const end = token.col + Array.from(token.text).length;+ widths.set(token.line, Math.max(widths.get(token.line) ?? 0, end));+ }+ return widths;+}++interface Shift {+ line: number;+ lines: number;+ cols: number;+}++function shiftOf(sides: Sides, pair: Pair): Shift {+ const anchor = sides.from[pair[0]];+ const landed = sides.to[pair[1]];+ return {+ line: anchor.line,+ lines: landed.line - anchor.line,+ cols: landed.col - anchor.col,+ };+}++const STILL: Shift = { line: -1, lines: 0, cols: 0 };++function expectedCost(sides: Sides, i: number, j: number, shift: Shift) {+ const source = sides.from[i];+ const target = sides.to[j];+ const lineOff = Math.abs(target.line - (source.line + shift.lines));+ if (source.line !== shift.line) {+ const colOff = Math.abs(target.col - source.col);+ return lineOff * LINE_COST + colOff * COLUMN_COST;+ }+ const left = source.col + shift.cols;+ const tail = (sides.fromWidths.get(source.line) ?? 0) - source.col;+ const right = (sides.toWidths.get(target.line) ?? 0) - tail;+ const colOff = Math.min(+ Math.abs(target.col - left),+ Math.abs(target.col - right),+ );+ return lineOff * LINE_COST + colOff * COLUMN_COST;+}++function costOf(+ sides: Sides,+ i: number,+ j: number,+ before: Shift | null,+ after: Shift | null,+) {+ if (before === null && after === null) {+ return Math.min(MAX_COST, expectedCost(sides, i, j, STILL));+ }+ const via = (shift: Shift | null) =>+ shift === null ? MAX_COST : expectedCost(sides, i, j, shift);+ return Math.min(MAX_COST, via(before), via(after));+}++function align(+ sources: number[],+ targets: number[],+ value: (i: number, j: number) => number,+): Pair[] {+ const rows = sources.length;+ const cols = targets.length;+ if (rows === 0 || cols === 0) return [];+ const width = cols + 1;+ const worth = new Float64Array(rows * cols);+ for (let a = 0; a < rows; a += 1) {+ for (let b = 0; b < cols; b += 1) {+ worth[a * cols + b] = value(sources[a], targets[b]);+ }+ }+ const table = new Float64Array((rows + 1) * width);+ const at = (a: number, b: number) => table[a * width + b];+ for (let a = rows - 1; a >= 0; a -= 1) {+ for (let b = cols - 1; b >= 0; b -= 1) {+ const gain = worth[a * cols + b];+ const skip = Math.max(at(a + 1, b), at(a, b + 1));+ const take = gain > 0 ? at(a + 1, b + 1) + gain : 0;+ table[a * width + b] = Math.max(skip, take);+ }+ }+ const pairs: Pair[] = [];+ let p = 0;+ let q = 0;+ while (p < rows && q < cols) {+ const gain = worth[p * cols + q];+ if (gain > 0 && at(p, q) === at(p + 1, q + 1) + gain) {+ pairs.push([sources[p], targets[q]]);+ p += 1;+ q += 1;+ } else if (at(p, q) === at(p + 1, q)) {+ p += 1;+ } else {+ q += 1;+ }+ }+ return pairs;+}++function increasing(candidates: Pair[]): Pair[] {+ const length: number[] = [];+ const previous: number[] = [];+ let best = -1;+ for (const [k, [, j]] of candidates.entries()) {+ length[k] = 1;+ previous[k] = -1;+ for (let p = 0; p < k; p += 1) {+ if (candidates[p][1] < j && length[p] + 1 > length[k]) {+ length[k] = length[p] + 1;+ previous[k] = p;+ }+ }+ if (best === -1 || length[k] > length[best]) best = k;+ }+ const chain: Pair[] = [];+ for (let k = best; k !== -1; k = previous[k]) chain.push(candidates[k]);+ return chain.reverse();+}++function anchorsOf(from: CodeMorphToken[], to: CodeMorphToken[]) {+ const fromCount = new Map<string, number>();+ const toCount = new Map<string, number>();+ const toIndex = new Map<string, number>();+ for (const token of from) {+ if (token.word) {+ fromCount.set(token.text, (fromCount.get(token.text) ?? 0) + 1);+ }+ }+ for (const [j, token] of to.entries()) {+ if (!token.word) continue;+ toCount.set(token.text, (toCount.get(token.text) ?? 0) + 1);+ toIndex.set(token.text, j);+ }+ const candidates: Pair[] = [];+ for (const [i, token] of from.entries()) {+ const j = toIndex.get(token.text);+ const unique =+ fromCount.get(token.text) === 1 && toCount.get(token.text) === 1;+ if (token.word && unique && j !== undefined) candidates.push([i, j]);+ }+ return increasing(candidates);+}++function guidesOf(sides: Sides, pairs: Pair[]) {+ const size = sides.from.length;+ const before: (Shift | null)[] = [];+ const after: (Shift | null)[] = [];+ let last: Shift | null = null;+ let cursor = 0;+ for (let i = 0; i < size; i += 1) {+ while (cursor < pairs.length && pairs[cursor][0] <= i) {+ last = shiftOf(sides, pairs[cursor]);+ cursor += 1;+ }+ before.push(last);+ }+ let next: Shift | null = null;+ cursor = pairs.length - 1;+ for (let i = size - 1; i >= 0; i -= 1) {+ while (cursor >= 0 && pairs[cursor][0] >= i) {+ next = shiftOf(sides, pairs[cursor]);+ cursor -= 1;+ }+ after[i] = next;+ }+ return { before, after };+}++function partnersOf(tokens: CodeMorphToken[]) {+ const partner = tokens.map(() => -1);+ const stack: number[] = [];+ for (const [index, token] of tokens.entries()) {+ if (token.kind !== "punct") continue;+ if (OPENERS.has(token.text)) {+ stack.push(index);+ continue;+ }+ const opener = CLOSERS.get(token.text);+ if (opener === undefined) continue;+ let depth = stack.length - 1;+ while (depth >= 0 && tokens[stack[depth]].text !== opener) depth -= 1;+ if (depth < 0) continue;+ partner[stack[depth]] = index;+ partner[index] = stack[depth];+ stack.length = depth;+ }+ return partner;+}++function linesOf(tokens: CodeMorphToken[]) {+ const lines = new Map<number, number[]>();+ for (const [index, token] of tokens.entries()) {+ const list = lines.get(token.line);+ if (list) list.push(index);+ else lines.set(token.line, [index]);+ }+ return lines;+}++function signatureOf(tokens: CodeMorphToken[], indices: number[]) {+ const base = tokens[indices[0]].col;+ const shape = indices.map((i) => [tokens[i].col - base, tokens[i].text]);+ return JSON.stringify(shape);+}++export function diffCodeMorphTokens(+ from: CodeMorphToken[],+ to: CodeMorphToken[],+): CodeMorphDiff {+ const sides: Sides = {+ from,+ to,+ fromWidths: widthsOf(from),+ toWidths: widthsOf(to),+ };+ const guides = guidesOf(sides, anchorsOf(from, to));+ const fromWords = range(0, from.length).filter((i) => from[i].word);+ const toWords = range(0, to.length).filter((j) => to[j].word);+ const weight = (Math.min(fromWords.length, toWords.length) + 1) * MAX_COST;+ const words = align(fromWords, toWords, (i, j) => {+ if (from[i].text !== to[j].text) return 0;+ return weight - costOf(sides, i, j, guides.before[i], guides.after[i]);+ });+ const fromTo = from.map(() => -1);+ const toFrom = to.map(() => -1);+ const link = ([i, j]: Pair) => {+ fromTo[i] = j;+ toFrom[j] = i;+ };+ const bounds: Pair[] = [[-1, -1], ...words, [from.length, to.length]];+ for (let k = 0; k + 1 < bounds.length; k += 1) {+ const [a0, b0] = bounds[k];+ const [a1, b1] = bounds[k + 1];+ const inner = k + 2 < bounds.length;+ const before = k > 0 ? shiftOf(sides, bounds[k]) : null;+ const after = inner ? shiftOf(sides, bounds[k + 1]) : null;+ const sources = range(a0 + 1, a1).filter((i) => !from[i].word);+ const targets = range(b0 + 1, b1).filter((j) => !to[j].word);+ const found = align(sources, targets, (i, j) => {+ if (from[i].text !== to[j].text) return 0;+ return PUNCT_VALUE - costOf(sides, i, j, before, after);+ });+ for (const pair of found) link(pair);+ if (inner) link(bounds[k + 1]);+ }+ const fromPartner = partnersOf(from);+ const toPartner = partnersOf(to);+ for (const [i, token] of from.entries()) {+ const j = fromTo[i];+ if (j < 0 || !OPENERS.has(token.text)) continue;+ const close = fromPartner[i];+ const target = toPartner[j];+ if (close < 0 || target < 0 || fromTo[close] === target) continue;+ if (fromTo[close] >= 0) toFrom[fromTo[close]] = -1;+ if (toFrom[target] >= 0) fromTo[toFrom[target]] = -1;+ link([close, target]);+ }+ const fromLines = linesOf(from);+ const pool = new Map<string, number[]>();+ for (const [line, indices] of fromLines) {+ const removed = indices.every((i) => fromTo[i] < 0);+ if (!removed || !indices.some((i) => from[i].word)) continue;+ const key = signatureOf(from, indices);+ const list = pool.get(key);+ if (list) list.push(line);+ else pool.set(key, [line]);+ }+ for (const [line, indices] of linesOf(to)) {+ if (!indices.every((j) => toFrom[j] < 0)) continue;+ const list = pool.get(signatureOf(to, indices));+ if (list === undefined || list.length === 0) continue;+ let best = 0;+ for (const [k, candidate] of list.entries()) {+ if (Math.abs(candidate - line) < Math.abs(list[best] - line)) best = k;+ }+ const [source] = list.splice(best, 1);+ const origin = fromLines.get(source) ?? [];+ for (const [k, j] of indices.entries()) link([origin[k], j]);+ }+ return { fromTo, toFrom };+}++function ranks(lines: number[]) {+ const distinct = Array.from(new Set(lines)).sort((a, b) => a - b);+ const map = new Map<number, number>();+ const last = distinct.length - 1;+ for (const [index, line] of distinct.entries()) {+ map.set(line, last > 0 ? index / last : 0);+ }+ return map;+}++function changedLines(+ from: CodeMorphVersion,+ to: CodeMorphVersion,+ diff: CodeMorphDiff,+) {+ const sizes = new Map<number, number>();+ for (const token of from.tokens) {+ sizes.set(token.line, (sizes.get(token.line) ?? 0) + 1);+ }+ const members = new Map<number, number[]>();+ for (const [j, token] of to.tokens.entries()) {+ const list = members.get(token.line);+ if (list) list.push(j);+ else members.set(token.line, [j]);+ }+ const changed: number[] = [];+ for (const [line, indices] of members) {+ const sources = indices.map((j) => diff.toFrom[j]);+ const origin = sources[0] >= 0 ? from.tokens[sources[0]].line : -1;+ const inLine = (i: number) => i >= 0 && from.tokens[i].line === origin;+ const copied = sources.every(inLine);+ if (!(copied && sizes.get(origin) === indices.length)) changed.push(line);+ }+ return changed.sort((a, b) => a - b);+}++function morphOf(from: CodeMorphVersion, to: CodeMorphVersion) {+ const diff = diffCodeMorphTokens(from.tokens, to.tokens);+ const leaving: number[] = [];+ const moving: number[] = [];+ const entering: number[] = [];+ for (const [i, token] of from.tokens.entries()) {+ if (diff.fromTo[i] < 0) leaving.push(token.line);+ }+ for (const [j, token] of to.tokens.entries()) {+ const i = diff.toFrom[j];+ if (i < 0) {+ entering.push(token.line);+ continue;+ }+ const source = from.tokens[i];+ if (source.line !== token.line || source.col !== token.col) {+ moving.push(token.line);+ }+ }+ return {+ diff,+ exitRank: ranks(leaving),+ moveRank: ranks(moving),+ enterRank: ranks(entering),+ changed: changedLines(from, to, diff),+ };+}++function stepsOf(steps: CodeMorphStep[] | undefined) {+ const source = Array.isArray(steps) ? steps : codeMorphDefaults.steps;+ const ordered = source+ .map((step, index) => ({+ index,+ at: Math.max(0, finite(step.at, 0)),+ code: typeof step.code === "string" ? step.code : "",+ }))+ .sort((a, b) => a.at - b.at || a.index - b.index);+ return ordered.length > 0 ? ordered : [{ index: 0, at: 0, code: "" }];+}++export function getCodeMorphLayout(options: CodeMorphOptions = {}) {+ const width = Math.max(1, finite(options.width, REFERENCE_WIDTH));+ const height = Math.max(1, finite(options.height, REFERENCE_HEIGHT));+ const requested = finite(options.fontSize, codeMorphDefaults.fontSize);+ const size = clamp(requested, MIN_FONT, MAX_FONT);+ const lineNumbers = options.lineNumbers !== false;+ const windowDots = options.windowDots !== false;+ const filename = (options.filename ?? codeMorphDefaults.filename).trim();+ const versions = stepsOf(options.steps).map((step) => versionOf(step.code));+ const morphs: ReturnType<typeof morphOf>[] = [];+ for (let index = 1; index < versions.length; index += 1) {+ morphs.push(morphOf(versions[index - 1], versions[index]));+ }+ const rows = Math.max(...versions.map((version) => version.lines));+ const columns = Math.max(...versions.map((version) => version.columns));+ const digits = lineNumbers ? Math.max(2, String(rows).length) : 0;+ const gutter = lineNumbers ? digits + GUTTER_GAP : 0;+ const header = windowDots || filename !== "" ? HEADER : 0;+ const leading = size * LEADING;+ const panelWidth = PAD_LEFT + PAD_RIGHT + (gutter + columns) * ADVANCE * size;+ const panelHeight = header + PAD_TOP + PAD_BOTTOM + rows * leading;+ const fit = Math.min(1, MAX_WIDTH / panelWidth, MAX_HEIGHT / panelHeight);+ const scale = Math.min(width / REFERENCE_WIDTH, height / REFERENCE_HEIGHT);+ const unit = scale * fit;+ return {+ width,+ height,+ unit,+ fit,+ fontSize: size * unit,+ lineHeight: leading * unit,+ header: header * unit,+ padTop: PAD_TOP * unit,+ padBottom: PAD_BOTTOM * unit,+ padLeft: PAD_LEFT * unit,+ padRight: PAD_RIGHT * unit,+ rows,+ columns,+ digits,+ gutter,+ lineNumbers,+ windowDots,+ filename,+ versions,+ morphs,+ };+}++export type CodeMorphLayout = ReturnType<typeof getCodeMorphLayout>;++export function getCodeMorphTimeline(options: CodeMorphOptions = {}) {+ const requested = finite(+ options.morphDuration,+ codeMorphDefaults.morphDuration,+ );+ const morph = clamp(requested, MIN_MORPH, MAX_MORPH);+ const highlight = options.highlight !== false;+ const steps = stepsOf(options.steps).map((step) => step.at);+ const starts: number[] = [];+ let ready = 0;+ for (const at of steps.slice(1)) {+ const start = Math.max(at, ready);+ starts.push(start);+ ready = start + morph;+ }+ const morphs = starts.map((start, index) => {+ const highlightStart = start + phase(ENTER_START, morph);+ const natural = highlightStart + RISE + SHOW;+ const next = index + 1 < starts.length ? starts[index + 1] : natural;+ const fallStart = Math.min(natural, next);+ return {+ from: index,+ to: index + 1,+ start,+ end: start + morph,+ highlightStart,+ fallStart,+ highlightEnd: fallStart + FALL,+ };+ });+ let settled = 0;+ if (morphs.length > 0) {+ const last = morphs[morphs.length - 1];+ settled = highlight ? Math.max(last.end, last.highlightEnd) : last.end;+ }+ return { morph, highlight, steps, morphs, settled, duration: settled + HOLD };+}++export type CodeMorphTimeline = ReturnType<typeof getCodeMorphTimeline>;++export const codeMorphLength = getCodeMorphTimeline().settled;++export function getCodeMorphDuration(options: CodeMorphOptions = {}) {+ const speed = Math.max(0, finite(options.speed, codeMorphDefaults.speed));+ if (speed === 0) return 1;+ const { duration } = getCodeMorphTimeline(options);+ return Math.max(1, Math.ceil(duration / speed));+}++export function getCodeMorphTime(+ frame: number,+ options: CodeMorphOptions = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const speed = Math.max(0, finite(options.speed, codeMorphDefaults.speed));+ return Math.max(0, finite(frame, 0)) * (30 / fps) * speed;+}++function rowsOf(count: number, opacity: (row: number) => number) {+ return Array.from({ length: count }, (_, row) => ({+ key: `${row}`,+ row,+ opacity: opacity(row),+ }));+}++function restingTokens(layout: CodeMorphLayout, version: number) {+ const { tokens } = layout.versions[version];+ return tokens.map(+ (token, j): CodeMorphRenderToken => ({+ key: `${version}:${j}`,+ text: token.text,+ kind: token.kind,+ role: "rest",+ line: token.line,+ col: token.col,+ opacity: 1,+ scale: 1,+ blur: 0,+ }),+ );+}++function morphFrame(+ layout: CodeMorphLayout,+ index: number,+ local: number,+ morph: number,+) {+ const data = layout.morphs[index];+ const from = layout.versions[index];+ const to = layout.versions[index + 1];+ const blur = BLUR * layout.unit;+ const tokens: CodeMorphRenderToken[] = [];+ for (const [i, token] of from.tokens.entries()) {+ if (data.diff.fromTo[i] >= 0) continue;+ const rank = data.exitRank.get(token.line) ?? 0;+ const delay = phase(EXIT_SPREAD, morph) * rank;+ const progress = (local - delay) / phase(EXIT_DURATION, morph);+ if (progress >= 1) continue;+ const eased = easeOut(progress);+ tokens.push({+ key: `${index}>${i}`,+ text: token.text,+ kind: token.kind,+ role: "exit",+ line: token.line,+ col: token.col,+ opacity: 1 - eased,+ scale: 1 - SHRINK * eased,+ blur: blur * eased,+ });+ }+ const travel = (delay: number) =>+ (local - phase(MOVE_START, morph) - delay) / phase(MOVE_DURATION, morph);+ for (const [j, token] of to.tokens.entries()) {+ const i = data.diff.toFrom[j];+ if (i < 0) continue;+ const source = from.tokens[i];+ const still = source.line === token.line && source.col === token.col;+ const rank = data.moveRank.get(token.line) ?? 0;+ const progress = travel(phase(CASCADE, morph) * rank);+ const vertical = glide(unit01(progress / (1 - ARC)));+ const horizontal = glide(unit01((progress - ARC) / (1 - ARC)));+ tokens.push({+ key: `${index + 1}:${j}`,+ text: token.text,+ kind: token.kind,+ role: still ? "stay" : "move",+ line: source.line + (token.line - source.line) * vertical,+ col: source.col + (token.col - source.col) * horizontal,+ opacity: 1,+ scale: 1,+ blur: 0,+ });+ }+ for (const [j, token] of to.tokens.entries()) {+ if (data.diff.toFrom[j] >= 0) continue;+ const rank = data.enterRank.get(token.line) ?? 0;+ const start = phase(ENTER_START + ENTER_SPREAD * rank, morph);+ const progress = (local - start) / phase(ENTER_DURATION, morph);+ if (progress <= 0) continue;+ const eased = easeOut(progress);+ tokens.push({+ key: `${index + 1}:${j}`,+ text: token.text,+ kind: token.kind,+ role: "enter",+ line: token.line,+ col: token.col,+ opacity: eased,+ scale: GROW_FROM + (1 - GROW_FROM) * eased,+ blur: blur * (1 - eased),+ });+ }+ const shrinking = to.lines < from.lines;+ const lag = shrinking ? phase(CASCADE, morph) : 0;+ const grown = glide(unit01(travel(lag) / (1 - ARC)));+ const lines = from.lines + (to.lines - from.lines) * grown;+ const shared = Math.min(from.lines, to.lines);+ const lineNumbers = rowsOf(Math.max(from.lines, to.lines), (row) => {+ if (row < shared) return 1;+ return shrinking ? 1 - grown : grown;+ });+ return { tokens, lines, lineNumbers };+}++function highlightsAt(+ time: number,+ timeline: CodeMorphTimeline,+ layout: CodeMorphLayout,+ active: number,+) {+ const rows: CodeMorphRow[] = [];+ if (!timeline.highlight) return rows;+ for (const index of [active - 1, active]) {+ if (index < 0) continue;+ const morph = timeline.morphs[index];+ const rise = easeOutQuad((time - morph.highlightStart) / RISE);+ const fall = smoothstep((time - morph.fallStart) / FALL);+ const opacity = rise * (1 - fall);+ if (opacity <= 0) continue;+ for (const row of layout.morphs[index].changed) {+ rows.push({ key: `${index}:${row}`, row, opacity });+ }+ }+ return rows;+}++export function getCodeMorphState(+ frame: number,+ options: CodeMorphOptions = {},+ layout: CodeMorphLayout = getCodeMorphLayout(options),+): CodeMorphState {+ const timeline = getCodeMorphTimeline(options);+ const time = getCodeMorphTime(frame, options);+ let active = -1;+ for (const [index, morph] of timeline.morphs.entries()) {+ if (morph.start <= time) active = index;+ }+ const highlights = highlightsAt(time, timeline, layout, active);+ if (active === -1) {+ const lines = layout.versions[0].lines;+ return {+ time,+ version: 0,+ morphing: false,+ progress: 0,+ lines,+ tokens: restingTokens(layout, 0),+ lineNumbers: rowsOf(lines, () => 1),+ highlights,+ };+ }+ const local = time - timeline.morphs[active].start;+ if (local >= timeline.morph) {+ const version = active + 1;+ const lines = layout.versions[version].lines;+ return {+ time,+ version,+ morphing: false,+ progress: 1,+ lines,+ tokens: restingTokens(layout, version),+ lineNumbers: rowsOf(lines, () => 1),+ highlights,+ };+ }+ const motion = morphFrame(layout, active, local, timeline.morph);+ return {+ time,+ version: active + 1,+ morphing: true,+ progress: local / timeline.morph,+ lines: motion.lines,+ tokens: motion.tokens,+ lineNumbers: motion.lineNumbers,+ highlights,+ };+}++function transformOf(token: CodeMorphRenderToken, lineHeight: number) {+ const move = `translate(${token.col}ch, ${token.line * lineHeight}px)`;+ return token.scale === 1 ? move : `${move} scale(${token.scale})`;+}++export function CodeMorph({+ steps = codeMorphDefaults.steps,+ morphDuration = codeMorphDefaults.morphDuration,+ highlight = codeMorphDefaults.highlight,+ fontSize = codeMorphDefaults.fontSize,+ lineNumbers = codeMorphDefaults.lineNumbers,+ filename = codeMorphDefaults.filename,+ windowDots = codeMorphDefaults.windowDots,+ theme = codeMorphDefaults.theme,+ accentColor = codeMorphDefaults.accentColor,+ speed = codeMorphDefaults.speed,+ className,+}: CodeMorphProps) {+ const frame = useCurrentFrame();+ const { width, height, fps } = useVideoConfig();+ const layout = useMemo(() => {+ const shape = { steps, fontSize, lineNumbers, filename, windowDots };+ return getCodeMorphLayout({ ...shape, width, height });+ }, [steps, fontSize, lineNumbers, filename, windowDots, width, height]);+ const motion = { steps, morphDuration, highlight, speed, fps };+ const state = getCodeMorphState(frame, motion, layout);+ const palette = theme === "light" ? PALETTES.light : PALETTES.dark;+ const unit = layout.unit;+ const hairline = Math.max(1, unit);+ const edge = `${hairline}px solid ${palette.border}`;+ const top = layout.header + layout.padTop;+ const blend = `${palette.share}%, ${palette.mix}`;+ const accentText = `color-mix(in oklab, ${accentColor} ${blend})`;+ const colorOf = (kind: CodeMorphKind) =>+ kind === "string" || kind === "number" ? accentText : palette[kind];+ const panelColumns = `${layout.gutter + layout.columns}ch`;+ const panelPadding = layout.padLeft + layout.padRight;+ const codeLeft = `${layout.gutter}ch`;+ const tabLeft = (layout.windowDots ? TAB_AFTER_DOTS : TAB_LEFT) * unit;+ const tabRadius = TAB_RADIUS * unit;++ return (+ <div+ className={className}+ style={{+ position: "absolute",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ <div+ style={{+ position: "relative",+ flexShrink: 0,+ boxSizing: "content-box",+ width: `calc(${panelColumns} + ${panelPadding}px)`,+ height: top + layout.rows * layout.lineHeight + layout.padBottom,+ background: palette.panel,+ color: palette.text,+ border: edge,+ borderRadius: RADIUS * unit,+ overflow: "hidden",+ fontFamily: FONT_MONO,+ fontSize: layout.fontSize,+ lineHeight: `${layout.lineHeight}px`,+ fontVariantLigatures: "none",+ fontKerning: "none",+ }}+ >+ {layout.header > 0 ? (+ <div+ style={{+ position: "absolute",+ left: 0,+ top: 0,+ right: 0,+ height: layout.header,+ background: palette.chrome,+ }}+ >+ <div+ style={{+ position: "absolute",+ left: 0,+ right: 0,+ bottom: 0,+ height: hairline,+ background: palette.border,+ }}+ />+ {layout.windowDots+ ? DOTS.map((dot) => (+ <div+ key={dot}+ style={{+ position: "absolute",+ left: (DOT_LEFT + dot * (DOT + DOT_GAP)) * unit,+ top: ((HEADER - DOT) / 2) * unit,+ width: DOT * unit,+ height: DOT * unit,+ borderRadius: "50%",+ background: palette.dot,+ }}+ />+ ))+ : null}+ {layout.filename !== "" ? (+ <div+ style={{+ position: "absolute",+ left: tabLeft,+ bottom: 0,+ height: (HEADER - TAB_TOP) * unit,+ boxSizing: "border-box",+ display: "flex",+ alignItems: "center",+ padding: `0 ${TAB_PAD * unit}px`,+ background: palette.panel,+ borderTop: edge,+ borderLeft: edge,+ borderRight: edge,+ borderRadius: `${tabRadius}px ${tabRadius}px 0 0`,+ color: palette.label,+ fontSize: TAB_FONT * unit,+ lineHeight: 1,+ whiteSpace: "pre",+ }}+ >+ {layout.filename}+ </div>+ ) : null}+ </div>+ ) : null}+ {state.highlights.map((band) => (+ <div+ key={band.key}+ style={{+ position: "absolute",+ left: 0,+ right: 0,+ top: top + band.row * layout.lineHeight,+ height: layout.lineHeight,+ }}+ >+ <div+ style={{+ position: "absolute",+ inset: 0,+ background: accentColor,+ opacity: band.opacity * palette.band,+ }}+ />+ <div+ style={{+ position: "absolute",+ left: 0,+ top: 0,+ bottom: 0,+ width: BAR * unit,+ background: accentColor,+ opacity: band.opacity,+ }}+ />+ </div>+ ))}+ <div style={{ position: "absolute", left: layout.padLeft, top }}>+ {layout.lineNumbers+ ? state.lineNumbers.map((row) => (+ <div+ key={row.key}+ style={{+ position: "absolute",+ left: 0,+ top: row.row * layout.lineHeight,+ width: `${layout.digits}ch`,+ textAlign: "right",+ whiteSpace: "pre",+ color: palette.gutter,+ opacity: row.opacity,+ }}+ >+ {row.row + 1}+ </div>+ ))+ : null}+ <div style={{ position: "absolute", left: codeLeft, top: 0 }}>+ {state.tokens.map((token) => (+ <span+ key={token.key}+ style={{+ position: "absolute",+ left: 0,+ top: 0,+ display: "block",+ whiteSpace: "pre",+ color: colorOf(token.kind),+ opacity: token.opacity,+ transform: transformOf(token, layout.lineHeight),+ filter: token.blur > 0 ? `blur(${token.blur}px)` : undefined,+ }}+ >+ {token.text}+ </span>+ ))}+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/registry/remocn/echo-stack/__tests__/echo-stack.test.ts b/registry/remocn/echo-stack/__tests__/echo-stack.test.tsnew file mode 100644index 00000000..d3905aa8--- /dev/null+++ b/registry/remocn/echo-stack/__tests__/echo-stack.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ echoStackDefaults,+ echoStackLength,+ getEchoStackFade,+ getEchoStackMain,+ getEchoStackRows,+ getEchoStackTime,+} from "..";+import { echoStackConfig } from "../config";++describe("echo-stack main word", () => {+ it("focuses in over 14 frames", () => {+ expect(getEchoStackMain(0)).toEqual({ blur: 12, opacity: 0, scale: 1.04 });+ expect(getEchoStackMain(14)).toEqual({ blur: 0, opacity: 1, scale: 1 });+ expect(getEchoStackMain(7).blur).toBeLessThan(6);+ });+});++describe("echo-stack fade", () => {+ it("hides echoes behind the word and fades them out toward the edges", () => {+ expect(getEchoStackFade(0, 3)).toBe(0);+ expect(getEchoStackFade(0.5, 3)).toBe(0);+ expect(getEchoStackFade(-0.5, 3)).toBe(0);+ expect(getEchoStackFade(1, 3)).toBe(1);+ expect(getEchoStackFade(-1, 3)).toBe(1);+ expect(getEchoStackFade(2, 3)).toBeCloseTo(0.6, 10);+ expect(getEchoStackFade(3.5, 3)).toBe(0);+ expect(getEchoStackFade(5, 3)).toBe(0);+ });++ it("never rises above one", () => {+ for (let d = -6; d <= 6; d += 0.05) {+ const fade = getEchoStackFade(d, 3);+ expect(fade).toBeGreaterThanOrEqual(0);+ expect(fade).toBeLessThanOrEqual(1);+ }+ });+});++describe("echo-stack rows", () => {+ it("stays empty until the unfold begins", () => {+ expect(getEchoStackRows(0)).toEqual([]);+ expect(getEchoStackRows(8)).toEqual([]);+ });++ it("unfolds from a compressed pitch to the full pitch", () => {+ const early = getEchoStackRows(12);+ for (const row of early) {+ expect(Math.abs(row.position)).toBeLessThan(Math.abs(row.offset));+ }+ const late = getEchoStackRows(echoStackLength);+ for (const row of late) expect(row.position).toBeCloseTo(row.offset, 10);+ });++ it("loops seamlessly every cycle", () => {+ const at = (t: number) =>+ getEchoStackRows(t)+ .map((r) => [r.offset.toFixed(6), r.opacity.toFixed(6)].join(":"))+ .sort();+ expect(at(90)).toEqual(at(90 + echoStackDefaults.cycle));+ expect(at(95.5)).toEqual(at(95.5 + echoStackDefaults.cycle));+ });++ it("drifts in the chosen direction", () => {+ const up = getEchoStackRows(70).map((r) => r.offset);+ const upLater = getEchoStackRows(71).map((r) => r.offset);+ expect(upLater[0]).toBeLessThan(up[0]);+ const down = getEchoStackRows(70, { direction: "down" }).map(+ (r) => r.offset,+ );+ const downLater = getEchoStackRows(71, { direction: "down" }).map(+ (r) => r.offset,+ );+ expect(downLater[0]).toBeGreaterThan(down[0]);+ });++ it("caps each echo at echoOpacity", () => {+ for (let t = 0; t < 200; t += 0.5) {+ for (const row of getEchoStackRows(t, { echoOpacity: 0.4 })) {+ expect(row.opacity).toBeGreaterThan(0);+ expect(row.opacity).toBeLessThanOrEqual(0.4);+ expect(Math.abs(row.offset)).toBeGreaterThanOrEqual(0.55);+ }+ }+ });++ it("scales the number of visible echoes with `echoes`", () => {+ const one = getEchoStackRows(60, { echoes: 1 });+ const five = getEchoStackRows(60, { echoes: 5 });+ expect(Math.max(...one.map((r) => Math.abs(r.offset)))).toBeLessThan(1.5);+ expect(Math.max(...five.map((r) => Math.abs(r.offset)))).toBe(5);+ });+});++describe("echo-stack time and config", () => {+ it("maps frames onto the 30 fps timeline", () => {+ expect(getEchoStackTime(30)).toBe(30);+ expect(getEchoStackTime(60, { fps: 60 })).toBe(30);+ expect(getEchoStackTime(10, { speed: 0.5 })).toBe(5);+ });++ it("previews with the component's defaults", () => {+ const defaults = getDefaults(+ resolveControls("echo-stack", echoStackConfig.controls),+ );+ expect(defaults.text).toBe(echoStackDefaults.text);+ expect(defaults.direction).toBe(echoStackDefaults.direction);+ expect(defaults.echoes).toBe(echoStackDefaults.echoes);+ expect(defaults.echoOpacity).toBe(echoStackDefaults.echoOpacity);+ expect(defaults.cycle).toBe(echoStackDefaults.cycle);+ expect(echoStackConfig.durationInFrames % echoStackDefaults.cycle).toBe(0);+ });+});diff --git a/registry/remocn/echo-stack/config.ts b/registry/remocn/echo-stack/config.tsnew file mode 100644index 00000000..97fef136--- /dev/null+++ b/registry/remocn/echo-stack/config.ts@@ -0,0 +1,64 @@+import {+ type ComponentConfig,+ enumVariants,+ FPS,+ H,+ W,+} from "@/lib/customizer-config";++export const echoStackConfig: ComponentConfig = {+ componentName: "EchoStack",+ importPath: "@/components/remocn/echo-stack",+ controls: {+ text: { type: "text-content", default: "Bold.", description: "Text" },+ color: { type: "color", default: "#fafafa", description: "Text color" },+ echoColor: { type: "color", default: "#fafafa", description: "Echo color" },+ direction: {+ type: "enum",+ default: "up",+ variants: enumVariants(["up", "down"]),+ description: "Direction",+ },+ fontSize: {+ type: "number",+ default: 170,+ min: 60,+ max: 300,+ step: 2,+ description: "Font size",+ hiddenFromList: false,+ },+ echoes: {+ type: "number",+ default: 3,+ min: 1,+ max: 6,+ step: 1,+ description: "Echoes per side",+ hiddenFromList: false,+ },+ echoOpacity: {+ type: "number",+ default: 0.35,+ min: 0.05,+ max: 1,+ step: 0.05,+ description: "Echo opacity",+ hiddenFromList: false,+ },+ cycle: {+ type: "number",+ default: 60,+ min: 15,+ max: 240,+ step: 5,+ description: "Frames per row",+ hiddenFromList: false,+ },+ },+ durationInFrames: 120,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#0a0a0a" },+};diff --git a/registry/remocn/echo-stack/index.tsx b/registry/remocn/echo-stack/index.tsxnew file mode 100644index 00000000..77299c56--- /dev/null+++ b/registry/remocn/echo-stack/index.tsx@@ -0,0 +1,247 @@+"use client";++import { loadFont } from "@remotion/google-fonts/Inter";+import { useId } from "react";+import { Easing, interpolate, useCurrentFrame, useVideoConfig } from "remotion";++const { fontFamily: INTER } = loadFont("normal", {+ weights: ["100", "900"],+ subsets: ["latin"],+});++export type EchoStackDirection = "up" | "down";++export interface EchoStackProps {+ text?: string;+ fontSize?: number;+ fontWeight?: number;+ fontFamily?: string;+ color?: string;+ echoColor?: string;+ echoes?: number;+ echoOpacity?: number;+ strokeWidth?: number;+ direction?: EchoStackDirection;+ cycle?: number;+ speed?: number;+ className?: string;+}++export const echoStackDefaults = {+ text: "Bold.",+ fontSize: 170,+ fontWeight: 800,+ fontFamily: INTER,+ color: "#fafafa",+ echoColor: "",+ echoes: 3,+ echoOpacity: 0.35,+ strokeWidth: 1.5,+ direction: "up",+ cycle: 60,+ speed: 1,+} satisfies Required<Omit<EchoStackProps, "className">>;++/** Frame where the entrance has finished; the drift keeps running after it. */+export const echoStackLength = 26;++/** Distance between echo rows, in em. */+export const echoStackPitch = 1.05;++/** Echoes closer to the center than this, in pitches, hide behind the word. */+const HIDDEN = 0.55;+const MAIN = [0, 14] as const;+const UNFOLD = [8, 26] as const;+const FADE_IN = [8, 24] as const;+const START_SPREAD = 0.6;+const MAX_BLUR = 12;++const CLAMP = {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+} as const;++const easeOutCubic = Easing.out(Easing.cubic);++function finite(value: number | undefined, fallback: number) {+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;+}++function smoothstep(x: number) {+ const c = Math.min(1, Math.max(0, x));+ return c * c * (3 - 2 * c);+}++/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */+export function getEchoStackTime(+ frame: number,+ options: { fps?: number; speed?: number } = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const speed = Math.max(0, finite(options.speed, 1));+ return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;+}++/** The main word focusing in. Blur is in reference px. */+export function getEchoStackMain(t: number) {+ const k = interpolate(t, [...MAIN], [0, 1], {+ ...CLAMP,+ easing: easeOutCubic,+ });+ return { blur: MAX_BLUR * (1 - k), opacity: k, scale: 1.04 - 0.04 * k };+}++/** Echo visibility at a distance from the center, in pitches, before `echoOpacity`. */+export function getEchoStackFade(distance: number, echoes: number) {+ const d = Math.abs(distance);+ if (d < HIDDEN) return 0;+ if (d < 1) return smoothstep((d - HIDDEN) / (1 - HIDDEN));+ const reach = Math.max(1, echoes + 0.5);+ return Math.max(0, 1 - (d - 1) / (reach - 1));+}++export interface EchoStackRow {+ /** Signed distance from the center in pitches, negative above. */+ offset: number;+ /** Row position in pitches after the unfold, negative above. */+ position: number;+ opacity: number;+}++export function getEchoStackRows(+ t: number,+ options: {+ echoes?: number;+ echoOpacity?: number;+ cycle?: number;+ direction?: EchoStackDirection;+ } = {},+): EchoStackRow[] {+ const echoes = Math.max(0, Math.round(finite(options.echoes, 3)));+ const echoOpacity = Math.max(0, finite(options.echoOpacity, 0.35));+ const cycle = Math.max(1, finite(options.cycle, 60));+ const sign = options.direction === "down" ? 1 : -1;+ const phase = sign * ((t / cycle) % 1);+ const spread = interpolate(t, [...UNFOLD], [START_SPREAD, 1], {+ ...CLAMP,+ easing: easeOutCubic,+ });+ const fadeIn = interpolate(t, [...FADE_IN], [0, 1], {+ ...CLAMP,+ easing: easeOutCubic,+ });+ const rows: EchoStackRow[] = [];+ const reach = echoes + 2;+ for (let k = -reach; k <= reach; k++) {+ const offset = k + phase;+ const opacity = echoOpacity * fadeIn * getEchoStackFade(offset, echoes);+ if (opacity <= 0) continue;+ rows.push({ offset, position: offset * spread, opacity });+ }+ return rows;+}++export function EchoStack({+ text = echoStackDefaults.text,+ fontSize = echoStackDefaults.fontSize,+ fontWeight = echoStackDefaults.fontWeight,+ fontFamily = echoStackDefaults.fontFamily,+ color = echoStackDefaults.color,+ echoColor = echoStackDefaults.echoColor,+ echoes = echoStackDefaults.echoes,+ echoOpacity = echoStackDefaults.echoOpacity,+ strokeWidth = echoStackDefaults.strokeWidth,+ direction = echoStackDefaults.direction,+ cycle = echoStackDefaults.cycle,+ speed = echoStackDefaults.speed,+ className,+}: EchoStackProps) {+ const frame = useCurrentFrame();+ const { fps, height } = useVideoConfig();+ const unit = height / 720;+ const size = fontSize * unit;+ const t = getEchoStackTime(frame, { fps, speed });+ const main = getEchoStackMain(t);+ const rows = getEchoStackRows(t, { echoes, echoOpacity, cycle, direction });+ const pitch = echoStackPitch * size;+ const outlineId = `echo-stack-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;++ const type = {+ fontFamily,+ fontSize: size,+ lineHeight: 1,+ fontWeight,+ fontVariationSettings: `"wght" ${fontWeight}`,+ whiteSpace: "pre",+ } as const;++ return (+ <div+ className={className}+ style={{+ position: "absolute",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ overflow: "hidden",+ }}+ >+ {/* Outline from the filled silhouette: the variable font's overlapping+ contours would show through a text stroke. */}+ <svg width={0} height={0} style={{ position: "absolute" }} aria-hidden>+ <defs>+ <filter id={outlineId}>+ <feMorphology+ in="SourceAlpha"+ operator="erode"+ radius={strokeWidth * unit}+ result="inner"+ />+ <feComposite+ in="SourceAlpha"+ in2="inner"+ operator="out"+ result="ring"+ />+ <feFlood floodColor={echoColor || color} />+ <feComposite in2="ring" operator="in" />+ </filter>+ </defs>+ </svg>+ <div style={{ position: "relative" }}>+ {rows.map((row, i) => (+ <div+ key={i}+ aria-hidden+ style={{+ ...type,+ position: "absolute",+ left: "50%",+ top: "50%",+ color: echoColor || color,+ filter: `url(#${outlineId})`,+ opacity: row.opacity,+ transform: `translate(-50%, calc(-50% + ${row.position * pitch}px))`,+ }}+ >+ {text}+ </div>+ ))}+ <div+ style={{+ ...type,+ position: "relative",+ color,+ opacity: main.opacity,+ filter:+ main.blur > 0.05 ? `blur(${main.blur * unit}px)` : undefined,+ transform: `scale(${main.scale})`,+ }}+ >+ {text}+ </div>+ </div>+ </div>+ );+}diff --git a/registry/remocn/glyph-anatomy/__tests__/glyph-anatomy.test.ts b/registry/remocn/glyph-anatomy/__tests__/glyph-anatomy.test.tsnew file mode 100644index 00000000..c3bfabc9--- /dev/null+++ b/registry/remocn/glyph-anatomy/__tests__/glyph-anatomy.test.ts@@ -0,0 +1,144 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getAnatomyContours,+ getAnatomyPath,+ getGlyphAnatomyAnchor,+ getGlyphAnatomyGuide,+ getGlyphAnatomyLength,+ getGlyphAnatomyLetter,+ getGlyphAnatomyPull,+ getGlyphAnatomyTime,+ glyphAnatomyDefaults,+ glyphAnatomyTiming,+} from "..";+import { glyphAnatomyConfig } from "../config";++describe("glyph-anatomy contours", () => {+ it("converts a quadratic into a cubic with handles two thirds out", () => {+ const [contour] = getAnatomyContours([+ { type: "M", x: 0, y: 0 },+ { type: "Q", x1: 30, y1: 30, x: 60, y: 0 },+ { type: "Z" },+ ]);+ expect(contour[0].c1).toEqual({ x: 20, y: 20 });+ expect(contour[0].c2).toEqual({ x: 40, y: 20 });+ expect(contour[0].to).toEqual({ x: 60, y: 0 });+ });++ it("closes an open contour with a straight segment back to its start", () => {+ const [contour] = getAnatomyContours([+ { type: "M", x: 0, y: 0 },+ { type: "L", x: 10, y: 0 },+ { type: "L", x: 10, y: 10 },+ { type: "Z" },+ ]);+ expect(contour).toHaveLength(3);+ expect(contour[2]).toEqual({ from: { x: 10, y: 10 }, to: { x: 0, y: 0 } });+ });++ it("keeps cubics and separates contours", () => {+ const contours = getAnatomyContours([+ { type: "M", x: 0, y: 0 },+ { type: "C", x1: 1, y1: 2, x2: 3, y2: 4, x: 5, y: 0 },+ { type: "Z" },+ { type: "M", x: 20, y: 0 },+ { type: "L", x: 30, y: 0 },+ { type: "Z" },+ ]);+ expect(contours).toHaveLength(2);+ expect(contours[0][0].c1).toEqual({ x: 1, y: 2 });+ expect(contours[0][0].c2).toEqual({ x: 3, y: 4 });+ });+});++describe("glyph-anatomy path", () => {+ const [contour] = getAnatomyContours([+ { type: "M", x: 0, y: 0 },+ { type: "Q", x1: 30, y1: 30, x: 60, y: 0 },+ { type: "Z" },+ ]);++ it("collapses curves onto their chords before the pull", () => {+ expect(getAnatomyPath(contour, () => 0)).toBe(+ "M0.00 0.00C0.00 0.00 60.00 0.00 60.00 0.00L0.00 0.00Z",+ );+ });++ it("puts the handles in place once pulled", () => {+ expect(getAnatomyPath(contour, () => 1)).toBe(+ "M0.00 0.00C20.00 20.00 40.00 20.00 60.00 0.00L0.00 0.00Z",+ );+ });+});++describe("glyph-anatomy timeline", () => {+ it("draws the guides three frames apart", () => {+ expect(getGlyphAnatomyGuide(0, 0)).toBe(0);+ expect(getGlyphAnatomyGuide(10, 0)).toBe(1);+ expect(getGlyphAnatomyGuide(3, 1)).toBe(0);+ expect(getGlyphAnatomyGuide(19, 3)).toBe(1);+ });++ it("pops anchors in path order between frames 8 and 22", () => {+ expect(getGlyphAnatomyAnchor(8, 0, 10)).toBe(0);+ expect(getGlyphAnatomyAnchor(12, 0, 10)).toBeCloseTo(1, 10);+ expect(getGlyphAnatomyAnchor(12, 9, 10)).toBe(0);+ expect(getGlyphAnatomyAnchor(22, 9, 10)).toBeCloseTo(1, 10);+ expect(getGlyphAnatomyAnchor(8, 0, 1)).toBe(0);+ });++ it("pulls each curve with an overshoot, in order", () => {+ let peak = 0;+ for (let t = 18; t <= 26; t += 0.1) {+ peak = Math.max(peak, getGlyphAnatomyPull(t, 0, 5));+ }+ expect(peak).toBeGreaterThan(1.05);+ expect(getGlyphAnatomyPull(26, 0, 5)).toBeCloseTo(1, 10);+ expect(getGlyphAnatomyPull(26, 4, 5)).toBe(0);+ expect(getGlyphAnatomyPull(40, 4, 5)).toBeCloseTo(1, 10);+ });++ it("fills, then fades the scaffolding", () => {+ expect(getGlyphAnatomyLetter(8)).toEqual({+ outline: 0,+ fill: 0,+ scaffold: 1,+ });+ expect(getGlyphAnatomyLetter(50).fill).toBe(1);+ expect(getGlyphAnatomyLetter(50).scaffold).toBeGreaterThan(0);+ expect(getGlyphAnatomyLetter(58).scaffold).toBe(0);+ });++ it("ends when the last letter's scaffolding has faded", () => {+ const count = Array.from(glyphAnatomyDefaults.text).length;+ expect(getGlyphAnatomyLength(count)).toBe(+ glyphAnatomyTiming.fade[1] + 2 * (count - 1),+ );+ });++ it("maps frames onto the 30 fps timeline", () => {+ expect(getGlyphAnatomyTime(30)).toBe(30);+ expect(getGlyphAnatomyTime(60, { fps: 60 })).toBe(30);+ expect(getGlyphAnatomyTime(10, { speed: 2 })).toBe(20);+ });+});++describe("glyph-anatomy config", () => {+ it("previews with the component's defaults", () => {+ const defaults = getDefaults(+ resolveControls("glyph-anatomy", glyphAnatomyConfig.controls),+ );+ expect(defaults).toMatchObject({+ text: glyphAnatomyDefaults.text,+ color: glyphAnatomyDefaults.color,+ guideColor: glyphAnatomyDefaults.guideColor,+ fontSize: glyphAnatomyDefaults.fontSize,+ guides: true,+ keepPoints: false,+ });+ expect(glyphAnatomyConfig.durationInFrames).toBeGreaterThan(+ getGlyphAnatomyLength(Array.from(glyphAnatomyDefaults.text).length),+ );+ });+});diff --git a/registry/remocn/glyph-anatomy/config.ts b/registry/remocn/glyph-anatomy/config.tsnew file mode 100644index 00000000..28f8deb4--- /dev/null+++ b/registry/remocn/glyph-anatomy/config.ts@@ -0,0 +1,27 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";++export const glyphAnatomyConfig: ComponentConfig = {+ componentName: "GlyphAnatomy",+ importPath: "@/components/remocn/glyph-anatomy",+ controls: {+ text: { type: "text-content", default: "Glyph", description: "Text" },+ color: { type: "color", default: "#fafafa", description: "Glyph color" },+ guideColor: { type: "color", default: "#0d99ff", description: "Points" },+ fontSize: {+ type: "number",+ default: 200,+ min: 80,+ max: 320,+ step: 2,+ description: "Font size",+ hiddenFromList: false,+ },+ guides: { type: "boolean", default: true, description: "Guides" },+ keepPoints: { type: "boolean", default: false, description: "Keep points" },+ },+ durationInFrames: 96,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#0a0a0a" },+};diff --git a/registry/remocn/glyph-anatomy/index.tsx b/registry/remocn/glyph-anatomy/index.tsxnew file mode 100644index 00000000..f48cec4c--- /dev/null+++ b/registry/remocn/glyph-anatomy/index.tsx@@ -0,0 +1,505 @@+"use client";++import { loadFont } from "@remotion/google-fonts/Inter";+import { type Font, parse } from "opentype.js";+import { useEffect, useState } from "react";+import {+ continueRender,+ delayRender,+ Easing,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+} from "remotion";++const { fontFamily: INTER } = loadFont("normal", {+ weights: ["500"],+ subsets: ["latin"],+});++export interface GlyphAnatomyProps {+ text?: string;+ fontUrl?: string;+ fontSize?: number;+ color?: string;+ guideColor?: string;+ guides?: boolean;+ keepPoints?: boolean;+ speed?: number;+ className?: string;+}++/** Static Inter ExtraBold (800) from Google Fonts. */+export const interExtraBoldTtf =+ "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuDyYMZg.ttf";++export const glyphAnatomyDefaults = {+ text: "Glyph",+ fontUrl: interExtraBoldTtf,+ fontSize: 200,+ color: "#fafafa",+ guideColor: "#0d99ff",+ guides: true,+ keepPoints: false,+ speed: 1,+} satisfies Required<Omit<GlyphAnatomyProps, "className">>;++/** Beats on the 30 fps clock. Letter beats shift by `letterStagger × i`. */+export const glyphAnatomyTiming = {+ guideStart: 0,+ guideStagger: 3,+ guideDraw: 10,+ anchors: [8, 22],+ anchorPop: 4,+ pull: [18, 40],+ pullDuration: 8,+ fill: [40, 50],+ fade: [46, 58],+ letterStagger: 2,+} as const;++const CLAMP = {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+} as const;++const easeOutCubic = Easing.out(Easing.cubic);+const easeInOutCubic = Easing.inOut(Easing.cubic);+const popEase = Easing.out(Easing.back(1.7));+const pullEase = Easing.out(Easing.back(1.6));++function finite(value: number | undefined, fallback: number) {+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;+}++/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */+export function getGlyphAnatomyTime(+ frame: number,+ options: { fps?: number; speed?: number } = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const speed = Math.max(0, finite(options.speed, 1));+ return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;+}++export interface Point {+ x: number;+ y: number;+}++export interface AnatomySegment {+ from: Point;+ to: Point;+ /** Cubic handles; absent on straight segments. */+ c1?: Point;+ c2?: Point;+}++export interface PathCommand {+ type: string;+ x?: number;+ y?: number;+ x1?: number;+ y1?: number;+ x2?: number;+ y2?: number;+}++const lerp = (a: Point, b: Point, k: number): Point => ({+ x: a.x + (b.x - a.x) * k,+ y: a.y + (b.y - a.y) * k,+});++/**+ * Turns glyph path commands into contours of explicit segments. Quadratic+ * curves become cubics (handles at ⅔ toward the control point), so every+ * curve shows one handle on each end, as in Figma or Glyphs.+ */+export function getAnatomyContours(+ commands: readonly PathCommand[],+): AnatomySegment[][] {+ const contours: AnatomySegment[][] = [];+ let segments: AnatomySegment[] = [];+ let start: Point | null = null;+ let at: Point | null = null;+ const close = () => {+ if (start && at && (at.x !== start.x || at.y !== start.y)) {+ segments.push({ from: at, to: start });+ }+ if (segments.length > 0) contours.push(segments);+ segments = [];+ start = null;+ at = null;+ };+ for (const c of commands) {+ const to = { x: c.x ?? 0, y: c.y ?? 0 };+ if (c.type === "M") {+ close();+ start = to;+ at = to;+ } else if (!at) {+ } else if (c.type === "L") {+ segments.push({ from: at, to });+ at = to;+ } else if (c.type === "Q") {+ const q = { x: c.x1 ?? 0, y: c.y1 ?? 0 };+ segments.push({+ from: at,+ to,+ c1: lerp(at, q, 2 / 3),+ c2: lerp(to, q, 2 / 3),+ });+ at = to;+ } else if (c.type === "C") {+ segments.push({+ from: at,+ to,+ c1: { x: c.x1 ?? 0, y: c.y1 ?? 0 },+ c2: { x: c.x2 ?? 0, y: c.y2 ?? 0 },+ });+ at = to;+ } else if (c.type === "Z") {+ close();+ }+ }+ close();+ return contours;+}++/**+ * How far each handle has travelled from its anchor to its place, 0 → 1 with+ * overshoot. At 0 the curve is its chord.+ */+export function getGlyphAnatomyPull(t: number, order: number, total: number) {+ const { pull, pullDuration } = glyphAnatomyTiming;+ const span = pull[1] - pull[0] - pullDuration;+ const start = pull[0] + (total > 1 ? (span * order) / (total - 1) : 0);+ return interpolate(t, [start, start + pullDuration], [0, 1], {+ ...CLAMP,+ easing: pullEase,+ });+}++/** Scale of anchor `order` of `total` popping in along the letter's path. */+export function getGlyphAnatomyAnchor(t: number, order: number, total: number) {+ const { anchors, anchorPop } = glyphAnatomyTiming;+ const span = anchors[1] - anchors[0] - anchorPop;+ const start = anchors[0] + (total > 1 ? (span * order) / (total - 1) : 0);+ return Math.max(+ 0,+ interpolate(t, [start, start + anchorPop], [0, 1], {+ ...CLAMP,+ easing: popEase,+ }),+ );+}++/** Letter-level fades: outline in, fill in, scaffolding out. */+export function getGlyphAnatomyLetter(t: number) {+ const { anchors, fill, fade } = glyphAnatomyTiming;+ return {+ outline: interpolate(t, [anchors[0], anchors[0] + 4], [0, 1], CLAMP),+ fill: interpolate(t, [...fill], [0, 1], {+ ...CLAMP,+ easing: easeInOutCubic,+ }),+ scaffold: interpolate(t, [...fade], [1, 0], {+ ...CLAMP,+ easing: easeInOutCubic,+ }),+ };+}++/** Draw progress of guide `index`, 0..1. */+export function getGlyphAnatomyGuide(t: number, index: number) {+ const { guideStart, guideStagger, guideDraw } = glyphAnatomyTiming;+ const start = guideStart + guideStagger * index;+ return interpolate(t, [start, start + guideDraw], [0, 1], {+ ...CLAMP,+ easing: easeOutCubic,+ });+}++/** Frame where the scaffolding of the last of `count` letters has faded. */+export function getGlyphAnatomyLength(count: number) {+ const { fade, letterStagger } = glyphAnatomyTiming;+ return fade[1] + letterStagger * Math.max(0, count - 1);+}++/** Path data for a contour with each handle pulled `k(segment)` of the way. */+export function getAnatomyPath(+ segments: readonly AnatomySegment[],+ pullOf: (index: number) => number,+) {+ if (segments.length === 0) return "";+ const f = (p: Point) => `${p.x.toFixed(2)} ${p.y.toFixed(2)}`;+ let d = `M${f(segments[0].from)}`;+ segments.forEach((s, i) => {+ if (s.c1 && s.c2) {+ const k = pullOf(i);+ d += `C${f(lerp(s.from, s.c1, k))} ${f(lerp(s.to, s.c2, k))} ${f(s.to)}`;+ } else {+ d += `L${f(s.to)}`;+ }+ });+ return `${d}Z`;+}++interface AnatomyLetter {+ contours: AnatomySegment[][];+}++function layout(font: Font, text: string, fontSize: number) {+ const scale = fontSize / font.unitsPerEm;+ // Per-character lookup: full shaping runs GSUB lookups that opentype.js+ // does not support in every font.+ const glyphs = Array.from(text).map((char) => font.charToGlyph(char));+ let x = 0;+ const letters: AnatomyLetter[] = glyphs.map((glyph, i) => {+ if (i > 0) x += font.getKerningValue(glyphs[i - 1], glyph) * scale;+ const contours = getAnatomyContours(glyph.getPath(x, 0, fontSize).commands);+ x += (glyph.advanceWidth ?? 0) * scale;+ return { contours };+ });+ const os2 = font.tables.os2 as+ | { sCapHeight?: number; sxHeight?: number }+ | undefined;+ const em = (v: number | undefined, fallback: number) =>+ ((v ?? fallback * font.unitsPerEm) * fontSize) / font.unitsPerEm;+ return {+ letters,+ width: x,+ capHeight: em(os2?.sCapHeight, 0.7),+ xHeight: em(os2?.sxHeight, 0.5),+ descender: (-font.descender * fontSize) / font.unitsPerEm,+ };+}++const fontCache = new Map<string, Promise<Font>>();++function loadAnatomyFont(url: string) {+ let pending = fontCache.get(url);+ if (!pending) {+ pending = fetch(url)+ .then((res) => res.arrayBuffer())+ .then((buffer) => parse(buffer));+ fontCache.set(url, pending);+ pending.catch(() => fontCache.delete(url));+ }+ return pending;+}++function useAnatomyFont(url: string) {+ const [font, setFont] = useState<Font | null>(null);++ useEffect(() => {+ const handle = delayRender(`glyph-anatomy: loading ${url}`);+ let released = false;+ const release = () => {+ if (released) return;+ released = true;+ continueRender(handle);+ };+ loadAnatomyFont(url).then((parsed) => {+ if (!released) setFont(parsed);+ release();+ }, release);+ return release;+ }, [url]);++ return font;+}++export function GlyphAnatomy({+ text = glyphAnatomyDefaults.text,+ fontUrl = glyphAnatomyDefaults.fontUrl,+ fontSize = glyphAnatomyDefaults.fontSize,+ color = glyphAnatomyDefaults.color,+ guideColor = glyphAnatomyDefaults.guideColor,+ guides = glyphAnatomyDefaults.guides,+ keepPoints = glyphAnatomyDefaults.keepPoints,+ speed = glyphAnatomyDefaults.speed,+ className,+}: GlyphAnatomyProps) {+ const frame = useCurrentFrame();+ const { fps, width, height } = useVideoConfig();+ const font = useAnatomyFont(fontUrl);+ if (!font) return null;++ const unit = height / 720;+ const t = getGlyphAnatomyTime(frame, { fps, speed });+ const word = layout(font, text, fontSize);+ const originX = (width - word.width * unit) / 2;+ const baseline = (height + word.capHeight * unit) / 2;+ const hair = 1.25;+ const anchorSize = 6;+ const handleRadius = 2.6;+ const margin = 0.3 * fontSize;+ // Guides fade with the last letter's scaffolding.+ const lastStart =+ glyphAnatomyTiming.letterStagger * Math.max(0, word.letters.length - 1);+ const scaffoldAll = keepPoints+ ? 1+ : getGlyphAnatomyLetter(t - lastStart).scaffold;++ const guideLines = [+ { label: "Cap height", y: -word.capHeight },+ { label: "x-height", y: -word.xHeight },+ { label: "Baseline", y: 0 },+ { label: "Descender", y: word.descender },+ ];++ return (+ <div+ className={className}+ style={{ position: "absolute", inset: 0, overflow: "hidden" }}+ >+ <svg+ width="100%"+ height="100%"+ viewBox={`0 0 ${width} ${height}`}+ style={{ display: "block" }}+ >+ <g transform={`translate(${originX} ${baseline}) scale(${unit})`}>+ {guides+ ? guideLines.map((guide, i) => {+ const draw = getGlyphAnatomyGuide(t, i);+ if (draw <= 0) return null;+ const length = word.width + 2 * margin;+ return (+ <g key={guide.label} opacity={0.7 * scaffoldAll}>+ <line+ x1={-margin}+ x2={-margin + length * draw}+ y1={guide.y}+ y2={guide.y}+ stroke={guideColor}+ strokeWidth={hair * 0.8}+ />+ <text+ x={-margin}+ y={guide.y - 5}+ fill={guideColor}+ fontFamily={INTER}+ fontSize={11}+ fontWeight={500}+ opacity={draw}+ >+ {guide.label}+ </text>+ </g>+ );+ })+ : null}+ {word.letters.map((letter, i) => {+ const lt = t - glyphAnatomyTiming.letterStagger * i;+ const state = getGlyphAnatomyLetter(lt);+ const scaffold = keepPoints ? 1 : state.scaffold;+ const curves = letter.contours.flatMap((segments, c) =>+ segments.flatMap((s, k) => (s.c1 ? [`${c}:${k}`] : [])),+ );+ const curveOrder = new Map(curves.map((key, n) => [key, n]));+ const anchors = letter.contours.flatMap((segments) =>+ segments.map((s) => s.from),+ );+ const pullOf = (c: number) => (k: number) =>+ getGlyphAnatomyPull(+ lt,+ curveOrder.get(`${c}:${k}`) ?? 0,+ curves.length,+ );+ const paths = letter.contours.map((segments, c) =>+ getAnatomyPath(segments, pullOf(c)),+ );+ let anchorIndex = 0;+ return (+ <g key={i}>+ {state.fill > 0 ? (+ <path d={paths.join("")} fill={color} opacity={state.fill} />+ ) : null}+ {state.outline > 0 && scaffold > 0 ? (+ <g opacity={scaffold}>+ {paths.map((d, c) => (+ <path+ key={c}+ d={d}+ fill="none"+ stroke={color}+ strokeWidth={hair}+ opacity={state.outline}+ />+ ))}+ {letter.contours.map((segments, c) =>+ segments.map((s, k) => {+ if (!s.c1 || !s.c2) return null;+ const pull = pullOf(c)(k);+ if (pull <= 0) return null;+ const h1 = lerp(s.from, s.c1, pull);+ const h2 = lerp(s.to, s.c2, pull);+ return (+ <g key={`${c}-${k}`}>+ <line+ x1={s.from.x}+ y1={s.from.y}+ x2={h1.x}+ y2={h1.y}+ stroke={guideColor}+ strokeWidth={hair * 0.8}+ />+ <line+ x1={s.to.x}+ y1={s.to.y}+ x2={h2.x}+ y2={h2.y}+ stroke={guideColor}+ strokeWidth={hair * 0.8}+ />+ <circle+ cx={h1.x}+ cy={h1.y}+ r={handleRadius}+ fill={guideColor}+ />+ <circle+ cx={h2.x}+ cy={h2.y}+ r={handleRadius}+ fill={guideColor}+ />+ </g>+ );+ }),+ )}+ {letter.contours.map((segments, c) =>+ segments.map((s, k) => {+ const scale = getGlyphAnatomyAnchor(+ lt,+ anchorIndex++,+ anchors.length,+ );+ if (scale <= 0) return null;+ const size = anchorSize * scale;+ return (+ <rect+ key={`${c}-${k}`}+ x={s.from.x - size / 2}+ y={s.from.y - size / 2}+ width={size}+ height={size}+ fill="#ffffff"+ stroke={guideColor}+ strokeWidth={hair}+ />+ );+ }),+ )}+ </g>+ ) : null}+ </g>+ );+ })}+ </g>+ </svg>+ </div>+ );+}diff --git a/registry/remocn/keystroke/__tests__/keystroke.test.ts b/registry/remocn/keystroke/__tests__/keystroke.test.tsnew file mode 100644index 00000000..77fe53b0--- /dev/null+++ b/registry/remocn/keystroke/__tests__/keystroke.test.ts@@ -0,0 +1,626 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getKeystrokeDepth,+ getKeystrokeDuration,+ getKeystrokeLayout,+ getKeystrokeLeadIn,+ getKeystrokeMetrics,+ getKeystrokePress,+ getKeystrokeRelease,+ getKeystrokeRise,+ getKeystrokeState,+ getKeystrokeTime,+ getKeystrokeTimeline,+ getKeystrokeWordUnits,+ type KeystrokeOptions,+ type KeystrokePlatform,+ keystrokeDefaultSteps,+ keystrokeDefaults,+ keystrokeLength,+ keystrokePalettes,+ parseKeystrokeKeys,+} from "..";+import { keystrokeConfig } from "../config";++type State = ReturnType<typeof getKeystrokeState>;++const frames = (from: number, to: number) =>+ Array.from({ length: to - from + 1 }, (_, i) => from + i);++const samples = (step: number, end: number) =>+ Array.from({ length: Math.round(end / step) + 1 }, (_, i) => i * step);++const legends = (keys: string, platform?: KeystrokePlatform) =>+ parseKeystrokeKeys(keys, platform).map((chord) =>+ chord.map(({ legend }) =>+ legend.kind === "icon" ? legend.icon : legend.text,+ ),+ );++const units = (keys: string, platform?: KeystrokePlatform) =>+ parseKeystrokeKeys(keys, platform)+ .flat()+ .map((key) => key.units);++const groupOf = (state: State, step: number) => {+ const group = state.groups.find((item) => item.step === step);+ if (!group) throw new Error(`step ${step} is not on screen`);+ return group;+};++const only = (keys: string, at = 40, hold?: number) => {+ const { groups } = getKeystrokeTimeline({ steps: [{ at, keys, hold }] });+ return groups[0];+};++describe("keystroke timeline", () => {+ it("fires every default step on its at frame and ends on the length", () => {+ const { groups, end } = getKeystrokeTimeline();+ expect(keystrokeLength).toBe(166);+ expect(end).toBe(keystrokeLength);+ expect(groups.map((group) => group.enter)).toEqual([7, 48, 98]);+ expect(groups.map((group) => group.timing.map((c) => c.fire))).toEqual([+ [20],+ [58, 78],+ [114],+ ]);+ expect(groups.map((group) => group.at)).toEqual(+ keystrokeDefaultSteps.map((step) => step.at),+ );+ expect(groups.map((group) => group.lastRelease)).toEqual([31, 86, 128]);+ expect(groups.map((group) => group.pushes)).toEqual([[48], [98], []]);+ expect(groups.map((group) => group.exit)).toEqual([61, 116, 158]);+ expect(groups.map((group) => group.end)).toEqual([69, 124, 166]);+ expect(getKeystrokeDuration()).toBe(180);+ expect(keystrokeConfig.durationInFrames).toBe(getKeystrokeDuration());+ });++ it("scales the preview with speed, linger and frame rate", () => {+ expect(getKeystrokeDuration({ speed: 2 })).toBe(97);+ expect(getKeystrokeDuration({ speed: 0.5 })).toBe(346);+ expect(getKeystrokeDuration({ speed: 0 })).toBe(14);+ expect(getKeystrokeDuration({ linger: 0 })).toBe(150);+ expect(getKeystrokeDuration({ linger: 90 })).toBe(240);+ expect(getKeystrokeDuration({ steps: [] })).toBe(14);+ const single = { steps: [{ at: 20, keys: "mod+k" }] };+ expect(getKeystrokeDuration(single)).toBe(83);+ const doubled = {+ steps: [{ at: 40, keys: "mod+k", hold: 16 }],+ linger: 60,+ fps: 60,+ };+ expect(getKeystrokeDuration(doubled)).toBe(166);+ const resolve = keystrokeConfig.getDurationInFrames;+ expect(resolve?.({ speed: 2, linger: 0 })).toBe(82);+ expect(resolve?.({ speed: "fast", linger: "long" })).toBe(180);+ });++ it("schedules a chord backward from the frame it fires", () => {+ const group = only("shift+mod+p", 40, 10);+ const [chord] = group.timing;+ expect(chord.fire).toBe(40);+ expect(chord.keys.map((key) => key.press)).toEqual([31, 34, 37]);+ expect(chord.keys.map((key) => key.release)).toEqual([56, 53, 50]);+ expect(chord.enter).toBe(24);+ expect(group.lastRelease).toBe(56);+ expect(getKeystrokeLeadIn("enter")).toBe(10);+ expect(getKeystrokeLeadIn("mod+k")).toBe(13);+ expect(getKeystrokeLeadIn("shift+mod+p")).toBe(16);+ expect(getKeystrokeLeadIn("g i")).toBe(30);+ expect(getKeystrokeLeadIn("g i", 20)).toBe(42);+ expect(getKeystrokeLeadIn("")).toBe(0);+ });++ it("chains the chords of a sequence and fires on the last one", () => {+ const group = only("g i", 60);+ expect(group.timing.map((chord) => chord.fire)).toEqual([40, 60]);+ expect(group.timing.map((chord) => chord.enter)).toEqual([30, 50]);+ expect(group.timing[1].enter).toBe(group.timing[0].keys[0].release + 2);+ expect(group.label).toBe("G then I");+ });++ it("drops invalid steps and orders groups by the frame they appear", () => {+ const { groups } = getKeystrokeTimeline({+ steps: [+ { at: 90, keys: "mod+s" },+ { at: Number.NaN, keys: "mod+k" },+ { at: 30, keys: " " },+ { at: 40, keys: "mod+z", hold: -5 },+ ],+ });+ expect(groups.map((group) => group.keys)).toEqual(["mod+z", "mod+s"]);+ expect(groups.map((group) => group.step)).toEqual([3, 0]);+ expect(groups.map((group) => group.index)).toEqual([0, 1]);+ expect(groups[0].hold).toBe(0);+ expect(getKeystrokeTimeline({ steps: [] })).toEqual({+ platform: "mac",+ linger: 30,+ groups: [],+ end: 0,+ });+ });+});++describe("keystroke press", () => {+ it("goes down in three eased frames and holds exactly at the bottom", () => {+ expect(getKeystrokePress(0)).toBe(0);+ expect(getKeystrokePress(1)).toBeCloseTo(7 / 27, 6);+ expect(getKeystrokePress(2)).toBeCloseTo(20 / 27, 6);+ expect(getKeystrokePress(3)).toBe(1);+ expect(getKeystrokePress(40)).toBe(1);+ expect(getKeystrokePress(-2)).toBe(0);+ expect(getKeystrokePress(Number.NaN)).toBe(0);+ const curve = samples(0.01, 3).map(getKeystrokePress);+ for (let i = 1; i < curve.length; i++) {+ expect(curve[i]).toBeGreaterThan(curve[i - 1]);+ }+ const steps = curve.slice(1).map((value, i) => value - curve[i]);+ expect(steps[0]).toBeLessThan(steps[150]);+ expect(steps[steps.length - 1]).toBeLessThan(steps[150]);+ });++ it("springs back up with a capped overshoot and lands on rest", () => {+ expect(getKeystrokeRelease(0)).toBe(0);+ expect(getKeystrokeRelease(-1)).toBe(0);+ expect(getKeystrokeRelease(Number.NaN)).toBe(0);+ expect(getKeystrokeRelease(3)).toBeCloseTo(1, 6);+ expect(getKeystrokeRelease(10)).toBe(1);+ expect(getKeystrokeRelease(60)).toBe(1);+ const curve = samples(0.01, 10).map(getKeystrokeRelease);+ const peak = Math.max(...curve);+ expect(peak).toBeGreaterThan(1.15);+ expect(peak).toBeLessThan(1.22);+ for (let i = 1; i <= 300; i++) {+ expect(curve[i]).toBeGreaterThan(curve[i - 1]);+ }+ const after = curve.slice(curve.indexOf(peak));+ expect(Math.min(...after)).toBeGreaterThan(0.98);+ expect(Math.abs(curve[999] - 1)).toBeLessThan(0.001);+ });++ it("rises in with a small settle and lands on frame 10", () => {+ expect(getKeystrokeRise(0)).toBe(0);+ expect(getKeystrokeRise(4)).toBeCloseTo(1, 6);+ expect(getKeystrokeRise(10)).toBe(1);+ const curve = samples(0.01, 10).map(getKeystrokeRise);+ const peak = Math.max(...curve);+ expect(peak).toBeGreaterThan(1.05);+ expect(peak).toBeLessThan(1.08);+ for (let i = 1; i <= 400; i++) {+ expect(curve[i]).toBeGreaterThan(curve[i - 1]);+ }+ expect(Math.min(...curve.slice(curve.indexOf(peak)))).toBeGreaterThan(0.99);+ });++ it("keeps the modifiers down while the trigger taps", () => {+ for (const keys of ["mod+k", "shift+mod+p", "ctrl+alt+shift+delete"]) {+ const [chord] = only(keys).timing;+ const trigger = chord.keys[chord.keys.length - 1];+ expect(getKeystrokeDepth(chord.fire, trigger)).toBe(1);+ expect(getKeystrokeDepth(chord.fire - 0.5, trigger)).toBeLessThan(1);+ for (const [i, key] of chord.keys.entries()) {+ if (i > 0) {+ expect(key.press - chord.keys[i - 1].press).toBe(3);+ expect(chord.keys[i - 1].release - key.release).toBe(3);+ }+ for (const later of chord.keys.slice(i + 1)) {+ for (const offset of samples(0.25, later.release - later.press)) {+ expect(getKeystrokeDepth(later.press + offset, key)).toBe(1);+ }+ }+ }+ }+ });++ it("shortens the wall, tightens the shadow and lights the legend", () => {+ const caps = (frame: number) => getKeystrokeState(frame).groups[0].caps;+ const [rest] = caps(14);+ const [command, key] = caps(20);+ expect(rest.depth).toBe(0);+ expect(rest.lift).toBe(0);+ expect(rest.wall).toBeCloseTo(64 * 0.16, 3);+ expect(command.depth).toBe(1);+ expect(key.depth).toBe(1);+ expect(command.lift).toBeCloseTo(64 * 0.12, 3);+ expect(command.wall).toBeCloseTo(64 * 0.04, 3);+ expect(command.shadowY).toBeLessThan(rest.shadowY);+ expect(command.shadowBlur).toBeLessThan(rest.shadowBlur);+ expect(rest.color).toBe(keystrokePalettes.light.ink);+ expect(command.color).toBe(keystrokeDefaults.accent);+ expect(caps(16)[0].color).toMatch(+ /^color-mix\(in srgb, #0a84ff \d+%, #1d1d1f\)$/,+ );+ const [, overshoot] = caps(33);+ expect(overshoot.depth).toBeLessThan(-0.15);+ expect(overshoot.wall).toBeGreaterThan(rest.wall);+ expect(overshoot.shadowY).toBeGreaterThan(rest.shadowY);+ expect(overshoot.color).toBe(keystrokePalettes.light.ink);+ for (const frame of frames(34, 47)) {+ for (const cap of caps(frame)) {+ expect(cap.depth).toBeLessThan(1);+ if (cap.depth < 0.01) {+ expect(cap.color).toBe(keystrokePalettes.light.ink);+ }+ }+ }+ });+});++describe("keystroke sequence", () => {+ it("adds a separator, re-centers the row and dims the earlier chord", () => {+ const before = groupOf(getKeystrokeState(66), 1);+ expect(before.caps.map((cap) => cap.key.label)).toEqual(["G"]);+ expect(before.separators).toEqual([]);+ expect(before.width).toBe(64);+ const settled = groupOf(getKeystrokeState(80), 1);+ expect(settled.caps.map((cap) => cap.key.label)).toEqual(["G", "I"]);+ expect(settled.separators).toHaveLength(1);+ expect(settled.width).toBeCloseTo(2.95 * 64, 3);+ const [first, last] = settled.caps;+ expect(first.x + last.x + last.width).toBeCloseTo(0, 3);+ expect(settled.separators[0].x).toBeCloseTo(first.x + 64, 3);+ expect(first.opacity).toBeCloseTo(0.45, 3);+ expect(last.opacity).toBe(1);+ let previous = Number.POSITIVE_INFINITY;+ for (const frame of frames(68, 78)) {+ const [g] = groupOf(getKeystrokeState(frame), 1).caps;+ expect(g.x).toBeLessThanOrEqual(previous);+ previous = g.x;+ }+ const dims = frames(72, 78).map(+ (frame) => groupOf(getKeystrokeState(frame), 1).caps[0].opacity,+ );+ expect(dims[0]).toBe(1);+ for (let i = 1; i < dims.length; i++) {+ expect(dims[i]).toBeLessThan(dims[i - 1]);+ }+ expect(dims[dims.length - 1]).toBeCloseTo(0.45, 3);+ });+});++describe("keystroke stack", () => {+ it("keeps at most two groups on screen, newest in front", () => {+ for (const frame of frames(0, 200)) {+ const { groups } = getKeystrokeState(frame);+ expect(groups.length).toBeLessThanOrEqual(2);+ if (groups.length < 2) continue;+ const [back, front] = groups;+ expect(back.index).toBeLessThan(front.index);+ expect(front.slot).toBe(0);+ expect(back.slot).toBeGreaterThan(0);+ expect(back.y).toBeLessThan(0);+ expect(back.scale).toBeLessThan(1);+ }+ });++ it("parks a pushed group one slot above the front row", () => {+ const [pushed] = getKeystrokeState(60).groups;+ expect(pushed.step).toBe(0);+ expect(pushed.slot).toBe(1);+ expect(pushed.scale).toBeCloseTo(0.86, 3);+ expect(pushed.opacity).toBeCloseTo(0.55, 3);+ expect(pushed.y).toBeCloseTo(-1.09 * 64, 2);+ const bottom = pushed.y + (64 / 2) * pushed.scale;+ expect(bottom).toBeCloseTo(-32 - 0.16 * 64, 2);+ });++ it("leaves after its linger, soon after a push, or on a third", () => {+ const linger = getKeystrokeTimeline({+ steps: [{ at: 20, keys: "mod+k" }],+ linger: 45,+ });+ expect(linger.groups[0].exit).toBe(31 + 45);+ const brief = getKeystrokeTimeline({+ steps: [+ { at: 20, keys: "mod+k" },+ { at: 50, keys: "mod+s" },+ ],+ linger: 60,+ });+ expect(brief.groups[0].pushes).toEqual([37]);+ expect(brief.groups[0].exit).toBe(37 + 18);+ const pressed = getKeystrokeTimeline({+ steps: [+ { at: 20, keys: "mod+k" },+ { at: 40, keys: "mod+s" },+ ],+ linger: 60,+ });+ expect(pressed.groups[0].pushes).toEqual([27]);+ expect(pressed.groups[0].exit).toBe(31 + 18);+ const dense = getKeystrokeTimeline({+ steps: [+ { at: 20, keys: "mod+k" },+ { at: 30, keys: "mod+s" },+ { at: 40, keys: "mod+z" },+ ],+ });+ expect(dense.groups[0].pushes).toEqual([17, 27]);+ expect(dense.groups[0].exit).toBe(27);+ for (const time of samples(0.5, 120)) {+ const holding = dense.groups.filter(+ (group) => time > group.enter && time < group.exit,+ );+ expect(holding.length).toBeLessThanOrEqual(2);+ }+ const late = getKeystrokeTimeline({+ steps: [+ { at: 20, keys: "mod+k" },+ { at: 120, keys: "mod+s" },+ ],+ });+ expect(late.groups[0].pushes).toEqual([]);+ expect(late.groups[0].exit).toBe(61);+ });++ it("brings the keys of a pushed group up before it leaves", () => {+ const steps = [+ { at: 20, keys: "shift+mod+z", hold: 30 },+ { at: 36, keys: "mod+k" },+ ];+ const [held] = getKeystrokeTimeline({ steps }).groups;+ expect(held.pushes).toEqual([23]);+ expect(held.lastRelease).toBe(56);+ expect(held.exit).toBe(56 + 18);+ for (const frame of frames(50, 66)) {+ const back = groupOf(getKeystrokeState(frame, { steps }), 0);+ expect(back.slot).toBe(1);+ expect(back.opacity).toBeCloseTo(0.55, 3);+ }+ const settled = groupOf(getKeystrokeState(66, { steps }), 0);+ expect(settled.caps.map((cap) => cap.depth)).toEqual([0, 0, 0]);+ });++ it("sinks a front group and lifts a pushed group as it leaves", () => {+ const front = frames(159, 165).map(+ (frame) => getKeystrokeState(frame).groups[0],+ );+ for (const [i, group] of front.entries()) {+ expect(group.step).toBe(2);+ expect(group.y).toBeGreaterThan(0);+ if (i > 0) {+ expect(group.y).toBeGreaterThan(front[i - 1].y);+ expect(group.opacity).toBeLessThan(front[i - 1].opacity);+ }+ }+ const pushed = frames(62, 68).map(+ (frame) => getKeystrokeState(frame).groups[0],+ );+ for (const [i, group] of pushed.entries()) {+ expect(group.step).toBe(0);+ if (i > 0) {+ expect(group.y).toBeLessThan(pushed[i - 1].y);+ expect(group.opacity).toBeLessThan(pushed[i - 1].opacity);+ }+ }+ const after = getKeystrokeState(69).groups.map((group) => group.step);+ expect(after).toEqual([1]);+ expect(getKeystrokeState(166).groups).toEqual([]);+ });+});++describe("keystroke keys", () => {+ it("resolves mod and draws glyphs on mac and words on windows", () => {+ expect(legends("mod+k")).toEqual([["command", "K"]]);+ expect(legends("mod+k", "windows")).toEqual([["Ctrl", "K"]]);+ expect(legends("shift+mod+p")).toEqual([["shift", "command", "P"]]);+ expect(legends("shift+mod+p", "windows")).toEqual([["Ctrl", "Shift", "P"]]);+ expect(legends("enter")).toEqual([["return"]]);+ expect(legends("return", "windows")).toEqual([["Enter"]]);+ expect(legends("mod+backspace")).toEqual([["command", "delete"]]);+ expect(legends("esc tab space")).toEqual([["escape"], ["tab"], ["space"]]);+ expect(legends("esc tab space", "windows")).toEqual([+ ["Esc"],+ ["Tab"],+ ["Space"],+ ]);+ expect(legends("up down left right", "windows")).toEqual([+ ["up"],+ ["down"],+ ["left"],+ ["right"],+ ]);+ const [[command]] = parseKeystrokeKeys("cmd");+ expect(command).toEqual({+ name: "meta",+ label: "Command",+ legend: { kind: "icon", icon: "command" },+ units: 1,+ modifier: true,+ });+ });++ it("orders modifiers the platform way and collapses duplicates", () => {+ expect(legends("mod+cmd+k")).toEqual([["command", "K"]]);+ expect(legends("cmd+option+control+esc")).toEqual([+ ["control", "option", "command", "escape"],+ ]);+ expect(legends("fn+cmd+shift+alt+ctrl+a")).toEqual([+ ["fn", "control", "option", "shift", "command", "A"],+ ]);+ expect(legends("shift+alt+ctrl+meta+x", "windows")).toEqual([+ ["Win", "Ctrl", "Alt", "Shift", "X"],+ ]);+ expect(legends("Mod+Shift+Enter")).toEqual([+ ["shift", "command", "return"],+ ]);+ });++ it("splits sequences on spaces and reads plus and named characters", () => {+ expect(legends("g i")).toEqual([["G"], ["I"]]);+ expect(legends(" g i ")).toEqual([["G"], ["I"]]);+ expect(legends("mod++")).toEqual([["command", "+"]]);+ expect(legends("mod+plus")).toEqual([["command", "+"]]);+ expect(legends("+")).toEqual([["+"]]);+ expect(legends("mod+slash shift+comma")).toEqual([+ ["command", "/"],+ ["shift", ","],+ ]);+ expect(legends("f5 fn+f12")).toEqual([["F5"], ["fn", "F12"]]);+ expect(legends("")).toEqual([]);+ expect(legends(" ")).toEqual([]);+ });++ it("makes shift, enter, space and windows words wider", () => {+ expect(units("shift+mod+p")).toEqual([1.5, 1, 1]);+ expect(units("mod+enter")).toEqual([1, 1.5]);+ expect(units("mod+space")).toEqual([1, 2.5]);+ expect(units("ctrl+alt+shift+enter", "windows")).toEqual([+ 1.25, 1.25, 1.5, 1.5,+ ]);+ expect(units("backspace", "windows")).toEqual([2]);+ expect(units("space", "windows")).toEqual([2.5]);+ for (const width of units("ctrl+alt+shift+esc+tab+delete", "windows")) {+ expect(width).toBeGreaterThan(1);+ }+ expect(getKeystrokeWordUnits("Ctrl")).toBe(1.25);+ expect(getKeystrokeWordUnits("fn")).toBe(1);+ expect(getKeystrokeWordUnits("Backspace")).toBe(2);+ });++ it("lays caps out left to right with a separator between chords", () => {+ const layout = getKeystrokeLayout(parseKeystrokeKeys("g shift+mod+p"));+ expect(layout.caps.map((cap) => cap.x)).toEqual([0, 1.95, 3.59, 4.73]);+ expect(layout.caps.map((cap) => cap.width)).toEqual([1, 1.5, 1, 1]);+ expect(layout.separators).toEqual([{ chord: 1, x: 1, width: 0.95 }]);+ expect(layout.widths).toEqual([1, 5.73]);+ });+});++describe("keystroke geometry", () => {+ it("sizes everything in reference px scaled by height / 720", () => {+ const base = getKeystrokeState(60);+ expect(base.originX).toBe(640);+ expect(base.originY).toBeCloseTo(619.2, 3);+ expect(base.metrics).toEqual(getKeystrokeMetrics(64));+ expect(base.metrics).toEqual({+ size: 64,+ height: 64,+ wall: 10.24,+ travel: 7.68,+ keytop: 53.76,+ radius: 10.24,+ rise: 26.88,+ border: 1,+ charFont: 25.6,+ wordFont: 16.64,+ icon: 23.04,+ separatorFont: 16,+ });+ const large = getKeystrokeState(60, { width: 1920, height: 1080 });+ expect(large.unit).toBe(1.5);+ expect(large.metrics.size).toBe(96);+ expect(large.metrics.border).toBe(1.5);+ for (const [g, group] of base.groups.entries()) {+ const other = large.groups[g];+ expect(other.y).toBeCloseTo(group.y * 1.5, 2);+ expect(other.width).toBeCloseTo(group.width * 1.5, 2);+ for (const [c, cap] of group.caps.entries()) {+ expect(other.caps[c].x).toBeCloseTo(cap.x * 1.5, 2);+ expect(other.caps[c].width).toBeCloseTo(cap.width * 1.5, 2);+ expect(other.caps[c].lift).toBeCloseTo(cap.lift * 1.5, 2);+ }+ }+ const small = getKeystrokeState(60, { size: 32 });+ expect(small.metrics.size).toBe(32);+ expect(small.groups[1].caps[0].width).toBe(32);+ });++ it("clamps size and falls back on invalid input", () => {+ const nan = Number.NaN;+ const broken = getKeystrokeState(60, {+ x: nan,+ y: nan,+ size: nan,+ linger: nan,+ speed: nan,+ fps: nan,+ width: nan,+ height: nan,+ accent: " ",+ });+ expect(broken).toEqual(getKeystrokeState(60));+ expect(getKeystrokeState(60, { size: 1 }).metrics.size).toBe(8);+ expect(getKeystrokeState(60, { size: 9000 }).metrics.size).toBe(400);+ const dark = getKeystrokeState(20, { theme: "dark", accent: "#ff6a00" });+ expect(dark.palette).toEqual(keystrokePalettes.dark);+ expect(dark.groups[0].caps[1].color).toBe("#ff6a00");+ });+});++describe("keystroke determinism", () => {+ it("renders any frame identically in any sampling order", () => {+ const options: KeystrokeOptions = {+ platform: "windows",+ theme: "dark",+ steps: [+ { at: 24, keys: "mod+shift+k" },+ { at: 70, keys: "g p", hold: 12 },+ { at: 96, keys: "alt+up" },+ ],+ };+ const sample = (frame: number) => getKeystrokeState(frame, options);+ const order = [0, 12, 20, 33, 49, 70, 81, 99, 130, 160];+ const forward = order.map(sample);+ const backward = [...order].reverse().map(sample).reverse();+ expect(backward).toEqual(forward);+ expect(sample(81)).toEqual(forward[6]);+ });++ it("maps other frame rates and speeds onto the same timeline", () => {+ const base = getKeystrokeState(50);+ expect(getKeystrokeState(100, { speed: 0.5 })).toEqual(base);+ const doubled = {+ steps: keystrokeDefaultSteps.map((step) => ({+ ...step,+ at: step.at * 2,+ hold: 16,+ })),+ linger: 60,+ fps: 60,+ };+ expect(getKeystrokeState(100, doubled)).toEqual(base);+ for (const frame of [0, 40, 90, 400]) {+ expect(getKeystrokeState(frame, { speed: 0 }).groups).toEqual([]);+ }+ expect(getKeystrokeTime(12, { speed: 2 })).toBe(24);+ expect(getKeystrokeTime(20, { fps: 60, speed: 0.5 })).toBe(5);+ expect(getKeystrokeTime(-5)).toBe(0);+ expect(getKeystrokeTime(Number.NaN)).toBe(0);+ });++ it("bottoms out on the frame a remocn-ui step with that at fires", () => {+ for (const speed of [0.5, 1, 2]) {+ for (const [step, { at }] of keystrokeDefaultSteps.entries()) {+ const trigger = (frame: number) =>+ groupOf(getKeystrokeState(frame, { speed }), step).caps.at(-1);+ expect(trigger(at / speed)?.depth).toBe(1);+ expect(trigger(at / speed - 1)?.depth).toBeLessThan(1);+ }+ }+ });+});++describe("keystroke config", () => {+ it("matches the component defaults and exposes every option", () => {+ const controls = resolveControls("keystroke", keystrokeConfig.controls);+ expect(getDefaults(controls)).toEqual(keystrokeDefaults);+ expect(keystrokeConfig.componentName).toBe("Keystroke");+ expect(keystrokeConfig.importPath).toBe("@/components/remocn/keystroke");+ const options = (key: string) => {+ const control = controls[key];+ return control.type === "select" ? control.options : [];+ };+ expect(options("platform")).toEqual(["mac", "windows"]);+ expect(options("theme")).toEqual(["light", "dark"]);+ const range = (key: string) => {+ const control = controls[key];+ return control.type === "number" ? [control.min, control.max] : [];+ };+ expect(range("size")).toEqual([32, 128]);+ expect(range("linger")).toEqual([0, 90]);+ expect(range("x")).toEqual([0, 1]);+ expect(range("y")).toEqual([0, 1]);+ });+});diff --git a/registry/remocn/keystroke/config.ts b/registry/remocn/keystroke/config.tsnew file mode 100644index 00000000..30772d91--- /dev/null+++ b/registry/remocn/keystroke/config.ts@@ -0,0 +1,74 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";+import { getKeystrokeDuration } from ".";++const numberOf = (value: unknown) =>+ typeof value === "number" ? value : undefined;++function durationOf(values: Record<string, unknown>) {+ return getKeystrokeDuration({+ linger: numberOf(values.linger),+ speed: numberOf(values.speed),+ });+}++export const keystrokeConfig: ComponentConfig = {+ componentName: "Keystroke",+ importPath: "@/components/remocn/keystroke",+ controls: {+ platform: {+ type: "enum",+ default: "mac",+ variants: { mac: {}, windows: {} },+ description: "Platform",+ },+ theme: {+ type: "enum",+ default: "light",+ variants: { light: {}, dark: {} },+ description: "Theme",+ },+ accent: { type: "color", default: "#0a84ff", description: "Accent" },+ size: {+ type: "number",+ default: 64,+ min: 32,+ max: 128,+ step: 1,+ description: "Key size",+ hiddenFromList: false,+ },+ linger: {+ type: "number",+ default: 30,+ min: 0,+ max: 90,+ step: 1,+ description: "Linger",+ hiddenFromList: false,+ },+ x: {+ type: "number",+ default: 0.5,+ min: 0,+ max: 1,+ step: 0.01,+ description: "Center x",+ hiddenFromList: false,+ },+ y: {+ type: "number",+ default: 0.86,+ min: 0,+ max: 1,+ step: 0.01,+ description: "Center y",+ hiddenFromList: false,+ },+ },+ durationInFrames: 180,+ getDurationInFrames: durationOf,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#e9e9e5" },+};diff --git a/registry/remocn/keystroke/index.tsx b/registry/remocn/keystroke/index.tsxnew file mode 100644index 00000000..b3f8bdd4--- /dev/null+++ b/registry/remocn/keystroke/index.tsx@@ -0,0 +1,1037 @@+"use client";++import { useMemo } from "react";+import { Easing, useCurrentFrame, useVideoConfig } from "remotion";++export type KeystrokePlatform = "mac" | "windows";+export type KeystrokeTheme = "light" | "dark";+export type KeystrokeIcon =+ | "command"+ | "option"+ | "shift"+ | "control"+ | "return"+ | "delete"+ | "escape"+ | "tab"+ | "space"+ | "capsLock"+ | "up"+ | "down"+ | "left"+ | "right";++export interface KeystrokeStep {+ at: number;+ keys: string;+ hold?: number;+}++export interface KeystrokeProps {+ steps?: readonly KeystrokeStep[];+ platform?: KeystrokePlatform;+ theme?: KeystrokeTheme;+ accent?: string;+ x?: number;+ y?: number;+ size?: number;+ linger?: number;+ speed?: number;+ className?: string;+}++export interface KeystrokeOptions extends Omit<KeystrokeProps, "className"> {+ width?: number;+ height?: number;+ fps?: number;+}++export type KeystrokeLegend =+ | { kind: "icon"; icon: KeystrokeIcon }+ | { kind: "char"; text: string }+ | { kind: "word"; text: string };++export interface KeystrokeKey {+ name: string;+ label: string;+ legend: KeystrokeLegend;+ units: number;+ modifier: boolean;+}++export type KeystrokeChord = KeystrokeKey[];++export interface KeystrokeKeyTiming {+ press: number;+ release: number;+}++export interface KeystrokeChordTiming {+ enter: number;+ fire: number;+ keys: KeystrokeKeyTiming[];+}++export interface KeystrokeLayout {+ caps: { chord: number; index: number; x: number; width: number }[];+ separators: { chord: number; x: number; width: number }[];+ widths: number[];+}++export interface KeystrokeGroup {+ index: number;+ step: number;+ keys: string;+ label: string;+ chords: KeystrokeChord[];+ timing: KeystrokeChordTiming[];+ layout: KeystrokeLayout;+ at: number;+ hold: number;+ enter: number;+ lastRelease: number;+ pushes: number[];+ exit: number;+ end: number;+}++export interface KeystrokePalette {+ cap: string;+ edge: string;+ wall: string;+ ink: string;+ separator: string;+ shadow: string;+}++type Unset = "steps" | "className";+type Modifier = "fn" | "ctrl" | "alt" | "shift" | "meta";+type Named =+ | "enter"+ | "escape"+ | "tab"+ | "space"+ | "backspace"+ | "delete"+ | "capsLock"+ | "up"+ | "down"+ | "left"+ | "right"+ | "home"+ | "end"+ | "pageUp"+ | "pageDown";+type IconShape = { box: string; paths: readonly string[] };+type IconSpec = { label: string; icon: KeystrokeIcon; units: number };+type NamedSpec = IconSpec | { label: string; word: string; units: number };+type Draft = Omit<+ KeystrokeGroup,+ "index" | "label" | "layout" | "pushes" | "exit" | "end"+>;++export const keystrokeDefaults: Required<Omit<KeystrokeProps, Unset>> = {+ platform: "mac",+ theme: "light",+ accent: "#0a84ff",+ x: 0.5,+ y: 0.86,+ size: 64,+ linger: 30,+ speed: 1,+};++export const keystrokeDefaultSteps: readonly KeystrokeStep[] = [+ { at: 20, keys: "mod+k" },+ { at: 78, keys: "g i" },+ { at: 114, keys: "shift+mod+p" },+];++export const keystrokePalettes: Record<KeystrokeTheme, KeystrokePalette> = {+ light: {+ cap: "#fcfcfb",+ edge: "#dfdfda",+ wall: "#cfcfca",+ ink: "#1d1d1f",+ separator: "#8e8e89",+ shadow: "rgba(20, 20, 16, 0.18)",+ },+ dark: {+ cap: "#38393e",+ edge: "#48494f",+ wall: "#1f2023",+ ink: "#f5f5f7",+ separator: "#9d9da4",+ shadow: "rgba(0, 0, 0, 0.5)",+ },+};++const PRESS = 3;+const PRESS_GAP = 3;+const RELEASE_GAP = 3;+const LEAD = 7;+const STAGGER = 1;+const BEAT = 2;+const HOLD = 8;+const RELEASE = 10;+const RELEASE_RISE = 3;+const RELEASE_TAPER = 6;+const RELEASE_DAMPING = 0.46;+const ENTER = 10;+const ENTER_RISE = 4;+const ENTER_TAPER = 7;+const ENTER_DAMPING = 0.65;+const FADE_IN = 4;+const SLIDE = 10;+const DIM = 6;+const DIM_OPACITY = 0.45;+const PUSH = 10;+const BRIEF = 18;+const EXIT = 8;+const TAIL = 14;+const MAX_FRAMES = 600;+const MIN_SIZE = 8;+const MAX_SIZE = 400;+const WALL = 0.16;+const TRAVEL = 0.12;+const RADIUS = 0.16;+const RISE = 0.42;+const KEY_GAP = 0.14;+const SEPARATOR = 0.95;+const CHAR_FONT = 0.4;+const WORD_FONT = 0.26;+const ICON_SIZE = 0.36;+const SEPARATOR_FONT = 0.25;+const WORD_CHAR = 0.6 * WORD_FONT;+const WORD_PAD = 0.24;+const WINDOWS_WORD = 1.25;+const SLOT_RISE = 1.09;+const SLOT_SCALE = 0.86;+const SLOT_OPACITY = 0.55;+const EXIT_DRIFT = 0.22;+const EXIT_SCALE = 0.04;+const SHADOW_Y = 0.07;+const SHADOW_Y_PRESSED = 0.02;+const SHADOW_BLUR = 0.11;+const SHADOW_BLUR_PRESSED = 0.03;+const GLIDE = Easing.bezier(0.33, 1, 0.68, 1);+const FONT_FAMILY =+ 'var(--font-geist-sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, Helvetica, Arial, sans-serif)';++const ICONS: Record<KeystrokeIcon, IconShape> = {+ command: {+ box: "0 0 24 24",+ paths: [+ "M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",+ ],+ },+ option: { box: "0 0 24 24", paths: ["M3 3h6l6 18h6", "M14 3h7"] },+ shift: {+ box: "0 0 24 24",+ paths: [+ "M9 19a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1v-6a1 1 0 0 1 1-1h3.293a.707.707 0 0 0 .5-1.207l-7.086-7.086a1 1 0 0 0-1.414 0l-7.086 7.086a.707.707 0 0 0 .5 1.207H8a1 1 0 0 1 1 1z",+ ],+ },+ control: { box: "0 0 24 24", paths: ["m18 15-6-6-6 6"] },+ return: {+ box: "0 0 24 24",+ paths: ["M20 4v7a4 4 0 0 1-4 4H4", "m9 10-5 5 5 5"],+ },+ delete: {+ box: "0 0 24 24",+ paths: [+ "M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z",+ "m12 9 6 6",+ "m18 9-6 6",+ ],+ },+ escape: {+ box: "0 0 24 24",+ paths: ["M2 8V2h6", "m2 2 10 10", "M12 2A10 10 0 1 1 2 12"],+ },+ tab: {+ box: "0 0 24 24",+ paths: ["M17 12H3", "m11 18 6-6-6-6", "M21 5v14"],+ },+ space: {+ box: "0 6 24 24",+ paths: ["M22 17v1c0 .5-.5 1-1 1H3c-.5 0-1-.5-1-1v-1"],+ },+ capsLock: {+ box: "0 0 24 24",+ paths: [+ "M14 16a1 1 0 0 0 1-1v-2a1 1 0 0 1 1-1h3.293a.707.707 0 0 0 .5-1.207l-6.939-6.939a1.207 1.207 0 0 0-1.708 0l-6.94 6.94a.707.707 0 0 0 .5 1.206H8a1 1 0 0 1 1 1v2a1 1 0 0 0 1 1z",+ "M9 20h6",+ ],+ },+ up: { box: "0 0 24 24", paths: ["m5 12 7-7 7 7", "M12 19V5"] },+ down: { box: "0 0 24 24", paths: ["M12 5v14", "m19 12-7 7-7-7"] },+ left: { box: "0 0 24 24", paths: ["m12 19-7-7 7-7", "M19 12H5"] },+ right: { box: "0 0 24 24", paths: ["M5 12h14", "m12 5 7 7-7 7"] },+};++const MODIFIERS = new Map<string, Modifier>([+ ["fn", "fn"],+ ["ctrl", "ctrl"],+ ["control", "ctrl"],+ ["alt", "alt"],+ ["option", "alt"],+ ["opt", "alt"],+ ["shift", "shift"],+ ["cmd", "meta"],+ ["command", "meta"],+ ["meta", "meta"],+ ["win", "meta"],+ ["super", "meta"],+]);++const MODIFIER_ORDER: Record<KeystrokePlatform, readonly Modifier[]> = {+ mac: ["fn", "ctrl", "alt", "shift", "meta"],+ windows: ["fn", "meta", "ctrl", "alt", "shift"],+};++const MAC_MODIFIERS: Record<Exclude<Modifier, "fn">, IconSpec> = {+ ctrl: { label: "Control", icon: "control", units: 1 },+ alt: { label: "Option", icon: "option", units: 1 },+ shift: { label: "Shift", icon: "shift", units: 1.5 },+ meta: { label: "Command", icon: "command", units: 1 },+};++const WINDOWS_MODIFIERS: Record<Modifier, string> = {+ fn: "Fn",+ ctrl: "Ctrl",+ alt: "Alt",+ shift: "Shift",+ meta: "Win",+};++const NAMED = new Map<string, Named>([+ ["enter", "enter"],+ ["return", "enter"],+ ["esc", "escape"],+ ["escape", "escape"],+ ["tab", "tab"],+ ["space", "space"],+ ["backspace", "backspace"],+ ["delete", "delete"],+ ["del", "delete"],+ ["capslock", "capsLock"],+ ["up", "up"],+ ["arrowup", "up"],+ ["down", "down"],+ ["arrowdown", "down"],+ ["left", "left"],+ ["arrowleft", "left"],+ ["right", "right"],+ ["arrowright", "right"],+ ["home", "home"],+ ["end", "end"],+ ["pageup", "pageUp"],+ ["pgup", "pageUp"],+ ["pagedown", "pageDown"],+ ["pgdn", "pageDown"],+]);++const CHARACTERS = new Map<string, string>([+ ["plus", "+"],+ ["minus", "-"],+ ["comma", ","],+ ["period", "."],+ ["slash", "/"],+ ["backslash", "\\"],+ ["semicolon", ";"],+ ["quote", "'"],+ ["backquote", "`"],+ ["bracketleft", "["],+ ["bracketright", "]"],+ ["equal", "="],+]);++const ARROWS: Record<"up" | "down" | "left" | "right", IconSpec> = {+ up: { label: "Up Arrow", icon: "up", units: 1 },+ down: { label: "Down Arrow", icon: "down", units: 1 },+ left: { label: "Left Arrow", icon: "left", units: 1 },+ right: { label: "Right Arrow", icon: "right", units: 1 },+};++const NAMED_KEYS: Record<KeystrokePlatform, Record<Named, NamedSpec>> = {+ mac: {+ enter: { label: "Return", icon: "return", units: 1.5 },+ escape: { label: "Escape", icon: "escape", units: 1 },+ tab: { label: "Tab", icon: "tab", units: 1.25 },+ space: { label: "Space", icon: "space", units: 2.5 },+ backspace: { label: "Delete", icon: "delete", units: 1.25 },+ delete: { label: "Delete", icon: "delete", units: 1.25 },+ capsLock: { label: "Caps Lock", icon: "capsLock", units: 1.5 },+ ...ARROWS,+ home: { label: "Home", word: "home", units: 1 },+ end: { label: "End", word: "end", units: 1 },+ pageUp: { label: "Page Up", word: "page up", units: 1 },+ pageDown: { label: "Page Down", word: "page down", units: 1 },+ },+ windows: {+ enter: { label: "Enter", word: "Enter", units: WINDOWS_WORD },+ escape: { label: "Esc", word: "Esc", units: WINDOWS_WORD },+ tab: { label: "Tab", word: "Tab", units: WINDOWS_WORD },+ space: { label: "Space", word: "Space", units: 2.5 },+ backspace: { label: "Backspace", word: "Backspace", units: WINDOWS_WORD },+ delete: { label: "Delete", word: "Delete", units: WINDOWS_WORD },+ capsLock: { label: "Caps Lock", word: "Caps Lock", units: WINDOWS_WORD },+ ...ARROWS,+ home: { label: "Home", word: "Home", units: WINDOWS_WORD },+ end: { label: "End", word: "End", units: WINDOWS_WORD },+ pageUp: { label: "Page Up", word: "PgUp", units: WINDOWS_WORD },+ pageDown: { label: "Page Down", word: "PgDn", units: WINDOWS_WORD },+ },+};++const finite = (value: number | undefined, fallback: number) =>+ typeof value === "number" && Number.isFinite(value) ? value : fallback;+const clamp = (value: number, min: number, max: number) =>+ Math.min(max, Math.max(min, value));+const within = (+ value: number | undefined,+ fallback: number,+ min: number,+ max: number,+) => clamp(finite(value, fallback), min, max);+const round = (value: number) => Math.round(value * 1000) / 1000 + 0;+const smoothstep = (value: number) => {+ const t = clamp(value, 0, 1);+ return t * t * (3 - 2 * t);+};+const fpsOf = (fps: number | undefined) => Math.max(1, finite(fps, 30));+const rateOf = (speed: number | undefined) =>+ Math.max(0, finite(speed, keystrokeDefaults.speed));+const platformOf = (value: string | undefined): KeystrokePlatform =>+ value === "windows" ? value : "mac";+const themeOf = (value: string | undefined): KeystrokeTheme =>+ value === "dark" ? value : "light";+const accentOf = (value: string | undefined) =>+ typeof value === "string" && value.trim() !== ""+ ? value.trim()+ : keystrokeDefaults.accent;+const modOf = (platform: KeystrokePlatform): Modifier =>+ platform === "mac" ? "meta" : "ctrl";++function eased(frames: number, duration: number, curve: (t: number) => number) {+ if (Number.isNaN(frames) || frames <= 0) return 0;+ if (frames >= duration) return 1;+ return curve(frames / duration);+}++function settle(rise: number, damping: number, taper: number, end: number) {+ const frequency = (Math.PI - Math.acos(damping)) / rise;+ const ratio = damping / Math.sqrt(1 - damping ** 2);+ return (frames: number) => {+ if (Number.isNaN(frames) || frames <= 0) return 0;+ if (frames >= end) return 1;+ const phase = frequency * frames;+ const decay = Math.exp(-ratio * phase);+ const ring = decay * (Math.cos(phase) + ratio * Math.sin(phase));+ return 1 - ring * (1 - smoothstep((frames - taper) / (end - taper)));+ };+}++const riseCurve = settle(ENTER_RISE, ENTER_DAMPING, ENTER_TAPER, ENTER);+const releaseCurve = settle(+ RELEASE_RISE,+ RELEASE_DAMPING,+ RELEASE_TAPER,+ RELEASE,+);++export function getKeystrokePress(frames: number) {+ return eased(frames, PRESS, smoothstep);+}++export function getKeystrokeRelease(frames: number) {+ return releaseCurve(frames);+}++export function getKeystrokeRise(frames: number) {+ return riseCurve(frames);+}++export function getKeystrokeDepth(time: number, timing: KeystrokeKeyTiming) {+ if (Number.isNaN(time) || time <= timing.press) return 0;+ if (time < timing.release) return getKeystrokePress(time - timing.press);+ const bottom = getKeystrokePress(timing.release - timing.press);+ return bottom * (1 - getKeystrokeRelease(time - timing.release));+}++export function getKeystrokeWordUnits(text: string, min = 1) {+ const raw = Array.from(text).length * WORD_CHAR + 2 * WORD_PAD;+ return Math.max(min, Math.ceil(raw * 4 - 1e-9) / 4);+}++function wordKey(+ name: string,+ label: string,+ text: string,+ platform: KeystrokePlatform,+ modifier: boolean,+ min = 1,+): KeystrokeKey {+ const floor = platform === "windows" ? Math.max(min, WINDOWS_WORD) : min;+ const units = getKeystrokeWordUnits(text, floor);+ return { name, label, legend: { kind: "word", text }, units, modifier };+}++function modifierKey(+ modifier: Modifier,+ platform: KeystrokePlatform,+): KeystrokeKey {+ if (platform === "windows") {+ const word = WINDOWS_MODIFIERS[modifier];+ return wordKey(modifier, word, word, platform, true);+ }+ if (modifier === "fn") return wordKey("fn", "Fn", "fn", platform, true);+ const { label, icon, units } = MAC_MODIFIERS[modifier];+ return {+ name: modifier,+ label,+ legend: { kind: "icon", icon },+ units,+ modifier: true,+ };+}++function namedKey(named: Named, platform: KeystrokePlatform): KeystrokeKey {+ const spec = NAMED_KEYS[platform][named];+ if ("word" in spec) {+ return wordKey(named, spec.label, spec.word, platform, false, spec.units);+ }+ return {+ name: named,+ label: spec.label,+ legend: { kind: "icon", icon: spec.icon },+ units: spec.units,+ modifier: false,+ };+}++function keyOf(part: string, platform: KeystrokePlatform): KeystrokeKey {+ const name = part.toLowerCase();+ const named = NAMED.get(name);+ if (named) return namedKey(named, platform);+ const character =+ CHARACTERS.get(name) ?? (Array.from(part).length === 1 ? part : undefined);+ if (character !== undefined) {+ const text = character.toUpperCase();+ return {+ name: character.toLowerCase(),+ label: text,+ legend: { kind: "char", text },+ units: 1,+ modifier: false,+ };+ }+ const fkey = /^f([1-9]|1\d|2[0-4])$/.exec(name);+ if (fkey) {+ const text = `F${fkey[1]}`;+ return wordKey(name, text, text, platform, false);+ }+ const text = `${part.charAt(0).toUpperCase()}${part.slice(1)}`;+ return wordKey(name, text, text, platform, false);+}++function splitChord(token: string) {+ const parts = token.split("+");+ const names: string[] = [];+ for (const [index, part] of parts.entries()) {+ if (part !== "") names.push(part);+ else if (index === parts.length - 1 && parts[index - 1] === "") {+ names.push("+");+ }+ }+ return names;+}++function parseChord(token: string, platform: KeystrokePlatform) {+ const held = new Set<Modifier>();+ const keys: KeystrokeKey[] = [];+ for (const part of splitChord(token)) {+ const name = part.toLowerCase();+ const modifier = name === "mod" ? modOf(platform) : MODIFIERS.get(name);+ if (modifier) held.add(modifier);+ else keys.push(keyOf(part, platform));+ }+ const modifiers = MODIFIER_ORDER[platform]+ .filter((modifier) => held.has(modifier))+ .map((modifier) => modifierKey(modifier, platform));+ return [...modifiers, ...keys];+}++export function parseKeystrokeKeys(+ keys: string,+ platform?: KeystrokePlatform,+): KeystrokeChord[] {+ if (typeof keys !== "string") return [];+ const target = platformOf(platform);+ return keys+ .trim()+ .split(/\s+/)+ .filter((token) => token !== "")+ .map((token) => parseChord(token, target))+ .filter((chord) => chord.length > 0);+}++export function getKeystrokeLayout(+ chords: readonly KeystrokeChord[],+): KeystrokeLayout {+ const layout: KeystrokeLayout = { caps: [], separators: [], widths: [] };+ let cursor = 0;+ for (const [chord, keys] of chords.entries()) {+ if (chord > 0) {+ layout.separators.push({ chord, x: round(cursor), width: SEPARATOR });+ cursor += SEPARATOR;+ }+ for (const [index, key] of keys.entries()) {+ if (index > 0) cursor += KEY_GAP;+ layout.caps.push({ chord, index, x: round(cursor), width: key.units });+ cursor += key.units;+ }+ layout.widths.push(round(cursor));+ }+ return layout;+}++function schedule(chords: readonly KeystrokeChord[], hold: number) {+ const timing: KeystrokeChordTiming[] = [];+ let enter = 0;+ for (const chord of chords) {+ const last = chord.length - 1;+ const fire = enter + LEAD + PRESS_GAP * last + PRESS;+ const keys = chord.map((_, index) => ({+ press: fire - PRESS - PRESS_GAP * (last - index),+ release: fire + hold + RELEASE_GAP * (last - index),+ }));+ timing.push({ enter, fire, keys });+ enter = fire + hold + RELEASE_GAP * last + BEAT;+ }+ return timing;+}++export function getKeystrokeLeadIn(keys: string, hold = HOLD) {+ const chords = parseKeystrokeKeys(keys);+ if (chords.length === 0) return 0;+ const timing = schedule(chords, within(hold, HOLD, 0, MAX_FRAMES));+ return timing[timing.length - 1].fire - timing[0].enter;+}++export function getKeystrokeTimeline(+ options: Pick<KeystrokeOptions, "steps" | "platform" | "linger" | "fps"> = {},+) {+ const platform = platformOf(options.platform);+ const scale = 30 / fpsOf(options.fps);+ const lingerFrames = within(+ options.linger,+ keystrokeDefaults.linger,+ 0,+ MAX_FRAMES,+ );+ const linger = lingerFrames * scale;+ const steps = options.steps ?? keystrokeDefaultSteps;+ const drafts: Draft[] = [];+ for (const [step, entry] of steps.entries()) {+ if (typeof entry.at !== "number" || !Number.isFinite(entry.at)) continue;+ const chords = parseKeystrokeKeys(entry.keys, platform);+ if (chords.length === 0) continue;+ const at = entry.at * scale;+ const hold = within(entry.hold, HOLD, 0, MAX_FRAMES) * scale;+ const planned = schedule(chords, hold);+ const offset = at - planned[planned.length - 1].fire;+ const timing = planned.map((chord) => ({+ enter: round(chord.enter + offset),+ fire: round(chord.fire + offset),+ keys: chord.keys.map((key) => ({+ press: round(key.press + offset),+ release: round(key.release + offset),+ })),+ }));+ const releases = timing.flatMap((chord) =>+ chord.keys.map((key) => key.release),+ );+ drafts.push({+ step,+ keys: entry.keys,+ chords,+ timing,+ at: round(at),+ hold: round(hold),+ enter: timing[0].enter,+ lastRelease: Math.max(...releases),+ });+ }+ drafts.sort((a, b) => a.enter - b.enter || a.at - b.at || a.step - b.step);+ const groups = drafts.map((draft, index): KeystrokeGroup => {+ const pushes: number[] = [];+ let exit = Math.max(draft.enter, draft.lastRelease + linger);+ for (const newer of drafts.slice(index + 1)) {+ if (newer.enter >= exit + EXIT) break;+ const at = Math.max(newer.enter, draft.enter);+ const brief = Math.max(at, draft.lastRelease) + BRIEF;+ pushes.push(at);+ exit = Math.min(exit, pushes.length === 1 ? brief : at);+ if (pushes.length === 2) break;+ }+ exit = round(Math.max(exit, draft.enter));+ const label = draft.chords+ .map((chord) => chord.map((key) => key.label).join(" "))+ .join(" then ");+ return {+ ...draft,+ index,+ label,+ layout: getKeystrokeLayout(draft.chords),+ pushes,+ exit,+ end: round(exit + EXIT),+ };+ });+ const end = groups.reduce((latest, group) => Math.max(latest, group.end), 0);+ return { platform, linger: round(linger), groups, end };+}++export type KeystrokeTimeline = ReturnType<typeof getKeystrokeTimeline>;++export const keystrokeLength = getKeystrokeTimeline().end;++export function getKeystrokeDuration(+ options: Pick<KeystrokeOptions, "steps" | "linger" | "speed" | "fps"> = {},+) {+ const fps = fpsOf(options.fps);+ const rate = rateOf(options.speed);+ const { end } = getKeystrokeTimeline(options);+ const motion = rate === 0 ? 0 : (end * fps) / 30 / rate;+ return Math.ceil(round(motion)) + Math.round((TAIL * fps) / 30);+}++export function getKeystrokeTime(+ frame: number,+ options: Pick<KeystrokeOptions, "fps" | "speed"> = {},+) {+ const elapsed = Math.max(0, finite(frame, 0));+ return (elapsed * rateOf(options.speed) * 30) / fpsOf(options.fps);+}++export function getKeystrokeMetrics(size: number, unit = 1) {+ return {+ size: round(size),+ height: round(size),+ wall: round(size * WALL),+ travel: round(size * TRAVEL),+ keytop: round(size * (1 - WALL)),+ radius: round(size * RADIUS),+ rise: round(size * RISE),+ border: round(Math.max(1, unit)),+ charFont: round(size * CHAR_FONT),+ wordFont: round(size * WORD_FONT),+ icon: round(size * ICON_SIZE),+ separatorFont: round(size * SEPARATOR_FONT),+ };+}++export type KeystrokeMetrics = ReturnType<typeof getKeystrokeMetrics>;++function legendColor(ink: string, accent: string, amount: number) {+ const share = Math.floor(clamp(amount, 0, 1) * 100);+ if (share <= 0) return ink;+ if (share >= 100) return accent;+ return `color-mix(in srgb, ${accent} ${share}%, ${ink})`;+}++function fadeIn(frames: number) {+ return eased(frames, FADE_IN, (t) => 1 - (1 - t) ** 2);+}++function groupState(+ group: KeystrokeGroup,+ time: number,+ metrics: KeystrokeMetrics,+ palette: KeystrokePalette,+ accent: string,+) {+ const { size } = metrics;+ const slot = group.pushes.reduce(+ (sum, at) => sum + eased(time - at, PUSH, GLIDE),+ 0,+ );+ const leaving = clamp((time - group.exit) / EXIT, 0, 1);+ const pushedAway = group.pushes.some((at) => at <= group.exit);+ const drift = (pushedAway ? -1 : 1) * EXIT_DRIFT * size * leaving ** 3;+ const dimmed = 1 - (1 - SLOT_OPACITY) * Math.min(1, slot);+ const last = group.chords.length - 1;+ let visible = group.layout.widths[0];+ for (let chord = 1; chord <= last; chord++) {+ const added = group.layout.widths[chord] - group.layout.widths[chord - 1];+ visible += added * eased(time - group.timing[chord].enter, SLIDE, GLIDE);+ }+ const left = -visible / 2;+ const caps = group.layout.caps.flatMap((cap) => {+ const timing = group.timing[cap.chord];+ const enter = timing.enter + cap.index * STAGGER;+ if (time <= enter) return [];+ const key = group.chords[cap.chord][cap.index];+ const depth = getKeystrokeDepth(time, timing.keys[cap.index]);+ const landing =+ group.timing.at(cap.chord + 1)?.fire ?? Number.POSITIVE_INFINITY;+ const dim = smoothstep((time - (landing - DIM)) / DIM);+ const lean = clamp(depth, -1, 1);+ const shadowY = SHADOW_Y - (SHADOW_Y - SHADOW_Y_PRESSED) * lean;+ const shadowBlur = SHADOW_BLUR - (SHADOW_BLUR - SHADOW_BLUR_PRESSED) * lean;+ return [+ {+ id: `${cap.chord}-${cap.index}`,+ chord: cap.chord,+ index: cap.index,+ key,+ x: round((left + cap.x) * size),+ y: round((1 - getKeystrokeRise(time - enter)) * metrics.rise),+ width: round(cap.width * size),+ opacity: round(fadeIn(time - enter) * (1 - (1 - DIM_OPACITY) * dim)),+ depth: round(depth),+ lift: round(depth * metrics.travel),+ wall: round(metrics.wall - depth * metrics.travel),+ shadowY: round(shadowY * size),+ shadowBlur: round(shadowBlur * size),+ color: legendColor(palette.ink, accent, clamp(depth, 0, 1)),+ },+ ];+ });+ const separators = group.layout.separators.flatMap((separator) => {+ const enter = group.timing[separator.chord].enter;+ if (time <= enter) return [];+ return [+ {+ id: `then-${separator.chord}`,+ chord: separator.chord,+ x: round((left + separator.x) * size),+ y: round((1 - getKeystrokeRise(time - enter)) * metrics.rise),+ width: round(separator.width * size),+ opacity: round(fadeIn(time - enter)),+ },+ ];+ });+ return {+ id: `${group.step}`,+ index: group.index,+ step: group.step,+ keys: group.keys,+ label: group.label,+ slot: round(slot),+ width: round(visible * size),+ y: round(-slot * SLOT_RISE * size + drift),+ scale: round((1 - (1 - SLOT_SCALE) * slot) * (1 - EXIT_SCALE * leaving)),+ opacity: round(dimmed * (1 - leaving ** 2)),+ caps,+ separators,+ };+}++export function getKeystrokeState(+ frame: number,+ options: KeystrokeOptions = {},+ timeline: KeystrokeTimeline = getKeystrokeTimeline(options),+) {+ const width = Math.max(1, finite(options.width, 1280));+ const height = Math.max(1, finite(options.height, 720));+ const unit = height / 720;+ const reference = within(+ options.size,+ keystrokeDefaults.size,+ MIN_SIZE,+ MAX_SIZE,+ );+ const metrics = getKeystrokeMetrics(reference * unit, unit);+ const time = getKeystrokeTime(frame, options);+ const x = finite(options.x, keystrokeDefaults.x);+ const y = finite(options.y, keystrokeDefaults.y);+ const theme = themeOf(options.theme);+ const palette = keystrokePalettes[theme];+ const accent = accentOf(options.accent);+ const groups = timeline.groups+ .filter((group) => time > group.enter && time < group.end)+ .map((group) => groupState(group, time, metrics, palette, accent));+ return {+ width,+ height,+ unit,+ time: round(time),+ x,+ y,+ originX: round(x * width),+ originY: round(y * height),+ theme,+ palette,+ accent,+ metrics,+ groups,+ };+}++export type KeystrokeState = ReturnType<typeof getKeystrokeState>;++function Legend({+ legend,+ metrics,+}: {+ legend: KeystrokeLegend;+ metrics: KeystrokeMetrics;+}) {+ if (legend.kind === "icon") {+ const icon = ICONS[legend.icon];+ return (+ <svg+ width={metrics.icon}+ height={metrics.icon}+ viewBox={icon.box}+ fill="none"+ stroke="currentColor"+ strokeWidth={2}+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden="true"+ style={{ display: "block" }}+ >+ {icon.paths.map((d) => (+ <path key={d} d={d} />+ ))}+ </svg>+ );+ }+ const fontSize = legend.kind === "word" ? metrics.wordFont : metrics.charFont;+ return (+ <span+ style={{ fontSize, fontWeight: 500, lineHeight: 1, whiteSpace: "nowrap" }}+ >+ {legend.text}+ </span>+ );+}++export function Keystroke({+ steps = keystrokeDefaultSteps,+ platform = keystrokeDefaults.platform,+ theme = keystrokeDefaults.theme,+ accent = keystrokeDefaults.accent,+ x = keystrokeDefaults.x,+ y = keystrokeDefaults.y,+ size = keystrokeDefaults.size,+ linger = keystrokeDefaults.linger,+ speed = keystrokeDefaults.speed,+ className,+}: KeystrokeProps) {+ const frame = useCurrentFrame();+ const { width, height, fps } = useVideoConfig();+ const timeline = useMemo(+ () => getKeystrokeTimeline({ steps, platform, linger, fps }),+ [steps, platform, linger, fps],+ );+ const state = getKeystrokeState(+ frame,+ { width, height, fps, theme, accent, x, y, size, speed },+ timeline,+ );+ const { metrics, palette } = state;++ return (+ <div+ className={className}+ style={{+ position: "absolute",+ inset: 0,+ overflow: "hidden",+ pointerEvents: "none",+ fontFamily: FONT_FAMILY,+ }}+ >+ {state.groups.map((group) => (+ <div+ key={group.id}+ style={{+ position: "absolute",+ left: `${state.x * 100}%`,+ top: `${state.y * 100}%`,+ width: 0,+ height: 0,+ opacity: group.opacity,+ transform: `translateY(${group.y}px) scale(${group.scale})`,+ transformOrigin: "0 0",+ }}+ >+ {group.separators.map((separator) => (+ <div+ key={separator.id}+ style={{+ position: "absolute",+ left: separator.x,+ top: separator.y - metrics.height / 2,+ width: separator.width,+ height: metrics.keytop,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ opacity: separator.opacity,+ color: palette.separator,+ fontSize: metrics.separatorFont,+ fontWeight: 500,+ lineHeight: 1,+ whiteSpace: "nowrap",+ }}+ >+ then+ </div>+ ))}+ {group.caps.map((cap) => (+ <div+ key={cap.id}+ style={{+ position: "absolute",+ left: cap.x,+ top: cap.y - metrics.height / 2,+ width: cap.width,+ height: metrics.height,+ opacity: cap.opacity,+ }}+ >+ <div+ style={{+ position: "absolute",+ left: 0,+ right: 0,+ top: metrics.travel,+ bottom: 0,+ borderRadius: metrics.radius,+ background: palette.wall,+ boxShadow: `0 ${cap.shadowY}px ${cap.shadowBlur}px ${palette.shadow}`,+ }}+ />+ <div+ style={{+ position: "absolute",+ left: 0,+ right: 0,+ top: 0,+ height: metrics.keytop,+ boxSizing: "border-box",+ borderRadius: metrics.radius,+ border: `${metrics.border}px solid ${palette.edge}`,+ background: palette.cap,+ color: cap.color,+ transform: `translateY(${cap.lift}px)`,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ <Legend legend={cap.key.legend} metrics={metrics} />+ </div>+ </div>+ ))}+ </div>+ ))}+ </div>+ );+}diff --git a/registry/remocn/mondrian-split/__tests__/mondrian-split.test.ts b/registry/remocn/mondrian-split/__tests__/mondrian-split.test.tsnew file mode 100644index 00000000..2cdb1e3a--- /dev/null+++ b/registry/remocn/mondrian-split/__tests__/mondrian-split.test.ts@@ -0,0 +1,449 @@+import { describe, expect, it } from "bun:test";+import {+ getMondrianSplitClip,+ getMondrianSplitDuration,+ getMondrianSplitLayout,+ getMondrianSplitState,+ getMondrianSplitTimeline,+ mondrianSplitDefaults,+ mondrianSplitLength,+} from "..";+import { mondrianSplitConfig } from "../config";++type MondrianState = ReturnType<typeof getMondrianSplitState>;++const SIZES = [+ [1280, 720],+ [720, 720],+ [720, 1280],+];+const SEEDS = Array.from({ length: 24 }, (_, index) => index + 1);+const COVERED = "inset(0.0000% 0.0000% 0.0000% 0.0000%)";+const same = (a: number, b: number) => Math.abs(a - b) < 1e-6;+const boxArea = (box: { x0: number; y0: number; x1: number; y1: number }) =>+ (box.x1 - box.x0) * (box.y1 - box.y0);+const cellOf = (state: MondrianState, id: number) => {+ const cell = state.cells.find((item) => item.id === id);+ if (!cell) throw new Error(`cell ${id} is missing`);+ return cell;+};+const positionsOn = (state: MondrianState, axis: "x" | "y") =>+ state.lines.filter((line) => line.axis === axis).map((line) => line.position);+const neighbours = (state: MondrianState, id: number) => {+ const line = state.lines.find((item) => item.id === id);+ if (!line) throw new Error(`line ${id} is missing`);+ const { position } = line;+ const vertical = line.axis === "x";+ const from = vertical ? line.y : line.x;+ const to = from + (vertical ? line.height : line.width);+ const before: number[] = [];+ const after: number[] = [];+ for (const cell of state.cells) {+ const low = vertical ? cell.y0 : cell.x0;+ const high = vertical ? cell.y1 : cell.x1;+ if (Math.min(to, high) - Math.max(from, low) <= 1e-6) continue;+ if (same(vertical ? cell.x1 : cell.y1, position)) before.push(cell.id);+ if (same(vertical ? cell.x0 : cell.y0, position)) after.push(cell.id);+ }+ return { position, before, after };+};++describe("mondrian split timeline", () => {+ it("derives every phase from the split count alone", () => {+ const timeline = getMondrianSplitTimeline();+ expect(timeline).toEqual({+ lines: 3,+ fill: 40,+ field: 50,+ reflow: 76,+ expand: 102,+ end: 133,+ });+ expect(mondrianSplitLength).toBe(timeline.end);+ expect(getMondrianSplitTimeline({ splits: 3 }).end).toBeLessThan(133);+ expect(getMondrianSplitTimeline({ splits: 12 }).end).toBeGreaterThan(133);+ const capped = getMondrianSplitTimeline({ splits: 12 });+ expect(getMondrianSplitTimeline({ splits: 40 })).toEqual(capped);+ expect(getMondrianSplitTimeline({ splits: Number.NaN })).toEqual(timeline);+ });++ it("starts blank, cuts one line at a time and ends on a fully covered frame", () => {+ const layout = getMondrianSplitLayout();+ const { timeline } = layout;+ for (const frame of [0, 2.9]) {+ const state = getMondrianSplitState(frame, layout);+ expect(state.lines).toEqual([]);+ expect(state.fills).toEqual([]);+ expect(state.field).toBeNull();+ }+ const first = getMondrianSplitState(4, layout);+ expect(first.lines).toHaveLength(1);+ expect(first.lines[0].drawn).toBeGreaterThan(0);+ expect(first.lines[0].drawn).toBeLessThan(1);+ expect(getMondrianSplitState(timeline.fill, layout).fills).toEqual([]);+ const built = getMondrianSplitState(timeline.field, layout);+ expect(built.lines).toHaveLength(layout.lines.length);+ expect(built.lines.every((line) => line.drawn === 1)).toBe(true);+ expect(built.field).toBeNull();+ const held = getMondrianSplitState(timeline.reflow, layout);+ expect(held.fills).toHaveLength(layout.fills.length);+ const target = cellOf(held, layout.target);+ if (!held.field) throw new Error("field is missing");+ expect(held.field.x).toBeCloseTo(target.x0, 6);+ expect(held.field.y).toBeCloseTo(target.y0, 6);+ expect(held.field.x + held.field.width).toBeCloseTo(target.x1, 6);+ expect(held.field.y + held.field.height).toBeCloseTo(target.y1, 6);+ for (const frame of [timeline.end, timeline.end + 12, 1000]) {+ const state = getMondrianSplitState(frame, layout);+ expect(state.lines).toEqual([]);+ expect(state.fills).toEqual([]);+ if (!state.field) throw new Error("field is missing");+ expect(state.field.x).toBeLessThanOrEqual(0);+ expect(state.field.y).toBeLessThanOrEqual(0);+ expect(state.field.x + state.field.width).toBeGreaterThanOrEqual(1280);+ expect(state.field.y + state.field.height).toBeGreaterThanOrEqual(720);+ }+ });++ it("holds the finished composition perfectly still before the reflow", () => {+ const layout = getMondrianSplitLayout();+ const settled = getMondrianSplitState(layout.timeline.field + 13, layout);+ const waiting = getMondrianSplitState(layout.timeline.reflow, layout);+ expect(waiting.cells).toEqual(settled.cells);+ expect(waiting.lines).toEqual(settled.lines);+ expect(waiting.fills).toEqual(settled.fills);+ expect(waiting.field).toEqual(settled.field);+ });++ it("adds a short tail and scales the duration with speed", () => {+ expect(getMondrianSplitDuration()).toBe(mondrianSplitLength + 12);+ expect(getMondrianSplitDuration({ speed: 0.5 })).toBe(290);+ expect(getMondrianSplitDuration({ speed: 2 })).toBe(73);+ expect(getMondrianSplitDuration({ speed: 0 })).toBe(1);+ const long = getMondrianSplitTimeline({ splits: 12 }).end;+ expect(getMondrianSplitDuration({ splits: 12 })).toBe(long + 12);+ });+});++describe("mondrian split composition", () => {+ it("tiles 16:9, 1:1 and 9:16 frames with exactly the requested cells", () => {+ for (const [width, height] of SIZES) {+ for (const splits of [3, 7, 12]) {+ for (const seed of SEEDS) {+ const layout = getMondrianSplitLayout({+ seed,+ splits,+ width,+ height,+ });+ expect(layout.lines).toHaveLength(splits);+ expect(layout.leaves).toHaveLength(splits + 1);+ const boxes = layout.leaves.map((id) => layout.nodes[id].box);+ const areas = boxes.map(boxArea);+ const covered = areas.reduce((sum, value) => sum + value, 0);+ expect(covered).toBeCloseTo(width * height, 3);+ for (const box of boxes) {+ expect(box.x1 - box.x0).toBeGreaterThan(layout.minSide - 1e-6);+ expect(box.y1 - box.y0).toBeGreaterThan(layout.minSide - 1e-6);+ }+ const chosen = boxArea(layout.nodes[layout.target].box);+ expect(chosen).toBe(Math.max(...areas));+ }+ }+ }+ });++ it("ranks the expanding cell by size", () => {+ const pick = (expandCell: number) => {+ const layout = getMondrianSplitLayout({ seed: 3, expandCell });+ const areas = layout.leaves.map((id) => boxArea(layout.nodes[id].box));+ return {+ chosen: boxArea(layout.nodes[layout.target].box),+ ranked: areas.sort((a, b) => b - a),+ };+ };+ expect(pick(0).chosen).toBe(pick(0).ranked[0]);+ expect(pick(1).chosen).toBe(pick(1).ranked[1]);+ const last = pick(99);+ expect(last.chosen).toBe(last.ranked[last.ranked.length - 1]);+ });++ it("paints a few other cells in distinct slots and keeps the field for the expanding cell", () => {+ for (const seed of SEEDS) {+ const layout = getMondrianSplitLayout({ seed });+ const slots = layout.fills.map((fill) => fill.slot).sort();+ expect(slots).toEqual(["blue", "yellow"]);+ const painted = new Set(layout.fills.map((fill) => fill.node));+ expect(painted.size).toBe(layout.fills.length);+ expect(painted.has(layout.target)).toBe(false);+ expect(layout.field.node).toBe(layout.target);+ }+ });++ it("draws every line from its older boundary toward the newer one", () => {+ for (const seed of SEEDS) {+ const layout = getMondrianSplitLayout({ seed, splits: 12 });+ for (const line of layout.lines) {+ const { bounds } = layout.nodes[line.node];+ const near = line.axis === "x" ? bounds.top : bounds.left;+ const far = line.axis === "x" ? bounds.bottom : bounds.right;+ const origin = line.fromEnd ? far : near;+ const destination = line.fromEnd ? near : far;+ expect(origin).toBeLessThanOrEqual(destination);+ expect(destination).toBeLessThan(line.id);+ }+ }+ });+});++describe("mondrian split rubber grid", () => {+ it("derives every cell from the current line positions throughout the reflow", () => {+ for (const [width, height] of SIZES) {+ for (const seed of SEEDS.slice(0, 8)) {+ const layout = getMondrianSplitLayout({ seed, width, height });+ const { reflow, expand } = layout.timeline;+ for (let frame = reflow; frame < expand; frame += 1.5) {+ const state = getMondrianSplitState(frame, layout);+ const xs = [0, width, ...positionsOn(state, "x")];+ const ys = [0, height, ...positionsOn(state, "y")];+ let covered = 0;+ for (const cell of state.cells) {+ expect(cell.x1 - cell.x0).toBeGreaterThan(0);+ expect(cell.y1 - cell.y0).toBeGreaterThan(0);+ expect(xs.some((x) => same(x, cell.x0))).toBe(true);+ expect(xs.some((x) => same(x, cell.x1))).toBe(true);+ expect(ys.some((y) => same(y, cell.y0))).toBe(true);+ expect(ys.some((y) => same(y, cell.y1))).toBe(true);+ covered += boxArea(cell);+ }+ expect(covered).toBeCloseTo(width * height, 3);+ }+ }+ }+ });++ it("drags the same cells with a sliding line, in lockstep, for its whole slide", () => {+ for (const seed of SEEDS.slice(0, 12)) {+ const layout = getMondrianSplitLayout({ seed });+ expect(layout.moves.length).toBeGreaterThan(0);+ for (const move of layout.moves) {+ const distance = Math.abs(move.to - move.from);+ expect(distance).toBeGreaterThanOrEqual(layout.minMove - 1e-9);+ for (const line of layout.lines) {+ if (line.track !== move.track) continue;+ const at = (offset: number) => {+ const state = getMondrianSplitState(move.start + offset, layout);+ return neighbours(state, line.id);+ };+ const start = at(0);+ expect(start.before.length).toBeGreaterThan(0);+ expect(start.after.length).toBeGreaterThan(0);+ for (const offset of [4, 9, 14, 20]) {+ const current = at(offset);+ expect(current.before).toEqual(start.before);+ expect(current.after).toEqual(start.after);+ }+ if (move.start + 20 <= layout.timeline.expand) {+ expect(at(20).position).toBeCloseTo(move.to, 6);+ }+ }+ }+ }+ });++ it("lands every sliding line on another line or clearly away from all of them", () => {+ for (const [width, height] of SIZES) {+ for (const seed of SEEDS) {+ const layout = getMondrianSplitLayout({ seed, width, height });+ const settle = (track: number, position: number) =>+ layout.moves.find((move) => move.track === track)?.to ?? position;+ for (const move of layout.moves) {+ const moving = layout.lines.find((line) => line.track === move.track);+ if (!moving) throw new Error(`track ${move.track} has no line`);+ const rivals = layout.lines.filter(+ (line) => line.axis === moving.axis && line.track !== move.track,+ );+ for (const line of rivals) {+ const rest = settle(line.track, line.position);+ const offset = Math.abs(rest - move.to);+ if (offset < 1e-6) continue;+ expect(offset).toBeGreaterThanOrEqual(layout.align - 1e-6);+ }+ }+ }+ }+ });++ it("keeps every fill glued to its cell while the grid reflows", () => {+ for (const seed of SEEDS.slice(0, 12)) {+ const layout = getMondrianSplitLayout({ seed });+ const { reflow, expand } = layout.timeline;+ for (let frame = reflow; frame < expand; frame += 2) {+ const state = getMondrianSplitState(frame, layout);+ const painted = [+ ...state.fills,+ ...(state.field ? [{ ...state.field, id: layout.target }] : []),+ ];+ expect(painted).toHaveLength(layout.fills.length + 1);+ for (const fill of painted) {+ const cell = cellOf(state, fill.id);+ expect(fill.x).toBeCloseTo(cell.x0, 6);+ expect(fill.y).toBeCloseTo(cell.y0, 6);+ expect(fill.x + fill.width).toBeCloseTo(cell.x1, 6);+ expect(fill.y + fill.height).toBeCloseTo(cell.y1, 6);+ }+ }+ }+ });++ it("pushes the expanding cell's own lines out past every frame edge", () => {+ for (const [width, height] of [...SIZES, [2560, 720]]) {+ for (const seed of SEEDS.slice(0, 8)) {+ for (const expandCell of [0, 3]) {+ const layout = getMondrianSplitLayout({+ seed,+ width,+ height,+ expandCell,+ });+ const { bounds } = layout.nodes[layout.target];+ const { expand, end } = layout.timeline;+ for (let frame = expand; frame <= end; frame++) {+ const state = getMondrianSplitState(frame, layout);+ const cell = cellOf(state, layout.target);+ const edges = [+ { bound: bounds.left, edge: cell.x0 },+ { bound: bounds.top, edge: cell.y0 },+ { bound: bounds.right, edge: cell.x1 },+ { bound: bounds.bottom, edge: cell.y1 },+ ];+ for (const { bound, edge } of edges) {+ const line = state.lines.find((item) => item.id === bound);+ if (line) expect(line.position).toBeCloseTo(edge, 6);+ }+ }+ const last = getMondrianSplitState(end, layout);+ expect(last.lines).toEqual([]);+ expect(last.fills).toEqual([]);+ const clip = getMondrianSplitClip(last.field, width, height);+ expect(clip).toBe(COVERED);+ }+ }+ }+ });++ it("only ever squeezes the expanding cell while the grid reflows", () => {+ for (const [width, height] of SIZES) {+ for (const seed of SEEDS) {+ const layout = getMondrianSplitLayout({ seed, width, height });+ const { reflow, expand } = layout.timeline;+ const built = getMondrianSplitState(reflow, layout);+ const first = cellOf(built, layout.target);+ for (let frame = reflow; frame <= expand; frame++) {+ const state = getMondrianSplitState(frame, layout);+ const cell = cellOf(state, layout.target);+ expect(cell.x0).toBeGreaterThanOrEqual(first.x0 - 1e-6);+ expect(cell.y0).toBeGreaterThanOrEqual(first.y0 - 1e-6);+ expect(cell.x1).toBeLessThanOrEqual(first.x1 + 1e-6);+ expect(cell.y1).toBeLessThanOrEqual(first.y1 + 1e-6);+ }+ }+ }+ const layout = getMondrianSplitLayout();+ const { reflow, expand } = layout.timeline;+ const before = cellOf(getMondrianSplitState(reflow, layout), layout.target);+ const after = cellOf(getMondrianSplitState(expand, layout), layout.target);+ expect(boxArea(after)).toBeLessThan(boxArea(before));+ });++ it("keeps a narrow expanding cell open through its wind-up on very wide frames", () => {+ for (const seed of SEEDS) {+ for (const expandCell of [6, 9, 12]) {+ const layout = getMondrianSplitLayout({+ seed,+ splits: 12,+ expandCell,+ width: 2560,+ height: 720,+ });+ const { expand, end } = layout.timeline;+ for (let frame = expand; frame <= end; frame++) {+ const state = getMondrianSplitState(frame, layout);+ const cell = cellOf(state, layout.target);+ expect(cell.x1 - cell.x0).toBeGreaterThan(0);+ expect(cell.y1 - cell.y0).toBeGreaterThan(0);+ expect(state.field).not.toBeNull();+ }+ }+ }+ });++ it("only grows the expanding cell once every wind-up has passed", () => {+ for (const seed of SEEDS.slice(0, 8)) {+ const layout = getMondrianSplitLayout({ seed });+ const { expand, end } = layout.timeline;+ let previous = 0;+ for (let frame = expand + 14; frame <= end; frame++) {+ const { field } = getMondrianSplitState(frame, layout);+ if (!field) throw new Error("field is missing");+ const size = field.width * field.height;+ expect(size).toBeGreaterThanOrEqual(previous - 1e-6);+ previous = size;+ }+ }+ });+});++describe("mondrian split determinism", () => {+ it("renders any frame identically no matter the order it is sampled in", () => {+ const frames = [0, 17, 41, 58, 77, 91, 104, 120, 133, 200];+ const layout = getMondrianSplitLayout({ seed: 11 });+ const forward = frames.map((frame) => getMondrianSplitState(frame, layout));+ const fresh = () => getMondrianSplitLayout({ seed: 11 });+ const replay = [...frames].reverse();+ const later = replay.map((frame) => getMondrianSplitState(frame, fresh()));+ expect(later.reverse()).toEqual(forward);+ });++ it("gives a seed the same grid every time and a new seed a new grid", () => {+ const layout = getMondrianSplitLayout({ seed: 5 });+ expect(getMondrianSplitLayout({ seed: 5 })).toEqual(layout);+ const next = getMondrianSplitLayout({ seed: 6 });+ const positions = (value: typeof layout) =>+ value.lines.map((line) => line.position);+ expect(positions(next)).not.toEqual(positions(layout));+ });++ it("refines the same grid when the split count rises", () => {+ const shape = (splits: number) => {+ const { lines } = getMondrianSplitLayout({ splits });+ return lines.map((line) => [line.axis, line.position, line.node]);+ };+ expect(shape(9).slice(0, 5)).toEqual(shape(5));+ });+});++describe("mondrian split children and config", () => {+ it("clips children to nothing until the expanding cell fills", () => {+ const layout = getMondrianSplitLayout();+ const early = getMondrianSplitState(layout.timeline.field, layout);+ expect(getMondrianSplitClip(early.field, 1280, 720)).toBe("inset(50%)");+ });++ it("mirrors the component defaults and duration", () => {+ const { controls, durationInFrames, previewBackdrop } = mondrianSplitConfig;+ const keys = Object.keys(controls).sort();+ expect(keys).toEqual(Object.keys(mondrianSplitDefaults).sort());+ for (const [key, value] of Object.entries(mondrianSplitDefaults)) {+ const field = controls[key];+ const declared = field && "default" in field ? field.default : undefined;+ expect(declared).toBe(value);+ }+ expect(durationInFrames).toBe(getMondrianSplitDuration());+ const faster = mondrianSplitConfig.getDurationInFrames?.({ speed: 2 });+ expect(faster).toBe(getMondrianSplitDuration({ speed: 2 }));+ const denser = mondrianSplitConfig.getDurationInFrames?.({ splits: 12 });+ expect(denser).toBe(getMondrianSplitDuration({ splits: 12 }));+ expect(previewBackdrop).toEqual({ type: "color", value: "#f3efe6" });+ });+});diff --git a/registry/remocn/mondrian-split/config.ts b/registry/remocn/mondrian-split/config.tsnew file mode 100644index 00000000..7c8c85ba--- /dev/null+++ b/registry/remocn/mondrian-split/config.ts@@ -0,0 +1,60 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";+import { getMondrianSplitDuration } from ".";++export const mondrianSplitConfig: ComponentConfig = {+ componentName: "MondrianSplit",+ importPath: "@/components/remocn/mondrian-split",+ controls: {+ seed: {+ type: "number",+ default: 7,+ min: 1,+ max: 99,+ step: 1,+ description: "Seed",+ hiddenFromList: false,+ },+ splits: {+ type: "number",+ default: 7,+ min: 3,+ max: 12,+ step: 1,+ description: "Splits",+ hiddenFromList: false,+ },+ lineWeight: {+ type: "number",+ default: 14,+ min: 4,+ max: 32,+ step: 1,+ description: "Line weight",+ hiddenFromList: false,+ },+ expandCell: {+ type: "number",+ default: 0,+ min: 0,+ max: 12,+ step: 1,+ description: "Expanding cell (0 is the largest)",+ hiddenFromList: false,+ },+ lineColor: { type: "color", default: "#121212", description: "Lines" },+ redColor: { type: "color", default: "#d62d20", description: "Red" },+ yellowColor: { type: "color", default: "#f4c20d", description: "Yellow" },+ blueColor: { type: "color", default: "#1f4e9e", description: "Blue" },+ fieldColor: {+ type: "color",+ default: "#d62d20",+ description: "Expanding cell color",+ },+ },+ durationInFrames: 145,+ getDurationInFrames: (values) => getMondrianSplitDuration(values),+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#f3efe6" },+};diff --git a/registry/remocn/mondrian-split/index.tsx b/registry/remocn/mondrian-split/index.tsxnew file mode 100644index 00000000..b729f29d--- /dev/null+++ b/registry/remocn/mondrian-split/index.tsx@@ -0,0 +1,873 @@+"use client";++import { type CSSProperties, type ReactNode, useMemo } from "react";+import { Easing, random, useCurrentFrame, useVideoConfig } from "remotion";++export type MondrianSplitAxis = "x" | "y";+export type MondrianSplitSlot = "red" | "yellow" | "blue";+export type MondrianSplitSide = "left" | "top" | "right" | "bottom";++export interface MondrianSplitProps {+ children?: ReactNode;+ seed?: number;+ splits?: number;+ lineWeight?: number;+ expandCell?: number;+ lineColor?: string;+ redColor?: string;+ yellowColor?: string;+ blueColor?: string;+ fieldColor?: string;+ speed?: number;+ className?: string;+}++export type MondrianSplitOptions = Pick<+ MondrianSplitProps,+ "seed" | "splits" | "lineWeight" | "expandCell"+> & {+ width?: number;+ height?: number;+};++export interface MondrianSplitBox {+ x0: number;+ y0: number;+ x1: number;+ y1: number;+}++export interface MondrianSplitRect {+ x: number;+ y: number;+ width: number;+ height: number;+}++interface GridNode {+ box: MondrianSplitBox;+ bounds: Record<MondrianSplitSide, number>;+ line: number;+}++interface GridCut {+ axis: MondrianSplitAxis;+ position: number;+ node: number;+}++interface GridMove {+ track: number;+ from: number;+ to: number;+ start: number;+}++interface GridWipe {+ axis: MondrianSplitAxis;+ fromEnd: boolean;+}++export const mondrianSplitDefaults = {+ seed: 7,+ splits: 7,+ lineWeight: 14,+ expandCell: 0,+ lineColor: "#121212",+ redColor: "#d62d20",+ yellowColor: "#f4c20d",+ blueColor: "#1f4e9e",+ fieldColor: "#d62d20",+};++const LINE_START = 3;+const LINE_GAP = 5;+const LINE_DRAW = 10;+const FILL_LAG = 7;+const FILL_GAP = 4;+const FILL_WIPE = 9;+const FIELD_LAG = 6;+const FIELD_WIPE = 12;+const HOLD = 14;+const TRACK_COUNT = 3;+const TRACK_GAP = 5;+const TRACK_SLIDE = 20;+const EXPAND_LEAD = 4;+const SIDE_GAP = 3;+const SIDE_PUSH = 22;+const TAIL = 12;+const SLIDE_PEAK = 0.72;+const SLIDE_OVER = 0.035;+const RESERVE = 0.045;+const WIND = 0.22;+const DIP = 0.035;+const DIP_SHARE = 0.2;+const SIDES: MondrianSplitSide[] = ["left", "top", "right", "bottom"];+const SLOTS: MondrianSplitSlot[] = ["blue", "yellow", "red", "blue", "yellow"];+const FALLBACK_CUTS = [0.38, 0.62, 0.3, 0.7, 0.5];++const drawEase = Easing.bezier(0.16, 1, 0.3, 1);+const wipeEase = Easing.bezier(0.7, 0, 0.2, 1);+const riseEase = Easing.bezier(0.65, 0, 0.3, 1);+const settleEase = Easing.bezier(0.4, 0, 0.6, 1);+const windEase = Easing.bezier(0.45, 0, 0.55, 1);+const pushEase = Easing.poly(2.5);+const layer: CSSProperties = { position: "absolute", inset: 0 };++const finite = (value: number, fallback: number) =>+ Number.isFinite(value) ? value : fallback;+const clamp = (value: number, min: number, max: number) =>+ Math.min(max, Math.max(min, value));+const mix = (from: number, to: number, amount: number) =>+ from + (to - from) * amount;+const progress = (time: number, start: number, duration: number) =>+ clamp((time - start) / duration, 0, 1);+const other = (axis: MondrianSplitAxis): MondrianSplitAxis =>+ axis === "x" ? "y" : "x";+const lowEdge = (box: MondrianSplitBox, axis: MondrianSplitAxis) =>+ axis === "x" ? box.x0 : box.y0;+const extent = (box: MondrianSplitBox, axis: MondrianSplitAxis) =>+ axis === "x" ? box.x1 - box.x0 : box.y1 - box.y0;+const area = (box: MondrianSplitBox) => extent(box, "x") * extent(box, "y");+const splitCount = (splits: number) =>+ Math.round(clamp(finite(splits, mondrianSplitDefaults.splits), 3, 12));+const coloredCount = (count: number) => clamp(Math.round(count * 0.3), 1, 5);++const touches = (a: MondrianSplitBox, b: MondrianSplitBox) => {+ const overlapX = Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0);+ const overlapY = Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0);+ const beside = Math.abs(a.x1 - b.x0) < 0.5 || Math.abs(b.x1 - a.x0) < 0.5;+ const stacked = Math.abs(a.y1 - b.y0) < 0.5 || Math.abs(b.y1 - a.y0) < 0.5;+ return (beside && overlapY > 0.5) || (stacked && overlapX > 0.5);+};++const choose = (weights: readonly number[], roll: number) => {+ let remaining = roll * weights.reduce((sum, value) => sum + value, 0);+ for (let index = 0; index < weights.length; index++) {+ remaining -= weights[index];+ if (remaining <= 0) return index;+ }+ return weights.length - 1;+};++const slide = (amount: number) => {+ if (amount >= 1) return 1;+ if (amount <= SLIDE_PEAK) {+ return (1 + SLIDE_OVER) * riseEase(amount / SLIDE_PEAK);+ }+ const settle = settleEase((amount - SLIDE_PEAK) / (1 - SLIDE_PEAK));+ return mix(1 + SLIDE_OVER, 1, settle);+};++const push = (amount: number, dip: number) => {+ if (amount >= 1) return 1;+ if (amount <= 0) return 0;+ if (amount < WIND) return -dip * windEase(amount / WIND);+ return mix(-dip, 1, pushEase((amount - WIND) / (1 - WIND)));+};++const stretch = (+ from0: number,+ from1: number,+ to0: number,+ to1: number,+ min: number,+ max: number,+) => {+ if (from0 === to0 && from1 === to1) return (value: number) => value;+ return (value: number) => {+ if (value <= from0) {+ return min + (value - min) * ((to0 - min) / (from0 - min));+ }+ if (value >= from1) {+ return max - (max - value) * ((max - to1) / (max - from1));+ }+ return to0 + (value - from0) * ((to1 - to0) / (from1 - from0));+ };+};++const wipe = (+ box: MondrianSplitBox,+ { axis, fromEnd }: GridWipe,+ amount: number,+): MondrianSplitRect => {+ const width = box.x1 - box.x0;+ const height = box.y1 - box.y0;+ if (axis === "x") {+ const span = width * amount;+ return {+ x: fromEnd ? box.x1 - span : box.x0,+ y: box.y0,+ width: span,+ height,+ };+ }+ const span = height * amount;+ return {+ x: box.x0,+ y: fromEnd ? box.y1 - span : box.y0,+ width,+ height: span,+ };+};++const inFrame = (rect: MondrianSplitRect, width: number, height: number) =>+ rect.width > 0.01 &&+ rect.height > 0.01 &&+ rect.x < width &&+ rect.y < height &&+ rect.x + rect.width > 0 &&+ rect.y + rect.height > 0;++const placeBoxes = (+ cuts: readonly Pick<GridCut, "axis" | "node">[],+ positions: readonly number[],+ width: number,+ height: number,+) => {+ const boxes: MondrianSplitBox[] = [{ x0: 0, y0: 0, x1: width, y1: height }];+ for (let id = 0; id < cuts.length; id++) {+ const { axis, node } = cuts[id];+ const box = boxes[node];+ const at = positions[id];+ boxes.push(+ axis === "x" ? { ...box, x1: at } : { ...box, y1: at },+ axis === "x" ? { ...box, x0: at } : { ...box, y0: at },+ );+ }+ return boxes;+};++const percent = (value: number, size: number) =>+ `${(clamp(value / size, 0, 1) * 100).toFixed(4)}%`;++export function getMondrianSplitTimeline({+ splits = mondrianSplitDefaults.splits,+}: Pick<MondrianSplitProps, "splits"> = {}) {+ const count = splitCount(splits);+ const fill = LINE_START + (count - 1) * LINE_GAP + FILL_LAG;+ const field = fill + (coloredCount(count) - 1) * FILL_GAP + FIELD_LAG;+ const reflow = field + FIELD_WIPE + HOLD;+ const settled = reflow + (TRACK_COUNT - 1) * TRACK_GAP + TRACK_SLIDE;+ const expand = settled - EXPAND_LEAD;+ const end = expand + (SIDES.length - 1) * SIDE_GAP + SIDE_PUSH;+ return { lines: LINE_START, fill, field, reflow, expand, end };+}++export const mondrianSplitLength = getMondrianSplitTimeline().end;++export function getMondrianSplitDuration({+ speed = 1,+ splits = mondrianSplitDefaults.splits,+}: Pick<MondrianSplitProps, "speed" | "splits"> = {}) {+ const rate = Math.max(0, finite(speed, 1));+ const frames = getMondrianSplitTimeline({ splits }).end + TAIL;+ return rate === 0 ? 1 : Math.max(1, Math.ceil(frames / rate));+}++export function getMondrianSplitLayout({+ seed = mondrianSplitDefaults.seed,+ splits = mondrianSplitDefaults.splits,+ lineWeight = mondrianSplitDefaults.lineWeight,+ expandCell = mondrianSplitDefaults.expandCell,+ width = 1280,+ height = 720,+}: MondrianSplitOptions = {}) {+ const w = Math.max(1, finite(width, 1280));+ const h = Math.max(1, finite(height, 720));+ const short = Math.min(w, h);+ const weight = clamp(finite(lineWeight, 14), 2, 48) * (short / 720);+ const count = splitCount(splits);+ const timeline = getMondrianSplitTimeline({ splits: count });+ const salt = Math.round(finite(seed, mondrianSplitDefaults.seed));+ const roll = (name: string) => random(`mondrian-split-${salt}-${name}`);+ const minSide = Math.max(short * 0.1, weight * 3);+ const snap = short * 0.045;+ const align = short * 0.075;+ const gap = Math.max(short * 0.07, weight * 2.5);+ const minMove = short * 0.06;+ const overscan = weight + short * 0.04;+ const nodes: GridNode[] = [+ {+ box: { x0: 0, y0: 0, x1: w, y1: h },+ bounds: { left: -1, top: -1, right: -1, bottom: -1 },+ line: -1,+ },+ ];+ const cuts: GridCut[] = [];++ const lean = (+ box: MondrianSplitBox,+ ratio: number,+ name: string,+ ): MondrianSplitAxis => {+ const wide = extent(box, "x");+ const tall = extent(box, "y");+ if (wide > tall * ratio) return "x";+ if (tall > wide * ratio) return "y";+ return roll(name) < 0.5 ? "x" : "y";+ };++ const cut = (node: number, axis: MondrianSplitAxis, position: number) => {+ const id = cuts.length;+ const { box, bounds: edges } = nodes[node];+ const vertical = axis === "x";+ nodes[node].line = id;+ cuts.push({ axis, position, node });+ nodes.push(+ {+ box: vertical ? { ...box, x1: position } : { ...box, y1: position },+ bounds: vertical ? { ...edges, right: id } : { ...edges, bottom: id },+ line: -1,+ },+ {+ box: vertical ? { ...box, x0: position } : { ...box, y0: position },+ bounds: vertical ? { ...edges, left: id } : { ...edges, top: id },+ line: -1,+ },+ );+ };++ const snapTo = (axis: MondrianSplitAxis, position: number) => {+ let best = position;+ let distance = snap;+ for (const line of cuts) {+ const offset = Math.abs(line.position - position);+ if (line.axis === axis && offset < distance) {+ best = line.position;+ distance = offset;+ }+ }+ return best;+ };++ const nearMiss = (axis: MondrianSplitAxis, position: number) =>+ cuts.some(+ (line) =>+ line.axis === axis &&+ line.position !== position &&+ Math.abs(line.position - position) < snap,+ );++ const tryCut = (+ node: number,+ axis: MondrianSplitAxis,+ fraction: number,+ strict: boolean,+ ) => {+ const { box } = nodes[node];+ const low = lowEdge(box, axis);+ const length = extent(box, axis);+ if (length < minSide * 2) return false;+ const position = clamp(+ snapTo(axis, low + length * fraction),+ low + minSide,+ low + length - minSide,+ );+ if (strict && nearMiss(axis, position)) return false;+ cut(node, axis, position);+ return true;+ };++ let anchor = -1;+ const longAxis = lean(nodes[0].box, 1.05, "square");+ const rootAxis = roll("root-axis") < 0.75 ? longAxis : other(longAxis);+ const rootFraction =+ roll("root-side") < 0.5+ ? mix(0.3, 0.4, roll("root-at"))+ : mix(0.6, 0.7, roll("root-at"));+ if (tryCut(0, rootAxis, rootFraction, false)) {+ const share = mix(0.6, 0.76, roll("anchor-at"));+ const anchorLow = roll("anchor-side") < 0.5;+ const big = rootFraction < 0.5 ? 2 : 1;+ if (tryCut(big, other(rootAxis), anchorLow ? share : 1 - share, false)) {+ anchor = anchorLow ? nodes.length - 2 : nodes.length - 1;+ }+ }++ const splittable = (index: number) => {+ const { box, line } = nodes[index];+ return (+ line === -1 &&+ index !== anchor &&+ Math.max(extent(box, "x"), extent(box, "y")) >= minSide * 2+ );+ };++ const budget = count * 24;+ for (let attempt = 0; cuts.length < count && attempt < budget; attempt++) {+ const tag = `${cuts.length}-${attempt}`;+ const pool = nodes.flatMap((_, index) =>+ splittable(index) ? [index] : [],+ );+ if (pool.length === 0) break;+ const weights = pool.map((index) => area(nodes[index].box) ** 1.2);+ const node = pool[choose(weights, roll(`${tag}-cell`))];+ const { box } = nodes[node];+ const preferred = lean(box, 1.25, `${tag}-axis`);+ const fits = extent(box, preferred) >= minSide * 2;+ const at = roll(`${tag}-at`);+ const fraction = at < 0.5 ? 0.28 + at * 0.34 : 0.55 + (at - 0.5) * 0.34;+ tryCut(node, fits ? preferred : other(preferred), fraction, true);+ }++ const byPriority = (a: number, b: number) =>+ Number(a === anchor) - Number(b === anchor) ||+ area(nodes[b].box) - area(nodes[a].box);+ const fallback = () => {+ const pool = nodes.flatMap((node, index) =>+ node.line === -1 ? [index] : [],+ );+ pool.sort(byPriority);+ for (const strict of [true, false]) {+ for (const node of pool) {+ const { box } = nodes[node];+ const first: MondrianSplitAxis =+ extent(box, "x") >= extent(box, "y") ? "x" : "y";+ for (const axis of [first, other(first)]) {+ for (const fraction of FALLBACK_CUTS) {+ if (tryCut(node, axis, fraction, strict)) return true;+ }+ }+ }+ }+ return false;+ };+ while (cuts.length < count) {+ if (!fallback()) break;+ }++ const trackKeys: string[] = [];+ const lines = cuts.map((draft, id) => {+ const key = `${draft.axis}:${draft.position}`;+ if (!trackKeys.includes(key)) trackKeys.push(key);+ const { bounds } = nodes[draft.node];+ const vertical = draft.axis === "x";+ const near = vertical ? bounds.top : bounds.left;+ const far = vertical ? bounds.bottom : bounds.right;+ return {+ id,+ axis: draft.axis,+ position: draft.position,+ node: draft.node,+ track: trackKeys.indexOf(key),+ lowBound: vertical ? bounds.left : bounds.top,+ highBound: vertical ? bounds.right : bounds.bottom,+ fromEnd: near === far ? roll(`draw-${id}`) < 0.5 : far < near,+ start: LINE_START + id * LINE_GAP,+ };+ });++ const leaves = nodes.flatMap((node, index) =>+ node.line === -1 ? [index] : [],+ );+ const ranked = [...leaves].sort(+ (a, b) => area(nodes[b].box) - area(nodes[a].box) || a - b,+ );+ const pick = clamp(Math.round(finite(expandCell, 0)), 0, ranked.length - 1);+ const target = ranked[pick];+ const targetBox = nodes[target].box;++ const others = leaves.filter((index) => index !== target);+ const largest = Math.max(1, ...others.map((index) => area(nodes[index].box)));+ const candidates = others+ .map((index) => ({+ index,+ score:+ roll(`fill-${index}`) ++ (touches(nodes[index].box, targetBox) ? 0.45 : 0) ++ (0.3 * area(nodes[index].box)) / largest,+ }))+ .sort((a, b) => a.score - b.score);+ const painted: { index: number; slot: MondrianSplitSlot }[] = [];+ const quota = Math.min(coloredCount(count), candidates.length);+ for (let order = 0; order < quota; order++) {+ const slot = SLOTS[order];+ const free = candidates.filter(+ ({ index }) => !painted.some((cell) => cell.index === index),+ );+ const clean = free.find(+ ({ index }) =>+ !painted.some(+ (cell) =>+ cell.slot === slot &&+ touches(nodes[cell.index].box, nodes[index].box),+ ) && !(slot === "red" && touches(nodes[index].box, targetBox)),+ );+ const choice = clean ?? free[0];+ if (choice) painted.push({ index: choice.index, slot });+ }++ const wipeOf = (index: number): GridWipe => {+ const { box } = nodes[index];+ const axis = extent(box, "x") >= extent(box, "y") ? "x" : "y";+ const middle = axis === "x" ? box.x0 + box.x1 : box.y0 + box.y1;+ return { axis, fromEnd: middle < (axis === "x" ? w : h) };+ };+ const diagonal = (index: number) => {+ const { box } = nodes[index];+ return (box.x0 + box.x1) / w + (box.y0 + box.y1) / h;+ };+ const fills = [...painted]+ .sort((a, b) => diagonal(a.index) - diagonal(b.index))+ .map((cell, order) => ({+ node: cell.index,+ slot: cell.slot,+ ...wipeOf(cell.index),+ start: timeline.fill + order * FILL_GAP,+ }));+ const field = { node: target, ...wipeOf(target), start: timeline.field };++ const tracks = trackKeys.map((_, track) => {+ const members = lines.filter((line) => line.track === track);+ return {+ track,+ axis: members[0].axis,+ position: members[0].position,+ length: members.reduce(+ (sum, line) => sum + extent(nodes[line.node].box, other(line.axis)),+ 0,+ ),+ };+ });+ const reserveLow = lines.map((line) => line.position);+ const reserveHigh = lines.map((line) => line.position);+ const limits = (track: number) => {+ let low = Number.NEGATIVE_INFINITY;+ let high = Number.POSITIVE_INFINITY;+ for (const line of lines) {+ if (line.track === track) {+ const size = line.axis === "x" ? w : h;+ const floor = line.lowBound === -1 ? 0 : reserveHigh[line.lowBound];+ const ceiling =+ line.highBound === -1 ? size : reserveLow[line.highBound];+ low = Math.max(low, floor + gap);+ high = Math.min(high, ceiling - gap);+ } else {+ if (line.lowBound !== -1 && lines[line.lowBound].track === track) {+ high = Math.min(high, reserveLow[line.id] - gap);+ }+ if (line.highBound !== -1 && lines[line.highBound].track === track) {+ low = Math.max(low, reserveHigh[line.id] + gap);+ }+ }+ }+ return { low, high };+ };+ const moves: GridMove[] = [];+ const settledAt = (track: number, position: number) =>+ moves.find((move) => move.track === track)?.to ?? position;+ const borders = (side: MondrianSplitSide, track: number) => {+ const id = nodes[target].bounds[side];+ return id !== -1 && lines[id].track === track;+ };+ const inward = (track: number) => {+ if (borders("left", track) || borders("top", track)) return 1;+ if (borders("right", track) || borders("bottom", track)) return -1;+ return 0;+ };+ const heading = (track: number, down: number, up: number) => {+ const squeeze = inward(track);+ if (squeeze !== 0) {+ return (squeeze > 0 ? up : down) >= minMove ? squeeze : 0;+ }+ if (down < minMove) return up >= minMove ? 1 : 0;+ if (up < minMove) return -1;+ return roll(`track-way-${track}`) < up / (up + down) ? 1 : -1;+ };+ const order = tracks+ .map((track) => ({+ ...track,+ weight: track.length * (0.6 + 0.8 * roll(`track-${track.track}`)),+ }))+ .sort((a, b) => b.weight - a.weight);+ for (const track of order) {+ if (moves.length >= TRACK_COUNT) break;+ const { low, high } = limits(track.track);+ const down = (track.position - low) / (1 + RESERVE);+ const up = (high - track.position) / (1 + RESERVE);+ const direction = heading(track.track, down, up);+ if (direction === 0) continue;+ const span = track.axis === "x" ? w : h;+ const room = Math.min(direction > 0 ? up : down, span * 0.2);+ const stride = mix(0.6, 0.95, roll(`track-far-${track.track}`));+ const reach = track.position + direction * Math.max(minMove, room * stride);+ const nearest = tracks+ .filter((rival) => rival.axis === track.axis)+ .filter((rival) => rival.track !== track.track)+ .map((rival) => settledAt(rival.track, rival.position))+ .reduce(+ (best, position) =>+ Math.abs(position - reach) < Math.abs(best - reach) ? position : best,+ Number.POSITIVE_INFINITY,+ );+ const to = Math.abs(nearest - reach) < align ? nearest : reach;+ const margin = Math.abs(to - track.position) * RESERVE;+ if (+ Math.abs(to - track.position) < minMove ||+ to - margin < low ||+ to + margin > high+ ) {+ continue;+ }+ for (const line of lines) {+ if (line.track === track.track) {+ reserveLow[line.id] = Math.min(track.position, to) - margin;+ reserveHigh[line.id] = Math.max(track.position, to) + margin;+ }+ }+ moves.push({+ track: track.track,+ from: track.position,+ to,+ start: timeline.reflow + moves.length * TRACK_GAP,+ });+ }++ const settled = lines.map((line) => settledAt(line.track, line.position));+ const home = placeBoxes(lines, settled, w, h)[target];+ const travel: Record<MondrianSplitSide, number> = {+ left: home.x0 + overscan,+ top: home.y0 + overscan,+ right: w + overscan - home.x1,+ bottom: h + overscan - home.y1,+ };+ const ranking = [...SIDES].sort((a, b) => travel[a] - travel[b]);+ const side = (name: MondrianSplitSide) => {+ const across = name === "left" || name === "right" ? "x" : "y";+ const share = (extent(home, across) * DIP_SHARE) / travel[name];+ return {+ start: timeline.expand + ranking.indexOf(name) * SIDE_GAP,+ dip: nodes[target].bounds[name] === -1 ? 0 : Math.min(DIP, share),+ };+ };++ return {+ width: w,+ height: h,+ weight,+ minSide,+ gap,+ minMove,+ align,+ overscan,+ timeline,+ nodes,+ lines,+ leaves,+ target,+ fills,+ field,+ moves,+ sides: {+ left: side("left"),+ top: side("top"),+ right: side("right"),+ bottom: side("bottom"),+ },+ };+}++export type MondrianSplitLayout = ReturnType<typeof getMondrianSplitLayout>;++export function getMondrianSplitState(+ frame: number,+ layout: MondrianSplitLayout = getMondrianSplitLayout(),+) {+ const time = Math.max(0, finite(frame, 0));+ const { width, height, weight, overscan } = layout;+ const positions = layout.lines.map((line) => {+ const move = layout.moves.find((item) => item.track === line.track);+ if (!move) return line.position;+ const amount = slide(progress(time, move.start, TRACK_SLIDE));+ return line.position + (move.to - move.from) * amount;+ });+ const boxes = placeBoxes(layout.lines, positions, width, height);+ const home = boxes[layout.target];+ const reach = (name: MondrianSplitSide) => {+ const { start, dip } = layout.sides[name];+ return push(progress(time, start, SIDE_PUSH), dip);+ };+ const mapX = stretch(+ home.x0,+ home.x1,+ mix(home.x0, -overscan, reach("left")),+ mix(home.x1, width + overscan, reach("right")),+ -overscan,+ width + overscan,+ );+ const mapY = stretch(+ home.y0,+ home.y1,+ mix(home.y0, -overscan, reach("top")),+ mix(home.y1, height + overscan, reach("bottom")),+ -overscan,+ height + overscan,+ );+ const project = (box: MondrianSplitBox): MondrianSplitBox => ({+ x0: mapX(box.x0),+ y0: mapY(box.y0),+ x1: mapX(box.x1),+ y1: mapY(box.y1),+ });++ const lines = layout.lines.flatMap((line) => {+ const drawn = drawEase(progress(time, line.start, LINE_DRAW));+ if (drawn <= 0) return [];+ const box = boxes[line.node];+ const vertical = line.axis === "x";+ const low = vertical ? box.y0 : box.x0;+ const high = vertical ? box.y1 : box.x1;+ const along = vertical ? mapY : mapX;+ const start = along(line.fromEnd ? high - (high - low) * drawn : low);+ const end = along(line.fromEnd ? high : low + (high - low) * drawn);+ const position = (vertical ? mapX : mapY)(positions[line.id]);+ const half = weight / 2;+ const length = end - start;+ const rect: MondrianSplitRect = vertical+ ? { x: position - half, y: start, width: weight, height: length }+ : { x: start, y: position - half, width: length, height: weight };+ return inFrame(rect, width, height)+ ? [{ id: line.id, axis: line.axis, position, drawn, ...rect }]+ : [];+ });++ const fills = layout.fills.flatMap((fill) => {+ const amount = wipeEase(progress(time, fill.start, FILL_WIPE));+ if (amount <= 0) return [];+ const rect = wipe(project(boxes[fill.node]), fill, amount);+ return inFrame(rect, width, height)+ ? [{ id: fill.node, slot: fill.slot, ...rect }]+ : [];+ });++ const reveal = wipeEase(progress(time, layout.field.start, FIELD_WIPE));+ const field = reveal > 0 ? wipe(project(home), layout.field, reveal) : null;++ return {+ time,+ lines,+ fills,+ field: field && inFrame(field, width, height) ? field : null,+ cells: layout.leaves.map((id) => ({ id, ...project(boxes[id]) })),+ };+}++export type MondrianSplitState = ReturnType<typeof getMondrianSplitState>;++export function getMondrianSplitClip(+ field: MondrianSplitRect | null,+ width: number,+ height: number,+) {+ if (!field) return "inset(50%)";+ const top = percent(field.y, height);+ const right = percent(width - field.x - field.width, width);+ const bottom = percent(height - field.y - field.height, height);+ const left = percent(field.x, width);+ return `inset(${top} ${right} ${bottom} ${left})`;+}++export function MondrianSplit({+ children,+ seed = mondrianSplitDefaults.seed,+ splits = mondrianSplitDefaults.splits,+ lineWeight = mondrianSplitDefaults.lineWeight,+ expandCell = mondrianSplitDefaults.expandCell,+ lineColor = mondrianSplitDefaults.lineColor,+ redColor = mondrianSplitDefaults.redColor,+ yellowColor = mondrianSplitDefaults.yellowColor,+ blueColor = mondrianSplitDefaults.blueColor,+ fieldColor = mondrianSplitDefaults.fieldColor,+ speed = 1,+ className,+}: MondrianSplitProps) {+ const frame = useCurrentFrame();+ const { width, height, fps } = useVideoConfig();+ const layout = useMemo(+ () =>+ getMondrianSplitLayout({+ seed,+ splits,+ lineWeight,+ expandCell,+ width,+ height,+ }),+ [seed, splits, lineWeight, expandCell, width, height],+ );+ const time = frame * (30 / fps) * Math.max(0, finite(speed, 1));+ const state = getMondrianSplitState(time, layout);+ const palette: Record<MondrianSplitSlot, string> = {+ red: redColor,+ yellow: yellowColor,+ blue: blueColor,+ };+ const viewBox = `0 0 ${width} ${height}`;++ return (+ <div+ className={className}+ style={{ position: "absolute", inset: 0, overflow: "hidden" }}+ >+ <svg+ width="100%"+ height="100%"+ viewBox={viewBox}+ preserveAspectRatio="none"+ aria-hidden="true"+ style={layer}+ >+ {state.fills.map((fill) => (+ <rect+ key={fill.id}+ x={fill.x}+ y={fill.y}+ width={fill.width}+ height={fill.height}+ fill={palette[fill.slot]}+ />+ ))}+ {state.field ? (+ <rect+ x={state.field.x}+ y={state.field.y}+ width={state.field.width}+ height={state.field.height}+ fill={fieldColor}+ />+ ) : null}+ </svg>+ {children == null ? null : (+ <div+ style={{+ ...layer,+ clipPath: getMondrianSplitClip(state.field, width, height),+ }}+ >+ {children}+ </div>+ )}+ <svg+ width="100%"+ height="100%"+ viewBox={viewBox}+ preserveAspectRatio="none"+ role="img"+ aria-label="De Stijl grid"+ style={layer}+ >+ {state.lines.map((line) => (+ <rect+ key={line.id}+ x={line.x}+ y={line.y}+ width={line.width}+ height={line.height}+ fill={lineColor}+ />+ ))}+ </svg>+ </div>+ );+}diff --git a/registry/remocn/outline-trace/__tests__/outline-trace.test.ts b/registry/remocn/outline-trace/__tests__/outline-trace.test.tsnew file mode 100644index 00000000..faa8b127--- /dev/null+++ b/registry/remocn/outline-trace/__tests__/outline-trace.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getOutlineContours,+ getOutlineTraceLength,+ getOutlineTraceLetter,+ getOutlineTraceTime,+ outlineTraceDefaults,+ outlineTraceTiming,+ type PathCommand,+} from "..";+import { outlineTraceConfig } from "../config";++const square = (x: number, y: number, size: number): PathCommand[] => [+ { type: "M", x, y },+ { type: "L", x: x + size, y },+ { type: "L", x: x + size, y: y + size },+ { type: "L", x, y: y + size },+ { type: "Z" },+];++describe("outline-trace contours", () => {+ it("splits commands into closed contours with their boxes", () => {+ const contours = getOutlineContours([+ ...square(0, 0, 10),+ ...square(20, 0, 5),+ ]);+ expect(contours).toHaveLength(2);+ expect(contours[0].d).toBe("M0 0L10 0L10 10L0 10Z");+ expect(contours[0].box).toEqual({ x0: 0, y0: 0, x1: 10, y1: 10 });+ expect(contours[1].box).toEqual({ x0: 20, y0: 0, x1: 25, y1: 5 });+ });++ it("marks a contour inside another as a counter", () => {+ const contours = getOutlineContours([+ ...square(0, 0, 10),+ ...square(3, 3, 4),+ ]);+ expect(contours.map((c) => c.counter)).toEqual([false, true]);+ });++ it("keeps curve control points in the box and in the path", () => {+ const [contour] = getOutlineContours([+ { type: "M", x: 0, y: 0 },+ { type: "Q", x1: 5, y1: -8, x: 10, y: 0 },+ { type: "C", x1: 12, y1: 4, x2: 8, y2: 6, x: 0, y: 0 },+ { type: "Z" },+ ]);+ expect(contour.d).toBe("M0 0Q5 -8 10 0C12 4 8 6 0 0Z");+ expect(contour.box).toEqual({ x0: 0, y0: -8, x1: 12, y1: 6 });+ });++ it("closes a contour that ends without Z", () => {+ const contours = getOutlineContours(square(0, 0, 4).slice(0, 4));+ expect(contours).toHaveLength(1);+ expect(contours[0].d.endsWith("Z")).toBe(true);+ });+});++describe("outline-trace timeline", () => {+ it("draws the outer contour, then the counters, then fills", () => {+ expect(getOutlineTraceLetter(0, 0)).toEqual({+ outer: 0,+ counter: 0,+ fill: 0,+ });+ const mid = getOutlineTraceLetter(9, 0);+ expect(mid.outer).toBeCloseTo(0.5, 6);+ expect(mid.counter).toBeLessThan(mid.outer);+ expect(mid.fill).toBe(0);+ expect(getOutlineTraceLetter(18, 0).outer).toBe(1);+ expect(getOutlineTraceLetter(22, 0).counter).toBe(1);+ expect(getOutlineTraceLetter(26, 0)).toEqual({+ outer: 1,+ counter: 1,+ fill: 1,+ });+ });++ it("staggers letters", () => {+ const first = getOutlineTraceLetter(10, 0);+ const third = getOutlineTraceLetter(10, 2);+ expect(third.outer).toBeLessThan(first.outer);+ expect(getOutlineTraceLetter(10 + 6, 2)).toEqual(first);+ expect(getOutlineTraceLetter(10, 2, 0)).toEqual(first);+ });++ it("ends when the last letter has filled", () => {+ const count = Array.from(outlineTraceDefaults.text).length;+ const length = getOutlineTraceLength(count);+ expect(length).toBe(6 * 3 + outlineTraceTiming.fill[1]);+ expect(getOutlineTraceLetter(length, count - 1).fill).toBe(1);+ expect(getOutlineTraceLetter(length - 1, count - 1).fill).toBeLessThan(1);+ });++ it("maps frames onto the 30 fps timeline", () => {+ expect(getOutlineTraceTime(30)).toBe(30);+ expect(getOutlineTraceTime(60, { fps: 60 })).toBe(30);+ expect(getOutlineTraceTime(10, { speed: 2 })).toBe(20);+ });+});++describe("outline-trace config", () => {+ it("previews dark type on the reel's orange field", () => {+ const defaults = getDefaults(+ resolveControls("outline-trace", outlineTraceConfig.controls),+ );+ expect(defaults.text).toBe(outlineTraceDefaults.text);+ expect(defaults.fontSize).toBe(outlineTraceDefaults.fontSize);+ expect(defaults.strokeWidth).toBe(outlineTraceDefaults.strokeWidth);+ expect(defaults.stagger).toBe(outlineTraceDefaults.stagger);+ expect(defaults.fill).toBe(true);+ expect(defaults.keepStroke).toBe(false);+ expect(outlineTraceConfig.durationInFrames).toBeGreaterThan(+ getOutlineTraceLength(Array.from(outlineTraceDefaults.text).length),+ );+ });+});diff --git a/registry/remocn/outline-trace/config.ts b/registry/remocn/outline-trace/config.tsnew file mode 100644index 00000000..cba65a0c--- /dev/null+++ b/registry/remocn/outline-trace/config.ts@@ -0,0 +1,45 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";++export const outlineTraceConfig: ComponentConfig = {+ componentName: "OutlineTrace",+ importPath: "@/components/remocn/outline-trace",+ controls: {+ text: { type: "text-content", default: "Outline", description: "Text" },+ color: { type: "color", default: "#111111", description: "Fill" },+ strokeColor: { type: "color", default: "#111111", description: "Stroke" },+ fontSize: {+ type: "number",+ default: 150,+ min: 60,+ max: 300,+ step: 2,+ description: "Font size",+ hiddenFromList: false,+ },+ strokeWidth: {+ type: "number",+ default: 2.5,+ min: 0.5,+ max: 8,+ step: 0.5,+ description: "Stroke width",+ hiddenFromList: false,+ },+ stagger: {+ type: "number",+ default: 3,+ min: 0,+ max: 12,+ step: 1,+ description: "Letter stagger",+ hiddenFromList: false,+ },+ fill: { type: "boolean", default: true, description: "Fill" },+ keepStroke: { type: "boolean", default: false, description: "Keep stroke" },+ },+ durationInFrames: 75,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#ff4d1a" },+};diff --git a/registry/remocn/outline-trace/index.tsx b/registry/remocn/outline-trace/index.tsxnew file mode 100644index 00000000..1d2f5710--- /dev/null+++ b/registry/remocn/outline-trace/index.tsx@@ -0,0 +1,390 @@+"use client";++import { type Font, parse } from "opentype.js";+import { useEffect, useId, useState } from "react";+import {+ continueRender,+ delayRender,+ Easing,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+} from "remotion";++export interface OutlineTraceProps {+ text?: string;+ fontUrl?: string;+ fontSize?: number;+ color?: string;+ strokeColor?: string;+ strokeWidth?: number;+ stagger?: number;+ fill?: boolean;+ keepStroke?: boolean;+ speed?: number;+ className?: string;+}++/** Static Inter ExtraBold (800) from Google Fonts. */+export const interExtraBoldTtf =+ "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuDyYMZg.ttf";++export const outlineTraceDefaults = {+ text: "Outline",+ fontUrl: interExtraBoldTtf,+ fontSize: 150,+ color: "#fafafa",+ strokeColor: "",+ strokeWidth: 2.5,+ stagger: 3,+ fill: true,+ keepStroke: false,+ speed: 1,+} satisfies Required<Omit<OutlineTraceProps, "className">>;++/** Per-letter beats on the 30 fps clock, relative to the letter's start. */+export const outlineTraceTiming = {+ outer: [0, 18],+ counter: [4, 18],+ fill: [14, 26],+} as const;++const CLAMP = {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+} as const;++const easeInOutCubic = Easing.inOut(Easing.cubic);+const easeOutCubic = Easing.out(Easing.cubic);++function finite(value: number | undefined, fallback: number) {+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;+}++/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */+export function getOutlineTraceTime(+ frame: number,+ options: { fps?: number; speed?: number } = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const speed = Math.max(0, finite(options.speed, 1));+ return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;+}++export interface OutlineTraceLetterState {+ /** Trim progress of the outer contours, 0..1. */+ outer: number;+ /** Trim progress of the counters, 0..1. */+ counter: number;+ /** Share of the glyph box the fill has risen through, 0..1. */+ fill: number;+}++export function getOutlineTraceLetter(+ t: number,+ index: number,+ stagger = outlineTraceDefaults.stagger,+): OutlineTraceLetterState {+ const u = t - index * Math.max(0, finite(stagger, 3));+ const { outer, counter, fill } = outlineTraceTiming;+ return {+ outer: interpolate(u, [...outer], [0, 1], {+ ...CLAMP,+ easing: easeInOutCubic,+ }),+ counter: interpolate(u, [...counter], [0, 1], {+ ...CLAMP,+ easing: easeInOutCubic,+ }),+ fill: interpolate(u, [...fill], [0, 1], { ...CLAMP, easing: easeOutCubic }),+ };+}++/** Frame where the last of `count` letters has filled. */+export function getOutlineTraceLength(+ count: number,+ stagger = outlineTraceDefaults.stagger,+) {+ const last = Math.max(0, count - 1) * Math.max(0, finite(stagger, 3));+ return Math.ceil(last + outlineTraceTiming.fill[1]);+}++export interface PathCommand {+ type: string;+ x?: number;+ y?: number;+ x1?: number;+ y1?: number;+ x2?: number;+ y2?: number;+}++export interface Box {+ x0: number;+ y0: number;+ x1: number;+ y1: number;+}++export interface OutlineContour {+ d: string;+ box: Box;+ /** True for a hole inside another contour of the same glyph. */+ counter: boolean;+}++const fmt = (n: number) => Number(n.toFixed(2));++/**+ * Splits glyph path commands into closed contours and marks the counters:+ * contours whose box lies inside another contour's box.+ */+export function getOutlineContours(commands: readonly PathCommand[]) {+ const raw: { d: string; box: Box }[] = [];+ let d = "";+ let box: Box | null = null;+ const grow = (x = 0, y = 0) => {+ if (!box) box = { x0: x, y0: y, x1: x, y1: y };+ else {+ box.x0 = Math.min(box.x0, x);+ box.y0 = Math.min(box.y0, y);+ box.x1 = Math.max(box.x1, x);+ box.y1 = Math.max(box.y1, y);+ }+ };+ const close = () => {+ if (d && box) raw.push({ d: `${d}Z`, box });+ d = "";+ box = null;+ };+ for (const c of commands) {+ if (c.type === "M") {+ close();+ d = `M${fmt(c.x ?? 0)} ${fmt(c.y ?? 0)}`;+ grow(c.x, c.y);+ } else if (c.type === "L") {+ d += `L${fmt(c.x ?? 0)} ${fmt(c.y ?? 0)}`;+ grow(c.x, c.y);+ } else if (c.type === "Q") {+ d += `Q${fmt(c.x1 ?? 0)} ${fmt(c.y1 ?? 0)} ${fmt(c.x ?? 0)} ${fmt(c.y ?? 0)}`;+ grow(c.x1, c.y1);+ grow(c.x, c.y);+ } else if (c.type === "C") {+ d += `C${fmt(c.x1 ?? 0)} ${fmt(c.y1 ?? 0)} ${fmt(c.x2 ?? 0)} ${fmt(c.y2 ?? 0)} ${fmt(c.x ?? 0)} ${fmt(c.y ?? 0)}`;+ grow(c.x1, c.y1);+ grow(c.x2, c.y2);+ grow(c.x, c.y);+ } else if (c.type === "Z") {+ close();+ }+ }+ close();+ const inside = (a: Box, b: Box) =>+ a !== b && a.x0 >= b.x0 && a.y0 >= b.y0 && a.x1 <= b.x1 && a.y1 <= b.y1;+ return raw.map(+ (c): OutlineContour => ({+ ...c,+ counter: raw.some((other) => inside(c.box, other.box)),+ }),+ );+}++export interface OutlineGlyph {+ contours: OutlineContour[];+ box: Box | null;+}++/**+ * Lays out `text` in reference px with the baseline at y = 0. Glyphs are+ * looked up per character: full shaping runs GSUB lookups that opentype.js+ * does not support in every font.+ */+export function layoutOutlineGlyphs(+ font: Font,+ text: string,+ fontSize: number,+) {+ const scale = fontSize / font.unitsPerEm;+ const glyphs = Array.from(text).map((char) => font.charToGlyph(char));+ let x = 0;+ const letters: OutlineGlyph[] = glyphs.map((glyph, i) => {+ if (i > 0) x += font.getKerningValue(glyphs[i - 1], glyph) * scale;+ const contours = getOutlineContours(glyph.getPath(x, 0, fontSize).commands);+ x += (glyph.advanceWidth ?? 0) * scale;+ const box = contours.reduce<Box | null>(+ (acc, c) =>+ acc+ ? {+ x0: Math.min(acc.x0, c.box.x0),+ y0: Math.min(acc.y0, c.box.y0),+ x1: Math.max(acc.x1, c.box.x1),+ y1: Math.max(acc.y1, c.box.y1),+ }+ : { ...c.box },+ null,+ );+ return { contours, box };+ });+ const os2 = font.tables.os2 as { sCapHeight?: number } | undefined;+ const capHeight =+ ((os2?.sCapHeight ?? font.unitsPerEm * 0.7) * fontSize) / font.unitsPerEm;+ return { letters, width: x, capHeight };+}++const fontCache = new Map<string, Promise<Font>>();++function loadOutlineFont(url: string) {+ let pending = fontCache.get(url);+ if (!pending) {+ pending = fetch(url)+ .then((res) => res.arrayBuffer())+ .then((buffer) => parse(buffer));+ fontCache.set(url, pending);+ pending.catch(() => fontCache.delete(url));+ }+ return pending;+}++function useOutlineFont(url: string) {+ const [font, setFont] = useState<Font | null>(null);++ useEffect(() => {+ const handle = delayRender(`outline-trace: loading ${url}`);+ let released = false;+ const release = () => {+ if (released) return;+ released = true;+ continueRender(handle);+ };+ loadOutlineFont(url).then((parsed) => {+ if (!released) setFont(parsed);+ release();+ }, release);+ return release;+ }, [url]);++ return font;+}++export function OutlineTrace({+ text = outlineTraceDefaults.text,+ fontUrl = outlineTraceDefaults.fontUrl,+ fontSize = outlineTraceDefaults.fontSize,+ color = outlineTraceDefaults.color,+ strokeColor = outlineTraceDefaults.strokeColor,+ strokeWidth = outlineTraceDefaults.strokeWidth,+ stagger = outlineTraceDefaults.stagger,+ fill = outlineTraceDefaults.fill,+ keepStroke = outlineTraceDefaults.keepStroke,+ speed = outlineTraceDefaults.speed,+ className,+}: OutlineTraceProps) {+ const frame = useCurrentFrame();+ const { fps, width, height } = useVideoConfig();+ const id = `outline-trace-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;+ const font = useOutlineFont(fontUrl);+ if (!font) return null;++ const unit = height / 720;+ const t = getOutlineTraceTime(frame, { fps, speed });+ const layout = layoutOutlineGlyphs(font, text, fontSize);+ const originX = (width - layout.width * unit) / 2;+ const baseline = (height + layout.capHeight * unit) / 2;+ const stroke = strokeColor || color;++ return (+ <div+ className={className}+ style={{ position: "absolute", inset: 0, overflow: "hidden" }}+ >+ <svg+ width="100%"+ height="100%"+ viewBox={`0 0 ${width} ${height}`}+ style={{ display: "block" }}+ >+ <g transform={`translate(${originX} ${baseline}) scale(${unit})`}>+ <filter id={`${id}-erode`}>+ <feMorphology operator="erode" radius={strokeWidth / 2} />+ </filter>+ {layout.letters.map((letter, i) => {+ if (!letter.box) return null;+ const state = getOutlineTraceLetter(t, i, stagger);+ const box = letter.box;+ const tall = box.y1 - box.y0 + 2 * strokeWidth;+ const rise = tall * (fill ? state.fill : 0);+ const strokeOpacity = fill && !keepStroke ? 1 - state.fill : 1;+ const whole = letter.contours.map((c) => c.d).join("");+ const margin = 4 * strokeWidth;+ return (+ <g key={i}>+ {/* Static instances of variable fonts keep overlapping+ contours (the bar of a t crosses its stem). The mask hides+ stroke that runs inside the glyph's filled silhouette. */}+ <mask+ id={`${id}-mask-${i}`}+ maskUnits="userSpaceOnUse"+ x={box.x0 - margin}+ y={box.y0 - margin}+ width={box.x1 - box.x0 + 2 * margin}+ height={box.y1 - box.y0 + 2 * margin}+ >+ <rect+ x={box.x0 - margin}+ y={box.y0 - margin}+ width={box.x1 - box.x0 + 2 * margin}+ height={box.y1 - box.y0 + 2 * margin}+ fill="#ffffff"+ />+ <path d={whole} fill="#000000" filter={`url(#${id}-erode)`} />+ </mask>+ {fill && state.fill > 0 ? (+ <>+ <clipPath id={`${id}-${i}`}>+ <rect+ x={box.x0 - strokeWidth}+ y={box.y1 + strokeWidth - rise}+ width={box.x1 - box.x0 + 2 * strokeWidth}+ height={rise}+ />+ </clipPath>+ <path+ d={whole}+ fill={color}+ clipPath={`url(#${id}-${i})`}+ />+ </>+ ) : null}+ {strokeOpacity > 0 ? (+ <g mask={`url(#${id}-mask-${i})`}>+ {letter.contours.map((contour, k) => {+ const progress = contour.counter+ ? state.counter+ : state.outer;+ if (progress <= 0) return null;+ return (+ <path+ key={k}+ d={contour.d}+ pathLength={1}+ fill="none"+ stroke={stroke}+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeDasharray="1 1"+ strokeDashoffset={1 - progress}+ opacity={strokeOpacity}+ />+ );+ })}+ </g>+ ) : null}+ </g>+ );+ })}+ </g>+ </svg>+ </div>+ );+}diff --git a/registry/remocn/path-ride/__tests__/path-ride.test.ts b/registry/remocn/path-ride/__tests__/path-ride.test.tsnew file mode 100644index 00000000..024f7040--- /dev/null+++ b/registry/remocn/path-ride/__tests__/path-ride.test.ts@@ -0,0 +1,129 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getPathRideArc,+ getPathRideCenters,+ getPathRideFade,+ getPathRideHead,+ getPathRideLine,+ getPathRidePoint,+ getPathRideStraighten,+ getPathRideTail,+ getPathRideTime,+ getPathSample,+ pathRideDefaults,+ pathRideLength,+ samplePath,+} from "..";+import { pathRideConfig } from "../config";++const LINE = samplePath("M 0 0 L 100 0", 11);+const STRAIGHT = { start: 20, left: 300, baseline: 400 };++describe("path-ride sampling", () => {+ it("samples points and unit tangents at even arc lengths", () => {+ expect(LINE.length).toBeCloseTo(100, 6);+ expect(LINE.points).toHaveLength(11);+ expect(LINE.points[5].x).toBeCloseTo(50, 6);+ const mid = getPathSample(LINE, 55);+ expect(mid.x).toBeCloseTo(55, 6);+ expect(mid.y).toBeCloseTo(0, 6);+ expect(mid.tx).toBeCloseTo(1, 6);+ expect(mid.ty).toBeCloseTo(0, 6);+ });++ it("clamps arc lengths to the path", () => {+ expect(getPathSample(LINE, -10).x).toBeCloseTo(0, 6);+ expect(getPathSample(LINE, 500).x).toBeCloseTo(100, 6);+ });++ it("measures the default curve", () => {+ const curve = samplePath(pathRideDefaults.path);+ expect(curve.length).toBeGreaterThan(1200);+ for (const tangent of curve.tangents) {+ expect(Math.hypot(tangent.x, tangent.y)).toBeCloseTo(1, 6);+ }+ });+});++describe("path-ride pose", () => {+ it("lifts letters off the line along the normal", () => {+ const pose = getPathRidePoint(LINE, 40, 0, STRAIGHT, 5);+ expect(pose.x).toBeCloseTo(40, 6);+ expect(pose.y).toBeCloseTo(-5, 6);+ expect(pose.angle).toBeCloseTo(0, 6);+ });++ it("follows a vertical tangent", () => {+ const down = samplePath("M 0 0 L 0 100", 11);+ const pose = getPathRidePoint(down, 50, 0, STRAIGHT, 5);+ expect(pose.x).toBeCloseTo(5, 6);+ expect(pose.y).toBeCloseTo(50, 6);+ expect(pose.angle).toBeCloseTo(Math.PI / 2, 6);+ });++ it("maps arc length one to one onto the straight baseline", () => {+ const down = samplePath("M 0 0 L 0 100", 11);+ const a = getPathRidePoint(down, 30, 1, STRAIGHT);+ const b = getPathRidePoint(down, 70, 1, STRAIGHT);+ expect(a).toEqual({ x: 310, y: 400, angle: 0 });+ expect(b.x - a.x).toBeCloseTo(40, 6);+ });++ it("draws the line between the tail and the head", () => {+ expect(getPathRideLine(LINE, 50, 50, 0, STRAIGHT)).toBe("");+ const d = getPathRideLine(LINE, 25, 75, 0, STRAIGHT);+ expect(d.startsWith("M25.00 0.00")).toBe(true);+ expect(d.endsWith("L75.00 0.00")).toBe(true);+ });+});++describe("path-ride timeline", () => {+ it("draws, straightens, then erases", () => {+ expect(getPathRideHead(0, 1000)).toBe(0);+ expect(getPathRideHead(20, 1000)).toBeCloseTo(500, 6);+ expect(getPathRideHead(40, 1000)).toBe(1000);+ expect(getPathRideStraighten(50)).toBe(0);+ expect(getPathRideStraighten(68)).toBe(1);+ expect(getPathRideTail(52, 1000)).toBe(0);+ expect(getPathRideTail(70, 1000)).toBe(1000);+ expect(pathRideLength).toBe(70);+ });++ it("keeps the last letter closest to the head", () => {+ const { centers, width } = getPathRideCenters([10, 20, 30]);+ expect(centers).toEqual([5, 20, 45]);+ expect(width).toBe(60);+ const arcs = centers.map((c) => getPathRideArc(500, c, width, 40));+ expect(arcs[2]).toBeCloseTo(500 - 12 - 15, 10);+ expect(arcs[0]).toBeLessThan(arcs[1]);+ });++ it("fades letters in over their first half-em", () => {+ expect(getPathRideFade(-5, 40)).toBe(0);+ expect(getPathRideFade(10, 40)).toBe(0.5);+ expect(getPathRideFade(30, 40)).toBe(1);+ });++ it("maps frames onto the 30 fps timeline", () => {+ expect(getPathRideTime(30)).toBe(30);+ expect(getPathRideTime(60, { fps: 60 })).toBe(30);+ expect(getPathRideTime(10, { speed: 2 })).toBe(20);+ });+});++describe("path-ride config", () => {+ it("previews dark type on the reel's orange field", () => {+ const defaults = getDefaults(+ resolveControls("path-ride", pathRideConfig.controls),+ );+ expect(defaults).toMatchObject({+ text: pathRideDefaults.text,+ path: pathRideDefaults.path,+ fontSize: pathRideDefaults.fontSize,+ fontWeight: pathRideDefaults.fontWeight,+ lineWidth: pathRideDefaults.lineWidth,+ });+ expect(pathRideConfig.durationInFrames).toBeGreaterThan(pathRideLength);+ });+});diff --git a/registry/remocn/path-ride/config.ts b/registry/remocn/path-ride/config.tsnew file mode 100644index 00000000..cb009a41--- /dev/null+++ b/registry/remocn/path-ride/config.ts@@ -0,0 +1,53 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";+import { pathRideDefaultPath } from ".";++export const pathRideConfig: ComponentConfig = {+ componentName: "PathRide",+ importPath: "@/components/remocn/path-ride",+ controls: {+ text: {+ type: "text-content",+ default: "Follow the line",+ description: "Text",+ },+ path: {+ type: "text-content",+ default: pathRideDefaultPath,+ description: "Path (1280×720)",+ },+ color: { type: "color", default: "#111111", description: "Text color" },+ lineColor: { type: "color", default: "#fafafa", description: "Line color" },+ fontSize: {+ type: "number",+ default: 44,+ min: 16,+ max: 120,+ step: 1,+ description: "Font size",+ hiddenFromList: false,+ },+ fontWeight: {+ type: "number",+ default: 700,+ min: 100,+ max: 900,+ step: 50,+ description: "Weight",+ hiddenFromList: false,+ },+ lineWidth: {+ type: "number",+ default: 3,+ min: 1,+ max: 12,+ step: 0.5,+ description: "Line width",+ hiddenFromList: false,+ },+ },+ durationInFrames: 96,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#ff4d1a" },+};diff --git a/registry/remocn/path-ride/index.tsx b/registry/remocn/path-ride/index.tsxnew file mode 100644index 00000000..17f98bc3--- /dev/null+++ b/registry/remocn/path-ride/index.tsx@@ -0,0 +1,433 @@+"use client";++import { loadFont } from "@remotion/google-fonts/Inter";+import {+ getLength,+ getPointAtLength,+ getTangentAtLength,+} from "@remotion/paths";+import { useEffect, useMemo, useState } from "react";+import {+ continueRender,+ delayRender,+ Easing,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+} from "remotion";++const { fontFamily: INTER } = loadFont("normal", {+ weights: ["100", "900"],+ subsets: ["latin"],+});++export interface PathRideProps {+ text?: string;+ path?: string;+ fontSize?: number;+ fontWeight?: number;+ fontFamily?: string;+ color?: string;+ lineColor?: string;+ lineWidth?: number;+ speed?: number;+ className?: string;+}++/** An S-curve across a 1280×720 frame. */+export const pathRideDefaultPath =+ "M 120 560 C 360 120 560 120 640 360 S 920 600 1160 160";++export const pathRideDefaults = {+ text: "Follow the line",+ path: pathRideDefaultPath,+ fontSize: 44,+ fontWeight: 700,+ fontFamily: INTER,+ color: "#fafafa",+ lineColor: "#D97757",+ lineWidth: 3,+ speed: 1,+} satisfies Required<Omit<PathRideProps, "className">>;++/** Beats on the 30 fps clock. */+export const pathRideTiming = {+ draw: [0, 40],+ straighten: [50, 68],+ erase: [52, 70],+} as const;++/** Gap between the head and the last letter, in em. */+const LEAD = 0.3;+/** Letters fade in over this much arc length, in em. */+const FADE_IN = 0.5;+/** Extra lift of the baseline above the line, in em. */+const LIFT = 0.08;+/** Samples along the path; the line and the letters read positions from them. */+const SAMPLES = 400;+const MEASURE_SIZE = 100;+/** Inter's baseline and cap height in a `line-height: 1` box, until measured. */+const INTER_METRICS = { baseline: 0.8637, capHeight: 0.7275 };++const CLAMP = {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+} as const;++const easeInOutCubic = Easing.inOut(Easing.cubic);++function finite(value: number | undefined, fallback: number) {+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;+}++/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */+export function getPathRideTime(+ frame: number,+ options: { fps?: number; speed?: number } = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const speed = Math.max(0, finite(options.speed, 1));+ return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;+}++/** Arc length drawn so far. */+export function getPathRideHead(t: number, length: number) {+ return interpolate(t, [...pathRideTiming.draw], [0, length], {+ ...CLAMP,+ easing: easeInOutCubic,+ });+}++/** Arc length erased from the start. */+export function getPathRideTail(t: number, length: number) {+ return interpolate(t, [...pathRideTiming.erase], [0, length], {+ ...CLAMP,+ easing: easeInOutCubic,+ });+}++/** How far the curve has pulled straight, 0..1. */+export function getPathRideStraighten(t: number) {+ return interpolate(t, [...pathRideTiming.straighten], [0, 1], {+ ...CLAMP,+ easing: easeInOutCubic,+ });+}++/** Frame where the line has erased and the text rests on its baseline. */+export const pathRideLength = Math.max(+ pathRideTiming.straighten[1],+ pathRideTiming.erase[1],+);++/** Letter centers from the text start, and the total width. */+export function getPathRideCenters(advances: readonly number[]) {+ let x = 0;+ const centers = advances.map((a) => {+ const c = x + a / 2;+ x += a;+ return c;+ });+ return { centers, width: x };+}++/**+ * Arc length of a letter's center: it trails the head by the lead plus the+ * text after it, so the last letter follows the head most closely.+ */+export function getPathRideArc(+ head: number,+ center: number,+ width: number,+ fontSize: number,+) {+ return head - LEAD * fontSize - (width - center);+}++/** Opacity of a letter from how far onto the curve it has come. */+export function getPathRideFade(arc: number, fontSize: number) {+ return Math.min(1, Math.max(0, arc / (FADE_IN * fontSize)));+}++export interface Point {+ x: number;+ y: number;+}++export interface PathSamples {+ length: number;+ points: Point[];+ tangents: Point[];+}++/** Points and unit tangents at evenly spaced arc lengths along `path`. */+export function samplePath(path: string, count = SAMPLES): PathSamples {+ const length = getLength(path);+ const n = Math.max(2, Math.round(count));+ const points: Point[] = [];+ const tangents: Point[] = [];+ for (let i = 0; i < n; i++) {+ const at = (length * i) / (n - 1);+ // Both can come back null on a degenerate path; reuse the last sample.+ const p = getPointAtLength(path, at) ?? points[i - 1] ?? { x: 0, y: 0 };+ const tangent = getTangentAtLength(path, at) ??+ tangents[i - 1] ?? { x: 1, y: 0 };+ points.push({ x: p.x, y: p.y });+ tangents.push({ x: tangent.x, y: tangent.y });+ }+ return { length, points, tangents };+}++/** Position and unit tangent at arc length `s`, clamped to the path. */+export function getPathSample(samples: PathSamples, s: number) {+ const n = samples.points.length;+ const u = samples.length > 0 ? (s / samples.length) * (n - 1) : 0;+ const i = Math.min(n - 2, Math.max(0, Math.floor(u)));+ const f = Math.min(1, Math.max(0, u - i));+ const a = samples.points[i];+ const b = samples.points[i + 1];+ const ta = samples.tangents[i];+ const tb = samples.tangents[i + 1];+ const tx = ta.x + (tb.x - ta.x) * f;+ const ty = ta.y + (tb.y - ta.y) * f;+ const norm = Math.hypot(tx, ty) || 1;+ return {+ x: a.x + (b.x - a.x) * f,+ y: a.y + (b.y - a.y) * f,+ tx: tx / norm,+ ty: ty / norm,+ };+}++export interface PathRideStraight {+ /** Arc length that lands on the text's left edge. */+ start: number;+ /** Reference x of the text's left edge on the straight baseline. */+ left: number;+ /** Reference y of the straight baseline. */+ baseline: number;+}++export interface PathRidePose {+ x: number;+ y: number;+ angle: number;+}++/**+ * A point of the path pulled `k` of the way from the curve to the straight+ * baseline, lifted `lift` along its normal. Arc length maps to x one to one,+ * so the text keeps its spacing while the curve pulls taut.+ */+export function getPathRidePoint(+ samples: PathSamples,+ s: number,+ k: number,+ straight: PathRideStraight,+ lift = 0,+): PathRidePose {+ const p = getPathSample(samples, s);+ const x = p.x + (straight.left + (s - straight.start) - p.x) * k;+ const y = p.y + (straight.baseline - p.y) * k;+ const tx = p.tx + (1 - p.tx) * k;+ const ty = p.ty * (1 - k);+ const norm = Math.hypot(tx, ty) || 1;+ return {+ x: x + (ty / norm) * lift,+ y: y - (tx / norm) * lift,+ angle: Math.atan2(ty, tx),+ };+}++/** Polyline of the pulled path between two arc lengths. */+export function getPathRideLine(+ samples: PathSamples,+ from: number,+ to: number,+ k: number,+ straight: PathRideStraight,+) {+ if (to <= from) return "";+ const step = samples.length / (samples.points.length - 1);+ const stops = [from];+ for (let s = Math.ceil(from / step) * step; s < to; s += step) {+ if (s > from) stops.push(s);+ }+ stops.push(to);+ return stops+ .map((s, i) => {+ const p = getPathRidePoint(samples, s, k, straight);+ return `${i === 0 ? "M" : "L"}${p.x.toFixed(2)} ${p.y.toFixed(2)}`;+ })+ .join("");+}++function useMetrics(text: string, font: string, fallback: number) {+ const chars = Array.from(text);+ const key = chars.join("");+ const [metrics, setMetrics] = useState<{+ advances: number[];+ baseline: number;+ capHeight: number;+ } | null>(null);++ useEffect(() => {+ const handle = delayRender("path-ride: measuring the text");+ let released = false;+ const release = () => {+ if (released) return;+ released = true;+ continueRender(handle);+ };+ const measure = () => {+ if (released) return;+ const ctx = document.createElement("canvas").getContext("2d");+ if (ctx) {+ ctx.font = font;+ const m = ctx.measureText("H");+ const ascent = m.fontBoundingBoxAscent / MEASURE_SIZE;+ const descent = m.fontBoundingBoxDescent / MEASURE_SIZE;+ setMetrics({+ advances: Array.from(key).map(+ (c) => ctx.measureText(c).width / MEASURE_SIZE,+ ),+ baseline:+ ascent > 0+ ? (1 - (ascent + descent)) / 2 + ascent+ : INTER_METRICS.baseline,+ capHeight:+ m.actualBoundingBoxAscent > 0+ ? m.actualBoundingBoxAscent / MEASURE_SIZE+ : INTER_METRICS.capHeight,+ });+ }+ release();+ };+ document.fonts.load(font, key).then(measure, measure);+ return release;+ }, [key, font]);++ return (+ metrics ?? {+ advances: chars.map(() => fallback),+ baseline: INTER_METRICS.baseline,+ capHeight: INTER_METRICS.capHeight,+ }+ );+}++export function PathRide({+ text = pathRideDefaults.text,+ path = pathRideDefaults.path,+ fontSize = pathRideDefaults.fontSize,+ fontWeight = pathRideDefaults.fontWeight,+ fontFamily = pathRideDefaults.fontFamily,+ color = pathRideDefaults.color,+ lineColor = pathRideDefaults.lineColor,+ lineWidth = pathRideDefaults.lineWidth,+ speed = pathRideDefaults.speed,+ className,+}: PathRideProps) {+ const frame = useCurrentFrame();+ const { fps, width, height } = useVideoConfig();+ const unit = height / 720;+ const t = getPathRideTime(frame, { fps, speed });+ const metrics = useMetrics(+ text,+ `${fontWeight} ${MEASURE_SIZE}px ${fontFamily}`,+ 0.55,+ );+ const samples = useMemo(() => samplePath(path), [path]);+ const chars = Array.from(text);+ const advances = metrics.advances.map((a) => a * fontSize);+ const { centers, width: textWidth } = getPathRideCenters(advances);+ const length = samples.length;+ const head = getPathRideHead(t, length);+ const tail = getPathRideTail(t, length);+ const k = getPathRideStraighten(t);+ const lift = lineWidth / 2 + LIFT * fontSize;+ // The line settles `lift` below the text so the capitals center on the frame.+ const straight: PathRideStraight = {+ start: getPathRideArc(length, 0, textWidth, fontSize),+ left: 640 - textWidth / 2,+ baseline: 360 + (metrics.capHeight * fontSize) / 2 + lift,+ };+ const tip = getPathRidePoint(samples, head, k, straight);+ const tipOpacity = interpolate(+ head,+ [0, length * 0.02, length * 0.98, length],+ [0, 1, 1, 0],+ CLAMP,+ );+ // Reference space (1280×720, y down) mapped onto the composition.+ const toX = (x: number) => width / 2 + (x - 640) * unit;+ const toY = (y: number) => height / 2 + (y - 360) * unit;+ const size = fontSize * unit;+ const line = getPathRideLine(samples, tail, head, k, straight);++ return (+ <div+ className={className}+ style={{ position: "absolute", inset: 0, overflow: "hidden" }}+ >+ <svg+ width="100%"+ height="100%"+ viewBox={`0 0 ${width} ${height}`}+ style={{ position: "absolute", inset: 0 }}+ >+ <g+ transform={`translate(${toX(0)} ${toY(0)}) scale(${unit})`}+ fill="none"+ >+ {line ? (+ <path+ d={line}+ stroke={lineColor}+ strokeWidth={lineWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ ) : null}+ {tipOpacity > 0 ? (+ <circle+ cx={tip.x}+ cy={tip.y}+ r={lineWidth * 1.6}+ fill={lineColor}+ opacity={tipOpacity}+ />+ ) : null}+ </g>+ </svg>+ {chars.map((char, j) => {+ const arc = getPathRideArc(head, centers[j], textWidth, fontSize);+ const fade = getPathRideFade(arc, fontSize);+ if (fade <= 0) return null;+ const pose = getPathRidePoint(samples, arc, k, straight, lift);+ return (+ <span+ key={j}+ style={{+ position: "absolute",+ left: 0,+ top: 0,+ fontFamily,+ fontSize: size,+ lineHeight: 1,+ fontWeight,+ fontVariationSettings: `"wght" ${fontWeight}`,+ color,+ whiteSpace: "pre",+ opacity: fade,+ transformOrigin: "0 0",+ transform: `translate(${toX(pose.x)}px, ${toY(pose.y)}px) rotate(${pose.angle}rad) translate(-50%, ${-metrics.baseline * size}px)`,+ }}+ >+ {char}+ </span>+ );+ })}+ </div>+ );+}diff --git a/registry/remocn/period-drop/__tests__/period-drop.test.ts b/registry/remocn/period-drop/__tests__/period-drop.test.tsnew file mode 100644index 00000000..53bff4cc--- /dev/null+++ b/registry/remocn/period-drop/__tests__/period-drop.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getPeriodDropDot,+ getPeriodDropImpacts,+ getPeriodDropRise,+ getPeriodDropTime,+ periodDropDefaults,+ periodDropLength,+ periodDropTiming,+} from "..";+import { periodDropConfig } from "../config";++const sample = (from: number, to: number, step = 0.02) => {+ const out: number[] = [];+ for (let t = from; t <= to; t += step) out.push(t);+ return out;+};++describe("period-drop word", () => {+ it("raises each letter out of its line in turn", () => {+ expect(getPeriodDropRise(0, 0)).toBe(1);+ expect(getPeriodDropRise(12, 0)).toBe(0);+ expect(getPeriodDropRise(12, 1)).toBeGreaterThan(0);+ expect(getPeriodDropRise(14, 1)).toBe(0);+ const last = Array.from(periodDropDefaults.text).length - 1;+ expect(getPeriodDropRise(2 * last + 12, last)).toBe(0);+ expect(2 * last + 12).toBeLessThanOrEqual(periodDropTiming.dropStart + 2);+ });+});++describe("period-drop dot", () => {+ it("stays hidden above the frame until the drop", () => {+ expect(getPeriodDropDot(0).visible).toBe(false);+ expect(getPeriodDropDot(19.99).visible).toBe(false);+ const start = getPeriodDropDot(periodDropTiming.dropStart);+ expect(start.visible).toBe(true);+ expect(start.y).toBe(-1);+ });++ it("lands, then bounces twice with restitution 0.35", () => {+ const impacts = getPeriodDropImpacts();+ expect(impacts[0]).toBe(32);+ expect(impacts[1]).toBeCloseTo(40.4, 10);+ expect(impacts[2]).toBeCloseTo(43.34, 10);+ for (const t of impacts) expect(getPeriodDropDot(t).y).toBeCloseTo(0, 10);+ const apex = (from: number, to: number) =>+ Math.min(...sample(from, to).map((t) => getPeriodDropDot(t).y));+ expect(apex(impacts[0], impacts[1])).toBeCloseTo(-(0.35 ** 2), 3);+ expect(apex(impacts[1], impacts[2])).toBeCloseTo(-(0.35 ** 4), 3);+ });++ it("never sinks below the line", () => {+ for (const t of sample(0, 80, 0.05)) {+ expect(getPeriodDropDot(t).y).toBeLessThanOrEqual(0);+ }+ });++ it("stretches in flight and squashes on impact, within the caps", () => {+ let minY = Number.POSITIVE_INFINITY;+ let maxY = 0;+ let maxX = 0;+ for (const t of sample(20, 80, 0.01)) {+ const d = getPeriodDropDot(t);+ minY = Math.min(minY, d.scaleY);+ maxY = Math.max(maxY, d.scaleY);+ maxX = Math.max(maxX, d.scaleX);+ expect(d.scaleX * d.scaleY).toBeCloseTo(1, 10);+ }+ expect(minY).toBeCloseTo(0.78, 6);+ expect(maxY).toBeLessThanOrEqual(1.3);+ expect(maxY).toBeGreaterThan(1.29);+ expect(maxX).toBeLessThanOrEqual(1.3);+ expect(getPeriodDropDot(32).scaleY).toBeCloseTo(0.78, 10);+ expect(getPeriodDropDot(31.9).scaleY).toBeGreaterThan(1.25);+ });++ it("rests exactly from its length on", () => {+ for (const t of [periodDropLength, periodDropLength + 1, 120]) {+ expect(getPeriodDropDot(t)).toEqual({+ visible: true,+ y: 0,+ scaleX: 1,+ scaleY: 1,+ });+ }+ expect(getPeriodDropDot(periodDropLength - 1).scaleY).not.toBe(1);+ });+});++describe("period-drop time and config", () => {+ it("maps frames onto the 30 fps timeline", () => {+ expect(getPeriodDropTime(30)).toBe(30);+ expect(getPeriodDropTime(60, { fps: 60 })).toBe(30);+ expect(getPeriodDropTime(10, { speed: 2 })).toBe(20);+ });++ it("previews with the reel's orange dot", () => {+ const defaults = getDefaults(+ resolveControls("period-drop", periodDropConfig.controls),+ );+ expect(defaults.text).toBe(periodDropDefaults.text);+ expect(defaults.fontSize).toBe(periodDropDefaults.fontSize);+ expect(defaults.fontWeight).toBe(periodDropDefaults.fontWeight);+ expect(defaults.dotSize).toBe(periodDropDefaults.dotSize);+ expect(periodDropConfig.durationInFrames).toBeGreaterThan(periodDropLength);+ });+});diff --git a/registry/remocn/period-drop/config.ts b/registry/remocn/period-drop/config.tsnew file mode 100644index 00000000..788a56a6--- /dev/null+++ b/registry/remocn/period-drop/config.ts@@ -0,0 +1,43 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";++export const periodDropConfig: ComponentConfig = {+ componentName: "PeriodDrop",+ importPath: "@/components/remocn/period-drop",+ controls: {+ text: { type: "text-content", default: "remocn", description: "Text" },+ color: { type: "color", default: "#fafafa", description: "Text color" },+ dotColor: { type: "color", default: "#ff4d1a", description: "Dot color" },+ fontSize: {+ type: "number",+ default: 160,+ min: 60,+ max: 280,+ step: 2,+ description: "Font size",+ hiddenFromList: false,+ },+ fontWeight: {+ type: "number",+ default: 800,+ min: 100,+ max: 900,+ step: 50,+ description: "Weight",+ hiddenFromList: false,+ },+ dotSize: {+ type: "number",+ default: 0.2,+ min: 0.08,+ max: 0.5,+ step: 0.01,+ description: "Dot size (em)",+ hiddenFromList: false,+ },+ },+ durationInFrames: 75,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#0a0a0a" },+};diff --git a/registry/remocn/period-drop/index.tsx b/registry/remocn/period-drop/index.tsxnew file mode 100644index 00000000..8256c087--- /dev/null+++ b/registry/remocn/period-drop/index.tsx@@ -0,0 +1,228 @@+"use client";++import { loadFont } from "@remotion/google-fonts/Inter";+import { Easing, interpolate, useCurrentFrame, useVideoConfig } from "remotion";++const { fontFamily: INTER } = loadFont("normal", {+ weights: ["100", "900"],+ subsets: ["latin"],+});++export interface PeriodDropProps {+ text?: string;+ fontSize?: number;+ fontWeight?: number;+ fontFamily?: string;+ color?: string;+ dotColor?: string;+ dotSize?: number;+ speed?: number;+ className?: string;+}++export const periodDropDefaults = {+ text: "remocn",+ fontSize: 160,+ fontWeight: 800,+ fontFamily: INTER,+ color: "#fafafa",+ dotColor: "#D97757",+ dotSize: 0.2,+ speed: 1,+} satisfies Required<Omit<PeriodDropProps, "className">>;++/** Frame where the dot has come to rest, squash included. */+export const periodDropLength = 47;++/** Timeline constants on the 30 fps clock. */+export const periodDropTiming = {+ riseFrames: 12,+ riseStagger: 2,+ dropStart: 20,+ fallFrames: 12,+ restitution: 0.35,+ bounces: 2,+ /** Drop height as a share of the composition height. */+ dropHeight: 0.62,+ /** `scaleY` at full speed. */+ stretch: 0.3,+ /** `scaleY` lost at a full-speed impact. */+ squash: 0.22,+ /** Frames for an impact squash to decay by 1/e. */+ recover: 1.1,+} as const;++const CLAMP = {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+} as const;++const easeOutQuart = Easing.out(Easing.poly(4));++function finite(value: number | undefined, fallback: number) {+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;+}++/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */+export function getPeriodDropTime(+ frame: number,+ options: { fps?: number; speed?: number } = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const speed = Math.max(0, finite(options.speed, 1));+ return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;+}++/** How far letter `index` still sits below its line, 1 → 0. */+export function getPeriodDropRise(t: number, index: number) {+ const start = periodDropTiming.riseStagger * index;+ return interpolate(t, [start, start + periodDropTiming.riseFrames], [1, 0], {+ ...CLAMP,+ easing: easeOutQuart,+ });+}++/** Frames at which the dot touches the line: the landing, then each bounce. */+export function getPeriodDropImpacts() {+ const { dropStart, fallFrames, restitution, bounces } = periodDropTiming;+ const impacts = [dropStart + fallFrames];+ for (let n = 1; n <= bounces; n++) {+ impacts.push(impacts[n - 1] + 2 * restitution ** n * fallFrames);+ }+ return impacts;+}++export interface PeriodDropDot {+ visible: boolean;+ /** Height above the rest point as a share of the drop, 0 at rest, −1 at the start. */+ y: number;+ scaleX: number;+ scaleY: number;+}++/**+ * The dot's fall and bounces. Heights are shares of the drop height, time is+ * in 30 fps frames. Gravity is set by the fall: `g = 2 / fall²`, so the+ * landing speed is `2 / fall`. Each bounce leaves at `restitution` times the+ * previous speed, and the squash of each impact scales with it.+ */+export function getPeriodDropDot(t: number): PeriodDropDot {+ const { dropStart, fallFrames, restitution, stretch, squash, recover } =+ periodDropTiming;+ if (t < dropStart) return { visible: false, y: -1, scaleX: 1, scaleY: 1 };+ const g = 2 / (fallFrames * fallFrames);+ const landing = g * fallFrames;+ const impacts = getPeriodDropImpacts();++ let y = 0;+ let speed = 0;+ let deform = 0;+ if (t < impacts[0]) {+ const u = t - dropStart;+ y = -1 + 0.5 * g * u * u;+ speed = g * u;+ deform = speed / landing;+ } else {+ let n = impacts.length - 1;+ while (n > 0 && t < impacts[n]) n--;+ const tau = t - impacts[n];+ const bounce = n + 1;+ const launch =+ bounce < impacts.length ? restitution ** bounce * landing : 0;+ const flight = launch > 0 ? (2 * launch) / g : 0;+ if (tau < flight) {+ y = -(launch * tau - 0.5 * g * tau * tau);+ speed = Math.abs(launch - g * tau);+ }+ const impact = restitution ** n;+ const decay = Math.exp(-tau / recover);+ deform = -impact * decay + (1 - decay) * (speed / landing);+ }+ // Snap the last imperceptible wobble so the dot rests exactly.+ if (Math.abs(deform) < 0.005) deform = 0;++ const scaleY =+ deform >= 0 ? 1 + stretch * deform : 1 + squash * Math.max(-1, deform);+ return { visible: true, y: Math.min(0, y), scaleX: 1 / scaleY, scaleY };+}++export function PeriodDrop({+ text = periodDropDefaults.text,+ fontSize = periodDropDefaults.fontSize,+ fontWeight = periodDropDefaults.fontWeight,+ fontFamily = periodDropDefaults.fontFamily,+ color = periodDropDefaults.color,+ dotColor = periodDropDefaults.dotColor,+ dotSize = periodDropDefaults.dotSize,+ speed = periodDropDefaults.speed,+ className,+}: PeriodDropProps) {+ const frame = useCurrentFrame();+ const { fps, height } = useVideoConfig();+ const unit = height / 720;+ const t = getPeriodDropTime(frame, { fps, speed });+ const dot = getPeriodDropDot(t);+ const drop = periodDropTiming.dropHeight * height;++ return (+ <div+ className={className}+ style={{+ position: "absolute",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ overflow: "hidden",+ }}+ >+ <div+ style={{+ fontFamily,+ fontSize: fontSize * unit,+ lineHeight: 1,+ fontWeight,+ fontVariationSettings: `"wght" ${fontWeight}`,+ color,+ whiteSpace: "pre",+ }}+ >+ {Array.from(text).map((char, i) => (+ <span+ key={i}+ style={{+ display: "inline-block",+ overflow: "hidden",+ // Extend the clip below the line box so descenders survive.+ paddingBottom: "0.15em",+ marginBottom: "-0.15em",+ verticalAlign: "top",+ }}+ >+ <span+ style={{+ display: "inline-block",+ transform: `translateY(${getPeriodDropRise(t, i) * 115}%)`,+ }}+ >+ {char}+ </span>+ </span>+ ))}+ <span+ style={{+ display: "inline-block",+ width: `${dotSize}em`,+ height: `${dotSize}em`,+ marginLeft: "0.04em",+ borderRadius: "50%",+ background: dotColor,+ visibility: dot.visible ? "visible" : "hidden",+ transformOrigin: "50% 100%",+ transform: `translateY(${dot.y * drop}px) scale(${dot.scaleX}, ${dot.scaleY})`,+ }}+ />+ </div>+ </div>+ );+}diff --git a/registry/remocn/registry.json b/registry/remocn/registry.jsonindex a7bb42c8..ff19c09a 100644--- a/registry/remocn/registry.json+++ b/registry/remocn/registry.json@@ -2305,6 +2305,272 @@"target": "components/remocn/shader-spiral-pass.tsx"}]+ },+ {+ "name": "truchet-flip",+ "type": "registry:component",+ "title": "Truchet Flip",+ "description": "Quarter-circle Truchet tiles snap a quarter turn as a wave crosses the grid, rerouting continuous lines until they settle into concentric loops, a calm field, or a circle of small rings.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "truchet-flip/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/truchet-flip.tsx"+ }+ ]+ },+ {+ "name": "mondrian-split",+ "type": "registry:component",+ "title": "Mondrian Split",+ "description": "Black lines cut the frame into a seeded De Stijl grid, primaries wipe into its cells, the grid reflows like rubber, and one cell pushes its own lines out past the edges to become a clean color field or the next scene.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "mondrian-split/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/mondrian-split.tsx"+ }+ ]+ },+ {+ "name": "bauhaus-build",+ "type": "registry:component",+ "title": "Bauhaus Build",+ "description": "Flat Bauhaus circles, arcs, squares and bars tumble corner over corner on a hidden grid into an asymmetric frieze, then rebuild into two friezes around an open band for the title.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "bauhaus-build/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/bauhaus-build.tsx"+ }+ ]+ },+ {+ "name": "squiggle",+ "type": "registry:component",+ "title": "Squiggle",+ "description": "A flat line draws itself along a straight course as a traveling wave whose crests swim forward and calm down as the head runs out, in wave, zigzag, loop or coil shapes, then erases toward its end point.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "squiggle/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/squiggle.tsx"+ }+ ]+ },+ {+ "name": "speed-lines",+ "type": "registry:component",+ "title": "Speed Lines",+ "description": "Parallel streaks trail an element as it flies in at its real speed, the element stretching with that speed and landing with a squash and a small bounce as the streaks die, or radial lines rush in from the frame edges and snap onto one point for a manga-style impact frame.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "speed-lines/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/speed-lines.tsx"+ }+ ]+ },+ {+ "name": "trim-burst",+ "type": "registry:component",+ "title": "Trim Burst",+ "description": "A ring of short straight strokes shoots out from a point like Trim Paths: each end races ahead on a hard-braking ease-out while its start holds, then chases it on a smoother ease-in-out, so every stroke grows, travels and zips shut at its outer distance.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "trim-burst/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/trim-burst.tsx"+ }+ ]+ },+ {+ "name": "keystroke",+ "type": "registry:component",+ "title": "Keystroke",+ "description": "Physical keycaps rise in for each shortcut, press in real order with the modifiers held while the letter taps, spring back with a small capped overshoot, and leave after an idle hold, firing on the same frames as the remocn-ui steps they trigger.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "keystroke/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/keystroke.tsx"+ }+ ]+ },+ {+ "name": "code-morph",+ "type": "registry:component",+ "title": "Code Morph",+ "description": "A flat code editor that morphs between versions of a file, gliding each surviving token to its new line and column while removed code dissolves and new code fades in.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "code-morph/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/code-morph.tsx"+ }+ ]+ },+ {+ "name": "agent-run",+ "type": "registry:component",+ "title": "Agent Run",+ "description": "Animated brand-neutral AI agent run — a Thinking status and short plan, tool calls whose spinners close into checks while a timer counts real seconds, then a markdown answer with citations and a code block that streams in irregular token bursts. Light/dark themes.",+ "dependencies": ["remotion"],+ "files": [+ {+ "path": "agent-run/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/agent-run.tsx"+ }+ ]+ },+ {+ "name": "selection-snap",+ "type": "registry:component",+ "title": "Selection Snap",+ "description": "A thin word in a loose viewfinder snaps into a design-tool selection while it goes from Thin to Black, pops its handles and counts up a size badge.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "selection-snap/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/selection-snap.tsx"+ }+ ]+ },+ {+ "name": "echo-stack",+ "type": "registry:component",+ "title": "Echo Stack",+ "description": "A word focuses in at the center while outline copies of it unfold above and below and keep drifting, like the one clear line on a spinning drum.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "echo-stack/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/echo-stack.tsx"+ }+ ]+ },+ {+ "name": "type-wall",+ "type": "registry:component",+ "title": "Type Wall",+ "description": "Rows of one word fill the frame, run in alternating directions at different speeds in heavy, narrow and outline faces, with an accent band through the middle.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "type-wall/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/type-wall.tsx"+ }+ ]+ },+ {+ "name": "ring-text",+ "type": "registry:component",+ "title": "Ring Text",+ "description": "Text runs around a tilted 3D band that spins, reading on the near side and mirrored on the far side.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "ring-text/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/ring-text.tsx"+ }+ ]+ },+ {+ "name": "period-drop",+ "type": "registry:component",+ "title": "Period Drop",+ "description": "A word rises out of its line, then a colored dot falls from above the frame, bounces with squash and stretch, and settles as the period.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "period-drop/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/period-drop.tsx"+ }+ ]+ },+ {+ "name": "outline-trace",+ "type": "registry:component",+ "title": "Outline Trace",+ "description": "Every glyph contour draws itself as a stroke, letter by letter, then the fill wipes up inside each letter and the stroke fades into it.",+ "dependencies": ["remotion", "opentype.js"],+ "files": [+ {+ "path": "outline-trace/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/outline-trace.tsx"+ }+ ]+ },+ {+ "name": "glyph-anatomy",+ "type": "registry:component",+ "title": "Glyph Anatomy",+ "description": "A word builds as in a font editor, with metric guides, anchors along each contour and Bézier handles that pull straight segments into curves before the glyphs fill.",+ "dependencies": ["remotion", "opentype.js", "@remotion/google-fonts"],+ "files": [+ {+ "path": "glyph-anatomy/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/glyph-anatomy.tsx"+ }+ ]+ },+ {+ "name": "stripe-type",+ "type": "registry:component",+ "title": "Stripe Type",+ "description": "A word cut into horizontal bands, as in the IBM logo, slides together from alternating sides and locks, then can pass on through.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "stripe-type/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/stripe-type.tsx"+ }+ ]+ },+ {+ "name": "path-ride",+ "type": "registry:component",+ "title": "Path Ride",+ "description": "A line draws itself along a curve with the text riding behind its head, then the curve pulls taut and the text settles on a straight, centered baseline.",+ "dependencies": ["remotion", "@remotion/google-fonts", "@remotion/paths"],+ "files": [+ {+ "path": "path-ride/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/path-ride.tsx"+ }+ ]+ },+ {+ "name": "type-repeater",+ "type": "registry:component",+ "title": "Type Repeater",+ "description": "An After Effects style repeater on a word, where copies unfold into a tunnel, a spiral or a fan behind it, breathe, then fold back into the word.",+ "dependencies": ["remotion", "@remotion/google-fonts"],+ "files": [+ {+ "path": "type-repeater/index.tsx",+ "type": "registry:component",+ "target": "components/remocn/type-repeater.tsx"+ }+ ]}]}diff --git a/registry/remocn/ring-text/__tests__/ring-text.test.ts b/registry/remocn/ring-text/__tests__/ring-text.test.tsnew file mode 100644index 00000000..1b2354f5--- /dev/null+++ b/registry/remocn/ring-text/__tests__/ring-text.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getRingTextLayout,+ getRingTextPose,+ getRingTextShade,+ getRingTextTime,+ getRingTextToken,+ ringTextDefaults,+ ringTextLength,+} from "..";+import { ringTextConfig } from "../config";++const TAU = 2 * Math.PI;++describe("ring-text token", () => {+ it("joins the text and separator with spaces", () => {+ expect(getRingTextToken("Hi", "•").join("")).toBe("Hi • ");+ expect(getRingTextToken("Hi", "").join("")).toBe("Hi ");+ expect(getRingTextToken("👋🏽", "").length).toBe(3);+ });+});++describe("ring-text layout", () => {+ const advances = [20, 12, 18, 10];++ it("repeats the token to fill the circumference and closes the band", () => {+ const layout = getRingTextLayout(advances, 100);+ const circumference = TAU * 100;+ expect(layout.repeats).toBe(Math.floor(circumference / 60));+ expect(layout.spacing).toBeGreaterThanOrEqual(0);+ const total = layout.panels.reduce((sum, p) => sum + p.width, 0);+ expect(total).toBeCloseTo(circumference, 6);+ expect(layout.panels).toHaveLength(layout.repeats * advances.length);+ });++ it("orders panels around one turn", () => {+ const { panels } = getRingTextLayout(advances, 100);+ let last = -1;+ for (const panel of panels) {+ expect(panel.angle).toBeGreaterThan(last);+ expect(panel.angle).toBeLessThan(TAU);+ last = panel.angle;+ }+ expect(panels[0].char).toBe(0);+ expect(panels[advances.length].char).toBe(0);+ });++ it("grows the radius when one lap of text is longer than the ring", () => {+ const layout = getRingTextLayout([400, 400], 50);+ expect(layout.repeats).toBe(1);+ expect(layout.spacing).toBe(0);+ expect(layout.radius).toBeCloseTo(800 / TAU, 10);+ });++ it("returns no panels for empty text", () => {+ expect(getRingTextLayout([], 100).panels).toEqual([]);+ expect(getRingTextLayout([0, 0], 100).panels).toEqual([]);+ });+});++describe("ring-text pose", () => {+ it("arrives spinning fast and settles to one turn per period", () => {+ const start = getRingTextPose(0);+ expect(start.spin).toBe(0);+ expect(start.scale).toBeCloseTo(0.85, 10);+ expect(start.opacity).toBe(0);+ const early = getRingTextPose(3).spin - getRingTextPose(0).spin;+ const cruise =+ getRingTextPose(ringTextLength + 10).spin -+ getRingTextPose(ringTextLength + 7).spin;+ expect(early).toBeGreaterThan(cruise * 2);+ expect(cruise).toBeCloseTo((3 * 360) / ringTextDefaults.period, 10);+ const settled = getRingTextPose(ringTextLength);+ expect(settled.scale).toBe(1);+ expect(settled.opacity).toBe(1);+ });++ it("wobbles the tilt by six degrees around its value", () => {+ let min = Number.POSITIVE_INFINITY;+ let max = Number.NEGATIVE_INFINITY;+ for (let t = 0; t < 300; t += 0.5) {+ const { tilt } = getRingTextPose(t);+ min = Math.min(min, tilt);+ max = Math.max(max, tilt);+ }+ expect(min).toBeCloseTo(ringTextDefaults.tilt - 6, 2);+ expect(max).toBeCloseTo(ringTextDefaults.tilt + 6, 2);+ });++ it("dims letters on the far side", () => {+ expect(getRingTextShade(0, 0)).toBe(1);+ expect(getRingTextShade(Math.PI, 0)).toBeCloseTo(0.55, 10);+ expect(getRingTextShade(Math.PI, 180)).toBe(1);+ });+});++describe("ring-text time and config", () => {+ it("maps frames onto the 30 fps timeline", () => {+ expect(getRingTextTime(30)).toBe(30);+ expect(getRingTextTime(60, { fps: 60 })).toBe(30);+ expect(getRingTextTime(10, { speed: 2 })).toBe(20);+ });++ it("previews on the reel's lime field", () => {+ const defaults = getDefaults(+ resolveControls("ring-text", ringTextConfig.controls),+ );+ expect(defaults.text).toBe(ringTextDefaults.text);+ expect(defaults.separator).toBe(ringTextDefaults.separator);+ expect(defaults.radius).toBe(ringTextDefaults.radius);+ expect(defaults.fontSize).toBe(ringTextDefaults.fontSize);+ expect(defaults.tilt).toBe(ringTextDefaults.tilt);+ expect(defaults.roll).toBe(ringTextDefaults.roll);+ expect(defaults.period).toBe(ringTextDefaults.period);+ });+});diff --git a/registry/remocn/ring-text/config.ts b/registry/remocn/ring-text/config.tsnew file mode 100644index 00000000..d6507e53--- /dev/null+++ b/registry/remocn/ring-text/config.ts@@ -0,0 +1,70 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";++export const ringTextConfig: ComponentConfig = {+ componentName: "RingText",+ importPath: "@/components/remocn/ring-text",+ controls: {+ text: {+ type: "text-content",+ default: "Type in motion",+ description: "Text",+ },+ separator: {+ type: "text-content",+ default: "•",+ description: "Separator",+ },+ color: { type: "color", default: "#d4ff1f", description: "Text color" },+ band: { type: "color", default: "#0a0a0a", description: "Band color" },+ radius: {+ type: "number",+ default: 210,+ min: 80,+ max: 340,+ step: 5,+ description: "Radius",+ hiddenFromList: false,+ },+ fontSize: {+ type: "number",+ default: 40,+ min: 16,+ max: 90,+ step: 1,+ description: "Font size",+ hiddenFromList: false,+ },+ tilt: {+ type: "number",+ default: 38,+ min: 0,+ max: 80,+ step: 1,+ description: "Tilt",+ hiddenFromList: false,+ },+ roll: {+ type: "number",+ default: -16,+ min: -60,+ max: 60,+ step: 1,+ description: "Roll",+ hiddenFromList: false,+ },+ period: {+ type: "number",+ default: 240,+ min: 60,+ max: 900,+ step: 10,+ description: "Frames per turn",+ hiddenFromList: false,+ },+ },+ durationInFrames: 180,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#d4ff1f" },+};diff --git a/registry/remocn/ring-text/index.tsx b/registry/remocn/ring-text/index.tsxnew file mode 100644index 00000000..8363aac0--- /dev/null+++ b/registry/remocn/ring-text/index.tsx@@ -0,0 +1,297 @@+"use client";++import { loadFont } from "@remotion/google-fonts/Inter";+import { useEffect, useState } from "react";+import {+ continueRender,+ delayRender,+ Easing,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+} from "remotion";++const { fontFamily: INTER } = loadFont("normal", {+ weights: ["100", "900"],+ subsets: ["latin"],+});++export interface RingTextProps {+ text?: string;+ separator?: string;+ radius?: number;+ fontSize?: number;+ fontWeight?: number;+ fontFamily?: string;+ color?: string;+ band?: string;+ tilt?: number;+ roll?: number;+ period?: number;+ speed?: number;+ className?: string;+}++export const ringTextDefaults = {+ text: "Type in motion",+ separator: "•",+ radius: 210,+ fontSize: 40,+ fontWeight: 800,+ fontFamily: INTER,+ color: "#fafafa",+ band: "#0a0a0a",+ tilt: 38,+ roll: -16,+ period: 240,+ speed: 1,+} satisfies Required<Omit<RingTextProps, "className">>;++/** Frame where the entrance has settled into the cruise spin. */+export const ringTextLength = 30;++/** Band height, in em. */+export const ringBandHeight = 1.5;++const ENTRANCE = 30;+const FADE = 12;+const START_SCALE = 0.85;+/** Extra turn, in degrees, that decays over the entrance. */+const ENTRANCE_SPIN = 90;+const WOBBLE = 6;+const WOBBLE_PERIOD = 150;+/** Letters on the far side of the ring dim to this opacity. */+const BACK_OPACITY = 0.55;+/** Advance per character, in em, until the face is measured. */+const FALLBACK_ADVANCE = 0.6;++const CLAMP = {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+} as const;++const easeOutCubic = Easing.out(Easing.cubic);++function finite(value: number | undefined, fallback: number) {+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;+}++/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */+export function getRingTextTime(+ frame: number,+ options: { fps?: number; speed?: number } = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const speed = Math.max(0, finite(options.speed, 1));+ return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;+}++/** The characters of one lap: the text, a space, the separator, a space. */+export function getRingTextToken(text: string, separator: string) {+ return Array.from(separator ? `${text} ${separator} ` : `${text} `);+}++export interface RingTextPanel {+ /** Index into the token. */+ char: number;+ /** Panel center around the ring, radians. */+ angle: number;+ /** Panel width, reference px. */+ width: number;+}++export interface RingTextLayout {+ radius: number;+ repeats: number;+ /** Extra space added to every character so the band closes, reference px. */+ spacing: number;+ panels: RingTextPanel[];+}++/**+ * Repeats the token as many times as fits the circumference and spreads the+ * remainder as letter spacing. A token longer than the ring grows the radius.+ */+export function getRingTextLayout(+ advances: readonly number[],+ radius: number,+): RingTextLayout {+ const tokenWidth = advances.reduce((sum, a) => sum + Math.max(0, a), 0);+ const count = advances.length;+ if (count === 0 || tokenWidth <= 0) {+ return { radius, repeats: 0, spacing: 0, panels: [] };+ }+ const circumference = Math.max(2 * Math.PI * Math.max(0, radius), tokenWidth);+ const repeats = Math.max(1, Math.floor(circumference / tokenWidth));+ const spacing = (circumference - repeats * tokenWidth) / (repeats * count);+ const panels: RingTextPanel[] = [];+ let travelled = 0;+ for (let r = 0; r < repeats; r++) {+ for (let char = 0; char < count; char++) {+ const width = Math.max(0, advances[char]) + spacing;+ panels.push({+ char,+ angle: (2 * Math.PI * (travelled + width / 2)) / circumference,+ width,+ });+ travelled += width;+ }+ }+ return {+ radius: circumference / (2 * Math.PI),+ repeats,+ spacing,+ panels,+ };+}++/** Ring pose at `t`: spin in degrees, tilt with its wobble, entrance scale and opacity. */+export function getRingTextPose(+ t: number,+ options: { period?: number; tilt?: number } = {},+) {+ const period = Math.max(1, finite(options.period, ringTextDefaults.period));+ const tilt = finite(options.tilt, ringTextDefaults.tilt);+ const settle = easeOutCubic(Math.min(1, Math.max(0, t / ENTRANCE)));+ return {+ spin: (360 * t) / period + ENTRANCE_SPIN * settle,+ tilt: tilt + WOBBLE * Math.sin((2 * Math.PI * t) / WOBBLE_PERIOD),+ scale: START_SCALE + (1 - START_SCALE) * settle,+ opacity: interpolate(t, [0, FADE], [0, 1], CLAMP),+ };+}++/** Letter opacity from how squarely its panel faces the camera. */+export function getRingTextShade(angle: number, spinDegrees: number) {+ const facing = Math.cos(angle - (spinDegrees * Math.PI) / 180);+ return BACK_OPACITY + ((1 - BACK_OPACITY) * (facing + 1)) / 2;+}++function useAdvances(chars: readonly string[], font: string, fallback: number) {+ const key = chars.join("");+ const [advances, setAdvances] = useState<number[] | null>(null);++ useEffect(() => {+ const handle = delayRender("ring-text: measuring the characters");+ let released = false;+ const release = () => {+ if (released) return;+ released = true;+ continueRender(handle);+ };+ const measure = () => {+ if (released) return;+ const ctx = document.createElement("canvas").getContext("2d");+ if (ctx) {+ ctx.font = font;+ setAdvances(Array.from(key).map((c) => ctx.measureText(c).width));+ }+ release();+ };+ document.fonts.load(font, key).then(measure, measure);+ return release;+ }, [key, font]);++ return advances ?? chars.map(() => fallback);+}++export function RingText({+ text = ringTextDefaults.text,+ separator = ringTextDefaults.separator,+ radius = ringTextDefaults.radius,+ fontSize = ringTextDefaults.fontSize,+ fontWeight = ringTextDefaults.fontWeight,+ fontFamily = ringTextDefaults.fontFamily,+ color = ringTextDefaults.color,+ band = ringTextDefaults.band,+ tilt = ringTextDefaults.tilt,+ roll = ringTextDefaults.roll,+ period = ringTextDefaults.period,+ speed = ringTextDefaults.speed,+ className,+}: RingTextProps) {+ const frame = useCurrentFrame();+ const { fps, height } = useVideoConfig();+ const unit = height / 720;+ const t = getRingTextTime(frame, { fps, speed });+ const chars = getRingTextToken(text, separator);+ const advances = useAdvances(+ chars,+ `${fontWeight} ${fontSize}px ${fontFamily}`,+ FALLBACK_ADVANCE * fontSize,+ );+ const layout = getRingTextLayout(advances, radius);+ const pose = getRingTextPose(t, { period, tilt });+ const bandHeight = ringBandHeight * fontSize * unit;+ // Adjacent flat panels meet at an angle and their antialiased edges let the+ // background through; bleeding each panel into its neighbors hides the seam.+ const bleed = 1.5 * Math.max(1, unit);++ return (+ <div+ className={className}+ style={{+ position: "absolute",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ overflow: "hidden",+ perspective: 1600 * unit,+ // Opacity lives here: on the preserve-3d ring it would flatten it.+ opacity: pose.opacity,+ }}+ >+ <div+ style={{+ position: "relative",+ width: 0,+ height: 0,+ transformStyle: "preserve-3d",+ // Negative tilt views the ring from above: the near side is at the+ // bottom and reads left to right, the far side shows it mirrored.+ transform: `scale(${pose.scale}) rotateZ(${roll}deg) rotateX(${-pose.tilt}deg) rotateY(${-pose.spin}deg)`,+ }}+ >+ {layout.panels.map((panel, i) => {+ const width = panel.width * unit;+ return (+ <div+ key={i}+ style={{+ position: "absolute",+ left: -width / 2 - bleed,+ top: -bandHeight / 2,+ width: width + 2 * bleed,+ height: bandHeight,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ background: band,+ color,+ fontFamily,+ fontSize: fontSize * unit,+ lineHeight: 1,+ fontWeight,+ fontVariationSettings: `"wght" ${fontWeight}`,+ whiteSpace: "pre",+ backfaceVisibility: "visible",+ transform: `rotateY(${panel.angle}rad) translateZ(${layout.radius * unit}px)`,+ }}+ >+ {/* Only the letter dims: shading the band per panel would show+ every seam between panels. */}+ <span+ style={{+ opacity: getRingTextShade(panel.angle, pose.spin),+ }}+ >+ {chars[panel.char]}+ </span>+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/registry/remocn/selection-snap/__tests__/selection-snap.test.ts b/registry/remocn/selection-snap/__tests__/selection-snap.test.tsnew file mode 100644index 00000000..9cc0d846--- /dev/null+++ b/registry/remocn/selection-snap/__tests__/selection-snap.test.ts@@ -0,0 +1,114 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getSelectionSnapPadding,+ getSelectionSnapSize,+ getSelectionSnapState,+ getSelectionSnapTime,+ selectionSnapDefaults,+ selectionSnapHandles,+ selectionSnapLength,+ selectionSnapPadding,+} from "..";+import { selectionSnapConfig } from "../config";++const sample = (from: number, to: number, step = 0.25) => {+ const out: number[] = [];+ for (let t = from; t <= to; t += step) out.push(t);+ return out;+};++describe("selection-snap timeline", () => {+ it("starts empty and loose", () => {+ const s = getSelectionSnapState(0);+ expect(s.intro).toBe(0);+ expect(s.snap).toBe(0);+ expect(s.weight).toBe(0);+ expect(s.tint).toBe(0);+ expect(s.edges).toBe(0);+ expect(s.badge).toBe(0);+ expect(s.handles.every((h) => h === 0)).toBe(true);+ });++ it("comes to rest exactly at its length", () => {+ for (const t of [selectionSnapLength, selectionSnapLength + 30]) {+ const s = getSelectionSnapState(t);+ expect(s.intro).toBe(1);+ expect(s.bracketScale).toBe(1);+ expect(s.snap).toBeCloseTo(1, 10);+ expect(s.weight).toBe(1);+ expect(s.tint).toBe(1);+ expect(s.edges).toBe(1);+ expect(s.badge).toBeCloseTo(1, 10);+ expect(s.count).toBe(1);+ for (const h of s.handles) expect(h).toBeCloseTo(1, 10);+ }+ const before = getSelectionSnapState(selectionSnapLength - 1);+ expect(before.count).toBeLessThan(1);+ });++ it("grows the weight monotonically", () => {+ let last = -1;+ for (const t of sample(0, selectionSnapLength)) {+ const { weight } = getSelectionSnapState(t);+ expect(weight).toBeGreaterThanOrEqual(last);+ last = weight;+ }+ });++ it("snaps with a small overshoot past the tight box", () => {+ const peak = Math.max(+ ...sample(14, 28).map((t) => getSelectionSnapState(t).snap),+ );+ expect(peak).toBeGreaterThan(1.02);+ expect(peak).toBeLessThan(1.12);+ const pad = getSelectionSnapPadding(peak);+ expect(pad.x).toBeGreaterThan(0);+ });++ it("closes the frame before the handles pop, corners before midpoints", () => {+ expect(getSelectionSnapState(24).edges).toBeCloseTo(0.94, 1);+ expect(getSelectionSnapState(26).edges).toBe(1);+ const s = getSelectionSnapState(28);+ const corners = s.handles.slice(0, 4);+ const mids = s.handles.slice(4);+ expect(Math.min(...corners)).toBeGreaterThan(Math.max(...mids));+ expect(selectionSnapHandles).toHaveLength(8);+ });++ it("maps frames onto the 30 fps timeline", () => {+ expect(getSelectionSnapTime(30)).toBe(30);+ expect(getSelectionSnapTime(60, { fps: 60 })).toBe(30);+ expect(getSelectionSnapTime(10, { speed: 2 })).toBe(20);+ expect(getSelectionSnapTime(10, { speed: 0 })).toBe(0);+ expect(getSelectionSnapTime(Number.NaN)).toBe(0);+ expect(getSelectionSnapTime(-5)).toBe(0);+ });+});++describe("selection-snap geometry", () => {+ it("interpolates the padding between the loose and tight boxes", () => {+ expect(getSelectionSnapPadding(0)).toEqual(selectionSnapPadding.loose);+ expect(getSelectionSnapPadding(1)).toEqual(selectionSnapPadding.tight);+ });++ it("reports the snapped box in reference px", () => {+ expect(getSelectionSnapSize(400, 150)).toEqual({ width: 436, height: 150 });+ });+});++describe("selection-snap config", () => {+ it("previews the reel palette over the component defaults", () => {+ const defaults = getDefaults(+ resolveControls("selection-snap", selectionSnapConfig.controls),+ );+ expect(defaults.text).toBe(selectionSnapDefaults.text);+ expect(defaults.fontSize).toBe(selectionSnapDefaults.fontSize);+ expect(defaults.fromWeight).toBe(selectionSnapDefaults.fromWeight);+ expect(defaults.toWeight).toBe(selectionSnapDefaults.toWeight);+ expect(defaults.speed).toBe(1);+ expect(selectionSnapConfig.durationInFrames).toBeGreaterThan(+ selectionSnapLength,+ );+ });+});diff --git a/registry/remocn/selection-snap/config.ts b/registry/remocn/selection-snap/config.tsnew file mode 100644index 00000000..8ad4bb7d--- /dev/null+++ b/registry/remocn/selection-snap/config.ts@@ -0,0 +1,49 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";++export const selectionSnapConfig: ComponentConfig = {+ componentName: "SelectionSnap",+ importPath: "@/components/remocn/selection-snap",+ controls: {+ text: { type: "text-content", default: "Frame", description: "Text" },+ color: { type: "color", default: "#fafafa", description: "Start color" },+ accent: { type: "color", default: "#ff4d1a", description: "Accent" },+ selectionColor: {+ type: "color",+ default: "#3d5afe",+ description: "Selection",+ },+ fontSize: {+ type: "number",+ default: 150,+ min: 60,+ max: 260,+ step: 2,+ description: "Font size",+ hiddenFromList: false,+ },+ fromWeight: {+ type: "number",+ default: 100,+ min: 100,+ max: 900,+ step: 50,+ description: "From weight",+ hiddenFromList: false,+ },+ toWeight: {+ type: "number",+ default: 900,+ min: 100,+ max: 900,+ step: 50,+ description: "To weight",+ hiddenFromList: false,+ },+ badge: { type: "boolean", default: true, description: "Size badge" },+ },+ durationInFrames: 75,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#0a0a0a" },+};diff --git a/registry/remocn/selection-snap/index.tsx b/registry/remocn/selection-snap/index.tsxnew file mode 100644index 00000000..16c9ab71--- /dev/null+++ b/registry/remocn/selection-snap/index.tsx@@ -0,0 +1,339 @@+"use client";++import { loadFont } from "@remotion/google-fonts/Inter";+import { type CSSProperties, useEffect, useState } from "react";+import {+ continueRender,+ delayRender,+ Easing,+ interpolate,+ interpolateColors,+ useCurrentFrame,+ useVideoConfig,+} from "remotion";++const { fontFamily: INTER } = loadFont("normal", {+ weights: ["100", "900"],+ subsets: ["latin"],+});++export interface SelectionSnapProps {+ text?: string;+ fontSize?: number;+ fontFamily?: string;+ fromWeight?: number;+ toWeight?: number;+ color?: string;+ accent?: string;+ selectionColor?: string;+ badge?: boolean;+ speed?: number;+ className?: string;+}++export const selectionSnapDefaults = {+ text: "Frame",+ fontSize: 150,+ fontFamily: INTER,+ fromWeight: 100,+ toWeight: 900,+ color: "#fafafa",+ accent: "#D97757",+ selectionColor: "#0d99ff",+ badge: true,+ speed: 1,+} satisfies Required<Omit<SelectionSnapProps, "className">>;++/** Frame on the 30 fps timeline where every channel has come to rest. */+export const selectionSnapLength = 38;++/** Padding around the word, in em: the loose viewfinder and the snapped box. */+export const selectionSnapPadding = {+ loose: { x: 1.1, y: 0.9 },+ tight: { x: 0.12, y: 0 },+} as const;++/** Corners first, then edge midpoints, as fractions of the box. */+export const selectionSnapHandles = [+ [0, 0],+ [1, 0],+ [1, 1],+ [0, 1],+ [0.5, 0],+ [1, 0.5],+ [0.5, 1],+ [0, 0.5],+] as const;++const CLAMP = {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+} as const;++const easeOutCubic = Easing.out(Easing.cubic);+const easeInOutCubic = Easing.inOut(Easing.cubic);+const snapEase = Easing.bezier(0.34, 1.3, 0.64, 1);+const popEase = Easing.out(Easing.back(1.7));++function finite(value: number | undefined, fallback: number) {+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;+}++/** Back-eased 0 → 1 over `duration` frames from `start`, never below 0. */+function pop(t: number, start: number, duration: number) {+ return Math.max(+ 0,+ interpolate(t, [start, start + duration], [0, 1], {+ ...CLAMP,+ easing: popEase,+ }),+ );+}++/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */+export function getSelectionSnapTime(+ frame: number,+ options: { fps?: number; speed?: number } = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const speed = Math.max(0, finite(options.speed, 1));+ return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;+}++export interface SelectionSnapState {+ /** Word and brackets fading in, 0..1. */+ intro: number;+ /** Viewfinder settle scale. */+ bracketScale: number;+ /** Loose (0) to tight (1) padding. Overshoots past 1 on the snap. */+ snap: number;+ /** Weight progress, 0..1. */+ weight: number;+ /** Color progress toward the accent, 0..1. */+ tint: number;+ /** Bracket arms growing along the edges; 1 closes them into a box. */+ edges: number;+ /** Scale of each handle, in `selectionSnapHandles` order. */+ handles: number[];+ /** Badge entrance, 0..1 with overshoot. */+ badge: number;+ /** Badge readout progress, 0..1. */+ count: number;+}++export function getSelectionSnapState(t: number): SelectionSnapState {+ return {+ intro: interpolate(t, [0, 8], [0, 1], { ...CLAMP, easing: easeOutCubic }),+ bracketScale: interpolate(t, [0, 8], [1.06, 1], {+ ...CLAMP,+ easing: easeOutCubic,+ }),+ snap: interpolate(t, [14, 28], [0, 1], { ...CLAMP, easing: snapEase }),+ weight: interpolate(t, [14, 30], [0, 1], {+ ...CLAMP,+ easing: easeInOutCubic,+ }),+ tint: interpolate(t, [18, 30], [0, 1], {+ ...CLAMP,+ easing: easeInOutCubic,+ }),+ edges: interpolate(t, [16, 26], [0, 1], {+ ...CLAMP,+ easing: easeInOutCubic,+ }),+ handles: selectionSnapHandles.map((_, i) => pop(t, 24 + i, 5)),+ badge: pop(t, 24, 8),+ count: interpolate(t, [24, 38], [0, 1], { ...CLAMP, easing: easeOutCubic }),+ };+}++/** Padding in em for a snap progress. */+export function getSelectionSnapPadding(snap: number) {+ const { loose, tight } = selectionSnapPadding;+ return {+ x: loose.x + (tight.x - loose.x) * snap,+ y: loose.y + (tight.y - loose.y) * snap,+ };+}++/** Size of the snapped box in reference px, from the word's final width. */+export function getSelectionSnapSize(textWidth: number, fontSize: number) {+ const { tight } = selectionSnapPadding;+ return {+ width: Math.round(textWidth + 2 * tight.x * fontSize),+ height: Math.round(fontSize * (1 + 2 * tight.y)),+ };+}++function useTextWidth(text: string, font: string) {+ const [width, setWidth] = useState<number | null>(null);++ useEffect(() => {+ const handle = delayRender("selection-snap: measuring the word");+ let released = false;+ const release = () => {+ if (released) return;+ released = true;+ continueRender(handle);+ };+ const measure = () => {+ if (released) return;+ const ctx = document.createElement("canvas").getContext("2d");+ if (ctx) {+ ctx.font = font;+ setWidth(ctx.measureText(text).width);+ }+ release();+ };+ document.fonts.load(font, text).then(measure, measure);+ return release;+ }, [text, font]);++ return width;+}++export function SelectionSnap({+ text = selectionSnapDefaults.text,+ fontSize = selectionSnapDefaults.fontSize,+ fontFamily = selectionSnapDefaults.fontFamily,+ fromWeight = selectionSnapDefaults.fromWeight,+ toWeight = selectionSnapDefaults.toWeight,+ color = selectionSnapDefaults.color,+ accent = selectionSnapDefaults.accent,+ selectionColor = selectionSnapDefaults.selectionColor,+ badge = selectionSnapDefaults.badge,+ speed = selectionSnapDefaults.speed,+ className,+}: SelectionSnapProps) {+ const frame = useCurrentFrame();+ const { fps, height } = useVideoConfig();+ const unit = height / 720;+ const t = getSelectionSnapTime(frame, { fps, speed });+ const state = getSelectionSnapState(t);++ const size = fontSize * unit;+ const pad = getSelectionSnapPadding(state.snap);+ const weight = fromWeight + (toWeight - fromWeight) * state.weight;+ const stroke = Math.max(1, 1.5 * unit);+ const arm = 0.16 * size;+ const handleSize = 9 * unit;+ const finalWidth = useTextWidth(+ text,+ `${toWeight} ${fontSize}px ${fontFamily}`,+ );+ const readout =+ finalWidth === null ? null : getSelectionSnapSize(finalWidth, fontSize);++ // Percentages resolve against the box width for `width` and its height for+ // `height`, so one expression grows every arm to its edge's midpoint.+ const along = `calc(${arm}px + (50% - ${arm}px) * ${state.edges})`;+ const arms: CSSProperties[] = [+ { top: 0, left: 0, width: along, height: stroke },+ { top: 0, right: 0, width: along, height: stroke },+ { bottom: 0, left: 0, width: along, height: stroke },+ { bottom: 0, right: 0, width: along, height: stroke },+ { top: 0, left: 0, width: stroke, height: along },+ { bottom: 0, left: 0, width: stroke, height: along },+ { top: 0, right: 0, width: stroke, height: along },+ { bottom: 0, right: 0, width: stroke, height: along },+ ];++ return (+ <div+ className={className}+ style={{+ position: "absolute",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ overflow: "hidden",+ }}+ >+ <div+ style={{+ position: "relative",+ display: "inline-block",+ padding: `${pad.y * size}px ${pad.x * size}px`,+ }}+ >+ <span+ style={{+ display: "block",+ whiteSpace: "pre",+ fontFamily,+ fontSize: size,+ lineHeight: 1,+ fontWeight: Math.round(weight / 100) * 100,+ fontVariationSettings: `"wght" ${weight.toFixed(2)}`,+ color: interpolateColors(state.tint, [0, 1], [color, accent]),+ opacity: state.intro,+ }}+ >+ {text}+ </span>+ <div+ style={{+ position: "absolute",+ inset: 0,+ opacity: state.intro,+ transform: `scale(${state.bracketScale})`,+ }}+ >+ {arms.map((style, i) => (+ <div+ key={i}+ style={{+ position: "absolute",+ background: selectionColor,+ ...style,+ }}+ />+ ))}+ {selectionSnapHandles.map(([x, y], i) => (+ <div+ key={`${x}-${y}`}+ style={{+ position: "absolute",+ left: `${x * 100}%`,+ top: `${y * 100}%`,+ width: handleSize,+ height: handleSize,+ boxSizing: "border-box",+ background: "#ffffff",+ border: `${stroke}px solid ${selectionColor}`,+ transform: `translate(-50%, -50%) scale(${state.handles[i]})`,+ }}+ />+ ))}+ </div>+ {badge && readout ? (+ <div+ style={{+ position: "absolute",+ left: "50%",+ top: `calc(100% + ${12 * unit}px)`,+ padding: `${3 * unit}px ${7 * unit}px`,+ borderRadius: 4 * unit,+ background: selectionColor,+ color: "#ffffff",+ fontFamily: INTER,+ fontSize: 14 * unit,+ lineHeight: 1.2,+ fontWeight: 600,+ fontVariationSettings: '"wght" 600',+ fontVariantNumeric: "tabular-nums",+ whiteSpace: "nowrap",+ opacity: Math.min(1, state.badge),+ transform: `translate(-50%, ${(1 - state.badge) * 8 * unit}px) scale(${0.6 + 0.4 * state.badge})`,+ transformOrigin: "50% 0",+ }}+ >+ {Math.round(readout.width * state.count)} ×{" "}+ {Math.round(readout.height * state.count)}+ </div>+ ) : null}+ </div>+ </div>+ );+}diff --git a/registry/remocn/speed-lines/__tests__/speed-lines.test.ts b/registry/remocn/speed-lines/__tests__/speed-lines.test.tsnew file mode 100644index 00000000..624cadb6--- /dev/null+++ b/registry/remocn/speed-lines/__tests__/speed-lines.test.ts@@ -0,0 +1,871 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getSpeedLinesDuration,+ getSpeedLinesEase,+ getSpeedLinesPosition,+ getSpeedLinesRadius,+ getSpeedLinesRays,+ getSpeedLinesShape,+ getSpeedLinesState,+ getSpeedLinesStreaks,+ getSpeedLinesTime,+ getSpeedLinesTimeline,+ getSpeedLinesVelocity,+ type SpeedLinesOptions,+ type SpeedLinesStreak,+ speedLinesDefaults,+ speedLinesLength,+} from "..";+import { speedLinesConfig } from "../config";++const FOCUS: SpeedLinesOptions = { mode: "focus" };+const DEAD: SpeedLinesOptions = { bounce: 0, squash: 0 };+const DIAGONAL: SpeedLinesOptions = {+ from: { x: 0.1, y: 0.9 },+ to: { x: 0.7, y: 0.2 },+};+const HD: SpeedLinesOptions = { width: 1920, height: 1080 };+const BAND = speedLinesDefaults.spread;+const TRANSFORM =+ /^translate\(-50%, -50%\) rotate\((-?[\d.]+)deg\) scale\(([\d.]+), ([\d.]+)\) rotate\((-?[\d.]+)deg\)$/;++const frames = (first: number, last: number, step = 1) =>+ Array.from(+ { length: Math.floor((last - first) / step) + 1 },+ (_, i) => first + i * step,+ );++function directionOf(options: SpeedLinesOptions) {+ const from = options.from ?? speedLinesDefaults.from;+ const to = options.to ?? { x: 0.5, y: 0.5 };+ const dx = (to.x - from.x) * (options.width ?? 1280);+ const dy = (to.y - from.y) * (options.height ?? 720);+ const distance = Math.hypot(dx, dy);+ return { dx: dx / distance, dy: dy / distance, distance };+}++function offsetOf(time: number, options: SpeedLinesOptions = {}) {+ const to = options.to ?? { x: 0.5, y: 0.5 };+ const { dx, dy } = directionOf(options);+ const { x, y } = getSpeedLinesPosition(time, options);+ const ox = x - to.x * (options.width ?? 1280);+ const oy = y - to.y * (options.height ?? 720);+ return { forward: ox * dx + oy * dy, lateral: -ox * dy + oy * dx };+}++function reachByIndex(options: SpeedLinesOptions, at: number) {+ const map = new Map<number, SpeedLinesStreak>();+ for (const streak of getSpeedLinesStreaks(at, options)) {+ map.set(streak.index, streak);+ }+ return map;+}++describe("speed lines timeline", () => {+ it("ends trail at the documented length and snaps focus on frame 3", () => {+ expect(speedLinesLength).toBe(31);+ expect(getSpeedLinesTimeline()).toEqual({+ mode: "trail",+ impact: 14,+ end: 31,+ });+ expect(getSpeedLinesTimeline({ duration: 22 })).toEqual({+ mode: "trail",+ impact: 22,+ end: 39,+ });+ expect(getSpeedLinesTimeline({ bounce: 0 })).toEqual({+ mode: "trail",+ impact: 14,+ end: 20,+ });+ expect(getSpeedLinesTimeline({ bounce: 1 })).toEqual({+ mode: "trail",+ impact: 14,+ end: 43,+ });+ expect(getSpeedLinesTimeline(FOCUS)).toEqual({+ mode: "focus",+ impact: 3,+ end: 13,+ });+ expect(getSpeedLinesTimeline({ ...FOCUS, bounce: 1 })).toEqual({+ mode: "focus",+ impact: 3,+ end: 13,+ });+ expect(getSpeedLinesDuration()).toBe(speedLinesConfig.durationInFrames);+ expect(getSpeedLinesDuration()).toBe(55);+ expect(getSpeedLinesDuration(FOCUS)).toBe(37);+ });++ it("scales the preview duration with speed, delay, travel and bounce", () => {+ expect(getSpeedLinesDuration({ speed: 2 })).toBe(28);+ expect(getSpeedLinesDuration({ speed: 0.5 })).toBe(110);+ expect(getSpeedLinesDuration({ speed: 0 })).toBe(1);+ expect(getSpeedLinesDuration({ delay: 10 })).toBe(65);+ expect(getSpeedLinesDuration({ delay: 10, speed: 2 })).toBe(38);+ expect(getSpeedLinesDuration({ duration: 30 })).toBe(71);+ expect(getSpeedLinesDuration({ duration: 1 })).toBe(45);+ expect(getSpeedLinesDuration({ duration: Number.NaN })).toBe(55);+ expect(getSpeedLinesDuration({ bounce: 0 })).toBe(44);+ expect(getSpeedLinesDuration({ bounce: 1 })).toBe(67);+ expect(getSpeedLinesDuration({ bounce: Number.NaN })).toBe(55);+ expect(getSpeedLinesDuration({ bounce: 4 })).toBe(67);+ expect(getSpeedLinesDuration({ ...FOCUS, speed: 2 })).toBe(19);+ expect(getSpeedLinesDuration({ ...FOCUS, duration: 40 })).toBe(37);+ const resolve = speedLinesConfig.getDurationInFrames;+ expect(resolve?.({ mode: "focus", speed: 0.5, delay: 6 })).toBe(80);+ expect(resolve?.({ mode: "trail", duration: 20 })).toBe(61);+ expect(resolve?.({ mode: "trail", bounce: 0 })).toBe(44);+ expect(resolve?.({ mode: "other", speed: "fast" })).toBe(55);+ });++ it("maps frames through delay, speed and frame rate", () => {+ expect(getSpeedLinesTime(10)).toBe(10);+ expect(getSpeedLinesTime(10, { delay: 4 })).toBe(6);+ expect(getSpeedLinesTime(10, { speed: 2 })).toBe(20);+ expect(getSpeedLinesTime(10, { delay: 4, speed: 2 })).toBe(12);+ expect(getSpeedLinesTime(10, { fps: 60 })).toBe(5);+ expect(getSpeedLinesTime(10, { fps: 60, delay: 4 })).toBe(3);+ expect(getSpeedLinesTime(3, { delay: 4 })).toBe(0);+ expect(getSpeedLinesTime(Number.NaN)).toBe(0);+ expect(getSpeedLinesTime(10, { delay: -5 })).toBe(10);+ });+});++describe("speed lines travel", () => {+ it("keeps the old hard stop when bounce is 0", () => {+ const ease = (t: number) => getSpeedLinesEase(t, { bounce: 0 });+ expect(ease(-3)).toBe(0);+ expect(ease(0)).toBe(0);+ expect(ease(14)).toBe(1);+ expect(ease(20)).toBe(1);+ expect(ease(90)).toBe(1);+ const flight = frames(0, 14, 0.05).map(ease);+ for (let i = 1; i < flight.length; i++) {+ expect(flight[i]).toBeGreaterThan(flight[i - 1]);+ }+ const h = 1e-4;+ const rate = (t: number) => ((ease(t + h) - ease(t - h)) / (2 * h)) * 14;+ const peak = Math.max(...frames(0.5, 13.5, 0.01).map(rate));+ const contact = ((ease(14) - ease(14 - h)) / h) * 14;+ expect(peak).toBeCloseTo(1.404, 2);+ expect(contact / peak).toBeCloseTo(0.3, 2);+ const recoil = frames(14, 20, 0.05).map(ease);+ expect(Math.max(...recoil)).toBeGreaterThan(1.005);+ expect(Math.max(...recoil)).toBeLessThan(1.02);+ for (const value of recoil) expect(value).toBeGreaterThanOrEqual(1);+ });++ it("carries momentum past the target, swings back once and settles", () => {+ const ease = (t: number) => getSpeedLinesEase(t);+ const sample = (t: number) => ({ t, value: ease(t) });+ const { impact, end } = getSpeedLinesTimeline();+ expect(ease(impact)).toBe(1);+ expect(ease(end)).toBe(1);+ expect(ease(90)).toBe(1);+ const h = 1e-4;+ const rate = (t: number) => ((ease(t + h) - ease(t - h)) / (2 * h)) * 14;+ const peak = Math.max(...frames(0.5, 13.5, 0.01).map(rate));+ const arriving = ((ease(14) - ease(14 - h)) / h) * 14;+ const leaving = ((ease(14 + h) - ease(14)) / h) * 14;+ expect(arriving / peak).toBeCloseTo(0.45, 2);+ expect(leaving).toBeCloseTo(arriving, 2);+ const landing = frames(impact, end, 0.01).map(sample);+ const top = landing.reduce((a, b) => (b.value > a.value ? b : a));+ expect(top.value).toBeGreaterThan(1.03);+ expect(top.value).toBeLessThan(1.04);+ expect(top.t - impact).toBeGreaterThan(1.5);+ expect(top.t - impact).toBeLessThan(2.5);+ const rebound = landing.filter((point) => point.t > top.t);+ const low = rebound.reduce((a, b) => (b.value < a.value ? b : a));+ expect(low.value).toBeLessThan(1);+ expect(1 - low.value).toBeLessThan((top.value - 1) * 0.15);+ const tail = rebound.filter((point) => point.t > low.t);+ expect(Math.max(...tail.map((point) => point.value))).toBeLessThan(1.0005);+ const bouncy = (t: number) => getSpeedLinesEase(t, { bounce: 1 });+ const harder = Math.max(...frames(14, 43, 0.01).map(bouncy));+ expect(harder).toBeGreaterThan(top.value + 0.02);+ expect(harder).toBeLessThan(1.08);+ });++ it("overshoots along the travel direction and stays on the line", () => {+ const cases: SpeedLinesOptions[] = [+ {},+ DIAGONAL,+ { ...DIAGONAL, ...HD },+ { ...DIAGONAL, bounce: 1 },+ ];+ for (const options of cases) {+ const { impact, end } = getSpeedLinesTimeline(options);+ const { distance } = directionOf(options);+ const times = frames(impact, end, 0.05);+ const offsets = times.map((t) => offsetOf(t, options));+ const peak = Math.max(...offsets.map((offset) => offset.forward));+ const expected = options.bounce === 1 ? 0.0722 : 0.0354;+ expect(peak / distance).toBeCloseTo(expected, 3);+ for (const offset of offsets) {+ expect(Math.abs(offset.lateral)).toBeLessThan(1e-6);+ }+ expect(offsetOf(end, options).forward).toBeCloseTo(0, 9);+ expect(offsetOf(end + 30, options).forward).toBeCloseTo(0, 9);+ }+ });++ it("moves the element center from the start to the target", () => {+ expect(getSpeedLinesPosition(0)).toEqual({ x: -320, y: 360 });+ expect(getSpeedLinesPosition(-6)).toEqual({ x: -320, y: 360 });+ expect(getSpeedLinesPosition(14)).toEqual({ x: 640, y: 360 });+ expect(getSpeedLinesPosition(speedLinesLength)).toEqual({ x: 640, y: 360 });+ expect(getSpeedLinesPosition(60)).toEqual({ x: 640, y: 360 });+ const landing = { x: 0.25, y: 0.75 };+ expect(getSpeedLinesPosition(40, landing)).toEqual({ x: 320, y: 540 });+ const target = { ...landing, to: { x: 0.9, y: 0.1 } };+ expect(getSpeedLinesPosition(40, target)).toEqual({ x: 1152, y: 72 });+ const focus = getSpeedLinesPosition(5, { ...FOCUS, x: 0.2, y: 0.4 });+ expect(focus).toEqual({ x: 256, y: 288 });+ });++ it("derives velocity from the same position function", () => {+ const cases: SpeedLinesOptions[] = [+ {},+ DIAGONAL,+ { ...DIAGONAL, speed: 1.5 },+ { bounce: 1 },+ ];+ for (const options of cases) {+ for (const frame of frames(0, 40)) {+ const now = getSpeedLinesTime(frame, options);+ const before = getSpeedLinesTime(frame - 1, options);+ const a = getSpeedLinesPosition(now, options);+ const b = getSpeedLinesPosition(before, options);+ const velocity = getSpeedLinesVelocity(frame, options);+ expect(velocity.x).toBeCloseTo(a.x - b.x, 9);+ expect(velocity.y).toBeCloseTo(a.y - b.y, 9);+ }+ }+ const fast = getSpeedLinesVelocity(9, { fps: 60 });+ const late = getSpeedLinesPosition(4.5);+ const early = getSpeedLinesPosition(4);+ expect(fast.x).toBeCloseTo((late.x - early.x) * 2, 9);+ const { dx, dy } = directionOf(DIAGONAL);+ const moving = getSpeedLinesVelocity(8, DIAGONAL);+ expect(moving.forward).toBeCloseTo(Math.hypot(moving.x, moving.y), 6);+ expect(moving.forward).toBeCloseTo(moving.x * dx + moving.y * dy, 9);+ const rebounding = getSpeedLinesVelocity(18, DIAGONAL);+ const back = Math.hypot(rebounding.x, rebounding.y);+ expect(rebounding.forward).toBeLessThan(-5);+ expect(-rebounding.forward).toBeCloseTo(back, 6);+ });+});++describe("speed lines shape", () => {+ it("preserves the element's area and stays inside the caps", () => {+ const cases: SpeedLinesOptions[] = [+ {},+ DIAGONAL,+ HD,+ { squash: 1 },+ { bounce: 1, squash: 1 },+ { duration: 4, squash: 1 },+ { ...DIAGONAL, duration: 6, speed: 2 },+ ];+ for (const options of cases) {+ for (const time of frames(0, 60, 0.25)) {+ const { along, across } = getSpeedLinesShape(time, options);+ expect(along * across).toBeCloseTo(1, 12);+ expect(along).toBeLessThanOrEqual(1.3);+ expect(along).toBeGreaterThanOrEqual(0.8);+ }+ }+ });++ it("stretches along the path while fast and squashes on impact", () => {+ const { impact, end } = getSpeedLinesTimeline();+ const ease = (t: number) => getSpeedLinesEase(t);+ const along = (t: number) => getSpeedLinesShape(t).along;+ expect(getSpeedLinesShape(0)).toEqual({ rotation: 0, along: 1, across: 1 });+ for (const t of frames(4, 12)) {+ expect(along(t)).toBeGreaterThan(1.2);+ expect(along(t)).toBeLessThan(1.26);+ }+ expect(along(impact)).toBeGreaterThan(1.1);+ const landing = frames(impact, impact + 6, 0.01);+ const squashed = landing.reduce((a, t) => (along(t) < along(a) ? t : a));+ const overshoot = landing.reduce((a, t) => (ease(t) > ease(a) ? t : a));+ expect(Math.abs(squashed - overshoot)).toBeLessThan(0.05);+ expect(along(squashed)).toBeGreaterThan(0.8);+ expect(along(squashed)).toBeLessThan(0.85);+ expect(getSpeedLinesShape(squashed).across).toBeGreaterThan(1.15);+ const after = frames(squashed, end, 0.01);+ expect(Math.max(...after.map(along))).toBeLessThan(1.02);+ const echo = after.reduce((a, t) => (ease(t) < ease(a) ? t : a));+ expect(ease(echo)).toBeLessThan(1);+ expect(along(echo)).toBeCloseTo(1, 3);+ expect(along(end)).toBeCloseTo(1, 6);+ expect(getSpeedLinesShape(60)).toEqual({+ rotation: 0,+ along: 1,+ across: 1,+ });+ });++ it("deforms more at higher speeds and scales with the squash prop", () => {+ const series = (options: SpeedLinesOptions, from: number, to: number) =>+ frames(from, to, 0.25).map((t) => getSpeedLinesShape(t, options).along);+ const peak = (options: SpeedLinesOptions) =>+ Math.max(...series(options, 0, 14));+ const deepest = (options: SpeedLinesOptions) =>+ Math.min(...series(options, 14, 24));+ const slow = { from: { x: 0.2, y: 0.5 }, to: { x: 0.5, y: 0.5 } };+ expect(peak(slow)).toBeLessThan(peak({}));+ expect(deepest(slow)).toBeGreaterThan(deepest({}));+ expect(peak({ squash: 0.25 })).toBeLessThan(peak({}));+ expect(peak({ squash: 1 })).toBeGreaterThan(peak({}));+ expect(deepest({ squash: 1 })).toBeLessThan(deepest({}));+ expect(peak({ squash: 1 })).toBeLessThanOrEqual(1.3);+ expect(deepest({ squash: 1 })).toBeGreaterThanOrEqual(0.8);+ expect(peak({ ...HD })).toBeCloseTo(peak({}), 9);+ const quick = getSpeedLinesShape(6, { speed: 2 }).along;+ expect(quick).toBeGreaterThan(getSpeedLinesShape(6).along);+ expect(quick).toBeLessThanOrEqual(1.3);+ });++ it("orients the deformation along the travel angle", () => {+ const { dx, dy } = directionOf(DIAGONAL);+ const degrees = (Math.atan2(dy, dx) * 180) / Math.PI;+ for (const frame of [8, 16]) {+ const state = getSpeedLinesState(frame, DIAGONAL);+ expect(state.rotation).toBeCloseTo(degrees, 1);+ const match = state.transform.match(TRANSFORM);+ expect(match).not.toBeNull();+ const [first, sx, sy, last] = match?.slice(1).map(Number) ?? [];+ expect(first).toBe(state.rotation);+ expect(last).toBe(-state.rotation);+ expect(sx).toBeCloseTo(state.along, 4);+ expect(sy).toBeCloseTo(state.across, 4);+ const turn = (first * Math.PI) / 180;+ const c = Math.cos(turn);+ const s = Math.sin(turn);+ const apply = (vx: number, vy: number) => {+ const ux = sx * (c * vx + s * vy);+ const uy = sy * (-s * vx + c * vy);+ return [c * ux - s * uy, s * ux + c * uy];+ };+ const [ax, ay] = apply(dx, dy);+ expect(ax).toBeCloseTo(sx * dx, 3);+ expect(ay).toBeCloseTo(sx * dy, 3);+ const [nx, ny] = apply(-dy, dx);+ expect(nx).toBeCloseTo(-sy * dy, 3);+ expect(ny).toBeCloseTo(sy * dx, 3);+ }+ expect(getSpeedLinesState(8, DIAGONAL).along).toBeGreaterThan(1.2);+ expect(getSpeedLinesState(16, DIAGONAL).along).toBeLessThan(0.85);+ expect(getSpeedLinesState(8).rotation).toBe(0);+ const down = { from: { x: 0.5, y: -0.3 }, to: { x: 0.5, y: 0.5 } };+ expect(getSpeedLinesState(8, down).rotation).toBe(90);+ });++ it("gives back a rigid dead stop with bounce and squash at 0", () => {+ const { impact, end } = getSpeedLinesTimeline(DEAD);+ const dead = (t: number) => getSpeedLinesEase(t, DEAD);+ const kappa = (1 + Math.sqrt(0.7)) / 2;+ const gain = 1 / (0.5 - kappa / 3);+ const previous = (t: number) => {+ if (t <= 0) return 0;+ if (t < 14) {+ const w = t / 14;+ return gain * ((w * w) / 2 - (kappa * w * w * w) / 3);+ }+ const s = t - 14;+ if (s >= 6) return 1;+ const x = Math.min(1, Math.max(0, (s - 3) / 3));+ const taper = x * x * (3 - 2 * x);+ return 1 + ((gain * (1 - kappa)) / 14) * s * Math.exp(-s) * (1 - taper);+ };+ expect(end).toBe(impact + 6);+ for (const frame of frames(0, 40, 0.5)) {+ const state = getSpeedLinesState(frame, DEAD);+ expect(state.along).toBe(1);+ expect(state.across).toBe(1);+ expect(state.transform).toBe("translate(-50%, -50%)");+ const rigid = getSpeedLinesState(frame, { squash: 0 });+ expect(rigid.transform).toBe("translate(-50%, -50%)");+ }+ const landing = frames(impact, end, 0.05).map(dead);+ expect(Math.max(...landing)).toBeLessThan(1.012);+ for (const value of landing) expect(value).toBeGreaterThanOrEqual(1);+ for (const time of frames(-2, 30, 0.25)) {+ expect(dead(time)).toBeCloseTo(previous(time), 12);+ }+ for (const frame of frames(0, 40)) {+ const focus = getSpeedLinesState(frame, { ...FOCUS, squash: 1 });+ expect(focus.transform).toBe("translate(-50%, -50%)");+ }+ });+});++describe("speed lines streaks", () => {+ it("draws nothing before the start, at rest, or after the landing", () => {+ for (const frame of [...frames(-6, 0), ...frames(15, 60)]) {+ expect(getSpeedLinesStreaks(frame)).toEqual([]);+ expect(getSpeedLinesState(frame).path).toBe("");+ }+ for (const frame of frames(0, 12)) {+ expect(getSpeedLinesStreaks(frame, { delay: 12 })).toEqual([]);+ }+ for (const frame of frames(0, 40)) {+ expect(getSpeedLinesStreaks(frame, { speed: 0 })).toEqual([]);+ expect(getSpeedLinesStreaks(frame, FOCUS)).toEqual([]);+ }+ const still = { from: { x: 0.5, y: 0.5 }, to: { x: 0.5, y: 0.5 } };+ for (const frame of frames(0, 20)) {+ expect(getSpeedLinesStreaks(frame, still)).toEqual([]);+ }+ });++ it("exists only while the element is actually fast", () => {+ let drawn = 0;+ const cases: SpeedLinesOptions[] = [{}, DIAGONAL, HD, { duration: 30 }];+ for (const options of cases) {+ const unit = (options.height ?? 720) / 720;+ for (const frame of frames(-2, 50, 0.5)) {+ const streaks = getSpeedLinesStreaks(frame, options);+ if (streaks.length === 0) continue;+ drawn++;+ const { forward } = getSpeedLinesVelocity(frame, options);+ expect(forward).toBeGreaterThan(5 * unit);+ }+ }+ expect(drawn).toBeGreaterThan(40);+ for (const frame of frames(6, 14)) {+ expect(getSpeedLinesStreaks(frame).length).toBeGreaterThan(0);+ }+ const nudge = { from: { x: 0.47, y: 0.5 }, to: { x: 0.5, y: 0.5 } };+ for (const frame of frames(0, 30, 0.5)) {+ expect(getSpeedLinesStreaks(frame, nudge)).toEqual([]);+ }+ });++ it("dies at impact and never points back during the rebound", () => {+ const cases: SpeedLinesOptions[] = [+ {},+ DIAGONAL,+ { bounce: 1 },+ { bounce: 0 },+ { duration: 6 },+ { duration: 40, bounce: 1 },+ { speed: 2 },+ { delay: 5 },+ { fps: 60 },+ ];+ for (const options of cases) {+ const { impact, end } = getSpeedLinesTimeline(options);+ const scale = (options.fps ?? 30) / 30 / (options.speed ?? 1);+ const last = (options.delay ?? 0) + (end + 10) * scale;+ let rebound = 0;+ for (const frame of frames(0, last, 0.5)) {+ const time = getSpeedLinesTime(frame, options);+ const streaks = getSpeedLinesStreaks(frame, options);+ const { forward } = getSpeedLinesVelocity(frame, options);+ if (time >= impact + 1) expect(streaks).toEqual([]);+ if (forward <= 0) expect(streaks).toEqual([]);+ if (time > impact && forward < 0) rebound++;+ }+ expect(rebound).toBeGreaterThan(3);+ }+ expect(getSpeedLinesStreaks(14).length).toBeGreaterThan(0);+ expect(getSpeedLinesVelocity(15).forward).toBeGreaterThan(20);+ expect(getSpeedLinesStreaks(15)).toEqual([]);+ const longest = (frame: number, options: SpeedLinesOptions = {}) =>+ Math.max(0, ...getSpeedLinesStreaks(frame, options).map((s) => s.reach));+ const sixty = { fps: 60 };+ expect(longest(29, sixty)).toBeGreaterThan(0);+ expect(longest(29, sixty)).toBeLessThan(longest(28, sixty) * 0.5);+ expect(getSpeedLinesStreaks(30, sixty)).toEqual([]);+ });++ it("keeps streaks parallel, behind the element and inside the band", () => {+ const cases: SpeedLinesOptions[] = [+ {},+ DIAGONAL,+ { ...DIAGONAL, spread: 200 },+ ];+ for (const options of cases) {+ const { dx, dy } = directionOf(options);+ const band = options.spread ?? BAND;+ let checked = 0;+ for (const frame of frames(1, 16, 0.5)) {+ const state = getSpeedLinesState(frame, options);+ for (const streak of state.streaks) {+ const vx = streak.x2 - streak.x1;+ const vy = streak.y2 - streak.y1;+ expect(Math.abs(vx * dy - vy * dx)).toBeLessThan(0.05);+ expect(vx * dx + vy * dy).toBeLessThan(0);+ expect(Math.hypot(vx, vy)).toBeCloseTo(streak.length, 1);+ const fx = streak.x1 - state.x;+ const fy = streak.y1 - state.y;+ expect(fx * dx + fy * dy).toBeLessThan(0.05);+ const lateral = -fx * dy + fy * dx;+ expect(lateral).toBeCloseTo(streak.offset, 1);+ expect(Math.abs(streak.offset)).toBeLessThanOrEqual(band / 2);+ checked++;+ }+ }+ expect(checked).toBeGreaterThan(20);+ }+ });++ it("stretches each streak in proportion to the element's speed", () => {+ const ratios = new Map<number, number[]>();+ for (const frame of frames(3, 13)) {+ const { forward } = getSpeedLinesVelocity(frame);+ expect(forward).toBeGreaterThanOrEqual(14);+ for (const streak of getSpeedLinesStreaks(frame)) {+ const list = ratios.get(streak.index) ?? [];+ list.push(streak.reach / forward);+ ratios.set(streak.index, list);+ }+ }+ expect(ratios.size).toBeGreaterThan(6);+ for (const list of ratios.values()) {+ for (const ratio of list) {+ expect(ratio).toBeCloseTo(list[0], 9);+ expect(ratio).toBeGreaterThanOrEqual(0.8);+ expect(ratio).toBeLessThanOrEqual(1.6);+ }+ }+ const near = { from: { x: 0.1, y: 0.5 }, to: { x: 0.4, y: 0.5 } };+ const far = { from: { x: 0.1, y: 0.5 }, to: { x: 0.7, y: 0.5 } };+ let compared = 0;+ for (const frame of frames(4, 11)) {+ const short = reachByIndex(near, frame);+ const long = reachByIndex(far, frame);+ for (const [index, streak] of short) {+ const twin = long.get(index);+ if (!twin) continue;+ expect(twin.reach).toBeCloseTo(streak.reach * 2, 6);+ expect(twin.length).toBeCloseTo(streak.length * 2, 6);+ compared++;+ }+ }+ expect(compared).toBeGreaterThan(10);+ });++ it("shortens the streaks as the element brakes into the landing", () => {+ const speeds = frames(9, 16).map((f) => getSpeedLinesVelocity(f).forward);+ for (let i = 1; i < speeds.length; i++) {+ expect(speeds[i]).toBeLessThan(speeds[i - 1]);+ }+ let compared = 0;+ for (const frame of frames(10, 13)) {+ const now = reachByIndex({}, frame);+ const next = reachByIndex({}, frame + 1);+ for (const [index, streak] of now) {+ const later = next.get(index);+ if (!later) continue;+ expect(later.reach).toBeLessThan(streak.reach);+ compared++;+ }+ }+ expect(compared).toBeGreaterThan(2);+ const longest = (frame: number) =>+ Math.max(0, ...getSpeedLinesStreaks(frame).map((s) => s.reach));+ expect(longest(14)).toBeLessThan(longest(9) * 0.65);+ expect(longest(15)).toBe(0);+ });++ it("spreads consecutive streaks far apart across the band", () => {+ const offsets = new Map<number, number>();+ for (const frame of frames(0, 16, 0.25)) {+ for (const streak of getSpeedLinesStreaks(frame)) {+ offsets.set(streak.index, streak.offset);+ }+ }+ expect(offsets.size).toBe(speedLinesDefaults.count);+ const lanes = frames(0, speedLinesDefaults.count - 1).map(+ (index) => offsets.get(index) ?? Number.NaN,+ );+ for (let i = 1; i < lanes.length; i++) {+ expect(Math.abs(lanes[i] - lanes[i - 1])).toBeGreaterThan(BAND * 0.25);+ }+ expect(Math.min(...lanes)).toBeLessThan(-BAND * 0.3);+ expect(Math.max(...lanes)).toBeGreaterThan(BAND * 0.3);+ });+});++describe("speed lines focus", () => {+ it("draws nothing before the rush or after the retract", () => {+ for (const frame of [...frames(-4, 0), ...frames(13, 40)]) {+ expect(getSpeedLinesRays(frame, FOCUS)).toEqual([]);+ expect(getSpeedLinesState(frame, FOCUS).path).toBe("");+ }+ for (const frame of frames(0, 9)) {+ expect(getSpeedLinesRays(frame, { ...FOCUS, delay: 9 })).toEqual([]);+ }+ for (const frame of frames(0, 20)) {+ expect(getSpeedLinesRays(frame)).toEqual([]);+ }+ for (const frame of frames(2, 9)) {+ const rays = getSpeedLinesRays(frame, FOCUS);+ expect(rays).toHaveLength(speedLinesDefaults.count);+ }+ });++ it("rushes inner ends in, snaps on the impact frame, then retracts", () => {+ const at = (frame: number) =>+ new Map(getSpeedLinesRays(frame, FOCUS).map((ray) => [ray.index, ray]));+ const impact = at(3);+ for (const [index, ray] of impact) {+ expect(ray.inner).toBe(ray.rest);+ expect(ray.rest).toBeGreaterThanOrEqual(BAND);+ expect(ray.rest).toBeLessThanOrEqual(BAND * 1.6);+ const inners = frames(1, 12).map((f) => at(f).get(index)?.inner);+ const rush = [inners[0] ?? ray.outer, inners[1], inners[2]];+ expect(rush[0]).toBeGreaterThan(rush[1] ?? 0);+ expect(rush[1]).toBeGreaterThan(ray.inner);+ for (const inner of inners) {+ if (inner !== undefined) expect(inner).toBeGreaterThanOrEqual(ray.rest);+ }+ const hold = [4, 5, 6, 7].map((f) => at(f).get(index)?.inner ?? 0);+ for (const inner of hold) {+ expect(inner).toBeGreaterThan(ray.rest);+ expect(inner).toBeLessThan(ray.rest * 1.12);+ }+ const innerAt = (f: number) => at(f).get(index)?.inner ?? ray.outer;+ const late = frames(9, 12).map(innerAt);+ for (let i = 1; i < late.length; i++) {+ expect(late[i]).toBeGreaterThanOrEqual(late[i - 1]);+ }+ expect(late[late.length - 1]).toBeGreaterThan(ray.rest * 1.5);+ }+ });++ it("keeps rays radial, clear of the point and running off the frame", () => {+ const cases: SpeedLinesOptions[] = [+ FOCUS,+ { ...FOCUS, x: 0.2, y: 0.7, spread: 60 },+ { ...FOCUS, ...HD, count: 30 },+ ];+ for (const options of cases) {+ const width = options.width ?? 1280;+ const height = options.height ?? 720;+ const unit = height / 720;+ const cx = (options.x ?? 0.5) * width;+ const cy = (options.y ?? 0.5) * height;+ const spread = (options.spread ?? BAND) * unit;+ for (const frame of frames(1, 12, 0.5)) {+ for (const ray of getSpeedLinesRays(frame, options)) {+ const ix = ray.x1 - cx;+ const iy = ray.y1 - cy;+ expect(Math.hypot(ix, iy)).toBeCloseTo(ray.inner, 1);+ expect(ray.inner).toBeGreaterThanOrEqual(spread);+ const vx = ray.x2 - ray.x1;+ const vy = ray.y2 - ray.y1;+ const sine =+ Math.abs(vx * iy - vy * ix) / (Math.hypot(vx, vy) * ray.inner);+ expect(sine).toBeLessThan(0.02);+ expect(vx * ix + vy * iy).toBeGreaterThan(0);+ const off =+ ray.x2 <= 0 || ray.x2 >= width || ray.y2 <= 0 || ray.y2 >= height;+ expect(off).toBe(true);+ }+ }+ }+ });++ it("times one ray from the edge to the snap and back", () => {+ const ray = { rest: 100, outer: 500, start: 0.5, release: 9 };+ expect(getSpeedLinesRadius(0, ray)).toBe(500);+ expect(getSpeedLinesRadius(0.5, ray)).toBe(500);+ expect(getSpeedLinesRadius(3, ray)).toBe(100);+ const rush = frames(0.5, 3, 0.25).map((t) => getSpeedLinesRadius(t, ray));+ for (let i = 1; i < rush.length; i++) {+ expect(rush[i]).toBeLessThan(rush[i - 1]);+ }+ const steps = rush.slice(1).map((value, i) => rush[i] - value);+ for (let i = 1; i < steps.length; i++) {+ expect(steps[i]).toBeGreaterThan(steps[i - 1]);+ }+ expect(getSpeedLinesRadius(9, ray)).toBeLessThan(112);+ expect(getSpeedLinesRadius(12.5, ray)).toBe(500);+ expect(getSpeedLinesRadius(30, ray)).toBe(500);+ });+});++describe("speed lines reference scaling", () => {+ it("scales every size with the composition height", () => {+ const cases: [SpeedLinesOptions, number][] = [+ [{}, 9],+ [{}, 16],+ [DIAGONAL, 7],+ [FOCUS, 5],+ [{ ...FOCUS, x: 0.3, y: 0.6 }, 10],+ ];+ for (const [options, frame] of cases) {+ const base = getSpeedLinesState(frame, options);+ const large = getSpeedLinesState(frame, { ...options, ...HD });+ expect(large.unit).toBe(1.5);+ expect(large.strokeWidth).toBeCloseTo(base.strokeWidth * 1.5, 9);+ expect(large.radius).toBeCloseTo(base.radius * 1.5, 9);+ expect(large.x).toBeCloseTo(base.x * 1.5, 6);+ expect(large.y).toBeCloseTo(base.y * 1.5, 6);+ expect(large.left).toBeCloseTo(base.left, 9);+ expect(large.along).toBeCloseTo(base.along, 9);+ expect(large.rotation).toBeCloseTo(base.rotation, 9);+ const segments = [...base.streaks, ...base.rays];+ const scaled = [...large.streaks, ...large.rays];+ expect(scaled).toHaveLength(segments.length);+ for (const [i, segment] of segments.entries()) {+ expect(scaled[i].index).toBe(segment.index);+ expect(scaled[i].x1).toBeCloseTo(segment.x1 * 1.5, 1);+ expect(scaled[i].y1).toBeCloseTo(segment.y1 * 1.5, 1);+ expect(scaled[i].x2).toBeCloseTo(segment.x2 * 1.5, 1);+ expect(scaled[i].y2).toBeCloseTo(segment.y2 * 1.5, 1);+ expect(scaled[i].length).toBeCloseTo(segment.length * 1.5, 6);+ }+ }+ expect(getSpeedLinesState(9).streaks.length).toBeGreaterThan(0);+ expect(getSpeedLinesState(16).along).toBeLessThan(0.85);+ expect(getSpeedLinesState(0).strokeWidth).toBe(2);+ expect(getSpeedLinesState(0, { height: 2160 }).strokeWidth).toBe(6);+ const heavy = getSpeedLinesState(0, { weight: 3, height: 1440 });+ expect(heavy.strokeWidth).toBe(6);+ expect(getSpeedLinesState(0).radius).toBe(48);+ });+});++describe("speed lines determinism", () => {+ it("renders any frame identically in any sampling order", () => {+ const cases: SpeedLinesOptions[] = [+ { ...DIAGONAL, seed: 7 },+ { ...FOCUS, seed: 7 },+ { bounce: 1, squash: 1 },+ ];+ for (const options of cases) {+ const sample = (frame: number) => getSpeedLinesState(frame, options);+ const order = [0, 4, 7.5, 9, 12, 3, 15, 16, 22, 30];+ const forward = order.map(sample);+ const backward = [...order].reverse().map(sample).reverse();+ expect(backward).toEqual(forward);+ expect(sample(9)).toEqual(forward[3]);+ expect(sample(16)).toEqual(forward[7]);+ }+ });++ it("reseeds the streaks and rays", () => {+ const streaks = (seed: number) => getSpeedLinesStreaks(9, { seed });+ expect(streaks(1)).toEqual(streaks(1));+ expect(streaks(2)).not.toEqual(streaks(1));+ const rays = (seed: number) => getSpeedLinesRays(5, { ...FOCUS, seed });+ expect(rays(3)).toEqual(rays(3));+ expect(rays(4)).not.toEqual(rays(3));+ });++ it("maps other frame rates and speeds onto the 30 fps timeline", () => {+ for (const frame of [0, 5, 9, 14, 16, 17, 22, 25]) {+ const base = getSpeedLinesState(frame);+ const doubled = getSpeedLinesState(frame * 2, { fps: 60 });+ expect(doubled.x).toBeCloseTo(base.x, 9);+ expect(doubled.y).toBeCloseTo(base.y, 9);+ expect(doubled.along).toBeCloseTo(base.along, 9);+ const slow = getSpeedLinesState(frame * 2, { speed: 0.5 });+ expect(slow.x).toBeCloseTo(base.x, 9);+ expect(slow.along).toBeLessThanOrEqual(base.along);+ const rays = getSpeedLinesRays(frame * 2, { ...FOCUS, fps: 60 });+ expect(rays).toEqual(getSpeedLinesRays(frame, FOCUS));+ }+ const frozen = getSpeedLinesState(30, { speed: 0 });+ expect(frozen.x).toBe(-320);+ expect(frozen.along).toBe(1);+ expect(frozen.path).toBe("");+ });+});++describe("speed lines render state", () => {+ it("builds one clean path and clamps invalid input", () => {+ const state = getSpeedLinesState(9);+ expect(state.path.match(/M /g)).toHaveLength(state.streaks.length);+ expect(state.path).toMatch(/^M -?\d/);+ const cases: SpeedLinesOptions[] = [+ { count: Number.NaN, weight: 99, spread: -5 },+ { ...FOCUS, count: 1000, x: 1.4, y: -0.3 },+ { from: { x: Number.NaN, y: 0.2 }, duration: 0 },+ { bounce: Number.NaN, squash: 9 },+ { ...DIAGONAL, bounce: -3, squash: Number.POSITIVE_INFINITY },+ ];+ for (const options of cases) {+ for (const frame of frames(0, 48)) {+ const probe = getSpeedLinesState(frame, options);+ expect(probe.path).not.toMatch(/NaN|Infinity/);+ expect(probe.transform).not.toMatch(/NaN|Infinity/);+ expect(Number.isFinite(probe.x) && Number.isFinite(probe.y)).toBe(true);+ expect(probe.along).toBeLessThanOrEqual(1.3);+ expect(probe.along).toBeGreaterThanOrEqual(0.8);+ expect(probe.rays.length).toBeLessThanOrEqual(64);+ expect(probe.streaks.length).toBeLessThanOrEqual(64);+ }+ }+ expect(getSpeedLinesState(0, { weight: 99 }).strokeWidth).toBe(12);+ expect(getSpeedLinesState(0, { spread: -5 }).radius).toBe(4);+ expect(getSpeedLinesTimeline({ duration: 0 }).impact).toBe(4);+ expect(getSpeedLinesTimeline({ bounce: -3 }).end).toBe(20);+ });++ it("centers children on the moving point in percent of the frame", () => {+ const start = getSpeedLinesState(0);+ expect(start.left).toBeCloseTo(-25, 9);+ expect(start.top).toBeCloseTo(50, 9);+ expect(start.transform).toBe("translate(-50%, -50%)");+ const settled = getSpeedLinesState(speedLinesLength);+ expect(settled.left).toBeCloseTo(50, 9);+ expect(settled.top).toBeCloseTo(50, 9);+ const rest = getSpeedLinesState(speedLinesLength + 1);+ expect(rest.transform).toBe("translate(-50%, -50%)");+ const focus = getSpeedLinesState(4, { ...FOCUS, x: 0.8, y: 0.25 });+ expect(focus.left).toBeCloseTo(80, 9);+ expect(focus.top).toBeCloseTo(25, 9);+ });+});++describe("speed lines config", () => {+ it("matches the component defaults and exposes both modes", () => {+ const controls = resolveControls("speed-lines", speedLinesConfig.controls);+ expect(getDefaults(controls)).toEqual({+ mode: speedLinesDefaults.mode,+ count: speedLinesDefaults.count,+ weight: speedLinesDefaults.weight,+ spread: speedLinesDefaults.spread,+ duration: speedLinesDefaults.duration,+ bounce: speedLinesDefaults.bounce,+ squash: speedLinesDefaults.squash,+ x: speedLinesDefaults.x,+ y: speedLinesDefaults.y,+ delay: speedLinesDefaults.delay,+ color: speedLinesDefaults.color,+ seed: speedLinesDefaults.seed,+ speed: speedLinesDefaults.speed,+ });+ const mode = controls.mode;+ const modes = mode.type === "select" ? mode.options : [];+ expect(modes).toEqual(["trail", "focus"]);+ const range = (key: string) => {+ const control = controls[key];+ return control.type === "number" ? [control.min, control.max] : [];+ };+ expect(range("count")).toEqual([3, 32]);+ expect(range("weight")).toEqual([1, 8]);+ expect(range("spread")).toEqual([16, 320]);+ expect(range("duration")).toEqual([6, 40]);+ expect(range("bounce")).toEqual([0, 1]);+ expect(range("squash")).toEqual([0, 1]);+ expect(range("x")).toEqual([0, 1]);+ expect(range("y")).toEqual([0, 1]);+ expect(speedLinesConfig.previewBackdrop).toEqual({+ type: "color",+ value: "#002fa7",+ });+ });+});diff --git a/registry/remocn/speed-lines/config.ts b/registry/remocn/speed-lines/config.tsnew file mode 100644index 00000000..70d712e5--- /dev/null+++ b/registry/remocn/speed-lines/config.ts@@ -0,0 +1,124 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";+import { getSpeedLinesDuration } from ".";++const numberOf = (value: unknown) =>+ typeof value === "number" ? value : undefined;++function durationOf(values: Record<string, unknown>) {+ return getSpeedLinesDuration({+ mode: values.mode === "focus" ? "focus" : "trail",+ duration: numberOf(values.duration),+ bounce: numberOf(values.bounce),+ delay: numberOf(values.delay),+ speed: numberOf(values.speed),+ });+}++export const speedLinesConfig: ComponentConfig = {+ componentName: "SpeedLines",+ importPath: "@/components/remocn/speed-lines",+ controls: {+ mode: {+ type: "enum",+ default: "trail",+ variants: { trail: {}, focus: {} },+ description: "Mode",+ },+ count: {+ type: "number",+ default: 12,+ min: 3,+ max: 32,+ step: 1,+ description: "Lines",+ hiddenFromList: false,+ },+ weight: {+ type: "number",+ default: 2,+ min: 1,+ max: 8,+ step: 0.5,+ description: "Stroke weight",+ hiddenFromList: false,+ },+ spread: {+ type: "number",+ default: 96,+ min: 16,+ max: 320,+ step: 4,+ description: "Spread",+ hiddenFromList: false,+ },+ duration: {+ type: "number",+ default: 14,+ min: 6,+ max: 40,+ step: 1,+ description: "Travel frames",+ hiddenFromList: false,+ },+ bounce: {+ type: "number",+ default: 0.5,+ min: 0,+ max: 1,+ step: 0.05,+ description: "Bounce",+ hiddenFromList: false,+ },+ squash: {+ type: "number",+ default: 0.5,+ min: 0,+ max: 1,+ step: 0.05,+ description: "Squash",+ hiddenFromList: false,+ },+ x: {+ type: "number",+ default: 0.5,+ min: 0,+ max: 1,+ step: 0.01,+ description: "Point x",+ hiddenFromList: false,+ },+ y: {+ type: "number",+ default: 0.5,+ min: 0,+ max: 1,+ step: 0.01,+ description: "Point y",+ hiddenFromList: false,+ },+ delay: {+ type: "number",+ default: 0,+ min: 0,+ max: 60,+ step: 1,+ description: "Delay",+ hiddenFromList: false,+ },+ color: { type: "color", default: "#ffffff", description: "Line color" },+ seed: {+ type: "number",+ default: 1,+ min: 1,+ step: 1,+ description: "Seed",+ hiddenFromList: false,+ },+ },+ durationInFrames: 55,+ getDurationInFrames: durationOf,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#002fa7" },+};diff --git a/registry/remocn/speed-lines/index.tsx b/registry/remocn/speed-lines/index.tsxnew file mode 100644index 00000000..3e2f0d05--- /dev/null+++ b/registry/remocn/speed-lines/index.tsx@@ -0,0 +1,623 @@+"use client";++import type { ReactNode } from "react";+import { random, useCurrentFrame, useVideoConfig } from "remotion";++export type SpeedLinesMode = "trail" | "focus";++export interface SpeedLinesPoint {+ x: number;+ y: number;+}++export interface SpeedLinesProps {+ mode?: SpeedLinesMode;+ from?: SpeedLinesPoint;+ to?: SpeedLinesPoint;+ x?: number;+ y?: number;+ count?: number;+ weight?: number;+ spread?: number;+ duration?: number;+ bounce?: number;+ squash?: number;+ color?: string;+ seed?: number;+ delay?: number;+ speed?: number;+ children?: ReactNode;+ className?: string;+}++type Paint = "color" | "children" | "className";+type Unset = "to" | "children" | "className";++export interface SpeedLinesOptions extends Omit<SpeedLinesProps, Paint> {+ width?: number;+ height?: number;+ fps?: number;+}++export interface SpeedLinesSegment {+ index: number;+ x1: number;+ y1: number;+ x2: number;+ y2: number;+ length: number;+}++export interface SpeedLinesStreak extends SpeedLinesSegment {+ offset: number;+ reach: number;+}++export interface SpeedLinesRay extends SpeedLinesSegment {+ angle: number;+ rest: number;+ inner: number;+ outer: number;+}++export interface SpeedLinesRayTiming {+ rest: number;+ outer: number;+ start?: number;+ release?: number;+}++export const speedLinesDefaults: Required<Omit<SpeedLinesProps, Unset>> = {+ mode: "trail",+ from: { x: -0.25, y: 0.5 },+ x: 0.5,+ y: 0.5,+ count: 12,+ weight: 2,+ spread: 96,+ duration: 14,+ bounce: 0.5,+ squash: 0.5,+ color: "#ffffff",+ seed: 1,+ delay: 0,+ speed: 1,+};++const REFERENCE = 720;+const LANDING = 0.3;+const CARRY = 0.3;+const ECHO = 0.2;+const SOFTEN = 1.2;+const SETTLE = 6;+const STRETCH = Math.log(1.3);+const SQUASH = Math.log(1.25);+const STRETCH_GAIN = 0.007;+const SQUASH_GAIN = 0.018;+const PROBE = 1e-3;+const CENTER = "translate(-50%, -50%)";+const HOLD = 24;+const SPAWN_START = 0.04;+const SPAWN_END = 0.8;+const LIFE = 0.3;+const MIN_LIFE = 3;+const DRAW = 0.4;+const ERASE = 0.35;+const SHUTTER = 1.6;+const DRIFT = 0.15;+const SETBACK = 0.35;+const SLOW = 5;+const FAST = 14;+const GOLDEN = (Math.sqrt(5) - 1) / 2;+const IMPACT = 3;+const RUSH_JITTER = 1;+const RELAX = 0.12;+const RELAX_RATE = 1.5;+const RELEASE = 8;+const RELEASE_JITTER = 1.5;+const RETRACT = 3.5;+const FOCUS_END = RELEASE + RELEASE_JITTER + RETRACT;+const ANGLE_JITTER = 0.6;+const RADIUS_JITTER = 0.6;+const MAX_COUNT = 64;+const MIN_WEIGHT = 0.5;+const MAX_WEIGHT = 12;+const MIN_SPREAD = 8;+const MAX_SPREAD = 480;+const MIN_DURATION = 4;+const MAX_DURATION = 120;++const finite = (value: number | undefined, fallback: number) =>+ typeof value === "number" && Number.isFinite(value) ? value : fallback;+const clamp = (value: number, min: number, max: number) =>+ Math.min(max, Math.max(min, value));+const round = (value: number) => Math.round(value * 100) / 100;+const fine = (value: number) => Math.round(value * 10000) / 10000;+const fraction = (value: number) => value - Math.floor(value);+const modeOf = (value: string | undefined): SpeedLinesMode =>+ value === "focus" ? "focus" : "trail";+const travelOf = (value: number | undefined) =>+ clamp(finite(value, speedLinesDefaults.duration), MIN_DURATION, MAX_DURATION);++function smoothstep(value: number) {+ const t = clamp(value, 0, 1);+ return t * t * (3 - 2 * t);+}++function easeOut(value: number) {+ const t = clamp(value, 0, 1);+ return 1 - (1 - t) * (1 - t);+}++function pointOf(+ value: SpeedLinesPoint | undefined,+ fallback: SpeedLinesPoint,+) {+ return { x: finite(value?.x, fallback.x), y: finite(value?.y, fallback.y) };+}++function key(seed: number, index: number, name: string) {+ return random(`speed-lines-${seed}-${index}-${name}`);+}++function settingsOf(options: SpeedLinesOptions) {+ const height = Math.max(1, finite(options.height, 720));+ const x = finite(options.x, speedLinesDefaults.x);+ const y = finite(options.y, speedLinesDefaults.y);+ const count = finite(options.count, speedLinesDefaults.count);+ const weight = finite(options.weight, speedLinesDefaults.weight);+ const spread = finite(options.spread, speedLinesDefaults.spread);+ return {+ mode: modeOf(options.mode),+ width: Math.max(1, finite(options.width, 1280)),+ height,+ fps: Math.max(1, finite(options.fps, 30)),+ unit: height / REFERENCE,+ from: pointOf(options.from, speedLinesDefaults.from),+ to: pointOf(options.to, { x, y }),+ x,+ y,+ count: Math.round(clamp(count, 1, MAX_COUNT)),+ weight: clamp(weight, MIN_WEIGHT, MAX_WEIGHT),+ spread: clamp(spread, MIN_SPREAD, MAX_SPREAD),+ duration: travelOf(options.duration),+ bounce: clamp(finite(options.bounce, speedLinesDefaults.bounce), 0, 1),+ squash: clamp(finite(options.squash, speedLinesDefaults.squash), 0, 1),+ seed: finite(options.seed, speedLinesDefaults.seed),+ delay: Math.max(0, finite(options.delay, speedLinesDefaults.delay)),+ speed: Math.max(0, finite(options.speed, speedLinesDefaults.speed)),+ };+}++type Settings = ReturnType<typeof settingsOf>;++function directionOf(settings: Settings) {+ const { from, to, width, height } = settings;+ const dx = (to.x - from.x) * width;+ const dy = (to.y - from.y) * height;+ const distance = Math.hypot(dx, dy);+ if (distance < 1e-6) return { dx: 1, dy: 0, distance: 0 };+ return { dx: dx / distance, dy: dy / distance, distance };+}++function along(position: number, size: number, step: number) {+ if (step > 1e-9) return (size - position) / step;+ if (step < -1e-9) return -position / step;+ return Number.POSITIVE_INFINITY;+}++function exitDistance(+ cx: number,+ cy: number,+ cos: number,+ sin: number,+ width: number,+ height: number,+) {+ const inside = cx >= 0 && cx <= width && cy >= 0 && cy <= height;+ if (!inside) {+ const reachX = Math.max(Math.abs(cx), Math.abs(width - cx));+ const reachY = Math.max(Math.abs(cy), Math.abs(height - cy));+ return Math.hypot(reachX, reachY);+ }+ return Math.min(along(cx, width, cos), along(cy, height, sin));+}++function springOf(bounce: number) {+ const landing = LANDING + CARRY * bounce;+ const kappa = (1 + Math.sqrt(1 - landing)) / 2;+ const gain = 1 / (0.5 - kappa / 3);+ const echo = ECHO * bounce;+ const decrement = -Math.log(echo);+ const damping = echo > 0 ? decrement / Math.hypot(Math.PI, decrement) : 1;+ const natural = 1 / (1 + SOFTEN * bounce);+ const decay = damping * natural;+ return {+ kappa,+ gain,+ contact: gain * (1 - kappa),+ decay,+ ring: natural * Math.sqrt(1 - damping * damping),+ settle: Math.ceil(SETTLE / decay),+ };+}++function easeOf(time: number, travel: number, bounce: number) {+ if (time <= 0) return 0;+ const { kappa, gain, contact, decay, ring, settle } = springOf(bounce);+ if (time < travel) {+ const w = time / travel;+ return gain * ((w * w) / 2 - (kappa * w * w * w) / 3);+ }+ const since = time - travel;+ if (since >= settle) return 1;+ const taper = smoothstep((2 * since) / settle - 1);+ const wave = ring > 1e-9 ? Math.sin(ring * since) / ring : since;+ const envelope = Math.exp(-decay * since) * (1 - taper);+ return 1 + (contact / travel) * wave * envelope;+}++export function getSpeedLinesTimeline(options: SpeedLinesOptions = {}) {+ const { mode, duration, bounce } = settingsOf(options);+ if (mode === "focus") return { mode, impact: IMPACT, end: FOCUS_END };+ return { mode, impact: duration, end: duration + springOf(bounce).settle };+}++export type SpeedLinesTimeline = ReturnType<typeof getSpeedLinesTimeline>;++export const speedLinesLength = getSpeedLinesTimeline().end;++export function getSpeedLinesDuration(options: SpeedLinesOptions = {}) {+ const { delay, speed } = settingsOf(options);+ if (speed === 0) return 1;+ const { end } = getSpeedLinesTimeline(options);+ return Math.max(1, Math.ceil(delay + (end + HOLD) / speed));+}++export function getSpeedLinesTime(+ frame: number,+ options: SpeedLinesOptions = {},+) {+ const { fps, delay, speed } = settingsOf(options);+ const elapsed = Math.max(0, finite(frame, 0) - delay);+ return elapsed * (30 / fps) * speed;+}++export function getSpeedLinesEase(+ time: number,+ options: SpeedLinesOptions = {},+) {+ const { duration, bounce } = settingsOf(options);+ return easeOf(finite(time, 0), duration, bounce);+}++function positionAt(time: number, settings: Settings) {+ const { mode, from, to, width, height, duration, bounce } = settings;+ if (mode === "focus") {+ return { x: settings.x * width, y: settings.y * height, progress: 1 };+ }+ const progress = easeOf(time, duration, bounce);+ const startX = from.x * width;+ const startY = from.y * height;+ return {+ x: startX + (to.x * width - startX) * progress,+ y: startY + (to.y * height - startY) * progress,+ progress,+ };+}++export function getSpeedLinesPosition(+ time: number,+ options: SpeedLinesOptions = {},+) {+ const { x, y } = positionAt(finite(time, 0), settingsOf(options));+ return { x, y };+}++function shapeAt(time: number, settings: Settings) {+ const { mode, duration, bounce, squash, unit, speed } = settings;+ if (mode === "focus") return { rotation: 0, along: 1, across: 1 };+ const { dx, dy, distance } = directionOf(settings);+ const rotation = (Math.atan2(dy, dx) * 180) / Math.PI;+ if (squash === 0 || distance === 0 || time <= 0) {+ return { rotation, along: 1, across: 1 };+ }+ const span = distance / unit;+ const ahead = easeOf(time + PROBE, duration, bounce);+ const behind = easeOf(time - PROBE, duration, bounce);+ const rate = (Math.abs(ahead - behind) / (2 * PROBE)) * span * speed;+ const landed = time > duration ? easeOf(time, duration, bounce) - 1 : 0;+ const past = Math.max(0, landed) * span;+ const stretch = STRETCH * Math.tanh((squash * STRETCH_GAIN * rate) / STRETCH);+ const compression =+ SQUASH * Math.tanh((squash * SQUASH_GAIN * past) / SQUASH);+ const strain = clamp(stretch - compression, -SQUASH, STRETCH);+ return { rotation, along: Math.exp(strain), across: Math.exp(-strain) };+}++export function getSpeedLinesShape(+ time: number,+ options: SpeedLinesOptions = {},+) {+ return shapeAt(finite(time, 0), settingsOf(options));+}++export type SpeedLinesShape = ReturnType<typeof getSpeedLinesShape>;++export function getSpeedLinesVelocity(+ frame: number,+ options: SpeedLinesOptions = {},+) {+ const settings = settingsOf(options);+ const current = finite(frame, 0);+ const now = positionAt(getSpeedLinesTime(current, options), settings);+ const before = positionAt(getSpeedLinesTime(current - 1, options), settings);+ const scale = settings.fps / 30;+ const x = (now.x - before.x) * scale;+ const y = (now.y - before.y) * scale;+ const { dx, dy } = directionOf(settings);+ return { x, y, forward: x * dx + y * dy };+}++function streakSeeds(settings: Settings) {+ const { seed, count, spread, unit } = settings;+ const band = spread * unit;+ const phase = random(`speed-lines-${seed}-lanes`);+ return Array.from({ length: count }, (_, index) => {+ const jitter = (key(seed, index, "lane") - 0.5) / (2 * count);+ const lane = fraction(phase + GOLDEN * index + jitter);+ const slot = (index + key(seed, index, "spawn")) / count;+ return {+ index,+ spawn: SPAWN_START + (SPAWN_END - SPAWN_START) * slot,+ offset: band * (lane - 0.5),+ factor: 0.5 + 0.5 * key(seed, index, "length"),+ setback: SETBACK * band * key(seed, index, "setback"),+ };+ });+}++export function getSpeedLinesStreaks(+ frame: number,+ options: SpeedLinesOptions = {},+): SpeedLinesStreak[] {+ const settings = settingsOf(options);+ if (settings.mode !== "trail") return [];+ const time = getSpeedLinesTime(frame, options);+ const { dx, dy, distance } = directionOf(settings);+ if (distance === 0 || time <= 0) return [];+ const { forward } = getSpeedLinesVelocity(frame, options);+ const { unit, duration, bounce, weight } = settings;+ const fast = smoothstep((forward - SLOW * unit) / ((FAST - SLOW) * unit));+ const gate = fast * (1 - smoothstep(time - duration));+ if (gate <= 0) return [];+ const center = positionAt(time, settings);+ const progress = time / duration;+ const life = Math.max(MIN_LIFE, LIFE * duration) / duration;+ const minimum = 0.5 * weight * unit;+ const streaks: SpeedLinesStreak[] = [];+ for (const streak of streakSeeds(settings)) {+ const age = (progress - streak.spawn) / life;+ if (age <= 0 || age >= 1) continue;+ const reach = SHUTTER * streak.factor * forward * gate;+ const drawn = easeOut(age / DRAW);+ const erased = smoothstep((age - ERASE) / (1 - ERASE));+ const length = reach * (drawn - erased);+ if (length < minimum) continue;+ const spawned = easeOf(streak.spawn * duration, duration, bounce);+ const since = Math.max(0, (center.progress - spawned) * distance);+ const base = streak.setback + DRIFT * since;+ const front = base + reach * erased;+ const back = base + reach * drawn;+ const laneX = center.x - dy * streak.offset;+ const laneY = center.y + dx * streak.offset;+ streaks.push({+ index: streak.index,+ offset: streak.offset,+ reach,+ x1: round(laneX - dx * front),+ y1: round(laneY - dy * front),+ x2: round(laneX - dx * back),+ y2: round(laneY - dy * back),+ length,+ });+ }+ return streaks;+}++export function getSpeedLinesRadius(time: number, ray: SpeedLinesRayTiming) {+ const { rest, outer, start = 0, release = RELEASE } = ray;+ const t = finite(time, 0);+ if (t <= start) return outer;+ if (t < IMPACT) {+ const q = (t - start) / (IMPACT - start);+ return outer + (rest - outer) * q * q;+ }+ const settle = (at: number) =>+ rest * (1 + RELAX * (1 - Math.exp(-(at - IMPACT) / RELAX_RATE)));+ if (t < release) return settle(t);+ const held = settle(release);+ const q = clamp((t - release) / RETRACT, 0, 1);+ return outer - (outer - held) * (1 - q * q);+}++export function getSpeedLinesRays(+ frame: number,+ options: SpeedLinesOptions = {},+): SpeedLinesRay[] {+ const settings = settingsOf(options);+ if (settings.mode !== "focus") return [];+ const time = getSpeedLinesTime(frame, options);+ if (time <= 0 || time >= FOCUS_END) return [];+ const { seed, count, spread, weight, unit, width, height } = settings;+ const cx = settings.x * width;+ const cy = settings.y * height;+ const minimum = 0.5 * weight * unit;+ const rotation = random(`speed-lines-${seed}-rotation`);+ const rays: SpeedLinesRay[] = [];+ for (let index = 0; index < count; index++) {+ const jitter = ANGLE_JITTER * (key(seed, index, "angle") - 0.5);+ const angle = 2 * Math.PI * (rotation + (index + jitter) / count);+ const cos = Math.cos(angle);+ const sin = Math.sin(angle);+ const reach = RADIUS_JITTER * key(seed, index, "radius");+ const rest = spread * unit * (1 + reach);+ const outer = exitDistance(cx, cy, cos, sin, width, height) + weight * unit;+ const inner = getSpeedLinesRadius(time, {+ rest,+ outer,+ start: RUSH_JITTER * key(seed, index, "rush"),+ release: RELEASE + RELEASE_JITTER * key(seed, index, "release"),+ });+ const length = outer - inner;+ if (length < minimum) continue;+ rays.push({+ index,+ angle,+ rest,+ inner,+ outer,+ x1: round(cx + cos * inner),+ y1: round(cy + sin * inner),+ x2: round(cx + cos * outer),+ y2: round(cy + sin * outer),+ length,+ });+ }+ return rays;+}++export function getSpeedLinesState(+ frame: number,+ options: SpeedLinesOptions = {},+) {+ const settings = settingsOf(options);+ const time = getSpeedLinesTime(frame, options);+ const point = positionAt(time, settings);+ const shape = shapeAt(time, settings);+ const rotation = round(shape.rotation);+ const scale = `scale(${fine(shape.along)}, ${fine(shape.across)})`;+ const streaks = getSpeedLinesStreaks(frame, options);+ const rays = getSpeedLinesRays(frame, options);+ const path = [...streaks, ...rays]+ .map(({ x1, y1, x2, y2 }) => `M ${x1} ${y1} L ${x2} ${y2}`)+ .join(" ");+ return {+ mode: settings.mode,+ width: settings.width,+ height: settings.height,+ unit: settings.unit,+ time,+ x: point.x,+ y: point.y,+ left: (point.x / settings.width) * 100,+ top: (point.y / settings.height) * 100,+ radius: (settings.spread * settings.unit) / 2,+ strokeWidth: settings.weight * settings.unit,+ rotation,+ along: shape.along,+ across: shape.across,+ transform:+ shape.along === 1+ ? CENTER+ : `${CENTER} rotate(${rotation}deg) ${scale} rotate(${-rotation}deg)`,+ streaks,+ rays,+ path,+ };+}++export type SpeedLinesState = ReturnType<typeof getSpeedLinesState>;++export function SpeedLines({+ mode = speedLinesDefaults.mode,+ from = speedLinesDefaults.from,+ to,+ x = speedLinesDefaults.x,+ y = speedLinesDefaults.y,+ count = speedLinesDefaults.count,+ weight = speedLinesDefaults.weight,+ spread = speedLinesDefaults.spread,+ duration = speedLinesDefaults.duration,+ bounce = speedLinesDefaults.bounce,+ squash = speedLinesDefaults.squash,+ color = speedLinesDefaults.color,+ seed = speedLinesDefaults.seed,+ delay = speedLinesDefaults.delay,+ speed = speedLinesDefaults.speed,+ children,+ className,+}: SpeedLinesProps) {+ const frame = useCurrentFrame();+ const { width, height, fps } = useVideoConfig();+ const state = getSpeedLinesState(frame, {+ mode,+ from,+ to,+ x,+ y,+ count,+ weight,+ spread,+ duration,+ bounce,+ squash,+ seed,+ delay,+ speed,+ width,+ height,+ fps,+ });+ const fallback = state.mode === "trail" && children === undefined;+ const placed = children !== undefined && children !== null;++ return (+ <div+ className={className}+ style={{ position: "absolute", inset: 0, pointerEvents: "none" }}+ >+ <svg+ width="100%"+ height="100%"+ viewBox={`0 0 ${width} ${height}`}+ aria-hidden="true"+ style={{ position: "absolute", inset: 0, display: "block" }}+ >+ {state.path ? (+ <path+ d={state.path}+ fill="none"+ stroke={color}+ strokeWidth={state.strokeWidth}+ strokeLinecap="round"+ />+ ) : null}+ {fallback ? (+ <ellipse+ cx={state.x}+ cy={state.y}+ rx={state.radius * state.along}+ ry={state.radius * state.across}+ transform={`rotate(${state.rotation} ${state.x} ${state.y})`}+ fill={color}+ />+ ) : null}+ </svg>+ {placed ? (+ <div+ style={{+ position: "absolute",+ left: `${state.left}%`,+ top: `${state.top}%`,+ width: "max-content",+ transform: state.transform,+ transformOrigin: "50% 50%",+ }}+ >+ {children}+ </div>+ ) : null}+ </div>+ );+}diff --git a/registry/remocn/squiggle/__tests__/squiggle.test.ts b/registry/remocn/squiggle/__tests__/squiggle.test.tsnew file mode 100644index 00000000..1a8652d2--- /dev/null+++ b/registry/remocn/squiggle/__tests__/squiggle.test.ts@@ -0,0 +1,533 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getSquiggleCalm,+ getSquiggleCurve,+ getSquiggleDuration,+ getSquiggleEnvelope,+ getSquiggleHead,+ getSquigglePath,+ getSquigglePhase,+ getSquiggleState,+ getSquiggleTail,+ getSquiggleTime,+ getSquiggleTimeline,+ getSquiggleTrim,+ type SquiggleOptions,+ type SquigglePoint,+ type SquiggleShape,+ squiggleDefaults,+ squiggleLength,+} from "..";+import { squiggleConfig } from "../config";++const SHAPES: SquiggleShape[] = ["wave", "zigzag", "loops", "coil"];+const ORIGIN = { x: 0.375, y: 0.5 };++function polylineLength(points: readonly SquigglePoint[]) {+ let total = 0;+ for (let i = 1; i < points.length; i++) {+ const a = points[i - 1];+ const b = points[i];+ total += Math.hypot(b.x - a.x, b.y - a.y);+ }+ return total;+}++function backwardRuns(points: readonly SquigglePoint[]) {+ const runs: number[] = [];+ let run = 0;+ for (let i = 1; i < points.length; i++) {+ const dx = points[i].x - points[i - 1].x;+ if (dx < 0) {+ run -= dx;+ } else if (run > 0) {+ runs.push(run);+ run = 0;+ }+ }+ return runs;+}++function crestsOf(points: readonly SquigglePoint[], from: number, to: number) {+ const crests: number[] = [];+ for (let i = 1; i < points.length - 1; i++) {+ const { x, y } = points[i];+ if (x <= from || x >= to) continue;+ if (y > points[i - 1].y && y >= points[i + 1].y) crests.push(x);+ }+ return crests;+}++function heightAt(points: readonly SquigglePoint[], x: number) {+ for (let i = 1; i < points.length; i++) {+ const a = points[i - 1];+ const b = points[i];+ if (a.x <= x && x <= b.x && b.x > a.x) {+ return a.y + ((b.y - a.y) * (x - a.x)) / (b.x - a.x);+ }+ }+ return Number.NaN;+}++function bandOf(frame: number, options: SquiggleOptions = {}) {+ const state = getSquiggleState(frame, { erase: false, ...options });+ return Math.max(...state.points.map((point) => point.y - state.start.y));+}++describe("squiggle timeline", () => {+ it("ends the default draw, hold and erase at the documented length", () => {+ const timeline = getSquiggleTimeline();+ expect(squiggleLength).toBe(66);+ expect(timeline.draw).toBe(24);+ expect(timeline.settle).toBe(36);+ expect(timeline.eraseStart).toBe(48);+ expect(timeline.eraseEnd).toBe(66);+ expect(timeline.end).toBe(squiggleLength);+ expect(timeline.duration).toBe(80);+ expect(getSquiggleDuration()).toBe(squiggleConfig.durationInFrames);+ });++ it("scales the preview duration with speed, hold, delay and erase", () => {+ expect(getSquiggleDuration({ speed: 2 })).toBe(40);+ expect(getSquiggleDuration({ speed: 0.5 })).toBe(160);+ expect(getSquiggleDuration({ speed: 0 })).toBe(1);+ expect(getSquiggleDuration({ hold: 30 })).toBe(98);+ expect(getSquiggleDuration({ hold: Number.NaN })).toBe(80);+ expect(getSquiggleDuration({ erase: false })).toBe(60);+ expect(getSquiggleDuration({ delay: 10 })).toBe(90);+ expect(getSquiggleDuration({ delay: 10, speed: 2 })).toBe(50);+ expect(getSquiggleTimeline({ erase: false }).end).toBe(36);+ const resolve = squiggleConfig.getDurationInFrames;+ expect(resolve?.({ speed: 2, hold: 0, erase: true })).toBe(34);+ expect(resolve?.({ erase: false, delay: 6 })).toBe(66);+ });++ it("maps frames onto the 30 fps timeline after the delay", () => {+ expect(getSquiggleTime(Number.NaN)).toBe(0);+ expect(getSquiggleTime(-5)).toBe(0);+ expect(getSquiggleTime(8, { delay: 12 })).toBe(0);+ expect(getSquiggleTime(10, { delay: 4, speed: 2, fps: 60 })).toBe(6);+ });++ it("draws nothing before the start and nothing once the tail lands", () => {+ for (const frame of [-5, 0]) {+ const state = getSquiggleState(frame);+ expect(state.visible).toBe(false);+ expect(state.path).toBe("");+ expect(state.points).toEqual([]);+ }+ expect(getSquiggleState(1).visible).toBe(true);+ for (const frame of [0, 6, 12]) {+ expect(getSquiggleState(frame, { delay: 12 }).visible).toBe(false);+ }+ expect(getSquiggleState(13, { delay: 12 }).visible).toBe(true);+ expect(getSquiggleState(64).visible).toBe(true);+ for (const frame of [66, 67, 80, 500]) {+ for (const shape of SHAPES) {+ const state = getSquiggleState(frame, { shape });+ expect(state.visible).toBe(false);+ expect(state.path).toBe("");+ }+ }+ const kept = getSquiggleState(500, { erase: false });+ expect(kept.visible).toBe(true);+ expect(kept.head).toBe(1);+ expect(kept.tail).toBe(0);+ });+});++describe("squiggle trim path", () => {+ it("runs the head out on a fast ease-out, never at constant speed", () => {+ expect(getSquiggleHead(0)).toBe(0);+ expect(getSquiggleHead(-3)).toBe(0);+ expect(getSquiggleHead(Number.NaN)).toBe(0);+ expect(getSquiggleHead(1)).toBeCloseTo(1 - (23 / 24) ** 4, 10);+ expect(getSquiggleHead(1)).toBeGreaterThan(3 / 24);+ expect(getSquiggleHead(8)).toBeGreaterThan(0.8);+ expect(getSquiggleHead(24)).toBe(1);+ expect(getSquiggleHead(40)).toBe(1);+ for (let frame = 1; frame < 24; frame++) {+ const before = getSquiggleHead(frame) - getSquiggleHead(frame - 1);+ const after = getSquiggleHead(frame + 1) - getSquiggleHead(frame);+ expect(after).toBeLessThan(before);+ }+ });++ it("advances the head point along the course on every frame", () => {+ const forward: SquiggleShape[] = ["wave", "zigzag"];+ for (const shape of forward) {+ let previous = Number.NEGATIVE_INFINITY;+ for (let frame = 1; frame <= 24; frame++) {+ const options = { ...ORIGIN, shape, erase: false };+ const { points } = getSquiggleState(frame, options);+ const head = points[points.length - 1].x;+ expect(head).toBeGreaterThan(previous);+ previous = head;+ }+ expect(previous).toBeCloseTo(800, 6);+ }+ });++ it("erases on an ease-in-out only after the hold", () => {+ const timeline = getSquiggleTimeline();+ const tail = (time: number) => getSquiggleTail(time, timeline);+ expect(tail(48)).toBe(0);+ expect(tail(57)).toBeCloseTo(0.5, 10);+ expect(tail(66)).toBe(1);+ const early = tail(49) - tail(48);+ const middle = tail(57) - tail(56);+ expect(middle).toBeGreaterThan(early * 20);+ const kept = getSquiggleTimeline({ erase: false });+ expect(getSquiggleTail(60, kept)).toBe(0);+ expect(getSquiggleTail(60, getSquiggleTimeline({ hold: 30 }))).toBe(0);+ });++ it("cuts the visible path at the head and tail fractions of the arc", () => {+ for (const shape of SHAPES) {+ for (const frame of [1, 4, 8, 12, 50, 57, 62]) {+ const state = getSquiggleState(frame, { shape });+ const drawn = polylineLength(state.points);+ expect(drawn / state.total).toBeCloseTo(state.head - state.tail, 6);+ }+ }+ const corner = [+ { x: 0, y: 0 },+ { x: 10, y: 0 },+ { x: 10, y: 10 },+ ];+ expect(getSquiggleTrim(corner, 0.25, 0.75)).toEqual({+ total: 20,+ points: [+ { x: 5, y: 0 },+ { x: 10, y: 0 },+ { x: 10, y: 5 },+ ],+ });+ expect(getSquiggleTrim(corner, 0.5, 0.5).points).toEqual([]);+ expect(getSquiggleTrim([], 0, 1)).toEqual({ total: 0, points: [] });+ });++ it("pins both ends of every shape to the course once drawn", () => {+ const placements = [+ { ...ORIGIN, angle: 0 },+ { angle: 30, x: 0.2, y: 0.3 },+ ];+ for (const placement of placements) {+ const radians = (placement.angle * Math.PI) / 180;+ const start = { x: placement.x * 1280, y: placement.y * 720 };+ const end = {+ x: start.x + 320 * Math.cos(radians),+ y: start.y + 320 * Math.sin(radians),+ };+ for (const shape of SHAPES) {+ for (const frame of [24, 36, 48]) {+ const state = getSquiggleState(frame, { shape, ...placement });+ const first = state.points[0];+ const last = state.points[state.points.length - 1];+ expect(first.x).toBeCloseTo(start.x, 6);+ expect(first.y).toBeCloseTo(start.y, 6);+ expect(last.x).toBeCloseTo(end.x, 6);+ expect(last.y).toBeCloseTo(end.y, 6);+ expect(state.end.x).toBeCloseTo(end.x, 6);+ expect(state.end.y).toBeCloseTo(end.y, 6);+ }+ }+ }+ });++ it("erases in the drawing direction toward the pinned end point", () => {+ for (const angle of [0, 90]) {+ let previous = Number.NEGATIVE_INFINITY;+ for (const frame of [50, 52, 54, 56, 58, 60, 62, 64]) {+ const state = getSquiggleState(frame, { angle });+ const first = state.points[0];+ const last = state.points[state.points.length - 1];+ expect(last.x).toBeCloseTo(state.end.x, 6);+ expect(last.y).toBeCloseTo(state.end.y, 6);+ const progress = angle === 0 ? first.x : first.y;+ expect(progress).toBeGreaterThan(previous);+ previous = progress;+ }+ }+ });+});++describe("squiggle signature motion", () => {+ it("swims the phase forward while drawing, then comes to rest", () => {+ const timeline = getSquiggleTimeline();+ const phase = (time: number) => getSquigglePhase(time, timeline);+ expect(phase(0)).toBe(0);+ for (let frame = 0; frame < 36; frame++) {+ expect(phase(frame + 1)).toBeGreaterThan(phase(frame));+ }+ for (let frame = 1; frame < 36; frame++) {+ const before = phase(frame) - phase(frame - 1);+ const after = phase(frame + 1) - phase(frame);+ expect(after).toBeLessThan(before);+ }+ expect(phase(12)).toBeGreaterThan(1);+ expect(phase(36)).toBe(1.5);+ expect(phase(48)).toBe(1.5);+ expect(phase(57)).toBeCloseTo(1.75, 10);+ expect(phase(66)).toBe(2);+ const kept = getSquiggleTimeline({ erase: false });+ expect(getSquigglePhase(66, kept)).toBe(1.5);+ });++ it("moves every crest of the drawn line forward with the phase", () => {+ const crests = (frame: number) => {+ const state = getSquiggleState(frame, { ...ORIGIN, erase: false });+ return { phase: state.phase, crests: crestsOf(state.points, 560, 720) };+ };+ for (const frame of [12, 16, 24, 36]) {+ const sample = crests(frame);+ expect(sample.crests.length).toBeGreaterThanOrEqual(3);+ for (const crest of sample.crests) {+ const cycles = (crest - 492) / 48 - sample.phase;+ expect(Math.abs(cycles - Math.round(cycles))).toBeLessThan(1e-6);+ }+ }+ const before = crests(12).crests[0];+ const after = crests(16).crests[0];+ const travel = (getSquigglePhase(16) - getSquigglePhase(12)) * 48;+ expect(after - before).toBeCloseTo(travel, 6);+ expect(travel).toBeGreaterThan(8);+ });++ it("eases the amplitude from lively to calm without overshoot", () => {+ expect(getSquiggleCalm(0)).toBe(0);+ expect(getSquiggleCalm(36)).toBe(1);+ expect(getSquiggleCalm(90)).toBe(1);+ const amplitudes: number[] = [];+ for (let frame = 0; frame <= 60; frame++) {+ amplitudes.push(getSquiggleState(frame).amplitude);+ }+ expect(amplitudes[0]).toBe(14);+ expect(amplitudes[36]).toBeCloseTo(7, 10);+ for (let i = 1; i < amplitudes.length; i++) {+ expect(amplitudes[i]).toBeLessThanOrEqual(amplitudes[i - 1]);+ }+ expect(Math.min(...amplitudes)).toBeCloseTo(7, 10);+ expect(bandOf(8)).toBeGreaterThan(12);+ expect(bandOf(8)).toBeLessThanOrEqual(14);+ expect(bandOf(36)).toBeCloseTo(7, 6);+ expect(bandOf(36, { settle: 0 })).toBeCloseTo(14, 6);+ expect(bandOf(36, { settle: 1 })).toBeCloseTo(0, 6);+ });++ it("recomputes the shape every frame, never a static reveal", () => {+ const early = getSquiggleState(6, ORIGIN).points;+ const later = getSquiggleState(10, ORIGIN).points;+ for (const x of [560, 600, 640]) {+ const drift = Math.abs(heightAt(early, x) - heightAt(later, x));+ expect(drift).toBeGreaterThan(1);+ }+ expect(getSquiggleState(24).path).not.toBe(getSquiggleState(36).path);+ expect(getSquiggleState(36).path).toBe(getSquiggleState(47).path);+ });+});++describe("squiggle shapes", () => {+ it("keeps the wave and the zigzag moving forward inside the band", () => {+ const forward: SquiggleShape[] = ["wave", "zigzag"];+ for (const shape of forward) {+ const points = getSquiggleCurve({+ shape,+ length: 320,+ wavelength: 48,+ amplitude: 10,+ phase: 0.3,+ });+ expect(backwardRuns(points)).toEqual([]);+ for (const point of points) {+ expect(Math.abs(point.y)).toBeLessThanOrEqual(10 + 1e-9);+ }+ expect(Math.max(...points.map((point) => point.y))).toBeCloseTo(10, 6);+ }+ });++ it("builds the zigzag from exact alternating corners", () => {+ const points = getSquiggleCurve({+ shape: "zigzag",+ length: 320,+ wavelength: 48,+ amplitude: 10,+ phase: 0,+ });+ expect(points).toHaveLength(15);+ const corners = points.slice(1, -1);+ for (const [index, corner] of corners.entries()) {+ expect(corner.x).toBeCloseTo(12 + index * 24, 6);+ expect(Math.sign(corner.y)).toBe(index % 2 === 0 ? 1 : -1);+ }+ for (const corner of corners.slice(2, -2)) {+ expect(Math.abs(corner.y)).toBeCloseTo(10, 6);+ }+ expect(getSquiggleState(24, { shape: "zigzag" }).join).toBe("miter");+ expect(getSquiggleState(24, { shape: "wave" }).join).toBe("round");+ });++ it("loops above the course, the coil wider than the loops", () => {+ const widthOf = (shape: SquiggleShape, amplitude: number) => {+ const points = getSquiggleCurve({+ shape,+ length: 320,+ wavelength: 48,+ amplitude,+ phase: 0,+ });+ for (let i = 1; i < points.length; i++) {+ if (points[i].x < points[i - 1].x) {+ expect(points[i].y).toBeLessThan(0);+ expect(points[i - 1].y).toBeLessThan(0);+ }+ }+ return Math.max(...backwardRuns(points));+ };+ for (const amplitude of [14, 7]) {+ const loops = widthOf("loops", amplitude);+ const coil = widthOf("coil", amplitude);+ expect(loops).toBeGreaterThan(12);+ expect(loops).toBeLessThan(20);+ expect(coil).toBeGreaterThan(36);+ expect(coil).toBeLessThan(48);+ }+ });++ it("unfurls loops into a straight line when the height calms away", () => {+ const looped: SquiggleShape[] = ["loops", "coil"];+ for (const shape of looped) {+ const points = getSquiggleCurve({+ shape,+ length: 320,+ wavelength: 48,+ amplitude: 0,+ phase: 0.4,+ });+ expect(backwardRuns(points)).toEqual([]);+ expect(polylineLength(points)).toBeCloseTo(320, 6);+ const state = getSquiggleState(40, { shape, settle: 1 });+ expect(state.total).toBeCloseTo(320, 6);+ }+ });++ it("tapers the pattern to nothing at both pinned ends", () => {+ expect(getSquiggleEnvelope(0, 320, 48)).toBe(0);+ expect(getSquiggleEnvelope(320, 320, 48)).toBe(0);+ expect(getSquiggleEnvelope(160, 320, 48)).toBe(1);+ expect(getSquiggleEnvelope(24, 320, 48)).toBeCloseTo(0.5, 10);+ expect(getSquiggleEnvelope(296, 320, 48)).toBeCloseTo(0.5, 10);+ expect(getSquiggleEnvelope(10, 0, 48)).toBe(0);+ });+});++describe("squiggle reference-px scaling", () => {+ it("scales sizes by height / 720 and positions by fractions", () => {+ const at = (width: number, height: number) =>+ getSquiggleState(36, { ...ORIGIN, width, height });+ const base = at(1280, 720);+ const hd = at(1920, 1080);+ const uhd = at(3840, 2160);+ expect(base.unit).toBe(1);+ expect(hd.unit).toBe(1.5);+ expect(uhd.unit).toBe(3);+ expect(base.strokeWidth).toBe(3);+ expect(hd.strokeWidth).toBe(4.5);+ expect(uhd.strokeWidth).toBe(9);+ expect(hd.amplitude).toBeCloseTo(10.5, 10);+ expect(uhd.amplitude).toBeCloseTo(21, 10);+ expect(hd.wavelength).toBe(72);+ expect(uhd.wavelength).toBe(144);+ expect(base.start).toEqual({ x: 480, y: 360 });+ expect(hd.start).toEqual({ x: 720, y: 540 });+ expect(uhd.start).toEqual({ x: 1440, y: 1080 });+ expect(hd.end.x).toBeCloseTo(1200, 6);+ expect(uhd.end.x).toBeCloseTo(2400, 6);+ expect(hd.total / base.total).toBeCloseTo(1.5, 2);+ expect(uhd.total / base.total).toBeCloseTo(3, 2);+ const band = (state: typeof base) =>+ Math.max(...state.points.map((point) => point.y - state.start.y));+ expect(band(hd) / band(base)).toBeCloseTo(1.5, 6);+ expect(band(uhd) / band(base)).toBeCloseTo(3, 6);+ expect(at(1080, 1920).length).toBeCloseTo((320 * 1920) / 720, 6);+ });+});++describe("squiggle determinism", () => {+ it("renders any frame identically in any sampling order", () => {+ const sample = (frame: number) =>+ getSquiggleState(frame, { shape: "coil", angle: -20, x: 0.3, y: 0.6 });+ const frames = [0, 1, 7, 19, 33, 50, 61, 66, 90];+ const forward = frames.map(sample);+ const backward = [...frames].reverse().map(sample).reverse();+ expect(backward).toEqual(forward);+ expect(sample(19)).toEqual(forward[3]);+ expect(sample(19).path).toBe(forward[3].path);+ });++ it("maps frame rate, speed and delay onto the same timeline", () => {+ const base = getSquiggleState(20, { shape: "loops" });+ expect(getSquiggleState(40, { shape: "loops", fps: 60 })).toEqual(base);+ expect(getSquiggleState(40, { shape: "loops", speed: 0.5 })).toEqual(base);+ expect(getSquiggleState(30, { shape: "loops", delay: 10 })).toEqual(base);+ const frozen = getSquiggleState(90, { speed: 0 });+ expect(frozen).toEqual(getSquiggleState(0));+ expect(frozen.visible).toBe(false);+ });++ it("stays finite and bounded for invalid or extreme input", () => {+ for (const shape of SHAPES) {+ for (const frame of [1, 12, 40, 57]) {+ const state = getSquiggleState(frame, {+ shape,+ length: Number.NaN,+ amplitude: -5,+ wavelength: 0,+ weight: Number.NaN,+ x: Number.POSITIVE_INFINITY,+ settle: 9,+ hold: -3,+ });+ expect(state.path).not.toMatch(/NaN|Infinity/);+ expect(state.strokeWidth).toBe(3);+ }+ const dense = getSquiggleCurve({+ shape,+ length: 100000,+ wavelength: 1,+ amplitude: 10,+ phase: 0.3,+ });+ expect(dense.length).toBeLessThanOrEqual(4000);+ }+ const repeated = [+ { x: 0, y: 0 },+ { x: 0.001, y: 0 },+ { x: 1, y: 1 },+ ];+ expect(getSquigglePath(repeated)).toBe("M0 0L1 1");+ });+});++describe("squiggle config", () => {+ it("matches the component defaults and exposes every shape", () => {+ const controls = resolveControls("squiggle", squiggleConfig.controls);+ expect(getDefaults(controls)).toEqual({ ...squiggleDefaults });+ const shape = controls.shape;+ expect(shape.type === "select" ? shape.options : []).toEqual(SHAPES);+ const range = (key: string) => {+ const control = controls[key];+ return control.type === "number" ? [control.min, control.max] : [];+ };+ expect(range("weight")).toEqual([1, 12]);+ expect(range("amplitude")).toEqual([0, 60]);+ expect(range("x")).toEqual([0, 1]);+ expect(range("y")).toEqual([0, 1]);+ expect(range("settle")).toEqual([0, 1]);+ expect(squiggleConfig.previewBackdrop).toEqual({+ type: "color",+ value: "#002fa7",+ });+ });+});diff --git a/registry/remocn/squiggle/config.ts b/registry/remocn/squiggle/config.tsnew file mode 100644index 00000000..1a9b0d54--- /dev/null+++ b/registry/remocn/squiggle/config.ts@@ -0,0 +1,126 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";+import { getSquiggleDuration } from ".";++function durationOf(values: Record<string, unknown>) {+ const numeric = (key: string) => {+ const value = values[key];+ return typeof value === "number" ? value : undefined;+ };+ return getSquiggleDuration({+ speed: numeric("speed"),+ delay: numeric("delay"),+ hold: numeric("hold"),+ erase: values.erase !== false,+ });+}++export const squiggleConfig: ComponentConfig = {+ componentName: "Squiggle",+ importPath: "@/components/remocn/squiggle",+ controls: {+ shape: {+ type: "enum",+ default: "wave",+ variants: { wave: {}, zigzag: {}, loops: {}, coil: {} },+ description: "Shape",+ },+ color: { type: "color", default: "#ffffff", description: "Line color" },+ weight: {+ type: "number",+ default: 3,+ min: 1,+ max: 12,+ step: 0.5,+ description: "Stroke weight",+ hiddenFromList: false,+ },+ amplitude: {+ type: "number",+ default: 14,+ min: 0,+ max: 60,+ step: 1,+ description: "Amplitude",+ hiddenFromList: false,+ },+ wavelength: {+ type: "number",+ default: 48,+ min: 12,+ max: 160,+ step: 2,+ description: "Wavelength",+ hiddenFromList: false,+ },+ length: {+ type: "number",+ default: 320,+ min: 40,+ max: 1200,+ step: 10,+ description: "Length",+ hiddenFromList: false,+ },+ angle: {+ type: "number",+ default: 0,+ min: -180,+ max: 180,+ step: 5,+ description: "Angle",+ hiddenFromList: false,+ },+ x: {+ type: "number",+ default: 0.375,+ min: 0,+ max: 1,+ step: 0.005,+ description: "Start x",+ hiddenFromList: false,+ },+ y: {+ type: "number",+ default: 0.5,+ min: 0,+ max: 1,+ step: 0.005,+ description: "Start y",+ hiddenFromList: false,+ },+ settle: {+ type: "number",+ default: 0.5,+ min: 0,+ max: 1,+ step: 0.05,+ description: "Settle",+ hiddenFromList: false,+ },+ hold: {+ type: "number",+ default: 12,+ min: 0,+ max: 90,+ step: 1,+ description: "Hold",+ hiddenFromList: false,+ },+ erase: { type: "boolean", default: true, description: "Erase" },+ delay: {+ type: "number",+ default: 0,+ min: 0,+ max: 60,+ step: 1,+ description: "Delay",+ hiddenFromList: false,+ },+ },+ durationInFrames: 80,+ getDurationInFrames: durationOf,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#002fa7" },+};diff --git a/registry/remocn/squiggle/index.tsx b/registry/remocn/squiggle/index.tsxnew file mode 100644index 00000000..2da709fe--- /dev/null+++ b/registry/remocn/squiggle/index.tsx@@ -0,0 +1,423 @@+"use client";++import { useCurrentFrame, useVideoConfig } from "remotion";++export type SquiggleShape = "wave" | "zigzag" | "loops" | "coil";+export type SquiggleJoin = "miter" | "round";++export interface SquiggleProps {+ shape?: SquiggleShape;+ x?: number;+ y?: number;+ length?: number;+ angle?: number;+ amplitude?: number;+ wavelength?: number;+ weight?: number;+ color?: string;+ settle?: number;+ hold?: number;+ erase?: boolean;+ delay?: number;+ speed?: number;+ className?: string;+}++type Paint = "color" | "className";++export interface SquiggleOptions extends Omit<SquiggleProps, Paint> {+ width?: number;+ height?: number;+ fps?: number;+}++export interface SquigglePoint {+ x: number;+ y: number;+}++export interface SquiggleCurveInput {+ shape: SquiggleShape;+ length: number;+ wavelength: number;+ amplitude: number;+ phase: number;+ unit?: number;+}++export const squiggleDefaults: Required<Omit<SquiggleProps, "className">> = {+ shape: "wave",+ x: 0.375,+ y: 0.5,+ length: 320,+ angle: 0,+ amplitude: 14,+ wavelength: 48,+ weight: 3,+ color: "#ffffff",+ settle: 0.5,+ hold: 12,+ erase: true,+ delay: 0,+ speed: 1,+};++type SmoothShape = Exclude<SquiggleShape, "zigzag">;++const DRAW = 24;+const SETTLE = 36;+const ERASE = 18;+const SWIM = 1.5;+const EXIT_SWIM = 0.5;+const TAIL = 14;+const REST = 24;+const MIN_WAVELENGTH = 8;+const LOOP_FLOOR = 3;+const MIN_POINTS = 24;+const MAX_POINTS = 4000;+const EPSILON = 0.01;+const SAMPLES: Record<SmoothShape, number> = { wave: 32, loops: 64, coil: 80 };+const REACH: Record<SmoothShape, number> = { wave: 0, loops: 2.4, coil: 4.2 };++const finite = (value: number | undefined, fallback: number) =>+ typeof value === "number" && Number.isFinite(value) ? value : fallback;+const clamp = (value: number, min: number, max: number) =>+ Math.min(max, Math.max(min, value));+const round = (value: number) => Math.round(value * 100) / 100;+const rateOf = (speed: number | undefined) =>+ Math.max(0, finite(speed, squiggleDefaults.speed));+const shapeOf = (value: string | undefined): SquiggleShape =>+ value === "zigzag" || value === "loops" || value === "coil" ? value : "wave";+const joinOf = (shape: SquiggleShape): SquiggleJoin =>+ shape === "zigzag" ? "miter" : "round";+const easeOutQuart = (t: number) => 1 - (1 - t) ** 4;+const easeOutCubic = (t: number) => 1 - (1 - t) ** 3;+const easeInOutCubic = (t: number) =>+ t < 0.5 ? 4 * t ** 3 : 1 - (-2 * t + 2) ** 3 / 2;+const easeInOutSine = (t: number) => (1 - Math.cos(Math.PI * t)) / 2;++function smoothstep(value: number) {+ const t = clamp(value, 0, 1);+ return t * t * (3 - 2 * t);+}++export function getSquiggleTimeline(+ options: Pick<SquiggleOptions, "hold" | "erase"> = {},+) {+ const hold = Math.max(0, finite(options.hold, squiggleDefaults.hold));+ const erase = options.erase !== false;+ const eraseStart = SETTLE + hold;+ const eraseEnd = eraseStart + ERASE;+ const end = erase ? eraseEnd : SETTLE;+ return {+ draw: DRAW,+ settle: SETTLE,+ hold,+ erase,+ eraseStart,+ eraseEnd,+ end,+ duration: end + (erase ? TAIL : REST),+ };+}++export type SquiggleTimeline = ReturnType<typeof getSquiggleTimeline>;++export const squiggleLength = getSquiggleTimeline().end;++export function getSquiggleDuration(+ options: Pick<SquiggleOptions, "hold" | "erase" | "speed" | "delay"> = {},+) {+ const rate = rateOf(options.speed);+ if (rate === 0) return 1;+ const delay = Math.max(0, finite(options.delay, squiggleDefaults.delay));+ const { duration } = getSquiggleTimeline(options);+ return Math.max(1, Math.ceil(delay + duration / rate));+}++export function getSquiggleTime(+ frame: number,+ options: Pick<SquiggleOptions, "fps" | "speed" | "delay"> = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const delay = Math.max(0, finite(options.delay, squiggleDefaults.delay));+ const elapsed = Math.max(0, finite(frame, 0) - delay);+ return (elapsed * 30 * rateOf(options.speed)) / fps;+}++export function getSquiggleHead(time: number) {+ if (!(time > 0)) return 0;+ return easeOutQuart(Math.min(1, time / DRAW));+}++export function getSquiggleTail(+ time: number,+ timeline: SquiggleTimeline = getSquiggleTimeline(),+) {+ if (!timeline.erase) return 0;+ const progress = (time - timeline.eraseStart) / ERASE;+ if (!(progress > 0)) return 0;+ return easeInOutCubic(Math.min(1, progress));+}++export function getSquiggleCalm(time: number) {+ if (!(time > 0)) return 0;+ return easeInOutSine(Math.min(1, time / SETTLE));+}++export function getSquigglePhase(+ time: number,+ timeline: SquiggleTimeline = getSquiggleTimeline(),+) {+ const swim = time > 0 ? easeOutCubic(Math.min(1, time / SETTLE)) : 0;+ return SWIM * swim + EXIT_SWIM * getSquiggleTail(time, timeline);+}++export function getSquiggleEnvelope(+ s: number,+ length: number,+ wavelength: number,+) {+ const taper = Math.min(wavelength, length / 3);+ if (!(taper > 0)) return 0;+ return smoothstep(s / taper) * smoothstep((length - s) / taper);+}++function getZigzagCurve(+ length: number,+ wavelength: number,+ amplitude: number,+ shift: number,+) {+ const k = (2 * Math.PI) / wavelength;+ const points: SquigglePoint[] = [{ x: 0, y: 0 }];+ const first = Math.floor(-(Math.PI / 2 + shift) / Math.PI) + 1;+ for (let m = first; points.length < MAX_POINTS - 1; m++) {+ const s = (Math.PI / 2 + m * Math.PI + shift) / k;+ if (s >= length) break;+ if (s <= 0) continue;+ const side = m % 2 === 0 ? 1 : -1;+ const w = getSquiggleEnvelope(s, length, wavelength);+ points.push({ x: s, y: side * amplitude * w });+ }+ points.push({ x: length, y: 0 });+ return points;+}++export function getSquiggleCurve(input: SquiggleCurveInput) {+ const shape = shapeOf(input.shape);+ const length = Math.max(0, finite(input.length, 0));+ const wavelength = Math.max(1e-3, finite(input.wavelength, 1));+ const amplitude = Math.max(0, finite(input.amplitude, 0));+ const unit = Math.max(1e-3, finite(input.unit, 1));+ const shift = 2 * Math.PI * finite(input.phase, 0);+ if (shape === "zigzag") {+ return getZigzagCurve(length, wavelength, amplitude, shift);+ }+ const k = (2 * Math.PI) / wavelength;+ const gate = smoothstep(amplitude / (LOOP_FLOOR * unit));+ const reach = (REACH[shape] / k) * gate;+ const fine = wavelength / (SAMPLES[shape] * Math.max(1, unit));+ const coarsest = Math.max(length / MIN_POINTS, 1e-6);+ const step = clamp(fine, length / (MAX_POINTS - 2), coarsest);+ const sample = (s: number): SquigglePoint => {+ const w = getSquiggleEnvelope(s, length, wavelength);+ const theta = k * s - shift;+ if (shape === "wave") return { x: s, y: amplitude * w * Math.sin(theta) };+ const along = s - reach * w * Math.sin(theta);+ return { x: along, y: -amplitude * w * Math.cos(theta) };+ };+ const offset = (((shift / k) % step) + step) % step;+ const points = [sample(0)];+ for (let j = 0; points.length < MAX_POINTS - 1; j++) {+ const s = offset + j * step;+ if (s >= length) break;+ if (s > 0) points.push(sample(s));+ }+ points.push(sample(length));+ return points;+}++export function getSquiggleTrim(+ points: readonly SquigglePoint[],+ tail: number,+ head: number,+) {+ const lengths = [0];+ for (let i = 1; i < points.length; i++) {+ const a = points[i - 1];+ const b = points[i];+ lengths.push(lengths[i - 1] + Math.hypot(b.x - a.x, b.y - a.y));+ }+ const last = points.length - 1;+ const total = last > 0 ? lengths[last] : 0;+ const from = clamp(finite(tail, 0), 0, 1) * total;+ const to = clamp(finite(head, 0), 0, 1) * total;+ const trimmed: SquigglePoint[] = [];+ if (last < 1 || !(to - from > EPSILON)) return { total, points: trimmed };+ const pointAt = (distance: number, index: number): SquigglePoint => {+ const a = points[index - 1];+ const b = points[index];+ const span = lengths[index] - lengths[index - 1];+ const t = span > 0 ? (distance - lengths[index - 1]) / span : 0;+ return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };+ };+ let index = 1;+ while (index < last && lengths[index] < from) index++;+ trimmed.push(pointAt(from, index));+ while (index < last && lengths[index] < to) {+ trimmed.push(points[index]);+ index++;+ }+ trimmed.push(pointAt(to, index));+ return { total, points: trimmed };+}++export function getSquigglePath(points: readonly SquigglePoint[]) {+ let path = "";+ let previous = "";+ for (const point of points) {+ const pair = `${round(point.x)} ${round(point.y)}`;+ if (pair === previous) continue;+ path += `${path === "" ? "M" : "L"}${pair}`;+ previous = pair;+ }+ return path;+}++export function getSquiggleState(frame: number, options: SquiggleOptions = {}) {+ const width = Math.max(1, finite(options.width, 1280));+ const height = Math.max(1, finite(options.height, 720));+ const unit = height / 720;+ const shape = shapeOf(options.shape);+ const timeline = getSquiggleTimeline(options);+ const time = getSquiggleTime(frame, options);+ const head = getSquiggleHead(time);+ const tail = getSquiggleTail(time, timeline);+ const phase = getSquigglePhase(time, timeline);+ const settle = clamp(finite(options.settle, squiggleDefaults.settle), 0, 1);+ const lively = finite(options.amplitude, squiggleDefaults.amplitude);+ const calm = 1 - settle * getSquiggleCalm(time);+ const amplitude = Math.max(0, lively) * unit * calm;+ const length = Math.max(0, finite(options.length, squiggleDefaults.length));+ const course = length * unit;+ const cycle = finite(options.wavelength, squiggleDefaults.wavelength);+ const wavelength = Math.max(MIN_WAVELENGTH, cycle) * unit;+ const weight = Math.max(0, finite(options.weight, squiggleDefaults.weight));+ const angle = finite(options.angle, squiggleDefaults.angle);+ const radians = (angle * Math.PI) / 180;+ const cos = Math.cos(radians);+ const sin = Math.sin(radians);+ const start = {+ x: finite(options.x, squiggleDefaults.x) * width,+ y: finite(options.y, squiggleDefaults.y) * height,+ };+ const end = { x: start.x + course * cos, y: start.y + course * sin };+ const drawn = head - tail > 0;+ const curve: SquigglePoint[] = drawn+ ? getSquiggleCurve({+ shape,+ length: course,+ wavelength,+ amplitude,+ phase,+ unit,+ })+ : [];+ const placed = curve.map((point) => ({+ x: start.x + point.x * cos - point.y * sin,+ y: start.y + point.x * sin + point.y * cos,+ }));+ const trim = getSquiggleTrim(placed, tail, head);+ const path = getSquigglePath(trim.points);+ return {+ width,+ height,+ unit,+ shape,+ time,+ timeline,+ head,+ tail,+ phase,+ amplitude,+ wavelength,+ length: course,+ strokeWidth: round(weight * unit),+ join: joinOf(shape),+ start,+ end,+ total: trim.total,+ points: trim.points,+ path,+ visible: path.includes("L"),+ };+}++export type SquiggleState = ReturnType<typeof getSquiggleState>;++export function Squiggle({+ shape = squiggleDefaults.shape,+ x = squiggleDefaults.x,+ y = squiggleDefaults.y,+ length = squiggleDefaults.length,+ angle = squiggleDefaults.angle,+ amplitude = squiggleDefaults.amplitude,+ wavelength = squiggleDefaults.wavelength,+ weight = squiggleDefaults.weight,+ color = squiggleDefaults.color,+ settle = squiggleDefaults.settle,+ hold = squiggleDefaults.hold,+ erase = squiggleDefaults.erase,+ delay = squiggleDefaults.delay,+ speed = squiggleDefaults.speed,+ className,+}: SquiggleProps) {+ const frame = useCurrentFrame();+ const { width, height, fps } = useVideoConfig();+ const state = getSquiggleState(frame, {+ shape,+ x,+ y,+ length,+ angle,+ amplitude,+ wavelength,+ weight,+ settle,+ hold,+ erase,+ delay,+ speed,+ width,+ height,+ fps,+ });++ return (+ <div+ className={className}+ style={{ position: "absolute", inset: 0, pointerEvents: "none" }}+ >+ <svg+ width="100%"+ height="100%"+ viewBox={`0 0 ${width} ${height}`}+ role="img"+ aria-label="Squiggle line"+ style={{ display: "block" }}+ >+ {state.visible ? (+ <path+ d={state.path}+ fill="none"+ stroke={color}+ strokeWidth={state.strokeWidth}+ strokeLinecap="round"+ strokeLinejoin={state.join}+ />+ ) : null}+ </svg>+ </div>+ );+}diff --git a/registry/remocn/stripe-type/__tests__/stripe-type.test.ts b/registry/remocn/stripe-type/__tests__/stripe-type.test.tsnew file mode 100644index 00000000..4563344f--- /dev/null+++ b/registry/remocn/stripe-type/__tests__/stripe-type.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getStripeBandOffset,+ getStripeBands,+ getStripeGap,+ getStripeTypeDuration,+ getStripeTypeTime,+ getStripeTypeTimeline,+ stripeTypeDefaults,+} from "..";+import { stripeTypeConfig } from "../config";++describe("stripe-type bands", () => {+ it("spans the ink box from the first band's top to the last band's bottom", () => {+ const bands = getStripeBands(8, 0.35);+ expect(bands).toHaveLength(8);+ expect(bands[0].top).toBe(0);+ expect(bands[7].bottom).toBeCloseTo(1, 10);+ });++ it("keeps equal bands and equal gaps", () => {+ const bands = getStripeBands(5, 0.4);+ const heights = bands.map((b) => b.bottom - b.top);+ const gaps = bands.slice(1).map((b, i) => b.top - bands[i].bottom);+ for (const h of heights) expect(h).toBeCloseTo(heights[0], 10);+ for (const g of gaps) expect(g).toBeCloseTo((heights[0] * 0.4) / 0.6, 10);+ });++ it("tiles the box without gaps at gap 0", () => {+ const bands = getStripeBands(4, 0);+ expect(bands.map((b) => [b.top, b.bottom])).toEqual([+ [0, 0.25],+ [0.25, 0.5],+ [0.5, 0.75],+ [0.75, 1],+ ]);+ });++ it("clamps the band count and gap", () => {+ expect(getStripeBands(0, 0.3)).toHaveLength(1);+ expect(getStripeBands(3.6, 0.3)).toHaveLength(4);+ const [only] = getStripeBands(1, 2);+ expect(only.top).toBe(0);+ expect(only.bottom).toBeCloseTo(1, 10);+ });+});++describe("stripe-type timeline", () => {+ it("locks every band by frame 30, then exits after the hold", () => {+ expect(getStripeTypeTimeline()).toEqual({+ entered: 30,+ settled: 30,+ exitStart: 60,+ exitEnd: 90,+ duration: 100,+ });+ const solid = getStripeTypeTimeline({ settle: "solid", exit: false });+ expect(solid.settled).toBe(40);+ expect(solid.duration).toBe(70);+ });++ it("enters from alternating sides and passes on through on the exit", () => {+ expect(getStripeBandOffset(0, 0)).toBe(-1);+ expect(getStripeBandOffset(0, 1)).toBe(1);+ expect(getStripeBandOffset(30, 0)).toBe(0);+ expect(getStripeBandOffset(30, 7)).toBe(0);+ expect(getStripeBandOffset(59, 3)).toBe(0);+ expect(getStripeBandOffset(90, 0)).toBe(1);+ expect(getStripeBandOffset(90, 1)).toBe(-1);+ expect(getStripeBandOffset(90, 0, { exit: false })).toBe(0);+ });++ it("staggers the bands two frames apart", () => {+ const first = getStripeBandOffset(8, 0);+ expect(getStripeBandOffset(10, 1)).toBeCloseTo(-first, 10);+ });++ it("closes the gaps only when settling solid", () => {+ expect(getStripeGap(35, 0.35)).toBe(0.35);+ expect(getStripeGap(30, 0.35, { settle: "solid" })).toBe(0.35);+ expect(getStripeGap(40, 0.35, { settle: "solid" })).toBe(0);+ });++ it("scales the preview duration with speed", () => {+ expect(getStripeTypeDuration()).toBe(100);+ expect(getStripeTypeDuration({ speed: 2 })).toBe(50);+ expect(getStripeTypeDuration({ speed: 0 })).toBe(1);+ expect(stripeTypeConfig.getDurationInFrames?.({ exit: false })).toBe(60);+ });++ it("maps frames onto the 30 fps timeline", () => {+ expect(getStripeTypeTime(30)).toBe(30);+ expect(getStripeTypeTime(60, { fps: 60 })).toBe(30);+ expect(getStripeTypeTime(10, { speed: 2 })).toBe(20);+ });+});++describe("stripe-type config", () => {+ it("previews with the component's defaults", () => {+ const defaults = getDefaults(+ resolveControls("stripe-type", stripeTypeConfig.controls),+ );+ expect(defaults).toMatchObject({+ text: stripeTypeDefaults.text,+ color: stripeTypeDefaults.color,+ settle: stripeTypeDefaults.settle,+ fontSize: stripeTypeDefaults.fontSize,+ fontWeight: stripeTypeDefaults.fontWeight,+ stripes: stripeTypeDefaults.stripes,+ gap: stripeTypeDefaults.gap,+ hold: stripeTypeDefaults.hold,+ exit: stripeTypeDefaults.exit,+ });+ expect(stripeTypeConfig.durationInFrames).toBe(getStripeTypeDuration());+ });+});diff --git a/registry/remocn/stripe-type/config.ts b/registry/remocn/stripe-type/config.tsnew file mode 100644index 00000000..fa3f82a4--- /dev/null+++ b/registry/remocn/stripe-type/config.ts@@ -0,0 +1,89 @@+import {+ type ComponentConfig,+ enumVariants,+ FPS,+ H,+ W,+} from "@/lib/customizer-config";+import { getStripeTypeDuration, type StripeTypeSettle } from ".";++function durationOf(values: Record<string, unknown>) {+ const numeric = (key: string) => {+ const value = values[key];+ return typeof value === "number" ? value : undefined;+ };+ return getStripeTypeDuration({+ stripes: numeric("stripes"),+ hold: numeric("hold"),+ speed: numeric("speed"),+ settle: values.settle as StripeTypeSettle | undefined,+ exit: values.exit !== false,+ });+}++export const stripeTypeConfig: ComponentConfig = {+ componentName: "StripeType",+ importPath: "@/components/remocn/stripe-type",+ controls: {+ text: { type: "text-content", default: "Launch", description: "Text" },+ color: { type: "color", default: "#fafafa", description: "Text color" },+ settle: {+ type: "enum",+ default: "striped",+ variants: enumVariants(["striped", "solid"]),+ description: "Settle",+ },+ fontSize: {+ type: "number",+ default: 180,+ min: 60,+ max: 320,+ step: 2,+ description: "Font size",+ hiddenFromList: false,+ },+ fontWeight: {+ type: "number",+ default: 800,+ min: 100,+ max: 900,+ step: 50,+ description: "Weight",+ hiddenFromList: false,+ },+ stripes: {+ type: "number",+ default: 8,+ min: 2,+ max: 16,+ step: 1,+ description: "Stripes",+ hiddenFromList: false,+ },+ gap: {+ type: "number",+ default: 0.35,+ min: 0,+ max: 0.8,+ step: 0.05,+ description: "Gap",+ hiddenFromList: false,+ },+ hold: {+ type: "number",+ default: 30,+ min: 0,+ max: 120,+ step: 5,+ description: "Hold",+ hiddenFromList: false,+ },+ exit: { type: "boolean", default: true, description: "Exit" },+ },+ durationInFrames: 100,+ getDurationInFrames: durationOf,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#2b3bff" },+};diff --git a/registry/remocn/stripe-type/index.tsx b/registry/remocn/stripe-type/index.tsxnew file mode 100644index 00000000..aadd27e2--- /dev/null+++ b/registry/remocn/stripe-type/index.tsx@@ -0,0 +1,326 @@+"use client";++import { loadFont } from "@remotion/google-fonts/Inter";+import { useEffect, useState } from "react";+import {+ continueRender,+ delayRender,+ Easing,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+} from "remotion";++const { fontFamily: INTER } = loadFont("normal", {+ weights: ["100", "900"],+ subsets: ["latin"],+});++export type StripeTypeSettle = "striped" | "solid";++export interface StripeTypeProps {+ text?: string;+ fontSize?: number;+ fontWeight?: number;+ fontFamily?: string;+ color?: string;+ stripes?: number;+ gap?: number;+ settle?: StripeTypeSettle;+ exit?: boolean;+ hold?: number;+ speed?: number;+ className?: string;+}++export const stripeTypeDefaults = {+ text: "Launch",+ fontSize: 180,+ fontWeight: 800,+ fontFamily: INTER,+ color: "#fafafa",+ stripes: 8,+ gap: 0.35,+ settle: "striped",+ exit: true,+ hold: 30,+ speed: 1,+} satisfies Required<Omit<StripeTypeProps, "className">>;++/** Beats on the 30 fps clock. */+export const stripeTypeTiming = {+ stagger: 2,+ travel: 16,+ close: 10,+ /** Frames of empty screen after the exit in the preview. */+ tail: 10,+} as const;++/** Ink box of Inter in a `line-height: 1` box, in em from the top, until measured. */+const INTER_INK = { top: 0.136, bottom: 0.864 + 0.24 };+const MEASURE_SIZE = 100;++const CLAMP = {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+} as const;++// Expo-shaped curves that land exactly on 0 and 1 (Easing.exp stops 2⁻¹⁰ short).+const easeOutExpo = Easing.bezier(0.16, 1, 0.3, 1);+const easeInExpo = Easing.bezier(0.7, 0, 0.84, 0);+const easeInOutCubic = Easing.inOut(Easing.cubic);++function finite(value: number | undefined, fallback: number) {+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;+}++/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */+export function getStripeTypeTime(+ frame: number,+ options: { fps?: number; speed?: number } = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const speed = Math.max(0, finite(options.speed, 1));+ return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;+}++function stripeCount(stripes: number | undefined) {+ return Math.max(1, Math.round(finite(stripes, stripeTypeDefaults.stripes)));+}++export interface StripeBand {+ /** Top of the band as a share of the ink box height. */+ top: number;+ /** Bottom of the band as a share of the ink box height. */+ bottom: number;+}++/**+ * Bands over the ink box. With `n` bands and gap share `g` the pitch is+ * `1 / (n − g)`: the first band starts at the top, the last ends at the+ * bottom.+ */+export function getStripeBands(stripes: number, gap: number): StripeBand[] {+ const n = stripeCount(stripes);+ const g = Math.min(0.95, Math.max(0, finite(gap, 0)));+ const pitch = 1 / (n - g);+ return Array.from({ length: n }, (_, k) => ({+ top: k * pitch,+ bottom: k * pitch + pitch * (1 - g),+ }));+}++export interface StripeTypeTimeline {+ /** Frame where the last band has locked. */+ entered: number;+ /** Frame where the gaps have closed (equals `entered` when striped). */+ settled: number;+ exitStart: number;+ exitEnd: number;+ /** Frames the preview needs. */+ duration: number;+}++export function getStripeTypeTimeline(+ options: Pick<StripeTypeProps, "stripes" | "settle" | "exit" | "hold"> = {},+): StripeTypeTimeline {+ const n = stripeCount(options.stripes);+ const { stagger, travel, close, tail } = stripeTypeTiming;+ const entered = stagger * (n - 1) + travel;+ const settled = options.settle === "solid" ? entered + close : entered;+ const hold = Math.max(0, finite(options.hold, stripeTypeDefaults.hold));+ const exitStart = settled + hold;+ const exitEnd = exitStart + stagger * (n - 1) + travel;+ const exit = options.exit !== false;+ return {+ entered,+ settled,+ exitStart,+ exitEnd,+ duration: exit ? exitEnd + tail : settled + hold,+ };+}++/** Preview length for the given options and speed. */+export function getStripeTypeDuration(+ options: Pick<+ StripeTypeProps,+ "stripes" | "settle" | "exit" | "hold" | "speed"+ > = {},+) {+ const speed = finite(options.speed, 1);+ if (speed <= 0) return 1;+ return Math.ceil(getStripeTypeTimeline(options).duration / speed);+}++/**+ * Horizontal offset of band `k` as a share of its travel distance: −1 or 1+ * off the frame, 0 locked. Even bands enter from the left, odd from the right,+ * and on the exit each band passes on through the other side.+ */+export function getStripeBandOffset(+ t: number,+ k: number,+ options: Pick<StripeTypeProps, "stripes" | "settle" | "exit" | "hold"> = {},+) {+ const { stagger, travel } = stripeTypeTiming;+ const timeline = getStripeTypeTimeline(options);+ const side = k % 2 === 0 ? -1 : 1;+ const inStart = stagger * k;+ const enter = interpolate(t, [inStart, inStart + travel], [1, 0], {+ ...CLAMP,+ easing: easeOutExpo,+ });+ // `|| 0` folds −0 into 0 for a locked band.+ if (options.exit === false) return side * enter || 0;+ const outStart = timeline.exitStart + stagger * k;+ const leave = interpolate(t, [outStart, outStart + travel], [0, 1], {+ ...CLAMP,+ easing: easeInExpo,+ });+ return side * enter - side * leave || 0;+}++/** Gap share over time: the set gap, closing to 0 when `settle` is solid. */+export function getStripeGap(+ t: number,+ gap: number,+ options: Pick<StripeTypeProps, "stripes" | "settle"> = {},+) {+ if (options.settle !== "solid") return gap;+ const { entered, settled } = getStripeTypeTimeline(options);+ return interpolate(t, [entered, settled], [gap, 0], {+ ...CLAMP,+ easing: easeInOutCubic,+ });+}++/** Ink box of the word in its `line-height: 1` box, and its width, in em. */+function useInkBox(text: string, font: string) {+ const [ink, setInk] = useState<{+ top: number;+ bottom: number;+ width: number;+ } | null>(null);++ useEffect(() => {+ const handle = delayRender("stripe-type: measuring the word");+ let released = false;+ const release = () => {+ if (released) return;+ released = true;+ continueRender(handle);+ };+ const measure = () => {+ if (released) return;+ const ctx = document.createElement("canvas").getContext("2d");+ if (ctx) {+ ctx.font = font;+ const m = ctx.measureText(text);+ const ascent = m.fontBoundingBoxAscent / MEASURE_SIZE;+ const descent = m.fontBoundingBoxDescent / MEASURE_SIZE;+ const baseline = (1 - (ascent + descent)) / 2 + ascent;+ if (ascent > 0) {+ setInk({+ top: baseline - m.actualBoundingBoxAscent / MEASURE_SIZE,+ bottom: baseline + m.actualBoundingBoxDescent / MEASURE_SIZE,+ width: m.width / MEASURE_SIZE,+ });+ }+ }+ release();+ };+ document.fonts.load(font, text).then(measure, measure);+ return release;+ }, [text, font]);++ return ink;+}++export function StripeType({+ text = stripeTypeDefaults.text,+ fontSize = stripeTypeDefaults.fontSize,+ fontWeight = stripeTypeDefaults.fontWeight,+ fontFamily = stripeTypeDefaults.fontFamily,+ color = stripeTypeDefaults.color,+ stripes = stripeTypeDefaults.stripes,+ gap = stripeTypeDefaults.gap,+ settle = stripeTypeDefaults.settle,+ exit = stripeTypeDefaults.exit,+ hold = stripeTypeDefaults.hold,+ speed = stripeTypeDefaults.speed,+ className,+}: StripeTypeProps) {+ const frame = useCurrentFrame();+ const { fps, width, height } = useVideoConfig();+ const unit = height / 720;+ const size = fontSize * unit;+ const t = getStripeTypeTime(frame, { fps, speed });+ const measured = useInkBox(+ text,+ `${fontWeight} ${MEASURE_SIZE}px ${fontFamily}`,+ );+ const ink = measured ?? {+ ...INTER_INK,+ width: 0.6 * Array.from(text).length,+ };+ const options = { stripes, settle, exit, hold };+ const bands = getStripeBands(stripes, getStripeGap(t, gap, options));+ const inkHeight = ink.bottom - ink.top;+ // Far enough that a band starting on either side is fully off the frame.+ const travel = (width + ink.width * size) / 2 + 0.2 * size;++ const type = {+ fontFamily,+ fontSize: size,+ lineHeight: 1,+ fontWeight,+ fontVariationSettings: `"wght" ${fontWeight}`,+ color,+ whiteSpace: "pre",+ } as const;++ return (+ <div+ className={className}+ style={{+ position: "absolute",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ overflow: "hidden",+ }}+ >+ <div style={{ position: "relative" }}>+ <div aria-hidden style={{ ...type, visibility: "hidden" }}>+ {text}+ </div>+ {bands.map((band, k) => {+ const top = (ink.top + band.top * inkHeight) * 100;+ // Each band reaches a pixel into the next gap, so closed gaps leave+ // no antialiased seam between bands.+ const bleed = k < bands.length - 1 ? Math.max(1, unit) / size : 0;+ const bottom =+ (1 - (ink.top + band.bottom * inkHeight) - bleed) * 100;+ const offset = getStripeBandOffset(t, k, options);+ return (+ <div+ key={k}+ aria-hidden={k > 0}+ style={{+ ...type,+ position: "absolute",+ inset: 0,+ clipPath: `inset(${top}% -1% ${bottom}% -1%)`,+ transform: `translateX(${offset * travel}px)`,+ }}+ >+ {text}+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/registry/remocn/trim-burst/__tests__/trim-burst.test.ts b/registry/remocn/trim-burst/__tests__/trim-burst.test.tsnew file mode 100644index 00000000..a4dfbe19--- /dev/null+++ b/registry/remocn/trim-burst/__tests__/trim-burst.test.ts@@ -0,0 +1,513 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getTrimBurstDotScale,+ getTrimBurstDuration,+ getTrimBurstEndProgress,+ getTrimBurstLeash,+ getTrimBurstStartProgress,+ getTrimBurstState,+ getTrimBurstStrokes,+ getTrimBurstTime,+ getTrimBurstTimeline,+ getTrimBurstTrim,+ trimBurstDefaults,+ trimBurstLength,+} from "..";+import { trimBurstConfig } from "../config";++type State = ReturnType<typeof getTrimBurstState>;+type Layout = Parameters<typeof getTrimBurstStrokes>[0];++const frames = (from: number, to: number) =>+ Array.from({ length: to - from + 1 }, (_, i) => from + i);++const samples = (step: number, end: number) =>+ Array.from({ length: Math.round(end / step) + 1 }, (_, i) => i * step);++const drawn = (state: State) => state.lines.length + state.dots.length;++const lengthOf = (line: State["lines"][number]) =>+ Math.hypot(line.x2 - line.x1, line.y2 - line.y1);++describe("trim burst timeline", () => {+ it("lives 18 frames and previews with a short hold", () => {+ expect(trimBurstLength).toBe(18);+ expect(getTrimBurstTimeline()).toEqual({+ life: 15,+ lag: 3,+ stagger: 3,+ length: 18,+ });+ expect(getTrimBurstTimeline({ jitter: 1 }).length).toBe(21);+ expect(getTrimBurstTimeline({ jitter: 0 }).length).toBe(15);+ expect(getTrimBurstTimeline({ count: 1 }).stagger).toBe(0);+ expect(getTrimBurstDuration()).toBe(42);+ expect(getTrimBurstDuration()).toBe(trimBurstConfig.durationInFrames);+ });++ it("scales the preview with speed, jitter, count and delay", () => {+ expect(getTrimBurstDuration({ speed: 2 })).toBe(33);+ expect(getTrimBurstDuration({ speed: 0.5 })).toBe(60);+ expect(getTrimBurstDuration({ speed: 0.25 })).toBe(96);+ expect(getTrimBurstDuration({ speed: 4 })).toBe(29);+ expect(getTrimBurstDuration({ speed: 0 })).toBe(24);+ expect(getTrimBurstDuration({ jitter: 0 })).toBe(39);+ expect(getTrimBurstDuration({ jitter: 1 })).toBe(45);+ expect(getTrimBurstDuration({ count: 1 })).toBe(39);+ expect(getTrimBurstDuration({ delay: 10 })).toBe(52);+ const resolve = trimBurstConfig.getDurationInFrames;+ expect(resolve?.({ speed: 2, jitter: 1, delay: 6 })).toBe(41);+ expect(resolve?.({ speed: "fast", jitter: "loose" })).toBe(42);+ });++ it("draws nothing before the burst fires or after it ends", () => {+ expect(drawn(getTrimBurstState(0, { dots: true }))).toBe(0);+ for (const frame of frames(1, 17)) {+ expect(getTrimBurstState(frame).lines.length).toBeGreaterThan(0);+ }+ for (const frame of [trimBurstLength, 19, 30, 200]) {+ expect(drawn(getTrimBurstState(frame, { dots: true }))).toBe(0);+ }+ const loose = { jitter: 1, dots: true };+ expect(drawn(getTrimBurstState(20, loose))).toBeGreaterThan(0);+ expect(drawn(getTrimBurstState(21, loose))).toBe(0);+ const rigid = { jitter: 0, dots: true };+ expect(drawn(getTrimBurstState(14, rigid))).toBeGreaterThan(0);+ expect(drawn(getTrimBurstState(15, rigid))).toBe(0);+ });++ it("waits for the delay and never fires at speed 0", () => {+ const delayed = { delay: 10, dots: true };+ for (const frame of frames(0, 10)) {+ expect(drawn(getTrimBurstState(frame, delayed))).toBe(0);+ }+ expect(getTrimBurstState(11, delayed).lines.length).toBeGreaterThan(0);+ expect(drawn(getTrimBurstState(27, delayed))).toBeGreaterThan(0);+ for (const frame of [28, 40]) {+ expect(drawn(getTrimBurstState(frame, delayed))).toBe(0);+ }+ for (const frame of [0, 10, 100]) {+ const frozen = getTrimBurstState(frame, { speed: 0, dots: true });+ expect(drawn(frozen)).toBe(0);+ }+ });++ it("maps other frame rates and speeds onto the 30 fps timeline", () => {+ const base = getTrimBurstState(5);+ expect(getTrimBurstState(10, { fps: 60 })).toEqual(base);+ expect(getTrimBurstState(10, { speed: 0.5 })).toEqual(base);+ expect(getTrimBurstTime(12, { delay: 4, speed: 2 })).toBe(16);+ expect(getTrimBurstTime(20, { fps: 60, speed: 0.5 })).toBe(5);+ expect(getTrimBurstTime(-5)).toBe(0);+ expect(getTrimBurstTime(Number.NaN)).toBe(0);+ });+});++describe("trim burst signature", () => {+ it("leads with the end on a fast ease-out that brakes hard", () => {+ const progress = frames(0, 15).map(getTrimBurstEndProgress);+ expect(progress[0]).toBe(0);+ expect(progress[1]).toBeGreaterThan(0.35);+ expect(progress[2]).toBeGreaterThan(0.55);+ expect(progress[15]).toBe(1);+ const steps = progress.slice(1).map((value, i) => value - progress[i]);+ for (let i = 1; i < steps.length; i++) {+ expect(steps[i]).toBeLessThan(steps[i - 1]);+ }+ expect(steps[14]).toBeLessThan(0.001);+ for (const time of samples(0.01, 30)) {+ expect(getTrimBurstEndProgress(time)).toBeLessThanOrEqual(1);+ }+ expect(getTrimBurstEndProgress(-3)).toBe(0);+ expect(getTrimBurstEndProgress(Number.NaN)).toBe(0);+ expect(getTrimBurstEndProgress(40)).toBe(1);+ });++ it("holds the start for three frames, then eases in and out", () => {+ for (const time of [0, 1, 2, 3]) {+ expect(getTrimBurstStartProgress(time)).toBe(0);+ }+ expect(getTrimBurstStartProgress(3.5)).toBeGreaterThan(0);+ expect(getTrimBurstStartProgress(9)).toBeCloseTo(0.5, 6);+ expect(getTrimBurstStartProgress(15)).toBe(1);+ expect(getTrimBurstStartProgress(Number.NaN)).toBe(0);+ const progress = frames(3, 15).map(getTrimBurstStartProgress);+ const steps = progress.slice(1).map((value, i) => value - progress[i]);+ for (let i = 1; i < 6; i++) {+ expect(steps[i]).toBeGreaterThan(steps[i - 1]);+ }+ for (let i = 7; i < steps.length; i++) {+ expect(steps[i]).toBeLessThan(steps[i - 1]);+ }+ for (const time of samples(0.25, 12)) {+ const early = getTrimBurstStartProgress(3 + time);+ const late = getTrimBurstStartProgress(15 - time);+ expect(early + late).toBeCloseTo(1, 6);+ }+ });++ it("grows, travels, then zips shut at the reach by default", () => {+ const { reach, strokeLength } = trimBurstDefaults;+ const trims = frames(0, 15).map((time) =>+ getTrimBurstTrim(time, reach, strokeLength),+ );+ const lengths = trims.map((trim) => trim.length);+ expect(lengths[0]).toBe(0);+ for (const trim of trims.slice(1, 4)) {+ expect(trim.start).toBeLessThan(0.05 * reach);+ }+ expect(trims[3].end).toBeGreaterThan(0.7 * reach);+ for (let time = 1; time <= 4; time++) {+ expect(lengths[time]).toBeGreaterThan(lengths[time - 1]);+ }+ const fine = samples(0.01, 15).map(+ (time) => getTrimBurstTrim(time, reach, strokeLength).length,+ );+ const peak = Math.max(...fine);+ expect(peak / reach).toBeGreaterThan(0.74);+ expect(peak / reach).toBeLessThan(0.8);+ for (const time of [4, 5, 6]) {+ expect(lengths[time]).toBeGreaterThan(0.95 * peak);+ }+ expect(trims[6].start - trims[4].start).toBeGreaterThan(5);+ expect(trims[6].end - trims[4].end).toBeGreaterThan(5);+ for (let time = 6; time <= 15; time++) {+ expect(lengths[time]).toBeLessThan(lengths[time - 1]);+ }+ const chase = trims[11].start - trims[10].start;+ expect(chase).toBeGreaterThan(20 * (trims[11].end - trims[10].end));+ expect(trims[15]).toEqual({ start: reach, end: reach, length: 0 });+ });++ it("moves the start on one smooth hump by default", () => {+ const { reach, strokeLength } = trimBurstDefaults;+ const starts = samples(0.05, 15).map(+ (time) => getTrimBurstTrim(time, reach, strokeLength).start,+ );+ const steps = starts.slice(1).map((value, i) => value - starts[i]);+ const top = steps.indexOf(Math.max(...steps));+ expect(top * 0.05).toBeGreaterThan(8);+ expect(top * 0.05).toBeLessThan(10.5);+ for (let i = 1; i <= top; i++) {+ expect(steps[i]).toBeGreaterThanOrEqual(steps[i - 1]);+ }+ for (let i = top + 1; i < steps.length; i++) {+ expect(steps[i]).toBeLessThanOrEqual(steps[i - 1]);+ }+ });++ it("turns a short stroke into a dash that travels, then zips", () => {+ const trims = frames(0, 15).map((time) => getTrimBurstTrim(time, 64, 32));+ expect(trims[0].length).toBe(0);+ expect(trims[1].start).toBeLessThan(1);+ expect(trims[1].length).toBeLessThan(trims[2].length);+ expect(trims[2].length).toBeLessThan(trims[3].length);+ for (const trim of trims.slice(3, 8)) {+ expect(trim.length).toBeGreaterThan(32 * 0.98);+ expect(trim.length).toBeLessThan(32);+ }+ expect(trims[8].start - trims[3].start).toBeGreaterThan(12);+ expect(trims[8].end - trims[3].end).toBeGreaterThan(12);+ for (let time = 9; time <= 15; time++) {+ expect(trims[time].length).toBeLessThan(trims[time - 1].length);+ }+ const chase = trims[11].start - trims[10].start;+ expect(chase).toBeGreaterThan(20 * (trims[11].end - trims[10].end));+ expect(trims[15]).toEqual({ start: 64, end: 64, length: 0 });+ });++ it("never lets a stroke outgrow its length or the free chase", () => {+ for (const length of [32, trimBurstDefaults.strokeLength]) {+ for (const time of samples(0.005, 15)) {+ const trim = getTrimBurstTrim(time, 64, length);+ const own = 64 * getTrimBurstStartProgress(time);+ expect(trim.length).toBeLessThan(length);+ expect(trim.length).toBeLessThanOrEqual(trim.end - own + 1e-9);+ expect(trim.start).toBeGreaterThanOrEqual(0);+ expect(trim.start).toBeLessThanOrEqual(trim.end);+ }+ }+ });++ it("chases freely when the stroke length does not bind", () => {+ for (const time of [1, 2, 3]) {+ expect(getTrimBurstTrim(time, 64, 1000).start).toBeLessThan(0.001);+ }+ const lengths = samples(0.01, 15).map(+ (time) => getTrimBurstTrim(time, 64, 1000).length,+ );+ const peak = Math.max(...lengths) / 64;+ expect(peak).toBeGreaterThan(0.84);+ expect(peak).toBeLessThan(0.86);+ });++ it("keeps a short stroke short on a long reach", () => {+ const lengths = samples(0.01, 15).map(+ (time) => getTrimBurstTrim(time, 200, 20).length,+ );+ const peak = Math.max(...lengths);+ expect(peak).toBeGreaterThan(19.9);+ expect(peak).toBeLessThan(20);+ const closed = getTrimBurstTrim(15, 200, 20);+ expect(closed).toEqual({ start: 200, end: 200, length: 0 });+ });++ it("caps the gap with a smooth minimum", () => {+ expect(getTrimBurstLeash(0, 32)).toBe(0);+ expect(getTrimBurstLeash(-5, 32)).toBe(0);+ expect(getTrimBurstLeash(10, 0)).toBe(0);+ expect(getTrimBurstLeash(Number.NaN, 32)).toBe(0);+ expect(getTrimBurstLeash(10, Number.POSITIVE_INFINITY)).toBe(10);+ expect(getTrimBurstLeash(32, 32)).toBeCloseTo(32 * 2 ** (-1 / 6), 6);+ expect(getTrimBurstLeash(1000, 32)).toBeCloseTo(32, 6);+ let previous = 0;+ for (const gap of samples(0.1, 200).slice(1)) {+ const length = getTrimBurstLeash(gap, 32);+ expect(length).toBeGreaterThan(previous);+ expect(length).toBeLessThanOrEqual(Math.min(gap, 32));+ previous = length;+ }+ });+});++describe("trim burst layout", () => {+ it("spaces a rigid ring evenly from 12 o'clock", () => {+ const strokes = getTrimBurstStrokes({ jitter: 0 });+ const angles = strokes.map((stroke) => stroke.angle);+ expect(angles).toEqual([0, 45, 90, 135, 180, 225, 270, 315]);+ for (const stroke of strokes) {+ expect(stroke.scale).toBe(1);+ expect(stroke.launch).toBe(0);+ }+ const turned = getTrimBurstStrokes({ jitter: 0, rotation: 30 });+ expect(turned.map((stroke) => stroke.angle)).toEqual([+ 30, 75, 120, 165, 210, 255, 300, 345,+ ]);+ });++ it("varies angles, lengths and launches slightly from the seed", () => {+ const strokes = getTrimBurstStrokes();+ const offsets = strokes.map((stroke) => stroke.angle - stroke.index * 45);+ for (const offset of offsets) {+ expect(Math.abs(offset)).toBeLessThanOrEqual(0.25 * 0.5 * 45);+ }+ expect(offsets.some((offset) => Math.abs(offset) > 1)).toBe(true);+ for (const stroke of strokes) {+ expect(stroke.scale).toBeGreaterThan(1 - 0.45 * 0.5);+ expect(stroke.scale).toBeLessThanOrEqual(1);+ }+ const launches = strokes.map((stroke) => stroke.launch);+ const sorted = [...launches].sort((a, b) => a - b);+ for (const [rank, launch] of sorted.entries()) {+ expect(launch).toBeCloseTo((rank * 3) / 7, 6);+ }+ expect(launches).not.toEqual(sorted);+ });++ it("fans strokes across the spread around the rotation", () => {+ const angles = (layout: Layout) =>+ getTrimBurstStrokes({ jitter: 0, ...layout }).map((item) => item.angle);+ expect(angles({ count: 3, spread: 90 })).toEqual([-45, 0, 45]);+ expect(angles({ count: 3, spread: 90, rotation: 90 })).toEqual([+ 45, 90, 135,+ ]);+ expect(angles({ count: 1, spread: 90, rotation: 20 })).toEqual([20]);+ expect(angles({ count: 1, rotation: 20 })).toEqual([20]);+ });++ it("rounds and clamps the stroke count", () => {+ const count = (value: number) =>+ getTrimBurstStrokes({ count: value }).length;+ expect(count(0)).toBe(1);+ expect(count(-3)).toBe(1);+ expect(count(7.6)).toBe(8);+ expect(count(99)).toBe(32);+ expect(count(Number.NaN)).toBe(8);+ });+});++describe("trim burst geometry", () => {+ it("runs every stroke outward along its angle from the inner radius", () => {+ const state = getTrimBurstState(5, { jitter: 0 });+ const { reach, strokeLength } = trimBurstDefaults;+ const trim = getTrimBurstTrim(5, reach, strokeLength);+ expect(state.lines).toHaveLength(8);+ for (const line of state.lines) {+ const inner = Math.hypot(line.x1 - 640, line.y1 - 360);+ const outer = Math.hypot(line.x2 - 640, line.y2 - 360);+ expect(inner).toBeCloseTo(16 + trim.start, 2);+ expect(outer).toBeCloseTo(16 + trim.end, 2);+ const angle = (Math.atan2(line.x2 - 640, 360 - line.y2) * 180) / Math.PI;+ expect((angle + 360) % 360).toBeCloseTo(line.index * 45, 2);+ }+ const up = state.lines.find((line) => line.index === 0);+ expect(up?.x2).toBeCloseTo(640, 3);+ expect(up?.y2).toBeLessThan(360);+ });++ it("sizes everything in reference px scaled by height / 720", () => {+ const base = getTrimBurstState(6, { dots: true });+ const large = getTrimBurstState(6, {+ width: 1920,+ height: 1080,+ dots: true,+ });+ expect(large.unit).toBe(1.5);+ expect(large.weight).toBe(3);+ expect(large.lines).toHaveLength(base.lines.length);+ expect(large.dots).toHaveLength(base.dots.length);+ expect(base.dots.length).toBeGreaterThan(0);+ for (const [i, line] of base.lines.entries()) {+ const other = large.lines[i];+ expect(other.x1).toBeCloseTo(line.x1 * 1.5, 2);+ expect(other.y1).toBeCloseTo(line.y1 * 1.5, 2);+ expect(other.x2).toBeCloseTo(line.x2 * 1.5, 2);+ expect(other.y2).toBeCloseTo(line.y2 * 1.5, 2);+ expect(other.width).toBeCloseTo(line.width * 1.5, 2);+ }+ for (const [i, dot] of base.dots.entries()) {+ const other = large.dots[i];+ expect(other.cx).toBeCloseTo(dot.cx * 1.5, 2);+ expect(other.cy).toBeCloseTo(dot.cy * 1.5, 2);+ expect(other.r).toBeCloseTo(dot.r * 1.5, 2);+ }+ const tall = getTrimBurstState(6, { width: 1080, height: 1920 });+ expect(tall.originX).toBe(540);+ expect(tall.originY).toBe(960);+ for (const [i, line] of base.lines.entries()) {+ const scaled = lengthOf(tall.lines[i]);+ expect(scaled).toBeCloseTo((lengthOf(line) * 1920) / 720, 1);+ }+ });++ it("keeps element counts small and falls back on invalid input", () => {+ for (const frame of frames(0, 30)) {+ const state = getTrimBurstState(frame, { count: 24, dots: true });+ expect(state.lines.length).toBeLessThanOrEqual(24);+ expect(state.dots.length).toBeLessThanOrEqual(24);+ }+ const nan = Number.NaN;+ const broken = getTrimBurstState(6, {+ x: nan,+ y: nan,+ count: nan,+ innerRadius: nan,+ reach: nan,+ strokeLength: nan,+ weight: nan,+ rotation: nan,+ spread: nan,+ jitter: nan,+ seed: nan,+ delay: nan,+ speed: nan,+ fps: nan,+ width: nan,+ height: nan,+ });+ expect(broken).toEqual(getTrimBurstState(6));+ expect(getTrimBurstState(6, { weight: 0 }).weight).toBe(0.25);+ expect(getTrimBurstState(6, { weight: 100 }).weight).toBe(24);+ for (const line of getTrimBurstState(6, { strokeLength: 0 }).lines) {+ expect(lengthOf(line)).toBeLessThanOrEqual(1.002);+ }+ });++ it("thins a closing stroke so a round cap shrinks to a point", () => {+ for (const frame of frames(0, 20)) {+ const state = getTrimBurstState(frame);+ for (const line of state.lines) {+ expect(line.width).toBeLessThanOrEqual(state.weight);+ expect(line.width).toBeLessThanOrEqual(lengthOf(line) + 0.003);+ }+ }+ const closing = getTrimBurstState(17).lines;+ expect(closing.length).toBeGreaterThan(0);+ for (const line of closing) {+ expect(line.width).toBeLessThan(1);+ }+ });+});++describe("trim burst dots", () => {+ it("stays off unless dots is set", () => {+ for (const frame of frames(0, 20)) {+ expect(getTrimBurstState(frame).dots).toEqual([]);+ }+ });++ it("pops just past full size, then shrinks to nothing", () => {+ for (const time of [0, 2, 4, 15, 20]) {+ expect(getTrimBurstDotScale(time)).toBe(0);+ }+ expect(getTrimBurstDotScale(Number.NaN)).toBe(0);+ const scales = samples(0.01, 15).map(getTrimBurstDotScale);+ const peak = Math.max(...scales);+ expect(peak).toBeGreaterThan(1.05);+ expect(peak).toBeLessThan(1.08);+ expect(getTrimBurstDotScale(8)).toBeCloseTo(1, 6);+ for (let i = 801; i < scales.length; i++) {+ expect(scales[i]).toBeLessThanOrEqual(scales[i - 1]);+ }+ });++ it("sits on each stroke's line just past its end", () => {+ const state = getTrimBurstState(8, { dots: true, jitter: 0 });+ expect(state.dots).toHaveLength(8);+ for (const dot of state.dots) {+ const line = state.lines.find((item) => item.index === dot.index);+ expect(line).toBeDefined();+ if (!line) continue;+ const tip = Math.hypot(line.x2 - 640, line.y2 - 360);+ const center = Math.hypot(dot.cx - 640, dot.cy - 360);+ expect(center - tip).toBeCloseTo(3.25 * 2, 2);+ expect(dot.r).toBeCloseTo(2.5, 3);+ }+ for (const frame of frames(0, 20)) {+ for (const dot of getTrimBurstState(frame, { dots: true }).dots) {+ expect(dot.r).toBeLessThanOrEqual(1.25 * 2 * 1.071);+ }+ }+ });+});++describe("trim burst determinism", () => {+ it("renders any frame identically in any sampling order", () => {+ const options = { seed: 7, jitter: 0.8, dots: true };+ const sample = (frame: number) => getTrimBurstState(frame, options);+ const order = [0, 3, 7, 12, 16, 25];+ const forward = order.map(sample);+ const backward = [...order].reverse().map(sample).reverse();+ expect(backward).toEqual(forward);+ expect(sample(12)).toEqual(forward[3]);+ });++ it("keeps the layout for a seed and changes it with another", () => {+ const layout = getTrimBurstStrokes({ seed: 2 });+ expect(getTrimBurstStrokes({ seed: 2 })).toEqual(layout);+ expect(getTrimBurstStrokes()).not.toEqual(layout);+ const state = getTrimBurstState(6, { seed: 3 });+ expect(getTrimBurstState(6, { seed: 3 })).toEqual(state);+ });+});++describe("trim burst config", () => {+ it("matches the component defaults and ranges", () => {+ const controls = resolveControls("trim-burst", trimBurstConfig.controls);+ expect(getDefaults(controls)).toEqual(trimBurstDefaults);+ expect(trimBurstConfig.componentName).toBe("TrimBurst");+ expect(trimBurstConfig.importPath).toBe("@/components/remocn/trim-burst");+ const cap = controls.cap;+ expect(cap.type === "select" ? cap.options : []).toEqual(["round", "butt"]);+ const range = (key: string) => {+ const control = controls[key];+ return control.type === "number" ? [control.min, control.max] : [];+ };+ expect(range("count")).toEqual([1, 24]);+ expect(range("weight")).toEqual([0.5, 8]);+ expect(range("jitter")).toEqual([0, 1]);+ expect(range("x")).toEqual([0, 1]);+ expect(range("y")).toEqual([0, 1]);+ });+});diff --git a/registry/remocn/trim-burst/config.ts b/registry/remocn/trim-burst/config.tsnew file mode 100644index 00000000..58e35698--- /dev/null+++ b/registry/remocn/trim-burst/config.ts@@ -0,0 +1,143 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";+import { getTrimBurstDuration } from ".";++const numberOf = (value: unknown) =>+ typeof value === "number" ? value : undefined;++function durationOf(values: Record<string, unknown>) {+ return getTrimBurstDuration({+ count: numberOf(values.count),+ jitter: numberOf(values.jitter),+ delay: numberOf(values.delay),+ speed: numberOf(values.speed),+ });+}++export const trimBurstConfig: ComponentConfig = {+ componentName: "TrimBurst",+ importPath: "@/components/remocn/trim-burst",+ controls: {+ count: {+ type: "number",+ default: 8,+ min: 1,+ max: 24,+ step: 1,+ description: "Strokes",+ hiddenFromList: false,+ },+ innerRadius: {+ type: "number",+ default: 16,+ min: 0,+ max: 160,+ step: 1,+ description: "Inner radius",+ hiddenFromList: false,+ },+ reach: {+ type: "number",+ default: 64,+ min: 8,+ max: 240,+ step: 1,+ description: "Reach",+ hiddenFromList: false,+ },+ strokeLength: {+ type: "number",+ default: 56,+ min: 4,+ max: 200,+ step: 1,+ description: "Stroke length",+ hiddenFromList: false,+ },+ weight: {+ type: "number",+ default: 2,+ min: 0.5,+ max: 8,+ step: 0.5,+ description: "Stroke weight",+ hiddenFromList: false,+ },+ rotation: {+ type: "number",+ default: 0,+ min: -180,+ max: 180,+ step: 1,+ description: "Rotation",+ hiddenFromList: false,+ },+ spread: {+ type: "number",+ default: 360,+ min: 15,+ max: 360,+ step: 5,+ description: "Spread",+ hiddenFromList: false,+ },+ jitter: {+ type: "number",+ default: 0.5,+ min: 0,+ max: 1,+ step: 0.05,+ description: "Jitter",+ hiddenFromList: false,+ },+ dots: { type: "boolean", default: false, description: "Tip dots" },+ cap: {+ type: "enum",+ default: "round",+ variants: { round: {}, butt: {} },+ description: "Caps",+ },+ color: { type: "color", default: "#ffffff", description: "Line color" },+ seed: {+ type: "number",+ default: 1,+ min: 1,+ max: 99,+ step: 1,+ description: "Seed",+ hiddenFromList: false,+ },+ delay: {+ type: "number",+ default: 0,+ min: 0,+ max: 30,+ step: 1,+ description: "Delay",+ hiddenFromList: false,+ },+ x: {+ type: "number",+ default: 0.5,+ min: 0,+ max: 1,+ step: 0.01,+ description: "Center x",+ hiddenFromList: false,+ },+ y: {+ type: "number",+ default: 0.5,+ min: 0,+ max: 1,+ step: 0.01,+ description: "Center y",+ hiddenFromList: false,+ },+ },+ durationInFrames: 42,+ getDurationInFrames: durationOf,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#002fa7" },+};diff --git a/registry/remocn/trim-burst/index.tsx b/registry/remocn/trim-burst/index.tsxnew file mode 100644index 00000000..40bfbd1b--- /dev/null+++ b/registry/remocn/trim-burst/index.tsx@@ -0,0 +1,389 @@+"use client";++import { useMemo } from "react";+import { Easing, random, useCurrentFrame, useVideoConfig } from "remotion";++export type TrimBurstCap = "round" | "butt";++export interface TrimBurstProps {+ x?: number;+ y?: number;+ count?: number;+ innerRadius?: number;+ reach?: number;+ strokeLength?: number;+ weight?: number;+ rotation?: number;+ spread?: number;+ jitter?: number;+ dots?: boolean;+ cap?: TrimBurstCap;+ color?: string;+ seed?: number;+ delay?: number;+ speed?: number;+ className?: string;+}++type Paint = "color" | "className";++export interface TrimBurstOptions extends Omit<TrimBurstProps, Paint> {+ width?: number;+ height?: number;+ fps?: number;+}++export interface TrimBurstStroke {+ index: number;+ angle: number;+ scale: number;+ launch: number;+}++export interface TrimBurstTrim {+ start: number;+ end: number;+ length: number;+}++export interface TrimBurstLine {+ index: number;+ x1: number;+ y1: number;+ x2: number;+ y2: number;+ width: number;+}++export interface TrimBurstDot {+ index: number;+ cx: number;+ cy: number;+ r: number;+}++export const trimBurstDefaults: Required<Omit<TrimBurstProps, "className">> = {+ x: 0.5,+ y: 0.5,+ count: 8,+ innerRadius: 16,+ reach: 64,+ strokeLength: 56,+ weight: 2,+ rotation: 0,+ spread: 360,+ jitter: 0.5,+ dots: false,+ cap: "round",+ color: "#ffffff",+ seed: 1,+ delay: 0,+ speed: 1,+};++const LIFE = 15;+const LAG = 3;+const STAGGER = 6;+const HOLD = 24;+const LEASH = 6;+const WOBBLE = 0.25;+const MAX_STEP = 45;+const SHRINK = 0.45;+const DOT_START = 4;+const DOT_POP = 4;+const DOT_BACK = 1.4;+const DOT_RADIUS = 1.25;+const DOT_GAP = 2;+const MAX_COUNT = 32;+const MAX_SIZE = 2000;+const MIN_STROKE = 1;+const MIN_WEIGHT = 0.25;+const MAX_WEIGHT = 24;+const VISIBLE = 0.001;+const END_EASE = Easing.bezier(0.16, 1, 0.3, 1);+const START_EASE = Easing.bezier(0.45, 0, 0.55, 1);++const finite = (value: number | undefined, fallback: number) =>+ typeof value === "number" && Number.isFinite(value) ? value : fallback;+const clamp = (value: number, min: number, max: number) =>+ Math.min(max, Math.max(min, value));+const within = (+ value: number | undefined,+ fallback: number,+ min: number,+ max: number,+) => clamp(finite(value, fallback), min, max);+const round = (value: number) => Math.round(value * 1000) / 1000;+const rateOf = (speed: number | undefined) =>+ Math.max(0, finite(speed, trimBurstDefaults.speed));+const delayOf = (delay: number | undefined) =>+ Math.max(0, finite(delay, trimBurstDefaults.delay));+const countOf = (count: number | undefined) =>+ Math.round(within(count, trimBurstDefaults.count, 1, MAX_COUNT));+const jitterOf = (jitter: number | undefined) =>+ within(jitter, trimBurstDefaults.jitter, 0, 1);+const capOf = (cap: string | undefined): TrimBurstCap =>+ cap === "butt" ? cap : "round";++export function getTrimBurstTimeline(+ options: Pick<TrimBurstOptions, "count" | "jitter"> = {},+) {+ const count = countOf(options.count);+ const stagger = count > 1 ? STAGGER * jitterOf(options.jitter) : 0;+ return { life: LIFE, lag: LAG, stagger, length: LIFE + stagger };+}++export type TrimBurstTimeline = ReturnType<typeof getTrimBurstTimeline>;++export const trimBurstLength = getTrimBurstTimeline().length;++export function getTrimBurstDuration(+ options: Pick<TrimBurstOptions, "count" | "jitter" | "delay" | "speed"> = {},+) {+ const rate = rateOf(options.speed);+ const { length } = getTrimBurstTimeline(options);+ const motion = rate === 0 ? 0 : length / rate;+ return Math.ceil(round(delayOf(options.delay) + motion)) + HOLD;+}++export function getTrimBurstTime(+ frame: number,+ options: Pick<TrimBurstOptions, "fps" | "delay" | "speed"> = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const elapsed = Math.max(0, finite(frame, 0) - delayOf(options.delay));+ return elapsed * (30 / fps) * rateOf(options.speed);+}++export function getTrimBurstEndProgress(time: number) {+ if (Number.isNaN(time) || time <= 0) return 0;+ if (time >= LIFE) return 1;+ return END_EASE(time / LIFE);+}++export function getTrimBurstStartProgress(time: number) {+ if (Number.isNaN(time) || time <= LAG) return 0;+ if (time >= LIFE) return 1;+ return START_EASE((time - LAG) / (LIFE - LAG));+}++export function getTrimBurstLeash(gap: number, strokeLength: number) {+ if (!(gap > 0 && strokeLength > 0)) return 0;+ return gap / (1 + (gap / strokeLength) ** LEASH) ** (1 / LEASH);+}++export function getTrimBurstTrim(+ time: number,+ reach: number,+ strokeLength: number,+): TrimBurstTrim {+ const distance = Math.max(0, finite(reach, 0));+ const end = distance * getTrimBurstEndProgress(time);+ const own = distance * getTrimBurstStartProgress(time);+ const length = getTrimBurstLeash(end - own, strokeLength);+ return { start: end - length, end, length };+}++export function getTrimBurstDotScale(time: number) {+ if (Number.isNaN(time) || time <= DOT_START || time >= LIFE) return 0;+ const pop = Math.min(1, (time - DOT_START) / DOT_POP) - 1;+ const grow = 1 + (DOT_BACK + 1) * pop ** 3 + DOT_BACK * pop ** 2;+ const settle = DOT_START + DOT_POP;+ const shrink = clamp((time - settle) / (LIFE - settle), 0, 1);+ return grow * (1 - shrink ** 3);+}++export function getTrimBurstStrokes(+ options: Pick<+ TrimBurstOptions,+ "count" | "rotation" | "spread" | "jitter" | "seed"+ > = {},+): TrimBurstStroke[] {+ const count = countOf(options.count);+ const rotation = finite(options.rotation, trimBurstDefaults.rotation);+ const spread = within(options.spread, trimBurstDefaults.spread, 0, 360);+ const jitter = jitterOf(options.jitter);+ const seed = finite(options.seed, trimBurstDefaults.seed);+ const fan = spread < 360 && count > 1;+ const step = fan ? spread / (count - 1) : 360 / count;+ const first = fan ? rotation - spread / 2 : rotation;+ const wobble = WOBBLE * jitter * Math.min(step, MAX_STEP);+ const { stagger } = getTrimBurstTimeline({ count, jitter });+ const keys = Array.from({ length: count }, (_, index) =>+ random(`trim-burst-${seed}-order-${index}`),+ );+ const order = keys.map((_, index) => index);+ order.sort((a, b) => keys[a] - keys[b]);+ const ranks: number[] = [];+ for (const [position, index] of order.entries()) ranks[index] = position;+ return keys.map((_, index) => {+ const turn = random(`trim-burst-${seed}-angle-${index}`) * 2 - 1;+ const shrink = random(`trim-burst-${seed}-scale-${index}`);+ return {+ index,+ angle: first + index * step + turn * wobble,+ scale: 1 - SHRINK * jitter * shrink,+ launch: count > 1 ? (stagger * ranks[index]) / (count - 1) : 0,+ };+ });+}++export function getTrimBurstState(+ frame: number,+ options: TrimBurstOptions = {},+ strokes: TrimBurstStroke[] = getTrimBurstStrokes(options),+) {+ const fallback = trimBurstDefaults;+ const width = Math.max(1, finite(options.width, 1280));+ const height = Math.max(1, finite(options.height, 720));+ const unit = height / 720;+ const time = getTrimBurstTime(frame, options);+ const originX = finite(options.x, fallback.x) * width;+ const originY = finite(options.y, fallback.y) * height;+ const inner = within(options.innerRadius, fallback.innerRadius, 0, MAX_SIZE);+ const reach = within(options.reach, fallback.reach, 0, MAX_SIZE);+ const strokeLength = within(+ options.strokeLength,+ fallback.strokeLength,+ MIN_STROKE,+ MAX_SIZE,+ );+ const size = within(options.weight, fallback.weight, MIN_WEIGHT, MAX_WEIGHT);+ const offset = inner * unit;+ const weight = size * unit;+ const gap = DOT_GAP * weight;+ const radius = DOT_RADIUS * weight;+ const lines: TrimBurstLine[] = [];+ const dots: TrimBurstDot[] = [];+ for (const stroke of strokes) {+ const local = time - stroke.launch;+ const trim = getTrimBurstTrim(+ local,+ reach * unit * stroke.scale,+ strokeLength * unit * stroke.scale,+ );+ const angle = (stroke.angle * Math.PI) / 180;+ const dx = Math.sin(angle);+ const dy = -Math.cos(angle);+ const along = (distance: number) => ({+ x: round(originX + dx * (offset + distance)),+ y: round(originY + dy * (offset + distance)),+ });+ if (trim.length > VISIBLE) {+ const from = along(trim.start);+ const to = along(trim.end);+ lines.push({+ index: stroke.index,+ x1: from.x,+ y1: from.y,+ x2: to.x,+ y2: to.y,+ width: round(Math.min(weight, trim.length)),+ });+ }+ const pop = options.dots === true ? getTrimBurstDotScale(local) : 0;+ if (pop > 0) {+ const center = along(trim.end + gap + radius);+ dots.push({+ index: stroke.index,+ cx: center.x,+ cy: center.y,+ r: round(radius * pop),+ });+ }+ }+ return {+ width,+ height,+ unit,+ time,+ originX,+ originY,+ weight,+ cap: capOf(options.cap),+ lines,+ dots,+ };+}++export type TrimBurstState = ReturnType<typeof getTrimBurstState>;++export function TrimBurst({+ x = trimBurstDefaults.x,+ y = trimBurstDefaults.y,+ count = trimBurstDefaults.count,+ innerRadius = trimBurstDefaults.innerRadius,+ reach = trimBurstDefaults.reach,+ strokeLength = trimBurstDefaults.strokeLength,+ weight = trimBurstDefaults.weight,+ rotation = trimBurstDefaults.rotation,+ spread = trimBurstDefaults.spread,+ jitter = trimBurstDefaults.jitter,+ dots = trimBurstDefaults.dots,+ cap = trimBurstDefaults.cap,+ color = trimBurstDefaults.color,+ seed = trimBurstDefaults.seed,+ delay = trimBurstDefaults.delay,+ speed = trimBurstDefaults.speed,+ className,+}: TrimBurstProps) {+ const frame = useCurrentFrame();+ const { width, height, fps } = useVideoConfig();+ const strokes = useMemo(+ () => getTrimBurstStrokes({ count, rotation, spread, jitter, seed }),+ [count, rotation, spread, jitter, seed],+ );+ const state = getTrimBurstState(+ frame,+ {+ width,+ height,+ fps,+ x,+ y,+ innerRadius,+ reach,+ strokeLength,+ weight,+ dots,+ cap,+ delay,+ speed,+ },+ strokes,+ );++ return (+ <div+ className={className}+ style={{ position: "absolute", inset: 0, pointerEvents: "none" }}+ >+ <svg+ width="100%"+ height="100%"+ viewBox={`0 0 ${width} ${height}`}+ role="img"+ aria-label="Trim burst"+ style={{ display: "block", overflow: "visible" }}+ >+ <g fill="none" stroke={color} strokeLinecap={state.cap}>+ {state.lines.map((line) => (+ <line+ key={line.index}+ x1={line.x1}+ y1={line.y1}+ x2={line.x2}+ y2={line.y2}+ strokeWidth={line.width}+ />+ ))}+ </g>+ <g fill={color}>+ {state.dots.map((dot) => (+ <circle key={dot.index} cx={dot.cx} cy={dot.cy} r={dot.r} />+ ))}+ </g>+ </svg>+ </div>+ );+}diff --git a/registry/remocn/truchet-flip/__tests__/truchet-flip.test.ts b/registry/remocn/truchet-flip/__tests__/truchet-flip.test.tsnew file mode 100644index 00000000..3d8059bf--- /dev/null+++ b/registry/remocn/truchet-flip/__tests__/truchet-flip.test.ts@@ -0,0 +1,407 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getTruchetFlipAngle,+ getTruchetFlipDuration,+ getTruchetFlipGrid,+ getTruchetFlipSnap,+ getTruchetFlipState,+ getTruchetFlipTilePath,+ getTruchetFlipTimeline,+ truchetFlipDefaults,+ truchetFlipLength,+} from "..";+import { truchetFlipConfig } from "../config";++type Side = "top" | "right" | "bottom" | "left";+type Cell = { col: number; row: number };+type State = ReturnType<typeof getTruchetFlipState>;++const CENTER = ["-1:-1", "0:-1", "-1:0", "0:0"];++const STEP: Record<Side, [number, number]> = {+ top: [0, -1],+ right: [1, 0],+ bottom: [0, 1],+ left: [-1, 0],+};++const OPPOSITE: Record<Side, Side> = {+ top: "bottom",+ right: "left",+ bottom: "top",+ left: "right",+};++const numbers = (path: string) =>+ (path.match(/-?\d+(?:\.\d+)?/g) ?? []).map(Number);++const orientationOf = (angle: number) => (((angle / 90) % 2) + 2) % 2;++const distance = ({ col, row }: Cell) => Math.hypot(col + 0.5, row + 0.5);++function rotate(x: number, y: number, angle: number): [number, number] {+ const radians = (angle * Math.PI) / 180;+ const cos = Math.round(Math.cos(radians));+ const sin = Math.round(Math.sin(radians));+ return [x * cos - y * sin, x * sin + y * cos];+}++function sideOf([x, y]: [number, number]): Side {+ if (y <= -0.5) return "top";+ if (x >= 0.5) return "right";+ if (y >= 0.5) return "bottom";+ return "left";+}++function connections() {+ const values = numbers(getTruchetFlipTilePath(2, "stroke", 0));+ const arcs = [+ [values[0], values[1], values[7], values[8]],+ [values[9], values[10], values[16], values[17]],+ ];+ return [0, 90].map((angle) => {+ const exits = new Map<Side, Side>();+ for (const [x1, y1, x2, y2] of arcs) {+ const from = sideOf(rotate(x1, y1, angle));+ const to = sideOf(rotate(x2, y2, angle));+ exits.set(from, to);+ exits.set(to, from);+ }+ return exits;+ });+}++function trace(state: State, col: number, row: number, side: Side) {+ const exits = connections();+ const orientation = new Map<string, number>();+ for (const tile of state.tiles) {+ orientation.set(`${tile.col}:${tile.row}`, orientationOf(tile.angle));+ }+ let cursor = { col, row, side };+ for (let step = 1; step <= 400; step++) {+ const current = orientation.get(`${cursor.col}:${cursor.row}`);+ if (current === undefined) return null;+ const exit = exits[current].get(cursor.side);+ if (exit === undefined) return null;+ const [dx, dy] = STEP[exit];+ const next = { col: cursor.col + dx, row: cursor.row + dy };+ cursor = { ...next, side: OPPOSITE[exit] };+ if (cursor.col === col && cursor.row === row && cursor.side === side) {+ return step;+ }+ }+ return null;+}++describe("truchet flip timeline", () => {+ it("settles the default resolve at the documented length", () => {+ const timeline = getTruchetFlipTimeline();+ expect(truchetFlipLength).toBe(102);+ expect(timeline.starts).toEqual([6, 30]);+ expect(timeline.resolveStart).toBe(60);+ expect(timeline.settled).toBe(truchetFlipLength);+ expect(timeline.duration).toBe(120);+ expect(getTruchetFlipDuration()).toBe(truchetFlipConfig.durationInFrames);+ });++ it("scales the preview duration with speed, passes and loop", () => {+ expect(getTruchetFlipDuration({ speed: 2 })).toBe(60);+ expect(getTruchetFlipDuration({ speed: 0.5 })).toBe(240);+ expect(getTruchetFlipDuration({ speed: 0 })).toBe(1);+ expect(getTruchetFlipDuration({ passes: 0 })).toBe(66);+ expect(getTruchetFlipDuration({ passes: 4 })).toBe(168);+ expect(getTruchetFlipDuration({ passes: 9 })).toBe(168);+ expect(getTruchetFlipDuration({ passes: Number.NaN })).toBe(120);+ expect(getTruchetFlipDuration({ loop: true })).toBe(168);+ const resolve = truchetFlipConfig.getDurationInFrames;+ expect(resolve?.({ speed: 0.5, passes: 1, loop: true })).toBe(288);+ });++ it("holds the seeded maze still until the first wave arrives", () => {+ for (const frame of [0, 3, 6]) {+ for (const tile of getTruchetFlipState(frame).tiles) {+ expect(tile.angle).toBe(tile.initial * 90);+ }+ }+ const { tiles } = getTruchetFlipState(8);+ const turning = tiles.filter((tile) => !Number.isInteger(tile.angle / 90));+ expect(turning.length).toBeGreaterThan(0);+ });++ it("rests every tile exactly on its target once the resolve settles", () => {+ for (const frame of [truchetFlipLength, 110, 119, 500]) {+ for (const tile of getTruchetFlipState(frame).tiles) {+ expect(Number.isInteger(tile.angle / 90)).toBe(true);+ expect(orientationOf(tile.angle)).toBe(tile.target);+ }+ }+ });+});++describe("truchet flip snap", () => {+ it("snaps fast, overshoots a little and lands on the quarter", () => {+ expect(getTruchetFlipSnap(-4)).toBe(0);+ expect(getTruchetFlipSnap(0)).toBe(0);+ expect(getTruchetFlipSnap(Number.NaN)).toBe(0);+ expect(getTruchetFlipSnap(1)).toBeGreaterThan(0.15);+ expect(getTruchetFlipSnap(4)).toBeCloseTo(1, 6);+ expect(getTruchetFlipSnap(12)).toBe(1);+ expect(getTruchetFlipSnap(40)).toBe(1);+ const times = Array.from({ length: 1200 }, (_, i) => i / 100);+ const samples = times.map(getTruchetFlipSnap);+ const peak = Math.max(...samples);+ expect(peak).toBeGreaterThan(1.04);+ expect(peak).toBeLessThan(1.1);+ for (let i = 1; i < 500; i++) {+ expect(samples[i]).toBeGreaterThan(samples[i - 1]);+ }+ expect(Math.abs(samples[1199] - 1)).toBeLessThan(0.002);+ });+});++describe("truchet flip wave order", () => {+ it("spreads the radial wave outward from the center vertex", () => {+ const { tiles } = getTruchetFlipGrid();+ const sorted = [...tiles].sort((a, b) => distance(a) - distance(b));+ for (let i = 1; i < sorted.length; i++) {+ expect(sorted[i].delay).toBeGreaterThanOrEqual(sorted[i - 1].delay);+ }+ const first = tiles.filter((tile) => tile.delay === 0);+ expect(first.map((tile) => `${tile.col}:${tile.row}`)).toEqual(CENTER);+ expect(Math.max(...tiles.map((tile) => tile.delay))).toBe(30);+ });++ it("sweeps the diagonal from the top-left corner to the bottom-right", () => {+ const { tiles } = getTruchetFlipGrid({ waveMode: "diagonal" });+ const index = ({ col, row }: Cell) => col + row;+ const sorted = [...tiles].sort((a, b) => index(a) - index(b));+ for (let i = 1; i < sorted.length; i++) {+ const step = index(sorted[i]) - index(sorted[i - 1]);+ const gap = sorted[i].delay - sorted[i - 1].delay;+ expect(step === 0 ? gap === 0 : gap > 0).toBe(true);+ }+ expect(sorted[0].delay).toBe(0);+ expect(sorted[sorted.length - 1].delay).toBe(30);+ });++ it("shuffles the random wave by seed at an even start rate", () => {+ const grid = getTruchetFlipGrid({ waveMode: "random", seed: 4 });+ const again = getTruchetFlipGrid({ waveMode: "random", seed: 4 });+ const other = getTruchetFlipGrid({ waveMode: "random", seed: 5 });+ expect(again).toEqual(grid);+ const delays = grid.tiles.map((tile) => tile.delay);+ expect(other.tiles.map((tile) => tile.delay)).not.toEqual(delays);+ const sorted = [...delays].sort((a, b) => a - b);+ expect(delays).not.toEqual(sorted);+ const step = 30 / (sorted.length - 1);+ for (const [rank, delay] of sorted.entries()) {+ expect(delay).toBeCloseTo(rank * step, 2);+ }+ });+});++describe("truchet flip resolve", () => {+ it("turns every tile each pass, then only the tiles off target", () => {+ const timeline = getTruchetFlipTimeline();+ const { tiles } = getTruchetFlipGrid();+ let resolving = 0;+ for (const tile of tiles) {+ const at = (time: number) => getTruchetFlipAngle(tile, time, timeline);+ const turned = (begin: number) => at(begin + 12.5) - at(begin - 0.5);+ for (const start of timeline.starts) {+ expect(Math.abs(turned(start + tile.delay))).toBe(90);+ }+ const begin = timeline.resolveStart + tile.delay;+ const change = Math.abs(turned(begin));+ const needed = orientationOf(at(begin - 0.5)) !== tile.target;+ expect(change).toBe(needed ? 90 : 0);+ if (needed) resolving++;+ }+ expect(resolving).toBeGreaterThan(0);+ expect(resolving).toBeLessThan(tiles.length);+ });++ it("closes the rings into a center circle and concentric loops", () => {+ const state = getTruchetFlipState(truchetFlipLength);+ const loops = [1, 2, 3, 4].map((k) => trace(state, 0, -k, "bottom"));+ expect(loops).toEqual([4, 12, 20, 28]);+ });++ it("aligns the field into open diagonals that run off the frame", () => {+ const state = getTruchetFlipState(truchetFlipLength, { resolve: "field" });+ const targets = state.tiles.map((tile) => tile.target);+ expect(targets.every((target) => target === 0)).toBe(true);+ for (const k of [1, 2, 3, 4]) {+ expect(trace(state, 0, -k, "bottom")).toBeNull();+ }+ });++ it("closes the silhouette into small rings inside a centered circle", () => {+ const settled = truchetFlipLength;+ const state = getTruchetFlipState(settled, { resolve: "silhouette" });+ const circles = [1, 2, 3].map((k) => trace(state, 0, -k, "bottom"));+ expect(circles).toEqual([4, 4, 4]);+ const inside = state.tiles.filter((tile) => distance(tile) < 3.8);+ const outside = state.tiles.filter((tile) => distance(tile) >= 3.8);+ expect(inside.some((tile) => tile.target === 1)).toBe(true);+ expect(outside.every((tile) => tile.target === 0)).toBe(true);+ expect(trace(state, 0, -5, "bottom")).toBeNull();+ });+});++describe("truchet flip determinism", () => {+ it("renders any frame identically in any sampling order", () => {+ const sample = (frame: number) =>+ getTruchetFlipState(frame, { seed: 11, waveMode: "random", passes: 3 });+ const frames = [0, 21, 57, 90, 133, 160];+ const forward = frames.map(sample);+ const backward = [...frames].reverse().map(sample).reverse();+ expect(backward).toEqual(forward);+ expect(sample(57)).toEqual(forward[2]);+ });++ it("changes the opening maze with the seed and keeps it balanced", () => {+ const maze = (seed: number) =>+ getTruchetFlipGrid({ seed }).tiles.map((tile) => tile.initial);+ expect(maze(1)).toEqual(maze(1));+ expect(maze(2)).not.toEqual(maze(1));+ const turned = maze(1).filter((value) => value === 1).length;+ expect(turned).toBeGreaterThan(180 * 0.3);+ expect(turned).toBeLessThan(180 * 0.7);+ });++ it("loops back to the opening maze without a seam", () => {+ const options = { loop: true };+ const { duration } = getTruchetFlipTimeline(options);+ expect(duration).toBe(168);+ const first = getTruchetFlipState(0, options).tiles;+ const last = getTruchetFlipState(duration - 1, options).tiles;+ for (const [index, tile] of first.entries()) {+ const halfTurns = (last[index].angle - tile.angle) / 180;+ expect(Math.abs(halfTurns - Math.round(halfTurns))).toBeLessThan(0.001);+ }+ const later = getTruchetFlipState(duration + 37, options);+ expect(later).toEqual(getTruchetFlipState(37, options));+ });++ it("maps other frame rates and speeds onto the 30 fps timeline", () => {+ const base = getTruchetFlipState(45).tiles;+ expect(getTruchetFlipState(90, { fps: 60 }).tiles).toEqual(base);+ expect(getTruchetFlipState(90, { speed: 0.5 }).tiles).toEqual(base);+ const frozen = getTruchetFlipState(90, { speed: 0 }).tiles;+ expect(frozen).toEqual(getTruchetFlipState(0).tiles);+ });+});++describe("truchet flip geometry", () => {+ it("covers wide, square and tall frames with short-side tiles", () => {+ for (const [width, height] of [+ [1280, 720],+ [720, 1280],+ [1080, 1080],+ [2560, 720],+ ]) {+ const grid = getTruchetFlipGrid({ width, height });+ const half = grid.size / 2;+ expect(grid.size).toBeCloseTo(Math.min(width, height) / 10, 6);+ for (const tile of grid.tiles) {+ expect(tile.x + half).toBeGreaterThan(0);+ expect(tile.x - half).toBeLessThan(width);+ expect(tile.y + half).toBeGreaterThan(0);+ expect(tile.y - half).toBeLessThan(height);+ }+ const xs = grid.tiles.map((tile) => tile.x);+ const ys = grid.tiles.map((tile) => tile.y);+ expect(Math.min(...xs) - half).toBeLessThanOrEqual(0.001);+ expect(Math.max(...xs) + half).toBeGreaterThanOrEqual(width - 0.001);+ expect(Math.min(...ys) - half).toBeLessThanOrEqual(0.001);+ expect(Math.max(...ys) + half).toBeGreaterThanOrEqual(height - 0.001);+ const origin = grid.tiles.find(({ col, row }) => col === 0 && row === 0);+ expect(origin?.x).toBeCloseTo(width / 2 + half, 2);+ expect(origin?.y).toBeCloseTo(height / 2 + half, 2);+ }+ });++ it("keeps element counts in the hundreds and clamps invalid input", () => {+ expect(getTruchetFlipGrid().tiles).toHaveLength(180);+ expect(getTruchetFlipGrid({ tiles: 24 }).tiles.length).toBeLessThan(1100);+ expect(getTruchetFlipGrid({ tiles: Number.NaN }).count).toBe(10);+ expect(getTruchetFlipGrid({ tiles: 1 }).count).toBe(4);+ expect(getTruchetFlipGrid({ tiles: 99 }).count).toBe(24);+ expect(getTruchetFlipGrid({ tiles: 9.6 }).count).toBe(10);+ for (const tiles of [4, 7, 24]) {+ for (const frame of [0, 40, 80, 200]) {+ const state = getTruchetFlipState(frame, { tiles, weight: 9 });+ expect(state.path).not.toMatch(/NaN|Infinity/);+ expect(state.strokeWidth).toBeCloseTo(state.size * 0.34, 2);+ for (const tile of state.tiles) {+ expect(tile.transform).not.toMatch(/NaN|Infinity/);+ }+ }+ }+ });++ it("ends every arc on an edge midpoint so neighbors join at rest", () => {+ const values = numbers(getTruchetFlipTilePath(72, "stroke", 0.75));+ expect(values).toHaveLength(18);+ const ends = [+ [values[0], values[1], 0, -36],+ [values[7], values[8], -36, 0],+ [values[9], values[10], 0, 36],+ [values[16], values[17], 36, 0],+ ];+ for (const [x, y, midX, midY] of ends) {+ expect(Math.hypot(x - midX, y - midY)).toBeCloseTo(0.75, 2);+ }+ const filled = getTruchetFlipTilePath(72, "filled", 0.75);+ expect(filled.match(/Z/g)).toHaveLength(2);+ expect(filled).not.toMatch(/NaN/);+ });++ it("fills the same two corners with quarter discs", () => {+ const values = numbers(getTruchetFlipTilePath(72, "filled", 0.75));+ expect(values).toHaveLength(22);+ for (const [offset, corner] of [+ [0, -36],+ [11, 36],+ ]) {+ const pushed = corner + Math.sign(corner) * 0.75;+ expect(values[offset]).toBeCloseTo(pushed, 2);+ expect(values[offset + 1]).toBeCloseTo(pushed, 2);+ for (const point of [offset + 2, offset + 9]) {+ const x = values[point] - corner;+ const y = values[point + 1] - corner;+ expect(Math.hypot(x, y)).toBeCloseTo(36, 2);+ }+ }+ const state = getTruchetFlipState(0, { variant: "filled" });+ expect(state.variant).toBe("filled");+ expect(state.path).toBe(getTruchetFlipTilePath(state.size, "filled"));+ });+});++describe("truchet flip config", () => {+ it("matches the component defaults and exposes every mode", () => {+ const { controls: schema } = truchetFlipConfig;+ const controls = resolveControls("truchet-flip", schema);+ expect(getDefaults(controls)).toEqual({+ ...truchetFlipDefaults,+ secondaryColor: truchetFlipDefaults.color,+ });+ const options = (key: string) => {+ const control = controls[key];+ return control.type === "select" ? control.options : [];+ };+ expect(options("waveMode")).toEqual(["radial", "diagonal", "random"]);+ expect(options("resolve")).toEqual(["rings", "field", "silhouette"]);+ expect(options("variant")).toEqual(["stroke", "filled"]);+ const range = (key: string) => {+ const control = controls[key];+ return control.type === "number" ? [control.min, control.max] : [];+ };+ expect(range("tiles")).toEqual([4, 24]);+ expect(range("weight")).toEqual([0.04, 0.34]);+ expect(range("passes")).toEqual([0, 4]);+ });+});diff --git a/registry/remocn/truchet-flip/config.ts b/registry/remocn/truchet-flip/config.tsnew file mode 100644index 00000000..0aca6de5--- /dev/null+++ b/registry/remocn/truchet-flip/config.ts@@ -0,0 +1,81 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";+import { getTruchetFlipDuration } from ".";++function durationOf(values: Record<string, unknown>) {+ const speed = typeof values.speed === "number" ? values.speed : undefined;+ const passes = typeof values.passes === "number" ? values.passes : undefined;+ return getTruchetFlipDuration({ speed, passes, loop: values.loop === true });+}++export const truchetFlipConfig: ComponentConfig = {+ componentName: "TruchetFlip",+ importPath: "@/components/remocn/truchet-flip",+ controls: {+ tiles: {+ type: "number",+ default: 10,+ min: 4,+ max: 24,+ step: 1,+ description: "Tiles across",+ hiddenFromList: false,+ },+ weight: {+ type: "number",+ default: 0.2,+ min: 0.04,+ max: 0.34,+ step: 0.01,+ description: "Stroke weight",+ hiddenFromList: false,+ },+ passes: {+ type: "number",+ default: 2,+ min: 0,+ max: 4,+ step: 1,+ description: "Passes",+ hiddenFromList: false,+ },+ waveMode: {+ type: "enum",+ default: "radial",+ variants: { radial: {}, diagonal: {}, random: {} },+ description: "Wave",+ },+ resolve: {+ type: "enum",+ default: "rings",+ variants: { rings: {}, field: {}, silhouette: {} },+ description: "Resolve to",+ },+ variant: {+ type: "enum",+ default: "stroke",+ variants: { stroke: {}, filled: {} },+ description: "Variant",+ },+ color: { type: "color", default: "#ffffff", description: "Line color" },+ secondaryColor: {+ type: "color",+ default: "#ffffff",+ description: "Alternate tiles",+ },+ seed: {+ type: "number",+ default: 1,+ min: 1,+ step: 1,+ description: "Seed",+ hiddenFromList: false,+ },+ loop: { type: "boolean", default: false, description: "Loop" },+ },+ durationInFrames: 120,+ getDurationInFrames: durationOf,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#002fa7" },+};diff --git a/registry/remocn/truchet-flip/index.tsx b/registry/remocn/truchet-flip/index.tsxnew file mode 100644index 00000000..7ebdc49c--- /dev/null+++ b/registry/remocn/truchet-flip/index.tsx@@ -0,0 +1,372 @@+"use client";++import { useMemo } from "react";+import { random, useCurrentFrame, useVideoConfig } from "remotion";++export type TruchetFlipWaveMode = "radial" | "diagonal" | "random";+export type TruchetFlipResolve = "rings" | "field" | "silhouette";+export type TruchetFlipVariant = "stroke" | "filled";+export type TruchetFlipOrientation = 0 | 1;++export interface TruchetFlipProps {+ tiles?: number;+ weight?: number;+ passes?: number;+ waveMode?: TruchetFlipWaveMode;+ resolve?: TruchetFlipResolve;+ variant?: TruchetFlipVariant;+ color?: string;+ secondaryColor?: string;+ seed?: number;+ speed?: number;+ loop?: boolean;+ className?: string;+}++type Paint = "color" | "secondaryColor" | "className";+type Unset = "secondaryColor" | "className";++export interface TruchetFlipOptions extends Omit<TruchetFlipProps, Paint> {+ width?: number;+ height?: number;+ fps?: number;+}++export interface TruchetFlipTile {+ col: number;+ row: number;+ x: number;+ y: number;+ alternate: boolean;+ initial: TruchetFlipOrientation;+ target: TruchetFlipOrientation;+ delay: number;+}++export const truchetFlipDefaults: Required<Omit<TruchetFlipProps, Unset>> = {+ tiles: 10,+ weight: 0.2,+ passes: 2,+ waveMode: "radial",+ resolve: "rings",+ variant: "stroke",+ color: "#ffffff",+ seed: 1,+ speed: 1,+ loop: false,+};++const LEAD = 6;+const SPREAD = 30;+const SNAP = 12;+const SNAP_SETTLE = 8;+const SNAP_RISE = 4;+const SNAP_DAMPING = 0.65;+const GAP = 24;+const RESOLVE_GAP = 30;+const HOLD = 18;+const LOOP_HOLD = 24;+const MAX_PASSES = 4;+const MIN_TILES = 4;+const MAX_TILES = 24;+const MIN_WEIGHT = 0.04;+const MAX_WEIGHT = 0.34;+const SILHOUETTE = 0.38;+const OVERLAP = 0.75;+const SNAP_FREQUENCY = (Math.PI - Math.acos(SNAP_DAMPING)) / SNAP_RISE;+const SNAP_RATIO = SNAP_DAMPING / Math.sqrt(1 - SNAP_DAMPING ** 2);++const finite = (value: number | undefined, fallback: number) =>+ typeof value === "number" && Number.isFinite(value) ? value : fallback;+const clamp = (value: number, min: number, max: number) =>+ Math.min(max, Math.max(min, value));+const round = (value: number) => Math.round(value * 1000) / 1000;+const isOdd = (value: number) => Math.abs(value % 2) === 1;+const turn = (wave: number) => (wave % 2 === 0 ? 1 : -1);+const rateOf = (speed: number | undefined) =>+ Math.max(0, finite(speed, truchetFlipDefaults.speed));+const waveOf = (value: string | undefined): TruchetFlipWaveMode =>+ value === "diagonal" || value === "random" ? value : "radial";+const resolveOf = (value: string | undefined): TruchetFlipResolve =>+ value === "field" || value === "silhouette" ? value : "rings";+const variantOf = (value: string | undefined): TruchetFlipVariant =>+ value === "filled" ? value : "stroke";++function smoothstep(value: number) {+ const t = clamp(value, 0, 1);+ return t * t * (3 - 2 * t);+}++function mazeKey(seed: number, col: number, row: number) {+ return random(`truchet-flip-${seed}-${col}-${row}`);+}++function waveKey(seed: number, col: number, row: number) {+ return random(`truchet-flip-${seed}-wave-${col}-${row}`);+}++export function getTruchetFlipSnap(frames: number) {+ if (Number.isNaN(frames) || frames <= 0) return 0;+ if (frames >= SNAP) return 1;+ const phase = SNAP_FREQUENCY * frames;+ const decay = Math.exp(-SNAP_RATIO * phase);+ const ring = decay * (Math.cos(phase) + SNAP_RATIO * Math.sin(phase));+ const settle = smoothstep((frames - SNAP_SETTLE) / (SNAP - SNAP_SETTLE));+ return 1 - ring * (1 - settle);+}++export function getTruchetFlipTimeline(options: TruchetFlipOptions = {}) {+ const requested = finite(options.passes, truchetFlipDefaults.passes);+ const passes = Math.round(clamp(requested, 0, MAX_PASSES));+ const starts = Array.from({ length: passes }, (_, i) => LEAD + i * GAP);+ const lastPass = LEAD + Math.max(0, passes - 1) * GAP;+ const resolveStart = passes === 0 ? LEAD : lastPass + RESOLVE_GAP;+ const settled = resolveStart + SPREAD + SNAP;+ const returnStart = settled + LOOP_HOLD;+ const loop = options.loop === true;+ const duration = loop ? returnStart + SPREAD + SNAP : settled + HOLD;+ return {+ passes,+ starts,+ resolveStart,+ settled,+ returnStart,+ loop,+ duration,+ };+}++export type TruchetFlipTimeline = ReturnType<typeof getTruchetFlipTimeline>;++export const truchetFlipLength = getTruchetFlipTimeline().settled;++export function getTruchetFlipDuration(options: TruchetFlipOptions = {}) {+ const rate = rateOf(options.speed);+ const { duration } = getTruchetFlipTimeline(options);+ return rate === 0 ? 1 : Math.max(1, Math.ceil(duration / rate));+}++export function getTruchetFlipTime(+ frame: number,+ options: TruchetFlipOptions = {},+) {+ const scale = 30 / Math.max(1, finite(options.fps, 30));+ const time = Math.max(0, finite(frame, 0)) * scale * rateOf(options.speed);+ const { duration, loop } = getTruchetFlipTimeline(options);+ return loop ? time % duration : time;+}++export function getTruchetFlipTarget(+ resolve: TruchetFlipResolve,+ col: number,+ row: number,+ tiles = truchetFlipDefaults.tiles,+): TruchetFlipOrientation {+ if (resolve === "field") return 0;+ if (resolve === "silhouette") {+ const inside = Math.hypot(col + 0.5, row + 0.5) < tiles * SILHOUETTE;+ return inside && isOdd(col + row) ? 1 : 0;+ }+ const left = col < 0;+ const above = row < 0;+ return left === above ? 0 : 1;+}++export function getTruchetFlipGrid(options: TruchetFlipOptions = {}) {+ const width = Math.max(1, finite(options.width, 1280));+ const height = Math.max(1, finite(options.height, 720));+ const requested = finite(options.tiles, truchetFlipDefaults.tiles);+ const count = Math.round(clamp(requested, MIN_TILES, MAX_TILES));+ const size = Math.min(width, height) / count;+ const halfCols = Math.ceil(width / 2 / size - 1e-6);+ const halfRows = Math.ceil(height / 2 / size - 1e-6);+ const seed = finite(options.seed, truchetFlipDefaults.seed);+ const mode = waveOf(options.waveMode);+ const resolve = resolveOf(options.resolve);+ const cells: { col: number; row: number }[] = [];+ for (let row = -halfRows; row < halfRows; row++) {+ for (let col = -halfCols; col < halfCols; col++) cells.push({ col, row });+ }+ const ranks: number[] = [];+ if (mode === "random") {+ const keys = cells.map(({ col, row }) => waveKey(seed, col, row));+ const order = keys.map((_, index) => index);+ order.sort((a, b) => keys[a] - keys[b]);+ for (const [position, index] of order.entries()) ranks[index] = position;+ }+ const shift = halfCols + halfRows;+ const diagonals = 2 * (shift - 1);+ const nearest = Math.hypot(0.5, 0.5);+ const farthest = Math.hypot(halfCols - 0.5, halfRows - 0.5);+ const delayOf = (col: number, row: number, index: number) => {+ if (mode === "random") {+ return (SPREAD * ranks[index]) / (cells.length - 1);+ }+ if (mode === "diagonal") {+ return (SPREAD * (col + row + shift)) / diagonals;+ }+ const distance = Math.hypot(col + 0.5, row + 0.5) - nearest;+ return (SPREAD * distance) / Math.max(1e-6, farthest - nearest);+ };+ const tiles: TruchetFlipTile[] = cells.map(({ col, row }, index) => ({+ col,+ row,+ x: round(width / 2 + (col + 0.5) * size),+ y: round(height / 2 + (row + 0.5) * size),+ alternate: isOdd(col + row),+ initial: mazeKey(seed, col, row) < 0.5 ? 0 : 1,+ target: getTruchetFlipTarget(resolve, col, row, count),+ delay: round(clamp(delayOf(col, row, index), 0, SPREAD)),+ }));+ return {+ width,+ height,+ count,+ size,+ unit: Math.min(width, height) / 720,+ tiles,+ };+}++export type TruchetFlipGrid = ReturnType<typeof getTruchetFlipGrid>;++export function getTruchetFlipAngle(+ tile: TruchetFlipTile,+ time: number,+ timeline: TruchetFlipTimeline,+) {+ let turns = 0;+ for (const [wave, start] of timeline.starts.entries()) {+ turns += turn(wave) * getTruchetFlipSnap(time - start - tile.delay);+ }+ const reached = (tile.initial + timeline.passes) % 2;+ if (reached !== tile.target) {+ const since = time - timeline.resolveStart - tile.delay;+ turns += turn(timeline.passes) * getTruchetFlipSnap(since);+ }+ if (timeline.loop && tile.target !== tile.initial) {+ const since = time - timeline.returnStart - tile.delay;+ turns += turn(timeline.passes + 1) * getTruchetFlipSnap(since);+ }+ return (tile.initial + turns) * 90;+}++export function getTruchetFlipTilePath(+ size: number,+ variant: TruchetFlipVariant = "stroke",+ overlap = OVERLAP,+) {+ const half = Math.max(0, finite(size, 0)) / 2;+ const pad = clamp(finite(overlap, OVERLAP), 0, half / 4);+ const radius = `${round(half)} ${round(half)}`;+ const point = (x: number, y: number) => `${round(x)} ${round(y)}`;+ if (variant === "filled") {+ const reach = Math.sqrt(half * half - pad * pad);+ const sector = (cx: number, cy: number, side: number) => {+ const corner = point(cx - side * pad, cy - side * pad);+ const start = point(cx + side * reach, cy - side * pad);+ const end = point(cx - side * pad, cy + side * reach);+ return `M ${corner} L ${start} A ${radius} 0 0 1 ${end} Z`;+ };+ return `${sector(-half, -half, 1)} ${sector(half, half, -1)}`;+ }+ const bend = half > 0 ? pad / half : 0;+ const cos = half * Math.cos(bend);+ const sin = half * Math.sin(bend);+ const arc = (cx: number, cy: number, side: number) => {+ const start = point(cx + side * cos, cy - side * sin);+ const end = point(cx - side * sin, cy + side * cos);+ return `M ${start} A ${radius} 0 0 1 ${end}`;+ };+ return `${arc(-half, -half, 1)} ${arc(half, half, -1)}`;+}++export function getTruchetFlipState(+ frame: number,+ options: TruchetFlipOptions = {},+ grid: TruchetFlipGrid = getTruchetFlipGrid(options),+) {+ const timeline = getTruchetFlipTimeline(options);+ const time = getTruchetFlipTime(frame, options);+ const variant = variantOf(options.variant);+ const requested = finite(options.weight, truchetFlipDefaults.weight);+ const weight = clamp(requested, MIN_WEIGHT, MAX_WEIGHT);+ return {+ ...grid,+ time,+ timeline,+ variant,+ strokeWidth: round(grid.size * weight),+ path: getTruchetFlipTilePath(grid.size, variant, OVERLAP * grid.unit),+ tiles: grid.tiles.map((tile) => {+ const angle = getTruchetFlipAngle(tile, time, timeline);+ const rotation = round(angle);+ const transform = `translate(${tile.x} ${tile.y}) rotate(${rotation})`;+ return { ...tile, angle, transform };+ }),+ };+}++export function TruchetFlip({+ tiles = truchetFlipDefaults.tiles,+ weight = truchetFlipDefaults.weight,+ passes = truchetFlipDefaults.passes,+ waveMode = truchetFlipDefaults.waveMode,+ resolve = truchetFlipDefaults.resolve,+ variant = truchetFlipDefaults.variant,+ color = truchetFlipDefaults.color,+ secondaryColor,+ seed = truchetFlipDefaults.seed,+ speed = truchetFlipDefaults.speed,+ loop = truchetFlipDefaults.loop,+ className,+}: TruchetFlipProps) {+ const frame = useCurrentFrame();+ const { width, height, fps } = useVideoConfig();+ const grid = useMemo(() => {+ const layout = { width, height, tiles, seed, waveMode, resolve };+ return getTruchetFlipGrid(layout);+ }, [width, height, tiles, seed, waveMode, resolve]);+ const motion = { fps, weight, passes, variant, speed, loop };+ const state = getTruchetFlipState(frame, motion, grid);+ const filled = state.variant === "filled";+ const primary = state.tiles.filter((tile) => !tile.alternate);+ const alternate = state.tiles.filter((tile) => tile.alternate);+ const layers = [+ { key: "primary", paint: color, tiles: primary },+ { key: "alternate", paint: secondaryColor ?? color, tiles: alternate },+ ];++ return (+ <div+ className={className}+ style={{ position: "absolute", inset: 0, overflow: "hidden" }}+ >+ <svg+ width="100%"+ height="100%"+ viewBox={`0 0 ${width} ${height}`}+ role="img"+ aria-label="Truchet tile pattern"+ style={{ display: "block" }}+ >+ {layers.map((layer) => (+ <g+ key={layer.key}+ fill={filled ? layer.paint : "none"}+ stroke={filled ? "none" : layer.paint}+ strokeWidth={filled ? undefined : state.strokeWidth}+ >+ {layer.tiles.map((tile) => (+ <path+ key={`${tile.col}:${tile.row}`}+ d={state.path}+ transform={tile.transform}+ />+ ))}+ </g>+ ))}+ </svg>+ </div>+ );+}diff --git a/registry/remocn/type-repeater/__tests__/type-repeater.test.ts b/registry/remocn/type-repeater/__tests__/type-repeater.test.tsnew file mode 100644index 00000000..ed33bb35--- /dev/null+++ b/registry/remocn/type-repeater/__tests__/type-repeater.test.ts@@ -0,0 +1,120 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getTypeRepeaterCopy,+ getTypeRepeaterIntro,+ getTypeRepeaterSpread,+ getTypeRepeaterTime,+ typeRepeaterDefaults,+ typeRepeaterLength,+ typeRepeaterModes,+} from "..";+import { typeRepeaterConfig } from "../config";++describe("type-repeater spread", () => {+ it("stays folded until frame 10 and after the collapse", () => {+ expect(getTypeRepeaterSpread(0)).toBe(0);+ expect(getTypeRepeaterSpread(10)).toBe(0);+ expect(getTypeRepeaterSpread(typeRepeaterLength)).toBe(0);+ expect(getTypeRepeaterSpread(200)).toBe(0);+ });++ it("unfolds with an overshoot, breathes, then collapses without jumps", () => {+ let peak = 0;+ for (let t = 10; t <= 34; t += 0.1) {+ peak = Math.max(peak, getTypeRepeaterSpread(t));+ }+ expect(peak).toBeGreaterThan(1.05);+ expect(getTypeRepeaterSpread(34)).toBeCloseTo(1, 10);+ expect(getTypeRepeaterSpread(43)).toBeCloseTo(1.06, 10);+ expect(getTypeRepeaterSpread(69.999)).toBeCloseTo(1, 3);+ expect(getTypeRepeaterSpread(70)).toBe(1);+ let last = getTypeRepeaterSpread(70);+ for (let t = 70; t <= 90; t += 0.5) {+ const s = getTypeRepeaterSpread(t);+ expect(s).toBeLessThanOrEqual(last);+ last = s;+ }+ });++ it("brings the word in over ten frames", () => {+ expect(getTypeRepeaterIntro(0)).toBe(0);+ expect(getTypeRepeaterIntro(10)).toBe(1);+ });+});++describe("type-repeater copies", () => {+ it("leaves the word itself untouched", () => {+ for (const mode of ["fan", "spiral", "tunnel"] as const) {+ expect(getTypeRepeaterCopy(0, 12, 1, mode)).toEqual({+ rotate: 0,+ scale: 1,+ opacity: 1,+ tint: 0,+ });+ }+ });++ it("grows tunnel copies outward without turning them", () => {+ const copy = getTypeRepeaterCopy(3, 12, 1, "tunnel");+ expect(copy.rotate).toBe(0);+ expect(copy.scale).toBeCloseTo(typeRepeaterModes.tunnel.scale ** 3, 10);+ });++ it("turns and grows spiral copies step by step", () => {+ const copy = getTypeRepeaterCopy(4, 12, 1, "spiral");+ expect(copy.rotate).toBeCloseTo(4 * typeRepeaterModes.spiral.rotate, 10);+ expect(copy.scale).toBeCloseTo(typeRepeaterModes.spiral.scale ** 4, 10);+ });++ it("fans copies out to alternating sides", () => {+ const step = typeRepeaterModes.fan.rotate;+ expect(getTypeRepeaterCopy(1, 12, 1, "fan").rotate).toBe(step);+ expect(getTypeRepeaterCopy(2, 12, 1, "fan").rotate).toBe(-step);+ expect(getTypeRepeaterCopy(3, 12, 1, "fan").rotate).toBe(2 * step);+ expect(getTypeRepeaterCopy(4, 12, 1, "fan").rotate).toBe(-2 * step);+ });++ it("collapses every copy onto the word at zero spread", () => {+ for (const mode of ["fan", "spiral", "tunnel"] as const) {+ const copy = getTypeRepeaterCopy(7, 12, 0, mode);+ expect(copy.rotate).toBe(0);+ expect(copy.scale).toBe(1);+ expect(copy.opacity).toBe(0);+ }+ });++ it("fades and tints copies toward the accent by index", () => {+ const near = getTypeRepeaterCopy(1, 12, 1, "tunnel");+ const far = getTypeRepeaterCopy(11, 12, 1, "tunnel");+ expect(far.opacity).toBeLessThan(near.opacity);+ expect(far.opacity).toBeGreaterThan(0);+ expect(far.tint).toBe(1);+ expect(near.tint).toBeCloseTo(1 / 11, 10);+ });+});++describe("type-repeater time and config", () => {+ it("maps frames onto the 30 fps timeline", () => {+ expect(getTypeRepeaterTime(30)).toBe(30);+ expect(getTypeRepeaterTime(60, { fps: 60 })).toBe(30);+ expect(getTypeRepeaterTime(10, { speed: 2 })).toBe(20);+ });++ it("previews the tunnel on the reel's orange field", () => {+ const defaults = getDefaults(+ resolveControls("type-repeater", typeRepeaterConfig.controls),+ );+ expect(defaults).toMatchObject({+ text: typeRepeaterDefaults.text,+ mode: typeRepeaterDefaults.mode,+ copies: typeRepeaterDefaults.copies,+ fontSize: typeRepeaterDefaults.fontSize,+ fontWeight: typeRepeaterDefaults.fontWeight,+ outline: typeRepeaterDefaults.outline,+ });+ expect(typeRepeaterConfig.durationInFrames).toBeGreaterThan(+ typeRepeaterLength,+ );+ });+});diff --git a/registry/remocn/type-repeater/config.ts b/registry/remocn/type-repeater/config.tsnew file mode 100644index 00000000..02001585--- /dev/null+++ b/registry/remocn/type-repeater/config.ts@@ -0,0 +1,56 @@+import {+ type ComponentConfig,+ enumVariants,+ FPS,+ H,+ W,+} from "@/lib/customizer-config";++export const typeRepeaterConfig: ComponentConfig = {+ componentName: "TypeRepeater",+ importPath: "@/components/remocn/type-repeater",+ controls: {+ text: { type: "text-content", default: "Repeat", description: "Text" },+ mode: {+ type: "enum",+ default: "tunnel",+ variants: enumVariants(["tunnel", "spiral", "fan"]),+ description: "Mode",+ },+ color: { type: "color", default: "#111111", description: "Word color" },+ accent: { type: "color", default: "#fafafa", description: "Last copy" },+ copies: {+ type: "number",+ default: 12,+ min: 2,+ max: 24,+ step: 1,+ description: "Copies",+ hiddenFromList: false,+ },+ fontSize: {+ type: "number",+ default: 110,+ min: 40,+ max: 240,+ step: 2,+ description: "Font size",+ hiddenFromList: false,+ },+ fontWeight: {+ type: "number",+ default: 800,+ min: 100,+ max: 900,+ step: 50,+ description: "Weight",+ hiddenFromList: false,+ },+ outline: { type: "boolean", default: true, description: "Outline copies" },+ },+ durationInFrames: 100,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#ff4d1a" },+};diff --git a/registry/remocn/type-repeater/index.tsx b/registry/remocn/type-repeater/index.tsxnew file mode 100644index 00000000..dd2901ea--- /dev/null+++ b/registry/remocn/type-repeater/index.tsx@@ -0,0 +1,245 @@+"use client";++import { loadFont } from "@remotion/google-fonts/Inter";+import { useId } from "react";+import {+ Easing,+ interpolate,+ interpolateColors,+ useCurrentFrame,+ useVideoConfig,+} from "remotion";++const { fontFamily: INTER } = loadFont("normal", {+ weights: ["100", "900"],+ subsets: ["latin"],+});++export type TypeRepeaterMode = "fan" | "spiral" | "tunnel";++export interface TypeRepeaterProps {+ text?: string;+ copies?: number;+ mode?: TypeRepeaterMode;+ fontSize?: number;+ fontWeight?: number;+ fontFamily?: string;+ color?: string;+ accent?: string;+ outline?: boolean;+ speed?: number;+ className?: string;+}++export const typeRepeaterDefaults = {+ text: "Repeat",+ copies: 12,+ mode: "tunnel",+ fontSize: 110,+ fontWeight: 800,+ fontFamily: INTER,+ color: "#fafafa",+ accent: "#D97757",+ outline: true,+ speed: 1,+} satisfies Required<Omit<TypeRepeaterProps, "className">>;++/** Beats on the 30 fps clock. */+export const typeRepeaterTiming = {+ intro: [0, 10],+ unfold: [10, 34],+ breathe: [34, 70],+ collapse: [70, 90],+} as const;++/** Frame where the copies have folded back into the word. */+export const typeRepeaterLength = typeRepeaterTiming.collapse[1];++/**+ * Per-copy steps for each mode. `fan` alternates sides around a pivot below+ * the word; `spiral` and `tunnel` grow each copy outward behind it.+ */+export const typeRepeaterModes = {+ fan: { rotate: 11, scale: 1, pivot: 2.6, symmetric: true },+ spiral: { rotate: 12, scale: 1.1, pivot: 0, symmetric: false },+ tunnel: { rotate: 0, scale: 1.2, pivot: 0, symmetric: false },+} as const satisfies Record<+ TypeRepeaterMode,+ { rotate: number; scale: number; pivot: number; symmetric: boolean }+>;++const BREATHE = 0.06;+const FADE = 0.85;++const CLAMP = {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+} as const;++const easeOutCubic = Easing.out(Easing.cubic);+const easeInOutCubic = Easing.inOut(Easing.cubic);+const unfoldEase = Easing.out(Easing.back(1.4));++function finite(value: number | undefined, fallback: number) {+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;+}++/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */+export function getTypeRepeaterTime(+ frame: number,+ options: { fps?: number; speed?: number } = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const speed = Math.max(0, finite(options.speed, 1));+ return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;+}++/** How far the copies have spread, 0 (one word) to about 1. */+export function getTypeRepeaterSpread(t: number) {+ const { unfold, breathe, collapse } = typeRepeaterTiming;+ if (t < breathe[0]) {+ return interpolate(t, [...unfold], [0, 1], {+ ...CLAMP,+ easing: unfoldEase,+ });+ }+ if (t < breathe[1]) {+ const phase = (t - breathe[0]) / (breathe[1] - breathe[0]);+ return 1 + BREATHE * Math.sin(2 * Math.PI * phase);+ }+ return interpolate(t, [...collapse], [1, 0], {+ ...CLAMP,+ easing: easeInOutCubic,+ });+}++/** Entrance of the front word, 0..1. */+export function getTypeRepeaterIntro(t: number) {+ return interpolate(t, [...typeRepeaterTiming.intro], [0, 1], {+ ...CLAMP,+ easing: easeOutCubic,+ });+}++export interface TypeRepeaterCopy {+ rotate: number;+ scale: number;+ opacity: number;+ /** 0 for the word's color, 1 for the accent. */+ tint: number;+}++/** Transform and fade of copy `index` (0 is the word itself). */+export function getTypeRepeaterCopy(+ index: number,+ copies: number,+ spread: number,+ mode: TypeRepeaterMode,+): TypeRepeaterCopy {+ const step = typeRepeaterModes[mode] ?? typeRepeaterModes.spiral;+ const n = Math.max(1, Math.round(copies));+ const steps = step.symmetric ? Math.ceil(index / 2) : index;+ const side = step.symmetric && index % 2 === 0 ? -1 : 1;+ const reach = steps * spread;+ return {+ rotate: side * step.rotate * reach || 0,+ scale: step.scale ** reach,+ opacity:+ index === 0+ ? 1+ : (1 - (FADE * index) / n) * Math.min(1, Math.max(0, spread * 4)),+ tint: n > 1 ? index / (n - 1) : 0,+ };+}++export function TypeRepeater({+ text = typeRepeaterDefaults.text,+ copies = typeRepeaterDefaults.copies,+ mode = typeRepeaterDefaults.mode,+ fontSize = typeRepeaterDefaults.fontSize,+ fontWeight = typeRepeaterDefaults.fontWeight,+ fontFamily = typeRepeaterDefaults.fontFamily,+ color = typeRepeaterDefaults.color,+ accent = typeRepeaterDefaults.accent,+ outline = typeRepeaterDefaults.outline,+ speed = typeRepeaterDefaults.speed,+ className,+}: TypeRepeaterProps) {+ const frame = useCurrentFrame();+ const { fps, height } = useVideoConfig();+ const outlineId = `type-repeater-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;+ const unit = height / 720;+ const size = fontSize * unit;+ const t = getTypeRepeaterTime(frame, { fps, speed });+ const spread = getTypeRepeaterSpread(t);+ const intro = getTypeRepeaterIntro(t);+ const count = Math.max(1, Math.round(finite(copies, 12)));+ const pivot = (typeRepeaterModes[mode] ?? typeRepeaterModes.spiral).pivot;++ return (+ <div+ className={className}+ style={{+ position: "absolute",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ overflow: "hidden",+ }}+ >+ {outline ? (+ // Outline from the filled silhouette: the variable font's overlapping+ // contours would show through a text stroke.+ <svg width={0} height={0} style={{ position: "absolute" }} aria-hidden>+ <defs>+ <filter id={outlineId}>+ <feMorphology+ in="SourceAlpha"+ operator="erode"+ radius={1.5 * unit}+ result="inner"+ />+ <feComposite in="SourceGraphic" in2="inner" operator="out" />+ </filter>+ </defs>+ </svg>+ ) : null}+ <div+ style={{+ position: "relative",+ opacity: intro,+ transform: `scale(${0.9 + 0.1 * intro})`,+ }}+ >+ {Array.from({ length: count }, (_, i) => count - 1 - i).map((i) => {+ const copy = getTypeRepeaterCopy(i, count, spread, mode);+ if (copy.opacity <= 0) return null;+ return (+ <div+ key={i}+ aria-hidden={i > 0}+ style={{+ position: i === 0 ? "relative" : "absolute",+ inset: i === 0 ? undefined : 0,+ fontFamily,+ fontSize: size,+ lineHeight: 1,+ fontWeight,+ fontVariationSettings: `"wght" ${fontWeight}`,+ whiteSpace: "pre",+ color: interpolateColors(copy.tint, [0, 1], [color, accent]),+ opacity: copy.opacity,+ filter: outline && i > 0 ? `url(#${outlineId})` : undefined,+ transformOrigin: `50% calc(50% + ${pivot}em)`,+ transform: `rotate(${copy.rotate}deg) scale(${copy.scale})`,+ }}+ >+ {text}+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/registry/remocn/type-wall/__tests__/type-wall.test.ts b/registry/remocn/type-wall/__tests__/type-wall.test.tsnew file mode 100644index 00000000..59cced70--- /dev/null+++ b/registry/remocn/type-wall/__tests__/type-wall.test.ts@@ -0,0 +1,116 @@+import { describe, expect, it } from "bun:test";+import { getDefaults, resolveControls } from "@/lib/customizer-config";+import {+ getTypeWallBand,+ getTypeWallDirection,+ getTypeWallEntranceEnd,+ getTypeWallMotion,+ getTypeWallRow,+ getTypeWallRows,+ getTypeWallStyle,+ getTypeWallTime,+ getTypeWallTokenCount,+ typeWallDefaults,+} from "..";+import { typeWallConfig } from "../config";++describe("type-wall layout", () => {+ it("covers the frame with rows around a centered row 0", () => {+ const rows = getTypeWallRows(720, 64);+ expect(rows).toContain(0);+ expect(rows[0]).toBe(-rows[rows.length - 1]);+ const top = 360 + (rows[0] - 0.5) * 64;+ const bottom = 360 + (rows[rows.length - 1] + 0.5) * 64;+ expect(top).toBeLessThanOrEqual(0);+ expect(bottom).toBeGreaterThanOrEqual(720);+ });++ it("keeps the accent row solid and cycles the faces outward", () => {+ expect(getTypeWallStyle(0)).toBe("solid");+ expect(getTypeWallStyle(1)).toBe("narrow");+ expect(getTypeWallStyle(2)).toBe("outline");+ expect(getTypeWallStyle(3)).toBe("solid");+ expect(getTypeWallStyle(-1)).toBe("outline");+ expect(getTypeWallStyle(-2)).toBe("narrow");+ });++ it("runs neighbors in opposite directions", () => {+ for (let k = -6; k < 6; k++) {+ expect(getTypeWallDirection(k)).toBe(-getTypeWallDirection(k + 1));+ }+ expect(getTypeWallDirection(0)).toBe(-1);+ });++ it("repeats enough tokens to cover the width twice", () => {+ const count = getTypeWallTokenCount(1280, 64, "MOTION · ");+ expect(count * 9 * 0.4 * 64).toBeGreaterThanOrEqual(1280);+ expect(getTypeWallTokenCount(1280, 1, "")).toBe(48);+ });+});++describe("type-wall motion", () => {+ it("gives every row a seeded speed within ±30% of the base", () => {+ const base = 0.22 / 30;+ for (let k = -8; k <= 8; k++) {+ const { velocity, phase } = getTypeWallMotion(k, 7);+ expect(velocity).toBeGreaterThanOrEqual(base * 0.7);+ expect(velocity).toBeLessThanOrEqual(base * 1.3);+ expect(phase).toBeGreaterThanOrEqual(0);+ expect(phase).toBeLessThan(1);+ expect(getTypeWallMotion(k, 7)).toEqual({ velocity, phase });+ }+ expect(getTypeWallMotion(1, 7)).not.toEqual(getTypeWallMotion(1, 8));+ });++ it("keeps the strip shift within one token", () => {+ for (let t = 0; t < 400; t += 3.7) {+ for (const k of [-3, 0, 2]) {+ const { shift } = getTypeWallRow(t, k);+ expect(shift).toBeGreaterThanOrEqual(-1);+ expect(shift).toBeLessThanOrEqual(0);+ }+ }+ });++ it("moves each row in its direction at cruise", () => {+ const step = (k: number) => {+ const a = getTypeWallRow(200, k).shift;+ const b = getTypeWallRow(201, k).shift;+ return b - a;+ };+ expect(step(0)).toBeLessThan(0);+ expect(step(1)).toBeGreaterThan(0);+ });++ it("reveals rows from the center outward", () => {+ expect(getTypeWallRow(0, 0).reveal).toBe(0);+ expect(getTypeWallRow(20, 0).reveal).toBe(1);+ expect(getTypeWallRow(20, 3).reveal).toBeLessThan(1);+ expect(getTypeWallRow(26, 3).reveal).toBe(1);+ expect(getTypeWallEntranceEnd(720, 64)).toBe(20 + 2 * 7);+ });++ it("grows the accent band over frames 6–20", () => {+ expect(getTypeWallBand(6)).toBe(0);+ expect(getTypeWallBand(20)).toBe(1);+ expect(getTypeWallBand(13)).toBeGreaterThan(0.5);+ });+});++describe("type-wall time and config", () => {+ it("maps frames onto the 30 fps timeline", () => {+ expect(getTypeWallTime(30)).toBe(30);+ expect(getTypeWallTime(60, { fps: 60 })).toBe(30);+ expect(getTypeWallTime(10, { speed: 2 })).toBe(20);+ });++ it("previews the reel's blue wall", () => {+ const defaults = getDefaults(+ resolveControls("type-wall", typeWallConfig.controls),+ );+ expect(defaults.text).toBe(typeWallDefaults.text);+ expect(defaults.separator).toBe(typeWallDefaults.separator);+ expect(defaults.fontSize).toBe(typeWallDefaults.fontSize);+ expect(defaults.seed).toBe(typeWallDefaults.seed);+ });+});diff --git a/registry/remocn/type-wall/config.ts b/registry/remocn/type-wall/config.tsnew file mode 100644index 00000000..f117faf1--- /dev/null+++ b/registry/remocn/type-wall/config.ts@@ -0,0 +1,44 @@+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";++export const typeWallConfig: ComponentConfig = {+ componentName: "TypeWall",+ importPath: "@/components/remocn/type-wall",+ controls: {+ text: { type: "text-content", default: "MOTION", description: "Text" },+ separator: {+ type: "text-content",+ default: "·",+ description: "Separator",+ },+ color: { type: "color", default: "#fafafa", description: "Text color" },+ accent: { type: "color", default: "#ff4d1a", description: "Band color" },+ accentText: {+ type: "color",+ default: "#111111",+ description: "Band text",+ },+ fontSize: {+ type: "number",+ default: 64,+ min: 24,+ max: 180,+ step: 2,+ description: "Row height",+ hiddenFromList: false,+ },+ seed: {+ type: "number",+ default: 7,+ min: 0,+ max: 99,+ step: 1,+ description: "Seed",+ hiddenFromList: false,+ },+ },+ durationInFrames: 150,+ fps: FPS,+ compositionWidth: W,+ compositionHeight: H,+ previewBackdrop: { type: "color", value: "#2b3bff" },+};diff --git a/registry/remocn/type-wall/index.tsx b/registry/remocn/type-wall/index.tsxnew file mode 100644index 00000000..d333f6b5--- /dev/null+++ b/registry/remocn/type-wall/index.tsx@@ -0,0 +1,276 @@+"use client";++import { loadFont as loadAnton } from "@remotion/google-fonts/Anton";+import { loadFont as loadInter } from "@remotion/google-fonts/Inter";+import { useId } from "react";+import {+ Easing,+ interpolate,+ random,+ useCurrentFrame,+ useVideoConfig,+} from "remotion";++const { fontFamily: INTER } = loadInter("normal", {+ weights: ["900"],+ subsets: ["latin"],+});+const { fontFamily: ANTON } = loadAnton("normal", {+ weights: ["400"],+ subsets: ["latin"],+});++export type TypeWallStyle = "solid" | "narrow" | "outline";++export interface TypeWallProps {+ text?: string;+ separator?: string;+ fontSize?: number;+ color?: string;+ accent?: string;+ accentText?: string;+ seed?: number;+ speed?: number;+ className?: string;+}++export const typeWallDefaults = {+ text: "MOTION",+ separator: "·",+ fontSize: 64,+ color: "#fafafa",+ accent: "#D97757",+ accentText: "#0a0a0a",+ seed: 7,+ speed: 1,+} satisfies Required<Omit<TypeWallProps, "className">>;++/** Row faces away from the center, the accent row always solid. */+export const typeWallStyles: readonly TypeWallStyle[] = [+ "solid",+ "narrow",+ "outline",+];++/** Anton sized so its capitals match Inter's cap height (0.7275 / 0.8594 em). */+const NARROW_SCALE = 0.7275 / 0.8594;+/** Tokens per second at speed 1, before each row's seeded factor. */+const TOKENS_PER_SECOND = 0.22;+const ENTRANCE = 20;+const STAGGER = 2;+/** Tokens a row streams past on its way in, on top of its cruise. */+const ENTRANCE_BURST = 2.5;+const BAND = [6, 20] as const;+/** Lower bound on a token's width per character, in em, for the repeat count. */+const MIN_CHAR_WIDTH = 0.4;+const MAX_TOKENS = 48;++const CLAMP = {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+} as const;++const easeOutCubic = Easing.out(Easing.cubic);++function finite(value: number | undefined, fallback: number) {+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;+}++function fract(x: number) {+ return x - Math.floor(x);+}++/** Maps a composition frame onto the 30 fps timeline, scaled by `speed`. */+export function getTypeWallTime(+ frame: number,+ options: { fps?: number; speed?: number } = {},+) {+ const fps = Math.max(1, finite(options.fps, 30));+ const speed = Math.max(0, finite(options.speed, 1));+ return (Math.max(0, finite(frame, 0)) * 30 * speed) / fps;+}++/** Row indices from the top of the frame to the bottom; row 0 is centered. */+export function getTypeWallRows(height: number, rowHeight: number) {+ const reach = Math.ceil((height / 2 - rowHeight / 2) / rowHeight) + 1;+ const rows: number[] = [];+ for (let k = -reach; k <= reach; k++) rows.push(k);+ return rows;+}++export function getTypeWallStyle(row: number): TypeWallStyle {+ if (row === 0) return "solid";+ const n = typeWallStyles.length;+ return typeWallStyles[((row % n) + n) % n];+}++/** −1 runs left, 1 runs right. The accent row runs left. */+export function getTypeWallDirection(row: number) {+ return Math.abs(row) % 2 === 0 ? -1 : 1;+}++/** Cruise speed in tokens per frame and the row's starting phase. */+export function getTypeWallMotion(row: number, seed: number) {+ const factor = 0.7 + 0.6 * random(`type-wall-${seed}-speed-${row}`);+ return {+ velocity: (TOKENS_PER_SECOND * factor) / 30,+ phase: random(`type-wall-${seed}-phase-${row}`),+ };+}++export interface TypeWallRowState {+ direction: number;+ /** Translation of the token strip in tokens, always in [−1, 0). */+ shift: number;+ /** Share of the row revealed from its entering side, 0..1. */+ reveal: number;+}++export function getTypeWallRow(+ t: number,+ row: number,+ seed = typeWallDefaults.seed,+): TypeWallRowState {+ const direction = getTypeWallDirection(row);+ const { velocity, phase } = getTypeWallMotion(row, seed);+ const e = easeOutCubic(+ Math.min(1, Math.max(0, (t - STAGGER * Math.abs(row)) / ENTRANCE)),+ );+ const travel = phase + velocity * t + ENTRANCE_BURST * e;+ // Leftward rows slide the strip left; rightward rows run it from −1 up to 0.+ const shift = direction < 0 ? -fract(travel) : fract(travel) - 1;+ return { direction, shift: shift || 0, reveal: e };+}++/** The accent band growing from the center, 0..1. */+export function getTypeWallBand(t: number) {+ return interpolate(t, [...BAND], [0, 1], { ...CLAMP, easing: easeOutCubic });+}++/** Frame where the slowest (outermost) row has finished entering. */+export function getTypeWallEntranceEnd(height: number, rowHeight: number) {+ const rows = getTypeWallRows(height, rowHeight);+ return ENTRANCE + STAGGER * Math.max(...rows.map(Math.abs));+}++/** How many tokens a strip needs to cover the width twice over. */+export function getTypeWallTokenCount(+ width: number,+ fontSize: number,+ token: string,+) {+ const tokenWidth =+ Math.max(1, Array.from(token).length) * MIN_CHAR_WIDTH * fontSize;+ return Math.min(MAX_TOKENS, Math.ceil(width / tokenWidth) + 2);+}++export function TypeWall({+ text = typeWallDefaults.text,+ separator = typeWallDefaults.separator,+ fontSize = typeWallDefaults.fontSize,+ color = typeWallDefaults.color,+ accent = typeWallDefaults.accent,+ accentText = typeWallDefaults.accentText,+ seed = typeWallDefaults.seed,+ speed = typeWallDefaults.speed,+ className,+}: TypeWallProps) {+ const frame = useCurrentFrame();+ const { fps, width, height } = useVideoConfig();+ const unit = height / 720;+ const rowHeight = Math.max(8, fontSize * unit);+ const t = getTypeWallTime(frame, { fps, speed });+ const rows = getTypeWallRows(height, rowHeight);+ const token = `${text} ${separator} `;+ const band = getTypeWallBand(t);+ const outlineId = `type-wall-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;++ return (+ <div+ className={className}+ style={{ position: "absolute", inset: 0, overflow: "hidden" }}+ >+ {/* Outline from the filled silhouette: the variable font's overlapping+ contours would show through a text stroke. */}+ <svg width={0} height={0} style={{ position: "absolute" }} aria-hidden>+ <defs>+ <filter id={outlineId}>+ <feMorphology+ in="SourceAlpha"+ operator="erode"+ radius={1.5 * unit}+ result="inner"+ />+ <feComposite+ in="SourceAlpha"+ in2="inner"+ operator="out"+ result="ring"+ />+ <feFlood floodColor={color} />+ <feComposite in2="ring" operator="in" />+ </filter>+ </defs>+ </svg>+ {rows.map((row) => {+ const style = getTypeWallStyle(row);+ const state = getTypeWallRow(t, row, seed);+ const narrow = style === "narrow";+ const size = narrow ? rowHeight * NARROW_SCALE : rowHeight;+ const count = getTypeWallTokenCount(width, size, token);+ const onBand = row === 0;+ const hidden = `${(1 - state.reveal) * 100}%`;+ return (+ <div+ key={row}+ style={{+ position: "absolute",+ left: 0,+ right: 0,+ top: height / 2 + (row - 0.5) * rowHeight,+ height: rowHeight,+ clipPath:+ state.direction < 0+ ? `inset(0 0 0 ${hidden})`+ : `inset(0 ${hidden} 0 0)`,+ }}+ >+ {onBand ? (+ <div+ style={{+ position: "absolute",+ inset: 0,+ background: accent,+ transform: `scaleX(${band})`,+ }}+ />+ ) : null}+ <div+ style={{+ position: "absolute",+ left: 0,+ top: 0,+ width: "max-content",+ height: "100%",+ display: "flex",+ alignItems: "center",+ whiteSpace: "pre",+ fontFamily: narrow ? ANTON : INTER,+ fontSize: size,+ lineHeight: 1,+ fontWeight: narrow ? 400 : 900,+ color: onBand ? accentText : color,+ filter: style === "outline" ? `url(#${outlineId})` : undefined,+ transform: `translateX(${(state.shift * 100) / count}%)`,+ }}+ >+ {Array.from({ length: count }, (_, i) => (+ <span key={i}>{token}</span>+ ))}+ </div>+ </div>+ );+ })}+ </div>+ );+}diff --git a/source.tsx b/source.tsxindex 43482512..815e46aa 100644--- a/source.tsx+++ b/source.tsx@@ -4,6 +4,7 @@ import {BookOpen01Icon,ColorsIcon,DashboardSquare01Icon,+ GeometricShapes01Icon,Layers01Icon,Layout01Icon,MagicWand01Icon,@@ -25,6 +26,7 @@ const DOCS_ICONS: Record<string, IconSvgElement> = {BookOpen01Icon,ColorsIcon,DashboardSquare01Icon,+ GeometricShapes01Icon,Layers01Icon,Layout01Icon,MagicWand01Icon,