forked from emdash-cms/emdash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMediaPickerModal.tsx
More file actions
989 lines (924 loc) · 31.1 KB
/
Copy pathMediaPickerModal.tsx
File metadata and controls
989 lines (924 loc) · 31.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
/**
* Media Picker Modal
*
* A modal dialog for selecting media from the library or uploading new files.
* Supports multiple media providers with tabbed navigation.
* Used by the rich text editor and image field components.
*/
import { Button, Dialog, Input, Label, Loader } from "@cloudflare/kumo";
import { plural } from "@lingui/core/macro";
import { useLingui } from "@lingui/react/macro";
import { Upload, Image, Check, Globe, MagnifyingGlass, Paperclip } from "@phosphor-icons/react";
import { X } from "@phosphor-icons/react";
import { useQuery, useInfiniteQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import * as React from "react";
import {
MEDIA_SEARCH_MAX_LENGTH,
fetchMediaList,
fetchMediaProviders,
fetchProviderMedia,
uploadMedia,
uploadToProvider,
updateMedia,
type MediaItem,
type MediaProviderItem,
} from "../lib/api";
import { useDebouncedValue } from "../lib/hooks.js";
import {
providerItemToMediaItem,
getFileIcon,
getMediaThumbnailUrl,
fallbackToOriginalThumbnail,
} from "../lib/media-utils";
import { matchesMimeAllowlist, mimeFromUrl } from "../lib/mime-utils.js";
import { cn } from "../lib/utils";
import { DialogError } from "./DialogError.js";
/** Selected item can be either a local MediaItem or a provider item with provider context */
interface SelectedMedia {
providerId: string;
item: MediaItem | MediaProviderItem;
}
/**
* Returns true if the given MIME type matches any entry in the filters array.
* Each filter entry is either an exact MIME type (e.g. "image/png") or a
* type prefix ending with "/" (e.g. "image/").
*/
function matchesAnyFilter(mime: string, filters: string[] | undefined): boolean {
if (!filters || filters.length === 0) return true;
const normalizedMime = mime.toLowerCase();
for (const entry of filters) {
if (!entry || !entry.includes("/")) continue;
const normalizedEntry = entry.toLowerCase();
if (normalizedEntry.endsWith("/")) {
if (normalizedMime.startsWith(normalizedEntry)) return true;
} else if (normalizedMime === normalizedEntry) {
return true;
}
}
return false;
}
export interface MediaPickerModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onSelect: (item: MediaItem) => void;
/** Allow selecting several items at once; confirms through `onSelectMany`. */
multiple?: boolean;
/** Called instead of `onSelect` when `multiple` is set. */
onSelectMany?: (items: MediaItem[]) => void;
/** Filter by mime type prefix, e.g. "image/" */
mimeTypeFilter?: string;
title?: string;
/**
* Hide the "Insert from URL" input. Defaults to false.
* The URL input probes image dimensions and is only meaningful for image pickers,
* so non-image pickers (e.g. generic file pickers) should hide it.
*/
hideUrlInput?: boolean;
/**
* What kind of media this picker is for. Drives user-facing copy
* (default title, empty-state message, upload button label, empty-state icon).
* Defaults to "image" — set to "file" for generic file pickers.
*/
mediaKind?: "image" | "file";
/** MIME allowlist — array of exact MIMEs or `type/` prefixes. */
mimeTypeFilters?: string[];
/** `_emdash_fields` row id for server-side MIME widening. */
fieldId?: string;
/**
* Restrict the picker to the local Library only — hides the "Insert from URL"
* input and suppresses external provider tabs.
*
* Use this for fields whose storage model only persists a local `mediaId`.
* Selecting an external URL or provider item would return an item the
* server cannot later resolve back to a URL (the `id` is either empty
* for "Insert from URL" or a provider-namespaced string that won't match
* a row in the `media` table). Site settings (logo, favicon,
* `seo.defaultOgImage`) are the canonical callers.
*/
localOnly?: boolean;
}
/**
* Probe image URL to get dimensions
*/
function probeImageDimensions(
url: string,
errorMessage: string,
): Promise<{ width: number; height: number }> {
return new Promise((resolve, reject) => {
const img = new window.Image();
img.onload = () => {
resolve({ width: img.naturalWidth, height: img.naturalHeight });
};
img.onerror = () => {
reject(new Error(errorMessage));
};
img.src = url;
});
}
export function MediaPickerModal({
open,
onOpenChange,
onSelect,
multiple = false,
onSelectMany,
mimeTypeFilter = "image/",
mimeTypeFilters,
fieldId,
title: providedTitle,
hideUrlInput = false,
mediaKind = "image",
localOnly = false,
}: MediaPickerModalProps) {
const { t } = useLingui();
const isFileKind = mediaKind === "file";
// Unified filters: mimeTypeFilters (plural array) takes precedence over the
// legacy mimeTypeFilter (singular string).
const filters = React.useMemo(() => {
if (mimeTypeFilters !== undefined)
return mimeTypeFilters.length > 0 ? mimeTypeFilters : undefined;
if (mimeTypeFilter && mimeTypeFilter.length > 0) return [mimeTypeFilter];
return undefined;
}, [mimeTypeFilters, mimeTypeFilter]);
const title = providedTitle ?? (isFileKind ? t`Select File` : t`Select Image`);
const emptyStateUploadHint = isFileKind
? t`Upload a file to get started`
: t`Upload an image to get started`;
const emptyStateUploadCta = isFileKind ? t`Upload File` : t`Upload Image`;
const EmptyStateIcon = isFileKind ? Paperclip : Image;
const queryClient = useQueryClient();
const [selectedItem, setSelectedItem] = React.useState<SelectedMedia | null>(null);
// Multi-select mode keeps items in click order — it becomes the gallery order.
const [selectedItems, setSelectedItems] = React.useState<SelectedMedia[]>([]);
const [activeProvider, setActiveProvider] = React.useState<string>("local");
const [searchQuery, setSearchQuery] = React.useState("");
// Debounced for the local library's server-side filename search.
const debouncedSearch = useDebouncedValue(searchQuery, 300);
const fileInputRef = React.useRef<HTMLInputElement>(null);
// URL input state
const [imageUrl, setImageUrl] = React.useState("");
const [isProbing, setIsProbing] = React.useState(false);
const [urlError, setUrlError] = React.useState<string | null>(null);
// Track loaded image dimensions for providers that don't return them (e.g., CF Images)
const [providerDimensions, setProviderDimensions] = React.useState<
Record<string, { width: number; height: number }>
>({});
// Reset state when modal opens, or when `localOnly` flips on while it's
// already open. Without the `localOnly` dependency a parent that toggles
// the prop mid-session could leave `activeProvider` on a non-local tab
// (the tab UI is suppressed, but the selection state and provider-media
// query would still target the external provider).
React.useEffect(() => {
if (open) {
setSelectedItem(null);
setSelectedItems([]);
setActiveProvider("local");
setSearchQuery("");
setImageUrl("");
setUrlError(null);
setUploadError(null);
setProviderDimensions({});
}
}, [open, localOnly]);
// Fetch available providers — skipped when `localOnly` is set since the
// list isn't used (provider tabs are suppressed and the active provider
// stays "local"). Avoids a request to /providers on every modal open
// when we'll just throw the result away.
const { data: providers } = useQuery({
queryKey: ["media-providers"],
queryFn: fetchMediaProviders,
enabled: open && !localOnly,
// Default to just local if fetch fails
placeholderData: [],
});
// Get active provider info
const activeProviderInfo = React.useMemo(() => {
if (activeProvider === "local") {
return {
id: "local",
name: t`Library`,
icon: undefined,
capabilities: { browse: true, search: false, upload: true, delete: true },
};
}
return providers?.find((p) => p.id === activeProvider);
}, [activeProvider, providers, t]);
// Fetch local media list (cursor-paginated so libraries beyond the
// first page remain selectable from the picker, not just the first 50).
// setQueryData is exact-match, so the optimistic dimension update below
// must share this exact key with the query that populates it.
const mediaQueryKey = ["media", filters?.join(",") ?? "", debouncedSearch.trim()];
const {
data: localData,
isLoading: localLoading,
fetchNextPage: fetchNextLocalPage,
hasNextPage: hasNextLocalPage,
isFetchingNextPage: isFetchingNextLocalPage,
} = useInfiniteQuery({
queryKey: mediaQueryKey,
queryFn: ({ pageParam }) =>
fetchMediaList({
mimeType: filters,
cursor: pageParam,
limit: 100,
search: debouncedSearch.trim() || undefined,
}),
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: open && activeProvider === "local",
});
// Fetch provider media list. Belt-and-suspenders: the reset effect
// forces `activeProvider` back to "local" when `localOnly` is true, but
// also gate this query directly so a stale render can't fire an
// external request between state updates.
const { data: providerData, isLoading: providerLoading } = useQuery({
queryKey: ["provider-media", activeProvider, filters?.join(",") ?? "", searchQuery],
queryFn: () =>
fetchProviderMedia(activeProvider, {
mimeType: filters,
limit: 50,
query: searchQuery || undefined,
}),
enabled: open && !localOnly && activeProvider !== "local",
});
const isLoading =
activeProvider === "local" ? localLoading || isFetchingNextLocalPage : providerLoading;
const [uploadError, setUploadError] = React.useState<string | null>(null);
// Upload mutation for local provider
const uploadLocalMutation = useMutation({
mutationFn: (file: File) => uploadMedia(file, { fieldId }),
onSuccess: (item) => {
void queryClient.invalidateQueries({ queryKey: ["media"] });
if (multiple) {
setSelectedItems((prev) => [...prev, { providerId: "local", item }]);
} else {
setSelectedItem({ providerId: "local", item });
}
setUploadError(null);
},
onError: (err: Error) => {
setUploadError(err.message);
},
});
// Upload mutation for external providers
const uploadProviderMutation = useMutation({
mutationFn: ({ providerId, file }: { providerId: string; file: File }) =>
uploadToProvider(providerId, file),
onSuccess: (item, { providerId }) => {
void queryClient.invalidateQueries({ queryKey: ["provider-media", providerId] });
if (multiple) {
setSelectedItems((prev) => [...prev, { providerId, item }]);
} else {
setSelectedItem({ providerId, item });
}
setUploadError(null);
},
onError: (err: Error) => {
setUploadError(err.message);
},
});
const isUploading = uploadLocalMutation.isPending || uploadProviderMutation.isPending;
// Track which items we've already updated dimensions for
const updatedDimensionsRef = React.useRef<Set<string>>(new Set());
// Mutation for updating media dimensions
const dimensionsMutation = useMutation({
mutationFn: ({ id, width, height }: { id: string; width: number; height: number }) =>
updateMedia(id, { width, height }),
onSuccess: (_updated, { id, width, height }) => {
queryClient.setQueryData(
mediaQueryKey,
(
old:
| {
pages: { items: MediaItem[]; nextCursor?: string }[];
pageParams: unknown[];
}
| undefined,
) => {
if (!old) return old;
return {
...old,
pages: old.pages.map((page) => ({
...page,
items: page.items.map((item) => (item.id === id ? { ...item, width, height } : item)),
})),
};
},
);
if (selectedItem?.providerId === "local" && selectedItem.item.id === id) {
setSelectedItem({
providerId: "local",
item: { ...selectedItem.item, width, height },
});
}
},
onError: (error) => {
console.warn("Failed to update media dimensions:", error);
},
});
// Handle dimensions detected for local images missing them
const handleDimensionsDetected = React.useCallback(
(id: string, width: number, height: number) => {
if (updatedDimensionsRef.current.has(id)) return;
updatedDimensionsRef.current.add(id);
dimensionsMutation.mutate({ id, width, height });
},
[dimensionsMutation],
);
// Get items for current view
const items = React.useMemo(() => {
if (activeProvider === "local") {
const localItems = localData?.pages.flatMap((page) => page.items) || [];
return localItems.filter((item) => matchesAnyFilter(item.mimeType, filters));
}
return providerData?.items || [];
}, [activeProvider, localData, providerData?.items, filters]);
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
const file = files?.[0];
if (file) {
if (activeProvider === "local") {
uploadLocalMutation.mutate(file);
} else if (activeProviderInfo?.capabilities.upload) {
uploadProviderMutation.mutate({ providerId: activeProvider, file });
}
}
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
};
// When providerId is "local", item is always MediaItem; otherwise MediaProviderItem
const toMediaItem = (selected: SelectedMedia): MediaItem => {
if (selected.providerId === "local") {
return selected.item as MediaItem;
}
const providerItem = selected.item as MediaProviderItem;
const dims = providerDimensions[providerItem.id];
const itemWithDims = dims
? {
...providerItem,
width: providerItem.width ?? dims.width,
height: providerItem.height ?? dims.height,
}
: providerItem;
return providerItemToMediaItem(selected.providerId, itemWithDims);
};
const isItemSelected = (providerId: string, id: string) =>
multiple
? selectedItems.some((s) => s.providerId === providerId && s.item.id === id)
: selectedItem?.providerId === providerId && selectedItem.item.id === id;
const handleItemClick = (providerId: string, item: MediaItem | MediaProviderItem) => {
if (multiple) {
setSelectedItems((prev) =>
prev.some((s) => s.providerId === providerId && s.item.id === item.id)
? prev.filter((s) => !(s.providerId === providerId && s.item.id === item.id))
: [...prev, { providerId, item }],
);
} else {
setSelectedItem({ providerId, item });
}
};
const handleConfirm = () => {
if (multiple) {
if (selectedItems.length === 0) return;
onSelectMany?.(selectedItems.map(toMediaItem));
onOpenChange(false);
setSelectedItems([]);
setImageUrl("");
return;
}
if (selectedItem) {
onSelect(toMediaItem(selectedItem));
onOpenChange(false);
setSelectedItem(null);
setImageUrl("");
}
};
const handleClose = () => {
onOpenChange(false);
setSelectedItem(null);
setSelectedItems([]);
setImageUrl("");
setUrlError(null);
};
const handleUrlSubmit = async () => {
if (!imageUrl.trim()) return;
let url: URL;
try {
url = new URL(imageUrl.trim());
} catch {
setUrlError(t`Please enter a valid URL`);
return;
}
setIsProbing(true);
setUrlError(null);
try {
const sniffedMime = mimeFromUrl(url) ?? "image/unknown";
// Pre-validate against the field's allowlist so the user sees the error
// here rather than at content-save time (where it becomes INVALID_MIME_FOR_FIELD).
if (sniffedMime === "image/unknown" && filters && filters.length > 0) {
setUrlError(
t`Cannot determine MIME type from URL. Use a URL ending in a recognized image extension (e.g. .jpg, .png, .webp).`,
);
return;
}
if (filters && filters.length > 0 && !matchesMimeAllowlist(sniffedMime, filters)) {
setUrlError(t`This field does not accept ${sniffedMime} files.`);
return;
}
const dimensions = await probeImageDimensions(url.href, t`Failed to load image`);
const externalItem: MediaItem = {
id: "",
filename: url.pathname.split("/").pop() || "external-image",
mimeType: sniffedMime,
url: url.href,
provider: "external-url",
size: 0,
width: dimensions.width,
height: dimensions.height,
createdAt: new Date().toISOString(),
};
if (multiple) {
onSelectMany?.([externalItem]);
} else {
onSelect(externalItem);
}
onOpenChange(false);
setImageUrl("");
} catch {
setUrlError(t`Could not load image from URL`);
} finally {
setIsProbing(false);
}
};
const handleUrlKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter") {
e.preventDefault();
void handleUrlSubmit();
}
};
const canUpload =
activeProvider === "local" || (activeProviderInfo?.capabilities.upload ?? false);
const canSearch = activeProviderInfo?.capabilities.search ?? false;
// Build provider tabs - always show local first, then add external providers
// Filter out "local" from API response since we add it manually.
// When `localOnly` is set, suppress external providers entirely so the
// picker can only return locally-stored media (see prop docs).
const providerTabs = React.useMemo(() => {
const tabs: Array<{ id: string; name: string; icon?: string }> = [
{ id: "local", name: t`Library`, icon: undefined },
];
if (providers && !localOnly) {
for (const p of providers) {
if (p.id !== "local") {
tabs.push({ id: p.id, name: p.name, icon: p.icon });
}
}
}
return tabs;
}, [providers, localOnly, t]);
return (
<Dialog.Root open={open} onOpenChange={handleClose}>
<Dialog className="p-6 max-w-4xl max-h-[80vh] flex flex-col overflow-hidden" size="xl">
<div className="flex items-start justify-between gap-4 mb-4">
<Dialog.Title className="text-lg font-semibold leading-none tracking-tight">
{title}
</Dialog.Title>
<Dialog.Close
aria-label={t`Close`}
render={(props) => (
<Button
{...props}
variant="ghost"
shape="square"
aria-label={t`Close`}
className="absolute end-4 top-4"
>
<X className="h-4 w-4" />
<span className="sr-only">{t`Close`}</span>
</Button>
)}
/>
</div>
{/* URL Input (image pickers only — probes image dimensions) */}
{!hideUrlInput && !localOnly && (
<>
<div className="border-b pb-4">
<Label>{t`Insert from URL`}</Label>
<div className="flex gap-2 mt-1.5">
<div className="flex-1 relative">
<Globe className="absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-kumo-subtle" />
<Input
type="url"
placeholder={t`https://example.com/image.jpg`}
aria-label={t`Image URL`}
value={imageUrl}
onChange={(e) => {
setImageUrl(e.target.value);
setUrlError(null);
}}
onKeyDown={handleUrlKeyDown}
className="ps-9"
/>
</div>
<Button onClick={handleUrlSubmit} disabled={!imageUrl.trim() || isProbing}>
{isProbing ? <Loader size="sm" /> : t`Insert`}
</Button>
</div>
{urlError && <p className="text-sm text-kumo-danger mt-1">{urlError}</p>}
</div>
{/* Divider with "or" */}
<div className="relative py-2">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-kumo-base px-2 text-kumo-subtle">{t`or choose from library`}</span>
</div>
</div>
</>
)}
{/* Provider Tabs */}
{providerTabs.length > 1 && (
<div className="flex gap-2 border-b pb-3 flex-wrap">
{providerTabs.map((tab) => (
<button
key={tab.id}
type="button"
onClick={() => {
setActiveProvider(tab.id);
setSelectedItem(null);
setSelectedItems([]);
setSearchQuery("");
}}
className={cn(
"flex items-center gap-2 px-4 h-9 text-sm font-medium rounded-md transition-colors whitespace-nowrap",
activeProvider === tab.id
? "bg-kumo-brand text-white"
: "bg-kumo-tint hover:bg-kumo-tint/80 text-kumo-subtle",
)}
>
{tab.icon &&
(tab.icon.startsWith("data:") ? (
<img src={tab.icon} alt="" className="h-4 w-4" aria-hidden="true" />
) : (
<span aria-hidden="true">{tab.icon}</span>
))}
{tab.name}
</button>
))}
</div>
)}
{/* Toolbar */}
<div className="flex items-center justify-between pb-3 gap-4">
{/* Search — providers that support it, plus the local library
(filename/extension search, handled server-side). */}
{canSearch || activeProvider === "local" ? (
<div className="relative flex-1 max-w-xs">
<MagnifyingGlass className="absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-kumo-subtle" />
<Input
type="search"
placeholder={activeProvider === "local" ? t`Search by filename...` : t`Search...`}
aria-label={t`Search media`}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
maxLength={MEDIA_SEARCH_MAX_LENGTH}
className="ps-9"
/>
</div>
) : (
<p className="text-sm text-kumo-subtle">
{plural(items.length, { one: "# item", other: "# items" })}
</p>
)}
{/* Upload button (if provider supports it) */}
{canUpload && (
<>
<Button
size="sm"
icon={<Upload />}
onClick={() => fileInputRef.current?.click()}
disabled={isUploading}
>
{isUploading ? t`Uploading...` : t`Upload`}
</Button>
<input
ref={fileInputRef}
type="file"
accept={
filters
? filters.map((f) => (f.endsWith("/") ? f + "*" : f)).join(",")
: undefined
}
className="sr-only"
onChange={handleFileSelect}
aria-label={t`Upload file`}
/>
</>
)}
</div>
{/* Upload error */}
<DialogError
message={uploadError ? t`Upload failed: ${uploadError}` : null}
className="mb-3"
/>
{/* Media Grid */}
<div className="flex-1 overflow-y-auto min-h-0">
{/*
* Gate the centered loader on items being empty so that "Load More"
* (which sets isLoading=true while fetching the next cursor page)
* does not blank out already-rendered items / lose the user's
* selection. Mirrors the ContentList pattern from #135.
*/}
{isLoading && items.length === 0 ? (
<div className="flex items-center justify-center h-full">
<Loader />
</div>
) : items.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full text-center p-8">
<EmptyStateIcon className="h-12 w-12 text-kumo-subtle mb-4" aria-hidden="true" />
<h3 className="text-lg font-medium">{t`No media found`}</h3>
<p className="text-sm text-kumo-subtle mt-1">
{canSearch && searchQuery
? t`Try a different search term`
: canUpload
? emptyStateUploadHint
: t`No media available from this provider`}
</p>
{canUpload && !searchQuery && (
<Button
className="mt-4"
icon={<Upload />}
onClick={() => fileInputRef.current?.click()}
>
{emptyStateUploadCta}
</Button>
)}
</div>
) : (
<ul
className="grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-3 p-1"
role="listbox"
aria-label={t`Available media`}
>
{activeProvider === "local"
? (items as MediaItem[]).map((item) => (
<MediaPickerItem
key={item.id}
item={item}
selected={isItemSelected("local", item.id)}
onClick={() => handleItemClick("local", item)}
onDoubleClick={() => {
// Multi-select: double-click is just a toggle, no instant insert
if (multiple) {
handleItemClick("local", item);
return;
}
onSelect(item);
onOpenChange(false);
}}
onDimensionsDetected={handleDimensionsDetected}
/>
))
: (items as MediaProviderItem[]).map((item) => (
<ProviderMediaItem
key={item.id}
item={item}
selected={isItemSelected(activeProvider, item.id)}
onClick={() => handleItemClick(activeProvider, item)}
onDoubleClick={() => {
if (multiple) {
handleItemClick(activeProvider, item);
return;
}
// Merge loaded dimensions for double-click select
const dims = providerDimensions[item.id];
const itemWithDims = dims
? {
...item,
width: item.width ?? dims.width,
height: item.height ?? dims.height,
}
: item;
const mediaItem = providerItemToMediaItem(activeProvider, itemWithDims);
onSelect(mediaItem);
onOpenChange(false);
}}
onDimensionsLoaded={(width, height) => {
setProviderDimensions((prev) => ({
...prev,
[item.id]: { width, height },
}));
}}
/>
))}
</ul>
)}
{/* Load more (local library only — providers handle pagination internally) */}
{activeProvider === "local" && hasNextLocalPage && (
<div className="flex justify-center py-3">
<Button
variant="outline"
size="sm"
onClick={() => void fetchNextLocalPage()}
disabled={isFetchingNextLocalPage}
>
{isFetchingNextLocalPage ? t`Loading...` : t`Load More`}
</Button>
</div>
)}
</div>
{/* Footer */}
<div className="flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2 border-t pt-4">
<div className="flex-1 text-sm text-kumo-subtle">
{multiple
? selectedItems.length > 0 && (
<span>
{plural(selectedItems.length, {
one: "# item selected",
other: "# items selected",
})}
</span>
)
: selectedItem && (
<span>
{t`Selected:`} <strong>{selectedItem.item.filename}</strong>
{selectedItem.providerId !== "local" && (
<span className="ms-2 text-xs">
{t`(from ${providers?.find((p) => p.id === selectedItem.providerId)?.name})`}
</span>
)}
</span>
)}
</div>
<Button variant="outline" onClick={handleClose}>
{t`Cancel`}
</Button>
<Button
onClick={handleConfirm}
disabled={multiple ? selectedItems.length === 0 : !selectedItem}
>
{t`Insert`}
</Button>
</div>
</Dialog>
</Dialog.Root>
);
}
interface MediaPickerItemProps {
item: MediaItem;
selected: boolean;
onClick: () => void;
onDoubleClick: () => void;
onDimensionsDetected?: (id: string, width: number, height: number) => void;
}
function MediaPickerItem({
item,
selected,
onClick,
onDoubleClick,
onDimensionsDetected,
}: MediaPickerItemProps) {
const { t } = useLingui();
const isImage = item.mimeType.startsWith("image/");
const needsDimensions = isImage && (!item.width || !item.height);
// Serve a resized thumbnail only when the original dimensions are already
// known. When they're missing we display the original so `onLoad` can read
// the true `naturalWidth`/`naturalHeight` to backfill them — a resized
// rendition would report the thumbnail's dimensions and corrupt the record.
const displayUrl = needsDimensions ? item.url : getMediaThumbnailUrl(item.url, item.mimeType);
const handleImageLoad = React.useCallback(
(e: React.SyntheticEvent<HTMLImageElement>) => {
if (needsDimensions && onDimensionsDetected) {
const img = e.currentTarget;
if (img.naturalWidth && img.naturalHeight) {
onDimensionsDetected(item.id, img.naturalWidth, img.naturalHeight);
}
}
},
[needsDimensions, onDimensionsDetected, item.id],
);
return (
<li role="option" aria-selected={selected}>
<button
type="button"
className={cn(
"relative aspect-square w-full rounded-lg border-2 overflow-hidden transition-all",
"hover:border-kumo-brand/50 focus:outline-none focus:ring-2 focus:ring-kumo-ring",
selected ? "border-kumo-brand ring-2 ring-kumo-brand/20" : "border-transparent",
)}
onClick={onClick}
onDoubleClick={onDoubleClick}
aria-label={t`${item.filename}${selected ? t` (selected)` : ""}`}
>
{isImage ? (
<img
src={displayUrl}
alt=""
className="h-full w-full object-cover"
onLoad={handleImageLoad}
onError={(e) => fallbackToOriginalThumbnail(e.currentTarget, item.url)}
/>
) : (
<div className="flex h-full w-full items-center justify-center bg-kumo-tint">
<span className="text-3xl" aria-hidden="true">
{getFileIcon(item.mimeType)}
</span>
</div>
)}
{selected && (
<div
className="absolute inset-0 bg-kumo-brand/20 flex items-center justify-center"
aria-hidden="true"
>
<div className="bg-kumo-brand text-white rounded-full p-1">
<Check className="h-4 w-4" />
</div>
</div>
)}
<div
className="absolute bottom-0 start-0 end-0 bg-gradient-to-t from-black/60 to-transparent p-2"
aria-hidden="true"
>
<p className="text-xs text-white truncate">{item.filename}</p>
</div>
</button>
</li>
);
}
interface ProviderMediaItemProps {
item: MediaProviderItem;
selected: boolean;
onClick: () => void;
onDoubleClick: () => void;
/** Callback when image dimensions are loaded (for providers that don't return dimensions) */
onDimensionsLoaded?: (width: number, height: number) => void;
}
function ProviderMediaItem({
item,
selected,
onClick,
onDoubleClick,
onDimensionsLoaded,
}: ProviderMediaItemProps) {
const { t } = useLingui();
const isImage = item.mimeType.startsWith("image/");
const needsDimensions = isImage && (!item.width || !item.height);
const handleImageLoad = React.useCallback(
(e: React.SyntheticEvent<HTMLImageElement>) => {
if (needsDimensions && onDimensionsLoaded) {
const img = e.currentTarget;
if (img.naturalWidth && img.naturalHeight) {
onDimensionsLoaded(img.naturalWidth, img.naturalHeight);
}
}
},
[needsDimensions, onDimensionsLoaded],
);
return (
<li role="option" aria-selected={selected}>
<button
type="button"
className={cn(
"relative aspect-square w-full rounded-lg border-2 overflow-hidden transition-all",
"hover:border-kumo-brand/50 focus:outline-none focus:ring-2 focus:ring-kumo-ring",
selected ? "border-kumo-brand ring-2 ring-kumo-brand/20" : "border-transparent",
)}
onClick={onClick}
onDoubleClick={onDoubleClick}
aria-label={t`${item.filename}${selected ? t` (selected)` : ""}`}
>
{isImage && item.previewUrl ? (
<img
src={item.previewUrl}
alt=""
className="h-full w-full object-cover"
onLoad={handleImageLoad}
/>
) : (
<div className="flex h-full w-full items-center justify-center bg-kumo-tint">
<span className="text-3xl" aria-hidden="true">
{getFileIcon(item.mimeType)}
</span>
</div>
)}
{selected && (
<div
className="absolute inset-0 bg-kumo-brand/20 flex items-center justify-center"
aria-hidden="true"
>
<div className="bg-kumo-brand text-white rounded-full p-1">
<Check className="h-4 w-4" />
</div>
</div>
)}
<div
className="absolute bottom-0 start-0 end-0 bg-gradient-to-t from-black/60 to-transparent p-2"
aria-hidden="true"
>
<p className="text-xs text-white truncate">{item.filename}</p>
</div>
</button>
</li>
);
}
export default MediaPickerModal;