373 lines
16 KiB
TypeScript
373 lines
16 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useMemo, useRef, useState } from "react";
|
|
import { toast } from "sonner";
|
|
import { ChevronDownIcon, SendIcon, UploadIcon } from "lucide-react";
|
|
import { useRouter } from "next/navigation";
|
|
import type { PublishingPolicy } from "@album/contracts";
|
|
import { cn } from "@/lib/utils";
|
|
import { MAX_PHOTO_BYTES } from "@album/contracts";
|
|
import { api } from "@/trpc/react";
|
|
import { imageContentType, isAllowedPhoto, putWithProgress } from "@/lib/upload";
|
|
import { Alert, AlertDescription } from "@/components/ui/alert";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
|
|
import { Input } from "@/components/ui/input";
|
|
import { Textarea } from "@/components/ui/textarea";
|
|
import { Switch } from "@/components/ui/switch";
|
|
import { Progress } from "@/components/ui/progress";
|
|
import { Spinner } from "@/components/ui/spinner";
|
|
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
|
|
import { uploadProgress } from "@/lib/upload-progress";
|
|
|
|
type QueueItem = {
|
|
file?: File;
|
|
created?: { photoId: string; eventId: string; uploadUrl: string };
|
|
uploaded?: boolean;
|
|
id: string;
|
|
name: string;
|
|
progress: number;
|
|
status: "queued" | "uploading" | "done" | "error";
|
|
error?: string;
|
|
};
|
|
|
|
function guestKey(slug: string, field: string) {
|
|
return `album:guest:${slug}:${field}`;
|
|
}
|
|
|
|
export function GuestUpload({
|
|
slug,
|
|
uploadEnabled,
|
|
notesEnabled,
|
|
notesPolicy,
|
|
}: {
|
|
slug: string;
|
|
uploadEnabled: boolean;
|
|
notesEnabled: boolean;
|
|
notesPolicy: PublishingPolicy;
|
|
}) {
|
|
const router = useRouter();
|
|
const [name, setName] = useState("");
|
|
const [email, setEmail] = useState("");
|
|
const [note, setNote] = useState("");
|
|
const [notify, setNotify] = useState(false);
|
|
const [detailsOpen, setDetailsOpen] = useState(false);
|
|
const [dragging, setDragging] = useState(false);
|
|
const [queue, setQueue] = useState<QueueItem[]>([]);
|
|
const ensureGuest = api.guest.ensure.useMutation();
|
|
const startSubmission = api.guest.startSubmission.useMutation();
|
|
const createPhoto = api.photos.create.useMutation();
|
|
const completePhoto = api.photos.complete.useMutation();
|
|
const retryUpload = api.photos.retryUpload.useMutation();
|
|
const uploading = useRef(false);
|
|
const utils = api.useUtils();
|
|
const progress = uploadProgress(queue);
|
|
|
|
useEffect(() => {
|
|
const storedName = localStorage.getItem(guestKey(slug, "name")) ?? "";
|
|
const storedEmail = localStorage.getItem(guestKey(slug, "email")) ?? "";
|
|
const storedNote = localStorage.getItem(guestKey(slug, "note")) ?? "";
|
|
setName(storedName);
|
|
setEmail(storedEmail);
|
|
setNote(storedNote);
|
|
setNotify(localStorage.getItem(guestKey(slug, "notify")) === "true");
|
|
if (storedName || storedEmail || storedNote) setDetailsOpen(true);
|
|
}, [slug]);
|
|
|
|
const busy = useMemo(
|
|
() => queue.some((item) => item.status === "queued" || item.status === "uploading"),
|
|
[queue],
|
|
);
|
|
useEffect(() => {
|
|
if (!busy) return;
|
|
const warn = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = ""; };
|
|
window.addEventListener("beforeunload", warn);
|
|
return () => window.removeEventListener("beforeunload", warn);
|
|
}, [busy]);
|
|
|
|
async function sendNote(detailsOnly = false) {
|
|
try {
|
|
await ensureGuest.mutateAsync({ eventSlug: slug, displayName: name.trim() || undefined,
|
|
email: email.trim() || undefined, notifyWhenReady: Boolean(email.trim()) && notify, note: detailsOnly ? undefined : note.trim() });
|
|
localStorage.setItem(guestKey(slug, "name"), name.trim());
|
|
localStorage.setItem(guestKey(slug, "email"), email.trim());
|
|
localStorage.setItem(guestKey(slug, "notify"), String(notify));
|
|
if (!detailsOnly) { localStorage.removeItem(guestKey(slug, "note")); setNote(""); }
|
|
toast.success(detailsOnly ? "Guest details saved" : "Note sent");
|
|
router.refresh();
|
|
} catch (error) { toast.error(error instanceof Error ? error.message : "Could not send note"); }
|
|
}
|
|
|
|
async function uploadFiles(files: File[], retryItems?: QueueItem[]) {
|
|
const accepted = files.filter(isAllowedPhoto);
|
|
if (!uploadEnabled || uploading.current) return;
|
|
if (accepted.length !== files.length) {
|
|
toast.error("Some files were skipped. Use JPEG, PNG, WebP, or HEIC under 25 MB.");
|
|
}
|
|
if (!accepted.length) return;
|
|
uploading.current = true;
|
|
const items: QueueItem[] = retryItems ?? accepted.map((file) => ({
|
|
file,
|
|
id: crypto.randomUUID(),
|
|
name: file.name,
|
|
progress: 0,
|
|
status: "queued",
|
|
}));
|
|
for (const item of items) { item.status = "queued"; item.error = undefined; }
|
|
setQueue((current) => retryItems ? current.map(entry => items.find(item => item.id === entry.id) ?? entry) : [...items, ...current]);
|
|
const trimmedName = name.trim();
|
|
const trimmedEmail = email.trim();
|
|
const trimmedNote = note.trim();
|
|
try {
|
|
localStorage.setItem(guestKey(slug, "name"), trimmedName);
|
|
localStorage.setItem(guestKey(slug, "email"), trimmedEmail);
|
|
localStorage.setItem(guestKey(slug, "note"), trimmedNote);
|
|
localStorage.setItem(guestKey(slug, "notify"), String(notify));
|
|
|
|
await ensureGuest.mutateAsync({
|
|
eventSlug: slug,
|
|
displayName: trimmedName || undefined,
|
|
email: trimmedEmail || undefined,
|
|
notifyWhenReady: Boolean(trimmedEmail) && notify,
|
|
note: trimmedNote || undefined,
|
|
});
|
|
const submission = await startSubmission.mutateAsync({ eventSlug: slug });
|
|
|
|
for (const [index, file] of accepted.entries()) {
|
|
const item = items[index];
|
|
if (!item) continue;
|
|
const contentType = imageContentType(file);
|
|
if (!contentType) continue;
|
|
setQueue((current) =>
|
|
current.map((entry) =>
|
|
entry.id === item.id ? { ...entry, status: "uploading" } : entry,
|
|
),
|
|
);
|
|
try {
|
|
const created = item.created ?? await createPhoto.mutateAsync({
|
|
eventSlug: slug,
|
|
submissionId: submission.submissionId,
|
|
contentType,
|
|
fileName: file.name,
|
|
byteSize: file.size,
|
|
});
|
|
const previous = item.created;
|
|
item.created = created;
|
|
const uploadUrl = previous && !item.uploaded ? (await retryUpload.mutateAsync({ photoId: created.photoId, eventId: created.eventId })).uploadUrl : created.uploadUrl;
|
|
if (!item.uploaded && uploadUrl) await putWithProgress(uploadUrl, file, contentType, (progress) => {
|
|
setQueue((current) =>
|
|
current.map((entry) =>
|
|
entry.id === item.id ? { ...entry, progress } : entry,
|
|
),
|
|
);
|
|
});
|
|
item.uploaded = true;
|
|
await completePhoto.mutateAsync({ photoId: created.photoId });
|
|
setQueue((current) =>
|
|
current.map((entry) =>
|
|
entry.id === item.id
|
|
? { ...entry, status: "done", progress: 100, file: undefined }
|
|
: entry,
|
|
),
|
|
);
|
|
} catch (error) {
|
|
const message =
|
|
error instanceof Error ? error.message : "Upload failed";
|
|
setQueue((current) =>
|
|
current.map((entry) =>
|
|
entry.id === item.id
|
|
? { ...entry, created: item.created, uploaded: item.uploaded, status: "error", error: message }
|
|
: entry,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
await utils.event.gallery.invalidate(slug);
|
|
router.refresh();
|
|
} catch (error) {
|
|
toast.error(error instanceof Error ? error.message : "Could not start upload");
|
|
setQueue((current) =>
|
|
current.map((entry) =>
|
|
items.some((item) => item.id === entry.id) && entry.status === "queued"
|
|
? { ...entry, status: "error", error: "Could not start upload" }
|
|
: entry,
|
|
),
|
|
);
|
|
} finally { uploading.current = false; }
|
|
}
|
|
|
|
if (!uploadEnabled && !notesEnabled) {
|
|
return (
|
|
<Alert>
|
|
<AlertDescription>Submissions are closed for this event.</AlertDescription>
|
|
</Alert>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="flex flex-col gap-4">
|
|
{uploadEnabled ? <label
|
|
className={cn(
|
|
"flex min-h-52 cursor-pointer flex-col items-center justify-center gap-3 rounded-2xl border border-dashed border-primary/35 bg-card px-5 py-10 text-center shadow-sm transition-all duration-200 hover:border-primary/60 hover:bg-accent/50 motion-reduce:transition-none",
|
|
dragging && "scale-[1.01] border-primary bg-accent/60 shadow-[0_0_0_6px] shadow-primary/15 motion-reduce:scale-100",
|
|
)}
|
|
onDragEnter={(event) => {
|
|
event.preventDefault();
|
|
setDragging(true);
|
|
}}
|
|
onDragOver={(event) => {
|
|
event.preventDefault();
|
|
setDragging(true);
|
|
}}
|
|
onDragLeave={(event) => {
|
|
if (!event.currentTarget.contains(event.relatedTarget as Node)) {
|
|
setDragging(false);
|
|
}
|
|
}}
|
|
onDrop={(event) => {
|
|
event.preventDefault();
|
|
setDragging(false);
|
|
const files = Array.from(event.dataTransfer.files);
|
|
if (files.length) void uploadFiles(files);
|
|
}}
|
|
>
|
|
<span className="flex size-14 items-center justify-center rounded-full bg-accent text-accent-foreground transition-transform duration-300 ease-out group-hover:scale-105">
|
|
<UploadIcon aria-hidden="true" />
|
|
</span>
|
|
<div className="flex flex-col gap-1">
|
|
<span className="text-base font-medium">Add photos from this phone</span>
|
|
<span className="text-sm text-foreground/70">
|
|
JPEG, PNG, WebP, or HEIC. Up to {Math.round(MAX_PHOTO_BYTES / (1024 * 1024))} MB each. Originals stay full quality.
|
|
</span>
|
|
</div>
|
|
<input
|
|
type="file"
|
|
accept="image/jpeg,image/png,image/webp,image/heic,image/heif,.heic,.heif"
|
|
multiple
|
|
className="sr-only"
|
|
disabled={busy}
|
|
onChange={(event) => {
|
|
const files = Array.from(event.target.files ?? []);
|
|
event.target.value = "";
|
|
if (files.length) void uploadFiles(files);
|
|
}}
|
|
/>
|
|
<Button type="button" disabled={busy} asChild className="tap-target">
|
|
<span>
|
|
{busy ? <Spinner data-icon="inline-start" /> : null}
|
|
{busy ? "Uploading…" : "Choose photos"}
|
|
</span>
|
|
</Button>
|
|
</label> : null}
|
|
{queue.length > 0 ? (
|
|
<Card>
|
|
<CardHeader>
|
|
<div className="flex items-center justify-between gap-4">
|
|
<CardTitle>{busy ? "Uploading your photos" : progress.failed ? "Some photos need attention" : "Photos uploaded"}</CardTitle>
|
|
<span className="text-2xl font-semibold tabular-nums">{progress.percent}%</span>
|
|
</div>
|
|
<CardDescription role="status">{progress.completed} of {progress.total} photos uploaded{progress.failed ? ` · ${progress.failed} need retry` : ""}</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="flex flex-col gap-4">
|
|
<Progress value={progress.percent} aria-label="Overall upload progress" />
|
|
<p className="text-sm text-muted-foreground">{busy ? "Keep this page open until uploading finishes." : progress.failed ? "Open file details below to retry unsuccessful uploads." : "Your originals are saved. Gallery previews may take a moment to appear."}</p>
|
|
<details className="group">
|
|
<summary className="flex min-h-11 cursor-pointer list-none items-center justify-between gap-3 text-sm font-medium [&::-webkit-details-marker]:hidden">File details<ChevronDownIcon className="size-4 transition-transform group-open:rotate-180" aria-hidden="true" /></summary>
|
|
<ul className="flex max-h-80 flex-col gap-4 overflow-y-auto pt-3">
|
|
{queue.map((item) => (
|
|
<li key={item.id} className="flex flex-col gap-1">
|
|
<div className="flex justify-between gap-3 text-sm">
|
|
<span className="truncate">{item.name}</span>
|
|
<span className="shrink-0 text-muted-foreground">{item.status === "done" ? "Uploaded · processing for gallery" : item.status === "uploading" ? `${item.progress}% uploaded` : item.status === "error" ? "Needs retry" : "Waiting"}</span>
|
|
</div>
|
|
<Progress value={item.progress} />
|
|
{item.error ? (
|
|
<p className="text-sm text-destructive">{item.error}</p>
|
|
) : null}
|
|
{item.status === "error" && item.file ? <Button type="button" variant="outline" disabled={busy || !uploadEnabled} onClick={() => void uploadFiles([item.file!], [{ ...item }])}>Retry file</Button> : null}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</details>
|
|
</CardContent>
|
|
</Card>
|
|
) : null}
|
|
<details
|
|
className="rounded-2xl border bg-card/60 px-4 py-1"
|
|
open={detailsOpen}
|
|
onToggle={(event) => setDetailsOpen(event.currentTarget.open)}
|
|
>
|
|
<summary className="tap-target flex cursor-pointer list-none items-center justify-between gap-3 py-2 font-medium [&::-webkit-details-marker]:hidden">
|
|
<span>Add a name or note</span>
|
|
<ChevronDownIcon
|
|
aria-hidden="true"
|
|
className={cn("size-4 shrink-0 transition-transform duration-200", detailsOpen && "rotate-180")}
|
|
/>
|
|
</summary>
|
|
<div className="pb-4">
|
|
<FieldGroup>
|
|
<Field>
|
|
<FieldLabel htmlFor="contributor-name">Your name (optional)</FieldLabel>
|
|
<Input
|
|
id="contributor-name"
|
|
name="contributor-name"
|
|
autoComplete="name"
|
|
value={name}
|
|
onChange={(event) => setName(event.target.value)}
|
|
placeholder="Your name"
|
|
maxLength={80}
|
|
className="tap-target"
|
|
/>
|
|
</Field>
|
|
<Field>
|
|
<FieldLabel htmlFor="contributor-email">Email (optional)</FieldLabel>
|
|
<Input
|
|
id="contributor-email"
|
|
name="contributor-email"
|
|
type="email"
|
|
autoComplete="email"
|
|
inputMode="email"
|
|
spellCheck={false}
|
|
value={email}
|
|
onChange={(event) => setEmail(event.target.value)}
|
|
placeholder="you@example.com"
|
|
className="tap-target"
|
|
/>
|
|
<FieldDescription>
|
|
Stay anonymous if you skip this. Remembered on this device for this event.
|
|
</FieldDescription>
|
|
</Field>
|
|
{email.trim() ? (
|
|
<Field orientation="horizontal">
|
|
<FieldLabel htmlFor="notify">Email me when the gallery is ready</FieldLabel>
|
|
<Switch id="notify" checked={notify} onCheckedChange={setNotify} />
|
|
</Field>
|
|
) : null}
|
|
<Field>
|
|
<FieldLabel htmlFor="note">A note for the event people (optional)</FieldLabel>
|
|
<Textarea
|
|
id="note"
|
|
value={note}
|
|
onChange={(event) => setNote(event.target.value)}
|
|
placeholder="Congratulations — enjoy the day."
|
|
maxLength={2000}
|
|
/>
|
|
<FieldDescription>
|
|
{notesPolicy === "automatic" ? "Your note and name will be published automatically."
|
|
: notesPolicy === "approved" ? "Your note and name may be published after organizer approval."
|
|
: "Your note is private to the event organizers."}
|
|
{" "}You can send a note without photos. Sending another replaces your previous note.
|
|
</FieldDescription>
|
|
</Field>
|
|
<Button type="button" disabled={!notesEnabled || !note.trim() || ensureGuest.isPending || busy} onClick={() => void sendNote()}>
|
|
<SendIcon data-icon="inline-start" aria-hidden="true" />
|
|
{ensureGuest.isPending ? "Sending…" : "Send note"}
|
|
</Button>
|
|
<Button type="button" variant="outline" disabled={!email.trim() || ensureGuest.isPending || busy} onClick={() => void sendNote(true)}>Save details without a photo or note</Button>
|
|
</FieldGroup>
|
|
</div>
|
|
</details>
|
|
</div>
|
|
);
|
|
}
|