"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { uploadMediaAndReturn } from "@/actions/admin-media"; import type { MediaFile } from "@/lib/media-files"; import { loadMediaFiles, validImageUrl } from "@/lib/media-files"; export function MediaPicker({ onSelect, current, }: { onSelect: (url: string) => void; current?: string; }) { const [open, setOpen] = useState(false); const [files, setFiles] = useState([]); const [loading, setLoading] = useState(false); const [uploading, setUploading] = useState(false); const fileRef = useRef(null); const load = useCallback(async () => { setLoading(true); setFiles(await loadMediaFiles()); setLoading(false); }, []); useEffect(() => { if (open) load(); }, [open, load]); async function handleUpload(e: React.ChangeEvent) { const files = e.target.files; if (!files || files.length === 0) return; setUploading(true); const urls: string[] = []; for (const file of Array.from(files)) { const fd = new FormData(); fd.set("file", file); const url = await uploadMediaAndReturn(fd); if (url) urls.push(url); } if (urls.length > 0) { await load(); onSelect(urls[urls.length - 1]); // select the last one for backward compatibility setOpen(false); } setUploading(false); if (fileRef.current) fileRef.current.value = ""; } return ( <>
{current && ( {current.split("/").pop()} )}
{open && ( // biome-ignore lint/a11y/useSemanticElements: backdrop overlay uses role=button for click-to-close
{ if (e.target === e.currentTarget) setOpen(false); }} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setOpen(false); } }} >
Media Library
{loading ? (

Loading…

) : files.length === 0 ? (

No images yet. Upload one above.

) : (
{files.map((f) => ( ))}
)}
)} ); }