react-smart-copy 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shubh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,336 @@
1
+ # react-smart-copy
2
+
3
+ **[Live demo and docs](https://suprabhat02.github.io/react-smart-copy/)**
4
+
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,
7
+ hover/focus/touch reveal, and screen-reader announcements built in.
8
+
9
+ ```
10
+ Email shubh@example.com [Copy] → Copied ✓
11
+ Phone +91 98xxx xxxxx [Copy]
12
+ ID PLT-29018 [Copy]
13
+ ```
14
+
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
17
+ - Every failure is a typed, classified error. Nothing silently no-ops
18
+ - Unstyled. Works with Tailwind, CSS modules, CSS-in-JS, shadcn, MUI, Ant Design
19
+ - SSR / Next.js App Router safe, React 18 and 19, StrictMode-proof
20
+
21
+ ## What it can and cannot copy
22
+
23
+ This package only promises what browsers actually support.
24
+
25
+ | Content | Supported | Notes |
26
+ | -------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
27
+ | Plain text | ✅ | Everywhere with the async Clipboard API |
28
+ | Rich HTML | ✅ | Always paired with a required plain-text fallback. Degrades to text when `ClipboardItem` is missing |
29
+ | Images | ✅ PNG only | `image/png` is the only format with reliable cross-browser write support. Convert with `canvas.toBlob(cb, 'image/png')` |
30
+ | JSON | ✅ | Serialised to text. JSON is not a native clipboard format |
31
+ | 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`) |
33
+ | Files (PDF, DOCX, ZIP) | ❌ | Not writable to the system clipboard by any browser API |
34
+ | Anything over plain HTTP | ❌ | The Clipboard API requires HTTPS or `localhost`. You get an `insecure-context` error, not a silent failure |
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ npm install react-smart-copy
40
+ ```
41
+
42
+ ## Quick start
43
+
44
+ ```tsx
45
+ import { CopyField } from "react-smart-copy";
46
+
47
+ export function ContactRow() {
48
+ return (
49
+ <CopyField.Root
50
+ value="shubh@example.com"
51
+ label="Email"
52
+ className="group flex items-center gap-3"
53
+ >
54
+ <CopyField.Label className="w-20 text-sm text-gray-500" />
55
+ <CopyField.Value className="font-mono" />
56
+ <CopyField.Trigger className="opacity-0 transition-opacity group-data-[revealed]:opacity-100 focus-visible:opacity-100 motion-reduce:transition-none">
57
+ {({ displayStatus }) =>
58
+ displayStatus === "copied"
59
+ ? "Copied ✓"
60
+ : displayStatus === "error"
61
+ ? "Retry"
62
+ : "Copy"
63
+ }
64
+ </CopyField.Trigger>
65
+ </CopyField.Root>
66
+ );
67
+ }
68
+ ```
69
+
70
+ That one component gives you: a real `<button type="button">` named "Copy Email", reveal on
71
+ mouse hover, keyboard focus and touch (always visible on devices that can't hover), a
72
+ polite "Copied to clipboard" announcement for screen readers, ignored double-clicks, and
73
+ automatic return to idle after 2 seconds.
74
+
75
+ ## No flicker
76
+
77
+ A text copy takes 1–5 ms, so rendering the raw state flashes "Copying…" for one frame and
78
+ resizes the button. Two statuses solve this:
79
+
80
+ - `status` / `data-state`: the real, instantaneous state. Use it for logic and tests.
81
+ - `displayStatus` / `data-display-state`: what to render. "Copying…" only appears when a
82
+ copy takes longer than `pendingDelayMs` (150 ms), then stays at least `minPendingMs`
83
+ (400 ms) so it can't blink.
84
+
85
+ The default trigger label also stacks every state in one grid cell, so its width never
86
+ changes, and crossfades between them (off under `prefers-reduced-motion`).
87
+
88
+ ```tsx
89
+ <CopyField.Root
90
+ value={big}
91
+ label="Report"
92
+ pendingDelayMs={200}
93
+ minPendingMs={500}
94
+ >
95
+ …
96
+ </CopyField.Root>;
97
+
98
+ // With the bare hook:
99
+ const { status } = useCopy();
100
+ const shown = useDisplayStatus(status);
101
+ ```
102
+
103
+ ## Just the hook
104
+
105
+ ```tsx
106
+ import { useCopy } from "react-smart-copy";
107
+
108
+ function InvoiceNumber({ id }: { id: string }) {
109
+ const { copy, status, error } = useCopy({ resetAfterMs: 1500 });
110
+
111
+ return (
112
+ <button type="button" onClick={() => void copy(id)} data-state={status}>
113
+ {status === "copied" ? "Copied" : "Copy"}
114
+ {error && <span role="alert">{error.type}</span>}
115
+ </button>
116
+ );
117
+ }
118
+ ```
119
+
120
+ `copy()` never rejects. It resolves to a `CopyOutcome` you can branch on:
121
+
122
+ ```ts
123
+ const outcome = await copy(id);
124
+ if (outcome.status === "error") track("copy_failed", outcome.error.type);
125
+ ```
126
+
127
+ ## Payloads
128
+
129
+ A bare string is shorthand for text. Everything else is a discriminated union, so the
130
+ compiler stops you from, say, copying HTML without a plain-text fallback.
131
+
132
+ ```ts
133
+ copy("PLT-29018");
134
+ copy({
135
+ kind: "html",
136
+ html: "<b>INV-29018</b> · ₹12,400",
137
+ text: "INV-29018 · ₹12,400",
138
+ });
139
+ copy({ kind: "json", value: row, pretty: true });
140
+ copy({ kind: "image", blob: () => chartToPngBlob() });
141
+ copy({
142
+ kind: "multi",
143
+ items: [
144
+ { mimeType: "text/plain", data: "INV-29018" },
145
+ { mimeType: "text/html", data: "<b>INV-29018</b>" },
146
+ ],
147
+ });
148
+ copy(() => editor.getValue()); // resolved at click time, always the latest value
149
+ ```
150
+
151
+ ### Copying an image, including a piece of your UI
152
+
153
+ Pass a **function** that produces the Blob. It is called synchronously inside the click,
154
+ and its promise is handed straight to `ClipboardItem`, which is what Safari needs to allow
155
+ asynchronous image generation.
156
+
157
+ ```tsx
158
+ import { domToBlob } from "modern-screenshot"; // your choice of rasteriser
159
+
160
+ <CopyField.Root
161
+ label="Invoice preview"
162
+ value={{
163
+ kind: "image",
164
+ blob: () => domToBlob(ref.current!, { type: "image/png" }),
165
+ }}
166
+ >
167
+ <CopyField.Trigger>Copy as image</CopyField.Trigger>
168
+ </CopyField.Root>;
169
+ ```
170
+
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.
174
+
175
+ ## States
176
+
177
+ ```ts
178
+ type CopyState =
179
+ | { status: "idle" }
180
+ | { status: "copying"; payload: CopyPayload; retryCount: number }
181
+ | { status: "copied"; payload: CopyPayload; at: number }
182
+ | {
183
+ status: "error";
184
+ payload: CopyPayload | null;
185
+ error: CopyError;
186
+ retryCount: number;
187
+ };
188
+ ```
189
+
190
+ | From | Event | To |
191
+ | ---------------------------------- | -------------- | ------------------------------------------------------ |
192
+ | any except `copying` | `copy()` | `copying` |
193
+ | `copying` | `copy()` | ignored (no double-fire) |
194
+ | `copying` | write resolves | `copied`, then `idle` after `resetAfterMs` |
195
+ | `copying` | write rejects | `error` |
196
+ | `error` (retryable, under the cap) | `retry()` | `copying` with the same payload, `retryCount + 1` |
197
+ | `error` (cap reached) | `retry()` | `error` with `max-retries-exceeded` |
198
+ | any | `reset()` | `idle`; an in-flight result is discarded |
199
+ | any | unmount | timers cleared; in-flight result and callbacks dropped |
200
+
201
+ ## Errors
202
+
203
+ | `error.type` | Meaning | Retryable |
204
+ | ------------------------ | ------------------------------------------------------------------------------- | --------- |
205
+ | `unsupported` | No Clipboard API (old browser, server, locked webview) | No |
206
+ | `insecure-context` | Not HTTPS / localhost | No |
207
+ | `permission-denied` | Blocked by browser or user. Safari also reports a missing user gesture this way | Yes |
208
+ | `not-focused` | Document lost focus mid-copy | Yes |
209
+ | `invalid-payload` | Empty or malformed input, or a source function that threw | No |
210
+ | `unsupported-format` | This browser can't write that MIME type | No |
211
+ | `blob-generation-failed` | Image source threw, rejected or didn't return a Blob | Yes |
212
+ | `max-retries-exceeded` | `retry()` after `maxRetries` | No |
213
+ | `unknown` | Anything unclassified | Yes |
214
+
215
+ `error.message` is for developers. For users, call `describeCopyError(error)` or map
216
+ `error.type` through your own translations.
217
+
218
+ ## Options
219
+
220
+ ```ts
221
+ useCopy({
222
+ resetAfterMs: 2000, // false or Infinity keeps "copied" until the next action
223
+ maxRetries: 3,
224
+ onCopy: (payload) => {}, // inline functions are fine; the latest one is always used
225
+ onError: (error, payload) => {},
226
+ adapter: myAdapter, // swap the clipboard backend (tests, Electron, native bridges)
227
+ });
228
+ ```
229
+
230
+ ## CopyField API
231
+
232
+ | Part | Renders | Notes |
233
+ | ------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
234
+ | `CopyField.Root` | `div` | Props: `value`, `label`, `copyOptions`, `messages`, `alwaysVisible`, `announce`, `pendingDelayMs`, `minPendingMs`. Forwards ref and all div props |
235
+ | `CopyField.Label` | `span` | Defaults to `label` |
236
+ | `CopyField.Value` | `span` | Defaults to the text value; pass children for anything else |
237
+ | `CopyField.Trigger` | `button type="button"` | Children can be a node or `({ status, displayStatus, state, revealed, canRetry }) => node` |
238
+ | `useCopyField()` | — | Full context, for building your own parts |
239
+
240
+ Styling hooks on Root and Trigger: `data-display-state="idle | copying | copied | error"`
241
+ (style with this one), `data-state` (the raw state), and `data-revealed` while the trigger
242
+ should be visible.
243
+
244
+ ### Translations
245
+
246
+ ```tsx
247
+ <CopyField.Root
248
+ label="ईमेल"
249
+ value={email}
250
+ messages={{
251
+ copied: "कॉपी हो गया",
252
+ error: (e) => t(`copy.errors.${e.type}`),
253
+ triggerLabel: (label) => `${label} कॉपी करें`,
254
+ }}
255
+ />
256
+ ```
257
+
258
+ ## Accessibility
259
+
260
+ - The trigger is always a real button, reachable with Tab and activated with Enter or Space.
261
+ - Hidden actions stay in the DOM and the tab order. Hide them with opacity keyed off
262
+ `data-revealed`, never `display: none`, or keyboard users can't reach them.
263
+ - Keyboard focus (`:focus-visible`) pins the reveal; a mouse click doesn't.
264
+ - The trigger is never `disabled` while copying, because disabling a focused button
265
+ throws keyboard focus back to the page.
266
+ - A live region is mounted before its first message, so the first announcement is not missed.
267
+ - The trigger's accessible name stays stable ("Copy Email"); the result is announced
268
+ separately, so screen readers don't re-read the button.
269
+ - Motion is yours to add; respect `prefers-reduced-motion` in your CSS.
270
+
271
+ ## Next.js and SSR
272
+
273
+ The React entry ships with `"use client"`, so import it directly from Server Components.
274
+ Nothing touches `window` during render: the server and the first client render are both
275
+ `idle` and not revealed, so there are no hydration mismatches.
276
+
277
+ `react-smart-copy/core` is framework-agnostic and safe to import anywhere.
278
+
279
+ ## Without React
280
+
281
+ ```ts
282
+ import { createCopyMachine } from "react-smart-copy/core";
283
+
284
+ const machine = createCopyMachine({ resetAfterMs: 1500 });
285
+ machine.subscribe(() => render(machine.getSnapshot()));
286
+ button.addEventListener("click", () => void machine.copy(input.value));
287
+ ```
288
+
289
+ ## Custom adapters
290
+
291
+ ```ts
292
+ import {
293
+ CopyFailure,
294
+ createCopyError,
295
+ type ClipboardAdapter,
296
+ } from "react-smart-copy/core";
297
+
298
+ const electronAdapter: ClipboardAdapter = {
299
+ write: async (payload) => {
300
+ if (payload.kind !== "text")
301
+ throw new CopyFailure(createCopyError("unsupported-format", "Text only"));
302
+ window.electron.clipboard.writeText(payload.value);
303
+ },
304
+ };
305
+ ```
306
+
307
+ Start the platform write before any `await`, or browsers drop the user gesture.
308
+
309
+ ## Browser support
310
+
311
+ Plain text works wherever `navigator.clipboard.writeText` exists: Chromium 66+, Firefox 63+,
312
+ 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.
315
+
316
+ ## Roadmap
317
+
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)
320
+ - **1.0** Frozen API, full external accessibility audit
321
+
322
+ ## Development
323
+
324
+ ```bash
325
+ npm install
326
+ npm run verify # lint, types, 90 tests, build, publint + attw, size budgets
327
+ npm run changeset # describe your change for the changelog
328
+ npm run site:preview # docs site at http://localhost:3000
329
+ ```
330
+
331
+ Releases are automated: merging the "Version Packages" PR publishes to npm through
332
+ trusted publishing with provenance. No long-lived npm token is stored in the repo.
333
+
334
+ ## License
335
+
336
+ MIT