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