Open History to see the last commit
1import { InternalFormApi } from '@tanstack/form-core/internals'
2import * as Preact from 'preact/compat'
3import { useEffect, useRef } from 'preact/compat'
4import { attachPreactFormComponents } from './Components.lib'
5import type { AnyInternalFormApi } from '@tanstack/form-core/internals'
6import type { FormOptions } from '@tanstack/form-core'
7import type { PreactTanStackFormComponents } from './Components.public'
8β
9const usePreactId =
10 (Preact as typeof Preact & { useId?: () => string }).useId ??
11 (() => undefined)
12β
13export interface InternalPreactFormApi
14 extends AnyInternalFormApi, PreactTanStackFormComponents<any, any, any> {}
15β
16export function initializeForm(
17 options: FormOptions<any, any, any, unknown>,
18): InternalPreactFormApi {
19 const form = new InternalFormApi(options)
20β
21 const preactFormApi = attachPreactFormComponents(form, null)
22β
23 return preactFormApi
24}
25β
26export function useInternalForm(
27 options: FormOptions<any, any, any, unknown>,
28 initializeFn: (
29 options: FormOptions<any, any, any, unknown>,
30 ) => InternalPreactFormApi,
31) {
32 const preactFormId = usePreactId()
33 const resolvedOptions =
34 options.formId === undefined
35 ? { ...options, formId: preactFormId }
36 : options
37 const formRef = useRef<InternalPreactFormApi>(null)
38β
39 if (!formRef.current) {
40 formRef.current = initializeFn(resolvedOptions)
41 }
42β
43 useEffect(() => formRef.current!._update(resolvedOptions))
44 useEffect(() => {
45 const unmount = formRef.current!.mount()
46 return unmount
47 }, [])
48β
49 return formRef.current
50}