# Modules

> How the modules option works, and how to write your own module with row and column stages, cell decorators, key handlers, menu items, slots and shared state.

Every feature beyond the core grid is a module: a plain object with a `name` and an `install()` function. Grid Pro's grouping, pivoting, clipboard and Excel export are modules, and you can write your own with exactly the same hooks. Modules are how you add behaviour to the grid without forking it.

```ts
import { createGrid } from '@birchui/core';
import { RowGroupingModule, AggregationModule } from '@birchui/grid-pro';

createGrid(container, {
  columns,
  rows: orders,
  modules: [RowGroupingModule, AggregationModule, OverdueInvoicesModule],
});
```

## How modules are installed

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

```ts
interface GridModule
```

| Property | Type | Description |
| --- | --- | --- |
| `readonly name` | `string` |  |
| `install` | `(grid: GridInternals<any>) => void \| (() => void)` |  |

- Modules in `modules` are installed in array order when the grid is created, before the first render, so their stages and listeners see the initial data.
- `install(grid)` receives the grid's internals (below) and may return a cleanup function.
- Names are unique per grid. A second module with a name that is already installed is ignored.
- If `install()` throws, the grid reports it with `console.error` and keeps working without that module.
- `update({ modules })` runs the cleanup of every module that is no longer listed, then installs the new ones. Modules that stay listed are not reinstalled.
- `destroy()` runs every module's cleanup before removing the grid.
- `api.hasModule(name)` tells you whether a module is installed, which is useful for feature detection in shared components.

When an option needs a Grid Pro module that is not installed, for example `groupBy` without `RowGroupingModule`, the grid ignores the option and prints one `console.warn` per feature naming the module to add.

## Grid internals

`install()` receives `GridInternals`, the API that modules build on. It includes the public `api`, the root and viewport elements, and the hooks described in the sections below.

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

```ts
interface GridInternals<TRow = RowData>
```

| Property | Type | Description |
| --- | --- | --- |
| `readonly api` | `GridApi<TRow>` |  |
| `readonly root` | `HTMLElement` |  |
| `readonly viewport` | `HTMLElement` |  |
| `options` | `() => Readonly<GridOptions<TRow>>` |  |
| `addRowStage` | `(stage: RowStage<TRow>) => () => void` |  |
| `addColumnStage` | `(stage: ColumnStage<TRow>) => () => void` |  |
| `addFullWidthRenderer` | `(kind: DisplayRowKind, renderer: FullWidthRenderer<TRow>) => () => void` |  |
| `addCellDecorator` | `(decorator: CellDecorator<TRow>) => () => void` |  |
| `addHeaderDecorator` | `(decorator: HeaderDecorator<TRow>) => () => void` |  |
| `addKeyHandler` | `(handler: (event: KeyboardEvent, focused: CellPosition \| null) => boolean) => () => void` |  |
| `addColumnMenuItems` | `(provider: (column: ResolvedColumn<TRow>) => MenuItem[]) => () => void` |  |
| `on` | `<K extends keyof InternalEvents<TRow>>(event: K, listener: (payload: InternalEvents<TRow>[K]) => void) => () => void` |  |
| `slot` | `(name: Slot) => HTMLElement` |  |
| `getCellElement` | `(rowIndex: number, colId: string) => HTMLElement \| null` |  |
| `cellFromPoint` | `(clientX: number, clientY: number) => CellPosition \| null` |  |
| `getRenderedRange` | `() => { firstRow: number; lastRow: number }` |  |
| `computeRows` | `(options?: ComputeRowsOptions) => DisplayRow<TRow>[]` |  |
| `refresh` | `() => void` |  |
| `render` | `() => void` |  |
| `emit` | `<K extends keyof GridEvents<TRow>>(event: K, payload: GridEvents<TRow>[K]) => void` |  |
| `state` | `<T>(key: string, init: () => T) => T` |  |
| `expose` | `(name: string, fn: (...args: any[]) => unknown) => () => void` |  |
| `getColumnElement` | `(colId: string) => HTMLElement \| null` |  |
| `addContextMenuItems` | `(provider: (ctx: CellContext<TRow>) => MenuItem[]) => () => void` |  |
| `addStateProvider` | `(name: string, provider: GridStateProvider) => () => void` |  |

## Row stages

The row pipeline turns source rows into display rows. It is a list of stages sorted by `order`; each stage receives the output of the previous one.

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

```ts
interface RowStage<TRow = RowData>
```

