/
useForm.ts
668 lines (573 loc) · 18.6 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
import { computed, ref, Ref, provide, reactive, onMounted, isRef, watch, unref, nextTick, warn } from 'vue';
import isEqual from 'fast-deep-equal/es6';
import type { SchemaOf, ValidationError } from 'yup';
import {
FieldMeta,
FormContext,
SubmissionHandler,
GenericValidateFunction,
ValidationResult,
MaybeRef,
FormState,
FormValidationResult,
PrivateFieldComposite,
YupValidator,
PublicFormContext,
FormErrors,
FormErrorBag,
SchemaValidationMode,
} from './types';
import {
applyFieldMutation,
getFromPath,
isYupValidator,
keysOf,
resolveNextCheckboxValue,
setInPath,
unsetPath,
isFormSubmitEvent,
} from './utils';
import { FormErrorsSymbol, FormContextSymbol, FormInitialValuesSymbol } from './symbols';
interface FormOptions<TValues extends Record<string, any>> {
validationSchema?: MaybeRef<
Record<keyof TValues, GenericValidateFunction | string | Record<string, any>> | SchemaOf<TValues>
>;
initialValues?: MaybeRef<TValues>;
initialErrors?: Record<keyof TValues, string | undefined>;
initialTouched?: Record<keyof TValues, boolean>;
validateOnMount?: boolean;
}
export function useForm<TValues extends Record<string, any> = Record<string, any>>(
opts?: FormOptions<TValues>
): PublicFormContext<TValues> {
// A flat array containing field references
const fields: Ref<PrivateFieldComposite[]> = ref([]);
// If the form is currently submitting
const isSubmitting = ref(false);
// a field map object useful for faster access of fields
const fieldsById = computed<Record<keyof TValues, PrivateFieldComposite | PrivateFieldComposite[]>>(() => {
return fields.value.reduce((acc, field) => {
const fieldPath: keyof TValues = unref(field.name);
// if the field was not added before
if (!acc[fieldPath]) {
acc[fieldPath] = field;
field.idx = -1;
return acc;
}
// if the same name is detected
const existingField: PrivateFieldComposite | PrivateFieldComposite[] = acc[fieldPath];
if (!Array.isArray(existingField)) {
existingField.idx = 0;
acc[fieldPath] = [existingField];
}
const fieldGroup = acc[fieldPath] as PrivateFieldComposite[];
field.idx = fieldGroup.length;
fieldGroup.push(field);
return acc;
}, {} as Record<keyof TValues, PrivateFieldComposite | PrivateFieldComposite[]>);
});
// The number of times the user tried to submit the form
const submitCount = ref(0);
// a private ref for all form values
const formValues = reactive({}) as TValues;
// a lookup to keep track of values by their field ids
// this is important because later we need it if fields swap names
const valuesByFid: Record<string, any> = {};
// 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>);
});
// initial form values
const { readonlyInitialValues, initialValues, setInitialValues } = useFormInitialValues<TValues>(
fieldsById,
formValues,
opts?.initialValues
);
// form meta aggregations
const meta = useFormMeta(fields, formValues, readonlyInitialValues);
/**
* 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: PrivateFieldComposite | PrivateFieldComposite[] | undefined = fieldsById.value[field];
// Multiple checkboxes, and only one of them got updated
if (Array.isArray(fieldInstance) && fieldInstance[0]?.type === 'checkbox' && !Array.isArray(value)) {
const newVal = resolveNextCheckboxValue(getFromPath(formValues, field as string) || [], value, undefined);
setInPath(formValues, field as string, newVal);
fieldInstance.forEach(fieldItem => {
valuesByFid[fieldItem.fid] = newVal;
});
return;
}
let newValue = value;
// Single Checkbox: toggles the field value unless the field is being reset then force it
if (!Array.isArray(fieldInstance) && fieldInstance?.type === 'checkbox' && !force) {
newValue = 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);
// multiple radio fields
if (fieldInstance && Array.isArray(fieldInstance)) {
fieldInstance.forEach(fieldItem => {
valuesByFid[fieldItem.fid] = newValue;
});
return;
}
if (fieldInstance) {
valuesByFid[fieldInstance.fid] = newValue;
}
}
/**
* Sets multiple fields values
*/
function setValues(fields: Partial<TValues>) {
keysOf(fields).forEach(field => {
setFieldValue(field, fields[field]);
});
}
/**
* Sets the touched meta state on a field
*/
function setFieldTouched(field: keyof TValues, isTouched: boolean) {
const fieldInstance: PrivateFieldComposite | PrivateFieldComposite[] | undefined = fieldsById.value[field];
if (!fieldInstance) {
return;
}
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
*/
const resetForm = (state?: Partial<FormState<TValues>>) => {
// set initial values if provided
if (state?.values) {
setInitialValues(state.values);
}
// Reset all fields state
fields.value.forEach(f => f.resetField());
if (state?.touched) {
setTouched(state.touched);
}
if (state?.errors) {
setErrors(state.errors);
}
submitCount.value = state?.submitCount || 0;
};
function registerField(field: PrivateFieldComposite<unknown>) {
fields.value.push(field);
if (isRef(field.name)) {
valuesByFid[field.fid] = field.value.value;
// ensures when a field's name was already taken that it preserves its same value
// necessary for fields generated by loops
watch(
field.name,
newPath => {
setFieldValue(newPath, valuesByFid[field.fid]);
},
{
flush: 'post',
}
);
}
}
function unregisterField(field: PrivateFieldComposite<unknown>) {
const idx = fields.value.indexOf(field);
if (idx === -1) {
return;
}
fields.value.splice(idx, 1);
const fid = field.fid;
// cleans up the field value from fid lookup
nextTick(() => {
delete valuesByFid[fid];
});
const fieldName = unref(field.name);
// in this case, this is a single field not a group (checkbox or radio)
// so remove the field value key immediately
if (field.idx === -1) {
// avoid un-setting the value if the field was switched with another that shares the same name
// #3166
const isSharingName = fields.value.find(f => unref(f.name) === fieldName);
if (isSharingName) {
return;
}
unsetPath(formValues, fieldName);
unsetPath(initialValues.value, fieldName);
return;
}
// otherwise find the actual value in the current array of values and remove it
const valueIdx: number | undefined = getFromPath<unknown[] | undefined>(formValues, fieldName)?.indexOf?.(
unref(field.valueProp)
);
if (valueIdx === undefined) {
unsetPath(formValues, fieldName);
return;
}
if (valueIdx === -1) {
return;
}
if (Array.isArray(formValues[fieldName])) {
unsetPath(formValues, `${fieldName}.${valueIdx}`);
return;
}
unsetPath(formValues, fieldName);
unsetPath(initialValues.value, fieldName);
}
async function validate(): Promise<FormValidationResult<TValues>> {
function resultReducer(acc: FormValidationResult<TValues>, result: { key: keyof TValues; errors: string[] }) {
if (!result.errors.length) {
return acc;
}
acc.valid = false;
acc.errors[result.key] = result.errors[0];
return acc;
}
if (formCtx.validateSchema) {
return formCtx.validateSchema('force').then(results => {
return keysOf(results)
.map(r => ({ key: r, errors: results[r].errors }))
.reduce(resultReducer, { errors: {}, valid: true });
});
}
const results = await Promise.all(
fields.value.map(f => {
return f.validate().then((result: ValidationResult) => {
return {
key: unref(f.name),
errors: result.errors,
};
});
})
);
return results.reduce(resultReducer, { errors: {}, valid: true });
}
async function validateField(field: keyof TValues): Promise<ValidationResult> {
const fieldInstance: PrivateFieldComposite | PrivateFieldComposite[] | undefined = fieldsById.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();
}
const handleSubmit = (fn?: SubmissionHandler<TValues>) => {
return function submissionHandler(e: unknown) {
if (e instanceof Event) {
e.preventDefault();
e.stopPropagation();
}
isSubmitting.value = true;
submitCount.value++;
return validate()
.then(result => {
if (result.valid && typeof fn === 'function') {
return fn(immutableFormValues.value, {
evt: e as Event,
setErrors,
setFieldError,
setTouched,
setFieldTouched,
setValues,
setFieldValue,
resetForm,
});
}
})
.then(
() => {
isSubmitting.value = false;
},
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, value);
}
/**
* Sneaky function to set initial field values
*/
function stageInitialValue(path: string, value: unknown) {
setInPath(formValues, path, value);
setFieldInitialValue(path, value);
}
const schema = opts?.validationSchema;
const formCtx: FormContext<TValues> = {
register: registerField,
unregister: unregisterField,
fieldsById,
values: formValues,
setFieldErrorBag,
errorBag,
schema,
submitCount,
validateSchema: isYupValidator(unref(schema))
? mode => {
return validateYupSchema(formCtx, mode);
}
: undefined,
validate,
validateField,
setFieldValue,
setValues,
setErrors,
setFieldError,
setFieldTouched,
setTouched,
resetForm,
meta,
isSubmitting,
handleSubmit,
stageInitialValue,
setFieldInitialValue,
};
const immutableFormValues = computed<TValues>(() => {
return fields.value.reduce((formData: Record<keyof TValues, any>, field) => {
setInPath(formData, unref(field.name), unref(field.value));
return formData;
}, {} as 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(FormContextSymbol, formCtx as FormContext);
provide(FormErrorsSymbol, errors);
return {
errors,
meta,
values: formValues,
isSubmitting,
submitCount,
validate,
validateField,
handleReset: () => resetForm(),
resetForm,
handleSubmit,
submitForm,
setFieldError,
setErrors,
setFieldValue,
setValues,
setFieldTouched,
setTouched,
};
}
/**
* Manages form meta aggregation
*/
function useFormMeta<TValues extends Record<string, unknown>>(
fields: Ref<PrivateFieldComposite[]>,
currentValues: TValues,
initialValues: MaybeRef<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));
});
return computed(() => {
const flags = keysOf(MERGE_STRATEGIES).reduce((acc, flag) => {
const mergeMethod = MERGE_STRATEGIES[flag];
acc[flag] = fields.value[mergeMethod](field => field.meta[flag]);
return acc;
}, {} as Record<keyof Omit<FieldMeta<unknown>, 'initialValue'>, boolean>);
return {
initialValues: unref(initialValues) as TValues,
...flags,
dirty: isDirty.value,
};
});
}
async function validateYupSchema<TValues>(
form: FormContext<TValues>,
mode: SchemaValidationMode
): Promise<Record<keyof TValues, ValidationResult>> {
const errors: ValidationError[] = await (unref(form.schema) as YupValidator)
.validate(form.values, { abortEarly: false })
.then(() => [])
.catch((err: ValidationError) => {
// Yup errors have a name prop one them.
// https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string
if (err.name !== 'ValidationError') {
throw err;
}
// list of aggregated errors
return err.inner || [];
});
const fieldsById = form.fieldsById.value || {};
const errorsByPath = errors.reduce((acc, err) => {
acc[err.path as keyof TValues] = err;
return acc;
}, {} as Record<keyof TValues, ValidationError>);
// Aggregates the validation result
const aggregatedResult = keysOf(fieldsById).reduce((result: Record<keyof TValues, ValidationResult>, fieldId) => {
const field: PrivateFieldComposite | PrivateFieldComposite[] = fieldsById[fieldId];
const messages = (errorsByPath[fieldId] || { errors: [] }).errors;
const fieldResult = {
errors: messages,
valid: !messages.length,
};
result[fieldId] = fieldResult;
if (mode === 'silent') {
applyFieldMutation(field, f => (f.meta.valid = fieldResult.valid));
return result;
}
const wasValidated = Array.isArray(field) ? field.some(f => f.meta.validated) : field.meta.validated;
if (mode === 'validated-only' && !wasValidated) {
return result;
}
applyFieldMutation(field, f => f.setValidationState(fieldResult), true);
return result;
}, {} as Record<keyof TValues, ValidationResult>);
return aggregatedResult;
}
/**
* Manages the initial values prop
*/
function useFormInitialValues<TValues extends Record<string, any>>(
fields: Ref<Record<keyof TValues, PrivateFieldComposite | PrivateFieldComposite[]>>,
formValues: TValues,
providedValues?: MaybeRef<TValues>
) {
const initialValues = ref<TValues>((unref(providedValues) as TValues) || ({} as TValues));
// acts as a read only proxy of the initial values object
const computedInitials = computed<TValues>(() => {
return initialValues.value as TValues;
});
function setInitialValues(values: Partial<TValues>, updateFields = false) {
initialValues.value = {
...initialValues.value,
...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
const hadInteraction = (f: PrivateFieldComposite) => f.meta.touched;
keysOf(fields.value).forEach(fieldPath => {
const field: PrivateFieldComposite | PrivateFieldComposite[] = fields.value[fieldPath];
const touchedByUser = Array.isArray(field) ? field.some(hadInteraction) : hadInteraction(field);
if (touchedByUser) {
return;
}
const newValue = getFromPath(initialValues.value, fieldPath as string);
setInPath(formValues, fieldPath as string, newValue);
});
}
if (isRef(providedValues)) {
watch(
providedValues,
value => {
setInitialValues(value, true);
},
{
deep: true,
}
);
}
provide(FormInitialValuesSymbol, computedInitials);
return {
readonlyInitialValues: computedInitials,
initialValues,
setInitialValues,
};
}
function useErrorBag<TValues extends Record<string, any>>(initialErrors?: FormErrors<TValues>) {
const errorBag: Ref<FormErrorBag<TValues>> = ref({});
/**
* Manually sets an error message on a specific field
*/
function setFieldErrorBag(field: keyof TValues, message: string | undefined | string[]) {
errorBag.value[field] = Array.isArray(message) ? message : message ? [message] : [];
}
/**
* Sets errors for the fields specified in the object
*/
function setErrorBag(fields: Partial<Record<keyof TValues, string | string[] | undefined>>) {
keysOf(fields).forEach(field => {
setFieldErrorBag(field, fields[field]);
});
}
if (initialErrors) {
setErrorBag(initialErrors);
}
return {
errorBag,
setErrorBag,
setFieldErrorBag,
};
}