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