forms-sdk 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,801 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ <img src="assets/icon.svg" width="64" height="64" alt="">
2
+
3
+ # forms-sdk
4
+
5
+ Headless, fully accessible form primitives built on top of [react-hook-form](https://react-hook-form.com/) for React 19.
6
+
7
+ ---
8
+
9
+ ## Table of Contents
10
+
11
+ - [Overview](#overview)
12
+ - [Key Features](#key-features)
13
+ - [Installation](#installation)
14
+ - [Mental Model & Architecture](#mental-model--architecture)
15
+ - [Component API Reference](#component-api-reference)
16
+ - [`<Form>` / `<FormRoot>`](#form--formroot)
17
+ - [`<Form.Title>`](#formtitle)
18
+ - [`<Form.Description>`](#formdescription)
19
+ - [`<Form.Item>`](#formitem)
20
+ - [`<Form.Group>`](#formgroup)
21
+ - [`<Form.Legend>`](#formlegend)
22
+ - [`<Form.Label>`](#formlabel)
23
+ - [`<Form.Hint>`](#formhint)
24
+ - [`<Form.Field>`](#formfield)
25
+ - [`<Form.Error>`](#formerror)
26
+ - [`<Form.Submit>`](#formsubmit)
27
+ - [`<Form.Reset>`](#formreset)
28
+ - [Type-Safe Forms with `createForm`](#type-safe-forms-with-createform)
29
+ - [Hooks](#hooks)
30
+ - [`useHeadlessForm()`](#useheadlessform)
31
+ - [Advanced Patterns](#advanced-patterns)
32
+ - [Schema Validation (Zod)](#schema-validation-zod)
33
+ - [Data Transformations (`format` & `parse`)](#data-transformations-format--parse)
34
+ - [Custom UI Components (Radix UI / shadcn)](#custom-ui-components-radix-ui--shadcn)
35
+ - [Slot Merging (`asChild`)](#slot-merging-aschild)
36
+ - [Full Implementation Example](#full-implementation-example)
37
+ - [Development & Testing](#development--testing)
38
+
39
+ ---
40
+
41
+ ## Overview
42
+
43
+ Building accessible forms with `react-hook-form` normally requires manual boilerplate: linking `htmlFor` with unique `id`s, joining `aria-describedby` for helper text and validation errors, toggling `aria-invalid`, handling `aria-required`, and synchronizing React 19 ref cleanups.
44
+
45
+ `forms-sdk` handles this wiring automatically through an internal reactive **Field Registry**, while leaving complete control over UI styling, layout, and markup to you.
46
+
47
+ ---
48
+
49
+ ## Key Features
50
+
51
+ - **100% Headless**: No opinions on styling. Drop in Tailwind, CSS Modules, or custom design system components.
52
+ - **Automatic Accessibility (a11y)**:
53
+ - Dynamically links `id` and `htmlFor` between controls and labels.
54
+ - Generates and synchronizes `aria-describedby` across multiple `<Form.Hint>`s and active `<Form.Error>` messages.
55
+ - Zero dangling IDs: if an error message is not rendered or a hint unmounts, its ID is automatically removed from `aria-describedby`.
56
+ - Links `<Form.Title>` and `<Form.Description>` to `<form>` via `aria-labelledby` and `aria-describedby`.
57
+ - Sets `aria-invalid` on failed fields and `aria-required` where appropriate (excluding group options where it violates WAI-ARIA).
58
+ - **React 19 Native**:
59
+ - Leverages `React.use()` for context resolution.
60
+ - Uses `<Context value={...}>` provider syntax.
61
+ - Properly merges React 19 callback refs with cleanup functions.
62
+ - **Smart Native Input Handling**:
63
+ - Native checkboxes: extracts boolean `checked`.
64
+ - Grouped checkboxes: binds to array values, toggling elements automatically.
65
+ - Radio inputs: binds to individual options, preserving primitive types (numbers stay numbers).
66
+ - Number & range inputs: reads `valueAsNumber` (or `null` when empty).
67
+ - Multi-selects (`<select multiple>`): extracts array of selected option values.
68
+ - File inputs: extracts `FileList`.
69
+ - **Compile-Time Type Safety**: Use `createForm<T>()` to validate field names, hints, labels, errors, and groups against your schema.
70
+ - **Server Components & Next.js Ready**: Preserves `"use client"` directives for dual ESM and CJS bundles.
71
+
72
+ ---
73
+
74
+ ## Installation
75
+
76
+ ```bash
77
+ npm install forms-sdk react-hook-form
78
+ # or
79
+ pnpm add forms-sdk react-hook-form
80
+ # or
81
+ yarn add forms-sdk react-hook-form
82
+ ```
83
+
84
+ ### Peer Dependencies
85
+ - `react`: `>= 19.0.0`
86
+ - `react-dom`: `>= 19.0.0`
87
+ - `react-hook-form`: `>= 7.50.0`
88
+
89
+ ---
90
+
91
+ ## Mental Model & Architecture
92
+
93
+ ```
94
+ <Form> <-- Form context & RHF FormProvider
95
+ <Form.Title /> <-- Form title (wired to form aria-labelledby)
96
+ <Form.Description /> <-- Form subtitle (wired to form aria-describedby)
97
+
98
+ <Form.Item name="email"> <-- Provides `name` context to nested items
99
+ <Form.Label /> <-- htmlFor pointing to control ID
100
+ <Form.Field required> <-- Injects id, name, onChange, onBlur, ref,
101
+ <input type="email" /> aria-invalid, aria-required, aria-describedby
102
+ </Form.Field>
103
+ <Form.Hint /> <-- Registered ID automatically added to aria-describedby
104
+ <Form.Error /> <-- Registered ID added to aria-describedby only when visible
105
+ </Form.Item>
106
+
107
+ <Form.Group name="roles"> <-- <fieldset> for radio/checkbox groups
108
+ <Form.Legend /> <-- <legend>
109
+ <Form.Field><input type="checkbox" value="admin" /></Form.Field>
110
+ <Form.Label value="admin" /> <-- Points specifically to option ID
111
+ </Form.Group>
112
+
113
+ <Form.Submit /> <-- Auto-disables during submit, sets aria-busy
114
+ <Form.Reset /> <-- Resets form state
115
+ </Form>
116
+ ```
117
+
118
+ ---
119
+
120
+ ## Component API Reference
121
+
122
+ ### `<Form>` / `<FormRoot>`
123
+
124
+ The root form container. Wraps children in react-hook-form's `FormProvider` and an internal headless `FormContext`. Renders a `<form noValidate>`.
125
+
126
+ #### Props
127
+
128
+ | Prop | Type | Default | Description |
129
+ |---|---|---|---|
130
+ | `onSubmit` | `SubmitHandler<TFieldValues>` | **Required** | Called with valid form data on submission. |
131
+ | `onInvalid` | `SubmitErrorHandler<TFieldValues>` | `undefined` | Optional callback called when validation fails. |
132
+ | `form` | `UseFormReturn<TFieldValues>` | `undefined` | External `useForm` instance. When supplied, `formOptions` is ignored. |
133
+ | `formOptions` | `UseFormProps<TFieldValues>` | `undefined` | Options passed to internal `useForm` instance when `form` is not provided. |
134
+ | `aria-labelledby` | `string` | Auto | Overrides the automatic link to `<Form.Title>`. |
135
+ | `aria-describedby` | `string` | Auto | Overrides the automatic link to `<Form.Description>`. |
136
+ | `...formProps` | `React.ComponentProps<"form">` | - | All standard HTML `<form>` attributes (except `onSubmit` and `onInvalid`). |
137
+
138
+ ```tsx
139
+ // Mode 1: Internal form state
140
+ <Form<MyForm>
141
+ formOptions={{ defaultValues: { name: "" } }}
142
+ onSubmit={(data) => console.log(data)}
143
+ >
144
+ ...
145
+ </Form>
146
+
147
+ // Mode 2: External form state
148
+ const form = useForm<MyForm>({ defaultValues: { name: "" } })
149
+ <Form form={form} onSubmit={(data) => console.log(data)}>
150
+ ...
151
+ </Form>
152
+ ```
153
+
154
+ ---
155
+
156
+ ### `<Form.Title>`
157
+
158
+ Renders an `<h2>` heading for the form. Automatically registers its ID with the root `<form>`'s `aria-labelledby`.
159
+
160
+ ```tsx
161
+ <Form.Title className="text-xl font-bold">Account Settings</Form.Title>
162
+ ```
163
+
164
+ ---
165
+
166
+ ### `<Form.Description>`
167
+
168
+ Renders a `<p>` description for the form. Automatically registers its ID with the root `<form>`'s `aria-describedby`.
169
+
170
+ ```tsx
171
+ <Form.Description className="text-sm text-gray-500">
172
+ Update your personal preferences and contact information.
173
+ </Form.Description>
174
+ ```
175
+
176
+ ---
177
+
178
+ ### `<Form.Item>`
179
+
180
+ A logical container that provides the field `name` to all child components via React Context. Renders no DOM element (`React.Fragment`).
181
+
182
+ #### Props
183
+
184
+ | Prop | Type | Description |
185
+ |---|---|---|
186
+ | `name` | `FieldPath<TFieldValues>` | The path to the field in your form values. |
187
+ | `children` | `React.ReactNode` | Children that can now omit the `name` prop. |
188
+
189
+ ```tsx
190
+ <Form.Item name="username">
191
+ <Form.Label>Username</Form.Label>
192
+ <Form.Field required>
193
+ <input type="text" />
194
+ </Form.Field>
195
+ <Form.Hint>Choose a unique handle.</Form.Hint>
196
+ <Form.Error />
197
+ </Form.Item>
198
+ ```
199
+
200
+ ---
201
+
202
+ ### `<Form.Group>`
203
+
204
+ Renders a `<fieldset>` for radio buttons or grouped checkboxes. Like `<Form.Item>`, it scopes child components to `name`. It also automatically links the group's `<Form.Hint>`s and `<Form.Error>` via `aria-describedby` on the `<fieldset>`.
205
+
206
+ #### Props
207
+
208
+ | Prop | Type | Description |
209
+ |---|---|---|
210
+ | `name` | `FieldPath<TFieldValues>` | The form field name for the group. |
211
+ | `...fieldsetProps` | `React.ComponentProps<"fieldset">` | Standard `<fieldset>` props. |
212
+
213
+ ```tsx
214
+ <Form.Group name="hobbies">
215
+ <Form.Legend>Select your hobbies</Form.Legend>
216
+ {/* Checkboxes bound to array */}
217
+ <Form.Field><input type="checkbox" value="reading" /></Form.Field>
218
+ <Form.Label value="reading">Reading</Form.Label>
219
+ <Form.Error />
220
+ </Form.Group>
221
+ ```
222
+
223
+ ---
224
+
225
+ ### `<Form.Legend>`
226
+
227
+ Renders a standard `<legend>` element inside `<Form.Group>`.
228
+
229
+ ---
230
+
231
+ ### `<Form.Label>`
232
+
233
+ Renders a `<label>` element. Automatically sets `htmlFor` to match the control's `id`.
234
+
235
+ #### Props
236
+
237
+ | Prop | Type | Description |
238
+ |---|---|---|
239
+ | `name` | `string` | Optional if inside `<Form.Item>` or `<Form.Group>`. |
240
+ | `value` | `unknown` | Targets a specific option within a radio or checkbox group. |
241
+ | `htmlFor` | `string` | Manual override for the `for` attribute. |
242
+
243
+ ```tsx
244
+ // Standard label: points to field control
245
+ <Form.Label>Email</Form.Label>
246
+
247
+ // Option label: points specifically to the option with value "yearly"
248
+ <Form.Label value="yearly">Yearly ($99/yr)</Form.Label>
249
+ ```
250
+
251
+ ---
252
+
253
+ ### `<Form.Hint>`
254
+
255
+ Renders a `<p>` helper text for a field. Dynamically registers its ID so it is included in the control's `aria-describedby`.
256
+
257
+ - Supports multiple hints per field (all IDs are joined with spaces in `aria-describedby`).
258
+ - When unmounted, its ID is cleaned up from the registry automatically.
259
+
260
+ #### Props
261
+
262
+ | Prop | Type | Description |
263
+ |---|---|---|
264
+ | `name` | `string` | Optional if inside `<Form.Item>` or `<Form.Group>`. |
265
+ | `id` | `string` | Optional custom ID (auto-generated if omitted). |
266
+
267
+ ```tsx
268
+ <Form.Hint>Password must be at least 8 characters long.</Form.Hint>
269
+ <Form.Hint>Include at least one uppercase letter and number.</Form.Hint>
270
+ ```
271
+
272
+ ---
273
+
274
+ ### `<Form.Field>`
275
+
276
+ Connects an input element to `react-hook-form` via `useController`.
277
+
278
+ #### Props
279
+
280
+ | Prop | Type | Description |
281
+ |---|---|---|
282
+ | `name` | `FieldPath<TFieldValues>` | Field path. Optional inside `<Form.Item>` / `<Form.Group>`. |
283
+ | `required` | `boolean \| string` | Adds validation rule (`required: "..."` or `true`) and `aria-required`. |
284
+ | `rules` | `RegisterOptions` | Standard `react-hook-form` validation rules (`pattern`, `validate`, `min`, `max`, etc.). |
285
+ | `format` | `(value) => unknown` | Formats store value before passing to control (e.g. date formatting). |
286
+ | `parse` | `(value) => unknown` | Transforms control value before saving into store (e.g. uppercase). |
287
+ | `override` | `(props) => Record<string, unknown>` | Merges custom props onto child element. |
288
+ | `children` | `ReactElement \| ((props: FormFieldRenderProps) => ReactNode)` | Single native element or a render prop function. |
289
+
290
+ #### Render Prop Callback
291
+
292
+ When `children` is a function, it receives `FormFieldRenderProps`:
293
+
294
+ ```tsx
295
+ <Form.Field name="customField">
296
+ {({ field, fieldState, ariaProps, isRequired, errorId, fieldId }) => (
297
+ <MyCustomInput
298
+ name={field.name}
299
+ value={field.value}
300
+ onChange={field.onChange}
301
+ onBlur={field.onBlur}
302
+ ref={field.ref}
303
+ {...ariaProps}
304
+ />
305
+ )}
306
+ </Form.Field>
307
+ ```
308
+
309
+ `ariaProps` contains:
310
+ - `id`: unique field ID
311
+ - `aria-describedby`: joined string of hint and error IDs (or `undefined`)
312
+ - `aria-invalid`: `true` if field has errors (or `undefined`)
313
+ - `aria-required`: `true` if required (or `undefined`)
314
+
315
+ ---
316
+
317
+ ### `<Form.Error>`
318
+
319
+ Renders a `<p role="alert">` validation error message.
320
+
321
+ - **Zero-Dangling Accessibility**: Only registers its ID in `aria-describedby` when an error is actively visible.
322
+ - Renders `null` when there is no error.
323
+
324
+ #### Props
325
+
326
+ | Prop | Type | Description |
327
+ |---|---|---|
328
+ | `name` | `string` | Optional inside `<Form.Item>` / `<Form.Group>`. |
329
+ | `id` | `string` | Optional custom ID (auto-generated if omitted). |
330
+ | `children` | `ReactNode \| ((error: FieldError) => ReactNode)` | Custom error content or render function. Defaults to `error.message`. |
331
+
332
+ ```tsx
333
+ // Default: renders error.message
334
+ <Form.Error className="text-red-600 text-sm" />
335
+
336
+ // Custom render function:
337
+ <Form.Error>
338
+ {(error) => <span className="error-badge">⚠️ {error.message}</span>}
339
+ </Form.Error>
340
+ ```
341
+
342
+ ---
343
+
344
+ ### `<Form.Submit>`
345
+
346
+ Renders a submit button (`<button type="submit">`).
347
+
348
+ #### Props
349
+
350
+ | Prop | Type | Default | Description |
351
+ |---|---|---|---|
352
+ | `disableWhileSubmitting` | `boolean` | `true` | Automatically disables button when `formState.isSubmitting` is true. |
353
+ | `pending` | `boolean` | `false` | Additional pending state (e.g. from an external server action or mutation). |
354
+ | `asChild` | `boolean` | `false` | Merges props onto a single child element (Slot pattern). |
355
+ | `children` | `ReactNode \| ((props) => ReactNode)` | - | Button content or render function receiving `{ disabled, form, isPending, isSubmitting }`. |
356
+
357
+ ```tsx
358
+ // Standard submit button with auto-pending
359
+ <Form.Submit pending={isMutating}>Save Changes</Form.Submit>
360
+
361
+ // Render function for loading spinner
362
+ <Form.Submit>
363
+ {({ isPending }) => (isPending ? <Spinner /> : "Submit")}
364
+ </Form.Submit>
365
+
366
+ // asChild with custom button component
367
+ <Form.Submit asChild>
368
+ <Button variant="primary">Submit</Button>
369
+ </Form.Submit>
370
+ ```
371
+
372
+ ---
373
+
374
+ ### `<Form.Reset>`
375
+
376
+ Renders a reset button (`<button type="button">`). Clicking triggers `form.reset()`.
377
+
378
+ #### Props
379
+
380
+ | Prop | Type | Default | Description |
381
+ |---|---|---|---|
382
+ | `asChild` | `boolean` | `false` | Merges props onto child element. |
383
+ | `onClick` | `(event) => void` | `undefined` | Custom handler. Calling `event.preventDefault()` cancels the reset. |
384
+ | `children` | `ReactNode \| ((props) => ReactNode)` | - | Button content or render function receiving `{ form, isDirty, isSubmitting }`. |
385
+
386
+ ```tsx
387
+ <Form.Reset>Reset to defaults</Form.Reset>
388
+
389
+ // Conditionally disable if form is not dirty
390
+ <Form.Reset>
391
+ {({ isDirty }) => <button disabled={!isDirty}>Reset Form</button>}
392
+ </Form.Reset>
393
+ ```
394
+
395
+ ---
396
+
397
+ ## Type-Safe Forms with `createForm`
398
+
399
+ For full compile-time autocomplete and validation of all field names, use `createForm<TFieldValues>()`:
400
+
401
+ ```tsx
402
+ import { createForm } from "forms-sdk"
403
+
404
+ type UserProfile = {
405
+ account: {
406
+ username: string
407
+ email: string
408
+ }
409
+ notifications: boolean
410
+ }
411
+
412
+ const ProfileForm = createForm<UserProfile>()
413
+
414
+ export function UserForm() {
415
+ return (
416
+ <ProfileForm onSubmit={(data) => console.log(data)}>
417
+ {/* Autocomplete for "account.username", "account.email", "notifications" */}
418
+ <ProfileForm.Item name="account.email">
419
+ <ProfileForm.Label>Email</ProfileForm.Label>
420
+ <ProfileForm.Field required="Email is required">
421
+ <input type="email" />
422
+ </ProfileForm.Field>
423
+ <ProfileForm.Error />
424
+ </ProfileForm.Item>
425
+
426
+ <ProfileForm.Submit>Save</ProfileForm.Submit>
427
+ </ProfileForm>
428
+ )
429
+ }
430
+ ```
431
+
432
+ ---
433
+
434
+ ## Hooks
435
+
436
+ ### `useHeadlessForm()`
437
+
438
+ Access the active form's metadata and registry:
439
+
440
+ ```tsx
441
+ import { useHeadlessForm } from "forms-sdk"
442
+
443
+ function CustomFormStatus() {
444
+ const { id, titleId, descriptionId, registry } = useHeadlessForm()
445
+ return <span>Form ID: {id}</span>
446
+ }
447
+ ```
448
+
449
+ ---
450
+
451
+ ## Advanced Patterns
452
+
453
+ ### Schema Validation (Zod)
454
+
455
+ Pair `forms-sdk` seamlessly with Zod via `@hookform/resolvers/zod`:
456
+
457
+ ```tsx
458
+ import { useForm } from "react-hook-form"
459
+ import { zodResolver } from "@hookform/resolvers/zod"
460
+ import { z } from "zod"
461
+ import { Form } from "forms-sdk"
462
+
463
+ const schema = z.object({
464
+ email: z.string().email("Invalid email address"),
465
+ age: z.number().min(18, "Must be at least 18"),
466
+ })
467
+
468
+ type FormData = z.infer<typeof schema>
469
+
470
+ export function ZodForm() {
471
+ const form = useForm<FormData>({
472
+ resolver: zodResolver(schema),
473
+ })
474
+
475
+ return (
476
+ <Form form={form} onSubmit={(data) => console.log(data)}>
477
+ <Form.Item name="email">
478
+ <Form.Label>Email</Form.Label>
479
+ <Form.Field><input type="email" /></Form.Field>
480
+ <Form.Error />
481
+ </Form.Item>
482
+
483
+ <Form.Item name="age">
484
+ <Form.Label>Age</Form.Label>
485
+ <Form.Field><input type="number" /></Form.Field>
486
+ <Form.Error />
487
+ </Form.Item>
488
+
489
+ <Form.Submit>Submit</Form.Submit>
490
+ </Form>
491
+ )
492
+ }
493
+ ```
494
+
495
+ ---
496
+
497
+ ### Data Transformations (`format` & `parse`)
498
+
499
+ Use `format` to transform stored data into input values, and `parse` to transform input values before saving:
500
+
501
+ ```tsx
502
+ <Form.Item name="code">
503
+ <Form.Label>Redemption Code</Form.Label>
504
+ <Form.Field
505
+ format={(val) => (val ? String(val).toUpperCase() : "")}
506
+ parse={(val) => String(val || "").toUpperCase().trim()}
507
+ >
508
+ <input type="text" placeholder="ABC-123" />
509
+ </Form.Field>
510
+ </Form.Item>
511
+ ```
512
+
513
+ ---
514
+
515
+ ### Custom UI Components (Radix UI / shadcn)
516
+
517
+ Pass `ariaProps` to your custom UI components:
518
+
519
+ ```tsx
520
+ <Form.Item name="theme">
521
+ <Form.Label>Theme Preference</Form.Label>
522
+ <Form.Field name="theme">
523
+ {({ field, ariaProps }) => (
524
+ <Select value={field.value} onValueChange={field.onChange} {...ariaProps}>
525
+ <SelectTrigger>
526
+ <SelectValue placeholder="Select a theme" />
527
+ </SelectTrigger>
528
+ <SelectContent>
529
+ <SelectItem value="light">Light</SelectItem>
530
+ <SelectItem value="dark">Dark</SelectItem>
531
+ <SelectItem value="system">System</SelectItem>
532
+ </SelectContent>
533
+ </Select>
534
+ )}
535
+ </Form.Field>
536
+ <Form.Error />
537
+ </Form.Item>
538
+ ```
539
+
540
+ ---
541
+
542
+ ### Slot Merging (`asChild`)
543
+
544
+ `<Form.Submit>` and `<Form.Reset>` support `asChild`. Props are merged intelligently:
545
+ - `onClick`: Child handler runs first. If `event.preventDefault()` is called on `<Form.Reset>`, the reset is aborted.
546
+ - `className`: Space-separated joined.
547
+ - `style`: Object merged.
548
+ - `ref`: React 19 cleanup-compatible ref merging.
549
+
550
+ ```tsx
551
+ <Form.Submit asChild>
552
+ <MyDesignSystemButton size="lg" variant="gradient">
553
+ Submit
554
+ </MyDesignSystemButton>
555
+ </Form.Submit>
556
+ ```
557
+
558
+ ---
559
+
560
+ ## Full Implementation Example
561
+
562
+ Here is a complete, real-world example covering text inputs, numbers, multi-select, radio groups, multi-checkboxes, file uploads, custom components, and submit states:
563
+
564
+ ```tsx
565
+ import * as React from "react"
566
+ import { useForm } from "react-hook-form"
567
+ import { createForm, type FormFieldRenderProps } from "forms-sdk"
568
+
569
+ export type UserRegistrationValues = {
570
+ fullName: string
571
+ email: string
572
+ couponCode: string
573
+ age: number | null
574
+ bio: string
575
+ country: string
576
+ skills: string[]
577
+ plan: "free" | "pro" | "enterprise"
578
+ notifications: string[]
579
+ agreeToTerms: boolean
580
+ avatar: FileList | null
581
+ rating: number
582
+ }
583
+
584
+ const RegistrationForm = createForm<UserRegistrationValues>()
585
+
586
+ function StarRating({
587
+ value,
588
+ onChange,
589
+ ariaProps,
590
+ }: {
591
+ value: number
592
+ onChange: (val: number) => void
593
+ ariaProps: FormFieldRenderProps<UserRegistrationValues, "rating">["ariaProps"]
594
+ }) {
595
+ return (
596
+ <div role="radiogroup" aria-label="Rating" {...ariaProps} style={{ display: "flex", gap: "6px" }}>
597
+ {[1, 2, 3, 4, 5].map((star) => (
598
+ <button
599
+ key={star}
600
+ type="button"
601
+ role="radio"
602
+ aria-checked={value === star}
603
+ onClick={() => onChange(star)}
604
+ >
605
+ {star} ★
606
+ </button>
607
+ ))}
608
+ </div>
609
+ )
610
+ }
611
+
612
+ export function ComprehensiveRegistrationForm() {
613
+ const form = useForm<UserRegistrationValues>({
614
+ defaultValues: {
615
+ fullName: "",
616
+ email: "",
617
+ couponCode: "",
618
+ age: null,
619
+ bio: "",
620
+ country: "",
621
+ skills: ["typescript"],
622
+ plan: "pro",
623
+ notifications: ["email"],
624
+ agreeToTerms: false,
625
+ avatar: null,
626
+ rating: 5,
627
+ },
628
+ mode: "onTouched",
629
+ })
630
+
631
+ const [saving, setSaving] = React.useState(false)
632
+
633
+ const handleSubmit = async (data: UserRegistrationValues) => {
634
+ setSaving(true)
635
+ try {
636
+ await new Promise((r) => setTimeout(r, 1000))
637
+ console.log("Submitted successfully:", data)
638
+ } finally {
639
+ setSaving(false)
640
+ }
641
+ }
642
+
643
+ return (
644
+ <RegistrationForm
645
+ form={form}
646
+ onSubmit={handleSubmit}
647
+ onInvalid={(errors) => console.warn(errors)}
648
+ >
649
+ <header>
650
+ <RegistrationForm.Title>Create Your Account</RegistrationForm.Title>
651
+ <RegistrationForm.Description>
652
+ Fill in your details below to set up your profile.
653
+ </RegistrationForm.Description>
654
+ </header>
655
+
656
+ {/* Text Input with validation */}
657
+ <RegistrationForm.Item name="fullName">
658
+ <RegistrationForm.Label>Full Name</RegistrationForm.Label>
659
+ <RegistrationForm.Field
660
+ required="Full name is required"
661
+ rules={{ minLength: { value: 2, message: "Min 2 characters" } }}
662
+ >
663
+ <input type="text" placeholder="Jane Doe" />
664
+ </RegistrationForm.Field>
665
+ <RegistrationForm.Hint>Legal name as shown on your passport.</RegistrationForm.Hint>
666
+ <RegistrationForm.Error />
667
+ </RegistrationForm.Item>
668
+
669
+ {/* Email Input */}
670
+ <RegistrationForm.Item name="email">
671
+ <RegistrationForm.Label>Email</RegistrationForm.Label>
672
+ <RegistrationForm.Field
673
+ required="Email is required"
674
+ rules={{
675
+ pattern: {
676
+ value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
677
+ message: "Invalid email address",
678
+ },
679
+ }}
680
+ >
681
+ <input type="email" placeholder="jane@example.com" />
682
+ </RegistrationForm.Field>
683
+ <RegistrationForm.Error />
684
+ </RegistrationForm.Item>
685
+
686
+ {/* Number Input (auto converts to number or null) */}
687
+ <RegistrationForm.Item name="age">
688
+ <RegistrationForm.Label>Age</RegistrationForm.Label>
689
+ <RegistrationForm.Field
690
+ required="Age is required"
691
+ rules={{ min: { value: 18, message: "Must be at least 18" } }}
692
+ >
693
+ <input type="number" min={1} max={120} />
694
+ </RegistrationForm.Field>
695
+ <RegistrationForm.Error />
696
+ </RegistrationForm.Item>
697
+
698
+ {/* Select Single */}
699
+ <RegistrationForm.Item name="country">
700
+ <RegistrationForm.Label>Country</RegistrationForm.Label>
701
+ <RegistrationForm.Field required="Select your country">
702
+ <select>
703
+ <option value="">-- Choose Country --</option>
704
+ <option value="AU">Australia</option>
705
+ <option value="US">United States</option>
706
+ </select>
707
+ </RegistrationForm.Field>
708
+ <RegistrationForm.Error />
709
+ </RegistrationForm.Item>
710
+
711
+ {/* Multiple Select */}
712
+ <RegistrationForm.Item name="skills">
713
+ <RegistrationForm.Label>Skills</RegistrationForm.Label>
714
+ <RegistrationForm.Field>
715
+ <select multiple size={3}>
716
+ <option value="typescript">TypeScript</option>
717
+ <option value="react">React</option>
718
+ <option value="node">Node.js</option>
719
+ </select>
720
+ </RegistrationForm.Field>
721
+ </RegistrationForm.Item>
722
+
723
+ {/* Radio Group */}
724
+ <RegistrationForm.Group name="plan">
725
+ <RegistrationForm.Legend>Plan</RegistrationForm.Legend>
726
+ <RegistrationForm.Field><input type="radio" value="free" /></RegistrationForm.Field>
727
+ <RegistrationForm.Label value="free">Free</RegistrationForm.Label>
728
+
729
+ <RegistrationForm.Field><input type="radio" value="pro" /></RegistrationForm.Field>
730
+ <RegistrationForm.Label value="pro">Pro</RegistrationForm.Label>
731
+
732
+ <RegistrationForm.Error />
733
+ </RegistrationForm.Group>
734
+
735
+ {/* Multi-Checkbox Group */}
736
+ <RegistrationForm.Group name="notifications">
737
+ <RegistrationForm.Legend>Notifications</RegistrationForm.Legend>
738
+ <RegistrationForm.Field><input type="checkbox" value="email" /></RegistrationForm.Field>
739
+ <RegistrationForm.Label value="email">Email</RegistrationForm.Label>
740
+
741
+ <RegistrationForm.Field><input type="checkbox" value="sms" /></RegistrationForm.Field>
742
+ <RegistrationForm.Label value="sms">SMS</RegistrationForm.Label>
743
+
744
+ <RegistrationForm.Error />
745
+ </RegistrationForm.Group>
746
+
747
+ {/* Custom Component Integration */}
748
+ <RegistrationForm.Item name="rating">
749
+ <RegistrationForm.Label>Rating</RegistrationForm.Label>
750
+ <RegistrationForm.Field name="rating">
751
+ {({ field, ariaProps }) => (
752
+ <StarRating
753
+ value={field.value}
754
+ onChange={field.onChange}
755
+ ariaProps={ariaProps}
756
+ />
757
+ )}
758
+ </RegistrationForm.Field>
759
+ </RegistrationForm.Item>
760
+
761
+ {/* Single Checkbox */}
762
+ <RegistrationForm.Item name="agreeToTerms">
763
+ <RegistrationForm.Field required="Must agree to terms">
764
+ <input type="checkbox" />
765
+ </RegistrationForm.Field>
766
+ <RegistrationForm.Label>I accept the terms</RegistrationForm.Label>
767
+ <RegistrationForm.Error />
768
+ </RegistrationForm.Item>
769
+
770
+ {/* Actions */}
771
+ <div style={{ display: "flex", gap: "10px" }}>
772
+ <RegistrationForm.Submit pending={saving}>
773
+ {({ isPending }) => (isPending ? "Submitting..." : "Submit Registration")}
774
+ </RegistrationForm.Submit>
775
+ <RegistrationForm.Reset>Reset</RegistrationForm.Reset>
776
+ </div>
777
+ </RegistrationForm>
778
+ )
779
+ }
780
+ ```
781
+
782
+ ---
783
+
784
+ ## Development & Testing
785
+
786
+ ```bash
787
+ # Type-check TypeScript files
788
+ pnpm run typecheck
789
+
790
+ # Run unit test suite
791
+ pnpm test
792
+
793
+ # Build production bundle (ESM + CJS + DTS)
794
+ pnpm run build
795
+ ```
796
+
797
+ ---
798
+
799
+ ## License
800
+
801
+ MIT © [Linus Kang](mailto:linus@kang.id.au)