forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaseValidateCodeForm.tsx
326 lines (289 loc) · 11.8 KB
/
BaseValidateCodeForm.tsx
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
import {useFocusEffect} from '@react-navigation/native';
import type {ForwardedRef} from 'react';
import React, {useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
import {View} from 'react-native';
import type {StyleProp, ViewStyle} from 'react-native';
import {useOnyx} from 'react-native-onyx';
import Button from '@components/Button';
import DotIndicatorMessage from '@components/DotIndicatorMessage';
import MagicCodeInput from '@components/MagicCodeInput';
import type {AutoCompleteVariant, MagicCodeInputHandle} from '@components/MagicCodeInput';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import PressableWithFeedback from '@components/Pressable/PressableWithFeedback';
import Text from '@components/Text';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import {isMobileSafari} from '@libs/Browser';
import {getLatestErrorField, getLatestErrorMessage} from '@libs/ErrorUtils';
import {isValidValidateCode} from '@libs/ValidationUtils';
import {clearValidateCodeActionError} from '@userActions/User';
import CONST from '@src/CONST';
import type {TranslationPaths} from '@src/languages/types';
import ONYXKEYS from '@src/ONYXKEYS';
import type {ValidateMagicCodeAction} from '@src/types/onyx';
import type {Errors, PendingAction} from '@src/types/onyx/OnyxCommon';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
type ValidateCodeFormHandle = {
focus: () => void;
focusLastSelected: () => void;
};
type ValidateCodeFormError = {
validateCode?: TranslationPaths;
};
type ValidateCodeFormProps = {
/** If the magic code has been resent previously */
hasMagicCodeBeenSent?: boolean;
/** Specifies autocomplete hints for the system, so it can provide autofill */
autoComplete?: AutoCompleteVariant;
/** Forwarded inner ref */
innerRef?: ForwardedRef<ValidateCodeFormHandle>;
/** The state of magic code that being sent */
validateCodeAction?: ValidateMagicCodeAction;
/** The pending action for submitting form */
validatePendingAction?: PendingAction | null;
/** The error of submitting */
validateError?: Errors;
/** Function is called when submitting form */
handleSubmitForm: (validateCode: string) => void;
/** Styles for the button */
buttonStyles?: StyleProp<ViewStyle>;
/** Function to clear error of the form */
clearError: () => void;
/** Whether to show the verify button */
hideSubmitButton?: boolean;
/** Text for the verify button */
submitButtonText?: string;
/** Function is called when validate code modal is mounted and on magic code resend */
sendValidateCode: () => void;
/** Whether the form is loading or not */
isLoading?: boolean;
/** Whether to show skip button */
shouldShowSkipButton?: boolean;
/** Function to call when skip button is pressed */
handleSkipButtonPress?: () => void;
};
function BaseValidateCodeForm({
hasMagicCodeBeenSent,
autoComplete = 'one-time-code',
innerRef = () => {},
validateCodeAction,
validatePendingAction,
validateError,
handleSubmitForm,
clearError,
sendValidateCode,
buttonStyles,
hideSubmitButton,
submitButtonText,
isLoading,
shouldShowSkipButton = false,
handleSkipButtonPress,
}: ValidateCodeFormProps) {
const {translate} = useLocalize();
const {isOffline} = useNetwork();
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const [formError, setFormError] = useState<ValidateCodeFormError>({});
const [validateCode, setValidateCode] = useState('');
const inputValidateCodeRef = useRef<MagicCodeInputHandle>(null);
const [account = {}] = useOnyx(ONYXKEYS.ACCOUNT, {canBeMissing: true});
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- nullish coalescing doesn't achieve the same result in this case
const shouldDisableResendValidateCode = !!isOffline || account?.isLoading;
const focusTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const [timeRemaining, setTimeRemaining] = useState(CONST.REQUEST_CODE_DELAY as number);
const [canShowError, setCanShowError] = useState<boolean>(false);
const latestActionVerifiedError = getLatestErrorField(validateCodeAction, 'actionVerified');
const timerRef = useRef<NodeJS.Timeout>();
useImperativeHandle(innerRef, () => ({
focus() {
inputValidateCodeRef.current?.focus();
},
focusLastSelected() {
if (!inputValidateCodeRef.current) {
return;
}
if (focusTimeoutRef.current) {
clearTimeout(focusTimeoutRef.current);
}
focusTimeoutRef.current = setTimeout(() => {
inputValidateCodeRef.current?.focusLastSelected();
}, CONST.ANIMATED_TRANSITION);
},
}));
useFocusEffect(
useCallback(() => {
if (!inputValidateCodeRef.current) {
return;
}
if (focusTimeoutRef.current) {
clearTimeout(focusTimeoutRef.current);
}
// Keyboard won't show if we focus the input with a delay, so we need to focus immediately.
if (!isMobileSafari()) {
focusTimeoutRef.current = setTimeout(() => {
inputValidateCodeRef.current?.focusLastSelected();
}, CONST.ANIMATED_TRANSITION);
} else {
inputValidateCodeRef.current?.focusLastSelected();
}
return () => {
if (!focusTimeoutRef.current) {
return;
}
clearTimeout(focusTimeoutRef.current);
};
}, []),
);
useEffect(() => {
if (!hasMagicCodeBeenSent) {
return;
}
inputValidateCodeRef.current?.clear();
}, [hasMagicCodeBeenSent]);
useEffect(() => {
if (timeRemaining > 0) {
timerRef.current = setTimeout(() => {
setTimeRemaining(timeRemaining - 1);
}, 1000);
}
return () => {
clearTimeout(timerRef.current);
};
}, [timeRemaining]);
/**
* Request a validate code / magic code be sent to verify this contact method
*/
const resendValidateCode = () => {
sendValidateCode();
inputValidateCodeRef.current?.clear();
setTimeRemaining(CONST.REQUEST_CODE_DELAY);
};
/**
* Handle text input and clear formError upon text change
*/
const onTextInput = useCallback(
(text: string) => {
setValidateCode(text);
setFormError({});
if (!isEmptyObject(validateError) || !isEmptyObject(latestActionVerifiedError)) {
clearError();
clearValidateCodeActionError('actionVerified');
}
},
[validateError, clearError, latestActionVerifiedError],
);
/**
* Check that all the form fields are valid, then trigger the submit callback
*/
const validateAndSubmitForm = useCallback(() => {
setCanShowError(true);
if (!validateCode.trim()) {
setFormError({validateCode: 'validateCodeForm.error.pleaseFillMagicCode'});
return;
}
if (!isValidValidateCode(validateCode)) {
setFormError({validateCode: 'validateCodeForm.error.incorrectMagicCode'});
return;
}
setFormError({});
handleSubmitForm(validateCode);
}, [validateCode, handleSubmitForm]);
const errorText = useMemo(() => {
if (!canShowError) {
return '';
}
if (formError?.validateCode) {
return translate(formError?.validateCode);
}
return getLatestErrorMessage(account ?? {});
}, [canShowError, formError, account, translate]);
const shouldShowTimer = timeRemaining > 0 && !isOffline;
return (
<>
<MagicCodeInput
autoComplete={autoComplete}
ref={inputValidateCodeRef}
name="validateCode"
value={validateCode}
onChangeText={onTextInput}
errorText={errorText}
hasError={canShowError ? !isEmptyObject(validateError) : false}
onFulfill={validateAndSubmitForm}
autoFocus={false}
/>
{shouldShowTimer && (
<Text style={[styles.mt5]}>
{translate('validateCodeForm.requestNewCode')}
<Text style={[styles.textBlue]}>00:{String(timeRemaining).padStart(2, '0')}</Text>
</Text>
)}
<OfflineWithFeedback
pendingAction={validateCodeAction?.pendingFields?.validateCodeSent}
errors={latestActionVerifiedError}
errorRowStyles={[styles.mt2]}
onClose={() => clearValidateCodeActionError('actionVerified')}
>
{!shouldShowTimer && (
<View style={[styles.mt5, styles.dFlex, styles.flexColumn, styles.alignItemsStart]}>
<PressableWithFeedback
disabled={shouldDisableResendValidateCode}
style={[styles.mr1]}
onPress={resendValidateCode}
underlayColor={theme.componentBG}
hoverDimmingValue={1}
pressDimmingValue={0.2}
role={CONST.ROLE.BUTTON}
accessibilityLabel={translate('validateCodeForm.magicCodeNotReceived')}
>
<Text style={[StyleUtils.getDisabledLinkStyles(shouldDisableResendValidateCode)]}>{translate('validateCodeForm.magicCodeNotReceived')}</Text>
</PressableWithFeedback>
</View>
)}
</OfflineWithFeedback>
{!!hasMagicCodeBeenSent && (
<DotIndicatorMessage
type="success"
style={[styles.mt6, styles.flex0]}
// eslint-disable-next-line @typescript-eslint/naming-convention
messages={{0: translate('validateCodeModal.successfulNewCodeRequest')}}
/>
)}
<OfflineWithFeedback
shouldDisplayErrorAbove
pendingAction={validatePendingAction}
errors={canShowError ? validateError : undefined}
errorRowStyles={[styles.mt2, styles.textWrap]}
onClose={() => clearError()}
style={buttonStyles}
>
{shouldShowSkipButton && (
<Button
text={translate('common.skip')}
onPress={handleSkipButtonPress}
success={false}
large
/>
)}
{!hideSubmitButton && (
<Button
isDisabled={isOffline}
text={submitButtonText ?? translate('common.verify')}
onPress={validateAndSubmitForm}
style={[styles.mt4]}
success
large
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
isLoading={account?.isLoading || isLoading}
/>
)}
</OfflineWithFeedback>
</>
);
}
BaseValidateCodeForm.displayName = 'BaseValidateCodeForm';
export type {ValidateCodeFormProps, ValidateCodeFormHandle};
export default BaseValidateCodeForm;