# Integrate `DataGrid` from Motion Garden

You are helping me add the **DataGrid** 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:** DataGrid
- **Category:** Power-User Systems
- **Summary:** A virtualised grid over thousands of rows: resizable columns, multi-key sorting, range selection and keyboard navigation. Header and body share one scroller so they can never desync, selection is keyed by row id so it survives a re-sort, and focus stays on the viewport so a recycled row can never take the arrow keys down with it. Give it a parent with a bounded height — like every windowing implementation, in an auto-height parent it quietly stops windowing and renders every row.
- **Reference:** https://motion-garden.netlify.app/components/data-grid
- **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 lucide-react clsx tailwind-merge
```

## Design tokens this source uses

Some classes in the source are Motion Garden theme tokens, not stock Tailwind (`text-ink`, `bg-panel`, `font-display` and the like). Without them, parts of the component render unstyled. Add this to my global CSS, after the Tailwind import:

```css
@theme {
  --font-display: "Space Mono", ui-monospace, "SFMono-Regular", monospace;
}

@theme inline {
  --color-panel: var(--sg-panel);
  --color-raised: var(--sg-raised);
  --color-hairline: var(--sg-hairline);
  --color-ink: var(--sg-ink);
  --color-ink-dim: var(--sg-ink-dim);
  --color-ink-mute: var(--sg-ink-mute);
  --color-accent: var(--sg-accent);
  --color-accent-muted: var(--sg-accent-muted);
}

:root {
  --sg-panel: #ffffff;
  --sg-raised: #eceaef;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-ink-dim: #545b64;
  --sg-ink-mute: #878e97;
  --sg-accent: #7e22ce;
  --sg-accent-muted: #d8b4fe;
}

.dark {
  --sg-panel: #101215;
  --sg-raised: #191d21;
  --sg-hairline: #2a2f36;
  --sg-ink: #e2e6e9;
  --sg-ink-dim: #bcc2c8;
  --sg-ink-mute: #6c737c;
  --sg-accent: #a855f7;
  --sg-accent-muted: #5b3a7a;
}
```

The values are Motion Garden's own light and dark themes. If my project already has tokens for these roles, point the `--sg-*` variables at mine instead and tell me which you mapped. `.dark` assumes class-based dark mode — adapt the selector to how my project switches themes.

`font-display` expects Space Mono, and this CSS only names it. Load the font (with `next/font/google`, for example) or put my own display face first in the stack; until then it falls back to the system monospace.

## Files to create

10 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/data-grid/data-grid.tsx`

