react-smart-copy 0.1.0 → 0.2.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 CHANGED
@@ -1,9 +1,14 @@
1
1
  # react-smart-copy
2
2
 
3
+ [![npm](https://img.shields.io/npm/v/react-smart-copy)](https://www.npmjs.com/package/react-smart-copy)
4
+ [![npm downloads](https://img.shields.io/npm/dm/react-smart-copy)](https://www.npmjs.com/package/react-smart-copy)
5
+ [![CI](https://github.com/suprabhat02/react-smart-copy/actions/workflows/ci.yml/badge.svg)](https://github.com/suprabhat02/react-smart-copy/actions/workflows/ci.yml)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
7
+
3
8
  **[Live demo and docs](https://suprabhat02.github.io/react-smart-copy/)**
4
9
 
5
- Headless, type-safe **copy interactions** for React. Not just a clipboard call: the
6
- whole interaction around it — copying, copied, failed, retry — with honest errors,
10
+ Headless, type-safe **clipboard interactions** for React. Not just a clipboard call: the
11
+ whole interaction around it — copying, copied, failed, retry, pasting — with honest errors,
7
12
  hover/focus/touch reveal, and screen-reader announcements built in.
8
13
 
9
14
  ```
@@ -12,8 +17,11 @@ Phone +91 98xxx xxxxx [Copy]
12
17
  ID PLT-29018 [Copy]
13
18
  ```
14
19
 
15
- - **~2.9 kB** for `useCopy`, **~4.7 kB** for everything (min + brotli), zero dependencies
16
- - Text, rich HTML (with plain-text fallback), PNG images, JSON, multi-format
20
+ - **~3.1 kB** for `useCopy`, **~5.1 kB** for everything copy (min + brotli), zero dependencies
21
+ - Copy text, rich HTML (with plain-text fallback), PNG images, JSON, multi-format
22
+ - **Paste** text, HTML and screenshots with `usePaste`: a Paste button or Ctrl/⌘+V, no permission prompt for keyboard paste
23
+ - **`<CopyGroup>`**: only one row shows "Copied" at a time
24
+ - **`react-smart-copy/capture`**: copy an `<svg>` or any piece of your UI as a PNG
17
25
  - Every failure is a typed, classified error. Nothing silently no-ops
18
26
  - Unstyled. Works with Tailwind, CSS modules, CSS-in-JS, shadcn, MUI, Ant Design
19
27
  - SSR / Next.js App Router safe, React 18 and 19, StrictMode-proof
@@ -29,7 +37,8 @@ This package only promises what browsers actually support.
29
37
  | Images | ✅ PNG only | `image/png` is the only format with reliable cross-browser write support. Convert with `canvas.toBlob(cb, 'image/png')` |
30
38
  | JSON | ✅ | Serialised to text. JSON is not a native clipboard format |
31
39
  | Several formats at once | ✅ | `kind: 'multi'`; each MIME type is checked with `ClipboardItem.supports()` first |
32
- | A section of your UI as an image | ⚠️ Bring a rasteriser | Browsers have no "screenshot this element" API. Pass a function that renders to a PNG Blob (e.g. with `modern-screenshot` or `html2canvas`) |
40
+ | SVG (icons, charts, logos) | ✅ as PNG | `svgToPngBlob()` from `react-smart-copy/capture` rasterises natively, no dependency. Raw SVG is not a clipboard image format |
41
+ | 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 |
33
42
  | Files (PDF, DOCX, ZIP) | ❌ | Not writable to the system clipboard by any browser API |
34
43
  | Anything over plain HTTP | ❌ | The Clipboard API requires HTTPS or `localhost`. You get an `insecure-context` error, not a silent failure |
35
44
 
@@ -152,27 +161,125 @@ copy(() => editor.getValue()); // resolved at click time, always the latest valu
152
161
 
153
162
  Pass a **function** that produces the Blob. It is called synchronously inside the click,
154
163
  and its promise is handed straight to `ClipboardItem`, which is what Safari needs to allow
155
- asynchronous image generation.
164
+ asynchronous image generation. The `react-smart-copy/capture` entry does this for you.
165
+
166
+ ## Copying SVG and UI as images
167
+
168
+ `react-smart-copy/capture` is a separate, opt-in entry (~3.3 kB, no dependencies). It never
169
+ ships in your bundle unless you import it.
156
170
 
157
171
  ```tsx
158
- import { domToBlob } from "modern-screenshot"; // your choice of rasteriser
172
+ import { captureImage, svgToPngBlob } from "react-smart-copy/capture";
173
+ import { domToBlob } from "modern-screenshot"; // any rasteriser you like, for HTML
174
+
175
+ // Any <svg> (chart, logo, icon): rasterised natively, no rasteriser needed.
176
+ <CopyField.Root label="Chart" value={captureImage(() => chartRef.current)}>
177
+ <CopyField.Trigger>Copy chart</CopyField.Trigger>
178
+ </CopyField.Root>;
159
179
 
180
+ // Any HTML element (invoice card, receipt): bring the rasteriser.
160
181
  <CopyField.Root
161
- label="Invoice preview"
162
- value={{
163
- kind: "image",
164
- blob: () => domToBlob(ref.current!, { type: "image/png" }),
165
- }}
182
+ label="Invoice"
183
+ value={captureImage(() => invoiceRef.current, {
184
+ rasterize: (node, { scale }) => domToBlob(node, { scale }),
185
+ background: "#ffffff",
186
+ })}
166
187
  >
167
188
  <CopyField.Trigger>Copy as image</CopyField.Trigger>
168
189
  </CopyField.Root>;
190
+
191
+ // Or by hand, e.g. from SVG markup:
192
+ const png = await svgToPngBlob('<svg viewBox="0 0 24 24">…</svg>', { width: 256 });
193
+ ```
194
+
195
+ What you get beyond calling a rasteriser yourself:
196
+
197
+ - **Always a real PNG.** Output is verified from its bytes; JPEG/WebP/canvas/data-URL outputs are re-encoded, anything else is refused
198
+ - **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`
199
+ - **Deadlines.** `timeoutMs` (default 15 s) and an optional `signal: AbortSignal`; the rasteriser receives a signal it can honour
200
+ - **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
201
+ - **Crisp by default.** `scale: 2`; pass `window.devicePixelRatio` or anything up to 10
202
+
203
+ Failures are classified like everything else: `invalid-payload` (no element / unknown size),
204
+ `unsupported`, `too-large`, `timeout`, `aborted`, `blob-generation-failed`. Rasterisers have
205
+ real limits (cross-origin images taint the canvas, web fonts must be loaded, `<video>` and
206
+ `<iframe>` rarely render), so offer a text fallback when capture fails.
207
+
208
+ ## Only one "Copied" at a time
209
+
210
+ Wrap a table or list in `<CopyGroup>`. A new successful copy returns the previously copied
211
+ row to idle, because the clipboard no longer holds its value. A failed copy releases nothing.
212
+
213
+ ```tsx
214
+ import { CopyField, CopyGroup } from "react-smart-copy";
215
+
216
+ <CopyGroup>
217
+ {rows.map((row) => (
218
+ <CopyField.Root key={row.id} value={row.email} label="Email">
219
+ <CopyField.Value />
220
+ <CopyField.Trigger />
221
+ </CopyField.Root>
222
+ ))}
223
+ </CopyGroup>;
169
224
  ```
170
225
 
171
- Rasterisers have real limits (cross-origin images taint the canvas, web fonts must be
172
- loaded, `<video>` and `<iframe>` rarely render). When one fails you get a
173
- `blob-generation-failed` error, so you can offer a text fallback instead.
226
+ It works for `useCopy()` too. Opt one field out with `copyOptions={{ coordinator: null }}`.
227
+ To share one group across React roots or with vanilla code, create it yourself:
228
+ `const coordinator = createCopyCoordinator()`, then `<CopyGroup coordinator={coordinator}>`
229
+ and `createCopyMachine({ coordinator })`.
230
+
231
+ ## Pasting
232
+
233
+ `usePaste` is the other half: read what the user pasted, with the same honest states.
234
+
235
+ ```tsx
236
+ import { describePasteError, usePaste } from "react-smart-copy";
237
+
238
+ function AvatarDrop() {
239
+ const { paste, status, result, error, targetProps } = usePaste<HTMLDivElement>({
240
+ accept: ["image"],
241
+ onPaste: (result) => {
242
+ const [image] = result.images;
243
+ if (image) void upload(image);
244
+ },
245
+ });
246
+
247
+ return (
248
+ <div {...targetProps} tabIndex={0}>
249
+ Press Ctrl/⌘+V to paste a screenshot, or
250
+ <button onClick={() => void paste()}>Paste from clipboard</button>
251
+ {error && <p role="alert">{describePasteError(error)}</p>}
252
+ </div>
253
+ );
254
+ }
255
+ ```
256
+
257
+ Two ways in, one state machine:
258
+
259
+ | Path | How | Permission prompt |
260
+ | ---- | --- | ----------------- |
261
+ | Keyboard paste | Spread `targetProps` on an element, or `listenOnDocument: true` for the whole page | **None**: the data is in the event |
262
+ | Paste button | Call `paste()` from a click | Browser may ask the user once |
263
+
264
+ Events without accepted content are left alone, so normal typing and pasting into your inputs
265
+ keeps working. Events with accepted content are `preventDefault()`-ed (opt out with
266
+ `preventDefault: false`).
267
+
268
+ **Result.** `result.text`, `result.html`, `result.images` (verified raster images),
269
+ `result.files` (files copied in the OS file manager), and `result.items` with everything.
270
+
271
+ **Security.** Everything pasted is untrusted input, and the defaults are strict:
272
+
273
+ - `accept` defaults to `['text']`. Ask for `'html'`, `'image'`, exact types like `'application/pdf'`, or `'image/*'` explicitly
274
+ - Images are verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP); a "PNG" that isn't one is dropped
275
+ - SVG is never matched by a wildcard, it must be listed exactly as `'image/svg+xml'` (it is scriptable XML)
276
+ - `maxBytes` (default 32 MiB) and `maxItems` (default 32) are enforced before anything is decoded
277
+ - **Never render `result.html` without a sanitiser** such as DOMPurify
278
+
279
+ States: `idle` → `reading` → `read` | `error`. `paste()` is ignored while reading; a keyboard
280
+ paste supersedes an in-flight read. Results persist until `reset()` unless you set `resetAfterMs`.
174
281
 
175
- ## States
282
+ ## States## States
176
283
 
177
284
  ```ts
178
285
  type CopyState =
@@ -210,10 +317,14 @@ type CopyState =
210
317
  | `unsupported-format` | This browser can't write that MIME type | No |
211
318
  | `blob-generation-failed` | Image source threw, rejected or didn't return a Blob | Yes |
212
319
  | `max-retries-exceeded` | `retry()` after `maxRetries` | No |
320
+ | `no-content` | Paste: nothing on the clipboard matches `accept` | No |
321
+ | `too-large` | Over `maxBytes`, `maxItems`, `maxPixels` or `maxLength` | No |
322
+ | `timeout` | Capture did not finish within `timeoutMs` | Yes |
323
+ | `aborted` | Your `AbortSignal` fired | No |
213
324
  | `unknown` | Anything unclassified | Yes |
214
325
 
215
- `error.message` is for developers. For users, call `describeCopyError(error)` or map
216
- `error.type` through your own translations.
326
+ `error.message` is for developers. For users, call `describeCopyError(error)` /
327
+ `describePasteError(error)` or map `error.type` through your own translations.
217
328
 
218
329
  ## Options
219
330
 
@@ -224,6 +335,7 @@ useCopy({
224
335
  onCopy: (payload) => {}, // inline functions are fine; the latest one is always used
225
336
  onError: (error, payload) => {},
226
337
  adapter: myAdapter, // swap the clipboard backend (tests, Electron, native bridges)
338
+ coordinator: null, // opt out of the surrounding <CopyGroup>
227
339
  });
228
340
  ```
229
341
 
@@ -310,13 +422,14 @@ Start the platform write before any `await`, or browsers drop the user gesture.
310
422
 
311
423
  Plain text works wherever `navigator.clipboard.writeText` exists: Chromium 66+, Firefox 63+,
312
424
  Safari 13.1+. Rich HTML, PNG images and multi-format need `ClipboardItem`: Chromium 86+,
313
- Safari 13.1+, Firefox 127+. Check MDN for embedded webviews. Where a capability is missing
314
- you get a typed error, never a silent success.
425
+ Safari 13.1+, Firefox 127+. Keyboard paste (`targetProps`, `listenOnDocument`) works in every
426
+ modern browser. The Paste button needs `navigator.clipboard.readText` (Chromium 66+, Safari 13.1+,
427
+ Firefox 125+) or `read()` for images (Chromium 86+, Safari 13.1+, Firefox 127+). Check MDN for
428
+ embedded webviews. Where a capability is missing you get a typed error, never a silent success.
315
429
 
316
430
  ## Roadmap
317
431
 
318
- - **0.2** `usePaste` (text and pasted OS screenshots) and an optional DOM-capture adapter
319
- - **0.3** Coordinated state across many fields (only one shows "Copied" at a time)
432
+ - ~~**0.2** `usePaste`, `<CopyGroup>`, SVG/DOM capture~~ shipped
320
433
  - **1.0** Frozen API, full external accessibility audit
321
434
 
322
435
  ## Development
@@ -328,7 +441,7 @@ npm run changeset # describe your change for the changelog
328
441
  npm run site:preview # docs site at http://localhost:3000
329
442
  ```
330
443
 
331
- Releases are automated: merging the "Version Packages" PR publishes to npm through
444
+ Releases are automated: merging the "chore: release" PR publishes to npm through
332
445
  trusted publishing with provenance. No long-lived npm token is stored in the repo.
333
446
 
334
447
  ## License