# Data sources

> Local arrays, the Salmon UI JSON protocol, offline, live and application-controlled data sources.

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

The grid reads rows through one structural data-source contract. A local
array is the simplest source; every other source implements the
same contract, including user-written ones. The current query
(sorting, filters, search, grouping, aggregates, paging and expansion) is a
serializable descriptor, and a grid can start from an initial
query (see [Initial query](https://salmonui.dev/docs/data-grid/data-sources#initial-query)).

```tsx
import { DataGrid } from '@salmonui/data-grid';
import { createJsonDataSource } from '@salmonui/data';

const orders = createJsonDataSource<Order>({ url: '/api/orders', key: 'id', fields: ['id', 'customer', 'total'] });

<DataGrid data={orders} columns={columns} sorting paging aria-label="Orders" />;
```

`data` takes either an array (reactive: a new array replaces the rows) or a
`DataSource`, which is read once on mount.

## Remote: the Salmon UI JSON protocol

Remote sources speak one JSON protocol over a pluggable transport.
The protocol does not send one object per row: a `{ result, count }`
shape costs payload and per-row decode
work, while tuples with dictionary encoding measure about a third of its
payload and decode time. To use an existing endpoint, expose one that
speaks the protocol, or give `createJsonDataSource` a `transport` that calls
the existing endpoint and maps its rows to tuple `rows` and `total`.
Rows travel as tuples with optional dictionaries; sorting, filtering and
grouping run on the server; results can include server-side
aggregates. Every request carries an abort signal and a version
stamp, so a stale response never overwrites a newer one. With
infinite paging the source loads blocks on demand and keeps a bounded block
cache.

The demo endpoint runs the reference handler from `@salmonui/data/server`
(`createJsonQueryHandler`) over an in-memory table. Salmon UI ships no
Entity Framework, Dapper or SQL server samples: the contract is the wire protocol, not a server stack, so a
real backend ports the handler's query semantics to its ORM or SQL, or the
client supplies a custom `transport`.

### Live demo: Remote JSON data source

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

50,000 orders from a Salmon UI JSON protocol endpoint (the reference handler, behind a Next.js route handler or in the browser on the static site), loaded in infinite blocks, sorted on the server with an initial sort.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { createJsonDataSource } from '@salmonui/data';
import { DataGrid, type DataGridColumn, type DataGridSorting } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { demoFetch, type RemoteOrder } from '../../lib/remote';

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

// Initial server-side sort; a constant (the options prop is reactive).
const sorting: DataGridSorting = { sortBy: [{ field: 'id', direction: 'desc' }] };

export default function RemoteJsonDemo() {
  const [log, push] = useEventLog();
  // Created once per mounted grid (data sources are initial-only).
  const [source] = useState(() =>
    createJsonDataSource<RemoteOrder>({
      url: '/api/orders?delay=150',
      fetch: demoFetch,
      key: 'id',
      paging: { kind: 'infinite', blockSize: 200, maxBlocks: 20 },
      // `onRequest` runs before each request (return false to cancel it);
      // `onResponse` runs before the response is decoded
      // and may return a replacement response.
      onRequest: (event) => push(`request ${event.kind}`),
      onResponse: (event) => {
        const rows = 'rows' in event.response ? event.response.rows.length : 0;
        push(`${event.kind}: ${rows} rows in ${Math.round(event.durationMs)} ms`);
      },
    }),
  );
  return (
    <>
      <DataGrid<RemoteOrder>
        aria-label="50,000 remote orders loaded in blocks"
        data={source}
        columns={columns}
        sorting={sorting}
        height={380}
        locale="en-US"
        currency="USD"
      />
      <p className="demo-status">Sorting runs on the server: click a header and watch the requests.</p>
      <EventLog entries={log} label="Requests" />
    </>
  );
}
```

### Request and response hooks

`createJsonDataSource` takes three hooks, each called with the request
`kind` (`read`, `prefetch`, `group`, `tree`, `facet` or `write`) and the
protocol `request`:

- `onRequest(event)` runs before a request is sent. Returning `false`
  cancels it: the read rejects with `RequestCanceledError` and nothing is
  sent.
- `onResponse(event)` runs with every successful `response` (and its
  `durationMs`) before the source decodes it into rows. It can observe or
  transform: returning a
  response object replaces the response for that request, so it can
  rewrite rows, dictionaries, `total` or aggregates; returning nothing (or
  any non-object) keeps the server response. Return a new object instead of
  mutating `event.response`: the cache keeps the server response, and a
  cache hit runs the hook again.
- `onError(event)` runs when a request fails (not when it is aborted).

```ts
const source = createJsonDataSource<Order>({
  url: '/api/orders',
  key: 'id',
  onRequest: (e) => e.kind !== 'prefetch' || navigator.onLine,
  onResponse: (e) =>
    e.kind === 'read' && 'rows' in e.response
      ? { ...e.response, rows: e.response.rows.filter((row) => row[0] !== null) }
      : undefined,
});
```

The grid-level `onViewChange` fires after the new
rows are rendered, for every source, with a `reason` of `data`, `sort`,
`filter`, `search`, `group`, `page` or `refresh`. The hooks above belong to
the JSON source only; the other sources need none: a controlled source
already returns the rows from `onQueryChange`, a local array is the data,
and a custom `transport` can rewrite responses for any protocol. The demo
logs every request and response.

## Other protocols: a custom transport

`@salmonui/data` has no built-in Web API, OData or GraphQL client:
.NET request shapes, an OData encoder, parser and
`$batch` writer, or a schema-specific GraphQL query builder would ship in
every bundle that imports `@salmonui/data`, against its 25 KB budget.
`createJsonDataSource` takes a `transport`
function instead of a `url`: it receives each protocol request (`query`
with `sort`, `where`, `search`, `page`, `select`) and resolves with a
protocol response (`fields`, tuple `rows`, `total`). A transport that maps
the query to `$orderby` / `$skip` / `$top` / `$count` and the OData
`value` back to tuples is an OData bridge; the same function can post the
request as a GraphQL variable or call a Web API action (for OData v2/v3,
read `total` from `$inlinecount`; an OData `$batch` submit becomes one
`write` request). Paging, caching, abort and stale-response handling stay in
the data source.

### Live demo: OData bridge transport

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

A user-written transport maps Salmon UI protocol reads to an OData-style GET ($orderby, $skip, $top, $count, $select) and the OData body back to tuples; the same pattern bridges Web API, OData and GraphQL backends.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { createJsonDataSource, encodeRows, HttpError, isWireWriteRequest, ProtocolError, type JsonTransport } from '@salmonui/data';
import { DataGrid, type DataGridColumn, type DataGridPaging } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { demoFetch, type RemoteOrder } from '../../lib/remote';

const FIELDS = ['id', 'customer', 'country', 'product', 'amount'] as const;

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

const paging: DataGridPaging = { pageSize: 10 };

/**
 * A user-written transport: maps each Salmon UI protocol read to an
 * OData-style GET (`$orderby`, `$skip`, `$top`, `$count`, `$select`) and the
 * OData `{ value, @odata.count }` body back to protocol tuples. The same shape
 * bridges Web API, OData v2/v3/v4 or GraphQL backends.
 */
function createODataTransport(log: (entry: string) => void): JsonTransport {
  return async (request, { signal }) => {
    if (isWireWriteRequest(request)) throw new ProtocolError('unsupported', 'This bridge is read-only.');
    const q = request.query;
    if (q.where || q.search || q.group) throw new ProtocolError('unsupported', 'This bridge maps sorting and paging only.');
    const params: [string, string][] = [];
    if (q.sort?.length) params.push(['$orderby', q.sort.map((s) => `${s.field} ${s.dir}`).join(',')]);
    if (q.page && 'offset' in q.page) params.push(['$skip', String(q.page.offset)], ['$top', String(q.page.limit)]);
    if (request.count !== false) params.push(['$count', 'true']);
    const fields = q.select ?? FIELDS;
    params.push(['$select', fields.join(',')]);
    log(`GET /api/odata/orders?${params.map(([k, v]) => `${k}=${v}`).join('&')}`);
    const url = `/api/odata/orders?${params.map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join('&')}`;
    const response = await demoFetch(url, { signal: signal as AbortSignal });
    if (!response.ok) throw new HttpError(response.status, response.statusText ?? '', await response.text());
    const body = (await response.json()) as { value: Record<string, unknown>[]; '@odata.count'?: number };
    const { rows } = encodeRows(body.value, { fields });
    return { v: 1, id: request.id, fields, rows, ...(body['@odata.count'] !== undefined ? { total: body['@odata.count'] } : {}) };
  };
}

export default function ODataBridgeDemo() {
  const [log, push] = useEventLog();
  // Created once per mounted grid (data sources are initial-only).
  const [source] = useState(() =>
    createJsonDataSource<RemoteOrder>({
      transport: createODataTransport(push),
      key: 'id',
      fields: FIELDS,
      rowShape: 'object',
      paging: { kind: 'offset' },
    }),
  );
  return (
    <>
      <DataGrid<RemoteOrder>
        aria-label="Orders from an OData-style endpoint through a custom transport"
        data={source}
        columns={columns}
        sorting
        paging={paging}
        height={360}
        locale="en-US"
        currency="USD"
      />
      <p className="demo-status">Sort a column or change the page: each request below is what the transport sent to the OData-style endpoint.</p>
      <EventLog entries={log} label="OData requests" />
    </>
  );
}
```

## Initial query

There is no separate query object prop: each feature owns its
state as a reactive options prop with before and after events, and a second
query builder would duplicate that state, conflict with it and add a query
DSL to the core bundle. The initial `sorting.sortBy`, `filtering.filters`,
`search.text`, `grouping.groupBy` and `paging.page` / `pageSize` form the
initial query, which is sent to remote sources on the first read. Remote
column selection is the source's `fields`; extra request parameters
(`addParams`) go through its `headers` or a custom `transport`.

```tsx
<DataGrid
  data={orders}
  columns={columns}
  filtering={{ filters: [{ field: 'Status', operator: 'equal', value: 'Open' }] }}
  sorting={{ sortBy: [{ field: 'OrderDate', direction: 'desc' }] }}
  paging={{ pageSize: 20 }}
/>
```

## Remote editing

With `editing`, saves go to `dataSource.write`: a JSON source sends one
`{ v: 1, write }` request per save with the added rows, the changed cells
of each row and the removed keys. Batch mode collects every
pending change into that single request. A rejected write keeps the
pending changes as drafts with the error message as their row error, so
the user can retry the save; row and cell errors returned by the server
mark only the affected rows and cells.

### Live demo: Remote editing

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

Batch edits, additions and deletions saved to a remote source as one protocol write request; a failed write keeps the pending changes.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { createJsonDataSource, isWireWriteRequest, ProtocolError, type JsonTransport } from '@salmonui/data';
import { createJsonQueryHandler } from '@salmonui/data/server';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridColumn, type DataGridEditing } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders } from '../../lib/fixtures';
import type { RemoteOrder } from '../../lib/remote';

