# Integrate `Masonry` from Motion Garden

You are helping me add the **Masonry** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** Masonry
- **Category:** Power-User Systems
- **Summary:** A Pinterest-style grid where every item drops into the shortest column, packed by measurement rather than by a shared row baseline.
- **Reference:** https://motion-garden.netlify.app/components/masonry
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add clsx tailwind-merge
```

## Files to create

2 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/masonry/masonry.tsx`

```tsx
"use client";

import {
  Children,
  isValidElement,
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type ReactNode,
} from "react";
import { cn } from "@/lib/utils";

export interface MasonryProps {
  children?: ReactNode;
  className?: string;
  minColumnWidth?: number;
  maxColumns?: number;
  gap?: number;
  packing?: "balanced" | "sequential";
  transition?: number;
  stagger?: number;
  revealOnScroll?: boolean;
  revealDistance?: number;
  reducedMotion?: boolean;
}

const EPSILON = 0.5;

const EASE = "cubic-bezier(0.22, 1, 0.36, 1)";

const STAGGER_CAP = 6;

const useIsomorphicLayoutEffect =
  typeof window === "undefined" ? useEffect : useLayoutEffect;

export function settleMasonryReveal(el: Element | null | undefined) {
  const inner = el?.closest<HTMLElement>("[data-masonry-item]");
  if (!inner || inner.dataset.revealed) return;
  inner.dataset.revealed = "1";
  inner.style.transition = "none";
  inner.style.opacity = "1";
  inner.style.transform = "translate3d(0, 0, 0)";
}

export default function Masonry({
  children,
  className,
  minColumnWidth = 240,
  maxColumns = 4,
  gap = 16,
  packing = "balanced",
  transition = 320,
  stagger = 45,
  revealOnScroll = true,
  revealDistance = 16,
  reducedMotion = false,
}: MasonryProps) {
  const items = Children.toArray(children);
  const count = items.length;
  const signature = items
    .map((child, i) => (isValidElement(child) ? (child.key ?? i) : i))
    .join("|");

  const containerRef = useRef<HTMLDivElement>(null);
  const wrapRefs = useRef<(HTMLDivElement | null)[]>([]);
  const innerRefs = useRef<(HTMLDivElement | null)[]>([]);
  const frameRef = useRef(0);
  const willChangeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const lastWidth = useRef(-1);
  const packedOnce = useRef(false);

  const [packed, setPacked] = useState(false);

  const tween =
    reducedMotion || transition <= 0
      ? "none"
      : `transform ${transition}ms ${EASE}`;

  const pack = useCallback(
    (animate: boolean) => {
      const el = containerRef.current;
      if (!el) return;

      const width = el.clientWidth;
      if (width <= 0) return;

      const columns = Math.max(
        1,
        Math.min(maxColumns, Math.floor((width + gap) / (minColumnWidth + gap))),
      );
      const colWidth = (width - gap * (columns - 1)) / columns;
      const rtl = getComputedStyle(el).direction === "rtl";
      const wraps = wrapRefs.current;

      for (const w of wraps) {
        if (w) w.style.width = `${colWidth}px`;
      }

      const heights: number[] = [];
      for (const w of wraps) {
        heights.push(w ? w.getBoundingClientRect().height : 0);
      }

      const colHeights = new Array<number>(columns).fill(0);
      for (let i = 0; i < wraps.length; i++) {
        const w = wraps[i];
        if (!w) continue;

        let col = 0;
        if (packing === "sequential") {
          col = i % columns;
        } else {
          for (let c = 1; c < columns; c++) {
            if (colHeights[c] < colHeights[col] - EPSILON) col = c;
          }
        }

        const x = rtl
          ? width - colWidth - col * (colWidth + gap)
          : col * (colWidth + gap);

        w.style.transition = animate ? tween : "none";
        w.style.transform = `translate3d(${x}px, ${colHeights[col]}px, 0)`;
        colHeights[col] += heights[i] + gap;
      }

      const tallest = colHeights.length ? Math.max(...colHeights) : 0;
      el.style.height = `${Math.max(0, tallest - gap)}px`;
      lastWidth.current = width;

      if (animate && tween !== "none") {
        for (const w of wraps) {
          if (w) w.style.willChange = "transform";
        }
        if (willChangeTimer.current) clearTimeout(willChangeTimer.current);
        willChangeTimer.current = setTimeout(() => {
          for (const w of wrapRefs.current) {
            if (w) w.style.willChange = "";
          }
        }, transition + 60);
      }
    },
    [gap, maxColumns, minColumnWidth, packing, transition, tween],
  );

  const schedule = useCallback(() => {
    if (frameRef.current) return;
    frameRef.current = requestAnimationFrame(() => {
      frameRef.current = 0;
      pack(true);
    });
  }, [pack]);

  useIsomorphicLayoutEffect(() => {
    wrapRefs.current.length = count;
    innerRefs.current.length = count;

    if (!packed) {
      setPacked(true);
      return;
    }

    pack(packedOnce.current);
    packedOnce.current = true;
  }, [packed, pack, count, signature]);

  useEffect(() => {
    const el = containerRef.current;
    if (!el || !packed) return;

    const ro = new ResizeObserver((entries) => {
      for (const entry of entries) {
        if (entry.target !== el) {
          schedule();
          return;
        }
        const w = entry.contentRect.width;
        if (Math.abs(w - lastWidth.current) > EPSILON) {
          schedule();
          return;
        }
      }
    });

    ro.observe(el);
    for (const w of wrapRefs.current) {
      if (w) ro.observe(w);
    }

    return () => ro.disconnect();
  }, [packed, schedule, signature]);

  useIsomorphicLayoutEffect(() => {
    if (!packed) return;
    const inners = innerRefs.current;
    const live = revealOnScroll && !reducedMotion && transition > 0;

    if (!live) {
      for (const el of inners) {
        if (!el) continue;
        el.style.opacity = "";
        el.style.transform = "";
        el.style.transition = "";
        el.style.transitionDelay = "";
        delete el.dataset.revealed;
      }
      return;
    }

    for (const el of inners) {
      if (!el) continue;
      if (el.dataset.revealed) {
        el.style.opacity = "1";
        el.style.transform = "translate3d(0, 0, 0)";
        continue;
      }
      el.style.opacity = "0";
      el.style.transform = `translate3d(0, ${revealDistance}px, 0)`;
      el.style.transition = `opacity ${transition}ms ${EASE}, transform ${transition}ms ${EASE}`;
    }

    const io = new IntersectionObserver(
      (entries) => {
        let n = 0;
        for (const entry of entries) {
          if (!entry.isIntersecting) continue;
          const el = entry.target as HTMLDivElement;
          io.unobserve(el);
          if (el.dataset.revealed) continue;
          el.dataset.revealed = "1";
          el.style.transitionDelay = `${Math.min(n, STAGGER_CAP) * stagger}ms`;
          el.style.opacity = "1";
          el.style.transform = "translate3d(0, 0, 0)";
          n++;
        }
      },
      { threshold: 0 },
    );

    for (const el of inners) {
      if (el && !el.dataset.revealed) io.observe(el);
    }

    return () => io.disconnect();
  }, [
    packed,
    revealOnScroll,
    revealDistance,
    reducedMotion,
    transition,
    stagger,
    signature,
  ]);

  useEffect(
    () => () => {
      if (frameRef.current) cancelAnimationFrame(frameRef.current);
      if (willChangeTimer.current) clearTimeout(willChangeTimer.current);
    },
    [],
  );

  return (
    <div
      ref={containerRef}
      className={cn(
        "contain-[layout_style] [overflow-anchor:none]",
        "print:h-auto! print:block!",
        className,
      )}
      style={
        packed
          ? { position: "relative", height: 0 }
          : {
              columnWidth: `${minColumnWidth}px`,
              columnCount: maxColumns,
              columnGap: `${gap}px`,
            }
      }
    >
      {items.map((child, i) => (
        <div
          key={isValidElement(child) ? (child.key ?? i) : i}
          ref={(el) => {
            wrapRefs.current[i] = el;
          }}
          className="print:static! print:w-auto! print:transform-none!"
          style={
            packed
              ? { position: "absolute", top: 0, left: 0 }
              : { breakInside: "avoid", marginBottom: `${gap}px` }
          }
        >
          <div
            data-masonry-item=""
            ref={(el) => {
              innerRefs.current[i] = el;
            }}
          >
            {child}
          </div>
        </div>
      ))}
    </div>
  );
}
```

