"use client"; import * as React from "react"; import { useEffect, useId, useRef, useState } from "react"; import { FieldError } from "./text-field"; import { cn } from "../lib/cn"; export type OtpInputProps = { label: string; /** The digits typed so far. */ value: string; onChange: (value: string) => void; /** How many digits: 6 by default. */ length?: number; error?: string; hint?: string; /** The name of box `n` of `total`; "Cifra 2 di 6" by default. */ digitLabel?: (n: number, total: number) => string; disabled?: boolean; /** The focus on the first box when the page opens. */ autoFocus?: boolean; className?: string; }; const italianDigitLabel = (n: number, total: number) => `Cifra ${n} di ${total}`; function toDigits(value: string, length: number): string[] { return Array.from({ length }, (_, i) => value[i]?.replace(/\D/, "") ?? ""); } /** * The design system's OtpInput (ACC-536): the digits of a sign-in code, one * box each. A digit moves the focus to the next box, Backspace on an empty * box goes back one, the arrows move between them, and a pasted code fills * every box from the first. The first box asks for the one-time code * (`autocomplete="one-time-code"`), so a phone offers the one from the email; * the whole code then lands in that box, and is spread over the others. * * Each box has its own name ("Cifra 2 di 6") and the group is named by the * label; the hint and the error describe the group. An error marks every box. * * `onChange` receives the digits in their boxes, joined: the page sends it * when it is `length` long. A value set from outside (an empty one after a * new code is sent) replaces what the boxes hold. */ export function OtpInput({ label, value, onChange, length = 6, error, hint, digitLabel = italianDigitLabel, disabled, autoFocus, className, }: OtpInputProps) { const id = useId(); const refs = useRef<(HTMLInputElement | null)[]>([]); const [digits, setDigits] = useState(() => toDigits(value, length)); // A gap between two digits (one typed into box 3 with box 2 empty) has no // place in the joined value: the boxes keep their own state and only follow // a value that differs from what they say. useEffect(() => { setDigits((current) => current.join("") === value ? current : toDigits(value, length), ); }, [value, length]); const focusBox = (i: number) => refs.current[i]?.focus(); const commit = (next: string[], focusAt?: number) => { setDigits(next); onChange(next.join("")); if (focusAt !== undefined) focusBox(focusAt); }; /** Fill the boxes from `text`, from the first, and focus the one after. */ const fillFrom = (text: string) => { const code = text.replace(/\D/g, "").slice(0, length); if (!code) return false; commit( Array.from({ length }, (_, i) => code[i] ?? ""), Math.min(code.length, length - 1), ); return true; }; const onBoxChange = (i: number, raw: string) => { const typed = raw.replace(/\D/g, ""); // More than a digit and the one the box had: a code filled in by the // phone, or by a keyboard that inserts it whole. if (typed.length > 2) { fillFrom(typed); return; } const next = digits.slice(); // Two digits: the box's own and the one typed, before or after it. // Keep the new one, wherever the caret was. next[i] = typed.length === 2 && typed[1] === digits[i] ? typed[0] : typed.slice(-1); commit(next, next[i] && i < length - 1 ? i + 1 : undefined); }; const onKeyDown = ( i: number, event: React.KeyboardEvent, ) => { if (event.key === "Backspace" && !digits[i] && i > 0) { event.preventDefault(); focusBox(i - 1); } else if (event.key === "ArrowLeft" && i > 0) { event.preventDefault(); focusBox(i - 1); } else if (event.key === "ArrowRight" && i < length - 1) { event.preventDefault(); focusBox(i + 1); } }; const labelId = `${id}-label`; const messageId = error ? `${id}-error` : hint ? `${id}-hint` : undefined; return (
{label}
{digits.map((digit, i) => ( { refs.current[i] = el; }} type="text" inputMode="numeric" pattern="[0-9]*" autoComplete={i === 0 ? "one-time-code" : "off"} // eslint-disable-next-line jsx-a11y/no-autofocus -- the code is the only thing to do on the page it opens on autoFocus={autoFocus && i === 0} aria-label={digitLabel(i + 1, length)} aria-invalid={error ? true : undefined} // On each box too: a screen reader on a box reads the error. aria-describedby={messageId} disabled={disabled} value={digit} onChange={(event) => onBoxChange(i, event.target.value)} onKeyDown={(event) => onKeyDown(i, event)} onPaste={(event) => { if (fillFrom(event.clipboardData.getData("text") ?? "")) { event.preventDefault(); } }} onFocus={(event) => event.target.select()} className={cn( "border-primary-black-60 bg-card text-primary-blue-100 font-heading h-15 w-13 max-w-14 min-w-0 flex-1 rounded-lg border-[1.2px] text-center text-xl font-bold transition-colors outline-none", "focus-visible:border-primary focus-visible:outline-ring focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid", "aria-invalid:border-semantic-error-100", "disabled:border-primary-black-20 disabled:bg-primary-black-5 disabled:text-primary-black-40 disabled:cursor-not-allowed", )} /> ))}
{hint && !error && (

{hint}

)} {error && {error}}
); }