```tsx
"use client";

import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import BodyRows from "./body-rows";
import HeaderRow from "./header-row";
import SkeletonRows from "./skeleton-rows";
import { useColumns } from "./use-columns";
import { useVirtualRows } from "./use-virtual-rows";
import { rangeBetween, sortRows } from "./util";
import type { DataGridColumn, SelectionMode } from "./types";

export interface DataGridProps<Row> {
  rows?: Row[];
  columns?: DataGridColumn<Row>[];
  getRowId: (row: Row) => string;
  className?: string;
  rowHeight?: number;
  headerHeight?: number;
  overscan?: number;
  minColumnWidth?: number;
  stickyHeader?: boolean;
  resizableColumns?: boolean;
  sortable?: boolean;
  multiSort?: boolean;
  selectionMode?: SelectionMode;
  zebra?: boolean;
  showSkeleton?: boolean;
  accent?: string;
  reducedMotion?: boolean;
  emptyMessage?: string;
  onSelectionChange?: (ids: string[]) => void;
}

export default function DataGrid<Row>({
  rows = [],
  columns = [],
  getRowId,
  className,
  rowHeight = 34,
  headerHeight = 34,
  overscan = 6,
  minColumnWidth = 80,
  stickyHeader = true,
  resizableColumns = true,
  sortable = true,
  multiSort = true,
  selectionMode = "range",
  zebra = true,
  showSkeleton = false,
  accent = "#a855f7",
  reducedMotion = false,
  emptyMessage = "Nothing here yet.",
  onSelectionChange,
}: DataGridProps<Row>) {
  const gridId = useId();
  const { sorts, widthOf, toggleSort, beginResize } = useColumns(columns, minColumnWidth);

  const sorted = useMemo(() => sortRows(rows, sorts, columns), [rows, sorts, columns]);

  const window_ = useVirtualRows(sorted.length, rowHeight, overscan, headerHeight);
  const { viewportRef, first, last, totalHeight, offsetTop, height, onScroll } = window_;

  const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set());
  const [activeIndex, setActiveIndex] = useState(0);
  const anchorIndex = useRef(0);

  useEffect(() => {
    onSelectionChange?.([...selected]);
  }, [selected, onSelectionChange]);

  const totalWidth = columns.reduce((sum, column) => sum + widthOf(column.key), 0);

  const select = useCallback(
    (index: number, mode: "replace" | "extend" | "toggle") => {
      if (selectionMode === "none") return;
      const row = sorted[index];
      if (!row) return;
      const id = getRowId(row);

      if (selectionMode === "single" || mode === "replace") {
        setSelected(new Set([id]));
        anchorIndex.current = index;
        return;
      }
      if (mode === "extend") {
        const next = new Set<string>();
        for (const i of rangeBetween(anchorIndex.current, index)) {
          const other = sorted[i];
          if (other) next.add(getRowId(other));
        }
        setSelected(next);
        return;
      }
      setSelected((current) => {
        const next = new Set(current);
        if (next.has(id)) next.delete(id);
        else next.add(id);
        return next;
      });
      anchorIndex.current = index;
    },
    [getRowId, selectionMode, sorted],
  );

  const move = useCallback(
    (to: number, extend: boolean) => {
      const clamped = Math.max(0, Math.min(sorted.length - 1, to));
      setActiveIndex(clamped);
      window_.scrollRowIntoView(clamped);
      if (extend) select(clamped, "extend");
    },
    [select, sorted.length, window_],
  );

  const slice = showSkeleton ? [] : sorted.slice(first, last);
  const skeletonCount = Math.max(1, Math.ceil((height || 240) / Math.max(rowHeight, 1)));

  return (
    <div
      className={cn(
        "flex h-full w-full flex-col overflow-hidden rounded-2xl border border-hairline bg-panel",
        className,
      )}
    >
      <div
        ref={viewportRef}
        onScroll={onScroll}
        tabIndex={0}
        role="grid"
        aria-rowcount={sorted.length + 1}
        aria-colcount={columns.length}
        aria-multiselectable={selectionMode === "range"}
        aria-activedescendant={
          selectionMode === "none" || showSkeleton || sorted.length === 0
            ? undefined
            : `${gridId}-row-${activeIndex}`
        }
        className="relative min-h-0 w-full flex-1 overflow-auto outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-accent"
        onKeyDown={(event) => {
          if (showSkeleton || sorted.length === 0) return;
          const extend = event.shiftKey && selectionMode === "range";
          const page = Math.max(1, Math.floor(height / Math.max(rowHeight, 1)) - 1);

          switch (event.key) {
            case "ArrowDown":
              event.preventDefault();
              move(activeIndex + 1, extend);
              return;
            case "ArrowUp":
              event.preventDefault();
              move(activeIndex - 1, extend);
              return;
            case "PageDown":
              event.preventDefault();
              move(activeIndex + page, extend);
              return;
            case "PageUp":
              event.preventDefault();
              move(activeIndex - page, extend);
              return;
            case "Home":
              event.preventDefault();
              move(0, extend);
              return;
            case "End":
              event.preventDefault();
              move(sorted.length - 1, extend);
              return;
            case " ":
            case "Enter":
              event.preventDefault();
              select(activeIndex, event.ctrlKey || event.metaKey ? "toggle" : "replace");
              return;
            case "a":
              if (!event.ctrlKey && !event.metaKey) return;
              if (selectionMode !== "range") return;
              event.preventDefault();
              setSelected(new Set(sorted.map(getRowId)));
              return;
            default:
          }
        }}
      >
        <div style={{ width: Math.max(totalWidth, 1) }}>
          <div className={cn(stickyHeader && "sticky top-0 z-20")}>
            <HeaderRow
              columns={columns}
              sorts={sorts}
              sortable={sortable}
              multiSort={multiSort}
              resizable={resizableColumns}
              height={headerHeight}
              accent={accent}
              widthOf={widthOf}
              onToggleSort={toggleSort}
              onBeginResize={beginResize}
            />
          </div>

          {showSkeleton ? (
            <SkeletonRows
              columns={columns}
              count={skeletonCount}
              rowHeight={rowHeight}
              widthOf={widthOf}
              animate={!reducedMotion}
            />
          ) : sorted.length === 0 ? (
            <p className="p-8 text-center text-xs text-ink-mute">{emptyMessage}</p>
          ) : (
            <div style={{ height: totalHeight, position: "relative" }}>
              <div style={{ transform: `translateY(${offsetTop}px)` }}>
                <BodyRows
                  rows={slice}
                  columns={columns}
                  first={first}
                  rowHeight={rowHeight}
                  zebra={zebra}
                  accent={accent}
                  gridId={gridId}
                  activeIndex={activeIndex}
                  selected={selected}
                  widthOf={widthOf}
                  rowId={getRowId}
                  onPick={(index, event) => {
                    setActiveIndex(index);
                    select(
                      index,
                      event.shiftKey
                        ? "extend"
                        : event.ctrlKey || event.metaKey
                          ? "toggle"
                          : "replace",
                    );
                  }}
                />
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
```

