dxbh-uiGitHub

Masonry Lightbox

A masonry grid of photos. Tap one and it grows out of its tile into a lightbox over a thick material; close it and it flies back along the same path, or swipe it down and let go.

Preview

Install

npx shadcn@latest add @dxbh-ui/masonry-lightbox

Add the @dxbh-ui registry to components.json once:

{
  "registries": {
    "@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
  }
}

Usage

demo.tsx
"use client";

import { MasonryLightbox, type MasonryLightboxItem } from "@/components/ui/masonry-lightbox/masonry-lightbox";

// Neutral stock photography from Lorem Picsum (Unsplash licence).
const photos: [id: number, w: number, h: number, alt: string][] = [
  [1015, 1200, 800, "A river winding through a green valley"],
  [1025, 900, 1200, "A small dog wrapped in a blanket"],
  [1043, 1200, 900, "Rocks on a misty shore"],
  [1035, 900, 1350, "A waterfall falling into a gorge"],
  [1039, 1200, 800, "Wet rocks under a waterfall"],
  [1018, 1200, 900, "Mountains under low clouds"],
  [1050, 900, 1200, "A quiet beach seen through trees"],
  [1060, 1200, 800, "Coffee being poured at a counter"],
  [1067, 1200, 900, "A city street at dusk"],
];

const items: MasonryLightboxItem[] = photos.map(([id, w, h, alt]) => ({
  src: `https://picsum.photos/id/${id}/${w}/${h}`,
  thumb: `https://picsum.photos/id/${id}/${Math.round(w / 3)}/${Math.round(h / 3)}`,
  width: w,
  height: h,
  alt,
  caption: alt,
}));

export default function MasonryLightboxDemo() {
  return (
    <div className="w-full max-w-2xl">
      <MasonryLightbox items={items} sizes="(min-width: 640px) 220px, 50vw" />
    </div>
  );
}

Props

PropTypeDefault
items*

Photos: src, alt, width, height, and optional thumb, thumbSrcSet, caption.

MasonryLightboxItem[]—
label

Accessible name for the grid.

string"Photo gallery"
sizes

sizes attribute for the tile images.

string—
className

Masonry container classes; defaults to columns-2 sm:columns-3.

string—
onOpenChange

Fires with the open index, or null once fully closed.

(index: number | null) => void—

Polish

  • Brand colours, logos and the hover lift removed; the grid and the lightbox use the shadcn palette and dxbh-ui tokens only.
  • FLIP open: the photo starts exactly over its tile (measured before first paint) and springs to its open rect. Close re-measures the tile and returns along the same path, about 15% quicker.
  • The tile hides while its photo is lifted out, so there is only ever one copy on screen.
  • Swipe down to dismiss: 1:1 tracking after a 10px hysteresis, rubber-band upwards, the backdrop fades and the photo shrinks with the pull.
  • Commit or cancel comes from the release velocity's sign and projected rest point, not from the position alone. A dismiss hands the release velocity to the spring, so the photo keeps moving the way it was thrown.
  • Interruptible: grab the photo while it springs back, or tap its tile while it flies home, and it turns around from where it is.
  • One pointer owns the gesture; a second finger is ignored, and a drag never also counts as a backdrop tap.
  • Thick material backdrop (material-regular) in place of a tinted scrim; controls on it are solid tints, never a second translucent layer.
  • Dialog semantics, focus moves to Close, Tab is trapped, Escape closes, focus returns to the tile of the photo you were on.
  • Arrow keys and buttons change photos instantly; the matching tile is kept on screen so closing has somewhere to land. Neighbours are preloaded.
  • Scroll is locked with scrollbar compensation so the grid never shifts sideways.
  • Reduced motion: no flight; the whole layer cross-fades in and out.

Source

masonry-lightbox.tsx
"use client";

import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type MouseEvent as ReactMouseEvent,
  type PointerEvent as ReactPointerEvent,
  type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import { ChevronLeft, ChevronRight, X } from "lucide-react";
import { prefersReducedMotion } from "@/hooks/use-reduced-motion";
import { releaseVelocity } from "@/hooks/use-snap-track";
import { createSpring, project, rubberband, type Spring } from "@/lib/spring";
import { cn } from "@/lib/utils";

