# Integrate `Passcode` from Motion Garden

You are helping me add the **Passcode** 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:** Passcode
- **Category:** Micro-interactions
- **Summary:** A one-time-code field whose cells answer every keystroke. Each character lands compressed and springs back, a paste distributes across the row rather than filling it on one frame, a wrong code shakes and clears itself, and a right one folds the whole row into a tick. Underneath there is exactly one real input holding the whole code, which is what keeps SMS autofill, password managers, select-all and a screen reader working. None of those survive six inputs with maxLength one.
- **Reference:** https://motion-garden.netlify.app/components/passcode
- **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-raised: var(--sg-raised);
  --color-hairline: var(--sg-hairline);
  --color-ink: var(--sg-ink);
}

:root {
  --sg-raised: #eceaef;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
}

.dark {
  --sg-raised: #191d21;
  --sg-hairline: #2a2f36;
  --sg-ink: #e2e6e9;
}
```

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

```tsx
"use client";

import { useEffect, useId, useRef, useState } from "react";
import { AnimatePresence, motion } from "motion/react";
import { cn } from "@/lib/utils";

export type PasscodeMode = "numeric" | "alphanumeric";
export type PasscodeStatus = "idle" | "error" | "success";

interface PasscodeProps {
  code?: string;
  length?: number;
  mode?: PasscodeMode;
  mask?: boolean;
  stiffness?: number;
  damping?: number;
  anticipation?: number;
  pasteStagger?: number;
  shakeAmplitude?: number;
  autoSubmit?: boolean;
  submitDelay?: number;
  accentColor?: string;
  errorColor?: string;
  onResolve?: (value: string, ok: boolean) => void;
  reducedMotion?: boolean;
  className?: string;
}

const DIGITS = /[^0-9]/g;
const ALNUM = /[^0-9a-zA-Z]/g;

