# Editing

> Row, batch, dialog and cell editing; built-in and custom editors; command column; edit methods and events; saving through the data source; edit marks; confirm prompts; the unsaved-changes guard; undo and redo.

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

Editing is one prop, `editing`: `true` for inline row editing, or settings.
`editing.edit`, `editing.add` and `editing.delete` switch the three
capabilities. Drafts, flags and errors live in the core `edit`
module, never in React state: a keystroke re-renders the edited cell only.

```tsx
<DataGrid
  data={orders}
  columns={[
    { field: 'id', header: 'Order', type: 'number', primaryKey: true },
    { field: 'customer', header: 'Customer', validation: { required: true } },
    { field: 'status', header: 'Status', editor: 'select', editorProps: { options: ['Open', 'Shipped'] } },
    { id: 'commands', header: 'Actions', commands: [{ type: 'edit' }, { type: 'delete' }, { type: 'save' }, { type: 'cancel' }] },
  ]}
  editing={{ mode: 'batch', confirmDelete: true, undo: true }}
  toolbar={['add', 'edit', 'delete', 'save', 'cancel']}
  onSave={(event) => console.log(event.status, event.failedRowIds)}
/>
```

## Modes

- `mode: 'row'` (default) opens an editor in every
  editable cell of the row; Enter saves the row.
- `mode: 'dialog'` edits the row in a modal form (a native `<dialog>`: focus
  trap, inert page, Escape) with a label per field.
  `editing.dialogProps` sets the title, width, class and close button;
`renderDialog`, `renderDialogHeader` and `renderDialogFooter`
  replace its parts. While the grid is adaptive the dialog is a
  full-screen sheet, which is also how vertical card rows edit (see Adaptive UI).
- `mode: 'batch'` edits one cell at a time and keeps every change, added
  row and deleted row as a draft until `save()` writes them in one request.
- `mode: 'cell'` (Salmon UI) writes each cell when its editor closes.

Added rows appear at `newRowPosition` (`top` or `bottom`) with the
columns' `defaultValue` and `editing.newRow()` values.
`column.editable: false`, the primary key on existing rows and
`editing.isCellEditable(ctx)` make cells read-only; cancel
`onBeforeEditStart` with `preventDefault()` to refuse one edit. Group
captions, group footers, aggregate rows and detail rows are not records and
never edit: Enter on a caption expands or collapses it.

Editing needs a row identity: a `column.primaryKey` column (or `getRowId`).
Without one the grid falls back to the `id` field and warns in development
on the first edit; added rows must carry a key before they save.
`editing.edit`, `editing.add` and `editing.delete` set to `false` refuse the
matching keys, toolbar items, command buttons and methods.

### Live demo: Editing

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

Inline row, batch, dialog and cell editing with the built-in editors, a command column, validation messages, edit marks, confirm prompts, the unsaved-changes guard and undo.

`Demo.tsx`:

