@frontlit/media-uploader 0.1.0-alpha.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.
package/dist/index.js ADDED
@@ -0,0 +1,1070 @@
1
+ "use client";
2
+ import { createContext, useContext, useState, useRef, useEffect } from 'react';
3
+ import { FileAudio, X, Upload, Search, ImageIcon, XIcon, File, FileArchive, FileText, FileVideo } from 'lucide-react';
4
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
5
+ import { Slot } from '@radix-ui/react-slot';
6
+ import { cva } from 'class-variance-authority';
7
+ import { clsx } from 'clsx';
8
+ import { twMerge } from 'tailwind-merge';
9
+ import * as DialogPrimitive from '@radix-ui/react-dialog';
10
+ import * as LabelPrimitive from '@radix-ui/react-label';
11
+ import * as TabsPrimitive from '@radix-ui/react-tabs';
12
+
13
+ // src/media-upload-dialog.tsx
14
+
15
+ // src/format-file-size.ts
16
+ function formatFileSize(bytes) {
17
+ if (bytes >= 1024 * 1024) {
18
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
19
+ }
20
+ if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
21
+ return `${bytes} B`;
22
+ }
23
+ var MediaUploaderContext = createContext(null);
24
+ function MediaUploaderProvider({
25
+ children,
26
+ ...adapters
27
+ }) {
28
+ return /* @__PURE__ */ jsx(MediaUploaderContext.Provider, { value: adapters, children });
29
+ }
30
+ var ImageUploaderProvider = MediaUploaderProvider;
31
+ function useMediaUploaderAdapters(overrides = {}) {
32
+ const context = useContext(
33
+ MediaUploaderContext
34
+ );
35
+ const uploadMedia = overrides.uploadMedia ?? context?.uploadMedia;
36
+ const fallbackUploadMedia = async () => {
37
+ throw new Error(
38
+ "MediaUploadDialog requires uploadMedia via props or MediaUploaderProvider."
39
+ );
40
+ };
41
+ const resolvedUploadMedia = uploadMedia ?? fallbackUploadMedia;
42
+ return {
43
+ uploadMedia: resolvedUploadMedia,
44
+ listMedia: overrides.listMedia ?? context?.listMedia,
45
+ searchUnsplash: overrides.searchUnsplash ?? context?.searchUnsplash,
46
+ isUploading: overrides.isUploading ?? context?.isUploading,
47
+ uploadProgress: overrides.uploadProgress ?? context?.uploadProgress,
48
+ cancelUpload: overrides.cancelUpload ?? context?.cancelUpload
49
+ };
50
+ }
51
+ var useImageUploaderAdapters = useMediaUploaderAdapters;
52
+
53
+ // src/mime.ts
54
+ var IMAGE_EXTENSIONS = [
55
+ ".jpg",
56
+ ".jpeg",
57
+ ".png",
58
+ ".gif",
59
+ ".webp",
60
+ ".svg",
61
+ ".avif",
62
+ ".bmp",
63
+ ".ico"
64
+ ];
65
+ var VIDEO_EXTENSIONS = [".mp4", ".webm", ".mov", ".mkv", ".avi", ".m4v"];
66
+ var AUDIO_EXTENSIONS = [".mp3", ".wav", ".ogg", ".m4a", ".aac", ".flac"];
67
+ var ARCHIVE_EXTENSIONS = [".zip", ".tar", ".gz", ".rar", ".7z", ".tar.gz"];
68
+ var DOCUMENT_EXTENSIONS = [
69
+ ".doc",
70
+ ".docx",
71
+ ".xls",
72
+ ".xlsx",
73
+ ".ppt",
74
+ ".pptx",
75
+ ".txt",
76
+ ".csv",
77
+ ".md",
78
+ ".json",
79
+ ".rtf"
80
+ ];
81
+ function getExtension(name) {
82
+ if (!name) return "";
83
+ const lastDot = name.lastIndexOf(".");
84
+ return lastDot !== -1 ? name.slice(lastDot).toLowerCase() : "";
85
+ }
86
+ function getMimeCategory(mimeType, fileName) {
87
+ const mime = mimeType?.toLowerCase().trim() ?? "";
88
+ const ext = getExtension(fileName);
89
+ if (mime.startsWith("image/") || IMAGE_EXTENSIONS.includes(ext)) {
90
+ return "image";
91
+ }
92
+ if (mime.startsWith("video/") || VIDEO_EXTENSIONS.includes(ext)) {
93
+ return "video";
94
+ }
95
+ if (mime.startsWith("audio/") || AUDIO_EXTENSIONS.includes(ext)) {
96
+ return "audio";
97
+ }
98
+ if (mime === "application/pdf" || ext === ".pdf") {
99
+ return "pdf";
100
+ }
101
+ if (mime.includes("zip") || mime.includes("tar") || mime.includes("compressed") || mime.includes("archive") || ARCHIVE_EXTENSIONS.includes(ext)) {
102
+ return "archive";
103
+ }
104
+ if (mime.includes("word") || mime.includes("sheet") || mime.includes("excel") || mime.includes("presentation") || mime.startsWith("text/") || DOCUMENT_EXTENSIONS.includes(ext)) {
105
+ return "document";
106
+ }
107
+ return "other";
108
+ }
109
+ function matchesMime(fileType, fileName, acceptedTypes) {
110
+ if (!acceptedTypes || acceptedTypes.length === 0) return true;
111
+ if (acceptedTypes.includes("*/*") || acceptedTypes.includes("*")) return true;
112
+ const mime = fileType.toLowerCase().trim();
113
+ const ext = getExtension(fileName);
114
+ return acceptedTypes.some((pattern) => {
115
+ const p = pattern.toLowerCase().trim();
116
+ if (p === "*/*" || p === "*") return true;
117
+ if (p.startsWith(".")) {
118
+ return ext === p;
119
+ }
120
+ if (p.endsWith("/*")) {
121
+ const prefix = p.slice(0, -1);
122
+ return mime.startsWith(prefix);
123
+ }
124
+ if (mime === p) return true;
125
+ if (p === "application/pdf" && ext === ".pdf") return true;
126
+ return false;
127
+ });
128
+ }
129
+ function allowsImages(acceptedTypes) {
130
+ if (!acceptedTypes || acceptedTypes.length === 0) return true;
131
+ if (acceptedTypes.includes("*/*") || acceptedTypes.includes("*")) return true;
132
+ return acceptedTypes.some((pattern) => {
133
+ const p = pattern.toLowerCase().trim();
134
+ if (p === "*/*" || p === "*" || p === "image/*") return true;
135
+ if (p.startsWith("image/")) return true;
136
+ if (IMAGE_EXTENSIONS.includes(p)) return true;
137
+ return false;
138
+ });
139
+ }
140
+ function cn(...inputs) {
141
+ return twMerge(clsx(inputs));
142
+ }
143
+ var buttonVariants = cva(
144
+ "inline-flex shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-[var(--radius)] border border-transparent text-sm font-semibold outline-none transition-[background-color,border-color,color] focus-visible:shadow-[var(--shadow-focus)] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
145
+ {
146
+ variants: {
147
+ variant: {
148
+ primary: "bg-primary text-primary-foreground hover:bg-[var(--primary-hover)]",
149
+ outline: "border-input text-foreground hover:bg-muted",
150
+ ghost: "hover:bg-muted text-foreground"
151
+ },
152
+ size: {
153
+ sm: "h-8 px-3 text-xs",
154
+ md: "h-9 px-4"
155
+ }
156
+ },
157
+ defaultVariants: {
158
+ variant: "primary",
159
+ size: "md"
160
+ }
161
+ }
162
+ );
163
+ function Button({
164
+ className,
165
+ variant,
166
+ size,
167
+ asChild = false,
168
+ ...props
169
+ }) {
170
+ const Comp = asChild ? Slot : "button";
171
+ return /* @__PURE__ */ jsx(
172
+ Comp,
173
+ {
174
+ "data-slot": "button",
175
+ className: cn(buttonVariants({ variant, size, className })),
176
+ ...props
177
+ }
178
+ );
179
+ }
180
+ function Dialog(props) {
181
+ return /* @__PURE__ */ jsx(DialogPrimitive.Root, { "data-slot": "dialog", ...props });
182
+ }
183
+ function DialogTrigger(props) {
184
+ return /* @__PURE__ */ jsx(DialogPrimitive.Trigger, { "data-slot": "dialog-trigger", ...props });
185
+ }
186
+ function DialogPortal(props) {
187
+ return /* @__PURE__ */ jsx(DialogPrimitive.Portal, { "data-slot": "dialog-portal", ...props });
188
+ }
189
+ function DialogOverlay({
190
+ className,
191
+ ...props
192
+ }) {
193
+ return /* @__PURE__ */ jsx(
194
+ DialogPrimitive.Overlay,
195
+ {
196
+ "data-slot": "dialog-overlay",
197
+ className: cn(
198
+ "fixed inset-0 z-50 grid place-items-center overflow-y-auto bg-[var(--scrim)] p-6 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
199
+ className
200
+ ),
201
+ ...props
202
+ }
203
+ );
204
+ }
205
+ function DialogContent({
206
+ className,
207
+ children,
208
+ showCloseButton = true,
209
+ ...props
210
+ }) {
211
+ return /* @__PURE__ */ jsx(DialogPortal, { children: /* @__PURE__ */ jsx(DialogOverlay, { children: /* @__PURE__ */ jsxs(
212
+ DialogPrimitive.Content,
213
+ {
214
+ "data-slot": "dialog-content",
215
+ className: cn(
216
+ "relative w-full max-w-[440px] rounded-[var(--radius-lg)] border bg-card p-6 text-card-foreground shadow-[var(--shadow-popover)] outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
217
+ className
218
+ ),
219
+ ...props,
220
+ children: [
221
+ children,
222
+ showCloseButton ? /* @__PURE__ */ jsxs(DialogPrimitive.Close, { className: "absolute top-4 right-4 rounded-[var(--radius-sm)] text-muted-foreground opacity-70 outline-none transition-opacity hover:opacity-100 focus-visible:shadow-[var(--shadow-focus)] disabled:pointer-events-none", children: [
223
+ /* @__PURE__ */ jsx(XIcon, { className: "size-4" }),
224
+ /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Close" })
225
+ ] }) : null
226
+ ]
227
+ }
228
+ ) }) });
229
+ }
230
+ function DialogHeader({ className, ...props }) {
231
+ return /* @__PURE__ */ jsx(
232
+ "div",
233
+ {
234
+ "data-slot": "dialog-header",
235
+ className: cn("flex flex-col gap-1.5", className),
236
+ ...props
237
+ }
238
+ );
239
+ }
240
+ function DialogFooter({ className, ...props }) {
241
+ return /* @__PURE__ */ jsx(
242
+ "div",
243
+ {
244
+ "data-slot": "dialog-footer",
245
+ className: cn("mt-5 flex items-center justify-end gap-2.5", className),
246
+ ...props
247
+ }
248
+ );
249
+ }
250
+ function DialogTitle({
251
+ className,
252
+ ...props
253
+ }) {
254
+ return /* @__PURE__ */ jsx(
255
+ DialogPrimitive.Title,
256
+ {
257
+ "data-slot": "dialog-title",
258
+ className: cn("text-lg leading-tight font-semibold", className),
259
+ ...props
260
+ }
261
+ );
262
+ }
263
+ function DialogDescription({
264
+ className,
265
+ ...props
266
+ }) {
267
+ return /* @__PURE__ */ jsx(
268
+ DialogPrimitive.Description,
269
+ {
270
+ "data-slot": "dialog-description",
271
+ className: cn("text-sm text-muted-foreground", className),
272
+ ...props
273
+ }
274
+ );
275
+ }
276
+ function Input({ className, type, ...props }) {
277
+ return /* @__PURE__ */ jsx(
278
+ "input",
279
+ {
280
+ type,
281
+ "data-slot": "input",
282
+ className: cn(
283
+ "h-9 w-full min-w-0 rounded-[var(--radius)] border border-input bg-card px-3 text-sm text-foreground outline-none transition-[border-color,box-shadow] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:shadow-[0_0_0_3px_var(--primary-soft)] disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-50",
284
+ className
285
+ ),
286
+ ...props
287
+ }
288
+ );
289
+ }
290
+ function Label({
291
+ className,
292
+ ...props
293
+ }) {
294
+ return /* @__PURE__ */ jsx(
295
+ LabelPrimitive.Root,
296
+ {
297
+ "data-slot": "label",
298
+ className: cn(
299
+ "flex items-center gap-2 text-[0.8125rem] font-semibold text-foreground select-none",
300
+ className
301
+ ),
302
+ ...props
303
+ }
304
+ );
305
+ }
306
+ function Tabs({
307
+ className,
308
+ ...props
309
+ }) {
310
+ return /* @__PURE__ */ jsx(
311
+ TabsPrimitive.Root,
312
+ {
313
+ "data-slot": "tabs",
314
+ className: cn("flex flex-col gap-2", className),
315
+ ...props
316
+ }
317
+ );
318
+ }
319
+ function TabsList({
320
+ className,
321
+ ...props
322
+ }) {
323
+ return /* @__PURE__ */ jsx(
324
+ TabsPrimitive.List,
325
+ {
326
+ "data-slot": "tabs-list",
327
+ className: cn(
328
+ "inline-flex w-fit items-center gap-0.5 rounded-[var(--radius)] bg-muted p-[3px]",
329
+ className
330
+ ),
331
+ ...props
332
+ }
333
+ );
334
+ }
335
+ function TabsTrigger({
336
+ className,
337
+ ...props
338
+ }) {
339
+ return /* @__PURE__ */ jsx(
340
+ TabsPrimitive.Trigger,
341
+ {
342
+ "data-slot": "tabs-trigger",
343
+ className: cn(
344
+ "inline-flex items-center justify-center gap-1.5 rounded-[7px] px-3.5 py-[7px] text-[0.8125rem] font-semibold whitespace-nowrap text-muted-foreground outline-none transition-[background-color,color,box-shadow] hover:text-foreground focus-visible:shadow-[var(--shadow-focus)] disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-card data-[state=active]:text-foreground data-[state=active]:shadow-[var(--shadow-card)]",
345
+ className
346
+ ),
347
+ ...props
348
+ }
349
+ );
350
+ }
351
+ function TabsContent({
352
+ className,
353
+ ...props
354
+ }) {
355
+ return /* @__PURE__ */ jsx(
356
+ TabsPrimitive.Content,
357
+ {
358
+ "data-slot": "tabs-content",
359
+ className: cn("flex-1 outline-none", className),
360
+ ...props
361
+ }
362
+ );
363
+ }
364
+ var DEFAULT_MAX_UPLOAD_BYTES = 50 * 1024 * 1024;
365
+ function defaultDescription(allowExistingMedia, showUnsplash, acceptsOnlyImages) {
366
+ const noun = acceptsOnlyImages ? "image" : "file";
367
+ if (allowExistingMedia && showUnsplash) {
368
+ return `Upload a new ${noun}, choose one from your library, or pick from Unsplash.`;
369
+ }
370
+ if (allowExistingMedia) {
371
+ return `Upload a new ${noun} or choose one from your library.`;
372
+ }
373
+ if (showUnsplash) {
374
+ return `Upload a new ${noun} or pick from Unsplash.`;
375
+ }
376
+ return `Upload a new ${noun}.`;
377
+ }
378
+ function errorMessage(error, fallback) {
379
+ return error instanceof Error && error.message ? error.message : fallback;
380
+ }
381
+ function CategoryIcon({
382
+ category,
383
+ className
384
+ }) {
385
+ switch (category) {
386
+ case "image":
387
+ return /* @__PURE__ */ jsx(ImageIcon, { className });
388
+ case "video":
389
+ return /* @__PURE__ */ jsx(FileVideo, { className });
390
+ case "audio":
391
+ return /* @__PURE__ */ jsx(FileAudio, { className });
392
+ case "pdf":
393
+ case "document":
394
+ return /* @__PURE__ */ jsx(FileText, { className });
395
+ case "archive":
396
+ return /* @__PURE__ */ jsx(FileArchive, { className });
397
+ default:
398
+ return /* @__PURE__ */ jsx(File, { className });
399
+ }
400
+ }
401
+ function MediaUploadDialog({
402
+ open,
403
+ onOpenChange,
404
+ onSelect,
405
+ title,
406
+ description,
407
+ children,
408
+ disabled = false,
409
+ allowUnsplash = true,
410
+ allowExistingMedia = true,
411
+ acceptedTypes,
412
+ maxUploadBytes = DEFAULT_MAX_UPLOAD_BYTES,
413
+ validateFile: customValidateFile,
414
+ defaultTab = "upload",
415
+ metadataMode = "auto",
416
+ uploadMedia: uploadMediaProp,
417
+ listMedia: listMediaProp,
418
+ searchUnsplash: searchUnsplashProp,
419
+ isUploading: isUploadingProp,
420
+ uploadProgress: uploadProgressProp,
421
+ cancelUpload: cancelUploadProp
422
+ }) {
423
+ const adapters = useMediaUploaderAdapters({
424
+ uploadMedia: uploadMediaProp,
425
+ listMedia: listMediaProp,
426
+ searchUnsplash: searchUnsplashProp,
427
+ isUploading: isUploadingProp,
428
+ uploadProgress: uploadProgressProp,
429
+ cancelUpload: cancelUploadProp
430
+ });
431
+ const {
432
+ uploadMedia,
433
+ listMedia,
434
+ searchUnsplash,
435
+ isUploading = false,
436
+ uploadProgress = 0,
437
+ cancelUpload
438
+ } = adapters;
439
+ const acceptsImages = allowsImages(acceptedTypes);
440
+ const acceptsOnlyImages = Boolean(
441
+ acceptedTypes && acceptedTypes.length > 0 && acceptedTypes.every(
442
+ (t) => t.startsWith("image/") || t === "image/*" || [".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg", ".avif"].includes(
443
+ t.toLowerCase()
444
+ )
445
+ )
446
+ );
447
+ const showExistingMedia = allowExistingMedia && Boolean(listMedia);
448
+ const showUnsplash = allowUnsplash && acceptsImages && Boolean(searchUnsplash);
449
+ const resolvedTitle = title ?? (acceptsOnlyImages ? "Select image" : "Select file");
450
+ const resolvedDescription = description ?? defaultDescription(showExistingMedia, showUnsplash, acceptsOnlyImages);
451
+ const tabCount = 1 + (showExistingMedia ? 1 : 0) + (showUnsplash ? 1 : 0);
452
+ const [activeTab, setActiveTab] = useState(defaultTab);
453
+ const [file, setFile] = useState(null);
454
+ const [previewUrl, setPreviewUrl] = useState(null);
455
+ const [metaValue, setMetaValue] = useState("");
456
+ const [isDragging, setIsDragging] = useState(false);
457
+ const [fileError, setFileError] = useState("");
458
+ const [uploadError, setUploadError] = useState("");
459
+ const [mediaItems, setMediaItems] = useState([]);
460
+ const [mediaQuery, setMediaQuery] = useState("");
461
+ const [mediaError, setMediaError] = useState("");
462
+ const [loadingMedia, setLoadingMedia] = useState(false);
463
+ const [selectedMedia, setSelectedMedia] = useState(null);
464
+ const [unsplashUrl, setUnsplashUrl] = useState("");
465
+ const [unsplashAlt, setUnsplashAlt] = useState("");
466
+ const [unsplashQuery, setUnsplashQuery] = useState("");
467
+ const [unsplashResults, setUnsplashResults] = useState([]);
468
+ const [loadingUnsplash, setLoadingUnsplash] = useState(false);
469
+ const [unsplashError, setUnsplashError] = useState("");
470
+ const [unsplashConfigured, setUnsplashConfigured] = useState(
471
+ null
472
+ );
473
+ const fileInputRef = useRef(null);
474
+ const isControlled = open !== void 0;
475
+ const [internalOpen, setInternalOpen] = useState(false);
476
+ const resolvedOpen = isControlled ? open : internalOpen;
477
+ const currentCategory = file ? getMimeCategory(file.type, file.name) : acceptsOnlyImages ? "image" : "other";
478
+ useEffect(() => {
479
+ if (!file) {
480
+ if (previewUrl) {
481
+ URL.revokeObjectURL(previewUrl);
482
+ setPreviewUrl(null);
483
+ }
484
+ return;
485
+ }
486
+ const url = URL.createObjectURL(file);
487
+ setPreviewUrl(url);
488
+ return () => {
489
+ URL.revokeObjectURL(url);
490
+ };
491
+ }, [file]);
492
+ function resetFields() {
493
+ setFile(null);
494
+ setMetaValue("");
495
+ setFileError("");
496
+ setUploadError("");
497
+ setIsDragging(false);
498
+ setMediaError("");
499
+ setSelectedMedia(null);
500
+ setUnsplashError("");
501
+ setUnsplashUrl("");
502
+ setUnsplashAlt("");
503
+ setUnsplashQuery("");
504
+ setUnsplashResults([]);
505
+ }
506
+ function closeDialog() {
507
+ cancelUpload?.();
508
+ resetFields();
509
+ if (!isControlled) setInternalOpen(false);
510
+ onOpenChange?.(false);
511
+ }
512
+ function selectMedia(media) {
513
+ onSelect(media);
514
+ closeDialog();
515
+ }
516
+ function confirmSelectedMedia() {
517
+ if (!selectedMedia) return;
518
+ selectMedia({
519
+ src: selectedMedia.url,
520
+ alt: selectedMedia.alt || selectedMedia.fileName || "Media",
521
+ fileName: selectedMedia.fileName || selectedMedia.title || void 0,
522
+ mimeType: selectedMedia.mimeType || void 0,
523
+ byteSize: selectedMedia.byteSize || void 0,
524
+ media: selectedMedia
525
+ });
526
+ }
527
+ async function validateSelectedFile(selected) {
528
+ if (!matchesMime(selected.type, selected.name, acceptedTypes)) {
529
+ const allowedText = acceptedTypes?.length ? acceptedTypes.join(", ") : "all formats";
530
+ setFileError(
531
+ `File format not accepted (${selected.type || "unknown"}). Allowed: ${allowedText}.`
532
+ );
533
+ setFile(null);
534
+ return false;
535
+ }
536
+ if (selected.size > maxUploadBytes) {
537
+ setFileError(
538
+ `File is too large. Maximum allowed size is ${formatFileSize(maxUploadBytes)}.`
539
+ );
540
+ setFile(null);
541
+ return false;
542
+ }
543
+ if (customValidateFile) {
544
+ try {
545
+ const error = await customValidateFile(selected);
546
+ if (error) {
547
+ setFileError(error);
548
+ setFile(null);
549
+ return false;
550
+ }
551
+ } catch (err) {
552
+ setFileError(errorMessage(err, "Validation failed."));
553
+ setFile(null);
554
+ return false;
555
+ }
556
+ }
557
+ setFileError("");
558
+ setUploadError("");
559
+ setFile(selected);
560
+ return true;
561
+ }
562
+ async function handleFileChange(event) {
563
+ const selected = event.target.files?.[0];
564
+ event.target.value = "";
565
+ if (selected) {
566
+ await validateSelectedFile(selected);
567
+ }
568
+ }
569
+ async function handleDrop(event) {
570
+ event.preventDefault();
571
+ setIsDragging(false);
572
+ const dropped = event.dataTransfer.files[0];
573
+ if (dropped) {
574
+ await validateSelectedFile(dropped);
575
+ }
576
+ }
577
+ async function handleUpload() {
578
+ if (!file) return;
579
+ setUploadError("");
580
+ const isImage = currentCategory === "image";
581
+ const meta = {
582
+ fileName: file.name,
583
+ mimeType: file.type,
584
+ alt: metadataMode === "alt" || metadataMode === "auto" && isImage ? metaValue.trim() || void 0 : void 0,
585
+ title: metadataMode === "title" || metadataMode === "auto" && !isImage ? metaValue.trim() || void 0 : void 0
586
+ };
587
+ try {
588
+ const media = await uploadMedia(file, meta);
589
+ selectMedia({
590
+ src: media.url,
591
+ alt: media.alt || meta.alt || file.name,
592
+ fileName: media.fileName || file.name,
593
+ mimeType: media.mimeType || file.type,
594
+ byteSize: media.byteSize || file.size,
595
+ media
596
+ });
597
+ } catch (error) {
598
+ setUploadError(errorMessage(error, "Failed to upload file."));
599
+ }
600
+ }
601
+ async function loadMedia() {
602
+ if (!listMedia) return;
603
+ setLoadingMedia(true);
604
+ setMediaError("");
605
+ try {
606
+ const items = await listMedia(mediaQuery);
607
+ setMediaItems(items);
608
+ setSelectedMedia(
609
+ (current) => current && items.some((item) => item.id === current.id) ? current : null
610
+ );
611
+ } catch (error) {
612
+ setMediaError(errorMessage(error, "Failed to load media."));
613
+ } finally {
614
+ setLoadingMedia(false);
615
+ }
616
+ }
617
+ function selectUnsplashUrl() {
618
+ const trimmedUrl = unsplashUrl.trim();
619
+ if (!trimmedUrl) {
620
+ setUnsplashError("Enter an Unsplash image URL");
621
+ return;
622
+ }
623
+ try {
624
+ const parsed = new URL(trimmedUrl);
625
+ if (!parsed.hostname.includes("unsplash.com")) {
626
+ setUnsplashError("Enter a valid Unsplash URL");
627
+ return;
628
+ }
629
+ } catch {
630
+ setUnsplashError("Enter a valid Unsplash URL");
631
+ return;
632
+ }
633
+ selectMedia({
634
+ src: trimmedUrl,
635
+ alt: unsplashAlt.trim() || "Unsplash image",
636
+ fileName: "unsplash-image.jpg",
637
+ mimeType: "image/jpeg"
638
+ });
639
+ }
640
+ async function loadUnsplashConfig() {
641
+ if (!searchUnsplash) return;
642
+ try {
643
+ const result = await searchUnsplash();
644
+ setUnsplashConfigured(result.configured);
645
+ } catch {
646
+ setUnsplashConfigured(false);
647
+ }
648
+ }
649
+ async function runUnsplashSearch() {
650
+ if (!searchUnsplash) return;
651
+ const query = unsplashQuery.trim();
652
+ if (!query) {
653
+ setUnsplashError("Enter a search term");
654
+ return;
655
+ }
656
+ setLoadingUnsplash(true);
657
+ setUnsplashError("");
658
+ try {
659
+ const result = await searchUnsplash(query);
660
+ setUnsplashConfigured(result.configured);
661
+ if (!result.configured) return;
662
+ setUnsplashResults(result.items);
663
+ } catch (error) {
664
+ setUnsplashError(errorMessage(error, "Failed to search Unsplash"));
665
+ } finally {
666
+ setLoadingUnsplash(false);
667
+ }
668
+ }
669
+ useEffect(() => {
670
+ if (!showUnsplash && activeTab === "unsplash" || !showExistingMedia && activeTab === "media") {
671
+ setActiveTab("upload");
672
+ return;
673
+ }
674
+ if (showExistingMedia && activeTab === "media") void loadMedia();
675
+ if (showUnsplash && activeTab === "unsplash" && unsplashConfigured === null) {
676
+ void loadUnsplashConfig();
677
+ }
678
+ }, [activeTab, showExistingMedia, showUnsplash]);
679
+ const showMetadataInput = metadataMode !== "none" && (metadataMode === "alt" || metadataMode === "title" || metadataMode === "auto" && Boolean(file));
680
+ const metadataLabel = metadataMode === "alt" || metadataMode === "auto" && currentCategory === "image" ? "Alt text" : "Display title / caption";
681
+ const metadataPlaceholder = metadataMode === "alt" || metadataMode === "auto" && currentCategory === "image" ? "Describe the image for accessibility" : "Give this file a display title";
682
+ return /* @__PURE__ */ jsxs(
683
+ Dialog,
684
+ {
685
+ open: resolvedOpen,
686
+ onOpenChange: (value) => {
687
+ if (isUploading && !value) return;
688
+ if (value) {
689
+ if (!isControlled) setInternalOpen(true);
690
+ onOpenChange?.(true);
691
+ return;
692
+ }
693
+ closeDialog();
694
+ },
695
+ children: [
696
+ children ? /* @__PURE__ */ jsx(DialogTrigger, { asChild: true, disabled, children }) : null,
697
+ /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-2xl", showCloseButton: !isUploading, children: [
698
+ /* @__PURE__ */ jsxs(DialogHeader, { children: [
699
+ /* @__PURE__ */ jsx(DialogTitle, { children: resolvedTitle }),
700
+ /* @__PURE__ */ jsx(DialogDescription, { children: resolvedDescription })
701
+ ] }),
702
+ /* @__PURE__ */ jsxs(Tabs, { value: activeTab, onValueChange: setActiveTab, children: [
703
+ tabCount > 1 ? /* @__PURE__ */ jsxs(
704
+ TabsList,
705
+ {
706
+ className: `grid w-full ${tabCount === 3 ? "grid-cols-3" : "grid-cols-2"}`,
707
+ children: [
708
+ /* @__PURE__ */ jsx(TabsTrigger, { value: "upload", children: "Upload" }),
709
+ showExistingMedia ? /* @__PURE__ */ jsx(TabsTrigger, { value: "media", children: "Your media" }) : null,
710
+ showUnsplash ? /* @__PURE__ */ jsx(TabsTrigger, { value: "unsplash", children: "Unsplash" }) : null
711
+ ]
712
+ }
713
+ ) : null,
714
+ /* @__PURE__ */ jsxs(TabsContent, { value: "upload", className: "space-y-4 py-4", children: [
715
+ /* @__PURE__ */ jsxs(
716
+ "div",
717
+ {
718
+ onDragOver: (event) => {
719
+ event.preventDefault();
720
+ setIsDragging(true);
721
+ },
722
+ onDragLeave: () => setIsDragging(false),
723
+ onDrop: (e) => void handleDrop(e),
724
+ onClick: () => {
725
+ if (!file) fileInputRef.current?.click();
726
+ },
727
+ className: `relative flex min-h-48 flex-col items-center justify-center rounded-lg border-2 border-dashed p-6 text-center ${file ? "cursor-default" : "cursor-pointer"} ${isDragging ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-muted-foreground/50"} ${file ? "bg-muted/10 border-solid" : ""} ${fileError ? "border-destructive bg-destructive/5" : ""}`,
728
+ style: {
729
+ pointerEvents: isUploading ? "none" : "auto"
730
+ },
731
+ children: [
732
+ /* @__PURE__ */ jsx(
733
+ "input",
734
+ {
735
+ ref: fileInputRef,
736
+ type: "file",
737
+ accept: acceptedTypes?.join(","),
738
+ className: "hidden",
739
+ disabled: isUploading,
740
+ onChange: (e) => void handleFileChange(e)
741
+ }
742
+ ),
743
+ file && previewUrl ? /* @__PURE__ */ jsxs("div", { className: "relative flex flex-col items-center gap-3 w-full max-w-sm", children: [
744
+ currentCategory === "image" ? /* @__PURE__ */ jsx("div", { className: "relative group", children: /* @__PURE__ */ jsx(
745
+ "img",
746
+ {
747
+ src: previewUrl,
748
+ alt: "Preview",
749
+ className: "max-h-48 w-auto max-w-full rounded-md object-contain border bg-muted/20"
750
+ }
751
+ ) }) : currentCategory === "video" ? /* @__PURE__ */ jsx(
752
+ "video",
753
+ {
754
+ src: previewUrl,
755
+ controls: true,
756
+ className: "max-h-48 w-full rounded-md bg-black object-contain"
757
+ }
758
+ ) : currentCategory === "audio" ? /* @__PURE__ */ jsxs("div", { className: "flex w-full flex-col items-center gap-2 rounded-lg border bg-background p-3", children: [
759
+ /* @__PURE__ */ jsx(FileAudio, { className: "size-8 text-primary" }),
760
+ /* @__PURE__ */ jsx("span", { className: "max-w-full truncate text-xs font-medium", children: file.name }),
761
+ /* @__PURE__ */ jsx("audio", { src: previewUrl, controls: true, className: "h-8 w-full" })
762
+ ] }) : /* @__PURE__ */ jsxs("div", { className: "flex w-full items-center gap-3 rounded-lg border bg-background p-3 text-left", children: [
763
+ /* @__PURE__ */ jsx(
764
+ CategoryIcon,
765
+ {
766
+ category: currentCategory,
767
+ className: "size-8 shrink-0 text-primary"
768
+ }
769
+ ),
770
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
771
+ /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-medium", children: file.name }),
772
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: formatFileSize(file.size) })
773
+ ] })
774
+ ] }),
775
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
776
+ /* @__PURE__ */ jsxs(
777
+ Button,
778
+ {
779
+ type: "button",
780
+ variant: "ghost",
781
+ size: "sm",
782
+ onClick: (e) => {
783
+ e.stopPropagation();
784
+ setFile(null);
785
+ setFileError("");
786
+ setUploadError("");
787
+ },
788
+ disabled: isUploading,
789
+ className: "text-xs text-muted-foreground hover:text-destructive",
790
+ children: [
791
+ /* @__PURE__ */ jsx(X, { className: "mr-1 size-3.5" }),
792
+ " Remove file"
793
+ ]
794
+ }
795
+ ),
796
+ /* @__PURE__ */ jsx(
797
+ Button,
798
+ {
799
+ type: "button",
800
+ variant: "outline",
801
+ size: "sm",
802
+ onClick: (e) => {
803
+ e.stopPropagation();
804
+ fileInputRef.current?.click();
805
+ },
806
+ disabled: isUploading,
807
+ className: "text-xs",
808
+ children: "Change file"
809
+ }
810
+ )
811
+ ] })
812
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
813
+ /* @__PURE__ */ jsx(
814
+ Upload,
815
+ {
816
+ className: `mb-2 size-6 ${fileError ? "text-destructive" : isDragging ? "text-primary" : "text-muted-foreground"}`
817
+ }
818
+ ),
819
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-muted-foreground", children: acceptsOnlyImages ? "Drop image here or click" : "Drop file here or click" }),
820
+ /* @__PURE__ */ jsxs("p", { className: "mt-1 text-xs text-muted-foreground", children: [
821
+ acceptedTypes?.length ? acceptedTypes.join(", ") : acceptsOnlyImages ? "JPEG, PNG, GIF, WebP" : "Any file",
822
+ " \xB7 ",
823
+ "up to ",
824
+ formatFileSize(maxUploadBytes)
825
+ ] })
826
+ ] }),
827
+ fileError ? /* @__PURE__ */ jsx("p", { className: "mt-2 text-xs text-destructive", children: fileError }) : null
828
+ ]
829
+ }
830
+ ),
831
+ showMetadataInput ? /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
832
+ /* @__PURE__ */ jsx(Label, { htmlFor: "media-meta", children: metadataLabel }),
833
+ /* @__PURE__ */ jsx(
834
+ Input,
835
+ {
836
+ id: "media-meta",
837
+ value: metaValue,
838
+ onChange: (event) => setMetaValue(event.target.value),
839
+ placeholder: metadataPlaceholder,
840
+ disabled: isUploading
841
+ }
842
+ )
843
+ ] }) : null,
844
+ uploadError ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: uploadError }) : null,
845
+ isUploading ? /* @__PURE__ */ jsx("div", { className: "h-2 overflow-hidden rounded-full bg-muted", children: /* @__PURE__ */ jsx(
846
+ "div",
847
+ {
848
+ className: "h-full rounded-full bg-primary transition-all",
849
+ style: { width: `${uploadProgress}%` }
850
+ }
851
+ ) }) : null,
852
+ /* @__PURE__ */ jsx(DialogFooter, { children: /* @__PURE__ */ jsx(
853
+ Button,
854
+ {
855
+ type: "button",
856
+ onClick: () => void handleUpload(),
857
+ disabled: !file || isUploading,
858
+ children: isUploading ? `Uploading\u2026 ${Math.round(uploadProgress)}%` : acceptsOnlyImages ? "Upload image" : "Upload file"
859
+ }
860
+ ) })
861
+ ] }),
862
+ showExistingMedia ? /* @__PURE__ */ jsxs(TabsContent, { value: "media", className: "space-y-4 py-4", children: [
863
+ /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
864
+ /* @__PURE__ */ jsx(
865
+ Input,
866
+ {
867
+ placeholder: "Search library",
868
+ value: mediaQuery,
869
+ onChange: (event) => setMediaQuery(event.target.value),
870
+ onKeyDown: (event) => {
871
+ if (event.key === "Enter") {
872
+ event.preventDefault();
873
+ void loadMedia();
874
+ }
875
+ }
876
+ }
877
+ ),
878
+ /* @__PURE__ */ jsx(
879
+ Button,
880
+ {
881
+ type: "button",
882
+ variant: "outline",
883
+ onClick: () => void loadMedia(),
884
+ disabled: loadingMedia,
885
+ children: /* @__PURE__ */ jsx(Search, { className: "size-4" })
886
+ }
887
+ )
888
+ ] }),
889
+ mediaError ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: mediaError }) : null,
890
+ loadingMedia ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Loading library\u2026" }) : mediaItems.length ? /* @__PURE__ */ jsx("div", { className: "grid max-h-80 grid-cols-3 gap-3 overflow-y-auto pr-1", children: mediaItems.map((item) => {
891
+ const isSelected = selectedMedia?.id === item.id;
892
+ const itemCat = getMimeCategory(
893
+ item.mimeType,
894
+ item.fileName
895
+ );
896
+ const isImg = Boolean(item.thumbnailUrl) || itemCat === "image";
897
+ return /* @__PURE__ */ jsxs(
898
+ "button",
899
+ {
900
+ type: "button",
901
+ "aria-pressed": isSelected,
902
+ className: `group relative overflow-hidden rounded-md border bg-background text-left transition hover:border-primary ${isSelected ? "border-primary ring-2 ring-primary/30" : ""}`,
903
+ onClick: () => setSelectedMedia(item),
904
+ children: [
905
+ /* @__PURE__ */ jsx("div", { className: "aspect-square bg-muted flex items-center justify-center overflow-hidden", children: isImg ? /* @__PURE__ */ jsx(
906
+ "img",
907
+ {
908
+ src: item.thumbnailUrl || item.url,
909
+ alt: item.alt || item.fileName || "",
910
+ className: "size-full object-cover transition-transform group-hover:scale-105"
911
+ }
912
+ ) : /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center p-2 text-muted-foreground", children: [
913
+ /* @__PURE__ */ jsx(
914
+ CategoryIcon,
915
+ {
916
+ category: itemCat,
917
+ className: "size-10 text-muted-foreground/70"
918
+ }
919
+ ),
920
+ item.mimeType ? /* @__PURE__ */ jsx("span", { className: "mt-1 rounded bg-muted-foreground/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground", children: item.fileName?.split(".").pop() || itemCat }) : null
921
+ ] }) }),
922
+ /* @__PURE__ */ jsx("div", { className: "truncate px-2 py-1.5 text-xs text-muted-foreground", children: item.fileName || item.title || item.alt || "File" })
923
+ ]
924
+ },
925
+ item.id
926
+ );
927
+ }) }) : /* @__PURE__ */ jsxs("div", { className: "flex min-h-48 flex-col items-center justify-center rounded-md border border-dashed text-muted-foreground", children: [
928
+ /* @__PURE__ */ jsx(ImageIcon, { className: "mb-2 size-6" }),
929
+ /* @__PURE__ */ jsx("p", { className: "text-sm", children: "No media yet" })
930
+ ] }),
931
+ /* @__PURE__ */ jsx(DialogFooter, { children: /* @__PURE__ */ jsx(
932
+ Button,
933
+ {
934
+ type: "button",
935
+ onClick: confirmSelectedMedia,
936
+ disabled: !selectedMedia,
937
+ children: "Select"
938
+ }
939
+ ) })
940
+ ] }) : null,
941
+ showUnsplash ? /* @__PURE__ */ jsxs(TabsContent, { value: "unsplash", className: "space-y-4 py-4", children: [
942
+ unsplashConfigured === false ? /* @__PURE__ */ jsxs(Fragment, { children: [
943
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
944
+ /* @__PURE__ */ jsx(Label, { htmlFor: "unsplash-url", children: "Unsplash URL" }),
945
+ /* @__PURE__ */ jsx(
946
+ Input,
947
+ {
948
+ id: "unsplash-url",
949
+ placeholder: "https://images.unsplash.com/...",
950
+ value: unsplashUrl,
951
+ onChange: (event) => {
952
+ setUnsplashUrl(event.target.value);
953
+ setUnsplashError("");
954
+ }
955
+ }
956
+ )
957
+ ] }),
958
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
959
+ /* @__PURE__ */ jsx(Label, { htmlFor: "unsplash-alt", children: "Alt text" }),
960
+ /* @__PURE__ */ jsx(
961
+ Input,
962
+ {
963
+ id: "unsplash-alt",
964
+ placeholder: "Describe the image",
965
+ value: unsplashAlt,
966
+ onChange: (event) => setUnsplashAlt(event.target.value)
967
+ }
968
+ )
969
+ ] }),
970
+ /* @__PURE__ */ jsx(DialogFooter, { children: /* @__PURE__ */ jsx(
971
+ Button,
972
+ {
973
+ type: "button",
974
+ disabled: !unsplashUrl.trim(),
975
+ onClick: selectUnsplashUrl,
976
+ children: "Insert"
977
+ }
978
+ ) })
979
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
980
+ /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
981
+ /* @__PURE__ */ jsx(
982
+ Input,
983
+ {
984
+ placeholder: "Search Unsplash",
985
+ value: unsplashQuery,
986
+ onChange: (event) => setUnsplashQuery(event.target.value),
987
+ onKeyDown: (event) => {
988
+ if (event.key === "Enter") {
989
+ event.preventDefault();
990
+ void runUnsplashSearch();
991
+ }
992
+ }
993
+ }
994
+ ),
995
+ /* @__PURE__ */ jsx(
996
+ Button,
997
+ {
998
+ type: "button",
999
+ variant: "outline",
1000
+ onClick: () => void runUnsplashSearch(),
1001
+ disabled: loadingUnsplash,
1002
+ children: /* @__PURE__ */ jsx(Search, { className: "size-4" })
1003
+ }
1004
+ )
1005
+ ] }),
1006
+ loadingUnsplash ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Searching Unsplash\u2026" }) : unsplashResults.length ? /* @__PURE__ */ jsx("div", { className: "grid max-h-80 grid-cols-3 gap-3 overflow-y-auto pr-1", children: unsplashResults.map((photo) => /* @__PURE__ */ jsxs(
1007
+ "button",
1008
+ {
1009
+ type: "button",
1010
+ className: "overflow-hidden rounded-md border bg-background text-left hover:border-primary",
1011
+ onClick: () => selectMedia({
1012
+ src: photo.url,
1013
+ alt: photo.alt || "Unsplash image",
1014
+ fileName: `unsplash-${photo.id}.jpg`,
1015
+ mimeType: "image/jpeg"
1016
+ }),
1017
+ children: [
1018
+ /* @__PURE__ */ jsx("div", { className: "aspect-square bg-muted", children: /* @__PURE__ */ jsx(
1019
+ "img",
1020
+ {
1021
+ src: photo.thumbUrl,
1022
+ alt: photo.alt || "Unsplash",
1023
+ className: "size-full object-cover"
1024
+ }
1025
+ ) }),
1026
+ /* @__PURE__ */ jsx("div", { className: "truncate px-2 py-1.5 text-xs text-muted-foreground", children: photo.photographer || "Unsplash" })
1027
+ ]
1028
+ },
1029
+ photo.id
1030
+ )) }) : null
1031
+ ] }),
1032
+ unsplashError ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: unsplashError }) : null
1033
+ ] }) : null
1034
+ ] })
1035
+ ] })
1036
+ ]
1037
+ }
1038
+ );
1039
+ }
1040
+ var DEFAULT_IMAGE_ACCEPTED_TYPES = [
1041
+ "image/jpeg",
1042
+ "image/png",
1043
+ "image/gif",
1044
+ "image/webp"
1045
+ ];
1046
+ var DEFAULT_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
1047
+ function ImageUploadDialog({
1048
+ acceptedTypes = DEFAULT_IMAGE_ACCEPTED_TYPES,
1049
+ maxUploadBytes = DEFAULT_IMAGE_MAX_BYTES,
1050
+ title = "Select image",
1051
+ metadataMode = "alt",
1052
+ onSelect,
1053
+ ...props
1054
+ }) {
1055
+ return /* @__PURE__ */ jsx(
1056
+ MediaUploadDialog,
1057
+ {
1058
+ acceptedTypes,
1059
+ maxUploadBytes,
1060
+ title,
1061
+ metadataMode,
1062
+ onSelect: (selected) => onSelect(selected),
1063
+ ...props
1064
+ }
1065
+ );
1066
+ }
1067
+
1068
+ export { ImageUploadDialog, ImageUploaderProvider, MediaUploadDialog, MediaUploaderProvider, allowsImages, formatFileSize, getMimeCategory, matchesMime, useImageUploaderAdapters, useMediaUploaderAdapters };
1069
+ //# sourceMappingURL=index.js.map
1070
+ //# sourceMappingURL=index.js.map