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

createFormHook.tsx

369 lines9.8 KB

1import { createContext, useContext, useMemo } from 'react'
2import { useForm } from './useForm'
3import type {
4 AnyFieldApi,
5 AnyFormApi,
6 FieldApi,
7 FormApi,
8 FormAsyncValidateOrFn,
9 FormOptions,
10 FormValidateOrFn,
11} from '@tanstack/form-core'
12import type { ComponentType, Context, JSX, PropsWithChildren } from 'react'
13import type { FieldComponent } from './useField'
14import type { ReactFormExtendedApi } from './useForm'
15​
16/**
17 * TypeScript inferencing is weird.
18 *
19 * If you have:
20 *
21 * @example
22 *
23 * interface Args<T> {
24 * arg?: T
25 * }
26 *
27 * function test<T>(arg?: Partial<Args<T>>): T {
28 * return 0 as any;
29 * }
30 *
31 * const a = test({});
32 *
33 * Then `T` will default to `unknown`.
34 *
35 * However, if we change `test` to be:
36 *
37 * @example
38 *
39 * function test<T extends undefined>(arg?: Partial<Args<T>>): T;
40 *
41 * Then `T` becomes `undefined`.
42 *
43 * Here, we are checking if the passed type `T` extends `DefaultT` and **only**
44 * `DefaultT`, as if that's the case we assume that inferencing has not occured.
45 */
46type UnwrapOrAny<T> = [unknown] extends [T] ? any : T
47type UnwrapDefaultOrAny<DefaultT, T> = [DefaultT] extends [T]
48 ? [T] extends [DefaultT]
49 ? any
50 : T
51 : T
52​
53export function createFormHookContexts() {
54 // We should never hit the `null` case here
55 const fieldContext = createContext<AnyFieldApi>(null as never)
56​
57 function useFieldContext<TData>() {
58 const field = useContext(fieldContext)
59​
60 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
61 if (!field) {
62 throw new Error(
63 '`fieldContext` only works when within a `fieldComponent` passed to `createFormHook`',
64 )
65 }
66​
67 return field as FieldApi<
68 any,
69 string,
70 TData,
71 any,
72 any,
73 any,
74 any,
75 any,
76 any,
77 any,
78 any,
79 any,
80 any,
81 any,
82 any,
83 any,
84 any,
85 any,
86 any
87 >
88 }
89​
90 // We should never hit the `null` case here
91 const formContext = createContext<AnyFormApi>(null as never)
92​
93 function useFormContext() {
94 const form = useContext(formContext)
95​
96 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
97 if (!form) {
98 throw new Error(
99 '`formContext` only works when within a `formComponent` passed to `createFormHook`',
100 )
101 }
102​
103 return form as ReactFormExtendedApi<
104 // If you need access to the form data, you need to use `withForm` instead
105 Record<string, never>,
106 any,
107 any,
108 any,
109 any,
110 any,
111 any,
112 any,
113 any,
114 any
115 >
116 }
117​
118 return { fieldContext, useFieldContext, useFormContext, formContext }
120​
121interface CreateFormHookProps<
122 TFieldComponents extends Record<string, ComponentType<any>>,
123 TFormComponents extends Record<string, ComponentType<any>>,
124> {
125 fieldComponents: TFieldComponents
126 fieldContext: Context<AnyFieldApi>
127 formComponents: TFormComponents
128 formContext: Context<AnyFormApi>
130​
131type AppFieldExtendedReactFormApi<
132 TFormData,
133 TOnMount extends undefined | FormValidateOrFn<TFormData>,
134 TOnChange extends undefined | FormValidateOrFn<TFormData>,
135 TOnChangeAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
136 TOnBlur extends undefined | FormValidateOrFn<TFormData>,
137 TOnBlurAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
138 TOnSubmit extends undefined | FormValidateOrFn<TFormData>,
139 TOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
140 TOnServer extends undefined | FormAsyncValidateOrFn<TFormData>,
141 TSubmitMeta,
142 TFieldComponents extends Record<string, ComponentType<any>>,
143 TFormComponents extends Record<string, ComponentType<any>>,
144> = ReactFormExtendedApi<
145 TFormData,
146 TOnMount,
147 TOnChange,
148 TOnChangeAsync,
149 TOnBlur,
150 TOnBlurAsync,
151 TOnSubmit,
152 TOnSubmitAsync,
153 TOnServer,
154 TSubmitMeta
155> &
156 NoInfer<TFormComponents> & {
157 AppField: FieldComponent<
158 TFormData,
159 TOnMount,
160 TOnChange,
161 TOnChangeAsync,
162 TOnBlur,
163 TOnBlurAsync,
164 TOnSubmit,
165 TOnSubmitAsync,
166 TOnServer,
167 TSubmitMeta,
168 NoInfer<TFieldComponents>
169 >
170 AppForm: ComponentType<PropsWithChildren>
171 }
172​
173export interface WithFormProps<
174 TFormData,
175 TOnMount extends undefined | FormValidateOrFn<TFormData>,
176 TOnChange extends undefined | FormValidateOrFn<TFormData>,
177 TOnChangeAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
178 TOnBlur extends undefined | FormValidateOrFn<TFormData>,
179 TOnBlurAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
180 TOnSubmit extends undefined | FormValidateOrFn<TFormData>,
181 TOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
182 TOnServer extends undefined | FormAsyncValidateOrFn<TFormData>,
183 TSubmitMeta,
184 TFieldComponents extends Record<string, ComponentType<any>>,
185 TFormComponents extends Record<string, ComponentType<any>>,
186 TRenderProps extends Record<string, unknown> = Record<string, never>,
187> extends FormOptions<
188 TFormData,
189 TOnMount,
190 TOnChange,
191 TOnChangeAsync,
192 TOnBlur,
193 TOnBlurAsync,
194 TOnSubmit,
195 TOnSubmitAsync,
196 TOnServer,
197 TSubmitMeta
198 > {
199 // Optional, but adds props to the `render` function outside of `form`
200 props?: TRenderProps
201 render: (
202 props: PropsWithChildren<
203 NoInfer<TRenderProps> & {
204 form: AppFieldExtendedReactFormApi<
205 TFormData,
206 TOnMount,
207 TOnChange,
208 TOnChangeAsync,
209 TOnBlur,
210 TOnBlurAsync,
211 TOnSubmit,
212 TOnSubmitAsync,
213 TOnServer,
214 TSubmitMeta,
215 TFieldComponents,
216 TFormComponents
217 >
218 }
219 >,
220 ) => JSX.Element
222​
223export function createFormHook<
224 const TComponents extends Record<string, ComponentType<any>>,
225 const TFormComponents extends Record<string, ComponentType<any>>,
226>({
227 fieldComponents,
228 fieldContext,
229 formContext,
230 formComponents,
231}: CreateFormHookProps<TComponents, TFormComponents>) {
232 function useAppForm<
233 TFormData,
234 TOnMount extends undefined | FormValidateOrFn<TFormData>,
235 TOnChange extends undefined | FormValidateOrFn<TFormData>,
236 TOnChangeAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
237 TOnBlur extends undefined | FormValidateOrFn<TFormData>,
238 TOnBlurAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
239 TOnSubmit extends undefined | FormValidateOrFn<TFormData>,
240 TOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
241 TOnServer extends undefined | FormAsyncValidateOrFn<TFormData>,
242 TSubmitMeta,
243 >(
244 props: FormOptions<
245 TFormData,
246 TOnMount,
247 TOnChange,
248 TOnChangeAsync,
249 TOnBlur,
250 TOnBlurAsync,
251 TOnSubmit,
252 TOnSubmitAsync,
253 TOnServer,
254 TSubmitMeta
255 >,
256 ): AppFieldExtendedReactFormApi<
257 TFormData,
258 TOnMount,
259 TOnChange,
260 TOnChangeAsync,
261 TOnBlur,
262 TOnBlurAsync,
263 TOnSubmit,
264 TOnSubmitAsync,
265 TOnServer,
266 TSubmitMeta,
267 TComponents,
268 TFormComponents
269 > {
270 const form = useForm(props)
271​
272 const AppForm = useMemo(() => {
273 return (({ children }) => {
274 return (
275 <formContext.Provider value={form}>{children}</formContext.Provider>
276 )
277 }) as ComponentType<PropsWithChildren>
278 }, [form])
279​
280 const AppField = useMemo(() => {
281 return (({ children, ...props }) => {
282 return (
283 <form.Field {...props}>
284 {(field) => (
285 // eslint-disable-next-line @eslint-react/no-context-provider
286 <fieldContext.Provider value={field}>
287 {children(Object.assign(field, fieldComponents))}
288 </fieldContext.Provider>
289 )}
290 </form.Field>
291 )
292 }) as FieldComponent<
293 TFormData,
294 TOnMount,
295 TOnChange,
296 TOnChangeAsync,
297 TOnBlur,
298 TOnBlurAsync,
299 TOnSubmit,
300 TOnSubmitAsync,
301 TOnServer,
302 TSubmitMeta,
303 TComponents
304 >
305 }, [form])
306​
307 const extendedForm = useMemo(() => {
308 return Object.assign(form, {
309 AppField,
310 AppForm,
311 ...formComponents,
312 })
313 }, [form, AppField, AppForm])
314​
315 return extendedForm
316 }
317​
318 function withForm<
319 TFormData,
320 TOnMount extends undefined | FormValidateOrFn<TFormData>,
321 TOnChange extends undefined | FormValidateOrFn<TFormData>,
322 TOnChangeAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
323 TOnBlur extends undefined | FormValidateOrFn<TFormData>,
324 TOnBlurAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
325 TOnSubmit extends undefined | FormValidateOrFn<TFormData>,
326 TOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TFormData>,
327 TOnServer extends undefined | FormAsyncValidateOrFn<TFormData>,
328 TSubmitMeta,
329 TRenderProps extends Record<string, unknown> = {},
330 >({
331 render,
332 props,
333 }: WithFormProps<
334 TFormData,
335 TOnMount,
336 TOnChange,
337 TOnChangeAsync,
338 TOnBlur,
339 TOnBlurAsync,
340 TOnSubmit,
341 TOnSubmitAsync,
342 TOnServer,
343 TSubmitMeta,
344 TComponents,
345 TFormComponents,
346 TRenderProps
347 >): WithFormProps<
348 UnwrapOrAny<TFormData>,
349 UnwrapDefaultOrAny<undefined | FormValidateOrFn<TFormData>, TOnMount>,
350 UnwrapDefaultOrAny<undefined | FormValidateOrFn<TFormData>, TOnChange>,
351 UnwrapDefaultOrAny<undefined | FormValidateOrFn<TFormData>, TOnChangeAsync>,
352 UnwrapDefaultOrAny<undefined | FormValidateOrFn<TFormData>, TOnBlur>,
353 UnwrapDefaultOrAny<undefined | FormValidateOrFn<TFormData>, TOnBlurAsync>,
354 UnwrapDefaultOrAny<undefined | FormValidateOrFn<TFormData>, TOnSubmit>,
355 UnwrapDefaultOrAny<undefined | FormValidateOrFn<TFormData>, TOnSubmitAsync>,
356 UnwrapDefaultOrAny<undefined | FormValidateOrFn<TFormData>, TOnServer>,
357 UnwrapOrAny<TSubmitMeta>,
358 UnwrapOrAny<TComponents>,
359 UnwrapOrAny<TFormComponents>,
360 UnwrapOrAny<TRenderProps>
361 >['render'] {
362 return (innerProps) => render({ ...props, ...innerProps })
363 }
364​
365 return {
366 useAppForm,
367 withForm,
368 }