@cdx-ui/primitives 0.0.1-alpha.36 → 0.0.1-alpha.38

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.
Files changed (64) hide show
  1. package/lib/commonjs/index.js +12 -0
  2. package/lib/commonjs/index.js.map +1 -1
  3. package/lib/commonjs/otp-input/context.js +14 -0
  4. package/lib/commonjs/otp-input/context.js.map +1 -0
  5. package/lib/commonjs/otp-input/createOtpInputCell.js +29 -0
  6. package/lib/commonjs/otp-input/createOtpInputCell.js.map +1 -0
  7. package/lib/commonjs/otp-input/createOtpInputField.js +104 -0
  8. package/lib/commonjs/otp-input/createOtpInputField.js.map +1 -0
  9. package/lib/commonjs/otp-input/createOtpInputRoot.js +136 -0
  10. package/lib/commonjs/otp-input/createOtpInputRoot.js.map +1 -0
  11. package/lib/commonjs/otp-input/index.js +48 -0
  12. package/lib/commonjs/otp-input/index.js.map +1 -0
  13. package/lib/commonjs/otp-input/types.js +6 -0
  14. package/lib/commonjs/otp-input/types.js.map +1 -0
  15. package/lib/commonjs/otp-input/utils/applyValueChange.js +73 -0
  16. package/lib/commonjs/otp-input/utils/applyValueChange.js.map +1 -0
  17. package/lib/commonjs/otp-input/utils/filterValue.js +46 -0
  18. package/lib/commonjs/otp-input/utils/filterValue.js.map +1 -0
  19. package/lib/module/index.js +1 -0
  20. package/lib/module/index.js.map +1 -1
  21. package/lib/module/otp-input/context.js +6 -0
  22. package/lib/module/otp-input/context.js.map +1 -0
  23. package/lib/module/otp-input/createOtpInputCell.js +24 -0
  24. package/lib/module/otp-input/createOtpInputCell.js.map +1 -0
  25. package/lib/module/otp-input/createOtpInputField.js +99 -0
  26. package/lib/module/otp-input/createOtpInputField.js.map +1 -0
  27. package/lib/module/otp-input/createOtpInputRoot.js +131 -0
  28. package/lib/module/otp-input/createOtpInputRoot.js.map +1 -0
  29. package/lib/module/otp-input/index.js +20 -0
  30. package/lib/module/otp-input/index.js.map +1 -0
  31. package/lib/module/otp-input/types.js +4 -0
  32. package/lib/module/otp-input/types.js.map +1 -0
  33. package/lib/module/otp-input/utils/applyValueChange.js +69 -0
  34. package/lib/module/otp-input/utils/applyValueChange.js.map +1 -0
  35. package/lib/module/otp-input/utils/filterValue.js +40 -0
  36. package/lib/module/otp-input/utils/filterValue.js.map +1 -0
  37. package/lib/typescript/index.d.ts +1 -0
  38. package/lib/typescript/index.d.ts.map +1 -1
  39. package/lib/typescript/otp-input/context.d.ts +10 -0
  40. package/lib/typescript/otp-input/context.d.ts.map +1 -0
  41. package/lib/typescript/otp-input/createOtpInputCell.d.ts +4 -0
  42. package/lib/typescript/otp-input/createOtpInputCell.d.ts.map +1 -0
  43. package/lib/typescript/otp-input/createOtpInputField.d.ts +4 -0
  44. package/lib/typescript/otp-input/createOtpInputField.d.ts.map +1 -0
  45. package/lib/typescript/otp-input/createOtpInputRoot.d.ts +4 -0
  46. package/lib/typescript/otp-input/createOtpInputRoot.d.ts.map +1 -0
  47. package/lib/typescript/otp-input/index.d.ts +11 -0
  48. package/lib/typescript/otp-input/index.d.ts.map +1 -0
  49. package/lib/typescript/otp-input/types.d.ts +75 -0
  50. package/lib/typescript/otp-input/types.d.ts.map +1 -0
  51. package/lib/typescript/otp-input/utils/applyValueChange.d.ts +10 -0
  52. package/lib/typescript/otp-input/utils/applyValueChange.d.ts.map +1 -0
  53. package/lib/typescript/otp-input/utils/filterValue.d.ts +7 -0
  54. package/lib/typescript/otp-input/utils/filterValue.d.ts.map +1 -0
  55. package/package.json +2 -2
  56. package/src/index.ts +1 -0
  57. package/src/otp-input/context.tsx +8 -0
  58. package/src/otp-input/createOtpInputCell.tsx +22 -0
  59. package/src/otp-input/createOtpInputField.tsx +98 -0
  60. package/src/otp-input/createOtpInputRoot.tsx +179 -0
  61. package/src/otp-input/index.tsx +34 -0
  62. package/src/otp-input/types.ts +92 -0
  63. package/src/otp-input/utils/applyValueChange.ts +56 -0
  64. package/src/otp-input/utils/filterValue.ts +37 -0
