In-cell editing for document forms
An order, a delivery note, an invoice or a stock movement is a document:
header fields at the top, and below them a grid of lines the user types into
directly — a code, a quantity, a price, a "…" button that opens a picker. This
page puts the pieces of EnterpriseDataGrid together for that screen. Every
option on it is off by default, so a grid without them behaves exactly as
described in Editing.
There are two ways to save the lines:
| Set-up | Options | The server sees |
|---|---|---|
| Batch — save the document as a whole | mode: 'batch' | one onSave call with every pending line, when the app calls saveChanges() |
| Instant — each line on its own | mode: 'cell', commitOn: 'row' | one onSave call per line, when the user leaves that line |
Both need Enterprise. The options are React
options: they are not in the plain-JavaScript createGrid yet.
The complete example
One component, both set-ups (instant switches them). The block at the top
stands in for your application: the server call, your confirm dialog and your
id generator. Everything else is the grid.
import { useEffect, useRef, useState } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { EnterpriseDataGrid, SaveRejected } from '@kanunilabs/datagrid-react-enterprise';
import type { EditingApi, LookupItem, RowChange } from '@kanunilabs/datagrid-core';
import type { EditorRenderContext, ReactGridColumnDef } from '@kanunilabs/datagrid-react';
interface Line {
ID: string; // the app's own key, also for rows that are not saved yet
itemCode: string | null;
itemName: string | null;
itemId: string | null;
colorCode: string | null;
colorName: string | null;
quantity: number | null;
price: number | null;
}
// --- Your application's side. Stand-ins so the example runs as it is. ---
const items: LookupItem[] = [
{ value: 'IP-01', label: 'İPLİK 30/1', id: 'a91f' },
{ value: 'KU-07', label: 'KUMAŞ Penye', id: 'b20c' },
{ value: 'DU-12', label: 'Düğme 12 mm', id: 'c7e4' },
];
const colors = [
{ code: 'R-01', name: 'Kırmızı' },
{ code: 'L-02', name: 'Lacivert' },
{ code: 'S-03', name: 'Siyah' },
];
/** A 32-character key without `crypto.randomUUID()`, which plain-HTTP pages lack. */
function newId(): string {
let id = Date.now().toString(16);
while (id.length < 32) id += Math.floor(Math.random() * 16).toString(16);
return id.slice(0, 32);
}
/** POST the lines; the server answers with the lines it refused, if any. */
async function sendLines(
changes: RowChange<Line>[],
): Promise<{ rowKey: string; columnId?: string; message: string }[]> {
const response = await fetch('/api/order-lines', { method: 'POST', body: JSON.stringify(changes) });
return response.ok ? [] : (await response.json()).refused;
}
/** Your own confirm dialog (here the browser's). */
async function askDelete(row: Line | undefined): Promise<boolean> {
return window.confirm(`Delete line ${row?.itemCode ?? ''}?`);
}
// -------------------------------------------------------------------------
/** The "…" cell: a text box plus a button that opens a picker dialog. */
function ColorEditor({ ctx }: { ctx: EditorRenderContext<Line> }) {
const [open, setOpen] = useState(false);
const input = useRef<HTMLInputElement | null>(null);
useEffect(() => input.current?.focus(), []);
const openPicker = (next: boolean) => {
// While the dialog has the focus, leaving the editor is not a commit.
if (next) ctx.suspendBlurCommit(true);
setOpen(next);
if (!next) ctx.suspendBlurCommit(false);
};
const pick = (color: { code: string; name: string }) => {
// Code and name in ONE step: one undo step, one validation, one save.
ctx.api.setRowValues({ colorCode: color.code, colorName: color.name });
openPicker(false);
};
return (
<div onBlur={ctx.commitOnBlur} style={{ display: 'flex', width: '100%' }}>
<input
ref={input}
aria-label={ctx.ariaLabel}
aria-invalid={ctx.invalid || undefined}
aria-errormessage={ctx.errorId}
value={String(ctx.value ?? '')}
onChange={(e) => ctx.setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'F4') {
e.preventDefault();
openPicker(true);
} else if (e.key === 'Enter') {
e.preventDefault();
ctx.commit({ move: 'none' }); // Enter stays on the cell
}
}}
style={{ flex: 1, minWidth: 0 }}
/>
<Dialog.Root open={open} onOpenChange={openPicker}>
<Dialog.Trigger asChild>
<button type="button" aria-label="Pick a colour" style={{ minWidth: 32 }}>…</button>
</Dialog.Trigger>
<Dialog.Portal>
<Dialog.Content aria-describedby={undefined} className="color-picker">
<Dialog.Title>Colour</Dialog.Title>
{colors.map((color) => (
<button key={color.code} type="button" onClick={() => pick(color)} style={{ display: 'block', minHeight: 44 }}>
{color.code} — {color.name}
</button>
))}
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
</div>
);
}
const columns: ReactGridColumnDef<Line>[] = [
{
field: 'itemCode',
headerName: 'Item',
width: 110,
lookup: {
items,
// Picking writes the code, the name and the id together.
linkedColumns: { code: 'itemCode', name: 'itemName', id: 'itemId' },
matchMode: { code: 'startsWith', name: 'contains' },
autoCompleteSingle: false, // typing only filters; Enter picks the highlighted item
onNoMatch: 'revert', // an unpicked text is dropped when the cell is left
},
},
{ field: 'itemName', headerName: 'Name', width: 160, editable: false },
{ field: 'colorCode', headerName: 'Colour', width: 120, renderEditor: (ctx) => <ColorEditor ctx={ctx} /> },
{ field: 'colorName', headerName: 'Colour name', width: 120, editable: false },
{
field: 'quantity',
headerName: 'Quantity',
width: 100,
dataType: 'number',
numberFormat: { locale: 'tr-TR', decimals: 2, step: 1 }, // "1.234,5"; a return is negative
},
{
field: 'price',
headerName: 'Price',
width: 110,
dataType: 'number',
numberFormat: { locale: 'tr-TR', decimals: 2, min: 0, allowNegative: false },
},
];
export function OrderLines({ lines, instant }: { lines: Line[]; instant: boolean }) {
const api = useRef<EditingApi<Line> | null>(null);
const [dirty, setDirty] = useState(false);
// "Unsaved changes?" when the page is closed with pending lines.
useEffect(() => {
if (!dirty) return;
const warn = (e: BeforeUnloadEvent) => e.preventDefault();
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [dirty]);
return (
<EnterpriseDataGrid<Line>
gridId="order-lines"
dataSource={lines}
rowKey="ID"
columns={columns}
locale="tr"
style={{ height: 360 }}
rowStatus={{ icons: true, messages: true, strike: true }}
rowClassName={({ row }) => ((row?.quantity ?? 0) < 0 ? 'line-return' : undefined)}
cardView={{
columns: ['itemCode', 'itemName', 'quantity', 'price'],
edit: 'popup', // a tap on a phone card opens the line in a dialog
onCardPress: (rowKey) => console.log('card', rowKey),
}}
onReady={(controller) => {
controller.events.on('changesChanged', ({ dirty }) => {
setDirty(dirty);
});
}}
onKeyDown={(event, ctx) => {
if (event.key !== 'F2') return;
// F2 is the form's Save: take the value being typed, then save.
event.preventDefault();
if (ctx.commit()) void api.current?.saveChanges();
return 'handled';
}}
editing={{
enabled: true,
mode: instant ? 'cell' : 'batch',
commitOn: instant ? 'row' : undefined, // instant: one save per row, when it is left
batchBar: false, // the form has its own Save button
allowAdding: true,
allowDeleting: true,
editKeys: { f2: false, enter: true }, // Enter opens and closes the editor
insertKey: 'above',
appendOnArrowDown: true,
appendOnTab: true,
deleteKey: true,
confirmDelete: (_rowKey, row) => askDelete(row),
fillKeys: false, // Ctrl+R / Ctrl+D stay the page's
rangePaste: false, // a paste goes to one cell
onInitNewRow: (values) => {
values.ID = newId(); // this key stays the row's key, before and after saving
},
onReady: (editing) => {
api.current = editing;
},
onSave: async (changes) => {
const refused = await sendLines(changes);
// Nothing is saved; the refused lines read `error` with the message.
if (refused.length > 0) throw new SaveRejected(refused);
},
}}
/>
);
}
The sections below explain each part.
The keyboard
With the settings above the grid behaves like a desktop data-entry form:
| Key | Editor closed | Editor open |
|---|---|---|
| Enter | opens the editor of the focused cell (editKeys.enter) | keeps the value and closes the editor; the focus stays on the cell. Enter never adds a row |
| typing | opens the editor with that character — also - and the decimal separator on a number cell, and a digit on a date cell | the editor's |
| double-click / double-tap | opens the editor (the grid counts the second tap itself on touch screens) | — |
| F2 | not handled by the grid (editKeys.f2: false): it reaches onKeyDown and the page | same — ctx.commit() keeps the value being typed before your Save runs |
| Tab / Shift+Tab | next / previous editable cell, row after row; on the last cell of the last row Tab adds a line (appendOnTab) | keeps the value and moves the same way |
| arrow down on the last line | adds a line (appendOnArrowDown) | the editor's |
| Insert | adds a blank line above the focused one and opens its first editable cell (insertKey: 'above') | the text box's |
| Ctrl+Delete | deletes the focused line after confirmDelete agrees (deleteKey); in batch the line is struck through and the same key restores it | the text box's (deletes the next word) |
| Ctrl+R / Ctrl+D | left to the page (fillKeys: false) | the editor's |
| Ctrl+V | pastes into the focused cell only, as one value (rangePaste: false) | the editor's |
Two rules hold whatever the settings: the grid does nothing with a key whose
event is already defaultPrevented (a page shortcut that a window listener
handled first), and nothing with a combination that includes Alt — so
Alt+PageDown can switch the page's tabs without scrolling the grid. Typing a
character with AltGr (Ctrl+Alt on Windows) still opens the editor.
onKeyDown(event, ctx) runs for every key pressed inside the grid, before the
grid and before an open editor. ctx tells you whether an editor is open, which
cell, whether its row is new, and gives you commit() and cancel(). Return
'handled' and the grid ignores the key.
editKeys.doubleClick: false turns off double-click and double-tap editing if
your screen opens the line some other way.
Row keys and new lines
rowKey="ID" with onInitNewRow setting values.ID makes the key yours:
a line added by Insert, arrow-down, Tab or api.addRow() carries that key in
the grid, in getChanges() and in onSave, and keeps it after it is saved.
Without a value the grid would use a temporary key of its own.
Under commitOn: 'row' a line nothing was typed into is never sent: leave it,
press Escape or click outside the grid and it disappears. The values
onInitNewRow seeds (the key, defaults) do not count as typing.
Numbers
numberFormat reads and shows numbers in a locale — here Turkish, where the
comma is the decimal separator and the dot groups thousands:
- the closed cell shows
1.234,50(decimals: 2); the open editor shows1234,5to edit; 1,5,1.234and1.234,5are read as 1.5, 1234 and 1234.5.1.5and12.34are refused with a message rather than guessed;- the value is rounded to
decimals(half away from zero:1,555→ 1.56); min,maxandallowNegative: falserefuse values outside the range;stepmakes the arrow keys step the value (Ctrl ×10);restrictInput: truerefuses, while typing, what can never become a number — a letter, a second comma, a late minus — instead of refusing it on save; a paste goes in when the whole text reads as a number (React);- phones get the decimal keyboard (
inputmode="decimal",numericwithdecimals: 0).
Without locale the grid's own locale is used — never the browser's
language. A column's valueParser still wins over the format when it is set.
Code + name
linkedColumns: { code, name, id } makes one lookup fill three columns: the
list shows code and name together, filters on both (matchMode per field) and
writes code, name and id in one step — one undo step and one change. The
name and id columns can stay editable: false; only the pick writes them.
autoCompleteSingle: false is the strict data-entry rule: typing only filters
the list, it never picks by itself — not even when one item is left. The user
picks with a click, a tap or the arrows and Enter. Enter with nothing
highlighted keeps the editor open and announces "no match"; with
onNoMatch: 'revert' leaving the cell drops the unpicked text and keeps the old
value.
A lookup whose items is a function of the row (a dealer list that depends on
the customer) shows labels in the closed cell too; give it dependsOn so the
answers are cached per row and parent value. When the parent changes and the
old value is no longer in the list, it is cleared.
A "…" picker in a cell
A lookup that is too long to scroll — every customer, every stock item —
usually also needs a search dialog. Give the lookup onPickerOpen and the
open editor gets a "…" button (and Ctrl+Enter) that calls it:
lookup: {
items: stockItems,
linkedColumns: { code: 'itemCode', name: 'itemName', id: 'itemId' },
onPickerOpen: ({ text, row }) => openStockSearch(text), // Promise<LookupItem | null>
}
Resolve with the chosen item and it is written exactly like a pick from the
list — code, name and id in one step. Resolve with null to keep the value;
the box gets focus back. While your dialog is open, focus leaving the grid for
it neither commits the cell nor sends the row (commitOn: 'row').
listResizable: true puts a grip on the open list's corner: drag it to make
the list wider and taller. The column's next list opens at that size until the
page reloads.
listColumns shows the list as a table with a header row — one column per
item field, value, label or any extra field your items carry:
listColumns: [
{ key: 'value', header: 'Code', width: 80 },
{ key: 'label', header: 'Name' },
{ key: 'unit', header: 'Unit', width: 56, align: 'end' },
],
dropButton: true, // a ▾ at the box's end; F4 and Alt+↓ open the list too
Several items in one cell
multiple: true turns a lookup into a set of check boxes — permission flags,
the days a route runs. The cell holds an array of item values (or, with
multiple: { bits: true }, a number whose bits are the items) and shows each
picked item's short joined with ;:
lookup: {
items: [
{ value: 1, label: 'Add', short: 'A' },
{ value: 2, label: 'Edit', short: 'E' },
{ value: 4, label: 'Cancel', short: 'C', disabled: 'Not your permission' },
],
multiple: { bits: true }, // 5 shows "A;C"
}
The editor is the list itself: Space or a click ticks, Enter keeps the set and
Esc drops the change. An item with disabled cannot change; a string there is
shown beside it as the reason.
items can be a function of the row, so each row offers its own flags (and
its own disabled reasons); the cell, the editor, copy and export all read
that row's list. Ticking an item changes only that item's bit: a bit no item
names is left as it is. A bit set may be a number, a bigint or a decimal
string — read as a signed 64-bit integer, where -1 is every bit — and is
written back in the type it came in. multiple.emptyText is what an empty
cell says ("None").
The same drop-down in a form
LookupBox is the cell's lookup editor as a form field, so the header of a
document and its lines use one control — the same list, matching and keys:
import { LookupBox } from '@kanunilabs/datagrid-react-enterprise';
<LookupBox
items={customers}
value={customerCode}
onChange={(code, item) => setCustomer(code, item)}
ariaLabel="Customer"
linked
matchMode={{ code: 'startsWith', name: 'contains' }}
autoCompleteSingle={false}
listColumns={[{ key: 'value', header: 'Code', width: 80 }, { key: 'label', header: 'Name' }]}
onPickerOpen={(text) => openCustomerSearch(text)}
/>
▾, F4 or Alt+↓ show the whole list without typing — focusing the field does
not (openOnFocus turns that on). An item reached with the arrow keys is what
Enter, Tab and leaving write; Esc closes the list and drops what was typed.
Unlike a cell, leaving the field with text that picks nothing drops the text
and keeps the value (onNoMatch: 'revert'), and emptying it clears the value.
openHighlight: 'current' opens the list on the current item — or the first
when the box is empty — so Enter takes what is highlighted; Tab still writes
only an item walked to with the keys. The default 'none' keeps strict data
entry (autoCompleteSingle: false) opening on nothing.
For a code + name list, display picks what the box shows and completes
against — 'code', 'name' or 'both' ("K001 — Kavak") — and an item's
code can differ from its value, which then is the record's identity.
matchMode: { code: 'none', name: 'contains' } makes a name field that does
not find codes. items={null} (or loading) while the list is on its way
keeps what is typed and checks it once the list arrives; error shows a
message under the field. pickerTabStop, buttonOrder, pickerLabel and
dropLabel arrange the "…" and ▾ buttons; id, name, required and
describedBy go on the box itself, so <label htmlFor> works.
For an editor that is entirely yours, renderEditor draws it. For one that
opens a dialog, the context gives you:
suspendBlurCommit(true)before the dialog takes the focus, andfalsewhen it closes. While it is on, leaving the editor is not a commit and the line is not sent. SpreadonBlur={ctx.commitOnBlur}on the editor to commit when the user really leaves.api.setRowValues({ ... })writes several fields of the line in one step and answersfalse(writing nothing) when any of them may not be written.commit({ move })—'down','next','previous'or'none'— to finish like Enter or Tab do.ariaLabel,invalidanderrorIdfor the editor's own input.
Keys pressed inside the dialog — a portal, outside the grid in the page — are not handled by the grid, even though React passes them through its handlers. Escape closes the dialog first and the editor on a second press. Inside the editor, Tab moves between your input and the "…" button, and leaves the cell from the last one.
Row status and row classes
rowStatus marks each line: new, changed, removed, saving, saved and
error, with a coloured edge (--dg-row-status-<status>), an icon with
icons, the reason under the line with messages, and the text of a removed
line struck through with strike. When several apply, error wins, then
saving, removed, new, changed, saved.
rowClassName adds your own class to a line — here line-return on a negative
quantity. It is asked again on every render, so it follows the edits.
Saving
Batch. batchBar: false removes the grid's own Save / Cancel strip; your
form calls api.saveChanges() and api.cancelChanges(). onSave receives
every pending line at once. If it throws, nothing is saved and every change
stays pending; throw new SaveRejected([{ rowKey, columnId, message }]) to
mark the lines the server refused — they read error with your message.
Instant. mode: 'cell' with commitOn: 'row' sends a line once, when the
user leaves it: another line, Tab past its end, Insert, a click outside the
grid. A refused line stays error and is not sent again until it is edited,
retried or saved with saveChanges().
In both, a saved change leaves the undo history, so Ctrl+Z never brings back something the server already has.
Unsaved changes. The changesChanged event fires whenever the pending
changes change, with { dirty, count } — enough for a "you have unsaved
changes" prompt and an enabled Save button. api.hasChanges() and
api.getChanges() answer the same question on demand.
Phones
cardView shows each line as a card below 600 px. onCardPress tells you
which card was tapped (the grid has already focused its line), and
edit: 'popup' opens the line in the grid's edit dialog: in batch its values
stay pending, in instant mode the line is sent when the dialog is saved.
renderCard draws the card's content yourself.
On touch screens the editors use at least a 16 px font and list items are 44 px tall, so iOS does not zoom in and fingers hit the right item.
Plain HTTP
Intranet pages are often served over plain HTTP, where the browser has no
secure context: no crypto.subtle, no crypto.randomUUID(), no async
clipboard. Nothing above depends on them — paste uses the browser's own paste
event there — and the example makes its keys without crypto.