Repository navigation
Expand file tree
/
Copy pathdropzone.tsx
More file actions
351 lines (318 loc) · 14.9 KB
/
Copy pathdropzone.tsx
File metadata and controls
351 lines (318 loc) · 14.9 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
'use client';
// A styled dropzone on top of the headless useDropzone: one card, the drop area on top and the
// uploads under it. Copy this file and restyle it; everything it shows comes from the hook's result.
import type { DropzoneResult, DropzoneUpload } from '@upstash/react-dropzone';
import { useEffect, useState, type ReactNode } from 'react';
type Props<R> = {
/** What `useDropzone()` returned. */
zone: DropzoneResult<R>;
/** The line in the middle of the drop area. */
label?: ReactNode;
/** A shorter drop area, for a single file. */
compact?: boolean;
};
export function Dropzone<R>({ zone, label = 'Drop files here', compact = false }: Props<R>) {
const { getRootProps, getInputProps, isDragActive, isDragReject, isFocused, uploads, clear } = zone;
// Refused files never uploaded, so they get one line, not a row each.
const refused = uploads.filter((u) => refusal(u));
const rows = uploads.filter((u) => !refusal(u) && u.status !== 'canceled');
// A canceled upload has nothing left to show.
useEffect(() => {
for (const u of uploads) if (u.status === 'canceled') clear(u.id);
}, [uploads, clear]);
const tone = isDragReject
? 'border-rose-400 bg-rose-50/70 dark:border-rose-400/70 dark:bg-rose-400/5'
: isDragActive
? 'border-emerald-500 bg-emerald-50/70 dark:border-emerald-400 dark:bg-emerald-400/5'
: 'border-zinc-300 hover:border-zinc-400 hover:bg-zinc-50/80 dark:border-zinc-700 dark:hover:border-zinc-600 dark:hover:bg-zinc-800/30';
const iconTone = isDragReject
? '-translate-y-1 bg-white text-rose-500 dark:bg-zinc-900 dark:text-rose-400'
: isDragActive
? '-translate-y-1 bg-white text-emerald-500 dark:bg-zinc-900 dark:text-emerald-400'
: 'bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400';
return (
<div className="rounded-[20px] border border-zinc-200/80 bg-white p-2 shadow-[0_1px_2px_rgba(24,24,27,.04),0_16px_40px_-14px_rgba(24,24,27,.16)] dark:border-zinc-800 dark:bg-zinc-900 dark:shadow-[0_1px_2px_rgba(0,0,0,.4),0_16px_40px_-12px_rgba(0,0,0,.7)]">
<div
{...getRootProps({
className: `flex cursor-pointer flex-col items-center justify-center gap-2.5 rounded-xl border-[1.5px] border-dashed text-center outline-none transition-colors ${
compact ? 'py-6' : 'py-10'
} ${tone} ${isFocused ? 'ring-2 ring-emerald-500/50 ring-offset-2 ring-offset-white dark:ring-offset-zinc-900' : ''}`,
})}
>
<input {...getInputProps()} />
<div className={`grid size-11 place-items-center rounded-xl transition ${iconTone}`}>
<UploadIcon />
</div>
<p className={`text-[15px] font-semibold tracking-tight ${isDragReject ? 'text-rose-600 dark:text-rose-400' : isDragActive ? 'text-emerald-600 dark:text-emerald-400' : ''}`}>
{isDragReject ? 'Not accepted here' : isDragActive ? 'Drop to upload' : label}
</p>
<p className="-mt-1.5 min-h-5 text-sm text-zinc-500 dark:text-zinc-400">{describe(zone.constraints)}</p>
</div>
{refused.length > 0 && <RefusedLine key={refused.map((u) => u.id).join()} files={refused} onDismiss={() => refused.forEach((u) => clear(u.id))} />}
{rows.length > 0 && (
<ul className="mt-1 divide-y divide-zinc-100 px-1 dark:divide-zinc-800">
{rows.map((upload) => (
<UploadRow key={upload.id} upload={upload} onRemove={() => clear(upload.id)} />
))}
</ul>
)}
</div>
);
}
/** Why a file was refused, in a few words, or undefined when it was not. Sending it again cannot help. */
export function refusal(u: DropzoneUpload<unknown>): string | undefined {
if (u.status !== 'error') return undefined;
switch (u.error.code) {
case 'content_type_not_allowed':
return 'Type not allowed';
case 'too_large':
return 'Too large';
case 'empty_body':
return 'Empty file';
case 'invalid_input':
// maxFiles and `multiple: false` refuse with invalid_input; so does a validator.
return /too many files|one file at a time/.test(u.error.message) ? 'Too many files' : 'Not accepted';
}
return undefined;
}
/** One line for every file the last drops refused. It fades out on its own; hovering holds it. */
function RefusedLine<R>({ files, onDismiss }: { files: DropzoneUpload<R>[]; onDismiss: () => void }) {
const [hold, setHold] = useState(false);
const [fading, setFading] = useState(false);
useEffect(() => {
if (hold) return;
const fade = setTimeout(() => setFading(true), 5000);
const gone = setTimeout(onDismiss, 5500);
return () => {
clearTimeout(fade);
clearTimeout(gone);
setFading(false);
};
// A new refusal remounts this line (its key), so the timers restart then.
}, [hold]);
const reasons = [...new Set(files.map((u) => refusal(u)!))];
const reason = reasons.length > 1 ? 'Not accepted' : files.length > 1 && reasons[0] === 'Empty file' ? 'Empty files' : reasons[0];
return (
<div
onMouseEnter={() => setHold(true)}
onMouseLeave={() => setHold(false)}
title={files.map((u) => `${u.file.name}: ${u.error?.message}`).join('\n')}
role="status"
className={`mx-1 mt-2 flex items-center gap-2.5 rounded-xl bg-rose-50 py-1.5 pr-1.5 pl-3 text-sm transition-[opacity,translate] duration-500 starting:-translate-y-1 starting:opacity-0 dark:bg-rose-400/10 ${
fading ? 'opacity-0' : ''
}`}
>
<BanIcon />
<p className="min-w-0 flex-1 truncate">
<span className="font-medium text-zinc-900 dark:text-zinc-100">{files.length === 1 ? files[0]!.file.name : `${files.length} files`}</span>
<span className="ml-2 text-rose-600 dark:text-rose-400">{reason}</span>
</p>
<IconButton label="Dismiss" onClick={onDismiss} className="size-7 hover:bg-rose-100 dark:hover:bg-rose-400/10">
<XIcon />
</IconButton>
</div>
);
}
// Failures where retrying sends the same request to the same answer.
const NO_RETRY = new Set(['unauthorized', 'forbidden']);
export function UploadRow<R>({ upload: u, onRemove }: { upload: DropzoneUpload<R>; onRemove: () => void }) {
// An image type the browser cannot draw (HEIC, TIFF) shows the file icon, not a broken image.
const [undrawable, setUndrawable] = useState(false);
// All bytes are sent while the route confirms; percent holds at 99 until done, so show it full.
const percent = u.status === 'finishing' ? 100 : u.percent;
const failed = u.status === 'error';
// A few words next to the name, or nothing once it is done.
const tag =
u.status === 'error' ? 'Failed'
: u.status === 'paused' ? 'Paused'
: u.status === 'queued' ? 'Queued'
: u.status === 'idle' ? 'Ready'
: u.status === 'uploading' || u.status === 'finishing' ? (u.stalled ? 'Retrying' : `${percent}%`)
: null;
// The icon on the right, and a second one that shows on hover in place of the size.
let action: ReactNode;
let extra: ReactNode = null;
if (u.status === 'done') {
action = (
<IconButton label={`Remove ${u.file.name}`} onClick={onRemove}>
<CheckIcon className="size-5 group-hover:hidden group-has-focus-visible:hidden" />
<XIcon className="hidden size-[18px] group-hover:block group-has-focus-visible:block" />
</IconButton>
);
} else if (failed) {
if (NO_RETRY.has(u.error.code)) action = <IconButton label={`Remove ${u.file.name}`} onClick={onRemove}><XIcon /></IconButton>;
else {
action = <IconButton label={`Retry ${u.file.name}`} onClick={u.retry} tone="danger"><RetryIcon /></IconButton>;
extra = <IconButton label={`Remove ${u.file.name}`} onClick={onRemove}><XIcon /></IconButton>;
}
} else if (u.status === 'paused') {
action = <IconButton label={`Resume ${u.file.name}`} onClick={u.resume} tone="accent"><PlayIcon /></IconButton>;
extra = <IconButton label={`Cancel ${u.file.name}`} onClick={u.cancel}><XIcon /></IconButton>;
} else if (u.status === 'uploading' && u.canPause) {
action = <IconButton label={`Pause ${u.file.name}`} onClick={u.pause}><PauseIcon /></IconButton>;
extra = <IconButton label={`Cancel ${u.file.name}`} onClick={u.cancel}><XIcon /></IconButton>;
} else {
action = <IconButton label={`${u.status === 'idle' ? 'Remove' : 'Cancel'} ${u.file.name}`} onClick={u.cancel}><XIcon /></IconButton>;
}
return (
<li className="group grid grid-cols-[3rem_minmax(0,1fr)_4.5rem_2.25rem] items-center gap-x-4 py-3 pr-1 pl-1 transition-[opacity,translate] duration-300 starting:translate-y-1 starting:opacity-0">
<div className="relative grid size-12 place-items-center overflow-hidden rounded-xl bg-zinc-100 text-zinc-400 ring-1 ring-zinc-900/5 dark:bg-zinc-800 dark:text-zinc-500 dark:ring-white/5">
{u.preview && !undrawable ? (
<img src={u.preview} alt="" className="absolute inset-0 block size-full object-cover" onError={() => setUndrawable(true)} />
) : u.file.type.startsWith('video/') ? (
<FilmIcon />
) : (
<FileIcon />
)}
</div>
<div className="min-w-0">
<div className="flex items-baseline gap-2">
<p className="truncate text-[15px] font-semibold tracking-tight text-zinc-900 dark:text-zinc-100">{u.file.name}</p>
{tag && (
<span
title={failed ? u.error.message : undefined}
className={`shrink-0 text-sm font-medium tabular-nums ${failed ? 'text-rose-600 dark:text-rose-400' : 'text-zinc-500 dark:text-zinc-400'}`}
>
{tag}
</span>
)}
</div>
{u.status !== 'done' && u.status !== 'idle' && (
<div className={`mt-2 h-1.5 overflow-hidden rounded-full ${failed ? 'bg-rose-100 dark:bg-rose-400/15' : 'bg-zinc-100 dark:bg-zinc-800'}`}>
<div
className={`h-full rounded-full transition-[width,background-color] duration-300 ${
failed ? 'bg-rose-500' : u.status === 'paused' ? 'bg-zinc-300 dark:bg-zinc-600' : 'bg-emerald-500 dark:bg-emerald-400'
}`}
style={{ width: `${percent}%` }}
/>
</div>
)}
</div>
<div className="relative flex items-center justify-end">
<span className={`text-sm font-medium tabular-nums text-zinc-500 dark:text-zinc-400 ${extra ? 'group-hover:invisible group-has-focus-visible:invisible pointer-coarse:invisible' : ''}`}>
{formatBytes(u.file.size)}
</span>
{extra && (
<div className="invisible absolute right-0 group-hover:visible group-has-focus-visible:visible pointer-coarse:visible">{extra}</div>
)}
</div>
{action}
</li>
);
}
const TONES = {
muted: 'text-zinc-500 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100',
danger: 'text-rose-600 dark:text-rose-400',
accent: 'text-emerald-600 dark:text-emerald-400',
};
function IconButton(props: { label: string; onClick: () => unknown; tone?: keyof typeof TONES; className?: string; children: ReactNode }) {
const { label, onClick, tone = 'muted', className = 'size-9 hover:bg-zinc-100 dark:hover:bg-zinc-800', children } = props;
return (
<button
type="button"
aria-label={label}
title={label.split(' ')[0]}
onClick={() => onClick()}
className={`grid shrink-0 place-items-center rounded-lg outline-none transition-colors focus-visible:ring-2 focus-visible:ring-emerald-500/60 ${TONES[tone]} ${className}`}
>
{children}
</button>
);
}
/** "Images, videos or PDF up to 100 MB", from the limits the route serves. */
function describe(constraints: { contentTypes?: readonly string[]; maxSize?: number } | undefined): string {
if (!constraints) return '';
const kinds = new Set(
(constraints.contentTypes ?? []).map((type) => {
const [group, sub = ''] = type.split('/');
if (group === 'image') return 'images';
if (group === 'video') return 'videos';
if (group === 'audio') return 'audio';
return sub.toUpperCase();
}),
);
const list = [...kinds];
const what = list.length === 0 ? 'Any file' : list.length === 1 ? list[0]! : `${list.slice(0, -1).join(', ')} or ${list.at(-1)}`;
const text = what.charAt(0).toUpperCase() + what.slice(1);
return constraints.maxSize ? `${text} up to ${formatBytes(constraints.maxSize)}` : text;
}
export function formatBytes(bytes: number): string {
if (bytes < 1000) return `${bytes} B`;
const units = ['KB', 'MB', 'GB'];
let value = bytes / 1000;
let unit = 0;
while (value >= 1000 && unit < units.length - 1) {
value /= 1000;
unit++;
}
return `${value >= 10 ? Math.round(value) : Number(value.toFixed(1))} ${units[unit]}`;
}
const stroke = { fill: 'none', stroke: 'currentColor', strokeLinecap: 'round', strokeLinejoin: 'round' } as const;
function UploadIcon() {
return (
<svg viewBox="0 0 24 24" {...stroke} strokeWidth={1.9} className="size-5" aria-hidden>
<path d="M12 15V4m0 0L7.5 8.5M12 4l4.5 4.5M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3" />
</svg>
);
}
function XIcon({ className = 'size-[18px]' }: { className?: string }) {
return (
<svg viewBox="0 0 24 24" {...stroke} strokeWidth={2} className={className} aria-hidden>
<path d="M7 7l10 10M17 7 7 17" />
</svg>
);
}
function PauseIcon() {
return (
<svg viewBox="0 0 24 24" fill="currentColor" className="size-[18px]" aria-hidden>
<rect x="6.5" y="5.5" width="3.6" height="13" rx="1.2" />
<rect x="13.9" y="5.5" width="3.6" height="13" rx="1.2" />
</svg>
);
}
function PlayIcon() {
return (
<svg viewBox="0 0 24 24" fill="currentColor" className="size-[18px]" aria-hidden>
<path d="M8 5.8v12.4a1 1 0 0 0 1.5.86l10.2-6.2a1 1 0 0 0 0-1.72L9.5 4.94A1 1 0 0 0 8 5.8z" />
</svg>
);
}
function RetryIcon() {
return (
<svg viewBox="0 0 24 24" {...stroke} strokeWidth={2.1} className="size-[18px]" aria-hidden>
<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3" />
<path d="M19.5 4.5v4.2h-4.2" />
</svg>
);
}
function CheckIcon({ className }: { className: string }) {
return (
<svg viewBox="0 0 24 24" className={`text-emerald-500 dark:text-emerald-400 ${className}`} aria-hidden>
<circle cx="12" cy="12" r="10" fill="currentColor" />
<path d="M7.6 12.4l3 3 5.8-6.4" {...stroke} stroke="white" strokeWidth={2.3} />
</svg>
);
}
function BanIcon() {
return (
<svg viewBox="0 0 24 24" {...stroke} strokeWidth={2} className="size-[18px] shrink-0 text-rose-600 dark:text-rose-400" aria-hidden>
<circle cx="12" cy="12" r="8.6" />
<path d="M6 6l12 12" />
</svg>
);
}
function FileIcon() {
return (
<svg viewBox="0 0 24 24" {...stroke} strokeWidth={1.7} className="size-6" aria-hidden>
<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Zm0 0v5h5" />
</svg>
);
}
function FilmIcon() {
return (
<svg viewBox="0 0 24 24" {...stroke} strokeWidth={1.7} className="size-6" aria-hidden>
<rect x="3" y="5" width="18" height="14" rx="2.5" />
<path d="m10 9.5 4.5 2.5-4.5 2.5z" />
</svg>
);
}