-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathBaseValidateCodeForm.tsx
More file actions
394 lines (347 loc) · 15.5 KB
/
BaseValidateCodeForm.tsx
File metadata and controls
394 lines (347 loc) · 15.5 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
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import {useFocusEffect} from '@react-navigation/native';
import type {ForwardedRef} from 'react';
import React, {useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
import {AccessibilityInfo, View} from 'react-native';
import type {StyleProp, ViewStyle} from 'react-native';
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 ValidateCodeCountdown from '@components/ValidateCodeCountdown';
import type {ValidateCodeCountdownHandle} from '@components/ValidateCodeCountdown/types';
import {useWideRHPState} from '@components/WideRHPContextProvider';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useOnyx from '@hooks/useOnyx';
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 {Account} from '@src/types/onyx';
import type {Errors, PendingAction} from '@src/types/onyx/OnyxCommon';
import {getEmptyObject, isEmptyObject} from '@src/types/utils/EmptyObject';
type ValidateCodeFormHandle = {
focus: () => void;
focusLastSelected: () => void;
};
type ValidateCodeFormError = {
validateCode?: TranslationPaths;
};
type ValidateCodeFormProps = {
/** Specifies autocomplete hints for the system, so it can provide autofill */
autoComplete?: AutoCompleteVariant;
/** Forwarded inner ref */
ref?: ForwardedRef<ValidateCodeFormHandle>;
hasMagicCodeBeenSent?: boolean;
/** The pending action of magic code being sent
* if not supplied, we will retrieve it from the validateCodeAction above: `validateCodeAction.pendingFields.validateCodeSent`
*/
validatePendingAction?: PendingAction;
/** The field where any magic code error will be stored. e.g. if replacing a card and magic code fails, it'll be stored in:
* {"errorFields": {"replaceLostCard": {<timestamp>}}}
* If replacing a virtual card, the errorField wil be 'reportVirtualCard', etc.
* These values are set in the backend, please reach out to an internal engineer if you're adding a validate code modal to a flow.
*/
validateCodeActionErrorField: string;
/** 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;
/** Whether the modal is used as a page modal. Used to determine input auto focus timing. */
isInPageModal?: boolean;
};
function BaseValidateCodeForm({
autoComplete = CONST.AUTO_COMPLETE_VARIANTS.ONE_TIME_CODE,
ref = () => {},
hasMagicCodeBeenSent,
validateCodeActionErrorField,
validatePendingAction,
validateError,
handleSubmitForm,
clearError,
sendValidateCode,
buttonStyles,
hideSubmitButton,
submitButtonText,
isLoading,
shouldShowSkipButton = false,
handleSkipButtonPress,
isInPageModal = false,
}: ValidateCodeFormProps) {
const {translate} = useLocalize();
const {isOffline} = useNetwork();
const {wideRHPRouteKeys} = useWideRHPState();
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const [formError, setFormError] = useState<ValidateCodeFormError>({});
const [validateCode, setValidateCode] = useState('');
const [isCountdownRunning, setIsCountdownRunning] = useState(true);
const inputValidateCodeRef = useRef<MagicCodeInputHandle>(null);
const [account = getEmptyObject<Account>()] = useOnyx(ONYXKEYS.ACCOUNT);
// 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 [canShowError, setCanShowError] = useState<boolean>(false);
const [validateCodeAction] = useOnyx(ONYXKEYS.VALIDATE_ACTION_CODE);
const validateCodeSent = useMemo(() => hasMagicCodeBeenSent ?? validateCodeAction?.validateCodeSent, [hasMagicCodeBeenSent, validateCodeAction?.validateCodeSent]);
const latestValidateCodeError = getLatestErrorField(validateCodeAction, validateCodeActionErrorField);
const defaultValidateCodeError = getLatestErrorField(validateCodeAction, 'actionVerified');
const countdownRef = useRef<ValidateCodeCountdownHandle | null>(null);
const clearDefaultValidationCodeError = useCallback(() => {
// Clear "Failed to send magic code" error
if (isEmptyObject(defaultValidateCodeError)) {
return;
}
clearValidateCodeActionError('actionVerified');
}, [defaultValidateCodeError]);
useImperativeHandle(ref, () => ({
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 (!isCountdownRunning) {
return;
}
countdownRef.current?.resetCountdown();
}, [isCountdownRunning]);
useEffect(() => {
if (!validateCodeSent) {
return;
}
AccessibilityInfo.announceForAccessibility(translate('validateCodeModal.successfulNewCodeRequest'));
}, [validateCodeSent, translate]);
useEffect(() => {
if (!validateCodeSent) {
return;
}
// Delay prevents the input from gaining focus before the RHP slide-out animation finishes,
// which would cause issues with the RHP sliding out smoothly and flickering of the wide RHP in the background.
if ((wideRHPRouteKeys.length > 0 && !isMobileSafari()) || isInPageModal) {
focusTimeoutRef.current = setTimeout(() => {
inputValidateCodeRef.current?.clear();
}, CONST.ANIMATED_TRANSITION);
} else {
inputValidateCodeRef.current?.clear();
}
}, [validateCodeSent, wideRHPRouteKeys.length, isInPageModal]);
/**
* Request a validate code / magic code be sent to verify this contact method
*/
const resendValidateCode = () => {
sendValidateCode();
inputValidateCodeRef.current?.clear();
countdownRef.current?.resetCountdown();
setIsCountdownRunning(true);
};
/**
* Handle text input and clear formError upon text change
*/
const onTextInput = useCallback(
(text: string) => {
setValidateCode(text);
setFormError({});
if (!isEmptyObject(validateError) || !isEmptyObject(latestValidateCodeError)) {
// Clear flow specific error
clearError();
// Clear "incorrect magic code" error
clearValidateCodeActionError(validateCodeActionErrorField);
}
},
[validateError, clearError, latestValidateCodeError, validateCodeActionErrorField],
);
/**
* Check that all the form fields are valid, then trigger the submit callback
*/
const validateAndSubmitForm = useCallback(() => {
// Clear flow specific error
clearError();
// Clear "incorrect magic" code error
clearValidateCodeActionError(validateCodeActionErrorField);
clearDefaultValidationCodeError();
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, validateCodeActionErrorField, clearError, clearDefaultValidationCodeError]);
const errorText = useMemo(() => {
if (!canShowError) {
return '';
}
if (formError?.validateCode) {
return translate(formError?.validateCode);
}
return getLatestErrorMessage(account ?? {});
}, [canShowError, formError?.validateCode, account, translate]);
const shouldShowTimer = isCountdownRunning && !isOffline;
const handleCountdownFinish = useCallback(() => {
setIsCountdownRunning(false);
}, []);
// latestValidateCodeError only holds an error related to bad magic code
// while validateError holds flow-specific errors
const finalValidateError = !isEmptyObject(latestValidateCodeError) ? latestValidateCodeError : validateError;
return (
<>
<MagicCodeInput
autoComplete={autoComplete}
ref={inputValidateCodeRef}
name="validateCode"
value={validateCode}
onChangeText={onTextInput}
errorText={errorText}
hasError={canShowError && !isEmptyObject(finalValidateError)}
onFulfill={validateAndSubmitForm}
autoFocus={false}
/>
{shouldShowTimer && (
<View style={[styles.mt5, styles.flexRow, styles.renderHTML]}>
<ValidateCodeCountdown
ref={countdownRef}
onCountdownFinish={handleCountdownFinish}
/>
</View>
)}
<OfflineWithFeedback
pendingAction={validateCodeAction?.pendingFields?.validateCodeSent}
errorRowStyles={[styles.mt2]}
onClose={() => clearValidateCodeActionError(validateCodeActionErrorField)}
>
{!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')}
sentryLabel={CONST.SENTRY_LABEL.VALIDATE_CODE.RESEND_CODE}
>
<Text style={[StyleUtils.getDisabledLinkStyles(shouldDisableResendValidateCode)]}>{translate('validateCodeForm.magicCodeNotReceived')}</Text>
</PressableWithFeedback>
</View>
)}
</OfflineWithFeedback>
<View accessibilityLiveRegion="polite">
{!!validateCodeSent && (
<DotIndicatorMessage
type="success"
style={[styles.mt6, styles.flex0]}
// eslint-disable-next-line @typescript-eslint/naming-convention
messages={{0: translate('validateCodeModal.successfulNewCodeRequest')}}
/>
)}
</View>
<OfflineWithFeedback
shouldDisplayErrorAbove
pendingAction={validatePendingAction}
errors={canShowError ? (finalValidateError ?? defaultValidateCodeError) : defaultValidateCodeError}
errorRowStyles={[styles.mt2, styles.textWrap]}
onClose={() => {
clearError();
if (!isEmptyObject(validateCodeAction?.errorFields) && validateCodeActionErrorField) {
clearValidateCodeActionError(validateCodeActionErrorField);
}
clearDefaultValidationCodeError();
}}
style={buttonStyles}
>
{shouldShowSkipButton && (
<Button
text={translate('common.skip')}
onPress={handleSkipButtonPress}
style={[styles.mt4]}
success={false}
large
sentryLabel={CONST.SENTRY_LABEL.VALIDATE_CODE.SKIP}
/>
)}
{!hideSubmitButton && (
<Button
isDisabled={isOffline}
text={submitButtonText ?? translate('common.verify')}
onPress={validateAndSubmitForm}
style={[shouldShowSkipButton ? styles.mt3 : styles.mt4]}
success
large
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
isLoading={account?.isLoading || isLoading}
sentryLabel={CONST.SENTRY_LABEL.VALIDATE_CODE.VERIFY}
/>
)}
</OfflineWithFeedback>
</>
);
}
export type {ValidateCodeFormProps, ValidateCodeFormHandle};
export default BaseValidateCodeForm;