### 2. `components/registry/data-grid/types.ts` — supporting file, required

```tsx
import type { ReactNode } from "react";

export type CellValue = string | number | boolean | null;

export interface DataGridColumn<Row> {
  key: string;
  header: string;
  width?: number;
  align?: "left" | "right";
  value: (row: Row) => CellValue;
  render?: (row: Row) => ReactNode;
}

export type SortDirection = "asc" | "desc";

export interface SortSpec {
  key: string;
  direction: SortDirection;
}

export type SelectionMode = "none" | "single" | "range";
```

### 3. `components/registry/data-grid/util.ts` — supporting file, required

```tsx
import type { CellValue, DataGridColumn, SortSpec } from "./types";

export function clamp(value: number, min: number, max: number): number {
  return value < min ? min : value > max ? max : value;
}

export function compareValues(a: CellValue, b: CellValue): number {
  if (a === b) return 0;
  if (a === null) return 1;
  if (b === null) return -1;

  if (typeof a === "number" && typeof b === "number") return a - b;
  if (typeof a === "boolean" && typeof b === "boolean") return Number(a) - Number(b);

  return String(a).localeCompare(String(b), undefined, {
    numeric: true,
    sensitivity: "base",
  });
}

export function sortRows<Row>(
  rows: Row[],
  sorts: SortSpec[],
  columns: DataGridColumn<Row>[],
): Row[] {
  if (sorts.length === 0) return rows;

  const lookup = new Map(columns.map((column) => [column.key, column]));

  return [...rows].sort((left, right) => {
    for (const sort of sorts) {
      const column = lookup.get(sort.key);
      if (!column) continue;
      const result = compareValues(column.value(left), column.value(right));
      if (result !== 0) return sort.direction === "asc" ? result : -result;
    }
    return 0;
  });
}

export function rangeBetween(a: number, b: number): number[] {
  const from = Math.min(a, b);
  const to = Math.max(a, b);
  const out: number[] = [];
  for (let i = from; i <= to; i++) out.push(i);
  return out;
}

export function cycleSort(
  sorts: SortSpec[],
  key: string,
  additive: boolean,
): SortSpec[] {
  const existing = sorts.find((sort) => sort.key === key);
  const others = additive ? sorts.filter((sort) => sort.key !== key) : [];

  if (!existing) return [...others, { key, direction: "asc" }];
  if (existing.direction === "asc") return [...others, { key, direction: "desc" }];
  return others;
}

export function formatCell(value: CellValue): string {
  if (value === null) return "—";
  if (typeof value === "boolean") return value ? "Yes" : "No";
  return String(value);
}
```

