Open History to see the last commit
1import { InternalFormApi } from '@tanstack/form-core/internals'
2import { useSelector } from '@tanstack/svelte-store'
3import { onMount } from 'svelte'
4import Field from './Field.svelte'
5import FormGroup from './FormGroup.svelte'
6import Subscribe from './Subscribe.svelte'
7import { withComponentProps } from './utils.lib.js'
8import type { FormOptions } from '@tanstack/form-core'
9import type { Component } from 'svelte'
10import type { AnyInternalFormApi } from '@tanstack/form-core/internals'
11import type { SvelteTanStackFormComponents } from './Components.public'
12β
13export interface InternalSvelteFormApi
14 extends AnyInternalFormApi, SvelteTanStackFormComponents<any, any, any> {
15 _Subscribe: Component<any>
16 useSelector: <TSelected = any>(
17 selector?: (state: any) => TSelected,
18 ) => { readonly current: TSelected }
19}
20β
21export function attachSvelteFormComponents(
22 form: AnyInternalFormApi,
23 fieldComponents: Record<string, Component<any>> | null,
24): InternalSvelteFormApi {
25 const result = form as InternalSvelteFormApi
26β
27 result.Field = ((internals: any, props: any) =>
28 Field(
29 internals,
30 withComponentProps(props, {
31 form,
32 fieldComponents: fieldComponents ?? {},
33 }),
34 )) as never
35 result.ArrayField = ((internals: any, props: any) =>
36 Field(
37 internals,
38 withComponentProps(props, {
39 form,
40 array: true,
41 fieldComponents: fieldComponents ?? {},
42 }),
43 )) as never
44 result._Subscribe = (internals, props) => Subscribe(internals, props)
45 result.Subscribe = ((internals: any, props: any) =>
46 Subscribe(
47 internals,
48 withComponentProps(props, { source: form.atom }),
49 )) as never
50 result.FormGroup = ((internals: any, props: any) =>
51 FormGroup(internals, withComponentProps(props, { form }))) as never
52 result.useSelector = ((selector?: (state: any) => any) =>
53 useSelector(form.atom, selector)) as never
54β
55 return result
56}
57β
58export function initializeForm(
59 options: FormOptions<any, any, any, unknown>,
60): InternalSvelteFormApi {
61 return attachSvelteFormComponents(new InternalFormApi(options), null)
62}
63β
64export function createInternalForm(
65 options: () => FormOptions<any, any, any, unknown>,
66 initialize: (
67 options: FormOptions<any, any, any, unknown>,
68 ) => InternalSvelteFormApi,
69): InternalSvelteFormApi {
70 const form = initialize(options())
71β
72 $effect.pre(() => {
73 form._update(options())
74 })
75 onMount(() => form.mount())
76β
77 return form
78}