# Integrate `ApprovalFlow` from Motion Garden

You are helping me add the **ApprovalFlow** 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:** ApprovalFlow
- **Category:** Power-User Systems
- **Summary:** A step-by-step approval checklist for agent permissions. Radio and checkbox groups, an "Other…" escape hatch that grows a field in place, and per-step validation that blocks the commit. Answering a step sends the chosen option flying into a running record of what you have already decided, so the screen accumulates a decision trail instead of replacing itself.
- **Reference:** https://motion-garden.netlify.app/components/approval-flow
- **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-panel: var(--sg-panel);
  --color-raised: var(--sg-raised);
  --color-hairline: var(--sg-hairline);
  --color-ink: var(--sg-ink);
  --color-ink-dim: var(--sg-ink-dim);
  --color-ink-mute: var(--sg-ink-mute);
  --color-accent: var(--sg-accent);
}

:root {
  --sg-surface: #f9f9fb;
  --sg-panel: #ffffff;
  --sg-raised: #eceaef;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-ink-dim: #545b64;
  --sg-ink-mute: #878e97;
  --sg-accent: #7e22ce;
  --sg-on-accent: #ffffff;
}

.dark {
  --sg-surface: #0a0b0c;
  --sg-panel: #101215;
  --sg-raised: #191d21;
  --sg-hairline: #2a2f36;
  --sg-ink: #e2e6e9;
  --sg-ink-dim: #bcc2c8;
  --sg-ink-mute: #6c737c;
  --sg-accent: #a855f7;
  --sg-on-accent: #0a0b0c;
}
```

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

7 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/approval-flow/approval-flow.tsx`

