Hover preview index

An editorial project list with large type rows, each showing a title, category, year and optional index number between hairline rules. Hovering a row brings in a preview card that follows the pointer with a soft lag, crossfades between projects without jumping and tilts slightly with sideways movement, while the active title slides right and the other rows dim. Rows are real links; keyboard focus places the preview beside the focused row. On touch screens each row expands inline to show its image and a link instead. Previews use gradients when no image is given, the card can be clipped to the block, and reduced motion pins the preview without lag or tilt.

MarketingBlockTailwind v4

Source

import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties, type FocusEvent, type PointerEvent } from "react";
import { ArrowUpRight, Plus } from "lucide-react";
import { cn } from "@/lib/utils";

export type IndexItem = {
  title: string;
  meta: string;
  year: string | number;
  href: string;
  /** Decorative preview. Without a src the gradient (or a built-in one) is shown. */
  image?: { src?: string; alt?: string; gradient?: string };
};

export type HoverPreviewIndexProps = {
  items: IndexItem[];
  previewSize?: "sm" | "md" | "lg";
  /** Clip the preview inside the block instead of letting it float over neighbouring content. */
  contained?: boolean;
  numbered?: boolean;
  /** Show this row's preview on mount, anchored beside the row. */
  initialActive?: number;
  className?: string;
};

const SIZES = { sm: 208, md: 288, lg: 368 } as const;
const RATIO = 0.68;
const GAP = 28;

const FALLBACKS = [
  "radial-gradient(120% 90% at 18% 12%, var(--chart-4), transparent 55%), linear-gradient(135deg, var(--chart-1), var(--chart-5))",
  "radial-gradient(100% 80% at 80% 20%, var(--chart-2), transparent 60%), linear-gradient(160deg, var(--chart-3), var(--chart-2))",
  "radial-gradient(90% 90% at 30% 80%, var(--chart-5), transparent 60%), linear-gradient(200deg, var(--chart-4), var(--chart-1))",
  "radial-gradient(120% 100% at 70% 70%, var(--chart-1), transparent 55%), linear-gradient(120deg, var(--chart-3), var(--chart-4))",
  "radial-gradient(100% 90% at 20% 30%, var(--chart-2), transparent 60%), linear-gradient(45deg, var(--chart-5), var(--chart-3))",
];

const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));

function useMedia(query: string) {
  const [matches, setMatches] = useState(false);
  useEffect(() => {
    const list = window.matchMedia(query);
    const update = () => setMatches(list.matches);
    update();
    list.addEventListener("change", update);
    return () => list.removeEventListener("change", update);
  }, [query]);
  return matches;
}

function Art({ item, index, className, style }: { item: IndexItem; index: number; className?: string; style?: CSSProperties }) {
  const gradient = item.image?.gradient || FALLBACKS[index % FALLBACKS.length];
  return (
    <div className={cn("absolute inset-0", className)} style={style}>
      {item.image?.src ? (
        <img src={item.image.src} alt={item.image.alt || ""} className="size-full object-cover" draggable={false} />
      ) : (
        <div className="relative size-full" style={{ background: gradient }}>
          <div className="absolute -bottom-1/4 -right-1/4 size-3/4 rounded-full border border-white/25" />
          <div className="absolute -bottom-[10%] -right-[10%] size-1/2 rounded-full border border-white/20" />
          <div className="absolute inset-0 bg-[linear-gradient(to_top,rgb(0_0_0/0.28),transparent_55%)]" />
          <span className="absolute bottom-3 left-3.5 text-[11px] font-medium uppercase tracking-[0.14em] text-white/90">{item.meta}</span>
        </div>
      )}
    </div>
  );
}