### 4. `components/registry/data-grid/use-columns.ts` — supporting file, required

```tsx
"use client";

import { useCallback, useMemo, useRef, useState } from "react";
import type { DataGridColumn, SortSpec } from "./types";
import { clamp, cycleSort } from "./util";

export interface ColumnState<Row> {
  columns: DataGridColumn<Row>[];
  sorts: SortSpec[];
  widthOf(key: string): number;
  toggleSort(key: string, additive: boolean): void;
  beginResize(key: string, startX: number): (clientX: number) => void;
}

const DEFAULT_WIDTH = 160;

export function useColumns<Row>(
  columns: DataGridColumn<Row>[],
  minColumnWidth: number,
): ColumnState<Row> {
  const [widths, setWidths] = useState<Record<string, number>>({});
  const [sorts, setSorts] = useState<SortSpec[]>([]);

  const anchor = useRef<{ key: string; startX: number; startWidth: number } | null>(null);

  const declared = useMemo(() => {
    const map = new Map<string, number>();
    for (const column of columns) map.set(column.key, column.width ?? DEFAULT_WIDTH);
    return map;
  }, [columns]);

  const widthOf = useCallback(
    (key: string) => widths[key] ?? declared.get(key) ?? DEFAULT_WIDTH,
    [declared, widths],
  );

  const toggleSort = useCallback((key: string, additive: boolean) => {
    setSorts((current) => cycleSort(current, key, additive));
  }, []);

  const beginResize = useCallback(
    (key: string, startX: number) => {
      anchor.current = { key, startX, startWidth: widthOf(key) };
      return (clientX: number) => {
        const start = anchor.current;
        if (!start) return;
        const next = clamp(
          start.startWidth + (clientX - start.startX),
          minColumnWidth,
          1200,
        );
        setWidths((current) =>
          current[start.key] === next ? current : { ...current, [start.key]: next },
        );
      };
    },
    [minColumnWidth, widthOf],
  );

  return { columns, sorts, widthOf, toggleSort, beginResize };
}
```

### 5. `components/registry/data-grid/use-virtual-rows.ts` — supporting file, required

```tsx
"use client";

import { useCallback, useRef, useState, type RefObject } from "react";
import { useAnimationLoop } from "@/hooks/use-animation-loop";

export interface VirtualWindow {
  viewportRef: RefObject<HTMLDivElement | null>;
  first: number;
  last: number;
  totalHeight: number;
  offsetTop: number;
  height: number;
  onScroll(): void;
  scrollRowIntoView(index: number): void;
}

export function useVirtualRows(
  rowCount: number,
  rowHeight: number,
  overscan: number,
  leadingOffset: number,
): VirtualWindow {
  const viewportRef = useRef<HTMLDivElement>(null);
  const [scrollTop, setScrollTop] = useState(0);
  const [height, setHeight] = useState(0);

  useAnimationLoop({
    target: viewportRef,
    halted: true,
    paintWhenHalted: false,
    onResize: (metrics) => setHeight(metrics.height),
  });

  const onScroll = useCallback(() => {
    const viewport = viewportRef.current;
    if (viewport) setScrollTop(viewport.scrollTop);
  }, []);

  const scrollRowIntoView = useCallback(
    (index: number) => {
      const viewport = viewportRef.current;
      if (!viewport) return;
      const top = leadingOffset + index * rowHeight;
      const bottom = top + rowHeight;
      if (top < viewport.scrollTop + leadingOffset) {
        viewport.scrollTop = top - leadingOffset;
      } else if (bottom > viewport.scrollTop + viewport.clientHeight) {
        viewport.scrollTop = bottom - viewport.clientHeight;
      }
    },
    [leadingOffset, rowHeight],
  );

  const safeHeight = Math.max(rowHeight, 1);
  const past = Math.max(0, scrollTop - leadingOffset);
  const first = Math.max(0, Math.floor(past / safeHeight) - overscan);
  const span = Math.ceil(height / safeHeight) + overscan * 2 + 1;
  const last = Math.min(rowCount, first + span);

  return {
    viewportRef,
    first,
    last,
    totalHeight: rowCount * rowHeight,
    offsetTop: first * rowHeight,
    height,
    onScroll,
    scrollRowIntoView,
  };
}
```