```tsx
"use client";

import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
import { animate, AnimatePresence, LayoutGroup, motion, useMotionValue } from "motion/react";
import { cn } from "@/lib/utils";
import DecidedRail from "./decided-rail";
import StepPanel from "./step-panel";
import { useApprovalFlow } from "./use-approval-flow";
import {
  freeformOption,
  summarise,
  type ApprovalAnswers,
  type ApprovalStep,
} from "./types";

export interface ApprovalFlowProps {
  steps?: ApprovalStep[];
  onSubmit?: (answers: ApprovalAnswers) => void;
  layout?: "rail" | "inline";
  morphDuration?: number;
  stiffness?: number;
  damping?: number;
  density?: "comfortable" | "compact";
  revealStagger?: number;
  shakeIntensity?: number;
  shakeCycles?: number;
  showProgress?: boolean;
  autoAdvance?: boolean;
  accentColor?: string;
  dangerColor?: string;
  reducedMotion?: boolean;
  className?: string;
}

const RECEIPT_ID = "__receipt__";

export default function ApprovalFlow({
  steps = [],
  onSubmit,
  layout = "rail",
  morphDuration = 420,
  stiffness = 380,
  damping = 34,
  density = "comfortable",
  revealStagger = 45,
  shakeIntensity = 6,
  shakeCycles = 3,
  showProgress = true,
  autoAdvance = false,
  accentColor = "#a855f7",
  dangerColor = "#f87171",
  reducedMotion = false,
  className,
}: ApprovalFlowProps) {
  const uid = useId().replace(/:/g, "");
  const flow = useApprovalFlow(steps);
  const {
    index,
    step,
    answer,
    answers,
    error,
    rejected,
    direction,
    submitted,
    last,
    passes,
    decided,
  } = flow;

  const [moved, setMoved] = useState(false);

  const live = useRef({ next: flow.next, onSubmit, answers });
  live.current = { next: flow.next, onSubmit, answers };

  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  useEffect(() => () => clearTimeout(timer.current), []);

  useEffect(() => {
    if (submitted) live.current.onSubmit?.(live.current.answers);
  }, [submitted]);

  const spring = reducedMotion
    ? { duration: 0 }
    : ({ type: "spring", stiffness, damping } as const);

  const go = (run: () => void) => {
    setMoved(true);
    run();
  };

  const handleToggle = (optionId: string) => {
    flow.toggleOption(optionId);
    if (!autoAdvance || reducedMotion || !step || last) return;
    if (step.kind !== "single" || freeformOption(step)?.id === optionId) return;
    clearTimeout(timer.current);
    timer.current = setTimeout(() => go(live.current.next), Math.max(180, morphDuration * 0.6));
  };

  const boxRef = useRef<HTMLDivElement>(null);
  const boxH = useMotionValue(0);
  const settled = useRef<number | null>(null);
  const [sizing, setSizing] = useState<null | "grow" | "shrink">(null);

  useLayoutEffect(() => {
    const el = boxRef.current;
    if (!el) return;

    el.style.height = "";
    const key = submitted ? RECEIPT_ID : step?.id;
    const panels = Array.from(el.querySelectorAll<HTMLElement>("[data-step-id]"));
    const live = panels.find((node) => node.dataset.stepId === key);

    const prev = settled.current;
    if (!live || prev === null) return;

    const next = live.offsetHeight;
    if (reducedMotion || prev === next) return;

    boxH.jump(prev);
    el.style.height = `${prev}px`;
    setSizing(next > prev ? "grow" : "shrink");

    const run = animate(boxH, next, spring);
    const release = () => {
      setSizing(null);
      if (boxRef.current) boxRef.current.style.height = "";
    };
    void run.then(release);
    return () => {
      run.stop();
      release();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [step?.id, submitted, reducedMotion]);

  useLayoutEffect(() => {
    const el = boxRef.current;
    if (!el || el.style.height) return;
    if (el.querySelectorAll("[data-step-id]").length !== 1) return;
    settled.current = el.offsetHeight;
  });

  if (!step) return null;

  const rail = decided.length > 0 || submitted;
  const done = submitted ? steps.length : index;

  const record = (
    <DecidedRail
      steps={submitted ? steps : decided}
      answers={answers}
      uid={uid}
      accentColor={accentColor}
      density={density}
      spring={spring}
      reducedMotion={reducedMotion}
      onEdit={(to) => go(() => flow.edit(to))}
    />
  );

  return (
    <div
      className={cn(
        "w-full rounded-lg border border-hairline bg-panel p-5 sm:p-6",
        className,
      )}
    >
      {showProgress ? (
        <div className="mb-5 flex items-center gap-3">
          <div
            className="h-px flex-1 overflow-hidden bg-hairline"
            role="progressbar"
            aria-valuemin={0}
            aria-valuemax={steps.length}
            aria-valuenow={done}
            aria-label="Approval progress"
          >
            <motion.div
              className="h-full origin-left"
              style={{ backgroundColor: accentColor }}
              initial={false}
              animate={{ scaleX: steps.length ? done / steps.length : 0 }}
              transition={reducedMotion ? { duration: 0 } : spring}
            />
          </div>
        </div>
      ) : null}

      <LayoutGroup id={uid}>
        <div
          className={cn(
            layout === "rail"
              ? "grid gap-6 md:grid-cols-[minmax(0,1fr)_minmax(0,15rem)]"
              : "flex flex-col gap-6",
          )}
        >
          {layout === "inline" && rail ? record : null}

          <motion.div
            ref={boxRef}
            style={sizing ? { height: boxH } : undefined}
            className={cn(
              "relative min-w-0",
              sizing === "grow" && "overflow-hidden",
            )}
          >
            <AnimatePresence mode="popLayout" initial={false}>
              {submitted ? (
                <motion.div
                  key="receipt"
                  data-step-live="true"
                  initial={reducedMotion ? false : { opacity: 0, x: 44 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0 }}
                  transition={
                    reducedMotion ? { duration: 0 } : { duration: morphDuration / 1000 }
                  }
                  className="flex flex-col gap-4"
                >
                  <h3 className="font-display text-[15px] tracking-[0.06em] text-ink uppercase">
                    Authorisation granted
                  </h3>
                  <p className="font-sans text-[13px] leading-relaxed text-ink-dim">
                    {steps.length} decision{steps.length === 1 ? "" : "s"} recorded.
                  </p>
                  <ul className="sr-only">
                    {steps.map((s) => (
                      <li key={s.id}>
                        {s.title}: {summarise(s, answers[s.id] ?? { optionIds: [] })}
                      </li>
                    ))}
                  </ul>
                  <div>
                    <button
                      type="button"
                      onClick={() => go(() => flow.edit(0))}
                      className="rounded-md border border-hairline px-4 py-2 font-display text-[11px] tracking-[0.18em] text-ink-dim uppercase transition-colors outline-none hover:bg-raised hover:text-ink focus-visible:ring-2 focus-visible:ring-accent"
                    >
                      Revise
                    </button>
                  </div>
                </motion.div>
              ) : (
                <StepPanel
                  key={step.id}
                  step={step}
                  answer={answer ?? { optionIds: [] }}
                  index={index}
                  total={steps.length}
                  direction={direction}
                  error={error}
                  rejected={rejected}
                  passes={passes}
                  last={last}
                  focusHeading={moved}
                  density={density}
                  accentColor={accentColor}
                  dangerColor={dangerColor}
                  shakeIntensity={shakeIntensity}
                  shakeCycles={shakeCycles}
                  revealStagger={revealStagger}
                  morphDuration={morphDuration}
                  spring={spring}
                  reducedMotion={reducedMotion}
                  uid={uid}
                  onToggle={handleToggle}
                  onOther={flow.setOther}
                  onNext={() => go(flow.next)}
                  onBack={() => go(flow.back)}
                />
              )}
            </AnimatePresence>
          </motion.div>

          {layout === "rail" ? (
            <div className="min-w-0 md:border-l md:border-hairline md:pl-6">
              <span className="mb-2.5 block font-display text-[9px] tracking-[0.28em] text-ink-mute uppercase">
                Decided
              </span>
              {record}
              {rail ? null : (
                <p className="font-sans text-[12px] text-ink-mute/70">Nothing yet.</p>
              )}
            </div>
          ) : null}
        </div>
      </LayoutGroup>
    </div>
  );
}
```

