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