@r5n/otp-react-native 0.0.0-stage → 8.0.1

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 (114) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/LICENSE +21 -0
  3. package/README.md +227 -2
  4. package/lib/commonjs/Cell.js +140 -0
  5. package/lib/commonjs/Cell.js.map +1 -0
  6. package/lib/commonjs/OtpInput.js +129 -0
  7. package/lib/commonjs/OtpInput.js.map +1 -0
  8. package/lib/commonjs/accessibility.js +90 -0
  9. package/lib/commonjs/accessibility.js.map +1 -0
  10. package/lib/commonjs/clipboard.js +197 -0
  11. package/lib/commonjs/clipboard.js.map +1 -0
  12. package/lib/commonjs/dev.js +63 -0
  13. package/lib/commonjs/dev.js.map +1 -0
  14. package/lib/commonjs/hiddenInput.js +95 -0
  15. package/lib/commonjs/hiddenInput.js.map +1 -0
  16. package/lib/commonjs/index.js +53 -0
  17. package/lib/commonjs/index.js.map +1 -0
  18. package/lib/commonjs/legacy.js +218 -0
  19. package/lib/commonjs/legacy.js.map +1 -0
  20. package/lib/commonjs/managedProps.js +73 -0
  21. package/lib/commonjs/managedProps.js.map +1 -0
  22. package/lib/commonjs/package.json +1 -0
  23. package/lib/commonjs/types.js +45 -0
  24. package/lib/commonjs/types.js.map +1 -0
  25. package/lib/commonjs/useOtpController.js +70 -0
  26. package/lib/commonjs/useOtpController.js.map +1 -0
  27. package/lib/commonjs/useOtpInput.js +251 -0
  28. package/lib/commonjs/useOtpInput.js.map +1 -0
  29. package/lib/module/Cell.js +103 -0
  30. package/lib/module/Cell.js.map +1 -0
  31. package/lib/module/OtpInput.js +94 -0
  32. package/lib/module/OtpInput.js.map +1 -0
  33. package/lib/module/accessibility.js +49 -0
  34. package/lib/module/accessibility.js.map +1 -0
  35. package/lib/module/clipboard.js +156 -0
  36. package/lib/module/clipboard.js.map +1 -0
  37. package/lib/module/dev.js +22 -0
  38. package/lib/module/dev.js.map +1 -0
  39. package/lib/module/hiddenInput.js +54 -0
  40. package/lib/module/hiddenInput.js.map +1 -0
  41. package/lib/module/index.js +14 -0
  42. package/lib/module/index.js.map +1 -0
  43. package/lib/module/legacy.js +188 -0
  44. package/lib/module/legacy.js.map +1 -0
  45. package/lib/module/managedProps.js +32 -0
  46. package/lib/module/managedProps.js.map +1 -0
  47. package/lib/module/types.js +3 -0
  48. package/lib/module/types.js.map +1 -0
  49. package/lib/module/useOtpController.js +29 -0
  50. package/lib/module/useOtpController.js.map +1 -0
  51. package/lib/module/useOtpInput.js +216 -0
  52. package/lib/module/useOtpInput.js.map +1 -0
  53. package/lib/typescript/commonjs/package.json +1 -0
  54. package/lib/typescript/commonjs/src/Cell.d.ts +39 -0
  55. package/lib/typescript/commonjs/src/Cell.d.ts.map +1 -0
  56. package/lib/typescript/commonjs/src/OtpInput.d.ts +12 -0
  57. package/lib/typescript/commonjs/src/OtpInput.d.ts.map +1 -0
  58. package/lib/typescript/commonjs/src/accessibility.d.ts +39 -0
  59. package/lib/typescript/commonjs/src/accessibility.d.ts.map +1 -0
  60. package/lib/typescript/commonjs/src/clipboard.d.ts +9 -0
  61. package/lib/typescript/commonjs/src/clipboard.d.ts.map +1 -0
  62. package/lib/typescript/commonjs/src/dev.d.ts +13 -0
  63. package/lib/typescript/commonjs/src/dev.d.ts.map +1 -0
  64. package/lib/typescript/commonjs/src/hiddenInput.d.ts +31 -0
  65. package/lib/typescript/commonjs/src/hiddenInput.d.ts.map +1 -0
  66. package/lib/typescript/commonjs/src/index.d.ts +11 -0
  67. package/lib/typescript/commonjs/src/index.d.ts.map +1 -0
  68. package/lib/typescript/commonjs/src/legacy.d.ts +78 -0
  69. package/lib/typescript/commonjs/src/legacy.d.ts.map +1 -0
  70. package/lib/typescript/commonjs/src/managedProps.d.ts +5 -0
  71. package/lib/typescript/commonjs/src/managedProps.d.ts.map +1 -0
  72. package/lib/typescript/commonjs/src/types.d.ts +262 -0
  73. package/lib/typescript/commonjs/src/types.d.ts.map +1 -0
  74. package/lib/typescript/commonjs/src/useOtpController.d.ts +28 -0
  75. package/lib/typescript/commonjs/src/useOtpController.d.ts.map +1 -0
  76. package/lib/typescript/commonjs/src/useOtpInput.d.ts +22 -0
  77. package/lib/typescript/commonjs/src/useOtpInput.d.ts.map +1 -0
  78. package/lib/typescript/module/src/Cell.d.ts +39 -0
  79. package/lib/typescript/module/src/Cell.d.ts.map +1 -0
  80. package/lib/typescript/module/src/OtpInput.d.ts +12 -0
  81. package/lib/typescript/module/src/OtpInput.d.ts.map +1 -0
  82. package/lib/typescript/module/src/accessibility.d.ts +39 -0
  83. package/lib/typescript/module/src/accessibility.d.ts.map +1 -0
  84. package/lib/typescript/module/src/clipboard.d.ts +9 -0
  85. package/lib/typescript/module/src/clipboard.d.ts.map +1 -0
  86. package/lib/typescript/module/src/dev.d.ts +13 -0
  87. package/lib/typescript/module/src/dev.d.ts.map +1 -0
  88. package/lib/typescript/module/src/hiddenInput.d.ts +31 -0
  89. package/lib/typescript/module/src/hiddenInput.d.ts.map +1 -0
  90. package/lib/typescript/module/src/index.d.ts +11 -0
  91. package/lib/typescript/module/src/index.d.ts.map +1 -0
  92. package/lib/typescript/module/src/legacy.d.ts +78 -0
  93. package/lib/typescript/module/src/legacy.d.ts.map +1 -0
  94. package/lib/typescript/module/src/managedProps.d.ts +5 -0
  95. package/lib/typescript/module/src/managedProps.d.ts.map +1 -0
  96. package/lib/typescript/module/src/types.d.ts +262 -0
  97. package/lib/typescript/module/src/types.d.ts.map +1 -0
  98. package/lib/typescript/module/src/useOtpController.d.ts +28 -0
  99. package/lib/typescript/module/src/useOtpController.d.ts.map +1 -0
  100. package/lib/typescript/module/src/useOtpInput.d.ts +22 -0
  101. package/lib/typescript/module/src/useOtpInput.d.ts.map +1 -0
  102. package/package.json +93 -4
  103. package/src/Cell.tsx +146 -0
  104. package/src/OtpInput.tsx +120 -0
  105. package/src/accessibility.ts +86 -0
  106. package/src/clipboard.ts +232 -0
  107. package/src/dev.ts +33 -0
  108. package/src/hiddenInput.ts +80 -0
  109. package/src/index.ts +38 -0
  110. package/src/legacy.tsx +320 -0
  111. package/src/managedProps.ts +29 -0
  112. package/src/types.ts +299 -0
  113. package/src/useOtpController.ts +58 -0
  114. package/src/useOtpInput.ts +313 -0
