react-smart-copy 1.6.0 → 1.7.1

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 = (message) => createCopyError("invalid-payload", message);
138
+ const invalid$1 = (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("Copy input must be a string or a payload object.");
144
+ if (typeof payload !== "object" || payload === null) return invalid$1("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("Text payload must be a non-empty string.");
147
+ case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid$1("Text payload must be a non-empty string.");
148
148
  case "html":
149
- if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid("HTML payload requires a non-empty `html` string.");
150
- return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid("HTML payload requires a non-empty plain-text `text` fallback.");
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.");
151
151
  case "image": {
152
152
  const source = candidate["blob"];
153
- return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
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.");
154
154
  }
155
- case "json": return candidate["value"] === void 0 ? invalid("JSON payload value is undefined.") : null;
155
+ case "json": return candidate["value"] === void 0 ? invalid$1("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("Multi payload requires at least one item.");
158
+ if (!Array.isArray(items) || items.length === 0) return invalid$1("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("Every multi item needs a non-empty `mimeType`.");
165
- if (seen.has(mimeType)) return invalid(`Duplicate MIME type "${mimeType}" in multi payload.`);
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.`);
166
166
  seen.add(mimeType);
167
- if (typeof data !== "string" && !isBlob(data)) return invalid(`Multi item "${mimeType}" must contain a string or a Blob.`);
167
+ if (typeof data !== "string" && !isBlob(data)) return invalid$1(`Multi item "${mimeType}" must contain a string or a Blob.`);
168
168
  }
169
169
  return null;
170
170
  }
171
- default: return invalid(`Unknown payload kind: ${String(candidate["kind"])}.`);
171
+ default: return invalid$1(`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. */
@@ -613,6 +613,307 @@ function createCopyMachine(options = {}) {
613
613
  };
614
614
  }
615
615
  //#endregion
616
+ //#region src/core/copy-interceptor.ts
617
+ const DEFAULT_INTERCEPTED_EVENTS = ["copy", "cut"];
618
+ function isNode(value) {
619
+ return typeof value === "object" && value !== null && typeof value.nodeType === "number";
620
+ }
621
+ function readTextField(target) {
622
+ if (!isNode(target) || target.nodeType !== 1) return null;
623
+ const tag = target.tagName;
624
+ if (tag !== "INPUT" && tag !== "TEXTAREA") return null;
625
+ const field = target;
626
+ try {
627
+ const { selectionStart: start, selectionEnd: end } = field;
628
+ return typeof start === "number" && typeof end === "number" ? {
629
+ field,
630
+ start,
631
+ end
632
+ } : null;
633
+ } catch {
634
+ return null;
635
+ }
636
+ }
637
+ function documentOf(target) {
638
+ if (isNode(target)) return target.nodeType === 9 ? target : target.ownerDocument;
639
+ return typeof document === "undefined" ? null : document;
640
+ }
641
+ function isEditableNode(node) {
642
+ return (node.nodeType === 1 ? node : node.parentElement)?.isContentEditable === true;
643
+ }
644
+ function selectedRanges(doc) {
645
+ const selection = doc?.getSelection();
646
+ if (!selection || selection.isCollapsed) return null;
647
+ const ranges = [];
648
+ for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));
649
+ return {
650
+ selection,
651
+ ranges
652
+ };
653
+ }
654
+ function readSelection(event) {
655
+ const kind = event.type === "cut" ? "cut" : "copy";
656
+ const fieldSelection = readTextField(event.target);
657
+ if (fieldSelection) {
658
+ const { field, start, end } = fieldSelection;
659
+ const text = field.value.slice(Math.min(start, end), Math.max(start, end));
660
+ if (text.length === 0) return null;
661
+ return {
662
+ selection: {
663
+ kind,
664
+ text,
665
+ html: null,
666
+ fragment: null,
667
+ field,
668
+ editable: !field.readOnly && !field.disabled
669
+ },
670
+ doc: field.ownerDocument
671
+ };
672
+ }
673
+ const doc = documentOf(event.target);
674
+ const selected = selectedRanges(doc);
675
+ const first = selected?.ranges[0];
676
+ if (!doc || !selected || !first) return null;
677
+ const text = selected.selection.toString();
678
+ if (text.length === 0) return null;
679
+ const container = doc.createElement("div");
680
+ for (const range of selected.ranges) container.appendChild(range.cloneContents());
681
+ const html = container.innerHTML;
682
+ const fragment = doc.createDocumentFragment();
683
+ while (container.firstChild) fragment.appendChild(container.firstChild);
684
+ return {
685
+ selection: {
686
+ kind,
687
+ text,
688
+ html,
689
+ fragment,
690
+ field: null,
691
+ editable: isEditableNode(first.startContainer)
692
+ },
693
+ doc
694
+ };
695
+ }
696
+ /** Reads the selection behind a copy event, or `null` if nothing readable is selected. */
697
+ function readCopySelection(event) {
698
+ const read = readSelection(event);
699
+ return read ? read.selection : null;
700
+ }
701
+ const nonEmpty = (value) => typeof value === "string" && value.length > 0;
702
+ const invalid = (message, cause) => ({
703
+ ok: false,
704
+ error: createCopyError("invalid-payload", message, cause)
705
+ });
706
+ const unsupported = (message) => ({
707
+ ok: false,
708
+ error: createCopyError("unsupported-format", message)
709
+ });
710
+ /**
711
+ * Validates a decision and turns it into `[mimeType, data]` pairs. Kept
712
+ * self-contained (no shared validator) so the interceptor stays small; the
713
+ * checks still run for plain-JS callers the types can't protect.
714
+ */
715
+ function prepare(decision) {
716
+ const candidate = typeof decision === "string" ? {
717
+ kind: "text",
718
+ value: decision
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.");
722
+ const payload = candidate;
723
+ const fields = candidate;
724
+ const ok = (entries) => ({
725
+ ok: true,
726
+ payload,
727
+ entries
728
+ });
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`.");
732
+ case "json": {
733
+ const pretty = fields["pretty"];
734
+ const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
735
+ let json;
736
+ try {
737
+ json = JSON.stringify(fields["value"], null, indent);
738
+ } catch (cause) {
739
+ return invalid("JSON payload could not be serialised (circular reference or BigInt?).", cause);
740
+ }
741
+ return typeof json === "string" ? ok([["text/plain", json]]) : invalid("JSON payload serialised to nothing.");
742
+ }
743
+ case "multi": {
744
+ const items = fields["items"];
745
+ if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
746
+ const entries = [];
747
+ for (const item of items) {
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.`);
751
+ entries.push([mimeType, data]);
752
+ }
753
+ return ok(entries);
754
+ }
755
+ default: return unsupported(`"${String(fields["kind"])}" payloads cannot be written during a copy event; use useCopy() for images.`);
756
+ }
757
+ }
758
+ /** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */
759
+ function deleteSelection(doc) {
760
+ const legacy = doc;
761
+ try {
762
+ return legacy.execCommand?.("delete") === true;
763
+ } catch {
764
+ return false;
765
+ }
766
+ }
767
+ /**
768
+ * Applies a transform to one `copy`/`cut` event. Use directly from an
769
+ * `onCopy` handler, or let {@link registerCopyInterceptor} scope it.
770
+ */
771
+ function interceptCopyEvent(event, options) {
772
+ if (event.type !== "copy" && event.type !== "cut") return {
773
+ status: "passed",
774
+ reason: "unsupported-event",
775
+ selection: null
776
+ };
777
+ if (event.defaultPrevented) return {
778
+ status: "passed",
779
+ reason: "already-handled",
780
+ selection: null
781
+ };
782
+ const read = readSelection(event);
783
+ if (!read) return {
784
+ status: "passed",
785
+ reason: "no-selection",
786
+ selection: null
787
+ };
788
+ const { selection, doc } = read;
789
+ const fail = (error) => {
790
+ const fallback = options.failureMode ?? "block";
791
+ if (fallback === "block") event.preventDefault();
792
+ return {
793
+ status: "failed",
794
+ selection,
795
+ error,
796
+ fallback
797
+ };
798
+ };
799
+ let decision;
800
+ try {
801
+ decision = options.transform(selection);
802
+ } catch (cause) {
803
+ return fail(createCopyError("invalid-payload", "The copy transform threw.", cause));
804
+ }
805
+ if (decision === null || decision === void 0) return {
806
+ status: "passed",
807
+ reason: "declined",
808
+ selection
809
+ };
810
+ if (decision === false) {
811
+ event.preventDefault();
812
+ return {
813
+ status: "blocked",
814
+ selection
815
+ };
816
+ }
817
+ const prepared = prepare(decision);
818
+ if (!prepared.ok) return fail(prepared.error);
819
+ const data = event.clipboardData;
820
+ if (!data) return fail(createCopyError("unsupported", "This browser exposes no clipboardData on copy events."));
821
+ event.preventDefault();
822
+ try {
823
+ for (const [mimeType, value] of prepared.entries) data.setData(mimeType, value);
824
+ } catch (cause) {
825
+ try {
826
+ data.clearData?.();
827
+ } catch {}
828
+ return {
829
+ status: "failed",
830
+ selection,
831
+ error: createCopyError("unknown", "The browser rejected the clipboard write.", cause),
832
+ fallback: "block"
833
+ };
834
+ }
835
+ const deleted = selection.kind === "cut" && selection.editable && deleteSelection(doc);
836
+ return {
837
+ status: "written",
838
+ selection,
839
+ payload: prepared.payload,
840
+ deleted
841
+ };
842
+ }
843
+ const registries = /* @__PURE__ */ new WeakMap();
844
+ function touches(root, event) {
845
+ const fieldSelection = readTextField(event.target);
846
+ if (fieldSelection) return root.contains(fieldSelection.field);
847
+ const selected = selectedRanges(root.ownerDocument);
848
+ return selected !== null && selected.ranges.some((range) => range.intersectsNode(root));
849
+ }
850
+ const priorityOf = (scope) => scope.read().priority ?? 0;
851
+ /**
852
+ * Highest `priority` first; then the innermost scope; then document order;
853
+ * then registration order (same root). A total order, so the result never
854
+ * depends on effect timing.
855
+ */
856
+ function compareScopes(a, b) {
857
+ const byPriority = priorityOf(b) - priorityOf(a);
858
+ if (byPriority !== 0) return byPriority;
859
+ const position = a.root.compareDocumentPosition(b.root);
860
+ if (position === 0) return 0;
861
+ if (position & 16) return 1;
862
+ if (position & 8) return -1;
863
+ return position & 4 ? -1 : 1;
864
+ }
865
+ function dispatch(registry, event) {
866
+ if (event.defaultPrevented) return;
867
+ const kind = event.type;
868
+ const [scope] = [...registry.scopes].filter((scope) => (scope.read().events ?? DEFAULT_INTERCEPTED_EVENTS).includes(kind) && touches(scope.root, event)).sort(compareScopes);
869
+ if (!scope) return;
870
+ const options = scope.read();
871
+ const outcome = interceptCopyEvent(event, options);
872
+ invoke(options.onIntercept, outcome);
873
+ if (outcome.status === "failed") invoke(options.onError, outcome.error);
874
+ }
875
+ /**
876
+ * Intercepts native copies and cuts whose selection touches `root`. Returns
877
+ * an unsubscribe function. Pass a getter to always read the latest options.
878
+ *
879
+ * One listener per document serves every scope, so overlapping scopes
880
+ * resolve deterministically (see `priority`) regardless of registration order.
881
+ * Handlers that call `preventDefault()` first (e.g. a React `onCopy`) win.
882
+ */
883
+ function registerCopyInterceptor(root, options) {
884
+ const doc = root.ownerDocument;
885
+ let registry = registries.get(doc);
886
+ if (!registry) {
887
+ const created = {
888
+ scopes: /* @__PURE__ */ new Set(),
889
+ listener: (event) => {
890
+ dispatch(created, event);
891
+ }
892
+ };
893
+ registry = created;
894
+ registries.set(doc, created);
895
+ doc.addEventListener("copy", created.listener);
896
+ doc.addEventListener("cut", created.listener);
897
+ }
898
+ const scope = {
899
+ root,
900
+ read: typeof options === "function" ? options : () => options
901
+ };
902
+ registry.scopes.add(scope);
903
+ const active = registry;
904
+ let registered = true;
905
+ return () => {
906
+ if (!registered) return;
907
+ registered = false;
908
+ active.scopes.delete(scope);
909
+ if (active.scopes.size === 0) {
910
+ doc.removeEventListener("copy", active.listener);
911
+ doc.removeEventListener("cut", active.listener);
912
+ registries.delete(doc);
913
+ }
914
+ };
915
+ }
916
+ //#endregion
616
917
  //#region src/core/paste-reader.ts
