Code input
A one-time code in six wells. Paste fills every cell at once, the caret glides to the next one as you type, a wrong code shakes and clears.
npx shadcn@latest add https://captain-ui.vercel.app/r/code-input.jsonApprove the deploy to production
Enter the code sent to the phone ending 4821. This demo accepts 204816.
"use client";
// Captain UI · Code input, MIT. A one-time code in wells: paste fills every cell, the caret glides between them, a wrong code shakes.
import { AnimatePresence, animate, motion, useMotionValue, useReducedMotion } from "motion/react";
import { useEffect, useRef, useState, type ChangeEvent } from "react";
import { EASE, SPRING_LAYOUT, cx } from "@/registry/captain/ui/captain";
export type CodeStatus = "idle" | "checking" | "error" | "success";
type CodeInputProps = {
length?: number;
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/** Called when every cell is filled. Return false (or resolve false) to shake and clear; true to show success. */
onComplete?: (code: string) => boolean | void | Promise<boolean | void>;
/** Overrides the status the component tracks itself. */
status?: CodeStatus;
/** Cell counts per group, e.g. [3, 3]. Defaults to two halves for 6 digits. */
groups?: number[];
autoFocus?: boolean;
disabled?: boolean;
"aria-label"?: string;
className?: string;
};
const CELL = 44;
const GAP = 8;
const SPLIT = 20;
export function CodeInput({
length = 6,
value,
defaultValue = "",
onValueChange,
onComplete,
status: forced,
groups,
autoFocus,
disabled,
className,
...rest
}: CodeInputProps) {
const [inner, setInner] = useState(defaultValue);
const code = (value ?? inner).slice(0, length);
const [own, setOwn] = useState<CodeStatus>("idle");
const status = forced ?? own;
const [focused, setFocused] = useState(false);
const input = useRef<HTMLInputElement>(null);
const prev = useRef(code.length);
const shake = useMotionValue(0);
const reduce = useReducedMotion();
const sizes = groups ?? (length === 6 ? [3, 3] : length === 8 ? [4, 4] : [length]);
// x offset of each cell, with a wider gap between groups.
const lefts: number[] = [];
let x = 0;
sizes.forEach((n, g) => {
for (let k = 0; k < n; k++) {
lefts.push(x);
x += CELL + (k < n - 1 ? GAP : 0);
}
if (g < sizes.length - 1) x += SPLIT;
});
const width = x;
const set = (next: string) => {
if (value === undefined) setInner(next);
onValueChange?.(next);
};
const fail = () => {
setOwn("error");
if (!reduce) animate(shake, [0, -10, 9, -6, 4, -2, 0], { duration: 0.42, ease: "easeOut" });
window.setTimeout(() => {
set("");
setOwn("idle");
input.current?.focus();
}, 700);
};
const check = async (full: string) => {
if (!onComplete) return;
const out = onComplete(full);
if (out instanceof Promise) {
setOwn("checking");
const ok = await out.catch(() => false);
if (ok === false) fail();
else setOwn(ok ? "success" : "idle");
} else if (out === false) fail();
else if (out === true) setOwn("success");
};
const change = (e: ChangeEvent<HTMLInputElement>) => {
if (status === "checking" || status === "success") return;
const next = e.target.value.replace(/\D/g, "").slice(0, length);
prev.current = code.length;
if (own === "error") setOwn("idle");
set(next);
if (next.length === length && next !== code) check(next);
};
// The real caret always sits at the end; the drawn caret shows where it is.
const pin = () => {
const el = input.current;
if (el && (el.selectionStart !== el.value.length || el.selectionEnd !== el.value.length)) el.setSelectionRange(el.value.length, el.value.length);
};
useEffect(() => {
if (autoFocus) input.current?.focus();
}, [autoFocus]);
const at = Math.min(code.length, length - 1);
const caret = focused && status === "idle" && code.length < length;
const tone = status === "error" ? "text-danger" : status === "success" ? "text-success" : status === "checking" ? "text-ink-3" : "text-ink";
return (
<motion.div className={cx("relative select-none", disabled && "opacity-45", className)} style={{ width, height: 52, x: shake }}>
{lefts.map((l, i) => (
<div key={i} className="well absolute top-0 h-[52px] rounded-inner" style={{ left: l, width: CELL }} />
))}
<AnimatePresence>
{caret ? (
<motion.div
key="lens"
aria-hidden
className="raised absolute top-0 grid h-[52px] place-items-center rounded-inner"
style={{ width: CELL }}
initial={{ opacity: 0, scale: 0.96, x: lefts[at] }}
animate={{ opacity: 1, scale: 1, x: lefts[at] }}
exit={{ opacity: 0, scale: 0.96 }}
transition={{ x: reduce ? { duration: 0 } : SPRING_LAYOUT, default: { duration: 0.16, ease: EASE } }}
>
{code.length === at ? (
<motion.span
className="h-6 w-0.5 rounded-[1px] bg-accent"
animate={{ opacity: [1, 1, 0, 0] }}
transition={{ duration: 1.05, times: [0, 0.5, 0.55, 1], repeat: Infinity, ease: "linear" }}
/>
) : null}
</motion.div>
) : null}
</AnimatePresence>
{lefts.map((l, i) => {
const c = code[i];
const fresh = i >= prev.current;
return (
<div key={i} className="pointer-events-none absolute top-0 z-10 grid h-[52px] place-items-center" style={{ left: l, width: CELL }}>
<AnimatePresence initial={false}>
{c ? (
<motion.span
key={c}
className={cx("tnum absolute text-[22px] font-medium transition-colors duration-200", tone)}
initial={{ opacity: 0, y: reduce ? 0 : 6, scale: reduce ? 1 : 0.8 }}
animate={status === "success" && !reduce ? { opacity: 1, y: 0, scale: [1, 1.14, 1] } : { opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, scale: reduce ? 1 : 0.8, transition: { duration: 0.12 } }}
transition={
status === "success"
? { duration: 0.32, ease: EASE, delay: i * 0.04 }
: { duration: 0.2, ease: EASE, delay: fresh ? (i - prev.current) * 0.035 : 0 }
}
>
{c}
</motion.span>
) : null}
</AnimatePresence>
</div>
);
})}
<input
ref={input}
value={code}
onChange={change}
onFocus={() => {
setFocused(true);
pin();
}}
onBlur={() => setFocused(false)}
onSelect={pin}
onKeyUp={pin}
onPointerUp={pin}
disabled={disabled}
maxLength={length}
inputMode="numeric"
pattern="[0-9]*"
autoComplete="one-time-code"
spellCheck={false}
aria-label={rest["aria-label"] ?? "Verification code"}
aria-invalid={status === "error" || undefined}
className="absolute inset-0 z-20 h-full w-full cursor-text bg-transparent text-[16px] text-transparent caret-transparent outline-none selection:bg-transparent disabled:cursor-not-allowed"
/>
<span role="status" className="sr-only">
{status === "error" ? "That code is wrong. Try again." : status === "success" ? "Code accepted." : status === "checking" ? "Checking the code." : ""}
</span>
</motion.div>
);
}Usage
import { CodeInput } from "@/components/ui/code-input"
<CodeInput onComplete={async (code) => (await verify(code)).ok} />Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| length | number | 6 | How many digits. |
| value | string | Controlled value. | |
| defaultValue | string | "" | Initial value when uncontrolled. |
| onValueChange | (value: string) => void | Called on every keystroke or paste. | |
| onComplete | (code: string) => boolean | void | Promise<boolean | void> | Called when full. false shakes and clears, true shows success; a promise shows checking until it settles. | |
| status | "idle" | "checking" | "error" | "success" | Drive the state yourself instead. | |
| groups | number[] | [3, 3] | Cells per group; groups get a wider gap. |
| autoFocus | boolean | Focus on mount. | |
| disabled | boolean | Dims and ignores input. |
Keyboard
- 0–9
- Type into the next cell
- Backspace
- Clear the last cell
- Cmd/Ctrl + V
- Paste the whole code
Accessibility
- One real input with autocomplete=one-time-code, so SMS codes autofill on iOS and Android.
- The status (checking, wrong, accepted) is announced through a polite live region.
- aria-invalid is set while a wrong code is shown.