### 6. `components/registry/data-grid/header-row.tsx` — supporting file, required

```tsx
"use client";

import { ArrowDown, ArrowUp, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import type { DataGridColumn, SortSpec } from "./types";

export default function HeaderRow<Row>({
  columns,
  sorts,
  sortable,
  multiSort,
  resizable,
  height,
  accent,
  widthOf,
  onToggleSort,
  onBeginResize,
}: {
  columns: DataGridColumn<Row>[];
  sorts: SortSpec[];
  sortable: boolean;
  multiSort: boolean;
  resizable: boolean;
  height: number;
  accent: string;
  widthOf: (key: string) => number;
  onToggleSort: (key: string, additive: boolean) => void;
  onBeginResize: (key: string, startX: number) => (clientX: number) => void;
}) {
  return (
    <div role="row" className="flex border-b border-hairline bg-panel" style={{ height }}>
      {columns.map((column) => {
        const rank = sorts.findIndex((sort) => sort.key === column.key);
        const sort = rank === -1 ? null : sorts[rank];

        return (
          <div
            key={column.key}
            role="columnheader"
            aria-sort={
              !sort ? "none" : sort.direction === "asc" ? "ascending" : "descending"
            }
            className="relative flex shrink-0 items-center border-r border-hairline last:border-r-0"
            style={{ width: widthOf(column.key) }}
          >
            <button
              type="button"
              disabled={!sortable}
              onClick={(event) => onToggleSort(column.key, multiSort && event.shiftKey)}
              className={cn(
                "flex h-full w-full items-center gap-1.5 px-3 text-left outline-none transition-colors",
                "font-display text-[10px] tracking-[0.16em] uppercase",
                sort ? "text-ink" : "text-ink-mute",
                sortable && "hover:text-ink focus-visible:text-ink",
                !sortable && "cursor-default",
              )}
              style={sort ? { color: accent } : undefined}
            >
              <span className="truncate">{column.header}</span>
              {sortable ? (
                <span className="ml-auto flex shrink-0 items-center gap-0.5 [&_svg]:h-3 [&_svg]:w-3">
                  {!sort ? (
                    <ChevronsUpDown className="opacity-30" />
                  ) : sort.direction === "asc" ? (
                    <ArrowUp />
                  ) : (
                    <ArrowDown />
                  )}
                  {multiSort && sorts.length > 1 && rank !== -1 ? (
                    <span className="font-mono text-[9px] tabular-nums">{rank + 1}</span>
                  ) : null}
                </span>
              ) : null}
            </button>

            {resizable ? (
              <span
                role="separator"
                aria-orientation="vertical"
                aria-label={`Resize ${column.header}`}
                onPointerDown={(event) => {
                  event.preventDefault();
                  event.stopPropagation();
                  const target = event.currentTarget;
                  target.setPointerCapture(event.pointerId);
                  const move = onBeginResize(column.key, event.clientX);

                  const onMove = (moveEvent: PointerEvent) => move(moveEvent.clientX);
                  const onUp = () => {
                    target.removeEventListener("pointermove", onMove);
                    target.removeEventListener("pointerup", onUp);
                    target.removeEventListener("pointercancel", onUp);
                  };
                  target.addEventListener("pointermove", onMove);
                  target.addEventListener("pointerup", onUp);
                  target.addEventListener("pointercancel", onUp);
                }}
                className="absolute top-0 right-0 z-10 h-full w-[9px] translate-x-1/2 cursor-col-resize touch-none"
              >
                <span className="pointer-events-none absolute inset-y-0 left-1/2 w-px bg-transparent transition-colors hover:bg-current" />
              </span>
            ) : null}
          </div>
        );
      })}
    </div>
  );
}
```