const FIELDS = ['id', 'customer', 'country', 'quantity', 'unitPrice'] as const;
type EditableOrder = Pick<RemoteOrder, (typeof FIELDS)[number]>;

const columns: DataGridColumn<EditableOrder>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 120 },
  { field: 'customer', header: 'Customer', width: 160, validation: { required: true } },
  { field: 'country', header: 'Country', width: 130 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 90, defaultValue: 1 },
  { field: 'unitPrice', header: 'Price', type: 'number', format: 'C2', align: 'end', width: 110, defaultValue: 10 },
];

let nextId = 30_000;
const editing: DataGridEditing<EditableOrder> = {
  mode: 'batch',
  confirmDelete: false,
  newRow: () => ({ id: `ORD-${nextId++}`, customer: 'New customer', country: 'Malaysia' }),
};

/**
 * The "server": the reference protocol handler from `@salmonui/data/server`
 * over a private copy of 200 orders, reached through its in-process
 * transport with 120 ms of latency. A private table per mounted demo keeps
 * writes out of the shared /api/orders table.
 */
function createServer(log: (entry: string) => void): { transport: JsonTransport; failNextWrite(): void } {
  const rows = createOrders(200, 5).map(({ id, customer, country, quantity, unitPrice }) => ({ id, customer, country, quantity, unitPrice }));
  const inner = createJsonQueryHandler(rows, { key: 'id', fields: FIELDS }).transport();
  let fail = false;
  const transport: JsonTransport = async (request, ctx) => {
    await new Promise((resolve) => setTimeout(resolve, 120));
    if (isWireWriteRequest(request)) {
      const { added, changed, removed } = request.write;
      log(`write: ${added.length} added, ${changed.length} changed (${changed.map((c) => `${String(c.key)} ${Object.keys(c.set).join('+')}`).join(', ') || '-'}), ${removed.length} removed`);
      if (fail) {
        fail = false;
        log('write rejected by the server');
        throw new ProtocolError('unavailable', 'The orders service is unavailable');
      }
    }
    return inner(request, ctx);
  };
  return { transport, failNextWrite: () => void (fail = true) };
}

