-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathForm.stories.tsx
762 lines (691 loc) · 25.9 KB
/
Form.stories.tsx
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
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {action} from '@storybook/addon-actions';
import {Button} from '@react-spectrum/button';
import {ButtonGroup} from '@react-spectrum/buttongroup';
import {CalendarDate} from '@internationalized/date';
import {chain} from '@react-aria/utils';
import {Checkbox, CheckboxGroup} from '@react-spectrum/checkbox';
import {ColorField} from '@react-spectrum/color';
import {ComboBox} from '@react-spectrum/combobox';
import {Content, Header} from '@react-spectrum/view';
import {ContextualHelp} from '@react-spectrum/contextualhelp';
import {countries, states} from './data';
import {DateField, DatePicker, DateRangePicker, TimeField} from '@react-spectrum/datepicker';
import {Flex} from '@react-spectrum/layout';
import {Form} from '../';
import {FormTranslatedText} from './../chromatic/FormLanguages.stories';
import {Heading} from '@react-spectrum/text';
import {InlineAlert} from '@react-spectrum/inlinealert';
import {Item, Picker} from '@react-spectrum/picker';
import {Key, ValidationState} from '@react-types/shared';
import {NumberField} from '@react-spectrum/numberfield';
import {Radio, RadioGroup} from '@react-spectrum/radio';
import React, {useEffect, useState} from 'react';
import {SearchAutocomplete} from '@react-spectrum/autocomplete';
import {SearchField} from '@react-spectrum/searchfield';
import {Slider} from '@react-spectrum/slider';
import {StatusLight} from '@react-spectrum/statuslight';
import {Switch} from '@react-spectrum/switch';
import {TagGroup} from '@react-spectrum/tag';
import {TextArea, TextField} from '@react-spectrum/textfield';
import typographyStyles from '@adobe/spectrum-css-temp/components/typography/vars.css';
import {Well} from '@react-spectrum/well';
export default {
title: 'Form',
providerSwitcher: {status: 'positive'}
};
export const Default = () => render({});
export const LabelPositionSide = () => render({labelPosition: 'side'});
LabelPositionSide.story = {
name: 'labelPosition: side'
};
export const CustomWidth = () => render({width: 400});
CustomWidth.story = {
name: 'custom width'
};
export const CustomWidthLabelPositionSide = () => render({width: 400, labelPosition: 'side'});
CustomWidthLabelPositionSide.story = {
name: 'custom width, labelPosition: side'
};
export const LabelAlignEnd = () => render({width: 400, labelAlign: 'end'});
LabelAlignEnd.story = {
name: 'labelAlign: end'
};
export const LabelPositionSideLabelAlignEnd = () =>
render({width: 400, labelPosition: 'side', labelAlign: 'end'});
LabelPositionSideLabelAlignEnd.story = {
name: 'labelPosition: side, labelAlign: end'
};
export const FieldsNextToEachOther = () => (
<Form>
<Flex>
<TextField
label="First Name"
marginEnd="size-100"
flex={1}
description="Please enter your first name." />
<TextField label="Last Name" flex={1} description="Please enter your last name." />
</Flex>
<TextField label="Street Address" description="Please include apartment or suite number." />
<Flex>
<TextField
label="City"
marginEnd="size-100"
flex={1}
description="Please enter the city you live in." />
<Picker label="State" items={states} marginEnd="size-100" flex={1}>
{(item) => <Item key={item.abbr}>{item.name}</Item>}
</Picker>
<TextField label="Zip code" flex={1} description="Please enter a five-digit zip code." />
</Flex>
</Form>
);
FieldsNextToEachOther.story = {
name: 'fields next to each other'
};
export const FieldsWithAutoCompleteProperty = () => {
const [checked, setChecked] = useState(true);
return (
<Form>
<Well role="group" aria-labelledby="billing-legend">
<h2 id="billing-legend" className={typographyStyles['spectrum-Heading4']}>
Billing address
</h2>
<Flex>
<TextField
autoComplete="billing given-name"
name="firstName"
isRequired
label="First Name"
marginEnd="size-100"
flex={1} />
<TextField
autoComplete="billing family-name"
name="lastName"
isRequired
label="Last Name"
flex={1} />
</Flex>
<Flex>
<TextArea
autoComplete="billing street-address"
name="streetAddress"
isRequired
label="Street Address"
flex={1} />
</Flex>
<Flex>
<TextField
autoComplete="billing address-level2"
name="city"
isRequired
label="City"
marginEnd="size-100"
flex={1} />
<Picker
autoComplete="billing address-level1"
name="state"
isRequired
label="State"
items={states}
marginEnd="size-100"
flex={1}>
{(item) => <Item key={item.abbr}>{item.name}</Item>}
</Picker>
<TextField
autoComplete="billing postal-code"
name="zip"
isRequired
label="Zip code"
flex={1} />
</Flex>
<Flex>
<Picker
autoComplete="billing country"
name="country"
isRequired
label="Country"
items={countries}
marginEnd="size-100"
flex={1}>
{(item) => <Item key={item.code}>{item.name}</Item>}
</Picker>
</Flex>
<Flex>
<TextField
autoComplete="billing tel"
type="tel"
name="phone"
label="Phone number"
marginEnd="size-100"
flex={1} />
<TextField
autoComplete="billing email"
type="email"
name="email"
isRequired
label="Email address"
marginEnd="size-100"
flex={1} />
</Flex>
</Well>
<Well role="group" aria-labelledby="shipping-legend">
<h2 id="shipping-legend" className={typographyStyles['spectrum-Heading4']}>
Shipping address
</h2>
<Checkbox isSelected={checked} onChange={setChecked}>
Same as billing address
</Checkbox>
{!checked && (
<>
<Flex>
<TextField
autoComplete="shipping given-name"
name="shippingFirstName"
isRequired
label="First Name"
marginEnd="size-100"
flex={1} />
<TextField
autoComplete="shipping family-name"
name="shippingLastName"
isRequired
label="Last Name"
flex={1} />
</Flex>
<Flex>
<TextArea
autoComplete="shipping street-address"
name="shippingStreetAddress"
isRequired
label="Street Address"
flex={1} />
</Flex>
<Flex>
<TextField
autoComplete="shipping address-level2"
name="shippingCity"
isRequired
label="City"
marginEnd="size-100"
flex={1} />
<Picker
autoComplete="shipping address-level1"
name="shippingState"
isRequired
label="State"
items={states}
marginEnd="size-100"
flex={1}>
{(item) => <Item key={item.abbr}>{item.name}</Item>}
</Picker>
<TextField
autoComplete="shipping postal-code"
name="shippingZip"
isRequired
label="Zip code"
flex={1} />
</Flex>
<Flex>
<Picker
autoComplete="shipping country"
name="shippingCountry"
isRequired
label="Country"
items={countries}
marginEnd="size-100"
flex={1}>
{(item) => <Item key={item.code}>{item.name}</Item>}
</Picker>
</Flex>
<Flex>
<TextField
autoComplete="shipping tel"
type="tel"
name="shippingPhone"
label="Phone number"
marginEnd="size-100"
flex={1} />
<TextField
autoComplete="shipping email"
type="email"
name="shippingEmail"
isRequired
label="Email address"
marginEnd="size-100"
flex={1} />
</Flex>
</>
)}
</Well>
</Form>
);
};
FieldsWithAutoCompleteProperty.story = {
name: 'fields with autoComplete property'
};
export const IsRequiredTrue = () => render({isRequired: true});
IsRequiredTrue.story = {
name: 'isRequired: true'
};
export const IsRequiredTrueNecessityIndicatorLabel = () =>
render({isRequired: true, necessityIndicator: 'label'});
IsRequiredTrueNecessityIndicatorLabel.story = {
name: 'isRequired: true, necessityIndicator: label'
};
export const IsRequiredFalseNecessityIndicatorLabel = () =>
render({isRequired: false, necessityIndicator: 'label'});
IsRequiredFalseNecessityIndicatorLabel.story = {
name: 'isRequired: false, necessityIndicator: label'
};
export const IsDisabled = () => render({isDisabled: true});
IsDisabled.story = {
name: 'isDisabled'
};
export const IsQuiet = () => render({isQuiet: true});
IsQuiet.story = {
name: 'isQuiet'
};
export const IsQuietLabelPositionSide = () => render({isQuiet: true, labelPosition: 'side'});
IsQuietLabelPositionSide.story = {
name: 'isQuiet, labelPosition: side'
};
export const IsEmphasized = () => render({isEmphasized: true});
IsEmphasized.story = {
name: 'isEmphasized'
};
export const ValidationStateInvalid = () => render({validationState: 'invalid'});
ValidationStateInvalid.story = {
name: 'validationState: invalid'
};
export const ValidationStateValid = () => render({validationState: 'valid'});
ValidationStateValid.story = {
name: 'validationState: valid'
};
export const ValidationStateInvalidIsQuietTrue = () =>
render({validationState: 'invalid', isQuiet: true});
ValidationStateInvalidIsQuietTrue.story = {
name: 'validationState: invalid, isQuiet: true'
};
export const ValidationStateValidIsQuietTrue = () =>
render({validationState: 'valid', isQuiet: true});
ValidationStateValidIsQuietTrue.story = {
name: 'validationState: valid, isQuiet: true'
};
export const FormWithReset = () => <FormWithControls />;
FormWithReset.story = {
name: 'form with reset'
};
export const _FormWithSubmit = () => <FormWithSubmit />;
_FormWithSubmit.story = {
name: 'form with submit'
};
export const FormWithNumberfieldAndLocaleArAe = () => (
<Flex gap="size-100">
<NumberField label="Outside form" description="Hello" />
<Form>
<NumberField label="Inside form" />
</Form>
<Form>
<TextField label="First Name" />
</Form>
<Form>
<TextField label="First Name" />
<NumberField label="Inside form" />
</Form>
</Flex>
);
FormWithNumberfieldAndLocaleArAe.story = {
name: 'form with numberfield and locale=ar-AE'
};
export const WithTranslations = () => <FormTranslatedText />;
WithTranslations.story = {
name: 'with translations',
parameters: {description: {data: 'Translations included for: Arabic, English, Hebrew, Japanese, Korean, Simplified Chinese, and Traditional Chinese.'}}
};
function render(props: any = {}) {
return (
<Form {...props}>
<CheckboxGroup label="Pets" name="pets" validate={v => v.includes('dogs') ? 'No dogs' : null}>
<Checkbox value="dogs">Dogs</Checkbox>
<Checkbox value="cats">Cats</Checkbox>
<Checkbox value="dragons">Dragons</Checkbox>
</CheckboxGroup>
<ComboBox label="More Animals" name="combobox">
<Item key="red panda">Red Panda</Item>
<Item key="aardvark">Aardvark</Item>
<Item key="kangaroo">Kangaroo</Item>
<Item key="snake">Snake</Item>
</ComboBox>
<SearchAutocomplete label="Search Animals" name="searchAutocomplete">
<Item key="red panda">Red Panda</Item>
<Item key="aardvark">Aardvark</Item>
<Item key="kangaroo">Kangaroo</Item>
<Item key="snake">Snake</Item>
</SearchAutocomplete>
<NumberField label="Years lived there" name="years" />
<Picker label="State" items={states} name="state">
{item => <Item key={item.abbr}>{item.name}</Item>}
</Picker>
<Picker label="Country" items={countries} name="country">
{item => <Item key={item.name}>{item.name}</Item>}
</Picker>
<Picker label="Favorite color" name="color" description="Select any color you like." errorMessage="Please select a nicer color.">
<Item>Red</Item>
<Item>Orange</Item>
<Item>Yellow</Item>
<Item>Green</Item>
<Item>Blue</Item>
<Item>Purple</Item>
</Picker>
<RadioGroup label="Favorite pet" name="favorite-pet-group">
<Radio value="dogs">Dogs</Radio>
<Radio value="cats">Cats</Radio>
<Radio value="dragons">Dragons</Radio>
</RadioGroup>
<SearchField label="Search" name="search" />
<Switch name="switch">Low power mode</Switch>
<TextArea name="comments" label="Comments" description="Express yourself!" errorMessage="No wrong answers, except for this one." />
<TextField
label="City"
name="city"
contextualHelp={(
<ContextualHelp>
<Heading>What is a segment?</Heading>
<Content>Segments identify who your visitors are, what devices and services they use, where they navigated from, and much more.</Content>
</ContextualHelp>
)} />
<TextField label="Zip code" description="Please enter a five-digit zip code." pattern="[0-9]{5}" name="zip" />
<TagGroup label="Favorite tags" description="Select your favorite tags." errorMessage="Incorrect combination of tags.">
<Item key="1">Cool Tag 1</Item>
<Item key="2">Cool Tag 2</Item>
<Item key="3">Cool Tag 3</Item>
<Item key="4">Cool Tag 4</Item>
<Item key="5">Cool Tag 5</Item>
<Item key="6">Cool Tag 6</Item>
</TagGroup>
<ColorField label="Color" name="color" />
<DateField label="Date" granularity="minute" name="date" />
<TimeField label="Time" name="time" />
<DatePicker label="Date picker" name="datePicker" />
<DateRangePicker label="Date range" startName="startDate" endName="endDate" />
<TextField type="email" label="Email" name="email" />
{props.showSubmit && (
<ButtonGroup>
<Button variant="primary" type="submit">Submit</Button>
<Button variant="secondary" type="reset">Reset</Button>
</ButtonGroup>
)}
</Form>
);
}
function FormWithControls(props: any = {}) {
let [firstName, setFirstName] = useState('hello');
let [isHunter, setIsHunter] = useState(true);
let [favoritePet, setFavoritePet] = useState('cats');
let [favoriteColor, setFavoriteColor] = useState<Key | null>('green');
let [howIFeel, setHowIFeel] = useState('I feel good, o I feel so good!');
let [birthday, setBirthday] = useState<CalendarDate | null>(new CalendarDate(1732, 2, 22));
let [money, setMoney] = useState(50);
let [superSpeed, setSuperSpeed] = useState(true);
return (
<Form
onSubmit={e => {
action('onSubmit')(Object.fromEntries(new FormData(e.target as HTMLFormElement).entries()));
e.preventDefault();
}}
{...props}>
<TextField name="first-name" label="First Name (controlled)" value={firstName} onChange={setFirstName} />
<TextField name="last-name" label="Last Name (uncontrolled)" defaultValue="world" />
<TextField name="street-address" label="Street Address (uncontrolled)" />
<Picker name="country" label="Country (uncontrolled)" items={countries}>
{item => <Item key={item.name}>{item.name}</Item>}
</Picker>
<NumberField name="age" label="Age (uncontrolled)" />
<NumberField name="money" label="Money (controlled)" formatOptions={{style: 'currency', currency: 'USD'}} value={money} onChange={setMoney} />
<Picker name="favorite-color" label="Favorite color (controlled)" selectedKey={favoriteColor} onSelectionChange={setFavoriteColor}>
<Item key="red">Red</Item>
<Item key="orange">Orange</Item>
<Item key="yellow">Yellow</Item>
<Item key="green">Green</Item>
<Item key="blue">Blue</Item>
<Item key="purple">Purple</Item>
</Picker>
<Checkbox name="is-hunter" isSelected={isHunter} onChange={setIsHunter}>I am a hunter! (controlled)</Checkbox>
<Checkbox name="is-wizard" defaultSelected>I am a wizard! (uncontrolled)</Checkbox>
<Switch name="airplane-mode">Airplane mode (uncontrolled)</Switch>
<Switch name="super-speed" isSelected={superSpeed} onChange={setSuperSpeed}>Super speed (controlled)</Switch>
<RadioGroup label="Favorite pet (controlled)" name="favorite-pet-group" value={favoritePet} onChange={setFavoritePet}>
<Radio value="dogs">Dogs</Radio>
<Radio value="cats">Cats</Radio>
<Radio value="dragons">Dragons</Radio>
</RadioGroup>
<RadioGroup label="Favorite pet (uncontrolled)" name="favorite-pet-group2" defaultValue="cats">
<Radio value="dogs">Dogs</Radio>
<Radio value="cats">Cats</Radio>
<Radio value="dragons">Dragons</Radio>
</RadioGroup>
<TextArea name="comments-controlled" label="Comments (controlled)" value={howIFeel} onChange={setHowIFeel} />
<TextArea name="comments-uncontrolled" label="Comments (uncontrolled)" defaultValue="hello" />
<ComboBox label="Favorite Animal (uncontrolled)" name="favorite-animal" formValue="key">
<Item key="red panda">Red Panda</Item>
<Item key="aardvark">Aardvark</Item>
<Item key="kangaroo">Kangaroo</Item>
<Item key="snake">Snake</Item>
</ComboBox>
<DateField name="date-uncontrolled" label="Birth date (uncontrolled)" />
<DateField name="date-controlled" label="Birth date (controlled)" value={birthday} onChange={setBirthday} />
<DateRangePicker startName="trip-start" endName="trip-end" label="Trip dates (uncontrolled)" />
<Slider name="cookies" label="Cookies (uncontrolled)" defaultValue={50} />
<ButtonGroup>
<Button variant="primary" type="submit">Submit</Button>
<Button variant="secondary" type="reset">Reset</Button>
</ButtonGroup>
</Form>
);
}
function FormWithSubmit() {
let [policies, setPolicies] = useState<string[]>([]);
let [policiesDirty, setPoliciesDirty] = useState(false);
let [pet, setPet] = useState('');
let [petDirty, setPetDirty] = useState(false);
let [truth, setTruth] = useState(false);
let [truthDirty, setTruthDirty] = useState(false);
let [email, setEmail] = useState('');
let [emailDirty, setEmailDirty] = useState(false);
let [formStatus, setFormStatus] = useState<'progress' | 'invalid' | 'valid' | 'fixing'>('progress');
let [isSubmitted, setSubmitted] = useState(false); // TODO: really should be isSectionInvalid / 'fixing' for each form field. once form is submitted with mistakes, unchecking an unrelated, previously valid field should not make it look invalid.
let getValidationState = (isValid: boolean): ValidationState | undefined =>
['invalid', 'fixing'].includes(formStatus) && !isValid ? 'invalid' : undefined;
useEffect(() => {
let validate = (): boolean => policies.length === 3 && !!pet && truth && email.includes('@');
let formDirty = policiesDirty || petDirty || truthDirty || emailDirty;
if (isSubmitted) {
if (formDirty) {
setFormStatus('fixing');
} else {
setFormStatus(validate() ? 'valid' : 'invalid');
}
} else {
setFormStatus('progress');
}
}, [policies, policiesDirty, pet, petDirty, truth, truthDirty, email, emailDirty, isSubmitted]);
let Status = ({formStatus}) => {
let [variant, setVariant] = useState<'info' | 'negative' | 'positive' | 'notice'>('info');
useEffect(() => {
switch (formStatus) {
case 'invalid':
return setVariant('negative');
case 'valid':
return setVariant('positive');
case 'fixing':
return setVariant('notice');
default:
return setVariant('info');
}
}, [formStatus]);
return (
<StatusLight variant={variant}>
{formStatus === 'progress' && 'In progress'}
{formStatus === 'valid' && 'Submitted successfully'}
{formStatus === 'invalid' && 'Error'}
{formStatus === 'fixing' && 'Fixing mistakes'}
</StatusLight>
);
};
let handleSubmit: React.FormEventHandler<Element> = (e) => {
e.preventDefault();
setPoliciesDirty(false);
setTruthDirty(false);
setPetDirty(false);
setEmailDirty(false);
setSubmitted(true);
action('onSubmit')(e);
};
let reset = () => {
setSubmitted(false);
setPolicies([]);
setPet('');
setTruth(false);
setPoliciesDirty(false);
setPetDirty(false);
setTruthDirty(false);
setEmail('');
setEmailDirty(false);
setFormStatus('progress');
};
return (
<Form onSubmit={handleSubmit} isReadOnly={formStatus === 'valid'}>
<>
{(formStatus === 'invalid' || formStatus === 'valid') &&
<InlineAlert variant={formStatus === 'invalid' ? 'negative' : 'positive'}>
<Header>{formStatus === 'invalid' ? 'Error' : 'Success'}</Header>
<Content>{formStatus === 'invalid' ? 'There was an error with the form.' : 'Form was successfully completed.'}</Content>
</InlineAlert>
}
</>
<TextField
label="Email address"
type="email"
value={email}
onChange={chain(() => setEmailDirty(true), setEmail)}
validationState={getValidationState(email.includes('@'))}
errorMessage="Email address must contain @" />
<CheckboxGroup
label="Agree to the following"
isRequired
value={policies}
onChange={chain(() => setPoliciesDirty(true), setPolicies)}>
<Checkbox
value="terms"
isRequired
isInvalid={getValidationState(policies.includes('terms')) === 'invalid'}>
Terms and conditions
</Checkbox>
<Checkbox
value="privacy"
isRequired
isInvalid={getValidationState(policies.includes('privacy')) === 'invalid'}>
Privacy policy
</Checkbox>
<Checkbox
value="cookies"
isRequired
isInvalid={getValidationState(policies.includes('cookies')) === 'invalid'}>
Cookie policy
</Checkbox>
</CheckboxGroup>
<Checkbox
isRequired
value="truth"
isSelected={truth}
onChange={(chain(() => setTruthDirty(true), setTruth))}
isInvalid={getValidationState(truth) === 'invalid'}>
I am telling the truth
</Checkbox>
<RadioGroup
label="Favorite pet"
isRequired
value={pet}
onChange={chain(() => setPetDirty(true), setPet)}
isInvalid={getValidationState(Boolean(pet)) === 'invalid'}>
<Radio value="dogs">
Dogs
</Radio>
<Radio value="cats">
Cats
</Radio>
<Radio value="dragons">
Dragons
</Radio>
</RadioGroup>
<TagGroup label="Favorite tags">
<Item key="1">Cool Tag 1</Item>
<Item key="2">Cool Tag 2</Item>
<Item key="3">Cool Tag 3</Item>
<Item key="4">Cool Tag 4</Item>
<Item key="5">Cool Tag 5</Item>
<Item key="6">Cool Tag 6</Item>
</TagGroup>
<Button variant="cta" type="submit" isDisabled={formStatus === 'valid'}>Submit</Button>
<Button variant="secondary" type="reset" onPress={reset}>Reset</Button>
<Status formStatus={formStatus} />
</Form>
);
}
export const NativeValidation = () => render({
isRequired: true,
validationBehavior: 'native',
showSubmit: true,
onSubmit: (e) => {
e.preventDefault();
action('onSubmit')(Object.fromEntries(new FormData(e.target as HTMLFormElement).entries()));
}
});
NativeValidation.story = {
parameters: {description: {data: 'This story is to test that client validation occurs on form submit and updates when the user commits changes to a field value (e.g. on blur).'}}
};
export function ServerValidation() {
let [serverErrors, setServerErrors] = useState<any>({});
let onSubmit = async (e) => {
e.preventDefault();
let errors = {};
for (let el of e.target.elements) {
errors[el.name] = `Invalid value for "${el.name}".`;
}
setServerErrors(errors);
};
return render({
validationBehavior: 'native',
onSubmit,
validationErrors: serverErrors,
showSubmit: true
});
}
ServerValidation.story = {
parameters: {description: {data: 'This story is to test that server errors appear after submission, and are cleared when a field is modified.'}}
};
export let NumberFieldFormSubmit = {
render: () => {
return (
<Form
onSubmit={(e) => {
e.preventDefault();
action('submitted the form')();
}}>
<NumberField label="Number" name="number" />
</Form>
);
},
parameters: {description: {data: 'Try using "Enter" to submit the form from the NumberField. It should call an action in the actions panel.'}}
};