@dowel-ui/react 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +10 -4
  2. package/dist/components/ai-agent-plan/ai-agent-plan.d.ts +50 -0
  3. package/dist/components/ai-agent-plan/ai-agent-plan.d.ts.map +1 -0
  4. package/dist/components/ai-agent-plan/ai-agent-plan.js +156 -0
  5. package/dist/components/ai-agent-plan/ai-agent-plan.js.map +1 -0
  6. package/dist/components/ai-agent-plan/index.d.ts +2 -0
  7. package/dist/components/ai-agent-plan/index.js +2 -0
  8. package/dist/components/ai-agent-plan/meta.js +17 -0
  9. package/dist/components/ai-agent-plan/meta.js.map +1 -0
  10. package/dist/components/ai-agent-status/ai-agent-status.d.ts +1 -1
  11. package/dist/components/ai-approval-request/ai-approval-request.d.ts +67 -0
  12. package/dist/components/ai-approval-request/ai-approval-request.d.ts.map +1 -0
  13. package/dist/components/ai-approval-request/ai-approval-request.js +218 -0
  14. package/dist/components/ai-approval-request/ai-approval-request.js.map +1 -0
  15. package/dist/components/ai-approval-request/index.d.ts +2 -0
  16. package/dist/components/ai-approval-request/index.js +2 -0
  17. package/dist/components/ai-approval-request/meta.js +17 -0
  18. package/dist/components/ai-approval-request/meta.js.map +1 -0
  19. package/dist/components/ai-response/ai-response.d.ts.map +1 -1
  20. package/dist/components/ai-response/ai-response.js +1 -0
  21. package/dist/components/ai-response/ai-response.js.map +1 -1
  22. package/dist/components/ai-structured-output/ai-structured-output.d.ts.map +1 -1
  23. package/dist/components/ai-structured-output/ai-structured-output.js +13 -2
  24. package/dist/components/ai-structured-output/ai-structured-output.js.map +1 -1
  25. package/dist/components/ai-tool/ai-tool.d.ts +1 -1
  26. package/dist/components/alert/alert.d.ts +1 -1
  27. package/dist/components/badge/badge.d.ts +1 -1
  28. package/dist/components/button/button.d.ts +1 -1
  29. package/dist/components/file-upload/file-upload.d.ts +46 -0
  30. package/dist/components/file-upload/file-upload.d.ts.map +1 -0
  31. package/dist/components/file-upload/file-upload.js +204 -0
  32. package/dist/components/file-upload/file-upload.js.map +1 -0
  33. package/dist/components/file-upload/index.d.ts +3 -0
  34. package/dist/components/file-upload/index.js +3 -0
  35. package/dist/components/file-upload/meta.js +17 -0
  36. package/dist/components/file-upload/meta.js.map +1 -0
  37. package/dist/components/file-upload/upload-queue.d.ts +87 -0
  38. package/dist/components/file-upload/upload-queue.d.ts.map +1 -0
  39. package/dist/components/file-upload/upload-queue.js +249 -0
  40. package/dist/components/file-upload/upload-queue.js.map +1 -0
  41. package/dist/components/progress/progress.d.ts +1 -1
  42. package/dist/components/progress/progress.js +1 -0
  43. package/dist/components/progress/progress.js.map +1 -1
  44. package/dist/components/spinner/spinner.js +1 -0
  45. package/dist/components/spinner/spinner.js.map +1 -1
  46. package/dist/components/tags-input/index.d.ts +2 -0
  47. package/dist/components/tags-input/index.js +2 -0
  48. package/dist/components/tags-input/meta.js +17 -0
  49. package/dist/components/tags-input/meta.js.map +1 -0
  50. package/dist/components/tags-input/tags-input.d.ts +47 -0
  51. package/dist/components/tags-input/tags-input.d.ts.map +1 -0
  52. package/dist/components/tags-input/tags-input.js +182 -0
  53. package/dist/components/tags-input/tags-input.js.map +1 -0
  54. package/dist/components/toast/toast.d.ts +1 -1
  55. package/dist/index.d.ts +10 -1
  56. package/dist/index.js +6 -1
  57. package/dist/registry/components.d.ts.map +1 -1
  58. package/dist/registry/components.js +58 -50
  59. package/dist/registry/components.js.map +1 -1
  60. package/package.json +4 -4
  61. package/src/components/ai-agent-plan/ai-agent-plan.tsx +0 -0
  62. package/src/components/ai-agent-plan/index.ts +10 -0
  63. package/src/components/ai-agent-plan/meta.ts +19 -0
  64. package/src/components/ai-approval-request/ai-approval-request.tsx +368 -0
  65. package/src/components/ai-approval-request/index.ts +7 -0
  66. package/src/components/ai-approval-request/meta.ts +21 -0
  67. package/src/components/ai-response/ai-response.tsx +1 -0
  68. package/src/components/ai-structured-output/ai-structured-output.tsx +25 -1
  69. package/src/components/file-upload/file-upload.tsx +322 -0
  70. package/src/components/file-upload/index.ts +20 -0
  71. package/src/components/file-upload/meta.ts +21 -0
  72. package/src/components/file-upload/upload-queue.ts +337 -0
  73. package/src/components/progress/progress.tsx +3 -0
  74. package/src/components/spinner/spinner.tsx +5 -0
  75. package/src/components/tags-input/index.ts +1 -0
  76. package/src/components/tags-input/meta.ts +23 -0
  77. package/src/components/tags-input/tags-input.tsx +300 -0
  78. package/src/index.ts +4 -0
  79. package/src/registry/components.ts +8 -0
