react-smart-copy 1.24.0 → 1.24.1

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.
Files changed (148) hide show
  1. package/README.md +130 -1834
  2. package/dist/capture.cjs +3 -3
  3. package/dist/capture.d.cts +1 -1
  4. package/dist/capture.d.ts +1 -1
  5. package/dist/capture.js +3 -3
  6. package/dist/chunks/{clipboard-adapter-CtH4VELE.d.cts → clipboard-adapter-CfaIbZpv.d.cts} +2 -2
  7. package/dist/chunks/{clipboard-adapter-Ds0irroN.d.ts → clipboard-adapter-Chm6zq60.d.ts} +2 -2
  8. package/dist/chunks/{clipboard-adapter-DEXkXxwV.js → clipboard-adapter-CmKDTFdO.js} +3 -3
  9. package/dist/chunks/{clipboard-adapter-DEXkXxwV.js.map → clipboard-adapter-CmKDTFdO.js.map} +1 -1
  10. package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs → clipboard-adapter-UIFc_Qso.cjs} +3 -3
  11. package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs.map → clipboard-adapter-UIFc_Qso.cjs.map} +1 -1
  12. package/dist/chunks/{contrast-C6CVklEI.cjs → contrast-C9d8QuaF.cjs} +2 -2
  13. package/dist/chunks/{contrast-C6CVklEI.cjs.map → contrast-C9d8QuaF.cjs.map} +1 -1
  14. package/dist/chunks/{contrast-DpK2JIVu.js → contrast-DUaZq5SA.js} +2 -2
  15. package/dist/chunks/{contrast-DpK2JIVu.js.map → contrast-DUaZq5SA.js.map} +1 -1
  16. package/dist/chunks/{copy-interceptor-CZWzGOkL.d.cts → copy-interceptor-BClcHS_P.d.cts} +2 -2
  17. package/dist/chunks/{copy-interceptor-C6NABy1l.d.ts → copy-interceptor-D8c9EDnO.d.ts} +2 -2
  18. package/dist/chunks/{core-Cp2HSpaz.js → core-BH2uIumi.js} +5 -5
  19. package/dist/chunks/{core-Cp2HSpaz.js.map → core-BH2uIumi.js.map} +1 -1
  20. package/dist/chunks/{core-DYf_Lhbe.cjs → core-DmncxMt3.cjs} +5 -5
  21. package/dist/chunks/{core-DYf_Lhbe.cjs.map → core-DmncxMt3.cjs.map} +1 -1
  22. package/dist/chunks/{deadline-C29AlS_Q.js → deadline-CbwnZ3Oq.js} +2 -2
  23. package/dist/chunks/{deadline-C29AlS_Q.js.map → deadline-CbwnZ3Oq.js.map} +1 -1
  24. package/dist/chunks/{deadline-DkiB8ZHE.cjs → deadline-j2hD7JKz.cjs} +2 -2
  25. package/dist/chunks/{deadline-DkiB8ZHE.cjs.map → deadline-j2hD7JKz.cjs.map} +1 -1
  26. package/dist/chunks/{errors-9h8sdFFX.js → errors-CT-FfUtU.js} +2 -2
  27. package/dist/chunks/errors-CT-FfUtU.js.map +1 -0
  28. package/dist/chunks/{errors-BwOF6T_M.cjs → errors-DFmEAC4E.cjs} +2 -2
  29. package/dist/chunks/errors-DFmEAC4E.cjs.map +1 -0
  30. package/dist/chunks/{field-BHo5y-t_.js → field-CK3NxfkM.js} +43 -14
  31. package/dist/chunks/field-CK3NxfkM.js.map +1 -0
  32. package/dist/chunks/{field-Bytz2WfN.cjs → field-CNEcZqa9.cjs} +43 -14
  33. package/dist/chunks/field-CNEcZqa9.cjs.map +1 -0
  34. package/dist/chunks/{index-vz0iW5V2.d.cts → index-CqYzvxSN.d.cts} +4 -4
  35. package/dist/chunks/{index-mr7sSAgP.d.ts → index-Q_QeSwGr.d.ts} +4 -4
  36. package/dist/chunks/{paste-adapter--SPL4PRE.d.cts → paste-adapter-B6eucH3E.d.cts} +2 -2
  37. package/dist/chunks/{paste-adapter-uahXnTYk.d.ts → paste-adapter-CfIDT3mp.d.ts} +2 -2
  38. package/dist/chunks/{paste-reader-Bo01IMC_.cjs → paste-reader-BWQaYNaV.cjs} +2 -2
  39. package/dist/chunks/paste-reader-BWQaYNaV.cjs.map +1 -0
  40. package/dist/chunks/{paste-reader-D9i7yMXF.js → paste-reader-D6uOTDBM.js} +2 -2
  41. package/dist/chunks/paste-reader-D6uOTDBM.js.map +1 -0
  42. package/dist/chunks/{payload-DI5AorDz.js → payload-BWQ6sPtS.js} +3 -3
  43. package/dist/chunks/{payload-DI5AorDz.js.map → payload-BWQ6sPtS.js.map} +1 -1
  44. package/dist/chunks/{payload-DGw-JOo7.js → payload-BrQWGwyx.js} +2 -2
  45. package/dist/chunks/{payload-DGw-JOo7.js.map → payload-BrQWGwyx.js.map} +1 -1
  46. package/dist/chunks/{payload-Cl_8hCI5.d.ts → payload-CcvSx_Hq.d.ts} +4 -2
  47. package/dist/chunks/{payload-CcwKJ_bU.d.cts → payload-qkAWVXWA.d.cts} +4 -2
  48. package/dist/chunks/{payload-CUymxwim.cjs → payload-sBxkG7jH.cjs} +2 -2
  49. package/dist/chunks/{payload-CUymxwim.cjs.map → payload-sBxkG7jH.cjs.map} +1 -1
  50. package/dist/chunks/{payload-J6GjHuh3.cjs → payload-tTK6REua.cjs} +3 -3
  51. package/dist/chunks/{payload-J6GjHuh3.cjs.map → payload-tTK6REua.cjs.map} +1 -1
  52. package/dist/chunks/{share-Bop47Znn.js → share-CU91L4EK.js} +6 -6
  53. package/dist/chunks/{share-Bop47Znn.js.map → share-CU91L4EK.js.map} +1 -1
  54. package/dist/chunks/{share-e7FenIr2.d.ts → share-DVR_DhHc.d.ts} +3 -3
  55. package/dist/chunks/{share-C0esXvRK.d.cts → share-hIwth7Dh.d.cts} +3 -3
  56. package/dist/chunks/{share-ayDz974N.cjs → share-nx7M4Z0t.cjs} +6 -6
  57. package/dist/chunks/{share-ayDz974N.cjs.map → share-nx7M4Z0t.cjs.map} +1 -1
  58. package/dist/chunks/{url-D4PGsRm8.cjs → url-BrhVUwn7.cjs} +2 -2
  59. package/dist/chunks/{url-D4PGsRm8.cjs.map → url-BrhVUwn7.cjs.map} +1 -1
  60. package/dist/chunks/{url-BcMYVCXQ.js → url-COID0BLY.js} +2 -2
  61. package/dist/chunks/{url-BcMYVCXQ.js.map → url-COID0BLY.js.map} +1 -1
  62. package/dist/code.cjs +1 -1
  63. package/dist/code.cjs.map +1 -1
  64. package/dist/code.d.cts +1 -1
  65. package/dist/code.d.ts +1 -1
  66. package/dist/code.js +1 -1
  67. package/dist/code.js.map +1 -1
  68. package/dist/color.cjs +2 -2
  69. package/dist/color.d.cts +1 -1
  70. package/dist/color.d.ts +1 -1
  71. package/dist/color.js +2 -2
  72. package/dist/core.cjs +5 -5
  73. package/dist/core.d.cts +5 -5
  74. package/dist/core.d.ts +5 -5
  75. package/dist/core.js +5 -5
  76. package/dist/email.cjs +1 -1
  77. package/dist/email.cjs.map +1 -1
  78. package/dist/email.d.cts +1 -1
  79. package/dist/email.d.ts +1 -1
  80. package/dist/email.js +1 -1
  81. package/dist/email.js.map +1 -1
  82. package/dist/files.cjs +1 -1
  83. package/dist/files.cjs.map +1 -1
  84. package/dist/files.d.cts +3 -59
  85. package/dist/files.d.ts +3 -59
  86. package/dist/files.js +1 -1
  87. package/dist/files.js.map +1 -1
  88. package/dist/image.cjs +2 -2
  89. package/dist/image.cjs.map +1 -1
  90. package/dist/image.js +2 -2
  91. package/dist/image.js.map +1 -1
  92. package/dist/index.cjs +7 -7
  93. package/dist/index.cjs.map +1 -1
  94. package/dist/index.d.cts +43 -19
  95. package/dist/index.d.ts +43 -19
  96. package/dist/index.js +7 -7
  97. package/dist/index.js.map +1 -1
  98. package/dist/link.cjs +3 -3
  99. package/dist/link.d.cts +1 -1
  100. package/dist/link.d.ts +1 -1
  101. package/dist/link.js +3 -3
  102. package/dist/markdown.cjs +1 -1
  103. package/dist/markdown.cjs.map +1 -1
  104. package/dist/markdown.js +1 -1
  105. package/dist/markdown.js.map +1 -1
  106. package/dist/number.cjs +1 -1
  107. package/dist/number.d.cts +1 -1
  108. package/dist/number.d.ts +1 -1
  109. package/dist/number.js +1 -1
  110. package/dist/otp.cjs +1 -1
  111. package/dist/otp.js +1 -1
  112. package/dist/rich.cjs +3 -3
  113. package/dist/rich.cjs.map +1 -1
  114. package/dist/rich.d.cts +2 -2
  115. package/dist/rich.d.ts +2 -2
  116. package/dist/rich.js +3 -3
  117. package/dist/rich.js.map +1 -1
  118. package/dist/secrets.cjs +1 -1
  119. package/dist/secrets.cjs.map +1 -1
  120. package/dist/secrets.d.cts +1 -1
  121. package/dist/secrets.d.ts +1 -1
  122. package/dist/secrets.js +1 -1
  123. package/dist/secrets.js.map +1 -1
  124. package/dist/share.cjs +1 -1
  125. package/dist/share.d.cts +1 -1
  126. package/dist/share.d.ts +1 -1
  127. package/dist/share.js +1 -1
  128. package/dist/structured.cjs +2 -2
  129. package/dist/structured.cjs.map +1 -1
  130. package/dist/structured.js +2 -2
  131. package/dist/structured.js.map +1 -1
  132. package/dist/table.cjs +1 -1
  133. package/dist/table.cjs.map +1 -1
  134. package/dist/table.d.cts +1 -1
  135. package/dist/table.d.ts +1 -1
  136. package/dist/table.js +1 -1
  137. package/dist/table.js.map +1 -1
  138. package/dist/testing.cjs +2 -2
  139. package/dist/testing.d.cts +3 -3
  140. package/dist/testing.d.ts +3 -3
  141. package/dist/testing.js +2 -2
  142. package/package.json +6 -4
  143. package/dist/chunks/errors-9h8sdFFX.js.map +0 -1
  144. package/dist/chunks/errors-BwOF6T_M.cjs.map +0 -1
  145. package/dist/chunks/field-BHo5y-t_.js.map +0 -1
  146. package/dist/chunks/field-Bytz2WfN.cjs.map +0 -1
  147. package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +0 -1
  148. package/dist/chunks/paste-reader-D9i7yMXF.js.map +0 -1