```tsx
'use client';

import { useMemo, useRef, useState } from 'react';
import { createLookupModule } from '@salmonui/data-grid/engine/lookup';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridEditing } 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 initialOrders = createOrders(500, 9);

// Lookup (foreign-key) table: the cell stores the key, shows the label, and edits with a select.
const categories = [
  { code: 'Coffee', label: 'Coffee beans' },
  { code: 'Tea', label: 'Loose tea' },
  { code: 'Equipment', label: 'Brewing equipment' },
];

const columns: DataGridColumn<Order>[] = [
  // Command column; the last column adds a custom command handled in `onCommandClick`.
  { id: 'commands', header: 'Actions', width: 150, commands: [{ type: 'edit' }, { type: 'delete' }, { type: 'save' }, { type: 'cancel' }] },
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150, validation: { required: true, minLength: 3 } },
  { field: 'category', header: 'Category', width: 160, lookup: { data: categories, keyField: 'code', displayField: 'label' } },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80, validation: { required: true, min: 1, max: 99 }, defaultValue: 1 },
  { field: 'unitPrice', header: 'Price', type: 'number', format: 'C2', align: 'end', width: 100, validation: { min: 0 } },
  { field: 'placed', header: 'Placed', type: 'datetime', format: 'yMMMdHm', width: 170 },
  { field: 'shipped', header: 'Shipped', type: 'boolean', displayAsCheckbox: true, align: 'center', width: 90 },
  { field: 'priority', header: 'Priority', width: 110, editor: 'select', editorProps: { options: ['Low', 'Normal', 'High'] }, defaultValue: 'Normal' },
  {
    field: 'note',
    header: 'Note (custom editor)',
    width: 220,
    // renderEditor: any element; spread inputProps for the ids, ARIA wiring and focus.
    renderEditor: ({ value, setValue, inputProps }) => (
      <input {...inputProps} className="salmon-data-grid-input salmon-data-grid-editor__input" list="demo-notes" defaultValue={String(value ?? '')} onChange={(e) => setValue(e.currentTarget.value)} />
    ),
  },
  { id: 'more', header: 'More', width: 110, commands: [{ type: 'custom', label: 'Details', title: 'Log the order details' }] },
];

type Mode = NonNullable<DataGridEditing<Order>['mode']>;
const modeItems = (['row', 'batch', 'dialog', 'cell'] as const).map((value) => ({ value, label: value }));

export default function EditingDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [mode, setMode] = useState<Mode>('row');
  const [confirmDelete, setConfirmDelete] = useState(true);
  const [confirmSave, setConfirmSave] = useState(true);
  const [confirmDiscard, setConfirmDiscard] = useState(true);
  const [data, setData] = useState(initialOrders);
  const [log, push] = useEventLog();
  const modules = useMemo(() => [createLookupModule<Order>()], []);
  const editing: DataGridEditing<Order> = {
    mode,
    confirmDelete,
    // Batch mode: a toolbar Save asks first; Cancel asks before it discards.
    confirmSave,
    confirmDiscard,
    undo: true,
    newRow: () => ({ id: `ORD-${20_000 + Math.floor(Math.random() * 10_000)}`, placed: new Date(Date.UTC(2026, 10, 11, 9)) }),
    validateRow: (row) => (row.priority === 'High' && !row.shipped && row.quantity > 10 ? 'High priority orders above 10 items must ship.' : null),
    dialogProps: { width: 520 },
  };
  return (
    <>
      <div className="demo-toolbar">
        <label>
          mode
          <Select aria-label="mode" data={modeItems} value={mode} onValueChange={(value) => value != null && setMode(value as Mode)} />
        </label>
        <Checkbox checked={confirmDelete} onCheckedChange={(checked) => setConfirmDelete(checked)}>
          confirmDelete
        </Checkbox>
        <Checkbox checked={confirmSave} onCheckedChange={(checked) => setConfirmSave(checked)}>
          confirmSave
        </Checkbox>
        <Checkbox checked={confirmDiscard} onCheckedChange={(checked) => setConfirmDiscard(checked)}>
          confirmDiscard
        </Checkbox>
        <Button variant="outline" type="button" onClick={() => push(`undo: ${api.current?.undo().status}`)}>
          Undo
        </Button>
        <Button variant="outline" type="button" onClick={() => push(`redo: ${api.current?.redo().status}`)}>
          Redo
        </Button>
        <Button variant="outline" type="button" onClick={() => void api.current?.validateBatch().then((ok) => push(`validateBatch: ${ok}`))}>
          Validate pending
        </Button>
        <Button variant="outline" type="button" onClick={() => push(`pending: ${JSON.stringify(api.current?.getBatchPreview() ? { dirty: api.current.getBatchPreview()?.dirtyCellCount, added: api.current.getBatchPreview()?.addedRowIds.length, deleted: api.current.getBatchPreview()?.deletedRowIds.length } : null)}`)}>
          Read pending changes
        </Button>
        <Button variant="outline" type="button" onClick={() => setData(initialOrders)}>
          Reset data
        </Button>
      </div>
      <datalist id="demo-notes">
        <option value="Gift wrap" />
        <option value="Leave at door" />
        <option value="Call on arrival" />
      </datalist>
      <DataGrid<Order>
        // The edit mode is initial: a new mode remounts the grid.
        key={mode}
        aria-label="Editable orders"
        data={data}
        columns={columns}
        modules={modules}
        sorting
        height={380}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        editing={editing}
        toolbar={['add', 'edit', 'delete', 'save', 'cancel']}
        onEditStart={(e) => push(`${e.source}: edit ${e.rowId}${e.field ? ` / ${e.field}` : ''}`)}
        onSave={(e) => push(`save (${e.mode}): +${e.added.length} ~${e.changed.length} −${e.deleted.length}`)}
        onAdd={(e) => push(`add at ${e.position}: ${e.rowId}`)}
        onDelete={(e) => push(`delete ${e.rowIds.join(', ')}${e.mode === 'batch' ? ' (marked until save)' : ''}`)}
        onEditCancel={(e) => push(`cancel (${e.scope})`)}
        onCommandClick={(e) => {
          if (e.command.type === 'custom') push(`details ${e.rowId}: ${e.row?.customer ?? '-'}, ${e.row?.quantity ?? 0} items`);
          else push(`command ${e.command.type} ${e.rowId}`);
        }}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## Starting and ending an edit

Double click (`editOnDoubleClick`), F2, the toolbar `edit` item
 or the command column start an edit. The keyboard
works as follows: Enter saves (batch: saves the cell
and edits the cell below; Shift+Enter the cell above), Tab and Shift+Tab
move between editable cells (`tabToNextRow` continues on the next row), Insert (Ctrl+⌘+Enter on macOS) adds a row, Delete deletes the selected rows, Escape
cancels and returns focus to the cell. `confirmDelete` asks before deleting
(default off), `confirmDiscard` before discarding a batch from Cancel or a
guarded action (default on; `confirmDiscard: false` discards at once), and
`confirmSave` before a toolbar or menu Save of a batch with pending changes
(default on; `confirmSave: false`
saves at once; `api.save()` never asks). Prompt texts are the `confirmDelete`, `confirmDiscard` and
`confirmSave` locale keys. The methods
`startEdit`, `save`, `saveCell`, `cancelEdit`, `addRow`, `deleteRows`,
`updateRow`, `updateCell` and `getPendingChanges` mirror these actions;
in batch mode `save()` writes and `cancelEdit()`
discards every pending change. `applyChanges({ added, changed, deleted })`
updates many records at once without the edit lifecycle, and
`setCellValue` / `setRowData` change one cell or row silently. Each method
returns a result (`applied`, `rejected` with a reason, or `async`); while
the lazily loaded editing code is still loading, methods return `async`,
so call them from `onReady` at startup.

Each action raises a cancelable before-event and an after-event:
`onBeforeEditStart` / `onEditStart`, `onBeforeCellValueChange` /
`onCellValueChange`, `onBeforeSave` / `onSave`, `onBeforeAdd` / `onAdd`,
`onBeforeDelete` / `onDelete`, `onBeforeEditCancel` / `onEditCancel`, and
`onCommandClick`.

`onBeforeSave` fires before the write is sent to the data source and can
cancel it; `onSave` fires once the write settled. Its `status` is
`'applied'`, `'partial'`, `'rejected'` or `'error'` (`'pending'` in the
before-event), with the source's `result` (a `WriteResult`, or null), the
thrown `error` (or null) and the `failedRowIds` that keep their drafts;
`rows()` returns the written rows. A failed save or delete also fires
`onError` with `action: 'save'`.

### Live demo: Edit methods and events

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

The editing capability flags, newRowPosition, tabToNextRow, read-only columns and isCellEditable, every edit method on the Data Grid instance and every edit event in a log.

`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 DataGridActionResult, type DataGridApi, type DataGridColumn, type DataGridEditing } 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 orders = createOrders(200, 21);

