react-smart-copy 1.17.1 → 1.18.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 +22 -3
- package/dist/capture.cjs +30 -153
- package/dist/capture.cjs.map +1 -1
- package/dist/capture.d.cts +2 -25
- package/dist/capture.d.ts +2 -25
- package/dist/capture.js +5 -128
- package/dist/capture.js.map +1 -1
- package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs +102 -0
- package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs.map +1 -0
- package/dist/chunks/clipboard-adapter-CtH4VELE.d.cts +43 -0
- package/dist/chunks/clipboard-adapter-DEXkXxwV.js +97 -0
- package/dist/chunks/clipboard-adapter-DEXkXxwV.js.map +1 -0
- package/dist/chunks/clipboard-adapter-Ds0irroN.d.ts +43 -0
- package/dist/chunks/contrast-C6CVklEI.cjs +842 -0
- package/dist/chunks/contrast-C6CVklEI.cjs.map +1 -0
- package/dist/chunks/contrast-DpK2JIVu.js +789 -0
- package/dist/chunks/contrast-DpK2JIVu.js.map +1 -0
- package/dist/chunks/copy-interceptor-C6NABy1l.d.ts +141 -0
- package/dist/chunks/copy-interceptor-CZWzGOkL.d.cts +141 -0
- package/dist/chunks/core-Cp2HSpaz.js +1035 -0
- package/dist/chunks/core-Cp2HSpaz.js.map +1 -0
- package/dist/chunks/core-DYf_Lhbe.cjs +1142 -0
- package/dist/chunks/core-DYf_Lhbe.cjs.map +1 -0
- package/dist/chunks/deadline-C29AlS_Q.js +46 -0
- package/dist/chunks/deadline-C29AlS_Q.js.map +1 -0
- package/dist/chunks/deadline-DkiB8ZHE.cjs +51 -0
- package/dist/chunks/deadline-DkiB8ZHE.cjs.map +1 -0
- package/dist/chunks/errors-9h8sdFFX.js +120 -0
- package/dist/chunks/errors-9h8sdFFX.js.map +1 -0
- package/dist/chunks/errors-BwOF6T_M.cjs +167 -0
- package/dist/chunks/errors-BwOF6T_M.cjs.map +1 -0
- package/dist/chunks/index-mr7sSAgP.d.ts +426 -0
- package/dist/chunks/index-vz0iW5V2.d.cts +426 -0
- package/dist/chunks/mime--LB7kdqG.cjs +153 -0
- package/dist/chunks/mime--LB7kdqG.cjs.map +1 -0
- package/dist/chunks/mime-aa-HA2dm.js +100 -0
- package/dist/chunks/mime-aa-HA2dm.js.map +1 -0
- package/dist/chunks/paste-adapter--SPL4PRE.d.cts +35 -0
- package/dist/chunks/paste-adapter-uahXnTYk.d.ts +35 -0
- package/dist/chunks/paste-reader-Bo01IMC_.cjs +289 -0
- package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +1 -0
- package/dist/chunks/paste-reader-D9i7yMXF.js +224 -0
- package/dist/chunks/paste-reader-D9i7yMXF.js.map +1 -0
- package/dist/chunks/paste-reader-DcXnRWQr.d.cts +96 -0
- package/dist/chunks/paste-reader-DcXnRWQr.d.ts +96 -0
- package/dist/chunks/payload-CUymxwim.cjs +100 -0
- package/dist/chunks/payload-CUymxwim.cjs.map +1 -0
- package/dist/chunks/payload-CcwKJ_bU.d.cts +162 -0
- package/dist/chunks/payload-Cl_8hCI5.d.ts +162 -0
- package/dist/chunks/payload-DGw-JOo7.js +71 -0
- package/dist/chunks/payload-DGw-JOo7.js.map +1 -0
- package/dist/chunks/payload-DI5AorDz.js +103 -0
- package/dist/chunks/payload-DI5AorDz.js.map +1 -0
- package/dist/chunks/payload-J6GjHuh3.cjs +132 -0
- package/dist/chunks/payload-J6GjHuh3.cjs.map +1 -0
- package/dist/chunks/share-Bop47Znn.js +208 -0
- package/dist/chunks/share-Bop47Znn.js.map +1 -0
- package/dist/chunks/share-C0esXvRK.d.cts +115 -0
- package/dist/chunks/share-ayDz974N.cjs +231 -0
- package/dist/chunks/share-ayDz974N.cjs.map +1 -0
- package/dist/chunks/share-e7FenIr2.d.ts +115 -0
- package/dist/chunks/text-field-Ba8W3v4R.cjs +77 -0
- package/dist/chunks/text-field-Ba8W3v4R.cjs.map +1 -0
- package/dist/chunks/text-field-C0SGmvvR.d.cts +18 -0
- package/dist/chunks/text-field-C0SGmvvR.d.ts +18 -0
- package/dist/chunks/text-field-DUvrMMaK.js +66 -0
- package/dist/chunks/text-field-DUvrMMaK.js.map +1 -0
- package/dist/chunks/url-BcMYVCXQ.js +135 -0
- package/dist/chunks/url-BcMYVCXQ.js.map +1 -0
- package/dist/chunks/url-D4PGsRm8.cjs +164 -0
- package/dist/chunks/url-D4PGsRm8.cjs.map +1 -0
- package/dist/chunks/url-DWdElCT3.d.cts +43 -0
- package/dist/chunks/url-DWdElCT3.d.ts +43 -0
- package/dist/code.cjs +20 -109
- package/dist/code.cjs.map +1 -1
- package/dist/code.d.cts +4 -28
- package/dist/code.d.ts +4 -28
- package/dist/code.js +4 -93
- package/dist/code.js.map +1 -1
- package/dist/color.cjs +21 -893
- package/dist/color.cjs.map +1 -1
- package/dist/color.d.cts +4 -28
- package/dist/color.d.ts +4 -28
- package/dist/color.js +4 -876
- package/dist/color.js.map +1 -1
- package/dist/core.cjs +52 -1659
- package/dist/core.d.cts +8 -878
- package/dist/core.d.ts +8 -878
- package/dist/core.js +7 -1614
- package/dist/image.cjs +23 -91
- package/dist/image.cjs.map +1 -1
- package/dist/image.d.cts +1 -0
- package/dist/image.d.ts +1 -0
- package/dist/image.js +5 -73
- package/dist/image.js.map +1 -1
- package/dist/index.cjs +74 -2072
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -978
- package/dist/index.d.ts +8 -978
- package/dist/index.js +7 -2005
- package/dist/index.js.map +1 -1
- package/dist/link.cjs +24 -338
- package/dist/link.cjs.map +1 -1
- package/dist/link.d.cts +5 -83
- package/dist/link.d.ts +5 -83
- package/dist/link.js +5 -319
- package/dist/link.js.map +1 -1
- package/dist/markdown.cjs +8 -97
- package/dist/markdown.cjs.map +1 -1
- package/dist/markdown.d.cts +3 -16
- package/dist/markdown.d.ts +3 -16
- package/dist/markdown.js +3 -92
- package/dist/markdown.js.map +1 -1
- package/dist/rich.cjs +26 -934
- package/dist/rich.cjs.map +1 -1
- package/dist/rich.d.cts +4 -90
- package/dist/rich.d.ts +4 -90
- package/dist/rich.js +4 -912
- package/dist/rich.js.map +1 -1
- package/dist/share.cjs +5 -640
- package/dist/share.d.cts +3 -248
- package/dist/share.d.ts +3 -248
- package/dist/share.js +1 -637
- package/dist/structured.cjs +13 -95
- package/dist/structured.cjs.map +1 -1
- package/dist/structured.d.cts +2 -11
- package/dist/structured.d.ts +2 -11
- package/dist/structured.js +4 -86
- package/dist/structured.js.map +1 -1
- package/dist/table.cjs +11 -39
- package/dist/table.cjs.map +1 -1
- package/dist/table.d.cts +2 -12
- package/dist/table.d.ts +2 -12
- package/dist/table.js +2 -30
- package/dist/table.js.map +1 -1
- package/dist/testing.cjs +10 -43
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +6 -181
- package/dist/testing.d.ts +6 -181
- package/dist/testing.js +3 -36
- package/dist/testing.js.map +1 -1
- package/package.json +20 -2
- package/dist/core.cjs.map +0 -1
- package/dist/core.js.map +0 -1
- package/dist/share.cjs.map +0 -1
- package/dist/share.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,1618 +1,13 @@
|
|
|
1
1
|
"use client";
|
|
2
|
+
import { a as describePasteError, c as toCopyError, i as describeCopyError, n as copyFailure, o as isCopyFailure, r as createCopyError, s as isRetryableError, t as CopyFailure } from "./chunks/errors-9h8sdFFX.js";
|
|
3
|
+
import { a as validatePayload, i as serializeJson, n as isBlob, r as normalizePayload, t as IMAGE_MIME_TYPE } from "./chunks/payload-DGw-JOo7.js";
|
|
4
|
+
import { a as matchesMimePattern, c as sniffImageBytes, i as isWebCustomFormat, l as sniffImageType, n as WEB_CUSTOM_FORMAT_PREFIX, o as normalizeClipboardType, r as isTextualMimeType, s as normalizeMimeType, t as SVG_MIME_TYPE } from "./chunks/mime-aa-HA2dm.js";
|
|
5
|
+
import { t as createBrowserClipboardAdapter } from "./chunks/clipboard-adapter-DEXkXxwV.js";
|
|
6
|
+
import { _ as resolveMaxRetries, a as applyDragCopy, c as interceptCopyEvent, d as DEFAULT_RESET_AFTER_MS, f as IDLE_STATE, g as invoke, h as DEFAULT_MAX_RETRIES, i as createBrowserPasteAdapter, l as readCopySelection, m as createCopyMachine, n as canRetryPasteState, o as registerDragCopy, p as canRetryState, r as createPasteMachine, s as DEFAULT_INTERCEPTED_EVENTS, t as PASTE_IDLE_STATE, u as registerCopyInterceptor, v as createCopyCoordinator } from "./chunks/core-Cp2HSpaz.js";
|
|
7
|
+
import { i as canAcceptDrag, l as resolvePasteReadOptions, n as DEFAULT_PASTE_MAX_BYTES, r as DEFAULT_PASTE_MAX_ITEMS, t as DEFAULT_PASTE_ACCEPT } from "./chunks/paste-reader-D9i7yMXF.js";
|
|
8
|
+
import { i as shareOrCopy, r as shareMethod, t as TOUCH_FIRST } from "./chunks/share-Bop47Znn.js";
|
|
2
9
|
import { createContext, forwardRef, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
3
10
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
4
|
-
//#region src/core/errors.ts
|
|
5
|
-
function createCopyError(type, message, cause) {
|
|
6
|
-
return cause === void 0 ? {
|
|
7
|
-
type,
|
|
8
|
-
message
|
|
9
|
-
} : {
|
|
10
|
-
type,
|
|
11
|
-
message,
|
|
12
|
-
cause
|
|
13
|
-
};
|
|
14
|
-
}
|
|
15
|
-
const RETRYABLE_ERRORS = /* @__PURE__ */ new Set([
|
|
16
|
-
"permission-denied",
|
|
17
|
-
"not-focused",
|
|
18
|
-
"blob-generation-failed",
|
|
19
|
-
"timeout",
|
|
20
|
-
"unknown"
|
|
21
|
-
]);
|
|
22
|
-
/** Whether retrying the same payload could plausibly succeed. */
|
|
23
|
-
function isRetryableError(error) {
|
|
24
|
-
return RETRYABLE_ERRORS.has(error.type);
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Branded (not `instanceof`) so failures stay recognisable even when the core
|
|
28
|
-
* is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
|
|
29
|
-
*/
|
|
30
|
-
const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
|
|
31
|
-
/** Error thrown by adapters to carry a fully classified {@link CopyError}. */
|
|
32
|
-
var CopyFailure = class extends Error {
|
|
33
|
-
constructor(copyError) {
|
|
34
|
-
super(copyError.message);
|
|
35
|
-
this[COPY_FAILURE_BRAND] = true;
|
|
36
|
-
this.name = "CopyFailure";
|
|
37
|
-
this.copyError = copyError;
|
|
38
|
-
}
|
|
39
|
-
};
|
|
40
|
-
function isCopyFailure(value) {
|
|
41
|
-
return typeof value === "object" && value !== null && value[COPY_FAILURE_BRAND] === true;
|
|
42
|
-
}
|
|
43
|
-
/** Shorthand for throwing a classified failure. */
|
|
44
|
-
function copyFailure(type, message, cause) {
|
|
45
|
-
return new CopyFailure(createCopyError(type, message, cause));
|
|
46
|
-
}
|
|
47
|
-
function readString(value, key) {
|
|
48
|
-
if (typeof value !== "object" || value === null) return void 0;
|
|
49
|
-
const field = value[key];
|
|
50
|
-
return typeof field === "string" ? field : void 0;
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Classifies anything thrown by the platform or an adapter into a {@link CopyError}.
|
|
54
|
-
* `operation` only tailors the developer-facing message.
|
|
55
|
-
*/
|
|
56
|
-
function toCopyError(cause, operation = "write") {
|
|
57
|
-
if (isCopyFailure(cause)) return cause.copyError;
|
|
58
|
-
const name = readString(cause, "name");
|
|
59
|
-
const message = readString(cause, "message") ?? "";
|
|
60
|
-
const verb = operation === "read" ? "read" : "write";
|
|
61
|
-
switch (name) {
|
|
62
|
-
case "NotAllowedError": return /focus/i.test(message) ? createCopyError("not-focused", `The document was not focused during the clipboard ${verb}.`, cause) : createCopyError("permission-denied", `Clipboard ${verb} permission was denied.`, cause);
|
|
63
|
-
case "SecurityError": return createCopyError("insecure-context", "The clipboard is blocked in this context.", cause);
|
|
64
|
-
case "NotSupportedError":
|
|
65
|
-
case "DataError": return createCopyError("unsupported-format", "The browser rejected this clipboard format.", cause);
|
|
66
|
-
case "AbortError": return createCopyError("aborted", `The clipboard ${verb} was aborted.`, cause);
|
|
67
|
-
case "TimeoutError": return createCopyError("timeout", `The clipboard ${verb} timed out.`, cause);
|
|
68
|
-
default: return createCopyError("unknown", message || `The clipboard ${verb} failed for an unknown reason.`, cause);
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
const COPY_DESCRIPTIONS = {
|
|
72
|
-
unsupported: "Copying isn't supported in this browser.",
|
|
73
|
-
"insecure-context": "Copying requires a secure (HTTPS) connection.",
|
|
74
|
-
"permission-denied": "Clipboard access was blocked. Allow it and try again.",
|
|
75
|
-
"not-focused": "The page lost focus while copying. Try again.",
|
|
76
|
-
"invalid-payload": "There is nothing to copy.",
|
|
77
|
-
"unsupported-format": "This content can't be copied in this browser.",
|
|
78
|
-
"blob-generation-failed": "The image couldn't be prepared for copying.",
|
|
79
|
-
"max-retries-exceeded": "Copying failed after several attempts.",
|
|
80
|
-
"no-content": "There is nothing to copy.",
|
|
81
|
-
"too-large": "This content is too large to copy.",
|
|
82
|
-
timeout: "Copying took too long. Try again.",
|
|
83
|
-
aborted: "Copying was cancelled.",
|
|
84
|
-
unknown: "Couldn't copy to the clipboard. Try again."
|
|
85
|
-
};
|
|
86
|
-
const PASTE_DESCRIPTIONS = {
|
|
87
|
-
unsupported: "Pasting isn't supported in this browser.",
|
|
88
|
-
"insecure-context": "Pasting requires a secure (HTTPS) connection.",
|
|
89
|
-
"permission-denied": "Clipboard access was blocked. Allow it and try again.",
|
|
90
|
-
"not-focused": "The page lost focus while pasting. Try again.",
|
|
91
|
-
"invalid-payload": "The clipboard content couldn't be read.",
|
|
92
|
-
"unsupported-format": "This clipboard content isn't supported here.",
|
|
93
|
-
"blob-generation-failed": "The pasted image couldn't be read.",
|
|
94
|
-
"max-retries-exceeded": "Pasting failed after several attempts.",
|
|
95
|
-
"no-content": "The clipboard doesn't contain anything that can be pasted here.",
|
|
96
|
-
"too-large": "The clipboard content is too large to paste.",
|
|
97
|
-
timeout: "Pasting took too long. Try again.",
|
|
98
|
-
aborted: "Pasting was cancelled.",
|
|
99
|
-
unknown: "Couldn't read the clipboard. Try again."
|
|
100
|
-
};
|
|
101
|
-
/** Default English, user-facing sentence for a copy error. Replace for i18n. */
|
|
102
|
-
function describeCopyError(error) {
|
|
103
|
-
return COPY_DESCRIPTIONS[error.type];
|
|
104
|
-
}
|
|
105
|
-
/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */
|
|
106
|
-
const DROP_DESCRIPTIONS = {
|
|
107
|
-
"invalid-payload": "The dropped content couldn't be read.",
|
|
108
|
-
"no-content": "Nothing that was dropped can be used here.",
|
|
109
|
-
"too-large": "The dropped content is too large.",
|
|
110
|
-
unknown: "Couldn't read the dropped content. Try again."
|
|
111
|
-
};
|
|
112
|
-
/**
|
|
113
|
-
* Default English, user-facing sentence for a paste error. Pass the error
|
|
114
|
-
* state's `source` to word drag-and-drop failures as drops. Replace for i18n.
|
|
115
|
-
*/
|
|
116
|
-
function describePasteError(error, source) {
|
|
117
|
-
return (source === "drop" ? DROP_DESCRIPTIONS[error.type] : void 0) ?? PASTE_DESCRIPTIONS[error.type];
|
|
118
|
-
}
|
|
119
|
-
//#endregion
|
|
120
|
-
//#region src/core/payload.ts
|
|
121
|
-
/** The only image MIME type with reliable cross-browser clipboard write support. */
|
|
122
|
-
const IMAGE_MIME_TYPE = "image/png";
|
|
123
|
-
function normalizePayload(input) {
|
|
124
|
-
return typeof input === "string" ? {
|
|
125
|
-
kind: "text",
|
|
126
|
-
value: input
|
|
127
|
-
} : input;
|
|
128
|
-
}
|
|
129
|
-
function isBlob(value) {
|
|
130
|
-
if (typeof Blob !== "undefined" && value instanceof Blob) return true;
|
|
131
|
-
const tag = Object.prototype.toString.call(value);
|
|
132
|
-
return tag === "[object Blob]" || tag === "[object File]";
|
|
133
|
-
}
|
|
134
|
-
function isThenable(value) {
|
|
135
|
-
return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
|
|
136
|
-
}
|
|
137
|
-
const invalid$5 = (message) => createCopyError("invalid-payload", message);
|
|
138
|
-
/**
|
|
139
|
-
* Structural validation. Typed callers can't produce most of these states,
|
|
140
|
-
* but plain-JS callers and runtime data can, so the check is always on.
|
|
141
|
-
*/
|
|
142
|
-
function validatePayload(payload) {
|
|
143
|
-
if (typeof payload !== "object" || payload === null) return invalid$5("Copy input must be a string or a payload object.");
|
|
144
|
-
const candidate = payload;
|
|
145
|
-
switch (candidate["kind"]) {
|
|
146
|
-
case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid$5("Text payload must be a non-empty string.");
|
|
147
|
-
case "html":
|
|
148
|
-
if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid$5("HTML payload requires a non-empty `html` string.");
|
|
149
|
-
return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid$5("HTML payload requires a non-empty plain-text `text` fallback.");
|
|
150
|
-
case "image": {
|
|
151
|
-
const source = candidate["blob"];
|
|
152
|
-
return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid$5("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
|
|
153
|
-
}
|
|
154
|
-
case "json": return candidate["value"] === void 0 ? invalid$5("JSON payload value is undefined.") : null;
|
|
155
|
-
case "multi": {
|
|
156
|
-
const items = candidate["items"];
|
|
157
|
-
if (!Array.isArray(items) || items.length === 0) return invalid$5("Multi payload requires at least one item.");
|
|
158
|
-
const seen = /* @__PURE__ */ new Set();
|
|
159
|
-
for (const item of items) {
|
|
160
|
-
const entry = typeof item === "object" && item !== null ? item : {};
|
|
161
|
-
const mimeType = entry["mimeType"];
|
|
162
|
-
const data = entry["data"];
|
|
163
|
-
if (typeof mimeType !== "string" || mimeType.length === 0) return invalid$5("Every multi item needs a non-empty `mimeType`.");
|
|
164
|
-
if (seen.has(mimeType)) return invalid$5(`Duplicate MIME type "${mimeType}" in multi payload.`);
|
|
165
|
-
seen.add(mimeType);
|
|
166
|
-
if (typeof data !== "string" && !isBlob(data)) return invalid$5(`Multi item "${mimeType}" must contain a string or a Blob.`);
|
|
167
|
-
}
|
|
168
|
-
return null;
|
|
169
|
-
}
|
|
170
|
-
default: return invalid$5(`Unknown payload kind: ${String(candidate["kind"])}.`);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
/** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
|
|
174
|
-
function serializeJson(payload) {
|
|
175
|
-
const indent = payload.pretty === true ? 2 : typeof payload.pretty === "number" ? payload.pretty : void 0;
|
|
176
|
-
let text;
|
|
177
|
-
try {
|
|
178
|
-
text = JSON.stringify(payload.value, null, indent);
|
|
179
|
-
} catch (cause) {
|
|
180
|
-
throw new CopyFailure(createCopyError("invalid-payload", "JSON payload could not be serialised (circular reference or BigInt?).", cause));
|
|
181
|
-
}
|
|
182
|
-
if (typeof text !== "string") throw new CopyFailure(createCopyError("invalid-payload", "JSON payload serialised to nothing (functions, symbols and undefined are not JSON)."));
|
|
183
|
-
return text;
|
|
184
|
-
}
|
|
185
|
-
//#endregion
|
|
186
|
-
//#region src/core/mime.ts
|
|
187
|
-
/**
|
|
188
|
-
* MIME helpers shared by paste and capture. Everything that comes from the
|
|
189
|
-
* clipboard is untrusted input, so types are normalised and validated before
|
|
190
|
-
* they are compared, and image types are confirmed from the bytes themselves.
|
|
191
|
-
*/
|
|
192
|
-
/** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */
|
|
193
|
-
const MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
|
|
194
|
-
/** SVG is XML that can carry scripts; it is never matched by a wildcard. */
|
|
195
|
-
const SVG_MIME_TYPE = "image/svg+xml";
|
|
196
|
-
/** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */
|
|
197
|
-
function normalizeMimeType(value) {
|
|
198
|
-
const separator = value.indexOf(";");
|
|
199
|
-
const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();
|
|
200
|
-
return MIME_SHAPE.test(base) ? base : null;
|
|
201
|
-
}
|
|
202
|
-
/** Prefix of the async Clipboard API's web custom formats (`web application/vnd.acme+json`). */
|
|
203
|
-
const WEB_CUSTOM_FORMAT_PREFIX = "web ";
|
|
204
|
-
/** Whether a clipboard type is a web custom format (`web type/subtype`). */
|
|
205
|
-
function isWebCustomFormat(type) {
|
|
206
|
-
return type.slice(0, 4).toLowerCase() === WEB_CUSTOM_FORMAT_PREFIX;
|
|
207
|
-
}
|
|
208
|
-
/**
|
|
209
|
-
* Like {@link normalizeMimeType}, but also accepts web custom formats
|
|
210
|
-
* (`web type/subtype`), returned as `web ` + the normalised MIME type.
|
|
211
|
-
*/
|
|
212
|
-
function normalizeClipboardType(value) {
|
|
213
|
-
if (!isWebCustomFormat(value)) return normalizeMimeType(value);
|
|
214
|
-
const inner = normalizeMimeType(value.slice(4));
|
|
215
|
-
return inner === null ? null : WEB_CUSTOM_FORMAT_PREFIX + inner;
|
|
216
|
-
}
|
|
217
|
-
/**
|
|
218
|
-
* Types a wildcard never matches, so accepting them must be explicit:
|
|
219
|
-
* `image/svg+xml` (scriptable XML), web custom formats and structured `+json` types
|
|
220
|
-
* (application-specific data that only the app that defined them should read).
|
|
221
|
-
*/
|
|
222
|
-
function requiresExactMatch(mimeType) {
|
|
223
|
-
return mimeType === "image/svg+xml" || isWebCustomFormat(mimeType) || mimeType.endsWith("+json");
|
|
224
|
-
}
|
|
225
|
-
/**
|
|
226
|
-
* Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\/*`)?
|
|
227
|
-
* Wildcards never match `image/svg+xml`, web custom formats or `+json` types: those must be listed exactly.
|
|
228
|
-
*/
|
|
229
|
-
function matchesMimePattern(mimeType, pattern) {
|
|
230
|
-
if (pattern === mimeType) return true;
|
|
231
|
-
if (requiresExactMatch(mimeType)) return false;
|
|
232
|
-
if (pattern === "*/*") return true;
|
|
233
|
-
return pattern.endsWith("/*") && mimeType.startsWith(pattern.slice(0, -1));
|
|
234
|
-
}
|
|
235
|
-
/** Types whose clipboard data is text and is therefore surfaced as a `string`. */
|
|
236
|
-
function isTextualMimeType(mimeType) {
|
|
237
|
-
const type = isWebCustomFormat(mimeType) ? mimeType.slice(4) : mimeType;
|
|
238
|
-
return type.startsWith("text/") || type === "image/svg+xml" || type === "application/json" || type === "application/xml" || type.endsWith("+json");
|
|
239
|
-
}
|
|
240
|
-
const SNIFF_BYTES = 16;
|
|
241
|
-
function startsWith(bytes, signature, offset = 0) {
|
|
242
|
-
return signature.every((byte, index) => bytes[offset + index] === byte);
|
|
243
|
-
}
|
|
244
|
-
const ascii = (text) => Array.from(text, (char) => char.charCodeAt(0));
|
|
245
|
-
const PNG = [
|
|
246
|
-
137,
|
|
247
|
-
80,
|
|
248
|
-
78,
|
|
249
|
-
71,
|
|
250
|
-
13,
|
|
251
|
-
10,
|
|
252
|
-
26,
|
|
253
|
-
10
|
|
254
|
-
];
|
|
255
|
-
const JPEG = [
|
|
256
|
-
255,
|
|
257
|
-
216,
|
|
258
|
-
255
|
|
259
|
-
];
|
|
260
|
-
const GIF = ascii("GIF8");
|
|
261
|
-
const RIFF = ascii("RIFF");
|
|
262
|
-
const WEBP = ascii("WEBP");
|
|
263
|
-
const BMP = ascii("BM");
|
|
264
|
-
const FTYP_AVIF = ascii("ftypavif");
|
|
265
|
-
const FTYP_AVIS = ascii("ftypavis");
|
|
266
|
-
/** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */
|
|
267
|
-
function sniffImageBytes(bytes) {
|
|
268
|
-
if (startsWith(bytes, PNG)) return "image/png";
|
|
269
|
-
if (startsWith(bytes, JPEG)) return "image/jpeg";
|
|
270
|
-
if (startsWith(bytes, GIF)) return "image/gif";
|
|
271
|
-
if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return "image/webp";
|
|
272
|
-
if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return "image/avif";
|
|
273
|
-
if (startsWith(bytes, BMP)) return "image/bmp";
|
|
274
|
-
return null;
|
|
275
|
-
}
|
|
276
|
-
/** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */
|
|
277
|
-
async function sniffImageType(blob) {
|
|
278
|
-
const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();
|
|
279
|
-
return sniffImageBytes(new Uint8Array(head));
|
|
280
|
-
}
|
|
281
|
-
//#endregion
|
|
282
|
-
//#region src/core/clipboard-adapter.ts
|
|
283
|
-
const fail = (type, message, cause) => new CopyFailure(createCopyError(type, message, cause));
|
|
284
|
-
const noop = () => void 0;
|
|
285
|
-
function defaultEnvironment$2() {
|
|
286
|
-
return typeof window === "undefined" ? void 0 : window;
|
|
287
|
-
}
|
|
288
|
-
function getRichClipboard(env, clipboard) {
|
|
289
|
-
const Item = env.ClipboardItem;
|
|
290
|
-
if (!Item || typeof clipboard.write !== "function") return null;
|
|
291
|
-
return {
|
|
292
|
-
Item,
|
|
293
|
-
write: clipboard.write.bind(clipboard)
|
|
294
|
-
};
|
|
295
|
-
}
|
|
296
|
-
function isTypeSupported(Item, type) {
|
|
297
|
-
return typeof Item.supports !== "function" || Item.supports(type);
|
|
298
|
-
}
|
|
299
|
-
function writeText(clipboard, text) {
|
|
300
|
-
if (typeof clipboard.writeText !== "function") throw fail("unsupported", "navigator.clipboard.writeText() is not available.");
|
|
301
|
-
return clipboard.writeText(text);
|
|
302
|
-
}
|
|
303
|
-
async function resolveImageBlob(source, context) {
|
|
304
|
-
let blob;
|
|
305
|
-
try {
|
|
306
|
-
blob = await (typeof source === "function" ? source(context ?? { signal: new AbortController().signal }) : source);
|
|
307
|
-
} catch (cause) {
|
|
308
|
-
if (context?.signal.aborted) throw fail("aborted", "The image copy was cancelled.", cause);
|
|
309
|
-
throw fail("blob-generation-failed", "The image source threw or rejected while producing a Blob.", cause);
|
|
310
|
-
}
|
|
311
|
-
if (!isBlob(blob)) throw fail("blob-generation-failed", "The image source did not produce a Blob.");
|
|
312
|
-
if (blob.type !== "image/png") throw fail("unsupported-format", `Only ${IMAGE_MIME_TYPE} can be written to the clipboard (received "${blob.type || "unknown"}"). Convert with canvas.toBlob(cb, "${IMAGE_MIME_TYPE}").`);
|
|
313
|
-
return blob;
|
|
314
|
-
}
|
|
315
|
-
async function writeImage(rich, source, context) {
|
|
316
|
-
if (!isTypeSupported(rich.Item, "image/png")) throw fail("unsupported-format", `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);
|
|
317
|
-
const blob = resolveImageBlob(source, context);
|
|
318
|
-
blob.catch(noop);
|
|
319
|
-
try {
|
|
320
|
-
await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);
|
|
321
|
-
} catch (error) {
|
|
322
|
-
throw await blob.then(noop, (inner) => inner) ?? error;
|
|
323
|
-
}
|
|
324
|
-
await blob;
|
|
325
|
-
}
|
|
326
|
-
async function writeToClipboard(payload, env, degradeHtmlToText, context) {
|
|
327
|
-
if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
|
|
328
|
-
if (env.isSecureContext === false) throw fail("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
|
|
329
|
-
const clipboard = env.navigator?.clipboard;
|
|
330
|
-
if (!clipboard) throw fail("unsupported", "navigator.clipboard is not available in this browser.");
|
|
331
|
-
switch (payload.kind) {
|
|
332
|
-
case "text": return writeText(clipboard, payload.value);
|
|
333
|
-
case "json": return writeText(clipboard, serializeJson(payload));
|
|
334
|
-
case "html": {
|
|
335
|
-
const rich = getRichClipboard(env, clipboard);
|
|
336
|
-
if (!rich || !isTypeSupported(rich.Item, "text/html")) {
|
|
337
|
-
if (degradeHtmlToText) return writeText(clipboard, payload.text);
|
|
338
|
-
throw fail("unsupported-format", "Rich HTML copy requires ClipboardItem and navigator.clipboard.write().");
|
|
339
|
-
}
|
|
340
|
-
return rich.write([new rich.Item({
|
|
341
|
-
"text/html": new Blob([payload.html], { type: "text/html" }),
|
|
342
|
-
"text/plain": new Blob([payload.text], { type: "text/plain" })
|
|
343
|
-
})]);
|
|
344
|
-
}
|
|
345
|
-
case "image": {
|
|
346
|
-
const rich = getRichClipboard(env, clipboard);
|
|
347
|
-
if (!rich) throw fail("unsupported-format", "Image copy requires ClipboardItem and navigator.clipboard.write().");
|
|
348
|
-
return writeImage(rich, payload.blob, context);
|
|
349
|
-
}
|
|
350
|
-
case "multi": {
|
|
351
|
-
const rich = getRichClipboard(env, clipboard);
|
|
352
|
-
if (!rich) throw fail("unsupported-format", "Multi-format copy requires ClipboardItem and navigator.clipboard.write().");
|
|
353
|
-
const record = Object.create(null);
|
|
354
|
-
let written = 0;
|
|
355
|
-
for (const { mimeType, data, optional } of payload.items) {
|
|
356
|
-
if (optional === true && !(typeof rich.Item.supports === "function" && rich.Item.supports(mimeType))) continue;
|
|
357
|
-
if (!isTypeSupported(rich.Item, mimeType)) throw fail("unsupported-format", `This browser cannot write "${mimeType}" to the clipboard.`);
|
|
358
|
-
record[mimeType] = typeof data === "string" ? new Blob([data], { type: mimeType }) : data;
|
|
359
|
-
written += 1;
|
|
360
|
-
}
|
|
361
|
-
if (written === 0) throw fail("unsupported-format", "This browser can write none of the payload types.");
|
|
362
|
-
return rich.write([new rich.Item(record)]);
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
/** The default adapter: async Clipboard API with feature detection and honest errors. */
|
|
367
|
-
function createBrowserClipboardAdapter(options = {}) {
|
|
368
|
-
const getEnvironment = options.getEnvironment ?? defaultEnvironment$2;
|
|
369
|
-
const degradeHtmlToText = options.degradeHtmlToText ?? true;
|
|
370
|
-
return { write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context) };
|
|
371
|
-
}
|
|
372
|
-
//#endregion
|
|
373
|
-
//#region src/core/copy-coordinator.ts
|
|
374
|
-
function createCopyCoordinator() {
|
|
375
|
-
let active = null;
|
|
376
|
-
return {
|
|
377
|
-
activate: (member) => {
|
|
378
|
-
const previous = active;
|
|
379
|
-
active = member;
|
|
380
|
-
if (previous !== null && previous !== member) previous.release();
|
|
381
|
-
},
|
|
382
|
-
deactivate: (member) => {
|
|
383
|
-
if (active === member) active = null;
|
|
384
|
-
},
|
|
385
|
-
getActive: () => active
|
|
386
|
-
};
|
|
387
|
-
}
|
|
388
|
-
//#endregion
|
|
389
|
-
//#region src/core/machine-shared.ts
|
|
390
|
-
/**
|
|
391
|
-
* Internals shared by the copy and paste state machines. Kept in one module so
|
|
392
|
-
* apps that use both don't ship two copies.
|
|
393
|
-
*/
|
|
394
|
-
const DEFAULT_MAX_RETRIES = 3;
|
|
395
|
-
function resolveMaxRetries(value) {
|
|
396
|
-
if (value === Infinity) return Infinity;
|
|
397
|
-
if (value === void 0 || !Number.isFinite(value)) return 3;
|
|
398
|
-
return Math.max(0, Math.floor(value));
|
|
399
|
-
}
|
|
400
|
-
function reportCallbackError(error) {
|
|
401
|
-
const scope = globalThis;
|
|
402
|
-
if (typeof scope.reportError === "function") scope.reportError(error);
|
|
403
|
-
else setTimeout(() => {
|
|
404
|
-
throw error;
|
|
405
|
-
}, 0);
|
|
406
|
-
}
|
|
407
|
-
/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
|
|
408
|
-
function invoke(fn, ...args) {
|
|
409
|
-
if (!fn) return;
|
|
410
|
-
try {
|
|
411
|
-
fn(...args);
|
|
412
|
-
} catch (error) {
|
|
413
|
-
reportCallbackError(error);
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
/** One cancellable operation at a time. Signals only fire while their operation is unfinished. */
|
|
417
|
-
function createOperations() {
|
|
418
|
-
let controller;
|
|
419
|
-
const abort = () => {
|
|
420
|
-
if (!controller) return false;
|
|
421
|
-
controller.abort();
|
|
422
|
-
controller = void 0;
|
|
423
|
-
return true;
|
|
424
|
-
};
|
|
425
|
-
return {
|
|
426
|
-
start: () => {
|
|
427
|
-
abort();
|
|
428
|
-
controller = new AbortController();
|
|
429
|
-
return { signal: controller.signal };
|
|
430
|
-
},
|
|
431
|
-
end: (context) => {
|
|
432
|
-
if (controller?.signal === context.signal) controller = void 0;
|
|
433
|
-
},
|
|
434
|
-
abort
|
|
435
|
-
};
|
|
436
|
-
}
|
|
437
|
-
//#endregion
|
|
438
|
-
//#region src/core/source-error.ts
|
|
439
|
-
/**
|
|
440
|
-
* The error for a user-supplied source (copy source, drag source, copy transform)
|
|
441
|
-
* that threw. A thrown `CopyFailure` keeps its classification, so a helper such as
|
|
442
|
-
* `tablePayload()` can report `too-large` instead of a generic `invalid-payload`.
|
|
443
|
-
* Internal: not part of the public API.
|
|
444
|
-
*/
|
|
445
|
-
function sourceError(cause, message) {
|
|
446
|
-
return isCopyFailure(cause) ? cause.copyError : createCopyError("invalid-payload", message, cause);
|
|
447
|
-
}
|
|
448
|
-
//#endregion
|
|
449
|
-
//#region src/core/copy-machine.ts
|
|
450
|
-
const DEFAULT_RESET_AFTER_MS = 2e3;
|
|
451
|
-
const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
|
|
452
|
-
const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
|
|
453
|
-
status: "ignored",
|
|
454
|
-
reason: "in-flight"
|
|
455
|
-
});
|
|
456
|
-
const IGNORED_NOTHING$1 = /* @__PURE__ */ Object.freeze({
|
|
457
|
-
status: "ignored",
|
|
458
|
-
reason: "nothing-to-retry"
|
|
459
|
-
});
|
|
460
|
-
const IGNORED_NOT_RETRYABLE$1 = /* @__PURE__ */ Object.freeze({
|
|
461
|
-
status: "ignored",
|
|
462
|
-
reason: "not-retryable"
|
|
463
|
-
});
|
|
464
|
-
const IGNORED_CANCELLED$1 = /* @__PURE__ */ Object.freeze({
|
|
465
|
-
status: "ignored",
|
|
466
|
-
reason: "cancelled"
|
|
467
|
-
});
|
|
468
|
-
function resolveResetDelay$1(value) {
|
|
469
|
-
if (value === false || value === Infinity) return null;
|
|
470
|
-
if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
|
|
471
|
-
return Math.max(0, value);
|
|
472
|
-
}
|
|
473
|
-
/** Pure helper: can `retry()` do anything from this state? */
|
|
474
|
-
function canRetryState(state, maxRetries) {
|
|
475
|
-
return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
|
|
476
|
-
}
|
|
477
|
-
let defaultAdapter$1;
|
|
478
|
-
const getDefaultAdapter$1 = () => defaultAdapter$1 ?? (defaultAdapter$1 = createBrowserClipboardAdapter());
|
|
479
|
-
/** Framework-agnostic copy state machine. */
|
|
480
|
-
function createCopyMachine(options = {}) {
|
|
481
|
-
const read = typeof options === "function" ? options : () => options;
|
|
482
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
483
|
-
let state = IDLE_STATE;
|
|
484
|
-
let generation = 0;
|
|
485
|
-
let resetTimer;
|
|
486
|
-
const operations = createOperations();
|
|
487
|
-
const now = () => (read().now ?? Date.now)();
|
|
488
|
-
let joined = null;
|
|
489
|
-
const member = { release: () => {
|
|
490
|
-
if (state.status === "copied") {
|
|
491
|
-
clearResetTimer();
|
|
492
|
-
setState(IDLE_STATE);
|
|
493
|
-
}
|
|
494
|
-
} };
|
|
495
|
-
const setState = (next) => {
|
|
496
|
-
if (next === state) return;
|
|
497
|
-
const previous = state;
|
|
498
|
-
state = next;
|
|
499
|
-
if (previous.status === "copied" && next.status !== "copied" && joined) {
|
|
500
|
-
joined.deactivate(member);
|
|
501
|
-
joined = null;
|
|
502
|
-
}
|
|
503
|
-
for (const listener of Array.from(listeners)) listener();
|
|
504
|
-
};
|
|
505
|
-
const joinCoordinator = () => {
|
|
506
|
-
joined = read().coordinator ?? null;
|
|
507
|
-
joined?.activate(member);
|
|
508
|
-
};
|
|
509
|
-
const clearResetTimer = () => {
|
|
510
|
-
if (resetTimer !== void 0) {
|
|
511
|
-
clearTimeout(resetTimer);
|
|
512
|
-
resetTimer = void 0;
|
|
513
|
-
}
|
|
514
|
-
};
|
|
515
|
-
const scheduleReset = (copied) => {
|
|
516
|
-
clearResetTimer();
|
|
517
|
-
const delay = resolveResetDelay$1(read().resetAfterMs);
|
|
518
|
-
if (delay === null) return;
|
|
519
|
-
const remaining = Math.max(0, delay - (now() - copied.at));
|
|
520
|
-
resetTimer = setTimeout(() => {
|
|
521
|
-
resetTimer = void 0;
|
|
522
|
-
setState(IDLE_STATE);
|
|
523
|
-
}, remaining);
|
|
524
|
-
};
|
|
525
|
-
const settleError = (error, payload, retryCount) => {
|
|
526
|
-
setState({
|
|
527
|
-
status: "error",
|
|
528
|
-
payload,
|
|
529
|
-
error,
|
|
530
|
-
retryCount
|
|
531
|
-
});
|
|
532
|
-
invoke(read().onError, error, payload);
|
|
533
|
-
};
|
|
534
|
-
const run = (source, retryCount) => {
|
|
535
|
-
clearResetTimer();
|
|
536
|
-
const current = ++generation;
|
|
537
|
-
let payload;
|
|
538
|
-
try {
|
|
539
|
-
const resolved = typeof source === "function" ? source() : source;
|
|
540
|
-
const resolvedUnknown = resolved;
|
|
541
|
-
if (resolvedUnknown !== null && typeof resolvedUnknown === "object" && typeof resolvedUnknown.then === "function") {
|
|
542
|
-
const error = createCopyError("invalid-payload", "The copy source function must be synchronous. Returning a Promise breaks the user-gesture window required for clipboard writes. Generate your content before calling copy().");
|
|
543
|
-
settleError(error, null, retryCount);
|
|
544
|
-
return Promise.resolve({
|
|
545
|
-
status: "error",
|
|
546
|
-
error
|
|
547
|
-
});
|
|
548
|
-
}
|
|
549
|
-
payload = normalizePayload(resolved);
|
|
550
|
-
} catch (cause) {
|
|
551
|
-
const error = sourceError(cause, "The copy source function threw.");
|
|
552
|
-
settleError(error, null, retryCount);
|
|
553
|
-
return Promise.resolve({
|
|
554
|
-
status: "error",
|
|
555
|
-
error
|
|
556
|
-
});
|
|
557
|
-
}
|
|
558
|
-
const invalid = validatePayload(payload);
|
|
559
|
-
if (invalid) {
|
|
560
|
-
settleError(invalid, payload, retryCount);
|
|
561
|
-
return Promise.resolve({
|
|
562
|
-
status: "error",
|
|
563
|
-
error: invalid
|
|
564
|
-
});
|
|
565
|
-
}
|
|
566
|
-
setState({
|
|
567
|
-
status: "copying",
|
|
568
|
-
payload,
|
|
569
|
-
retryCount
|
|
570
|
-
});
|
|
571
|
-
const context = operations.start();
|
|
572
|
-
let pending;
|
|
573
|
-
try {
|
|
574
|
-
pending = (read().adapter ?? getDefaultAdapter$1()).write(payload, context);
|
|
575
|
-
} catch (cause) {
|
|
576
|
-
pending = Promise.reject(cause);
|
|
577
|
-
}
|
|
578
|
-
return pending.then(() => {
|
|
579
|
-
operations.end(context);
|
|
580
|
-
if (current === generation) {
|
|
581
|
-
const copied = {
|
|
582
|
-
status: "copied",
|
|
583
|
-
payload,
|
|
584
|
-
at: now()
|
|
585
|
-
};
|
|
586
|
-
setState(copied);
|
|
587
|
-
joinCoordinator();
|
|
588
|
-
scheduleReset(copied);
|
|
589
|
-
invoke(read().onCopy, payload);
|
|
590
|
-
}
|
|
591
|
-
return {
|
|
592
|
-
status: "copied",
|
|
593
|
-
payload
|
|
594
|
-
};
|
|
595
|
-
}, (cause) => {
|
|
596
|
-
operations.end(context);
|
|
597
|
-
if (context.signal.aborted) return IGNORED_CANCELLED$1;
|
|
598
|
-
const error = toCopyError(cause);
|
|
599
|
-
settleError(error, payload, retryCount);
|
|
600
|
-
return {
|
|
601
|
-
status: "error",
|
|
602
|
-
error
|
|
603
|
-
};
|
|
604
|
-
});
|
|
605
|
-
};
|
|
606
|
-
const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
|
|
607
|
-
const retry = () => {
|
|
608
|
-
if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING$1);
|
|
609
|
-
if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE$1);
|
|
610
|
-
if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
|
|
611
|
-
const error = createCopyError("max-retries-exceeded", `Copy failed after ${String(state.retryCount)} retries.`, state.error);
|
|
612
|
-
settleError(error, state.payload, state.retryCount);
|
|
613
|
-
return Promise.resolve({
|
|
614
|
-
status: "error",
|
|
615
|
-
error
|
|
616
|
-
});
|
|
617
|
-
}
|
|
618
|
-
return run(state.payload, state.retryCount + 1);
|
|
619
|
-
};
|
|
620
|
-
const reset = () => {
|
|
621
|
-
++generation;
|
|
622
|
-
const cancelled = operations.abort();
|
|
623
|
-
clearResetTimer();
|
|
624
|
-
const wasIdle = state.status === "idle";
|
|
625
|
-
setState(IDLE_STATE);
|
|
626
|
-
if (cancelled) invoke(read().onCancel, "reset");
|
|
627
|
-
if (!wasIdle) invoke(read().onReset);
|
|
628
|
-
};
|
|
629
|
-
const connect = () => {
|
|
630
|
-
if (state.status === "copied") scheduleReset(state);
|
|
631
|
-
return () => {
|
|
632
|
-
++generation;
|
|
633
|
-
const cancelled = operations.abort();
|
|
634
|
-
clearResetTimer();
|
|
635
|
-
if (state.status === "copying") setState(IDLE_STATE);
|
|
636
|
-
if (cancelled) invoke(read().onCancel, "disconnect");
|
|
637
|
-
};
|
|
638
|
-
};
|
|
639
|
-
return {
|
|
640
|
-
getSnapshot: () => state,
|
|
641
|
-
subscribe: (listener) => {
|
|
642
|
-
listeners.add(listener);
|
|
643
|
-
return () => {
|
|
644
|
-
listeners.delete(listener);
|
|
645
|
-
};
|
|
646
|
-
},
|
|
647
|
-
copy,
|
|
648
|
-
retry,
|
|
649
|
-
reset,
|
|
650
|
-
connect
|
|
651
|
-
};
|
|
652
|
-
}
|
|
653
|
-
//#endregion
|
|
654
|
-
//#region src/core/copy-interceptor.ts
|
|
655
|
-
const DEFAULT_INTERCEPTED_EVENTS = ["copy", "cut"];
|
|
656
|
-
function isNode(value) {
|
|
657
|
-
return typeof value === "object" && value !== null && typeof value.nodeType === "number";
|
|
658
|
-
}
|
|
659
|
-
function readTextField(target) {
|
|
660
|
-
if (!isNode(target) || target.nodeType !== 1) return null;
|
|
661
|
-
const tag = target.tagName;
|
|
662
|
-
if (tag !== "INPUT" && tag !== "TEXTAREA") return null;
|
|
663
|
-
const field = target;
|
|
664
|
-
try {
|
|
665
|
-
const { selectionStart: start, selectionEnd: end } = field;
|
|
666
|
-
return typeof start === "number" && typeof end === "number" ? {
|
|
667
|
-
field,
|
|
668
|
-
start,
|
|
669
|
-
end
|
|
670
|
-
} : null;
|
|
671
|
-
} catch {
|
|
672
|
-
return null;
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
function documentOf(target) {
|
|
676
|
-
if (isNode(target)) return target.nodeType === 9 ? target : target.ownerDocument;
|
|
677
|
-
return typeof document === "undefined" ? null : document;
|
|
678
|
-
}
|
|
679
|
-
function isEditableNode(node) {
|
|
680
|
-
return (node.nodeType === 1 ? node : node.parentElement)?.isContentEditable === true;
|
|
681
|
-
}
|
|
682
|
-
function selectedRanges(doc) {
|
|
683
|
-
const selection = doc?.getSelection();
|
|
684
|
-
if (!selection || selection.isCollapsed) return null;
|
|
685
|
-
const ranges = [];
|
|
686
|
-
for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));
|
|
687
|
-
return {
|
|
688
|
-
selection,
|
|
689
|
-
ranges
|
|
690
|
-
};
|
|
691
|
-
}
|
|
692
|
-
function readSelection(event) {
|
|
693
|
-
const kind = event.type === "cut" ? "cut" : "copy";
|
|
694
|
-
const fieldSelection = readTextField(event.target);
|
|
695
|
-
if (fieldSelection) {
|
|
696
|
-
const { field, start, end } = fieldSelection;
|
|
697
|
-
const text = field.value.slice(Math.min(start, end), Math.max(start, end));
|
|
698
|
-
if (text.length === 0) return null;
|
|
699
|
-
return {
|
|
700
|
-
selection: {
|
|
701
|
-
kind,
|
|
702
|
-
text,
|
|
703
|
-
html: null,
|
|
704
|
-
fragment: null,
|
|
705
|
-
field,
|
|
706
|
-
editable: !field.readOnly && !field.disabled
|
|
707
|
-
},
|
|
708
|
-
doc: field.ownerDocument
|
|
709
|
-
};
|
|
710
|
-
}
|
|
711
|
-
const doc = documentOf(event.target);
|
|
712
|
-
const selected = selectedRanges(doc);
|
|
713
|
-
const first = selected?.ranges[0];
|
|
714
|
-
if (!doc || !selected || !first) return null;
|
|
715
|
-
const text = selected.selection.toString();
|
|
716
|
-
if (text.length === 0) return null;
|
|
717
|
-
const container = doc.createElement("div");
|
|
718
|
-
for (const range of selected.ranges) container.appendChild(range.cloneContents());
|
|
719
|
-
const html = container.innerHTML;
|
|
720
|
-
const fragment = doc.createDocumentFragment();
|
|
721
|
-
while (container.firstChild) fragment.appendChild(container.firstChild);
|
|
722
|
-
return {
|
|
723
|
-
selection: {
|
|
724
|
-
kind,
|
|
725
|
-
text,
|
|
726
|
-
html,
|
|
727
|
-
fragment,
|
|
728
|
-
field: null,
|
|
729
|
-
editable: isEditableNode(first.startContainer)
|
|
730
|
-
},
|
|
731
|
-
doc
|
|
732
|
-
};
|
|
733
|
-
}
|
|
734
|
-
/** Reads the selection behind a copy event, or `null` if nothing readable is selected. */
|
|
735
|
-
function readCopySelection(event) {
|
|
736
|
-
const read = readSelection(event);
|
|
737
|
-
return read ? read.selection : null;
|
|
738
|
-
}
|
|
739
|
-
const nonEmpty$1 = (value) => typeof value === "string" && value.length > 0;
|
|
740
|
-
const invalid$4 = (message, cause) => ({
|
|
741
|
-
ok: false,
|
|
742
|
-
error: createCopyError("invalid-payload", message, cause)
|
|
743
|
-
});
|
|
744
|
-
const unsupported$1 = (message) => ({
|
|
745
|
-
ok: false,
|
|
746
|
-
error: createCopyError("unsupported-format", message)
|
|
747
|
-
});
|
|
748
|
-
/**
|
|
749
|
-
* Validates a decision and turns it into `[mimeType, data]` pairs. Kept
|
|
750
|
-
* self-contained (no shared validator) so the interceptor stays small; the
|
|
751
|
-
* checks still run for plain-JS callers the types can't protect.
|
|
752
|
-
*/
|
|
753
|
-
function prepare(decision) {
|
|
754
|
-
const candidate = typeof decision === "string" ? {
|
|
755
|
-
kind: "text",
|
|
756
|
-
value: decision
|
|
757
|
-
} : decision;
|
|
758
|
-
if (typeof candidate !== "object" || candidate === null) return invalid$4("Copy transforms must return a string, a payload, false, or nothing.");
|
|
759
|
-
if (typeof candidate.then === "function") return invalid$4("Copy transforms must be synchronous; the clipboard closes when the event ends.");
|
|
760
|
-
const payload = candidate;
|
|
761
|
-
const fields = candidate;
|
|
762
|
-
const ok = (entries) => ({
|
|
763
|
-
ok: true,
|
|
764
|
-
payload,
|
|
765
|
-
entries
|
|
766
|
-
});
|
|
767
|
-
switch (fields["kind"]) {
|
|
768
|
-
case "text": return nonEmpty$1(fields["value"]) ? ok([["text/plain", fields["value"]]]) : invalid$4("Text payload must be a non-empty string.");
|
|
769
|
-
case "html": return nonEmpty$1(fields["html"]) && nonEmpty$1(fields["text"]) ? ok([["text/html", fields["html"]], ["text/plain", fields["text"]]]) : invalid$4("HTML payload requires non-empty `html` and plain-text `text`.");
|
|
770
|
-
case "json": {
|
|
771
|
-
const pretty = fields["pretty"];
|
|
772
|
-
const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
|
|
773
|
-
let json;
|
|
774
|
-
try {
|
|
775
|
-
json = JSON.stringify(fields["value"], null, indent);
|
|
776
|
-
} catch (cause) {
|
|
777
|
-
return invalid$4("JSON payload could not be serialised (circular reference or BigInt?).", cause);
|
|
778
|
-
}
|
|
779
|
-
return typeof json === "string" ? ok([["text/plain", json]]) : invalid$4("JSON payload serialised to nothing.");
|
|
780
|
-
}
|
|
781
|
-
case "multi": {
|
|
782
|
-
const items = fields["items"];
|
|
783
|
-
if (!Array.isArray(items) || items.length === 0) return invalid$4("Multi payload requires at least one item.");
|
|
784
|
-
const entries = [];
|
|
785
|
-
for (const item of items) {
|
|
786
|
-
const { mimeType, data } = item ?? {};
|
|
787
|
-
if (!nonEmpty$1(mimeType) || entries.some(([seen]) => seen === mimeType)) return invalid$4("Every multi item needs a unique, non-empty `mimeType`.");
|
|
788
|
-
if (typeof data !== "string") return unsupported$1(`Multi item "${mimeType}" must be a string during a copy event.`);
|
|
789
|
-
entries.push([mimeType, data]);
|
|
790
|
-
}
|
|
791
|
-
const writable = entries.filter(([mimeType]) => !isWebCustomFormat(mimeType));
|
|
792
|
-
return writable.length > 0 ? ok(writable) : unsupported$1("Web custom formats need the async Clipboard API (useCopy).");
|
|
793
|
-
}
|
|
794
|
-
default: return unsupported$1(`"${String(fields["kind"])}" payloads cannot be written during a copy event; use useCopy() for images.`);
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
/** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */
|
|
798
|
-
function deleteSelection(doc) {
|
|
799
|
-
const legacy = doc;
|
|
800
|
-
try {
|
|
801
|
-
return legacy.execCommand?.("delete") === true;
|
|
802
|
-
} catch {
|
|
803
|
-
return false;
|
|
804
|
-
}
|
|
805
|
-
}
|
|
806
|
-
/**
|
|
807
|
-
* Applies a transform to one `copy`/`cut` event. Use directly from an
|
|
808
|
-
* `onCopy` handler, or let {@link registerCopyInterceptor} scope it.
|
|
809
|
-
*/
|
|
810
|
-
function interceptCopyEvent(event, options) {
|
|
811
|
-
if (event.type !== "copy" && event.type !== "cut") return {
|
|
812
|
-
status: "passed",
|
|
813
|
-
reason: "unsupported-event",
|
|
814
|
-
selection: null
|
|
815
|
-
};
|
|
816
|
-
if (event.defaultPrevented) return {
|
|
817
|
-
status: "passed",
|
|
818
|
-
reason: "already-handled",
|
|
819
|
-
selection: null
|
|
820
|
-
};
|
|
821
|
-
const read = readSelection(event);
|
|
822
|
-
if (!read) return {
|
|
823
|
-
status: "passed",
|
|
824
|
-
reason: "no-selection",
|
|
825
|
-
selection: null
|
|
826
|
-
};
|
|
827
|
-
const { selection, doc } = read;
|
|
828
|
-
const fail = (error) => {
|
|
829
|
-
const fallback = options.failureMode ?? "block";
|
|
830
|
-
if (fallback === "block") event.preventDefault();
|
|
831
|
-
return {
|
|
832
|
-
status: "failed",
|
|
833
|
-
selection,
|
|
834
|
-
error,
|
|
835
|
-
fallback
|
|
836
|
-
};
|
|
837
|
-
};
|
|
838
|
-
let decision;
|
|
839
|
-
try {
|
|
840
|
-
decision = options.transform(selection);
|
|
841
|
-
} catch (cause) {
|
|
842
|
-
return fail(sourceError(cause, "The copy transform threw."));
|
|
843
|
-
}
|
|
844
|
-
if (decision === null || decision === void 0) return {
|
|
845
|
-
status: "passed",
|
|
846
|
-
reason: "declined",
|
|
847
|
-
selection
|
|
848
|
-
};
|
|
849
|
-
if (decision === false) {
|
|
850
|
-
event.preventDefault();
|
|
851
|
-
return {
|
|
852
|
-
status: "blocked",
|
|
853
|
-
selection
|
|
854
|
-
};
|
|
855
|
-
}
|
|
856
|
-
const prepared = prepare(decision);
|
|
857
|
-
if (!prepared.ok) return fail(prepared.error);
|
|
858
|
-
const data = event.clipboardData;
|
|
859
|
-
if (!data) return fail(createCopyError("unsupported", "This browser exposes no clipboardData on copy events."));
|
|
860
|
-
event.preventDefault();
|
|
861
|
-
try {
|
|
862
|
-
for (const [mimeType, value] of prepared.entries) data.setData(mimeType, value);
|
|
863
|
-
} catch (cause) {
|
|
864
|
-
try {
|
|
865
|
-
data.clearData?.();
|
|
866
|
-
} catch {}
|
|
867
|
-
return {
|
|
868
|
-
status: "failed",
|
|
869
|
-
selection,
|
|
870
|
-
error: createCopyError("unknown", "The browser rejected the clipboard write.", cause),
|
|
871
|
-
fallback: "block"
|
|
872
|
-
};
|
|
873
|
-
}
|
|
874
|
-
const deleted = selection.kind === "cut" && selection.editable && deleteSelection(doc);
|
|
875
|
-
return {
|
|
876
|
-
status: "written",
|
|
877
|
-
selection,
|
|
878
|
-
payload: prepared.payload,
|
|
879
|
-
deleted
|
|
880
|
-
};
|
|
881
|
-
}
|
|
882
|
-
const registries = /* @__PURE__ */ new WeakMap();
|
|
883
|
-
function touches(root, event) {
|
|
884
|
-
const fieldSelection = readTextField(event.target);
|
|
885
|
-
if (fieldSelection) return root.contains(fieldSelection.field);
|
|
886
|
-
const selected = selectedRanges(root.ownerDocument);
|
|
887
|
-
return selected !== null && selected.ranges.some((range) => range.intersectsNode(root));
|
|
888
|
-
}
|
|
889
|
-
const priorityOf = (scope) => scope.read().priority ?? 0;
|
|
890
|
-
/**
|
|
891
|
-
* Highest `priority` first; then the innermost scope; then document order;
|
|
892
|
-
* then registration order (same root). A total order, so the result never
|
|
893
|
-
* depends on effect timing.
|
|
894
|
-
*/
|
|
895
|
-
function compareScopes(a, b) {
|
|
896
|
-
const byPriority = priorityOf(b) - priorityOf(a);
|
|
897
|
-
if (byPriority !== 0) return byPriority;
|
|
898
|
-
const position = a.root.compareDocumentPosition(b.root);
|
|
899
|
-
if (position === 0) return 0;
|
|
900
|
-
if (position & 16) return 1;
|
|
901
|
-
if (position & 8) return -1;
|
|
902
|
-
return position & 4 ? -1 : 1;
|
|
903
|
-
}
|
|
904
|
-
function dispatch(registry, event) {
|
|
905
|
-
if (event.defaultPrevented) return;
|
|
906
|
-
const kind = event.type;
|
|
907
|
-
const [scope] = [...registry.scopes].filter((scope) => (scope.read().events ?? DEFAULT_INTERCEPTED_EVENTS).includes(kind) && touches(scope.root, event)).sort(compareScopes);
|
|
908
|
-
if (!scope) return;
|
|
909
|
-
const options = scope.read();
|
|
910
|
-
const outcome = interceptCopyEvent(event, options);
|
|
911
|
-
invoke(options.onIntercept, outcome);
|
|
912
|
-
if (outcome.status === "failed") invoke(options.onError, outcome.error);
|
|
913
|
-
}
|
|
914
|
-
/**
|
|
915
|
-
* Intercepts native copies and cuts whose selection touches `root`. Returns
|
|
916
|
-
* an unsubscribe function. Pass a getter to always read the latest options.
|
|
917
|
-
*
|
|
918
|
-
* One listener per document serves every scope, so overlapping scopes
|
|
919
|
-
* resolve deterministically (see `priority`) regardless of registration order.
|
|
920
|
-
* Handlers that call `preventDefault()` first (e.g. a React `onCopy`) win.
|
|
921
|
-
*/
|
|
922
|
-
function registerCopyInterceptor(root, options) {
|
|
923
|
-
const doc = root.ownerDocument;
|
|
924
|
-
let registry = registries.get(doc);
|
|
925
|
-
if (!registry) {
|
|
926
|
-
const created = {
|
|
927
|
-
scopes: /* @__PURE__ */ new Set(),
|
|
928
|
-
listener: (event) => {
|
|
929
|
-
dispatch(created, event);
|
|
930
|
-
}
|
|
931
|
-
};
|
|
932
|
-
registry = created;
|
|
933
|
-
registries.set(doc, created);
|
|
934
|
-
doc.addEventListener("copy", created.listener);
|
|
935
|
-
doc.addEventListener("cut", created.listener);
|
|
936
|
-
}
|
|
937
|
-
const scope = {
|
|
938
|
-
root,
|
|
939
|
-
read: typeof options === "function" ? options : () => options
|
|
940
|
-
};
|
|
941
|
-
registry.scopes.add(scope);
|
|
942
|
-
const active = registry;
|
|
943
|
-
let registered = true;
|
|
944
|
-
return () => {
|
|
945
|
-
if (!registered) return;
|
|
946
|
-
registered = false;
|
|
947
|
-
active.scopes.delete(scope);
|
|
948
|
-
if (active.scopes.size === 0) {
|
|
949
|
-
doc.removeEventListener("copy", active.listener);
|
|
950
|
-
doc.removeEventListener("cut", active.listener);
|
|
951
|
-
registries.delete(doc);
|
|
952
|
-
}
|
|
953
|
-
};
|
|
954
|
-
}
|
|
955
|
-
//#endregion
|
|
956
|
-
//#region src/core/drag-copy.ts
|
|
957
|
-
/**
|
|
958
|
-
* Drag-to-copy: populate `DataTransfer` when the user starts dragging an
|
|
959
|
-
* element, so whatever they drop it into receives structured data — plain text,
|
|
960
|
-
* HTML, JSON, or multiple MIME types — instead of the browser's default
|
|
961
|
-
* text-extraction of the dragged DOM.
|
|
962
|
-
*
|
|
963
|
-
* No Clipboard API, no permission prompt, works in every browser that supports
|
|
964
|
-
* HTML5 drag-and-drop (all modern browsers and IE11+).
|
|
965
|
-
*/
|
|
966
|
-
const nonEmpty = (value) => typeof value === "string" && value.length > 0;
|
|
967
|
-
const invalid$3 = (message, cause) => ({
|
|
968
|
-
ok: false,
|
|
969
|
-
error: createCopyError("invalid-payload", message, cause)
|
|
970
|
-
});
|
|
971
|
-
const unsupported = (message) => ({
|
|
972
|
-
ok: false,
|
|
973
|
-
error: createCopyError("unsupported-format", message)
|
|
974
|
-
});
|
|
975
|
-
function prepareDragDecision(decision) {
|
|
976
|
-
const candidate = typeof decision === "string" ? {
|
|
977
|
-
kind: "text",
|
|
978
|
-
value: decision
|
|
979
|
-
} : decision;
|
|
980
|
-
if (typeof candidate !== "object" || candidate === null) return invalid$3("Drag source must return a string, a payload, false, or nothing.");
|
|
981
|
-
if (typeof candidate.then === "function") return invalid$3("Drag sources must be synchronous; DataTransfer closes when dragstart returns.");
|
|
982
|
-
const payload = candidate;
|
|
983
|
-
const fields = candidate;
|
|
984
|
-
const ok = (items) => ({
|
|
985
|
-
ok: true,
|
|
986
|
-
payload,
|
|
987
|
-
items
|
|
988
|
-
});
|
|
989
|
-
switch (fields["kind"]) {
|
|
990
|
-
case "text": return nonEmpty(fields["value"]) ? ok([{
|
|
991
|
-
mimeType: "text/plain",
|
|
992
|
-
data: fields["value"]
|
|
993
|
-
}]) : invalid$3("Text payload must be a non-empty string.");
|
|
994
|
-
case "html": return nonEmpty(fields["html"]) && nonEmpty(fields["text"]) ? ok([{
|
|
995
|
-
mimeType: "text/html",
|
|
996
|
-
data: fields["html"]
|
|
997
|
-
}, {
|
|
998
|
-
mimeType: "text/plain",
|
|
999
|
-
data: fields["text"]
|
|
1000
|
-
}]) : invalid$3("HTML payload requires non-empty `html` and `text`.");
|
|
1001
|
-
case "json": {
|
|
1002
|
-
const pretty = fields["pretty"];
|
|
1003
|
-
const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
|
|
1004
|
-
let json;
|
|
1005
|
-
try {
|
|
1006
|
-
json = JSON.stringify(fields["value"], null, indent);
|
|
1007
|
-
} catch (cause) {
|
|
1008
|
-
return invalid$3("JSON payload could not be serialised (circular reference or BigInt?).", cause);
|
|
1009
|
-
}
|
|
1010
|
-
return typeof json === "string" ? ok([{
|
|
1011
|
-
mimeType: "text/plain",
|
|
1012
|
-
data: json
|
|
1013
|
-
}]) : invalid$3("JSON payload serialised to nothing.");
|
|
1014
|
-
}
|
|
1015
|
-
case "multi": {
|
|
1016
|
-
const items = fields["items"];
|
|
1017
|
-
if (!Array.isArray(items) || items.length === 0) return invalid$3("Multi payload requires at least one item.");
|
|
1018
|
-
const out = [];
|
|
1019
|
-
for (const item of items) {
|
|
1020
|
-
const { mimeType, data } = item ?? {};
|
|
1021
|
-
if (!nonEmpty(mimeType) || out.some((i) => i.mimeType === mimeType)) return invalid$3("Every multi item needs a unique, non-empty `mimeType`.");
|
|
1022
|
-
if (typeof data !== "string") return unsupported(`Multi item "${mimeType}" must be a string; DataTransfer does not accept Blobs.`);
|
|
1023
|
-
out.push({
|
|
1024
|
-
mimeType,
|
|
1025
|
-
data
|
|
1026
|
-
});
|
|
1027
|
-
}
|
|
1028
|
-
const writable = out.filter((item) => !isWebCustomFormat(item.mimeType));
|
|
1029
|
-
return writable.length > 0 ? ok(writable) : unsupported("Web custom formats need the async Clipboard API (useCopy).");
|
|
1030
|
-
}
|
|
1031
|
-
default: return unsupported(`"${String(fields["kind"])}" payloads cannot be used for drag-copy; use useCopy() for images.`);
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
/**
|
|
1035
|
-
* Populates a `dragstart` event's `DataTransfer` with the given payload.
|
|
1036
|
-
* Use this from a raw `dragstart` handler or a React `onDragStart` prop.
|
|
1037
|
-
* Returns the outcome so you can inspect what happened.
|
|
1038
|
-
*/
|
|
1039
|
-
function applyDragCopy(event, options) {
|
|
1040
|
-
if (event.defaultPrevented) return {
|
|
1041
|
-
status: "passed",
|
|
1042
|
-
reason: "declined"
|
|
1043
|
-
};
|
|
1044
|
-
let decision;
|
|
1045
|
-
try {
|
|
1046
|
-
decision = options.source(event);
|
|
1047
|
-
} catch (cause) {
|
|
1048
|
-
return {
|
|
1049
|
-
status: "failed",
|
|
1050
|
-
error: sourceError(cause, "The drag source threw.")
|
|
1051
|
-
};
|
|
1052
|
-
}
|
|
1053
|
-
if (decision === null || decision === void 0) return {
|
|
1054
|
-
status: "passed",
|
|
1055
|
-
reason: "declined"
|
|
1056
|
-
};
|
|
1057
|
-
if (decision === false) {
|
|
1058
|
-
event.preventDefault();
|
|
1059
|
-
return {
|
|
1060
|
-
status: "passed",
|
|
1061
|
-
reason: "cancelled"
|
|
1062
|
-
};
|
|
1063
|
-
}
|
|
1064
|
-
const transfer = event.dataTransfer;
|
|
1065
|
-
if (!transfer) return {
|
|
1066
|
-
status: "passed",
|
|
1067
|
-
reason: "no-transfer"
|
|
1068
|
-
};
|
|
1069
|
-
const prepared = prepareDragDecision(decision);
|
|
1070
|
-
if (!prepared.ok) return {
|
|
1071
|
-
status: "failed",
|
|
1072
|
-
error: prepared.error
|
|
1073
|
-
};
|
|
1074
|
-
try {
|
|
1075
|
-
transfer.effectAllowed = options.effectAllowed ?? "copy";
|
|
1076
|
-
for (const { mimeType, data } of prepared.items) transfer.setData(mimeType, data);
|
|
1077
|
-
} catch (cause) {
|
|
1078
|
-
try {
|
|
1079
|
-
transfer.clearData?.();
|
|
1080
|
-
} catch {}
|
|
1081
|
-
return {
|
|
1082
|
-
status: "failed",
|
|
1083
|
-
error: createCopyError("unknown", "The browser rejected the DataTransfer write.", cause)
|
|
1084
|
-
};
|
|
1085
|
-
}
|
|
1086
|
-
return {
|
|
1087
|
-
status: "written",
|
|
1088
|
-
payload: prepared.payload
|
|
1089
|
-
};
|
|
1090
|
-
}
|
|
1091
|
-
/**
|
|
1092
|
-
* Attaches `dragstart` and `dragend` listeners to `element`, calling
|
|
1093
|
-
* `applyDragCopy` on every drag start. Returns an object with an
|
|
1094
|
-
* `unsubscribe` function.
|
|
1095
|
-
*
|
|
1096
|
-
* Pass an options getter so the latest options are always used without
|
|
1097
|
-
* re-registering — safe to pass an inline object from a React render.
|
|
1098
|
-
*
|
|
1099
|
-
* ```ts
|
|
1100
|
-
* const { unsubscribe } = registerDragCopy(el, () => ({
|
|
1101
|
-
* source: () => `${title}\n${url}`,
|
|
1102
|
-
* }));
|
|
1103
|
-
* ```
|
|
1104
|
-
*/
|
|
1105
|
-
function registerDragCopy(element, options) {
|
|
1106
|
-
const read = typeof options === "function" ? options : () => options;
|
|
1107
|
-
let unsubscribed = false;
|
|
1108
|
-
let currentOutcome = null;
|
|
1109
|
-
function onDragStart(raw) {
|
|
1110
|
-
const event = raw;
|
|
1111
|
-
const opts = read();
|
|
1112
|
-
const outcome = applyDragCopy({
|
|
1113
|
-
type: event.type,
|
|
1114
|
-
dataTransfer: event.dataTransfer,
|
|
1115
|
-
get defaultPrevented() {
|
|
1116
|
-
return event.defaultPrevented;
|
|
1117
|
-
},
|
|
1118
|
-
preventDefault: () => {
|
|
1119
|
-
event.preventDefault();
|
|
1120
|
-
}
|
|
1121
|
-
}, opts);
|
|
1122
|
-
currentOutcome = outcome;
|
|
1123
|
-
const state = {
|
|
1124
|
-
status: "dragging",
|
|
1125
|
-
outcome
|
|
1126
|
-
};
|
|
1127
|
-
if (outcome.status === "failed") invoke(opts.onError, outcome.error);
|
|
1128
|
-
invoke(opts.onDrag, state);
|
|
1129
|
-
}
|
|
1130
|
-
function onDragEnd() {
|
|
1131
|
-
const opts = read();
|
|
1132
|
-
const state = {
|
|
1133
|
-
status: "done",
|
|
1134
|
-
outcome: currentOutcome
|
|
1135
|
-
};
|
|
1136
|
-
invoke(opts.onDrag, state);
|
|
1137
|
-
currentOutcome = null;
|
|
1138
|
-
}
|
|
1139
|
-
element.setAttribute("draggable", "true");
|
|
1140
|
-
element.addEventListener("dragstart", onDragStart);
|
|
1141
|
-
element.addEventListener("dragend", onDragEnd);
|
|
1142
|
-
return { unsubscribe() {
|
|
1143
|
-
if (unsubscribed) return;
|
|
1144
|
-
unsubscribed = true;
|
|
1145
|
-
element.removeEventListener("dragstart", onDragStart);
|
|
1146
|
-
element.removeEventListener("dragend", onDragEnd);
|
|
1147
|
-
element.removeAttribute("draggable");
|
|
1148
|
-
} };
|
|
1149
|
-
}
|
|
1150
|
-
//#endregion
|
|
1151
|
-
//#region src/core/paste-reader.ts
|
|
1152
|
-
/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
|
|
1153
|
-
function completePasteResult(result) {
|
|
1154
|
-
const images = new Set(result.images);
|
|
1155
|
-
return {
|
|
1156
|
-
...result,
|
|
1157
|
-
imageFiles: result.files.filter((file) => images.has(file))
|
|
1158
|
-
};
|
|
1159
|
-
}
|
|
1160
|
-
const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
|
|
1161
|
-
const DEFAULT_PASTE_MAX_BYTES = 33554432;
|
|
1162
|
-
const DEFAULT_PASTE_MAX_ITEMS = 32;
|
|
1163
|
-
const SHORTHANDS = /* @__PURE__ */ new Map([
|
|
1164
|
-
["text", "text/plain"],
|
|
1165
|
-
["html", "text/html"],
|
|
1166
|
-
["image", "image/*"],
|
|
1167
|
-
["any", "*/*"]
|
|
1168
|
-
]);
|
|
1169
|
-
const TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
|
|
1170
|
-
function resolvePattern(entry) {
|
|
1171
|
-
if (typeof entry !== "string") return null;
|
|
1172
|
-
const shorthand = SHORTHANDS.get(entry);
|
|
1173
|
-
if (shorthand !== void 0) return shorthand;
|
|
1174
|
-
if (entry === "*/*") return entry;
|
|
1175
|
-
if (entry.endsWith("/*")) {
|
|
1176
|
-
const type = entry.slice(0, -2).toLowerCase();
|
|
1177
|
-
return TYPE_TOKEN.test(type) ? `${type}/*` : null;
|
|
1178
|
-
}
|
|
1179
|
-
return normalizeClipboardType(entry);
|
|
1180
|
-
}
|
|
1181
|
-
function resolveLimit(value, fallback, name) {
|
|
1182
|
-
if (value === void 0) return fallback;
|
|
1183
|
-
if (value === Infinity || Number.isInteger(value) && value > 0) return value;
|
|
1184
|
-
throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
|
|
1185
|
-
}
|
|
1186
|
-
/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
|
|
1187
|
-
function resolvePasteReadOptions(options = {}) {
|
|
1188
|
-
const accept = [];
|
|
1189
|
-
for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {
|
|
1190
|
-
const pattern = resolvePattern(entry);
|
|
1191
|
-
if (pattern === null) throw copyFailure("invalid-payload", `Invalid \`accept\` entry: ${JSON.stringify(entry)}.`);
|
|
1192
|
-
if (!accept.includes(pattern)) accept.push(pattern);
|
|
1193
|
-
}
|
|
1194
|
-
if (accept.length === 0) throw copyFailure("invalid-payload", "`accept` must list at least one type.");
|
|
1195
|
-
return {
|
|
1196
|
-
accept,
|
|
1197
|
-
maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, "maxBytes"),
|
|
1198
|
-
maxItems: resolveLimit(options.maxItems, 32, "maxItems")
|
|
1199
|
-
};
|
|
1200
|
-
}
|
|
1201
|
-
/** Whether a normalised MIME type is allowed by the resolved `accept` list. */
|
|
1202
|
-
function isAccepted(mimeType, options) {
|
|
1203
|
-
return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));
|
|
1204
|
-
}
|
|
1205
|
-
function createBudget(options) {
|
|
1206
|
-
let bytes = 0;
|
|
1207
|
-
let items = 0;
|
|
1208
|
-
return { charge: (size) => {
|
|
1209
|
-
items += 1;
|
|
1210
|
-
bytes += size;
|
|
1211
|
-
if (items > options.maxItems) throw copyFailure("too-large", `The paste has more than ${String(options.maxItems)} accepted items.`);
|
|
1212
|
-
if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
|
|
1213
|
-
} };
|
|
1214
|
-
}
|
|
1215
|
-
/**
|
|
1216
|
-
* UTF-8 byte length of a string, without allocating an encoded copy.
|
|
1217
|
-
* Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.
|
|
1218
|
-
*/
|
|
1219
|
-
function utf8ByteLength(text) {
|
|
1220
|
-
let bytes = 0;
|
|
1221
|
-
for (let i = 0; i < text.length; i += 1) {
|
|
1222
|
-
const unit = text.charCodeAt(i);
|
|
1223
|
-
if (unit < 128) bytes += 1;
|
|
1224
|
-
else if (unit < 2048) bytes += 2;
|
|
1225
|
-
else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length && (text.charCodeAt(i + 1) & 64512) === 56320) {
|
|
1226
|
-
bytes += 4;
|
|
1227
|
-
i += 1;
|
|
1228
|
-
} else bytes += 3;
|
|
1229
|
-
}
|
|
1230
|
-
return bytes;
|
|
1231
|
-
}
|
|
1232
|
-
/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */
|
|
1233
|
-
const sizeOf = (data) => typeof data === "string" ? utf8ByteLength(data) : data.size;
|
|
1234
|
-
/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
|
|
1235
|
-
function enforcePasteLimits(entries, options) {
|
|
1236
|
-
const budget = createBudget(options);
|
|
1237
|
-
for (const entry of entries) budget.charge(sizeOf(entry.data));
|
|
1238
|
-
}
|
|
1239
|
-
/**
|
|
1240
|
-
* Whether a drag in progress could drop anything `accept`s. Uses only what
|
|
1241
|
-
* browsers expose before the drop (item kinds and types, never the data).
|
|
1242
|
-
* A file whose type is not known yet (some browsers hide it while dragging)
|
|
1243
|
-
* counts as a maybe: the drop itself is checked against `accept`.
|
|
1244
|
-
*/
|
|
1245
|
-
function canAcceptDrag(data, options) {
|
|
1246
|
-
const items = data.items ?? Array.from(data.types, (type) => type === "Files" ? {
|
|
1247
|
-
kind: "file",
|
|
1248
|
-
type: ""
|
|
1249
|
-
} : {
|
|
1250
|
-
kind: "string",
|
|
1251
|
-
type
|
|
1252
|
-
});
|
|
1253
|
-
return Array.from(items).some(({ kind, type: raw }) => {
|
|
1254
|
-
const file = kind === "file";
|
|
1255
|
-
const type = normalizeClipboardType(raw);
|
|
1256
|
-
if (type === null) return file;
|
|
1257
|
-
return (file || isTextualMimeType(type)) && isAccepted(type, options);
|
|
1258
|
-
});
|
|
1259
|
-
}
|
|
1260
|
-
/**
|
|
1261
|
-
* Synchronously copies the accepted parts of a paste event's `DataTransfer`.
|
|
1262
|
-
* It must run during the event: browsers empty the object afterwards.
|
|
1263
|
-
*/
|
|
1264
|
-
function snapshotDataTransfer(data, options) {
|
|
1265
|
-
const entries = [];
|
|
1266
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1267
|
-
for (const raw of Array.from(data.types)) {
|
|
1268
|
-
const type = normalizeClipboardType(raw);
|
|
1269
|
-
if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;
|
|
1270
|
-
seen.add(type);
|
|
1271
|
-
const text = data.getData(raw);
|
|
1272
|
-
if (text.length > 0) entries.push({
|
|
1273
|
-
type,
|
|
1274
|
-
data: text,
|
|
1275
|
-
file: false
|
|
1276
|
-
});
|
|
1277
|
-
}
|
|
1278
|
-
for (const file of Array.from(data.files ?? [])) {
|
|
1279
|
-
const type = normalizeMimeType(file.type) ?? "application/octet-stream";
|
|
1280
|
-
if (isAccepted(type, options)) entries.push({
|
|
1281
|
-
type,
|
|
1282
|
-
data: file,
|
|
1283
|
-
file: true
|
|
1284
|
-
});
|
|
1285
|
-
}
|
|
1286
|
-
return entries;
|
|
1287
|
-
}
|
|
1288
|
-
/**
|
|
1289
|
-
* Reads the accepted types from `navigator.clipboard.read()` items, enforcing
|
|
1290
|
-
* the limits *before* decoding any text so an oversized paste is never buffered twice.
|
|
1291
|
-
*/
|
|
1292
|
-
async function collectClipboardItems(items, options, signal) {
|
|
1293
|
-
const budget = createBudget(options);
|
|
1294
|
-
const entries = [];
|
|
1295
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1296
|
-
for (const item of items) for (const raw of item.types) {
|
|
1297
|
-
const type = normalizeClipboardType(raw);
|
|
1298
|
-
if (type === null || seen.has(type) || !isAccepted(type, options)) continue;
|
|
1299
|
-
seen.add(type);
|
|
1300
|
-
let blob;
|
|
1301
|
-
try {
|
|
1302
|
-
blob = await item.getType(raw);
|
|
1303
|
-
} catch {
|
|
1304
|
-
continue;
|
|
1305
|
-
}
|
|
1306
|
-
if (signal?.aborted) throw copyFailure("aborted", "The paste was cancelled.");
|
|
1307
|
-
if (blob.size === 0) continue;
|
|
1308
|
-
budget.charge(blob.size);
|
|
1309
|
-
entries.push({
|
|
1310
|
-
type,
|
|
1311
|
-
data: isTextualMimeType(type) ? await blob.text() : blob,
|
|
1312
|
-
file: false
|
|
1313
|
-
});
|
|
1314
|
-
}
|
|
1315
|
-
return entries;
|
|
1316
|
-
}
|
|
1317
|
-
function retype(entry, data, type) {
|
|
1318
|
-
if (entry.file) {
|
|
1319
|
-
const file = data;
|
|
1320
|
-
return new File([file], file.name, {
|
|
1321
|
-
type,
|
|
1322
|
-
lastModified: file.lastModified
|
|
1323
|
-
});
|
|
1324
|
-
}
|
|
1325
|
-
return data.slice(0, data.size, type);
|
|
1326
|
-
}
|
|
1327
|
-
/**
|
|
1328
|
-
* Verifies image bytes, then builds the result. Blobs that claim to be images
|
|
1329
|
-
* but aren't (or whose real format is not accepted) are dropped. Throws
|
|
1330
|
-
* `no-content` when nothing survives.
|
|
1331
|
-
*/
|
|
1332
|
-
async function finalizePaste(entries, source, options) {
|
|
1333
|
-
const items = [];
|
|
1334
|
-
const images = [];
|
|
1335
|
-
const files = [];
|
|
1336
|
-
let text = null;
|
|
1337
|
-
let html = null;
|
|
1338
|
-
for (const entry of entries) {
|
|
1339
|
-
let { type, data } = entry;
|
|
1340
|
-
if (typeof data === "string") {
|
|
1341
|
-
if (type === "text/plain") text = data;
|
|
1342
|
-
else if (type === "text/html") html = data;
|
|
1343
|
-
} else if (type.startsWith("image/")) {
|
|
1344
|
-
const actual = await sniffImageType(data);
|
|
1345
|
-
if (actual === null || !isAccepted(actual, options)) continue;
|
|
1346
|
-
if (actual !== type) {
|
|
1347
|
-
data = retype(entry, data, actual);
|
|
1348
|
-
type = actual;
|
|
1349
|
-
}
|
|
1350
|
-
images.push(data);
|
|
1351
|
-
}
|
|
1352
|
-
if (entry.file) files.push(data);
|
|
1353
|
-
items.push({
|
|
1354
|
-
type,
|
|
1355
|
-
data
|
|
1356
|
-
});
|
|
1357
|
-
}
|
|
1358
|
-
if (items.length === 0) throw copyFailure("no-content", "The content holds nothing that matches `accept`.");
|
|
1359
|
-
return {
|
|
1360
|
-
source,
|
|
1361
|
-
items,
|
|
1362
|
-
text,
|
|
1363
|
-
html,
|
|
1364
|
-
images,
|
|
1365
|
-
files
|
|
1366
|
-
};
|
|
1367
|
-
}
|
|
1368
|
-
//#endregion
|
|
1369
|
-
//#region src/core/paste-adapter.ts
|
|
1370
|
-
function defaultEnvironment$1() {
|
|
1371
|
-
return typeof window === "undefined" ? void 0 : window;
|
|
1372
|
-
}
|
|
1373
|
-
const canRead = (clipboard) => typeof clipboard.read === "function";
|
|
1374
|
-
const canReadText = (clipboard) => typeof clipboard.readText === "function";
|
|
1375
|
-
async function readPlainText(clipboard, options) {
|
|
1376
|
-
let text;
|
|
1377
|
-
try {
|
|
1378
|
-
text = await clipboard.readText();
|
|
1379
|
-
} catch (cause) {
|
|
1380
|
-
throw new CopyFailure(toCopyError(cause, "read"));
|
|
1381
|
-
}
|
|
1382
|
-
const entries = text.length > 0 ? [{
|
|
1383
|
-
type: "text/plain",
|
|
1384
|
-
data: text,
|
|
1385
|
-
file: false
|
|
1386
|
-
}] : [];
|
|
1387
|
-
enforcePasteLimits(entries, options);
|
|
1388
|
-
return finalizePaste(entries, "clipboard", options);
|
|
1389
|
-
}
|
|
1390
|
-
async function readRich(clipboard, options, signal) {
|
|
1391
|
-
let items;
|
|
1392
|
-
try {
|
|
1393
|
-
items = await clipboard.read();
|
|
1394
|
-
} catch (cause) {
|
|
1395
|
-
throw new CopyFailure(toCopyError(cause, "read"));
|
|
1396
|
-
}
|
|
1397
|
-
return finalizePaste(await collectClipboardItems(items, options, signal), "clipboard", options);
|
|
1398
|
-
}
|
|
1399
|
-
function readFromClipboard(env, options, signal) {
|
|
1400
|
-
if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
|
|
1401
|
-
if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
|
|
1402
|
-
const clipboard = env.navigator?.clipboard;
|
|
1403
|
-
if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
|
|
1404
|
-
const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
|
|
1405
|
-
const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
|
|
1406
|
-
if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options, signal);
|
|
1407
|
-
if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
|
|
1408
|
-
throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
|
|
1409
|
-
}
|
|
1410
|
-
/** The default paste adapter: async Clipboard API with feature detection and honest errors. */
|
|
1411
|
-
function createBrowserPasteAdapter(options = {}) {
|
|
1412
|
-
const getEnvironment = options.getEnvironment ?? defaultEnvironment$1;
|
|
1413
|
-
return { read: (resolved, context) => {
|
|
1414
|
-
try {
|
|
1415
|
-
return readFromClipboard(getEnvironment(), resolved, context?.signal);
|
|
1416
|
-
} catch (cause) {
|
|
1417
|
-
return Promise.reject(cause);
|
|
1418
|
-
}
|
|
1419
|
-
} };
|
|
1420
|
-
}
|
|
1421
|
-
//#endregion
|
|
1422
|
-
//#region src/core/paste-machine.ts
|
|
1423
|
-
const PASTE_IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
|
|
1424
|
-
const PASTE_READING_STATE = /* @__PURE__ */ Object.freeze({ status: "reading" });
|
|
1425
|
-
const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
|
|
1426
|
-
status: "ignored",
|
|
1427
|
-
reason: "in-flight"
|
|
1428
|
-
});
|
|
1429
|
-
const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
|
|
1430
|
-
status: "ignored",
|
|
1431
|
-
reason: "no-accepted-content"
|
|
1432
|
-
});
|
|
1433
|
-
const IGNORED_NOTHING = /* @__PURE__ */ Object.freeze({
|
|
1434
|
-
status: "ignored",
|
|
1435
|
-
reason: "nothing-to-retry"
|
|
1436
|
-
});
|
|
1437
|
-
const IGNORED_NOT_RETRYABLE = /* @__PURE__ */ Object.freeze({
|
|
1438
|
-
status: "ignored",
|
|
1439
|
-
reason: "not-retryable"
|
|
1440
|
-
});
|
|
1441
|
-
const IGNORED_CANCELLED = /* @__PURE__ */ Object.freeze({
|
|
1442
|
-
status: "ignored",
|
|
1443
|
-
reason: "cancelled"
|
|
1444
|
-
});
|
|
1445
|
-
function resolveResetDelay(value) {
|
|
1446
|
-
if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
|
|
1447
|
-
return Math.max(0, value);
|
|
1448
|
-
}
|
|
1449
|
-
/** Pure helper: can `retry()` do anything from this state? */
|
|
1450
|
-
function canRetryPasteState(state, maxRetries) {
|
|
1451
|
-
return state.status === "error" && state.source === "clipboard" && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
|
|
1452
|
-
}
|
|
1453
|
-
let defaultAdapter;
|
|
1454
|
-
const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
|
|
1455
|
-
/** Framework-agnostic paste state machine. */
|
|
1456
|
-
function createPasteMachine(options = {}) {
|
|
1457
|
-
const read = typeof options === "function" ? options : () => options;
|
|
1458
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
1459
|
-
let state = PASTE_IDLE_STATE;
|
|
1460
|
-
let generation = 0;
|
|
1461
|
-
let resetTimer;
|
|
1462
|
-
const operations = createOperations();
|
|
1463
|
-
const now = () => (read().now ?? Date.now)();
|
|
1464
|
-
const setState = (next) => {
|
|
1465
|
-
if (next === state) return;
|
|
1466
|
-
state = next;
|
|
1467
|
-
for (const listener of Array.from(listeners)) listener();
|
|
1468
|
-
};
|
|
1469
|
-
const clearResetTimer = () => {
|
|
1470
|
-
if (resetTimer !== void 0) {
|
|
1471
|
-
clearTimeout(resetTimer);
|
|
1472
|
-
resetTimer = void 0;
|
|
1473
|
-
}
|
|
1474
|
-
};
|
|
1475
|
-
const scheduleReset = (readState) => {
|
|
1476
|
-
clearResetTimer();
|
|
1477
|
-
const delay = resolveResetDelay(read().resetAfterMs);
|
|
1478
|
-
if (delay === null) return;
|
|
1479
|
-
const remaining = Math.max(0, delay - (now() - readState.at));
|
|
1480
|
-
resetTimer = setTimeout(() => {
|
|
1481
|
-
resetTimer = void 0;
|
|
1482
|
-
setState(PASTE_IDLE_STATE);
|
|
1483
|
-
}, remaining);
|
|
1484
|
-
};
|
|
1485
|
-
const settleError = (error, source, retryCount) => {
|
|
1486
|
-
setState({
|
|
1487
|
-
status: "error",
|
|
1488
|
-
error,
|
|
1489
|
-
source,
|
|
1490
|
-
retryCount
|
|
1491
|
-
});
|
|
1492
|
-
invoke(read().onError, error);
|
|
1493
|
-
};
|
|
1494
|
-
/** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
|
|
1495
|
-
const run = (produce, source, retryCount) => {
|
|
1496
|
-
clearResetTimer();
|
|
1497
|
-
const current = ++generation;
|
|
1498
|
-
const superseded = operations.abort();
|
|
1499
|
-
const context = operations.start();
|
|
1500
|
-
setState(PASTE_READING_STATE);
|
|
1501
|
-
if (superseded) invoke(read().onCancel, "superseded");
|
|
1502
|
-
let pending;
|
|
1503
|
-
try {
|
|
1504
|
-
pending = produce(context);
|
|
1505
|
-
} catch (cause) {
|
|
1506
|
-
pending = Promise.reject(cause);
|
|
1507
|
-
}
|
|
1508
|
-
return pending.then(completePasteResult).then((result) => {
|
|
1509
|
-
operations.end(context);
|
|
1510
|
-
if (current === generation) {
|
|
1511
|
-
const readState = {
|
|
1512
|
-
status: "read",
|
|
1513
|
-
result,
|
|
1514
|
-
at: now()
|
|
1515
|
-
};
|
|
1516
|
-
setState(readState);
|
|
1517
|
-
scheduleReset(readState);
|
|
1518
|
-
invoke(read().onPaste, result);
|
|
1519
|
-
}
|
|
1520
|
-
return {
|
|
1521
|
-
status: "read",
|
|
1522
|
-
result
|
|
1523
|
-
};
|
|
1524
|
-
}, (cause) => {
|
|
1525
|
-
operations.end(context);
|
|
1526
|
-
if (context.signal.aborted) return IGNORED_CANCELLED;
|
|
1527
|
-
const error = toCopyError(cause, "read");
|
|
1528
|
-
settleError(error, source, retryCount);
|
|
1529
|
-
return {
|
|
1530
|
-
status: "error",
|
|
1531
|
-
error
|
|
1532
|
-
};
|
|
1533
|
-
});
|
|
1534
|
-
};
|
|
1535
|
-
const readClipboard = (retryCount) => run((context) => (read().adapter ?? getDefaultAdapter()).read(resolvePasteReadOptions(read()), context), "clipboard", retryCount);
|
|
1536
|
-
const paste = () => state.status === "reading" ? Promise.resolve(IGNORED_IN_FLIGHT) : readClipboard(0);
|
|
1537
|
-
const retry = () => {
|
|
1538
|
-
if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
|
|
1539
|
-
if (state.source !== "clipboard" || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
|
|
1540
|
-
if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
|
|
1541
|
-
const error = createCopyError("max-retries-exceeded", `Paste failed after ${String(state.retryCount)} retries.`, state.error);
|
|
1542
|
-
settleError(error, "clipboard", state.retryCount);
|
|
1543
|
-
return Promise.resolve({
|
|
1544
|
-
status: "error",
|
|
1545
|
-
error
|
|
1546
|
-
});
|
|
1547
|
-
}
|
|
1548
|
-
return readClipboard(state.retryCount + 1);
|
|
1549
|
-
};
|
|
1550
|
-
/** Shared by paste and drop events: their `DataTransfer` has the same shape and lifetime. */
|
|
1551
|
-
const transfer = (data, event, source) => {
|
|
1552
|
-
const current = read();
|
|
1553
|
-
if (source === "drop" && current.preventDefault !== false) event.preventDefault();
|
|
1554
|
-
if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
|
|
1555
|
-
let resolved;
|
|
1556
|
-
try {
|
|
1557
|
-
resolved = resolvePasteReadOptions(current);
|
|
1558
|
-
} catch (cause) {
|
|
1559
|
-
const error = toCopyError(cause, "read");
|
|
1560
|
-
++generation;
|
|
1561
|
-
const superseded = operations.abort();
|
|
1562
|
-
clearResetTimer();
|
|
1563
|
-
settleError(error, source, 0);
|
|
1564
|
-
if (superseded) invoke(current.onCancel, "superseded");
|
|
1565
|
-
return Promise.resolve({
|
|
1566
|
-
status: "error",
|
|
1567
|
-
error
|
|
1568
|
-
});
|
|
1569
|
-
}
|
|
1570
|
-
const entries = snapshotDataTransfer(data, resolved);
|
|
1571
|
-
if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);
|
|
1572
|
-
if (source === "event" && current.preventDefault !== false) event.preventDefault();
|
|
1573
|
-
return run(() => {
|
|
1574
|
-
enforcePasteLimits(entries, resolved);
|
|
1575
|
-
return finalizePaste(entries, source, resolved);
|
|
1576
|
-
}, source, 0);
|
|
1577
|
-
};
|
|
1578
|
-
const pasteEvent = (event) => transfer(event.clipboardData, event, "event");
|
|
1579
|
-
const dropEvent = (event) => transfer(event.dataTransfer, event, "drop");
|
|
1580
|
-
const reset = () => {
|
|
1581
|
-
++generation;
|
|
1582
|
-
const cancelled = operations.abort();
|
|
1583
|
-
clearResetTimer();
|
|
1584
|
-
const wasIdle = state.status === "idle";
|
|
1585
|
-
setState(PASTE_IDLE_STATE);
|
|
1586
|
-
if (cancelled) invoke(read().onCancel, "reset");
|
|
1587
|
-
if (!wasIdle) invoke(read().onReset);
|
|
1588
|
-
};
|
|
1589
|
-
const connect = () => {
|
|
1590
|
-
if (state.status === "read") scheduleReset(state);
|
|
1591
|
-
return () => {
|
|
1592
|
-
++generation;
|
|
1593
|
-
const cancelled = operations.abort();
|
|
1594
|
-
clearResetTimer();
|
|
1595
|
-
if (state.status === "reading") setState(PASTE_IDLE_STATE);
|
|
1596
|
-
if (cancelled) invoke(read().onCancel, "disconnect");
|
|
1597
|
-
};
|
|
1598
|
-
};
|
|
1599
|
-
return {
|
|
1600
|
-
getSnapshot: () => state,
|
|
1601
|
-
subscribe: (listener) => {
|
|
1602
|
-
listeners.add(listener);
|
|
1603
|
-
return () => {
|
|
1604
|
-
listeners.delete(listener);
|
|
1605
|
-
};
|
|
1606
|
-
},
|
|
1607
|
-
paste,
|
|
1608
|
-
pasteEvent,
|
|
1609
|
-
dropEvent,
|
|
1610
|
-
retry,
|
|
1611
|
-
reset,
|
|
1612
|
-
connect
|
|
1613
|
-
};
|
|
1614
|
-
}
|
|
1615
|
-
//#endregion
|
|
1616
11
|
//#region src/react/CopyGroup.tsx
|
|
1617
12
|
const CopyGroupContext = /* @__PURE__ */ createContext(null);
|
|
1618
13
|
/**
|
|
@@ -2622,399 +1017,6 @@ function useDragCopy(options) {
|
|
|
2622
1017
|
};
|
|
2623
1018
|
}
|
|
2624
1019
|
//#endregion
|
|
2625
|
-
//#region src/link/url.ts
|
|
2626
|
-
/** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */
|
|
2627
|
-
const DEFAULT_LINK_PROTOCOLS = /* @__PURE__ */ Object.freeze([
|
|
2628
|
-
"https:",
|
|
2629
|
-
"http:",
|
|
2630
|
-
"mailto:",
|
|
2631
|
-
"tel:"
|
|
2632
|
-
]);
|
|
2633
|
-
/**
|
|
2634
|
-
* Query parameters that only track where a click came from: the defaults of
|
|
2635
|
-
* {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.
|
|
2636
|
-
*/
|
|
2637
|
-
const TRACKING_PARAMETERS = /* @__PURE__ */ Object.freeze([
|
|
2638
|
-
"utm_",
|
|
2639
|
-
"fbclid",
|
|
2640
|
-
"gclid",
|
|
2641
|
-
"gclsrc",
|
|
2642
|
-
"dclid",
|
|
2643
|
-
"gbraid",
|
|
2644
|
-
"wbraid",
|
|
2645
|
-
"msclkid",
|
|
2646
|
-
"yclid",
|
|
2647
|
-
"twclid",
|
|
2648
|
-
"ttclid",
|
|
2649
|
-
"li_fat_id",
|
|
2650
|
-
"igshid",
|
|
2651
|
-
"igsh",
|
|
2652
|
-
"mc_cid",
|
|
2653
|
-
"mc_eid",
|
|
2654
|
-
"_hsenc",
|
|
2655
|
-
"_hsmi",
|
|
2656
|
-
"mkt_tok",
|
|
2657
|
-
"oly_anon_id",
|
|
2658
|
-
"oly_enc_id",
|
|
2659
|
-
"vero_id",
|
|
2660
|
-
"wickedid",
|
|
2661
|
-
"_gl"
|
|
2662
|
-
]);
|
|
2663
|
-
const invalid$2 = (message) => copyFailure("invalid-payload", message);
|
|
2664
|
-
function baseUrl(base) {
|
|
2665
|
-
if (base !== void 0) {
|
|
2666
|
-
if (typeof base === "string" || base instanceof URL) return String(base);
|
|
2667
|
-
throw invalid$2("`base` must be a string or a URL.");
|
|
2668
|
-
}
|
|
2669
|
-
return typeof location === "undefined" ? void 0 : location.href;
|
|
2670
|
-
}
|
|
2671
|
-
function protocolSet(protocols) {
|
|
2672
|
-
const list = protocols ?? DEFAULT_LINK_PROTOCOLS;
|
|
2673
|
-
const valid = (protocol) => typeof protocol === "string" && /^[a-z][a-z\d+.-]*:$/i.test(protocol);
|
|
2674
|
-
if (!Array.isArray(list) || list.length === 0 || !list.every(valid)) throw invalid$2("`protocols` must be a non-empty list of schemes with their colon, like \"https:\".");
|
|
2675
|
-
return new Set(list.map((protocol) => protocol.toLowerCase()));
|
|
2676
|
-
}
|
|
2677
|
-
function matcher(params) {
|
|
2678
|
-
const list = params ?? TRACKING_PARAMETERS;
|
|
2679
|
-
if (!Array.isArray(list) || !list.every((param) => typeof param === "string" || param instanceof RegExp)) throw invalid$2("`clean.params` must be a list of strings and regular expressions.");
|
|
2680
|
-
return (name) => {
|
|
2681
|
-
const lower = name.toLowerCase();
|
|
2682
|
-
return list.some((param) => {
|
|
2683
|
-
if (typeof param !== "string") return new RegExp(param.source, param.flags.replace(/[gy]/g, "")).test(name);
|
|
2684
|
-
const wanted = param.toLowerCase();
|
|
2685
|
-
return wanted.endsWith("_") ? lower.startsWith(wanted) : lower === wanted;
|
|
2686
|
-
});
|
|
2687
|
-
};
|
|
2688
|
-
}
|
|
2689
|
-
/** The cleaning step `clean` asks for, or `null`. Throws for an invalid option. */
|
|
2690
|
-
function cleaner(option) {
|
|
2691
|
-
const cleaning = option ?? false;
|
|
2692
|
-
if (cleaning === false) return null;
|
|
2693
|
-
if (cleaning !== true && (typeof cleaning !== "object" || cleaning === null)) throw invalid$2("`clean` must be a boolean or an options object.");
|
|
2694
|
-
const settings = cleaning === true ? {} : cleaning;
|
|
2695
|
-
const tracking = matcher(settings.params);
|
|
2696
|
-
const keep = settings.keep ?? [];
|
|
2697
|
-
if (!Array.isArray(keep) || !keep.every((name) => typeof name === "string")) throw invalid$2("`clean.keep` must be a list of strings.");
|
|
2698
|
-
const kept = new Set(keep.map((name) => name.toLowerCase()));
|
|
2699
|
-
return (url) => {
|
|
2700
|
-
for (const name of [...new Set(url.searchParams.keys())]) if (tracking(name) && !kept.has(name.toLowerCase())) url.searchParams.delete(name);
|
|
2701
|
-
};
|
|
2702
|
-
}
|
|
2703
|
-
/**
|
|
2704
|
-
* Validates `options` once (throwing a typed `invalid-payload` error for invalid
|
|
2705
|
-
* ones) and returns a resolver that throws only for invalid links.
|
|
2706
|
-
* @internal
|
|
2707
|
-
*/
|
|
2708
|
-
function linkUrlResolver(options = {}) {
|
|
2709
|
-
const protocols = protocolSet(options.protocols);
|
|
2710
|
-
const base = baseUrl(options.base);
|
|
2711
|
-
const clean = cleaner(options.clean);
|
|
2712
|
-
return (input) => {
|
|
2713
|
-
if (typeof input !== "string" && !(input instanceof URL)) throw invalid$2("A link must be a string or a URL.");
|
|
2714
|
-
const raw = String(input).trim();
|
|
2715
|
-
if (raw === "") throw invalid$2("A link must not be empty.");
|
|
2716
|
-
let url;
|
|
2717
|
-
try {
|
|
2718
|
-
url = new URL(raw, base);
|
|
2719
|
-
} catch (cause) {
|
|
2720
|
-
throw copyFailure("invalid-payload", `Not a valid link: ${JSON.stringify(raw.slice(0, 200))}.`, cause);
|
|
2721
|
-
}
|
|
2722
|
-
if (!protocols.has(url.protocol)) throw invalid$2(`Links with the scheme "${url.protocol}" are not allowed (allowed: ${[...protocols].join(", ")}).`);
|
|
2723
|
-
url.username = "";
|
|
2724
|
-
url.password = "";
|
|
2725
|
-
clean?.(url);
|
|
2726
|
-
return url.href;
|
|
2727
|
-
};
|
|
2728
|
-
}
|
|
2729
|
-
/**
|
|
2730
|
-
* The link as an absolute, safe URL string, or a typed `invalid-payload` error:
|
|
2731
|
-
* relative links are resolved, the scheme must be allowed, user names and
|
|
2732
|
-
* passwords are always removed, and tracking parameters optionally.
|
|
2733
|
-
*/
|
|
2734
|
-
function resolveLinkUrl(input, options = {}) {
|
|
2735
|
-
return linkUrlResolver(options)(input);
|
|
2736
|
-
}
|
|
2737
|
-
const invalid$1 = (message) => copyFailure("invalid-payload", message);
|
|
2738
|
-
/**
|
|
2739
|
-
* Characters a title never keeps: controls, bidi overrides and isolates (which can
|
|
2740
|
-
* make a title read differently), and zero-width characters.
|
|
2741
|
-
*/
|
|
2742
|
-
const HIDDEN = /[\0-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u061C\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g;
|
|
2743
|
-
/** A title as one clean line: hidden characters removed, whitespace collapsed, length capped. */
|
|
2744
|
-
function cleanTitle(title, maxLength) {
|
|
2745
|
-
const clean = title.replace(HIDDEN, "").replace(/\s+/g, " ").trim();
|
|
2746
|
-
if (clean.length <= maxLength) return clean;
|
|
2747
|
-
return `${Array.from(clean).slice(0, maxLength - 1).join("").trimEnd()}\u2026`;
|
|
2748
|
-
}
|
|
2749
|
-
function maxTitle(value) {
|
|
2750
|
-
if (value === void 0) return 300;
|
|
2751
|
-
if (Number.isInteger(value) && value >= 1) return value;
|
|
2752
|
-
throw invalid$1(`\`maxTitleLength\` must be a positive integer (received ${String(value)}).`);
|
|
2753
|
-
}
|
|
2754
|
-
function isAnchor(source) {
|
|
2755
|
-
return typeof source === "object" && source !== null && source.nodeName === "A" && typeof source.href === "string";
|
|
2756
|
-
}
|
|
2757
|
-
/**
|
|
2758
|
-
* Validates a link and its title: see {@link resolveLinkUrl} for the URL rules.
|
|
2759
|
-
* An `<a>` element gives its `href` and its text (or `title` attribute).
|
|
2760
|
-
*/
|
|
2761
|
-
function resolveLink(source, options = {}) {
|
|
2762
|
-
let url;
|
|
2763
|
-
let title;
|
|
2764
|
-
if (typeof source === "string" || source instanceof URL) url = source;
|
|
2765
|
-
else if (isAnchor(source)) {
|
|
2766
|
-
url = source.getAttribute("href") ?? "";
|
|
2767
|
-
title = source.textContent.trim() !== "" ? source.textContent : source.getAttribute("title") ?? void 0;
|
|
2768
|
-
if (url !== "" && options.base === void 0) url = source.href;
|
|
2769
|
-
} else if (typeof source === "object" && source !== null && "url" in source) {
|
|
2770
|
-
url = source.url;
|
|
2771
|
-
title = source.title;
|
|
2772
|
-
} else throw invalid$1("A link must be a URL, a { url, title } object or an <a> element.");
|
|
2773
|
-
if (title !== void 0 && typeof title !== "string") throw invalid$1("A link title must be a string.");
|
|
2774
|
-
const href = resolveLinkUrl(url, options);
|
|
2775
|
-
const clean = title === void 0 ? "" : cleanTitle(title, maxTitle(options.maxTitleLength));
|
|
2776
|
-
return {
|
|
2777
|
-
url: href,
|
|
2778
|
-
title: clean === "" ? href : clean,
|
|
2779
|
-
titled: clean !== ""
|
|
2780
|
-
};
|
|
2781
|
-
}
|
|
2782
|
-
const escapeHtml = (text) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
2783
|
-
/** `[title](url)`, safe in every CommonMark renderer: brackets and backslashes escaped, parentheses and spaces encoded. */
|
|
2784
|
-
function markdownLink(link) {
|
|
2785
|
-
return `[${link.title.replace(/[\\[\]]/g, "\\$&")}](${link.url.replace(/[()<> ]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)})`;
|
|
2786
|
-
}
|
|
2787
|
-
function plainText(link, format) {
|
|
2788
|
-
switch (format) {
|
|
2789
|
-
case "url": return link.url;
|
|
2790
|
-
case "title": return link.title;
|
|
2791
|
-
case "title-and-url": return link.titled ? `${link.title}\n${link.url}` : link.url;
|
|
2792
|
-
case "markdown": return markdownLink(link);
|
|
2793
|
-
default: throw invalid$1(`\`text\` must be "url", "title", "title-and-url" or "markdown" (received ${JSON.stringify(format)}).`);
|
|
2794
|
-
}
|
|
2795
|
-
}
|
|
2796
|
-
function linkPayload(source, options = {}) {
|
|
2797
|
-
const target = options.target ?? "clipboard";
|
|
2798
|
-
if (target !== "drag" && target !== "clipboard") throw invalid$1("`target` must be \"clipboard\" or \"drag\".");
|
|
2799
|
-
const link = resolveLink(source, options);
|
|
2800
|
-
const text = plainText(link, options.text ?? "url");
|
|
2801
|
-
const html = `<a href="${escapeHtml(link.url)}">${escapeHtml(link.title)}</a>`;
|
|
2802
|
-
if (target === "clipboard") return {
|
|
2803
|
-
kind: "html",
|
|
2804
|
-
html,
|
|
2805
|
-
text
|
|
2806
|
-
};
|
|
2807
|
-
return {
|
|
2808
|
-
kind: "multi",
|
|
2809
|
-
items: [
|
|
2810
|
-
{
|
|
2811
|
-
mimeType: "text/plain",
|
|
2812
|
-
data: text
|
|
2813
|
-
},
|
|
2814
|
-
{
|
|
2815
|
-
mimeType: "text/html",
|
|
2816
|
-
data: html
|
|
2817
|
-
},
|
|
2818
|
-
{
|
|
2819
|
-
mimeType: "text/uri-list",
|
|
2820
|
-
data: link.url,
|
|
2821
|
-
optional: true
|
|
2822
|
-
},
|
|
2823
|
-
{
|
|
2824
|
-
mimeType: "text/x-moz-url",
|
|
2825
|
-
data: `${link.url}\n${link.title}`,
|
|
2826
|
-
optional: true
|
|
2827
|
-
}
|
|
2828
|
-
]
|
|
2829
|
-
};
|
|
2830
|
-
}
|
|
2831
|
-
//#endregion
|
|
2832
|
-
//#region src/share/share.ts
|
|
2833
|
-
/** Phones and tablets: a touch screen is the main input and nothing hovers. */
|
|
2834
|
-
const TOUCH_FIRST = "(hover: none) and (pointer: coarse)";
|
|
2835
|
-
const defaultEnvironment = () => typeof window === "undefined" ? void 0 : window;
|
|
2836
|
-
const invalid = (message) => createCopyError("invalid-payload", message);
|
|
2837
|
-
/** Validates and cleans what to share, or returns the typed error for invalid input. */
|
|
2838
|
-
function resolveContent(content, options) {
|
|
2839
|
-
const value = content;
|
|
2840
|
-
if (typeof value !== "object" || value === null) return invalid("Share content must be an object with a url, text or files.");
|
|
2841
|
-
const { url, title, text, files } = value;
|
|
2842
|
-
let href = null;
|
|
2843
|
-
if (url !== void 0 && url !== null) try {
|
|
2844
|
-
href = linkUrlResolver(options)(url);
|
|
2845
|
-
} catch (error) {
|
|
2846
|
-
return toCopyError(error);
|
|
2847
|
-
}
|
|
2848
|
-
if (title !== void 0 && typeof title !== "string") return invalid("`title` must be a string.");
|
|
2849
|
-
if (text !== void 0 && typeof text !== "string") return invalid("`text` must be a string.");
|
|
2850
|
-
const list = files ?? [];
|
|
2851
|
-
if (!Array.isArray(list) || !list.every((file) => typeof File !== "undefined" && file instanceof File)) return invalid("`files` must be a list of File objects.");
|
|
2852
|
-
const cleanName = title === void 0 ? "" : cleanTitle(title, 300);
|
|
2853
|
-
const message = text === void 0 || text.trim() === "" ? null : text;
|
|
2854
|
-
if (href === null && message === null && list.length === 0) return invalid("There is nothing to share: give a url, text or files.");
|
|
2855
|
-
return {
|
|
2856
|
-
url: href,
|
|
2857
|
-
title: cleanName === "" ? null : cleanName,
|
|
2858
|
-
text: message,
|
|
2859
|
-
files: list
|
|
2860
|
-
};
|
|
2861
|
-
}
|
|
2862
|
-
/** The `ShareData` the browser receives: only the fields that are set. */
|
|
2863
|
-
function shareData(content) {
|
|
2864
|
-
return {
|
|
2865
|
-
...content.url === null ? {} : { url: content.url },
|
|
2866
|
-
...content.title === null ? {} : { title: content.title },
|
|
2867
|
-
...content.text === null ? {} : { text: content.text },
|
|
2868
|
-
...content.files.length === 0 ? {} : { files: [...content.files] }
|
|
2869
|
-
};
|
|
2870
|
-
}
|
|
2871
|
-
/** Whether this browser can open its share sheet for `data`. */
|
|
2872
|
-
function canShareNatively(environment, data) {
|
|
2873
|
-
const nav = environment?.navigator;
|
|
2874
|
-
if (typeof nav?.share !== "function") return false;
|
|
2875
|
-
if (data === null) return true;
|
|
2876
|
-
return typeof nav.canShare === "function" ? nav.canShare(data) : data.files === void 0;
|
|
2877
|
-
}
|
|
2878
|
-
function isTouchFirst(environment) {
|
|
2879
|
-
return typeof environment?.matchMedia === "function" && environment.matchMedia("(hover: none) and (pointer: coarse)").matches;
|
|
2880
|
-
}
|
|
2881
|
-
function resolveMode(mode) {
|
|
2882
|
-
if (mode === void 0) return "auto";
|
|
2883
|
-
return mode === "auto" || mode === "native" || mode === "copy" ? mode : invalid("`mode` must be \"auto\", \"native\" or \"copy\".");
|
|
2884
|
-
}
|
|
2885
|
-
/**
|
|
2886
|
-
* How {@link shareOrCopy} would share right now: `"native"` (the share sheet) or
|
|
2887
|
-
* `"copy"`. Use it to label the button ("Share…" or "Copy link"). Pass the
|
|
2888
|
-
* content when it has files, since not every share sheet takes them.
|
|
2889
|
-
*/
|
|
2890
|
-
function shareMethod(options = {}, content) {
|
|
2891
|
-
const mode = resolveMode(options.mode);
|
|
2892
|
-
if (typeof mode !== "string" || mode === "copy") return "copy";
|
|
2893
|
-
const environment = options.environment ?? defaultEnvironment();
|
|
2894
|
-
if (mode === "auto" && !isTouchFirst(environment)) return "copy";
|
|
2895
|
-
const resolved = content === void 0 ? null : resolveContent(content, {});
|
|
2896
|
-
const data = resolved === null ? null : "type" in resolved ? void 0 : shareData(resolved);
|
|
2897
|
-
return data !== void 0 && canShareNatively(environment, data) ? "native" : "copy";
|
|
2898
|
-
}
|
|
2899
|
-
/** The default copy: a titled link when there is a URL, otherwise the text (one of them is always set here). */
|
|
2900
|
-
function defaultCopy(content) {
|
|
2901
|
-
if (content.url !== null) return linkPayload({
|
|
2902
|
-
url: content.url,
|
|
2903
|
-
...content.title === null ? {} : { title: content.title }
|
|
2904
|
-
});
|
|
2905
|
-
return content.text;
|
|
2906
|
-
}
|
|
2907
|
-
async function copyContent(content, reason, options) {
|
|
2908
|
-
if (options.copy === void 0 && content.url === null && content.text === null) return {
|
|
2909
|
-
status: "error",
|
|
2910
|
-
method: "copy",
|
|
2911
|
-
error: createCopyError("unsupported-format", "Files can only be shared through a share sheet, and this browser has none for them.")
|
|
2912
|
-
};
|
|
2913
|
-
let payload;
|
|
2914
|
-
try {
|
|
2915
|
-
payload = normalizePayload((options.copy ?? defaultCopy)(content));
|
|
2916
|
-
} catch (error) {
|
|
2917
|
-
return {
|
|
2918
|
-
status: "error",
|
|
2919
|
-
method: "copy",
|
|
2920
|
-
error: toCopyError(error)
|
|
2921
|
-
};
|
|
2922
|
-
}
|
|
2923
|
-
const problem = validatePayload(payload);
|
|
2924
|
-
if (problem !== null) return {
|
|
2925
|
-
status: "error",
|
|
2926
|
-
method: "copy",
|
|
2927
|
-
error: problem
|
|
2928
|
-
};
|
|
2929
|
-
if (options.signal?.aborted === true) return {
|
|
2930
|
-
status: "error",
|
|
2931
|
-
method: "copy",
|
|
2932
|
-
error: createCopyError("aborted", "The share was aborted.")
|
|
2933
|
-
};
|
|
2934
|
-
try {
|
|
2935
|
-
await (options.adapter ?? createBrowserClipboardAdapter()).write(payload, options.signal === void 0 ? void 0 : { signal: options.signal });
|
|
2936
|
-
} catch (error) {
|
|
2937
|
-
return {
|
|
2938
|
-
status: "error",
|
|
2939
|
-
method: "copy",
|
|
2940
|
-
error: toCopyError(error)
|
|
2941
|
-
};
|
|
2942
|
-
}
|
|
2943
|
-
return {
|
|
2944
|
-
status: "copied",
|
|
2945
|
-
method: "copy",
|
|
2946
|
-
reason,
|
|
2947
|
-
payload,
|
|
2948
|
-
content
|
|
2949
|
-
};
|
|
2950
|
-
}
|
|
2951
|
-
/**
|
|
2952
|
-
* Shares through the device's share sheet where people expect one, and copies a
|
|
2953
|
-
* titled link everywhere else. Call it directly in a click handler: the share
|
|
2954
|
-
* sheet needs the user's gesture.
|
|
2955
|
-
*
|
|
2956
|
-
* It never rejects. It resolves to `shared`, `copied` (with why), `cancelled`
|
|
2957
|
-
* (the user closed the share sheet: nothing to report) or `error` with a typed
|
|
2958
|
-
* {@link CopyError}.
|
|
2959
|
-
*
|
|
2960
|
-
* @example
|
|
2961
|
-
* button.addEventListener('click', async () => {
|
|
2962
|
-
* const outcome = await shareOrCopy({ url: location.href, title: document.title });
|
|
2963
|
-
* if (outcome.status === 'copied') toast('Link copied');
|
|
2964
|
-
* });
|
|
2965
|
-
*/
|
|
2966
|
-
async function shareOrCopy(content, options = {}) {
|
|
2967
|
-
const mode = resolveMode(options.mode);
|
|
2968
|
-
if (typeof mode !== "string") return {
|
|
2969
|
-
status: "error",
|
|
2970
|
-
method: "copy",
|
|
2971
|
-
error: mode
|
|
2972
|
-
};
|
|
2973
|
-
const resolved = resolveContent(content, options);
|
|
2974
|
-
if ("type" in resolved) return {
|
|
2975
|
-
status: "error",
|
|
2976
|
-
method: "copy",
|
|
2977
|
-
error: resolved
|
|
2978
|
-
};
|
|
2979
|
-
const environment = options.environment ?? defaultEnvironment();
|
|
2980
|
-
if (mode === "copy" || mode === "auto" && !isTouchFirst(environment)) return copyContent(resolved, "preferred", options);
|
|
2981
|
-
const data = shareData(resolved);
|
|
2982
|
-
if (!canShareNatively(environment, data)) return copyContent(resolved, "unsupported", options);
|
|
2983
|
-
try {
|
|
2984
|
-
await (environment?.navigator?.share)(data);
|
|
2985
|
-
return {
|
|
2986
|
-
status: "shared",
|
|
2987
|
-
method: "native",
|
|
2988
|
-
content: resolved
|
|
2989
|
-
};
|
|
2990
|
-
} catch (error) {
|
|
2991
|
-
if (readName(error) === "AbortError") return {
|
|
2992
|
-
status: "cancelled",
|
|
2993
|
-
method: "native"
|
|
2994
|
-
};
|
|
2995
|
-
if (options.fallback === false) return {
|
|
2996
|
-
status: "error",
|
|
2997
|
-
method: "native",
|
|
2998
|
-
error: shareError(error)
|
|
2999
|
-
};
|
|
3000
|
-
return copyContent(resolved, "fallback", options);
|
|
3001
|
-
}
|
|
3002
|
-
}
|
|
3003
|
-
function readName(error) {
|
|
3004
|
-
const name = typeof error === "object" && error !== null ? error.name : void 0;
|
|
3005
|
-
return typeof name === "string" ? name : void 0;
|
|
3006
|
-
}
|
|
3007
|
-
/** Classifies a share sheet failure. */
|
|
3008
|
-
function shareError(cause) {
|
|
3009
|
-
switch (readName(cause)) {
|
|
3010
|
-
case "NotAllowedError": return createCopyError("permission-denied", "The share sheet was blocked: it needs a click, and an iframe needs the web-share permission.", cause);
|
|
3011
|
-
case "InvalidStateError": return createCopyError("unknown", "Another share sheet is already open.", cause);
|
|
3012
|
-
case "DataError":
|
|
3013
|
-
case "TypeError": return createCopyError("unsupported-format", "The share sheet rejected this content.", cause);
|
|
3014
|
-
default: return toCopyError(cause);
|
|
3015
|
-
}
|
|
3016
|
-
}
|
|
3017
|
-
//#endregion
|
|
3018
1020
|
//#region src/react/useShare.ts
|
|
3019
1021
|
const IDLE = {
|
|
3020
1022
|
status: "idle",
|