# Data Grid

> Edit a native table with keyboard movement, drag or Shift ranges, clipboard paste, fill-down, undo, and redo.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/data-grid`
- File: `src/components/haze/ui/data-grid.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/button, @haze/sortable-data-table, @haze/utils
- Docs page: https://hazeui.com/ui/data-grid

## Use when
- People edit a small to medium budget or inventory in place.
- Copying rectangular values between the grid and a spreadsheet speeds up entry.

## Avoid when
- The dataset needs server paging or virtualization. Use a data-source integration around a paged table.

## Alternatives
- [sortable-data-table](https://hazeui.com/ui/sortable-data-table.md)
- [inline-edit](https://hazeui.com/ui/inline-edit.md)
- [table](https://hazeui.com/ui/table.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique table ID and keyboard instructions prefix. |
| caption | `string` |  | no | Visible name for the editable dataset. |
| columns | `Column[]` |  | no | Column keys, labels, numeric flags and optional editable false. |
| rows | `Record<string, string \| number>[]` |  | no | Initial values. The browser dispatches changes for the host to persist. |
| class | `string` |  | no | Additional classes on the component wrapper. |

## Accessibility
- Only one data cell enters the tab order. Arrow keys move through cells, Shift extends a rectangular range, and Enter opens a labelled input.
- Numeric cells reject empty and nonfinite edits. All edits emit haze:grid-change for application persistence. Static markup exposes the full native table.
- Key Arrows / Home / End: Move the active cell. Hold Shift to extend the selected range.
- Key Enter / F2 / Escape: Edit the cell, commit, or cancel.
- Key Control / Command C, V, Z: Copy, paste or undo. Shift Z redoes.

## Agent prompts

### Install and use

Install the Haze UI component "Data Grid" with `npx shadcn@latest add @haze/data-grid`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import DataGrid from "@/components/haze/ui/data-grid.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/data-grid.md

### Customize with real content

Adapt the Haze data-grid ui for our product. Replace the demo values of these props with our real content: id, caption, columns, rows, class. Keep the layout, the heading level rules and these accessibility details: Only one data cell enters the tab order. Arrow keys move through cells, Shift extends a rectangular range, and Enter opens a labelled input. Numeric cells reject empty and nonfinite edits. All edits emit haze:grid-change for application persistence. Static markup exposes the full native table. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using data-grid, check it fits: use it when people edit a small to medium budget or inventory in place.; copying rectangular values between the grid and a spreadsheet speeds up entry.. Avoid it when the dataset needs server paging or virtualization. use a data-source integration around a paged table.. Alternatives: @haze/sortable-data-table, @haze/inline-edit, @haze/table.

## Example requests that should lead here
- Create an editable release budget with range paste, fill-down and undo.

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";
import { Check, Clipboard } from "@lucide/astro";
import SortableDataTable from "./sortable-data-table.astro";
import Button from "./button.astro";
interface Props {
  id: string;
  caption?: string;
  columns?: { key: string; label: string; numeric?: boolean; editable?: boolean }[];
  rows?: Record<string, string | number>[];
  class?: string;
}
const { id, caption = "Release budget", class: className,
  columns = [{ key: "item", label: "Item" }, { key: "planned", label: "Planned", numeric: true }, { key: "actual", label: "Actual", numeric: true }],
  rows = [{ item: "Design", planned: 2400, actual: 2100 }, { item: "Development", planned: 5200, actual: 4800 }, { item: "Review", planned: 1600, actual: 1400 }],
} = Astro.props;
---
<div data-haze-data-grid class={cn("grid min-w-0 gap-3", className)}>
  <p id={`${id}-help`} class="text-xs/5 text-muted-foreground">Use arrows to move, Shift to select a range, Enter to edit, and Control or Command Z to undo.</p>
  <div data-grid-actions hidden class="flex flex-wrap gap-2 [&[hidden]]:hidden">
    <Button data-grid-undo size="sm" variant="outline" disabled>Undo</Button>
    <Button data-grid-redo size="sm" variant="outline" disabled>Redo</Button>
    <Button data-grid-copy size="sm" variant="outline" class="group" data-state="idle"><span aria-hidden="true" class="grid shrink-0 place-items-center"><Clipboard class="[grid-area:1/1] group-data-[state=copied]:invisible" /><Check class="invisible [grid-area:1/1] group-data-[state=copied]:visible motion-safe:group-data-[state=copied]:animate-pop" /></span>Copy range</Button>
    <Button data-grid-fill size="sm" variant="outline">Fill down</Button>
  </div>
  <SortableDataTable {id} {caption} {columns} {rows} editable selectable={false} searchable={false} />
  <p data-grid-status role="status" class="text-xs/5 text-muted-foreground">Editing is enabled when scripts are available.</p>
</div>
<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const table = root.querySelector<HTMLTableElement>("table");
    const status = root.querySelector<HTMLElement>("[data-grid-status]");
    if (!table || !status) return;
    const undo = root.querySelector<HTMLButtonElement>("[data-grid-undo]")!;
    const redo = root.querySelector<HTMLButtonElement>("[data-grid-redo]")!;
    const cells = () => Array.from(table.querySelectorAll<HTMLTableCellElement>("[data-record]:not([hidden]) [data-cell]"));
    const width = table.querySelectorAll("th[data-column]").length;
    if (!width || !cells().length) return;
    let active = cells()[0], anchor = active;
    type Change = { cell: HTMLTableCellElement; before: string; after: string };
    const past: Change[][] = [], future: Change[][] = [];
    let editor: HTMLInputElement | null = null;
    let dragging = false;
    const region = table.closest<HTMLElement>("[role=region]")!;
    const render = (focus = true) => {
      const list = cells(), a = list.indexOf(anchor), b = list.indexOf(active);
      const left = Math.min(a % width, b % width), right = Math.max(a % width, b % width);
      const top = Math.min(Math.floor(a / width), Math.floor(b / width)), bottom = Math.max(Math.floor(a / width), Math.floor(b / width));
      list.forEach((cell, index) => {
        const row = Math.floor(index / width), col = index % width;
        cell.toggleAttribute("data-selected", row >= top && row <= bottom && col >= left && col <= right);
        cell.toggleAttribute("data-active", cell === active);
        cell.tabIndex = cell === active ? 0 : -1;
      });
      if (focus) active.focus({ preventScroll: true });
      undo.disabled = past.length === 0;
      redo.disabled = future.length === 0;
    };
    const apply = (changes: Change[], remember = true) => {
      if (!changes.length) return;
      changes.forEach(({ cell, after }) => { cell.textContent = after; });
      if (remember) { past.push(changes); future.length = 0; }
      render();
      status.textContent = `${changes.length} ${changes.length === 1 ? "cell" : "cells"} updated.`;
      root.dispatchEvent(new CustomEvent("haze:grid-change", { bubbles: true, detail: { changes: changes.map(change => ({ row: change.cell.closest<HTMLElement>("[data-record]")?.dataset.recordKey, column: change.cell.dataset.field, value: change.after })) } }));
    };
    const commit = () => {
      if (!editor) return true;
      const input = editor, cell = input.parentElement as HTMLTableCellElement;
      if (!input.checkValidity() || (cell.hasAttribute("data-numeric") && (!input.value.trim() || !Number.isFinite(Number(input.value))))) {
        input.setAttribute("aria-invalid", "true");
        status.textContent = "Enter a finite number for this column.";
        input.focus();
        return false;
      }
      const before = input.dataset.previous ?? "", after = input.value;
      editor = null;
      cell.textContent = before;
      if (before !== after) apply([{ cell, before, after }]);
      return true;
    };
    const edit = () => {
      if (editor || active.hasAttribute("data-readonly")) return;
      const input = document.createElement("input");
      input.type = active.hasAttribute("data-numeric") ? "number" : "text";
      if (input.type === "number") input.step = "any";
      input.value = active.textContent ?? "";
      input.dataset.previous = input.value;
      const heads = Array.from(table.querySelectorAll<HTMLElement>("[data-column]"));
      const column = heads.find(head => head.dataset.column === active.dataset.field);
      input.setAttribute("aria-label", `${column?.textContent?.trim() ?? "Cell"}, row ${Math.floor(cells().indexOf(active) / width) + 1}`);
      input.className = "absolute inset-0 w-full min-w-0 border border-ring bg-card px-2 text-xs text-foreground outline-none";
      active.textContent = "";
      active.append(input);
      editor = input;
      input.focus();
      input.select();
      input.addEventListener("blur", () => { if (editor === input) commit(); });
    };
    table.addEventListener("pointerdown", event => {
      const cell = (event.target as Element).closest<HTMLTableCellElement>("[data-cell]");
      if (!cell || event.target === editor || !commit()) return;
      if (!event.shiftKey) anchor = cell;
      active = cell;
      dragging = event.pointerType === "mouse";
      render();
    });
    table.addEventListener("pointerover", event => {
      if (!dragging || !event.buttons) return;
      const cell = (event.target as Element).closest<HTMLTableCellElement>("[data-cell]");
      if (cell) { active = cell; render(false); }
    });
    root.addEventListener("haze:grid-pointer-end", () => {
      if (dragging) { dragging = false; render(); }
    });
    table.addEventListener("dblclick", event => { if ((event.target as Element).closest("[data-cell]")) edit(); });
    table.addEventListener("keydown", event => {
      if (!active.contains(event.target as Node)) return;
      if (editor) {
        if (event.key === "Escape") { event.preventDefault(); const input = editor; editor = null; active.textContent = input.dataset.previous ?? ""; render(); }
        else if (event.key === "Enter") { event.preventDefault(); if (commit()) render(); }
        return;
      }
      const list = cells(), index = list.indexOf(active);
      const moves: Record<string, number> = { ArrowRight: Math.min(list.length - 1, index + 1), ArrowLeft: Math.max(0, index - 1), ArrowDown: Math.min(list.length - 1, index + width), ArrowUp: Math.max(0, index - width), Home: Math.floor(index / width) * width, End: Math.min(list.length - 1, Math.floor(index / width) * width + width - 1) };
      if (event.key in moves) { event.preventDefault(); active = list[moves[event.key]]; if (!event.shiftKey) anchor = active; render(); active.scrollIntoView({ block: "nearest", inline: "nearest" }); }
      else if (event.key === "Enter" || event.key === "F2") { event.preventDefault(); edit(); }
      else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "z") { event.preventDefault(); (event.shiftKey ? redo : undo).click(); }
    });
    const selected = () => cells().filter(cell => cell.hasAttribute("data-selected"));
    const copy = () => selected().reduce((text, cell, index, list) => text + (index ? list[index - 1].parentElement === cell.parentElement ? "\t" : "\n" : "") + cell.textContent, "");
    const paste = (text: string) => {
      if (!text) return;
      const list = cells(), start = list.indexOf(active);
      const changes: Change[] = [];
      text.replace(/\r\n?/g, "\n").replace(/\n$/, "").split("\n").forEach((line, row) => line.split("\t").forEach((after, col) => {
        if (start % width + col >= width) return;
        const cell = list[start + row * width + col];
        if (!cell || cell.hasAttribute("data-readonly") || (cell.hasAttribute("data-numeric") && (!after.trim() || !Number.isFinite(Number(after))))) return;
        changes.push({ cell, before: cell.textContent ?? "", after });
      }));
      apply(changes);
    };
    table.addEventListener("copy", event => { if (editor) return; event.preventDefault(); event.clipboardData?.setData("text/plain", copy()); });
    table.addEventListener("paste", event => { if (editor) return; event.preventDefault(); paste(event.clipboardData?.getData("text/plain") ?? ""); });
    const copyBtn = root.querySelector<HTMLElement>("[data-grid-copy]");
    let copyTimer: number | undefined;
    copyBtn?.addEventListener("click", async () => {
      if (!commit()) return;
      try { await navigator.clipboard.writeText(copy()); status.textContent = "Range copied."; copyBtn.dataset.state = "copied"; window.clearTimeout(copyTimer); copyTimer = window.setTimeout(() => { copyBtn.dataset.state = "idle"; }, 2000); } catch { status.textContent = "Focus a cell and press Control or Command C to copy the range."; active.focus(); }
    });
    root.querySelector("[data-grid-fill]")?.addEventListener("click", () => {
      if (!commit()) return;
      const firsts = new Map<string, string>();
      const changes = selected().flatMap(cell => {
        const key = cell.dataset.field!;
        const before = cell.textContent ?? "";
        if (!firsts.has(key)) { firsts.set(key, before); return []; }
        const after = firsts.get(key)!;
        return cell.hasAttribute("data-readonly") || after === before || (cell.hasAttribute("data-numeric") && (!after.trim() || !Number.isFinite(Number(after)))) ? [] : [{ cell, before, after }];
      });
      apply(changes);
    });
    undo.addEventListener("click", () => { if (!commit()) return; const changes = past.pop(); if (changes) { future.push(changes); apply(changes.map(change => ({ ...change, after: change.before })), false); status.textContent = "Edit undone."; } });
    redo.addEventListener("click", () => { if (!commit()) return; const changes = future.pop(); if (changes) { past.push(changes); apply(changes, false); status.textContent = "Edit restored."; } });
    root.addEventListener("haze:table-before-sort", event => { if (!commit()) event.preventDefault(); });
    root.addEventListener("haze:table-sort", () => render(false));
    region.setAttribute("aria-describedby", `${table.id}-help`);
    root.querySelector<HTMLElement>("[data-grid-actions]")!.hidden = false;
    status.textContent = "Select a cell to begin editing.";
    render(false);
    root.setAttribute("data-enhanced", "");
  }
  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-data-grid]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-data-grid-listener")) {
    document.documentElement.setAttribute("data-haze-data-grid-listener", "");
    document.addEventListener("astro:page-load", init);
    const finish = () => document.querySelectorAll<HTMLElement>("[data-haze-data-grid]").forEach(root => root.dispatchEvent(new Event("haze:grid-pointer-end")));
    document.addEventListener("pointerup", finish);
    document.addEventListener("pointercancel", finish);
  }
</script>
```
