Open History to see the last commit
1import { Store } from '@tanstack/store'
2import {
3 deleteBy,
4 functionalUpdate,
5 getAsyncValidatorArray,
6 getBy,
7 getSyncValidatorArray,
8 isNonEmptyArray,
9 setBy,
10} from './utils'
11import type { Updater } from './utils'
12import type { DeepKeys, DeepValue } from './util-types'
13import type { FieldApi, FieldMeta } from './FieldApi'
14import type {
15 UpdateMetaOptions,
16 ValidationCause,
17 ValidationError,
18 ValidationErrorMap,
19 ValidationErrorMapKeys,
20 Validator,
21} from './types'
22β
23/**
24 * @private
25 */
26export type FormValidateFn<
27 TFormData,
28 TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
29> = (props: {
30 value: TFormData
31 formApi: FormApi<TFormData, TFormValidator>
32}) => ValidationError
33β
34/**
35 * @private
36 */
37export type FormValidateOrFn<
38 TFormData,
39 TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
40> = TFormValidator extends Validator<TFormData, infer TFN>
41 ? TFN
42 : FormValidateFn<TFormData, TFormValidator>
43β
44/**
45 * @private
46 */
47export type FormValidateAsyncFn<
48 TFormData,
49 TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
50> = (props: {
51 value: TFormData
52 formApi: FormApi<TFormData, TFormValidator>
53 signal: AbortSignal
54}) => ValidationError | Promise<ValidationError>
55β
56/**
57 * @private
58 */
59export type FormAsyncValidateOrFn<
60 TFormData,
61 TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
62> = TFormValidator extends Validator<TFormData, infer FFN>
63 ? FFN | FormValidateAsyncFn<TFormData, TFormValidator>
64 : FormValidateAsyncFn<TFormData, TFormValidator>
65β
66export interface FormValidators<
67 TFormData,
68 TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
69> {
70 /**
71 * Optional function that fires as soon as the component mounts.
72 */
73 onMount?: FormValidateOrFn<TFormData, TFormValidator>
74 /**
75 * Optional function that checks the validity of your data whenever a value changes
76 */
77 onChange?: FormValidateOrFn<TFormData, TFormValidator>
78 /**
79 * Optional onChange asynchronous counterpart to onChange. Useful for more complex validation logic that might involve server requests.
80 */
81 onChangeAsync?: FormAsyncValidateOrFn<TFormData, TFormValidator>
82 /**
83 * The default time in milliseconds that if set to a number larger than 0, will debounce the async validation event by this length of time in milliseconds.
84 */
85 onChangeAsyncDebounceMs?: number
86 /**
87 * Optional function that validates the form data when a field loses focus, returns a ValidationError
88 */
89 onBlur?: FormValidateOrFn<TFormData, TFormValidator>
90 /**
91 * Optional onBlur asynchronous validation method for when a field loses focus return a `ValidationError` or a promise of `Promise<ValidationError>`
92 */
93 onBlurAsync?: FormAsyncValidateOrFn<TFormData, TFormValidator>
94 /**
95 * The default time in milliseconds that if set to a number larger than 0, will debounce the async validation event by this length of time in milliseconds.
96 */
97 onBlurAsyncDebounceMs?: number
98 onSubmit?: FormValidateOrFn<TFormData, TFormValidator>
99 onSubmitAsync?: FormAsyncValidateOrFn<TFormData, TFormValidator>
100}
101β
102/**
103 * @private
104 */
105export interface FormTransform<
106 TFormData,
107 TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
108> {
109 fn: (
110 formBase: FormApi<TFormData, TFormValidator>,
111 ) => FormApi<TFormData, TFormValidator>
112 deps: unknown[]
113}
114β
115/**
116 * An object representing the options for a form.
117 */
118export interface FormOptions<
119 TFormData,
120 TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
121> {
122 /**
123 * Set initial values for your form.
124 */
125 defaultValues?: TFormData
126 /**
127 * The default state for the form.
128 */
129 defaultState?: Partial<FormState<TFormData>>
130 /**
131 * If true, always run async validation, even when sync validation has produced an error. Defaults to undefined.
132 */
133 asyncAlways?: boolean
134 /**
135 * Optional time in milliseconds if you want to introduce a delay before firing off an async action.
136 */
137 asyncDebounceMs?: number
138 /**
139 * A validator adapter to support usage of extra validation types (IE: Zod, Yup, or Valibot usage)
140 */
141 validatorAdapter?: TFormValidator
142 /**
143 * A list of validators to pass to the form
144 */
145 validators?: FormValidators<TFormData, TFormValidator>
146 /**
147 * A function to be called when the form is submitted, what should happen once the user submits a valid form returns `any` or a promise `Promise<any>`
148 */
149 onSubmit?: (props: {
150 value: TFormData
151 formApi: FormApi<TFormData, TFormValidator>
152 }) => any | Promise<any>
153 /**
154 * Specify an action for scenarios where the user tries to submit an invalid form.
155 */
156 onSubmitInvalid?: (props: {
157 value: TFormData
158 formApi: FormApi<TFormData, TFormValidator>
159 }) => void
160 transform?: FormTransform<TFormData, TFormValidator>
161}
162β
163/**
164 * An object representing the validation metadata for a field. Not intended for public usage.
165 */
166export type ValidationMeta = {
167 /**
168 * An abort controller stored in memory to cancel previous async validation attempts.
169 */
170 lastAbortController: AbortController
171}
172β
173/**
174 * An object representing the field information for a specific field within the form.
175 */
176export type FieldInfo<
177 TFormData,
178 TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
179> = {
180 /**
181 * An instance of the FieldAPI.
182 */
183 instance: FieldApi<
184 TFormData,
185 any,
186 Validator<unknown, unknown> | undefined,
187 TFormValidator
188 > | null
189 /**
190 * A record of field validation internal handling.
191 */
192 validationMetaMap: Record<ValidationErrorMapKeys, ValidationMeta | undefined>
193}
194β
195/**
196 * An object representing the current state of the form.
197 */
198export type FormState<TFormData> = {
199 /**
200 * The current values of the form fields.
201 */
202 values: TFormData
203 /**
204 * A boolean indicating if the form is currently validating.
205 */
206 isFormValidating: boolean
207 /**
208 * A boolean indicating if the form is valid.
209 */
210 isFormValid: boolean
211 /**
212 * The error array for the form itself.
213 */
214 errors: ValidationError[]
215 /**
216 * The error map for the form itself.
217 */
218 errorMap: ValidationErrorMap
219 /**
220 * An internal mechanism used for keeping track of validation logic in a form.
221 */
222 validationMetaMap: Record<ValidationErrorMapKeys, ValidationMeta | undefined>
223 /**
224 * A record of field metadata for each field in the form.
225 */
226 fieldMeta: Record<DeepKeys<TFormData>, FieldMeta>
227 /**
228 * A boolean indicating if any of the form fields are currently validating.
229 */
230 isFieldsValidating: boolean
231 /**
232 * A boolean indicating if all the form fields are valid.
233 */
234 isFieldsValid: boolean
235 /**
236 * A boolean indicating if the form is currently submitting.
237 */
238 isSubmitting: boolean
239 /**
240 * A boolean indicating if any of the form fields have been touched.
241 */
242 isTouched: boolean
243 /**
244 * A boolean indicating if any of the form's fields' values have been modified by the user. `True` if the user have modified at least one of the fields. Opposite of `isPristine`.
245 */
246 isDirty: boolean
247 /**
248 * A boolean indicating if none of the form's fields' values have been modified by the user. `True` if the user have not modified any of the fields. Opposite of `isDirty`.
249 */
250 isPristine: boolean
251 /**
252 * A boolean indicating if the form has been submitted.
253 */
254 isSubmitted: boolean
255 /**
256 * A boolean indicating if the form or any of its fields are currently validating.
257 */
258 isValidating: boolean
259 /**
260 * A boolean indicating if the form and all its fields are valid.
261 */
262 isValid: boolean
263 /**
264 * A boolean indicating if the form can be submitted based on its current state.
265 */
266 canSubmit: boolean
267 /**
268 * A counter for tracking the number of submission attempts.
269 */
270 submissionAttempts: number
271}
272β
273function getDefaultFormState<TFormData>(
274 defaultState: Partial<FormState<TFormData>>,
275): FormState<TFormData> {
276 return {
277 values: defaultState.values ?? ({} as never),
278 errors: defaultState.errors ?? [],
279 errorMap: defaultState.errorMap ?? {},
280 fieldMeta: defaultState.fieldMeta ?? ({} as never),
281 canSubmit: defaultState.canSubmit ?? true,
282 isFieldsValid: defaultState.isFieldsValid ?? false,
283 isFieldsValidating: defaultState.isFieldsValidating ?? false,
284 isFormValid: defaultState.isFormValid ?? false,
285 isFormValidating: defaultState.isFormValidating ?? false,
286 isSubmitted: defaultState.isSubmitted ?? false,
287 isSubmitting: defaultState.isSubmitting ?? false,
288 isTouched: defaultState.isTouched ?? false,
289 isPristine: defaultState.isPristine ?? true,
290 isDirty: defaultState.isDirty ?? false,
291 isValid: defaultState.isValid ?? false,
292 isValidating: defaultState.isValidating ?? false,
293 submissionAttempts: defaultState.submissionAttempts ?? 0,
294 validationMetaMap: defaultState.validationMetaMap ?? {
295 onChange: undefined,
296 onBlur: undefined,
297 onSubmit: undefined,
298 onMount: undefined,
299 onServer: undefined,
300 },
301 }
302}
303β
304/**
305 * A class representing the Form API. It handles the logic and interactions with the form state.
306 *
307 * Normally, you will not need to create a new `FormApi` instance directly. Instead, you will use a framework
308 * hook/function like `useForm` or `createForm` to create a new instance for you that uses your framework's reactivity model.
309 * However, if you need to create a new instance manually, you can do so by calling the `new FormApi` constructor.
310 */
311export class FormApi<
312 TFormData,
313 TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
314> {
315 /**
316 * The options for the form.
317 */
318 options: FormOptions<TFormData, TFormValidator> = {}
319 /**
320 * A [TanStack Store instance](https://tanstack.com/store/latest/docs/reference/Store) that keeps track of the form's state.
321 */
322 store!: Store<FormState<TFormData>>
323 /**
324 * The current state of the form.
325 *
326 * **Note:**
327 * Do not use `state` directly, as it is not reactive.
328 * Please use form.useStore() utility to subscribe to state
329 */
330 state!: FormState<TFormData>
331 /**
332 * A record of field information for each field in the form.
333 */
334 fieldInfo: Record<DeepKeys<TFormData>, FieldInfo<TFormData, TFormValidator>> =
335 {} as any
336β
337 /**
338 * @private
339 */
340 prevTransformArray: unknown[] = []
341β
342 /**
343 * Constructs a new `FormApi` instance with the given form options.
344 */
345 constructor(opts?: FormOptions<TFormData, TFormValidator>) {
346 this.store = new Store<FormState<TFormData>>(
347 getDefaultFormState({
348 ...(opts?.defaultState as any),
349 values: opts?.defaultValues ?? opts?.defaultState?.values,
350 isFormValid: true,
351 }),
352 {
353 onUpdate: () => {
354 let { state } = this.store
355 // Computed state
356 const fieldMetaValues = Object.values(state.fieldMeta) as (
357 | FieldMeta
358 | undefined
359 )[]
360β
361 const isFieldsValidating = fieldMetaValues.some(
362 (field) => field?.isValidating,
363 )
364β
365 const isFieldsValid = !fieldMetaValues.some(
366 (field) =>
367 field?.errorMap &&
368 isNonEmptyArray(Object.values(field.errorMap).filter(Boolean)),
369 )
370β
371 const isTouched = fieldMetaValues.some((field) => field?.isTouched)
372β
373 const isDirty = fieldMetaValues.some((field) => field?.isDirty)
374 const isPristine = !isDirty
375β
376 const isValidating = isFieldsValidating || state.isFormValidating
377 state.errors = Object.values(state.errorMap).filter(
378 (val: unknown) => val !== undefined,
379 )
380 const isFormValid = state.errors.length === 0
381 const isValid = isFieldsValid && isFormValid
382 const canSubmit =
383 (state.submissionAttempts === 0 && !isTouched) ||
384 (!isValidating && !state.isSubmitting && isValid)
385β
386 state = {
387 ...state,
388 isFieldsValidating,
389 isFieldsValid,
390 isFormValid,
391 isValid,
392 canSubmit,
393 isTouched,
394 isPristine,
395 isDirty,
396 }
397β
398 this.state = state
399 this.store.state = this.state
400β
401 // Only run transform if state has shallowly changed - IE how React.useEffect works
402 const transformArray = this.options.transform?.deps ?? []
403 const shouldTransform =
404 transformArray.length !== this.prevTransformArray.length ||
405 transformArray.some((val, i) => val !== this.prevTransformArray[i])
406β
407 if (shouldTransform) {
408 // This mutates the state
409 this.options.transform?.fn(this)
410 this.store.state = this.state
411 this.prevTransformArray = transformArray
412 }
413 },
414 },
415 )
416β
417 this.state = this.store.state
418β
419 this.update(opts || {})
420 }
421β
422 /**
423 * @private
424 */
425 runValidator<
426 TValue extends { value: TFormData; formApi: FormApi<any, any> },
427 TType extends 'validate' | 'validateAsync',
428 >(props: {
429 validate: TType extends 'validate'
430 ? FormValidateOrFn<TFormData, TFormValidator>
431 : FormAsyncValidateOrFn<TFormData, TFormValidator>
432 value: TValue
433 type: TType
434 }): ReturnType<ReturnType<Validator<any>>[TType]> {
435 const adapter = this.options.validatorAdapter
436 if (adapter && typeof props.validate !== 'function') {
437 return adapter()[props.type](props.value, props.validate) as never
438 }
439β
440 return (props.validate as FormValidateFn<any, any>)(props.value) as never
441 }
442β
443 mount = () => {
444 const { onMount } = this.options.validators || {}
445 if (!onMount) return
446 const error = this.runValidator({
447 validate: onMount,
448 value: {
449 value: this.state.values,
450 formApi: this,
451 },
452 type: 'validate',
453 })
454 if (error) {
455 this.store.setState((prev) => ({
456 ...prev,
457 errorMap: { ...prev.errorMap, onMount: error },
458 }))
459 }
460 }
461β
462 /**
463 * Updates the form options and form state.
464 */
465 update = (options?: FormOptions<TFormData, TFormValidator>) => {
466 if (!options) return
467β
468 const oldOptions = this.options
469β
470 // Options need to be updated first so that when the store is updated, the state is correct for the derived state
471 this.options = options
472β
473 this.store.batch(() => {
474 const shouldUpdateValues =
475 options.defaultValues &&
476 options.defaultValues !== oldOptions.defaultValues &&
477 !this.state.isTouched
478β
479 const shouldUpdateState =
480 options.defaultState !== oldOptions.defaultState &&
481 !this.state.isTouched
482β
483 this.store.setState(() =>
484 getDefaultFormState(
485 Object.assign(
486 {},
487 this.state as any,
488β
489 shouldUpdateState ? options.defaultState : {},
490β
491 shouldUpdateValues
492 ? {
493 values: options.defaultValues,
494 }
495 : {},
496 ),
497 ),
498 )
499 })
500 }
501β
502 /**
503 * Resets the form state to the default values.
504 */
505 reset = () => {
506 const { fieldMeta: currentFieldMeta } = this.state
507 const fieldMeta = this.resetFieldMeta(currentFieldMeta)
508 this.store.setState(() =>
509 getDefaultFormState({
510 ...(this.options.defaultState as any),
511 values: this.options.defaultValues ?? this.options.defaultState?.values,
512 fieldMeta,
513 }),
514 )
515 }
516β
517 /**
518 * Validates all fields in the form using the correct handlers for a given validation type.
519 */
520 validateAllFields = async (cause: ValidationCause) => {
521 const fieldValidationPromises: Promise<ValidationError[]>[] = [] as any
522 this.store.batch(() => {
523 void (
524 Object.values(this.fieldInfo) as FieldInfo<any, TFormValidator>[]
525 ).forEach((field) => {
526 if (!field.instance) return
527 const fieldInstance = field.instance
528 // Validate the field
529 fieldValidationPromises.push(
530 Promise.resolve().then(() => fieldInstance.validate(cause)),
531 )
532 // If any fields are not touched
533 if (!field.instance.state.meta.isTouched) {
534 // Mark them as touched
535 field.instance.setMeta((prev) => ({ ...prev, isTouched: true }))
536 }
537 })
538 })
539β
540 const fieldErrorMapMap = await Promise.all(fieldValidationPromises)
541 return fieldErrorMapMap.flat()
542 }
543β
544 /**
545 * Validates the children of a specified array in the form starting from a given index until the end using the correct handlers for a given validation type.
546 */
547 validateArrayFieldsStartingFrom = async <TField extends DeepKeys<TFormData>>(
548 field: TField,
549 index: number,
550 cause: ValidationCause,
551 ) => {
552 const currentValue = this.getFieldValue(field)
553β
554 const lastIndex = Array.isArray(currentValue)
555 ? Math.max(currentValue.length - 1, 0)
556 : null
557β
558 // We have to validate all fields that have shifted (at least the current field)
559 const fieldKeysToValidate = [`${field}[${index}]`]
560 for (let i = index + 1; i <= (lastIndex ?? 0); i++) {
561 fieldKeysToValidate.push(`${field}[${i}]`)
562 }
563β
564 // We also have to include all fields that are nested in the shifted fields
565 const fieldsToValidate = Object.keys(this.fieldInfo).filter((fieldKey) =>
566 fieldKeysToValidate.some((key) => fieldKey.startsWith(key)),
567 ) as DeepKeys<TFormData>[]
568β
569 // Validate the fields
570 const fieldValidationPromises: Promise<ValidationError[]>[] = [] as any
571 this.store.batch(() => {
572 fieldsToValidate.forEach((nestedField) => {
573 fieldValidationPromises.push(
574 Promise.resolve().then(() => this.validateField(nestedField, cause)),
575 )
576 })
577 })
578β
579 const fieldErrorMapMap = await Promise.all(fieldValidationPromises)
580 return fieldErrorMapMap.flat()
581 }
582β
583 /**
584 * Validates a specified field in the form using the correct handlers for a given validation type.
585 */
586 validateField = <TField extends DeepKeys<TFormData>>(
587 field: TField,
588 cause: ValidationCause,
589 ) => {
590 // eslint-disable-next-line ts/no-unnecessary-condition
591 const fieldInstance = this.fieldInfo[field]?.instance
592 if (!fieldInstance) return []
593β
594 // If the field is not touched (same logic as in validateAllFields)
595 if (!fieldInstance.state.meta.isTouched) {
596 // Mark it as touched
597 fieldInstance.setMeta((prev) => ({ ...prev, isTouched: true }))
598 }
599β
600 return fieldInstance.validate(cause)
601 }
602β
603 /**
604 * TODO: This code is copied from FieldApi, we should refactor to share
605 * @private
606 */
607 validateSync = (cause: ValidationCause) => {
608 const validates = getSyncValidatorArray(cause, this.options)
609 let hasErrored = false as boolean
610β
611 this.store.batch(() => {
612 for (const validateObj of validates) {
613 if (!validateObj.validate) continue
614β
615 const error = normalizeError(
616 this.runValidator({
617 validate: validateObj.validate,
618 value: {
619 value: this.state.values,
620 formApi: this,
621 },
622 type: 'validate',
623 }),
624 )
625 const errorMapKey = getErrorMapKey(validateObj.cause)
626 if (this.state.errorMap[errorMapKey] !== error) {
627 this.store.setState((prev) => ({
628 ...prev,
629 errorMap: {
630 ...prev.errorMap,
631 [errorMapKey]: error,
632 },
633 }))
634 }
635 if (error) {
636 hasErrored = true
637 }
638 }
639 })
640β
641 /**
642 * when we have an error for onSubmit in the state, we want
643 * to clear the error as soon as the user enters a valid value in the field
644 */
645 const submitErrKey = getErrorMapKey('submit')
646 if (
647 this.state.errorMap[submitErrKey] &&
648 cause !== 'submit' &&
649 !hasErrored
650 ) {
651 this.store.setState((prev) => ({
652 ...prev,
653 errorMap: {
654 ...prev.errorMap,
655 [submitErrKey]: undefined,
656 },
657 }))
658 }
659β
660 return { hasErrored }
661 }
662β
663 /**
664 * @private
665 */
666 validateAsync = async (
667 cause: ValidationCause,
668 ): Promise<ValidationError[]> => {
669 const validates = getAsyncValidatorArray(cause, this.options)
670β
671 if (!this.state.isFormValidating) {
672 this.store.setState((prev) => ({ ...prev, isFormValidating: true }))
673 }
674β
675 /**
676 * We have to use a for loop and generate our promises this way, otherwise it won't be sync
677 * when there are no validators needed to be run
678 */
679 const promises: Promise<ValidationError | undefined>[] = []
680β
681 for (const validateObj of validates) {
682 if (!validateObj.validate) continue
683 const key = getErrorMapKey(validateObj.cause)
684 const fieldValidatorMeta = this.state.validationMetaMap[key]
685β
686 fieldValidatorMeta?.lastAbortController.abort()
687 const controller = new AbortController()
688β
689 this.state.validationMetaMap[key] = {
690 lastAbortController: controller,
691 }
692β
693 promises.push(
694 new Promise<ValidationError | undefined>(async (resolve) => {
695 let rawError!: ValidationError | undefined
696 try {
697 rawError = await new Promise((rawResolve, rawReject) => {
698 setTimeout(async () => {
699 if (controller.signal.aborted) return rawResolve(undefined)
700 try {
701 rawResolve(
702 await this.runValidator({
703 validate: validateObj.validate!,
704 value: {
705 value: this.state.values,
706 formApi: this,
707 signal: controller.signal,
708 },
709 type: 'validateAsync',
710 }),
711 )
712 } catch (e) {
713 rawReject(e)
714 }
715 }, validateObj.debounceMs)
716 })
717 } catch (e: unknown) {
718 rawError = e as ValidationError
719 }
720 const error = normalizeError(rawError)
721 this.store.setState((prev) => ({
722 ...prev,
723 errorMap: {
724 ...prev.errorMap,
725 [getErrorMapKey(cause)]: error,
726 },
727 }))
728β
729 resolve(error)
730 }),
731 )
732 }
733β
734 let results: ValidationError[] = []
735 if (promises.length) {
736 results = await Promise.all(promises)
737 }
738β
739 this.store.setState((prev) => ({
740 ...prev,
741 isFormValidating: false,
742 }))
743β
744 return results.filter(Boolean)
745 }
746β
747 /**
748 * @private
749 */
750 validate = (
751 cause: ValidationCause,
752 ): ValidationError[] | Promise<ValidationError[]> => {
753 // Attempt to sync validate first
754 const { hasErrored } = this.validateSync(cause)
755β
756 if (hasErrored && !this.options.asyncAlways) {
757 return this.state.errors
758 }
759β
760 // No error? Attempt async validation
761 return this.validateAsync(cause)
762 }
763β
764 /**
765 * Handles the form submission, performs validation, and calls the appropriate onSubmit or onInvalidSubmit callbacks.
766 */
767 handleSubmit = async () => {
768 this.store.setState((old) => ({
769 ...old,
770 // Submission attempts mark the form as not submitted
771 isSubmitted: false,
772 // Count submission attempts
773 submissionAttempts: old.submissionAttempts + 1,
774 }))
775β
776 // Don't let invalid forms submit
777 if (!this.state.canSubmit) return
778β
779 this.store.setState((d) => ({ ...d, isSubmitting: true }))
780β
781 const done = () => {
782 this.store.setState((prev) => ({ ...prev, isSubmitting: false }))
783 }
784β
785 // Validate all fields
786 await this.validateAllFields('submit')
787β
788 // Fields are invalid, do not submit
789 if (!this.state.isFieldsValid) {
790 done()
791 this.options.onSubmitInvalid?.({
792 value: this.state.values,
793 formApi: this,
794 })
795 return
796 }
797β
798 // Run validation for the form
799 await this.validate('submit')
800β
801 if (!this.state.isValid) {
802 done()
803 this.options.onSubmitInvalid?.({
804 value: this.state.values,
805 formApi: this,
806 })
807 return
808 }
809β
810 try {
811 // Run the submit code
812 await this.options.onSubmit?.({ value: this.state.values, formApi: this })
813β
814 this.store.batch(() => {
815 this.store.setState((prev) => ({ ...prev, isSubmitted: true }))
816 done()
817 })
818 } catch (err) {
819 done()
820 throw err
821 }
822 }
823β
824 /**
825 * Gets the value of the specified field.
826 */
827 getFieldValue = <TField extends DeepKeys<TFormData>>(
828 field: TField,
829 ): DeepValue<TFormData, TField> => getBy(this.state.values, field)
830β
831 /**
832 * Gets the metadata of the specified field.
833 */
834 getFieldMeta = <TField extends DeepKeys<TFormData>>(
835 field: TField,
836 ): FieldMeta | undefined => {
837 return this.state.fieldMeta[field]
838 }
839β
840 /**
841 * Gets the field info of the specified field.
842 */
843 getFieldInfo = <TField extends DeepKeys<TFormData>>(
844 field: TField,
845 ): FieldInfo<TFormData, TFormValidator> => {
846 // eslint-disable-next-line ts/no-unnecessary-condition
847 return (this.fieldInfo[field] ||= {
848 instance: null,
849 validationMetaMap: {
850 onChange: undefined,
851 onBlur: undefined,
852 onSubmit: undefined,
853 onMount: undefined,
854 onServer: undefined,
855 },
856 })
857 }
858β
859 /**
860 * Updates the metadata of the specified field.
861 */
862 setFieldMeta = <TField extends DeepKeys<TFormData>>(
863 field: TField,
864 updater: Updater<FieldMeta>,
865 ) => {
866 this.store.setState((prev) => {
867 return {
868 ...prev,
869 fieldMeta: {
870 ...prev.fieldMeta,
871 [field]: functionalUpdate(updater, prev.fieldMeta[field]),
872 },
873 }
874 })
875 }
876β
877 resetFieldMeta = <TField extends DeepKeys<TFormData>>(
878 fieldMeta: Record<TField, FieldMeta>,
879 ): Record<TField, FieldMeta> => {
880 return Object.keys(fieldMeta).reduce(
881 (acc: Record<TField, FieldMeta>, key) => {
882 const fieldKey = key as TField
883 acc[fieldKey] = {
884 isValidating: false,
885 isTouched: false,
886 isDirty: false,
887 isPristine: true,
888 errors: [],
889 errorMap: {},
890 }
891 return acc
892 },
893 {} as Record<TField, FieldMeta>,
894 )
895 }
896β
897 /**
898 * Sets the value of the specified field and optionally updates the touched state.
899 */
900 setFieldValue = <TField extends DeepKeys<TFormData>>(
901 field: TField,
902 updater: Updater<DeepValue<TFormData, TField>>,
903 opts?: UpdateMetaOptions,
904 ) => {
905 const dontUpdateMeta = opts?.dontUpdateMeta ?? false
906β
907 this.store.batch(() => {
908 if (!dontUpdateMeta) {
909 this.setFieldMeta(field, (prev) => ({
910 ...prev,
911 isTouched: true,
912 isDirty: true,
913 }))
914 }
915β
916 this.store.setState((prev) => {
917 return {
918 ...prev,
919 values: setBy(prev.values, field, updater),
920 }
921 })
922 })
923 }
924β
925 deleteField = <TField extends DeepKeys<TFormData>>(field: TField) => {
926 this.store.setState((prev) => {
927 const newState = { ...prev }
928 newState.values = deleteBy(newState.values, field)
929 delete newState.fieldMeta[field]
930β
931 return newState
932 })
933 delete this.fieldInfo[field]
934 }
935β
936 /**
937 * Pushes a value into an array field.
938 */
939 pushFieldValue = <TField extends DeepKeys<TFormData>>(
940 field: TField,
941 value: DeepValue<TFormData, TField> extends any[]
942 ? DeepValue<TFormData, TField>[number]
943 : never,
944 opts?: UpdateMetaOptions,
945 ) => {
946 this.setFieldValue(
947 field,
948 (prev) => [...(Array.isArray(prev) ? prev : []), value] as any,
949 opts,
950 )
951 this.validateField(field, 'change')
952 }
953β
954 /**
955 * Inserts a value into an array field at the specified index, shifting the subsequent values to the right.
956 */
957 insertFieldValue = async <TField extends DeepKeys<TFormData>>(
958 field: TField,
959 index: number,
960 value: DeepValue<TFormData, TField> extends any[]
961 ? DeepValue<TFormData, TField>[number]
962 : never,
963 opts?: UpdateMetaOptions,
964 ) => {
965 this.setFieldValue(
966 field,
967 (prev) => {
968 return [
969 ...(prev as DeepValue<TFormData, TField>[]).slice(0, index),
970 value,
971 ...(prev as DeepValue<TFormData, TField>[]).slice(index),
972 ] as any
973 },
974 opts,
975 )
976β
977 // Validate the whole array + all fields that have shifted
978 await this.validateField(field, 'change')
979 }
980β
981 /**
982 * Replaces a value into an array field at the specified index.
983 */
984 replaceFieldValue = async <TField extends DeepKeys<TFormData>>(
985 field: TField,
986 index: number,
987 value: DeepValue<TFormData, TField> extends any[]
988 ? DeepValue<TFormData, TField>[number]
989 : never,
990 opts?: UpdateMetaOptions,
991 ) => {
992 this.setFieldValue(
993 field,
994 (prev) => {
995 return (prev as DeepValue<TFormData, TField>[]).map((d, i) =>
996 i === index ? value : d,
997 ) as any
998 },
999 opts,
1000 )
1001β
1002 // Validate the whole array + all fields that have shifted
1003 await this.validateField(field, 'change')
1004 await this.validateArrayFieldsStartingFrom(field, index, 'change')
1005 }
1006β
1007 /**
1008 * Removes a value from an array field at the specified index.
1009 */
1010 removeFieldValue = async <TField extends DeepKeys<TFormData>>(
1011 field: TField,
1012 index: number,
1013 opts?: UpdateMetaOptions,
1014 ) => {
1015 const fieldValue = this.getFieldValue(field)
1016β
1017 const lastIndex = Array.isArray(fieldValue)
1018 ? Math.max(fieldValue.length - 1, 0)
1019 : null
1020β
1021 this.setFieldValue(
1022 field,
1023 (prev) => {
1024 return (prev as DeepValue<TFormData, TField>[]).filter(
1025 (_d, i) => i !== index,
1026 ) as any
1027 },
1028 opts,
1029 )
1030β
1031 if (lastIndex !== null) {
1032 const start = `${field}[${lastIndex}]`
1033 const fieldsToDelete = Object.keys(this.fieldInfo).filter((f) =>
1034 f.startsWith(start),
1035 )
1036β
1037 // Cleanup the last fields
1038 fieldsToDelete.forEach((f) => this.deleteField(f as TField))
1039 }
1040β
1041 // Validate the whole array + all fields that have shifted
1042 await this.validateField(field, 'change')
1043 await this.validateArrayFieldsStartingFrom(field, index, 'change')
1044 }
1045β
1046 /**
1047 * Swaps the values at the specified indices within an array field.
1048 */
1049 swapFieldValues = <TField extends DeepKeys<TFormData>>(
1050 field: TField,
1051 index1: number,
1052 index2: number,
1053 opts?: UpdateMetaOptions,
1054 ) => {
1055 this.setFieldValue(
1056 field,
1057 (prev: any) => {
1058 const prev1 = prev[index1]!
1059 const prev2 = prev[index2]!
1060 return setBy(setBy(prev, `${index1}`, prev2), `${index2}`, prev1)
1061 },
1062 opts,
1063 )
1064β
1065 // Validate the whole array
1066 this.validateField(field, 'change')
1067 // Validate the swapped fields
1068 this.validateField(`${field}[${index1}]` as DeepKeys<TFormData>, 'change')
1069 this.validateField(`${field}[${index2}]` as DeepKeys<TFormData>, 'change')
1070 }
1071β
1072 /**
1073 * Moves the value at the first specified index to the second specified index within an array field.
1074 */
1075 moveFieldValues = <TField extends DeepKeys<TFormData>>(
1076 field: TField,
1077 index1: number,
1078 index2: number,
1079 opts?: UpdateMetaOptions,
1080 ) => {
1081 this.setFieldValue(
1082 field,
1083 (prev: any) => {
1084 prev.splice(index2, 0, prev.splice(index1, 1)[0])
1085 return prev
1086 },
1087 opts,
1088 )
1089β
1090 // Validate the whole array
1091 this.validateField(field, 'change')
1092 // Validate the moved fields
1093 this.validateField(`${field}[${index1}]` as DeepKeys<TFormData>, 'change')
1094 this.validateField(`${field}[${index2}]` as DeepKeys<TFormData>, 'change')
1095 }
1096}
1097β
1098function normalizeError(rawError?: ValidationError) {
1099 if (rawError) {
1100 if (typeof rawError !== 'string') {
1101 return 'Invalid Form Values'
1102 }
1103β
1104 return rawError
1105 }
1106β
1107 return undefined
1108}
1109β
1110function getErrorMapKey(cause: ValidationCause) {
1111 switch (cause) {
1112 case 'submit':
1113 return 'onSubmit'
1114 case 'blur':
1115 return 'onBlur'
1116 case 'mount':
1117 return 'onMount'
1118 case 'server':
1119 return 'onServer'
1120 case 'change':
1121 default:
1122 return 'onChange'
1123 }
1124}