@r5n/otp-react-native 0.0.0-stage → 8.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 +104 -0
- package/LICENSE +21 -0
- package/README.md +227 -2
- package/lib/commonjs/Cell.js +140 -0
- package/lib/commonjs/Cell.js.map +1 -0
- package/lib/commonjs/OtpInput.js +129 -0
- package/lib/commonjs/OtpInput.js.map +1 -0
- package/lib/commonjs/accessibility.js +90 -0
- package/lib/commonjs/accessibility.js.map +1 -0
- package/lib/commonjs/clipboard.js +197 -0
- package/lib/commonjs/clipboard.js.map +1 -0
- package/lib/commonjs/dev.js +63 -0
- package/lib/commonjs/dev.js.map +1 -0
- package/lib/commonjs/hiddenInput.js +95 -0
- package/lib/commonjs/hiddenInput.js.map +1 -0
- package/lib/commonjs/index.js +53 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/legacy.js +217 -0
- package/lib/commonjs/legacy.js.map +1 -0
- package/lib/commonjs/managedProps.js +73 -0
- package/lib/commonjs/managedProps.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/commonjs/types.js +45 -0
- package/lib/commonjs/types.js.map +1 -0
- package/lib/commonjs/useOtpController.js +70 -0
- package/lib/commonjs/useOtpController.js.map +1 -0
- package/lib/commonjs/useOtpInput.js +251 -0
- package/lib/commonjs/useOtpInput.js.map +1 -0
- package/lib/module/Cell.js +103 -0
- package/lib/module/Cell.js.map +1 -0
- package/lib/module/OtpInput.js +94 -0
- package/lib/module/OtpInput.js.map +1 -0
- package/lib/module/accessibility.js +49 -0
- package/lib/module/accessibility.js.map +1 -0
- package/lib/module/clipboard.js +156 -0
- package/lib/module/clipboard.js.map +1 -0
- package/lib/module/dev.js +22 -0
- package/lib/module/dev.js.map +1 -0
- package/lib/module/hiddenInput.js +54 -0
- package/lib/module/hiddenInput.js.map +1 -0
- package/lib/module/index.js +14 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/legacy.js +187 -0
- package/lib/module/legacy.js.map +1 -0
- package/lib/module/managedProps.js +32 -0
- package/lib/module/managedProps.js.map +1 -0
- package/lib/module/types.js +3 -0
- package/lib/module/types.js.map +1 -0
- package/lib/module/useOtpController.js +29 -0
- package/lib/module/useOtpController.js.map +1 -0
- package/lib/module/useOtpInput.js +216 -0
- package/lib/module/useOtpInput.js.map +1 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/commonjs/src/Cell.d.ts +39 -0
- package/lib/typescript/commonjs/src/Cell.d.ts.map +1 -0
- package/lib/typescript/commonjs/src/OtpInput.d.ts +12 -0
- package/lib/typescript/commonjs/src/OtpInput.d.ts.map +1 -0
- package/lib/typescript/commonjs/src/accessibility.d.ts +39 -0
- package/lib/typescript/commonjs/src/accessibility.d.ts.map +1 -0
- package/lib/typescript/commonjs/src/clipboard.d.ts +9 -0
- package/lib/typescript/commonjs/src/clipboard.d.ts.map +1 -0
- package/lib/typescript/commonjs/src/dev.d.ts +13 -0
- package/lib/typescript/commonjs/src/dev.d.ts.map +1 -0
- package/lib/typescript/commonjs/src/hiddenInput.d.ts +31 -0
- package/lib/typescript/commonjs/src/hiddenInput.d.ts.map +1 -0
- package/lib/typescript/commonjs/src/index.d.ts +11 -0
- package/lib/typescript/commonjs/src/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/src/legacy.d.ts +78 -0
- package/lib/typescript/commonjs/src/legacy.d.ts.map +1 -0
- package/lib/typescript/commonjs/src/managedProps.d.ts +5 -0
- package/lib/typescript/commonjs/src/managedProps.d.ts.map +1 -0
- package/lib/typescript/commonjs/src/types.d.ts +262 -0
- package/lib/typescript/commonjs/src/types.d.ts.map +1 -0
- package/lib/typescript/commonjs/src/useOtpController.d.ts +28 -0
- package/lib/typescript/commonjs/src/useOtpController.d.ts.map +1 -0
- package/lib/typescript/commonjs/src/useOtpInput.d.ts +22 -0
- package/lib/typescript/commonjs/src/useOtpInput.d.ts.map +1 -0
- package/lib/typescript/module/src/Cell.d.ts +39 -0
- package/lib/typescript/module/src/Cell.d.ts.map +1 -0
- package/lib/typescript/module/src/OtpInput.d.ts +12 -0
- package/lib/typescript/module/src/OtpInput.d.ts.map +1 -0
- package/lib/typescript/module/src/accessibility.d.ts +39 -0
- package/lib/typescript/module/src/accessibility.d.ts.map +1 -0
- package/lib/typescript/module/src/clipboard.d.ts +9 -0
- package/lib/typescript/module/src/clipboard.d.ts.map +1 -0
- package/lib/typescript/module/src/dev.d.ts +13 -0
- package/lib/typescript/module/src/dev.d.ts.map +1 -0
- package/lib/typescript/module/src/hiddenInput.d.ts +31 -0
- package/lib/typescript/module/src/hiddenInput.d.ts.map +1 -0
- package/lib/typescript/module/src/index.d.ts +11 -0
- package/lib/typescript/module/src/index.d.ts.map +1 -0
- package/lib/typescript/module/src/legacy.d.ts +78 -0
- package/lib/typescript/module/src/legacy.d.ts.map +1 -0
- package/lib/typescript/module/src/managedProps.d.ts +5 -0
- package/lib/typescript/module/src/managedProps.d.ts.map +1 -0
- package/lib/typescript/module/src/types.d.ts +262 -0
- package/lib/typescript/module/src/types.d.ts.map +1 -0
- package/lib/typescript/module/src/useOtpController.d.ts +28 -0
- package/lib/typescript/module/src/useOtpController.d.ts.map +1 -0
- package/lib/typescript/module/src/useOtpInput.d.ts +22 -0
- package/lib/typescript/module/src/useOtpInput.d.ts.map +1 -0
- package/package.json +102 -4
- package/src/Cell.tsx +146 -0
- package/src/OtpInput.tsx +120 -0
- package/src/accessibility.ts +86 -0
- package/src/clipboard.ts +232 -0
- package/src/dev.ts +33 -0
- package/src/hiddenInput.ts +80 -0
- package/src/index.ts +38 -0
- package/src/legacy.tsx +317 -0
- package/src/managedProps.ts +29 -0
- package/src/types.ts +299 -0
- package/src/useOtpController.ts +58 -0
- package/src/useOtpInput.ts +313 -0
package/src/types.ts
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import type { OtpController, OtpOptions, OtpSnapshot } from '@r5n/otp-core';
|
|
2
|
+
import type { ComponentRef, ReactNode, RefObject } from 'react';
|
|
3
|
+
import type {
|
|
4
|
+
ColorValue,
|
|
5
|
+
StyleProp,
|
|
6
|
+
TextInput,
|
|
7
|
+
TextInputProps,
|
|
8
|
+
TextStyle,
|
|
9
|
+
ViewProps,
|
|
10
|
+
ViewStyle,
|
|
11
|
+
} from 'react-native';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Layout direction of the row of cells. The value is always stored in logical order; only the
|
|
15
|
+
* row is mirrored.
|
|
16
|
+
* - `'ltr'` (default): codes read left to right, also in right-to-left apps.
|
|
17
|
+
* - `'rtl'`: the first character is in the right-most cell.
|
|
18
|
+
* - `'auto'`: follows `I18nManager.isRTL`.
|
|
19
|
+
*/
|
|
20
|
+
export type OtpInputDirection = 'ltr' | 'rtl' | 'auto';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* OS one-time-code autofill. `'auto'` (or its alias `'one-time-code'`, the value
|
|
24
|
+
* `@r5n/otp-react` uses) offers SMS codes (iOS `oneTimeCode`, Android `sms-otp`); `'off'` opts the
|
|
25
|
+
* field out of autofill.
|
|
26
|
+
*/
|
|
27
|
+
export type OtpInputAutoComplete = 'auto' | 'one-time-code' | 'off';
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Clipboard access injected by the app, so the package needs no native clipboard module. Works
|
|
31
|
+
* with `@react-native-clipboard/clipboard` (pass the default export) and `expo-clipboard`
|
|
32
|
+
* (`{ getString: Clipboard.getStringAsync, hasString: Clipboard.hasStringAsync }`).
|
|
33
|
+
*/
|
|
34
|
+
export interface OtpClipboardProvider {
|
|
35
|
+
/** Reads the clipboard text. Never written to: the component only reads. */
|
|
36
|
+
getString(): Promise<string>;
|
|
37
|
+
/**
|
|
38
|
+
* Optional cheap check run before `getString`. Returning `false` skips the read, which avoids
|
|
39
|
+
* the iOS 16+ paste prompt when the clipboard has no text. iOS can report no text while it is
|
|
40
|
+
* still presenting the keyboard, so after an empty result on focus or on return to the
|
|
41
|
+
* foreground the clipboard is checked once more about 800 ms later.
|
|
42
|
+
*/
|
|
43
|
+
hasString?: (() => Promise<boolean>) | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* Also read every `intervalMs` milliseconds while the input is focused and incomplete. Without
|
|
46
|
+
* it the clipboard is read only on focus and when the app returns to the foreground (plus the
|
|
47
|
+
* one later check described under `hasString`).
|
|
48
|
+
*/
|
|
49
|
+
intervalMs?: number | undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Texts read by screen readers. Defaults are English; override them to localise. Announcements
|
|
54
|
+
* are queued behind speech in progress on iOS.
|
|
55
|
+
*/
|
|
56
|
+
export interface OtpInputAccessibilityTexts {
|
|
57
|
+
/** Announced when the code becomes complete; `false` disables it. Default `'Code complete'`. */
|
|
58
|
+
complete?: string | false | undefined;
|
|
59
|
+
/**
|
|
60
|
+
* Announced when `error` turns on, and part of the field's accessibility value while it stays
|
|
61
|
+
* on; `false` disables it. Default `'Incorrect code'`. Only a change from `false` to `true` is
|
|
62
|
+
* announced: turn `error` off when the user edits the code, so a second wrong code is announced
|
|
63
|
+
* too.
|
|
64
|
+
*/
|
|
65
|
+
error?: string | false | undefined;
|
|
66
|
+
/** Progress part of the field's accessibility value. Default `` `${filled} of ${length} entered` ``. */
|
|
67
|
+
progress?: ((filled: number, length: number) => string) | undefined;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Instance of the hidden native `TextInput`. */
|
|
71
|
+
export type OtpTextInputRef = ComponentRef<typeof TextInput>;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Props of the hidden `TextInput` that the component manages, or that would break paste, autofill
|
|
75
|
+
* or screen readers on it (P1). Passed anyway (from JavaScript or through a cast), they are
|
|
76
|
+
* dropped with a development warning (C:S3-6).
|
|
77
|
+
*/
|
|
78
|
+
export type OtpTextInputManagedProp =
|
|
79
|
+
| 'value'
|
|
80
|
+
| 'defaultValue'
|
|
81
|
+
| 'maxLength'
|
|
82
|
+
| 'selection'
|
|
83
|
+
| 'editable'
|
|
84
|
+
| 'readOnly'
|
|
85
|
+
| 'caretHidden'
|
|
86
|
+
| 'contextMenuHidden'
|
|
87
|
+
| 'pointerEvents'
|
|
88
|
+
| 'selectTextOnFocus'
|
|
89
|
+
| 'clearTextOnFocus'
|
|
90
|
+
| 'inputMode';
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Extra props for the hidden `TextInput` (escape hatch). The props in `OtpTextInputManagedProp`
|
|
94
|
+
* cannot be passed. Overriding the functional props it sets (style,
|
|
95
|
+
* autofill, keyboard) is possible but voids the platform guarantees described in the docs.
|
|
96
|
+
* `secureTextEntry` is allowed as an opt-in that hides the characters from screen readers too, at
|
|
97
|
+
* the cost described in the accessibility docs (iOS clears a secure field when typing resumes after
|
|
98
|
+
* refocusing, and may offer password AutoFill).
|
|
99
|
+
*/
|
|
100
|
+
export type OtpTextInputProps = Omit<TextInputProps, OtpTextInputManagedProp>;
|
|
101
|
+
|
|
102
|
+
/** Props spread onto the hidden `TextInput` by {@link UseOtpInputResult.inputProps}. */
|
|
103
|
+
export type OtpHiddenInputProps = TextInputProps & { ref: RefObject<OtpTextInputRef | null> };
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Props of a cell's `View` that keep it out of touches and screen readers (P4). Passed in
|
|
107
|
+
* `cellProps` anyway, they are dropped with a development warning (C:S3-6).
|
|
108
|
+
*/
|
|
109
|
+
export type OtpCellManagedProp =
|
|
110
|
+
| 'children'
|
|
111
|
+
| 'style'
|
|
112
|
+
| 'testID'
|
|
113
|
+
| 'pointerEvents'
|
|
114
|
+
| 'aria-hidden'
|
|
115
|
+
| 'accessible'
|
|
116
|
+
| 'accessibilityElementsHidden'
|
|
117
|
+
| 'importantForAccessibility';
|
|
118
|
+
|
|
119
|
+
/** Extra props applied to the `View` of every cell. */
|
|
120
|
+
export type OtpCellProps = Omit<ViewProps, OtpCellManagedProp>;
|
|
121
|
+
|
|
122
|
+
/** Props that hide a decorative view from touches and screen readers; see `decorationProps`. */
|
|
123
|
+
export interface OtpDecorationProps {
|
|
124
|
+
readonly pointerEvents: 'none';
|
|
125
|
+
readonly accessibilityElementsHidden: true;
|
|
126
|
+
readonly importantForAccessibility: 'no-hide-descendants';
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Render state of one cell: primitives only, so memoised cells re-render only when it changes. */
|
|
130
|
+
export interface OtpInputCellState {
|
|
131
|
+
/** Position of the cell, from 0, in logical order. */
|
|
132
|
+
readonly index: number;
|
|
133
|
+
/** The entered character, `''` when empty. Not masked: render `displayChar` to honour `mask`. */
|
|
134
|
+
readonly char: string;
|
|
135
|
+
/** What the default cell shows: the character, the mask glyph, the placeholder, or `''`. */
|
|
136
|
+
readonly displayChar: string;
|
|
137
|
+
readonly isFilled: boolean;
|
|
138
|
+
/** The caret is on this cell while the input is focused. */
|
|
139
|
+
readonly isActive: boolean;
|
|
140
|
+
/** `displayChar` is the placeholder. */
|
|
141
|
+
readonly isPlaceholder: boolean;
|
|
142
|
+
readonly isMasked: boolean;
|
|
143
|
+
readonly isError: boolean;
|
|
144
|
+
readonly isDisabled: boolean;
|
|
145
|
+
/** Index of the group (see `groups`) the cell belongs to. */
|
|
146
|
+
readonly groupIndex: number;
|
|
147
|
+
readonly isFirstInGroup: boolean;
|
|
148
|
+
readonly isLastInGroup: boolean;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Imperative API of {@link OtpInput} (via `ref`) and of {@link useOtpInput}. */
|
|
152
|
+
export interface OtpInputRef {
|
|
153
|
+
/** Focuses the hidden input (no-op while `disabled`). */
|
|
154
|
+
focus(): void;
|
|
155
|
+
blur(): void;
|
|
156
|
+
/**
|
|
157
|
+
* Empties the value. Fires `onChange('')` only when the value was not already empty. Never
|
|
158
|
+
* touches the clipboard.
|
|
159
|
+
*/
|
|
160
|
+
clear(): void;
|
|
161
|
+
/**
|
|
162
|
+
* Sets the value as if the user entered it: fires `onChange` when the value changes and, for a
|
|
163
|
+
* complete code, `onComplete` (in controlled mode, once the parent confirms it; see
|
|
164
|
+
* `onComplete`). `''` clears. Text longer than `length` (an SMS body) is searched for a code;
|
|
165
|
+
* otherwise only a bare code is set (`'12'`, `'123 456'`), and other text (`'Error: 15'`) is
|
|
166
|
+
* ignored: the value stays and no callback fires.
|
|
167
|
+
*/
|
|
168
|
+
setValue(value: string): void;
|
|
169
|
+
getValue(): string;
|
|
170
|
+
isFocused(): boolean;
|
|
171
|
+
/**
|
|
172
|
+
* The hidden native `TextInput` instance, for measuring or for native methods the component does
|
|
173
|
+
* not wrap. `null` before mount and after unmount. It reads the current instance on every access,
|
|
174
|
+
* so it stays valid after React re-runs the effects of a mounted input (StrictMode,
|
|
175
|
+
* `<Activity>`). The same name as `OtpInputRef.input` in `@r5n/otp-react` (W:#22). The component
|
|
176
|
+
* owns the value, selection and managed props: change those through this API, not on the
|
|
177
|
+
* instance.
|
|
178
|
+
*/
|
|
179
|
+
readonly input: OtpTextInputRef | null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Behaviour options shared by {@link OtpInput} and {@link useOtpInput}. */
|
|
183
|
+
export interface UseOtpInputOptions extends OtpOptions {
|
|
184
|
+
/**
|
|
185
|
+
* Controlled value. Updates from the parent never fire `onChange`; a change the parent does not
|
|
186
|
+
* accept is reverted on the next render. A parent update fires `onComplete` only to confirm a
|
|
187
|
+
* complete value the user just entered (see `onComplete`).
|
|
188
|
+
*/
|
|
189
|
+
value?: string | undefined;
|
|
190
|
+
/** Initial value when uncontrolled. Read once; never fires callbacks. */
|
|
191
|
+
defaultValue?: string | undefined;
|
|
192
|
+
/** Called once per visible change of the value, from the input event (never during render). */
|
|
193
|
+
onChange?: ((value: string) => void) | undefined;
|
|
194
|
+
/**
|
|
195
|
+
* Called when a user action, paste, autofill, clipboard autofill or `ref.setValue()` produces a
|
|
196
|
+
* different complete value. Uncontrolled: right after `onChange`. Controlled (`value` set): after
|
|
197
|
+
* the parent confirms that value, that is, once the next render passes it back as `value`; if
|
|
198
|
+
* the parent passes a different value instead, `onComplete` does not fire.
|
|
199
|
+
*/
|
|
200
|
+
onComplete?: ((value: string) => void) | undefined;
|
|
201
|
+
/** Focuses the input one frame after mount (deferred, so it survives navigation transitions). */
|
|
202
|
+
autoFocus?: boolean | undefined;
|
|
203
|
+
/** Makes the input non-editable and reports the disabled state to screen readers. */
|
|
204
|
+
disabled?: boolean | undefined;
|
|
205
|
+
/** Shows the error styles and announces `accessibilityTexts.error` when it turns on. */
|
|
206
|
+
error?: boolean | undefined;
|
|
207
|
+
/**
|
|
208
|
+
* Hides the characters in the cells: `true` shows `•`, a string shows that glyph (`''` means not
|
|
209
|
+
* masked). The value is not changed. Screen readers: on iOS the field's value then reports only
|
|
210
|
+
* progress, but typing echo and the field's text can still speak the characters on both
|
|
211
|
+
* platforms; pass `textInputProps={{ secureTextEntry: true }}` to hide them from assistive
|
|
212
|
+
* technology too (see `OtpTextInputProps`).
|
|
213
|
+
*/
|
|
214
|
+
mask?: boolean | string | undefined;
|
|
215
|
+
/**
|
|
216
|
+
* Shown in empty cells. A string of exactly `length` characters gives each cell its own
|
|
217
|
+
* character; any other string is shown whole in every empty cell.
|
|
218
|
+
*/
|
|
219
|
+
placeholder?: string | undefined;
|
|
220
|
+
/** Default `'auto'`. */
|
|
221
|
+
autoComplete?: OtpInputAutoComplete | undefined;
|
|
222
|
+
/** Default: `'number-pad'` for the numeric charset, `'default'` otherwise. */
|
|
223
|
+
keyboardType?: TextInputProps['keyboardType'];
|
|
224
|
+
/** Default `'ltr'`. */
|
|
225
|
+
direction?: OtpInputDirection | undefined;
|
|
226
|
+
/** Blurs the input (closing the keyboard) right after `onComplete`. Default `false`. */
|
|
227
|
+
blurOnComplete?: boolean | undefined;
|
|
228
|
+
/** Opt-in clipboard autofill. Default `false`: the clipboard is never read. */
|
|
229
|
+
clipboardAutofill?: false | OtpClipboardProvider | undefined;
|
|
230
|
+
/**
|
|
231
|
+
* Default `'One-time code, <length> digits'`: `digit(s)` for the numeric charset, `letter(s)` for
|
|
232
|
+
* alphabetic, `character(s)` otherwise (for example `'One-time code, 6 digits'`).
|
|
233
|
+
*/
|
|
234
|
+
accessibilityLabel?: string | undefined;
|
|
235
|
+
accessibilityHint?: string | undefined;
|
|
236
|
+
accessibilityTexts?: OtpInputAccessibilityTexts | undefined;
|
|
237
|
+
onFocus?: TextInputProps['onFocus'];
|
|
238
|
+
onBlur?: TextInputProps['onBlur'];
|
|
239
|
+
/** See {@link OtpTextInputProps}. */
|
|
240
|
+
textInputProps?: OtpTextInputProps | undefined;
|
|
241
|
+
/** Test ID of the hidden input; cells get `` `${testID}-cell-${index}` ``. */
|
|
242
|
+
testID?: string | undefined;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Everything needed to render a custom code input around the hidden `TextInput`. */
|
|
246
|
+
export interface UseOtpInputResult extends OtpInputRef {
|
|
247
|
+
/** Current state of the core controller (value, selection, slots, completion, focus). */
|
|
248
|
+
snapshot: OtpSnapshot;
|
|
249
|
+
/** Render state of every cell, with `mask`, `placeholder`, `error` and `disabled` applied. */
|
|
250
|
+
cells: readonly OtpInputCellState[];
|
|
251
|
+
/**
|
|
252
|
+
* Spread onto every cell and separator view: hides them from touches and screen readers, so the
|
|
253
|
+
* hidden input stays the only accessibility element (P4, W:#15).
|
|
254
|
+
*/
|
|
255
|
+
decorationProps: OtpDecorationProps;
|
|
256
|
+
/**
|
|
257
|
+
* Spread onto a `TextInput` rendered **last** inside the row, so it covers the cells and owns
|
|
258
|
+
* every tap, long-press paste, autofill and screen-reader focus.
|
|
259
|
+
*/
|
|
260
|
+
inputProps: OtpHiddenInputProps;
|
|
261
|
+
/** Style for the row that contains the cells and the input (`flexDirection` and `direction`). */
|
|
262
|
+
rowStyle: ViewStyle;
|
|
263
|
+
/** For a `Pressable` around custom cells when the input does not cover them. */
|
|
264
|
+
pressableProps: { onPress: () => void; disabled: boolean; accessible: false };
|
|
265
|
+
/** The underlying `@r5n/otp-core` controller (advanced use). */
|
|
266
|
+
controller: OtpController;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Props of {@link OtpInput}. */
|
|
270
|
+
export interface OtpInputProps extends UseOtpInputOptions {
|
|
271
|
+
/** Row that contains the cells. */
|
|
272
|
+
style?: StyleProp<ViewStyle>;
|
|
273
|
+
cellStyle?: StyleProp<ViewStyle>;
|
|
274
|
+
/** Applied to the active cell while focused. Precedence: cell < filled < focused < error. */
|
|
275
|
+
focusedCellStyle?: StyleProp<ViewStyle>;
|
|
276
|
+
filledCellStyle?: StyleProp<ViewStyle>;
|
|
277
|
+
errorCellStyle?: StyleProp<ViewStyle>;
|
|
278
|
+
/**
|
|
279
|
+
* Style of the cell text. The default colour follows the system colour scheme (`useColorScheme`:
|
|
280
|
+
* near-black in light mode, white in dark mode); set `color` here when the app's theme does not
|
|
281
|
+
* follow the system scheme.
|
|
282
|
+
*/
|
|
283
|
+
cellTextStyle?: StyleProp<TextStyle>;
|
|
284
|
+
/** Colour of placeholder characters (applied after `cellTextStyle`). Default `'#8E8E93'`. */
|
|
285
|
+
placeholderTextColor?: ColorValue | undefined;
|
|
286
|
+
/** Style of the spacer between groups (see `groups`). */
|
|
287
|
+
separatorStyle?: StyleProp<ViewStyle>;
|
|
288
|
+
/** Replaces the content of every cell; the cell styles are then not applied. */
|
|
289
|
+
renderCell?: ((state: OtpInputCellState) => ReactNode) | undefined;
|
|
290
|
+
/** Content of the spacer between groups; `groupIndex` is the group before it. */
|
|
291
|
+
renderSeparator?: ((groupIndex: number) => ReactNode) | undefined;
|
|
292
|
+
cellProps?: OtpCellProps | undefined;
|
|
293
|
+
/**
|
|
294
|
+
* Largest font scale of the cell text (Dynamic Type, font size settings). Default `2` (200%,
|
|
295
|
+
* WCAG 1.4.4). The text shrinks to fit its cell (`adjustsFontSizeToFit`, down to half size on
|
|
296
|
+
* iOS), so long codes at the largest sizes get smaller digits instead of clipped ones.
|
|
297
|
+
*/
|
|
298
|
+
maxFontSizeMultiplier?: number | undefined;
|
|
299
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { OtpController, OtpControllerOptions, OtpSnapshot } from '@r5n/otp-core';
|
|
2
|
+
import { useEffect, useLayoutEffect, useState, useSyncExternalStore } from 'react';
|
|
3
|
+
|
|
4
|
+
/** Controllers destroyed by an effect cleanup. */
|
|
5
|
+
const destroyed = new WeakSet<OtpController>();
|
|
6
|
+
|
|
7
|
+
/** Whether an effect cleanup destroyed `controller` (it is about to be replaced). */
|
|
8
|
+
export const isDestroyed = (controller: OtpController): boolean => destroyed.has(controller);
|
|
9
|
+
|
|
10
|
+
/** Creates a controller; `seed` is the last snapshot of a destroyed one being replaced. */
|
|
11
|
+
export type CreateController = (seed?: OtpSnapshot) => OtpController;
|
|
12
|
+
|
|
13
|
+
interface ControllerBinding {
|
|
14
|
+
controller: OtpController;
|
|
15
|
+
snapshot: OtpSnapshot;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Owns the core controller of one mounted input (`rn-platform.md` Q5).
|
|
20
|
+
*
|
|
21
|
+
* - Created in the state initialiser: pure, no subscriptions, so double rendering is harmless.
|
|
22
|
+
* - Destroyed on unmount. When React runs the effects of a component that is still mounted again
|
|
23
|
+
* (StrictMode in development, an `<Activity>` becoming visible), the destroyed controller is
|
|
24
|
+
* replaced by a new one seeded with its last value, so the input never stays dead. Focus is not
|
|
25
|
+
* carried over: the caller reads it from the native input (C:S3-1).
|
|
26
|
+
* - Props are reconciled after every render with `update()` from a layout effect, never during
|
|
27
|
+
* render (core B6). Running it after every render reverts an optimistic edit that a controlled
|
|
28
|
+
* parent did not accept, and confirms a complete one it did: `update()` calls no `onChange`, and
|
|
29
|
+
* calls `onComplete` only for that confirmation (C:S3-4).
|
|
30
|
+
* - Read through `useSyncExternalStore`; the snapshot is stable until something changes.
|
|
31
|
+
*
|
|
32
|
+
* `create` must be stable (it should read the latest props from a ref).
|
|
33
|
+
*/
|
|
34
|
+
export const useOtpController = (
|
|
35
|
+
create: CreateController,
|
|
36
|
+
reconcile: Partial<OtpControllerOptions>,
|
|
37
|
+
): ControllerBinding => {
|
|
38
|
+
const [controller, setController] = useState<OtpController>(() => create());
|
|
39
|
+
useEffect(() => {
|
|
40
|
+
if (isDestroyed(controller)) {
|
|
41
|
+
setController(create(controller.getSnapshot()));
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
return () => {
|
|
45
|
+
destroyed.add(controller);
|
|
46
|
+
controller.destroy();
|
|
47
|
+
};
|
|
48
|
+
}, [controller, create]);
|
|
49
|
+
useLayoutEffect(() => {
|
|
50
|
+
controller.update(reconcile);
|
|
51
|
+
});
|
|
52
|
+
const snapshot = useSyncExternalStore(
|
|
53
|
+
controller.subscribe,
|
|
54
|
+
controller.getSnapshot,
|
|
55
|
+
controller.getSnapshot,
|
|
56
|
+
);
|
|
57
|
+
return { controller, snapshot };
|
|
58
|
+
};
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { createOtpController, type OtpController } from '@r5n/otp-core';
|
|
2
|
+
import { type RefObject, useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react';
|
|
3
|
+
import { I18nManager, type TextInputProps, type ViewStyle } from 'react-native';
|
|
4
|
+
import {
|
|
5
|
+
accessibilityValue,
|
|
6
|
+
announce,
|
|
7
|
+
announcementText,
|
|
8
|
+
defaultLabel,
|
|
9
|
+
useAnnounceOnRise,
|
|
10
|
+
} from './accessibility';
|
|
11
|
+
import { DECORATION_PROPS } from './Cell';
|
|
12
|
+
import { useClipboardAutofill } from './clipboard';
|
|
13
|
+
import { forbiddenKeys, warnOnce, withoutKeys } from './dev';
|
|
14
|
+
import { HIDDEN_INPUT_STYLE, hiddenInputProps } from './hiddenInput';
|
|
15
|
+
import { TEXT_INPUT_MANAGED_PROPS } from './managedProps';
|
|
16
|
+
import type {
|
|
17
|
+
OtpHiddenInputProps,
|
|
18
|
+
OtpInputCellState,
|
|
19
|
+
OtpInputRef,
|
|
20
|
+
OtpTextInputRef,
|
|
21
|
+
UseOtpInputOptions,
|
|
22
|
+
UseOtpInputResult,
|
|
23
|
+
} from './types';
|
|
24
|
+
import { type CreateController, useOtpController } from './useOtpController';
|
|
25
|
+
|
|
26
|
+
const MASK_GLYPH = '•';
|
|
27
|
+
|
|
28
|
+
type SelectionChangeEvent = Parameters<NonNullable<TextInputProps['onSelectionChange']>>[0];
|
|
29
|
+
type FocusEvent = Parameters<NonNullable<TextInputProps['onFocus']>>[0];
|
|
30
|
+
type BlurEvent = Parameters<NonNullable<TextInputProps['onBlur']>>[0];
|
|
31
|
+
|
|
32
|
+
/** React Native reports UTF-16 offsets; core counts code points (core T5). */
|
|
33
|
+
const toCodePoints = (text: string, offset: number): number =>
|
|
34
|
+
Array.from(text.slice(0, offset)).length;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Keeps the caret at the end (orchestrator decisions G12 and P3): typing always appends and
|
|
38
|
+
* Backspace removes the last character, whatever cell was tapped. A range (Select All before
|
|
39
|
+
* Paste) is mirrored instead, so the cells show it and core replaces it.
|
|
40
|
+
*/
|
|
41
|
+
const followSelection = (
|
|
42
|
+
controller: OtpController,
|
|
43
|
+
input: RefObject<OtpTextInputRef | null>,
|
|
44
|
+
{ start, end }: { start: number; end: number },
|
|
45
|
+
): void => {
|
|
46
|
+
const { value } = controller.getSnapshot();
|
|
47
|
+
if (start !== end) {
|
|
48
|
+
controller.setSelection({ start: toCodePoints(value, start), end: toCodePoints(value, end) });
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
// Only a caret before the end is pinned. One beyond it belongs to a native edit whose change
|
|
52
|
+
// event has not arrived yet: the order of change and selection events differs per platform
|
|
53
|
+
// (`rn-platform.md` Q5). `setSelection` is guarded because the `TextInput` mock of React Native's
|
|
54
|
+
// Jest preset (0.86 and later) has none, and a custom input given to `useOtpInput` may not; a
|
|
55
|
+
// stale call (an edit already queued natively) is dropped by React Native's event-count check.
|
|
56
|
+
if (end < value.length) input.current?.setSelection?.(value.length, value.length);
|
|
57
|
+
const caret = Array.from(value).length;
|
|
58
|
+
controller.setSelection({ start: caret, end: caret });
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Headless code input: the state, cell render data and hidden `TextInput` props behind
|
|
63
|
+
* `OtpInput`, for building a custom layout.
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```tsx
|
|
67
|
+
* const otp = useOtpInput({ length: 6, onComplete: verify });
|
|
68
|
+
* return (
|
|
69
|
+
* <View style={otp.rowStyle}>
|
|
70
|
+
* {otp.cells.map((cell) => (
|
|
71
|
+
* <View key={cell.index} {...otp.decorationProps}>
|
|
72
|
+
* <Text>{cell.displayChar}</Text>
|
|
73
|
+
* </View>
|
|
74
|
+
* ))}
|
|
75
|
+
* <TextInput {...otp.inputProps} />
|
|
76
|
+
* </View>
|
|
77
|
+
* );
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
export function useOtpInput(options: UseOtpInputOptions): UseOtpInputResult {
|
|
81
|
+
const latest = useRef(options);
|
|
82
|
+
useLayoutEffect(() => {
|
|
83
|
+
latest.current = options;
|
|
84
|
+
});
|
|
85
|
+
const inputRef = useRef<OtpTextInputRef | null>(null);
|
|
86
|
+
|
|
87
|
+
const create = useCallback<CreateController>((seed) => {
|
|
88
|
+
const { length, charset, casing, groups, value, defaultValue } = latest.current;
|
|
89
|
+
const controller = createOtpController({
|
|
90
|
+
length,
|
|
91
|
+
charset,
|
|
92
|
+
casing,
|
|
93
|
+
groups,
|
|
94
|
+
value,
|
|
95
|
+
defaultValue: seed ? seed.value : defaultValue,
|
|
96
|
+
// Callbacks read the latest props, so a new `onChange` identity never re-creates anything.
|
|
97
|
+
onChange: (next) => latest.current.onChange?.(next),
|
|
98
|
+
onComplete: (next) => {
|
|
99
|
+
const current = latest.current;
|
|
100
|
+
current.onComplete?.(next);
|
|
101
|
+
announce(announcementText(current.accessibilityTexts?.complete, 'complete'));
|
|
102
|
+
if (current.blurOnComplete) inputRef.current?.blur();
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
// A replacement after revival takes its focus from the native input, not from the destroyed
|
|
106
|
+
// controller: the input may have blurred while its events went nowhere (C:S3-1).
|
|
107
|
+
if (seed !== undefined && inputRef.current?.isFocused?.() === true) controller.setFocused(true);
|
|
108
|
+
return controller;
|
|
109
|
+
}, []);
|
|
110
|
+
|
|
111
|
+
const {
|
|
112
|
+
length,
|
|
113
|
+
charset,
|
|
114
|
+
casing,
|
|
115
|
+
groups,
|
|
116
|
+
value,
|
|
117
|
+
autoFocus,
|
|
118
|
+
disabled,
|
|
119
|
+
error,
|
|
120
|
+
mask,
|
|
121
|
+
placeholder,
|
|
122
|
+
direction,
|
|
123
|
+
autoComplete = 'auto',
|
|
124
|
+
keyboardType,
|
|
125
|
+
accessibilityLabel,
|
|
126
|
+
accessibilityHint,
|
|
127
|
+
accessibilityTexts,
|
|
128
|
+
textInputProps,
|
|
129
|
+
testID,
|
|
130
|
+
} = options;
|
|
131
|
+
const { controller, snapshot } = useOtpController(create, {
|
|
132
|
+
length,
|
|
133
|
+
charset,
|
|
134
|
+
casing,
|
|
135
|
+
groups,
|
|
136
|
+
value,
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
useEffect(() => {
|
|
140
|
+
if (!autoFocus) return;
|
|
141
|
+
// Deferred by a frame: focusing during a navigation transition often opens no keyboard
|
|
142
|
+
// (`rn-platform.md` Q2).
|
|
143
|
+
const frame = requestAnimationFrame(() => {
|
|
144
|
+
if (!latest.current.disabled) inputRef.current?.focus();
|
|
145
|
+
});
|
|
146
|
+
return () => cancelAnimationFrame(frame);
|
|
147
|
+
}, [autoFocus]);
|
|
148
|
+
|
|
149
|
+
useClipboardAutofill(controller, options.clipboardAutofill);
|
|
150
|
+
|
|
151
|
+
const blockedInputProps = forbiddenKeys(textInputProps, TEXT_INPUT_MANAGED_PROPS);
|
|
152
|
+
const blocked = blockedInputProps.join(', ');
|
|
153
|
+
useEffect(() => {
|
|
154
|
+
if (!__DEV__ || blocked === '') return;
|
|
155
|
+
warnOnce(
|
|
156
|
+
`textInputProps:${blocked}`,
|
|
157
|
+
`${blocked
|
|
158
|
+
.split(', ')
|
|
159
|
+
.map((key) => `textInputProps.${key}`)
|
|
160
|
+
.join(', ')} ignored: the ` +
|
|
161
|
+
'component manages these props, or they break paste, autofill or screen readers on the ' +
|
|
162
|
+
'hidden input (C:S3-6).',
|
|
163
|
+
);
|
|
164
|
+
}, [blocked]);
|
|
165
|
+
|
|
166
|
+
const controlled = value !== undefined;
|
|
167
|
+
const wasControlled = useRef(controlled);
|
|
168
|
+
const readOnlyValue = controlled && options.onChange === undefined && disabled !== true;
|
|
169
|
+
useEffect(() => {
|
|
170
|
+
if (!__DEV__) return;
|
|
171
|
+
if (readOnlyValue) {
|
|
172
|
+
warnOnce(
|
|
173
|
+
'value-without-onChange',
|
|
174
|
+
'`value` was passed without `onChange`, so every edit is reverted. Pass `onChange`, ' +
|
|
175
|
+
'use `defaultValue` for an uncontrolled input, or set `disabled` (W:#21).',
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
if (controlled !== wasControlled.current) {
|
|
179
|
+
warnOnce(
|
|
180
|
+
'controlled-switch',
|
|
181
|
+
`an input switched from ${wasControlled.current ? 'controlled' : 'uncontrolled'} to ` +
|
|
182
|
+
`${controlled ? 'controlled' : 'uncontrolled'}. Keep \`value\` either always defined or ` +
|
|
183
|
+
'always undefined for the lifetime of the input (W:#21).',
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
wasControlled.current = controlled;
|
|
187
|
+
}, [readOnlyValue, controlled]);
|
|
188
|
+
|
|
189
|
+
const errorText = announcementText(accessibilityTexts?.error, 'error');
|
|
190
|
+
useAnnounceOnRise(error === true, errorText);
|
|
191
|
+
|
|
192
|
+
// `input` is a getter on the result and on `OtpInput`'s handle, read live (W:#22).
|
|
193
|
+
const actions = useMemo<Omit<OtpInputRef, 'input'>>(
|
|
194
|
+
() => ({
|
|
195
|
+
focus: () => {
|
|
196
|
+
if (!latest.current.disabled) inputRef.current?.focus();
|
|
197
|
+
},
|
|
198
|
+
blur: () => inputRef.current?.blur(),
|
|
199
|
+
clear: () => controller.clear(),
|
|
200
|
+
setValue: (next) => controller.setValue(next),
|
|
201
|
+
getValue: () => controller.getSnapshot().value,
|
|
202
|
+
isFocused: () => controller.getSnapshot().isFocused,
|
|
203
|
+
}),
|
|
204
|
+
[controller],
|
|
205
|
+
);
|
|
206
|
+
|
|
207
|
+
const handlers = useMemo(
|
|
208
|
+
() => ({
|
|
209
|
+
onChangeText: (text: string): void => {
|
|
210
|
+
// No selection: the caret is pinned to the end, which lets core locate the edit (core B2).
|
|
211
|
+
controller.input(text);
|
|
212
|
+
latest.current.textInputProps?.onChangeText?.(text);
|
|
213
|
+
},
|
|
214
|
+
onSelectionChange: (event: SelectionChangeEvent): void => {
|
|
215
|
+
followSelection(controller, inputRef, event.nativeEvent.selection);
|
|
216
|
+
latest.current.textInputProps?.onSelectionChange?.(event);
|
|
217
|
+
},
|
|
218
|
+
onFocus: (event: FocusEvent): void => {
|
|
219
|
+
controller.setFocused(true);
|
|
220
|
+
latest.current.onFocus?.(event);
|
|
221
|
+
latest.current.textInputProps?.onFocus?.(event);
|
|
222
|
+
},
|
|
223
|
+
onBlur: (event: BlurEvent): void => {
|
|
224
|
+
controller.setFocused(false);
|
|
225
|
+
latest.current.onBlur?.(event);
|
|
226
|
+
latest.current.textInputProps?.onBlur?.(event);
|
|
227
|
+
},
|
|
228
|
+
}),
|
|
229
|
+
[controller],
|
|
230
|
+
);
|
|
231
|
+
|
|
232
|
+
const glyph =
|
|
233
|
+
mask === true ? MASK_GLYPH : typeof mask === 'string' && mask !== '' ? mask : undefined;
|
|
234
|
+
const isError = error === true;
|
|
235
|
+
const isDisabled = disabled === true;
|
|
236
|
+
const { slots, options: resolved } = snapshot;
|
|
237
|
+
|
|
238
|
+
const cells = useMemo(() => {
|
|
239
|
+
const hints = Array.from(placeholder ?? '');
|
|
240
|
+
const perCell = hints.length === resolved.length;
|
|
241
|
+
return slots.map((slot): OtpInputCellState => {
|
|
242
|
+
const hint = perCell ? (hints[slot.index] ?? '') : (placeholder ?? '');
|
|
243
|
+
return Object.freeze({
|
|
244
|
+
index: slot.index,
|
|
245
|
+
char: slot.char,
|
|
246
|
+
displayChar: slot.isFilled ? (glyph ?? slot.char) : hint,
|
|
247
|
+
isFilled: slot.isFilled,
|
|
248
|
+
isActive: slot.isActive,
|
|
249
|
+
isPlaceholder: !slot.isFilled && hint !== '',
|
|
250
|
+
isMasked: glyph !== undefined,
|
|
251
|
+
isError,
|
|
252
|
+
isDisabled,
|
|
253
|
+
groupIndex: slot.groupIndex,
|
|
254
|
+
isFirstInGroup: slot.isFirstInGroup,
|
|
255
|
+
isLastInGroup: slot.isLastInGroup,
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
}, [slots, resolved.length, placeholder, glyph, isError, isDisabled]);
|
|
259
|
+
|
|
260
|
+
const rtl = direction === 'rtl' || (direction === 'auto' && I18nManager.isRTL);
|
|
261
|
+
const rowStyle = useMemo<ViewStyle>(
|
|
262
|
+
() => ({ flexDirection: 'row', direction: rtl ? 'rtl' : 'ltr' }),
|
|
263
|
+
[rtl],
|
|
264
|
+
);
|
|
265
|
+
|
|
266
|
+
// Managed props are dropped, so none can re-enable `maxLength` (G1), `caretHidden` or the
|
|
267
|
+
// other P1-forbidden props (C:S3-6).
|
|
268
|
+
const extraInputProps = withoutKeys(textInputProps, blockedInputProps);
|
|
269
|
+
const inputProps: OtpHiddenInputProps = {
|
|
270
|
+
...hiddenInputProps({ options: resolved, autoComplete, keyboardType }),
|
|
271
|
+
...extraInputProps,
|
|
272
|
+
...handlers,
|
|
273
|
+
ref: inputRef,
|
|
274
|
+
// Controlled: rejected characters never stay in the native buffer (G7).
|
|
275
|
+
value: snapshot.value,
|
|
276
|
+
editable: !isDisabled,
|
|
277
|
+
style: [textInputProps?.style, HIDDEN_INPUT_STYLE],
|
|
278
|
+
accessibilityLabel:
|
|
279
|
+
accessibilityLabel ?? textInputProps?.accessibilityLabel ?? defaultLabel(resolved),
|
|
280
|
+
accessibilityHint: accessibilityHint ?? textInputProps?.accessibilityHint,
|
|
281
|
+
accessibilityState: { ...textInputProps?.accessibilityState, disabled: isDisabled },
|
|
282
|
+
accessibilityValue: accessibilityValue(
|
|
283
|
+
snapshot.value,
|
|
284
|
+
resolved.length,
|
|
285
|
+
glyph !== undefined,
|
|
286
|
+
isError ? errorText : '',
|
|
287
|
+
accessibilityTexts,
|
|
288
|
+
),
|
|
289
|
+
testID: testID ?? textInputProps?.testID,
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
// No object spread here: a Babel setup that compiles it to `Object.assign` reads the `input`
|
|
293
|
+
// getter once, so `input` would stay `null` (W:#22). React Native's preset (0.86 and later) leaves
|
|
294
|
+
// object spread alone, but other toolchains might not.
|
|
295
|
+
return {
|
|
296
|
+
focus: actions.focus,
|
|
297
|
+
blur: actions.blur,
|
|
298
|
+
clear: actions.clear,
|
|
299
|
+
setValue: actions.setValue,
|
|
300
|
+
getValue: actions.getValue,
|
|
301
|
+
isFocused: actions.isFocused,
|
|
302
|
+
get input() {
|
|
303
|
+
return inputRef.current;
|
|
304
|
+
},
|
|
305
|
+
snapshot,
|
|
306
|
+
cells,
|
|
307
|
+
decorationProps: DECORATION_PROPS,
|
|
308
|
+
inputProps,
|
|
309
|
+
rowStyle,
|
|
310
|
+
pressableProps: { onPress: actions.focus, disabled: isDisabled, accessible: false },
|
|
311
|
+
controller,
|
|
312
|
+
};
|
|
313
|
+
}
|