package/src/Cell.tsx ADDED
@@ -0,0 +1,146 @@
1
+ import { createContext, memo, type ReactElement, type ReactNode, useContext } from 'react';
2
+ import {
3
+ type ColorValue,
4
+ type StyleProp,
5
+ StyleSheet,
6
+ Text,
7
+ type TextStyle,
8
+ View,
9
+ type ViewStyle,
10
+ } from 'react-native';
11
+ import type { OtpCellProps, OtpDecorationProps, OtpInputCellState } from './types';
12
+
13
+ /**
14
+ * Cells and separators are decoration: the hidden input on top owns every touch and is the only
15
+ * accessibility element (P4), so this layer ignores touches (a custom cell with `elevation` must
16
+ * not steal taps on Android) and is hidden from VoiceOver and TalkBack.
17
+ */
18
+ export const DECORATION_PROPS: OtpDecorationProps = Object.freeze({
19
+ pointerEvents: 'none',
20
+ accessibilityElementsHidden: true,
21
+ importantForAccessibility: 'no-hide-descendants',
22
+ });
23
+
24
+ /**
25
+ * Whether cells get the built-in look. Internal: the v7 wrapper turns it off under v7 style props,
26
+ * which styled unstyled cells (C:S3-7).
27
+ */
28
+ export const CellAppearance = createContext<'default' | 'none'>('default');
29
+
30
+ const styles = StyleSheet.create({
31
+ cell: {
32
+ // A preferred width that shrinks when the row is narrower: 8 cells and their gaps need 408 pt
33
+ // at 44 pt, more than a 375 pt screen offers (C:S3-8). A `width` or `flex` in `cellStyle` wins.
34
+ width: 44,
35
+ flexShrink: 1,
36
+ minHeight: 52,
37
+ // The text is centred, so this only sets how much room a shrinking cell leaves its text.
38
+ paddingHorizontal: 4,
39
+ borderWidth: 1,
40
+ borderRadius: 8,
41
+ // Mid grey: at least 3:1 against both white and black (WCAG 1.4.11), as are the focus and error
42
+ // colours below.
43
+ borderColor: '#8E8E93',
44
+ alignItems: 'center',
45
+ justifyContent: 'center',
46
+ },
47
+ disabled: { opacity: 0.5 },
48
+ focused: { borderColor: '#007AFF' },
49
+ error: { borderColor: '#FF3B30' },
50
+ // React Native's default text colour is black in both colour schemes, so the built-in look sets
51
+ // one that follows the scheme (D:#1); `cellTextStyle.color` wins.
52
+ text: { fontSize: 24, fontWeight: '600', fontVariant: ['tabular-nums'], color: '#1C1C1E' },
53
+ textDark: { color: '#FFFFFF' },
54
+ separator: { minWidth: 8, alignItems: 'center', justifyContent: 'center' },
55
+ });
56
+
57
+ export interface CellProps extends OtpInputCellState {
58
+ testID: string | undefined;
59
+ cellStyle: StyleProp<ViewStyle>;
60
+ filledCellStyle: StyleProp<ViewStyle>;
61
+ focusedCellStyle: StyleProp<ViewStyle>;
62
+ errorCellStyle: StyleProp<ViewStyle>;
63
+ cellTextStyle: StyleProp<TextStyle>;
64
+ placeholderTextColor: ColorValue;
65
+ maxFontSizeMultiplier: number;
66
+ /** The colour scheme is dark: the built-in text colour is white. */
67
+ dark: boolean;
68
+ renderCell: ((state: OtpInputCellState) => ReactNode) | undefined;
69
+ cellProps: OtpCellProps | undefined;
70
+ }
71
+
72
+ /** One visual cell. Memoised on primitives, so typing re-renders only the cells that changed. */
73
+ export const Cell = memo(function Cell({
74
+ testID,
75
+ cellStyle,
76
+ filledCellStyle,
77
+ focusedCellStyle,
78
+ errorCellStyle,
79
+ cellTextStyle,
80
+ placeholderTextColor,
81
+ maxFontSizeMultiplier,
82
+ dark,
83
+ renderCell,
84
+ cellProps,
85
+ ...state
86
+ }: CellProps): ReactElement {
87
+ const styled = useContext(CellAppearance) === 'default';
88
+ if (renderCell) {
89
+ return (
90
+ <View {...cellProps} {...DECORATION_PROPS} testID={testID}>
91
+ {renderCell(state)}
92
+ </View>
93
+ );
94
+ }
95
+ return (
96
+ <View
97
+ {...cellProps}
98
+ {...DECORATION_PROPS}
99
+ testID={testID}
100
+ style={[
101
+ styled && styles.cell,
102
+ styled && state.isDisabled && styles.disabled,
103
+ cellStyle,
104
+ state.isFilled && filledCellStyle,
105
+ state.isActive && [styled && styles.focused, focusedCellStyle],
106
+ state.isError && [styled && styles.error, errorCellStyle],
107
+ ]}
108
+ >
109
+ <Text
110
+ style={[
111
+ styled && styles.text,
112
+ styled && dark && styles.textDark,
113
+ cellTextStyle,
114
+ state.isPlaceholder && { color: placeholderTextColor },
115
+ ]}
116
+ maxFontSizeMultiplier={maxFontSizeMultiplier}
117
+ // Long codes at the largest text sizes: shrink the glyph to the cell instead of clipping it
118
+ // (D:#4). `minimumFontScale` is iOS-only; Android uses its own minimum size.
119
+ numberOfLines={1}
120
+ adjustsFontSizeToFit
121
+ minimumFontScale={0.5}
122
+ >
123
+ {state.displayChar}
124
+ </Text>
125
+ </View>
126
+ );
127
+ });
128
+
129
+ interface SeparatorProps {
130
+ groupIndex: number;
131
+ style: StyleProp<ViewStyle>;
132
+ renderSeparator: ((groupIndex: number) => ReactNode) | undefined;
133
+ }
134
+
135
+ /** Spacer between two groups; `groupIndex` is the group before it. */
136
+ export const Separator = memo(function Separator({
137
+ groupIndex,
138
+ style,
139
+ renderSeparator,
140
+ }: SeparatorProps): ReactElement {
141
+ return (
142
+ <View {...DECORATION_PROPS} style={[styles.separator, style]}>
143
+ {renderSeparator?.(groupIndex)}
144
+ </View>
145
+ );
146
+ });
@@ -0,0 +1,120 @@
1
+ import {
2
+ Fragment,
3
+ forwardRef,
4
+ type ReactElement,
5
+ useEffect,
6
+ useImperativeHandle,
7
+ useMemo,
8
+ } from 'react';
9
+ import { StyleSheet, TextInput, useColorScheme, View } from 'react-native';
10
+ import { Cell, Separator } from './Cell';
11
+ import { forbiddenKeys, warnOnce, withoutKeys } from './dev';
12
+ import { CELL_MANAGED_PROPS } from './managedProps';
13
+ import type { OtpInputProps, OtpInputRef } from './types';
14
+ import { useOtpInput } from './useOtpInput';
15
+
16
+ const styles = StyleSheet.create({
17
+ row: { alignItems: 'center', gap: 8 },
18
+ });
19
+
20
+ const DEFAULT_PLACEHOLDER_COLOUR = '#8E8E93';
21
+
22
+ /**
23
+ * One-time code input: one hidden native `TextInput` over a row of visual cells, so the OS owns
24
+ * typing, paste, SMS autofill and screen-reader focus, and the whole row is one touch target.
25
+ *
26
+ * @example
27
+ * ```tsx
28
+ * <OtpInput length={6} onComplete={(code) => verify(code)} autoFocus />
29
+ * ```
30
+ */
31
+ export const OtpInput = forwardRef<OtpInputRef, OtpInputProps>(function OtpInput(
32
+ {
33
+ style,
34
+ cellStyle,
35
+ focusedCellStyle,
36
+ filledCellStyle,
37
+ errorCellStyle,
38
+ cellTextStyle,
39
+ placeholderTextColor = DEFAULT_PLACEHOLDER_COLOUR,
40
+ separatorStyle,
41
+ renderCell,
42
+ renderSeparator,
43
+ cellProps,
44
+ maxFontSizeMultiplier = 2,
45
+ ...options
46
+ },
47
+ ref,
48
+ ): ReactElement {
49
+ const otp = useOtpInput(options);
50
+ const { focus, blur, clear, setValue, getValue, isFocused } = otp;
51
+ // The hidden input's own ref object, read on every access: no second ref to keep in sync (W:#22).
52
+ const inputRef = otp.inputProps.ref;
53
+ useImperativeHandle(
54
+ ref,
55
+ () => ({
56
+ focus,
57
+ blur,
58
+ clear,
59
+ setValue,
60
+ getValue,
61
+ isFocused,
62
+ get input() {
63
+ return inputRef.current;
64
+ },
65
+ }),
66
+ [focus, blur, clear, setValue, getValue, isFocused, inputRef],
67
+ );
68
+ const testID = otp.inputProps.testID;
69
+ // Read once per input and passed down as a primitive, so the memoised cells re-render only when
70
+ // the scheme changes (D:#1).
71
+ const dark = useColorScheme() === 'dark';
72
+
73
+ // Cells stay hidden from touches and screen readers whatever `cellProps` says (C:S3-6). Memoised,
74
+ // so a stable `cellProps` keeps the cells memoised.
75
+ const blocked = forbiddenKeys(cellProps, CELL_MANAGED_PROPS).join(', ');
76
+ const safeCellProps = useMemo(
77
+ () => withoutKeys(cellProps, blocked === '' ? [] : blocked.split(', ')),
78
+ [cellProps, blocked],
79
+ );
80
+ useEffect(() => {
81
+ if (!__DEV__ || blocked === '') return;
82
+ warnOnce(
83
+ `cellProps:${blocked}`,
84
+ `cellProps.${blocked.split(', ').join(', cellProps.')} ignored: cells must stay hidden from ` +
85
+ 'touches and screen readers (C:S3-6).',
86
+ );
87
+ }, [blocked]);
88
+
89
+ return (
90
+ <View style={[styles.row, otp.rowStyle, style]}>
91
+ {otp.cells.map((cell) => (
92
+ <Fragment key={cell.index}>
93
+ {cell.isFirstInGroup && cell.groupIndex > 0 ? (
94
+ <Separator
95
+ groupIndex={cell.groupIndex - 1}
96
+ style={separatorStyle}
97
+ renderSeparator={renderSeparator}
98
+ />
99
+ ) : null}
100
+ <Cell
101
+ {...cell}
102
+ testID={testID === undefined ? undefined : `${testID}-cell-${cell.index}`}
103
+ cellStyle={cellStyle}
104
+ filledCellStyle={filledCellStyle}
105
+ focusedCellStyle={focusedCellStyle}
106
+ errorCellStyle={errorCellStyle}
107
+ cellTextStyle={cellTextStyle}
108
+ placeholderTextColor={placeholderTextColor}
109
+ maxFontSizeMultiplier={maxFontSizeMultiplier}
110
+ dark={dark}
111
+ renderCell={renderCell}
112
+ cellProps={safeCellProps}
113
+ />
114
+ </Fragment>
115
+ ))}
116
+ {/* Rendered last so it lies on top of the cells and receives every touch (#306, P1). */}
117
+ <TextInput {...otp.inputProps} />
118
+ </View>
119
+ );
120
+ });
@@ -0,0 +1,86 @@
1
+ import type { ResolvedOtpOptions } from '@r5n/otp-core';
2
+ import { useEffect, useRef } from 'react';
3
+ import { AccessibilityInfo, Platform } from 'react-native';
4
+ import type { OtpInputAccessibilityTexts } from './types';
5
+
6
+ const DEFAULT_COMPLETE = 'Code complete';
7
+ const DEFAULT_ERROR = 'Incorrect code';
8
+
9
+ /** Resolves an announcement text: `undefined` falls back to the default, `false`/`''` disable it. */
10
+ export const announcementText = (
11
+ text: string | false | undefined,
12
+ fallback: 'complete' | 'error',
13
+ ): string => {
14
+ if (text === undefined) return fallback === 'complete' ? DEFAULT_COMPLETE : DEFAULT_ERROR;
15
+ return text === false ? '' : text;
16
+ };
17
+
18
+ /**
19
+ * Default accessible name of the hidden input, for example "One-time code, 6 digits" (scenario 31;
20
+ * the same wording as `@r5n/otp-react`, W:#20). Never the test ID (v7 used it, so screen readers
21
+ * said "otpInput-0", G10).
22
+ */
23
+ export const defaultLabel = ({ length, charset }: ResolvedOtpOptions): string => {
24
+ const unit = charset === 'numeric' ? 'digit' : charset === 'alphabetic' ? 'letter' : 'character';
25
+ return `One-time code, ${length} ${unit}${length === 1 ? '' : 's'}`;
26
+ };
27
+
28
+ /**
29
+ * Accessibility value of the hidden input. React Native has no "invalid" state (`rn-platform.md`
30
+ * Q7), so the error is part of the text. Characters are separated by spaces so they are read one
31
+ * by one; a masked value only reports progress, never the characters.
32
+ */
33
+ export const valueText = (
34
+ value: string,
35
+ length: number,
36
+ masked: boolean,
37
+ error: string,
38
+ texts: OtpInputAccessibilityTexts | undefined,
39
+ ): string => {
40
+ const chars = Array.from(value);
41
+ const progress =
42
+ texts?.progress?.(chars.length, length) ?? `${chars.length} of ${length} entered`;
43
+ const spoken = masked || chars.length === 0 ? progress : `${chars.join(' ')}, ${progress}`;
44
+ return error === '' ? spoken : `${error}, ${spoken}`;
45
+ };
46
+
47
+ /**
48
+ * The hidden input's `accessibilityValue`.
49
+ *
50
+ * - iOS: VoiceOver reads it in place of the field's text, so a masked code reports only progress.
51
+ * - Android: React Native appends the value text to the field's `contentDescription`, which
52
+ * TalkBack reads together with the field's own text. Progress there would be read twice and
53
+ * rewritten on every keystroke (W:#8), so only the error is reported. The value is always an
54
+ * object: when it went from `{ text: error }` back to `undefined` as the error cleared, React
55
+ * Native left the content description empty and TalkBack lost the field's name (a plain
56
+ * `TextInput` does the same, on React Native 0.86 and 0.88). `{ text: '' }` keeps the name.
57
+ */
58
+ export const accessibilityValue = (
59
+ value: string,
60
+ length: number,
61
+ masked: boolean,
62
+ error: string,
63
+ texts: OtpInputAccessibilityTexts | undefined,
64
+ ): { text: string } => {
65
+ if (Platform.OS !== 'android') return { text: valueText(value, length, masked, error, texts) };
66
+ return { text: error };
67
+ };
68
+
69
+ /**
70
+ * Announces `text` to VoiceOver/TalkBack; a no-op for an empty text. Queued on iOS, so it follows
71
+ * the echo of the last typed character instead of cutting it off or being dropped (W:#17). `queue`
72
+ * is iOS-only: on Android React Native ignores the options and announces the text.
73
+ */
74
+ export const announce = (text: string): void => {
75
+ if (text === '') return;
76
+ AccessibilityInfo.announceForAccessibilityWithOptions(text, { queue: true });
77
+ };
78
+
79
+ /** Announces `text` when `active` turns on after mount (not on mount, not while it stays on). */
80
+ export const useAnnounceOnRise = (active: boolean, text: string): void => {
81
+ const previous = useRef(active);
82
+ useEffect(() => {
83
+ if (active && !previous.current) announce(text);
84
+ previous.current = active;
85
+ }, [active, text]);
86
+ };
@@ -0,0 +1,232 @@
1
+ import { extractCode, type OtpController } from '@r5n/otp-core';
2
+ import { useEffect, useLayoutEffect, useRef } from 'react';
3
+ import { AppState, Platform } from 'react-native';
4
+ import type { OtpClipboardProvider } from './types';
5
+ import { isDestroyed } from './useOtpController';
6
+
7
+ const usable = (provider: false | OtpClipboardProvider | undefined) =>
8
+ provider && typeof provider.getString === 'function' ? provider : undefined;
9
+
10
+ const describe = (error: unknown): string =>
11
+ error instanceof Error ? `${error.name}: ${error.message}` : String(error);
12
+
13
+ /**
14
+ * Reads the clipboard text through the provider; `''` when `hasString` reports no text. Async, so
15
+ * a provider that throws synchronously (a missing native module, #269) becomes a rejection.
16
+ */
17
+ const readClipboard = async (provider: OtpClipboardProvider): Promise<string> => {
18
+ if (provider.hasString && !(await provider.hasString())) return '';
19
+ const text = await provider.getString();
20
+ return typeof text === 'string' ? text : '';
21
+ };
22
+
23
+ /**
24
+ * What clipboard autofill remembers while it is enabled. It outlives one run, so a controller
25
+ * replaced by revival (StrictMode, `<Activity>`) keeps the baseline and the strings already
26
+ * considered (C:S3-1); switching autofill off forgets it.
27
+ */
28
+ interface ClipboardMemory {
29
+ /** The clipboard text when autofill was enabled; `undefined` until the first read settles. */
30
+ baseline: string | undefined;
31
+ /** Strings already considered: each is applied at most once (#132). */
32
+ readonly seen: Set<string>;
33
+ warned: boolean;
34
+ /** The read in flight. A newer read supersedes it once it is older than the timeout. */
35
+ read: { readonly id: number; readonly startedAt: number } | undefined;
36
+ reads: number;
37
+ }
38
+
39
+ const newMemory = (): ClipboardMemory => ({
40
+ baseline: undefined,
41
+ seen: new Set(),
42
+ warned: false,
43
+ read: undefined,
44
+ reads: 0,
45
+ });
46
+
47
+ /** A read that has not settled after this long (or `intervalMs`, if longer) is abandoned (C:S4-1). */
48
+ const READ_TIMEOUT_MS = 5000;
49
+
50
+ /**
51
+ * Delay of the one follow-up look after a read at focus or on return to the foreground found
52
+ * nothing. iOS can report an empty clipboard (`hasString` false) while it is still presenting the
53
+ * keyboard, and the text a moment later (D:#2).
54
+ */
55
+ const FOLLOW_UP_MS = 800;
56
+
57
+ /** What started a check. Only `focus` and `foreground` get a follow-up; a follow-up gets none. */
58
+ type Trigger = 'start' | 'focus' | 'foreground' | 'interval' | 'follow-up';
59
+
60
+ /** One development warning per input for clipboard problems; autofill keeps running. */
61
+ const warnOnce = (memory: ClipboardMemory, message: string): void => {
62
+ if (memory.warned) return;
63
+ memory.warned = true;
64
+ console.warn(`@r5n/otp-react-native: ${message}`);
65
+ };
66
+
67
+ /**
68
+ * Starts clipboard autofill for one controller and returns its disposer (orchestrator decision
69
+ * G3, `rn-platform.md` Q4).
70
+ *
71
+ * - The first successful read is the **baseline**: whatever was on the clipboard when autofill was
72
+ * enabled (typically the previous code, #259) is never applied.
73
+ * - Later reads happen on focus, when the app returns to the foreground, on Android when the app's
74
+ * window gets focus back (the notification shade closes, where users copy SMS codes), and every
75
+ * `intervalMs` when given; only while the input is focused and incomplete, one read at a time, so
76
+ * triggers that fire together share one read.
77
+ * - A read at focus or on return to the foreground that finds nothing is not trusted: one
78
+ * follow-up check runs `FOLLOW_UP_MS` later, cancelled by blur, disposal or the next trigger. It
79
+ * is not polling: the follow-up never schedules another (D:#2).
80
+ * - A clipboard string is considered once: it is applied only if `extractCode` finds a code, and
81
+ * never again afterwards, even after the user edits the value (#132).
82
+ * - Provider failures are swallowed (one development warning); nothing is applied after disposal,
83
+ * so a read that resolves after unmount changes nothing. The clipboard is never written to.
84
+ */
85
+ const startClipboardAutofill = (
86
+ controller: OtpController,
87
+ getProvider: () => OtpClipboardProvider | undefined,
88
+ intervalMs: number | undefined,
89
+ memory: ClipboardMemory,
90
+ ): (() => void) => {
91
+ let stopped = false;
92
+ const timeout = Math.max(intervalMs ?? 0, READ_TIMEOUT_MS);
93
+ let followUp: ReturnType<typeof setTimeout> | undefined;
94
+ const cancelFollowUp = (): void => {
95
+ if (followUp === undefined) return;
96
+ clearTimeout(followUp);
97
+ followUp = undefined;
98
+ };
99
+
100
+ const apply = (text: string): void => {
101
+ const { value, isComplete, options } = controller.getSnapshot();
102
+ // A complete value is left alone and the text is not consumed: it can still apply after the
103
+ // user clears a wrong code.
104
+ if (text === memory.baseline || memory.seen.has(text) || isComplete) return;
105
+ memory.seen.add(text);
106
+ const code = extractCode(text, options);
107
+ if (code === null || code === value) return;
108
+ try {
109
+ controller.setValue(code);
110
+ } catch (error) {
111
+ // A consumer callback threw. Report it like an error thrown in an event handler instead of
112
+ // an unhandled promise rejection (C:S4-2).
113
+ setTimeout(() => {
114
+ throw error;
115
+ }, 0);
116
+ }
117
+ };
118
+
119
+ const check = (trigger: Trigger): void => {
120
+ if (trigger !== 'follow-up') cancelFollowUp();
121
+ const provider = getProvider();
122
+ if (stopped || !provider) return;
123
+ const { isFocused, isComplete } = controller.getSnapshot();
124
+ if (memory.baseline !== undefined && (!isFocused || isComplete)) return;
125
+ const now = Date.now();
126
+ if (memory.read !== undefined) {
127
+ if (now - memory.read.startedAt < timeout) return;
128
+ if (__DEV__) {
129
+ warnOnce(
130
+ memory,
131
+ `a clipboardAutofill read did not settle within ${timeout} ms; its result will be ` +
132
+ 'ignored and a new read starts.',
133
+ );
134
+ }
135
+ }
136
+ memory.reads += 1;
137
+ const id = memory.reads;
138
+ memory.read = { id, startedAt: now };
139
+ readClipboard(provider).then(
140
+ (text) => {
141
+ if (memory.read?.id !== id) return;
142
+ memory.read = undefined;
143
+ if (memory.baseline === undefined) {
144
+ memory.baseline = text;
145
+ return;
146
+ }
147
+ if (stopped) return;
148
+ const unknown = text === '' && (trigger === 'focus' || trigger === 'foreground');
149
+ if (!unknown) {
150
+ apply(text);
151
+ return;
152
+ }
153
+ if (!controller.getSnapshot().isFocused) return;
154
+ followUp = setTimeout(() => {
155
+ followUp = undefined;
156
+ check('follow-up');
157
+ }, FOLLOW_UP_MS);
158
+ },
159
+ (error: unknown) => {
160
+ if (memory.read?.id !== id) return;
161
+ memory.read = undefined;
162
+ if (__DEV__ && !stopped) {
163
+ warnOnce(
164
+ memory,
165
+ `clipboardAutofill could not read the clipboard (${describe(error)}); this check is ` +
166
+ 'skipped and the next one reads again.',
167
+ );
168
+ }
169
+ },
170
+ );
171
+ };
172
+
173
+ let wasFocused = controller.getSnapshot().isFocused;
174
+ const unsubscribe = controller.subscribe(() => {
175
+ const { isFocused } = controller.getSnapshot();
176
+ if (isFocused && !wasFocused) check('focus');
177
+ if (!isFocused && wasFocused) cancelFollowUp();
178
+ wasFocused = isFocused;
179
+ });
180
+ const appState = AppState.addEventListener('change', (state) => {
181
+ if (state === 'active') check('foreground');
182
+ });
183
+ // Android only (React Native emits `focus` nowhere else): closing the notification shade after
184
+ // "Copy code" changes neither the input's focus nor `AppState` (device-android finding 1).
185
+ const windowFocus =
186
+ Platform.OS === 'android'
187
+ ? AppState.addEventListener('focus', () => check('foreground'))
188
+ : undefined;
189
+ const timer =
190
+ intervalMs !== undefined && Number.isFinite(intervalMs) && intervalMs > 0
191
+ ? setInterval(() => check('interval'), intervalMs)
192
+ : undefined;
193
+ check('start');
194
+
195
+ return () => {
196
+ stopped = true;
197
+ cancelFollowUp();
198
+ unsubscribe();
199
+ appState.remove();
200
+ windowFocus?.remove();
201
+ if (timer !== undefined) clearInterval(timer);
202
+ };
203
+ };
204
+
205
+ /**
206
+ * Opt-in clipboard autofill (`clipboardAutofill`). The provider object may be a new literal on
207
+ * every render. Enabling autofill takes a new baseline; changing `intervalMs` or replacing the
208
+ * controller (revival) restarts the triggers but keeps what was read so far.
209
+ */
210
+ export const useClipboardAutofill = (
211
+ controller: OtpController,
212
+ clipboardAutofill: false | OtpClipboardProvider | undefined,
213
+ ): void => {
214
+ const provider = usable(clipboardAutofill);
215
+ const latest = useRef(provider);
216
+ useLayoutEffect(() => {
217
+ latest.current = provider;
218
+ });
219
+ const memory = useRef<ClipboardMemory | undefined>(undefined);
220
+ const enabled = provider !== undefined;
221
+ const intervalMs = provider?.intervalMs;
222
+ useEffect(() => {
223
+ if (!enabled) {
224
+ memory.current = undefined;
225
+ return;
226
+ }
227
+ // A destroyed controller is about to be replaced (C:S3-1): its replacement starts autofill.
228
+ if (isDestroyed(controller)) return;
229
+ memory.current ??= newMemory();
230
+ return startClipboardAutofill(controller, () => latest.current, intervalMs, memory.current);
231
+ }, [controller, enabled, intervalMs]);
232
+ };
package/src/dev.ts ADDED
@@ -0,0 +1,33 @@
1
+ const warned = new Set<string>();
2
+
3
+ /**
4
+ * Prints a development-only warning once per `key` for the lifetime of the app. Call it behind an
5
+ * `if (__DEV__)` guard, so production builds drop the message text.
6
+ */
7
+ export const warnOnce = (key: string, message: string): void => {
8
+ if (!__DEV__ || warned.has(key)) return;
9
+ warned.add(key);
10
+ console.warn(`@r5n/otp-react-native: ${message}`);
11
+ };
12
+
13
+ /** The keys of `props` from `forbidden` that are set (not `undefined`). */
14
+ export const forbiddenKeys = (
15
+ props: object | undefined,
16
+ forbidden: readonly string[],
17
+ ): readonly string[] =>
18
+ props === undefined
19
+ ? []
20
+ : forbidden.filter((key) => (props as Record<string, unknown>)[key] !== undefined);
21
+
22
+ /**
23
+ * A copy of `props` without `keys`, or `props` itself when there is nothing to remove (so a stable
24
+ * object keeps its identity for memoised children).
25
+ */
26
+ export const withoutKeys = <T extends object>(
27
+ props: T | undefined,
28
+ keys: readonly string[],
29
+ ): T | undefined => {
30
+ if (props === undefined || keys.length === 0) return props;
31
+ // Same object minus keys that the caller's type already excludes.
32
+ return Object.fromEntries(Object.entries(props).filter(([key]) => !keys.includes(key))) as T;
33
+ };