const columns: DataGridColumn<Order>[] = [
  // The primary key identifies rows for every edit; it is read-only on existing rows.
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  // Read-only column.
  { field: 'country', header: 'Country (read-only)', width: 180, editable: false },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80, defaultValue: 1 },
  { field: 'unitPrice', header: 'Price', type: 'number', format: 'C2', align: 'end', width: 100, defaultValue: 10 },
  { field: 'shipped', header: 'Shipped', type: 'boolean', displayAsCheckbox: true, align: 'center', width: 90 },
  { field: 'priority', header: 'Priority', width: 110, editor: 'select', editorProps: { options: ['Low', 'Normal', 'High'] }, defaultValue: 'Normal' },
];

type Mode = 'row' | 'batch' | 'cell';
const MODES = [
  { value: 'row', label: 'row' },
  { value: 'batch', label: 'batch' },
  { value: 'cell', label: 'cell' },
];
const POSITIONS = [
  { value: 'top', label: 'top' },
  { value: 'bottom', label: 'bottom' },
];
let nextId = 30_000;

export default function EditingApiDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [mode, setMode] = useState<Mode>('batch');
  const [flags, setFlags] = useState({ edit: true, add: true, delete: true, tabToNextRow: true, lockShipped: true, blockFirstRow: false });
  const [position, setPosition] = useState<'top' | 'bottom'>('top');
  const [log, push] = useEventLog(40);
  const toggle = (key: keyof typeof flags) => setFlags((f) => ({ ...f, [key]: !f[key] }));
  const editing: DataGridEditing<Order> = {
    mode,
    edit: flags.edit,
    add: flags.add,
    delete: flags.delete,
    newRowPosition: position,
    tabToNextRow: flags.tabToNextRow,
    confirmDiscard: false,
    guardUnsaved: false,
    // Per-cell policy: shipped orders keep their quantity.
    isCellEditable: (ctx) => !(flags.lockShipped && ctx.columnId === 'quantity' && ctx.row.shipped),
    newRow: () => ({ id: `ORD-${nextId++}` }),
  };
  const report = (label: string, result: DataGridActionResult | undefined) =>
    push(`${label}: ${result?.status ?? 'no grid'}${result?.status === 'rejected' ? ` (${result.reason})` : ''}`);
  const first = () => api.current?.getViewRows()[0]?.id;
  return (
    <>
      <div className="demo-toolbar">
        <label>
          mode
          <Select aria-label="mode" data={MODES} value={mode} onValueChange={(value) => value != null && setMode(value as Mode)} />
        </label>
        <label>
          newRowPosition
          <Select aria-label="newRowPosition" data={POSITIONS} value={position} onValueChange={(value) => value != null && setPosition(value as 'top' | 'bottom')} />
        </label>
        {(['edit', 'add', 'delete', 'tabToNextRow'] as const).map((key) => (
          <Checkbox key={key} checked={flags[key]} onCheckedChange={() => toggle(key)}>
            {key}
          </Checkbox>
        ))}
        <Checkbox checked={flags.lockShipped} onCheckedChange={() => toggle('lockShipped')}>
          isCellEditable: lock shipped Qty
        </Checkbox>
        <Checkbox checked={flags.blockFirstRow} onCheckedChange={() => toggle('blockFirstRow')}>
          onBeforeEditStart: block the first row
        </Checkbox>
      </div>
      <div className="demo-toolbar" aria-label="Edit methods">
        <Button variant="outline" onClick={() => report('startEdit', api.current?.startEdit(first(), 'customer'))}>
          startEdit(first row)
        </Button>
        <Button variant="outline" onClick={() => report('addRow', api.current?.addRow({ customer: 'Added by API' }))}>
          addRow()
        </Button>
        <Button variant="outline" onClick={() => report('deleteRows', api.current?.deleteRows())}>
          deleteRows(selected)
        </Button>
        <Button variant="outline" onClick={() => report('updateRow', api.current?.updateRow(first() ?? '', { customer: 'Updated row', quantity: 7 }))}>
          updateRow(first row)
        </Button>
        <Button variant="outline" onClick={() => report('updateCell', api.current?.updateCell(first() ?? '', 'priority', 'High'))}>
          updateCell(first row, priority)
        </Button>
        <Button variant="outline" onClick={() => report('save', api.current?.save())}>
          save()
        </Button>
        <Button variant="outline" onClick={() => report('cancelEdit', api.current?.cancelEdit())}>
          cancelEdit()
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            const changes = api.current?.getPendingChanges();
            push(`getPendingChanges: added ${changes?.addedRecords.length ?? 0}, changed ${changes?.changedRecords.length ?? 0}, deleted ${changes?.deletedRecords.length ?? 0}`);
          }}
        >
          getPendingChanges()
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            const rows = api.current?.getViewRows().slice(0, 5) ?? [];
            report('applyChanges', api.current?.applyChanges({ changed: rows.map((row) => ({ ...row, priority: 'Low' as const })) }));
          }}
        >
          applyChanges(5 rows → Low)
        </Button>
      </div>
      <DataGrid<Order>
        // `mode` and the capability flags are initial: a new value remounts the grid.
        key={`${mode}-${JSON.stringify(flags)}-${position}`}
        aria-label="Edit methods and events"
        data={orders}
        columns={columns}
        selection={{ multiple: true }}
        height={340}
        locale="en-US"
        currency="USD"
        ref={api}
        editing={editing}
        onBeforeEditStart={(e) => {
          if (flags.blockFirstRow && e.rowId === first()) {
            e.preventDefault();
            push(`onBeforeEditStart: prevented ${e.rowId}`);
          }
        }}
        onEditStart={(e) => push(`onEditStart: ${e.rowId}${e.field ? ` / ${e.field}` : ''} (${e.source})`)}
        onCellValueChange={(e) => push(`onCellValueChange: ${e.field} ${String(e.previousValue)} → ${String(e.value)}`)}
        onBeforeSave={(e) => push(`onBeforeSave: +${e.added.length} ~${e.changed.length} −${e.deleted.length}`)}
        onSave={(e) => push(`onSave (${e.mode}): +${e.added.length} ~${e.changed.length} −${e.deleted.length}`)}
        onBeforeAdd={() => push('onBeforeAdd')}
        onAdd={(e) => push(`onAdd at ${e.position}: ${e.rowId}`)}
        onBeforeDelete={(e) => push(`onBeforeDelete: ${e.rowIds.join(', ')}`)}
        onDelete={(e) => push(`onDelete: ${e.rowIds.join(', ')}`)}
        onEditCancel={(e) => push(`onEditCancel (${e.scope})`)}
      />
      <EventLog entries={log} label="Edit events" />
    </>
  );
}
```

## Command column

A column with `commands` renders buttons in every row and is never edited
itself:

```tsx
{ id: 'commands', header: 'Actions', commands: [{ type: 'edit' }, { type: 'delete' }, { type: 'save' }, { type: 'cancel' }] },
{ id: 'more', header: 'More', commands: [{ type: 'custom', label: 'Details' }] },
```

Edit and Delete show while the row is idle, Save and Cancel while it
edits, and `custom` buttons always. Each item takes a `label` (default:
the localized command name), an `icon`, a `title` and, for `custom`, an
`onClick({ rowId, row })`. `onCommandClick` receives `{ command, rowId,
row }` for every button first; `preventDefault()` cancels the built-in
command.

## Editors

`column.editor` picks a built-in editor: `text`, `number`, `select`,
`checkbox`, `date` or `datetime`; without it the column
type decides. `column.editorProps` configures it, for example the `select`
options, `min` / `max` / `step` of the `number` editor (ArrowUp
and ArrowDown step within the range; a typed number outside it is clamped
on save or blur), the picker range of the `date` editors, and `minLength` /
`maxLength` of the `text` editor. Lookup columns edit their key with a select of the
lookup rows and show the display value. `column.renderEditor(ctx)`
renders any editor; spread `ctx.inputProps` on the focusable
element to keep the ids, ARIA wiring and focus.

Column `validation` rules, custom validators and `editing.validateRow`
gate every save; see [Validation](https://salmonui.dev/docs/data-grid/validation).

## Saving to a server

Every save (a row, a cell, or a whole batch) is one call of the data
source's `write({ added, changed, deleted })` with the rows and their
changed columns. There are no per-operation URL options: wrap
your endpoint in `write`, or use a `@salmonui/data` source, which speaks
the Salmon UI JSON protocol. While the request runs the cells carry
`data-pending`. A `partial` result applies the accepted rows and keeps the
rejected ones as drafts with the server's `cellErrors` / `rowErrors` as
messages; a thrown error or a `rejected` result keeps every draft, so the
user can fix and save again. `getEditSnapshot()` reads the
current cell and row errors.

```tsx
const source: DataSource<Order> = {
  mode: 'local',
  read: (request) => store.read(request),
  subscribe: (listener) => store.subscribe(listener),
  async write(request) {
    const { added, changed, deleted } = request;
    const response = await fetch('/api/orders/batch', { method: 'POST', body: JSON.stringify({ added, changed, deleted }) });
    return response.json(); // { version, status, changed?, cellErrors?, ... }
  },
};
```

### Live demo: Saving to a server

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

Batch saves go to dataSource.write as one request with added, changed and deleted rows; a simulated server rejects some cells or fails, and the grid keeps the drafts with the server errors.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { createLocalDataSource, type DataSource } from '@salmonui/data-grid/engine';
import { type WriteRequest, type WriteResult } from '@salmonui/core/data';
import { DataGrid, type DataGridColumn } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useDemoStore, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const OUTCOMES = [
  { value: 'reject-names', label: 'rejects names containing “reject”' },
  { value: 'accept', label: 'accepts everything' },
  { value: 'offline', label: 'offline (request fails)' },
];

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

const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

type Outcome = 'accept' | 'reject-names' | 'offline';

/**
 * A simulated server behind `dataSource.write()`: every save is one request
 * with `added`, `changed` and `deleted`. The server rejects
 * customer names containing "reject" with a field error (partial write) or
 * fails the whole request while "offline"; the grid keeps the drafts with the
 * errors.
 */
function createDemoServer(outcome: { current: Outcome }, push: (entry: string) => void): DataSource<Order> {
  const store = createLocalDataSource(createOrders(80, 13), { getRowId: (row) => row.id });
  return {
    mode: 'local',
    read: (request) => store.read(request),
    subscribe: (listener) => store.subscribe(listener),
    capabilities: { write: true },
    async write(request: WriteRequest<Order>): Promise<WriteResult<Order>> {
      push(`write (${request.mode}): +${request.added.length} ~${request.changed.length} −${request.deleted.length}`);
      await delay(500);
      if (outcome.current === 'offline') {
        push('write failed: server unavailable');
        throw new Error('Server unavailable');
      }
      const rejected = outcome.current === 'reject-names' ? request.changed.filter((c) => c.row.customer.toLowerCase().includes('reject')) : [];
      if (rejected.length === 0) {
        push('write applied');
        return store.write(request);
      }
      const accepted = await store.write({ ...request, changed: request.changed.filter((c) => !rejected.includes(c)) });
      push(`write partial: rejected ${rejected.map((c) => c.rowId).join(', ')}`);
      return {
        ...accepted,
        status: 'partial',
        changed: accepted.changed ?? [],
        cellErrors: Object.fromEntries(rejected.map((c) => [`${c.rowId}:customer`, ['The server rejected this customer name.']])),
      };
    },
  };
}

export default function EditingServerDemo() {
  const [log, push] = useEventLog();
  const [outcome, outcomeStore] = useDemoStore<Outcome>('reject-names');
  // A mutable box the data source reads at write time (the source is created once).
  const [box] = useState<{ current: Outcome }>(() => ({ current: 'reject-names' }));
  const [source] = useState(() => createDemoServer(box, push));
  const choose = (next: Outcome) => {
    box.current = next;
    outcomeStore.set(next);
  };
  return (
    <>
      <div className="demo-toolbar">
        <label>
          server
          <Select aria-label="server" data={OUTCOMES} value={outcome} onValueChange={(value) => value != null && choose(value as Outcome)} />
        </label>
      </div>
      <DataGrid<Order>
        aria-label="Orders saved through dataSource.write"
        data={source}
        columns={columns}
        height={320}
        locale="en-US"
        currency="USD"
        editing={{ mode: 'batch', confirmDiscard: false }}
        toolbar={['add', 'delete', 'save', 'cancel']}
      />
      <p className="demo-status">
        Edit a few customers (type “reject” in one), then Save: one request carries every change. Pending cells show
        while the request runs; rejected cells keep their draft with the server message.
      </p>
      <EventLog entries={log} label="Server requests" />
    </>
  );
}
```

