react-smart-copy 1.2.0 → 1.4.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.js CHANGED
@@ -99,9 +99,19 @@ const PASTE_DESCRIPTIONS = {
99
99
  function describeCopyError(error) {
100
100
  return COPY_DESCRIPTIONS[error.type];
101
101
  }
102
- /** Default English, user-facing sentence for a paste error. Replace for i18n. */
103
- function describePasteError(error) {
104
- return PASTE_DESCRIPTIONS[error.type];
102
+ /** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */
103
+ const DROP_DESCRIPTIONS = {
104
+ "invalid-payload": "The dropped content couldn't be read.",
105
+ "no-content": "Nothing that was dropped can be used here.",
106
+ "too-large": "The dropped content is too large.",
107
+ unknown: "Couldn't read the dropped content. Try again."
108
+ };
109
+ /**
110
+ * Default English, user-facing sentence for a paste error. Pass the error
111
+ * state's `source` to word drag-and-drop failures as drops. Replace for i18n.
112
+ */
113
+ function describePasteError(error, source) {
114
+ return (source === "drop" ? DROP_DESCRIPTIONS[error.type] : void 0) ?? PASTE_DESCRIPTIONS[error.type];
105
115
  }
106
116
  //#endregion
107
117
  //#region src/core/payload.ts
@@ -376,8 +386,10 @@ function invoke(fn, ...args) {
376
386
  function createOperations() {
377
387
  let controller;
378
388
  const abort = () => {
379
- controller?.abort();
389
+ if (!controller) return false;
390
+ controller.abort();
380
391
  controller = void 0;
392
+ return true;
381
393
  };
382
394
  return {
383
395
  start: () => {
@@ -565,17 +577,21 @@ function createCopyMachine(options = {}) {
565
577
  };
566
578
  const reset = () => {
567
579
  ++generation;
568
- operations.abort();
580
+ const cancelled = operations.abort();
569
581
  clearResetTimer();
582
+ const wasIdle = state.status === "idle";
570
583
  setState(IDLE_STATE);
584
+ if (cancelled) invoke(read().onCancel, "reset");
585
+ if (!wasIdle) invoke(read().onReset);
571
586
  };
572
587
  const connect = () => {
573
588
  if (state.status === "copied") scheduleReset(state);
574
589
  return () => {
575
590
  ++generation;
576
- operations.abort();
591
+ const cancelled = operations.abort();
577
592
  clearResetTimer();
578
593
  if (state.status === "copying") setState(IDLE_STATE);
594
+ if (cancelled) invoke(read().onCancel, "disconnect");
579
595
  };
580
596
  };
581
597
  return {
@@ -594,6 +610,14 @@ function createCopyMachine(options = {}) {
594
610
  }
595
611
  //#endregion
596
612
  //#region src/core/paste-reader.ts
613
+ /** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
614
+ function completePasteResult(result) {
615
+ const images = new Set(result.images);
616
+ return {
617
+ ...result,
618
+ imageFiles: result.files.filter((file) => images.has(file))
619
+ };
620
+ }
597
621
  const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
598
622
  const DEFAULT_PASTE_MAX_BYTES = 33554432;
599
623
  const DEFAULT_PASTE_MAX_ITEMS = 32;
@@ -649,13 +673,52 @@ function createBudget(options) {
649
673
  if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
650
674
  } };
651
675
  }
652
- const sizeOf = (data) => typeof data === "string" ? data.length : data.size;
676
+ /**
677
+ * UTF-8 byte length of a string, without allocating an encoded copy.
678
+ * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.
679
+ */
680
+ function utf8ByteLength(text) {
681
+ let bytes = 0;
682
+ for (let i = 0; i < text.length; i += 1) {
683
+ const unit = text.charCodeAt(i);
684
+ if (unit < 128) bytes += 1;
685
+ else if (unit < 2048) bytes += 2;
686
+ else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length && (text.charCodeAt(i + 1) & 64512) === 56320) {
687
+ bytes += 4;
688
+ i += 1;
689
+ } else bytes += 3;
690
+ }
691
+ return bytes;
692
+ }
693
+ /** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */
694
+ const sizeOf = (data) => typeof data === "string" ? utf8ByteLength(data) : data.size;
653
695
  /** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
654
696
  function enforcePasteLimits(entries, options) {
655
697
  const budget = createBudget(options);
656
698
  for (const entry of entries) budget.charge(sizeOf(entry.data));
657
699
  }
658
700
  /**
701
+ * Whether a drag in progress could drop anything `accept`s. Uses only what
702
+ * browsers expose before the drop (item kinds and types, never the data).
703
+ * A file whose type is not known yet (some browsers hide it while dragging)
704
+ * counts as a maybe: the drop itself is checked against `accept`.
705
+ */
706
+ function canAcceptDrag(data, options) {
707
+ const items = data.items ?? Array.from(data.types, (type) => type === "Files" ? {
708
+ kind: "file",
709
+ type: ""
710
+ } : {
711
+ kind: "string",
712
+ type
713
+ });
714
+ return Array.from(items).some(({ kind, type: raw }) => {
715
+ const file = kind === "file";
716
+ const type = normalizeMimeType(raw);
717
+ if (type === null) return file;
718
+ return (file || isTextualMimeType(type)) && isAccepted(type, options);
719
+ });
720
+ }
721
+ /**
659
722
  * Synchronously copies the accepted parts of a paste event's `DataTransfer`.
660
723
  * It must run during the event: browsers empty the object afterwards.
661
724
  */
@@ -753,7 +816,7 @@ async function finalizePaste(entries, source, options) {
753
816
  data
754
817
  });
755
818
  }
756
- if (items.length === 0) throw copyFailure("no-content", "The clipboard holds nothing that matches `accept`.");
819
+ if (items.length === 0) throw copyFailure("no-content", "The content holds nothing that matches `accept`.");
757
820
  return {
758
821
  source,
759
822
  items,
@@ -893,15 +956,17 @@ function createPasteMachine(options = {}) {
893
956
  const run = (produce, source, retryCount) => {
894
957
  clearResetTimer();
895
958
  const current = ++generation;
959
+ const superseded = operations.abort();
896
960
  const context = operations.start();
897
961
  setState(PASTE_READING_STATE);
962
+ if (superseded) invoke(read().onCancel, "superseded");
898
963
  let pending;
899
964
  try {
900
965
  pending = produce(context);
901
966
  } catch (cause) {
902
967
  pending = Promise.reject(cause);
903
968
  }
904
- return pending.then((result) => {
969
+ return pending.then(completePasteResult).then((result) => {
905
970
  operations.end(context);
906
971
  if (current === generation) {
907
972
  const readState = {
@@ -943,19 +1008,21 @@ function createPasteMachine(options = {}) {
943
1008
  }
944
1009
  return readClipboard(state.retryCount + 1);
945
1010
  };
946
- const pasteEvent = (event) => {
947
- const data = event.clipboardData;
948
- if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
1011
+ /** Shared by paste and drop events: their `DataTransfer` has the same shape and lifetime. */
1012
+ const transfer = (data, event, source) => {
949
1013
  const current = read();
1014
+ if (source === "drop" && current.preventDefault !== false) event.preventDefault();
1015
+ if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
950
1016
  let resolved;
951
1017
  try {
952
1018
  resolved = resolvePasteReadOptions(current);
953
1019
  } catch (cause) {
954
1020
  const error = toCopyError(cause, "read");
955
1021
  ++generation;
956
- operations.abort();
1022
+ const superseded = operations.abort();
957
1023
  clearResetTimer();
958
- settleError(error, "event", 0);
1024
+ settleError(error, source, 0);
1025
+ if (superseded) invoke(current.onCancel, "superseded");
959
1026
  return Promise.resolve({
960
1027
  status: "error",
961
1028
  error
@@ -963,25 +1030,31 @@ function createPasteMachine(options = {}) {
963
1030
  }
964
1031
  const entries = snapshotDataTransfer(data, resolved);
965
1032
  if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);
966
- if (current.preventDefault !== false) event.preventDefault();
1033
+ if (source === "event" && current.preventDefault !== false) event.preventDefault();
967
1034
  return run(() => {
968
1035
  enforcePasteLimits(entries, resolved);
969
- return finalizePaste(entries, "event", resolved);
970
- }, "event", 0);
1036
+ return finalizePaste(entries, source, resolved);
1037
+ }, source, 0);
971
1038
  };
1039
+ const pasteEvent = (event) => transfer(event.clipboardData, event, "event");
1040
+ const dropEvent = (event) => transfer(event.dataTransfer, event, "drop");
972
1041
  const reset = () => {
973
1042
  ++generation;
974
- operations.abort();
1043
+ const cancelled = operations.abort();
975
1044
  clearResetTimer();
1045
+ const wasIdle = state.status === "idle";
976
1046
  setState(PASTE_IDLE_STATE);
1047
+ if (cancelled) invoke(read().onCancel, "reset");
1048
+ if (!wasIdle) invoke(read().onReset);
977
1049
  };
978
1050
  const connect = () => {
979
1051
  if (state.status === "read") scheduleReset(state);
980
1052
  return () => {
981
1053
  ++generation;
982
- operations.abort();
1054
+ const cancelled = operations.abort();
983
1055
  clearResetTimer();
984
1056
  if (state.status === "reading") setState(PASTE_IDLE_STATE);
1057
+ if (cancelled) invoke(read().onCancel, "disconnect");
985
1058
  };
986
1059
  };
987
1060
  return {
@@ -994,12 +1067,13 @@ function createPasteMachine(options = {}) {
994
1067
  },
995
1068
  paste,
996
1069
  pasteEvent,
1070
+ dropEvent,
997
1071
  retry,
998
1072
  reset,
999
1073
  connect
1000
1074
  };
1001
1075
  }
1002
1076
  //#endregion
1003
- export { CopyFailure, DEFAULT_MAX_RETRIES, DEFAULT_PASTE_ACCEPT, DEFAULT_PASTE_MAX_BYTES, DEFAULT_PASTE_MAX_ITEMS, DEFAULT_RESET_AFTER_MS, IDLE_STATE, IMAGE_MIME_TYPE, PASTE_IDLE_STATE, SVG_MIME_TYPE, canRetryPasteState, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, describeCopyError, describePasteError, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, matchesMimePattern, normalizeMimeType, normalizePayload, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, validatePayload };
1077
+ export { CopyFailure, DEFAULT_MAX_RETRIES, DEFAULT_PASTE_ACCEPT, DEFAULT_PASTE_MAX_BYTES, DEFAULT_PASTE_MAX_ITEMS, DEFAULT_RESET_AFTER_MS, IDLE_STATE, IMAGE_MIME_TYPE, PASTE_IDLE_STATE, SVG_MIME_TYPE, canAcceptDrag, canRetryPasteState, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, describeCopyError, describePasteError, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, matchesMimePattern, normalizeMimeType, normalizePayload, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, validatePayload };
1004
1078
 
1005
1079
  //# sourceMappingURL=core.js.map