# Grid API reference

Ownership modes and key public types for @pretable/react.


The generated `react.api.md` and `core.api.md` reports contain every declaration. This page summarizes the primary contracts.

## Putting it together

Typed columns via `createColumnHelper`, rows mode, a controlled `PretableSelectionFor<typeof columns>` on `onSelectionChange`, and the row-selection checkbox column on its own `onRowSelectionChange` — the two are separate slices, as [Selection](/docs/grid/selection) explains — all in the shapes documented below:

### Example: Range selection

The two selection slices side by side: cell ranges controlled through PretableSelectionFor<typeof columns> and onSelectionChange, and the rowSelectionColumn checkbox set reported by onRowSelectionChange — shift-click extends a range, Cmd/Ctrl-click adds a discontiguous one, dragging marquees a rectangle, and a caption under each shows which callback just fired.

Source: https://pretable.ai/examples/range-selection.md

```tsx RangeSelectionGrid.tsx
"use client";

import { useState } from "react";

import { PretableSurface } from "@pretable/react";
import type {
  PretableCellRangeFor,
  PretableSelectionFor,
} from "@pretable/react";

import { columns } from "./columns";
import { rows } from "./data";

const VIEWPORT_HEIGHT = 300;

// Echoes `PretableCellRangeFor`'s own fields — the shape the page's
// "Selection model" section describes below — rather than a re-derived summary,
// so the caption stays an honest window onto the controlled state above it.
// Narrowed to `typeof columns`, so a typo'd column id here is a compile error
// rather than a silently-dead comparison.
function describeRange(range: PretableCellRangeFor<typeof columns>): string {
  return range.startRowId === range.endRowId &&
    range.startColumnId === range.endColumnId
    ? `${range.startColumnId}@${range.startRowId}`
    : `${range.startColumnId}@${range.startRowId} → ${range.endColumnId}@${range.endRowId}`;
}

export function RangeSelectionGrid() {
  // The CELL-RANGE slice. Controlled, and narrowed to the column tuple.
  const [selection, setSelection] = useState<
    PretableSelectionFor<typeof columns>
  >({
    ranges: [],
    anchor: null,
  });
  // The CHECKBOX slice, which is a different thing entirely: it lives in the
  // engine, is reported by its own callback, and never appears in `selection`.
  // Wiring only `onSelectionChange` — the mistake this example exists to make
  // hard — leaves the checkboxes ticking with nothing downstream ever hearing.
  const [checkedRowIds, setCheckedRowIds] = useState<readonly string[]>([]);

  return (
    <div>
      <p style={{ margin: "0 0 8px", fontSize: 13 }}>
        Click a cell, then <kbd>Shift</kbd>+click another to extend the range.{" "}
        <kbd>Cmd</kbd>/<kbd>Ctrl</kbd>+click adds a discontiguous range. Drag
        from one cell to another for a marquee selection. Then tick a checkbox,
        and watch the second caption move instead of the first.
      </p>
      <PretableSurface
        ariaLabel="Selection demo"
        columns={columns}
        getRowId={(row) => row.id}
        rows={rows}
        rowSelectionColumn={{ enabled: true }}
        state={{ selection }}
        onSelectionChange={setSelection}
        onRowSelectionChange={setCheckedRowIds}
        viewportHeight={VIEWPORT_HEIGHT}
      />
      <p style={{ margin: "8px 0 0", fontSize: 13 }}>
        Cell ranges (<code>onSelectionChange</code>):{" "}
        <code>
          {selection.ranges.length > 0
            ? selection.ranges.map(describeRange).join(" · ")
            : "(none)"}
        </code>
      </p>
      <p style={{ margin: "4px 0 0", fontSize: 13 }}>
        Ticked rows (<code>onRowSelectionChange</code>):{" "}
        <code>
          {checkedRowIds.length > 0 ? checkedRowIds.join(", ") : "(none)"}
        </code>
      </p>
    </div>
  );
}
```

```ts columns.ts
import { createColumnHelper } from "@pretable/core";

import type { Row } from "./data";

// `createColumnHelper` + `as const` — the idiom the "Selection model" section
// on this page teaches — produces a `readonly` literal-id column tuple. That
// tuple is what narrows the controlled `state.selection` prop's `columnId` to
// a checked union via `PretableSelectionFor<typeof columns>`, rather than the
// broad `startColumnId: string` on `@pretable/core`'s `PretableCellRange`.
const column = createColumnHelper<Row>();

export const columns = [
  column.accessor("name", { type: "text", header: "Name" }),
  column.accessor("city", { type: "text", header: "City" }),
  column.accessor("region", { type: "text", header: "Region" }),
  column.accessor("status", { type: "enum", header: "Status" }),
] as const;
```