### 2. `components/registry/approval-flow/types.ts` — supporting file, required

```tsx
export interface ApprovalOption {
  id: string;
  label: string;
  hint?: string;
  freeform?: boolean;
  placeholder?: string;
}

export interface ApprovalStep {
  id: string;
  kind: "single" | "multi";
  title: string;
  prompt?: string;
  options: ApprovalOption[];
  optional?: boolean;
  validate?: (answer: ApprovalAnswer, step: ApprovalStep) => string | null;
}

export interface ApprovalAnswer {
  optionIds: string[];
  other?: string;
}

export type ApprovalAnswers = Record<string, ApprovalAnswer>;

export const EMPTY_ANSWER: ApprovalAnswer = { optionIds: [] };

export function answerFor(answers: ApprovalAnswers, stepId: string): ApprovalAnswer {
  return answers[stepId] ?? EMPTY_ANSWER;
}

export function freeformOption(step: ApprovalStep): ApprovalOption | undefined {
  return step.options.find((option) => option.freeform);
}

export function freeformActive(step: ApprovalStep, answer: ApprovalAnswer): boolean {
  const hatch = freeformOption(step);
  return Boolean(hatch && answer.optionIds.includes(hatch.id));
}

export function defaultValidate(
  answer: ApprovalAnswer,
  step: ApprovalStep,
): string | null {
  if (step.optional) return null;
  if (answer.optionIds.length === 0) return "Choose an option to continue.";
  if (freeformActive(step, answer) && !(answer.other ?? "").trim()) {
    return "Describe what you need instead.";
  }
  return null;
}

export function validateStep(
  answer: ApprovalAnswer,
  step: ApprovalStep,
): string | null {
  return step.validate ? step.validate(answer, step) : defaultValidate(answer, step);
}

export function summarise(step: ApprovalStep, answer: ApprovalAnswer): string {
  if (answer.optionIds.length === 0) return "Skipped";

  if (freeformActive(step, answer)) {
    const typed = (answer.other ?? "").trim();
    const rest = answer.optionIds.length - 1;
    if (typed) return rest > 0 ? `${typed} +${rest}` : typed;
  }

  const chosen = step.options.filter((option) => answer.optionIds.includes(option.id));
  const [first, ...others] = chosen;
  if (!first) return "Skipped";
  return others.length > 0 ? `${first.label} +${others.length}` : first.label;
}

export function travelId(uid: string, stepId: string, optionId: string): string {
  return [uid, stepId, optionId].map(encodeURIComponent).join("/");
}

export function travellingOption(
  step: ApprovalStep,
  answer: ApprovalAnswer,
): ApprovalOption | undefined {
  return step.options.find((option) => answer.optionIds.includes(option.id));
}
```

### 3. `components/registry/approval-flow/use-approval-flow.ts` — supporting file, required