export type MasonryLightboxItem = {
  /** Full-size image shown in the lightbox. */
  src: string;
  /** Describes the photo. Names the tile and the lightbox image. */
  alt: string;
  /** Intrinsic size. Sets the tile's aspect ratio; the lightbox never upscales past it. */
  width: number;
  height: number;
  /** Smaller image for the tile, shown in the lightbox until `src` loads. */
  thumb?: string;
  thumbSrcSet?: string;
  /** Shown under the open photo. */
  caption?: ReactNode;
};

export type MasonryLightboxProps = {
  items: MasonryLightboxItem[];
  /** Accessible name for the gallery. */
  label?: string;
  /** `sizes` for the tile images. */
  sizes?: string;
  /** Class names for the masonry container (column count, gap). */
  className?: string;
  /** Fires with the open index, or null once the lightbox has fully closed. */
  onOpenChange?: (index: number | null) => void;
};

type Rect = { left: number; top: number; width: number; height: number };
type Drag = { id: number; startX: number; startY: number; origin: number; dragging: boolean; history: { x: number; t: number }[] };

const TOP_BAR = 56;
const BOTTOM_BAR = 72;

/** Where the open photo sits: centred between the bars, never upscaled. */
export function fitRect(width: number, height: number, vw: number, vh: number): Rect {
  const padX = vw >= 640 ? 48 : 12;
  const boxW = Math.max(1, vw - padX * 2);
  const boxH = Math.max(1, vh - TOP_BAR - BOTTOM_BAR);
  const s = Math.min(boxW / width, boxH / height, 1);
  const w = width * s;
  const h = height * s;
  return { left: (vw - w) / 2, top: TOP_BAR + (boxH - h) / 2, width: w, height: h };
}

/** Swipe-down dismissal: a downward flick commits, an upward one cancels, a slow release goes by distance. */
export function shouldDismiss(offset: number, velocity: number, threshold = 120) {
  if (velocity < -100) return false;
  return offset + project(Math.max(0, velocity)) > threshold;
}

const FOCUSABLE = 'button:not([disabled]), [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';

const control =
  "pointer-events-auto inline-flex size-10 cursor-pointer items-center justify-center rounded-full bg-foreground/10 text-foreground outline-none " +
  "transition-transform duration-(--duration-press,120ms) ease-out active:scale-[0.97] " +
  "hover:bg-foreground/15 focus-visible:ring-2 focus-visible:ring-ring/50 [&>svg]:size-5";

/**
 * A masonry grid of photos that open into a lightbox. The photo grows out of
 * its tile and returns along the same path; swipe it down to dismiss.
 */
