Open History to see the last commit
1import {
2 InternalFieldGroupApi,
3 defineFieldGroupFieldsRuntime,
4 fieldGroupHelperRuntime,
5} from '@tanstack/form-core/internals'
6import { computed, defineComponent, h } from 'vue'
7import type { Component } from 'vue'
8import type {
9 AnyFieldApiOptions,
10 InternalFieldGroupBindings,
11} from '@tanstack/form-core/internals'
12import type { AnyFieldGroupApi } from './FieldGroupApi.public'
13β
14function attachVueFieldGroupComponents(
15 group: InternalFieldGroupApi,
16 form: any,
17): AnyFieldGroupApi {
18 const forwardField = (component: Component, name: string) =>
19 defineComponent(
20 (_props, context) => {
21 const resolved = computed(() => {
22 const options = {
23 ...context.attrs,
24 } as unknown as AnyFieldApiOptions
25 return group._getFormFieldOptions(options, (base, overrides) => ({
26 ...base,
27 ...overrides,
28 }))
29 })
30 return () => h(component, resolved.value as never, context.slots)
31 },
32 { name, inheritAttrs: false },
33 )
34β
35 const Field = forwardField(form.Field, 'TanStackForm.FieldGroup.Field')
36 const ArrayField = forwardField(
37 form.ArrayField,
38 'TanStackForm.FieldGroup.ArrayField',
39 )
40 const Subscribe = defineComponent(
41 (_props, context) => () =>
42 h(form.Subscribe, { ...context.attrs } as never, context.slots),
43 { name: 'TanStackForm.FieldGroup.Subscribe', inheritAttrs: false },
44 )
45β
46 return Object.assign(group, {
47 Field,
48 ArrayField,
49 Subscribe,
50 }) as never
51}
52β
53export function defineFieldGroupRuntime<
54 TFields extends Record<string, unknown>,
55>(defineFieldGroupFn: (helperRuntime: any) => TFields) {
56 const fields = defineFieldGroupFieldsRuntime(
57 defineFieldGroupFn(fieldGroupHelperRuntime),
58 )
59β
60 return {
61 fields,
62 bindComponent: (component: Component, fieldsPropName: string) =>
63 withFieldsRuntime(fields, component, fieldsPropName),
64 }
65}
66β
67function withFieldsRuntime(
68 fields: Record<string, unknown>,
69 component: Component,
70 fieldsPropName: string,
71) {
72 const fieldNames = Object.keys(fields)
73β
74 return defineComponent(
75 (_props, context) => {
76 const form = context.attrs.form as any
77 if (!form) {
78 throw new Error(
79 'TanStack Form: Field groups must receive a `form` prop.',
80 )
81 }
82β
83 const fieldGroupApi = attachVueFieldGroupComponents(
84 new InternalFieldGroupApi({
85 form,
86 fieldNames,
87 getBindings: () =>
88 context.attrs[fieldsPropName] as
89 InternalFieldGroupBindings | undefined,
90 }),
91 form,
92 )
93β
94 return () => {
95 const componentProps = { ...context.attrs }
96 delete componentProps.form
97 delete componentProps[fieldsPropName]
98 componentProps[fieldsPropName] = fieldGroupApi
99 return h(component, componentProps, context.slots)
100 }
101 },
102 { name: 'TanStackForm.FieldGroup', inheritAttrs: false },
103 )
104}