export default function RemoteEditingDemo() {
  const [log, push] = useEventLog();
  // Created once per mounted grid (data sources are initial-only).
  const [server] = useState(() => createServer(push));
  const [source] = useState(() => createJsonDataSource<EditableOrder>({ transport: server.transport, key: 'id', fields: FIELDS, rowShape: 'object' }));
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={server.failNextWrite}>
          Fail the next save
        </Button>
      </div>
      <DataGrid<EditableOrder>
        aria-label="Remote orders edited in batch mode"
        data={source}
        columns={columns}
        height={340}
        locale="en-US"
        currency="USD"
        editing={editing}
        toolbar={['add', 'delete', 'save', 'cancel']}
        // onSave fires once the write settled; status tells applied, partial, rejected and error apart.
        onSave={(e) => push(`save: +${e.added.length} ~${e.changed.length} −${e.deleted.length}, ${e.status}`)}
        onError={(e) => push(`onError (${e.action}): ${e.error.message}`)}
      />
      <p className="demo-status">Edit cells, add or delete rows, then Save: all pending changes go to the server as one write request.</p>
      <EventLog entries={log} label="Server requests" />
    </>
  );
}
```

## Offline

An offline source loads a full array once, then queries it locally.

### Live demo: Offline data source

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

Loads a fetched array once and runs sorting and filtering locally.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { createOfflineDataSource } from '@salmonui/data';
import { DataGrid, type DataGridColumn } from '@salmonui/data-grid';
import { useDemoStore } from '../../components/demo-kit';
import { demoFetch, type RemoteOrder } from '../../lib/remote';

const columns: DataGridColumn<RemoteOrder>[] = [
  { 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 OfflineDataDemo() {
  const [status, statusStore] = useDemoStore('Loading…');
  const [source] = useState(() =>
    createOfflineDataSource<RemoteOrder>({
      // One fetch, then sorting and filtering run locally. Server rendering
      // leaves the load pending (demoFetch); the browser loads after hydration.
      load: async (signal) => {
        const response = await demoFetch('/api/orders?limit=3000', { signal: signal as AbortSignal });
        const rows = (await response.json()) as RemoteOrder[];
        statusStore.set(`Loaded ${rows.length} rows once; sorting and filtering are local.`);
        return rows;
      },
      onError: (error) => statusStore.set(`Load failed: ${String(error)}`),
    }),
  );
  return (
    <>
      <DataGrid<RemoteOrder>
        aria-label="Orders loaded once and queried offline"
        data={source}
        columns={columns}
        sorting
        filtering
        height={340}
        locale="en-US"
        currency="USD"
      />
      <p className="demo-status" role="status">
        {status}
      </p>
    </>
  );
}
```

