@bymax-one/nest-notification 1.0.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 +70 -0
- package/LICENSE +21 -0
- package/README.md +785 -0
- package/dist/react/index.cjs +225 -0
- package/dist/react/index.d.cts +105 -0
- package/dist/react/index.d.ts +105 -0
- package/dist/react/index.mjs +222 -0
- package/dist/server/index.cjs +2087 -0
- package/dist/server/index.d.cts +2155 -0
- package/dist/server/index.d.ts +2155 -0
- package/dist/server/index.mjs +2067 -0
- package/dist/shared/index.cjs +49 -0
- package/dist/shared/index.d.cts +138 -0
- package/dist/shared/index.d.ts +138 -0
- package/dist/shared/index.mjs +46 -0
- package/package.json +244 -0
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var react = require('react');
|
|
4
|
+
|
|
5
|
+
// src/react/useOtpInput.ts
|
|
6
|
+
var DEFAULT_LENGTH = 6;
|
|
7
|
+
function charPattern(type) {
|
|
8
|
+
switch (type) {
|
|
9
|
+
case "alpha":
|
|
10
|
+
return /^[A-Za-z]$/;
|
|
11
|
+
case "alphanumeric":
|
|
12
|
+
return /^[A-Za-z0-9]$/;
|
|
13
|
+
default:
|
|
14
|
+
return /^[0-9]$/;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function isValidChar(char, type) {
|
|
18
|
+
return charPattern(type).test(char);
|
|
19
|
+
}
|
|
20
|
+
function normalizeChar(char, type) {
|
|
21
|
+
return type === "numeric" ? char : char.toUpperCase();
|
|
22
|
+
}
|
|
23
|
+
function filterValid(input, type) {
|
|
24
|
+
let result = "";
|
|
25
|
+
for (const char of input) {
|
|
26
|
+
if (isValidChar(char, type)) {
|
|
27
|
+
result += normalizeChar(char, type);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
function makeEmptyValues(length) {
|
|
33
|
+
return Array.from({ length }, () => "");
|
|
34
|
+
}
|
|
35
|
+
function resizeValues(values, length) {
|
|
36
|
+
return Array.from({ length }, (_, i) => values.at(i) ?? "");
|
|
37
|
+
}
|
|
38
|
+
function replaceAt(values, index, value) {
|
|
39
|
+
return values.map((slot, i) => i === index ? value : slot);
|
|
40
|
+
}
|
|
41
|
+
function focusSlot(refs, index) {
|
|
42
|
+
if (index < 0) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
refs.at(index)?.current?.focus();
|
|
46
|
+
}
|
|
47
|
+
function deferComplete(ref, next) {
|
|
48
|
+
if (!next.every((value) => value !== "")) {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const code = next.join("");
|
|
52
|
+
void Promise.resolve().then(() => {
|
|
53
|
+
ref.current?.(code);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
function applyChange(ctx, index, rawValue) {
|
|
57
|
+
if (rawValue.length > 1) {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (rawValue !== "" && !isValidChar(rawValue, ctx.type)) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const char = normalizeChar(rawValue, ctx.type);
|
|
64
|
+
const next = replaceAt(ctx.values, index, char);
|
|
65
|
+
ctx.setValues(next);
|
|
66
|
+
if (char !== "") {
|
|
67
|
+
ctx.focus(index + 1);
|
|
68
|
+
}
|
|
69
|
+
ctx.complete(next);
|
|
70
|
+
}
|
|
71
|
+
function applyKeyDown(ctx, index, key) {
|
|
72
|
+
if (key === "Backspace" && ctx.values.at(index) === "" && index > 0) {
|
|
73
|
+
ctx.setValues(replaceAt(ctx.values, index - 1, ""));
|
|
74
|
+
ctx.focus(index - 1);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (key === "ArrowLeft") {
|
|
78
|
+
ctx.focus(index - 1);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (key === "ArrowRight") {
|
|
82
|
+
ctx.focus(index + 1);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function applyPaste(ctx, text) {
|
|
86
|
+
const cleaned = ctx.sanitizeOnPaste ? text.replace(/[\s-]+/g, "") : text;
|
|
87
|
+
const filled = filterValid(cleaned, ctx.type).slice(0, ctx.length);
|
|
88
|
+
const next = Array.from({ length: ctx.length }, (_, i) => filled.charAt(i));
|
|
89
|
+
ctx.setValues(next);
|
|
90
|
+
ctx.focus(filled.length - 1);
|
|
91
|
+
ctx.complete(next);
|
|
92
|
+
}
|
|
93
|
+
function handlePaste(ctx, event) {
|
|
94
|
+
event.preventDefault();
|
|
95
|
+
applyPaste(ctx, event.clipboardData.getData("text"));
|
|
96
|
+
}
|
|
97
|
+
function buildHandlers(ctx) {
|
|
98
|
+
return {
|
|
99
|
+
onChange: (index) => (event) => applyChange(ctx, index, event.target.value),
|
|
100
|
+
onKeyDown: (index) => (event) => applyKeyDown(ctx, index, event.key),
|
|
101
|
+
onPaste: (event) => handlePaste(ctx, event)
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function useSlotValues(length, complete) {
|
|
105
|
+
const [values, setValues] = react.useState(() => makeEmptyValues(length));
|
|
106
|
+
const valuesRef = react.useRef(values);
|
|
107
|
+
valuesRef.current = values;
|
|
108
|
+
react.useEffect(() => {
|
|
109
|
+
setValues((prev) => prev.length === length ? prev : resizeValues(prev, length));
|
|
110
|
+
}, [length]);
|
|
111
|
+
const setValue = react.useCallback(
|
|
112
|
+
(index, value) => {
|
|
113
|
+
const next = replaceAt(valuesRef.current, index, value);
|
|
114
|
+
valuesRef.current = next;
|
|
115
|
+
setValues(next);
|
|
116
|
+
complete(next);
|
|
117
|
+
},
|
|
118
|
+
[complete]
|
|
119
|
+
);
|
|
120
|
+
return [values, setValues, setValue];
|
|
121
|
+
}
|
|
122
|
+
function useOtpInput(options = {}) {
|
|
123
|
+
const {
|
|
124
|
+
length = DEFAULT_LENGTH,
|
|
125
|
+
type = "numeric",
|
|
126
|
+
autoSubmit = true,
|
|
127
|
+
// Stryker disable next-line BooleanLiteral: flipping this default to `false` is equivalent — `sanitizeOnPaste` only strips `[\s-]` before `filterValid`, and `filterValid` already drops every non-charset character (whitespace and `-` are never in numeric/alpha/alphanumeric), so the sanitized and unsanitized paths yield identical slot values.
|
|
128
|
+
sanitizeOnPaste = true,
|
|
129
|
+
onComplete
|
|
130
|
+
} = options;
|
|
131
|
+
const refs = react.useMemo(() => Array.from({ length }, () => ({ current: null })), [length]);
|
|
132
|
+
const onCompleteRef = react.useRef(onComplete);
|
|
133
|
+
onCompleteRef.current = onComplete;
|
|
134
|
+
const focus = react.useCallback((index) => focusSlot(refs, index), [refs]);
|
|
135
|
+
const complete = react.useCallback(
|
|
136
|
+
(next) => {
|
|
137
|
+
if (autoSubmit) {
|
|
138
|
+
deferComplete(onCompleteRef, next);
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
[autoSubmit]
|
|
142
|
+
);
|
|
143
|
+
const [values, setValues, setValue] = useSlotValues(length, complete);
|
|
144
|
+
const reset = react.useCallback(() => {
|
|
145
|
+
setValues(makeEmptyValues(length));
|
|
146
|
+
focus(0);
|
|
147
|
+
}, [length, focus, setValues]);
|
|
148
|
+
const handlers = react.useMemo(
|
|
149
|
+
() => buildHandlers({ values, type, length, sanitizeOnPaste, setValues, focus, complete }),
|
|
150
|
+
[values, type, length, sanitizeOnPaste, focus, complete]
|
|
151
|
+
);
|
|
152
|
+
return {
|
|
153
|
+
values,
|
|
154
|
+
setValue,
|
|
155
|
+
...handlers,
|
|
156
|
+
refs,
|
|
157
|
+
reset,
|
|
158
|
+
code: values.join(""),
|
|
159
|
+
isComplete: values.every((value) => value !== "")
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
var MS_PER_SECOND = 1e3;
|
|
163
|
+
var DEFAULT_TICK_MS = MS_PER_SECOND;
|
|
164
|
+
var SECONDS_PER_MINUTE = 60;
|
|
165
|
+
var SECONDS_PER_HOUR = 3600;
|
|
166
|
+
function computeRemaining(expiresAt) {
|
|
167
|
+
if (expiresAt === null) {
|
|
168
|
+
return 0;
|
|
169
|
+
}
|
|
170
|
+
return Math.max(0, Math.floor((expiresAt - Date.now()) / MS_PER_SECOND));
|
|
171
|
+
}
|
|
172
|
+
function pad2(value) {
|
|
173
|
+
return value.toString().padStart(2, "0");
|
|
174
|
+
}
|
|
175
|
+
function formatTime(totalSeconds) {
|
|
176
|
+
if (totalSeconds <= 0) {
|
|
177
|
+
return "00:00";
|
|
178
|
+
}
|
|
179
|
+
const hours = Math.floor(totalSeconds / SECONDS_PER_HOUR);
|
|
180
|
+
const minutes = Math.floor(totalSeconds % SECONDS_PER_HOUR / SECONDS_PER_MINUTE);
|
|
181
|
+
const seconds = totalSeconds % SECONDS_PER_MINUTE;
|
|
182
|
+
if (hours > 0) {
|
|
183
|
+
return `${pad2(hours)}:${pad2(minutes)}:${pad2(seconds)}`;
|
|
184
|
+
}
|
|
185
|
+
return `${pad2(minutes)}:${pad2(seconds)}`;
|
|
186
|
+
}
|
|
187
|
+
function useOtpCountdown(options) {
|
|
188
|
+
const { expiresAt, tickIntervalMs = DEFAULT_TICK_MS, onExpired } = options;
|
|
189
|
+
const [remainingSeconds, setRemainingSeconds] = react.useState(
|
|
190
|
+
() => computeRemaining(expiresAt)
|
|
191
|
+
);
|
|
192
|
+
const onExpiredRef = react.useRef(onExpired);
|
|
193
|
+
onExpiredRef.current = onExpired;
|
|
194
|
+
react.useEffect(() => {
|
|
195
|
+
if (expiresAt === null) {
|
|
196
|
+
setRemainingSeconds(0);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
const initial = computeRemaining(expiresAt);
|
|
200
|
+
setRemainingSeconds(initial);
|
|
201
|
+
if (initial === 0) {
|
|
202
|
+
onExpiredRef.current?.();
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const interval = setInterval(() => {
|
|
206
|
+
const remaining = computeRemaining(expiresAt);
|
|
207
|
+
setRemainingSeconds(remaining);
|
|
208
|
+
if (remaining === 0) {
|
|
209
|
+
clearInterval(interval);
|
|
210
|
+
onExpiredRef.current?.();
|
|
211
|
+
}
|
|
212
|
+
}, tickIntervalMs);
|
|
213
|
+
return () => {
|
|
214
|
+
clearInterval(interval);
|
|
215
|
+
};
|
|
216
|
+
}, [expiresAt, tickIntervalMs]);
|
|
217
|
+
return {
|
|
218
|
+
remainingSeconds,
|
|
219
|
+
expired: remainingSeconds === 0,
|
|
220
|
+
formatted: formatTime(remainingSeconds)
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
exports.useOtpCountdown = useOtpCountdown;
|
|
225
|
+
exports.useOtpInput = useOtpInput;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { ChangeEvent, KeyboardEvent, ClipboardEvent, RefObject } from 'react';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Public types for the React subpath (`@bymax-one/nest-notification/react`).
|
|
5
|
+
* @layer api
|
|
6
|
+
*
|
|
7
|
+
* Option and state shapes for the browser-targeted OTP hooks. These are pure
|
|
8
|
+
* type declarations — no runtime code, no `react` runtime import — so the
|
|
9
|
+
* subpath stays state/UX-only and never reaches for an HTTP client or a Node
|
|
10
|
+
* builtin. Only the React event/ref *types* are referenced, erased at build.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Character class a slot accepts: digits, letters, or both. */
|
|
14
|
+
type OtpInputType = 'numeric' | 'alpha' | 'alphanumeric';
|
|
15
|
+
/** Options for {@link useOtpInput}. All fields are optional with sensible defaults. */
|
|
16
|
+
interface UseOtpInputOptions {
|
|
17
|
+
/** Number of single-character slots. Default: `6`. */
|
|
18
|
+
length?: number;
|
|
19
|
+
/** Accepted character class per slot. Default: `'numeric'`. */
|
|
20
|
+
type?: OtpInputType;
|
|
21
|
+
/** Invoked (deferred to a microtask) once every slot is filled. */
|
|
22
|
+
onComplete?: (code: string) => void | Promise<void>;
|
|
23
|
+
/** Whether a full code auto-fires {@link UseOtpInputOptions.onComplete}. Default: `true`. */
|
|
24
|
+
autoSubmit?: boolean;
|
|
25
|
+
/** Whether paste input has spaces and hyphens stripped before distribution. Default: `true`. */
|
|
26
|
+
sanitizeOnPaste?: boolean;
|
|
27
|
+
}
|
|
28
|
+
/** Reactive state and handlers returned by {@link useOtpInput}. */
|
|
29
|
+
interface UseOtpInputState {
|
|
30
|
+
/** Current value of each slot (one character per slot, `''` when empty). */
|
|
31
|
+
values: string[];
|
|
32
|
+
/** Imperatively set a single slot's raw value. */
|
|
33
|
+
setValue: (index: number, value: string) => void;
|
|
34
|
+
/** Per-slot change handler — attach to each input's `onChange`. */
|
|
35
|
+
onChange: (index: number) => (event: ChangeEvent<HTMLInputElement>) => void;
|
|
36
|
+
/** Per-slot keydown handler — drives Backspace clear and Arrow navigation. */
|
|
37
|
+
onKeyDown: (index: number) => (event: KeyboardEvent<HTMLInputElement>) => void;
|
|
38
|
+
/** Paste handler — distributes the clipboard across slots. Attach to the FIRST input only. */
|
|
39
|
+
onPaste: (event: ClipboardEvent<HTMLInputElement>) => void;
|
|
40
|
+
/** Stable ref objects — spread onto each input as `ref={refs[i]}`. */
|
|
41
|
+
refs: ReadonlyArray<RefObject<HTMLInputElement | null>>;
|
|
42
|
+
/** Clear every slot and move focus back to the first slot. */
|
|
43
|
+
reset: () => void;
|
|
44
|
+
/** The slots joined into a single string. */
|
|
45
|
+
code: string;
|
|
46
|
+
/** Whether every slot is filled. */
|
|
47
|
+
isComplete: boolean;
|
|
48
|
+
}
|
|
49
|
+
/** Options for {@link useOtpCountdown}. */
|
|
50
|
+
interface UseOtpCountdownOptions {
|
|
51
|
+
/** Unix epoch milliseconds of expiry, or `null` to disable the countdown. */
|
|
52
|
+
expiresAt: number | null;
|
|
53
|
+
/** Recompute interval in milliseconds. Default: `1000`. */
|
|
54
|
+
tickIntervalMs?: number;
|
|
55
|
+
/** Invoked once when the countdown first reaches zero. */
|
|
56
|
+
onExpired?: () => void;
|
|
57
|
+
}
|
|
58
|
+
/** Reactive state returned by {@link useOtpCountdown}. */
|
|
59
|
+
interface UseOtpCountdownState {
|
|
60
|
+
/** Whole seconds remaining until expiry (never negative). */
|
|
61
|
+
remainingSeconds: number;
|
|
62
|
+
/** Whether the countdown has reached zero. */
|
|
63
|
+
expired: boolean;
|
|
64
|
+
/** Remaining time as `MM:SS` (under one hour) or `HH:MM:SS` (one hour or more). */
|
|
65
|
+
formatted: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* @fileoverview `useOtpInput` — multi-slot OTP entry state and UX for React.
|
|
70
|
+
* @layer api
|
|
71
|
+
*
|
|
72
|
+
* Manages N single-character inputs: per-character validation, auto-advance,
|
|
73
|
+
* Backspace/Arrow navigation, and clipboard distribution. State and UX only —
|
|
74
|
+
* the hook never performs network I/O; verifying the code is the consumer's job.
|
|
75
|
+
* `react` is an optional peer dependency, external in the published bundle.
|
|
76
|
+
*/
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Hook that manages an N-slot OTP input with auto-focus, paste distribution, and
|
|
80
|
+
* Backspace/Arrow navigation.
|
|
81
|
+
*
|
|
82
|
+
* @param options - Length, character class, completion callback, and UX toggles.
|
|
83
|
+
* @returns Slot values, event handlers, stable input refs, and derived state.
|
|
84
|
+
*/
|
|
85
|
+
declare function useOtpInput(options?: UseOtpInputOptions): UseOtpInputState;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* @fileoverview `useOtpCountdown` — reactive countdown to an OTP expiry.
|
|
89
|
+
* @layer api
|
|
90
|
+
*
|
|
91
|
+
* Recomputes the seconds remaining until `expiresAt` on a fixed tick, fires a
|
|
92
|
+
* one-shot `onExpired` callback at zero, and formats the remainder as `MM:SS`
|
|
93
|
+
* (or `HH:MM:SS` past one hour). State only — no network I/O. `react` is an
|
|
94
|
+
* optional peer dependency, external in the published bundle.
|
|
95
|
+
*/
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Hook that exposes a live countdown to `expiresAt`.
|
|
99
|
+
*
|
|
100
|
+
* @param options - Expiry timestamp, tick cadence, and optional expiry callback.
|
|
101
|
+
* @returns Remaining seconds, an `expired` flag, and the formatted remainder.
|
|
102
|
+
*/
|
|
103
|
+
declare function useOtpCountdown(options: UseOtpCountdownOptions): UseOtpCountdownState;
|
|
104
|
+
|
|
105
|
+
export { type OtpInputType, type UseOtpCountdownOptions, type UseOtpCountdownState, type UseOtpInputOptions, type UseOtpInputState, useOtpCountdown, useOtpInput };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { ChangeEvent, KeyboardEvent, ClipboardEvent, RefObject } from 'react';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Public types for the React subpath (`@bymax-one/nest-notification/react`).
|
|
5
|
+
* @layer api
|
|
6
|
+
*
|
|
7
|
+
* Option and state shapes for the browser-targeted OTP hooks. These are pure
|
|
8
|
+
* type declarations — no runtime code, no `react` runtime import — so the
|
|
9
|
+
* subpath stays state/UX-only and never reaches for an HTTP client or a Node
|
|
10
|
+
* builtin. Only the React event/ref *types* are referenced, erased at build.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Character class a slot accepts: digits, letters, or both. */
|
|
14
|
+
type OtpInputType = 'numeric' | 'alpha' | 'alphanumeric';
|
|
15
|
+
/** Options for {@link useOtpInput}. All fields are optional with sensible defaults. */
|
|
16
|
+
interface UseOtpInputOptions {
|
|
17
|
+
/** Number of single-character slots. Default: `6`. */
|
|
18
|
+
length?: number;
|
|
19
|
+
/** Accepted character class per slot. Default: `'numeric'`. */
|
|
20
|
+
type?: OtpInputType;
|
|
21
|
+
/** Invoked (deferred to a microtask) once every slot is filled. */
|
|
22
|
+
onComplete?: (code: string) => void | Promise<void>;
|
|
23
|
+
/** Whether a full code auto-fires {@link UseOtpInputOptions.onComplete}. Default: `true`. */
|
|
24
|
+
autoSubmit?: boolean;
|
|
25
|
+
/** Whether paste input has spaces and hyphens stripped before distribution. Default: `true`. */
|
|
26
|
+
sanitizeOnPaste?: boolean;
|
|
27
|
+
}
|
|
28
|
+
/** Reactive state and handlers returned by {@link useOtpInput}. */
|
|
29
|
+
interface UseOtpInputState {
|
|
30
|
+
/** Current value of each slot (one character per slot, `''` when empty). */
|
|
31
|
+
values: string[];
|
|
32
|
+
/** Imperatively set a single slot's raw value. */
|
|
33
|
+
setValue: (index: number, value: string) => void;
|
|
34
|
+
/** Per-slot change handler — attach to each input's `onChange`. */
|
|
35
|
+
onChange: (index: number) => (event: ChangeEvent<HTMLInputElement>) => void;
|
|
36
|
+
/** Per-slot keydown handler — drives Backspace clear and Arrow navigation. */
|
|
37
|
+
onKeyDown: (index: number) => (event: KeyboardEvent<HTMLInputElement>) => void;
|
|
38
|
+
/** Paste handler — distributes the clipboard across slots. Attach to the FIRST input only. */
|
|
39
|
+
onPaste: (event: ClipboardEvent<HTMLInputElement>) => void;
|
|
40
|
+
/** Stable ref objects — spread onto each input as `ref={refs[i]}`. */
|
|
41
|
+
refs: ReadonlyArray<RefObject<HTMLInputElement | null>>;
|
|
42
|
+
/** Clear every slot and move focus back to the first slot. */
|
|
43
|
+
reset: () => void;
|
|
44
|
+
/** The slots joined into a single string. */
|
|
45
|
+
code: string;
|
|
46
|
+
/** Whether every slot is filled. */
|
|
47
|
+
isComplete: boolean;
|
|
48
|
+
}
|
|
49
|
+
/** Options for {@link useOtpCountdown}. */
|
|
50
|
+
interface UseOtpCountdownOptions {
|
|
51
|
+
/** Unix epoch milliseconds of expiry, or `null` to disable the countdown. */
|
|
52
|
+
expiresAt: number | null;
|
|
53
|
+
/** Recompute interval in milliseconds. Default: `1000`. */
|
|
54
|
+
tickIntervalMs?: number;
|
|
55
|
+
/** Invoked once when the countdown first reaches zero. */
|
|
56
|
+
onExpired?: () => void;
|
|
57
|
+
}
|
|
58
|
+
/** Reactive state returned by {@link useOtpCountdown}. */
|
|
59
|
+
interface UseOtpCountdownState {
|
|
60
|
+
/** Whole seconds remaining until expiry (never negative). */
|
|
61
|
+
remainingSeconds: number;
|
|
62
|
+
/** Whether the countdown has reached zero. */
|
|
63
|
+
expired: boolean;
|
|
64
|
+
/** Remaining time as `MM:SS` (under one hour) or `HH:MM:SS` (one hour or more). */
|
|
65
|
+
formatted: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* @fileoverview `useOtpInput` — multi-slot OTP entry state and UX for React.
|
|
70
|
+
* @layer api
|
|
71
|
+
*
|
|
72
|
+
* Manages N single-character inputs: per-character validation, auto-advance,
|
|
73
|
+
* Backspace/Arrow navigation, and clipboard distribution. State and UX only —
|
|
74
|
+
* the hook never performs network I/O; verifying the code is the consumer's job.
|
|
75
|
+
* `react` is an optional peer dependency, external in the published bundle.
|
|
76
|
+
*/
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Hook that manages an N-slot OTP input with auto-focus, paste distribution, and
|
|
80
|
+
* Backspace/Arrow navigation.
|
|
81
|
+
*
|
|
82
|
+
* @param options - Length, character class, completion callback, and UX toggles.
|
|
83
|
+
* @returns Slot values, event handlers, stable input refs, and derived state.
|
|
84
|
+
*/
|
|
85
|
+
declare function useOtpInput(options?: UseOtpInputOptions): UseOtpInputState;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* @fileoverview `useOtpCountdown` — reactive countdown to an OTP expiry.
|
|
89
|
+
* @layer api
|
|
90
|
+
*
|
|
91
|
+
* Recomputes the seconds remaining until `expiresAt` on a fixed tick, fires a
|
|
92
|
+
* one-shot `onExpired` callback at zero, and formats the remainder as `MM:SS`
|
|
93
|
+
* (or `HH:MM:SS` past one hour). State only — no network I/O. `react` is an
|
|
94
|
+
* optional peer dependency, external in the published bundle.
|
|
95
|
+
*/
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Hook that exposes a live countdown to `expiresAt`.
|
|
99
|
+
*
|
|
100
|
+
* @param options - Expiry timestamp, tick cadence, and optional expiry callback.
|
|
101
|
+
* @returns Remaining seconds, an `expired` flag, and the formatted remainder.
|
|
102
|
+
*/
|
|
103
|
+
declare function useOtpCountdown(options: UseOtpCountdownOptions): UseOtpCountdownState;
|
|
104
|
+
|
|
105
|
+
export { type OtpInputType, type UseOtpCountdownOptions, type UseOtpCountdownState, type UseOtpInputOptions, type UseOtpInputState, useOtpCountdown, useOtpInput };
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { useMemo, useRef, useCallback, useState, useEffect } from 'react';
|
|
2
|
+
|
|
3
|
+
// src/react/useOtpInput.ts
|
|
4
|
+
var DEFAULT_LENGTH = 6;
|
|
5
|
+
function charPattern(type) {
|
|
6
|
+
switch (type) {
|
|
7
|
+
case "alpha":
|
|
8
|
+
return /^[A-Za-z]$/;
|
|
9
|
+
case "alphanumeric":
|
|
10
|
+
return /^[A-Za-z0-9]$/;
|
|
11
|
+
default:
|
|
12
|
+
return /^[0-9]$/;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function isValidChar(char, type) {
|
|
16
|
+
return charPattern(type).test(char);
|
|
17
|
+
}
|
|
18
|
+
function normalizeChar(char, type) {
|
|
19
|
+
return type === "numeric" ? char : char.toUpperCase();
|
|
20
|
+
}
|
|
21
|
+
function filterValid(input, type) {
|
|
22
|
+
let result = "";
|
|
23
|
+
for (const char of input) {
|
|
24
|
+
if (isValidChar(char, type)) {
|
|
25
|
+
result += normalizeChar(char, type);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return result;
|
|
29
|
+
}
|
|
30
|
+
function makeEmptyValues(length) {
|
|
31
|
+
return Array.from({ length }, () => "");
|
|
32
|
+
}
|
|
33
|
+
function resizeValues(values, length) {
|
|
34
|
+
return Array.from({ length }, (_, i) => values.at(i) ?? "");
|
|
35
|
+
}
|
|
36
|
+
function replaceAt(values, index, value) {
|
|
37
|
+
return values.map((slot, i) => i === index ? value : slot);
|
|
38
|
+
}
|
|
39
|
+
function focusSlot(refs, index) {
|
|
40
|
+
if (index < 0) {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
refs.at(index)?.current?.focus();
|
|
44
|
+
}
|
|
45
|
+
function deferComplete(ref, next) {
|
|
46
|
+
if (!next.every((value) => value !== "")) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const code = next.join("");
|
|
50
|
+
void Promise.resolve().then(() => {
|
|
51
|
+
ref.current?.(code);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
function applyChange(ctx, index, rawValue) {
|
|
55
|
+
if (rawValue.length > 1) {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (rawValue !== "" && !isValidChar(rawValue, ctx.type)) {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const char = normalizeChar(rawValue, ctx.type);
|
|
62
|
+
const next = replaceAt(ctx.values, index, char);
|
|
63
|
+
ctx.setValues(next);
|
|
64
|
+
if (char !== "") {
|
|
65
|
+
ctx.focus(index + 1);
|
|
66
|
+
}
|
|
67
|
+
ctx.complete(next);
|
|
68
|
+
}
|
|
69
|
+
function applyKeyDown(ctx, index, key) {
|
|
70
|
+
if (key === "Backspace" && ctx.values.at(index) === "" && index > 0) {
|
|
71
|
+
ctx.setValues(replaceAt(ctx.values, index - 1, ""));
|
|
72
|
+
ctx.focus(index - 1);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (key === "ArrowLeft") {
|
|
76
|
+
ctx.focus(index - 1);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (key === "ArrowRight") {
|
|
80
|
+
ctx.focus(index + 1);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function applyPaste(ctx, text) {
|
|
84
|
+
const cleaned = ctx.sanitizeOnPaste ? text.replace(/[\s-]+/g, "") : text;
|
|
85
|
+
const filled = filterValid(cleaned, ctx.type).slice(0, ctx.length);
|
|
86
|
+
const next = Array.from({ length: ctx.length }, (_, i) => filled.charAt(i));
|
|
87
|
+
ctx.setValues(next);
|
|
88
|
+
ctx.focus(filled.length - 1);
|
|
89
|
+
ctx.complete(next);
|
|
90
|
+
}
|
|
91
|
+
function handlePaste(ctx, event) {
|
|
92
|
+
event.preventDefault();
|
|
93
|
+
applyPaste(ctx, event.clipboardData.getData("text"));
|
|
94
|
+
}
|
|
95
|
+
function buildHandlers(ctx) {
|
|
96
|
+
return {
|
|
97
|
+
onChange: (index) => (event) => applyChange(ctx, index, event.target.value),
|
|
98
|
+
onKeyDown: (index) => (event) => applyKeyDown(ctx, index, event.key),
|
|
99
|
+
onPaste: (event) => handlePaste(ctx, event)
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function useSlotValues(length, complete) {
|
|
103
|
+
const [values, setValues] = useState(() => makeEmptyValues(length));
|
|
104
|
+
const valuesRef = useRef(values);
|
|
105
|
+
valuesRef.current = values;
|
|
106
|
+
useEffect(() => {
|
|
107
|
+
setValues((prev) => prev.length === length ? prev : resizeValues(prev, length));
|
|
108
|
+
}, [length]);
|
|
109
|
+
const setValue = useCallback(
|
|
110
|
+
(index, value) => {
|
|
111
|
+
const next = replaceAt(valuesRef.current, index, value);
|
|
112
|
+
valuesRef.current = next;
|
|
113
|
+
setValues(next);
|
|
114
|
+
complete(next);
|
|
115
|
+
},
|
|
116
|
+
[complete]
|
|
117
|
+
);
|
|
118
|
+
return [values, setValues, setValue];
|
|
119
|
+
}
|
|
120
|
+
function useOtpInput(options = {}) {
|
|
121
|
+
const {
|
|
122
|
+
length = DEFAULT_LENGTH,
|
|
123
|
+
type = "numeric",
|
|
124
|
+
autoSubmit = true,
|
|
125
|
+
// Stryker disable next-line BooleanLiteral: flipping this default to `false` is equivalent — `sanitizeOnPaste` only strips `[\s-]` before `filterValid`, and `filterValid` already drops every non-charset character (whitespace and `-` are never in numeric/alpha/alphanumeric), so the sanitized and unsanitized paths yield identical slot values.
|
|
126
|
+
sanitizeOnPaste = true,
|
|
127
|
+
onComplete
|
|
128
|
+
} = options;
|
|
129
|
+
const refs = useMemo(() => Array.from({ length }, () => ({ current: null })), [length]);
|
|
130
|
+
const onCompleteRef = useRef(onComplete);
|
|
131
|
+
onCompleteRef.current = onComplete;
|
|
132
|
+
const focus = useCallback((index) => focusSlot(refs, index), [refs]);
|
|
133
|
+
const complete = useCallback(
|
|
134
|
+
(next) => {
|
|
135
|
+
if (autoSubmit) {
|
|
136
|
+
deferComplete(onCompleteRef, next);
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
[autoSubmit]
|
|
140
|
+
);
|
|
141
|
+
const [values, setValues, setValue] = useSlotValues(length, complete);
|
|
142
|
+
const reset = useCallback(() => {
|
|
143
|
+
setValues(makeEmptyValues(length));
|
|
144
|
+
focus(0);
|
|
145
|
+
}, [length, focus, setValues]);
|
|
146
|
+
const handlers = useMemo(
|
|
147
|
+
() => buildHandlers({ values, type, length, sanitizeOnPaste, setValues, focus, complete }),
|
|
148
|
+
[values, type, length, sanitizeOnPaste, focus, complete]
|
|
149
|
+
);
|
|
150
|
+
return {
|
|
151
|
+
values,
|
|
152
|
+
setValue,
|
|
153
|
+
...handlers,
|
|
154
|
+
refs,
|
|
155
|
+
reset,
|
|
156
|
+
code: values.join(""),
|
|
157
|
+
isComplete: values.every((value) => value !== "")
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
var MS_PER_SECOND = 1e3;
|
|
161
|
+
var DEFAULT_TICK_MS = MS_PER_SECOND;
|
|
162
|
+
var SECONDS_PER_MINUTE = 60;
|
|
163
|
+
var SECONDS_PER_HOUR = 3600;
|
|
164
|
+
function computeRemaining(expiresAt) {
|
|
165
|
+
if (expiresAt === null) {
|
|
166
|
+
return 0;
|
|
167
|
+
}
|
|
168
|
+
return Math.max(0, Math.floor((expiresAt - Date.now()) / MS_PER_SECOND));
|
|
169
|
+
}
|
|
170
|
+
function pad2(value) {
|
|
171
|
+
return value.toString().padStart(2, "0");
|
|
172
|
+
}
|
|
173
|
+
function formatTime(totalSeconds) {
|
|
174
|
+
if (totalSeconds <= 0) {
|
|
175
|
+
return "00:00";
|
|
176
|
+
}
|
|
177
|
+
const hours = Math.floor(totalSeconds / SECONDS_PER_HOUR);
|
|
178
|
+
const minutes = Math.floor(totalSeconds % SECONDS_PER_HOUR / SECONDS_PER_MINUTE);
|
|
179
|
+
const seconds = totalSeconds % SECONDS_PER_MINUTE;
|
|
180
|
+
if (hours > 0) {
|
|
181
|
+
return `${pad2(hours)}:${pad2(minutes)}:${pad2(seconds)}`;
|
|
182
|
+
}
|
|
183
|
+
return `${pad2(minutes)}:${pad2(seconds)}`;
|
|
184
|
+
}
|
|
185
|
+
function useOtpCountdown(options) {
|
|
186
|
+
const { expiresAt, tickIntervalMs = DEFAULT_TICK_MS, onExpired } = options;
|
|
187
|
+
const [remainingSeconds, setRemainingSeconds] = useState(
|
|
188
|
+
() => computeRemaining(expiresAt)
|
|
189
|
+
);
|
|
190
|
+
const onExpiredRef = useRef(onExpired);
|
|
191
|
+
onExpiredRef.current = onExpired;
|
|
192
|
+
useEffect(() => {
|
|
193
|
+
if (expiresAt === null) {
|
|
194
|
+
setRemainingSeconds(0);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const initial = computeRemaining(expiresAt);
|
|
198
|
+
setRemainingSeconds(initial);
|
|
199
|
+
if (initial === 0) {
|
|
200
|
+
onExpiredRef.current?.();
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const interval = setInterval(() => {
|
|
204
|
+
const remaining = computeRemaining(expiresAt);
|
|
205
|
+
setRemainingSeconds(remaining);
|
|
206
|
+
if (remaining === 0) {
|
|
207
|
+
clearInterval(interval);
|
|
208
|
+
onExpiredRef.current?.();
|
|
209
|
+
}
|
|
210
|
+
}, tickIntervalMs);
|
|
211
|
+
return () => {
|
|
212
|
+
clearInterval(interval);
|
|
213
|
+
};
|
|
214
|
+
}, [expiresAt, tickIntervalMs]);
|
|
215
|
+
return {
|
|
216
|
+
remainingSeconds,
|
|
217
|
+
expired: remainingSeconds === 0,
|
|
218
|
+
formatted: formatTime(remainingSeconds)
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export { useOtpCountdown, useOtpInput };
|