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