# OTP Field
A one-time code in separate slots.
Source page: https://dinachi.dev/docs/components/otp-field

## Installation
```bash
npx @dinachi/cli@latest add otp-field
```
Adds to your project:
- `components/ui/otp-field/otp-field.tsx`
- `components/ui/otp-field/index.ts`
Installs:
- `@base-ui/react` ^1.9.0

## Usage
```tsx
import { OTPField, OTPFieldGroup, OTPFieldInput } from "@/components/ui/otp-field"

export function VerificationCode() {
  return (
    <OTPField length={6} aria-label="Verification code">
      <OTPFieldGroup>
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
      </OTPFieldGroup>
    </OTPField>
  )
}
```

## Anatomy
```tsx
<OTPField>
  <OTPFieldGroup>
    <OTPFieldInput />
  </OTPFieldGroup>
  <OTPFieldSeparator />
  <OTPFieldGroup>
    <OTPFieldInput />
  </OTPFieldGroup>
</OTPField>
```
- `OTPField`: Holds the code; moves focus between slots.
- `OTPFieldGroup`: A row of joined slots.
- `OTPFieldInput`: One slot. Render one per character.
- `OTPFieldSeparator`: A mark between groups.

## Examples

### Default
Six digits that advance as you type and fill on paste.
```tsx
import { OTPField, OTPFieldGroup, OTPFieldInput } from '@/components/ui/otp-field';

export function Example() {
  return (
    <OTPField length={6}>
      <OTPFieldGroup>
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
      </OTPFieldGroup>
    </OTPField>
  );
}
```

### With separator
The code split into two groups.
```tsx
import { OTPField, OTPFieldGroup, OTPFieldInput, OTPFieldSeparator } from '@/components/ui/otp-field';

export function Example() {
  return (
    <OTPField length={6}>
      <OTPFieldGroup>
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
      </OTPFieldGroup>
      <OTPFieldSeparator>-</OTPFieldSeparator>
      <OTPFieldGroup>
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
      </OTPFieldGroup>
    </OTPField>
  );
}
```

### Masked
Hides each character like a password field.
```tsx
import { OTPField, OTPFieldGroup, OTPFieldInput } from '@/components/ui/otp-field';

export function Example() {
  return (
    <OTPField length={4} mask>
      <OTPFieldGroup>
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
      </OTPFieldGroup>
    </OTPField>
  );
}
```

### Controlled
Tracks the value and reacts once the code is complete.
```tsx
import * as React from 'react';
import { OTPField, OTPFieldGroup, OTPFieldInput } from '@/components/ui/otp-field';

export function Example() {
  const [value, setValue] = React.useState('');
  const [completed, setCompleted] = React.useState<string | null>(null);

  return (
    <div className="space-y-3">
      <OTPField
        length={6}
        value={value}
        onValueChange={(next) => setValue(next)}
        onValueComplete={(next) => setCompleted(next)}
      >
        <OTPFieldGroup>
          <OTPFieldInput />
          <OTPFieldInput />
          <OTPFieldInput />
          <OTPFieldInput />
          <OTPFieldInput />
          <OTPFieldInput />
        </OTPFieldGroup>
      </OTPField>
      <p className="text-sm text-muted-foreground">Value: {value || '(empty)'}</p>
      {completed ? <p className="text-sm text-success">Code complete: {completed}</p> : null}
    </div>
  );
}
```

### Disabled
Blocks input and keeps the value visible.
```tsx
import { OTPField, OTPFieldGroup, OTPFieldInput } from '@/components/ui/otp-field';

export function Example() {
  return (
    <OTPField length={4} defaultValue="1234" disabled>
      <OTPFieldGroup>
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
        <OTPFieldInput />
      </OTPFieldGroup>
    </OTPField>
  );
}
```

## Notes

### Slots
Render exactly `length` OTPFieldInputs, split across any number of groups. Separate groups with `OTPFieldSeparator`.

## API reference
Props marked **agent** change what an agent reads or may do.