| Property | Type | Description |
| --- | --- | --- |
| `name` | `string` |  |
| `order` | `number` |  |
| `run` | `(rows: DisplayRow<TRow>[], ctx: PipelineContext<TRow>) => DisplayRow<TRow>[]` |  |

| Order | Stage |
| --- | --- |
| 100 | Filter (`FILTER_STAGE_ORDER`) |
| 200 | Sort (`SORT_STAGE_ORDER`) |
| 250 | Aggregation capture (Grid Pro) |
| 300 | Row grouping, tree data and pivoting (Grid Pro) |
| 310 | Pivot result shaping (Grid Pro) |
| 390 | Aggregation totals (Grid Pro) |
| 800 | Master/detail rows (Grid Pro) |
| 10000 | Status bar and Excel snapshots (Grid Pro) |

Pagination is applied after every stage has run, so all stages see every row; `PAGINATION_STAGE_ORDER` (900) is exported for reference. `FILTER_STAGE_ORDER`, `SORT_STAGE_ORDER` and `PAGINATION_STAGE_ORDER` are exported from `@birchui/core`, so position your stage relative to them instead of hard-coding numbers.

A stage returns a new array or the same array. It must not drop the `DisplayRow` objects it is given in favour of copies of data rows; use `ctx.makeDataRow(row, sourceIndex)` when you need a display row for a source row.

```ts title="urgent-first.ts"
import { SORT_STAGE_ORDER, type GridModule } from '@birchui/core';

export const UrgentFirstModule: GridModule = {
  name: 'urgentFirst',
  install(grid) {
    return grid.addRowStage({
      name: 'urgent-first',
      order: SORT_STAGE_ORDER + 20,
      run(rows) {
        const urgent = rows.filter((row) => row.data?.priority === 'Urgent');
        if (urgent.length === 0) return rows;
        return [...urgent, ...rows.filter((row) => row.data?.priority !== 'Urgent')];
      },
    });
  },
};
```

Because this stage runs after sorting, urgent tickets float to the top while keeping the user's sort among themselves. If a stage throws, the grid reports it with `console.error` and continues with the rows it had before that stage.

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

```ts
interface PipelineContext<TRow = RowData>
```

| Property | Type | Description |
| --- | --- | --- |
| `api` | `GridApi<TRow>` |  |
| `options` | `Readonly<GridOptions<TRow>>` |  |
| `columns` | `readonly ResolvedColumn<TRow>[]` |  |
| `sort` | `readonly SortItem[]` |  |
| `filterModel` | `Readonly<Record<string, FilterModel>>` |  |
| `quickFilter` | `string` |  |
| `getValue` | `(row: TRow, colId: string) => unknown` |  |
| `compareValues` | `(colId: string, a: unknown, b: unknown, rowA?: TRow, rowB?: TRow) => number` |  |
| `isExpanded` | `(rowId: string, fallback: boolean, options?: ExpansionQuery) => boolean` |  |
| `makeDataRow` | `(row: TRow, sourceIndex: number, depth?: number) => DisplayRow<TRow>` |  |

## Column stages

Column stages transform the column definitions before the grid resolves them, in `order`. Grid Pro uses them to add the group column and the generated pivot columns.

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

```ts
interface ColumnStage<TRow = RowData>
```

| Property | Type | Description |
| --- | --- | --- |
| `name` | `string` |  |
| `order` | `number` |  |
| `run` | `(columns: ColumnDef<TRow>[], ctx: { api: GridApi<TRow>; options: Readonly<GridOptions<TRow>> }) => ColumnDef<TRow>[]` |  |

```ts title="days-overdue-column.ts"
import type { GridModule } from '@birchui/core';

const DAY = 86_400_000;

export const DaysOverdueModule: GridModule = {
  name: 'daysOverdue',
  install(grid) {
    return grid.addColumnStage({
      name: 'days-overdue',
      order: 100,
      run: (columns) => [
        ...columns,
        {
          id: 'daysOverdue',
          header: 'Days overdue',
          type: 'number',
          width: 120,
          valueGetter: (invoice) => (invoice.paid ? null : Math.max(0, Math.floor((Date.now() - Date.parse(invoice.due)) / DAY))),
        },
      ],
    });
  },
};
```

Columns that a stage adds are marked `generated: true`. Generated columns cannot be edited, are skipped by the quick filter, and get no pin or hide entries in the column menu.

## Cell decorators

A decorator runs for every rendered cell after its content and classes are set, every time the cell renders. Use it to add classes, attributes or small adornments. Cell elements are recycled while scrolling and their class list is rebuilt on each render, so toggle classes rather than accumulating state on the element.

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

