react-smart-copy 1.2.0 → 1.3.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
@@ -262,6 +262,11 @@ export type CopyStatus = CopyState['status'];
262
262
  * so its work was aborted. Nothing to report to the user.
263
263
  */
264
264
  export type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';
265
+ /**
266
+ * Why an in-flight copy was cancelled: `reset` (`reset()` was called) or
267
+ * `disconnect` (its host disconnected, e.g. the React component unmounted).
268
+ */
269
+ export type CopyCancelReason = 'reset' | 'disconnect';
265
270
  /** What `copy()`/`retry()` resolve to. They never reject. */
266
271
  export type CopyOutcome = {
267
272
  readonly status: 'copied';
@@ -290,6 +295,18 @@ export interface CopyMachineOptions {
290
295
  readonly coordinator?: CopyCoordinator | null;
291
296
  readonly onCopy?: (payload: CopyPayload) => void;
292
297
  readonly onError?: (error: CopyError, payload: CopyPayload | null) => void;
298
+ /**
299
+ * `reset()` moved the machine back to `idle` from any other state. Not
300
+ * called for the automatic return after `resetAfterMs`, for a `<CopyGroup>`
301
+ * handing "Copied" to another member, or when already `idle`.
302
+ */
303
+ readonly onReset?: () => void;
304
+ /**
305
+ * A copy in flight was cancelled before it settled: its `signal` aborted
306
+ * and its result will not reach state or `onCopy` / `onError`. Fires
307
+ * before `onReset` when `reset()` cancels a copy.
308
+ */
309
+ readonly onCancel?: (reason: CopyCancelReason) => void;
293
310
  /** Clock injection for tests and deterministic environments. */
294
311
  readonly now?: () => number;
295
312
  }
@@ -326,7 +343,11 @@ type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';
326
343
  */
327
344
  type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;
328
345
  interface PasteLimits {
329
- /** Total size cap across all accepted items. Strings count UTF-16 code units. Default 32 MiB. */
346
+ /**
347
+ * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as
348
+ * they would be encoded, matching `Blob.size`, so every paste path counts the same way.
349
+ * Default 32 MiB.
350
+ */
330
351
  readonly maxBytes?: number;
331
352
  /** Max number of accepted items (types + files). Default 32. */
332
353
  readonly maxItems?: number;
@@ -365,7 +386,14 @@ interface PasteResult {
365
386
  readonly images: readonly Blob[];
366
387
  /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */
367
388
  readonly files: readonly File[];
389
+ /**
390
+ * The entries of `files` that are also in `images`: verified image files, keeping their
391
+ * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.
392
+ */
393
+ readonly imageFiles: readonly File[];
368
394
  }
395
+ /** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */
396
+ type PasteReadResult = Omit<PasteResult, 'imageFiles'>;
369
397
  export declare const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[];
370
398
  export declare const DEFAULT_PASTE_MAX_BYTES: number;
371
399
  export declare const DEFAULT_PASTE_MAX_ITEMS = 32;
@@ -404,7 +432,7 @@ interface PasteEnvironment {
404
432
  * unmounts; honour it to stop decoding early.
405
433
  */
406
434
  interface PasteAdapter {
407
- read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteResult>;
435
+ read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteReadResult>;
408
436
  }
409
437
  interface BrowserPasteAdapterOptions {
410
438
  /** Defaults to `window`, read lazily at paste time (SSR-safe). */
@@ -441,6 +469,12 @@ export type PasteStatus = PasteState['status'];
441
469
  * finished, so its work was aborted. Nothing to report to the user.
442
470
  */
443
471
  export type PasteIgnoredReason = 'in-flight' | 'no-accepted-content' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';
472
+ /**
473
+ * Why an in-flight read was cancelled: `reset` (`reset()` was called),
474
+ * `disconnect` (its host disconnected, e.g. the React component unmounted) or
475
+ * `superseded` (a paste event arrived while a clipboard read was pending).
476
+ */
477
+ export type PasteCancelReason = 'reset' | 'disconnect' | 'superseded';
444
478
  /** What `paste()` / `pasteEvent()` / `retry()` resolve to. They never reject. */
445
479
  export type PasteOutcome = {
446
480
  readonly status: 'read';
@@ -474,6 +508,17 @@ export interface PasteMachineOptions extends PasteReadOptions {
474
508
  readonly maxRetries?: number;
475
509
  readonly onPaste?: (result: PasteResult) => void;
476
510
  readonly onError?: (error: CopyError) => void;
511
+ /**
512
+ * `reset()` moved the machine back to `idle` from any other state. Not
513
+ * called for the automatic return after `resetAfterMs`, or when already `idle`.
514
+ */
515
+ readonly onReset?: () => void;
516
+ /**
517
+ * A read in flight was cancelled before it settled: its `signal` aborted
518
+ * and its result will not reach state or `onPaste` / `onError`. Fires
519
+ * before `onReset` when `reset()` cancels a read.
520
+ */
521
+ readonly onCancel?: (reason: PasteCancelReason) => void;
477
522
  /** Clock injection for tests and deterministic environments. */
478
523
  readonly now?: () => number;
479
524
  }
@@ -877,5 +922,5 @@ export declare const PasteField: {
877
922
  readonly Preview: import("react").ForwardRefExoticComponent<PasteFieldPreviewProps & import("react").RefAttributes<HTMLDivElement>>;
878
923
  };
879
924
  //#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 };
925
+ 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, PasteReadResult, PasteResult, PasteSource, PasteTargetProps, ResolvedPasteReadOptions, RevealReason, RevealTargetProps, UseCopyOptions, UseCopyResult, UseDisplayStatusOptions, UsePasteDisplayStatusOptions, UsePasteOptions, UsePasteResult, UseRevealOnInteractionOptions, UseRevealOnInteractionResult };
881
926
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -262,6 +262,11 @@ export type CopyStatus = CopyState['status'];
262
262
  * so its work was aborted. Nothing to report to the user.
263
263
  */
264
264
  export type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';
265
+ /**
266
+ * Why an in-flight copy was cancelled: `reset` (`reset()` was called) or
267
+ * `disconnect` (its host disconnected, e.g. the React component unmounted).
268
+ */
269
+ export type CopyCancelReason = 'reset' | 'disconnect';
265
270
  /** What `copy()`/`retry()` resolve to. They never reject. */
266
271
  export type CopyOutcome = {
267
272
  readonly status: 'copied';
@@ -290,6 +295,18 @@ export interface CopyMachineOptions {
290
295
  readonly coordinator?: CopyCoordinator | null;
291
296
  readonly onCopy?: (payload: CopyPayload) => void;
292
297
  readonly onError?: (error: CopyError, payload: CopyPayload | null) => void;
298
+ /**
299
+ * `reset()` moved the machine back to `idle` from any other state. Not
300
+ * called for the automatic return after `resetAfterMs`, for a `<CopyGroup>`
301
+ * handing "Copied" to another member, or when already `idle`.
302
+ */
303
+ readonly onReset?: () => void;
304
+ /**
305
+ * A copy in flight was cancelled before it settled: its `signal` aborted
306
+ * and its result will not reach state or `onCopy` / `onError`. Fires
307
+ * before `onReset` when `reset()` cancels a copy.
308
+ */
309
+ readonly onCancel?: (reason: CopyCancelReason) => void;
293
310
  /** Clock injection for tests and deterministic environments. */
294
311
  readonly now?: () => number;
295
312
  }
@@ -326,7 +343,11 @@ type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';
326
343
  */
327
344
  type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;
328
345
  interface PasteLimits {
329
- /** Total size cap across all accepted items. Strings count UTF-16 code units. Default 32 MiB. */
346
+ /**
347
+ * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as
348
+ * they would be encoded, matching `Blob.size`, so every paste path counts the same way.
349
+ * Default 32 MiB.
350
+ */
330
351
  readonly maxBytes?: number;
331
352
  /** Max number of accepted items (types + files). Default 32. */
332
353
  readonly maxItems?: number;
@@ -365,7 +386,14 @@ interface PasteResult {
365
386
  readonly images: readonly Blob[];
366
387
  /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */
367
388
  readonly files: readonly File[];
389
+ /**
390
+ * The entries of `files` that are also in `images`: verified image files, keeping their
391
+ * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.
392
+ */
393
+ readonly imageFiles: readonly File[];
368
394
  }
395
+ /** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */
396
+ type PasteReadResult = Omit<PasteResult, 'imageFiles'>;
369
397
  export declare const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[];
370
398
  export declare const DEFAULT_PASTE_MAX_BYTES: number;
371
399
  export declare const DEFAULT_PASTE_MAX_ITEMS = 32;
@@ -404,7 +432,7 @@ interface PasteEnvironment {
404
432
  * unmounts; honour it to stop decoding early.
405
433
  */
406
434
  interface PasteAdapter {
407
- read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteResult>;
435
+ read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteReadResult>;
408
436
  }
409
437
  interface BrowserPasteAdapterOptions {
410
438
  /** Defaults to `window`, read lazily at paste time (SSR-safe). */
@@ -441,6 +469,12 @@ export type PasteStatus = PasteState['status'];
441
469
  * finished, so its work was aborted. Nothing to report to the user.
442
470
  */
443
471
  export type PasteIgnoredReason = 'in-flight' | 'no-accepted-content' | 'nothing-to-retry' | 'not-retryable' | 'cancelled';
472
+ /**
473
+ * Why an in-flight read was cancelled: `reset` (`reset()` was called),
474
+ * `disconnect` (its host disconnected, e.g. the React component unmounted) or
475
+ * `superseded` (a paste event arrived while a clipboard read was pending).
476
+ */
477
+ export type PasteCancelReason = 'reset' | 'disconnect' | 'superseded';
444
478
  /** What `paste()` / `pasteEvent()` / `retry()` resolve to. They never reject. */
445
479
  export type PasteOutcome = {
446
480
  readonly status: 'read';
@@ -474,6 +508,17 @@ export interface PasteMachineOptions extends PasteReadOptions {
474
508
  readonly maxRetries?: number;
475
509
  readonly onPaste?: (result: PasteResult) => void;
476
510
  readonly onError?: (error: CopyError) => void;
511
+ /**
512
+ * `reset()` moved the machine back to `idle` from any other state. Not
513
+ * called for the automatic return after `resetAfterMs`, or when already `idle`.
514
+ */
515
+ readonly onReset?: () => void;
516
+ /**
517
+ * A read in flight was cancelled before it settled: its `signal` aborted
518
+ * and its result will not reach state or `onPaste` / `onError`. Fires
519
+ * before `onReset` when `reset()` cancels a read.
520
+ */
521
+ readonly onCancel?: (reason: PasteCancelReason) => void;
477
522
  /** Clock injection for tests and deterministic environments. */
478
523
  readonly now?: () => number;
479
524
  }
@@ -877,5 +922,5 @@ export declare const PasteField: {
877
922
  readonly Preview: import("react").ForwardRefExoticComponent<PasteFieldPreviewProps & import("react").RefAttributes<HTMLDivElement>>;
878
923
  };
879
924
  //#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 };
925
+ 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, PasteReadResult, PasteResult, PasteSource, PasteTargetProps, ResolvedPasteReadOptions, RevealReason, RevealTargetProps, UseCopyOptions, UseCopyResult, UseDisplayStatusOptions, UsePasteDisplayStatusOptions, UsePasteOptions, UsePasteResult, UseRevealOnInteractionOptions, UseRevealOnInteractionResult };
881
926
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -379,8 +379,10 @@ function invoke(fn, ...args) {
379
379
  function createOperations() {
380
380
  let controller;
381
381
  const abort = () => {
382
- controller?.abort();
382
+ if (!controller) return false;
383
+ controller.abort();
383
384
  controller = void 0;
385
+ return true;
384
386
  };
385
387
  return {
386
388
  start: () => {
@@ -568,17 +570,21 @@ function createCopyMachine(options = {}) {
568
570
  };
569
571
  const reset = () => {
570
572
  ++generation;
571
- operations.abort();
573
+ const cancelled = operations.abort();
572
574
  clearResetTimer();
575
+ const wasIdle = state.status === "idle";
573
576
  setState(IDLE_STATE);
577
+ if (cancelled) invoke(read().onCancel, "reset");
578
+ if (!wasIdle) invoke(read().onReset);
574
579
  };
575
580
  const connect = () => {
576
581
  if (state.status === "copied") scheduleReset(state);
577
582
  return () => {
578
583
  ++generation;
579
- operations.abort();
584
+ const cancelled = operations.abort();
580
585
  clearResetTimer();
581
586
  if (state.status === "copying") setState(IDLE_STATE);
587
+ if (cancelled) invoke(read().onCancel, "disconnect");
582
588
  };
583
589
  };
584
590
  return {
@@ -597,6 +603,14 @@ function createCopyMachine(options = {}) {
597
603
  }
598
604
  //#endregion
599
605
  //#region src/core/paste-reader.ts
606
+ /** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
607
+ function completePasteResult(result) {
608
+ const images = new Set(result.images);
609
+ return {
610
+ ...result,
611
+ imageFiles: result.files.filter((file) => images.has(file))
612
+ };
613
+ }
600
614
  const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
601
615
  const DEFAULT_PASTE_MAX_BYTES = 33554432;
602
616
  const DEFAULT_PASTE_MAX_ITEMS = 32;
@@ -652,7 +666,25 @@ function createBudget(options) {
652
666
  if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
653
667
  } };
654
668
  }
655
- const sizeOf = (data) => typeof data === "string" ? data.length : data.size;
669
+ /**
670
+ * UTF-8 byte length of a string, without allocating an encoded copy.
671
+ * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.
672
+ */
673
+ function utf8ByteLength(text) {
674
+ let bytes = 0;
675
+ for (let i = 0; i < text.length; i += 1) {
676
+ const unit = text.charCodeAt(i);
677
+ if (unit < 128) bytes += 1;
678
+ else if (unit < 2048) bytes += 2;
679
+ else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length && (text.charCodeAt(i + 1) & 64512) === 56320) {
680
+ bytes += 4;
681
+ i += 1;
682
+ } else bytes += 3;
683
+ }
684
+ return bytes;
685
+ }
686
+ /** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */
687
+ const sizeOf = (data) => typeof data === "string" ? utf8ByteLength(data) : data.size;
656
688
  /** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
657
689
  function enforcePasteLimits(entries, options) {
658
690
  const budget = createBudget(options);
@@ -896,15 +928,17 @@ function createPasteMachine(options = {}) {
896
928
  const run = (produce, source, retryCount) => {
897
929
  clearResetTimer();
898
930
  const current = ++generation;
931
+ const superseded = operations.abort();
899
932
  const context = operations.start();
900
933
  setState(PASTE_READING_STATE);
934
+ if (superseded) invoke(read().onCancel, "superseded");
901
935
  let pending;
902
936
  try {
903
937
  pending = produce(context);
904
938
  } catch (cause) {
905
939
  pending = Promise.reject(cause);
906
940
  }
907
- return pending.then((result) => {
941
+ return pending.then(completePasteResult).then((result) => {
908
942
  operations.end(context);
909
943
  if (current === generation) {
910
944
  const readState = {
@@ -956,9 +990,10 @@ function createPasteMachine(options = {}) {
956
990
  } catch (cause) {
957
991
  const error = toCopyError(cause, "read");
958
992
  ++generation;
959
- operations.abort();
993
+ const superseded = operations.abort();
960
994
  clearResetTimer();
961
995
  settleError(error, "event", 0);
996
+ if (superseded) invoke(current.onCancel, "superseded");
962
997
  return Promise.resolve({
963
998
  status: "error",
964
999
  error
@@ -974,17 +1009,21 @@ function createPasteMachine(options = {}) {
974
1009
  };
975
1010
  const reset = () => {
976
1011
  ++generation;
977
- operations.abort();
1012
+ const cancelled = operations.abort();
978
1013
  clearResetTimer();
1014
+ const wasIdle = state.status === "idle";
979
1015
  setState(PASTE_IDLE_STATE);
1016
+ if (cancelled) invoke(read().onCancel, "reset");
1017
+ if (!wasIdle) invoke(read().onReset);
980
1018
  };
981
1019
  const connect = () => {
982
1020
  if (state.status === "read") scheduleReset(state);
983
1021
  return () => {
984
1022
  ++generation;
985
- operations.abort();
1023
+ const cancelled = operations.abort();
986
1024
  clearResetTimer();
987
1025
  if (state.status === "reading") setState(PASTE_IDLE_STATE);
1026
+ if (cancelled) invoke(read().onCancel, "disconnect");
988
1027
  };
989
1028
  };
990
1029
  return {