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

createFormHook.test-d.tsx

861 lines21.3 KB

1import { describe, expectTypeOf, it } from 'vitest'
2import { formOptions } from '@tanstack/form-core'
3import { createFormHook, createFormHookContexts } from '../src'
4​
5const { fieldContext, useFieldContext, formContext, useFormContext } =
6 createFormHookContexts()
7​
8function Test() {
9 return null
11​
12const { useAppForm, withForm, withFieldGroup } = createFormHook({
13 fieldComponents: {
14 Test,
15 },
16 formComponents: {
17 Test,
18 },
19 fieldContext,
20 formContext,
21})
22​
23describe('createFormHook', () => {
24 it('should not break with an infinite type on large schemas', () => {
25 const ActivityKind0_Names = ['Work', 'Rest', 'OnCall'] as const
26 type ActivityKind0 = (typeof ActivityKind0_Names)[number]
27​
28 enum DayOfWeek {
29 Monday = 1,
30 Tuesday,
31 Wednesday,
32 Thursday,
33 Friday,
34 Saturday,
35 Sunday,
36 }
37​
38 interface Branding<Brand> {
39 __type?: Brand
40 }
41 type Branded<T, Brand> = T & Branding<Brand>
42 type ActivityId = Branded<string, 'ActivityId'>
43 interface ActivitySelectorFormData {
44 includeAll: boolean
45 includeActivityIds: ActivityId[]
46 includeActivityKinds: Set<ActivityKind0>
47 excludeActivityIds: ActivityId[]
48 }
49​
50 const GeneratedTypes0Visibility_Names = [
51 'Normal',
52 'Advanced',
53 'Hidden',
54 ] as const
55 type GeneratedTypes0Visibility =
56 (typeof GeneratedTypes0Visibility_Names)[number]
57 interface FormValuesBase {
58 key: string
59 visibility: GeneratedTypes0Visibility
60 }
61​
62 interface ActivityCountFormValues extends FormValuesBase {
63 _type: 'ActivityCount'
64 activitySelector: ActivitySelectorFormData
65 daysOfWeek: DayOfWeek[]
66 label: string
67 }
68​
69 interface PlanningTimesFormValues extends FormValuesBase {
70 _type: 'PlanningTimes'
71 showTarget: boolean
72 showPlanned: boolean
73 showDiff: boolean
74 }
75​
76 type EditorValues = ActivityCountFormValues | PlanningTimesFormValues
77 interface EditorFormValues<EditorType extends EditorValues = EditorValues> {
78 editors: Record<string, EditorType>
79 ordering: string[]
80 }
81​
82 const ExampleUsage = withForm({
83 props: {
84 initialValues: '' as keyof EditorFormValues['editors'],
85 },
86 defaultValues: {} as EditorFormValues,
87 render: ({ form, initialValues }) => {
88 return (
89 <div className="m-3">
90 <form.AppField name={`editors.${initialValues}.key` as const}>
91 {(field) => {
92 expectTypeOf(field.state.value).toExtend<string>()
93 return null
94 }}
95 </form.AppField>
96 <form.AppForm>
97 <form.Test />
98 </form.AppForm>
99 </div>
100 )
101 },
102 })
103​
104 const ExampleUsage2 = withFieldGroup({
105 defaultValues: {} as EditorValues,
106 render: ({ group }) => {
107 const test = group.state.values.key
108 return (
109 <div className="m-3">
110 <group.AppField name="key">
111 {(field) => {
112 expectTypeOf(field.state.value).toExtend<string>()
113 return null
114 }}
115 </group.AppField>
116 <group.AppForm>
117 <group.Test />
118 </group.AppForm>
119 </div>
120 )
121 },
122 })
123 })
124​
125 it('types should be properly inferred when using formOptions', () => {
126 type Person = {
127 firstName: string
128 lastName: string
129 }
130​
131 const formOpts = formOptions({
132 defaultValues: {
133 firstName: 'FirstName',
134 lastName: 'LastName',
135 } as Person,
136 })
137​
138 const WithFormComponent = withForm({
139 ...formOpts,
140 render: ({ form }) => {
141 expectTypeOf(form.state.values).toEqualTypeOf<Person>()
142 return <form.Test />
143 },
144 })
145 })
146​
147 it('types should be properly inferred when passing args alongside formOptions', () => {
148 type Person = {
149 firstName: string
150 lastName: string
151 }
152​
153 const formOpts = formOptions({
154 defaultValues: {
155 firstName: 'FirstName',
156 lastName: 'LastName',
157 } as Person,
158 })
159​
160 const WithFormComponent = withForm({
161 ...formOpts,
162 onSubmitMeta: {
163 test: 'test',
164 },
165 render: ({ form }) => {
166 expectTypeOf(form.handleSubmit).toEqualTypeOf<{
167 (): Promise<void>
168 (submitMeta: { test: string }): Promise<void>
169 }>
170 return <form.Test />
171 },
172 })
173 })
174​
175 it('types should be properly inferred when formOptions are being overridden', () => {
176 type Person = {
177 firstName: string
178 lastName: string
179 }
180​
181 type PersonWithAge = Person & {
182 age: number
183 }
184​
185 const formOpts = formOptions({
186 defaultValues: {
187 firstName: 'FirstName',
188 lastName: 'LastName',
189 } as Person,
190 })
191​
192 const WithFormComponent = withForm({
193 ...formOpts,
194 defaultValues: {
195 firstName: 'FirstName',
196 lastName: 'LastName',
197 age: 10,
198 },
199 render: ({ form }) => {
200 expectTypeOf(form.state.values).toExtend<PersonWithAge>()
201 return <form.Test />
202 },
203 })
204 })
205​
206 it('withForm props should be properly inferred', () => {
207 const WithFormComponent = withForm({
208 props: {
209 prop1: 'test',
210 prop2: 10,
211 },
212 render: ({ form, ...props }) => {
213 expectTypeOf(props).toEqualTypeOf<{
214 prop1: string
215 prop2: number
216 children?: React.ReactNode
217 }>()
218​
219 return <form.Test />
220 },
221 })
222 })
223​
224 it('component made from withForm should have its props properly typed', () => {
225 const formOpts = formOptions({
226 defaultValues: {
227 firstName: 'FirstName',
228 lastName: 'LastName',
229 },
230 })
231​
232 const appForm = useAppForm(formOpts)
233​
234 const WithFormComponent = withForm({
235 ...formOpts,
236 props: {
237 prop1: 'test',
238 prop2: 10,
239 },
240 render: ({ form, children, ...props }) => {
241 expectTypeOf(props).toEqualTypeOf<{
242 prop1: string
243 prop2: number
244 }>()
245 return <form.Test />
246 },
247 })
248​
249 const CorrectComponent = (
250 <WithFormComponent form={appForm} prop1="test" prop2={10} />
251 )
252​
253 // @ts-expect-error Missing required props prop1 and prop2
254 const MissingPropsComponent = <WithFormComponent form={appForm} />
255​
256 const incorrectFormOpts = formOptions({
257 defaultValues: {
258 firstName: 'FirstName',
259 lastName: 'LastName',
260 firstNameWrong: 'FirstName',
261 lastNameWrong: 'LastName',
262 },
263 })
264​
265 const incorrectAppForm = useAppForm(incorrectFormOpts)
266​
267 const IncorrectFormOptsComponent = (
268 // @ts-expect-error Incorrect form opts
269 <WithFormComponent form={incorrectAppForm} prop1="test" prop2={10} />
270 )
271 })
272​
273 it('should infer subset values and props when calling withFieldGroup', () => {
274 type Person = {
275 firstName: string
276 lastName: string
277 }
278 type ComponentProps = {
279 prop1: string
280 prop2: number
281 }
282​
283 const defaultValues: Person = {
284 firstName: 'FirstName',
285 lastName: 'LastName',
286 }
287​
288 const FormGroupComponent = withFieldGroup({
289 defaultValues,
290 render: function Render({ group, children, ...props }) {
291 // Existing types may be inferred
292 expectTypeOf(group.state.values.firstName).toEqualTypeOf<string>()
293 expectTypeOf(group.state.values.lastName).toEqualTypeOf<string>()
294​
295 expectTypeOf(group.state.values).toEqualTypeOf<Person>()
296 expectTypeOf(children).toEqualTypeOf<React.ReactNode>()
297 expectTypeOf(props).toEqualTypeOf<{}>()
298 return <group.Test />
299 },
300 })
301​
302 const FormGroupComponentWithProps = withFieldGroup({
303 ...defaultValues,
304 props: {} as ComponentProps,
305 render: ({ group, children, ...props }) => {
306 expectTypeOf(props).toEqualTypeOf<{
307 prop1: string
308 prop2: number
309 }>()
310 return <group.Test />
311 },
312 })
313 })
314​
315 it('should allow spreading formOptions when calling withFieldGroup', () => {
316 type Person = {
317 firstName: string
318 lastName: string
319 }
320​
321 const defaultValues: Person = {
322 firstName: '',
323 lastName: '',
324 }
325 const formOpts = formOptions({
326 defaultValues,
327 validators: {
328 onChange: () => 'Error',
329 },
330 listeners: {
331 onBlur: () => 'Something',
332 },
333 asyncAlways: true,
334 asyncDebounceMs: 500,
335 })
336​
337 // validators and listeners are ignored, only defaultValues is acknowledged
338 const FormGroupComponent = withFieldGroup({
339 ...formOpts,
340 render: function Render({ group }) {
341 // Existing types may be inferred
342 expectTypeOf(group.state.values.firstName).toEqualTypeOf<string>()
343 expectTypeOf(group.state.values.lastName).toEqualTypeOf<string>()
344 return <group.Test />
345 },
346 })
347​
348 const noDefaultValuesFormOpts = formOptions({
349 onSubmitMeta: { foo: '' },
350 })
351​
352 const UnknownFormGroupComponent = withFieldGroup({
353 ...noDefaultValuesFormOpts,
354 render: function Render({ group }) {
355 // group.state.values can be anything.
356 // note that T extends unknown !== unknown extends T.
357 expectTypeOf<unknown>().toExtend<typeof group.state.values>()
358​
359 // either no submit meta or of the type in formOptions
360 expectTypeOf(group.handleSubmit).parameters.toEqualTypeOf<
361 [] | [{ foo: string }]
362 >()
363 return <group.Test />
364 },
365 })
366 })
367​
368 it('should allow passing compatible forms to withFieldGroup', () => {
369 type Person = {
370 firstName: string
371 lastName: string
372 }
373 type ComponentProps = {
374 prop1: string
375 prop2: number
376 }
377​
378 const defaultValues: Person = {
379 firstName: 'FirstName',
380 lastName: 'LastName',
381 }
382​
383 const FormGroup = withFieldGroup({
384 defaultValues,
385 props: {} as ComponentProps,
386 render: () => {
387 return <></>
388 },
389 })
390​
391 const equalAppForm = useAppForm({
392 defaultValues,
393 })
394​
395 // -----------------
396 // Assert that an equal form is not compatible as you have no name to pass
397 const NoSubfield = (
398 <FormGroup
399 form={equalAppForm}
400 // @ts-expect-error
401 fields=""
402 prop1="Test"
403 prop2={10}
404 />
405 )
406​
407 // -----------------
408 // Assert that a form extending Person in a property is allowed
409​
410 const extendedAppForm = useAppForm({
411 defaultValues: { person: { ...defaultValues, address: '' }, address: '' },
412 })
413 // While it has other properties, it satisfies defaultValues
414 const CorrectComponent1 = (
415 <FormGroup
416 form={extendedAppForm}
417 fields="person"
418 prop1="Test"
419 prop2={10}
420 />
421 )
422​
423 const MissingProps = (
424 // @ts-expect-error because prop1 and prop2 are not added
425 <FormGroup form={extendedAppForm} fields="person" />
426 )
427​
428 // -----------------
429 // Assert that a form not satisfying Person errors
430 const incompatibleAppForm = useAppForm({
431 defaultValues: { person: { ...defaultValues, lastName: 0 } },
432 })
433 const IncompatibleComponent = (
434 <FormGroup
435 // @ts-expect-error because the required subset of properties is not compatible.
436 form={incompatibleAppForm}
437 name=""
438 prop1="test"
439 prop2={10}
440 />
441 )
442 })
443​
444 it('should require strict equal submitMeta if it is set in withFieldGroup', () => {
445 type Person = {
446 firstName: string
447 lastName: string
448 }
449 type SubmitMeta = {
450 correct: string
451 }
452​
453 const defaultValues = {
454 person: { firstName: 'FirstName', lastName: 'LastName' } as Person,
455 }
456 const onSubmitMeta: SubmitMeta = {
457 correct: 'Prop',
458 }
459​
460 const FormLensNoMeta = withFieldGroup({
461 defaultValues: {} as Person,
462 render: function Render({ group }) {
463 // Since handleSubmit always allows to submit without meta, this is okay
464 group.handleSubmit()
465​
466 // To prevent unwanted meta behaviour, handleSubmit's meta should be never if not set.
467 expectTypeOf(group.handleSubmit).parameters.toEqualTypeOf<
468 [] | [submitMeta: never]
469 >()
470​
471 return <group.Test />
472 },
473 })
474​
475 const FormGroupWithMeta = withFieldGroup({
476 defaultValues: {} as Person,
477 onSubmitMeta,
478 render: function Render({ group }) {
479 // Since handleSubmit always allows to submit without meta, this is okay
480 group.handleSubmit()
481​
482 // This matches the value
483 group.handleSubmit({ correct: '' })
484​
485 // This does not.
486 // @ts-expect-error
487 group.handleSubmit({ wrong: 'Meta' })
488​
489 return <group.Test />
490 },
491 })
492​
493 const noMetaForm = useAppForm({
494 defaultValues,
495 })
496​
497 const CorrectComponent1 = (
498 <FormLensNoMeta form={noMetaForm} fields="person" />
499 )
500​
501 const WrongComponent1 = (
502 <FormGroupWithMeta
503 // @ts-expect-error because the meta is not existent
504 form={noMetaForm}
505 fields="person"
506 />
507 )
508​
509 const metaForm = useAppForm({
510 defaultValues,
511 onSubmitMeta,
512 })
513​
514 const CorrectComponent2 = <FormLensNoMeta form={metaForm} fields="person" />
515 const CorrectComponent3 = (
516 <FormGroupWithMeta form={metaForm} fields="person" />
517 )
518​
519 const diffMetaForm = useAppForm({
520 defaultValues,
521 onSubmitMeta: { ...onSubmitMeta, something: 'else' },
522 })
523​
524 const CorrectComponent4 = (
525 <FormLensNoMeta form={diffMetaForm} fields="person" />
526 )
527 const WrongComponent2 = (
528 <FormGroupWithMeta
529 // @ts-expect-error because the metas do not align.
530 form={diffMetaForm}
531 fields="person"
532 />
533 )
534 })
535​
536 it('should accept any validators for withFieldGroup', () => {
537 type Person = {
538 firstName: string
539 lastName: string
540 }
541​
542 const defaultValues = {
543 person: { firstName: 'FirstName', lastName: 'LastName' } satisfies Person,
544 }
545​
546 const formA = useAppForm({
547 defaultValues,
548 validators: {
549 onChange: () => 'A',
550 },
551 listeners: {
552 onChange: () => 'A',
553 },
554 })
555 const formB = useAppForm({
556 defaultValues,
557 validators: {
558 onChange: () => 'B',
559 },
560 listeners: {
561 onChange: () => 'B',
562 },
563 })
564​
565 const FormGroup = withFieldGroup({
566 defaultValues: defaultValues.person,
567 render: function Render({ group }) {
568 return <group.Test />
569 },
570 })
571​
572 const CorrectComponent1 = <FormGroup form={formA} fields="person" />
573 const CorrectComponent2 = <FormGroup form={formB} fields="person" />
574 })
575​
576 it('should allow nesting withFieldGroup in other withFieldGroups', () => {
577 type Nested = {
578 firstName: string
579 }
580 type Wrapper = {
581 field: Nested
582 }
583 type FormValues = {
584 form: Wrapper
585 unrelated: { something: { lastName: string } }
586 }
587​
588 const defaultValues: FormValues = {
589 form: {
590 field: {
591 firstName: 'Test',
592 },
593 },
594 unrelated: {
595 something: {
596 lastName: '',
597 },
598 },
599 }
600​
601 const form = useAppForm({
602 defaultValues,
603 })
604 const LensNested = withFieldGroup({
605 defaultValues: defaultValues.form.field,
606 render: function Render() {
607 return <></>
608 },
609 })
610 const LensWrapper = withFieldGroup({
611 defaultValues: defaultValues.form,
612 render: function Render({ group }) {
613 return (
614 <div>
615 <LensNested form={group} fields="field" />
616 </div>
617 )
618 },
619 })
620​
621 const Component = <LensWrapper form={form} fields="form" />
622 })
623​
624 it('should not allow withFieldGroups with different metas to be nested', () => {
625 type Nested = {
626 firstName: string
627 }
628 type Wrapper = {
629 field: Nested
630 }
631 type FormValues = {
632 form: Wrapper
633 unrelated: { something: { lastName: string } }
634 }
635​
636 const defaultValues: FormValues = {
637 form: {
638 field: {
639 firstName: 'Test',
640 },
641 },
642 unrelated: {
643 something: {
644 lastName: '',
645 },
646 },
647 }
648​
649 const LensNestedNoMeta = withFieldGroup({
650 defaultValues: defaultValues.form.field,
651 render: function Render() {
652 return <></>
653 },
654 })
655 const LensNestedWithMeta = withFieldGroup({
656 defaultValues: defaultValues.form.field,
657 onSubmitMeta: { meta: '' },
658 render: function Render() {
659 return <></>
660 },
661 })
662 const LensWrapper = withFieldGroup({
663 defaultValues: defaultValues.form,
664 render: function Render({ group }) {
665 return (
666 <div>
667 <LensNestedNoMeta form={group} fields="field" />
668 <LensNestedWithMeta
669 // @ts-expect-error Wrong meta!
670 form={group}
671 fields="field"
672 />
673 </div>
674 )
675 },
676 })
677​
678 it('should allow mapping withFieldGroup to different fields', () => {
679 const defaultValues = {
680 firstName: '',
681 lastName: '',
682 age: 0,
683 relatives: [{ firstName: '', lastName: '', age: 0 }],
684 }
685 const defaultFields = {
686 first: '',
687 last: '',
688 }
689​
690 const form = useAppForm({
691 defaultValues,
692 })
693​
694 const FieldGroup = withFieldGroup({
695 defaultValues: defaultFields,
696 render: function Render() {
697 return <></>
698 },
699 })
700​
701 const Component1 = (
702 <FieldGroup
703 form={form}
704 fields={{
705 first: 'lastName',
706 last: 'firstName',
707 }}
708 />
709 )
710​
711 const Component2 = (
712 <FieldGroup
713 form={form}
714 fields={{
715 first: 'relatives[0].lastName',
716 last: 'relatives[0].firstName',
717 }}
718 />
719 )
720 })
721​
722 it('should not allow fields mapping if the top level is an array', () => {
723 const defaultValues = {
724 firstName: '',
725 lastName: '',
726 age: 0,
727 relatives: [{ firstName: '', lastName: '', age: 0 }],
728 relativesRecord: {
729 something: { firstName: '', lastName: '', age: 0 },
730 } as Record<string, { firstName: string; lastName: string }>,
731 }
732 const defaultFields = {
733 firstName: '',
734 lastName: '',
735 }
736​
737 const form = useAppForm({
738 defaultValues,
739 })
740​
741 const FieldGroupRecord = withFieldGroup({
742 defaultValues: { anything: defaultFields } as Record<
743 string,
744 typeof defaultFields
745 >,
746 render: function Render() {
747 return <></>
748 },
749 })
750 const FieldGroupArray = withFieldGroup({
751 defaultValues: [defaultFields],
752 render: function Render() {
753 return <></>
754 },
755 })
756​
757 const CorrectComponent1 = (
758 <FieldGroupRecord form={form} fields="relativesRecord" />
759 )
760 const WrongComponent1 = (
761 <FieldGroupRecord
762 form={form}
763 // @ts-expect-error because record is non-indexable
764 fields={{
765 'any field goes': 'relatives[0]',
766 }}
767 />
768 )
769 const CorrectComponent3 = (
770 <FieldGroupArray form={form} fields="relatives" />
771 )
772 const WrongComponent2 = (
773 <FieldGroupArray
774 form={form}
775 // @ts-expect-error because arrays are non-indexable
776 fields={{}}
777 />
778 )
779 })
780 })
781​
782 it('should allow mapping field groups to optional fields', () => {
783 const groupFields = {
784 name: '',
785 }
786​
787 type WrapperValues = {
788 namespace: { name: string } | undefined
789 namespace2: { name: string } | null
790 namespace3: { name: string } | null | undefined
791 nope: null | undefined
792 nope2: { lastName: string } | null | undefined
793 }
794​
795 const defaultValues: WrapperValues = {
796 namespace: undefined,
797 namespace2: null,
798 namespace3: null,
799 nope: null,
800 nope2: null,
801 }
802​
803 const FieldGroup = withFieldGroup({
804 defaultValues: groupFields,
805 render: function Render() {
806 return <></>
807 },
808 })
809​
810 const form = useAppForm({
811 defaultValues,
812 })
813​
814 const Component = <FieldGroup form={form} fields="namespace" />
815 const Component2 = <FieldGroup form={form} fields="namespace2" />
816 const Component3 = <FieldGroup form={form} fields="namespace3" />
817 // @ts-expect-error because it doesn't ever evaluate to the expected values
818 const Component4 = <FieldGroup form={form} fields="nope" />
819 // @ts-expect-error because the types don't match properly
820 const Component5 = <FieldGroup form={form} fields="nope2" />
821 })
822​
823 it('should allow interfaces without index signatures to be assigned to `props` in withForm', () => {
824 interface TestNoSignature {
825 title: string
826 }
827​
828 interface TestWithSignature {
829 title: string
830 [key: string]: unknown
831 }
832​
833 const WithFormComponent1 = withForm({
834 defaultValues: { name: '' },
835 props: {} as TestNoSignature,
836 render: () => <></>,
837 })
838​
839 const WithFormComponent2 = withForm({
840 defaultValues: { name: '' },
841 props: {} as TestWithSignature,
842 render: () => <></>,
843 })
844​
845 const appForm = useAppForm({ defaultValues: { name: '' } })
846​
847 const Component1 = <WithFormComponent1 title="" form={appForm} />
848 const Component2 = (
849 <WithFormComponent2 title="" something="else" form={appForm} />
850 )
851 })
852​
853 it('should not allow null as prop in withForm', () => {
854 const WithFormComponent = withForm({
855 defaultValues: { name: '' },
856 // @ts-expect-error
857 props: null,
858 render: () => <></>,
859 })
860 })
861})