export function MasonryLightbox({ items, label = "Photo gallery", sizes, className, onOpenChange }: MasonryLightboxProps) {
  const [open, setOpen] = useState<number | null>(null);
  const [closing, setClosing] = useState(false);
  const [viewport, setViewport] = useState({ w: 1024, h: 768 });
  const [loaded, setLoaded] = useState<string | null>(null);

  const tiles = useRef<(HTMLButtonElement | null)[]>([]);
  const rootRef = useRef<HTMLDivElement>(null);
  const frameRef = useRef<HTMLDivElement>(null);
  const backdropRef = useRef<HTMLDivElement>(null);
  const chromeRef = useRef<HTMLDivElement>(null);
  const closeRef = useRef<HTMLButtonElement>(null);

  const progress = useRef<Spring | null>(null); // 0 = on the tile, 1 = open
  const offset = useRef<Spring | null>(null); // swipe-down offset in px
  const geo = useRef({ dx: 0, dy: 0, s: 1 });
  const drag = useRef<Drag | null>(null);
  const suppressClick = useRef(false);
  const opening = useRef(false);
  const closingRef = useRef(false);
  const openRef = useRef<number | null>(null);
  const fadeTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
  const onOpenChangeRef = useRef(onOpenChange);
  useEffect(() => {
    onOpenChangeRef.current = onOpenChange;
    openRef.current = open;
  });

  // One transform for the whole journey: interpolate from the tile's rect to
  // the open rect by `progress`, then add the drag offset on top.
  const paint = useCallback(() => {
    const frame = frameRef.current;
    if (!frame) return;
    const p = progress.current?.value ?? 1;
    const y = offset.current?.value ?? 0;
    const vh = typeof window === "undefined" ? 800 : window.innerHeight || 800;
    const pull = Math.min(Math.max(y, 0) / vh, 1);
    const { dx, dy, s } = geo.current;
    const scale = (s + (1 - s) * p) * (1 - pull * 0.3);
    frame.style.transform = `translate3d(${dx * (1 - p)}px, ${dy * (1 - p) + y}px, 0) scale(${scale})`;
    const opacity = String(Math.min(1, Math.max(0, p)) * (1 - Math.min(pull * 2.5, 1)));
    if (backdropRef.current) backdropRef.current.style.opacity = opacity;
    if (chromeRef.current) chromeRef.current.style.opacity = opacity;
  }, []);

  const finish = useCallback(() => {
    clearTimeout(fadeTimer.current);
    const index = openRef.current;
    closingRef.current = false;
    setClosing(false);
    setOpen(null);
    setLoaded(null);
    if (index !== null) tiles.current[index]?.focus({ preventScroll: true });
    onOpenChangeRef.current?.(null);
  }, []);

  useEffect(() => {
    const settle = () => {
      paint();
      const p = progress.current;
      const o = offset.current;
      if (closingRef.current && p && o && !p.animating && !o.animating && p.value === 0) finish();
    };
    progress.current = createSpring(settle, { reducedMotion: prefersReducedMotion });
    offset.current = createSpring(settle, { reducedMotion: prefersReducedMotion });
    progress.current.set(1);
    return () => {
      progress.current?.stop();
      offset.current?.stop();
      clearTimeout(fadeTimer.current);
    };
  }, [paint, finish]);

  // Measure the tile against the open rect; the tile may have moved since.
  const measure = useCallback(
    (index: number) => {
      const tile = tiles.current[index];
      const item = items[index];
      if (!tile || !item) return;
      const r = tile.getBoundingClientRect();
      const f = fitRect(item.width, item.height, window.innerWidth, window.innerHeight);
      geo.current =
        r.width > 0 && f.width > 0
          ? {
              dx: r.left + r.width / 2 - (f.left + f.width / 2),
              dy: r.top + r.height / 2 - (f.top + f.height / 2),
              s: r.width / f.width,
            }
          : { dx: 0, dy: 0, s: 1 };
    },
    [items],
  );

  const openAt = (index: number) => {
    if (closingRef.current) {
      if (index === open) {
        // Grabbed again on its way home: turn around from where it is.
        clearTimeout(fadeTimer.current);
        closingRef.current = false;
        setClosing(false);
        progress.current?.to(1, { response: 0.35 });
        offset.current?.to(0, { response: 0.35 });
        return;
      }
      finish();
    }
    opening.current = true;
    setViewport({ w: window.innerWidth, h: window.innerHeight });
    setOpen(index);
    onOpenChangeRef.current?.(index);
  };

  const close = useCallback(
    (velocity = 0) => {
      if (openRef.current === null || closingRef.current) return;
      closingRef.current = true;
      setClosing(true);
      if (prefersReducedMotion()) {
        // Gentler, not none: the whole layer fades out in place.
        fadeTimer.current = setTimeout(finish, 200);
        return;
      }
      measure(openRef.current);
      // Same path home, a little quicker than the way out.
      progress.current?.to(0, { damping: 1, response: 0.3 });
      offset.current?.to(0, { damping: 1, response: 0.3, velocity });
    },
    [finish, measure],
  );

  const step = useCallback(
    (delta: number) => {
      if (openRef.current === null || closingRef.current || items.length < 2) return;
      const next = (openRef.current + delta + items.length) % items.length;
      // Keep the matching tile on screen so closing has somewhere to land.
      tiles.current[next]?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
      setOpen(next);
      onOpenChangeRef.current?.(next);
    },
    [items.length],
  );

  // Opening: start the frame exactly over the tile, before the first paint.
  useLayoutEffect(() => {
    if (open === null || !opening.current) return;
    opening.current = false;
    offset.current?.set(0);
    if (prefersReducedMotion()) {
      progress.current?.set(1);
    } else {
      measure(open);
      progress.current?.set(0);
      progress.current?.to(1, { damping: 1, response: 0.35 });
    }
    closeRef.current?.focus({ preventScroll: true });
  }, [open, measure]);

  // Scroll lock while the lightbox is up, without the page shifting sideways.
  const isOpen = open !== null;
  useLayoutEffect(() => {
    if (!isOpen) return;
    const body = document.body;
    const prev = { overflow: body.style.overflow, paddingRight: body.style.paddingRight };
    const bar = window.innerWidth - document.documentElement.clientWidth;
    body.style.overflow = "hidden";
    if (bar > 0) body.style.paddingRight = `${bar}px`;
    const onResize = () => setViewport({ w: window.innerWidth, h: window.innerHeight });
    window.addEventListener("resize", onResize);
    return () => {
      body.style.overflow = prev.overflow;
      body.style.paddingRight = prev.paddingRight;
      window.removeEventListener("resize", onResize);
    };
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") close();
      else if (e.key === "ArrowLeft") step(-1);
      else if (e.key === "ArrowRight") step(1);
      else return;
      e.preventDefault();
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [isOpen, close, step]);

  // Warm the neighbours so arrowing through feels instant.
  useEffect(() => {
    if (open === null || items.length < 2) return;
    for (const delta of [1, -1]) new Image().src = items[(open + delta + items.length) % items.length].src;
  }, [open, items]);

  // Keep Tab inside the dialog.
  const onDialogKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {
    if (e.key !== "Tab" || !rootRef.current) return;
    const nodes = Array.from(rootRef.current.querySelectorAll<HTMLElement>(FOCUSABLE));
    if (nodes.length === 0) return;
    const first = nodes[0];
    const last = nodes[nodes.length - 1];
    if (e.shiftKey && (document.activeElement === first || !rootRef.current.contains(document.activeElement))) {
      e.preventDefault();
      last.focus();
    } else if (!e.shiftKey && document.activeElement === last) {
      e.preventDefault();
      first.focus();
    }
  };

  // Swipe-down to dismiss: 1:1 tracking after a 10px hysteresis, one pointer only.
  const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
    if (e.button !== 0 || drag.current || closingRef.current) return;
    // Catch it mid-flight: stop where it is on screen.
    offset.current?.set(offset.current.value);
    suppressClick.current = false;
    drag.current = { id: e.pointerId, startX: e.clientX, startY: e.clientY, origin: offset.current?.value ?? 0, dragging: false, history: [] };
  };

  const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
    const d = drag.current;
    if (!d || e.pointerId !== d.id) return;
    if (!d.dragging) {
      const dx = e.clientX - d.startX;
      const dy = e.clientY - d.startY;
      if (Math.abs(dx) > 10 && Math.abs(dx) > Math.abs(dy)) {
        drag.current = null; // sideways: not a dismiss
        return;
      }
      if (Math.abs(dy) < 10) return;
      d.dragging = true;
      d.startY = e.clientY;
      suppressClick.current = true;
      try {
        e.currentTarget.setPointerCapture(e.pointerId);
      } catch {
        // The pointer already ended; tracking works without capture.
      }
    }
    const raw = d.origin + (e.clientY - d.startY);
    // Down follows the finger; up resists, since there is nothing up there.
    offset.current?.set(raw >= 0 ? raw : -rubberband(-raw, window.innerHeight || 800));
    d.history.push({ x: e.clientY, t: e.timeStamp });
    if (d.history.length > 8) d.history.shift();
  };

  const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {
    const d = drag.current;
    if (!d || e.pointerId !== d.id) return;
    drag.current = null;
    if (!d.dragging || !offset.current) return;
    const velocity = releaseVelocity(d.history, e.timeStamp);
    if (shouldDismiss(offset.current.value, velocity)) close(velocity);
    else offset.current.to(0, { velocity, damping: Math.abs(velocity) > 400 ? 0.8 : 1, response: 0.35 });
  };

  const onStageClick = (e: ReactMouseEvent<HTMLDivElement>) => {
    if (suppressClick.current) {
      suppressClick.current = false;
      return;
    }
    // A tap on the backdrop closes; a tap on the photo does not.
    if (!frameRef.current?.contains(e.target as Node)) close();
  };

  const current = open !== null ? items[open] : null;
  const rect = current ? fitRect(current.width, current.height, viewport.w, viewport.h) : null;
  const reduced = typeof window !== "undefined" && prefersReducedMotion();

  return (
    <>
      <div role="list" aria-label={label} className={cn("columns-2 gap-3 sm:columns-3", className)}>
        {items.map((item, i) => (
          <div role="listitem" key={item.src} className="mb-3 break-inside-avoid">
            <button
              ref={(el) => {
                tiles.current[i] = el;
              }}
              type="button"
              aria-haspopup="dialog"
              data-active={open === i || undefined}
              onClick={() => openAt(i)}
              className={cn(
                "block w-full cursor-zoom-in overflow-hidden rounded-lg bg-muted outline-none",
                "transition-transform duration-(--duration-press,120ms) ease-out active:scale-[0.98]",
                "focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background",
                // The photo has lifted out of this tile.
                "data-active:opacity-0",
              )}
              style={{ aspectRatio: `${item.width} / ${item.height}` }}
            >
              <img
                src={item.thumb ?? item.src}
                srcSet={item.thumbSrcSet}
                sizes={sizes}
                alt={item.alt}
                width={item.width}
                height={item.height}
                loading={i < 6 ? "eager" : "lazy"}
                decoding="async"
                draggable={false}
                className="block size-full object-cover"
              />
            </button>
          </div>
        ))}
      </div>

      {current && rect && open !== null
        ? createPortal(
            <div
              ref={rootRef}
              role="dialog"
              aria-modal="true"
              aria-label="Photo viewer"
              data-closing={closing || undefined}
              onKeyDown={onDialogKeyDown}
              className={cn(
                "fixed inset-0 z-50 select-none data-closing:pointer-events-none",
                reduced && "transition-opacity duration-(--duration-modal,240ms) ease-out starting:opacity-0 data-closing:opacity-0 data-closing:duration-200",
              )}
            >
              {/* Thick material: blurs the grid away and stands in for the scrim. */}
              <div ref={backdropRef} aria-hidden="true" className="material-regular absolute inset-0" />

              <div
                className="absolute inset-0 cursor-zoom-out touch-none"
                onPointerDown={onPointerDown}
                onPointerMove={onPointerMove}
                onPointerUp={onPointerUp}
                onPointerCancel={onPointerUp}
                onClick={onStageClick}
              >
                <div
                  ref={frameRef}
                  className="absolute cursor-grab overflow-hidden rounded-xl bg-muted shadow-[0_30px_80px_-20px_rgb(0_0_0/0.45)] will-change-transform active:cursor-grabbing"
                  style={{ left: rect.left, top: rect.top, width: rect.width, height: rect.height }}
                >
                  <img
                    key={`thumb-${current.src}`}
                    src={current.thumb ?? current.src}
                    alt=""
                    aria-hidden="true"
                    draggable={false}
                    className="absolute inset-0 size-full object-cover"
                  />
                  <img
                    key={current.src}
                    src={current.src}
                    alt={current.alt}
                    draggable={false}
                    onLoad={() => setLoaded(current.src)}
                    className={cn(
                      "absolute inset-0 size-full object-cover transition-opacity duration-(--duration-popover,180ms) ease-out",
                      loaded === current.src || !current.thumb ? "opacity-100" : "opacity-0",
                    )}
                  />
                </div>
              </div>

              <div ref={chromeRef} className="pointer-events-none absolute inset-0">
                <div className="absolute inset-x-0 top-0 flex items-center justify-between px-3 sm:px-6" style={{ height: TOP_BAR }}>
                  <span className="text-sm text-muted-foreground tabular-nums">
                    {open + 1} / {items.length}
                  </span>
                  <button ref={closeRef} type="button" className={control} aria-label="Close" onClick={() => close()}>
                    <X />
                  </button>
                </div>
                <div className="absolute inset-x-0 bottom-0 flex items-center gap-3 px-3 sm:px-6" style={{ height: BOTTOM_BAR }}>
                  {items.length > 1 ? (
                    <button type="button" className={control} aria-label="Previous photo" onClick={() => step(-1)}>
                      <ChevronLeft />
                    </button>
                  ) : null}
                  <div className="min-w-0 flex-1 truncate text-center text-sm text-muted-foreground">{current.caption}</div>
                  {items.length > 1 ? (
                    <button type="button" className={control} aria-label="Next photo" onClick={() => step(1)}>
                      <ChevronRight />
                    </button>
                  ) : null}
                </div>
              </div>

              <span role="status" aria-live="polite" className="sr-only">
                {`${current.alt}, photo ${open + 1} of ${items.length}`}
              </span>
            </div>,
            document.body,
          )
        : null}
    </>
  );
}

Extracted from Apricot/src/components/GalleryMasonry.tsx at ec7cef6.