# Integrate `Rewind` from Motion Garden

You are helping me add the **Rewind** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** Rewind
- **Category:** Power-User Systems
- **Summary:** An undo history you can scrub, and that refuses to throw the future away. Drag the head and the interface reverts live under your finger rather than on release. Act from a past point and the abandoned future stays drawn on the rail as a branch you can walk back onto, instead of being silently destroyed the way every real undo stack destroys it. Controlled in the same shape as Ledger: it owns the rail, the gesture and the branch graph, and your reducer owns the states.
- **Reference:** https://motion-garden.netlify.app/components/rewind
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add motion clsx tailwind-merge
```

## Design tokens this source uses

Some classes in the source are Motion Garden theme tokens, not stock Tailwind (`text-ink`, `bg-panel`, `font-display` and the like). Without them, parts of the component render unstyled. Add this to my global CSS, after the Tailwind import:

```css
@theme {
  --font-display: "Space Mono", ui-monospace, "SFMono-Regular", monospace;
}

@theme inline {
  --color-surface: var(--sg-surface);
  --color-raised: var(--sg-raised);
  --color-ink-dim: var(--sg-ink-dim);
  --color-ink-mute: var(--sg-ink-mute);
  --color-accent: var(--sg-accent);
}

:root {
  --sg-surface: #f9f9fb;
  --sg-raised: #eceaef;
  --sg-ink-dim: #545b64;
  --sg-ink-mute: #878e97;
  --sg-accent: #7e22ce;
}

.dark {
  --sg-surface: #0a0b0c;
  --sg-raised: #191d21;
  --sg-ink-dim: #bcc2c8;
  --sg-ink-mute: #6c737c;
  --sg-accent: #a855f7;
}
```

The values are Motion Garden's own light and dark themes. If my project already has tokens for these roles, point the `--sg-*` variables at mine instead and tell me which you mapped. `.dark` assumes class-based dark mode — adapt the selector to how my project switches themes.

`font-display` expects Space Mono, and this CSS only names it. Load the font (with `next/font/google`, for example) or put my own display face first in the stack; until then it falls back to the system monospace.

## Files to create

2 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/rewind/rewind.tsx`

