Birch UI v0.1
Pricing

Editing

Make cells editable with built-in text, number, select, checkbox and date editors or your own, parse input with valueParser and react to cellValueChanged.

Open .md

Cells become editable with editable on the column. The grid picks an editor from the column type, parses what the user typed, writes the value back to the row and fires cellValueChanged. Everything is keyboard-first: users can tab through a row editing as they go without touching the mouse.

Inline editing

Loading demo…

View source

Sample data and small UI helpers are imported from the docs' demos/_shared.ts and demos/_scheduler-data.ts files.

demos/editing.ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { docsTheme, formatCurrency, layout, makeOrders, onDocsThemeChange, revenueOf, type Order } from './_shared';

export const meta = { title: 'Inline editing', height: 440 };

const columns: ColumnDef<Order>[] = [
  { field: 'id', header: 'Order', width: 110 },
  { field: 'customer', header: 'Customer', flex: 1, minWidth: 170, editable: true },
  {
    field: 'status',
    header: 'Status',
    width: 130,
    editable: true,
    editor: 'select',
    options: ['Pending', 'Shipped', 'Delivered', 'Returned'],
  },
  {
    field: 'quantity',
    header: 'Qty',
    type: 'number',
    width: 90,
    editable: true,
    editor: 'number',
    valueParser: (input) => Math.max(1, Math.round(Number(input))),
  },
  { field: 'shipped', header: 'Shipped', type: 'boolean', width: 100, editable: true, editor: 'checkbox' },
  { field: 'orderDate', header: 'Ordered', type: 'date', width: 130, editable: true, editor: 'date' },
  { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  toolbar.append('Double-click, press Enter or F2, or just start typing. Escape cancels, Enter or Tab commits.');
  const grid = createGrid<Order>(body, {
    columns,
    rows: makeOrders(200, 7),
    getRowId: (order) => order.id,
    theme: docsTheme(),
    ariaLabel: 'Editable orders',
  });
  status.textContent = 'No changes yet.';
  const off = grid.on('cellValueChanged', ({ row, colId, oldValue, newValue }) => {
    status.textContent = `${row.id}: ${colId} changed from ${String(oldValue)} to ${String(newValue)}`;
  });
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    off();
    stopTheme();
    grid.destroy();
  };
}

Making columns editable#

editable is true, false or a function of the cell context, so you can lock cells per row.

invoice-editing.ts
import { createGrid, type ColumnDef } from '@birchui/core';

interface InvoiceLine {
  id: string;
  description: string;
  quantity: number;
  unitPrice: number;
  taxCode: 'STD' | 'RED' | 'ZERO';
  billable: boolean;
  serviceDate: string;
  locked: boolean;
}

const columns: ColumnDef<InvoiceLine>[] = [
  { field: 'description', flex: 1, editable: (ctx) => !ctx.row?.locked },
  { field: 'quantity', type: 'number', editable: true, width: 100 },
  { field: 'unitPrice', header: 'Unit price', type: 'number', editable: true, width: 120 },
  {
    field: 'taxCode',
    header: 'Tax',
    editable: true,
    options: [
      { value: 'STD', label: 'Standard 20%' },
      { value: 'RED', label: 'Reduced 5%' },
      { value: 'ZERO', label: 'Zero-rated' },
    ],
    format: (v) => ({ STD: 'Standard 20%', RED: 'Reduced 5%', ZERO: 'Zero-rated' })[v as InvoiceLine['taxCode']] ?? '',
  },
  { field: 'billable', type: 'boolean', editable: true, width: 90 },
  { field: 'serviceDate', header: 'Service date', type: 'date', editable: true },
];

const grid = createGrid<InvoiceLine>(document.querySelector('#invoice-lines')!, {
  columns,
  rows: lines,
  getRowId: (line) => line.id,
});

grid.on('cellValueChanged', async ({ row, colId, newValue, oldValue, source }) => {
  if (source !== 'edit') return;
  const response = await fetch(`/api/invoice-lines/${row.id}`, {
    method: 'PATCH',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ [colId]: newValue }),
  });
  if (!response.ok) grid.setValue(row, colId, oldValue);
});

To make a whole grid editable, set defaultColumn: { editable: true } and opt individual columns out with editable: false.

