-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Form.js
257 lines (215 loc) · 8.83 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
import lodashGet from 'lodash/get';
import React from 'react';
import {ScrollView, View} 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';
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: 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),
}),
/** 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,
...withLocalizePropTypes,
};
const defaultProps = {
isSubmitButtonVisible: true,
formState: {
isLoading: false,
errors: null,
},
draftValues: {},
enabledWhenOffline: false,
};
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {},
inputValues: {},
};
this.inputRefs = {};
this.touchedInputs = {};
this.setTouchedInput = this.setTouchedInput.bind(this);
this.validate = this.validate.bind(this);
this.submit = this.submit.bind(this);
}
/**
* @param {String} inputID - The inputID of the input being touched
*/
setTouchedInput(inputID) {
this.touchedInputs[inputID] = true;
}
getErrorMessage() {
const latestErrorMessage = ErrorUtils.getLatestErrorMessage(this.props.formState);
return this.props.formState.error || (typeof latestErrorMessage === 'string' ? latestErrorMessage : '');
}
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);
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])
));
this.setState({errors});
return errors;
}
/**
* Loops over Form's children and automatically supplies Form props to them
*
* @param {Array} 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 nestedChildren = new child.type(child.props);
if (!React.isValidElement(nestedChildren) || !lodashGet(nestedChildren, 'props.children')) {
return child;
}
return React.cloneElement(nestedChildren, {
children: this.childrenWrapperWithProps(lodashGet(nestedChildren, 'props.children')),
});
}
// 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;
}
return React.cloneElement(child, {
ref: node => this.inputRefs[inputID] = node,
value: this.state.inputValues[inputID],
errorText: this.state.errors[inputID] || '',
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() {
return (
<>
<ScrollView
style={[styles.w100, styles.flex1]}
contentContainerStyle={styles.flexGrow1}
keyboardShouldPersistTaps="handled"
>
<View style={[this.props.style]}>
{this.childrenWrapperWithProps(this.props.children)}
{this.props.isSubmitButtonVisible && (
<FormAlertWithSubmitButton
buttonText={this.props.submitButtonText}
isAlertVisible={_.size(this.state.errors) > 0 || Boolean(this.getErrorMessage())}
isLoading={this.props.formState.isLoading}
message={this.getErrorMessage()}
onSubmit={this.submit}
onFixTheErrorsLinkPressed={() => {
this.inputRefs[_.first(_.keys(this.state.errors))].focus();
}}
containerStyles={[styles.mh0, styles.mt5]}
enabledWhenOffline={this.props.enabledWhenOffline}
/>
)}
</View>
</ScrollView>
</>
);
}
}
Form.propTypes = propTypes;
Form.defaultProps = defaultProps;
export default compose(
withLocalize,
withOnyx({
formState: {
key: props => props.formID,
},
draftValues: {
key: props => `${props.formID}Draft`,
},
}),
)(Form);