```tsx
"use client";

import { useCallback, useMemo, useReducer } from "react";
import {
  answerFor,
  freeformOption,
  validateStep,
  type ApprovalAnswer,
  type ApprovalAnswers,
  type ApprovalStep,
} from "./types";

interface FlowState {
  index: number;
  answers: ApprovalAnswers;
  error: string | null;
  rejected: number;
  direction: 1 | -1;
  submitted: boolean;
}

type FlowAction =
  | { type: "toggle"; step: ApprovalStep; optionId: string }
  | { type: "other"; stepId: string; value: string }
  | { type: "advance"; error: string | null; last: boolean }
  | { type: "back" }
  | { type: "edit"; index: number }
  | { type: "reset" };

const INITIAL: FlowState = {
  index: 0,
  answers: {},
  error: null,
  rejected: 0,
  direction: 1,
  submitted: false,
};

function toggle(state: FlowState, step: ApprovalStep, optionId: string): FlowState {
  const current = answerFor(state.answers, step.id);
  const held = current.optionIds.includes(optionId);
  const hatch = freeformOption(step);

  let optionIds: string[];
  if (step.kind === "single") {
    optionIds = held ? [] : [optionId];
  } else if (held) {
    optionIds = current.optionIds.filter((id) => id !== optionId);
  } else {
    const next = new Set([...current.optionIds, optionId]);
    optionIds = step.options.filter((option) => next.has(option.id)).map((o) => o.id);
  }

  const answer: ApprovalAnswer = { ...current, optionIds };

  return {
    ...state,
    answers: { ...state.answers, [step.id]: answer },
    error: state.error && optionIds.length > 0 ? null : state.error,
    ...(hatch && optionId !== hatch.id && step.kind === "single" ? { error: null } : {}),
  };
}

function reducer(state: FlowState, action: FlowAction): FlowState {
  switch (action.type) {
    case "toggle":
      return toggle(state, action.step, action.optionId);

    case "other": {
      const current = answerFor(state.answers, action.stepId);
      return {
        ...state,
        answers: {
          ...state.answers,
          [action.stepId]: { ...current, other: action.value },
        },
        error: action.value.trim() ? null : state.error,
      };
    }

    case "advance":
      if (action.error) {
        return { ...state, error: action.error, rejected: state.rejected + 1 };
      }
      return {
        ...state,
        error: null,
        direction: 1,
        index: action.last ? state.index : state.index + 1,
        submitted: action.last ? true : state.submitted,
      };

    case "back":
      if (state.index === 0) return state;
      return { ...state, index: state.index - 1, direction: -1, error: null };

    case "edit":
      return {
        ...state,
        index: action.index,
        direction: action.index > state.index ? 1 : -1,
        error: null,
        submitted: false,
      };

    case "reset":
      return INITIAL;

    default:
      return state;
  }
}

export function useApprovalFlow(steps: ApprovalStep[]) {
  const [state, dispatch] = useReducer(reducer, INITIAL);

  const index = Math.min(state.index, Math.max(0, steps.length - 1));
  const step = steps[index];
  const answer = step ? answerFor(state.answers, step.id) : undefined;
  const last = index === steps.length - 1;

  const passes = useMemo(
    () => (step && answer ? validateStep(answer, step) === null : true),
    [step, answer],
  );

  const next = useCallback(() => {
    if (!step || !answer) return;
    dispatch({ type: "advance", error: validateStep(answer, step), last });
  }, [step, answer, last]);

  const toggleOption = useCallback(
    (optionId: string) => {
      if (!step) return;
      dispatch({ type: "toggle", step, optionId });
    },
    [step],
  );

  const setOther = useCallback(
    (value: string) => {
      if (!step) return;
      dispatch({ type: "other", stepId: step.id, value });
    },
    [step],
  );

  const back = useCallback(() => dispatch({ type: "back" }), []);
  const edit = useCallback((to: number) => dispatch({ type: "edit", index: to }), []);
  const reset = useCallback(() => dispatch({ type: "reset" }), []);

  return {
    index,
    step,
    answer,
    answers: state.answers,
    error: state.error,
    rejected: state.rejected,
    direction: state.direction,
    submitted: state.submitted,
    last,
    passes,
    decided: steps.slice(0, index),
    toggleOption,
    setOther,
    next,
    back,
    edit,
    reset,
  };
}
```

### 4. `components/registry/approval-flow/step-panel.tsx` — supporting file, required

