# Clipboard

> Copy cells as tab-separated text that Excel and Google Sheets understand, cut and clear ranges, and paste into editable cells with type-aware parsing.

The clipboard module makes `Ctrl` + `C`, `Ctrl` + `X` and `Ctrl` + `V` (`Cmd` on macOS) work on grid cells the way spreadsheet users expect. Copied cells arrive in Excel, Google Sheets or Numbers as separate cells, and data copied from a spreadsheet can be pasted straight into editable grid cells.

> **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> Clipboard support requires `ClipboardModule` from `@birchui/grid-pro`. It works on the focused cell by itself; add `RangeSelectionModule` with `rangeSelection: true` to copy and paste blocks of cells.

**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 the clipboard

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

interface InvoiceLine {
  id: string;
  sku: string;
  description: string;
  quantity: number;
  unitPrice: number;
  shipDate: string;
  taxable: boolean;
}

const columns: ColumnDef<InvoiceLine>[] = [
  { field: 'sku', header: 'SKU', width: 120 },
  { field: 'description', flex: 1, editable: true },
  { field: 'quantity', type: 'number', editable: true },
  { field: 'unitPrice', header: 'Unit price', type: 'number', editable: true },
  { field: 'shipDate', header: 'Ship date', type: 'date', editable: true },
  { field: 'taxable', type: 'boolean', editable: true },
];

const api = createGrid(container, {
  columns,
  rows: invoiceLines,
  getRowId: (row) => row.id,
  modules: [RangeSelectionModule, ClipboardModule],
  rangeSelection: true,
});
```

The clipboard is on as soon as the module is installed. Set `clipboard: false` to switch it off without removing the module, for example while a grid is read-only.

## Copy

With focus in the grid, `Ctrl` + `C` copies the active range, or the focused cell when there is no range. The text is tab-separated values (TSV), one line per row:

- Number columns copy the raw number, such as `1249.5`, so spreadsheets receive a real number rather than a formatted string like `$1,249.50`.
- All other columns copy what the cell shows, after the column's `format` function.
- Values that contain a tab, a line break or a double quote are quoted, and inner quotes are doubled, so multi-line notes survive the round trip.
- Utility columns, such as the [master/detail](https://docs.birchui.com/grid-pro/master-detail.md) toggle column, and full-width detail rows are left out.

The grid writes to the system clipboard through the Clipboard API, and falls back to a hidden text area on older browsers or pages without clipboard permission.

## Cut and clear

`Ctrl` + `X` copies the selection, then clears every editable cell in it. Text columns are set to an empty string and other columns to `null`. Read-only cells are copied but left unchanged.

`Delete` or `Backspace` on a range of two or more cells clears the editable cells without copying. On a single cell, the grid's normal [editing](https://docs.birchui.com/grid/editing.md) behaviour applies.

## Paste

`Ctrl` + `V` pastes tab-separated text into the grid, starting at the top-left cell of the active range or at the focused cell. How much of the grid is filled depends on the selection:

| Clipboard | Selection | Result |
| --- | --- | --- |
| A single value | Any range | The value is written to every cell of the range. |
| A block, such as 2 × 3 | A range that is an exact multiple of it, such as 4 × 6 | The block is repeated to fill the range. |
| A block | A single cell, or a range that is not a multiple | The block is pasted at its own size from the top-left cell, and may extend beyond the selection. |

After pasting, the range is moved to cover the cells that were pasted, so a second `Ctrl` + `V` or a [fill handle](https://docs.birchui.com/grid-pro/fill-handle.md) drag continues from there.

Paste only writes to cells that are editable: the column has `editable: true`, or an `editable` function that returns `true` for that row. Group rows, total rows and read-only cells are skipped. Values that would not change a cell are skipped too, so they do not fire events.

### How pasted text becomes values

If the column has a `valueParser`, it receives the pasted text and the row, and its return value is written. Otherwise the text is converted according to the column `type`, using the grid's `locale`:

| Column type | Accepted input | Result |
| --- | --- | --- |
| `text` | Anything | The text as is. |
| `number` | `1249.5`, `1,249.50`, `1.249,50` in a German locale, `(250)` for negatives, `12%` | A number. `12%` becomes `0.12`. |
| `boolean` | `true`, `yes`, `y`, `1`, `on`, `x`, `✓` and `false`, `no`, `n`, `0`, `off` | `true` or `false`. |
| `date` | ISO dates such as `2026-03-15` or `2026-03-15 14:30`, and numeric dates in the locale's order, such as `15/03/2026` in `en-GB` | A date in the same form the column already holds: an ISO string, a timestamp or a `Date`. |

An empty cell in the pasted block clears the target: text columns get `''`, others `null`. Text that cannot be converted, such as `n/a` in a number column, leaves that cell unchanged.

A `valueParser` is the place for domain rules, such as accepting currency codes:

```ts
{
  field: 'unitPrice',
  type: 'number',
  editable: true,
  valueParser: (input) => {
    const amount = Number(input.replace(/[^\d.-]/g, ''));
    return Number.isFinite(amount) ? amount : null;
  },
}
```

If a `valueParser` throws, the error is logged and that cell is skipped.

## Events

Every changed cell fires `cellValueChanged`, with `source` telling you where the change came from:

| `source` | Caused by |
| --- | --- |
| `'paste'` | `Ctrl` + `V`, `pasteText()`, `pasteFromClipboard()`, or `Ctrl` + `X` clearing cut cells. |
| `'edit'` | `Delete` or `Backspace` on a range, and normal cell editing. |
| `'fill'` | The [fill handle](https://docs.birchui.com/grid-pro/fill-handle.md). |

```ts
api.on('cellValueChanged', ({ row, colId, oldValue, newValue, source }) => {
  if (source === 'paste') pendingChanges.set(`${row.id}:${colId}`, newValue);
  console.log(`${colId}: ${String(oldValue)} -> ${String(newValue)} (${source})`);
});
```

A paste of 500 cells fires 500 events. Batch your save requests, for example by collecting changes and sending them on the next animation frame.

## Clipboard API methods

| Method | Purpose |
| --- | --- |
| `copyToClipboard()` | Copy the active range or focused cell. Returns a promise. |
| `cutToClipboard()` | Copy, then clear the editable cells. |
| `pasteFromClipboard()` | Read the system clipboard and paste. Resolves to the number of cells changed. |
| `pasteText(text)` | Paste a TSV string you already have. Returns the number of cells changed. |

`pasteFromClipboard()` asks the browser for clipboard read permission, which some browsers only grant inside a user gesture such as a button click. When access is blocked, it logs a warning and resolves to `0`. Keyboard paste does not need the permission.

```ts
toolbar.querySelector('#paste')!.addEventListener('click', async () => {
  const changed = (await api.pasteFromClipboard?.()) ?? 0;
  statusText.textContent = changed ? `Pasted ${changed} cells` : 'Nothing to paste';
});
```

`pasteText()` applies the same rules to tab-separated text you already have, for example from a drop zone or a server response:

```ts
api.focusCell(0, 'quantity');
api.pasteText?.('12\t18.5\n4\t22');
```

## When the grid does not handle the clipboard

To keep normal text editing intact, the grid leaves clipboard keys alone when:

- a cell editor is open;
- focus is in an input, select, text area or content-editable element, including inputs inside a detail panel;
- `clipboard` is `false`.
