-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileInput.tsx
More file actions
328 lines (302 loc) · 9.91 KB
/
FileInput.tsx
File metadata and controls
328 lines (302 loc) · 9.91 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
import type { DropEvent, FileDropItem } from '@react-types/shared';
import { UploadIcon, XIcon } from 'lucide-react';
import { useState } from 'react';
import {
Button as AriaButton,
DropZone as AriaDropZone,
FileTrigger as AriaFileTrigger,
type FileTriggerProps as AriaFileTriggerProps,
GridList,
GridListItem,
TooltipTrigger,
type ValidationResult,
} from 'react-aria-components';
import { twMerge } from 'tailwind-merge';
import { tv } from 'tailwind-variants';
import { Button } from './Button';
import { Description, Label } from './Field';
import { Tooltip } from './Tooltip';
import { focusRing } from './utils';
export interface FileInputProps
extends Omit<AriaFileTriggerProps, 'children' | 'onSelect'> {
label?: string;
description?: string;
errorMessage?: string | ((validation: ValidationResult) => string);
isRequired?: boolean;
isDisabled?: boolean;
isInvalid?: boolean;
/**
* Text to display in the drop zone when no files are selected
*/
placeholder?: string;
/**
* Show file size in the selected files list
*/
showFileSize?: boolean;
/**
* Custom class for the drop zone container
*/
className?: string;
/**
* Controlled value - the current files selected.
* When provided, the component becomes controlled.
*/
value?: File[] | null;
/**
* Callback when files change.
* We use onChange rather than onSelect to make it clear that we are diverting from AriaFileTrigger which doesn't support being controlled
*/
onChange?: (files: File[] | null) => void;
}
const labelStyles = tv({
variants: {
isRequired: {
true: "after:ml-0.5 after:text-warning-500 after:content-['*'] after:dark:text-warning-300",
},
},
});
const dropZoneStyles = tv({
base: 'group flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed bg-white p-4 text-center outline-none transition-colors hover:border-primary-900 hover:bg-zinc-50 dark:bg-zinc-900 dark:hover:border-secondary-600 dark:hover:bg-zinc-800',
variants: {
isDisabled: {
true: 'cursor-not-allowed border-gray-200 bg-gray-50 hover:border-gray-200 hover:bg-gray-50 dark:border-zinc-700 dark:bg-zinc-800 dark:hover:border-zinc-700 dark:hover:bg-zinc-800',
false: 'border-zinc-300 dark:border-zinc-600',
},
isInvalid: {
true: 'border-warning-600 hover:border-warning-700 dark:border-warning-600 dark:hover:border-warning-500',
},
isDropTarget: {
true: 'border-primary-900 bg-primary-50 dark:border-secondary-600 dark:bg-secondary-900/20',
},
},
});
const buttonStyles = tv({
extend: focusRing,
base: 'flex w-full flex-col items-center justify-center gap-2 rounded-md font-normal',
});
const iconStyles = tv({
base: 'size-8',
variants: {
isDisabled: {
true: 'text-gray-300 dark:text-zinc-600',
false: 'text-zinc-400 dark:text-zinc-500',
},
},
});
const textStyles = tv({
base: 'text-sm',
variants: {
isDisabled: {
true: 'text-gray-400 dark:text-zinc-600',
false: 'text-zinc-600 dark:text-zinc-400',
},
},
});
const fileItemStyles = tv({
extend: focusRing,
base: 'flex cursor-default items-center justify-between gap-2 rounded-md border bg-white px-3 py-2 text-sm outline-none dark:bg-zinc-800',
variants: {
isSelected: {
true: 'border-primary-900 bg-primary-50 dark:border-secondary-600 dark:bg-secondary-900/20',
false: 'border-zinc-200 dark:border-zinc-700',
},
isFocusVisible: {
true: 'outline-2',
false: 'outline-0',
},
isDisabled: {
true: 'opacity-50',
},
},
});
function formatFileSize(bytes: number): string {
if (bytes === 0) {
return '0 Bytes';
}
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
}
function matchesAcceptedType(
fileType: string,
acceptedTypes: readonly string[],
): boolean {
return acceptedTypes.some((accepted) => {
if (accepted.endsWith('/*')) {
const prefix = accepted.slice(0, -2);
return fileType.startsWith(prefix + '/');
}
return fileType === accepted;
});
}
export function FileInput({
label,
description,
errorMessage,
isRequired,
isDisabled,
isInvalid,
placeholder = 'Drag a file here or click to upload',
showFileSize = true,
className,
allowsMultiple,
acceptedFileTypes,
value,
onChange,
...props
}: FileInputProps) {
const isControlled = value !== undefined;
const [internalFiles, setInternalFiles] = useState<File[]>([]);
// Use controlled value if provided, otherwise use internal state
const selectedFiles = isControlled ? (value ?? []) : internalFiles;
const updateFiles = (files: File[] | null) => {
if (!isControlled) {
setInternalFiles(files ?? []);
}
onChange?.(files);
};
const handleSelect = (fileList: FileList | null) => {
if (fileList) {
const files = Array.from(fileList);
updateFiles(files);
}
};
const handleDrop = async (e: DropEvent) => {
// Filter for files only
const filePromises = e.items
.filter((item): item is FileDropItem => item.kind === 'file')
.map((item) => item.getFile());
const files = await Promise.all(filePromises);
if (files.length > 0) {
// If not allowing multiple, only take the first file
const filesToAdd = allowsMultiple ? files : files.slice(0, 1);
// Filter by accepted file types if specified
const filteredFiles = acceptedFileTypes
? filesToAdd.filter((file) =>
matchesAcceptedType(file.type, acceptedFileTypes),
)
: filesToAdd;
if (filteredFiles.length > 0) {
updateFiles(filteredFiles);
}
}
};
const removeFile = (index: number) => {
const updated = selectedFiles.filter((_, i) => i !== index);
updateFiles(updated.length === 0 ? null : updated);
};
const clearFiles = () => {
updateFiles(null);
};
return (
<div className={twMerge('flex flex-col gap-1', className)}>
{/* We wrap the file trigger in a label to make sure that the label is associated with its hidden input for a11y */}
<Label className="flex flex-col gap-1">
{label && (
<span className={labelStyles({ isRequired: Boolean(isRequired) })}>
{label}
</span>
)}
{description && (
<Description className="font-normal">{description}</Description>
)}
<AriaDropZone
onDrop={handleDrop}
className={(renderProps) =>
dropZoneStyles({
...renderProps,
isDisabled,
isInvalid,
})
}
>
<AriaFileTrigger
{...props}
allowsMultiple={allowsMultiple}
acceptedFileTypes={acceptedFileTypes}
onSelect={handleSelect}
>
<AriaButton isDisabled={isDisabled} className={buttonStyles}>
<UploadIcon className={iconStyles({ isDisabled })} />
<div className={textStyles({ isDisabled })}>{placeholder}</div>
</AriaButton>
</AriaFileTrigger>
</AriaDropZone>
</Label>
{selectedFiles.length > 0 && !isDisabled && (
<div className="mt-2 space-y-2">
<div className="flex items-center justify-between">
<div className="text-sm font-medium text-zinc-700 dark:text-zinc-300">
{selectedFiles.length}{' '}
{selectedFiles.length === 1 ? 'file' : 'files'} selected
</div>
<Button
onPress={clearFiles}
isDisabled={isDisabled}
size="extraSmall"
variant="secondary"
>
Clear all
</Button>
</div>
<GridList aria-label="Selected files" className="space-y-1">
{selectedFiles.map((file, index) => (
<GridListItem
key={`${file.name}-${file.size}-${file.lastModified}`}
textValue={file.name}
className={(renderProps) => fileItemStyles(renderProps)}
>
<div className="flex min-w-0 flex-1 flex-col">
<div className="truncate font-medium text-zinc-800 dark:text-zinc-200">
{file.name}
</div>
{showFileSize && (
<div className="text-xs text-zinc-500 dark:text-zinc-400">
{formatFileSize(file.size)}
</div>
)}
</div>
<TooltipTrigger>
<Button
variant="icon"
onPress={() => removeFile(index)}
isDisabled={isDisabled}
className="rounded"
aria-label={`Remove ${file.name}`}
>
<XIcon className="h-4 w-4 text-zinc-600 dark:text-zinc-400" />
</Button>
<Tooltip>Remove {file.name}</Tooltip>
</TooltipTrigger>
</GridListItem>
))}
</GridList>
</div>
)}
{errorMessage && (
<div className="text-sm text-warning-600 dark:text-warning-500">
{typeof errorMessage === 'function'
? errorMessage({
isInvalid: isInvalid ?? false,
validationErrors: [],
validationDetails: {
badInput: false,
customError: false,
patternMismatch: false,
rangeOverflow: false,
rangeUnderflow: false,
stepMismatch: false,
tooLong: false,
tooShort: false,
typeMismatch: false,
valueMissing: false,
valid: !isInvalid,
},
})
: errorMessage}
</div>
)}
</div>
);
}