-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllms.txt
More file actions
1341 lines (1145 loc) · 38.2 KB
/
llms.txt
File metadata and controls
1341 lines (1145 loc) · 38.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# LambdaCurry Forms - Complete Implementation Guide for LLMs
This comprehensive guide covers everything needed to implement forms using the `@lambdacurry/forms` remix-hook-form components, including the new FormError component for form-level error handling. This documentation is specifically designed for LLMs to understand all features, patterns, and best practices.
## Core Architecture Overview
The library provides **form-aware wrapper components** in the `remix-hook-form` directory that automatically integrate with React Router forms and Remix Hook Form context. These components eliminate boilerplate while maintaining full customization capabilities.
### Key Principle: Zero Boilerplate Form Integration
- Components automatically access form context via `useRemixFormContext()`
- No need to manually pass `control` props
- Automatic error handling and validation display
- Built-in accessibility features
## Form-Level Error Handling with FormError
The `FormError` component provides standardized form-level error handling, complementing the existing field-level error system.
### FormError Component Usage
```typescript
// Import form-aware FormError component
import { FormError } from '@lambdacurry/forms';
// Basic usage - looks for errors._form by default
<FormError />
// Custom error key
<FormError name="general" />
// With custom styling and placement
<FormError className="mb-4 p-3 bg-red-50 border border-red-200 rounded" />
// With custom component override
<FormError
components={{
FormMessage: CustomErrorMessage,
}}
/>
```
### Server Action Pattern for Form-Level Errors
```typescript
export const action = async ({ request }: ActionFunctionArgs) => {
const { data, errors } = await getValidatedFormData<FormData>(
request,
zodResolver(formSchema)
);
// Return field-level validation errors
if (errors) {
return { errors };
}
// Business logic validation
try {
await processForm(data);
return { message: 'Success!' };
} catch (error) {
// Return form-level error using _form key
return {
errors: {
_form: { message: 'Unable to process form. Please try again.' }
}
};
}
};
```
### Error Hierarchy Guidelines
**Field-Level Errors (use FormMessage automatically in form components):**
- Validation errors: "Email is required", "Password too short"
- Format errors: "Invalid email format"
- Field-specific business rules: "Username already taken"
**Form-Level Errors (use FormError component):**
- Server errors: "Server temporarily unavailable"
- Authentication failures: "Invalid credentials"
- Network issues: "Connection timeout"
- General business logic: "Account suspended"
- Rate limiting: "Too many attempts, try again later"
## Basic Form Setup Pattern
## Import Structure
The `@lambdacurry/forms` library follows a clear import structure:
### Form-Aware Components (from `@lambdacurry/forms`)
These components automatically integrate with React Router forms and Remix Hook Form context:
- `TextField` - Form-aware text input with automatic validation
- `Textarea` - Form-aware textarea with automatic validation
- `Checkbox` - Form-aware checkbox with automatic validation
- `Switch` - Form-aware switch/toggle with automatic validation
- `RadioGroup` - Form-aware radio group with automatic validation
- `RadioGroupItem` - Individual radio items for RadioGroup
- `DatePicker` - Form-aware date picker with automatic validation
- `DropdownMenuSelect` - Form-aware dropdown select with automatic validation
- `OtpInput` - Form-aware OTP/PIN input with automatic validation
- `FormError` - Component for displaying form-level errors
- `FormLabel`, `FormControl`, `FormDescription`, `FormMessage` - Form field components
- `useFormField` - Hook for accessing form field context
- Data table components: `DataTableRouterForm`, `DataTableRouterToolbar`, etc.
### UI Components (from `@lambdacurry/forms/ui`)
These are the underlying UI components without form integration:
- `Button` - Button component with variants
- `Calendar` - Calendar component for date selection
- `Badge` - Badge/chip component for labels
- `Dialog` - Modal dialog component
- `Popover` - Popover/tooltip component
- `Select` - Basic select dropdown
- `Separator` - Visual separator/divider
- `Slider` - Range slider component
- `Table` - Table components for data display
- `Tabs` - Tab navigation component
- `Command` - Command palette/search component
- Field variants: `CheckboxField`, `TextareaField`, `TextField`, `SwitchField`, etc.
- And many more UI primitives
## Component Reference
### Complete List of Form-Aware Components (`@lambdacurry/forms`)
```typescript
// Form input components (automatically integrate with form context)
import {
TextField, // Text input with validation
Textarea, // Multi-line text input with validation
Checkbox, // Checkbox with validation
Switch, // Toggle switch with validation
RadioGroup, // Radio button group with validation
RadioGroupItem, // Individual radio button
DatePicker, // Date selection with validation
DropdownMenuSelect, // Dropdown select with validation
OtpInput, // OTP/PIN input with validation
// Form structure components
FormError, // Form-level error display
FormLabel, // Form field labels
FormControl, // Form field wrapper
FormDescription, // Form field descriptions
FormMessage, // Form field error messages
useFormField, // Hook for form field context
// Data table components
DataTableRouterForm,
DataTableRouterToolbar,
useDataTableUrlState,
} from '@lambdacurry/forms';
```
### Complete List of UI Components (`@lambdacurry/forms/ui`)
```typescript
// Basic UI components (no form integration)
import {
// Buttons and actions
Button, // Button with variants
// Form inputs (non-form-aware versions)
CheckboxField, // Checkbox without form integration
TextareaField, // Textarea without form integration
TextField, // Text input without form integration
SwitchField, // Switch without form integration
RadioGroupField, // Radio group without form integration
DatePickerField, // Date picker without form integration
DropdownMenuSelectField, // Dropdown without form integration
OtpInputField, // OTP input without form integration
FormErrorField, // Error display without form integration
// Layout and navigation
Dialog, // Modal dialogs
Popover, // Popover/tooltips
Tabs, // Tab navigation
Separator, // Visual dividers
// Data display
Table, // Table components
Badge, // Labels and badges
Calendar, // Calendar component
// Form primitives
Label, // Basic labels
Select, // Basic select dropdown
Slider, // Range slider
Command, // Command palette
// Data table system
DataTable, // Data table components
DataTableFilter, // Table filtering
// Utilities
DebouncedInput, // Debounced input
} from '@lambdacurry/forms/ui';
```
### 1. Required Imports
```typescript
import { zodResolver } from '@hookform/resolvers/zod';
import { RemixFormProvider, useRemixForm, getValidatedFormData } from 'remix-hook-form';
import { z } from 'zod';
import { useFetcher, type ActionFunctionArgs } from 'react-router';
// Import form-aware components from main package
import { TextField, Checkbox, FormError } from '@lambdacurry/forms';
// Import UI components from /ui subpath
import { Button } from '@lambdacurry/forms/ui';
```
### 2. Zod Schema Definition
```typescript
const formSchema = z.object({
username: z.string().min(3, 'Username must be at least 3 characters'),
email: z.string().email('Invalid email address'),
terms: z.boolean().refine(val => val === true, 'You must accept the terms'),
age: z.coerce.number().min(18, 'Must be at least 18 years old'),
});
type FormData = z.infer<typeof formSchema>;
```
### 3. Complete Login Form Example with FormError
```typescript
const LoginForm = () => {
const fetcher = useFetcher<{
message?: string;
errors?: Record<string, { message: string }>
}>();
const methods = useRemixForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
email: '',
password: '',
},
fetcher,
submitConfig: {
action: '/login',
method: 'post',
},
});
const isSubmitting = fetcher.state === 'submitting';
return (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={methods.handleSubmit} className="max-w-md mx-auto p-6 space-y-4">
<h2 className="text-xl font-semibold text-gray-900">Sign In</h2>
<TextField
name="email"
type="email"
label="Email Address"
placeholder="Enter your email"
disabled={isSubmitting}
/>
<TextField
name="password"
type="password"
label="Password"
placeholder="Enter your password"
disabled={isSubmitting}
/>
<FormError className="mb-4" />
<Button type="submit" disabled={isSubmitting} className="w-full">
{isSubmitting ? 'Signing In...' : 'Sign In'}
</Button>
{fetcher.data?.message && (
<div className="mt-4 p-4 bg-green-50 border border-green-200 rounded-md">
<p className="text-green-700 font-medium">{fetcher.data.message}</p>
</div>
)}
</fetcher.Form>
</RemixFormProvider>
);
};
```
### 4. General Form Component Setup
```typescript
const MyFormComponent = () => {
const fetcher = useFetcher<{ message: string; errors?: Record<string, { message: string }> }>();
const methods = useRemixForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
username: '',
email: '',
terms: false,
age: undefined,
},
fetcher,
submitConfig: {
action: '/',
method: 'post',
},
});
return (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={methods.handleSubmit}>
<TextField name="username" label="Username" />
<TextField name="email" label="Email Address" />
<TextField name="age" type="number" label="Age" />
<Checkbox name="terms" label="Accept Terms and Conditions" />
<Button type="submit">Submit</Button>
{fetcher.data?.message && <p>{fetcher.data.message}</p>}
</fetcher.Form>
</RemixFormProvider>
);
};
```
### 5. Server Action Handler with FormError Support
```typescript
export const action = async ({ request }: ActionFunctionArgs) => {
const { data, errors } = await getValidatedFormData<FormData>(
request,
zodResolver(formSchema)
);
if (errors) {
return { errors };
}
// Business logic validation
try {
const user = await authenticateUser(data.email, data.password);
return { message: 'Login successful!', redirectTo: '/dashboard' };
} catch (error) {
// Return form-level error using _form key
return {
errors: {
_form: { message: 'Invalid credentials. Please try again.' }
}
};
}
};
```
## Available Form Components
### TextField Component
```typescript
<TextField
name="fieldName" // Required: field name for form registration
label="Field Label" // Optional: display label
description="Help text" // Optional: description text
placeholder="Enter text" // Optional: placeholder text
type="text" // Optional: input type (text, email, password, number, etc.)
prefix="$" // Optional: prefix content (e.g., currency symbol)
suffix="USD" // Optional: suffix content (e.g., units)
className="custom-class" // Optional: additional CSS classes
components={{ // Optional: custom component overrides
Input: CustomInput,
FormLabel: CustomLabel,
FormMessage: CustomMessage,
}}
/>
```
### Textarea Component
```typescript
<Textarea
name="message"
label="Your Message"
description="Enter your detailed message"
placeholder="Type your message here..."
rows={5} // Optional: number of visible rows
className="custom-class"
components={{
TextArea: CustomTextarea,
FormLabel: CustomLabel,
}}
/>
```
### Checkbox Component
```typescript
<Checkbox
name="terms"
label="Accept Terms and Conditions"
description="You must accept our terms to continue"
className="custom-class"
components={{
FormLabel: CustomLabel,
FormMessage: CustomMessage,
}}
/>
```
### Switch Component
```typescript
<Switch
name="notifications"
label="Enable Notifications"
description="Receive email notifications"
className="custom-class"
/>
```
### RadioGroup Component
Two usage patterns available:
#### Pattern 1: Using options prop
```typescript
const sizeOptions = [
{ value: 'xs', label: 'Extra Small' },
{ value: 'sm', label: 'Small' },
{ value: 'md', label: 'Medium' },
{ value: 'lg', label: 'Large' },
];
<RadioGroup
name="size"
label="Select Size"
description="Choose your preferred size"
options={sizeOptions}
labelClassName="font-semibold" // Optional: custom label styling
itemClassName="p-2 rounded" // Optional: custom item styling
/>
```
#### Pattern 2: Using RadioGroupItem children
```typescript
<RadioGroup
name="design"
label="Design Style"
description="Choose your design preference"
>
<div className="grid grid-cols-3 gap-4">
<RadioGroupItem
value="modern"
label="Modern"
wrapperClassName="bg-blue-50 p-3 rounded-lg"
labelClassName="text-blue-800 font-bold"
/>
<RadioGroupItem
value="classic"
label="Classic"
wrapperClassName="bg-amber-50 p-3 rounded-lg"
labelClassName="text-amber-800 font-bold"
/>
</div>
</RadioGroup>
```
### DatePicker Component
```typescript
<DatePicker
name="birthDate"
label="Birth Date"
description="Select your date of birth"
className="custom-class"
disabled={isSubmitting} // Optional: disable during form submission
/>
```
**Zod Schema for Date Fields:**
```typescript
const formSchema = z.object({
birthDate: z.coerce.date({
required_error: 'Please select a date',
}),
});
```
### DropdownMenuSelect Component
```typescript
<DropdownMenuSelect
name="fruit"
label="Select Fruit"
description="Choose your favorite fruit"
disabled={isSubmitting} // Optional: disable during form submission
>
<DropdownMenuSelectItem value="apple">Apple</DropdownMenuSelectItem>
<DropdownMenuSelectItem value="banana">Banana</DropdownMenuSelectItem>
<DropdownMenuSelectItem value="orange">Orange</DropdownMenuSelectItem>
</DropdownMenuSelect>
```
**Zod Schema for Select Fields:**
```typescript
const formSchema = z.object({
fruit: z.string({
required_error: 'Please select a fruit',
}),
});
```
### OTPInput Component
```typescript
<OTPInput
name="otp"
label="Enter Verification Code"
description="Enter the 6-digit code sent to your phone"
maxLength={6} // Required: number of digits
className="custom-class"
disabled={isSubmitting} // Optional: disable during form submission
/>
```
**Zod Schema for OTP Fields:**
```typescript
const formSchema = z.object({
otp: z.string().min(6, 'OTP must be 6 digits'),
});
```
## Component Customization System
### Custom Input Components
```typescript
// Create custom input component
const PurpleInput = (props: React.InputHTMLAttributes<HTMLInputElement>) => (
<input
{...props}
className="w-full rounded-lg border-2 border-purple-300 bg-purple-50 px-4 py-2 text-purple-900 focus:border-purple-500"
/>
);
// Use in TextField
<TextField
name="email"
label="Email"
components={{
Input: PurpleInput,
}}
/>
```
### Custom Form Components
```typescript
// Custom label
const CustomLabel = (props: React.ComponentPropsWithoutRef<typeof FormLabel>) => (
<FormLabel className="text-lg font-bold text-blue-700" {...props} />
);
// Custom error message
const CustomMessage = (props: React.ComponentPropsWithoutRef<typeof FormMessage>) => (
<FormMessage className="text-red-500 bg-red-50 p-2 rounded-md" {...props} />
);
// Apply to any component
<TextField
name="username"
label="Username"
components={{
FormLabel: CustomLabel,
FormMessage: CustomMessage,
}}
/>
```
## Advanced Form Patterns
### Custom Submit Handlers
Use `submitHandlers.onValid` to transform data before submission. This is useful for:
- Adding computed fields (timestamps, IDs)
- Transforming data formats
- Combining multiple fields
- Adding metadata
```typescript
const methods = useRemixForm<FormData>({
resolver: zodResolver(formSchema),
fetcher,
submitConfig: {
action: '/',
method: 'post',
},
submitHandlers: {
onValid: (data) => {
// Transform data before submission
const transformedData = {
...data,
timestamp: new Date().toISOString(),
processed: true,
fullName: `${data.firstName} ${data.lastName}`, // Combine fields
};
fetcher.submit(
createFormData(transformedData),
{
method: 'post',
action: '/',
}
);
},
},
});
```
### Checkbox Groups with Custom Submission
When working with multiple checkboxes, you often want to transform the boolean object into an array of selected values:
**Schema for Checkbox Group:**
```typescript
const formSchema = z.object({
colors: z.object({
red: z.boolean().default(false),
blue: z.boolean().default(false),
green: z.boolean().default(false),
}),
});
```
**Form Implementation:**
```typescript
<div className="space-y-2">
<Checkbox name="colors.red" label="Red" />
<Checkbox name="colors.blue" label="Blue" />
<Checkbox name="colors.green" label="Green" />
</div>
```
**Custom Submission Handler:**
```typescript
submitHandlers: {
onValid: (data) => {
// Extract selected colors into array
const selectedColors = Object.entries(data.colors)
.filter(([_, selected]) => selected)
.map(([color]) => color);
// Submit transformed data
fetcher.submit(
createFormData({ selectedColors }),
{ method: 'post', action: '/' }
);
},
}
```
### Conditional Field Display
```typescript
const MyForm = () => {
const methods = useRemixForm<FormData>({...});
const watchAccountType = methods.watch('accountType');
return (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={methods.handleSubmit}>
<RadioGroup
name="accountType"
label="Account Type"
options={[
{ value: 'personal', label: 'Personal' },
{ value: 'business', label: 'Business' },
]}
/>
{/* Conditional field based on selection */}
{watchAccountType === 'business' && (
<TextField
name="companyName"
label="Company Name"
description="Enter your company name"
/>
)}
<Button type="submit">Submit</Button>
</fetcher.Form>
</RemixFormProvider>
);
};
```
### Form with Loading States
```typescript
const MyForm = () => {
const fetcher = useFetcher<{ message: string }>();
const isSubmitting = fetcher.state === 'submitting';
return (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={methods.handleSubmit}>
<TextField name="email" label="Email" disabled={isSubmitting} />
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Submitting...' : 'Submit'}
</Button>
{fetcher.data?.message && (
<div className="mt-4 p-4 bg-green-50 rounded-md">
<p className="text-green-700">{fetcher.data.message}</p>
</div>
)}
</fetcher.Form>
</RemixFormProvider>
);
};
```
## Zod Schema Patterns & Validation
### Common Validation Patterns
```typescript
const formSchema = z.object({
// Required string with minimum length
username: z.string().min(3, 'Username must be at least 3 characters'),
// Email validation
email: z.string().email('Please enter a valid email address'),
// Password with complexity requirements
password: z.string()
.min(8, 'Password must be at least 8 characters')
.regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, 'Password must contain uppercase, lowercase, and number'),
// Number with range validation
age: z.coerce.number()
.min(18, 'Must be at least 18 years old')
.max(120, 'Age must be realistic'),
// Boolean with custom validation
terms: z.boolean().refine(val => val === true, 'You must accept the terms'),
// Optional fields
middleName: z.string().optional(),
// Date validation
birthDate: z.coerce.date({
required_error: 'Please select your birth date',
}),
// Enum validation for select/radio
size: z.enum(['xs', 'sm', 'md', 'lg', 'xl'], {
required_error: 'Please select a size',
}),
// Array validation
hobbies: z.array(z.string()).min(1, 'Select at least one hobby'),
// Object validation for nested data
address: z.object({
street: z.string().min(1, 'Street is required'),
city: z.string().min(1, 'City is required'),
zipCode: z.string().regex(/^\d{5}$/, 'ZIP code must be 5 digits'),
}),
});
```
### Server-Side Validation & Error Handling
```typescript
export const action = async ({ request }: ActionFunctionArgs) => {
const { data, errors } = await getValidatedFormData<FormData>(
request,
zodResolver(formSchema)
);
// Return validation errors
if (errors) {
return { errors };
}
// Additional server-side validation
const existingUser = await getUserByEmail(data.email);
if (existingUser) {
return {
errors: {
email: { message: 'Email address is already registered' }
}
};
}
// Process successful submission
try {
await createUser(data);
return {
message: 'Account created successfully!',
redirectTo: '/dashboard'
};
} catch (error) {
return {
errors: {
_form: { message: 'Failed to create account. Please try again.' }
}
};
}
};
```
## Success Handling & Redirects
### Success Messages
Display success messages from server responses:
```typescript
// In your component
{fetcher.data?.message && (
<div className="mt-4 p-4 bg-green-50 border border-green-200 rounded-md">
<p className="text-green-700 font-medium">{fetcher.data.message}</p>
</div>
)}
// Error messages
{fetcher.data?.errors?._form && (
<div className="mt-4 p-4 bg-red-50 border border-red-200 rounded-md">
<p className="text-red-700 font-medium">{fetcher.data.errors._form.message}</p>
</div>
)}
```
### Programmatic Redirects
**Client-side redirect handling:**
```typescript
import { useNavigate } from 'react-router';
const MyForm = () => {
const navigate = useNavigate();
const fetcher = useFetcher();
// Handle redirect from server response
useEffect(() => {
if (fetcher.data?.redirectTo) {
navigate(fetcher.data.redirectTo);
}
}, [fetcher.data?.redirectTo, navigate]);
// ... rest of component
};
```
**Server-side redirect:**
```typescript
import { redirect } from 'react-router';
export const action = async ({ request }: ActionFunctionArgs) => {
// ... validation and processing
// Redirect after successful submission
return redirect('/success');
};
```
### Optimistic UI Updates
Show immediate feedback while form is submitting:
```typescript
import { useState, useEffect } from 'react';
const MyForm = () => {
const fetcher = useFetcher();
const [optimisticMessage, setOptimisticMessage] = useState('');
const handleSubmit = (data: FormData) => {
// Show optimistic message immediately
setOptimisticMessage('Saving...');
// Submit form
methods.handleSubmit();
};
useEffect(() => {
if (fetcher.state === 'idle' && fetcher.data) {
setOptimisticMessage('');
}
}, [fetcher.state, fetcher.data]);
return (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={handleSubmit}>
{/* Form fields */}
{optimisticMessage && <p className="text-blue-600">{optimisticMessage}</p>}
{fetcher.data?.message && <p className="text-green-600">{fetcher.data.message}</p>}
</fetcher.Form>
</RemixFormProvider>
);
};
```
## Complete Form Example
Here's a comprehensive example demonstrating all major features:
```typescript
import { zodResolver } from '@hookform/resolvers/zod';
import {
TextField,
Textarea,
Checkbox,
RadioGroup,
DatePicker,
DropdownMenuSelect
} from '@lambdacurry/forms';
import { Button } from '@lambdacurry/forms/ui';
import { DropdownMenuSelectItem } from '@lambdacurry/forms/ui';
import { RemixFormProvider, useRemixForm, getValidatedFormData, createFormData } from 'remix-hook-form';
import { useFetcher, type ActionFunctionArgs } from 'react-router';
import { z } from 'zod';
// Comprehensive form schema
const formSchema = z.object({
// Personal Information
firstName: z.string().min(2, 'First name must be at least 2 characters'),
lastName: z.string().min(2, 'Last name must be at least 2 characters'),
email: z.string().email('Please enter a valid email address'),
birthDate: z.coerce.date({
required_error: 'Please select your birth date',
}),
// Preferences
accountType: z.enum(['personal', 'business'], {
required_error: 'Please select an account type',
}),
notifications: z.boolean().default(false),
newsletter: z.boolean().default(false),
// Additional Info
bio: z.string().min(10, 'Bio must be at least 10 characters').optional(),
country: z.string({
required_error: 'Please select your country',
}),
// Terms
terms: z.boolean().refine(val => val === true, 'You must accept the terms'),
});
type FormData = z.infer<typeof formSchema>;
const ComprehensiveForm = () => {
const fetcher = useFetcher<{
message: string;
errors?: Record<string, { message: string }>;
redirectTo?: string;
}>();
const methods = useRemixForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
firstName: '',
lastName: '',
email: '',
birthDate: undefined,
accountType: undefined,
notifications: false,
newsletter: false,
bio: '',
country: '',
terms: false,
},
fetcher,
submitConfig: {
action: '/register',
method: 'post',
},
submitHandlers: {
onValid: (data) => {
// Transform data before submission
const transformedData = {
...data,
fullName: `${data.firstName} ${data.lastName}`,
registrationDate: new Date().toISOString(),
};
fetcher.submit(
createFormData(transformedData),
{
method: 'post',
action: '/register',
}
);
},
},
});
const watchAccountType = methods.watch('accountType');
const isSubmitting = fetcher.state === 'submitting';
return (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={methods.handleSubmit} className="max-w-2xl mx-auto p-6 space-y-6">
<h1 className="text-2xl font-bold text-gray-900">Create Account</h1>
{/* Personal Information Section */}
<div className="space-y-4">
<h2 className="text-lg font-semibold text-gray-800">Personal Information</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<TextField
name="firstName"
label="First Name"
placeholder="Enter your first name"
disabled={isSubmitting}
/>
<TextField