# OTPField

A row of one-character inputs for a verification code, which move focus as you type and take a pasted code whole.

- Page: https://www.effectcn.com/components/otp-field
- Kind: Headless component with parts
- File: `src/ui/otp-field.ts`
- Built on: `OTPField` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/otp-field.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/otp-field.ts`

```ts
import type { Component } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import type { InputElement, OTPField } from "@effect/ui-kit"
import { cn } from "#lib/cn"

/** What the kit's `OTPField` hands its `view` closure. */
export type OTPFieldParts = Component.Headless.Parts<typeof OTPField>

interface ClassOption {
  readonly class?: string | undefined
}

const sizes = {
  default: "h-10 w-9 text-base",
  lg: "h-12 w-11 text-lg"
} as const

export type OTPFieldSize = keyof typeof sizes

/**
 * The row of slots. Name it with `aria-label`, or with a `<label for>` that
 * points at the kit's `id` prop. In a `Field`, pass `element: field.group(h.div)`.
 */
export const OTPFieldRoot = <Msg>(
  h: Html.H<Msg>,
  otpField: OTPFieldParts,
  options: ClassOption & { readonly element?: ReturnType<Html.H<Msg>["div"]["attr"]> | undefined } = {}
) => otpField.root((options.element ?? h.div).class(cn("flex items-center gap-2", options.class)))

/** A few slots that belong together, with an `OTPFieldSeparator` between two groups. */
export const OTPFieldGroup = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.div.class(cn("flex items-center gap-2", options.class))

/** One slot. `index` is its place in the code, from 0. In a `Field`, pass `element: field.member(h.input)`. */
export const OTPFieldInput = <Msg>(
  h: Html.H<Msg>,
  otpField: OTPFieldParts,
  options: ClassOption & {
    readonly index: number
    readonly size?: OTPFieldSize | undefined
    readonly element?: InputElement<Msg> | undefined
  }
) =>
  otpField.input({
    element: (options.element ?? h.input).class(cn(
      "rounded-md border border-input bg-background p-0 text-center font-medium text-foreground caret-brand tabular-nums shadow-sm outline-none",
      "transition-[border-color,box-shadow] duration-150 focus:border-ring focus:ring-3 focus:ring-ring/20",
      "aria-invalid:border-destructive aria-invalid:focus:ring-destructive/20",
      "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[readonly]:bg-muted",
      sizes[options.size ?? "default"],
      options.class
    )),
    index: options.index
  })

/** A dash between two groups of slots. */
export const OTPFieldSeparator = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.span.class(cn("h-0.5 w-3 rounded-full bg-input", options.class)).attr("aria-hidden", "true")
```

```ts
import { OTPFieldRoot, OTPFieldGroup, OTPFieldInput, OTPFieldSeparator } from "#ui/otp-field"
```

## Usage

Type, paste, or use the arrow keys and Backspace. Completed fires once every slot is filled.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { OTPField } from "@effect/ui-kit"
import { Redacted, Schema } from "effect"
import { OTPFieldInput, OTPFieldRoot } from "#ui/otp-field"

const OTPFieldBasicMessage = UiSchema.TaggedEnum({
  UpdatedOTPField: { value: Schema.Redacted(Schema.String) },
  CompletedOTPField: {}
})

export const OTPFieldBasic = Html.component({
  name: "OTPFieldBasic",
  model: Schema.Struct({ code: Schema.Redacted(Schema.String), completed: Schema.Boolean }),
  message: OTPFieldBasicMessage
}).make({
  init: () => ({ code: Redacted.make(""), completed: false }),
  update: {
    UpdatedOTPField: (_, { value }) => ({ code: value, completed: false }),
    CompletedOTPField: ($) => $.evolve({ completed: true })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      // The code is a Redacted<string>, so it stays out of the message log.
      OTPField(h, {
        props: { value: model.code, length: 6, name: "code" },
        onEmit: {
          Updated: ({ value }) => OTPFieldBasicMessage.UpdatedOTPField({ value }),
          Completed: () => OTPFieldBasicMessage.CompletedOTPField(),
          Rejected: () => undefined
        },
        view: (otpField) =>
          OTPFieldRoot(h, otpField).attr("aria-label", "Verification code").children(
            Array.from({ length: otpField.length }, (_, index) =>
              OTPFieldInput(h, otpField, { index }))
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(
        model.completed
          ? "Completed: every slot has a digit"
          : `${Redacted.value(model.code).length} of 6 digits. Try pasting 123456.`
      )
    )
})
```

