react-smart-copy 1.2.0 → 1.4.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.d.cts CHANGED
@@ -1,5 +1,97 @@
1
1
 
2
- import { ButtonHTMLAttributes, CSSProperties, ClipboardEventHandler, FocusEventHandler, HTMLAttributes, PointerEventHandler, ReactNode, RefCallback } from "react";
2
+ import { ButtonHTMLAttributes, CSSProperties, ClipboardEventHandler, DragEventHandler, FocusEventHandler, HTMLAttributes, PointerEventHandler, ReactNode, RefCallback } from "react";
3
+ //#region src/core/paste-reader.d.ts
4
+ /** Friendly names for the common cases. */
5
+ type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';
6
+ /**
7
+ * What a paste may contain, in any order: a shorthand, an exact MIME type
8
+ * (`'image/png'`) or a wildcard (`'image/*'`, `'*\/*'`).
9
+ * `image/svg+xml` is only accepted when listed exactly (it is scriptable XML).
10
+ */
11
+ type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;
12
+ interface PasteLimits {
13
+ /**
14
+ * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as
15
+ * they would be encoded, matching `Blob.size`, so every paste path counts the same way.
16
+ * Default 32 MiB.
17
+ */
18
+ readonly maxBytes?: number;
19
+ /** Max number of accepted items (types + files). Default 32. */
20
+ readonly maxItems?: number;
21
+ }
22
+ interface PasteReadOptions extends PasteLimits {
23
+ /** Default `['text']` (plain text only): the safest choice. */
24
+ readonly accept?: readonly PasteAccept[];
25
+ }
26
+ /** Validated, normalised options that adapters receive. */
27
+ interface ResolvedPasteReadOptions {
28
+ /** Normalised patterns: `type/subtype`, `type/*` or `*\/*`. */
29
+ readonly accept: readonly string[];
30
+ readonly maxBytes: number;
31
+ readonly maxItems: number;
32
+ }
33
+ /** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */
34
+ type PasteSource = 'clipboard' | 'event' | 'drop';
35
+ /** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */
36
+ interface PasteItem {
37
+ readonly type: string;
38
+ readonly data: string | Blob;
39
+ }
40
+ /**
41
+ * Everything the paste produced. Treat all of it as untrusted user input:
42
+ * in particular never inject `html` into the DOM without sanitising it.
43
+ */
44
+ interface PasteResult {
45
+ readonly source: PasteSource;
46
+ /** Every accepted entry, in clipboard order. */
47
+ readonly items: readonly PasteItem[];
48
+ /** `text/plain`, when accepted and present. */
49
+ readonly text: string | null;
50
+ /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */
51
+ readonly html: string | null;
52
+ /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */
53
+ readonly images: readonly Blob[];
54
+ /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */
55
+ readonly files: readonly File[];
56
+ /**
57
+ * The entries of `files` that are also in `images`: verified image files, keeping their
58
+ * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.
59
+ */
60
+ readonly imageFiles: readonly File[];
61
+ }
62
+ /** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */
63
+ type PasteReadResult = Omit<PasteResult, 'imageFiles'>;
64
+ export declare const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[];
65
+ export declare const DEFAULT_PASTE_MAX_BYTES: number;
66
+ export declare const DEFAULT_PASTE_MAX_ITEMS = 32;
67
+ /** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
68
+ export declare function resolvePasteReadOptions(options?: PasteReadOptions): ResolvedPasteReadOptions;
69
+ /** Structural view of a `DataTransferItem`: only what is readable while dragging. */
70
+ interface DataTransferItemLike {
71
+ /** `'string'` or `'file'`. */
72
+ readonly kind: string;
73
+ readonly type: string;
74
+ }
75
+ /** Structural view of `DataTransfer` (paste and drop events). */
76
+ interface DataTransferLike {
77
+ readonly types: ArrayLike<string>;
78
+ getData(format: string): string;
79
+ readonly files?: ArrayLike<File> | null;
80
+ readonly items?: ArrayLike<DataTransferItemLike> | null;
81
+ }
82
+ /**
83
+ * Whether a drag in progress could drop anything `accept`s. Uses only what
84
+ * browsers expose before the drop (item kinds and types, never the data).
85
+ * A file whose type is not known yet (some browsers hide it while dragging)
86
+ * counts as a maybe: the drop itself is checked against `accept`.
87
+ */
88
+ export declare function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean;
89
+ /** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */
90
+ interface ClipboardItemLike {
91
+ readonly types: readonly string[];
92
+ getType(type: string): Promise<Blob>;
93
+ }
94
+ //#endregion
3
95
  //#region src/core/errors.d.ts
