gridcn2.0.0
Clipboard and undo

Clipboard

Copy, cut, and paste cell ranges as TSV and HTML, protect copied formulas, and change the copy and paste steps with your own functions.

Users move data between the grid and spreadsheets with Ctrl+C, Ctrl+X, and Ctrl+V. The grid listens for the native clipboard events, so the core needs no add-on and no permission prompt. Three props change what the grid copies, how it reads a paste, and whether a paste can land.

Select the Formula cells and press Ctrl/Cmd+C. Paste into a spreadsheet: each cell that starts with =, +, -, or @ arrives as text. Paste back into the grid to restore the raw value.

Label
Formula
Total
=SUM(B2:B9)
Offset
+12
Mention
@alice
Note
plain text

Paste

The grid reads the text/html payload first, for example from gridcn, Excel, Sheets, or Numbers. If the payload has no table, it reads the text/plain payload with a quoted-TSV parser. The parser handles tabs, line breaks, and quotes in cells.

  • Anchored expand. An N×M block lands at the top-left of the selected range and overwrites that N×M region. The block stops at the last row and the last column. To add rows from a longer sheet, use Import or Row operations.
  • Single-row tiling. If you paste one row into a taller selected range, the row repeats down every selected row.
  • Value steps. The fromText of each target cell type reads the pasted text. Then validate runs. A cell that fails stays unchanged, and onValidationError reports it with the source "paste". A column with validationMode: "warn" keeps the pasted value and flags the cell instead.
  • Skipped cells. Read-only cells keep their value. This covers a column's static readOnly and its per-row function form. A readOnly grid ignores the paste.
  • One change. A paste calls onDataChange once, with one batch of operations (ops) and the source "paste". The selection then covers the written cells.

A column with an async validate holds the paste until the schema answers. Row validation and async checks owns that contract. For a large paste against a remote check, processPaste validates the whole block in one request.

Copy

Copy takes the range that the user selected last, and no earlier Ctrl/Cmd+click range. If no range exists, it takes the selected rows or the selected columns whole. Ctrl/Cmd+C writes two formats to the clipboard:

  • text/plain: tab-separated values (TSV), one row per line. A cell that contains a tab, a line break, or a quote gets wrapped in quotes, and the grid doubles each inner quote.
  • text/html: a <table>. Each cell carries its exact text in a data-gridcn-raw attribute.

A paste back into gridcn reads that attribute, so tabs and runs of spaces survive.

Ctrl/Cmd+X copies the same way and then clears the copied cells. Cut skips read-only cells. It writes one change with the source "cut". On a readOnly grid, cut only copies. While a cell editor is open, the editor handles copy, cut, and paste itself.

toText, not toDisplayText

The copied text of each cell comes from the toText of its cell type. Display formatting, such as a locale date string, stays out of the clipboard.

Copy to Excel or Sheets

Select a range, press Ctrl/Cmd+C, and paste into a cell of the spreadsheet. The spreadsheet reads the text/html table, so each grid cell lands in its own spreadsheet cell. The spreadsheet reads each text with its own locale rules. The copy follows these rules:

  • The rows come in view order, after the sort and the filters.
  • Only visible columns go into the copy. Column headers stay out.
  • In the table, a tab in a cell becomes four spaces, and a line break stays inside the cell.
  • The copy prefixes formula-like text with ', so the spreadsheet pastes it as text. sanitizeClipboardFormulas controls this.

Known limitations

LimitValueAbove the limit
Copied cells200,000The copy writes only the rows that fit.
Pasted cells200,000The paste applies only the first rows that fit.
Pasted HTML16,000,000 characters (80 characters for each of the 200,000 cells a paste can write)The grid ignores the HTML and reads the plain text.
Pasted plain text51,200,000 characters, 200,000 cells at 256 characters eachThe paste writes nothing.

A truncated copy or paste warns in the browser console in development.

Real-world clipboard HTML is messy

The HTML reader takes the first <table>. A merged cell keeps its text in its first position and leaves the cells it covers empty. Inline styles from Excel, Sheets, and Numbers can hide this structure. If one app pastes wrong, patch it with processPaste or processCellFromClipboard.

