-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect.stories.tsx
More file actions
632 lines (541 loc) · 22.4 KB
/
select.stories.tsx
File metadata and controls
632 lines (541 loc) · 22.4 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
import { zodResolver } from '@hookform/resolvers/zod';
import { CanadaProvinceSelect, Select, USStateSelect } from '@lambdacurry/forms/remix-hook-form';
import { Button } from '@lambdacurry/forms/ui/button';
import { CANADA_PROVINCES } from '@lambdacurry/forms/ui/data/canada-provinces';
import { US_STATES } from '@lambdacurry/forms/ui/data/us-states';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, userEvent, within } from '@storybook/test';
import { type ActionFunctionArgs, useFetcher } from 'react-router';
import { getValidatedFormData, RemixFormProvider, useRemixForm } from 'remix-hook-form';
import { z } from 'zod';
import { withReactRouterStubDecorator } from '../lib/storybook/react-router-stub';
const formSchema = z.object({
state: z.string().min(1, 'Please select a state'),
province: z.string().min(1, 'Please select a province'),
region: z.string().min(1, 'Please select a region'),
});
type FormData = z.infer<typeof formSchema>;
const RegionSelectExample = () => {
const fetcher = useFetcher<{ message: string; selectedRegions: Record<string, string> }>();
const methods = useRemixForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
state: '',
province: '',
region: '',
},
fetcher,
submitConfig: { action: '/', method: 'post' },
});
return (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={methods.handleSubmit} className="space-y-6">
<div className="space-y-4">
<USStateSelect name="state" label="US State" description="Select a US state" />
<CanadaProvinceSelect name="province" label="Canadian Province" description="Select a Canadian province" />
<Select
name="region"
label="Custom Region"
description="Select a custom region"
options={[...US_STATES.slice(0, 5), ...CANADA_PROVINCES.slice(0, 5)]}
placeholder="Select a custom region"
/>
</div>
<Button type="submit">Submit</Button>
{fetcher.data?.selectedRegions && (
<div className="mt-4 p-4 bg-gray-100 rounded-md">
<p className="text-sm font-medium">Selected regions:</p>
<ul className="text-sm text-gray-500">
{Object.entries(fetcher.data.selectedRegions).map(([key, value]) => (
<li key={key}>
{key}: {value}
</li>
))}
</ul>
</div>
)}
</fetcher.Form>
</RemixFormProvider>
);
};
const handleFormSubmission = async (request: Request) => {
const { data, errors } = await getValidatedFormData<FormData>(request, zodResolver(formSchema));
if (errors) {
return { errors };
}
return {
message: 'Form submitted successfully',
selectedRegions: {
state: data.state,
province: data.province,
region: data.region,
},
};
};
// Region-only submission handler for stories that only submit the `region` field
const handleRegionSubmission = async (request: Request) => {
const regionSchema = z.object({ region: z.string().min(1) });
const { data, errors } = await getValidatedFormData<{ region: string }>(request, zodResolver(regionSchema));
if (errors) {
return { errors };
}
return {
message: 'Form submitted successfully',
selectedRegion: data.region,
};
};
const meta: Meta<typeof Select> = {
title: 'RemixHookForm/Select',
component: Select,
parameters: { layout: 'centered' },
tags: ['autodocs'],
} satisfies Meta<typeof Select>;
export default meta;
type Story = StoryObj<typeof meta>;
const selectRouterDecorator = withReactRouterStubDecorator({
routes: [
{
path: '/',
Component: RegionSelectExample,
action: async ({ request }: ActionFunctionArgs) => handleFormSubmission(request),
},
],
});
export const Default: Story = {
parameters: {
docs: {
description: {
story:
'A select component for selecting options from a dropdown list. Includes specialized components for US states and Canadian provinces.',
},
source: {
code: `
const formSchema = z.object({
state: z.string().min(1, 'Please select a state'),
province: z.string().min(1, 'Please select a province'),
region: z.string().min(1, 'Please select a region'),
});
const RegionSelectExample = () => {
const fetcher = useFetcher<{ message: string; selectedRegions: Record<string, string> }>();
const methods = useRemixForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
state: '',
province: '',
region: '',
},
fetcher,
submitConfig: { action: '/', method: 'post' },
});
return (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={methods.handleSubmit} className="space-y-6">
<div className="space-y-4">
<USStateSelect
name="state"
label="US State"
description="Select a US state"
/>
<CanadaProvinceSelect
name="province"
label="Canadian Province"
description="Select a Canadian province"
/>
<Select
name="region"
label="Custom Region"
description="Select a custom region"
options={[
...US_STATES.slice(0, 5),
...CANADA_PROVINCES.slice(0, 5),
]}
placeholder="Select a custom region"
/>
</div>
<Button type="submit">Submit</Button>
</fetcher.Form>
</RemixFormProvider>
);
};`,
},
},
},
decorators: [selectRouterDecorator],
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);
await step('Verify initial state', () => {
// Verify all selects are empty initially
const stateSelect = canvas.getByLabelText('US State');
const provinceSelect = canvas.getByLabelText('Canadian Province');
const regionSelect = canvas.getByLabelText('Custom Region');
expect(stateSelect).toHaveTextContent('Select a state');
expect(provinceSelect).toHaveTextContent('Select a province');
expect(regionSelect).toHaveTextContent('Select a custom region');
// Verify submit button is present
const submitButton = canvas.getByRole('button', { name: 'Submit' });
expect(submitButton).toBeInTheDocument();
});
await step('Test validation errors on invalid submission', async () => {
// Wait for component to be fully loaded
await canvas.findByLabelText('US State');
// Submit form without selecting any options
const submitButton = canvas.getByRole('button', { name: 'Submit' });
await userEvent.click(submitButton);
// Verify validation error messages appear
// Use getByText with fallback to findByText for better WebKit compatibility
expect(canvas.getByText('Please select a state')).toBeInTheDocument();
expect(canvas.getByText('Please select a province')).toBeInTheDocument();
expect(canvas.getByText('Please select a region')).toBeInTheDocument();
});
await step('Test successful submission', async () => {
// Select a state
const stateSelect = canvas.getByLabelText('US State');
await userEvent.click(stateSelect);
try {
const listbox = await within(document.body).findByRole('listbox', {}, { timeout: 5000 });
const californiaOption = within(listbox).getByRole('option', { name: 'California' });
await userEvent.click(californiaOption);
} catch (error) {
// Fallback: try clicking the option directly if listbox approach fails
console.warn('Listbox approach failed, trying direct option selection', error);
const californiaOption = canvas.getByRole('option', { name: 'California' });
await userEvent.click(californiaOption);
}
// Select a province
const provinceSelect = canvas.getByLabelText('Canadian Province');
await userEvent.click(provinceSelect);
try {
const listbox = await within(document.body).findByRole('listbox', {}, { timeout: 5000 });
const ontarioOption = within(listbox).getByRole('option', { name: 'Ontario' });
await userEvent.click(ontarioOption);
} catch (error) {
// Fallback: try clicking the option directly if listbox approach fails
console.warn('Listbox approach failed, trying direct option selection', error);
const ontarioOption = canvas.getByRole('option', { name: 'Ontario' });
await userEvent.click(ontarioOption);
}
// Select a custom region
const regionSelect = canvas.getByLabelText('Custom Region');
await userEvent.click(regionSelect);
try {
const listbox = await within(document.body).findByRole('listbox', {}, { timeout: 5000 });
const customOption = within(listbox).getByRole('option', { name: 'California' });
await userEvent.click(customOption);
} catch (error) {
// Fallback: try clicking the option directly if listbox approach fails
console.warn('Listbox approach failed, trying direct option selection', error);
const customOption = canvas.getByRole('option', { name: 'California' });
await userEvent.click(customOption);
}
// Submit
const submitButton = canvas.getByRole('button', { name: 'Submit' });
await userEvent.click(submitButton);
// Assert success UI
await expect(canvas.findByText('Selected regions:')).resolves.toBeInTheDocument();
expect(canvas.getByText('state: CA')).toBeInTheDocument();
expect(canvas.getByText('province: ON')).toBeInTheDocument();
expect(canvas.getByText('region: CA')).toBeInTheDocument();
});
},
};
export const USStateSelection: Story = {
parameters: {
docs: {
description: {
story: 'Test selecting a US state from the dropdown.',
},
},
},
decorators: [selectRouterDecorator],
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);
await step('Select a US state', async () => {
// Wait for component to be fully loaded
await canvas.findByLabelText('US State');
// Find and click the US state dropdown
const stateSelect = canvas.getByLabelText('US State');
await userEvent.click(stateSelect);
// Wait for the dropdown to open and find the listbox with timeout
const listbox = await within(document.body).findByRole('listbox', {}, { timeout: 5000 });
expect(listbox).toBeInTheDocument();
// Find and click the California option
const californiaOption = within(listbox).getByRole('option', { name: 'California' });
expect(californiaOption).toBeInTheDocument();
await userEvent.click(californiaOption);
// Wait for the trigger text to update after portal selection
await expect(canvas.findByRole('combobox', { name: 'US State' })).resolves.toHaveTextContent('California');
});
},
};
export const CanadaProvinceSelection: Story = {
parameters: {
docs: {
description: {
story: 'Test selecting a Canadian province from the dropdown.',
},
},
},
decorators: [selectRouterDecorator],
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);
await step('Select a Canadian province', async () => {
// Wait for component to be fully loaded
await canvas.findByLabelText('Canadian Province');
// Find and click the Canada province dropdown
const provinceSelect = canvas.getByLabelText('Canadian Province');
await userEvent.click(provinceSelect);
// Wait for the dropdown to open and find the listbox with timeout
const listbox = await within(document.body).findByRole('listbox', {}, { timeout: 5000 });
expect(listbox).toBeInTheDocument();
// Find and click the Ontario option
const ontarioOption = within(listbox).getByRole('option', { name: 'Ontario' });
expect(ontarioOption).toBeInTheDocument();
await userEvent.click(ontarioOption);
// Wait for the trigger text to update after portal selection
await expect(canvas.findByRole('combobox', { name: 'Canadian Province' })).resolves.toHaveTextContent('Ontario');
});
},
};
export const FormSubmission: Story = {
parameters: {
docs: {
description: {
story: 'Test form submission with selected regions.',
},
},
},
decorators: [selectRouterDecorator],
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);
await step('Select all regions', async () => {
// Wait for component to be fully loaded
await canvas.findByLabelText('US State');
// Select a state
const stateSelect = canvas.getByLabelText('US State');
await userEvent.click(stateSelect);
const listbox = await within(document.body).findByRole('listbox', {}, { timeout: 5000 });
expect(listbox).toBeInTheDocument();
const californiaOption = within(listbox).getByRole('option', { name: 'California' });
expect(californiaOption).toBeInTheDocument();
await userEvent.click(californiaOption);
// Select a province
const provinceSelect = canvas.getByLabelText('Canadian Province');
await userEvent.click(provinceSelect);
const provinceListbox = await within(document.body).findByRole('listbox', {}, { timeout: 5000 });
expect(provinceListbox).toBeInTheDocument();
const ontarioOption = within(provinceListbox).getByRole('option', { name: 'Ontario' });
expect(ontarioOption).toBeInTheDocument();
await userEvent.click(ontarioOption);
// Select a custom region
const regionSelect = canvas.getByLabelText('Custom Region');
await userEvent.click(regionSelect);
const regionListbox = await within(document.body).findByRole('listbox', {}, { timeout: 5000 });
expect(regionListbox).toBeInTheDocument();
const customOption = within(regionListbox).getByRole('option', { name: 'California' });
expect(customOption).toBeInTheDocument();
await userEvent.click(customOption);
});
await step('Submit the form', async () => {
// Submit the form
const submitButton = canvas.getByRole('button', { name: 'Submit' });
await userEvent.click(submitButton);
// Verify the submission result
await expect(canvas.findByText('Selected regions:')).resolves.toBeInTheDocument();
});
},
};
// Additional examples for search behavior and creatable options
const SearchDisabledExample = () => {
const fetcher = useFetcher<{ message: string }>();
const methods = useRemixForm<{ region: string }>({
resolver: zodResolver(z.object({ region: z.string().min(1) })),
defaultValues: { region: '' },
fetcher,
submitConfig: { action: '/', method: 'post' },
});
return (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={methods.handleSubmit}>
<Select
name="region"
label="Custom Region"
description="Search disabled"
options={[...US_STATES.slice(0, 5), ...CANADA_PROVINCES.slice(0, 5)]}
placeholder="Select a custom region"
searchable={false}
/>
</fetcher.Form>
</RemixFormProvider>
);
};
export const SearchDisabled: Story = {
decorators: [
withReactRouterStubDecorator({
routes: [
{
path: '/',
Component: SearchDisabledExample,
action: async ({ request }: ActionFunctionArgs) => handleFormSubmission(request),
},
],
}),
],
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);
await step('Open select and ensure no search input', async () => {
// Wait for component to be fully loaded
await canvas.findByLabelText('Custom Region');
const regionSelect = canvas.getByLabelText('Custom Region');
await userEvent.click(regionSelect);
// Wait for the dropdown to open
const listbox = await within(document.body).findByRole('listbox', {}, { timeout: 5000 });
expect(listbox).toBeInTheDocument();
// Verify no search input is present when searchable is disabled
const searchInput = within(listbox).queryByPlaceholderText('Search...');
expect(searchInput).not.toBeInTheDocument();
});
},
};
const CustomSearchPlaceholderExample = () => {
const fetcher = useFetcher<{ message: string }>();
const methods = useRemixForm<{ region: string }>({
resolver: zodResolver(z.object({ region: z.string().min(1) })),
defaultValues: { region: '' },
fetcher,
submitConfig: { action: '/', method: 'post' },
});
return (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={methods.handleSubmit}>
<Select
name="region"
label="Custom Region"
description="Custom search placeholder"
options={[...US_STATES.slice(0, 5), ...CANADA_PROVINCES.slice(0, 5)]}
placeholder="Select a custom region"
searchInputProps={{ placeholder: 'Type to filter…' }}
/>
</fetcher.Form>
</RemixFormProvider>
);
};
export const CustomSearchPlaceholder: Story = {
decorators: [
withReactRouterStubDecorator({
routes: [
{
path: '/',
Component: CustomSearchPlaceholderExample,
action: async ({ request }: ActionFunctionArgs) => handleFormSubmission(request),
},
],
}),
],
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);
await step('Open select and see custom placeholder', async () => {
// Wait for component to be fully loaded
await canvas.findByLabelText('Custom Region');
const regionSelect = canvas.getByLabelText('Custom Region');
await userEvent.click(regionSelect);
// The search input is rendered alongside the listbox in the portal, not inside the listbox itself.
const searchInput = await within(document.body).findByPlaceholderText('Type to filter…', {}, { timeout: 5000 });
expect(searchInput).toBeInTheDocument();
});
},
};
const CreatableSelectExample = () => {
const fetcher = useFetcher<{ message: string; selectedRegion?: string }>();
const methods = useRemixForm<{ region: string }>({
resolver: zodResolver(z.object({ region: z.string().min(1) })),
defaultValues: { region: '' },
fetcher,
submitConfig: { action: '/', method: 'post' },
});
return (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={methods.handleSubmit} className="space-y-4">
<Select
name="region"
label="Custom Region"
description="Creatable option enabled (defaults to trimming the input and using it as label/value)"
options={[...US_STATES.slice(0, 5), ...CANADA_PROVINCES.slice(0, 5)]}
placeholder="Select a custom region"
creatable
/>
<Button type="submit">Submit</Button>
{fetcher.data?.selectedRegion && (
<div className="mt-4 p-4 bg-gray-100 rounded-md" data-testid="submitted-region">
<p className="text-sm font-medium">Submitted region: {fetcher.data.selectedRegion}</p>
</div>
)}
</fetcher.Form>
</RemixFormProvider>
);
};
export const CreatableOption: Story = {
decorators: [
withReactRouterStubDecorator({
routes: [
{
path: '/',
Component: CreatableSelectExample,
action: async ({ request }: ActionFunctionArgs) => handleRegionSubmission(request),
},
],
}),
],
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);
await step('Create new option when no exact match', async () => {
// Wait for the component to fully load - check for loading screen absence
// This prevents the "sb-loader" (loading screen) from interfering with interactions
await canvas.findByLabelText('Custom Region');
// Additional wait to ensure the component is fully interactive
await new Promise((resolve) => setTimeout(resolve, 1000));
const regionSelect = canvas.getByLabelText('Custom Region');
await userEvent.click(regionSelect);
// Wait for the dropdown to open and find the listbox with timeout
const listbox = await within(document.body).findByRole('listbox', {}, { timeout: 5000 });
expect(listbox).toBeInTheDocument();
// The search input is outside the listbox container; query from the portal root
const input = await within(document.body).findByPlaceholderText('Search...');
expect(input).toBeInTheDocument();
await userEvent.click(input);
await userEvent.clear(input);
await userEvent.type(input, 'Atlantis');
// Wait for the creatable option to appear
const createItem = await within(listbox).findByRole('option', { name: 'Select "Atlantis"' }, { timeout: 2000 });
expect(createItem).toBeInTheDocument();
await userEvent.click(createItem);
// Verify the selection was applied
await expect(canvas.findByRole('combobox', { name: 'Custom Region' })).resolves.toHaveTextContent('Atlantis');
// Submit and verify server received the created option value
const submitButton = canvas.getByRole('button', { name: 'Submit' });
await userEvent.click(submitButton);
await expect(canvas.findByText('Submitted region: Atlantis')).resolves.toBeInTheDocument();
});
await step('No creatable when exact match exists', async () => {
// Wait for the component to fully load - check for loading screen absence
await canvas.findByLabelText('Custom Region');
// Additional wait to ensure the component is fully interactive
await new Promise((resolve) => setTimeout(resolve, 1000));
const regionSelect = canvas.getByLabelText('Custom Region');
await userEvent.click(regionSelect);
// Wait for the dropdown to open and find the listbox
const listbox = await within(document.body).findByRole('listbox', {}, { timeout: 5000 });
expect(listbox).toBeInTheDocument();
// The search input is outside the listbox container; query from the portal root
const input = await within(document.body).findByPlaceholderText('Search...');
expect(input).toBeInTheDocument();
await userEvent.click(input);
await userEvent.clear(input);
await userEvent.type(input, 'California');
// Verify no creatable option appears when exact match exists
const createOption = within(listbox).queryByRole('option', { name: 'Select "California"' });
expect(createOption).not.toBeInTheDocument();
// Close the dropdown
await userEvent.click(regionSelect);
});
},
};