package/README.md CHANGED
@@ -8,13 +8,14 @@
8
8
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
9
9
  [![React 18+](https://img.shields.io/badge/React-18%2B-61dafb)](https://react.dev)
10
10
  [![TypeScript](https://img.shields.io/badge/TypeScript-strict-3178c6)](https://www.typescriptlang.org)
11
- [![GitHub stars](https://img.shields.io/github/stars/suprabhat02/react-smart-copy?style=social)](https://github.com/suprabhat02/react-smart-copy)
12
11
 
13
- **[Live demo and docs](https://suprabhat02.github.io/react-smart-copy/)**
12
+ **[Documentation and live demos](https://suprabhat02.github.io/react-smart-copy/)**
14
13
 
15
14
  Headless, type-safe **clipboard interactions** for React. Not just a clipboard call: the
16
- whole interaction around it — copying, copied, failed, retry, pasting — with honest errors,
17
- hover/focus/touch reveal, and screen-reader announcements built in.
15
+ whole interaction around it (copying, copied, failed, retry, pasting) with honest errors,
16
+ hover, focus and touch reveal, and screen-reader announcements built in. Around that core,
17
+ opt-in modules handle what people actually copy and paste: spreadsheet ranges, code, rich
18
+ text, images, files, secrets, one-time codes, amounts, e-mail recipients, links and colours.
18
19
 
19
20
  ```
20
21
  Email shubh@example.com [Copy] → Copied ✓
@@ -22,56 +23,16 @@ Phone +91 98xxx xxxxx [Copy]
22
23
  ID PLT-29018 [Copy]
23
24
  ```
24
25
 
25
- - **~3.5 kB** for `useCopy`, **~5.6 kB** for everything copy (min + brotli), zero runtime dependencies
26
- - Copy text, rich HTML (with plain-text fallback), PNG images, JSON, multi-format
27
- - **Paste** text, HTML and screenshots with `usePaste`: a Paste button or Ctrl/⌘+V, no permission prompt for keyboard paste
28
- - **`<CopyGroup>`**: only one row shows "Copied" at a time
29
- - **`useCopyInterceptor`**: control what Ctrl/⌘+C copies from your page — attribution, redaction, Excel-ready tables, no-copy zones
30
- - **`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>`
31
- - **`react-smart-copy/structured`**: copy your own objects and paste them back as the same typed, validated objects in another tab or app, the way design tools do. Versioned, with migrations, and works with Zod, Valibot or ArkType
32
- - **`react-smart-copy/markdown`**: paste from Google Docs, Word, Notion or any web page into a Markdown field and get clean Markdown, with undo intact: `<textarea onPaste={pasteAsMarkdown} />`
33
- - **`react-smart-copy/code`**: copy code blocks the way developers expect (a terminal session copies as its commands, gutters and prompts stay behind, colours survive in Docs and Slack), paste code cleaned and indented, and catch Trojan Source, invisible identifiers and lookalike letters
34
- - **`react-smart-copy/image`**: get pasted photos and screenshots ready to upload. It removes GPS location, camera data and hidden thumbnails without touching a pixel, and fits size and byte limits, re-encoding only when it has to
35
- - **`react-smart-copy/files`**: take pasted and dropped files and whole folders safely. Types come from each file's content, so a program named `invoice.pdf.exe` or a web page named `report.pdf` is turned away with a reason, names are made safe for every operating system, and limits cap count, size and depth
36
- - **`react-smart-copy/secrets`**: keep API keys, tokens, private keys, passwords, card numbers and IBANs out of pastes and copies. Paste guards for chat boxes and forms, and redaction of what people copy from logs and consoles. Every pattern runs in linear time, and no finding holds the secret
37
- - **`react-smart-copy/otp`** and **`useOtpField`**: one-time code fields that typing, pasting a whole SMS, SMS autofill and WebOTP fill, with an accessible name on every box, and `extractOtp` to read the code in a message while leaving prices, dates, phone numbers and order numbers alone
38
- - **`react-smart-copy/number`**: read the numbers and amounts people paste, in any locale's format (`1.234,50 €`, `$1,234.50`, `(1,234.00)`, lakh grouping, any script's digits), exactly, as a decimal string as well as a `number`. Paste them into number fields with `pasteAsNumber`, and write them back for any locale with `formatNumber`
39
- - **`react-smart-copy/email`**: read the lists of recipients people paste from Outlook, Gmail, Apple Mail and spreadsheets, names and all (even Outlook's unquoted `Lima, Ana <ana@example.com>`), into checked addresses. Duplicates are dropped, lookalike domains flagged, hidden characters caught, and lists copied back so they paste into any To field
40
- - **`react-smart-copy/link`**: "Copy link" buttons that paste as a titled link in Slack, Docs and Notion and as the URL in editors, links that scroll to a highlighted passage, tracking parameters removed, and pasting a URL over selected text to make a link
41
- - **`react-smart-copy/rich`**: copy styled content so it pastes as it looks in Gmail, Outlook, Apple Mail, Google Docs, Word, Notion and Slack: sanitized HTML with inline styles, email-safe colours and absolute links, plus readable plain text. Works for buttons and for Ctrl/⌘+C. And the other way: paste from Docs, Word and mail into a rich-text editor (TipTap, Lexical, `contenteditable`) as clean, semantic HTML
42
- - **`react-smart-copy/color`**: copy colours in any CSS format (hex to `oklch()` and Display P3) with a swatch for Docs and Slack, paste any format into a colour field, and check WCAG contrast. Wide-gamut colours are mapped the way CSS specifies, never clipped to a wrong hue
43
- - **`react-smart-copy/share`**: one "Share" button that opens the share sheet on phones and copies a titled link on desktop, with honest states: a closed share sheet is never an error
44
- - **`react-smart-copy/capture`**: copy an `<svg>` or any piece of your UI as a PNG
45
- - Every failure is a typed, classified error. Nothing silently no-ops
46
- - Unstyled. Works with Tailwind, CSS modules, CSS-in-JS, shadcn, MUI, Ant Design
47
- - SSR / Next.js App Router safe, React 18 and 19, StrictMode-proof
48
- - Tested in real browser engines on every change: Chromium, Firefox and WebKit (Safari's engine)
49
-
50
- ## What it can and cannot copy
51
-
52
- This package only promises what browsers actually support.
53
-
54
- | Content | Supported | Notes |
55
- | -------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
56
- | Plain text | ✅ | Everywhere with the async Clipboard API |
57
- | Rich HTML | ✅ | Always paired with a required plain-text fallback. Degrades to text when `ClipboardItem` is missing |
58
- | Images | ✅ PNG only | `image/png` is the only format with reliable cross-browser write support. Convert with `canvas.toBlob(cb, 'image/png')` |
59
- | JSON | ✅ | Serialised to text. JSON is not a native clipboard format |
60
- | Tables (Excel, Sheets, Docs) | ✅ | `react-smart-copy/table`: an HTML table plus tab-separated text in one entry. Pasting reads both back |
61
- | Several formats at once | ✅ | `kind: 'multi'`; each MIME type is checked with `ClipboardItem.supports()` first |
62
- | Your app's own data (typed) | ✅ | `react-smart-copy/structured`: a web custom format, a custom type and an HTML envelope, so every browser and paste path gets one |
63
- | Rich text as Markdown | ✅ paste | `react-smart-copy/markdown`: CommonMark + GFM from Docs, Word, web pages and mail; plain-text pastes stay untouched |
64
- | Code (blocks, sessions, diffs) | ✅ | `react-smart-copy/code`: plain text plus monospaced, highlighted HTML; commands without prompts or output; Trojan Source checks on paste |
65
- | Pasted images, made safe | ✅ paste | `react-smart-copy/image`: removes location and camera metadata losslessly; resizes and compresses under a byte budget |
66
- | Links (titled, to a passage) | ✅ | `react-smart-copy/link`: a titled `<a>` plus the URL; `text/uri-list` when dragged; text fragment links; never `javascript:` |
67
- | Styled content, portable | ✅ | `react-smart-copy/rich`: sanitized HTML with inline styles and email-safe colours, plus plain text; for buttons and Ctrl/⌘+C |
68
- | Rich text pasted into an editor | ✅ | `react-smart-copy/rich`: Docs, Word and mail into TipTap, Lexical or `contenteditable` as clean, semantic HTML |
69
- | Colours (every CSS format) | ✅ | `react-smart-copy/color`: the value as text, plus a swatch for rich-text apps; any CSS colour read back on paste |
70
- | Share sheet (Web Share API) | ✅ with copy fallback | `react-smart-copy/share`: the share sheet on phones and tablets, a titled link copied elsewhere; files where the share sheet takes them |
71
- | SVG (icons, charts, logos) | ✅ as PNG | `svgToPngBlob()` from `react-smart-copy/capture` rasterises natively, no dependency. Raw SVG is not a clipboard image format |
72
- | 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 |
73
- | Files (PDF, DOCX, ZIP) | ❌ | Not writable to the system clipboard by any browser API |
74
- | Anything over plain HTTP | ❌ | The Clipboard API requires HTTPS or `localhost`. You get an `insecure-context` error, not a silent failure |
26
+ - **Small.** About 3.4 kB for `useCopy` (min + brotli), zero runtime dependencies, and every
27
+ module is a separate entry point that shares one copy of the core.
28
+ - **Honest.** Every failure is a typed, classified error. Nothing silently does nothing.
29
+ - **Accessible.** Real buttons, accessible names, polite announcements, reduced motion, and
30
+ everything the docs render checked with axe in real browsers.
31
+ - **Unstyled.** Works with Tailwind, CSS modules, CSS-in-JS, shadcn, MUI and Ant Design.
32
+ - **Safe on servers.** SSR and Next.js App Router safe, React 18 and 19, StrictMode-proof.
33
+ - **Safe with hostile input.** Every parser caps its input and runs in linear time.
34
+ - **Tested in real engines.** Chromium, Firefox and WebKit on every change, 100% test
35
+ coverage, and property tests for every parser and serialiser.
75
36
 
76
37
  ## Install
77
38
 
@@ -79,78 +40,42 @@ This package only promises what browsers actually support.
79
40
  npm install react-smart-copy
80
41
  ```
81
42
 
82
- Works with React 18 and 19 and TypeScript 5.0 or later (the published types are checked on 5.0, 6 and 7 in CI).
83
- React is an optional peer: every entry point except the main one runs without it, in browsers and in Node.js 18 or later.
43
+ Works with React 18 and 19 and TypeScript 5.0 or later (the published types are checked on
44
+ 5.0, 6 and 7 in CI). React is an optional peer: every entry point except the main one runs
45
+ without it, in browsers and in Node.js 18 or later.
84
46
 
85
47
  ## Quick start
86
48
 
49
+ A copy button, with everything around it:
50
+
87
51
  ```tsx
88
52
  import { CopyField } from "react-smart-copy";
89
53
 
90
54
  export function ContactRow() {
91
55
  return (
92
- <CopyField.Root
93
- value="shubh@example.com"
94
- label="Email"
95
- className="group flex items-center gap-3"
96
- >
56
+ <CopyField.Root value="shubh@example.com" label="Email" className="group flex items-center gap-3">
97
57
  <CopyField.Label className="w-20 text-sm text-gray-500" />
98
58
  <CopyField.Value className="font-mono" />
99
- <CopyField.Trigger className="opacity-0 transition-opacity group-data-[revealed]:opacity-100 focus-visible:opacity-100 motion-reduce:transition-none">
100
- {({ displayStatus }) =>
101
- displayStatus === "copied"
102
- ? "Copied ✓"
103
- : displayStatus === "error"
104
- ? "Retry"
105
- : "Copy"
106
- }
59
+ <CopyField.Trigger className="opacity-0 group-data-[revealed]:opacity-100 focus-visible:opacity-100">
60
+ {({ displayStatus }) => (displayStatus === "copied" ? "Copied ✓" : displayStatus === "error" ? "Retry" : "Copy")}
107
61
  </CopyField.Trigger>
108
62
  </CopyField.Root>
109
63
  );
110
64
  }
111
65
  ```
112
66
 
113
- That one component gives you: a real `<button type="button">` named "Copy Email", reveal on
114
- mouse hover, keyboard focus and touch (always visible on devices that can't hover), a
115
- polite "Copied to clipboard" announcement for screen readers, ignored double-clicks, and
116
- automatic return to idle after 2 seconds.
117
-
118
- ## No flicker
119
-
120
- A text copy takes 1–5 ms, so rendering the raw state flashes "Copying…" for one frame and
121
- resizes the button. Two statuses solve this:
67
+ That one component gives you a real `<button type="button">` named "Copy Email". It is
68
+ revealed on mouse hover, keyboard focus and touch, and always visible on devices that can't
69
+ hover. It announces "Copied to clipboard" politely to screen readers, ignores double-clicks,
70
+ and returns to idle after 2 seconds.
122
71
 
123
- - `status` / `data-state`: the real, instantaneous state. Use it for logic and tests.
124
- - `displayStatus` / `data-display-state`: what to render. "Copying…" only appears when a
125
- copy takes longer than `pendingDelayMs` (150 ms), then stays at least `minPendingMs`
126
- (400 ms) so it can't blink.
127
-
128
- The default trigger label also stacks every state in one grid cell, so its width never
129
- changes, and crossfades between them (off under `prefers-reduced-motion`).
130
-
131
- ```tsx
132
- <CopyField.Root
133
- value={big}
134
- label="Report"
135
- pendingDelayMs={200}
136
- minPendingMs={500}
137
- >
138
- …
139
- </CopyField.Root>;
140
-
141
- // With the bare hook:
142
- const { status } = useCopy();
143
- const shown = useDisplayStatus(status);
144
- ```
145
-
146
- ## Just the hook
72
+ Just the hook:
147
73
 
148
74
  ```tsx
149
75
  import { useCopy } from "react-smart-copy";
150
76
 
151
77
  function InvoiceNumber({ id }: { id: string }) {
152
78
  const { copy, status, error } = useCopy({ resetAfterMs: 1500 });
153
-
154
79
  return (
155
80
  <button type="button" onClick={() => void copy(id)} data-state={status}>
156
81
  {status === "copied" ? "Copied" : "Copy"}
@@ -160,1787 +85,158 @@ function InvoiceNumber({ id }: { id: string }) {
160
85
  }
161
86
  ```
162
87
 
163
- `copy()` never rejects. It resolves to a `CopyOutcome` you can branch on:
164
-
165
- ```ts
166
- const outcome = await copy(id);
167
- if (outcome.status === "error") track("copy_failed", outcome.error.type);
168
- ```
169
-
170
- ## Payloads
171
-
172
- A bare string is shorthand for text. Everything else is a discriminated union, so the
173
- compiler stops you from, say, copying HTML without a plain-text fallback.
174
-
175
- ```ts
176
- copy("PLT-29018");
177
- copy({
178
- kind: "html",
179
- html: "<b>INV-29018</b> · ₹12,400",
180
- text: "INV-29018 · ₹12,400",
181
- });
182
- copy({ kind: "json", value: row, pretty: true });
183
- copy({ kind: "image", blob: () => chartToPngBlob() });
184
- copy({
185
- kind: "multi",
186
- items: [
187
- { mimeType: "text/plain", data: "INV-29018" },
188
- { mimeType: "text/html", data: "<b>INV-29018</b>" },
189
- ],
190
- });
191
- copy(() => editor.getValue()); // resolved at click time, always the latest value
192
- ```
193
-
194
- A `multi` item can be marked `optional: true`: it is written only when `ClipboardItem.supports()`
195
- confirms its type, and skipped otherwise instead of failing the copy. That is how a web custom
196
- format (`"web application/vnd.acme.rows+json"`, Chromium) rides along with HTML and text that
197
- every browser writes. Copy and drag events skip web custom formats, which only the async
198
- Clipboard API can write.
199
-
200
- ### Copying an image, including a piece of your UI
201
-
202
- Pass a **function** that produces the Blob. It is called synchronously inside the click,
203
- and its promise is handed straight to `ClipboardItem`, which is what Safari needs to allow
204
- asynchronous image generation. The `react-smart-copy/capture` entry does this for you.
205
-
206
- ## Copying SVG and UI as images
207
-
208
- `react-smart-copy/capture` is a separate, opt-in entry (~3.3 kB, no dependencies). It never
209
- ships in your bundle unless you import it.
210
-
211
- ```tsx
212
- import { captureImage, svgToPngBlob } from "react-smart-copy/capture";
213
- import { domToBlob } from "modern-screenshot"; // any rasteriser you like, for HTML
214
-
215
- // Any <svg> (chart, logo, icon): rasterised natively, no rasteriser needed.
216
- <CopyField.Root label="Chart" value={captureImage(() => chartRef.current)}>
217
- <CopyField.Trigger>Copy chart</CopyField.Trigger>
218
- </CopyField.Root>;
219
-
220
- // Any HTML element (invoice card, receipt): bring the rasteriser.
221
- <CopyField.Root
222
- label="Invoice"
223
- value={captureImage(() => invoiceRef.current, {
224
- rasterize: (node, { scale }) => domToBlob(node, { scale }),
225
- background: "#ffffff",
226
- })}
227
- >
228
- <CopyField.Trigger>Copy as image</CopyField.Trigger>
229
- </CopyField.Root>;
230
-
231
- // Or by hand, e.g. from SVG markup:
232
- const png = await svgToPngBlob('<svg viewBox="0 0 24 24">…</svg>', { width: 256 });
233
- ```
234
-
235
- What you get beyond calling a rasteriser yourself:
236
-
237
- - **Always a real PNG.** Output is verified from its bytes; JPEG/WebP/canvas/data-URL outputs are re-encoded, anything else is refused
238
- - **Size limits.** `maxPixels` (default 4096 × 4096, Safari's canvas limit) is checked _before_ rendering and again on the output; SVG markup is capped at `maxLength`
239
- - **Deadlines.** `timeoutMs` (default 15 s) and an optional `signal: AbortSignal`; the rasteriser receives a signal it can honour
240
- - **Safe SVG handling.** SVG is decoded as an image, where browsers disable scripts and external loads, and it is never inserted into your page. Network URLs from a rasteriser are never fetched
241
- - **Crisp by default.** `scale: 2`; pass `window.devicePixelRatio` or anything up to 10
242
-
243
- Failures are classified like everything else: `invalid-payload` (no element / unknown size),
244
- `unsupported`, `too-large`, `timeout`, `aborted`, `blob-generation-failed`. Rasterisers have
245
- real limits (cross-origin images taint the canvas, web fonts must be loaded, `<video>` and
246
- `<iframe>` rarely render), so offer a text fallback when capture fails.
247
-
248
- ## Controlling native copy (Ctrl/⌘+C)
249
-
250
- Everything above copies from a button. `useCopyInterceptor` handles the other way people
251
- copy: selecting text and pressing Ctrl/⌘+C, Ctrl/⌘+X or using the context menu. Inside the
252
- element you attach it to, you decide what reaches the clipboard.
253
-
254
- ```tsx
255
- import { useCopyInterceptor } from "react-smart-copy";
256
-
257
- function Article({ children }: { children: React.ReactNode }) {
258
- const { ref } = useCopyInterceptor<HTMLElement>({
259
- transform: ({ text }) => `${text}\n\nSource: ${location.href}`,
260
- });
261
- return <article ref={ref}>{children}</article>;
262
- }
263
- ```
264
-
265
- The transform receives the selection (`text`, `html`, a detached `fragment` you may
266
- mutate, the `field` for inputs, and whether it was a `copy` or `cut`) and returns:
267
-
268
- | Return | Effect |
269
- | ---------------------------------------- | -------------------------------------------------------------- |
270
- | a string or a text/HTML/JSON/multi payload | written instead of the selection |
271
- | `false` | nothing is copied; a blocked cut deletes nothing |
272
- | `null` / `undefined` | the browser's normal copy, untouched |
273
-
274
- It writes through the copy event itself, so there is no permission prompt, it works over
275
- plain HTTP, and in every browser. The trade-off: only strings can be written, so the types
276
- reject image payloads and `async` transforms (the clipboard closes when the event returns).
277
- Use `useCopy` for images.
278
-
279
- **Redaction.** Mutate the fragment and return HTML with a text fallback:
280
-
281
- ```tsx
282
- const { ref } = useCopyInterceptor<HTMLDivElement>({
283
- priority: 10, // see "Overlapping scopes"
284
- transform: ({ fragment, text }) => {
285
- if (!fragment) return text.replace(/sk-live-\w+/g, "••••"); // inside an <input>
286
- fragment.querySelectorAll("[data-redact]").forEach((node) => (node.textContent = "••••"));
287
- const box = document.createElement("div");
288
- box.append(fragment);
289
- return { kind: "html", html: box.innerHTML, text: box.textContent };
290
- },
291
- });
292
- ```
293
-
294
- **Tables to Excel.** Return a `multi` payload with tab-separated `text/plain` and an HTML
295
- `<table>`; spreadsheets paste either into cells.
296
-
297
- **Cuts** in inputs and `contenteditable` still remove the selection after your content is
298
- written, through the browser's own editing path: undo works and React sees an `input` event.
299
- `outcome.deleted` tells you whether that happened.
300
-
301
- **Failures fail closed.** If the transform throws or returns something unwritable, nothing
302
- is copied and `onError` fires. That is the safe default for redaction; pass
303
- `failureMode: "native"` to let the original copy through instead (e.g. for attribution).
304
-
305
- **Overlapping scopes.** One selection can touch several intercepted elements. Exactly one
306
- handles it: the highest `priority`, then the innermost, then the first in the document. The
307
- winner receives the whole selection, so give redaction scopes a higher priority than
308
- attribution scopes and copying across both is still masked. A React `onCopy` handler that
309
- calls `preventDefault()` always wins.
310
-
311
- Other options: `events` (`["copy"]`, `["cut"]` or both, the default), `enabled`, and
312
- `onIntercept(outcome)` for telemetry. Without React, call `registerCopyInterceptor(element,
313
- options)` from `react-smart-copy/core`; it returns an unsubscribe function. For a single
314
- element's own `onCopy` handler, `interceptCopyEvent(event, { transform })` applies a
315
- transform to one event.
316
-
317
- > This guards against accidents, not adversaries. Anyone can still screenshot, open dev
318
- > tools or disable JavaScript. Never send data to the page that the user must not see.
319
-
320
- ## Drag-to-copy
321
-
322
- `useDragCopy` makes any element draggable and populates its `DataTransfer` with structured
323
- data when the user starts dragging it. No Clipboard API, no permission prompt — it works
324
- in every browser that supports HTML5 drag-and-drop.
88
+ `copy()` never rejects: it resolves to an outcome you can branch on. Pasting is the other
89
+ half, with the same honest states, from a button, Ctrl/⌘+V, or a drop:
325
90
 
326
91
  ```tsx
327
- import { useDragCopy } from "react-smart-copy";
328
- import { linkPayload } from "react-smart-copy/link";
92
+ import { describePasteError, usePaste } from "react-smart-copy";
329
93
 
330
- function DraggableCard({ title, url }: { title: string; url: string }) {
331
- const { ref, status } = useDragCopy({
332
- // Escaped, scheme-checked, and with text/uri-list so it drops into the address bar too.
333
- source: () => linkPayload({ url, title }, { target: "drag" }),
334
- effectAllowed: "copy",
94
+ function AvatarDrop() {
95
+ const { paste, state, targetProps, dropTargetProps } = usePaste<HTMLDivElement>({
96
+ accept: ["image"],
97
+ onPaste: (result) => void upload(result.images[0]),
335
98
  });
336
99
  return (
337
- <div ref={ref} style={{ opacity: status === "dragging" ? 0.5 : 1 }}>
338
- {title}
100
+ <div {...targetProps} {...dropTargetProps} tabIndex={0}>
101
+ Drop an image, press Ctrl/⌘+V, or <button onClick={() => void paste()}>Paste</button>
102
+ {state.status === "error" && <p role="alert">{describePasteError(state.error, state.source)}</p>}
339
103
  </div>
340
104
  );
341
105
  }
342
106
  ```
343
107
 
344
- The `source` callback is called synchronously on `dragstart` and must return synchronously
345
- (the `DataTransfer` closes when the event handler returns). Return:
346
-
347
- | Return value | Effect |
348
- | ------------------------------------ | --------------------------------------------------- |
349
- | a string | written as `text/plain` |
350
- | a text / HTML / JSON / multi payload | written according to its `kind` |
351
- | `false` | `preventDefault()` is called; the drag is cancelled |
352
- | `null` / `undefined` | the browser's default drag data, untouched |
353
-
354
- The same payload shapes as `useCopy` are accepted (`kind: "text"`, `kind: "html"`,
355
- `kind: "json"`, `kind: "multi"`), minus images — `DataTransfer` accepts strings only.
356
-
357
- ```tsx
358
- // Plain text
359
- source: () => `${title}\n${url}`
360
-
361
- // HTML + text fallback (e.g. for dropping into a rich-text editor)
362
- source: () => ({ kind: "html", html: `<b>${title}</b>`, text: title })
363
-
364
- // JSON (serialised as text/plain)
365
- source: () => ({ kind: "json", value: { id, title }, pretty: true })
366
-
367
- // Multiple MIME types (e.g. custom application type for your own drop targets)
368
- source: () => ({
369
- kind: "multi",
370
- items: [
371
- { mimeType: "text/plain", data: title },
372
- { mimeType: "application/x-my-id", data: String(id) },
373
- ],
374
- })
375
- ```
376
-
377
- **`effectAllowed`** controls the drag cursor and the effects drop targets may request.
378
- Defaults to `"copy"`; pass `"move"` to signal that the source will be removed after a
379
- successful drop (your app must do the actual removal in `dragend` or on the server).
380
-
381
- **Always-fresh source.** The `source` callback reads the latest props and state on every
382
- drag. You never need to list it in a dependency array or wrap it in a ref yourself.
383
-
384
- **`enabled`** removes `draggable` and the listener without unmounting the component.
385
- Status resets to `idle` while disabled.
386
-
387
- ```tsx
388
- const { ref, status, outcome } = useDragCopy({
389
- source: () => text,
390
- enabled: !isLocked,
391
- effectAllowed: "copyMove",
392
- onDrag: (state) => {
393
- if (state.status === "done") analytics.track("drag_complete");
394
- },
395
- onError: (err) => console.error("drag source failed", err),
396
- });
397
- ```
398
-
399
- | Return value | Type | Description |
400
- | ------------ | ----------------------------- | -------------------------------------------------- |
401
- | `ref` | `RefCallback<T>` | Attach to the element you want to make draggable |
402
- | `status` | `'idle' \| 'dragging' \| 'done'` | Current drag state |
403
- | `outcome` | `DragCopyOutcome \| null` | Result of the last `dragstart`; `null` before any drag |
404
- | `onDragStart`| `(event) => void` | For wiring via React's `onDragStart` prop if needed |
405
-
406
- **`onDragStart` prop path.** The hook attaches its own native listener through `ref`, so you
407
- rarely need `onDragStart`. It is there for render-prop components or controlled drag
408
- libraries that require a React prop:
108
+ More in the docs: [`useCopy`](https://suprabhat02.github.io/react-smart-copy/copy/use-copy/),
109
+ [`CopyField`](https://suprabhat02.github.io/react-smart-copy/copy/copy-field/),
110
+ [payloads](https://suprabhat02.github.io/react-smart-copy/copy/payloads/),
111
+ [native Ctrl/⌘+C](https://suprabhat02.github.io/react-smart-copy/copy/native-copy/),
112
+ [drag to copy](https://suprabhat02.github.io/react-smart-copy/copy/drag-to-copy/),
113
+ [`usePaste`](https://suprabhat02.github.io/react-smart-copy/paste/use-paste/) and
114
+ [`PasteField`](https://suprabhat02.github.io/react-smart-copy/paste/paste-field/).
409
115
 
410
- ```tsx
411
- const { ref, onDragStart } = useDragCopy({ source: () => "data" });
412
- return (
413
- <SortableItem
414
- ref={ref}
415
- onDragStart={(e) =>
416
- onDragStart({
417
- type: "dragstart",
418
- dataTransfer: e.dataTransfer,
419
- defaultPrevented: e.defaultPrevented,
420
- preventDefault: () => e.preventDefault(),
421
- })
422
- }
423
- />
424
- );
425
- ```
426
-
427
- **SSR-safe.** `draggable` is never set during server rendering; the ref callback runs only
428
- in the browser.
429
-
430
- **Without React.** `applyDragCopy` and `registerDragCopy` are exported from
431
- `react-smart-copy/core` for framework-agnostic use:
116
+ ## What it can and cannot copy
432
117
 
433
- ```ts
434
- import { registerDragCopy } from "react-smart-copy/core";
118
+ This package only promises what browsers actually support.
435
119
 
436
- const { unsubscribe } = registerDragCopy(element, () => ({
437
- source: () => `${title}\n${url}`,
438
- effectAllowed: "copy",
439
- }));
440
- // later: unsubscribe();
441
- ```
120
+ | Content | Supported | Notes |
121
+ | --- | --- | --- |
122
+ | Plain text | ✅ | Everywhere with the async Clipboard API |
123
+ | Rich HTML | ✅ | Always with a plain-text fallback; degrades to text without `ClipboardItem` |
124
+ | Images | ✅ PNG only | `image/png` is the only format with reliable cross-browser write support |
125
+ | JSON, your own typed data | ✅ | As text, or as a web custom format with `react-smart-copy/structured` |
126
+ | Several formats at once | ✅ | `kind: 'multi'`; each type is checked with `ClipboardItem.supports()` first |
127
+ | SVG and UI | ✅ as PNG | `react-smart-copy/capture`; for HTML elements, bring a rasteriser |
128
+ | Files (PDF, DOCX, ZIP) | ❌ | Not writable to the system clipboard by any browser API |
129
+ | Anything over plain HTTP | ❌ | The Clipboard API needs HTTPS or `localhost`: you get an `insecure-context` error |
442
130
 
443
- > **Drag vs. copy.** `useCopy` writes to the clipboard when the user clicks a button.
444
- > `useDragCopy` writes to the `DataTransfer` when the user drags an element. Use them
445
- > together if your UI supports both flows.
131
+ ## Modules
446
132
 
447
- ## Tables: Excel, Google Sheets, AG Grid, TanStack
133
+ Import only what you use. Each entry point is separate, and they share one copy of the core.
134
+ Sizes are minified and brotli-compressed, for everything the entry point exports.
448
135
 
449
- `react-smart-copy/table` copies rows so they land as cells in Excel, Google Sheets, Numbers
450
- and LibreOffice, and as a real table in Docs, Word, Notion and mail. It also reads ranges
451
- pasted from those apps back into rows and typed records. It has no dependencies, works
452
- without React, and tree-shakes to what you use (about 1.9 kB for copying).
136
+ | Entry point | What it is for | Size |
137
+ | --- | --- | --- |
138
+ | [`react-smart-copy`](https://suprabhat02.github.io/react-smart-copy/start/introduction/) | React hooks and components: `useCopy`, `usePaste`, `CopyField`, `PasteField`, `CopyGroup`, `useCopyInterceptor`, `useDragCopy`, `useShare`, `useOtpField` | from 3.4 kB |
139
+ | [`/core`](https://suprabhat02.github.io/react-smart-copy/guides/without-react/) | The framework-agnostic machines and adapters | 8.3 kB |
140
+ | [`/capture`](https://suprabhat02.github.io/react-smart-copy/copy/capture/) | Copy an `<svg>` or a piece of your UI as a PNG | 3.4 kB |
141
+ | [`/table`](https://suprabhat02.github.io/react-smart-copy/modules/tables/) | Ranges that paste into Excel and Google Sheets as cells, and back as typed records | 5.6 kB |
142
+ | [`/structured`](https://suprabhat02.github.io/react-smart-copy/modules/structured/) | Your own typed, versioned, validated objects on the clipboard | 3.5 kB |
143
+ | [`/markdown`](https://suprabhat02.github.io/react-smart-copy/modules/markdown/) | Paste from Docs, Word and web pages as clean Markdown | 7.7 kB |
144
+ | [`/code`](https://suprabhat02.github.io/react-smart-copy/modules/code/) | Code blocks and sessions copied cleanly; Trojan Source and lookalike checks | 7.5 kB |
145
+ | [`/image`](https://suprabhat02.github.io/react-smart-copy/modules/images/) | Pasted photos without location or camera data, within size limits | 7.3 kB |
146
+ | [`/files`](https://suprabhat02.github.io/react-smart-copy/modules/files/) | Pasted and dropped files and folders, typed by content, with safe names | 7.0 kB |
147
+ | [`/secrets`](https://suprabhat02.github.io/react-smart-copy/modules/secrets/) | Keys, tokens, passwords, cards and IBANs kept out of pastes and copies | 4.1 kB |
148
+ | [`/otp`](https://suprabhat02.github.io/react-smart-copy/modules/otp/) | One-time codes from pasted messages, SMS autofill and WebOTP | 3.6 kB |
149
+ | [`/number`](https://suprabhat02.github.io/react-smart-copy/modules/numbers/) | Numbers and amounts in any locale's format, read and written exactly | 3.5 kB |
150
+ | [`/email`](https://suprabhat02.github.io/react-smart-copy/modules/email/) | Lists of e-mail recipients from Outlook, Gmail and spreadsheets, checked | 2.8 kB |
151
+ | [`/link`](https://suprabhat02.github.io/react-smart-copy/modules/links/) | Links that paste titled, links to a passage, tracking removed | 4.1 kB |
152
+ | [`/rich`](https://suprabhat02.github.io/react-smart-copy/modules/rich-text/) | Styled content that pastes as it looks in mail and docs, and clean pastes into editors | 16.7 kB |
153
+ | [`/color`](https://suprabhat02.github.io/react-smart-copy/modules/colors/) | Colours in every CSS format, with gamut mapping and contrast | 6.6 kB |
154
+ | [`/share`](https://suprabhat02.github.io/react-smart-copy/modules/share/) | The share sheet on phones, a copied link everywhere else | 4.8 kB |
155
+ | [`/testing`](https://suprabhat02.github.io/react-smart-copy/guides/testing/) | Mock adapters and result builders for your tests | 0.7 kB |
156
+
157
+ A taste of each:
453
158
 
454
159
  ```tsx
455
- import { useCopy } from "react-smart-copy";
456
160
  import { fromRows, tablePayload } from "react-smart-copy/table";
457
-
458
- function CopyInvoices({ invoices }: { invoices: Invoice[] }) {
459
- const { copy, status } = useCopy();
460
- return (
461
- <button
462
- type="button"
463
- onClick={() =>
464
- void copy(() =>
465
- tablePayload(
466
- fromRows(invoices, [
467
- { header: "Invoice", value: "id" },
468
- { header: "Amount", value: "amount" }, // stays a number in Excel
469
- { header: "Due", value: (row) => row.due.toLocaleDateString() },
470
- ]),
471
- ),
472
- )
473
- }
474
- >
475
- {status === "copied" ? "Copied" : "Copy as table"}
476
- </button>
477
- );
478
- }
161
+ copy(() => tablePayload(fromRows(invoices, [{ header: "Invoice", value: "id" }, { header: "Amount", value: "amount" }])));
479
162
  ```
480
163
 
481
- `tablePayload` returns an ordinary `html` payload: an HTML `<table>` with tab-separated text
482
- as its fallback. That means it works everywhere a payload does: `copy()`, `useCopyInterceptor`
483
- transforms and `useDragCopy` sources. Where rich copy is unavailable, the plain-text fallback
484
- still pastes into cells.
485
-
486
- **What survives the trip.** Cells keep their types. Numbers, bigints, booleans and dates stay
487
- values the spreadsheet can calculate with, while strings are marked as text so Excel keeps
488
- `00123`, `1/2` and `1E5` as written (`preserveText`). Tabs, quotes and line breaks inside cells
489
- are quoted the way Excel quotes them. A one-column table ending in an empty cell keeps that
490
- row. Use `formatCell` for your own number or date formats.
491
-
492
- **Formula injection is off by default.** A text cell starting with `=`, `+`, `-`, `@`, a tab or
493
- a line break (or their full-width forms) would run as a formula when pasted. Following OWASP's
494
- CSV Injection guidance, such cells get a leading `'`, which spreadsheets read as "this is text".
495
- Typed numbers are never touched, so `-5` passed as a number stays a number. Rich editors show
496
- that apostrophe, so pass `formulaGuard: false` only for data you trust.
497
-
498
- ### From your grid
499
-
500
- ```tsx
501
- import { fromAgGrid, fromTanStackTable, fromTableElement } from "react-smart-copy/table";
502
-
503
- // AG Grid v31+ (Community or Enterprise): selected rows in on-screen order.
504
- copy(() => tablePayload(fromAgGrid(gridRef.current!.api, { rows: "selected" })));
505
-
506
- // TanStack Table v8 or v9, in any framework adapter, and libraries built on it
507
- // such as Material React Table and Mantine React Table.
508
- copy(() => tablePayload(fromTanStackTable(table, { rows: "selected" })));
509
-
510
- // Any library that renders a real <table>.
511
- copy(() => tablePayload(fromTableElement(containerRef.current!)));
512
- ```
513
-
514
- | Adapter | Rows | Columns and values |
515
- | ------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
516
- | `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 |
517
- | `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 |
518
- | `fromTableElement` | Every visible row of the first table | Merged cells, `<br>` line breaks, hidden rows and cells handled |
519
- | `fromRows` | Your objects | You choose: a property (type-checked to hold a cell) or a function |
520
-
521
- AG Grid ships clipboard support only in Enterprise. This gives Community grids Excel-ready
522
- copy; for Ctrl/⌘+C, call it from `onCellKeyDown`:
523
-
524
- ```tsx
525
- onCellKeyDown={(event) => {
526
- const key = event.event as KeyboardEvent | null;
527
- if (!key || !(key.ctrlKey || key.metaKey) || key.key.toLowerCase() !== "c") return;
528
- const selected = event.api.getSelectedNodes().length > 0;
529
- void copy(() => tablePayload(fromAgGrid(event.api, selected ? { rows: "selected" } : { rows: [event.node] })));
530
- }}
531
- ```
532
-
533
- ### Pasting a range from Excel or Google Sheets
534
-
535
- ```tsx
536
- import { usePaste } from "react-smart-copy";
537
- import { parseTable, toRecords } from "react-smart-copy/table";
538
-
539
- const { targetProps } = usePaste<HTMLDivElement>({
540
- accept: ["html", "text"], // the HTML flavour keeps merged cells and line breaks exact
541
- onPaste: (result) => {
542
- const table = parseTable(result, { headers: true });
543
- if (!table) return;
544
- const { records, missing, errors } = toRecords(table, {
545
- email: { header: ["Email", "E-mail"], required: true },
546
- seats: { header: "Seats", parse: (text) => Number.parseInt(text, 10) },
547
- });
548
- // records: { email: string | undefined; seats: number | undefined }[]
549
- },
550
- });
551
- ```
552
-
553
- `parseTable` reads the HTML flavour when it holds a table (Excel, Google Sheets, Word and web
554
- pages all write one) and falls back to tab-separated text, which is also what it uses on the
555
- server. Pasted HTML is parsed in an inert document: scripts never run and nothing is fetched.
556
- Every limit is explicit: `maxRows` (100,000), `maxColumns` (16,384, Excel's own), `maxCells`
557
- (1,000,000) and `maxLength` (32 MiB). Content beyond them sets `truncated: true` instead of
558
- being dropped silently, and merged cells are counted too, so a tiny document can't claim
559
- millions of cells. `toRecords` matches headers ignoring case, spacing and full-width forms,
560
- reports `missing` required columns and every cell whose `parse` threw, and never stops at the
561
- first bad row.
562
-
563
- ## Structured data: copy objects, paste typed objects
564
-
565
- `react-smart-copy/structured` puts your app's own data on the clipboard: invoice rows, a
566
- dashboard widget, a form's configuration, a set of shapes. Paste it in another tab, another
567
- window or another of your apps and you get the same typed objects back, validated against
568
- your schema. Text editors, chat and mail get readable text and HTML instead. No dependencies,
569
- about 1.9 kB for the copy side.
570
-
571
- ```tsx
572
- import { z } from "zod"; // or Valibot, ArkType, any Standard Schema, or a plain function
573
- import { useCopy, usePaste } from "react-smart-copy";
574
- import { clipAccept, clipPayload, defineClipFormat, readClip } from "react-smart-copy/structured";
575
-
576
- // Define each format once and share it between the copying and the pasting code.
577
- export const InvoiceRows = defineClipFormat({
578
- id: "acme.invoice-rows", // namespaced, stable: it names the clipboard type
579
- version: 2,
580
- schema: z.array(z.object({ id: z.string(), amount: z.number(), issued: z.coerce.date() })),
581
- migrate: { 1: (rows) => upgradeFromV1(rows) }, // data from older deployments still pastes
582
- text: (rows) => rows.map((row) => `${row.id}\t${row.amount}`).join("\n"),
583
- });
584
-
585
- function CopyRows({ rows }: { rows: Invoice[] }) {
586
- const { copy } = useCopy();
587
- return <button onClick={() => void copy(() => clipPayload(InvoiceRows, rows))}>Copy rows</button>;
588
- }
589
-
590
- function PasteRows({ onRows }: { onRows: (rows: Invoice[]) => void }) {
591
- const { paste, targetProps } = usePaste<HTMLDivElement>({
592
- accept: [...clipAccept(InvoiceRows), "text"],
593
- onPaste: async (result) => {
594
- const clip = await readClip(result, InvoiceRows);
595
- switch (clip.status) {
596
- case "ok": return onRows(clip.value); // typed, validated, migrated
597
- case "invalid": return report(clip.issues); // [{ message, path }]
598
- case "unsupported-version": return askToReload(); // written by a newer deployment
599
- case "absent": return; // not ours: handle result.text if you like
600
- }
601
- },
602
- });
603
- return <div {...targetProps} tabIndex={0}>Paste rows here <button onClick={() => void paste()}>Paste</button></div>;
604
- }
605
- ```
606
-
607
- `clipPayload` works everywhere a payload does: `copy()`, a `useCopyInterceptor` transform (so
608
- Ctrl/⌘+C on selected rows copies the objects) and a `useDragCopy` source. `readClip` reads from a
609
- `PasteResult` (paste button, Ctrl/⌘+V, drops, `PasteField`), a raw `DataTransfer` or a payload.
610
- Use `readClipSync` when you need the answer synchronously and your schema is synchronous.
611
-
612
- **Why three carriers.** No single clipboard entry survives every path in every browser, so each
613
- copy writes three and `readClip` takes the first that holds this format:
614
-
615
- | Carrier | Written by | Read back by |
616
- | ------- | ---------- | ------------ |
617
- | `web application/vnd.<id>+json` | `copy()` in Chromium | the paste button (`clipboard.read()`), also across origins. Hidden from paste events |
618
- | `application/vnd.<id>+json` | copy interceptor, drag | Ctrl/⌘+V and drops. Hidden from `clipboard.read()` |
619
- | hidden envelope in `text/html` | every path | every path, every browser, including Safari and Firefox |
620
-
621
- **Security.** The clipboard is untrusted input: any page or app can put any format on it, so
622
- the data is never trusted, only checked.
623
-
624
- - Each carrier is size-checked (`maxBytes`, default 8 MiB) before it is parsed or decoded
625
- - Own `__proto__` keys are dropped while parsing, so merging pasted data can't swap a prototype
626
- - Migrations run on untrusted data, then the schema validates the result; nothing unvalidated reaches `clip.value`
627
- - The HTML carrier is found with a strict token match on a closed alphabet (`id;base64url`): no HTML parsing, no DOM
628
- - Reading never throws for clipboard content: every outcome is a result
629
- - The data is **not authenticated**. Validate it as you would a form submission, and check permissions server-side
630
- - The HTML envelope travels wherever the HTML is pasted (a mail, a document), hidden but readable. Copy only what the user may share, or set `embedInHtml: false` (keyboard paste in Chromium and drops still work through the custom type)
631
-
632
- **Copying is strict too.** The data must survive `JSON.stringify` unchanged: `NaN`, `Infinity`,
633
- `BigInt`, `Map`, `Set`, functions and symbols throw an `invalid-payload` error naming the key
634
- instead of turning silently into `null` or `{}`. Dates become ISO strings, so read them back with a
635
- coercing schema (`z.coerce.date()`), or convert in `encode`.
636
-
637
- ## Paste as Markdown
638
-
639
- `react-smart-copy/markdown` turns what people paste into comment boxes, editors and CMS
640
- fields into clean Markdown: headings, bold and italic, links, lists (nested and task
641
- lists), tables, code blocks and quotes, from Google Docs, Word, Notion, GitHub, web pages
642
- and mail. No dependencies, about 7.6 kB.
643
-
644
164
  ```tsx
645
165
  import { pasteAsMarkdown } from "react-smart-copy/markdown";
646
-
647
- <textarea value={body} onChange={(event) => setBody(event.target.value)} onPaste={pasteAsMarkdown} />
166
+ <textarea value={body} onChange={(event) => setBody(event.target.value)} onPaste={pasteAsMarkdown} />;
648
167
  ```
649
168
 
650
- That one handler:
651
-
652
- - converts rich pastes (the HTML flavour) and inserts the Markdown at the cursor, replacing the selection
653
- - keeps the browser's **undo** (Ctrl/⌘+Z undoes the paste), fires `input` so React state follows, respects `maxlength`
654
- - leaves **plain-text pastes alone**, because plain text pasted into a Markdown field is usually Markdown already, and leaves code from editors (VS Code, JetBrains) as plain code
655
- - in a single-line `<input>`, joins the result into one line
656
-
657
- Pass options with `onPaste={(event) => pasteAsMarkdown(event, { images: "keep" })}`.
658
- For other flows, the pieces are separate:
659
-
660
- ```ts
661
- import { escapeMarkdown, htmlToMarkdown, insertText, pasteToMarkdown } from "react-smart-copy/markdown";
662
-
663
- // With usePaste or PasteField: Markdown for a paste result (plain text stays as it is).
664
- const pasted = pasteToMarkdown(result); // { markdown, source: "html" | "text", truncated } | null
665
- if (pasted) insertText(textarea, pasted.markdown);
666
-
667
- // Copy a rendered article as Markdown (a DOM node is converted in place, not re-parsed).
668
- copy(() => htmlToMarkdown(articleRef.current).markdown);
669
-
670
- // Any text, rendered literally by any Markdown renderer.
671
- escapeMarkdown("1. *Not* a list <b>"); // "1\\. \\*Not\\* a list \\<b>"
672
- ```
673
-
674
- **What real clipboards look like, handled.** Google Docs sets bold and italic with CSS on
675
- spans, wraps everything in a non-bold `<b>`, nests lists as siblings and wraps links in
676
- `google.com/url?q=` redirects. Word writes lists as `mso-list` paragraphs with hidden
677
- markers. Mail clients use `<div>` per line and layout tables. Spreadsheets and Docs tables
678
- become GFM tables, merged cells included.
679
-
680
- **Correct by construction.** Every delimiter the converter writes is checked with
681
- CommonMark's own pairing algorithm before it is kept, so text always renders as the same
682
- text: where CommonMark can't express a style (`x**[y]**z`), the style is dropped, never the
683
- text, and asterisks never leak into the output. Property tests render thousands of random
684
- documents with a CommonMark parser and compare the result character by character.
685
-
686
- **Security.** Pasted HTML is untrusted, so:
687
-
688
- - it is parsed in an inert document: scripts never run and nothing is fetched, not even images
689
- - the output never contains raw HTML: any `<` in the text is escaped
690
- - links keep only `http:`, `https:` and `mailto:` (`linkProtocols`); `javascript:`, `data:` and relative links keep only their text
691
- - images default to their alt text (`images: "alt"`), so rendering the Markdown loads no tracking pixels. `"keep"` writes `![alt](url)` for `https:`/`http:` images, `"drop"` removes them
692
- - `maxLength` (16 MiB), `maxNodes` (200,000) and `maxDepth` (200) bound the work; content left out sets `truncated: true`, and merged-cell expansion is capped
693
-
694
- | Option | Default | Notes |
695
- | ------ | ------- | - |
696
- | `images` | `"alt"` | `"alt"`, `"keep"` or `"drop"` |
697
- | `links` | `"keep"` | `"text"` keeps only the link text |
698
- | `linkProtocols` / `imageProtocols` | `http(s)`, `mailto` / `https`, `http` | allowed URL schemes |
699
- | `baseUrl` | none | resolves relative links and images |
700
- | `bullet` | `"-"` | `"*"` or `"+"` |
701
- | `hardBreak` | `"backslash"` | `"spaces"` for two trailing spaces |
702
- | `codeAsText` (paste) | `true` | `false` turns code-only pastes into fenced code blocks |
703
-
704
- ## Copy and paste code
705
-
706
- `react-smart-copy/code` is for the copy button on every code block and for fields people
707
- paste code into. It also catches code that reads differently from how it runs. No
708
- dependencies, about 7.4 kB (`inspectCode` alone is about 2.5 kB).
709
-
710
- ```tsx
711
- import { useCopy } from "react-smart-copy";
712
- import { codePayload } from "react-smart-copy/code";
713
-
714
- const { copy, status } = useCopy();
715
- <pre ref={preRef}>…</pre>
716
- <button onClick={() => copy(() => codePayload(preRef.current!, { language: "tsx" }))}>Copy</button>
717
- ```
718
-
719
- What gets copied is the code the reader means to run:
720
-
721
- - **A terminal or REPL session copies as its commands.** `$ npm test` followed by its output copies as `npm test`. Prompts from `bash`/`zsh` (`$`, `user@host:~$`, `(venv) $`), PowerShell, `cmd`, Python, IPython and Node are recognised. Continued commands stay whole: a trailing `\`, a heredoc or an open quote. `prompt: "auto"` (the default) only acts when the first line starts with a prompt
722
- - **A highlighted block copies without its chrome.** Line-number gutters (Prism, highlight.js, Rouge, react-syntax-highlighter and others), `user-select: none` and `aria-hidden` parts, hidden parts, buttons and anything with `data-copy-ignore` are left out. `ignore` takes a CSS selector for more
723
- - **It pastes well everywhere.** Plain text for editors and terminals, plus monospaced HTML with the block's syntax colours for Google Docs, Word, Slack, Teams and mail. Both flavours always hold the same code
724
- - **Diffs, line numbers, indentation.** `diff: "after"` (or `"before"`) copies one side of a unified diff. `lineNumbers: true` removes typed line numbers when they count up on every line. Shared indentation, trailing whitespace and blank edges are removed, and line endings are normalised (`lineEnding: "crlf"` for Windows)
725
-
726
- For a code field, `pasteAsCode` is a ready paste handler:
727
-
728
- ```tsx
729
- import { pasteAsCode } from "react-smart-copy/code";
730
-
731
- <textarea onPaste={pasteAsCode} />
732
- <textarea onPaste={(event) => pasteAsCode(event, { onPaste: (r) => !r.danger || confirm("Paste anyway?") })} />
733
- ```
734
-
735
- It fixes what chat apps and word processors do to code (curly quotes, `—` for `--`,
736
- no-break spaces, zero-width characters) and dedents the paste. Each line after the first is
737
- indented to the cursor line, as code editors do. The paste is one step on the browser's
738
- undo stack. `onPaste` sees every finding first and can cancel. For CodeMirror, Monaco or
739
- `usePaste`, `pasteToCode(result)` returns the same `{ code, findings, fixed, remaining, danger }`.
740
-
741
- **Security: code that runs differently from how it reads.** `inspectCode` reports, with
742
- line, column and a label such as `U+202E RIGHT-TO-LEFT OVERRIDE`:
743
-
744
- | Kind | Severity | What it catches |
745
- | ---- | -------- | --------------- |
746
- | `bidi-control` | danger | Trojan Source ([CVE-2021-42574](https://trojansource.codes/)): overrides and isolates that reorder how code is shown. Implicit marks are a warning |
747
- | `invisible` | danger / warning | Hangul fillers that make invisible identifiers, and tag characters that hide ASCII (including hidden instructions in prompts) are danger. Zero-width spaces, joiners outside words and emoji, and runs of variation selectors that smuggle data are warnings |
748
- | `mixed-script` | danger / warning | A Cyrillic or Greek letter inside a Latin word (`аdmin` with a Cyrillic `а`). A Latin lookalike is danger; another letter is a warning |
749
- | `control` | warning | Control characters other than tab, line feed, carriage return and form feed, and Unicode line separators |
750
- | `unusual-space` | warning | No-break, em, ideographic and similar spaces |
751
- | `confusable-punctuation` | warning | Curly quotes, dashes, `…`, the Greek question mark that looks like `;`, full-width punctuation outside CJK text |
752
-
753
- Joiners inside Arabic, Persian or Indic words and emoji, a single emoji variation
754
- selector, and full-width punctuation in CJK comments are left alone. `cleanCode` applies
755
- the safe replacement of every finding. It runs until nothing fixable is left, because
756
- removing a zero-width space can expose a mixed word. It never guesses a letter that has no
757
- Latin lookalike; those stay in `remaining`. Copying doesn't clean by default
758
- (`clean: true` turns it on). Pasting does (`clean: false` turns it off).
759
-
760
- ```ts
761
- import { cleanCode, inspectCode, normalizeCode } from "react-smart-copy/code";
762
-
763
- inspectCode(source).danger; // true for Trojan Source, lookalikes, invisible identifiers
764
- cleanCode("const s = “hi”;").code; // 'const s = "hi";'
765
- normalizeCode("$ npm i\nadded 1 package"); // "npm i" (also works on the server)
766
- ```
767
-
768
- Pasted code is never cut: past `maxLength` (2,000,000 characters) `pasteToCode` throws a
769
- `too-large` error, and `pasteAsCode` leaves the paste to the browser. HTML is parsed
770
- inertly and only its text is used.
771
-
772
- | Option | Default | Notes |
773
- | ------ | ------- | - |
774
- | `prompt` | `"auto"` copy, `false` paste | a style (`"shell"`, `"powershell"`, `"cmd"`, `"python"`, `"ipython"`, `"node"`), `{ command, continuation }` regexes, or `false` |
775
- | `diff` | `false` | `"after"` or `"before"` |
776
- | `lineNumbers` | `false` | remove typed line numbers that count up |
777
- | `dedent` / `trimTrailingWhitespace` / `trimBlankLines` | `true` | |
778
- | `lineEnding` / `finalNewline` | `"lf"` / `false` | |
779
- | `clean` | `false` copy, `true` paste | `true`, `false` or a list of kinds |
780
- | `html` / `language` (copy) | `true` / none | add the HTML flavour; `class="language-…"` on `<code>` |
781
- | `indentToCursor` / `onPaste` (`pasteAsCode`) | `true` / none | |
782
-
783
- ## Pasted images: private and small
784
-
785
- `react-smart-copy/image` gets pasted and dropped images ready to upload. A photo from a
786
- phone usually carries the exact location it was taken, the device and its serial number,
787
- and an embedded preview that can show what was cropped out. This module removes that
788
- data, and makes the image fit your size and byte limits. No dependencies, about 7.3 kB
789
- (about 4.8 kB for the server-safe `stripMetadata` and `readImageInfo`).
790
-
791
169
  ```ts
792
- import { usePaste } from "react-smart-copy";
793
170
  import { prepareImage } from "react-smart-copy/image";
794
-
795
- usePaste({
796
- accept: ["image"],
797
- onPaste: async ({ imageFiles }) => {
798
- const image = await prepareImage(imageFiles[0], { maxWidth: 2048, maxBytes: 1_000_000 });
799
- upload(image.file); // a File named like the original, metadata removed
800
- if (image.original.info.metadata.includes("gps")) notice("Location removed from the photo.");
801
- },
802
- });
171
+ const image = await prepareImage(file, { maxWidth: 2048, maxBytes: 1_000_000 }); // GPS and camera data removed
803
172
  ```
804
173
 
805
- **Lossless whenever it can be.** When only the metadata has to go, nothing is
806
- re-encoded. JPEG, PNG, WebP and GIF are rewritten without their metadata, and every
807
- pixel stays the same, so screenshots stay sharp and photos lose no quality. The image is
808
- decoded and encoded again only when it has to change: to fit `maxWidth`, `maxHeight`,
809
- `maxPixels` or `maxBytes`, to change its format, or because it is AVIF or HEIC.
810
-
811
- **What is removed:** Exif (camera, lens, dates, serial numbers), the GPS location, embedded
812
- thumbnails, XMP (edit history, authors), IPTC (captions, credits), comments, PNG text chunks,
813
- multi-picture and depth images (MPF), content credentials (C2PA), and data appended after
814
- the image (motion-photo videos). The colour profile is kept (`keepColorProfile: false`
815
- removes it). The orientation is kept in a 26-byte Exif block holding nothing else, so a
816
- photo still displays the right way up (`keepOrientation: false` removes it).
817
-
818
- **Fits a byte budget.** For `maxBytes`, JPEG and WebP search for the highest quality that
819
- fits (down to `minQuality`, 0.5 by default), and only then reduce the size. A screenshot
820
- stays PNG when it fits. When it doesn't, `type: "auto"` turns it into WebP, or JPEG where
821
- the browser can't encode WebP. If the limit can't be met, you get a `too-large` error,
822
- never a file that is still too big. Large reductions are drawn in halving steps, so text
823
- and edges stay clean.
824
-
825
- **Safe with hostile files.** The format is read from the bytes, never from the file name
826
- or the claimed type. Sizes come from the header and are checked against
827
- `maxInputPixels` (100 million) *before* decoding, which stops decompression bombs. Every
828
- parser read is bounded by its own box or chunk. Fuzz tests feed random and mutated files
829
- to every parser. Animations keep every frame by default (`animated: "keep"`): a resize
830
- they would need is a `too-large` error, `"first-frame"` makes a still image, and
831
- `"reject"` refuses them. Every failure is a typed error: `too-large`,
832
- `unsupported-format`, `unsupported` (re-encoding outside a browser), `timeout` or
833
- `aborted` (`signal`).
834
-
835
- ```ts
836
- import { readImageInfo, stripMetadata } from "react-smart-copy/image";
837
-
838
- // Anywhere, including the server (Node 18+): no decoding, no canvas.
839
- const info = await readImageInfo(file);
840
- // { format: "jpeg", width: 4032, height: 3024, orientation: 6, animated: false,
841
- // metadata: ["exif", "gps", "thumbnail", "icc", "other"] }
842
-
843
- const { blob, removed } = await stripMetadata(file); // bit-for-bit the same picture
844
- ```
845
-
846
- | Option (`prepareImage`) | Default | Notes |
847
- | ----------------------- | ------- | - |
848
- | `maxWidth` / `maxHeight` | none | only ever makes images smaller |
849
- | `maxPixels` | 16,777,216 | Safari's canvas limit |
850
- | `maxBytes` | none | quality first, then size; `too-large` when it can't |
851
- | `type` | `"auto"` | `"image/jpeg"`, `"image/png"` or `"image/webp"` |
852
- | `quality` / `minQuality` | 0.85 / 0.5 | JPEG and WebP |
853
- | `background` | `"#fff"` | under transparent pixels in JPEG |
854
- | `animated` | `"keep"` | `"first-frame"` or `"reject"` |
855
- | `keepColorProfile` | `true` | re-encoded images are written in sRGB |
856
- | `maxInputPixels` / `maxInputBytes` | 100,000,000 / 100 MiB | checked before decoding |
857
- | `timeoutMs` / `signal` | 30 s / none | |
858
- | `environment` | the browser | your own decoder (e.g. WebAssembly HEIC) or a test double |
859
-
860
- `width` and `height` in the result are the displayed size. Browsers turn JPEG and PNG by
861
- their orientation, and Chromium doesn't turn WebP. `removed` is read back from the
862
- output, not assumed, because some browsers' encoders add their own colour profile.
863
-
864
- ## Pasted and dropped files: safe by content
865
-
866
- `react-smart-copy/files` takes the files people paste or drop, whole folders included, and
867
- decides for each one whether it is safe and wanted. The type comes from the file's content,
868
- never from its name or the type the browser claims. So an HTML page named `invoice.pdf`, a
869
- program named `invoice.pdf.exe`, or a name that hides its real extension behind a
870
- right-to-left character is turned away, with a reason you can show. No dependencies, about
871
- 6.9 kB (about 2.3 kB for `safeFileName` alone). It works the same on a server.
872
-
873
174
  ```tsx
874
- import { acceptFiles } from "react-smart-copy/files";
875
-
876
- <div
877
- onDragOver={(event) => event.preventDefault()}
878
- onDrop={(event) => {
879
- event.preventDefault();
880
- // Call it in the handler, before any await: the browser empties the drop when the event ends.
881
- void acceptFiles(event, { accept: ".pdf,image/*", maxFileBytes: 20_000_000, digest: true }).then(({ accepted, rejected }) => {
882
- for (const file of accepted) upload(file.upload, file.path); // safe name, real type
883
- for (const file of rejected) toast(file.message); // "invoice.pdf.exe is a program or script, which can't be added."
884
- });
885
- }}
886
- />
175
+ import { pasteWithoutSecrets } from "react-smart-copy/secrets";
176
+ <textarea onPaste={(event) => pasteWithoutSecrets(event, { onSecrets: (found) => toast(`Removed a ${found[0].label}.`) })} />;
887
177
  ```
888
178
 
889
- It takes a drop or paste event (DOM or React), its `DataTransfer`, the `FileList` of an
890
- `<input type="file">`, or any list of files. With `usePaste` and `PasteField`, pass the
891
- result's `files`.
892
-
893
- **Known by content.** The first 8 KB of each file is read, and more than 50 formats are
894
- recognised by their signatures: PDF; images (JPEG, PNG, GIF, WebP, AVIF, HEIC, TIFF, BMP,
895
- ICO, PSD, SVG); audio and video; Office and OpenDocument files, told apart inside their
896
- ZIP; archives; fonts; SQLite; HTML, XML, JSON and other text; and programs (Windows, Linux
897
- and macOS executables, WebAssembly, Java and Android archives, shortcuts and scripts). Each
898
- accepted file's `type` is the detected one, never the claimed one: `upload` is the same
899
- bytes as a `File` with that type and the safe name.
900
-
901
- **Risky files are rejected by default.** Each file is checked for these risks, and by
902
- default any of them rejects it. Pass `block` to choose which ones do.
903
-
904
- | Risk | What it catches |
905
- | --- | --- |
906
- | `executable` | Programs and scripts, by content or by a name the system runs (`.exe`, `.bat`, `.ps1`, `.js`, `.jar`, `.iso`, `.lnk`, ...) |
907
- | `active-content` | HTML and SVG, and XML with XHTML or scripts: they run script when opened from your site |
908
- | `macros` | Office files that can hold macros (`.docm`, `.xlsm`, or a `vbaProject.bin` inside) |
909
- | `type-mismatch` | The content is not what the extension says: `report.pdf` holding HTML |
910
- | `double-extension` | `invoice.pdf.exe`, or `invoice.pdf .exe` |
911
- | `hidden-characters` | Bidirectional controls and invisible characters in the name: `photo\u202Egpj.exe` shows as `photoexe.jpg` |
912
- | `empty` | No bytes: often a folder dropped where folders aren't read |
913
-
914
- **Folders, within limits.** Dropped folders are walked depth-first, and each file's
915
- `path` keeps where it was (`photos/2024/a.jpg`). `maxFiles` (100), `maxFileBytes`
916
- (100 MiB), `maxTotalBytes` (1 GiB) and `maxDepth` (8) bound the walk, so a dropped home
917
- folder can't hang the page. With `digest: true`, each file's SHA-256 is computed and a
918
- repeated file is rejected as a `duplicate`.
919
-
920
- **Names safe everywhere.** `safeFileName` keeps only the last path segment (no `../`),
921
- removes hidden and control characters, replaces the characters Windows, macOS and Linux
922
- reject, prefixes Windows device names (`CON`, `NUL`, `COM1`), and fits the name to 255
923
- UTF-8 bytes, keeping its extension.
924
-
925
179
  ```ts
926
- import { inspectFile, safeFileName } from "react-smart-copy/files";
927
-
928
- // In the browser or on a server (Node 18+), for a file you already have.
929
- const inspection = await inspectFile(file);
930
- // { name: "invoice.pdf", safeName: "invoice.pdf", extension: "pdf", type: "text/html",
931
- // detected: { mime: "text/html", family: "text", ... }, mismatch: true,
932
- // risks: ["active-content", "type-mismatch"], ... }
933
-
934
- safeFileName("../../uploads/CON.txt"); // "_CON.txt"
180
+ import { parseNumber } from "react-smart-copy/number";
181
+ parseNumber("1.234,50 €"); // { value: 1234.5, exact: "1234.50", currency: { symbol: "€", code: "EUR" }, … }
935
182
  ```
936
183
 
937
- | Option (`acceptFiles`) | Default | Notes |
938
- | --- | --- | --- |
939
- | `accept` | any | as in `<input accept>`: `".pdf,image/*"`, judged by content |
940
- | `block` | every risk | `[]` accepts risky files; their `inspection.risks` still say |
941
- | `maxFiles` | 100 | the walk stops at the next file, and `truncated` is `true` |
942
- | `maxFileBytes` / `maxTotalBytes` | 100 MiB / 1 GiB | |
943
- | `folders` / `maxDepth` | `true` / 8 | |
944
- | `digest` | `false` | SHA-256 for each file, and `duplicate` rejections; needs Web Crypto (a secure page, or Node.js 20+) |
945
- | `names` | | `maxBytes`, `replacement` and `fallback` for `safeFileName` |
946
- | `signal` | none | aborts with an `aborted` CopyFailure |
947
-
948
- Each rejection has a `reason` (`blocked`, `not-accepted`, `too-large`, `total-too-large`,
949
- `too-many`, `too-deep`, `unreadable` or `duplicate`), the file's `risks`, and a `message`
950
- that names the file by its safe name. Checking files in the browser is for the people
951
- using your app: check them again on your server, where `inspectFile` works the same, and
952
- serve uploads with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`.
953
-
954
- ## Secrets: keep keys out of pastes and copies
955
-
956
- `react-smart-copy/secrets` keeps secrets from travelling through the clipboard. It finds API
957
- keys, tokens, private keys, passwords, card numbers and IBANs in text people paste or copy,
958
- and redacts or blocks them: in a chat box, a support ticket, or a log someone copies from
959
- your app. No dependencies, about 4.1 kB (about 3.3 kB for `scanSecrets` alone), and it works
960
- the same on a server.
961
-
962
- ```tsx
963
- import { pasteWithoutSecrets } from "react-smart-copy/secrets";
964
-
965
- <textarea
966
- onPaste={(event) =>
967
- pasteWithoutSecrets(event, {
968
- // "redact" (the default) inserts the paste with each secret replaced; "block" inserts nothing.
969
- action: "redact",
970
- onSecrets: (found) => toast(`Removed a ${found[0].label} from your message.`),
971
- })
972
- }
973
- />
974
- ```
975
-
976
- **What it finds.** Each finding has a kind, a confidence, and a masked preview.
977
-
978
- - **Service keys and tokens, by their documented formats:** AWS access key IDs, GitHub
979
- (classic and fine-grained), GitLab, Slack tokens and webhooks, Stripe live keys, Google API
980
- keys, npm, PyPI, SendGrid, Twilio, Azure storage keys, and JSON Web Tokens (whose
981
- header must decode).
982
- - **Private keys** (PEM and OpenSSH), from their `BEGIN` line to their `END` line.
983
- - **Passwords inside other text:** in URLs (`postgres://app:password@db`) and in connection
984
- strings (`;Password=...`).
985
- - **Card numbers and IBANs, by checksum:** Luhn plus the card brand's ranges and lengths,
986
- and mod-97 plus the country's IBAN length.
987
- - **Random-looking values assigned to secret names:** `API_KEY="..."`, `"password": "..."`,
988
- `client_secret: ...`, including an AWS secret key next to its name. Placeholders
989
- (`changeme`, `<token>`, `${TOKEN}`) and references (`process.env.TOKEN`) are left alone.
990
-
991
- **Safe to run on anything.** Every pattern runs in linear time: no nested quantifiers, no
992
- lookbehind. Hostile text of hundreds of kilobytes is scanned in milliseconds. A finding never
993
- holds the secret: it holds where the secret is (`start`, `end`), its `kind` and `label`, a
994
- `confidence`, and `masked`. `masked` keeps at most a known prefix and the last 4 characters
995
- (`ghp_` and the last 4, or `•••• 4242` for a card), and nothing at all for passwords. Text
996
- past `maxLength` (1,000,000 characters) is not scanned, and `redactSecrets` drops it rather
997
- than pass it on unchecked.
998
-
999
184
  ```ts
1000
- import { redactSecrets, scanSecrets, secretRedactor } from "react-smart-copy/secrets";
1001
-
1002
- const { findings } = scanSecrets(text, { minConfidence: "high" });
1003
- // [{ kind: "github-token", label: "GitHub token", confidence: "high", start: 13, end: 53, masked: "ghp_…a1B2" }]
1004
-
1005
- redactSecrets("token=ghp_…").text; // "token=[redacted GitHub token]"
1006
-
1007
- // Mask secrets in what people copy from a log viewer or an admin console.
1008
- useCopyInterceptor(logRef, { transform: secretRedactor() });
185
+ import { parseAddresses } from "react-smart-copy/email";
186
+ parseAddresses('Lima, Ana <ana@example.com>; bo@ex\u0430mple.com'); // two addresses, the second flagged as a lookalike
1009
187
  ```
1010
188
 
1011
- | Option | Default | Notes |
1012
- | --- | --- | --- |
1013
- | `kinds` | every kind | the kinds to look for |
1014
- | `minConfidence` | `"medium"` | `"high"` leaves out values that only look like secrets |
1015
- | `maxLength` | 1,000,000 | characters scanned |
1016
- | `replace` | `[redacted <label>]` | `redactSecrets`, `pasteWithoutSecrets` and `secretRedactor` |
1017
- | `action` | `"redact"` | `pasteWithoutSecrets`: `"block"` inserts nothing |
1018
- | `onSecrets` | | `pasteWithoutSecrets`: called with the findings and what was done |
1019
-
1020
- A paste is redacted in a `<textarea>` or text `<input>`, with undo intact; anywhere else, a
1021
- paste with secrets is blocked. Scanning in the browser protects the people using your app.
1022
- Scan again on your server before you store or forward text, because `scanSecrets` works the
1023
- same there.
1024
-
1025
- ## One-time codes
1026
-
1027
- `react-smart-copy/otp` handles the one-time codes people copy from an SMS or an e-mail.
1028
- `extractOtp` finds the code in a message, and leaves prices, dates, times, phone numbers and
1029
- order numbers alone. `useOtpField` (in the React entry) wires a row of single-character
1030
- boxes: typing moves on, Backspace goes back, and pasting a whole message into any box fills
1031
- them all. No dependencies, about 3.6 kB (about 2 kB for `extractOtp` alone).
1032
-
1033
189
  ```tsx
1034
190
  import { useOtpField } from "react-smart-copy";
1035
-
1036
191
  const otp = useOtpField({ length: 6, onComplete: verify });
1037
-
1038
- <div role="group" aria-label="Verification code">
1039
- {Array.from({ length: 6 }, (_, index) => (
1040
- <input key={index} {...otp.getInputProps(index)} />
1041
- ))}
1042
- </div>
1043
- ```
1044
-
1045
- - **SMS autofill** on iOS and Android (`autocomplete="one-time-code"` on the first box), and
1046
- the **WebOTP API** with `webOtp: true`, cancelled when the boxes unmount or the code is typed.
1047
- - **Every box is named** (`Digit 1 of 6`), numeric codes get the numeric keyboard, and the
1048
- arrow keys, Home, End, Backspace and Delete work as people expect.
1049
- - **`extractOtp`** reads codes on their own (`482 913`), origin-bound lines
1050
- (`@example.com #482913`, refused for another `domain`), and numbers next to a word that
1051
- names them in twenty languages, with digits of any script. Linear time, first 100,000
1052
- characters.
1053
-
1054
- ```ts
1055
- import { extractOtp } from "react-smart-copy/otp";
1056
-
1057
- extractOtp("Your verification code is 482913. It expires in 10 minutes.");
1058
- // { code: "482913", source: "keyword", confidence: "high", domain: null }
1059
- extractOtp("Your order 48291 of $1,249.00 ships on 24/10."); // null
192
+ // {Array.from({ length: 6 }, (_, index) => <input key={index} {...otp.getInputProps(index)} />)}
1060
193
  ```
1061
194
 
1062
- ## Numbers and amounts
1063
-
1064
- `react-smart-copy/number` reads the numbers people paste: `1.234,50 €` from a bank statement,
1065
- `$1,234.50` from an invoice, `(1,234.00)` from a spreadsheet, `₹ 12,34,567` in lakh grouping.
1066
- It gives the number exactly, as a decimal string as well as a `number`, and turns away dates,
1067
- phone numbers and wrongly grouped text. No dependencies, about 3.5 kB.
1068
-
1069
195
  ```tsx
1070
- import { parseNumber, pasteAsNumber } from "react-smart-copy/number";
1071
-
1072
- parseNumber("1.234,50 €");
1073
- // { value: 1234.5, exact: "1234.50", kind: "number", currency: { symbol: "€", code: "EUR" }, ambiguous: false }
1074
-
1075
- <input type="number" step="any" onPaste={(event) => pasteAsNumber(event, { locale: "de-DE" })} />
1076
- ```
1077
-
1078
- - **Every grouping and decimal style:** `,` `.` `'` and spaces, groups of three and lakh
1079
- grouping. Text that can be read only one way is read that way everywhere; a lone `1,234` is
1080
- settled by `locale`, and flagged `ambiguous`.
1081
- - **Signs, currencies and percent:** `−`, trailing minus, accounting brackets, symbols and ISO
1082
- codes before or after, `%` and `‰`, scientific notation.
1083
- - **`pasteAsNumber`** puts `exact` in `<input type="number">` and the locale's format in text
1084
- fields, with undo intact, and turns away pastes that are not numbers.
1085
- - **`formatNumber` and `numberPayload`** write a number, bigint or exact string for any locale,
1086
- grouped or not, rounded to `fractionDigits` without float error.
1087
-
1088
- ## E-mail recipients
1089
-
1090
- `react-smart-copy/email` reads the lists of recipients people paste into To fields and invite
1091
- dialogs, from Outlook, Gmail, Apple Mail, contact cards and spreadsheet columns. No
1092
- dependencies, about 2.8 kB.
1093
-
1094
- ```tsx
1095
- import { parseAddresses, pasteAddresses } from "react-smart-copy/email";
1096
-
1097
- parseAddresses('Lima, Ana <ana@example.com>; "Diaz, Bo" <bo@example.org>, cy@example');
1098
- // addresses: Ana (name "Lima, Ana") and Bo (name "Diaz, Bo"); invalid: [{ text: "cy@example", reason: "domain" }]
1099
-
1100
- <input onPaste={(event) => pasteAddresses(event, { onAddresses: ({ addresses }) => addRecipients(addresses) })} />
1101
- ```
1102
-
1103
- - **Every way mail programs copy lists:** commas, semicolons, line breaks and tabs; quoted and
1104
- unquoted names, `mailto:` links, the old `address (Name)` form, and spreadsheet rows with
1105
- names in the cells around the address.
1106
- - **Checked addresses:** dot-atom local parts, domains that can exist, length limits.
1107
- Invisible and direction-changing characters are turned away, and domains that mix Latin
1108
- with Cyrillic or Greek letters are flagged `lookalike`.
1109
- - **International addresses** in their ASCII form for storing and their Unicode form for
1110
- showing; `domains` restricts a list to your company's domains.
1111
- - **`addressesPayload`** copies a list that pastes into any To field, names quoted as mail
1112
- needs; names can never end a mail header.
1113
-
1114
- ## Copy links
1115
-
1116
- `react-smart-copy/link` is for "Copy link" and "Share" buttons, and for fields people
1117
- paste links into. No dependencies, about 4 kB (`linkPayload` alone is about 1.8 kB).
1118
-
1119
- ```tsx
1120
- import { useCopy } from "react-smart-copy";
1121
196
  import { linkPayload } from "react-smart-copy/link";
1122
-
1123
- const { copy, status } = useCopy();
1124
- <button onClick={() => copy(() => linkPayload({ url: issue.url, title: issue.title }, { clean: true }))}>Copy link</button>
1125
- ```
1126
-
1127
- **It pastes as the right thing everywhere.** The clipboard gets a titled link (`<a href>`)
1128
- and the URL. Slack, Google Docs, Notion, Teams, Word and mail paste the title as a link;
1129
- editors, terminals and the address bar paste the URL. `text: "markdown"` makes the plain
1130
- text `[title](url)` for Markdown fields, `"title-and-url"` puts both on two lines. Dragged
1131
- with `useDragCopy` (`{ target: "drag" }`), it also carries `text/uri-list` and Firefox's
1132
- `text/x-moz-url`, so it drops into tabs, bookmarks and other apps as a link.
1133
-
1134
- **Safe by default.** Every URL is resolved to an absolute one and checked: only `https:`,
1135
- `http:`, `mailto:` and `tel:` are allowed (`protocols` changes that), so `javascript:` and
1136
- `data:` links are never copied or pasted. User names and passwords in a URL are always
1137
- removed. International domains are written in punycode, so a lookalike domain shows as
1138
- one. Titles are cleaned of hidden and reordering characters and capped at 300 characters
1139
- (`maxTitleLength`), and all HTML is escaped. Invalid input is a typed `invalid-payload` error.
1140
-
1141
- **Tracking parameters removed.** `clean: true` (or `cleanLinkUrl(url)`) removes `utm_*`,
1142
- `fbclid`, `gclid`, `msclkid` and other click trackers, and keeps every other parameter and
1143
- the `#section`. `clean: { params, keep }` sets your own list.
1144
-
1145
- ```ts
1146
- import { cleanLinkUrl, linkPayload, resolveLink } from "react-smart-copy/link";
1147
-
1148
- cleanLinkUrl("https://shop.example/p/42?utm_source=news&color=red#reviews");
1149
- // "https://shop.example/p/42?color=red#reviews"
1150
-
1151
- linkPayload(anchorElement); // an <a>: its resolved href and its text
1152
- ```
1153
-
1154
- **Links to a passage.** `textFragmentUrl` makes a link that scrolls to a passage and
1155
- highlights it (`#:~:text=`), in Chrome, Edge, Safari and Firefox. Other browsers open the
1156
- page as usual. `selectionLink()` links to what the reader has selected, with the page title
1157
- and the quote, ready for `linkPayload`. Passing a function to `copy` turns an invalid link into an
1158
- `invalid-payload` error state rather than an exception:
1159
-
1160
- ```tsx
1161
- import { linkPayload, selectionLink, textFragmentUrl } from "react-smart-copy/link";
1162
-
1163
- <button onClick={() => { const link = selectionLink(); if (link) void copy(() => linkPayload(link)); }}>Copy link to selection</button>
1164
-
1165
- textFragmentUrl("https://example.com/docs#install", "npm install react-smart-copy");
1166
- // "https://example.com/docs#install:~:text=npm%20install%20react%2Dsmart%2Dcopy"
1167
- ```
1168
-
1169
- Long passages link by their first and last words, each taken from within one paragraph,
1170
- as the syntax requires. When the passage appears more than once on the page, the words
1171
- around it are added so the link finds the right one.
1172
-
1173
- **Pasting links.** `pasteAsLink` turns selected text into a link when a URL is pasted over
1174
- it, as GitHub, Slack and Notion do. It writes `[selection](url)` by default (`format`
1175
- changes that) and keeps the browser's undo. Every other paste is left alone.
1176
- `readLink(result)` reads the one link a paste or drop holds, with its title, from
1177
- `text/uri-list`, a single `<a>` or a single URL, or returns `null`.
1178
-
1179
- ```tsx
1180
- import { pasteAsLink, readLink } from "react-smart-copy/link";
1181
-
1182
- <textarea onPaste={pasteAsLink} />
1183
-
1184
- usePaste({ accept: ["text", "html", "text/uri-list"], onPaste: (result) => {
1185
- const link = readLink(result);
1186
- if (link) addBookmark(link.url, link.title);
1187
- } });
1188
- ```
1189
-
1190
- | Option | Default | Notes |
1191
- | ------ | ------- | - |
1192
- | `text` | `"url"` | plain text: `"url"`, `"title"`, `"title-and-url"` or `"markdown"` |
1193
- | `target` | clipboard | `"drag"` adds `text/uri-list` and `text/x-moz-url` |
1194
- | `clean` | `false` | `true`, or `{ params, keep }` |
1195
- | `protocols` | `https:`, `http:`, `mailto:`, `tel:` | allowed schemes |
1196
- | `base` | the page's address | resolves relative links; needed on the server |
1197
- | `maxTitleLength` | 300 | |
1198
- | `maxWords` / `contextWords` | 10 / 4 | text fragments |
1199
-
1200
- ## Copy styled content: paste it as it looks
1201
-
1202
- Copy a card, a note, a report or a table from your app and paste it into Gmail, Outlook
1203
- or Google Docs, and it usually comes out wrong. The classes and stylesheets it depended on
1204
- don't travel. Modern CSS colours like Tailwind's `oklch()` mean nothing to mail clients.
1205
- Light text from a dark theme turns invisible on a white page. Relative links and images
1206
- break. And the browser's own copy fills the paste with layout CSS and page chrome.
1207
- `react-smart-copy/rich` copies what the reader sees, in HTML that every destination keeps.
1208
-
1209
- ```tsx
1210
- import { useCopy, useCopyInterceptor } from "react-smart-copy";
1211
- import { richPayload, richTransform } from "react-smart-copy/rich";
1212
-
1213
- const { copy } = useCopy();
1214
- <button onClick={() => copy(() => richPayload(cardRef.current))}>Copy for email</button>
1215
-
1216
- // Ctrl/⌘+C of any selection inside the article is portable too:
1217
- useCopyInterceptor(articleRef, { transform: richTransform() });
1218
- ```
1219
-
1220
- **What it writes:**
1221
-
1222
- - **Only what's safe and widely supported.** Text, headings, lists, tables, links, images,
1223
- quotes and code. Scripts, event handlers, embeds, SVG, media, forms and controls are left
1224
- out. So are hidden content and anything marked `data-copy-ignore` or `aria-hidden`. Every
1225
- attribute is checked against an allowlist.
1226
- - **Styles inline, from what the reader sees.** For content on the page, the computed
1227
- styles are read: colours, fonts, sizes, weight, alignment, borders, padding, list markers.
1228
- They are written only where they change, so the HTML stays small. Layout CSS (`flex`,
1229
- `grid`, `position`) is never copied, because no destination keeps it.
1230
- - **Colours every mail client understands.** Every colour, from `oklch()`, `color()`,
1231
- `rgb(… / 50%)` or a CSS variable, becomes an opaque hex value drawn over its background.
1232
- With `colors: "readable"` (the default), text that would fall under 3:1 contrast where
1233
- it lands, like light text from a dark theme, takes the destination's own colour.
1234
- `"keep"` copies every colour, and `"none"` copies none.
1235
- - **Absolute, safe URLs.** Links resolve against the page and keep only `https:`,
1236
- `http:`, `mailto:` and `tel:` (`protocols` changes this). Images keep `https:` and `http:`
1237
- sources with their displayed size as attributes, which Outlook needs. `data:` images
1238
- need `dataImages: true`, because many mail clients block them. `images: "alt"` writes
1239
- their alt text instead, and `images: "drop"` leaves them out.
1240
- - **Structure that survives the paste.** Rows sit in table bodies. A block inside a
1241
- paragraph is written inline. Nothing is left where an HTML parser would move it.
1242
- - **Readable plain text** for editors and plain fields: lists with bullets or numbers,
1243
- table cells separated by tabs, line breaks kept. `text: (root) => htmlToMarkdown(root).markdown`
1244
- gives Markdown instead.
1245
-
1246
- `prepareRich(source, options)` returns `{ html, text, removed, truncated }`. `removed`
1247
- lists what was left out and why (`unsafe-element`, `unsafe-link`, `unreadable-color`,
1248
- `hidden`, …), for logs and audits. The source can be an element, a selection `Range`, a
1249
- fragment or HTML text. HTML text is parsed inertly, and only its `style` attributes are
1250
- read. The output is built in a separate, inert document, so nothing is inserted into your
1251
- page and no image loads while it is prepared. `maxElements` (10,000) and `maxLength`
1252
- (about 1 MB) bound the work.
1253
-
1254
- The output is property-tested against hostile HTML. [DOMPurify](https://github.com/cure53/DOMPurify)
1255
- finds nothing to remove from it, and running the output through again changes nothing.
1256
- In Chromium, Firefox and WebKit, the computed styles are checked end to end.
1257
-
1258
- | Option | Default | Notes |
1259
- | --- | --- | --- |
1260
- | `colors` | `"readable"` | `"keep"`, `"none"` |
1261
- | `background` | `"#ffffff"` | where it is pasted, for readability |
1262
- | `images` / `dataImages` | `"keep"` / `false` | `"alt"`, `"drop"` |
1263
- | `styles` | `"computed"` on the page, `"inline"` otherwise | `"none"` |
1264
- | `ignore` | none | a CSS selector to leave out |
1265
- | `base` / `protocols` | the page / `https:`, `http:`, `mailto:`, `tel:` | links |
1266
- | `maxElements` / `maxLength` | 10,000 / 1,000,000 | then `truncated` |
1267
- | `text` | readable plain text | your own, such as Markdown |
1268
-
1269
- ### Paste into a rich-text editor
1270
-
1271
- The other way round: paste from Google Docs, Word, Outlook, Gmail or a web page into your
1272
- editor, and get the content without the mess. Docs marks bold with `font-weight: 700` on
1273
- spans inside a `<b>` that isn't bold. Word writes lists as paragraphs with `mso-list`
1274
- styles and hides the bullets in spans. Mail wraps everything in layout tables. And every
1275
- source brings its fonts, colours and classes, which fight your editor's look.
1276
- `pasteToRich` turns all of it into clean, semantic HTML.
1277
-
1278
- ```tsx
1279
- import { pasteAsRich, pasteToRich } from "react-smart-copy/rich";
1280
-
1281
- // A contenteditable element: inserted with undo intact
1282
- <div contentEditable onPaste={pasteAsRich} />
1283
-
1284
- // TipTap / ProseMirror: clean it before the editor parses it
1285
- useEditor({ editorProps: { transformPastedHTML: (html) => pasteToRich({ html })?.html ?? html } });
1286
-
1287
- // Lexical: clean, then let Lexical import it
1288
- editor.registerCommand(PASTE_COMMAND, (event) => {
1289
- const pasted = pasteToRich({ html: event.clipboardData?.getData("text/html") });
1290
- if (pasted?.source !== "html") return false;
1291
- editor.update(() => $insertNodes($generateNodesFromDOM(editor, new DOMParser().parseFromString(pasted.html, "text/html"))));
1292
- return true;
1293
- }, COMMAND_PRIORITY_HIGH);
1294
-
1295
- // A comment box: only what its toolbar has, and all of the text
1296
- pasteToRich(result, { formats: ["bold", "italic", "link", "list"] });
1297
- ```
1298
-
1299
- **What it writes:**
1300
-
1301
- - **Semantic markup only.** Paragraphs, headings, lists, quotes, code blocks, tables, rules,
1302
- links and images, with `<strong>`, `<em>`, `<u>`, `<s>`, `<code>`, `<sup>` and `<sub>`.
1303
- Formatting set by CSS becomes these tags, and CSS wins over tags, as in the browser.
1304
- Every style, class and id is left out, so pasted content takes your editor's look.
1305
- - **Real structure from Word and Docs.** Word's list paragraphs become nested lists with
1306
- their numbering. Docs' wrappers, paragraphs inside list items and lists nested beside
1307
- their items are put right. Layout tables from mail become their content; data tables
1308
- keep their sections, merged cells and captions. Code from editors and `<pre>` keeps its
1309
- lines and indentation.
1310
- - **Canonical.** The same content always gives the same HTML: links outermost, then formats
1311
- in a fixed order, each over the longest stretch it covers. Whitespace collapses as the
1312
- browser shows it. Cleaning the output again changes nothing.
1313
- - **Safe.** The same sanitizer as `prepareRich`: allowlisted elements and attributes, links
1314
- and images with absolute, scheme-checked URLs. Google and Outlook Safe Links redirects
1315
- are unwrapped to their destination. Relative links have no address to resolve against,
1316
- so they keep their text, unless you give `base`. `removed` reports scripts, embeds, unsafe
1317
- links and images left out; it doesn't report what every clipboard document carries (its
1318
- head, Office markup).
1319
- - **`formats`** limits the output to what your editor holds. Nothing is lost: a heading
1320
- becomes a bold paragraph, a list item a paragraph after its marker, a table its cells, a
1321
- code block its lines, an image its alt text.
1322
-
1323
- `pasteToRich(source, options)` takes `{ html, text }` (a `PasteResult` from `usePaste`
1324
- fits) and returns `{ html, text, removed, truncated, source }`, or `null` when there is
1325
- nothing to paste. Plain text becomes paragraphs and line breaks (`source: "text"`), and
1326
- needs no DOM, so it works on a server too. `pasteAsRich(event, options)` handles a paste
1327
- into a `contenteditable` element and leaves plain-text pastes to the browser; `onPaste`
1328
- sees the result first, and returning `false` lets you insert it yourself. `maxNodes`
1329
- (200,000), `maxElements` and `maxLength` bound the work, and HTML is read up to 16 MiB.
1330
-
1331
- It is property-tested against generated Docs, Word, mail and hostile HTML. It writes only
1332
- allowlisted markup, and DOMPurify finds nothing to remove. Every visible character is kept,
1333
- with the bold, italic, underline, strikethrough, code, superscript and subscript it showed.
1334
- And cleaning twice changes nothing.
1335
-
1336
- A note for sites that collect Content Security Policy reports. Pasted HTML is parsed in an
1337
- inert document, where scripts and handlers never run. Since Chromium 156, though, parsing an
1338
- inline handler there (`<img onerror=…>` from a web page) under a policy that blocks inline
1339
- handlers sends a `script-src-attr` report, whose target is the document rather than an element.
1340
- Every HTML sanitizer that parses in the browser triggers it, and nothing is blocked that would
1341
- have run ([w3c/webappsec-csp#824](https://github.com/w3c/webappsec-csp/issues/824)).
1342
-
1343
- ## Copy and paste colours
1344
-
1345
- `react-smart-copy/color` is for design-system docs, colour pickers, theme editors and
1346
- design tools. It reads and writes every CSS Color 4 notation, without dependencies.
1347
- About 6.5 kB in total; `parseColor` with `formatColor` is about 5.3 kB.
1348
-
1349
- ```tsx
1350
- import { useCopy } from "react-smart-copy";
1351
- import { colorPayload, pasteAsColor } from "react-smart-copy/color";
1352
-
1353
- const { copy } = useCopy();
1354
- <button onClick={() => copy(() => colorPayload(token.value, { format: "oklch" }))}>Copy</button>
1355
- // Text: "oklch(62.31% 0.18801 259.81)". Docs, Notion, Slack and mail also get a swatch.
1356
-
1357
- <input value={hex} onChange={…} onPaste={(event) => pasteAsColor(event, { format: "hex" })} />
1358
- // Pasting "rgb(59 130 246)" or "background: #3b82f6;" inserts "#3b82f6".
1359
- ```
1360
-
1361
- **Every format, both ways.** `parseColor` reads hex (3, 4, 6 and 8 digits), the 148 named
1362
- colours and `transparent`, `rgb()` and `hsl()` (both syntaxes), `hwb()`, `lab()`, `lch()`,
1363
- `oklab()`, `oklch()`, and `color()` in `srgb`, `srgb-linear`, `display-p3`, `xyz`, `xyz-d65`
1364
- and `xyz-d50`, with every angle unit, percentages and `none`. It returns `null` for
1365
- anything else and never throws. `formatColor(color, format)` writes `hex`, `rgb`, `hsl`,
1366
- `hwb`, `oklch`, `oklab`, `lab`, `lch` or `p3`. Its default precision brings every 8-bit
1367
- colour back exactly; this was checked on 836,056 colours.
1368
-
1369
- **Wide gamut done right.** A Display P3 or OKLCH colour outside sRGB stays exact until a
1370
- format needs it in sRGB. Then it is gamut-mapped as CSS Color 4 specifies: lightness and
1371
- hue are kept and chroma is reduced, so a vivid P3 red becomes the closest sRGB red, not an
1372
- orange. `gamut: "clip"` clips each channel instead, as most browsers draw. `inGamut` and
1373
- `toGamut` are exported.
1374
-
1375
- **Pasting.** `readColor(text)` reads the one colour in pasted text. That includes a
1376
- declaration copied from a stylesheet or developer tools: `color: #3b82f6;`,
1377
- `--brand: oklch(…) !important;`. `bareHex: true` also reads `3b82f6`; it is off by default,
1378
- because words like "decade" are hex. `pasteAsColor` is a paste handler for colour fields
1379
- that keeps the browser's undo.
1380
-
1381
- **Contrast.** `contrastRatio(text, background)` is the WCAG 2 ratio. Translucent colours
1382
- are drawn the way a browser draws them, and the ratio is never rounded, so 4.499 fails.
1383
- `contrastLevel(ratio, { large })` gives `AAA`, `AA` or `fail`.
1384
-
1385
- ```ts
1386
- import { contrastLevel, contrastRatio, formatColor, parseColor } from "react-smart-copy/color";
1387
-
1388
- formatColor("color(display-p3 1 0 0)", "hex"); // "#ff0b0c": mapped, not clipped
1389
- formatColor("#3b82f6", "hsl", { legacy: true }); // "hsl(217.22, 91.22%, 59.8%)"
1390
- contrastLevel(contrastRatio("#767676", "#fff")); // "AA" (4.54)
1391
- parseColor("hsl(1turn 100% 50% / 50%)"); // { r: 1, g: 0, b: 0, alpha: 0.5 }
1392
- ```
1393
-
1394
- | Option (`formatColor`, `colorPayload`) | Default | Notes |
1395
- | --- | --- | --- |
1396
- | `format` | `"hex"` | `colorPayload` only |
1397
- | `gamut` | `"map"` | `"clip"` |
1398
- | `legacy` | `false` | comma syntax for `rgb` and `hsl` |
1399
- | `uppercase` | `false` | hex digits |
1400
- | `precision` | per format | decimal places |
1401
- | `swatch` | `true` | `colorPayload` only |
1402
-
1403
- Accuracy is property-tested against [culori](https://culorijs.org) for every notation and
1404
- format. In Chromium, Firefox and WebKit, colours are also checked against the browser's
1405
- own CSS parser.
1406
-
1407
- ## Share, or copy the link
1408
-
1409
- `react-smart-copy/share` is one button that does the right thing on every device: the
1410
- share sheet on phones and tablets, where people expect it, and a copied titled link on
1411
- desktop. `useShare` comes from `react-smart-copy`; without React, use
1412
- `shareOrCopy` from `react-smart-copy/share` (about 4.4 kB).
1413
-
1414
- ```tsx
1415
- import { useShare } from "react-smart-copy";
1416
-
1417
- function ShareButton({ url, title }: { url: string; title: string }) {
1418
- const { share, status, method } = useShare({ clean: true });
1419
- return (
1420
- <button type="button" onClick={() => void share({ url, title })}>
1421
- {status === "copied" ? "Link copied" : status === "shared" ? "Shared" : method === "native" ? "Share…" : "Copy link"}
1422
- </button>
1423
- );
1424
- }
1425
- ```
1426
-
1427
- **Honest outcomes.** `share()` never rejects. It resolves to `shared`, `copied` (with a
1428
- `reason`: `preferred`, `unsupported` or `fallback`), `cancelled` or `error`. Closing the
1429
- share sheet is `cancelled`, and the status goes back to `idle`: it is not an error, and it
1430
- never triggers a surprise copy. When the share sheet fails for another reason (an iframe
1431
- without the `web-share` permission, content it rejects), the link is copied instead.
1432
- `fallback: false` reports the error instead. `describeShareError(error, method)` gives a
1433
- sentence for each.
1434
-
1435
- **Labelled correctly.** `method` says what the button will do, `"native"` or `"copy"`, so
1436
- the label can say "Share…" or "Copy link". It is `"copy"` during server rendering and
1437
- hydration, so there is no mismatch. Then it follows the device, including a tablet that
1438
- gets a keyboard and a mouse.
1439
-
1440
- | `mode` | What happens |
1441
- | ------ | ------------ |
1442
- | `"auto"` (default) | the share sheet on touch-first devices (`(hover: none) and (pointer: coarse)`), copy elsewhere |
1443
- | `"native"` | the share sheet wherever the browser has one (also desktop Safari, and Edge and Chrome on Windows and macOS) |
1444
- | `"copy"` | always copy |
1445
-
1446
- **What is shared.** `url`, `title`, `text` and `files`. The URL is checked like every link
1447
- in `react-smart-copy/link`: only safe schemes, with credentials removed, and tracking
1448
- parameters removed with `clean: true`. The title is cleaned of hidden characters. Files go
1449
- only to a share sheet that accepts them (`navigator.canShare`); otherwise the link is
1450
- copied. The copy is a titled link (`linkPayload`), or the text when there is no URL.
1451
- `copy` sets your own.
1452
-
1453
- Without React, `shareOrCopy(content, options)` resolves to the same outcomes, and
1454
- `shareMethod(options)` says how it would share:
1455
-
1456
- ```ts
1457
- import { shareOrCopy } from "react-smart-copy/share";
1458
-
1459
- button.addEventListener("click", async () => {
1460
- const outcome = await shareOrCopy({ url: location.href, title: document.title });
1461
- if (outcome.status === "copied") toast("Link copied");
1462
- });
1463
- ```
1464
-
1465
- Call `share()` directly in the click handler. The share sheet needs the click's user
1466
- activation, so don't `await` anything before it.
1467
-
1468
- ## Only one "Copied" at a time
1469
-
1470
- Wrap a table or list in `<CopyGroup>`. A new successful copy returns the previously copied
1471
- row to idle, because the clipboard no longer holds its value. A failed copy releases nothing.
1472
-
1473
- ```tsx
1474
- import { CopyField, CopyGroup } from "react-smart-copy";
1475
-
1476
- <CopyGroup>
1477
- {rows.map((row) => (
1478
- <CopyField.Root key={row.id} value={row.email} label="Email">
1479
- <CopyField.Value />
1480
- <CopyField.Trigger />
1481
- </CopyField.Root>
1482
- ))}
1483
- </CopyGroup>;
1484
- ```
1485
-
1486
- It works for `useCopy()` too. Opt one field out with `copyOptions={{ coordinator: null }}`.
1487
- To share one group across React roots or with vanilla code, create it yourself:
1488
- `const coordinator = createCopyCoordinator()`, then `<CopyGroup coordinator={coordinator}>`
1489
- and `createCopyMachine({ coordinator })`.
1490
-
1491
- ## Pasting
1492
-
1493
- `usePaste` is the other half: read what the user pasted, with the same honest states.
1494
-
1495
- ```tsx
1496
- import { describePasteError, usePaste } from "react-smart-copy";
1497
-
1498
- function AvatarDrop() {
1499
- const { paste, state, targetProps, dropTargetProps, isDragOver } = usePaste<HTMLDivElement>({
1500
- accept: ["image"],
1501
- onPaste: (result) => {
1502
- const [image] = result.images;
1503
- if (image) void upload(image);
1504
- },
1505
- });
1506
-
1507
- return (
1508
- <div {...targetProps} {...dropTargetProps} tabIndex={0} data-over={isDragOver || undefined}>
1509
- Drop an image, press Ctrl/⌘+V to paste a screenshot, or
1510
- <button onClick={() => void paste()}>Paste from clipboard</button>
1511
- {state.status === "error" && <p role="alert">{describePasteError(state.error, state.source)}</p>}
1512
- </div>
1513
- );
1514
- }
1515
- ```
1516
-
1517
- Three ways in, one state machine:
1518
-
1519
- | Path | How | Permission prompt |
1520
- | ---- | --- | ----------------- |
1521
- | Keyboard paste | Spread `targetProps` on an element, or `listenOnDocument: true` for the whole page | **None**: the data is in the event |
1522
- | Drag and drop | Spread `dropTargetProps` on one element | **None**: the data is in the event |
1523
- | Paste button | Call `paste()` from a click | Browser may ask the user once |
1524
-
1525
- Paste events without accepted content are left alone, so normal typing and pasting into your
1526
- inputs keeps working. Paste events with accepted content are `preventDefault()`-ed (opt out with
1527
- `preventDefault: false`).
1528
-
1529
- **Drops** go through the same `accept`, limits and image checks, with `result.source === "drop"`.
1530
- While dragging, browsers only reveal the kinds and types of what is dragged, so `canAcceptDrag`
1531
- decides from those: accepted drags get the copy cursor (or the effect the drag source allows) and
1532
- `isDragOver`, which stays steady as the pointer crosses child elements. Other drags are cancelled
1533
- with `dropEffect: "none"`, so a rejected file is never opened by the browser in place of your page.
1534
- A file whose type the browser hides until the drop (Safari does this) counts as a maybe and is
1535
- checked when it lands. Drags aimed at an `<input>`, `<textarea>` or editable region inside the
1536
- target keep their native behaviour, and drops are separate from `targetProps`, so a textarea that
1537
- only spreads `targetProps` keeps its native text drop. Drop failures can't be retried (`retry()`
1538
- returns `not-retryable`); pass `state.source` to `describePasteError` to word them as drops.
1539
-
1540
- **Result.** `result.text`, `result.html`, `result.images` (verified raster images),
1541
- `result.files` (files copied in the OS file manager), `result.imageFiles` (the files that are
1542
- verified images, with their names kept, ready for `FormData`), and `result.items` with everything.
1543
-
1544
- ```ts
1545
- onPaste: ({ imageFiles }) => {
1546
- const form = new FormData();
1547
- for (const file of imageFiles) form.append("attachments", file, file.name);
1548
- void fetch("/api/attachments", { method: "POST", body: form });
1549
- };
1550
- ```
1551
-
1552
- A screenshot read with the paste button arrives as an unnamed `Blob` in `images` only; files
1553
- pasted from the OS file manager arrive in `files`, and the verified ones also in `imageFiles`.
1554
- Custom adapters resolve without `imageFiles` (`PasteReadResult`); the machine derives it.
1555
-
1556
- **Security.** Everything pasted is untrusted input, and the defaults are strict:
1557
-
1558
- - `accept` defaults to `['text']`. Ask for `'html'`, `'image'`, exact types like `'application/pdf'`, or `'image/*'` explicitly
1559
- - Images are verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP); a "PNG" that isn't one is dropped
1560
- - SVG is never matched by a wildcard, it must be listed exactly as `'image/svg+xml'` (it is scriptable XML)
1561
- - Application data is never matched by a wildcard either: web custom formats (`'web application/vnd.acme.rows+json'`)
1562
- and `+json` types must be listed exactly, and arrive as strings. `clipAccept()` lists them for you
1563
- - `maxBytes` (default 32 MiB) and `maxItems` (default 32) are enforced before anything is decoded.
1564
- `maxBytes` counts UTF-8 bytes on every path, so `'日本'` costs 6 bytes whether it arrives
1565
- from a paste event, `readText()` or `read()`
1566
- - **Never render `result.html` without a sanitiser** such as DOMPurify
1567
-
1568
- States: `idle` → `reading` → `read` | `error`. `paste()` is ignored while reading; a keyboard
1569
- paste or a drop supersedes an in-flight read. Results persist until `reset()` unless you set `resetAfterMs`.
1570
-
1571
- **Retry.** After a retryable failure of the Paste button (permission denied, page not focused),
1572
- `retry()` reads the clipboard again, up to `maxRetries` (default 3), and `canRetry` tells you
1573
- whether it can help. Call it from a click, like `paste()`. Keyboard-paste failures can't be
1574
- retried: the event's data is gone once it has been handled, so ask the user to paste again.
1575
-
1576
- ```tsx
1577
- const { paste, retry, canRetry, error } = usePaste({ accept: ["image"] });
1578
- // ...
1579
- {error && (canRetry
1580
- ? <button onClick={() => void retry()}>Allow clipboard access and try again</button>
1581
- : <p role="alert">{describePasteError(error)}</p>)}
1582
- ```
1583
-
1584
- ## States
1585
-
1586
- ```ts
1587
- type CopyState =
1588
- | { status: "idle" }
1589
- | { status: "copying"; payload: CopyPayload; retryCount: number }
1590
- | { status: "copied"; payload: CopyPayload; at: number }
1591
- | {
1592
- status: "error";
1593
- payload: CopyPayload | null;
1594
- error: CopyError;
1595
- retryCount: number;
1596
- };
1597
- ```
1598
-
1599
- | From | Event | To |
1600
- | ---------------------------------- | -------------- | ------------------------------------------------------ |
1601
- | any except `copying` | `copy()` | `copying` |
1602
- | `copying` | `copy()` | ignored (no double-fire) |
1603
- | `copying` | write resolves | `copied`, then `idle` after `resetAfterMs` |
1604
- | `copying` | write rejects | `error` |
1605
- | `error` (retryable, under the cap) | `retry()` | `copying` with the same payload, `retryCount + 1` |
1606
- | `error` (cap reached) | `retry()` | `error` with `max-retries-exceeded` |
1607
- | any | `reset()` | `idle`; in-flight work is aborted and its result discarded |
1608
- | any | unmount | timers cleared; in-flight work aborted, its result and callbacks dropped |
1609
-
1610
- ## Errors
1611
-
1612
- | `error.type` | Meaning | Retryable |
1613
- | ------------------------ | ------------------------------------------------------------------------------- | --------- |
1614
- | `unsupported` | No Clipboard API (old browser, server, locked webview) | No |
1615
- | `insecure-context` | Not HTTPS / localhost | No |
1616
- | `permission-denied` | Blocked by browser or user. Safari also reports a missing user gesture this way | Yes |
1617
- | `not-focused` | Document lost focus mid-copy | Yes |
1618
- | `invalid-payload` | Empty or malformed input, or a source function that threw | No |
1619
- | `unsupported-format` | This browser can't write that MIME type | No |
1620
- | `blob-generation-failed` | Image source threw, rejected or didn't return a Blob | Yes |
1621
- | `max-retries-exceeded` | `retry()` after `maxRetries` | No |
1622
- | `no-content` | Paste: nothing on the clipboard matches `accept` | No |
1623
- | `too-large` | Over `maxBytes`, `maxItems`, `maxPixels` or `maxLength` | No |
1624
- | `timeout` | Capture did not finish within `timeoutMs` | Yes |
1625
- | `aborted` | Your `AbortSignal` fired, or the operation was reset, superseded or unmounted | No |
1626
- | `unknown` | Anything unclassified | Yes |
1627
-
1628
- `error.message` is for developers. For users, call `describeCopyError(error)` /
1629
- `describePasteError(error)` or map `error.type` through your own translations.
1630
-
1631
- ## Options
1632
-
1633
- ```ts
1634
- useCopy({
1635
- resetAfterMs: 2000, // false or Infinity keeps "copied" until the next action
1636
- maxRetries: 3,
1637
- onCopy: (payload) => {}, // inline functions are fine; the latest one is always used
1638
- onError: (error, payload) => {},
1639
- onReset: () => {}, // reset() left a non-idle state (not the automatic reset)
1640
- onCancel: (reason) => {}, // "reset" | "disconnect": a copy in flight was cancelled
1641
- adapter: myAdapter, // swap the clipboard backend (tests, Electron, native bridges)
1642
- coordinator: null, // opt out of the surrounding <CopyGroup>
1643
- });
1644
- ```
1645
-
1646
- ## Cancellation
1647
-
1648
- Every copy and paste gets an `AbortSignal`. It fires when the operation is superseded, when you
1649
- call `reset()`, or when the component unmounts. The state machine already ignores late results;
1650
- the signal lets the *work* stop too, so a slow screenshot or a large clipboard decode doesn't keep
1651
- running (and holding memory) after nobody needs it.
1652
-
1653
- - **Image sources** receive it: `copy({ kind: "image", blob: (context) => render(context?.signal) })`
1654
- - **`captureSource` / `captureImage`** wire it up for you, combined with any `signal` you pass
1655
- - **Custom adapters** receive it as their last argument: `write(payload, { signal })`, `read(options, { signal })`
1656
-
1657
- The signal never fires after an operation has finished. If a cancelled operation fails anyway,
1658
- the promise you awaited resolves `{ status: "ignored", reason: "cancelled" }` rather than an
1659
- error, and `onError` is not called, so you never toast a failure for work the user walked away
1660
- from. Adapters and sources written before 1.2 keep working: the argument is optional.
1661
-
1662
- To observe cancellations (for analytics, or to clean up your own work), pass `onCancel`. It
1663
- receives why the operation stopped: `"reset"`, `"disconnect"` (the component unmounted) or, for
1664
- paste only, `"superseded"` (a paste event replaced a Clipboard API read). It fires once per
1665
- cancelled operation and never for one the library has already settled, so React Strict Mode's
1666
- extra mount/unmount does not trigger it. (If the clipboard resolves in the same tick as the
1667
- cancellation, the awaited promise may still report the result; state is not updated.) When
1668
- `reset()` cancels work, `onCancel("reset")` runs first, then `onReset()`.
1669
-
1670
- ```ts
1671
- usePaste({
1672
- onCancel: (reason) => analytics.track("paste_cancelled", { reason }),
1673
- onReset: () => setDraft(""),
1674
- });
1675
- ```
1676
-
1677
- ## CopyField API
1678
-
1679
- | Part | Renders | Notes |
1680
- | ------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
1681
- | `CopyField.Root` | `div` | Props: `value`, `label`, `copyOptions`, `messages`, `alwaysVisible`, `announce`, `pendingDelayMs`, `minPendingMs`. Forwards ref and all div props |
1682
- | `CopyField.Label` | `span` | Defaults to `label` |
1683
- | `CopyField.Value` | `span` | Defaults to the text value; pass children for anything else |
1684
- | `CopyField.Trigger` | `button type="button"` | Children can be a node or `({ status, displayStatus, state, revealed, canRetry }) => node` |
1685
- | `useCopyField()` | — | Full context, for building your own parts |
1686
-
1687
- Styling hooks on Root and Trigger: `data-display-state="idle | copying | copied | error"`
1688
- (style with this one), `data-state` (the raw state), and `data-revealed` while the trigger
1689
- should be visible.
1690
-
1691
- ### Translations
1692
-
1693
- ```tsx
1694
- <CopyField.Root
1695
- label="ईमेल"
1696
- value={email}
1697
- messages={{
1698
- copied: "कॉपी हो गया",
1699
- error: (e) => t(`copy.errors.${e.type}`),
1700
- triggerLabel: (label) => `${label} कॉपी करें`,
1701
- }}
1702
- />
1703
- ```
1704
-
1705
- ## PasteField
1706
-
1707
- The paste-side companion to `CopyField`. Drop it wherever you need a labelled, accessible paste target — a Zone that accepts keyboard paste and drop, a Trigger button that calls the Clipboard API, and a Status indicator that reflects the current state.
1708
-
1709
- ```tsx
1710
- import { PasteField } from "react-smart-copy";
1711
-
1712
- export function NotesPasteField() {
1713
- return (
1714
- <PasteField.Root
1715
- label="Notes"
1716
- pasteOptions={{ accept: ["text", "image"], onPaste: (result) => setNotes(result.text ?? "") }}
1717
- >
1718
- <PasteField.Label />
1719
- <PasteField.Status /> {/* "Ready" → "Reading…" → "Pasted" → "Error" */}
1720
- <PasteField.Zone /> {/* focusable paste target; accepts Ctrl/⌘+V and drops */}
1721
- <PasteField.Trigger /> {/* "Paste" → "Pasting…" → "Pasted" → "Retry" */}
1722
- <PasteField.Preview placeholder="Nothing pasted yet" /> {/* text, thumbnails, file names */}
1723
- </PasteField.Root>
1724
- );
1725
- }
1726
- ```
1727
-
1728
- | Part | Renders | Notes |
1729
- | -------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
1730
- | `PasteField.Root` | `div` | Props: `label`, `pasteOptions`, `messages`, `alwaysVisible`, `announce`, `pendingDelayMs`, `minPendingMs`. Forwards ref and all div props |
1731
- | `PasteField.Label` | `span` | Defaults to `label` |
1732
- | `PasteField.Status` | `span` | Text label per status. Defaults: `idle → "Ready"`, `reading → "Reading…"`, `read → "Pasted"`, `error → "Error"`. Custom `labels` prop |
1733
- | `PasteField.Zone` | `div role="region"` | Focusable paste target (`tabIndex=0`); handles Ctrl/⌘+V itself. Named "Paste area for {label}" via `aria-label` (override with `aria-label`, `aria-labelledby` or `messages.zoneLabel`). Sets `aria-keyshortcuts="Control+V Meta+V"`. `focusable={false}` removes tabIndex. Accepts drag-and-drop and sets `data-drag-over` while an accepted drag is over it; `droppable={false}` turns drops off. Announces `messages.dropped`, or your own `pasted` message if you only translated that one. Your own `onDrag*` / `onDrop` handlers run first, and calling `preventDefault()` in one takes over |
1734
- | `PasteField.Trigger` | `button type="button"` | Children can be a node or `({ status, displayStatus, state, revealed, canRetry }) => node`. `aria-busy` while reading; never `disabled`, so focus stays put |
1735
- | `PasteField.Preview` | `div` | What was pasted: text (truncated at `maxTextLength`, default 2000), image thumbnails (`imageAlt` for alt text) and non-image file names. **Never renders pasted HTML.** Shows `placeholder` until there is a result. Object URLs are revoked on change and unmount. Pass `({ result, imageUrls }) => node` to render it yourself |
1736
- | `usePasteField()` | — | Full context, for building your own parts inside `PasteField.Root` |
1737
-
1738
- Styling hooks on Root, Zone and Trigger: `data-display-state="idle | reading | read | error"`
1739
- (style with this one), `data-state` (the raw state), and `data-revealed` while the trigger should be visible.
1740
- The Zone also has `data-drag-over`:
1741
-
1742
- ```css
1743
- [data-zone][data-drag-over] { outline: 2px dashed currentColor; }
1744
- ```
1745
-
1746
- ### PasteField messages
1747
-
1748
- ```tsx
1749
- <PasteField.Root
1750
- label="Resume"
1751
- messages={{
1752
- pasted: (result) => `Got ${result.text?.length ?? 0} characters`,
1753
- dropped: (result) => `Added ${result.files.length} dropped files`,
1754
- error: (e, source) => t(`${source === "drop" ? "drop" : "paste"}.errors.${e.type}`),
1755
- triggerLabel: (label) => `Paste ${label}`,
1756
- zoneLabel: (label) => `Drop zone for ${label}`,
1757
- }}
1758
- />
1759
- ```
1760
-
1761
- ## Accessibility
1762
-
1763
- - The trigger is always a real button, reachable with Tab and activated with Enter or Space.
1764
- - Hidden actions stay in the DOM and the tab order. Hide them with opacity keyed off
1765
- `data-revealed`, never `display: none`, or keyboard users can't reach them.
1766
- - Keyboard focus (`:focus-visible`) pins the reveal; a mouse click doesn't.
1767
- - The trigger is never `disabled` while copying, because disabling a focused button
1768
- throws keyboard focus back to the page.
1769
- - A live region is mounted before its first message, so the first announcement is not missed.
1770
- - The trigger's accessible name stays stable ("Copy Email"); the result is announced
1771
- separately, so screen readers don't re-read the button.
1772
- - The default trigger's crossfade animation is disabled when `prefers-reduced-motion` is set. Respect it in your own CSS too.
1773
-
1774
- ## Next.js and SSR
1775
-
1776
- The React entry ships with `"use client"`, so import it directly from Server Components.
1777
- Nothing touches `window` during render: the server and the first client render are both
1778
- `idle` and not revealed, so there are no hydration mismatches.
1779
-
1780
- `react-smart-copy/core` is framework-agnostic and safe to import anywhere, and so is every other
1781
- entry point (`/table`, `/markdown`, `/rich`, ...): only the main entry imports React, and the build
1782
- checks that no other entry reaches it.
1783
-
1784
- All entry points share one copy of the core. Using several of them loads it once, and a
1785
- `CopyFailure` from any of them is an `instanceof` the one exported by `react-smart-copy` and
1786
- `react-smart-copy/core`.
1787
-
1788
- ## Without React
1789
-
1790
- ```ts
1791
- import { createCopyMachine } from "react-smart-copy/core";
1792
-
1793
- const machine = createCopyMachine({ resetAfterMs: 1500 });
1794
- machine.subscribe(() => render(machine.getSnapshot()));
1795
- button.addEventListener("click", () => void machine.copy(input.value));
1796
- ```
1797
-
1798
- Paste and drop work the same way with `createPasteMachine`:
1799
-
1800
- ```ts
1801
- import { canAcceptDrag, createPasteMachine, resolvePasteReadOptions } from "react-smart-copy/core";
1802
-
1803
- const options = { accept: ["image"] } as const;
1804
- const paster = createPasteMachine(options);
1805
- zone.addEventListener("paste", (event) => void paster.pasteEvent(event));
1806
- zone.addEventListener("dragover", (event) => {
1807
- if (!event.dataTransfer) return;
1808
- event.preventDefault(); // claim it, then cancel drops you don't accept
1809
- event.dataTransfer.dropEffect = canAcceptDrag(event.dataTransfer, resolvePasteReadOptions(options)) ? "copy" : "none";
1810
- });
1811
- zone.addEventListener("drop", (event) => void paster.dropEvent(event));
1812
- ```
1813
-
1814
- ## Testing
1815
-
1816
- `react-smart-copy/testing` ships utilities that keep consumer test suites
1817
- green across library upgrades. Every `PasteResult` field added in v1.3 and
1818
- v1.4 required updating hand-written result literals — these helpers absorb
1819
- future additions at the library level.
1820
-
1821
- ### `createPasteResult(init?)`
1822
-
1823
- Builds a complete `PasteResult` from partial input. Every field defaults
1824
- sensibly, so adding a required field in a future release won't touch your tests.
1825
-
1826
- ```ts
1827
- import { createPasteResult } from "react-smart-copy/testing";
1828
-
1829
- const result = createPasteResult({ text: "hello" });
1830
- // result.source → 'clipboard'
1831
- // result.text → 'hello'
1832
- // result.html → null
1833
- // result.images → []
1834
- // result.files → []
1835
- // result.imageFiles → []
1836
- // result.items → [{ type: 'text/plain', data: 'hello' }]
1837
- ```
1838
-
1839
- ### `createMockPasteAdapter()`
1840
-
1841
- A controllable `PasteAdapter` backed by a result queue. Queue entries
1842
- are consumed FIFO; an empty queue rejects with `'no-content'`.
1843
-
1844
- ```ts
1845
- import { createMockPasteAdapter, createPasteResult } from "react-smart-copy/testing";
1846
- import { createPasteMachine } from "react-smart-copy/core";
1847
-
1848
- const mock = createMockPasteAdapter();
1849
- mock.queueResult(createPasteResult({ text: "hello" }));
1850
- mock.queueError(createCopyError("permission-denied", "blocked"));
1851
-
1852
- const machine = createPasteMachine({ adapter: mock.adapter });
1853
- await machine.paste(); // → { status: 'read', result: … }
1854
- expect(mock.readCount()).toBe(1);
1855
- ```
1856
-
1857
- ### `createMockClipboardAdapter()`
1858
-
1859
- A controllable `ClipboardAdapter` for copy tests. Captures the last payload
1860
- the machine sent so you can assert on it.
1861
-
1862
- ```ts
1863
- import { createMockClipboardAdapter } from "react-smart-copy/testing";
1864
- import { createCopyMachine } from "react-smart-copy/core";
1865
-
1866
- const mock = createMockClipboardAdapter();
1867
- mock.queueSuccess();
1868
-
1869
- const machine = createCopyMachine({ adapter: mock.adapter });
1870
- await machine.copy("hello");
1871
- expect(mock.lastPayload()).toEqual({ kind: "text", value: "hello" });
1872
- ```
1873
-
1874
- The subpackage also re-exports the types most often needed in test files:
1875
- `CopyFailure`, `CopyError`, `PasteResult`, `PasteSource`, `ClipboardAdapter`,
1876
- and more — so a single import covers both utilities and type annotations.
1877
-
1878
- ## Custom adapters
1879
-
1880
- ```ts
1881
- import {
1882
- CopyFailure,
1883
- createCopyError,
1884
- type ClipboardAdapter,
1885
- } from "react-smart-copy/core";
1886
-
1887
- const electronAdapter: ClipboardAdapter = {
1888
- write: async (payload, context) => {
1889
- if (payload.kind !== "text")
1890
- throw new CopyFailure(createCopyError("unsupported-format", "Text only"));
1891
- window.electron.clipboard.writeText(payload.value);
1892
- // context?.signal aborts on reset / unmount: check it before any slow follow-up work.
1893
- },
1894
- };
1895
- ```
1896
-
1897
- Start the platform write before any `await`, or browsers drop the user gesture.
1898
-
1899
- ## Browser support
1900
-
1901
- Plain text works wherever `navigator.clipboard.writeText` exists: Chromium 66+, Firefox 63+,
1902
- Safari 13.1+. Rich HTML, PNG images and multi-format need `ClipboardItem`: Chromium 86+,
1903
- Safari 13.1+, Firefox 127+. Keyboard paste (`targetProps`, `listenOnDocument`) and drag-and-drop
1904
- (`dropTargetProps`, `PasteField.Zone`) work in every modern browser. The Paste button needs `navigator.clipboard.readText` (Chromium 66+, Safari 13.1+,
1905
- Firefox 125+) or `read()` for images (Chromium 86+, Safari 13.1+, Firefox 127+). Web custom formats
1906
- (`react-smart-copy/structured`'s first carrier) need Chromium 104+; elsewhere the HTML carrier is used. Check MDN for
1907
- embedded webviews. Where a capability is missing you get a typed error, never a silent success.
1908
-
1909
- ## Roadmap
1910
-
1911
- - ~~**0.2** `usePaste`, `<CopyGroup>`, SVG/DOM capture~~ shipped
1912
- - ~~**1.0** Frozen API, SSR / security / accessibility audit~~ shipped
1913
- - ~~**1.1** `PasteField`~~ shipped
1914
- - ~~**1.2** Paste `retry()`, cancellation with `AbortSignal`, `PasteField.Preview`~~ shipped
1915
- - ~~**1.3** `onReset` / `onCancel` callbacks, UTF-8 `maxBytes` on every paste path, `PasteResult.imageFiles`~~ shipped
1916
- - ~~**1.4** Drag-and-drop through the paste pipeline: `dropTargetProps`, `isDragOver`, droppable `PasteField.Zone`~~ shipped
1917
- - ~~**1.6** `react-smart-copy/testing` — mock adapters and result builders so consumer tests stay green across releases~~ shipped
1918
- - ~~**1.7** `useCopyInterceptor` / `registerCopyInterceptor` — attribution, redaction and no-copy zones for native Ctrl/⌘+C~~ shipped
1919
- - ~~**1.8** `useDragCopy` / `registerDragCopy` — populate `DataTransfer` on drag-start; no Clipboard API needed~~ shipped
1920
- - ~~**1.9** `react-smart-copy/table` — Excel- and Sheets-ready copy and paste, AG Grid and TanStack Table adapters, typed record import~~ shipped
1921
- - ~~**1.10** `react-smart-copy/structured` — typed, versioned, validated application data on the clipboard~~ shipped
1922
- - ~~**1.11** `react-smart-copy/markdown` — paste rich content as Markdown, with undo intact~~ shipped
1923
- - ~~**1.12** `react-smart-copy/code` — copy code blocks and sessions cleanly, paste code safely, detect Trojan Source and homoglyphs~~ shipped
1924
- - ~~**1.13** `react-smart-copy/image` — pasted images without location or camera metadata, fitted to size and byte limits~~ shipped
1925
- - ~~**1.14** `react-smart-copy/link` — links that paste well everywhere, links to a passage, tracking parameters removed, paste a URL over text to make a link~~ shipped
1926
- - ~~**1.15** `react-smart-copy/share` — the share sheet on phones, a copied titled link everywhere else, with honest outcomes~~ shipped
1927
- - ~~**1.16** `react-smart-copy/color` — copy and paste colours in every CSS format, CSS gamut mapping, WCAG contrast~~ shipped
1928
- - ~~**1.17** `react-smart-copy/rich` — styled content that pastes as it looks in mail, Docs, Word and Slack, for buttons and Ctrl/⌘+C~~ shipped
1929
- - ~~**1.18** One shared copy of the core across entry points: smaller bundles when you use several modules, and one `CopyFailure` class~~ shipped
1930
- - ~~**1.19** `react-smart-copy/rich`, paste side: paste from Word, Google Docs and web pages into rich-text editors as clean, safe HTML~~ shipped
1931
- - ~~**1.20** `react-smart-copy/files` — take pasted and dropped files and folders safely: types from content, risky files rejected, safe names, limits~~ shipped
1932
- - ~~**1.21** `react-smart-copy/secrets` — find and redact API keys, tokens, private keys, passwords, cards and IBANs in pastes and copies~~ shipped
1933
- - ~~**1.22** `react-smart-copy/otp` and `useOtpField` — one-time code fields filled by typing, pasting, SMS autofill and WebOTP, and codes read from pasted messages~~ shipped
1934
- - ~~**1.23** `react-smart-copy/number` — numbers and amounts pasted and copied exactly in any locale's format, with currencies, percent and accounting negatives~~ shipped
1935
- - ~~**1.24** `react-smart-copy/email` — lists of e-mail recipients pasted from Outlook, Gmail and spreadsheets, checked for lookalike domains and hidden characters, and copied back with names~~ shipped
1936
-
1937
- Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://suprabhat02.github.io/react-smart-copy/project/releases/).
197
+ copy(() => linkPayload({ url: issue.url, title: issue.title }, { clean: true })); // titled in Slack, Docs and Notion
198
+ ```
199
+
200
+ ## Production notes
201
+
202
+ - **Tree-shaking.** The package is ESM and CommonJS, `sideEffects: false`, with one entry
203
+ point per module. A bundler keeps only what you import. Shared code (the copy and paste
204
+ core, `CopyFailure`) is emitted once and shared by every entry point.
205
+ - **Client boundary.** Only the React entry is a client module (`"use client"`). Server code
206
+ can import every other entry point, and the parsers (`/number`, `/email`, `/secrets`,
207
+ `/otp`, `/table`, `/markdown`, `/code`) work the same on a server.
208
+ - **Types.** Strict TypeScript with `exactOptionalPropertyTypes`, explicit types on every
209
+ export, and declarations checked by consumers on TypeScript 5.0, 6 and 7 with both
210
+ `bundler` and `node16` resolution.
211
+ - **Hostile input.** Every parser caps its input and runs in linear time. The limits are listed
212
+ in [Performance and limits](https://suprabhat02.github.io/react-smart-copy/guides/performance/).
213
+ - **Supply chain.** No runtime dependencies. Releases are published from CI with npm
214
+ provenance, and each GitHub release carries the signed tarball.
215
+
216
+ ## Guides
217
+
218
+ - [Next.js and SSR](https://suprabhat02.github.io/react-smart-copy/guides/ssr/)
219
+ - [Accessibility](https://suprabhat02.github.io/react-smart-copy/guides/accessibility/)
220
+ - [Security](https://suprabhat02.github.io/react-smart-copy/guides/security/)
221
+ - [Performance and limits](https://suprabhat02.github.io/react-smart-copy/guides/performance/)
222
+ - [Testing your app](https://suprabhat02.github.io/react-smart-copy/guides/testing/)
223
+ - [Custom adapters](https://suprabhat02.github.io/react-smart-copy/guides/custom-adapters/)
224
+ - [Without React](https://suprabhat02.github.io/react-smart-copy/guides/without-react/)
225
+ - [Errors](https://suprabhat02.github.io/react-smart-copy/reference/errors/) and [states](https://suprabhat02.github.io/react-smart-copy/reference/states/)
226
+ - [Browser support](https://suprabhat02.github.io/react-smart-copy/start/browser-support/)
227
+
228
+ ## Releases and roadmap
229
+
230
+ What changed in each version: [CHANGELOG.md](./CHANGELOG.md) or the
231
+ [releases page](https://suprabhat02.github.io/react-smart-copy/project/releases/). What comes
232
+ next: the [roadmap](https://suprabhat02.github.io/react-smart-copy/project/roadmap/).
1938
233
 
1939
234
  ## Development
1940
235
 
1941
236
  ```bash
1942
237
  npm install
1943
- npm run verify # lint, types, tests at 100% coverage, build, publint + attw, consumer types, size budgets
238
+ npm run verify # lint, types, tests at 100% coverage, build, package and docs checks, size budgets
239
+ npm run bench # parser benchmarks
1944
240
  npm run changeset # describe your change for the changelog
1945
241
  npm run docs:install # once: the docs site has its own lockfile, in docs/
1946
242
  npm run docs:dev # the docs, with live demos, at http://localhost:4321/react-smart-copy/