{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "otp-field",
  "title": "OTP field",
  "description": "A one-time code in one field frame (Base UI OTP Field): a cell per character on shared seams, groups split by a join cell, paste and SMS autofill, a Field participant; verification signals pending, done and failed in the frame.",
  "dependencies": [
    "@base-ui/react@1.9.0"
  ],
  "registryDependencies": [
    "@keyline-ui/keyline",
    "utils",
    "@keyline-ui/keyline-render",
    "@keyline-ui/field"
  ],
  "files": [
    {
      "path": "src/registry/keyline/ui/otp-field.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { Field as FieldPrimitive } from \"@base-ui/react/field\";\nimport { mergeProps } from \"@base-ui/react/merge-props\";\nimport { OTPField as OTPFieldPrimitive } from \"@base-ui/react/otp-field\";\nimport { useRender } from \"@base-ui/react/use-render\";\n\nimport { cn } from \"@/lib/utils\";\nimport { type PartProps, resolveClassName, resolveStyle } from \"../lib/keyline-render\";\nimport { FieldMessages, type FieldParticipantProps } from \"./field\";\n\n/*\n * OTP field, as Base UI's parts (OtpFieldRoot, OtpFieldInput, OtpFieldSeparator), Keyline's OtpFieldFrame, and\n * OtpField, the field built from them.\n *\n * One field frame, one cell per character on shared seams, a join cell between groups. The frame is as wide as its\n * code (a code is not a sentence) and never wider than its column. Every part is sized from one scale: the root (the\n * row of slots) is a size container `--kl-otp-u` units wide (one per slot, half per join; set by the frame's\n * `units`), so a slot is exactly 100cqi / u, a join half of that, and the character is half a slot (capped at 22px).\n * Whatever else takes room in the frame (the ! cell when invalid, the ✓ cell when done) shrinks the row, and every slot\n * and its character shrink with it: nothing is pushed past the frame's clipped edge. Below a readable floor (26px a\n * slot) the frame keeps its size and its column overflows: a character is never clipped.\n */\n\ntype Layout = \"control\" | \"cell\";\ntype OtpSignal = \"idle\" | \"pending\" | \"done\" | \"failed\";\ntype OtpRootProps = OTPFieldPrimitive.Root.Props;\n\ntype FrameState = { layout: Layout };\n\nconst frame = cn(\n  \"kl-ctl kl-cells kl-field-frame kl-edge [--kl-otp-floor:26px] [--kl-otp-fs:22px] [--kl-otp-w:44px]\",\n  \"[[data-kl-density=compact]_&]:[--kl-otp-fs:18px] [[data-kl-density=compact]_&]:[--kl-otp-w:34px]\",\n  // as wide as the code, capped by the column; at the floor (slots at 26px, plus one ! or ✓ cell) the cap gives way,\n  // so the column overflows instead of the frame clipping a character\n  \"w-fit max-w-[max(100%,var(--kl-otp-u,6)*var(--kl-otp-floor)+var(--kl-ctl)+2*var(--kl-bw,2px))]\",\n  \"data-[kl-layout=cell]:w-auto data-[kl-layout=cell]:justify-self-stretch\",\n  // the slots are always LTR (a code reads left to right): in an RTL frame the ! cell is on their right, so the red\n  // seam of an invalid field is their inline end, not their start\n  \"kl-rtl:[[data-invalid]_&>.kl-field-bang+*]:border-s-0 kl-rtl:[[data-invalid]_&>.kl-field-bang+*]:border-e-(length:--kl-k1)\",\n  \"kl-rtl:[[data-invalid]_&>.kl-field-bang+*]:border-e-kl-red\",\n);\n\n/**\n * The field frame: the attention cell (inserted at its start, open while the field is invalid), then its children\n * (the OtpFieldRoot, and any signal cells). `units` is the code's width in slots (a join counts half), which sizes\n * every slot. `layout=\"cell\"`: the frame is a cell of an enclosing frame and the code takes the cell's width.\n */\nfunction OtpFieldFrame({\n  layout = \"control\",\n  units,\n  render,\n  className,\n  style,\n  children,\n  ...props\n}: PartProps<\"div\", FrameState> & { layout?: Layout; units?: number }): React.ReactElement {\n  const state = React.useMemo(() => ({ layout }), [layout]);\n  const own = {\n    \"data-slot\": \"otp-field-frame\",\n    \"data-kl-layout\": layout,\n    className: resolveClassName(frame, className)(state),\n    style: resolveStyle(\n      units === undefined ? undefined : ({ \"--kl-otp-u\": units } as React.CSSProperties),\n      style,\n    )(state),\n    children: (\n      <>\n        <span className=\"kl-slot kl-field-bang\" aria-hidden>\n          <span>\n            <span>!</span>\n          </span>\n        </span>\n        {children}\n      </>\n    ),\n  };\n  return useRender({ defaultTagName: \"div\", render, state, props: mergeProps<\"div\">(props, own) });\n}\n\n/**\n * Base UI's OTPField.Root: the row of slots, always left to right. Typing advances, Backspace goes back, arrows move,\n * paste and SMS autofill (`one-time-code`) fill every slot. `onValueChange` gets Base UI's event details last.\n */\nfunction OtpFieldRoot({ className, ...props }: OtpRootProps): React.ReactElement {\n  return (\n    <OTPFieldPrimitive.Root\n      dir=\"ltr\"\n      className={resolveClassName(\n        cn(\n          \"@container flex w-[calc(var(--kl-otp-u,6)*var(--kl-otp-w,44px))] flex-[0_1_auto] items-stretch\",\n          \"min-w-[calc(var(--kl-otp-u,6)*var(--kl-otp-floor,26px))]\",\n          // as a cell, the code owns the cell's width: the slots share it, like keys of a row\n          \"[[data-slot=otp-field-frame][data-kl-layout=cell]>&]:flex-[1_1_auto]\",\n        ),\n        className,\n      )}\n      {...props}\n      data-slot=\"otp-field-root\"\n    />\n  );\n}\n\nconst input = cn(\n  \"m-0 box-border w-[calc(100cqi/var(--kl-otp-u,6))] min-w-0 flex-none appearance-none rounded-none border-0 p-0 outline-none\",\n  \"bg-transparent text-center text-kl-ink caret-kl-focus\",\n  // the Count voice: strong, tabular, large enough to check against the message that brought the code\n  \"font-(family-name:--kl-font) text-[length:min(var(--kl-otp-fs,22px),100cqi/var(--kl-otp-u,6)/2)]/none\",\n  \"font-(--kl-weight-strong) not-italic tabular-nums\",\n  // an empty slot shows where its character goes: a short keyline at the baseline\n  \"bg-[linear-gradient(var(--kl-line-soft),var(--kl-line-soft))] bg-size-[10px_2px] bg-position-[50%_calc(100%-9px)] bg-no-repeat\",\n  \"data-filled:bg-none [[data-kl-density=compact]_&]:bg-position-[50%_calc(100%-6px)]\",\n  \"[[data-slot=otp-field-input]+&]:border-s-(length:--kl-k1) [[data-slot=otp-field-input]+&]:border-s-kl-seam\",\n  \"[[data-slot=otp-field-separator]+&]:border-s-(length:--kl-k1) [[data-slot=otp-field-separator]+&]:border-s-kl-seam\",\n  // the slot being typed into: the frame owns focus (its edge); the slot shows position with a commit keyline on its\n  // floor, the caret's cell. Hover tints like any field.\n  \"hover:not-data-disabled:not-data-readonly:bg-kl-tint focus:bg-kl-tint\",\n  \"focus:shadow-[inset_0_calc(-1*var(--kl-ring))_0_var(--kl-focus)]\",\n  \"selection:bg-kl-yellow selection:text-kl-on-yellow\",\n  // masked: the dot is the Count voice too\n  \"[&[type=password]]:text-[length:min(var(--kl-otp-fs,22px)+4px,100cqi/var(--kl-otp-u,6)*0.6)] [&[type=password]]:tracking-[0]\",\n  // pending verification, disabled and read-only: out of service, the code still readable\n  \"in-data-[signal=pending]:cursor-progress in-data-[signal=pending]:text-kl-ink-2\",\n  \"data-disabled:cursor-not-allowed data-disabled:bg-none data-disabled:text-kl-dis data-readonly:not-data-filled:bg-none\",\n  \"forced-colors:focus:shadow-none forced-colors:focus:outline-2 forced-colors:focus:-outline-offset-4\",\n  \"forced-colors:focus:outline-[Highlight] forced-colors:focus:outline-solid\",\n);\n\n/** One character's cell. Base UI derives each slot's id from the root's `id` (`{id}-2`, `{id}-3`…). */\nfunction OtpFieldInput({ className, ...props }: OTPFieldPrimitive.Input.Props): React.ReactElement {\n  return (\n    <OTPFieldPrimitive.Input className={resolveClassName(input, className)} {...props} data-slot=\"otp-field-input\" />\n  );\n}\n\n/** The join between groups: a drawn dash in its own narrow cell, no seam of its own (the slot after it draws one). */\nfunction OtpFieldSeparator({ className, ...props }: OTPFieldPrimitive.Separator.Props): React.ReactElement {\n  return (\n    <OTPFieldPrimitive.Separator\n      className={resolveClassName(\n        cn(\n          \"box-border grid w-[calc(100cqi/var(--kl-otp-u,6)/2)] flex-none place-items-center\",\n          \"border-s-(length:--kl-k1) border-s-kl-seam\",\n          \"before:h-0.5 before:w-[min(8px,50%)] before:bg-kl-ink-2 before:content-[''] forced-colors:before:bg-[CanvasText]\",\n        ),\n        className,\n      )}\n      {...props}\n      data-slot=\"otp-field-separator\"\n    />\n  );\n}\n\n/* ------------------------------------------------------------------ the field */\n\ntype OtpFieldProps = FieldParticipantProps & {\n  /** Visible label (visually hidden with layout=\"cell\"); it names the first slot, and the rest say \"Character n of N\". */\n  label: React.ReactNode;\n  /** Number of characters. */\n  length: number;\n  /** Split the slots into groups, e.g. [3, 3] for \"123 456\". Must add up to `length`; otherwise one group. */\n  groups?: number[];\n  value?: string;\n  defaultValue?: string;\n  /** Called with the code and Base UI's event details (the reason, the event). */\n  onValueChange?: OtpRootProps[\"onValueChange\"];\n  /** Fired once every slot holds a character (and when a complete code is pasted again). Verify here. */\n  onValueComplete?: OtpRootProps[\"onValueComplete\"];\n  onValueInvalid?: OtpRootProps[\"onValueInvalid\"];\n  /** numeric (default) · alpha · alphanumeric (recovery and invite codes) · none. */\n  validationType?: OtpRootProps[\"validationType\"];\n  normalizeValue?: OtpRootProps[\"normalizeValue\"];\n  inputMode?: OtpRootProps[\"inputMode\"];\n  /** Mask the characters (a PIN). */\n  mask?: boolean;\n  /** Submit the owning form as soon as the code is complete. */\n  autoSubmit?: boolean;\n  /**\n   * The verification of a complete code, shown in the frame (Button's signals):\n   * pending: a segment runs along the bottom keyline and the slots are read-only (aria-busy);\n   * done: a ✓ cell is inserted at the end; failed: the frame turns red, the ! cell is inserted at the start\n   * and, if focus was in the field, the caret returns to the first slot with the code still visible.\n   * Pair failed with `error` (\"That code has expired. Send a new one.\").\n   */\n  signal?: OtpSignal;\n  /** Form name; the submitted value is the code (possibly incomplete). */\n  name?: string;\n  required?: boolean;\n  disabled?: boolean;\n  readOnly?: boolean;\n  /** control: its own 2px frame. cell: a cell of an enclosing frame (label visually hidden). */\n  layout?: Layout;\n  /** Announced politely while pending and when done. Default \"Checking the code…\" and \"Code verified.\" */\n  signalText?: { pending?: string; done?: string };\n  /** Accessible name of slot n (from 2). Default (n, total) => `Character ${n} of ${total}`. */\n  slotLabel?: (n: number, total: number) => string;\n  /** id of the first slot (Base UI derives `{id}-2`, `{id}-3`… for the rest). */\n  id?: string;\n  className?: string;\n} & Omit<React.ComponentProps<\"div\">, \"defaultValue\" | \"onChange\" | \"children\" | \"id\" | \"className\" | \"dir\">;\n\nconst sumOk = (groups: number[] | undefined, length: number) =>\n  !!groups && groups.length > 1 && groups.every((g) => g > 0) && groups.reduce((a, b) => a + b, 0) === length;\n\nconst SLOT = '[data-slot=\"otp-field-input\"]';\n\n/**\n * A one-time code in one field frame (Base UI OTP Field inside a Base UI Field), built from the parts above: every\n * character is a cell on a shared seam, groups are split by a join cell, and the whole code is one Tab stop's worth of\n * typing. A code reads left to right in every script, so the slots stay in that order in RTL; the ! cell and the\n * message follow the page. A Form collects it by `name`; `validate`, `required` and the Form's `errors` reach it like\n * any Field.\n */\nfunction OtpField({\n  label,\n  length,\n  groups,\n  value,\n  defaultValue,\n  onValueChange,\n  onValueComplete,\n  onValueInvalid,\n  validationType,\n  normalizeValue,\n  inputMode,\n  mask,\n  autoSubmit,\n  signal = \"idle\",\n  signalText,\n  name,\n  required,\n  disabled,\n  readOnly,\n  layout = \"control\",\n  slotLabel = (n, total) => `Character ${n} of ${total}`,\n  invalid,\n  error,\n  description,\n  validate,\n  validationMode,\n  orientation,\n  id,\n  className,\n  ...rest\n}: OtpFieldProps) {\n  const frameRef = React.useRef<HTMLDivElement>(null);\n  const pending = signal === \"pending\";\n  const failed = signal === \"failed\";\n\n  // recovery: when a verification fails while the person is still in the field, put the caret back on the\n  // first slot (the code stays visible so they can compare it with the message they received)\n  const prev = React.useRef(signal);\n  React.useEffect(() => {\n    if (failed && prev.current !== \"failed\" && frameRef.current?.contains(document.activeElement)) {\n      const first = frameRef.current.querySelector<HTMLInputElement>(SLOT);\n      first?.focus();\n      first?.select();\n    }\n    prev.current = signal;\n  }, [signal, failed]);\n\n  // Base UI describes only its hidden input; mirror its aria-describedby (description, error) onto the\n  // first visible slot, so they are announced where focus lands. Base UI sets and changes it after render.\n  React.useEffect(() => {\n    const el = frameRef.current;\n    const hidden = el?.querySelector<HTMLInputElement>(\"input[aria-hidden='true']\");\n    if (!el || !hidden) return;\n    const sync = () => {\n      const first = el.querySelector<HTMLInputElement>(SLOT);\n      const ids = hidden.getAttribute(\"aria-describedby\");\n      if (first) ids ? first.setAttribute(\"aria-describedby\", ids) : first.removeAttribute(\"aria-describedby\");\n    };\n    sync();\n    const mo = new MutationObserver(sync);\n    mo.observe(hidden, { attributes: true, attributeFilter: [\"aria-describedby\"] });\n    return () => mo.disconnect();\n  }, []);\n\n  const split = sumOk(groups, length) ? groups! : [length];\n  const slots: React.ReactNode[] = [];\n  let n = 0;\n  split.forEach((g, gi) => {\n    if (gi > 0) slots.push(<OtpFieldSeparator key={`s${gi}`} render={<span />} />);\n    for (let i = 0; i < g; i++, n++) {\n      const k = n + 1;\n      slots.push(<OtpFieldInput key={k} aria-label={k === 1 ? undefined : slotLabel(k, length)} />);\n    }\n  });\n\n  return (\n    <FieldPrimitive.Root\n      data-kl-layout={layout}\n      data-kl-orientation={orientation}\n      data-signal={signal === \"idle\" ? undefined : signal}\n      name={name}\n      disabled={disabled}\n      invalid={invalid || failed || undefined}\n      validate={validate}\n      validationMode={validationMode}\n      className={cn(\"kl-field grid-cols-[minmax(0,1fr)] justify-items-start\", className)}\n      {...(rest as object)}\n      data-slot=\"otp-field\"\n    >\n      <FieldPrimitive.Label className={cn(\"kl-field-label\", layout === \"cell\" && \"kl-sr\")}>\n        {label}\n      </FieldPrimitive.Label>\n      <OtpFieldFrame\n        ref={frameRef}\n        layout={layout}\n        units={length + (split.length - 1) / 2}\n        aria-busy={pending || undefined}\n      >\n        <OtpFieldRoot\n          id={id}\n          length={length}\n          value={value}\n          defaultValue={defaultValue}\n          onValueChange={onValueChange}\n          onValueComplete={onValueComplete}\n          onValueInvalid={onValueInvalid}\n          validationType={validationType}\n          normalizeValue={normalizeValue}\n          inputMode={inputMode}\n          mask={mask}\n          autoSubmit={autoSubmit}\n          required={required}\n          disabled={disabled}\n          readOnly={readOnly || pending}\n        >\n          {slots}\n        </OtpFieldRoot>\n        {/* done: a ✓ cell, inserted at the end, that floods yellow */}\n        <span\n          data-slot=\"otp-field-done\"\n          // closed, it has no seam, even in a disabled frame (whose seams are all drawn)\n          className=\"kl-slot flex-none not-data-open:border-s-transparent\"\n          data-open={signal === \"done\" ? \"\" : undefined}\n          aria-hidden\n        >\n          <span className=\"flex\">\n            <span\n              className={cn(\n                \"grid h-full w-[calc(var(--kl-ctl)-2*var(--kl-bw,2px))] place-items-center bg-kl-yellow text-kl-on-yellow\",\n                \"border-s-(length:--kl-k1) border-s-kl-on-yellow\",\n                \"forced-colors:bg-[Highlight] forced-colors:text-[HighlightText] forced-colors:forced-color-adjust-none\",\n              )}\n            >\n              <svg\n                className=\"kl-tick\"\n                viewBox=\"0 0 16 16\"\n                width=\"14\"\n                height=\"14\"\n                fill=\"none\"\n                stroke=\"currentColor\"\n                strokeWidth=\"2.25\"\n                strokeLinecap=\"square\"\n              >\n                <path pathLength={1} d=\"m3.5 8.5 3 3 6-7\" />\n              </svg>\n            </span>\n          </span>\n        </span>\n        {/* pending: the frame clips (its cut), so the segment runs on the inside of the bottom keyline, over the slot\n            floors */}\n        {pending ? <span className=\"kl-pending bottom-0 z-2 [--kl-bw:3px]\" aria-hidden /> : null}\n      </OtpFieldFrame>\n      <span role=\"status\" className=\"kl-sr\">\n        {pending\n          ? (signalText?.pending ?? \"Checking the code…\")\n          : signal === \"done\"\n            ? (signalText?.done ?? \"Code verified.\")\n            : \"\"}\n      </span>\n      <FieldMessages description={description} error={error} invalid={invalid || failed} layout={layout} />\n    </FieldPrimitive.Root>\n  );\n}\n\nexport { OtpField, OtpFieldFrame, OtpFieldRoot, OtpFieldInput, OtpFieldSeparator, type OtpFieldProps, type OtpSignal };\n",
      "type": "registry:ui",
      "target": "components/keyline/ui/otp-field.tsx"
    }
  ],
  "type": "registry:ui"
}