@arun-dev/headless 4.17.0 → 4.18.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.
@@ -0,0 +1,383 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/otp-input/index.ts
21
+ var otp_input_exports = {};
22
+ __export(otp_input_exports, {
23
+ OtpInput: () => index_parts_exports
24
+ });
25
+ module.exports = __toCommonJS(otp_input_exports);
26
+
27
+ // src/otp-input/index.parts.ts
28
+ var index_parts_exports = {};
29
+ __export(index_parts_exports, {
30
+ Input: () => OtpInputInput,
31
+ Root: () => OtpInputRoot,
32
+ Slot: () => OtpInputSlot
33
+ });
34
+
35
+ // src/otp-input/OtpInputRoot.tsx
36
+ var import_react4 = require("react");
37
+
38
+ // src/core/useControlled.ts
39
+ var import_react = require("react");
40
+ function useControlled({
41
+ controlled,
42
+ default: defaultValue,
43
+ name = "Component",
44
+ state = "value"
45
+ }) {
46
+ const { current: isControlled } = (0, import_react.useRef)(controlled !== void 0);
47
+ const [uncontrolled, setUncontrolled] = (0, import_react.useState)(defaultValue);
48
+ const defaultRef = (0, import_react.useRef)(defaultValue);
49
+ const value = isControlled ? controlled : uncontrolled;
50
+ if (process.env.NODE_ENV !== "production") {
51
+ if (isControlled !== (controlled !== void 0)) {
52
+ console.error(
53
+ `${name}: cannot switch between controlled and uncontrolled \`${state}\`. Decide which one this component is for the whole of its life.`
54
+ );
55
+ }
56
+ if (!isControlled && defaultRef.current !== defaultValue) {
57
+ console.error(
58
+ `${name}: cannot change the default \`${state}\` after mount. It is only read once, so later changes are silently ignored.`
59
+ );
60
+ }
61
+ }
62
+ const setValue = (0, import_react.useCallback)(
63
+ (next) => {
64
+ if (!isControlled) setUncontrolled(next);
65
+ },
66
+ [isControlled]
67
+ );
68
+ return [value, setValue];
69
+ }
70
+
71
+ // src/core/useRender.ts
72
+ var import_react2 = require("react");
73
+
74
+ // src/core/mergeProps.ts
75
+ function isEventHandler(key) {
76
+ return key.length > 2 && key.startsWith("on") && key[2] === key[2]?.toUpperCase();
77
+ }
78
+ function mergeRefs(...refs) {
79
+ return (node) => {
80
+ const cleanups = refs.map((ref) => {
81
+ if (typeof ref === "function") {
82
+ const result = ref(node);
83
+ return typeof result === "function" ? result : () => ref(null);
84
+ }
85
+ if (ref && typeof ref === "object") {
86
+ ref.current = node;
87
+ return () => {
88
+ ref.current = null;
89
+ };
90
+ }
91
+ return void 0;
92
+ });
93
+ return () => {
94
+ cleanups.forEach((cleanup) => {
95
+ if (typeof cleanup === "function") cleanup();
96
+ });
97
+ };
98
+ };
99
+ }
100
+ function isSyntheticEvent(event) {
101
+ return typeof event === "object" && event !== null && "nativeEvent" in event;
102
+ }
103
+ function makeEventPreventable(event) {
104
+ if (Object.prototype.hasOwnProperty.call(event, "preventComponentHandler")) return;
105
+ const target = event;
106
+ target.preventComponentHandler = () => {
107
+ target.componentHandlerPrevented = true;
108
+ };
109
+ }
110
+ function isComponentHandlerPrevented(event) {
111
+ return typeof event === "object" && event !== null && event.componentHandlerPrevented === true;
112
+ }
113
+ function chainHandlers(earlier, value) {
114
+ return (...args) => {
115
+ const event = args[0];
116
+ if (isSyntheticEvent(event)) makeEventPreventable(event);
117
+ value(...args);
118
+ if (isComponentHandlerPrevented(event)) return;
119
+ earlier(...args);
120
+ };
121
+ }
122
+ function mergeProps(...objects) {
123
+ const merged = {};
124
+ for (const props of objects) {
125
+ if (!props) continue;
126
+ for (const key of Object.keys(props)) {
127
+ const value = props[key];
128
+ if (value === void 0) continue;
129
+ if (isEventHandler(key) && typeof value === "function") {
130
+ const earlier = merged[key];
131
+ merged[key] = typeof earlier === "function" ? chainHandlers(earlier, value) : value;
132
+ } else if (key === "className") {
133
+ merged.className = merged.className ? `${String(merged.className)} ${String(value)}` : value;
134
+ } else if (key === "style") {
135
+ merged.style = { ...merged.style, ...value };
136
+ } else if (key === "ref") {
137
+ merged.ref = merged.ref ? mergeRefs(merged.ref, value) : value;
138
+ } else {
139
+ merged[key] = value;
140
+ }
141
+ }
142
+ }
143
+ return merged;
144
+ }
145
+
146
+ // src/core/useRender.ts
147
+ function useRender({
148
+ render,
149
+ defaultTagName,
150
+ props,
151
+ consumerProps
152
+ }) {
153
+ const merged = mergeProps(props, consumerProps);
154
+ if ((0, import_react2.isValidElement)(render)) {
155
+ return (0, import_react2.cloneElement)(render, mergeProps(merged, render.props));
156
+ }
157
+ return (0, import_react2.createElement)(defaultTagName, merged);
158
+ }
159
+
160
+ // src/otp-input/OtpInputRootContext.ts
161
+ var import_react3 = require("react");
162
+ var OtpInputRootContext = (0, import_react3.createContext)(null);
163
+ function useOtpInputRootContext(part) {
164
+ const context = (0, import_react3.useContext)(OtpInputRootContext);
165
+ if (context === null) {
166
+ throw new Error(`<OtpInput.${part}> must be rendered inside <OtpInput.Root>.`);
167
+ }
168
+ return context;
169
+ }
170
+ function sanitize(text, validationType) {
171
+ return validationType === "numeric" ? text.replace(/\D/g, "") : text.replace(/[^A-Za-z0-9]/g, "");
172
+ }
173
+ function otpInputDataAttributes({ value, length, disabled }) {
174
+ return {
175
+ "data-complete": value.length === length ? "" : void 0,
176
+ "data-disabled": disabled ? "" : void 0
177
+ };
178
+ }
179
+
180
+ // src/otp-input/OtpInputRoot.tsx
181
+ var import_jsx_runtime = require("react/jsx-runtime");
182
+ function OtpInputRoot({
183
+ value: valueProp,
184
+ defaultValue,
185
+ onValueChange,
186
+ length = 6,
187
+ validationType = "numeric",
188
+ disabled = false,
189
+ className,
190
+ children,
191
+ render,
192
+ ...rest
193
+ }) {
194
+ const [value, setValue] = useControlled({
195
+ controlled: valueProp,
196
+ default: defaultValue ?? "",
197
+ name: "OtpInput.Root",
198
+ state: "value"
199
+ });
200
+ const commit = (0, import_react4.useCallback)(
201
+ (next) => {
202
+ const clean = sanitize(next, validationType).slice(0, length);
203
+ if (clean === value) return;
204
+ setValue(clean);
205
+ onValueChange?.(clean);
206
+ },
207
+ [validationType, length, value, setValue, onValueChange]
208
+ );
209
+ const [selection, setSelection] = (0, import_react4.useState)(null);
210
+ const inputRef = (0, import_react4.useRef)(null);
211
+ const slotsRef = (0, import_react4.useRef)(/* @__PURE__ */ new Map());
212
+ const registerSlot = (0, import_react4.useCallback)((index, element2) => {
213
+ if (element2) slotsRef.current.set(index, element2);
214
+ else slotsRef.current.delete(index);
215
+ }, []);
216
+ const slotAt = (0, import_react4.useCallback)((clientX) => {
217
+ let nearest = null;
218
+ let distance = Infinity;
219
+ for (const [index, element2] of slotsRef.current) {
220
+ const rect = element2.getBoundingClientRect();
221
+ const d = clientX < rect.left ? rect.left - clientX : clientX > rect.right ? clientX - rect.right : 0;
222
+ if (d < distance) {
223
+ distance = d;
224
+ nearest = index;
225
+ }
226
+ }
227
+ return nearest;
228
+ }, []);
229
+ const { current: initialValue } = (0, import_react4.useRef)(value);
230
+ (0, import_react4.useEffect)(() => {
231
+ const form = inputRef.current?.form;
232
+ if (!form) return;
233
+ function onReset(event) {
234
+ queueMicrotask(() => {
235
+ if (!event.defaultPrevented) commit(initialValue);
236
+ });
237
+ }
238
+ form.addEventListener("reset", onReset);
239
+ return () => form.removeEventListener("reset", onReset);
240
+ }, [commit, initialValue]);
241
+ const context = (0, import_react4.useMemo)(
242
+ () => ({
243
+ value,
244
+ length,
245
+ disabled,
246
+ validationType,
247
+ selection,
248
+ setSelection,
249
+ commit,
250
+ inputRef,
251
+ registerSlot,
252
+ slotAt
253
+ }),
254
+ [value, length, disabled, validationType, selection, commit, registerSlot, slotAt]
255
+ );
256
+ const element = useRender({
257
+ render,
258
+ defaultTagName: "div",
259
+ props: {
260
+ ...otpInputDataAttributes({ value, length, disabled }),
261
+ className,
262
+ children
263
+ },
264
+ consumerProps: rest
265
+ });
266
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(OtpInputRootContext.Provider, { value: context, children: element });
267
+ }
268
+
269
+ // src/otp-input/OtpInputInput.tsx
270
+ function OtpInputInput({ render, ...rest }) {
271
+ const { value, length, disabled, validationType, setSelection, commit, inputRef, slotAt } = useOtpInputRootContext("Input");
272
+ function select(input, index) {
273
+ const filled = input.value.length;
274
+ const at = Math.max(0, Math.min(index, filled, length - 1));
275
+ if (at < filled) input.setSelectionRange(at, at + 1);
276
+ else input.setSelectionRange(filled, filled);
277
+ report(input);
278
+ }
279
+ function report(input) {
280
+ setSelection({ start: input.selectionStart ?? 0, end: input.selectionEnd ?? 0 });
281
+ }
282
+ function syncSelection(event) {
283
+ const input = event.currentTarget;
284
+ const start = input.selectionStart ?? 0;
285
+ const end = input.selectionEnd ?? start;
286
+ if (start === end && (start < input.value.length || start >= length)) select(input, start);
287
+ else report(input);
288
+ }
289
+ return useRender({
290
+ render,
291
+ defaultTagName: "input",
292
+ props: {
293
+ ref: inputRef,
294
+ type: "text",
295
+ value,
296
+ inputMode: validationType === "numeric" ? "numeric" : "text",
297
+ autoComplete: "one-time-code",
298
+ autoCapitalize: "off",
299
+ autoCorrect: "off",
300
+ spellCheck: false,
301
+ maxLength: length,
302
+ pattern: validationType === "numeric" ? `\\d{${length}}` : `[A-Za-z0-9]{${length}}`,
303
+ disabled: disabled || void 0,
304
+ onBeforeInput(event) {
305
+ const typed = event.data;
306
+ if (typed && typed.length === 1 && !sanitize(typed, validationType)) {
307
+ event.preventDefault();
308
+ }
309
+ },
310
+ onChange(event) {
311
+ commit(event.currentTarget.value);
312
+ syncSelection(event);
313
+ },
314
+ onPaste(event) {
315
+ const pasted = sanitize(event.clipboardData.getData("text/plain"), validationType);
316
+ event.preventDefault();
317
+ if (!pasted) return;
318
+ const input = event.currentTarget;
319
+ if (pasted.length >= length) {
320
+ commit(pasted);
321
+ return;
322
+ }
323
+ const start = input.selectionStart ?? value.length;
324
+ const end = input.selectionEnd ?? start;
325
+ commit(value.slice(0, start) + pasted + value.slice(end));
326
+ },
327
+ onKeyDown(event) {
328
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
329
+ if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey) return;
330
+ const input = event.currentTarget;
331
+ const at = input.selectionStart ?? 0;
332
+ event.preventDefault();
333
+ select(input, event.key === "ArrowLeft" ? at - 1 : at + 1);
334
+ },
335
+ onClick(event) {
336
+ if (event.detail > 1) return;
337
+ const index = slotAt(event.clientX);
338
+ if (index !== null) select(event.currentTarget, index);
339
+ },
340
+ onSelect: syncSelection,
341
+ onFocus(event) {
342
+ select(event.currentTarget, event.currentTarget.value.length);
343
+ },
344
+ onBlur() {
345
+ setSelection(null);
346
+ }
347
+ },
348
+ consumerProps: rest
349
+ });
350
+ }
351
+
352
+ // src/otp-input/OtpInputSlot.tsx
353
+ var import_react5 = require("react");
354
+ function OtpInputSlot({ index, className, children, render, ...rest }) {
355
+ const { value, length, disabled, selection, registerSlot } = useOtpInputRootContext("Slot");
356
+ const char = value.charAt(index);
357
+ let active = false;
358
+ if (selection) {
359
+ active = selection.start === selection.end ? index === Math.min(selection.start, length - 1) : index >= selection.start && index < selection.end;
360
+ }
361
+ const ref = (0, import_react5.useCallback)(
362
+ (element) => registerSlot(index, element),
363
+ [registerSlot, index]
364
+ );
365
+ return useRender({
366
+ render,
367
+ defaultTagName: "div",
368
+ props: {
369
+ ref,
370
+ "aria-hidden": true,
371
+ "data-active": active ? "" : void 0,
372
+ "data-filled": char ? "" : void 0,
373
+ "data-disabled": disabled ? "" : void 0,
374
+ className,
375
+ children: children ?? char
376
+ },
377
+ consumerProps: rest
378
+ });
379
+ }
380
+ // Annotate the CommonJS export names for ESM import in node:
381
+ 0 && (module.exports = {
382
+ OtpInput
383
+ });
@@ -0,0 +1,99 @@
1
+ import * as react from 'react';
2
+ import { ReactElement, Ref, ComponentPropsWithRef } from 'react';
3
+
4
+ /** The characters a code may hold: digits only, or letters and digits. */
5
+ type OtpInputValidationType = 'numeric' | 'alphanumeric';
6
+ /** The state OtpInput.Root shares with its parts, and projects as `data-*` attributes. */
7
+ type OtpInputState = {
8
+ value: string;
9
+ length: number;
10
+ disabled: boolean;
11
+ };
12
+
13
+ type OtpInputRootOwnProps = {
14
+ /**
15
+ * Controlled value. Provide `onValueChange` alongside it.
16
+ *
17
+ * Never `undefined` once mounted: the mode is latched at mount. Coalesce at the call site —
18
+ * `value={code ?? ''}`.
19
+ */
20
+ value?: string;
21
+ /** Initial value when uncontrolled. Read once, at mount. */
22
+ defaultValue?: string;
23
+ /** Called with the code after every change, partial or complete. */
24
+ onValueChange?: (value: string) => void;
25
+ /** How many characters the code has, and so how many slots it shows. Defaults to 6. */
26
+ length?: number;
27
+ /**
28
+ * Which characters are kept: `numeric` (the default) keeps digits, `alphanumeric` letters and
29
+ * digits. Anything else typed or pasted is dropped.
30
+ */
31
+ validationType?: OtpInputValidationType;
32
+ /** Disables the input, and marks the Root and every Slot `data-disabled`. */
33
+ disabled?: boolean;
34
+ /** Element to render instead of the default `<div>`. Props and ref are merged onto it. */
35
+ render?: ReactElement;
36
+ /** Ref to the rendered element. Merged with any ref on the `render` element. */
37
+ ref?: Ref<HTMLElement>;
38
+ };
39
+ type OtpInputRootProps = OtpInputRootOwnProps & Omit<ComponentPropsWithRef<'div'>, keyof OtpInputRootOwnProps | 'defaultValue'>;
40
+ /**
41
+ * A one-time code: a single native `<input>` that holds the whole code, with one Slot per
42
+ * character drawn beside it (decision 20).
43
+ *
44
+ * One real input rather than one per character, because a text field cannot leave the native
45
+ * element (decision 7): SMS autofill (`autocomplete="one-time-code"`), paste, the numeric
46
+ * keypad, IME and password managers all target one input. The Slots are pictures of it.
47
+ *
48
+ * Holds the value through `useControlled`. The input reports changes, and the Root keeps only
49
+ * the characters `validationType` allows, up to `length`.
50
+ */
51
+ declare function OtpInputRoot({ value: valueProp, defaultValue, onValueChange, length, validationType, disabled, className, children, render, ...rest }: OtpInputRootProps): react.JSX.Element;
52
+
53
+ type OtpInputInputOwnProps = {
54
+ /** Element to render instead of the default `<input>`. Props and ref are merged onto it. */
55
+ render?: ReactElement;
56
+ /** Ref to the `<input>`, so focus management and a form library's focus-on-error reach it. */
57
+ ref?: Ref<HTMLElement>;
58
+ };
59
+ type OtpInputInputProps = OtpInputInputOwnProps & Omit<ComponentPropsWithRef<'input'>, keyof OtpInputInputOwnProps | 'value' | 'defaultValue' | 'type' | 'disabled'>;
60
+ /**
61
+ * The native `<input>` that holds the code: the element focus, typing, paste, autofill and
62
+ * the form all use. `name`, `required`, `autoFocus`, `aria-*` and a Field's attributes go here.
63
+ *
64
+ * Draw it over the Slots, transparent: a press then lands on the input, so mobile paste menus
65
+ * and autofill prompts work, and the Root maps the press to the slot under it.
66
+ *
67
+ * The caret always covers one character, so typing replaces the character in the active slot
68
+ * and moves on, and the last slot of a full code is replaced rather than refused. Left and
69
+ * Right move one slot; Backspace and Delete are the platform's.
70
+ *
71
+ * Carries `maxLength` and a `pattern` of exactly `length` allowed characters, so the browser's
72
+ * own validation reports a code that is too short. Both can be overridden.
73
+ */
74
+ declare function OtpInputInput({ render, ...rest }: OtpInputInputProps): ReactElement<unknown, string | react.JSXElementConstructor<any>>;
75
+
76
+ type OtpInputSlotOwnProps = {
77
+ /** Which character of the code this slot shows, from 0. */
78
+ index: number;
79
+ /** Element to render instead of the default `<div>`. Props and ref are merged onto it. */
80
+ render?: ReactElement;
81
+ /** Ref to the rendered element. Merged with any ref on the `render` element. */
82
+ ref?: Ref<HTMLElement>;
83
+ };
84
+ type OtpInputSlotProps = OtpInputSlotOwnProps & Omit<ComponentPropsWithRef<'div'>, keyof OtpInputSlotOwnProps>;
85
+ /**
86
+ * One character of the code, drawn. Shows the character at `index` unless given children,
87
+ * and is hidden from assistive technology: the Input carries the code.
88
+ *
89
+ * `data-active` marks the slot the caret is on while the input has focus — every slot of a
90
+ * selection — and `data-filled` a slot holding a character. A separator between groups of
91
+ * slots is the consumer's own element.
92
+ */
93
+ declare function OtpInputSlot({ index, className, children, render, ...rest }: OtpInputSlotProps): ReactElement<unknown, string | react.JSXElementConstructor<any>>;
94
+
95
+ declare namespace index_parts {
96
+ export { OtpInputInput as Input, OtpInputRoot as Root, OtpInputSlot as Slot };
97
+ }
98
+
99
+ export { index_parts as OtpInput, type OtpInputInputProps, type OtpInputRootProps, type OtpInputSlotProps, type OtpInputState, type OtpInputValidationType };
@@ -0,0 +1,99 @@
1
+ import * as react from 'react';
2
+ import { ReactElement, Ref, ComponentPropsWithRef } from 'react';
3
+
4
+ /** The characters a code may hold: digits only, or letters and digits. */
5
+ type OtpInputValidationType = 'numeric' | 'alphanumeric';
6
+ /** The state OtpInput.Root shares with its parts, and projects as `data-*` attributes. */
7
+ type OtpInputState = {
8
+ value: string;
9
+ length: number;
10
+ disabled: boolean;
11
+ };
12
+
13
+ type OtpInputRootOwnProps = {
14
+ /**
15
+ * Controlled value. Provide `onValueChange` alongside it.
16
+ *
17
+ * Never `undefined` once mounted: the mode is latched at mount. Coalesce at the call site —
18
+ * `value={code ?? ''}`.
19
+ */
20
+ value?: string;
21
+ /** Initial value when uncontrolled. Read once, at mount. */
22
+ defaultValue?: string;
23
+ /** Called with the code after every change, partial or complete. */
24
+ onValueChange?: (value: string) => void;
25
+ /** How many characters the code has, and so how many slots it shows. Defaults to 6. */
26
+ length?: number;
27
+ /**
28
+ * Which characters are kept: `numeric` (the default) keeps digits, `alphanumeric` letters and
29
+ * digits. Anything else typed or pasted is dropped.
30
+ */
31
+ validationType?: OtpInputValidationType;
32
+ /** Disables the input, and marks the Root and every Slot `data-disabled`. */
33
+ disabled?: boolean;
34
+ /** Element to render instead of the default `<div>`. Props and ref are merged onto it. */
35
+ render?: ReactElement;
36
+ /** Ref to the rendered element. Merged with any ref on the `render` element. */
37
+ ref?: Ref<HTMLElement>;
38
+ };
39
+ type OtpInputRootProps = OtpInputRootOwnProps & Omit<ComponentPropsWithRef<'div'>, keyof OtpInputRootOwnProps | 'defaultValue'>;
40
+ /**
41
+ * A one-time code: a single native `<input>` that holds the whole code, with one Slot per
42
+ * character drawn beside it (decision 20).
43
+ *
44
+ * One real input rather than one per character, because a text field cannot leave the native
45
+ * element (decision 7): SMS autofill (`autocomplete="one-time-code"`), paste, the numeric
46
+ * keypad, IME and password managers all target one input. The Slots are pictures of it.
47
+ *
48
+ * Holds the value through `useControlled`. The input reports changes, and the Root keeps only
49
+ * the characters `validationType` allows, up to `length`.
50
+ */
51
+ declare function OtpInputRoot({ value: valueProp, defaultValue, onValueChange, length, validationType, disabled, className, children, render, ...rest }: OtpInputRootProps): react.JSX.Element;
52
+
53
+ type OtpInputInputOwnProps = {
54
+ /** Element to render instead of the default `<input>`. Props and ref are merged onto it. */
55
+ render?: ReactElement;
56
+ /** Ref to the `<input>`, so focus management and a form library's focus-on-error reach it. */
57
+ ref?: Ref<HTMLElement>;
58
+ };
59
+ type OtpInputInputProps = OtpInputInputOwnProps & Omit<ComponentPropsWithRef<'input'>, keyof OtpInputInputOwnProps | 'value' | 'defaultValue' | 'type' | 'disabled'>;
60
+ /**
61
+ * The native `<input>` that holds the code: the element focus, typing, paste, autofill and
62
+ * the form all use. `name`, `required`, `autoFocus`, `aria-*` and a Field's attributes go here.
63
+ *
64
+ * Draw it over the Slots, transparent: a press then lands on the input, so mobile paste menus
65
+ * and autofill prompts work, and the Root maps the press to the slot under it.
66
+ *
67
+ * The caret always covers one character, so typing replaces the character in the active slot
68
+ * and moves on, and the last slot of a full code is replaced rather than refused. Left and
69
+ * Right move one slot; Backspace and Delete are the platform's.
70
+ *
71
+ * Carries `maxLength` and a `pattern` of exactly `length` allowed characters, so the browser's
72
+ * own validation reports a code that is too short. Both can be overridden.
73
+ */
74
+ declare function OtpInputInput({ render, ...rest }: OtpInputInputProps): ReactElement<unknown, string | react.JSXElementConstructor<any>>;
75
+
76
+ type OtpInputSlotOwnProps = {
77
+ /** Which character of the code this slot shows, from 0. */
78
+ index: number;
79
+ /** Element to render instead of the default `<div>`. Props and ref are merged onto it. */
80
+ render?: ReactElement;
81
+ /** Ref to the rendered element. Merged with any ref on the `render` element. */
82
+ ref?: Ref<HTMLElement>;
83
+ };
84
+ type OtpInputSlotProps = OtpInputSlotOwnProps & Omit<ComponentPropsWithRef<'div'>, keyof OtpInputSlotOwnProps>;
85
+ /**
86
+ * One character of the code, drawn. Shows the character at `index` unless given children,
87
+ * and is hidden from assistive technology: the Input carries the code.
88
+ *
89
+ * `data-active` marks the slot the caret is on while the input has focus — every slot of a
90
+ * selection — and `data-filled` a slot holding a character. A separator between groups of
91
+ * slots is the consumer's own element.
92
+ */
93
+ declare function OtpInputSlot({ index, className, children, render, ...rest }: OtpInputSlotProps): ReactElement<unknown, string | react.JSXElementConstructor<any>>;
94
+
95
+ declare namespace index_parts {
96
+ export { OtpInputInput as Input, OtpInputRoot as Root, OtpInputSlot as Slot };
97
+ }
98
+
99
+ export { index_parts as OtpInput, type OtpInputInputProps, type OtpInputRootProps, type OtpInputSlotProps, type OtpInputState, type OtpInputValidationType };
@@ -0,0 +1,242 @@
1
+ import {
2
+ useControlled
3
+ } from "../chunk-UEIB3I3T.js";
4
+ import {
5
+ __export,
6
+ useRender
7
+ } from "../chunk-OQTWWZ4B.js";
8
+
9
+ // src/otp-input/index.parts.ts
10
+ var index_parts_exports = {};
11
+ __export(index_parts_exports, {
12
+ Input: () => OtpInputInput,
13
+ Root: () => OtpInputRoot,
14
+ Slot: () => OtpInputSlot
15
+ });
16
+
17
+ // src/otp-input/OtpInputRoot.tsx
18
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
19
+
20
+ // src/otp-input/OtpInputRootContext.ts
21
+ import { createContext, useContext } from "react";
22
+ var OtpInputRootContext = createContext(null);
23
+ function useOtpInputRootContext(part) {
24
+ const context = useContext(OtpInputRootContext);
25
+ if (context === null) {
26
+ throw new Error(`<OtpInput.${part}> must be rendered inside <OtpInput.Root>.`);
27
+ }
28
+ return context;
29
+ }
30
+ function sanitize(text, validationType) {
31
+ return validationType === "numeric" ? text.replace(/\D/g, "") : text.replace(/[^A-Za-z0-9]/g, "");
32
+ }
33
+ function otpInputDataAttributes({ value, length, disabled }) {
34
+ return {
35
+ "data-complete": value.length === length ? "" : void 0,
36
+ "data-disabled": disabled ? "" : void 0
37
+ };
38
+ }
39
+
40
+ // src/otp-input/OtpInputRoot.tsx
41
+ import { jsx } from "react/jsx-runtime";
42
+ function OtpInputRoot({
43
+ value: valueProp,
44
+ defaultValue,
45
+ onValueChange,
46
+ length = 6,
47
+ validationType = "numeric",
48
+ disabled = false,
49
+ className,
50
+ children,
51
+ render,
52
+ ...rest
53
+ }) {
54
+ const [value, setValue] = useControlled({
55
+ controlled: valueProp,
56
+ default: defaultValue ?? "",
57
+ name: "OtpInput.Root",
58
+ state: "value"
59
+ });
60
+ const commit = useCallback(
61
+ (next) => {
62
+ const clean = sanitize(next, validationType).slice(0, length);
63
+ if (clean === value) return;
64
+ setValue(clean);
65
+ onValueChange?.(clean);
66
+ },
67
+ [validationType, length, value, setValue, onValueChange]
68
+ );
69
+ const [selection, setSelection] = useState(null);
70
+ const inputRef = useRef(null);
71
+ const slotsRef = useRef(/* @__PURE__ */ new Map());
72
+ const registerSlot = useCallback((index, element2) => {
73
+ if (element2) slotsRef.current.set(index, element2);
74
+ else slotsRef.current.delete(index);
75
+ }, []);
76
+ const slotAt = useCallback((clientX) => {
77
+ let nearest = null;
78
+ let distance = Infinity;
79
+ for (const [index, element2] of slotsRef.current) {
80
+ const rect = element2.getBoundingClientRect();
81
+ const d = clientX < rect.left ? rect.left - clientX : clientX > rect.right ? clientX - rect.right : 0;
82
+ if (d < distance) {
83
+ distance = d;
84
+ nearest = index;
85
+ }
86
+ }
87
+ return nearest;
88
+ }, []);
89
+ const { current: initialValue } = useRef(value);
90
+ useEffect(() => {
91
+ const form = inputRef.current?.form;
92
+ if (!form) return;
93
+ function onReset(event) {
94
+ queueMicrotask(() => {
95
+ if (!event.defaultPrevented) commit(initialValue);
96
+ });
97
+ }
98
+ form.addEventListener("reset", onReset);
99
+ return () => form.removeEventListener("reset", onReset);
100
+ }, [commit, initialValue]);
101
+ const context = useMemo(
102
+ () => ({
103
+ value,
104
+ length,
105
+ disabled,
106
+ validationType,
107
+ selection,
108
+ setSelection,
109
+ commit,
110
+ inputRef,
111
+ registerSlot,
112
+ slotAt
113
+ }),
114
+ [value, length, disabled, validationType, selection, commit, registerSlot, slotAt]
115
+ );
116
+ const element = useRender({
117
+ render,
118
+ defaultTagName: "div",
119
+ props: {
120
+ ...otpInputDataAttributes({ value, length, disabled }),
121
+ className,
122
+ children
123
+ },
124
+ consumerProps: rest
125
+ });
126
+ return /* @__PURE__ */ jsx(OtpInputRootContext.Provider, { value: context, children: element });
127
+ }
128
+
129
+ // src/otp-input/OtpInputInput.tsx
130
+ function OtpInputInput({ render, ...rest }) {
131
+ const { value, length, disabled, validationType, setSelection, commit, inputRef, slotAt } = useOtpInputRootContext("Input");
132
+ function select(input, index) {
133
+ const filled = input.value.length;
134
+ const at = Math.max(0, Math.min(index, filled, length - 1));
135
+ if (at < filled) input.setSelectionRange(at, at + 1);
136
+ else input.setSelectionRange(filled, filled);
137
+ report(input);
138
+ }
139
+ function report(input) {
140
+ setSelection({ start: input.selectionStart ?? 0, end: input.selectionEnd ?? 0 });
141
+ }
142
+ function syncSelection(event) {
143
+ const input = event.currentTarget;
144
+ const start = input.selectionStart ?? 0;
145
+ const end = input.selectionEnd ?? start;
146
+ if (start === end && (start < input.value.length || start >= length)) select(input, start);
147
+ else report(input);
148
+ }
149
+ return useRender({
150
+ render,
151
+ defaultTagName: "input",
152
+ props: {
153
+ ref: inputRef,
154
+ type: "text",
155
+ value,
156
+ inputMode: validationType === "numeric" ? "numeric" : "text",
157
+ autoComplete: "one-time-code",
158
+ autoCapitalize: "off",
159
+ autoCorrect: "off",
160
+ spellCheck: false,
161
+ maxLength: length,
162
+ pattern: validationType === "numeric" ? `\\d{${length}}` : `[A-Za-z0-9]{${length}}`,
163
+ disabled: disabled || void 0,
164
+ onBeforeInput(event) {
165
+ const typed = event.data;
166
+ if (typed && typed.length === 1 && !sanitize(typed, validationType)) {
167
+ event.preventDefault();
168
+ }
169
+ },
170
+ onChange(event) {
171
+ commit(event.currentTarget.value);
172
+ syncSelection(event);
173
+ },
174
+ onPaste(event) {
175
+ const pasted = sanitize(event.clipboardData.getData("text/plain"), validationType);
176
+ event.preventDefault();
177
+ if (!pasted) return;
178
+ const input = event.currentTarget;
179
+ if (pasted.length >= length) {
180
+ commit(pasted);
181
+ return;
182
+ }
183
+ const start = input.selectionStart ?? value.length;
184
+ const end = input.selectionEnd ?? start;
185
+ commit(value.slice(0, start) + pasted + value.slice(end));
186
+ },
187
+ onKeyDown(event) {
188
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
189
+ if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey) return;
190
+ const input = event.currentTarget;
191
+ const at = input.selectionStart ?? 0;
192
+ event.preventDefault();
193
+ select(input, event.key === "ArrowLeft" ? at - 1 : at + 1);
194
+ },
195
+ onClick(event) {
196
+ if (event.detail > 1) return;
197
+ const index = slotAt(event.clientX);
198
+ if (index !== null) select(event.currentTarget, index);
199
+ },
200
+ onSelect: syncSelection,
201
+ onFocus(event) {
202
+ select(event.currentTarget, event.currentTarget.value.length);
203
+ },
204
+ onBlur() {
205
+ setSelection(null);
206
+ }
207
+ },
208
+ consumerProps: rest
209
+ });
210
+ }
211
+
212
+ // src/otp-input/OtpInputSlot.tsx
213
+ import { useCallback as useCallback2 } from "react";
214
+ function OtpInputSlot({ index, className, children, render, ...rest }) {
215
+ const { value, length, disabled, selection, registerSlot } = useOtpInputRootContext("Slot");
216
+ const char = value.charAt(index);
217
+ let active = false;
218
+ if (selection) {
219
+ active = selection.start === selection.end ? index === Math.min(selection.start, length - 1) : index >= selection.start && index < selection.end;
220
+ }
221
+ const ref = useCallback2(
222
+ (element) => registerSlot(index, element),
223
+ [registerSlot, index]
224
+ );
225
+ return useRender({
226
+ render,
227
+ defaultTagName: "div",
228
+ props: {
229
+ ref,
230
+ "aria-hidden": true,
231
+ "data-active": active ? "" : void 0,
232
+ "data-filled": char ? "" : void 0,
233
+ "data-disabled": disabled ? "" : void 0,
234
+ className,
235
+ children: children ?? char
236
+ },
237
+ consumerProps: rest
238
+ });
239
+ }
240
+ export {
241
+ index_parts_exports as OtpInput
242
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arun-dev/headless",
3
- "version": "4.17.0",
3
+ "version": "4.18.0",
4
4
  "description": "Unstyled React behaviour primitives — render engine, controlled/uncontrolled state, and data-* state projection. Ships no CSS and no class names.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -84,6 +84,16 @@
84
84
  "default": "./dist/menu/index.cjs"
85
85
  }
86
86
  },
87
+ "./otp-input": {
88
+ "import": {
89
+ "types": "./dist/otp-input/index.d.ts",
90
+ "default": "./dist/otp-input/index.js"
91
+ },
92
+ "require": {
93
+ "types": "./dist/otp-input/index.d.cts",
94
+ "default": "./dist/otp-input/index.cjs"
95
+ }
96
+ },
87
97
  "./popover": {
88
98
  "import": {
89
99
  "types": "./dist/popover/index.d.ts",