```ts
interface CellDecorator<TRow = RowData>
(cell: HTMLElement, ctx: CellContext<TRow>): void
```

```ts
const removeDecorator = grid.addCellDecorator((cell, ctx) => {
  if (ctx.column.id === 'amount' && Number(ctx.value) >= 10_000) cell.classList.add('invoice-large');
});
```

## Key handlers

Key handlers run before the grid's built-in key map whenever no editor is open. A handler receives the keyboard event and the focused cell (`rowIndex: -1` for the header row) and returns `true` when it handled the key. The grid then calls `preventDefault()` and skips its own handling, including starting an edit for printable keys. Handlers run in the order they were added; the first one to return `true` wins.

```ts
const removeKeys = grid.addKeyHandler((event, focused) => {
  if (event.key !== 'Delete' || !event.shiftKey || !focused || focused.rowIndex < 0) return false;
  const invoice = grid.api.getDisplayRow(focused.rowIndex)?.data;
  if (invoice) grid.api.applyTransaction({ remove: [invoice] });
  return true;
});
```

### Order of key handling

When a key is pressed in the grid and no editor is open, the grid offers it to four layers in turn. Each layer can stop the ones after it:

| Step | Layer | Sees | Stops later layers by |
| --- | --- | --- | --- |
| 1 | Internal `keyDown` event (`grid.on('keyDown', …)` in a module) | Keys on body cells and headers, with the focused position | `event.preventDefault()` |
| 2 | Public `cellKeyDown` event | Keys on body cells, with the row, column and value | `event.preventDefault()` |
| 3 | Key handlers (`addKeyHandler`) | Keys on body cells and headers, with the focused position | Returning `true` |
| 4 | Built-in key map | Navigation, sorting, selection, editing | |

While an editor is open, none of these run: keys belong to the editor, and the grid only handles <kbd>Tab</kbd> to move to the next editable cell.

Use `keyDown` when a module must see every key first, for example to cancel a key before app code reacts to it; use `addKeyHandler` when the module provides a fallback that app-level `cellKeyDown` listeners should be able to override.

```ts title="read-only-hours.ts"
import type { GridModule } from '@birchui/core';

export const ReadOnlyAfterCloseModule: GridModule = {
  name: 'readOnlyAfterClose',
  install(grid) {
    return grid.on('keyDown', ({ event, focused }) => {
      const closed = new Date().getHours() >= 18;
      if (closed && focused && focused.rowIndex >= 0 && (event.key === 'Delete' || event.key.length === 1)) {
        event.preventDefault();
      }
    });
  },
};
```

## Column menu items

A provider returns extra items for a column's menu, appended after the built-in ones. Return an empty array to add nothing.

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

```ts
interface MenuItem
```

| Property | Type | Description |
| --- | --- | --- |
| `label` | `string` |  |
| `action` | `() => void` |  |
| `checked?` | `boolean` |  |
| `disabled?` | `boolean` |  |
| `separatorBefore?` | `boolean` |  |

```ts
const removeMenu = grid.addColumnMenuItems((column) =>
  column.type === 'number'
    ? [{ label: 'Copy column total', separatorBefore: true, action: () => copyTotal(column.id) }]
    : [],
);
```

## Full-width rows

A display row with `fullWidth: true` is rendered as a single cell that spans the grid. `addFullWidthRenderer(kind, renderer)` registers the renderer for one row kind; the renderer receives the row, an empty container and the API, and may return a cleanup function that runs when the row is recycled. Registering a renderer for a kind replaces the previous one, so avoid kinds that an installed Grid Pro module already renders (`detail` for master/detail).

```ts title="vat-note.ts"
import type { GridModule } from '@birchui/core';

export const VatNoteModule: GridModule = {
  name: 'vatNote',
  install(grid) {
    const offStage = grid.addRowStage({
      name: 'vat-note',
      order: 1_000,
      run: (rows) => [
        ...rows,
        { kind: 'total', id: '__vat-note', data: undefined, depth: 0, sourceIndex: -1, expandable: false, expanded: false, fullWidth: true, height: 40 },
      ],
    });
    const offRenderer = grid.addFullWidthRenderer('total', (row, container) => {
      container.textContent = 'Amounts in EUR, excluding VAT. Payment terms: 30 days net.';
    });
    return () => {
      offStage();
      offRenderer();
    };
  },
};
```

Full-width rows are skipped by CSV export and cannot be selected or edited.

## Slots

`slot(name)` returns a container the grid lays out for you:

