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

FormGroup.svelte

101 lines2.7 KB

1<script module lang="ts">
2 import { InternalFormGroupApi } from '@tanstack/form-core/internals'
3 import { useSelector } from '@tanstack/svelte-store'
4 import { withComponentProps } from './utils.lib.js'
5 import type {
6 FormErrorTypes,
7 FormGroupApi,
8 FormGroupOptions,
9 FormGroupValidators,
10 ToFormGroupErrorTypes,
11 } from '@tanstack/form-core'
12 import type { AnyInternalFormApi } from '@tanstack/form-core/internals'
13​
14 export function createFormGroup<
15 TFormData,
16 TGroupName,
17 TGroupValue,
18 const TGroupValidators extends FormGroupValidators<TGroupValue>,
19 TFormErrorTypes extends FormErrorTypes,
20 >(
21 options: () => FormGroupOptions<
22 TFormData,
23 TGroupName,
24 TGroupValue,
25 TGroupValidators,
26 TFormErrorTypes
27 >,
28 ): FormGroupApi<
29 TFormData,
30 TGroupName,
31 TGroupValue,
32 ToFormGroupErrorTypes<TGroupValidators>,
33 TFormErrorTypes
34 > {
35 const group = new InternalFormGroupApi(options() as never)
36​
37 $effect.pre(() => {
38 group.update(options() as never)
39 })
40 $effect(() => {
41 group.mount()
42 return () => group._cleanup()
43 })
44​
45 const state = useSelector(group.atom)
46​
47 return new Proxy({} as typeof group, {
48 get(target, property) {
49 if (Reflect.has(target, property)) return Reflect.get(target, property)
50 if (property === 'state') return state.current
51 if (property === 'value') return state.current.values
52 const value = Reflect.get(group, property, group)
53 return typeof value === 'function' ? value.bind(group) : value
54 },
55 }) as never
56 }
57​
58 export function attachGroupComponents(
59 group: any,
60 form: AnyInternalFormApi & Record<string, any>,
61 ) {
62 group.Field = (internals: any, props: any) =>
63 form.Field(
64 internals,
65 group._getFormFieldOptions(props, withComponentProps),
66 )
67 group.ArrayField = (internals: any, props: any) =>
68 form.ArrayField(
69 internals,
70 group._getFormFieldOptions(props, withComponentProps),
71 )
72 group.Subscribe = (internals: any, props: any) =>
73 form._Subscribe(
74 internals,
75 withComponentProps(props, { source: group.atom }),
76 )
77 return group
78 }
79</script>
80​
81<script lang="ts">
82 import { untrack, type Snippet } from 'svelte'
83​
84 interface Props {
85 form: AnyInternalFormApi & Record<string, any>
86 children: Snippet<[any]>
87 name: string
88 validators?: any
89 onSubmit?: any
90 onSubmitInvalid?: any
91 }
92​
93 let { children, form, ...groupOptions }: Props = $props()
94 const initialForm = untrack(() => form)
95 const groupApi = attachGroupComponents(
96 createFormGroup(() => ({ ...groupOptions, form: initialForm }) as never),
97 initialForm,
98 )
99</script>
100​
101{@render children(groupApi)}