### 7. `components/registry/data-grid/body-rows.tsx` — supporting file, required

```tsx
"use client";

import { cn } from "@/lib/utils";
import type { DataGridColumn } from "./types";
import { formatCell } from "./util";

export default function BodyRows<Row>({
  rows,
  columns,
  first,
  rowHeight,
  zebra,
  accent,
  gridId,
  activeIndex,
  selected,
  widthOf,
  rowId,
  onPick,
}: {
  rows: Row[];
  columns: DataGridColumn<Row>[];
  first: number;
  rowHeight: number;
  zebra: boolean;
  accent: string;
  gridId: string;
  activeIndex: number;
  selected: ReadonlySet<string>;
  widthOf: (key: string) => number;
  rowId: (row: Row) => string;
  onPick: (index: number, event: React.MouseEvent) => void;
}) {
  return (
    <>
      {rows.map((row, offset) => {
        const index = first + offset;
        const id = rowId(row);
        const isSelected = selected.has(id);
        const isActive = index === activeIndex;

        return (
          <div
            key={id}
            id={`${gridId}-row-${index}`}
            role="row"
            aria-rowindex={index + 2}
            aria-selected={isSelected}
            onMouseDown={(event) => onPick(index, event)}
            className={cn(
              "flex cursor-default items-stretch border-b border-hairline/60",
              zebra && index % 2 === 1 && "bg-raised/40",
              isSelected ? "bg-accent-muted/25" : "hover:bg-raised/60",
            )}
            style={{
              height: rowHeight,
              boxShadow: isActive ? `inset 2px 0 0 0 ${accent}` : undefined,
            }}
          >
            {columns.map((column) => (
              <div
                key={column.key}
                role="gridcell"
                className={cn(
                  "flex shrink-0 items-center overflow-hidden px-3 text-xs whitespace-nowrap",
                  column.align === "right"
                    ? "justify-end text-right font-mono tabular-nums"
                    : "text-left",
                  isSelected ? "text-ink" : "text-ink-dim",
                )}
                style={{ width: widthOf(column.key) }}
              >
                <span className="truncate">
                  {column.render ? column.render(row) : formatCell(column.value(row))}
                </span>
              </div>
            ))}
          </div>
        );
      })}
    </>
  );
}
```

### 8. `components/registry/data-grid/skeleton-rows.tsx` — supporting file, required

```tsx
"use client";

import { cn } from "@/lib/utils";
import type { DataGridColumn } from "./types";

const WIDTHS = [0.82, 0.55, 0.7, 0.4, 0.9, 0.62, 0.75, 0.5];

export default function SkeletonRows<Row>({
  columns,
  count,
  rowHeight,
  widthOf,
  animate,
}: {
  columns: DataGridColumn<Row>[];
  count: number;
  rowHeight: number;
  widthOf: (key: string) => number;
  animate: boolean;
}) {
  return (
    <>
      {Array.from({ length: count }, (_, index) => (
        <div
          key={index}
          role="row"
          aria-hidden
          className="flex items-stretch border-b border-hairline/60"
          style={{ height: rowHeight }}
        >
          {columns.map((column, column_index) => (
            <div
              key={column.key}
              className="flex shrink-0 items-center px-3"
              style={{ width: widthOf(column.key) }}
            >
              <span
                className={cn(
                  "h-2 rounded-full bg-ink-mute/25",
                  animate && "animate-pulse",
                )}
                style={{
                  width: `${WIDTHS[(index + column_index) % WIDTHS.length] * 100}%`,
                  animationDelay: animate ? `${((index * 3 + column_index) % 6) * 90}ms` : undefined,
                }}
              />
            </div>
          ))}
        </div>
      ))}
    </>
  );
}
```

