# Clipboard

> Copy cell ranges, selected rows or the focused cell as TSV with or without headers, paste spreadsheet blocks into edit drafts, formatted or raw copy text per column, `onBeforeCopy` and `onBeforePaste`, and the fallbacks when the browser blocks clipboard access.

Canonical: https://salmonui.dev/docs/data-grid/clipboard

A grid with `editing` copies and pastes like a spreadsheet: the `editing`
prop registers the core `clipboard` module, and the keyboard, toolbar and
menu wiring lives in the lazy editing chunk, so a grid without `editing`
loads none of it. A read-only grid that should still copy turns the
capabilities off:

```tsx
<DataGrid data={orders} columns={columns} editing={{ edit: false, add: false, delete: false }} selection={{ mode: 'cell', cellRange: 'box' }} />
```

## Copy

Ctrl+C (⌘C on macOS) copies, Ctrl+Shift+H copies with the header row.
`api.copy({ includeHeaders })` does the same from code
 and returns `applied`, or
`rejected` with `nothingToCopy` or `cancelled`. The toolbar item `'copy'`
and the context menu item `'copy'` copy the selection too.

The text is TSV: fields holding a tab, a newline or a quote are quoted with
`""`. A copy takes, in order of priority, the bounding box of the selected
cell ranges, else the selected rows, else the focused cell; only data rows
(group captions and footers are left out), and a row number column copies
empty. Pending drafts are copied as shown. A copy above one million cells is
refused.

## Formatted or raw text

A copy uses the display text of each cell by default: formats, lookup
display values and `valueFormatter` output. `column.clipboardFormatter(value,
ctx)` replaces that text for one column, for example a raw number for a
currency column. `api.copy({ copyFormatted: false })` copies raw
values instead (numbers unformatted, dates as ISO strings) for every column
except those with a `clipboardFormatter`, which always wins; lookup columns
still copy their display text. Keyboard and menu copies use the display text.

## Paste

Ctrl+V (⌘V) pastes TSV (quoted fields, CRLF, CR or LF) from the top-left
cell of the selected range, or from the focused cell.
`api.paste(text)` pastes text from code; `api.paste()` without text reads the
system clipboard.

- one value fills the whole selected range; a larger block is clipped to
  the range or the grid edge;
- read-only cells (`editable: false`, `isCellEditable`, primary keys on
  existing rows) and utility columns are skipped;
- values are parsed by the column type and validated like typed input
  (accepting a copied `$18.50` or `25%` back);
- in `cell` mode the values are written at once; in the other modes they
  become drafts (in batch mode marked until Save).

## Events

```tsx
<DataGrid
  editing={{ mode: 'batch' }}
  selection={{ mode: 'cell', multiple: true, cellRange: 'box' }}
  onBeforeCopy={(e) => {
    // e.data: the TSV text; e.copied: 'range' | 'rows' | 'cell'; e.cells, e.rowIds, e.fields, e.includeHeaders
    e.data = e.data.replaceAll('\t', ';');
  }}
  onBeforePaste={(e) => {
    // e.data: the clipboard text; e.target: the top-left target cell
    if (e.data.length > 100_000) e.preventDefault();
  }}
/>
```

`onBeforeCopy` and `onBeforePaste` are cancellable with `preventDefault()`, and assigning
`event.data` replaces the text that is written or pasted; `data`
is the one writable field of these otherwise frozen event objects.
`e.cells` is the number of copied data cells. Paste
raises one event per paste with the whole text, not one per cell: per-cell
conversions belong in the column parser.

## Without clipboard access

The async Clipboard API exists only in secure contexts (HTTPS, localhost) and
can be blocked by permissions. The grid falls back instead of failing:

- Copy writes with `navigator.clipboard.writeText` when it is available,
  else selects the text in a hidden textarea and runs the browser's copy
  command. When both are refused, a small dialog shows the text selected:
  press Ctrl/⌘+C, and the dialog closes.
- Ctrl/⌘+V never needs the Clipboard API: the keystroke moves focus to a
  hidden textarea for an instant, the browser pastes into it, and the grid
  reads the paste event. There is no permission prompt.
- `api.paste()` without text reads `navigator.clipboard.readText()`, or opens
  a paste dialog: press Ctrl/⌘+V in it.

The dialogs are native `<dialog>` elements with the grid's localized texts
(`clipboardCopyHint`, `clipboardPasteHint`, `clipboardText`, `copy`,
`paste`); focus returns to the grid when they close.

### Live demo: Copy and paste

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

Copy a cell range, the selected rows or the focused cell as TSV, with or without headers; paste TSV into batch drafts, skipping read-only cells; raw and display-text copies; `onBeforeCopy` / `onBeforePaste` changing or cancelling the text.

`Demo.tsx`:

