/
useForm.ts
950 lines (814 loc) · 28.2 KB
/
useForm.ts
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
import {
computed,
ref,
Ref,
provide,
reactive,
onMounted,
isRef,
watch,
unref,
nextTick,
warn,
markRaw,
watchEffect,
} from 'vue';
import isEqual from 'fast-deep-equal/es6';
import { klona as deepCopy } from 'klona/full';
import {
FieldMeta,
SubmissionHandler,
GenericValidateFunction,
ValidationResult,
MaybeRef,
FormState,
FormValidationResult,
PrivateFieldContext,
PrivateFormContext,
FormContext,
FormErrors,
FormErrorBag,
SchemaValidationMode,
RawFormSchema,
ValidationOptions,
FieldPathLookup,
PrivateFieldArrayContext,
InvalidSubmissionHandler,
MapValues,
} from './types';
import {
getFromPath,
isYupValidator,
keysOf,
resolveNextCheckboxValue,
setInPath,
unsetPath,
isFormSubmitEvent,
debounceAsync,
isEmptyContainer,
} from './utils';
import { FormContextKey } from './symbols';
import { validateYupSchema, validateObjectSchema } from './validate';
import { refreshInspector, registerFormWithDevTools } from './devtools';
import { _useFieldValue } from './useFieldState';
export interface FormOptions<TValues extends Record<string, any>> {
validationSchema?: MaybeRef<
Record<keyof TValues, GenericValidateFunction | string | Record<string, any>> | any | undefined
>;
initialValues?: MaybeRef<TValues>;
initialErrors?: Record<keyof TValues, string | undefined>;
initialTouched?: Record<keyof TValues, boolean>;
validateOnMount?: boolean;
keepValuesOnUnmount?: MaybeRef<boolean>;
}
let FORM_COUNTER = 0;
export function useForm<TValues extends Record<string, any> = Record<string, any>>(
opts?: FormOptions<TValues>
): FormContext<TValues> {
const formId = FORM_COUNTER++;
// Prevents fields from double resetting their values, which causes checkboxes to toggle their initial value
// TODO: This won't be needed if we centralize all the state inside the `form` for form inputs
let RESET_LOCK = false;
// A lookup containing fields or field groups
const fieldsByPath: Ref<FieldPathLookup<TValues>> = ref({} as any);
// If the form is currently submitting
const isSubmitting = ref(false);
// The number of times the user tried to submit the form
const submitCount = ref(0);
// field arrays managed by this form
const fieldArrays: PrivateFieldArrayContext[] = [];
// a private ref for all form values
const formValues = reactive(deepCopy(unref(opts?.initialValues) || {})) as TValues;
// the source of errors for the form fields
const { errorBag, setErrorBag, setFieldErrorBag } = useErrorBag(opts?.initialErrors);
// Gets the first error of each field
const errors = computed<FormErrors<TValues>>(() => {
return keysOf(errorBag.value).reduce((acc, key) => {
const bag = errorBag.value[key];
if (bag && bag.length) {
acc[key] = bag[0];
}
return acc;
}, {} as FormErrors<TValues>);
});
function getFirstFieldAtPath(path: string): PrivateFieldContext<unknown> | undefined {
const fieldOrGroup = fieldsByPath.value[path];
return Array.isArray(fieldOrGroup) ? fieldOrGroup[0] : fieldOrGroup;
}
function fieldExists(path: string) {
return !!fieldsByPath.value[path];
}
/**
* Holds a computed reference to all fields names and labels
*/
const fieldNames = computed(() => {
return keysOf(fieldsByPath.value).reduce((names, path) => {
const field = getFirstFieldAtPath(path as string);
if (field) {
names[path as string] = unref(field.label || field.name) || '';
}
return names;
}, {} as Record<string, string>);
});
const fieldBailsMap = computed(() => {
return keysOf(fieldsByPath.value).reduce((map, path) => {
const field = getFirstFieldAtPath(path as string);
if (field) {
map[path as string] = field.bails ?? true;
}
return map;
}, {} as Record<string, boolean>);
});
// mutable non-reactive reference to initial errors
// we need this to process initial errors then unset them
const initialErrors = { ...(opts?.initialErrors || {}) };
const keepValuesOnUnmount = opts?.keepValuesOnUnmount ?? false;
// initial form values
const { initialValues, originalInitialValues, setInitialValues } = useFormInitialValues<TValues>(
fieldsByPath,
formValues,
opts?.initialValues
);
// form meta aggregations
const meta = useFormMeta(fieldsByPath, formValues, originalInitialValues, errors);
const schema = opts?.validationSchema;
const formCtx: PrivateFormContext<TValues> = {
formId,
fieldsByPath,
values: formValues,
errorBag,
errors,
schema,
submitCount,
meta,
isSubmitting,
fieldArrays,
keepValuesOnUnmount,
validateSchema: unref(schema) ? validateSchema : undefined,
validate,
register: registerField,
unregister: unregisterField,
setFieldErrorBag,
validateField,
setFieldValue,
setValues,
setErrors,
setFieldError,
setFieldTouched,
setTouched,
resetForm,
handleSubmit,
stageInitialValue,
unsetInitialValue,
setFieldInitialValue,
useFieldModel,
};
function isFieldGroup(
fieldOrGroup: PrivateFieldContext | PrivateFieldContext[]
): fieldOrGroup is PrivateFieldContext[] {
return Array.isArray(fieldOrGroup);
}
function applyFieldMutation(
fieldOrGroup: PrivateFieldContext | PrivateFieldContext[],
mutation: (f: PrivateFieldContext) => unknown
) {
if (Array.isArray(fieldOrGroup)) {
return fieldOrGroup.forEach(mutation);
}
return mutation(fieldOrGroup);
}
function mutateAllFields(mutation: (f: PrivateFieldContext) => unknown) {
Object.values(fieldsByPath.value).forEach(field => {
if (!field) {
return;
}
// avoid resetting the field values, because they should've been reset already.
applyFieldMutation(field, mutation);
});
}
/**
* Manually sets an error message on a specific field
*/
function setFieldError(field: keyof TValues, message: string | string[] | undefined) {
setFieldErrorBag(field, message);
}
/**
* Sets errors for the fields specified in the object
*/
function setErrors(fields: Partial<Record<keyof TValues, string | string[] | undefined>>) {
setErrorBag(fields);
}
/**
* Sets a single field value
*/
function setFieldValue<T extends keyof TValues = string>(
field: T,
value: TValues[T] | undefined,
{ force } = { force: false }
) {
const fieldInstance = fieldsByPath.value[field];
const clonedValue = deepCopy(value);
// field wasn't found, create a virtual field as a placeholder
if (!fieldInstance) {
setInPath(formValues, field as string, clonedValue);
return;
}
if (isFieldGroup(fieldInstance) && fieldInstance[0]?.type === 'checkbox' && !Array.isArray(value)) {
// Multiple checkboxes, and only one of them got updated
const newValue = deepCopy(
resolveNextCheckboxValue(getFromPath(formValues, field as string) || [], value, undefined)
);
setInPath(formValues, field as string, newValue);
return;
}
let newValue = value;
// Single Checkbox: toggles the field value unless the field is being reset then force it
if (!isFieldGroup(fieldInstance) && fieldInstance.type === 'checkbox' && !force && !RESET_LOCK) {
newValue = deepCopy(
resolveNextCheckboxValue<TValues[T]>(
getFromPath<TValues[T]>(formValues, field as string) as TValues[T],
value as TValues[T],
unref(fieldInstance.uncheckedValue) as TValues[T]
)
);
}
setInPath(formValues, field as string, newValue);
}
/**
* Sets multiple fields values
*/
function setValues(fields: Partial<TValues>) {
// clean up old values
keysOf(formValues).forEach(key => {
delete formValues[key];
});
// set up new values
keysOf(fields).forEach(path => {
setFieldValue(path, fields[path]);
});
// regenerate the arrays when the form values change
fieldArrays.forEach(f => f && f.reset());
}
function createModel<TPath extends keyof TValues>(path: MaybeRef<TPath>) {
const { value } = _useFieldValue<TValues[TPath]>(path as string);
watch(
value,
() => {
if (!fieldExists(unref(path as string))) {
validate({ mode: 'validated-only' });
}
},
{
deep: true,
}
);
return value;
}
function useFieldModel<TPath extends keyof TValues>(path: MaybeRef<TPath>): Ref<TValues[TPath]>;
function useFieldModel<TPath extends keyof TValues>(paths: [...TPath[]]): MapValues<typeof paths, TValues>;
function useFieldModel<TPath extends keyof TValues>(path: MaybeRef<TPath> | [...MaybeRef<TPath>[]]) {
if (!Array.isArray(path)) {
return createModel<TPath>(path);
}
return path.map(createModel) as MapValues<typeof path, TValues>;
}
/**
* Sets the touched meta state on a field
*/
function setFieldTouched(field: keyof TValues, isTouched: boolean) {
const fieldInstance = fieldsByPath.value[field];
if (fieldInstance) {
applyFieldMutation(fieldInstance, f => f.setTouched(isTouched));
}
}
/**
* Sets the touched meta state on multiple fields
*/
function setTouched(fields: Partial<Record<keyof TValues, boolean>>) {
keysOf(fields).forEach(field => {
setFieldTouched(field, !!fields[field]);
});
}
/**
* Resets all fields
*/
function resetForm(state?: Partial<FormState<TValues>>) {
RESET_LOCK = true;
// set initial values if provided
if (state?.values) {
setInitialValues(state.values);
setValues(state?.values);
} else {
// clean up the initial values back to the original
setInitialValues(originalInitialValues.value);
// otherwise clean the current values
setValues(originalInitialValues.value);
}
// avoid resetting the field values, because they should've been reset already.
mutateAllFields(f => f.resetField());
if (state?.touched) {
setTouched(state.touched);
}
setErrors(state?.errors || {});
submitCount.value = state?.submitCount || 0;
nextTick(() => {
RESET_LOCK = false;
});
}
function insertFieldAtPath(field: PrivateFieldContext, path: string) {
const rawField = markRaw(field);
const fieldPath: keyof TValues = path;
// first field at that path
if (!fieldsByPath.value[fieldPath]) {
fieldsByPath.value[fieldPath] = rawField;
return;
}
const fieldAtPath = fieldsByPath.value[fieldPath];
if (fieldAtPath && !Array.isArray(fieldAtPath)) {
fieldsByPath.value[fieldPath] = [fieldAtPath];
}
// add the new array to that path
fieldsByPath.value[fieldPath] = [...(fieldsByPath.value[fieldPath] as PrivateFieldContext[]), rawField];
}
function removeFieldFromPath(field: PrivateFieldContext, path: string) {
const fieldPath: keyof TValues = path;
const fieldAtPath = fieldsByPath.value[fieldPath];
if (!fieldAtPath) {
return;
}
// same field at path
if (!isFieldGroup(fieldAtPath) && field.id === fieldAtPath.id) {
delete fieldsByPath.value[fieldPath];
return;
}
if (isFieldGroup(fieldAtPath)) {
const idx = fieldAtPath.findIndex(f => f.id === field.id);
if (idx === -1) {
return;
}
fieldAtPath.splice(idx, 1);
if (!fieldAtPath.length) {
delete fieldsByPath.value[fieldPath];
}
}
}
function registerField(field: PrivateFieldContext) {
const fieldPath = unref(field.name);
insertFieldAtPath(field, fieldPath);
if (isRef(field.name)) {
// ensures when a field's name was already taken that it preserves its same value
// necessary for fields generated by loops
watch(field.name, async (newPath, oldPath) => {
// cache the value
await nextTick();
removeFieldFromPath(field, oldPath);
insertFieldAtPath(field, newPath);
// re-validate if either path had errors before
if (errors.value[oldPath] || errors.value[newPath]) {
// clear up both paths errors
setFieldError(oldPath, undefined);
validateField(newPath);
}
// clean up the old path if no other field is sharing that name
// #3325
await nextTick();
if (!fieldExists(oldPath)) {
unsetPath(formValues, oldPath);
}
});
}
// if field already had errors (initial errors) that's not user-set, validate it again to ensure state is correct
// the difference being that `initialErrors` will contain the error message while other errors (pre-validated schema) won't have them as initial errors
// #3342
const initialErrorMessage = unref(field.errorMessage);
if (initialErrorMessage && initialErrors?.[fieldPath] !== initialErrorMessage) {
validateField(fieldPath);
}
// marks the initial error as "consumed" so it won't be matched later with same non-initial error
delete initialErrors[fieldPath];
}
function unregisterField(field: PrivateFieldContext<unknown>) {
const fieldName = unref(field.name);
const fieldInstance = fieldsByPath.value[fieldName];
const isGroup = !!fieldInstance && isFieldGroup(fieldInstance);
removeFieldFromPath(field, fieldName);
// clears a field error on unmounted
// we wait till next tick to make sure if the field is completely removed and doesn't have any siblings like checkboxes
nextTick(() => {
const shouldKeepValue = unref(field.keepValueOnUnmount) ?? unref(keepValuesOnUnmount);
const currentGroupValue = getFromPath(formValues, fieldName);
// The boolean here is we check if the field still belongs to the same control group with that name
// if another group claimed the name, we should avoid handling it since it is no longer the same group
// this happens with `v-for` over some checkboxes and field arrays.
// also if the group no longer exist we can assume this group was the last one that controlled it
const isSameGroup =
isGroup && (fieldInstance === fieldsByPath.value[fieldName] || !fieldsByPath.value[fieldName]);
// group field that still has a dangling value, the field may exist or not after it was removed.
// This used to be handled in the useField composable but the form has better context on when it should/not happen.
// if it does belong to it that means the group still exists
// #3844
if (isSameGroup && Array.isArray(currentGroupValue) && !shouldKeepValue) {
const valueIdx = currentGroupValue.findIndex(i => isEqual(i, unref(field.checkedValue)));
if (valueIdx > -1) {
const newVal = [...currentGroupValue];
newVal.splice(valueIdx, 1);
setFieldValue(fieldName, newVal as any, { force: true });
}
}
// Field was removed entirely, we should unset its path
// #3384
if (!fieldExists(fieldName)) {
setFieldError(fieldName, undefined);
// Checks if the field was configured to be unset during unmount or not
// Checks both the form-level config and field-level one
// Field has the priority if it is set, otherwise it goes to the form settings
if (shouldKeepValue) {
return;
}
if (isGroup && !isEmptyContainer(getFromPath(formValues, fieldName))) {
return;
}
unsetPath(formValues, fieldName);
}
});
}
async function validate(opts?: Partial<ValidationOptions>): Promise<FormValidationResult<TValues>> {
mutateAllFields(f => (f.meta.validated = true));
if (formCtx.validateSchema) {
return formCtx.validateSchema(opts?.mode || 'force');
}
// No schema, each field is responsible to validate itself
const validations = await Promise.all(
Object.values(fieldsByPath.value).map(field => {
const fieldInstance: PrivateFieldContext | undefined = Array.isArray(field) ? field[0] : field;
if (!fieldInstance) {
return Promise.resolve({ key: '', valid: true, errors: [] });
}
return fieldInstance.validate(opts).then((result: ValidationResult) => {
return {
key: unref(fieldInstance.name),
valid: result.valid,
errors: result.errors,
};
});
})
);
const results: Partial<Record<keyof TValues, ValidationResult>> = {};
const errors: Partial<Record<keyof TValues, string>> = {};
for (const validation of validations) {
results[validation.key as keyof TValues] = {
valid: validation.valid,
errors: validation.errors,
};
if (validation.errors.length) {
errors[validation.key as keyof TValues] = validation.errors[0];
}
}
return {
valid: validations.every(r => r.valid),
results,
errors,
};
}
async function validateField(field: keyof TValues): Promise<ValidationResult> {
const fieldInstance = fieldsByPath.value[field];
if (!fieldInstance) {
warn(`field with name ${field} was not found`);
return Promise.resolve({ errors: [], valid: true });
}
if (Array.isArray(fieldInstance)) {
return fieldInstance.map(f => f.validate())[0];
}
return fieldInstance.validate();
}
function handleSubmit<TReturn = unknown>(
fn?: SubmissionHandler<TValues, TReturn>,
onValidationError?: InvalidSubmissionHandler<TValues>
) {
return function submissionHandler(e: unknown) {
if (e instanceof Event) {
e.preventDefault();
e.stopPropagation();
}
// Touch all fields
setTouched(
keysOf(fieldsByPath.value).reduce((acc, field) => {
acc[field] = true;
return acc;
}, {} as Record<keyof TValues, boolean>)
);
isSubmitting.value = true;
submitCount.value++;
return validate()
.then(result => {
if (result.valid && typeof fn === 'function') {
return fn(deepCopy(formValues), {
evt: e as Event,
setErrors,
setFieldError,
setTouched,
setFieldTouched,
setValues,
setFieldValue,
resetForm,
});
}
if (!result.valid && typeof onValidationError === 'function') {
onValidationError({
values: deepCopy(formValues),
evt: e as Event,
errors: result.errors,
results: result.results,
});
}
})
.then(
returnVal => {
isSubmitting.value = false;
return returnVal;
},
err => {
isSubmitting.value = false;
// re-throw the err so it doesn't go silent
throw err;
}
);
};
}
function setFieldInitialValue(path: string, value: unknown) {
setInPath(initialValues.value, path, deepCopy(value));
}
function unsetInitialValue(path: string) {
unsetPath(initialValues.value, path);
}
/**
* Sneaky function to set initial field values
*/
function stageInitialValue(path: string, value: unknown, updateOriginal = false) {
setInPath(formValues, path, value);
setFieldInitialValue(path, value);
if (updateOriginal && !opts?.initialValues) {
setInPath(originalInitialValues.value, path, deepCopy(value));
}
}
async function _validateSchema(): Promise<FormValidationResult<TValues>> {
const schemaValue = unref(schema);
if (!schemaValue) {
return { valid: true, results: {}, errors: {} };
}
const formResult = isYupValidator(schemaValue)
? await validateYupSchema(schemaValue, formValues)
: await validateObjectSchema(schemaValue as RawFormSchema<TValues>, formValues, {
names: fieldNames.value,
bailsMap: fieldBailsMap.value,
});
return formResult;
}
/**
* Batches validation runs in 5ms batches
* Must have two distinct batch queues to make sure they don't override each other settings #3783
*/
const debouncedSilentValidation = debounceAsync(_validateSchema, 5);
const debouncedValidation = debounceAsync(_validateSchema, 5);
async function validateSchema(mode: SchemaValidationMode): Promise<FormValidationResult<TValues>> {
const formResult = await (mode === 'silent' ? debouncedSilentValidation() : debouncedValidation());
// fields by id lookup
const fieldsById = formCtx.fieldsByPath.value || {};
// errors fields names, we need it to also check if custom errors are updated
const currentErrorsPaths = keysOf(formCtx.errorBag.value);
// collect all the keys from the schema and all fields
// this ensures we have a complete keymap of all the fields
const paths = [
...new Set([...keysOf(formResult.results), ...keysOf(fieldsById), ...currentErrorsPaths]),
] as string[];
// aggregates the paths into a single result object while applying the results on the fields
return paths.reduce(
(validation, path) => {
const field = fieldsById[path];
const messages = (formResult.results[path] || { errors: [] as string[] }).errors;
const fieldResult = {
errors: messages,
valid: !messages.length,
};
validation.results[path as keyof TValues] = fieldResult;
if (!fieldResult.valid) {
validation.errors[path as keyof TValues] = fieldResult.errors[0];
}
// field not rendered
if (!field) {
setFieldError(path, messages);
return validation;
}
// always update the valid flag regardless of the mode
applyFieldMutation(field, f => (f.meta.valid = fieldResult.valid));
if (mode === 'silent') {
return validation;
}
const wasValidated = Array.isArray(field) ? field.some(f => f.meta.validated) : field.meta.validated;
if (mode === 'validated-only' && !wasValidated) {
return validation;
}
applyFieldMutation(field, f => f.setState({ errors: fieldResult.errors }));
return validation;
},
{ valid: formResult.valid, results: {}, errors: {} } as FormValidationResult<TValues>
);
}
const submitForm = handleSubmit((_, { evt }) => {
if (isFormSubmitEvent(evt)) {
evt.target.submit();
}
});
// Trigger initial validation
onMounted(() => {
if (opts?.initialErrors) {
setErrors(opts.initialErrors);
}
if (opts?.initialTouched) {
setTouched(opts.initialTouched);
}
// if validate on mount was enabled
if (opts?.validateOnMount) {
validate();
return;
}
// otherwise run initial silent validation through schema if available
// the useField should skip their own silent validation if a yup schema is present
if (formCtx.validateSchema) {
formCtx.validateSchema('silent');
}
});
if (isRef(schema)) {
watch(schema, () => {
formCtx.validateSchema?.('validated-only');
});
}
// Provide injections
provide(FormContextKey, formCtx as PrivateFormContext);
if (__DEV__) {
registerFormWithDevTools(formCtx as PrivateFormContext);
watch(
() => ({
errors: errorBag.value,
...meta.value,
values: formValues,
isSubmitting: isSubmitting.value,
submitCount: submitCount.value,
}),
refreshInspector,
{
deep: true,
}
);
}
return {
errors,
meta,
values: formValues,
isSubmitting,
submitCount,
validate,
validateField,
handleReset: () => resetForm(),
resetForm,
handleSubmit,
submitForm,
setFieldError,
setErrors,
setFieldValue,
setValues,
setFieldTouched,
setTouched,
useFieldModel,
};
}
/**
* Manages form meta aggregation
*/
function useFormMeta<TValues extends Record<string, unknown>>(
fieldsByPath: Ref<FieldPathLookup<TValues>>,
currentValues: TValues,
initialValues: MaybeRef<TValues>,
errors: Ref<FormErrors<TValues>>
) {
const MERGE_STRATEGIES: Record<keyof Pick<FieldMeta<unknown>, 'touched' | 'pending' | 'valid'>, 'every' | 'some'> = {
touched: 'some',
pending: 'some',
valid: 'every',
};
const isDirty = computed(() => {
return !isEqual(currentValues, unref(initialValues));
});
function calculateFlags() {
const fields = Object.values(fieldsByPath.value).flat(1).filter(Boolean) as PrivateFieldContext[];
return keysOf(MERGE_STRATEGIES).reduce((acc, flag) => {
const mergeMethod = MERGE_STRATEGIES[flag];
acc[flag] = fields[mergeMethod](field => field.meta[flag]);
return acc;
}, {} as Record<keyof Omit<FieldMeta<unknown>, 'initialValue'>, boolean>);
}
const flags = reactive(calculateFlags());
watchEffect(() => {
const value = calculateFlags();
flags.touched = value.touched;
flags.valid = value.valid;
flags.pending = value.pending;
});
return computed(() => {
return {
initialValues: unref(initialValues) as TValues,
...flags,
valid: flags.valid && !keysOf(errors.value as any).length,
dirty: isDirty.value,
};
});
}
/**
* Manages the initial values prop
*/
function useFormInitialValues<TValues extends Record<string, any>>(
fields: Ref<FieldPathLookup<TValues>>,
formValues: TValues,
providedValues?: MaybeRef<TValues>
) {
// these are the mutable initial values as the fields are mounted/unmounted
const initialValues = ref<TValues>(deepCopy(unref(providedValues) as TValues) || ({} as TValues));
// these are the original initial value as provided by the user initially, they don't keep track of conditional fields
// this is important because some conditional fields will overwrite the initial values for other fields who had the same name
// like array fields, any push/insert operation will overwrite the initial values because they "create new fields"
// so these are the values that the reset function should use
// these only change when the user explicitly chanegs the initial values or when the user resets them with new values.
const originalInitialValues = ref<TValues>(deepCopy(unref(providedValues) as TValues) || ({} as TValues));
function setInitialValues(values: Partial<TValues>, updateFields = false) {
initialValues.value = deepCopy(values);
originalInitialValues.value = deepCopy(values);
if (!updateFields) {
return;
}
// update the pristine non-touched fields
// those are excluded because it's unlikely you want to change the form values using initial values
// we mostly watch them for API population or newly inserted fields
// if the user API is taking too much time before user interaction they should consider disabling or hiding their inputs until the values are ready
keysOf(fields.value).forEach(fieldPath => {
const field = fields.value[fieldPath];
const wasTouched = Array.isArray(field) ? field.some(f => f.meta.touched) : field?.meta.touched;
if (!field || wasTouched) {
return;
}
const newValue = getFromPath(initialValues.value, fieldPath as string);
setInPath(formValues, fieldPath as string, deepCopy(newValue));
});
}
if (isRef(providedValues)) {
watch(
providedValues,
value => {
setInitialValues(value, true);
},
{
deep: true,
}
);
}
return {
initialValues,
originalInitialValues,
setInitialValues,
};
}
function useErrorBag<TValues extends Record<string, any>>(initialErrors?: FormErrors<TValues>) {
const errorBag: Ref<FormErrorBag<TValues>> = ref({});
function normalizeErrorItem(message: string | string[]) {
return Array.isArray(message) ? message : message ? [message] : [];
}
/**
* Manually sets an error message on a specific field
*/
function setFieldErrorBag(field: keyof TValues, message: string | undefined | string[]) {
if (!message) {
delete errorBag.value[field];
return;
}
errorBag.value[field] = normalizeErrorItem(message);
}
/**
* Sets errors for the fields specified in the object
*/
function setErrorBag(fields: Partial<Record<keyof TValues, string | string[] | undefined>>) {
errorBag.value = keysOf(fields).reduce((acc, key) => {
const message = fields[key] as string | string[] | undefined;
if (message) {
acc[key] = normalizeErrorItem(message);
}
return acc;
}, {} as FormErrorBag<TValues>);
}
if (initialErrors) {
setErrorBag(initialErrors);
}
return {
errorBag,
setErrorBag,
setFieldErrorBag,
};
}