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

withFields.lib.ts

76 lines2.1 KB

1import {
2 InternalFieldGroupApi,
3 defineFieldGroupFieldsRuntime,
4 fieldGroupHelperRuntime,
5} from '@tanstack/form-core/internals'
6import { createComponent, mergeProps, splitProps } from 'solid-js'
7import type { Component } from 'solid-js'
8import type { AnyFieldGroupApi } from './FieldGroupApi.public'
9​
10function attachSolidFieldGroupComponents(
11 group: InternalFieldGroupApi,
12 form: any,
13): AnyFieldGroupApi {
14 const Field: Component<any> = (props) =>
15 createComponent(
16 form.Field as Component<any>,
17 group._getFormFieldOptions(props, mergeProps),
18 )
19 const ArrayField: Component<any> = (props) =>
20 createComponent(
21 form.ArrayField as Component<any>,
22 group._getFormFieldOptions(props, mergeProps),
23 )
24 const Subscribe: Component<any> = (props) =>
25 createComponent(form.Subscribe as Component<any>, props)
26​
27 return Object.assign(group, {
28 Field,
29 ArrayField,
30 Subscribe,
31 }) as never
33​
34export function defineFieldGroupRuntime<
35 TFields extends Record<string, unknown>,
36>(defineFieldGroupFn: (helperRuntime: any) => TFields) {
37 const fields = defineFieldGroupFieldsRuntime(
38 defineFieldGroupFn(fieldGroupHelperRuntime),
39 )
40​
41 return {
42 fields,
43 bindComponent: (Component: Component<any>, fieldsPropName: string) =>
44 withFieldsRuntime(fields, Component, fieldsPropName),
45 }
47​
48function withFieldsRuntime(
49 fields: Record<string, unknown>,
50 Component: Component<any>,
51 fieldsPropName: string,
52) {
53 const fieldNames = Object.keys(fields)
54​
55 return function FieldGroupComponent(props: any) {
56 const [localProps, restProps] = splitProps(props, ['form', fieldsPropName])
57 const form = localProps.form
58 if (!form) {
59 throw new Error('TanStack Form: Field groups must receive a `form` prop.')
60 }
61​
62 const fieldGroupApi = attachSolidFieldGroupComponents(
63 new InternalFieldGroupApi({
64 form,
65 fieldNames,
66 getBindings: () => localProps[fieldsPropName],
67 }),
68 form,
69 )
70​
71 return createComponent(
72 Component,
73 mergeProps(restProps, { [fieldsPropName]: fieldGroupApi }),
74 )
75 }