Masonry

A masonry grid of image tiles that animate in from an edge and rearrange smoothly when the layout changes.

pnpm dlx shadcn@latest add @leo/masonry

Props

NameTypeDefaultDescription
animateFromundefined | "bottom" | "top" | "left" | "right" | "center" | "random"bottom
blurToFocusboolean | undefinedtrue
classNamestring | undefined-
colorShiftOnHoverboolean | undefinedfalse
durationnumber | undefined0.6
easestring | undefinedpower3.out
hoverScalenumber | undefined0.95
itemsMasonryItem[] | undefinedDEFAULT_HEIGHTS.map((height, i) => ({ id: `tile-${i + 1}`, img: createTile((i * 47 + 200) % 360, i), height, }))
scaleOnHoverboolean | undefinedtrue
staggernumber | undefined0.05

Dependencies

  • gsap@^3.13.0

Source

"use client";

import { gsap } from "gsap";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { cn } from "@/lib/utils";

const MEDIA_QUERIES = [
  "(min-width:1500px)",
  "(min-width:1000px)",
  "(min-width:600px)",
  "(min-width:400px)",
];
const MEDIA_COLUMNS = [5, 4, 3, 2];

const useMedia = (queries: string[], values: number[], defaultValue: number): number => {
  const get = () => {
    if (typeof window === "undefined") return defaultValue;
    return values[queries.findIndex((q) => matchMedia(q).matches)] ?? defaultValue;
  };

  const [value, setValue] = useState<number>(get);

  // biome-ignore lint/correctness/useExhaustiveDependencies: `get` only reads `queries` and `values`
  useEffect(() => {
    const handler = () => setValue(get);
    for (const q of queries) matchMedia(q).addEventListener("change", handler);
    return () => {
      for (const q of queries) matchMedia(q).removeEventListener("change", handler);
    };
  }, [queries]);

  return value;
};