Batch mode works with row and column virtualization. Drafts, delete marks and added rows are
keyed by row id in the core, so an edited row keeps its draft and marks
after it scrolls out of the DOM and back, and an open editor comes back
with its text. Enter, Shift+Enter, Tab and Shift+Tab move through the row
model, scroll the next cell into view and focus its editor when it mounts;
`save()` and `cancelEdit()` cover rows that are not rendered.

### Live demo: Batch editing over 100,000 rows

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

Batch mode with row virtualization; drafts survive scrolling, and group captions stay read-only when the rows are grouped.

`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 } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

// 100,000 virtualized rows in batch mode: drafts live in the core edit
// module, keyed by row id, so they survive scrolling rows out of the DOM.
// Group captions are not records and never edit.
const orders = createOrders(100_000, 17);

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

export default function BatchVirtualDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [grouped, setGrouped] = useState(false);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={grouped} onCheckedChange={(checked) => setGrouped(checked)}>
          Group by country
        </Checkbox>
        <Button variant="outline" type="button" onClick={() => api.current?.scrollToRow('ORD-109999')}>
          Scroll to the last row
        </Button>
        <Button variant="outline" type="button" onClick={() => api.current?.scrollToRow('ORD-10000')}>
          Scroll to the first row
        </Button>
        <Button
          variant="outline"
          type="button"
          onClick={() => {
            const preview = api.current?.getBatchPreview();
            push(`pending: ${preview?.dirtyCellCount ?? 0} dirty cells, ${preview?.addedRowIds.length ?? 0} added, ${preview?.deletedRowIds.length ?? 0} deleted`);
          }}
        >
          Read pending changes
        </Button>
      </div>
      <DataGrid<Order>
        key={grouped ? 'grouped' : 'flat'}
        aria-label="Batch editing over 100,000 virtualized rows"
        data={orders}
        columns={columns}
        height={360}
        locale="en-US"
        currency="USD"
        ref={api}
        editing={{ mode: 'batch', confirmDiscard: false, guardUnsaved: false }}
        toolbar={['save', 'cancel']}
        {...(grouped ? { grouping: { groupBy: ['country'] } } : {})}
        onSave={(e) => push(`saved: ~${e.changed.length} rows`)}
      />
      <p className="demo-status">Edit a cell, scroll to the end and back: the draft and its mark stay. Group captions expand and collapse on Enter; they never open an editor.</p>
      <EventLog entries={log} />
    </>
  );
}
```