@@ -0,0 +1,322 @@
1
+ "use client";
2
+
3
+ import {
4
+ useId,
5
+ useRef,
6
+ useState,
7
+ type ComponentPropsWithRef,
8
+ type DragEvent,
9
+ type ReactNode,
10
+ } from "react";
11
+
12
+ import { disabledStyles, focusRing } from "@/lib/styles";
13
+ import { cn } from "@/lib/utils";
14
+
15
+ import { formatBytes, type QueuedFile, type UploadStatus } from "./upload-queue";
16
+
17
+ /**
18
+ * The visible half of uploading. The queue is in `upload-queue.ts` and is the
19
+ * part worth owning.
20
+ *
21
+ * There is no dropzone pattern in the WAI-ARIA APG, and inventing one is the
22
+ * usual failure: a `div` with `role="button"`, a keydown handler, and a file
23
+ * picker that keyboard users can never reach. So the control here is a real
24
+ * `<input type="file">` with a real `<label>`. That is already operable by
25
+ * keyboard, already announces itself, already opens the picker on Enter and
26
+ * Space, and needs nothing added. Drag and drop is layered on top as a pointer
27
+ * convenience, and every drop can also be done from the input.
28
+ */
29
+
30
+ const STATUS_LABEL: Record<UploadStatus, string> = {
31
+ queued: "Waiting",
32
+ uploading: "Uploading",
33
+ done: "Uploaded",
34
+ failed: "Failed",
35
+ cancelled: "Cancelled",
36
+ };
37
+
38
+ export interface FileUploadProps extends Omit<ComponentPropsWithRef<"div">, "onDrop"> {
39
+ /** Names the control. */
40
+ label: string;
41
+ onFiles: (files: File[]) => void;
42
+ accept?: string;
43
+ multiple?: boolean;
44
+ disabled?: boolean;
45
+ /** Shown under the prompt: accepted types, size limit. */
46
+ hint?: ReactNode;
47
+ children?: ReactNode;
48
+ }
49
+
50
+ export function FileUpload({
51
+ className,
52
+ label,
53
+ onFiles,
54
+ accept,
55
+ multiple = true,
56
+ disabled = false,
57
+ hint,
58
+ children,
59
+ ...props
60
+ }: FileUploadProps) {
61
+ const inputId = useId();
62
+ const hintId = useId();
63
+ const [dragging, setDragging] = useState(false);
64
+ const depth = useRef(0);
65
+
66
+ function handleDrop(event: DragEvent<HTMLDivElement>) {
67
+ event.preventDefault();
68
+ depth.current = 0;
69
+ setDragging(false);
70
+ if (disabled) return;
71
+
72
+ const dropped = [...event.dataTransfer.files];
73
+ if (dropped.length > 0) onFiles(multiple ? dropped : dropped.slice(0, 1));
74
+ }
75
+
76
+ return (
77
+ <div data-slot="file-upload" className={cn("flex flex-col gap-3", className)} {...props}>
78
+ {/* dragenter/dragleave fire for every child element, so a plain boolean
79
+ flickers as the pointer crosses the prompt text. Counting depth is
80
+ what makes the highlight steady. */}
81
+ <div
82
+ data-slot="file-upload-dropzone"
83
+ data-dragging={dragging || undefined}
84
+ onDragEnter={(event) => {
85
+ event.preventDefault();
86
+ depth.current += 1;
87
+ if (!disabled) setDragging(true);
88
+ }}
89
+ onDragLeave={() => {
90
+ depth.current -= 1;
91
+ if (depth.current <= 0) setDragging(false);
92
+ }}
93
+ onDragOver={(event) => {
94
+ event.preventDefault();
95
+ }}
96
+ onDrop={handleDrop}
97
+ className={cn(
98
+ "rounded-lg border border-dashed border-border-strong bg-muted/30 px-4 py-6 text-center",
99
+ "transition-colors duration-[var(--duration-fast)]",
100
+ dragging && "border-primary bg-primary/5",
101
+ disabled && "pointer-events-none opacity-55",
102
+ )}
103
+ >
104
+ {/* The label is the control. Clicking it opens the picker, Enter and
105
+ Space activate it, and assistive technology already describes it. */}
106
+ <label
107
+ htmlFor={inputId}
108
+ className={cn(
109
+ "inline-flex cursor-pointer flex-col items-center gap-1 rounded-md px-2 py-1 text-sm",
110
+ "focus-within:ring-2 focus-within:ring-ring/55",
111
+ )}
112
+ >
113
+ <span className="font-medium">{label}</span>
114
+ <span className="text-xs text-muted-foreground">
115
+ Drop {multiple ? "files" : "a file"} here, or choose from your device
116
+ </span>
117
+ <input
118
+ id={inputId}
119
+ type="file"
120
+ accept={accept}
121
+ multiple={multiple}
122
+ disabled={disabled}
123
+ aria-describedby={hint ? hintId : undefined}
124
+ onChange={(event) => {
125
+ const chosen = [...(event.target.files ?? [])];
126
+ if (chosen.length > 0) onFiles(chosen);
127
+ // Reset, so choosing the same file twice fires change twice.
128
+ event.target.value = "";
129
+ }}
130
+ className="sr-only"
131
+ />
132
+ </label>
133
+
134
+ {hint ? (
135
+ <p id={hintId} className="mt-2 text-xs text-muted-foreground">
136
+ {hint}
137
+ </p>
138
+ ) : null}
139
+ </div>
140
+
141
+ {children}
142
+ </div>
143
+ );
144
+ }
145
+
146
+ export interface FileUploadListProps extends ComponentPropsWithRef<"ul"> {
147
+ files: QueuedFile[];
148
+ onCancel?: (id: string) => void;
149
+ onRetry?: (id: string) => void;
150
+ onRemove?: (id: string) => void;
151
+ }
152
+
153
+ export function FileUploadList({
154
+ className,
155
+ files,
156
+ onCancel,
157
+ onRetry,
158
+ onRemove,
159
+ ...props
160
+ }: FileUploadListProps) {
161
+ if (files.length === 0) return null;
162
+
163
+ return (
164
+ <ul
165
+ data-slot="file-upload-list"
166
+ className={cn("flex list-none flex-col gap-2", className)}
167
+ {...props}
168
+ >
169
+ {files.map((entry) => (
170
+ <FileUploadItem
171
+ key={entry.id}
172
+ entry={entry}
173
+ onCancel={onCancel}
174
+ onRetry={onRetry}
175
+ onRemove={onRemove}
176
+ />
177
+ ))}
178
+ </ul>
179
+ );
180
+ }
181
+
182
+ export interface FileUploadItemProps extends Omit<ComponentPropsWithRef<"li">, "children"> {
183
+ entry: QueuedFile;
184
+ onCancel?: (id: string) => void;
185
+ onRetry?: (id: string) => void;
186
+ onRemove?: (id: string) => void;
187
+ }
188
+
189
+ export function FileUploadItem({
190
+ className,
191
+ entry,
192
+ onCancel,
193
+ onRetry,
194
+ onRemove,
195
+ ...props
196
+ }: FileUploadItemProps) {
197
+ const { id, file, status, progress, error } = entry;
198
+ const percent = progress === null ? null : Math.round(progress * 100);
199
+
200
+ return (
201
+ <li
202
+ data-slot="file-upload-item"
203
+ data-status={status}
204
+ className={cn(
205
+ "flex items-center gap-3 rounded-lg border px-3 py-2 text-sm",
206
+ status === "failed"
207
+ ? "border-destructive/40 bg-destructive/5"
208
+ : "border-border bg-card",
209
+ className,
210
+ )}
211
+ {...props}
212
+ >
213
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
214
+ <div className="flex items-baseline justify-between gap-2">
215
+ <span className="truncate font-medium">{file.name}</span>
216
+ <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
217
+ {formatBytes(file.size)}
218
+ </span>
219
+ </div>
220
+
221
+ {/* Status in words, always. A bar at 60% with a red tint does not say
222
+ whether it is uploading, stalled or failed. */}
223
+ <p
224
+ className={cn(
225
+ "text-xs",
226
+ status === "failed" ? "text-destructive" : "text-muted-foreground",
227
+ )}
228
+ >
229
+ {STATUS_LABEL[status]}
230
+ {status === "uploading" && percent !== null ? ` · ${String(percent)}%` : null}
231
+ {error ? ` · ${error}` : null}
232
+ </p>
233
+
234
+ {status === "uploading" ? (
235
+ <div
236
+ role="progressbar"
237
+ aria-label={`Uploading ${file.name}`}
238
+ aria-valuenow={percent ?? undefined}
239
+ aria-valuemin={0}
240
+ aria-valuemax={100}
241
+ className="h-1 w-full overflow-hidden rounded-full bg-muted"
242
+ >
243
+ <div
244
+ data-slot="file-upload-progress"
245
+ className="h-full rounded-full bg-primary transition-[width] duration-[var(--duration-normal)] ease-[var(--ease-out-quint)]"
246
+ style={{ width: `${String(percent ?? 0)}%` }}
247
+ />
248
+ </div>
249
+ ) : null}
250
+ </div>
251
+
252
+ <div className="flex shrink-0 items-center gap-1">
253
+ {status === "uploading" && onCancel ? (
254
+ <ItemButton onClick={() => onCancel(id)}>Cancel</ItemButton>
255
+ ) : null}
256
+ {(status === "failed" || status === "cancelled") && onRetry ? (
257
+ <ItemButton onClick={() => onRetry(id)}>Retry</ItemButton>
258
+ ) : null}
259
+ {onRemove ? (
260
+ <ItemButton onClick={() => onRemove(id)} aria-label={`Remove ${file.name}`}>
261
+ Remove
262
+ </ItemButton>
263
+ ) : null}
264
+ </div>
265
+ </li>
266
+ );
267
+ }
268
+
269
+ function ItemButton({ className, ...props }: ComponentPropsWithRef<"button">) {
270
+ return (
271
+ <button
272
+ type="button"
273
+ className={cn(
274
+ "rounded-md border border-input bg-background px-2 py-0.5 text-xs font-medium",
275
+ "transition-colors hover:bg-accent hover:text-accent-foreground",
276
+ focusRing,
277
+ disabledStyles,
278
+ className,
279
+ )}
280
+ {...props}
281
+ />
282
+ );
283
+ }
284
+
285
+ /**
286
+ * One sentence covering the whole queue, announced politely.
287
+ *
288
+ * Per-file live regions would talk over each other the moment two uploads run
289
+ * at once; one summary of the set is readable where six competing ones are not.
290
+ */
291
+ export function FileUploadStatus({
292
+ className,
293
+ stats,
294
+ ...props
295
+ }: ComponentPropsWithRef<"p"> & {
296
+ stats: { total: number; active: number; done: number; failed: number };
297
+ }) {
298
+ const { total, active, done, failed } = stats;
299
+
300
+ // Progress through the set, not a count of what happens to be in flight.
301
+ // "3 of 5 uploading" is wrong the moment a concurrency limit holds two back,
302
+ // and it never tells the reader how much of the job is left.
303
+ const message =
304
+ total === 0
305
+ ? ""
306
+ : active > 0
307
+ ? `${String(done)} of ${String(total)} uploaded`
308
+ : failed > 0
309
+ ? `${String(done)} uploaded, ${String(failed)} failed`
310
+ : `${String(done)} uploaded`;
311
+
312
+ return (
313
+ <p
314
+ data-slot="file-upload-status"
315
+ aria-live="polite"
316
+ className={cn("text-xs text-muted-foreground", className)}
317
+ {...props}
318
+ >
319
+ {message}
320
+ </p>
321
+ );
322
+ }
@@ -0,0 +1,20 @@
1
+ export {
2
+ FileUpload,
3
+ FileUploadItem,
4
+ FileUploadList,
5
+ FileUploadStatus,
6
+ type FileUploadItemProps,
7
+ type FileUploadListProps,
8
+ type FileUploadProps,
9
+ } from "./file-upload";
10
+ export {
11
+ formatBytes,
12
+ matchesAccept,
13
+ useUploadQueue,
14
+ xhrUpload,
15
+ type QueuedFile,
16
+ type UploadContext,
17
+ type UploadFn,
18
+ type UploadQueueOptions,
19
+ type UploadStatus,
20
+ } from "./upload-queue";
@@ -0,0 +1,21 @@
1
+ import { defineMeta } from "@/registry/schema";
2
+
3
+ export const meta = defineMeta({
4
+ name: "file-upload",
5
+ title: "File Upload",
6
+ description: "A dropzone over a real file input, plus the upload queue nobody ships.",
7
+ category: "form",
8
+ status: "stable",
9
+ dependencies: [],
10
+ registryDependencies: [],
11
+ files: ["upload-queue.ts", "file-upload.tsx"],
12
+ a11y:
13
+ "The APG has no dropzone pattern, and inventing one is the usual failure — a div with " +
14
+ 'role="button", a keydown handler, and a picker keyboard users never reach. The control here ' +
15
+ "is a real input[type=file] with a real label, which is already operable, already announced, " +
16
+ "and opens the picker on Enter and Space with nothing added. Drag and drop is a pointer " +
17
+ "convenience layered on top; every drop can also be done from the input. Each uploading file " +
18
+ "gets a progressbar named after it, status is always stated in words as well as drawn, and " +
19
+ "one polite live region summarises the whole queue rather than six per-file regions talking " +
20
+ "over each other.",
21
+ });
@@ -0,0 +1,337 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
+
5
+ /**
6
+ * The upload queue.
7
+ *
8
+ * The dropzone is the most duplicated component in the React ecosystem and the
9
+ * least valuable half: it is a styled rectangle over `<input type="file">`.
10
+ * What almost nobody ships is this — progress, cancel, retry with backoff, and
11
+ * a concurrency limit — so every team writes it again, usually twice, because
12
+ * the first version has no cancel and no retry.
13
+ *
14
+ * Transport is injected. This never calls `fetch` or constructs a request,
15
+ * because the request is the part that differs everywhere: presigned S3 PUT,
16
+ * multipart POST, tus, an internal gateway with its own auth. `upload` receives
17
+ * the file, a progress callback and an AbortSignal, and returns a promise. That
18
+ * is the whole contract.
19
+ *
20
+ * Progress needs XHR, not fetch. `fetch` still cannot report upload progress in
21
+ * any shipping browser — there is no readable stream for the request body — so
22
+ * a transport that wants a real progress bar has to use XMLHttpRequest. That is
23
+ * the consumer's choice to make, and `xhrUpload` below is a working example
24
+ * rather than a dependency.
25
+ */
26
+
27
+ export type UploadStatus = "queued" | "uploading" | "done" | "failed" | "cancelled";
28
+
29
+ export interface QueuedFile {
30
+ /** Stable across retries, so React keys and announcements do not jump. */
31
+ id: string;
32
+ file: File;
33
+ status: UploadStatus;
34
+ /** 0–1, or null when the transport cannot report it. */
35
+ progress: number | null;
36
+ /** Why it failed or was refused. Kept so it can be read and acted on. */
37
+ error?: string;
38
+ attempts: number;
39
+ }
40
+
41
+ export interface UploadContext {
42
+ onProgress: (fraction: number) => void;
43
+ signal: AbortSignal;
44
+ }
45
+
46
+ export type UploadFn = (file: File, context: UploadContext) => Promise<void>;
47
+
48
+ export interface UploadQueueOptions {
49
+ upload: UploadFn;
50
+ /** Uploads running at once. More is not faster once the link is saturated. */
51
+ concurrency?: number;
52
+ /** Automatic retries per file before it is left failed. */
53
+ maxAttempts?: number;
54
+ /** Largest accepted file, in bytes. */
55
+ maxSize?: number;
56
+ /** Accepted types, as an `accept` attribute value: ".pdf,image/*". */
57
+ accept?: string;
58
+ /** Total files the queue will hold. */
59
+ maxFiles?: number;
60
+ onComplete?: (file: QueuedFile) => void;
61
+ }
62
+
63
+ /** Backoff between attempts. Bounded, because a person is waiting. */
64
+ function backoffMs(attempt: number): number {
65
+ return Math.min(8000, 500 * 2 ** (attempt - 1));
66
+ }
67
+
68
+ /** Matches a file against an `accept` string the same way the browser does. */
69
+ export function matchesAccept(file: File, accept: string | undefined): boolean {
70
+ if (!accept) return true;
71
+ const patterns = accept
72
+ .split(",")
73
+ .map((part) => part.trim().toLowerCase())
74
+ .filter(Boolean);
75
+ if (patterns.length === 0) return true;
76
+
77
+ const type = file.type.toLowerCase();
78
+ const name = file.name.toLowerCase();
79
+
80
+ return patterns.some((pattern) => {
81
+ if (pattern.startsWith(".")) return name.endsWith(pattern);
82
+ if (pattern.endsWith("/*")) return type.startsWith(pattern.slice(0, -1));
83
+ return type === pattern;
84
+ });
85
+ }
86
+
87
+ export function formatBytes(bytes: number): string {
88
+ if (bytes < 1000) return `${String(bytes)} B`;
89
+ const units = ["kB", "MB", "GB", "TB"];
90
+ let value = bytes / 1000;
91
+ let unit = 0;
92
+ while (value >= 1000 && unit < units.length - 1) {
93
+ value /= 1000;
94
+ unit += 1;
95
+ }
96
+ return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit] ?? "B"}`;
97
+ }
98
+
99
+ let sequence = 0;
100
+
101
+ export function useUploadQueue(options: UploadQueueOptions) {
102
+ const {
103
+ upload,
104
+ concurrency = 3,
105
+ maxAttempts = 3,
106
+ maxSize,
107
+ accept,
108
+ maxFiles,
109
+ onComplete,
110
+ } = options;
111
+
112
+ const [files, setFiles] = useState<QueuedFile[]>([]);
113
+
114
+ const controllers = useRef(new Map<string, AbortController>());
115
+ const running = useRef(new Set<string>());
116
+
117
+ // The live option values, so an in-flight upload reads the current transport
118
+ // without `run` being re-created — which would churn the scheduling effect
119
+ // every time a consumer passes an inline `upload`. Written after commit
120
+ // rather than during render, because a ref write during render is unsafe
121
+ // under concurrent rendering; `run` only reads this once it is executing,
122
+ // which is always after the effect has run.
123
+ const latest = useRef({ upload, concurrency, maxAttempts, onComplete });
124
+ useEffect(() => {
125
+ latest.current = { upload, concurrency, maxAttempts, onComplete };
126
+ });
127
+
128
+ const patch = useCallback((id: string, changes: Partial<QueuedFile>) => {
129
+ setFiles((current) =>
130
+ current.map((entry) => (entry.id === id ? { ...entry, ...changes } : entry)),
131
+ );
132
+ }, []);
133
+
134
+ const run = useCallback(
135
+ async (entry: QueuedFile) => {
136
+ const controller = new AbortController();
137
+ controllers.current.set(entry.id, controller);
138
+
139
+ const attempt = entry.attempts + 1;
140
+ patch(entry.id, {
141
+ status: "uploading",
142
+ progress: 0,
143
+ attempts: attempt,
144
+ error: undefined,
145
+ });
146
+
147
+ try {
148
+ await latest.current.upload(entry.file, {
149
+ signal: controller.signal,
150
+ onProgress: (fraction) => {
151
+ patch(entry.id, { progress: Math.min(1, Math.max(0, fraction)) });
152
+ },
153
+ });
154
+
155
+ patch(entry.id, { status: "done", progress: 1 });
156
+ latest.current.onComplete?.({ ...entry, status: "done", progress: 1 });
157
+ } catch (error) {
158
+ if (controller.signal.aborted) {
159
+ patch(entry.id, { status: "cancelled", progress: null });
160
+ } else if (attempt < latest.current.maxAttempts) {
161
+ // Back off, then requeue. Releasing the slot only after the delay is
162
+ // what makes the wait real rather than a busy retry, and the file
163
+ // re-enters the queue like any other so retries obey concurrency too.
164
+ setTimeout(() => {
165
+ running.current.delete(entry.id);
166
+ controllers.current.delete(entry.id);
167
+ patch(entry.id, { status: "queued", progress: null });
168
+ }, backoffMs(attempt));
169
+ return;
170
+ } else {
171
+ patch(entry.id, {
172
+ status: "failed",
173
+ progress: null,
174
+ error: error instanceof Error ? error.message : "Upload failed",
175
+ });
176
+ }
177
+ }
178
+
179
+ controllers.current.delete(entry.id);
180
+ running.current.delete(entry.id);
181
+ // No explicit pump: the scheduling effect below reacts to the state
182
+ // change and starts whatever can start next.
183
+ setFiles((current) => [...current]);
184
+ },
185
+ [patch],
186
+ );
187
+
188
+ // Starts whatever can start, once the state that made it startable has been
189
+ // committed. Doing this inside a setState updater — the obvious shortcut —
190
+ // means React may run it twice and upload the same file twice; the `running`
191
+ // set guards that, but the effect is the honest place for it.
192
+ useEffect(() => {
193
+ const free = concurrency - running.current.size;
194
+ if (free <= 0) return;
195
+
196
+ const next = files
197
+ .filter((entry) => entry.status === "queued" && !running.current.has(entry.id))
198
+ .slice(0, free);
199
+
200
+ for (const entry of next) {
201
+ running.current.add(entry.id);
202
+ void run(entry);
203
+ }
204
+ }, [files, concurrency, run]);
205
+
206
+ /** Validates and enqueues. A rejected file is kept and told why. */
207
+ const add = useCallback(
208
+ (incoming: File[]) => {
209
+ setFiles((current) => {
210
+ const room = maxFiles === undefined ? incoming.length : maxFiles - current.length;
211
+ const admitted: QueuedFile[] = [];
212
+
213
+ for (const file of incoming.slice(0, Math.max(0, room))) {
214
+ sequence += 1;
215
+ const id = `upload-${String(sequence)}`;
216
+
217
+ // A rejected file becomes a failed entry rather than disappearing.
218
+ // Silently dropping a file the reader chose is how these components
219
+ // lose work without anybody noticing.
220
+ if (maxSize !== undefined && file.size > maxSize) {
221
+ admitted.push({
222
+ id,
223
+ file,
224
+ status: "failed",
225
+ progress: null,
226
+ attempts: 0,
227
+ error: `Larger than ${formatBytes(maxSize)}`,
228
+ });
229
+ continue;
230
+ }
231
+ if (!matchesAccept(file, accept)) {
232
+ admitted.push({
233
+ id,
234
+ file,
235
+ status: "failed",
236
+ progress: null,
237
+ attempts: 0,
238
+ error: "Type not accepted",
239
+ });
240
+ continue;
241
+ }
242
+
243
+ admitted.push({ id, file, status: "queued", progress: null, attempts: 0 });
244
+ }
245
+
246
+ return [...current, ...admitted];
247
+ });
248
+ },
249
+ [accept, maxFiles, maxSize],
250
+ );
251
+
252
+ const cancel = useCallback((id: string) => {
253
+ controllers.current.get(id)?.abort();
254
+ }, []);
255
+
256
+ const retry = useCallback((id: string) => {
257
+ setFiles((current) =>
258
+ current.map((entry) =>
259
+ entry.id === id
260
+ ? { ...entry, status: "queued" as const, error: undefined, attempts: 0 }
261
+ : entry,
262
+ ),
263
+ );
264
+ }, []);
265
+
266
+ const remove = useCallback((id: string) => {
267
+ controllers.current.get(id)?.abort();
268
+ controllers.current.delete(id);
269
+ running.current.delete(id);
270
+ setFiles((current) => current.filter((entry) => entry.id !== id));
271
+ }, []);
272
+
273
+ const clearCompleted = useCallback(() => {
274
+ setFiles((current) => current.filter((entry) => entry.status !== "done"));
275
+ }, []);
276
+
277
+ const stats = useMemo(() => {
278
+ const by = (status: UploadStatus) =>
279
+ files.filter((entry) => entry.status === status).length;
280
+ return {
281
+ total: files.length,
282
+ queued: by("queued"),
283
+ uploading: by("uploading"),
284
+ done: by("done"),
285
+ failed: by("failed"),
286
+ cancelled: by("cancelled"),
287
+ active: by("queued") + by("uploading"),
288
+ };
289
+ }, [files]);
290
+
291
+ return { files, stats, add, cancel, retry, remove, clearCompleted };
292
+ }
293
+
294
+ /**
295
+ * A working XHR transport, as an example rather than a dependency.
296
+ *
297
+ * XMLHttpRequest and not fetch, because fetch still cannot report upload
298
+ * progress: there is no readable stream for a request body in any shipping
299
+ * browser. Copy this and change the request to match your backend.
300
+ */
301
+ export function xhrUpload(
302
+ url: string,
303
+ init: { method?: string; headers?: Record<string, string> } = {},
304
+ ): UploadFn {
305
+ return (file, { onProgress, signal }) =>
306
+ new Promise<void>((resolve, reject) => {
307
+ const request = new XMLHttpRequest();
308
+ request.open(init.method ?? "POST", url);
309
+
310
+ for (const [header, value] of Object.entries(init.headers ?? {})) {
311
+ request.setRequestHeader(header, value);
312
+ }
313
+
314
+ request.upload.addEventListener("progress", (event) => {
315
+ if (event.lengthComputable) onProgress(event.loaded / event.total);
316
+ });
317
+
318
+ request.addEventListener("load", () => {
319
+ if (request.status >= 200 && request.status < 300) resolve();
320
+ else reject(new Error(`Upload failed with status ${String(request.status)}`));
321
+ });
322
+ request.addEventListener("error", () => {
323
+ reject(new Error("Network error"));
324
+ });
325
+ request.addEventListener("abort", () => {
326
+ reject(new Error("Cancelled"));
327
+ });
328
+
329
+ signal.addEventListener("abort", () => {
330
+ request.abort();
331
+ });
332
+
333
+ const body = new FormData();
334
+ body.append("file", file);
335
+ request.send(body);
336
+ });
337
+ }