-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathFormik.tsx
executable file
·744 lines (692 loc) · 20 KB
/
Formik.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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
import * as React from 'react';
import isEqual from 'react-fast-compare';
import deepmerge from 'deepmerge';
import {
FormikConfig,
FormikErrors,
FormikState,
FormikTouched,
FormikValues,
FormikProps,
} from './types';
import {
isFunction,
isString,
setIn,
isEmptyChildren,
isPromise,
setNestedObjectValues,
getActiveElement,
getIn,
makeCancelable,
} from './utils';
import { FormikProvider } from './FormikContext';
import warning from 'warning';
// We already used FormikActions. So we'll go all Elm-y, and use Message.
type FormikMessage<Values> =
| { type: 'SUBMIT_ATTEMPT' }
| { type: 'SUBMIT_FAILURE' }
| { type: 'SUBMIT_SUCCESS' }
| { type: 'SET_ISVALIDATING'; payload: boolean }
| { type: 'SET_ISSUBMITTING'; payload: boolean }
| { type: 'SET_VALUES'; payload: Values }
| { type: 'SET_FIELD_VALUE'; payload: { field: string; value?: any } }
| { type: 'SET_FIELD_TOUCHED'; payload: { field: string; value?: boolean } }
| { type: 'SET_FIELD_ERROR'; payload: { field: string; value?: string } }
| { type: 'SET_TOUCHED'; payload: FormikTouched<Values> }
| { type: 'SET_ERRORS'; payload: FormikErrors<Values> }
| { type: 'SET_STATUS'; payload: any }
| { type: 'SET_FORMIK_STATE'; payload: FormikState<Values> }
| { type: 'RESET_FORM'; payload: FormikState<Values> };
// State reducer
function formikReducer<Values>(
state: FormikState<Values>,
msg: FormikMessage<Values>
) {
switch (msg.type) {
case 'SET_VALUES':
return { ...state, values: msg.payload };
case 'SET_TOUCHED':
return { ...state, touched: msg.payload };
case 'SET_ERRORS':
return { ...state, errors: msg.payload };
case 'SET_STATUS':
return { ...state, status: msg.payload };
case 'SET_ISSUBMITTING':
return { ...state, isSubmitting: msg.payload };
case 'SET_FIELD_VALUE':
return {
...state,
values: setIn(state.values, msg.payload.field, msg.payload.value),
};
case 'SET_FIELD_TOUCHED':
return {
...state,
touched: setIn(state.touched, msg.payload.field, msg.payload.value),
};
case 'SET_FIELD_ERROR':
return {
...state,
errors: setIn(state.errors, msg.payload.field, msg.payload.value),
};
case 'RESET_FORM':
case 'SET_FORMIK_STATE':
return { ...state, ...msg.payload };
case 'SUBMIT_ATTEMPT':
return {
...state,
touched: setNestedObjectValues<FormikTouched<Values>>(
state.values,
true
),
isSubmitting: true,
isValidating: true,
submitCount: state.submitCount + 1,
};
case 'SUBMIT_FAILURE':
return {
...state,
isSubmitting: false,
};
case 'SUBMIT_SUCCESS':
return {
...state,
isSubmitting: false,
};
default:
return state;
}
}
export function useFormik<Values = object>({
validateOnChange = true,
validateOnBlur = true,
isInitialValid = false,
debounceValidationMs = 300,
...rest
}: FormikConfig<Values>) {
const props = { validateOnChange, validateOnBlur, isInitialValid, ...rest };
const initialValues = React.useRef(props.initialValues);
const didMount = React.useRef<boolean>(false);
const fields = React.useRef<{
[field: string]: {
validate: (value: any) => string | Promise<string> | undefined;
};
}>({});
React.useEffect(
() => {
initialValues.current = props.initialValues;
},
[props.initialValues]
);
const [state, dispatch] = React.useReducer<
FormikState<Values>,
FormikMessage<Values>
>(formikReducer, {
values: props.initialValues,
errors: {},
touched: {},
isSubmitting: false,
isValidating: false,
submitCount: 0,
});
const runValidationAsEffect = React.useCallback(
() => {
const [validate, cancel] = makeCancelable(validateForm(state.values));
validate.catch(x => x); // catch the rejection silently
return cancel;
},
[state.values]
);
React.useEffect(
() => {
if (!!validateOnChange && !state.isSubmitting) {
return runValidationAsEffect();
}
return;
},
[state.values, state.isSubmitting]
);
React.useEffect(
() => {
if (!!validateOnBlur && !state.isSubmitting) {
return runValidationAsEffect();
}
return;
},
[state.touched, state.isSubmitting]
);
const imperativeMethods = {
resetForm,
submitForm,
validateForm,
validateField,
setErrors,
setFieldError,
setFieldTouched,
setFieldValue,
setStatus,
setSubmitting,
setTouched,
setValues,
setFormikState,
};
function registerField(name: string, { validate }: any) {
if (fields.current !== null) {
fields.current[name] = {
validate,
};
}
}
function unregisterField(name: string) {
if (fields.current !== null) {
delete fields.current[name];
}
}
function handleBlur(eventOrString: any): void | ((e: any) => void) {
if (isString(eventOrString)) {
return event => executeBlur(event, eventOrString);
} else {
executeBlur(eventOrString);
}
function executeBlur(e: any, path?: string) {
if (e.persist) {
e.persist();
}
const { name, id, outerHTML } = e.target;
const field = path ? path : name ? name : id;
if (!field && process.env.NODE_ENV !== 'production') {
warnAboutMissingIdentifier({
htmlContent: outerHTML,
documentationAnchorLink: 'handleblur-e-any--void',
handlerName: 'handleBlur',
});
}
dispatch({
type: 'SET_FIELD_TOUCHED',
payload: { field, value: true },
});
}
}
function handleChange(
eventOrPath: string | React.ChangeEvent<any>
): void | ((eventOrTextValue: string | React.ChangeEvent<any>) => void) {
if (isString(eventOrPath)) {
return event => executeChange(event, eventOrPath);
} else {
executeChange(eventOrPath);
}
function executeChange(
eventOrTextValue: string | React.ChangeEvent<any>,
maybePath?: string
) {
// By default, assume that the first argument is a string. This allows us to use
// handleChange with React Native and React Native Web's onChangeText prop which
// provides just the value of the input.
let field = maybePath;
let val = eventOrTextValue;
let parsed;
// If the first argument is not a string though, it has to be a synthetic React Event (or a fake one),
// so we handle like we would a normal HTML change event.
if (!isString(eventOrTextValue)) {
// If we can, persist the event
// @see https://reactjs.org/docs/events.html#event-pooling
if ((eventOrTextValue as React.ChangeEvent<any>).persist) {
(eventOrTextValue as React.ChangeEvent<any>).persist();
}
const {
type,
name,
id,
value,
checked,
outerHTML,
} = (eventOrTextValue as React.ChangeEvent<any>).target;
field = maybePath ? maybePath : name ? name : id;
if (!field && process.env.NODE_ENV !== 'production') {
warnAboutMissingIdentifier({
htmlContent: outerHTML,
documentationAnchorLink: 'handlechange-e-reactchangeeventany--void',
handlerName: 'handleChange',
});
}
val = /number|range/.test(type)
? ((parsed = parseFloat(value)), isNaN(parsed) ? '' : parsed)
: /checkbox/.test(type) ? checked : value;
}
if (field) {
// Set form fields by name
dispatch({ type: 'SET_FIELD_VALUE', payload: { field, value: val } });
}
}
}
function handleReset() {
if (props.onReset) {
const maybePromisedOnReset = (props.onReset as any)(
state.values,
imperativeMethods
);
if (isPromise(maybePromisedOnReset)) {
(maybePromisedOnReset as Promise<any>).then(resetForm);
} else {
resetForm();
}
} else {
resetForm();
}
}
function handleSubmit(e: React.FormEvent<HTMLFormElement> | undefined) {
if (e && e.preventDefault) {
e.preventDefault();
}
// Warn if form submission is triggered by a <button> without a
// specified `type` attribute during development. This mitigates
// a common gotcha in forms with both reset and submit buttons,
// where the dev forgets to add type="button" to the reset button.
if (
process.env.NODE_ENV !== 'production' &&
typeof document !== 'undefined'
) {
// Safely get the active element (works with IE)
const activeElement = getActiveElement();
if (
activeElement !== null &&
activeElement instanceof HTMLButtonElement
) {
warning(
!!(
activeElement.attributes &&
activeElement.attributes.getNamedItem('type')
),
'You submitted a Formik form using a button with an unspecified `type` attribute. Most browsers default button elements to `type="submit"`. If this is not a submit button, please add `type="button"`.'
);
}
}
submitForm();
}
function executeSubmit() {
props.onSubmit(state.values, imperativeMethods);
}
function resetForm(nextValues?: Values) {
const values = nextValues
? nextValues
: initialValues.current !== null
? initialValues.current
: props.initialValues;
initialValues.current = values;
dispatch({
type: 'RESET_FORM',
payload: {
isSubmitting: false,
errors: {},
touched: {},
status: undefined,
values,
isValidating: false,
submitCount: 0,
},
});
}
function setTouched(touched: FormikTouched<Values>) {
dispatch({ type: 'SET_TOUCHED', payload: touched });
}
function setErrors(errors: FormikErrors<Values>) {
dispatch({ type: 'SET_ERRORS', payload: errors });
}
function setValues(values: Values) {
dispatch({ type: 'SET_VALUES', payload: values });
}
function setFieldError(field: string, value: string | undefined) {
dispatch({
type: 'SET_FIELD_ERROR',
payload: { field, value },
});
}
function setFieldValue(
field: string,
value: any
// shouldValidate: boolean = true
) {
dispatch({
type: 'SET_FIELD_VALUE',
payload: {
field,
value,
},
});
}
function setFieldTouched(
field: string,
touched: boolean = true
// shouldValidate: boolean = true
) {
dispatch({
type: 'SET_FIELD_TOUCHED',
payload: {
field,
value: touched,
},
});
}
function validateField(name: string) {
// This will efficiently validate a single field by avoiding state
// changes if the validation function is synchronous. It's different from
// what is called when using validateForm.
if (
fields.current !== null &&
fields.current[name] &&
fields.current[name].validate &&
isFunction(fields.current[name].validate)
) {
const value = getIn(state.values, name);
const maybePromise = fields.current[name].validate(value);
if (isPromise(maybePromise)) {
// Only flip isValidating if the function is async.
dispatch({ type: 'SET_ISVALIDATING', payload: true });
return maybePromise
.then((x: any) => x, (e: any) => e)
.then((error: string) => {
dispatch({
type: 'SET_FIELD_ERROR',
payload: { field: name, value: error },
});
dispatch({ type: 'SET_ISVALIDATING', payload: false });
});
} else {
dispatch({
type: 'SET_FIELD_ERROR',
payload: {
field: name,
value: maybePromise as string | undefined,
},
});
return Promise.resolve(maybePromise as string | undefined);
}
} else {
return Promise.resolve();
}
}
function runValidateHandler(
values: Values,
field?: string
): Promise<FormikErrors<Values>> {
return new Promise(resolve => {
const maybePromisedErrors = (props.validate as any)(values, field);
if (maybePromisedErrors === undefined) {
resolve({});
} else if (isPromise(maybePromisedErrors)) {
(maybePromisedErrors as Promise<any>).then(
() => {
resolve({});
},
errors => {
resolve(errors);
}
);
} else {
resolve(maybePromisedErrors);
}
});
}
/**
* Run validation against a Yup schema and optionally run a function if successful
*/
function runValidationSchema(values: Values, field?: string) {
return new Promise(resolve => {
const { validationSchema } = props;
const schema = isFunction(validationSchema)
? validationSchema(field)
: validationSchema;
let promise =
field && schema.validateAt
? schema.validateAt(field, values)
: validateYupSchema(values, schema);
promise.then(
() => {
resolve({});
},
(err: any) => {
resolve(yupToFormErrors(err));
}
);
});
}
/**
* Run all validations methods and update state accordingly
*/
function validateForm(
values: Values = state.values
): Promise<FormikErrors<Values>> {
if (props.validationSchema || props.validate) {
return Promise.all([
props.validationSchema ? runValidationSchema(values) : {},
props.validate ? runValidateHandler(values) : {},
]).then(([fieldErrors, schemaErrors]) => {
const combinedErrors = deepmerge.all<FormikErrors<Values>>(
[fieldErrors, schemaErrors],
{ arrayMerge }
);
if (!isEqual(state.errors, combinedErrors)) {
dispatch({ type: 'SET_ERRORS', payload: combinedErrors });
}
return combinedErrors;
});
} else {
return Promise.resolve({});
}
}
function setFormikState(
stateOrCb:
| FormikState<Values>
| ((state: FormikState<Values>) => FormikState<Values>)
): void {
if (isFunction(stateOrCb)) {
dispatch({ type: 'SET_FORMIK_STATE', payload: stateOrCb(state) });
} else {
dispatch({ type: 'SET_FORMIK_STATE', payload: stateOrCb });
}
}
function setStatus(status: any) {
dispatch({ type: 'SET_STATUS', payload: status });
}
function setSubmitting(isSubmitting: boolean) {
dispatch({ type: 'SET_ISSUBMITTING', payload: isSubmitting });
}
function submitForm() {
dispatch({ type: 'SUBMIT_ATTEMPT' });
return validateForm().then((combinedErrors: FormikErrors<Values>) => {
dispatch({ type: 'SET_ISVALIDATING', payload: false });
const isActuallyValid = Object.keys(combinedErrors).length === 0;
if (isActuallyValid) {
Promise.resolve(executeSubmit())
.then(() => {
dispatch({ type: 'SUBMIT_SUCCESS' });
})
.catch(_errors => {
dispatch({ type: 'SUBMIT_FAILURE' });
});
} else if (didMount.current) {
// ^^^ Make sure Formik is still mounted before calling setState
dispatch({ type: 'SUBMIT_FAILURE' });
}
});
}
function getFieldProps(
name: string,
type: string
): [
{
value: any;
name: string;
onChange: ((e: React.ChangeEvent<any>) => void);
onBlur: ((e: any) => void);
},
{
value: any;
error?: string | undefined;
touch: boolean;
initialValue?: any;
}
] {
const field = {
name,
value:
type && (type === 'radio' || type === 'checkbox')
? undefined // React uses checked={} for these inputs
: getIn(state.values, name),
onChange: handleChange,
onBlur: handleBlur,
};
return [field, getFieldMeta(name)];
}
function getFieldMeta(name: string) {
return {
value: getIn(state.values, name),
error: getIn(state.errors, name),
touch: getIn(state.touched, name),
initialValue: getIn(initialValues.current, name),
} as {
value: any;
error?: string;
touch: boolean;
initialValue?: any;
};
}
const dirty = React.useMemo(
() => !isEqual(initialValues.current, state.values),
[initialValues.current, state.values]
);
const isValid = React.useMemo(
() =>
dirty
? state.errors && Object.keys(state.errors).length === 0
: isInitialValid !== false && isFunction(isInitialValid)
? (isInitialValid as (props: FormikConfig<Values>) => boolean)(props)
: (isInitialValid as boolean),
[state.errors, dirty, isInitialValid]
);
const ctx = {
...state,
initialValues: initialValues.current || props.initialValues,
handleBlur,
handleChange,
handleReset,
handleSubmit,
resetForm,
setErrors,
setFormikState,
setFieldTouched,
setFieldValue,
setFieldError,
setStatus,
setSubmitting,
setTouched,
setValues,
submitForm,
validateForm,
validateField,
isValid,
dirty,
unregisterField,
registerField,
getFieldProps,
validateOnBlur,
validateOnChange,
};
return ctx;
}
export function Formik<Values = object, ExtraProps = {}>(
props: FormikConfig<Values> & ExtraProps
) {
const formikbag = useFormik<Values>(props);
const { component, children, render } = props;
return (
<FormikProvider value={formikbag}>
{component
? React.createElement(component as any, formikbag)
: render
? render(formikbag)
: children // children come last, always called
? isFunction(children)
? (children as ((bag: FormikProps<Values>) => React.ReactNode))(
formikbag as FormikProps<Values>
)
: !isEmptyChildren(children)
? React.Children.only(children)
: null
: null}
</FormikProvider>
);
}
function warnAboutMissingIdentifier({
htmlContent,
documentationAnchorLink,
handlerName,
}: {
htmlContent: string;
documentationAnchorLink: string;
handlerName: string;
}) {
console.error(
`Warning: Formik called \`${handlerName}\`, but you forgot to pass an \`id\` or \`name\` attribute to your input:
${htmlContent}
Formik cannot determine which value to update. For more info see https://github.com/jaredpalmer/formik#${documentationAnchorLink}
`
);
}
/**
* Transform Yup ValidationError to a more usable object
*/
export function yupToFormErrors<Values>(yupError: any): FormikErrors<Values> {
let errors: any = {} as FormikErrors<Values>;
if (yupError.inner.length === 0) {
return setIn(errors, yupError.path, yupError.message);
}
for (let err of yupError.inner) {
if (!errors[err.path]) {
errors = setIn(errors, err.path, err.message);
}
}
return errors;
}
/**
* Validate a yup schema.
*/
export function validateYupSchema<T extends FormikValues>(
values: T,
schema: any,
sync: boolean = false,
context: any = {}
): Promise<Partial<T>> {
let validateData: Partial<T> = {};
for (let k in values) {
if (values.hasOwnProperty(k)) {
const key = String(k);
validateData[key] = values[key] !== '' ? values[key] : undefined;
}
}
return schema[sync ? 'validateSync' : 'validate'](validateData, {
abortEarly: false,
context: context,
});
}
/**
* deepmerge array merging algorithm
* https://github.com/KyleAMathews/deepmerge#combine-array
*/
function arrayMerge(target: any[], source: any[], options: any): any[] {
const destination = target.slice();
source.forEach(function(e: any, i: number) {
if (typeof destination[i] === 'undefined') {
const cloneRequested = options.clone !== false;
const shouldClone = cloneRequested && options.isMergeableObject(e);
destination[i] = shouldClone
? deepmerge(Array.isArray(e) ? [] : {}, e, options)
: e;
} else if (options.isMergeableObject(e)) {
destination[i] = deepmerge(target[i], e, options);
} else if (target.indexOf(e) === -1) {
destination.push(e);
}
});
return destination;
}