push to maple-street

This commit is contained in:
Tiel Coder
2026-11-20 04:07:02 +00:00
parent 2cec220a24
commit 5adf1cef1f
345 changed files with 86105 additions and 1079 deletions
+401
View File
@@ -0,0 +1,401 @@
"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";
export interface GalleryPhoto {
id: string;
filename: string;
sizeBytes: number;
kind: "raw" | "image";
uploaderId: string;
uploaderName: string;
previewable: boolean;
editable: boolean;
adjustments: PhotoAdjustments;
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();
}
/**
* Folder 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,
folderId,
photos,
canContribute,
canManage,
currentUserId,
}: {
eventId: string;
folderId: string;
photos: GalleryPhoto[];
canContribute: boolean;
canManage: boolean;
currentUserId: 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);
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}/folders/${folderId}/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 in this folder` : 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/${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 && (
<div className="space-y-2 rounded-md border border-border p-3">
<p className="text-sm font-medium">Upload photos to this folder</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}
onChange={(event) => {
setFiles(Array.from(event.target.files ?? []));
setNotice(null);
setError(null);
}}
/>
<Button
type="button"
size="sm"
disabled={uploading || files.length === 0}
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">
This folder is empty.
</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/${folderId}/photos/${photo.id}`;
const canRemove = canManage || photo.uploaderId === currentUserId;
const version = photo.editedAt ? Date.parse(photo.editedAt) : 0;
const displaySrc = photo.editedAt
? `${src}?variant=edited&v=${version}`
: src;
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={
photo.editable
? `View and edit ${photo.filename}`
: `View ${photo.filename}`
}
disabled={!photo.editable}
onClick={() => setViewing(photo)}
>
{photo.previewable || photo.editedAt ? (
// Frames are private; the serving route sets the cache policy.
// eslint-disable-next-line @next/next/no-img-element
<img
src={displaySrc}
alt={photo.filename}
loading="lazy"
decoding="async"
className="h-full w-full object-cover"
/>
) : (
<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>
)}
{photo.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 &amp; 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">
<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>
{photo.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={folderId}
photo={{
id: viewing.id,
filename: viewing.filename,
kind: viewing.kind,
editedAt: viewing.editedAt,
editedSizeBytes: viewing.editedSizeBytes,
adjustments: viewing.adjustments,
} 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>
);
}