## Live streams

A live source combines a snapshot with a stream of patches (upserts,
removals, appends) applied by row id, so updates do not refresh the whole
grid.

### Live demo: Live data stream

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

A snapshot plus a stream of upsert patches applied by row id without a full refresh; sorting stays live.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { createLiveDataSource } from '@salmonui/data';
import { createLocalDataSource } from '@salmonui/data-grid/engine';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridColumn } from '@salmonui/data-grid';
import { createOrders, seeded, type Order } from '../../lib/fixtures';

const initial = createOrders(500, 61);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'shipped', header: 'Shipped', type: 'boolean', displayAsCheckbox: true, align: 'center', width: 100 },
];

export default function LiveDataDemo() {
  const [running, setRunning] = useState(true);
  // Read by the stream callback, written by the button handler; never read during render.
  const [control] = useState(() => ({ running: true }));
  const [source] = useState(() =>
    createLiveDataSource<Order>({
      initial: createLocalDataSource(initial),
      getRowId: (row) => row.id,
      // The stream opens in the browser only; the server renders the snapshot.
      connect: (_query, emit) => {
        if (typeof window === 'undefined') return;
        const next = seeded(99);
        const timer = window.setInterval(() => {
          if (document.hidden || !control.running) return;
          const upsert: Order[] = [];
          for (let i = 0; i < 5; i++) {
            const base = initial[next() % 40] as Order;
            const quantity = 1 + (next() % 12);
            upsert.push({ ...base, quantity, amount: Math.round(quantity * base.unitPrice * 100) / 100, shipped: next() % 2 === 0 });
          }
          emit.patch({ upsert });
        }, 800);
        return () => window.clearInterval(timer);
      },
    }),
  );
  return (
    <>
      <div className="demo-toolbar">
        <Button
          variant="outline"
          aria-pressed={running}
          onClick={() => {
            control.running = !running;
            setRunning(!running);
          }}
        >
          {running ? 'Pause stream' : 'Resume stream'}
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders updated by a live stream"
        data={source}
        columns={columns}
        sorting
        height={340}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
      />
      <p className="demo-status">The first 40 orders receive patches every 0.8 s; sort by Amount to see rows move.</p>
    </>
  );
}
```

## Silent updates through the API

`api.setCellValue(rowId, field, value)` and `api.setRowData(rowId, row)`
change one cell or one row in place, without the edit lifecycle (no
`onBeforeCellValueChange`, no validation, no dirty mark) and without
refreshing the grid: only the touched row re-renders. Both
return a `DataGridActionResult`. They need no `editing` prop: they replace
the row of a local source, and the demo grid has no editing at all.

### Live demo: Silent cell and row updates

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

setCellValue and setRowData change one cell or one row in place without the edit lifecycle and without a full refresh; only the touched row re-renders.

`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(2_000, 23);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'product', header: 'Product', width: 140 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'priority', header: 'Priority', width: 100 },
];

