Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

fieldTree.lib.ts

518 lines14.2 KB

1import { batch } from '@tanstack/store'
2import { devtools } from '../devtoolsBridge.lib'
3import {
4 detachWatchingListenerField,
5 detachWatchingValidatorField,
6} from './linked-fields.lib'
7import {
8 childContributionKeys,
9 defaultInternalBaseFieldMeta,
10 getChildContributionStates,
11 isPrunableMeta,
12} from './fieldState.lib'
13import {
14 collectFieldSubtree,
15 visitAllFormFields,
16 visitFieldAndAncestors,
17} from './fieldTraversal.lib'
18import type { FieldListenerTriggers } from '../listeners.public'
19import type { FieldDependencyChange } from '../devtoolsBridge.lib'
20import type {
21 AnyInternalFieldApi,
22 FieldWatchingListenerFields,
23 FieldWatchingValidatorFields,
24} from './FieldApi.lib'
25import type {
26 InternalRootFieldApi,
27 RootCounterContributionKey,
28} from './RootFieldApi.lib'
29import type { ChildContributionStates } from './fieldState.lib'
30import type { NameSegment } from '../utils.lib'
31​
32const rootCounterContributionKeys: Array<RootCounterContributionKey> = [
33 'touched',
34 'validating',
36​
37function detachWatchedListenerFields({
38 field,
39 nodesToKill,
40 fieldsToPruneAfterKill,
41 dependencyChanges,
42}: {
43 field: AnyInternalFieldApi
44 nodesToKill: Set<AnyInternalFieldApi>
45 fieldsToPruneAfterKill: Set<AnyInternalFieldApi>
46 dependencyChanges: Array<FieldDependencyChange> | null
47}) {
48 field._listenerInstances?.forEach((listenerInstance) => {
49 listenerInstance.resolvedWatchFields?.forEach((sourceField) => {
50 const change = {
51 kind: 'listener' as const,
52 sourceField,
53 watchingField: field,
54 listenerInstance,
55 }
56 detachWatchingListenerField(change, { pruneSourceField: false })
57 dependencyChanges?.push(change)
58​
59 if (!nodesToKill.has(sourceField)) {
60 fieldsToPruneAfterKill.add(sourceField)
61 }
62 })
63 listenerInstance.resolvedWatchFields = null
64 })
66​
67function detachWatchingListenerFields({
68 sourceField,
69 watchingFields,
70 nodesToKill,
71 fieldsToPruneAfterKill,
72 dependencyChanges,
73}: {
74 sourceField: AnyInternalFieldApi
75 watchingFields: FieldWatchingListenerFields | null
76 nodesToKill: Set<AnyInternalFieldApi>
77 fieldsToPruneAfterKill: Set<AnyInternalFieldApi>
78 dependencyChanges: Array<FieldDependencyChange> | null
79}) {
80 if (!watchingFields) return
81​
82 for (const [watchingField, listenerInstances] of Array.from(watchingFields)) {
83 for (const listenerInstance of Array.from(listenerInstances)) {
84 const change = {
85 kind: 'listener' as const,
86 sourceField,
87 watchingField,
88 listenerInstance,
89 }
90 detachWatchingListenerField(change, { pruneSourceField: false })
91 dependencyChanges?.push(change)
92​
93 listenerInstance.resolvedWatchFields?.forEach((resolvedField, name) => {
94 if (resolvedField === sourceField) {
95 listenerInstance.deleteResolvedWatchField(name)
96 }
97 })
98​
99 if (!nodesToKill.has(watchingField)) {
100 fieldsToPruneAfterKill.add(watchingField)
101 }
102 }
103 }
105​
106/**
107 * Detaches watched-field dependencies owned by validators on a field being killed.
108 *
109 * Validator instances hold the forward references in `resolvedWatchFields`,
110 * while each watched source field holds the reverse registration in
111 * `_watchingValidatorFields`. The reverse registrations must be removed before
112 * the instances are disposed. Surviving source fields are queued for pruning
113 * after the complete kill pass to avoid recursively mutating the field tree
114 * during cleanup.
115 */
116function detachWatchedValidatorFields({
117 field,
118 nodesToKill,
119 fieldsToPruneAfterKill,
120 dependencyChanges,
121}: {
122 field: AnyInternalFieldApi
123 nodesToKill: Set<AnyInternalFieldApi>
124 fieldsToPruneAfterKill: Set<AnyInternalFieldApi>
125 dependencyChanges: Array<FieldDependencyChange> | null
126}) {
127 field._validatorInstances?.forEach((validatorInstance) => {
128 validatorInstance.resolvedWatchFields?.forEach((sourceField) => {
129 const change = {
130 kind: 'validator' as const,
131 sourceField,
132 watchingField: field,
133 validatorInstance,
134 }
135 detachWatchingValidatorField(change, { pruneSourceField: false })
136 dependencyChanges?.push(change)
137​
138 if (!nodesToKill.has(sourceField)) {
139 fieldsToPruneAfterKill.add(sourceField)
140 }
141 })
142 validatorInstance.resolvedWatchFields = null
143 })
145​
146/**
147 * Detaches validators on other fields that watch a source field being killed.
148 *
149 * This removes the source field's reverse registrations and the corresponding
150 * forward references from each surviving validator instance. Surviving
151 * watching fields are queued for pruning after the complete kill pass.
152 */
153function detachWatchingValidatorFields({
154 sourceField,
155 watchingFields,
156 nodesToKill,
157 fieldsToPruneAfterKill,
158 dependencyChanges,
159}: {
160 sourceField: AnyInternalFieldApi
161 watchingFields: FieldWatchingValidatorFields | null
162 nodesToKill: Set<AnyInternalFieldApi>
163 fieldsToPruneAfterKill: Set<AnyInternalFieldApi>
164 dependencyChanges: Array<FieldDependencyChange> | null
165}) {
166 if (!watchingFields) return
167​
168 for (const [watchingField, validatorInstances] of Array.from(
169 watchingFields,
170 )) {
171 for (const validatorInstance of Array.from(validatorInstances)) {
172 const change = {
173 kind: 'validator' as const,
174 sourceField,
175 watchingField,
176 validatorInstance,
177 }
178 detachWatchingValidatorField(change, { pruneSourceField: false })
179 dependencyChanges?.push(change)
180​
181 validatorInstance.resolvedWatchFields?.forEach((resolvedField, name) => {
182 if (resolvedField === sourceField) {
183 validatorInstance.deleteResolvedWatchField(name)
184 }
185 })
186​
187 if (!nodesToKill.has(watchingField)) {
188 fieldsToPruneAfterKill.add(watchingField)
189 }
190 }
191 }
193​
194function detachLinkedFieldReferences({
195 field,
196 nodesToKill,
197 fieldsToPruneAfterKill,
198 dependencyChanges,
199}: {
200 field: AnyInternalFieldApi
201 nodesToKill: Set<AnyInternalFieldApi>
202 fieldsToPruneAfterKill: Set<AnyInternalFieldApi>
203 dependencyChanges: Array<FieldDependencyChange> | null
204}) {
205 detachWatchedListenerFields({
206 field,
207 nodesToKill,
208 fieldsToPruneAfterKill,
209 dependencyChanges,
210 })
211​
212 detachWatchedValidatorFields({
213 field,
214 nodesToKill,
215 fieldsToPruneAfterKill,
216 dependencyChanges,
217 })
218​
219 detachWatchingListenerFields({
220 sourceField: field,
221 watchingFields: field._watchingListenerFields,
222 nodesToKill,
223 fieldsToPruneAfterKill,
224 dependencyChanges,
225 })
226 field._watchingListenerFields = null
227​
228 detachWatchingValidatorFields({
229 sourceField: field,
230 watchingFields: field._watchingValidatorFields,
231 nodesToKill,
232 fieldsToPruneAfterKill,
233 dependencyChanges,
234 })
235 field._watchingValidatorFields = null
237​
238export function updateChildContributionCount(
239 field: AnyInternalFieldApi,
240 prevState: ChildContributionStates,
241 newState: ChildContributionStates,
242): void {
243 if (field._isKilled) return
244​
245 batch(() => {
246 for (const key of childContributionKeys) {
247 const prevContributes = prevState[key]
248 const newContributes = newState[key]
249​
250 if (prevContributes === newContributes) continue
251​
252 const delta = newContributes ? 1 : -1
253​
254 field._setMeta((prev) => ({
255 ...prev,
256 childContributionCounts: {
257 ...prev.childContributionCounts,
258 [key]: prev.childContributionCounts[key] + delta,
259 },
260 }))
261 }
262 })
264​
265export function moveFieldToSegment(
266 field: AnyInternalFieldApi,
267 newSegment: NameSegment,
268): void {
269 if (field._isKilled) return
270​
271 if (field._segmentValue === newSegment) {
272 return
273 }
274​
275 const oldSegment = field._segmentValue
276 field._segmentValue = newSegment
277 field._defaultValueCache = null
278 if (field._parent._getChild(oldSegment) === field) {
279 field._parent._removeChild(oldSegment)
280 }
281 field._parent._setChild(field)
283​
284function notifyFieldSubtreeListeners(
285 field: AnyInternalFieldApi,
286 trigger: FieldListenerTriggers,
287): void {
288 if (field._isKilled) return
289​
290 for (const node of collectFieldSubtree(field)) {
291 if (node._isKilled) continue
292 node._notifyListener(trigger, new WeakSet())
293 }
295​
296function prepareFormGroupsForFieldReplacement(
297 fields: ReadonlyArray<AnyInternalFieldApi>,
298): () => void {
299 const fieldsToReplace = new Set(fields)
300 const formGroups = fields.flatMap((field) =>
301 field._formGroup ? [{ group: field._formGroup, name: field.name }] : [],
302 )
303 const affectedFormGroups = new Set(formGroups.map(({ group }) => group))
304​
305 const replacementRoot = fields[0]
306 if (replacementRoot) {
307 visitFieldAndAncestors(replacementRoot, (field) => {
308 if (field._formGroup) affectedFormGroups.add(field._formGroup)
309 })
310 }
311​
312 for (const group of affectedFormGroups) {
313 group._removeRoutedErrorFields(fieldsToReplace)
314 }
315​
316 for (const { group } of formGroups) {
317 group._cancelValidation()
318 }
319​
320 return () => {
321 if (formGroups.length === 0) return
322​
323 batch(() => {
324 for (const { group, name } of formGroups) {
325 group._attachToFieldTrie(name)
326 }
327 })
328 }
330​
331export function killField(
332 field: AnyInternalFieldApi,
333 options: {
334 listenerEvent?: FieldListenerTriggers
335 } = {},
336) {
337 const bridge = devtools()
338 const dependencyChanges = bridge.fieldDependenciesChanged
339 ? new Array<FieldDependencyChange>()
340 : null
341 let removedFields: Array<{
342 field: AnyInternalFieldApi
343 previousPath: string
344 }> = []
345 let reattachFormGroups = () => {}
346​
347 batch(() => {
348 const nodesToKill = collectFieldSubtree(field)
349 removedFields = nodesToKill.map((node) => ({
350 field: node,
351 previousPath: node.name,
352 }))
353 const nodesToKillSet = new Set(nodesToKill)
354 const fieldsToPruneAfterKill = new Set<AnyInternalFieldApi>()
355​
356 reattachFormGroups = prepareFormGroupsForFieldReplacement(nodesToKill)
357​
358 if (options.listenerEvent) {
359 notifyFieldSubtreeListeners(field, options.listenerEvent)
360 }
361​
362 field._parent._removeChild(field._segment)
363​
364 const killedRootCounterContributions: Record<
365 RootCounterContributionKey,
366 number
367 > = {
368 touched: 0,
369 validating: 0,
370 }
371​
372 for (const node of nodesToKill) {
373 const nodeMeta = node._atoms.meta?.get()
374 nodeMeta?._validationSourceErrors?.forEach((_error, validationSource) =>
375 validationSource.deleteErrorTarget(node),
376 )
377 detachLinkedFieldReferences({
378 field: node,
379 nodesToKill: nodesToKillSet,
380 fieldsToPruneAfterKill,
381 dependencyChanges,
382 })
383​
384 if (!node._parent._isRoot && nodeMeta) {
385 node._parent._updateChildContributionCount(
386 getChildContributionStates(nodeMeta),
387 {
388 dirty: false,
389 error: false,
390 touched: false,
391 validating: false,
392 },
393 )
394 } else if (nodeMeta) {
395 const contributions = getChildContributionStates(nodeMeta)
396 for (const key of rootCounterContributionKeys) {
397 if (contributions[key]) {
398 killedRootCounterContributions[key]++
399 }
400 }
401 }
402​
403 node._isKilled = true
404 node._refCount = 0
405 node._formGroup = null
406 node._defaultValueCache = null
407 node._atoms.store = undefined
408 node._listenerInstances?.forEach((instance) => instance.dispose())
409 node._listenerInstances = null
410 node._validatorInstances?.forEach((instance) => instance.dispose())
411 node._validatorInstances = null
412 node._childrenMap.clear()
413 node._parent._removeChild(node._segment)
414 }
415​
416 for (const fieldToPrune of fieldsToPruneAfterKill) {
417 pruneFieldIfUnused(fieldToPrune)
418 }
419​
420 field.form._atoms.meta.touchedFieldCount.set((prev) =>
421 Math.max(0, prev - killedRootCounterContributions.touched),
422 )
423 field.form._atoms.meta.fieldValidationCount.set((prev) =>
424 Math.max(0, prev - killedRootCounterContributions.validating),
425 )
426​
427 field.form._atoms.meta.errorFields.set((prev) => {
428 if (prev.size > 0) {
429 const nextErrorFields = new Set(prev)
430​
431 for (const node of nodesToKill) {
432 nextErrorFields.delete(node)
433 }
434​
435 if (nextErrorFields.size !== prev.size) {
436 return nextErrorFields
437 }
438 }
439​
440 return prev
441 })
442 })
443​
444 if (removedFields.length > 0) {
445 bridge.removeFieldSubtree?.(field.form, removedFields)
446 }
447 if (dependencyChanges && dependencyChanges.length > 0) {
448 bridge.fieldDependenciesChanged?.(dependencyChanges)
449 }
450 reattachFormGroups()
452​
453function canPruneField(field: AnyInternalFieldApi): boolean {
454 if (field._isKilled) return false
455​
456 if (field._refCount > 0) return false
457 if (field._formGroup) return false
458 if (field._childrenMap.size > 0) return false
459 if (field._watchingListenerFields) return false
460 if (field._watchingValidatorFields) return false
461 // Watched source maps retain and notify this field, so keep both endpoints
462 // reachable from the form trie while an outgoing link is active.
463 if (field._listenerInstances?.some((v) => v.resolvedWatchFields)) {
464 return false
465 }
466 if (field._validatorInstances?.some((v) => v.resolvedWatchFields)) {
467 return false
468 }
469 const meta = field._atoms.meta?.get() ?? defaultInternalBaseFieldMeta
470 if (!isPrunableMeta(meta)) return false
471​
472 return true
474​
475export function pruneFieldIfUnused(field: AnyInternalFieldApi): void {
476 const bridge = devtools()
477 const removedFields = bridge.removeFieldSubtree
478 ? new Array<{ field: AnyInternalFieldApi; previousPath: string }>()
479 : null
480​
481 visitFieldAndAncestors(field, (node, stop) => {
482 if (!canPruneField(node)) return stop
483​
484 removedFields?.push({ field: node, previousPath: node.name })
485 node._parent._removeChild(node._segment)
486 return undefined
487 })
488​
489 if (removedFields && removedFields.length > 0) {
490 bridge.removeFieldSubtree?.(field.form, removedFields)
491 }
493​
494export function touchAllFieldsAndCollectSubmitValidators(
495 root: InternalRootFieldApi,
496): Array<AnyInternalFieldApi> {
497 const fieldsWithValidators: Array<AnyInternalFieldApi> = []
498 visitAllFormFields(root, (field) => {
499 field._notifyEvent(
500 {
501 causeValidation: false,
502 markAsBlurred: false,
503 markAsDirty: false,
504 // Touch all fields
505 markAsTouched: true,
506 // We're doing DFS, so propagation is useless
507 doPropagate: false,
508 },
509 'submit',
510 )
511​
512 if (field._validatorInstances && field._validatorInstances.length > 0) {
513 fieldsWithValidators.push(field)
514 }
515 })
516​
517 return fieldsWithValidators