Open History to see the last commit
1import { shallow } from '@tanstack/vue-store'
2import { shallowRef, toRaw, watch } from 'vue'
3import type { ShallowRef } from 'vue'
4import type {
5 AnyInternalFieldApi,
6 InternalBaseFieldMeta,
7} from '@tanstack/form-core/internals'
8β
9function createFieldSelection<TSelected>(
10 fieldApi: ShallowRef<AnyInternalFieldApi>,
11 selector: (field: AnyInternalFieldApi) => TSelected,
12) {
13 const selected = shallowRef(selector(fieldApi.value)) as ShallowRef<TSelected>
14 // Metadata can change without an array's structure changing. Keep it
15 // reactive for metadata consumers without invalidating value-only slots.
16 const meta = shallowRef(fieldApi.value.meta)
17β
18 watch(
19 fieldApi,
20 (field, _previous, onCleanup) => {
21 meta.value = field.meta
22 selected.value = selector(field)
23 const subscription = field.atom.subscribe(() => {
24 meta.value = field.meta
25 const next = selector(field)
26 if (!shallow(toRaw(selected.value), next)) selected.value = next
27 })
28 onCleanup(() => subscription.unsubscribe())
29 },
30 { immediate: true, flush: 'sync' },
31 )
32β
33 return { selection: selected, meta }
34}
35β
36export function createValueFieldSubscription(
37 fieldApi: ShallowRef<AnyInternalFieldApi>,
38) {
39 return createFieldSelection(fieldApi, (field) => ({
40 value: field.value,
41 meta: field.meta,
42 }))
43}
44β
45export function createArrayFieldSubscription(
46 fieldApi: ShallowRef<AnyInternalFieldApi>,
47) {
48 return createFieldSelection(fieldApi, (field) => ({
49 length: field.value.length,
50 version: (field.meta as InternalBaseFieldMeta)._arrayVersion,
51 }))
52}