```tsx
"use client";

import { useEffect, useRef, useState } from "react";
import { motion, useMotionValue, useSpring, useTransform } from "motion/react";
import { cn } from "@/lib/utils";

export type RewindOrientation = "horizontal" | "vertical";
export type RewindTicks = "sparse" | "even" | "all";

export interface RewindNode {
  id: string;
  label: string;
}

export interface RewindBranch {
  at: number;
  nodes: RewindNode[];
}

interface RewindProps {
  nodes?: RewindNode[];
  branches?: RewindBranch[];
  index?: number;
  onScrub?: (index: number) => void;
  onEnterBranch?: (branch: number) => void;
  orientation?: RewindOrientation;
  scrubSnap?: boolean;
  branching?: boolean;
  branchDepth?: number;
  stiffness?: number;
  damping?: number;
  tickDensity?: RewindTicks;
  showLabels?: boolean;
  railHeight?: number;
  accentColor?: string;
  branchColor?: string;
  reducedMotion?: boolean;
  className?: string;
}

const EMPTY: RewindNode[] = [];
const NO_BRANCHES: RewindBranch[] = [];

export default function Rewind({
  nodes = EMPTY,
  branches = NO_BRANCHES,
  index = 0,
  onScrub,
  onEnterBranch,
  orientation = "horizontal",
  scrubSnap = true,
  branching = true,
  branchDepth = 3,
  stiffness = 420,
  damping = 34,
  tickDensity = "even",
  showLabels = true,
  railHeight = 4,
  accentColor = "#a855f7",
  branchColor = "#f0a830",
  reducedMotion = false,
  className,
}: RewindProps) {
  const railRef = useRef<HTMLDivElement>(null);
  const [dragging, setDragging] = useState(false);

  const vertical = orientation === "vertical";
  const last = Math.max(0, nodes.length - 1);
  const clamped = Math.max(0, Math.min(last, index));

  const raw = useMotionValue(last === 0 ? 0 : clamped / last);
  const sprung = useSpring(raw, { stiffness, damping, mass: 0.6 });
  const head = reducedMotion ? raw : sprung;
  const offset = useTransform(head, (v) => `${(v * 100).toFixed(3)}%`);

  useEffect(() => {
    if (dragging) return;
    raw.set(last === 0 ? 0 : clamped / last);
  }, [clamped, last, dragging, raw]);

  const fractionFrom = (event: React.PointerEvent<HTMLDivElement>): number => {
    const rail = railRef.current;
    if (!rail) return 0;
    const box = rail.getBoundingClientRect();
    const span = vertical ? box.height : box.width;
    if (span <= 0) return 0;
    const along = vertical ? event.clientY - box.top : event.clientX - box.left;
    return Math.max(0, Math.min(1, along / span));
  };

  const apply = (fraction: number) => {
    const next = Math.max(0, Math.min(last, Math.round(fraction * last)));
    raw.set(scrubSnap ? (last === 0 ? 0 : next / last) : fraction);
    if (next !== clamped) onScrub?.(next);
  };

  const onDown = (event: React.PointerEvent<HTMLDivElement>) => {
    if (nodes.length < 2) return;
    event.currentTarget.setPointerCapture(event.pointerId);
    setDragging(true);
    apply(fractionFrom(event));
  };
  const onMove = (event: React.PointerEvent<HTMLDivElement>) => {
    if (dragging) apply(fractionFrom(event));
  };
  const onUp = (event: React.PointerEvent<HTMLDivElement>) => {
    setDragging(false);
    if (event.currentTarget.hasPointerCapture(event.pointerId)) {
      event.currentTarget.releasePointerCapture(event.pointerId);
    }
    raw.set(last === 0 ? 0 : clamped / last);
  };

  const onKey = (event: React.KeyboardEvent<HTMLDivElement>) => {
    const back = vertical ? "ArrowUp" : "ArrowLeft";
    const forward = vertical ? "ArrowDown" : "ArrowRight";
    const go = (to: number) => {
      event.preventDefault();
      onScrub?.(Math.max(0, Math.min(last, to)));
    };
    if (event.key === back) go(clamped - 1);
    else if (event.key === forward) go(clamped + 1);
    else if (event.key === "Home") go(0);
    else if (event.key === "End") go(last);
  };

  const stride =
    tickDensity === "all"
      ? 1
      : Math.max(1, Math.ceil(nodes.length / (tickDensity === "even" ? 24 : 10)));

  const shown = branching ? branches.slice(0, Math.max(1, branchDepth)) : [];
  const pct = (i: number) => (last === 0 ? 0 : (i / last) * 100);

  const branchSpan = (branch: RewindBranch) =>
    Math.max(5, Math.min(100 - pct(branch.at), (branch.nodes.length / Math.max(1, last)) * 100));

  return (
    <div
      className={cn(
        "flex select-none",
        vertical ? "h-full flex-row gap-5" : "w-full flex-col gap-3",
        className,
      )}
    >
      <div className={cn("relative", vertical ? "h-full" : "w-full")}>
        <div
          ref={railRef}
          role="slider"
          tabIndex={0}
          aria-label="History position"
          aria-valuemin={0}
          aria-valuemax={last}
          aria-valuenow={clamped}
          aria-valuetext={nodes[clamped]?.label ?? "empty"}
          aria-orientation={orientation}
          onPointerDown={onDown}
          onPointerMove={onMove}
          onPointerUp={onUp}
          onPointerCancel={onUp}
          onKeyDown={onKey}
          className={cn(
            "relative cursor-pointer touch-none rounded-full bg-raised outline-none focus-visible:ring-2 focus-visible:ring-accent/60",
            vertical ? "mx-auto h-full" : "w-full",
          )}
          style={vertical ? { width: railHeight } : { height: railHeight }}
        >
          {vertical ? (
            <motion.span
              aria-hidden
              className="absolute top-0 left-0 block w-full rounded-full"
              style={{ backgroundColor: accentColor, height: offset }}
            />
          ) : (
            <motion.span
              aria-hidden
              className="absolute top-0 left-0 block h-full rounded-full"
              style={{ backgroundColor: accentColor, width: offset }}
            />
          )}

          {nodes.map((node, i) =>
            i % stride === 0 || i === last ? (
              <span
                key={node.id}
                aria-hidden
                className="absolute block rounded-full bg-ink-mute"
                style={{
                  width: 3,
                  height: 3,
                  opacity: i <= clamped ? 0 : 0.8,
                  transform: "translate(-50%, -50%)",
                  ...(vertical
                    ? { top: `${pct(i)}%`, left: "50%" }
                    : { left: `${pct(i)}%`, top: "50%" }),
                }}
              />
            ) : null,
          )}

          <motion.span
            aria-hidden
            className="absolute block rounded-full border-2 bg-surface shadow-lg"
            style={{
              width: 14,
              height: 14,
              borderColor: accentColor,
              transform: "translate(-50%, -50%)",
              ...(vertical ? { top: offset, left: "50%" } : { left: offset, top: "50%" }),
            }}
          />
        </div>

        {shown.map((branch, b) => (
          <button
            key={`${branch.at}-${b}-${branch.nodes.length}`}
            type="button"
            onClick={() => onEnterBranch?.(b)}
            title={`Abandoned future · ${branch.nodes.length} step${branch.nodes.length === 1 ? "" : "s"}`}
            aria-label={`Return to an abandoned future of ${branch.nodes.length} steps`}
            className="absolute rounded-full opacity-50 transition-opacity hover:opacity-100"
            style={{
              backgroundColor: branchColor,
              ...(vertical
                ? {
                    width: railHeight,
                    left: `calc(50% + ${(b + 1) * 11}px)`,
                    top: `${pct(branch.at)}%`,
                    height: `${branchSpan(branch)}%`,
                  }
                : {
                    height: railHeight,
                    top: `calc(50% + ${(b + 1) * 10}px)`,
                    left: `${pct(branch.at)}%`,
                    width: `${branchSpan(branch)}%`,
                  }),
            }}
          />
        ))}
      </div>

      {showLabels ? (
        <div
          className={cn(
            "flex gap-2 font-display text-[10px] tracking-[0.18em] uppercase",
            vertical ? "flex-col" : "items-baseline justify-between",
            shown.length > 0 && !vertical ? "pt-3" : "",
          )}
        >
          <span className="text-ink-dim">{nodes[clamped]?.label ?? "—"}</span>
          <span className="tabular-nums text-ink-mute">
            {nodes.length === 0 ? "0 / 0" : `${clamped + 1} / ${nodes.length}`}
            {clamped < last ? " · in the past" : ""}
          </span>
        </div>
      ) : null}
    </div>
  );
}
```