### OTPField
Holds the code; moves focus between slots.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `length` **agent** | `number` | - | Required. Number of slots. Longer codes are refused, for agents too. |
| `value` | `string` | - | Controlled value. |
| `defaultValue` | `string` | `""` | Starting value when uncontrolled. |
| `onValueChange` **agent** | `(value, details) => void` | - | Runs for people and agents. `details.cancel()` refuses the change. |
| `onValueComplete` | `(value, details) => void` | - | Runs once every slot is filled. |
| `onValueInvalid` | `(value, details) => void` | - | Runs when typed or pasted characters are rejected. |
| `validationType` **agent** | `"numeric" \| "alpha" \| "alphanumeric" \| "none"` | `"numeric"` | Allowed characters. Agent codes are checked too. |
| `normalizeValue` | `(value: string) => string` | - | Rewrites the value after filtering, such as uppercasing. Must be idempotent. |
| `mask` **agent** | `boolean` | `false` | Hides each character. The agent reads the value as redacted. |
| `autoComplete` **agent** | `string` | `"one-time-code"` | Set on the first slot. While `one-time-code`, the agent reads the value as redacted. |
| `autoSubmit` | `boolean` | `false` | Submits the owning form once the code is complete. |
| `inputMode` | `string` | - | On-screen keyboard. Defaults per `validationType`. |
| `disabled` **agent** | `boolean` | `false` | Blocks people and agents. |
| `readOnly` **agent** | `boolean` | `false` | Shows the code, refuses any change. |
| `name` | `string` | - | Submits the code with a form. |
| `required` | `boolean` | `false` | Must be filled before the form submits. |

### OTPFieldGroup
A row of joined slots.

Takes the props of the element it renders.

### OTPFieldInput
One slot. Render one per character.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `type` | `string` | - | Overrides the input type for this slot. |

### OTPFieldSeparator
A mark between groups.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode` | - | What to show, such as a dash. |

## Agent
Inside an `AgentProvider`, OTP Field appears in `agent.snapshot()` as `input`.
Reads:
- `label`: The root's aria-label or aria-labelledby.
- `value`: The code, or [redacted] for a one-time code or a masked field.
- `length`: How many characters the code takes.
- `disabled`: True when the field is blocked.
Actions:
- `setValue("4321")`: Fills the code. Spaces are dropped; too long or invalid characters fails.
- `clear()`: Empties every slot.
Listed once, not per slot. An agent's change runs through `onValueChange`; `isAgentChange(details)` is true for it, and `details.cancel()` refuses it. The agent is told the app refused. Disabled or `readOnly` fields refuse on their own.
```ts
await agent.act({
  steps: [{ ref: "input", action: "setValue", args: ["482913"] }],
})
```

## Accessibility
- The root is a group. Name it with aria-label or aria-labelledby; the agent reads it.
- One slot is in the tab order; arrows move between slots.
- The first slot has `autocomplete="one-time-code"` so browsers can offer received codes.
- Disabled fields show their value but take no input.
### Keyboard
| Keys | Does |
| --- | --- |
| `←` / `→` | Moves to the previous or next slot |
| `Home` / `End` | Moves to the first slot, or the first empty one |
| `Backspace` | Deletes the character and moves back |
| `Delete` | Deletes the character in this slot |
| `Ctrl` / `Backspace` | Clears the whole code. Cmd on macOS |

## Source
`components/ui/otp-field/otp-field.tsx`
```tsx
"use client"

import * as React from "react"
import { OTPField as OTPFieldPrimitive } from "@base-ui/react/otp-field"
import { cn } from "@/lib/utils"
import { changeAsAgent, useAgentControl, useAgentState, useHasAgent, useMergedRef } from "@/components/ui/agent"

const CODE_PATTERNS: Record<string, RegExp> = {
  numeric: /^\d*$/,
  alpha: /^[a-z]*$/i,
  alphanumeric: /^[a-z\d]*$/i,
}

function checkCode(code: string, length: number, validationType = "numeric") {
  if (code.length > length) return `The code is ${length} characters.`
  if (!(CODE_PATTERNS[validationType]?.test(code) ?? true)) return `The code takes ${validationType} characters only.`
}

