react-smart-copy 1.1.1 → 1.3.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 +80 -12
- package/dist/capture.cjs +36 -2
- package/dist/capture.cjs.map +1 -1
- package/dist/capture.d.cts +18 -4
- package/dist/capture.d.ts +18 -4
- package/dist/capture.js +36 -2
- package/dist/capture.js.map +1 -1
- package/dist/core.cjs +176 -82
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +108 -15
- package/dist/core.d.ts +108 -15
- package/dist/core.js +176 -83
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +267 -106
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +136 -17
- package/dist/index.d.ts +136 -17
- package/dist/index.js +268 -108
- package/dist/index.js.map +1 -1
- package/package.json +8 -8
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { createContext, forwardRef, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
3
|
-
import { jsx, jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
4
4
|
//#region src/core/errors.ts
|
|
5
5
|
function createCopyError(type, message, cause) {
|
|
6
6
|
return cause === void 0 ? {
|
|
@@ -266,20 +266,21 @@ function writeText(clipboard, text) {
|
|
|
266
266
|
if (typeof clipboard.writeText !== "function") throw fail("unsupported", "navigator.clipboard.writeText() is not available.");
|
|
267
267
|
return clipboard.writeText(text);
|
|
268
268
|
}
|
|
269
|
-
async function resolveImageBlob(source) {
|
|
269
|
+
async function resolveImageBlob(source, context) {
|
|
270
270
|
let blob;
|
|
271
271
|
try {
|
|
272
|
-
blob = await (typeof source === "function" ? source() : source);
|
|
272
|
+
blob = await (typeof source === "function" ? source(context ?? { signal: new AbortController().signal }) : source);
|
|
273
273
|
} catch (cause) {
|
|
274
|
+
if (context?.signal.aborted) throw fail("aborted", "The image copy was cancelled.", cause);
|
|
274
275
|
throw fail("blob-generation-failed", "The image source threw or rejected while producing a Blob.", cause);
|
|
275
276
|
}
|
|
276
277
|
if (!isBlob(blob)) throw fail("blob-generation-failed", "The image source did not produce a Blob.");
|
|
277
278
|
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}").`);
|
|
278
279
|
return blob;
|
|
279
280
|
}
|
|
280
|
-
async function writeImage(rich, source) {
|
|
281
|
+
async function writeImage(rich, source, context) {
|
|
281
282
|
if (!isTypeSupported(rich.Item, "image/png")) throw fail("unsupported-format", `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);
|
|
282
|
-
const blob = resolveImageBlob(source);
|
|
283
|
+
const blob = resolveImageBlob(source, context);
|
|
283
284
|
blob.catch(noop);
|
|
284
285
|
try {
|
|
285
286
|
await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);
|
|
@@ -288,7 +289,7 @@ async function writeImage(rich, source) {
|
|
|
288
289
|
}
|
|
289
290
|
await blob;
|
|
290
291
|
}
|
|
291
|
-
async function writeToClipboard(payload, env, degradeHtmlToText) {
|
|
292
|
+
async function writeToClipboard(payload, env, degradeHtmlToText, context) {
|
|
292
293
|
if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
|
|
293
294
|
if (env.isSecureContext === false) throw fail("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
|
|
294
295
|
const clipboard = env.navigator?.clipboard;
|
|
@@ -310,7 +311,7 @@ async function writeToClipboard(payload, env, degradeHtmlToText) {
|
|
|
310
311
|
case "image": {
|
|
311
312
|
const rich = getRichClipboard(env, clipboard);
|
|
312
313
|
if (!rich) throw fail("unsupported-format", "Image copy requires ClipboardItem and navigator.clipboard.write().");
|
|
313
|
-
return writeImage(rich, payload.blob);
|
|
314
|
+
return writeImage(rich, payload.blob, context);
|
|
314
315
|
}
|
|
315
316
|
case "multi": {
|
|
316
317
|
const rich = getRichClipboard(env, clipboard);
|
|
@@ -328,7 +329,7 @@ async function writeToClipboard(payload, env, degradeHtmlToText) {
|
|
|
328
329
|
function createBrowserClipboardAdapter(options = {}) {
|
|
329
330
|
const getEnvironment = options.getEnvironment ?? defaultEnvironment$1;
|
|
330
331
|
const degradeHtmlToText = options.degradeHtmlToText ?? true;
|
|
331
|
-
return { write: (payload) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText) };
|
|
332
|
+
return { write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context) };
|
|
332
333
|
}
|
|
333
334
|
//#endregion
|
|
334
335
|
//#region src/core/copy-coordinator.ts
|
|
@@ -347,27 +348,74 @@ function createCopyCoordinator() {
|
|
|
347
348
|
};
|
|
348
349
|
}
|
|
349
350
|
//#endregion
|
|
351
|
+
//#region src/core/machine-shared.ts
|
|
352
|
+
/**
|
|
353
|
+
* Internals shared by the copy and paste state machines. Kept in one module so
|
|
354
|
+
* apps that use both don't ship two copies.
|
|
355
|
+
*/
|
|
356
|
+
const DEFAULT_MAX_RETRIES = 3;
|
|
357
|
+
function resolveMaxRetries(value) {
|
|
358
|
+
if (value === Infinity) return Infinity;
|
|
359
|
+
if (value === void 0 || !Number.isFinite(value)) return 3;
|
|
360
|
+
return Math.max(0, Math.floor(value));
|
|
361
|
+
}
|
|
362
|
+
function reportCallbackError(error) {
|
|
363
|
+
const scope = globalThis;
|
|
364
|
+
if (typeof scope.reportError === "function") scope.reportError(error);
|
|
365
|
+
else setTimeout(() => {
|
|
366
|
+
throw error;
|
|
367
|
+
}, 0);
|
|
368
|
+
}
|
|
369
|
+
/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
|
|
370
|
+
function invoke(fn, ...args) {
|
|
371
|
+
if (!fn) return;
|
|
372
|
+
try {
|
|
373
|
+
fn(...args);
|
|
374
|
+
} catch (error) {
|
|
375
|
+
reportCallbackError(error);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
/** One cancellable operation at a time. Signals only fire while their operation is unfinished. */
|
|
379
|
+
function createOperations() {
|
|
380
|
+
let controller;
|
|
381
|
+
const abort = () => {
|
|
382
|
+
if (!controller) return false;
|
|
383
|
+
controller.abort();
|
|
384
|
+
controller = void 0;
|
|
385
|
+
return true;
|
|
386
|
+
};
|
|
387
|
+
return {
|
|
388
|
+
start: () => {
|
|
389
|
+
abort();
|
|
390
|
+
controller = new AbortController();
|
|
391
|
+
return { signal: controller.signal };
|
|
392
|
+
},
|
|
393
|
+
end: (context) => {
|
|
394
|
+
if (controller?.signal === context.signal) controller = void 0;
|
|
395
|
+
},
|
|
396
|
+
abort
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
//#endregion
|
|
350
400
|
//#region src/core/copy-machine.ts
|
|
351
401
|
const DEFAULT_RESET_AFTER_MS = 2e3;
|
|
352
|
-
const DEFAULT_MAX_RETRIES = 3;
|
|
353
402
|
const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
|
|
354
403
|
const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
|
|
355
404
|
status: "ignored",
|
|
356
405
|
reason: "in-flight"
|
|
357
406
|
});
|
|
358
|
-
const IGNORED_NOTHING = /* @__PURE__ */ Object.freeze({
|
|
407
|
+
const IGNORED_NOTHING$1 = /* @__PURE__ */ Object.freeze({
|
|
359
408
|
status: "ignored",
|
|
360
409
|
reason: "nothing-to-retry"
|
|
361
410
|
});
|
|
362
|
-
const IGNORED_NOT_RETRYABLE = /* @__PURE__ */ Object.freeze({
|
|
411
|
+
const IGNORED_NOT_RETRYABLE$1 = /* @__PURE__ */ Object.freeze({
|
|
363
412
|
status: "ignored",
|
|
364
413
|
reason: "not-retryable"
|
|
365
414
|
});
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
}
|
|
415
|
+
const IGNORED_CANCELLED$1 = /* @__PURE__ */ Object.freeze({
|
|
416
|
+
status: "ignored",
|
|
417
|
+
reason: "cancelled"
|
|
418
|
+
});
|
|
371
419
|
function resolveResetDelay$1(value) {
|
|
372
420
|
if (value === false || value === Infinity) return null;
|
|
373
421
|
if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
|
|
@@ -377,22 +425,6 @@ function resolveResetDelay$1(value) {
|
|
|
377
425
|
function canRetryState(state, maxRetries) {
|
|
378
426
|
return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
|
|
379
427
|
}
|
|
380
|
-
function reportCallbackError$1(error) {
|
|
381
|
-
const scope = globalThis;
|
|
382
|
-
if (typeof scope.reportError === "function") scope.reportError(error);
|
|
383
|
-
else setTimeout(() => {
|
|
384
|
-
throw error;
|
|
385
|
-
}, 0);
|
|
386
|
-
}
|
|
387
|
-
/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
|
|
388
|
-
function invoke$1(fn, ...args) {
|
|
389
|
-
if (!fn) return;
|
|
390
|
-
try {
|
|
391
|
-
fn(...args);
|
|
392
|
-
} catch (error) {
|
|
393
|
-
reportCallbackError$1(error);
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
428
|
let defaultAdapter$1;
|
|
397
429
|
const getDefaultAdapter$1 = () => defaultAdapter$1 ?? (defaultAdapter$1 = createBrowserClipboardAdapter());
|
|
398
430
|
/** Framework-agnostic copy state machine. */
|
|
@@ -402,6 +434,7 @@ function createCopyMachine(options = {}) {
|
|
|
402
434
|
let state = IDLE_STATE;
|
|
403
435
|
let generation = 0;
|
|
404
436
|
let resetTimer;
|
|
437
|
+
const operations = createOperations();
|
|
405
438
|
const now = () => (read().now ?? Date.now)();
|
|
406
439
|
let joined = null;
|
|
407
440
|
const member = { release: () => {
|
|
@@ -447,7 +480,7 @@ function createCopyMachine(options = {}) {
|
|
|
447
480
|
error,
|
|
448
481
|
retryCount
|
|
449
482
|
});
|
|
450
|
-
invoke
|
|
483
|
+
invoke(read().onError, error, payload);
|
|
451
484
|
};
|
|
452
485
|
const run = (source, retryCount) => {
|
|
453
486
|
clearResetTimer();
|
|
@@ -486,13 +519,15 @@ function createCopyMachine(options = {}) {
|
|
|
486
519
|
payload,
|
|
487
520
|
retryCount
|
|
488
521
|
});
|
|
522
|
+
const context = operations.start();
|
|
489
523
|
let pending;
|
|
490
524
|
try {
|
|
491
|
-
pending = (read().adapter ?? getDefaultAdapter$1()).write(payload);
|
|
525
|
+
pending = (read().adapter ?? getDefaultAdapter$1()).write(payload, context);
|
|
492
526
|
} catch (cause) {
|
|
493
527
|
pending = Promise.reject(cause);
|
|
494
528
|
}
|
|
495
529
|
return pending.then(() => {
|
|
530
|
+
operations.end(context);
|
|
496
531
|
if (current === generation) {
|
|
497
532
|
const copied = {
|
|
498
533
|
status: "copied",
|
|
@@ -502,15 +537,17 @@ function createCopyMachine(options = {}) {
|
|
|
502
537
|
setState(copied);
|
|
503
538
|
joinCoordinator();
|
|
504
539
|
scheduleReset(copied);
|
|
505
|
-
invoke
|
|
540
|
+
invoke(read().onCopy, payload);
|
|
506
541
|
}
|
|
507
542
|
return {
|
|
508
543
|
status: "copied",
|
|
509
544
|
payload
|
|
510
545
|
};
|
|
511
546
|
}, (cause) => {
|
|
547
|
+
operations.end(context);
|
|
548
|
+
if (context.signal.aborted) return IGNORED_CANCELLED$1;
|
|
512
549
|
const error = toCopyError(cause);
|
|
513
|
-
|
|
550
|
+
settleError(error, payload, retryCount);
|
|
514
551
|
return {
|
|
515
552
|
status: "error",
|
|
516
553
|
error
|
|
@@ -519,8 +556,8 @@ function createCopyMachine(options = {}) {
|
|
|
519
556
|
};
|
|
520
557
|
const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
|
|
521
558
|
const retry = () => {
|
|
522
|
-
if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
|
|
523
|
-
if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
|
|
559
|
+
if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING$1);
|
|
560
|
+
if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE$1);
|
|
524
561
|
if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
|
|
525
562
|
const error = createCopyError("max-retries-exceeded", `Copy failed after ${String(state.retryCount)} retries.`, state.error);
|
|
526
563
|
settleError(error, state.payload, state.retryCount);
|
|
@@ -533,15 +570,21 @@ function createCopyMachine(options = {}) {
|
|
|
533
570
|
};
|
|
534
571
|
const reset = () => {
|
|
535
572
|
++generation;
|
|
573
|
+
const cancelled = operations.abort();
|
|
536
574
|
clearResetTimer();
|
|
575
|
+
const wasIdle = state.status === "idle";
|
|
537
576
|
setState(IDLE_STATE);
|
|
577
|
+
if (cancelled) invoke(read().onCancel, "reset");
|
|
578
|
+
if (!wasIdle) invoke(read().onReset);
|
|
538
579
|
};
|
|
539
580
|
const connect = () => {
|
|
540
581
|
if (state.status === "copied") scheduleReset(state);
|
|
541
582
|
return () => {
|
|
542
583
|
++generation;
|
|
584
|
+
const cancelled = operations.abort();
|
|
543
585
|
clearResetTimer();
|
|
544
586
|
if (state.status === "copying") setState(IDLE_STATE);
|
|
587
|
+
if (cancelled) invoke(read().onCancel, "disconnect");
|
|
545
588
|
};
|
|
546
589
|
};
|
|
547
590
|
return {
|
|
@@ -560,6 +603,14 @@ function createCopyMachine(options = {}) {
|
|
|
560
603
|
}
|
|
561
604
|
//#endregion
|
|
562
605
|
//#region src/core/paste-reader.ts
|
|
606
|
+
/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
|
|
607
|
+
function completePasteResult(result) {
|
|
608
|
+
const images = new Set(result.images);
|
|
609
|
+
return {
|
|
610
|
+
...result,
|
|
611
|
+
imageFiles: result.files.filter((file) => images.has(file))
|
|
612
|
+
};
|
|
613
|
+
}
|
|
563
614
|
const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
|
|
564
615
|
const DEFAULT_PASTE_MAX_BYTES = 33554432;
|
|
565
616
|
const DEFAULT_PASTE_MAX_ITEMS = 32;
|
|
@@ -615,7 +666,25 @@ function createBudget(options) {
|
|
|
615
666
|
if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
|
|
616
667
|
} };
|
|
617
668
|
}
|
|
618
|
-
|
|
669
|
+
/**
|
|
670
|
+
* UTF-8 byte length of a string, without allocating an encoded copy.
|
|
671
|
+
* Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.
|
|
672
|
+
*/
|
|
673
|
+
function utf8ByteLength(text) {
|
|
674
|
+
let bytes = 0;
|
|
675
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
676
|
+
const unit = text.charCodeAt(i);
|
|
677
|
+
if (unit < 128) bytes += 1;
|
|
678
|
+
else if (unit < 2048) bytes += 2;
|
|
679
|
+
else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length && (text.charCodeAt(i + 1) & 64512) === 56320) {
|
|
680
|
+
bytes += 4;
|
|
681
|
+
i += 1;
|
|
682
|
+
} else bytes += 3;
|
|
683
|
+
}
|
|
684
|
+
return bytes;
|
|
685
|
+
}
|
|
686
|
+
/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */
|
|
687
|
+
const sizeOf = (data) => typeof data === "string" ? utf8ByteLength(data) : data.size;
|
|
619
688
|
/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
|
|
620
689
|
function enforcePasteLimits(entries, options) {
|
|
621
690
|
const budget = createBudget(options);
|
|
@@ -653,7 +722,7 @@ function snapshotDataTransfer(data, options) {
|
|
|
653
722
|
* Reads the accepted types from `navigator.clipboard.read()` items, enforcing
|
|
654
723
|
* the limits *before* decoding any text so an oversized paste is never buffered twice.
|
|
655
724
|
*/
|
|
656
|
-
async function collectClipboardItems(items, options) {
|
|
725
|
+
async function collectClipboardItems(items, options, signal) {
|
|
657
726
|
const budget = createBudget(options);
|
|
658
727
|
const entries = [];
|
|
659
728
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -667,6 +736,7 @@ async function collectClipboardItems(items, options) {
|
|
|
667
736
|
} catch {
|
|
668
737
|
continue;
|
|
669
738
|
}
|
|
739
|
+
if (signal?.aborted) throw copyFailure("aborted", "The paste was cancelled.");
|
|
670
740
|
if (blob.size === 0) continue;
|
|
671
741
|
budget.charge(blob.size);
|
|
672
742
|
entries.push({
|
|
@@ -750,32 +820,32 @@ async function readPlainText(clipboard, options) {
|
|
|
750
820
|
enforcePasteLimits(entries, options);
|
|
751
821
|
return finalizePaste(entries, "clipboard", options);
|
|
752
822
|
}
|
|
753
|
-
async function readRich(clipboard, options) {
|
|
823
|
+
async function readRich(clipboard, options, signal) {
|
|
754
824
|
let items;
|
|
755
825
|
try {
|
|
756
826
|
items = await clipboard.read();
|
|
757
827
|
} catch (cause) {
|
|
758
828
|
throw new CopyFailure(toCopyError(cause, "read"));
|
|
759
829
|
}
|
|
760
|
-
return finalizePaste(await collectClipboardItems(items, options), "clipboard", options);
|
|
830
|
+
return finalizePaste(await collectClipboardItems(items, options, signal), "clipboard", options);
|
|
761
831
|
}
|
|
762
|
-
function readFromClipboard(env, options) {
|
|
832
|
+
function readFromClipboard(env, options, signal) {
|
|
763
833
|
if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
|
|
764
834
|
if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
|
|
765
835
|
const clipboard = env.navigator?.clipboard;
|
|
766
836
|
if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
|
|
767
837
|
const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
|
|
768
838
|
const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
|
|
769
|
-
if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options);
|
|
839
|
+
if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options, signal);
|
|
770
840
|
if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
|
|
771
841
|
throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
|
|
772
842
|
}
|
|
773
843
|
/** The default paste adapter: async Clipboard API with feature detection and honest errors. */
|
|
774
844
|
function createBrowserPasteAdapter(options = {}) {
|
|
775
845
|
const getEnvironment = options.getEnvironment ?? defaultEnvironment;
|
|
776
|
-
return { read: (resolved) => {
|
|
846
|
+
return { read: (resolved, context) => {
|
|
777
847
|
try {
|
|
778
|
-
return readFromClipboard(getEnvironment(), resolved);
|
|
848
|
+
return readFromClipboard(getEnvironment(), resolved, context?.signal);
|
|
779
849
|
} catch (cause) {
|
|
780
850
|
return Promise.reject(cause);
|
|
781
851
|
}
|
|
@@ -793,25 +863,25 @@ const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
|
|
|
793
863
|
status: "ignored",
|
|
794
864
|
reason: "no-accepted-content"
|
|
795
865
|
});
|
|
866
|
+
const IGNORED_NOTHING = /* @__PURE__ */ Object.freeze({
|
|
867
|
+
status: "ignored",
|
|
868
|
+
reason: "nothing-to-retry"
|
|
869
|
+
});
|
|
870
|
+
const IGNORED_NOT_RETRYABLE = /* @__PURE__ */ Object.freeze({
|
|
871
|
+
status: "ignored",
|
|
872
|
+
reason: "not-retryable"
|
|
873
|
+
});
|
|
874
|
+
const IGNORED_CANCELLED = /* @__PURE__ */ Object.freeze({
|
|
875
|
+
status: "ignored",
|
|
876
|
+
reason: "cancelled"
|
|
877
|
+
});
|
|
796
878
|
function resolveResetDelay(value) {
|
|
797
879
|
if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
|
|
798
880
|
return Math.max(0, value);
|
|
799
881
|
}
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
else setTimeout(() => {
|
|
804
|
-
throw error;
|
|
805
|
-
}, 0);
|
|
806
|
-
}
|
|
807
|
-
/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
|
|
808
|
-
function invoke(fn, ...args) {
|
|
809
|
-
if (!fn) return;
|
|
810
|
-
try {
|
|
811
|
-
fn(...args);
|
|
812
|
-
} catch (error) {
|
|
813
|
-
reportCallbackError(error);
|
|
814
|
-
}
|
|
882
|
+
/** Pure helper: can `retry()` do anything from this state? */
|
|
883
|
+
function canRetryPasteState(state, maxRetries) {
|
|
884
|
+
return state.status === "error" && state.source === "clipboard" && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
|
|
815
885
|
}
|
|
816
886
|
let defaultAdapter;
|
|
817
887
|
const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
|
|
@@ -822,6 +892,7 @@ function createPasteMachine(options = {}) {
|
|
|
822
892
|
let state = PASTE_IDLE_STATE;
|
|
823
893
|
let generation = 0;
|
|
824
894
|
let resetTimer;
|
|
895
|
+
const operations = createOperations();
|
|
825
896
|
const now = () => (read().now ?? Date.now)();
|
|
826
897
|
const setState = (next) => {
|
|
827
898
|
if (next === state) return;
|
|
@@ -844,18 +915,31 @@ function createPasteMachine(options = {}) {
|
|
|
844
915
|
setState(PASTE_IDLE_STATE);
|
|
845
916
|
}, remaining);
|
|
846
917
|
};
|
|
918
|
+
const settleError = (error, source, retryCount) => {
|
|
919
|
+
setState({
|
|
920
|
+
status: "error",
|
|
921
|
+
error,
|
|
922
|
+
source,
|
|
923
|
+
retryCount
|
|
924
|
+
});
|
|
925
|
+
invoke(read().onError, error);
|
|
926
|
+
};
|
|
847
927
|
/** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
|
|
848
|
-
const run = (produce) => {
|
|
928
|
+
const run = (produce, source, retryCount) => {
|
|
849
929
|
clearResetTimer();
|
|
850
930
|
const current = ++generation;
|
|
931
|
+
const superseded = operations.abort();
|
|
932
|
+
const context = operations.start();
|
|
851
933
|
setState(PASTE_READING_STATE);
|
|
934
|
+
if (superseded) invoke(read().onCancel, "superseded");
|
|
852
935
|
let pending;
|
|
853
936
|
try {
|
|
854
|
-
pending = produce();
|
|
937
|
+
pending = produce(context);
|
|
855
938
|
} catch (cause) {
|
|
856
939
|
pending = Promise.reject(cause);
|
|
857
940
|
}
|
|
858
|
-
return pending.then((result) => {
|
|
941
|
+
return pending.then(completePasteResult).then((result) => {
|
|
942
|
+
operations.end(context);
|
|
859
943
|
if (current === generation) {
|
|
860
944
|
const readState = {
|
|
861
945
|
status: "read",
|
|
@@ -871,26 +955,30 @@ function createPasteMachine(options = {}) {
|
|
|
871
955
|
result
|
|
872
956
|
};
|
|
873
957
|
}, (cause) => {
|
|
958
|
+
operations.end(context);
|
|
959
|
+
if (context.signal.aborted) return IGNORED_CANCELLED;
|
|
874
960
|
const error = toCopyError(cause, "read");
|
|
875
|
-
|
|
876
|
-
setState({
|
|
877
|
-
status: "error",
|
|
878
|
-
error
|
|
879
|
-
});
|
|
880
|
-
invoke(read().onError, error);
|
|
881
|
-
}
|
|
961
|
+
settleError(error, source, retryCount);
|
|
882
962
|
return {
|
|
883
963
|
status: "error",
|
|
884
964
|
error
|
|
885
965
|
};
|
|
886
966
|
});
|
|
887
967
|
};
|
|
888
|
-
const
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
968
|
+
const readClipboard = (retryCount) => run((context) => (read().adapter ?? getDefaultAdapter()).read(resolvePasteReadOptions(read()), context), "clipboard", retryCount);
|
|
969
|
+
const paste = () => state.status === "reading" ? Promise.resolve(IGNORED_IN_FLIGHT) : readClipboard(0);
|
|
970
|
+
const retry = () => {
|
|
971
|
+
if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
|
|
972
|
+
if (state.source !== "clipboard" || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
|
|
973
|
+
if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
|
|
974
|
+
const error = createCopyError("max-retries-exceeded", `Paste failed after ${String(state.retryCount)} retries.`, state.error);
|
|
975
|
+
settleError(error, "clipboard", state.retryCount);
|
|
976
|
+
return Promise.resolve({
|
|
977
|
+
status: "error",
|
|
978
|
+
error
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
return readClipboard(state.retryCount + 1);
|
|
894
982
|
};
|
|
895
983
|
const pasteEvent = (event) => {
|
|
896
984
|
const data = event.clipboardData;
|
|
@@ -902,12 +990,10 @@ function createPasteMachine(options = {}) {
|
|
|
902
990
|
} catch (cause) {
|
|
903
991
|
const error = toCopyError(cause, "read");
|
|
904
992
|
++generation;
|
|
993
|
+
const superseded = operations.abort();
|
|
905
994
|
clearResetTimer();
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
error
|
|
909
|
-
});
|
|
910
|
-
invoke(current.onError, error);
|
|
995
|
+
settleError(error, "event", 0);
|
|
996
|
+
if (superseded) invoke(current.onCancel, "superseded");
|
|
911
997
|
return Promise.resolve({
|
|
912
998
|
status: "error",
|
|
913
999
|
error
|
|
@@ -919,19 +1005,25 @@ function createPasteMachine(options = {}) {
|
|
|
919
1005
|
return run(() => {
|
|
920
1006
|
enforcePasteLimits(entries, resolved);
|
|
921
1007
|
return finalizePaste(entries, "event", resolved);
|
|
922
|
-
});
|
|
1008
|
+
}, "event", 0);
|
|
923
1009
|
};
|
|
924
1010
|
const reset = () => {
|
|
925
1011
|
++generation;
|
|
1012
|
+
const cancelled = operations.abort();
|
|
926
1013
|
clearResetTimer();
|
|
1014
|
+
const wasIdle = state.status === "idle";
|
|
927
1015
|
setState(PASTE_IDLE_STATE);
|
|
1016
|
+
if (cancelled) invoke(read().onCancel, "reset");
|
|
1017
|
+
if (!wasIdle) invoke(read().onReset);
|
|
928
1018
|
};
|
|
929
1019
|
const connect = () => {
|
|
930
1020
|
if (state.status === "read") scheduleReset(state);
|
|
931
1021
|
return () => {
|
|
932
1022
|
++generation;
|
|
1023
|
+
const cancelled = operations.abort();
|
|
933
1024
|
clearResetTimer();
|
|
934
1025
|
if (state.status === "reading") setState(PASTE_IDLE_STATE);
|
|
1026
|
+
if (cancelled) invoke(read().onCancel, "disconnect");
|
|
935
1027
|
};
|
|
936
1028
|
};
|
|
937
1029
|
return {
|
|
@@ -944,6 +1036,7 @@ function createPasteMachine(options = {}) {
|
|
|
944
1036
|
},
|
|
945
1037
|
paste,
|
|
946
1038
|
pasteEvent,
|
|
1039
|
+
retry,
|
|
947
1040
|
reset,
|
|
948
1041
|
connect
|
|
949
1042
|
};
|
|
@@ -1007,7 +1100,7 @@ function useCopy(options = {}) {
|
|
|
1007
1100
|
const [machine] = useState(() => createCopyMachine(() => optionsRef.current));
|
|
1008
1101
|
useEffect(() => machine.connect(), [machine]);
|
|
1009
1102
|
const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot$2);
|
|
1010
|
-
const canRetry = canRetryState(state,
|
|
1103
|
+
const canRetry = canRetryState(state, effective.maxRetries);
|
|
1011
1104
|
return useMemo(() => ({
|
|
1012
1105
|
state,
|
|
1013
1106
|
status: state.status,
|
|
@@ -1433,6 +1526,7 @@ function usePaste(options = {}) {
|
|
|
1433
1526
|
};
|
|
1434
1527
|
}, [listenOnDocument, machine]);
|
|
1435
1528
|
const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot);
|
|
1529
|
+
const canRetry = canRetryPasteState(state, options.maxRetries);
|
|
1436
1530
|
const targetProps = useMemo(() => ({ onPaste: (event) => {
|
|
1437
1531
|
machine.pasteEvent(event);
|
|
1438
1532
|
} }), [machine]);
|
|
@@ -1441,12 +1535,15 @@ function usePaste(options = {}) {
|
|
|
1441
1535
|
status: state.status,
|
|
1442
1536
|
result: state.status === "read" ? state.result : null,
|
|
1443
1537
|
error: state.status === "error" ? state.error : null,
|
|
1538
|
+
canRetry,
|
|
1444
1539
|
paste: machine.paste,
|
|
1445
1540
|
pasteEvent: machine.pasteEvent,
|
|
1541
|
+
retry: machine.retry,
|
|
1446
1542
|
reset: machine.reset,
|
|
1447
1543
|
targetProps
|
|
1448
1544
|
}), [
|
|
1449
1545
|
state,
|
|
1546
|
+
canRetry,
|
|
1450
1547
|
machine,
|
|
1451
1548
|
targetProps
|
|
1452
1549
|
]);
|
|
@@ -1635,6 +1732,56 @@ const DEFAULT_TRIGGER_TEXT = {
|
|
|
1635
1732
|
read: "Pasted",
|
|
1636
1733
|
error: "Retry"
|
|
1637
1734
|
};
|
|
1735
|
+
const Trigger = /* @__PURE__ */ forwardRef(function PasteFieldTrigger({ children, onClick, "aria-label": ariaLabel, ...rest }, ref) {
|
|
1736
|
+
const field = usePasteField();
|
|
1737
|
+
const renderProps = {
|
|
1738
|
+
status: field.status,
|
|
1739
|
+
displayStatus: field.displayStatus,
|
|
1740
|
+
state: field.state,
|
|
1741
|
+
revealed: field.revealed,
|
|
1742
|
+
canRetry: field.canRetry
|
|
1743
|
+
};
|
|
1744
|
+
const safeAriaLabel = (ariaLabel ?? field.messages.triggerLabel(field.label)) || defaultPasteFieldMessages.triggerLabel(field.label);
|
|
1745
|
+
return /* @__PURE__ */ jsx("button", {
|
|
1746
|
+
...rest,
|
|
1747
|
+
ref,
|
|
1748
|
+
type: "button",
|
|
1749
|
+
"aria-label": safeAriaLabel,
|
|
1750
|
+
"aria-busy": field.status === "reading" ? true : void 0,
|
|
1751
|
+
"data-state": field.status,
|
|
1752
|
+
"data-display-state": field.displayStatus,
|
|
1753
|
+
"data-revealed": field.revealed ? "" : void 0,
|
|
1754
|
+
onClick: composeEventHandlers(onClick, () => {
|
|
1755
|
+
field.doPaste();
|
|
1756
|
+
}),
|
|
1757
|
+
children: typeof children === "function" ? children(renderProps) : children ?? /* @__PURE__ */ jsx(TriggerLabel, {
|
|
1758
|
+
status: field.displayStatus,
|
|
1759
|
+
labels: DEFAULT_TRIGGER_TEXT
|
|
1760
|
+
})
|
|
1761
|
+
});
|
|
1762
|
+
});
|
|
1763
|
+
const NO_URLS = [];
|
|
1764
|
+
/**
|
|
1765
|
+
* Object URLs for blobs, revoked when the blobs change or the component
|
|
1766
|
+
* unmounts. URLs are only returned for the blobs they were made from, so they
|
|
1767
|
+
* never pair with the wrong result.
|
|
1768
|
+
*/
|
|
1769
|
+
function useObjectUrls(blobs) {
|
|
1770
|
+
const [entry, setEntry] = useState({ urls: NO_URLS });
|
|
1771
|
+
useEffect(() => {
|
|
1772
|
+
if (!blobs?.length || typeof URL.createObjectURL !== "function") return void 0;
|
|
1773
|
+
const urls = blobs.map((blob) => URL.createObjectURL(blob));
|
|
1774
|
+
setEntry({
|
|
1775
|
+
blobs,
|
|
1776
|
+
urls
|
|
1777
|
+
});
|
|
1778
|
+
return () => {
|
|
1779
|
+
for (const url of urls) URL.revokeObjectURL(url);
|
|
1780
|
+
};
|
|
1781
|
+
}, [blobs]);
|
|
1782
|
+
return entry.blobs === blobs ? entry.urls : NO_URLS;
|
|
1783
|
+
}
|
|
1784
|
+
const defaultImageAlt = (index, total) => `Pasted image ${String(index + 1)} of ${String(total)}`;
|
|
1638
1785
|
/**
|
|
1639
1786
|
* Headless compound component for a labelled, paste-ready field.
|
|
1640
1787
|
*
|
|
@@ -1649,6 +1796,7 @@ const DEFAULT_TRIGGER_TEXT = {
|
|
|
1649
1796
|
* <PasteField.Label />
|
|
1650
1797
|
* <PasteField.Zone />
|
|
1651
1798
|
* <PasteField.Trigger />
|
|
1799
|
+
* <PasteField.Preview placeholder="Nothing pasted yet" />
|
|
1652
1800
|
* </PasteField.Root>
|
|
1653
1801
|
* ```
|
|
1654
1802
|
*/
|
|
@@ -1657,35 +1805,47 @@ const PasteField = {
|
|
|
1657
1805
|
Label,
|
|
1658
1806
|
Status,
|
|
1659
1807
|
Zone,
|
|
1660
|
-
Trigger
|
|
1661
|
-
|
|
1662
|
-
const
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1808
|
+
Trigger,
|
|
1809
|
+
Preview: /* @__PURE__ */ forwardRef(function PasteFieldPreview({ children, placeholder = null, maxTextLength = 2e3, imageAlt = defaultImageAlt, ...rest }, ref) {
|
|
1810
|
+
const { result, status } = usePasteField();
|
|
1811
|
+
const imageUrls = useObjectUrls(result?.images);
|
|
1812
|
+
let content = placeholder;
|
|
1813
|
+
if (result) {
|
|
1814
|
+
if (children) content = children({
|
|
1815
|
+
result,
|
|
1816
|
+
imageUrls
|
|
1817
|
+
});
|
|
1818
|
+
else {
|
|
1819
|
+
const { text } = result;
|
|
1820
|
+
const files = result.files.filter((file) => !file.type.startsWith("image/"));
|
|
1821
|
+
content = /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
1822
|
+
text ? /* @__PURE__ */ jsx("pre", {
|
|
1823
|
+
"data-preview-text": "",
|
|
1824
|
+
children: text.length > maxTextLength ? `${text.slice(0, maxTextLength)}…` : text
|
|
1825
|
+
}) : null,
|
|
1826
|
+
imageUrls.map((url, index) => /* @__PURE__ */ jsx("img", {
|
|
1827
|
+
"data-preview-image": "",
|
|
1828
|
+
src: url,
|
|
1829
|
+
alt: imageAlt(index, imageUrls.length)
|
|
1830
|
+
}, url)),
|
|
1831
|
+
files.length > 0 ? /* @__PURE__ */ jsx("ul", {
|
|
1832
|
+
"data-preview-files": "",
|
|
1833
|
+
children: files.map((file, index) => /* @__PURE__ */ jsx("li", { children: file.name }, `${String(index)}-${file.name}`))
|
|
1834
|
+
}) : null
|
|
1835
|
+
] });
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
return /* @__PURE__ */ jsx("div", {
|
|
1670
1839
|
...rest,
|
|
1671
1840
|
ref,
|
|
1672
|
-
|
|
1673
|
-
"
|
|
1674
|
-
"
|
|
1675
|
-
|
|
1676
|
-
"data-display-state": field.displayStatus,
|
|
1677
|
-
"data-revealed": field.revealed ? "" : void 0,
|
|
1678
|
-
onClick: composeEventHandlers(onClick, () => {
|
|
1679
|
-
field.doPaste();
|
|
1680
|
-
}),
|
|
1681
|
-
children: typeof children === "function" ? children(renderProps) : children ?? /* @__PURE__ */ jsx(TriggerLabel, {
|
|
1682
|
-
status: field.displayStatus,
|
|
1683
|
-
labels: DEFAULT_TRIGGER_TEXT
|
|
1684
|
-
})
|
|
1841
|
+
"data-preview": "",
|
|
1842
|
+
"data-state": status,
|
|
1843
|
+
"data-empty": result ? void 0 : "",
|
|
1844
|
+
children: content
|
|
1685
1845
|
});
|
|
1686
1846
|
})
|
|
1687
1847
|
};
|
|
1688
1848
|
//#endregion
|
|
1689
|
-
export { CopyFailure, CopyField, CopyGroup, DEFAULT_MAX_RETRIES, DEFAULT_MIN_PENDING_MS, DEFAULT_PASTE_ACCEPT, DEFAULT_PASTE_MAX_BYTES, DEFAULT_PASTE_MAX_ITEMS, DEFAULT_PASTE_MIN_PENDING_MS, DEFAULT_PASTE_PENDING_DELAY_MS, DEFAULT_PENDING_DELAY_MS, DEFAULT_RESET_AFTER_MS, IDLE_STATE, IMAGE_MIME_TYPE, LiveRegion, PASTE_IDLE_STATE, PasteField, SVG_MIME_TYPE, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, defaultCopyFieldMessages, defaultPasteFieldMessages, describeCopyError, describePasteError, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, matchesMimePattern, normalizeMimeType, normalizePayload, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, useCopy, useCopyField, useCopyGroup, useDisplayStatus, usePaste, usePasteDisplayStatus, usePasteField, useRevealOnInteraction, validatePayload, visuallyHiddenStyle };
|
|
1849
|
+
export { CopyFailure, CopyField, CopyGroup, DEFAULT_MAX_RETRIES, DEFAULT_MIN_PENDING_MS, DEFAULT_PASTE_ACCEPT, DEFAULT_PASTE_MAX_BYTES, DEFAULT_PASTE_MAX_ITEMS, DEFAULT_PASTE_MIN_PENDING_MS, DEFAULT_PASTE_PENDING_DELAY_MS, DEFAULT_PENDING_DELAY_MS, DEFAULT_RESET_AFTER_MS, IDLE_STATE, IMAGE_MIME_TYPE, LiveRegion, PASTE_IDLE_STATE, PasteField, SVG_MIME_TYPE, canRetryPasteState, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, defaultCopyFieldMessages, defaultPasteFieldMessages, describeCopyError, describePasteError, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, matchesMimePattern, normalizeMimeType, normalizePayload, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, useCopy, useCopyField, useCopyGroup, useDisplayStatus, usePaste, usePasteDisplayStatus, usePasteField, useRevealOnInteraction, validatePayload, visuallyHiddenStyle };
|
|
1690
1850
|
|
|
1691
1851
|
//# sourceMappingURL=index.js.map
|