{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "code-input",
  "title": "Code Input",
  "description": "A calm code field with a caret that glides between underlined slots. Digits rise into place, pasted codes stream in, a line runs while checking, and on success the underlines join into one with a check. Optional masking.",
  "dependencies": [
    "motion"
  ],
  "files": [
    {
      "path": "src/components/code-input/code-input.tsx",
      "content": "// Brio UI · code-input · MIT License · Copyright (c) 2026 Harjot Singh Rana · https://brioui.com/docs/components/code-input\n'use client'\n/*\n * Reduced-motion preference, hydration-safe: the server and the hydrating render both read\n * `false`, then React re-renders with the real value, so server HTML and the first client\n * render always agree.\n */\nconst REDUCED_QUERY = '(prefers-reduced-motion: reduce)'\nfunction subscribeReduced(onChange: () => void) {\n  const mq = window.matchMedia(REDUCED_QUERY)\n  mq.addEventListener('change', onChange)\n  return () => mq.removeEventListener('change', onChange)\n}\nconst getReduced = () => window.matchMedia(REDUCED_QUERY).matches\nconst getServerReduced = () => false\n\n/**\n * Code Input — a verification code field that stays calm and still feels alive.\n *\n * Six thin underlines on one baseline. A single caret glides from slot to slot\n * on a spring; each digit rises into place from behind the line. Paste a code\n * (or let the phone autofill it) and the digits stream in one after another.\n * While the code is checked a line runs along the underlines; when it's\n * accepted the six underlines join into one and a check draws itself at the\n * end. A wrong code drops the digits out, right to left, and starts over.\n *\n * Functional:\n *   - one real input: autocomplete=\"one-time-code\" (SMS autofill), paste\n *     anywhere, numeric keyboard, ← → to move, Backspace to go back, click a slot\n *   - `pattern=\"alphanumeric\"` accepts letters too (shown upper-case)\n *   - digits are read from the input's own value changes, so on-screen\n *     keyboards, Android IMEs and voice input work, not just hardware keys\n *   - onComplete(code) → boolean | Promise<boolean>; auto-submits when full\n *   - `mask` shows every entered digit as a dot, never the digit itself\n *   - resend with a cooldown (after each resend; from mount with\n *     `cooldownOnMount`); a rejected `onResend` shows an error and re-enables it\n *   - `ref` exposes { reset(), focus() } to start over (e.g. after success)\n *   - any length, grouped visually (e.g. 3 · 3); in a container narrower than\n *     the field, slots, gaps and digits scale down together so it never overflows\n *\n * Accessible: a single labelled input described by its hint (string or\n * ReactNode); the slots are decorative;\n * checking, success and failure are announced. Reduced motion: digits and\n * caret simply appear, nothing glides or drops.\n *\n * Corners follow --ui-radius-sm (see Theming → Corners).\n * Theme via library tokens (--ui-ink, --ui-surface, --ui-accent) or\n * --code-input-*.\n *\n * Requires: react >= 19, motion >= 11.\n */\nimport { AnimatePresence, animate, motion, useMotionValue } from 'motion/react'\nimport {\n  createElement,\n  useEffect,\n  useId,\n  useImperativeHandle,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type ChangeEvent,\n  type ClipboardEvent,\n  type CSSProperties,\n  type KeyboardEvent,\n  type ReactNode,\n  type Ref,\n} from 'react'\n\n/* Icons: Iconoir (MIT, © 2021 Luca Burgio, iconoir.com), inlined so the component stays dependency-free. */\nconst UI_ICONS = {\n  'refresh': [['path', { d: 'M21.8883 13.5C21.1645 18.3113 17.013 22 12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C16.1006 2 19.6248 4.46819 21.1679 8' }], ['path', { d: 'M17 8H21.4C21.7314 8 22 7.73137 22 7.4V3' }]],\n} as const satisfies Record<string, readonly (readonly [string, Record<string, string>])[]>\n\ntype UiIconName = keyof typeof UI_ICONS\n\nfunction UiIcon({ name, size = 16, className }: { name: UiIconName; size?: number; className?: string }) {\n  return (\n    <svg className={['ui-icon', className].filter(Boolean).join(' ')} viewBox=\"0 0 24 24\" width={size} height={size} fill=\"none\" stroke=\"currentColor\" strokeWidth={1.6} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n      {UI_ICONS[name].map(([tag, attrs], i) => createElement(tag, { key: i, ...attrs }))}\n    </svg>\n  )\n}\n\n/** Imperative handle, from `ref` on {@link CodeInput}. */\nexport type CodeInputHandle = {\n  /** Clear every slot and go back to idle (also after success or mid-check; a pending check's result is ignored). Keeps the resend cooldown. Does not move focus. */\n  reset: () => void\n  /** Focus the input. */\n  focus: () => void\n}\n\n/** Props for {@link CodeInput}. */\nexport type CodeInputProps = {\n  /**\n   * Number of slots (a whole number ≥ 1; anything lower falls back to 1 with a dev warning).\n   * Changing it clears the field.\n   *\n   * @default 6\n   */\n  length?: number\n  /**\n   * Which characters a slot takes. `'numeric'`: digits 0–9 (numeric keyboard). `'alphanumeric'`:\n   * A–Z and 0–9, letters shown and passed upper-case (text keyboard). Anything else in typed or\n   * pasted text is dropped. Changing it clears the field. `'numeric'`: 0–9, number pad.\n   *\n   * @default 'numeric'\n   */\n  pattern?: 'numeric' | 'alphanumeric'\n  /**\n   * `{ reset(), focus() }`: start over after success, or focus from outside. See\n   * [CodeInputHandle](#codeinputhandle).\n   */\n  ref?: Ref<CodeInputHandle>\n  /**\n   * Called with the full code once every slot is filled. Return or resolve `true` to accept.\n   * `false` or a thrown error shows \"That code didn't work. Try again.\", shakes the field and\n   * clears it.\n   */\n  onComplete: (code: string) => boolean | Promise<boolean>\n  /**\n   * Accessible label of the input (visually hidden).\n   * @default 'Verification code'\n   */\n  label?: string\n  /**\n   * Text under the slots when no status message is showing. Always the input's accessible\n   * description: a string or number through a visually hidden copy, any other node by pointing\n   * `aria-describedby` at the visible hint itself (never duplicated, so links inside stay single).\n   * Without a hint the description is \"Enter the N-digit code we sent you\" (\"N-character\" for\n   * `alphanumeric`). Falls back to \"Enter the code we sent you\".\n   *\n   * @default `'Enter the code we sent you'`\n   */\n  hint?: ReactNode\n  /**\n   * Show every entered digit as a dot; the digits never appear on screen.\n   * @default false\n   */\n  mask?: boolean\n  /**\n   * Shows a \"Resend code\" button. Called on press; it clears the field and a returned promise is\n   * awaited (the button stays disabled meanwhile) before focus returns to the input. If it throws\n   * or rejects: \"Couldn't send a new code. Try again.\" shows in the error colour, the cooldown is\n   * cancelled and focus goes to the button. Called when it is pressed; may return a promise. If it\n   * throws or rejects, the field says so, the cooldown is cancelled so it can be retried, and focus\n   * goes back to the button.\n   */\n  onResend?: () => unknown\n  /**\n   * Seconds the resend button stays disabled after each resend. Shown as `Resend in m:ss`\n   * (`h:mm:ss` from an hour up).\n   *\n   * @default 30\n   */\n  resendAfter?: number\n  /**\n   * Also run the `resendAfter` cooldown from mount (the code was just sent when the field appears).\n   * Off by default: \"Resend code\" is available straight away. Before this prop existed the cooldown\n   * always started on mount; pass it to keep that.\n   *\n   * @default false\n   */\n  cooldownOnMount?: boolean\n  /**\n   * Slots per visual group; groups get a wider gap. `0` for no grouping (negative values are\n   * treated as `0`). Visual grouping, e.g. 3 → 123 · 456. 0 (or a negative number) for none.\n   *\n   * @default 3\n   */\n  group?: number\n  /**\n   * Focus the input on mount.\n   * @default false\n   */\n  autoFocus?: boolean\n  /** Extra class on the root (`.ci-root`). */\n  className?: string\n  /** Inline styles on the root, for example `--code-input-accent`. */\n  /**\n   * Replace any UI string: `prompt`, `checking`, `accepted`, `rejected`, `sent`, `sendFailed`,\n   * `resend` and `resendIn(time)`. Pass only the ones you change. Replace any UI string (status\n   * messages, the resend button). See `CodeInputLabels`.\n   *\n   * @default English\n   */\n  labels?: Partial<CodeInputLabels>\n    /** Inline styles on the root. Use it to set the `--code-input-*` variables. */\n  style?: CSSProperties\n}\n\n/** Every UI string. Pass any subset through `labels` to translate or reword. The field's own label is the `label` prop. */\nexport type CodeInputLabels = {\n  /** Under the field before anything is typed, when there's no `hint`. */\n  prompt: string\n  /** While `onComplete` runs. */\n  checking: string\n  /** After `onComplete` resolves true. */\n  accepted: string\n  /** After `onComplete` resolves false (the field clears). */\n  rejected: string\n  /** Right after a resend starts. */\n  sent: string\n  /** When `onResend` throws. */\n  sendFailed: string\n  /** The resend button. */\n  resend: string\n  /** The resend button during the cooldown; `time` is formatted like \"0:25\". */\n  resendIn: (time: string) => string\n}\n\nconst DEFAULT_LABELS: CodeInputLabels = {\n  prompt: 'Enter the code we sent you',\n  checking: 'Checking…',\n  accepted: 'Code accepted',\n  rejected: 'That code didn’t work. Try again.',\n  sent: 'A new code is on its way.',\n  sendFailed: 'Couldn’t send a new code. Try again.',\n  resend: 'Resend code',\n  resendIn: time => `Resend in ${time}`,\n}\n\n/** Mirrored on the root as `data-status`. */\ntype Status = 'idle' | 'checking' | 'ok' | 'error'\n\nconst SLOT = 40 // px per slot (at full size; the field scales down to fit its container)\nconst GAP = 10\nconst GROUP_GAP = 22\nconst HEIGHT = 58\nconst CHECK = 34 // room kept after the last slot for the success check: 12 px gap + 22 px check\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const\nconst RISE = { type: 'spring' as const, stiffness: 520, damping: 34, mass: 0.7 }\n\n/** 75 → \"1:15\", 3725 → \"1:02:05\" */\nconst clock = (s: number) => {\n  const h = Math.floor(s / 3600)\n  const m = Math.floor((s % 3600) / 60)\n  const sec = String(s % 60).padStart(2, '0')\n  return h ? `${h}:${String(m).padStart(2, '0')}:${sec}` : `${m}:${sec}`\n}\n\n// `process.env.NODE_ENV` is replaced at build time by most bundlers; where it\n// isn't and `process` doesn't exist, warn anyway (warnings are once per message)\ndeclare const process: { env: Record<string, string | undefined> }\nconst warned = new Set<string>()\nfunction devWarn(message: string) {\n  let dev = true\n  try {\n    dev = process.env.NODE_ENV !== 'production'\n  } catch {\n    /* no process: treat as development */\n  }\n  if (!dev || warned.has(message)) return\n  warned.add(message)\n  console.warn(message)\n}\n\n/** A whole number ≥ `min`, or `fallback` (with a dev warning) for NaN, ±Infinity and anything below `min`. */\nfunction whole(value: number, min: number, fallback: number, name: string) {\n  if (Number.isFinite(value) && value >= min) return Math.floor(value)\n  devWarn(`CodeInput: \\`${name}\\` must be a whole number ≥ ${min} (got ${value}); using ${fallback}.`)\n  return fallback\n}\n\n/**\n * One-time / verification code field: a single hidden native input drawn as\n * underlined slots. Calls `onComplete` when full; stays read-only after\n * success (call `ref.current.reset()` to start over), clears itself after a failure.\n */\nexport function CodeInput({\n  length: lengthProp = 6,\n  pattern = 'numeric',\n  ref,\n  onComplete,\n  label = 'Verification code',\n  hint,\n  mask = false,\n  onResend,\n  resendAfter: resendAfterProp = 30,\n  cooldownOnMount = false,\n  group: groupProp = 3,\n  autoFocus = false,\n  className,\n  style,\n  labels: labelsProp,\n}: CodeInputProps) {\n  const labels = { ...DEFAULT_LABELS, ...labelsProp }\n  const reduced = useSyncExternalStore(subscribeReduced, getReduced, getServerReduced)\n  // degenerate props fall back instead of breaking the math (0 slots would count as \"full\" on mount)\n  const length = whole(lengthProp, 1, Number.isFinite(lengthProp) ? 1 : 6, 'length')\n  const group = whole(groupProp, 0, 0, 'group')\n  const resendAfter = whole(resendAfterProp, 0, 30, 'resendAfter')\n  const uid = useId().replace(/[^a-zA-Z0-9_-]/g, '')\n  const [digits, setDigits] = useState<(string | null)[]>(() => Array(length).fill(null))\n  const [active, setActive] = useState(0)\n  const [focused, setFocused] = useState(false)\n  const [status, setStatus] = useState<Status>('idle')\n  const [message, setMessage] = useState('')\n  const [stagger, setStagger] = useState<number[]>(() => Array(length).fill(0))\n  const [cooldown, setCooldown] = useState(onResend && cooldownOnMount ? resendAfter : 0)\n  const [sending, setSending] = useState(false)\n  const [resendFailed, setResendFailed] = useState(false)\n  const resendRef = useRef<HTMLButtonElement>(null)\n  // after a failed resend, focus the button once it is enabled again (a counter, so a second failure refocuses)\n  const [refocusResend, setRefocusResend] = useState(0)\n  // bumped by reset(): a check or clean-up that started under an older epoch does nothing\n  const epoch = useRef(0)\n  const inputRef = useRef<HTMLInputElement>(null)\n  const shake = useMotionValue(0)\n  const alive = useRef(true)\n  const composing = useRef(false)\n  // Backspace/Delete already handled on keydown: ignore the input event if the browser still sends one\n  const keyHandled = useRef(false)\n\n  /* keep only the characters a slot takes */\n  const clean = (text: string) => (pattern === 'alphanumeric' ? text.replace(/[^a-z0-9]/gi, '').toUpperCase() : text.replace(/\\D/g, ''))\n\n  /* a new `length` or `pattern` starts the field over */\n  const [shape, setShape] = useState(`${length}:${pattern}`)\n  if (shape !== `${length}:${pattern}`) {\n    setShape(`${length}:${pattern}`)\n    setDigits(Array(length).fill(null))\n    setStagger(Array(length).fill(0))\n    setActive(0)\n    setStatus('idle')\n    setMessage('')\n  }\n\n  useEffect(() => {\n    alive.current = true\n    return () => {\n      alive.current = false\n    }\n  }, [])\n\n  useEffect(() => {\n    if (cooldown <= 0) return\n    const t = setTimeout(() => setCooldown(c => c - 1), 1000)\n    return () => clearTimeout(t)\n  }, [cooldown])\n\n  // left edge of slot i: the regular pitch plus the extra group gap for each completed group before it\n  const x = (i: number) => i * (SLOT + GAP) + (group > 0 ? Math.floor(i / group) * (GROUP_GAP - GAP) : 0)\n  const width = x(length - 1) + SLOT\n  /*\n   * One design pixel, as a length. It is exactly 1px while the slots and the success\n   * check fit their track; narrower than that, every slot, gap and glyph scales down\n   * together, so the check never lands on the last digit.\n   */\n  const unit = `min(1px, calc((100cqw - ${CHECK}px) / ${width}))`\n  const code = digits.map(d => (d === null ? '' : String(d))).join('')\n  const full = digits.every(d => d !== null)\n  const locked = status === 'checking' || status === 'ok'\n\n  /* when the last digit lands, check the code */\n  // latest-closure ref instead of useEffectEvent, so React 19.0/19.1 still work\n  const verifyRef = useRef<(isCancelled: () => boolean) => void>(() => {})\n  const verify = (isCancelled: () => boolean) => verifyRef.current(isCancelled)\n  const verifyImpl = (isCancelled: () => boolean) => {\n    if (status !== 'idle') return\n    // only take focus back after an error if the field had it: an autofill or paste elsewhere\n    // must not steal focus or scroll the page to this field\n    const hadFocus = document.activeElement === inputRef.current\n    const run = async () => {\n      // wait for pasted digits to finish streaming in before saying anything\n      const streaming = Math.max(0, ...stagger) * 1000\n      await new Promise(r => setTimeout(r, reduced ? 0 : 200 + streaming))\n      if (isCancelled() || !alive.current) return\n      const at = epoch.current\n      setStatus('checking')\n      setMessage(labels.checking)\n      await new Promise(r => setTimeout(r, reduced ? 0 : 250))\n      let ok = false\n      try {\n        ok = await onComplete(code)\n      } catch {\n        ok = false\n      }\n      if (isCancelled() || !alive.current || at !== epoch.current) return\n      if (ok) {\n        // focus stays on the (now read-only) input so keyboard and screen reader users aren't dropped to <body>\n        setStatus('ok')\n        setMessage(labels.accepted)\n        return\n      }\n      setStatus('error')\n      setMessage(labels.rejected)\n      if (!reduced) {\n        shake.set(-1)\n        animate(shake, 0, { type: 'spring', velocity: 320, stiffness: 900, damping: 16 })\n      }\n      // digits drop out right to left, then the field is ready again\n      setStagger(Array.from({ length }, (_, i) => (length - 1 - i) * 0.045))\n      setTimeout(() => {\n        if (!alive.current || at !== epoch.current) return\n        setDigits(cur => cur.map(() => null))\n        setActive(0)\n        setTimeout(() => {\n          if (!alive.current || at !== epoch.current) return\n          setStagger(cur => cur.map(() => 0))\n          setStatus('idle')\n          if (hadFocus) inputRef.current?.focus({ preventScroll: true })\n        }, reduced ? 0 : 420)\n      }, reduced ? 0 : 380)\n    }\n    run()\n  }\n  useEffect(() => {\n    verifyRef.current = verifyImpl\n  })\n  useEffect(() => {\n    if (!full) return\n    let cancelled = false\n    verify(() => cancelled)\n    return () => {\n      cancelled = true\n    }\n  }, [full, code])\n\n  /* start over: bumping the epoch makes any check or clean-up still in flight a no-op */\n  const reset = () => {\n    epoch.current++\n    setDigits(Array(length).fill(null))\n    setStagger(Array(length).fill(0))\n    setActive(0)\n    setStatus('idle')\n    setMessage('')\n    setResendFailed(false)\n  }\n  // latest-value ref: the handle stays stable while always calling the current reset\n  const resetRef = useRef(reset)\n  useEffect(() => {\n    resetRef.current = reset\n  })\n  useImperativeHandle(ref, () => ({ reset: () => resetRef.current(), focus: () => inputRef.current?.focus() }), [])\n\n  const setAt = (i: number, d: string | null) => {\n    setDigits(cur => cur.map((v, k) => (k === i ? d : v)))\n  }\n\n  const fill = (text: string, from: number) => {\n    const incoming = clean(text).slice(0, length - from).split('')\n    if (!incoming.length) return\n    setStagger(Array.from({ length }, (_, i) => (i >= from ? (i - from) * 0.05 : 0)))\n    setDigits(cur => cur.map((v, k) => (k >= from && k < from + incoming.length ? incoming[k - from] : v)))\n    setActive(Math.min(length - 1, from + incoming.length))\n    setMessage('')\n    setResendFailed(false)\n    setTimeout(() => alive.current && setStagger(cur => cur.map(() => 0)), 700)\n  }\n\n  const typeDigit = (d: string) => {\n    setStagger(Array(length).fill(0))\n    setAt(active, d)\n    setActive(a => Math.min(length - 1, a + 1))\n    setMessage('')\n    setResendFailed(false)\n  }\n\n  const erase = (forward: boolean) => {\n    if (forward) return setAt(active, null)\n    // filled slot: clear it in place; empty slot: step back and clear that one\n    if (digits[active] !== null) setAt(active, null)\n    else if (active > 0) {\n      setAt(active - 1, null)\n      setActive(active - 1)\n    }\n  }\n\n  /* digits never come from keydown: IMEs report key 229 / \"Unidentified\", voice and on-screen keyboards send no keys at all */\n  const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n    keyHandled.current = false\n    if (locked || status === 'error' || e.nativeEvent.isComposing) return\n    if (e.key === 'Backspace' || e.key === 'Delete') {\n      e.preventDefault()\n      keyHandled.current = true\n      setTimeout(() => (keyHandled.current = false), 0)\n      erase(e.key === 'Delete')\n    } else if (e.key === 'ArrowLeft') {\n      e.preventDefault()\n      setActive(a => Math.max(0, a - 1))\n    } else if (e.key === 'ArrowRight') {\n      e.preventDefault()\n      setActive(a => Math.min(length - 1, a + 1, digits.filter(d => d !== null).length))\n    }\n  }\n\n  const onPaste = (e: ClipboardEvent<HTMLInputElement>) => {\n    e.preventDefault()\n    if (locked) return\n    fill(e.clipboardData.getData('text'), 0)\n  }\n\n  /* the input's value is the source of truth for what was typed, said or autofilled */\n  const read = (el: HTMLInputElement, inputType: string) => {\n    const next = el.value\n    const prev = code\n    // put the text back; the effect below writes the new code once state settles\n    el.value = prev\n    if (keyHandled.current || locked || status === 'error' || next === prev) return\n    // diff old vs new text: skip the common prefix and suffix; what's left in between is what was inserted\n    let start = 0\n    while (start < prev.length && start < next.length && prev[start] === next[start]) start++\n    let end = 0\n    while (end < prev.length - start && end < next.length - start && prev[prev.length - 1 - end] === next[next.length - 1 - end]) end++\n    const inserted = clean(next.slice(start, next.length - end))\n    const all = clean(next)\n    if (inputType.startsWith('delete') || (!inserted && next.length < prev.length)) {\n      erase(inputType === 'deleteContentForward')\n    } else if (!inserted) {\n      return\n    } else if (inserted.length >= length || inputType === 'insertReplacementText') {\n      fill(inserted, 0) // SMS autofill writes the whole code at once\n    } else if (inserted.length > 1) {\n      if (all.length >= length) fill(all.slice(-length), 0)\n      else fill(inserted, active)\n    } else typeDigit(inserted)\n  }\n\n  const onChange = (e: ChangeEvent<HTMLInputElement>) => {\n    if (composing.current) return\n    read(e.currentTarget, (e.nativeEvent as InputEvent).inputType ?? '')\n  }\n\n  /* keep the hidden input's text equal to the code (and its caret at the end) */\n  useEffect(() => {\n    const el = inputRef.current\n    if (!el || composing.current) return\n    if (el.value !== code) el.value = code\n    if (document.activeElement === el) el.setSelectionRange(code.length, code.length)\n  }, [code])\n\n  const pick = (i: number) => {\n    if (locked) return\n    // you can revisit any filled slot, or the first empty one\n    const firstEmpty = digits.findIndex(d => d === null)\n    setActive(firstEmpty === -1 ? i : Math.min(i, firstEmpty))\n    inputRef.current?.focus()\n  }\n\n  const resend = async () => {\n    if (cooldown > 0 || sending || !onResend) return\n    reset()\n    setCooldown(resendAfter)\n    setSending(true)\n    setMessage(labels.sent)\n    let failed = false\n    try {\n      await onResend()\n    } catch {\n      failed = true\n    }\n    if (!alive.current) return\n    setSending(false)\n    if (!failed) {\n      inputRef.current?.focus()\n      return\n    }\n    // let them try again straight away; focus waits for the button to be enabled\n    setCooldown(0)\n    setResendFailed(true)\n    setMessage(labels.sendFailed)\n    setRefocusResend(n => n + 1)\n  }\n  useEffect(() => {\n    if (refocusResend) resendRef.current?.focus()\n  }, [refocusResend])\n\n  const hintId = `ci-${uid}-hint`\n  // a string hint gets a hidden copy; any other node is described in place (never duplicated: it may hold links)\n  const plainHint = hint == null || typeof hint === 'string' || typeof hint === 'number'\n  const showCaret = focused && !locked && status !== 'error'\n\n  return (\n    <div className={['ci-root', className].filter(Boolean).join(' ')} style={style} data-status={status}>\n      <CodeInputStyles />\n      <label className=\"ci-sr\" htmlFor={`ci-${uid}`}>\n        {label}\n      </label>\n      <input\n        ref={inputRef}\n        id={`ci-${uid}`}\n        className=\"ci-sr\"\n        type=\"text\"\n        inputMode={pattern === 'alphanumeric' ? 'text' : 'numeric'}\n        autoComplete=\"one-time-code\"\n        autoCapitalize={pattern === 'alphanumeric' ? 'characters' : undefined}\n        autoCorrect=\"off\"\n        spellCheck={false}\n        pattern={pattern === 'alphanumeric' ? '[A-Za-z0-9]*' : '[0-9]*'}\n        aria-describedby={hintId}\n        aria-invalid={status === 'error' || undefined}\n        readOnly={locked}\n        autoFocus={autoFocus}\n        onChange={onChange}\n        onCompositionStart={() => (composing.current = true)}\n        onCompositionEnd={e => {\n          composing.current = false\n          read(e.currentTarget, 'insertText')\n        }}\n        onKeyDown={onKeyDown}\n        onPaste={onPaste}\n        onFocus={() => setFocused(true)}\n        onBlur={() => setFocused(false)}\n      />\n\n      <div className=\"ci-track\" style={{ width: width + CHECK, ...({ '--ci-u': unit, '--ci-w': width } as CSSProperties) }}>\n        <motion.div className=\"ci-field\" aria-hidden style={{ x: shake }}>\n          {digits.map((d, i) => (\n            <div\n              key={i}\n              className=\"ci-slot\"\n              style={{ left: `calc(${x(i)} * var(--ci-u))` }}\n              data-active={(showCaret && i === active) || undefined}\n              data-filled={d !== null || undefined}\n              onMouseDown={e => {\n                e.preventDefault()\n                pick(i)\n              }}\n            >\n              <span className=\"ci-glyph\">\n                <AnimatePresence initial={false}>\n                  {d !== null && (\n                    <motion.span\n                      key={`${d}-${i}`}\n                      className=\"ci-digit\"\n                      data-dot={mask || undefined}\n                      initial={reduced ? { opacity: 0 } : { y: '110%' }}\n                      animate={{ y: 0, scale: 1, opacity: 1 }}\n                      exit={\n                        reduced\n                          ? { opacity: 0 }\n                          : status !== 'error'\n                            ? { opacity: 0, transition: { duration: 0.12 } }\n                            : { y: '110%', transition: { duration: 0.26, ease: [0.55, 0, 1, 0.45], delay: stagger[i] } }\n                      }\n                      transition={reduced ? { duration: 0 } : { ...RISE, delay: stagger[i] }}\n                    >\n                      {/* masked: only ever a dot on screen; the digit lives in the hidden input */}\n                      {mask ? '•' : d}\n                    </motion.span>\n                  )}\n                </AnimatePresence>\n              </span>\n              <motion.i\n                className=\"ci-rule\"\n                initial={false}\n                animate={{ opacity: status === 'ok' ? 0 : 1 }}\n                transition={{ duration: 0.2, delay: status === 'ok' ? 0.35 : 0 }}\n              />\n            </div>\n          ))}\n\n          {/* one caret that glides between slots */}\n          <motion.i\n            className=\"ci-caret\"\n            initial={false}\n            animate={{ x: `${((x(active) + SLOT / 2 - 1) / width) * 100}%`, opacity: showCaret ? 1 : 0 }}\n            transition={reduced ? { duration: 0 } : { x: { type: 'spring', stiffness: 700, damping: 40 }, opacity: { duration: 0.12 } }}\n          />\n\n          {/* checking: a line runs along the underlines; accepted: one continuous line */}\n          <motion.i\n            className=\"ci-run\"\n            initial={false}\n            animate={\n              status === 'checking'\n                ? { scaleX: 0.86, opacity: 1 }\n                : status === 'ok'\n                  ? { scaleX: 1, opacity: 1 }\n                  : { scaleX: 0, opacity: 0 }\n            }\n            transition={\n              status === 'checking'\n                ? { scaleX: { duration: reduced ? 0 : 1.4, ease: EASE_OUT }, opacity: { duration: 0.1 } }\n                : status === 'ok'\n                  ? { duration: reduced ? 0 : 0.32, ease: EASE_OUT }\n                  : { duration: 0.2 }\n            }\n          />\n        </motion.div>\n        {/* outside the field (which clips the caret's full-width box), in the room the track keeps for it */}\n        <svg className=\"ci-check\" aria-hidden viewBox=\"0 0 20 20\" style={{ left: `min(calc(${width + 12} * var(--ci-u)), calc(100cqw - 22px))` }}>\n          <motion.path\n            d=\"M4 10.5 L8.2 14.5 L16 5.5\"\n            initial={false}\n            animate={{ pathLength: status === 'ok' ? 1 : 0, opacity: status === 'ok' ? 1 : 0 }}\n            transition={{ duration: reduced ? 0 : 0.35, ease: EASE_OUT, delay: status === 'ok' && !reduced ? 0.3 : 0 }}\n          />\n        </svg>\n      </div>\n\n      <div className=\"ci-foot\" style={{ minWidth: `min(${width}px, 100%)` }}>\n        <span className=\"ci-msg\" aria-live=\"polite\">\n          <AnimatePresence mode=\"popLayout\" initial={false}>\n            <motion.span\n              key={message || 'hint'}\n              initial={reduced ? { opacity: 0 } : { y: '100%', opacity: 0 }}\n              animate={{ y: 0, opacity: 1 }}\n              exit={reduced ? { opacity: 0 } : { y: '-100%', opacity: 0 }}\n              transition={{ duration: 0.22, ease: EASE_OUT }}\n              data-kind={resendFailed ? 'error' : status}\n              dir=\"auto\"\n              id={!message && !plainHint ? hintId : undefined}\n            >\n              {message || hint || labels.prompt}\n            </motion.span>\n          </AnimatePresence>\n        </span>\n        {plainHint && (\n          <span className=\"ci-sr\" id={hintId}>\n            {hint != null ? String(hint) : `Enter the ${length}-${pattern === 'alphanumeric' ? 'character' : 'digit'} code we sent you`}\n          </span>\n        )}\n        {onResend && status !== 'ok' && (\n          <button ref={resendRef} type=\"button\" className=\"ci-resend\" onClick={resend} disabled={cooldown > 0 || sending}>\n            <UiIcon name=\"refresh\" size={13} />\n            {cooldown > 0 ? labels.resendIn(clock(cooldown)) : labels.resend}\n          </button>\n        )}\n      </div>\n    </div>\n  )\n}\n\n/* ────────────────────────────────────────────────────────────────────────── */\n/* Styles — injected once, hoisted by React 19                               */\n/* ────────────────────────────────────────────────────────────────────────── */\n\nfunction CodeInputStyles() {\n  return (\n    <style href=\"code-input\" precedence=\"medium\">\n      {CSS}\n    </style>\n  )\n}\n\nconst CSS = /* css */ `\n.ci-root {\n  --_ink: var(--code-input-ink, var(--ui-ink, #17140f));\n  --_radius-sm: var(--ui-radius-sm, 8px);\n  --_accent: var(--code-input-accent, var(--ui-accent, #d4452b));\n  --_ok: var(--code-input-ok, var(--ui-ok, #3f8f55));\n  --_muted: color-mix(in oklab, var(--_ink) 62%, transparent);\n  --_rule: color-mix(in oklab, var(--_ink) 22%, transparent);\n  display: inline-flex; flex-direction: column; align-items: flex-start; max-width: 100%; min-width: 0; color: var(--_ink);\n  -webkit-tap-highlight-color: transparent;\n}\n.ci-sr {\n  position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; border: 0;\n  overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap;\n}\n/* codes read left to right in every script: the slots, caret and check keep LTR geometry in RTL pages too\n   (the message line and resend button below still follow the page's direction) */\n.ci-track { position: relative; max-width: 100%; container-type: inline-size; direction: ltr; }\n.ci-field {\n  position: relative; width: calc(var(--ci-w) * var(--ci-u)); height: calc(${HEIGHT} * var(--ci-u));\n  overflow: clip; cursor: text; user-select: none; -webkit-user-select: none;\n}\n.ci-slot { position: absolute; top: 0; width: calc(${SLOT} * var(--ci-u)); height: 100%; }\n.ci-glyph { position: absolute; left: 0; right: 0; top: 0; bottom: calc(8 * var(--ci-u)); display: grid; place-items: end center; overflow: hidden; }\n.ci-digit {\n  display: block; padding-bottom: calc(4 * var(--ci-u));\n  font-size: calc(32 * var(--ci-u)); font-weight: 500; line-height: 1; letter-spacing: -0.02em; font-variant-numeric: tabular-nums;\n}\n.ci-digit[data-dot] { font-size: calc(30 * var(--ci-u)); padding-bottom: calc(8 * var(--ci-u)); }\n.ci-rule {\n  position: absolute; left: 0; right: 0; bottom: 0; height: 2px; border-radius: 2px; background: var(--_rule);\n  transition: background-color 160ms ease;\n}\n.ci-slot[data-filled] .ci-rule { background: color-mix(in oklab, var(--_ink) 55%, transparent); }\n.ci-slot[data-active] .ci-rule { background: var(--_ink); }\n.ci-root[data-status=\"error\"] .ci-rule { background: var(--_accent); }\n.ci-caret {\n  /* as wide as the field, so its x (a percentage) lands on a slot at any scale; the line is ::before */\n  position: absolute; left: 0; top: calc(14 * var(--ci-u)); width: 100%; height: calc(30 * var(--ci-u)); pointer-events: none;\n}\n.ci-caret::before {\n  content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 2px; border-radius: 1px; background: var(--_accent);\n  animation: ci-blink 1.1s steps(1) 12 0.6s;\n}\n@keyframes ci-blink { 50% { visibility: hidden; } }\n.ci-run {\n  position: absolute; left: 0; right: 0; bottom: 0; height: 2px; border-radius: 2px; transform-origin: 0 50%;\n  background: var(--_ink);\n}\n.ci-root[data-status=\"ok\"] .ci-run { background: var(--_ok); }\n.ci-check { position: absolute; bottom: calc(4 * var(--ci-u)); width: 22px; height: 22px; overflow: visible; fill: none; stroke: var(--_ok); stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; }\n\n.ci-foot {\n  display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; column-gap: 16px; row-gap: 4px;\n  margin-top: 14px; min-height: 24px; max-width: 100%;\n}\n/* the message wraps (never clipped); \"Resend\" drops to its own row only when even a short message line won't fit */\n.ci-msg { position: relative; flex: 1 1 9em; min-width: 0; min-height: 20px; overflow: hidden; font-size: 13.5px; line-height: 20px; color: var(--_muted); }\n.ci-msg > span { display: block; text-align: start; text-wrap: pretty; overflow-wrap: anywhere; }\n.ci-msg > span[data-kind=\"error\"] { color: var(--_accent); }\n.ci-msg > span[data-kind=\"ok\"] { color: var(--_ok); font-weight: 550; }\n.ci-root .ci-resend {\n  display: inline-flex; align-items: center; gap: 5px; min-height: 24px;\n  flex: none; margin: 0; padding: 0; border: 0; background: none; cursor: pointer;\n  font: inherit; font-size: 13px; color: var(--_ink); font-variant-numeric: tabular-nums;\n  text-decoration: underline; text-underline-offset: 3px; text-decoration-color: color-mix(in oklab, var(--_ink) 30%, transparent);\n}\n.ci-resend:disabled { color: var(--_muted); cursor: default; text-decoration: none; }\n.ci-resend:focus-visible { outline: 2px solid var(--_accent); outline-offset: 2px; border-radius: calc(var(--_radius-sm) * 0.375); }\n/* a text-sized link: a taller hit area on touch, without moving the row */\n@media (pointer: coarse) {\n  .ci-root .ci-resend { position: relative; }\n  .ci-root .ci-resend::after { content: ''; position: absolute; inset: -10px -8px; }\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .ci-caret::before { animation: none; }\n}\n`\n\nexport default CodeInput\n",
      "type": "registry:ui"
    }
  ],
  "meta": {
    "tier": "free",
    "version": "1.0.0",
    "docs": "https://brioui.com/docs/components/code-input",
    "license": "MIT"
  },
  "docs": "Docs: https://brioui.com/docs/components/code-input",
  "categories": [
    "Forms"
  ],
  "type": "registry:ui"
}