```ts data.ts
export interface Row {
  id: string;
  name: string;
  city: string;
  region: string;
  status: "ok" | "warn" | "error";
}

/**
 * A dozen rows across four columns — enough that a marquee drag spans a
 * genuine rectangle of cells and a shift-click range covers more than one
 * row, while still fitting the demo's fixed viewport without scrolling.
 */
export const rows: Row[] = [
  {
    id: "r1",
    name: "Ada Lovelace",
    city: "London",
    region: "EMEA",
    status: "ok",
  },
  {
    id: "r2",
    name: "Grace Hopper",
    city: "New York",
    region: "AMER",
    status: "ok",
  },
  {
    id: "r3",
    name: "Linus Torvalds",
    city: "Helsinki",
    region: "EMEA",
    status: "warn",
  },
  {
    id: "r4",
    name: "Margaret Hamilton",
    city: "Indianapolis",
    region: "AMER",
    status: "ok",
  },
  {
    id: "r5",
    name: "Alan Turing",
    city: "London",
    region: "EMEA",
    status: "error",
  },
  {
    id: "r6",
    name: "Katherine Johnson",
    city: "Hampton",
    region: "AMER",
    status: "ok",
  },
  {
    id: "r7",
    name: "Tim Berners-Lee",
    city: "London",
    region: "EMEA",
    status: "warn",
  },
  {
    id: "r8",
    name: "Radia Perlman",
    city: "Boston",
    region: "AMER",
    status: "ok",
  },
  {
    id: "r9",
    name: "Yukihiro Matsumoto",
    city: "Osaka",
    region: "APAC",
    status: "ok",
  },
  {
    id: "r10",
    name: "Hedy Lamarr",
    city: "Vienna",
    region: "EMEA",
    status: "ok",
  },
  {
    id: "r11",
    name: "Shigeru Miyamoto",
    city: "Kyoto",
    region: "APAC",
    status: "warn",
  },
  {
    id: "r12",
    name: "Barbara Liskov",
    city: "Boston",
    region: "AMER",
    status: "ok",
  },
];
```


## Typed columns

The example above builds its columns with exactly this idiom:

```ts
import { createColumnHelper } from "@pretable/core";

interface Order {
  id: string;
  customer: string;
  total: number;
}

const column = createColumnHelper<Order>();
const columns = [
  column.accessor("customer", { type: "text", header: "Customer" }),
  column.accessor("total", {
    type: "number",
    header: "Total",
    aggregate: "sum",
  }),
] as const;
```

The tuple preserves row, column-ID, value, filter, editor, formatter, and
aggregate correlations. Column options include typed accessors, `header`,
`type`, sorting and filtering behavior, layout fields, `dateFormat`,
`numberFormat`, `format`, `aggregate`, `formatAggregate`, `formatSummary`, editing hooks, and
React `render` / `renderEditor` callbacks. A `type: "date"` accessor accepts
only `string | null` values.

### Number formatting exports

```ts
import { numberFormats } from "@pretable/react";

const usd = numberFormats.money({ currency: "USD" });
const accounting = numberFormats.accounting({ currency: "USD" });
```

Both helpers return native `Intl.NumberFormatOptions` and are exported from `@pretable/react` and `@pretable/core`. A surface's `locale` applies to cell display, inherited numeric aggregate display, and built-in clipboard text. See [Number formatting](/docs/grid/number-formatting).

### Date formatting exports

```ts
import {
  isValidDateValue,
  type PretableDateFormatOptions,
} from "@pretable/react";
```

`isValidDateValue(value)` narrows an exact, Gregorian `YYYY-MM-DD` string.
`PretableDateFormatOptions` allows only `localeMatcher`, `calendar`,
`numberingSystem`, `dateStyle`, `weekday`, `era`, `year`, `month`, `day`, and
`formatMatcher`; Pretable owns the UTC time zone and rejects every time field,
unknown key, and symbol key. Both exports are also available from
`@pretable/core`. See [Date formatting](/docs/grid/date-formatting) for storage,
query, aggregate, precedence, SSR, and migration rules.

### Shared cell presentations

`PretableBadge`, `PretableDelta`, `PretableEntity`, and `PretableStatus` are theme-aware React presentations for semantic badges, signed changes, primary/secondary entities, and labelled states. They do not replace typed values or formatting; pass already-formatted content where appropriate. See [Cell presentations](/docs/grid/cell-presentations) for each one's props.

## `<PretableSurface>` ownership

```tsx
// Declarative rows mode
<PretableSurface rows={rows} columns={columns} getRowId={(row) => row.id} />

// Explicit-model mode
<PretableSurface model={rowModel} />
```

`rows` and `model` are mutually exclusive. Rows mode diffs each new `rows` prop into its long-lived local model. Explicit-model mode makes the supplied model the only data/derivation owner; compatible `columns` may override presentation only.

Rows with a conventional string or number `id` do not require `getRowId`. Otherwise it is required, and omitting it is a compile error rather than a runtime failure. This is one contract across every entry point that takes rows — `<Pretable>`, `<PretableSurface>`, `usePretable`, `useLocalRowModel`, and `createLocalRowModel` all treat the accessor the same way. Identity survives row-array replacements and is used by selection, focus, editing, expansion, and transactions.

Important shared props include `ariaLabel`, `viewportHeight`, `overscan`, `locale`, `state`, `onSelectionChange`, `onRowSelectionChange`, `onFocusChange`, `onPaste`, `onCopy`, `copyToClipboard`, `csvOptions`, `onExport`, `saveFile`, `groupPanel`, `groupColumn`, `hideGroupedColumns`, `summaries`, and cell/header/row render hooks. Rows mode alone accepts the exact controlled `query`/`onQueryChange` pair, `onRowChange`, `initialExpansion`, and `aggregateFilteredRows`. Explicit-model mode alone accepts `beforeRowChange`.