## Examples

### With a separator

Two groups of three, named by a label that focuses the first slot.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { OTPField } from "@effect/ui-kit"
import { Redacted, Schema } from "effect"
import { OTPFieldGroup, OTPFieldInput, OTPFieldRoot, OTPFieldSeparator } from "#ui/otp-field"

const OTPFieldWithSeparatorMessage = UiSchema.TaggedEnum({
  UpdatedOTPField: { value: Schema.Redacted(Schema.String) }
})

export const OTPFieldWithSeparator = Html.component({
  name: "OTPFieldWithSeparator",
  model: Schema.Struct({ code: Schema.Redacted(Schema.String) }),
  message: OTPFieldWithSeparatorMessage
}).make({
  init: () => ({ code: Redacted.make("123") }),
  update: {
    UpdatedOTPField: (_, { value }) => ({ code: value })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      h.label.class("text-[13px] font-medium").attr("for", "otp-separator").children("Verification code"),
      // A <label for> pointing at the id prop focuses the first slot and names the group.
      OTPField(h, {
        props: { value: model.code, length: 6, id: "otp-separator", name: "code" },
        onEmit: {
          Updated: ({ value }) => OTPFieldWithSeparatorMessage.UpdatedOTPField({ value }),
          Completed: () => undefined,
          Rejected: () => undefined
        },
        view: (otpField) => {
          const slots = (indexes: ReadonlyArray<number>) =>
            OTPFieldGroup(h).children(
              indexes.map((index) => OTPFieldInput(h, otpField, { index }))
            )
          return OTPFieldRoot(h, otpField).children(
            slots([0, 1, 2]),
            OTPFieldSeparator(h),
            slots([3, 4, 5])
          )
        }
      })
    )
})
```

### Masked PIN

Four larger slots drawn as password inputs.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { OTPField } from "@effect/ui-kit"
import { Redacted, Schema } from "effect"
import { Button } from "#ui/button"
import { OTPFieldInput, OTPFieldRoot } from "#ui/otp-field"

const OTPFieldPinMessage = UiSchema.TaggedEnum({
  UpdatedOTPField: { value: Schema.Redacted(Schema.String) },
  PressedReveal: {}
})

export const OTPFieldPin = Html.component({
  name: "OTPFieldPin",
  model: Schema.Struct({ pin: Schema.Redacted(Schema.String), masked: Schema.Boolean }),
  message: OTPFieldPinMessage
}).make({
  init: () => ({ pin: Redacted.make("48"), masked: true }),
  update: {
    UpdatedOTPField: ($, { value }) => $.evolve({ pin: value }),
    PressedReveal: ($) => $.evolve({ masked: (masked) => !masked })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      OTPField(h, {
        // `mask` draws each slot as a password input.
        props: { value: model.pin, length: 4, mask: model.masked, autoComplete: "off", name: "pin" },
        onEmit: {
          Updated: ({ value }) => OTPFieldPinMessage.UpdatedOTPField({ value }),
          Completed: () => undefined,
          Rejected: () => undefined
        },
        view: (otpField) =>
          OTPFieldRoot(h, otpField).attr("aria-label", "Card PIN").children(
            Array.from({ length: otpField.length }, (_, index) =>
              OTPFieldInput(h, otpField, { index, size: "lg" }))
          )
      }),
      Button(h, { variant: "ghost", size: "sm", onPress: OTPFieldPinMessage.PressedReveal() })
        .children(model.masked ? "Show PIN" : "Hide PIN")
    )
})
```

