react-smart-copy 1.1.1 → 1.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/dist/core.cjs CHANGED
@@ -264,20 +264,21 @@ function writeText(clipboard, text) {
264
264
  if (typeof clipboard.writeText !== "function") throw fail("unsupported", "navigator.clipboard.writeText() is not available.");
265
265
  return clipboard.writeText(text);
266
266
  }
267
- async function resolveImageBlob(source) {
267
+ async function resolveImageBlob(source, context) {
268
268
  let blob;
269
269
  try {
270
- blob = await (typeof source === "function" ? source() : source);
270
+ blob = await (typeof source === "function" ? source(context ?? { signal: new AbortController().signal }) : source);
271
271
  } catch (cause) {
272
+ if (context?.signal.aborted) throw fail("aborted", "The image copy was cancelled.", cause);
272
273
  throw fail("blob-generation-failed", "The image source threw or rejected while producing a Blob.", cause);
273
274
  }
274
275
  if (!isBlob(blob)) throw fail("blob-generation-failed", "The image source did not produce a Blob.");
275
276
  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}").`);
276
277
  return blob;
277
278
  }
278
- async function writeImage(rich, source) {
279
+ async function writeImage(rich, source, context) {
279
280
  if (!isTypeSupported(rich.Item, "image/png")) throw fail("unsupported-format", `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);
280
- const blob = resolveImageBlob(source);
281
+ const blob = resolveImageBlob(source, context);
281
282
  blob.catch(noop);
282
283
  try {
283
284
  await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);
@@ -286,7 +287,7 @@ async function writeImage(rich, source) {
286
287
  }
287
288
  await blob;
288
289
  }
289
- async function writeToClipboard(payload, env, degradeHtmlToText) {
290
+ async function writeToClipboard(payload, env, degradeHtmlToText, context) {
290
291
  if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
291
292
  if (env.isSecureContext === false) throw fail("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
292
293
  const clipboard = env.navigator?.clipboard;
@@ -308,7 +309,7 @@ async function writeToClipboard(payload, env, degradeHtmlToText) {
308
309
  case "image": {
309
310
  const rich = getRichClipboard(env, clipboard);
310
311
  if (!rich) throw fail("unsupported-format", "Image copy requires ClipboardItem and navigator.clipboard.write().");
311
- return writeImage(rich, payload.blob);
312
+ return writeImage(rich, payload.blob, context);
312
313
  }
313
314
  case "multi": {
314
315
  const rich = getRichClipboard(env, clipboard);
@@ -326,7 +327,7 @@ async function writeToClipboard(payload, env, degradeHtmlToText) {
326
327
  function createBrowserClipboardAdapter(options = {}) {
327
328
  const getEnvironment = options.getEnvironment ?? defaultEnvironment$1;
328
329
  const degradeHtmlToText = options.degradeHtmlToText ?? true;
329
- return { write: (payload) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText) };
330
+ return { write: (payload, context) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText, context) };
330
331
  }
331
332
  //#endregion
332
333
  //#region src/core/copy-coordinator.ts
@@ -345,27 +346,72 @@ function createCopyCoordinator() {
345
346
  };
346
347
  }
347
348
  //#endregion
349
+ //#region src/core/machine-shared.ts
350
+ /**
351
+ * Internals shared by the copy and paste state machines. Kept in one module so
352
+ * apps that use both don't ship two copies.
353
+ */
354
+ const DEFAULT_MAX_RETRIES = 3;
355
+ function resolveMaxRetries(value) {
356
+ if (value === Infinity) return Infinity;
357
+ if (value === void 0 || !Number.isFinite(value)) return 3;
358
+ return Math.max(0, Math.floor(value));
359
+ }
360
+ function reportCallbackError(error) {
361
+ const scope = globalThis;
362
+ if (typeof scope.reportError === "function") scope.reportError(error);
363
+ else setTimeout(() => {
364
+ throw error;
365
+ }, 0);
366
+ }
367
+ /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
368
+ function invoke(fn, ...args) {
369
+ if (!fn) return;
370
+ try {
371
+ fn(...args);
372
+ } catch (error) {
373
+ reportCallbackError(error);
374
+ }
375
+ }
376
+ /** One cancellable operation at a time. Signals only fire while their operation is unfinished. */
377
+ function createOperations() {
378
+ let controller;
379
+ const abort = () => {
380
+ controller?.abort();
381
+ controller = void 0;
382
+ };
383
+ return {
384
+ start: () => {
385
+ abort();
386
+ controller = new AbortController();
387
+ return { signal: controller.signal };
388
+ },
389
+ end: (context) => {
390
+ if (controller?.signal === context.signal) controller = void 0;
391
+ },
392
+ abort
393
+ };
394
+ }
395
+ //#endregion
348
396
  //#region src/core/copy-machine.ts
349
397
  const DEFAULT_RESET_AFTER_MS = 2e3;
350
- const DEFAULT_MAX_RETRIES = 3;
351
398
  const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
352
399
  const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
353
400
  status: "ignored",
354
401
  reason: "in-flight"
355
402
  });
356
- const IGNORED_NOTHING = /* @__PURE__ */ Object.freeze({
403
+ const IGNORED_NOTHING$1 = /* @__PURE__ */ Object.freeze({
357
404
  status: "ignored",
358
405
  reason: "nothing-to-retry"
359
406
  });
360
- const IGNORED_NOT_RETRYABLE = /* @__PURE__ */ Object.freeze({
407
+ const IGNORED_NOT_RETRYABLE$1 = /* @__PURE__ */ Object.freeze({
361
408
  status: "ignored",
362
409
  reason: "not-retryable"
363
410
  });
364
- function resolveMaxRetries(value) {
365
- if (value === Infinity) return Infinity;
366
- if (value === void 0 || !Number.isFinite(value)) return 3;
367
- return Math.max(0, Math.floor(value));
368
- }
411
+ const IGNORED_CANCELLED$1 = /* @__PURE__ */ Object.freeze({
412
+ status: "ignored",
413
+ reason: "cancelled"
414
+ });
369
415
  function resolveResetDelay$1(value) {
370
416
  if (value === false || value === Infinity) return null;
371
417
  if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
@@ -375,22 +421,6 @@ function resolveResetDelay$1(value) {
375
421
  function canRetryState(state, maxRetries) {
376
422
  return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
377
423
  }
378
- function reportCallbackError$1(error) {
379
- const scope = globalThis;
380
- if (typeof scope.reportError === "function") scope.reportError(error);
381
- else setTimeout(() => {
382
- throw error;
383
- }, 0);
384
- }
385
- /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
386
- function invoke$1(fn, ...args) {
387
- if (!fn) return;
388
- try {
389
- fn(...args);
390
- } catch (error) {
391
- reportCallbackError$1(error);
392
- }
393
- }
394
424
  let defaultAdapter$1;
395
425
  const getDefaultAdapter$1 = () => defaultAdapter$1 ?? (defaultAdapter$1 = createBrowserClipboardAdapter());
396
426
  /** Framework-agnostic copy state machine. */
@@ -400,6 +430,7 @@ function createCopyMachine(options = {}) {
400
430
  let state = IDLE_STATE;
401
431
  let generation = 0;
402
432
  let resetTimer;
433
+ const operations = createOperations();
403
434
  const now = () => (read().now ?? Date.now)();
404
435
  let joined = null;
405
436
  const member = { release: () => {
@@ -445,7 +476,7 @@ function createCopyMachine(options = {}) {
445
476
  error,
446
477
  retryCount
447
478
  });
448
- invoke$1(read().onError, error, payload);
479
+ invoke(read().onError, error, payload);
449
480
  };
450
481
  const run = (source, retryCount) => {
451
482
  clearResetTimer();
@@ -484,13 +515,15 @@ function createCopyMachine(options = {}) {
484
515
  payload,
485
516
  retryCount
486
517
  });
518
+ const context = operations.start();
487
519
  let pending;
488
520
  try {
489
- pending = (read().adapter ?? getDefaultAdapter$1()).write(payload);
521
+ pending = (read().adapter ?? getDefaultAdapter$1()).write(payload, context);
490
522
  } catch (cause) {
491
523
  pending = Promise.reject(cause);
492
524
  }
493
525
  return pending.then(() => {
526
+ operations.end(context);
494
527
  if (current === generation) {
495
528
  const copied = {
496
529
  status: "copied",
@@ -500,15 +533,17 @@ function createCopyMachine(options = {}) {
500
533
  setState(copied);
501
534
  joinCoordinator();
502
535
  scheduleReset(copied);
503
- invoke$1(read().onCopy, payload);
536
+ invoke(read().onCopy, payload);
504
537
  }
505
538
  return {
506
539
  status: "copied",
507
540
  payload
508
541
  };
509
542
  }, (cause) => {
543
+ operations.end(context);
544
+ if (context.signal.aborted) return IGNORED_CANCELLED$1;
510
545
  const error = toCopyError(cause);
511
- if (current === generation) settleError(error, payload, retryCount);
546
+ settleError(error, payload, retryCount);
512
547
  return {
513
548
  status: "error",
514
549
  error
@@ -517,8 +552,8 @@ function createCopyMachine(options = {}) {
517
552
  };
518
553
  const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
519
554
  const retry = () => {
520
- if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
521
- if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
555
+ if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING$1);
556
+ if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE$1);
522
557
  if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
523
558
  const error = createCopyError("max-retries-exceeded", `Copy failed after ${String(state.retryCount)} retries.`, state.error);
524
559
  settleError(error, state.payload, state.retryCount);
@@ -531,6 +566,7 @@ function createCopyMachine(options = {}) {
531
566
  };
532
567
  const reset = () => {
533
568
  ++generation;
569
+ operations.abort();
534
570
  clearResetTimer();
535
571
  setState(IDLE_STATE);
536
572
  };
@@ -538,6 +574,7 @@ function createCopyMachine(options = {}) {
538
574
  if (state.status === "copied") scheduleReset(state);
539
575
  return () => {
540
576
  ++generation;
577
+ operations.abort();
541
578
  clearResetTimer();
542
579
  if (state.status === "copying") setState(IDLE_STATE);
543
580
  };
@@ -651,7 +688,7 @@ function snapshotDataTransfer(data, options) {
651
688
  * Reads the accepted types from `navigator.clipboard.read()` items, enforcing
652
689
  * the limits *before* decoding any text so an oversized paste is never buffered twice.
653
690
  */
654
- async function collectClipboardItems(items, options) {
691
+ async function collectClipboardItems(items, options, signal) {
655
692
  const budget = createBudget(options);
656
693
  const entries = [];
657
694
  const seen = /* @__PURE__ */ new Set();
@@ -665,6 +702,7 @@ async function collectClipboardItems(items, options) {
665
702
  } catch {
666
703
  continue;
667
704
  }
705
+ if (signal?.aborted) throw copyFailure("aborted", "The paste was cancelled.");
668
706
  if (blob.size === 0) continue;
669
707
  budget.charge(blob.size);
670
708
  entries.push({
@@ -748,32 +786,32 @@ async function readPlainText(clipboard, options) {
748
786
  enforcePasteLimits(entries, options);
749
787
  return finalizePaste(entries, "clipboard", options);
750
788
  }
751
- async function readRich(clipboard, options) {
789
+ async function readRich(clipboard, options, signal) {
752
790
  let items;
753
791
  try {
754
792
  items = await clipboard.read();
755
793
  } catch (cause) {
756
794
  throw new CopyFailure(toCopyError(cause, "read"));
757
795
  }
758
- return finalizePaste(await collectClipboardItems(items, options), "clipboard", options);
796
+ return finalizePaste(await collectClipboardItems(items, options, signal), "clipboard", options);
759
797
  }
760
- function readFromClipboard(env, options) {
798
+ function readFromClipboard(env, options, signal) {
761
799
  if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
762
800
  if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
763
801
  const clipboard = env.navigator?.clipboard;
764
802
  if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
765
803
  const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
766
804
  const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
767
- if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options);
805
+ if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options, signal);
768
806
  if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
769
807
  throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
770
808
  }
771
809
  /** The default paste adapter: async Clipboard API with feature detection and honest errors. */
772
810
  function createBrowserPasteAdapter(options = {}) {
773
811
  const getEnvironment = options.getEnvironment ?? defaultEnvironment;
774
- return { read: (resolved) => {
812
+ return { read: (resolved, context) => {
775
813
  try {
776
- return readFromClipboard(getEnvironment(), resolved);
814
+ return readFromClipboard(getEnvironment(), resolved, context?.signal);
777
815
  } catch (cause) {
778
816
  return Promise.reject(cause);
779
817
  }
@@ -791,25 +829,25 @@ const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
791
829
  status: "ignored",
792
830
  reason: "no-accepted-content"
793
831
  });
832
+ const IGNORED_NOTHING = /* @__PURE__ */ Object.freeze({
833
+ status: "ignored",
834
+ reason: "nothing-to-retry"
835
+ });
836
+ const IGNORED_NOT_RETRYABLE = /* @__PURE__ */ Object.freeze({
837
+ status: "ignored",
838
+ reason: "not-retryable"
839
+ });
840
+ const IGNORED_CANCELLED = /* @__PURE__ */ Object.freeze({
841
+ status: "ignored",
842
+ reason: "cancelled"
843
+ });
794
844
  function resolveResetDelay(value) {
795
845
  if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
796
846
  return Math.max(0, value);
797
847
  }
798
- function reportCallbackError(error) {
799
- const scope = globalThis;
800
- if (typeof scope.reportError === "function") scope.reportError(error);
801
- else setTimeout(() => {
802
- throw error;
803
- }, 0);
804
- }
805
- /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
806
- function invoke(fn, ...args) {
807
- if (!fn) return;
808
- try {
809
- fn(...args);
810
- } catch (error) {
811
- reportCallbackError(error);
812
- }
848
+ /** Pure helper: can `retry()` do anything from this state? */
849
+ function canRetryPasteState(state, maxRetries) {
850
+ return state.status === "error" && state.source === "clipboard" && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
813
851
  }
814
852
  let defaultAdapter;
815
853
  const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
@@ -820,6 +858,7 @@ function createPasteMachine(options = {}) {
820
858
  let state = PASTE_IDLE_STATE;
821
859
  let generation = 0;
822
860
  let resetTimer;
861
+ const operations = createOperations();
823
862
  const now = () => (read().now ?? Date.now)();
824
863
  const setState = (next) => {
825
864
  if (next === state) return;
@@ -842,18 +881,29 @@ function createPasteMachine(options = {}) {
842
881
  setState(PASTE_IDLE_STATE);
843
882
  }, remaining);
844
883
  };
884
+ const settleError = (error, source, retryCount) => {
885
+ setState({
886
+ status: "error",
887
+ error,
888
+ source,
889
+ retryCount
890
+ });
891
+ invoke(read().onError, error);
892
+ };
845
893
  /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
846
- const run = (produce) => {
894
+ const run = (produce, source, retryCount) => {
847
895
  clearResetTimer();
848
896
  const current = ++generation;
897
+ const context = operations.start();
849
898
  setState(PASTE_READING_STATE);
850
899
  let pending;
851
900
  try {
852
- pending = produce();
901
+ pending = produce(context);
853
902
  } catch (cause) {
854
903
  pending = Promise.reject(cause);
855
904
  }
856
905
  return pending.then((result) => {
906
+ operations.end(context);
857
907
  if (current === generation) {
858
908
  const readState = {
859
909
  status: "read",
@@ -869,26 +919,30 @@ function createPasteMachine(options = {}) {
869
919
  result
870
920
  };
871
921
  }, (cause) => {
922
+ operations.end(context);
923
+ if (context.signal.aborted) return IGNORED_CANCELLED;
872
924
  const error = toCopyError(cause, "read");
873
- if (current === generation) {
874
- setState({
875
- status: "error",
876
- error
877
- });
878
- invoke(read().onError, error);
879
- }
925
+ settleError(error, source, retryCount);
880
926
  return {
881
927
  status: "error",
882
928
  error
883
929
  };
884
930
  });
885
931
  };
886
- const paste = () => {
887
- if (state.status === "reading") return Promise.resolve(IGNORED_IN_FLIGHT);
888
- return run(() => {
889
- const resolved = resolvePasteReadOptions(read());
890
- return (read().adapter ?? getDefaultAdapter()).read(resolved);
891
- });
932
+ const readClipboard = (retryCount) => run((context) => (read().adapter ?? getDefaultAdapter()).read(resolvePasteReadOptions(read()), context), "clipboard", retryCount);
933
+ const paste = () => state.status === "reading" ? Promise.resolve(IGNORED_IN_FLIGHT) : readClipboard(0);
934
+ const retry = () => {
935
+ if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
936
+ if (state.source !== "clipboard" || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
937
+ if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
938
+ const error = createCopyError("max-retries-exceeded", `Paste failed after ${String(state.retryCount)} retries.`, state.error);
939
+ settleError(error, "clipboard", state.retryCount);
940
+ return Promise.resolve({
941
+ status: "error",
942
+ error
943
+ });
944
+ }
945
+ return readClipboard(state.retryCount + 1);
892
946
  };
893
947
  const pasteEvent = (event) => {
894
948
  const data = event.clipboardData;
@@ -900,12 +954,9 @@ function createPasteMachine(options = {}) {
900
954
  } catch (cause) {
901
955
  const error = toCopyError(cause, "read");
902
956
  ++generation;
957
+ operations.abort();
903
958
  clearResetTimer();
904
- setState({
905
- status: "error",
906
- error
907
- });
908
- invoke(current.onError, error);
959
+ settleError(error, "event", 0);
909
960
  return Promise.resolve({
910
961
  status: "error",
911
962
  error
@@ -917,10 +968,11 @@ function createPasteMachine(options = {}) {
917
968
  return run(() => {
918
969
  enforcePasteLimits(entries, resolved);
919
970
  return finalizePaste(entries, "event", resolved);
920
- });
971
+ }, "event", 0);
921
972
  };
922
973
  const reset = () => {
923
974
  ++generation;
975
+ operations.abort();
924
976
  clearResetTimer();
925
977
  setState(PASTE_IDLE_STATE);
926
978
  };
@@ -928,6 +980,7 @@ function createPasteMachine(options = {}) {
928
980
  if (state.status === "read") scheduleReset(state);
929
981
  return () => {
930
982
  ++generation;
983
+ operations.abort();
931
984
  clearResetTimer();
932
985
  if (state.status === "reading") setState(PASTE_IDLE_STATE);
933
986
  };
@@ -942,6 +995,7 @@ function createPasteMachine(options = {}) {
942
995
  },
943
996
  paste,
944
997
  pasteEvent,
998
+ retry,
945
999
  reset,
946
1000
  connect
947
1001
  };
@@ -957,6 +1011,7 @@ exports.IDLE_STATE = IDLE_STATE;
957
1011
  exports.IMAGE_MIME_TYPE = IMAGE_MIME_TYPE;
958
1012
  exports.PASTE_IDLE_STATE = PASTE_IDLE_STATE;
959
1013
  exports.SVG_MIME_TYPE = SVG_MIME_TYPE;
1014
+ exports.canRetryPasteState = canRetryPasteState;
960
1015
  exports.canRetryState = canRetryState;
961
1016
  exports.copyFailure = copyFailure;
962
1017
  exports.createBrowserClipboardAdapter = createBrowserClipboardAdapter;