The `processing`, `resultMeta`, `dataState`, and `renderBodyState` props describe external filter/sort authority, total and dataset identity, and consumer-owned loading/error presentation. They do not move row or query ownership into the UI grid: the query is still published, reported, and reflected in the header exactly as before. What `processing.filter: "external"` does change, in rows mode only, is that the engine stops applying `query.filters` to the rows it was handed; `processing.sort` suppresses nothing, and an explicit model decides its own query. See [Server-side data](/docs/server-data) for the complete contract.

See [Row grouping and aggregation](/docs/grid/grouping) for grouping, expansion, aggregate formatting, and group-panel behavior.

## Explicit row model

Create one with `createLocalRowModel({ rows, columns })`. It owns:

- immutable indexed snapshots and revisions;
- source rows and atomic transactions;
- typed filters, sort, grouping, and derivations;
- expansion and aggregates;
- async distinct-value queries.

The snapshot exposes `visibleRowCount`, `rowAt`, `range`, `indexOf`, data-row navigation, and discriminated data/group references. Read only the viewport range you need.

## UI grid

`createGrid({ rowModel, columns })` is a framework-independent UI-only store. It owns focus, selection, editing, viewport, and visual column layout. It has no row/query mutation methods.

## Selection and focus

`PretableSelectionState` (from `@pretable/core`) stores an anchor plus indexed cell ranges with `string` column ids; `PretableSelectionFor<TColumns>` (from `@pretable/react`) is the same shape narrowed to a column tuple, for hand-declaring controlled selection state — the example above threads exactly this type through `useState` and `onSelectionChange`. Both are the CELL-RANGE slice only: the `rowSelectionColumn` checkbox set is a separate engine slice, with its own `PretableRowSelectionState` type, its own `state.rowSelection` slice, and its own `onRowSelectionChange` callback. See [Selection](/docs/grid/selection#selection-model) for the full model. Focus and range endpoints use discriminated data/group row references so an application row ID cannot collide with a derived group ID. The surface's `state` prop controls interaction and layout slices; it does not mirror rows or the row-model query.

## Copy types

```ts
interface SerializeRangesArgs<TRow, TRowId, TColumns> {
  ranges: readonly { start: CellAddress; end: CellAddress }[];
  rowModelSnapshot: PretableRowModelSnapshot<TRow, TRowId, TColumns>;
  columns: readonly PretableColumn<TRow>[];
  copyWithHeaders?: boolean;
  locale?: PretableLocale;
  scope: "all" | "loaded";
}
```

`serializeRanges` performs indexed reads from the supplied snapshot. `onCopy` returns `{ text, html? }` or `null`. The aggregate scope and locale keep custom serialization aligned with what the surface presents.

## Telemetry

`PretableTelemetry` reports source, logical, and rendered row counts plus the current rendered range, dimensions, focus, and selection summary. Keep `onTelemetryChange` callback identity stable.

## Hooks and components

- `PretableSurface` — full production surface, in rows or explicit-model mode.
- `Pretable` — concise declarative preset.
- `usePretable` — surface internals for advanced custom rendering.
- `PretableBadge`, `PretableDelta`, `PretableEntity`, `PretableStatus` — shared cell presentations.
- `PretableButton`, `PretableIconButton`, `PretableSelect`, `PretableTextInput`, `PretableTextarea`, `PretableCheckbox` — [shared controls](/docs/grid/components#the-components), with corresponding `Props` and `Component` types.
- `PretableComponents` — the [replacement map](/docs/grid/components#replacing-a-component) accepted by the surface's `components` prop.
- `PretableSite` / `PretableBuiltInSite` — control placement names for styling and replacement logic.
- `PretableOverlayProvider` / `PretableOverlayProviderProps` — [popup portal scope](/docs/grid/components#overlay-scope) for application-owned hosts and local themes.
- `getDensityHeights` — public density-aware sizing for custom renderers.
- `serializeRanges` / `defaultCoerceForCopy` — clipboard primitives.
- `numberFormats.money` / `numberFormats.accounting` — native numeric option helpers.
- `isValidDateValue` / `PretableDateFormatOptions` — strict calendar-date validation and native display options.

For framework-independent control, see the [headless API](/docs/headless/api-reference).

## Summary contracts

`PretableSummaryScope` is `"filtered"` or `"all"`.

`PretableSummaries` maps optional `filtered` and `all` scopes to independent
`PretableSummaryDescriptor` values. Server descriptors carry a
`PretableServerSummaryResult` with explicit keys and completeness for ready/stale
answers. Core exposes `PretableSummaryScope`, `PretableEngineSummary`,
`PretableSummaryFormatInput`, and `PretableSummaryFormatContext`. See
[summary rows and headless leases](/docs/grid/grouping#grand-totals-and-summary-rows)
and [server answer provenance](/docs/server-data/totals#summary-answers).
