# Range selection

> Select rectangular blocks of cells with the mouse or keyboard, read their values and react to changes.

Range selection lets users select cells the way they do in a spreadsheet: drag across a block, extend it with `Shift`, add more blocks with `Ctrl` or `Cmd`. Ranges are the input for [clipboard](https://docs.birchui.com/grid-pro/clipboard.md) copy and paste, the [fill handle](https://docs.birchui.com/grid-pro/fill-handle.md) and the aggregates in the [status bar](https://docs.birchui.com/grid-pro/status-bar.md).

> **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> Range selection requires `RangeSelectionModule` from `@birchui/grid-pro`.

**Live demo: Range selection, clipboard and fill handle** (runs on the HTML version of this page). Source of `demos/range-clipboard.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { ClipboardModule, FillHandleModule, RangeSelectionModule, StatusBarModule } from '@birchui/grid-pro';
import { docsTheme, layout, onDocsThemeChange, seededRandom } from './_shared';

export const meta = { title: 'Range selection, clipboard and fill handle', height: 480 };

interface ForecastRow {
  id: string;
  product: string;
  jan: number;
  feb: number;
  mar: number;
  apr: number;
  may: number;
  jun: number;
}

const PRODUCTS = [
  'Standing desk',
  'Ergonomic chair',
  'Monitor arm',
  '27" 4K monitor',
  'USB-C dock',
  'Desk lamp',
  'Filing cabinet',
  'Headset',
];
const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun'] as const;

function makeForecast(): ForecastRow[] {
  const random = seededRandom(8);
  return PRODUCTS.flatMap((product, p) =>
    ['North America', 'Europe', 'Asia Pacific'].map((region, r) => {
      const row: ForecastRow = {
        id: `${p}-${r}`,
        product: `${product}, ${region}`,
        jan: 0,
        feb: 0,
        mar: 0,
        apr: 0,
        may: 0,
        jun: 0,
      };
      for (const month of MONTHS) row[month] = Math.round(40 + random() * 260);
      return row;
    }),
  );
}

const columns: ColumnDef<ForecastRow>[] = [
  { field: 'product', header: 'Product and region', width: 240, pinned: 'left' },
  ...MONTHS.map((month): ColumnDef<ForecastRow> => ({
    field: month,
    header: month[0].toUpperCase() + month.slice(1),
    type: 'number',
    width: 100,
    editable: true,
    valueParser: (input) => Number(String(input).replace(/[^\d.-]/g, '')),
  })),
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  toolbar.append(
    'Drag across cells or use Shift+arrows. Ctrl/Cmd+C copies as TSV; paste from a spreadsheet with Ctrl/Cmd+V; drag the fill handle to extend a series.',
  );
  const grid = createGrid<ForecastRow>(body, {
    columns,
    rows: makeForecast(),
    getRowId: (row) => row.id,
    modules: [RangeSelectionModule, ClipboardModule, FillHandleModule, StatusBarModule],
    rangeSelection: true,
    clipboard: true,
    fillHandle: true,
    statusBar: { rowCount: true, aggregates: ['sum', 'avg', 'count'] },
    theme: docsTheme(),
    ariaLabel: 'Unit forecast by month',
  });
  status.textContent = 'Edits from paste and fill arrive as cellValueChanged events.';
  const off = grid.on('cellValueChanged', ({ source, colId, row, newValue }) => {
    status.textContent = `${source}: ${row.product} ${colId.toUpperCase()} = ${String(newValue)}`;
  });
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    off();
    stopTheme();
    grid.destroy();
  };
}
```

## Enable range selection

```ts
import { createGrid } from '@birchui/core';
import { RangeSelectionModule, ClipboardModule, StatusBarModule } from '@birchui/grid-pro';

const api = createGrid(container, {
  columns,
  rows: invoices,
  getRowId: (row) => row.invoiceNo,
  modules: [RangeSelectionModule, ClipboardModule, StatusBarModule],
  rangeSelection: true,
  clipboard: true,
  statusBar: true,
});
```

Range selection is off until you set `rangeSelection: true`. It can be switched at runtime with `api.update({ rangeSelection: false })`. Turning it off clears the current ranges.

Range selection is independent of [row selection](https://docs.birchui.com/grid/selection.md). You can use both: row selection for "which records does this action apply to", ranges for "which cells am I working with".

## Mouse

| Action | Result |
| --- | --- |
| Press and drag | Selects the block from the cell under the pointer to the cell where you release. Dragging past the edge of the grid scrolls it. |
| `Shift` + click | Extends the current range from its starting cell to the clicked cell. |
| `Ctrl` + click, `Cmd` + click on macOS | Adds the clicked cell as a new range, keeping the existing ones. Drag to make the new range larger. |
| Click | Starts a new single-cell range. |

Pressing on buttons, links, inputs or the fill handle inside a cell does not start a range, so cell renderers with controls keep working.

## Keyboard

| Keys | Result |
| --- | --- |
| `Shift` + arrow keys | Extend the range by one cell. |
| `Shift` + `Ctrl`/`Cmd` + arrow keys | Extend the range to the first or last row or column. |
| `Shift` + `Home` / `End` | Extend to the first or last column. |
| `Shift` + `Ctrl`/`Cmd` + `Home` / `End` | Extend to the first or last cell of the grid. |
| `Shift` + `Page Up` / `Page Down` | Extend by one page of rows. |
| `Ctrl`/`Cmd` + `A` | Select every cell. |
| `Escape` | Clear the ranges. |
| Arrow keys without `Shift` | Move focus and collapse the selection to the focused cell. |

Keyboard shortcuts are inactive while a cell is being edited, so `Shift` + arrow keys select text inside the editor as usual. The grid scrolls to keep the moving end of the range visible.

## Ranges in code

A range is a plain object. Rows are display row indices, as used by `focusCell()` and `scrollToRow()`; columns are column ids. A range covers every visible column between `startCol` and `endCol` in the current display order.

```ts
interface CellRange {
  startRow: number;
  endRow: number;
  startCol: string;
  endCol: string;
}
```

The module adds these methods to the grid API:

| Method | Purpose |
| --- | --- |
| `getCellRanges()` | The current ranges, in the order they were made. The last one is the active range. |
| `setCellRange(range)` | Replace all ranges with one range. Pass `null` to clear. |
| `addCellRange(range)` | Add a range, keeping the existing ones. |
| `clearCellRanges()` | Remove every range. |
| `getRangeValues(rangeIndex?)` | A 2D array of the raw values in a range, the active range by default. |
| `onRangeChanged(listener)` | Call `listener({ ranges })` whenever the ranges change. Returns an unsubscribe function. |

Like all Pro methods, they are optional on the `GridApi` type, so call them with `?.`. Ranges that name unknown columns are ignored, and row indices are clamped to the rows that exist.

### Select a block programmatically

```ts
api.setCellRange?.({ startRow: 0, endRow: 9, startCol: 'amount', endCol: 'tax' });
```

### Summarise the selection

```ts
const unsubscribe = api.onRangeChanged?.(() => {
  const values = (api.getRangeValues?.() ?? []).flat();
  const numbers = values.filter((value): value is number => typeof value === 'number');
  const total = numbers.reduce((sum, n) => sum + n, 0);
  summary.textContent = numbers.length ? `${numbers.length} values, total ${total.toFixed(2)}` : '';
});
```

The [status bar](https://docs.birchui.com/grid-pro/status-bar.md) does this for you, with configurable aggregates.

### Chart the selection

`getRangeValues()` returns values in display order, so it is a convenient source for a chart or a quick report:

```ts
const [first] = api.getCellRanges?.() ?? [];
if (first) {
  const matrix = api.getRangeValues?.(0) ?? [];
  renderBarChart(matrix);
}
```

## Ranges and data changes

Ranges refer to display positions, not to records. When sorting, filtering, grouping or a data update changes the display rows, ranges that no longer fit are clamped to the remaining rows, and ranges whose columns were removed are dropped. Hiding or moving a column changes which columns a range covers.

Full-width [detail rows](https://docs.birchui.com/grid-pro/master-detail.md) are skipped when values are read, so a range that spans an open detail panel returns only grid cells. Group and total rows inside a range contribute their aggregate values. Paste, cut and fill only ever write to editable data cells.

## Accessibility

Cells inside a range get `aria-selected="true"`, so screen readers announce them as selected. The focused cell keeps the roving tabindex described in [Keyboard navigation & accessibility](https://docs.birchui.com/grid/accessibility.md). Ranges are tinted with the theme variable `--lq-range-bg` and outlined with `--lq-pro-range-edge`, which defaults to `--lq-accent`; see [Theming](https://docs.birchui.com/grid/theming.md) to change them.
