react-smart-copy 1.6.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/README.md +75 -1
- package/dist/core.cjs +313 -12
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +133 -0
- package/dist/core.d.ts +133 -0
- package/dist/core.js +310 -13
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +343 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +159 -1
- package/dist/index.d.ts +159 -1
- package/dist/index.js +339 -13
- package/dist/index.js.map +1 -1
- package/package.json +9 -4
package/dist/core.d.cts
CHANGED
|
@@ -426,6 +426,139 @@ export declare function canRetryState(state: CopyState, maxRetries?: number): bo
|
|
|
426
426
|
/** Framework-agnostic copy state machine. */
|
|
427
427
|
export declare function createCopyMachine(options?: CopyMachineOptionsSource): CopyMachine;
|
|
428
428
|
//#endregion
|
|
429
|
+
//#region src/core/copy-interceptor.d.ts
|
|
430
|
+
/**
|
|
431
|
+
* Native copy interception: rewrite, redact or block what lands on the
|
|
432
|
+
* clipboard when the user copies (Ctrl/Cmd+C, context menu) or cuts inside a
|
|
433
|
+
* scope.
|
|
434
|
+
*
|
|
435
|
+
* Writes go through `event.clipboardData` synchronously, so no permission
|
|
436
|
+
* prompt, no secure-context requirement, and it works in every browser. The
|
|
437
|
+
* price is that only strings can be written, which the types enforce.
|
|
438
|
+
*
|
|
439
|
+
* Not a security boundary: users can still screenshot, use dev tools or
|
|
440
|
+
* disable script. Treat redaction as a guard against accidents.
|
|
441
|
+
*/
|
|
442
|
+
export type InterceptedCopyKind = 'copy' | 'cut';
|
|
443
|
+
export declare const DEFAULT_INTERCEPTED_EVENTS: readonly InterceptedCopyKind[];
|
|
444
|
+
/** The writable slice of `DataTransfer` during a `copy`/`cut` event. */
|
|
445
|
+
export interface ClipboardDataLike {
|
|
446
|
+
setData(format: string, data: string): void;
|
|
447
|
+
clearData?(format?: string): void;
|
|
448
|
+
}
|
|
449
|
+
/** Structural `ClipboardEvent`: DOM and React clipboard events both satisfy it. */
|
|
450
|
+
export interface CopyEventLike {
|
|
451
|
+
readonly type: string;
|
|
452
|
+
readonly target: EventTarget | null;
|
|
453
|
+
readonly clipboardData: ClipboardDataLike | null;
|
|
454
|
+
readonly defaultPrevented: boolean;
|
|
455
|
+
preventDefault(): void;
|
|
456
|
+
}
|
|
457
|
+
/** What the user selected when they copied. */
|
|
458
|
+
export interface CopySelection {
|
|
459
|
+
readonly kind: InterceptedCopyKind;
|
|
460
|
+
/** What the browser would put on the clipboard as `text/plain`. */
|
|
461
|
+
readonly text: string;
|
|
462
|
+
/** Serialised HTML of the selection; `null` inside text inputs. */
|
|
463
|
+
readonly html: string | null;
|
|
464
|
+
/** A detached clone of the selected nodes, safe to mutate; `null` inside text inputs. */
|
|
465
|
+
readonly fragment: DocumentFragment | null;
|
|
466
|
+
/** The `<input>`/`<textarea>` the selection lives in, if any. */
|
|
467
|
+
readonly field: HTMLInputElement | HTMLTextAreaElement | null;
|
|
468
|
+
/** Whether a `cut` would remove the selection (form field or contenteditable). */
|
|
469
|
+
readonly editable: boolean;
|
|
470
|
+
}
|
|
471
|
+
/** A multi payload whose items are all strings; the only kind `setData` accepts. */
|
|
472
|
+
export interface SyncMultiPayload {
|
|
473
|
+
readonly kind: 'multi';
|
|
474
|
+
readonly items: readonly {
|
|
475
|
+
readonly mimeType: string;
|
|
476
|
+
readonly data: string;
|
|
477
|
+
}[];
|
|
478
|
+
}
|
|
479
|
+
/** Payloads writable synchronously during a copy event. Images need the async clipboard. */
|
|
480
|
+
export type SyncCopyPayload = TextPayload | HtmlPayload | JsonPayload | SyncMultiPayload;
|
|
481
|
+
/**
|
|
482
|
+
* What a transform returns:
|
|
483
|
+
* - a string or payload: write that instead of the selection
|
|
484
|
+
* - `false`: block the copy (nothing reaches the clipboard; a cut deletes nothing)
|
|
485
|
+
* - `null` / `undefined`: leave the browser's default copy untouched
|
|
486
|
+
*
|
|
487
|
+
* Must be synchronous: the clipboard closes when the event handler returns.
|
|
488
|
+
*/
|
|
489
|
+
export type CopyInterceptDecision = string | SyncCopyPayload | false | null | undefined;
|
|
490
|
+
export type CopyInterceptTransform = (selection: CopySelection) => CopyInterceptDecision;
|
|
491
|
+
/**
|
|
492
|
+
* When the transform throws or returns something unwritable:
|
|
493
|
+
* - `'block'` (default): nothing is copied. Safe for redaction.
|
|
494
|
+
* - `'native'`: the browser's default copy proceeds unmodified.
|
|
495
|
+
*/
|
|
496
|
+
export type CopyInterceptFailureMode = 'block' | 'native';
|
|
497
|
+
export interface CopyInterceptOptions {
|
|
498
|
+
readonly transform: CopyInterceptTransform;
|
|
499
|
+
readonly failureMode?: CopyInterceptFailureMode;
|
|
500
|
+
}
|
|
501
|
+
export type CopyInterceptPassReason =
|
|
502
|
+
/** Not a `copy`/`cut` event. */
|
|
503
|
+
'unsupported-event' |
|
|
504
|
+
/** Another handler already called `preventDefault()`. */
|
|
505
|
+
'already-handled' |
|
|
506
|
+
/** Nothing readable was selected. */
|
|
507
|
+
'no-selection' |
|
|
508
|
+
/** The transform returned `null`/`undefined`. */
|
|
509
|
+
'declined';
|
|
510
|
+
export type CopyInterceptOutcome = {
|
|
511
|
+
readonly status: 'passed';
|
|
512
|
+
readonly reason: CopyInterceptPassReason;
|
|
513
|
+
readonly selection: CopySelection | null;
|
|
514
|
+
} | {
|
|
515
|
+
readonly status: 'written';
|
|
516
|
+
readonly selection: CopySelection;
|
|
517
|
+
readonly payload: SyncCopyPayload;
|
|
518
|
+
/** For an editable `cut`: whether the selection was removed. Always `false` for `copy`. */
|
|
519
|
+
readonly deleted: boolean;
|
|
520
|
+
} | {
|
|
521
|
+
readonly status: 'blocked';
|
|
522
|
+
readonly selection: CopySelection;
|
|
523
|
+
} | {
|
|
524
|
+
readonly status: 'failed';
|
|
525
|
+
readonly selection: CopySelection;
|
|
526
|
+
readonly error: CopyError;
|
|
527
|
+
/** What actually happened to the copy. */
|
|
528
|
+
readonly fallback: CopyInterceptFailureMode;
|
|
529
|
+
};
|
|
530
|
+
/** Reads the selection behind a copy event, or `null` if nothing readable is selected. */
|
|
531
|
+
export declare function readCopySelection(event: CopyEventLike): CopySelection | null;
|
|
532
|
+
/**
|
|
533
|
+
* Applies a transform to one `copy`/`cut` event. Use directly from an
|
|
534
|
+
* `onCopy` handler, or let {@link registerCopyInterceptor} scope it.
|
|
535
|
+
*/
|
|
536
|
+
export declare function interceptCopyEvent(event: CopyEventLike, options: CopyInterceptOptions): CopyInterceptOutcome;
|
|
537
|
+
export interface CopyInterceptorOptions extends CopyInterceptOptions {
|
|
538
|
+
/**
|
|
539
|
+
* When one selection touches several scopes, exactly one handles it: the
|
|
540
|
+
* highest `priority`, then the innermost, then the first in the document.
|
|
541
|
+
* The winner sees the *whole* selection. Give redaction scopes a higher
|
|
542
|
+
* priority so text copied across them is always masked. Default `0`.
|
|
543
|
+
*/
|
|
544
|
+
readonly priority?: number;
|
|
545
|
+
/** Which events to intercept. Default: both `copy` and `cut`. */
|
|
546
|
+
readonly events?: readonly InterceptedCopyKind[];
|
|
547
|
+
/** Every outcome for selections inside this scope, including `passed`. */
|
|
548
|
+
readonly onIntercept?: (outcome: CopyInterceptOutcome) => void;
|
|
549
|
+
/** Called when the transform failed; the outcome's `fallback` says what happened to the copy. */
|
|
550
|
+
readonly onError?: (error: CopyError) => void;
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Intercepts native copies and cuts whose selection touches `root`. Returns
|
|
554
|
+
* an unsubscribe function. Pass a getter to always read the latest options.
|
|
555
|
+
*
|
|
556
|
+
* One listener per document serves every scope, so overlapping scopes
|
|
557
|
+
* resolve deterministically (see `priority`) regardless of registration order.
|
|
558
|
+
* Handlers that call `preventDefault()` first (e.g. a React `onCopy`) win.
|
|
559
|
+
*/
|
|
560
|
+
export declare function registerCopyInterceptor(root: Element, options: CopyInterceptorOptions | (() => CopyInterceptorOptions)): () => void;
|
|
561
|
+
//#endregion
|
|
429
562
|
//#region src/core/paste-adapter.d.ts
|
|
430
563
|
/** Minimal structural view of `navigator.clipboard` for reading. */
|
|
431
564
|
interface PasteClipboardLike {
|
package/dist/core.d.ts
CHANGED
|
@@ -426,6 +426,139 @@ export declare function canRetryState(state: CopyState, maxRetries?: number): bo
|
|
|
426
426
|
/** Framework-agnostic copy state machine. */
|
|
427
427
|
export declare function createCopyMachine(options?: CopyMachineOptionsSource): CopyMachine;
|
|
428
428
|
//#endregion
|
|
429
|
+
//#region src/core/copy-interceptor.d.ts
|
|
430
|
+
/**
|
|
431
|
+
* Native copy interception: rewrite, redact or block what lands on the
|
|
432
|
+
* clipboard when the user copies (Ctrl/Cmd+C, context menu) or cuts inside a
|
|
433
|
+
* scope.
|
|
434
|
+
*
|
|
435
|
+
* Writes go through `event.clipboardData` synchronously, so no permission
|
|
436
|
+
* prompt, no secure-context requirement, and it works in every browser. The
|
|
437
|
+
* price is that only strings can be written, which the types enforce.
|
|
438
|
+
*
|
|
439
|
+
* Not a security boundary: users can still screenshot, use dev tools or
|
|
440
|
+
* disable script. Treat redaction as a guard against accidents.
|
|
441
|
+
*/
|
|
442
|
+
export type InterceptedCopyKind = 'copy' | 'cut';
|
|
443
|
+
export declare const DEFAULT_INTERCEPTED_EVENTS: readonly InterceptedCopyKind[];
|
|
444
|
+
/** The writable slice of `DataTransfer` during a `copy`/`cut` event. */
|
|
445
|
+
export interface ClipboardDataLike {
|
|
446
|
+
setData(format: string, data: string): void;
|
|
447
|
+
clearData?(format?: string): void;
|
|
448
|
+
}
|
|
449
|
+
/** Structural `ClipboardEvent`: DOM and React clipboard events both satisfy it. */
|
|
450
|
+
export interface CopyEventLike {
|
|
451
|
+
readonly type: string;
|
|
452
|
+
readonly target: EventTarget | null;
|
|
453
|
+
readonly clipboardData: ClipboardDataLike | null;
|
|
454
|
+
readonly defaultPrevented: boolean;
|
|
455
|
+
preventDefault(): void;
|
|
456
|
+
}
|
|
457
|
+
/** What the user selected when they copied. */
|
|
458
|
+
export interface CopySelection {
|
|
459
|
+
readonly kind: InterceptedCopyKind;
|
|
460
|
+
/** What the browser would put on the clipboard as `text/plain`. */
|
|
461
|
+
readonly text: string;
|
|
462
|
+
/** Serialised HTML of the selection; `null` inside text inputs. */
|
|
463
|
+
readonly html: string | null;
|
|
464
|
+
/** A detached clone of the selected nodes, safe to mutate; `null` inside text inputs. */
|
|
465
|
+
readonly fragment: DocumentFragment | null;
|
|
466
|
+
/** The `<input>`/`<textarea>` the selection lives in, if any. */
|
|
467
|
+
readonly field: HTMLInputElement | HTMLTextAreaElement | null;
|
|
468
|
+
/** Whether a `cut` would remove the selection (form field or contenteditable). */
|
|
469
|
+
readonly editable: boolean;
|
|
470
|
+
}
|
|
471
|
+
/** A multi payload whose items are all strings; the only kind `setData` accepts. */
|
|
472
|
+
export interface SyncMultiPayload {
|
|
473
|
+
readonly kind: 'multi';
|
|
474
|
+
readonly items: readonly {
|
|
475
|
+
readonly mimeType: string;
|
|
476
|
+
readonly data: string;
|
|
477
|
+
}[];
|
|
478
|
+
}
|
|
479
|
+
/** Payloads writable synchronously during a copy event. Images need the async clipboard. */
|
|
480
|
+
export type SyncCopyPayload = TextPayload | HtmlPayload | JsonPayload | SyncMultiPayload;
|
|
481
|
+
/**
|
|
482
|
+
* What a transform returns:
|
|
483
|
+
* - a string or payload: write that instead of the selection
|
|
484
|
+
* - `false`: block the copy (nothing reaches the clipboard; a cut deletes nothing)
|
|
485
|
+
* - `null` / `undefined`: leave the browser's default copy untouched
|
|
486
|
+
*
|
|
487
|
+
* Must be synchronous: the clipboard closes when the event handler returns.
|
|
488
|
+
*/
|
|
489
|
+
export type CopyInterceptDecision = string | SyncCopyPayload | false | null | undefined;
|
|
490
|
+
export type CopyInterceptTransform = (selection: CopySelection) => CopyInterceptDecision;
|
|
491
|
+
/**
|
|
492
|
+
* When the transform throws or returns something unwritable:
|
|
493
|
+
* - `'block'` (default): nothing is copied. Safe for redaction.
|
|
494
|
+
* - `'native'`: the browser's default copy proceeds unmodified.
|
|
495
|
+
*/
|
|
496
|
+
export type CopyInterceptFailureMode = 'block' | 'native';
|
|
497
|
+
export interface CopyInterceptOptions {
|
|
498
|
+
readonly transform: CopyInterceptTransform;
|
|
499
|
+
readonly failureMode?: CopyInterceptFailureMode;
|
|
500
|
+
}
|
|
501
|
+
export type CopyInterceptPassReason =
|
|
502
|
+
/** Not a `copy`/`cut` event. */
|
|
503
|
+
'unsupported-event' |
|
|
504
|
+
/** Another handler already called `preventDefault()`. */
|
|
505
|
+
'already-handled' |
|
|
506
|
+
/** Nothing readable was selected. */
|
|
507
|
+
'no-selection' |
|
|
508
|
+
/** The transform returned `null`/`undefined`. */
|
|
509
|
+
'declined';
|
|
510
|
+
export type CopyInterceptOutcome = {
|
|
511
|
+
readonly status: 'passed';
|
|
512
|
+
readonly reason: CopyInterceptPassReason;
|
|
513
|
+
readonly selection: CopySelection | null;
|
|
514
|
+
} | {
|
|
515
|
+
readonly status: 'written';
|
|
516
|
+
readonly selection: CopySelection;
|
|
517
|
+
readonly payload: SyncCopyPayload;
|
|
518
|
+
/** For an editable `cut`: whether the selection was removed. Always `false` for `copy`. */
|
|
519
|
+
readonly deleted: boolean;
|
|
520
|
+
} | {
|
|
521
|
+
readonly status: 'blocked';
|
|
522
|
+
readonly selection: CopySelection;
|
|
523
|
+
} | {
|
|
524
|
+
readonly status: 'failed';
|
|
525
|
+
readonly selection: CopySelection;
|
|
526
|
+
readonly error: CopyError;
|
|
527
|
+
/** What actually happened to the copy. */
|
|
528
|
+
readonly fallback: CopyInterceptFailureMode;
|
|
529
|
+
};
|
|
530
|
+
/** Reads the selection behind a copy event, or `null` if nothing readable is selected. */
|
|
531
|
+
export declare function readCopySelection(event: CopyEventLike): CopySelection | null;
|
|
532
|
+
/**
|
|
533
|
+
* Applies a transform to one `copy`/`cut` event. Use directly from an
|
|
534
|
+
* `onCopy` handler, or let {@link registerCopyInterceptor} scope it.
|
|
535
|
+
*/
|
|
536
|
+
export declare function interceptCopyEvent(event: CopyEventLike, options: CopyInterceptOptions): CopyInterceptOutcome;
|
|
537
|
+
export interface CopyInterceptorOptions extends CopyInterceptOptions {
|
|
538
|
+
/**
|
|
539
|
+
* When one selection touches several scopes, exactly one handles it: the
|
|
540
|
+
* highest `priority`, then the innermost, then the first in the document.
|
|
541
|
+
* The winner sees the *whole* selection. Give redaction scopes a higher
|
|
542
|
+
* priority so text copied across them is always masked. Default `0`.
|
|
543
|
+
*/
|
|
544
|
+
readonly priority?: number;
|
|
545
|
+
/** Which events to intercept. Default: both `copy` and `cut`. */
|
|
546
|
+
readonly events?: readonly InterceptedCopyKind[];
|
|
547
|
+
/** Every outcome for selections inside this scope, including `passed`. */
|
|
548
|
+
readonly onIntercept?: (outcome: CopyInterceptOutcome) => void;
|
|
549
|
+
/** Called when the transform failed; the outcome's `fallback` says what happened to the copy. */
|
|
550
|
+
readonly onError?: (error: CopyError) => void;
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Intercepts native copies and cuts whose selection touches `root`. Returns
|
|
554
|
+
* an unsubscribe function. Pass a getter to always read the latest options.
|
|
555
|
+
*
|
|
556
|
+
* One listener per document serves every scope, so overlapping scopes
|
|
557
|
+
* resolve deterministically (see `priority`) regardless of registration order.
|
|
558
|
+
* Handlers that call `preventDefault()` first (e.g. a React `onCopy`) win.
|
|
559
|
+
*/
|
|
560
|
+
export declare function registerCopyInterceptor(root: Element, options: CopyInterceptorOptions | (() => CopyInterceptorOptions)): () => void;
|
|
561
|
+
//#endregion
|
|
429
562
|
//#region src/core/paste-adapter.d.ts
|
|
430
563
|
/** Minimal structural view of `navigator.clipboard` for reading. */
|
|
431
564
|
interface PasteClipboardLike {
|
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 = (message) => createCopyError("invalid-payload", message);
|
|
134
|
+
const invalid$1 = (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("Copy input must be a string or a payload object.");
|
|
140
|
+
if (typeof payload !== "object" || payload === null) return invalid$1("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("Text payload must be a non-empty string.");
|
|
143
|
+
case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid$1("Text payload must be a non-empty string.");
|
|
144
144
|
case "html":
|
|
145
|
-
if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid("HTML payload requires a non-empty `html` string.");
|
|
146
|
-
return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid("HTML payload requires a non-empty plain-text `text` fallback.");
|
|
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.");
|
|
147
147
|
case "image": {
|
|
148
148
|
const source = candidate["blob"];
|
|
149
|
-
return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
|
|
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.");
|
|
150
150
|
}
|
|
151
|
-
case "json": return candidate["value"] === void 0 ? invalid("JSON payload value is undefined.") : null;
|
|
151
|
+
case "json": return candidate["value"] === void 0 ? invalid$1("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("Multi payload requires at least one item.");
|
|
154
|
+
if (!Array.isArray(items) || items.length === 0) return invalid$1("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("Every multi item needs a non-empty `mimeType`.");
|
|
161
|
-
if (seen.has(mimeType)) return invalid(`Duplicate MIME type "${mimeType}" in multi payload.`);
|
|
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.`);
|
|
162
162
|
seen.add(mimeType);
|
|
163
|
-
if (typeof data !== "string" && !isBlob(data)) return invalid(`Multi item "${mimeType}" must contain a string or a Blob.`);
|
|
163
|
+
if (typeof data !== "string" && !isBlob(data)) return invalid$1(`Multi item "${mimeType}" must contain a string or a Blob.`);
|
|
164
164
|
}
|
|
165
165
|
return null;
|
|
166
166
|
}
|
|
167
|
-
default: return invalid(`Unknown payload kind: ${String(candidate["kind"])}.`);
|
|
167
|
+
default: return invalid$1(`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. */
|
|
@@ -609,6 +609,303 @@ function createCopyMachine(options = {}) {
|
|
|
609
609
|
};
|
|
610
610
|
}
|
|
611
611
|
//#endregion
|
|
612
|
+
//#region src/core/copy-interceptor.ts
|
|
613
|
+
const DEFAULT_INTERCEPTED_EVENTS = ["copy", "cut"];
|
|
614
|
+
function isNode(value) {
|
|
615
|
+
return typeof value === "object" && value !== null && typeof value.nodeType === "number";
|
|
616
|
+
}
|
|
617
|
+
function readTextField(target) {
|
|
618
|
+
if (!isNode(target) || target.nodeType !== 1) return null;
|
|
619
|
+
const tag = target.tagName;
|
|
620
|
+
if (tag !== "INPUT" && tag !== "TEXTAREA") return null;
|
|
621
|
+
const field = target;
|
|
622
|
+
try {
|
|
623
|
+
const { selectionStart: start, selectionEnd: end } = field;
|
|
624
|
+
return typeof start === "number" && typeof end === "number" ? {
|
|
625
|
+
field,
|
|
626
|
+
start,
|
|
627
|
+
end
|
|
628
|
+
} : null;
|
|
629
|
+
} catch {
|
|
630
|
+
return null;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
function documentOf(target) {
|
|
634
|
+
if (isNode(target)) return target.nodeType === 9 ? target : target.ownerDocument;
|
|
635
|
+
return typeof document === "undefined" ? null : document;
|
|
636
|
+
}
|
|
637
|
+
function isEditableNode(node) {
|
|
638
|
+
return (node.nodeType === 1 ? node : node.parentElement)?.isContentEditable === true;
|
|
639
|
+
}
|
|
640
|
+
function rangesOf(doc) {
|
|
641
|
+
const ranges = [];
|
|
642
|
+
const selection = doc?.getSelection();
|
|
643
|
+
if (!selection || selection.isCollapsed) return ranges;
|
|
644
|
+
for (let index = 0; index < selection.rangeCount; index += 1) ranges.push(selection.getRangeAt(index));
|
|
645
|
+
return ranges;
|
|
646
|
+
}
|
|
647
|
+
function readSelection(event) {
|
|
648
|
+
const kind = event.type === "cut" ? "cut" : "copy";
|
|
649
|
+
const fieldSelection = readTextField(event.target);
|
|
650
|
+
if (fieldSelection) {
|
|
651
|
+
const { field, start, end } = fieldSelection;
|
|
652
|
+
const text = field.value.slice(Math.min(start, end), Math.max(start, end));
|
|
653
|
+
if (text.length === 0) return null;
|
|
654
|
+
return {
|
|
655
|
+
selection: {
|
|
656
|
+
kind,
|
|
657
|
+
text,
|
|
658
|
+
html: null,
|
|
659
|
+
fragment: null,
|
|
660
|
+
field,
|
|
661
|
+
editable: !field.readOnly && !field.disabled
|
|
662
|
+
},
|
|
663
|
+
doc: field.ownerDocument
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
const doc = documentOf(event.target);
|
|
667
|
+
const ranges = rangesOf(doc);
|
|
668
|
+
const [first] = ranges;
|
|
669
|
+
if (!doc || !first) return null;
|
|
670
|
+
const text = ranges.map((range) => range.toString()).join("\n");
|
|
671
|
+
if (text.length === 0) return null;
|
|
672
|
+
const container = doc.createElement("div");
|
|
673
|
+
for (const range of ranges) container.appendChild(range.cloneContents());
|
|
674
|
+
const html = container.innerHTML;
|
|
675
|
+
const fragment = doc.createDocumentFragment();
|
|
676
|
+
while (container.firstChild) fragment.appendChild(container.firstChild);
|
|
677
|
+
return {
|
|
678
|
+
selection: {
|
|
679
|
+
kind,
|
|
680
|
+
text,
|
|
681
|
+
html,
|
|
682
|
+
fragment,
|
|
683
|
+
field: null,
|
|
684
|
+
editable: isEditableNode(first.startContainer)
|
|
685
|
+
},
|
|
686
|
+
doc
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
/** Reads the selection behind a copy event, or `null` if nothing readable is selected. */
|
|
690
|
+
function readCopySelection(event) {
|
|
691
|
+
const read = readSelection(event);
|
|
692
|
+
return read ? read.selection : null;
|
|
693
|
+
}
|
|
694
|
+
const nonEmpty = (value) => typeof value === "string" && value.length > 0;
|
|
695
|
+
const invalid = (message, cause) => ({
|
|
696
|
+
ok: false,
|
|
697
|
+
error: createCopyError("invalid-payload", message, cause)
|
|
698
|
+
});
|
|
699
|
+
const unsupported = (message) => ({
|
|
700
|
+
ok: false,
|
|
701
|
+
error: createCopyError("unsupported-format", message)
|
|
702
|
+
});
|
|
703
|
+
/**
|
|
704
|
+
* Validates a decision and turns it into `[mimeType, data]` pairs. Kept
|
|
705
|
+
* self-contained (no shared validator) so the interceptor stays small; the
|
|
706
|
+
* checks still run for plain-JS callers the types can't protect.
|
|
707
|
+
*/
|
|
708
|
+
function prepare(decision) {
|
|
709
|
+
const candidate = typeof decision === "string" ? {
|
|
710
|
+
kind: "text",
|
|
711
|
+
value: decision
|
|
712
|
+
} : decision;
|
|
713
|
+
if (typeof candidate !== "object" || candidate === null) return invalid("Copy transforms must return a string, a payload, false, or nothing.");
|
|
714
|
+
if (typeof candidate.then === "function") return invalid("Copy transforms must be synchronous; the clipboard closes when the event ends.");
|
|
715
|
+
const payload = candidate;
|
|
716
|
+
const fields = candidate;
|
|
717
|
+
const ok = (entries) => ({
|
|
718
|
+
ok: true,
|
|
719
|
+
payload,
|
|
720
|
+
entries
|
|
721
|
+
});
|
|
722
|
+
switch (fields["kind"]) {
|
|
723
|
+
case "text": return nonEmpty(fields["value"]) ? ok([["text/plain", fields["value"]]]) : invalid("Text payload must be a non-empty string.");
|
|
724
|
+
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`.");
|
|
725
|
+
case "json": {
|
|
726
|
+
const pretty = fields["pretty"];
|
|
727
|
+
const indent = pretty === true ? 2 : typeof pretty === "number" ? pretty : void 0;
|
|
728
|
+
let json;
|
|
729
|
+
try {
|
|
730
|
+
json = JSON.stringify(fields["value"], null, indent);
|
|
731
|
+
} catch (cause) {
|
|
732
|
+
return invalid("JSON payload could not be serialised (circular reference or BigInt?).", cause);
|
|
733
|
+
}
|
|
734
|
+
return typeof json === "string" ? ok([["text/plain", json]]) : invalid("JSON payload serialised to nothing.");
|
|
735
|
+
}
|
|
736
|
+
case "multi": {
|
|
737
|
+
const items = fields["items"];
|
|
738
|
+
if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
|
|
739
|
+
const entries = [];
|
|
740
|
+
for (const item of items) {
|
|
741
|
+
const { mimeType, data } = item ?? {};
|
|
742
|
+
if (!nonEmpty(mimeType) || entries.some(([seen]) => seen === mimeType)) return invalid("Every multi item needs a unique, non-empty `mimeType`.");
|
|
743
|
+
if (typeof data !== "string") return unsupported(`Multi item "${mimeType}" must be a string during a copy event.`);
|
|
744
|
+
entries.push([mimeType, data]);
|
|
745
|
+
}
|
|
746
|
+
return ok(entries);
|
|
747
|
+
}
|
|
748
|
+
default: return unsupported(`"${String(fields["kind"])}" payloads cannot be written during a copy event; use useCopy() for images.`);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
/** Deletes the selection the way a native cut would (keeps undo history, fires `input`). */
|
|
752
|
+
function deleteSelection(doc) {
|
|
753
|
+
const legacy = doc;
|
|
754
|
+
try {
|
|
755
|
+
return legacy.execCommand?.("delete") === true;
|
|
756
|
+
} catch {
|
|
757
|
+
return false;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* Applies a transform to one `copy`/`cut` event. Use directly from an
|
|
762
|
+
* `onCopy` handler, or let {@link registerCopyInterceptor} scope it.
|
|
763
|
+
*/
|
|
764
|
+
function interceptCopyEvent(event, options) {
|
|
765
|
+
if (event.type !== "copy" && event.type !== "cut") return {
|
|
766
|
+
status: "passed",
|
|
767
|
+
reason: "unsupported-event",
|
|
768
|
+
selection: null
|
|
769
|
+
};
|
|
770
|
+
if (event.defaultPrevented) return {
|
|
771
|
+
status: "passed",
|
|
772
|
+
reason: "already-handled",
|
|
773
|
+
selection: null
|
|
774
|
+
};
|
|
775
|
+
const read = readSelection(event);
|
|
776
|
+
if (!read) return {
|
|
777
|
+
status: "passed",
|
|
778
|
+
reason: "no-selection",
|
|
779
|
+
selection: null
|
|
780
|
+
};
|
|
781
|
+
const { selection, doc } = read;
|
|
782
|
+
const fail = (error) => {
|
|
783
|
+
const fallback = options.failureMode ?? "block";
|
|
784
|
+
if (fallback === "block") event.preventDefault();
|
|
785
|
+
return {
|
|
786
|
+
status: "failed",
|
|
787
|
+
selection,
|
|
788
|
+
error,
|
|
789
|
+
fallback
|
|
790
|
+
};
|
|
791
|
+
};
|
|
792
|
+
let decision;
|
|
793
|
+
try {
|
|
794
|
+
decision = options.transform(selection);
|
|
795
|
+
} catch (cause) {
|
|
796
|
+
return fail(createCopyError("invalid-payload", "The copy transform threw.", cause));
|
|
797
|
+
}
|
|
798
|
+
if (decision === null || decision === void 0) return {
|
|
799
|
+
status: "passed",
|
|
800
|
+
reason: "declined",
|
|
801
|
+
selection
|
|
802
|
+
};
|
|
803
|
+
if (decision === false) {
|
|
804
|
+
event.preventDefault();
|
|
805
|
+
return {
|
|
806
|
+
status: "blocked",
|
|
807
|
+
selection
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
const prepared = prepare(decision);
|
|
811
|
+
if (!prepared.ok) return fail(prepared.error);
|
|
812
|
+
const data = event.clipboardData;
|
|
813
|
+
if (!data) return fail(createCopyError("unsupported", "This browser exposes no clipboardData on copy events."));
|
|
814
|
+
event.preventDefault();
|
|
815
|
+
try {
|
|
816
|
+
for (const [mimeType, value] of prepared.entries) data.setData(mimeType, value);
|
|
817
|
+
} catch (cause) {
|
|
818
|
+
try {
|
|
819
|
+
data.clearData?.();
|
|
820
|
+
} catch {}
|
|
821
|
+
return {
|
|
822
|
+
status: "failed",
|
|
823
|
+
selection,
|
|
824
|
+
error: createCopyError("unknown", "The browser rejected the clipboard write.", cause),
|
|
825
|
+
fallback: "block"
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
const deleted = selection.kind === "cut" && selection.editable && deleteSelection(doc);
|
|
829
|
+
return {
|
|
830
|
+
status: "written",
|
|
831
|
+
selection,
|
|
832
|
+
payload: prepared.payload,
|
|
833
|
+
deleted
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
const registries = /* @__PURE__ */ new WeakMap();
|
|
837
|
+
function touches(root, event) {
|
|
838
|
+
const fieldSelection = readTextField(event.target);
|
|
839
|
+
if (fieldSelection) return root.contains(fieldSelection.field);
|
|
840
|
+
return rangesOf(root.ownerDocument).some((range) => range.intersectsNode(root));
|
|
841
|
+
}
|
|
842
|
+
const priorityOf = (scope) => scope.read().priority ?? 0;
|
|
843
|
+
/**
|
|
844
|
+
* Highest `priority` first; then the innermost scope; then document order;
|
|
845
|
+
* then registration order (same root). A total order, so the result never
|
|
846
|
+
* depends on effect timing.
|
|
847
|
+
*/
|
|
848
|
+
function compareScopes(a, b) {
|
|
849
|
+
const byPriority = priorityOf(b) - priorityOf(a);
|
|
850
|
+
if (byPriority !== 0) return byPriority;
|
|
851
|
+
const position = a.root.compareDocumentPosition(b.root);
|
|
852
|
+
if (position === 0) return 0;
|
|
853
|
+
if (position & 16) return 1;
|
|
854
|
+
if (position & 8) return -1;
|
|
855
|
+
return position & 4 ? -1 : 1;
|
|
856
|
+
}
|
|
857
|
+
function dispatch(registry, event) {
|
|
858
|
+
if (event.defaultPrevented) return;
|
|
859
|
+
const kind = event.type;
|
|
860
|
+
const [scope] = [...registry.scopes].filter((scope) => (scope.read().events ?? DEFAULT_INTERCEPTED_EVENTS).includes(kind) && touches(scope.root, event)).sort(compareScopes);
|
|
861
|
+
if (!scope) return;
|
|
862
|
+
const options = scope.read();
|
|
863
|
+
const outcome = interceptCopyEvent(event, options);
|
|
864
|
+
invoke(options.onIntercept, outcome);
|
|
865
|
+
if (outcome.status === "failed") invoke(options.onError, outcome.error);
|
|
866
|
+
}
|
|
867
|
+
/**
|
|
868
|
+
* Intercepts native copies and cuts whose selection touches `root`. Returns
|
|
869
|
+
* an unsubscribe function. Pass a getter to always read the latest options.
|
|
870
|
+
*
|
|
871
|
+
* One listener per document serves every scope, so overlapping scopes
|
|
872
|
+
* resolve deterministically (see `priority`) regardless of registration order.
|
|
873
|
+
* Handlers that call `preventDefault()` first (e.g. a React `onCopy`) win.
|
|
874
|
+
*/
|
|
875
|
+
function registerCopyInterceptor(root, options) {
|
|
876
|
+
const doc = root.ownerDocument;
|
|
877
|
+
let registry = registries.get(doc);
|
|
878
|
+
if (!registry) {
|
|
879
|
+
const created = {
|
|
880
|
+
scopes: /* @__PURE__ */ new Set(),
|
|
881
|
+
listener: (event) => {
|
|
882
|
+
dispatch(created, event);
|
|
883
|
+
}
|
|
884
|
+
};
|
|
885
|
+
registry = created;
|
|
886
|
+
registries.set(doc, created);
|
|
887
|
+
doc.addEventListener("copy", created.listener);
|
|
888
|
+
doc.addEventListener("cut", created.listener);
|
|
889
|
+
}
|
|
890
|
+
const scope = {
|
|
891
|
+
root,
|
|
892
|
+
read: typeof options === "function" ? options : () => options
|
|
893
|
+
};
|
|
894
|
+
registry.scopes.add(scope);
|
|
895
|
+
const active = registry;
|
|
896
|
+
let registered = true;
|
|
897
|
+
return () => {
|
|
898
|
+
if (!registered) return;
|
|
899
|
+
registered = false;
|
|
900
|
+
active.scopes.delete(scope);
|
|
901
|
+
if (active.scopes.size === 0) {
|
|
902
|
+
doc.removeEventListener("copy", active.listener);
|
|
903
|
+
doc.removeEventListener("cut", active.listener);
|
|
904
|
+
registries.delete(doc);
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
//#endregion
|
|
612
909
|
//#region src/core/paste-reader.ts
|
|
613
910
|
/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
|
|
614
911
|
function completePasteResult(result) {
|
|
@@ -1074,6 +1371,6 @@ function createPasteMachine(options = {}) {
|
|
|
1074
1371
|
};
|
|
1075
1372
|
}
|
|
1076
1373
|
//#endregion
|
|
1077
|
-
export { CopyFailure, 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, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, matchesMimePattern, normalizeMimeType, normalizePayload, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, validatePayload };
|
|
1374
|
+
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 };
|
|
1078
1375
|
|
|
1079
1376
|
//# sourceMappingURL=core.js.map
|