/**
 * Base UI's root, holding its own value so an agent can fill the code the way a parent
 * would. `onValueChange` sees the agent's changes first and can cancel them.
 */
const OTPField = React.forwardRef<
  React.ComponentRef<typeof OTPFieldPrimitive.Root>,
  React.ComponentPropsWithoutRef<typeof OTPFieldPrimitive.Root>
>(({ className, value: valueProp, defaultValue = "", onValueChange, ...props }, ref) => {
  type Details = OTPFieldPrimitive.Root.ChangeEventDetails
  const [value, changeValue] = useAgentState<string, Details>(valueProp, defaultValue, onValueChange)
  const element = React.useRef<HTMLDivElement>(null)
  const mergedRef = useMergedRef(ref, element)

  useAgentControl(() => {
    const setValue = (next: unknown) => {
      if (props.readOnly) return "The code is read-only."
      const code = String(next ?? "").replace(/\s+/g, "")
      return checkCode(code, props.length, props.validationType) ?? changeAsAgent(changeValue, code)
    }
    return {
      kind: "input" as const,
      element: element.current,
      value,
      disabled: props.disabled,
      length: props.length,
      // A one-time code is a credential, like the autocomplete token Base UI gives it,
      // and a masked one is hidden from the person too.
      secret: Boolean(props.mask) || (props.autoComplete ?? "one-time-code") === "one-time-code",
      actions: { setValue, clear: () => setValue("") },
    }
  })

  return (
    <OTPFieldPrimitive.Root
      ref={mergedRef}
      data-slot="otp-field"
      className={cn(
        "flex items-center gap-2",
        "data-[disabled]:opacity-50",
        className
      )}
      {...props}
      value={value}
      onValueChange={changeValue}
    />
  )
})
OTPField.displayName = "OTPField"

const OTPFieldGroup = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
  <div
    ref={ref}
    data-slot="otp-field-group"
    className={cn("flex items-center", className)}
    {...props}
  />
))
OTPFieldGroup.displayName = "OTPFieldGroup"

const OTPFieldInput = React.forwardRef<
  React.ComponentRef<typeof OTPFieldPrimitive.Input>,
  React.ComponentPropsWithoutRef<typeof OTPFieldPrimitive.Input>
>(({ className, ...props }, ref) => (
  <OTPFieldPrimitive.Input
    ref={ref}
    data-slot="otp-field-input"
    // The root reports the whole code, so a slot is part of it rather than a control.
    data-agent-part={useHasAgent() ? "" : undefined}
    className={cn(
      "relative h-10 w-10 border-y border-r border-input bg-background text-center text-sm shadow-sm outline-none",
      "transition-[color,background-color,border-color,box-shadow] duration-[var(--motion-duration-fast,150ms)]",
      "first:rounded-l-md first:border-l last:rounded-r-md",
      "focus-visible:z-10 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50",
      "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",
      "aria-invalid:border-destructive aria-invalid:ring-destructive/20",
      className
    )}
    {...props}
  />
))
OTPFieldInput.displayName = "OTPFieldInput"

const OTPFieldSeparator = React.forwardRef<
  React.ComponentRef<typeof OTPFieldPrimitive.Separator>,
  React.ComponentPropsWithoutRef<typeof OTPFieldPrimitive.Separator>
>(({ className, ...props }, ref) => (
  <OTPFieldPrimitive.Separator
    ref={ref}
    data-slot="otp-field-separator"
    role="separator"
    className={cn("text-muted-foreground", className)}
    {...props}
  />
))
OTPFieldSeparator.displayName = "OTPFieldSeparator"

export type OTPFieldProps = React.ComponentPropsWithoutRef<typeof OTPFieldPrimitive.Root>
export type OTPFieldGroupProps = React.HTMLAttributes<HTMLDivElement>
export type OTPFieldInputProps = React.ComponentPropsWithoutRef<typeof OTPFieldPrimitive.Input>
export type OTPFieldSeparatorProps = React.ComponentPropsWithoutRef<typeof OTPFieldPrimitive.Separator>

export { OTPField, OTPFieldGroup, OTPFieldInput, OTPFieldSeparator }
```
