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