@brightlocal/ui-components 3.3.0 → 3.5.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 (207) hide show
  1. package/AI_USAGE.md +22 -3
  2. package/README.md +177 -109
  3. package/component-meta.json +1307 -113
  4. package/dist/alert-dialog.cjs +1 -1
  5. package/dist/alert-dialog.d.ts +13 -2
  6. package/dist/alert-dialog.d.ts.map +1 -1
  7. package/dist/alert-dialog.js +4 -3
  8. package/dist/banner.cjs +1 -1
  9. package/dist/banner.d.ts +47 -11
  10. package/dist/banner.d.ts.map +1 -1
  11. package/dist/banner.js +156 -79
  12. package/dist/blocks/empty-state.cjs +1 -1
  13. package/dist/blocks/empty-state.d.ts +40 -5
  14. package/dist/blocks/empty-state.d.ts.map +1 -1
  15. package/dist/blocks/empty-state.js +59 -52
  16. package/dist/blocks/input-list.cjs +1 -1
  17. package/dist/blocks/input-list.d.ts +1 -0
  18. package/dist/blocks/input-list.d.ts.map +1 -1
  19. package/dist/blocks/input-list.js +39 -39
  20. package/dist/blocks/sidebar.cjs +1 -1
  21. package/dist/blocks/sidebar.d.ts +12 -6
  22. package/dist/blocks/sidebar.d.ts.map +1 -1
  23. package/dist/blocks/sidebar.js +64 -63
  24. package/dist/button.cjs +1 -1
  25. package/dist/button.d.ts.map +1 -1
  26. package/dist/button.js +47 -43
  27. package/dist/card.cjs +1 -1
  28. package/dist/card.d.ts +12 -0
  29. package/dist/card.d.ts.map +1 -1
  30. package/dist/card.js +115 -97
  31. package/dist/chart.cjs +6 -6
  32. package/dist/chart.d.ts +6 -10
  33. package/dist/chart.d.ts.map +1 -1
  34. package/dist/chart.js +281 -296
  35. package/dist/combobox.cjs +3 -3
  36. package/dist/combobox.d.ts.map +1 -1
  37. package/dist/combobox.js +430 -343
  38. package/dist/command.cjs +1 -1
  39. package/dist/command.d.ts +23 -2
  40. package/dist/command.d.ts.map +1 -1
  41. package/dist/command.js +212 -207
  42. package/dist/count-indicator.cjs +1 -0
  43. package/dist/count-indicator.d.ts +85 -0
  44. package/dist/count-indicator.d.ts.map +1 -0
  45. package/dist/count-indicator.js +72 -0
  46. package/dist/data-table.cjs +1 -1
  47. package/dist/data-table.d.ts +101 -11
  48. package/dist/data-table.d.ts.map +1 -1
  49. package/dist/data-table.js +593 -523
  50. package/dist/description-list.cjs +1 -0
  51. package/dist/description-list.d.ts +142 -0
  52. package/dist/description-list.d.ts.map +1 -0
  53. package/dist/description-list.js +173 -0
  54. package/dist/dialog.cjs +1 -1
  55. package/dist/dialog.d.ts +26 -3
  56. package/dist/dialog.d.ts.map +1 -1
  57. package/dist/dialog.js +62 -47
  58. package/dist/drawer.cjs +1 -1
  59. package/dist/drawer.d.ts +8 -4
  60. package/dist/drawer.d.ts.map +1 -1
  61. package/dist/drawer.js +37 -38
  62. package/dist/file-upload.cjs +1 -0
  63. package/dist/file-upload.d.ts +546 -0
  64. package/dist/file-upload.d.ts.map +1 -0
  65. package/dist/file-upload.js +1103 -0
  66. package/dist/global-layout.cjs +1 -1
  67. package/dist/global-layout.d.ts +7 -2
  68. package/dist/global-layout.d.ts.map +1 -1
  69. package/dist/global-layout.js +52 -52
  70. package/dist/hooks/use-file-dropzone.cjs +1 -0
  71. package/dist/hooks/use-file-dropzone.d.ts +75 -0
  72. package/dist/hooks/use-file-dropzone.d.ts.map +1 -0
  73. package/dist/hooks/use-file-dropzone.js +133 -0
  74. package/dist/hover-card.cjs +1 -1
  75. package/dist/hover-card.d.ts +29 -16
  76. package/dist/hover-card.d.ts.map +1 -1
  77. package/dist/hover-card.js +153 -36
  78. package/dist/index.cjs +1 -1
  79. package/dist/index.d.ts +4 -0
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +681 -623
  82. package/dist/input-chip.cjs +1 -1
  83. package/dist/input-chip.d.ts +30 -1
  84. package/dist/input-chip.d.ts.map +1 -1
  85. package/dist/input-chip.js +131 -115
  86. package/dist/input-group.cjs +1 -1
  87. package/dist/input-group.d.ts +37 -2
  88. package/dist/input-group.d.ts.map +1 -1
  89. package/dist/input-group.js +131 -114
  90. package/dist/input-password.cjs +1 -1
  91. package/dist/input-password.js +6 -6
  92. package/dist/lib/empty-canvas.cjs +1 -1
  93. package/dist/lib/empty-canvas.d.ts +27 -1
  94. package/dist/lib/empty-canvas.d.ts.map +1 -1
  95. package/dist/lib/empty-canvas.js +27 -23
  96. package/dist/lib/empty-chip.cjs +1 -1
  97. package/dist/lib/empty-chip.d.ts +19 -2
  98. package/dist/lib/empty-chip.d.ts.map +1 -1
  99. package/dist/lib/empty-chip.js +14 -9
  100. package/dist/lib/field-aria.cjs +1 -1
  101. package/dist/lib/field-aria.d.ts +4 -4
  102. package/dist/lib/field-aria.d.ts.map +1 -1
  103. package/dist/lib/field-aria.js +7 -5
  104. package/dist/lib/media-viewer-content.cjs +1 -1
  105. package/dist/lib/media-viewer-content.js +1 -1
  106. package/dist/lib/motion.cjs +1 -1
  107. package/dist/lib/motion.js +15 -10
  108. package/dist/lib/table-internal.cjs +1 -1
  109. package/dist/lib/table-internal.d.ts +19 -0
  110. package/dist/lib/table-internal.d.ts.map +1 -1
  111. package/dist/lib/table-internal.js +22 -7
  112. package/dist/list.cjs +1 -1
  113. package/dist/list.d.ts +230 -40
  114. package/dist/list.d.ts.map +1 -1
  115. package/dist/list.js +301 -66
  116. package/dist/logo-mark.cjs +1 -1
  117. package/dist/logo-mark.d.ts +18 -2
  118. package/dist/logo-mark.d.ts.map +1 -1
  119. package/dist/logo-mark.js +159 -79
  120. package/dist/media-empty.cjs +1 -1
  121. package/dist/media-empty.d.ts +50 -7
  122. package/dist/media-empty.d.ts.map +1 -1
  123. package/dist/media-empty.js +14 -13
  124. package/dist/media-viewer.cjs +1 -1
  125. package/dist/media-viewer.js +6 -6
  126. package/dist/multi-select-filter.cjs +1 -1
  127. package/dist/multi-select-filter.d.ts.map +1 -1
  128. package/dist/multi-select-filter.js +92 -101
  129. package/dist/pagination.cjs +1 -1
  130. package/dist/pagination.d.ts +11 -0
  131. package/dist/pagination.d.ts.map +1 -1
  132. package/dist/pagination.js +17 -17
  133. package/dist/relative-date.d.ts +6 -0
  134. package/dist/relative-date.d.ts.map +1 -1
  135. package/dist/resizable.d.ts +1 -1
  136. package/dist/result-count.cjs +1 -1
  137. package/dist/result-count.d.ts +13 -16
  138. package/dist/result-count.d.ts.map +1 -1
  139. package/dist/result-count.js +24 -33
  140. package/dist/route-progress.cjs +1 -1
  141. package/dist/route-progress.js +24 -23
  142. package/dist/sheet.cjs +1 -1
  143. package/dist/sheet.d.ts +22 -3
  144. package/dist/sheet.d.ts.map +1 -1
  145. package/dist/sheet.js +152 -125
  146. package/dist/single-select-filter.cjs +1 -1
  147. package/dist/single-select-filter.d.ts.map +1 -1
  148. package/dist/single-select-filter.js +67 -76
  149. package/dist/table.cjs +1 -1
  150. package/dist/table.d.ts.map +1 -1
  151. package/dist/table.js +77 -76
  152. package/dist/tabs.cjs +1 -1
  153. package/dist/tabs.d.ts +39 -3
  154. package/dist/tabs.d.ts.map +1 -1
  155. package/dist/tabs.js +127 -76
  156. package/dist/textarea.cjs +1 -1
  157. package/dist/textarea.d.ts +34 -0
  158. package/dist/textarea.d.ts.map +1 -1
  159. package/dist/textarea.js +115 -19
  160. package/dist/tooltip.cjs +1 -1
  161. package/dist/tooltip.d.ts.map +1 -1
  162. package/dist/tooltip.js +137 -131
  163. package/dist/typography-text.cjs +1 -1
  164. package/dist/typography-text.d.ts +6 -2
  165. package/dist/typography-text.d.ts.map +1 -1
  166. package/dist/typography-text.js +14 -13
  167. package/package.json +2 -3
  168. package/src/blocks/empty-state.tsx +108 -48
  169. package/src/blocks/input-list.tsx +15 -9
  170. package/src/blocks/sidebar.tsx +39 -16
  171. package/src/components/alert-dialog.tsx +18 -2
  172. package/src/components/banner.tsx +247 -68
  173. package/src/components/button.tsx +27 -10
  174. package/src/components/card.tsx +89 -7
  175. package/src/components/chart.tsx +47 -67
  176. package/src/components/combobox.tsx +221 -12
  177. package/src/components/command.tsx +83 -37
  178. package/src/components/count-indicator.tsx +188 -0
  179. package/src/components/data-table.tsx +506 -159
  180. package/src/components/description-list.tsx +445 -0
  181. package/src/components/dialog.tsx +74 -5
  182. package/src/components/drawer.tsx +52 -32
  183. package/src/components/file-upload.tsx +2574 -0
  184. package/src/components/global-layout.tsx +18 -5
  185. package/src/components/hover-card.tsx +395 -65
  186. package/src/components/input-chip.tsx +67 -2
  187. package/src/components/input-group.tsx +89 -6
  188. package/src/components/list.tsx +720 -72
  189. package/src/components/logo-mark.tsx +109 -25
  190. package/src/components/media-empty.tsx +62 -7
  191. package/src/components/multi-select-filter.tsx +9 -16
  192. package/src/components/pagination.tsx +15 -2
  193. package/src/components/relative-date.tsx +6 -0
  194. package/src/components/result-count.tsx +27 -54
  195. package/src/components/sheet.tsx +86 -8
  196. package/src/components/single-select-filter.tsx +9 -16
  197. package/src/components/table.tsx +16 -1
  198. package/src/components/tabs.tsx +223 -41
  199. package/src/components/textarea.tsx +271 -4
  200. package/src/components/tooltip.tsx +29 -2
  201. package/src/components/typography-text.tsx +7 -2
  202. package/src/hooks/use-file-dropzone.ts +325 -0
  203. package/src/index.ts +4 -0
  204. package/src/lib/empty-canvas.tsx +47 -20
  205. package/src/lib/empty-chip.tsx +38 -3
  206. package/src/lib/field-aria.tsx +11 -6
  207. package/src/lib/table-internal.ts +38 -0
