react-smart-copy 0.1.0 → 0.2.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 +136 -23
- package/dist/capture.cjs +498 -0
- package/dist/capture.cjs.map +1 -0
- package/dist/capture.d.cts +142 -0
- package/dist/capture.d.ts +142 -0
- package/dist/capture.js +485 -0
- package/dist/capture.js.map +1 -0
- package/dist/core.cjs +559 -22
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +257 -9
- package/dist/core.d.ts +257 -9
- package/dist/core.js +544 -23
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +645 -29
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +312 -11
- package/dist/index.d.ts +312 -11
- package/dist/index.js +627 -30
- package/dist/index.js.map +1 -1
- package/package.json +39 -10
package/dist/index.cjs
CHANGED
|
@@ -17,6 +17,7 @@ const RETRYABLE_ERRORS = /* @__PURE__ */ new Set([
|
|
|
17
17
|
"permission-denied",
|
|
18
18
|
"not-focused",
|
|
19
19
|
"blob-generation-failed",
|
|
20
|
+
"timeout",
|
|
20
21
|
"unknown"
|
|
21
22
|
]);
|
|
22
23
|
/** Whether retrying the same payload could plausibly succeed. */
|
|
@@ -40,25 +41,35 @@ var CopyFailure = class extends Error {
|
|
|
40
41
|
function isCopyFailure(value) {
|
|
41
42
|
return typeof value === "object" && value !== null && value[COPY_FAILURE_BRAND] === true;
|
|
42
43
|
}
|
|
44
|
+
/** Shorthand for throwing a classified failure. */
|
|
45
|
+
function copyFailure(type, message, cause) {
|
|
46
|
+
return new CopyFailure(createCopyError(type, message, cause));
|
|
47
|
+
}
|
|
43
48
|
function readString(value, key) {
|
|
44
49
|
if (typeof value !== "object" || value === null) return void 0;
|
|
45
50
|
const field = value[key];
|
|
46
51
|
return typeof field === "string" ? field : void 0;
|
|
47
52
|
}
|
|
48
|
-
/**
|
|
49
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Classifies anything thrown by the platform or an adapter into a {@link CopyError}.
|
|
55
|
+
* `operation` only tailors the developer-facing message.
|
|
56
|
+
*/
|
|
57
|
+
function toCopyError(cause, operation = "write") {
|
|
50
58
|
if (isCopyFailure(cause)) return cause.copyError;
|
|
51
59
|
const name = readString(cause, "name");
|
|
52
60
|
const message = readString(cause, "message") ?? "";
|
|
61
|
+
const verb = operation === "read" ? "read" : "write";
|
|
53
62
|
switch (name) {
|
|
54
|
-
case "NotAllowedError": return /focus/i.test(message) ? createCopyError("not-focused",
|
|
63
|
+
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);
|
|
55
64
|
case "SecurityError": return createCopyError("insecure-context", "The clipboard is blocked in this context.", cause);
|
|
56
65
|
case "NotSupportedError":
|
|
57
66
|
case "DataError": return createCopyError("unsupported-format", "The browser rejected this clipboard format.", cause);
|
|
58
|
-
|
|
67
|
+
case "AbortError": return createCopyError("aborted", `The clipboard ${verb} was aborted.`, cause);
|
|
68
|
+
case "TimeoutError": return createCopyError("timeout", `The clipboard ${verb} timed out.`, cause);
|
|
69
|
+
default: return createCopyError("unknown", message || `The clipboard ${verb} failed for an unknown reason.`, cause);
|
|
59
70
|
}
|
|
60
71
|
}
|
|
61
|
-
const
|
|
72
|
+
const COPY_DESCRIPTIONS = {
|
|
62
73
|
unsupported: "Copying isn't supported in this browser.",
|
|
63
74
|
"insecure-context": "Copying requires a secure (HTTPS) connection.",
|
|
64
75
|
"permission-denied": "Clipboard access was blocked. Allow it and try again.",
|
|
@@ -67,11 +78,34 @@ const DEFAULT_DESCRIPTIONS = {
|
|
|
67
78
|
"unsupported-format": "This content can't be copied in this browser.",
|
|
68
79
|
"blob-generation-failed": "The image couldn't be prepared for copying.",
|
|
69
80
|
"max-retries-exceeded": "Copying failed after several attempts.",
|
|
81
|
+
"no-content": "There is nothing to copy.",
|
|
82
|
+
"too-large": "This content is too large to copy.",
|
|
83
|
+
timeout: "Copying took too long. Try again.",
|
|
84
|
+
aborted: "Copying was cancelled.",
|
|
70
85
|
unknown: "Couldn't copy to the clipboard. Try again."
|
|
71
86
|
};
|
|
72
|
-
|
|
87
|
+
const PASTE_DESCRIPTIONS = {
|
|
88
|
+
unsupported: "Pasting isn't supported in this browser.",
|
|
89
|
+
"insecure-context": "Pasting requires a secure (HTTPS) connection.",
|
|
90
|
+
"permission-denied": "Clipboard access was blocked. Allow it and try again.",
|
|
91
|
+
"not-focused": "The page lost focus while pasting. Try again.",
|
|
92
|
+
"invalid-payload": "The clipboard content couldn't be read.",
|
|
93
|
+
"unsupported-format": "This clipboard content isn't supported here.",
|
|
94
|
+
"blob-generation-failed": "The pasted image couldn't be read.",
|
|
95
|
+
"max-retries-exceeded": "Pasting failed after several attempts.",
|
|
96
|
+
"no-content": "The clipboard doesn't contain anything that can be pasted here.",
|
|
97
|
+
"too-large": "The clipboard content is too large to paste.",
|
|
98
|
+
timeout: "Pasting took too long. Try again.",
|
|
99
|
+
aborted: "Pasting was cancelled.",
|
|
100
|
+
unknown: "Couldn't read the clipboard. Try again."
|
|
101
|
+
};
|
|
102
|
+
/** Default English, user-facing sentence for a copy error. Replace for i18n. */
|
|
73
103
|
function describeCopyError(error) {
|
|
74
|
-
return
|
|
104
|
+
return COPY_DESCRIPTIONS[error.type];
|
|
105
|
+
}
|
|
106
|
+
/** Default English, user-facing sentence for a paste error. Replace for i18n. */
|
|
107
|
+
function describePasteError(error) {
|
|
108
|
+
return PASTE_DESCRIPTIONS[error.type];
|
|
75
109
|
}
|
|
76
110
|
//#endregion
|
|
77
111
|
//#region src/core/payload.ts
|
|
@@ -140,10 +174,82 @@ function serializeJson(payload) {
|
|
|
140
174
|
return text;
|
|
141
175
|
}
|
|
142
176
|
//#endregion
|
|
177
|
+
//#region src/core/mime.ts
|
|
178
|
+
/**
|
|
179
|
+
* MIME helpers shared by paste and capture. Everything that comes from the
|
|
180
|
+
* clipboard is untrusted input, so types are normalised and validated before
|
|
181
|
+
* they are compared, and image types are confirmed from the bytes themselves.
|
|
182
|
+
*/
|
|
183
|
+
/** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */
|
|
184
|
+
const MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
|
|
185
|
+
/** SVG is XML that can carry scripts; it is never matched by a wildcard. */
|
|
186
|
+
const SVG_MIME_TYPE = "image/svg+xml";
|
|
187
|
+
/** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */
|
|
188
|
+
function normalizeMimeType(value) {
|
|
189
|
+
const separator = value.indexOf(";");
|
|
190
|
+
const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();
|
|
191
|
+
return MIME_SHAPE.test(base) ? base : null;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\/*`)?
|
|
195
|
+
* Wildcards never match `image/svg+xml`: accepting SVG must be explicit.
|
|
196
|
+
*/
|
|
197
|
+
function matchesMimePattern(mimeType, pattern) {
|
|
198
|
+
if (pattern === mimeType) return true;
|
|
199
|
+
if (mimeType === "image/svg+xml") return false;
|
|
200
|
+
if (pattern === "*/*") return true;
|
|
201
|
+
return pattern.endsWith("/*") && mimeType.startsWith(pattern.slice(0, -1));
|
|
202
|
+
}
|
|
203
|
+
/** Types whose clipboard data is text and is therefore surfaced as a `string`. */
|
|
204
|
+
function isTextualMimeType(mimeType) {
|
|
205
|
+
return mimeType.startsWith("text/") || mimeType === "image/svg+xml" || mimeType === "application/json" || mimeType === "application/xml";
|
|
206
|
+
}
|
|
207
|
+
const SNIFF_BYTES = 16;
|
|
208
|
+
function startsWith(bytes, signature, offset = 0) {
|
|
209
|
+
return signature.every((byte, index) => bytes[offset + index] === byte);
|
|
210
|
+
}
|
|
211
|
+
const ascii = (text) => Array.from(text, (char) => char.charCodeAt(0));
|
|
212
|
+
const PNG = [
|
|
213
|
+
137,
|
|
214
|
+
80,
|
|
215
|
+
78,
|
|
216
|
+
71,
|
|
217
|
+
13,
|
|
218
|
+
10,
|
|
219
|
+
26,
|
|
220
|
+
10
|
|
221
|
+
];
|
|
222
|
+
const JPEG = [
|
|
223
|
+
255,
|
|
224
|
+
216,
|
|
225
|
+
255
|
|
226
|
+
];
|
|
227
|
+
const GIF = ascii("GIF8");
|
|
228
|
+
const RIFF = ascii("RIFF");
|
|
229
|
+
const WEBP = ascii("WEBP");
|
|
230
|
+
const BMP = ascii("BM");
|
|
231
|
+
const FTYP_AVIF = ascii("ftypavif");
|
|
232
|
+
const FTYP_AVIS = ascii("ftypavis");
|
|
233
|
+
/** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */
|
|
234
|
+
function sniffImageBytes(bytes) {
|
|
235
|
+
if (startsWith(bytes, PNG)) return "image/png";
|
|
236
|
+
if (startsWith(bytes, JPEG)) return "image/jpeg";
|
|
237
|
+
if (startsWith(bytes, GIF)) return "image/gif";
|
|
238
|
+
if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return "image/webp";
|
|
239
|
+
if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return "image/avif";
|
|
240
|
+
if (startsWith(bytes, BMP)) return "image/bmp";
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
/** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */
|
|
244
|
+
async function sniffImageType(blob) {
|
|
245
|
+
const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();
|
|
246
|
+
return sniffImageBytes(new Uint8Array(head));
|
|
247
|
+
}
|
|
248
|
+
//#endregion
|
|
143
249
|
//#region src/core/clipboard-adapter.ts
|
|
144
250
|
const fail = (type, message, cause) => new CopyFailure(createCopyError(type, message, cause));
|
|
145
251
|
const noop = () => void 0;
|
|
146
|
-
function defaultEnvironment() {
|
|
252
|
+
function defaultEnvironment$1() {
|
|
147
253
|
return typeof window === "undefined" ? void 0 : window;
|
|
148
254
|
}
|
|
149
255
|
function getRichClipboard(env, clipboard) {
|
|
@@ -181,6 +287,7 @@ async function writeImage(rich, source) {
|
|
|
181
287
|
} catch (error) {
|
|
182
288
|
throw await blob.then(noop, (inner) => inner) ?? error;
|
|
183
289
|
}
|
|
290
|
+
await blob;
|
|
184
291
|
}
|
|
185
292
|
async function writeToClipboard(payload, env, degradeHtmlToText) {
|
|
186
293
|
if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
|
|
@@ -220,16 +327,32 @@ async function writeToClipboard(payload, env, degradeHtmlToText) {
|
|
|
220
327
|
}
|
|
221
328
|
/** The default adapter: async Clipboard API with feature detection and honest errors. */
|
|
222
329
|
function createBrowserClipboardAdapter(options = {}) {
|
|
223
|
-
const getEnvironment = options.getEnvironment ?? defaultEnvironment;
|
|
330
|
+
const getEnvironment = options.getEnvironment ?? defaultEnvironment$1;
|
|
224
331
|
const degradeHtmlToText = options.degradeHtmlToText ?? true;
|
|
225
332
|
return { write: (payload) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText) };
|
|
226
333
|
}
|
|
227
334
|
//#endregion
|
|
335
|
+
//#region src/core/copy-coordinator.ts
|
|
336
|
+
function createCopyCoordinator() {
|
|
337
|
+
let active = null;
|
|
338
|
+
return {
|
|
339
|
+
activate: (member) => {
|
|
340
|
+
const previous = active;
|
|
341
|
+
active = member;
|
|
342
|
+
if (previous !== null && previous !== member) previous.release();
|
|
343
|
+
},
|
|
344
|
+
deactivate: (member) => {
|
|
345
|
+
if (active === member) active = null;
|
|
346
|
+
},
|
|
347
|
+
getActive: () => active
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
//#endregion
|
|
228
351
|
//#region src/core/copy-machine.ts
|
|
229
352
|
const DEFAULT_RESET_AFTER_MS = 2e3;
|
|
230
353
|
const DEFAULT_MAX_RETRIES = 3;
|
|
231
354
|
const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
|
|
232
|
-
const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
|
|
355
|
+
const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
|
|
233
356
|
status: "ignored",
|
|
234
357
|
reason: "in-flight"
|
|
235
358
|
});
|
|
@@ -246,7 +369,7 @@ function resolveMaxRetries(value) {
|
|
|
246
369
|
if (value === void 0 || !Number.isFinite(value)) return 3;
|
|
247
370
|
return Math.max(0, Math.floor(value));
|
|
248
371
|
}
|
|
249
|
-
function resolveResetDelay(value) {
|
|
372
|
+
function resolveResetDelay$1(value) {
|
|
250
373
|
if (value === false || value === Infinity) return null;
|
|
251
374
|
if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
|
|
252
375
|
return Math.max(0, value);
|
|
@@ -255,7 +378,7 @@ function resolveResetDelay(value) {
|
|
|
255
378
|
function canRetryState(state, maxRetries) {
|
|
256
379
|
return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
|
|
257
380
|
}
|
|
258
|
-
function reportCallbackError(error) {
|
|
381
|
+
function reportCallbackError$1(error) {
|
|
259
382
|
const scope = globalThis;
|
|
260
383
|
if (typeof scope.reportError === "function") scope.reportError(error);
|
|
261
384
|
else setTimeout(() => {
|
|
@@ -263,16 +386,16 @@ function reportCallbackError(error) {
|
|
|
263
386
|
}, 0);
|
|
264
387
|
}
|
|
265
388
|
/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
|
|
266
|
-
function invoke(fn, ...args) {
|
|
389
|
+
function invoke$1(fn, ...args) {
|
|
267
390
|
if (!fn) return;
|
|
268
391
|
try {
|
|
269
392
|
fn(...args);
|
|
270
393
|
} catch (error) {
|
|
271
|
-
reportCallbackError(error);
|
|
394
|
+
reportCallbackError$1(error);
|
|
272
395
|
}
|
|
273
396
|
}
|
|
274
|
-
let defaultAdapter;
|
|
275
|
-
const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserClipboardAdapter());
|
|
397
|
+
let defaultAdapter$1;
|
|
398
|
+
const getDefaultAdapter$1 = () => defaultAdapter$1 ?? (defaultAdapter$1 = createBrowserClipboardAdapter());
|
|
276
399
|
/** Framework-agnostic copy state machine. */
|
|
277
400
|
function createCopyMachine(options = {}) {
|
|
278
401
|
const read = typeof options === "function" ? options : () => options;
|
|
@@ -281,11 +404,27 @@ function createCopyMachine(options = {}) {
|
|
|
281
404
|
let generation = 0;
|
|
282
405
|
let resetTimer;
|
|
283
406
|
const now = () => (read().now ?? Date.now)();
|
|
407
|
+
let joined = null;
|
|
408
|
+
const member = { release: () => {
|
|
409
|
+
if (state.status === "copied") {
|
|
410
|
+
clearResetTimer();
|
|
411
|
+
setState(IDLE_STATE);
|
|
412
|
+
}
|
|
413
|
+
} };
|
|
284
414
|
const setState = (next) => {
|
|
285
415
|
if (next === state) return;
|
|
416
|
+
const previous = state;
|
|
286
417
|
state = next;
|
|
418
|
+
if (previous.status === "copied" && next.status !== "copied" && joined) {
|
|
419
|
+
joined.deactivate(member);
|
|
420
|
+
joined = null;
|
|
421
|
+
}
|
|
287
422
|
for (const listener of Array.from(listeners)) listener();
|
|
288
423
|
};
|
|
424
|
+
const joinCoordinator = () => {
|
|
425
|
+
joined = read().coordinator ?? null;
|
|
426
|
+
joined?.activate(member);
|
|
427
|
+
};
|
|
289
428
|
const clearResetTimer = () => {
|
|
290
429
|
if (resetTimer !== void 0) {
|
|
291
430
|
clearTimeout(resetTimer);
|
|
@@ -294,12 +433,12 @@ function createCopyMachine(options = {}) {
|
|
|
294
433
|
};
|
|
295
434
|
const scheduleReset = (copied) => {
|
|
296
435
|
clearResetTimer();
|
|
297
|
-
const delay = resolveResetDelay(read().resetAfterMs);
|
|
436
|
+
const delay = resolveResetDelay$1(read().resetAfterMs);
|
|
298
437
|
if (delay === null) return;
|
|
299
438
|
const remaining = Math.max(0, delay - (now() - copied.at));
|
|
300
439
|
resetTimer = setTimeout(() => {
|
|
301
440
|
resetTimer = void 0;
|
|
302
|
-
|
|
441
|
+
setState(IDLE_STATE);
|
|
303
442
|
}, remaining);
|
|
304
443
|
};
|
|
305
444
|
const settleError = (error, payload, retryCount) => {
|
|
@@ -309,7 +448,7 @@ function createCopyMachine(options = {}) {
|
|
|
309
448
|
error,
|
|
310
449
|
retryCount
|
|
311
450
|
});
|
|
312
|
-
invoke(read().onError, error, payload);
|
|
451
|
+
invoke$1(read().onError, error, payload);
|
|
313
452
|
};
|
|
314
453
|
const run = (source, retryCount) => {
|
|
315
454
|
clearResetTimer();
|
|
@@ -340,7 +479,7 @@ function createCopyMachine(options = {}) {
|
|
|
340
479
|
});
|
|
341
480
|
let pending;
|
|
342
481
|
try {
|
|
343
|
-
pending = (read().adapter ?? getDefaultAdapter()).write(payload);
|
|
482
|
+
pending = (read().adapter ?? getDefaultAdapter$1()).write(payload);
|
|
344
483
|
} catch (cause) {
|
|
345
484
|
pending = Promise.reject(cause);
|
|
346
485
|
}
|
|
@@ -352,8 +491,9 @@ function createCopyMachine(options = {}) {
|
|
|
352
491
|
at: now()
|
|
353
492
|
};
|
|
354
493
|
setState(copied);
|
|
494
|
+
joinCoordinator();
|
|
355
495
|
scheduleReset(copied);
|
|
356
|
-
invoke(read().onCopy, payload);
|
|
496
|
+
invoke$1(read().onCopy, payload);
|
|
357
497
|
}
|
|
358
498
|
return {
|
|
359
499
|
status: "copied",
|
|
@@ -368,7 +508,7 @@ function createCopyMachine(options = {}) {
|
|
|
368
508
|
};
|
|
369
509
|
});
|
|
370
510
|
};
|
|
371
|
-
const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT) : run(source, 0);
|
|
511
|
+
const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
|
|
372
512
|
const retry = () => {
|
|
373
513
|
if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
|
|
374
514
|
if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
|
|
@@ -410,6 +550,406 @@ function createCopyMachine(options = {}) {
|
|
|
410
550
|
};
|
|
411
551
|
}
|
|
412
552
|
//#endregion
|
|
553
|
+
//#region src/core/paste-reader.ts
|
|
554
|
+
const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
|
|
555
|
+
const DEFAULT_PASTE_MAX_BYTES = 33554432;
|
|
556
|
+
const DEFAULT_PASTE_MAX_ITEMS = 32;
|
|
557
|
+
const SHORTHANDS = /* @__PURE__ */ new Map([
|
|
558
|
+
["text", "text/plain"],
|
|
559
|
+
["html", "text/html"],
|
|
560
|
+
["image", "image/*"],
|
|
561
|
+
["any", "*/*"]
|
|
562
|
+
]);
|
|
563
|
+
const TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
|
|
564
|
+
function resolvePattern(entry) {
|
|
565
|
+
if (typeof entry !== "string") return null;
|
|
566
|
+
const shorthand = SHORTHANDS.get(entry);
|
|
567
|
+
if (shorthand !== void 0) return shorthand;
|
|
568
|
+
if (entry === "*/*") return entry;
|
|
569
|
+
if (entry.endsWith("/*")) {
|
|
570
|
+
const type = entry.slice(0, -2).toLowerCase();
|
|
571
|
+
return TYPE_TOKEN.test(type) ? `${type}/*` : null;
|
|
572
|
+
}
|
|
573
|
+
return normalizeMimeType(entry);
|
|
574
|
+
}
|
|
575
|
+
function resolveLimit(value, fallback, name) {
|
|
576
|
+
if (value === void 0) return fallback;
|
|
577
|
+
if (value === Infinity || Number.isInteger(value) && value > 0) return value;
|
|
578
|
+
throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
|
|
579
|
+
}
|
|
580
|
+
/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
|
|
581
|
+
function resolvePasteReadOptions(options = {}) {
|
|
582
|
+
const accept = [];
|
|
583
|
+
for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {
|
|
584
|
+
const pattern = resolvePattern(entry);
|
|
585
|
+
if (pattern === null) throw copyFailure("invalid-payload", `Invalid \`accept\` entry: ${JSON.stringify(entry)}.`);
|
|
586
|
+
if (!accept.includes(pattern)) accept.push(pattern);
|
|
587
|
+
}
|
|
588
|
+
if (accept.length === 0) throw copyFailure("invalid-payload", "`accept` must list at least one type.");
|
|
589
|
+
return {
|
|
590
|
+
accept,
|
|
591
|
+
maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, "maxBytes"),
|
|
592
|
+
maxItems: resolveLimit(options.maxItems, 32, "maxItems")
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
/** Whether a normalised MIME type is allowed by the resolved `accept` list. */
|
|
596
|
+
function isAccepted(mimeType, options) {
|
|
597
|
+
return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));
|
|
598
|
+
}
|
|
599
|
+
function createBudget(options) {
|
|
600
|
+
let bytes = 0;
|
|
601
|
+
let items = 0;
|
|
602
|
+
return { charge: (size) => {
|
|
603
|
+
items += 1;
|
|
604
|
+
bytes += size;
|
|
605
|
+
if (items > options.maxItems) throw copyFailure("too-large", `The paste has more than ${String(options.maxItems)} accepted items.`);
|
|
606
|
+
if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
|
|
607
|
+
} };
|
|
608
|
+
}
|
|
609
|
+
const sizeOf = (data) => typeof data === "string" ? data.length : data.size;
|
|
610
|
+
/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
|
|
611
|
+
function enforcePasteLimits(entries, options) {
|
|
612
|
+
const budget = createBudget(options);
|
|
613
|
+
for (const entry of entries) budget.charge(sizeOf(entry.data));
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Synchronously copies the accepted parts of a paste event's `DataTransfer`.
|
|
617
|
+
* It must run during the event: browsers empty the object afterwards.
|
|
618
|
+
*/
|
|
619
|
+
function snapshotDataTransfer(data, options) {
|
|
620
|
+
const entries = [];
|
|
621
|
+
const seen = /* @__PURE__ */ new Set();
|
|
622
|
+
for (const raw of Array.from(data.types)) {
|
|
623
|
+
const type = normalizeMimeType(raw);
|
|
624
|
+
if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;
|
|
625
|
+
seen.add(type);
|
|
626
|
+
const text = data.getData(raw);
|
|
627
|
+
if (text.length > 0) entries.push({
|
|
628
|
+
type,
|
|
629
|
+
data: text,
|
|
630
|
+
file: false
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
for (const file of Array.from(data.files ?? [])) {
|
|
634
|
+
const type = normalizeMimeType(file.type) ?? "application/octet-stream";
|
|
635
|
+
if (isAccepted(type, options)) entries.push({
|
|
636
|
+
type,
|
|
637
|
+
data: file,
|
|
638
|
+
file: true
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
return entries;
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Reads the accepted types from `navigator.clipboard.read()` items, enforcing
|
|
645
|
+
* the limits *before* decoding any text so an oversized paste is never buffered twice.
|
|
646
|
+
*/
|
|
647
|
+
async function collectClipboardItems(items, options) {
|
|
648
|
+
const budget = createBudget(options);
|
|
649
|
+
const entries = [];
|
|
650
|
+
const seen = /* @__PURE__ */ new Set();
|
|
651
|
+
for (const item of items) for (const raw of item.types) {
|
|
652
|
+
const type = normalizeMimeType(raw);
|
|
653
|
+
if (type === null || seen.has(type) || !isAccepted(type, options)) continue;
|
|
654
|
+
seen.add(type);
|
|
655
|
+
let blob;
|
|
656
|
+
try {
|
|
657
|
+
blob = await item.getType(raw);
|
|
658
|
+
} catch {
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
if (blob.size === 0) continue;
|
|
662
|
+
budget.charge(blob.size);
|
|
663
|
+
entries.push({
|
|
664
|
+
type,
|
|
665
|
+
data: isTextualMimeType(type) ? await blob.text() : blob,
|
|
666
|
+
file: false
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
return entries;
|
|
670
|
+
}
|
|
671
|
+
function retype(entry, data, type) {
|
|
672
|
+
if (entry.file) {
|
|
673
|
+
const file = data;
|
|
674
|
+
return new File([file], file.name, {
|
|
675
|
+
type,
|
|
676
|
+
lastModified: file.lastModified
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
return data.slice(0, data.size, type);
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* Verifies image bytes, then builds the result. Blobs that claim to be images
|
|
683
|
+
* but aren't (or whose real format is not accepted) are dropped. Throws
|
|
684
|
+
* `no-content` when nothing survives.
|
|
685
|
+
*/
|
|
686
|
+
async function finalizePaste(entries, source, options) {
|
|
687
|
+
const items = [];
|
|
688
|
+
const images = [];
|
|
689
|
+
const files = [];
|
|
690
|
+
let text = null;
|
|
691
|
+
let html = null;
|
|
692
|
+
for (const entry of entries) {
|
|
693
|
+
let { type, data } = entry;
|
|
694
|
+
if (typeof data === "string") {
|
|
695
|
+
if (type === "text/plain") text = data;
|
|
696
|
+
else if (type === "text/html") html = data;
|
|
697
|
+
} else if (type.startsWith("image/")) {
|
|
698
|
+
const actual = await sniffImageType(data);
|
|
699
|
+
if (actual === null || !isAccepted(actual, options)) continue;
|
|
700
|
+
if (actual !== type) {
|
|
701
|
+
data = retype(entry, data, actual);
|
|
702
|
+
type = actual;
|
|
703
|
+
}
|
|
704
|
+
images.push(data);
|
|
705
|
+
}
|
|
706
|
+
if (entry.file) files.push(data);
|
|
707
|
+
items.push({
|
|
708
|
+
type,
|
|
709
|
+
data
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
if (items.length === 0) throw copyFailure("no-content", "The clipboard holds nothing that matches `accept`.");
|
|
713
|
+
return {
|
|
714
|
+
source,
|
|
715
|
+
items,
|
|
716
|
+
text,
|
|
717
|
+
html,
|
|
718
|
+
images,
|
|
719
|
+
files
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
//#endregion
|
|
723
|
+
//#region src/core/paste-adapter.ts
|
|
724
|
+
function defaultEnvironment() {
|
|
725
|
+
return typeof window === "undefined" ? void 0 : window;
|
|
726
|
+
}
|
|
727
|
+
const canRead = (clipboard) => typeof clipboard.read === "function";
|
|
728
|
+
const canReadText = (clipboard) => typeof clipboard.readText === "function";
|
|
729
|
+
async function readPlainText(clipboard, options) {
|
|
730
|
+
let text;
|
|
731
|
+
try {
|
|
732
|
+
text = await clipboard.readText();
|
|
733
|
+
} catch (cause) {
|
|
734
|
+
throw new CopyFailure(toCopyError(cause, "read"));
|
|
735
|
+
}
|
|
736
|
+
const entries = text.length > 0 ? [{
|
|
737
|
+
type: "text/plain",
|
|
738
|
+
data: text,
|
|
739
|
+
file: false
|
|
740
|
+
}] : [];
|
|
741
|
+
enforcePasteLimits(entries, options);
|
|
742
|
+
return finalizePaste(entries, "clipboard", options);
|
|
743
|
+
}
|
|
744
|
+
async function readRich(clipboard, options) {
|
|
745
|
+
let items;
|
|
746
|
+
try {
|
|
747
|
+
items = await clipboard.read();
|
|
748
|
+
} catch (cause) {
|
|
749
|
+
throw new CopyFailure(toCopyError(cause, "read"));
|
|
750
|
+
}
|
|
751
|
+
return finalizePaste(await collectClipboardItems(items, options), "clipboard", options);
|
|
752
|
+
}
|
|
753
|
+
function readFromClipboard(env, options) {
|
|
754
|
+
if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
|
|
755
|
+
if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
|
|
756
|
+
const clipboard = env.navigator?.clipboard;
|
|
757
|
+
if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
|
|
758
|
+
const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
|
|
759
|
+
const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
|
|
760
|
+
if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options);
|
|
761
|
+
if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
|
|
762
|
+
throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
|
|
763
|
+
}
|
|
764
|
+
/** The default paste adapter: async Clipboard API with feature detection and honest errors. */
|
|
765
|
+
function createBrowserPasteAdapter(options = {}) {
|
|
766
|
+
const getEnvironment = options.getEnvironment ?? defaultEnvironment;
|
|
767
|
+
return { read: (resolved) => {
|
|
768
|
+
try {
|
|
769
|
+
return readFromClipboard(getEnvironment(), resolved);
|
|
770
|
+
} catch (cause) {
|
|
771
|
+
return Promise.reject(cause);
|
|
772
|
+
}
|
|
773
|
+
} };
|
|
774
|
+
}
|
|
775
|
+
//#endregion
|
|
776
|
+
//#region src/core/paste-machine.ts
|
|
777
|
+
const PASTE_IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
|
|
778
|
+
const PASTE_READING_STATE = /* @__PURE__ */ Object.freeze({ status: "reading" });
|
|
779
|
+
const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
|
|
780
|
+
status: "ignored",
|
|
781
|
+
reason: "in-flight"
|
|
782
|
+
});
|
|
783
|
+
const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
|
|
784
|
+
status: "ignored",
|
|
785
|
+
reason: "no-accepted-content"
|
|
786
|
+
});
|
|
787
|
+
function resolveResetDelay(value) {
|
|
788
|
+
if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
|
|
789
|
+
return Math.max(0, value);
|
|
790
|
+
}
|
|
791
|
+
function reportCallbackError(error) {
|
|
792
|
+
const scope = globalThis;
|
|
793
|
+
if (typeof scope.reportError === "function") scope.reportError(error);
|
|
794
|
+
else setTimeout(() => {
|
|
795
|
+
throw error;
|
|
796
|
+
}, 0);
|
|
797
|
+
}
|
|
798
|
+
/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
|
|
799
|
+
function invoke(fn, ...args) {
|
|
800
|
+
if (!fn) return;
|
|
801
|
+
try {
|
|
802
|
+
fn(...args);
|
|
803
|
+
} catch (error) {
|
|
804
|
+
reportCallbackError(error);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
let defaultAdapter;
|
|
808
|
+
const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
|
|
809
|
+
/** Framework-agnostic paste state machine. */
|
|
810
|
+
function createPasteMachine(options = {}) {
|
|
811
|
+
const read = typeof options === "function" ? options : () => options;
|
|
812
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
813
|
+
let state = PASTE_IDLE_STATE;
|
|
814
|
+
let generation = 0;
|
|
815
|
+
let resetTimer;
|
|
816
|
+
const now = () => (read().now ?? Date.now)();
|
|
817
|
+
const setState = (next) => {
|
|
818
|
+
if (next === state) return;
|
|
819
|
+
state = next;
|
|
820
|
+
for (const listener of Array.from(listeners)) listener();
|
|
821
|
+
};
|
|
822
|
+
const clearResetTimer = () => {
|
|
823
|
+
if (resetTimer !== void 0) {
|
|
824
|
+
clearTimeout(resetTimer);
|
|
825
|
+
resetTimer = void 0;
|
|
826
|
+
}
|
|
827
|
+
};
|
|
828
|
+
const scheduleReset = (readState) => {
|
|
829
|
+
clearResetTimer();
|
|
830
|
+
const delay = resolveResetDelay(read().resetAfterMs);
|
|
831
|
+
if (delay === null) return;
|
|
832
|
+
const remaining = Math.max(0, delay - (now() - readState.at));
|
|
833
|
+
resetTimer = setTimeout(() => {
|
|
834
|
+
resetTimer = void 0;
|
|
835
|
+
setState(PASTE_IDLE_STATE);
|
|
836
|
+
}, remaining);
|
|
837
|
+
};
|
|
838
|
+
/** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
|
|
839
|
+
const run = (produce) => {
|
|
840
|
+
clearResetTimer();
|
|
841
|
+
const current = ++generation;
|
|
842
|
+
setState(PASTE_READING_STATE);
|
|
843
|
+
let pending;
|
|
844
|
+
try {
|
|
845
|
+
pending = produce();
|
|
846
|
+
} catch (cause) {
|
|
847
|
+
pending = Promise.reject(cause);
|
|
848
|
+
}
|
|
849
|
+
return pending.then((result) => {
|
|
850
|
+
if (current === generation) {
|
|
851
|
+
const readState = {
|
|
852
|
+
status: "read",
|
|
853
|
+
result,
|
|
854
|
+
at: now()
|
|
855
|
+
};
|
|
856
|
+
setState(readState);
|
|
857
|
+
scheduleReset(readState);
|
|
858
|
+
invoke(read().onPaste, result);
|
|
859
|
+
}
|
|
860
|
+
return {
|
|
861
|
+
status: "read",
|
|
862
|
+
result
|
|
863
|
+
};
|
|
864
|
+
}, (cause) => {
|
|
865
|
+
const error = toCopyError(cause, "read");
|
|
866
|
+
if (current === generation) {
|
|
867
|
+
setState({
|
|
868
|
+
status: "error",
|
|
869
|
+
error
|
|
870
|
+
});
|
|
871
|
+
invoke(read().onError, error);
|
|
872
|
+
}
|
|
873
|
+
return {
|
|
874
|
+
status: "error",
|
|
875
|
+
error
|
|
876
|
+
};
|
|
877
|
+
});
|
|
878
|
+
};
|
|
879
|
+
const paste = () => {
|
|
880
|
+
if (state.status === "reading") return Promise.resolve(IGNORED_IN_FLIGHT);
|
|
881
|
+
return run(() => {
|
|
882
|
+
const resolved = resolvePasteReadOptions(read());
|
|
883
|
+
return (read().adapter ?? getDefaultAdapter()).read(resolved);
|
|
884
|
+
});
|
|
885
|
+
};
|
|
886
|
+
const pasteEvent = (event) => {
|
|
887
|
+
const data = event.clipboardData;
|
|
888
|
+
if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
|
|
889
|
+
const current = read();
|
|
890
|
+
let resolved;
|
|
891
|
+
try {
|
|
892
|
+
resolved = resolvePasteReadOptions(current);
|
|
893
|
+
} catch (cause) {
|
|
894
|
+
return run(() => {
|
|
895
|
+
throw cause;
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
const entries = snapshotDataTransfer(data, resolved);
|
|
899
|
+
if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);
|
|
900
|
+
if (current.preventDefault !== false) event.preventDefault();
|
|
901
|
+
return run(() => {
|
|
902
|
+
enforcePasteLimits(entries, resolved);
|
|
903
|
+
return finalizePaste(entries, "event", resolved);
|
|
904
|
+
});
|
|
905
|
+
};
|
|
906
|
+
const reset = () => {
|
|
907
|
+
++generation;
|
|
908
|
+
clearResetTimer();
|
|
909
|
+
setState(PASTE_IDLE_STATE);
|
|
910
|
+
};
|
|
911
|
+
const connect = () => {
|
|
912
|
+
if (state.status === "read") scheduleReset(state);
|
|
913
|
+
return () => {
|
|
914
|
+
++generation;
|
|
915
|
+
clearResetTimer();
|
|
916
|
+
if (state.status === "reading") setState(PASTE_IDLE_STATE);
|
|
917
|
+
};
|
|
918
|
+
};
|
|
919
|
+
return {
|
|
920
|
+
getSnapshot: () => state,
|
|
921
|
+
subscribe: (listener) => {
|
|
922
|
+
listeners.add(listener);
|
|
923
|
+
return () => {
|
|
924
|
+
listeners.delete(listener);
|
|
925
|
+
};
|
|
926
|
+
},
|
|
927
|
+
paste,
|
|
928
|
+
pasteEvent,
|
|
929
|
+
reset,
|
|
930
|
+
connect
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
//#endregion
|
|
934
|
+
//#region src/react/CopyGroup.tsx
|
|
935
|
+
const CopyGroupContext = /* @__PURE__ */ (0, react.createContext)(null);
|
|
936
|
+
/**
|
|
937
|
+
* Every `useCopy` / `<CopyField.Root>` inside behaves like one clipboard:
|
|
938
|
+
* a new successful copy returns the previously "Copied" one to idle.
|
|
939
|
+
* Opt a single field out with `copyOptions={{ coordinator: null }}`. Groups nest; the nearest wins.
|
|
940
|
+
*/
|
|
941
|
+
function CopyGroup({ children, coordinator }) {
|
|
942
|
+
const [owned] = (0, react.useState)(createCopyCoordinator);
|
|
943
|
+
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopyGroupContext.Provider, {
|
|
944
|
+
value: coordinator ?? owned,
|
|
945
|
+
children
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
/** The nearest `<CopyGroup>`'s coordinator, or `null` outside any group. */
|
|
949
|
+
function useCopyGroup() {
|
|
950
|
+
return (0, react.useContext)(CopyGroupContext);
|
|
951
|
+
}
|
|
952
|
+
//#endregion
|
|
413
953
|
//#region src/react/utils.ts
|
|
414
954
|
/** `useLayoutEffect` in the browser, `useEffect` on the server (no SSR warning). */
|
|
415
955
|
const useIsomorphicLayoutEffect = typeof window === "undefined" ? react.useEffect : react.useLayoutEffect;
|
|
@@ -428,19 +968,27 @@ function composeEventHandlers(theirs, ours) {
|
|
|
428
968
|
}
|
|
429
969
|
//#endregion
|
|
430
970
|
//#region src/react/useCopy.ts
|
|
431
|
-
const getServerSnapshot$
|
|
971
|
+
const getServerSnapshot$2 = () => IDLE_STATE;
|
|
972
|
+
/** An explicit `coordinator` (including `null`) wins over the surrounding `<CopyGroup>`. */
|
|
973
|
+
function withGroup(options, group) {
|
|
974
|
+
return options.coordinator !== void 0 || group === null ? options : {
|
|
975
|
+
...options,
|
|
976
|
+
coordinator: group
|
|
977
|
+
};
|
|
978
|
+
}
|
|
432
979
|
/**
|
|
433
980
|
* Copy state machine bound to a component. Options may change on every render
|
|
434
981
|
* (inline callbacks are fine); the latest ones are always used.
|
|
435
982
|
*/
|
|
436
983
|
function useCopy(options = {}) {
|
|
437
|
-
const
|
|
984
|
+
const effective = withGroup(options, useCopyGroup());
|
|
985
|
+
const optionsRef = (0, react.useRef)(effective);
|
|
438
986
|
useIsomorphicLayoutEffect(() => {
|
|
439
|
-
optionsRef.current =
|
|
987
|
+
optionsRef.current = effective;
|
|
440
988
|
});
|
|
441
989
|
const [machine] = (0, react.useState)(() => createCopyMachine(() => optionsRef.current));
|
|
442
990
|
(0, react.useEffect)(() => machine.connect(), [machine]);
|
|
443
|
-
const state = (0, react.useSyncExternalStore)(machine.subscribe, machine.getSnapshot, getServerSnapshot$
|
|
991
|
+
const state = (0, react.useSyncExternalStore)(machine.subscribe, machine.getSnapshot, getServerSnapshot$2);
|
|
444
992
|
const canRetry = canRetryState(state, options.maxRetries);
|
|
445
993
|
return (0, react.useMemo)(() => ({
|
|
446
994
|
state,
|
|
@@ -458,7 +1006,7 @@ function useCopy(options = {}) {
|
|
|
458
1006
|
}
|
|
459
1007
|
//#endregion
|
|
460
1008
|
//#region src/react/useMediaQuery.ts
|
|
461
|
-
const getServerSnapshot = () => false;
|
|
1009
|
+
const getServerSnapshot$1 = () => false;
|
|
462
1010
|
function getMediaQueryList(query) {
|
|
463
1011
|
return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(query) : null;
|
|
464
1012
|
}
|
|
@@ -473,7 +1021,7 @@ function useMediaQuery(query) {
|
|
|
473
1021
|
};
|
|
474
1022
|
}, [query]);
|
|
475
1023
|
const getSnapshot = (0, react.useCallback)(() => getMediaQueryList(query)?.matches ?? false, [query]);
|
|
476
|
-
return (0, react.useSyncExternalStore)(subscribe, getSnapshot, getServerSnapshot);
|
|
1024
|
+
return (0, react.useSyncExternalStore)(subscribe, getSnapshot, getServerSnapshot$1);
|
|
477
1025
|
}
|
|
478
1026
|
//#endregion
|
|
479
1027
|
//#region src/react/useRevealOnInteraction.ts
|
|
@@ -558,7 +1106,9 @@ function useDisplayStatus(status, options = {}) {
|
|
|
558
1106
|
const pendingDelayMs = Math.max(0, options.pendingDelayMs ?? 150);
|
|
559
1107
|
const minPendingMs = Math.max(0, options.minPendingMs ?? 400);
|
|
560
1108
|
const [settled, setSettled] = (0, react.useState)(status === "copying" ? "idle" : status);
|
|
561
|
-
|
|
1109
|
+
useIsomorphicLayoutEffect(() => {
|
|
1110
|
+
if (status !== "copying") setSettled(status);
|
|
1111
|
+
}, [status]);
|
|
562
1112
|
const [pendingShownAt, setPendingShownAt] = (0, react.useState)(null);
|
|
563
1113
|
(0, react.useEffect)(() => {
|
|
564
1114
|
if (status !== "copying") return void 0;
|
|
@@ -789,31 +1339,97 @@ const CopyField = {
|
|
|
789
1339
|
})
|
|
790
1340
|
};
|
|
791
1341
|
//#endregion
|
|
1342
|
+
//#region src/react/usePaste.ts
|
|
1343
|
+
const getServerSnapshot = () => PASTE_IDLE_STATE;
|
|
1344
|
+
/**
|
|
1345
|
+
* Paste state machine bound to a component. Supports a "Paste" button
|
|
1346
|
+
* (`paste()`, may prompt for permission) and keyboard paste (`targetProps`
|
|
1347
|
+
* or `listenOnDocument`, no prompt). Options may change on every render.
|
|
1348
|
+
*
|
|
1349
|
+
* Everything in the result is untrusted user input.
|
|
1350
|
+
*/
|
|
1351
|
+
function usePaste(options = {}) {
|
|
1352
|
+
const optionsRef = (0, react.useRef)(options);
|
|
1353
|
+
useIsomorphicLayoutEffect(() => {
|
|
1354
|
+
optionsRef.current = options;
|
|
1355
|
+
});
|
|
1356
|
+
const [machine] = (0, react.useState)(() => createPasteMachine(() => optionsRef.current));
|
|
1357
|
+
(0, react.useEffect)(() => machine.connect(), [machine]);
|
|
1358
|
+
const listenOnDocument = options.listenOnDocument === true;
|
|
1359
|
+
(0, react.useEffect)(() => {
|
|
1360
|
+
if (!listenOnDocument) return void 0;
|
|
1361
|
+
const onPaste = (event) => {
|
|
1362
|
+
if (!event.defaultPrevented) machine.pasteEvent(event);
|
|
1363
|
+
};
|
|
1364
|
+
document.addEventListener("paste", onPaste);
|
|
1365
|
+
return () => {
|
|
1366
|
+
document.removeEventListener("paste", onPaste);
|
|
1367
|
+
};
|
|
1368
|
+
}, [listenOnDocument, machine]);
|
|
1369
|
+
const state = (0, react.useSyncExternalStore)(machine.subscribe, machine.getSnapshot, getServerSnapshot);
|
|
1370
|
+
const targetProps = (0, react.useMemo)(() => ({ onPaste: (event) => {
|
|
1371
|
+
machine.pasteEvent(event);
|
|
1372
|
+
} }), [machine]);
|
|
1373
|
+
return (0, react.useMemo)(() => ({
|
|
1374
|
+
state,
|
|
1375
|
+
status: state.status,
|
|
1376
|
+
result: state.status === "read" ? state.result : null,
|
|
1377
|
+
error: state.status === "error" ? state.error : null,
|
|
1378
|
+
paste: machine.paste,
|
|
1379
|
+
pasteEvent: machine.pasteEvent,
|
|
1380
|
+
reset: machine.reset,
|
|
1381
|
+
targetProps
|
|
1382
|
+
}), [
|
|
1383
|
+
state,
|
|
1384
|
+
machine,
|
|
1385
|
+
targetProps
|
|
1386
|
+
]);
|
|
1387
|
+
}
|
|
1388
|
+
//#endregion
|
|
792
1389
|
exports.CopyFailure = CopyFailure;
|
|
793
1390
|
exports.CopyField = CopyField;
|
|
1391
|
+
exports.CopyGroup = CopyGroup;
|
|
794
1392
|
exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES;
|
|
795
1393
|
exports.DEFAULT_MIN_PENDING_MS = DEFAULT_MIN_PENDING_MS;
|
|
1394
|
+
exports.DEFAULT_PASTE_ACCEPT = DEFAULT_PASTE_ACCEPT;
|
|
1395
|
+
exports.DEFAULT_PASTE_MAX_BYTES = DEFAULT_PASTE_MAX_BYTES;
|
|
1396
|
+
exports.DEFAULT_PASTE_MAX_ITEMS = DEFAULT_PASTE_MAX_ITEMS;
|
|
796
1397
|
exports.DEFAULT_PENDING_DELAY_MS = DEFAULT_PENDING_DELAY_MS;
|
|
797
1398
|
exports.DEFAULT_RESET_AFTER_MS = DEFAULT_RESET_AFTER_MS;
|
|
798
1399
|
exports.IDLE_STATE = IDLE_STATE;
|
|
799
1400
|
exports.IMAGE_MIME_TYPE = IMAGE_MIME_TYPE;
|
|
800
1401
|
exports.LiveRegion = LiveRegion;
|
|
1402
|
+
exports.PASTE_IDLE_STATE = PASTE_IDLE_STATE;
|
|
1403
|
+
exports.SVG_MIME_TYPE = SVG_MIME_TYPE;
|
|
801
1404
|
exports.canRetryState = canRetryState;
|
|
1405
|
+
exports.copyFailure = copyFailure;
|
|
802
1406
|
exports.createBrowserClipboardAdapter = createBrowserClipboardAdapter;
|
|
1407
|
+
exports.createBrowserPasteAdapter = createBrowserPasteAdapter;
|
|
1408
|
+
exports.createCopyCoordinator = createCopyCoordinator;
|
|
803
1409
|
exports.createCopyError = createCopyError;
|
|
804
1410
|
exports.createCopyMachine = createCopyMachine;
|
|
1411
|
+
exports.createPasteMachine = createPasteMachine;
|
|
805
1412
|
exports.defaultCopyFieldMessages = defaultCopyFieldMessages;
|
|
806
1413
|
exports.describeCopyError = describeCopyError;
|
|
1414
|
+
exports.describePasteError = describePasteError;
|
|
807
1415
|
exports.isBlob = isBlob;
|
|
808
1416
|
exports.isCopyFailure = isCopyFailure;
|
|
809
1417
|
exports.isRetryableError = isRetryableError;
|
|
1418
|
+
exports.isTextualMimeType = isTextualMimeType;
|
|
1419
|
+
exports.matchesMimePattern = matchesMimePattern;
|
|
1420
|
+
exports.normalizeMimeType = normalizeMimeType;
|
|
810
1421
|
exports.normalizePayload = normalizePayload;
|
|
811
1422
|
exports.resolveMaxRetries = resolveMaxRetries;
|
|
1423
|
+
exports.resolvePasteReadOptions = resolvePasteReadOptions;
|
|
812
1424
|
exports.serializeJson = serializeJson;
|
|
1425
|
+
exports.sniffImageBytes = sniffImageBytes;
|
|
1426
|
+
exports.sniffImageType = sniffImageType;
|
|
813
1427
|
exports.toCopyError = toCopyError;
|
|
814
1428
|
exports.useCopy = useCopy;
|
|
815
1429
|
exports.useCopyField = useCopyField;
|
|
1430
|
+
exports.useCopyGroup = useCopyGroup;
|
|
816
1431
|
exports.useDisplayStatus = useDisplayStatus;
|
|
1432
|
+
exports.usePaste = usePaste;
|
|
817
1433
|
exports.useRevealOnInteraction = useRevealOnInteraction;
|
|
818
1434
|
exports.validatePayload = validatePayload;
|
|
819
1435
|
exports.visuallyHiddenStyle = visuallyHiddenStyle;
|