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

FormGroup.test-d.tsx

425 lines11.3 KB

1import React from 'react'
2import { expectTypeOf } from 'vitest'
3import { z } from 'zod'
4import { useForm } from '../src'
5import type {
6 DeepKeys,
7 FieldApi,
8 FormErrorTypes,
9 FormGroupApi,
10 StandardSchemaV1Issue,
11 ValidationIssue,
12} from '../src'
13​
14type FieldErrorOf<TField> =
15 TField extends FieldApi<any, any, infer TFieldError, any, any>
16 ? TFieldError
17 : never
18​
19type FormGroupErrorTypesOf<TGroup> =
20 TGroup extends FormGroupApi<any, any, any, infer TGroupErrorTypes, any>
21 ? TGroupErrorTypes
22 : never
23​
24function FormGroupTypes() {
25 const form = useForm({
26 defaultValues: {
27 guestDetails: {
28 name: '',
29 emails: [''],
30 },
31 budget: 0,
32 },
33 validators: [
34 {
35 triggers: [],
36 run: () => ({
37 form: { message: '', fromForm: true as const },
38 fields: {},
39 }),
40 },
41 ],
42 onSubmit: () => 'submitted' as const,
43 })
44​
45 return (
46 <form.FormGroup
47 name="guestDetails"
48 validators={[
49 {
50 triggers: [],
51 run: ({ value }) => {
52 value.name
53 value.emails
54 // @ts-expect-error group validators receive the group value, not the root form value
55 value.budget
56 const invalidFields = {
57 // @ts-expect-error group validator field paths are relative to the group value
58 budget: { message: '' },
59 } satisfies Partial<
60 Record<DeepKeys<typeof value>, { message: string }>
61 >
62 void invalidFields
63 return {
64 fields: {
65 name: { message: '', fromGroup: true as const },
66 },
67 }
68 },
69 },
70 ]}
71 >
72 {(group) => {
73 expectTypeOf(group.atom.get().values.name).toEqualTypeOf<string>()
74 group.state.values.name
75 expectTypeOf(group.state.isTouched).toEqualTypeOf<boolean>()
76 expectTypeOf(group.state.isDirty).toEqualTypeOf<boolean>()
77 expectTypeOf(group.state.isPristine).toEqualTypeOf<boolean>()
78 expectTypeOf(group.form.state.values.budget).toEqualTypeOf<number>()
79 expectTypeOf<FormGroupErrorTypesOf<typeof group>>().toEqualTypeOf<
80 FormErrorTypes<never, { message: string; fromGroup: true }>
81 >()
82 // @ts-expect-error group state values are scoped to guestDetails
83 group.state.values.budget
84 // @ts-expect-error isDefaultValue is exposed on form state and field meta, not group state
85 group.state.isDefaultValue
86​
87 return (
88 <>
89 <group.Field name="name">
90 {(field) => {
91 expectTypeOf(field.atom.get().value).toEqualTypeOf<string>()
92 expectTypeOf(
93 field.form.state.values.budget,
94 ).toEqualTypeOf<number>()
95 expectTypeOf(field.errors).toEqualTypeOf<
96 Array<GroupValidationError>
97 >()
98 expectTypeOf<
99 FieldErrorOf<typeof field>
100 >().toEqualTypeOf<GroupValidationError>()
101 // @ts-expect-error public field APIs expose atom, not store
102 field.store
103 return null
104 }}
105 </group.Field>
106 <group.Field
107 name="name"
108 listeners={[
109 {
110 triggers: [],
111 run: ({ fieldApi }) => {
112 expectTypeOf(fieldApi.errors).toEqualTypeOf<
113 Array<GroupValidationError>
114 >()
115 },
116 },
117 ]}
118 >
119 {() => null}
120 </group.Field>
121 <group.ArrayField name="emails">{() => null}</group.ArrayField>
122​
123 {/* @ts-expect-error field names are scoped to the group value */}
124 <group.Field name="budget">{() => null}</group.Field>
125​
126 {/* @ts-expect-error ArrayField only accepts array-valued group paths */}
127 <group.ArrayField name="name">{() => null}</group.ArrayField>
128 </>
129 )
130 }}
131 </form.FormGroup>
132 )
134​
135type GuestDetails = {
136 name: string
137 emails: Array<string>
139​
140type GroupValidationError = {
141 message: string
142 fromGroup: true
144​
145const guestDetailsSchema = z
146 .object({
147 name: z.string(),
148 emails: z.array(z.string()),
149 })
150 .transform(({ name }) => ({ nameLength: name.length }))
151​
152function FormGroupSubmitTypes() {
153 const form = useForm({
154 defaultValues: {
155 guestDetails: {
156 name: '',
157 emails: [''],
158 },
159 },
160 })
161​
162 return (
163 <form.FormGroup
164 name="guestDetails"
165 validators={[
166 { run: guestDetailsSchema, triggers: [] },
167 {
168 run: guestDetailsSchema,
169 runOnSubmit: false,
170 triggers: [],
171 },
172 ]}
173 onSubmit={({ schemaOutputs, groupApi }) => {
174 expectTypeOf(schemaOutputs['length']).toEqualTypeOf<2>()
175 expectTypeOf(schemaOutputs[0]).toEqualTypeOf<{
176 nameLength: number
177 }>()
178 expectTypeOf(schemaOutputs[1]).toEqualTypeOf<undefined>()
179 expectTypeOf<FormGroupErrorTypesOf<typeof groupApi>>().toEqualTypeOf<
180 FormErrorTypes<StandardSchemaV1Issue, StandardSchemaV1Issue>
181 >()
182 }}
183 onSubmitInvalid={(context) => {
184 expectTypeOf<keyof typeof context>().toEqualTypeOf<
185 'value' | 'formApi' | 'groupApi'
186 >()
187 expectTypeOf(context.value).toEqualTypeOf<GuestDetails>()
188 expectTypeOf<
189 FormGroupErrorTypesOf<typeof context.groupApi>
190 >().toEqualTypeOf<
191 FormErrorTypes<StandardSchemaV1Issue, StandardSchemaV1Issue>
192 >()
193 }}
194 >
195 {(group) => {
196 void group.validate('submit')
197 return null
198 }}
199 </form.FormGroup>
200 )
202​
203function FormGroupSubscribeTypes() {
204 const form = useForm({
205 defaultValues: {
206 guestDetails: {
207 name: '',
208 emails: [''],
209 },
210 budget: 0,
211 },
212 })
213​
214 return (
215 <form.FormGroup
216 name="guestDetails"
217 validators={[
218 {
219 triggers: [],
220 run: () => ({
221 form: {
222 message: '',
223 fromGroup: true as const,
224 },
225 fields: {},
226 }),
227 },
228 ]}
229 >
230 {(group) => (
231 <>
232 <group.Subscribe
233 selector={(state) => {
234 expectTypeOf(state.values).toEqualTypeOf<GuestDetails>()
235 // @ts-expect-error selector values are scoped to guestDetails
236 state.values.budget
237 return state.values
238 }}
239 >
240 {(values) => {
241 expectTypeOf(values).toEqualTypeOf<GuestDetails>()
242 return null
243 }}
244 </group.Subscribe>
245​
246 <group.Subscribe
247 selector={(state) => {
248 expectTypeOf(state.errors).not.toBeNever()
249 expectTypeOf(state.errors).toEqualTypeOf<
250 Array<GroupValidationError>
251 >()
252 return state.errors
253 }}
254 when={(errors) => {
255 expectTypeOf(errors).toEqualTypeOf<Array<GroupValidationError>>()
256 return errors.length > 0
257 }}
258 >
259 {(errors) => {
260 expectTypeOf(errors).toEqualTypeOf<Array<GroupValidationError>>()
261 return null
262 }}
263 </group.Subscribe>
264​
265 <group.Subscribe selector={(state) => state.meta}>
266 {(meta) => {
267 expectTypeOf(meta).toBeUnknown()
268 return null
269 }}
270 </group.Subscribe>
271​
272 <group.Subscribe
273 selector={(state) => {
274 expectTypeOf(state.isTouched).toEqualTypeOf<boolean>()
275 expectTypeOf(state.isDirty).toEqualTypeOf<boolean>()
276 expectTypeOf(state.isPristine).toEqualTypeOf<boolean>()
277 expectTypeOf(state.isValid).toEqualTypeOf<boolean>()
278 expectTypeOf(state.isInvalid).toEqualTypeOf<boolean>()
279 expectTypeOf(state.canSubmit).toEqualTypeOf<boolean>()
280 expectTypeOf(state.isSubmitting).toEqualTypeOf<boolean>()
281 expectTypeOf(state.isSubmitSuccessful).toEqualTypeOf<boolean>()
282 expectTypeOf(state.isValidating).toEqualTypeOf<boolean>()
283 expectTypeOf(state.submissionAttempts).toEqualTypeOf<number>()
284​
285 return {
286 isSubmitting: state.isSubmitting,
287 submissionAttempts: state.submissionAttempts,
288 }
289 }}
290 >
291 {(status) => {
292 expectTypeOf(status.isSubmitting).toEqualTypeOf<boolean>()
293 expectTypeOf(status.submissionAttempts).toEqualTypeOf<number>()
294 return null
295 }}
296 </group.Subscribe>
297 </>
298 )}
299 </form.FormGroup>
300 )
302​
303function FormGroupSubscribeWithoutGroupErrorsTypes() {
304 const form = useForm({
305 defaultValues: {
306 guestDetails: {
307 name: '',
308 },
309 },
310 })
311​
312 return (
313 <form.FormGroup
314 name="guestDetails"
315 validators={[
316 {
317 triggers: [],
318 run: () => ({
319 fields: {
320 name: { message: '' },
321 },
322 }),
323 },
324 ]}
325 >
326 {(group) => (
327 <group.Subscribe
328 selector={(state) => {
329 expectTypeOf(state.errors).not.toBeNever()
330 expectTypeOf(state.errors).toEqualTypeOf<Array<never>>()
331 return state.errors
332 }}
333 >
334 {(errors) => {
335 expectTypeOf(errors).toEqualTypeOf<Array<never>>()
336 return null
337 }}
338 </group.Subscribe>
339 )}
340 </form.FormGroup>
341 )
343​
344function FormGroupWithoutValidatorsTypes() {
345 const form = useForm({
346 defaultValues: {
347 guestDetails: {
348 name: '',
349 },
350 },
351 validators: [],
352 })
353​
354 return (
355 <form.FormGroup name="guestDetails">
356 {(group) => {
357 expectTypeOf<FormGroupErrorTypesOf<typeof group>>().toEqualTypeOf<
358 FormErrorTypes<never, never>
359 >()
360 expectTypeOf(group.state.errors).toEqualTypeOf<Array<never>>()
361 return null
362 }}
363 </form.FormGroup>
364 )
366​
367function RootFieldTypes() {
368 const form = useForm({
369 defaultValues: {
370 guestDetails: {
371 name: '',
372 },
373 },
374 })
375​
376 expectTypeOf(form.atom.get().values.guestDetails.name).toEqualTypeOf<string>()
377 // @ts-expect-error public form APIs expose atom, not store
378 form.store
379​
380 return (
381 <form.Field
382 name="guestDetails.name"
383 listeners={[
384 {
385 triggers: [],
386 run: ({ fieldApi }) => {
387 expectTypeOf(fieldApi.errors).toEqualTypeOf<
388 Array<ValidationIssue>
389 >()
390 },
391 },
392 ]}
393 >
394 {(field) => {
395 expectTypeOf(field.errors).toEqualTypeOf<Array<ValidationIssue>>()
396 return null
397 }}
398 </form.Field>
399 )
401​
402function RootSubscribeTypes() {
403 const form = useForm({
404 defaultValues: { name: '' },
405 })
406​
407 return (
408 <form.Subscribe
409 selector={(state) => [state.values.name, state.submissionAttempts]}
410 >
411 {(selected) => {
412 expectTypeOf(selected).toEqualTypeOf<readonly [string, number]>()
413 return null
414 }}
415 </form.Subscribe>
416 )
418​
419void FormGroupTypes
420void FormGroupSubmitTypes
421void FormGroupSubscribeTypes
422void FormGroupSubscribeWithoutGroupErrorsTypes
423void FormGroupWithoutValidatorsTypes
424void RootFieldTypes
425void RootSubscribeTypes