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/core.d.cts CHANGED
@@ -71,7 +71,7 @@ interface DataTransferItemLike {
71
71
  readonly type: string;
72
72
  }
73
73
  /** Structural view of `DataTransfer` (paste and drop events). */
74
- interface DataTransferLike {
74
+ export interface DataTransferLike {
75
75
  readonly types: ArrayLike<string>;
76
76
  getData(format: string): string;
77
77
  readonly files?: ArrayLike<File> | null;
@@ -559,6 +559,131 @@ export interface CopyInterceptorOptions extends CopyInterceptOptions {
559
559
  */
560
560
  export declare function registerCopyInterceptor(root: Element, options: CopyInterceptorOptions | (() => CopyInterceptorOptions)): () => void;
561
561
  //#endregion
562
+ //#region src/core/drag-copy.d.ts
563
+ /**
564
+ * The `effectAllowed` a drag operation advertises. Controls which cursor the
565
+ * browser shows and which `dropEffect` the drop target may request.
566
+ *
567
+ * - `'copy'` (default): dragging produces a copy of the data.
568
+ * - `'move'`: dragging removes the source after a drop (the app must do this).
569
+ * - `'link'`: dragging creates a link/reference.
570
+ * - `'copyMove'` / `'copyLink'` / `'linkMove'` / `'all'`: combinations.
571
+ * - `'none'`: the drag is not droppable anywhere.
572
+ * - `'uninitialized'`: browser default (same as `'all'` in most cases).
573
+ */
574
+ export type DragEffectAllowed = 'copy' | 'move' | 'link' | 'copyMove' | 'copyLink' | 'linkMove' | 'all' | 'none' | 'uninitialized';
575
+ /** What is put into `DataTransfer` when a drag starts. */
576
+ export interface DragCopyItem {
577
+ readonly mimeType: string;
578
+ readonly data: string;
579
+ }
580
+ /**
581
+ * A multi-format drag payload — strings only (DataTransfer only accepts strings).
582
+ * Mirrors `SyncCopyPayload` from copy-interceptor but scoped to drag.
583
+ */
584
+ export type DragCopyPayload = TextPayload | HtmlPayload | JsonPayload | DragMultiPayload;
585
+ export interface DragMultiPayload {
586
+ readonly kind: 'multi';
587
+ readonly items: readonly DragCopyItem[];
588
+ }
589
+ /**
590
+ * What the source getter returns:
591
+ * - a string: written as `text/plain`.
592
+ * - a `DragCopyPayload`: written according to its `kind`.
593
+ * - `false`: cancels the drag (`preventDefault()` on `dragstart`).
594
+ * - `null` / `undefined`: leaves the browser's default drag data untouched.
595
+ */
596
+ export type DragCopyDecision = string | DragCopyPayload | false | null | undefined;
597
+ /** Called once when the user begins dragging the element. Must be synchronous. */
598
+ export type DragCopySource = (event: DragStartEventLike) => DragCopyDecision;
599
+ /** Structural `DragEvent`: DOM and React drag events both satisfy it. */
600
+ export interface DragStartEventLike {
601
+ readonly type: string;
602
+ readonly dataTransfer: DataTransferLike$1 | null;
603
+ readonly defaultPrevented: boolean;
604
+ preventDefault(): void;
605
+ }
606
+ /** The writable face of `DataTransfer`. */
607
+ interface DataTransferLike$1 {
608
+ effectAllowed: string;
609
+ setData(format: string, data: string): void;
610
+ clearData?(format?: string): void;
611
+ }
612
+ export type DragCopyStatus =
613
+ /** No drag has started yet, or it was cancelled / never had source data. */
614
+ 'idle' |
615
+ /** The element is being dragged and data is on the DataTransfer. */
616
+ 'dragging' |
617
+ /** The drag ended (dropped or abandoned). */
618
+ 'done';
619
+ export type DragCopyPassReason =
620
+ /** Source returned `null`/`undefined`. */
621
+ 'declined' |
622
+ /** `DataTransfer` is not present on this event. */
623
+ 'no-transfer' |
624
+ /** Source returned `false`. */
625
+ 'cancelled';
626
+ export type DragCopyOutcome = {
627
+ readonly status: 'written';
628
+ readonly payload: DragCopyPayload;
629
+ } | {
630
+ readonly status: 'passed';
631
+ readonly reason: DragCopyPassReason;
632
+ } | {
633
+ readonly status: 'failed';
634
+ readonly error: CopyError;
635
+ };
636
+ export interface DragCopyState {
637
+ readonly status: DragCopyStatus;
638
+ /** The last `dragstart` outcome; `null` before the first drag. */
639
+ readonly outcome: DragCopyOutcome | null;
640
+ }
641
+ export interface DragCopyOptions {
642
+ /**
643
+ * Returns the data to put in the drag. Called synchronously on `dragstart`.
644
+ * Return a string (shorthand for `{ kind: 'text' }`), a payload object,
645
+ * `false` to cancel the drag, or `null`/`undefined` to pass through.
646
+ */
647
+ readonly source: DragCopySource;
648
+ /**
649
+ * `effectAllowed` advertised on the drag. Default `'copy'`.
650
+ * Setting `'move'` signals to drop targets that the source will be removed.
651
+ */
652
+ readonly effectAllowed?: DragEffectAllowed;
653
+ /**
654
+ * Called each time a drag starts or ends, with the latest outcome and status.
655
+ * Stable across re-renders when written as a class method or via `useRef`.
656
+ */
657
+ readonly onDrag?: (state: DragCopyState) => void;
658
+ /** Called when preparing the drag payload fails. */
659
+ readonly onError?: (error: CopyError) => void;
660
+ }
661
+ /**
662
+ * Populates a `dragstart` event's `DataTransfer` with the given payload.
663
+ * Use this from a raw `dragstart` handler or a React `onDragStart` prop.
664
+ * Returns the outcome so you can inspect what happened.
665
+ */
666
+ export declare function applyDragCopy(event: DragStartEventLike, options: DragCopyOptions): DragCopyOutcome;
667
+ export interface RegisterDragCopyResult {
668
+ /** Unsubscribes all listeners. Idempotent. */
669
+ readonly unsubscribe: () => void;
670
+ }
671
+ /**
672
+ * Attaches `dragstart` and `dragend` listeners to `element`, calling
673
+ * `applyDragCopy` on every drag start. Returns an object with an
674
+ * `unsubscribe` function.
675
+ *
676
+ * Pass an options getter so the latest options are always used without
677
+ * re-registering — safe to pass an inline object from a React render.
678
+ *
679
+ * ```ts
680
+ * const { unsubscribe } = registerDragCopy(el, () => ({
681
+ * source: () => `${title}\n${url}`,
682
+ * }));
683
+ * ```
684
+ */
685
+ export declare function registerDragCopy(element: HTMLElement, options: DragCopyOptions | (() => DragCopyOptions)): RegisterDragCopyResult;
686
+ //#endregion
562
687
  //#region src/core/paste-adapter.d.ts
563
688
  /** Minimal structural view of `navigator.clipboard` for reading. */
564
689
  interface PasteClipboardLike {
@@ -721,5 +846,5 @@ export declare function canRetryPasteState(state: PasteState, maxRetries?: numbe
721
846
  /** Framework-agnostic paste state machine. */
722
847
  export declare function createPasteMachine(options?: PasteMachineOptionsSource): PasteMachine;
723
848
  //#endregion
724
- export type { BrowserPasteAdapterOptions, ClipboardItemLike, DataTransferItemLike, DataTransferLike, OperationContext, PasteAccept, PasteAcceptShorthand, PasteAdapter, PasteClipboardLike, PasteEnvironment, PasteItem, PasteLimits, PasteReadOptions, PasteReadResult, PasteResult, PasteSource, ResolvedPasteReadOptions };
849
+ export type { BrowserPasteAdapterOptions, ClipboardItemLike, DataTransferItemLike, OperationContext, PasteAccept, PasteAcceptShorthand, PasteAdapter, PasteClipboardLike, PasteEnvironment, PasteItem, PasteLimits, PasteReadOptions, PasteReadResult, PasteResult, PasteSource, ResolvedPasteReadOptions };
725
850
  //# sourceMappingURL=core.d.cts.map
package/dist/core.d.ts CHANGED
@@ -71,7 +71,7 @@ interface DataTransferItemLike {
71
71
  readonly type: string;
72
72
  }
73
73
  /** Structural view of `DataTransfer` (paste and drop events). */
74
- interface DataTransferLike {
74
+ export interface DataTransferLike {
75
75
  readonly types: ArrayLike<string>;
76
76
  getData(format: string): string;
77
77
  readonly files?: ArrayLike<File> | null;
@@ -559,6 +559,131 @@ export interface CopyInterceptorOptions extends CopyInterceptOptions {
559
559
  */
560
560
  export declare function registerCopyInterceptor(root: Element, options: CopyInterceptorOptions | (() => CopyInterceptorOptions)): () => void;
561
561
  //#endregion
562
+ //#region src/core/drag-copy.d.ts
563
+ /**
564
+ * The `effectAllowed` a drag operation advertises. Controls which cursor the
565
+ * browser shows and which `dropEffect` the drop target may request.
566
+ *
567
+ * - `'copy'` (default): dragging produces a copy of the data.
568
+ * - `'move'`: dragging removes the source after a drop (the app must do this).
569
+ * - `'link'`: dragging creates a link/reference.
570
+ * - `'copyMove'` / `'copyLink'` / `'linkMove'` / `'all'`: combinations.
571
+ * - `'none'`: the drag is not droppable anywhere.
572
+ * - `'uninitialized'`: browser default (same as `'all'` in most cases).
573
+ */
574
+ export type DragEffectAllowed = 'copy' | 'move' | 'link' | 'copyMove' | 'copyLink' | 'linkMove' | 'all' | 'none' | 'uninitialized';
575
+ /** What is put into `DataTransfer` when a drag starts. */
576
+ export interface DragCopyItem {
577
+ readonly mimeType: string;
578
+ readonly data: string;
579
+ }
580
+ /**
581
+ * A multi-format drag payload — strings only (DataTransfer only accepts strings).
582
+ * Mirrors `SyncCopyPayload` from copy-interceptor but scoped to drag.
583
+ */
584
+ export type DragCopyPayload = TextPayload | HtmlPayload | JsonPayload | DragMultiPayload;
585
+ export interface DragMultiPayload {
586
+ readonly kind: 'multi';
587
+ readonly items: readonly DragCopyItem[];
588
+ }
589
+ /**
590
+ * What the source getter returns:
591
+ * - a string: written as `text/plain`.
592
+ * - a `DragCopyPayload`: written according to its `kind`.
593
+ * - `false`: cancels the drag (`preventDefault()` on `dragstart`).
594
+ * - `null` / `undefined`: leaves the browser's default drag data untouched.
595
+ */
596
+ export type DragCopyDecision = string | DragCopyPayload | false | null | undefined;
597
+ /** Called once when the user begins dragging the element. Must be synchronous. */
598
+ export type DragCopySource = (event: DragStartEventLike) => DragCopyDecision;
599
+ /** Structural `DragEvent`: DOM and React drag events both satisfy it. */
600
+ export interface DragStartEventLike {
601
+ readonly type: string;
602
+ readonly dataTransfer: DataTransferLike$1 | null;
603
+ readonly defaultPrevented: boolean;
604
+ preventDefault(): void;
605
+ }
606
+ /** The writable face of `DataTransfer`. */
607
+ interface DataTransferLike$1 {
608
+ effectAllowed: string;
609
+ setData(format: string, data: string): void;
610
+ clearData?(format?: string): void;
611
+ }
612
+ export type DragCopyStatus =
613
+ /** No drag has started yet, or it was cancelled / never had source data. */
614
+ 'idle' |
615
+ /** The element is being dragged and data is on the DataTransfer. */
616
+ 'dragging' |
617
+ /** The drag ended (dropped or abandoned). */
618
+ 'done';
619
+ export type DragCopyPassReason =
620
+ /** Source returned `null`/`undefined`. */
621
+ 'declined' |
622
+ /** `DataTransfer` is not present on this event. */
623
+ 'no-transfer' |
624
+ /** Source returned `false`. */
625
+ 'cancelled';
626
+ export type DragCopyOutcome = {
627
+ readonly status: 'written';
628
+ readonly payload: DragCopyPayload;
629
+ } | {
630
+ readonly status: 'passed';
631
+ readonly reason: DragCopyPassReason;
632
+ } | {
633
+ readonly status: 'failed';
634
+ readonly error: CopyError;
635
+ };
636
+ export interface DragCopyState {
637
+ readonly status: DragCopyStatus;
638
+ /** The last `dragstart` outcome; `null` before the first drag. */
639
+ readonly outcome: DragCopyOutcome | null;
640
+ }
641
+ export interface DragCopyOptions {
642
+ /**
643
+ * Returns the data to put in the drag. Called synchronously on `dragstart`.
644
+ * Return a string (shorthand for `{ kind: 'text' }`), a payload object,
645
+ * `false` to cancel the drag, or `null`/`undefined` to pass through.
646
+ */
647
+ readonly source: DragCopySource;
648
+ /**
649
+ * `effectAllowed` advertised on the drag. Default `'copy'`.
650
+ * Setting `'move'` signals to drop targets that the source will be removed.
651
+ */
652
+ readonly effectAllowed?: DragEffectAllowed;
653
+ /**
654
+ * Called each time a drag starts or ends, with the latest outcome and status.
655
+ * Stable across re-renders when written as a class method or via `useRef`.
656
+ */
657
+ readonly onDrag?: (state: DragCopyState) => void;
658
+ /** Called when preparing the drag payload fails. */
659
+ readonly onError?: (error: CopyError) => void;
660
+ }
661
+ /**
662
+ * Populates a `dragstart` event's `DataTransfer` with the given payload.
663
+ * Use this from a raw `dragstart` handler or a React `onDragStart` prop.
664
+ * Returns the outcome so you can inspect what happened.
665
+ */
666
+ export declare function applyDragCopy(event: DragStartEventLike, options: DragCopyOptions): DragCopyOutcome;
667
+ export interface RegisterDragCopyResult {
668
+ /** Unsubscribes all listeners. Idempotent. */
669
+ readonly unsubscribe: () => void;
670
+ }
671
+ /**
672
+ * Attaches `dragstart` and `dragend` listeners to `element`, calling
673
+ * `applyDragCopy` on every drag start. Returns an object with an
674
+ * `unsubscribe` function.
675
+ *
676
+ * Pass an options getter so the latest options are always used without
677
+ * re-registering — safe to pass an inline object from a React render.
678
+ *
679
+ * ```ts
680
+ * const { unsubscribe } = registerDragCopy(el, () => ({
681
+ * source: () => `${title}\n${url}`,
682
+ * }));
683
+ * ```
684
+ */
685
+ export declare function registerDragCopy(element: HTMLElement, options: DragCopyOptions | (() => DragCopyOptions)): RegisterDragCopyResult;
686
+ //#endregion
562
687
  //#region src/core/paste-adapter.d.ts
563
688
  /** Minimal structural view of `navigator.clipboard` for reading. */
564
689
  interface PasteClipboardLike {
@@ -721,5 +846,5 @@ export declare function canRetryPasteState(state: PasteState, maxRetries?: numbe
721
846
  /** Framework-agnostic paste state machine. */
722
847
  export declare function createPasteMachine(options?: PasteMachineOptionsSource): PasteMachine;
723
848
  //#endregion
724
- export type { BrowserPasteAdapterOptions, ClipboardItemLike, DataTransferItemLike, DataTransferLike, OperationContext, PasteAccept, PasteAcceptShorthand, PasteAdapter, PasteClipboardLike, PasteEnvironment, PasteItem, PasteLimits, PasteReadOptions, PasteReadResult, PasteResult, PasteSource, ResolvedPasteReadOptions };
849
+ export type { BrowserPasteAdapterOptions, ClipboardItemLike, DataTransferItemLike, OperationContext, PasteAccept, PasteAcceptShorthand, PasteAdapter, PasteClipboardLike, PasteEnvironment, PasteItem, PasteLimits, PasteReadOptions, PasteReadResult, PasteResult, PasteSource, ResolvedPasteReadOptions };
725
850
  //# sourceMappingURL=core.d.ts.map
package/dist/core.js CHANGED
@@ -131,40 +131,40 @@ function isBlob(value) {
131
131
  function isThenable(value) {
132
132
  return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
133
133
  }
134
- const invalid$1 = (message) => createCopyError("invalid-payload", message);
134
+ const invalid$2 = (message) => createCopyError("invalid-payload", message);
135
135
  /**
136
136
  * Structural validation. Typed callers can't produce most of these states,
137
137
  * but plain-JS callers and runtime data can, so the check is always on.
138
138
  */
139
139
  function validatePayload(payload) {
140
- if (typeof payload !== "object" || payload === null) return invalid$1("Copy input must be a string or a payload object.");
140
+ if (typeof payload !== "object" || payload === null) return invalid$2("Copy input must be a string or a payload object.");
141
141
  const candidate = payload;
142
142
  switch (candidate["kind"]) {
143
- case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid$1("Text payload must be a non-empty string.");
143
+ case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid$2("Text payload must be a non-empty string.");
144
144
  case "html":
145
- if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid$1("HTML payload requires a non-empty `html` string.");
146
- return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid$1("HTML payload requires a non-empty plain-text `text` fallback.");
145
+ if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid$2("HTML payload requires a non-empty `html` string.");
146
+ return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid$2("HTML payload requires a non-empty plain-text `text` fallback.");
147
147
  case "image": {
148
148
  const source = candidate["blob"];
149
- return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid$1("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
149
+ return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid$2("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
150
150
  }
151
- case "json": return candidate["value"] === void 0 ? invalid$1("JSON payload value is undefined.") : null;
151
+ case "json": return candidate["value"] === void 0 ? invalid$2("JSON payload value is undefined.") : null;
152
152
  case "multi": {
153
153
  const items = candidate["items"];
154
- if (!Array.isArray(items) || items.length === 0) return invalid$1("Multi payload requires at least one item.");
154
+ if (!Array.isArray(items) || items.length === 0) return invalid$2("Multi payload requires at least one item.");
155
155
  const seen = /* @__PURE__ */ new Set();
156
156
  for (const item of items) {
157
157
  const entry = typeof item === "object" && item !== null ? item : {};
158
158
  const mimeType = entry["mimeType"];
159
159
  const data = entry["data"];
160
- if (typeof mimeType !== "string" || mimeType.length === 0) return invalid$1("Every multi item needs a non-empty `mimeType`.");
161
- if (seen.has(mimeType)) return invalid$1(`Duplicate MIME type "${mimeType}" in multi payload.`);
160
+ if (typeof mimeType !== "string" || mimeType.length === 0) return invalid$2("Every multi item needs a non-empty `mimeType`.");
161
+ if (seen.has(mimeType)) return invalid$2(`Duplicate MIME type "${mimeType}" in multi payload.`);
162
162
  seen.add(mimeType);
163
- if (typeof data !== "string" && !isBlob(data)) return invalid$1(`Multi item "${mimeType}" must contain a string or a Blob.`);
163
+ if (typeof data !== "string" && !isBlob(data)) return invalid$2(`Multi item "${mimeType}" must contain a string or a Blob.`);
164
164
  }
165
165
  return null;
166
166
  }
167
- default: return invalid$1(`Unknown payload kind: ${String(candidate["kind"])}.`);
167
+ default: return invalid$2(`Unknown payload kind: ${String(candidate["kind"])}.`);
168
168
  }
169
169
  }
170
170
  /** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
@@ -694,12 +694,12 @@ function readCopySelection(event) {
694
694
  const read = readSelection(event);
695
695
  return read ? read.selection : null;
696
696
  }
697
- const nonEmpty = (value) => typeof value === "string" && value.length > 0;
698
- const invalid = (message, cause) => ({
697
+ const nonEmpty$1 = (value) => typeof value === "string" && value.length > 0;
698
+ const invalid$1 = (message, cause) => ({
699
699
  ok: false,
700
700
  error: createCopyError("invalid-payload", message, cause)
701
701
  });
702
- const unsupported = (message) => ({
702
+ const unsupported$1 = (message) => ({
703
703
  ok: false,
704
704
  error: createCopyError("unsupported-format", message)
705
705
  });
@@ -713,8 +713,8 @@ function prepare(decision) {
713
713
  kind: "text",
714
714
  value: decision
715
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.");
716
+ if (typeof candidate !== "object" || candidate === null) return invalid$1("Copy transforms must return a string, a payload, false, or nothing.");
717
+ if (typeof candidate.then === "function") return invalid$1("Copy transforms must be synchronous; the clipboard closes when the event ends.");
718
718
  const payload = candidate;
719
719
  const fields = candidate;
720
720
  const ok = (entries) => ({
@@ -723,8 +723,8 @@ function prepare(decision) {
723
723
  entries
724
724
  });
725
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`.");
726
+ case "text": return nonEmpty$1(fields["value"]) ? ok([["text/plain", fields["value"]]]) : invalid$1("Text payload must be a non-empty string.");
727
+ 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`.");
728
728
  case "json": {
729
729
  const pretty = fields["pretty"];
730
730
  const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
@@ -732,23 +732,23 @@ function prepare(decision) {
732
732
  try {
733
733
  json = JSON.stringify(fields["value"], null, indent);
734
734
  } catch (cause) {
735
- return invalid("JSON payload could not be serialised (circular reference or BigInt?).", cause);
735
+ return invalid$1("JSON payload could not be serialised (circular reference or BigInt?).", cause);
736
736
  }
737
- return typeof json === "string" ? ok([["text/plain", json]]) : invalid("JSON payload serialised to nothing.");
737
+ return typeof json === "string" ? ok([["text/plain", json]]) : invalid$1("JSON payload serialised to nothing.");
738
738
  }
739
739
  case "multi": {
740
740
  const items = fields["items"];
741
- if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
741
+ if (!Array.isArray(items) || items.length === 0) return invalid$1("Multi payload requires at least one item.");
742
742
  const entries = [];
743
743
  for (const item of items) {
744
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.`);
745
+ if (!nonEmpty$1(mimeType) || entries.some(([seen]) => seen === mimeType)) return invalid$1("Every multi item needs a unique, non-empty `mimeType`.");
746
+ if (typeof data !== "string") return unsupported$1(`Multi item "${mimeType}" must be a string during a copy event.`);
747
747
  entries.push([mimeType, data]);
748
748
  }
749
749
  return ok(entries);
750
750
  }
751
- default: return unsupported(`"${String(fields["kind"])}" payloads cannot be written during a copy event; use useCopy() for images.`);
751
+ default: return unsupported$1(`"${String(fields["kind"])}" payloads cannot be written during a copy event; use useCopy() for images.`);
752
752
  }
753
753
  }
754
754
  /** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */
@@ -910,6 +910,200 @@ function registerCopyInterceptor(root, options) {
910
910
  };
911
911
  }
912
912
  //#endregion
913
+ //#region src/core/drag-copy.ts
914
+ /**
915
+ * Drag-to-copy: populate `DataTransfer` when the user starts dragging an
916
+ * element, so whatever they drop it into receives structured data — plain text,
917
+ * HTML, JSON, or multiple MIME types — instead of the browser's default
918
+ * text-extraction of the dragged DOM.
919
+ *
920
+ * No Clipboard API, no permission prompt, works in every browser that supports
921
+ * HTML5 drag-and-drop (all modern browsers and IE11+).
922
+ */
923
+ const nonEmpty = (value) => typeof value === "string" && value.length > 0;
924
+ const invalid = (message, cause) => ({
925
+ ok: false,
926
+ error: createCopyError("invalid-payload", message, cause)
927
+ });
928
+ const unsupported = (message) => ({
929
+ ok: false,
930
+ error: createCopyError("unsupported-format", message)
931
+ });
932
+ function prepareDragDecision(decision) {
933
+ const candidate = typeof decision === "string" ? {
934
+ kind: "text",
935
+ value: decision
936
+ } : decision;
937
+ if (typeof candidate !== "object" || candidate === null) return invalid("Drag source must return a string, a payload, false, or nothing.");
938
+ if (typeof candidate.then === "function") return invalid("Drag sources must be synchronous; DataTransfer closes when dragstart returns.");
939
+ const payload = candidate;
940
+ const fields = candidate;
941
+ const ok = (items) => ({
942
+ ok: true,
943
+ payload,
944
+ items
945
+ });
946
+ switch (fields["kind"]) {
947
+ case "text": return nonEmpty(fields["value"]) ? ok([{
948
+ mimeType: "text/plain",
949
+ data: fields["value"]
950
+ }]) : invalid("Text payload must be a non-empty string.");
951
+ case "html": return nonEmpty(fields["html"]) && nonEmpty(fields["text"]) ? ok([{
952
+ mimeType: "text/html",
953
+ data: fields["html"]
954
+ }, {
955
+ mimeType: "text/plain",
956
+ data: fields["text"]
957
+ }]) : invalid("HTML payload requires non-empty `html` and `text`.");
958
+ case "json": {
959
+ const pretty = fields["pretty"];
960
+ const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
961
+ let json;
962
+ try {
963
+ json = JSON.stringify(fields["value"], null, indent);
964
+ } catch (cause) {
965
+ return invalid("JSON payload could not be serialised (circular reference or BigInt?).", cause);
966
+ }
967
+ return typeof json === "string" ? ok([{
968
+ mimeType: "text/plain",
969
+ data: json
970
+ }]) : invalid("JSON payload serialised to nothing.");
971
+ }
972
+ case "multi": {
973
+ const items = fields["items"];
974
+ if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
975
+ const out = [];
976
+ for (const item of items) {
977
+ const { mimeType, data } = item ?? {};
978
+ if (!nonEmpty(mimeType) || out.some((i) => i.mimeType === mimeType)) return invalid("Every multi item needs a unique, non-empty `mimeType`.");
979
+ if (typeof data !== "string") return unsupported(`Multi item "${mimeType}" must be a string; DataTransfer does not accept Blobs.`);
980
+ out.push({
981
+ mimeType,
982
+ data
983
+ });
984
+ }
985
+ return ok(out);
986
+ }
987
+ default: return unsupported(`"${String(fields["kind"])}" payloads cannot be used for drag-copy; use useCopy() for images.`);
988
+ }
989
+ }
990
+ /**
991
+ * Populates a `dragstart` event's `DataTransfer` with the given payload.
992
+ * Use this from a raw `dragstart` handler or a React `onDragStart` prop.
993
+ * Returns the outcome so you can inspect what happened.
994
+ */
995
+ function applyDragCopy(event, options) {
996
+ if (event.defaultPrevented) return {
997
+ status: "passed",
998
+ reason: "declined"
999
+ };
1000
+ let decision;
1001
+ try {
1002
+ decision = options.source(event);
1003
+ } catch (cause) {
1004
+ return {
1005
+ status: "failed",
1006
+ error: createCopyError("invalid-payload", "The drag source threw.", cause)
1007
+ };
1008
+ }
1009
+ if (decision === null || decision === void 0) return {
1010
+ status: "passed",
1011
+ reason: "declined"
1012
+ };
1013
+ if (decision === false) {
1014
+ event.preventDefault();
1015
+ return {
1016
+ status: "passed",
1017
+ reason: "cancelled"
1018
+ };
1019
+ }
1020
+ const transfer = event.dataTransfer;
1021
+ if (!transfer) return {
1022
+ status: "passed",
1023
+ reason: "no-transfer"
1024
+ };
1025
+ const prepared = prepareDragDecision(decision);
1026
+ if (!prepared.ok) return {
1027
+ status: "failed",
1028
+ error: prepared.error
1029
+ };
1030
+ try {
1031
+ transfer.effectAllowed = options.effectAllowed ?? "copy";
1032
+ for (const { mimeType, data } of prepared.items) transfer.setData(mimeType, data);
1033
+ } catch (cause) {
1034
+ try {
1035
+ transfer.clearData?.();
1036
+ } catch {}
1037
+ return {
1038
+ status: "failed",
1039
+ error: createCopyError("unknown", "The browser rejected the DataTransfer write.", cause)
1040
+ };
1041
+ }
1042
+ return {
1043
+ status: "written",
1044
+ payload: prepared.payload
1045
+ };
1046
+ }
1047
+ /**
1048
+ * Attaches `dragstart` and `dragend` listeners to `element`, calling
1049
+ * `applyDragCopy` on every drag start. Returns an object with an
1050
+ * `unsubscribe` function.
1051
+ *
1052
+ * Pass an options getter so the latest options are always used without
1053
+ * re-registering — safe to pass an inline object from a React render.
1054
+ *
1055
+ * ```ts
1056
+ * const { unsubscribe } = registerDragCopy(el, () => ({
1057
+ * source: () => `${title}\n${url}`,
1058
+ * }));
1059
+ * ```
1060
+ */
1061
+ function registerDragCopy(element, options) {
1062
+ const read = typeof options === "function" ? options : () => options;
1063
+ let unsubscribed = false;
1064
+ let currentOutcome = null;
1065
+ function onDragStart(raw) {
1066
+ const event = raw;
1067
+ const opts = read();
1068
+ const outcome = applyDragCopy({
1069
+ type: event.type,
1070
+ dataTransfer: event.dataTransfer,
1071
+ get defaultPrevented() {
1072
+ return event.defaultPrevented;
1073
+ },
1074
+ preventDefault: () => {
1075
+ event.preventDefault();
1076
+ }
1077
+ }, opts);
1078
+ currentOutcome = outcome;
1079
+ const state = {
1080
+ status: "dragging",
1081
+ outcome
1082
+ };
1083
+ if (outcome.status === "failed") invoke(opts.onError, outcome.error);
1084
+ invoke(opts.onDrag, state);
1085
+ }
1086
+ function onDragEnd() {
1087
+ const opts = read();
1088
+ const state = {
1089
+ status: "done",
1090
+ outcome: currentOutcome
1091
+ };
1092
+ invoke(opts.onDrag, state);
1093
+ currentOutcome = null;
1094
+ }
1095
+ element.setAttribute("draggable", "true");
1096
+ element.addEventListener("dragstart", onDragStart);
1097
+ element.addEventListener("dragend", onDragEnd);
1098
+ return { unsubscribe() {
1099
+ if (unsubscribed) return;
1100
+ unsubscribed = true;
1101
+ element.removeEventListener("dragstart", onDragStart);
1102
+ element.removeEventListener("dragend", onDragEnd);
1103
+ element.removeAttribute("draggable");
1104
+ } };
1105
+ }
1106
+ //#endregion
913
1107
  //#region src/core/paste-reader.ts
914
1108
  /** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
915
1109
  function completePasteResult(result) {
@@ -1375,6 +1569,6 @@ function createPasteMachine(options = {}) {
1375
1569
  };
1376
1570
  }
1377
1571
  //#endregion
1378
- export { CopyFailure, DEFAULT_INTERCEPTED_EVENTS, DEFAULT_MAX_RETRIES, DEFAULT_PASTE_ACCEPT, DEFAULT_PASTE_MAX_BYTES, DEFAULT_PASTE_MAX_ITEMS, DEFAULT_RESET_AFTER_MS, IDLE_STATE, IMAGE_MIME_TYPE, PASTE_IDLE_STATE, SVG_MIME_TYPE, canAcceptDrag, canRetryPasteState, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, describeCopyError, describePasteError, interceptCopyEvent, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, matchesMimePattern, normalizeMimeType, normalizePayload, readCopySelection, registerCopyInterceptor, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, validatePayload };
1572
+ export { CopyFailure, DEFAULT_INTERCEPTED_EVENTS, DEFAULT_MAX_RETRIES, DEFAULT_PASTE_ACCEPT, DEFAULT_PASTE_MAX_BYTES, DEFAULT_PASTE_MAX_ITEMS, DEFAULT_RESET_AFTER_MS, IDLE_STATE, IMAGE_MIME_TYPE, PASTE_IDLE_STATE, SVG_MIME_TYPE, applyDragCopy, canAcceptDrag, canRetryPasteState, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, describeCopyError, describePasteError, interceptCopyEvent, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, matchesMimePattern, normalizeMimeType, normalizePayload, readCopySelection, registerCopyInterceptor, registerDragCopy, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, validatePayload };
1379
1573
 
1380
1574
  //# sourceMappingURL=core.js.map