# Row and column spans

> Span cells across columns and rows with column `colSpan` and `rowSpan`, or merge equal adjacent values grid-wide with `mergeCells`.

Canonical: https://salmonui.dev/docs/data-grid/cell-spans

Spans are declarative column fields, not per-cell callbacks or global
switches. Spans are computed for rendered rows only, so the default path pays
one flag check per row when no column spans.

## Column fields

`colSpan` covers the following visible columns of the same row and `rowSpan` the following rows of the same column.
Both take either:

- a function of the cell context (`row`, `rowId`, `rowIndex`, `column`,
  `field`, `value`) that returns the span, where `1` means no span; or
- `true`, which merges equal adjacent non-empty values.

```tsx
const columns = [
  { field: 'block', header: 'Block', rowSpan: true },
  { field: 'tue', header: 'Tuesday', colSpan: ({ row }) => (row.id === 's10' ? 3 : 1) },
];
```

## Data Grid-wide merging

The grid `mergeCells` prop merges equal adjacent values without touching the
column definitions: `'rows'` merges vertically (as if every column had
`rowSpan: true`), `'columns'` horizontally, and `true` both ways. A column's
own `colSpan` or `rowSpan` wins over `mergeCells`.

## Rendering, pinning and virtualization

A spanning cell covers the cells it spans and carries `aria-colspan` or
`aria-rowspan` for assistive technology. Column spans work with column
virtualization: a span that starts before the rendered column range is drawn
from the start of the range, as long as it starts at most 16 columns before
it; a `colSpan` wider than that which starts further left is not
drawn while its start is out of that reach. Row spans work with row
virtualization too: a span whose first row has scrolled above the
rendered rows is drawn from that row, with its value, however far above it
starts, so a `rowSpan` of 20,000 rows stays one cell while you scroll through
it. Explicit `rowSpan` functions are read through an anchor index: the rows
are scanned once, as they come into view (or once up to the target of a
jump), and the index is rebuilt only when the data, sorting, filtering or
the span settings change, so scrolling never re-reads the rows above the
window. A span function should therefore depend only on its cell context.
Merges of equal values (`rowSpan: true`) are drawn from up to 64 rows above
the window, which looks the same since every covered row has the same value.
Spans never cross the edge of the sticky top or bottom rows. Their height
follows the row heights: the fixed `rowHeight`, or the per-row heights of
`getRowHeight`; with rows measured from their content
(`estimatedRowHeight`) a span assumes the fixed row height. The demo below
renders every row with `virtualization: { rows: false }` only because it is
small.

A span never crosses a pin edge: a `colSpan` that would leave its pin zone,
or run past the last column, is clamped there with a development warning.

## Focus, selection and editing

Spanning works with editing, CRUD and `updateCell`: a span behaves as one
cell at its anchor, the top-left cell that draws it:

- **Keyboard.** Arrow keys skip covered cells. Moving into a span lands on
  its anchor; moving out leaves from the span's edge, so ArrowRight from a
  three-column span goes to the column after it and ArrowDown from a
  two-row span goes two rows down. Moving down through a column span
  returns to the column you started in, and moving sideways through a row
  span returns to your row, as in a spreadsheet. Home, End, Ctrl+Home,
  Ctrl+End (⌘+Home and ⌘+End on macOS) and PageUp/PageDown land on anchors
  too.
- **Pointer and selection.** Clicking anywhere on a span focuses and
  selects its anchor cell; `api` calls that name a covered cell use the
  anchor. With `selection: { cellRange: 'box' }` a range grows to cover
  every span it touches (Shift+click, Shift+Arrow); a `flow` range runs
  between anchor cells.
- **Editing.** F2, double-click and Enter edit the anchor cell; Tab,
  Shift+Tab, Enter and Shift+Enter in cell and batch editing skip covered
  cells. `updateCell`, `updateRow`, adding, deleting and batch saves write
  any cell, covered or not, and spans are recomputed from the changed data
  (an edited value can start or end a `rowSpan: true` merge).

Span lookups run only on these actions, never while scrolling, and answer
for any row, including rows outside the rendered window: column spans of the
row, explicit row spans that start any distance above it (from the same
anchor index), and equal-value merges followed up to 4,096 rows each way. A box range whose edges hold more
than 1,024 cells is kept as drawn instead of growing.

### Live demo: Row and column spans

Live demo: https://salmonui.dev/demos/data-grid/cell-spans

A weekly schedule with `rowSpan: true` on a pinned column, an explicit `colSpan` function, and the grid `mergeCells` switch for merging equal adjacent values by rows, columns or both, with `aria-rowspan` and `aria-colspan` on merged cells. Merged cells are one focus stop: arrow keys skip covered cells, box selection covers whole spans, and cell editing edits the span's anchor cell.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { DataGrid, type DataGridColumn, type DataGridEditing, type DataGridMergeCells, type DataGridSelection, type DataGridVirtualization } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';