@@ -0,0 +1,22 @@
1
+ import type React from 'react';
2
+ import type { PropsWithChildren } from 'react';
3
+ import { forwardRef } from 'react';
4
+ import { useOtpInputContext } from './context';
5
+ import type { IOtpInputCellProps } from './types';
6
+
7
+ export const createOtpInputCell = <T,>(BaseCell: React.ComponentType<T>) =>
8
+ forwardRef<unknown, PropsWithChildren<IOtpInputCellProps & T>>(({ children, ...props }, ref) => {
9
+ const { isDisabled, isInvalid, isReadOnly } = useOtpInputContext();
10
+
11
+ return (
12
+ <BaseCell
13
+ ref={ref}
14
+ isDisabled={isDisabled}
15
+ isInvalid={isInvalid}
16
+ isReadOnly={isReadOnly}
17
+ {...(props as T)}
18
+ >
19
+ {children}
20
+ </BaseCell>
21
+ );
22
+ });
@@ -0,0 +1,98 @@
1
+ import type React from 'react';
2
+ import { forwardRef, useMemo } from 'react';
3
+ import { Platform, type TextInput, type TextInputKeyPressEvent } from 'react-native';
4
+ import { mergeRefs } from '@cdx-ui/utils';
5
+ import { useOtpCellIndexContext, useOtpInputContext } from './context';
6
+ import type { IOtpInputFieldProps } from './types';
7
+
8
+ export const createOtpInputField = <T,>(BaseField: React.ComponentType<T>) =>
9
+ forwardRef<TextInput, IOtpInputFieldProps & Omit<T, keyof IOtpInputFieldProps>>((props, ref) => {
10
+ const { cellIndex } = useOtpCellIndexContext();
11
+ const {
12
+ value,
13
+ cellCount,
14
+ isDisabled,
15
+ isReadOnly,
16
+ smsOtpAutofill,
17
+ getCellProps,
18
+ cellTestIdPrefix,
19
+ rootAccessibilityLabel,
20
+ setFieldRef,
21
+ handleFieldChange,
22
+ handleFieldKeyPress,
23
+ } = useOtpInputContext();
24
+
25
+ const char = cellIndex < value.length ? (value[cellIndex] ?? '') : '';
26
+ const extra = getCellProps?.(cellIndex) ?? {};
27
+
28
+ const accessibilityLabel = useMemo(() => {
29
+ const fromExtra = extra.accessibilityLabel;
30
+ if (typeof fromExtra === 'string' && fromExtra !== '') {
31
+ return fromExtra;
32
+ }
33
+ if (rootAccessibilityLabel) {
34
+ return `${rootAccessibilityLabel}, ${String(cellIndex + 1)} of ${String(cellCount)}`;
35
+ }
36
+ return `OTP digit ${String(cellIndex + 1)} of ${String(cellCount)}`;
37
+ }, [cellCount, cellIndex, extra.accessibilityLabel, rootAccessibilityLabel]);
38
+
39
+ const autofillProps = useMemo(() => {
40
+ if (!smsOtpAutofill || cellIndex !== 0) {
41
+ return {};
42
+ }
43
+ return Platform.select<Record<string, unknown>>({
44
+ web: { autoComplete: 'one-time-code' },
45
+ ios: { textContentType: 'oneTimeCode' },
46
+ android: { autoComplete: 'sms-otp' },
47
+ default: {},
48
+ });
49
+ }, [cellIndex, smsOtpAutofill]);
50
+
51
+ const editable = !(isDisabled || isReadOnly);
52
+
53
+ const { style: extraStyle, accessibilityLabel: _omitExtraA11y, ...extraRest } = extra;
54
+ void _omitExtraA11y;
55
+ const {
56
+ style: incomingStyle,
57
+ value: _omitValue,
58
+ defaultValue: _omitDefault,
59
+ onChangeText: _omitOnChange,
60
+ ...incomingRest
61
+ } = props as IOtpInputFieldProps;
62
+ void _omitValue;
63
+ void _omitDefault;
64
+ void _omitOnChange;
65
+
66
+ // Default digit OTP (`number-pad`). Root `getCellProps` is spread after and may override `keyboardType`.
67
+ return (
68
+ <BaseField
69
+ ref={mergeRefs(ref, (el: TextInput | null) => {
70
+ setFieldRef(cellIndex, el);
71
+ })}
72
+ accessibilityLabel={accessibilityLabel}
73
+ aria-label={accessibilityLabel}
74
+ accessible
75
+ autoFocus={cellIndex === 0 && editable && value.length === 0}
76
+ editable={editable}
77
+ keyboardType="number-pad"
78
+ returnKeyType="done"
79
+ selectTextOnFocus
80
+ testID={
81
+ cellTestIdPrefix
82
+ ? `${cellTestIdPrefix}:${String(cellIndex)}:textField:changeText`
83
+ : undefined
84
+ }
85
+ value={char}
86
+ onChangeText={(text: string) => {
87
+ handleFieldChange(cellIndex, text);
88
+ }}
89
+ onKeyPress={(e: TextInputKeyPressEvent) => {
90
+ handleFieldKeyPress(cellIndex, e.nativeEvent.key);
91
+ }}
92
+ {...autofillProps}
93
+ {...(extraRest as object)}
94
+ {...(incomingRest as T)}
95
+ style={[extraStyle, incomingStyle]}
96
+ />
97
+ );
98
+ });
@@ -0,0 +1,179 @@
1
+ import type React from 'react';
2
+ import { forwardRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react';
3
+ import type { TextInput } from 'react-native';
4
+ import { useFormControlContext } from '@cdx-ui/utils';
5
+ import { applyOtpInputChange } from './utils/applyValueChange';
6
+ import { OtpCellIndexProvider, OtpInputProvider } from './context';
7
+ import { filterAllowedCharacters, filterByRegExp, filterDigits } from './utils/filterValue';
8
+ import type { IOtpInputRootProps } from './types';
9
+
10
+ export const createOtpInputRoot = <RootProps,>(
11
+ BaseRoot: React.ComponentType<RootProps>,
12
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- slot components are generic across design systems
13
+ OtpCell: React.ComponentType<any>,
14
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
+ OtpField: React.ComponentType<any>,
16
+ ) =>
17
+ forwardRef<unknown, IOtpInputRootProps & RootProps>(
18
+ (
19
+ {
20
+ cellCount,
21
+ value,
22
+ onChangeText,
23
+ onComplete,
24
+ isDisabled: isDisabledProp,
25
+ isInvalid: isInvalidProp,
26
+ isReadOnly: isReadOnlyProp,
27
+ smsOtpAutofill = true,
28
+ filterInput,
29
+ allowedCharacters,
30
+ characterPattern,
31
+ getCellProps,
32
+ cellTestIdPrefix,
33
+ accessibilityLabel: rootAccessibilityLabel,
34
+ ...rest
35
+ },
36
+ ref,
37
+ ) => {
38
+ const form = useFormControlContext();
39
+ const isDisabled = isDisabledProp ?? form.isDisabled ?? false;
40
+ const isInvalid = isInvalidProp ?? form.isInvalid ?? false;
41
+ const isReadOnly = isReadOnlyProp ?? form.isReadOnly ?? false;
42
+
43
+ const fieldRefs = useRef<(TextInput | null)[]>([]);
44
+ const focusAfterApply = useRef<number | null>(null);
45
+ const prevLenRef = useRef(value.length);
46
+ const prevValueRef = useRef(value);
47
+
48
+ const filter = useMemo(() => {
49
+ if (filterInput) {
50
+ return filterInput;
51
+ }
52
+ if (allowedCharacters !== undefined) {
53
+ return filterAllowedCharacters(allowedCharacters);
54
+ }
55
+ if (characterPattern !== undefined) {
56
+ return filterByRegExp(characterPattern);
57
+ }
58
+ return filterDigits;
59
+ }, [filterInput, allowedCharacters, characterPattern]);
60
+
61
+ const setFieldRef = useCallback((index: number, el: TextInput | null) => {
62
+ fieldRefs.current[index] = el;
63
+ }, []);
64
+
65
+ const focusCell = useCallback(
66
+ (index: number) => {
67
+ const safe = Math.max(0, Math.min(index, cellCount - 1));
68
+ fieldRefs.current[safe]?.focus();
69
+ },
70
+ [cellCount],
71
+ );
72
+
73
+ const handleFieldChange = useCallback(
74
+ (index: number, text: string) => {
75
+ const { nextValue, focusIndex } = applyOtpInputChange(
76
+ value,
77
+ index,
78
+ text,
79
+ cellCount,
80
+ filter,
81
+ );
82
+ if (nextValue !== value) {
83
+ onChangeText(nextValue);
84
+ }
85
+ focusAfterApply.current = focusIndex;
86
+ },
87
+ [cellCount, filter, onChangeText, value],
88
+ );
89
+
90
+ const handleFieldKeyPress = useCallback(
91
+ (index: number, key: string) => {
92
+ if (key !== 'Backspace') {
93
+ return;
94
+ }
95
+ const char = index < value.length ? value[index] : '';
96
+ if (!char && index > 0) {
97
+ focusCell(index - 1);
98
+ }
99
+ },
100
+ [focusCell, value],
101
+ );
102
+
103
+ useLayoutEffect(() => {
104
+ if (focusAfterApply.current !== null) {
105
+ const i = focusAfterApply.current;
106
+ focusAfterApply.current = null;
107
+ fieldRefs.current[i]?.focus();
108
+ }
109
+ });
110
+
111
+ useEffect(() => {
112
+ const prevLen = prevLenRef.current;
113
+ const prevVal = prevValueRef.current;
114
+ const isFull = value.length === cellCount;
115
+ const becameFullByLength = isFull && prevLen < cellCount;
116
+ const correctedWhileFull = isFull && prevLen === cellCount && prevVal !== value;
117
+
118
+ if (becameFullByLength || correctedWhileFull) {
119
+ onComplete?.();
120
+ }
121
+ prevLenRef.current = value.length;
122
+ prevValueRef.current = value;
123
+ }, [cellCount, onComplete, value]);
124
+
125
+ const contextValue = useMemo(
126
+ () => ({
127
+ cellCount,
128
+ value,
129
+ isDisabled,
130
+ isInvalid,
131
+ isReadOnly,
132
+ smsOtpAutofill,
133
+ filter,
134
+ getCellProps,
135
+ cellTestIdPrefix,
136
+ rootAccessibilityLabel,
137
+ setFieldRef,
138
+ handleFieldChange,
139
+ handleFieldKeyPress,
140
+ }),
141
+ [
142
+ cellCount,
143
+ value,
144
+ isDisabled,
145
+ isInvalid,
146
+ isReadOnly,
147
+ smsOtpAutofill,
148
+ filter,
149
+ getCellProps,
150
+ cellTestIdPrefix,
151
+ rootAccessibilityLabel,
152
+ setFieldRef,
153
+ handleFieldChange,
154
+ handleFieldKeyPress,
155
+ ],
156
+ );
157
+
158
+ // Hermes drops outer-scope closure vars from its environment record when
159
+ // they are only referenced inside a nested callback (Array.from). Using a
160
+ // for-loop keeps OtpCell/OtpField references in the render function's own
161
+ // scope, avoiding the Hermes closure-capture bug.
162
+ const cells: React.ReactElement[] = [];
163
+ for (let i = 0; i < cellCount; i++) {
164
+ cells.push(
165
+ <OtpCellIndexProvider key={i} value={{ cellIndex: i }}>
166
+ <OtpCell>
167
+ <OtpField />
168
+ </OtpCell>
169
+ </OtpCellIndexProvider>,
170
+ );
171
+ }
172
+
173
+ return (
174
+ <BaseRoot ref={ref as React.Ref<unknown>} {...(rest as RootProps)}>
175
+ <OtpInputProvider value={contextValue}>{cells}</OtpInputProvider>
176
+ </BaseRoot>
177
+ );
178
+ },
179
+ );
@@ -0,0 +1,34 @@
1
+ import type React from 'react';
2
+ import { createOtpInputCell } from './createOtpInputCell';
3
+ import { createOtpInputField } from './createOtpInputField';
4
+ import { createOtpInputRoot } from './createOtpInputRoot';
5
+ import type { IOtpInputComponentType } from './types';
6
+
7
+ export { applyOtpInputChange } from './utils/applyValueChange';
8
+ export { filterAllowedCharacters, filterByRegExp, filterDigits } from './utils/filterValue';
9
+ export type * from './types';
10
+
11
+ export function createOtpInput<
12
+ RootProps,
13
+ CellProps,
14
+ FieldProps,
15
+ RootRef = unknown,
16
+ FieldRef = unknown,
17
+ >(BaseComponents: {
18
+ Root: React.ComponentType<RootProps>;
19
+ Cell: React.ComponentType<CellProps>;
20
+ Field: React.ComponentType<FieldProps>;
21
+ }) {
22
+ const Cell = createOtpInputCell(BaseComponents.Cell);
23
+ const Field = createOtpInputField(BaseComponents.Field);
24
+ const Root = createOtpInputRoot(BaseComponents.Root, Cell, Field);
25
+
26
+ Root.displayName = 'OtpInputPrimitive';
27
+ Cell.displayName = 'OtpInputPrimitive.Cell';
28
+ Field.displayName = 'OtpInputPrimitive.Field';
29
+
30
+ return Object.assign(Root, {
31
+ Cell,
32
+ Field,
33
+ }) as IOtpInputComponentType<RootProps, CellProps, FieldProps, RootRef, FieldRef>;
34
+ }
@@ -0,0 +1,92 @@
1
+ import type React from 'react';
2
+ import type { ReactNode } from 'react';
3
+ import type { TextInputProps, ViewProps } from 'react-native';
4
+
5
+ export interface IOtpInputRootProps extends ViewProps {
6
+ /** Number of OTP cells (fixed). */
7
+ cellCount: number;
8
+ /** Controlled value: characters in order, length 0..`cellCount` (prefix fill). */
9
+ value: string;
10
+ onChangeText: (value: string) => void;
11
+ /**
12
+ * Called when the code is ready to verify again:
13
+ * - `value` becomes full (`length === cellCount`) after being shorter, or
14
+ * - `value` stays full but the string changes (user corrected a digit without dropping below full length).
15
+ * Does not fire on mount when `value` is already full and unchanged, nor on re-renders with the same full `value`.
16
+ */
17
+ onComplete?: () => void;
18
+ isDisabled?: boolean;
19
+ isInvalid?: boolean;
20
+ isReadOnly?: boolean;
21
+ /** When false, no SMS / Web OTP autofill hints on the first cell. @default true */
22
+ smsOtpAutofill?: boolean;
23
+ /**
24
+ * Override default digit-only filtering.
25
+ * Takes priority over `allowedCharacters` and `characterPattern` when truthy.
26
+ * Does not change the default `keyboardType` (`number-pad`); use `getCellProps` if the allowed
27
+ * character set needs a different keyboard.
28
+ */
29
+ filterInput?: (input: string) => string;
30
+ /**
31
+ * Keep only characters present in this string (treated as a set of code units).
32
+ * Used when `filterInput` is not provided. Takes priority over `characterPattern`.
33
+ * Default keyboard remains numeric; use `getCellProps` to set `keyboardType` when allowing letters/symbols.
34
+ */
35
+ allowedCharacters?: string;
36
+ /**
37
+ * Keep only characters matching this pattern (tested per code unit).
38
+ * Used when neither `filterInput` nor `allowedCharacters` is provided.
39
+ * Default keyboard remains numeric; use `getCellProps` to set `keyboardType` for non-digit input.
40
+ */
41
+ characterPattern?: RegExp;
42
+ /**
43
+ * Spread onto each cell after built-in field props (including `keyboardType="number-pad"`),
44
+ * so consumers can override `keyboardType`, `autoCapitalize`, etc. for non-digit OTPs.
45
+ */
46
+ getCellProps?: (index: number) => Partial<TextInputProps>;
47
+ /** Optional prefix for `testID` on each field: `${cellTestIdPrefix}:${index}:...` */
48
+ cellTestIdPrefix?: string;
49
+ }
50
+
51
+ export interface IOtpInputCellProps extends ViewProps {
52
+ children?: ReactNode;
53
+ }
54
+
55
+ export type IOtpInputFieldProps = TextInputProps;
56
+
57
+ export interface OtpInputCellIndexContextValue {
58
+ cellIndex: number;
59
+ }
60
+
61
+ export interface OtpInputContextValue {
62
+ cellCount: number;
63
+ value: string;
64
+ isDisabled: boolean;
65
+ isInvalid: boolean;
66
+ isReadOnly: boolean;
67
+ smsOtpAutofill: boolean;
68
+ filter: (input: string) => string;
69
+ getCellProps?: (index: number) => Partial<TextInputProps>;
70
+ cellTestIdPrefix?: string;
71
+ rootAccessibilityLabel?: string;
72
+ setFieldRef: (index: number, el: import('react-native').TextInput | null) => void;
73
+ handleFieldChange: (index: number, text: string) => void;
74
+ handleFieldKeyPress: (index: number, key: string) => void;
75
+ }
76
+
77
+ export type IOtpInputComponentType<
78
+ RootProps,
79
+ CellProps,
80
+ FieldProps,
81
+ RootRef = unknown,
82
+ FieldRef = unknown,
83
+ > = React.ForwardRefExoticComponent<
84
+ React.PropsWithoutRef<RootProps & IOtpInputRootProps> & React.RefAttributes<RootRef>
85
+ > & {
86
+ Cell: React.ForwardRefExoticComponent<
87
+ React.PropsWithoutRef<CellProps & IOtpInputCellProps> & React.RefAttributes<unknown>
88
+ >;
89
+ Field: React.ForwardRefExoticComponent<
90
+ React.PropsWithoutRef<FieldProps & IOtpInputFieldProps> & React.RefAttributes<FieldRef>
91
+ >;
92
+ };
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Pure OTP value transition for a controlled prefix string (no explicit empty slots).
3
+ * - Single-character edits use index-based replace/append (no reorder).
4
+ * - Multi-character input (paste/autofill) writes at `index` forward, then packs left.
5
+ */
6
+ export function applyOtpInputChange(
7
+ value: string,
8
+ index: number,
9
+ rawText: string,
10
+ cellCount: number,
11
+ filter: (input: string) => string,
12
+ ): { nextValue: string; focusIndex: number } {
13
+ const text = filter(rawText);
14
+
15
+ if (text.length === 0) {
16
+ if (index < value.length) {
17
+ const next = (value.slice(0, index) + value.slice(index + 1)).slice(0, cellCount);
18
+ return { nextValue: next, focusIndex: Math.max(0, index - 1) };
19
+ }
20
+ return { nextValue: value, focusIndex: index };
21
+ }
22
+
23
+ if (text.length === 1) {
24
+ if (index < value.length) {
25
+ const next = (value.slice(0, index) + text + value.slice(index + 1)).slice(0, cellCount);
26
+ return { nextValue: next, focusIndex: Math.min(index + 1, cellCount - 1) };
27
+ }
28
+ if (value.length < cellCount) {
29
+ if (index === value.length) {
30
+ const next = (value + text).slice(0, cellCount);
31
+ return { nextValue: next, focusIndex: Math.min(next.length, cellCount - 1) };
32
+ }
33
+ const arr = Array.from({ length: cellCount }, (_, i) => (i < value.length ? value[i] : ''));
34
+ arr[index] = text;
35
+ const next = arr
36
+ .filter((c) => c)
37
+ .join('')
38
+ .slice(0, cellCount);
39
+ return { nextValue: next, focusIndex: Math.min(index + 1, cellCount - 1) };
40
+ }
41
+ const next = (value.slice(0, index) + text + value.slice(index + 1)).slice(0, cellCount);
42
+ return { nextValue: next, focusIndex: Math.min(index + 1, cellCount - 1) };
43
+ }
44
+
45
+ const arr = Array.from({ length: cellCount }, (_, i) => (i < value.length ? value[i] : ''));
46
+ for (let k = 0; k < text.length && index + k < cellCount; k++) {
47
+ arr[index + k] = text.charAt(k);
48
+ }
49
+ const next = arr
50
+ .filter((c) => c)
51
+ .join('')
52
+ .slice(0, cellCount);
53
+ const lastWritten = Math.min(index + text.length - 1, cellCount - 1);
54
+ const focusIndex = Math.min(Math.max(lastWritten, next.length - 1), cellCount - 1);
55
+ return { nextValue: next, focusIndex: Math.max(0, focusIndex) };
56
+ }
@@ -0,0 +1,37 @@
1
+ /** Strip to digits (default OTP behavior). */
2
+ export function filterDigits(input: string): string {
3
+ return input.replace(/\D/g, '');
4
+ }
5
+
6
+ /** Keep only characters present in `allowed` (treat as a set of UTF-16 code units). */
7
+ export function filterAllowedCharacters(allowed: string) {
8
+ const allowedSet = new Set<string>();
9
+ for (let i = 0; i < allowed.length; i++) {
10
+ allowedSet.add(allowed.charAt(i));
11
+ }
12
+ return (input: string) => {
13
+ let out = '';
14
+ for (let i = 0; i < input.length; i++) {
15
+ const ch = input.charAt(i);
16
+ if (allowedSet.has(ch)) {
17
+ out += ch;
18
+ }
19
+ }
20
+ return out;
21
+ };
22
+ }
23
+
24
+ /** Keep only characters matching `re` (tested per UTF-16 code unit). */
25
+ export function filterByRegExp(re: RegExp) {
26
+ return (input: string) => {
27
+ let out = '';
28
+ for (let i = 0; i < input.length; i++) {
29
+ const ch = input.charAt(i);
30
+ re.lastIndex = 0;
31
+ if (re.test(ch)) {
32
+ out += ch;
33
+ }
34
+ }
35
+ return out;
36
+ };
37
+ }