react-smart-copy 1.4.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +140 -1
- package/dist/core.cjs +313 -12
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +133 -0
- package/dist/core.d.ts +133 -0
- package/dist/core.js +310 -13
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +343 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +159 -1
- package/dist/index.d.ts +159 -1
- package/dist/index.js +339 -13
- package/dist/index.js.map +1 -1
- package/dist/testing.cjs +201 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +309 -0
- package/dist/testing.d.ts +309 -0
- package/dist/testing.js +197 -0
- package/dist/testing.js.map +1 -0
- package/package.json +27 -4
package/README.md
CHANGED
|
@@ -23,6 +23,7 @@ ID PLT-29018 [Copy]
|
|
|
23
23
|
- Copy text, rich HTML (with plain-text fallback), PNG images, JSON, multi-format
|
|
24
24
|
- **Paste** text, HTML and screenshots with `usePaste`: a Paste button or Ctrl/⌘+V, no permission prompt for keyboard paste
|
|
25
25
|
- **`<CopyGroup>`**: only one row shows "Copied" at a time
|
|
26
|
+
- **`useCopyInterceptor`**: control what Ctrl/⌘+C copies from your page — attribution, redaction, Excel-ready tables, no-copy zones
|
|
26
27
|
- **`react-smart-copy/capture`**: copy an `<svg>` or any piece of your UI as a PNG
|
|
27
28
|
- Every failure is a typed, classified error. Nothing silently no-ops
|
|
28
29
|
- Unstyled. Works with Tailwind, CSS modules, CSS-in-JS, shadcn, MUI, Ant Design
|
|
@@ -207,6 +208,78 @@ Failures are classified like everything else: `invalid-payload` (no element / un
|
|
|
207
208
|
real limits (cross-origin images taint the canvas, web fonts must be loaded, `<video>` and
|
|
208
209
|
`<iframe>` rarely render), so offer a text fallback when capture fails.
|
|
209
210
|
|
|
211
|
+
## Controlling native copy (Ctrl/⌘+C)
|
|
212
|
+
|
|
213
|
+
Everything above copies from a button. `useCopyInterceptor` handles the other way people
|
|
214
|
+
copy: selecting text and pressing Ctrl/⌘+C, Ctrl/⌘+X or using the context menu. Inside the
|
|
215
|
+
element you attach it to, you decide what reaches the clipboard.
|
|
216
|
+
|
|
217
|
+
```tsx
|
|
218
|
+
import { useCopyInterceptor } from "react-smart-copy";
|
|
219
|
+
|
|
220
|
+
function Article({ children }: { children: React.ReactNode }) {
|
|
221
|
+
const { ref } = useCopyInterceptor<HTMLElement>({
|
|
222
|
+
transform: ({ text }) => `${text}\n\nSource: ${location.href}`,
|
|
223
|
+
});
|
|
224
|
+
return <article ref={ref}>{children}</article>;
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
The transform receives the selection (`text`, `html`, a detached `fragment` you may
|
|
229
|
+
mutate, the `field` for inputs, and whether it was a `copy` or `cut`) and returns:
|
|
230
|
+
|
|
231
|
+
| Return | Effect |
|
|
232
|
+
| ---------------------------------------- | -------------------------------------------------------------- |
|
|
233
|
+
| a string or a text/HTML/JSON/multi payload | written instead of the selection |
|
|
234
|
+
| `false` | nothing is copied; a blocked cut deletes nothing |
|
|
235
|
+
| `null` / `undefined` | the browser's normal copy, untouched |
|
|
236
|
+
|
|
237
|
+
It writes through the copy event itself, so there is no permission prompt, it works over
|
|
238
|
+
plain HTTP, and in every browser. The trade-off: only strings can be written, so the types
|
|
239
|
+
reject image payloads and `async` transforms (the clipboard closes when the event returns).
|
|
240
|
+
Use `useCopy` for images.
|
|
241
|
+
|
|
242
|
+
**Redaction.** Mutate the fragment and return HTML with a text fallback:
|
|
243
|
+
|
|
244
|
+
```tsx
|
|
245
|
+
const { ref } = useCopyInterceptor<HTMLDivElement>({
|
|
246
|
+
priority: 10, // see "Overlapping scopes"
|
|
247
|
+
transform: ({ fragment, text }) => {
|
|
248
|
+
if (!fragment) return text.replace(/sk-live-\w+/g, "••••"); // inside an <input>
|
|
249
|
+
fragment.querySelectorAll("[data-redact]").forEach((node) => (node.textContent = "••••"));
|
|
250
|
+
const box = document.createElement("div");
|
|
251
|
+
box.append(fragment);
|
|
252
|
+
return { kind: "html", html: box.innerHTML, text: box.textContent };
|
|
253
|
+
},
|
|
254
|
+
});
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
**Tables to Excel.** Return a `multi` payload with tab-separated `text/plain` and an HTML
|
|
258
|
+
`<table>`; spreadsheets paste either into cells.
|
|
259
|
+
|
|
260
|
+
**Cuts** in inputs and `contenteditable` still remove the selection after your content is
|
|
261
|
+
written, through the browser's own editing path: undo works and React sees an `input` event.
|
|
262
|
+
`outcome.deleted` tells you whether that happened.
|
|
263
|
+
|
|
264
|
+
**Failures fail closed.** If the transform throws or returns something unwritable, nothing
|
|
265
|
+
is copied and `onError` fires. That is the safe default for redaction; pass
|
|
266
|
+
`failureMode: "native"` to let the original copy through instead (e.g. for attribution).
|
|
267
|
+
|
|
268
|
+
**Overlapping scopes.** One selection can touch several intercepted elements. Exactly one
|
|
269
|
+
handles it: the highest `priority`, then the innermost, then the first in the document. The
|
|
270
|
+
winner receives the whole selection, so give redaction scopes a higher priority than
|
|
271
|
+
attribution scopes and copying across both is still masked. A React `onCopy` handler that
|
|
272
|
+
calls `preventDefault()` always wins.
|
|
273
|
+
|
|
274
|
+
Other options: `events` (`["copy"]`, `["cut"]` or both, the default), `enabled`, and
|
|
275
|
+
`onIntercept(outcome)` for telemetry. Without React, call `registerCopyInterceptor(element,
|
|
276
|
+
options)` from `react-smart-copy/core`; it returns an unsubscribe function. For a single
|
|
277
|
+
element's own `onCopy` handler, `interceptCopyEvent(event, { transform })` applies a
|
|
278
|
+
transform to one event.
|
|
279
|
+
|
|
280
|
+
> This guards against accidents, not adversaries. Anyone can still screenshot, open dev
|
|
281
|
+
> tools or disable JavaScript. Never send data to the page that the user must not see.
|
|
282
|
+
|
|
210
283
|
## Only one "Copied" at a time
|
|
211
284
|
|
|
212
285
|
Wrap a table or list in `<CopyGroup>`. A new successful copy returns the previously copied
|
|
@@ -545,6 +618,70 @@ zone.addEventListener("dragover", (event) => {
|
|
|
545
618
|
zone.addEventListener("drop", (event) => void paster.dropEvent(event));
|
|
546
619
|
```
|
|
547
620
|
|
|
621
|
+
## Testing
|
|
622
|
+
|
|
623
|
+
`react-smart-copy/testing` ships utilities that keep consumer test suites
|
|
624
|
+
green across library upgrades. Every `PasteResult` field added in v1.3 and
|
|
625
|
+
v1.4 required updating hand-written result literals — these helpers absorb
|
|
626
|
+
future additions at the library level.
|
|
627
|
+
|
|
628
|
+
### `createPasteResult(init?)`
|
|
629
|
+
|
|
630
|
+
Builds a complete `PasteResult` from partial input. Every field defaults
|
|
631
|
+
sensibly, so adding a required field in a future release won't touch your tests.
|
|
632
|
+
|
|
633
|
+
```ts
|
|
634
|
+
import { createPasteResult } from "react-smart-copy/testing";
|
|
635
|
+
|
|
636
|
+
const result = createPasteResult({ text: "hello" });
|
|
637
|
+
// result.source → 'clipboard'
|
|
638
|
+
// result.text → 'hello'
|
|
639
|
+
// result.html → null
|
|
640
|
+
// result.images → []
|
|
641
|
+
// result.files → []
|
|
642
|
+
// result.imageFiles → []
|
|
643
|
+
// result.items → [{ type: 'text/plain', data: 'hello' }]
|
|
644
|
+
```
|
|
645
|
+
|
|
646
|
+
### `createMockPasteAdapter()`
|
|
647
|
+
|
|
648
|
+
A controllable `PasteAdapter` backed by a result queue. Queue entries
|
|
649
|
+
are consumed FIFO; an empty queue rejects with `'no-content'`.
|
|
650
|
+
|
|
651
|
+
```ts
|
|
652
|
+
import { createMockPasteAdapter, createPasteResult } from "react-smart-copy/testing";
|
|
653
|
+
import { createPasteMachine } from "react-smart-copy/core";
|
|
654
|
+
|
|
655
|
+
const mock = createMockPasteAdapter();
|
|
656
|
+
mock.queueResult(createPasteResult({ text: "hello" }));
|
|
657
|
+
mock.queueError(createCopyError("permission-denied", "blocked"));
|
|
658
|
+
|
|
659
|
+
const machine = createPasteMachine({ adapter: mock.adapter });
|
|
660
|
+
await machine.paste(); // → { status: 'read', result: … }
|
|
661
|
+
expect(mock.readCount()).toBe(1);
|
|
662
|
+
```
|
|
663
|
+
|
|
664
|
+
### `createMockClipboardAdapter()`
|
|
665
|
+
|
|
666
|
+
A controllable `ClipboardAdapter` for copy tests. Captures the last payload
|
|
667
|
+
the machine sent so you can assert on it.
|
|
668
|
+
|
|
669
|
+
```ts
|
|
670
|
+
import { createMockClipboardAdapter } from "react-smart-copy/testing";
|
|
671
|
+
import { createCopyMachine } from "react-smart-copy/core";
|
|
672
|
+
|
|
673
|
+
const mock = createMockClipboardAdapter();
|
|
674
|
+
mock.queueSuccess();
|
|
675
|
+
|
|
676
|
+
const machine = createCopyMachine({ adapter: mock.adapter });
|
|
677
|
+
await machine.copy("hello");
|
|
678
|
+
expect(mock.lastPayload()).toEqual({ kind: "text", value: "hello" });
|
|
679
|
+
```
|
|
680
|
+
|
|
681
|
+
The subpackage also re-exports the types most often needed in test files:
|
|
682
|
+
`CopyFailure`, `CopyError`, `PasteResult`, `PasteSource`, `ClipboardAdapter`,
|
|
683
|
+
and more — so a single import covers both utilities and type annotations.
|
|
684
|
+
|
|
548
685
|
## Custom adapters
|
|
549
686
|
|
|
550
687
|
```ts
|
|
@@ -583,6 +720,8 @@ embedded webviews. Where a capability is missing you get a typed error, never a
|
|
|
583
720
|
- ~~**1.2** Paste `retry()`, cancellation with `AbortSignal`, `PasteField.Preview`~~ shipped
|
|
584
721
|
- ~~**1.3** `onReset` / `onCancel` callbacks, UTF-8 `maxBytes` on every paste path, `PasteResult.imageFiles`~~ shipped
|
|
585
722
|
- ~~**1.4** Drag-and-drop through the paste pipeline: `dropTargetProps`, `isDragOver`, droppable `PasteField.Zone`~~ shipped
|
|
723
|
+
- ~~**1.5** `react-smart-copy/testing` — mock adapters and result builders so consumer tests stay green across releases~~ shipped
|
|
724
|
+
- ~~**1.7** `useCopyInterceptor` / `registerCopyInterceptor` — attribution, redaction and no-copy zones for native Ctrl/⌘+C~~ shipped
|
|
586
725
|
|
|
587
726
|
Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://suprabhat02.github.io/react-smart-copy/#releases).
|
|
588
727
|
|
|
@@ -590,7 +729,7 @@ Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://supr
|
|
|
590
729
|
|
|
591
730
|
```bash
|
|
592
731
|
npm install
|
|
593
|
-
npm run verify # lint, types,
|
|
732
|
+
npm run verify # lint, types, 565 tests at 100% coverage, build, publint + attw, size budgets
|
|
594
733
|
npm run changeset # describe your change for the changelog
|
|
595
734
|
npm run site:preview # docs site at http://localhost:3000
|
|
596
735
|
```
|
package/dist/core.cjs
CHANGED
|
@@ -132,40 +132,40 @@ function isBlob(value) {
|
|
|
132
132
|
function isThenable(value) {
|
|
133
133
|
return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
|
|
134
134
|
}
|
|
135
|
-
const invalid = (message) => createCopyError("invalid-payload", message);
|
|
135
|
+
const invalid$1 = (message) => createCopyError("invalid-payload", message);
|
|
136
136
|
/**
|
|
137
137
|
* Structural validation. Typed callers can't produce most of these states,
|
|
138
138
|
* but plain-JS callers and runtime data can, so the check is always on.
|
|
139
139
|
*/
|
|
140
140
|
function validatePayload(payload) {
|
|
141
|
-
if (typeof payload !== "object" || payload === null) return invalid("Copy input must be a string or a payload object.");
|
|
141
|
+
if (typeof payload !== "object" || payload === null) return invalid$1("Copy input must be a string or a payload object.");
|
|
142
142
|
const candidate = payload;
|
|
143
143
|
switch (candidate["kind"]) {
|
|
144
|
-
case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid("Text payload must be a non-empty string.");
|
|
144
|
+
case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid$1("Text payload must be a non-empty string.");
|
|
145
145
|
case "html":
|
|
146
|
-
if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid("HTML payload requires a non-empty `html` string.");
|
|
147
|
-
return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid("HTML payload requires a non-empty plain-text `text` fallback.");
|
|
146
|
+
if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid$1("HTML payload requires a non-empty `html` string.");
|
|
147
|
+
return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid$1("HTML payload requires a non-empty plain-text `text` fallback.");
|
|
148
148
|
case "image": {
|
|
149
149
|
const source = candidate["blob"];
|
|
150
|
-
return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
|
|
150
|
+
return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid$1("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
|
|
151
151
|
}
|
|
152
|
-
case "json": return candidate["value"] === void 0 ? invalid("JSON payload value is undefined.") : null;
|
|
152
|
+
case "json": return candidate["value"] === void 0 ? invalid$1("JSON payload value is undefined.") : null;
|
|
153
153
|
case "multi": {
|
|
154
154
|
const items = candidate["items"];
|
|
155
|
-
if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
|
|
155
|
+
if (!Array.isArray(items) || items.length === 0) return invalid$1("Multi payload requires at least one item.");
|
|
156
156
|
const seen = /* @__PURE__ */ new Set();
|
|
157
157
|
for (const item of items) {
|
|
158
158
|
const entry = typeof item === "object" && item !== null ? item : {};
|
|
159
159
|
const mimeType = entry["mimeType"];
|
|
160
160
|
const data = entry["data"];
|
|
161
|
-
if (typeof mimeType !== "string" || mimeType.length === 0) return invalid("Every multi item needs a non-empty `mimeType`.");
|
|
162
|
-
if (seen.has(mimeType)) return invalid(`Duplicate MIME type "${mimeType}" in multi payload.`);
|
|
161
|
+
if (typeof mimeType !== "string" || mimeType.length === 0) return invalid$1("Every multi item needs a non-empty `mimeType`.");
|
|
162
|
+
if (seen.has(mimeType)) return invalid$1(`Duplicate MIME type "${mimeType}" in multi payload.`);
|
|
163
163
|
seen.add(mimeType);
|
|
164
|
-
if (typeof data !== "string" && !isBlob(data)) return invalid(`Multi item "${mimeType}" must contain a string or a Blob.`);
|
|
164
|
+
if (typeof data !== "string" && !isBlob(data)) return invalid$1(`Multi item "${mimeType}" must contain a string or a Blob.`);
|
|
165
165
|
}
|
|
166
166
|
return null;
|
|
167
167
|
}
|
|
168
|
-
default: return invalid(`Unknown payload kind: ${String(candidate["kind"])}.`);
|
|
168
|
+
default: return invalid$1(`Unknown payload kind: ${String(candidate["kind"])}.`);
|
|
169
169
|
}
|
|
170
170
|
}
|
|
171
171
|
/** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
|
|
@@ -610,6 +610,303 @@ function createCopyMachine(options = {}) {
|
|
|
610
610
|
};
|
|
611
611
|
}
|
|
612
612
|
//#endregion
|
|
613
|
+
//#region src/core/copy-interceptor.ts
|
|
614
|
+
const DEFAULT_INTERCEPTED_EVENTS = ["copy", "cut"];
|
|
615
|
+
function isNode(value) {
|
|
616
|
+
return typeof value === "object" && value !== null && typeof value.nodeType === "number";
|
|
617
|
+
}
|
|
618
|
+
function readTextField(target) {
|
|
619
|
+
if (!isNode(target) || target.nodeType !== 1) return null;
|
|
620
|
+
const tag = target.tagName;
|
|
621
|
+
if (tag !== "INPUT" && tag !== "TEXTAREA") return null;
|
|
622
|
+
const field = target;
|
|
623
|
+
try {
|
|
624
|
+
const { selectionStart: start, selectionEnd: end } = field;
|
|
625
|
+
return typeof start === "number" && typeof end === "number" ? {
|
|
626
|
+
field,
|
|
627
|
+
start,
|
|
628
|
+
end
|
|
629
|
+
} : null;
|
|
630
|
+
} catch {
|
|
631
|
+
return null;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
function documentOf(target) {
|
|
635
|
+
if (isNode(target)) return target.nodeType === 9 ? target : target.ownerDocument;
|
|
636
|
+
return typeof document === "undefined" ? null : document;
|
|
637
|
+
}
|
|
638
|
+
function isEditableNode(node) {
|
|
639
|
+
return (node.nodeType === 1 ? node : node.parentElement)?.isContentEditable === true;
|
|
640
|
+
}
|
|
641
|
+
function rangesOf(doc) {
|
|
642
|
+
const ranges = [];
|
|
643
|
+
const selection = doc?.getSelection();
|
|
644
|
+
if (!selection || selection.isCollapsed) return ranges;
|
|
645
|
+
for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));
|
|
646
|
+
return ranges;
|
|
647
|
+
}
|
|
648
|
+
function readSelection(event) {
|
|
649
|
+
const kind = event.type === "cut" ? "cut" : "copy";
|
|
650
|
+
const fieldSelection = readTextField(event.target);
|
|
651
|
+
if (fieldSelection) {
|
|
652
|
+
const { field, start, end } = fieldSelection;
|
|
653
|
+
const text = field.value.slice(Math.min(start, end), Math.max(start, end));
|
|
654
|
+
if (text.length === 0) return null;
|
|
655
|
+
return {
|
|
656
|
+
selection: {
|
|
657
|
+
kind,
|
|
658
|
+
text,
|
|
659
|
+
html: null,
|
|
660
|
+
fragment: null,
|
|
661
|
+
field,
|
|
662
|
+
editable: !field.readOnly && !field.disabled
|
|
663
|
+
},
|
|
664
|
+
doc: field.ownerDocument
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
const doc = documentOf(event.target);
|
|
668
|
+
const ranges = rangesOf(doc);
|
|
669
|
+
const [first] = ranges;
|
|
670
|
+
if (!doc || !first) return null;
|
|
671
|
+
const text = ranges.map((range) => range.toString()).join("\n");
|
|
672
|
+
if (text.length === 0) return null;
|
|
673
|
+
const container = doc.createElement("div");
|
|
674
|
+
for (const range of ranges) container.appendChild(range.cloneContents());
|
|
675
|
+
const html = container.innerHTML;
|
|
676
|
+
const fragment = doc.createDocumentFragment();
|
|
677
|
+
while (container.firstChild) fragment.appendChild(container.firstChild);
|
|
678
|
+
return {
|
|
679
|
+
selection: {
|
|
680
|
+
kind,
|
|
681
|
+
text,
|
|
682
|
+
html,
|
|
683
|
+
fragment,
|
|
684
|
+
field: null,
|
|
685
|
+
editable: isEditableNode(first.startContainer)
|
|
686
|
+
},
|
|
687
|
+
doc
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
/** Reads the selection behind a copy event, or `null` if nothing readable is selected. */
|
|
691
|
+
function readCopySelection(event) {
|
|
692
|
+
const read = readSelection(event);
|
|
693
|
+
return read ? read.selection : null;
|
|
694
|
+
}
|
|
695
|
+
const nonEmpty = (value) => typeof value === "string" && value.length > 0;
|
|
696
|
+
const invalid = (message, cause) => ({
|
|
697
|
+
ok: false,
|
|
698
|
+
error: createCopyError("invalid-payload", message, cause)
|
|
699
|
+
});
|
|
700
|
+
const unsupported = (message) => ({
|
|
701
|
+
ok: false,
|
|
702
|
+
error: createCopyError("unsupported-format", message)
|
|
703
|
+
});
|
|
704
|
+
/**
|
|
705
|
+
* Validates a decision and turns it into `[mimeType, data]` pairs. Kept
|
|
706
|
+
* self-contained (no shared validator) so the interceptor stays small; the
|
|
707
|
+
* checks still run for plain-JS callers the types can't protect.
|
|
708
|
+
*/
|
|
709
|
+
function prepare(decision) {
|
|
710
|
+
const candidate = typeof decision === "string" ? {
|
|
711
|
+
kind: "text",
|
|
712
|
+
value: decision
|
|
713
|
+
} : decision;
|
|
714
|
+
if (typeof candidate !== "object" || candidate === null) return invalid("Copy transforms must return a string, a payload, false, or nothing.");
|
|
715
|
+
if (typeof candidate.then === "function") return invalid("Copy transforms must be synchronous; the clipboard closes when the event ends.");
|
|
716
|
+
const payload = candidate;
|
|
717
|
+
const fields = candidate;
|
|
718
|
+
const ok = (entries) => ({
|
|
719
|
+
ok: true,
|
|
720
|
+
payload,
|
|
721
|
+
entries
|
|
722
|
+
});
|
|
723
|
+
switch (fields["kind"]) {
|
|
724
|
+
case "text": return nonEmpty(fields["value"]) ? ok([["text/plain", fields["value"]]]) : invalid("Text payload must be a non-empty string.");
|
|
725
|
+
case "html": return nonEmpty(fields["html"]) && nonEmpty(fields["text"]) ? ok([["text/html", fields["html"]], ["text/plain", fields["text"]]]) : invalid("HTML payload requires non-empty `html` and plain-text `text`.");
|
|
726
|
+
case "json": {
|
|
727
|
+
const pretty = fields["pretty"];
|
|
728
|
+
const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
|
|
729
|
+
let json;
|
|
730
|
+
try {
|
|
731
|
+
json = JSON.stringify(fields["value"], null, indent);
|
|
732
|
+
} catch (cause) {
|
|
733
|
+
return invalid("JSON payload could not be serialised (circular reference or BigInt?).", cause);
|
|
734
|
+
}
|
|
735
|
+
return typeof json === "string" ? ok([["text/plain", json]]) : invalid("JSON payload serialised to nothing.");
|
|
736
|
+
}
|
|
737
|
+
case "multi": {
|
|
738
|
+
const items = fields["items"];
|
|
739
|
+
if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
|
|
740
|
+
const entries = [];
|
|
741
|
+
for (const item of items) {
|
|
742
|
+
const { mimeType, data } = item ?? {};
|
|
743
|
+
if (!nonEmpty(mimeType) || entries.some(([seen]) => seen === mimeType)) return invalid("Every multi item needs a unique, non-empty `mimeType`.");
|
|
744
|
+
if (typeof data !== "string") return unsupported(`Multi item "${mimeType}" must be a string during a copy event.`);
|
|
745
|
+
entries.push([mimeType, data]);
|
|
746
|
+
}
|
|
747
|
+
return ok(entries);
|
|
748
|
+
}
|
|
749
|
+
default: return unsupported(`"${String(fields["kind"])}" payloads cannot be written during a copy event; use useCopy() for images.`);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
/** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */
|
|
753
|
+
function deleteSelection(doc) {
|
|
754
|
+
const legacy = doc;
|
|
755
|
+
try {
|
|
756
|
+
return legacy.execCommand?.("delete") === true;
|
|
757
|
+
} catch {
|
|
758
|
+
return false;
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Applies a transform to one `copy`/`cut` event. Use directly from an
|
|
763
|
+
* `onCopy` handler, or let {@link registerCopyInterceptor} scope it.
|
|
764
|
+
*/
|
|
765
|
+
function interceptCopyEvent(event, options) {
|
|
766
|
+
if (event.type !== "copy" && event.type !== "cut") return {
|
|
767
|
+
status: "passed",
|
|
768
|
+
reason: "unsupported-event",
|
|
769
|
+
selection: null
|
|
770
|
+
};
|
|
771
|
+
if (event.defaultPrevented) return {
|
|
772
|
+
status: "passed",
|
|
773
|
+
reason: "already-handled",
|
|
774
|
+
selection: null
|
|
775
|
+
};
|
|
776
|
+
const read = readSelection(event);
|
|
777
|
+
if (!read) return {
|
|
778
|
+
status: "passed",
|
|
779
|
+
reason: "no-selection",
|
|
780
|
+
selection: null
|
|
781
|
+
};
|
|
782
|
+
const { selection, doc } = read;
|
|
783
|
+
const fail = (error) => {
|
|
784
|
+
const fallback = options.failureMode ?? "block";
|
|
785
|
+
if (fallback === "block") event.preventDefault();
|
|
786
|
+
return {
|
|
787
|
+
status: "failed",
|
|
788
|
+
selection,
|
|
789
|
+
error,
|
|
790
|
+
fallback
|
|
791
|
+
};
|
|
792
|
+
};
|
|
793
|
+
let decision;
|
|
794
|
+
try {
|
|
795
|
+
decision = options.transform(selection);
|
|
796
|
+
} catch (cause) {
|
|
797
|
+
return fail(createCopyError("invalid-payload", "The copy transform threw.", cause));
|
|
798
|
+
}
|
|
799
|
+
if (decision === null || decision === void 0) return {
|
|
800
|
+
status: "passed",
|
|
801
|
+
reason: "declined",
|
|
802
|
+
selection
|
|
803
|
+
};
|
|
804
|
+
if (decision === false) {
|
|
805
|
+
event.preventDefault();
|
|
806
|
+
return {
|
|
807
|
+
status: "blocked",
|
|
808
|
+
selection
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
const prepared = prepare(decision);
|
|
812
|
+
if (!prepared.ok) return fail(prepared.error);
|
|
813
|
+
const data = event.clipboardData;
|
|
814
|
+
if (!data) return fail(createCopyError("unsupported", "This browser exposes no clipboardData on copy events."));
|
|
815
|
+
event.preventDefault();
|
|
816
|
+
try {
|
|
817
|
+
for (const [mimeType, value] of prepared.entries) data.setData(mimeType, value);
|
|
818
|
+
} catch (cause) {
|
|
819
|
+
try {
|
|
820
|
+
data.clearData?.();
|
|
821
|
+
} catch {}
|
|
822
|
+
return {
|
|
823
|
+
status: "failed",
|
|
824
|
+
selection,
|
|
825
|
+
error: createCopyError("unknown", "The browser rejected the clipboard write.", cause),
|
|
826
|
+
fallback: "block"
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
const deleted = selection.kind === "cut" && selection.editable && deleteSelection(doc);
|
|
830
|
+
return {
|
|
831
|
+
status: "written",
|
|
832
|
+
selection,
|
|
833
|
+
payload: prepared.payload,
|
|
834
|
+
deleted
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
const registries = /* @__PURE__ */ new WeakMap();
|
|
838
|
+
function touches(root, event) {
|
|
839
|
+
const fieldSelection = readTextField(event.target);
|
|
840
|
+
if (fieldSelection) return root.contains(fieldSelection.field);
|
|
841
|
+
return rangesOf(root.ownerDocument).some((range) => range.intersectsNode(root));
|
|
842
|
+
}
|
|
843
|
+
const priorityOf = (scope) => scope.read().priority ?? 0;
|
|
844
|
+
/**
|
|
845
|
+
* Highest `priority` first; then the innermost scope; then document order;
|
|
846
|
+
* then registration order (same root). A total order, so the result never
|
|
847
|
+
* depends on effect timing.
|
|
848
|
+
*/
|
|
849
|
+
function compareScopes(a, b) {
|
|
850
|
+
const byPriority = priorityOf(b) - priorityOf(a);
|
|
851
|
+
if (byPriority !== 0) return byPriority;
|
|
852
|
+
const position = a.root.compareDocumentPosition(b.root);
|
|
853
|
+
if (position === 0) return 0;
|
|
854
|
+
if (position & 16) return 1;
|
|
855
|
+
if (position & 8) return -1;
|
|
856
|
+
return position & 4 ? -1 : 1;
|
|
857
|
+
}
|
|
858
|
+
function dispatch(registry, event) {
|
|
859
|
+
if (event.defaultPrevented) return;
|
|
860
|
+
const kind = event.type;
|
|
861
|
+
const [scope] = [...registry.scopes].filter((scope) => (scope.read().events ?? DEFAULT_INTERCEPTED_EVENTS).includes(kind) && touches(scope.root, event)).sort(compareScopes);
|
|
862
|
+
if (!scope) return;
|
|
863
|
+
const options = scope.read();
|
|
864
|
+
const outcome = interceptCopyEvent(event, options);
|
|
865
|
+
invoke(options.onIntercept, outcome);
|
|
866
|
+
if (outcome.status === "failed") invoke(options.onError, outcome.error);
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Intercepts native copies and cuts whose selection touches `root`. Returns
|
|
870
|
+
* an unsubscribe function. Pass a getter to always read the latest options.
|
|
871
|
+
*
|
|
872
|
+
* One listener per document serves every scope, so overlapping scopes
|
|
873
|
+
* resolve deterministically (see `priority`) regardless of registration order.
|
|
874
|
+
* Handlers that call `preventDefault()` first (e.g. a React `onCopy`) win.
|
|
875
|
+
*/
|
|
876
|
+
function registerCopyInterceptor(root, options) {
|
|
877
|
+
const doc = root.ownerDocument;
|
|
878
|
+
let registry = registries.get(doc);
|
|
879
|
+
if (!registry) {
|
|
880
|
+
const created = {
|
|
881
|
+
scopes: /* @__PURE__ */ new Set(),
|
|
882
|
+
listener: (event) => {
|
|
883
|
+
dispatch(created, event);
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
registry = created;
|
|
887
|
+
registries.set(doc, created);
|
|
888
|
+
doc.addEventListener("copy", created.listener);
|
|
889
|
+
doc.addEventListener("cut", created.listener);
|
|
890
|
+
}
|
|
891
|
+
const scope = {
|
|
892
|
+
root,
|
|
893
|
+
read: typeof options === "function" ? options : () => options
|
|
894
|
+
};
|
|
895
|
+
registry.scopes.add(scope);
|
|
896
|
+
const active = registry;
|
|
897
|
+
let registered = true;
|
|
898
|
+
return () => {
|
|
899
|
+
if (!registered) return;
|
|
900
|
+
registered = false;
|
|
901
|
+
active.scopes.delete(scope);
|
|
902
|
+
if (active.scopes.size === 0) {
|
|
903
|
+
doc.removeEventListener("copy", active.listener);
|
|
904
|
+
doc.removeEventListener("cut", active.listener);
|
|
905
|
+
registries.delete(doc);
|
|
906
|
+
}
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
//#endregion
|
|
613
910
|
//#region src/core/paste-reader.ts
|
|
614
911
|
/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
|
|
615
912
|
function completePasteResult(result) {
|
|
@@ -1076,6 +1373,7 @@ function createPasteMachine(options = {}) {
|
|
|
1076
1373
|
}
|
|
1077
1374
|
//#endregion
|
|
1078
1375
|
exports.CopyFailure = CopyFailure;
|
|
1376
|
+
exports.DEFAULT_INTERCEPTED_EVENTS = DEFAULT_INTERCEPTED_EVENTS;
|
|
1079
1377
|
exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES;
|
|
1080
1378
|
exports.DEFAULT_PASTE_ACCEPT = DEFAULT_PASTE_ACCEPT;
|
|
1081
1379
|
exports.DEFAULT_PASTE_MAX_BYTES = DEFAULT_PASTE_MAX_BYTES;
|
|
@@ -1097,6 +1395,7 @@ exports.createCopyMachine = createCopyMachine;
|
|
|
1097
1395
|
exports.createPasteMachine = createPasteMachine;
|
|
1098
1396
|
exports.describeCopyError = describeCopyError;
|
|
1099
1397
|
exports.describePasteError = describePasteError;
|
|
1398
|
+
exports.interceptCopyEvent = interceptCopyEvent;
|
|
1100
1399
|
exports.isBlob = isBlob;
|
|
1101
1400
|
exports.isCopyFailure = isCopyFailure;
|
|
1102
1401
|
exports.isRetryableError = isRetryableError;
|
|
@@ -1104,6 +1403,8 @@ exports.isTextualMimeType = isTextualMimeType;
|
|
|
1104
1403
|
exports.matchesMimePattern = matchesMimePattern;
|
|
1105
1404
|
exports.normalizeMimeType = normalizeMimeType;
|
|
1106
1405
|
exports.normalizePayload = normalizePayload;
|
|
1406
|
+
exports.readCopySelection = readCopySelection;
|
|
1407
|
+
exports.registerCopyInterceptor = registerCopyInterceptor;
|
|
1107
1408
|
exports.resolveMaxRetries = resolveMaxRetries;
|
|
1108
1409
|
exports.resolvePasteReadOptions = resolvePasteReadOptions;
|
|
1109
1410
|
exports.serializeJson = serializeJson;
|