Skip to content

Production-ready animations, transitions, backgrounds, and scenes for Remotion

feat: added core ui

dev_wandry06814952d90f
diff --git a/bun.lock b/bun.lock
index a7605c64..3bdfbfd1 100644
--- a/bun.lock
+++ b/bun.lock
@@ -16,6 +16,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
+ "culori": "^4.0.1",
"date-fns": "^4.1.0",
"embla-carousel-react": "^8.6.0",
"fumadocs-core": "^16.7.10",
@@ -48,6 +49,7 @@
"devDependencies": {
"@biomejs/biome": "2.2.0",
"@tailwindcss/postcss": "^4",
+ "@types/culori": "^4.0.0",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
@@ -582,6 +584,8 @@
"@types/css-font-loading-module": ["@types/[email protected]", "", {}, "sha512-nl09VhutdjINdWyXxHWN/w9zlNCfr60JUqJbd24YXUuCwgeL0TpFSdElCwb6cxfB6ybE19Gjj4g0jsgkXxKv1Q=="],
+ "@types/culori": ["@types/[email protected]", "", {}, "sha512-43M51r/22CjhbOXyGT361GZ9vncSVQ39u62x5eJdBQFviI8zWp2X5jzqg7k4M6PVgDQAClpy2bUe2dtwEgEDVQ=="],
+
"@types/d3-array": ["@types/[email protected]", "", {}, "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw=="],
"@types/d3-color": ["@types/[email protected]", "", {}, "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A=="],
@@ -816,6 +820,8 @@
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
+ "culori": ["[email protected]", "", {}, "sha512-1+BhOB8ahCn4O0cep0Sh2l9KCOfOdY+BXJnKMHFFzDEouSr/el18QwXEMRlOj9UY5nCeA8UN3a/82rUWRBeyBw=="],
+
"d3-array": ["[email protected]", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg=="],
"d3-color": ["[email protected]", "", {}, "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA=="],
diff --git a/content/docs/meta.json b/content/docs/meta.json
index fcf40c1c..483df2ec 100644
--- a/content/docs/meta.json
+++ b/content/docs/meta.json
@@ -4,6 +4,7 @@
"getting-started",
"typography",
"primitives",
+ "ui",
"environment",
"ui-blocks",
"transitions",
diff --git a/content/docs/ui/index.mdx b/content/docs/ui/index.mdx
new file mode 100644
index 00000000..db0abffc
--- /dev/null
+++ b/content/docs/ui/index.mdx
@@ -0,0 +1,181 @@
+---
+title: UI
+description: shadcn-style primitives scripted on the Remotion timeline
+---
+
+The `ui` tier brings familiar shadcn components — Button, Input, Checkbox, Switch — into Remotion video. Instead of responding to mouse events, their interactions are **scripted on the timeline**: you declare what happens and when, and the component renders it as a deterministic pure function of `useCurrentFrame()`.
+
+No `useState`. No event handlers. No CSS transitions. Every pixel is a function of the current frame — which is exactly what Remotion's headless per-frame renderer requires.
+
+## What makes this different from regular shadcn
+
+In a browser, a button enters its loading state because the user clicked. In a video, it enters that state because you authored `{ at: 35, action: "loading" }`. The component looks identical; the wiring is completely different.
+
+This also means you get things that are impossible in a real UI: scrub backward through a form fill, play a button click at half speed, or loop a checkbox toggle indefinitely — all without any special setup.
+
+## Installation
+
+Each component installs via the standard shadcn CLI. The shared `remocn-ui` core installs automatically as a `registryDependencies` entry — you do not need to install it separately.
+
+```bash
+npx shadcn add @remocn/ui-button
+```
+
+This writes `components/remocn/ui-button.tsx` and `lib/remocn-ui/` to your project. Every `ui-*` component depends on the same `lib/remocn-ui/` core.
+
+## The `steps` timeline envelope
+
+Every `ui` primitive accepts a `steps` prop — an array of `Step` objects that describe what the component does and when.
+
+```ts
+interface Step<A extends string = string, V = unknown> {
+ /** Sequence-local frame at which this step begins. */
+ at: number;
+ /** Action name — component-specific (e.g. "hover" | "press" | "loading"). */
+ action: A;
+ /** Optional payload; meaning depends on the action. */
+ value?: V;
+ /** Frames to animate the transition. 0 = snap instantly. Omit = component default. */
+ duration?: number;
+}
+```
+
+A Button scripted through a full interaction looks like this:
+
+```tsx
+import { UIButton } from "@/components/remocn/ui-button";
+
+export const Scene = () => (
+ <UIButton
+ label="Continue"
+ steps={[
+ { at: 10, action: "hover" },
+ { at: 25, action: "press" },
+ { at: 35, action: "loading" },
+ { at: 70, action: "success" },
+ ]}
+ />
+);
+```
+
+The `at` value is always a **Sequence-local authored frame** — the frame number as you write it. If the component is inside a `<Sequence from={30}>`, Remotion shifts the frame counter automatically; `at: 10` still means "10 frames into this Sequence."
+
+## How the fold works
+
+Internally, every `ui` primitive calls `useTimelineState` from `lib/remocn-ui/timeline.ts`. This hook folds the `steps` array into two things:
+
+- **`state`** — the resolved logical state at the current frame (e.g. `{ phase: "loading" }`). This is the settled truth: what the component *is* right now.
+- **`progressOf(action)`** — a 0–1 progress value for the currently in-flight animation window of a given action. This is for driving the animation itself.
+
+```ts
+const { state, progressOf } = useTimelineState(steps, defaultState, reducer, durationDefaults);
+
+// state.phase tells you what the button IS (settled)
+// progressOf("hover") tells you how far into the hover animation you are (in-flight)
+```
+
+### The single fold invariant
+
+<Note>
+`progressOf(action)` is in-flight animation only. Once an animation window ends, `progressOf` returns 0 — it does not hold at 1. **Settled visual values must always be derived from `state`, not from `progressOf`.**
+</Note>
+
+This matters most for persistent visuals. A checkbox that has been checked should keep its checkmark drawn at frame 200, long after the 12-frame `check` animation finished. The correct pattern:
+
+```tsx
+// Good: settled truth from state, animation from progressOf
+const drawProgress = active.some(e => e.step.action === "check")
+ ? progressOf("check")
+ : active.some(e => e.step.action === "uncheck")
+ ? 1 - progressOf("uncheck")
+ : state.checked ? 1 : 0; // <-- this line keeps the mark drawn after the window closes
+
+// Bad: reading progressOf alone — the mark flashes away once the animation ends
+const drawProgress = progressOf("check");
+```
+
+### Concurrent animation tracks
+
+`progressOf` returns a **per-action** progress value, so two animations can run at the same time. A Button can crossfade its spinner into a checkmark while the checkmark's background also animates. An Input can reveal characters while the focus ring is still settling.
+
+```tsx
+// Loading → success crossfade: both tracks are live simultaneously
+const spinnerOpacity = 1 - progressOf("success");
+const checkmarkOpacity = progressOf("success");
+const loadingRingProgress = progressOf("loading");
+```
+
+A single scalar `progress` value could not express this. The per-action tracks are why `useTimelineState` returns a function rather than a number.
+
+### `duration: 0` snaps
+
+A step with `duration: 0` (or whose action has a default duration of 0) updates the logical `state` at frame `at` with no animation window. `progressOf` will never return a non-zero value for it. Use this for instantaneous state changes that need no visual transition.
+
+### The `speed` prop
+
+Every `ui` primitive accepts a `speed` prop (default `1`). The fold scales the **playhead** by `speed`, not the authored step times. A step at `{ at: 30 }` with `speed: 2` fires at render frame 15 (`effectiveFrame = 15 * 2 = 30`). The component preview wires this to the shared speed slider automatically.
+
+## Theming
+
+The `ui` tier uses a JS theme object with stock shadcn token names. Values are concrete oklch strings — not CSS custom properties.
+
+```ts
+import type { RemocnTheme } from "@/lib/remocn-ui";
+
+// All tokens match shadcn's default neutral palette out of the box
+const myTheme: Partial<RemocnTheme> = {
+ primary: "oklch(0.55 0.2 250)", // override just what you need
+ radius: 6,
+};
+```
+
+### `RemocnUIProvider`
+
+Wrap your composition (or a subtree) in `RemocnUIProvider` to set a theme and/or mode for all nested `ui` primitives:
+
+```tsx
+import { RemocnUIProvider } from "@/lib/remocn-ui";
+
+export const Scene = () => (
+ <RemocnUIProvider mode="dark" theme={{ primary: "oklch(0.6 0.22 260)" }}>
+ <UIButton label="Continue" steps={[{ at: 10, action: "hover" }]} />
+ <UICheckbox label="Remember me" steps={[{ at: 30, action: "check" }]} />
+ </RemocnUIProvider>
+);
+```
+
+Token resolution order (highest wins): per-component `theme` prop > `RemocnUIProvider` theme > `defaultLightTheme` / `defaultDarkTheme` per `mode`. The `mode` prop on a component wins over `RemocnUIProvider`'s `mode`.
+
+Available exports from `lib/remocn-ui`:
+
+| Export | Type | Description |
+|---|---|---|
+| `RemocnUIProvider` | Component | Context provider for theme and mode |
+| `useRemocnTheme` | Hook | Resolves the active theme inside a component |
+| `defaultLightTheme` | `RemocnTheme` | Stock shadcn neutral light palette |
+| `defaultDarkTheme` | `RemocnTheme` | Stock shadcn neutral dark palette |
+| `RemocnTheme` | Interface | Full token shape with `radius: number` |
+
+### Animated colors require concrete JS values
+
+<Warning>
+CSS custom properties (`var(--primary)`) work for **static** styling only. Remotion's headless per-frame renderer cannot resolve `var(...)` for JS interpolation. If you pass `var(--primary)` as an animated token, `parseColor` will warn in dev mode and fall back to the JS default theme value — not your CSS override.
+
+To override an animated color, pass a concrete oklch, hex, or rgb value via the `theme` prop or `RemocnUIProvider`. Static colors (borders, backgrounds that never animate) can safely use `var()` in `style` props.
+</Warning>
+
+A project whose `:root` overrides `--primary` will see static elements pick up the CSS variable correctly, but animated transitions (hover fades, press darkening) will use the JS theme default. The defaults match stock shadcn, so unless you have custom colors, you will not notice the difference — but if you do have custom colors, supply them through the JS theme.
+
+## Core library exports
+
+Installing any `@remocn/ui-*` component also installs `lib/remocn-ui/` with these modules:
+
+| Module | Key exports |
+|---|---|
+| `timeline.ts` | `useTimelineState`, `framesFor`, `revealCount` |
+| `theme.ts` | `RemocnUIProvider`, `useRemocnTheme`, `defaultLightTheme`, `defaultDarkTheme` |
+| `color.ts` | `mixOklch`, `parseColor`, `oklchToRgb`, `rgbToOklch`, `toCss` |
+| `motion.ts` | `easings`, `springs` |
+| `types.ts` | `Step`, `TimelineState` |
+
+You can import from `@/lib/remocn-ui` (the barrel) or from the individual module paths.
diff --git a/content/docs/ui/meta.json b/content/docs/ui/meta.json
new file mode 100644
index 00000000..a2c78775
--- /dev/null
+++ b/content/docs/ui/meta.json
@@ -0,0 +1,5 @@
+{
+ "title": "UI",
+ "collapsible": false,
+ "pages": ["index"]
+}
diff --git a/package.json b/package.json
index 88f019ac..246ebb24 100644
--- a/package.json
+++ b/package.json
@@ -25,6 +25,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
+ "culori": "^4.0.1",
"date-fns": "^4.1.0",
"embla-carousel-react": "^8.6.0",
"fumadocs-core": "^16.7.10",
@@ -57,6 +58,7 @@
"devDependencies": {
"@biomejs/biome": "2.2.0",
"@tailwindcss/postcss": "^4",
+ "@types/culori": "^4.0.0",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
diff --git a/registry.json b/registry.json
index 33577044..3e17d8ff 100644
--- a/registry.json
+++ b/registry.json
@@ -744,6 +744,60 @@
"target": "components/remocn/github-stars.tsx"
}
]
+ },
+ {
+ "name": "remocn-ui",
+ "type": "registry:lib",
+ "title": "remocn UI Core",
+ "description": "Shared timeline-fold hook, theme context, and color math for remocn UI primitives.",
+ "dependencies": ["remotion", "culori"],
+ "files": [
+ {
+ "path": "registry/remocn/ui-core/timeline.ts",
+ "type": "registry:lib",
+ "target": "lib/remocn-ui/timeline.ts"
+ },
+ {
+ "path": "registry/remocn/ui-core/theme.ts",
+ "type": "registry:lib",
+ "target": "lib/remocn-ui/theme.ts"
+ },
+ {
+ "path": "registry/remocn/ui-core/color.ts",
+ "type": "registry:lib",
+ "target": "lib/remocn-ui/color.ts"
+ },
+ {
+ "path": "registry/remocn/ui-core/motion.ts",
+ "type": "registry:lib",
+ "target": "lib/remocn-ui/motion.ts"
+ },
+ {
+ "path": "registry/remocn/ui-core/types.ts",
+ "type": "registry:lib",
+ "target": "lib/remocn-ui/types.ts"
+ },
+ {
+ "path": "registry/remocn/ui-core/index.ts",
+ "type": "registry:lib",
+ "target": "lib/remocn-ui/index.ts"
+ }
+ ]
+ },
+ {
+ "name": "ui-button",
+ "type": "registry:component",
+ "title": "UI Button",
+ "description": "A shadcn-style button whose hover/press/loading/success states are scripted on the Remotion timeline.",
+ "dependencies": ["remotion"],
+ "registryDependencies": ["remocn-ui"],
+ "files": [
+ {
+ "path": "registry/remocn/ui-button/index.tsx",
+ "type": "registry:component",
+ "target": "components/remocn/ui-button.tsx"
+ }
+ ]
}
]
}
diff --git a/registry/remocn/ui-button/index.tsx b/registry/remocn/ui-button/index.tsx
new file mode 100644
index 00000000..dd0e91b1
--- /dev/null
+++ b/registry/remocn/ui-button/index.tsx
@@ -0,0 +1,72 @@
+"use client";
+
+import { interpolate, spring, useCurrentFrame, useVideoConfig } from "remotion";
+import { springs, useRemocnTheme } from "@/lib/remocn-ui";
+
+export interface UIButtonProps {
+ label?: string;
+ mode?: "light" | "dark";
+ speed?: number;
+ className?: string;
+}
+
+export function UIButton({
+ label = "Continue",
+ mode,
+ speed = 1,
+ className,
+}: UIButtonProps) {
+ const frame = useCurrentFrame() * speed;
+ const { fps } = useVideoConfig();
+ const theme = useRemocnTheme(undefined, mode);
+
+ const enter = spring({
+ frame,
+ fps,
+ config: springs.soft,
+ durationInFrames: 14,
+ });
+ const opacity = interpolate(enter, [0, 1], [0, 1], {
+ extrapolateRight: "clamp",
+ });
+ const translateY = interpolate(enter, [0, 1], [8, 0]);
+
+ return (
+ <div
+ style={{
+ position: "absolute",
+ inset: 0,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ background: theme.background,
+ fontFamily:
+ "var(--font-geist-sans), -apple-system, BlinkMacSystemFont, sans-serif",
+ }}
+ >
+ <button
+ type="button"
+ className={className}
+ style={{
+ opacity,
+ transform: `translateY(${translateY}px)`,
+ display: "inline-flex",
+ alignItems: "center",
+ justifyContent: "center",
+ height: 40,
+ padding: "0 20px",
+ fontSize: 15,
+ fontWeight: 500,
+ letterSpacing: "-0.01em",
+ color: theme.primaryForeground,
+ background: theme.primary,
+ border: "none",
+ borderRadius: theme.radius,
+ cursor: "pointer",
+ }}
+ >
+ {label}
+ </button>
+ </div>
+ );
+}
diff --git a/registry/remocn/ui-core/__tests__/README.md b/registry/remocn/ui-core/__tests__/README.md
new file mode 100644
index 00000000..23a30362
--- /dev/null
+++ b/registry/remocn/ui-core/__tests__/README.md
@@ -0,0 +1,82 @@
+# `remocn-ui` core — verification tests (Iteration 1)
+
+Pure / deterministic verification for the `ui` tier core lib
+(`registry/remocn/ui-core/`). Covers the hand-rolled OKLCH color math and the
+timeline fold semantics. No React / Remotion render required.
+
+## How to run
+
+The repo uses **Bun**, which has a built-in test runner — runs TypeScript
+natively, no test-framework dep.
+
+```bash
+bun install # color.ts now imports `culori`
+bun test registry/remocn/ui-core/__tests__
+```
+
+`color.ts` was rewritten to wrap the **`culori`** package, which is already
+declared in `package.json` (`culori` + `@types/culori`). Run `bun install`
+first so it lands in `node_modules`, or `color.test.ts` will fail to resolve the
+import. The test runner itself still needs nothing: these tests import
+`bun:test`, not `vitest`/`jest`, so no test script or test-framework dep is
+added to `package.json`.
+
+> If you would rather standardize on a framework later, the lightest path that
+> needs a dep is **vitest**: `bunx vitest run registry/remocn/ui-core` after
+> `bun add -d vitest`. The test bodies are framework-agnostic (`describe/it/
+> expect`); only the top `import { ... } from "bun:test"` line would change to
+> `from "vitest"`. Not required for Iteration 1.
+
+## What is covered
+
+- `color.test.ts` — imports the REAL `color.ts` (pure, no remotion). Now a
+ `culori` wrapper exposing culori's NATIVE shapes/scales: `Rgb` objects are
+ `{ mode:"rgb", r, g, b, alpha }` with channels in **0..1** (NOT 0..255),
+ `Oklch` objects are `{ mode:"oklch", l, c, h, alpha? }` (lowercase l/c/h,
+ achromatic hue normalized to `0`), and `rgbToOklch` takes an `Rgb` OBJECT.
+ Assertions are PROPERTY-BASED and tolerance-based in the 0..1 scale
+ (`TOL = 0.01 ≈ 2/255`), immune to culori's 8-bit rounding / version drift:
+ - `mixOklch` endpoints (`t=0`≈a, `t=1`≈b within `TOL`, alpha within 0.01).
+ `mixOklch` still returns an inline CSS string; `rgbOf` parses culori's
+ `formatRgb` output (0..255 ints) back to 0..1 for comparison.
+ - OKLCH midpoint ≠ naive sRGB lerp: black↔[email protected] is neutral (`r≈g≈b`) and
+ clears the naive 0..1 sRGB midpoint `0.5` by a real margin (`>0.039`,
+ i.e. >10/255), and equals the module's own `oklchToRgb(0.5,0,0)`
+ (self-consistent, no magic number).
+ - shortest-arc hue (350↔10 → ~0/360, not ~180), neutral-hold (gray↔gray stays
+ gray; gray↔chromatic carries the chromatic hue). Hue read via
+ `rgbToOklch({ mode:"rgb", r, g, b })`.
+ - `oklchToRgb` anchors: only the gamut corners are checked (`oklch(1 0 0)`→
+ white `r≈g≈b≈1`, `oklch(0 0 0)`→black `r≈g≈b≈0`); mid-lightness neutrals
+ asserted as properties (neutral + monotonic, thresholds in 0..1), never
+ pinned.
+ - theme-override AC (§6): `oklchToRgb(0.205,0,0)` ≈ `parseColor("oklch(0.205
+ 0 0)")` within `TOL` — value computed from the module itself, immune to
+ culori version drift.
+ - `rgb`/`oklch` round-trip via `rgbToOklch(oklchToRgb(...))` taking the `Rgb`
+ object (l/c/h recovered within tol; achromatic hue normalized to `0`),
+ `parseColor` formats (hex/rgb/oklch + alpha in 0..1, `var()` and unparseable
+ → black-sentinel `{ mode:"rgb", r:0, g:0, b:0, alpha:1 }` no throw, default
+ alpha 1), `toCss` (culori `formatRgb` LEGACY comma syntax with 0..255 int
+ channels: `rgb(255, 128, 0)` opaque, `rgba(10, 20, 30, 0.5)` when alpha < 1,
+ plus a re-parse round-trip guard), `mixOklch` alpha interpolation.
+- `timeline.test.ts` — `framesFor` / `revealCount` as exact spec mirrors, plus a
+ pure replica of the `useTimelineState` fold (the only impure line,
+ `useCurrentFrame()`, is injected as a `raw` arg) to assert: speed contract
+ (`{at:30}` fires at render frame 15 when `speed=2`), active-window
+ `[at, at+dur)` boundaries, `progressOf` in-flight-only flash-bug guard,
+ `duration:0` snap, most-recent-active resolution.
+
+## Determinism grep checklist (run manually; must print NOTHING)
+
+The `ui` tier contract is "pure function of `useCurrentFrame()`" (plan §6). No
+React state, no DOM events, no wall-clock, no randomness anywhere in the tier
+source. Verify with:
+
+```bash
+grep -nE "useState|useEffect|onClick|onChange|addEventListener|Date\.now|Math\.random" \
+ registry/remocn/ui-*/index.tsx registry/remocn/ui-core/*.ts
+```
+
+Expected: no output (exit code 1). Any match is a determinism violation.
+(Verified clean on the source as of Iteration 1.)
diff --git a/registry/remocn/ui-core/__tests__/color.test.ts b/registry/remocn/ui-core/__tests__/color.test.ts
new file mode 100644
index 00000000..4168ac49
--- /dev/null
+++ b/registry/remocn/ui-core/__tests__/color.test.ts
@@ -0,0 +1,387 @@
+/**
+ * Verification tests for the OKLCH <-> sRGB color helpers in
+ * registry/remocn/ui-core/color.ts.
+ *
+ * color.ts is now a thin wrapper over the `culori` package, and it exposes
+ * culori's NATIVE shapes and scales:
+ * - `Rgb` objects are mode-tagged `{ mode: "rgb", r, g, b, alpha }` with
+ * channels in 0..1 (NOT 0..255).
+ * - `Oklch` objects are `{ mode: "oklch", l, c, h, alpha? }` with lowercase
+ * l/c/h; achromatic hue is normalized to 0.
+ * - `rgbToOklch` takes a culori `Rgb` OBJECT (not 3 scalars).
+ * - `toCss` uses culori's `formatRgb`, which emits LEGACY comma syntax with
+ * 0..255 integer channels: `"rgb(255, 128, 0)"` / `"rgba(255, 128, 0, 0.5)"`.
+ *
+ * culori must be installed before these run:
+ *
+ * bun install # pulls culori + @types/culori
+ * bun test registry/remocn/ui-core/__tests__
+ *
+ * These tests are deliberately PROPERTY-BASED, not pinned to magic RGB numbers.
+ * culori uses its own matrices and gamut-mapping (clampChroma), so exact
+ * channels can shift by a hair between culori versions. Instead we assert the
+ * INVARIANTS that must hold regardless of culori's rounding: endpoint identity,
+ * perceptual (non-sRGB) midpoint, shortest-arc hue, neutral-hold, round-trip,
+ * and alpha handling. All channel tolerances are expressed in the 0..1 scale
+ * (~0.01 ~= 2/255), immune to culori's 8-bit quantization.
+ *
+ * Where an exact value is genuinely useful (theme-override AC), we compute the
+ * expected from the module's OWN oklchToRgb/parseColor so the test is
+ * self-consistent and immune to culori version drift.
+ *
+ * These are PURE (no React / no Remotion), so they import the real module.
+ */
+
+import { describe, expect, it } from "bun:test";
+import {
+ mixOklch,
+ oklchToRgb,
+ parseColor,
+ rgbToOklch,
+ toCss,
+} from "../color";
+
+// --- helpers ---------------------------------------------------------------
+
+/**
+ * Parse culori `formatRgb` output -- legacy comma syntax with 0..255 integer
+ * channels -- back into a 0..1 culori-shaped Rgb so it compares directly
+ * against parseColor/oklchToRgb output (which are also 0..1).
+ * "rgb(255, 128, 0)" -> { r: 1, g: 0.502, b: 0, alpha: 1 }
+ * "rgba(10, 20, 30, 0.5)" -> { r: 0.039, g: 0.078, b: 0.118, alpha: 0.5 }
+ * Robust to either comma- or space-separated forms just in case.
+ */
+function rgbOf(css: string): { r: number; g: number; b: number; alpha: number } {
+ const inner = css.slice(css.indexOf("(") + 1, css.lastIndexOf(")"));
+ const parts = inner
+ .replace(/\//g, " ")
+ .replace(/,/g, " ")
+ .trim()
+ .split(/\s+/)
+ .filter(Boolean)
+ .map((n) => Number.parseFloat(n));
+ const [r255, g255, b255, a] = parts;
+ return {
+ r: r255 / 255,
+ g: g255 / 255,
+ b: b255 / 255,
+ alpha: a === undefined ? 1 : a,
+ };
+}
+
+/** Assert each RGB channel (0..1) of two colors is within `tol`. */
+function expectRgbClose(
+ got: { r: number; g: number; b: number },
+ want: { r: number; g: number; b: number },
+ tol: number,
+) {
+ expect(Math.abs(got.r - want.r)).toBeLessThanOrEqual(tol);
+ expect(Math.abs(got.g - want.g)).toBeLessThanOrEqual(tol);
+ expect(Math.abs(got.b - want.b)).toBeLessThanOrEqual(tol);
+}
+
+// Channel tolerance in the 0..1 scale: ~2/255, covers clampChroma + 8-bit
+// rounding on both the interpolate and the direct-convert paths.
+const TOL = 0.01;
+
+const BLACK = "oklch(0 0 0)";
+const WHITE = "oklch(1 0 0)";
+
+// --- mixOklch endpoints ----------------------------------------------------
+// Property: a mix at t=0 IS the first color, at t=1 IS the second color.
+
+describe("mixOklch endpoints", () => {
+ const a = "oklch(0.5 0.12 250)";
+ const b = "oklch(0.7 0.15 140)";
+
+ it("returns ~a at t=0 (within tol of parseColor(a))", () => {
+ expectRgbClose(rgbOf(mixOklch(a, b, 0)), parseColor(a), TOL);
+ });
+
+ it("returns ~b at t=1 (within tol of parseColor(b))", () => {
+ expectRgbClose(rgbOf(mixOklch(a, b, 1)), parseColor(b), TOL);
+ });
+
+ it("preserves alpha at the endpoints (within 0.01)", () => {
+ const aa = "oklch(0.5 0.12 250 / 40%)";
+ const bb = "oklch(0.7 0.15 140 / 80%)";
+ expect(Math.abs(rgbOf(mixOklch(aa, bb, 0)).alpha - 0.4)).toBeLessThanOrEqual(0.01);
+ expect(Math.abs(rgbOf(mixOklch(aa, bb, 1)).alpha - 0.8)).toBeLessThanOrEqual(0.01);
+ });
+});
+
+// --- midpoint is the OKLCH midpoint, NOT the naive sRGB midpoint -----------
+// Property (not a pinned value): mixing black<->white in OKLCH at t=0.5 lands
+// on the PERCEPTUAL midpoint, which is meaningfully different from the naive
+// sRGB lerp (0.5 in the 0..1 scale). It must also stay neutral (r==g==b).
+
+describe("mixOklch midpoint (perceptual, not naive sRGB lerp)", () => {
+ it("black<->white at t=0.5 is neutral and clearly off the sRGB midpoint 0.5", () => {
+ const mid = rgbOf(mixOklch(BLACK, WHITE, 0.5));
+ // Neutral: no phantom hue swept through the achromatic axis. Compared in
+ // 0..1 with TOL (formatRgb rounds to ints, so equal channels stay equal).
+ expect(Math.abs(mid.r - mid.g)).toBeLessThanOrEqual(TOL);
+ expect(Math.abs(mid.g - mid.b)).toBeLessThanOrEqual(TOL);
+ // A naive sRGB lerp at t=0.5 would land at ~0.5 (0..1). The OKLCH
+ // (perceptual) midpoint is well clear of that by a real margin -> proves we
+ // are NOT lerping in sRGB. Assert the GAP magnitude, never the exact value.
+ // 10/255 ~= 0.039 in the 0..1 scale.
+ expect(Math.abs(mid.g - 0.5)).toBeGreaterThan(0.039);
+ });
+
+ it("matches the module's own oklchToRgb(0.5,0,0) (self-consistent, no magic number)", () => {
+ // Both routes (interpolate->clampChroma->rgb vs oklchToRgb) must agree on
+ // the neutral L=0.5 point. Computed from the module, so it tracks culori.
+ expectRgbClose(rgbOf(mixOklch(BLACK, WHITE, 0.5)), oklchToRgb(0.5, 0, 0), TOL);
+ });
+});
+
+// --- shortest-arc hue ------------------------------------------------------
+// Property: culori's fixupHueShorter takes the SHORT way around the hue circle.
+// Hues straddling the 0/360 seam (350 <-> 10) mix to ~0/360, never ~180.
+
+describe("mixOklch shortest-arc hue", () => {
+ it("h=350 <-> h=10 midpoint lands near 0/360, not ~180 (short way)", () => {
+ const a = "oklch(0.6 0.12 350)";
+ const b = "oklch(0.6 0.12 10)";
+ const mid = rgbOf(mixOklch(a, b, 0.5));
+ const hue = rgbToOklch({ mode: "rgb", r: mid.r, g: mid.g, b: mid.b }).h;
+ // Short arc -> ~0deg. Accept the wraparound band [345,360] U [0,15];
+ // reject the long-way ~180.
+ const nearZero = hue <= 15 || hue >= 345;
+ expect(nearZero).toBe(true);
+ expect(Math.abs(hue - 180)).toBeGreaterThan(120);
+ });
+});
+
+// --- neutral-hold ----------------------------------------------------------
+// Property: mixing two grays yields a gray (no phantom hue), and mixing a gray
+// with a chromatic color carries the chromatic hue rather than the gray's
+// meaningless hue.
+
+describe("mixOklch holds hue for neutrals (no phantom hue)", () => {
+ it("midpoint of two grays stays neutral (r==g==b within tol)", () => {
+ const a = "oklch(0.3 0 0)";
+ const b = "oklch(0.8 0 0)";
+ const mid = rgbOf(mixOklch(a, b, 0.5));
+ expect(Math.abs(mid.r - mid.g)).toBeLessThanOrEqual(TOL);
+ expect(Math.abs(mid.g - mid.b)).toBeLessThanOrEqual(TOL);
+ });
+
+ it("gray<->chromatic near the chromatic end carries that hue (within ~20deg)", () => {
+ const gray = "oklch(0.6 0 0)";
+ const blue = "oklch(0.6 0.12 250)";
+ const near = rgbOf(mixOklch(gray, blue, 0.9));
+ const hue = rgbToOklch({ mode: "rgb", r: near.r, g: near.g, b: near.b }).h;
+ // Hue distance on the circle.
+ const dh = Math.abs(((hue - 250 + 540) % 360) - 180);
+ expect(dh).toBeLessThan(20);
+ });
+});
+
+// --- oklchToRgb anchors ----------------------------------------------------
+// Only the TRUE endpoints (pure black / pure white) are pinned, since those are
+// gamut corners every correct implementation must hit exactly. In the 0..1
+// scale white is r==g==b==1 and black is r==g==b==0. Mid-lightness neutrals are
+// asserted as PROPERTIES (neutral + ordered), not pinned values.
+
+describe("oklchToRgb anchors and neutral properties", () => {
+ it("oklch(1 0 0) -> pure white (r==g==b==1)", () => {
+ const w = oklchToRgb(1, 0, 0);
+ expectRgbClose(w, { r: 1, g: 1, b: 1 }, TOL);
+ expect(w.alpha ?? 1).toBe(1);
+ });
+
+ it("oklch(0 0 0) -> pure black (r==g==b==0)", () => {
+ const k = oklchToRgb(0, 0, 0);
+ expectRgbClose(k, { r: 0, g: 0, b: 0 }, TOL);
+ expect(k.alpha ?? 1).toBe(1);
+ });
+
+ it("neutral oklch inputs (C=0) produce gray (r==g==b)", () => {
+ for (const L of [0.205, 0.5, 0.985]) {
+ const rgb = oklchToRgb(L, 0, 0);
+ expect(Math.abs(rgb.r - rgb.g)).toBeLessThanOrEqual(TOL);
+ expect(Math.abs(rgb.g - rgb.b)).toBeLessThanOrEqual(TOL);
+ }
+ });
+
+ it("neutral lightness is monotonic: darker L -> darker gray", () => {
+ const dark = oklchToRgb(0.205, 0, 0).r;
+ const mid = oklchToRgb(0.5, 0, 0).r;
+ const light = oklchToRgb(0.985, 0, 0).r;
+ expect(dark).toBeLessThan(mid);
+ expect(mid).toBeLessThan(light);
+ // Near-corner sanity without pinning: dark neutral is genuinely dark,
+ // light neutral is genuinely light (0..1 scale; 80/255 ~= 0.314,
+ // 230/255 ~= 0.902).
+ expect(dark).toBeLessThan(0.314);
+ expect(light).toBeGreaterThan(0.902);
+ });
+});
+
+// --- theme-override AC (plan §6) -------------------------------------------
+// AC: a theme override "primary" oklch value resolves to a concrete RGB used in
+// the inline style. We assert SELF-CONSISTENCY between the two ways the module
+// can produce that RGB (oklchToRgb vs parseColor of the oklch string) rather
+// than hard-coding a culori-version-specific value. This is the (a) path from
+// the brief; no TODO/magic number needed.
+
+describe("theme-override primary resolves consistently", () => {
+ it("oklchToRgb(0.205,0,0) ~= parseColor('oklch(0.205 0 0)')", () => {
+ const viaArgs = oklchToRgb(0.205, 0, 0);
+ const viaParse = parseColor("oklch(0.205 0 0)");
+ expectRgbClose(viaParse, viaArgs, TOL);
+ });
+});
+
+// --- round trip rgbToOklch(oklchToRgb(...)) --------------------------------
+// Property: converting OKLCH -> sRGB -> OKLCH recovers the original within
+// 8-bit quantization. Catches a transposed matrix / atan2 sign error.
+// rgbToOklch now takes the Rgb OBJECT directly, and returns lowercase l/c/h.
+
+describe("oklch <-> rgb round-trip (in-gamut values)", () => {
+ const cases: Array<[number, number, number]> = [
+ [0.6, 0.1, 30],
+ [0.5, 0.12, 250],
+ [0.7, 0.15, 140],
+ ];
+ for (const [L, C, h] of cases) {
+ it(`L=${L} C=${C} h=${h} survives a round trip`, () => {
+ const rgb = oklchToRgb(L, C, h);
+ const back = rgbToOklch(rgb);
+ expect(Math.abs(back.l - L)).toBeLessThan(0.02);
+ expect(Math.abs((back.c ?? 0) - C)).toBeLessThan(0.02);
+ // Hue compared on the circle.
+ const dh = Math.abs((((back.h ?? 0) - h + 540) % 360) - 180);
+ expect(dh).toBeLessThan(2);
+ });
+ }
+
+ it("achromatic round-trip normalizes hue to 0 (not NaN/undefined)", () => {
+ // culori leaves hue undefined for achromatic; the module normalizes to 0.
+ const back = rgbToOklch({ mode: "rgb", r: 0.5, g: 0.5, b: 0.5 });
+ expect(back.h).toBe(0);
+ expect(Number.isNaN(back.h)).toBe(false);
+ expect(back.c ?? 0).toBeLessThan(0.001);
+ });
+});
+
+// --- parseColor format coverage --------------------------------------------
+// parseColor returns { mode: "rgb", r, g, b, alpha } with channels in 0..1.
+
+describe("parseColor formats", () => {
+ it("parses #rrggbb hex", () => {
+ const c = parseColor("#ff8000");
+ // 0xff/255=1, 0x80/255~=0.502, 0x00/255=0
+ expectRgbClose(c, { r: 1, g: 0x80 / 255, b: 0 }, TOL);
+ expect(c.mode).toBe("rgb");
+ expect(c.alpha).toBe(1);
+ });
+
+ it("parses #rgb shorthand hex", () => {
+ const c = parseColor("#f80");
+ // #f80 -> #ff8800: 1, 0x88/255~=0.533, 0
+ expectRgbClose(c, { r: 1, g: 0x88 / 255, b: 0 }, TOL);
+ });
+
+ it("parses rgb() space-separated", () => {
+ expectRgbClose(
+ parseColor("rgb(10 20 30)"),
+ { r: 10 / 255, g: 20 / 255, b: 30 / 255 },
+ TOL,
+ );
+ });
+
+ it("parses rgb() comma-separated", () => {
+ expectRgbClose(
+ parseColor("rgb(10, 20, 30)"),
+ { r: 10 / 255, g: 20 / 255, b: 30 / 255 },
+ TOL,
+ );
+ });
+
+ it("parses oklch() with a percent alpha (alpha ~= 0.10)", () => {
+ const c = parseColor("oklch(1 0 0 / 10%)");
+ expect(Math.abs(c.alpha! - 0.1)).toBeLessThanOrEqual(0.01);
+ });
+
+ it("defaults alpha to 1 when no alpha is present", () => {
+ expect(parseColor("rgb(10 20 30)").alpha).toBe(1);
+ });
+
+ it("var(...) does not throw and returns the black sentinel", () => {
+ // Documented contract: the animated path cannot resolve var() under
+ // Remotion's per-frame render; falls back to black rather than throwing.
+ expect(() => parseColor("var(--primary)")).not.toThrow();
+ expect(parseColor("var(--primary)")).toEqual({
+ mode: "rgb",
+ r: 0,
+ g: 0,
+ b: 0,
+ alpha: 1,
+ });
+ });
+
+ it("unparseable input falls back to the black sentinel", () => {
+ expect(parseColor("not-a-color")).toEqual({
+ mode: "rgb",
+ r: 0,
+ g: 0,
+ b: 0,
+ alpha: 1,
+ });
+ });
+});
+
+// --- toCss -----------------------------------------------------------------
+// toCss uses culori's formatRgb: LEGACY comma syntax, 0..255 integer channels,
+// alpha emitted as rgba(...) only when alpha < 1.
+
+describe("toCss (culori formatRgb output)", () => {
+ it('emits legacy "rgb(r, g, b)" with 0..255 ints when opaque', () => {
+ // 1 -> 255, 0.5 -> round(127.5)=128, 0 -> 0
+ expect(toCss({ mode: "rgb", r: 1, g: 0.5, b: 0, alpha: 1 })).toBe(
+ "rgb(255, 128, 0)",
+ );
+ });
+
+ it("emits opaque rgb(...) when alpha is omitted", () => {
+ // formatRgb treats undefined alpha as opaque.
+ expect(toCss({ mode: "rgb", r: 0, g: 0, b: 0 } as never)).toBe("rgb(0, 0, 0)");
+ });
+
+ it('emits legacy "rgba(r, g, b, a)" when alpha < 1', () => {
+ expect(toCss({ mode: "rgb", r: 10 / 255, g: 20 / 255, b: 30 / 255, alpha: 0.5 })).toBe(
+ "rgba(10, 20, 30, 0.5)",
+ );
+ });
+
+ it("round-trips through culori: toCss output re-parses to the same channels", () => {
+ // Structural guard independent of the exact format string: whatever
+ // formatRgb emits must parse back to the same 0..1 channels (within 8-bit).
+ const want = { r: 1, g: 0.5, b: 0 };
+ const reparsed = parseColor(toCss({ mode: "rgb", ...want, alpha: 1 }));
+ expectRgbClose(reparsed, want, TOL);
+ expect(reparsed.alpha).toBe(1);
+ });
+
+ it("carries alpha through the re-parse when alpha < 1", () => {
+ const reparsed = parseColor(
+ toCss({ mode: "rgb", r: 10 / 255, g: 20 / 255, b: 30 / 255, alpha: 0.5 }),
+ );
+ expect(Math.abs(reparsed.alpha! - 0.5)).toBeLessThanOrEqual(0.01);
+ });
+});
+
+// --- alpha interpolation through mixOklch ----------------------------------
+
+describe("mixOklch interpolates alpha", () => {
+ it("midpoint of two alpha-bearing colors averages their alpha", () => {
+ const a = "oklch(0.5 0.12 250 / 20%)";
+ const b = "oklch(0.5 0.12 250 / 80%)";
+ const mid = rgbOf(mixOklch(a, b, 0.5));
+ // Equal L/C/h so only alpha moves; midpoint alpha ~= 0.5.
+ expect(Math.abs(mid.alpha - 0.5)).toBeLessThanOrEqual(0.02);
+ });
+});
diff --git a/registry/remocn/ui-core/__tests__/timeline.test.ts b/registry/remocn/ui-core/__tests__/timeline.test.ts
new file mode 100644
index 00000000..1329bd1a
--- /dev/null
+++ b/registry/remocn/ui-core/__tests__/timeline.test.ts
@@ -0,0 +1,331 @@
+/**
+ * Verification tests for the timeline FOLD SEMANTICS.
+ *
+ * Scope: registry/remocn/ui-core/timeline.ts — framesFor, revealCount, and the
+ * pure fold logic inside useTimelineState (speed contract, active windows,
+ * progressOf in-flight-only, duration:0 snap).
+ *
+ * Runner: Bun's built-in test runner.
+ * bun test registry/remocn/ui-core/__tests__
+ *
+ * --------------------------------------------------------------------------
+ * WHY THE FOLD IS REPLICATED HERE INSTEAD OF IMPORTED
+ * --------------------------------------------------------------------------
+ * `useTimelineState` is a React hook whose FIRST line is `useCurrentFrame()`
+ * from "remotion" — it cannot run outside a Remotion render tree, and even
+ * importing the module pulls the remotion runtime. `framesFor` and
+ * `revealCount` are pure but share that module.
+ *
+ * So we do BOTH:
+ * 1. Re-derive framesFor / revealCount as exact spec mirrors and assert their
+ * numeric contract (these formulas are trivially copyable and stable).
+ * 2. Replicate the documented pure fold ("foldTimeline" below) byte-for-byte
+ * from timeline.ts's algorithm, factoring out the single impure line
+ * (useCurrentFrame) into an injected `raw` frame. This lets us assert the
+ * speed contract, active-window math, and the progressOf flash-bug guard
+ * headlessly.
+ *
+ * MAINTENANCE CONTRACT: if timeline.ts's fold body changes, this replica MUST
+ * be updated in lockstep. The replica is annotated with the source line ranges
+ * it mirrors so a reviewer can diff them. The numeric expectations are the real
+ * verification value; the replica is the harness that lets us reach them
+ * without a Remotion render. The same expectations are ALSO encoded as the
+ * Player-level ACs in plan §6 (speed contract, settled-read persists) — see the
+ * cross-references on each test.
+ * --------------------------------------------------------------------------
+ */
+
+import { describe, expect, it } from "bun:test";
+
+// ===========================================================================
+// 1. framesFor / revealCount — exact spec mirrors of timeline.ts lines 5-19
+// ===========================================================================
+
+/** MIRROR of timeline.ts:framesFor (lines 5-7). */
+function framesFor(d: number | { seconds: number }, fps: number): number {
+ return typeof d === "number" ? d : Math.round(d.seconds * fps);
+}
+
+/** MIRROR of timeline.ts:revealCount (lines 10-19). */
+function revealCount(
+ localFrame: number,
+ fps: number,
+ len: number,
+ cps: number,
+): number {
+ const over = (len / cps) * fps;
+ if (over <= 0) return len;
+ return Math.max(0, Math.min(len, Math.floor((localFrame / over) * len)));
+}
+
+describe("framesFor", () => {
+ it("passes a raw frame number through unchanged", () => {
+ expect(framesFor(30, 30)).toBe(30);
+ });
+
+ it("converts {seconds} to rounded frames at fps", () => {
+ expect(framesFor({ seconds: 2 }, 30)).toBe(60);
+ expect(framesFor({ seconds: 0.5 }, 30)).toBe(15);
+ });
+
+ it("rounds fractional second->frame conversions", () => {
+ // 0.1s * 30fps = 3 exactly; 0.11s * 30 = 3.3 -> 3
+ expect(framesFor({ seconds: 0.11 }, 30)).toBe(3);
+ // 0.116s * 30 = 3.48 -> 3 ; 0.117 * 30 = 3.51 -> 4
+ expect(framesFor({ seconds: 0.117 }, 30)).toBe(4);
+ });
+});
+
+describe("revealCount (typewriter math)", () => {
+ // over = (len/cps)*fps. For len=5, cps=10, fps=30 => over = 0.5*30 = 15 frames
+ // to fully reveal 5 chars. count = floor((frame/15)*5).
+ it("reveals nothing at frame 0", () => {
+ expect(revealCount(0, 30, 5, 10)).toBe(0);
+ });
+
+ it("reveals proportionally mid-flight", () => {
+ // frame 6 of 15 => floor((6/15)*5) = floor(2) = 2
+ expect(revealCount(6, 30, 5, 10)).toBe(2);
+ // frame 9 => floor((9/15)*5)=floor(3)=3
+ expect(revealCount(9, 30, 5, 10)).toBe(3);
+ });
+
+ it("clamps to full length once the reveal window has elapsed", () => {
+ expect(revealCount(15, 30, 5, 10)).toBe(5);
+ expect(revealCount(999, 30, 5, 10)).toBe(5);
+ });
+
+ it("never goes negative for a negative localFrame", () => {
+ expect(revealCount(-50, 30, 5, 10)).toBe(0);
+ });
+
+ it("returns full length immediately when the window is non-positive", () => {
+ // len=0 => over=0 => guarded early-return of len (0). Also guards cps<=0.
+ expect(revealCount(0, 30, 0, 10)).toBe(0);
+ });
+});
+
+// ===========================================================================
+// 2. Pure fold replica — MIRROR of timeline.ts useTimelineState body
+// (lines 62-99), with the one impure line (useCurrentFrame) injected as
+// `raw`. Keep in lockstep with source.
+// ===========================================================================
+
+interface Step<A extends string = string, V = unknown> {
+ at: number;
+ action: A;
+ value?: V;
+ duration?: number;
+}
+
+function clamp01(t: number): number {
+ return Math.max(0, Math.min(1, t));
+}
+
+function foldTimeline<S, A extends string>(
+ raw: number, // injected useCurrentFrame() — MIRROR of timeline.ts line 62
+ steps: Step<A>[],
+ defaultState: S,
+ reducer: (draft: S, step: Step<A>) => S,
+ durationDefaults: Record<A, number>,
+ speed = 1,
+): {
+ state: S;
+ active: Array<{ step: Step<A>; progress: number }>;
+ progressOf: (action: A) => number;
+ frame: number;
+} {
+ const effectiveFrame = raw * speed; // line 63: SPEED CONTRACT
+
+ const ordered = steps // lines 67-70: stable sort by `at`, ties in array order
+ .map((step, index) => ({ step, index }))
+ .sort((a, b) => a.step.at - b.step.at || a.index - b.index)
+ .map((entry) => entry.step);
+
+ let state: S = { ...defaultState }; // line 72: shallow clone
+ const active: Array<{ step: Step<A>; progress: number }> = [];
+
+ for (const step of ordered) {
+ // lines 75-85
+ if (step.at <= effectiveFrame) {
+ state = reducer(state, step);
+ }
+ const dur = step.duration ?? durationDefaults[step.action];
+ const end = step.at + dur;
+ if (dur > 0 && step.at <= effectiveFrame && effectiveFrame < end) {
+ active.push({ step, progress: clamp01((effectiveFrame - step.at) / dur) });
+ }
+ }
+
+ const progressOf = (action: A): number => {
+ // lines 87-97: most-recent active step of `action`, else 0
+ let result = 0;
+ let bestAt = -Infinity;
+ for (const entry of active) {
+ if (entry.step.action === action && entry.step.at >= bestAt) {
+ bestAt = entry.step.at;
+ result = entry.progress;
+ }
+ }
+ return result;
+ };
+
+ return { state, active, progressOf, frame: effectiveFrame };
+}
+
+// --- speed contract --------------------------------------------------------
+
+describe("fold speed contract (plan §6 'Speed contract LIVE', R7)", () => {
+ type A = "go";
+ const dd: Record<A, number> = { go: 10 };
+ const steps: Step<A>[] = [{ at: 30, action: "go" }];
+ const reducer = (s: { fired: boolean }, _step: Step<A>) => ({ fired: true });
+
+ it("a step {at:30} is NOT yet active at render frame 14 when speed=2 (eff=28)", () => {
+ const r = foldTimeline(14, steps, { fired: false }, reducer, dd, 2);
+ expect(r.frame).toBe(28);
+ expect(r.state.fired).toBe(false);
+ expect(r.active.length).toBe(0);
+ });
+
+ it("a step {at:30} becomes active at render frame 15 when speed=2 (eff=30)", () => {
+ const r = foldTimeline(15, steps, { fired: false }, reducer, dd, 2);
+ expect(r.frame).toBe(30); // effectiveFrame = 15 * 2
+ expect(r.state.fired).toBe(true);
+ expect(r.active.length).toBe(1);
+ expect(r.progressOf("go")).toBe(0); // just entered the window
+ });
+
+ it("the same step fires at render frame 60 when speed=0.5 (eff=30)", () => {
+ const r = foldTimeline(60, steps, { fired: false }, reducer, dd, 0.5);
+ expect(r.frame).toBe(30);
+ expect(r.state.fired).toBe(true);
+ });
+
+ it("at speed=1 a step fires at its authored frame", () => {
+ expect(foldTimeline(29, steps, { fired: false }, reducer, dd, 1).state.fired)
+ .toBe(false);
+ expect(foldTimeline(30, steps, { fired: false }, reducer, dd, 1).state.fired)
+ .toBe(true);
+ });
+});
+
+// --- progressOf in-flight only (the flash-bug guard) -----------------------
+
+describe("progressOf is IN-FLIGHT ONLY (plan §6 'Settled-read persists', R-flash)", () => {
+ type A = "check";
+ const dd: Record<A, number> = { check: 12 }; // 12f default window
+ const steps: Step<A>[] = [{ at: 15, action: "check" }];
+ const reducer = (_s: { checked: boolean }, _step: Step<A>) => ({
+ checked: true,
+ });
+
+ const run = (raw: number) =>
+ foldTimeline(raw, steps, { checked: false }, reducer, dd, 1);
+
+ it("progressOf('check') is 0 before the window (frame 10)", () => {
+ const r = run(10);
+ expect(r.progressOf("check")).toBe(0);
+ expect(r.state.checked).toBe(false);
+ });
+
+ it("ramps 0->1 across frames 15..27", () => {
+ expect(run(15).progressOf("check")).toBeCloseTo(0, 5); // (15-15)/12 = 0
+ expect(run(21).progressOf("check")).toBeCloseTo(0.5, 5); // (21-15)/12 = 0.5
+ // frame 27 is the exclusive end (15+12) => no longer active => 0
+ expect(run(26).progressOf("check")).toBeCloseTo(11 / 12, 5);
+ });
+
+ it("at frame 90 progressOf('check') returns to 0 (window closed)", () => {
+ const r = run(90);
+ expect(r.progressOf("check")).toBe(0); // THE FLASH BUG GUARD
+ });
+
+ it("but state.checked STAYS true after the window closes (settled truth)", () => {
+ expect(run(90).state.checked).toBe(true);
+ expect(run(27).state.checked).toBe(true); // settled at the boundary too
+ });
+
+ it("toggle sequence check@15 -> uncheck@60: state reflects most-recent reducer", () => {
+ type T = "check" | "uncheck";
+ const tdd: Record<T, number> = { check: 12, uncheck: 10 };
+ const tsteps: Step<T>[] = [
+ { at: 15, action: "check" },
+ { at: 60, action: "uncheck" },
+ ];
+ const treducer = (
+ _s: { checked: boolean },
+ step: Step<T>,
+ ): { checked: boolean } => ({ checked: step.action === "check" });
+ const trun = (raw: number) =>
+ foldTimeline(raw, tsteps, { checked: false }, treducer, tdd, 1);
+
+ expect(trun(40).state.checked).toBe(true); // after check, before uncheck
+ expect(trun(40).progressOf("check")).toBe(0); // check window closed -> in-flight 0
+ expect(trun(90).state.checked).toBe(false); // after uncheck settled
+ expect(trun(90).progressOf("uncheck")).toBe(0); // uncheck window closed too
+ });
+});
+
+// --- duration:0 snaps (never active) ---------------------------------------
+
+describe("duration:0 snaps the logical state and is never active", () => {
+ type A = "set";
+ const dd: Record<A, number> = { set: 12 };
+ const steps: Step<A>[] = [{ at: 20, action: "set", duration: 0 }];
+ const reducer = (_s: { v: number }, _step: Step<A>) => ({ v: 1 });
+ const run = (raw: number) =>
+ foldTimeline(raw, steps, { v: 0 }, reducer, dd, 1);
+
+ it("state updates exactly at `at`", () => {
+ expect(run(19).state.v).toBe(0);
+ expect(run(20).state.v).toBe(1);
+ });
+
+ it("the duration:0 step never enters `active` and progressOf stays 0", () => {
+ expect(run(20).active.length).toBe(0);
+ expect(run(20).progressOf("set")).toBe(0);
+ expect(run(25).active.length).toBe(0);
+ });
+});
+
+// --- active-window boundaries ----------------------------------------------
+
+describe("active window is [at, at+dur) — inclusive start, exclusive end", () => {
+ type A = "x";
+ const dd: Record<A, number> = { x: 10 };
+ const steps: Step<A>[] = [{ at: 5, action: "x" }];
+ const reducer = (s: object) => s;
+ const run = (raw: number) => foldTimeline(raw, steps, {}, reducer, dd, 1);
+
+ it("active at the start frame", () => {
+ expect(run(5).active.length).toBe(1);
+ expect(run(5).progressOf("x")).toBe(0);
+ });
+
+ it("active just before the end frame", () => {
+ expect(run(14).active.length).toBe(1); // 14 < 15
+ });
+
+ it("NOT active at the exclusive end frame at+dur=15", () => {
+ expect(run(15).active.length).toBe(0);
+ });
+});
+
+// --- progressOf picks the most-recent active step of an action -------------
+
+describe("progressOf resolves the MOST-RECENT in-flight step of an action", () => {
+ it("overlapping windows of the same action -> later `at` wins", () => {
+ type A = "pulse";
+ const dd: Record<A, number> = { pulse: 20 };
+ const steps: Step<A>[] = [
+ { at: 0, action: "pulse" }, // window [0,20)
+ { at: 10, action: "pulse" }, // window [10,30) — overlaps
+ ];
+ const reducer = (s: object) => s;
+ const r = foldTimeline(15, steps, {}, reducer, dd, 1);
+ // both active at frame 15; most-recent (at=10) wins: (15-10)/20 = 0.25
+ expect(r.active.length).toBe(2);
+ expect(r.progressOf("pulse")).toBeCloseTo(0.25, 5);
+ });
+});
diff --git a/registry/remocn/ui-core/color.ts b/registry/remocn/ui-core/color.ts
new file mode 100644
index 00000000..31f2285a
--- /dev/null
+++ b/registry/remocn/ui-core/color.ts
@@ -0,0 +1,93 @@
+// Thin wrapper over culori. All color objects use culori's NATIVE shapes and
+// scales: `Rgb` channels are 0..1 (mode "rgb", optional `alpha`), `Oklch` uses
+// lowercase `l,c,h` (mode "oklch", optional `alpha`). The public channel scale
+// is culori-native 0..1 (NOT 0..255).
+
+import {
+ clampChroma,
+ converter,
+ formatRgb,
+ interpolate,
+ parse,
+ type Oklch,
+ type Rgb,
+} from "culori";
+
+const toRgb = converter("rgb");
+const toOklch = converter("oklch");
+
+const BLACK: Rgb = { mode: "rgb", r: 0, g: 0, b: 0, alpha: 1 };
+
+export function parseColor(c: string): Rgb {
+ const s = c.trim();
+
+ if (s.startsWith("var(")) {
+ if (process.env.NODE_ENV !== "production") {
+ console.warn(
+ `[remocn-ui] parseColor cannot resolve CSS variable "${s}" under Remotion's per-frame render. ` +
+ "Animated colors must be concrete oklch/hex/rgb values supplied via the theme. " +
+ "Falling back to the JS default.",
+ );
+ }
+ return { ...BLACK };
+ }
+
+ const rgb = toRgb(parse(s));
+ if (!rgb) {
+ if (process.env.NODE_ENV !== "production") {
+ console.warn(`[remocn-ui] parseColor could not parse "${s}"; using black.`);
+ }
+ return { ...BLACK };
+ }
+
+ return { mode: "rgb", r: rgb.r, g: rgb.g, b: rgb.b, alpha: rgb.alpha ?? 1 };
+}
+
+export function oklchToRgb(l: number, c: number, h: number): Rgb {
+ // Map into the sRGB gamut before converting so the result is displayable.
+ const mapped = clampChroma({ mode: "oklch", l, c, h }, "oklch", "rgb");
+ return toRgb(mapped);
+}
+
+// Takes a culori `Rgb` object (0..1). Achromatic colors yield an undefined/NaN
+// hue from culori; we normalize it to `0` to keep a numeric hue.
+export function rgbToOklch(rgb: Rgb): Oklch {
+ const { l, c, h } = toOklch(rgb);
+ return { mode: "oklch", l, c, h: Number.isFinite(h) ? h : 0 };
+}
+
+function resolveColorString(s: string): string {
+ const trimmed = s.trim();
+ if (trimmed.startsWith("var(")) {
+ if (process.env.NODE_ENV !== "production") {
+ console.warn(
+ `[remocn-ui] mixOklch cannot resolve CSS variable "${trimmed}" under Remotion's per-frame render. ` +
+ "Animated colors must be concrete oklch/hex/rgb values supplied via the theme. " +
+ "Falling back to the JS default.",
+ );
+ }
+ return "#000";
+ }
+ if (!parse(trimmed)) {
+ if (process.env.NODE_ENV !== "production") {
+ console.warn(`[remocn-ui] mixOklch could not parse "${trimmed}"; using black.`);
+ }
+ return "#000";
+ }
+ return trimmed;
+}
+
+export function mixOklch(a: string, b: string, t: number): string {
+ const mixed = clampChroma(
+ interpolate([resolveColorString(a), resolveColorString(b)], "oklch")(t),
+ "oklch",
+ "rgb",
+ );
+ return toCss(toRgb(mixed));
+}
+
+// Emits an inline-style sRGB string using culori's own formatter. `formatRgb`
+// produces the legacy `rgb()/rgba()` form.
+export function toCss(color: Rgb): string {
+ return formatRgb(color);
+}
diff --git a/registry/remocn/ui-core/index.ts b/registry/remocn/ui-core/index.ts
new file mode 100644
index 00000000..7e8b658d
--- /dev/null
+++ b/registry/remocn/ui-core/index.ts
@@ -0,0 +1,18 @@
+export type { Step, TimelineState } from "./types";
+export { framesFor, revealCount, useTimelineState } from "./timeline";
+export {
+ mixOklch,
+ oklchToRgb,
+ parseColor,
+ rgbToOklch,
+ toCss,
+} from "./color";
+export {
+ defaultDarkTheme,
+ defaultLightTheme,
+ RemocnUIProvider,
+ useRemocnTheme,
+} from "./theme";
+export type { RemocnTheme, RemocnUIProviderProps } from "./theme";
+export { easings, springs } from "./motion";
+export type { EasingName, SpringName } from "./motion";
diff --git a/registry/remocn/ui-core/motion.ts b/registry/remocn/ui-core/motion.ts
new file mode 100644
index 00000000..4e9a8f67
--- /dev/null
+++ b/registry/remocn/ui-core/motion.ts
@@ -0,0 +1,32 @@
+/**
+ * Deterministic, frame-based motion presets for remocn UI primitives.
+ *
+ * `easings` are pure functions on normalized progress `t ∈ [0,1]`. `springs` are
+ * parameter bags passed straight to Remotion's `spring({ config })`.
+ */
+
+export const easings = {
+ /** Linear. */
+ linear: (t: number): number => t,
+ /** Ease-out cubic — decelerates into rest. */
+ out: (t: number): number => 1 - (1 - t) ** 3,
+ /** Ease-in cubic — accelerates from rest. */
+ in: (t: number): number => t * t * t,
+ /** Ease-in-out cubic. */
+ inOut: (t: number): number =>
+ t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2,
+} as const;
+
+export type EasingName = keyof typeof easings;
+
+/** Remotion `spring()` config presets. */
+export const springs = {
+ /** Fast, tight settle — good for presses and toggles. */
+ snappy: { damping: 18, stiffness: 220, mass: 0.7 },
+ /** Gentle, smooth settle — good for entrances. */
+ soft: { damping: 14, stiffness: 120, mass: 0.9 },
+ /** Slight overshoot for playful pops. */
+ bouncy: { damping: 10, stiffness: 180, mass: 0.8 },
+} as const;
+
+export type SpringName = keyof typeof springs;
diff --git a/registry/remocn/ui-core/theme.ts b/registry/remocn/ui-core/theme.ts
new file mode 100644
index 00000000..4114286c
--- /dev/null
+++ b/registry/remocn/ui-core/theme.ts
@@ -0,0 +1,123 @@
+"use client";
+
+import { createContext, createElement, useContext } from "react";
+import type { ReactNode } from "react";
+
+/**
+ * The remocn UI theme — stock shadcn token names. Values are concrete oklch
+ * strings (NOT `var(...)`) so they can be interpolated under Remotion's headless
+ * per-frame render. `radius` is a pixel number (not the CSS `rem`).
+ */
+export interface RemocnTheme {
+ background: string;
+ foreground: string;
+ card: string;
+ cardForeground: string;
+ popover: string;
+ popoverForeground: string;
+ primary: string;
+ primaryForeground: string;
+ secondary: string;
+ secondaryForeground: string;
+ muted: string;
+ mutedForeground: string;
+ accent: string;
+ accentForeground: string;
+ destructive: string;
+ destructiveForeground: string;
+ border: string;
+ input: string;
+ ring: string;
+ /** Border radius in px. */
+ radius: number;
+}
+
+/** Stock shadcn "neutral" light theme (oklch tokens). */
+export const defaultLightTheme: RemocnTheme = {
+ background: "oklch(1 0 0)",
+ foreground: "oklch(0.145 0 0)",
+ card: "oklch(1 0 0)",
+ cardForeground: "oklch(0.145 0 0)",
+ popover: "oklch(1 0 0)",
+ popoverForeground: "oklch(0.145 0 0)",
+ primary: "oklch(0.205 0 0)",
+ primaryForeground: "oklch(0.985 0 0)",
+ secondary: "oklch(0.97 0 0)",
+ secondaryForeground: "oklch(0.205 0 0)",
+ muted: "oklch(0.97 0 0)",
+ mutedForeground: "oklch(0.556 0 0)",
+ accent: "oklch(0.97 0 0)",
+ accentForeground: "oklch(0.205 0 0)",
+ destructive: "oklch(0.577 0.245 27.325)",
+ destructiveForeground: "oklch(0.985 0 0)",
+ border: "oklch(0.922 0 0)",
+ input: "oklch(0.922 0 0)",
+ ring: "oklch(0.708 0 0)",
+ radius: 10,
+};
+
+/** Stock shadcn "neutral" dark theme (oklch tokens). */
+export const defaultDarkTheme: RemocnTheme = {
+ background: "oklch(0.145 0 0)",
+ foreground: "oklch(0.985 0 0)",
+ card: "oklch(0.205 0 0)",
+ cardForeground: "oklch(0.985 0 0)",
+ popover: "oklch(0.205 0 0)",
+ popoverForeground: "oklch(0.985 0 0)",
+ primary: "oklch(0.922 0 0)",
+ primaryForeground: "oklch(0.205 0 0)",
+ secondary: "oklch(0.269 0 0)",
+ secondaryForeground: "oklch(0.985 0 0)",
+ muted: "oklch(0.269 0 0)",
+ mutedForeground: "oklch(0.708 0 0)",
+ accent: "oklch(0.269 0 0)",
+ accentForeground: "oklch(0.985 0 0)",
+ destructive: "oklch(0.704 0.191 22.216)",
+ destructiveForeground: "oklch(0.985 0 0)",
+ border: "oklch(1 0 0 / 10%)",
+ input: "oklch(1 0 0 / 15%)",
+ ring: "oklch(0.556 0 0)",
+ radius: 10,
+};
+
+interface RemocnThemeContextValue {
+ theme?: Partial<RemocnTheme>;
+ mode?: "light" | "dark";
+}
+
+const RemocnThemeContext = createContext<RemocnThemeContextValue>({});
+
+export interface RemocnUIProviderProps {
+ theme?: Partial<RemocnTheme>;
+ mode?: "light" | "dark";
+ children: ReactNode;
+}
+
+export function RemocnUIProvider({
+ theme,
+ mode,
+ children,
+}: RemocnUIProviderProps) {
+ return createElement(
+ RemocnThemeContext.Provider,
+ { value: { theme, mode } },
+ children,
+ );
+}
+
+/**
+ * Resolve the active theme.
+ *
+ * Token resolution order: per-component `override` ▸ Provider `theme` ▸ default[mode].
+ * `mode` precedence: per-component `modeOverride` (the component's own `mode` prop)
+ * ▸ Provider `mode` ▸ "light".
+ */
+export function useRemocnTheme(
+ override?: Partial<RemocnTheme>,
+ modeOverride?: "light" | "dark",
+): RemocnTheme {
+ const ctx = useContext(RemocnThemeContext);
+ const mode = modeOverride ?? ctx.mode ?? "light";
+ const base = mode === "dark" ? defaultDarkTheme : defaultLightTheme;
+ return { ...base, ...ctx.theme, ...override };
+}
diff --git a/registry/remocn/ui-core/timeline.ts b/registry/remocn/ui-core/timeline.ts
new file mode 100644
index 00000000..475fd555
--- /dev/null
+++ b/registry/remocn/ui-core/timeline.ts
@@ -0,0 +1,73 @@
+import { useCurrentFrame } from "remotion";
+import type { Step } from "./types";
+
+/** duration(seconds-or-frames) -> frames. Number = frames; {seconds} -> *fps. */
+export function framesFor(d: number | { seconds: number }, fps: number): number {
+ return typeof d === "number" ? d : Math.round(d.seconds * fps);
+}
+
+/** Deterministic char-reveal count (same math as the typewriter component). */
+export function revealCount(
+ localFrame: number,
+ fps: number,
+ len: number,
+ cps: number,
+): number {
+ const over = (len / cps) * fps;
+ if (over <= 0) return len;
+ return Math.max(0, Math.min(len, Math.floor((localFrame / over) * len)));
+}
+
+function clamp01(t: number): number {
+ return Math.max(0, Math.min(1, t));
+}
+
+export function useTimelineState<S, A extends string>(
+ steps: Step<A>[],
+ defaultState: S,
+ reducer: (draft: S, step: Step<A>) => S,
+ durationDefaults: Record<A, number>,
+ speed = 1,
+): {
+ state: S;
+ active: Array<{ step: Step<A>; progress: number }>;
+ progressOf: (action: A) => number;
+ frame: number;
+} {
+ const raw = useCurrentFrame();
+ const effectiveFrame = raw * speed;
+
+ const ordered = steps
+ .map((step, index) => ({ step, index }))
+ .sort((a, b) => a.step.at - b.step.at || a.index - b.index)
+ .map((entry) => entry.step);
+
+ let state: S = { ...defaultState };
+ const active: Array<{ step: Step<A>; progress: number }> = [];
+
+ for (const step of ordered) {
+ if (step.at <= effectiveFrame) {
+ state = reducer(state, step);
+ }
+
+ const dur = step.duration ?? durationDefaults[step.action];
+ const end = step.at + dur;
+ if (dur > 0 && step.at <= effectiveFrame && effectiveFrame < end) {
+ active.push({ step, progress: clamp01((effectiveFrame - step.at) / dur) });
+ }
+ }
+
+ const progressOf = (action: A): number => {
+ let result = 0;
+ let bestAt = -Infinity;
+ for (const entry of active) {
+ if (entry.step.action === action && entry.step.at >= bestAt) {
+ bestAt = entry.step.at;
+ result = entry.progress;
+ }
+ }
+ return result;
+ };
+
+ return { state, active, progressOf, frame: effectiveFrame };
+}
diff --git a/registry/remocn/ui-core/types.ts b/registry/remocn/ui-core/types.ts
new file mode 100644
index 00000000..ed1302ef
--- /dev/null
+++ b/registry/remocn/ui-core/types.ts
@@ -0,0 +1,19 @@
+/**
+ * A single scripted interaction on the Remotion timeline.
+ *
+ * Every remocn UI primitive consumes the same `steps: Step[]` envelope. State is
+ * a deterministic left-fold over the steps whose `at` is <= the current frame.
+ */
+export interface Step<A extends string = string, V = unknown> {
+ /** LOCAL (Sequence-relative) authored frame at which this step begins. */
+ at: number;
+ /** Per-component action union (e.g. "hover" | "press" | "loading"). */
+ action: A;
+ /** Polymorphic payload; meaning depends on action. */
+ value?: V;
+ /** Frames to animate the transition. 0 = snap. Omitted = component default. */
+ duration?: number;
+}
+
+/** Result of folding steps: the resolved logical state at the current frame. */
+export type TimelineState<S> = S;