# Pivot engine

> The framework-agnostic pivot engine at @salmonui/pivot-table/engine — report model, local and CSV data, field definitions, the result accessors, incremental data updates, time slicing and the Worker host.

Canonical: https://salmonui.dev/docs/pivot-table/engine

`PivotTable` is rendered from a `PivotResult` computed by the pivot engine,
`@salmonui/pivot-table/engine`. The engine has no React and no DOM code and
no dependencies, so the same code runs on the main thread, in a Worker, during
SSR and on a server. No Data Grid entry imports it, so a `DataGrid` bundle
contains no pivot code.

```ts
import { createPivotEngine } from '@salmonui/pivot-table/engine';

const pivot = createPivotEngine({
  data: sales, // raw rows, read in place (never copied)
  model: {
    rows: [{ field: 'region' }, { field: 'country' }],
    columns: [{ field: 'year' }],
    values: [{ field: 'amount', aggregate: 'sum' }],
  },
});
const result = pivot.getSnapshot();
result.valueAt(0, 0); // Grand totals, members and subtotals are all positions
```

## Report model

`pivotModel` is plain JSON without the data: `rows`, `columns`, `values` and `filters` hold the placed
fields, and `filterBy`, `sort`, `valueSort`, `groups`, `calculatedFields`,
`formats`, `conditionalFormats`, `expanded`, `totals`, `valuesPlacement`,
`showEmptyMembers` and `showValueHeader` hold the rest. You can pass a partial
model; `normalizePivotModel()` fills in every default and returns a deeply
frozen model, and normalizing a normalized model returns an equal one.
`stableStringifyModel()` returns key-sorted JSON with the default-valued
fields left out, which works as a cache key or a URL parameter.

A `filterBy` entry applies only when its field is placed on the rows, columns
or filters axis. If you remove a field from
the filters axis, its filter stops applying.

## Data

`data` is an array of row objects, read by reference: `getRawRows()` and
`drillThrough()` return the same objects you passed in. Missing values (`null`,
`undefined`, `''`) are grouped under one `(Blank)` member.

CSV text becomes rows with `parseCsv(text, { delimiter, header, types })`. The
parser follows RFC 4180: quoted fields, `""` escapes, CRLF line endings and a
byte order mark are handled. A column whose values are all numeric becomes
`number` unless `types` names another type (`'string'`, `'number'`, `'date'`,
`'boolean'`). There is no CSV prop.

```ts
import { parseCsv } from '@salmonui/pivot-table'; // re-exported from @salmonui/pivot-table/engine

const rows = parseCsv(await (await fetch('/sales.csv')).text(), { types: { year: 'string' } });
```