@@ -0,0 +1,2574 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import { Slot } from "@radix-ui/react-slot";
5
+ import { cva } from "class-variance-authority";
6
+ import {
7
+ Check,
8
+ CircleX,
9
+ File as FileIcon,
10
+ FileCode as FileCodeIcon,
11
+ FileImage as FileImageIcon,
12
+ FileJson as FileJsonIcon,
13
+ FileSpreadsheet as FileSpreadsheetIcon,
14
+ FileText as FileTextIcon,
15
+ TriangleAlert,
16
+ X,
17
+ } from "@brightlocal/icons";
18
+
19
+ import { cn } from "@brightlocal/ui-components/lib/utils";
20
+ import { composeEventHandlers } from "../lib/compose-event-handlers";
21
+ import { Alert, AlertTitle } from "@brightlocal/ui-components/alert";
22
+ import { MediaEmpty } from "@brightlocal/ui-components/media-empty";
23
+ import { Button } from "@brightlocal/ui-components/button";
24
+ import { LogoMark } from "@brightlocal/ui-components/logo-mark";
25
+ import {
26
+ CountIndicator,
27
+ type CountIndicatorProps,
28
+ } from "@brightlocal/ui-components/count-indicator";
29
+ import { Progress } from "@brightlocal/ui-components/progress";
30
+ import { TypographyText } from "@brightlocal/ui-components/typography-text";
31
+ import { Spinner } from "@brightlocal/ui-components/spinner";
32
+ import {
33
+ dragItemsMatchAccept,
34
+ useFileDropzone,
35
+ validateFile,
36
+ type DropzoneState,
37
+ type FileError,
38
+ type FileRejection,
39
+ type UseFileDropzoneOptions,
40
+ } from "@brightlocal/ui-components/hooks/use-file-dropzone";
41
+
42
+ /* -------------------------------------------------------------------------------------------------
43
+ * Utilities
44
+ * -----------------------------------------------------------------------------------------------*/
45
+
46
+ /** Format bytes as a human-readable string: "1.2 MB", "980 KB", "512 B". */
47
+ function formatBytes(bytes: number): string {
48
+ if (bytes < 1024) return `${bytes} B`;
49
+ const units = ["KB", "MB", "GB"];
50
+ let value = bytes / 1024;
51
+ let i = 0;
52
+ while (value >= 1024 && i < units.length - 1) {
53
+ value /= 1024;
54
+ i++;
55
+ }
56
+ const shown =
57
+ value >= 10
58
+ ? String(Math.round(value))
59
+ : value.toFixed(1).replace(/\.0$/, "");
60
+ return `${shown} ${units[i]}`;
61
+ }
62
+
63
+ /** Read an image's pixel dimensions. Resolves `null` when the browser can't decode it. */
64
+ async function getImageDimensions(
65
+ file: Blob
66
+ ): Promise<{ width: number; height: number } | null> {
67
+ if (typeof window === "undefined") return null;
68
+ if (typeof createImageBitmap === "function") {
69
+ try {
70
+ const bitmap = await createImageBitmap(file);
71
+ const size = { width: bitmap.width, height: bitmap.height };
72
+ bitmap.close();
73
+ return size;
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+ return new Promise((resolve) => {
79
+ const url = URL.createObjectURL(file);
80
+ const img = new window.Image();
81
+ img.onload = () => {
82
+ resolve({ width: img.naturalWidth, height: img.naturalHeight });
83
+ URL.revokeObjectURL(url);
84
+ };
85
+ img.onerror = () => {
86
+ resolve(null);
87
+ URL.revokeObjectURL(url);
88
+ };
89
+ img.src = url;
90
+ });
91
+ }
92
+
93
+ /** "JPG, PNG or PDF" from an `accept` map. Wildcard subtypes (`image/*`) are skipped. */
94
+ function describeAccept(accept?: Record<string, readonly string[]>): string {
95
+ if (!accept) return "";
96
+ const labels: string[] = [];
97
+ for (const [mime, exts] of Object.entries(accept)) {
98
+ for (const ext of exts) {
99
+ labels.push(ext.replace(/^\./, "").toUpperCase());
100
+ }
101
+ if (exts.length === 0 && mime.includes("/")) {
102
+ const subtype = mime.split("/").pop();
103
+ if (subtype && subtype !== "*") labels.push(subtype.toUpperCase());
104
+ }
105
+ }
106
+ const unique = [...new Set(labels)];
107
+ if (unique.length <= 1) return unique[0] ?? "";
108
+ return `${unique.slice(0, -1).join(", ")} or ${unique[unique.length - 1]}`;
109
+ }
110
+
111
+ /** Replace `{key}` placeholders in a message template. */
112
+ function formatMessage(
113
+ template: string,
114
+ vars: Record<string, string | number>
115
+ ): string {
116
+ return template.replace(/\{(\w+)\}/g, (match, key: string) =>
117
+ key in vars ? String(vars[key]) : match
118
+ );
119
+ }
120
+
121
+ function clampProgress(progress: number): number {
122
+ return Math.round(Math.min(100, Math.max(0, progress)));
123
+ }
124
+
125
+ /* -------------------------------------------------------------------------------------------------
126
+ * Messages — every user-facing string the component produces itself
127
+ * -----------------------------------------------------------------------------------------------*/
128
+
129
+ /**
130
+ * User-facing messages produced by `FileUpload` and `FileUploadSlot`:
131
+ * rejection reasons, upload outcomes and live-region announcements.
132
+ * Pass translations through the `messages` prop; placeholders in `{braces}`
133
+ * are filled in by the component.
134
+ */
135
+ interface FileUploadMessages {
136
+ /**
137
+ * Rejection: type not accepted and no accepted-types label is available.
138
+ * @default "This type of file isn't supported."
139
+ */
140
+ invalidType: string;
141
+ /**
142
+ * Rejection: type not accepted. `{label}` is the accepted-types label.
143
+ * @default "This type of file isn't supported. Use {label}."
144
+ */
145
+ invalidTypeWithLabel: string;
146
+ /**
147
+ * Rejection: over `maxSize`. `{size}` and `{maxSize}` are formatted sizes.
148
+ * @default "This file is {size}. Files need to be {maxSize} or smaller."
149
+ */
150
+ tooLarge: string;
151
+ /**
152
+ * Rejection: under `minSize`. `{size}` and `{minSize}` are formatted sizes.
153
+ * @default "This file is {size}. Files need to be at least {minSize}."
154
+ */
155
+ tooSmall: string;
156
+ /**
157
+ * Rejection: the single allowed file is already present (`maxFiles === 1`).
158
+ * @default "You can add one file. Remove it to add a different one."
159
+ */
160
+ tooManyFilesOne: string;
161
+ /**
162
+ * Rejection: `maxFiles` reached. `{maxFiles}` is the limit.
163
+ * @default "You've reached the limit of {maxFiles} files. Remove one to add another."
164
+ */
165
+ tooManyFiles: string;
166
+ /**
167
+ * Rejection: the browser could not decode the image for a `minImageSize` check.
168
+ * @default "We couldn't read this image."
169
+ */
170
+ imageUnreadable: string;
171
+ /**
172
+ * Rejection: under `minImageSize`. `{width}`, `{height}`, `{minWidth}`, `{minHeight}` in px.
173
+ * @default "This image is {width} × {height} px. Images need to be at least {minWidth} × {minHeight} px."
174
+ */
175
+ imageTooSmall: string;
176
+ /**
177
+ * Per-file error when the `onUpload` handler fails without a message.
178
+ * @default "Upload failed."
179
+ */
180
+ uploadFailed: string;
181
+ /**
182
+ * Announced after `FileUploadItemRemove` is activated. `{name}` is the file name.
183
+ * @default "{name} removed."
184
+ */
185
+ fileRemoved: string;
186
+ /**
187
+ * Announced when exactly one file uploaded.
188
+ * @default "1 file uploaded."
189
+ */
190
+ uploadedOne: string;
191
+ /**
192
+ * Announced when several files uploaded. `{n}` is the count.
193
+ * @default "{n} files uploaded."
194
+ */
195
+ uploadedMany: string;
196
+ /**
197
+ * Announced when exactly one file failed to upload.
198
+ * @default "1 file failed to upload."
199
+ */
200
+ uploadFailedOne: string;
201
+ /**
202
+ * Announced when several files failed to upload. `{n}` is the count.
203
+ * @default "{n} files failed to upload."
204
+ */
205
+ uploadFailedMany: string;
206
+ }
207
+
208
+ /** English defaults for every `FileUploadMessages` entry. */
209
+ const FILE_UPLOAD_MESSAGES: FileUploadMessages = {
210
+ invalidType: "This type of file isn't supported.",
211
+ invalidTypeWithLabel: "This type of file isn't supported. Use {label}.",
212
+ tooLarge: "This file is {size}. Files need to be {maxSize} or smaller.",
213
+ tooSmall: "This file is {size}. Files need to be at least {minSize}.",
214
+ tooManyFilesOne: "You can add one file. Remove it to add a different one.",
215
+ tooManyFiles:
216
+ "You've reached the limit of {maxFiles} files. Remove one to add another.",
217
+ imageUnreadable: "We couldn't read this image.",
218
+ imageTooSmall:
219
+ "This image is {width} × {height} px. Images need to be at least {minWidth} × {minHeight} px.",
220
+ uploadFailed: "Upload failed.",
221
+ fileRemoved: "{name} removed.",
222
+ uploadedOne: "1 file uploaded.",
223
+ uploadedMany: "{n} files uploaded.",
224
+ uploadFailedOne: "1 file failed to upload.",
225
+ uploadFailedMany: "{n} files failed to upload.",
226
+ };
227
+
228
+ function useMessages(
229
+ overrides: Partial<FileUploadMessages> | undefined
230
+ ): FileUploadMessages {
231
+ return React.useMemo(
232
+ () => ({ ...FILE_UPLOAD_MESSAGES, ...overrides }),
233
+ [overrides]
234
+ );
235
+ }
236
+
237
+ interface RejectMessageOptions {
238
+ accept?: Record<string, readonly string[]>;
239
+ acceptLabel?: string;
240
+ maxSize?: number;
241
+ minSize?: number;
242
+ maxFiles?: number;
243
+ messages: FileUploadMessages;
244
+ }
245
+
246
+ function rejectMessage(
247
+ file: File,
248
+ error: FileError,
249
+ opts: RejectMessageOptions
250
+ ): string {
251
+ const { messages } = opts;
252
+ switch (error) {
253
+ case "file-invalid-type": {
254
+ const label = opts.acceptLabel ?? describeAccept(opts.accept);
255
+ return label
256
+ ? formatMessage(messages.invalidTypeWithLabel, { label })
257
+ : messages.invalidType;
258
+ }
259
+ case "file-too-large":
260
+ return formatMessage(messages.tooLarge, {
261
+ size: formatBytes(file.size),
262
+ maxSize: formatBytes(opts.maxSize ?? 0),
263
+ });
264
+ case "file-too-small":
265
+ return formatMessage(messages.tooSmall, {
266
+ size: formatBytes(file.size),
267
+ minSize: formatBytes(opts.minSize ?? 0),
268
+ });
269
+ case "too-many-files":
270
+ return opts.maxFiles === 1
271
+ ? messages.tooManyFilesOne
272
+ : formatMessage(messages.tooManyFiles, {
273
+ maxFiles: opts.maxFiles ?? 0,
274
+ });
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Checks shared by `FileUpload` and `FileUploadSlot` that run after the
280
+ * synchronous type/size validation: image dimensions and the consumer's
281
+ * `onFileValidate`. Resolves the rejection message, or `null` when the file passes.
282
+ */
283
+ async function runAsyncChecks(
284
+ file: File,
285
+ opts: {
286
+ minImageSize?: { width: number; height: number };
287
+ onFileValidate?: FileValidator;
288
+ messages: FileUploadMessages;
289
+ }
290
+ ): Promise<string | null> {
291
+ const isImage =
292
+ file.type.startsWith("image/") ||
293
+ (!file.type &&
294
+ /\.(jpe?g|png|gif|webp|avif|svg|bmp|ico|tiff?)$/i.test(file.name));
295
+ if (opts.minImageSize && isImage) {
296
+ const dims = await getImageDimensions(file);
297
+ if (!dims) return opts.messages.imageUnreadable;
298
+ if (
299
+ dims.width < opts.minImageSize.width ||
300
+ dims.height < opts.minImageSize.height
301
+ ) {
302
+ return formatMessage(opts.messages.imageTooSmall, {
303
+ width: dims.width,
304
+ height: dims.height,
305
+ minWidth: opts.minImageSize.width,
306
+ minHeight: opts.minImageSize.height,
307
+ });
308
+ }
309
+ }
310
+ if (opts.onFileValidate) {
311
+ const msg = await opts.onFileValidate(file);
312
+ if (msg) return msg;
313
+ }
314
+ return null;
315
+ }
316
+
317
+ /* -------------------------------------------------------------------------------------------------
318
+ * File-type icon helper
319
+ * -----------------------------------------------------------------------------------------------*/
320
+
321
+ type IconComponent = React.ComponentType<{
322
+ size?: number;
323
+ strokeWidth?: number;
324
+ "aria-hidden"?: boolean | "true";
325
+ }>;
326
+
327
+ const MIME_ICON_MAP: Array<{
328
+ test: (mime: string, ext: string) => boolean;
329
+ icon: IconComponent;
330
+ }> = [
331
+ {
332
+ test: (mime) => mime.startsWith("image/"),
333
+ icon: FileImageIcon,
334
+ },
335
+ {
336
+ test: (mime, ext) =>
337
+ mime === "text/csv" ||
338
+ mime === "application/vnd.ms-excel" ||
339
+ mime ===
340
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
341
+ ext === "csv" ||
342
+ ext === "xlsx" ||
343
+ ext === "xls",
344
+ icon: FileSpreadsheetIcon,
345
+ },
346
+ {
347
+ test: (mime, ext) => mime === "application/json" || ext === "json",
348
+ icon: FileJsonIcon,
349
+ },
350
+ {
351
+ test: (mime, ext) =>
352
+ mime === "application/xml" ||
353
+ mime === "text/xml" ||
354
+ ext === "xml" ||
355
+ ext === "html" ||
356
+ ext === "htm" ||
357
+ ext === "svg",
358
+ icon: FileCodeIcon,
359
+ },
360
+ {
361
+ test: (mime, ext) =>
362
+ mime === "application/pdf" ||
363
+ mime.startsWith("text/") ||
364
+ ext === "pdf" ||
365
+ ext === "txt" ||
366
+ ext === "md" ||
367
+ ext === "doc" ||
368
+ ext === "docx" ||
369
+ ext === "rtf",
370
+ icon: FileTextIcon,
371
+ },
372
+ ];
373
+
374
+ /**
375
+ * Returns the icon component that best represents the file's type.
376
+ * Images → `FileImage`, spreadsheets → `FileSpreadsheet`,
377
+ * JSON → `FileJson`, XML/HTML → `FileCode`,
378
+ * text/PDF/docs → `FileText`, everything else → `File`.
379
+ */
380
+ function getFileTypeIcon(file: File): IconComponent {
381
+ const mime = file.type.toLowerCase();
382
+ const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
383
+ for (const entry of MIME_ICON_MAP) {
384
+ if (entry.test(mime, ext)) return entry.icon;
385
+ }
386
+ return FileIcon;
387
+ }
388
+
389
+ let rejectionIdCounter = 0;
390
+
391
+ /* -------------------------------------------------------------------------------------------------
392
+ * Live-region announcer
393
+ * -----------------------------------------------------------------------------------------------*/
394
+
395
+ /**
396
+ * Returns `[text, announce]`. Alternates a trailing space so repeating the
397
+ * same message still changes the DOM and is re-announced.
398
+ */
399
+ function useAnnouncer(): [string, (message: string) => void] {
400
+ const [announcement, setAnnouncement] = React.useState("");
401
+ const countRef = React.useRef(0);
402
+ const announce = React.useCallback((message: string) => {
403
+ countRef.current += 1;
404
+ setAnnouncement(message + (countRef.current % 2 === 0 ? "" : " "));
405
+ }, []);
406
+ return [announcement, announce];
407
+ }
408
+
409
+ /* -------------------------------------------------------------------------------------------------
410
+ * useObjectUrl — reference-counted object URL safe under React Strict Mode
411
+ * -----------------------------------------------------------------------------------------------*/
412
+
413
+ const objectUrls = new Map<Blob, { url: string; refs: number }>();
414
+
415
+ function getObjectUrl(blob: Blob): string {
416
+ const existing = objectUrls.get(blob);
417
+ if (existing) return existing.url;
418
+ const url = URL.createObjectURL(blob);
419
+ objectUrls.set(blob, { url, refs: 0 });
420
+ return url;
421
+ }
422
+
423
+ /**
424
+ * Creates and manages a browser object URL for a `Blob` or `File`.
425
+ * Reference-counted so the same file shared across components reuses one URL;
426
+ * the URL is revoked once the last component using it unmounts.
427
+ * Safe under React Strict Mode (double mount/unmount in development).
428
+ *
429
+ * The URL is created during render so the first paint already has it; a render
430
+ * that never commits leaves that one URL alive until the page unloads.
431
+ */
432
+ function useObjectUrl(file: Blob | null | undefined): string | undefined {
433
+ const url =
434
+ file && typeof window !== "undefined" ? getObjectUrl(file) : undefined;
435
+
436
+ React.useEffect(() => {
437
+ if (!file) return;
438
+ getObjectUrl(file);
439
+ const record = objectUrls.get(file)!;
440
+ record.refs++;
441
+ return () => {
442
+ record.refs--;
443
+ setTimeout(() => {
444
+ if (record.refs <= 0 && objectUrls.get(file) === record) {
445
+ URL.revokeObjectURL(record.url);
446
+ objectUrls.delete(file);
447
+ }
448
+ }, 0);
449
+ };
450
+ }, [file]);
451
+
452
+ return url;
453
+ }
454
+
455
+ /* -------------------------------------------------------------------------------------------------
456
+ * Upload status types
457
+ * -----------------------------------------------------------------------------------------------*/
458
+
459
+ /** Status of a file in the upload lifecycle. */
460
+ type FileUploadStatus = "idle" | "uploading" | "success" | "error";
461
+
462
+ interface FileUploadFileState {
463
+ status: FileUploadStatus;
464
+ /** 0 to 100. */
465
+ progress: number;
466
+ /** Plain-English error message when status is "error". */
467
+ error?: string;
468
+ }
469
+
470
+ const DEFAULT_FILE_STATE: FileUploadFileState = {
471
+ status: "idle",
472
+ progress: 0,
473
+ };
474
+
475
+ /** Callbacks provided to the `onUpload` handler for per-file progress reporting. */
476
+ interface FileUploadHelpers {
477
+ onProgress: (file: File, progress: number) => void;
478
+ onSuccess: (file: File) => void;
479
+ /** Pass a plain-English message or an Error. Falls back to `messages.uploadFailed`. */
480
+ onError: (file: File, error?: Error | string) => void;
481
+ }
482
+
483
+ /**
484
+ * Handler for uploading accepted files. Called with newly accepted files and
485
+ * helpers to report per-file progress, success, or failure. Any file not
486
+ * resolved through `onSuccess`/`onError` by the time the handler settles is
487
+ * marked failed.
488
+ */
489
+ type FileUploadHandler = (
490
+ files: File[],
491
+ helpers: FileUploadHelpers
492
+ ) => Promise<void> | void;
493
+
494
+ /**
495
+ * Extra per-file check. Return a plain-English message to reject the file, or
496
+ * `null`/`undefined` to accept. Can be async (e.g. for image dimension checks).
497
+ */
498
+ type FileValidator = (
499
+ file: File
500
+ ) => string | null | undefined | Promise<string | null | undefined>;
501
+
502
+ /* -------------------------------------------------------------------------------------------------
503
+ * Presets
504
+ * -----------------------------------------------------------------------------------------------*/
505
+
506
+ /**
507
+ * Standard photo upload rules for BrightLocal location photos.
508
+ * JPG/PNG, 10 KB–5 MB, at least 250 × 250 px.
509
+ */
510
+ const PHOTO_UPLOAD_RULES = {
511
+ accept: { "image/jpeg": [".jpg", ".jpeg"], "image/png": [".png"] },
512
+ acceptLabel: "JPG or PNG",
513
+ minSize: 10 * 1024,
514
+ maxSize: 5 * 1024 * 1024,
515
+ minImageSize: { width: 250, height: 250 },
516
+ } as const;
517
+
518
+ /* -------------------------------------------------------------------------------------------------
519
+ * FileUpload Context
520
+ * -----------------------------------------------------------------------------------------------*/
521
+
522
+ interface FileUploadRejectionEntry {
523
+ id: string;
524
+ name: string;
525
+ message: string;
526
+ }
527
+
528
+ interface FileUploadContextValue {
529
+ state: DropzoneState;
530
+ dragActive: boolean;
531
+ disabled: boolean;
532
+ files: File[];
533
+ maxFiles: number | undefined;
534
+ openFilePicker: () => void;
535
+ dropzoneProps: ReturnType<typeof useFileDropzone>["dropzoneProps"];
536
+ inputProps: ReturnType<typeof useFileDropzone>["inputProps"];
537
+ inputRef: React.RefObject<HTMLInputElement | null>;
538
+ rootRef: React.RefObject<HTMLDivElement | null>;
539
+ rejections: FileUploadRejectionEntry[];
540
+ dismissRejection: (id: string) => void;
541
+ clearRejections: () => void;
542
+ announce: (message: string) => void;
543
+ getFileStatus: (file: File) => FileUploadFileState;
544
+ messages: FileUploadMessages;
545
+ }
546
+
547
+ const FileUploadContext = React.createContext<FileUploadContextValue | null>(
548
+ null
549
+ );
550
+
551
+ function useFileUploadContext() {
552
+ const context = React.useContext(FileUploadContext);
553
+ if (!context) {
554
+ throw new Error("FileUpload components must be used within a <FileUpload>");
555
+ }
556
+ return context;
557
+ }
558
+
559
+ /* -------------------------------------------------------------------------------------------------
560
+ * FileUpload (Root)
561
+ * -----------------------------------------------------------------------------------------------*/
562
+
563
+ interface FileUploadProps extends React.ComponentPropsWithoutRef<"div"> {
564
+ /** Required test hook identifier. */
565
+ dataHook: string;
566
+ /**
567
+ * Accepted MIME types or extensions, keyed by MIME with extension arrays.
568
+ * @example { "image/*": [".png", ".jpg"], "application/pdf": [".pdf"] }
569
+ */
570
+ accept?: Record<string, readonly string[]>;
571
+ /**
572
+ * Human-readable label for accepted types, used in rejection messages.
573
+ * Derived from `accept` when omitted.
574
+ * @example "JPG or PNG"
575
+ */
576
+ acceptLabel?: string;
577
+ /** Maximum file size in bytes. */
578
+ maxSize?: number;
579
+ /** Minimum file size in bytes. */
580
+ minSize?: number;
581
+ /**
582
+ * Maximum number of files in the list, counting files already present.
583
+ * `1` disables `multiple` on the input when `multiple` is not set.
584
+ */
585
+ maxFiles?: number;
586
+ /** Whether the file input accepts multiple files. Defaults to `maxFiles !== 1`. */
587
+ multiple?: boolean;
588
+ /** Minimum pixel dimensions for image files. */
589
+ minImageSize?: { width: number; height: number };
590
+ /** Whether the file upload is disabled. */
591
+ disabled?: boolean;
592
+ /** Custom validation function. Return an array of error codes or empty array. */
593
+ validate?: UseFileDropzoneOptions["validate"];
594
+ /**
595
+ * Extra per-file check. Return a plain-English message to reject the file, or `null` to accept.
596
+ * Can be async (e.g. for image dimension checks).
597
+ */
598
+ onFileValidate?: FileValidator;
599
+ /** Controlled list of accepted files. */
600
+ value?: File[];
601
+ /** Called with the full updated file list when accepted files change. */
602
+ onValueChange?: (files: File[]) => void;
603
+ /**
604
+ * Called for each file that fails validation, with a human-readable message.
605
+ * Fires for both built-in validation (type, size, count) and custom `onFileValidate`.
606
+ */
607
+ onFileReject?: (file: File, message: string) => void;
608
+ /** Called with accepted and rejected files after a drop or file pick. */
609
+ onFilesChange?: (details: {
610
+ acceptedFiles: File[];
611
+ rejectedFiles: FileRejection[];
612
+ }) => void;
613
+ /**
614
+ * Upload handler. Called with newly accepted files after validation passes.
615
+ * Use the helpers to report per-file progress, success, or failure.
616
+ */
617
+ onUpload?: FileUploadHandler;
618
+ /**
619
+ * Translations for the messages the component produces (rejection reasons,
620
+ * upload outcomes, announcements). Merged over the English defaults.
621
+ * @default FILE_UPLOAD_MESSAGES
622
+ */
623
+ messages?: Partial<FileUploadMessages>;
624
+ /** Analytics element identifier. */
625
+ trackingEl?: string;
626
+ /** Analytics label. */
627
+ trackingLabel?: string;
628
+ }
629
+
630
+ const FileUpload = React.forwardRef<HTMLDivElement, FileUploadProps>(
631
+ (
632
+ {
633
+ className,
634
+ dataHook,
635
+ accept,
636
+ acceptLabel,
637
+ maxSize,
638
+ minSize,
639
+ maxFiles,
640
+ multiple,
641
+ minImageSize,
642
+ disabled = false,
643
+ validate,
644
+ onFileValidate,
645
+ value,
646
+ onValueChange,
647
+ onFileReject,
648
+ onFilesChange,
649
+ onUpload,
650
+ messages: messagesProp,
651
+ trackingEl,
652
+ trackingLabel,
653
+ children,
654
+ ...props
655
+ },
656
+ ref
657
+ ) => {
658
+ const [internalFiles, setInternalFiles] = React.useState<File[]>([]);
659
+ const isControlled = value !== undefined;
660
+ const files = isControlled ? value : internalFiles;
661
+ const messages = useMessages(messagesProp);
662
+
663
+ const rootRef = React.useRef<HTMLDivElement | null>(null);
664
+
665
+ const [rejections, setRejections] = React.useState<
666
+ FileUploadRejectionEntry[]
667
+ >([]);
668
+ const [announcement, announce] = useAnnouncer();
669
+
670
+ const dismissRejection = React.useCallback((id: string) => {
671
+ setRejections((prev) => prev.filter((r) => r.id !== id));
672
+ }, []);
673
+
674
+ const clearRejections = React.useCallback(() => {
675
+ setRejections([]);
676
+ }, []);
677
+
678
+ const [fileStatuses, setFileStatuses] = React.useState<
679
+ Map<File, FileUploadFileState>
680
+ >(() => new Map());
681
+
682
+ const updateFileStatus = React.useCallback(
683
+ (file: File, updates: Partial<FileUploadFileState>) => {
684
+ setFileStatuses((prev) => {
685
+ const next = new Map(prev);
686
+ const current = next.get(file) ?? { ...DEFAULT_FILE_STATE };
687
+ next.set(file, { ...current, ...updates });
688
+ return next;
689
+ });
690
+ },
691
+ []
692
+ );
693
+
694
+ const getFileStatus = React.useCallback(
695
+ (file: File): FileUploadFileState => {
696
+ return fileStatuses.get(file) ?? DEFAULT_FILE_STATE;
697
+ },
698
+ [fileStatuses]
699
+ );
700
+
701
+ // Drop the status of files that left the list, so a re-added File object
702
+ // starts idle and the map doesn't grow with every removal.
703
+ const previousFilesRef = React.useRef<File[]>(files);
704
+ React.useEffect(() => {
705
+ const removed = previousFilesRef.current.filter(
706
+ (f) => !files.includes(f)
707
+ );
708
+ previousFilesRef.current = files;
709
+ if (removed.length === 0) return;
710
+ setFileStatuses((prev) => {
711
+ const next = new Map(prev);
712
+ for (const file of removed) next.delete(file);
713
+ return next;
714
+ });
715
+ }, [files]);
716
+
717
+ const latestRef = React.useRef({
718
+ files,
719
+ maxFiles,
720
+ minImageSize,
721
+ acceptLabel,
722
+ accept,
723
+ maxSize,
724
+ minSize,
725
+ messages,
726
+ onFileValidate,
727
+ onValueChange,
728
+ onFileReject,
729
+ onFilesChange,
730
+ onUpload,
731
+ });
732
+ React.useEffect(() => {
733
+ latestRef.current = {
734
+ files,
735
+ maxFiles,
736
+ minImageSize,
737
+ acceptLabel,
738
+ accept,
739
+ maxSize,
740
+ minSize,
741
+ messages,
742
+ onFileValidate,
743
+ onValueChange,
744
+ onFileReject,
745
+ onFilesChange,
746
+ onUpload,
747
+ };
748
+ });
749
+
750
+ const runUpload = React.useCallback(
751
+ async (accepted: File[]) => {
752
+ const handler = latestRef.current.onUpload;
753
+ if (!handler || accepted.length === 0) return;
754
+ const { messages: msgs } = latestRef.current;
755
+
756
+ // Outcomes are tracked locally: React state can't be read back
757
+ // synchronously after the handler settles.
758
+ const outcomes = new Map<File, "success" | "error">();
759
+
760
+ for (const file of accepted) {
761
+ updateFileStatus(file, {
762
+ status: "uploading",
763
+ progress: 0,
764
+ error: undefined,
765
+ });
766
+ }
767
+
768
+ try {
769
+ await handler(accepted, {
770
+ onProgress: (file, progress) => {
771
+ updateFileStatus(file, { progress: clampProgress(progress) });
772
+ },
773
+ onSuccess: (file) => {
774
+ outcomes.set(file, "success");
775
+ updateFileStatus(file, { status: "success", progress: 100 });
776
+ },
777
+ onError: (file, error) => {
778
+ outcomes.set(file, "error");
779
+ const message =
780
+ typeof error === "string" ? error : error?.message;
781
+ updateFileStatus(file, {
782
+ status: "error",
783
+ error: message || msgs.uploadFailed,
784
+ });
785
+ },
786
+ });
787
+ } catch {
788
+ // handler threw — unresolved files are marked failed below
789
+ }
790
+
791
+ let failed = 0;
792
+ for (const file of accepted) {
793
+ const outcome = outcomes.get(file);
794
+ if (outcome === "error") {
795
+ failed++;
796
+ } else if (outcome === undefined) {
797
+ failed++;
798
+ updateFileStatus(file, {
799
+ status: "error",
800
+ error: msgs.uploadFailed,
801
+ });
802
+ }
803
+ }
804
+ const succeeded = accepted.length - failed;
805
+
806
+ const parts: string[] = [];
807
+ if (failed > 0) {
808
+ parts.push(
809
+ failed === 1
810
+ ? msgs.uploadFailedOne
811
+ : formatMessage(msgs.uploadFailedMany, { n: failed })
812
+ );
813
+ }
814
+ if (succeeded > 0) {
815
+ parts.push(
816
+ succeeded === 1
817
+ ? msgs.uploadedOne
818
+ : formatMessage(msgs.uploadedMany, { n: succeeded })
819
+ );
820
+ }
821
+ announce(parts.join(" "));
822
+ },
823
+ [updateFileStatus, announce]
824
+ );
825
+
826
+ const handleFilesChange = React.useCallback(
827
+ (details: { acceptedFiles: File[]; rejectedFiles: FileRejection[] }) => {
828
+ void (async () => {
829
+ const current = latestRef.current;
830
+ const newRejections: FileUploadRejectionEntry[] = [];
831
+ const reject = (file: File, message: string) => {
832
+ current.onFileReject?.(file, message);
833
+ rejectionIdCounter += 1;
834
+ newRejections.push({
835
+ id: String(rejectionIdCounter),
836
+ name: file.name,
837
+ message,
838
+ });
839
+ };
840
+
841
+ for (const { file, errors } of details.rejectedFiles) {
842
+ const firstError = errors[0];
843
+ if (firstError)
844
+ reject(file, rejectMessage(file, firstError, current));
845
+ }
846
+
847
+ // Per-file async checks first…
848
+ const candidates: File[] = [];
849
+ for (const file of details.acceptedFiles) {
850
+ const message = await runAsyncChecks(file, current);
851
+ if (message) {
852
+ reject(file, message);
853
+ continue;
854
+ }
855
+ candidates.push(file);
856
+ }
857
+
858
+ // …then the count limit against the list as it is *after* the awaits,
859
+ // so a second drop that landed meanwhile is counted. (Two batches
860
+ // settling in the same tick still see one render's `files`; the
861
+ // uncontrolled path below is a functional update and stays correct.)
862
+ const latest = latestRef.current;
863
+ const baseFiles = latest.files;
864
+ const room =
865
+ latest.maxFiles !== undefined
866
+ ? Math.max(0, latest.maxFiles - baseFiles.length)
867
+ : Infinity;
868
+ const finalAccepted = candidates.slice(0, room);
869
+ for (const file of candidates.slice(finalAccepted.length)) {
870
+ reject(file, rejectMessage(file, "too-many-files", latest));
871
+ }
872
+
873
+ if (newRejections.length > 0) {
874
+ setRejections((prev) => [...prev, ...newRejections]);
875
+ }
876
+
877
+ if (finalAccepted.length > 0) {
878
+ if (!isControlled) {
879
+ setInternalFiles((prev) => [...prev, ...finalAccepted]);
880
+ }
881
+ latest.onValueChange?.([...baseFiles, ...finalAccepted]);
882
+ }
883
+
884
+ latest.onFilesChange?.({
885
+ acceptedFiles: finalAccepted,
886
+ rejectedFiles: details.rejectedFiles,
887
+ });
888
+
889
+ if (finalAccepted.length > 0 && latest.onUpload) {
890
+ void runUpload(finalAccepted);
891
+ }
892
+ })();
893
+ },
894
+ [isControlled, runUpload]
895
+ );
896
+
897
+ const dropzone = useFileDropzone({
898
+ accept,
899
+ maxSize,
900
+ minSize,
901
+ // The hook's limit is per batch; the total is enforced above.
902
+ maxFiles: undefined,
903
+ multiple: multiple ?? maxFiles !== 1,
904
+ disabled,
905
+ validate,
906
+ onFilesChange: handleFilesChange,
907
+ });
908
+
909
+ const contextValue = React.useMemo<FileUploadContextValue>(
910
+ () => ({
911
+ state: dropzone.state,
912
+ dragActive: dropzone.dragActive,
913
+ disabled,
914
+ files,
915
+ maxFiles,
916
+ openFilePicker: dropzone.openFilePicker,
917
+ dropzoneProps: dropzone.dropzoneProps,
918
+ inputProps: dropzone.inputProps,
919
+ inputRef: dropzone.inputRef,
920
+ rootRef,
921
+ rejections,
922
+ dismissRejection,
923
+ clearRejections,
924
+ announce,
925
+ getFileStatus,
926
+ messages,
927
+ }),
928
+ [
929
+ dropzone,
930
+ disabled,
931
+ files,
932
+ maxFiles,
933
+ rejections,
934
+ dismissRejection,
935
+ clearRejections,
936
+ announce,
937
+ getFileStatus,
938
+ messages,
939
+ ]
940
+ );
941
+
942
+ const setRefs = React.useCallback(
943
+ (node: HTMLDivElement | null) => {
944
+ rootRef.current = node;
945
+ if (typeof ref === "function") {
946
+ ref(node);
947
+ } else if (ref) {
948
+ (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
949
+ }
950
+ },
951
+ [ref]
952
+ );
953
+
954
+ return (
955
+ <FileUploadContext.Provider value={contextValue}>
956
+ <div
957
+ ref={setRefs}
958
+ className={cn("relative flex flex-col gap-3", className)}
959
+ data-hook={dataHook}
960
+ data-slot="file-upload"
961
+ data-tracking-el={trackingEl ?? "file-upload"}
962
+ data-tracking-label={trackingLabel}
963
+ {...props}
964
+ >
965
+ {children}
966
+ <div
967
+ aria-live="polite"
968
+ className="sr-only"
969
+ data-slot="file-upload-announcer"
970
+ role="status"
971
+ >
972
+ {announcement}
973
+ </div>
974
+ </div>
975
+ </FileUploadContext.Provider>
976
+ );
977
+ }
978
+ );
979
+
980
+ FileUpload.displayName = "FileUpload";
981
+
982
+ /* -------------------------------------------------------------------------------------------------
983
+ * FileUploadDropzone
984
+ * -----------------------------------------------------------------------------------------------*/
985
+
986
+ const dropzoneStyles = cva(
987
+ [
988
+ "relative flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed p-6",
989
+ "transition-[border-color,background-color] duration-fast ease-out",
990
+ "outline-none has-[:focus-visible]:shadow-default has-[:focus-visible]:border-transparent",
991
+ "cursor-pointer",
992
+ ],
993
+ {
994
+ variants: {
995
+ state: {
996
+ idle: "border-input bg-background hover:bg-accent",
997
+ accept: "border-success-mark bg-success-mark/5 dark:bg-success-mark/10",
998
+ reject: "border-destructive bg-destructive/5 dark:bg-destructive/10",
999
+ },
1000
+ disabled: {
1001
+ true: "pointer-events-none cursor-not-allowed opacity-50",
1002
+ },
1003
+ },
1004
+ defaultVariants: {
1005
+ state: "idle",
1006
+ disabled: false,
1007
+ },
1008
+ }
1009
+ );
1010
+
1011
+ interface FileUploadDropzoneProps extends React.ComponentPropsWithoutRef<"div"> {
1012
+ /** Test hook identifier. */
1013
+ dataHook?: string;
1014
+ /**
1015
+ * Accessible label for the file input.
1016
+ * @default "Upload file"
1017
+ */
1018
+ ariaLabel?: string;
1019
+ }
1020
+
1021
+ const FileUploadDropzone = React.forwardRef<
1022
+ HTMLDivElement,
1023
+ FileUploadDropzoneProps
1024
+ >(
1025
+ (
1026
+ {
1027
+ className,
1028
+ dataHook,
1029
+ ariaLabel,
1030
+ children,
1031
+ onClick,
1032
+ onDragEnter,
1033
+ onDragOver,
1034
+ onDragLeave,
1035
+ onDrop,
1036
+ onPaste,
1037
+ ...props
1038
+ },
1039
+ ref
1040
+ ) => {
1041
+ const {
1042
+ state,
1043
+ disabled,
1044
+ openFilePicker,
1045
+ dropzoneProps,
1046
+ inputProps,
1047
+ inputRef,
1048
+ } = useFileUploadContext();
1049
+
1050
+ const handleClick = React.useCallback(
1051
+ (e: React.MouseEvent<HTMLDivElement>) => {
1052
+ if ((e.target as HTMLElement).closest("button, a, input")) return;
1053
+ openFilePicker();
1054
+ },
1055
+ [openFilePicker]
1056
+ );
1057
+
1058
+ return (
1059
+ // The zone itself is not focusable: keyboard users reach the visually
1060
+ // hidden <input type="file"> inside it, which opens the picker natively.
1061
+ // eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events
1062
+ <div
1063
+ ref={ref}
1064
+ aria-disabled={disabled ? "true" : undefined}
1065
+ className={cn(dropzoneStyles({ state, disabled }), className)}
1066
+ data-hook={dataHook}
1067
+ data-slot="file-upload-dropzone"
1068
+ data-state={state}
1069
+ onClick={composeEventHandlers(onClick, handleClick)}
1070
+ onDragEnter={composeEventHandlers(
1071
+ onDragEnter,
1072
+ dropzoneProps.onDragEnter
1073
+ )}
1074
+ onDragLeave={composeEventHandlers(
1075
+ onDragLeave,
1076
+ dropzoneProps.onDragLeave
1077
+ )}
1078
+ onDragOver={composeEventHandlers(onDragOver, dropzoneProps.onDragOver)}
1079
+ onDrop={composeEventHandlers(onDrop, dropzoneProps.onDrop)}
1080
+ onPaste={composeEventHandlers(onPaste, dropzoneProps.onPaste)}
1081
+ {...props}
1082
+ >
1083
+ <input
1084
+ ref={inputRef}
1085
+ {...inputProps}
1086
+ aria-label={ariaLabel ?? "Upload file"}
1087
+ data-hook={dataHook ? `${dataHook}-input` : undefined}
1088
+ disabled={disabled}
1089
+ tabIndex={disabled ? -1 : 0}
1090
+ />
1091
+ {children}
1092
+ </div>
1093
+ );
1094
+ }
1095
+ );
1096
+
1097
+ FileUploadDropzone.displayName = "FileUploadDropzone";
1098
+
1099
+ /* -------------------------------------------------------------------------------------------------
1100
+ * FileUploadTrigger
1101
+ * -----------------------------------------------------------------------------------------------*/
1102
+
1103
+ interface FileUploadTriggerProps extends React.ComponentPropsWithoutRef<"button"> {
1104
+ /** Test hook identifier. */
1105
+ dataHook?: string;
1106
+ /** Render as child element. */
1107
+ asChild?: boolean;
1108
+ }
1109
+
1110
+ const FileUploadTrigger = React.forwardRef<
1111
+ HTMLButtonElement,
1112
+ FileUploadTriggerProps
1113
+ >(({ asChild = false, dataHook, onClick, children, ...props }, ref) => {
1114
+ const { disabled, openFilePicker } = useFileUploadContext();
1115
+
1116
+ const Comp = asChild ? Slot : "button";
1117
+
1118
+ return (
1119
+ <Comp
1120
+ ref={ref}
1121
+ data-file-upload-trigger=""
1122
+ data-hook={dataHook}
1123
+ data-slot="file-upload-trigger"
1124
+ disabled={disabled}
1125
+ type={asChild ? undefined : "button"}
1126
+ onClick={composeEventHandlers(onClick, openFilePicker)}
1127
+ {...props}
1128
+ >
1129
+ {children}
1130
+ </Comp>
1131
+ );
1132
+ });
1133
+
1134
+ FileUploadTrigger.displayName = "FileUploadTrigger";
1135
+
1136
+ /* -------------------------------------------------------------------------------------------------
1137
+ * FileUploadIdle / FileUploadAccept / FileUploadReject
1138
+ * -----------------------------------------------------------------------------------------------*/
1139
+
1140
+ interface FileUploadStateChildProps {
1141
+ children: React.ReactNode;
1142
+ }
1143
+
1144
+ function FileUploadIdle({ children }: FileUploadStateChildProps) {
1145
+ const { state } = useFileUploadContext();
1146
+ if (state !== "idle") return null;
1147
+ return <>{children}</>;
1148
+ }
1149
+
1150
+ FileUploadIdle.displayName = "FileUploadIdle";
1151
+
1152
+ function FileUploadAccept({ children }: FileUploadStateChildProps) {
1153
+ const { state } = useFileUploadContext();
1154
+ if (state !== "accept") return null;
1155
+ return <>{children}</>;
1156
+ }
1157
+
1158
+ FileUploadAccept.displayName = "FileUploadAccept";
1159
+
1160
+ function FileUploadReject({ children }: FileUploadStateChildProps) {
1161
+ const { state } = useFileUploadContext();
1162
+ if (state !== "reject") return null;
1163
+ return <>{children}</>;
1164
+ }
1165
+
1166
+ FileUploadReject.displayName = "FileUploadReject";
1167
+
1168
+ /* -------------------------------------------------------------------------------------------------
1169
+ * FileUploadDropzoneContent — pre-composed idle/accept/reject content
1170
+ * -----------------------------------------------------------------------------------------------*/
1171
+
1172
+ interface FileUploadDropzoneContentProps extends Omit<
1173
+ React.ComponentPropsWithoutRef<"div">,
1174
+ "children"
1175
+ > {
1176
+ /** Required test hook identifier. */
1177
+ dataHook: string;
1178
+ /** Icon shown in the idle state. */
1179
+ icon: React.ComponentType<{ size?: number; className?: string }>;
1180
+ /** Title shown in the idle state. */
1181
+ title: string;
1182
+ /** Description shown below the title in the idle state. */
1183
+ description: string;
1184
+ /**
1185
+ * Label for the trigger button in the idle state. Omit to hide the button.
1186
+ */
1187
+ triggerLabel?: string;
1188
+ /**
1189
+ * Text shown during the accept (drag-over-valid) state.
1190
+ * @default "Release to upload"
1191
+ */
1192
+ acceptMessage?: string;
1193
+ /**
1194
+ * Text shown during the reject (drag-over-invalid) state.
1195
+ * @default "File not accepted"
1196
+ */
1197
+ rejectMessage?: string;
1198
+ /** Analytics element identifier. */
1199
+ trackingEl?: string;
1200
+ /** Analytics label. */
1201
+ trackingLabel?: string;
1202
+ }
1203
+
1204
+ const FileUploadDropzoneContent = React.forwardRef<
1205
+ HTMLDivElement,
1206
+ FileUploadDropzoneContentProps
1207
+ >(
1208
+ (
1209
+ {
1210
+ className,
1211
+ dataHook,
1212
+ icon: Icon,
1213
+ title,
1214
+ description,
1215
+ triggerLabel,
1216
+ acceptMessage,
1217
+ rejectMessage,
1218
+ trackingEl,
1219
+ trackingLabel,
1220
+ ...props
1221
+ },
1222
+ ref
1223
+ ) => {
1224
+ return (
1225
+ <div
1226
+ ref={ref}
1227
+ className={cn(
1228
+ "flex flex-col items-center gap-2 text-center",
1229
+ className
1230
+ )}
1231
+ data-slot="file-upload-dropzone-content"
1232
+ {...props}
1233
+ >
1234
+ <FileUploadIdle>
1235
+ {/* The icon chip is the DS LogoMark at lg — a 40px circle — in all
1236
+ three drag states, so the shape never changes mid-drag. Idle is
1237
+ the muted chip; accept and reject use LogoMark's `success` /
1238
+ `destructive` variant, and each message uses the same ink as
1239
+ its chip's glyph (score-strong-ink, score-poor-ink), alongside
1240
+ the dropzone border and fill (DS-1291). */}
1241
+ <LogoMark
1242
+ data-slot="file-upload-dropzone-icon"
1243
+ data-state="idle"
1244
+ dataHook={`${dataHook}-icon`}
1245
+ name={<Icon className="text-muted-foreground" />}
1246
+ shape="circle"
1247
+ size="lg"
1248
+ />
1249
+ <TypographyText dataHook={`${dataHook}-title`}>
1250
+ {title}
1251
+ </TypographyText>
1252
+ <TypographyText
1253
+ color="muted"
1254
+ dataHook={`${dataHook}-description`}
1255
+ variant="body-sm"
1256
+ >
1257
+ {description}
1258
+ </TypographyText>
1259
+ {triggerLabel && (
1260
+ <FileUploadTrigger asChild dataHook={`${dataHook}-trigger`}>
1261
+ <Button
1262
+ className="mt-1"
1263
+ data-tracking-el={trackingEl}
1264
+ data-tracking-label={trackingLabel}
1265
+ dataHook={`${dataHook}-trigger-btn`}
1266
+ size="sm"
1267
+ variant="outline"
1268
+ >
1269
+ {triggerLabel}
1270
+ </Button>
1271
+ </FileUploadTrigger>
1272
+ )}
1273
+ </FileUploadIdle>
1274
+ <FileUploadAccept>
1275
+ <LogoMark
1276
+ data-slot="file-upload-dropzone-icon"
1277
+ data-state="accept"
1278
+ dataHook={`${dataHook}-icon`}
1279
+ name={<Icon />}
1280
+ shape="circle"
1281
+ size="lg"
1282
+ variant="success"
1283
+ />
1284
+ <TypographyText
1285
+ className="text-score-strong-ink"
1286
+ dataHook={`${dataHook}-accept-message`}
1287
+ >
1288
+ {acceptMessage ?? "Release to upload"}
1289
+ </TypographyText>
1290
+ </FileUploadAccept>
1291
+ <FileUploadReject>
1292
+ <LogoMark
1293
+ data-slot="file-upload-dropzone-icon"
1294
+ data-state="reject"
1295
+ dataHook={`${dataHook}-icon`}
1296
+ name={<CircleX />}
1297
+ shape="circle"
1298
+ size="lg"
1299
+ variant="destructive"
1300
+ />
1301
+ <TypographyText
1302
+ className="text-score-poor-ink"
1303
+ dataHook={`${dataHook}-reject-message`}
1304
+ >
1305
+ {rejectMessage ?? "File not accepted"}
1306
+ </TypographyText>
1307
+ </FileUploadReject>
1308
+ </div>
1309
+ );
1310
+ }
1311
+ );
1312
+
1313
+ FileUploadDropzoneContent.displayName = "FileUploadDropzoneContent";
1314
+
1315
+ /* -------------------------------------------------------------------------------------------------
1316
+ * FileUploadList
1317
+ * -----------------------------------------------------------------------------------------------*/
1318
+
1319
+ const fileUploadListStyles = cva("", {
1320
+ variants: {
1321
+ variant: {
1322
+ list: "flex flex-col gap-2",
1323
+ grid: "grid grid-cols-3 gap-2 sm:grid-cols-4 sm:gap-3 xl:grid-cols-5 2xl:grid-cols-6",
1324
+ },
1325
+ },
1326
+ defaultVariants: {
1327
+ variant: "list",
1328
+ },
1329
+ });
1330
+
1331
+ interface FileUploadListProps extends React.ComponentPropsWithoutRef<"ul"> {
1332
+ /** Test hook identifier. */
1333
+ dataHook?: string;
1334
+ /**
1335
+ * Accessible label for the file list.
1336
+ * @default "Uploaded files"
1337
+ */
1338
+ ariaLabel?: string;
1339
+ /**
1340
+ * Layout variant for the file list.
1341
+ * @default "list"
1342
+ */
1343
+ variant?: "list" | "grid";
1344
+ }
1345
+
1346
+ const FileUploadList = React.forwardRef<HTMLUListElement, FileUploadListProps>(
1347
+ (
1348
+ { className, dataHook, ariaLabel, variant = "list", children, ...props },
1349
+ ref
1350
+ ) => {
1351
+ return (
1352
+ <ul
1353
+ ref={ref}
1354
+ aria-label={ariaLabel ?? "Uploaded files"}
1355
+ className={cn(fileUploadListStyles({ variant }), className)}
1356
+ data-hook={dataHook}
1357
+ data-slot="file-upload-list"
1358
+ data-variant={variant}
1359
+ {...props}
1360
+ >
1361
+ {children}
1362
+ </ul>
1363
+ );
1364
+ }
1365
+ );
1366
+
1367
+ FileUploadList.displayName = "FileUploadList";
1368
+
1369
+ /* -------------------------------------------------------------------------------------------------
1370
+ * FileUploadItem
1371
+ * -----------------------------------------------------------------------------------------------*/
1372
+
1373
+ interface FileUploadItemProps extends React.ComponentPropsWithoutRef<"li"> {
1374
+ /** Test hook identifier. */
1375
+ dataHook?: string;
1376
+ }
1377
+
1378
+ const FileUploadItem = React.forwardRef<HTMLLIElement, FileUploadItemProps>(
1379
+ ({ className, dataHook, children, ...props }, ref) => {
1380
+ return (
1381
+ <li
1382
+ ref={ref}
1383
+ className={cn("flex items-center gap-2", className)}
1384
+ data-hook={dataHook}
1385
+ data-slot="file-upload-item"
1386
+ {...props}
1387
+ >
1388
+ {children}
1389
+ </li>
1390
+ );
1391
+ }
1392
+ );
1393
+
1394
+ FileUploadItem.displayName = "FileUploadItem";
1395
+
1396
+ /* -------------------------------------------------------------------------------------------------
1397
+ * FileUploadItemPreview — image thumbnail or file icon
1398
+ * -----------------------------------------------------------------------------------------------*/
1399
+
1400
+ const previewStyles = cva(
1401
+ "bg-muted text-muted-foreground relative flex items-center justify-center overflow-hidden rounded-md",
1402
+ {
1403
+ variants: {
1404
+ size: {
1405
+ sm: "size-10 shrink-0",
1406
+ lg: "aspect-square w-full",
1407
+ },
1408
+ },
1409
+ defaultVariants: { size: "sm" },
1410
+ }
1411
+ );
1412
+
1413
+ interface FileUploadItemPreviewProps extends React.ComponentPropsWithoutRef<"div"> {
1414
+ /** Test hook identifier. */
1415
+ dataHook?: string;
1416
+ /** The file to preview. */
1417
+ file: File;
1418
+ /**
1419
+ * Preview size. `"sm"` for inline list items, `"lg"` for grid cards.
1420
+ * @default "sm"
1421
+ */
1422
+ size?: "sm" | "lg";
1423
+ /** Optional overlay content (e.g. a remove button positioned absolutely). */
1424
+ children?: React.ReactNode;
1425
+ }
1426
+
1427
+ const FileUploadItemPreview = React.forwardRef<
1428
+ HTMLDivElement,
1429
+ FileUploadItemPreviewProps
1430
+ >(({ className, dataHook, file, size = "sm", children, ...props }, ref) => {
1431
+ const url = useObjectUrl(file);
1432
+ const isImage = file.type.startsWith("image/");
1433
+
1434
+ return (
1435
+ <div
1436
+ ref={ref}
1437
+ className={cn(previewStyles({ size }), className)}
1438
+ data-hook={dataHook}
1439
+ data-size={size}
1440
+ data-slot="file-upload-item-preview"
1441
+ {...props}
1442
+ >
1443
+ {isImage && url ? (
1444
+ <img alt={file.name} className="size-full object-cover" src={url} />
1445
+ ) : (
1446
+ React.createElement(getFileTypeIcon(file), {
1447
+ "aria-hidden": true,
1448
+ size: size === "lg" ? 32 : 20,
1449
+ strokeWidth: 1.5,
1450
+ })
1451
+ )}
1452
+ {children}
1453
+ </div>
1454
+ );
1455
+ });
1456
+
1457
+ FileUploadItemPreview.displayName = "FileUploadItemPreview";
1458
+
1459
+ /* -------------------------------------------------------------------------------------------------
1460
+ * FileUploadItemRemove — remove button with focus management
1461
+ * -----------------------------------------------------------------------------------------------*/
1462
+
1463
+ interface FileUploadItemRemoveProps extends React.ComponentPropsWithoutRef<"button"> {
1464
+ /** Test hook identifier. */
1465
+ dataHook?: string;
1466
+ /**
1467
+ * The file to remove. Used for focus management (finds next/previous item).
1468
+ * The consumer is responsible for actually removing the file from the list.
1469
+ */
1470
+ file: File;
1471
+ /**
1472
+ * Accessible label for the remove button.
1473
+ * @default "Remove {fileName}"
1474
+ */
1475
+ removeAriaLabel?: string;
1476
+ }
1477
+
1478
+ const FileUploadItemRemove = React.forwardRef<
1479
+ HTMLButtonElement,
1480
+ FileUploadItemRemoveProps
1481
+ >(
1482
+ (
1483
+ { file, dataHook, removeAriaLabel, onClick, children, className, ...props },
1484
+ ref
1485
+ ) => {
1486
+ const { rootRef, announce, messages } = useFileUploadContext();
1487
+
1488
+ const handleClick = React.useCallback(
1489
+ (e: React.MouseEvent<HTMLButtonElement>) => {
1490
+ onClick?.(e);
1491
+ if (e.defaultPrevented) return;
1492
+
1493
+ announce(formatMessage(messages.fileRemoved, { name: file.name }));
1494
+
1495
+ const li = e.currentTarget.closest("li");
1496
+ const neighbour = (li?.nextElementSibling ??
1497
+ li?.previousElementSibling) as HTMLElement | null;
1498
+
1499
+ setTimeout(() => {
1500
+ const target =
1501
+ (neighbour?.isConnected
1502
+ ? neighbour.querySelector<HTMLElement>(
1503
+ "[data-file-upload-remove]"
1504
+ )
1505
+ : null) ??
1506
+ rootRef.current?.querySelector<HTMLElement>(
1507
+ "[data-file-upload-trigger]"
1508
+ );
1509
+ target?.focus();
1510
+ }, 0);
1511
+ },
1512
+ [onClick, file.name, rootRef, announce, messages.fileRemoved]
1513
+ );
1514
+
1515
+ return (
1516
+ <button
1517
+ ref={ref}
1518
+ aria-label={removeAriaLabel ?? `Remove ${file.name}`}
1519
+ className={cn(
1520
+ "text-muted-foreground hover:text-foreground duration-fast cursor-pointer rounded-sm transition-colors ease-out",
1521
+ "focus-visible:shadow-default outline-none",
1522
+ "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",
1523
+ className
1524
+ )}
1525
+ data-file-upload-remove=""
1526
+ data-hook={dataHook}
1527
+ data-slot="file-upload-item-remove"
1528
+ type="button"
1529
+ onClick={handleClick}
1530
+ {...props}
1531
+ >
1532
+ {children}
1533
+ </button>
1534
+ );
1535
+ }
1536
+ );
1537
+
1538
+ FileUploadItemRemove.displayName = "FileUploadItemRemove";
1539
+
1540
+ /* -------------------------------------------------------------------------------------------------
1541
+ * FileUploadItemProgress — per-file upload status indicator
1542
+ * -----------------------------------------------------------------------------------------------*/
1543
+
1544
+ interface FileUploadItemProgressProps extends React.ComponentPropsWithoutRef<"div"> {
1545
+ /**
1546
+ * Test hook identifier.
1547
+ * @default "file-upload-item-progress"
1548
+ */
1549
+ dataHook?: string;
1550
+ /** The file whose upload status to display. */
1551
+ file: File;
1552
+ /**
1553
+ * Label shown while uploading; also the progress bar's accessible name.
1554
+ * @default "Uploading…"
1555
+ */
1556
+ uploadingLabel?: string;
1557
+ /**
1558
+ * Label shown on success.
1559
+ * @default "Uploaded"
1560
+ */
1561
+ successLabel?: string;
1562
+ /**
1563
+ * Label shown on error. Falls back to the error message from the handler.
1564
+ * @default "Upload failed"
1565
+ */
1566
+ errorLabel?: string;
1567
+ }
1568
+
1569
+ const FileUploadItemProgress = React.forwardRef<
1570
+ HTMLDivElement,
1571
+ FileUploadItemProgressProps
1572
+ >(
1573
+ (
1574
+ {
1575
+ className,
1576
+ dataHook,
1577
+ file,
1578
+ uploadingLabel,
1579
+ successLabel,
1580
+ errorLabel,
1581
+ ...props
1582
+ },
1583
+ ref
1584
+ ) => {
1585
+ const { getFileStatus } = useFileUploadContext();
1586
+ const fileState = getFileStatus(file);
1587
+ const hook = dataHook ?? "file-upload-item-progress";
1588
+
1589
+ if (fileState.status === "idle") return null;
1590
+
1591
+ if (fileState.status === "uploading") {
1592
+ return (
1593
+ <div
1594
+ ref={ref}
1595
+ className={cn("flex items-center gap-2", className)}
1596
+ data-hook={hook}
1597
+ data-slot="file-upload-item-progress"
1598
+ data-status="uploading"
1599
+ {...props}
1600
+ >
1601
+ <Progress
1602
+ ariaLabel={uploadingLabel ?? "Uploading…"}
1603
+ className="flex-1"
1604
+ dataHook={`${hook}-bar`}
1605
+ size="sm"
1606
+ value={fileState.progress}
1607
+ />
1608
+ <TypographyText
1609
+ asChild
1610
+ color="muted"
1611
+ dataHook={`${hook}-text`}
1612
+ variant="body-xs"
1613
+ >
1614
+ <span className="shrink-0">{uploadingLabel ?? "Uploading…"}</span>
1615
+ </TypographyText>
1616
+ </div>
1617
+ );
1618
+ }
1619
+
1620
+ if (fileState.status === "success") {
1621
+ return (
1622
+ <div
1623
+ ref={ref}
1624
+ className={cn(
1625
+ "text-label-sm text-success-foreground flex items-center gap-1",
1626
+ className
1627
+ )}
1628
+ data-hook={hook}
1629
+ data-slot="file-upload-item-progress"
1630
+ data-status="success"
1631
+ {...props}
1632
+ >
1633
+ <Check aria-hidden size={14} />
1634
+ {successLabel ?? "Uploaded"}
1635
+ </div>
1636
+ );
1637
+ }
1638
+
1639
+ return (
1640
+ <div
1641
+ ref={ref}
1642
+ className={cn(
1643
+ "text-label-sm text-destructive-foreground flex items-center gap-1",
1644
+ className
1645
+ )}
1646
+ data-hook={hook}
1647
+ data-slot="file-upload-item-progress"
1648
+ data-status="error"
1649
+ {...props}
1650
+ >
1651
+ <TriangleAlert aria-hidden size={14} />
1652
+ {errorLabel ?? fileState.error ?? "Upload failed"}
1653
+ </div>
1654
+ );
1655
+ }
1656
+ );
1657
+
1658
+ FileUploadItemProgress.displayName = "FileUploadItemProgress";
1659
+
1660
+ /* -------------------------------------------------------------------------------------------------
1661
+ * FileUploadCardItem — pre-composed file row: preview + name + size + remove + progress
1662
+ * -----------------------------------------------------------------------------------------------*/
1663
+
1664
+ interface FileUploadCardItemProps extends Omit<
1665
+ React.ComponentPropsWithoutRef<"li">,
1666
+ "children"
1667
+ > {
1668
+ /** Required test hook identifier. */
1669
+ dataHook: string;
1670
+ /** The file to display. */
1671
+ file: File;
1672
+ /** Called when the remove button is clicked. Omit to hide the remove button. */
1673
+ onRemove?: () => void;
1674
+ /**
1675
+ * Accessible label for the remove button.
1676
+ * @default "Remove {fileName}"
1677
+ */
1678
+ removeAriaLabel?: string;
1679
+ /** Analytics element identifier. */
1680
+ trackingEl?: string;
1681
+ /** Analytics label. */
1682
+ trackingLabel?: string;
1683
+ }
1684
+
1685
+ const FileUploadCardItem = React.forwardRef<
1686
+ HTMLLIElement,
1687
+ FileUploadCardItemProps
1688
+ >(
1689
+ (
1690
+ {
1691
+ className,
1692
+ dataHook,
1693
+ file,
1694
+ onRemove,
1695
+ removeAriaLabel,
1696
+ trackingEl,
1697
+ trackingLabel,
1698
+ ...props
1699
+ },
1700
+ ref
1701
+ ) => {
1702
+ return (
1703
+ <FileUploadItem
1704
+ ref={ref}
1705
+ className={className}
1706
+ dataHook={dataHook}
1707
+ {...props}
1708
+ >
1709
+ <div className="flex w-full flex-col gap-2 rounded-lg border p-3">
1710
+ <div className="flex items-center gap-3">
1711
+ <FileUploadItemPreview file={file} />
1712
+ <div className="min-w-0 flex-1">
1713
+ <TypographyText
1714
+ truncate
1715
+ data-slot="file-upload-file-name"
1716
+ dataHook={`${dataHook}-name`}
1717
+ >
1718
+ {file.name}
1719
+ </TypographyText>
1720
+ <TypographyText
1721
+ color="muted"
1722
+ data-slot="file-upload-file-description"
1723
+ dataHook={`${dataHook}-size`}
1724
+ variant="body-sm"
1725
+ >
1726
+ {formatBytes(file.size)}
1727
+ </TypographyText>
1728
+ </div>
1729
+ {onRemove && (
1730
+ <FileUploadItemRemove
1731
+ data-tracking-el={trackingEl}
1732
+ data-tracking-label={trackingLabel}
1733
+ dataHook={`${dataHook}-remove`}
1734
+ file={file}
1735
+ removeAriaLabel={removeAriaLabel}
1736
+ onClick={onRemove}
1737
+ >
1738
+ <X size={16} />
1739
+ </FileUploadItemRemove>
1740
+ )}
1741
+ </div>
1742
+ <FileUploadItemProgress file={file} />
1743
+ </div>
1744
+ </FileUploadItem>
1745
+ );
1746
+ }
1747
+ );
1748
+
1749
+ FileUploadCardItem.displayName = "FileUploadCardItem";
1750
+
1751
+ /* -------------------------------------------------------------------------------------------------
1752
+ * FileUploadGridItem — pre-composed grid thumbnail with hover-reveal remove
1753
+ * -----------------------------------------------------------------------------------------------*/
1754
+
1755
+ interface FileUploadGridItemProps extends Omit<
1756
+ React.ComponentPropsWithoutRef<"li">,
1757
+ "children"
1758
+ > {
1759
+ /** Required test hook identifier. */
1760
+ dataHook: string;
1761
+ /** The file to display. */
1762
+ file: File;
1763
+ /** Called when the remove button is clicked. Omit to hide the remove button. */
1764
+ onRemove?: () => void;
1765
+ /**
1766
+ * Accessible label for the remove button.
1767
+ * @default "Remove {fileName}"
1768
+ */
1769
+ removeAriaLabel?: string;
1770
+ /**
1771
+ * Show the file name below the thumbnail.
1772
+ * @default false
1773
+ */
1774
+ showName?: boolean;
1775
+ /** Analytics element identifier. */
1776
+ trackingEl?: string;
1777
+ /** Analytics label. */
1778
+ trackingLabel?: string;
1779
+ }
1780
+
1781
+ const FileUploadGridItem = React.forwardRef<
1782
+ HTMLLIElement,
1783
+ FileUploadGridItemProps
1784
+ >(
1785
+ (
1786
+ {
1787
+ className,
1788
+ dataHook,
1789
+ file,
1790
+ onRemove,
1791
+ removeAriaLabel,
1792
+ showName = false,
1793
+ trackingEl,
1794
+ trackingLabel,
1795
+ ...props
1796
+ },
1797
+ ref
1798
+ ) => {
1799
+ return (
1800
+ <FileUploadItem
1801
+ ref={ref}
1802
+ className={cn("flex min-w-0 flex-col gap-1.5", className)}
1803
+ dataHook={dataHook}
1804
+ {...props}
1805
+ >
1806
+ <FileUploadItemPreview className="group/thumb" file={file} size="lg">
1807
+ {onRemove && (
1808
+ <div className="bg-background/80 hover:bg-background duration-fast absolute top-1.5 right-1.5 rounded-full p-0.5 opacity-0 transition-opacity ease-out group-focus-within/thumb:opacity-100 group-hover/thumb:opacity-100">
1809
+ <FileUploadItemRemove
1810
+ className="flex"
1811
+ data-tracking-el={trackingEl}
1812
+ data-tracking-label={trackingLabel}
1813
+ dataHook={`${dataHook}-remove`}
1814
+ file={file}
1815
+ removeAriaLabel={removeAriaLabel}
1816
+ onClick={onRemove}
1817
+ >
1818
+ <X size={16} />
1819
+ </FileUploadItemRemove>
1820
+ </div>
1821
+ )}
1822
+ </FileUploadItemPreview>
1823
+ {showName && (
1824
+ <TypographyText
1825
+ asChild
1826
+ truncate
1827
+ color="muted"
1828
+ dataHook={`${dataHook}-name`}
1829
+ variant="body-xs"
1830
+ >
1831
+ <span data-slot="file-upload-file-name">{file.name}</span>
1832
+ </TypographyText>
1833
+ )}
1834
+ <FileUploadItemProgress file={file} />
1835
+ </FileUploadItem>
1836
+ );
1837
+ }
1838
+ );
1839
+
1840
+ FileUploadGridItem.displayName = "FileUploadGridItem";
1841
+
1842
+ /* -------------------------------------------------------------------------------------------------
1843
+ * FileUploadRejections — banner showing files that weren't added
1844
+ * -----------------------------------------------------------------------------------------------*/
1845
+
1846
+ interface FileUploadRejectionsProps extends React.ComponentPropsWithoutRef<"div"> {
1847
+ /**
1848
+ * Test hook identifier.
1849
+ * @default "file-upload-rejections"
1850
+ */
1851
+ dataHook?: string;
1852
+ /**
1853
+ * Banner title. `{n}` is replaced with the count of rejected files.
1854
+ * @default "{n} files weren't added"
1855
+ */
1856
+ title?: string;
1857
+ /**
1858
+ * Label for the dismiss button.
1859
+ * @default "Dismiss"
1860
+ */
1861
+ dismissLabel?: string;
1862
+ }
1863
+
1864
+ /**
1865
+ * Lists the files that failed validation since the last dismiss, in a warning
1866
+ * `Alert`. Polite (`role="status"`): entries accumulate across drops, and an
1867
+ * assertive alert would re-read the whole list on every addition.
1868
+ */
1869
+ const FileUploadRejections = React.forwardRef<
1870
+ HTMLDivElement,
1871
+ FileUploadRejectionsProps
1872
+ >(({ className, dataHook, title: titleProp, dismissLabel, ...props }, ref) => {
1873
+ const { rejections, clearRejections } = useFileUploadContext();
1874
+ const hook = dataHook ?? "file-upload-rejections";
1875
+
1876
+ if (rejections.length === 0) return null;
1877
+
1878
+ const count = rejections.length;
1879
+ const titleText = titleProp
1880
+ ? titleProp.replace("{n}", String(count))
1881
+ : count === 1
1882
+ ? "1 file wasn't added"
1883
+ : `${count} files weren't added`;
1884
+
1885
+ return (
1886
+ <Alert
1887
+ ref={ref}
1888
+ className={className}
1889
+ data-hook={hook}
1890
+ data-slot="file-upload-rejections"
1891
+ role="status"
1892
+ variant="warning"
1893
+ {...props}
1894
+ >
1895
+ <TriangleAlert aria-hidden className="shrink-0 translate-y-0.5" />
1896
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
1897
+ <div className="flex items-start justify-between gap-2">
1898
+ <AlertTitle>{titleText}</AlertTitle>
1899
+ <Button
1900
+ aria-label={dismissLabel ?? "Dismiss"}
1901
+ className="-my-1.5 -mr-2 shrink-0"
1902
+ dataHook={`${hook}-dismiss`}
1903
+ size="sm"
1904
+ variant="ghost"
1905
+ onClick={clearRejections}
1906
+ >
1907
+ <X aria-hidden />
1908
+ </Button>
1909
+ </div>
1910
+ <TypographyText asChild dataHook={`${hook}-list`} variant="body-sm">
1911
+ <ul className="flex flex-col gap-1">
1912
+ {rejections.map((entry) => (
1913
+ <li
1914
+ key={entry.id}
1915
+ className="min-w-0 break-words"
1916
+ data-slot="file-upload-rejection"
1917
+ >
1918
+ <strong>{entry.name}</strong> &mdash; {entry.message}
1919
+ </li>
1920
+ ))}
1921
+ </ul>
1922
+ </TypographyText>
1923
+ </div>
1924
+ </Alert>
1925
+ );
1926
+ });
1927
+
1928
+ FileUploadRejections.displayName = "FileUploadRejections";
1929
+
1930
+ /* -------------------------------------------------------------------------------------------------
1931
+ * FileUploadSlot — standalone single-image slot (logo, cover photo)
1932
+ * -----------------------------------------------------------------------------------------------*/
1933
+
1934
+ interface FileUploadSlotProps extends Omit<
1935
+ React.ComponentPropsWithoutRef<"div">,
1936
+ "onChange"
1937
+ > {
1938
+ /** Required test hook identifier. */
1939
+ dataHook: string;
1940
+ /**
1941
+ * Layout direction: vertical centres the image above the label and buttons;
1942
+ * horizontal places the image beside a column of label, description and buttons.
1943
+ * @default "vertical"
1944
+ */
1945
+ layout?: "vertical" | "horizontal";
1946
+ /**
1947
+ * Shape of the slot.
1948
+ * @default "square"
1949
+ */
1950
+ shape?: "square" | "wide";
1951
+ /** Label displayed below the slot. */
1952
+ label?: string;
1953
+ /**
1954
+ * Descriptive hint below the label (e.g. recommended dimensions or formats).
1955
+ */
1956
+ description?: string;
1957
+ /**
1958
+ * Text shown in the empty state alongside the placeholder icon.
1959
+ */
1960
+ emptyMessage?: string;
1961
+ /** Current image source URL (controlled). */
1962
+ src?: string | null;
1963
+ /**
1964
+ * Called when a file is accepted. `previewUrl` is an object URL that stays
1965
+ * valid while the slot holds the file; it is revoked shortly after the file
1966
+ * is removed or replaced, so store the `File`, not the URL, if you need it later.
1967
+ */
1968
+ onChange?: (file: File, previewUrl: string) => void;
1969
+ /** Called when the current image is removed. */
1970
+ onRemove?: () => void;
1971
+ /**
1972
+ * Accepted MIME types or extensions.
1973
+ * @example { "image/*": [".png", ".jpg"] }
1974
+ */
1975
+ accept?: Record<string, readonly string[]>;
1976
+ /** Human-readable accepted types label. */
1977
+ acceptLabel?: string;
1978
+ /** Maximum file size in bytes. */
1979
+ maxSize?: number;
1980
+ /** Minimum file size in bytes. */
1981
+ minSize?: number;
1982
+ /** Minimum pixel dimensions for image files. */
1983
+ minImageSize?: { width: number; height: number };
1984
+ /** Custom per-file validation. */
1985
+ onFileValidate?: FileValidator;
1986
+ /** Whether the slot is disabled. */
1987
+ disabled?: boolean;
1988
+ /**
1989
+ * Upload handler for the slot. Called after a file passes validation.
1990
+ * Use the helpers to report progress, success, or failure.
1991
+ */
1992
+ onUpload?: FileUploadHandler;
1993
+ /**
1994
+ * Translations for the messages the slot produces (rejection reasons,
1995
+ * upload failure). Merged over the English defaults.
1996
+ * @default FILE_UPLOAD_MESSAGES
1997
+ */
1998
+ messages?: Partial<FileUploadMessages>;
1999
+ /**
2000
+ * Label for the upload button.
2001
+ * @default "Upload" or "Replace"
2002
+ */
2003
+ uploadLabel?: string;
2004
+ /**
2005
+ * Label for the remove button.
2006
+ * @default "Remove"
2007
+ */
2008
+ removeLabel?: string;
2009
+ /**
2010
+ * Accessible label of the spinner shown while uploading.
2011
+ * @default "Uploading…"
2012
+ */
2013
+ uploadingLabel?: string;
2014
+ /**
2015
+ * Extra content rendered in the action button row (e.g. an additional button
2016
+ * for "Edit description"). Shown only when an image is present.
2017
+ */
2018
+ actions?: React.ReactNode;
2019
+ /** Analytics element identifier. */
2020
+ trackingEl?: string;
2021
+ /** Analytics label. */
2022
+ trackingLabel?: string;
2023
+ }
2024
+
2025
+ const FileUploadSlot = React.forwardRef<HTMLDivElement, FileUploadSlotProps>(
2026
+ (
2027
+ {
2028
+ className,
2029
+ dataHook,
2030
+ layout = "vertical",
2031
+ shape = "square",
2032
+ label,
2033
+ description,
2034
+ emptyMessage,
2035
+ src,
2036
+ onChange,
2037
+ onRemove,
2038
+ accept,
2039
+ acceptLabel,
2040
+ maxSize,
2041
+ minSize,
2042
+ minImageSize,
2043
+ onFileValidate,
2044
+ onUpload,
2045
+ messages: messagesProp,
2046
+ disabled = false,
2047
+ uploadLabel,
2048
+ removeLabel,
2049
+ uploadingLabel,
2050
+ actions,
2051
+ trackingEl,
2052
+ trackingLabel,
2053
+ onDragEnter,
2054
+ onDragOver,
2055
+ onDragLeave,
2056
+ onDrop,
2057
+ onPaste,
2058
+ ...props
2059
+ },
2060
+ ref
2061
+ ) => {
2062
+ const inputRef = React.useRef<HTMLInputElement>(null);
2063
+ const busyRef = React.useRef(false);
2064
+ const [internalFile, setInternalFile] = React.useState<File | null>(null);
2065
+ const previewUrl = useObjectUrl(internalFile);
2066
+ const displaySrc = src !== undefined ? src : (previewUrl ?? null);
2067
+ const messages = useMessages(messagesProp);
2068
+ const [dragState, setDragState] = React.useState<DropzoneState>("idle");
2069
+ const dragCounterRef = React.useRef(0);
2070
+
2071
+ const [uploadState, setUploadState] =
2072
+ React.useState<FileUploadFileState>(DEFAULT_FILE_STATE);
2073
+ /** Last rejection reason; shown below the slot until the next accepted file. */
2074
+ const [rejection, setRejection] = React.useState<string | null>(null);
2075
+ const [announcement, announce] = useAnnouncer();
2076
+
2077
+ const reject = React.useCallback(
2078
+ (message: string) => {
2079
+ setRejection(message);
2080
+ announce(message);
2081
+ },
2082
+ [announce]
2083
+ );
2084
+
2085
+ const latestRef = React.useRef({
2086
+ accept,
2087
+ acceptLabel,
2088
+ maxSize,
2089
+ minSize,
2090
+ minImageSize,
2091
+ messages,
2092
+ onFileValidate,
2093
+ onChange,
2094
+ onUpload,
2095
+ });
2096
+ React.useEffect(() => {
2097
+ latestRef.current = {
2098
+ accept,
2099
+ acceptLabel,
2100
+ maxSize,
2101
+ minSize,
2102
+ minImageSize,
2103
+ messages,
2104
+ onFileValidate,
2105
+ onChange,
2106
+ onUpload,
2107
+ };
2108
+ });
2109
+
2110
+ const handleFiles = React.useCallback(
2111
+ (incoming: File[]) => {
2112
+ const file = incoming[0];
2113
+ if (disabled || busyRef.current || !file) return;
2114
+
2115
+ void (async () => {
2116
+ const current = latestRef.current;
2117
+
2118
+ const errors = validateFile(file, {
2119
+ accept: current.accept,
2120
+ maxSize: current.maxSize,
2121
+ minSize: current.minSize,
2122
+ });
2123
+ const firstError = errors[0];
2124
+ if (firstError) {
2125
+ reject(
2126
+ rejectMessage(file, firstError, { ...current, maxFiles: 1 })
2127
+ );
2128
+ return;
2129
+ }
2130
+
2131
+ const asyncMessage = await runAsyncChecks(file, current);
2132
+ if (asyncMessage) {
2133
+ reject(asyncMessage);
2134
+ return;
2135
+ }
2136
+
2137
+ setRejection(null);
2138
+ setInternalFile(file);
2139
+ current.onChange?.(file, getObjectUrl(file));
2140
+
2141
+ if (!current.onUpload) return;
2142
+
2143
+ let outcome: "success" | "error" | undefined;
2144
+ busyRef.current = true;
2145
+ setUploadState({ status: "uploading", progress: 0 });
2146
+ try {
2147
+ await current.onUpload([file], {
2148
+ onProgress: (_f, progress) => {
2149
+ setUploadState((prev) => ({
2150
+ ...prev,
2151
+ progress: clampProgress(progress),
2152
+ }));
2153
+ },
2154
+ onSuccess: () => {
2155
+ outcome = "success";
2156
+ setUploadState({ status: "success", progress: 100 });
2157
+ },
2158
+ onError: (_f, error) => {
2159
+ outcome = "error";
2160
+ const message =
2161
+ typeof error === "string" ? error : error?.message;
2162
+ const errorMsg = message || current.messages.uploadFailed;
2163
+ setUploadState({
2164
+ status: "error",
2165
+ progress: 0,
2166
+ error: errorMsg,
2167
+ });
2168
+ announce(errorMsg);
2169
+ },
2170
+ });
2171
+ } catch {
2172
+ // handler threw — treated as a failed upload below
2173
+ }
2174
+ if (outcome === undefined) {
2175
+ const errorMsg = current.messages.uploadFailed;
2176
+ setUploadState({
2177
+ status: "error",
2178
+ progress: 0,
2179
+ error: errorMsg,
2180
+ });
2181
+ announce(errorMsg);
2182
+ }
2183
+ busyRef.current = false;
2184
+ })();
2185
+ },
2186
+ [disabled, reject, announce]
2187
+ );
2188
+
2189
+ const handleDragEnter = React.useCallback(
2190
+ (e: React.DragEvent<HTMLDivElement>) => {
2191
+ onDragEnter?.(e);
2192
+ e.preventDefault();
2193
+ if (disabled) return;
2194
+ dragCounterRef.current += 1;
2195
+ if (dragCounterRef.current === 1) {
2196
+ const matches = dragItemsMatchAccept(e.dataTransfer.items, accept);
2197
+ setDragState(matches ? "accept" : "reject");
2198
+ }
2199
+ },
2200
+ [onDragEnter, disabled, accept]
2201
+ );
2202
+
2203
+ const handleDragOver = React.useCallback(
2204
+ (e: React.DragEvent<HTMLDivElement>) => {
2205
+ onDragOver?.(e);
2206
+ e.preventDefault();
2207
+ if (!disabled) e.dataTransfer.dropEffect = "copy";
2208
+ },
2209
+ [onDragOver, disabled]
2210
+ );
2211
+
2212
+ const handleDragLeave = React.useCallback(
2213
+ (e: React.DragEvent<HTMLDivElement>) => {
2214
+ onDragLeave?.(e);
2215
+ e.preventDefault();
2216
+ if (disabled) return;
2217
+ dragCounterRef.current -= 1;
2218
+ if (dragCounterRef.current === 0) setDragState("idle");
2219
+ },
2220
+ [onDragLeave, disabled]
2221
+ );
2222
+
2223
+ // Consumer handlers run first; `preventDefault()` in them opts out of ours.
2224
+ const handleDrop = React.useCallback(
2225
+ (e: React.DragEvent<HTMLDivElement>) => {
2226
+ onDrop?.(e);
2227
+ if (e.defaultPrevented) return;
2228
+ e.preventDefault();
2229
+ dragCounterRef.current = 0;
2230
+ setDragState("idle");
2231
+ handleFiles(Array.from(e.dataTransfer.files));
2232
+ },
2233
+ [onDrop, handleFiles]
2234
+ );
2235
+
2236
+ const handlePaste = React.useCallback(
2237
+ (e: React.ClipboardEvent<HTMLDivElement>) => {
2238
+ onPaste?.(e);
2239
+ if (e.defaultPrevented) return;
2240
+ const files = Array.from(e.clipboardData.files);
2241
+ if (files.length > 0) {
2242
+ e.preventDefault();
2243
+ handleFiles(files);
2244
+ }
2245
+ },
2246
+ [onPaste, handleFiles]
2247
+ );
2248
+
2249
+ const handleInputChange = React.useCallback(
2250
+ (e: React.ChangeEvent<HTMLInputElement>) => {
2251
+ handleFiles(Array.from(e.target.files ?? []));
2252
+ e.target.value = "";
2253
+ },
2254
+ [handleFiles]
2255
+ );
2256
+
2257
+ const handleRemove = React.useCallback(() => {
2258
+ busyRef.current = false;
2259
+ setInternalFile(null);
2260
+ setUploadState(DEFAULT_FILE_STATE);
2261
+ setRejection(null);
2262
+ onRemove?.();
2263
+ }, [onRemove]);
2264
+
2265
+ const acceptStr = accept
2266
+ ? Object.entries(accept)
2267
+ .flatMap(([mime, exts]) => (exts.length > 0 ? exts : [mime]))
2268
+ .join(",")
2269
+ : undefined;
2270
+
2271
+ const uploading = uploadState.status === "uploading";
2272
+ const statusText =
2273
+ rejection ??
2274
+ (uploadState.status === "error"
2275
+ ? (uploadState.error ?? messages.uploadFailed)
2276
+ : null);
2277
+ const horizontal = layout === "horizontal";
2278
+
2279
+ const buttonRow = (
2280
+ <div className="flex flex-wrap gap-2">
2281
+ <input
2282
+ ref={inputRef}
2283
+ accept={acceptStr}
2284
+ aria-label={label ? `Upload ${label}` : "Upload file"}
2285
+ className="sr-only"
2286
+ disabled={disabled || uploading}
2287
+ tabIndex={-1}
2288
+ type="file"
2289
+ onChange={handleInputChange}
2290
+ />
2291
+ <Button
2292
+ dataHook={`${dataHook}-upload`}
2293
+ disabled={disabled || uploading}
2294
+ size="sm"
2295
+ variant="outline"
2296
+ onClick={() => inputRef.current?.click()}
2297
+ >
2298
+ {uploadLabel ?? (displaySrc ? "Replace" : "Upload")}
2299
+ </Button>
2300
+ {displaySrc && !uploading && actions}
2301
+ {displaySrc && !uploading && (
2302
+ <Button
2303
+ dataHook={`${dataHook}-remove`}
2304
+ disabled={disabled}
2305
+ size="sm"
2306
+ variant="ghost"
2307
+ onClick={handleRemove}
2308
+ >
2309
+ {removeLabel ?? "Remove"}
2310
+ </Button>
2311
+ )}
2312
+ </div>
2313
+ );
2314
+
2315
+ return (
2316
+ // Drag/paste targets only; the buttons below are the keyboard controls.
2317
+ // eslint-disable-next-line jsx-a11y/no-static-element-interactions
2318
+ <div
2319
+ ref={ref}
2320
+ className={cn(
2321
+ "relative flex",
2322
+ horizontal
2323
+ ? "flex-wrap items-start gap-4"
2324
+ : "flex-col items-center gap-2",
2325
+ className
2326
+ )}
2327
+ data-hook={dataHook}
2328
+ data-slot="file-upload-slot"
2329
+ data-tracking-el={trackingEl ?? "file-upload-slot"}
2330
+ data-tracking-label={trackingLabel}
2331
+ onDragEnter={handleDragEnter}
2332
+ onDragLeave={handleDragLeave}
2333
+ onDragOver={handleDragOver}
2334
+ onDrop={handleDrop}
2335
+ onPaste={handlePaste}
2336
+ {...props}
2337
+ >
2338
+ <div
2339
+ className={cn(
2340
+ "bg-muted text-muted-foreground relative flex shrink-0 items-center justify-center overflow-hidden rounded-lg",
2341
+ "duration-fast transition-shadow ease-out",
2342
+ shape === "square" ? "size-24" : "h-24 w-40",
2343
+ disabled && "opacity-50",
2344
+ dragState === "accept" && "ring-success-mark ring-2",
2345
+ dragState === "reject" && "ring-destructive ring-2"
2346
+ )}
2347
+ data-drag-state={dragState !== "idle" ? dragState : undefined}
2348
+ data-hook={`${dataHook}-frame`}
2349
+ data-slot="file-upload-slot-frame"
2350
+ >
2351
+ {displaySrc ? (
2352
+ <img
2353
+ alt={label ?? ""}
2354
+ className="size-full object-cover"
2355
+ src={displaySrc}
2356
+ />
2357
+ ) : (
2358
+ <MediaEmpty dataHook={`${dataHook}-empty`} message={emptyMessage} />
2359
+ )}
2360
+ {uploading && (
2361
+ <div className="bg-background/70 absolute inset-0 flex items-center justify-center">
2362
+ <Spinner
2363
+ className="text-primary"
2364
+ dataHook={`${dataHook}-spinner`}
2365
+ loadingLabel={uploadingLabel ?? "Uploading…"}
2366
+ size="lg"
2367
+ />
2368
+ </div>
2369
+ )}
2370
+ </div>
2371
+
2372
+ {horizontal ? (
2373
+ <div className="flex min-w-0 flex-1 flex-col gap-2">
2374
+ {label && (
2375
+ <TypographyText
2376
+ asChild
2377
+ dataHook={`${dataHook}-label`}
2378
+ variant="body-sm"
2379
+ >
2380
+ <span>{label}</span>
2381
+ </TypographyText>
2382
+ )}
2383
+ {description && (
2384
+ <TypographyText
2385
+ color="muted"
2386
+ dataHook={`${dataHook}-description`}
2387
+ variant="body-xs"
2388
+ >
2389
+ {description}
2390
+ </TypographyText>
2391
+ )}
2392
+ {statusText && (
2393
+ <TypographyText
2394
+ asChild
2395
+ color="destructive"
2396
+ dataHook={`${dataHook}-status-text`}
2397
+ variant="body-xs"
2398
+ >
2399
+ <p
2400
+ aria-hidden
2401
+ className="flex items-start gap-1"
2402
+ data-hook={`${dataHook}-status`}
2403
+ data-slot="file-upload-slot-status"
2404
+ >
2405
+ <TriangleAlert className="mt-0.5 shrink-0" size={14} />
2406
+ <span>{statusText}</span>
2407
+ </p>
2408
+ </TypographyText>
2409
+ )}
2410
+ {buttonRow}
2411
+ </div>
2412
+ ) : (
2413
+ <>
2414
+ {label && (
2415
+ <TypographyText
2416
+ asChild
2417
+ color="muted"
2418
+ dataHook={`${dataHook}-label`}
2419
+ variant="body-xs"
2420
+ >
2421
+ <span>{label}</span>
2422
+ </TypographyText>
2423
+ )}
2424
+ {description && (
2425
+ <TypographyText
2426
+ align="center"
2427
+ className="max-w-60"
2428
+ color="muted"
2429
+ dataHook={`${dataHook}-description`}
2430
+ variant="body-xs"
2431
+ >
2432
+ {description}
2433
+ </TypographyText>
2434
+ )}
2435
+ {statusText && (
2436
+ <TypographyText
2437
+ asChild
2438
+ color="destructive"
2439
+ dataHook={`${dataHook}-status-text`}
2440
+ variant="body-xs"
2441
+ >
2442
+ <p
2443
+ aria-hidden
2444
+ className="flex max-w-60 items-start gap-1 text-center"
2445
+ data-hook={`${dataHook}-status`}
2446
+ data-slot="file-upload-slot-status"
2447
+ >
2448
+ <TriangleAlert className="mt-0.5 shrink-0" size={14} />
2449
+ <span>{statusText}</span>
2450
+ </p>
2451
+ </TypographyText>
2452
+ )}
2453
+ {buttonRow}
2454
+ </>
2455
+ )}
2456
+
2457
+ <div
2458
+ aria-live="polite"
2459
+ className="sr-only"
2460
+ data-slot="file-upload-announcer"
2461
+ role="status"
2462
+ >
2463
+ {announcement}
2464
+ </div>
2465
+ </div>
2466
+ );
2467
+ }
2468
+ );
2469
+
2470
+ FileUploadSlot.displayName = "FileUploadSlot";
2471
+
2472
+ /* -------------------------------------------------------------------------------------------------
2473
+ * FileUploadCount
2474
+ * -----------------------------------------------------------------------------------------------*/
2475
+
2476
+ interface FileUploadCountProps extends Omit<
2477
+ CountIndicatorProps,
2478
+ "count" | "limit" | "dataHook"
2479
+ > {
2480
+ /**
2481
+ * Override the count derived from context. When omitted the number of files
2482
+ * currently in the upload is used.
2483
+ */
2484
+ count?: number;
2485
+ /**
2486
+ * Test hook identifier.
2487
+ * @default "file-upload-count"
2488
+ */
2489
+ dataHook?: string;
2490
+ }
2491
+
2492
+ /**
2493
+ * Displays the current file count against `maxFiles` using the shared
2494
+ * `CountIndicator` primitive. Renders nothing when `maxFiles` is not set on
2495
+ * the parent `FileUpload`.
2496
+ */
2497
+ const FileUploadCount = React.forwardRef<HTMLSpanElement, FileUploadCountProps>(
2498
+ ({ className, count, dataHook, ...props }, ref) => {
2499
+ const { files, maxFiles } = useFileUploadContext();
2500
+
2501
+ if (maxFiles === undefined) return null;
2502
+
2503
+ return (
2504
+ <CountIndicator
2505
+ ref={ref}
2506
+ className={cn("order-last ml-auto pl-3", className)}
2507
+ count={count ?? files.length}
2508
+ data-slot="file-upload-count"
2509
+ dataHook={dataHook ?? "file-upload-count"}
2510
+ limit={maxFiles}
2511
+ {...props}
2512
+ />
2513
+ );
2514
+ }
2515
+ );
2516
+
2517
+ FileUploadCount.displayName = "FileUploadCount";
2518
+
2519
+ /* -------------------------------------------------------------------------------------------------
2520
+ * Exports
2521
+ * -----------------------------------------------------------------------------------------------*/
2522
+
2523
+ export {
2524
+ FileUpload,
2525
+ FileUploadDropzone,
2526
+ FileUploadTrigger,
2527
+ FileUploadIdle,
2528
+ FileUploadAccept,
2529
+ FileUploadReject,
2530
+ FileUploadDropzoneContent,
2531
+ FileUploadList,
2532
+ FileUploadItem,
2533
+ FileUploadItemPreview,
2534
+ FileUploadItemRemove,
2535
+ FileUploadItemProgress,
2536
+ FileUploadCardItem,
2537
+ FileUploadGridItem,
2538
+ FileUploadRejections,
2539
+ FileUploadSlot,
2540
+ FileUploadCount,
2541
+ PHOTO_UPLOAD_RULES,
2542
+ FILE_UPLOAD_MESSAGES,
2543
+ formatBytes,
2544
+ getFileTypeIcon,
2545
+ getImageDimensions,
2546
+ useObjectUrl,
2547
+ };
2548
+
2549
+ export type {
2550
+ FileUploadProps,
2551
+ FileUploadDropzoneProps,
2552
+ FileUploadTriggerProps,
2553
+ FileUploadStateChildProps,
2554
+ FileUploadDropzoneContentProps,
2555
+ FileUploadListProps,
2556
+ FileUploadItemProps,
2557
+ FileUploadItemPreviewProps,
2558
+ FileUploadItemRemoveProps,
2559
+ FileUploadItemProgressProps,
2560
+ FileUploadCardItemProps,
2561
+ FileUploadGridItemProps,
2562
+ FileUploadRejectionsProps,
2563
+ FileUploadSlotProps,
2564
+ FileUploadCountProps,
2565
+ FileUploadRejectionEntry,
2566
+ FileUploadMessages,
2567
+ FileUploadStatus,
2568
+ FileUploadFileState,
2569
+ FileUploadHelpers,
2570
+ FileUploadHandler,
2571
+ FileValidator,
2572
+ FileError,
2573
+ FileRejection,
2574
+ };