Open History to see the last commit
1import { batch } from '@tanstack/store'
2import { touchAllFieldsAndCollectSubmitValidators } from './fieldTree.lib'
3import type { AnyInternalFieldApi } from './FieldApi.lib'
4import type { ChildContributionStates } from './fieldState.lib'
5import type { AnyInternalFormApi, FormMetaAtoms } from '../FormApi/FormApi.lib'
6import type { NameSegment } from '../utils.lib'
7β
8export type RootCounterContributionKey = 'touched' | 'validating'
9β
10export const rootCounterContributionKeys: Array<RootCounterContributionKey> = [
11 'touched',
12 'validating',
13]
14β
15const rootCounterMetaKeys: Record<
16 RootCounterContributionKey,
17 keyof Pick<FormMetaAtoms, 'touchedFieldCount' | 'fieldValidationCount'>
18> = {
19 touched: 'touchedFieldCount',
20 validating: 'fieldValidationCount',
21}
22β
23export class InternalRootFieldApi {
24 readonly _isRoot = true
25 #children: Map<NameSegment, AnyInternalFieldApi> = new Map()
26β
27 form: AnyInternalFormApi
28β
29 readonly name = ''
30β
31 get _children(): Array<AnyInternalFieldApi> {
32 return Array.from(this.#children.values())
33 }
34β
35 constructor(form: AnyInternalFormApi) {
36 this.form = form
37 }
38β
39 /**
40 * @private
41 * Get a child FieldApi by its segment name.
42 */
43 _getChild(segment: NameSegment): AnyInternalFieldApi | undefined {
44 return this.#children.get(segment)
45 }
46β
47 /**
48 * @private
49 * Set an existing node as a child of this root node.
50 */
51 _setChild(node: AnyInternalFieldApi): void {
52 this.#children.set(node._segment, node)
53 }
54β
55 _updateErrorFields(
56 node: AnyInternalFieldApi,
57 prevContributes: boolean,
58 newContributes: boolean,
59 ) {
60 if (prevContributes === newContributes) return
61β
62 this.form._atoms.meta.errorFields.set((prev) => {
63 const errorFields = new Set(prev)
64β
65 if (newContributes) {
66 errorFields.add(node)
67 } else {
68 errorFields.delete(node)
69 }
70β
71 return errorFields
72 })
73 }
74β
75 _updateFieldContributionCount(
76 prevState: ChildContributionStates,
77 newState: ChildContributionStates,
78 ) {
79 batch(() => {
80 for (const key of rootCounterContributionKeys) {
81 const prevContributes = prevState[key]
82 const newContributes = newState[key]
83β
84 if (prevContributes === newContributes) continue
85β
86 const atom = this.form._atoms.meta[rootCounterMetaKeys[key]]
87 atom.set((prev) => {
88 const delta = newContributes ? 1 : -1
89 return Math.max(0, prev + delta)
90 })
91 }
92 })
93 }
94β
95 _removeChild(segment: NameSegment): void {
96 this.#children.delete(segment)
97 }
98β
99 _touchAllFieldsAndCollectSubmitValidators(): Array<AnyInternalFieldApi> {
100 return touchAllFieldsAndCollectSubmitValidators(this)
101 }
102}