Open History to see the last commit
1import { batch, createAtom } from '@tanstack/store'
2import { callUpdater, evaluate, getBy } from '../utils.lib'
3import {
4 clearValidationSourceErrorsFromEvent,
5 isValidationTriggerEnabled,
6 parseValidationResult,
7 runFieldMountValidatorPipeline,
8 runFieldValidatorPipeline,
9 setValidationSourceError,
10} from '../validation'
11import { runFieldListenerPipeline } from '../listeners.lib'
12import { devtools } from '../devtoolsBridge.lib'
13import { reconcileValidatorInstances } from '../ValidatorInstance.lib'
14import { reconcileListenerInstances } from '../ListenerInstance.lib'
15import { resolveDefaultOptions } from '../defaultOptions.lib'
16import {
17 attachWatchingListenerField,
18 attachWatchingValidatorField,
19 detachWatchingListenerField,
20 detachWatchingValidatorField,
21 reconcileWatchedListenerFields,
22 reconcileWatchedValidatorFields,
23} from './linked-fields.lib'
24import {
25 defaultInternalBaseFieldMeta,
26 deriveFromBaseFieldMeta,
27 getChildContributionStates,
28 getFieldSnapshot,
29} from './fieldState.lib'
30import {
31 killField,
32 moveFieldToSegment,
33 pruneFieldIfUnused,
34 updateChildContributionCount,
35} from './fieldTree.lib'
36import { visitFieldAndAncestors } from './fieldTraversal.lib'
37import type { InternalRootFieldApi } from './RootFieldApi.lib'
38import type {
39 DeepKeys,
40 DeepValue,
41 TryGetArrayElementType,
42} from '../deep-keys.public'
43import type {
44 AnyFieldListener,
45 FieldListenerTriggers,
46} from '../listeners.public'
47import type { NameSegment, NameSegments } from '../utils.lib'
48import type {
49 FieldValidatorPipelineResult,
50 PipelineResult,
51} from '../validation'
52import type { ResolvedInternalFieldUpdateOptions } from '../types.lib'
53import type { FieldUpdateOptions, Updater } from '../types.public'
54import type { AnyInternalFormApi } from '../FormApi/FormApi.lib'
55import type { AnyInternalFormGroupApi } from '../FormGroupApi/FormGroupApi.lib'
56import type { FieldDependencyChange } from '../devtoolsBridge.lib'
57import type { ReadonlyAtom } from '@tanstack/store'
58import type {
59 InternalValidatorInstance,
60 InternalValidatorInstances,
61} from '../ValidatorInstance.lib'
62import type {
63 InternalListenerInstance,
64 InternalListenerInstances,
65} from '../ListenerInstance.lib'
66import type { FieldApi, FieldApiOptions } from './FieldApi.public'
67import type {
68 ErrorVisibility,
69 FieldErrors,
70 FieldValidateResult,
71 FieldValidator,
72 FieldValidators,
73} from '../validation.public'
74import type {
75 ChildContributionStates,
76 DerivedMetaMarkers,
77 FieldAtoms,
78 InternalBaseFieldMeta,
79 InternalFieldMeta,
80 InternalFieldState,
81} from './fieldState.lib'
82
83export type AnyFieldApiOptions = FieldApiOptions<
84 any,
85 any,
86 any,
87 any,
88 any,
89 any,
90 any
91>
92export type AnyFieldValidator = FieldValidator<any, any, any>
93
94type FieldOptionItemWithWatchedFields = {
95 watchFields?: ReadonlyArray<string>
96}
97
98type FieldOptionsWithFieldNameReferences = {
99 name: string
100 validators?: ReadonlyArray<FieldOptionItemWithWatchedFields | undefined>
101 listeners?: ReadonlyArray<FieldOptionItemWithWatchedFields | undefined>
102}
103
104function transformFieldOptionItemsWithWatchedFields<
105 TItem extends FieldOptionItemWithWatchedFields | undefined,
106>(
107 items: ReadonlyArray<TItem> | undefined,
108 transformFieldName: (fieldName: string) => string,
109): Array<TItem> | undefined {
110 if (!items) return undefined
111
112 return items.map((item) => {
113 if (!item?.watchFields) return item
114
115 return {
116 ...item,
117 watchFields: item.watchFields.map(transformFieldName),
118 }
119 })
120}
121
122export function transformFieldOptionsFieldNames<
123 TFieldOptions extends AnyFieldApiOptions,
124>(
125 fieldOptions: TFieldOptions,
126 transformFieldName: (fieldName: string) => string,
127 mergeOptions: (
128 props: TFieldOptions,
129 overrides: Partial<TFieldOptions>,
130 ) => TFieldOptions,
131): TFieldOptions {
132 const options = fieldOptions as TFieldOptions &
133 FieldOptionsWithFieldNameReferences
134
135 const overrides = {
136 get name() {
137 return transformFieldName(options.name)
138 },
139 } as Partial<TFieldOptions>
140
141 if (Object.hasOwn(options, 'validators')) {
142 Object.defineProperty(overrides, 'validators', {
143 enumerable: true,
144 get() {
145 return transformFieldOptionItemsWithWatchedFields(
146 options.validators,
147 transformFieldName,
148 )
149 },
150 })
151 }
152
153 if (Object.hasOwn(options, 'listeners')) {
154 Object.defineProperty(overrides, 'listeners', {
155 enumerable: true,
156 get() {
157 return transformFieldOptionItemsWithWatchedFields(
158 options.listeners,
159 transformFieldName,
160 )
161 },
162 })
163 }
164
165 return mergeOptions(fieldOptions, overrides)
166}
167
168export interface DefaultValueCacheEntry {
169 name: string
170 value: unknown
171 defaultValue: unknown
172 isDefaultValue: boolean
173}
174
175export function getDefaultValueCacheResult(
176 cache: DefaultValueCacheEntry | null,
177 name: string,
178 value: unknown,
179 defaultValue: unknown,
180): boolean | undefined {
181 if (!shouldCacheDefaultValue(value, defaultValue)) return undefined
182 if (!cache) return undefined
183 if (cache.name !== name) return undefined
184 if (!Object.is(cache.value, value)) return undefined
185 if (!Object.is(cache.defaultValue, defaultValue)) return undefined
186 return cache.isDefaultValue
187}
188
189export function shouldCacheDefaultValue(
190 value: unknown,
191 defaultValue: unknown,
192): boolean {
193 return isObjectLike(value) || isObjectLike(defaultValue)
194}
195
196function isObjectLike(value: unknown): boolean {
197 return (
198 (typeof value === 'object' && value !== null) || typeof value === 'function'
199 )
200}
201
202/**
203 * @private
204 * Get a field api at the specified location. If it doesn't exist,
205 * it will create the necessary nodes to get it.
206 *
207 * @important This mutates the segments array.
208 */
209export function getOrCreateFieldApi(
210 node: AnyInternalFieldApi | InternalRootFieldApi,
211 segments: NameSegments,
212 form: AnyInternalFormApi,
213 options?: Omit<AnyFieldApiOptions, 'name'>,
214 scope: FieldOptionsScope = 'field',
215): AnyInternalFieldApi {
216 const segment = segments.shift()
217 if (segment === undefined) {
218 // If trieNode is the root, we need to return a field node, not the root
219 if (node._isRoot) {
220 throw new Error('Root node cannot be a field API')
221 }
222 // Internal trie nodes defer their options until they are first requested as
223 // a configured field. Adapter updates handle subsequent option changes.
224 if (scope !== 'internal' && !node._fieldOptionsInitialized) {
225 node._update(options ?? {}, scope)
226 }
227 return node
228 }
229
230 let childNode = node._getChild(segment)
231 if (childNode) {
232 return getOrCreateFieldApi(childNode, segments, form, options, scope)
233 }
234
235 childNode = new form._FieldApi(
236 {
237 segment,
238 parent: node,
239 form: form,
240 },
241 'internal',
242 )
243
244 node._setChild(childNode)
245 if (segments.length === 0) {
246 const field = getOrCreateFieldApi(childNode, segments, form, options, scope)
247 devtools().fieldAdded?.(childNode)
248 return field
249 }
250
251 devtools().fieldAdded?.(childNode)
252
253 return getOrCreateFieldApi(childNode, segments, form, options, scope)
254}
255
256/**
257 * @private
258 *
259 * @important This mutates the segments array.
260 */
261export function tryGetFieldApi(
262 trieNode: AnyInternalFieldApi | InternalRootFieldApi,
263 segments: NameSegments,
264): AnyInternalFieldApi | null {
265 const segment = segments.shift()
266 if (segment === undefined) {
267 // If trieNode is the root, we cannot return it as a field API
268 if (!trieNode._isRoot) {
269 return trieNode
270 }
271 return null
272 }
273
274 const childNode = trieNode._getChild(segment)
275 if (childNode) {
276 return tryGetFieldApi(childNode, segments)
277 } else {
278 return null
279 }
280}
281
282export interface InternalFieldApiParams extends Omit<
283 AnyFieldApiOptions,
284 'name'
285> {
286 segment: NameSegment
287 parent: AnyInternalFieldApi | InternalRootFieldApi
288 form: AnyInternalFormApi
289 validators?: FieldValidators<any, any, any>
290}
291
292export type FieldOptionsScope = 'internal' | 'field'
293
294export type FieldWatchingListenerFields = Map<
295 AnyInternalFieldApi,
296 Set<InternalFieldListenerInstance>
297>
298export type FieldWatchingValidatorFields = Map<
299 AnyInternalFieldApi,
300 Set<InternalFieldValidatorInstance>
301>
302
303export type AnyInternalFieldApi = InternalFieldApi<any, any, any>
304export type InternalFieldListenerInstance = InternalListenerInstance<
305 AnyFieldListener,
306 AnyInternalFieldApi,
307 AnyInternalFieldApi
308>
309export type InternalFieldValidatorInstance = InternalValidatorInstance<
310 AnyFieldValidator,
311 AnyInternalFieldApi,
312 AnyInternalFieldApi,
313 AnyInternalFieldApi
314>
315
316export class InternalFieldApi<
317 TFormData,
318 TFieldName extends DeepKeys<TFormData>,
319 TFieldValue extends DeepValue<TFormData, TFieldName>,
320> implements FieldApi<any, any, any, any, any> {
321 readonly _isRoot = false
322 _parent: AnyInternalFieldApi | InternalRootFieldApi
323 _childrenMap: Map<NameSegment, AnyInternalFieldApi> = new Map()
324 _defaultValueCache: DefaultValueCacheEntry | null = null
325 _atoms: FieldAtoms
326 /** Stable runtime instances for this field's validator definitions. */
327 _validatorInstances: InternalValidatorInstances<
328 AnyFieldValidator,
329 AnyInternalFieldApi,
330 AnyInternalFieldApi,
331 AnyInternalFieldApi
332 >
333 /** Stable runtime instances for this field's listener definitions. */
334 _listenerInstances: InternalListenerInstances<
335 AnyFieldListener,
336 AnyInternalFieldApi,
337 AnyInternalFieldApi
338 >
339 _errorVisibility: ErrorVisibility<any, any> | undefined
340 _errorBoundary: boolean
341 /** The form group occupying this trie node. */
342 _formGroup: AnyInternalFormGroupApi | null = null
343
344 // TODO implement
345 /**
346 * @private
347 * Fields that are listening to this one.
348 */
349 _watchingListenerFields: FieldWatchingListenerFields | null
350 _watchingValidatorFields: FieldWatchingValidatorFields | null
351 /** Whether this trie node has received usage-site field options. */
352 _fieldOptionsInitialized: boolean
353 _isKilled = false
354
355 _segmentValue: NameSegment
356 /**
357 * @private
358 * How many components have marked this field as desired / registered.
359 */
360 _refCount = 0
361
362 /**
363 * @private
364 * This is read-only. Use fieldApi._moveTo() instead for writes.
365 */
366 get _segment(): NameSegment {
367 return this._segmentValue
368 }
369
370 form: AnyInternalFormApi
371
372 /**
373 * @private
374 * Whether a derived atom exists for this field. Atoms are only made
375 * on-demand if there is an adapter component that needs one.
376 */
377 get _isMounted(): boolean {
378 return this._refCount > 0
379 }
380
381 get _children(): Array<AnyInternalFieldApi> {
382 return Array.from(this._childrenMap.values())
383 }
384
385 _getOrCreateAtoms(): Required<FieldAtoms> {
386 let { meta: metaAtom, store: storeAtom } = this._atoms
387 if (!metaAtom) {
388 metaAtom = createAtom(defaultInternalBaseFieldMeta)
389 }
390 if (!storeAtom) {
391 const markers: DerivedMetaMarkers = {
392 source: undefined,
393 canDisplayErrors: undefined,
394 }
395 storeAtom = createAtom<InternalFieldState>((prev) => {
396 const newMeta = metaAtom.get()
397 const value = this._getValue()
398
399 const meta = deriveFromBaseFieldMeta(
400 newMeta,
401 prev?.meta,
402 this,
403 value,
404 markers,
405 )
406
407 if (prev?.meta === meta && prev.value === value) {
408 return prev
409 }
410
411 return {
412 meta,
413 value,
414 }
415 })
416 }
417
418 const required: Required<FieldAtoms> = { meta: metaAtom, store: storeAtom }
419
420 this._atoms = required
421 return required
422 }
423
424 get atom(): ReadonlyAtom<InternalFieldState> {
425 return this._getOrCreateAtoms().store
426 }
427
428 get name(): TFieldName {
429 const ownSegment =
430 typeof this._segment === 'number' ? `[${this._segment}]` : this._segment
431
432 let name = this._parent.name
433
434 // If my parent is not root and not an array, add a dot
435 if (!this._parent._isRoot && typeof this._segment !== 'number') {
436 name += '.'
437 }
438 name += ownSegment
439
440 return name as TFieldName
441 }
442
443 _getBaseMeta(): InternalBaseFieldMeta {
444 return this._atoms.meta?.get() ?? defaultInternalBaseFieldMeta
445 }
446
447 _setDefaultValueCache(
448 value: unknown,
449 defaultValue: unknown,
450 isDefaultValue: boolean,
451 ): boolean {
452 if (!shouldCacheDefaultValue(value, defaultValue)) {
453 this._defaultValueCache = null
454 return isDefaultValue
455 }
456
457 this._defaultValueCache = {
458 name: this.name,
459 value,
460 defaultValue,
461 isDefaultValue,
462 }
463 return isDefaultValue
464 }
465
466 _getCachedIsDefaultValue(
467 value: unknown = this._getValue(),
468 defaultValue: unknown = getBy(this.form.defaultValues, this.name),
469 ): boolean | undefined {
470 return getDefaultValueCacheResult(
471 this._defaultValueCache,
472 this.name,
473 value,
474 defaultValue,
475 )
476 }
477
478 _getIsDefaultValue(value: unknown = this._getValue()): boolean {
479 void this.form._atoms.defaultValuesVersion.get()
480 const defaultValue = getBy(this.form.defaultValues, this.name)
481 const cached = this._getCachedIsDefaultValue(value, defaultValue)
482 if (cached !== undefined) return cached
483
484 const isDefaultValue = evaluate(defaultValue, value)
485 return this._setDefaultValueCache(value, defaultValue, isDefaultValue)
486 }
487
488 constructor(
489 options: InternalFieldApiParams,
490 scope: FieldOptionsScope = 'field',
491 ) {
492 this._fieldOptionsInitialized = scope !== 'internal'
493 const defaultOptions =
494 scope === 'field' ? options.form._defaultOptions?.field : undefined
495 const {
496 segment,
497 parent,
498 validators,
499 form,
500 listeners,
501 errorVisibility,
502 errorBoundary,
503 } = resolveDefaultOptions(options, defaultOptions)
504
505 this._segmentValue = segment
506 this._parent = parent
507 this.form = form
508 const normalizedValidators =
509 validators && validators.length > 0
510 ? (validators as Array<AnyFieldValidator>)
511 : null
512 this._errorVisibility = errorVisibility
513 this._errorBoundary = errorBoundary ?? false
514 this._atoms = {}
515 this._watchingListenerFields = null
516 this._watchingValidatorFields = null
517 this._listenerInstances = reconcileListenerInstances<
518 AnyFieldListener,
519 AnyInternalFieldApi,
520 AnyInternalFieldApi
521 >({
522 definitions: listeners,
523 instances: null,
524 owner: this,
525 })
526 this._validatorInstances = reconcileValidatorInstances<
527 AnyFieldValidator,
528 AnyInternalFieldApi,
529 AnyInternalFieldApi,
530 AnyInternalFieldApi
531 >({
532 definitions: normalizedValidators,
533 instances: null,
534 owner: this,
535 scope: 'field',
536 })
537
538 const reconciledListeners = reconcileWatchedListenerFields({
539 field: this,
540 listenerInstances: this._listenerInstances,
541 form,
542 })
543
544 reconciledListeners.attach.forEach(attachWatchingListenerField)
545
546 const reconciledValidators = reconcileWatchedValidatorFields({
547 field: this,
548 validatorInstances: this._validatorInstances,
549 form,
550 })
551
552 reconciledValidators.attach.forEach(attachWatchingValidatorField)
553 }
554
555 _update(
556 options: Omit<AnyFieldApiOptions, 'name' | 'form'>,
557 scope: FieldOptionsScope = 'field',
558 ) {
559 if (this._isKilled) return
560
561 const isInitializing =
562 scope !== 'internal' && !this._fieldOptionsInitialized
563 const defaultOptions =
564 scope === 'field' ? this.form._defaultOptions?.field : undefined
565 const resolvedOptions = resolveDefaultOptions(options, defaultOptions)
566
567 this._errorVisibility = resolvedOptions.errorVisibility
568 this._errorBoundary = resolvedOptions.errorBoundary ?? false
569
570 const notifyDependencyChanges = devtools().fieldDependenciesChanged
571 const dependencyChanges: Array<FieldDependencyChange> | null =
572 notifyDependencyChanges ? [] : null
573
574 if (resolvedOptions.listeners) {
575 const previousListeners = this._listenerInstances?.map(
576 (instance) => instance.definition,
577 )
578 this._listenerInstances = reconcileListenerInstances<
579 AnyFieldListener,
580 AnyInternalFieldApi,
581 AnyInternalFieldApi
582 >({
583 definitions: resolvedOptions.listeners,
584 previousDefinitions: isInitializing
585 ? undefined
586 : (previousListeners ?? null),
587 instances: this._listenerInstances,
588 owner: this,
589 onBeforeDispose: (listenerInstance) => {
590 listenerInstance.resolvedWatchFields?.forEach((sourceField) => {
591 const operation = {
592 kind: 'listener' as const,
593 sourceField,
594 watchingField: this,
595 listenerInstance,
596 }
597 detachWatchingListenerField(operation)
598 dependencyChanges?.push(operation)
599 })
600 listenerInstance.resolvedWatchFields = null
601 },
602 })
603
604 const reconciledListeners = reconcileWatchedListenerFields({
605 field: this,
606 listenerInstances: this._listenerInstances,
607 form: this.form,
608 })
609
610 reconciledListeners.detach.forEach((operation) =>
611 detachWatchingListenerField(operation),
612 )
613 reconciledListeners.attach.forEach(attachWatchingListenerField)
614 dependencyChanges?.push(
615 ...reconciledListeners.attach,
616 ...reconciledListeners.detach,
617 )
618 }
619
620 if (resolvedOptions.validators) {
621 const previousValidators = this._validatorInstances?.map(
622 (instance) => instance.definition,
623 )
624 const nextValidators =
625 resolvedOptions.validators.length > 0
626 ? (resolvedOptions.validators as Array<AnyFieldValidator>)
627 : null
628 this._validatorInstances = reconcileValidatorInstances<
629 AnyFieldValidator,
630 AnyInternalFieldApi,
631 AnyInternalFieldApi,
632 AnyInternalFieldApi
633 >({
634 definitions: nextValidators,
635 previousDefinitions: isInitializing
636 ? undefined
637 : (previousValidators ?? null),
638 instances: this._validatorInstances,
639 owner: this,
640 scope: 'field',
641 onBeforeDispose: (validatorInstance) => {
642 validatorInstance.resolvedWatchFields?.forEach((sourceField) => {
643 const operation = {
644 kind: 'validator' as const,
645 sourceField,
646 watchingField: this,
647 validatorInstance,
648 }
649 detachWatchingValidatorField(operation)
650 dependencyChanges?.push(operation)
651 })
652 validatorInstance.resolvedWatchFields = null
653 this._removeValidatorInstance(validatorInstance)
654 },
655 })
656 const reconciledValidators = reconcileWatchedValidatorFields({
657 field: this,
658 validatorInstances: this._validatorInstances,
659 form: this.form,
660 })
661
662 reconciledValidators.detach.forEach((operation) =>
663 detachWatchingValidatorField(operation),
664 )
665 reconciledValidators.attach.forEach(attachWatchingValidatorField)
666
667 dependencyChanges?.push(
668 ...reconciledValidators.attach,
669 ...reconciledValidators.detach,
670 )
671 }
672
673 if (dependencyChanges && dependencyChanges.length > 0) {
674 notifyDependencyChanges?.(dependencyChanges)
675 }
676
677 if (scope !== 'internal') {
678 this._fieldOptionsInitialized = true
679 }
680 }
681
682 /**
683 * @private
684 * Get a child FieldApi by its segment name.
685 */
686 _getChild(segment: NameSegment): AnyInternalFieldApi | undefined {
687 return this._childrenMap.get(segment)
688 }
689
690 /**
691 * @private
692 * Set an existing node as a child of this FieldApi.
693 */
694 _setChild(node: AnyInternalFieldApi): void {
695 this._childrenMap.set(node._segment, node)
696 }
697
698 /**
699 * @private
700 * Remove a child node from this FieldApi.
701 *
702 * @important Does not kill the child node.
703 */
704 _removeChild(segment: NameSegment): void {
705 this._childrenMap.delete(segment)
706 }
707
708 /**
709 * @private
710 * Set this field's meta. If not present, it will create the
711 * entry.
712 */
713 _setMeta(updater: Updater<InternalBaseFieldMeta>) {
714 if (this._isKilled) return
715
716 this._getOrCreateAtoms().meta.set((prevMeta) => {
717 const newMeta = callUpdater(updater, prevMeta)
718 const prevContributions = getChildContributionStates(prevMeta)
719 const newContributions = getChildContributionStates(newMeta)
720
721 if (!this._parent._isRoot) {
722 this._parent._updateChildContributionCount(
723 prevContributions,
724 newContributions,
725 )
726 } else {
727 this._parent._updateFieldContributionCount(
728 prevContributions,
729 newContributions,
730 )
731
732 this._parent._updateErrorFields(
733 this,
734 prevContributions.error,
735 newContributions.error,
736 )
737 }
738
739 return newMeta
740 })
741 devtools().updateField?.(this)
742 }
743
744 /**
745 * @private
746 * Called when a child's meta contribution changes.
747 * Increments/decrements the relevant child contribution count and propagates up.
748 */
749 _updateChildContributionCount(
750 prevState: ChildContributionStates,
751 newState: ChildContributionStates,
752 ): void {
753 updateChildContributionCount(this, prevState, newState)
754 }
755
756 /**
757 * @private
758 * Triggers validation for this field and all parent fields,
759 * eventually calling form validation.
760 */
761 _triggerValidationCascade(event: 'change' | 'blur' | 'submit'): void {
762 if (this._isKilled) return
763
764 const seenValidatorFields = new WeakSet<AnyInternalFieldApi>()
765
766 visitFieldAndAncestors(this, (current, stop) => {
767 if (current._isKilled) return stop
768
769 current._runFieldValidation(event)
770 current._notifyValidator(event, seenValidatorFields)
771 return undefined
772 })
773
774 const group = this._getFormGroup()
775 if (group) {
776 group.validate(event, { triggerFieldApi: this })
777 return
778 }
779
780 this.form.validate(event, { fieldApiOverride: this })
781 }
782
783 /**
784 * @private
785 * Runs this field's validation pipeline.
786 */
787 async _runFieldValidation(
788 event: 'change' | 'blur' | 'submit',
789 options?: {
790 onResult?: boolean
791 onlyRunValidatorInstances?: ReadonlySet<InternalFieldValidatorInstance> | null
792 _startValidation?: () => () => void
793 },
794 ): Promise<FieldValidatorPipelineResult> {
795 if (this._isKilled)
796 return {
797 results: [],
798 hasErrors: false,
799 thrownError: null,
800 }
801
802 const validators = this._validatorInstances
803
804 if (!validators)
805 return {
806 results: [],
807 hasErrors: false,
808 thrownError: null,
809 }
810
811 let finishValidation = options?._startValidation?.()
812 if (!finishValidation) {
813 this._setValidationCount((count) => count + 1)
814 finishValidation = () => {
815 this._setValidationCount((count) => Math.max(0, count - 1))
816 }
817 }
818
819 try {
820 return await runFieldValidatorPipeline({
821 pipeline: validators,
822 context: {
823 scope: 'field',
824 event,
825 fieldApi: this,
826 formApi: this.form,
827 },
828 onResult:
829 options?.onResult !== false
830 ? (result) => this._processValidationResult(result, event)
831 : undefined,
832 validatorInstancesToRun: options?.onlyRunValidatorInstances ?? null,
833 })
834 } finally {
835 finishValidation()
836 }
837 }
838
839 _setValidationCount(updater: Updater<number>): void {
840 this._setMeta((prev) => {
841 const _validationCount = callUpdater(updater, prev._validationCount)
842 const isValidating = _validationCount > 0
843
844 if (
845 prev._validationCount === _validationCount &&
846 prev.isValidating === isValidating
847 ) {
848 return prev
849 }
850
851 return {
852 ...prev,
853 _validationCount,
854 isValidating,
855 }
856 })
857 }
858
859 _processValidationResult(
860 result: PipelineResult<FieldValidateResult>,
861 sourceEvent: string,
862 ) {
863 if (this._isKilled) return
864 const validatorInstance =
865 result.validatorInstance as InternalFieldValidatorInstance
866
867 this._setMeta((prev) => {
868 const { self } = parseValidationResult(result.result)
869 const nextErrors = setValidationSourceError(
870 prev._validationSourceErrors,
871 validatorInstance,
872 self ?? [],
873 sourceEvent,
874 )
875
876 if (!nextErrors) return prev
877
878 if (self && self.length > 0) {
879 validatorInstance.addErrorTarget(this)
880 } else {
881 validatorInstance.deleteErrorTarget(this)
882 }
883
884 return {
885 ...prev,
886 _validationSourceErrors: nextErrors.errorMap,
887 } satisfies InternalBaseFieldMeta
888 })
889 }
890
891 /** Removes all field-owned state associated with a disposed validator. */
892 _removeValidatorInstance(
893 validatorInstance: InternalFieldValidatorInstance,
894 ): void {
895 this._setMeta((prev) => {
896 const nextErrors = setValidationSourceError(
897 prev._validationSourceErrors,
898 validatorInstance,
899 [],
900 '',
901 )
902 if (!nextErrors) return prev
903
904 return {
905 ...prev,
906 _validationSourceErrors: nextErrors.errorMap,
907 }
908 })
909 validatorInstance.deleteErrorTarget(this)
910 }
911
912 _clearEventErrors(event: 'change' | 'blur', sourceEvent: string): void {
913 if (this._isKilled) return
914
915 const validators = this._validatorInstances
916 if (!validators) return
917
918 const validatorInstancesToClear: Array<InternalFieldValidatorInstance> = []
919
920 for (const validatorInstance of validators) {
921 const runsOnEvent = validatorInstance.definition.triggers.some(
922 (trigger) =>
923 isValidationTriggerEnabled(trigger, {
924 scope: 'field',
925 event,
926 fieldApi: this,
927 formApi: this.form,
928 }),
929 )
930
931 if (!runsOnEvent) {
932 validatorInstancesToClear.push(validatorInstance)
933 }
934 }
935
936 if (validatorInstancesToClear.length === 0) return
937 const clearedInstances = validatorInstancesToClear.filter(
938 (validatorInstance) =>
939 this._getBaseMeta()._validationSourceErrors?.get(validatorInstance)
940 ?.sourceEvent === sourceEvent,
941 )
942 if (clearedInstances.length === 0) return
943
944 this._setMeta((prev) => {
945 const clearedErrors = clearValidationSourceErrorsFromEvent(
946 prev._validationSourceErrors,
947 clearedInstances,
948 sourceEvent,
949 )
950
951 if (!clearedErrors) return prev
952
953 clearedInstances.forEach((validatorInstance) =>
954 validatorInstance.deleteErrorTarget(this),
955 )
956
957 return {
958 ...prev,
959 _validationSourceErrors: clearedErrors.errorMap,
960 } satisfies InternalBaseFieldMeta
961 })
962 this._pruneIfUnused()
963 }
964
965 _notifyEvent(
966 options: Omit<
967 ResolvedInternalFieldUpdateOptions,
968 'fieldApiOverride' | '_skipFieldCreation'
969 >,
970 event: 'change' | 'blur' | 'submit',
971 ): void {
972 if (this._isKilled) return
973
974 if (event === 'change' || event === 'blur') {
975 this._clearEventErrors(event, 'submit')
976
977 if (event === 'blur') {
978 this._clearEventErrors('blur', 'mount')
979 this.form._clearEventErrors(this, 'submit', event)
980 this.form._clearEventErrors(this, 'server', event)
981 this.form._clearEventErrors(this, 'mount', event)
982 }
983 }
984
985 const {
986 markAsDirty,
987 markAsTouched,
988 causeValidation,
989 markAsBlurred,
990 doPropagate,
991 } = options
992 // Not sure if we lose this context, so might as well
993 const originalField = this
994
995 batch(() => {
996 const seenListenerFields = new WeakSet<AnyInternalFieldApi>()
997
998 visitFieldAndAncestors(this, (currNode, stop) => {
999 const isOriginalField = currNode === originalField
1000 const { isSelfDirty, isSelfTouched, isBlurred } = currNode.meta
1001 const shouldUpdateDirty = isOriginalField && markAsDirty && !isSelfDirty
1002 const shouldUpdateTouched =
1003 isOriginalField && markAsTouched && !isSelfTouched
1004
1005 const shouldUpdateBlurred = markAsBlurred && !isBlurred
1006
1007 if (shouldUpdateDirty || shouldUpdateTouched || shouldUpdateBlurred) {
1008 currNode._setMeta((prev) => ({
1009 ...prev,
1010 isTouched: shouldUpdateTouched ? true : prev.isTouched,
1011 isDirty: shouldUpdateDirty ? true : prev.isDirty,
1012 isBlurred: markAsBlurred ? true : prev.isBlurred,
1013 }))
1014 }
1015
1016 currNode._notifyListener(event, seenListenerFields)
1017
1018 if (!doPropagate) return stop
1019 return undefined
1020 })
1021 })
1022
1023 if (causeValidation) {
1024 this._triggerValidationCascade(event)
1025 }
1026 }
1027
1028 _notifyListener(
1029 trigger: FieldListenerTriggers,
1030 seenFields: WeakSet<AnyInternalFieldApi>,
1031 onlyRunListenerInstances: ReadonlySet<InternalFieldListenerInstance> | null = null,
1032 ) {
1033 if (this._isKilled) return
1034
1035 // Field A listens to Field B listens to field A
1036 // FieldA.notifyListener -> fieldB.notifyListener -> fieldA.notifyLister
1037 if (seenFields.has(this)) {
1038 console.warn(
1039 `Field listener: cyclical listener cycle detected. Check around the field ${this.name}`,
1040 )
1041 return
1042 }
1043
1044 seenFields.add(this)
1045
1046 if (this._listenerInstances) {
1047 runFieldListenerPipeline({
1048 pipeline: this._listenerInstances,
1049 context: {
1050 event: trigger,
1051 fieldApi: this,
1052 formApi: this.form,
1053 },
1054 listenerInstancesToRun: onlyRunListenerInstances,
1055 })
1056 }
1057
1058 const watchingFields = this._watchingListenerFields
1059 if (!watchingFields) return
1060
1061 for (const [watchingField, listenerInstances] of watchingFields) {
1062 if (watchingField._isKilled) {
1063 watchingFields.delete(watchingField)
1064 continue
1065 }
1066
1067 watchingField._notifyListener(trigger, seenFields, listenerInstances)
1068 }
1069
1070 if (watchingFields.size === 0) {
1071 this._watchingListenerFields = null
1072 }
1073 }
1074
1075 _notifyValidator(
1076 trigger: 'change' | 'blur' | 'submit',
1077 seenFields: WeakSet<AnyInternalFieldApi>,
1078 onlyRunValidatorInstances: ReadonlySet<InternalFieldValidatorInstance> | null = null,
1079 ) {
1080 if (this._isKilled) return
1081
1082 if (seenFields.has(this)) {
1083 console.warn(
1084 `Field validator: cyclical validator cycle detected. Check around the field ${this.name}`,
1085 )
1086 return
1087 }
1088
1089 seenFields.add(this)
1090
1091 if (this._validatorInstances && onlyRunValidatorInstances) {
1092 this._runFieldValidation(trigger, { onlyRunValidatorInstances })
1093 }
1094
1095 const watchingFields = this._watchingValidatorFields
1096 if (!watchingFields) return
1097
1098 for (const [watchingField, validatorInstances] of watchingFields) {
1099 if (watchingField._isKilled) {
1100 watchingFields.delete(watchingField)
1101 continue
1102 }
1103
1104 watchingField._notifyValidator(trigger, seenFields, validatorInstances)
1105 }
1106
1107 if (watchingFields.size === 0) {
1108 this._watchingValidatorFields = null
1109 }
1110 }
1111
1112 /**
1113 * @private
1114 * Register as a component that you're using this field.
1115 *
1116 */
1117 _register(): () => void {
1118 if (this._isKilled) {
1119 return () => {}
1120 }
1121
1122 const isMountTransition = this._refCount === 0
1123 const mountValidatorInstances = isMountTransition
1124 ? (this._validatorInstances?.filter(
1125 (validatorInstance) => !validatorInstance.didRunOnMount,
1126 ) ?? [])
1127 : []
1128 this._refCount++
1129 this._getOrCreateAtoms()
1130 if (isMountTransition) {
1131 devtools().mountField?.(this)
1132 }
1133
1134 this._notifyListener('mount', new WeakSet())
1135
1136 if (mountValidatorInstances.length > 0) {
1137 mountValidatorInstances.forEach((validatorInstance) =>
1138 validatorInstance.markMountValidationRan(),
1139 )
1140 this._runMountValidation(mountValidatorInstances)
1141 }
1142
1143 return () => this._unregister()
1144 }
1145
1146 /**
1147 * @private
1148 * Runs validators marked with runOnMount on the first component mount.
1149 */
1150 _runMountValidation(validators = this._validatorInstances): void {
1151 if (!validators || validators.length === 0) return
1152
1153 this._setValidationCount((count) => count + 1)
1154
1155 const { didRun, asyncPromise } = runFieldMountValidatorPipeline({
1156 pipeline: validators,
1157 fieldApi: this,
1158 onResult: (result) => this._processValidationResult(result, 'mount'),
1159 })
1160
1161 if (!didRun) {
1162 this._setValidationCount((count) => Math.max(0, count - 1))
1163 return
1164 }
1165
1166 if (asyncPromise) {
1167 void asyncPromise.finally(() => {
1168 this._setValidationCount((count) => Math.max(0, count - 1))
1169 })
1170 return
1171 }
1172
1173 this._setValidationCount((count) => Math.max(0, count - 1))
1174 }
1175
1176 /**
1177 * @private
1178 * Unregister as a component that you're using this field.
1179 *
1180 */
1181 _unregister(): void {
1182 if (this._isKilled) return
1183
1184 const previousPath = this.name
1185 const isUnmountTransition = this._refCount === 1
1186 this._refCount--
1187 if (isUnmountTransition) {
1188 devtools().unmountField?.(this, previousPath)
1189 }
1190 this._notifyListener('unmount', new WeakSet())
1191
1192 if (this._refCount <= 0) {
1193 setTimeout(() => {
1194 if (this._refCount > 0) return
1195
1196 this._atoms.store = undefined
1197
1198 if (this._atoms.meta?.get() === defaultInternalBaseFieldMeta) {
1199 this._atoms.meta = undefined
1200 }
1201
1202 this._pruneIfUnused()
1203 }, 0)
1204 }
1205 }
1206
1207 reset = () => {
1208 this.form.resetField(this.name, { fieldApiOverride: this })
1209 }
1210
1211 /**
1212 * @private
1213 */
1214 _moveTo(newSegment: NameSegment): void {
1215 const previousPath = this.name
1216 moveFieldToSegment(this, newSegment)
1217 if (this.name !== previousPath) {
1218 devtools().moveField?.(this, previousPath)
1219 }
1220 }
1221
1222 /**
1223 * @private
1224 * Kill this field and its children.
1225 * Removes the affected fields' meta as well.
1226 */
1227 _kill(
1228 options: {
1229 listenerEvent?: FieldListenerTriggers
1230 } = {},
1231 ) {
1232 killField(this, options)
1233 }
1234
1235 _pruneIfUnused(): void {
1236 pruneFieldIfUnused(this)
1237 }
1238
1239 /** Updates the form group occupying this trie node. */
1240 _setFormGroup(formGroup: AnyInternalFormGroupApi | null): void {
1241 if (this._formGroup === formGroup) return
1242
1243 this._formGroup = formGroup
1244 devtools().updateField?.(this)
1245
1246 if (!formGroup) this._pruneIfUnused()
1247 }
1248
1249 /** Returns the form group containing this trie node, if one exists. */
1250 _getFormGroup(): AnyInternalFormGroupApi | null {
1251 let formGroup: AnyInternalFormGroupApi | null = null
1252
1253 visitFieldAndAncestors(this, (field, stop) => {
1254 if (!field._formGroup) return
1255
1256 formGroup = field._formGroup
1257 return stop
1258 })
1259
1260 return formGroup
1261 }
1262
1263 _getValue(): any {
1264 return this.form.getFieldValue(this.name)
1265 }
1266
1267 get state(): InternalFieldState {
1268 // Accessing `atom` mounts the field, which we don't necessarily want.
1269 // Parent or child nodes may simply want some info about a field's state.
1270 if (this._isMounted) {
1271 return this.atom.get()
1272 } else {
1273 return getFieldSnapshot(this)
1274 }
1275 }
1276
1277 get value() {
1278 return this.state.value
1279 }
1280
1281 get meta(): InternalFieldMeta {
1282 return this.state.meta
1283 }
1284
1285 get errors(): FieldErrors<any> {
1286 return this.state.meta.errors
1287 }
1288
1289 // data: ['a', 'b']
1290 // name="data[0]" -> node created, meta created
1291 // data.swapValues(0, 1) -> valid, but node errors
1292 // -> swapValues or other arary mutations need to check runtime -> swap values in the array -> THAT's where the check has to occur.
1293 // after we made the form data update, we getOrCreateNode() of the two elements
1294
1295 swapValues = (indexA: number, indexB: number) => {
1296 if (this._isKilled) return
1297
1298 this.form.swapFieldValues(this.name, indexA, indexB, {
1299 fieldApiOverride: this,
1300 })
1301 }
1302
1303 moveValue = (
1304 fromIndex: number,
1305 toIndex: number,
1306 options: FieldUpdateOptions = {},
1307 ) => {
1308 if (this._isKilled) return
1309
1310 this.form.moveFieldValue(this.name, fromIndex, toIndex, {
1311 ...options,
1312 fieldApiOverride: this,
1313 })
1314 }
1315
1316 clearValues = (options: FieldUpdateOptions = {}): void => {
1317 if (this._isKilled) return
1318
1319 this.form.clearFieldValues(this.name, {
1320 ...options,
1321 fieldApiOverride: this,
1322 })
1323 }
1324
1325 pushValue = (value: any, options: FieldUpdateOptions = {}): void => {
1326 if (this._isKilled) return
1327
1328 return this.form.pushFieldValue(this.name, value, {
1329 ...options,
1330 fieldApiOverride: this,
1331 })
1332 }
1333
1334 insertValue = (
1335 index: number,
1336 value: any,
1337 options: FieldUpdateOptions = {},
1338 ): void => {
1339 if (this._isKilled) return
1340
1341 return this.form.insertFieldValue(this.name, index, value, {
1342 ...options,
1343 fieldApiOverride: this,
1344 })
1345 }
1346
1347 replaceValue = (
1348 index: number,
1349 value: any,
1350 options: FieldUpdateOptions = {},
1351 ): void => {
1352 if (this._isKilled) return
1353
1354 return this.form.replaceFieldValue(this.name, index, value, {
1355 ...options,
1356 fieldApiOverride: this,
1357 })
1358 }
1359
1360 removeValue = (index: number, options: FieldUpdateOptions = {}): void => {
1361 if (this._isKilled) return
1362
1363 return this.form.removeFieldValue(this.name, index, {
1364 ...options,
1365 fieldApiOverride: this,
1366 })
1367 }
1368
1369 filterValues = (
1370 predicate: (
1371 value: TryGetArrayElementType<TFieldValue>,
1372 index: number,
1373 array: TFieldValue,
1374 ) => boolean,
1375 options?: FieldUpdateOptions & { thisArg?: any },
1376 ) => {
1377 if (this._isKilled) return
1378
1379 return this.form.filterFieldValues(this.name, predicate as never, {
1380 ...options,
1381 fieldApiOverride: this,
1382 })
1383 }
1384
1385 handleChange = (
1386 value: Updater<TFieldValue>,
1387 options: FieldUpdateOptions = {},
1388 ): void => {
1389 if (this._isKilled) return
1390
1391 return this.form.setFieldValue(this.name, value, {
1392 ...options,
1393 fieldApiOverride: this,
1394 })
1395 }
1396
1397 handleBlur = (): void => {
1398 if (this._isKilled) return
1399
1400 this._notifyEvent(
1401 {
1402 markAsDirty: false,
1403 causeValidation: true,
1404 doPropagate: true,
1405 markAsTouched: true,
1406 markAsBlurred: true,
1407 },
1408 'blur',
1409 )
1410
1411 this.form._notifyFormListener('blur', this)
1412 }
1413}