react-smart-copy 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,6 +6,7 @@
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
7
7
  [![React 18+](https://img.shields.io/badge/React-18%2B-61dafb)](https://react.dev)
8
8
  [![TypeScript](https://img.shields.io/badge/TypeScript-strict-3178c6)](https://www.typescriptlang.org)
9
+ [![GitHub stars](https://img.shields.io/github/stars/suprabhat02/react-smart-copy?style=social)](https://github.com/suprabhat02/react-smart-copy)
9
10
 
10
11
  **[Live demo and docs](https://suprabhat02.github.io/react-smart-copy/)**
11
12
 
@@ -24,6 +25,7 @@ ID PLT-29018 [Copy]
24
25
  - **Paste** text, HTML and screenshots with `usePaste`: a Paste button or Ctrl/⌘+V, no permission prompt for keyboard paste
25
26
  - **`<CopyGroup>`**: only one row shows "Copied" at a time
26
27
  - **`useCopyInterceptor`**: control what Ctrl/⌘+C copies from your page — attribution, redaction, Excel-ready tables, no-copy zones
28
+ - **`react-smart-copy/table`**: copy rows that paste into Excel and Google Sheets as cells, and read pasted ranges back as typed records. Works with AG Grid, TanStack Table and any `<table>`
27
29
  - **`react-smart-copy/capture`**: copy an `<svg>` or any piece of your UI as a PNG
28
30
  - Every failure is a typed, classified error. Nothing silently no-ops
29
31
  - Unstyled. Works with Tailwind, CSS modules, CSS-in-JS, shadcn, MUI, Ant Design
@@ -39,6 +41,7 @@ This package only promises what browsers actually support.
39
41
  | Rich HTML | ✅ | Always paired with a required plain-text fallback. Degrades to text when `ClipboardItem` is missing |
40
42
  | Images | ✅ PNG only | `image/png` is the only format with reliable cross-browser write support. Convert with `canvas.toBlob(cb, 'image/png')` |
41
43
  | JSON | ✅ | Serialised to text. JSON is not a native clipboard format |
44
+ | Tables (Excel, Sheets, Docs) | ✅ | `react-smart-copy/table`: an HTML table plus tab-separated text in one entry. Pasting reads both back |
42
45
  | Several formats at once | ✅ | `kind: 'multi'`; each MIME type is checked with `ClipboardItem.supports()` first |
43
46
  | SVG (icons, charts, logos) | ✅ as PNG | `svgToPngBlob()` from `react-smart-copy/capture` rasterises natively, no dependency. Raw SVG is not a clipboard image format |
44
47
  | A section of your UI as an image | ✅ bring a rasteriser | Browsers have no "screenshot this element" API. `captureElement()` wraps one you choose (e.g. `modern-screenshot`) with limits and checks |
@@ -405,6 +408,122 @@ const { unsubscribe } = registerDragCopy(element, () => ({
405
408
  > `useDragCopy` writes to the `DataTransfer` when the user drags an element. Use them
406
409
  > together if your UI supports both flows.
407
410
 
411
+ ## Tables: Excel, Google Sheets, AG Grid, TanStack
412
+
413
+ `react-smart-copy/table` copies rows so they land as cells in Excel, Google Sheets, Numbers
414
+ and LibreOffice, and as a real table in Docs, Word, Notion and mail. It also reads ranges
415
+ pasted from those apps back into rows and typed records. It has no dependencies, works
416
+ without React, and tree-shakes to what you use (about 1.9 kB for copying).
417
+
418
+ ```tsx
419
+ import { useCopy } from "react-smart-copy";
420
+ import { fromRows, tablePayload } from "react-smart-copy/table";
421
+
422
+ function CopyInvoices({ invoices }: { invoices: Invoice[] }) {
423
+ const { copy, status } = useCopy();
424
+ return (
425
+ <button
426
+ type="button"
427
+ onClick={() =>
428
+ void copy(() =>
429
+ tablePayload(
430
+ fromRows(invoices, [
431
+ { header: "Invoice", value: "id" },
432
+ { header: "Amount", value: "amount" }, // stays a number in Excel
433
+ { header: "Due", value: (row) => row.due.toLocaleDateString() },
434
+ ]),
435
+ ),
436
+ )
437
+ }
438
+ >
439
+ {status === "copied" ? "Copied" : "Copy as table"}
440
+ </button>
441
+ );
442
+ }
443
+ ```
444
+
445
+ `tablePayload` returns an ordinary `html` payload: an HTML `<table>` with tab-separated text
446
+ as its fallback. That means it works everywhere a payload does: `copy()`, `useCopyInterceptor`
447
+ transforms and `useDragCopy` sources. Where rich copy is unavailable, the plain-text fallback
448
+ still pastes into cells.
449
+
450
+ **What survives the trip.** Cells keep their types. Numbers, bigints, booleans and dates stay
451
+ values the spreadsheet can calculate with, while strings are marked as text so Excel keeps
452
+ `00123`, `1/2` and `1E5` as written (`preserveText`). Tabs, quotes and line breaks inside cells
453
+ are quoted the way Excel quotes them. A one-column table ending in an empty cell keeps that
454
+ row. Use `formatCell` for your own number or date formats.
455
+
456
+ **Formula injection is off by default.** A text cell starting with `=`, `+`, `-`, `@`, a tab or
457
+ a line break (or their full-width forms) would run as a formula when pasted. Following OWASP's
458
+ CSV Injection guidance, such cells get a leading `'`, which spreadsheets read as "this is text".
459
+ Typed numbers are never touched, so `-5` passed as a number stays a number. Rich editors show
460
+ that apostrophe, so pass `formulaGuard: false` only for data you trust.
461
+
462
+ ### From your grid
463
+
464
+ ```tsx
465
+ import { fromAgGrid, fromTanStackTable, fromTableElement } from "react-smart-copy/table";
466
+
467
+ // AG Grid v31+ (Community or Enterprise): selected rows in on-screen order.
468
+ copy(() => tablePayload(fromAgGrid(gridRef.current!.api, { rows: "selected" })));
469
+
470
+ // TanStack Table v8 or v9, in any framework adapter, and libraries built on it
471
+ // such as Material React Table and Mantine React Table.
472
+ copy(() => tablePayload(fromTanStackTable(table, { rows: "selected" })));
473
+
474
+ // Any library that renders a real <table>.
475
+ copy(() => tablePayload(fromTableElement(containerRef.current!)));
476
+ ```
477
+
478
+ | Adapter | Rows | Columns and values |
479
+ | ------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
480
+ | `fromAgGrid` | `displayed` (default), `selected`, `filtered`, `all`, or row nodes | Displayed columns minus the selection and row-number columns. `values: "auto"` keeps numbers raw and formats the rest |
481
+ | `fromTanStackTable` | `visible` (default: what `getRowModel()` renders), `selected`, or rows | Visible columns that hold data; display columns such as checkboxes are skipped. `header` and `value` overrides |
482
+ | `fromTableElement` | Every visible row of the first table | Merged cells, `<br>` line breaks, hidden rows and cells handled |
483
+ | `fromRows` | Your objects | You choose: a property (type-checked to hold a cell) or a function |
484
+
485
+ AG Grid ships clipboard support only in Enterprise. This gives Community grids Excel-ready
486
+ copy; for Ctrl/⌘+C, call it from `onCellKeyDown`:
487
+
488
+ ```tsx
489
+ onCellKeyDown={(event) => {
490
+ const key = event.event as KeyboardEvent | null;
491
+ if (!key || !(key.ctrlKey || key.metaKey) || key.key.toLowerCase() !== "c") return;
492
+ const selected = event.api.getSelectedNodes().length > 0;
493
+ void copy(() => tablePayload(fromAgGrid(event.api, selected ? { rows: "selected" } : { rows: [event.node] })));
494
+ }}
495
+ ```
496
+
497
+ ### Pasting a range from Excel or Google Sheets
498
+
499
+ ```tsx
500
+ import { usePaste } from "react-smart-copy";
501
+ import { parseTable, toRecords } from "react-smart-copy/table";
502
+
503
+ const { targetProps } = usePaste<HTMLDivElement>({
504
+ accept: ["html", "text"], // the HTML flavour keeps merged cells and line breaks exact
505
+ onPaste: (result) => {
506
+ const table = parseTable(result, { headers: true });
507
+ if (!table) return;
508
+ const { records, missing, errors } = toRecords(table, {
509
+ email: { header: ["Email", "E-mail"], required: true },
510
+ seats: { header: "Seats", parse: (text) => Number.parseInt(text, 10) },
511
+ });
512
+ // records: { email: string | undefined; seats: number | undefined }[]
513
+ },
514
+ });
515
+ ```
516
+
517
+ `parseTable` reads the HTML flavour when it holds a table (Excel, Google Sheets, Word and web
518
+ pages all write one) and falls back to tab-separated text, which is also what it uses on the
519
+ server. Pasted HTML is parsed in an inert document: scripts never run and nothing is fetched.
520
+ Every limit is explicit: `maxRows` (100,000), `maxColumns` (16,384, Excel's own), `maxCells`
521
+ (1,000,000) and `maxLength` (32 MiB). Content beyond them sets `truncated: true` instead of
522
+ being dropped silently, and merged cells are counted too, so a tiny document can't claim
523
+ millions of cells. `toRecords` matches headers ignoring case, spacing and full-width forms,
524
+ reports `missing` required columns and every cell whose `parse` threw, and never stops at the
525
+ first bad row.
526
+
408
527
  ## Only one "Copied" at a time
409
528
 
410
529
  Wrap a table or list in `<CopyGroup>`. A new successful copy returns the previously copied
@@ -845,9 +964,10 @@ embedded webviews. Where a capability is missing you get a typed error, never a
845
964
  - ~~**1.2** Paste `retry()`, cancellation with `AbortSignal`, `PasteField.Preview`~~ shipped
846
965
  - ~~**1.3** `onReset` / `onCancel` callbacks, UTF-8 `maxBytes` on every paste path, `PasteResult.imageFiles`~~ shipped
847
966
  - ~~**1.4** Drag-and-drop through the paste pipeline: `dropTargetProps`, `isDragOver`, droppable `PasteField.Zone`~~ shipped
848
- - ~~**1.5** `react-smart-copy/testing` — mock adapters and result builders so consumer tests stay green across releases~~ shipped
967
+ - ~~**1.6** `react-smart-copy/testing` — mock adapters and result builders so consumer tests stay green across releases~~ shipped
849
968
  - ~~**1.7** `useCopyInterceptor` / `registerCopyInterceptor` — attribution, redaction and no-copy zones for native Ctrl/⌘+C~~ shipped
850
969
  - ~~**1.8** `useDragCopy` / `registerDragCopy` — populate `DataTransfer` on drag-start; no Clipboard API needed~~ shipped
970
+ - ~~**1.9** `react-smart-copy/table` — Excel- and Sheets-ready copy and paste, AG Grid and TanStack Table adapters, typed record import~~ shipped
851
971
 
852
972
  Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://suprabhat02.github.io/react-smart-copy/#releases).
853
973
 
@@ -855,7 +975,7 @@ Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://supr
855
975
 
856
976
  ```bash
857
977
  npm install
858
- npm run verify # lint, types, 638 tests at 100% coverage, build, publint + attw, size budgets
978
+ npm run verify # lint, types, 820 tests at 100% coverage, build, publint + attw, size budgets
859
979
  npm run changeset # describe your change for the changelog
860
980
  npm run site:preview # docs site at http://localhost:3000
861
981
  ```
@@ -863,6 +983,17 @@ npm run site:preview # docs site at http://localhost:3000
863
983
  Releases are automated: merging the "chore: release" PR publishes to npm through
864
984
  trusted publishing with provenance. No long-lived npm token is stored in the repo.
865
985
 
986
+ ## Support
987
+
988
+ If react-smart-copy saves you time, [star it on GitHub](https://github.com/suprabhat02/react-smart-copy):
989
+ it helps other React developers find it. Bugs and ideas are welcome in
990
+ [issues](https://github.com/suprabhat02/react-smart-copy/issues).
991
+
992
+ ## Author
993
+
994
+ Built and maintained by [Suprabhat Kumar](https://suprabhat-dev.com/), a frontend
995
+ engineer working on React, TypeScript and accessible UI.
996
+
866
997
  ## License
867
998
 
868
999
  MIT
package/dist/core.cjs CHANGED
@@ -405,6 +405,17 @@ function createOperations() {
405
405
  };
406
406
  }
407
407
  //#endregion
408
+ //#region src/core/source-error.ts
409
+ /**
410
+ * The error for a user-supplied source (copy source, drag source, copy transform)
411
+ * that threw. A thrown `CopyFailure` keeps its classification, so a helper such as
412
+ * `tablePayload()` can report `too-large` instead of a generic `invalid-payload`.
413
+ * Internal: not part of the public API.
414
+ */
415
+ function sourceError(cause, message) {
416
+ return isCopyFailure(cause) ? cause.copyError : createCopyError("invalid-payload", message, cause);
417
+ }
418
+ //#endregion
408
419
  //#region src/core/copy-machine.ts
409
420
  const DEFAULT_RESET_AFTER_MS = 2e3;
410
421
  const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
@@ -507,7 +518,7 @@ function createCopyMachine(options = {}) {
507
518
  }
508
519
  payload = normalizePayload(resolved);
509
520
  } catch (cause) {
510
- const error = createCopyError("invalid-payload", "The copy source function threw.", cause);
521
+ const error = sourceError(cause, "The copy source function threw.");
511
522
  settleError(error, null, retryCount);
512
523
  return Promise.resolve({
513
524
  status: "error",
@@ -797,7 +808,7 @@ function interceptCopyEvent(event, options) {
797
808
  try {
798
809
  decision = options.transform(selection);
799
810
  } catch (cause) {
800
- return fail(createCopyError("invalid-payload", "The copy transform threw.", cause));
811
+ return fail(sourceError(cause, "The copy transform threw."));
801
812
  }
802
813
  if (decision === null || decision === void 0) return {
803
814
  status: "passed",
@@ -1004,7 +1015,7 @@ function applyDragCopy(event, options) {
1004
1015
  } catch (cause) {
1005
1016
  return {
1006
1017
  status: "failed",
1007
- error: createCopyError("invalid-payload", "The drag source threw.", cause)
1018
+ error: sourceError(cause, "The drag source threw.")
1008
1019
  };
1009
1020
  }
1010
1021
  if (decision === null || decision === void 0) return {