{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "motion-masonry-grid",
  "title": "Masonry grid",
  "description": "A responsive masonry layout for items of different heights.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "components/core/masonry-grid.tsx",
      "content": "'use client';\nimport { motion, useInView } from 'motion/react';\nimport {\n  Children,\n  createContext,\n  isValidElement,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type ReactNode,\n} from 'react';\nimport { cn } from '@/lib/utils';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\n\nexport type MasonryGridLayout = 'columns' | 'balanced';\n\nexport type MasonryGridProps = {\n  children: ReactNode;\n  className?: string;\n  layout?: MasonryGridLayout;\n  columnWidth?: number;\n  maxColumns?: number;\n  gap?: number;\n  revealOnView?: boolean;\n};\n\ntype Cell = {\n  key: string;\n  node: ReactNode;\n};\n\ntype MasonryContextValue = {\n  gap: number;\n  revealOnView: boolean;\n  seenKeys: Set<string>;\n  markSeen: (key: string) => void;\n};\n\nconst MasonryContext = createContext<MasonryContextValue | undefined>(\n  undefined\n);\n\nconst REVEAL_MARGIN = '0px 0px -8% 0px';\n\nconst REVEAL_HIDDEN = { opacity: 0, y: 12 };\n\nconst REVEAL_SHOWN = { opacity: 1, y: 0 };\n\nconst COLUMN_STAGGER = 0.04;\n\nfunction useMasonry() {\n  const context = useContext(MasonryContext);\n  if (!context) {\n    throw new Error('MasonryCell must be used within MasonryGrid');\n  }\n  return context;\n}\n\nfunction cellsOf(children: ReactNode) {\n  const cells: Cell[] = [];\n  Children.toArray(children).forEach((child, index) => {\n    let key = String(index);\n    if (isValidElement(child) && child.key !== null) {\n      key = String(child.key);\n    }\n    cells.push({ key, node: child });\n  });\n  return cells;\n}\n\nfunction columnCountOf(\n  width: number,\n  columnWidth: number,\n  gap: number,\n  maxColumns: number\n) {\n  const fitting = Math.floor((width + gap) / (columnWidth + gap));\n  const atLeastOne = Math.max(1, fitting);\n  return Math.min(maxColumns, atLeastOne);\n}\n\nfunction indexOfShortest(totals: number[]) {\n  let shortest = 0;\n  totals.forEach((total, index) => {\n    if (total < totals[shortest]) {\n      shortest = index;\n    }\n  });\n  return shortest;\n}\n\n/** Places each item, in reading order, at the bottom of the shortest column. */\nfunction balancedColumnsOf(heights: number[], columnCount: number) {\n  const columns: number[][] = Array.from({ length: columnCount }, () => []);\n  const totals: number[] = Array.from({ length: columnCount }, () => 0);\n  heights.forEach((height, index) => {\n    const shortest = indexOfShortest(totals);\n    columns[shortest].push(index);\n    totals[shortest] += height;\n  });\n  return columns;\n}\n\nfunction measuredHeightsOf(container: HTMLElement, count: number) {\n  const heights: number[] = Array.from({ length: count }, () => 0);\n  const cells = container.querySelectorAll<HTMLElement>('[data-masonry-cell]');\n  cells.forEach((cell) => {\n    const index = Number(cell.dataset.masonryCell);\n    heights[index] = cell.offsetHeight;\n  });\n  return heights;\n}\n\nfunction roundRobinColumnsOf(cellCount: number, columnCount: number) {\n  const columns: number[][] = Array.from({ length: columnCount }, () => []);\n  for (let index = 0; index < cellCount; index += 1) {\n    const columnIndex = index % columnCount;\n    columns[columnIndex].push(index);\n  }\n  return columns;\n}\n\nfunction placedCountOf(columns: number[][]) {\n  let placed = 0;\n  columns.forEach((column) => {\n    placed += column.length;\n  });\n  return placed;\n}\n\nfunction fitsLayout(\n  columns: number[][] | null,\n  columnCount: number,\n  cellCount: number\n) {\n  if (!columns) {\n    return false;\n  }\n  const hasSameColumnCount = columns.length === columnCount;\n  const placesEveryCell = placedCountOf(columns) === cellCount;\n  return hasSameColumnCount && placesEveryCell;\n}\n\nfunction contentWidthOf(container: HTMLElement) {\n  const style = window.getComputedStyle(container);\n  const paddingLeft = Number.parseFloat(style.paddingLeft);\n  const paddingRight = Number.parseFloat(style.paddingRight);\n  return container.clientWidth - paddingLeft - paddingRight;\n}\n\nfunction sameColumns(current: number[][] | null, next: number[][]) {\n  if (!current) {\n    return false;\n  }\n  return JSON.stringify(current) === JSON.stringify(next);\n}\n\nfunction revealDelayOf(columnIndex: number) {\n  return columnIndex * COLUMN_STAGGER;\n}\n\ntype MasonryCellProps = {\n  children: ReactNode;\n  cellKey: string;\n  index: number;\n  columnIndex: number;\n};\n\nfunction StaticCell({ children, index }: MasonryCellProps) {\n  const { gap } = useMasonry();\n\n  return (\n    <div\n      data-masonry-cell={index}\n      style={{ marginBottom: gap }}\n      className='break-inside-avoid'\n    >\n      {children}\n    </div>\n  );\n}\n\nfunction RevealCell({\n  children,\n  cellKey,\n  index,\n  columnIndex,\n}: MasonryCellProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const { gap, markSeen } = useMasonry();\n  const isInView = useInView(ref, { once: true, margin: REVEAL_MARGIN });\n\n  useEffect(() => {\n    if (isInView) {\n      markSeen(cellKey);\n    }\n  }, [isInView, cellKey, markSeen]);\n\n  return (\n    <motion.div\n      ref={ref}\n      data-masonry-cell={index}\n      style={{ marginBottom: gap }}\n      initial={REVEAL_HIDDEN}\n      animate={isInView && REVEAL_SHOWN}\n      transition={{\n        duration: 0.32,\n        ease: [0.23, 1, 0.32, 1],\n        delay: revealDelayOf(columnIndex),\n      }}\n      className='break-inside-avoid'\n    >\n      {children}\n    </motion.div>\n  );\n}\n\n/**\n * Whether the cell was new is read once per mount, so marking it as seen does not swap it\n * mid-entrance. The motion preference stays live: it is only known after the page hydrates.\n */\nfunction MasonryCell(props: MasonryCellProps) {\n  const { revealOnView, seenKeys } = useMasonry();\n  const prefersReducedMotion = usePrefersReducedMotion();\n  const [isFirstEntry] = useState(() => !seenKeys.has(props.cellKey));\n  const isMotionAllowed = !prefersReducedMotion;\n  const wantsReveal = revealOnView && isMotionAllowed;\n  const shouldReveal = wantsReveal && isFirstEntry;\n\n  if (shouldReveal) {\n    return <RevealCell {...props} />;\n  }\n  return <StaticCell {...props} />;\n}\n\nfunction MasonryGrid({\n  children,\n  className,\n  layout = 'columns',\n  columnWidth = 220,\n  maxColumns = 4,\n  gap = 16,\n  revealOnView = false,\n}: MasonryGridProps) {\n  const containerRef = useRef<HTMLDivElement>(null);\n  const [columnCount, setColumnCount] = useState(0);\n  const [columns, setColumns] = useState<number[][] | null>(null);\n  const [seenKeys, setSeenKeys] = useState<Set<string>>(() => new Set());\n  const cells = cellsOf(children);\n  const cellCount = cells.length;\n  const cellSignature = cells.map((cell) => cell.key).join('|');\n  const isBalanced = layout === 'balanced';\n\n  const markSeen = useCallback((key: string) => {\n    setSeenKeys((current) => {\n      if (current.has(key)) {\n        return current;\n      }\n      const next = new Set(current);\n      next.add(key);\n      return next;\n    });\n  }, []);\n\n  useEffect(() => {\n    const container = containerRef.current;\n    if (!container) {\n      return;\n    }\n    if (!isBalanced) {\n      return;\n    }\n    const observer = new ResizeObserver(() => {\n      const width = contentWidthOf(container);\n      const count = columnCountOf(width, columnWidth, gap, maxColumns);\n      setColumnCount(count);\n    });\n    observer.observe(container);\n    return () => observer.disconnect();\n  }, [isBalanced, columnWidth, gap, maxColumns]);\n\n  useLayoutEffect(() => {\n    const container = containerRef.current;\n    if (!container) {\n      return;\n    }\n    if (!isBalanced) {\n      return;\n    }\n    const width = contentWidthOf(container);\n    const count = columnCountOf(width, columnWidth, gap, maxColumns);\n    if (count !== columnCount) {\n      setColumnCount(count);\n      return;\n    }\n    const hasFittingColumns = fitsLayout(columns, count, cellCount);\n    if (!hasFittingColumns) {\n      setColumns(roundRobinColumnsOf(cellCount, count));\n      return;\n    }\n    const heights = measuredHeightsOf(container, cellCount);\n    const next = balancedColumnsOf(heights, count);\n    if (!sameColumns(columns, next)) {\n      setColumns(next);\n    }\n  }, [\n    isBalanced,\n    columnCount,\n    columns,\n    cellCount,\n    cellSignature,\n    columnWidth,\n    gap,\n    maxColumns,\n  ]);\n\n  const contextValue = { gap, revealOnView, seenKeys, markSeen };\n  const hasBalancedColumns = isBalanced && columns !== null;\n\n  if (hasBalancedColumns) {\n    return (\n      <MasonryContext.Provider value={contextValue}>\n        <div\n          ref={containerRef}\n          style={{ columnGap: gap }}\n          className={cn('flex items-start', className)}\n          data-layout='balanced'\n        >\n          {columns.map((column, columnIndex) => (\n            <div key={columnIndex} className='flex min-w-0 flex-1 flex-col'>\n              {column.map((cellIndex) => {\n                const cell = cells[cellIndex];\n                if (!cell) {\n                  return null;\n                }\n                return (\n                  <MasonryCell\n                    key={cell.key}\n                    cellKey={cell.key}\n                    index={cellIndex}\n                    columnIndex={columnIndex}\n                  >\n                    {cell.node}\n                  </MasonryCell>\n                );\n              })}\n            </div>\n          ))}\n        </div>\n      </MasonryContext.Provider>\n    );\n  }\n\n  return (\n    <MasonryContext.Provider value={contextValue}>\n      <div\n        ref={containerRef}\n        style={{ columnWidth, columnCount: maxColumns, columnGap: gap }}\n        className={className}\n        data-layout='columns'\n      >\n        {cells.map((cell, index) => (\n          <MasonryCell\n            key={cell.key}\n            cellKey={cell.key}\n            index={index}\n            columnIndex={0}\n          >\n            {cell.node}\n          </MasonryCell>\n        ))}\n      </div>\n    </MasonryContext.Provider>\n  );\n}\n\nexport { MasonryGrid };\n",
      "type": "registry:component",
      "target": "components/core/masonry-grid.tsx"
    }
  ],
  "categories": [
    "motion"
  ],
  "type": "registry:component"
}