### 9. `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));
}
```

### 10. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `rowHeight` | `number` | `34` | Height of one row. Fixed rather than measured, and that is the whole performance story — a constant height makes the first visible row a division instead of a search, so scrolling to row 90,000 costs exactly what scrolling to row 3 costs. Range 22–72 px. |
| `headerHeight` | `number` | `34` | Height of the header. It shares the body's scroller, so this is also the offset the window calculation has to subtract from `scrollTop` — get it wrong and the rendered slice lags the scroll by exactly one header. Range 24–64 px. |
| `overscan` | `number` | `6` | Extra rows rendered above and below the fold. At 0 you can out-scroll the renderer and see white bands at the leading edge; past about fifteen you are paying for rows nobody will reach before they are recycled. Range 0–30. |
| `minColumnWidth` | `number` | `80` | Floor a column can be dragged to. Without one a column can be collapsed to nothing and then cannot be grabbed again, because the handle it would be grabbed by has no width either. Range 40–240 px. |
| `stickyHeader` | `boolean` | `true` | Pin the header while the body scrolls. It sits inside the same scroller rather than in a second one kept in sync by hand — that synchronisation is never actually synchronous, and the header lagging the body on a fast horizontal flick is its signature. |
| `resizableColumns` | `boolean` | `true` | Allow dragging column edges. The handle is a sibling of the sort button, not a child: nested, every resize would end by firing a click on the header and re-sorting the grid you were only trying to widen. |
| `sortable` | `boolean` | `true` | Allow clicking a header to sort. The cycle has three states — ascending, descending, unsorted — because without the third there is no way back to the order the data arrived in, and for a feed that is most-recent-first one click destroys it permanently. |
| `multiSort` | `boolean` | `true` | Shift-click a second header to sort by it as a tiebreak. The rank is printed beside each arrow: two arrows with no numbers do not say which key is primary, and that is the entire difference between two different orderings. |
| `selectionMode` | `"none" | "single" | "range"` | `"range"` | How rows may be selected. Range adds Shift-click for a span and Ctrl/Cmd-click for a toggle, both anchored the same way the keyboard's Shift+Arrow is — one code path, so the two can never disagree about what is selected. |
| `zebra` | `boolean` | `true` | Band alternate rows. Computed from the absolute row index rather than from the position inside the rendered window, which is what stops the stripes from crawling as you scroll. |
| `showSkeleton` | `boolean` | `false` | Render placeholder rows instead of data. They hold the exact row height and column widths the real rows will, so nothing moves when the data lands — a spinner in an empty box only promises a wait, and then rearranges the page at the end of it. |
| `accent` | `string (hex)` | `"#a855f7"` | Selection wash, the active-row marker down the left edge, and the colour a sorted header takes. |

## Usage

```tsx
import DataGrid from "@/components/registry/data-grid/data-grid";

<DataGrid
  rowHeight={34}
  headerHeight={34}
  overscan={6}
  minColumnWidth={80}
  stickyHeader={true}
  resizableColumns={true}
  sortable={true}
  multiSort={true}
  selectionMode="range"
  zebra={true}
  showSkeleton={false}
  accent="#a855f7"
/>
```

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`.
- The `touch-action: none` on the hit target is load-bearing — without it a finger drag scrolls the page instead of driving the effect. Do not strip it as a stray utility class.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- `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.
- The supporting files are part of the component, not examples. Copy every file listed, preserving the directory layout — they import each other by relative path.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Add the design tokens to my global CSS, or map them to tokens I already have.
4. Wire the component into the place I point you at, with sensible props for that context.
5. 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.
