Number 46: Photo grid that opens into the photo
Specification
- Catalogue
- No. 46 of 110
- Section
- Media and galleries
- Interaction
- Layout Animation
- Element
- Media, Overlay
- Preview
- Live component
- Imports
- react 19.3.1
- Added
Notes
Tap a thumbnail and that same picture grows to full view, then shrinks back to its place.
The visitor never loses their place in the set: the photo they chose is the one that grows, and closing sends it back to the same square. Arrow keys move through the set, a drag down closes it.
Grows from the thumbnail 420ms, cubic-bezier(.16, 1, .3, 1); back to it 300ms. Animates position and size, not scale, so the crop changes smoothly and nothing stretches. Native dialog: Escape closes, focus returns to the thumbnail of the photo last shown. Drag down more than 90px to close. Left and Right move to the previous and next photo, Home and End to the first and last; the frame glides to the next photo's shape in 320ms, and a press past either end nudges the photo instead of wrapping round. The keys are read for the whole open view, so they work wherever focus sits inside it. Instant under reduced motion.
The names, figures and pictures in the demo are sample content; a real build uses the client's own.
Code
React and plain CSS"use client";
import { useEffect, useId, useLayoutEffect, useRef, useState, type PointerEvent } from "react";
import { growBetween, reducedNow } from "@/components/pieces/motion-helpers";
import type { LivePreviewProps } from "@/components/live/types";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import "@/components/pieces/styles/lightbox-bar.css";
import "./lightbox-grid.css";
const S = "/samples";
const WORK = [
{ src: "studio-vases.svg", w: 900, h: 600, title: "Bottle vases", note: "Ash glaze and celadon, stoneware" },
{ src: "studio-bowls.svg", w: 720, h: 900, title: "Nesting bowls", note: "Ink blue outside, raw clay foot" },
{ src: "studio-jug.svg", w: 900, h: 600, title: "Pouring jug", note: "Terracotta with a pulled handle" },
{ src: "studio-plates.svg", w: 900, h: 600, title: "Side plates", note: "Oatmeal and sea green, set of four" },
{ src: "studio-shelf.svg", w: 720, h: 900, title: "Shelf pieces", note: "Rust and bone glazes" },
{ src: "studio-cups.svg", w: 900, h: 600, title: "Morning cups", note: "Four glazes from one firing" },
];
const LAST = WORK.length - 1;
function fitRect(w: number, h: number): DOMRect {
const vw = window.innerWidth;
const vh = window.innerHeight;
const maxW = Math.min(vw - 32, 1100);
const maxH = vh - 170;
const s = Math.min(maxW / w, maxH / h);
const width = Math.round(w * s);
const height = Math.round(h * s);
return new DOMRect(Math.round((vw - width) / 2), Math.max(56, Math.round((vh - height) / 2) - 40), width, height);
}
/** The step a key asks for while the photo is open, or null for keys the view leaves alone. */
function keyStep(e: KeyboardEvent, index: number): number | null {
if (e.altKey || e.ctrlKey || e.metaKey || e.defaultPrevented) return null;
if (e.key === "ArrowRight") return 1;
if (e.key === "ArrowLeft") return -1;
if (e.key === "Home") return -index;
if (e.key === "End") return LAST - index;
return null;
}
function LightboxDemo() {
const dialog = useRef<HTMLDialogElement>(null);
const photo = useRef<HTMLImageElement>(null);
const thumbs = useRef<(HTMLButtonElement | null)[]>([]);
const [index, setIndex] = useState<number | null>(null);
const [rect, setRect] = useState<DOMRect | null>(null);
const [closing, setClosing] = useState(false);
const drag = useRef<{ y: number; id: number } | null>(null);
const [dragging, setDragging] = useState(false);
const [dy, setDy] = useState(0);
// Where the photo was on screen when the visitor moved to another one.
const glideFrom = useRef<DOMRect | null>(null);
const titleId = useId();
const open = (i: number) => {
const d = dialog.current;
const thumb = thumbs.current[i];
if (!d || !thumb) return;
const to = fitRect(WORK[i]!.w, WORK[i]!.h);
setIndex(i);
setRect(to);
setClosing(false);
// The dialog itself takes focus (it is empty until React renders the photo),
// so the arrow keys reach the open view at once.
d.showModal();
// The photo renders at its final box; grow it there from the thumbnail.
requestAnimationFrame(() => {
if (photo.current) void growBetween(photo.current, thumb.getBoundingClientRect(), to, 420, ["10px", "6px"]);
});
};
const close = async () => {
const d = dialog.current;
const el = photo.current;
if (!d || index === null || closing) return;
const thumb = thumbs.current[index];
setClosing(true);
if (el && thumb) {
const from = el.getBoundingClientRect();
setDy(0);
await growBetween(el, from, thumb.getBoundingClientRect(), 300, ["6px", "10px"]);
}
d.close();
setClosing(false);
setIndex(null);
thumb?.focus();
};
// A press past either end nudges the photo, so the key visibly landed.
const nudge = (step: number) => {
const el = photo.current;
if (!el || reducedNow()) return;
el.animate([{ translate: "0 0" }, { translate: `${step * -14}px 0` }, { translate: "0 0" }], { duration: 260, easing: "cubic-bezier(0.22, 1, 0.36, 1)" });
};
const go = (step: number) => {
if (index === null || closing || step === 0) return;
const next = index + step;
if (next < 0 || next > LAST) return nudge(Math.sign(step));
if (photo.current) glideFrom.current = photo.current.getBoundingClientRect();
setIndex(next);
setRect(fitRect(WORK[next]!.w, WORK[next]!.h));
};
// After the next photo renders at its own box, glide there from where the last one was.
// This also replaces a grow that is still running, so the new photo never sits in the old box.
useLayoutEffect(() => {
const el = photo.current;
const from = glideFrom.current;
glideFrom.current = null;
if (!el || !from || !rect) return;
for (const a of el.getAnimations()) a.cancel();
void growBetween(el, from, rect, 320);
}, [index, rect]);
useEffect(() => {
if (index === null) return;
const onResize = () => setRect(fitRect(WORK[index]!.w, WORK[index]!.h));
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, [index]);
// While the photo is open the rest of the page is inert, so every key press belongs
// to it. Listening on the document means the keys work wherever focus sits inside.
const onKeyRef = useRef<(e: KeyboardEvent) => void>(() => {});
useLayoutEffect(() => {
onKeyRef.current = (e) => {
if (index === null) return;
const step = keyStep(e, index);
if (step === null) return;
e.preventDefault();
go(step);
};
});
const isOpen = index !== null;
useEffect(() => {
if (!isOpen) return;
const onKey = (e: KeyboardEvent) => onKeyRef.current(e);
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [isOpen]);
// Drag the photo down to send it back to its thumbnail.
const onDown = (e: PointerEvent<HTMLImageElement>) => {
if (closing) return;
drag.current = { y: e.clientY, id: e.pointerId };
setDragging(true);
e.currentTarget.setPointerCapture(e.pointerId);
};
const onMove = (e: PointerEvent<HTMLImageElement>) => {
if (drag.current?.id === e.pointerId) setDy(Math.max(0, e.clientY - drag.current.y));
};
const onUp = (e: PointerEvent<HTMLImageElement>) => {
if (drag.current?.id !== e.pointerId) return;
drag.current = null;
setDragging(false);
if (dy > 90) void close();
else setDy(0);
};
const item = index === null ? null : WORK[index];
return (
<div className="dm">
<ul className="lb-grid" aria-label="Sample work">
{WORK.map((w, i) => (
<li key={w.src}>
<button
ref={(el) => {
thumbs.current[i] = el;
}}
type="button"
className="lb-thumb"
onClick={() => open(i)}
aria-label={`Open ${w.title}`}
aria-haspopup="dialog"
data-hidden={index === i || undefined}
>
<img src={`${S}/${w.src}`} alt="" draggable={false} />
</button>
</li>
))}
</ul>
<p className="dm-hint">Open a photo, then use the arrow keys, or drag it down to close</p>
<dialog
ref={dialog}
className="lb"
tabIndex={-1}
aria-labelledby={titleId}
data-closing={closing || undefined}
onCancel={(e) => {
e.preventDefault();
void close();
}}
onClick={(e) => {
if (e.target === e.currentTarget) void close();
}}
>
{item && index !== null && (
<>
<img
ref={photo}
className="lb-photo"
src={`${S}/${item.src}`}
alt={`${item.title}: ${item.note}`}
draggable={false}
style={{
...(rect ? { left: rect.left, top: rect.top, width: rect.width, height: rect.height } : {}),
translate: `0 ${dy}px`,
transition: dragging ? "none" : undefined,
}}
onPointerDown={onDown}
onPointerMove={onMove}
onPointerUp={onUp}
onPointerCancel={onUp}
/>
<div className="lb-bar" style={{ opacity: Math.max(0, 1 - dy / 160) }}>
<div className="lb-caption" aria-live="polite">
<strong id={titleId}>{item.title}</strong>
<span>
{item.note} · {index + 1} of {WORK.length}
</span>
</div>
<div className="lb-controls">
<button type="button" className="lb-btn" onClick={() => go(-1)} aria-label="Previous photo" aria-disabled={index === 0 || undefined}>
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
<path d="m15 6-6 6 6 6" />
</svg>
</button>
<button type="button" className="lb-btn" onClick={() => go(1)} aria-label="Next photo" aria-disabled={index === LAST || undefined}>
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
<path d="m9 6 6 6-6 6" />
</svg>
</button>
<button type="button" className="lb-btn" data-wide onClick={() => void close()}>
Close
</button>
</div>
</div>
</>
)}
</dialog>
</div>
);
}
export default function LightboxGridEntry(props: LivePreviewProps) {
return (
<PieceStage {...props} label="Photo grid that opens into the photo" sample>
<LightboxDemo />
</PieceStage>
);
}