617
918
  /** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
618
919
  function completePasteResult(result) {
@@ -1152,6 +1453,35 @@ function useCopy(options = {}) {
1152
1453
  ]);
1153
1454
  }
1154
1455
  //#endregion
1456
+ //#region src/react/useCopyInterceptor.ts
1457
+ /**
1458
+ * Rewrites, redacts or blocks native copies (Ctrl/Cmd+C, context menu) and
1459
+ * cuts whose selection touches the referenced element.
1460
+ *
1461
+ * ```tsx
1462
+ * const { ref } = useCopyInterceptor<HTMLElement>({
1463
+ * transform: ({ text }) => `${text}\n\nSource: ${location.href}`,
1464
+ * });
1465
+ * return <article ref={ref}>…</article>;
1466
+ * ```
1467
+ *
1468
+ * The transform runs synchronously inside the event and always sees the
1469
+ * latest props; changing it never re-subscribes. SSR-safe.
1470
+ */
1471
+ function useCopyInterceptor(options) {
1472
+ const optionsRef = (0, react.useRef)(options);
1473
+ useIsomorphicLayoutEffect(() => {
1474
+ optionsRef.current = options;
1475
+ });
1476
+ const [node, setNode] = (0, react.useState)(null);
1477
+ const enabled = options.enabled !== false;
1478
+ (0, react.useEffect)(() => {
1479
+ if (!node || !enabled) return void 0;
1480
+ return registerCopyInterceptor(node, () => optionsRef.current);
1481
+ }, [node, enabled]);
1482
+ return { ref: setNode };
1483
+ }
1484
+ //#endregion
1155
1485
  //#region src/react/useMediaQuery.ts