export default function CellUpdatesDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <Button
          variant="outline"
          onClick={() => {
            const current = api.current?.getRow('ORD-10002');
            const result = api.current?.setCellValue('ORD-10002', 'amount', Math.round(((current?.amount ?? 0) + 100) * 100) / 100);
            push(`setCellValue(ORD-10002, amount): ${result?.status}`);
          }}
        >
          Add 100 to ORD-10002 amount
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            const current = api.current?.getRow('ORD-10003');
            if (!current) return;
            const result = api.current?.setRowData('ORD-10003', { ...current, customer: 'Updated customer', priority: 'High', quantity: 99 });
            push(`setRowData(ORD-10003): ${result?.status}`);
          }}
        >
          Replace ORD-10003
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders updated in place through the grid API"
        data={orders}
        columns={columns}
        height={320}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        onViewChange={(e) => push(`onViewChange: ${e.reason}, ${e.rowCount} rows`)}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## Application-controlled

A controlled source hands each query to the application, which returns the
rows. Saves go to `onDataChange` with the same `WriteRequest`
a remote source receives; the application persists
them and returns a `WriteResult`. Both are options of
`createControlledDataSource`, not `DataGrid` props. When the write settles,
the grid shows the rows the application applied (the rows echoed in the
`WriteResult`, else the request rows) without a re-read; rows the result
reports as failed keep their previous values.

The controlled source is also the integration point for state libraries:
Salmon UI ships no Redux sample (state library samples are not
library features); keep the rows in the store and answer `onQueryChange` and `onDataChange` from it, or
pass the store's rows to `data` and the query to the controlled feature
props (`sorting.sortBy`, `filtering.filters`, `paging.page`).

### Live demo: Controlled data operations

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

The grid hands each query to the application, which runs it and returns rows (onQueryChange), and each save, which the application persists (onDataChange); the serialized query and the writes are shown.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { createControlledDataSource } from '@salmonui/data';
import { serializeDataGridQuery } from '@salmonui/data-grid/engine';
import { type DataSourceRequest, type WriteRequest, type WriteResult } from '@salmonui/core/data';
import { DataGrid, type DataGridColumn, type DataGridEditing } from '@salmonui/data-grid';
import { EventLog, useDemoStore, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

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 },
];

const editing: DataGridEditing<Order> = { mode: 'cell', add: false, delete: false };

/** The application's own data operations: a sort over an in-memory table, and writes into it. */
function createOrderStore() {
  let table = createOrders(3_000, 51);
  const query = (request: DataSourceRequest): Order[] => {
    const rows = [...table];
    const sorting = request.query.sorting;
    if (sorting.length > 0) {
      rows.sort((a, b) => {
        for (const { columnId, direction } of sorting) {
          const x = a[columnId as keyof Order];
          const y = b[columnId as keyof Order];
          const order = x < y ? -1 : x > y ? 1 : 0;
          if (order !== 0) return direction === 'asc' ? order : -order;
        }
        return 0;
      });
    }
    return rows;
  };
  const write = (request: WriteRequest<Order>): WriteResult<Order> => {
    const changed = new Map(request.changed.map((c) => [c.rowId, c.row]));
    table = table.map((row) => changed.get(row.id) ?? row);
    return { version: request.version, status: 'applied', changed: request.changed.map((c) => ({ rowId: c.rowId, row: c.row })) };
  };
  return { query, write };
}