export function HoverPreviewIndex({ items, previewSize = "md", contained = false, numbered = true, initialActive, className }: HoverPreviewIndexProps) {
  const touch = useMedia("(hover: none)");
  const reduced = useMedia("(prefers-reduced-motion: reduce)");
  const rootRef = useRef<HTMLDivElement>(null);
  const cardRef = useRef<HTMLDivElement>(null);
  const innerRef = useRef<HTMLDivElement>(null);
  const titleRefs = useRef<(HTMLSpanElement | null)[]>([]);
  const rowRefs = useRef<(HTMLAnchorElement | null)[]>([]);
  const target = useRef({ x: 0, y: 0 });
  const current = useRef({ x: 0, y: 0 });
  const tilt = useRef(0);
  const frame = useRef(0);
  const pointerInside = useRef(false);
  const visibleRef = useRef(false);
  const tilting = useRef(false);
  const reducedRef = useRef(reduced);
  reducedRef.current = reduced;

  const [width, setWidth] = useState<number>(SIZES[previewSize]);
  const [active, setActive] = useState<number>(initialActive ?? 0);
  const [visible, setVisible] = useState(initialActive != null);
  const [expanded, setExpanded] = useState<number | null>(initialActive ?? null);
  visibleRef.current = visible;
  const height = Math.round(width * RATIO);

  const uid = useId();

  useLayoutEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const resize = () => setWidth(Math.round(Math.min(SIZES[previewSize], root.clientWidth * 0.62)));
    resize();
    const observer = new ResizeObserver(resize);
    observer.observe(root);
    return () => observer.disconnect();
  }, [previewSize]);

  const paint = useCallback(() => {
    const { x, y } = current.current;
    if (cardRef.current) cardRef.current.style.transform = `translate3d(${x}px, ${y}px, 0)`;
    if (innerRef.current) innerRef.current.style.rotate = `${tilt.current.toFixed(2)}deg`;
  }, []);

  const tick = useCallback(() => {
    const still = reducedRef.current;
    const c = current.current;
    const t = target.current;
    const dx = t.x - c.x;
    const dy = t.y - c.y;
    const ease = still ? 1 : 0.14;
    c.x += dx * ease;
    c.y += dy * ease;
    const wanted = still || !tilting.current ? 0 : clamp(dx * 0.05, -6, 6);
    tilt.current += (wanted - tilt.current) * 0.18;
    paint();
    if (Math.abs(dx) > 0.2 || Math.abs(dy) > 0.2 || Math.abs(tilt.current) > 0.03) frame.current = requestAnimationFrame(tick);
    else frame.current = 0;
  }, [paint]);

  const start = useCallback(() => {
    if (!frame.current) frame.current = requestAnimationFrame(tick);
  }, [tick]);

  useEffect(() => () => cancelAnimationFrame(frame.current), []);

  /** Moves the card; when it is hidden it jumps there so it never flies in from the last spot. */
  const moveTo = useCallback((x: number, y: number, snap = false) => {
    target.current = { x, y };
    if (snap || !visibleRef.current || reducedRef.current) {
      current.current = { x, y };
      tilt.current = 0;
      paint();
    } else start();
  }, [paint, start]);

  /** Places the card beside a row (keyboard focus, reduced motion, initial state). It never tilts there. */
  const anchorTo = useCallback((index: number, snap = false) => {
    tilting.current = false;
    const root = rootRef.current;
    const row = rowRefs.current[index];
    const title = titleRefs.current[index];
    if (!root || !row) return;
    const box = root.getBoundingClientRect();
    const rowBox = row.getBoundingClientRect();
    const titleRight = title ? title.getBoundingClientRect().right - box.left : box.width / 2;
    // Beside the title when it fits, otherwise tucked under the row on the right so the title stays readable.
    if (titleRight + GAP + width <= box.width) moveTo(titleRight + GAP, rowBox.top - box.top + rowBox.height / 2 - height / 2, snap);
    else moveTo(Math.max(0, box.width - width), rowBox.bottom - box.top + 8, snap);
  }, [height, moveTo, width]);

  useLayoutEffect(() => {
    if (initialActive == null || touch || pointerInside.current) return;
    anchorTo(initialActive, true);
    setVisible(true);
    // Runs once the preview width is known.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [width, touch]);

  const followPointer = (event: PointerEvent) => {
    if (event.pointerType === "touch" || !rootRef.current) return;
    if (reducedRef.current) return;
    tilting.current = true;
    const box = rootRef.current.getBoundingClientRect();
    const px = event.clientX - box.left;
    const py = event.clientY - box.top;
    let x = px + GAP;
    if (x + width > box.width) x = px - GAP - width;
    moveTo(clamp(x, 0, Math.max(0, box.width - width)), py - height / 2);
  };

  const enterRow = (index: number, event: PointerEvent) => {
    if (event.pointerType === "touch") return;
    pointerInside.current = true;
    setActive(index);
    if (reducedRef.current) anchorTo(index);
    else followPointer(event);
    setVisible(true);
  };

  const leaveList = () => {
    // A leave without an enter (a page load under a resting pointer) leaves the initial preview alone.
    if (!pointerInside.current) return;
    pointerInside.current = false;
    if (!rootRef.current?.contains(document.activeElement)) setVisible(false);
  };

  const focusRow = (index: number) => {
    setActive(index);
    anchorTo(index);
    setVisible(true);
  };

  const blurList = (event: FocusEvent) => {
    if (!event.currentTarget.contains(event.relatedTarget as Node) && !pointerInside.current) setVisible(false);
  };

  const current_ = visible ? active : null;
  const number = (index: number) => String(index + 1).padStart(2, "0");

  if (touch) {
    return (
      <div className={cn("w-full", className)}>
        <ul className="border-t border-border">
          {items.map((item, index) => {
            const open = expanded === index;
            const panelId = `${uid}-panel-${index}`;
            return (
              <li key={item.href + index} className="border-b border-border">
                <button
                  type="button"
                  aria-expanded={open}
                  aria-controls={panelId}
                  onClick={() => setExpanded(open ? null : index)}
                  className="flex w-full items-baseline gap-3 py-5 text-left outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
                >
                  {numbered && <span aria-hidden="true" className="w-6 shrink-0 font-mono text-xs tabular-nums text-muted-foreground">{number(index)}</span>}
                  <span className="min-w-0 flex-1">
                    <span className="block text-2xl font-medium leading-tight tracking-tight text-foreground">{item.title}</span>
                    <span className="mt-1 block text-xs uppercase tracking-[0.12em] text-muted-foreground">{item.meta} · {item.year}</span>
                  </span>
                  <Plus aria-hidden="true" className={cn("size-4 shrink-0 self-center text-muted-foreground motion-safe:transition-transform", open && "rotate-45")} />
                </button>
                <div id={panelId} className={cn("grid motion-safe:transition-[grid-template-rows] motion-safe:duration-300", open ? "grid-rows-[1fr]" : "grid-rows-[0fr]")}>
                  <div className="overflow-hidden" inert={!open}>
                    <div className="pb-5">
                      <div className="relative aspect-[16/10] overflow-hidden rounded-lg border border-border">
                        <Art item={item} index={index} />
                      </div>
                      <a href={item.href} className="mt-3 inline-flex items-center gap-1 rounded-md text-sm font-medium text-foreground underline-offset-4 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring">
                        View project <ArrowUpRight aria-hidden="true" className="size-4" />
                      </a>
                    </div>
                  </div>
                </div>
              </li>
            );
          })}
        </ul>
      </div>
    );
  }

  return (
    <div ref={rootRef} className={cn("relative w-full", contained && "overflow-hidden", className)}>
      <ul className="border-t border-border" onPointerMove={followPointer} onPointerLeave={leaveList} onBlur={blurList}>
        {items.map((item, index) => {
          const dimmed = current_ !== null && current_ !== index;
          const lit = current_ === index;
          return (
            <li key={item.href + index} className={cn("border-b border-border motion-safe:transition-opacity motion-safe:duration-300", dimmed && "opacity-40")}>
              <a
                ref={(node) => { rowRefs.current[index] = node; }}
                href={item.href}
                onPointerEnter={(event) => enterRow(index, event)}
                onFocus={() => focusRow(index)}
                className="grid grid-cols-[auto_1fr] items-baseline gap-x-4 gap-y-1 py-5 outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring sm:grid-cols-[auto_1fr_auto_auto] sm:gap-x-8 sm:py-7"
              >
                <span aria-hidden="true" className={cn("w-6 font-mono text-xs tabular-nums text-muted-foreground", !numbered && "invisible w-0")}>{numbered ? number(index) : ""}</span>
                <span className="min-w-0">
                  <span
                    ref={(node) => { titleRefs.current[index] = node; }}
                    className={cn(
                      "inline-block text-[clamp(1.6rem,4.6vw,3.4rem)] font-medium leading-[1.05] tracking-tight text-foreground motion-safe:transition-transform motion-safe:duration-500 motion-safe:ease-[cubic-bezier(.2,.7,.2,1)]",
                      lit && "translate-x-2",
                    )}
                  >
                    {item.title}
                  </span>
                </span>
                <span className="col-start-2 text-xs uppercase tracking-[0.12em] text-muted-foreground sm:col-start-auto">{item.meta}</span>
                <span className="col-start-2 hidden font-mono text-xs tabular-nums text-muted-foreground sm:col-start-auto sm:block">{item.year}</span>
              </a>
            </li>
          );
        })}
      </ul>

      <div ref={cardRef} aria-hidden="true" className="pointer-events-none absolute left-0 top-0 z-20 will-change-transform" style={{ width, height }}>
        <div
          ref={innerRef}
          className={cn(
            "relative size-full overflow-hidden rounded-xl border border-border bg-card shadow-[0_24px_60px_-20px_rgb(0_0_0/0.45)] transition-opacity duration-300 motion-safe:transition-[opacity,scale] motion-safe:duration-[300ms,450ms] motion-safe:ease-[cubic-bezier(.2,.8,.2,1)]",
            visible ? "scale-100 opacity-100" : "opacity-0 motion-safe:scale-50",
          )}
        >
          {items.map((item, index) => (
            <Art key={index} item={{ ...item, image: item.image && { ...item.image, alt: "" } }} index={index} className={cn("transition-opacity duration-300", index === active ? "opacity-100" : "opacity-0")} />
          ))}
        </div>
      </div>
    </div>
  );
}