```tsx
"use client";

import { forwardRef, useEffect, useRef } from "react";
import {
  animate,
  motion,
  useIsPresent,
  useMotionValue,
  type Transition,
} from "motion/react";
import { cn } from "@/lib/utils";
import OptionRow from "./option-row";
import { freeformOption, travelId, type ApprovalAnswer, type ApprovalStep } from "./types";

export interface StepPanelProps {
  step: ApprovalStep;
  answer: ApprovalAnswer;
  index: number;
  total: number;
  direction: 1 | -1;
  error: string | null;
  rejected: number;
  passes: boolean;
  last: boolean;
  focusHeading: boolean;
  density: "comfortable" | "compact";
  accentColor: string;
  dangerColor: string;
  shakeIntensity: number;
  shakeCycles: number;
  revealStagger: number;
  morphDuration: number;
  spring: Transition;
  reducedMotion: boolean;
  uid: string;
  onToggle: (optionId: string) => void;
  onOther: (value: string) => void;
  onNext: () => void;
  onBack: () => void;
}

const SLIDE = 44;

const STAGGER_CAP = 7;

const EASE = [0.22, 1, 0.36, 1] as const;

function shakeKeyframes(intensity: number, cycles: number): number[] {
  const out: number[] = [0];
  for (let i = 0; i < cycles; i += 1) {
    const decay = 1 - i / (cycles + 1);
    out.push(-intensity * decay, intensity * decay);
  }
  out.push(0);
  return out;
}

const StepPanel = forwardRef<HTMLElement, StepPanelProps>(function StepPanel(
  {
    step,
    answer,
    index,
    total,
    direction,
    error,
    rejected,
    passes,
    last,
    focusHeading,
    density,
    accentColor,
    dangerColor,
    shakeIntensity,
    shakeCycles,
    revealStagger,
    morphDuration,
    spring,
    reducedMotion,
    uid,
    onToggle,
    onOther,
    onNext,
    onBack,
  },
  ref,
) {
  const headingRef = useRef<HTMLHeadingElement>(null);
  const firstRejection = useRef(rejected);
  const shakeX = useMotionValue(0);
  const present = useIsPresent();

  useEffect(() => {
    if (focusHeading) headingRef.current?.focus({ preventScroll: true });
  }, [focusHeading]);

  useEffect(() => {
    if (rejected === firstRejection.current) return;
    firstRejection.current = rejected;
    if (reducedMotion || shakeIntensity <= 0 || shakeCycles <= 0) return;
    const run = animate(shakeX, shakeKeyframes(shakeIntensity, shakeCycles), {
      duration: 0.09 * shakeCycles + 0.12,
      ease: "easeInOut",
    });
    return () => run.stop();
  }, [rejected, reducedMotion, shakeIntensity, shakeCycles, shakeX]);

  const errorId = `${uid}-error-${step.id}`;
  const morph = !reducedMotion;

  const hatch = freeformOption(step);
  const hatchBlank = hatch
    ? answer.optionIds.includes(hatch.id) && !(answer.other ?? "").trim()
    : false;
  const invalidId = error && hatch && hatchBlank ? hatch.id : null;

  return (
    <motion.section
      ref={ref}
      initial={reducedMotion ? false : { x: SLIDE * direction }}
      animate={{ x: 0 }}
      exit={{
        opacity: 0,
        transition: { duration: reducedMotion ? 0 : (morphDuration / 1000) * 0.34 },
      }}
      transition={
        reducedMotion ? { duration: 0 } : { duration: morphDuration / 1000, ease: EASE }
      }
      aria-labelledby={`${uid}-title-${step.id}`}
      inert={!present}
      data-step-id={step.id}
      className="flex min-w-0 flex-col gap-5"
    >
      <header className="flex flex-col gap-1.5">
        <span className="font-display text-[10px] tracking-[0.28em] text-ink-mute uppercase">
          Step {index + 1} of {total}
        </span>
        <h3
          id={`${uid}-title-${step.id}`}
          ref={headingRef}
          tabIndex={-1}
          className="font-display text-[15px] tracking-[0.06em] text-ink uppercase outline-none"
        >
          {step.title}
        </h3>
        {step.prompt ? (
          <p className="font-sans text-[13px] leading-relaxed text-ink-dim">
            {step.prompt}
          </p>
        ) : null}
      </header>

      <motion.div style={{ x: shakeX }}>
        <div
          role={step.kind === "single" ? "radiogroup" : "group"}
          aria-labelledby={`${uid}-title-${step.id}`}
          aria-describedby={error ? errorId : undefined}
          className="flex flex-col gap-2"
        >
          {step.options.map((option, i) => (
            <motion.div
              key={option.id}
              initial={reducedMotion ? false : { opacity: 0, x: SLIDE * 0.4 }}
              animate={{ opacity: 1, x: 0 }}
              transition={
                reducedMotion
                  ? { duration: 0 }
                  : {
                      duration: (morphDuration / 1000) * 0.5,
                      delay: (Math.min(i, STAGGER_CAP) * revealStagger) / 1000,
                      ease: EASE,
                    }
              }
            >
              <OptionRow
                option={option}
                kind={step.kind}
                name={`${uid}-${step.id}`}
                checked={answer.optionIds.includes(option.id)}
                density={density}
                accentColor={accentColor}
                dangerColor={dangerColor}
                invalid={invalidId === option.id}
                reducedMotion={reducedMotion}
                transition={spring}
                travelId={morph ? travelId(uid, step.id, option.id) : undefined}
                other={answer.other ?? ""}
                onToggle={() => onToggle(option.id)}
                onOther={onOther}
              />
            </motion.div>
          ))}
        </div>

        <p
          id={errorId}
          role="alert"
          aria-live="assertive"
          className={cn(
            "mt-3 font-sans text-[12px] transition-opacity",
            error ? "opacity-100" : "opacity-0",
          )}
          style={{ color: dangerColor }}
        >
          {error ?? " "}
        </p>
      </motion.div>

      <div className="flex items-center gap-3">
        <button
          type="button"
          onClick={onBack}
          disabled={index === 0}
          className="rounded-md border border-hairline px-4 py-2 font-display text-[11px] tracking-[0.18em] text-ink-dim uppercase transition-colors outline-none hover:bg-raised hover:text-ink focus-visible:ring-2 focus-visible:ring-accent disabled:pointer-events-none disabled:opacity-40"
        >
          Back
        </button>
        <button
          type="button"
          onClick={onNext}
          aria-disabled={!passes}
          className={cn(
            "rounded-md border px-5 py-2 font-display text-[11px] tracking-[0.18em] uppercase transition-colors outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-panel",
            passes ? "border-transparent" : "border-hairline bg-raised text-ink-mute",
          )}
          style={
            passes
              ? { backgroundColor: accentColor, color: "var(--sg-on-accent)" }
              : undefined
          }
        >
          {last ? "Approve" : "Next"}
        </button>
      </div>
    </motion.section>
  );
});

export default StepPanel;
```

