react-smart-copy 1.1.0 → 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/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,72 @@ 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
+ controller?.abort();
383
+ controller = void 0;
384
+ };
385
+ return {
386
+ start: () => {
387
+ abort();
388
+ controller = new AbortController();
389
+ return { signal: controller.signal };
390
+ },
391
+ end: (context) => {
392
+ if (controller?.signal === context.signal) controller = void 0;
393
+ },
394
+ abort
395
+ };
396
+ }
397
+ //#endregion
350
398
  //#region src/core/copy-machine.ts
351
399
  const DEFAULT_RESET_AFTER_MS = 2e3;
352
- const DEFAULT_MAX_RETRIES = 3;
353
400
  const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
354
401
  const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
355
402
  status: "ignored",
356
403
  reason: "in-flight"
357
404
  });
358
- const IGNORED_NOTHING = /* @__PURE__ */ Object.freeze({
405
+ const IGNORED_NOTHING$1 = /* @__PURE__ */ Object.freeze({
359
406
  status: "ignored",
360
407
  reason: "nothing-to-retry"
361
408
  });
362
- const IGNORED_NOT_RETRYABLE = /* @__PURE__ */ Object.freeze({
409
+ const IGNORED_NOT_RETRYABLE$1 = /* @__PURE__ */ Object.freeze({
363
410
  status: "ignored",
364
411
  reason: "not-retryable"
365
412
  });
366
- function resolveMaxRetries(value) {
367
- if (value === Infinity) return Infinity;
368
- if (value === void 0 || !Number.isFinite(value)) return 3;
369
- return Math.max(0, Math.floor(value));
370
- }
413
+ const IGNORED_CANCELLED$1 = /* @__PURE__ */ Object.freeze({
414
+ status: "ignored",
415
+ reason: "cancelled"
416
+ });
371
417
  function resolveResetDelay$1(value) {
372
418
  if (value === false || value === Infinity) return null;
373
419
  if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
@@ -377,22 +423,6 @@ function resolveResetDelay$1(value) {
377
423
  function canRetryState(state, maxRetries) {
378
424
  return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
379
425
  }
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
426
  let defaultAdapter$1;
397
427
  const getDefaultAdapter$1 = () => defaultAdapter$1 ?? (defaultAdapter$1 = createBrowserClipboardAdapter());
398
428
  /** Framework-agnostic copy state machine. */
@@ -402,6 +432,7 @@ function createCopyMachine(options = {}) {
402
432
  let state = IDLE_STATE;
403
433
  let generation = 0;
404
434
  let resetTimer;
435
+ const operations = createOperations();
405
436
  const now = () => (read().now ?? Date.now)();
406
437
  let joined = null;
407
438
  const member = { release: () => {
@@ -447,7 +478,7 @@ function createCopyMachine(options = {}) {
447
478
  error,
448
479
  retryCount
449
480
  });
450
- invoke$1(read().onError, error, payload);
481
+ invoke(read().onError, error, payload);
451
482
  };
452
483
  const run = (source, retryCount) => {
453
484
  clearResetTimer();
@@ -486,13 +517,15 @@ function createCopyMachine(options = {}) {
486
517
  payload,
487
518
  retryCount
488
519
  });
520
+ const context = operations.start();
489
521
  let pending;
490
522
  try {
491
- pending = (read().adapter ?? getDefaultAdapter$1()).write(payload);
523
+ pending = (read().adapter ?? getDefaultAdapter$1()).write(payload, context);
492
524
  } catch (cause) {
493
525
  pending = Promise.reject(cause);
494
526
  }
495
527
  return pending.then(() => {
528
+ operations.end(context);
496
529
  if (current === generation) {
497
530
  const copied = {
498
531
  status: "copied",
@@ -502,15 +535,17 @@ function createCopyMachine(options = {}) {
502
535
  setState(copied);
503
536
  joinCoordinator();
504
537
  scheduleReset(copied);
505
- invoke$1(read().onCopy, payload);
538
+ invoke(read().onCopy, payload);
506
539
  }
507
540
  return {
508
541
  status: "copied",
509
542
  payload
510
543
  };
511
544
  }, (cause) => {
545
+ operations.end(context);
546
+ if (context.signal.aborted) return IGNORED_CANCELLED$1;
512
547
  const error = toCopyError(cause);
513
- if (current === generation) settleError(error, payload, retryCount);
548
+ settleError(error, payload, retryCount);
514
549
  return {
515
550
  status: "error",
516
551
  error
@@ -519,8 +554,8 @@ function createCopyMachine(options = {}) {
519
554
  };
520
555
  const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
521
556
  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);
557
+ if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING$1);
558
+ if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE$1);
524
559
  if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
525
560
  const error = createCopyError("max-retries-exceeded", `Copy failed after ${String(state.retryCount)} retries.`, state.error);
526
561
  settleError(error, state.payload, state.retryCount);
@@ -533,6 +568,7 @@ function createCopyMachine(options = {}) {
533
568
  };
534
569
  const reset = () => {
535
570
  ++generation;
571
+ operations.abort();
536
572
  clearResetTimer();
537
573
  setState(IDLE_STATE);
538
574
  };
@@ -540,6 +576,7 @@ function createCopyMachine(options = {}) {
540
576
  if (state.status === "copied") scheduleReset(state);
541
577
  return () => {
542
578
  ++generation;
579
+ operations.abort();
543
580
  clearResetTimer();
544
581
  if (state.status === "copying") setState(IDLE_STATE);
545
582
  };
@@ -653,7 +690,7 @@ function snapshotDataTransfer(data, options) {
653
690
  * Reads the accepted types from `navigator.clipboard.read()` items, enforcing
654
691
  * the limits *before* decoding any text so an oversized paste is never buffered twice.
655
692
  */
656
- async function collectClipboardItems(items, options) {
693
+ async function collectClipboardItems(items, options, signal) {
657
694
  const budget = createBudget(options);
658
695
  const entries = [];
659
696
  const seen = /* @__PURE__ */ new Set();
@@ -667,6 +704,7 @@ async function collectClipboardItems(items, options) {
667
704
  } catch {
668
705
  continue;
669
706
  }
707
+ if (signal?.aborted) throw copyFailure("aborted", "The paste was cancelled.");
670
708
  if (blob.size === 0) continue;
671
709
  budget.charge(blob.size);
672
710
  entries.push({
@@ -750,32 +788,32 @@ async function readPlainText(clipboard, options) {
750
788
  enforcePasteLimits(entries, options);
751
789
  return finalizePaste(entries, "clipboard", options);
752
790
  }
753
- async function readRich(clipboard, options) {
791
+ async function readRich(clipboard, options, signal) {
754
792
  let items;
755
793
  try {
756
794
  items = await clipboard.read();
757
795
  } catch (cause) {
758
796
  throw new CopyFailure(toCopyError(cause, "read"));
759
797
  }
760
- return finalizePaste(await collectClipboardItems(items, options), "clipboard", options);
798
+ return finalizePaste(await collectClipboardItems(items, options, signal), "clipboard", options);
761
799
  }
762
- function readFromClipboard(env, options) {
800
+ function readFromClipboard(env, options, signal) {
763
801
  if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
764
802
  if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
765
803
  const clipboard = env.navigator?.clipboard;
766
804
  if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
767
805
  const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
768
806
  const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
769
- if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options);
807
+ if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options, signal);
770
808
  if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
771
809
  throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
772
810
  }
773
811
  /** The default paste adapter: async Clipboard API with feature detection and honest errors. */
774
812
  function createBrowserPasteAdapter(options = {}) {
775
813
  const getEnvironment = options.getEnvironment ?? defaultEnvironment;
776
- return { read: (resolved) => {
814
+ return { read: (resolved, context) => {
777
815
  try {
778
- return readFromClipboard(getEnvironment(), resolved);
816
+ return readFromClipboard(getEnvironment(), resolved, context?.signal);
779
817
  } catch (cause) {
780
818
  return Promise.reject(cause);
781
819
  }
@@ -793,25 +831,25 @@ const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
793
831
  status: "ignored",
794
832
  reason: "no-accepted-content"
795
833
  });
834
+ const IGNORED_NOTHING = /* @__PURE__ */ Object.freeze({
835
+ status: "ignored",
836
+ reason: "nothing-to-retry"
837
+ });
838
+ const IGNORED_NOT_RETRYABLE = /* @__PURE__ */ Object.freeze({
839
+ status: "ignored",
840
+ reason: "not-retryable"
841
+ });
842
+ const IGNORED_CANCELLED = /* @__PURE__ */ Object.freeze({
843
+ status: "ignored",
844
+ reason: "cancelled"
845
+ });
796
846
  function resolveResetDelay(value) {
797
847
  if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
798
848
  return Math.max(0, value);
799
849
  }
800
- function reportCallbackError(error) {
801
- const scope = globalThis;
802
- if (typeof scope.reportError === "function") scope.reportError(error);
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
- }
850
+ /** Pure helper: can `retry()` do anything from this state? */
851
+ function canRetryPasteState(state, maxRetries) {
852
+ return state.status === "error" && state.source === "clipboard" && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
815
853
  }
816
854
  let defaultAdapter;
817
855
  const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
@@ -822,6 +860,7 @@ function createPasteMachine(options = {}) {
822
860
  let state = PASTE_IDLE_STATE;
823
861
  let generation = 0;
824
862
  let resetTimer;
863
+ const operations = createOperations();
825
864
  const now = () => (read().now ?? Date.now)();
826
865
  const setState = (next) => {
827
866
  if (next === state) return;
@@ -844,18 +883,29 @@ function createPasteMachine(options = {}) {
844
883
  setState(PASTE_IDLE_STATE);
845
884
  }, remaining);
846
885
  };
886
+ const settleError = (error, source, retryCount) => {
887
+ setState({
888
+ status: "error",
889
+ error,
890
+ source,
891
+ retryCount
892
+ });
893
+ invoke(read().onError, error);
894
+ };
847
895
  /** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
848
- const run = (produce) => {
896
+ const run = (produce, source, retryCount) => {
849
897
  clearResetTimer();
850
898
  const current = ++generation;
899
+ const context = operations.start();
851
900
  setState(PASTE_READING_STATE);
852
901
  let pending;
853
902
  try {
854
- pending = produce();
903
+ pending = produce(context);
855
904
  } catch (cause) {
856
905
  pending = Promise.reject(cause);
857
906
  }
858
907
  return pending.then((result) => {
908
+ operations.end(context);
859
909
  if (current === generation) {
860
910
  const readState = {
861
911
  status: "read",
@@ -871,26 +921,30 @@ function createPasteMachine(options = {}) {
871
921
  result
872
922
  };
873
923
  }, (cause) => {
924
+ operations.end(context);
925
+ if (context.signal.aborted) return IGNORED_CANCELLED;
874
926
  const error = toCopyError(cause, "read");
875
- if (current === generation) {
876
- setState({
877
- status: "error",
878
- error
879
- });
880
- invoke(read().onError, error);
881
- }
927
+ settleError(error, source, retryCount);
882
928
  return {
883
929
  status: "error",
884
930
  error
885
931
  };
886
932
  });
887
933
  };
888
- const paste = () => {
889
- if (state.status === "reading") return Promise.resolve(IGNORED_IN_FLIGHT);
890
- return run(() => {
891
- const resolved = resolvePasteReadOptions(read());
892
- return (read().adapter ?? getDefaultAdapter()).read(resolved);
893
- });
934
+ const readClipboard = (retryCount) => run((context) => (read().adapter ?? getDefaultAdapter()).read(resolvePasteReadOptions(read()), context), "clipboard", retryCount);
935
+ const paste = () => state.status === "reading" ? Promise.resolve(IGNORED_IN_FLIGHT) : readClipboard(0);
936
+ const retry = () => {
937
+ if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
938
+ if (state.source !== "clipboard" || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
939
+ if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
940
+ const error = createCopyError("max-retries-exceeded", `Paste failed after ${String(state.retryCount)} retries.`, state.error);
941
+ settleError(error, "clipboard", state.retryCount);
942
+ return Promise.resolve({
943
+ status: "error",
944
+ error
945
+ });
946
+ }
947
+ return readClipboard(state.retryCount + 1);
894
948
  };
895
949
  const pasteEvent = (event) => {
896
950
  const data = event.clipboardData;
@@ -902,12 +956,9 @@ function createPasteMachine(options = {}) {
902
956
  } catch (cause) {
903
957
  const error = toCopyError(cause, "read");
904
958
  ++generation;
959
+ operations.abort();
905
960
  clearResetTimer();
906
- setState({
907
- status: "error",
908
- error
909
- });
910
- invoke(current.onError, error);
961
+ settleError(error, "event", 0);
911
962
  return Promise.resolve({
912
963
  status: "error",
913
964
  error
@@ -919,10 +970,11 @@ function createPasteMachine(options = {}) {
919
970
  return run(() => {
920
971
  enforcePasteLimits(entries, resolved);
921
972
  return finalizePaste(entries, "event", resolved);
922
- });
973
+ }, "event", 0);
923
974
  };
924
975
  const reset = () => {
925
976
  ++generation;
977
+ operations.abort();
926
978
  clearResetTimer();
927
979
  setState(PASTE_IDLE_STATE);
928
980
  };
@@ -930,6 +982,7 @@ function createPasteMachine(options = {}) {
930
982
  if (state.status === "read") scheduleReset(state);
931
983
  return () => {
932
984
  ++generation;
985
+ operations.abort();
933
986
  clearResetTimer();
934
987
  if (state.status === "reading") setState(PASTE_IDLE_STATE);
935
988
  };
@@ -944,6 +997,7 @@ function createPasteMachine(options = {}) {
944
997
  },
945
998
  paste,
946
999
  pasteEvent,
1000
+ retry,
947
1001
  reset,
948
1002
  connect
949
1003
  };
@@ -1007,7 +1061,7 @@ function useCopy(options = {}) {
1007
1061
  const [machine] = useState(() => createCopyMachine(() => optionsRef.current));
1008
1062
  useEffect(() => machine.connect(), [machine]);
1009
1063
  const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot$2);
1010
- const canRetry = canRetryState(state, options.maxRetries);
1064
+ const canRetry = canRetryState(state, effective.maxRetries);
1011
1065
  return useMemo(() => ({
1012
1066
  state,
1013
1067
  status: state.status,
@@ -1218,6 +1272,36 @@ function LiveRegion({ message, politeness = "polite", visuallyHidden = true, sty
1218
1272
  });
1219
1273
  }
1220
1274
  //#endregion
1275
+ //#region src/react/TriggerLabel.tsx
1276
+ /**
1277
+ * Default trigger label shared by `CopyField` and `PasteField`: every state's
1278
+ * text is stacked in one grid cell, so the button is always as wide as its
1279
+ * longest label and never resizes (no layout shift). Only the active label is
1280
+ * visible and exposed to assistive tech; the crossfade is skipped when the
1281
+ * user prefers reduced motion.
1282
+ */
1283
+ function TriggerLabel({ status, labels }) {
1284
+ const reduceMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
1285
+ return /* @__PURE__ */ jsx("span", {
1286
+ style: { display: "inline-grid" },
1287
+ children: Object.keys(labels).map((candidate) => {
1288
+ const active = candidate === status;
1289
+ return /* @__PURE__ */ jsx("span", {
1290
+ "data-trigger-label": candidate,
1291
+ "data-active": active ? "" : void 0,
1292
+ "aria-hidden": !active || void 0,
1293
+ style: {
1294
+ gridArea: "1 / 1",
1295
+ opacity: active ? 1 : 0,
1296
+ visibility: active ? "visible" : "hidden",
1297
+ ...reduceMotion ? {} : { transition: "opacity 150ms ease, visibility 150ms" }
1298
+ },
1299
+ children: labels[candidate]
1300
+ }, candidate);
1301
+ })
1302
+ });
1303
+ }
1304
+ //#endregion
1221
1305
  //#region src/react/CopyField.tsx
1222
1306
  const defaultCopyFieldMessages = {
1223
1307
  copied: "Copied to clipboard",
@@ -1333,38 +1417,6 @@ const DEFAULT_TRIGGER_TEXT$1 = {
1333
1417
  copied: "Copied",
1334
1418
  error: "Retry"
1335
1419
  };
1336
- const TRIGGER_STATUSES = [
1337
- "idle",
1338
- "copying",
1339
- "copied",
1340
- "error"
1341
- ];
1342
- /**
1343
- * Default label: every state's text is stacked in the same grid cell, so the
1344
- * button is always as wide as its longest label and never resizes (no layout
1345
- * shift). Only the active one is visible; the others crossfade out.
1346
- */
1347
- function DefaultTriggerLabel$1({ status }) {
1348
- const reduceMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
1349
- return /* @__PURE__ */ jsx("span", {
1350
- style: { display: "inline-grid" },
1351
- children: TRIGGER_STATUSES.map((candidate) => {
1352
- const active = candidate === status;
1353
- return /* @__PURE__ */ jsx("span", {
1354
- "data-trigger-label": candidate,
1355
- "data-active": active ? "" : void 0,
1356
- "aria-hidden": active ? void 0 : true,
1357
- style: {
1358
- gridArea: "1 / 1",
1359
- opacity: active ? 1 : 0,
1360
- visibility: active ? "visible" : "hidden",
1361
- ...reduceMotion ? {} : { transition: "opacity 150ms ease, visibility 150ms" }
1362
- },
1363
- children: DEFAULT_TRIGGER_TEXT$1[candidate]
1364
- }, candidate);
1365
- })
1366
- });
1367
- }
1368
1420
  /**
1369
1421
  * Headless compound component for a labelled, copyable value.
1370
1422
  *
@@ -1386,20 +1438,23 @@ const CopyField = {
1386
1438
  revealed: field.revealed,
1387
1439
  canRetry: field.canRetry
1388
1440
  };
1389
- const computedAriaLabel = ariaLabel ?? field.messages.triggerLabel(field.label);
1390
- const safeAriaLabel = computedAriaLabel.length > 0 ? computedAriaLabel : `Copy ${field.label}`;
1441
+ const safeAriaLabel = (ariaLabel ?? field.messages.triggerLabel(field.label)) || defaultCopyFieldMessages.triggerLabel(field.label);
1391
1442
  return /* @__PURE__ */ jsx("button", {
1392
1443
  ...rest,
1393
1444
  ref,
1394
1445
  type: "button",
1395
1446
  "aria-label": safeAriaLabel,
1447
+ "aria-busy": field.status === "copying" ? true : void 0,
1396
1448
  "data-state": field.status,
1397
1449
  "data-display-state": field.displayStatus,
1398
1450
  "data-revealed": field.revealed ? "" : void 0,
1399
1451
  onClick: composeEventHandlers(onClick, () => {
1400
1452
  field.copyValue();
1401
1453
  }),
1402
- children: typeof children === "function" ? children(renderProps) : children ?? /* @__PURE__ */ jsx(DefaultTriggerLabel$1, { status: field.displayStatus })
1454
+ children: typeof children === "function" ? children(renderProps) : children ?? /* @__PURE__ */ jsx(TriggerLabel, {
1455
+ status: field.displayStatus,
1456
+ labels: DEFAULT_TRIGGER_TEXT$1
1457
+ })
1403
1458
  });
1404
1459
  })
1405
1460
  };
@@ -1432,6 +1487,7 @@ function usePaste(options = {}) {
1432
1487
  };
1433
1488
  }, [listenOnDocument, machine]);
1434
1489
  const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot);
1490
+ const canRetry = canRetryPasteState(state, options.maxRetries);
1435
1491
  const targetProps = useMemo(() => ({ onPaste: (event) => {
1436
1492
  machine.pasteEvent(event);
1437
1493
  } }), [machine]);
@@ -1440,12 +1496,15 @@ function usePaste(options = {}) {
1440
1496
  status: state.status,
1441
1497
  result: state.status === "read" ? state.result : null,
1442
1498
  error: state.status === "error" ? state.error : null,
1499
+ canRetry,
1443
1500
  paste: machine.paste,
1444
1501
  pasteEvent: machine.pasteEvent,
1502
+ retry: machine.retry,
1445
1503
  reset: machine.reset,
1446
1504
  targetProps
1447
1505
  }), [
1448
1506
  state,
1507
+ canRetry,
1449
1508
  machine,
1450
1509
  targetProps
1451
1510
  ]);
@@ -1602,22 +1661,24 @@ const Status = /* @__PURE__ */ forwardRef(function PasteFieldStatus({ children,
1602
1661
  });
1603
1662
  });
1604
1663
  /**
1605
- * A drop/paste target area. Spread `usePaste`'s `targetProps` here so the
1606
- * zone accepts keyboard paste events. Also renders a `data-zone` attribute
1607
- * so it can be styled separately from the root.
1664
+ * A focusable paste target. Accepts keyboard paste (Ctrl/⌘+V) without a
1665
+ * permission prompt and renders `data-zone` for styling.
1666
+ *
1667
+ * Accessible name: `aria-label` prop, else `messages.zoneLabel(label)`
1668
+ * ("Paste area for Notes"). Pass `aria-labelledby` explicitly to name it from
1669
+ * another element instead.
1608
1670
  */
1609
1671
  const Zone = /* @__PURE__ */ forwardRef(function PasteFieldZone({ children, focusable = true, onPaste, "aria-label": ariaLabel, tabIndex, ...rest }, ref) {
1610
1672
  const field = usePasteField();
1611
1673
  const { targetProps } = field;
1612
- const computedAriaLabel = ariaLabel ?? field.messages.zoneLabel(field.label);
1613
- const safeAriaLabel = computedAriaLabel.length > 0 ? computedAriaLabel : `Paste area for ${field.label}`;
1674
+ const safeAriaLabel = (ariaLabel ?? field.messages.zoneLabel(field.label)) || defaultPasteFieldMessages.zoneLabel(field.label);
1614
1675
  return /* @__PURE__ */ jsx("div", {
1676
+ "aria-keyshortcuts": "Control+V Meta+V",
1615
1677
  ...rest,
1616
1678
  ref,
1617
1679
  id: field.zoneId,
1618
1680
  role: "region",
1619
1681
  "aria-label": safeAriaLabel,
1620
- "aria-labelledby": field.labelId,
1621
1682
  "data-zone": "",
1622
1683
  "data-state": field.status,
1623
1684
  "data-display-state": field.displayStatus,
@@ -1632,32 +1693,56 @@ const DEFAULT_TRIGGER_TEXT = {
1632
1693
  read: "Pasted",
1633
1694
  error: "Retry"
1634
1695
  };
1635
- const PASTE_STATUSES = [
1636
- "idle",
1637
- "reading",
1638
- "read",
1639
- "error"
1640
- ];
1641
- function DefaultTriggerLabel({ status }) {
1642
- return /* @__PURE__ */ jsx("span", {
1643
- style: { display: "inline-grid" },
1644
- children: PASTE_STATUSES.map((candidate) => {
1645
- const active = candidate === status;
1646
- return /* @__PURE__ */ jsx("span", {
1647
- "data-trigger-label": candidate,
1648
- "data-active": active ? "" : void 0,
1649
- "aria-hidden": active ? void 0 : true,
1650
- style: {
1651
- gridArea: "1 / 1",
1652
- opacity: active ? 1 : 0,
1653
- visibility: active ? "visible" : "hidden",
1654
- transition: "opacity 150ms ease, visibility 150ms"
1655
- },
1656
- children: DEFAULT_TRIGGER_TEXT[candidate]
1657
- }, candidate);
1696
+ const Trigger = /* @__PURE__ */ forwardRef(function PasteFieldTrigger({ children, onClick, "aria-label": ariaLabel, ...rest }, ref) {
1697
+ const field = usePasteField();
1698
+ const renderProps = {
1699
+ status: field.status,
1700
+ displayStatus: field.displayStatus,
1701
+ state: field.state,
1702
+ revealed: field.revealed,
1703
+ canRetry: field.canRetry
1704
+ };
1705
+ const safeAriaLabel = (ariaLabel ?? field.messages.triggerLabel(field.label)) || defaultPasteFieldMessages.triggerLabel(field.label);
1706
+ return /* @__PURE__ */ jsx("button", {
1707
+ ...rest,
1708
+ ref,
1709
+ type: "button",
1710
+ "aria-label": safeAriaLabel,
1711
+ "aria-busy": field.status === "reading" ? true : void 0,
1712
+ "data-state": field.status,
1713
+ "data-display-state": field.displayStatus,
1714
+ "data-revealed": field.revealed ? "" : void 0,
1715
+ onClick: composeEventHandlers(onClick, () => {
1716
+ field.doPaste();
1717
+ }),
1718
+ children: typeof children === "function" ? children(renderProps) : children ?? /* @__PURE__ */ jsx(TriggerLabel, {
1719
+ status: field.displayStatus,
1720
+ labels: DEFAULT_TRIGGER_TEXT
1658
1721
  })
1659
1722
  });
1723
+ });
1724
+ const NO_URLS = [];
1725
+ /**
1726
+ * Object URLs for blobs, revoked when the blobs change or the component
1727
+ * unmounts. URLs are only returned for the blobs they were made from, so they
1728
+ * never pair with the wrong result.
1729
+ */
1730
+ function useObjectUrls(blobs) {
1731
+ const [entry, setEntry] = useState({ urls: NO_URLS });
1732
+ useEffect(() => {
1733
+ if (!blobs?.length || typeof URL.createObjectURL !== "function") return void 0;
1734
+ const urls = blobs.map((blob) => URL.createObjectURL(blob));
1735
+ setEntry({
1736
+ blobs,
1737
+ urls
1738
+ });
1739
+ return () => {
1740
+ for (const url of urls) URL.revokeObjectURL(url);
1741
+ };
1742
+ }, [blobs]);
1743
+ return entry.blobs === blobs ? entry.urls : NO_URLS;
1660
1744
  }
1745
+ const defaultImageAlt = (index, total) => `Pasted image ${String(index + 1)} of ${String(total)}`;
1661
1746
  /**
1662
1747
  * Headless compound component for a labelled, paste-ready field.
1663
1748
  *
@@ -1672,6 +1757,7 @@ function DefaultTriggerLabel({ status }) {
1672
1757
  * <PasteField.Label />
1673
1758
  * <PasteField.Zone />
1674
1759
  * <PasteField.Trigger />
1760
+ * <PasteField.Preview placeholder="Nothing pasted yet" />
1675
1761
  * </PasteField.Root>
1676
1762
  * ```
1677
1763
  */
@@ -1680,32 +1766,47 @@ const PasteField = {
1680
1766
  Label,
1681
1767
  Status,
1682
1768
  Zone,
1683
- Trigger: /* @__PURE__ */ forwardRef(function PasteFieldTrigger({ children, onClick, "aria-label": ariaLabel, ...rest }, ref) {
1684
- const field = usePasteField();
1685
- const renderProps = {
1686
- status: field.status,
1687
- displayStatus: field.displayStatus,
1688
- state: field.state,
1689
- revealed: field.revealed
1690
- };
1691
- const computedAriaLabel = ariaLabel ?? field.messages.triggerLabel(field.label);
1692
- const safeAriaLabel = computedAriaLabel.length > 0 ? computedAriaLabel : `Paste ${field.label}`;
1693
- return /* @__PURE__ */ jsx("button", {
1769
+ Trigger,
1770
+ Preview: /* @__PURE__ */ forwardRef(function PasteFieldPreview({ children, placeholder = null, maxTextLength = 2e3, imageAlt = defaultImageAlt, ...rest }, ref) {
1771
+ const { result, status } = usePasteField();
1772
+ const imageUrls = useObjectUrls(result?.images);
1773
+ let content = placeholder;
1774
+ if (result) {
1775
+ if (children) content = children({
1776
+ result,
1777
+ imageUrls
1778
+ });
1779
+ else {
1780
+ const { text } = result;
1781
+ const files = result.files.filter((file) => !file.type.startsWith("image/"));
1782
+ content = /* @__PURE__ */ jsxs(Fragment, { children: [
1783
+ text ? /* @__PURE__ */ jsx("pre", {
1784
+ "data-preview-text": "",
1785
+ children: text.length > maxTextLength ? `${text.slice(0, maxTextLength)}…` : text
1786
+ }) : null,
1787
+ imageUrls.map((url, index) => /* @__PURE__ */ jsx("img", {
1788
+ "data-preview-image": "",
1789
+ src: url,
1790
+ alt: imageAlt(index, imageUrls.length)
1791
+ }, url)),
1792
+ files.length > 0 ? /* @__PURE__ */ jsx("ul", {
1793
+ "data-preview-files": "",
1794
+ children: files.map((file, index) => /* @__PURE__ */ jsx("li", { children: file.name }, `${String(index)}-${file.name}`))
1795
+ }) : null
1796
+ ] });
1797
+ }
1798
+ }
1799
+ return /* @__PURE__ */ jsx("div", {
1694
1800
  ...rest,
1695
1801
  ref,
1696
- type: "button",
1697
- "aria-label": safeAriaLabel,
1698
- "data-state": field.status,
1699
- "data-display-state": field.displayStatus,
1700
- "data-revealed": field.revealed ? "" : void 0,
1701
- onClick: composeEventHandlers(onClick, () => {
1702
- field.doPaste();
1703
- }),
1704
- children: typeof children === "function" ? children(renderProps) : children ?? /* @__PURE__ */ jsx(DefaultTriggerLabel, { status: field.displayStatus })
1802
+ "data-preview": "",
1803
+ "data-state": status,
1804
+ "data-empty": result ? void 0 : "",
1805
+ children: content
1705
1806
  });
1706
1807
  })
1707
1808
  };
1708
1809
  //#endregion
1709
- 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 };
1810
+ 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 };
1710
1811
 
1711
1812
  //# sourceMappingURL=index.js.map