components/linyi/otp-input.tsx
"use client"; import * as React from "react";import { cn } from "@/lib/cn"; export interface OtpInputProps { length?: number; value?: string; defaultValue?: string; onChange?: (value: string) => void; onComplete?: (value: string) => void; disabled?: boolean; invalid?: boolean; compact?: boolean; className?: string;} function normalizeDigits(raw: string, length: number): string[] { const digits = raw.replace(/\D/g, "").slice(0, length).split(""); return Array.from({ length }, (_, idx) => digits[idx] ?? "");} export function OtpInput({ length = 6, value, defaultValue = "", onChange, onComplete, disabled = false, invalid = false, compact = false, className,}: OtpInputProps) { const safeLength = Math.max(1, Math.min(8, length)); const isControlled = value !== undefined; const [internal, setInternal] = React.useState<string>(() => defaultValue.replace(/\D/g, "").slice(0, safeLength) ); const inputRefs = React.useRef<Array<HTMLInputElement | null>>([]); React.useEffect(() => { if (!isControlled) { setInternal((prev) => prev.slice(0, safeLength)); } }, [safeLength, isControlled]); const currentString = isControlled ? value : internal; const slots = React.useMemo( () => normalizeDigits(currentString, safeLength), [currentString, safeLength] ); const focusSlot = (index: number) => { const clamped = Math.max(0, Math.min(safeLength - 1, index)); inputRefs.current[clamped]?.focus(); inputRefs.current[clamped]?.select(); }; const commitSlots = (nextSlots: string[]) => { const joined = nextSlots.join(""); if (!isControlled) { setInternal(joined); } onChange?.(joined); if (nextSlots.every((ch) => ch.length === 1) && joined.length === safeLength) { onComplete?.(joined); } }; const handleChange = (index: number, rawValue: string) => { if (disabled) return; const digits = rawValue.replace(/\D/g, ""); if (!digits) { const next = [...slots]; next[index] = ""; commitSlots(next); return; } const next = [...slots]; let cursor = index; for (const ch of digits) { if (cursor >= safeLength) break; next[cursor] = ch; cursor += 1; } commitSlots(next); if (cursor < safeLength) { focusSlot(cursor); } else { focusSlot(safeLength - 1); } }; const handleKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => { if (disabled) return; if (e.key === "Backspace") { e.preventDefault(); const next = [...slots]; if (next[index]) { next[index] = ""; commitSlots(next); } else if (index > 0) { next[index - 1] = ""; commitSlots(next); focusSlot(index - 1); } return; } if (e.key === "ArrowLeft") { e.preventDefault(); if (index > 0) focusSlot(index - 1); return; } if (e.key === "ArrowRight") { e.preventDefault(); if (index < safeLength - 1) focusSlot(index + 1); return; } if (e.key === "Home") { e.preventDefault(); focusSlot(0); return; } if (e.key === "End") { e.preventDefault(); focusSlot(safeLength - 1); } }; const handlePaste = (index: number, e: React.ClipboardEvent<HTMLInputElement>) => { if (disabled) return; const pasted = e.clipboardData.getData("text").replace(/\D/g, ""); if (!pasted) return; e.preventDefault(); const startIdx = pasted.length >= safeLength ? 0 : index; const next = [...slots]; let cursor = startIdx; for (const ch of pasted) { if (cursor >= safeLength) break; next[cursor] = ch; cursor += 1; } commitSlots(next); focusSlot(Math.min(cursor, safeLength - 1)); }; return ( <div role="group" aria-label={`${safeLength} 位验证码输入框`} className={cn("inline-flex items-center", compact ? "gap-1.5" : "gap-2", className)} > {slots.map((digit, idx) => ( <input key={idx} ref={(el) => { inputRefs.current[idx] = el; }} type="text" inputMode="numeric" autoComplete={idx === 0 ? "one-time-code" : "off"} pattern="[0-9]*" maxLength={safeLength} disabled={disabled} value={digit} aria-label={`第 ${idx + 1} 位验证码`} aria-invalid={invalid || undefined} onChange={(e) => handleChange(idx, e.target.value)} onKeyDown={(e) => handleKeyDown(idx, e)} onPaste={(e) => handlePaste(idx, e)} onFocus={(e) => e.currentTarget.select()} className={cn( "rounded-control border bg-surface text-center font-mono-num font-semibold text-fg transition outline-none", "focus-visible:border-accent focus-visible:ring-2 focus-visible:ring-accent/25", "disabled:cursor-not-allowed disabled:opacity-45", compact ? "h-10 w-8 text-xs" : "h-12 w-10 text-base sm:h-13 sm:w-11", invalid ? "border-danger bg-danger-soft/35 text-danger" : digit ? "border-accent shadow-panel" : "border-line-strong hover:border-fg-muted" )} /> ))} </div> );}