```tsx
'use client';

import { useMemo, useRef, useState } from 'react';
import { createLookupModule } from '@salmonui/data-grid/engine/lookup';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { TextArea } from '@salmonui/inputs/text-field';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(2_000, 31);

// Lookup (foreign-key) column: copies its display text.
const categories = [
  { code: 'Coffee', label: 'Coffee beans' },
  { code: 'Tea', label: 'Loose tea' },
  { code: 'Equipment', label: 'Brewing equipment' },
];

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 140 },
  { field: 'category', header: 'Category', width: 160, lookup: { data: categories, keyField: 'code', displayField: 'label' } },
  // Read-only: paste skips it.
  { field: 'country', header: 'Country (read-only)', width: 170, editable: false },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80 },
  // Copies the formatted text ("$18.50"); a pasted "$20.00" parses back to 20.
  { field: 'unitPrice', header: 'Price', type: 'number', format: 'C2', align: 'end', width: 100 },
  // Raw copy: `clipboardFormatter` wins over the display format.
  { field: 'amount', header: 'Amount (raw copy)', type: 'number', format: 'C2', align: 'end', width: 170, clipboardFormatter: (value) => Number(value).toFixed(2) },
];

// `editing` brings the clipboard: Ctrl/⌘+C, Ctrl+Shift+H, Ctrl/⌘+V, copy(), paste() and the copy items.
const editing = { mode: 'batch', confirmDiscard: false, guardUnsaved: false } as const;
const selection = { mode: 'cell', cellRange: 'box', multiple: true } as const;
const toolbar = ['copy', 'save', 'cancel'] as const;
const contextMenu = ['copy'] as const;

export default function ClipboardDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const modules = useMemo(() => [createLookupModule<Order>()], []);
  const [copied, setCopied] = useState('');
  // Customer, Category (a lookup key), Country (read-only: skipped), Qty.
  const [pasteText, setPasteText] = useState('Pasted one\tTea\tIgnored\t5\nPasted two\tCoffee\tIgnored\t6');
  const [semicolons, setSemicolons] = useState(false);
  const [blockPaste, setBlockPaste] = useState(false);
  const [log, push] = useEventLog();
  const result = (name: string, r: { status: string; reason?: string } | undefined) => push(`${name}: ${r?.status ?? 'no grid'}${r?.status === 'rejected' ? ` (${r.reason})` : ''}`);

  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" type="button" onClick={() => result('copy()', api.current?.copy())}>
          copy()
        </Button>
        <Button variant="outline" type="button" onClick={() => result('copy({ includeHeaders: true })', api.current?.copy({ includeHeaders: true }))}>
          {'copy({ includeHeaders: true })'}
        </Button>
        <Button variant="outline" type="button" onClick={() => result('copy({ copyFormatted: false })', api.current?.copy({ copyFormatted: false }))}>
          {'copy({ copyFormatted: false })'}
        </Button>
        <Button variant="outline" type="button" onClick={() => api.current?.selectCellRange({ rowId: 'ORD-10000', field: 'customer' }, { rowId: 'ORD-10002', field: 'amount' })}>
          Select 3 rows × Customer–Amount
        </Button>
        <Button variant="outline" type="button" onClick={() => result('paste', api.current?.paste(pasteText))}>
          Paste the text below
        </Button>
        <Button variant="outline" type="button" onClick={() => result('paste()', api.current?.paste())}>
          Paste from the clipboard
        </Button>
        <Checkbox checked={semicolons} onCheckedChange={(checked) => setSemicolons(checked)}>
          Copy with semicolons
        </Checkbox>
        <Checkbox checked={blockPaste} onCheckedChange={(checked) => setBlockPaste(checked)}>
          Cancel pastes
        </Checkbox>
      </div>
      <DataGrid<Order>
        aria-label="Clipboard copy and paste"
        data={orders}
        columns={columns}
        modules={modules}
        height={320}
        locale="en-US"
        currency="USD"
        ref={api}
        selection={selection}
        editing={editing}
        toolbar={toolbar}
        contextMenu={contextMenu}
        onBeforeCopy={(e) => {
          // assigning `data` replaces the text written to the clipboard.
          if (semicolons) e.data = e.data.replaceAll('\t', ';');
          setCopied(e.data);
          push(`copy${e.includeHeaders ? ' with headers' : ''}: ${e.cells} cells from the ${e.copied} (${e.source})`);
        }}
        onBeforePaste={(e) => {
          push(`onBeforePaste (${e.source}): ${e.data.length} characters at ${e.target ? `${e.target.rowId} / ${e.target.field}` : 'no target'}${blockPaste ? ', cancelled' : ''}`);
          if (blockPaste) e.preventDefault();
        }}
      />
      <div className="demo-toolbar" style={{ marginBlockStart: 'var(--salmon-space-4)' }}>
        <TextArea label="Last copy (TSV)" aria-label="Last copy" readOnly rows={4} cols={60} value={copied} />
        <TextArea label="Text to paste (TSV)" aria-label="Text to paste" rows={4} cols={40} value={pasteText} onValueChange={(value) => setPasteText(value)} />
      </div>
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

See [`DataGridClipboardApi`](https://salmonui.dev/docs/reference/data-grid/DataGridClipboardApi),
[`DataGridClipboardProps`](https://salmonui.dev/docs/reference/data-grid/DataGridClipboardProps)
and [`ColumnDef`](https://salmonui.dev/docs/reference/data-grid/engine/ColumnDef)
(`clipboardFormatter`) in the API reference.
