react-smart-copy 1.7.2 → 1.8.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 +139 -1
- package/dist/core.cjs +221 -25
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +127 -2
- package/dist/core.d.ts +127 -2
- package/dist/core.js +220 -26
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +324 -25
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +171 -2
- package/dist/index.d.ts +171 -2
- package/dist/index.js +322 -26
- package/dist/index.js.map +1 -1
- package/package.json +12 -3
package/README.md
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
[](LICENSE)
|
|
7
7
|
[](https://react.dev)
|
|
8
8
|
[](https://www.typescriptlang.org)
|
|
9
|
+
[](https://github.com/suprabhat02/react-smart-copy)
|
|
9
10
|
|
|
10
11
|
**[Live demo and docs](https://suprabhat02.github.io/react-smart-copy/)**
|
|
11
12
|
|
|
@@ -280,6 +281,131 @@ transform to one event.
|
|
|
280
281
|
> This guards against accidents, not adversaries. Anyone can still screenshot, open dev
|
|
281
282
|
> tools or disable JavaScript. Never send data to the page that the user must not see.
|
|
282
283
|
|
|
284
|
+
## Drag-to-copy
|
|
285
|
+
|
|
286
|
+
`useDragCopy` makes any element draggable and populates its `DataTransfer` with structured
|
|
287
|
+
data when the user starts dragging it. No Clipboard API, no permission prompt — it works
|
|
288
|
+
in every browser that supports HTML5 drag-and-drop.
|
|
289
|
+
|
|
290
|
+
```tsx
|
|
291
|
+
import { useDragCopy } from "react-smart-copy";
|
|
292
|
+
|
|
293
|
+
function DraggableCard({ title, url }: { title: string; url: string }) {
|
|
294
|
+
const { ref, status } = useDragCopy({
|
|
295
|
+
source: () => ({ kind: "html", html: `<a href="${url}">${title}</a>`, text: title }),
|
|
296
|
+
effectAllowed: "copy",
|
|
297
|
+
});
|
|
298
|
+
return (
|
|
299
|
+
<div ref={ref} style={{ opacity: status === "dragging" ? 0.5 : 1 }}>
|
|
300
|
+
{title}
|
|
301
|
+
</div>
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
The `source` callback is called synchronously on `dragstart` and must return synchronously
|
|
307
|
+
(the `DataTransfer` closes when the event handler returns). Return:
|
|
308
|
+
|
|
309
|
+
| Return value | Effect |
|
|
310
|
+
| ------------------------------------ | --------------------------------------------------- |
|
|
311
|
+
| a string | written as `text/plain` |
|
|
312
|
+
| a text / HTML / JSON / multi payload | written according to its `kind` |
|
|
313
|
+
| `false` | `preventDefault()` is called; the drag is cancelled |
|
|
314
|
+
| `null` / `undefined` | the browser's default drag data, untouched |
|
|
315
|
+
|
|
316
|
+
The same payload shapes as `useCopy` are accepted (`kind: "text"`, `kind: "html"`,
|
|
317
|
+
`kind: "json"`, `kind: "multi"`), minus images — `DataTransfer` accepts strings only.
|
|
318
|
+
|
|
319
|
+
```tsx
|
|
320
|
+
// Plain text
|
|
321
|
+
source: () => `${title}\n${url}`
|
|
322
|
+
|
|
323
|
+
// HTML + text fallback (e.g. for dropping into a rich-text editor)
|
|
324
|
+
source: () => ({ kind: "html", html: `<b>${title}</b>`, text: title })
|
|
325
|
+
|
|
326
|
+
// JSON (serialised as text/plain)
|
|
327
|
+
source: () => ({ kind: "json", value: { id, title }, pretty: true })
|
|
328
|
+
|
|
329
|
+
// Multiple MIME types (e.g. custom application type for your own drop targets)
|
|
330
|
+
source: () => ({
|
|
331
|
+
kind: "multi",
|
|
332
|
+
items: [
|
|
333
|
+
{ mimeType: "text/plain", data: title },
|
|
334
|
+
{ mimeType: "application/x-my-id", data: String(id) },
|
|
335
|
+
],
|
|
336
|
+
})
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
**`effectAllowed`** controls the drag cursor and the effects drop targets may request.
|
|
340
|
+
Defaults to `"copy"`; pass `"move"` to signal that the source will be removed after a
|
|
341
|
+
successful drop (your app must do the actual removal in `dragend` or on the server).
|
|
342
|
+
|
|
343
|
+
**Always-fresh source.** The `source` callback reads the latest props and state on every
|
|
344
|
+
drag. You never need to list it in a dependency array or wrap it in a ref yourself.
|
|
345
|
+
|
|
346
|
+
**`enabled`** removes `draggable` and the listener without unmounting the component.
|
|
347
|
+
Status resets to `idle` while disabled.
|
|
348
|
+
|
|
349
|
+
```tsx
|
|
350
|
+
const { ref, status, outcome } = useDragCopy({
|
|
351
|
+
source: () => text,
|
|
352
|
+
enabled: !isLocked,
|
|
353
|
+
effectAllowed: "copyMove",
|
|
354
|
+
onDrag: (state) => {
|
|
355
|
+
if (state.status === "done") analytics.track("drag_complete");
|
|
356
|
+
},
|
|
357
|
+
onError: (err) => console.error("drag source failed", err),
|
|
358
|
+
});
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
| Return value | Type | Description |
|
|
362
|
+
| ------------ | ----------------------------- | -------------------------------------------------- |
|
|
363
|
+
| `ref` | `RefCallback<T>` | Attach to the element you want to make draggable |
|
|
364
|
+
| `status` | `'idle' \| 'dragging' \| 'done'` | Current drag state |
|
|
365
|
+
| `outcome` | `DragCopyOutcome \| null` | Result of the last `dragstart`; `null` before any drag |
|
|
366
|
+
| `onDragStart`| `(event) => void` | For wiring via React's `onDragStart` prop if needed |
|
|
367
|
+
|
|
368
|
+
**`onDragStart` prop path.** The hook attaches its own native listener through `ref`, so you
|
|
369
|
+
rarely need `onDragStart`. It is there for render-prop components or controlled drag
|
|
370
|
+
libraries that require a React prop:
|
|
371
|
+
|
|
372
|
+
```tsx
|
|
373
|
+
const { ref, onDragStart } = useDragCopy({ source: () => "data" });
|
|
374
|
+
return (
|
|
375
|
+
<SortableItem
|
|
376
|
+
ref={ref}
|
|
377
|
+
onDragStart={(e) =>
|
|
378
|
+
onDragStart({
|
|
379
|
+
type: "dragstart",
|
|
380
|
+
dataTransfer: e.dataTransfer,
|
|
381
|
+
defaultPrevented: e.defaultPrevented,
|
|
382
|
+
preventDefault: () => e.preventDefault(),
|
|
383
|
+
})
|
|
384
|
+
}
|
|
385
|
+
/>
|
|
386
|
+
);
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
**SSR-safe.** `draggable` is never set during server rendering; the ref callback runs only
|
|
390
|
+
in the browser.
|
|
391
|
+
|
|
392
|
+
**Without React.** `applyDragCopy` and `registerDragCopy` are exported from
|
|
393
|
+
`react-smart-copy/core` for framework-agnostic use:
|
|
394
|
+
|
|
395
|
+
```ts
|
|
396
|
+
import { registerDragCopy } from "react-smart-copy/core";
|
|
397
|
+
|
|
398
|
+
const { unsubscribe } = registerDragCopy(element, () => ({
|
|
399
|
+
source: () => `${title}\n${url}`,
|
|
400
|
+
effectAllowed: "copy",
|
|
401
|
+
}));
|
|
402
|
+
// later: unsubscribe();
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
> **Drag vs. copy.** `useCopy` writes to the clipboard when the user clicks a button.
|
|
406
|
+
> `useDragCopy` writes to the `DataTransfer` when the user drags an element. Use them
|
|
407
|
+
> together if your UI supports both flows.
|
|
408
|
+
|
|
283
409
|
## Only one "Copied" at a time
|
|
284
410
|
|
|
285
411
|
Wrap a table or list in `<CopyGroup>`. A new successful copy returns the previously copied
|
|
@@ -722,6 +848,7 @@ embedded webviews. Where a capability is missing you get a typed error, never a
|
|
|
722
848
|
- ~~**1.4** Drag-and-drop through the paste pipeline: `dropTargetProps`, `isDragOver`, droppable `PasteField.Zone`~~ shipped
|
|
723
849
|
- ~~**1.5** `react-smart-copy/testing` — mock adapters and result builders so consumer tests stay green across releases~~ shipped
|
|
724
850
|
- ~~**1.7** `useCopyInterceptor` / `registerCopyInterceptor` — attribution, redaction and no-copy zones for native Ctrl/⌘+C~~ shipped
|
|
851
|
+
- ~~**1.8** `useDragCopy` / `registerDragCopy` — populate `DataTransfer` on drag-start; no Clipboard API needed~~ shipped
|
|
725
852
|
|
|
726
853
|
Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://suprabhat02.github.io/react-smart-copy/#releases).
|
|
727
854
|
|
|
@@ -729,7 +856,7 @@ Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://supr
|
|
|
729
856
|
|
|
730
857
|
```bash
|
|
731
858
|
npm install
|
|
732
|
-
npm run verify # lint, types,
|
|
859
|
+
npm run verify # lint, types, 638 tests at 100% coverage, build, publint + attw, size budgets
|
|
733
860
|
npm run changeset # describe your change for the changelog
|
|
734
861
|
npm run site:preview # docs site at http://localhost:3000
|
|
735
862
|
```
|
|
@@ -737,6 +864,17 @@ npm run site:preview # docs site at http://localhost:3000
|
|
|
737
864
|
Releases are automated: merging the "chore: release" PR publishes to npm through
|
|
738
865
|
trusted publishing with provenance. No long-lived npm token is stored in the repo.
|
|
739
866
|
|
|
867
|
+
## Support
|
|
868
|
+
|
|
869
|
+
If react-smart-copy saves you time, [star it on GitHub](https://github.com/suprabhat02/react-smart-copy):
|
|
870
|
+
it helps other React developers find it. Bugs and ideas are welcome in
|
|
871
|
+
[issues](https://github.com/suprabhat02/react-smart-copy/issues).
|
|
872
|
+
|
|
873
|
+
## Author
|
|
874
|
+
|
|
875
|
+
Built and maintained by [Suprabhat Kumar](https://suprabhat-dev.com/), a frontend
|
|
876
|
+
engineer working on React, TypeScript and accessible UI.
|
|
877
|
+
|
|
740
878
|
## License
|
|
741
879
|
|
|
742
880
|
MIT
|
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$
|
|
135
|
+
const invalid$2 = (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$
|
|
141
|
+
if (typeof payload !== "object" || payload === null) return invalid$2("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$
|
|
144
|
+
case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid$2("Text payload must be a non-empty string.");
|
|
145
145
|
case "html":
|
|
146
|
-
if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid$
|
|
147
|
-
return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid$
|
|
146
|
+
if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid$2("HTML payload requires a non-empty `html` string.");
|
|
147
|
+
return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid$2("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$
|
|
150
|
+
return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid$2("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
|
|
151
151
|
}
|
|
152
|
-
case "json": return candidate["value"] === void 0 ? invalid$
|
|
152
|
+
case "json": return candidate["value"] === void 0 ? invalid$2("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$
|
|
155
|
+
if (!Array.isArray(items) || items.length === 0) return invalid$2("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$
|
|
162
|
-
if (seen.has(mimeType)) return invalid$
|
|
161
|
+
if (typeof mimeType !== "string" || mimeType.length === 0) return invalid$2("Every multi item needs a non-empty `mimeType`.");
|
|
162
|
+
if (seen.has(mimeType)) return invalid$2(`Duplicate MIME type "${mimeType}" in multi payload.`);
|
|
163
163
|
seen.add(mimeType);
|
|
164
|
-
if (typeof data !== "string" && !isBlob(data)) return invalid$
|
|
164
|
+
if (typeof data !== "string" && !isBlob(data)) return invalid$2(`Multi item "${mimeType}" must contain a string or a Blob.`);
|
|
165
165
|
}
|
|
166
166
|
return null;
|
|
167
167
|
}
|
|
168
|
-
default: return invalid$
|
|
168
|
+
default: return invalid$2(`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. */
|
|
@@ -695,12 +695,12 @@ function readCopySelection(event) {
|
|
|
695
695
|
const read = readSelection(event);
|
|
696
696
|
return read ? read.selection : null;
|
|
697
697
|
}
|
|
698
|
-
const nonEmpty = (value) => typeof value === "string" && value.length > 0;
|
|
699
|
-
const invalid = (message, cause) => ({
|
|
698
|
+
const nonEmpty$1 = (value) => typeof value === "string" && value.length > 0;
|
|
699
|
+
const invalid$1 = (message, cause) => ({
|
|
700
700
|
ok: false,
|
|
701
701
|
error: createCopyError("invalid-payload", message, cause)
|
|
702
702
|
});
|
|
703
|
-
const unsupported = (message) => ({
|
|
703
|
+
const unsupported$1 = (message) => ({
|
|
704
704
|
ok: false,
|
|
705
705
|
error: createCopyError("unsupported-format", message)
|
|
706
706
|
});
|
|
@@ -714,8 +714,8 @@ function prepare(decision) {
|
|
|
714
714
|
kind: "text",
|
|
715
715
|
value: decision
|
|
716
716
|
} : decision;
|
|
717
|
-
if (typeof candidate !== "object" || candidate === null) return invalid("Copy transforms must return a string, a payload, false, or nothing.");
|
|
718
|
-
if (typeof candidate.then === "function") return invalid("Copy transforms must be synchronous; the clipboard closes when the event ends.");
|
|
717
|
+
if (typeof candidate !== "object" || candidate === null) return invalid$1("Copy transforms must return a string, a payload, false, or nothing.");
|
|
718
|
+
if (typeof candidate.then === "function") return invalid$1("Copy transforms must be synchronous; the clipboard closes when the event ends.");
|
|
719
719
|
const payload = candidate;
|
|
720
720
|
const fields = candidate;
|
|
721
721
|
const ok = (entries) => ({
|
|
@@ -724,8 +724,8 @@ function prepare(decision) {
|
|
|
724
724
|
entries
|
|
725
725
|
});
|
|
726
726
|
switch (fields["kind"]) {
|
|
727
|
-
case "text": return nonEmpty(fields["value"]) ? ok([["text/plain", fields["value"]]]) : invalid("Text payload must be a non-empty string.");
|
|
728
|
-
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`.");
|
|
727
|
+
case "text": return nonEmpty$1(fields["value"]) ? ok([["text/plain", fields["value"]]]) : invalid$1("Text payload must be a non-empty string.");
|
|
728
|
+
case "html": return nonEmpty$1(fields["html"]) && nonEmpty$1(fields["text"]) ? ok([["text/html", fields["html"]], ["text/plain", fields["text"]]]) : invalid$1("HTML payload requires non-empty `html` and plain-text `text`.");
|
|
729
729
|
case "json": {
|
|
730
730
|
const pretty = fields["pretty"];
|
|
731
731
|
const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
|
|
@@ -733,23 +733,23 @@ function prepare(decision) {
|
|
|
733
733
|
try {
|
|
734
734
|
json = JSON.stringify(fields["value"], null, indent);
|
|
735
735
|
} catch (cause) {
|
|
736
|
-
return invalid("JSON payload could not be serialised (circular reference or BigInt?).", cause);
|
|
736
|
+
return invalid$1("JSON payload could not be serialised (circular reference or BigInt?).", cause);
|
|
737
737
|
}
|
|
738
|
-
return typeof json === "string" ? ok([["text/plain", json]]) : invalid("JSON payload serialised to nothing.");
|
|
738
|
+
return typeof json === "string" ? ok([["text/plain", json]]) : invalid$1("JSON payload serialised to nothing.");
|
|
739
739
|
}
|
|
740
740
|
case "multi": {
|
|
741
741
|
const items = fields["items"];
|
|
742
|
-
if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
|
|
742
|
+
if (!Array.isArray(items) || items.length === 0) return invalid$1("Multi payload requires at least one item.");
|
|
743
743
|
const entries = [];
|
|
744
744
|
for (const item of items) {
|
|
745
745
|
const { mimeType, data } = item ?? {};
|
|
746
|
-
if (!nonEmpty(mimeType) || entries.some(([seen]) => seen === mimeType)) return invalid("Every multi item needs a unique, non-empty `mimeType`.");
|
|
747
|
-
if (typeof data !== "string") return unsupported(`Multi item "${mimeType}" must be a string during a copy event.`);
|
|
746
|
+
if (!nonEmpty$1(mimeType) || entries.some(([seen]) => seen === mimeType)) return invalid$1("Every multi item needs a unique, non-empty `mimeType`.");
|
|
747
|
+
if (typeof data !== "string") return unsupported$1(`Multi item "${mimeType}" must be a string during a copy event.`);
|
|
748
748
|
entries.push([mimeType, data]);
|
|
749
749
|
}
|
|
750
750
|
return ok(entries);
|
|
751
751
|
}
|
|
752
|
-
default: return unsupported(`"${String(fields["kind"])}" payloads cannot be written during a copy event; use useCopy() for images.`);
|
|
752
|
+
default: return unsupported$1(`"${String(fields["kind"])}" payloads cannot be written during a copy event; use useCopy() for images.`);
|
|
753
753
|
}
|
|
754
754
|
}
|
|
755
755
|
/** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */
|
|
@@ -911,6 +911,200 @@ function registerCopyInterceptor(root, options) {
|
|
|
911
911
|
};
|
|
912
912
|
}
|
|
913
913
|
//#endregion
|
|
914
|
+
//#region src/core/drag-copy.ts
|
|
915
|
+
/**
|
|
916
|
+
* Drag-to-copy: populate `DataTransfer` when the user starts dragging an
|
|
917
|
+
* element, so whatever they drop it into receives structured data — plain text,
|
|
918
|
+
* HTML, JSON, or multiple MIME types — instead of the browser's default
|
|
919
|
+
* text-extraction of the dragged DOM.
|
|
920
|
+
*
|
|
921
|
+
* No Clipboard API, no permission prompt, works in every browser that supports
|
|
922
|
+
* HTML5 drag-and-drop (all modern browsers and IE11+).
|
|
923
|
+
*/
|
|
924
|
+
const nonEmpty = (value) => typeof value === "string" && value.length > 0;
|
|
925
|
+
const invalid = (message, cause) => ({
|
|
926
|
+
ok: false,
|
|
927
|
+
error: createCopyError("invalid-payload", message, cause)
|
|
928
|
+
});
|
|
929
|
+
const unsupported = (message) => ({
|
|
930
|
+
ok: false,
|
|
931
|
+
error: createCopyError("unsupported-format", message)
|
|
932
|
+
});
|
|
933
|
+
function prepareDragDecision(decision) {
|
|
934
|
+
const candidate = typeof decision === "string" ? {
|
|
935
|
+
kind: "text",
|
|
936
|
+
value: decision
|
|
937
|
+
} : decision;
|
|
938
|
+
if (typeof candidate !== "object" || candidate === null) return invalid("Drag source must return a string, a payload, false, or nothing.");
|
|
939
|
+
if (typeof candidate.then === "function") return invalid("Drag sources must be synchronous; DataTransfer closes when dragstart returns.");
|
|
940
|
+
const payload = candidate;
|
|
941
|
+
const fields = candidate;
|
|
942
|
+
const ok = (items) => ({
|
|
943
|
+
ok: true,
|
|
944
|
+
payload,
|
|
945
|
+
items
|
|
946
|
+
});
|
|
947
|
+
switch (fields["kind"]) {
|
|
948
|
+
case "text": return nonEmpty(fields["value"]) ? ok([{
|
|
949
|
+
mimeType: "text/plain",
|
|
950
|
+
data: fields["value"]
|
|
951
|
+
}]) : invalid("Text payload must be a non-empty string.");
|
|
952
|
+
case "html": return nonEmpty(fields["html"]) && nonEmpty(fields["text"]) ? ok([{
|
|
953
|
+
mimeType: "text/html",
|
|
954
|
+
data: fields["html"]
|
|
955
|
+
}, {
|
|
956
|
+
mimeType: "text/plain",
|
|
957
|
+
data: fields["text"]
|
|
958
|
+
}]) : invalid("HTML payload requires non-empty `html` and `text`.");
|
|
959
|
+
case "json": {
|
|
960
|
+
const pretty = fields["pretty"];
|
|
961
|
+
const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
|
|
962
|
+
let json;
|
|
963
|
+
try {
|
|
964
|
+
json = JSON.stringify(fields["value"], null, indent);
|
|
965
|
+
} catch (cause) {
|
|
966
|
+
return invalid("JSON payload could not be serialised (circular reference or BigInt?).", cause);
|
|
967
|
+
}
|
|
968
|
+
return typeof json === "string" ? ok([{
|
|
969
|
+
mimeType: "text/plain",
|
|
970
|
+
data: json
|
|
971
|
+
}]) : invalid("JSON payload serialised to nothing.");
|
|
972
|
+
}
|
|
973
|
+
case "multi": {
|
|
974
|
+
const items = fields["items"];
|
|
975
|
+
if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
|
|
976
|
+
const out = [];
|
|
977
|
+
for (const item of items) {
|
|
978
|
+
const { mimeType, data } = item ?? {};
|
|
979
|
+
if (!nonEmpty(mimeType) || out.some((i) => i.mimeType === mimeType)) return invalid("Every multi item needs a unique, non-empty `mimeType`.");
|
|
980
|
+
if (typeof data !== "string") return unsupported(`Multi item "${mimeType}" must be a string; DataTransfer does not accept Blobs.`);
|
|
981
|
+
out.push({
|
|
982
|
+
mimeType,
|
|
983
|
+
data
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
return ok(out);
|
|
987
|
+
}
|
|
988
|
+
default: return unsupported(`"${String(fields["kind"])}" payloads cannot be used for drag-copy; use useCopy() for images.`);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Populates a `dragstart` event's `DataTransfer` with the given payload.
|
|
993
|
+
* Use this from a raw `dragstart` handler or a React `onDragStart` prop.
|
|
994
|
+
* Returns the outcome so you can inspect what happened.
|
|
995
|
+
*/
|
|
996
|
+
function applyDragCopy(event, options) {
|
|
997
|
+
if (event.defaultPrevented) return {
|
|
998
|
+
status: "passed",
|
|
999
|
+
reason: "declined"
|
|
1000
|
+
};
|
|
1001
|
+
let decision;
|
|
1002
|
+
try {
|
|
1003
|
+
decision = options.source(event);
|
|
1004
|
+
} catch (cause) {
|
|
1005
|
+
return {
|
|
1006
|
+
status: "failed",
|
|
1007
|
+
error: createCopyError("invalid-payload", "The drag source threw.", cause)
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1010
|
+
if (decision === null || decision === void 0) return {
|
|
1011
|
+
status: "passed",
|
|
1012
|
+
reason: "declined"
|
|
1013
|
+
};
|
|
1014
|
+
if (decision === false) {
|
|
1015
|
+
event.preventDefault();
|
|
1016
|
+
return {
|
|
1017
|
+
status: "passed",
|
|
1018
|
+
reason: "cancelled"
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
const transfer = event.dataTransfer;
|
|
1022
|
+
if (!transfer) return {
|
|
1023
|
+
status: "passed",
|
|
1024
|
+
reason: "no-transfer"
|
|
1025
|
+
};
|
|
1026
|
+
const prepared = prepareDragDecision(decision);
|
|
1027
|
+
if (!prepared.ok) return {
|
|
1028
|
+
status: "failed",
|
|
1029
|
+
error: prepared.error
|
|
1030
|
+
};
|
|
1031
|
+
try {
|
|
1032
|
+
transfer.effectAllowed = options.effectAllowed ?? "copy";
|
|
1033
|
+
for (const { mimeType, data } of prepared.items) transfer.setData(mimeType, data);
|
|
1034
|
+
} catch (cause) {
|
|
1035
|
+
try {
|
|
1036
|
+
transfer.clearData?.();
|
|
1037
|
+
} catch {}
|
|
1038
|
+
return {
|
|
1039
|
+
status: "failed",
|
|
1040
|
+
error: createCopyError("unknown", "The browser rejected the DataTransfer write.", cause)
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
return {
|
|
1044
|
+
status: "written",
|
|
1045
|
+
payload: prepared.payload
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
/**
|
|
1049
|
+
* Attaches `dragstart` and `dragend` listeners to `element`, calling
|
|
1050
|
+
* `applyDragCopy` on every drag start. Returns an object with an
|
|
1051
|
+
* `unsubscribe` function.
|
|
1052
|
+
*
|
|
1053
|
+
* Pass an options getter so the latest options are always used without
|
|
1054
|
+
* re-registering — safe to pass an inline object from a React render.
|
|
1055
|
+
*
|
|
1056
|
+
* ```ts
|
|
1057
|
+
* const { unsubscribe } = registerDragCopy(el, () => ({
|
|
1058
|
+
* source: () => `${title}\n${url}`,
|
|
1059
|
+
* }));
|
|
1060
|
+
* ```
|
|
1061
|
+
*/
|
|
1062
|
+
function registerDragCopy(element, options) {
|
|
1063
|
+
const read = typeof options === "function" ? options : () => options;
|
|
1064
|
+
let unsubscribed = false;
|
|
1065
|
+
let currentOutcome = null;
|
|
1066
|
+
function onDragStart(raw) {
|
|
1067
|
+
const event = raw;
|
|
1068
|
+
const opts = read();
|
|
1069
|
+
const outcome = applyDragCopy({
|
|
1070
|
+
type: event.type,
|
|
1071
|
+
dataTransfer: event.dataTransfer,
|
|
1072
|
+
get defaultPrevented() {
|
|
1073
|
+
return event.defaultPrevented;
|
|
1074
|
+
},
|
|
1075
|
+
preventDefault: () => {
|
|
1076
|
+
event.preventDefault();
|
|
1077
|
+
}
|
|
1078
|
+
}, opts);
|
|
1079
|
+
currentOutcome = outcome;
|
|
1080
|
+
const state = {
|
|
1081
|
+
status: "dragging",
|
|
1082
|
+
outcome
|
|
1083
|
+
};
|
|
1084
|
+
if (outcome.status === "failed") invoke(opts.onError, outcome.error);
|
|
1085
|
+
invoke(opts.onDrag, state);
|
|
1086
|
+
}
|
|
1087
|
+
function onDragEnd() {
|
|
1088
|
+
const opts = read();
|
|
1089
|
+
const state = {
|
|
1090
|
+
status: "done",
|
|
1091
|
+
outcome: currentOutcome
|
|
1092
|
+
};
|
|
1093
|
+
invoke(opts.onDrag, state);
|
|
1094
|
+
currentOutcome = null;
|
|
1095
|
+
}
|
|
1096
|
+
element.setAttribute("draggable", "true");
|
|
1097
|
+
element.addEventListener("dragstart", onDragStart);
|
|
1098
|
+
element.addEventListener("dragend", onDragEnd);
|
|
1099
|
+
return { unsubscribe() {
|
|
1100
|
+
if (unsubscribed) return;
|
|
1101
|
+
unsubscribed = true;
|
|
1102
|
+
element.removeEventListener("dragstart", onDragStart);
|
|
1103
|
+
element.removeEventListener("dragend", onDragEnd);
|
|
1104
|
+
element.removeAttribute("draggable");
|
|
1105
|
+
} };
|
|
1106
|
+
}
|
|
1107
|
+
//#endregion
|
|
914
1108
|
//#region src/core/paste-reader.ts
|
|
915
1109
|
/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
|
|
916
1110
|
function completePasteResult(result) {
|
|
@@ -1387,6 +1581,7 @@ exports.IDLE_STATE = IDLE_STATE;
|
|
|
1387
1581
|
exports.IMAGE_MIME_TYPE = IMAGE_MIME_TYPE;
|
|
1388
1582
|
exports.PASTE_IDLE_STATE = PASTE_IDLE_STATE;
|
|
1389
1583
|
exports.SVG_MIME_TYPE = SVG_MIME_TYPE;
|
|
1584
|
+
exports.applyDragCopy = applyDragCopy;
|
|
1390
1585
|
exports.canAcceptDrag = canAcceptDrag;
|
|
1391
1586
|
exports.canRetryPasteState = canRetryPasteState;
|
|
1392
1587
|
exports.canRetryState = canRetryState;
|
|
@@ -1409,6 +1604,7 @@ exports.normalizeMimeType = normalizeMimeType;
|
|
|
1409
1604
|
exports.normalizePayload = normalizePayload;
|
|
1410
1605
|
exports.readCopySelection = readCopySelection;
|
|
1411
1606
|
exports.registerCopyInterceptor = registerCopyInterceptor;
|
|
1607
|
+
exports.registerDragCopy = registerDragCopy;
|
|
1412
1608
|
exports.resolveMaxRetries = resolveMaxRetries;
|
|
1413
1609
|
exports.resolvePasteReadOptions = resolvePasteReadOptions;
|
|
1414
1610
|
exports.serializeJson = serializeJson;
|