export default function ControlledDataDemo() {
  const [lastQuery, queryStore] = useDemoStore('');
  const [log, push] = useEventLog();
  const [source] = useState(() => {
    const store = createOrderStore();
    return createControlledDataSource<Order>({
      // Reads: the grid hands over the query; the app returns rows.
      onQueryChange: (request) => {
        const rows = store.query(request);
        queryStore.set(serializeDataGridQuery(request.query));
        const page = request.range ? rows.slice(request.range.start, request.range.end) : rows;
        return { version: request.version, rows: page, totalRowCount: rows.length };
      },
      // Writes: the grid hands over each save; the app persists it.
      onDataChange: async (request) => {
        push(`onDataChange (${request.mode}): ${request.changed.map((c) => `${c.rowId} ${c.changedColumnIds.join('+')}`).join(', ')}`);
        // The grid shows the rows echoed in the WriteResult (else the request rows) without a re-read.
        return store.write(request);
      },
    });
  });
  return (
    <>
      <DataGrid<Order>
        aria-label="Orders with application-controlled data operations"
        data={source}
        columns={columns}
        sorting
        editing={editing}
        height={320}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
      />
      <p className="demo-status">Sort a column: the serialized query below is what the application received. Double-click a cell and edit it: the save goes to onDataChange.</p>
      <pre className="demo-log" aria-label="Last query">
        {lastQuery || '(waiting for the first query)'}
      </pre>
      <EventLog entries={log} label="Writes" />
    </>
  );
}
```

## Empty state

With no rows the body shows one empty row. `renderEmpty({ reason })`
replaces its content; `reason` is `'noData'` when the source has no rows
and `'noMatch'` when the query filters every row out. Without it the grid
shows `localeText.noRows`.

### Live demo: Empty state

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

renderEmpty tells an empty data set (noData) from a query without matches (noMatch); without it the grid shows localeText.noRows.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridEmptyContext } from '@salmonui/data-grid';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(40, 31);
const none: Order[] = [];

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 },
];

// localeText.noRows replaces the default text; renderEmpty replaces the whole empty row content.
const localeText = { noRows: 'No orders yet' };

function renderEmpty({ reason }: DataGridEmptyContext) {
  return reason === 'noMatch' ? <span className="demo-empty">No order matches the filter. Clear it to see every order.</span> : <span className="demo-empty">The order book is empty.</span>;
}

export default function EmptyStateDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [rows, setRows] = useState<Order[]>(orders);
  const [custom, setCustom] = useState(true);
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => setRows(none)}>
          Remove every row
        </Button>
        <Button variant="outline" onClick={() => api.current?.filterColumn('country', 'equal', 'Atlantis')}>
          Filter to no match
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            api.current?.clearFiltering();
            setRows(orders);
          }}
        >
          Restore
        </Button>
        <Checkbox checked={custom} onCheckedChange={(checked) => setCustom(checked)}>
          renderEmpty
        </Checkbox>
      </div>
      <DataGrid<Order>
        aria-label="Orders with an empty state"
        data={rows}
        columns={columns}
        filtering
        height={260}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        localeText={localeText}
        {...(custom ? { renderEmpty } : {})}
        ref={api}
      />
    </>
  );
}
```

## Loading indicator and refresh

While the source loads, an overlay covers the body: a spinner by default,
or skeleton rows with `loadingIndicator: 'skeleton'`. The overlay
element is `.salmon-data-grid-loading` (the `loading` part of `classNames` and
`styles`) and is `aria-hidden`; the grid root carries `aria-busy`, and the
polite live region announces "Loading" after 400 ms and "Loaded {n} rows"
once the rows arrive. The empty-state row stays hidden while the source
loads. `renderLoading({ phase })` replaces the overlay content; `phase` is
`'initial'` before the first result, `'page'` while a page change loads and
`'refresh'` otherwise. `api.setLoading(true)` / `api.setLoading(false)`
show and hide the indicator by hand; a data load in progress shows it
regardless.