## Always-visible add row

`editing.showNewRow` keeps a blank add row at
`newRowPosition` in row mode. It shows its editors at rest and
is already in the server markup (empty cells until the editing code
loads). Type into it and press Enter, use Save, or Tab past its last cell
to write the record; a fresh blank row follows and takes focus, so entry
continues row after row. Escape clears it and returns focus to the grid;
leaving it untouched writes nothing. While another row edits, the add row
is disabled (`aria-disabled`, disabled editors). Insert, the toolbar `add`
item and `addRow(values)` fill this row instead of opening a second one;
it cannot be deleted, and it counts as an unsaved change only once a value
changed. Batch, dialog and cell modes ignore it (a development warning
says so). Under virtual scrolling it stays at `bottom` too: the added-rows
band is sticky.

### Live demo: Always-visible add row

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

editing.showNewRow keeps a blank add row at newRowPosition; Enter saves it and a fresh one follows.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { DataGrid, type DataGridColumn } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

// The always-visible add row: row
// mode only. Type into it and press Enter to save; a fresh blank row
// follows. Escape clears it; it is disabled while another row edits.
const orders = createOrders(2_000, 5);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 120 },
  { field: 'customer', header: 'Customer', width: 170, validation: { required: true } },
  { field: 'country', header: 'Country', width: 130 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 90, defaultValue: 1, validation: { min: 1 } },
  { field: 'shipped', header: 'Shipped', type: 'boolean', displayAsCheckbox: true, width: 100 },
];

