@r5n/otp-react 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/LICENSE +21 -0
- package/README.md +178 -2
- package/dist/index.cjs +394 -0
- package/dist/index.d.cts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +366 -0
- package/dist/otp-input.d.cts +153 -0
- package/dist/otp-input.d.ts +153 -0
- package/dist/styles.d.cts +22 -0
- package/dist/styles.d.ts +22 -0
- package/dist/use-otp.d.cts +101 -0
- package/dist/use-otp.d.ts +101 -0
- package/package.json +95 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
// src/otp-input.tsx
|
|
4
|
+
import {
|
|
5
|
+
Fragment,
|
|
6
|
+
forwardRef,
|
|
7
|
+
useId,
|
|
8
|
+
useImperativeHandle,
|
|
9
|
+
useLayoutEffect as useLayoutEffect2,
|
|
10
|
+
useState as useState2
|
|
11
|
+
} from "react";
|
|
12
|
+
|
|
13
|
+
// src/styles.ts
|
|
14
|
+
var ROOT_STYLE = { position: "relative" };
|
|
15
|
+
var INPUT_STYLE = {
|
|
16
|
+
position: "absolute",
|
|
17
|
+
inset: 0,
|
|
18
|
+
width: "100%",
|
|
19
|
+
height: "100%",
|
|
20
|
+
margin: 0,
|
|
21
|
+
padding: 0,
|
|
22
|
+
border: 0,
|
|
23
|
+
outline: "none",
|
|
24
|
+
boxShadow: "none",
|
|
25
|
+
boxSizing: "border-box",
|
|
26
|
+
appearance: "none",
|
|
27
|
+
background: "transparent",
|
|
28
|
+
opacity: 1,
|
|
29
|
+
color: "transparent",
|
|
30
|
+
WebkitTextFillColor: "transparent",
|
|
31
|
+
caretColor: "transparent",
|
|
32
|
+
forcedColorAdjust: "none",
|
|
33
|
+
fontSize: "16px",
|
|
34
|
+
fontFamily: "monospace",
|
|
35
|
+
lineHeight: 1,
|
|
36
|
+
textAlign: "start",
|
|
37
|
+
letterSpacing: "-0.5em"
|
|
38
|
+
};
|
|
39
|
+
var PASSIVE_STYLE = { pointerEvents: "none" };
|
|
40
|
+
var toCssName = (name) => name.replace(/[A-Z]/g, (upper) => `-${upper.toLowerCase()}`);
|
|
41
|
+
var restoreStyle = (element, style) => {
|
|
42
|
+
if (element.style.length > 0)
|
|
43
|
+
return;
|
|
44
|
+
for (const [name, value] of Object.entries(style)) {
|
|
45
|
+
element.style.setProperty(toCssName(name), String(value));
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
// src/use-otp.ts
|
|
50
|
+
import {
|
|
51
|
+
createOtpController
|
|
52
|
+
} from "@r5n/otp-core";
|
|
53
|
+
import { attachOtpInput } from "@r5n/otp-core/dom";
|
|
54
|
+
import {
|
|
55
|
+
useLayoutEffect,
|
|
56
|
+
useRef,
|
|
57
|
+
useState,
|
|
58
|
+
useSyncExternalStore
|
|
59
|
+
} from "react";
|
|
60
|
+
var defaultInputMode = (charset) => charset === undefined || charset === "numeric" ? "numeric" : "text";
|
|
61
|
+
var submitForm = (form) => {
|
|
62
|
+
if (typeof form.requestSubmit === "function") {
|
|
63
|
+
form.requestSubmit();
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const button = form.ownerDocument.createElement("button");
|
|
67
|
+
button.type = "submit";
|
|
68
|
+
button.hidden = true;
|
|
69
|
+
form.append(button);
|
|
70
|
+
button.click();
|
|
71
|
+
button.remove();
|
|
72
|
+
};
|
|
73
|
+
var focusAtEnd = (input, controller) => {
|
|
74
|
+
input.focus();
|
|
75
|
+
const end = input.value.length;
|
|
76
|
+
input.setSelectionRange(end, end);
|
|
77
|
+
const { length } = controller.getSnapshot().options;
|
|
78
|
+
controller.setSelection({ start: length, end: length });
|
|
79
|
+
};
|
|
80
|
+
function useOtp(options) {
|
|
81
|
+
const {
|
|
82
|
+
length,
|
|
83
|
+
charset,
|
|
84
|
+
casing,
|
|
85
|
+
groups,
|
|
86
|
+
value,
|
|
87
|
+
defaultValue,
|
|
88
|
+
onChange,
|
|
89
|
+
onComplete,
|
|
90
|
+
autoComplete = "one-time-code",
|
|
91
|
+
inputMode = defaultInputMode(charset),
|
|
92
|
+
autoSubmit = false,
|
|
93
|
+
direction = "ltr"
|
|
94
|
+
} = options;
|
|
95
|
+
const inputRef = useRef(null);
|
|
96
|
+
const submitted = useRef(null);
|
|
97
|
+
const controllerOptions = {
|
|
98
|
+
length,
|
|
99
|
+
charset,
|
|
100
|
+
casing,
|
|
101
|
+
groups,
|
|
102
|
+
value,
|
|
103
|
+
defaultValue,
|
|
104
|
+
onChange,
|
|
105
|
+
onComplete: autoSubmit ? (code) => {
|
|
106
|
+
onComplete?.(code);
|
|
107
|
+
const form = inputRef.current?.form;
|
|
108
|
+
if (!form)
|
|
109
|
+
return;
|
|
110
|
+
submitted.current = code;
|
|
111
|
+
submitForm(form);
|
|
112
|
+
} : onComplete
|
|
113
|
+
};
|
|
114
|
+
const latest = useRef(controllerOptions);
|
|
115
|
+
const [controller, setController] = useState(() => createOtpController(controllerOptions));
|
|
116
|
+
const destroyed = useRef(null);
|
|
117
|
+
const snapshot = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
|
|
118
|
+
useLayoutEffect(() => {
|
|
119
|
+
latest.current = controllerOptions;
|
|
120
|
+
controller.update(controllerOptions);
|
|
121
|
+
});
|
|
122
|
+
useLayoutEffect(() => {
|
|
123
|
+
const input = inputRef.current;
|
|
124
|
+
if (!input || destroyed.current === controller)
|
|
125
|
+
return;
|
|
126
|
+
restoreStyle(input, INPUT_STYLE);
|
|
127
|
+
const root = input.closest("[data-otp-root]");
|
|
128
|
+
if (root)
|
|
129
|
+
restoreStyle(root, ROOT_STYLE);
|
|
130
|
+
const onKeyDown = (event) => {
|
|
131
|
+
if (event.key !== "Enter" || event.isComposing)
|
|
132
|
+
return;
|
|
133
|
+
if (submitted.current === controller.getSnapshot().value)
|
|
134
|
+
event.preventDefault();
|
|
135
|
+
};
|
|
136
|
+
input.addEventListener("keydown", onKeyDown);
|
|
137
|
+
const detach = attachOtpInput(input, controller, { autoComplete, inputMode });
|
|
138
|
+
return () => {
|
|
139
|
+
input.removeEventListener("keydown", onKeyDown);
|
|
140
|
+
detach();
|
|
141
|
+
};
|
|
142
|
+
}, [controller, autoComplete, inputMode]);
|
|
143
|
+
useLayoutEffect(() => {
|
|
144
|
+
if (destroyed.current === controller) {
|
|
145
|
+
const { value: last } = controller.getSnapshot();
|
|
146
|
+
setController(createOtpController({ ...latest.current, defaultValue: last }));
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
return () => {
|
|
150
|
+
destroyed.current = controller;
|
|
151
|
+
controller.destroy();
|
|
152
|
+
};
|
|
153
|
+
}, [controller]);
|
|
154
|
+
return {
|
|
155
|
+
controller,
|
|
156
|
+
snapshot,
|
|
157
|
+
slots: snapshot.slots,
|
|
158
|
+
inputRef,
|
|
159
|
+
rootProps: {
|
|
160
|
+
"data-otp-root": "",
|
|
161
|
+
dir: direction === "auto" ? undefined : direction,
|
|
162
|
+
"data-complete": snapshot.isComplete ? "" : undefined,
|
|
163
|
+
style: ROOT_STYLE,
|
|
164
|
+
onMouseDown: (event) => {
|
|
165
|
+
const input = inputRef.current;
|
|
166
|
+
if (!input || input.disabled || event.button !== 0 || event.target === input)
|
|
167
|
+
return;
|
|
168
|
+
event.preventDefault();
|
|
169
|
+
focusAtEnd(input, controller);
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
inputProps: {
|
|
173
|
+
ref: inputRef,
|
|
174
|
+
type: "text",
|
|
175
|
+
autoComplete,
|
|
176
|
+
inputMode,
|
|
177
|
+
"data-otp-input": "",
|
|
178
|
+
style: INPUT_STYLE
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// src/otp-input.tsx
|
|
184
|
+
import { jsx, jsxs, Fragment as Fragment2 } from "react/jsx-runtime";
|
|
185
|
+
var MASK_GLYPH = "•";
|
|
186
|
+
var PASSWORD_MANAGER_IGNORE = {
|
|
187
|
+
"data-1p-ignore": "true",
|
|
188
|
+
"data-lpignore": "true",
|
|
189
|
+
"data-bwignore": "true",
|
|
190
|
+
"data-form-type": "other"
|
|
191
|
+
};
|
|
192
|
+
var PASSIVE_SELECTOR = "[data-otp-slot], [data-otp-separator]";
|
|
193
|
+
var flag = (on) => on ? "" : undefined;
|
|
194
|
+
var defaultLabel = (length, charset) => {
|
|
195
|
+
const unit = charset === "numeric" ? "digit" : charset === "alphabetic" ? "letter" : "character";
|
|
196
|
+
return `One-time code, ${length} ${unit}${length === 1 ? "" : "s"}`;
|
|
197
|
+
};
|
|
198
|
+
var OtpInput = forwardRef(function OtpInput(props, ref) {
|
|
199
|
+
const {
|
|
200
|
+
autoFocus,
|
|
201
|
+
disabled,
|
|
202
|
+
readOnly,
|
|
203
|
+
name,
|
|
204
|
+
form,
|
|
205
|
+
required,
|
|
206
|
+
mask,
|
|
207
|
+
type = "text",
|
|
208
|
+
placeholder,
|
|
209
|
+
error,
|
|
210
|
+
errorMessage,
|
|
211
|
+
"aria-invalid": ariaInvalid,
|
|
212
|
+
"aria-label": ariaLabel,
|
|
213
|
+
"aria-labelledby": ariaLabelledBy,
|
|
214
|
+
"aria-describedby": ariaDescribedBy,
|
|
215
|
+
id,
|
|
216
|
+
className,
|
|
217
|
+
style,
|
|
218
|
+
slotClassName,
|
|
219
|
+
render,
|
|
220
|
+
renderSeparator,
|
|
221
|
+
renderCaret,
|
|
222
|
+
passwordManagers = "allow",
|
|
223
|
+
inputProps,
|
|
224
|
+
onFocus,
|
|
225
|
+
onBlur,
|
|
226
|
+
...options
|
|
227
|
+
} = props;
|
|
228
|
+
const {
|
|
229
|
+
controller,
|
|
230
|
+
snapshot,
|
|
231
|
+
inputRef,
|
|
232
|
+
rootProps,
|
|
233
|
+
inputProps: ownInputProps
|
|
234
|
+
} = useOtp(options);
|
|
235
|
+
const errorId = useId();
|
|
236
|
+
const [labelled, setLabelled] = useState2(false);
|
|
237
|
+
const [resetValue] = useState2(options.defaultValue);
|
|
238
|
+
useLayoutEffect2(() => {
|
|
239
|
+
const input = inputRef.current;
|
|
240
|
+
const { labels } = input;
|
|
241
|
+
const hasLabel = labels !== null && labels.length > 0;
|
|
242
|
+
if (hasLabel !== labelled)
|
|
243
|
+
setLabelled(hasLabel);
|
|
244
|
+
const root = input.parentElement;
|
|
245
|
+
for (const element of root.querySelectorAll(PASSIVE_SELECTOR)) {
|
|
246
|
+
restoreStyle(element, PASSIVE_STYLE);
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
useImperativeHandle(ref, () => ({
|
|
250
|
+
focus: () => {
|
|
251
|
+
if (inputRef.current)
|
|
252
|
+
focusAtEnd(inputRef.current, controller);
|
|
253
|
+
},
|
|
254
|
+
blur: () => inputRef.current?.blur(),
|
|
255
|
+
clear: () => controller.clear(),
|
|
256
|
+
setValue: (value) => controller.setValue(value),
|
|
257
|
+
getValue: () => controller.getSnapshot().value,
|
|
258
|
+
select: () => {
|
|
259
|
+
const input = inputRef.current;
|
|
260
|
+
if (!input)
|
|
261
|
+
return;
|
|
262
|
+
input.focus();
|
|
263
|
+
input.select();
|
|
264
|
+
controller.setSelection({ start: 0, end: controller.getSnapshot().options.length });
|
|
265
|
+
},
|
|
266
|
+
get input() {
|
|
267
|
+
return inputRef.current;
|
|
268
|
+
}
|
|
269
|
+
}), [controller, inputRef]);
|
|
270
|
+
const { length, charset, groups } = snapshot.options;
|
|
271
|
+
const { selection, isFocused, isComplete } = snapshot;
|
|
272
|
+
const glyph = mask === true ? MASK_GLYPH : typeof mask === "string" && mask !== "" ? mask : undefined;
|
|
273
|
+
const placeholders = placeholder === undefined ? [] : Array.from(placeholder);
|
|
274
|
+
const isError = error === true || ariaInvalid !== undefined && ariaInvalid !== false && ariaInvalid !== "false";
|
|
275
|
+
const { style: inputStyle, ...nativeInputProps } = inputProps ?? {};
|
|
276
|
+
const showsError = isError && errorMessage !== undefined && errorMessage !== null;
|
|
277
|
+
const describedBy = [ariaDescribedBy, showsError ? errorId : undefined].filter(Boolean).join(" ") || undefined;
|
|
278
|
+
const root = /* @__PURE__ */ jsxs("div", {
|
|
279
|
+
...rootProps,
|
|
280
|
+
"data-disabled": flag(disabled === true),
|
|
281
|
+
"data-error": flag(isError),
|
|
282
|
+
className,
|
|
283
|
+
style: style === undefined ? rootProps.style : { ...rootProps.style, ...style },
|
|
284
|
+
children: [
|
|
285
|
+
snapshot.slots.map((slot) => {
|
|
286
|
+
const fallback = placeholder === undefined ? undefined : placeholders.length === length ? placeholders[slot.index] : placeholder;
|
|
287
|
+
const state = {
|
|
288
|
+
display: slot.isFilled ? glyph ?? slot.char : fallback ?? "",
|
|
289
|
+
isPlaceholder: !slot.isFilled && fallback !== undefined,
|
|
290
|
+
hasCaret: slot.isActive && !slot.isFilled && selection.start === selection.end && !readOnly,
|
|
291
|
+
isFocused,
|
|
292
|
+
isComplete,
|
|
293
|
+
isDisabled: disabled === true,
|
|
294
|
+
isError
|
|
295
|
+
};
|
|
296
|
+
return /* @__PURE__ */ jsxs(Fragment, {
|
|
297
|
+
children: [
|
|
298
|
+
/* @__PURE__ */ jsxs("div", {
|
|
299
|
+
"data-otp-slot": "",
|
|
300
|
+
"data-index": slot.index,
|
|
301
|
+
"data-active": flag(slot.isActive),
|
|
302
|
+
"data-filled": flag(slot.isFilled),
|
|
303
|
+
"data-caret": flag(state.hasCaret),
|
|
304
|
+
"data-placeholder": flag(state.isPlaceholder),
|
|
305
|
+
"data-first-in-group": flag(slot.isFirstInGroup),
|
|
306
|
+
"data-last-in-group": flag(slot.isLastInGroup),
|
|
307
|
+
"aria-hidden": "true",
|
|
308
|
+
className: slotClassName,
|
|
309
|
+
style: PASSIVE_STYLE,
|
|
310
|
+
children: [
|
|
311
|
+
render ? render(slot, state) : state.display,
|
|
312
|
+
state.hasCaret && renderCaret ? renderCaret() : null
|
|
313
|
+
]
|
|
314
|
+
}),
|
|
315
|
+
renderSeparator && slot.isLastInGroup && slot.groupIndex < groups.length - 1 ? /* @__PURE__ */ jsx("div", {
|
|
316
|
+
"data-otp-separator": "",
|
|
317
|
+
"aria-hidden": "true",
|
|
318
|
+
style: PASSIVE_STYLE,
|
|
319
|
+
children: renderSeparator(slot.groupIndex)
|
|
320
|
+
}) : null
|
|
321
|
+
]
|
|
322
|
+
}, slot.index);
|
|
323
|
+
}),
|
|
324
|
+
/* @__PURE__ */ jsx("input", {
|
|
325
|
+
...ownInputProps,
|
|
326
|
+
type,
|
|
327
|
+
defaultValue: resetValue,
|
|
328
|
+
id,
|
|
329
|
+
name,
|
|
330
|
+
form,
|
|
331
|
+
required,
|
|
332
|
+
disabled,
|
|
333
|
+
readOnly,
|
|
334
|
+
autoFocus,
|
|
335
|
+
"aria-label": ariaLabel ?? (ariaLabelledBy === undefined && !labelled ? defaultLabel(length, charset) : undefined),
|
|
336
|
+
"aria-labelledby": ariaLabelledBy,
|
|
337
|
+
"aria-describedby": describedBy,
|
|
338
|
+
"aria-invalid": ariaInvalid ?? (error === true ? true : undefined),
|
|
339
|
+
onFocus,
|
|
340
|
+
onBlur,
|
|
341
|
+
...passwordManagers === "ignore" ? PASSWORD_MANAGER_IGNORE : undefined,
|
|
342
|
+
...nativeInputProps,
|
|
343
|
+
style: {
|
|
344
|
+
...ownInputProps.style,
|
|
345
|
+
cursor: disabled === true ? "default" : "text",
|
|
346
|
+
...inputStyle
|
|
347
|
+
}
|
|
348
|
+
})
|
|
349
|
+
]
|
|
350
|
+
});
|
|
351
|
+
return errorMessage === undefined ? root : /* @__PURE__ */ jsxs(Fragment2, {
|
|
352
|
+
children: [
|
|
353
|
+
root,
|
|
354
|
+
/* @__PURE__ */ jsx("div", {
|
|
355
|
+
id: errorId,
|
|
356
|
+
"data-otp-error-message": "",
|
|
357
|
+
role: "alert",
|
|
358
|
+
children: showsError ? errorMessage : null
|
|
359
|
+
})
|
|
360
|
+
]
|
|
361
|
+
});
|
|
362
|
+
});
|
|
363
|
+
export {
|
|
364
|
+
OtpInput,
|
|
365
|
+
useOtp
|
|
366
|
+
};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import type { OtpSlot } from '@r5n/otp-core';
|
|
2
|
+
import { type AriaAttributes, type CSSProperties, type FocusEventHandler, type ForwardRefExoticComponent, type InputHTMLAttributes, type ReactNode, type RefAttributes } from 'react';
|
|
3
|
+
import { type UseOtpOptions } from './use-otp.cjs';
|
|
4
|
+
/** What {@link OtpInputProps.render} receives besides the core slot state. */
|
|
5
|
+
export interface OtpSlotState {
|
|
6
|
+
/** Text the slot shows by default: the character, the mask glyph, the placeholder, or `''`. */
|
|
7
|
+
readonly display: string;
|
|
8
|
+
/** The slot is empty and shows the placeholder. */
|
|
9
|
+
readonly isPlaceholder: boolean;
|
|
10
|
+
/**
|
|
11
|
+
* The caret is in this empty slot: the input is focused, editable and has a collapsed
|
|
12
|
+
* selection. Render a fake caret here (or use `renderCaret`, or `[data-caret]` in CSS).
|
|
13
|
+
*/
|
|
14
|
+
readonly hasCaret: boolean;
|
|
15
|
+
/** The input has the focus. */
|
|
16
|
+
readonly isFocused: boolean;
|
|
17
|
+
readonly isComplete: boolean;
|
|
18
|
+
readonly isDisabled: boolean;
|
|
19
|
+
/** `error` is set (or `aria-invalid` is true). */
|
|
20
|
+
readonly isError: boolean;
|
|
21
|
+
}
|
|
22
|
+
/** Imperative API of {@link OtpInput}. */
|
|
23
|
+
export interface OtpInputRef {
|
|
24
|
+
/** Focuses the input with the caret after the last character. */
|
|
25
|
+
focus(): void;
|
|
26
|
+
blur(): void;
|
|
27
|
+
/** Empties the value; fires `onChange('')`. */
|
|
28
|
+
clear(): void;
|
|
29
|
+
/**
|
|
30
|
+
* Sets the value like a user edit: sanitised, fires `onChange` and `onComplete` (when
|
|
31
|
+
* controlled, once the parent's `value` confirms it). Text longer than `length`, such as an SMS
|
|
32
|
+
* body, is searched for a code first; text that is neither a code nor a partial code
|
|
33
|
+
* (`'Error: 15'`) is ignored.
|
|
34
|
+
*/
|
|
35
|
+
setValue(value: string): void;
|
|
36
|
+
getValue(): string;
|
|
37
|
+
/** Focuses the input and selects the whole value, so typing replaces it. */
|
|
38
|
+
select(): void;
|
|
39
|
+
/**
|
|
40
|
+
* The native `<input>`, for `setCustomValidity`, `reportValidity`, `scrollIntoView` or
|
|
41
|
+
* measuring; `null` before mount and after unmount. Its value and attributes are managed.
|
|
42
|
+
*/
|
|
43
|
+
readonly input: HTMLInputElement | null;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Attributes passed to the `<input>` through `inputProps`. Excluded: the value (owned by the
|
|
47
|
+
* controller), `type` (see the prop), `maxLength` (it would truncate pastes and autofill before
|
|
48
|
+
* the code can be extracted), and the attributes `@r5n/otp-core/dom` writes after every option
|
|
49
|
+
* change, which would override them: `autoComplete` and `inputMode` (use the props of the same
|
|
50
|
+
* name), `pattern`, `spellCheck`, `autoCorrect`, `autoCapitalize` and `enterKeyHint`.
|
|
51
|
+
*/
|
|
52
|
+
export type OtpNativeInputProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'defaultValue' | 'type' | 'maxLength' | 'autoComplete' | 'inputMode' | 'pattern' | 'spellCheck' | 'autoCorrect' | 'autoCapitalize' | 'enterKeyHint' | 'children' | 'dangerouslySetInnerHTML'>;
|
|
53
|
+
/** Props of {@link OtpInput}. */
|
|
54
|
+
export interface OtpInputProps extends UseOtpOptions {
|
|
55
|
+
/** Focuses the input on mount. */
|
|
56
|
+
autoFocus?: boolean | undefined;
|
|
57
|
+
disabled?: boolean | undefined;
|
|
58
|
+
/** The value can be focused and selected but not edited, pasted into or autofilled. */
|
|
59
|
+
readOnly?: boolean | undefined;
|
|
60
|
+
/** Form field name: the code is submitted with the form. */
|
|
61
|
+
name?: string | undefined;
|
|
62
|
+
/** `id` of the form the input belongs to, when it is not inside it. */
|
|
63
|
+
form?: string | undefined;
|
|
64
|
+
/** Native constraint: with the built-in charsets a `pattern` also rejects incomplete codes. */
|
|
65
|
+
required?: boolean | undefined;
|
|
66
|
+
/**
|
|
67
|
+
* Hides the characters on screen: `true` shows `•` in filled slots, a non-empty string shows
|
|
68
|
+
* that string (`''` means not masked, as in `@r5n/otp-react-native`). The native input stays
|
|
69
|
+
* `type="text"`, so screen readers still read the value; see `type`.
|
|
70
|
+
*/
|
|
71
|
+
mask?: boolean | string | undefined;
|
|
72
|
+
/**
|
|
73
|
+
* Type of the native input. Default `'text'`. `'password'` (with `mask`) also hides the value
|
|
74
|
+
* from assistive technology and from autocorrect and form history, but browsers then treat the
|
|
75
|
+
* code as a password: Chrome's password manager offers to save it after submission (also with
|
|
76
|
+
* `autoComplete="off"`), and Edge and Safari draw their password icons over the last slot.
|
|
77
|
+
*/
|
|
78
|
+
type?: 'text' | 'password' | undefined;
|
|
79
|
+
/**
|
|
80
|
+
* Shown in empty slots. A string with exactly `length` characters is spread over the slots
|
|
81
|
+
* (`'000000'`); any other string is shown in every empty slot (`'○'`).
|
|
82
|
+
*/
|
|
83
|
+
placeholder?: string | undefined;
|
|
84
|
+
/** Error state: sets `aria-invalid` on the input and `data-error` on the root. */
|
|
85
|
+
error?: boolean | undefined;
|
|
86
|
+
/**
|
|
87
|
+
* Error text for assistive technology and sighted users. When given, an element
|
|
88
|
+
* `<div data-otp-error-message role="alert">` is rendered right after the root (outside it, so
|
|
89
|
+
* the input overlay does not cover it); while `error` is set it holds this content, is announced,
|
|
90
|
+
* and is linked to the input through `aria-describedby`. Clear `error` when the user edits, so
|
|
91
|
+
* the next wrong code is announced again.
|
|
92
|
+
*/
|
|
93
|
+
errorMessage?: ReactNode | undefined;
|
|
94
|
+
/** Overrides the `aria-invalid` derived from `error`. */
|
|
95
|
+
'aria-invalid'?: AriaAttributes['aria-invalid'];
|
|
96
|
+
/**
|
|
97
|
+
* Accessible name of the input. Default: `'One-time code, 6 digits'` (`letters` or `characters`
|
|
98
|
+
* for other charsets), unless `aria-labelledby` is set or a `<label>` names the input (through
|
|
99
|
+
* `htmlFor={id}` or by wrapping it). The label is detected after mount, so server markup carries
|
|
100
|
+
* the default until hydration.
|
|
101
|
+
*/
|
|
102
|
+
'aria-label'?: string | undefined;
|
|
103
|
+
'aria-labelledby'?: string | undefined;
|
|
104
|
+
'aria-describedby'?: string | undefined;
|
|
105
|
+
/** `id` of the input, for `<label htmlFor>`. */
|
|
106
|
+
id?: string | undefined;
|
|
107
|
+
/** Class of the root element. */
|
|
108
|
+
className?: string | undefined;
|
|
109
|
+
/** Style of the root element, merged over `position: relative`. */
|
|
110
|
+
style?: CSSProperties | undefined;
|
|
111
|
+
/** Class of every slot element. */
|
|
112
|
+
slotClassName?: string | undefined;
|
|
113
|
+
/** Content of each slot. Default: `state.display`. */
|
|
114
|
+
render?: ((slot: OtpSlot, state: OtpSlotState) => ReactNode) | undefined;
|
|
115
|
+
/** Rendered between two groups (see `groups`), with the index of the group before it. */
|
|
116
|
+
renderSeparator?: ((groupIndex: number) => ReactNode) | undefined;
|
|
117
|
+
/** Rendered inside the slot that holds the caret (see {@link OtpSlotState.hasCaret}). */
|
|
118
|
+
renderCaret?: (() => ReactNode) | undefined;
|
|
119
|
+
/**
|
|
120
|
+
* `'allow'` (default) leaves password managers alone: 1Password, Bitwarden and others fill
|
|
121
|
+
* TOTP codes into such fields, which is legitimate. `'ignore'` adds the hints 1Password,
|
|
122
|
+
* LastPass, Bitwarden and Dashlane read to skip the field (for SMS or email codes).
|
|
123
|
+
*/
|
|
124
|
+
passwordManagers?: 'allow' | 'ignore' | undefined;
|
|
125
|
+
/**
|
|
126
|
+
* Escape hatch: attributes and handlers for the `<input>`. They win over the props above; the
|
|
127
|
+
* attributes the binder owns are excluded (see {@link OtpNativeInputProps}).
|
|
128
|
+
*/
|
|
129
|
+
inputProps?: OtpNativeInputProps | undefined;
|
|
130
|
+
onFocus?: FocusEventHandler<HTMLInputElement> | undefined;
|
|
131
|
+
onBlur?: FocusEventHandler<HTMLInputElement> | undefined;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* One-time code input for React DOM: one real `<input>`, stacked invisibly over `length` slots.
|
|
135
|
+
* Unstyled: style the data attributes (see the README).
|
|
136
|
+
*
|
|
137
|
+
* ```html
|
|
138
|
+
* <div data-otp-root dir="ltr" data-complete data-disabled data-error>
|
|
139
|
+
* <div data-otp-slot data-index="0" data-active data-filled data-caret data-placeholder
|
|
140
|
+
* data-first-in-group data-last-in-group aria-hidden="true">1</div>
|
|
141
|
+
* <div data-otp-separator aria-hidden="true">...</div>
|
|
142
|
+
* <input data-otp-input autocomplete="one-time-code" inputmode="numeric" />
|
|
143
|
+
* </div>
|
|
144
|
+
* ```
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* ```tsx
|
|
148
|
+
* <form action="/verify">
|
|
149
|
+
* <OtpInput length={6} groups={[3, 3]} name="code" autoSubmit />
|
|
150
|
+
* </form>
|
|
151
|
+
* ```
|
|
152
|
+
*/
|
|
153
|
+
export declare const OtpInput: ForwardRefExoticComponent<OtpInputProps & RefAttributes<OtpInputRef>>;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import type { OtpSlot } from '@r5n/otp-core';
|
|
2
|
+
import { type AriaAttributes, type CSSProperties, type FocusEventHandler, type ForwardRefExoticComponent, type InputHTMLAttributes, type ReactNode, type RefAttributes } from 'react';
|
|
3
|
+
import { type UseOtpOptions } from './use-otp.js';
|
|
4
|
+
/** What {@link OtpInputProps.render} receives besides the core slot state. */
|
|
5
|
+
export interface OtpSlotState {
|
|
6
|
+
/** Text the slot shows by default: the character, the mask glyph, the placeholder, or `''`. */
|
|
7
|
+
readonly display: string;
|
|
8
|
+
/** The slot is empty and shows the placeholder. */
|
|
9
|
+
readonly isPlaceholder: boolean;
|
|
10
|
+
/**
|
|
11
|
+
* The caret is in this empty slot: the input is focused, editable and has a collapsed
|
|
12
|
+
* selection. Render a fake caret here (or use `renderCaret`, or `[data-caret]` in CSS).
|
|
13
|
+
*/
|
|
14
|
+
readonly hasCaret: boolean;
|
|
15
|
+
/** The input has the focus. */
|
|
16
|
+
readonly isFocused: boolean;
|
|
17
|
+
readonly isComplete: boolean;
|
|
18
|
+
readonly isDisabled: boolean;
|
|
19
|
+
/** `error` is set (or `aria-invalid` is true). */
|
|
20
|
+
readonly isError: boolean;
|
|
21
|
+
}
|
|
22
|
+
/** Imperative API of {@link OtpInput}. */
|
|
23
|
+
export interface OtpInputRef {
|
|
24
|
+
/** Focuses the input with the caret after the last character. */
|
|
25
|
+
focus(): void;
|
|
26
|
+
blur(): void;
|
|
27
|
+
/** Empties the value; fires `onChange('')`. */
|
|
28
|
+
clear(): void;
|
|
29
|
+
/**
|
|
30
|
+
* Sets the value like a user edit: sanitised, fires `onChange` and `onComplete` (when
|
|
31
|
+
* controlled, once the parent's `value` confirms it). Text longer than `length`, such as an SMS
|
|
32
|
+
* body, is searched for a code first; text that is neither a code nor a partial code
|
|
33
|
+
* (`'Error: 15'`) is ignored.
|
|
34
|
+
*/
|
|
35
|
+
setValue(value: string): void;
|
|
36
|
+
getValue(): string;
|
|
37
|
+
/** Focuses the input and selects the whole value, so typing replaces it. */
|
|
38
|
+
select(): void;
|
|
39
|
+
/**
|
|
40
|
+
* The native `<input>`, for `setCustomValidity`, `reportValidity`, `scrollIntoView` or
|
|
41
|
+
* measuring; `null` before mount and after unmount. Its value and attributes are managed.
|
|
42
|
+
*/
|
|
43
|
+
readonly input: HTMLInputElement | null;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Attributes passed to the `<input>` through `inputProps`. Excluded: the value (owned by the
|
|
47
|
+
* controller), `type` (see the prop), `maxLength` (it would truncate pastes and autofill before
|
|
48
|
+
* the code can be extracted), and the attributes `@r5n/otp-core/dom` writes after every option
|
|
49
|
+
* change, which would override them: `autoComplete` and `inputMode` (use the props of the same
|
|
50
|
+
* name), `pattern`, `spellCheck`, `autoCorrect`, `autoCapitalize` and `enterKeyHint`.
|
|
51
|
+
*/
|
|
52
|
+
export type OtpNativeInputProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'defaultValue' | 'type' | 'maxLength' | 'autoComplete' | 'inputMode' | 'pattern' | 'spellCheck' | 'autoCorrect' | 'autoCapitalize' | 'enterKeyHint' | 'children' | 'dangerouslySetInnerHTML'>;
|
|
53
|
+
/** Props of {@link OtpInput}. */
|
|
54
|
+
export interface OtpInputProps extends UseOtpOptions {
|
|
55
|
+
/** Focuses the input on mount. */
|
|
56
|
+
autoFocus?: boolean | undefined;
|
|
57
|
+
disabled?: boolean | undefined;
|
|
58
|
+
/** The value can be focused and selected but not edited, pasted into or autofilled. */
|
|
59
|
+
readOnly?: boolean | undefined;
|
|
60
|
+
/** Form field name: the code is submitted with the form. */
|
|
61
|
+
name?: string | undefined;
|
|
62
|
+
/** `id` of the form the input belongs to, when it is not inside it. */
|
|
63
|
+
form?: string | undefined;
|
|
64
|
+
/** Native constraint: with the built-in charsets a `pattern` also rejects incomplete codes. */
|
|
65
|
+
required?: boolean | undefined;
|
|
66
|
+
/**
|
|
67
|
+
* Hides the characters on screen: `true` shows `•` in filled slots, a non-empty string shows
|
|
68
|
+
* that string (`''` means not masked, as in `@r5n/otp-react-native`). The native input stays
|
|
69
|
+
* `type="text"`, so screen readers still read the value; see `type`.
|
|
70
|
+
*/
|
|
71
|
+
mask?: boolean | string | undefined;
|
|
72
|
+
/**
|
|
73
|
+
* Type of the native input. Default `'text'`. `'password'` (with `mask`) also hides the value
|
|
74
|
+
* from assistive technology and from autocorrect and form history, but browsers then treat the
|
|
75
|
+
* code as a password: Chrome's password manager offers to save it after submission (also with
|
|
76
|
+
* `autoComplete="off"`), and Edge and Safari draw their password icons over the last slot.
|
|
77
|
+
*/
|
|
78
|
+
type?: 'text' | 'password' | undefined;
|
|
79
|
+
/**
|
|
80
|
+
* Shown in empty slots. A string with exactly `length` characters is spread over the slots
|
|
81
|
+
* (`'000000'`); any other string is shown in every empty slot (`'○'`).
|
|
82
|
+
*/
|
|
83
|
+
placeholder?: string | undefined;
|
|
84
|
+
/** Error state: sets `aria-invalid` on the input and `data-error` on the root. */
|
|
85
|
+
error?: boolean | undefined;
|
|
86
|
+
/**
|
|
87
|
+
* Error text for assistive technology and sighted users. When given, an element
|
|
88
|
+
* `<div data-otp-error-message role="alert">` is rendered right after the root (outside it, so
|
|
89
|
+
* the input overlay does not cover it); while `error` is set it holds this content, is announced,
|
|
90
|
+
* and is linked to the input through `aria-describedby`. Clear `error` when the user edits, so
|
|
91
|
+
* the next wrong code is announced again.
|
|
92
|
+
*/
|
|
93
|
+
errorMessage?: ReactNode | undefined;
|
|
94
|
+
/** Overrides the `aria-invalid` derived from `error`. */
|
|
95
|
+
'aria-invalid'?: AriaAttributes['aria-invalid'];
|
|
96
|
+
/**
|
|
97
|
+
* Accessible name of the input. Default: `'One-time code, 6 digits'` (`letters` or `characters`
|
|
98
|
+
* for other charsets), unless `aria-labelledby` is set or a `<label>` names the input (through
|
|
99
|
+
* `htmlFor={id}` or by wrapping it). The label is detected after mount, so server markup carries
|
|
100
|
+
* the default until hydration.
|
|
101
|
+
*/
|
|
102
|
+
'aria-label'?: string | undefined;
|
|
103
|
+
'aria-labelledby'?: string | undefined;
|
|
104
|
+
'aria-describedby'?: string | undefined;
|
|
105
|
+
/** `id` of the input, for `<label htmlFor>`. */
|
|
106
|
+
id?: string | undefined;
|
|
107
|
+
/** Class of the root element. */
|
|
108
|
+
className?: string | undefined;
|
|
109
|
+
/** Style of the root element, merged over `position: relative`. */
|
|
110
|
+
style?: CSSProperties | undefined;
|
|
111
|
+
/** Class of every slot element. */
|
|
112
|
+
slotClassName?: string | undefined;
|
|
113
|
+
/** Content of each slot. Default: `state.display`. */
|
|
114
|
+
render?: ((slot: OtpSlot, state: OtpSlotState) => ReactNode) | undefined;
|
|
115
|
+
/** Rendered between two groups (see `groups`), with the index of the group before it. */
|
|
116
|
+
renderSeparator?: ((groupIndex: number) => ReactNode) | undefined;
|
|
117
|
+
/** Rendered inside the slot that holds the caret (see {@link OtpSlotState.hasCaret}). */
|
|
118
|
+
renderCaret?: (() => ReactNode) | undefined;
|
|
119
|
+
/**
|
|
120
|
+
* `'allow'` (default) leaves password managers alone: 1Password, Bitwarden and others fill
|
|
121
|
+
* TOTP codes into such fields, which is legitimate. `'ignore'` adds the hints 1Password,
|
|
122
|
+
* LastPass, Bitwarden and Dashlane read to skip the field (for SMS or email codes).
|
|
123
|
+
*/
|
|
124
|
+
passwordManagers?: 'allow' | 'ignore' | undefined;
|
|
125
|
+
/**
|
|
126
|
+
* Escape hatch: attributes and handlers for the `<input>`. They win over the props above; the
|
|
127
|
+
* attributes the binder owns are excluded (see {@link OtpNativeInputProps}).
|
|
128
|
+
*/
|
|
129
|
+
inputProps?: OtpNativeInputProps | undefined;
|
|
130
|
+
onFocus?: FocusEventHandler<HTMLInputElement> | undefined;
|
|
131
|
+
onBlur?: FocusEventHandler<HTMLInputElement> | undefined;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* One-time code input for React DOM: one real `<input>`, stacked invisibly over `length` slots.
|
|
135
|
+
* Unstyled: style the data attributes (see the README).
|
|
136
|
+
*
|
|
137
|
+
* ```html
|
|
138
|
+
* <div data-otp-root dir="ltr" data-complete data-disabled data-error>
|
|
139
|
+
* <div data-otp-slot data-index="0" data-active data-filled data-caret data-placeholder
|
|
140
|
+
* data-first-in-group data-last-in-group aria-hidden="true">1</div>
|
|
141
|
+
* <div data-otp-separator aria-hidden="true">...</div>
|
|
142
|
+
* <input data-otp-input autocomplete="one-time-code" inputmode="numeric" />
|
|
143
|
+
* </div>
|
|
144
|
+
* ```
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* ```tsx
|
|
148
|
+
* <form action="/verify">
|
|
149
|
+
* <OtpInput length={6} groups={[3, 3]} name="code" autoSubmit />
|
|
150
|
+
* </form>
|
|
151
|
+
* ```
|
|
152
|
+
*/
|
|
153
|
+
export declare const OtpInput: ForwardRefExoticComponent<OtpInputProps & RefAttributes<OtpInputRef>>;
|