| Slot | Position | Notes |
| --- | --- | --- |
| `top` | Above the header | Hidden while empty. Toolbars, group panels. |
| `bottom` | Below the rows | Hidden while empty. The pager lives here; status bars and summaries go here too. |
| `overlay` | Covers the whole grid | `pointer-events: none` except on its children. Drag previews, selection handles, popovers. |

## Shared state and exposing methods

`state(key, init)` returns a value stored per grid, creating it with `init()` the first time. Cooperating modules use it to share state without globals, for example a grouping module and a status bar reading the same group model.

`expose(name, fn)` adds a method to the public API and returns a function that removes it. Grid Pro's `ExcelModule` adds `exportExcel()` this way, which is why such methods are typed as optional and called with optional chaining (`grid.exportExcel?.()`). Names that already exist on the API are refused with a `console.warn`.

```ts
const removeMethod = grid.expose('getOverdueInvoices', () => grid.api.getRows().filter(isOverdue));
```

## Internal events

`on(event, listener)` subscribes to events that only modules need. It returns an unsubscribe function. `emit(event, payload)` fires a public `GridEvents` event, for modules that change data or state on the user's behalf.

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

```ts
interface InternalEvents<TRow = RowData>
```

| Property | Type | Description |
| --- | --- | --- |
| `cellPointerDown` | `{ position: CellPosition; event: PointerEvent }` |  |
| `cellPointerEnter` | `{ position: CellPosition; event: PointerEvent }` |  |
| `pointerUp` | `{ event: PointerEvent }` |  |
| `keyDown` | `{ event: KeyboardEvent; focused: CellPosition \| null }` |  |
| `rendered` | `{ firstRow: number; lastRow: number }` |  |
| `pipelineDone` | `{ rows: readonly DisplayRow<TRow>[] }` |  |
| `optionsChanged` | `{ changed: (keyof GridOptions<TRow>)[] }` |  |
| `columnDragMove` | `{ colId: string; clientX: number; clientY: number; event: PointerEvent }` |  |
| `columnDragEnd` | `{ colId: string; clientX: number; clientY: number; event: PointerEvent; handled: boolean }` |  |
| `headerContextMenu` | `{ colId: string; event: MouseEvent }` |  |
| `destroy` | `Record<string, never>` |  |

| Event | Fires |
| --- | --- |
| `pipelineDone` | After every pipeline run, with the display rows of the current page |
| `rendered` | After every render, with the first and last rendered row index |
| `optionsChanged` | After `update()`, with the option keys that changed |
| `keyDown` | For every key pressed in the grid while no editor is open, with `{ event, focused }`, before any other key handling; call `event.preventDefault()` to stop it |
| `cellPointerDown`, `cellPointerEnter`, `pointerUp` | Pointer interaction on body cells, for drag selections |
| `columnDragMove`, `columnDragEnd` | While a header is dragged; set `handled: true` in `columnDragEnd` to take over the drop |
| `headerContextMenu` | When a header's context menu is requested |
| `destroy` | Right before the grid tears down |

## Computing rows for exports

`computeRows(options?)` returns a copy of the display rows across every page, after all stages, without touching what the user sees. With `{ expandAll: true }` the pipeline is re-run as if every group, tree and master row were expanded, then the user's expansion state is restored. Export modules use it so a file can contain every row even when groups are collapsed on screen.

```ts
const everyRow = grid.computeRows({ expandAll: true });
const leafCount = everyRow.filter((row) => row.kind === 'data').length;
```

The rows are shallow copies, so changing them does not affect the grid. Running the pipeline twice costs time on large datasets, so call it on demand, for example when the user clicks Export, not on every render.

Lower-level helpers round out the internals: `getCellElement(rowIndex, colId)`, `getColumnElement(colId)`, `cellFromPoint(clientX, clientY)`, `getRenderedRange()`, `refresh()` (re-resolve columns and re-run the pipeline) and `render()` (re-render every visible cell).

## A complete module: overdue invoices

This module highlights overdue invoices, shows a live summary under the grid, adds a column menu filter, a keyboard shortcut to jump between overdue rows, and an API method. It cleans up everything it registers.