4
96
  /**
5
97
  * Every way a clipboard operation can fail, as a closed union.
@@ -66,8 +158,11 @@ export declare function copyFailure(type: CopyErrorType, message: string, cause?
66
158
  export declare function toCopyError(cause: unknown, operation?: ClipboardOperation): CopyError;
67
159
  /** Default English, user-facing sentence for a copy error. Replace for i18n. */
68
160
  export declare function describeCopyError(error: CopyError): string;
69
- /** Default English, user-facing sentence for a paste error. Replace for i18n. */
70
- export declare function describePasteError(error: CopyError): string;
161
+ /**
162
+ * Default English, user-facing sentence for a paste error. Pass the error
163
+ * state's `source` to word drag-and-drop failures as drops. Replace for i18n.
164
+ */
165
+ export declare function describePasteError(error: CopyError, source?: PasteSource): string;
71
166
  //#endregion
72
167
  //#region src/core/machine-shared.d.ts
73
168
  /**
@@ -262,6 +357,11 @@ export type CopyStatus = CopyState['status'];
262
357
  * so its work was aborted. Nothing to report to the user.
263
358
  */
264
359
  export type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';
360
+ /**
361
+ * Why an in-flight copy was cancelled: `reset` (`reset()` was called) or
362
+ * `disconnect` (its host disconnected, e.g. the React component unmounted).
363
+ */
364
+ export type CopyCancelReason = 'reset' | 'disconnect';
265
365
  /** What `copy()`/`retry()` resolve to. They never reject. */
