-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathindex.tsx
More file actions
285 lines (256 loc) · 7.72 KB
/
Copy pathindex.tsx
File metadata and controls
285 lines (256 loc) · 7.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import Clipboard from '@react-native-clipboard/clipboard';
import React, {
forwardRef,
RefObject,
useCallback,
useEffect,
useImperativeHandle,
useReducer,
useRef,
} from 'react';
import {
Keyboard,
NativeSyntheticEvent,
Platform,
StyleProp,
StyleSheet,
TextInput,
TextInputKeyPressEventData,
TextInputProps,
TextStyle,
View,
ViewStyle,
} from 'react-native';
import { fillOtpCode } from './helpers';
import OtpInput from './OtpInput';
import reducer from './reducer';
import { OtpInputsRef, SupportedKeyboardType } from './types';
const supportAutofillFromClipboard =
Platform.OS === 'android' || parseInt(Platform.Version as string, 10) < 14;
export type OtpInputsProps = TextInputProps & {
autofillFromClipboard: boolean;
autofillListenerIntervalMS?: number;
keyboardType?: SupportedKeyboardType;
style?: StyleProp<ViewStyle>;
focusStyles?: StyleProp<ViewStyle>;
defaultValue?: string;
handleChange: (otpCode: string) => void;
inputContainerStyles?: StyleProp<ViewStyle>;
inputStyles?: StyleProp<TextStyle>;
isRTL?: boolean;
numberOfInputs: number;
testIDPrefix?: string;
};
const styles = StyleSheet.create({
container: {
alignItems: 'center',
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
},
});
const OtpInputs = forwardRef<OtpInputsRef, OtpInputsProps>(
(
{
autoFocus,
autofillFromClipboard = supportAutofillFromClipboard,
autofillListenerIntervalMS = 1000,
autoCapitalize = 'none',
clearTextOnFocus = false,
defaultValue,
focusStyles,
handleChange = console.log,
inputContainerStyles,
inputStyles,
isRTL = false,
keyboardType = 'phone-pad',
numberOfInputs = 4,
placeholder = '',
secureTextEntry = false,
selectTextOnFocus = true,
style,
testIDPrefix = 'otpInput',
...restProps
},
ref,
) => {
const previousCopiedText = useRef<string>('');
const inputs = useRef<Array<RefObject<TextInput>>>([]);
const [{ otpCode, hasKeySupport }, dispatch] = useReducer(reducer, {}, () => ({
otpCode: fillOtpCode(numberOfInputs, defaultValue),
handleChange,
hasKeySupport: Platform.OS === 'ios',
}));
useEffect(() => {
if (defaultValue) {
dispatch({
type: 'setOtpCode',
payload: { numberOfInputs, code: defaultValue },
});
}
}, [defaultValue, numberOfInputs]);
useEffect(() => {
dispatch({ type: 'setHandleChange', payload: handleChange });
}, [handleChange]);
useImperativeHandle(
ref,
() => ({
reset: (): void => {
dispatch({ type: 'clearOtp', payload: numberOfInputs });
inputs.current.forEach((input) => input?.current?.clear());
previousCopiedText.current = '';
Clipboard.setString('');
},
focus: (): void => {
const firstInput = inputs.current[0];
firstInput?.current?.focus();
},
}),
[numberOfInputs],
);
const handleInputTextChange = (text: string, index: number): void => {
if (!text.length) {
handleClearInput(index);
}
if (text.length > 1) {
handleClearInput(index);
Keyboard.dismiss();
return fillInputs(text);
}
if (text) {
dispatch({
type: 'setOtpTextForIndex',
payload: {
text,
index,
},
});
focusInput(index + 1);
}
if (index === numberOfInputs - 1 && text) {
Keyboard.dismiss();
}
};
const handleTextChange = (text: string, index: number) => {
if (
(Platform.OS === 'android' && !hasKeySupport) ||
// Pasted from input accessory
(Platform.OS === 'ios' && text.length > 1)
) {
handleInputTextChange(text, index);
}
};
const handleKeyPress = (
{ nativeEvent: { key } }: NativeSyntheticEvent<TextInputKeyPressEventData>,
index: number,
) => {
const text = key === 'Backspace' || key.length > 1 ? '' : key;
handleInputTextChange(text, index);
if (Platform.OS === 'android' && !hasKeySupport && !isNaN(parseInt(key)))
dispatch({ type: 'setHasKeySupport', payload: true });
};
const focusInput = useCallback(
(index: number): void => {
if (index >= 0 && index < numberOfInputs) {
const input = inputs.current[index];
input?.current?.focus();
}
},
[numberOfInputs],
);
const handleClearInput = useCallback(
(inputIndex: number) => {
const input = inputs.current[inputIndex];
input?.current?.clear();
dispatch({
type: 'setOtpTextForIndex',
payload: {
index: inputIndex,
text: '',
},
});
focusInput(inputIndex - 1);
},
[focusInput],
);
const fillInputs = useCallback(
(code: string) => {
dispatch({
type: 'setOtpCode',
payload: { numberOfInputs, code },
});
},
[numberOfInputs],
);
const listenOnCopiedText = useCallback(async (): Promise<void> => {
const copiedText = await Clipboard.getString();
const otpCodeValue = Object.values(otpCode).join('');
if (
copiedText?.length === numberOfInputs &&
copiedText !== otpCodeValue &&
copiedText !== previousCopiedText.current
) {
previousCopiedText.current = copiedText;
fillInputs(copiedText);
}
}, [fillInputs, numberOfInputs, otpCode]);
useEffect(() => {
let interval: NodeJS.Timeout;
if (autofillFromClipboard) {
interval = setInterval(() => {
listenOnCopiedText();
}, autofillListenerIntervalMS);
}
return () => {
clearInterval(interval);
};
}, [autofillFromClipboard, autofillListenerIntervalMS, listenOnCopiedText, numberOfInputs]);
const renderInputs = (): Array<JSX.Element> => {
const iterationArray = Array<number>(numberOfInputs).fill(0);
return iterationArray.map((_, index) => {
let inputIndex = index;
if (isRTL) {
inputIndex = numberOfInputs - 1 - index;
}
const inputValue = otpCode[`${inputIndex}`];
if (!inputs.current[inputIndex]) {
inputs.current[inputIndex] = React.createRef<TextInput>();
}
return (
<OtpInput
accessible
accessibilityLabel={`${testIDPrefix}-${inputIndex}`}
autoCapitalize={autoCapitalize}
autoFocus={index === 0 && autoFocus}
clearTextOnFocus={clearTextOnFocus}
firstInput={index === 0}
focusStyles={focusStyles}
handleKeyPress={(keyPressEvent: NativeSyntheticEvent<TextInputKeyPressEventData>) =>
handleKeyPress(keyPressEvent, inputIndex)
}
handleTextChange={(text: string) => handleTextChange(text, inputIndex)}
inputContainerStyles={inputContainerStyles}
inputStyles={inputStyles}
inputValue={inputValue}
key={inputIndex}
keyboardType={keyboardType}
maxLength={Platform.select({
android: 1,
ios: index === 0 ? numberOfInputs : 1,
})}
numberOfInputs={numberOfInputs}
placeholder={placeholder}
ref={inputs.current[inputIndex]}
secureTextEntry={secureTextEntry}
selectTextOnFocus={selectTextOnFocus}
testID={`${testIDPrefix}-${inputIndex}`}
{...restProps}
/>
);
});
};
return <View style={style || styles.container}>{renderInputs()}</View>;
},
);
export { OtpInputsRef };
export default OtpInputs;