### 2. `lib/utils.ts` — peer util, required

```tsx
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `orientation` | `"horizontal" | "vertical"` | `"horizontal"` | Which axis the rail runs on. Horizontal reads as a scrubber; vertical reads as a commit log and stacks better beside a form. The gesture is written against one axis abstraction rather than two handlers, so the modes cannot drift apart. |
| `scrubSnap` | `boolean` | `true` | Lock the head to the nearest recorded state while dragging. Off, it moves continuously and the surface shows the state at or before it, which makes the density of the history visible — you can feel where you were working fast. |
| `branching` | `boolean` | `true` | Draw the futures you abandoned instead of discarding them. Off is the familiar destructive undo; on is the honest model, and the difference between the two is the whole component. |
| `branchDepth` | `number` | `3` | How many abandoned branches stay drawn beside the trunk before the oldest is folded away. Past about four the rail stops being a timeline and becomes a graph, which is a different component. Range 1–8. Ignored while `branching` is `false`. |
| `stiffness` | `number` | `420` | Spring tension on the head. The marker and the reported index come off the same drag, so the surface can never show a state the head has not reached — a readout running ahead of its own scrubber is the single thing that makes time travel feel fake. Range 120–900. |
| `damping` | `number` | `34` | Spring friction. Low lets the head ring past a state and come back, which is charming on a scrubber and disastrous on the fields it drives — this is the control that decides which of those you get. Range 8–60. |
| `tickDensity` | `"sparse" | "even" | "all"` | `"even"` | How many states the rail actually draws. All is truthful and unreadable past about sixty entries; even samples at a fixed pitch and leaves the true count in the label instead. |
| `showLabels` | `boolean` | `true` | The action name and position under the rail. Without it a scrub is a position; with it, it is a history you can read while dragging. |
| `railHeight` | `number` | `4` | Thickness of the rail, and of every branch beside it. Thin reads as a scrubber under a document; thick reads as the primary control on the screen. Range 2–14 px. |
| `accentColor` | `string (hex)` | `"#a855f7"` | The trunk, the head, and the travelled portion. |
| `branchColor` | `string (hex)` | `"#f0a830"` | Abandoned futures. Deliberately a warm off-accent rather than a dimmed trunk — a discarded future is a different kind of thing from a quiet one, not a fainter version of the same thing. Ignored while `branching` is `false`. |

## Usage

```tsx
import Rewind from "@/components/registry/rewind/rewind";

<Rewind
  orientation="horizontal"
  scrubSnap={true}
  branching={true}
  branchDepth={3}
  stiffness={420}
  damping={34}
  tickDensity="even"
  showLabels={true}
  railHeight={4}
  accentColor="#a855f7"
  branchColor="#f0a830"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- The `touch-action: none` on the hit target is load-bearing — without it a finger drag scrolls the page instead of driving the effect. Do not strip it as a stray utility class.
- `lib/utils.ts` is required, not optional. It exports the `cn` helper the component imports from `@/lib/utils` — keep it at that path, or rewrite every `cn` import to wherever you already keep yours. If your project is shadcn-based you almost certainly have this file already; keep yours and drop mine.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Add the design tokens to my global CSS, or map them to tokens I already have.
4. Wire the component into the place I point you at, with sensible props for that context.
5. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