const useMeasure = <T extends HTMLElement>() => {
  const ref = useRef<T | null>(null);
  const [size, setSize] = useState({ width: 0, height: 0 });

  useLayoutEffect(() => {
    if (!ref.current) return;
    const ro = new ResizeObserver(([entry]) => {
      const { width, height } = entry.contentRect;
      setSize({ width, height });
    });
    ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);

  return [ref, size] as const;
};

// Data URIs decode without a network round trip, so waiting for `Image.onload` only delays the entrance.
const allInline = (items: MasonryItem[]): boolean => items.every((i) => i.img.startsWith("data:"));

const preloadImages = async (urls: string[]): Promise<void> => {
  await Promise.all(
    urls.map(
      (src) =>
        new Promise<void>((resolve) => {
          const img = new Image();
          img.src = src;
          img.onload = img.onerror = () => resolve();
        }),
    ),
  );
};

// Generated artwork so the default tiles load nothing from the network.
function createTile(hue: number, variant: number): string {
  const h2 = (hue + 60) % 360;
  const svg =
    '<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 400 400">' +
    `<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="hsl(${hue} 60% 26%)"/><stop offset="1" stop-color="hsl(${h2} 75% 58%)"/></linearGradient></defs>` +
    '<rect width="400" height="400" fill="url(#g)"/>' +
    `<circle cx="${110 + ((variant * 83) % 190)}" cy="${110 + ((variant * 47) % 70)}" r="${44 + (variant % 3) * 14}" fill="hsl(${h2} 90% 86%)" fill-opacity="0.85"/>` +
    `<path d="M0 300 Q120 ${210 + (variant % 4) * 12} 230 290 T400 270 V400 H0Z" fill="hsl(${hue} 45% 14%)" fill-opacity="0.8"/>` +
    "</svg>";
  return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
}

export interface MasonryItem {
  id: string;
  img: string;
  url?: string;
  height: number;
}

interface GridItem extends MasonryItem {
  x: number;
  y: number;
  w: number;
  h: number;
}

export interface MasonryProps {
  items?: MasonryItem[];
  ease?: string;
  duration?: number;
  stagger?: number;
  animateFrom?: "bottom" | "top" | "left" | "right" | "center" | "random";
  scaleOnHover?: boolean;
  hoverScale?: number;
  blurToFocus?: boolean;
  colorShiftOnHover?: boolean;
  className?: string;
}

const DEFAULT_HEIGHTS = [400, 300, 500, 340, 460, 300, 380, 520, 320, 440, 360, 300];
const DEFAULT_ITEMS: MasonryItem[] = DEFAULT_HEIGHTS.map((height, i) => ({
  id: `tile-${i + 1}`,
  img: createTile((i * 47 + 200) % 360, i),
  height,
}));

const Masonry = ({
  items = DEFAULT_ITEMS,
  ease = "power3.out",
  duration = 0.6,
  stagger = 0.05,
  animateFrom = "bottom",
  scaleOnHover = true,
  hoverScale = 0.95,
  blurToFocus = true,
  colorShiftOnHover = false,
  className,
}: MasonryProps) => {
  const columns = useMedia(MEDIA_QUERIES, MEDIA_COLUMNS, 1);

  const [containerRef, { width }] = useMeasure<HTMLDivElement>();
  const [imagesReady, setImagesReady] = useState(() => allInline(items));

  const getInitialPosition = (item: GridItem) => {
    const containerRect = containerRef.current?.getBoundingClientRect();
    if (!containerRect) return { x: item.x, y: item.y };

    let direction = animateFrom;
    if (animateFrom === "random") {
      const dirs = ["top", "bottom", "left", "right"];
      direction = dirs[Math.floor(Math.random() * dirs.length)] as typeof animateFrom;
    }

    switch (direction) {
      case "top":
        return { x: item.x, y: -200 };
      case "bottom":
        return { x: item.x, y: window.innerHeight + 200 };
      case "left":
        return { x: -200, y: item.y };
      case "right":
        return { x: window.innerWidth + 200, y: item.y };
      case "center":
        return {
          x: containerRect.width / 2 - item.w / 2,
          y: containerRect.height / 2 - item.h / 2,
        };
      default:
        return { x: item.x, y: item.y + 100 };
    }
  };

  useEffect(() => {
    if (allInline(items)) {
      setImagesReady(true);
      return;
    }
    let cancelled = false;
    setImagesReady(false);
    preloadImages(items.map((i) => i.img)).then(() => {
      if (!cancelled) setImagesReady(true);
    });
    return () => {
      cancelled = true;
    };
  }, [items]);

  // Tweens are scoped to this container, so two masonries sharing item ids do not animate each other.
  useEffect(() => {
    const root = containerRef.current;
    return () => {
      if (root) gsap.killTweensOf(root.querySelectorAll("[data-key]"));
    };
  }, [containerRef]);

  const grid = useMemo<GridItem[]>(() => {
    if (!width) return [];
    const colHeights = new Array(columns).fill(0);
    const gap = 16;
    const totalGaps = (columns - 1) * gap;
    const columnWidth = (width - totalGaps) / columns;

    return items.map((child) => {
      const col = colHeights.indexOf(Math.min(...colHeights));
      const x = col * (columnWidth + gap);
      const height = child.height / 2;
      const y = colHeights[col];

      colHeights[col] += height + gap;
      return { ...child, x, y, w: columnWidth, h: height };
    });
  }, [columns, items, width]);

  const hasMounted = useRef(false);

  // biome-ignore lint/correctness/useExhaustiveDependencies: re-runs on the layout inputs only; `getInitialPosition` closes over `animateFrom`, which is listed
  useLayoutEffect(() => {
    const root = containerRef.current;
    if (!imagesReady || !root) return;

    grid.forEach((item, index) => {
      const target = Array.from(root.querySelectorAll<HTMLElement>("[data-key]")).find(
        (el) => el.dataset.key === item.id,
      );
      if (!target) return;
      const animProps = { x: item.x, y: item.y, width: item.w, height: item.h };

      if (!hasMounted.current) {
        const start = getInitialPosition(item);
        gsap.fromTo(
          target,
          {
            opacity: 0,
            x: start.x,
            y: start.y,
            width: item.w,
            height: item.h,
            ...(blurToFocus && { filter: "blur(10px)" }),
          },
          {
            opacity: 1,
            ...animProps,
            ...(blurToFocus && { filter: "blur(0px)" }),
            duration: 0.8,
            ease: "power3.out",
            delay: index * stagger,
          },
        );
      } else {
        gsap.to(target, {
          ...animProps,
          duration,
          ease,
          overwrite: "auto",
        });
      }
    });

    hasMounted.current = true;
  }, [grid, imagesReady, stagger, animateFrom, blurToFocus, duration, ease]);

  const handleMouseEnter = (element: HTMLElement) => {
    if (scaleOnHover) {
      gsap.to(element, {
        scale: hoverScale,
        duration: 0.3,
        ease: "power2.out",
      });
    }
    if (colorShiftOnHover) {
      const overlay = element.querySelector(".color-overlay") as HTMLElement;
      if (overlay) gsap.to(overlay, { opacity: 0.3, duration: 0.3 });
    }
  };

  const handleMouseLeave = (element: HTMLElement) => {
    if (scaleOnHover) {
      gsap.to(element, {
        scale: 1,
        duration: 0.3,
        ease: "power2.out",
      });
    }
    if (colorShiftOnHover) {
      const overlay = element.querySelector(".color-overlay") as HTMLElement;
      if (overlay) gsap.to(overlay, { opacity: 0, duration: 0.3 });
    }
  };

  return (
    <div ref={containerRef} className={cn("relative w-full h-full", className)}>
      {grid.map((item) => (
        // biome-ignore lint/a11y/noStaticElementInteractions: tiles are decorative pointer targets, as upstream
        // biome-ignore lint/a11y/useKeyWithClickEvents: tiles are decorative pointer targets, as upstream
        <div
          key={item.id}
          data-key={item.id}
          className={cn("absolute box-content", item.url && "cursor-pointer")}
          style={{ willChange: "transform, width, height, opacity" }}
          onClick={() => item.url && window.open(item.url, "_blank", "noopener")}
          onMouseEnter={(e) => handleMouseEnter(e.currentTarget)}
          onMouseLeave={(e) => handleMouseLeave(e.currentTarget)}
        >
          <div
            className="relative w-full h-full bg-cover bg-center rounded-[10px] shadow-[0px_10px_50px_-10px_rgba(0,0,0,0.2)] uppercase text-[10px] leading-[10px]"
            style={{ backgroundImage: `url("${item.img}")` }}
          >
            {colorShiftOnHover && (
              <div className="color-overlay absolute inset-0 rounded-[10px] bg-gradient-to-tr from-pink-500/50 to-sky-500/50 opacity-0 pointer-events-none" />
            )}
          </div>
        </div>
      ))}
    </div>
  );
};

export { Masonry };
export default Masonry;