{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"reflow-grid","type":"registry:component","title":"Reflow Grid","description":"Filter the shelf. The objects find their new places.","dependencies":[],"categories":["systems","grid","filter","FLIP","collection"],"files":[{"path":"components/lab/reflow-grid/reflow-grid.tsx","target":"components/lab/reflow-grid/reflow-grid.tsx","type":"registry:component","content":"\"use client\";\n\nimport {\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type CSSProperties,\n  type ReactNode,\n} from \"react\";\nimport \"./reflow-grid.css\";\n\nexport type ReflowGridProps<T> = {\n  items: T[];\n  getKey: (item: T) => string;\n  renderItem: (item: T, context: { mode: \"grid\" | \"list\" }) => ReactNode;\n  mode?: \"grid\" | \"list\";\n  empty?: ReactNode;\n  label?: string;\n  /** Disable layout animation without changing the rendered result. */\n  animate?: boolean;\n  /** Space between cards, in pixels. */\n  gap?: number;\n  className?: string;\n};\n\ntype Box = { x: number; y: number; width: number; height: number };\n\nfunction prefersReduced() {\n  return (\n    typeof window !== \"undefined\" &&\n    window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches\n  );\n}\n\n/**\n * REFLOW GRID\n *\n * Filtering and sorting keep the same DOM nodes and animate from their\n * previous slots with a FLIP pass measured in layout space (offset\n * coordinates, so a running animation never feeds back into the next\n * measurement). Removed cards leave as short-lived, inert ghosts at\n * their old coordinates; the survivors move at the same time instead of\n * waiting for a second layout. Empty, grid, list and narrow states all\n * share one component.\n */\nexport function ReflowGrid<T>({\n  items,\n  getKey,\n  renderItem,\n  mode = \"grid\",\n  empty,\n  label = \"Collection\",\n  animate = true,\n  gap = 14,\n  className,\n}: ReflowGridProps<T>) {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const nodes = useRef(new Map<string, HTMLElement>());\n  const boxes = useRef(new Map<string, Box>());\n  const known = useRef(new Map<string, T>());\n  const knownMode = useRef(mode);\n  const knownGap = useRef(gap);\n  const keysRef = useRef<string[]>([]);\n  const animations = useRef(new Map<string, Animation>());\n  const focusKey = useRef<string | null>(null);\n  const ghostTimer = useRef<number | null>(null);\n  const [ghosts, setGhosts] = useState<\n    { key: string; box: Box; node: ReactNode }[]\n  >([]);\n\n  const keys = items.map(getKey);\n  const signature = keys.join(\"\\u0001\");\n  const previousSignature = useRef(signature);\n\n  const setNode = useCallback((key: string, node: HTMLElement | null) => {\n    if (node) nodes.current.set(key, node);\n    else nodes.current.delete(key);\n  }, []);\n\n  useLayoutEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const changed =\n      previousSignature.current !== signature ||\n      knownMode.current !== mode ||\n      knownGap.current !== gap;\n    const reduced = prefersReduced() || !animate;\n\n    const nextBoxes = new Map<string, Box>();\n    for (const key of keys) {\n      const node = nodes.current.get(key);\n      if (!node) continue;\n      nextBoxes.set(key, {\n        x: node.offsetLeft,\n        y: node.offsetTop,\n        width: node.offsetWidth,\n        height: node.offsetHeight,\n      });\n    }\n\n    if (changed && !reduced) {\n      for (const key of keys) {\n        const node = nodes.current.get(key);\n        const before = boxes.current.get(key);\n        const after = nextBoxes.get(key);\n        if (!node || !before || !after) continue;\n        const dx = before.x - after.x;\n        const dy = before.y - after.y;\n        if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) continue;\n        animations.current.get(key)?.cancel();\n        const animation = node.animate(\n          [\n            { transform: `translate3d(${dx}px, ${dy}px, 0)` },\n            { transform: \"translate3d(0, 0, 0)\" },\n          ],\n          {\n            duration: 340,\n            easing: \"cubic-bezier(0.22, 1, 0.36, 1)\",\n          },\n        );\n        animations.current.set(key, animation);\n        animation.finished\n          .catch(() => {})\n          .finally(() => {\n            if (animations.current.get(key) === animation)\n              animations.current.delete(key);\n          });\n      }\n\n      const seen = new Set(keysRef.current);\n      for (const key of keys) {\n        if (seen.has(key)) continue;\n        const node = nodes.current.get(key);\n        if (!node) continue;\n        animations.current.get(key)?.cancel();\n        const animation = node.animate(\n          [\n            { opacity: 0, transform: \"scale(0.975)\" },\n            { opacity: 1, transform: \"scale(1)\" },\n          ],\n          { duration: 260, easing: \"cubic-bezier(0.22, 1, 0.36, 1)\" },\n        );\n        animations.current.set(key, animation);\n      }\n\n      const removed = keysRef.current.filter((key) => !keys.includes(key));\n      if (removed.length) {\n        const leaving = removed.flatMap((key) => {\n          const box = boxes.current.get(key);\n          const item = known.current.get(key);\n          if (!box || item === undefined) return [];\n          return [\n            {\n              key,\n              box,\n              node: renderItem(item, { mode: knownMode.current }),\n            },\n          ];\n        });\n        if (leaving.length) {\n          setGhosts(leaving);\n          if (ghostTimer.current !== null)\n            window.clearTimeout(ghostTimer.current);\n          ghostTimer.current = window.setTimeout(() => {\n            setGhosts([]);\n            ghostTimer.current = null;\n          }, 230);\n        }\n      }\n    }\n\n    boxes.current = nextBoxes;\n    keysRef.current = keys;\n    knownMode.current = mode;\n    knownGap.current = gap;\n    previousSignature.current = signature;\n    for (const item of items) known.current.set(getKey(item), item);\n    for (const key of [...known.current.keys()]) {\n      if (!keys.includes(key)) known.current.delete(key);\n    }\n\n    if (\n      focusKey.current &&\n      !keys.includes(focusKey.current) &&\n      (document.activeElement === document.body ||\n        !root.contains(document.activeElement))\n    ) {\n      focusKey.current = null;\n      root.focus({ preventScroll: true });\n    }\n  }, [signature, mode, animate, gap, keys, items, getKey, renderItem]);\n\n  useEffect(\n    () => () => {\n      if (ghostTimer.current !== null) window.clearTimeout(ghostTimer.current);\n      for (const animation of animations.current.values()) animation.cancel();\n      animations.current.clear();\n    },\n    [],\n  );\n\n  const style = {\n    \"--rg-gap\": `${gap}px`,\n  } as CSSProperties;\n\n  return (\n    <div\n      ref={rootRef}\n      className={`rg-root${className ? ` ${className}` : \"\"}`}\n      data-mode={mode}\n      role=\"region\"\n      aria-label={label}\n      tabIndex={-1}\n      style={style}\n      onFocusCapture={(event) => {\n        const item = (event.target as HTMLElement).closest<HTMLElement>(\n          \"[data-reflow-key]\",\n        );\n        focusKey.current = item?.dataset.reflowKey ?? null;\n      }}\n    >\n      {items.length === 0 ? (\n        <div className=\"rg-empty\" role=\"status\">\n          {empty ?? \"Nothing matches these filters.\"}\n        </div>\n      ) : (\n        <div className=\"rg-grid\" role=\"list\">\n          {items.map((item) => {\n            const key = getKey(item);\n            return (\n              <div\n                key={key}\n                ref={(node) => setNode(key, node)}\n                className=\"rg-item\"\n                role=\"listitem\"\n                data-reflow-key={key}\n              >\n                {renderItem(item, { mode })}\n              </div>\n            );\n          })}\n        </div>\n      )}\n      {ghosts.length > 0 ? (\n        <div className=\"rg-ghosts\" aria-hidden=\"true\" inert>\n          {ghosts.map((ghost) => (\n            <div\n              key={`ghost-${ghost.key}`}\n              className=\"rg-ghost\"\n              style={{\n                left: ghost.box.x,\n                top: ghost.box.y,\n                width: ghost.box.width,\n                height: ghost.box.height,\n              }}\n            >\n              {ghost.node}\n            </div>\n          ))}\n        </div>\n      ) : null}\n    </div>\n  );\n}\n"},{"path":"components/lab/reflow-grid/reflow-grid.css","target":"components/lab/reflow-grid/reflow-grid.css","type":"registry:file","content":".rg-root {\n  position: relative;\n  min-width: 0;\n  font: inherit;\n}\n\n.rg-root:focus-visible {\n  outline: 2px solid #4b3f95;\n  outline-offset: 4px;\n  border-radius: 8px;\n}\n\n.rg-grid {\n  display: grid;\n  grid-template-columns: repeat(auto-fill, minmax(min(210px, 100%), 1fr));\n  gap: var(--rg-gap, 14px);\n  align-items: stretch;\n}\n\n.rg-root[data-mode=\"grid\"] .rg-item {\n  min-width: 0;\n  height: 100%;\n}\n\n.rg-root[data-mode=\"grid\"] .rg-item > * {\n  height: 100%;\n}\n\n.rg-root[data-mode=\"list\"] .rg-grid {\n  grid-template-columns: minmax(0, 1fr);\n  gap: 8px;\n}\n\n.rg-root[data-mode=\"list\"] .rg-item {\n  min-width: 0;\n}\n\n.rg-empty {\n  display: grid;\n  place-items: center;\n  min-height: 210px;\n  padding: 28px;\n  border: 1px dashed rgba(20, 20, 24, 0.16);\n  border-radius: 12px;\n  color: #71717a;\n  font-size: 0.875rem;\n  text-align: center;\n}\n\n.rg-ghosts {\n  position: absolute;\n  inset: 0;\n  z-index: 2;\n  pointer-events: none;\n}\n\n.rg-ghost {\n  position: absolute;\n  overflow: hidden;\n  border-radius: 12px;\n  animation: rg-ghost-out 220ms cubic-bezier(0.4, 0, 1, 1) both;\n  will-change: opacity, transform;\n}\n\n@keyframes rg-ghost-out {\n  from {\n    opacity: 1;\n    transform: scale(1);\n  }\n  to {\n    opacity: 0;\n    transform: scale(0.96);\n  }\n}\n\n@media (max-width: 520px) {\n  .rg-grid {\n    grid-template-columns: repeat(auto-fill, minmax(min(160px, 100%), 1fr));\n    gap: 10px;\n  }\n\n  .rg-root[data-mode=\"grid\"] .rg-item > * {\n    height: auto;\n  }\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .rg-ghost {\n    animation-duration: 0.01ms;\n  }\n}\n"}]}