Specification
- Catalogue
- No. 84 of 110
- Section
- Forms and inputs
- Interaction
- Type, Feedback
- Element
- Input, Form
- Preview
- Live component
- Imports
- react 19.3.1, framer-motion 12.40.0
- Added
Notes
Four boxes that are one single input underneath, so paste, the phone's code autofill and backspace all work. A full code is checked: the right one closes the boxes into a Verified capsule, a wrong one shakes and clears.
Two-step sign-in and phone checks are common on booking and finance sites, and one field is the accessible way to build them: it is read as a single "4-digit code", and the browser does the typing. Pressing the capsule splits it back into empty boxes.
Each digit swells its box by 4% over 260ms; a paste runs along the row 45ms apart. A full code waits 420ms while the boxes dim, then either merges on a spring a little under critical damping (the boxes' travel is clamped and only the capsule takes the overshoot, stretching long and thin and settling round) or shakes each box on a decaying wave (5px, 190ms decay, offset per box, 620ms) before clearing. The input keeps inputMode="numeric" and autocomplete="one-time-code". The status line is announced. Cuts straight to each result under reduced motion.
Six separate inputs with a gliding focus ring would each have to handle paste themselves; a single input lets the browser's own autofill and editing work. The boxes slide together without a gooey merge filter.
The code in the preview is fixed (4821) and checking is simulated.
Code
React and plain CSS"use client";
import { useEffect, useId, useRef, useState, type CSSProperties } from "react";
import { animate, motion, useMotionValue, useTransform, type MotionValue } from "framer-motion";
import type { LivePreviewProps } from "@/components/live/types";
import { useSafeReducedMotion } from "@/components/pieces/kit/use-safe-reduced-motion";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./code-field.css";
const N = 4;
const W = 46;
const H = 56;
const G = 8;
const ROW = N * W + (N - 1) * G;
const CAP = 148;
const RIGHT = "4821";
const CHECK_MS = 420;
const SHAKE_MS = 620;
/** A little under critical damping, so the capsule runs past its size and settles back. */
const MERGE = { type: "spring" as const, stiffness: 270, damping: 14, mass: 1 };
const clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v));
const mix = (a: number, b: number, t: number) => a + (b - a) * t;
const smooth = (a: number, b: number, v: number) => {
const u = clamp((v - a) / (b - a), 0, 1);
return u * u * (3 - 2 * u);
};
type Phase = "type" | "check" | "ok" | "no";
/** A decaying side-to-side wave, offset per cell so the row ripples rather than jumps. */
function shakeFrames(i: number): Keyframe[] {
return Array.from({ length: 32 }, (_, k) => {
const t = (k / 31) * SHAKE_MS;
const x = 5 * Math.exp(-t / 190) * Math.sin((t / 1000) * Math.PI * 2 * 10 + i * 0.55);
return { translate: `${x.toFixed(2)}px 0` };
});
}
function Cell({ i, m, digit, wave }: { i: number; m: MotionValue<number>; digit: string | undefined; wave: number }) {
// Cells travel to the middle only as far as the merge goes; the overshoot belongs to the capsule alone.
const x = useTransform(m, (v) => mix(i * (W + G), (ROW - W) / 2, clamp(v, 0, 1)));
const radius = useTransform(m, (v) => mix(12, H / 2, smooth(0.15, 0.7, clamp(v, 0, 1))));
const fade = useTransform(m, (v) => 1 - smooth(0, 0.6, clamp(v, 0, 1)));
return (
<motion.span className="cd-cell" style={{ x, opacity: fade }}>
<motion.span className="cd-box" data-cell={i} style={{ borderRadius: radius }}>
{digit && (
<span key={digit} className="cd-digit" style={{ "--pop-delay": `${wave * 45}ms` } as CSSProperties}>
{digit}
</span>
)}
</motion.span>
</motion.span>
);
}
function CodeFieldDemo() {
const reduce = useSafeReducedMotion();
const uid = useId();
const [code, setCode] = useState("");
const [phase, setPhase] = useState<Phase>("type");
const [focus, setFocus] = useState(false);
const [wave, setWave] = useState<number[]>([]);
const input = useRef<HTMLInputElement>(null);
const row = useRef<HTMLDivElement>(null);
const timers = useRef<number[]>([]);
const m = useMotionValue(0);
const over = useTransform(m, (v) => Math.max(-0.12, v - 1));
const capW = useTransform(m, (v) => CAP * smooth(0.3, 1, clamp(v, 0, 1.5)) * (1 + Math.max(-0.12, v - 1) * 0.9));
const capSy = useTransform(over, (o) => 1 - o * 0.55);
const capX = useTransform(capW, (w) => (ROW - w) / 2);
const okOpacity = useTransform(m, (v) => smooth(0.72, 1, v));
const later = (fn: () => void, ms: number) => timers.current.push(window.setTimeout(fn, ms));
useEffect(() => () => timers.current.forEach((t) => window.clearTimeout(t)), []);
const fuse = (to: 0 | 1) => {
if (reduce) m.jump(to);
else animate(m, to, MERGE);
};
const onChange = (raw: string) => {
if (phase !== "type") return;
const next = raw.replace(/\D/g, "").slice(0, N);
// Each new digit swells its cell; a paste runs along the row 45ms apart.
if (next.length > code.length) setWave(Array.from({ length: N }, (_, i) => Math.max(0, i - code.length)));
setCode(next);
if (next.length < N) return;
setPhase("check");
later(
() => {
if (next === RIGHT) {
setPhase("ok");
fuse(1);
return;
}
setPhase("no");
if (!reduce) row.current?.querySelectorAll<HTMLElement>(".cd-box").forEach((el, i) => el.animate(shakeFrames(i), { duration: SHAKE_MS }));
later(() => {
setCode("");
setPhase("type");
}, reduce ? 900 : SHAKE_MS + 300);
},
reduce ? 0 : CHECK_MS,
);
};
// Pressing the capsule splits it back into empty cells.
const reopen = () => {
if (phase !== "ok") return;
setCode("");
setPhase("type");
fuse(0);
input.current?.focus();
};
const status = phase === "check" ? "Checking the code" : phase === "ok" ? "Verified" : phase === "no" ? "That code did not match. Try again." : "";
return (
<div className="dm cd">
<label className="cd-label" htmlFor={`${uid}-in`}>
Enter the code we texted you
</label>
<div ref={row} className="cd-row" data-phase={phase} style={{ width: ROW, height: H }}>
{Array.from({ length: N }, (_, i) => (
<Cell key={i} i={i} m={m} digit={code[i]} wave={wave[i] ?? 0} />
))}
<motion.span className="cd-cap" aria-hidden="true" style={{ width: capW, x: capX, scaleY: capSy, opacity: okOpacity }}>
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
<path d="M5 12.5l4.5 4.5L19 7.5" />
</svg>
Verified
</motion.span>
<span className="cd-caret" data-on={(focus && phase === "type" && code.length < N) || undefined} style={{ translate: `${Math.min(code.length, N - 1) * (W + G) + W / 2 - 1}px 0` }} aria-hidden="true" />
<input
ref={input}
id={`${uid}-in`}
className="cd-input"
value={code}
inputMode="numeric"
autoComplete="one-time-code"
pattern="[0-9]*"
maxLength={N}
aria-label={phase === "ok" ? "Verified. Press to enter a new code" : "4-digit code"}
aria-describedby={`${uid}-st`}
readOnly={phase !== "type"}
onChange={(e) => onChange(e.target.value)}
onFocus={() => setFocus(true)}
onBlur={() => setFocus(false)}
onPointerDown={(e) => {
if (phase === "ok") {
e.preventDefault();
reopen();
}
}}
onKeyDown={(e) => {
if (phase === "ok" && (e.key === "Enter" || e.key === " ")) {
e.preventDefault();
reopen();
}
}}
/>
</div>
<p id={`${uid}-st`} className="cd-status" role="status" data-phase={phase}>
{status || "The code in this preview is 4821."}
</p>
</div>
);
}
// What a hovered card shows: a wrong code shaking clear, then the right one closing into Verified.
const TOUR: Tour = [
{ input: ".cd-input", value: "1937", wait: 1500 },
{ input: ".cd-input", value: "4821", wait: 1800 },
];
export default function CodeFieldEntry(props: LivePreviewProps) {
return (
<PieceStage {...props} label="Code field that behaves as one input" tour={TOUR}>
<CodeFieldDemo />
</PieceStage>
);
}