{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "grid-bento-dense",
  "title": "Grid Bento Dense",
  "description": "A composable bento grid where activating a tile genuinely promotes it: the tile takes a 2x2 slot and every other tile re-packs around it via CSS grid-auto-flow: dense, FLIP-animated so the reflow reads as tiles sliding into new slots rather than jumping.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/core/grid-bento-dense/component.tsx",
      "content": "\"use client\";\n\nimport { useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from \"react\";\n\nexport type BentoSize = \"1x1\" | \"2x1\" | \"1x2\";\n\nexport interface BentoCell {\n  /** Stable id — also the roving-tabindex key and the FLIP measurement key. */\n  id: string;\n  title: string;\n  meta?: string;\n  body?: ReactNode;\n  /** Resting footprint. Ignored while this cell is featured (always 2x2). */\n  size?: BentoSize;\n}\n\nexport interface BentoGridProps {\n  /** the grid's tiles */\n  cells: BentoCell[];\n  /** number of grid columns */\n  cols?: number;\n  /** id of the cell that starts featured (always 2x2). Defaults to the first cell. */\n  defaultFeaturedId?: string;\n  /** extra classes merged onto the rendered root element */\n  className?: string;\n}\n\nconst SPAN: Record<BentoSize, { c: number; r: number }> = {\n  \"1x1\": { c: 1, r: 1 },\n  \"2x1\": { c: 2, r: 1 },\n  \"1x2\": { c: 1, r: 2 },\n};\n\nconst ROW_PX = 108;\n\nfunction spanFor(cell: BentoCell, isFeatured: boolean, cols: number) {\n  if (isFeatured) return { c: Math.min(2, cols), r: 2 };\n  return SPAN[cell.size ?? \"1x1\"];\n}\n\n// Worst-case row count across every possible featured cell — computed once\n// from the cell list, not the live state — so the grid's own box height\n// never jumps as different cells get promoted. Dense packing may leave a\n// little trailing slack in the non-worst states; it never overflows.\nfunction computeRows(cells: BentoCell[], cols: number): number {\n  let worst = 0;\n  for (const candidate of cells) {\n    let units = 0;\n    for (const cell of cells) {\n      const { c, r } = spanFor(cell, cell.id === candidate.id, cols);\n      units += c * r;\n    }\n    worst = Math.max(worst, units);\n  }\n  return Math.max(1, Math.ceil(worst / cols));\n}\n\n/**\n * A bento grid where cells reflow for real: activating one promotes it to a\n * 2x2 slot and every other cell re-packs around it via CSS `grid-auto-flow:\n * dense` — the browser's own layout engine, not a fixed grid-template-areas\n * arrangement. The reflow is FLIP-animated (translate only, size changes\n * instantly) so it reads as tiles sliding into new slots rather than\n * teleporting or smearing under a scale transform. Arrow keys move focus\n * spatially between tiles by their actual on-screen geometry, not DOM order.\n */\nexport function BentoGrid({ cells, cols = 4, defaultFeaturedId, className = \"\" }: BentoGridProps) {\n  const initial = defaultFeaturedId ?? cells[0]?.id ?? \"\";\n  const [featuredId, setFeaturedId] = useState(initial);\n  const [activeId, setActiveId] = useState(initial);\n  const [announce, setAnnounce] = useState(\"\");\n  const refs = useRef(new Map<string, HTMLDivElement>());\n  const pendingFirst = useRef<Map<string, DOMRect> | null>(null);\n\n  const rows = useMemo(() => computeRows(cells, cols), [cells, cols]);\n\n  const activate = (id: string) => {\n    setActiveId(id);\n    if (id === featuredId) return;\n    const reduce =\n      typeof window !== \"undefined\" && window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    if (!reduce) {\n      const first = new Map<string, DOMRect>();\n      refs.current.forEach((el, key) => first.set(key, el.getBoundingClientRect()));\n      pendingFirst.current = first;\n    }\n    setFeaturedId(id);\n    const cell = cells.find((c) => c.id === id);\n    if (cell) setAnnounce(`${cell.title} featured`);\n  };\n\n  // FLIP: positions were captured synchronously before the state write above;\n  // once the new layout has painted, invert each moved cell back to its old\n  // position with transitions off, then release it into a transform\n  // transition back to zero. Size changes (1x1 -> 2x2) happen instantly —\n  // scaling a bordered, rounded card is what smears its border and text.\n  useLayoutEffect(() => {\n    const first = pendingFirst.current;\n    pendingFirst.current = null;\n    if (!first) return;\n    refs.current.forEach((el, key) => {\n      const from = first.get(key);\n      if (!from) return;\n      const to = el.getBoundingClientRect();\n      const dx = from.left - to.left;\n      const dy = from.top - to.top;\n      if (!dx && !dy) return;\n      el.style.transition = \"none\";\n      el.style.transform = `translate(${dx}px, ${dy}px)`;\n      void el.getBoundingClientRect(); // force reflow before releasing\n      requestAnimationFrame(() => {\n        el.style.transition = \"transform 380ms cubic-bezier(0.22, 1, 0.36, 1)\";\n        el.style.transform = \"\";\n      });\n    });\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [featuredId]);\n\n  // Spatial nav: candidates are filtered to the pressed half-plane by their\n  // actual rendered centre, then scored by distance along the pressed axis\n  // plus double the perpendicular drift — reading order plays no part.\n  const move = (dir: \"up\" | \"down\" | \"left\" | \"right\") => {\n    const cur = refs.current.get(activeId)?.getBoundingClientRect();\n    if (!cur) return;\n    const cx = cur.left + cur.width / 2;\n    const cy = cur.top + cur.height / 2;\n    let bestId: string | null = null;\n    let bestScore = Infinity;\n    refs.current.forEach((el, id) => {\n      if (id === activeId) return;\n      const r = el.getBoundingClientRect();\n      const x = r.left + r.width / 2 - cx;\n      const y = r.top + r.height / 2 - cy;\n      let primary: number;\n      let secondary: number;\n      if (dir === \"right\") {\n        if (x <= 1) return;\n        primary = x;\n        secondary = Math.abs(y);\n      } else if (dir === \"left\") {\n        if (x >= -1) return;\n        primary = -x;\n        secondary = Math.abs(y);\n      } else if (dir === \"down\") {\n        if (y <= 1) return;\n        primary = y;\n        secondary = Math.abs(x);\n      } else {\n        if (y >= -1) return;\n        primary = -y;\n        secondary = Math.abs(x);\n      }\n      const score = primary + secondary * 2;\n      if (score < bestScore) {\n        bestScore = score;\n        bestId = id;\n      }\n    });\n    if (bestId) {\n      setActiveId(bestId);\n      refs.current.get(bestId)?.focus();\n    }\n  };\n\n  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>, id: string) => {\n    switch (e.key) {\n      case \"ArrowRight\":\n        e.preventDefault();\n        move(\"right\");\n        break;\n      case \"ArrowLeft\":\n        e.preventDefault();\n        move(\"left\");\n        break;\n      case \"ArrowDown\":\n        e.preventDefault();\n        move(\"down\");\n        break;\n      case \"ArrowUp\":\n        e.preventDefault();\n        move(\"up\");\n        break;\n      case \"Enter\":\n      case \" \":\n        e.preventDefault();\n        activate(id);\n        break;\n      default:\n        break;\n    }\n  };\n\n  return (\n    <div className=\"w-full\">\n      <div\n        role=\"group\"\n        aria-label=\"Bento grid. Arrow keys move between tiles, Enter or Space features one.\"\n        className={`grid gap-3 ${className}`}\n        style={{\n          gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`,\n          gridTemplateRows: `repeat(${rows}, ${ROW_PX}px)`,\n          gridAutoFlow: \"dense\",\n        }}\n      >\n        {cells.map((cell) => {\n          const isFeatured = cell.id === featuredId;\n          const { c, r } = spanFor(cell, isFeatured, cols);\n          return (\n            <div\n              key={cell.id}\n              ref={(el) => {\n                if (el) refs.current.set(cell.id, el);\n                else refs.current.delete(cell.id);\n              }}\n              role=\"button\"\n              tabIndex={cell.id === activeId ? 0 : -1}\n              aria-pressed={isFeatured}\n              aria-label={cell.title}\n              data-cell-id={cell.id}\n              data-featured={String(isFeatured)}\n              onClick={() => activate(cell.id)}\n              onKeyDown={(e) => onKeyDown(e, cell.id)}\n              onFocus={() => setActiveId(cell.id)}\n              className=\"group relative flex cursor-pointer flex-col justify-between overflow-hidden rounded-md border border-border bg-surface p-4 text-left transition-colors duration-150 hover:border-ns-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ns-accent\"\n              style={{ gridColumn: `span ${c}`, gridRow: `span ${r}` }}\n            >\n              {isFeatured && (\n                <span aria-hidden className=\"absolute right-3 top-3 h-1.5 w-1.5 rounded-full bg-ns-accent\" />\n              )}\n              <div>\n                {cell.meta && (\n                  <p className=\"mb-1 font-mono text-[10px] uppercase tracking-widest text-ns-muted\">{cell.meta}</p>\n                )}\n                <h3 className={`font-medium text-foreground ${isFeatured ? \"text-base\" : \"text-sm\"}`}>\n                  {cell.title}\n                </h3>\n              </div>\n              {cell.body && <div className=\"mt-2 flex-1 text-sm text-ns-muted\">{cell.body}</div>}\n              <span\n                aria-hidden\n                className=\"pointer-events-none mt-2 block text-right font-mono text-[10px] uppercase tracking-widest text-ns-muted opacity-0 transition-opacity duration-150 group-hover:opacity-100 group-focus-visible:opacity-100\"\n              >\n                {isFeatured ? \"featured\" : \"feature this\"}\n              </span>\n            </div>\n          );\n        })}\n      </div>\n      <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {announce}\n      </span>\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "components/ui/grid-bento-dense.tsx"
    }
  ],
  "cssVars": {
    "theme": {
      "color-ns-muted": "var(--ns-muted)",
      "color-ns-accent": "var(--ns-accent)",
      "color-surface": "var(--surface)"
    },
    "light": {
      "ns-muted": "#4d4d4d",
      "ns-accent": "#006bff",
      "surface": "#fafafa"
    },
    "dark": {
      "ns-muted": "#8f8f8f",
      "surface": "#171717"
    }
  },
  "meta": {
    "collection": "core",
    "tags": [
      "grid",
      "layout",
      "bento",
      "dashboard",
      "keyboard-navigation",
      "reflow",
      "accessibility"
    ],
    "instruction": "A bento grid built as a real layout primitive rather than a fixed grid-template-areas arrangement: it takes a `cells` array of arbitrary length and content (`{ id, title, meta?, body?, size? }`, size one of 1x1/2x1/1x2 as its resting footprint) and a `cols` count, and lays every cell out with native CSS `grid-auto-flow: dense` — the browser's own packing algorithm, not JS-computed positions. Clicking, or Enter/Space on, any tile ACTIVATES it: that tile's span becomes 2x2 regardless of its resting size, the previously-featured tile drops back to its own resting size, and dense re-runs the pack — every other tile can shift to fill the gap, which is what makes this a primitive the rest of a dashboard composes into rather than a decoration. The reflow is FLIP-animated: before the state write, every tile's current getBoundingClientRect is captured; after the new layout has painted, each tile that moved is inverted back to its old screen position with transitions off, forced to reflow, then released into a 380ms transform transition back to zero — so the motion is a real position change riding a transform, not a fake. Size changes happen INSTANTLY, never scaled: animating a bordered, rounded tile's width/height via scale is what smears its border and distorts its text, so only translation is animated and the grid-column/row spans swap in the same frame as the state update. The container's own height never changes across activations — `computeRows` evaluates every cell as the hypothetical featured one, takes the worst-case total area, and fixes `grid-template-rows` to that count once, so a dashboard embedding this grid never has its neighbors jump when someone taps a different tile. ARROW KEYS move focus by actual on-screen geometry, not DOM order: from the focused tile's centre, candidates in the pressed half-plane are scored by distance along that axis plus double the perpendicular drift, and the closest wins — a tile below and slightly right of the current one is `ArrowDown`, not `ArrowRight`, which flat DOM-order roving tabindex gets wrong the moment tiles vary in size. Every tile is `role=button` with roving tabindex (exactly one at 0), `aria-pressed` reflecting featured state, and an `aria-label` from its title; a visually-hidden `role=status` region announces which tile just got featured. Hover and keyboard focus both lift the border from --border to --ns-muted and reveal a small 'feature this' hint (opacity 0 to 1), and the featured tile alone carries a small --ns-accent dot — the only place accent appears. `prefers-reduced-motion` skips the FLIP capture entirely: the new layout still applies, cells still move, there's just no transform animating the transition. All color from --background/--foreground/--ns-muted/--border/--ns-accent tokens via Tailwind utility classes, zero canvas, zero dependencies."
  },
  "type": "registry:ui"
}