Open History to see the last commit
1import { nothing } from 'lit'
2import { AsyncDirective } from 'lit/async-directive.js'
3import { PartType, directive } from 'lit/directive.js'
4import { TanStackStoreSelector, shallow } from '@tanstack/lit-store'
5import {
6 InternalFormApi,
7 InternalFormGroupApi,
8} from '@tanstack/form-core/internals'
9import type {
10 DeepKeys,
11 DeepKeysWhereValueIncludes,
12 DeepValue,
13 FieldApi,
14 FieldApiOptions,
15 FieldValidators,
16 FormApi,
17 FormErrorTypes,
18 FormGroupApi,
19 FormGroupOptions,
20 FormGroupState,
21 FormGroupValidators,
22 FormOptions,
23 FormState,
24 FormValidators,
25 ToFieldError,
26 ToFormErrorTypes,
27 ToFormGroupErrorTypes,
28} from '@tanstack/form-core'
29import type {
30 AnyFieldApiOptions,
31 AnyInternalFieldApi,
32 AnyInternalFormApi,
33 InternalBaseFieldMeta,
34} from '@tanstack/form-core/internals'
35import type { ReactiveController, ReactiveControllerHost } from 'lit'
36import type { Part, PartInfo } from 'lit/directive.js'
37β
38type SelectionSource<TValue> = {
39 get: () => TValue
40 subscribe: (listener: (value: TValue) => void) => {
41 unsubscribe: () => void
42 }
43}
44β
45type RenderCallback<TValue> = (value: TValue) => unknown
46β
47type LitFieldOptions<
48 TFieldData,
49 TFieldName,
50 TFieldValue,
51 TFieldValidators extends FieldValidators<TFieldData, TFieldName, TFieldValue>,
52 TGroupFieldError,
53 TFormData,
54 TFormErrorTypes extends FormErrorTypes,
55> = FieldApiOptions<
56 TFieldData,
57 TFieldName,
58 TFieldValue,
59 TFieldValidators,
60 TGroupFieldError,
61 TFormData,
62 TFormErrorTypes
63>
64β
65type LitFieldRenderApi<
66 TFieldData,
67 TFieldName,
68 TFieldValue,
69 TFieldValidators extends FieldValidators<TFieldData, TFieldName, TFieldValue>,
70 TGroupFieldError,
71 TFormData,
72 TFormErrorTypes extends FormErrorTypes,
73> = FieldApi<
74 TFieldName,
75 TFieldValue,
76 ToFieldError<NoInfer<TFieldValidators>, TGroupFieldError, TFormErrorTypes>,
77 TFormData,
78 TFormErrorTypes
79>
80β
81export interface LitFieldMethods<
82 TFieldData,
83 TGroupFieldError,
84 TFormData,
85 TFormErrorTypes extends FormErrorTypes,
86> {
87 field<
88 const TFieldName extends DeepKeys<TFieldData>,
89 const TFieldValidators extends FieldValidators<
90 TFieldData,
91 TFieldName,
92 DeepValue<TFieldData, TFieldName>
93 >,
94 >(
95 options: LitFieldOptions<
96 TFieldData,
97 TFieldName,
98 DeepValue<TFieldData, TFieldName>,
99 TFieldValidators,
100 TGroupFieldError,
101 TFormData,
102 TFormErrorTypes
103 >,
104 render: RenderCallback<
105 LitFieldRenderApi<
106 TFieldData,
107 TFieldName,
108 DeepValue<TFieldData, TFieldName>,
109 TFieldValidators,
110 TGroupFieldError,
111 TFormData,
112 TFormErrorTypes
113 >
114 >,
115 ): unknown
116β
117 arrayField<
118 const TFieldName extends DeepKeysWhereValueIncludes<TFieldData, Array<any>>,
119 const TFieldValidators extends FieldValidators<
120 TFieldData,
121 TFieldName,
122 DeepValue<TFieldData, TFieldName>
123 >,
124 >(
125 options: LitFieldOptions<
126 TFieldData,
127 TFieldName,
128 DeepValue<TFieldData, TFieldName>,
129 TFieldValidators,
130 TGroupFieldError,
131 TFormData,
132 TFormErrorTypes
133 >,
134 render: RenderCallback<
135 LitFieldRenderApi<
136 TFieldData,
137 TFieldName,
138 DeepValue<TFieldData, TFieldName>,
139 TFieldValidators,
140 TGroupFieldError,
141 TFormData,
142 TFormErrorTypes
143 >
144 >,
145 ): unknown
146}
147β
148export interface LitSubscribeMethod<TState> {
149 subscribe<const TSelected>(
150 selector: (state: TState) => TSelected,
151 render: RenderCallback<NoInfer<TSelected>>,
152 when?: (selected: NoInfer<TSelected>) => boolean,
153 ): unknown
154}
155β
156export type LitFormGroupApi<
157 TFormData,
158 TGroupName,
159 TGroupValue,
160 TGroupErrorTypes extends FormErrorTypes,
161 TFormErrorTypes extends FormErrorTypes,
162> = FormGroupApi<
163 TFormData,
164 TGroupName,
165 TGroupValue,
166 TGroupErrorTypes,
167 TFormErrorTypes
168> &
169 LitFieldMethods<
170 TGroupValue,
171 TGroupErrorTypes['fieldError'],
172 TFormData,
173 TFormErrorTypes
174 > &
175 LitSubscribeMethod<FormGroupState<TGroupValue, TGroupErrorTypes>>
176β
177/**
178 * Owns a form for a Lit reactive-controller host and provides Lit-specific
179 * field, form-group, and subscription render helpers.
180 *
181 * `defaultValues` establish the initial state and inferred form value type.
182 * The form mounts when its host connects and is cleaned up when the host
183 * disconnects. Call `update(...)` to apply later options without replacing the
184 * form instance, and access the framework-agnostic form API through `api`.
185 *
186 * @example
187 * ```ts
188 * class ProfileForm extends LitElement {
189 * private form = new TanStackFormController(this, {
190 * defaultValues: { name: '' },
191 * onSubmit: ({ value }) => saveProfile(value),
192 * })
193 *
194 * render() {
195 * return html`<form
196 * @submit=${(event: SubmitEvent) => {
197 * event.preventDefault()
198 * void this.form.api.handleSubmit()
199 * }}
200 * ></form>`
201 * }
202 * }
203 * ```
204 *
205 * @typeParam TFormData - Library-managed. Do not specify explicitly.
206 * @typeParam TFormValidators - Library-managed. Do not specify explicitly.
207 * @typeParam TSubmitReturn - Library-managed. Do not specify explicitly.
208 */
209export class TanStackFormController<
210 TFormData,
211 const TFormValidators extends FormValidators<TFormData>,
212 TSubmitReturn,
213>
214 implements
215 ReactiveController,
216 LitFieldMethods<
217 TFormData,
218 never,
219 TFormData,
220 ToFormErrorTypes<TFormValidators, TSubmitReturn>
221 >,
222 LitSubscribeMethod<
223 FormState<TFormData, ToFormErrorTypes<TFormValidators, TSubmitReturn>>
224 >
225{
226 readonly #form: InternalFormApi<TFormData, TFormValidators, TSubmitReturn>
227 #unmount?: () => void
228β
229 get api(): FormApi<
230 TFormData,
231 ToFormErrorTypes<TFormValidators, TSubmitReturn>
232 > {
233 return this.#form
234 }
235β
236 /**
237 * @param host - The Lit host that owns the controller and form lifecycle.
238 * @param options - The initial form options. `defaultValues` drive form value
239 * inference.
240 */
241 constructor(
242 host: ReactiveControllerHost,
243 options: FormOptions<TFormData, TFormValidators, TSubmitReturn, unknown>,
244 ) {
245 this.#form = new InternalFormApi(options)
246 new TanStackStoreSelector(host, () => this.#form._atoms.resetVersion)
247 host.addController(this)
248 }
249β
250 hostConnected() {
251 this.#disconnect()
252 this.#unmount = this.#form.mount()
253 }
254β
255 hostDisconnected() {
256 this.#disconnect()
257 }
258β
259 #disconnect() {
260 this.#unmount?.()
261 this.#unmount = undefined
262 }
263β
264 /** Updates reactive form options without replacing the form instance. */
265 update(
266 options: FormOptions<TFormData, TFormValidators, TSubmitReturn, unknown>,
267 ) {
268 this.#form._update(options)
269 }
270β
271 field<
272 const TFieldName extends DeepKeys<TFormData>,
273 const TFieldValidators extends FieldValidators<
274 TFormData,
275 TFieldName,
276 DeepValue<TFormData, TFieldName>
277 >,
278 >(
279 options: LitFieldOptions<
280 TFormData,
281 TFieldName,
282 DeepValue<TFormData, TFieldName>,
283 TFieldValidators,
284 never,
285 TFormData,
286 ToFormErrorTypes<TFormValidators, TSubmitReturn>
287 >,
288 render: RenderCallback<
289 LitFieldRenderApi<
290 TFormData,
291 TFieldName,
292 DeepValue<TFormData, TFieldName>,
293 TFieldValidators,
294 never,
295 TFormData,
296 ToFormErrorTypes<TFormValidators, TSubmitReturn>
297 >
298 >,
299 ): unknown {
300 return fieldDirective(
301 this.#form,
302 options as unknown as AnyFieldApiOptions,
303 render,
304 false,
305 )
306 }
307β
308 arrayField<
309 const TFieldName extends DeepKeysWhereValueIncludes<TFormData, Array<any>>,
310 const TFieldValidators extends FieldValidators<
311 TFormData,
312 TFieldName,
313 DeepValue<TFormData, TFieldName>
314 >,
315 >(
316 options: LitFieldOptions<
317 TFormData,
318 TFieldName,
319 DeepValue<TFormData, TFieldName>,
320 TFieldValidators,
321 never,
322 TFormData,
323 ToFormErrorTypes<TFormValidators, TSubmitReturn>
324 >,
325 render: RenderCallback<
326 LitFieldRenderApi<
327 TFormData,
328 TFieldName,
329 DeepValue<TFormData, TFieldName>,
330 TFieldValidators,
331 never,
332 TFormData,
333 ToFormErrorTypes<TFormValidators, TSubmitReturn>
334 >
335 >,
336 ): unknown {
337 return fieldDirective(
338 this.#form,
339 options as unknown as AnyFieldApiOptions,
340 render,
341 true,
342 )
343 }
344β
345 subscribe<const TSelected>(
346 selector: (
347 state: FormState<
348 TFormData,
349 ToFormErrorTypes<TFormValidators, TSubmitReturn>
350 >,
351 ) => TSelected,
352 render: RenderCallback<NoInfer<TSelected>>,
353 when?: (selected: NoInfer<TSelected>) => boolean,
354 ): unknown {
355 return subscribeDirective(this.#form.atom, selector, render, when)
356 }
357β
358 formGroup<
359 const TGroupName extends DeepKeys<TFormData>,
360 TGroupValue extends DeepValue<TFormData, TGroupName>,
361 const TGroupValidators extends FormGroupValidators<TGroupValue>,
362 >(
363 options: Omit<
364 FormGroupOptions<
365 TFormData,
366 TGroupName,
367 TGroupValue,
368 TGroupValidators,
369 ToFormErrorTypes<TFormValidators, TSubmitReturn>
370 >,
371 'form'
372 >,
373 render: RenderCallback<
374 LitFormGroupApi<
375 TFormData,
376 TGroupName,
377 TGroupValue,
378 ToFormGroupErrorTypes<TGroupValidators>,
379 ToFormErrorTypes<TFormValidators, TSubmitReturn>
380 >
381 >,
382 ): unknown {
383 return formGroupDirective(this.#form, options, render)
384 }
385}
386β
387type AnyRender = (value: any) => unknown
388β
389class FieldDirective extends AsyncDirective {
390 #form?: AnyInternalFormApi
391 #options?: AnyFieldApiOptions
392 #renderCallback?: AnyRender
393 #isArrayField = false
394 #field?: AnyInternalFieldApi
395 #unregister?: () => void
396 #unsubscribe?: () => void
397 #selection?: readonly [any, any]
398β
399 constructor(partInfo: PartInfo) {
400 super(partInfo)
401 if (partInfo.type !== PartType.CHILD) {
402 throw new Error('The `field` directive must be used in a child part')
403 }
404 }
405β
406 update(
407 _part: Part,
408 [form, options, renderCallback, isArrayField]: Parameters<this['render']>,
409 ) {
410 this.#form = form
411 this.#options = options
412 this.#renderCallback = renderCallback
413 this.#isArrayField = isArrayField
414 if (this.isConnected) this.#connect()
415 return this.#renderValue()
416 }
417β
418 render(
419 form: AnyInternalFormApi,
420 options: AnyFieldApiOptions,
421 renderCallback: AnyRender,
422 isArrayField: boolean,
423 ) {
424 void form
425 void options
426 void renderCallback
427 void isArrayField
428 return nothing
429 }
430β
431 #connect() {
432 if (!this.#form || !this.#options || !this.#renderCallback) return
433β
434 const field = this.#form._getOrCreateFieldApi(this.#options)
435 if (field !== this.#field) {
436 this.#disconnect()
437 this.#field = field
438 } else {
439 const { name: _name, ...fieldOptions } = this.#options
440 field._update(fieldOptions)
441 }
442β
443 if (!this.#unregister) {
444 this.#unregister = field._register()
445 this.#selection = this.#select(field)
446 }
447 if (!this.#unsubscribe) {
448 this.#unsubscribe = field.atom.subscribe(() => {
449 const next = this.#select(field)
450 if (
451 this.#selection?.[0] === next[0] &&
452 this.#selection?.[1] === next[1]
453 ) {
454 return
455 }
456 this.#selection = next
457 this.setValue(this.#renderValue())
458 }).unsubscribe
459 }
460 }
461β
462 #select(field: AnyInternalFieldApi): readonly [any, any] {
463 if (this.#isArrayField) {
464 return [
465 field.value.length,
466 (field.meta as InternalBaseFieldMeta)._arrayVersion,
467 ]
468 }
469 return [field.value, field.meta]
470 }
471β
472 #renderValue() {
473 return this.#field && this.#renderCallback
474 ? this.#renderCallback(this.#field)
475 : nothing
476 }
477β
478 #disconnect() {
479 this.#unsubscribe?.()
480 this.#unsubscribe = undefined
481 this.#unregister?.()
482 this.#unregister = undefined
483 this.#selection = undefined
484 }
485β
486 protected disconnected() {
487 super.disconnected()
488 this.#disconnect()
489 }
490β
491 protected reconnected() {
492 super.reconnected()
493 this.#connect()
494 this.setValue(this.#renderValue())
495 }
496}
497β
498class SubscribeDirective extends AsyncDirective {
499 #source?: SelectionSource<any>
500 #selector?: (state: any) => any
501 #renderCallback?: AnyRender
502 #when?: (selected: any) => boolean
503 #selected?: any
504 #hasSelected = false
505 #unsubscribe?: () => void
506β
507 constructor(partInfo: PartInfo) {
508 super(partInfo)
509 if (partInfo.type !== PartType.CHILD) {
510 throw new Error('The `subscribe` directive must be used in a child part')
511 }
512 }
513β
514 update(
515 _part: Part,
516 [source, selector, renderCallback, when]: Parameters<this['render']>,
517 ) {
518 const sourceChanged = source !== this.#source
519 this.#source = source
520 this.#selector = selector
521 this.#renderCallback = renderCallback
522 this.#when = when
523 if (sourceChanged) this.#disconnect()
524 if (this.isConnected) this.#connect()
525 if (!sourceChanged) {
526 this.#selected = selector(source.get())
527 this.#hasSelected = true
528 }
529 return this.#renderValue()
530 }
531β
532 render(
533 source: SelectionSource<any>,
534 selector: (state: any) => any,
535 renderCallback: AnyRender,
536 when?: (selected: any) => boolean,
537 ) {
538 void source
539 void selector
540 void renderCallback
541 void when
542 return nothing
543 }
544β
545 #connect() {
546 if (
547 this.#unsubscribe ||
548 !this.#source ||
549 !this.#selector ||
550 !this.#renderCallback
551 ) {
552 return
553 }
554β
555 this.#selected = this.#selector(this.#source.get())
556 this.#hasSelected = true
557 this.#unsubscribe = this.#source.subscribe((state: any) => {
558 const next = this.#selector!(state)
559 if (this.#hasSelected && shallow(this.#selected, next)) return
560 this.#selected = next
561 this.#hasSelected = true
562 this.setValue(this.#renderValue())
563 }).unsubscribe
564 }
565β
566 #renderValue() {
567 if (!this.#hasSelected || !this.#renderCallback) return nothing
568 if (this.#when && !this.#when(this.#selected)) return nothing
569 return this.#renderCallback(this.#selected)
570 }
571β
572 #disconnect() {
573 this.#unsubscribe?.()
574 this.#unsubscribe = undefined
575 this.#hasSelected = false
576 this.#selected = undefined
577 }
578β
579 protected disconnected() {
580 super.disconnected()
581 this.#disconnect()
582 }
583β
584 protected reconnected() {
585 super.reconnected()
586 this.#connect()
587 this.setValue(this.#renderValue())
588 }
589}
590β
591type AnyInternalFormGroupApi = InternalFormGroupApi<any, any, any, any, any> &
592 LitFieldMethods<any, any, any, any> &
593 LitSubscribeMethod<any>
594β
595class FormGroupDirective extends AsyncDirective {
596 #form?: AnyInternalFormApi
597 #options?: Omit<FormGroupOptions<any, any, any, any, any>, 'form'>
598 #renderCallback?: AnyRender
599 #group?: AnyInternalFormGroupApi
600 #unsubscribe?: () => void
601 #mounted = false
602β
603 constructor(partInfo: PartInfo) {
604 super(partInfo)
605 if (partInfo.type !== PartType.CHILD) {
606 throw new Error('The `formGroup` directive must be used in a child part')
607 }
608 }
609β
610 update(
611 _part: Part,
612 [form, options, renderCallback]: Parameters<this['render']>,
613 ) {
614 this.#form = form
615 this.#options = options
616 this.#renderCallback = renderCallback
617 if (this.isConnected) this.#connect()
618 return this.#renderValue()
619 }
620β
621 render(
622 form: AnyInternalFormApi,
623 options: Omit<FormGroupOptions<any, any, any, any, any>, 'form'>,
624 renderCallback: AnyRender,
625 ) {
626 void form
627 void options
628 void renderCallback
629 return nothing
630 }
631β
632 #connect() {
633 if (!this.#form || !this.#options || !this.#renderCallback) return
634β
635 if (
636 !this.#group ||
637 this.#group.form !== this.#form ||
638 this.#group.name !== this.#options.name
639 ) {
640 this.#disconnect(true)
641 this.#group = attachGroupMethods(
642 new InternalFormGroupApi({
643 ...this.#options,
644 form: this.#form,
645 } as never),
646 this.#form,
647 )
648 } else {
649 this.#group.update({ ...this.#options, form: this.#form } as never)
650 }
651β
652 if (!this.#mounted) {
653 this.#group.mount()
654 this.#mounted = true
655 }
656 if (!this.#unsubscribe) {
657 this.#unsubscribe = this.#group.atom.subscribe(() => {
658 this.setValue(this.#renderValue())
659 }).unsubscribe
660 }
661 }
662β
663 #renderValue() {
664 return this.#group && this.#renderCallback
665 ? this.#renderCallback(this.#group)
666 : nothing
667 }
668β
669 #disconnect(destroy = false) {
670 this.#unsubscribe?.()
671 this.#unsubscribe = undefined
672 if (this.#mounted) this.#group?._cleanup()
673 this.#mounted = false
674 if (destroy) this.#group = undefined
675 }
676β
677 protected disconnected() {
678 super.disconnected()
679 this.#disconnect()
680 }
681β
682 protected reconnected() {
683 super.reconnected()
684 this.#connect()
685 this.setValue(this.#renderValue())
686 }
687}
688β
689function attachGroupMethods(
690 group: InternalFormGroupApi<any, any, any, any, any>,
691 form: AnyInternalFormApi,
692): AnyInternalFormGroupApi {
693 const result = group as AnyInternalFormGroupApi
694 result.field = (options, render) =>
695 fieldDirective(
696 form,
697 group._getFormFieldOptions(options, (base, overrides) => ({
698 ...base,
699 ...overrides,
700 })),
701 render,
702 false,
703 )
704 result.arrayField = (options, render) =>
705 fieldDirective(
706 form,
707 group._getFormFieldOptions(options, (base, overrides) => ({
708 ...base,
709 ...overrides,
710 })),
711 render,
712 true,
713 )
714 result.subscribe = (selector, render, when) =>
715 subscribeDirective(group.atom, selector, render, when)
716 return result
717}
718β
719const fieldDirective = directive(FieldDirective)
720const subscribeDirective = directive(SubscribeDirective)
721const formGroupDirective = directive(FormGroupDirective)