266
366
  export type CopyOutcome = {
267
367
  readonly status: 'copied';
@@ -290,6 +390,18 @@ export interface CopyMachineOptions {
290
390
  readonly coordinator?: CopyCoordinator | null;
291
391
  readonly onCopy?: (payload: CopyPayload) => void;
292
392
  readonly onError?: (error: CopyError, payload: CopyPayload | null) => void;
393
+ /**
394
+ * `reset()` moved the machine back to `idle` from any other state. Not
395
+ * called for the automatic return after `resetAfterMs`, for a `<CopyGroup>`
396
+ * handing "Copied" to another member, or when already `idle`.
397
+ */
398
+ readonly onReset?: () => void;
399
+ /**
400
+ * A copy in flight was cancelled before it settled: its `signal` aborted
401
+ * and its result will not reach state or `onCopy` / `onError`. Fires
402
+ * before `onReset` when `reset()` cancels a copy.
403
+ */
404
+ readonly onCancel?: (reason: CopyCancelReason) => void;
293
405
  /** Clock injection for tests and deterministic environments. */
294
406
  readonly now?: () => number;
295
407
  }
@@ -316,73 +428,6 @@ export declare function canRetryState(state: CopyState, maxRetries?: number): bo
316
428
  /** Framework-agnostic copy state machine. */
317
429
  export declare function createCopyMachine(options?: CopyMachineOptionsSource): CopyMachine;
318
430
  //#endregion
319
- //#region src/core/paste-reader.d.ts
320
- /** Friendly names for the common cases. */
321
- type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';
322
- /**
323
- * What a paste may contain, in any order: a shorthand, an exact MIME type
324
- * (`'image/png'`) or a wildcard (`'image/*'`, `'*\/*'`).
325
- * `image/svg+xml` is only accepted when listed exactly (it is scriptable XML).
326
- */
327
- type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;
328
- interface PasteLimits {
329
- /** Total size cap across all accepted items. Strings count UTF-16 code units. Default 32 MiB. */
330
- readonly maxBytes?: number;
331
- /** Max number of accepted items (types + files). Default 32. */
332
- readonly maxItems?: number;
333
- }
334
- interface PasteReadOptions extends PasteLimits {
335
- /** Default `['text']` (plain text only): the safest choice. */
336
- readonly accept?: readonly PasteAccept[];
337
- }
338
- /** Validated, normalised options that adapters receive. */
339
- interface ResolvedPasteReadOptions {
340
- /** Normalised patterns: `type/subtype`, `type/*` or `*\/*`. */
341
- readonly accept: readonly string[];
342
- readonly maxBytes: number;
343
- readonly maxItems: number;
344
- }
345
- /** Where the content came from. */
346
- type PasteSource = 'clipboard' | 'event';
347
- /** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */
348
- interface PasteItem {
349
- readonly type: string;
350
- readonly data: string | Blob;
351
- }
352
- /**
353
- * Everything the paste produced. Treat all of it as untrusted user input:
354
- * in particular never inject `html` into the DOM without sanitising it.
355
- */
356
- interface PasteResult {
357
- readonly source: PasteSource;
358
- /** Every accepted entry, in clipboard order. */
359
- readonly items: readonly PasteItem[];
360
- /** `text/plain`, when accepted and present. */
361
- readonly text: string | null;
362
- /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */
363
- readonly html: string | null;
364
- /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */
365
- readonly images: readonly Blob[];
366
- /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */
367
- readonly files: readonly File[];
368
- }
369
- export declare const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[];
370
- export declare const DEFAULT_PASTE_MAX_BYTES: number;
371
- export declare const DEFAULT_PASTE_MAX_ITEMS = 32;
372
- /** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
373
- export declare function resolvePasteReadOptions(options?: PasteReadOptions): ResolvedPasteReadOptions;
374
- /** Structural view of `DataTransfer` (paste events). */
375
- interface DataTransferLike {
376
- readonly types: ArrayLike<string>;
377
- getData(format: string): string;
378
- readonly files?: ArrayLike<File> | null;
379
- }
380
- /** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */
381
- interface ClipboardItemLike {
382
- readonly types: readonly string[];
383
- getType(type: string): Promise<Blob>;
384
- }
385
- //#endregion
386
431
  //#region src/core/paste-adapter.d.ts
387
432
  /** Minimal structural view of `navigator.clipboard` for reading. */
388
433
  interface PasteClipboardLike {
@@ -404,7 +449,7 @@ interface PasteEnvironment {
404
449
  * unmounts; honour it to stop decoding early.
405
450
  */
406
451
  interface PasteAdapter {
407
- read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteResult>;
452
+ read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteReadResult>;
408
453
  }
409
454
  interface BrowserPasteAdapterOptions {
410
455
  /** Defaults to `window`, read lazily at paste time (SSR-safe). */
@@ -441,7 +486,13 @@ export type PasteStatus = PasteState['status'];
441
486
  * finished, so its work was aborted. Nothing to report to the user.
442
487
  */
443
488
  export type PasteIgnoredReason = 'in-flight' | 'no-accepted-content' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';
444
- /** What `paste()` / `pasteEvent()` / `retry()` resolve to. They never reject. */
489
+ /**
490
+ * Why an in-flight read was cancelled: `reset` (`reset()` was called),
491
+ * `disconnect` (its host disconnected, e.g. the React component unmounted) or
492
+ * `superseded` (a paste or drop event arrived while a read was pending).
493
+ */
494
+ export type PasteCancelReason = 'reset' | 'disconnect' | 'superseded';
495
+ /** What `paste()` / `pasteEvent()` / `dropEvent()` / `retry()` resolve to. They never reject. */
445
496
  export type PasteOutcome = {
446
497
  readonly status: 'read';
447
498
  readonly result: PasteResult;
@@ -457,14 +508,20 @@ export interface PasteEventLike {
457
508
  readonly clipboardData: DataTransferLike | null | undefined;
458
509
  preventDefault(): void;
459
510
  }
511
+ /** Structural view of a DOM / React `drop` event. */
512
+ export interface PasteDropEventLike {
513
+ readonly dataTransfer: DataTransferLike | null | undefined;
514
+ preventDefault(): void;
515
+ }
460
516
  export interface PasteMachineOptions extends PasteReadOptions {
461
517
  /** Defaults to the browser Clipboard API adapter. */
462
518
  readonly adapter?: PasteAdapter;
463
519
  /** Return from `read` to `idle` after this many ms. `false` / `Infinity` / omitted = keep the result. */
464
520
  readonly resetAfterMs?: number | false;
465
521
  /**
466
- * Paste events only: call `event.preventDefault()` when the event carried
467
- * accepted content, so the browser doesn't also insert it. Default `true`.
522
+ * Paste events: call `event.preventDefault()` when the event carried accepted
523
+ * content, so the browser doesn't also insert it. Drop events: always call it,
524
+ * so the browser doesn't open the dropped file. Default `true`.
468
525
  */
469
526
  readonly preventDefault?: boolean;
470
527
  /**
@@ -474,6 +531,17 @@ export interface PasteMachineOptions extends PasteReadOptions {
474
531
  readonly maxRetries?: number;
475
532
  readonly onPaste?: (result: PasteResult) => void;
476
533
  readonly onError?: (error: CopyError) => void;
534
+ /**
535
+ * `reset()` moved the machine back to `idle` from any other state. Not
536
+ * called for the automatic return after `resetAfterMs`, or when already `idle`.
537
+ */
538
+ readonly onReset?: () => void;
539
+ /**
540
+ * A read in flight was cancelled before it settled: its `signal` aborted
541
+ * and its result will not reach state or `onPaste` / `onError`. Fires
542
+ * before `onReset` when `reset()` cancels a read.
543
+ */
544
+ readonly onCancel?: (reason: PasteCancelReason) => void;
477
545
  /** Clock injection for tests and deterministic environments. */
478
546
  readonly now?: () => number;
479
547
  }
@@ -493,6 +561,13 @@ export interface PasteMachine {
493
561
  * accepted content are ignored and left untouched for the browser.
494
562
  */
495
563
  readonly pasteEvent: (event: PasteEventLike) => Promise<PasteOutcome>;
564
+ /**
565
+ * Handles a drag-and-drop `drop` event exactly like a paste event: same
566
+ * `accept`, limits and image checks, `result.source === 'drop'`. Always calls
567
+ * `event.preventDefault()` (unless `preventDefault: false`), so a rejected
568
+ * file is not opened by the browser in place of the page.
569
+ */
570
+ readonly dropEvent: (event: PasteDropEventLike) => Promise<PasteOutcome>;
496
571
  /**
497
572
  * Re-reads the clipboard after a retryable failure (e.g. permission denied,
498
573
  * page not focused), up to `maxRetries`. Call it from a user gesture.
@@ -698,6 +773,12 @@ interface UsePasteOptions extends PasteMachineOptions {
698
773
  interface PasteTargetProps<T extends Element> {
699
774
  readonly onPaste: ClipboardEventHandler<T>;
700
775
  }
776
+ interface PasteDropTargetProps<T extends Element> {
777
+ readonly onDragEnter: DragEventHandler<T>;
778
+ readonly onDragOver: DragEventHandler<T>;
779
+ readonly onDragLeave: DragEventHandler<T>;
780
+ readonly onDrop: DragEventHandler<T>;
781
+ }
701
782
  interface UsePasteResult<T extends Element = HTMLElement> {
702
783
  /** Full discriminated state; narrow on `state.status`. */
703
784
  readonly state: PasteState;
@@ -711,17 +792,28 @@ interface UsePasteResult<T extends Element = HTMLElement> {
711
792
  readonly paste: PasteMachine['paste'];
712
793
  /** Stable identity. Handles a paste event you received yourself. Never rejects. */
713
794
  readonly pasteEvent: PasteMachine['pasteEvent'];
795
+ /** Stable identity. Handles a drop event you received yourself. Never rejects. */
796
+ readonly dropEvent: PasteMachine['dropEvent'];
714
797
  /** Stable identity. Re-reads the clipboard after a retryable failure, up to `maxRetries`. */
715
798
  readonly retry: PasteMachine['retry'];
716
799
  /** Stable identity. Back to `idle`, discarding and aborting any in-flight read. */
717
800
  readonly reset: PasteMachine['reset'];
718
801
  /** Spread onto an element (drop zone, textarea, editor) to accept Ctrl/⌘+V there. */
719
802
  readonly targetProps: PasteTargetProps<T>;
803
+ /**
804
+ * Spread onto one element to accept drag-and-drop there, through the same
805
+ * `accept` and limits as paste. Only drags carrying accepted types show the
806
+ * drop cursor. Separate from `targetProps` so text fields keep native drops.
807
+ */
808
+ readonly dropTargetProps: PasteDropTargetProps<T>;
809
+ /** An accepted drag is over the `dropTargetProps` element. Style the drop zone with it. */
810
+ readonly isDragOver: boolean;
720
811
  }
721
812
  /**
722
813
  * Paste state machine bound to a component. Supports a "Paste" button
723
- * (`paste()`, may prompt for permission) and keyboard paste (`targetProps`
724
- * or `listenOnDocument`, no prompt). Options may change on every render.
814
+ * (`paste()`, may prompt for permission), keyboard paste (`targetProps` or
815
+ * `listenOnDocument`, no prompt) and drag-and-drop (`dropTargetProps`).
816
+ * Options may change on every render.
725
817
  *
726
818
  * Everything in the result is untrusted user input.
727
819
  */
@@ -771,8 +863,13 @@ export declare function usePasteDisplayStatus(status: PasteStatus, options?: Use
771
863
  interface PasteFieldMessages {
772
864
  /** Announced to screen readers on successful paste. */
773
865
  readonly pasted: string | ((result: PasteResult) => string);
774
- /** Announced on failure. Defaults to {@link describePasteError}. */
775
- readonly error: (error: CopyError) => string;
866
+ /**
867
+ * Announced to screen readers when content is dropped onto the zone. When
868
+ * you override `pasted` but not this, your `pasted` message is used for drops too.
869
+ */
870
+ readonly dropped?: string | ((result: PasteResult) => string);
871
+ /** Announced on failure. Defaults to {@link describePasteError}. `source` tells drops from pastes. */
872
+ readonly error: (error: CopyError, source?: PasteSource) => string;
776
873
  /**
777
874
  * Accessible name of the trigger button. Receives the field's `label` prop.
778
875
  * The returned string must not be empty.
@@ -817,6 +914,11 @@ interface PasteFieldStatusProps extends HTMLAttributes<HTMLSpanElement> {
817
914
  interface PasteFieldZoneProps extends HTMLAttributes<HTMLDivElement> {
818
915
  /** When true, the zone is always focusable (tabIndex=0). Default true. */
819
916
  readonly focusable?: boolean;
917
+ /**
918
+ * Accept drag-and-drop, through the same `accept` and limits as paste.
919
+ * `data-drag-over` is present while an accepted drag is over the zone. Default true.
920
+ */
921
+ readonly droppable?: boolean;
820
922
  }
821
923
  interface PasteFieldTriggerRenderProps {
822
924
  /** The real state. Use for logic. */
@@ -877,5 +979,5 @@ export declare const PasteField: {
877
979
  readonly Preview: import("react").ForwardRefExoticComponent<PasteFieldPreviewProps & import("react").RefAttributes<HTMLDivElement>>;
878
980
  };
879
981
  //#endregion
880
- export type { BrowserPasteAdapterOptions, ClipboardItemLike, CopyFieldContextValue, CopyFieldLabelProps, CopyFieldMessages, CopyFieldRootProps, CopyFieldTriggerProps, CopyFieldTriggerRenderProps, CopyFieldValueProps, CopyGroupProps, DataTransferLike, LiveRegionProps, OperationContext, PasteAccept, PasteAcceptShorthand, PasteAdapter, PasteClipboardLike, PasteEnvironment, PasteFieldContextValue, PasteFieldLabelProps, PasteFieldMessages, PasteFieldPreviewProps, PasteFieldPreviewRenderProps, PasteFieldRootProps, PasteFieldStatusProps, PasteFieldTriggerProps, PasteFieldTriggerRenderProps, PasteFieldZoneProps, PasteItem, PasteLimits, PasteReadOptions, PasteResult, PasteSource, PasteTargetProps, ResolvedPasteReadOptions, RevealReason, RevealTargetProps, UseCopyOptions, UseCopyResult, UseDisplayStatusOptions, UsePasteDisplayStatusOptions, UsePasteOptions, UsePasteResult, UseRevealOnInteractionOptions, UseRevealOnInteractionResult };
982
+ export type { BrowserPasteAdapterOptions, ClipboardItemLike, CopyFieldContextValue, CopyFieldLabelProps, CopyFieldMessages, CopyFieldRootProps, CopyFieldTriggerProps, CopyFieldTriggerRenderProps, CopyFieldValueProps, CopyGroupProps, DataTransferItemLike, DataTransferLike, LiveRegionProps, OperationContext, PasteAccept, PasteAcceptShorthand, PasteAdapter, PasteClipboardLike, PasteDropTargetProps, PasteEnvironment, PasteFieldContextValue, PasteFieldLabelProps, PasteFieldMessages, PasteFieldPreviewProps, PasteFieldPreviewRenderProps, PasteFieldRootProps, PasteFieldStatusProps, PasteFieldTriggerProps, PasteFieldTriggerRenderProps, PasteFieldZoneProps, PasteItem, PasteLimits, PasteReadOptions, PasteReadResult, PasteResult, PasteSource, PasteTargetProps, ResolvedPasteReadOptions, RevealReason, RevealTargetProps, UseCopyOptions, UseCopyResult, UseDisplayStatusOptions, UsePasteDisplayStatusOptions, UsePasteOptions, UsePasteResult, UseRevealOnInteractionOptions, UseRevealOnInteractionResult };
881
983
  //# sourceMappingURL=index.d.cts.map