Skip to content

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

feat: impl timeline transition, state transition, refactor button component

dev_wandryb3225d75ba66
diff --git a/biome.json b/biome.json
index 41b3b952..bcd936a3 100644
--- a/biome.json
+++ b/biome.json
@@ -20,6 +20,9 @@
"recommended": true,
"suspicious": {
"noUnknownAtRules": "off"
+ },
+ "a11y": {
+ "noSvgWithoutTitle": "off"
}
},
"domains": {
diff --git a/components/docs/examples/button-example.tsx b/components/docs/examples/button-example.tsx
new file mode 100644
index 00000000..4eb4428e
--- /dev/null
+++ b/components/docs/examples/button-example.tsx
@@ -0,0 +1,28 @@
+"use client";
+
+import { Button } from "@/registry/remocn-ui/button";
+import { useButtonTransition } from "@/registry/remocn-ui/button/use-button-transition";
+
+export const ButtonExampleScene = () => {
+ const style = useButtonTransition([
+ { at: 12, state: "hover" },
+ { at: 30, state: "press" },
+ { at: 48, state: "loading", duration: 6 },
+ { at: 96, state: "success", duration: 16 },
+ ]);
+ return <Button label="Continue" style={style} />;
+};
+
+export const buttonExampleCode = `import { Button } from "@/components/remocn/button";
+import { useButtonTransition } from "@/components/remocn/use-button-transition";
+
+export const Scene = () => {
+ const style = useButtonTransition([
+ { at: 12, state: "hover" },
+ { at: 30, state: "press" },
+ { at: 48, state: "loading", duration: 6 },
+ { at: 96, state: "success", duration: 16 },
+ ]);
+
+ return <Button label="Continue" style={style} />;
+};`;
diff --git a/components/docs/examples/index.tsx b/components/docs/examples/index.tsx
new file mode 100644
index 00000000..d2fc94a9
--- /dev/null
+++ b/components/docs/examples/index.tsx
@@ -0,0 +1,23 @@
+import type { ComponentType } from "react";
+import { FPS, H, W } from "@/lib/customizer-config";
+import { ButtonExampleScene, buttonExampleCode } from "./button-example";
+
+export interface ExampleEntry {
+ Component: ComponentType;
+ code: string;
+ durationInFrames: number;
+ fps: number;
+ width: number;
+ height: number;
+}
+
+export const examples: Record<string, ExampleEntry> = {
+ "button-example": {
+ Component: ButtonExampleScene,
+ code: buttonExampleCode,
+ durationInFrames: 132,
+ fps: FPS,
+ width: W,
+ height: H,
+ },
+};
diff --git a/components/docs/live-example.tsx b/components/docs/live-example.tsx
new file mode 100644
index 00000000..98d708b4
--- /dev/null
+++ b/components/docs/live-example.tsx
@@ -0,0 +1,116 @@
+"use client";
+
+import { Player } from "@remotion/player";
+import { DynamicCodeBlock } from "fumadocs-ui/components/dynamic-codeblock";
+import { PlayIcon } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { usePrefersReducedMotion } from "@/lib/use-prefers-reduced-motion";
+import { cn } from "@/lib/utils";
+import { examples } from "./examples";
+
+export function LiveExample({ name }: { name: string }) {
+ const entry = examples[name];
+
+ if (!entry) {
+ return (
+ <div className="not-prose mb-6 rounded-lg border border-fd-border p-4 text-sm text-fd-muted-foreground">
+ Unknown component: <code>{name}</code>
+ </div>
+ );
+ }
+
+ return (
+ <div className="not-prose mb-6 flex w-full flex-col gap-4">
+ <Tabs defaultValue="preview" className="gap-3">
+ <TabsList>
+ <TabsTrigger value="preview">Preview</TabsTrigger>
+ <TabsTrigger value="code">Code</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="preview" className="mt-0">
+ <LivePreviewStage entry={entry} name={name} />
+ </TabsContent>
+
+ <TabsContent value="code" className="mt-0">
+ <div className="surface-card overflow-hidden rounded-2xl [&_pre]:!rounded-none [&_pre]:!border-0 [&_pre]:!bg-transparent">
+ <DynamicCodeBlock lang="tsx" code={entry.code} />
+ </div>
+ </TabsContent>
+ </Tabs>
+ </div>
+ );
+}
+
+function LivePreviewStage({
+ entry,
+ name,
+}: {
+ entry: (typeof examples)[string];
+ name: string;
+}) {
+ const [mounted, setMounted] = useState(false);
+ const frameRef = useRef<HTMLDivElement>(null);
+ const reducedMotion = usePrefersReducedMotion();
+
+ useEffect(() => {
+ if (mounted) return;
+ const el = frameRef.current;
+ if (!el || typeof IntersectionObserver === "undefined") return;
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((e) => e.isIntersecting)) {
+ setMounted(true);
+ observer.disconnect();
+ }
+ },
+ { rootMargin: "200px 0px" },
+ );
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [mounted]);
+
+ return (
+ <div
+ ref={frameRef}
+ className="surface-card aspect-video w-full overflow-hidden rounded-2xl"
+ >
+ {mounted ? (
+ <div
+ className={cn(
+ "size-full",
+ !reducedMotion && "animate-in fade-in duration-300 ease-out",
+ )}
+ >
+ <Player
+ component={entry.Component}
+ inputProps={{}}
+ durationInFrames={entry.durationInFrames}
+ fps={entry.fps}
+ compositionWidth={entry.width}
+ compositionHeight={entry.height}
+ style={{ width: "100%", height: "100%" }}
+ controls
+ loop
+ autoPlay
+ acknowledgeRemotionLicense
+ />
+ </div>
+ ) : (
+ <button
+ type="button"
+ onClick={() => setMounted(true)}
+ aria-label={`Play preview of ${name}`}
+ className={cn(
+ "group flex size-full items-center justify-center bg-muted/40 transition-colors",
+ "hover:bg-muted/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",
+ )}
+ >
+ <span className="flex size-12 items-center justify-center rounded-full bg-background/80 text-foreground transition-colors group-hover:bg-background">
+ <PlayIcon className="size-5 translate-x-px fill-current" />
+ </span>
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/content/docs/ui/button.mdx b/content/docs/ui/button.mdx
index 70c14606..26a1b2d4 100644
--- a/content/docs/ui/button.mdx
+++ b/content/docs/ui/button.mdx
@@ -1,86 +1,112 @@
---
title: Button
-description: A scripted button that animates hover, press, loading, and success states as a pure function of the Remotion timeline
+description: A button whose visual state is a pure function of the timeline
---
<ComponentPreview name="button" />
+A state atom whose appearance (idle, hover, press, loading, success) is a pure function of the `state` prop. Pass a state directly or drive it from the Remotion timeline via `useCurrentState`. The component reads no frame — only the state value you give it.
+
## Installation
<InstallBlock name="button" />
<Note>
-Installing `button` automatically installs the shared `remocn-ui` core (`lib/remocn-ui/`) and its `culori` color dependency via `registryDependencies`. You do not need to install either separately.
+Installing `button` automatically installs `spinner` and the shared `remocn-ui` core (`lib/remocn-ui/`) via `registryDependencies`. You do not need to install either separately.
</Note>
-## The steps timeline
+## States
-`Button` accepts a `steps` prop — an array of `Step<ButtonAction>` objects that script the button's interaction. The full `ButtonAction` union is:
+`ButtonState` is:
```ts
-type ButtonAction =
- | "hover" // lift + background crossfade
+type ButtonState =
+ | "idle" // resting
+ | "hover" // lifted + background shift
| "press" // scale down + darken
- | "release" // return to hover level
- | "loading" // label fades out, spinner fades in
- | "success" // spinner fades out, checkmark draws
- | "reset" // destructive flash, then return to idle
+ | "loading" // renders <Spinner />
+ | "success" // renders a static checkmark, background fills primary
```
-A realistic happy-path interaction — hover, click, load, succeed:
+`loading` composes `<Spinner />` in place of the label. `success` renders a static checkmark SVG. Both `loading` and `success` hide the label text.
+
+## Snap usage (simple path)
+
+Pass `state` directly — the component snaps instantly to that visual. Useful for static previews or when you drive state from your own logic:
```tsx
import { Button } from "@/components/remocn/button";
-export const Scene = () => (
- <Button
- label="Continue"
- steps={[
- { at: 10, action: "hover" },
- { at: 25, action: "press" },
- { at: 35, action: "loading" },
- { at: 70, action: "success" },
- ]}
- />
-);
+export const Scene = () => <Button state="loading" />;
```
-Each `at` value is a **Sequence-local authored frame**. If the component sits inside a `<Sequence from={30}>`, Remotion shifts the playhead automatically — `at: 10` always means "10 frames into this Sequence." See the [ui tier intro](/docs/ui) for how `useTimelineState` resolves the fold.
-
-### Single-action shortcut
-
-For a quick loading spinner or a one-step hover, pass a single step:
+To drive state from the timeline, use `useCurrentState`:
```tsx
-// Spinner only — no label
-<Button label="Save" steps={[{ at: 0, action: "loading" }]} />
+import { useCurrentState } from "@/lib/remocn-ui";
+import { Button } from "@/components/remocn/button";
-// Hover state held for the full duration
-<Button label="Sign up" steps={[{ at: 5, action: "hover" }]} />
+export const Scene = () => {
+ const state = useCurrentState(
+ [
+ { at: 8, state: "hover" },
+ { at: 20, state: "press" },
+ { at: 35, state: "loading" },
+ { at: 70, state: "success" },
+ ],
+ "idle",
+ );
+
+ return <Button label="Continue" state={state} />;
+};
```
-### Using a preset scenario
+Each `at` is a **Sequence-local authored frame**. State persists between steps: `hover` at frame 8 keeps the button lifted until `press` fires at frame 20. See the [ui tier intro](/docs/ui) for the full `useCurrentState` API.
-The `scenario` prop is a preview-convenience alias for a fixed `steps` array. It exists so the live preview customizer can switch between canned interactions without the user manually editing step objects. In production compositions, prefer explicit `steps`.
+## Smooth transitions (opt-in)
-| Scenario | Equivalent steps |
-|---|---|
-| `"happy"` | hover→press→loading→success |
-| `"loading"` | loading (at 10) |
-| `"error"` | hover→press→loading→reset |
-| `"idle"` | `[]` (static button) |
+State changes via `state` snap with no cross-fade. For animated transitions, use `useButtonTransition` from the copied `use-button-transition.ts` file. It reads the frame, interpolates between state presets, and returns a resolved `ButtonStyle` — pass it to the `style` prop:
```tsx
-// Fine for quick previews; prefer steps={[...]} in real compositions
-<Button scenario="happy" />
+import { Button } from "@/components/remocn/button";
+import { useButtonTransition } from "@/components/remocn/use-button-transition";
+
+export const Scene = () => {
+ const style = useButtonTransition([
+ { at: 12, state: "hover" },
+ { at: 30, state: "press" },
+ { at: 48, state: "loading", duration: 6 },
+ { at: 96, state: "success", duration: 16 },
+ ]);
+ return <Button label="Continue" style={style} />;
+};
```
-When both `steps` and `scenario` are supplied, `steps` wins.
+The `duration` field on each step overrides the file's `DEFAULT_DURATION` for that specific transition. To globally tune timing and easing, edit `use-button-transition.ts` directly in your project — that file is yours (shadcn "own your code" philosophy).
+
+`style` takes precedence over `state` when both are provided.
+
+## Full lifecycle
+
+A complete idle → hover → press → loading → success run using the smooth transition path. Copy the code to drop it into your own composition.
+
+<LiveExample name="button-example" />
## Props
<PropsTable
rows={[
+ {
+ name: "state",
+ type: "\"idle\" | \"hover\" | \"press\" | \"loading\" | \"success\"",
+ default: "\"idle\"",
+ description: "Current visual state (snap path). State changes snap — no automatic cross-fade.",
+ },
+ {
+ name: "style",
+ type: "ButtonStyle",
+ description: "Resolved animated visual (smooth path). Pass an interpolated ButtonStyle from useButtonTransition. Takes precedence over state when provided.",
+ },
{
name: "label",
type: "string",
@@ -99,11 +125,6 @@ When both `steps` and `scenario` are supplied, `steps` wins.
default: "\"default\"",
description: "Button height and padding. sm=32px, default=40px, lg=48px.",
},
- {
- name: "steps",
- type: "Step<ButtonAction>[]",
- description: "Timeline script for the button interaction. Takes precedence over scenario.",
- },
{
name: "theme",
type: "Partial<RemocnTheme>",
@@ -116,16 +137,15 @@ When both `steps` and `scenario` are supplied, `steps` wins.
description: "Sets the base palette. Overrides the mode on RemocnUIProvider when both are present.",
},
{
- name: "scenario",
- type: "\"happy\" | \"loading\" | \"error\" | \"idle\"",
- default: "\"idle\"",
- description: "Preview-convenience alias for a preset steps array. Ignored when steps is provided. Prefer steps in production compositions.",
+ name: "primary",
+ type: "string",
+ description: "Convenience override for the primary theme token. Merged into theme — saves a theme object for single-token changes.",
},
{
name: "speed",
type: "number",
default: "1",
- description: "Scales the playhead, not the authored step times. speed=2 makes all animations run twice as fast without changing your at values.",
+ description: "Forwarded to the loading Spinner. Scales the spinner playhead — speed=2 spins twice as fast without changing authored step times.",
},
{
name: "className",
diff --git a/content/docs/ui/index.mdx b/content/docs/ui/index.mdx
index 26ca82c3..bb33da3a 100644
--- a/content/docs/ui/index.mdx
+++ b/content/docs/ui/index.mdx
@@ -3,13 +3,13 @@ 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()`.
+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 state a component is in and when, and it renders that state 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.
+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, state: "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.
@@ -23,97 +23,135 @@ npx shadcn add @remocn/button
This writes `components/remocn/button.tsx` and `lib/remocn-ui/` to your project. Every component depends on the same `lib/remocn-ui/` core.
-## The `steps` timeline envelope
+## Two kinds of atom
-Every `ui` primitive accepts a `steps` prop — an array of `Step` objects that describe what the component does and when.
+### State atoms
-```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;
-}
-```
+**State atoms** (Button, Input, Checkbox, Switch) are pure visual functions of `(state | style, theme)`. They read no frame, hold no internal clock, and snap instantly between named states. The component accepts either a `state` (named preset, snap path) or a `style` (resolved, interpolated visual, smooth path) — but never reads the frame itself. The state or style value comes from outside: a direct prop, `useCurrentState`, or a transition hook (see below).
-A Button scripted through a full interaction looks like this:
+**Purity boundary:** `useCurrentFrame()` is never called inside a state atom. Frame resolution happens in the caller — either in `useCurrentState`, `useStateTransition`, or a component's transition hook like `useButtonTransition`. This keeps every state atom safe as a pure renderer.
-```tsx
-import { Button } from "@/components/remocn/button";
+### Motion atoms
-export const Scene = () => (
- <Button
- label="Continue"
- steps={[
- { at: 10, action: "hover" },
- { at: 25, action: "press" },
- { at: 35, action: "loading" },
- { at: 70, action: "success" },
- ]}
- />
-);
-```
+**Motion atoms** (Spinner) loop on `useCurrentFrame()` with no discrete states. They are pure functions of the frame and safe in Remotion's headless renderer — no `Date`, no `Math.random`, no `requestAnimationFrame`. Spinner is the first motion atom in this tier.
+
+## Timeline hooks
+
+### `useCurrentState` — snap resolution
-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."
+`useCurrentState` resolves the current state as a **latest-step-wins fold**: it scans the steps array and returns the `state` of the last step whose `at` is at or before the current effective frame.
-## How the fold works
+```ts
+function useCurrentState<S extends string>(
+ steps: Step<S>[],
+ defaultState: S,
+ speed?: number,
+): S
+```
-Internally, every `ui` primitive calls `useTimelineState` from `lib/remocn-ui/timeline.ts`. This hook folds the `steps` array into two things:
+- `defaultState` is returned before the first step fires.
+- `speed` scales the playhead: `effectiveFrame = currentFrame * speed`. A step at `{ at: 30 }` with `speed: 2` activates at render frame 15.
+- `at` values are always **Sequence-local authored frames** — if the component sits inside `<Sequence from={30}>`, Remotion shifts the playhead automatically.
-- **`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.
+### `useStateTransition` — smooth resolution
+
+`useStateTransition` is the lower-level resolver used by transition hooks. It returns the `from` state, the `to` state, and a `progress` value (0 → 1) over the transition window. Transition hooks call this and blend the visuals; you generally do not call it directly.
```ts
-const { state, progressOf } = useTimelineState(steps, defaultState, reducer, durationDefaults);
+function useStateTransition<S extends string>(
+ steps: Step<S>[],
+ defaultState: S,
+ speed?: number,
+ defaultDuration?: number,
+): { from: S; to: S; progress: number }
+```
+
+- `defaultDuration` — frames to animate into a step that omits `duration`. Defaults to `8`.
+- `progress` ramps from 0 to 1 over `[step.at, step.at + duration)`, then holds at 1.
+- Ties on `at` resolve later-array-wins (same as `useCurrentState`).
+
+### `Step`
-// state.phase tells you what the button IS (settled)
-// progressOf("hover") tells you how far into the hover animation you are (in-flight)
+```ts
+interface Step<S extends string = string> {
+ /** Sequence-local frame at which this state becomes active. */
+ at: number;
+ /** The state value to enter at this frame. */
+ state: S;
+ /** Frames to animate the transition INTO this state. Omitted → caller's defaultDuration. */
+ duration?: number;
+}
```
-### The single fold invariant
+`duration` is consumed by `useStateTransition` (and transition hooks). `useCurrentState` ignores it — snap resolution has no concept of transition length.
+
+## Usage patterns
-<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>
+### Controlled (canonical)
-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:
+Pass a state value directly — useful when you want to drive the component from your own logic:
```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");
+import { Button } from "@/components/remocn/button";
+
+// Always shows the loading state
+export const Scene = () => <Button state="loading" />;
```
-### Concurrent animation tracks
+### Timeline-driven
-`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.
+Drive state from the Remotion timeline via `useCurrentState`:
```tsx
-// Loading → success crossfade: both tracks are live simultaneously
-const spinnerOpacity = 1 - progressOf("success");
-const checkmarkOpacity = progressOf("success");
-const loadingRingProgress = progressOf("loading");
+import { useCurrentState } from "@/lib/remocn-ui";
+import { Button } from "@/components/remocn/button";
+
+export const Scene = () => {
+ const state = useCurrentState(
+ [
+ { at: 8, state: "hover" },
+ { at: 20, state: "press" },
+ { at: 35, state: "loading" },
+ { at: 70, state: "success" },
+ ],
+ "idle",
+ );
+
+ return <Button state={state} />;
+};
```
-A single scalar `progress` value could not express this. The per-action tracks are why `useTimelineState` returns a function rather than a number.
+The `at` value is a **Sequence-local authored frame** throughout. State persists between steps: `hover` at frame 8 keeps the button lifted all the way until `press` at frame 20, with no extra bookkeeping.
+
+## States snap by default
+
+State atoms snap instantly between named states — no automatic cross-fade or enter-tween. Snap is the default and cheapest path: author `{ at: N, state: "hover" }` and the atom jumps straight to that visual at frame N.
+
+## Smooth transitions — opt-in via transition hooks
+
+Each state atom ships a **transition file** (e.g. `use-button-transition.ts`) that is copied into your project alongside the component. That file:
-### `duration: 0` snaps
+- owns `DEFAULT_DURATION` and easing
+- exports a `use<Name>Transition(steps, opts?) → <Name>Style` hook
+- calls `useStateTransition` internally and interpolates between state presets
-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.
+To get smooth motion, call the hook in your composition and feed the result to the component's `style` prop:
-### The `speed` prop
+```tsx
+import { Button } from "@/components/remocn/button";
+import { useButtonTransition } from "@/components/remocn/use-button-transition";
+
+export const Scene = () => {
+ const style = useButtonTransition([
+ { at: 12, state: "hover" },
+ { at: 30, state: "press" },
+ { at: 48, state: "loading", duration: 6 },
+ ]);
+ return <Button label="Continue" style={style} />;
+};
+```
-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.
+To tune timing globally, edit `DEFAULT_DURATION` in your copied `use-button-transition.ts`. To tune a single transition, add `duration` to that step — it overrides the file default for that transition only. To tune easing, edit the `easings.out(progress)` call in the same file.
## Theming
@@ -138,8 +176,8 @@ import { RemocnUIProvider } from "@/lib/remocn-ui";
export const Scene = () => (
<RemocnUIProvider mode="dark" theme={{ primary: "oklch(0.6 0.22 260)" }}>
- <Button label="Continue" steps={[{ at: 10, action: "hover" }]} />
- <UICheckbox label="Remember me" steps={[{ at: 30, action: "check" }]} />
+ <Button state={buttonState} label="Continue" />
+ <UICheckbox label="Remember me" state={checkState} />
</RemocnUIProvider>
);
```
@@ -164,7 +202,7 @@ CSS custom properties (`var(--primary)`) work for **static** styling only. Remot
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.
+A project whose `:root` overrides `--primary` will see static elements pick up the CSS variable correctly, but state-dependent visuals (hover background, 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
@@ -172,10 +210,10 @@ Installing any component in this tier also installs `lib/remocn-ui/` with these
| Module | Key exports |
|---|---|
-| `timeline.ts` | `useTimelineState`, `framesFor`, `revealCount` |
+| `timeline.ts` | `useCurrentState`, `useStateTransition`, `framesFor`, `revealCount` |
| `theme.ts` | `RemocnUIProvider`, `useRemocnTheme`, `defaultLightTheme`, `defaultDarkTheme` |
| `color.ts` | `mixOklch`, `parseColor`, `oklchToRgb`, `rgbToOklch`, `toCss` |
| `motion.ts` | `easings`, `springs` |
-| `types.ts` | `Step`, `TimelineState` |
+| `types.ts` | `Step` (with optional `duration`) |
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
index f0f3abfc..158e5caa 100644
--- a/content/docs/ui/meta.json
+++ b/content/docs/ui/meta.json
@@ -1,5 +1,5 @@
{
"title": "UI",
"collapsible": false,
- "pages": ["index", "button"]
+ "pages": ["index", "button", "spinner"]
}
diff --git a/content/docs/ui/spinner.mdx b/content/docs/ui/spinner.mdx
new file mode 100644
index 00000000..86d2861a
--- /dev/null
+++ b/content/docs/ui/spinner.mdx
@@ -0,0 +1,80 @@
+---
+title: Spinner
+description: A deterministic spinning arc — pure function of the Remotion frame
+---
+
+<ComponentPreview name="spinner" />
+
+A **motion atom**: a looping animation that is a pure function of `useCurrentFrame()`. No states, no props to sequence — just a spinning arc that advances deterministically with the timeline. Safe in Remotion's headless per-frame renderer (no `Date`, `Math.random`, or `requestAnimationFrame`).
+
+## Installation
+
+<InstallBlock name="spinner" />
+
+<Note>
+`spinner` is also installed automatically when you install `button`, via `registryDependencies`.
+</Note>
+
+## Usage
+
+Minimal — inherits color from the surrounding text:
+
+```tsx
+import { Spinner } from "@/components/remocn/spinner";
+
+export const Scene = () => <Spinner />;
+```
+
+Sized and colored explicitly:
+
+```tsx
+import { Spinner } from "@/components/remocn/spinner";
+
+export const Scene = () => (
+ <Spinner size={32} color="oklch(0.55 0.2 250)" speed={1.5} />
+);
+```
+
+## How rotation works
+
+```
+rotation (deg) = frame × speed × 6
+```
+
+At 30 fps with `speed=1`, one full rotation takes 20 frames (2 frames per 12°). Increase `speed` to spin faster without changing the composition fps.
+
+## Props
+
+<PropsTable
+ rows={[
+ {
+ name: "size",
+ type: "number",
+ default: "20",
+ description: "Width and height of the SVG in px.",
+ },
+ {
+ name: "color",
+ type: "string",
+ default: "\"currentColor\"",
+ description: "Stroke color. Defaults to currentColor so it inherits the surrounding text color.",
+ },
+ {
+ name: "speed",
+ type: "number",
+ default: "1",
+ description: "Scales the playhead. rotation = frame × speed × 6 (deg). speed=2 spins twice as fast.",
+ },
+ {
+ name: "strokeWidth",
+ type: "number",
+ default: "2.5",
+ description: "Arc stroke width in viewBox units (viewBox is 0 0 24 24).",
+ },
+ {
+ name: "className",
+ type: "string",
+ description: "Optional className passed to the SVG element.",
+ },
+ ]}
+/>
diff --git a/mdx-components.tsx b/mdx-components.tsx
index 27ec98c7..5bfa6dd3 100644
--- a/mdx-components.tsx
+++ b/mdx-components.tsx
@@ -4,6 +4,7 @@ import { Note, Warning } from "@/components/docs/callout";
import { ComponentCardGrid } from "@/components/docs/component-card-grid";
import { ComponentPreview } from "@/components/docs/component-preview";
import { Dependencies } from "@/components/docs/dependencies";
+import { LiveExample } from "@/components/docs/live-example";
import { InstallBlock } from "@/components/docs/install-block";
import { PropsTable } from "@/components/docs/props-table";
@@ -32,6 +33,7 @@ export function getMDXComponents(components?: MDXComponents): MDXComponents {
// Custom doc widgets — registrations only, not reimplemented here.
ComponentPreview,
+ LiveExample,
InstallBlock,
PropsTable,
Note,
diff --git a/registry/__index__.tsx b/registry/__index__.tsx
index 58dce8ba..1dfc3749 100644
--- a/registry/__index__.tsx
+++ b/registry/__index__.tsx
@@ -107,6 +107,8 @@ import { Typewriter } from "@/registry/remocn/typewriter";
import { typewriterConfig } from "@/registry/remocn/typewriter/config";
import { Button } from "@/registry/remocn-ui/button";
import { buttonConfig } from "@/registry/remocn-ui/button/config";
+import { Spinner } from "@/registry/remocn-ui/spinner";
+import { spinnerConfig } from "@/registry/remocn-ui/spinner/config";
import { ZoomThroughTransition } from "@/registry/remocn/zoom-through-transition";
import { zoomThroughTransitionConfig } from "@/registry/remocn/zoom-through-transition/config";
@@ -281,6 +283,7 @@ const registry: Record<string, RegistryEntry> = {
},
"github-stars": { Component: GitHubStars, config: githubStarsConfig },
"button": { Component: Button, config: buttonConfig },
+ "spinner": { Component: Spinner, config: spinnerConfig },
};
// Append the shared controls (e.g. `speed`) to every component config so
diff --git a/registry/remocn-ui/STYLE-GUIDE.md b/registry/remocn-ui/STYLE-GUIDE.md
new file mode 100644
index 00000000..70dce573
--- /dev/null
+++ b/registry/remocn-ui/STYLE-GUIDE.md
@@ -0,0 +1,251 @@
+# remocn-ui — component style guide
+
+The contract every `remocn-ui` primitive follows. Read this before adding a new
+component (Input, Checkbox, Switch, …). It is the frozen output of the design
+decisions behind `button` + `spinner`; new components copy these patterns
+verbatim so the tier stays coherent.
+
+> **Hard rule for contributors and agents:** the user runs ALL verification
+> (`bun test`, `bun run registry:build`, `bun dev`) and all commits. Do NOT run
+> build / dev / lint / test / registry:build. Verify by reading + `grep` only.
+
+---
+
+## 1. Two kinds of primitive
+
+Every component is exactly one of these. Decide which before writing a line.
+
+### State atom (Button, Input, Checkbox, Switch, …)
+
+A **pure function of its inputs** — `(state | style, theme) => view`. It:
+
+- knows only the **current state** (a string union) or a pre-resolved **visual**;
+- knows nothing about time — it never calls `useCurrentFrame`, holds no
+ `useState`/`useEffect`, has no `localFrame`, no transition logic;
+- **snaps** between states by default. Smooth motion is opt-in and lives
+ OUTSIDE the component (see §4).
+
+### Motion atom (Spinner, and future Pulse/Typewriter, …)
+
+A continuous animation with **no discrete states**. It is the ONLY kind of atom
+allowed to read `useCurrentFrame()`. Keep it tiny, self-contained, theme-light
+(take a `color` prop defaulting to `currentColor`). Example: `spinner` —
+`rotation = useCurrentFrame() * speed * 6`, no Date/RAF/random.
+
+State atoms **compose** motion atoms (Button renders `<Spinner/>` in `loading`).
+
+---
+
+## 2. The purity boundary (the line you must not cross)
+
+> The frame is read by **motion atoms** and by the **caller's transition hook**
+> (`use<Name>Transition`), NEVER inside a state-atom component.
+
+This is what keeps state atoms deterministic and trivially testable. A state
+atom that calls `useCurrentFrame` (directly or via a timeline hook) is a bug.
+
+Determinism grep — must print NOTHING for a state atom's `index.tsx`:
+
+```bash
+grep -nE "useState|useEffect|useCurrentFrame|onClick|onChange|addEventListener|Date\.now|Math\.random|requestAnimationFrame" \
+ registry/remocn-ui/<name>/index.tsx
+```
+
+---
+
+## 3. File layout per state atom
+
+```
+registry/remocn-ui/<name>/
+ index.tsx # pure render + state→visual presets (SHIPS)
+ use-<name>-transition.ts # durations + easing + tween + hook (SHIPS)
+ config.ts # customizer config (preview-only, NOT shipped)
+ __tests__/ # bun:test + README
+```
+
+Motion atoms ship only `index.tsx` (+ optional `config.ts`).
+
+### `index.tsx` — the pure renderer
+
+Exports, by convention (mirror `button`):
+
+- `type <Name>State` — the state union (e.g. `"idle" | "hover" | …`).
+- `interface <Name>Style` — the **animated** visual: only the values that change
+ between states (transforms, animated colors, child opacities). Static,
+ non-animated parts (text color, border, radius, size) are resolved inside the
+ component from variant/theme and are NOT in `<Name>Style`.
+- `interface <Name>StyleContext` — concrete colors derived once per render from
+ `(variant, theme)`.
+- `function <name>StyleContext(variant, theme): <Name>StyleContext` — pure.
+- `function <name>Style(state, ctx): <Name>Style` — pure preset map. Each state
+ is the COMPLETE resting visual for that state (a keyframe, not a delta).
+- `interface <Name>Props` — includes `state?: <Name>State` (snap) AND
+ `style?: <Name>Style` (smooth; takes precedence over `state`).
+- the component: `const v = style ?? <name>Style(state, ctx);` then render from
+ `v`. Snap and smooth share ONE render path.
+
+**Child crossfade rule:** when a state swaps content (label ↔ spinner ↔ check),
+put opacities in `<Name>Style` (`labelOpacity`, `spinnerOpacity`, …), render ALL
+children always, drive them by opacity, and keep the width-defining child in
+normal flow (others as absolute overlays) so the box does not jump. The opacity
+fields of a preset sum to 1.
+
+### `use-<name>-transition.ts` — the opt-in smoothing (SHIPS, user-editable)
+
+This is shadcn "own your code": it lands in the user's project and they tune
+motion by editing it — no config props. Exports:
+
+- `const DEFAULT_DURATION = <n>` — transition length (frames) when a `Step`
+ omits `duration`. One number, not a per-state map.
+- `function tween<Name>Style(a, b, t): <Name>Style` — blend two visuals: numbers
+ lerp, colors via `mixOklch`. Must cover EVERY field (a missing field freezes
+ that channel).
+- `interface <Name>TransitionOptions` — `{ variant?, theme?, mode?, primary?,
+ speed?, defaultDuration? }`.
+- `function use<Name>Transition(steps, opts?): <Name>Style` — resolves theme +
+ ctx, calls core `useStateTransition`, eases progress (`easings.out` default),
+ returns the tweened visual. THIS hook reads the frame (via `useStateTransition`),
+ on the caller's side.
+
+---
+
+## 4. State, snap, and smooth
+
+- **Snap (default):** `<Button state="loading" />`. The component renders
+ `<name>Style(state, ctx)` — no tween, no clock.
+- **Smooth (opt-in):** the caller drives it.
+ ```tsx
+ const style = useButtonTransition([
+ { at: 12, state: "hover" },
+ { at: 30, state: "press" },
+ { at: 48, state: "loading", duration: 6 }, // per-step override
+ { at: 96, state: "success", duration: 16 },
+ ]);
+ return <Button style={style} />;
+ ```
+ Mental model: **a state is a named preset of a visual; smooth = feed an
+ interpolated visual.** The component cannot tell the difference.
+
+There is no automatic cross-fade baked into the component. Cross-component
+*morphs* (button→input) are a separate, deferred composition layer — not a
+primitive concern.
+
+---
+
+## 5. The timeline (core `lib/remocn-ui`)
+
+`Step` is the uniform envelope:
+
+```ts
+interface Step<S extends string = string> {
+ at: number; // LOCAL (Sequence-relative) authored frame
+ state: S; // per-component state union
+ duration?: number; // frames for the transition INTO this state; omit → default
+}
+```
+
+Two core resolvers (both pure folds; `effectiveFrame = useCurrentFrame()*speed`):
+
+- `useCurrentState(steps, defaultState, speed?) → S` — latest step with
+ `at <= effectiveFrame`, else default. For snap-from-timeline.
+- `useStateTransition(steps, defaultState, speed?, defaultDuration?) →
+ { from, to, progress }` — `to` = latest started step (ties → later array
+ entry), `from` = the one before (else default), `progress` ramps 0→1 over
+ `[to.at, to.at + (to.duration ?? defaultDuration))` then holds at 1. Before any
+ step → `{ from: default, to: default, progress: 1 }`. For smooth transitions.
+
+Other core exports you reuse, never re-implement: `mixOklch` (animated colors),
+`useRemocnTheme` / `RemocnUIProvider` / `RemocnTheme` (theming), `easings` /
+`springs` (motion), `framesFor` / `revealCount` (typewriter math).
+
+---
+
+## 6. Theming
+
+- JS theme object with stock shadcn token names is the source of truth
+ (`RemocnTheme`); defaults match stock shadcn neutral.
+- Resolve with `useRemocnTheme(override, mode)`. Order: per-component `theme`
+ prop > `RemocnUIProvider` > `defaultLightTheme`/`defaultDarkTheme` per `mode`.
+- **Animated colors** must be concrete oklch/hex/rgb and interpolated with
+ `mixOklch` — `var(--token)` cannot be resolved by Remotion's headless renderer
+ for JS interpolation. Static (never-animated) colors may use `var()` in inline
+ `style`.
+- Transparent variants (outline/ghost) rest on a concrete `theme.background` so
+ the color mix has a real endpoint — never pass the literal `"transparent"` to
+ `mixOklch`.
+
+---
+
+## 7. Registry wiring
+
+- A state atom's registry item ships BOTH `index.tsx` → `components/remocn/<name>.tsx`
+ AND `use-<name>-transition.ts` → `components/remocn/use-<name>-transition.ts`.
+- Declare deps: `dependencies` for npm packages (`remotion`, `culori`),
+ `registryDependencies` for sibling registry items (`["remocn-ui", "spinner", …]`).
+- Source files import siblings by the **install path** (`@/components/remocn/<name>`),
+ not the repo path — that ships correctly to users and resolves in-repo via the
+ tsconfig alias `@/components/remocn/* → registry/remocn-ui/*/index.tsx`.
+- `config.ts` is preview-only — do NOT list it in registry files.
+- The shared core (`remocn-ui` registry:lib, sourced from `core/`) is pulled
+ automatically via `registryDependencies`; never duplicate it per component.
+
+---
+
+## 8. Customizer, preview, and the live example
+
+- **`config.ts`**: a `ComponentConfig` with `controls` (a `state` select +
+ scalar knobs), `componentName`, `importPath`, and a `snippet(values)` that
+ emits the controlled snap form (`<Comp state="…" />`, default-equal props
+ omitted). `speed` comes from `SHARED_CONTROLS`.
+- Register the component in `registry/__index__.tsx` (`{ Component, config }`).
+ The customizer Player passes control values straight to the component.
+- **`<ComponentPreview name="<name>" />`** = the interactive customizer (single
+ state, snap, live motion atoms).
+- **`<LiveExample name="<name>-example" />`** = ONE fixed, non-adjustable demo
+ (Player video + copyable code) showing a full smooth lifecycle. **Naming
+ convention (locked): the example is `<name>-example`** — `button-example`,
+ later `input-example`, `checkbox-example`, … Register it in
+ `components/docs/examples/index.tsx` and author the scene + a user-facing code
+ string (install paths) in `components/docs/examples/<name>-example.tsx`; keep
+ the scene's step timeline and the code string IN SYNC.
+
+---
+
+## 9. Docs
+
+- One page per component: `content/docs/ui/<name>.mdx`, listed in
+ `content/docs/ui/meta.json`.
+- **MDX frontmatter is unquoted YAML — never use a colon-space (`: `) in
+ `title`/`description`** (it breaks the fumadocs build). Use `—` or rephrase.
+- Include `<ComponentPreview>`, `<InstallBlock>`, a "Smooth transitions" section
+ (`use<Name>Transition`), the `<LiveExample>`, and a `<PropsTable>`.
+
+---
+
+## 10. Tests (bun:test)
+
+- Render output needs `useCurrentFrame()` → NOT unit-tested. Test the PURE
+ surface only: the core resolvers (spec-mirror in `core/__tests__/timeline.test.ts`),
+ the exported `<name>Style` presets + `tween<Name>Style`, and `config` snippet
+ codegen.
+- Mirror impure folds (anything calling `useCurrentFrame`) as pure replicas with
+ the frame injected as `raw`; annotate the source lines they mirror and keep
+ them in lockstep.
+- Use relative imports for component source, `@/lib/remocn-ui` for the core
+ alias. Add a `__tests__/README.md` with the determinism grep checklist.
+
+---
+
+## 11. Naming cheat-sheet
+
+| Thing | Convention | Example |
+|---|---|---|
+| Component dir / install name | kebab | `button`, `spinner` |
+| Component export | PascalCase | `Button`, `Spinner` |
+| State union | `<Name>State` | `ButtonState` |
+| Visual / preset / ctx | `<Name>Style` / `<name>Style` / `<name>StyleContext` | `ButtonStyle` |
+| Transition file | `use-<name>-transition.ts` | `use-button-transition.ts` |
+| Transition hook | `use<Name>Transition` | `useButtonTransition` |
+| Tween | `tween<Name>Style` | `tweenButtonStyle` |
+| Live example | `<name>-example` | `button-example` |
+| Docs page | `content/docs/ui/<name>.mdx` | `button.mdx` |
diff --git a/registry/remocn-ui/button/__tests__/README.md b/registry/remocn-ui/button/__tests__/README.md
index 460fea04..8c2fbed1 100644
--- a/registry/remocn-ui/button/__tests__/README.md
+++ b/registry/remocn-ui/button/__tests__/README.md
@@ -3,8 +3,34 @@
Pure / deterministic verification for the `button` component
(`registry/remocn-ui/button/`). The RENDER path needs Remotion's
`useCurrentFrame()` and cannot run headless, so the render is NOT exercised
-here. This suite covers the pieces that ARE pure: the `BUTTON_SCENARIOS` data
-shape, the reducer's phase mapping, and `buttonConfig.snippet` codegen.
+here. This suite covers the pieces that ARE pure: `ButtonState` union
+membership, `buttonConfig.controls.state` wiring, `buttonConfig.snippet`
+codegen, `buttonStyle` presets, and `tweenButtonStyle` interpolation.
+
+## Animation model — pure snap + opt-in smooth path
+
+Button ships two complementary paths:
+
+**Snap path** (`state?: ButtonState` prop):
+`Button` is a frame-free pure renderer. The `state` prop drives all visuals.
+Each state maps to a complete resting visual via the exported pure function
+`buttonStyle(state, ctx) => ButtonStyle`. State changes snap instantly — no
+tweening inside the component.
+
+**Smooth path** (`style?: ButtonStyle` prop):
+Callers opt in to smooth transitions by passing a pre-interpolated `ButtonStyle`
+to the `style` prop. The caller — typically `useButtonTransition` — reads
+`useCurrentFrame()` and calls `useStateTransition` from `core/timeline.ts` to
+compute `{ from, to, progress }`, then blends the two presets via
+`tweenButtonStyle(from, to, t)`. The `Button` component itself remains
+frame-free; it simply renders whatever `ButtonStyle` it receives.
+
+This design keeps `Button` pure-testable (no Remotion render context needed)
+while still supporting smooth enter-transitions for production use.
+
+The loading spinner lives in the separate `<Spinner/>` **motion atom** which
+reads `useCurrentFrame()` internally — that is correct and expected for motion
+atoms. See `registry/remocn-ui/spinner/__tests__/README.md`.
## How to run
@@ -21,63 +47,70 @@ or framework dep is added to `package.json`.
## What is covered
-- **`BUTTON_SCENARIOS` validity** — REAL export, plain data. Asserts: exactly the
- four scenario keys; every step has a numeric, non-negative `at`; every
- `action` is in the `ButtonAction` union; `idle` is empty; `happy`/`error` have
- strictly increasing `at`; `happy` ends with `success`; `error` ends with
- `reset`; `loading` is a single `loading` step.
-- **Reducer phase mapping** — the reducer is **NOT exported** (module-private
- `function reducer` in `index.tsx:88-107`). The phase map is replicated as a
- SPEC MIRROR (`hover→hover, press→press, release→hover, loading→loading,
- success→success, reset→error`) and folded over each scenario: `idle`→`idle`,
- `happy`→`success`, `error`→`error`, `loading`→`loading`. The mirror is
- cross-checked against the scenarios' last actions. See testability gap below.
-- **`buttonConfig.snippet`** — REAL pure string builder (high value). Asserts:
- emits `steps={[`; never leaks `scenario`; includes `import { Button }`;
- omits props equal to defaults (`label=Continue`, `variant=default`,
- `size=default`, `mode=light`); EMITS non-default `label`/`variant`/`size`/
- `mode`; defaults scenario to `happy`; embeds each `BUTTON_SCENARIOS.happy`
- step's `at`/`action`; `idle`→`steps={[]}`; entry count matches per scenario;
- structural round-trip (starts with import, contains `<Button`, ends `/>`).
-- **`serializeSteps` emission** — NOT exported (module-private in
- `config.ts:9-19`). Replicated as a SPEC MIRROR (`[]` for empty, omits/includes
- `duration`) and the mirror's `happy` output is asserted to be a SUBSTRING of
- the REAL snippet, proving the mirror tracks the real serializer.
+- **`ButtonState` union** — asserts the five states
+ `["idle","hover","press","loading","success"]` are the complete set (via the
+ real `controls.state.options` list from `config.ts`).
+- **`buttonConfig.controls.state`** — the customizer control wiring. Asserts a
+ `select` control exists with exactly those five options, default `"loading"`
+ (so the preview showcases the live Spinner), and that every option is a
+ member of the `ButtonState` union.
+- **`buttonConfig.snippet`** — REAL pure string builder (high value).
+ Asserts: emits `state="<state>"` as a bare JSX prop for every option; NEVER
+ emits `steps` or `action`; includes `import { Button }` from
+ `@/components/remocn/button`; omits default-equal props (`label=Continue`,
+ `variant=default`, `size=default`, `mode=light`, `primary=#171717`); EMITS
+ non-default `label`/`variant`/`size`/`mode`/`primary`; structural round-trip
+ (starts with import, contains `<Button`, ends `/>`).
+- **`buttonStyle` presets** — exported pure `(state, ctx) => ButtonStyle` map.
+ A `ButtonStyleContext` is built from `buttonStyleContext("default",
+ defaultLightTheme)` — the same call the component makes internally. Asserts
+ per-state numeric/opacity invariants (translateY, scale, labelOpacity,
+ spinnerOpacity, checkOpacity) and that `background` is always a non-empty
+ string. Also asserts the sum of the three opacity fields equals 1 for every
+ state (exactly one of label/spinner/check is visible at any resting state).
+- **`tweenButtonStyle`** — exported pure `(a, b, t) => ButtonStyle`. Asserts:
+ at t=0 all numeric fields equal `a`; at t=1 all equal `b`; at t=0.5 each
+ numeric field is the exact midpoint (e.g. translateY 0→−1 gives −0.5,
+ scale 1→0.97 gives 0.985, spinnerOpacity 0→1 gives 0.5). `background` at
+ all t is a non-empty string (the oklch mix value is not hardcoded).
+
+**Button render** is a pure `(style | state) => visual` observable only via
+Remotion render, not unit-tested here.
## Import strategy
-`button.test.ts` imports the REAL `BUTTON_SCENARIOS` (from `../index`) and
-the REAL `buttonConfig` (from `../config`) via **relative paths** — matching
-`ui-core/__tests__/color.test.ts`, which uses `../color`, not the `@/` alias.
-`bun test` does resolve tsconfig `paths`, but relative imports are the proven,
-alias-independent form used by the existing suite. Importing `index.tsx` pulls
-the `remotion` module, but the pieces under test never CALL `useCurrentFrame()`
-at import time (`BUTTON_SCENARIOS` is an object literal; `.snippet` is a pure
-function), so no Remotion render tree is required.
-
-> If `bun test` cannot resolve `remotion` at import (e.g. the package is not
-> installed), switch the top two imports to a local re-derivation: copy the
-> `BUTTON_SCENARIOS` literal and the `snippet`/`serializeSteps` bodies as
-> annotated MIRRORS — the section 2 and section 4 mirrors already demonstrate
-> the pattern. The numeric/string expectations are the verification value; the
-> import is just the harness.
+`button.test.ts` imports via a mix of **relative paths** and the
+**`@/lib/remocn-ui` tsconfig alias**:
+
+- `../index` — relative, for `ButtonState`, `buttonStyle`, `buttonStyleContext`
+- `../use-button-transition` — relative, for `tweenButtonStyle`
+- `../config` — relative, for `buttonConfig`
+- `@/lib/remocn-ui` — alias (resolves to `registry/remocn-ui/core/index.ts`),
+ for `defaultLightTheme`
+
+Importing `index.tsx` and `use-button-transition.ts` pulls the `remotion`
+module (and React), but neither `buttonStyle`, `buttonStyleContext`, nor
+`tweenButtonStyle` call `useCurrentFrame()` at import time or at call time —
+they are pure value functions. `bun test` resolves tsconfig `paths`, so the
+alias works without additional config.
## 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 in the tier source.
-Verify `button` (and the rest of the tier) with:
+Button is frame-free. The component must contain **none** of the following:
```bash
-grep -nE "useState|useEffect|onClick|onChange|addEventListener|Date\.now|Math\.random" \
+grep -nE "useCurrentFrame|useState|useEffect|onClick|onChange|addEventListener|Date\.now|Math\.random" \
registry/remocn-ui/button/index.tsx
```
-Expected: no output (exit code 1). Any match is a determinism violation. The
-spinner rotation in `button` is driven by `frame * speed * 6` (the injected
-playhead), NOT `Date.now()` / RAF — keep it that way.
+Expected: no output. Any match is a determinism violation.
+
+`use-button-transition.ts` is the CALLER hook that intentionally reads
+`useCurrentFrame()` (via `useStateTransition`). It is not a render component;
+the smooth-path design isolates all frame-reading to the hook, keeping
+`Button` pure.
-Tier-wide sweep (mirrors the ui-core checklist):
+Tier-wide sweep:
```bash
grep -nE "useState|useEffect|onClick|onChange|addEventListener|Date\.now|Math\.random" \
diff --git a/registry/remocn-ui/button/__tests__/button.test.ts b/registry/remocn-ui/button/__tests__/button.test.ts
index a9f77119..44adb8b5 100644
--- a/registry/remocn-ui/button/__tests__/button.test.ts
+++ b/registry/remocn-ui/button/__tests__/button.test.ts
@@ -2,366 +2,553 @@
* Verification tests for the PURE / DETERMINISTIC parts of `button`.
*
* Scope:
- * - registry/remocn-ui/button/index.tsx — BUTTON_SCENARIOS shape + the
- * (module-private) reducer's phase mapping.
- * - registry/remocn-ui/button/config.ts — buttonConfig.snippet output +
- * the (module-private) serializeSteps emission.
+ * - registry/remocn-ui/button/index.tsx — ButtonState union membership
+ * - registry/remocn-ui/button/config.ts — buttonConfig.controls.state
+ * wiring + buttonConfig.snippet output (the state → JSX codegen)
+ *
+ * The render path (index.tsx) is a PURE-STATE model: `(state) => visual`.
+ * Every visual is the complete resting look for that state — state changes
+ * snap (no tweening). The loading spinner lives in the separate `<Spinner/>`
+ * motion atom which reads `useCurrentFrame()` internally; it cannot run
+ * outside a Remotion render tree. So Button render is NOT exercised here.
+ * The pure-testable surface is the customizer wiring + snippet codegen (below).
*
* Runner: Bun's built-in test runner (TypeScript-native, no framework dep).
* bun test registry/remocn-ui/button/__tests__
*
* --------------------------------------------------------------------------
- * IMPORT STRATEGY — why we import REAL code here (unlike ui-core/timeline)
+ * IMPORT STRATEGY
* --------------------------------------------------------------------------
- * `index.tsx` and `config.ts` both top-level `import { … } from "remotion"`
- * (index) / re-use BUTTON_SCENARIOS (config). The ui-core `timeline.test.ts`
- * REPLICATED its fold because the impure part — `useCurrentFrame()` — is CALLED
- * at module evaluation inside a hook. Here, by contrast, the pieces under test
- * (`BUTTON_SCENARIOS`, `buttonConfig.snippet`, the reducer) never CALL a
- * Remotion runtime API at import time:
- * - `BUTTON_SCENARIOS` is a plain object literal.
- * - `buttonConfig.snippet` is a pure string builder.
- * Importing `remotion` only registers its module; it does not invoke
- * `useCurrentFrame`. So we import the REAL source via RELATIVE paths (matching
- * `color.test.ts` which uses `../color`, NOT the `@/` alias — `bun test` does
- * resolve tsconfig `paths`, but relative is the proven, alias-independent form).
- *
- * The reducer is NOT exported (module-private `function reducer` in index.tsx).
- * We therefore (a) assert everything reachable about it INDIRECTLY via the
- * scenario shapes, and (b) replicate its documented phase mapping as a SPEC
- * MIRROR (annotated with source line ranges) so the phase contract is pinned.
- * See TESTABILITY GAP note at the bottom.
- *
- * MAINTENANCE CONTRACT: if index.tsx's reducer body or config.ts's
- * serializeSteps body changes, the MIRROR replicas below MUST be updated in
- * lockstep. The replicas are annotated with the source line ranges they mirror.
+ * `config.ts` imports `ButtonState` from `@/registry/remocn-ui/button` and
+ * the pieces under test never CALL a Remotion runtime API at import time —
+ * `buttonConfig` is a plain object; `.snippet` is a pure string builder.
+ * We import via RELATIVE paths (matching the existing test suite pattern),
+ * annotating each import with the source it corresponds to.
* --------------------------------------------------------------------------
*/
import { describe, expect, it } from "bun:test";
-import {
- BUTTON_SCENARIOS,
- type ButtonAction,
- type ButtonPhase,
- type ButtonScenario,
-} from "../index";
+import { type ButtonState, buttonStyle, buttonStyleContext } from "../index";
+import { tweenButtonStyle } from "../use-button-transition";
import { buttonConfig } from "../config";
+import { defaultLightTheme } from "@/lib/remocn-ui";
// ===========================================================================
// Shared fixtures
// ===========================================================================
-/** The ButtonAction union, enumerated as a runtime list for membership checks. */
-const VALID_ACTIONS: readonly ButtonAction[] = [
+/**
+ * The ButtonState union, enumerated as a runtime list for membership checks.
+ * Must stay in sync with `export type ButtonState` in index.tsx.
+ */
+const VALID_STATES: readonly ButtonState[] = [
+ "idle",
"hover",
"press",
- "release",
"loading",
"success",
- "reset",
];
-const SCENARIO_KEYS: readonly ButtonScenario[] = [
- "happy",
- "loading",
- "error",
- "idle",
-];
+/** Minimal shape mirroring the customizer's value bag passed to snippet(). */
+type SnippetValues = {
+ state?: string;
+ label?: string;
+ variant?: string;
+ size?: string;
+ mode?: string;
+ primary?: string;
+};
+
+const snippet = (values: SnippetValues): string =>
+ buttonConfig.snippet(values as Record<string, unknown>);
// ===========================================================================
-// 1. BUTTON_SCENARIOS validity (real export, plain data — fully pure)
+// 1. ButtonState union membership
// ===========================================================================
-describe("BUTTON_SCENARIOS", () => {
- it("exposes exactly the four documented scenario keys", () => {
- expect(Object.keys(BUTTON_SCENARIOS).sort()).toEqual(
- [...SCENARIO_KEYS].sort(),
- );
+describe("ButtonState union", () => {
+ it("contains exactly the five documented states", () => {
+ // We can't enumerate a TS type at runtime, but we can assert the REAL
+ // controls.state options match and that all known states are members.
+ const control = buttonConfig.controls.state;
+ if (control.type !== "select") throw new Error("state control must be a select");
+ expect(control.options).toEqual([
+ "idle",
+ "hover",
+ "press",
+ "loading",
+ "success",
+ ]);
});
- it("every step in every scenario has a numeric, non-negative `at`", () => {
- for (const key of SCENARIO_KEYS) {
- for (const step of BUTTON_SCENARIOS[key]) {
- expect(typeof step.at).toBe("number");
- expect(Number.isFinite(step.at)).toBe(true);
- expect(step.at).toBeGreaterThanOrEqual(0);
- }
+ it("every VALID_STATES entry is assignable (no typos in the fixture)", () => {
+ // Belt-and-suspenders: the fixture array must have exactly 5 entries and
+ // match the options list from the real config.
+ const control = buttonConfig.controls.state;
+ if (control.type !== "select") throw new Error("state control must be a select");
+ expect(VALID_STATES).toHaveLength(5);
+ for (const s of VALID_STATES) {
+ expect(control.options).toContain(s);
}
});
+});
- it("every step's `action` is a member of the ButtonAction union", () => {
- for (const key of SCENARIO_KEYS) {
- for (const step of BUTTON_SCENARIOS[key]) {
- expect(VALID_ACTIONS).toContain(step.action);
- }
+// ===========================================================================
+// 2. buttonConfig.controls.state — customizer control wiring
+// ===========================================================================
+
+describe("buttonConfig.controls.state", () => {
+ it("is a select control", () => {
+ expect(buttonConfig.controls.state.type).toBe("select");
+ });
+
+ it("has exactly the five ButtonState options in order", () => {
+ const control = buttonConfig.controls.state;
+ if (control.type !== "select") throw new Error("state control must be a select");
+ expect(control.options).toEqual([
+ "idle",
+ "hover",
+ "press",
+ "loading",
+ "success",
+ ]);
+ });
+
+ it("defaults to 'loading' so the preview showcases the live Spinner", () => {
+ const control = buttonConfig.controls.state;
+ expect(control.default).toBe("loading");
+ });
+
+ it("every option is a member of the ButtonState union", () => {
+ const control = buttonConfig.controls.state;
+ if (control.type !== "select") throw new Error("state control must be a select");
+ for (const option of control.options) {
+ expect(VALID_STATES).toContain(option as ButtonState);
}
});
+});
+
+// ===========================================================================
+// 3. buttonConfig.snippet — pure string builder
+// State model: snippet emits `state="<state>"` as a bare JSX prop.
+// It NEVER emits `steps` or `action`.
+// ===========================================================================
+
+describe("buttonConfig.snippet: state prop emission", () => {
+ it("emits state=\"idle\" for the idle option", () => {
+ expect(snippet({ state: "idle" })).toContain('state="idle"');
+ });
+
+ it("emits state=\"hover\" for the hover option", () => {
+ expect(snippet({ state: "hover" })).toContain('state="hover"');
+ });
- it("`idle` is empty", () => {
- expect(BUTTON_SCENARIOS.idle).toEqual([]);
+ it("emits state=\"press\" for the press option", () => {
+ expect(snippet({ state: "press" })).toContain('state="press"');
});
- it("`happy` and `error` have strictly increasing `at` values", () => {
- for (const key of ["happy", "error"] as const) {
- const ats = BUTTON_SCENARIOS[key].map((s) => s.at);
- for (let i = 1; i < ats.length; i++) {
- expect(ats[i]).toBeGreaterThan(ats[i - 1]);
- }
+ it("emits state=\"loading\" for the loading option", () => {
+ expect(snippet({ state: "loading" })).toContain('state="loading"');
+ });
+
+ it("emits state=\"success\" for the success option", () => {
+ expect(snippet({ state: "success" })).toContain('state="success"');
+ });
+
+ it("emits the correct state for every control option", () => {
+ const control = buttonConfig.controls.state;
+ if (control.type !== "select") throw new Error("state control must be a select");
+ for (const state of control.options) {
+ const out = snippet({ state });
+ expect(out).toContain(`state="${state}"`);
}
});
+});
- it("`happy` ends with a `success` action", () => {
- const steps = BUTTON_SCENARIOS.happy;
- expect(steps.length).toBeGreaterThan(0);
- expect(steps[steps.length - 1].action).toBe("success");
+describe("buttonConfig.snippet: NEVER emits steps or action", () => {
+ it("never emits `steps` in any state", () => {
+ for (const state of VALID_STATES) {
+ expect(snippet({ state })).not.toContain("steps");
+ }
+ });
+
+ it("never emits `action` in any state", () => {
+ for (const state of VALID_STATES) {
+ expect(snippet({ state })).not.toContain("action");
+ }
+ });
+});
+
+describe("buttonConfig.snippet: import line", () => {
+ it("includes `import { Button }` from the correct path", () => {
+ const out = snippet({ state: "loading" });
+ expect(out).toContain('import { Button }');
+ expect(out).toContain('from "@/components/remocn/button"');
+ });
+});
+
+describe("buttonConfig.snippet: default props are omitted", () => {
+ // Defaults: label=Continue, variant=default, size=default, mode=light, primary=#171717
+ const allDefaults = snippet({
+ state: "loading",
+ label: "Continue",
+ variant: "default",
+ size: "default",
+ mode: "light",
+ primary: "#171717",
+ });
+
+ it("omits label when it equals the default 'Continue'", () => {
+ expect(allDefaults).not.toContain("label=");
+ });
+
+ it("omits variant when it equals the default 'default'", () => {
+ expect(allDefaults).not.toContain("variant=");
+ });
+
+ it("omits size when it equals the default 'default'", () => {
+ expect(allDefaults).not.toContain("size=");
+ });
+
+ it("omits mode when it equals the default 'light'", () => {
+ expect(allDefaults).not.toContain("mode=");
+ });
+
+ it("omits primary when it equals the default '#171717'", () => {
+ expect(allDefaults).not.toContain("primary=");
+ });
+});
+
+describe("buttonConfig.snippet: non-default props are emitted", () => {
+ it("emits a non-default label", () => {
+ expect(snippet({ state: "success", label: "Submit" })).toContain('label="Submit"');
+ });
+
+ it("emits a non-default variant", () => {
+ expect(snippet({ state: "success", variant: "destructive" })).toContain('variant="destructive"');
+ });
+
+ it("emits a non-default size", () => {
+ expect(snippet({ state: "success", size: "lg" })).toContain('size="lg"');
+ });
+
+ it("emits a non-default mode", () => {
+ expect(snippet({ state: "success", mode: "dark" })).toContain('mode="dark"');
+ });
+
+ it("emits a non-default primary color", () => {
+ expect(snippet({ state: "success", primary: "#6366f1" })).toContain('primary="#6366f1"');
});
+});
+
+describe("buttonConfig.snippet: structural round-trip", () => {
+ const out = snippet({ state: "loading" });
- it("`error` ends with a `reset` action", () => {
- const steps = BUTTON_SCENARIOS.error;
- expect(steps.length).toBeGreaterThan(0);
- expect(steps[steps.length - 1].action).toBe("reset");
+ it("starts with the import line", () => {
+ expect(out.startsWith('import { Button }')).toBe(true);
});
- it("`loading` is a single `loading` step", () => {
- expect(BUTTON_SCENARIOS.loading).toHaveLength(1);
- expect(BUTTON_SCENARIOS.loading[0].action).toBe("loading");
+ it("contains a <Button JSX opening", () => {
+ expect(out).toContain("<Button");
+ });
+
+ it("ends with a self-closing />", () => {
+ expect(out.trimEnd().endsWith("/>")).toBe(true);
});
});
// ===========================================================================
-// 2. Reducer phase mapping — MIRROR of index.tsx reducer (lines 90-109)
-// The reducer is NOT exported; this replica pins the documented contract.
-// See TESTABILITY GAP note at the bottom of this file.
+// 4. buttonStyle presets — pure (state, ctx) => ButtonStyle
+// buttonStyleContext and buttonStyle are now exported and frame-free.
+// Build one ctx from the default light theme + "default" variant, then
+// assert the numeric/opacity invariants for every state.
+// background is a derived oklch/rgb string — asserted non-empty only
+// (its exact value is an implementation detail of mixOklch).
// ===========================================================================
-/**
- * MIRROR of the module-private `reducer` in index.tsx (lines 90-109) plus the
- * DEFAULT_STATE seed (line 79). Phase per action:
- * hover→hover, press→press, release→hover, loading→loading,
- * success→success, reset→idle (the destructive flash is IN-FLIGHT ONLY via
- * isActiveReset; once the reset window closes the button settles to idle).
- */
-const PHASE_AFTER_ACTION: Record<ButtonAction, ButtonPhase> = {
- hover: "hover",
- press: "press",
- release: "hover",
- loading: "loading",
- success: "success",
- reset: "idle",
-};
+const ctx = buttonStyleContext("default", defaultLightTheme);
-/** MIRROR fold: seed = idle, apply each step's action via the map. */
-function phaseAfter(steps: { action: ButtonAction }[]): ButtonPhase {
- let phase: ButtonPhase = "idle";
- for (const step of steps) {
- phase = PHASE_AFTER_ACTION[step.action];
- }
- return phase;
-}
+describe("buttonStyle: idle state", () => {
+ const s = buttonStyle("idle", ctx);
-describe("reducer phase mapping (spec mirror of index.tsx:88-107)", () => {
- it("each action maps to its documented terminal phase", () => {
- expect(PHASE_AFTER_ACTION.hover).toBe("hover");
- expect(PHASE_AFTER_ACTION.press).toBe("press");
- expect(PHASE_AFTER_ACTION.release).toBe("hover");
- expect(PHASE_AFTER_ACTION.loading).toBe("loading");
- expect(PHASE_AFTER_ACTION.success).toBe("success");
- // `reset` settles to idle. The destructive flash is in-flight only
- // (driven by isActiveReset in the render path), NOT a settled phase.
- expect(PHASE_AFTER_ACTION.reset).toBe("idle");
+ it("translateY is 0 (at rest, not lifted)", () => {
+ expect(s.translateY).toBe(0);
});
- it("folding `idle` (empty) stays idle", () => {
- expect(phaseAfter(BUTTON_SCENARIOS.idle)).toBe("idle");
+ it("scale is 1 (no shrink)", () => {
+ expect(s.scale).toBe(1);
});
- it("folding `happy` lands on `success`", () => {
- expect(phaseAfter(BUTTON_SCENARIOS.happy)).toBe("success");
+ it("labelOpacity is 1 (label visible)", () => {
+ expect(s.labelOpacity).toBe(1);
});
- it("folding `error` lands on `idle` (reset settles to idle, flash is in-flight only)", () => {
- expect(phaseAfter(BUTTON_SCENARIOS.error)).toBe("idle");
+ it("spinnerOpacity is 0 (spinner hidden)", () => {
+ expect(s.spinnerOpacity).toBe(0);
});
- it("folding `loading` lands on `loading`", () => {
- expect(phaseAfter(BUTTON_SCENARIOS.loading)).toBe("loading");
+ it("checkOpacity is 0 (check hidden)", () => {
+ expect(s.checkOpacity).toBe(0);
});
- it("the terminal phase agrees with the scenario's last action", () => {
- for (const key of SCENARIO_KEYS) {
- const steps = BUTTON_SCENARIOS[key];
- if (steps.length === 0) {
- expect(phaseAfter(steps)).toBe("idle");
- continue;
- }
- const lastAction = steps[steps.length - 1].action;
- expect(phaseAfter(steps)).toBe(PHASE_AFTER_ACTION[lastAction]);
+ it("background is a non-empty string", () => {
+ expect(typeof s.background).toBe("string");
+ expect(s.background.length).toBeGreaterThan(0);
+ });
+});
+
+describe("buttonStyle: hover state", () => {
+ const s = buttonStyle("hover", ctx);
+
+ it("translateY is -1 (button lifts)", () => {
+ expect(s.translateY).toBe(-1);
+ });
+
+ it("scale is 1 (no shrink on hover)", () => {
+ expect(s.scale).toBe(1);
+ });
+
+ it("labelOpacity is 1 (label stays visible)", () => {
+ expect(s.labelOpacity).toBe(1);
+ });
+
+ it("spinnerOpacity is 0", () => {
+ expect(s.spinnerOpacity).toBe(0);
+ });
+
+ it("checkOpacity is 0", () => {
+ expect(s.checkOpacity).toBe(0);
+ });
+
+ it("background is a non-empty string", () => {
+ expect(typeof s.background).toBe("string");
+ expect(s.background.length).toBeGreaterThan(0);
+ });
+});
+
+describe("buttonStyle: press state", () => {
+ const s = buttonStyle("press", ctx);
+
+ it("translateY is -1", () => {
+ expect(s.translateY).toBe(-1);
+ });
+
+ it("scale is 0.97 (slight shrink on press)", () => {
+ expect(s.scale).toBeCloseTo(0.97, 10);
+ });
+
+ it("labelOpacity is 1", () => {
+ expect(s.labelOpacity).toBe(1);
+ });
+
+ it("spinnerOpacity is 0", () => {
+ expect(s.spinnerOpacity).toBe(0);
+ });
+
+ it("checkOpacity is 0", () => {
+ expect(s.checkOpacity).toBe(0);
+ });
+
+ it("background is a non-empty string", () => {
+ expect(typeof s.background).toBe("string");
+ expect(s.background.length).toBeGreaterThan(0);
+ });
+});
+
+describe("buttonStyle: loading state", () => {
+ const s = buttonStyle("loading", ctx);
+
+ it("labelOpacity is 0 (label hidden while loading)", () => {
+ expect(s.labelOpacity).toBe(0);
+ });
+
+ it("spinnerOpacity is 1 (spinner fully visible)", () => {
+ expect(s.spinnerOpacity).toBe(1);
+ });
+
+ it("checkOpacity is 0 (check not yet shown)", () => {
+ expect(s.checkOpacity).toBe(0);
+ });
+
+ it("background is a non-empty string", () => {
+ expect(typeof s.background).toBe("string");
+ expect(s.background.length).toBeGreaterThan(0);
+ });
+});
+
+describe("buttonStyle: success state", () => {
+ const s = buttonStyle("success", ctx);
+
+ it("labelOpacity is 0 (label replaced by check)", () => {
+ expect(s.labelOpacity).toBe(0);
+ });
+
+ it("spinnerOpacity is 0 (spinner gone)", () => {
+ expect(s.spinnerOpacity).toBe(0);
+ });
+
+ it("checkOpacity is 1 (checkmark fully visible)", () => {
+ expect(s.checkOpacity).toBe(1);
+ });
+
+ it("background is a non-empty string", () => {
+ expect(typeof s.background).toBe("string");
+ expect(s.background.length).toBeGreaterThan(0);
+ });
+});
+
+describe("buttonStyle: opacity invariant — exactly one of label/spinner/check is visible per non-idle state", () => {
+ // For non-animated states the three opacities are always discrete 0 or 1.
+ const states: ButtonState[] = ["idle", "hover", "press", "loading", "success"];
+
+ it("sum of label+spinner+check opacities equals 1 for every state (exactly one is shown)", () => {
+ for (const state of states) {
+ const s = buttonStyle(state, ctx);
+ const sum = s.labelOpacity + s.spinnerOpacity + s.checkOpacity;
+ expect(sum).toBe(1);
}
});
});
// ===========================================================================
-// 3. buttonConfig.snippet — REAL pure string builder (high value)
+// 5. tweenButtonStyle — pure linear interpolation between two ButtonStyles.
+// Numbers lerp linearly; background is an oklch color string at all t.
+// Concrete expectations: idle(translateY=0,scale=1) → hover(translateY=-1,scale=1)
+// and idle(spinnerOpacity=0) → loading(spinnerOpacity=1) for midpoint math.
// ===========================================================================
-/** Minimal shape mirroring the customizer's value bag passed to snippet(). */
-type SnippetValues = {
- scenario?: string;
- label?: string;
- variant?: string;
- size?: string;
- mode?: string;
- primary?: string;
-};
+describe("tweenButtonStyle: t=0 returns values equal to `a`", () => {
+ const a = buttonStyle("idle", ctx);
+ const b = buttonStyle("hover", ctx);
+ const r = tweenButtonStyle(a, b, 0);
-const snippet = (values: SnippetValues): string =>
- buttonConfig.snippet(values as Record<string, unknown>);
+ it("translateY equals a.translateY at t=0", () => {
+ expect(r.translateY).toBeCloseTo(a.translateY, 10);
+ });
-describe("buttonConfig.snippet", () => {
- const happy = snippet({
- scenario: "happy",
- label: "Continue",
- variant: "default",
- size: "default",
- mode: "light",
- primary: "#171717",
+ it("scale equals a.scale at t=0", () => {
+ expect(r.scale).toBeCloseTo(a.scale, 10);
});
- it("emits the `steps={[` literal", () => {
- expect(happy).toContain("steps={[");
+ it("labelOpacity equals a.labelOpacity at t=0", () => {
+ expect(r.labelOpacity).toBeCloseTo(a.labelOpacity, 10);
});
- it("does NOT leak the `scenario` prop into the snippet", () => {
- // scenario is resolved to steps at snippet time; it must never appear as a
- // prop or key in the emitted JSX.
- expect(happy).not.toContain("scenario");
+ it("spinnerOpacity equals a.spinnerOpacity at t=0", () => {
+ expect(r.spinnerOpacity).toBeCloseTo(a.spinnerOpacity, 10);
});
- it("includes the `import { Button }` line", () => {
- expect(happy).toContain('import { Button }');
- expect(happy).toContain('from "@/components/remocn/button"');
+ it("checkOpacity equals a.checkOpacity at t=0", () => {
+ expect(r.checkOpacity).toBeCloseTo(a.checkOpacity, 10);
});
- it("omits all props that equal their defaults", () => {
- // label=Continue, variant=default, size=default, mode=light, primary=#171717
- // are all defaults → only `steps` should remain.
- expect(happy).not.toContain("label=");
- expect(happy).not.toContain("variant=");
- expect(happy).not.toContain("size=");
- expect(happy).not.toContain("mode=");
- expect(happy).not.toContain("primary=");
- expect(happy).toContain("steps={");
+ it("background is a non-empty string at t=0", () => {
+ expect(typeof r.background).toBe("string");
+ expect(r.background.length).toBeGreaterThan(0);
});
+});
+
+describe("tweenButtonStyle: t=1 returns values equal to `b`", () => {
+ const a = buttonStyle("idle", ctx);
+ const b = buttonStyle("hover", ctx);
+ const r = tweenButtonStyle(a, b, 1);
- it("emits a non-default `label`", () => {
- const out = snippet({ scenario: "happy", label: "Submit" });
- expect(out).toContain('label="Submit"');
+ it("translateY equals b.translateY at t=1", () => {
+ expect(r.translateY).toBeCloseTo(b.translateY, 10);
});
- it("emits a non-default `variant`", () => {
- const out = snippet({ scenario: "happy", variant: "destructive" });
- expect(out).toContain('variant="destructive"');
+ it("scale equals b.scale at t=1", () => {
+ expect(r.scale).toBeCloseTo(b.scale, 10);
});
- it("emits a non-default `size`", () => {
- const out = snippet({ scenario: "happy", size: "lg" });
- expect(out).toContain('size="lg"');
+ it("labelOpacity equals b.labelOpacity at t=1", () => {
+ expect(r.labelOpacity).toBeCloseTo(b.labelOpacity, 10);
});
- it("emits a non-default `mode`", () => {
- const out = snippet({ scenario: "happy", mode: "dark" });
- expect(out).toContain('mode="dark"');
+ it("spinnerOpacity equals b.spinnerOpacity at t=1", () => {
+ expect(r.spinnerOpacity).toBeCloseTo(b.spinnerOpacity, 10);
});
- it("omits `primary` when it equals the default #171717", () => {
- const out = snippet({ scenario: "happy", primary: "#171717" });
- expect(out).not.toContain("primary=");
+ it("checkOpacity equals b.checkOpacity at t=1", () => {
+ expect(r.checkOpacity).toBeCloseTo(b.checkOpacity, 10);
});
- it("emits a non-default `primary`", () => {
- const out = snippet({ scenario: "happy", primary: "#6366f1" });
- expect(out).toContain('primary="#6366f1"');
+ it("background is a non-empty string at t=1", () => {
+ expect(typeof r.background).toBe("string");
+ expect(r.background.length).toBeGreaterThan(0);
});
+});
+
+describe("tweenButtonStyle: t=0.5 midpoint numeric lerp (idle → hover)", () => {
+ // idle: translateY=0, scale=1, labelOpacity=1, spinnerOpacity=0, checkOpacity=0
+ // hover: translateY=-1, scale=1, labelOpacity=1, spinnerOpacity=0, checkOpacity=0
+ const a = buttonStyle("idle", ctx);
+ const b = buttonStyle("hover", ctx);
+ const r = tweenButtonStyle(a, b, 0.5);
- it("defaults scenario to `happy` when omitted", () => {
- const withDefault = snippet({});
- const explicitHappy = snippet({ scenario: "happy" });
- expect(withDefault).toBe(explicitHappy);
+ it("translateY midpoint: 0 → -1 gives -0.5", () => {
+ expect(r.translateY).toBeCloseTo(-0.5, 10);
});
- it("serializes each happy step's `at` and `action` into the steps literal", () => {
- for (const step of BUTTON_SCENARIOS.happy) {
- expect(happy).toContain(`at: ${step.at}`);
- expect(happy).toContain(`action: "${step.action}"`);
- }
+ it("scale midpoint: 1 → 1 gives 1 (both same)", () => {
+ expect(r.scale).toBeCloseTo(1, 10);
});
- it("emits `steps={[]}` for the empty `idle` scenario", () => {
- const out = snippet({ scenario: "idle" });
- expect(out).toContain("steps={[]}");
+ it("labelOpacity midpoint: 1 → 1 gives 1 (both same)", () => {
+ expect(r.labelOpacity).toBeCloseTo(1, 10);
});
- it("emits the right number of step entries for each scenario", () => {
- for (const key of SCENARIO_KEYS) {
- const out = snippet({ scenario: key });
- const entryCount = (out.match(/action:/g) ?? []).length;
- expect(entryCount).toBe(BUTTON_SCENARIOS[key].length);
- }
+ it("background is a non-empty string at t=0.5", () => {
+ expect(typeof r.background).toBe("string");
+ expect(r.background.length).toBeGreaterThan(0);
+ });
+});
+
+describe("tweenButtonStyle: t=0.5 midpoint numeric lerp (idle → loading)", () => {
+ // idle: translateY=0, scale=1, labelOpacity=1, spinnerOpacity=0, checkOpacity=0
+ // loading: translateY=-1, scale=1, labelOpacity=0, spinnerOpacity=1, checkOpacity=0
+ const a = buttonStyle("idle", ctx);
+ const b = buttonStyle("loading", ctx);
+ const r = tweenButtonStyle(a, b, 0.5);
+
+ it("translateY midpoint: 0 → -1 gives -0.5", () => {
+ expect(r.translateY).toBeCloseTo(-0.5, 10);
});
- it("produces output that round-trips to a valid-looking JSX block", () => {
- // Structural smoke: opens with the import, contains a self-closing Button.
- expect(happy.startsWith("import { Button }")).toBe(true);
- expect(happy).toContain("<Button");
- expect(happy.trimEnd().endsWith("/>")).toBe(true);
+ it("scale midpoint: 1 → 1 gives 1", () => {
+ expect(r.scale).toBeCloseTo(1, 10);
+ });
+
+ it("labelOpacity midpoint: 1 → 0 gives 0.5", () => {
+ expect(r.labelOpacity).toBeCloseTo(0.5, 10);
+ });
+
+ it("spinnerOpacity midpoint: 0 → 1 gives 0.5", () => {
+ expect(r.spinnerOpacity).toBeCloseTo(0.5, 10);
+ });
+
+ it("checkOpacity midpoint: 0 → 0 gives 0", () => {
+ expect(r.checkOpacity).toBeCloseTo(0, 10);
+ });
+
+ it("background is a non-empty string at t=0.5", () => {
+ expect(typeof r.background).toBe("string");
+ expect(r.background.length).toBeGreaterThan(0);
});
});
-// ===========================================================================
-// 4. serializeSteps emission — MIRROR of config.ts serializeSteps (lines 9-19)
-// serializeSteps is NOT exported; this replica pins the emission format and
-// is cross-checked against the REAL snippet output above.
-// See TESTABILITY GAP note at the bottom.
-// ===========================================================================
+describe("tweenButtonStyle: t=0.5 midpoint numeric lerp (hover → press)", () => {
+ // hover: translateY=-1, scale=1
+ // press: translateY=-1, scale=0.97
+ const a = buttonStyle("hover", ctx);
+ const b = buttonStyle("press", ctx);
+ const r = tweenButtonStyle(a, b, 0.5);
-/** MIRROR of config.ts:serializeSteps (lines 9-19). */
-function serializeStepsMirror(
- steps: { at: number; action: ButtonAction; duration?: number }[],
-): string {
- if (steps.length === 0) return "[]";
- const body = steps
- .map((step) => {
- const parts = [`at: ${step.at}`, `action: "${step.action}"`];
- if (step.duration !== undefined) parts.push(`duration: ${step.duration}`);
- return ` { ${parts.join(", ")} },`;
- })
- .join("\n");
- return `[\n${body}\n ]`;
-}
-
-describe("serializeSteps emission (spec mirror of config.ts:9-19)", () => {
- it("returns `[]` for empty steps", () => {
- expect(serializeStepsMirror([])).toBe("[]");
- });
-
- it("omits the `duration` key when undefined", () => {
- const out = serializeStepsMirror([{ at: 10, action: "hover" }]);
- expect(out).not.toContain("duration");
- expect(out).toContain('at: 10, action: "hover"');
- });
-
- it("includes the `duration` key when present", () => {
- const out = serializeStepsMirror([
- { at: 10, action: "loading", duration: 12 },
- ]);
- expect(out).toContain("duration: 12");
+ it("translateY midpoint: -1 → -1 gives -1 (both same)", () => {
+ expect(r.translateY).toBeCloseTo(-1, 10);
});
- it("the mirror's happy output is a substring of the REAL snippet", () => {
- // Cross-check: proves the mirror tracks the real serializer, and that the
- // real snippet embeds exactly the BUTTON_SCENARIOS.happy steps.
- const mirrored = serializeStepsMirror(BUTTON_SCENARIOS.happy);
- const real = snippet({ scenario: "happy" });
- expect(real).toContain(mirrored);
+ it("scale midpoint: 1 → 0.97 gives 0.985", () => {
+ expect(r.scale).toBeCloseTo(0.985, 10);
});
});
diff --git a/registry/remocn-ui/button/config.ts b/registry/remocn-ui/button/config.ts
index a941ac36..22a4e006 100644
--- a/registry/remocn-ui/button/config.ts
+++ b/registry/remocn-ui/button/config.ts
@@ -1,22 +1,5 @@
-import type { Step } from "@/lib/remocn-ui";
import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";
-import {
- BUTTON_SCENARIOS,
- type ButtonAction,
- type ButtonScenario,
-} from "@/registry/remocn-ui/button";
-
-function serializeSteps(steps: Step<ButtonAction>[]): string {
- if (steps.length === 0) return "[]";
- const body = steps
- .map((step) => {
- const parts = [`at: ${step.at}`, `action: "${step.action}"`];
- if (step.duration !== undefined) parts.push(`duration: ${step.duration}`);
- return ` { ${parts.join(", ")} },`;
- })
- .join("\n");
- return `[\n${body}\n ]`;
-}
+import type { ButtonState } from "@/registry/remocn-ui/button";
export const buttonConfig: ComponentConfig = {
componentName: "Button",
@@ -35,11 +18,12 @@ export const buttonConfig: ComponentConfig = {
options: ["sm", "default", "lg"],
label: "Size",
},
- scenario: {
+ state: {
type: "select",
- default: "happy",
- options: ["happy", "loading", "error", "idle"],
- label: "Scenario",
+ // Default to `loading` so the preview showcases the live spinner motion.
+ default: "loading",
+ options: ["idle", "hover", "press", "loading", "success"],
+ label: "State",
},
mode: {
type: "select",
@@ -54,14 +38,14 @@ export const buttonConfig: ComponentConfig = {
compositionWidth: W,
compositionHeight: H,
snippet: (values) => {
- const scenario = (values.scenario as ButtonScenario) ?? "happy";
+ const state = (values.state as ButtonState) ?? "loading";
const label = values.label as string | undefined;
const variant = values.variant as string | undefined;
const size = values.size as string | undefined;
const mode = values.mode as string | undefined;
const primary = values.primary as string | undefined;
- const props: string[] = [];
+ const props: string[] = [` state="${state}"`];
if (label !== undefined && label !== "Continue")
props.push(` label="${label}"`);
if (variant !== undefined && variant !== "default")
@@ -72,7 +56,6 @@ export const buttonConfig: ComponentConfig = {
props.push(` mode="${mode}"`);
if (primary !== undefined && primary !== "#171717")
props.push(` primary="${primary}"`);
- props.push(` steps={${serializeSteps(BUTTON_SCENARIOS[scenario])}}`);
return `import { Button } from "@/components/remocn/button";
diff --git a/registry/remocn-ui/button/index.tsx b/registry/remocn-ui/button/index.tsx
index fca0d2bf..38578fee 100644
--- a/registry/remocn-ui/button/index.tsx
+++ b/registry/remocn-ui/button/index.tsx
@@ -1,31 +1,9 @@
"use client";
-import { interpolate, useCurrentFrame } from "remotion";
-import {
- mixOklch,
- type RemocnTheme,
- type Step,
- useRemocnTheme,
- useTimelineState,
-} from "@/lib/remocn-ui";
+import { Spinner } from "@/components/remocn/spinner";
+import { mixOklch, type RemocnTheme, useRemocnTheme } from "@/lib/remocn-ui";
-export type ButtonAction =
- | "hover"
- | "press"
- | "release"
- | "loading"
- | "success"
- | "reset";
-
-export type ButtonPhase =
- | "idle"
- | "hover"
- | "press"
- | "loading"
- | "success"
- | "error";
-
-export type ButtonScenario = "happy" | "loading" | "error" | "idle";
+export type ButtonState = "idle" | "hover" | "press" | "loading" | "success";
type ButtonVariant =
| "default"
@@ -36,77 +14,28 @@ type ButtonVariant =
type ButtonSize = "sm" | "default" | "lg";
-interface ButtonState {
- phase: ButtonPhase;
-}
-
export interface ButtonProps {
+ /** Current visual state (snap path). State changes snap (no enter-tweens). */
+ state?: ButtonState;
+ /**
+ * Resolved animated visual (smooth path). When provided, takes precedence over
+ * `state` — feed it an interpolated `ButtonStyle` from `useButtonTransition`.
+ */
+ style?: ButtonStyle;
label?: string;
variant?: ButtonVariant;
size?: ButtonSize;
- steps?: Step<ButtonAction>[];
theme?: Partial<RemocnTheme>;
/** Convenience override for the `primary` theme token — merged into `theme`. */
primary?: string;
mode?: "light" | "dark";
- scenario?: ButtonScenario;
+ /** Playhead scale, forwarded to the loading Spinner. */
speed?: number;
className?: string;
}
-/**
- * The single source of truth for the preview scenarios. The component resolves
- * `scenario`→steps when `steps` is absent; `config.snippet` imports this map to
- * emit the `steps={[…]}` literal — so component and snippet never drift.
- */
-export const BUTTON_SCENARIOS: Record<ButtonScenario, Step<ButtonAction>[]> = {
- happy: [
- { at: 10, action: "hover" },
- { at: 25, action: "press" },
- { at: 35, action: "loading" },
- { at: 70, action: "success" },
- ],
- loading: [{ at: 10, action: "loading" }],
- error: [
- { at: 10, action: "hover" },
- { at: 25, action: "press" },
- { at: 35, action: "loading" },
- { at: 70, action: "reset" },
- ],
- idle: [],
-};
-
-const DEFAULT_STATE: ButtonState = { phase: "idle" };
-
-const DURATION_DEFAULTS: Record<ButtonAction, number> = {
- hover: 8,
- press: 5,
- release: 6,
- loading: 10,
- success: 14,
- reset: 8,
-};
-
-function reducer(state: ButtonState, step: Step<ButtonAction>): ButtonState {
- switch (step.action) {
- case "hover":
- return { phase: "hover" };
- case "press":
- return { phase: "press" };
- case "release":
- return { phase: "hover" };
- case "loading":
- return { phase: "loading" };
- case "success":
- return { phase: "success" };
- case "reset":
- // `reset` animates a destructive flash IN-FLIGHT (read via isActiveReset),
- // then settles to idle. Settled truth = idle, not error.
- return { phase: "idle" };
- default:
- return state;
- }
-}
+/** Checkmark stroke length (svg path units). */
+const CHECK_PATH_LENGTH = 14;
const SIZE_STYLES: Record<
ButtonSize,
@@ -128,159 +57,169 @@ function variantTokens(
variant: ButtonVariant,
theme: RemocnTheme,
): VariantTokens {
- switch (variant) {
- case "secondary":
+ const variants = {
+ secondary: {
+ bg: theme.secondary,
+ fg: theme.secondaryForeground,
+ hoverBg: mixOklch(theme.secondary, theme.muted, 1),
+ border: "transparent",
+ },
+ destructive: {
+ bg: theme.destructive,
+ fg: theme.destructiveForeground,
+ hoverBg: mixOklch(theme.destructive, theme.foreground, 0.12),
+ border: "transparent",
+ },
+ outline: {
+ bg: "transparent",
+ fg: theme.foreground,
+ hoverBg: theme.accent,
+ border: theme.border,
+ },
+ ghost: {
+ bg: "transparent",
+ fg: theme.foreground,
+ hoverBg: theme.accent,
+ border: "transparent",
+ },
+ default: {
+ bg: theme.primary,
+ fg: theme.primaryForeground,
+ hoverBg: mixOklch(theme.primary, theme.foreground, 0.1),
+ border: "transparent",
+ },
+ };
+
+ return variants[variant] ?? variants.default;
+}
+
+// ===========================================================================
+// Button visual — the COMPLETE animated look for a moment in time. A `state` is
+// a named preset of this visual (`buttonStyle`); the smooth path feeds an
+// interpolated `ButtonStyle` straight through. The component is a pure renderer
+// of whichever `ButtonStyle` it receives.
+// ===========================================================================
+
+export interface ButtonStyle {
+ translateY: number;
+ scale: number;
+ background: string;
+ labelOpacity: number;
+ spinnerOpacity: number;
+ checkOpacity: number;
+}
+
+/** Concrete colors for the active variant/theme, resolved once per render. */
+export interface ButtonStyleContext {
+ /** Resting background (a concrete color, never "transparent"). */
+ restBg: string;
+ hoverBg: string;
+ pressBg: string;
+ primary: string;
+}
+
+/**
+ * Derive the concrete colors for a variant/theme. Pure — call it once and reuse
+ * the result for every `buttonStyle(state, ctx)` preset.
+ */
+export function buttonStyleContext(
+ variant: ButtonVariant,
+ theme: RemocnTheme,
+): ButtonStyleContext {
+ const tokens = variantTokens(variant, theme);
+ // Transparent variants (outline/ghost) rest on the page background so the
+ // resting state has a concrete color.
+ const restBg = tokens.bg === "transparent" ? theme.background : tokens.bg;
+ return {
+ restBg,
+ hoverBg: tokens.hoverBg,
+ pressBg:
+ tokens.bg === "transparent"
+ ? tokens.hoverBg
+ : mixOklch(tokens.hoverBg, theme.foreground, 0.08),
+ primary: theme.primary,
+ };
+}
+
+/**
+ * The COMPLETE resting visual for a state — a pure `(state, ctx) => ButtonStyle`
+ * map. To change how a state looks, edit one entry.
+ */
+export function buttonStyle(
+ state: ButtonState,
+ ctx: ButtonStyleContext,
+): ButtonStyle {
+ switch (state) {
+ case "hover":
return {
- bg: theme.secondary,
- fg: theme.secondaryForeground,
- hoverBg: mixOklch(theme.secondary, theme.muted, 1),
- border: "transparent",
+ translateY: -1,
+ scale: 1,
+ background: ctx.hoverBg,
+ labelOpacity: 1,
+ spinnerOpacity: 0,
+ checkOpacity: 0,
};
- case "destructive":
+ case "press":
return {
- bg: theme.destructive,
- fg: theme.destructiveForeground,
- hoverBg: mixOklch(theme.destructive, theme.foreground, 0.12),
- border: "transparent",
+ translateY: -1,
+ scale: 0.97,
+ background: ctx.pressBg,
+ labelOpacity: 1,
+ spinnerOpacity: 0,
+ checkOpacity: 0,
};
- case "outline":
+ case "loading":
return {
- bg: "transparent",
- fg: theme.foreground,
- hoverBg: theme.accent,
- border: theme.border,
+ translateY: -1,
+ scale: 1,
+ background: ctx.hoverBg,
+ labelOpacity: 0,
+ spinnerOpacity: 1,
+ checkOpacity: 0,
};
- case "ghost":
+ case "success":
return {
- bg: "transparent",
- fg: theme.foreground,
- hoverBg: theme.accent,
- border: "transparent",
+ translateY: -1,
+ scale: 1,
+ background: ctx.primary,
+ labelOpacity: 0,
+ spinnerOpacity: 0,
+ checkOpacity: 1,
};
default:
return {
- bg: theme.primary,
- fg: theme.primaryForeground,
- hoverBg: mixOklch(theme.primary, theme.foreground, 0.1),
- border: "transparent",
+ translateY: 0,
+ scale: 1,
+ background: ctx.restBg,
+ labelOpacity: 1,
+ spinnerOpacity: 0,
+ checkOpacity: 0,
};
}
}
export function Button({
+ state = "idle",
+ style,
label = "Continue",
variant = "default",
size = "default",
- steps,
theme: themeOverride,
primary,
mode,
- scenario = "idle",
speed = 1,
className,
}: ButtonProps) {
- const frame = useCurrentFrame();
const theme = useRemocnTheme(
{ ...themeOverride, ...(primary ? { primary } : {}) },
mode,
);
- const resolvedSteps = steps ?? BUTTON_SCENARIOS[scenario];
-
- const { state, active, progressOf } = useTimelineState<ButtonState, ButtonAction>(
- resolvedSteps,
- DEFAULT_STATE,
- reducer,
- DURATION_DEFAULTS,
- speed,
- );
-
const sizeStyle = SIZE_STYLES[size];
const tokens = variantTokens(variant, theme);
- // --- Concurrent animation tracks (in-flight only) ---
- const hoverP = progressOf("hover");
- const pressP = progressOf("press");
- const loadingP = progressOf("loading");
- const successP = progressOf("success");
- const resetP = progressOf("reset");
-
- // --- Settled truth comes from state.phase (never from a closed progressOf) ---
- const isHoverPhase =
- state.phase === "hover" ||
- state.phase === "press" ||
- state.phase === "loading" ||
- state.phase === "success";
- const isPressPhase = state.phase === "press";
- const isLoadingPhase = state.phase === "loading";
- const isSuccessPhase = state.phase === "success";
-
- // Whether the reset window is currently in-flight (progressOf is in-flight-only;
- // use the active array for the gate so the flash only exists during the window).
- const isActiveReset = active.some((a) => a.step.action === "reset");
-
- // Hover lift + bg crossfade. Settled hover level holds at 1 once hovered.
- const hoverLevel = isHoverPhase ? 1 : 0;
- const hoverMix = Math.max(hoverLevel, hoverP);
- const translateY = interpolate(hoverMix, [0, 1], [0, -1]);
-
- // Press scale + darken. Settled at 0.97 while in press phase.
- const pressLevel = isPressPhase ? 1 : 0;
- const pressMix = Math.max(pressLevel, pressP);
- const scale = interpolate(pressMix, [0, 1], [1, 0.97]);
-
- // Loading: label fades out, spinner fades in. Settled fully on in loading.
- const loadingLevel = isLoadingPhase || isSuccessPhase ? 1 : 0;
- const loadingMix = Math.max(loadingLevel, loadingP);
-
- // Success: spinner fades out, checkmark draws. Settled fully on in success.
- const successLevel = isSuccessPhase ? 1 : 0;
- const successMix = Math.max(successLevel, successP);
-
- // Error flash on reset: IN-FLIGHT ONLY. Peaks at the start of the reset window
- // (resetP=0 → full destructive) and fades back to base (resetP=1 → no flash).
- // After the window closes isActiveReset is false → errorFlash=0, button is idle.
- const errorFlash = isActiveReset ? 1 - resetP : 0;
-
- // --- Resolve background ---
- let background = tokens.bg;
- if (isActiveReset) {
- // destructive flash, easing back to base bg as reset window completes
- background =
- tokens.bg === "transparent"
- ? mixOklch(theme.background, theme.destructive, errorFlash)
- : mixOklch(tokens.bg, theme.destructive, errorFlash);
- } else if (isSuccessPhase) {
- // success settles bg to primary
- background = mixOklch(tokens.bg, theme.primary, successMix);
- } else if (tokens.bg === "transparent") {
- // outline / ghost: fade in the accent bg on hover
- background = mixOklch(theme.background, tokens.hoverBg, hoverMix);
- } else {
- const hovered = mixOklch(tokens.bg, tokens.hoverBg, hoverMix);
- // press darkens further toward foreground
- background = mixOklch(hovered, theme.foreground, pressMix * 0.08);
- }
-
- const labelOpacity = interpolate(loadingMix, [0, 1], [1, 0]);
- const spinnerOpacity = Math.min(
- interpolate(loadingMix, [0, 1], [0, 1]),
- interpolate(successMix, [0, 1], [1, 0]),
- );
- const checkOpacity = interpolate(successMix, [0, 1], [0, 1]);
-
- // Deterministic spinner rotation (no Date/RAF) — scaled by the same playhead.
- const spinnerRotation = frame * speed * 6;
-
- // Checkmark stroke draw via dash offset (path length ~ 14 units).
- const checkPathLength = 14;
- const checkDashOffset = interpolate(
- successMix,
- [0, 1],
- [checkPathLength, 0],
- );
-
- const showSpinner = loadingMix > 0 || successMix > 0;
+ const ctx = buttonStyleContext(variant, theme);
+ const v = style ?? buttonStyle(state, ctx);
const iconSize = Math.round(sizeStyle.fontSize * 1.1);
return (
@@ -301,7 +240,7 @@ export function Button({
className={className}
style={{
position: "relative",
- transform: `translateY(${translateY}px) scale(${scale})`,
+ transform: `translateY(${v.translateY}px) scale(${v.scale})`,
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
@@ -312,7 +251,7 @@ export function Button({
fontWeight: 500,
letterSpacing: "-0.01em",
color: tokens.fg,
- background,
+ background: v.background,
border:
variant === "outline"
? `1px solid ${tokens.border}`
@@ -321,70 +260,51 @@ export function Button({
cursor: "pointer",
}}
>
- <span
- style={{
- display: "inline-flex",
- alignItems: "center",
- justifyContent: "center",
- position: "relative",
- }}
- >
- {showSpinner && (
- <span
- style={{
- position: "absolute",
- inset: 0,
- display: "inline-flex",
- alignItems: "center",
- justifyContent: "center",
- }}
+ {/* The label stays in normal flow so it sets the button width; the
+ spinner and checkmark are absolutely-positioned overlays that
+ crossfade over it. */}
+ <span style={{ position: "relative", display: "inline-flex" }}>
+ <span style={{ opacity: v.labelOpacity }}>{label}</span>
+ <span
+ style={{
+ position: "absolute",
+ inset: 0,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ opacity: v.spinnerOpacity,
+ }}
+ >
+ <Spinner color={tokens.fg} speed={speed} size={iconSize} />
+ </span>
+ <span
+ style={{
+ position: "absolute",
+ inset: 0,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ opacity: v.checkOpacity,
+ }}
+ >
+ <svg
+ width={iconSize}
+ height={iconSize}
+ viewBox="0 0 24 24"
+ fill="none"
>
- {/* Spinner */}
- <svg
- width={iconSize}
- height={iconSize}
- viewBox="0 0 24 24"
- fill="none"
- style={{
- position: "absolute",
- opacity: spinnerOpacity,
- transform: `rotate(${spinnerRotation}deg)`,
- }}
- >
- <circle
- cx="12"
- cy="12"
- r="9"
- stroke={tokens.fg}
- strokeWidth="2.5"
- strokeLinecap="round"
- strokeDasharray="44"
- strokeDashoffset="33"
- opacity={0.9}
- />
- </svg>
- {/* Checkmark */}
- <svg
- width={iconSize}
- height={iconSize}
- viewBox="0 0 24 24"
- fill="none"
- style={{ position: "absolute", opacity: checkOpacity }}
- >
- <path
- d="M5 12.5l4.5 4.5L19 7"
- stroke={tokens.fg}
- strokeWidth="2.6"
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeDasharray={checkPathLength}
- strokeDashoffset={checkDashOffset}
- pathLength={checkPathLength}
- />
- </svg>
- </span>
- )}
- <span style={{ opacity: labelOpacity }}>{label}</span>
+ <path
+ d="M5 12.5l4.5 4.5L19 7"
+ stroke={tokens.fg}
+ strokeWidth="2.6"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeDasharray={CHECK_PATH_LENGTH}
+ strokeDashoffset={0}
+ pathLength={CHECK_PATH_LENGTH}
+ />
+ </svg>
+ </span>
</span>
</button>
</div>
diff --git a/registry/remocn-ui/button/use-button-transition.ts b/registry/remocn-ui/button/use-button-transition.ts
new file mode 100644
index 00000000..b5357957
--- /dev/null
+++ b/registry/remocn-ui/button/use-button-transition.ts
@@ -0,0 +1,78 @@
+"use client";
+
+import {
+ easings,
+ mixOklch,
+ type RemocnTheme,
+ type Step,
+ useRemocnTheme,
+ useStateTransition,
+} from "@/lib/remocn-ui";
+import {
+ buttonStyle,
+ buttonStyleContext,
+ type ButtonState,
+ type ButtonStyle,
+} from "@/components/remocn/button";
+// ^ install path; resolves in-repo via the @/components/remocn/* tsconfig alias.
+
+/** Default transition length (frames) when a step omits `duration`. Tune to taste. */
+export const DEFAULT_DURATION = 8;
+
+/** Blend two button visuals: numbers lerp, background via oklch mix. */
+export function tweenButtonStyle(
+ a: ButtonStyle,
+ b: ButtonStyle,
+ t: number,
+): ButtonStyle {
+ return {
+ translateY: a.translateY + (b.translateY - a.translateY) * t,
+ scale: a.scale + (b.scale - a.scale) * t,
+ labelOpacity: a.labelOpacity + (b.labelOpacity - a.labelOpacity) * t,
+ spinnerOpacity:
+ a.spinnerOpacity + (b.spinnerOpacity - a.spinnerOpacity) * t,
+ checkOpacity: a.checkOpacity + (b.checkOpacity - a.checkOpacity) * t,
+ background: mixOklch(a.background, b.background, t),
+ };
+}
+
+export interface ButtonTransitionOptions {
+ variant?: "default" | "secondary" | "destructive" | "outline" | "ghost";
+ theme?: Partial<RemocnTheme>;
+ mode?: "light" | "dark";
+ primary?: string;
+ speed?: number;
+ defaultDuration?: number;
+}
+
+/**
+ * Timeline → resolved (eased, tweened) ButtonStyle. The CALLER invokes this; it
+ * reads the frame, the `<Button>` component does not. Feed the result to
+ * `<Button style={...} />` for smooth transitions.
+ */
+export function useButtonTransition(
+ steps: Step<ButtonState>[],
+ opts: ButtonTransitionOptions = {},
+): ButtonStyle {
+ const {
+ variant = "default",
+ theme: themeOverride,
+ mode,
+ primary,
+ speed = 1,
+ defaultDuration = DEFAULT_DURATION,
+ } = opts;
+ const theme = useRemocnTheme(
+ { ...themeOverride, ...(primary ? { primary } : {}) },
+ mode,
+ );
+ const ctx = buttonStyleContext(variant, theme);
+ const { from, to, progress } = useStateTransition(
+ steps,
+ "idle",
+ speed,
+ defaultDuration,
+ );
+ const t = easings.out(progress);
+ return tweenButtonStyle(buttonStyle(from, ctx), buttonStyle(to, ctx), t);
+}
diff --git a/registry/remocn-ui/core/__tests__/README.md b/registry/remocn-ui/core/__tests__/README.md
index bce96c29..079b90e9 100644
--- a/registry/remocn-ui/core/__tests__/README.md
+++ b/registry/remocn-ui/core/__tests__/README.md
@@ -60,12 +60,20 @@ added to `package.json`.
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.
+- `timeline.test.ts` — `framesFor` / `revealCount` as exact spec mirrors, plus
+ two pure resolver replicas (each factoring out the single impure
+ `useCurrentFrame()` line as an injected `raw` arg):
+ - **`resolveCurrentState`** (mirrors `useCurrentState`): speed contract
+ (`{at:30}` fires at raw frame 15 when `speed=2`), default-state before
+ first step, exact-frame activation, latest-started-wins, same-`at` ties
+ (later array entry wins).
+ - **`resolveStateTransition`** (mirrors `useStateTransition`): before-any-step
+ → `{from:default, to:default, progress:1}`; at step boundary →
+ `progress=0`; mid-window → fractional progress (concrete numeric);
+ past window → `progress=1` held; per-step `duration` overrides
+ `defaultDuration`; `duration:0` snaps to `progress=1`; chained steps carry
+ `from=previous-step state`; same-`at` ties (later array wins); `speed=2`
+ scales the playhead (effective frame, not authored `at`).
## Determinism grep checklist (run manually; must print NOTHING)
diff --git a/registry/remocn-ui/core/__tests__/timeline.test.ts b/registry/remocn-ui/core/__tests__/timeline.test.ts
index f432e619..593d4699 100644
--- a/registry/remocn-ui/core/__tests__/timeline.test.ts
+++ b/registry/remocn-ui/core/__tests__/timeline.test.ts
@@ -1,37 +1,34 @@
/**
- * Verification tests for the timeline FOLD SEMANTICS.
+ * Verification tests for the timeline 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).
+ * Scope: registry/remocn-ui/core/timeline.ts — framesFor, revealCount, and
+ * the pure resolver logic inside useCurrentState (speed contract, state
+ * resolution, ties).
*
* Runner: Bun's built-in test runner.
* bun test registry/remocn-ui/core/__tests__
*
* --------------------------------------------------------------------------
- * WHY THE FOLD IS REPLICATED HERE INSTEAD OF IMPORTED
+ * WHY THE RESOLVER IS REPLICATED HERE INSTEAD OF IMPORTED
* --------------------------------------------------------------------------
- * `useTimelineState` is a React hook whose FIRST line is `useCurrentFrame()`
+ * `useCurrentState` 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.
+ * 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 resolver ("resolveCurrentState" 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 and state-resolution rules 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.
+ * MAINTENANCE CONTRACT: if timeline.ts's resolver body changes, this replica
+ * MUST be updated in lockstep. The replica is annotated with the source line
+ * ranges it mirrors. The numeric expectations are the real verification value;
+ * the replica is the harness that lets us reach them without a Remotion render.
* --------------------------------------------------------------------------
*/
@@ -69,9 +66,9 @@ describe("framesFor", () => {
});
it("rounds fractional second->frame conversions", () => {
- // 0.1s * 30fps = 3 exactly; 0.11s * 30 = 3.3 -> 3
+ // 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
+ // 0.117 * 30 = 3.51 -> 4
expect(framesFor({ seconds: 0.117 }, 30)).toBe(4);
});
});
@@ -100,232 +97,484 @@ describe("revealCount (typewriter math)", () => {
});
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.
+ // len=0 => over=0 => guarded early-return of len (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.
+// 2. useCurrentState resolver replica — MIRROR of timeline.ts useCurrentState
+// body (lines 31-46), with the one impure line (useCurrentFrame) injected
+// as `raw`. Keep in lockstep with source.
+//
+// The resolver contract: returns the `state` of the latest step with
+// `at <= effectiveFrame` (effectiveFrame = raw * speed), else `defaultState`.
+// Ties on `at` resolve by array order — later entry wins.
// ===========================================================================
-interface Step<A extends string = string, V = unknown> {
+interface Step<S extends string = string> {
at: number;
- action: A;
- value?: V;
+ state: S;
duration?: number;
}
+/**
+ * MIRROR of timeline.ts:useCurrentState (lines 31-46).
+ * `raw` is the injected useCurrentFrame() value — annotates mirror source.
+ */
+function resolveCurrentState<S extends string>(
+ raw: number, // injected useCurrentFrame() — MIRROR of timeline.ts line 36
+ steps: Step<S>[],
+ defaultState: S,
+ speed = 1,
+): S {
+ const effectiveFrame = raw * speed; // MIRROR of timeline.ts line 36
+ let current = defaultState; // MIRROR of timeline.ts line 38
+ let bestAt = -Infinity; // MIRROR of timeline.ts line 39
+ steps.forEach((step) => { // MIRROR of timeline.ts lines 40-44
+ if (step.at <= effectiveFrame && step.at >= bestAt) {
+ bestAt = step.at;
+ current = step.state;
+ }
+ });
+ return current;
+}
+
+// ---------------------------------------------------------------------------
+// Empty steps / default state
+// ---------------------------------------------------------------------------
+
+describe("resolveCurrentState: empty steps always returns defaultState", () => {
+ it("returns defaultState when steps is empty", () => {
+ expect(resolveCurrentState(0, [], "idle")).toBe("idle");
+ expect(resolveCurrentState(100, [], "idle")).toBe("idle");
+ });
+
+ it("returns defaultState when no step has started yet (frame before first at)", () => {
+ const steps: Step<"hover">[] = [{ at: 10, state: "hover" }];
+ expect(resolveCurrentState(9, steps, "idle")).toBe("idle");
+ expect(resolveCurrentState(0, steps, "idle")).toBe("idle");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Exact-frame activation
+// ---------------------------------------------------------------------------
+
+describe("resolveCurrentState: activates exactly at `at`", () => {
+ type S = "idle" | "hover";
+ const steps: Step<S>[] = [{ at: 10, state: "hover" }];
+
+ it("returns defaultState one frame before `at`", () => {
+ expect(resolveCurrentState(9, steps, "idle")).toBe("idle");
+ });
+
+ it("returns the step's state exactly at `at`", () => {
+ expect(resolveCurrentState(10, steps, "idle")).toBe("hover");
+ });
+
+ it("holds that state past `at`", () => {
+ expect(resolveCurrentState(999, steps, "idle")).toBe("hover");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Latest of several started steps wins
+// ---------------------------------------------------------------------------
+
+describe("resolveCurrentState: latest started step wins", () => {
+ type S = "idle" | "hover" | "press" | "loading";
+ const steps: Step<S>[] = [
+ { at: 0, state: "hover" },
+ { at: 10, state: "press" },
+ { at: 20, state: "loading" },
+ ];
+
+ it("returns hover between frames 0-9", () => {
+ expect(resolveCurrentState(0, steps, "idle")).toBe("hover");
+ expect(resolveCurrentState(9, steps, "idle")).toBe("hover");
+ });
+
+ it("returns press between frames 10-19", () => {
+ expect(resolveCurrentState(10, steps, "idle")).toBe("press");
+ expect(resolveCurrentState(19, steps, "idle")).toBe("press");
+ });
+
+ it("returns loading from frame 20 onward", () => {
+ expect(resolveCurrentState(20, steps, "idle")).toBe("loading");
+ expect(resolveCurrentState(500, steps, "idle")).toBe("loading");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Ties on `at` — later array entry wins
+// ---------------------------------------------------------------------------
+
+describe("resolveCurrentState: same-`at` ties resolve to later array entry", () => {
+ type S = "idle" | "hover" | "press";
+
+ it("second entry at the same `at` wins over the first", () => {
+ const steps: Step<S>[] = [
+ { at: 5, state: "hover" },
+ { at: 5, state: "press" }, // same `at`, later in array — must win
+ ];
+ expect(resolveCurrentState(5, steps, "idle")).toBe("press");
+ });
+
+ it("third entry at the same `at` wins over the first two", () => {
+ const steps: Step<"idle" | "a" | "b" | "c">[] = [
+ { at: 5, state: "a" },
+ { at: 5, state: "b" },
+ { at: 5, state: "c" }, // latest in array
+ ];
+ expect(resolveCurrentState(5, steps, "idle")).toBe("c");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Speed contract — speed scales the playhead, not the authored `at`s
+// ---------------------------------------------------------------------------
+
+describe("resolveCurrentState: speed contract", () => {
+ type S = "idle" | "go";
+ const steps: Step<S>[] = [{ at: 30, state: "go" }];
+
+ it("step {at:30} is NOT active at raw frame 14 when speed=2 (eff=28)", () => {
+ expect(resolveCurrentState(14, steps, "idle", 2)).toBe("idle");
+ });
+
+ it("step {at:30} activates at raw frame 15 when speed=2 (eff=30)", () => {
+ expect(resolveCurrentState(15, steps, "idle", 2)).toBe("go");
+ });
+
+ it("step {at:30} activates at raw frame 60 when speed=0.5 (eff=30)", () => {
+ expect(resolveCurrentState(60, steps, "idle", 0.5)).toBe("go");
+ });
+
+ it("step {at:30} is NOT active at raw frame 59 when speed=0.5 (eff=29.5)", () => {
+ expect(resolveCurrentState(59, steps, "idle", 0.5)).toBe("idle");
+ });
+
+ it("at speed=1 a step fires exactly at its authored frame", () => {
+ expect(resolveCurrentState(29, steps, "idle", 1)).toBe("idle");
+ expect(resolveCurrentState(30, steps, "idle", 1)).toBe("go");
+ });
+});
+
+// ===========================================================================
+// 3. useStateTransition resolver replica
+// MIRRORS timeline.ts:useStateTransition (lines 55-73).
+// `raw` is injected in place of useCurrentFrame(). Keep in lockstep.
+//
+// Contract:
+// - `to` = latest step with at <= effectiveFrame; else defaultState.
+// - `from` = the step just before `to` in time-sorted order; else defaultState.
+// - `progress` = clamp01((eff - to.at) / (to.duration ?? defaultDuration));
+// before any step started → progress=1 (holds).
+// - Ties on `at`: later array index wins (sort is stable, later-index last).
+// - `speed` scales the playhead: effectiveFrame = raw * speed.
+// ===========================================================================
+
+/** MIRROR of timeline.ts:clamp01 (line 21-23). */
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>[],
+/**
+ * MIRROR of timeline.ts:useStateTransition (lines 55-73).
+ * `raw` = injected useCurrentFrame() value.
+ */
+function resolveStateTransition<S extends string>(
+ raw: number, // injected useCurrentFrame() — MIRROR of timeline.ts line 61
+ steps: Step<S>[],
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
+ defaultDuration = 8,
+): { from: S; to: S; progress: number } {
+ const effectiveFrame = raw * speed; // MIRROR line 61
+ const started = steps // MIRROR lines 62-65
.map((step, index) => ({ step, index }))
.sort((a, b) => a.step.at - b.step.at || a.index - b.index)
- .map((entry) => entry.step);
+ .filter((e) => e.step.at <= effectiveFrame);
+ if (started.length === 0) // MIRROR line 66-67
+ return { from: defaultState, to: defaultState, progress: 1 };
+ const to = started[started.length - 1].step; // MIRROR line 68
+ const from = started.length >= 2 ? started[started.length - 2].step : null; // MIRROR line 69
+ const dur = to.duration ?? defaultDuration; // MIRROR line 70
+ const progress = dur > 0 ? clamp01((effectiveFrame - to.at) / dur) : 1; // MIRROR line 71
+ return { from: from ? from.state : defaultState, to: to.state, progress }; // MIRROR line 72
+}
- let state: S = { ...defaultState }; // line 72: shallow clone
- const active: Array<{ step: Step<A>; progress: number }> = [];
+// ---------------------------------------------------------------------------
+// Before any step: {from:default, to:default, progress:1}
+// ---------------------------------------------------------------------------
- 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;
- };
+describe("resolveStateTransition: before any step starts", () => {
+ type S = "idle" | "hover";
- return { state, active, progressOf, frame: effectiveFrame };
-}
+ it("returns {from:default, to:default, progress:1} when steps is empty", () => {
+ expect(resolveStateTransition(0, [], "idle")).toEqual({
+ from: "idle",
+ to: "idle",
+ progress: 1,
+ });
+ });
+
+ it("returns {from:default, to:default, progress:1} when frame is before first step", () => {
+ const steps: Step<S>[] = [{ at: 10, state: "hover" }];
+ expect(resolveStateTransition(9, steps, "idle")).toEqual({
+ from: "idle",
+ to: "idle",
+ progress: 1,
+ });
+ });
+
+ it("returns {from:default, to:default, progress:1} at frame 0 with step at 5", () => {
+ const steps: Step<S>[] = [{ at: 5, state: "hover" }];
+ expect(resolveStateTransition(0, steps, "idle")).toEqual({
+ from: "idle",
+ to: "idle",
+ progress: 1,
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// At a step boundary: from=prev (or default if first), to=that state, progress=0
+// ---------------------------------------------------------------------------
-// --- speed contract --------------------------------------------------------
+describe("resolveStateTransition: exactly at a step's `at` frame", () => {
+ type S = "idle" | "hover" | "press";
-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("first step: from=default, to=step state, progress=0 (at transition start)", () => {
+ // at frame=10 exactly: effectiveFrame=10, to.at=10, progress=(10-10)/8=0
+ const steps: Step<S>[] = [{ at: 10, state: "hover" }];
+ const result = resolveStateTransition(10, steps, "idle");
+ expect(result.from).toBe("idle");
+ expect(result.to).toBe("hover");
+ expect(result.progress).toBe(0);
+ });
- 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("second step: from=first step state, to=second step state, progress=0", () => {
+ // frame=20: to={at:20, state:press}, from={at:10, state:hover}
+ // progress = (20-20)/8 = 0
+ const steps: Step<S>[] = [
+ { at: 10, state: "hover" },
+ { at: 20, state: "press" },
+ ];
+ const result = resolveStateTransition(20, steps, "idle");
+ expect(result.from).toBe("hover");
+ expect(result.to).toBe("press");
+ expect(result.progress).toBe(0);
});
+});
+
+// ---------------------------------------------------------------------------
+// Mid-window: fractional progress
+// ---------------------------------------------------------------------------
- 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
+describe("resolveStateTransition: fractional progress mid-window", () => {
+ type S = "idle" | "hover";
+
+ it("progress is 0.5 at the midpoint of defaultDuration=8 (frame=to.at+4)", () => {
+ // step at=10, defaultDuration=8; at frame=14: progress=(14-10)/8=0.5
+ const steps: Step<S>[] = [{ at: 10, state: "hover" }];
+ const result = resolveStateTransition(14, steps, "idle", 1, 8);
+ expect(result.to).toBe("hover");
+ expect(result.from).toBe("idle");
+ expect(result.progress).toBeCloseTo(0.5, 10);
});
- 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("progress is 0.25 at one quarter through defaultDuration=8 (frame=to.at+2)", () => {
+ // step at=10, frame=12: progress=(12-10)/8=0.25
+ const steps: Step<S>[] = [{ at: 10, state: "hover" }];
+ const result = resolveStateTransition(12, steps, "idle", 1, 8);
+ expect(result.progress).toBeCloseTo(0.25, 10);
});
- 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);
+ it("progress is 0.75 three-quarters through defaultDuration=8 (frame=to.at+6)", () => {
+ // step at=10, frame=16: progress=(16-10)/8=0.75
+ const steps: Step<S>[] = [{ at: 10, state: "hover" }];
+ const result = resolveStateTransition(16, steps, "idle", 1, 8);
+ expect(result.progress).toBeCloseTo(0.75, 10);
});
});
-// --- progressOf in-flight only (the flash-bug guard) -----------------------
+// ---------------------------------------------------------------------------
+// Past the window: progress holds at 1, to = that state
+// ---------------------------------------------------------------------------
+
+describe("resolveStateTransition: progress holds at 1 past the transition window", () => {
+ type S = "idle" | "hover";
-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,
+ it("progress=1 exactly at to.at+defaultDuration (frame=to.at+8)", () => {
+ // step at=10, defaultDuration=8, frame=18: progress=(18-10)/8=1
+ const steps: Step<S>[] = [{ at: 10, state: "hover" }];
+ const result = resolveStateTransition(18, steps, "idle", 1, 8);
+ expect(result.to).toBe("hover");
+ expect(result.progress).toBe(1);
});
- const run = (raw: number) =>
- foldTimeline(raw, steps, { checked: false }, reducer, dd, 1);
+ it("progress=1 well past the window (large frame)", () => {
+ const steps: Step<S>[] = [{ at: 10, state: "hover" }];
+ const result = resolveStateTransition(999, steps, "idle", 1, 8);
+ expect(result.to).toBe("hover");
+ expect(result.progress).toBe(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);
+// ---------------------------------------------------------------------------
+// Per-step `duration` overrides `defaultDuration`
+// ---------------------------------------------------------------------------
+
+describe("resolveStateTransition: per-step duration overrides defaultDuration", () => {
+ type S = "idle" | "hover";
+
+ it("step with duration:6 yields different progress at frame=to.at+4 than defaultDuration:8", () => {
+ // With duration:6: progress=(14-10)/6 ≈ 0.667
+ // With defaultDuration:8: progress=(14-10)/8 = 0.5
+ const stepsWithDur: Step<S>[] = [{ at: 10, state: "hover", duration: 6 }];
+ const stepsNoDur: Step<S>[] = [{ at: 10, state: "hover" }];
+ const withDur = resolveStateTransition(14, stepsWithDur, "idle", 1, 8);
+ const withDefault = resolveStateTransition(14, stepsNoDur, "idle", 1, 8);
+ expect(withDur.progress).toBeCloseTo(4 / 6, 10);
+ expect(withDefault.progress).toBeCloseTo(4 / 8, 10);
+ // They must differ
+ expect(Math.abs(withDur.progress - withDefault.progress)).toBeGreaterThan(0.1);
});
- 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("step with duration:6 completes (progress=1) at frame=to.at+6, not at to.at+8", () => {
+ const steps: Step<S>[] = [{ at: 10, state: "hover", duration: 6 }];
+ const atSix = resolveStateTransition(16, steps, "idle", 1, 8);
+ const atEight = resolveStateTransition(18, steps, "idle", 1, 8);
+ expect(atSix.progress).toBe(1);
+ expect(atEight.progress).toBe(1); // also clamped at 1, not beyond
});
- 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("step with duration:0 snaps immediately to progress=1", () => {
+ const steps: Step<S>[] = [{ at: 10, state: "hover", duration: 0 }];
+ const result = resolveStateTransition(10, steps, "idle", 1, 8);
+ expect(result.progress).toBe(1);
});
+});
+
+// ---------------------------------------------------------------------------
+// Chained steps: from = previous step state
+// ---------------------------------------------------------------------------
- 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
+describe("resolveStateTransition: chained steps carry from=previous state", () => {
+ type S = "idle" | "hover" | "press" | "loading";
+
+ const steps: Step<S>[] = [
+ { at: 0, state: "hover" },
+ { at: 10, state: "press" },
+ { at: 20, state: "loading" },
+ ];
+
+ it("at frame 0: from=defaultState (no prior step), to=hover", () => {
+ const r = resolveStateTransition(0, steps, "idle");
+ expect(r.from).toBe("idle");
+ expect(r.to).toBe("hover");
});
- 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
+ it("at frame 10: from=hover, to=press", () => {
+ const r = resolveStateTransition(10, steps, "idle");
+ expect(r.from).toBe("hover");
+ expect(r.to).toBe("press");
+ });
+
+ it("at frame 20: from=press, to=loading", () => {
+ const r = resolveStateTransition(20, steps, "idle");
+ expect(r.from).toBe("press");
+ expect(r.to).toBe("loading");
+ });
+
+ it("at frame 25: still from=press, to=loading (held)", () => {
+ const r = resolveStateTransition(25, steps, "idle");
+ expect(r.from).toBe("press");
+ expect(r.to).toBe("loading");
});
});
-// --- duration:0 snaps (never active) ---------------------------------------
+// ---------------------------------------------------------------------------
+// Ties on `at`: later array entry wins (same contract as useCurrentState)
+// ---------------------------------------------------------------------------
+
+describe("resolveStateTransition: same-`at` ties — later array entry wins", () => {
+ type S = "idle" | "a" | "b" | "c";
-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("second entry at same `at` wins: to=second, from=default", () => {
+ const steps: Step<S>[] = [
+ { at: 5, state: "a" },
+ { at: 5, state: "b" },
+ ];
+ const r = resolveStateTransition(5, steps, "idle");
+ expect(r.to).toBe("b");
+ expect(r.from).toBe("idle");
+ });
- it("state updates exactly at `at`", () => {
- expect(run(19).state.v).toBe(0);
- expect(run(20).state.v).toBe(1);
+ it("third entry at same `at` wins: to=third, from=default (all share same at)", () => {
+ const steps: Step<S>[] = [
+ { at: 5, state: "a" },
+ { at: 5, state: "b" },
+ { at: 5, state: "c" },
+ ];
+ const r = resolveStateTransition(5, steps, "idle");
+ expect(r.to).toBe("c");
+ // all three share the same at, so only one "time slot" — from=default
+ expect(r.from).toBe("idle");
});
- 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);
+ it("tie at second step: from=first step (different at), to=later-array winner", () => {
+ // step at=0 state=a, then two tied at=10 steps
+ const steps: Step<S>[] = [
+ { at: 0, state: "a" },
+ { at: 10, state: "b" },
+ { at: 10, state: "c" },
+ ];
+ const r = resolveStateTransition(10, steps, "idle");
+ expect(r.to).toBe("c"); // later array entry wins
+ expect(r.from).toBe("b"); // the other at=10 entry is second-to-last in sorted order
});
});
-// --- active-window boundaries ----------------------------------------------
+// ---------------------------------------------------------------------------
+// speed=2 scales the playhead
+// ---------------------------------------------------------------------------
-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);
+describe("resolveStateTransition: speed contract", () => {
+ type S = "idle" | "hover";
- it("active at the start frame", () => {
- expect(run(5).active.length).toBe(1);
- expect(run(5).progressOf("x")).toBe(0);
+ it("speed=2: step at=20 fires at raw frame 10 (eff=20)", () => {
+ const steps: Step<S>[] = [{ at: 20, state: "hover" }];
+ const r = resolveStateTransition(10, steps, "idle", 2);
+ expect(r.to).toBe("hover");
});
- it("active just before the end frame", () => {
- expect(run(14).active.length).toBe(1); // 14 < 15
+ it("speed=2: step at=20 has NOT fired at raw frame 9 (eff=18 < 20)", () => {
+ const steps: Step<S>[] = [{ at: 20, state: "hover" }];
+ const r = resolveStateTransition(9, steps, "idle", 2);
+ expect(r.to).toBe("idle");
+ expect(r.progress).toBe(1);
});
- it("NOT active at the exclusive end frame at+dur=15", () => {
- expect(run(15).active.length).toBe(0);
+ it("speed=2: progress mid-window uses effectiveFrame (raw=12, eff=24, at=20, dur=8 → prog=0.5)", () => {
+ // eff=24, to.at=20, dur=8 → (24-20)/8 = 0.5
+ const steps: Step<S>[] = [{ at: 20, state: "hover" }];
+ const r = resolveStateTransition(12, steps, "idle", 2, 8);
+ expect(r.to).toBe("hover");
+ expect(r.progress).toBeCloseTo(0.5, 10);
});
-});
-// --- progressOf picks the most-recent active step of an action -------------
+ it("speed=0.5: step at=20 fires at raw frame 40 (eff=20)", () => {
+ const steps: Step<S>[] = [{ at: 20, state: "hover" }];
+ const r = resolveStateTransition(40, steps, "idle", 0.5);
+ expect(r.to).toBe("hover");
+ });
-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);
+ it("speed=0.5: step at=20 has NOT fired at raw frame 39 (eff=19.5 < 20)", () => {
+ const steps: Step<S>[] = [{ at: 20, state: "hover" }];
+ const r = resolveStateTransition(39, steps, "idle", 0.5);
+ expect(r.to).toBe("idle");
});
});
diff --git a/registry/remocn-ui/core/index.ts b/registry/remocn-ui/core/index.ts
index 7e8b658d..e34de09a 100644
--- a/registry/remocn-ui/core/index.ts
+++ b/registry/remocn-ui/core/index.ts
@@ -1,5 +1,11 @@
-export type { Step, TimelineState } from "./types";
-export { framesFor, revealCount, useTimelineState } from "./timeline";
+export type { Step } from "./types";
+export {
+ clamp01,
+ framesFor,
+ revealCount,
+ useCurrentState,
+ useStateTransition,
+} from "./timeline";
export {
mixOklch,
oklchToRgb,
diff --git a/registry/remocn-ui/core/timeline.ts b/registry/remocn-ui/core/timeline.ts
index 475fd555..6f720508 100644
--- a/registry/remocn-ui/core/timeline.ts
+++ b/registry/remocn-ui/core/timeline.ts
@@ -18,56 +18,56 @@ export function revealCount(
return Math.max(0, Math.min(len, Math.floor((localFrame / over) * len)));
}
-function clamp01(t: number): number {
+export function clamp01(t: number): number {
return Math.max(0, Math.min(1, t));
}
-export function useTimelineState<S, A extends string>(
- steps: Step<A>[],
+/**
+ * Resolve the current state from a `steps` timeline: the state of the latest
+ * step whose `at <= effectiveFrame`, else `defaultState`. Pure deterministic
+ * fold; `speed` scales the playhead (effectiveFrame = useCurrentFrame()*speed).
+ * Ties on `at` resolve by array order (later wins).
+ */
+export function useCurrentState<S extends string>(
+ steps: Step<S>[],
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;
+): S {
+ const effectiveFrame = useCurrentFrame() * speed;
+ let current = defaultState;
+ let bestAt = -Infinity;
+ steps.forEach((step) => {
+ if (step.at <= effectiveFrame && step.at >= bestAt) {
+ bestAt = step.at;
+ current = step.state;
+ }
+ });
+ return current;
+}
- const ordered = steps
+/**
+ * Resolve the in-flight transition for keyframe-style atoms. `to` = latest step
+ * with at<=effectiveFrame (else defaultState); `from` = the step just before it
+ * (else defaultState); `progress` ramps 0→1 over [to.at, to.at + (to.duration ??
+ * defaultDuration)), then holds at 1. effectiveFrame = useCurrentFrame()*speed.
+ * Ties on `at` resolve later-array-wins.
+ */
+export function useStateTransition<S extends string>(
+ steps: Step<S>[],
+ defaultState: S,
+ speed = 1,
+ defaultDuration = 8,
+): { from: S; to: S; progress: number } {
+ const effectiveFrame = useCurrentFrame() * speed;
+ const started = 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 };
+ .filter((e) => e.step.at <= effectiveFrame);
+ if (started.length === 0)
+ return { from: defaultState, to: defaultState, progress: 1 };
+ const to = started[started.length - 1].step;
+ const from = started.length >= 2 ? started[started.length - 2].step : null;
+ const dur = to.duration ?? defaultDuration;
+ const progress = dur > 0 ? clamp01((effectiveFrame - to.at) / dur) : 1;
+ return { from: from ? from.state : defaultState, to: to.state, progress };
}
diff --git a/registry/remocn-ui/core/types.ts b/registry/remocn-ui/core/types.ts
index ed1302ef..5f0ebd7c 100644
--- a/registry/remocn-ui/core/types.ts
+++ b/registry/remocn-ui/core/types.ts
@@ -1,19 +1,14 @@
/**
- * A single scripted interaction on the Remotion timeline.
+ * A single scripted state 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.
+ * Every remocn UI state atom consumes the same `steps: Step[]` envelope. The
+ * current state is the latest step 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. */
+export interface Step<S extends string = string> {
+ /** LOCAL (Sequence-relative) authored frame at which the component enters this state. */
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. */
+ /** Per-component state union (e.g. "idle" | "hover" | "loading"). */
+ state: S;
+ /** Frames to animate the transition INTO this state. Omitted → caller's default. */
duration?: number;
}
-
-/** Result of folding steps: the resolved logical state at the current frame. */
-export type TimelineState<S> = S;
diff --git a/registry/remocn-ui/registry.json b/registry/remocn-ui/registry.json
index e349fd38..6f444167 100644
--- a/registry/remocn-ui/registry.json
+++ b/registry/remocn-ui/registry.json
@@ -42,18 +42,38 @@
}
]
},
+ {
+ "name": "spinner",
+ "type": "registry:component",
+ "title": "UI Spinner",
+ "description": "A deterministic spinning arc that loops on the Remotion frame — a pure motion atom with no state.",
+ "dependencies": ["remotion"],
+ "registryDependencies": [],
+ "files": [
+ {
+ "path": "spinner/index.tsx",
+ "type": "registry:component",
+ "target": "components/remocn/spinner.tsx"
+ }
+ ]
+ },
{
"name": "button",
"type": "registry:component",
"title": "UI Button",
- "description": "A shadcn-style button whose hover/press/loading/success states are scripted on the Remotion timeline.",
+ "description": "A button whose idle/hover/press/loading/success state is a pure function of the timeline; the loading state composes the Spinner motion atom.",
"dependencies": ["remotion"],
- "registryDependencies": ["remocn-ui"],
+ "registryDependencies": ["remocn-ui", "spinner"],
"files": [
{
"path": "button/index.tsx",
"type": "registry:component",
"target": "components/remocn/button.tsx"
+ },
+ {
+ "path": "button/use-button-transition.ts",
+ "type": "registry:component",
+ "target": "components/remocn/use-button-transition.ts"
}
]
}
diff --git a/registry/remocn-ui/spinner/__tests__/README.md b/registry/remocn-ui/spinner/__tests__/README.md
new file mode 100644
index 00000000..286c3001
--- /dev/null
+++ b/registry/remocn-ui/spinner/__tests__/README.md
@@ -0,0 +1,23 @@
+# `spinner` — determinism note
+
+`Spinner` is a **motion atom**: its only time source is `useCurrentFrame()`.
+The rotation formula is `rotation = frame * speed * 6` (degrees), computed
+directly from the Remotion playhead — there is no `Date.now()`, no
+`requestAnimationFrame`, and no `Math.random()`. This makes it a pure function
+of the frame: given the same frame number and the same `speed` prop, `Spinner`
+always produces the same transform, making it frame-perfect and scrub-safe on
+the Remotion timeline.
+
+Because `useCurrentFrame()` can only be called inside a Remotion render tree,
+`Spinner` has no headless unit tests. Its determinism guarantee is structural:
+read `registry/remocn-ui/spinner/index.tsx` and verify the single expression
+`useCurrentFrame() * speed * 6` is the only quantity that varies between
+renders. The grep below must print nothing — any match is a determinism
+violation:
+
+```bash
+grep -nE "useState|useEffect|Date\.now|Math\.random|requestAnimationFrame" \
+ registry/remocn-ui/spinner/index.tsx
+```
+
+Expected: no output.
diff --git a/registry/remocn-ui/spinner/config.ts b/registry/remocn-ui/spinner/config.ts
new file mode 100644
index 00000000..d644f874
--- /dev/null
+++ b/registry/remocn-ui/spinner/config.ts
@@ -0,0 +1,21 @@
+import { type ComponentConfig, FPS, H, W } from "@/lib/customizer-config";
+
+export const spinnerConfig: ComponentConfig = {
+ componentName: "Spinner",
+ importPath: "@/components/remocn/spinner",
+ controls: {
+ size: { type: "number", default: 20, min: 8, max: 64, step: 2, label: "Size" },
+ strokeWidth: {
+ type: "number",
+ default: 2.5,
+ min: 1,
+ max: 6,
+ step: 0.5,
+ label: "Stroke width",
+ },
+ },
+ durationInFrames: 120,
+ fps: FPS,
+ compositionWidth: W,
+ compositionHeight: H,
+};
diff --git a/registry/remocn-ui/spinner/index.tsx b/registry/remocn-ui/spinner/index.tsx
new file mode 100644
index 00000000..29570f74
--- /dev/null
+++ b/registry/remocn-ui/spinner/index.tsx
@@ -0,0 +1,53 @@
+"use client";
+
+import { useCurrentFrame } from "remotion";
+
+export interface SpinnerProps {
+ /** Rendered size in px (width === height). */
+ size?: number;
+ /** Stroke color. Defaults to `currentColor` so it inherits text color. */
+ color?: string;
+ /** Scales the playhead: rotation = frame * speed * 6 (deg). */
+ speed?: number;
+ /** Arc stroke width in viewBox units. */
+ strokeWidth?: number;
+ className?: string;
+}
+
+/**
+ * A deterministic spinning arc. Pure function of `useCurrentFrame()` — no
+ * Date, Math.random, or RAF — so it renders identically every render and
+ * frame-perfectly on the Remotion timeline. The single time source is the
+ * frame; there are no states.
+ */
+export function Spinner({
+ size = 20,
+ color = "currentColor",
+ speed = 1,
+ strokeWidth = 2.5,
+ className,
+}: SpinnerProps) {
+ const rotation = useCurrentFrame() * speed * 6;
+
+ return (
+ <svg
+ className={className}
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="none"
+ style={{ transform: `rotate(${rotation}deg)` }}
+ >
+ <circle
+ cx="12"
+ cy="12"
+ r="9"
+ stroke={color}
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeDasharray="44"
+ strokeDashoffset="33"
+ />
+ </svg>
+ );
+}
diff --git a/tsconfig.json b/tsconfig.json
index f9e8ef5a..4f1b41a7 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -21,6 +21,7 @@
"paths": {
"@/lib/remocn-ui": ["./registry/remocn-ui/core/index.ts"],
"@/lib/remocn-ui/*": ["./registry/remocn-ui/core/*"],
+ "@/components/remocn/*": ["./registry/remocn-ui/*/index.tsx"],
"@/*": ["./*"]
}
},