In React, pass the rows as `data` to `usePivot()` or `PivotTable`. A new
array re-aggregates (see [Data updates](https://salmonui.dev/docs/pivot-table/engine#data-updates)); mutating the
array in place does not, so call `api.refresh()` (or `pivot.refresh()`)
after an in-place change.

## Field definitions

`fields` describes the source fields. Each definition
can set `caption`, `type` (inferred from the first non-empty value when
omitted), `folder` (a field list folder), `hidden` (left out of the field
list), the per-field `sortable`, `filterable`, `removable` and
`draggable` flags, and a `valueGetter(row)` for computed fields. When you omit
`fields`, the engine infers them from the keys of the first rows.
The definitions are read when the store is created. `getFields()` returns the resolved definitions with their `memberCount`, and
`getMembers(field, { search, limit })` lists the members in display order with
their row counts. The member editor uses both.

## The result

`getSnapshot()` returns an immutable `PivotResult`, and its identity changes
only when the result changes, so it works as a `useSyncExternalStore`
snapshot. `subscribe()` notifies listeners on every change.

| Accessor | Returns |
| --- | --- |
| `rowCount`, `columnCount` | Visible row and column positions (members, subtotals, grand totals, value rows) |
| `rowTree`, `columnTree`, `rowDepth`, `columnDepth` | Header trees. Each `PivotHeaderNode` has `key`, `kind`, `path`, `field`, `measure`, `label`, `depth`, `position` / `span` over the leaf positions, `expandable` and `expanded` |
| `memberAt(axis, i)` | The header node of a position |
| `valueAt(r, c)` | The value shown: aggregate, then calculated field, then show values as, then `getCellValue` |
| `cellAt(r, c)` | `PivotCell`: keys, measure, `value`, `rawValue`, `formattedValue`, `kind`, `rowCount` |
| `rowsAt(r, c)` | Indexes of the raw rows behind a cell (drill through) |

Header nodes and cells are created only when you read them, so a result with
50,000 × 500 cells never allocates 25 million objects.

Header keys are the JSON array of the member path: `'["Asia","Japan"]'`. The
grand total is `''`. A leaf on the axis that carries the values gets
`|<measure id>` appended (`'["Asia"]|amount'`, `'|amount'` for the grand
total column). A value header that has members under it is
`<path>||<measure id>`. A subtotal header that has value children, and a
subtotal row in `subPosition: 'end'`, is `<path>|total`. Cell selection keys
are `rowKey|columnKey`. The measure id is the value field's `field`, or
`field#aggregate` when two value fields share a field (see
[Aggregation](https://salmonui.dev/docs/pivot-table/aggregation)).

## Commands

`setModel(input | (model) => input)`, `expand(path)` / `collapse(path)` with
paths such as `['rows', 'Asia']`, `expandAll(axis?)` / `collapseAll(axis?)`,
`setData(rows)`, `refresh()` and `destroy()`. Each command returns the new
result. A model equal to the current one does nothing.

- Expanding a member aggregates only that member's rows. Collapsing it changes
  only the view.
- A member filter on a row field recomputes only the members it changes.
- Values do not depend on the order of earlier commands: the same model and
  data give bit-identical numbers whether you reach them by drilling,
  filtering or computing from scratch.

## Data updates

`setData(next)` compares `next` with the previous array by row reference. If
only a few rows were replaced (up to 1/64 of the rows), or rows were only
appended, the engine re-encodes just those rows and recomputes only the
members whose rows changed. Any other change, and any change while a value
filter is active, recomputes everything. `refresh()` always recomputes from
scratch.

## Time slicing, SSR and Workers

- `computePivot(options)` is a one-shot, synchronous compute for SSR and
  servers.
- `createPivotJob(options).run(budgetMs)` works in slices of about
  `budgetMs` milliseconds and returns `{ done, progress }`. Call `result()`
  once it is done.
- `createPivotWorkerEngine(worker, options)` runs the engine in a Worker. The
  application creates the Worker, because bundlers differ:

```ts
const worker = new Worker(new URL('@salmonui/pivot-table/engine/worker', import.meta.url), { type: 'module' });
const pivot = createPivotWorkerEngine(worker, { data, model });
await pivot.ready;
const view = await pivot.getWindow({ rowStart: 0, rowEnd: 40, columnStart: 0, columnEnd: 20 });
```

The raw rows are sent once, in chunks of `chunkSize` rows (20,000 by default),
and the worker acknowledges each chunk. After that only summaries, windows,
member lists and drill-through rows cross the boundary. A window holds the
leaf headers, the header nodes overlapping the window (without children) and
the cells. Calls run in order, so a functional `setModel` sees the model left
by the calls before it. `getStatus()` returns `idle`, `computing`, `ready` or
`error`. To use another host, such as `node:worker_threads`, call
`attachPivotWorker(scope)` (from `@salmonui/pivot-table/engine/worker`)
in the worker entry with an adapter over `parentPort`.

In React, pass the Worker as `worker` to `usePivot()` or `PivotTable`
(read when the store is created); the table then loads only the windows it
renders. A Worker exists only in the browser, so create it in the
component that calls `usePivot()` and render that component on the client
only (after a mounted flag, or a client-only dynamic import): the server
HTML and the first client render then agree.

## Performance

On the 1,000,000-row `pivot` fixture (3 row fields, 2 column fields, 2 value
fields), the engine computes the initial result in about 0.3 s in-process and
about 1 s through a Worker, transfer included. Drilling takes under 10 ms, a
member filter under 100 ms and a sort under 5 ms. These are release gates.

### Live demo: Data binding and the report model

Live demo: https://salmonui.dev/demos/pivot-table/pivot-table-data-binding

CSV text parsed with parseCsv into the data prop, field definitions with captions, folders and per-field capabilities, a controlled pivotModel, data replacement, refresh and the result API.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { parseCsv, PivotTable, type PivotFieldDefinition, type PivotModel, type PivotModelInput, type PivotTableApi } from '@salmonui/pivot-table';
import { Button } from '@salmonui/buttons/button';
import { TextArea } from '@salmonui/inputs/text-field';

type Sale = { id: number; region: string; country: string; product: string; year: string; amount: number; units: number };

// CSV text as an app would fetch it from a file or an endpoint.
const CSV = `id,region,country,product,year,amount,units
1,Asia,Japan,Bikes,2025,1200,6
2,Asia,Japan,Helmets,2025,310,12
3,Asia,India,Bikes,2025,980,5
4,Asia,India,Gloves,2026,140,20
5,Europe,France,Bikes,2025,1450,7
6,Europe,France,Helmets,2026,420,15
7,Europe,Germany,Bikes,2026,1610,8
8,Europe,Germany,Gloves,2025,95,13
9,Americas,Brazil,Bikes,2026,870,4
10,Americas,Brazil,Helmets,2025,260,10
11,Americas,Canada,Bikes,2025,1320,6
12,Americas,Canada,Gloves,2026,180,24`;

// Field definitions: captions, types, field list folders, a hidden
// key and per-field capabilities (Region cannot be removed or dragged).
const FIELDS: PivotFieldDefinition<Sale>[] = [
  { field: 'id', caption: 'Id', type: 'number', hidden: true },
  { field: 'region', caption: 'Region', type: 'string', folder: 'Geography', removable: false, draggable: false },
  { field: 'country', caption: 'Country', type: 'string', folder: 'Geography' },
  { field: 'product', caption: 'Product', type: 'string', folder: 'Catalog' },
  { field: 'year', caption: 'Year', type: 'string', sortable: false },
  { field: 'amount', caption: 'Amount', type: 'number', folder: 'Measures' },
  { field: 'units', caption: 'Units', type: 'number', folder: 'Measures', filterable: false },
];

const INITIAL_MODEL: PivotModelInput = {
  rows: [{ field: 'region' }, { field: 'country' }],
  columns: [{ field: 'year' }],
  values: [{ field: 'amount', aggregate: 'sum' }],
  formats: { amount: { number: { style: 'currency', currency: 'USD', maximumFractionDigits: 0 } } },
};

const toSales = (text: string): Sale[] => parseCsv(text, { types: { year: 'string' } }) as unknown as Sale[];

/** parseCsv feeding `data`, field definitions, a controlled `pivotModel`, data replacement, refresh and the result API. */
export default function PivotTableDataBindingDemo() {
  const tableRef = useRef<PivotTableApi<Sale>>(null);
  const [csv, setCsv] = useState(CSV);
  const [data, setData] = useState<Sale[]>(() => toSales(CSV));
  // Controlled report model: the table proposes, the app applies.
  const [model, setModel] = useState<PivotModelInput>(INITIAL_MODEL);
  const [readout, setReadout] = useState('Read the result to see the grand total.');

  const addSale = () => {
    const id = data.length + 1;
    setData([...data, { id, region: 'Asia', country: 'Japan', product: 'Bikes', year: '2026', amount: 500, units: 3 }]);
  };
  const readResult = () => {
    // The computed matrix is code-readable; the last row and column are the grand totals.
    const result = tableRef.current?.getResult();
    if (!result) return;
    const last = result.cellAt(result.rowCount - 1, result.columnCount - 1);
    const first = result.memberAt('rows', 0);
    setReadout(`${result.rowCount} rows × ${result.columnCount} columns · first row "${first.label}" · grand total ${last.formattedValue} from ${last.rowCount} raw rows`);
  };
  const usesRegion = (m: PivotModelInput) => m.rows?.some((f) => f.field === 'region') ?? false;

  return (
    <div>
      <TextArea label="CSV source" value={csv} onValueChange={(next) => setCsv(next)} rows={5} spellCheck={false} resize="vertical" style={{ inlineSize: "100%", maxInlineSize: 640 }} />
      <div className="demo-toolbar" style={{ marginBlockStart: 8 }}>
        <Button variant="outline" onClick={() => setData(toSales(csv))}>
          Parse CSV
        </Button>
        <Button variant="outline" onClick={addSale}>
          Add a 2026 Japan bike sale
        </Button>
        <Button variant="outline" onClick={() => tableRef.current?.refresh()}>
          Refresh
        </Button>
        <Button variant="outline" onClick={readResult}>
          Read result
        </Button>
        <Button variant="outline" onClick={() => setModel({ ...INITIAL_MODEL, rows: [{ field: 'product' }], columns: [{ field: 'region' }] })}>
          Products by region
        </Button>
        <Button variant="outline" onClick={() => setModel(INITIAL_MODEL)}>
          Reset report
        </Button>
      </div>
      <PivotTable<Sale>
        ref={tableRef}
        data={data}
        fields={FIELDS}
        pivotModel={model}
        onBeforePivotModelChange={(event) => {
          // A controlled model can refuse a change: the Region field must stay on rows when it is there.
          if (usesRegion(model) && !event.model.rows.some((f) => f.field === 'region')) event.preventDefault();
        }}
        onPivotModelChange={(event) => setModel(event.model as PivotModel)}
        axisBar={{ showFieldsPanel: true }}
        fieldList="popup"
        toolbar={['fieldList']}
        locale="en-US"
        height={300}
        aria-label="Sales parsed from CSV"
      />
      <p className="demo-status" aria-live="polite">
        {data.length} raw rows · rows <code>{(model.rows ?? []).map((f) => f.field).join(', ') || 'none'}</code> · columns{' '}
        <code>{(model.columns ?? []).map((f) => f.field).join(', ') || 'none'}</code>
      </p>
      <p className="demo-status" aria-live="polite">
        {readout}
      </p>
    </div>
  );
}
```