Built-in editors#

Without an editor, the grid chooses one:

Column Editor Value written
Has options select: a native select listing the options The option's value
type: 'boolean' checkbox true or false
type: 'date' date: a native date input Same representation as the old value: an ISO string stays a YYYY-MM-DD string, a number stays epoch milliseconds, otherwise a Date
type: 'number' number: a text input with a decimal keypad on touch devices A number, or null when cleared
Anything else text The string typed

Force a specific editor with editor: 'text' | 'number' | 'select' | 'checkbox' | 'date'.

Select options#

options is a list of strings, numbers or { value, label } pairs. Labels are shown, values are written. The select editor commits as soon as the user picks an option.

TypeScript
const columns: ColumnDef<Ticket>[] = [
  { field: 'priority', editable: true, options: ['Low', 'Normal', 'High', 'Urgent'] },
  {
    field: 'technicianId',
    header: 'Technician',
    editable: true,
    options: technicians.map((t) => ({ value: t.employeeId, label: t.name })),
    format: (id) => technicians.find((t) => t.employeeId === id)?.name ?? 'Unassigned',
  },
];

Use format to show the label in the cell as well, as above; the grid displays the raw value otherwise.

Parsing input: valueParser#

Text-based editors (text, number and date) produce a string. The grid converts it by column type: numbers through a lenient parser that accepts thousands separators (an empty input becomes null), dates through Date parsing (an invalid date keeps the previous value), and booleans from words such as yes and no. valueParser(input, row) replaces that conversion.

TypeScript
const columns: ColumnDef<InvoiceLine>[] = [
  {
    field: 'unitPrice',
    type: 'number',
    editable: true,
    valueParser: (input) => {
      const normalized = input.replace(/[^\d,.-]/g, '').replace(',', '.');
      const value = Number.parseFloat(normalized);
      return Number.isFinite(value) ? Math.round(value * 100) / 100 : null;
    },
  },
  {
    field: 'description',
    editable: true,
    valueParser: (input) => input.trim().replace(/\s+/g, ' '),
  },
];

Writing values: valueSetter#

The parsed value is written with the column's valueSetter, or to field when there is none. Use a setter to update derived fields, validate, or write to a nested structure:

TypeScript
const columns: ColumnDef<InvoiceLine>[] = [
  {
    field: 'quantity',
    type: 'number',
    editable: true,
    valueSetter: (line, value) => {
      const quantity = Math.max(0, Math.round(Number(value) || 0));
      line.quantity = quantity;
      line.total = quantity * line.unitPrice;
    },
  },
];

Keyboard and mouse#

Input When Action
Enter or F2 A cell is focused Start editing with the current value selected
Any printable character A cell is focused Start editing and replace the value with the typed character
Space A checkbox cell is focused and row selection is off Start editing and toggle the checkbox
Delete or Backspace An editable cell is focused Clear the value: an empty string for text columns, null for other types
Double-click Any editable cell Start editing
Enter Editing Commit
Tab / Shift+Tab Editing Commit and start editing the next or previous editable cell, wrapping across rows
Escape Editing Cancel and keep the previous value

To change what a key does on a focused cell, listen to cellKeyDown and call preventDefault(). The grid then skips its own handling, so you can replace Delete with your own action or stop typing from opening an editor:

TypeScript
grid.on('cellKeyDown', ({ event, row, colId }) => {
  const key = event as KeyboardEvent;
  if (key.key === 'Delete' && row) {
    key.preventDefault();
    if (confirm(`Remove "${row.description}" from the invoice?`)) grid.applyTransaction({ remove: [row] });
  } else if (colId === 'serviceDate' && row?.locked && key.key.length === 1) {
    key.preventDefault();
  }
});

cellKeyDown does not fire while an editor is open; keys inside an editor belong to the editor.

A select editor commits as soon as an option is chosen. Starting an edit in another cell, from the keyboard or with startEdit(), commits the edit in progress first. Clearing a cell with Delete fires cellValueChanged with source: 'edit'.

Only data rows can be edited. Group, total and detail rows and generated columns such as the selection checkbox column are never editable. See Keyboard navigation & accessibility for the complete key map.

