"use client"; import { useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { Download, FileImage, Pencil, Trash2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Input } from "@/components/ui/input"; import { PhotoViewer, type ViewerPhoto } from "./photo-viewer"; import type { PhotoAdjustments } from "@/lib/photo-adjustments"; import type { AdvancedEditView } from "@/lib/advanced-edit"; /** * Grid image that degrades to a readable tile instead of a blank square when * the thumbnail cannot be produced (damaged or unsupported RAW, missing file). */ function GalleryImage({ src, alt }: { src: string; alt: string }) { const [failed, setFailed] = useState(false); if (failed) { return (
); } return ( // Frames are private; the serving route sets the cache policy. // eslint-disable-next-line @next/next/no-img-element {alt} setFailed(true)} className="h-full w-full object-cover" /> ); } export interface GalleryPhoto { id: string; /** Storage folder the photo lives in; photos are shown as one event gallery. */ folderId: string; filename: string; sizeBytes: number; kind: "raw" | "image"; uploaderId: string; uploaderName: string; previewable: boolean; editable: boolean; adjustments: PhotoAdjustments; /** The saved edit was produced by the advanced (Lumenroom) editor. */ advancedEdit: boolean; /** Read-only view of the advanced recipe and a quick-editor seed. */ advancedSummary: AdvancedEditView | null; editedAt: string | null; editedSizeBytes: number | null; } const ACCEPT = [ ".jpg", ".jpeg", ".png", ".webp", ".gif", ".avif", ".heic", ".heif", ".tif", ".tiff", ".psd", ".3fr", ".arw", ".cr2", ".cr3", ".dng", ".erf", ".kdc", ".mef", ".mos", ".mrw", ".nef", ".nrw", ".orf", ".pef", ".raf", ".raw", ".rw2", ".rwl", ".sr2", ".srf", ".srw", ".x3f", ].join(","); function formatBytes(bytes: number): string { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`; if (bytes < 1024 * 1024 * 1024) { return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; } return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`; } function extensionOf(filename: string): string { const dot = filename.lastIndexOf("."); return dot === -1 ? "FILE" : filename.slice(dot + 1).toUpperCase(); } /** * The event's photo gallery + uploader. Files upload one at a time as raw * request bodies, which keeps a 100 MB RAW frame out of memory and gives usable * per-file progress on a phone. RAW files show a file tile; JPEG/PNG/WebP * preview. */ export function PhotoGallery({ eventId, photos, canContribute, canManage, currentUserId, storageReady, storageMessage, }: { eventId: string; photos: GalleryPhoto[]; canContribute: boolean; canManage: boolean; currentUserId: string; /** Photos are stored only on the configured media storage share. */ storageReady: boolean; storageMessage: string; }) { const router = useRouter(); const inputRef = useRef(null); const [files, setFiles] = useState([]); const [uploading, setUploading] = useState(false); const [progress, setProgress] = useState<{ done: number; total: number; current: string; } | null>(null); const [error, setError] = useState(null); const [notice, setNotice] = useState(null); const [viewing, setViewing] = useState(null); const editablePhotos = photos.filter( (photo) => photo.editable && storageReady, ); const viewingIndex = viewing ? editablePhotos.findIndex((photo) => photo.id === viewing.id) : -1; async function upload() { if (files.length === 0) return; setUploading(true); setError(null); setNotice(null); const failures: string[] = []; let duplicates = 0; let uploaded = 0; for (let index = 0; index < files.length; index += 1) { const file = files[index]; setProgress({ done: index, total: files.length, current: file.name }); try { const res = await fetch( `/api/events/${eventId}/photos?name=${encodeURIComponent(file.name)}`, { method: "POST", headers: { "content-type": file.type || "application/octet-stream", }, body: file, }, ); const data = (await res.json().catch(() => ({}))) as { error?: string; duplicate?: boolean; }; if (res.status === 401) { setError("Your session expired. Sign in again to upload."); window.location.assign("/login"); return; } if (!res.ok) { failures.push(`${file.name}: ${data.error ?? "upload failed"}`); continue; } if (data.duplicate) duplicates += 1; else uploaded += 1; } catch { failures.push(`${file.name}: network error`); } } setProgress({ done: files.length, total: files.length, current: "", }); setFiles([]); if (inputRef.current) inputRef.current.value = ""; setUploading(false); setNotice( [ uploaded > 0 ? `${uploaded} uploaded` : null, duplicates > 0 ? `${duplicates} already on this event` : null, ] .filter(Boolean) .join(" · ") || null, ); if (failures.length > 0) { setError(failures.join("\n")); } router.refresh(); } async function remove(photo: GalleryPhoto) { if (!window.confirm(`Delete ${photo.filename}?`)) return; setError(null); try { const res = await fetch( `/api/events/${eventId}/folders/${photo.folderId}/photos/${photo.id}`, { method: "DELETE" }, ); const data = (await res.json().catch(() => ({}))) as { error?: string }; if (!res.ok) { setError(data.error ?? "Could not delete that photo."); return; } router.refresh(); } catch { setError("Network error."); } } return (
{canContribute && !storageReady && (

Photo uploads and editing are disabled. {storageMessage}

)} {canContribute && (

Upload photos to this event

{ setFiles(Array.from(event.target.files ?? [])); setNotice(null); setError(null); }} />
{files.length > 0 && !uploading && (

{files.length} file{files.length === 1 ? "" : "s"} selected,{" "} {formatBytes(files.reduce((sum, file) => sum + file.size, 0))}. Uploads run one at a time.

)} {progress && (

{progress.done < progress.total ? `Uploading ${progress.done + 1} of ${progress.total}: ${progress.current}` : "Upload finished."}

)} {notice && (

{notice}

)} {error && (

{error}

)}

RAW files download as originals; browsers cannot preview them. JPEG, PNG, WebP, GIF and AVIF show a preview.

)} {photos.length === 0 ? (

No photos yet. Upload the first frame for this event.

) : (
    {photos.map((photo) => { const src = `/api/events/${eventId}/folders/${photo.folderId}/photos/${photo.id}`; const editable = photo.editable && storageReady; const canRemove = canManage || photo.uploaderId === currentUserId; const version = photo.editedAt ? Date.parse(photo.editedAt) : 0; // The grid uses the cached 640px thumbnail; a saved edit is shown // from the full-resolution export so the badge and the image agree. const displaySrc = photo.editedAt ? `${src}?variant=edited&v=${version}` : `${src}/thumb`; return (
  • {photo.filename}

    {formatBytes(photo.sizeBytes)}
    {photo.editedAt && ( Edited )} {photo.kind === "raw" ? "RAW" : "Image"}

    {photo.uploaderName}

    {photo.editedAt ? ( <> Original ) : ( )} {editable && ( )} {canRemove && ( )}
  • ); })}
)} {viewing && ( setViewing(null)} onSaved={() => router.refresh()} onPrevious={ viewingIndex > 0 ? () => setViewing(editablePhotos[viewingIndex - 1]) : undefined } onNext={ viewingIndex >= 0 && viewingIndex < editablePhotos.length - 1 ? () => setViewing(editablePhotos[viewingIndex + 1]) : undefined } /> )}
); }