{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "masonry-grid",
  "title": "Masonry Grid",
  "author": "AlgorizeTech",
  "description": "A CSS-column masonry layout with staggered entrance animation. Use it for image galleries and card walls of uneven height.",
  "dependencies": [
    "gsap"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "src/components/custom/blocks/MasonryGridBlock.tsx",
      "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\nimport gsap from \"gsap\";\n// gsap/dist: the plain \"gsap/Flip\" path clashes with types/flip.d.ts on case-insensitive file systems.\nimport { Flip } from \"gsap/dist/Flip\";\nimport React, { useLayoutEffect, useRef } from \"react\";\nimport { bezierEase } from \"./gsap-motion\";\nimport { LAYOUT_TRANSITION, springEase } from \"./motion-curves\";\n\nif (typeof window !== \"undefined\") {\n  gsap.registerPlugin(Flip);\n}\n\nexport interface MasonryGridProps<T>\n  extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\"> {\n  items: T[];\n  renderItem: (item: T, index: number) => React.ReactNode;\n  columnsClassName?: string;\n  gapClassName?: string;\n  animateIn?: boolean;\n  staggerDelay?: number;\n}\n\n/** The grid itself fades in over 0.3s on Motion's default opacity curve. */\nconst CONTAINER_EASE = bezierEase([0.25, 0.1, 0.35, 1]);\n/** Each tile: one spring for opacity, rise, scale and blur. */\nconst ITEM_SPRING = springEase({ stiffness: 200, damping: 20, mass: 1 });\n/** Reflow when items change: Motion's default layout transition. */\nconst LAYOUT_EASE = bezierEase(LAYOUT_TRANSITION.ease);\n\nconst ITEM_HIDDEN: React.CSSProperties = {\n  opacity: 0,\n  transform: \"translateY(40px) scale(0.95)\",\n  filter: \"blur(8px)\",\n};\n\nexport function MasonryGrid<T extends { id: string | number }>({\n  items,\n  renderItem,\n  columnsClassName = \"columns-1 sm:columns-2 md:columns-3 lg:columns-4\",\n  gapClassName = \"gap-6\",\n  animateIn = true,\n  staggerDelay = 0.08,\n  className,\n  style,\n  ...props\n}: MasonryGridProps<T>) {\n  const itemSpacingClass = gapClassName.replace(\"gap-\", \"mb-\");\n\n  const containerRef = useRef<HTMLDivElement>(null);\n  const tiles = useRef(new Map<string | number, HTMLDivElement>());\n  const entering = useRef(new Set<HTMLDivElement>());\n  const known = useRef(new Set<HTMLDivElement>());\n  const revealed = useRef(false);\n\n  // Tiles' boxes before this render commits, for the reflow below.\n  const before = useRef<Flip.FlipState | null>(null);\n  const captureBefore = () => {\n    if (tiles.current.size > 0) {\n      before.current = Flip.getState(Array.from(tiles.current.values()));\n    }\n  };\n\n  /** Blur-fade a tile in: y 40 → 0, scale 0.95 → 1, opacity and blur on the same spring. */\n  const enter = (el: HTMLDivElement, delay: number) => {\n    entering.current.add(el);\n    gsap.fromTo(\n      el,\n      { opacity: 0, y: 40, scale: 0.95 },\n      {\n        opacity: 1,\n        y: 0,\n        scale: 1,\n        duration: ITEM_SPRING.duration,\n        ease: ITEM_SPRING.ease,\n        delay,\n        force3D: false,\n        onUpdate() {\n          el.style.filter = `blur(${Math.max(0, 8 * (1 - this.ratio))}px)`;\n        },\n        onComplete: () => {\n          entering.current.delete(el);\n          el.style.filter = \"blur(0px)\";\n          gsap.set(el, { clearProps: \"transform\" });\n        },\n      },\n    );\n  };\n\n  // Entrance: once, when the grid comes within 50px of the viewport.\n  useLayoutEffect(() => {\n    const container = containerRef.current;\n    if (!animateIn || !container) return;\n    const ctx = gsap.context(() => {});\n    const observer = new IntersectionObserver(\n      (entries) => {\n        if (!entries.some((entry) => entry.isIntersecting)) return;\n        observer.disconnect();\n        revealed.current = true;\n        ctx.add(() => {\n          gsap.to(container, { opacity: 1, duration: 0.3, ease: CONTAINER_EASE });\n          Array.from(tiles.current.values())\n            .sort((a, b) => (a.compareDocumentPosition(b) & 2 ? 1 : -1))\n            .forEach((el, i) => enter(el, 0.1 + i * staggerDelay));\n        });\n      },\n      { rootMargin: \"-50px\" },\n    );\n    observer.observe(container);\n    const inFlight = entering.current;\n    return () => {\n      observer.disconnect();\n      ctx.revert();\n      inFlight.clear();\n      revealed.current = false;\n    };\n  }, [animateIn, staggerDelay]);\n\n  // After every commit: tiles added after the entrance come in on their own,\n  // and tiles the columns moved glide from where they were.\n  useLayoutEffect(() => {\n    const state = before.current;\n    before.current = null;\n    const current = Array.from(tiles.current.values());\n    const visible = !animateIn || revealed.current;\n    current.forEach((el) => {\n      if (!known.current.has(el) && animateIn && revealed.current) enter(el, 0);\n    });\n    known.current = new Set(current);\n    if (!state || !visible) return;\n    const moved = current.filter((el) => {\n      if (entering.current.has(el)) return false;\n      const was = state.getElementState(el)?.bounds;\n      if (!was) return false;\n      const now = el.getBoundingClientRect();\n      return (\n        Math.abs(was.left - now.left) > 0.5 ||\n        Math.abs(was.top - now.top) > 0.5 ||\n        Math.abs(was.width - now.width) > 0.5 ||\n        Math.abs(was.height - now.height) > 0.5\n      );\n    });\n    if (moved.length) {\n      Flip.from(state, {\n        targets: moved,\n        duration: LAYOUT_TRANSITION.duration,\n        ease: LAYOUT_EASE,\n        scale: true,\n        // Back to no transform at rest, as Motion leaves it.\n        onComplete: () => {\n          gsap.set(moved, { clearProps: \"transform\" });\n        },\n      });\n    }\n  });\n\n  return (\n    <BeforeCommit capture={captureBefore}>\n      <div\n        ref={containerRef}\n        className={cn(\"w-full\", columnsClassName, gapClassName, className)}\n        style={animateIn ? { ...style, opacity: 0 } : style}\n        {...props}\n      >\n        {items.map((item, index) => (\n          <div\n            key={item.id}\n            ref={(el) => {\n              if (el) tiles.current.set(item.id, el);\n              else tiles.current.delete(item.id);\n            }}\n            style={animateIn ? ITEM_HIDDEN : undefined}\n            // 2. FIXED GAP ISSUE: Added \"inline-block w-full\" to prevent margin collapse & awkward breaks\n            className={cn(\n              \"break-inside-avoid inline-block w-full\",\n              itemSpacingClass,\n            )}\n          >\n            {renderItem(item, index)}\n          </div>\n        ))}\n      </div>\n    </BeforeCommit>\n  );\n}\n\n/**\n * Runs `capture` on every update, just before React touches the DOM (the\n * commit's before-mutation phase), so the grid can record where its tiles sat\n * before the new items/columns land. Renders nothing of its own.\n */\nclass BeforeCommit extends React.Component<{\n  capture: () => void;\n  children: React.ReactNode;\n}> {\n  getSnapshotBeforeUpdate() {\n    this.props.capture();\n    return null;\n  }\n\n  // Required alongside getSnapshotBeforeUpdate; the work happens in the grid's layout effect.\n  componentDidUpdate() {}\n\n  render() {\n    return this.props.children;\n  }\n}\n",
      "type": "registry:component",
      "target": "components/custom/blocks/MasonryGridBlock.tsx"
    },
    {
      "path": "src/components/custom/blocks/gsap-motion.ts",
      "content": "import gsap from \"gsap\";\nimport { cubicBezier, type FrameTicker } from \"./motion-curves\";\n\n/**\n * GSAP-side glue for the GSAP builds of components that also ship a Motion\n * Motion twin. Kept apart from motion-curves.ts so the library-free curves\n * never pull GSAP into a CSS or Motion build.\n */\n\n/** `gsap.ticker` as a FrameTicker, so spring followers run on GSAP's loop. */\nexport const gsapTicker: FrameTicker = {\n  add(callback) {\n    const tick = (_time: number, deltaTime: number) => callback(deltaTime);\n    gsap.ticker.add(tick);\n    return () => gsap.ticker.remove(tick);\n  },\n};\n\n/** A Motion / CSS cubic-bezier array as a GSAP ease. */\nexport const bezierEase = (curve: readonly [number, number, number, number] | readonly number[]) =>\n  cubicBezier(curve[0], curve[1], curve[2], curve[3]);\n\n/** `(prefers-reduced-motion: reduce)` right now. */\nexport const prefersReducedMotion = () =>\n  typeof window !== \"undefined\" &&\n  window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches === true;\n",
      "type": "registry:component",
      "target": "components/custom/blocks/gsap-motion.ts"
    },
    {
      "path": "src/components/custom/blocks/motion-curves.ts",
      "content": "/**\n * Motion curves with no animation library behind them.\n *\n * The components here ship as CSS, GSAP or Motion builds that must move\n * identically, so the curves are computed once, from the same numbers, and\n * handed to whichever engine runs them:\n *\n *   - `cubicBezier(x1, y1, x2, y2)` → an easing function (GSAP accepts any\n *     `(progress) => value` as `ease`), exact for Motion's `ease: [..]` arrays\n *     and for CSS `cubic-bezier()`.\n *   - `spring({ stiffness, damping, mass })` → the analytic solution Motion\n *     Motion uses, as an easing function plus the time it takes to settle, or\n *     as a CSS `linear()` string for a fixed start and end.\n *   - `createSpringFollower` → a value that chases a moving target through the\n *     same spring every frame, like Motion's `useSpring`, for pointer-driven\n *     motion that no fixed curve can describe.\n */\n\n// ---------------------------------------------------------------------------\n// Cubic bezier\n// ---------------------------------------------------------------------------\n\n/**\n * The CSS / Motion cubic-bezier as a function of progress. Newton-Raphson\n * with a bisection fallback, the same solver browsers use.\n */\nexport function cubicBezier(x1: number, y1: number, x2: number, y2: number) {\n  if (x1 === y1 && x2 === y2) return (t: number) => t;\n\n  const a = (p1: number, p2: number) => 1 - 3 * p2 + 3 * p1;\n  const b = (p1: number, p2: number) => 3 * p2 - 6 * p1;\n  const c = (p1: number) => 3 * p1;\n  const at = (t: number, p1: number, p2: number) =>\n    ((a(p1, p2) * t + b(p1, p2)) * t + c(p1)) * t;\n  const slope = (t: number, p1: number, p2: number) =>\n    3 * a(p1, p2) * t * t + 2 * b(p1, p2) * t + c(p1);\n\n  const solveX = (x: number) => {\n    let t = x;\n    for (let i = 0; i < 8; i++) {\n      const s = slope(t, x1, x2);\n      if (Math.abs(s) < 1e-6) break;\n      const err = at(t, x1, x2) - x;\n      if (Math.abs(err) < 1e-7) return t;\n      t -= err / s;\n    }\n    let lo = 0;\n    let hi = 1;\n    t = x;\n    for (let i = 0; i < 30 && hi - lo > 1e-7; i++) {\n      const value = at(t, x1, x2);\n      if (value < x) lo = t;\n      else hi = t;\n      t = (lo + hi) / 2;\n    }\n    return t;\n  };\n\n  return (x: number) => (x <= 0 ? 0 : x >= 1 ? 1 : at(solveX(x), y1, y2));\n}\n\n/** Motion's named eases, as the cubic-beziers they are. */\nexport const MOTION_EASE = {\n  linear: [0, 0, 1, 1],\n  easeIn: [0.42, 0, 1, 1],\n  easeOut: [0, 0, 0.58, 1],\n  easeInOut: [0.42, 0, 0.58, 1],\n  circIn: [0.55, 0, 1, 0.45],\n  circOut: [0.55, 0, 0.45, 1],\n  circInOut: [0.85, 0, 0.15, 1],\n  backIn: [0.31, 0.01, 0.66, -0.59],\n  backOut: [0.33, 1.53, 0.69, 0.99],\n  anticipate: [0.66, -0.56, 0.34, 1.35],\n} as const;\n\n/**\n * Motion's default layout transition (`layout` / `layoutId`):\n * `{ duration: 0.45, ease: [0.4, 0, 0.1, 1] }`.\n */\nexport const LAYOUT_TRANSITION = { duration: 0.45, ease: [0.4, 0, 0.1, 1] as const };\n\n// ---------------------------------------------------------------------------\n// Spring\n// ---------------------------------------------------------------------------\n\nexport interface SpringOptions {\n  /** Motion default 100. */\n  stiffness?: number;\n  /** Motion default 10. */\n  damping?: number;\n  /** Motion default 1. */\n  mass?: number;\n  /** Starting velocity, in units of the whole distance per second. */\n  velocity?: number;\n  /** How close to the end counts as settled, as a fraction of the distance. */\n  restDelta?: number;\n}\n\n/**\n * Normalised position (0 → 1) of a spring released from 0 towards 1, at time\n * `t` seconds. The closed-form solution Motion's `spring()` generator\n * uses for the under-, critically and over-damped cases.\n */\nexport function springAt(options: SpringOptions = {}) {\n  const { stiffness = 100, damping = 10, mass = 1, velocity = 0 } = options;\n  const zeta = damping / (2 * Math.sqrt(stiffness * mass));\n  const omega0 = Math.sqrt(stiffness / mass);\n  // Motion's convention: distance still to cover, velocity toward it negated.\n  const delta = 1;\n  const v0 = -velocity;\n\n  if (zeta < 1) {\n    const omegaD = omega0 * Math.sqrt(1 - zeta * zeta);\n    return (t: number) => {\n      const envelope = Math.exp(-zeta * omega0 * t);\n      return (\n        1 -\n        envelope *\n          (((v0 + zeta * omega0 * delta) / omegaD) * Math.sin(omegaD * t) +\n            delta * Math.cos(omegaD * t))\n      );\n    };\n  }\n  if (zeta === 1) {\n    return (t: number) => 1 - Math.exp(-omega0 * t) * (delta + (v0 + omega0 * delta) * t);\n  }\n  const omegaD = omega0 * Math.sqrt(zeta * zeta - 1);\n  return (t: number) => {\n    const envelope = Math.exp(-zeta * omega0 * t);\n    const freq = Math.min(omegaD * t, 300);\n    return (\n      1 -\n      (envelope *\n        ((v0 + zeta * omega0 * delta) * Math.sinh(freq) + omegaD * delta * Math.cosh(freq))) /\n        omegaD\n    );\n  };\n}\n\n/** Seconds until the spring stays within `restDelta` of its end. */\nexport function springDuration(options: SpringOptions = {}) {\n  const at = springAt(options);\n  const restDelta = options.restDelta ?? 0.001;\n  const step = 1 / 240;\n  let lastOutside = 0;\n  for (let t = 0; t <= 10; t += step) {\n    if (Math.abs(1 - at(t)) > restDelta) lastOutside = t;\n    else if (t - lastOutside > 0.1) break;\n  }\n  return Math.max(lastOutside + step, step);\n}\n\n/**\n * A spring as a duration and an easing function over it — what GSAP takes:\n *\n *   const { duration, ease } = springEase({ stiffness: 300, damping: 20 });\n *   gsap.to(el, { y: 0, duration, ease });\n *\n * Exact for a fixed start and end; a spring that has to react mid-flight to a\n * new target needs `createSpringFollower` instead.\n */\nexport function springEase(options: SpringOptions = {}) {\n  const duration = springDuration(options);\n  const at = springAt(options);\n  return {\n    duration,\n    ease: (progress: number) => (progress >= 1 ? 1 : at(progress * duration)),\n  };\n}\n\n/**\n * A spring as a CSS `linear()` easing and its duration in ms, for\n * `transition` / `animation` with a fixed start and end.\n *\n *   const { easing, duration } = springLinear({ stiffness: 400, damping: 30 });\n *   el.style.transition = `transform ${duration}ms ${easing}`;\n */\nexport function springLinear(options: SpringOptions = {}, pointsPerSecond = 60) {\n  const duration = springDuration(options);\n  const at = springAt(options);\n  const count = Math.max(Math.ceil(duration * pointsPerSecond), 8);\n  const points: string[] = [];\n  for (let i = 0; i <= count; i++) {\n    const t = (i / count) * duration;\n    points.push(String(Math.round((i === count ? 1 : at(t)) * 10000) / 10000));\n  }\n  return { easing: `linear(${points.join(\", \")})`, duration: Math.round(duration * 1000) };\n}\n\n// ---------------------------------------------------------------------------\n// Spring follower (useSpring equivalent)\n// ---------------------------------------------------------------------------\n\n/** Something that calls back once per frame with the time since the last, in ms. */\nexport interface FrameTicker {\n  add: (callback: (deltaMs: number) => void) => () => void;\n}\n\n/** requestAnimationFrame as a ticker — the library-free default. */\nexport const rafTicker: FrameTicker = {\n  add(callback) {\n    let last = performance.now();\n    let frame = requestAnimationFrame(function tick(now) {\n      callback(now - last);\n      last = now;\n      frame = requestAnimationFrame(tick);\n    });\n    return () => cancelAnimationFrame(frame);\n  },\n};\n\nexport interface SpringFollower {\n  /** Chase a new target from wherever the value is now, keeping its velocity. */\n  set: (target: number) => void;\n  /** Move to a value instantly, with no motion. */\n  jump: (value: number) => void;\n  get: () => number;\n  destroy: () => void;\n}\n\n/**\n * A value that follows its target through a spring, integrating the same\n * equation of motion Motion's `useSpring` solves — so a pointer-driven spring\n * reads the same in every build. Runs only while moving; `onUpdate` receives\n * each new value.\n */\nexport function createSpringFollower(\n  initial: number,\n  onUpdate: (value: number) => void,\n  options: SpringOptions & { restSpeed?: number; ticker?: FrameTicker } = {},\n): SpringFollower {\n  const { stiffness = 100, damping = 10, mass = 1, ticker = rafTicker } = options;\n  const restDelta = options.restDelta ?? 0.01;\n  const restSpeed = options.restSpeed ?? 0.01;\n  let value = initial;\n  let target = initial;\n  let velocity = 0;\n  let stop: (() => void) | null = null;\n\n  const step = (deltaMs: number) => {\n    // Fixed 1ms sub-steps keep the integration stable for stiff springs and\n    // independent of the frame rate.\n    const steps = Math.min(Math.max(Math.round(deltaMs), 1), 250);\n    for (let i = 0; i < steps; i++) {\n      const force = -stiffness * (value - target) - damping * velocity;\n      velocity += (force / mass) * 0.001;\n      value += velocity * 0.001;\n    }\n    if (Math.abs(target - value) < restDelta && Math.abs(velocity) < restSpeed) {\n      value = target;\n      velocity = 0;\n      stop?.();\n      stop = null;\n    }\n    onUpdate(value);\n  };\n\n  return {\n    set(next) {\n      target = next;\n      if (!stop && value !== target) stop = ticker.add(step);\n    },\n    jump(next) {\n      stop?.();\n      stop = null;\n      value = target = next;\n      velocity = 0;\n      onUpdate(value);\n    },\n    get: () => value,\n    destroy() {\n      stop?.();\n      stop = null;\n    },\n  };\n}\n",
      "type": "registry:component",
      "target": "components/custom/blocks/motion-curves.ts"
    }
  ],
  "docs": "Named export: MasonryGrid. Generic over your item type — pass `items` and a `renderItem` callback. Column count and gaps come from `columnsClassName` and `gapClassName`, so responsive behaviour is plain Tailwind. CSS columns fill top-to-bottom per column, so visual order differs from DOM order.",
  "categories": [
    "layout",
    "media"
  ],
  "type": "registry:component"
}
