# Keyboard navigation & accessibility

> The grid follows the WAI-ARIA grid pattern with a roving tabindex, a complete keyboard map and correct row and column counts while virtualized.

Birch UI Grid implements the [WAI-ARIA grid pattern](https://www.w3.org/WAI/ARIA/apg/patterns/grid/). Everything a mouse user can do is available from the keyboard, focus is always visible, and screen readers announce the real size of the dataset and the position of the focused cell even though only a fraction of the rows exist in the DOM.

## Structure and roles

| Element | Role and attributes |
| --- | --- |
| Grid viewport | `role="grid"`, or `role="treegrid"` when any row is nested or expandable; `aria-label` from the `ariaLabel` option; `aria-rowcount`; `aria-colcount`; `aria-multiselectable="true"` when `rowSelection` is `'multiple'` or `rangeSelection` is on |
| Header row | `role="row"` with `aria-rowindex="1"` |
| Floating filter row | `role="row"` with `aria-rowindex="2"`, each cell with the column's `aria-colindex` and each control labelled "Filter &lt;column&gt;" |
| Header cell | `role="columnheader"`, `aria-colindex`, named by its label through `aria-labelledby`, and `aria-sort` (`ascending`, `descending` or `none`) on sortable columns. With a multi-column sort only the primary column carries `aria-sort`; the order of the others is shown visually |
| Body row | `role="row"`, `aria-rowindex`, `aria-selected` when selection is enabled, `aria-level` in a treegrid, `aria-expanded` on expandable rows |
| Body cell | `role="gridcell"` and `aria-colindex`, or `role="rowheader"` in a column with `rowHeader: true` |
| Full-width row content | `role="gridcell"` with `aria-colspan` covering every column |
| Column menu button | `aria-haspopup="menu"`, `aria-expanded`, labelled "&lt;column&gt; column menu" |
| Pager | A `nav` landmark labelled "Pagination", with a polite live region for the page label |

### Counts under virtualization

Only the visible window of rows and columns is rendered, so the DOM alone would tell assistive technology that the grid has 30 rows. The grid sets `aria-rowcount` to the number of display rows plus the header rows (one, or two with floating filters), and gives every rendered row its true `aria-rowindex`. With pagination, counts and indexes cover the whole result, not only the current page. Columns get `aria-colcount` and `aria-colindex` the same way. A screen reader therefore announces "row 48,213 of 1,000,001" while users move through a large grid.

### Announcements

The grid owns a visually hidden polite live region. Sort changes are announced there, for example "Sorted by Revenue, descending" or "Sort cleared for Revenue", so users who sort from the keyboard hear the result without moving focus.

### Name the grid

Give every grid an accessible name that describes its content:

```ts title="accessible-grid.ts"
import { createGrid, type ColumnDef } from '@birchui/core';

createGrid<Order>(document.querySelector('#orders')!, {
  columns,
  rows: orders,
  ariaLabel: 'Open sales orders, EMEA',
  emptyMessage: 'No open orders in EMEA',
});
```

## Focus model

The grid uses a roving tabindex: exactly one cell, header cell or the viewport itself is in the page's tab order at any time. <kbd>Tab</kbd> moves focus into the grid at that cell, and the next <kbd>Tab</kbd> leaves the grid. Inside the grid, arrow keys move between cells, and <kbd>Arrow Up</kbd> from the first row moves into the header.

When data changes, focus stays at the same row index and column. If the column disappears, focus moves to the first column; if the row index no longer exists, focus moves to the last row.

```ts
grid.focusCell(0, 'customer');

const cell = grid.getFocusedCell();

grid.on('focusChanged', ({ cell }) => {
  if (cell) statusLine.textContent = `${cell.colId}, row ${cell.rowIndex + 1}`;
});
```

`focusCell()` scrolls the cell into view and moves DOM focus to it. A `rowIndex` of `-1` refers to the header row.

**`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface GridApi<TRow = RowData> extends Widget<GridOptions<TRow>, GridEvents<TRow>>, GridFeatureApi<TRow>
```

| Property | Type | Description |
| --- | --- | --- |
| `scrollToRow` | `(rowIndex: number, align?: 'auto' \| 'start' \| 'center' \| 'end') => void` |  |
| `scrollToColumn` | `(colId: string) => void` |  |
| `focusCell` | `(rowIndex: number, colId: string) => void` |  |
| `getFocusedCell` | `() => CellPosition \| null` |  |

## Keyboard map

### Moving around

| Key | Action |
| --- | --- |
| <kbd>Arrow keys</kbd> | Move one cell. <kbd>Arrow Up</kbd> from the first row moves to the header. |
| <kbd>Home</kbd> / <kbd>End</kbd> | First or last column of the current row |
| <kbd>Ctrl</kbd>+<kbd>Home</kbd> / <kbd>Ctrl</kbd>+<kbd>End</kbd> | First column of the first row, or last column of the last row |
| <kbd>Page Up</kbd> / <kbd>Page Down</kbd> | Up or down by one screen of rows |
| <kbd>Tab</kbd> / <kbd>Shift</kbd>+<kbd>Tab</kbd> | Leave the grid (when not editing) |

On macOS, <kbd>Cmd</kbd> works wherever <kbd>Ctrl</kbd> is listed.

### Headers and filters

| Key | Action |
| --- | --- |
| <kbd>Enter</kbd> or <kbd>Space</kbd> on a header | Sort by that column |
| <kbd>Shift</kbd>+<kbd>Enter</kbd> or <kbd>Shift</kbd>+<kbd>Space</kbd> on a header | Add the column to a multi-column sort |
| <kbd>Alt</kbd>+<kbd>Arrow Down</kbd> or the context menu key on a header | Open the column menu |
| <kbd>Arrow Down</kbd> on a header | Move to the column's floating filter when the filter row is shown, otherwise to the first row |
| <kbd>Arrow Down</kbd> / <kbd>Arrow Up</kbd> in a floating filter | Move to the first row, or back to the header |

The column menu also holds the keyboard and single-pointer alternatives to dragging a header: **Move left**, **Move
right**, **Move to first** and **Move to last** (within the column's pinned section and column group, skipping columns
with `reorderable: false`), and **Autosize this column**, **Increase width** and **Decrease width** (20 px steps,
within `minWidth` and `maxWidth`). They call `moveColumn` and `setColumnWidth`, so the usual `columnMoved` and
`columnResized` events fire.

### Selection

| Key | Action |
| --- | --- |
| <kbd>Space</kbd> | Toggle selection of the focused row, when `rowSelection` is set |
| <kbd>Shift</kbd>+<kbd>Space</kbd> | Select the range from the last toggled row to the focused row (`'multiple'`) |
| <kbd>Ctrl</kbd>+<kbd>A</kbd> | Select all rows (`'multiple'`) |

### Editing

| Key | Action |
| --- | --- |
| <kbd>Enter</kbd> or <kbd>F2</kbd> | Start editing the focused cell |
| Printable character | Start editing, replacing the value with that character |
| <kbd>Space</kbd> on a checkbox cell | Start editing and toggle the checkbox, when row selection is off |
| <kbd>Delete</kbd> or <kbd>Backspace</kbd> | Clear an editable cell (an empty string for text columns, `null` otherwise) |
| <kbd>Enter</kbd> while editing | Commit |
| <kbd>Tab</kbd> / <kbd>Shift</kbd>+<kbd>Tab</kbd> while editing | Commit and start editing the next or previous editable cell, wrapping to the next or previous row |
| <kbd>Escape</kbd> while editing | Cancel |

### Expandable rows

| Key | Action |
| --- | --- |
| <kbd>Enter</kbd> on a non-editable cell of an expandable row | Toggle expansion |
| <kbd>Space</kbd> on an expandable row, when row selection is off | Toggle expansion |

Expandable rows come from Grid Pro features such as [row grouping](https://docs.birchui.com/grid-pro/row-grouping.md), [tree data](https://docs.birchui.com/grid-pro/tree-data.md) and [master/detail](https://docs.birchui.com/grid-pro/master-detail.md). Grid Pro modules add their own keys through key handlers, for example for [range selection](https://docs.birchui.com/grid-pro/range-selection.md) and [clipboard](https://docs.birchui.com/grid-pro/clipboard.md) copy and paste.

## Adding your own keys

There are two ways to add keys, and both run before the built-in key map whenever no editor is open.

**`cellKeyDown`** fires for every key pressed on a focused body cell. Call `event.preventDefault()` to stop the grid from handling the key itself. This suits app-level shortcuts and blocking keys you do not want:

```ts title="ledger-keys.ts"
grid.on('cellKeyDown', ({ event, row, colId }) => {
  const key = event as KeyboardEvent;

  if (key.key === 'Delete' && row) {
    key.preventDefault();
    if (confirm(`Archive order ${row.id}?`)) grid.applyTransaction({ remove: [row] });
    return;
  }

  if (colId === 'amount' && key.key.length === 1) {
    key.preventDefault();
  }
});
```

The second branch blocks typing into the locked `amount` column, so a stray keystroke never opens its editor, while arrow keys keep navigating.

**Module key handlers** see keys in header cells too and receive the focused position. Register them with `addKeyHandler` in a [module](https://docs.birchui.com/grid/modules.md#key-handlers) and return `true` when you handle the key; the grid then calls `preventDefault()` and skips its own handling.

```ts title="order-shortcuts.ts"
import { createGrid, type GridModule } from '@birchui/core';

const OpenOrderShortcut: GridModule = {
  name: 'openOrderShortcut',
  install(grid) {
    return grid.addKeyHandler((event, focused) => {
      if (event.key !== 'o' || !focused || focused.rowIndex < 0) return false;
      const order = grid.api.getDisplayRow(focused.rowIndex)?.data;
      if (order) window.location.assign(`/orders/${order.id}`);
      return true;
    });
  },
};

createGrid<Order>(container, { columns, rows: orders, modules: [OpenOrderShortcut] });
```

`cellKeyDown` listeners run before module key handlers, so a key that a listener cancels never reaches them. Modules can also listen to the internal `keyDown` event, which runs before both. See [Order of key handling](https://docs.birchui.com/grid/modules.md#order-of-key-handling).

## Row headers

Mark the column that names each row with `rowHeader: true` so screen readers announce it as the row header when users
move across the other cells:

```ts title="row-header.ts"
const columns: ColumnDef<Order>[] = [
  { field: 'customer', header: 'Customer', rowHeader: true },
  { field: 'total', header: 'Total', type: 'number' },
];
```

Grid Pro sets it on the group and pivot label column.

## Treegrid for grouped and tree data

When any display row is nested or expandable, the viewport switches to `role="treegrid"`. Each row then carries `aria-level` (1 for top-level rows), and expandable rows carry `aria-expanded`. Screen readers announce the hierarchy as users move, for example "EMEA, expanded, level 1".

## Visual accessibility

- **Focus** is drawn as a 2-pixel inset ring in `--lq-focus-ring` on the focused cell, header or filter control, and as an outline on menu items. If you change the color, keep a 3:1 contrast ratio with the cell background.
- **Forced colors**: in Windows High Contrast and other `forced-colors: active` modes, focus is drawn as a real outline in the system `Highlight` colour and selected rows use `Highlight` and `HighlightText`.
- **Selection**: with `rowSelection` but no checkbox column, selected rows use `--lq-selection-strong-bg` and `--lq-selection-strong-fg`, so selection does not rely on a faint tint. With `checkboxSelection` the lighter `--lq-selection-bg` tint is used and the checkbox shows the state.
- **Inputs**: filter inputs use `--lq-input-border` for their outline and `--lq-placeholder-fg` for hint text, both chosen to pass WCAG contrast in the bundled themes. Set them too if you override the theme.
- **Themes**: the bundled light and dark themes meet WCAG 2.2 AA contrast for text, and their accent colors meet the 3:1 minimum for non-text UI such as sort indicators and the focus ring. See the [contrast table](https://docs.birchui.com/grid/theming.md#contrast). `theme: 'auto'` follows `prefers-color-scheme`.
- **Motion**: the grid respects `prefers-reduced-motion` and does not animate scrolling or data changes.
- **Zoom**: text sizes come from `--lq-font-size`, so browser zoom and your own font-size overrides scale the grid.

## Checklist for your grid

- Set `ariaLabel` to a name that describes the data.
- Give icon-only cells and buttons in renderers an `aria-label`.
- Keep `emptyMessage` meaningful; the default is "No rows to show".
- Do not put interactive controls in cells without handling their keys: stop propagation of the keys your control uses, like the [custom editors](https://docs.birchui.com/grid/editing.md#custom-editors) example does.
- Test with a screen reader in focus mode; the grid is a composite widget and expects focus mode for navigation.