```ts title="overdue-invoices-module.ts"
import type { FilterModel, GridApi, GridInternals, GridModule } from '@birchui/core';

export interface Invoice {
  number: string;
  customer: string;
  due: string;
  amount: number;
  paid: boolean;
}

export interface OverdueInvoicesApi {
  getOverdueInvoices(): Invoice[];
}

export function overdueInvoicesModule(options: { dueColumn: string; currency?: string }): GridModule {
  const money = new Intl.NumberFormat('en-IE', { style: 'currency', currency: options.currency ?? 'EUR' });

  return {
    name: 'overdueInvoices',
    install(grid: GridInternals<Invoice>) {
      const today = () => new Date(new Date().toDateString()).getTime();
      const isOverdue = (invoice: Invoice | undefined): invoice is Invoice =>
        !!invoice && !invoice.paid && Date.parse(`${invoice.due}T00:00:00`) < today();

      const removeDecorator = grid.addCellDecorator((cell, ctx) => {
        if (isOverdue(ctx.row)) {
          cell.classList.add('invoice-overdue-row');
          if (ctx.column.id === options.dueColumn) cell.classList.add('invoice-overdue');
        }
      });

      const summary = document.createElement('div');
      summary.className = 'overdue-summary';
      summary.setAttribute('role', 'status');
      grid.slot('bottom').append(summary);

      const offPipeline = grid.on('pipelineDone', () => {
        const overdue = grid.api.getRows().filter(isOverdue);
        const outstanding = overdue.reduce((sum, invoice) => sum + invoice.amount, 0);
        summary.textContent = overdue.length
          ? `${overdue.length} overdue invoices, ${money.format(outstanding)} outstanding`
          : 'No overdue invoices';
      });

      const overdueOnly: FilterModel = { type: 'custom', test: (_value, row) => isOverdue(row as Invoice) };
      const isFiltering = () => grid.api.getFilterModel()[options.dueColumn] === overdueOnly;

      const removeMenu = grid.addColumnMenuItems((column) =>
        column.id === options.dueColumn
          ? [
              {
                label: 'Show only overdue',
                separatorBefore: true,
                checked: isFiltering(),
                action: () => grid.api.setFilter(options.dueColumn, isFiltering() ? null : overdueOnly),
              },
            ]
          : [],
      );

      const removeKeys = grid.addKeyHandler((event, focused) => {
        if (event.key !== 'n' || event.ctrlKey || event.metaKey || event.altKey) return false;
        const rows = grid.api.getDisplayRows();
        const start = (focused?.rowIndex ?? -1) + 1;
        for (let step = 0; step < rows.length; step++) {
          const index = (start + step) % rows.length;
          if (isOverdue(rows[index].data)) {
            grid.api.focusCell(index, options.dueColumn);
            return true;
          }
        }
        return false;
      });

      const removeMethod = grid.expose('getOverdueInvoices', () => grid.api.getRows().filter(isOverdue));

      return () => {
        removeDecorator();
        offPipeline();
        removeMenu();
        removeKeys();
        removeMethod();
        summary.remove();
      };
    },
  };
}

export type InvoiceGridApi = GridApi<Invoice> & Partial<OverdueInvoicesApi>;
```

```ts title="invoices-grid.ts"
import { createGrid, type ColumnDef } from '@birchui/core';
import { overdueInvoicesModule, type Invoice, type InvoiceGridApi } from './overdue-invoices-module';

const columns: ColumnDef<Invoice>[] = [
  { field: 'number', header: 'Invoice', width: 130 },
  { field: 'customer', flex: 1 },
  { field: 'due', type: 'date', width: 130 },
  { field: 'amount', type: 'number', width: 130 },
  { field: 'paid', type: 'boolean', width: 90 },
];

const grid: InvoiceGridApi = createGrid<Invoice>(document.querySelector('#invoices')!, {
  columns,
  rows: invoices,
  getRowId: (invoice) => invoice.number,
  modules: [overdueInvoicesModule({ dueColumn: 'due' })],
});

console.info(grid.getOverdueInvoices?.().length, 'invoices need a reminder');
```

```css title="overdue.css"
.lq-grid .lq-cell.invoice-overdue-row {
  background: color-mix(in srgb, #cf222e 6%, var(--lq-bg));
}
.lq-grid .lq-cell.invoice-overdue {
  color: #cf222e;
  font-weight: 600;
}
.overdue-summary {
  padding: 6px var(--lq-cell-padding);
  color: var(--lq-muted-fg);
}
```

Press <kbd>N</kbd> in the grid to jump to the next overdue invoice; the key handler runs before the grid would start editing.

## Related

- [Grid Pro overview](https://docs.birchui.com/grid-pro/overview.md) lists every Pro module.
- [Events reference](https://docs.birchui.com/grid/events.md) covers the public events modules can emit.
- [Keyboard navigation & accessibility](https://docs.birchui.com/grid/accessibility.md) for the built-in key map that key handlers run before.
