This repository is currently being migrated. It's locked while the migration is in progress.
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathva-file-input-multiple-uswds.stories.tsx
More file actions
824 lines (750 loc) · 25.8 KB
/
va-file-input-multiple-uswds.stories.tsx
File metadata and controls
824 lines (750 loc) · 25.8 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
import { useEffect, useRef, useState } from 'react';
import { VaFileInputMultiple } from '@department-of-veterans-affairs/web-components/react-bindings';
import { getWebComponentDocs, propStructure, StoryDocs } from './wc-helpers';
// @ts-ignore ignores "module not found" error
import testImage from './images/search-bar.png';
VaFileInputMultiple.displayName = 'VaFileInputMultiple';
const fileInputMultipleDocs = getWebComponentDocs('va-file-input-multiple');
export default {
title: 'Components/File input multiple USWDS',
id: 'uswds/va-file-input-multiple',
parameters: {
componentSubtitle: 'va-file-input-multiple web component',
docs: {
page: () => (
<StoryDocs storyDefault={Default} data={fileInputMultipleDocs} />
),
},
storyType: 'form',
},
};
const defaultArgs = {
'label': 'Select a file to upload',
'name': 'my-file-input',
'accept': null,
'required': false,
'errors': [],
'encrypted': [],
'enable-analytics': false,
'hint': 'You can upload a .pdf, .gif, .jpg, .bmp, or .txt file.',
'vaMultipleChange': null,
'header-size': null,
'children': null,
'value': null,
'read-only': false,
'slotFieldIndexes': null,
'disablePasswordSubmitButtonPattern': false,
};
const Template = ({
label,
name,
accept,
errors,
encrypted,
required,
hint,
enableAnalytics,
vaMultipleChange,
headerSize,
value,
readOnly,
children,
slotFieldIndexes,
disablePasswordSubmitButton,
}) => {
return (
<VaFileInputMultiple
label={label}
name={name}
accept={accept}
required={required}
errors={errors}
encrypted={encrypted}
hint={hint}
enable-analytics={enableAnalytics}
onVaMultipleChange={vaMultipleChange}
header-size={headerSize}
value={value}
read-only={readOnly}
children={children}
slot-field-indexes={slotFieldIndexes}
disablePasswordSubmitButtonPattern={disablePasswordSubmitButton}
/>
);
};
export const Default = Template.bind(null);
Default.args = { ...defaultArgs };
Default.argTypes = propStructure(fileInputMultipleDocs);
export const Accept = Template.bind(null);
Accept.args = {
...defaultArgs,
label: 'Select PDF files',
hint: 'All files in this list must be PDFs',
accept: '.pdf',
};
// Snapshots disabled because visual difference is only apparent after interaction.
// TODO: Enable snapshots after integrating Storybook play function
Accept.parameters = {
chromatic: { disableSnapshot: true },
};
export const HeaderSize = Template.bind(null);
HeaderSize.args = {
...defaultArgs,
label: 'Custom sized header',
hint: 'Numbers from 1-6 correspond to an H1-H6 tag',
headerSize: 1,
};
const additionalFormInputsContent = (
<div>
<va-select label="What kind of file is this?" name="fileType" required>
<option key="1" value="1">
Public Document
</option>
<option key="2" value="2">
Private Document
</option>
</va-select>
</div>
);
const AdditionalFormInputsContentTemplate = ({
label,
name,
accept,
errors,
required,
hint,
'enable-analytics': enableAnalytics,
vaMultipleChange,
headerSize,
slotFieldIndexes,
children,
}) => {
return (
<>
<VaFileInputMultiple
label={label}
name={name}
accept={accept}
required={required}
errors={errors}
hint={hint}
enable-analytics={enableAnalytics}
onVaMultipleChange={vaMultipleChange}
slot-field-indexes={slotFieldIndexes}
header-size={headerSize}
>
{children}
</VaFileInputMultiple>
<hr />
<div>
<p>
You can collect additional information about an uploaded file by
passing inputs to the slot of this component. The slot content will
render after a file is uploaded.
</p>
<p>
This example showcases how to include custom content, such as
dropdowns, within the file input component.
</p>
</div>
<div className="vads-u-margin-top--2">
<pre className="vads-u-font-size--sm vads-u-background-color--gray-lightest vads-u-padding--2">
<code>
{`const additionalFormInputsContent = (
<div>
<va-select label='What kind of file is this?' required>
<option key="1" value="1">Public Document</option>
<option key="2" value="2">Private Document</option>
</va-select>
</div>
);
<VaFileInputMultiple ... >
{additionalFormInputsContent}
</VaFileInputMultiple>`}
</code>
</pre>
<a
href="https://github.com/department-of-veterans-affairs/component-library/tree/main/packages/storybook/stories"
target="_blank"
>
View validation code in our repo
</a>
</div>
</>
);
};
export const AdditionalFormInputs =
AdditionalFormInputsContentTemplate.bind(null);
AdditionalFormInputs.args = {
...defaultArgs,
label: 'Additional Form Inputs',
children: additionalFormInputsContent,
};
// Snapshots disabled because visual difference is only apparent after interaction.
// TODO: Enable snapshots after integrating Storybook play function
AdditionalFormInputs.parameters = {
chromatic: { disableSnapshot: true },
};
const AdditionalFormInputsOnSpecificFieldsContentTemplate = ({
label,
name,
accept,
errors,
required,
hint,
'enable-analytics': enableAnalytics,
vaMultipleChange,
headerSize,
slotFieldIndexes,
children,
}) => {
return (
<>
<VaFileInputMultiple
label={label}
name={name}
accept={accept}
required={required}
errors={errors}
hint={hint}
enable-analytics={enableAnalytics}
onVaMultipleChange={vaMultipleChange}
slotFieldIndexes={slotFieldIndexes}
header-size={headerSize}
>
{children}
</VaFileInputMultiple>
<hr />
<div>
<p>
This example showcases how to only render additional content for
specific file input fields.
</p>
</div>
<div className="vads-u-margin-top--2">
<pre className="vads-u-font-size--sm vads-u-background-color--gray-lightest vads-u-padding--2">
<code>
{`const additionalFormInputsContent = (
<div>
<va-select label='What kind of file is this?' required>
<option key="1" value="1">Public Document</option>
<option key="2" value="2">Private Document</option>
</va-select>
</div>
);
<VaFileInputMultiple slot-field-indexes="[1,3]" ... >
{additionalFormInputsContent}
</VaFileInputMultiple>`}
</code>
</pre>
</div>
</>
);
};
export const AdditionalFormInputsOnSpecificFields =
AdditionalFormInputsOnSpecificFieldsContentTemplate.bind(null);
AdditionalFormInputsOnSpecificFields.args = {
...defaultArgs,
label: 'Additional Form Inputs On Specific Inputs',
children: additionalFormInputsContent,
slotFieldIndexes: '[1,3]',
};
// Snapshots disabled because visual difference is only apparent after interaction.
// TODO: Enable snapshots after integrating Storybook play function
AdditionalFormInputsOnSpecificFields.parameters = {
chromatic: { disableSnapshot: true },
};
const ErrorsTemplate = ({ label, name, hint }) => {
const [errorsList, setErrorsList] = useState([]);
function setErrorForEachFile(event) {
const fileEntries = event.detail.state;
const errors = fileEntries.map((file, index) => {
if (!file.file) {
return '';
}
return 'Error for index ' + index;
});
setErrorsList(errors);
}
return (
<>
<VaFileInputMultiple
label={label}
name={name}
hint={hint}
errors={errorsList}
onVaMultipleChange={setErrorForEachFile}
/>
<hr />
<div>
<p>
Parent components are responsible for managing error states through a
dedicated error array. Each index in this array corresponds to a file
input, with the value at each index representing the error state for
that specific file. This setup allows for the dynamic display of
errors based on real-time validation of each file as it is processed.
</p>
</div>
<div className="vads-u-margin-top--2">
<pre className="vads-u-font-size--sm vads-u-background-color--gray-lightest vads-u-padding--2">
<code>
{`const [errorsList, setErrorsList] = useState([]);
function setErrorForEachFile(event) {
const fileEntries = event.detail.state;
const errors = fileEntries.map((file, index) => {
if (!file.file) {
return '';
}
return 'Error for index ' + index;
});
setErrorsList(errors);
}
return (
<VaFileInputMultiple
...
errors={errorsList}
onVaMultipleChange={setErrorForEachFile}
/>`}
</code>
</pre>
<a
href="https://github.com/department-of-veterans-affairs/component-library/tree/main/packages/storybook/stories"
target="_blank"
>
View validation code in our repo
</a>
</div>
</>
);
};
export const Errors = ErrorsTemplate.bind(null);
Errors.args = {
...defaultArgs,
label: 'Label Header',
};
// Snapshots disabled because visual difference is only apparent after interaction.
// TODO: Enable snapshots after integrating Storybook play function
Errors.parameters = {
chromatic: { disableSnapshot: true },
};
const CustomValidationTemplate = ({ label, name, accept, hint }) => {
const [errorsList, setErrorsList] = useState([]);
function validateFileContents(event) {
let errors = [];
const fileEntries = event.detail.state;
fileEntries.forEach(fileEntry => {
const file = fileEntry.file;
if (file) {
let error = '';
if (file.size > 2 * 1024 * 1024) {
// 2MB = 2 * 1024 * 1024 bytes
error = 'File size cannot be greater than 2MB';
}
errors.push(error);
} else {
errors.push(''); // Add an empty error if no fileEntry
}
});
setErrorsList(errors);
}
return (
<>
<VaFileInputMultiple
label={label}
name={name}
hint={hint}
errors={errorsList}
accept={accept}
onVaMultipleChange={validateFileContents}
/>
<hr />
<div>
<p>
The parent component can capture the files from the onVaMultipleChange
event, validate the files, and dynamically set errors. Each file must
have a corresponding entry in the errors array prop, even if the entry
is an empty string indicating no errors.
</p>
<p>
This example demonstrates custom validation logic to show an error if
the file size exceeds 2MB. Validation occurs when a file is added or
removed.{' '}
</p>
</div>
<div className="vads-u-margin-top--2">
<pre className="vads-u-font-size--sm vads-u-background-color--gray-lightest vads-u-padding--2">
<code>
{`const [errorsList, setErrorsList] = useState([]);
function validateFileContents(event) {
let errors = [];
const fileEntries = event.detail.state;
fileEntries.forEach(fileEntry => {
const file = fileEntry.file;
if (file) {
let error = '';
if (file.size > 2 * 1024 * 1024) {
// 2MB = 2 * 1024 * 1024 bytes
error = 'File size cannot be greater than 2MB';
}
errors.push(error);
} else {
errors.push(''); // Add an empty error if no fileEntry
}
});
setErrorsList(errors);
}
<VaFileInputMultiple
...
errors={errorsList}
onVaMultipleChange={validateFileContents}
/>`}
</code>
</pre>
<a
href="https://github.com/department-of-veterans-affairs/component-library/tree/main/packages/storybook/stories"
target="_blank"
>
View validation code in our repo
</a>
</div>
</>
);
};
export const CustomValidation = CustomValidationTemplate.bind(null);
CustomValidation.args = {
...defaultArgs,
label: 'Upload files which are smaller than 2 MB',
hint: 'Select any file type',
};
// Snapshots disabled because visual difference is only apparent after interaction.
// TODO: Enable snapshots after integrating Storybook play function
CustomValidation.parameters = {
chromatic: { disableSnapshot: true },
};
const EncryptedTemplate = ( {label, name, disablePasswordSubmitButtonPattern }) => {
const [trackedFiles, setTrackedFiles] = useState([]);
const [encryptedList, setEncryptedList] = useState([]);
const [passwordSubmissionSuccessList, setPasswordSubmissionSuccessList] = useState<boolean[]>([]);
const [derivedPasswordErrorList, setDerivedPasswordErrorList] = useState<string[]>([]);
/**
* Callback passed to onVaMultipleChange to track the file objects for each
* file input, and update the encryptedList based on the file types of the
* tracked files. The encryptedList is used to determine whether a password
* field should be displayed for each file input.
* @param event The custom event emitted by the va-file-input-multiple component.
* @returns {void}
*/
function handleChange(event: CustomEvent<{
action: string;
file?: File;
index?: number }>
): void {
const { detail } = event;
const trackedFilesToSet = [...trackedFiles];
const trackedPasswordSubmissionSuccessList = [
...passwordSubmissionSuccessList
];
const currentDerivedPasswordErrorList = [...derivedPasswordErrorList];
// Add new file to trackedFiles if action is FILE_ADDED
if (detail.action === 'FILE_ADDED') {
trackedFilesToSet.push(detail.file);
if (detail.file.type === 'application/pdf') {
trackedPasswordSubmissionSuccessList.push(null);
}
} else if (detail.action === 'FILE_UPDATED' && detail.file) {
// If an existing file is updated successfully, replace the corresponding
// error object in trackedFiles with the file
const indexToUpdate = trackedFilesToSet.findIndex(
file => file.name === detail.file.name,
);
if (indexToUpdate !== -1) {
trackedFilesToSet[indexToUpdate] = detail.file;
trackedPasswordSubmissionSuccessList[indexToUpdate] = null;
}
} else if (detail.action === 'FILE_REMOVED' && detail.file) {
// Remove file from trackedFiles if action is FILE_REMOVED when a valid
// file is removed
const indexToRemove = trackedFilesToSet.findIndex(
file => file.name === detail.file.name,
);
if (indexToRemove !== -1) {
trackedFilesToSet.splice(indexToRemove, 1);
// Remove index from success submission list and derived error list to
// ensure password submission/error state is cleared for deleted file
trackedPasswordSubmissionSuccessList.splice(indexToRemove, 1);
currentDerivedPasswordErrorList.splice(indexToRemove, 1);
}
} else if (detail.action === 'FILE_REMOVED' && !detail.file) {
// If an error file was deleted, remove the corresponding file from
// trackedFiles
const indexToRemove = trackedFilesToSet.findIndex(
file => file.index === detail.index,
);
if (indexToRemove !== -1) {
trackedFilesToSet.splice(indexToRemove, 1);
// Remove index from success submission list and derived error list to
// ensure password submission/error state is cleared for deleted file
trackedPasswordSubmissionSuccessList.splice(indexToRemove, 1);
currentDerivedPasswordErrorList.splice(indexToRemove, 1);
}
} else if (detail.action === 'PASSWORD_UPDATE') {
// Update value at index of file that password was updated to null to
// enable validation to take place again at va-file-input level.
const indexToUpdate = trackedFilesToSet.findIndex(
file => file.name === detail.file.name,
);
if (indexToUpdate !== -1) {
trackedPasswordSubmissionSuccessList[indexToUpdate] = null;
}
}
const pdfFiles = trackedFilesToSet.map((file) => {
return file.type === 'application/pdf'
});
setPasswordSubmissionSuccessList(trackedPasswordSubmissionSuccessList);
setDerivedPasswordErrorList(currentDerivedPasswordErrorList);
setEncryptedList(pdfFiles);
setTrackedFiles(trackedFilesToSet);
}
function handleError(event: CustomEvent<{
index: number;
error: string
}>): void {
const { index, error } = event.detail;
let trackedFilesToSet = [...trackedFiles];
// If index of error is greater than length of trackedFiles, we know this
// error is for a new file input that has not been added to trackedFiles
// yet, so we add it to the end of trackedFiles. Otherwise, we update the
// existing file input at the index of the error with the error.
if (index >= trackedFiles.length) {
trackedFilesToSet.push({ index, error });
} else {
trackedFilesToSet[index] = {
index,
error,
}
}
const pdfFiles = trackedFilesToSet.map((file) => {
return file.type === 'application/pdf'
});
setEncryptedList(pdfFiles);
setTrackedFiles(trackedFilesToSet);
}
const handlePasswordSubmissionSuccessClick = (index: number, isSuccess: boolean = false) => {
const currentState = [...passwordSubmissionSuccessList];
currentState[index] = isSuccess;
if (!isSuccess) {
const currentDerivedPasswordErrorList = [...derivedPasswordErrorList];
currentDerivedPasswordErrorList[index] = 'Incorrect password. Try again or delete file.';
setDerivedPasswordErrorList(currentDerivedPasswordErrorList);
}
setPasswordSubmissionSuccessList(currentState);
}
return (
<>
To learn how to check for an encrypted PDF <va-link
text='see platform documentation'
href='https://depo-platform-documentation.scrollhelp.site/developer-docs/checking-if-an-uploaded-pdf-is-encrypted'
/>.
<VaFileInputMultiple
label={label}
name={name}
hint={"This example shows a password field when a .pdf file is uploaded."}
encrypted={encryptedList}
passwordSubmissionSuccessList={passwordSubmissionSuccessList}
passwordErrors={derivedPasswordErrorList}
onVaMultipleChange={handleChange}
onVaMultipleError={handleError}
disablePasswordSubmitButtonPattern={disablePasswordSubmitButtonPattern}
/>
<hr />
<p>Password submission list: {JSON.stringify(passwordSubmissionSuccessList)}</p>
{ !disablePasswordSubmitButtonPattern &&
(<div
className="vads-u-display--flex vads-u-flex-direction--column vads-u-margin--2 vads-u-border--1px vads-u-border-color--gray-light vads-u-padding--2"
style={{ width: 'fit-content' }}
>
<p className="vads-u-margin-y--0">
Simulate checking of submitted password for uploaded <strong>encrypted (PDF)</strong> files. Simulation is done
by updating the <code>passwordSubmissionSuccessList</code> prop based on button clicks below.
</p>
<em>Each pair of buttons controls the password submission status for the corresponding encrypted file in the file list.</em>
{
encryptedList?.length ? (
<ul>
{encryptedList.map((isEncrypted, index) => {
if (isEncrypted) {
return (
<li key={index}>
<div className="vads-u-display--flex vads-u-align-items--center vads-u-gap--2 vads-u-margin-bottom--1">
<p className="vads-u-margin-y--0 vads-u-margin-right--2">File {index + 1}</p>
<va-button
class="vads-u-margin-y--1"
text="Set success"
onClick={() => handlePasswordSubmissionSuccessClick(index, true)}
/>
<va-button
text="Set error"
onClick={() => handlePasswordSubmissionSuccessClick(index, false)}
/>
</div>
</li>
);
}
})}
</ul>
) : null
}
</div>)
}
<div>
<p>
Parent components are responsible for managing if a password
needs to be requested for the file through a dedicated encrypted
array. Each index in this array corresponds to a file input,
with the value at each index being true if a password should
be requested for that specific file, or false if no password is
needed. By default, no password field will be displayed. This
setup allows for the dynamic display of a password field based
on real-time validation of each file as it is processed. Passwords
are passed through the <code>onVaMultipleChange</code> event.
</p>
</div>
<div className="vads-u-margin-top--2">
<pre className="vads-u-font-size--sm vads-u-background-color--gray-lightest vads-u-padding--2">
<code>
{`
const [encryptedList, setEncryptedList] = useState([]);
function setEncryptedForEachFile(event) {
const fileEntries = event.detail.state;
const pdfFiles = fileEntries.map((file, index) => {
return file.file.type === 'application/pdf'
});
setEncryptedList(pdfFiles);
}
return (
<VaFileInputMultiple
...
encrypted={encryptedList}
onVaMultipleChange={setEncryptedForEachFile}
/>
);
`}
</code>
</pre>
<a
href="https://github.com/department-of-veterans-affairs/component-library/tree/main/packages/storybook/stories"
target="_blank"
>
View validation code in our repo
</a>
</div>
</>
);
};
export const AcceptsFilePassword = EncryptedTemplate.bind(null);
AcceptsFilePassword.args = {...defaultArgs};
// Snapshots disabled because visual difference is only apparent after interaction.
// TODO: Enable snapshots after integrating Storybook play function
AcceptsFilePassword.parameters = {
chromatic: { disableSnapshot: true },
};
export const AcceptsFilePasswordWithoutSubmitButton = EncryptedTemplate.bind(null);
AcceptsFilePasswordWithoutSubmitButton.args = {
...defaultArgs,
disablePasswordSubmitButtonPattern: true,
};
// Snapshots disabled because visual difference is only apparent after interaction.
// TODO: Enable snapshots after integrating Storybook play function
AcceptsFilePasswordWithoutSubmitButton.parameters = {
chromatic: { disableSnapshot: true },
};
const FilesUploadedTemplate = args => {
const [mockFiles, setMockFiles] = useState(null);
useEffect(() => {
let isMounted = true;
const loadImage = async () => {
const response = await fetch(testImage);
const blob = await response.blob();
const file1 = new File([blob], 'test1.jpg', { type: 'image/jpeg' });
const file2 = new File([blob], 'test2.jpg', { type: 'image/jpeg' });
if (isMounted) {
// @ts-ignore
setMockFiles([file1, file2]);
}
};
loadImage();
return () => {
isMounted = false;
};
}, []);
return <Template {...args} value={mockFiles} />;
};
export const FilesUploaded = FilesUploadedTemplate.bind(null);
FilesUploaded.args = { ...defaultArgs, vaMultipleChange: event => event };
export const ReadOnly = FilesUploadedTemplate.bind(null);
ReadOnly.args = {
...defaultArgs,
vaMultipleChange: event => event,
readOnly: true,
};
const readOnlyAdditionalInfoContent = (
<dl>
<dt style={{ marginTop: '1rem' }}>What kind of file is this?</dt>
<dd style={{ marginTop: '.5rem', marginLeft: '0' }}>Public Document</dd>
</dl>
);
export const ReadOnlyWithAdditionalInputs = FilesUploadedTemplate.bind(null);
ReadOnlyWithAdditionalInputs.args = {
...defaultArgs,
vaMultipleChange: event => event,
readOnly: true,
children: readOnlyAdditionalInfoContent,
};
// Mock upload progress per file
// Note: `index` in the event is the pageIndex from the unfiltered internal files array,
// which matches how va-file-input-multiple indexes into the percentUploaded prop.
const PercentUploadedTemplate = args => {
const [percents, setPercents] = useState<number[]>([]);
const intervalsRef = useRef<{ [key: number]: ReturnType<typeof setInterval> }>({});
function startInterval(index: number) {
clearInterval(intervalsRef.current[index]);
delete intervalsRef.current[index];
setPercents(prev => { const u = [...prev]; u[index] = null; return u; });
intervalsRef.current[index] = setInterval(() => {
setPercents(prev => {
const updated = [...prev];
const current = updated[index] ?? 0;
if (current >= 100) {
clearInterval(intervalsRef.current[index]);
delete intervalsRef.current[index];
updated[index] = 100;
} else {
updated[index] = current + Math.random() * 4;
}
return updated;
});
}, 100);
}
function handleUpload(event) {
const { action, index: changedIndex } = event.detail;
if (action === 'FILE_ADDED' || action === 'FILE_UPDATED') {
startInterval(changedIndex);
} else if (action === 'FILE_REMOVED') {
clearInterval(intervalsRef.current[changedIndex]);
delete intervalsRef.current[changedIndex];
setPercents(prev => { const u = [...prev]; u.splice(changedIndex, 1); return u; });
}
}
return (
<VaFileInputMultiple
{...args}
percentUploaded={percents}
onVaMultipleChange={handleUpload}
/>
);
};
export const WithPercentUploaded = PercentUploadedTemplate.bind(null);
WithPercentUploaded.args = { ...defaultArgs };
WithPercentUploaded.parameters = {
chromatic: { disableSnapshot: true },
};