### 5. `components/registry/approval-flow/option-row.tsx` — supporting file, required

```tsx
"use client";

import { useEffect, useRef } from "react";
import { motion, type Transition } from "motion/react";
import { cn } from "@/lib/utils";
import type { ApprovalOption } from "./types";

export interface OptionRowProps {
  option: ApprovalOption;
  kind: "single" | "multi";
  name: string;
  checked: boolean;
  density: "comfortable" | "compact";
  accentColor: string;
  dangerColor: string;
  invalid: boolean;
  reducedMotion: boolean;
  transition: Transition;
  travelId?: string;
  other: string;
  onToggle: () => void;
  onOther: (value: string) => void;
}

export default function OptionRow({
  option,
  kind,
  name,
  checked,
  density,
  accentColor,
  dangerColor,
  invalid,
  reducedMotion,
  transition,
  travelId,
  other,
  onToggle,
  onOther,
}: OptionRowProps) {
  const fieldRef = useRef<HTMLInputElement>(null);
  const wasOpen = useRef(false);
  const revertTo = useRef("");

  const hatch = Boolean(option.freeform);
  const open = hatch && checked;
  const compact = density === "compact";

  useEffect(() => {
    if (open && !wasOpen.current) {
      revertTo.current = other;
      fieldRef.current?.focus();
    }
    wasOpen.current = open;
  }, [open, other]);

  const tick = checked ? 1 : 0;
  const ring = invalid ? dangerColor : accentColor;

  return (
    <div
      className={cn(
        "rounded-md border transition-colors",
        checked ? "bg-raised" : "bg-transparent hover:bg-raised/60",
      )}
      style={{
        borderColor: checked || invalid ? ring : "var(--sg-hairline)",
        boxShadow: checked && !invalid ? `inset 0 0 0 1px ${accentColor}33` : undefined,
      }}
    >
      <label
        className={cn(
          "relative flex cursor-pointer items-start outline-none",
          compact ? "gap-2.5 px-3 py-2" : "gap-3 px-4 py-3",
        )}
      >
        <input
          type={kind === "single" ? "radio" : "checkbox"}
          name={name}
          checked={checked}
          onChange={onToggle}
          className="peer absolute inset-0 size-full cursor-pointer opacity-0"
        />

        <span className="pointer-events-none absolute inset-0 rounded-md peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-[var(--sg-accent)]" />

        <svg
          viewBox="0 0 24 24"
          className={cn("mt-px shrink-0", compact ? "size-4" : "size-[18px]")}
          aria-hidden
        >
          <rect
            x="2.5"
            y="2.5"
            width="19"
            height="19"
            rx={kind === "single" ? 9.5 : 5}
            fill="none"
            stroke={checked ? ring : "currentColor"}
            strokeWidth="2"
            className={checked ? undefined : "text-ink-mute"}
          />
          <motion.path
            d="M7.5 12.5 11 16 16.5 8.5"
            fill="none"
            stroke={ring}
            strokeWidth="2.6"
            strokeLinecap="round"
            strokeLinejoin="round"
            pathLength={1}
            initial={false}
            animate={{ pathLength: tick, opacity: tick }}
            transition={reducedMotion ? { duration: 0 } : transition}
          />
        </svg>

        <span className="min-w-0 flex-1">
          {travelId ? (
            <motion.span
              layoutId={travelId}
              transition={transition}
              className={cn(
                "block font-display tracking-[0.1em] text-ink uppercase",
                compact ? "text-[11px]" : "text-[12px]",
              )}
            >
              {option.label}
            </motion.span>
          ) : (
            <span
              className={cn(
                "block font-display tracking-[0.1em] text-ink uppercase",
                compact ? "text-[11px]" : "text-[12px]",
              )}
            >
              {option.label}
            </span>
          )}
          {option.hint ? (
            <span
              className={cn(
                "mt-1 block font-sans text-ink-mute",
                compact ? "text-[11px]" : "text-[12px]",
              )}
            >
              {option.hint}
            </span>
          ) : null}
        </span>
      </label>

      {hatch ? (
        <motion.div
          initial={false}
          animate={{ height: open ? "auto" : 0, opacity: open ? 1 : 0 }}
          transition={reducedMotion ? { duration: 0 } : transition}
          className="overflow-hidden"
        >
          <div className={cn(compact ? "px-3 pb-2" : "px-4 pb-3")}>
            <input
              ref={fieldRef}
              type="text"
              value={other}
              placeholder={option.placeholder ?? "Type what you need instead"}
              aria-label={option.label}
              aria-invalid={invalid || undefined}
              disabled={!open}
              onChange={(event) => onOther(event.target.value)}
              onKeyDown={(event) => {
                if (event.key === "Escape") {
                  event.stopPropagation();
                  onOther(revertTo.current);
                }
              }}
              className={cn(
                "w-full rounded-sm border bg-surface font-sans text-ink outline-none",
                "placeholder:text-ink-mute/70",
                compact ? "px-2.5 py-1.5 text-[12px]" : "px-3 py-2 text-[13px]",
              )}
              style={{
                borderColor: invalid ? dangerColor : "var(--sg-hairline)",
              }}
            />
          </div>
        </motion.div>
      ) : null}
    </div>
  );
}
```

