Agent playbook
For an AI coding agent writing @apsw/gridwright code in someone's React application. Rules and canonical snippets, no narrative. The reasoning behind every rule is in the React playbook; follow the rule, read the reasoning only when a request seems to need an exception.
How well this file works is measured in the agent benchmark.
This file is about using the package in an application. It is not the repository's own operating cycle — that is
workflow.ai.ymlandAGENTS.md, and it applies to changing this package, not to consuming it.
Imports#
import { Gridwright, /* add-ons, hooks, parts */ } from '@apsw/gridwright/react'; // build with this
import { createRestDataSource, /* engine, sources */ } from '@apsw/gridwright'; // headless engine
import { pl } from '@apsw/gridwright/locales'; // translations
import '@apsw/gridwright/styles.css'; // once, at the entryPeer dependency: React 18 or 19. No runtime dependencies.
Always#
- Give every grid an
aria-labelor acaption. - Build a data source in
useMemo(deps = what it reads) or at module scope. Never inline in JSX. - Declare
capabilitiestruthfully. Unstated facets default to all-true for remote sources. - Use
formatValuewhen the cell's answer is text;cellonly for real React. - Pass
signalfrom the fetcher intofetch. - Pass
getRowIdwhen rows have noidproperty. - Put a feature in
addons={[...]}; put per-column configuration on the column. - Keep
virtualRows({ rowHeight })equal to--gw-row-height. - Let
inlineEditing'scommitthrow to reject an edit. Do not also mutate local state.
Never#
- Never compute or fake a total the source did not supply. No
totalRowsmeans the grid says "of many", and that is correct. - Never claim a capability the endpoint does not implement.
- Never list
rowDetail()withvirtualRows()— it throws by design. - Never give an add-on's extra
<tr>role="row"; userole="presentation"with a labelledrole="region"inside. - Never assert on class names or DOM structure in tests. Query by role and accessible name.
- Never add a runtime dependency to make a recipe work.
- Never render a visible string as a JSX literal inside an add-on; use
messages/labels. - Never reach into the grid's DOM to attach behaviour. Use the add-on contract.
- Never rebuild the column picker to change one rule.
columnLayout({ canChange })refuses a change;picker: falseis for replacing the control, not the policy. - Never render a control that a guard will refuse as though it were available. Ask
useColumnLayout().allows(change)and setaria-disabled— notdisabled, which drops the item out of the menu's arrow-key order. - Never count
canChange'slayout.pinned/layout.hiddento decide a rule — those are the reader's overrides, not the effective state. Use the third argument,resolved.
Decision rules#
rows come from an array -> data={rows}
rows come from REST -> createRestDataSource({ url })
rows come from GraphQL / SDK / tRPC -> createRemoteDataSource({ fetcher })
server accepts only page+pageSize -> capabilities: { paginate: true, sort: false, filter: false, search: false }
(sort/filter/search then cover the loaded page only; the grid warns once per
facet, silence with warnOnPageScopedQuery={false} when that is intended)
> ~10k rows rendered at once -> virtualRows()
result set too large to hold in memory -> createWindowedDataSource
both -> createWindowedDataSource + virtualRows()
a panel under a row -> rowDetail()
nested rows of the same shape -> treeData()
keyboard users must cross many columns -> cellNavigation()
Ctrl+C / Cmd+C should copy rows or a cell -> cellNavigation() (copy is on by default)
a feature that does not exist -> a GridAddon of your own
a row transformation for local and remote -> an engine plugin (registerStage)
one column must not be resized/hidden/moved-> column layout: { resizable, hideable, movable }
one column must not be pinned -> columnLayout({ canChange }) — no column option for it
a rule about more than one column -> columnLayout({ canChange })Common requests, as people phrase them#
Each line is a request, then the whole answer. Reach for these before reading any other file.
"A search box" — add search(). It searches every row, not just the page shown. To search only some columns, set searchable: false on the others. Do not write your own <input>.
const columns: GridwrightColumn<Person>[] = [
{ id: 'name', header: 'Name' },
{ id: 'salary', header: 'Salary', searchable: false },
];
<Gridwright<Person> columns={columns} data={people} pageSize={25} aria-label="People" addons={[search()]} />;"100 000 rows" / "must stay fast" — virtualRows({ rowHeight, height }) over the plain data array. It replaces the page controls with the scrollbar, so build none (under it pageSize only sizes the fetch window). The rows are already in memory, so no data source is needed.
<Gridwright<Person> columns={columns} data={people} aria-label="People" addons={[virtualRows({ rowHeight: 40, height: 600 })]} />;"The server does the paging, sorting and searching" — createRestDataSource already speaks the wire format in Grid over REST below: page is one-based, sort=column:asc, search, and it reads { data, total }. State the facets the endpoint really handles. Do not sort or page on the client, and do not subtract one from page.
createRestDataSource<Person>({ url: '/api/people', capabilities: { paginate: true, sort: true, search: true, filter: false } })"The endpoint cannot sort / search / filter, or rejects other parameters" — use createRemoteDataSource with only paginate: true, and build the request yourself so that no other parameter is sent (Grid over anything async below). createRestDataSource would send sort and search and the endpoint would answer 400.
"It returns a bare array, no total" — return { rows } and no totalRows. The grid then says "of many", and treats a page shorter than pageSize as the last one: it disables Next by itself. Add no logic for that and show no count.
"Rows are identified by uuid / a key other than id" — pass getRowId={(row) => row.uuid} on the grid, before using selection, row detail or any per-row state.
Canonical snippets#
Grid over an array#
const columns: GridwrightColumn<Person>[] = [
{ id: 'name', header: 'Name' },
{ id: 'salary', header: 'Salary', align: 'end', formatValue: (v) => money.format(Number(v)) },
];
<Gridwright<Person> columns={columns} data={people} pageSize={25} aria-label="People" />;Grid over REST#
const source = useMemo(() => createRestDataSource<Person>({ url: '/api/people' }), []);
<Gridwright<Person> columns={columns} dataSource={source} pageSize={25} aria-label="People" addons={[search()]} />;Wire format sent: page (one-based), pageSize, sort=col:asc,other:desc, search, filters (JSON array of { columnId, operator, value }). Accepted back: an array, { data, total }, { items, count }, meta.total, or an X-Total-Count header. Override with buildParams / parseResponse.
Grid over anything async#
const source = useMemo(
() =>
createRemoteDataSource<Person>({
capabilities: { paginate: true, sort: false, filter: false, search: false },
fetcher: async ({ query, signal }) => {
const { pageIndex, pageSize } = query.pagination;
const body = await client.people.list({ page: pageIndex + 1, size: pageSize }, { signal });
return body.total === undefined ? { rows: body.rows } : { rows: body.rows, totalRows: body.total };
},
}),
[client],
);Add-ons#
addons={[search(), columnFilters(), exportMenu({ filename: 'people' }), rowActions({ items })]}Core four (sorting, selection, pagination, staleNotice) are on by default. Configure: coreAddons={coreAddons<Person>({ selection: { checkboxes: false }, pagination: { pageSizeOptions: [10, 50] } })}. Remove all: coreAddons={false}.
Changing which add-on names are listed remounts the grid. This is by design; it resets the page.
Selection#
<Gridwright<Person>
selectionMode="multiple"
onSelectionChange={(ids, rows) => setSelected(rows)}
getRowId={(row) => row.uuid}
/* ... */
/>Selection is engine state. selection({ checkboxes: false }) removes the column, not the state. Then only selection({ selectOnRowClick: true }), and Space on a focused cell under cellNavigation(), select a row; with neither, drive it yourself via api.toggleRowSelection.
Editable cells#
// column
{ id: 'salary', header: 'Salary', edit: { inputType: 'number', editable: (row) => row.canEditPay } }
// add-on
inlineEditing({
commit: async (rowId, columnId, value) => {
const response = await fetch(`/api/people/${rowId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ [columnId]: value }),
});
if (!response.ok) throw new Error(await response.text()); // throwing reverts the cell
source.invalidate();
},
})edit fields: editable, inputType (text | number | date | checkbox | select), choices, parse, editor.
Expandable rows / master–detail#
rowDetail<Order>({
hasDetail: (row) => row.data.lineCount > 0,
render: ({ data, close }) => <OrderLines orderId={data.id} />,
})render runs only while open; a collapsed panel is unmounted, so the panel component is the lazy load. Options: single, toggle: 'start' | 'end' | 'none', canToggle, persistAcrossPages, initialExpanded + onExpandedChange, rowLabel, controllerRef. useRowDetail() gives the controller.
Keyboard cell navigation#
addons={[cellNavigation()]} // one Tab stop, then the arrowsArrows move cell to cell, Home/End along the row, Ctrl+them to the first/last cell, PageUp/PageDown by a page. Over treeData(), right and left expand and collapse a node.
- No key fetches a page.
Ctrl+Endstops at the last loaded row, because a source with no total has no known last row. - Arrow keys inside an
<input>stay there, soinlineEditing()keeps its caret. - Extra columns (the
selection()checkbox) are reachable;includeExtraColumns: falseexcludes them. headerRow: trueputs the header row in the cursor:ArrowUpreaches it,Enter/Spacesorts,Shift+Enteradds to the sort, and the sort buttons stop being Tab stops.useCellNavigation()gives your own control the same cursor:activeCell,columnIds,isActive,focusCell.- Nothing is announced on a move — the browser already announces the focused cell.
- Copy is part of it. The platform's shortcut (
Ctrl+C,Cmd+C,Ctrl+Insert) copies the selected loaded rows with a header row, else the cursor's cell, as TSV plus an HTML table — resolved like an export, formula-guarded, escaped.copy: falseturns it off. - Do not add a clipboard handler of your own with
navigator.clipboardorexecCommand('copy')next to it. The add-on writes in the browser'scopyevent, which needs no permission and works on plain HTTP and in iframes; a second writer races it. Column text for a copy comes fromexportValue/formatValue, so change it there, not in a clipboard hook. - Never platform-sniff for the modifier (
navigator.platform,userAgent) — the add-on already acceptsCtrlandCmdand reads the letter from the keyboard layout.
Column layout, and locking it#
// Per column, read on every render — so `hideable: user.isAdmin` works.
{ id: 'name', header: 'Name', layout: { resizable: false, hideable: false, movable: false, pinned: 'left', maxWidth: 400 } }
// Cross-column rules, and the pin lock no column option has:
columnLayout<Person>({
// `resolved`, not `layout`: `layout.pinned` holds the reader's overrides only, so a column
// pinned by its own definition is not in it and the count comes out short.
canChange: (change, layout, resolved) =>
change.type !== 'pin' ||
change.side === null ||
resolved.order.filter((id) => resolved.pinOf(id) !== null).length < 3,
});canChange is asked before every committed change — width, pin, visibility, move, showAll, reset — and false refuses it. It narrows and never widens: a movable: false column stays locked whatever the guard returns. It governs the controller too, so your own button cannot step around your own rule.
Never count layout.pinned or layout.hidden to decide a rule. That is the saved state — the reader's overrides — and a column pinned or hidden by its own definition is absent from it. The third argument, resolved, has order, pinOf, isHidden, widthOf and indexOf, and answers what is actually painted.
Ask allows in a control of your own, so it disables itself exactly as the built-in ones do:
const layout = useColumnLayout();
const refused = !layout.allows({ type: 'pin', columnId, side: 'left' });
<button aria-disabled={refused || undefined} onClick={() => !refused && layout.setPinned(columnId, 'left')}>Pin</button>;A width and a move are refused only on commit — the gesture decides the number, so nothing can be disabled in advance. Nothing is announced when a change is refused, and there is no reason string: say it where your rule is.
Huge data sets#
const source = useMemo(
() =>
createWindowedDataSource<Person>({
blockSize: 200,
maxBlocks: 12,
fetchRange: async ({ offset, limit, query, signal }) => {
const body = await api.people({ offset, limit }, { signal });
return { rows: body.rows, totalRows: body.total }; // totalRows is REQUIRED here
},
}),
[api],
);
<Gridwright<Person> columns={columns} dataSource={source} pageSize={100} aria-label="People" addons={[virtualRows({ rowHeight: 40, height: 600 })]} />;Persisting state#
initialQuery={saved} // read once, at engine creation
onQueryChange={(q) => save(q)} // sort, filters, search, page
columnLayout({ initial, onChange }) // widths, pinning, visibility, order
rowDetail({ initialExpanded, onExpandedChange }) // open panelsonChange / onExpandedChange never fire on mount, so they cannot overwrite a saved value on the first paint.
An add-on of your own#
const highlight = (): GridAddon<Row> => ({
name: 'acme:highlight', // namespaced; also the messages namespace
setup: function useHighlight() { // may call hooks; name it use* for the lint rule
return {
cellAttributes: (row, column) => (column.id === 'due' && row.data.overdue ? { className: 'is-overdue' } : {}),
toolbar: () => <MyButton />, // slot functions must NOT call hooks
messages: { en: { label: 'Overdue' } },
};
},
});Contributable attributes are an allowlist: on*, aria-*, data-*, className, style, role, id, title, tabIndex, hidden, dir, lang, draggable, scope, colSpan, rowSpan, abbr, headers. No children, no markup, no URL attributes.
Slots: configure, plugins, columnSignature, provide, suppresses, navigation, toolbar, toolbarStatus, aboveTable, belowTable, overlay, rootAttributes, tableAttributes, tableWrapper, tableKeyDown, tableFooter, headerLabel, headerBefore, headerAfter, headerAttributes, columns, extraCellAttributes, extraHeaderAttributes, body, rowAttributes, renderRow, rowAfter, cellAttributes, status, announce, messages.
A row after a row spans the table with columnCountOf(grid) and is presentational:
rowAfter: (row, grid) =>
open.has(row.id) ? (
<tr role="presentation">
<td role="presentation" colSpan={columnCountOf(grid)}>
<div role="region" aria-label={`Details for ${row.data.name}`}>{/* ... */}</div>
</td>
</tr>
) : undefined,Tests#
screen.getAllByRole('row') // [0] is the header
within(row).getAllByRole('cell')
screen.getByRole('button', { name: /Salary/ }) // the sort control
screen.getByRole('columnheader', { name: /Salary/ }) // carries aria-sort
screen.getByRole('status') // the live region
screen.getAllByRole('checkbox', { name: 'Select row' })
await waitFor(() => expect(screen.getAllByRole('row')).toHaveLength(1 + 25)); // no arbitrary timersTheming#
Override custom properties on any ancestor; do not fork the stylesheet.
--gw-font-size, --gw-line-height, --gw-row-height, --gw-cell-padding-x, --gw-cell-padding-y, --gw-radius, --gw-gap, --gw-surface, --gw-surface-muted, --gw-surface-hover, --gw-surface-selected, --gw-text, --gw-text-muted, --gw-border, --gw-border-strong, --gw-accent, --gw-accent-contrast, --gw-danger, --gw-focus-ring.
Per-part classes: classNames={{ root, toolbar, search, tableWrapper, table, thead, headerRow, headerCell, tbody, row, rowSelected, cell, pagination, status, stale, filterTrigger, filterDialog }}.
Translation#
<Gridwright locale={pl} /* or */ translate={(key, values) => t(key, values)} /* or */ messages={{ 'status.empty': '…' }} />Packs: en, de, es, fr, pl. A translate that returns the key falls back to the catalog. Column header strings are yours — pass them already translated.
Failure modes to check before reporting done#
| Check | Why |
|---|---|
Is every data source inside useMemo or at module scope? | An inline one refetches forever |
Do capabilities match what the endpoint actually implements? | Silent no-op sorting and filtering |
Does every grid have aria-label or caption? | A screen reader announces only "table" |
Is @apsw/gridwright/styles.css imported once? | Otherwise unstyled |
Do rows have stable ids (or getRowId)? | Selection and panels are keyed on them |
Does virtualRows({ rowHeight }) match --gw-row-height? | Rows drift from the scrollbar |
| Is any total being computed client-side? | Never do this |
| Are tests querying by role rather than class? | Class names are not the contract |
Does every control a canChange guard can refuse ask allows first? | Otherwise it looks live and does nothing |
Does a canChange rule read resolved rather than counting layout.pinned? | A column pinned by its own definition is not in the saved state |
Escalate to the user, do not guess#
- The endpoint's paging contract is unknown (zero- vs one-based, parameter names).
- The endpoint cannot return a total and the user asked for an exact page count. Say the grid will show "of many" and why.
- A requirement needs a feature the package refuses on purpose (a total from one page, expandable rows under windowing, a runtime dependency). Name the refusal and offer the nearest thing.
- A required seam does not exist in the add-on contract. That is a gap in the package, not a reason to reach into the DOM.
Reference#
| Need | Page |
|---|---|
| Task-indexed recipes with reasoning | React playbook |
| Every prop, option, field, default | API reference |
| Column widths, pinning, locks and guards | Column layout |
| Tutorial, six steps | Getting started |
| Add-on contract in full | Add-ons |
| Capabilities, totals, aborts, retries | Data sources |
| What is deliberately closed | Extensibility |
| Keyboard and screen-reader contract | Accessibility |
| Runnable, step by step | examples/react-quickstart/ |