Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | 55x 55x 55x 55x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 11x 11x 3x 1x 1x 2x 1x 3x 1x 1x 1x 1x 1x 1x 11x 11x 20x 20x 20x 4x 4x 4x 20x 2x 1x 1x 20x 2x 1x 20x 1x 20x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 20x 8x 1x 3x 80x | "use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { getPhotoAssetUrl } from "@/lib/photos";
export interface ViewerPhoto {
id: string;
/** Item-assigned photos only (covers/heroes) — the only photos the viewer opens. */
itemId: string;
collectionId: string;
rotation: number;
updatedAt: string | Date;
alt?: string;
}
const MIN_SCALE = 1;
const MAX_SCALE = 4;
const STEP = 0.5;
/** Tap-first photo lightbox: zoom (+/-), drag-to-pan when zoomed, and persisted
* rotate. No swipe. Standard modal idiom (scrim + bg-surface panel). Portaled to <body> so
* the card's `isolate` stacking context can't trap it. */
export function ImageViewer({ photo, onClose }: { photo: ViewerPhoto; onClose: () => void }) {
const router = useRouter();
const panelRef = useRef<HTMLDivElement>(null);
const [rotation, setRotation] = useState(photo.rotation);
const [version, setVersion] = useState(() => new Date(photo.updatedAt).getTime());
const [optimisticDeg, setOptimisticDeg] = useState(0); // CSS turn until the rotated bytes load
const [scale, setScale] = useState(MIN_SCALE);
const [pan, setPan] = useState({ x: 0, y: 0 });
const dragOrigin = useRef<{ x: number; y: number } | null>(null);
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState("");
useEffect(() => {
panelRef.current?.focus();
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
onClose();
return;
}
if (e.key !== "Tab") return;
const focusables = panelRef.current?.querySelectorAll<HTMLElement>(
'button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])',
);
Iif (!focusables || focusables.length === 0) return;
const first = focusables[0];
const last = focusables[focusables.length - 1];
Iif (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else Eif (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [onClose]);
const src = getPhotoAssetUrl(photo.collectionId, photo.itemId, photo.id, { w: 1280, v: version });
const patchUrl = `/api/collections/${photo.collectionId}/items/${photo.itemId}/photos/${photo.id}`;
const zoomTo = (next: number) => {
const clamped = Math.min(MAX_SCALE, Math.max(MIN_SCALE, next));
setScale(clamped);
if (clamped <= MIN_SCALE) setPan({ x: 0, y: 0 }); // panning only matters while zoomed
};
// Drag-to-pan (pointer events → mouse + touch). Only meaningful while zoomed in.
const onPointerDown = (e: React.PointerEvent) => {
if (scale <= MIN_SCALE) return;
dragOrigin.current = { x: e.clientX - pan.x, y: e.clientY - pan.y };
(e.currentTarget as Element).setPointerCapture?.(e.pointerId);
};
const onPointerMove = (e: React.PointerEvent) => {
if (!dragOrigin.current) return;
setPan({ x: e.clientX - dragOrigin.current.x, y: e.clientY - dragOrigin.current.y });
};
const endPan = () => {
dragOrigin.current = null;
};
const rotate = async () => {
Iif (busy) return;
const next = (rotation + 90) % 360;
setOptimisticDeg((d) => d + 90); // instant visual feedback
setBusy(true);
try {
const res = await fetch(patchUrl, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ rotation: next }),
});
if (!res.ok) throw new Error(String(res.status));
const data = (await res.json()) as { rotation: number; updatedAt: string };
setRotation(data.rotation);
setVersion(new Date(data.updatedAt).getTime()); // new src → the rotated bytes load (onLoad clears the CSS turn)
setStatus(`Rotated to ${data.rotation} degrees`);
router.refresh();
} catch {
setOptimisticDeg((d) => d - 90); // revert the optimistic turn
setStatus("We couldn't rotate that photo. Please try again.");
} finally {
setBusy(false);
}
};
return createPortal(
<div
className="fixed inset-0 z-50 flex items-center justify-center"
onClick={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<div className="absolute inset-0 bg-ground" onClick={onClose} aria-hidden />
<div
ref={panelRef}
role="dialog"
aria-modal="true"
aria-label="Photo"
tabIndex={-1}
className="relative z-10 mx-4 flex max-h-[90vh] w-full max-w-3xl flex-col gap-4 rounded-card bg-surface p-4 shadow-raised outline-hidden"
>
<div
className="relative flex-1 overflow-hidden rounded-card bg-ground"
style={{ minHeight: "50vh", touchAction: scale > MIN_SCALE ? "none" : "auto", cursor: scale > MIN_SCALE ? "grab" : "default" }}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={endPan}
onPointerCancel={endPan}
>
<Image
key={version}
src={src}
alt={photo.alt ?? "Photo"}
fill
unoptimized
draggable={false}
className="object-contain transition-transform motion-reduce:transition-none"
style={{ transform: `translate(${pan.x}px, ${pan.y}px) rotate(${optimisticDeg}deg) scale(${scale})` }}
onLoad={() => {
if (optimisticDeg !== 0) setOptimisticDeg(0);
}}
/>
</div>
<div className="flex items-center justify-center gap-2">
<ViewerButton label="Zoom out" disabled={scale <= MIN_SCALE} onClick={() => zoomTo(scale - STEP)}>−</ViewerButton>
<ViewerButton label="Zoom in" disabled={scale >= MAX_SCALE} onClick={() => zoomTo(scale + STEP)}>+</ViewerButton>
<ViewerButton label="Rotate photo" disabled={busy} onClick={rotate}>↻</ViewerButton>
<ViewerButton label="Close" onClick={onClose}>✕</ViewerButton>
</div>
<p role="status" aria-live="polite" className="min-h-5 text-center text-sm text-ink-soft">
{status}
</p>
</div>
</div>,
document.body,
);
}
function ViewerButton({
label,
onClick,
disabled,
children,
}: {
label: string;
onClick: () => void;
disabled?: boolean;
children: React.ReactNode;
}) {
return (
<button
type="button"
aria-label={label}
onClick={onClick}
disabled={disabled}
className="inline-flex h-11 min-w-11 items-center justify-center rounded-control bg-surface-raised px-3 text-lg text-ink shadow-lift transition-colors hover:bg-ground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-40"
>
{children}
</button>
);
}
|