`api.refresh()` re-reads the data
with the current query and keeps sorting, filters, grouping, the page, the
selection and the scroll position. A local array mutated in place renders
its new values; a remote source is re-read past its cache. `onViewChange`
reports the result with `reason: 'refresh'`, and while an asynchronous read
is in flight the indicator shows with phase `'refresh'`. There is no
`refreshColumns()`: columns are a prop.

### Live demo: Loading indicator and refresh

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

The spinner or skeleton overlay while a slow source loads, renderLoading with its initial, page and refresh phases, setLoading(true/false), and refresh() re-reading the data with the current query.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { createControlledDataSource } from '@salmonui/data';
import type { DataSourceRequest } from '@salmonui/core/data';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridLoadingContext } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

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

const paging = { pageSize: 10 };

const INDICATORS = [
  { value: 'spinner', label: 'spinner' },
  { value: 'skeleton', label: 'skeleton' },
];

/** Every read of the demo "server" takes this long, so each loading phase stays on screen. */
const LATENCY = 700;

function renderLoading({ phase }: DataGridLoadingContext) {
  return <span className="demo-loading">Loading ({phase})…</span>;
}

/** An in-memory order table behind a controlled source with an artificial delay. */
function createServer(log: (entry: string) => void) {
  const table = createOrders(300, 71);
  const source = createControlledDataSource<Order>({
    onQueryChange: async (request: DataSourceRequest) => {
      const p = request.query.paging;
      const range = request.range ?? (p ? { start: (p.page - 1) * p.pageSize, end: p.page * p.pageSize } : { start: 0, end: table.length });
      log(`read: rows ${range.start + 1}-${Math.min(range.end, table.length)}`);
      await new Promise((resolve) => setTimeout(resolve, LATENCY));
      return { version: request.version, rows: table.slice(range.start, range.end), totalRowCount: table.length };
    },
  });
  // A change the grid is not told about: only refresh() shows it.
  const touch = () => {
    // ORD-10001 is the second row (ids start at ORD-10000).
    const first = table[1]!;
    table[1] = { ...first, customer: `${first.customer.replace(/ \(changed\)$/, '')} (changed)` };
  };
  return { source, touch };
}

export default function LoadingIndicatorDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [log, push] = useEventLog();
  const [server] = useState(() => createServer(push));
  const [indicator, setIndicator] = useState<'spinner' | 'skeleton'>('spinner');
  const [custom, setCustom] = useState(false);
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.setLoading(true)}>
          setLoading(true)
        </Button>
        <Button variant="outline" onClick={() => api.current?.setLoading(false)}>
          setLoading(false)
        </Button>
        <Button variant="outline" onClick={server.touch}>
          Change ORD-10001 on the server
        </Button>
        <Button variant="outline" onClick={() => api.current?.refresh()}>
          refresh()
        </Button>
        <label>
          loadingIndicator{' '}
          <Select aria-label="loadingIndicator" data={INDICATORS} value={indicator} onValueChange={(value) => value != null && setIndicator(value as 'spinner' | 'skeleton')} />
        </label>
        <Checkbox checked={custom} onCheckedChange={(checked) => setCustom(checked)}>
          renderLoading
        </Checkbox>
      </div>
      <DataGrid<Order>
        aria-label="Orders from a slow source with a loading indicator"
        data={server.source}
        columns={columns}
        paging={paging}
        loadingIndicator={indicator}
        {...(custom ? { renderLoading } : {})}
        height={340}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        onViewChange={(e) => push(`onViewChange: ${e.reason}, ${e.rowCount} of ${e.totalRowCount} rows`)}
      />
      <p className="demo-status">Every read takes {LATENCY} ms. Change the page to see the indicator; refresh() re-reads the current page.</p>
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

The sources are [`createJsonDataSource`](https://salmonui.dev/docs/reference/data/json/createJsonDataSource),
[`createOfflineDataSource`](https://salmonui.dev/docs/reference/data/local/createOfflineDataSource),
[`createLiveDataSource`](https://salmonui.dev/docs/reference/data/stream/createLiveDataSource) and
[`createControlledDataSource`](https://salmonui.dev/docs/reference/data/createControlledDataSource)
from `@salmonui/data`; the reference handler is
[`createJsonQueryHandler`](https://salmonui.dev/docs/reference/data/server/createJsonQueryHandler)
from `@salmonui/data/server`. A custom source implements
[`DataSource`](https://salmonui.dev/docs/reference/data-grid/engine/DataSource).
