1 "use client"
2
3 import * as React from "react"
4
5 import { clx } from "@/utils/clx"
6
7 interface OtpInputProps
8 extends Omit<React.HTMLAttributes<HTMLDivElement>, "onChange"> {
9 /**
10 * Whether the inputs should focus the first field on mount.
11 */
12 autoFocus?: boolean
13 /**
14 * Whether the inputs are disabled.
15 */
16 disabled?: boolean
17 /**
18 * How many digits to show before rendering a separator.
19 */
20 groupSize?: number
21 /**
22 * Additional class name for each input.
23 */
24 inputClassName?: string
25 /**
26 * The number of digits in the code.
27 */
28 length?: number
29 /**
30 * Called with the sanitized code whenever it changes.
31 */
32 onChange: (value: string) => void
33 /**
34 * Called when the sanitized code reaches the configured length.
35 */
36 onComplete?: (value: string) => void
37 /**
38 * Whether the inputs are read-only.
39 */
40 readOnly?: boolean
41 /**
42 * The separator rendered between groups.
43 */
44 separator?: React.ReactNode
45 /**
46 * The controlled code value.
47 */
48 value: string
49 }
50
51 const sanitizeOtp = (value: string, length: number) => {
52 return value.replace(/\D/g, "").slice(0, length)
53 }
54
55 const getDigits = (value: string, length: number) => {
56 return sanitizeOtp(value, length).padEnd(length, " ").split("")
57 }
58
59 const getWritableDigits = (value: string, length: number) => {
60 return getDigits(value, length).map((digit) => (digit === " " ? "" : digit))
61 }
62
63 const getDigitGroups = (length: number, groupSize: number) => {
64 return Array.from({ length: Math.ceil(length / groupSize) }).map(
65 (_, groupIndex) => {
66 const start = groupIndex * groupSize
67
68 return {
69 start,
70 length: Math.min(groupSize, length - start),
71 }
72 }
73 )
74 }
75
76 const applyOtpAtIndex = (
77 digits: string[],
78 index: number,
79 value: string,
80 length: number
81 ) => {
82 value.split("").forEach((digit, offset) => {
83 if (index + offset < length) {
84 digits[index + offset] = digit
85 }
86 })
87
88 return digits
89 }
90
91 /**
92 * A controlled segmented input for one-time passwords, PINs, and short numeric verification codes.
93 */
94 const OtpInput = React.forwardRef<HTMLDivElement, OtpInputProps>(
95 (
96 {
97 "aria-invalid": ariaInvalid,
98 "aria-label": ariaLabel = "One-time password",
99 autoFocus,
100 className,
101 disabled,
102 groupSize = 3,
103 inputClassName,
104 length = 6,
105 onChange,
106 onComplete,
107 readOnly,
108 separator = "-",
109 value,
110 ...props
111 }: OtpInputProps,
112 ref
113 ) => {
114 const inputRefs = React.useRef<Array<HTMLInputElement | null>>([])
115 const codeLength = Math.max(1, length)
116 const digits = getDigits(value, codeLength)
117 const safeGroupSize = Math.max(1, groupSize)
118 const digitGroups = getDigitGroups(codeLength, safeGroupSize)
119
120 const focusInput = (index: number) => {
121 const nextIndex = Math.min(Math.max(index, 0), codeLength - 1)
122
123 inputRefs.current[nextIndex]?.focus()
124 }
125
126 const updateValue = (nextValue: string, nextFocusIndex?: number) => {
127 const sanitizedValue = sanitizeOtp(nextValue, codeLength)
128
129 onChange(sanitizedValue)
130
131 if (sanitizedValue.length === codeLength) {
132 onComplete?.(sanitizedValue)
133 }
134
135 if (typeof nextFocusIndex === "number") {
136 requestAnimationFrame(() => focusInput(nextFocusIndex))
137 }
138 }
139
140 const handleChange = (index: number, rawValue: string) => {
141 const nextDigits = getWritableDigits(value, codeLength)
142 const incoming = sanitizeOtp(rawValue, codeLength)
143
144 if (!incoming) {
145 nextDigits[index] = ""
146 updateValue(nextDigits.join(""), index)
147 return
148 }
149
150 applyOtpAtIndex(nextDigits, index, incoming, codeLength)
151
152 updateValue(
153 nextDigits.join(""),
154 Math.min(index + incoming.length, codeLength - 1)
155 )
156 }
157
158 const handleKeyDown = (
159 event: React.KeyboardEvent<HTMLInputElement>,
160 index: number
161 ) => {
162 if (event.key === "Backspace" && !digits[index].trim()) {
163 event.preventDefault()
164
165 if (index === 0) {
166 return
167 }
168
169 const nextDigits = getWritableDigits(value, codeLength)
170
171 nextDigits[index - 1] = ""
172 updateValue(nextDigits.join(""), index - 1)
173 }
174
175 if (event.key === "ArrowLeft") {
176 event.preventDefault()
177 focusInput(index - 1)
178 }
179
180 if (event.key === "ArrowRight") {
181 event.preventDefault()
182 focusInput(index + 1)
183 }
184
185 if (event.key === "Home") {
186 event.preventDefault()
187 focusInput(0)
188 }
189
190 if (event.key === "End") {
191 event.preventDefault()
192 focusInput(codeLength - 1)
193 }
194 }
195
196 const handlePaste = (
197 event: React.ClipboardEvent<HTMLInputElement>,
198 index: number
199 ) => {
200 event.preventDefault()
201
202 const pastedValue = sanitizeOtp(
203 event.clipboardData.getData("text"),
204 codeLength
205 )
206
207 if (!pastedValue) {
208 return
209 }
210
211 if (pastedValue.length === codeLength) {
212 updateValue(pastedValue, codeLength - 1)
213 return
214 }
215
216 const nextDigits = getWritableDigits(value, codeLength)
217
218 applyOtpAtIndex(nextDigits, index, pastedValue, codeLength)
219
220 updateValue(
221 nextDigits.join(""),
222 Math.min(index + pastedValue.length, codeLength - 1)
223 )
224 }
225
226 const renderInput = (index: number) => {
227 return (
228 <input
229 key={index}
230 ref={(element) => {
231 inputRefs.current[index] = element
232 }}
233 aria-invalid={ariaInvalid}
234 aria-label={`${ariaLabel} ${index + 1}`}
235 autoComplete={index === 0 ? "one-time-code" : "off"}
236 autoFocus={autoFocus && index === 0}
237 className={clx(
238 "txt-compact-large font-mono text-ui-fg-base bg-ui-bg-field hover:bg-ui-bg-field-hover shadow-borders-base transition-fg relative -ml-px flex size-10 appearance-none items-center justify-center border-0 text-center outline-none first:ml-0 first:rounded-l-md last:rounded-r-md",
239 "focus-visible:z-10 focus-visible:shadow-borders-interactive-with-active",
240 "disabled:text-ui-fg-disabled disabled:!bg-ui-bg-disabled disabled:cursor-not-allowed",
241 "aria-[invalid=true]:!shadow-borders-error",
242 inputClassName
243 )}
244 disabled={disabled}
245 inputMode="numeric"
246 maxLength={codeLength}
247 onChange={(event) => handleChange(index, event.target.value)}
248 onFocus={(event) => event.target.select()}
249 onKeyDown={(event) => handleKeyDown(event, index)}
250 onPaste={(event) => handlePaste(event, index)}
251 pattern="[0-9]*"
252 readOnly={readOnly}
253 type="text"
254 value={digits[index].trim()}
255 />
256 )
257 }
258
259 return (
260 <div
261 ref={ref}
262 aria-invalid={ariaInvalid}
263 aria-label={ariaLabel}
264 className={clx("flex items-center justify-center gap-x-3", className)}
265 role="group"
266 {...props}
267 >
268 {digitGroups.map(({ start, length }, groupIndex) => {
269 return (
270 <React.Fragment key={groupIndex}>
271 {groupIndex > 0 && separator && (
272 <span
273 aria-hidden="true"
274 className="txt-compact-small-plus text-ui-fg-muted"
275 >
276 {separator}
277 </span>
278 )}
279 <div className="flex">
280 {Array.from({ length }).map((_, offset) =>
281 renderInput(start + offset)
282 )}
283 </div>
284 </React.Fragment>
285 )
286 })}
287 </div>
288 )
289 }
290 )
291 OtpInput.displayName = "OtpInput"
292
293 export { OtpInput }
294 export type { OtpInputProps }