{"$schema":"https:\/\/ui.shadcn.com\/schema\/registry-item.json","name":"otp-input","type":"registry:block","title":"OTP Input","description":"One-time-code input with a gliding focus ring, digits that roll in per slot, error shake and a success check draw.","author":"Saurabh <saurabh10102@gmail.com>","dependencies":["clsx","motion","tailwind-merge"],"registryDependencies":["https:\/\/beui.dev\/r\/theme.json"],"docs":"OTP Input: usage, props and types at https:\/\/beui.dev\/components\/blocks\/otp-input.md It uses beUI's theme tokens, added with this install.","files":[{"path":"components\/motion\/otp-input.tsx","type":"registry:component","target":"@components\/motion\/otp-input.tsx","content":"\"use client\";\n\/\/ beui.dev\/components\/blocks\/otp-input\n\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useReducedMotion,\n} from \"motion\/react\";\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { EASE_OUT, SPRING_PRESS } from \"@\/lib\/ease\";\nimport { useMessages } from \"@\/lib\/i18n\";\nimport { cn } from \"@\/lib\/utils\";\n\n\/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. *\/\nexport const otpInputMessages = {\n  label: \"One-time passcode\",\n  progress: \"{entered} of {total} digits entered.\",\n  entered: \"{digit}. {progress}\",\n  maskedDigit: \"Digit\",\n  deleted: \"Deleted. {progress}\",\n  position: \"{slot}, digit {position} of {total}.\",\n  filled: \"Filled\",\n  empty: \"Empty\",\n  verified: \"Verified\",\n};\n\nexport type OTPInputMessages = typeof otpInputMessages;\n\nexport type OTPStatus = \"idle\" | \"error\" | \"success\";\n\nexport interface OTPInputProps {\n  \/** Number of slots. Default 6. *\/\n  length?: number;\n  \/** The entered digits, for controlled use. *\/\n  value?: string;\n  \/** The initial digits when uncontrolled. Default: \"\" *\/\n  defaultValue?: string;\n  \/** Called with the entered digits whenever a slot changes. *\/\n  onChange?: (value: string) => void;\n  \/** Fires once every slot is filled. *\/\n  onComplete?: (value: string) => void;\n  \/** Optional label rendered above the slots. *\/\n  label?: string;\n  \/** Helper text shown below the slots while idle. *\/\n  hint?: string;\n  \/** Message shown below the slots when status is \"success\". *\/\n  successMessage?: string;\n  \/** Message shown below the slots when status is \"error\". *\/\n  errorMessage?: string;\n  \/** External validation feedback. \"error\" shakes, \"success\" draws a check. *\/\n  status?: OTPStatus;\n  \/** Render dots instead of the typed digits. *\/\n  mask?: boolean;\n  \/** Block typing and dim the slots. Default: false *\/\n  disabled?: boolean;\n  \/** Focus the input on mount. Default: false *\/\n  autoFocus?: boolean;\n  \/** Accessible label for the underlying input. *\/\n  \"aria-label\"?: string;\n  \/** Override any built-in string. *\/\n  labels?: Partial<OTPInputMessages>;\n  \/** Classes merged onto the root element. *\/\n  className?: string;\n}\n\nexport function OTPInput({\n  length = 6,\n  value: controlledValue,\n  defaultValue = \"\",\n  onChange,\n  onComplete,\n  label,\n  hint,\n  successMessage,\n  errorMessage,\n  status = \"idle\",\n  mask = false,\n  disabled = false,\n  autoFocus = false,\n  \"aria-label\": ariaLabelProp,\n  labels,\n  className,\n}: OTPInputProps) {\n  const t = useMessages(\"otpInput\", otpInputMessages, labels);\n  const ariaLabel = ariaLabelProp ?? t(\"label\");\n  const uid = useId();\n  const reduce = useReducedMotion();\n  const inputRef = useRef<HTMLInputElement>(null);\n  const slotsRef = useRef<HTMLDivElement>(null);\n\n  const controlled = controlledValue !== undefined;\n\n  \/\/ Source of truth is a fixed-length array, so a cleared middle slot stays an\n  \/\/ in-place hole instead of collapsing the digits after it to the left.\n  const [slots, setSlots] = useState<string[]>(() =>\n    toSlots(controlled ? controlledValue : defaultValue, length),\n  );\n  const [focused, setFocused] = useState(false);\n  const [active, setActive] = useState(0);\n  \/\/ The native input holds no value, so screen readers cannot echo what was\n  \/\/ typed. This polite region speaks each change instead; the alternating\n  \/\/ trailing space makes a repeated phrase count as new text.\n  const [announcement, setAnnouncement] = useState(\"\");\n  const announce = (text: string) =>\n    setAnnouncement((previous) =>\n      previous === text ? `${text}\\u00a0` : text,\n    );\n  const spokenSlot = (char: string) =>\n    char ? (mask ? t(\"filled\") : char) : t(\"empty\");\n\n  const joined = slots.join(\"\");\n  const joinedRef = useRef(joined);\n\n  useEffect(() => {\n    joinedRef.current = joined;\n  }, [joined]);\n\n  \/\/ Pull in external value changes; skip when the parent is just echoing our own\n  \/\/ onChange, so internal holes survive the controlled round-trip.\n  useEffect(() => {\n    if (!controlled) return;\n    const incoming = sanitize(controlledValue, length);\n    if (incoming !== joinedRef.current) setSlots(toSlots(incoming, length));\n  }, [controlled, controlledValue, length]);\n\n  const commit = (next: string[]) => {\n    const wasComplete = slots.every((c) => c !== \"\");\n    const changed = next.flatMap((c, i) => (c !== slots[i] ? [i] : []));\n    const progress = t(\"progress\", {\n      entered: next.filter(Boolean).length,\n      total: length,\n    });\n    if (changed.length === 1) {\n      const char = next[changed[0]];\n      announce(\n        char\n          ? t(\"entered\", { digit: mask ? t(\"maskedDigit\") : char, progress })\n          : t(\"deleted\", { progress }),\n      );\n    } else if (changed.length > 1) {\n      announce(progress);\n    }\n    setSlots(next);\n    const str = next.join(\"\");\n    onChange?.(str);\n    \/\/ Fire only on the empty\u2192full transition, not on every edit of a full code.\n    if (!wasComplete && next.every((c) => c !== \"\")) onComplete?.(str);\n  };\n\n  const clearSlot = (idx: number) => {\n    const next = [...slots];\n    next[idx] = \"\";\n    commit(next);\n  };\n\n  const slotFromClientX = (clientX: number) => {\n    const els = slotsRef.current?.children;\n    if (!els) return 0;\n    for (let i = 0; i < els.length; i++) {\n      if (clientX < els[i].getBoundingClientRect().right) return i;\n    }\n    return length - 1;\n  };\n\n  \/\/ Single insertion path: one digit overwrites the active slot and advances; a\n  \/\/ multi-digit chunk (paste \/ SMS autofill) fills forward from the active slot.\n  const insert = (raw: string, from = active) => {\n    const digits = raw.replace(\/\\D\/g, \"\");\n    if (!digits) return;\n    const next = [...slots];\n    let i = from;\n    for (const ch of digits) {\n      if (i >= length) break;\n      next[i] = ch;\n      i++;\n    }\n    commit(next);\n    setActive(Math.min(i, length - 1));\n  };\n\n  \/\/ The keyboard is the single source of truth: preventDefault on keydown\n  \/\/ reliably blocks native insertion (unlike beforeinput in React), so the hidden\n  \/\/ input never accumulates a competing string and slot holes survive.\n  const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n    if (disabled || e.metaKey || e.ctrlKey || e.altKey) return;\n    const k = e.key;\n    if (\/^[0-9]$\/.test(k)) {\n      e.preventDefault();\n      insert(k);\n    } else if (k === \"Backspace\") {\n      e.preventDefault();\n      \/\/ A filled slot clears in place; an empty slot steps back and clears there.\n      if (slots[active]) {\n        clearSlot(active);\n      } else if (active > 0) {\n        clearSlot(active - 1);\n        setActive((current) => Math.max(current - 1, 0));\n      }\n    } else if (k === \"Delete\") {\n      e.preventDefault();\n      clearSlot(active);\n    } else if (\n      k === \"ArrowLeft\" ||\n      k === \"ArrowRight\" ||\n      k === \"Home\" ||\n      k === \"End\"\n    ) {\n      e.preventDefault();\n      const to =\n        k === \"ArrowLeft\"\n          ? Math.max(active - 1, 0)\n          : k === \"ArrowRight\"\n            ? Math.min(active + 1, length - 1)\n            : k === \"Home\"\n              ? 0\n              : length - 1;\n      setActive(to);\n      announce(\n        t(\"position\", {\n          slot: spokenSlot(slots[to] ?? \"\"),\n          position: to + 1,\n          total: length,\n        }),\n      );\n    }\n  };\n\n  const onPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {\n    if (disabled) return;\n    \/\/ preventDefault suppresses the duplicate onChange, keeping that path autofill-only.\n    e.preventDefault();\n    insert(e.clipboardData.getData(\"text\"), active);\n  };\n\n  \/\/ Autofill path: SMS one-time-code arrives as a whole value in one shot.\n  \/\/ Keystrokes go through onKeyDown and paste through onPaste, so only autofill\n  \/\/ reaches here - spread it across the slots from the start.\n  const onChangeNative = (e: React.ChangeEvent<HTMLInputElement>) => {\n    const digits = sanitize(e.target.value, length);\n    if (!digits) return;\n    commit(toSlots(digits, length));\n    setActive(Math.min(digits.length, length - 1));\n  };\n\n  \/\/ Error shake - imperative so it replays on every transition into \"error\".\n  useEffect(() => {\n    if (status !== \"error\" || reduce || !slotsRef.current) return;\n    animate(\n      slotsRef.current,\n      { x: [0, -5, 5, -3, 3, -1, 0] },\n      { duration: 0.45, ease: EASE_OUT },\n    );\n  }, [status, reduce]);\n\n  const showSuccess = status === \"success\";\n  const activeIndex = focused ? active : -1;\n  const message = showSuccess\n    ? successMessage\n    : status === \"error\"\n      ? errorMessage\n      : hint;\n\n  return (\n    <div className={cn(\"inline-flex flex-col gap-2\", className)}>\n      {label ? (\n        <label\n          htmlFor={`${uid}-input`}\n          className=\"text-sm font-medium text-foreground\"\n        >\n          {label}\n        <\/label>\n      ) : null}\n      <fieldset\n        className=\"relative m-0 inline-flex w-max border-0 p-0\"\n        onMouseDown={(e) => {\n          if (disabled) return;\n          \/\/ Suppress the native click-caret; we drive the active slot ourselves.\n          e.preventDefault();\n          \/\/ Clamp to the first empty slot so a click can't jump ahead of progress.\n          const firstEmpty = slots.indexOf(\"\");\n          const cap = firstEmpty === -1 ? length - 1 : firstEmpty;\n          setActive(Math.min(slotFromClientX(e.clientX), cap));\n          inputRef.current?.focus();\n        }}\n      >\n        <input\n          ref={inputRef}\n          id={`${uid}-input`}\n          inputMode=\"numeric\"\n          autoComplete=\"one-time-code\"\n          \/\/ biome-ignore lint\/a11y\/noAutofocus: opt-in via prop for OTP-first screens.\n          autoFocus={autoFocus}\n          disabled={disabled}\n          aria-label={ariaLabel}\n          aria-invalid={status === \"error\"}\n          \/\/ Kept empty on purpose - our state owns the digits, native holds none.\n          value=\"\"\n          maxLength={length}\n          onKeyDown={onKeyDown}\n          onChange={onChangeNative}\n          onPaste={onPaste}\n          onFocus={() => setFocused(true)}\n          onBlur={() => setFocused(false)}\n          \/\/ Transparent overlay owns focus, the soft keyboard, paste and autofill;\n          \/\/ the slots below are purely presentational.\n          className=\"absolute inset-0 z-20 h-full w-full cursor-text bg-transparent text-transparent caret-transparent opacity-0 outline-none disabled:cursor-not-allowed\"\n        \/>\n\n        <div ref={slotsRef} className=\"flex items-center gap-2\">\n          {Array.from({ length }, (_, i) => {\n            const char = slots[i] ?? \"\";\n            const isActive = i === activeIndex;\n            return (\n              <div\n                \/\/ biome-ignore lint\/suspicious\/noArrayIndexKey: fixed-length slot grid, never reordered.\n                key={`${uid}-${i}`}\n                data-active={isActive}\n                data-filled={char !== \"\"}\n                className={cn(\n                  \"relative grid h-14 w-12 place-items-center overflow-hidden rounded-full border text-xl font-medium tabular-nums transition-colors duration-200\",\n                  showSuccess\n                    ? \"border-emerald-500\/60 text-foreground\"\n                    : status === \"error\"\n                      ? \"border-destructive\/60 text-foreground\"\n                      : char\n                        ? \"border-border-strong text-foreground\"\n                        : \"border-border text-muted-foreground\",\n                  \/\/ Active slot reads stronger; twMerge lets this win the border.\n                  isActive && !showSuccess && status !== \"error\" && \"border-foreground\",\n                  disabled && \"opacity-50\",\n                )}\n              >\n                {\/* Blinking caret marks the active slot - centered when empty,\n                    trailing the digit when the slot is already filled. *\/}\n                {isActive && !showSuccess ? (\n                  <motion.span\n                    aria-hidden\n                    animate={reduce ? undefined : { opacity: [1, 1, 0, 0] }}\n                    transition={\n                      reduce\n                        ? undefined\n                        : { duration: 1, repeat: Number.POSITIVE_INFINITY, ease: \"linear\" }\n                    }\n                    className={cn(\n                      \"pointer-events-none absolute top-1\/2 h-6 w-px -translate-y-1\/2 bg-foreground\",\n                      char ? \"right-3\" : \"left-1\/2 -translate-x-1\/2\",\n                    )}\n                  \/>\n                ) : null}\n\n                {\/* Digits roll vertically. Each is absolutely centered so enter and\n                    exit overlap in place - no in-flow reflow, no sideways drift. *\/}\n                <AnimatePresence initial={false}>\n                  {char ? (\n                    <motion.span\n                      key={char}\n                      initial={\n                        reduce\n                          ? { opacity: 0 }\n                          : { y: 14, opacity: 0, filter: \"blur(4px)\" }\n                      }\n                      animate={\n                        reduce\n                          ? { opacity: 1 }\n                          : { y: 0, opacity: 1, filter: \"blur(0px)\" }\n                      }\n                      exit={\n                        reduce\n                          ? { opacity: 0 }\n                          : { y: -14, opacity: 0, filter: \"blur(4px)\" }\n                      }\n                      transition={\n                        reduce\n                          ? { duration: 0 }\n                          : { duration: 0.22, ease: EASE_OUT }\n                      }\n                      className=\"absolute inset-0 grid place-items-center leading-none\"\n                    >\n                      {mask ? \"\u2022\" : char}\n                    <\/motion.span>\n                  ) : null}\n                <\/AnimatePresence>\n              <\/div>\n            );\n          })}\n        <\/div>\n\n        <AnimatePresence>\n          {showSuccess ? (\n            <motion.span\n              initial={reduce ? { opacity: 0 } : { scale: 0.6, opacity: 0 }}\n              animate={reduce ? { opacity: 1 } : { scale: 1, opacity: 1 }}\n              exit={reduce ? { opacity: 0 } : { scale: 0.6, opacity: 0 }}\n              transition={\n                reduce\n                  ? { duration: 0 }\n                  : SPRING_PRESS\n              }\n              className=\"pointer-events-none absolute -right-7 top-1\/2 -translate-y-1\/2 text-emerald-500\"\n              aria-hidden\n            >\n              <svg\n                width=\"20\"\n                height=\"20\"\n                viewBox=\"0 0 24 24\"\n                fill=\"none\"\n                stroke=\"currentColor\"\n                strokeWidth={3}\n                strokeLinecap=\"round\"\n                strokeLinejoin=\"round\"\n              >\n                <title>{t(\"verified\")}<\/title>\n                <motion.path\n                  d=\"M5 13l4 4L19 7\"\n                  initial={reduce ? { pathLength: 1 } : { pathLength: 0 }}\n                  animate={{ pathLength: 1 }}\n                  transition={\n                    reduce\n                      ? { duration: 0 }\n                      : { duration: 0.35, ease: EASE_OUT, delay: 0.1 }\n                  }\n                \/>\n              <\/svg>\n            <\/motion.span>\n          ) : null}\n        <\/AnimatePresence>\n      <\/fieldset>\n\n      <span aria-live=\"polite\" aria-atomic=\"true\" className=\"sr-only\">\n        {announcement}\n      <\/span>\n\n      {message ? (\n        <p\n          aria-live=\"polite\"\n          className={cn(\n            \"text-sm\",\n            showSuccess\n              ? \"text-emerald-500\"\n              : status === \"error\"\n                ? \"text-destructive\"\n                : \"text-muted-foreground\",\n          )}\n        >\n          {message}\n        <\/p>\n      ) : null}\n    <\/div>\n  );\n}\n\nfunction sanitize(raw: string, length: number) {\n  return raw.replace(\/\\D\/g, \"\").slice(0, length);\n}\n\nfunction toSlots(raw: string, length: number) {\n  const digits = sanitize(raw, length);\n  return Array.from({ length }, (_, i) => digits[i] ?? \"\");\n}\n"},{"path":"lib\/ease.ts","type":"registry:lib","target":"@lib\/ease.ts","content":"\/\/ Shared motion tokens. Easing curves mirror the CSS custom properties in\n\/\/ globals.css; springs are the canonical physics used across components.\n\/\/ Strong custom variants - defaults like `ease-in`\/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n\/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. *\/\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n\/** CSS string form of EASE_OUT for inline style transitions. *\/\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n\/** Press feedback on buttons and other tappable surfaces. *\/\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n\/** Content swaps - label\/icon slots trading places inside a control. *\/\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n\/** Overlay panel entrances - modals and sheets summoned by pointer. *\/\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n\/** Shared-layout glides - pills, indicators and panels morphing between positions. *\/\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n\/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). *\/\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n\/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. *\/\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n\/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. *\/\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib\/i18n.tsx","type":"registry:lib","target":"@lib\/i18n.tsx","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n\/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n *\/\nexport type Messages = Record<string, string>;\n\n\/** A language file: component namespace \u2192 any subset of that component's messages. *\/\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n\/** Without a locale, digits stay plain so server and client render the same text. *\/\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  \/** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. *\/\n  locale: string;\n  \/**\n   * Component namespace \u2192 translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   *\/\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}<\/LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n\/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n *\/\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  \/\/ Inline `labels={{ \u2026 }}` is a new object every render. Keying it by content\n  \/\/ keeps `t` one identity until a label changes, so effects and memos that\n  \/\/ depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(\/\\{(\\w+)\\}\/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib\/utils.ts","type":"registry:lib","target":"@lib\/utils.ts","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"}]}