0 of 6 digits. Try pasting 123456.

Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/otp-field.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")
    
  3. Import it

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

Usage

Six digits.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.

Masked PIN

Four larger slots drawn as password inputs.

Letters and digits

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

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.

Enter the code we sent to ada@example.com

The code in this demo is 123456.

Disabled and read-only

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

Disabled
Read-only

Anatomy

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

PartDescription
rootAny element, role="group". Adds the hidden input that submits the whole code.
inputinput({ element, index }): the <input> of one slot, by its place in the code from 0.
lengthThe number of slots, to draw them from.

API reference

Props

PropTypeDescription
valueRedacted<string>The code. Redacted, so it stays out of message logs and history.
lengthnumberThe number of slots.
validationType"numeric" | "alpha" | "alphanumeric" | "none"Which characters are accepted. "numeric" by default.
maskbooleanDraws each slot as a password input.
autoSubmitbooleanSubmits the form the field belongs to once the stored code is complete.
idstringThe first slot's id, so a <label for> focuses it and names the group.
disabled / readOnly / requiredbooleanThe state of the field.
namestringThe name the form submits the code under.

Events

EventDescription
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

AttributeDescription
data-filledOn the root, the code isn't empty. On a slot, the slot has a character.
data-completeEvery slot has a character.
data-focusedA slot has focus.
data-disabled / data-readonly / data-requiredFrom the props, on the root and every slot.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.
  • Field: Groups a control with its label, description and error, and reports whether it is invalid, touched or focused on each of them.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.