### Letters and digits

validationType: "alphanumeric", stored in upper case, with Rejected for what doesn't fit.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { OTPField } from "@effect/ui-kit"
import { Redacted, Schema } from "effect"
import { OTPFieldInput, OTPFieldRoot } from "#ui/otp-field"

const OTPFieldAlphanumericMessage = UiSchema.TaggedEnum({
  UpdatedOTPField: { value: Schema.Redacted(Schema.String) },
  RejectedOTPField: {}
})

export const OTPFieldAlphanumeric = Html.component({
  name: "OTPFieldAlphanumeric",
  model: Schema.Struct({ code: Schema.Redacted(Schema.String), rejected: Schema.Boolean }),
  message: OTPFieldAlphanumericMessage
}).make({
  init: () => ({ code: Redacted.make("EF"), rejected: false }),
  update: {
    // What is stored is what the slots show, so this is where the code is changed on the way in.
    UpdatedOTPField: (_, { value }) => ({
      code: Redacted.make(Redacted.value(value).toUpperCase()),
      rejected: false
    }),
    RejectedOTPField: ($) => $.evolve({ rejected: true })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      h.label.class("text-[13px] font-medium").attr("for", "otp-invite").children("Invite code"),
      OTPField(h, {
        props: { value: model.code, length: 5, id: "otp-invite", validationType: "alphanumeric", name: "invite" },
        onEmit: {
          Updated: ({ value }) => OTPFieldAlphanumericMessage.UpdatedOTPField({ value }),
          Completed: () => undefined,
          Rejected: () => OTPFieldAlphanumericMessage.RejectedOTPField()
        },
        view: (otpField) =>
          OTPFieldRoot(h, otpField).children(
            Array.from({ length: otpField.length }, (_, index) =>
              OTPFieldInput(h, otpField, { index }))
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").attr("role", "status").children(
        model.rejected
          ? "Only letters and digits fit here."
          : "Letters are stored in upper case. Try typing a dash."
      )
    )
})
```

### In a form

A Field names the group and shows the error, and autoSubmit submits the form when the code is complete.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Field, Form, OTPField } from "@effect/ui-kit"
import { Redacted, Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { FieldDescription, FieldError, FieldLegend } from "#ui/field"
import { OTPFieldInput, OTPFieldRoot } from "#ui/otp-field"

const OTPFieldFormMessage = UiSchema.TaggedEnum({
  UpdatedOTPField: { value: Schema.Redacted(Schema.String) },
  SubmittedForm: {}
})

const expected = "123456"

export const OTPFieldForm = Html.component({
  name: "OTPFieldForm",
  model: Schema.Struct({
    code: Schema.Redacted(Schema.String),
    status: Schema.Literals(["editing", "wrong", "verified"])
  }),
  message: OTPFieldFormMessage
}).make({
  init: () => ({ code: Redacted.make(""), status: "editing" }),
  update: {
    UpdatedOTPField: (_, { value }) => ({ code: value, status: "editing" }),
    SubmittedForm: ($) =>
      $.evolve({ status: Redacted.value($.model.code) === expected ? "verified" : "wrong" })
  },
  view: (h, model) =>
    Form(h, {
      onEmit: () => OTPFieldFormMessage.SubmittedForm(),
      view: (form) =>
        form.root(h.form.class("flex flex-col items-center gap-3.5")).children(
          Field(h, {
            props: { invalid: model.status === "wrong", described: true },
            view: (field) =>
              field.root(h.div.class("flex flex-col items-center gap-2")).children(
                FieldLegend(h, field).children("Enter the code we sent to ada@example.com"),
                // `autoSubmit` submits the form once the stored code is complete.
                OTPField(h, {
                  props: {
                    value: model.code,
                    length: 6,
                    name: "code",
                    required: true,
                    autoSubmit: true,
                    disabled: field.disabled
                  },
                  onEmit: {
                    Updated: ({ value }) => OTPFieldFormMessage.UpdatedOTPField({ value }),
                    Completed: () => undefined,
                    Rejected: () => undefined
                  },
                  view: (otpField) =>
                    OTPFieldRoot(h, otpField, { element: field.group(h.div) }).children(
                      Array.from({ length: otpField.length }, (_, index) =>
                        OTPFieldInput(h, otpField, { index, element: field.member(h.input) }))
                    )
                }),
                FieldDescription(h, field).children(
                  model.status === "verified" ? "Verified. Welcome back." : "The code in this demo is 123456."
                ),
                FieldError(h, field)?.children(
                  "That code doesn't match. Try again."
                )
              )
          }),
          h.button.class(buttonVariants({ size: "sm" })).attr("type", "submit").children("Verify")
        )
    })
})
```

### Disabled and read-only

A read-only field keeps focus and the arrow keys, and drops every edit.

```ts
import { Html } from "@effect/ui/html"
import { OTPField } from "@effect/ui-kit"
import { Redacted, Schema } from "effect"
import { OTPFieldInput, OTPFieldRoot } from "#ui/otp-field"

const states = [
  { key: "disabled", label: "Disabled", props: { disabled: true } },
  { key: "readonly", label: "Read-only", props: { readOnly: true } }
] as const

export const OTPFieldStates = Html.component({
  name: "OTPFieldStates",
  model: Schema.Struct({ code: Schema.Redacted(Schema.String) }),
  message: Schema.Never
}).make({
  init: () => ({ code: Redacted.make("4821") }),
  update: ($) => $.model,
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      states.map(({ key, label, props }) =>
        h.div.class("flex flex-col items-center gap-1.5").children(
          h.span.class("text-[13px] font-medium").attr("id", `otp-${key}-label`).children(label),
          // A read-only field keeps focus and the arrow keys, and drops every edit.
          OTPField(h, {
            key,
            props: { ...props, value: model.code, length: 4 },
            onEmit: { Updated: () => undefined, Completed: () => undefined, Rejected: () => undefined },
            view: (otpField) =>
              OTPFieldRoot(h, otpField).attr("aria-labelledby", `otp-${key}-label`).children(
                Array.from({ length: otpField.length }, (_, index) =>
                  OTPFieldInput(h, otpField, { index }))
              )
          })
        )
      )
    )
})
```

## Anatomy

The parts the `view` closure receives. Apply each one to an element of your own.

| Part | Description |
| --- | --- |
| `root` | Any element, role="group". Adds the hidden input that submits the whole code. |
| `input` | input({ element, index }): the <input> of one slot, by its place in the code from 0. |
| `length` | The number of slots, to draw them from. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `value` | `Redacted<string>` | The code. Redacted, so it stays out of message logs and history. |
| `length` | `number` | The number of slots. |
| `validationType` | `"numeric" \| "alpha" \| "alphanumeric" \| "none"` | Which characters are accepted. "numeric" by default. |
| `mask` | `boolean` | Draws each slot as a password input. |
| `autoSubmit` | `boolean` | Submits the form the field belongs to once the stored code is complete. |
| `id` | `string` | The first slot's id, so a <label for> focuses it and names the group. |
| `disabled / readOnly / required` | `boolean` | The state of the field. |
| `name` | `string` | The name the form submits the code under. |

### Events

| Event | Description |
| --- | --- |
| `Updated` | { value, reason }: the code the user asked for. Store it and pass it back, changed if need be. |
| `Completed` | { value, reason }: the stored code fills every slot after typing or a paste. |
| `Rejected` | { value, reason }: the text held characters the field dropped, or too many. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-filled` | On the root, the code isn't empty. On a slot, the slot has a character. |
| `data-complete` | Every slot has a character. |
| `data-focused` | A slot has focus. |
| `data-disabled / data-readonly / data-required` | From the props, on the root and every slot. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
- [Field](https://www.effectcn.com/components/field.md): Groups a control with its label, description and error, and reports whether it is invalid, touched or focused on each of them.
