react-smart-copy 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,31 +1,42 @@
1
1
 
2
- import { ButtonHTMLAttributes, CSSProperties, FocusEventHandler, HTMLAttributes, PointerEventHandler, ReactNode, RefCallback } from "react";
2
+ import { ButtonHTMLAttributes, CSSProperties, ClipboardEventHandler, FocusEventHandler, HTMLAttributes, PointerEventHandler, ReactNode, RefCallback } from "react";
3
3
  //#region src/core/errors.d.ts
4
4
  /**
5
- * Every way a copy can fail, as a closed union.
5
+ * Every way a clipboard operation can fail, as a closed union.
6
6
  *
7
7
  * `CopyError.message` is developer-facing (logs, telemetry). For user-facing
8
- * text use {@link describeCopyError} or map `type` through your own i18n layer.
8
+ * text use {@link describeCopyError} / {@link describePasteError}, or map
9
+ * `type` through your own i18n layer.
9
10
  */
10
11
  export type CopyErrorType =
11
12
  /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */
12
13
  'unsupported' |
13
14
  /** Page is not served over HTTPS/localhost. Not retryable. */
14
15
  'insecure-context' |
15
- /** Browser or user blocked the write. Also what Safari reports for a missing user gesture. */
16
+ /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */
16
17
  'permission-denied' |
17
- /** The document lost focus mid-copy (Chromium). Retrying after refocus usually works. */
18
+ /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */
18
19
  'not-focused' |
19
20
  /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */
20
21
  'invalid-payload' |
21
- /** The browser cannot write this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */
22
+ /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */
22
23
  'unsupported-format' |
23
- /** A lazy image source threw, rejected or did not produce a Blob. */
24
+ /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */
24
25
  'blob-generation-failed' |
25
26
  /** `retry()` was called after `maxRetries` was reached. Terminal. */
26
27
  'max-retries-exceeded' |
28
+ /** Paste: the clipboard held nothing matching `accept`. */
29
+ 'no-content' |
30
+ /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */
31
+ 'too-large' |
32
+ /** An operation did not settle within its deadline. Retryable. */
33
+ 'timeout' |
34
+ /** The caller aborted the operation through an `AbortSignal`. Not retryable. */
35
+ 'aborted' |
27
36
  /** Anything the platform threw that we could not classify. */
28
37
  'unknown';