Formula sanitizing

If a copied cell starts with =, +, -, @, TAB, or CR, a spreadsheet app that pastes it runs it as a formula. By default, the grid copies such cells as text. Set sanitizeClipboardFormulas to false to copy the raw text:

import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";

type Row = { id: string; formula: string };

const rows: Row[] = [{ id: "1", formula: "=SUM(A1:A3)" }];
const columns = defineColumns<Row>()([
  { id: "formula", header: "Formula", accessorKey: "formula" },
]);

function MyGrid() {
  return (
    <DataGrid
      defaultData={rows}
      columns={columns}
      sanitizeClipboardFormulas={false}
    />
  );
}

Result: copying the cell puts =SUM(A1:A3) on the clipboard. Without the prop, it puts '=SUM(A1:A3) there.

By default, Ctrl+C, Ctrl+X, and the context menu's Copy and Cut put a single quote in front of each formula-like cell. The quote goes into both the text/plain and the text/html payload. Plain numbers such as -5, +5, and -1e-7 stay unchanged. A paste back into gridcn restores the raw value.

The context menu writes through the async Clipboard API. If the browser lacks or denies that API, the copy writes plain text only. A paste back from that copy keeps the quote.

DataGridProvider takes the same prop. A custom copy UI built on useDataGridClipboard follows the prop, and its sanitizeFormulas option overrides it.

Overrides

Three props replace one step of copy or paste. Change copy and paste shows how to use them.

Props

PropTypeDefault
sanitizeClipboardFormulasbooleantrue
processCellForClipboard(value, ctx) => stringnone
processCellFromClipboard(text, ctx) => unknownnone
processPaste({ cells, target, signal }) => string[][] | false | Promise<string[][] | false>none

Copy and paste from code

useDataGridClipboard returns copy, cut, and pasteFromClipboard for your own buttons. Call it under the grid's provider:

import {
  DataGridProvider,
  DataGridRoot,
  defineColumns,
  useDataGridClipboard,
} from "@/components/data-grid/data-grid";

type Row = { id: string; name: string };

const rows: Row[] = [{ id: "1", name: "Pen" }];
const columns = defineColumns<Row>()([
  { id: "name", header: "Name", accessorKey: "name" },
]);

function CopyButton() {
  const clipboard = useDataGridClipboard();
  return <button onClick={() => void clipboard.copy()}>Copy selection</button>;
}

function MyGrid() {
  return (
    <DataGridProvider defaultData={rows} columns={columns}>
      <CopyButton />
      <DataGridRoot />
    </DataGridProvider>
  );
}

copy also runs while a cell editor is open. cut and pasteFromClipboard resolve "refused" then.

copy and cut resolve "ok", "fallback" (plain text only), "failed", or "no-selection". cut also resolves "refused". pasteFromClipboard resolves one of these:

ResultMeaning
"ok"A paste started.
"permission-denied"The browser refused to read the clipboard.
"empty"The clipboard holds no text.
"refused"No paste started. The grid is readOnly, a cell editor is open, there is no target, a sync processPaste vetoed it, or the text holds no cells.

A paste through this hook carries no HTML.

Context menu paste

The context menu add-on adds a Paste item that calls pasteFromClipboard. It needs the clipboard-read permission. If the browser withholds it, the item turns off and shows a "press Ctrl+V" hint.

Server mode

Copy and paste work on the rows that the grid displays, in their displayed order. On a paged grid, that is the shown page. A column selection copies the rows of the shown page, and a paste stops at the page's last row. Client and server pagination follow this rule. With sortMode="server", the displayed order is the order your server returned.

A paste is one change with the source "paste". The grid calls onDataChange and onSave with it, and onSave sends it to the server. If onSave resolves with { rejected } or rejects, the grid reverts the refused cells through onDataChange with the source "rollback".

In scroll mode, a paste writes the loaded rows, skips the rest, and adds no row. A copy gives empty cells for rows that are not loaded. Data modes owns the detail for every mode. To copy or export every server row, see Export the whole result.

On this page