interface Slot {
  readonly id: string;
  readonly block: string;
  readonly time: string;
  readonly mon: string;
  readonly tue: string;
  readonly wed: string;
  readonly thu: string;
  readonly fri: string;
}

// A weekly room schedule: equal adjacent values merge, and one booking spans
// three days through an explicit `colSpan` function.
const slots: Slot[] = [
  { id: 's08', block: 'Morning', time: '08:00', mon: 'Stand-up', tue: 'Stand-up', wed: 'Stand-up', thu: 'Stand-up', fri: 'Stand-up' },
  { id: 's09', block: 'Morning', time: '09:00', mon: 'Design review', tue: 'Planning', wed: 'Planning', thu: 'Workshop', fri: 'Retro' },
  { id: 's10', block: 'Morning', time: '10:00', mon: 'Design review', tue: 'Offsite', wed: '', thu: '', fri: 'Retro' },
  { id: 's11', block: 'Morning', time: '11:00', mon: 'Focus time', tue: 'Focus time', wed: 'Focus time', thu: 'Interviews', fri: 'Demo' },
  { id: 's12', block: 'Midday', time: '12:00', mon: 'Lunch', tue: 'Lunch', wed: 'Lunch', thu: 'Lunch', fri: 'Lunch' },
  { id: 's13', block: 'Afternoon', time: '13:00', mon: 'Pairing', tue: 'Customer call', wed: 'Pairing', thu: 'Interviews', fri: 'Demo' },
  { id: 's14', block: 'Afternoon', time: '14:00', mon: 'Pairing', tue: 'Customer call', wed: 'Pairing', thu: 'Training', fri: 'Release' },
  { id: 's15', block: 'Afternoon', time: '15:00', mon: 'Support', tue: 'Support', wed: 'Support', thu: 'Training', fri: 'Release' },
  { id: 's16', block: 'Afternoon', time: '16:00', mon: 'Office hours', tue: 'Office hours', wed: 'Office hours', thu: 'Office hours', fri: '' },
];

const day = (field: keyof Slot, header: string): DataGridColumn<Slot> => ({ field, header, width: 140 });

const columns: DataGridColumn<Slot>[] = [
  // Vertical merge of the block names, pinned with the time column.
  { field: 'block', header: 'Block', width: 110, pinned: 'start', rowSpan: true },
  { field: 'time', header: 'Time', width: 80, pinned: 'start', primaryKey: true },
  day('mon', 'Monday'),
  // An explicit span: the 10:00 offsite covers Tuesday to Thursday.
  { ...day('tue', 'Tuesday'), colSpan: ({ row }) => (row.id === 's10' ? 3 : 1) },
  day('wed', 'Wednesday'),
  day('thu', 'Thursday'),
  day('fri', 'Friday'),
];

const modes: readonly { readonly label: string; readonly value: DataGridMergeCells }[] = [
  { label: 'Off (column spans only)', value: false },
  { label: 'Rows', value: 'rows' },
  { label: 'Columns', value: 'columns' },
  { label: 'Both', value: true },
];
const MODE_OPTIONS = modes.map((m, index) => ({ value: String(index), label: m.label }));

// Row spans are computed over rendered rows: this demo renders every row.
const noRowVirtualization: DataGridVirtualization = { rows: false };
// Spans are one focus stop at their anchor: box ranges grow over
// whole spans, and double-click, F2 or typing edits the anchor cell.
const cellSelection: DataGridSelection = { mode: 'cell', multiple: true, cellRange: 'box' };
const cellEditing: DataGridEditing<Slot> = { mode: 'cell' };

export default function CellSpansDemo() {
  const [mode, setMode] = useState(3);
  return (
    <>
      <div className="demo-toolbar">
        <label>
          mergeCells
          <Select aria-label="mergeCells" data={MODE_OPTIONS} value={String(mode)} onValueChange={(value) => value != null && setMode(Number(value))} />
        </label>
      </div>
      <DataGrid<Slot>
        aria-label="Weekly room schedule with merged cells"
        data={slots}
        columns={columns}
        mergeCells={modes[mode]?.value ?? false}
        virtualization={noRowVirtualization}
        gridLines="both"
        striped={false}
        height={380}
        selection={cellSelection}
        editing={cellEditing}
      />
    </>
  );
}
```

## API reference

[`DataGridSpan`](https://salmonui.dev/docs/reference/data-grid/DataGridSpan) and
[`DataGridSpanContext`](https://salmonui.dev/docs/reference/data-grid/DataGridSpanContext)
describe the column `colSpan` / `rowSpan` fields, and
[`DataGridMergeCells`](https://salmonui.dev/docs/reference/data-grid/DataGridMergeCells) the
`mergeCells` prop.
