{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "otp-input",
  "title": "OTP input",
  "description": "One-time code input from plain inputs with auto-advance, paste and SMS autofill, a blinking caret and popping digits, then a pulsing verify, green success bounce or red shake.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/inputs/otp-input.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, motion, useAnimate, useReducedMotion } from \"motion/react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { spring } from \"@/lib/goodui-motion\"\n\nconst CSS = `\n@keyframes pc-otp-input-caret { 0%, 100% { opacity: 1 } 50% { opacity: 0 } }\n.pc-otp-input-caret { animation: pc-otp-input-caret 1.05s step-end infinite }\n@keyframes pc-otp-input-pulse { 0%, 100% { opacity: 1 } 50% { opacity: .45 } }\n.pc-otp-input-verifying .pc-otp-input-cell { animation: pc-otp-input-pulse 1s ease-in-out infinite; animation-delay: calc(var(--i) * 90ms) }\n@media (prefers-reduced-motion: reduce) {\n  .pc-otp-input-caret, .pc-otp-input-verifying .pc-otp-input-cell { animation: none }\n}\n`\n\nexport type OtpStatus = \"idle\" | \"verifying\" | \"success\" | \"error\"\n\nexport type OtpInputProps = Omit<React.ComponentProps<\"div\">, \"onChange\" | \"defaultValue\"> & {\n  /** Number of cells. */\n  length?: number\n  /** Controlled code (no gaps, at most `length` characters). Pair with `onValueChange`. */\n  value?: string\n  /** Initial code when uncontrolled. */\n  defaultValue?: string\n  /** Called with the current code on every change, including paste, autofill and clear-on-error. */\n  onValueChange?: (code: string) => void\n  /**\n   * Called once every cell is filled. Return (or resolve) `true` for success, `false` for error.\n   * While a returned promise is pending the cells pulse and are read-only.\n   */\n  onComplete?: (code: string) => void | boolean | Promise<boolean | void>\n  /** Force a status from outside (e.g. after your own server check). */\n  status?: OtpStatus\n  /** Allowed characters. */\n  allow?: \"numeric\" | \"alphanumeric\"\n  /** Show dots instead of characters (PINs). */\n  mask?: boolean\n  /** Put a separator after every N cells; 0 for none. */\n  groupSize?: number\n  /** Empty the cells and refocus the first one after an error. */\n  clearOnError?: boolean\n  /** Focus the first cell on mount. */\n  autoFocus?: boolean\n  disabled?: boolean\n  /** Form field name for a hidden input with the full code. */\n  name?: string\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<OtpInputLabels>\n}\n\nexport type OtpInputLabels = {\n  character: (index: number, length: number) => string\n  verifying: string\n  success: string\n  error: string\n}\nconst DEFAULT_LABELS: OtpInputLabels = {\n  character: (index, length) => `Character ${index} of ${length}`,\n  verifying: \"Verifying code…\",\n  success: \"Code verified\",\n  error: \"That code is incorrect\",\n}\n\n/** One-time code input from plain inputs: auto-advance, paste and autofill, popping digits, success and error states. */\nexport function OtpInput({\n  length = 6,\n  value,\n  defaultValue = \"\",\n  onValueChange,\n  onComplete,\n  status: statusProp,\n  allow = \"numeric\",\n  mask = false,\n  groupSize = 3,\n  clearOnError = true,\n  autoFocus,\n  disabled,\n  name,\n  labels,\n  className,\n  \"aria-label\": ariaLabel = \"Verification code\",\n  ...props\n}: OtpInputProps) {\n  const l = useLabels(\"otp-input\", DEFAULT_LABELS, labels)\n  const reduce = useReducedMotion() ?? false\n  const [inner, setInner] = React.useState(defaultValue.slice(0, length))\n  const code = (value ?? inner).slice(0, length)\n  const [innerStatus, setInnerStatus] = React.useState<OtpStatus>(\"idle\")\n  const status = statusProp ?? innerStatus\n  const [focused, setFocused] = React.useState(-1)\n  const refs = React.useRef<(HTMLInputElement | null)[]>([])\n  const [rowScope, animateRow] = useAnimate<HTMLDivElement>()\n  const run = React.useRef(0)\n  const onCompleteRef = React.useRef(onComplete)\n  React.useLayoutEffect(() => {\n    onCompleteRef.current = onComplete\n  })\n  // Programmatic focus moves skip the \"jump to first empty cell\" redirect.\n  const internalFocus = React.useRef(false)\n\n  const chars = Array.from({ length }, (_, i) => code[i] ?? \"\")\n  const filter = (s: string) => (allow === \"numeric\" ? s.replace(/\\D/g, \"\") : s.replace(/[^a-z0-9]/gi, \"\").toUpperCase())\n  const locked = disabled || status === \"verifying\" || status === \"success\"\n\n  const setCode = (next: string) => {\n    const v = next.slice(0, length)\n    if (value === undefined) setInner(v)\n    onValueChange?.(v)\n    if (statusProp === undefined && innerStatus !== \"idle\") setInnerStatus(\"idle\")\n  }\n\n  const focusCell = (i: number) => {\n    const el = refs.current[Math.max(0, Math.min(length - 1, i))]\n    if (!el || el === document.activeElement) return\n    internalFocus.current = true\n    el.focus()\n    internalFocus.current = false\n  }\n\n  // Fire onComplete when the code becomes complete, whatever filled it (typing, paste, SMS autofill or a parent).\n  const wasComplete = React.useRef(code.length === length)\n  React.useEffect(() => {\n    const complete = code.length === length\n    if (complete && !wasComplete.current) {\n      const id = ++run.current\n      const finish = (r: boolean | void) => {\n        if (id !== run.current) return\n        if (r === true) setInnerStatus(\"success\")\n        else if (r === false) setInnerStatus(\"error\")\n        else setInnerStatus(\"idle\")\n      }\n      const r = onCompleteRef.current?.(code)\n      if (r && typeof (r as Promise<boolean | void>).then === \"function\") {\n        setInnerStatus(\"verifying\")\n        ;(r as Promise<boolean | void>).then(finish, () => finish(false))\n      } else finish(r as boolean | void)\n    }\n    if (!complete) {\n      run.current++\n      // A parent reset (or deleting a character) leaves the success/verifying state.\n      setInnerStatus((s) => (s === \"error\" ? s : \"idle\"))\n    }\n    wasComplete.current = complete\n  }, [code, length])\n\n  // Error: shake, then optionally clear and refocus.\n  React.useEffect(() => {\n    if (status !== \"error\") return\n    if (!reduce && rowScope.current) animateRow(rowScope.current, { x: [0, -10, 10, -7, 7, -3, 0] }, { duration: 0.45 })\n    if (!clearOnError) return\n    const t = window.setTimeout(() => {\n      if (value === undefined) setInner(\"\")\n      onValueChange?.(\"\")\n      if (statusProp === undefined) setInnerStatus(\"idle\")\n      focusCell(0)\n    }, 650)\n    return () => window.clearTimeout(t)\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [status])\n\n  const fillFrom = (start: number, text: string) => {\n    const clean = filter(text)\n    if (!clean) return\n    // A full-length paste always replaces the whole code.\n    const from = clean.length >= length ? 0 : start\n    const next = chars.slice()\n    for (let k = 0; k < clean.length && from + k < length; k++) next[from + k] = clean[k]!\n    const joined = next.join(\"\")\n    // Keep only the contiguous filled prefix so the code never has holes.\n    const firstHole = next.findIndex((c) => !c)\n    setCode(firstHole === -1 ? joined : next.slice(0, firstHole).join(\"\"))\n    const after = Math.min(from + clean.length, length - 1)\n    focusCell(after)\n  }\n\n  const onInput = (i: number, raw: string) => {\n    const old = chars[i]\n    let incoming = raw\n    if (old && raw.length === 2) incoming = raw.startsWith(old) ? raw.slice(1) : raw.slice(0, 1)\n    const clean = filter(incoming)\n    if (!clean) return\n    if (clean.length > 1) return fillFrom(i, clean)\n    const next = chars.slice()\n    next[i] = clean\n    const firstHole = next.findIndex((c) => !c)\n    setCode(firstHole === -1 ? next.join(\"\") : next.slice(0, firstHole).join(\"\"))\n    if (i < length - 1) focusCell(i + 1)\n  }\n\n  const onKeyDown = (i: number, e: React.KeyboardEvent<HTMLInputElement>) => {\n    if (e.key === \"Backspace\" || e.key === \"Delete\") {\n      e.preventDefault()\n      if (locked) return\n      // Behaves like text: the characters after the removed one shift left.\n      if (chars[i]) {\n        setCode(code.slice(0, i) + code.slice(i + 1))\n      } else if (e.key === \"Backspace\" && i > 0) {\n        setCode(code.slice(0, i - 1) + code.slice(i))\n        focusCell(i - 1)\n      }\n    } else if (e.key === \"ArrowLeft\") {\n      e.preventDefault()\n      focusCell(i - 1)\n    } else if (e.key === \"ArrowRight\") {\n      e.preventDefault()\n      if (chars[i]) focusCell(i + 1)\n    } else if (e.key === \"Home\") {\n      e.preventDefault()\n      focusCell(0)\n    } else if (e.key === \"End\") {\n      e.preventDefault()\n      focusCell(Math.min(code.length, length - 1))\n    }\n  }\n\n  const tone =\n    status === \"success\"\n      ? \"border-emerald-500 bg-emerald-500/5 text-emerald-700 dark:text-emerald-400\"\n      : status === \"error\"\n        ? \"border-destructive bg-destructive/5 text-destructive\"\n        : \"\"\n\n  return (\n    <div className={cn(\"inline-flex flex-col items-center gap-2\", className)} {...props}>\n      <style href=\"pc-otp-input\" precedence=\"default\">\n        {CSS}\n      </style>\n      <div\n        ref={rowScope}\n        role=\"group\"\n        aria-label={ariaLabel}\n        className={cn(\"flex items-center gap-1.5 sm:gap-2\", status === \"verifying\" && \"pc-otp-input-verifying\")}\n      >\n        {chars.map((ch, i) => (\n          <React.Fragment key={i}>\n            {groupSize > 0 && i > 0 && i % groupSize === 0 && (\n              <span aria-hidden=\"true\" className=\"mx-0.5 h-0.5 w-2.5 rounded-full bg-border sm:mx-1\" />\n            )}\n            <motion.div\n              className={cn(\n                \"pc-otp-input-cell relative grid h-12 w-10 place-items-center rounded-lg border border-input bg-background text-xl font-semibold shadow-xs transition-[border-color,box-shadow,background-color,color] sm:h-14 sm:w-12 sm:text-2xl dark:bg-input/30\",\n                ch && \"border-foreground/25\",\n                focused === i && \"border-ring ring-3 ring-ring/50\",\n                tone,\n                disabled && \"opacity-50\",\n              )}\n              style={{ [\"--i\" as string]: i }}\n              animate={status === \"success\" && !reduce ? { y: [0, -6, 0] } : { y: 0 }}\n              transition={status === \"success\" ? { duration: 0.4, delay: i * 0.045, ease: \"easeOut\" } : { duration: 0 }}\n            >\n              <input\n                ref={(el) => {\n                  refs.current[i] = el\n                }}\n                type=\"text\"\n                inputMode={allow === \"numeric\" ? \"numeric\" : \"text\"}\n                autoComplete={i === 0 ? \"one-time-code\" : \"off\"}\n                pattern={allow === \"numeric\" ? \"[0-9]*\" : undefined}\n                aria-label={l.character(i + 1, length)}\n                aria-invalid={status === \"error\" || undefined}\n                autoFocus={autoFocus && i === 0}\n                disabled={disabled}\n                readOnly={locked}\n                value={ch}\n                onChange={(e) => !locked && onInput(i, e.target.value)}\n                onKeyDown={(e) => onKeyDown(i, e)}\n                onPaste={(e) => {\n                  e.preventDefault()\n                  if (!locked) fillFrom(i, e.clipboardData.getData(\"text\"))\n                }}\n                onFocus={(e) => {\n                  // Jump to the first empty cell so the code never has gaps.\n                  if (!internalFocus.current && i > code.length) {\n                    focusCell(code.length)\n                    return\n                  }\n                  setFocused(i)\n                  const el = e.currentTarget\n                  requestAnimationFrame(() => el.select())\n                }}\n                onBlur={() => setFocused((f) => (f === i ? -1 : f))}\n                className=\"absolute inset-0 size-full rounded-lg bg-transparent text-center text-transparent caret-transparent outline-none selection:bg-transparent disabled:cursor-not-allowed\"\n              />\n              <span aria-hidden=\"true\" className=\"pointer-events-none relative\">\n                <AnimatePresence initial={false} mode=\"popLayout\">\n                  {ch ? (\n                    <motion.span\n                      key={ch + i}\n                      className=\"block\"\n                      initial={reduce ? { opacity: 0 } : { opacity: 0, y: 10, scale: 0.5 }}\n                      animate={{ opacity: 1, y: 0, scale: 1 }}\n                      exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, transition: { duration: 0.1 } }}\n                      transition={reduce ? { duration: 0.1 } : spring.play}\n                    >\n                      {mask ? <span className=\"mx-auto block size-3 rounded-full bg-current\" /> : ch}\n                    </motion.span>\n                  ) : focused === i && !locked ? (\n                    <motion.span\n                      key=\"caret\"\n                      initial={{ opacity: 0 }}\n                      animate={{ opacity: 1 }}\n                      exit={{ opacity: 0, transition: { duration: 0 } }}\n                      className=\"block\"\n                    >\n                      <span className=\"pc-otp-input-caret block h-6 w-0.5 rounded-full bg-foreground sm:h-7\" />\n                    </motion.span>\n                  ) : null}\n                </AnimatePresence>\n              </span>\n            </motion.div>\n          </React.Fragment>\n        ))}\n      </div>\n      {name && <input type=\"hidden\" name={name} value={code} />}\n      <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {status === \"idle\" ? \"\" : l[status]}\n      </span>\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/otp-input.tsx"
    }
  ],
  "categories": [
    "components",
    "inputs"
  ],
  "type": "registry:component"
}