import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { cx } from '../internal/cx.js' import { Spinner } from './Spinner.jsx' import { canSubmit, nextPin, pinAction } from './pin.js' import { useLabels } from './labels.js' const KEYS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', null, '0', 'Backspace'] const KEYS_VARIABLE = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'Enter', '0', 'Backspace'] /** * Numeric PIN entry: dots + a 3×4 keypad, also driven by the physical keyboard. * * { await unlock(pin) }} /> * * Fixed length (`length`, default 4): onComplete(pin) runs as soon as `length` digits are in. * Variable length (`minLength` + `maxLength`, e.g. PINs of 4–8 digits): an OK key (and the * Enter key) submits once at least `minLength` digits are in. * * If onComplete returns a promise the pad * shows a spinner until it settles. If it throws / rejects (or returns false), the pad * shakes, shows `error` text if given, and clears for another try. On success it clears too. * * error: text under the dots (e.g. "Wrong PIN"); a change of it also shakes the pad. * captureKeyboard (default true): digits/Backspace typed anywhere go to the pad, * except while the user is typing in a field. * backspaceLabel / submitLabel / progressLabel(n, length) override the UiLabelsProvider texts. */ export function PinPad({ length = 4, minLength, maxLength, onComplete, onChange, disabled = false, error, title, captureKeyboard = true, backspaceLabel, submitLabel, progressLabel, className, }) { const labels = useLabels() const backspaceText = backspaceLabel ?? labels.backspace const submitText = submitLabel ?? labels.submit const progress = progressLabel ?? labels.pinProgress const variable = minLength != null && maxLength != null const max = variable ? maxLength : length const [value, setValue] = useState('') const [busy, setBusy] = useState(false) const [shake, setShake] = useState(0) const latest = useRef({ value, busy, disabled }) useLayoutEffect(() => { latest.current = { value, busy, disabled } }) const fail = useCallback(() => { setShake(n => n + 1) setValue('') onChange?.('') }, [onChange]) const submit = useCallback(async pin => { let ok = true try { const result = onComplete?.(pin) if (result && typeof result.then === 'function') { setBusy(true) ok = (await result) !== false } else { ok = result !== false } } catch { ok = false } finally { setBusy(false) } if (ok) { setValue(''); onChange?.('') } else fail() }, [onComplete, onChange, fail]) const press = useCallback(key => { const { value: current, busy: isBusy, disabled: isDisabled } = latest.current const action = pinAction(key) if (!action || isBusy || isDisabled) return if (action.type === 'submit') { if (variable && canSubmit(current, minLength)) submit(current) return } const next = nextPin(current, action, max) if (next === current) return setValue(next) onChange?.(next) if (!variable && next.length === max) submit(next) }, [variable, minLength, max, onChange, submit]) useEffect(() => { if (!captureKeyboard) return const onKey = e => { if (e.ctrlKey || e.metaKey || e.altKey) return const t = e.target if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return const action = pinAction(e.key) if (!action || (action.type === 'submit' && !variable)) return // Enter only means "OK" in variable mode e.preventDefault() press(e.key) } document.addEventListener('keydown', onKey) return () => document.removeEventListener('keydown', onKey) }, [captureKeyboard, press, variable]) return (
{title &&
{title}
} {/* Re-keyed on every failed attempt and on every new error text, which replays the shake */}
0 || error) && 'x-pinpad__dots--shake')} aria-hidden="true"> {Array.from({ length: variable ? Math.max(minLength, value.length) : max }, (_, i) => ( ))}
{progress(value.length, variable ? minLength : max)}
{busy ? : error ? {error} : null}
{(variable ? KEYS_VARIABLE : KEYS).map(k => k === null ?
) }