Custom editors#

An editor can be a factory function. It receives CellEditorParams (the cell context plus initialInput, commit() and cancel()) and returns a CellEditor: an element, a getValue() function, a focus() function and an optional destroy().

CellEditorinterface@birchui/coreFull reference
PropertyTypeDescription
elementHTMLElement—
getValue()() => unknown—
focus()() => void—
destroy()optional() => void—
currency-editor.ts
import type { CellEditorFactory } from '@birchui/core';

export const currencyEditor: CellEditorFactory<InvoiceLine> = (params) => {
  const wrapper = document.createElement('div');
  wrapper.className = 'currency-editor';

  const symbol = document.createElement('span');
  symbol.textContent = '€';

  const input = document.createElement('input');
  input.inputMode = 'decimal';
  input.setAttribute('aria-label', params.column.header);
  input.value = params.initialInput ?? String(params.value ?? '');

  input.addEventListener('keydown', (event) => {
    if (event.key === 'Enter') {
      event.preventDefault();
      params.commit();
    } else if (event.key === 'Escape') {
      event.preventDefault();
      params.cancel();
    }
    event.stopPropagation();
  });

  wrapper.append(symbol, input);

  return {
    element: wrapper,
    getValue: () => Number.parseFloat(input.value.replace(',', '.')),
    focus: () => {
      input.focus();
      if (params.initialInput === undefined) input.select();
    },
  };
};
TypeScript
const columns: ColumnDef<InvoiceLine>[] = [
  { field: 'unitPrice', header: 'Unit price', type: 'number', editable: true, editor: currencyEditor },
];

Notes for custom editors:

  • getValue() returns the final value. valueParser is not applied to values from custom editors (or from the select and checkbox editors), so return the type you want stored.
  • Call params.commit() and params.cancel() from your own key handling. Stop propagation of keys your editor uses so the grid does not treat them as navigation.
  • initialInput is the character the user typed to start editing, or undefined when editing started with Enter, F2, a double click or the API.
  • Release anything you registered outside your element in destroy().

Editing from code#

TypeScript
grid.startEdit(3, 'quantity');
grid.startEdit(3, 'description', 'R');
grid.stopEdit();
grid.stopEdit(true);
grid.isEditing();

startEdit(rowIndex, colId, initialInput?) focuses and scrolls to the cell and returns false when the row or column does not exist or the cell is not editable. stopEdit(cancel?) commits, or cancels when passed true; it does nothing when no editor is open.

GridApiinterface@birchui/coreFull reference
MemberTypeDescription
setValue()(row: TRow, colId: string, value: unknown, source?: CellValueChangedEvent['source']) => boolean—
startEdit()(rowIndex: number, colId: string, initialInput?: string) => boolean—
stopEdit()(cancel?: boolean) => void—
isEditing()() => boolean—

Edit events#

TypeScript
grid.on('editStart', ({ rowIndex, colId }) => toolbar.classList.add('is-editing'));
grid.on('editStop', ({ rowIndex, colId, cancelled }) => toolbar.classList.remove('is-editing'));

grid.on('cellValueChanged', ({ row, rowIndex, colId, oldValue, newValue, source }) => {
  if (source === 'edit') audit.push({ invoiceLine: row.id, field: colId, from: oldValue, to: newValue });
});

cellValueChanged fires after the value is written, and only when the value actually changed: committing an editor without changing the value fires editStop but not cellValueChanged. source tells you where the change came from:

source Origin
edit A user edit in a cell editor
api setValue() from your code
paste Clipboard paste (Grid Pro)
fill Fill handle drag (Grid Pro)
CellValueChangedEventinterface@birchui/coreFull reference
PropertyTypeDescription
rowTRow—
rowIndexnumber—
colIdstring—
oldValueunknown—
newValueunknown—
source'edit' | 'paste' | 'fill' | 'api' | 'undo' | 'redo'—

Validation and rollback#

Validate in valueSetter to reject values before they are stored. If a valueSetter throws, the grid reports the error with console.error, keeps the old value and fires no cellValueChanged. To roll back after an asynchronous save fails, call setValue(row, colId, oldValue) as in the first example on this page.

↑ ↓ to move, Enter to open, Esc to close