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