### 2. `lib/utils.ts` — peer util, required

```tsx
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `minColumnWidth` | `number` | `240` | Target column width. The column count is derived from the container, not the viewport. Range 120–480 px. |
| `maxColumns` | `number` | `4` | Ceiling on the derived column count, however wide the container gets. Range 1–8. |
| `gap` | `number` | `16` | Space between columns and between stacked items. Range 0–48 px. |
| `packing` | `"balanced" | "sequential"` | `"balanced"` | Balanced packs into the shortest column; sequential keeps strict left-to-right order. |
| `transition` | `number` | `320` | How long an item takes to glide to a new slot. 0 snaps. Range 0–800 ms. |
| `stagger` | `number` | `45` | Delay added per item as a batch reveals. Range 0–120 ms. Ignored while `revealOnScroll` is `false`. |
| `revealOnScroll` | `boolean` | `true` | Fade and rise each item in as it enters the viewport. |
| `revealDistance` | `number` | `16` | How far an item rises on reveal. Range 0–64 px. Ignored while `revealOnScroll` is `false`. |

## Usage

```tsx
import Masonry from "@/components/registry/masonry/masonry";

<Masonry
  minColumnWidth={240}
  maxColumns={4}
  gap={16}
  packing="balanced"
  transition={320}
  stagger={45}
  revealOnScroll={true}
  revealDistance={16}
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- `lib/utils.ts` is required, not optional. It exports the `cn` helper the component imports from `@/lib/utils` — keep it at that path, or rewrite every `cn` import to wherever you already keep yours. If your project is shadcn-based you almost certainly have this file already; keep yours and drop mine.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Wire the component into the place I point you at, with sensible props for that context.
4. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