export default function Passcode({
  code = "424242",
  length = 6,
  mode = "numeric",
  mask = false,
  stiffness = 520,
  damping = 26,
  anticipation = 0.12,
  pasteStagger = 45,
  shakeAmplitude = 10,
  autoSubmit = true,
  submitDelay = 220,
  accentColor = "#a855f7",
  errorColor = "#f87171",
  onResolve,
  reducedMotion = false,
  className,
}: PasscodeProps) {
  const uid = useId();
  const inputRef = useRef<HTMLInputElement>(null);
  const timers = useRef<ReturnType<typeof setTimeout>[]>([]);

  const [value, setValue] = useState("");
  const [caret, setCaret] = useState(0);
  const [focused, setFocused] = useState(false);
  const [status, setStatus] = useState<PasscodeStatus>("idle");

  const size = Math.max(3, Math.min(12, Math.round(length)));

  const clearTimers = () => {
    timers.current.forEach(clearTimeout);
    timers.current = [];
  };
  useEffect(() => clearTimers, []);

  useEffect(() => {
    clearTimers();
    setValue("");
    setCaret(0);
    setStatus("idle");
  }, [size, mode]);

  const clean = (raw: string): string => {
    const stripped = raw.replace(mode === "numeric" ? DIGITS : ALNUM, "");
    const cased = mode === "numeric" ? stripped : stripped.toUpperCase();
    return cased.slice(0, size);
  };

  const settle = (next: string) => {
    if (next.length < size) return;
    const ok = next === clean(code);
    const run = () => {
      setStatus(ok ? "success" : "error");
      onResolve?.(next, ok);
      if (!ok) {
        timers.current.push(
          setTimeout(
            () => {
              setValue("");
              setCaret(0);
              setStatus("idle");
              inputRef.current?.focus();
            },
            reducedMotion ? 700 : 620,
          ),
        );
      }
    };
    if (!autoSubmit) return;
    timers.current.push(setTimeout(run, reducedMotion ? 0 : Math.max(0, submitDelay)));
  };

  const commit = (raw: string) => {
    const next = clean(raw);
    const grew = next.length - value.length;

    clearTimers();
    setStatus("idle");

    if (grew > 1 && pasteStagger > 0 && !reducedMotion) {
      const from = value.length;
      for (let i = from; i < next.length; i++) {
        const slice = next.slice(0, i + 1);
        timers.current.push(
          setTimeout(
            () => {
              setValue(slice);
              setCaret(slice.length);
              if (slice.length === next.length) settle(next);
            },
            (i - from) * pasteStagger,
          ),
        );
      }
      return;
    }

    setValue(next);
    setCaret(next.length);
    settle(next);
  };

  const focusCell = (index: number) => {
    const input = inputRef.current;
    if (!input) return;
    input.focus();
    const at = Math.min(index, value.length);
    timers.current.push(setTimeout(() => input.setSelectionRange(at, at), 0));
    setCaret(at);
  };

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

  const active = focused ? Math.min(caret, size - 1) : -1;
  const shake = shakeAmplitude;

  return (
    <div className={cn("inline-flex flex-col items-center gap-4", className)}>
      <div className="relative">
        <input
          ref={inputRef}
          id={uid}
          value={value}
          onChange={(event) => commit(event.target.value)}
          onSelect={(event) => setCaret(event.currentTarget.selectionStart ?? 0)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          inputMode={mode === "numeric" ? "numeric" : "text"}
          pattern={mode === "numeric" ? "[0-9]*" : undefined}
          autoComplete="one-time-code"
          aria-label={`${size}-character verification code`}
          maxLength={size}
          spellCheck={false}
          className="absolute inset-0 z-10 h-full w-full cursor-default rounded-md text-transparent opacity-0 outline-none"
        />

        <AnimatePresence mode="wait" initial={false}>
          {status === "success" ? (
            <motion.div
              key="done"
              initial={reducedMotion ? false : { scale: 0.7, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={spring}
              className="flex h-14 items-center justify-center gap-3 px-6"
              style={{ color: accentColor }}
            >
              <svg
                width="28"
                height="28"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth={2}
                strokeLinecap="round"
                strokeLinejoin="round"
                aria-hidden
              >
                <motion.path
                  d="M20 6 9 17l-5-5"
                  initial={reducedMotion ? false : { pathLength: 0 }}
                  animate={{ pathLength: 1 }}
                  transition={reducedMotion ? { duration: 0 } : { duration: 0.35, delay: 0.05 }}
                />
              </svg>
              <span className="font-display text-[11px] tracking-[0.22em] uppercase">
                verified
              </span>
            </motion.div>
          ) : (
            <motion.div
              key="cells"
              animate={
                status === "error" && !reducedMotion
                  ? { x: [0, -shake, shake, -shake * 0.6, shake * 0.5, 0] }
                  : { x: 0 }
              }
              transition={
                status === "error" && !reducedMotion
                  ? { duration: 0.42, ease: "easeInOut" }
                  : { duration: 0.15 }
              }
              className="flex items-center gap-2 select-none"
            >
              {Array.from({ length: size }, (_, i) => {
                const char = value[i];
                const filled = char !== undefined;
                const isActive = i === active;
                const border =
                  status === "error"
                    ? errorColor
                    : isActive || filled
                      ? accentColor
                      : undefined;

                return (
                  <div
                    key={i}
                    onPointerDown={(event) => {
                      event.preventDefault();
                      focusCell(i);
                    }}
                    className={cn(
                      "relative flex h-14 w-11 items-center justify-center rounded-md border bg-raised/60 font-mono text-[20px] text-ink tabular-nums transition-colors",
                      border ? "border-transparent" : "border-hairline",
                    )}
                    style={border ? { boxShadow: `inset 0 0 0 1.5px ${border}` } : undefined}
                  >
                    <AnimatePresence initial={false} mode="popLayout">
                      {filled ? (
                        <motion.span
                          key={`${i}-${char}`}
                          initial={
                            reducedMotion
                              ? false
                              : { scale: Math.max(0.2, 1 - anticipation * 3), opacity: 0 }
                          }
                          animate={{ scale: 1, opacity: 1 }}
                          exit={reducedMotion ? { opacity: 0 } : { scale: 0.6, opacity: 0 }}
                          transition={spring}
                        >
                          {mask ? "•" : char}
                        </motion.span>
                      ) : null}
                    </AnimatePresence>

                    {isActive && !filled ? (
                      <motion.span
                        aria-hidden
                        className="absolute h-6 w-px"
                        style={{ backgroundColor: accentColor }}
                        animate={reducedMotion ? { opacity: 1 } : { opacity: [1, 1, 0, 0] }}
                        transition={
                          reducedMotion
                            ? { duration: 0 }
                            : { duration: 1.1, repeat: Infinity, times: [0, 0.5, 0.5, 1] }
                        }
                      />
                    ) : null}
                  </div>
                );
              })}
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      <p
        className="h-4 font-display text-[10px] tracking-[0.22em] uppercase"
        style={{ color: status === "error" ? errorColor : undefined }}
        role="status"
      >
        {status === "error"
          ? "that code is not right"
          : status === "success"
            ? ""
            : " "}
      </p>
    </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 |
| --- | --- | --- | --- |
| `length` | `number` | `6` | Cells in the code. Six is the industry default because it is about the longest string most people can hold in working memory between reading it and typing it — the control exists so you can feel where that stops being true. Range 4–8. |
| `mode` | `"numeric" | "alphanumeric"` | `"numeric"` | What the field accepts. Numeric also asks for the number pad, which matters far more on a phone than the validation does — an alphanumeric code field that opens a full keyboard costs the user two taps every single time. |
| `mask` | `boolean` | `false` | Render dots instead of characters. Off by default on purpose: a one-time code is worthless a minute after it arrives, and masking it only stops the person entitled to read it from checking their own typing. |
| `stiffness` | `number` | `520` | Spring tension of the per-character pop. High enough to land inside the gap between two fast keystrokes, or the cells queue up behind a quick typist and the feedback arrives after the character it is confirming. Range 120–900. |
| `damping` | `number` | `26` | Spring friction. Low rings past and settles, which is the difference between a cell that acknowledges a keystroke and one that merely updates. Range 8–60. |
| `anticipation` | `number` | `0.12` | How far a cell compresses before it springs back. A brief gather in the opposite direction is what makes the pop read as the cell reacting rather than as the cell being resized — at zero it is a plain overshoot and noticeably flatter. Range 0–0.4. |
| `pasteStagger` | `number` | `45` | Delay between cells as a pasted or autofilled code distributes. Zero fills every cell on one frame, which is honest and reads as a glitch; the stagger turns an instantaneous state change into something the eye can follow. Range 0–200 ms. |
| `shakeAmplitude` | `number` | `10` | Lateral travel of the rejection. It moves the whole row rather than the cells individually — a row that shakes has been judged, a set of cells that each shake looks broken. Range 0–24 px. |
| `autoSubmit` | `boolean` | `true` | Judge the code the moment the last cell fills instead of waiting for a button. Correct when a wrong answer costs nothing; wrong the instant it does. |
| `submitDelay` | `number` | `220` | Pause between the last character landing and the verdict. It exists so the final cell finishes its own pop before the row is judged — validating on the same frame steals the confirmation of the keystroke that caused it, and the user never learns their last character registered. Range 0–800 ms. Ignored while `autoSubmit` is `false`. |
| `accentColor` | `string (hex)` | `"#a855f7"` | The focused cell's ring, the filled border, the caret, and the success tick. |
| `errorColor` | `string (hex)` | `"#f87171"` | The rejection. It takes the cell borders rather than flooding the fills, so the code you typed stays readable while you are being told it is wrong. |

## Usage

```tsx
import Passcode from "@/components/registry/passcode/passcode";

<Passcode
  length={6}
  mode="numeric"
  mask={false}
  stiffness={520}
  damping={26}
  anticipation={0.12}
  pasteStagger={45}
  shakeAmplitude={10}
  autoSubmit={true}
  submitDelay={220}
  accentColor="#a855f7"
  errorColor="#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.

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