Card expand dialog

A preview card that grows into a centred dialog and shrinks back into place. The dialog opens out of the card's rectangle while the shared image and title travel and resize to their dialog positions, and the rest of the dialog fades in a beat later. Closing shrinks back into wherever the card is now, even after the page scrolled. On touch the dialog can be dragged down to close with the backdrop fading, and gallery mode adds previous and next controls plus arrow keys to move between cards. Built from small parts (CardExpand, Item, Trigger, Content, Image, Title, Description, Close). The dialog is modal and labelled by its title, focus moves to Close and stays inside, Escape closes, focus returns to the card and the page behind is inert. Reduced motion uses a plain fade.

Modals & overlaysComponentTailwind v4

Source

"use client";

import {
  createContext, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState,
  type ButtonHTMLAttributes, type HTMLAttributes, type KeyboardEvent as ReactKeyboardEvent,
  type PointerEvent as ReactPointerEvent, type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import { ChevronLeft, ChevronRight, X } from "lucide-react";
import { cn } from "@/lib/utils";

/* A card that grows into a dialog and shrinks back into place.
   Opening: the panel is rendered at its final size and clipped to the card's rectangle, then the clip opens out while
   the shared parts (image, title) travel from their card positions to their dialog positions. Everything else in the
   dialog fades in a beat later. Closing runs the same steps backwards toward wherever the card is now. */

const MORPH_MS = 440;
const EASE = "cubic-bezier(.2,.8,.2,1)";
const FOCUSABLE = "a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex='-1'])";

interface RootContext {
  openId: string | null;
  shown: string | null;
  setOpen: (id: string | null) => void;
  go: (delta: number) => void;
  items: string[];
  triggers: Map<string, HTMLElement>;
  lastShown: { current: string | null };
  direction: { current: number };
  finishClose: (id: string) => void;
}

const Root = createContext<RootContext | null>(null);
const Item = createContext<string>("");
const Part = createContext<{ inContent: boolean; titleId: string; descriptionId: string }>({ inContent: false, titleId: "", descriptionId: "" });

function useRoot() {
  const ctx = useContext(Root);
  if (!ctx) throw new Error("CardExpand parts must be used inside <CardExpand>.");
  return ctx;
}

function reducedMotion() {
  return !!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
}

export interface CardExpandProps {
  /** Id of the open item, or null. Leave undefined to let the component manage it. */
  open?: string | null;
  defaultOpen?: string | null;
  onOpenChange?: (id: string | null) => void;
  /** Item ids in order. With more than one, the dialog gets previous/next and the arrow keys move between them. */
  items?: string[];
  children: ReactNode;
}

export function CardExpand({ open, defaultOpen = null, onOpenChange, items = [], children }: CardExpandProps) {
  const [inner, setInner] = useState<string | null>(defaultOpen);
  const openId = open === undefined ? inner : open;
  const [closing, setClosing] = useState<string | null>(null);
  const triggers = useRef(new Map<string, HTMLElement>()).current;
  const lastShown = useRef<string | null>(null);
  const direction = useRef(0);
  const shown = openId ?? closing;

  const setOpen = useCallback((id: string | null) => {
    if (open === undefined) setInner(id);
    onOpenChange?.(id);
  }, [open, onOpenChange]);

  // Remember what was open so a close can play out before the dialog unmounts (updated during render, so the
  // dialog never disappears for a frame).
  const [previous, setPrevious] = useState(openId);
  if (previous !== openId) {
    setPrevious(openId);
    setClosing(openId ? null : previous);
  }

  useEffect(() => {
    lastShown.current = shown;
  }, [shown]);

  const go = useCallback((delta: number) => {
    if (!openId || items.length < 2) return;
    const index = items.indexOf(openId);
    if (index < 0) return;
    direction.current = delta;
    setOpen(items[(index + delta + items.length) % items.length]);
  }, [items, openId, setOpen]);

  const finishClose = useCallback((id: string) => {
    setClosing((current) => (current === id ? null : current));
    lastShown.current = null;
    const trigger = triggers.get(id);
    requestAnimationFrame(() => trigger?.focus({ preventScroll: true }));
  }, [triggers]);

  // While a dialog is up: the page behind is inert and does not scroll.
  const anyShown = shown !== null;
  useEffect(() => {
    if (!anyShown) return;
    const { body } = document;
    const overflow = body.style.overflow;
    body.style.overflow = "hidden";
    const marked: Element[] = [];
    // One level below each page root, so the app's own mount node keeps its attributes untouched.
    for (const top of Array.from(body.children)) {
      if (top.hasAttribute("data-card-expand-layer") || top.tagName === "SCRIPT" || top.tagName === "STYLE") continue;
      const nodes = top.children.length ? Array.from(top.children) : [top];
      for (const node of nodes) {
        if (node.hasAttribute("inert")) continue;
        node.setAttribute("inert", "");
        marked.push(node);
      }
    }
    return () => {
      body.style.overflow = overflow;
      for (const child of marked) child.removeAttribute("inert");
    };
  }, [anyShown]);

  const value = useMemo<RootContext>(
    () => ({ openId, shown, setOpen, go, items, triggers, lastShown, direction, finishClose }),
    [openId, shown, setOpen, go, items, triggers, finishClose],
  );
  return <Root.Provider value={value}>{children}</Root.Provider>;
}

/** Groups one card with its dialog. */
export function CardExpandItem({ id, children }: { id: string; children: ReactNode }) {
  return <Item.Provider value={id}>{children}</Item.Provider>;
}

export function CardExpandTrigger({ className, children, onClick, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) {
  const root = useRoot();
  const id = useContext(Item);
  const hidden = root.shown === id;
  return (
    <Part.Provider value={{ inContent: false, titleId: "", descriptionId: "" }}>
      <button
        {...props}
        type="button"
        ref={(element) => {
          if (element) root.triggers.set(id, element);
          else root.triggers.delete(id);
        }}
        aria-haspopup="dialog"
        aria-expanded={root.openId === id}
        data-card-expand-trigger={id}
        onClick={(event) => {
          onClick?.(event);
          if (!event.defaultPrevented) root.setOpen(id);
        }}
        className={cn(
          "block w-full text-left outline-hidden focus-visible:ring-[3px] focus-visible:ring-ring/50",
          hidden && "opacity-0",
          className,
        )}
      >
        {children}
      </button>
    </Part.Provider>
  );
}

interface SharedProps extends HTMLAttributes<HTMLElement> {
  /** Parts with the same name in the card and the dialog travel between the two. */
  layoutId?: string;
}

export function CardExpandImage({ layoutId = "image", className, ...props }: SharedProps) {
  return <span {...props} aria-hidden="true" data-ce-part={layoutId} className={cn("block", className)} />;
}

export function CardExpandTitle({ layoutId = "title", className, ...props }: SharedProps) {
  const part = useContext(Part);
  if (part.inContent) return <h2 {...props} id={part.titleId} data-ce-part={layoutId} data-ce-text="" className={cn("w-fit", className)} />;
  return <span {...props} data-ce-part={layoutId} data-ce-text="" className={cn("block w-fit", className)} />;
}

export function CardExpandDescription({ className, ...props }: HTMLAttributes<HTMLParagraphElement>) {
  const part = useContext(Part);
  return <p {...props} id={part.inContent ? part.descriptionId : undefined} className={className} />;
}

export function CardExpandClose({ className, children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) {
  const root = useRoot();
  return (
    <button
      {...props}
      type="button"
      data-ce-close=""
      aria-label={children ? undefined : "Close"}
      onClick={() => root.setOpen(null)}
      className={cn(
        "inline-flex size-9 items-center justify-center rounded-full bg-background/80 text-foreground shadow-sm outline-hidden backdrop-blur",
        "hover:bg-background focus-visible:ring-[3px] focus-visible:ring-ring/50",
        className,
      )}
    >
      {children ?? <X aria-hidden="true" className="size-4" />}
    </button>
  );
}

function rectOf(element: Element) {
  return element.getBoundingClientRect();
}

// Elements that only exist in the dialog: everything that is not a shared part and does not contain one.
function fadeTargets(container: Element): HTMLElement[] {
  const out: HTMLElement[] = [];
  for (const child of Array.from(container.children)) {
    if (!(child instanceof HTMLElement) || child.hasAttribute("data-ce-part")) continue;
    if (child.querySelector("[data-ce-part]")) out.push(...fadeTargets(child));
    else out.push(child);
  }
  return out;
}

function sharedPairs(panel: HTMLElement, trigger: HTMLElement | undefined) {
  if (!trigger) return [];
  return Array.from(panel.querySelectorAll<HTMLElement>("[data-ce-part]")).flatMap((to) => {
    const from = trigger.querySelector<HTMLElement>(`[data-ce-part="${to.dataset.cePart}"]`);
    return from ? [{ from, to }] : [];
  });
}

// The transform that puts `to` exactly over `from`. Text scales uniformly by font size so it never stretches.
function inverse(from: HTMLElement, to: HTMLElement) {
  const a = rectOf(from);
  const b = rectOf(to);
  if (to.hasAttribute("data-ce-text")) {
    const scale = parseFloat(getComputedStyle(from).fontSize) / parseFloat(getComputedStyle(to).fontSize) || 1;
    return `translate(${a.left - b.left}px, ${a.top - b.top}px) scale(${scale})`;
  }
  return `translate(${a.left - b.left}px, ${a.top - b.top}px) scale(${a.width / (b.width || 1)}, ${a.height / (b.height || 1)})`;
}

function clipTo(panel: HTMLElement, trigger: HTMLElement) {
  const p = rectOf(panel);
  const c = rectOf(trigger);
  const radius = getComputedStyle(trigger).borderTopLeftRadius || "16px";
  return `inset(${c.top - p.top}px ${p.right - c.right}px ${p.bottom - c.bottom}px ${c.left - p.left}px round ${radius})`;
}

export interface CardExpandContentProps extends HTMLAttributes<HTMLDivElement> {
  /** Accessible name for the previous/next controls in gallery mode. */
  galleryLabel?: string;
}

export function CardExpandContent({ className, children, galleryLabel = "Item", ...props }: CardExpandContentProps) {
  const root = useRoot();
  const id = useContext(Item);
  const uid = useId();
  const [mounted, setMounted] = useState(false);
  const instant = useRef(false);
  useEffect(() => {
    instant.current = root.shown === id;
    setMounted(true);
  }, []);
  if (!mounted || root.shown !== id) return null;
  return (
    <Panel id={id} uid={uid} instant={instant} className={className} galleryLabel={galleryLabel} {...props}>
      {children}
    </Panel>
  );
}

function Panel({ id, uid, instant, className, children, galleryLabel = "Item", ...props }: CardExpandContentProps & { id: string; uid: string; instant: { current: boolean } }) {
  const root = useRoot();
  const panelRef = useRef<HTMLDivElement>(null);
  const backdropRef = useRef<HTMLDivElement>(null);
  const closing = root.openId !== id;
  const titleId = `${uid}-title`;
  const descriptionId = `${uid}-description`;
  const timers = useRef<number[]>([]);
  const swipe = useRef<null | { pointer: number; y: number; dy: number; t: number; active: boolean }>(null);

  const index = root.items.indexOf(id);
  const gallery = root.items.length > 1 && index >= 0;

  const later = (fn: () => void, ms: number) => timers.current.push(window.setTimeout(fn, ms));
  useEffect(() => () => timers.current.forEach(clearTimeout), []);

  // Opening: morph out of the card, or slide in from a neighbour in gallery mode.
  useLayoutEffect(() => {
    const panel = panelRef.current;
    const backdrop = backdropRef.current;
    if (!panel || !backdrop) return;
    const trigger = root.triggers.get(id);
    const fades = fadeTargets(panel);
    const fromNeighbour = root.lastShown.current !== null && root.lastShown.current !== id;
    const all = [panel, backdrop, ...fades, ...sharedPairs(panel, trigger).map((pair) => pair.to)];
    all.forEach((el) => (el.style.transition = "none"));

    if (instant.current) {
      instant.current = false;
      // Open on first paint (e.g. restored from a URL): show it in place without a morph.
      backdrop.style.opacity = "1";
    } else if (reducedMotion() || !trigger) {
      backdrop.style.opacity = fromNeighbour ? "1" : "0";
      panel.style.opacity = "0";
      panel.style.transform = "scale(.98)";
      void panel.offsetWidth;
      backdrop.style.transition = panel.style.transition = "opacity 160ms linear, transform 160ms linear";
      backdrop.style.opacity = "1";
      panel.style.opacity = "1";
      panel.style.transform = "";
    } else if (fromNeighbour) {
      const dir = root.direction.current || 1;
      backdrop.style.opacity = "1";
      panel.style.opacity = "0";
      panel.style.transform = `translateX(${dir * 56}px) scale(.97)`;
      void panel.offsetWidth;
      panel.style.transition = `opacity 260ms ${EASE}, transform 360ms ${EASE}`;
      panel.style.opacity = "1";
      panel.style.transform = "";
    } else {
      const pairs = sharedPairs(panel, trigger);
      panel.style.clipPath = clipTo(panel, trigger);
      backdrop.style.opacity = "0";
      pairs.forEach(({ from, to }) => {
        to.style.transformOrigin = "0 0";
        to.style.transform = inverse(from, to);
      });
      fades.forEach((el) => (el.style.opacity = "0"));
      void panel.offsetWidth;
      panel.style.transition = `clip-path ${MORPH_MS}ms ${EASE}`;
      backdrop.style.transition = `opacity ${MORPH_MS}ms ${EASE}`;
      pairs.forEach(({ to }) => (to.style.transition = `transform ${MORPH_MS}ms ${EASE}`));
      fades.forEach((el) => (el.style.transition = `opacity 260ms ease ${MORPH_MS * 0.45}ms`));
      panel.style.clipPath = "inset(0px 0px 0px 0px round 20px)";
      backdrop.style.opacity = "1";
      pairs.forEach(({ to }) => (to.style.transform = ""));
      fades.forEach((el) => (el.style.opacity = ""));
      later(() => (panel.style.clipPath = ""), MORPH_MS + 20);
    }
    root.direction.current = 0;
    (panel.querySelector<HTMLElement>("[data-ce-close]") ?? panel).focus({ preventScroll: true });
  }, []);

  // Closing: shrink back into wherever the card is now.
  useLayoutEffect(() => {
    if (!closing) return;
    const panel = panelRef.current;
    const backdrop = backdropRef.current;
    const trigger = root.triggers.get(id);
    if (!panel || !backdrop) return;
    timers.current.forEach(clearTimeout);
    const done = () => root.finishClose(id);
    if (reducedMotion() || !trigger) {
      panel.style.transition = backdrop.style.transition = "opacity 140ms linear, transform 140ms linear";
      panel.style.opacity = "0";
      panel.style.transform = `${panel.style.transform || ""} scale(.98)`;
      backdrop.style.opacity = "0";
      later(done, 150);
      return;
    }
    const pairs = sharedPairs(panel, trigger);
    const fades = fadeTargets(panel);
    panel.scrollTop = 0;
    pairs.forEach(({ to }) => {
      to.style.transition = "none";
      to.style.transform = "";
    });
    panel.style.transition = "none";
    panel.style.clipPath = "inset(0px 0px 0px 0px round 20px)";
    const targets = pairs.map(({ from, to }) => inverse(from, to));
    const clip = clipTo(panel, trigger);
    void panel.offsetWidth;
    fades.forEach((el) => {
      el.style.transition = "opacity 120ms linear";
      el.style.opacity = "0";
    });
    panel.style.transition = `clip-path ${MORPH_MS - 60}ms ${EASE}, transform ${MORPH_MS - 60}ms ${EASE}`;
    backdrop.style.transition = `opacity ${MORPH_MS - 60}ms ${EASE}`;
    panel.style.clipPath = clip;
    backdrop.style.opacity = "0";
    pairs.forEach(({ to }, i) => {
      to.style.transformOrigin = "0 0";
      to.style.transition = `transform ${MORPH_MS - 60}ms ${EASE}`;
      to.style.transform = targets[i];
    });
    later(done, MORPH_MS - 40);
  }, [closing]);

  // Keep focus inside while open.
  useEffect(() => {
    if (closing) return;
    function keepInside(event: FocusEvent) {
      const panel = panelRef.current;
      if (panel && event.target instanceof Node && !panel.contains(event.target)) panel.focus({ preventScroll: true });
    }
    document.addEventListener("focusin", keepInside);
    return () => document.removeEventListener("focusin", keepInside);
  }, [closing]);

  function onKeyDown(event: ReactKeyboardEvent<HTMLDivElement>) {
    if (closing) return;
    if (event.key === "Escape") {
      event.preventDefault();
      root.setOpen(null);
    } else if (gallery && (event.key === "ArrowRight" || event.key === "ArrowLeft") && !(event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement)) {
      event.preventDefault();
      root.go(event.key === "ArrowRight" ? 1 : -1);
    } else if (event.key === "Tab" && panelRef.current) {
      const items = Array.from(panelRef.current.querySelectorAll<HTMLElement>(FOCUSABLE));
      if (!items.length) return;
      const first = items[0];
      const last = items[items.length - 1];
      if (event.shiftKey && (document.activeElement === first || document.activeElement === panelRef.current)) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    }
  }

  // Touch: drag the dialog down to close it; the backdrop fades with the finger.
  function onPointerDown(event: ReactPointerEvent<HTMLDivElement>) {
    if (event.pointerType === "mouse" || closing || (panelRef.current?.scrollTop ?? 0) > 0) return;
    swipe.current = { pointer: event.pointerId, y: event.clientY, dy: 0, t: event.timeStamp, active: false };
  }
  function onPointerMove(event: ReactPointerEvent<HTMLDivElement>) {
    const s = swipe.current;
    const panel = panelRef.current;
    if (!s || !panel || s.pointer !== event.pointerId) return;
    const dy = event.clientY - s.y;
    if (!s.active) {
      if (dy < 8) {
        if (dy < -4) swipe.current = null;
        return;
      }
      s.active = true;
      panel.setPointerCapture(event.pointerId);
      panel.style.transition = "none";
    }
    s.dy = Math.max(0, dy);
    panel.style.transform = `translateY(${s.dy}px)`;
    if (backdropRef.current) {
      backdropRef.current.style.transition = "none";
      backdropRef.current.style.opacity = String(Math.max(0.15, 1 - s.dy / 420));
    }
  }
  function onPointerUp(event: ReactPointerEvent<HTMLDivElement>) {
    const s = swipe.current;
    swipe.current = null;
    const panel = panelRef.current;
    if (!s || !s.active || !panel) return;
    const speed = s.dy / Math.max(1, event.timeStamp - s.t);
    if (s.dy > 120 || speed > 0.6) {
      root.setOpen(null);
      return;
    }
    panel.style.transition = `transform 320ms ${EASE}`;
    panel.style.transform = "";
    if (backdropRef.current) {
      backdropRef.current.style.transition = "opacity 200ms ease";
      backdropRef.current.style.opacity = "1";
    }
  }

  return createPortal(
    <div data-card-expand-layer="" className="fixed inset-0 z-50">
      <div
        ref={backdropRef}
        aria-hidden="true"
        onClick={() => root.setOpen(null)}
        className="absolute inset-0 bg-black/45 backdrop-blur-[2px] dark:bg-black/65"
      />
      <div className="pointer-events-none relative flex h-full items-end justify-center p-3 sm:items-center sm:p-6">
        <Part.Provider value={{ inContent: true, titleId, descriptionId }}>
          <div
            {...props}
            ref={panelRef}
            role="dialog"
            aria-modal="true"
            aria-labelledby={titleId}
            aria-describedby={descriptionId}
            tabIndex={-1}
            onKeyDown={onKeyDown}
            onPointerDown={onPointerDown}
            onPointerMove={onPointerMove}
            onPointerUp={onPointerUp}
            onPointerCancel={onPointerUp}
            className={cn(
              "pointer-events-auto relative max-h-[calc(100dvh-1.5rem)] w-full max-w-lg overflow-y-auto overscroll-contain rounded-[20px] bg-card text-card-foreground outline-hidden",
              "shadow-[0_32px_80px_-24px_rgb(0_0_0/0.45)] ring-1 ring-border sm:max-h-[calc(100dvh-3rem)]",
              closing && "pointer-events-none",
              className,
            )}
          >
            {children}
            {gallery && (
              <div className="sticky bottom-0 flex items-center justify-between gap-2 border-t border-border bg-card/95 px-4 py-3 backdrop-blur">
                <button
                  type="button"
                  aria-label={`Previous ${galleryLabel.toLowerCase()}`}
                  onClick={() => root.go(-1)}
                  className="inline-flex size-9 items-center justify-center rounded-full border border-border outline-hidden hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50"
                >
                  <ChevronLeft aria-hidden="true" className="size-4" />
                </button>
                <p className="text-xs tabular-nums text-muted-foreground" aria-live="polite">
                  {galleryLabel} {index + 1} of {root.items.length}
                </p>
                <button
                  type="button"
                  aria-label={`Next ${galleryLabel.toLowerCase()}`}
                  onClick={() => root.go(1)}
                  className="inline-flex size-9 items-center justify-center rounded-full border border-border outline-hidden hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50"
                >
                  <ChevronRight aria-hidden="true" className="size-4" />
                </button>
              </div>
            )}
          </div>
        </Part.Provider>
      </div>
    </div>,
    document.body,
  );
}