### 6. `components/registry/approval-flow/decided-rail.tsx` — supporting file, required

```tsx
"use client";

import { AnimatePresence, motion, type Transition } from "motion/react";
import { cn } from "@/lib/utils";
import {
  answerFor,
  freeformActive,
  summarise,
  travelId,
  travellingOption,
  type ApprovalAnswers,
  type ApprovalStep,
} from "./types";

export interface DecidedRailProps {
  steps: ApprovalStep[];
  answers: ApprovalAnswers;
  uid: string;
  accentColor: string;
  density: "comfortable" | "compact";
  spring: Transition;
  reducedMotion: boolean;
  onEdit: (index: number) => void;
}

export default function DecidedRail({
  steps,
  answers,
  uid,
  accentColor,
  density,
  spring,
  reducedMotion,
  onEdit,
}: DecidedRailProps) {
  const compact = density === "compact";

  return (
    <ol className="flex flex-col gap-1.5">
      <AnimatePresence initial={false} mode="popLayout">
        {steps.map((step, i) => {
          const answer = answerFor(answers, step.id);
          const lead = travellingOption(step, answer);
          const extra = Math.max(0, answer.optionIds.length - 1);
          const typed = freeformActive(step, answer) ? (answer.other ?? "").trim() : "";

          return (
            <motion.li
              key={step.id}
              layout={!reducedMotion}
              initial={reducedMotion ? false : { opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={reducedMotion ? { duration: 0 } : spring}
              className={cn(
                "group flex items-start gap-3 rounded-md border border-hairline bg-raised/50",
                compact ? "px-3 py-2" : "px-3.5 py-2.5",
              )}
            >
              <svg viewBox="0 0 24 24" className="mt-0.5 size-3.5 shrink-0" aria-hidden>
                <path
                  d="M5 12.5 10 17 19 7"
                  fill="none"
                  stroke={accentColor}
                  strokeWidth="3"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>

              <div className="min-w-0 flex-1">
                <span className="block font-display text-[9px] tracking-[0.24em] text-ink-mute uppercase">
                  {step.title}
                </span>

                <span className="mt-0.5 flex flex-wrap items-baseline gap-x-2">
                  <motion.span
                    layoutId={
                      reducedMotion || !lead
                        ? undefined
                        : travelId(uid, step.id, lead.id)
                    }
                    transition={spring}
                    className="block font-display text-[11px] tracking-[0.1em] text-ink uppercase"
                  >
                    {lead?.label ?? "Skipped"}
                  </motion.span>
                  {extra > 0 ? (
                    <motion.span
                      initial={reducedMotion ? false : { opacity: 0 }}
                      animate={{ opacity: 1 }}
                      transition={reducedMotion ? { duration: 0 } : spring}
                      className="font-display text-[10px] tracking-[0.1em] text-ink-mute"
                    >
                      +{extra}
                    </motion.span>
                  ) : null}
                </span>

                {typed ? (
                  <motion.span
                    initial={reducedMotion ? false : { opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={reducedMotion ? { duration: 0 } : spring}
                    className="mt-1 block truncate font-sans text-[12px] text-ink-dim"
                  >
                    {typed}
                  </motion.span>
                ) : null}
              </div>

              <button
                type="button"
                onClick={() => onEdit(i)}
                aria-label={`Edit ${step.title} — ${summarise(step, answer)}`}
                className="shrink-0 rounded-sm px-1.5 py-0.5 font-display text-[9px] tracking-[0.2em] text-ink-mute uppercase transition-colors outline-none hover:text-accent focus-visible:ring-2 focus-visible:ring-accent"
              >
                Edit
              </button>
            </motion.li>
          );
        })}
      </AnimatePresence>
    </ol>
  );
}
```