38
+ /** Which clipboard direction failed; only changes developer-facing messages. */
39
+ export type ClipboardOperation = 'write' | 'read';
29
40
  export interface CopyError {
30
41
  readonly type: CopyErrorType;
31
42
  readonly message: string;
@@ -46,10 +57,17 @@ export declare class CopyFailure extends Error {
46
57
  constructor(copyError: CopyError);
47
58
  }
48
59
  export declare function isCopyFailure(value: unknown): value is CopyFailure;
49
- /** Classifies anything thrown by the platform or an adapter into a {@link CopyError}. */
50
- export declare function toCopyError(cause: unknown): CopyError;
51
- /** Default English, user-facing sentence for an error. Replace for i18n. */
60
+ /** Shorthand for throwing a classified failure. */
61
+ export declare function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure;
62
+ /**
63
+ * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.
64
+ * `operation` only tailors the developer-facing message.
65
+ */
66
+ export declare function toCopyError(cause: unknown, operation?: ClipboardOperation): CopyError;
67
+ /** Default English, user-facing sentence for a copy error. Replace for i18n. */
52
68
  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;
53
71
  //#endregion
54
72
  //#region src/core/payload.d.ts
55
73
  /** The only image MIME type with reliable cross-browser clipboard write support. */
@@ -107,6 +125,30 @@ export declare function validatePayload(payload: unknown): CopyError | null;
107
125
  /** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
108
126
  export declare function serializeJson(payload: JsonPayload): string;
109
127
  //#endregion
128
+ //#region src/core/mime.d.ts
129
+ /**
130
+ * MIME helpers shared by paste and capture. Everything that comes from the
131
+ * clipboard is untrusted input, so types are normalised and validated before
132
+ * they are compared, and image types are confirmed from the bytes themselves.
133
+ */
134
+ /** SVG is XML that can carry scripts; it is never matched by a wildcard. */
135
+ export declare const SVG_MIME_TYPE = "image/svg+xml";
136
+ /** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */
137
+ export declare function normalizeMimeType(value: string): string | null;
138
+ /**
139
+ * Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\/*`)?
140
+ * Wildcards never match `image/svg+xml`: accepting SVG must be explicit.
141
+ */
142
+ export declare function matchesMimePattern(mimeType: string, pattern: string): boolean;
143
+ /** Types whose clipboard data is text and is therefore surfaced as a `string`. */
144
+ export declare function isTextualMimeType(mimeType: string): boolean;
145
+ /** Raster image formats recognised from their leading bytes. */
146
+ export type RasterImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/bmp' | 'image/avif';
147
+ /** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */
148
+ export declare function sniffImageBytes(bytes: Uint8Array): RasterImageMimeType | null;
149
+ /** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */
150
+ export declare function sniffImageType(blob: Blob): Promise<RasterImageMimeType | null>;
151
+ //#endregion
110
152
  //#region src/core/clipboard-adapter.d.ts
111
153
  /** Minimal structural view of `navigator.clipboard`, so fakes and polyfills fit. */
112
154
  export interface ClipboardLike {
@@ -145,6 +187,31 @@ export interface BrowserClipboardAdapterOptions {
145
187
  /** The default adapter: async Clipboard API with feature detection and honest errors. */
146
188
  export declare function createBrowserClipboardAdapter(options?: BrowserClipboardAdapterOptions): ClipboardAdapter;
147
189
  //#endregion
190
+ //#region src/core/copy-coordinator.d.ts
191
+ /**
192
+ * A copy machine as seen by a coordinator. `release()` returns it from
193
+ * `copied` to `idle`; it is a no-op in any other state.
194
+ */
195
+ export interface CopyCoordinatorMember {
196
+ readonly release: () => void;
197
+ }
198
+ /**
199
+ * Makes a set of copy machines behave like one clipboard: when a member
200
+ * succeeds, the member that previously showed "Copied" goes back to idle,
201
+ * because the clipboard no longer holds its value.
202
+ *
203
+ * Failed copies never release anyone (the clipboard still holds the previous value).
204
+ */
205
+ export interface CopyCoordinator {
206
+ /** A member just reached `copied`. Releases the previous one. */
207
+ readonly activate: (member: CopyCoordinatorMember) => void;
208
+ /** A member left `copied` on its own (auto-reset, reset, unmount). */
209
+ readonly deactivate: (member: CopyCoordinatorMember) => void;
210
+ /** The member currently showing `copied`, if any. */
211
+ readonly getActive: () => CopyCoordinatorMember | null;
212
+ }
213
+ export declare function createCopyCoordinator(): CopyCoordinator;
214
+ //#endregion
148
215
  //#region src/core/copy-machine.d.ts
149
216
  export declare const DEFAULT_RESET_AFTER_MS = 2000;
150
217
  export declare const DEFAULT_MAX_RETRIES = 3;
@@ -190,6 +257,11 @@ export interface CopyMachineOptions {
190
257
  readonly resetAfterMs?: number | false;
191
258
  /** Max `retry()` calls after the first failure. Default 3. */
192
259
  readonly maxRetries?: number;
260
+ /**
261
+ * Share "Copied" with other machines: only one member of a coordinator
262
+ * shows `copied` at a time. `null` explicitly opts out (e.g. of a React `<CopyGroup>`).
263
+ */
264
+ readonly coordinator?: CopyCoordinator | null;
193
265
  readonly onCopy?: (payload: CopyPayload) => void;
194
266
  readonly onError?: (error: CopyError, payload: CopyPayload | null) => void;
195
267
  /** Clock injection for tests and deterministic environments. */
@@ -217,6 +289,181 @@ export declare function canRetryState(state: CopyState, maxRetries?: number): bo
217
289
  /** Framework-agnostic copy state machine. */
218
290
  export declare function createCopyMachine(options?: CopyMachineOptionsSource): CopyMachine;
219
291
  //#endregion
292
+ //#region src/core/paste-reader.d.ts
293
+ /** Friendly names for the common cases. */
294
+ type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';
295
+ /**
296
+ * What a paste may contain, in any order: a shorthand, an exact MIME type
297
+ * (`'image/png'`) or a wildcard (`'image/*'`, `'*\/*'`).
298
+ * `image/svg+xml` is only accepted when listed exactly (it is scriptable XML).
299
+ */
300
+ type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;
301
+ interface PasteLimits {
302
+ /** Total size cap across all accepted items. Strings count UTF-16 code units. Default 32 MiB. */
303
+ readonly maxBytes?: number;
304
+ /** Max number of accepted items (types + files). Default 32. */
305
+ readonly maxItems?: number;
306
+ }
307
+ interface PasteReadOptions extends PasteLimits {
308
+ /** Default `['text']` (plain text only): the safest choice. */
309
+ readonly accept?: readonly PasteAccept[];
310
+ }
311
+ /** Validated, normalised options that adapters receive. */
312
+ interface ResolvedPasteReadOptions {
313
+ /** Normalised patterns: `type/subtype`, `type/*` or `*\/*`. */
314
+ readonly accept: readonly string[];
315
+ readonly maxBytes: number;
316
+ readonly maxItems: number;
317
+ }
318
+ /** Where the content came from. */
319
+ type PasteSource = 'clipboard' | 'event';
320
+ /** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */
321
+ interface PasteItem {
322
+ readonly type: string;
323
+ readonly data: string | Blob;
324
+ }
325
+ /**
326
+ * Everything the paste produced. Treat all of it as untrusted user input:
327
+ * in particular never inject `html` into the DOM without sanitising it.
328
+ */
329
+ interface PasteResult {
330
+ readonly source: PasteSource;
331
+ /** Every accepted entry, in clipboard order. */
332
+ readonly items: readonly PasteItem[];
333
+ /** `text/plain`, when accepted and present. */
334
+ readonly text: string | null;
335
+ /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */
336
+ readonly html: string | null;
337
+ /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */
338
+ readonly images: readonly Blob[];
339
+ /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */
340
+ readonly files: readonly File[];
341
+ }
342
+ export declare const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[];
343
+ export declare const DEFAULT_PASTE_MAX_BYTES: number;
344
+ export declare const DEFAULT_PASTE_MAX_ITEMS = 32;
345
+ /** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
346
+ export declare function resolvePasteReadOptions(options?: PasteReadOptions): ResolvedPasteReadOptions;
347
+ /** Structural view of `DataTransfer` (paste events). */
348
+ interface DataTransferLike {
349
+ readonly types: ArrayLike<string>;
350
+ getData(format: string): string;
351
+ readonly files?: ArrayLike<File> | null;
352
+ }
353
+ /** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */
354
+ interface ClipboardItemLike {
355
+ readonly types: readonly string[];
356
+ getType(type: string): Promise<Blob>;
357
+ }
358
+ //#endregion
359
+ //#region src/core/paste-adapter.d.ts
360
+ /** Minimal structural view of `navigator.clipboard` for reading. */
361
+ interface PasteClipboardLike {
362
+ read?(): Promise<readonly ClipboardItemLike[]>;
363
+ readText?(): Promise<string>;
364
+ }
365
+ interface PasteEnvironment {
366
+ readonly isSecureContext?: boolean;
367
+ readonly navigator?: {
368
+ readonly clipboard?: PasteClipboardLike | undefined;
369
+ } | undefined;
370
+ }
371
+ /**
372
+ * Reads the system clipboard. Implement it for Electron, a native bridge or tests.
373
+ *
374
+ * Contract: call the platform API synchronously (before any `await`) so the
375
+ * browser still sees the user gesture, and reject with a `CopyFailure`.
376
+ */
377
+ interface PasteAdapter {
378
+ read(options: ResolvedPasteReadOptions): Promise<PasteResult>;
379
+ }
380
+ interface BrowserPasteAdapterOptions {
381
+ /** Defaults to `window`, read lazily at paste time (SSR-safe). */
382
+ readonly getEnvironment?: () => PasteEnvironment | undefined;
383
+ }
384
+ /** The default paste adapter: async Clipboard API with feature detection and honest errors. */
385
+ export declare function createBrowserPasteAdapter(options?: BrowserPasteAdapterOptions): PasteAdapter;
386
+ //#endregion
387
+ //#region src/core/paste-machine.d.ts
388
+ export interface PasteIdleState {
389
+ readonly status: 'idle';
390
+ }
391
+ export interface PasteReadingState {
392
+ readonly status: 'reading';
393
+ }
394
+ export interface PasteReadState {
395
+ readonly status: 'read';
396
+ readonly result: PasteResult;
397
+ /** Epoch ms when the read resolved. */
398
+ readonly at: number;
399
+ }
400
+ export interface PasteErrorState {
401
+ readonly status: 'error';
402
+ readonly error: CopyError;
403
+ }
404
+ export type PasteState = PasteIdleState | PasteReadingState | PasteReadState | PasteErrorState;
405
+ export type PasteStatus = PasteState['status'];
406
+ export type PasteIgnoredReason = 'in-flight' | 'no-accepted-content';
407
+ /** What `paste()` / `pasteEvent()` resolve to. They never reject. */
408
+ export type PasteOutcome = {
409
+ readonly status: 'read';
410
+ readonly result: PasteResult;
411
+ } | {
412
+ readonly status: 'error';
413
+ readonly error: CopyError;
414
+ } | {
415
+ readonly status: 'ignored';
416
+ readonly reason: PasteIgnoredReason;
417
+ };
418
+ /** Structural view of a DOM / React `paste` event. */
419
+ export interface PasteEventLike {
420
+ readonly clipboardData: DataTransferLike | null | undefined;
421
+ preventDefault(): void;
422
+ }
423
+ export interface PasteMachineOptions extends PasteReadOptions {
424
+ /** Defaults to the browser Clipboard API adapter. */
425
+ readonly adapter?: PasteAdapter;
426
+ /** Return from `read` to `idle` after this many ms. `false` / `Infinity` / omitted = keep the result. */
427
+ readonly resetAfterMs?: number | false;
428
+ /**
429
+ * Paste events only: call `event.preventDefault()` when the event carried
430
+ * accepted content, so the browser doesn't also insert it. Default `true`.
431
+ */
432
+ readonly preventDefault?: boolean;
433
+ readonly onPaste?: (result: PasteResult) => void;
434
+ readonly onError?: (error: CopyError) => void;
435
+ /** Clock injection for tests and deterministic environments. */
436
+ readonly now?: () => number;
437
+ }
438
+ /** Options object, or a getter so hosts (like React) can supply the latest options. */
439
+ export type PasteMachineOptionsSource = PasteMachineOptions | (() => PasteMachineOptions);
440
+ export interface PasteMachine {
441
+ readonly getSnapshot: () => PasteState;
442
+ readonly subscribe: (listener: () => void) => () => void;
443
+ /**
444
+ * Reads the system clipboard via the adapter. Call it from a user gesture
445
+ * (click, keypress). May show a permission prompt. Ignored while `reading`.
446
+ */
447
+ readonly paste: () => Promise<PasteOutcome>;
448
+ /**
449
+ * Handles a `paste` event (Ctrl/⌘+V). No permission prompt: the data is
450
+ * already in the event. Supersedes any read in flight. Events without
451
+ * accepted content are ignored and left untouched for the browser.
452
+ */
453
+ readonly pasteEvent: (event: PasteEventLike) => Promise<PasteOutcome>;
454
+ /** Back to `idle`, discarding any in-flight result. */
455
+ readonly reset: () => void;
456
+ /**
457
+ * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned
458
+ * cleanup clears timers, drops in-flight results and unsticks `reading`.
459
+ * Safe to call repeatedly (React StrictMode).
460
+ */
461
+ readonly connect: () => () => void;
462
+ }
463
+ export declare const PASTE_IDLE_STATE: PasteIdleState;
464
+ /** Framework-agnostic paste state machine. */
465
+ export declare function createPasteMachine(options?: PasteMachineOptionsSource): PasteMachine;
466
+ //#endregion
220
467
  //#region src/react/useCopy.d.ts
221
468
  type UseCopyOptions = CopyMachineOptions;
222
469
  interface UseCopyResult {
@@ -303,6 +550,18 @@ interface LiveRegionProps extends Omit<HTMLAttributes<HTMLSpanElement>, 'childre
303
550
  /**
304
551
  * Always-mounted announcer. Screen readers ignore regions that are inserted
305
552
  * together with their content, so this must render before the first message.
553
+ *
554
+ * **Mount safety**: the live region is intentionally empty on mount. We write
555
+ * the message into the DOM imperatively (via a ref) only after the element has
556
+ * been live for at least one browser paint. This prevents SSR hydration and
557
+ * strict-mode double-mount from producing a spurious announcement on some
558
+ * screen readers (JAWS / NVDA observe the initial DOM during hydration and
559
+ * re-read regions that already have text content).
560
+ *
561
+ * **WCAG 4.1.3 / ARIA spec**: we use `role="status"` with explicit `aria-live`
562
+ * rather than `role="alert"`. `role="alert"` interrupts any sentence being
563
+ * spoken even in polite mode, which is inappropriate for copy feedback.
564
+ * `role="status"` + `aria-live` is correct for both politeness levels.
306
565
  */
307
566
  export declare function LiveRegion({ message, politeness, visuallyHidden, style, ...rest }: LiveRegionProps): import("react").JSX.Element;
308
567
  //#endregion
@@ -312,7 +571,10 @@ interface CopyFieldMessages {
312
571
  readonly copied: string;
313
572
  /** Announced on failure. Defaults to {@link describeCopyError}. */
314
573
  readonly error: (error: CopyError) => string;
315
- /** Accessible name of the trigger. */
574
+ /**
575
+ * Accessible name of the trigger button. Receives the field's `label` prop.
576
+ * The returned string must not be empty.
577
+ */
316
578
  readonly triggerLabel: (label: string) => string;
317
579
  }
318
580
  export declare const defaultCopyFieldMessages: CopyFieldMessages;
@@ -374,5 +636,59 @@ export declare const CopyField: {
374
636
  readonly Trigger: import("react").ForwardRefExoticComponent<CopyFieldTriggerProps & import("react").RefAttributes<HTMLButtonElement>>;
375
637
  };
376
638
  //#endregion
377
- export type { CopyFieldContextValue, CopyFieldLabelProps, CopyFieldMessages, CopyFieldRootProps, CopyFieldTriggerProps, CopyFieldTriggerRenderProps, CopyFieldValueProps, LiveRegionProps, RevealReason, RevealTargetProps, UseCopyOptions, UseCopyResult, UseDisplayStatusOptions, UseRevealOnInteractionOptions, UseRevealOnInteractionResult };
639
+ //#region src/react/usePaste.d.ts
640
+ interface UsePasteOptions extends PasteMachineOptions {
641
+ /**
642
+ * Also handle Ctrl/⌘+V anywhere on the page (chat-style "paste a screenshot").
643
+ * Events an element already handled (`defaultPrevented`) are skipped. Default `false`.
644
+ */
645
+ readonly listenOnDocument?: boolean;
646
+ }
647
+ interface PasteTargetProps<T extends Element> {
648
+ readonly onPaste: ClipboardEventHandler<T>;
649
+ }
650
+ interface UsePasteResult<T extends Element = HTMLElement> {
651
+ /** Full discriminated state; narrow on `state.status`. */
652
+ readonly state: PasteState;
653
+ readonly status: PasteStatus;
654
+ /** The latest result while `status === 'read'`, otherwise `null`. */
655
+ readonly result: PasteResult | null;
656
+ readonly error: CopyError | null;
657
+ /** Stable identity. Reads the clipboard from a user gesture. Never rejects. */
658
+ readonly paste: PasteMachine['paste'];
659
+ /** Stable identity. Handles a paste event you received yourself. Never rejects. */
660
+ readonly pasteEvent: PasteMachine['pasteEvent'];
661
+ /** Stable identity. Back to `idle`, discarding any in-flight result. */
662
+ readonly reset: PasteMachine['reset'];
663
+ /** Spread onto an element (drop zone, textarea, editor) to accept Ctrl/⌘+V there. */
664
+ readonly targetProps: PasteTargetProps<T>;
665
+ }
666
+ /**
667
+ * Paste state machine bound to a component. Supports a "Paste" button
668
+ * (`paste()`, may prompt for permission) and keyboard paste (`targetProps`
669
+ * or `listenOnDocument`, no prompt). Options may change on every render.
670
+ *
671
+ * Everything in the result is untrusted user input.
672
+ */
673
+ export declare function usePaste<T extends Element = HTMLElement>(options?: UsePasteOptions): UsePasteResult<T>;
674
+ //#endregion
675
+ //#region src/react/CopyGroup.d.ts
676
+ interface CopyGroupProps {
677
+ readonly children?: ReactNode;
678
+ /**
679
+ * Share a coordinator with code outside this tree (another root, a vanilla
680
+ * `createCopyMachine`). Defaults to one owned by this group.
681
+ */
682
+ readonly coordinator?: CopyCoordinator;
683
+ }
684
+ /**
685
+ * Every `useCopy` / `<CopyField.Root>` inside behaves like one clipboard:
686
+ * a new successful copy returns the previously "Copied" one to idle.
687
+ * Opt a single field out with `copyOptions={{ coordinator: null }}`. Groups nest; the nearest wins.
688
+ */
689
+ export declare function CopyGroup({ children, coordinator }: CopyGroupProps): import("react").JSX.Element;
690
+ /** The nearest `<CopyGroup>`'s coordinator, or `null` outside any group. */
691
+ export declare function useCopyGroup(): CopyCoordinator | null;
692
+ //#endregion
693
+ export type { BrowserPasteAdapterOptions, ClipboardItemLike, CopyFieldContextValue, CopyFieldLabelProps, CopyFieldMessages, CopyFieldRootProps, CopyFieldTriggerProps, CopyFieldTriggerRenderProps, CopyFieldValueProps, CopyGroupProps, DataTransferLike, LiveRegionProps, PasteAccept, PasteAcceptShorthand, PasteAdapter, PasteClipboardLike, PasteEnvironment, PasteItem, PasteLimits, PasteReadOptions, PasteResult, PasteSource, PasteTargetProps, ResolvedPasteReadOptions, RevealReason, RevealTargetProps, UseCopyOptions, UseCopyResult, UseDisplayStatusOptions, UsePasteOptions, UsePasteResult, UseRevealOnInteractionOptions, UseRevealOnInteractionResult };
378
694
  //# sourceMappingURL=index.d.cts.map