Components
Input OTP
A one-time code, one cell per character, each cell drawn as the input. It is one real field, so paste and the phone's code suggestion work.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add input-otp<script type="module" src="/spyglass-ds/elements/input-otp.js"></script>Code from your email
We sent it to you@acme.com.
That code has expired. Send a new one.
Usage
Sign-in and verification codes sent by email or text. Say under it where the code went.
Never
- Passwords or keys
- Cells that move focus on their own: it is one field
- A colored or glowing cell for the one being typed: its hairline turns White
Props
The web component takes the same as attributes or properties (<spyglass-input-otp>); title is heading there.
<InputOtp>
| Prop | Type | Default |
|---|---|---|
length | number How many cells (6). | 6 |
split | number A gap after this many cells (3 for two threes). | |
label | string The name for assistive tech. | |
numeric | boolean Digits only (false takes letters too). | true |
invalid | boolean A red hairline on every cell. | |
disabled | boolean | |
name | string | |
value | string | |
defaultValue | string | '' |
onValueChange | (code: string) => void | |
onComplete | (code: string) => void Every cell is filled. | |
className | string |
Examples
The same example in React and as web components; both render identically.
'use client'
import { useState } from 'react'
import { InputOtp } from '@/react/components/ui/InputOtp'
// Signing in with a code from email: six digits in two threes, and a line that says when it is checked.
export default function Verify() {
const [done, setDone] = useState(false)
return (
<div className="flex flex-col items-start gap-3">
<p className="type-label text-fg-soft">Code from your email</p>
<InputOtp label="Code from your email" split={3} onValueChange={() => setDone(false)} onComplete={() => setDone(true)} />
<p className="type-caption text-fg-muted" role="status">{done ? 'Checking your code.' : 'We sent it to you@acme.com.'}</p>
</div>
)
}<!-- Signing in with a code from email: six digits in two threes, and a line that says when it is checked. -->
<div class="flex flex-col items-start gap-3">
<p class="type-label text-fg-soft">Code from your email</p>
<spyglass-input-otp id="otp-verify" label="Code from your email" split="3"></spyglass-input-otp>
<p id="otp-status" class="type-caption text-fg-muted" role="status">We sent it to you@acme.com.</p>
</div>
<script type="module">
const otp = document.getElementById('otp-verify')
const status = document.getElementById('otp-status')
// The input event reaches the page after complete: only a code still being typed resets the line.
otp.addEventListener('input', () => { if (otp.value.length < otp.length) status.textContent = 'We sent it to you@acme.com.' })
otp.addEventListener('complete', () => { status.textContent = 'Checking your code.' })
</script>import { InputOtp } from '@/react/components/ui/InputOtp'
// A code that was wrong, and one that can't be changed while it is checked.
export default function States() {
return (
<div className="flex flex-col items-start gap-6">
<div className="flex flex-col items-start gap-3">
<InputOtp label="Wrong code" defaultValue="481920" invalid />
<p className="type-caption text-fg-danger">That code has expired. Send a new one.</p>
</div>
<InputOtp label="Code being checked" defaultValue="2741" length={4} disabled />
</div>
)
}<!-- A code that was wrong, and one that can't be changed while it is checked. -->
<div class="flex flex-col items-start gap-6">
<div class="flex flex-col items-start gap-3">
<spyglass-input-otp label="Wrong code" value="481920" invalid></spyglass-input-otp>
<p class="type-caption text-fg-danger">That code has expired. Send a new one.</p>
</div>
<spyglass-input-otp label="Code being checked" value="2741" length="4" disabled></spyglass-input-otp>
</div>Source
'use client'
import { useRef, useState, type FormEvent } from 'react'
import { useControllable } from '@/react/hooks/useControllable'
// A one-time code: square cells drawn as the Input is (a #666666 hairline on Black, the brand corner, 48px; 40px on
// phones), DM Sans digits at 18px in tabular figures, the cell being typed into edged in White with a caret, and an
// optional gap after `split` cells. It is one real input laid over the cells, so paste, the phone's code suggestion
// (autocomplete="one-time-code"), arrows and delete all work as in any field. Calls `onComplete` when every cell is
// filled. A red hairline on every cell when invalid. The caret blinks in steps (no fade); reduced motion holds it still.
// `value` with `onValueChange` controls it (or `defaultValue` alone).
export interface InputOtpProps {
/** How many cells (6). */
length?: number
/** A gap after this many cells (3 for two threes). */
split?: number
/** The name for assistive tech. */
label: string
/** Digits only (false takes letters too). */
numeric?: boolean
/** A red hairline on every cell. */
invalid?: boolean
disabled?: boolean
name?: string
value?: string
defaultValue?: string
onValueChange?: (code: string) => void
/** Every cell is filled. */
onComplete?: (code: string) => void
className?: string
}
export function InputOtp({ length = 6, split, label, numeric = true, invalid, disabled, name, value, defaultValue = '', onValueChange, onComplete, className }: InputOtpProps) {
const [code, setCode] = useControllable(value, defaultValue, onValueChange)
const input = useRef<HTMLInputElement | null>(null)
const [focused, setFocused] = useState(false)
const [caret, setCaret] = useState(0)
const cells = Array.from({ length }, (_, i) => code[i] ?? '')
const active = focused ? Math.min(caret, length - 1) : -1
function sync() {
const el = input.current
if (!el) return
setCaret(el.selectionStart ?? el.value.length)
}
// A click lands on the next empty cell, as typing would.
function toEnd() {
const el = input.current
if (!el) return
const end = el.value.length
el.setSelectionRange(end, end)
sync()
}
function onInput(event: FormEvent<HTMLInputElement>) {
const el = event.currentTarget
const clean = (numeric ? el.value.replace(/\D/g, '') : el.value.replace(/\s/g, '')).slice(0, length)
if (clean !== el.value) el.value = clean
setCode(clean)
sync()
if (clean.length === length) onComplete?.(clean)
}
return (
<>
<style href="ds-input-otp" precedence="ds">{css}</style>
<div data-ds="input-otp" className={className ? `ds-otp ${className}` : 'ds-otp'} data-invalid={invalid || undefined} data-disabled={disabled || undefined}>
<input
ref={input}
value={code}
name={name}
maxLength={length}
inputMode={numeric ? 'numeric' : 'text'}
pattern={numeric ? '[0-9]*' : undefined}
autoComplete="one-time-code"
spellCheck="false"
aria-label={label}
aria-invalid={invalid || undefined}
disabled={disabled}
onChange={onInput}
onFocus={() => { setFocused(true); toEnd() }}
onBlur={() => setFocused(false)}
onKeyUp={sync}
onClick={toEnd}
/>
{cells.map((c, i) => (
<span key={i} className="ds-otp-cell" data-active={i === active || undefined} data-gap={split && i === split - 1 && i < length - 1 ? true : undefined} aria-hidden="true">{c}{i === active && !c && <i />}</span>
))}
</div>
</>
)
}
export default InputOtp
const css = `
.ds-otp { position: relative; display: inline-flex; gap: var(--ds-space-sm); }
.ds-otp > input { position: absolute; inset: 0; z-index: 1; width: 100%; height: 100%; border: 0; background: transparent; color: transparent; caret-color: transparent; font-size: var(--ds-text-input); letter-spacing: 1em; outline: none; cursor: text; }
.ds-otp > input::selection { background: transparent; }
.ds-otp > input:disabled { cursor: not-allowed; }
.ds-otp-cell { position: relative; display: inline-flex; width: var(--ds-size-control-lg); height: var(--ds-size-control-lg); align-items: center; justify-content: center; border: var(--ds-border-hairline) solid var(--ds-color-edge-strong); border-radius: var(--ds-radius-control); background: var(--ds-color-surface); color: var(--ds-color-fg); font-family: var(--ds-font-text); font-size: var(--ds-text-body-lg); line-height: var(--ds-text-body-lg-leading); font-variant-numeric: tabular-nums; transition: border-color var(--ds-duration-micro) var(--ds-easing-standard); }
.ds-otp-cell[data-gap] { margin-right: var(--ds-space-md); }
.ds-otp-cell[data-active] { border-color: var(--ds-color-edge-focus); }
.ds-otp-cell > i { width: 1px; height: 20px; background: var(--ds-color-fg); animation: ds-otp-caret 1000ms steps(1, end) infinite; }
@keyframes ds-otp-caret { 50% { opacity: 0; } }
@media (hover: hover) and (pointer: fine) { .ds-otp:not([data-disabled], [data-invalid]):hover .ds-otp-cell:not([data-active]) { border-color: var(--ds-color-action-secondary-edge-hover); } }
.ds-otp[data-invalid] .ds-otp-cell { border-color: var(--ds-color-action-danger); }
.ds-otp[data-disabled] .ds-otp-cell { border-color: var(--ds-color-edge); background: var(--ds-color-surface-sunken); color: var(--ds-color-fg-faint); }
@media (max-width: 767px) { .ds-otp-cell { width: var(--ds-size-control-md); height: var(--ds-size-control-md); } }
@media (prefers-reduced-motion: reduce) { .ds-otp-cell > i { animation: none; } }
`'use client'
import { useCallback, useRef, useState } from 'react'
// Vue's defineModel in React: a value that is controlled when the caller passes it (value + onValueChange, as Radix
// does) and kept inside otherwise (defaultValue). setValue calls onChange either way.
export function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void) {
const [inner, setInner] = useState<T>(defaultValue)
const controlled = value !== undefined
const current = controlled ? value : inner
const ref = useRef(onChange)
ref.current = onChange
const set = useCallback((next: T) => {
if (!controlled) setInner(next)
ref.current?.(next)
}, [controlled])
return [current, set] as const
}import { html, LitElement, nothing, type PropertyValues } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { live } from 'lit/directives/live.js'
import { DsFormElement, define } from '@/elements/lib/element'
import styles from 'virtual:tw'
// InputOtp.tsx as <spyglass-input-otp>: a one-time code: square cells drawn as the input is (a #666666 hairline on
// Black, the brand corner, 48px; 40px on phones), DM Sans digits at 18px, the cell being typed into edged in White with
// a caret, and an optional gap after `split` cells. It is one real input laid over the cells, so paste, the phone's code
// suggestion, arrows and delete all work as in any field. Fires `complete` when every cell is filled. A red hairline on
// every cell when invalid. Form-associated (its `name` and `value` go with its form); the value is `value` with the
// native `input` and `change` events.
/**
* @summary A one-time code, one cell per character.
* @fires input - On every keystroke (read `value`).
* @fires change - When the value is committed.
* @fires complete - Every cell is filled; detail.value is the code.
*/
export class InputOtp extends DsFormElement {
static styles = [DsFormElement.styles, styles]
static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true }
static dsField = true
static properties = {
value: {},
length: { type: Number },
split: { type: Number },
label: {},
numeric: { converter: { fromAttribute: (v: string | null) => v !== 'false' } },
invalid: { type: Boolean, reflect: true },
disabled: { type: Boolean, reflect: true },
name: {},
required: { type: Boolean },
focused: { state: true },
caret: { state: true },
}
value = ''
length = 6
/** A gap after this many cells (3 for two threes). */
split?: number
/** The name for assistive tech. */
label = ''
/** Digits only (numeric="false" takes letters too). */
numeric = true
invalid = false
disabled = false
name?: string
/** A code must be typed for its form to send. */
required = false
private focused = false
private caret = 0
protected updated(changed: PropertyValues) {
super.updated(changed)
if (changed.has('value')) this.internals.setFormValue(this.value)
}
protected validityControl() {
return this.renderRoot.querySelector<HTMLInputElement>('input')
}
formResetCallback() {
this.value = this.getAttribute('value') ?? ''
}
private get input() {
return this.renderRoot.querySelector('input')
}
private sync() {
const el = this.input
if (!el) return
this.caret = el.selectionStart ?? el.value.length
}
// A click lands on the next empty cell, as typing would.
private toEnd() {
const el = this.input
if (!el) return
const end = el.value.length
el.setSelectionRange(end, end)
this.sync()
}
private onInput(event: Event) {
const el = event.target as HTMLInputElement
const clean = (this.numeric ? el.value.replace(/\D/g, '') : el.value.replace(/\s/g, '')).slice(0, this.length)
if (clean !== el.value) el.value = clean
this.value = clean
this.sync()
if (clean.length === this.length) this.emit('complete', { value: clean })
}
// The inner change does not leave the shadow root: the element sends its own.
private onChange() {
this.dispatchEvent(new Event('change', { bubbles: true, composed: true }))
}
render() {
const active = this.focused ? Math.min(this.caret, this.length - 1) : -1
const cells = Array.from({ length: this.length }, (_, i) => this.value[i] ?? '')
return html`<div data-ds="input-otp" class="ds-otp" data-invalid=${ifDefined(this.invalid ? 'true' : undefined)} data-disabled=${ifDefined(this.inactive ? 'true' : undefined)}>
<input
.value=${live(this.value)}
maxlength=${this.length}
inputmode=${this.numeric ? 'numeric' : 'text'}
pattern=${ifDefined(this.numeric ? '[0-9]*' : undefined)}
autocomplete="one-time-code"
spellcheck="false"
aria-label=${this.label}
aria-invalid=${ifDefined(this.invalid ? 'true' : undefined)}
?disabled=${this.inactive}
?required=${this.required}
@input=${this.onInput}
@change=${this.onChange}
@focus=${() => { this.focused = true; this.toEnd() }}
@blur=${() => { this.focused = false }}
@keyup=${this.sync}
@click=${this.toEnd}
>
${cells.map((c, i) => html`<span class="ds-otp-cell" data-active=${ifDefined(i === active ? 'true' : undefined)} data-gap=${ifDefined(this.split && i === this.split - 1 && i < this.length - 1 ? 'true' : undefined)} aria-hidden="true">${c}${i === active && !c ? html`<i></i>` : nothing}</span>`)}
</div>`
}
}
define('input-otp', InputOtp)/* InputOtp.tsx's styles, as they are. */
.ds-otp { position: relative; display: inline-flex; gap: var(--ds-space-sm); }
.ds-otp > input { position: absolute; inset: 0; z-index: 1; width: 100%; height: 100%; border: 0; background: transparent; color: transparent; caret-color: transparent; font-size: var(--ds-text-input); letter-spacing: 1em; outline: none; cursor: text; }
.ds-otp > input::selection { background: transparent; }
.ds-otp > input:disabled { cursor: not-allowed; }
.ds-otp-cell { position: relative; display: inline-flex; width: var(--ds-size-control-lg); height: var(--ds-size-control-lg); align-items: center; justify-content: center; border: var(--ds-border-hairline) solid var(--ds-color-edge-strong); border-radius: var(--ds-radius-control); background: var(--ds-color-surface); color: var(--ds-color-fg); font-family: var(--ds-font-text); font-size: var(--ds-text-body-lg); line-height: var(--ds-text-body-lg-leading); font-variant-numeric: tabular-nums; transition: border-color var(--ds-duration-micro) var(--ds-easing-standard); }
.ds-otp-cell[data-gap] { margin-right: var(--ds-space-md); }
.ds-otp-cell[data-active] { border-color: var(--ds-color-edge-focus); }
.ds-otp-cell > i { width: 1px; height: 20px; background: var(--ds-color-fg); animation: ds-otp-caret 1000ms steps(1, end) infinite; }
@keyframes ds-otp-caret { 50% { opacity: 0; } }
@media (hover: hover) and (pointer: fine) { .ds-otp:not([data-disabled], [data-invalid]):hover .ds-otp-cell:not([data-active]) { border-color: var(--ds-color-action-secondary-edge-hover); } }
.ds-otp[data-invalid] .ds-otp-cell { border-color: var(--ds-color-action-danger); }
.ds-otp[data-disabled] .ds-otp-cell { border-color: var(--ds-color-edge); background: var(--ds-color-surface-sunken); color: var(--ds-color-fg-faint); }
@media (max-width: 767px) { .ds-otp-cell { width: var(--ds-size-control-md); height: var(--ds-size-control-md); } }
@media (prefers-reduced-motion: reduce) { .ds-otp-cell > i { animation: none; } }Reference: Derived from the brand guidelines (no code field in the brand assets): the input's hairline, fill and corner, DM Sans for the digits.