# Data Grid API and keyboard hooks

> The imperative grid instance and custom keyboard handling.

Canonical: https://salmonui.dev/docs/data-grid/api

The grid exposes an imperative instance through its ref, through
`onReady(api)` after the first commit, and to components rendered inside
the grid (templates, toolbar content) through `useDataGridApi()`. It reads
the rows of the current view; resolves a row, a row from any
element inside it, or a cell by ids; returns the data source and
the primary-key fields; scrolls to a row or a column; and
moves keyboard focus to the grid or a specific cell. Every method
works by row id and column id, so it is independent of virtualization and
of the current sort. The generated [API reference](https://salmonui.dev/docs/reference) lists
the signature of every exported symbol, including the full `DataGridApi`.

Scrolling: `api.scrollToRow(rowId, { align })` and
`api.scrollToColumn(field, { align })` bring a row or a center column into
view (`align` is `'nearest'` by default, or `'start'`, `'center'`,
`'end'`; pinned columns are always in view). `api.scrollTo({ top, left })`
scrolls by offset:
`top` is the offset of the first body row in px (row `i` of a fixed
36 px grid starts at `36 * i`, also beyond the browser's height limit,
where the grid compresses the scroll range), `left` is the offset of the
center columns from the inline start (positive in RTL too). An omitted
axis keeps its position and both are clamped to the scroll range.
`api.getRenderedRange()` returns the rendered row and column ranges.

Rows by position: `api.getRowIdAt(index)` returns the id of the row at a
position of the current view and
`api.getRowIndex(rowId)` is its inverse; `api.getRow(rowId)` returns the
row data. `api.getRowInfo(target)` takes a row id or any element inside a
row (a cell or custom template content) and
returns the row, its index, the field of the cell and the row and cell
elements. `api.getRowElement(rowId)` and `api.getCellElement(rowId,
field)` return the rendered elements; outside the rendered (virtualized)
window they return `null`, as does the `element` of `getRowInfo`.

Every key pressed in the grid first reaches a key handler with the bound
command and the focused cell; the handler can suppress the built-in
behavior: the `onKeyDown(ctx)` prop receives the
`command`, the `context`, the focused `rowId` and `field` and the
`nativeEvent`, and `ctx.preventDefault()` suppresses the binding;
`api.registerKeyHandler(command, handler, { priority })` adds a handler for
one command and returns its unregister function. The `keyBindings` prop
rebinds built-in commands to other key combinations
(`{ 'selection.selectAll': ['Mod+Shift+L'] }`); the default table is
`DEFAULT_KEY_BINDINGS`.

```tsx
<DataGrid
  data={orders}
  columns={columns}
  keyBindings={{ 'selection.selectAll': ['Mod+Shift+L'] }}
  onKeyDown={(ctx) => {
    if (ctx.command === 'edit.delete' && !confirm('Delete?')) ctx.preventDefault();
  }}
/>
```

`api.setLoading(true)` / `api.setLoading(false)` show and hide the loading
indicator, and `api.refresh()` re-reads the data with the current
query; headers and columns need no refresh method because they
render from props. Both are shown
on the [data sources](https://salmonui.dev/docs/data-grid/data-sources) page.

### Live demo: Data Grid API and keyboard hooks

Live demo: https://salmonui.dev/demos/data-grid/grid-api

The imperative grid instance - focus a cell, scroll to a row or to an offset (scrollTo), read view rows, the primary-key fields, the data source, cells, row info and the focused cell - plus a rebound key and a custom key handler.

`Demo.tsx`:

```tsx
'use client';

import { useRef } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(5_000, 71);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];

export default function DataGridApiDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.focusCell('ORD-12500', 'customer')}>
          Focus ORD-12500 / Customer
        </Button>
        <Button variant="outline" onClick={() => api.current?.scrollToRow('ORD-14999', { align: 'end' })}>
          Scroll to the last order
        </Button>
        <Button variant="outline" onClick={() => api.current?.scrollTo({ top: 36 * 100 })}>
          Scroll to offset 3,600 px
        </Button>
        <Button variant="outline" onClick={() => push(`view rows: ${api.current?.getViewRows().length ?? 0}; primary key fields: ${JSON.stringify(api.current?.getPrimaryKeyFields() ?? null)}; source mode: ${api.current?.getDataSource().mode ?? '-'}`)}>
          Read view, key and data source
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            const cell = api.current?.getCell('ORD-10003', 'amount');
            push(`getCell(ORD-10003, amount): ${cell ? JSON.stringify({ value: cell.value, formatted: cell.formattedValue }) : 'undefined'}`);
          }}
        >
          Read a cell
        </Button>
        <Button variant="outline" onClick={() => push(`focused: ${JSON.stringify(api.current?.getFocusedCell() ?? null)}`)}>
          Read focused cell
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders driven through the grid API"
        data={orders}
        columns={columns}
        height={320}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        // Custom keyboard handling: Mod+Shift+K is rebound to select-all; the `g` key logs the row under focus.
        keyBindings={{ 'selection.selectAll': ['Mod+Shift+K'] }}
        onKeyDown={(ctx) => {
          if (ctx.nativeEvent.key === 'g' && ctx.rowId !== null) {
            ctx.preventDefault();
            const info = api.current?.getRowInfo(ctx.rowId);
            push(`key g on ${ctx.rowId}: view index ${info?.rowIndex ?? '?'}, ${info?.row?.customer ?? ""}`);
          }
        }}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## Elements, engine, modules and commands

The grid renders one element tree. `api.element` is the root;
`api.getPartElement(part)` returns the first rendered element of a part
(`'header'`, `'body'`, `'pager'`, `'toolbar'`, ...) and
`api.getHeaderElement(field)` a header cell. The grid is one
`role="grid"` tree with no separate header, content or frozen tables
([Accessibility](https://salmonui.dev/docs/data-grid/accessibility)), so there are no
per-table getters: use `getPartElement('header')`,
`getPartElement('body')` and `getPartElement('pager')`. Row
and cell elements are `null` outside the rendered window: call
`scrollToRow` first, or read the data with `getRow`.

`api.engine` is the core engine behind the grid. Custom renderers read
`engine.getCellSnapshot(rowId, columnId)` and subscribe to one cell or one
row with `engine.subscribeCell` / `engine.subscribeRow`; the listener runs
only when that cell or row changes, never for the rest of the grid.

Every state change is a plain, serializable command (`{ type: 'sort.set',
... }`). `engine.dispatch(command)` applies one and returns a result;
`engine.onCommand` reports each applied command, so a test or a support
tool can record a session and replay it on another grid. The demo
records sorting and the custom module's command, resets the grid and
replays them. For development tooling, the initial-only `recordCommands`
prop keeps that log in the engine (`api.engine.getCommandLog()`), and
`instrument` exposes store counters (`api.engine.getInstrumentation()`);
both are off by default and cost nothing then.

Features need no registration: a feature is on when its prop is
set, and the grid loads its code on demand, so only the features in use
are downloaded. To bundle feature code with the page instead of
loading it later, pass it to the optional `features` prop (see
[Performance](https://salmonui.dev/docs/data-grid/performance#what-a-grid-downloads)).
`modules` adds extra core modules for custom features. The demo's `minAmount` module declares one
command (`minAmount.set`) and a `filter` stage of the query pipeline.

Unmounting `DataGrid` releases everything it created. An engine created
outside `DataGrid`
with `createDataGridEngine` belongs to its owner, who calls `dispose()`; a
disposed engine stops notifying and rejects further commands.

### Live demo: Engine, modules and commands

Live demo: https://salmonui.dev/demos/data-grid/grid-internals

Part elements of the rendered grid, a one-cell subscription on the core engine, a custom core module with its own command and pipeline stage, a recorder that replays serializable commands, and disposing a standalone engine.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { createDataGridApi, createDataGridEngine, createRowModel, defineDataGridModule, type DataGridCommand, type RowModelSnapshot } from '@salmonui/data-grid/engine';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const initialOrders = createOrders(500, 83);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];

/** A custom core module: one serializable command and a filter stage in the query pipeline. */
type MinAmountCommand = { type: 'minAmount.set'; min: number };
const minAmountModule = defineDataGridModule<Order, { min: number }, MinAmountCommand, 'minAmount'>({
  name: 'minAmount',
  commands: ['minAmount.set'],
  initialState: () => ({ min: 0 }),
  reduce: (state, command) => (command.min === state.min ? state : { min: command.min }),
  pipeline: [
    {
      name: 'filter',
      key: (_query, state) => [state.min],
      run(input: RowModelSnapshot<Order>, ctx) {
        if (ctx.state.min === 0) return input;
        const keep: number[] = [];
        for (let i = 0; i < input.count; i++) {
          const at = input.order ? (input.order[i] as number) : i;
          if ((input.source[at]?.amount ?? 0) >= ctx.state.min) keep.push(at);
        }
        return createRowModel(input, Int32Array.from(keep));
      },
    },
  ],
});
const modules = [minAmountModule];

/** A core engine created outside `DataGrid` is disposed by its owner. */
function disposeStandaloneEngine(): string {
  const engine = createDataGridEngine<Order>({ columns: [{ field: 'id' }], dataSource: initialOrders.slice(0, 3), getRowId: (row) => row.id });
  const api = createDataGridApi(engine);
  const before = api.getViewRows().length;
  api.dispose();
  let after: string;
  try {
    after = engine.dispatch({ type: 'columns.hide', keys: ['id'] } as DataGridCommand).status;
  } catch (error) {
    after = `throws (${error instanceof Error ? error.message : String(error)})`;
  }
  return `standalone engine: ${before} rows, disposed=${engine.disposed}, dispatch after dispose: ${after}`;
}

export default function DataGridInternalsDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [log, push] = useEventLog();
  const [data, setData] = useState(initialOrders);
  const recorded = useRef<DataGridCommand[]>([]);
  const [recording, setRecording] = useState('');
  const unsubscribe = useRef<(() => void)[]>([]);
  const onReady = (grid: DataGridApi<Order>) => {
    // onReady runs once per mount (twice under StrictMode): drop the listeners of an earlier mount.
    for (const off of unsubscribe.current) off();
    // Fine-grained subscription: one cell, outside React rendering.
    const offCell = grid.engine.subscribeCell('ORD-10001', 'amount', () => push(`subscribeCell ORD-10001/amount: ${grid.engine.getCellSnapshot('ORD-10001', 'amount')?.formattedValue ?? '-'}`));
    // Every applied command is a plain, serializable object.
    const offCommands = grid.engine.onCommand(({ command, result }) => {
      if (result.status === 'rejected' || command.type.startsWith('focus.') || command.type.startsWith('selection.')) return;
      recorded.current = [...recorded.current, command];
      setRecording(JSON.stringify(recorded.current));
    });
    unsubscribe.current = [offCell, offCommands];
  };
  return (
    <>
      <div className="demo-toolbar">
        <Button
          variant="outline"
          onClick={() => {
            const a = api.current;
            if (!a) return;
            push(`element: ${a.element?.className.split(' ')[0]}; header: ${a.getPartElement('header')?.className.split(' ')[0]}; body: ${a.getPartElement('body')?.className.split(' ')[0]}; Amount header: ${a.getHeaderElement('amount')?.textContent}`);
          }}
        >
          Read part elements
        </Button>
        <Button variant="outline" onClick={() => setData((rows) => rows.map((row) => (row.id === 'ORD-10001' ? { ...row, amount: row.amount + 1 } : row)))}>
          Add 1 to ORD-10001 amount
        </Button>
        <Button variant="outline" onClick={() => push(`minAmount.set: ${api.current?.engine.dispatch({ type: 'minAmount.set', min: 500 } as DataGridCommand).status}; ${api.current?.getViewRows().length} view rows`)}>
          Keep amounts ≥ 500 (custom module)
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            const a = api.current;
            if (!a) return;
            const commands = recorded.current;
            a.clearSorting();
            a.engine.dispatch({ type: 'minAmount.set', min: 0 } as DataGridCommand);
            recorded.current = [];
            for (const command of commands) a.engine.dispatch(command);
            push(`replayed ${commands.length} commands; first row ${a.getViewRows()[0]?.id ?? '-'}`);
          }}
        >
          Reset and replay
        </Button>
        <Button variant="outline" onClick={() => push(disposeStandaloneEngine())}>
          Dispose a standalone engine
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders with a custom module and a command recorder"
        data={data}
        columns={columns}
        modules={modules}
        sorting
        height={300}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        onReady={onReady}
      />
      <pre className="demo-log" aria-label="Recorded commands">
        {recording || '(sort a column or use the custom module)'}
      </pre>
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

[`DataGridApi`](https://salmonui.dev/docs/reference/data-grid/DataGridApi) lists every
method, [`DataGridKeyDownContext`](https://salmonui.dev/docs/reference/data-grid/DataGridKeyDownContext)
the key hook context, and
[`DataGridEngine`](https://salmonui.dev/docs/reference/data-grid/engine/DataGridEngine) the core
engine.
