-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
BaseValidateCodeForm.js
254 lines (227 loc) · 9.48 KB
/
BaseValidateCodeForm.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
import {useFocusEffect} from '@react-navigation/native';
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
import React, {useCallback, useEffect, useImperativeHandle, useRef, useState} from 'react';
import {View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
import Button from '@components/Button';
import DotIndicatorMessage from '@components/DotIndicatorMessage';
import MagicCodeInput from '@components/MagicCodeInput';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import {withNetwork} from '@components/OnyxProvider';
import PressableWithFeedback from '@components/Pressable/PressableWithFeedback';
import Text from '@components/Text';
import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import compose from '@libs/compose';
import * as ErrorUtils from '@libs/ErrorUtils';
import * as ValidationUtils from '@libs/ValidationUtils';
import * as Session from '@userActions/Session';
import * as User from '@userActions/User';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
const propTypes = {
...withLocalizePropTypes,
/** The contact method being valdiated */
contactMethod: PropTypes.string.isRequired,
/** If the magic code has been resent previously */
hasMagicCodeBeenSent: PropTypes.bool.isRequired,
/** Login list for the user that is signed in */
loginList: PropTypes.shape({
/** Value of partner name */
partnerName: PropTypes.string,
/** Phone/Email associated with user */
partnerUserID: PropTypes.string,
/** Date when login was validated */
validatedDate: PropTypes.string,
/** Field-specific server side errors keyed by microtime */
errorFields: PropTypes.objectOf(PropTypes.objectOf(PropTypes.string)),
/** Field-specific pending states for offline UI status */
pendingFields: PropTypes.objectOf(PropTypes.objectOf(PropTypes.string)),
}).isRequired,
/** Forwarded inner ref */
innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
/* Onyx Props */
/** The details about the account that the user is signing in with */
account: PropTypes.shape({
/** Whether or not a sign on form is loading (being submitted) */
isLoading: PropTypes.bool,
}),
/** Specifies autocomplete hints for the system, so it can provide autofill */
autoComplete: PropTypes.oneOf(['sms-otp', 'one-time-code']).isRequired,
};
const defaultProps = {
account: {},
innerRef: () => {},
};
function BaseValidateCodeForm(props) {
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const [formError, setFormError] = useState({});
const [validateCode, setValidateCode] = useState('');
const loginData = props.loginList[props.contactMethod];
const inputValidateCodeRef = useRef();
const validateLoginError = ErrorUtils.getEarliestErrorField(loginData, 'validateLogin');
const shouldDisableResendValidateCode = props.network.isOffline || props.account.isLoading;
const focusTimeoutRef = useRef(null);
useImperativeHandle(props.innerRef, () => ({
focus() {
if (!inputValidateCodeRef.current) {
return;
}
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);
}
focusTimeoutRef.current = setTimeout(inputValidateCodeRef.current.focus, CONST.ANIMATED_TRANSITION);
return () => {
if (!focusTimeoutRef.current) {
return;
}
clearTimeout(focusTimeoutRef.current);
};
}, []),
);
useEffect(() => {
Session.clearAccountMessages();
if (!validateLoginError) {
return;
}
User.clearContactMethodErrors(props.contactMethod, 'validateLogin');
// contactMethod is not added as a dependency since it does not change between renders
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (!props.hasMagicCodeBeenSent) {
return;
}
inputValidateCodeRef.current.clear();
}, [props.hasMagicCodeBeenSent]);
/**
* Request a validate code / magic code be sent to verify this contact method
*/
const resendValidateCode = () => {
User.requestContactMethodValidateCode(props.contactMethod);
inputValidateCodeRef.current.clear();
};
/**
* Handle text input and clear formError upon text change
*
* @param {String} text
*/
const onTextInput = useCallback(
(text) => {
setValidateCode(text);
setFormError({});
if (validateLoginError) {
User.clearContactMethodErrors(props.contactMethod, 'validateLogin');
}
},
[validateLoginError, props.contactMethod],
);
/**
* Check that all the form fields are valid, then trigger the submit callback
*/
const validateAndSubmitForm = useCallback(() => {
if (!validateCode.trim()) {
setFormError({validateCode: 'validateCodeForm.error.pleaseFillMagicCode'});
return;
}
if (!ValidationUtils.isValidValidateCode(validateCode)) {
setFormError({validateCode: 'validateCodeForm.error.incorrectMagicCode'});
return;
}
setFormError({});
User.validateSecondaryLogin(props.contactMethod, validateCode);
}, [validateCode, props.contactMethod]);
return (
<>
<MagicCodeInput
autoComplete={props.autoComplete}
ref={inputValidateCodeRef}
label={props.translate('common.magicCode')}
name="validateCode"
value={validateCode}
onChangeText={onTextInput}
errorText={formError.validateCode ? props.translate(formError.validateCode) : ErrorUtils.getLatestErrorMessage(props.account)}
hasError={!_.isEmpty(validateLoginError)}
onFulfill={validateAndSubmitForm}
autoFocus={false}
/>
<OfflineWithFeedback
pendingAction={lodashGet(loginData, 'pendingFields.validateCodeSent', null)}
errors={ErrorUtils.getLatestErrorField(loginData, 'validateCodeSent')}
errorRowStyles={[styles.mt2]}
onClose={() => User.clearContactMethodErrors(props.contactMethod, 'validateCodeSent')}
>
<View style={[styles.mt2, 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={props.translate('validateCodeForm.magicCodeNotReceived')}
>
<Text style={[StyleUtils.getDisabledLinkStyles(shouldDisableResendValidateCode)]}>{props.translate('validateCodeForm.magicCodeNotReceived')}</Text>
</PressableWithFeedback>
{props.hasMagicCodeBeenSent && (
<DotIndicatorMessage
type="success"
style={[styles.mt6, styles.flex0]}
messages={{0: 'resendValidationForm.linkHasBeenResent'}}
/>
)}
</View>
</OfflineWithFeedback>
<OfflineWithFeedback
pendingAction={lodashGet(loginData, 'pendingFields.validateLogin', null)}
errors={validateLoginError}
errorRowStyles={[styles.mt2]}
onClose={() => User.clearContactMethodErrors(props.contactMethod, 'validateLogin')}
>
<Button
isDisabled={props.network.isOffline}
text={props.translate('common.verify')}
onPress={validateAndSubmitForm}
style={[styles.mt4]}
success
pressOnEnter
isLoading={props.account.isLoading}
/>
</OfflineWithFeedback>
</>
);
}
BaseValidateCodeForm.propTypes = propTypes;
BaseValidateCodeForm.defaultProps = defaultProps;
BaseValidateCodeForm.displayName = 'BaseValidateCodeForm';
export default compose(
withLocalize,
withOnyx({
account: {key: ONYXKEYS.ACCOUNT},
}),
withNetwork(),
)(BaseValidateCodeForm);