-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcheckbox-list.stories.tsx
More file actions
212 lines (189 loc) · 6.56 KB
/
Copy pathcheckbox-list.stories.tsx
File metadata and controls
212 lines (189 loc) · 6.56 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
import { zodResolver } from '@hookform/resolvers/zod';
import { Checkbox } from '@lambdacurry/forms/remix-hook-form/checkbox';
import { Button } from '@lambdacurry/forms/ui/button';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, userEvent, within } from '@storybook/test';
import { type ActionFunctionArgs, useFetcher } from 'react-router';
import { RemixFormProvider, getValidatedFormData, useRemixForm } from 'remix-hook-form';
import { z } from 'zod';
import { withReactRouterStubDecorator } from '../lib/storybook/react-router-stub';
const AVAILABLE_COLORS = [
{ value: 'red', label: 'Red' },
{ value: 'blue', label: 'Blue' },
{ value: 'green', label: 'Green' },
{ value: 'yellow', label: 'Yellow' },
{ value: 'purple', label: 'Purple' },
] as const;
const formSchema = z.object({
colors: z.record(z.boolean()).refine((colors) => {
return Object.values(colors).some((selected) => selected);
}, 'Please select at least one color'),
});
type FormData = z.infer<typeof formSchema>;
// Custom FormLabel component that makes the entire area clickable
const FullWidthLabel = ({ className, children, htmlFor, ...props }: React.ComponentPropsWithoutRef<'label'>) => {
return (
<label
htmlFor={htmlFor}
className={`absolute inset-0 cursor-pointer flex items-center py-4 px-8 ${className}`}
{...props}
>
<span className="ml-2">{children}</span>
</label>
);
};
const ControlledCheckboxListExample = () => {
const fetcher = useFetcher<{ message: string; selectedColors: string[] }>();
const methods = useRemixForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
colors: AVAILABLE_COLORS.reduce((acc, { value }) => ({ ...acc, [value]: false }), {}),
},
fetcher,
submitConfig: {
action: '/',
method: 'post',
},
submitHandlers: {
onValid: (data) => {
const selectedColors = Object.entries(data.colors)
.filter(([_, selected]) => selected)
.map(([color]) => color);
const filteredData = Object.fromEntries(
Object.entries(data).filter(([key]) => !AVAILABLE_COLORS.some((color) => color.value === key)),
);
fetcher.submit(createFormData({ ...filteredData, selectedColors }), {
method: 'post',
action: '/',
});
},
},
});
return (
<RemixFormProvider {...methods}>
<Form onSubmit={methods.handleSubmit}>
<div className="space-y-4">
<p className="text-sm text-gray-500">Select your favorite colors:</p>
<div className="grid gap-4">
{AVAILABLE_COLORS.map(({ value, label }) => (
<Checkbox
key={value}
className="relative rounded-md border p-4 hover:bg-gray-50"
name={`colors.${value}`}
label={label}
components={{
FormLabel: FullWidthLabel,
}}
/>
))}
</div>
<FormMessage error={methods.formState.errors.colors?.root?.message} />
<Button type="submit" className="mt-4">
Submit
</Button>
{fetcher.data?.selectedColors && (
<div className="mt-4">
<p className="text-sm font-medium">Submitted with selected colors:</p>
<p className="text-sm text-gray-500">{fetcher.data.selectedColors.join(', ')}</p>
</div>
)}
</div>
</Form>
</RemixFormProvider>
);
};
const handleFormSubmission = async (request: Request) => {
const { data, errors } = await getValidatedFormData<FormData>(request, zodResolver(formSchema));
if (errors) {
return { errors };
}
const selectedColors = Object.entries(data.colors)
.filter(([_, selected]) => selected)
.map(([color]) => AVAILABLE_COLORS.find((c) => c.value === color)?.label ?? color);
return { message: 'Colors selected successfully', selectedColors };
};
const meta: Meta<typeof Checkbox> = {
title: 'RemixHookForm/Checkbox List',
component: Checkbox,
parameters: { layout: 'centered' },
tags: ['autodocs'],
decorators: [
withReactRouterStubDecorator({
routes: [
{
path: '/',
Component: ControlledCheckboxListExample,
action: async ({ request }: ActionFunctionArgs) => handleFormSubmission(request),
},
],
}),
],
} satisfies Meta<typeof Checkbox>;
export default meta;
type Story = StoryObj<typeof meta>;
const testDefaultValues = ({ canvas }: StoryContext) => {
AVAILABLE_COLORS.forEach(({ label }) => {
const checkbox = canvas.getByLabelText(label);
expect(checkbox).not.toBeChecked();
});
};
const testErrorState = async ({ canvas }: StoryContext) => {
// Submit form without selecting any colors
const submitButton = canvas.getByRole('button', { name: 'Submit' });
await userEvent.click(submitButton);
// Check if error message is displayed
await expect(await canvas.findByText('Please select at least one color')).toBeInTheDocument();
};
const testColorSelection = async ({ canvas }: StoryContext) => {
// Select two colors
const redCheckbox = canvas.getByLabelText('Red');
const blueCheckbox = canvas.getByLabelText('Blue');
await userEvent.click(redCheckbox);
await userEvent.click(blueCheckbox);
const submitButton = canvas.getByRole('button', { name: 'Submit' });
await userEvent.click(submitButton);
// Check if the selected colors are displayed
await expect(await canvas.findByText('Red, Blue')).toBeInTheDocument();
};
export const Tests: Story = {
parameters: {
docs: {
description: {
story: 'A checkbox list component for selecting multiple colors with full-width clickable area.',
},
source: {
code: `
// Custom FormLabel component that makes the entire area clickable
const FullWidthLabel = React.forwardRef<HTMLLabelElement, React.ComponentPropsWithoutRef<'label'>>(
({ className, children, htmlFor, ...props }, ref) => {
return (
<label
ref={ref}
htmlFor={htmlFor}
className={\`absolute inset-0 cursor-pointer flex items-center py-4 px-8 \${className}\`}
{...props}
>
<span className="ml-2">{children}</span>
</label>
);
},
);
// Usage in your component
<Checkbox
className="relative rounded-md border p-4 hover:bg-gray-50"
name="colors.red"
label="Red"
components={{
FormLabel: FullWidthLabel,
}}
/>
`,
},
},
},
play: async (storyContext) => {
testDefaultValues(storyContext);
await testErrorState(storyContext);
await testColorSelection(storyContext);
},
};