const ADD_ROW_POSITION_OPTIONS = [
  { value: 'top', label: 'top' },
  { value: 'bottom', label: 'bottom' },
];

export default function NewRowDemo() {
  const [position, setPosition] = useState<'top' | 'bottom'>('top');
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Add row position
          <Select aria-label="Add row position" data={ADD_ROW_POSITION_OPTIONS} value={position} onValueChange={(value) => value != null && setPosition(value as 'top' | 'bottom')} />
        </label>
      </div>
      <DataGrid<Order>
        aria-label="Orders with an always-visible add row"
        data={orders}
        columns={columns}
        height={360}
        locale="en-US"
        editing={{ showNewRow: true, newRowPosition: position }}
        onSave={(e) => push(`saved: ${e.added.length} added, ${e.changed.length} changed`)}
        onEditCancel={() => push('cancelled')}
      />
      <p className="demo-status">Type an order id and a customer in the add row, press Enter: the order is saved and a fresh add row takes focus. Double click another row: the add row is disabled until that edit ends.</p>
      <EventLog entries={log} />
    </>
  );
}
```

## Marks, guard and undo

Changed cells, invalid cells, pending writes, added rows and deleted rows
carry `data-dirty`, `data-invalid`, `data-pending`, `data-new` and
`data-deleted`; `getBatchPreview()` lists the diff for a review
UI. With unsaved changes, `editing.guardUnsaved` (on by default in batch
mode) asks before sorting, filtering, searching, paging or grouping
discards them, and warns on page unload. `editing.undo` records
edits for `undo()` / `redo()` and Ctrl/⌘+Z / Ctrl/⌘+Y (also
Ctrl/⌘+Shift+Z), keeping `undoLimit` entries (default 10).

## Formulas

The grid has no formula cells: a reference grammar, dependency graph and recalculation pass are
spreadsheet territory and would sit on the edit path. A value computed from
other fields of the same row is a computed column, `column.valueGetter(row)`,
which sorts, filters, groups, aggregates and exports like any column. When
the exported workbook must keep a live formula, return it from the XLSX
export `cell` hook: `cell: (ctx) => ({ formula: 'B2*C2' })`
([Export](https://salmonui.dev/docs/data-grid/export); the export demo writes its Stretch column as a
formula). Cross-row or user-entered formulas belong in a spreadsheet
component.

## API reference

See [`DataGridEditing`](https://salmonui.dev/docs/reference/data-grid/DataGridEditing),
[`DataGridEditColumn`](https://salmonui.dev/docs/reference/data-grid/DataGridEditColumn),
[`DataGridCommandItem`](https://salmonui.dev/docs/reference/data-grid/DataGridCommandItem),
[`DataGridSaveEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridSaveEvent) and
the edit methods of [`DataGridApi`](https://salmonui.dev/docs/reference/data-grid/DataGridApi)
in the API reference.
