{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "otp-input",
  "title": "OTP Input",
  "description": "A pill that opens into code slots, verifies, and shakes and clears on a wrong code. Paste and SMS autofill work.",
  "dependencies": [
    "motion"
  ],
  "files": [
    {
      "path": "src/registry/easeout/otp-input.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, LayoutGroup, motion, useReducedMotion, type Transition } from \"motion/react\"\n\n/*\n  OTP input by easeout (easeoutstudio.com). Free to use, MIT.\n  Install: npx shadcn@latest add @easeout/otp-input\n  A pill opens into slots, a ring follows the caret, then it morphs into \"Verifying\" and either \"Verified\" or back\n  into the slots in red, which shake and clear right to left. One real <input> sits over the slots, so typing,\n  paste, SMS autofill (autocomplete=\"one-time-code\") and screen readers all work.\n*/\n\ntype Phase = \"idle\" | \"typing\" | \"verifying\" | \"error\" | \"ok\"\n\n/*\n  Keyboard sounds, synthesised with Web Audio (no files): a filtered noise tick plus a short low \"thock\" per key,\n  each slightly randomised so a run of keys never sounds like a machine gun. Quiet by design.\n  The context is created on first use; browsers keep it silent until the page has had a click or a key press.\n*/\nlet audio: AudioContext | null = null\nlet noise: AudioBuffer | null = null\nfunction ctx() {\n  if (typeof window === \"undefined\") return null\n  if (!audio) {\n    const AC = window.AudioContext || (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext\n    if (!AC) return null\n    audio = new AC()\n    noise = audio.createBuffer(1, Math.floor(audio.sampleRate * 0.05), audio.sampleRate)\n    const d = noise.getChannelData(0)\n    for (let i = 0; i < d.length; i++) d[i] = (Math.random() * 2 - 1) * (1 - i / d.length)\n  }\n  if (audio.state === \"suspended\") audio.resume().catch(() => {})\n  return audio\n}\nfunction thock(a: AudioContext, t: number, f0: number, f1: number, gain: number, len = 0.05) {\n  const o = a.createOscillator()\n  const g = a.createGain()\n  o.type = \"triangle\"\n  o.frequency.setValueAtTime(f0, t)\n  o.frequency.exponentialRampToValueAtTime(f1, t + len)\n  g.gain.setValueAtTime(0.0001, t)\n  g.gain.exponentialRampToValueAtTime(gain, t + 0.002)\n  g.gain.exponentialRampToValueAtTime(0.0001, t + len)\n  o.connect(g).connect(a.destination)\n  o.start(t)\n  o.stop(t + len + 0.02)\n}\nconst sfx = {\n  key(soft = false) {\n    const a = ctx()\n    if (!a || !noise || a.state !== \"running\") return\n    const t = a.currentTime\n    const src = a.createBufferSource()\n    src.buffer = noise\n    src.playbackRate.value = 0.9 + Math.random() * 0.25\n    const bp = a.createBiquadFilter()\n    bp.type = \"bandpass\"\n    bp.frequency.value = (soft ? 1800 : 2600) + Math.random() * 1400\n    bp.Q.value = 1.1\n    const g = a.createGain()\n    g.gain.setValueAtTime(0.0001, t)\n    g.gain.exponentialRampToValueAtTime(soft ? 0.12 : 0.22, t + 0.0015)\n    g.gain.exponentialRampToValueAtTime(0.0001, t + 0.035)\n    src.connect(bp).connect(g).connect(a.destination)\n    src.start(t)\n    src.stop(t + 0.05)\n    const base = (soft ? 120 : 165) + Math.random() * 30\n    thock(a, t, base, base * 0.55, soft ? 0.06 : 0.1)\n  },\n  wrong() {\n    const a = ctx()\n    if (!a || a.state !== \"running\") return\n    const t = a.currentTime\n    thock(a, t, 150, 95, 0.14, 0.09)\n    thock(a, t + 0.11, 130, 80, 0.12, 0.1)\n  },\n  right() {\n    const a = ctx()\n    if (!a || a.state !== \"running\") return\n    const t = a.currentTime\n    ;[880, 1318.5].forEach((f, i) => {\n      const o = a.createOscillator()\n      const g = a.createGain()\n      o.type = \"sine\"\n      o.frequency.value = f\n      const s = t + i * 0.11\n      g.gain.setValueAtTime(0.0001, s)\n      g.gain.exponentialRampToValueAtTime(0.07, s + 0.01)\n      g.gain.exponentialRampToValueAtTime(0.0001, s + 0.35)\n      o.connect(g).connect(a.destination)\n      o.start(s)\n      o.stop(s + 0.4)\n    })\n  },\n}\n\nexport type OtpInputProps = {\n  /** Number of digits. */\n  length?: number\n  /** Return true when the code is right. Can be async. */\n  onVerify?: (code: string) => boolean | Promise<boolean>\n  /** Called after the success state has shown. */\n  onSuccess?: (code: string) => void\n  label?: string\n  cta?: string\n  verifying?: string\n  verified?: string\n  wrong?: string\n  /** Plays itself on a loop (a wrong code, then the right one) until the user points at it or focuses it. */\n  autoplay?: boolean\n  /** Keyboard clicks when someone types, plus a knock on a wrong code and a chime on the right one. */\n  sound?: boolean\n  /** Also play the sounds during autoplay. Off by default: sound nobody asked for is annoying. */\n  autoplaySound?: boolean\n  className?: string\n}\n\nconst SPRING: Transition = { type: \"spring\", stiffness: 400, damping: 40, mass: 1 }\nconst SOFT: Transition = { type: \"spring\", stiffness: 300, damping: 30, mass: 1 }\nconst wait = (ms: number) => new Promise((r) => setTimeout(r, ms))\n\nexport function OtpInput({\n  length = 6,\n  onVerify = async (code) => (await wait(1100), code === \"123456\"),\n  onSuccess,\n  label = `One-time code, ${length} digits`,\n  cta = \"Enter code\",\n  verifying = \"Verifying\",\n  verified = \"Verified\",\n  wrong = \"That code didn't work. Try again.\",\n  autoplay = false,\n  sound = true,\n  autoplaySound = false,\n  className,\n}: OtpInputProps) {\n  const reduce = useReducedMotion()\n  const [phase, setPhase] = React.useState<Phase>(\"idle\")\n  const [code, setCode] = React.useState(\"\")\n  const input = React.useRef<HTMLInputElement>(null)\n  const timers = React.useRef<number[]>([])\n  const alive = React.useRef(true)\n  const later = (fn: () => void, ms: number) => timers.current.push(window.setTimeout(fn, reduce ? Math.min(ms, 250) : ms))\n  React.useEffect(() => {\n    alive.current = true\n    const t = timers.current\n    return () => {\n      alive.current = false\n      t.forEach(clearTimeout)\n    }\n  }, [])\n\n  // autoplay: a scripted loop that drives the same states a person would; stops the moment they take over\n  const [human, setHuman] = React.useState(false)\n  React.useEffect(() => {\n    if (!autoplay || human || reduce) return\n    let dead = false\n    const nap = (ms: number) => new Promise<void>((r, j) => {\n      const id = window.setTimeout(() => (dead ? j() : r()), ms)\n      timers.current.push(id)\n    })\n    const loud = sound && autoplaySound\n    const type = async (digits: string) => {\n      for (let i = 1; i <= digits.length; i++) {\n        setCode(digits.slice(0, i))\n        if (loud) sfx.key()\n        await nap(150)\n      }\n    }\n    const run = async () => {\n      for (;;) {\n        await nap(700)\n        setCode(\"\")\n        setPhase(\"typing\")\n        await nap(450)\n        await type(\"482917\".slice(0, length))\n        setPhase(\"verifying\")\n        await nap(1000)\n        setPhase(\"error\")\n        if (loud) sfx.wrong()\n        await nap(700)\n        for (let n = length - 1; n >= 0; n--) {\n          setCode(\"482917\".slice(0, n))\n          if (loud) sfx.key(true)\n          await nap(55)\n        }\n        setPhase(\"typing\")\n        await nap(500)\n        await type(\"123456\".slice(0, length))\n        setPhase(\"verifying\")\n        await nap(1000)\n        setPhase(\"ok\")\n        if (loud) sfx.right()\n        await nap(2000)\n        setCode(\"\")\n        setPhase(\"idle\")\n        await nap(900)\n      }\n    }\n    run().catch(() => {})\n    return () => {\n      // leaving autoplay mid-script: start the person from a clean pill\n      dead = true\n      setCode(\"\")\n      setPhase(\"idle\")\n    }\n  }, [autoplay, human, reduce, length, sound, autoplaySound])\n  const takeOver = () => autoplay && !human && setHuman(true)\n\n  // browsers only start audio after a click or key press; unlock on the first one anywhere on the page\n  React.useEffect(() => {\n    if (!sound || !autoplaySound) return\n    const unlock = () => ctx()\n    document.addEventListener(\"pointerdown\", unlock, { once: true })\n    document.addEventListener(\"keydown\", unlock, { once: true })\n    return () => {\n      document.removeEventListener(\"pointerdown\", unlock)\n      document.removeEventListener(\"keydown\", unlock)\n    }\n  }, [sound, autoplaySound])\n\n  const swap = reduce\n    ? { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 } }\n    : {\n        initial: { opacity: 0, filter: \"blur(6px)\", scale: 0.92 },\n        animate: { opacity: 1, filter: \"blur(0px)\", scale: 1 },\n        exit: { opacity: 0, filter: \"blur(6px)\", scale: 0.92 },\n      }\n\n  const open = () => {\n    if (sound) ctx() // the opening click is the gesture that lets audio start\n    setCode(\"\")\n    setPhase(\"typing\")\n    requestAnimationFrame(() => input.current?.focus())\n  }\n\n  const verify = async (v: string) => {\n    setPhase(\"verifying\")\n    let ok = false\n    try {\n      ok = await onVerify(v)\n    } catch {}\n    if (!alive.current) return\n    if (ok) {\n      setPhase(\"ok\")\n      if (sound) sfx.right()\n      later(() => {\n        onSuccess?.(v)\n        setCode(\"\")\n        setPhase(\"idle\")\n      }, 2600)\n      return\n    }\n    setPhase(\"error\")\n    if (sound) sfx.wrong()\n    // after the shake, clear right to left, then hand the caret back\n    later(() => {\n      let n = v.length\n      const step = () => {\n        n -= 1\n        setCode(v.slice(0, n))\n        if (sound) sfx.key(true)\n        if (n > 0) later(step, 55)\n        else\n          later(() => {\n            setPhase(\"typing\")\n            input.current?.focus()\n          }, 120)\n      }\n      step()\n    }, 700)\n  }\n\n  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    if (phase !== \"typing\") return\n    const v = e.target.value.replace(/\\D/g, \"\").slice(0, length)\n    if (sound && v !== code) sfx.key(v.length < code.length)\n    setCode(v)\n    if (v.length === length) later(() => verify(v), 160)\n  }\n\n  const showSlots = phase === \"typing\" || phase === \"error\"\n  const active = phase === \"typing\" ? Math.min(code.length, length - 1) : -1\n  const status = phase === \"verifying\" ? verifying : phase === \"ok\" ? verified : phase === \"error\" ? wrong : \"\"\n  const pill =\n    \"relative inline-flex h-11 items-center gap-2 overflow-hidden whitespace-nowrap rounded-full border-0 px-5 text-[15px] font-medium tracking-[-0.01em]\"\n\n  return (\n    <LayoutGroup id={React.useId()}>\n      <motion.div\n        layout\n        // the layout morph springs; the error shake is a keyframe tween (springs only take two keyframes)\n        transition={{ ...SPRING, x: { duration: 0.42, ease: \"easeOut\" } }}\n        onPointerEnter={takeOver}\n        onFocus={takeOver}\n        className={[\"relative flex bg-card p-1 shadow-[0_0_0_1px_var(--color-border),0_12px_12px_-3px_rgba(0,0,0,.06),0_3px_3px_-1.5px_rgba(0,0,0,.03)]\", className].filter(Boolean).join(\" \")}\n        style={{ borderRadius: 999 }}\n        animate={phase === \"error\" && !reduce ? { x: [0, -9, 8, -6, 5, -3, 2, 0] } : { x: 0 }}\n      >\n        <AnimatePresence mode=\"popLayout\" initial={false}>\n          {phase === \"idle\" && (\n            <motion.button\n              key=\"idle\"\n              type=\"button\"\n              onClick={open}\n              transition={SOFT}\n              {...swap}\n              className={`${pill} cursor-pointer bg-secondary text-foreground transition-[background-color,scale] duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-[3px] focus-visible:outline-foreground active:scale-[.97] [@media(hover:hover)]:hover:bg-[color-mix(in_srgb,var(--color-foreground)_8%,var(--color-secondary))]`}\n            >\n              <svg viewBox=\"0 0 24 24\" width=\"15\" height=\"15\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" aria-hidden=\"true\">\n                <rect x=\"5\" y=\"11\" width=\"14\" height=\"10\" rx=\"2.5\" />\n                <path d=\"M8 11V8a4 4 0 0 1 8 0v3\" />\n              </svg>\n              {cta}\n            </motion.button>\n          )}\n\n          {showSlots && (\n            <motion.div key=\"slots\" className=\"relative flex gap-1.5 max-[520px]:gap-1\" transition={SOFT} {...swap}>\n              {Array.from({ length }, (_, i) => (\n                <motion.span\n                  key={i}\n                  className={[\n                    \"relative h-11 w-[42px] text-[17px] font-medium tabular-nums transition-colors duration-300 max-[520px]:h-[42px] max-[520px]:w-9\",\n                    i === 0 ? \"rounded-[22px_12px_12px_22px]\" : i === length - 1 ? \"rounded-[12px_22px_22px_12px]\" : \"rounded-xl\",\n                    phase === \"error\" ? \"bg-[color-mix(in_srgb,#E5484D_13%,var(--color-secondary))] text-[#E5484D]\" : \"bg-secondary text-foreground\",\n                  ].join(\" \")}\n                  initial={reduce ? false : { opacity: 0, filter: \"blur(4px)\", scale: 0.8 }}\n                  animate={{ opacity: 1, filter: \"blur(0px)\", scale: 1 }}\n                  transition={{ ...SOFT, delay: reduce ? 0 : i * 0.035 }}\n                >\n                  <AnimatePresence initial={false}>\n                    {code[i] && (\n                      <motion.b\n                        key={code[i] + i}\n                        className=\"absolute inset-0 grid place-items-center font-medium\"\n                        initial={reduce ? { opacity: 0 } : { opacity: 0, y: 10, scale: 0.7, filter: \"blur(4px)\" }}\n                        animate={{ opacity: 1, y: 0, scale: 1, filter: \"blur(0px)\" }}\n                        exit={reduce ? { opacity: 0 } : { opacity: 0, y: -6, scale: 0.7, filter: \"blur(4px)\" }}\n                        transition={SOFT}\n                      >\n                        {code[i]}\n                      </motion.b>\n                    )}\n                  </AnimatePresence>\n                  {i === active && (\n                    <motion.i layoutId=\"otp-ring\" className=\"absolute inset-0 grid place-items-center rounded-[inherit] shadow-[inset_0_0_0_1.5px_var(--color-foreground)]\" transition={SPRING}>\n                      {!code[i] && <span className=\"h-[18px] w-[1.5px] animate-[otp-blink_1.1s_steps(1,end)_infinite] rounded-[1px] bg-foreground motion-reduce:animate-none\" />}\n                    </motion.i>\n                  )}\n                </motion.span>\n              ))}\n              <input\n                ref={input}\n                className=\"absolute inset-0 z-[2] m-0 h-full w-full cursor-text border-0 bg-transparent p-0 text-[16px] text-transparent opacity-0 [caret-color:transparent]\"\n                value={code}\n                onChange={onChange}\n                onBlur={() => phase === \"typing\" && code.length === 0 && setPhase(\"idle\")}\n                onKeyDown={(e) => {\n                  if (e.key !== \"Escape\") return\n                  setCode(\"\")\n                  setPhase(\"idle\")\n                }}\n                readOnly={phase !== \"typing\"}\n                inputMode=\"numeric\"\n                autoComplete=\"one-time-code\"\n                pattern=\"[0-9]*\"\n                maxLength={length}\n                aria-label={label}\n                aria-invalid={phase === \"error\"}\n              />\n            </motion.div>\n          )}\n\n          {phase === \"verifying\" && (\n            <motion.div key=\"verifying\" className={`${pill} bg-secondary text-muted-foreground`} transition={SOFT} {...swap}>\n              <span className=\"size-3.5 animate-spin rounded-full border-[1.75px] border-current border-r-transparent [animation-duration:.7s]\" aria-hidden=\"true\" />\n              {verifying}\n            </motion.div>\n          )}\n\n          {phase === \"ok\" && (\n            <motion.div key=\"ok\" className={`${pill} bg-[#1F9D55] text-white`} transition={SOFT} {...swap}>\n              <span\n                aria-hidden=\"true\"\n                className=\"absolute inset-0 -translate-x-full animate-[otp-shine_900ms_cubic-bezier(.23,1,.32,1)_250ms_both] bg-[linear-gradient(105deg,transparent_30%,rgba(255,255,255,.35)_50%,transparent_70%)] motion-reduce:hidden\"\n              />\n              <svg viewBox=\"0 0 24 24\" width=\"15\" height=\"15\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.4\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n                <motion.path d=\"M5 12.5l4.5 4.5L19 7.5\" initial={{ pathLength: 0 }} animate={{ pathLength: 1 }} transition={{ duration: 0.35, delay: 0.1, ease: [0.16, 1, 0.3, 1] }} />\n              </svg>\n              {verified}\n            </motion.div>\n          )}\n        </AnimatePresence>\n        <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n          {status}\n        </span>\n        <style>{`@keyframes otp-blink{0%,50%{opacity:1}50.01%,100%{opacity:0}}@keyframes otp-shine{to{transform:translateX(100%)}}`}</style>\n      </motion.div>\n    </LayoutGroup>\n  )\n}\n",
      "type": "registry:component"
    }
  ],
  "docs": "Import it with `import { OtpInput } from \"@/components/otp-input\"`. Live demo, props and a usage example: https://www.easeoutstudio.com/lab/otp-input",
  "type": "registry:component"
}