forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Form.js
360 lines (302 loc) · 13.5 KB
/
Form.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
import lodashGet from 'lodash/get';
import React from 'react';
import {ScrollView, StyleSheet} from 'react-native';
import PropTypes from 'prop-types';
import _ from 'underscore';
import {withOnyx} from 'react-native-onyx';
import compose from '../libs/compose';
import withLocalize, {withLocalizePropTypes} from './withLocalize';
import * as FormActions from '../libs/actions/FormActions';
import * as ErrorUtils from '../libs/ErrorUtils';
import styles from '../styles/styles';
import FormAlertWithSubmitButton from './FormAlertWithSubmitButton';
import FormSubmit from './FormSubmit';
import SafeAreaConsumer from './SafeAreaConsumer';
import ScrollViewWithContext from './ScrollViewWithContext';
import stylePropTypes from '../styles/stylePropTypes';
const propTypes = {
/** A unique Onyx key identifying the form */
formID: PropTypes.string.isRequired,
/** Text to be displayed in the submit button */
submitButtonText: PropTypes.string.isRequired,
/** Controls the submit button's visibility */
isSubmitButtonVisible: PropTypes.bool,
/** Callback to validate the form */
validate: PropTypes.func.isRequired,
/** Callback to submit the form */
onSubmit: PropTypes.func.isRequired,
/** Children to render. */
children: PropTypes.oneOfType([
PropTypes.func,
PropTypes.node,
]).isRequired,
/* Onyx Props */
/** Contains the form state that must be accessed outside of the component */
formState: PropTypes.shape({
/** Controls the loading state of the form */
isLoading: PropTypes.bool,
/** Server side errors keyed by microtime */
errors: PropTypes.objectOf(PropTypes.string),
/** Field-specific server side errors keyed by microtime */
errorFields: PropTypes.objectOf(PropTypes.objectOf(PropTypes.string)),
}),
/** Contains draft values for each input in the form */
// eslint-disable-next-line react/forbid-prop-types
draftValues: PropTypes.object,
/** Should the button be enabled when offline */
enabledWhenOffline: PropTypes.bool,
/** Whether the form submit action is dangerous */
isSubmitActionDangerous: PropTypes.bool,
/** Whether the ScrollView overflow content is scrollable.
* Set to true to avoid nested Picker components at the bottom of the Form from rendering the popup selector over Picker
* e.g. https://github.com/Expensify/App/issues/13909#issuecomment-1396859008
*/
scrollToOverflowEnabled: PropTypes.bool,
/** Whether ScrollWithContext should be used instead of regular ScrollView.
* Set to true when there's a nested Picker component in Form.
*/
scrollContextEnabled: PropTypes.bool,
/** Container styles */
style: stylePropTypes,
...withLocalizePropTypes,
};
const defaultProps = {
isSubmitButtonVisible: true,
formState: {
isLoading: false,
errors: null,
},
draftValues: {},
enabledWhenOffline: false,
isSubmitActionDangerous: false,
scrollToOverflowEnabled: false,
scrollContextEnabled: false,
style: [],
};
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {},
inputValues: {
...props.draftValues,
},
};
this.formRef = React.createRef(null);
this.inputRefs = {};
this.touchedInputs = {};
this.setTouchedInput = this.setTouchedInput.bind(this);
this.validate = this.validate.bind(this);
this.submit = this.submit.bind(this);
}
componentDidUpdate(prevProps) {
if (prevProps.preferredLocale === this.props.preferredLocale) {
return;
}
// Update the error messages if the language changes
this.validate(this.state.inputValues);
}
getErrorMessage() {
const latestErrorMessage = ErrorUtils.getLatestErrorMessage(this.props.formState);
return this.props.formState.error || (typeof latestErrorMessage === 'string' ? latestErrorMessage : '');
}
getFirstErroredInput() {
const hasStateErrors = !_.isEmpty(this.state.errors);
const hasErrorFields = !_.isEmpty(this.props.formState.errorFields);
if (!hasStateErrors && !hasErrorFields) {
return;
}
return _.first(_.keys(hasStateErrors ? this.state.erorrs : this.props.formState.errorFields));
}
/**
* @param {String} inputID - The inputID of the input being touched
*/
setTouchedInput(inputID) {
this.touchedInputs[inputID] = true;
}
submit() {
// Return early if the form is already submitting to avoid duplicate submission
if (this.props.formState.isLoading) {
return;
}
// Touches all form inputs so we can validate the entire form
_.each(this.inputRefs, (inputRef, inputID) => (
this.touchedInputs[inputID] = true
));
// Validate form and return early if any errors are found
if (!_.isEmpty(this.validate(this.state.inputValues))) {
return;
}
// Call submit handler
this.props.onSubmit(this.state.inputValues);
}
/**
* @param {Object} values - An object containing the value of each inputID, e.g. {inputID1: value1, inputID2: value2}
* @returns {Object} - An object containing the errors for each inputID, e.g. {inputID1: error1, inputID2: error2}
*/
validate(values) {
FormActions.setErrors(this.props.formID, null);
FormActions.setErrorFields(this.props.formID, null);
const validationErrors = this.props.validate(values);
if (!_.isObject(validationErrors)) {
throw new Error('Validate callback must return an empty object or an object with shape {inputID: error}');
}
const errors = _.pick(validationErrors, (inputValue, inputID) => (
Boolean(this.touchedInputs[inputID])
));
if (!_.isEqual(errors, this.state.errors)) {
this.setState({errors});
}
return errors;
}
/**
* Loops over Form's children and automatically supplies Form props to them
*
* @param {Array | Function | Node} children - An array containing all Form children
* @returns {React.Component}
*/
childrenWrapperWithProps(children) {
return React.Children.map(children, (child) => {
// Just render the child if it is not a valid React element, e.g. text within a <Text> component
if (!React.isValidElement(child)) {
return child;
}
// Depth first traversal of the render tree as the input element is likely to be the last node
if (child.props.children) {
return React.cloneElement(child, {
children: this.childrenWrapperWithProps(child.props.children),
});
}
// Look for any inputs nested in a custom component, e.g AddressForm or IdentityForm
if (_.isFunction(child.type)) {
const childNode = new child.type(child.props);
// If the custom component has a render method, use it to get the nested children
const nestedChildren = _.isFunction(childNode.render) ? childNode.render() : childNode;
// Render the custom component if it's a valid React element
// If the custom component has nested children, Loop over them and supply From props
if (React.isValidElement(nestedChildren) || lodashGet(nestedChildren, 'props.children')) {
return this.childrenWrapperWithProps(nestedChildren);
}
// Just render the child if it's custom component not a valid React element, or if it hasn't children
return child;
}
// We check if the child has the inputID prop.
// We don't want to pass form props to non form components, e.g. View, Text, etc
if (!child.props.inputID) {
return child;
}
// We clone the child passing down all form props
const inputID = child.props.inputID;
const defaultValue = this.props.draftValues[inputID] || child.props.defaultValue;
// We want to initialize the input value if it's undefined
if (_.isUndefined(this.state.inputValues[inputID])) {
this.state.inputValues[inputID] = defaultValue;
}
if (!_.isUndefined(child.props.value)) {
this.state.inputValues[inputID] = child.props.value;
}
const errorFields = lodashGet(this.props.formState, 'errorFields', {});
const fieldErrorMessage = _.chain(errorFields[inputID])
.keys()
.sortBy()
.reverse()
.map(key => errorFields[inputID][key])
.first()
.value() || '';
return React.cloneElement(child, {
ref: node => this.inputRefs[inputID] = node,
value: this.state.inputValues[inputID],
errorText: this.state.errors[inputID] || fieldErrorMessage,
onBlur: () => {
this.setTouchedInput(inputID);
this.validate(this.state.inputValues);
},
onInputChange: (value, key) => {
const inputKey = key || inputID;
this.setState(prevState => ({
inputValues: {
...prevState.inputValues,
[inputKey]: value,
},
}), () => this.validate(this.state.inputValues));
if (child.props.shouldSaveDraft) {
FormActions.setDraftValues(this.props.formID, {[inputKey]: value});
}
if (child.props.onValueChange) {
child.props.onValueChange(value);
}
},
});
});
}
render() {
const scrollViewContent = safeAreaPaddingBottomStyle => (
<FormSubmit style={StyleSheet.flatten([this.props.style, safeAreaPaddingBottomStyle])} onSubmit={this.submit}>
{this.childrenWrapperWithProps(_.isFunction(this.props.children) ? this.props.children({inputValues: this.state.inputValues}) : this.props.children)}
{this.props.isSubmitButtonVisible && (
<FormAlertWithSubmitButton
buttonText={this.props.submitButtonText}
isAlertVisible={_.size(this.state.errors) > 0 || Boolean(this.getErrorMessage()) || !_.isEmpty(this.props.formState.errorFields)}
isLoading={this.props.formState.isLoading}
message={_.isEmpty(this.props.formState.errorFields) ? this.getErrorMessage() : null}
onSubmit={this.submit}
onFixTheErrorsLinkPressed={() => {
const errors = !_.isEmpty(this.state.errors) ? this.state.errors : this.props.formState.errorFields;
const focusKey = _.find(_.keys(this.inputRefs), key => _.keys(errors).includes(key));
const focusInput = this.inputRefs[focusKey];
if (focusInput.focus && typeof focusInput.focus === 'function') {
focusInput.focus();
}
// We subtract 10 to scroll slightly above the input
if (focusInput.measureLayout && typeof focusInput.measureLayout === 'function') {
focusInput.measureLayout(this.formRef.current, (x, y) => this.formRef.current.scrollTo({y: y - 10, animated: false}));
}
}}
containerStyles={[styles.mh0, styles.mt5, styles.flex1]}
enabledWhenOffline={this.props.enabledWhenOffline}
isSubmitActionDangerous={this.props.isSubmitActionDangerous}
disablePressOnEnter
/>
)}
</FormSubmit>
);
return (
<SafeAreaConsumer>
{({safeAreaPaddingBottomStyle}) => (this.props.scrollContextEnabled ? (
<ScrollViewWithContext
style={[styles.w100, styles.flex1]}
contentContainerStyle={styles.flexGrow1}
keyboardShouldPersistTaps="handled"
scrollToOverflowEnabled={this.props.scrollToOverflowEnabled}
ref={this.formRef}
>
{scrollViewContent(safeAreaPaddingBottomStyle)}
</ScrollViewWithContext>
) : (
<ScrollView
style={[styles.w100, styles.flex1]}
contentContainerStyle={styles.flexGrow1}
keyboardShouldPersistTaps="handled"
scrollToOverflowEnabled={this.props.scrollToOverflowEnabled}
ref={this.formRef}
>
{scrollViewContent(safeAreaPaddingBottomStyle)}
</ScrollView>
))}
</SafeAreaConsumer>
);
}
}
Form.propTypes = propTypes;
Form.defaultProps = defaultProps;
export default compose(
withLocalize,
withOnyx({
formState: {
key: props => props.formID,
},
draftValues: {
key: props => `${props.formID}Draft`,
},
}),
)(Form);