fac9b96cca
CI / build (push) Has been cancelled
Folders were an implementation detail leaking into the event workflow: every upload needed a folder first and photos were split across pages. Uploads now land in a single implicit "Photos" folder and the event page renders one gallery with the uploader and an edited-only download. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
472 lines
16 KiB
TypeScript
472 lines
16 KiB
TypeScript
"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 (
|
|
<div className="flex h-full w-full flex-col items-center justify-center gap-1 px-2 text-center text-muted-foreground">
|
|
<FileImage className="h-8 w-8" aria-hidden="true" />
|
|
<span className="text-[11px] font-medium">Preview unavailable</span>
|
|
<span className="w-full truncate text-[10px]" title={alt}>
|
|
{alt}
|
|
</span>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
// Frames are private; the serving route sets the cache policy.
|
|
// eslint-disable-next-line @next/next/no-img-element
|
|
<img
|
|
src={src}
|
|
alt={alt}
|
|
loading="lazy"
|
|
decoding="async"
|
|
onError={() => 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<HTMLInputElement>(null);
|
|
const [files, setFiles] = useState<File[]>([]);
|
|
const [uploading, setUploading] = useState(false);
|
|
const [progress, setProgress] = useState<{
|
|
done: number;
|
|
total: number;
|
|
current: string;
|
|
} | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [notice, setNotice] = useState<string | null>(null);
|
|
const [viewing, setViewing] = useState<GalleryPhoto | null>(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 (
|
|
<div className="space-y-4">
|
|
{canContribute && !storageReady && (
|
|
<p
|
|
role="alert"
|
|
className="rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-xs text-amber-900 dark:text-amber-200"
|
|
>
|
|
Photo uploads and editing are disabled. {storageMessage}
|
|
</p>
|
|
)}
|
|
|
|
{canContribute && (
|
|
<div className="space-y-2 rounded-md border border-border p-3">
|
|
<p className="text-sm font-medium">Upload photos to this event</p>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<Input
|
|
ref={inputRef}
|
|
type="file"
|
|
multiple
|
|
accept={ACCEPT}
|
|
aria-label="Choose photos to upload"
|
|
className="h-9 max-w-md text-xs"
|
|
disabled={uploading || !storageReady}
|
|
onChange={(event) => {
|
|
setFiles(Array.from(event.target.files ?? []));
|
|
setNotice(null);
|
|
setError(null);
|
|
}}
|
|
/>
|
|
<Button
|
|
type="button"
|
|
size="sm"
|
|
disabled={uploading || files.length === 0 || !storageReady}
|
|
onClick={upload}
|
|
>
|
|
{uploading ? "Uploading…" : `Upload ${files.length || ""}`.trim()}
|
|
</Button>
|
|
</div>
|
|
{files.length > 0 && !uploading && (
|
|
<p className="text-xs text-muted-foreground">
|
|
{files.length} file{files.length === 1 ? "" : "s"} selected,{" "}
|
|
{formatBytes(files.reduce((sum, file) => sum + file.size, 0))}.
|
|
Uploads run one at a time.
|
|
</p>
|
|
)}
|
|
{progress && (
|
|
<p role="status" className="text-xs text-muted-foreground">
|
|
{progress.done < progress.total
|
|
? `Uploading ${progress.done + 1} of ${progress.total}: ${progress.current}`
|
|
: "Upload finished."}
|
|
</p>
|
|
)}
|
|
{notice && (
|
|
<p role="status" className="text-xs text-muted-foreground">
|
|
{notice}
|
|
</p>
|
|
)}
|
|
{error && (
|
|
<p role="alert" className="whitespace-pre-line text-xs text-destructive">
|
|
{error}
|
|
</p>
|
|
)}
|
|
<p className="text-xs text-muted-foreground">
|
|
RAW files download as originals; browsers cannot preview them. JPEG,
|
|
PNG, WebP, GIF and AVIF show a preview.
|
|
</p>
|
|
</div>
|
|
)}
|
|
|
|
{photos.length === 0 ? (
|
|
<p className="py-10 text-center text-sm text-muted-foreground">
|
|
No photos yet. Upload the first frame for this event.
|
|
</p>
|
|
) : (
|
|
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
|
{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 (
|
|
<li
|
|
key={photo.id}
|
|
className="overflow-hidden rounded-md border border-border bg-background"
|
|
>
|
|
<button
|
|
type="button"
|
|
className="group relative flex aspect-square w-full items-center justify-center bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
|
aria-label={
|
|
editable
|
|
? `View and edit ${photo.filename}`
|
|
: `View ${photo.filename}`
|
|
}
|
|
disabled={!editable}
|
|
onClick={() => setViewing(photo)}
|
|
>
|
|
{photo.previewable || photo.editedAt || photo.kind === "raw" ? (
|
|
<GalleryImage src={displaySrc} alt={photo.filename} />
|
|
) : (
|
|
<div className="flex flex-col items-center gap-1 text-muted-foreground">
|
|
<FileImage className="h-8 w-8" aria-hidden="true" />
|
|
<span className="text-xs font-medium">
|
|
{extensionOf(photo.filename)}
|
|
</span>
|
|
</div>
|
|
)}
|
|
{editable && (
|
|
<span className="absolute inset-x-0 bottom-0 translate-y-full bg-black/70 px-2 py-1 text-[11px] font-medium text-white transition-transform group-hover:translate-y-0 group-focus-visible:translate-y-0">
|
|
<Pencil className="mr-1 inline h-3 w-3" aria-hidden="true" />
|
|
View & edit
|
|
</span>
|
|
)}
|
|
</button>
|
|
<div className="space-y-1 p-2">
|
|
<p className="truncate text-xs font-medium" title={photo.filename}>
|
|
{photo.filename}
|
|
</p>
|
|
<div className="flex items-center justify-between gap-1">
|
|
<span className="text-[11px] text-muted-foreground">
|
|
{formatBytes(photo.sizeBytes)}
|
|
</span>
|
|
<div className="flex items-center gap-1">
|
|
{photo.editedAt && (
|
|
<Badge
|
|
variant="secondary"
|
|
className="px-1.5 py-0 text-[10px]"
|
|
>
|
|
Edited
|
|
</Badge>
|
|
)}
|
|
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
|
|
{photo.kind === "raw" ? "RAW" : "Image"}
|
|
</Badge>
|
|
</div>
|
|
</div>
|
|
<p className="truncate text-[11px] text-muted-foreground">
|
|
{photo.uploaderName}
|
|
</p>
|
|
<div className="flex flex-wrap items-center gap-1">
|
|
{photo.editedAt ? (
|
|
<>
|
|
<a
|
|
href={`${src}?variant=edited&download=1&v=${version}`}
|
|
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-primary hover:underline"
|
|
>
|
|
<Download className="h-3 w-3" aria-hidden="true" />
|
|
Download edited
|
|
</a>
|
|
<a
|
|
href={`${src}?download=1`}
|
|
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-muted-foreground hover:underline"
|
|
>
|
|
Original
|
|
</a>
|
|
</>
|
|
) : (
|
|
<a
|
|
href={`${src}?download=1`}
|
|
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-primary hover:underline"
|
|
>
|
|
<Download className="h-3 w-3" aria-hidden="true" />
|
|
Download
|
|
</a>
|
|
)}
|
|
{editable && (
|
|
<button
|
|
type="button"
|
|
onClick={() => setViewing(photo)}
|
|
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-primary hover:underline"
|
|
>
|
|
<Pencil className="h-3 w-3" aria-hidden="true" />
|
|
Edit
|
|
</button>
|
|
)}
|
|
{canRemove && (
|
|
<button
|
|
type="button"
|
|
onClick={() => remove(photo)}
|
|
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-destructive hover:underline"
|
|
>
|
|
<Trash2 className="h-3 w-3" aria-hidden="true" />
|
|
Delete
|
|
</button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</li>
|
|
);
|
|
})}
|
|
</ul>
|
|
)}
|
|
|
|
{viewing && (
|
|
<PhotoViewer
|
|
key={viewing.id}
|
|
eventId={eventId}
|
|
folderId={viewing.folderId}
|
|
photo={{
|
|
id: viewing.id,
|
|
filename: viewing.filename,
|
|
kind: viewing.kind,
|
|
editedAt: viewing.editedAt,
|
|
editedSizeBytes: viewing.editedSizeBytes,
|
|
adjustments: viewing.adjustments,
|
|
advancedEdit: viewing.advancedEdit,
|
|
advancedSummary: viewing.advancedSummary,
|
|
} satisfies ViewerPhoto}
|
|
onClose={() => 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
|
|
}
|
|
/>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|