/
FastField.tsx
302 lines (276 loc) · 9.35 KB
/
FastField.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
import * as React from 'react';
import isEqual from 'react-fast-compare';
import warning from 'warning';
import { FieldAttributes, FieldConfig, FieldProps } from './Field';
import { validateYupSchema, yupToFormErrors } from './Formik';
import { connect } from './connect';
import { FormikProps } from './types';
import { getIn, isEmptyChildren, isFunction, isPromise, setIn } from './utils';
export interface FastFieldState {
value: any;
error?: string;
}
/** @private Returns whether two objects are deeply equal **excluding** a key / dot path */
function isEqualExceptForKey(a: any, b: any, path: string) {
return isEqual(setIn(a, path, undefined), setIn(b, path, undefined));
}
/**
* Custom Field component for quickly hooking into Formik
* context and wiring up forms.
*/
class FastFieldInner<
Props extends FieldAttributes = any,
Values = {}
> extends React.Component<
Props & { formik: FormikProps<Values> },
FastFieldState
> {
reset: (nextValues?: any) => void;
constructor(props: Props & { formik: FormikProps<Values> }) {
super(props);
this.state = {
value: getIn(props.formik.values, props.name),
error: getIn(props.formik.errors, props.name),
};
this.reset = (nextValues?: any) => {
this.setState({
value: getIn(nextValues, props.name),
error: getIn(props.formik.errors, props.name),
});
};
props.formik.registerField(props.name, this.reset);
}
componentWillReceiveProps(nextProps: Props & { formik: FormikProps<any> }) {
const nextFieldValue = getIn(nextProps.formik.values, nextProps.name);
const nextFieldError = getIn(nextProps.formik.errors, nextProps.name);
let nextState: any;
if (nextFieldValue !== this.state.value) {
nextState = { value: nextFieldValue };
}
if (nextFieldError !== this.state.error) {
nextState = { ...nextState, error: nextFieldError };
}
if (nextState) {
this.setState(s => ({ ...s, ...nextState }));
}
}
componentWillUnmount() {
this.props.formik.unregisterField(this.props.name);
}
componentWillMount() {
const { render, children, component } = this.props;
warning(
!(component && render),
'You should not use <FastField component> and <FastField render> in the same <FastField> component; <FastField component> will be ignored'
);
warning(
!(this.props.component && children && isFunction(children)),
'You should not use <FastField component> and <FastField children> as a function in the same <FastField> component; <FastField component> will be ignored.'
);
warning(
!(render && children && !isEmptyChildren(children)),
'You should not use <FastField render> and <FastField children> in the same <FastField> component; <FastField children> will be ignored'
);
}
handleChange = (e: React.ChangeEvent<any>) => {
e.persist();
const {
validateOnChange,
validate,
values,
validationSchema,
errors,
setFormikState,
} = this.props.formik;
const { type, value, checked } = e.target;
const val = /number|range/.test(type)
? parseFloat(value)
: /checkbox/.test(type) ? checked : value;
if (validateOnChange) {
// Field-level validation
if (this.props.validate) {
const maybePromise = (this.props.validate as any)(value);
if (isPromise(maybePromise)) {
this.setState({ value: val });
(maybePromise as any).then(
() => this.setState({ error: undefined }),
(error: string) => this.setState({ error })
);
} else {
this.setState({ value: val, error: maybePromise });
}
} else if (validate) {
// Top-level validate
const maybePromise = (validate as any)(
setIn(values, this.props.name, val)
);
if (isPromise(maybePromise)) {
this.setState({ value: val });
(maybePromise as any).then(
() => this.setState({ error: undefined }),
(error: any) => {
// Here we diff the errors object relative to Formik parents except for
// the Field's key. If they are equal, the field's validation function is
// has no inter-field side-effects and we only need to update local state
// otherwise we need to lift up the update to the parent (causing a full form render)
if (isEqualExceptForKey(maybePromise, errors, this.props.name)) {
this.setState({ error: getIn(error, this.props.name) });
} else {
setFormikState((prevState: any) => ({
...prevState,
errors: error,
// touched: setIn(prevState.touched, name, true),
}));
}
}
);
} else {
// Handle the same diff situation
// @todo refactor
if (isEqualExceptForKey(maybePromise, errors, this.props.name)) {
this.setState({
value: val,
error: getIn(maybePromise, this.props.name),
});
} else {
this.setState({
value: val,
});
setFormikState((prevState: any) => ({
...prevState,
errors: maybePromise,
}));
}
}
} else if (validationSchema) {
// Top-level validationsSchema
const schema = isFunction(validationSchema)
? validationSchema()
: validationSchema;
const mergedValues = setIn(values, this.props.name, val);
// try to validate with yup synchronously if possible...saves a render.
try {
validateYupSchema(mergedValues, schema, true);
this.setState({
value: val,
error: undefined,
});
} catch (e) {
if (e.name === 'ValidationError') {
this.setState({
value: val,
error: getIn(yupToFormErrors(e), this.props.name),
});
} else {
this.setState({
value: val,
});
// try yup async validation
validateYupSchema(mergedValues, schema).then(
() => this.setState({ error: undefined }),
(err: any) =>
this.setState(s => ({
...s,
error: getIn(yupToFormErrors(err), this.props.name),
}))
);
}
}
} else {
this.setState({ value: val });
}
} else {
this.setState({ value: val });
}
};
handleBlur = () => {
const { validateOnBlur, setFormikState } = this.props.formik;
const { name, validate } = this.props;
// @todo refactor
if (validateOnBlur && validate) {
const maybePromise = (validate as any)(this.state.value);
if (isPromise(maybePromise)) {
(maybePromise as Promise<any>).then(
() =>
setFormikState((prevState: any) => ({
...prevState,
values: setIn(prevState.values, name, this.state.value),
errors: setIn(prevState.errors, name, undefined),
touched: setIn(prevState.touched, name, true),
})),
error =>
setFormikState((prevState: any) => ({
...prevState,
values: setIn(prevState.values, name, this.state.value),
errors: setIn(prevState.errors, name, error),
touched: setIn(prevState.touched, name, true),
}))
);
} else {
setFormikState((prevState: any) => ({
...prevState,
values: setIn(prevState.values, name, this.state.value),
errors: setIn(prevState.errors, name, maybePromise),
touched: setIn(prevState.touched, name, true),
}));
}
} else {
setFormikState((prevState: any) => ({
...prevState,
errors: setIn(prevState.errors, name, this.state.error),
values: setIn(prevState.values, name, this.state.value),
touched: setIn(prevState.touched, name, true),
}));
}
};
render() {
const {
validate,
name,
render,
children,
component = 'input',
formik,
...props
} = this.props as FieldConfig & { formik: FormikProps<Values> };
const field = {
value:
props.type === 'radio' || props.type === 'checkbox'
? props.value // React uses checked={} for these inputs
: this.state.value,
name,
onChange: this.handleChange,
onBlur: this.handleBlur,
};
const bag = {
field,
form: formik,
meta: { touched: getIn(formik.touched, name), error: this.state.error },
};
if (render) {
return (render as (
props: FieldProps<any> & {
meta: { error?: string; touched?: boolean };
}
) => React.ReactNode)(bag);
}
if (isFunction(children)) {
return (children as (props: FieldProps<any>) => React.ReactNode)(bag);
}
if (typeof component === 'string') {
const { innerRef, ...rest } = props;
return React.createElement(component as any, {
ref: innerRef,
...field,
...rest,
children,
});
}
return React.createElement(component as any, {
...bag,
...props,
children,
});
}
}
export const FastField = connect<FieldAttributes, any>(FastFieldInner);