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.cjs CHANGED
@@ -103,9 +103,19 @@ const PASTE_DESCRIPTIONS = {
103
103
  function describeCopyError(error) {
104
104
  return COPY_DESCRIPTIONS[error.type];
105
105
  }
106
- /** Default English, user-facing sentence for a paste error. Replace for i18n. */
107
- function describePasteError(error) {
108
- return PASTE_DESCRIPTIONS[error.type];
106
+ /** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */
107
+ const DROP_DESCRIPTIONS = {
108
+ "invalid-payload": "The dropped content couldn't be read.",
109
+ "no-content": "Nothing that was dropped can be used here.",
110
+ "too-large": "The dropped content is too large.",
111
+ unknown: "Couldn't read the dropped content. Try again."
112
+ };
113
+ /**
114
+ * Default English, user-facing sentence for a paste error. Pass the error
115
+ * state's `source` to word drag-and-drop failures as drops. Replace for i18n.
116
+ */
117
+ function describePasteError(error, source) {
118
+ return (source === "drop" ? DROP_DESCRIPTIONS[error.type] : void 0) ?? PASTE_DESCRIPTIONS[error.type];
109
119
  }
110
120
  //#endregion
111
121
  //#region src/core/payload.ts
@@ -380,8 +390,10 @@ function invoke(fn, ...args) {
380
390
  function createOperations() {
381
391
  let controller;
382
392
  const abort = () => {
383
- controller?.abort();
393
+ if (!controller) return false;
394
+ controller.abort();
384
395
  controller = void 0;
396
+ return true;
385
397
  };
386
398
  return {
387
399
  start: () => {
@@ -569,17 +581,21 @@ function createCopyMachine(options = {}) {
569
581
  };
570
582
  const reset = () => {
571
583
  ++generation;
572
- operations.abort();
584
+ const cancelled = operations.abort();
573
585
  clearResetTimer();
586
+ const wasIdle = state.status === "idle";
574
587
  setState(IDLE_STATE);
588
+ if (cancelled) invoke(read().onCancel, "reset");
589
+ if (!wasIdle) invoke(read().onReset);
575
590
  };
576
591
  const connect = () => {
577
592
  if (state.status === "copied") scheduleReset(state);
578
593
  return () => {
579
594
  ++generation;
580
- operations.abort();
595
+ const cancelled = operations.abort();
581
596
  clearResetTimer();
582
597
  if (state.status === "copying") setState(IDLE_STATE);
598
+ if (cancelled) invoke(read().onCancel, "disconnect");
583
599
  };
584
600
  };
585
601
  return {
@@ -598,6 +614,14 @@ function createCopyMachine(options = {}) {
598
614
  }
599
615
  //#endregion
600
616
  //#region src/core/paste-reader.ts
617
+ /** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
618
+ function completePasteResult(result) {
619
+ const images = new Set(result.images);
620
+ return {
621
+ ...result,
622
+ imageFiles: result.files.filter((file) => images.has(file))
623
+ };
624
+ }
601
625
  const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
602
626
  const DEFAULT_PASTE_MAX_BYTES = 33554432;
603
627
  const DEFAULT_PASTE_MAX_ITEMS = 32;
@@ -653,13 +677,52 @@ function createBudget(options) {
653
677
  if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
654
678
  } };
655
679
  }
656
- const sizeOf = (data) => typeof data === "string" ? data.length : data.size;
680
+ /**
681
+ * UTF-8 byte length of a string, without allocating an encoded copy.
682
+ * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.
683
+ */
684
+ function utf8ByteLength(text) {
685
+ let bytes = 0;
686
+ for (let i = 0; i < text.length; i += 1) {
687
+ const unit = text.charCodeAt(i);
688
+ if (unit < 128) bytes += 1;
689
+ else if (unit < 2048) bytes += 2;
690
+ else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length && (text.charCodeAt(i + 1) & 64512) === 56320) {
691
+ bytes += 4;
692
+ i += 1;
693
+ } else bytes += 3;
694
+ }
695
+ return bytes;
696
+ }
697
+ /** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */
698
+ const sizeOf = (data) => typeof data === "string" ? utf8ByteLength(data) : data.size;
657
699
  /** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
658
700
  function enforcePasteLimits(entries, options) {
659
701
  const budget = createBudget(options);
660
702
  for (const entry of entries) budget.charge(sizeOf(entry.data));
661
703
  }
662
704
  /**
705
+ * Whether a drag in progress could drop anything `accept`s. Uses only what
706
+ * browsers expose before the drop (item kinds and types, never the data).
707
+ * A file whose type is not known yet (some browsers hide it while dragging)
708
+ * counts as a maybe: the drop itself is checked against `accept`.
709
+ */
710
+ function canAcceptDrag(data, options) {
711
+ const items = data.items ?? Array.from(data.types, (type) => type === "Files" ? {
712
+ kind: "file",
713
+ type: ""
714
+ } : {
715
+ kind: "string",
716
+ type
717
+ });
718
+ return Array.from(items).some(({ kind, type: raw }) => {
719
+ const file = kind === "file";
720
+ const type = normalizeMimeType(raw);
721
+ if (type === null) return file;
722
+ return (file || isTextualMimeType(type)) && isAccepted(type, options);
723
+ });
724
+ }
725
+ /**
663
726
  * Synchronously copies the accepted parts of a paste event's `DataTransfer`.
664
727
  * It must run during the event: browsers empty the object afterwards.
665
728
  */
@@ -757,7 +820,7 @@ async function finalizePaste(entries, source, options) {
757
820
  data
758
821
  });
759
822
  }
760
- if (items.length === 0) throw copyFailure("no-content", "The clipboard holds nothing that matches `accept`.");
823
+ if (items.length === 0) throw copyFailure("no-content", "The content holds nothing that matches `accept`.");
761
824
  return {
762
825
  source,
763
826
  items,
@@ -897,15 +960,17 @@ function createPasteMachine(options = {}) {
897
960
  const run = (produce, source, retryCount) => {
898
961
  clearResetTimer();
899
962
  const current = ++generation;
963
+ const superseded = operations.abort();
900
964
  const context = operations.start();
901
965
  setState(PASTE_READING_STATE);
966
+ if (superseded) invoke(read().onCancel, "superseded");
902
967
  let pending;
903
968
  try {
904
969
  pending = produce(context);
905
970
  } catch (cause) {
906
971
  pending = Promise.reject(cause);
907
972
  }
908
- return pending.then((result) => {
973
+ return pending.then(completePasteResult).then((result) => {
909
974
  operations.end(context);
910
975
  if (current === generation) {
911
976
  const readState = {
@@ -947,19 +1012,21 @@ function createPasteMachine(options = {}) {
947
1012
  }
948
1013
  return readClipboard(state.retryCount + 1);
949
1014
  };
950
- const pasteEvent = (event) => {
951
- const data = event.clipboardData;
952
- if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
1015
+ /** Shared by paste and drop events: their `DataTransfer` has the same shape and lifetime. */
1016
+ const transfer = (data, event, source) => {
953
1017
  const current = read();
1018
+ if (source === "drop" && current.preventDefault !== false) event.preventDefault();
1019
+ if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
954
1020
  let resolved;
955
1021
  try {
956
1022
  resolved = resolvePasteReadOptions(current);
957
1023
  } catch (cause) {
958
1024
  const error = toCopyError(cause, "read");
959
1025
  ++generation;
960
- operations.abort();
1026
+ const superseded = operations.abort();
961
1027
  clearResetTimer();
962
- settleError(error, "event", 0);
1028
+ settleError(error, source, 0);
1029
+ if (superseded) invoke(current.onCancel, "superseded");
963
1030
  return Promise.resolve({
964
1031
  status: "error",
965
1032
  error
@@ -967,25 +1034,31 @@ function createPasteMachine(options = {}) {
967
1034
  }
968
1035
  const entries = snapshotDataTransfer(data, resolved);
969
1036
  if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);
970
- if (current.preventDefault !== false) event.preventDefault();
1037
+ if (source === "event" && current.preventDefault !== false) event.preventDefault();
971
1038
  return run(() => {
972
1039
  enforcePasteLimits(entries, resolved);
973
- return finalizePaste(entries, "event", resolved);
974
- }, "event", 0);
1040
+ return finalizePaste(entries, source, resolved);
1041
+ }, source, 0);
975
1042
  };
1043
+ const pasteEvent = (event) => transfer(event.clipboardData, event, "event");
1044
+ const dropEvent = (event) => transfer(event.dataTransfer, event, "drop");
976
1045
  const reset = () => {
977
1046
  ++generation;
978
- operations.abort();
1047
+ const cancelled = operations.abort();
979
1048
  clearResetTimer();
1049
+ const wasIdle = state.status === "idle";
980
1050
  setState(PASTE_IDLE_STATE);
1051
+ if (cancelled) invoke(read().onCancel, "reset");
1052
+ if (!wasIdle) invoke(read().onReset);
981
1053
  };
982
1054
  const connect = () => {
983
1055
  if (state.status === "read") scheduleReset(state);
984
1056
  return () => {
985
1057
  ++generation;
986
- operations.abort();
1058
+ const cancelled = operations.abort();
987
1059
  clearResetTimer();
988
1060
  if (state.status === "reading") setState(PASTE_IDLE_STATE);
1061
+ if (cancelled) invoke(read().onCancel, "disconnect");
989
1062
  };
990
1063
  };
991
1064
  return {
@@ -998,6 +1071,7 @@ function createPasteMachine(options = {}) {
998
1071
  },
999
1072
  paste,
1000
1073
  pasteEvent,
1074
+ dropEvent,
1001
1075
  retry,
1002
1076
  reset,
1003
1077
  connect
@@ -1462,10 +1536,21 @@ const CopyField = {
1462
1536
  //#endregion
1463
1537
  //#region src/react/usePaste.ts
1464
1538
  const getServerSnapshot = () => PASTE_IDLE_STATE;
1539
+ const DRAG_END_EVENTS = ["drop", "dragend"];
1540
+ /** A text field or editable region nested inside the drop target, which should keep its native drop. */
1541
+ const isNestedEditable = (event) => {
1542
+ const { target, currentTarget } = event;
1543
+ if (target === currentTarget || !(target instanceof HTMLElement)) return false;
1544
+ if (target.tagName === "INPUT" || target.tagName === "TEXTAREA") return true;
1545
+ return target.isContentEditable && !(currentTarget instanceof HTMLElement && currentTarget.isContentEditable);
1546
+ };
1547
+ /** The drop effect the drag source allows, preferring copy: an effect it disallows cancels the drop. */
1548
+ const dropEffectFor = (allowed) => /^(all|uninitialized|copy)/.test(allowed) ? "copy" : /move/i.test(allowed) ? "move" : allowed === "link" ? "link" : "none";
1465
1549
  /**
1466
1550
  * Paste state machine bound to a component. Supports a "Paste" button
1467
- * (`paste()`, may prompt for permission) and keyboard paste (`targetProps`
1468
- * or `listenOnDocument`, no prompt). Options may change on every render.
1551
+ * (`paste()`, may prompt for permission), keyboard paste (`targetProps` or
1552
+ * `listenOnDocument`, no prompt) and drag-and-drop (`dropTargetProps`).
1553
+ * Options may change on every render.
1469
1554
  *
1470
1555
  * Everything in the result is untrusted user input.
1471
1556
  */
@@ -1492,6 +1577,48 @@ function usePaste(options = {}) {
1492
1577
  const targetProps = (0, react.useMemo)(() => ({ onPaste: (event) => {
1493
1578
  machine.pasteEvent(event);
1494
1579
  } }), [machine]);
1580
+ const [isDragOver, setIsDragOver] = (0, react.useState)(false);
1581
+ const dragDepth = (0, react.useRef)(0);
1582
+ const [endDrag] = (0, react.useState)(() => () => {
1583
+ dragDepth.current = 0;
1584
+ setIsDragOver(false);
1585
+ });
1586
+ const dropTargetProps = (0, react.useMemo)(() => {
1587
+ const accepts = (data) => {
1588
+ try {
1589
+ return canAcceptDrag(data, resolvePasteReadOptions(optionsRef.current));
1590
+ } catch {
1591
+ return true;
1592
+ }
1593
+ };
1594
+ return {
1595
+ onDragEnter: (event) => {
1596
+ dragDepth.current += 1;
1597
+ if (accepts(event.dataTransfer)) setIsDragOver(true);
1598
+ },
1599
+ onDragOver: (event) => {
1600
+ if (isNestedEditable(event)) return;
1601
+ event.preventDefault();
1602
+ event.dataTransfer.dropEffect = accepts(event.dataTransfer) ? dropEffectFor(event.dataTransfer.effectAllowed) : "none";
1603
+ },
1604
+ onDragLeave: (event) => {
1605
+ const next = event.relatedTarget;
1606
+ dragDepth.current -= 1;
1607
+ if (dragDepth.current <= 0 || next instanceof Node && !event.currentTarget.contains(next)) endDrag();
1608
+ },
1609
+ onDrop: (event) => {
1610
+ endDrag();
1611
+ if (!isNestedEditable(event)) machine.dropEvent(event);
1612
+ }
1613
+ };
1614
+ }, [machine, endDrag]);
1615
+ (0, react.useEffect)(() => {
1616
+ if (!isDragOver) return void 0;
1617
+ for (const type of DRAG_END_EVENTS) window.addEventListener(type, endDrag, true);
1618
+ return () => {
1619
+ for (const type of DRAG_END_EVENTS) window.removeEventListener(type, endDrag, true);
1620
+ };
1621
+ }, [isDragOver, endDrag]);
1495
1622
  return (0, react.useMemo)(() => ({
1496
1623
  state,
1497
1624
  status: state.status,
@@ -1500,14 +1627,19 @@ function usePaste(options = {}) {
1500
1627
  canRetry,
1501
1628
  paste: machine.paste,
1502
1629
  pasteEvent: machine.pasteEvent,
1630
+ dropEvent: machine.dropEvent,
1503
1631
  retry: machine.retry,
1504
1632
  reset: machine.reset,
1505
- targetProps
1633
+ targetProps,
1634
+ dropTargetProps,
1635
+ isDragOver
1506
1636
  }), [
1507
1637
  state,
1508
1638
  canRetry,
1509
1639
  machine,
1510
- targetProps
1640
+ targetProps,
1641
+ dropTargetProps,
1642
+ isDragOver
1511
1643
  ]);
1512
1644
  }
1513
1645
  //#endregion
@@ -1563,6 +1695,7 @@ function usePasteDisplayStatus(status, options = {}) {
1563
1695
  //#region src/react/PasteField.tsx
1564
1696
  const defaultPasteFieldMessages = {
1565
1697
  pasted: "Pasted from clipboard",
1698
+ dropped: "Dropped content added",
1566
1699
  error: describePasteError,
1567
1700
  triggerLabel: (label) => `Paste ${label}`,
1568
1701
  zoneLabel: (label) => `Paste area for ${label}`
@@ -1586,6 +1719,7 @@ const Root = /* @__PURE__ */ (0, react.forwardRef)(function PasteFieldRoot({ lab
1586
1719
  const zoneId = `${baseId}-zone`;
1587
1720
  const messages = (0, react.useMemo)(() => ({
1588
1721
  ...defaultPasteFieldMessages,
1722
+ ...messageOverrides?.pasted === void 0 ? {} : { dropped: messageOverrides.pasted },
1589
1723
  ...messageOverrides
1590
1724
  }), [messageOverrides]);
1591
1725
  const { paste: machinePaste } = pasteState;
@@ -1614,7 +1748,11 @@ const Root = /* @__PURE__ */ (0, react.forwardRef)(function PasteFieldRoot({ lab
1614
1748
  doPaste
1615
1749
  ]);
1616
1750
  const { state } = pasteState;
1617
- const announcement = state.status === "read" ? typeof messages.pasted === "function" ? messages.pasted(state.result) : messages.pasted : state.status === "error" ? messages.error(state.error) : "";
1751
+ let announcement = "";
1752
+ if (state.status === "read") {
1753
+ const message = (state.result.source === "drop" ? messages.dropped : void 0) ?? messages.pasted;
1754
+ announcement = typeof message === "function" ? message(state.result) : message;
1755
+ } else if (state.status === "error") announcement = messages.error(state.error, state.source);
1618
1756
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PasteFieldContext.Provider, {
1619
1757
  value: context,
1620
1758
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
@@ -1663,15 +1801,23 @@ const Status = /* @__PURE__ */ (0, react.forwardRef)(function PasteFieldStatus({
1663
1801
  });
1664
1802
  /**
1665
1803
  * A focusable paste target. Accepts keyboard paste (Ctrl/⌘+V) without a
1666
- * permission prompt and renders `data-zone` for styling.
1804
+ * permission prompt and, unless `droppable={false}`, drag-and-drop. Renders
1805
+ * `data-zone` and `data-drag-over` for styling.
1667
1806
  *
1668
1807
  * Accessible name: `aria-label` prop, else `messages.zoneLabel(label)`
1669
1808
  * ("Paste area for Notes"). Pass `aria-labelledby` explicitly to name it from
1670
1809
  * another element instead.
1671
1810
  */
1672
- const Zone = /* @__PURE__ */ (0, react.forwardRef)(function PasteFieldZone({ children, focusable = true, onPaste, "aria-label": ariaLabel, tabIndex, ...rest }, ref) {
1811
+ const Zone = /* @__PURE__ */ (0, react.forwardRef)(function PasteFieldZone({ children, focusable = true, droppable = true, onPaste, onDragEnter, onDragOver, onDragLeave, onDrop, "aria-label": ariaLabel, tabIndex, ...rest }, ref) {
1673
1812
  const field = usePasteField();
1674
- const { targetProps } = field;
1813
+ const { targetProps, dropTargetProps } = field;
1814
+ const drop = {
1815
+ onDragEnter,
1816
+ onDragOver,
1817
+ onDragLeave,
1818
+ onDrop
1819
+ };
1820
+ if (droppable) for (const key of Object.keys(dropTargetProps)) drop[key] = composeEventHandlers(drop[key], dropTargetProps[key]);
1675
1821
  const safeAriaLabel = (ariaLabel ?? field.messages.zoneLabel(field.label)) || defaultPasteFieldMessages.zoneLabel(field.label);
1676
1822
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1677
1823
  "aria-keyshortcuts": "Control+V Meta+V",
@@ -1683,8 +1829,10 @@ const Zone = /* @__PURE__ */ (0, react.forwardRef)(function PasteFieldZone({ chi
1683
1829
  "data-zone": "",
1684
1830
  "data-state": field.status,
1685
1831
  "data-display-state": field.displayStatus,
1832
+ "data-drag-over": droppable && field.isDragOver ? "" : void 0,
1686
1833
  tabIndex: tabIndex ?? (focusable ? 0 : void 0),
1687
1834
  onPaste: composeEventHandlers(onPaste, targetProps.onPaste),
1835
+ ...drop,
1688
1836
  children
1689
1837
  });
1690
1838
  });
@@ -1826,6 +1974,7 @@ exports.LiveRegion = LiveRegion;
1826
1974
  exports.PASTE_IDLE_STATE = PASTE_IDLE_STATE;
1827
1975
  exports.PasteField = PasteField;
1828
1976
  exports.SVG_MIME_TYPE = SVG_MIME_TYPE;
1977
+ exports.canAcceptDrag = canAcceptDrag;
1829
1978
  exports.canRetryPasteState = canRetryPasteState;
1830
1979
  exports.canRetryState = canRetryState;
1831
1980
  exports.copyFailure = copyFailure;