import React, { useState, useEffect } from "react"; import { API_BASE } from "../config"; function MediaGalleryModal({ isOpen, onClose, onSelect, slug }) { const [images, setImages] = useState([]); const [loading, setLoading] = useState(false); const [uploading, setUploading] = useState(false); const [error, setError] = useState(null); useEffect(() => { if (isOpen) { fetchMedia(); } }, [isOpen, slug]); const fetchMedia = async () => { try { setLoading(true); const url = slug ? `${API_BASE}/media?slug=${encodeURIComponent(slug)}` : `${API_BASE}/media`; const response = await fetch(url, { credentials: "include" }); if (!response.ok) throw new Error("Failed to load media"); const data = await response.json(); setImages(data); } catch (err) { console.error("Fetch media error:", err); setError("Could not load images."); } finally { setLoading(false); } }; const handleUpload = async (e) => { const file = e.target.files[0]; if (!file) return; try { setUploading(true); const formData = new FormData(); formData.append("file", file); const uploadUrl = slug ? `${API_BASE}/upload?slug=${encodeURIComponent(slug)}` : `${API_BASE}/upload`; const response = await fetch(uploadUrl, { method: "POST", body: formData, credentials: "include", }); if (!response.ok) throw new Error("Upload failed"); await fetchMedia(); // Refresh list } catch (err) { setError(err.message); } finally { setUploading(false); } }; const handleDelete = async (path, e) => { e.stopPropagation(); if (!window.confirm("Delete this image?")) return; try { const response = await fetch(`${API_BASE}/media`, { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ path }), credentials: "include", }); if (!response.ok) throw new Error("Delete failed"); await fetchMedia(); } catch (err) { alert(err.message); } }; if (!isOpen) return null; return (
{/* Header */}

Media Gallery

{/* Content */}
{error && (
{error}
)} {loading ? (
) : images.length === 0 ? (
No images found in this folder.
) : (
{images.map((img) => (
onSelect(`${API_BASE}${img.url}`, img.name)} > {img.name}
{/* Delete Button */} {/* Name Label */}
{img.name}
))}
)}
Click an image to insert it into the editor.
); } export default MediaGalleryModal;