react-smart-copy 1.7.1 → 1.8.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
@@ -134,40 +134,40 @@ function isBlob(value) {
134
134
  function isThenable(value) {
135
135
  return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
136
136
  }
137
- const invalid$1 = (message) => createCopyError("invalid-payload", message);
137
+ const invalid$2 = (message) => createCopyError("invalid-payload", message);
138
138
  /**
139
139
  * Structural validation. Typed callers can't produce most of these states,
140
140
  * but plain-JS callers and runtime data can, so the check is always on.
141
141
  */
142
142
  function validatePayload(payload) {
143
- if (typeof payload !== "object" || payload === null) return invalid$1("Copy input must be a string or a payload object.");
143
+ if (typeof payload !== "object" || payload === null) return invalid$2("Copy input must be a string or a payload object.");
144
144
  const candidate = payload;
145
145
  switch (candidate["kind"]) {
146
- case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid$1("Text payload must be a non-empty string.");
146
+ case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid$2("Text payload must be a non-empty string.");
147
147
  case "html":
148
- if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid$1("HTML payload requires a non-empty `html` string.");
149
- return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid$1("HTML payload requires a non-empty plain-text `text` fallback.");
148
+ if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid$2("HTML payload requires a non-empty `html` string.");
149
+ return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid$2("HTML payload requires a non-empty plain-text `text` fallback.");
150
150
  case "image": {
151
151
  const source = candidate["blob"];
152
- return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid$1("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
152
+ return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid$2("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
153
153
  }
154
- case "json": return candidate["value"] === void 0 ? invalid$1("JSON payload value is undefined.") : null;
154
+ case "json": return candidate["value"] === void 0 ? invalid$2("JSON payload value is undefined.") : null;
155
155
  case "multi": {
156
156
  const items = candidate["items"];
157
- if (!Array.isArray(items) || items.length === 0) return invalid$1("Multi payload requires at least one item.");
157
+ if (!Array.isArray(items) || items.length === 0) return invalid$2("Multi payload requires at least one item.");
158
158
  const seen = /* @__PURE__ */ new Set();
159
159
  for (const item of items) {
160
160
  const entry = typeof item === "object" && item !== null ? item : {};
161
161
  const mimeType = entry["mimeType"];
162
162
  const data = entry["data"];
163
- if (typeof mimeType !== "string" || mimeType.length === 0) return invalid$1("Every multi item needs a non-empty `mimeType`.");
164
- if (seen.has(mimeType)) return invalid$1(`Duplicate MIME type "${mimeType}" in multi payload.`);
163
+ if (typeof mimeType !== "string" || mimeType.length === 0) return invalid$2("Every multi item needs a non-empty `mimeType`.");
164
+ if (seen.has(mimeType)) return invalid$2(`Duplicate MIME type "${mimeType}" in multi payload.`);
165
165
  seen.add(mimeType);
166
- if (typeof data !== "string" && !isBlob(data)) return invalid$1(`Multi item "${mimeType}" must contain a string or a Blob.`);
166
+ if (typeof data !== "string" && !isBlob(data)) return invalid$2(`Multi item "${mimeType}" must contain a string or a Blob.`);
167
167
  }
168
168
  return null;
169
169
  }
170
- default: return invalid$1(`Unknown payload kind: ${String(candidate["kind"])}.`);
170
+ default: return invalid$2(`Unknown payload kind: ${String(candidate["kind"])}.`);
171
171
  }
172
172
  }
173
173
  /** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
@@ -697,12 +697,12 @@ function readCopySelection(event) {
697
697
  const read = readSelection(event);
698
698
  return read ? read.selection : null;
699
699
  }
700
- const nonEmpty = (value) => typeof value === "string" && value.length > 0;
701
- const invalid = (message, cause) => ({
700
+ const nonEmpty$1 = (value) => typeof value === "string" && value.length > 0;
701
+ const invalid$1 = (message, cause) => ({
702
702
  ok: false,
703
703
  error: createCopyError("invalid-payload", message, cause)
704
704
  });
705
- const unsupported = (message) => ({
705
+ const unsupported$1 = (message) => ({
706
706
  ok: false,
707
707
  error: createCopyError("unsupported-format", message)
708
708
  });
@@ -716,8 +716,8 @@ function prepare(decision) {
716
716
  kind: "text",
717
717
  value: decision
718
718
  } : decision;
719
- if (typeof candidate !== "object" || candidate === null) return invalid("Copy transforms must return a string, a payload, false, or nothing.");
720
- if (typeof candidate.then === "function") return invalid("Copy transforms must be synchronous; the clipboard closes when the event ends.");
719
+ if (typeof candidate !== "object" || candidate === null) return invalid$1("Copy transforms must return a string, a payload, false, or nothing.");
720
+ if (typeof candidate.then === "function") return invalid$1("Copy transforms must be synchronous; the clipboard closes when the event ends.");
721
721
  const payload = candidate;
722
722
  const fields = candidate;
723
723
  const ok = (entries) => ({
@@ -726,8 +726,8 @@ function prepare(decision) {
726
726
  entries
727
727
  });
728
728
  switch (fields["kind"]) {
729
- case "text": return nonEmpty(fields["value"]) ? ok([["text/plain", fields["value"]]]) : invalid("Text payload must be a non-empty string.");
730
- case "html": return nonEmpty(fields["html"]) && nonEmpty(fields["text"]) ? ok([["text/html", fields["html"]], ["text/plain", fields["text"]]]) : invalid("HTML payload requires non-empty `html` and plain-text `text`.");
729
+ case "text": return nonEmpty$1(fields["value"]) ? ok([["text/plain", fields["value"]]]) : invalid$1("Text payload must be a non-empty string.");
730
+ case "html": return nonEmpty$1(fields["html"]) && nonEmpty$1(fields["text"]) ? ok([["text/html", fields["html"]], ["text/plain", fields["text"]]]) : invalid$1("HTML payload requires non-empty `html` and plain-text `text`.");
731
731
  case "json": {
732
732
  const pretty = fields["pretty"];
733
733
  const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
@@ -735,23 +735,23 @@ function prepare(decision) {
735
735
  try {
736
736
  json = JSON.stringify(fields["value"], null, indent);
737
737
  } catch (cause) {
738
- return invalid("JSON payload could not be serialised (circular reference or BigInt?).", cause);
738
+ return invalid$1("JSON payload could not be serialised (circular reference or BigInt?).", cause);
739
739
  }
740
- return typeof json === "string" ? ok([["text/plain", json]]) : invalid("JSON payload serialised to nothing.");
740
+ return typeof json === "string" ? ok([["text/plain", json]]) : invalid$1("JSON payload serialised to nothing.");
741
741
  }
742
742
  case "multi": {
743
743
  const items = fields["items"];
744
- if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
744
+ if (!Array.isArray(items) || items.length === 0) return invalid$1("Multi payload requires at least one item.");
745
745
  const entries = [];
746
746
  for (const item of items) {
747
747
  const { mimeType, data } = item ?? {};
748
- if (!nonEmpty(mimeType) || entries.some(([seen]) => seen === mimeType)) return invalid("Every multi item needs a unique, non-empty `mimeType`.");
749
- if (typeof data !== "string") return unsupported(`Multi item "${mimeType}" must be a string during a copy event.`);
748
+ if (!nonEmpty$1(mimeType) || entries.some(([seen]) => seen === mimeType)) return invalid$1("Every multi item needs a unique, non-empty `mimeType`.");
749
+ if (typeof data !== "string") return unsupported$1(`Multi item "${mimeType}" must be a string during a copy event.`);
750
750
  entries.push([mimeType, data]);
751
751
  }
752
752
  return ok(entries);
753
753
  }
754
- default: return unsupported(`"${String(fields["kind"])}" payloads cannot be written during a copy event; use useCopy() for images.`);
754
+ default: return unsupported$1(`"${String(fields["kind"])}" payloads cannot be written during a copy event; use useCopy() for images.`);
755
755
  }
756
756
  }
757
757
  /** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */
@@ -913,6 +913,200 @@ function registerCopyInterceptor(root, options) {
913
913
  };
914
914
  }
915
915
  //#endregion
916
+ //#region src/core/drag-copy.ts
917
+ /**
918
+ * Drag-to-copy: populate `DataTransfer` when the user starts dragging an
919
+ * element, so whatever they drop it into receives structured data — plain text,
920
+ * HTML, JSON, or multiple MIME types — instead of the browser's default
921
+ * text-extraction of the dragged DOM.
922
+ *
923
+ * No Clipboard API, no permission prompt, works in every browser that supports
924
+ * HTML5 drag-and-drop (all modern browsers and IE11+).
925
+ */
926
+ const nonEmpty = (value) => typeof value === "string" && value.length > 0;
927
+ const invalid = (message, cause) => ({
928
+ ok: false,
929
+ error: createCopyError("invalid-payload", message, cause)
930
+ });
931
+ const unsupported = (message) => ({
932
+ ok: false,
933
+ error: createCopyError("unsupported-format", message)
934
+ });
935
+ function prepareDragDecision(decision) {
936
+ const candidate = typeof decision === "string" ? {
937
+ kind: "text",
938
+ value: decision
939
+ } : decision;
940
+ if (typeof candidate !== "object" || candidate === null) return invalid("Drag source must return a string, a payload, false, or nothing.");
941
+ if (typeof candidate.then === "function") return invalid("Drag sources must be synchronous; DataTransfer closes when dragstart returns.");
942
+ const payload = candidate;
943
+ const fields = candidate;
944
+ const ok = (items) => ({
945
+ ok: true,
946
+ payload,
947
+ items
948
+ });
949
+ switch (fields["kind"]) {
950
+ case "text": return nonEmpty(fields["value"]) ? ok([{
951
+ mimeType: "text/plain",
952
+ data: fields["value"]
953
+ }]) : invalid("Text payload must be a non-empty string.");
954
+ case "html": return nonEmpty(fields["html"]) && nonEmpty(fields["text"]) ? ok([{
955
+ mimeType: "text/html",
956
+ data: fields["html"]
957
+ }, {
958
+ mimeType: "text/plain",
959
+ data: fields["text"]
960
+ }]) : invalid("HTML payload requires non-empty `html` and `text`.");
961
+ case "json": {
962
+ const pretty = fields["pretty"];
963
+ const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
964
+ let json;
965
+ try {
966
+ json = JSON.stringify(fields["value"], null, indent);
967
+ } catch (cause) {
968
+ return invalid("JSON payload could not be serialised (circular reference or BigInt?).", cause);
969
+ }
970
+ return typeof json === "string" ? ok([{
971
+ mimeType: "text/plain",
972
+ data: json
973
+ }]) : invalid("JSON payload serialised to nothing.");
974
+ }
975
+ case "multi": {
976
+ const items = fields["items"];
977
+ if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
978
+ const out = [];
979
+ for (const item of items) {
980
+ const { mimeType, data } = item ?? {};
981
+ if (!nonEmpty(mimeType) || out.some((i) => i.mimeType === mimeType)) return invalid("Every multi item needs a unique, non-empty `mimeType`.");
982
+ if (typeof data !== "string") return unsupported(`Multi item "${mimeType}" must be a string; DataTransfer does not accept Blobs.`);
983
+ out.push({
984
+ mimeType,
985
+ data
986
+ });
987
+ }
988
+ return ok(out);
989
+ }
990
+ default: return unsupported(`"${String(fields["kind"])}" payloads cannot be used for drag-copy; use useCopy() for images.`);
991
+ }
992
+ }
993
+ /**
994
+ * Populates a `dragstart` event's `DataTransfer` with the given payload.
995
+ * Use this from a raw `dragstart` handler or a React `onDragStart` prop.
996
+ * Returns the outcome so you can inspect what happened.
997
+ */
998
+ function applyDragCopy(event, options) {
999
+ if (event.defaultPrevented) return {
1000
+ status: "passed",
1001
+ reason: "declined"
1002
+ };
1003
+ let decision;
1004
+ try {
1005
+ decision = options.source(event);
1006
+ } catch (cause) {
1007
+ return {
1008
+ status: "failed",
1009
+ error: createCopyError("invalid-payload", "The drag source threw.", cause)
1010
+ };
1011
+ }
1012
+ if (decision === null || decision === void 0) return {
1013
+ status: "passed",
1014
+ reason: "declined"
1015
+ };
1016
+ if (decision === false) {
1017
+ event.preventDefault();
1018
+ return {
1019
+ status: "passed",
1020
+ reason: "cancelled"
1021
+ };
1022
+ }
1023
+ const transfer = event.dataTransfer;
1024
+ if (!transfer) return {
1025
+ status: "passed",
1026
+ reason: "no-transfer"
1027
+ };
1028
+ const prepared = prepareDragDecision(decision);
1029
+ if (!prepared.ok) return {
1030
+ status: "failed",
1031
+ error: prepared.error
1032
+ };
1033
+ try {
1034
+ transfer.effectAllowed = options.effectAllowed ?? "copy";
1035
+ for (const { mimeType, data } of prepared.items) transfer.setData(mimeType, data);
1036
+ } catch (cause) {
1037
+ try {
1038
+ transfer.clearData?.();
1039
+ } catch {}
1040
+ return {
1041
+ status: "failed",
1042
+ error: createCopyError("unknown", "The browser rejected the DataTransfer write.", cause)
1043
+ };
1044
+ }
1045
+ return {
1046
+ status: "written",
1047
+ payload: prepared.payload
1048
+ };
1049
+ }
1050
+ /**
1051
+ * Attaches `dragstart` and `dragend` listeners to `element`, calling
1052
+ * `applyDragCopy` on every drag start. Returns an object with an
1053
+ * `unsubscribe` function.
1054
+ *
1055
+ * Pass an options getter so the latest options are always used without
1056
+ * re-registering — safe to pass an inline object from a React render.
1057
+ *
1058
+ * ```ts
1059
+ * const { unsubscribe } = registerDragCopy(el, () => ({
1060
+ * source: () => `${title}\n${url}`,
1061
+ * }));
1062
+ * ```
1063
+ */
1064
+ function registerDragCopy(element, options) {
1065
+ const read = typeof options === "function" ? options : () => options;
1066
+ let unsubscribed = false;
1067
+ let currentOutcome = null;
1068
+ function onDragStart(raw) {
1069
+ const event = raw;
1070
+ const opts = read();
1071
+ const outcome = applyDragCopy({
1072
+ type: event.type,
1073
+ dataTransfer: event.dataTransfer,
1074
+ get defaultPrevented() {
1075
+ return event.defaultPrevented;
1076
+ },
1077
+ preventDefault: () => {
1078
+ event.preventDefault();
1079
+ }
1080
+ }, opts);
1081
+ currentOutcome = outcome;
1082
+ const state = {
1083
+ status: "dragging",
1084
+ outcome
1085
+ };
1086
+ if (outcome.status === "failed") invoke(opts.onError, outcome.error);
1087
+ invoke(opts.onDrag, state);
1088
+ }
1089
+ function onDragEnd() {
1090
+ const opts = read();
1091
+ const state = {
1092
+ status: "done",
1093
+ outcome: currentOutcome
1094
+ };
1095
+ invoke(opts.onDrag, state);
1096
+ currentOutcome = null;
1097
+ }
1098
+ element.setAttribute("draggable", "true");
1099
+ element.addEventListener("dragstart", onDragStart);
1100
+ element.addEventListener("dragend", onDragEnd);
1101
+ return { unsubscribe() {
1102
+ if (unsubscribed) return;
1103
+ unsubscribed = true;
1104
+ element.removeEventListener("dragstart", onDragStart);
1105
+ element.removeEventListener("dragend", onDragEnd);
1106
+ element.removeAttribute("draggable");
1107
+ } };
1108
+ }
1109
+ //#endregion
916
1110
  //#region src/core/paste-reader.ts
917
1111
  /** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
918
1112
  function completePasteResult(result) {
@@ -2285,6 +2479,108 @@ const PasteField = {
2285
2479
  })
2286
2480
  };
2287
2481
  //#endregion
2288
- export { CopyFailure, CopyField, CopyGroup, DEFAULT_INTERCEPTED_EVENTS, 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, canAcceptDrag, canRetryPasteState, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, defaultCopyFieldMessages, defaultPasteFieldMessages, describeCopyError, describePasteError, interceptCopyEvent, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, matchesMimePattern, normalizeMimeType, normalizePayload, readCopySelection, registerCopyInterceptor, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, useCopy, useCopyField, useCopyGroup, useCopyInterceptor, useDisplayStatus, usePaste, usePasteDisplayStatus, usePasteField, useRevealOnInteraction, validatePayload, visuallyHiddenStyle };
2482
+ //#region src/react/useDragCopy.ts
2483
+ /**
2484
+ * Makes an element draggable and populates its `DataTransfer` with your data.
2485
+ *
2486
+ * ```tsx
2487
+ * const { ref } = useDragCopy({
2488
+ * source: () => ({ kind: 'html', html: '<b>Hello</b>', text: 'Hello' }),
2489
+ * });
2490
+ * return <div ref={ref}>Drag me</div>;
2491
+ * ```
2492
+ *
2493
+ * - No Clipboard API needed — works in every browser supporting HTML5 drag-and-drop.
2494
+ * - The `source` callback always reads the latest props/state, never stale closures.
2495
+ * - `enabled={false}` removes `draggable` and the listener without unmounting.
2496
+ * - SSR-safe: no DOM access during server rendering.
2497
+ */
2498
+ function useDragCopy(options) {
2499
+ const optionsRef = useRef(options);
2500
+ useIsomorphicLayoutEffect(() => {
2501
+ optionsRef.current = options;
2502
+ });
2503
+ const [node, setNode] = useState(null);
2504
+ const [state, setState] = useState({
2505
+ status: "idle",
2506
+ outcome: null
2507
+ });
2508
+ const enabled = options.enabled !== false;
2509
+ const onDragStart = useCallback((event) => {
2510
+ const { onDrag, onError, source, effectAllowed } = optionsRef.current;
2511
+ const outcome = applyDragCopy(event, effectAllowed !== void 0 ? {
2512
+ source,
2513
+ effectAllowed
2514
+ } : { source });
2515
+ const next = {
2516
+ status: "dragging",
2517
+ outcome
2518
+ };
2519
+ setState(next);
2520
+ if (outcome.status === "failed") invoke(onError, outcome.error);
2521
+ invoke(onDrag, next);
2522
+ }, []);
2523
+ useEffect(() => {
2524
+ if (!node || !enabled) return void 0;
2525
+ node.setAttribute("draggable", "true");
2526
+ function handleDragStart(raw) {
2527
+ const event = raw;
2528
+ const { onDrag, onError, source, effectAllowed } = optionsRef.current;
2529
+ const coreOpts = effectAllowed !== void 0 ? {
2530
+ source,
2531
+ effectAllowed
2532
+ } : { source };
2533
+ const outcome = applyDragCopy({
2534
+ type: event.type,
2535
+ dataTransfer: event.dataTransfer,
2536
+ get defaultPrevented() {
2537
+ return event.defaultPrevented;
2538
+ },
2539
+ preventDefault: () => {
2540
+ event.preventDefault();
2541
+ }
2542
+ }, coreOpts);
2543
+ const next = {
2544
+ status: "dragging",
2545
+ outcome
2546
+ };
2547
+ setState(next);
2548
+ if (outcome.status === "failed") invoke(onError, outcome.error);
2549
+ invoke(onDrag, next);
2550
+ }
2551
+ function handleDragEnd() {
2552
+ const opts = optionsRef.current;
2553
+ setState((prev) => {
2554
+ const next = {
2555
+ status: "done",
2556
+ outcome: prev.outcome
2557
+ };
2558
+ invoke(opts.onDrag, next);
2559
+ return next;
2560
+ });
2561
+ }
2562
+ node.addEventListener("dragstart", handleDragStart);
2563
+ node.addEventListener("dragend", handleDragEnd);
2564
+ return () => {
2565
+ node.removeEventListener("dragstart", handleDragStart);
2566
+ node.removeEventListener("dragend", handleDragEnd);
2567
+ node.removeAttribute("draggable");
2568
+ };
2569
+ }, [node, enabled]);
2570
+ useEffect(() => {
2571
+ if (!enabled) setState({
2572
+ status: "idle",
2573
+ outcome: null
2574
+ });
2575
+ }, [enabled]);
2576
+ return {
2577
+ ref: setNode,
2578
+ status: state.status,
2579
+ outcome: state.outcome,
2580
+ onDragStart
2581
+ };
2582
+ }
2583
+ //#endregion
2584
+ export { CopyFailure, CopyField, CopyGroup, DEFAULT_INTERCEPTED_EVENTS, 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, applyDragCopy, canAcceptDrag, canRetryPasteState, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, defaultCopyFieldMessages, defaultPasteFieldMessages, describeCopyError, describePasteError, interceptCopyEvent, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, matchesMimePattern, normalizeMimeType, normalizePayload, readCopySelection, registerCopyInterceptor, registerDragCopy, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, useCopy, useCopyField, useCopyGroup, useCopyInterceptor, useDisplayStatus, useDragCopy, usePaste, usePasteDisplayStatus, usePasteField, useRevealOnInteraction, validatePayload, visuallyHiddenStyle };
2289
2585
 
2290
2586
  //# sourceMappingURL=index.js.map