1156
1486
  const getServerSnapshot$1 = () => false;
1157
1487
  /** SSR-safe media query subscription. Server and hydration render `false`. */
@@ -1959,6 +2289,7 @@ const PasteField = {
1959
2289
  exports.CopyFailure = CopyFailure;
1960
2290
  exports.CopyField = CopyField;
1961
2291
  exports.CopyGroup = CopyGroup;
2292
+ exports.DEFAULT_INTERCEPTED_EVENTS = DEFAULT_INTERCEPTED_EVENTS;
1962
2293
  exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES;
1963
2294
  exports.DEFAULT_MIN_PENDING_MS = DEFAULT_MIN_PENDING_MS;
1964
2295
  exports.DEFAULT_PASTE_ACCEPT = DEFAULT_PASTE_ACCEPT;
@@ -1988,6 +2319,7 @@ exports.defaultCopyFieldMessages = defaultCopyFieldMessages;
1988
2319
  exports.defaultPasteFieldMessages = defaultPasteFieldMessages;
1989
2320
  exports.describeCopyError = describeCopyError;
1990
2321
  exports.describePasteError = describePasteError;
2322
+ exports.interceptCopyEvent = interceptCopyEvent;
1991
2323
  exports.isBlob = isBlob;
1992
2324
  exports.isCopyFailure = isCopyFailure;
1993
2325
  exports.isRetryableError = isRetryableError;
@@ -1995,6 +2327,8 @@ exports.isTextualMimeType = isTextualMimeType;
1995
2327
  exports.matchesMimePattern = matchesMimePattern;
1996
2328
  exports.normalizeMimeType = normalizeMimeType;
1997
2329
  exports.normalizePayload = normalizePayload;
2330
+ exports.readCopySelection = readCopySelection;
2331
+ exports.registerCopyInterceptor = registerCopyInterceptor;
1998
2332
  exports.resolveMaxRetries = resolveMaxRetries;
1999
2333
  exports.resolvePasteReadOptions = resolvePasteReadOptions;
2000
2334
  exports.serializeJson = serializeJson;
@@ -2004,6 +2338,7 @@ exports.toCopyError = toCopyError;
2004
2338
  exports.useCopy = useCopy;
2005
2339
  exports.useCopyField = useCopyField;
2006
2340
  exports.useCopyGroup = useCopyGroup;
2341
+ exports.useCopyInterceptor = useCopyInterceptor;
2007
2342
  exports.useDisplayStatus = useDisplayStatus;
2008
2343
  exports.usePaste = usePaste;
2009
2344
  exports.usePasteDisplayStatus = usePasteDisplayStatus;