### 7. `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 |
| --- | --- | --- | --- |
| `layout` | `"rail" | "inline"` | `"rail"` | Where the record of decided steps sits. A rail parks it beside the live step on wide screens; inline stacks it above. |
| `morphDuration` | `number` | `420` | Step change, option reveal and the escape hatch growing open. The flight into the record is a spring and ignores this — stiffness and damping own that one. Range 120–1200 ms. |
| `stiffness` | `number` | `380` | How hard the chosen option is pulled toward its slot in the record. Range 80–800. |
| `damping` | `number` | `34` | How fast that flight settles. Low values let the label overshoot its slot before landing. Range 8–80. |
| `density` | `"comfortable" | "compact"` | `"comfortable"` | Row height, padding and glyph size throughout. |
| `revealStagger` | `number` | `45` | Delay added per option as a step's list arrives. 0 lands the whole group at once. Range 0–200 ms. |
| `shakeIntensity` | `number` | `6` | Travel of the shake when a step is rejected. 0 disables it — the message and the red border still fire, because a rejection with no signal at all is a dead end. Range 0–16 px. |
| `shakeCycles` | `number` | `3` | Round trips in that shake. Each one decays, and the last always ends on centre. Range 1–6. Ignored while `shakeIntensity` is `0`. |
| `showProgress` | `boolean` | `true` | Completion bar and step count above the live step. |
| `autoAdvance` | `boolean` | `false` | Commit a single-choice step the moment it is answered. Never applies to the escape hatch, which needs a sentence first, and it is forced off under reduced motion. |
| `accentColor` | `string (hex)` | `"#a855f7"` | Selection, checked glyph, progress fill and the approve button. |
| `dangerColor` | `string (hex)` | `"#f87171"` | Invalid row border and the rejection message. |

## Usage

```tsx
import ApprovalFlow from "@/components/registry/approval-flow/approval-flow";

<ApprovalFlow
  layout="rail"
  morphDuration={420}
  stiffness={380}
  damping={34}
  density="comfortable"
  revealStagger={45}
  shakeIntensity={6}
  shakeCycles={3}
  showProgress={true}
  autoAdvance={false}
  accentColor="#a855f7"
  dangerColor="#f87171"
/>
```

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`.
- `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.
- The supporting files are part of the component, not examples. Copy every file listed, preserving the directory layout — they import each other by relative path.

## 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.
