-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
MagicCodeInput.js
380 lines (333 loc) · 14.2 KB
/
MagicCodeInput.js
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import React, {useEffect, useImperativeHandle, useRef, useState, forwardRef} from 'react';
import {StyleSheet, View} from 'react-native';
import PropTypes from 'prop-types';
import _ from 'underscore';
import styles from '../styles/styles';
import * as StyleUtils from '../styles/StyleUtils';
import * as ValidationUtils from '../libs/ValidationUtils';
import CONST from '../CONST';
import Text from './Text';
import TextInput from './TextInput';
import FormHelpMessage from './FormHelpMessage';
import {withNetwork} from './OnyxProvider';
import networkPropTypes from './networkPropTypes';
import useNetwork from '../hooks/useNetwork';
import * as Browser from '../libs/Browser';
const propTypes = {
/** Information about the network */
network: networkPropTypes.isRequired,
/** Name attribute for the input */
name: PropTypes.string,
/** Input value */
value: PropTypes.string,
/** Should the input auto focus */
autoFocus: PropTypes.bool,
/** Whether we should wait before focusing the TextInput, useful when using transitions */
shouldDelayFocus: PropTypes.bool,
/** Error text to display */
errorText: PropTypes.string,
/** Specifies autocomplete hints for the system, so it can provide autofill */
autoComplete: PropTypes.oneOf(['sms-otp', 'one-time-code']).isRequired,
/* Should submit when the input is complete */
shouldSubmitOnComplete: PropTypes.bool,
innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
/** Function to call when the input is changed */
onChangeText: PropTypes.func,
/** Function to call when the input is submitted or fully complete */
onFulfill: PropTypes.func,
/** Specifies if the input has a validation error */
hasError: PropTypes.bool,
/** Specifies the max length of the input */
maxLength: PropTypes.number,
};
const defaultProps = {
value: undefined,
name: '',
autoFocus: true,
shouldDelayFocus: false,
errorText: '',
shouldSubmitOnComplete: true,
innerRef: null,
onChangeText: () => {},
onFulfill: () => {},
hasError: false,
maxLength: CONST.MAGIC_CODE_LENGTH,
};
/**
* Converts a given string into an array of numbers that must have the same
* number of elements as the number of inputs.
*
* @param {String} value
* @param {Number} length
* @returns {Array}
*/
const decomposeString = (value, length) => {
let arr = _.map(value.split('').slice(0, length), (v) => (ValidationUtils.isNumeric(v) ? v : CONST.MAGIC_CODE_EMPTY_CHAR));
if (arr.length < length) {
arr = arr.concat(Array(length - arr.length).fill(CONST.MAGIC_CODE_EMPTY_CHAR));
}
return arr;
};
/**
* Converts an array of strings into a single string. If there are undefined or
* empty values, it will replace them with a space.
*
* @param {Array} value
* @returns {String}
*/
const composeToString = (value) => _.map(value, (v) => (v === undefined || v === '' ? CONST.MAGIC_CODE_EMPTY_CHAR : v)).join('');
const getInputPlaceholderSlots = (length) => Array.from(Array(length).keys());
function MagicCodeInput(props) {
const inputRefs = useRef([]);
const [input, setInput] = useState('');
const [focusedIndex, setFocusedIndex] = useState(0);
const [editIndex, setEditIndex] = useState(0);
const blurMagicCodeInput = () => {
inputRefs.current[editIndex].blur();
setFocusedIndex(undefined);
};
const focusMagicCodeInput = () => {
setFocusedIndex(0);
inputRefs.current[0].focus();
};
useImperativeHandle(props.innerRef, () => ({
focus() {
focusMagicCodeInput();
},
resetFocus() {
setInput('');
focusMagicCodeInput();
},
clear() {
setInput('');
setFocusedIndex(0);
setEditIndex(0);
inputRefs.current[0].focus();
props.onChangeText('');
},
blur() {
blurMagicCodeInput();
},
}));
const validateAndSubmit = () => {
const numbers = decomposeString(props.value, props.maxLength);
if (!props.shouldSubmitOnComplete || _.filter(numbers, (n) => ValidationUtils.isNumeric(n)).length !== props.maxLength || props.network.isOffline) {
return;
}
// Blurs the input and removes focus from the last input and, if it should submit
// on complete, it will call the onFulfill callback.
blurMagicCodeInput();
props.onFulfill(props.value);
};
useNetwork({onReconnect: validateAndSubmit});
useEffect(() => {
validateAndSubmit();
// We have not added:
// + the editIndex as the dependency because we don't want to run this logic after focusing on an input to edit it after the user has completed the code.
// + the props.onFulfill as the dependency because props.onFulfill is changed when the preferred locale changed => avoid auto submit form when preferred locale changed.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.value, props.shouldSubmitOnComplete]);
useEffect(() => {
if (!props.autoFocus) {
return;
}
let focusTimeout = null;
if (props.shouldDelayFocus) {
focusTimeout = setTimeout(() => inputRefs.current[0].focus(), CONST.ANIMATED_TRANSITION);
} else {
inputRefs.current[0].focus();
}
return () => {
if (!focusTimeout) {
return;
}
clearTimeout(focusTimeout);
};
// We only want this to run on mount
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
/**
* Focuses on the input when it is pressed.
*
* @param {Object} event
* @param {Number} index
*/
const onFocus = (event) => {
event.preventDefault();
};
/**
* Callback for the onPress event, updates the indexes
* of the currently focused input.
*
* @param {Object} event
* @param {Number} index
*/
const onPress = (event, index) => {
event.preventDefault();
setInput('');
setFocusedIndex(index);
setEditIndex(index);
};
/**
* Updates the magic inputs with the contents written in the
* input. It spreads each number into each input and updates
* the focused input on the next empty one, if exists.
* It handles both fast typing and only one digit at a time
* in a specific position.
*
* @param {String} value
*/
const onChangeText = (value) => {
if (_.isUndefined(value) || _.isEmpty(value) || !ValidationUtils.isNumeric(value)) {
return;
}
// Updates the focused input taking into consideration the last input
// edited and the number of digits added by the user.
const numbersArr = value
.trim()
.split('')
.slice(0, props.maxLength - editIndex);
const updatedFocusedIndex = Math.min(editIndex + (numbersArr.length - 1) + 1, props.maxLength - 1);
let numbers = decomposeString(props.value, props.maxLength);
numbers = [...numbers.slice(0, editIndex), ...numbersArr, ...numbers.slice(numbersArr.length + editIndex, props.maxLength)];
setFocusedIndex(updatedFocusedIndex);
setInput(value);
const finalInput = composeToString(numbers);
props.onChangeText(finalInput);
};
/**
* Handles logic related to certain key presses.
*
* NOTE: when using Android Emulator, this can only be tested using
* hardware keyboard inputs.
*
* @param {Object} event
*/
const onKeyPress = ({nativeEvent: {key: keyValue}}) => {
if (keyValue === 'Backspace') {
let numbers = decomposeString(props.value, props.maxLength);
// If the currently focused index already has a value, it will delete
// that value but maintain the focus on the same input.
if (numbers[focusedIndex] !== CONST.MAGIC_CODE_EMPTY_CHAR) {
setInput('');
numbers = [...numbers.slice(0, focusedIndex), CONST.MAGIC_CODE_EMPTY_CHAR, ...numbers.slice(focusedIndex + 1, props.maxLength)];
setEditIndex(focusedIndex);
props.onChangeText(composeToString(numbers));
return;
}
const hasInputs = _.filter(numbers, (n) => ValidationUtils.isNumeric(n)).length !== 0;
// Fill the array with empty characters if there are no inputs.
if (focusedIndex === 0 && !hasInputs) {
numbers = Array(props.maxLength).fill(CONST.MAGIC_CODE_EMPTY_CHAR);
// Deletes the value of the previous input and focuses on it.
} else if (focusedIndex !== 0) {
numbers = [...numbers.slice(0, Math.max(0, focusedIndex - 1)), CONST.MAGIC_CODE_EMPTY_CHAR, ...numbers.slice(focusedIndex, props.maxLength)];
}
const newFocusedIndex = Math.max(0, focusedIndex - 1);
// Saves the input string so that it can compare to the change text
// event that will be triggered, this is a workaround for mobile that
// triggers the change text on the event after the key press.
setInput('');
setFocusedIndex(newFocusedIndex);
setEditIndex(newFocusedIndex);
props.onChangeText(composeToString(numbers));
if (!_.isUndefined(newFocusedIndex)) {
inputRefs.current[newFocusedIndex].focus();
}
}
if (keyValue === 'ArrowLeft' && !_.isUndefined(focusedIndex)) {
const newFocusedIndex = Math.max(0, focusedIndex - 1);
setInput('');
setFocusedIndex(newFocusedIndex);
setEditIndex(newFocusedIndex);
inputRefs.current[newFocusedIndex].focus();
} else if (keyValue === 'ArrowRight' && !_.isUndefined(focusedIndex)) {
const newFocusedIndex = Math.min(focusedIndex + 1, props.maxLength - 1);
setInput('');
setFocusedIndex(newFocusedIndex);
setEditIndex(newFocusedIndex);
inputRefs.current[newFocusedIndex].focus();
} else if (keyValue === 'Enter') {
// We should prevent users from submitting when it's offline.
if (props.network.isOffline) {
return;
}
setInput('');
props.onFulfill(props.value);
}
};
// We need to check the browser because, in iOS Safari, an input in a container with its opacity set to
// 0 (completely transparent) cannot handle user interaction, hence the Paste option is never shown.
// Alternate styling will be applied based on this condition.
const isMobileSafari = Browser.isMobileSafari();
return (
<>
<View style={[styles.magicCodeInputContainer]}>
{_.map(getInputPlaceholderSlots(props.maxLength), (index) => (
<View
key={index}
style={[styles.w15]}
>
<View
style={[
styles.textInputContainer,
StyleUtils.getHeightOfMagicCodeInput(),
props.hasError || props.errorText ? styles.borderColorDanger : {},
focusedIndex === index ? styles.borderColorFocus : {},
]}
>
<Text style={[styles.magicCodeInput, styles.textAlignCenter]}>{decomposeString(props.value, props.maxLength)[index] || ''}</Text>
</View>
<View style={[StyleSheet.absoluteFillObject, styles.w100, isMobileSafari ? styles.bgTransparent : styles.opacity0]}>
<TextInput
ref={(ref) => (inputRefs.current[index] = ref)}
autoFocus={index === 0 && props.autoFocus && !props.shouldDelayFocus}
inputMode="numeric"
textContentType="oneTimeCode"
name={props.name}
maxLength={props.maxLength}
value={input}
hideFocusedState
autoComplete={index === 0 ? props.autoComplete : 'off'}
keyboardType={CONST.KEYBOARD_TYPE.NUMBER_PAD}
onChangeText={(value) => {
// Do not run when the event comes from an input that is
// not currently being responsible for the input, this is
// necessary to avoid calls when the input changes due to
// deleted characters. Only happens in mobile.
if (index !== editIndex || _.isUndefined(focusedIndex)) {
return;
}
onChangeText(value);
}}
onKeyPress={onKeyPress}
onPress={(event) => onPress(event, index)}
onFocus={onFocus}
caretHidden={isMobileSafari}
inputStyle={[isMobileSafari ? styles.magicCodeInputTransparent : undefined]}
accessibilityRole={CONST.ACCESSIBILITY_ROLE.TEXT}
/>
</View>
</View>
))}
</View>
{!_.isEmpty(props.errorText) && (
<FormHelpMessage
isError
message={props.errorText}
/>
)}
</>
);
}
MagicCodeInput.propTypes = propTypes;
MagicCodeInput.defaultProps = defaultProps;
export default withNetwork()(
forwardRef((props, ref) => (
<MagicCodeInput
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
innerRef={ref}
/>
)),
);