plitejs 54.0.0-beta.4 → 54.0.0-beta.6

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.
Files changed (56) hide show
  1. package/dist/annotations/index.d.ts +1 -1
  2. package/dist/annotations/index.js +1 -1
  3. package/dist/authored/index.d.ts +2 -2
  4. package/dist/authored/index.js +1302 -490
  5. package/dist/{authored-veto-D_9wCJcK.js → authored-veto-BsBDXC0b.js} +1 -1
  6. package/dist/{comparison-plan-DY_vuGPq.js → comparison-plan-IOewH50q.js} +1 -1
  7. package/dist/{comparison-types-DdwE6mYq.d.ts → comparison-types-DBQFu7Rt.d.ts} +1 -1
  8. package/dist/{create-editor-CLQEkEZ1.js → create-editor-DRRzGwaC.js} +1 -1
  9. package/dist/diff/index.d.ts +2 -2
  10. package/dist/diff/index.js +2 -2
  11. package/dist/dom/index.d.ts +1 -1
  12. package/dist/dom/index.js +1 -1
  13. package/dist/{dom-CH2BXXj6.js → dom-CVYV5Qd5.js} +400 -100
  14. package/dist/{editor-owner-C9rVbMTs.js → editor-owner-CGj1wYCa.js} +1 -1
  15. package/dist/history/index.d.ts +1 -1
  16. package/dist/history/index.js +252 -178
  17. package/dist/hyperscript/index.d.ts +1 -1
  18. package/dist/hyperscript/index.js +1 -1
  19. package/dist/{hyperscript-CeT83ZLB.js → hyperscript-CT6hhnAY.js} +2 -2
  20. package/dist/{index-UrB4jAwl.d.ts → index-BT7D4vtf.d.ts} +5 -1
  21. package/dist/{index-BWPcE4ac.d.ts → index-BvQzYVAW.d.ts} +1 -1
  22. package/dist/{index-Db-ktCTE.d.ts → index-D7-n2GCk.d.ts} +6 -3
  23. package/dist/{index-BXjLmx1n.d.ts → index-DHt8nZQ6.d.ts} +143 -78
  24. package/dist/{index-Dq3Jlj8O.d.ts → index-PDROnF1G.d.ts} +1 -1
  25. package/dist/{index-DVMNewDn.d.ts → index-VZrKWWeh.d.ts} +20 -13
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.js +4 -4
  28. package/dist/internal/index.d.ts +2 -2
  29. package/dist/internal/index.js +4 -4
  30. package/dist/{mapped-view-store-CbWqba_1.js → mapped-view-store-CBk2-bDR.js} +1 -1
  31. package/dist/pagination/index.d.ts +1 -1
  32. package/dist/pagination/index.js +1 -1
  33. package/dist/pagination/react.d.ts +2 -2
  34. package/dist/pagination/react.js +5 -5
  35. package/dist/{pagination-CBdYiOuR.js → pagination-Cs5ka6hW.js} +1 -1
  36. package/dist/{plugin-SR3HTH0j.js → plugin-Bm6nsPHh.js} +1984 -751
  37. package/dist/{range-geometry-CdltxcH6.js → range-geometry-D1XfYWs0.js} +2 -2
  38. package/dist/{range-geometry-Dwp2oyCc.d.ts → range-geometry-DO-kbNrb.d.ts} +1 -1
  39. package/dist/react/index.d.ts +4 -4
  40. package/dist/react/index.js +6 -6
  41. package/dist/react/virtualized.d.ts +2 -2
  42. package/dist/react/virtualized.js +1 -1
  43. package/dist/{react-CN-iBh1z.js → react-BYtwRr4v.js} +18 -9
  44. package/dist/{retraction-BmPJB9cE.js → retraction-DnEUo8oE.js} +18 -2
  45. package/dist/{src-B-zm0kz4.js → src-DIQDddmh.js} +227 -40
  46. package/dist/{store-51r4zpCR.js → store-BLYxJgOU.js} +35 -5
  47. package/dist/testing/index.d.ts +2 -2
  48. package/dist/testing/index.js +3 -3
  49. package/dist/{use-editor-dom-scope-uDJQ692F.js → use-editor-dom-scope-hT7W9d-p.js} +1089 -606
  50. package/dist/yjs/index.d.ts +1 -1
  51. package/dist/yjs/index.js +1 -1
  52. package/dist/yjs/react/index.d.ts +3 -3
  53. package/dist/yjs/react/index.js +3 -3
  54. package/dist/{yjs-IGE0Al3n.js → yjs-C_g9gZwI.js} +6 -3
  55. package/package.json +1 -1
  56. package/dist/native-grouping-input-DXNhlPHd.js +0 -8
@@ -1,5 +1,5 @@
1
- import { $f as PathApi, B as NodeApi, Ba as getCaretOwner, Bt as point, Cl as getPluginContributions, Cu as getEditorRuntime, Du as hasEditorRuntime, Ea as isTextCell, Ei as withUpdateTagContext, En as attachTransactionSpecAfterCommit, Et as isInline, Eu as getEditorSchema, F as getActiveCommandEditor, Fd as DocumentIndex, Gf as RangeApi, Go as txLocate, Hs as EditorSchemaValidationError, Il as getCompiledSchemaPropertyId, Jf as PointApi, Kf as LocationApi, Kr as resolveEditorNodeKeyForNode, Lt as next, M as dispatchCommand, Ma as nodes, N as evaluateCommand, Os as mapSelectionThroughChange, P as evaluateCommandWithState, Pn as getActiveEditorTransaction, Qa as resolveParkedCaret, Rn as getBaseCallRoot, Ts as getSelectionDOMRange, Tu as getEditorRuntimeRoot, U as after, Ua as holdsCaret, V as above, Va as getPlacementGeneration, W as before, Wt as range, Ya as placedSince, _n as afterActiveTransactionEnds, al as toInternalRoot, at as getNodeKey, bt as isBlock, ca as withLandingBlock, cp as countCoreWork, ct as getSelection$1, da as readRemovalLanding, dn as voidEditor, du as definePluginPoint, fi as subscribeCaretTarget, ft as hasPath, gd as valueRoot, gi as toEditorCoreStateView, gu as formatDebugValue, hl as reportEditorLifecycleError, ho as getOwnViewPresentation, hp as getDefined, hu as ElementApi, if as getNodeKeyForNode, il as getPublicExplicitLocationRoot, ki as captureSliceLanding, kt as isVoid$2, ku as defineCommand, l as definePlugin, lc as ContentSlice, lr as getNodeTargetRoot, ls as getCompiledEditorSchemaFromApi, lt as getSnapshot, m as getInstalledPlugin, md as mapInternalDocumentChangePosition, mu as SelectionApi, ni as setEditorFocused, no as setSelectionAsView, ol as toPublicRoot, ot as getPathByNodeKey, pd as mapInternalDocumentChangePoint, pn as editorCommands, pr as getSetSite, sn as unhangRange, tr as getEditorStateView, tt as getChildren, uc as createDetachedContentSlice, ud as hasInternalDocumentChangeRoot, us as getInternalEditorSchemaFromApi, uu as failInvariant, vo as getViewFollowTarget, wc as getEditorCommitValue, wl as getPluginRegistry, wu as getEditorRuntimeOwner, xc as getEditorCommitSnapshot, xl as getCompiledEditorSchema, xn as applyTransactionSpec, yu as TextApi } from "./plugin-SR3HTH0j.js";
2
- import { a as transferEntries, n as checkFilesLanding, r as checkTransfer } from "./src-B-zm0kz4.js";
1
+ import { Au as ElementApi, B as NodeApi, Bt as point, Bu as getEditorRuntimeOwner, Ef as getNodeKeyForNode, En as attachTransactionSpecAfterCommit, Et as isInline, Eu as definePluginPoint, F as getActiveCommandEditor, Fd as mapInternalDocumentChangePosition, Gu as defineCommand, Hu as getEditorSchema, Il as getPluginContributions, Is as mapSelectionThroughChange, Jr as resolveEditorNodeKeyForNode, Ka as getCaretOwner, Ld as valueRoot, Ll as getPluginRegistry, Lt as next, M as dispatchCommand, Ma as isTextCell, N as evaluateCommand, Ns as getSelectionDOMRange, Oc as getEditorCommitSnapshot, Oi as withUpdateTagContext, Ol as reportEditorLifecycleError, P as evaluateCommandWithState, Pd as mapInternalDocumentChangePoint, Pl as getCompiledEditorSchema, Pn as getActiveEditorTransaction, Pu as TextApi, Qn as getEditorReadDepth, Ra as nodes, Rn as getBaseCallRoot, Rp as getDefined, Sp as PathApi, Tu as failInvariant, U as after, Uu as hasEditorRuntime, V as above, Vu as getEditorRuntimeRoot, W as before, Wt as range, Ya as holdsCaret, Yl as getCompiledSchemaPropertyId, Zo as txLocate, _a as readRemovalLanding, _c as createDetachedContentSlice, _n as afterActiveTransactionEnds, _p as PointApi, _s as getCompiledEditorSchemaFromApi, at as getNodeKey, bt as isBlock, co as setSelectionAsView, ct as getSelection$1, dn as voidEditor, ft as hasPath, gc as ContentSlice, hl as toPublicRoot, hp as LocationApi, hu as EditorSchemaValidationError, ii as setEditorFocused, io as resolveParkedCaret, jc as getEditorCommitValue, jd as hasInternalDocumentChangeRoot, ji as captureSliceLanding, jp as countCoreWork, ju as formatDebugValue, kt as isVoid$2, ku as SelectionApi, l as definePlugin, lr as getNodeTargetRoot, lt as getSnapshot, m as getInstalledPlugin, ma as withLandingBlock, mi as subscribeCaretTarget, ml as toInternalRoot, mp as RangeApi, ot as getPathByNodeKey, pl as getPublicExplicitLocationRoot, pn as editorCommands, pr as getSetSite, qa as getPlacementGeneration, rf as DocumentIndex, sn as unhangRange, to as placedSince, tr as getEditorStateView, tt as getChildren, vi as toEditorCoreStateView, vs as getInternalEditorSchemaFromApi, wo as getViewFollowTarget, xn as applyTransactionSpec, xo as getOwnViewPresentation, zu as getEditorRuntime } from "./plugin-Bm6nsPHh.js";
2
+ import { a as transferEntries, c as dispatchPaste, n as checkFilesLanding, r as checkTransfer, u as landPaste } from "./src-DIQDddmh.js";
3
3
  import scrollIntoViewIfNeeded from "scroll-into-view-if-needed";
4
4
  //#region src/dom/utils/dom.ts
5
5
  globalThis.Node;
@@ -22,13 +22,21 @@ const isDOMComment = (value) => isDOMNode(value) && value.nodeType === 8;
22
22
  * Check if a DOM node is an element node.
23
23
  */
24
24
  const isDOMElement = (value) => isDOMNode(value) && value.nodeType === 1;
25
+ const isDOMInstance = (value, key) => {
26
+ const GlobalConstructor = globalThis[key];
27
+ if (typeof GlobalConstructor === "function" && value instanceof GlobalConstructor) return true;
28
+ const view = getDefaultView(value);
29
+ if (!view || view === globalThis) return false;
30
+ const ViewConstructor = view[key];
31
+ return typeof ViewConstructor === "function" && value instanceof ViewConstructor;
32
+ };
25
33
  /**
26
34
  * Check if a value is a DOM node.
27
35
  */
28
- const isDOMNode = (value) => {
29
- const Node = getDefaultView(value)?.Node;
30
- return typeof Node === "function" && value instanceof Node;
31
- };
36
+ const isDOMNode = (value) => isDOMInstance(value, "Node");
37
+ const isDOMHTMLElement = (value) => isDOMInstance(value, "HTMLElement");
38
+ const isDOMInputOrTextArea = (value) => isDOMInstance(value, "HTMLInputElement") || isDOMInstance(value, "HTMLTextAreaElement");
39
+ const isDOMTableRowElement = (value) => isDOMInstance(value, "HTMLTableRowElement");
32
40
  /**
33
41
  * Check if a value is a DOM selection.
34
42
  */
@@ -171,6 +179,27 @@ const markPlainTextPaste = (data) => {
171
179
  plainTextPastes.add(data);
172
180
  };
173
181
  const isPlainTextPaste = (data) => plainTextPastes.has(data);
182
+ const CUT_MIME_TYPE = "application/x-editor-cut";
183
+ const catchTagName = /^<[A-Za-z][^\s/>]*/;
184
+ const catchLeadingEditorCut = /^<[A-Za-z][^\s/>]*\s+data-editor-cut="([^"]*)"/;
185
+ const readClipboardCut = (data) => {
186
+ if (isPlainTextPaste(data)) return null;
187
+ const id = data.getData(CUT_MIME_TYPE);
188
+ if (id) return id;
189
+ for (const [tag] of data.getData("text/html").matchAll(catchOpeningHtmlTag)) if (catchEditorFragment.test(tag)) return tag.match(catchLeadingEditorCut)?.[1] ?? null;
190
+ return null;
191
+ };
192
+ const writeClipboardCut = (data, id) => {
193
+ const html = data.getData("text/html");
194
+ let tagged = false;
195
+ data.setData(CUT_MIME_TYPE, id);
196
+ if (!html) return;
197
+ data.setData("text/html", html.replace(catchOpeningHtmlTag, (tag) => {
198
+ if (tagged || !catchEditorFragment.test(tag)) return tag;
199
+ tagged = true;
200
+ return tag.replace(catchTagName, `$& data-editor-cut="${id}"`);
201
+ }));
202
+ };
174
203
  const readClipboardFragmentPayload = (data, clipboardFormatKey) => {
175
204
  if (isPlainTextPaste(data)) return null;
176
205
  const mime = `application/${clipboardFormatKey}`;
@@ -200,6 +229,10 @@ const getFlatTreeParentElement = (element) => {
200
229
  const ShadowRootConstructor = element.ownerDocument.defaultView?.ShadowRoot;
201
230
  return ShadowRootConstructor && root instanceof ShadowRootConstructor ? root.host : null;
202
231
  };
232
+ const pageOf = (document) => {
233
+ const frame = document.defaultView?.frameElement;
234
+ return frame ? pageOf(frame.ownerDocument) : document;
235
+ };
203
236
  /**
204
237
  * Retrieves the deepest active element in the DOM, considering nested shadow DOMs.
205
238
  */
@@ -1186,7 +1219,7 @@ const getPliteStringLength = (string) => {
1186
1219
  };
1187
1220
  const PLITE_STRING_SELECTOR = "[data-editor-string], [data-editor-zero-width]";
1188
1221
  const getPliteTextHostStrings = (textHost) => {
1189
- if (textHost instanceof HTMLElement && textHost.matches("[data-editor-string], [data-editor-zero-width]")) return [textHost];
1222
+ if (isDOMHTMLElement(textHost) && textHost.matches("[data-editor-string], [data-editor-zero-width]")) return [textHost];
1190
1223
  const owner = textHost.closest("[data-editor-node=\"text\"]");
1191
1224
  return Array.from(textHost.querySelectorAll(PLITE_STRING_SELECTOR)).filter((string) => string.closest("[data-editor-node=\"text\"]") === owner);
1192
1225
  };
@@ -1597,6 +1630,30 @@ const getOwnedPliteStrings = ({ root, target }) => {
1597
1630
  return root.contains(string) && (!owner || owner === root);
1598
1631
  });
1599
1632
  };
1633
+ const caretShowsPointOffTextFlowCharacters = ({ host, x, y }) => {
1634
+ const point = getNativeDOMPointAtCoordinates(host.ownerDocument, x, y);
1635
+ if (!point) return false;
1636
+ const [node, offset] = point;
1637
+ if (!isPointInside(point, host) || !isDOMText(node)) return true;
1638
+ const range = host.ownerDocument.createRange();
1639
+ range.setStart(...moveTextPoint(host, node, offset, -TEXT_FLOW_CARET_REACH));
1640
+ range.setEnd(...moveTextPoint(host, node, offset, TEXT_FLOW_CARET_REACH));
1641
+ return !getUsableRangeRects(range).some((rect) => x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom);
1642
+ };
1643
+ const TEXT_FLOW_CARET_REACH = 16;
1644
+ const moveTextPoint = (host, node, offset, units) => {
1645
+ const walker = host.ownerDocument.createTreeWalker(host, host.ownerDocument.defaultView?.NodeFilter.SHOW_TEXT ?? 4);
1646
+ let current = node;
1647
+ let at = offset + units;
1648
+ walker.currentNode = node;
1649
+ while (at < 0 || at > current.data.length) {
1650
+ const next = at < 0 ? walker.previousNode() : walker.nextNode();
1651
+ if (!next) return [current, at < 0 ? 0 : current.data.length];
1652
+ at = at < 0 ? at + next.data.length : at - current.data.length;
1653
+ current = next;
1654
+ }
1655
+ return [current, at];
1656
+ };
1600
1657
  const getRootEdgeCoordinatePlacement = ({ root, strings, x, y }) => {
1601
1658
  const rootRect = root.getBoundingClientRect();
1602
1659
  if (y < rootRect.top || y > rootRect.bottom) return null;
@@ -1735,6 +1792,37 @@ const getElementTextNodes = (element) => {
1735
1792
  };
1736
1793
  const TEXT_FLOW_LINE_BREAKS = /\r\n|[\n\r]/g;
1737
1794
  const TEXT_FLOW_UNPAINTED = /^(?:\r\n|[\n\r\uFEFF])$/;
1795
+ const GRAPHEME_CHUNK_LENGTH = 32;
1796
+ const codePointLengthAt = (data, offset) => (data.codePointAt(offset) ?? 0) > 65535 ? 2 : 1;
1797
+ const isTextFlowBreak = (unit) => unit === "\n" || unit === "\r" || unit === "\r\n";
1798
+ const isOnVisualRow = (rect, row) => getRectOverlap(rect, row) > Math.min(rect.height, row.height) / 2;
1799
+ function* getGraphemeRangesFrom(data, from) {
1800
+ let start = from;
1801
+ let length = GRAPHEME_CHUNK_LENGTH;
1802
+ while (start < data.length) {
1803
+ let chunkEnd = Math.min(start + length, data.length);
1804
+ if (chunkEnd < data.length && /[\uD800-\uDBFF]/.test(data[chunkEnd - 1])) chunkEnd += 1;
1805
+ const chunk = data.slice(start, chunkEnd);
1806
+ let next = chunkEnd;
1807
+ if (graphemeSegmenter) for (const { index, segment } of graphemeSegmenter.segment(chunk)) {
1808
+ const end = start + index + segment.length;
1809
+ if (end === chunkEnd && chunkEnd < data.length) {
1810
+ next = start + index;
1811
+ break;
1812
+ }
1813
+ yield [start + index, end];
1814
+ }
1815
+ else {
1816
+ let offset = start;
1817
+ for (const character of chunk) {
1818
+ yield [offset, offset + character.length];
1819
+ offset += character.length;
1820
+ }
1821
+ }
1822
+ if (next === start) length *= 2;
1823
+ start = next;
1824
+ }
1825
+ }
1738
1826
  const getTextFlowPointAtCoordinates = ({ host, x, y }) => {
1739
1827
  const nodes = getElementTextNodes(host).filter((node) => node.data !== "");
1740
1828
  const starts = [];
@@ -1743,6 +1831,7 @@ const getTextFlowPointAtCoordinates = ({ host, x, y }) => {
1743
1831
  starts.push(text.length);
1744
1832
  text += node.data;
1745
1833
  }
1834
+ if (nodes.length === 0) return null;
1746
1835
  const range = host.ownerDocument.createRange();
1747
1836
  const nodeIndexAt = (index) => {
1748
1837
  let low = 0;
@@ -1754,17 +1843,24 @@ const getTextFlowPointAtCoordinates = ({ host, x, y }) => {
1754
1843
  }
1755
1844
  return low;
1756
1845
  };
1757
- const pointAt = (index) => {
1758
- const nodeIndex = nodeIndexAt(index);
1846
+ const pointAt = (index, from = index) => {
1847
+ const nodeIndex = nodeIndexAt(from);
1759
1848
  return [nodes[nodeIndex], index - starts[nodeIndex]];
1760
1849
  };
1850
+ const probes = /* @__PURE__ */ new Map();
1851
+ const unitRectAt = (index) => {
1852
+ if (!probes.has(index)) {
1853
+ const end = index + codePointLengthAt(text, index);
1854
+ range.setStart(...pointAt(index));
1855
+ range.setEnd(...pointAt(end, end - 1));
1856
+ probes.set(index, getUsableRangeRects(range)[0] ?? null);
1857
+ }
1858
+ return probes.get(index) ?? null;
1859
+ };
1761
1860
  const paintedUnitAt = (from, step) => {
1762
1861
  for (let index = from; index >= 0 && index < text.length; index += step) {
1763
1862
  if (TEXT_FLOW_UNPAINTED.test(text[index])) continue;
1764
- const [node, offset] = pointAt(index);
1765
- range.setStart(node, offset);
1766
- range.setEnd(node, offset + 1);
1767
- const rect = getUsableRangeRects(range)[0];
1863
+ const rect = unitRectAt(index);
1768
1864
  if (rect) return {
1769
1865
  index,
1770
1866
  rect
@@ -1772,6 +1868,15 @@ const getTextFlowPointAtCoordinates = ({ host, x, y }) => {
1772
1868
  }
1773
1869
  return null;
1774
1870
  };
1871
+ const probesInSourceOrder = () => {
1872
+ let maxTop = Number.NEGATIVE_INFINITY;
1873
+ for (const [, rect] of [...probes].sort(([a], [b]) => a - b)) {
1874
+ if (!rect) continue;
1875
+ if (rect.bottom < maxTop) return false;
1876
+ maxTop = Math.max(maxTop, rect.top);
1877
+ }
1878
+ return true;
1879
+ };
1775
1880
  const firstIndexEndingBelowY = () => {
1776
1881
  let low = 0;
1777
1882
  let high = text.length;
@@ -1787,7 +1892,19 @@ const getTextFlowPointAtCoordinates = ({ host, x, y }) => {
1787
1892
  const below = paintedUnitAt(split, 1);
1788
1893
  const above = split > 0 ? paintedUnitAt(split - 1, -1) : null;
1789
1894
  const nearest = below && (!above || getRectVerticalDistance(below.rect, y) <= getRectVerticalDistance(above.rect, y)) ? below : above;
1790
- if (!nearest) return null;
1895
+ if (!nearest) {
1896
+ const rowStarts = [...text.matchAll(TEXT_FLOW_LINE_BREAKS)].map((match) => match.index + match[0].length);
1897
+ let low = 0;
1898
+ let high = rowStarts.length;
1899
+ while (low < high) {
1900
+ const middle = Math.floor((low + high) / 2);
1901
+ const rect = unitRectAt(rowStarts[middle] - 1);
1902
+ if (!rect) return null;
1903
+ if (rect.bottom <= y) low = middle + 1;
1904
+ else high = middle;
1905
+ }
1906
+ return (rowStarts.length > 0 || unitRectAt(0)) && probesInSourceOrder() ? pointAt(low === 0 ? 0 : rowStarts[low - 1]) : null;
1907
+ }
1791
1908
  if (!below || below.rect.top > y) {
1792
1909
  const from = above ? above.index + 1 : 0;
1793
1910
  const breaks = [...text.slice(from, below?.index ?? text.length).matchAll(TEXT_FLOW_LINE_BREAKS)];
@@ -1801,45 +1918,70 @@ const getTextFlowPointAtCoordinates = ({ host, x, y }) => {
1801
1918
  return pointAt(previousBreak ? from + previousBreak.index + previousBreak[0].length : from);
1802
1919
  }
1803
1920
  }
1804
- const lineStart = Math.max(text.lastIndexOf("\n", nearest.index), text.lastIndexOf("\r", nearest.index)) + 1;
1805
- const lineEnd = Math.min(...["\n", "\r"].map((lineBreak) => {
1806
- const index = text.indexOf(lineBreak, nearest.index);
1807
- return index === -1 ? text.length : index;
1808
- }));
1921
+ const row = nearest.rect;
1922
+ let low = 0;
1923
+ let high = nearest.index;
1924
+ while (low < high) {
1925
+ const middle = Math.floor((low + high) / 2);
1926
+ const unit = paintedUnitAt(middle, 1);
1927
+ if (unit && unit.index < nearest.index && unit.rect.top < row.top && !isOnVisualRow(unit.rect, row)) low = unit.index + 1;
1928
+ else high = middle;
1929
+ }
1930
+ if (!probesInSourceOrder()) return null;
1931
+ const rowStart = paintedUnitAt(low, 1)?.index ?? nearest.index;
1809
1932
  let best = null;
1810
- let onLine = false;
1811
- for (let nodeIndex = nodeIndexAt(lineStart); nodeIndex < nodes.length && starts[nodeIndex] < lineEnd; nodeIndex++) {
1812
- const node = nodes[nodeIndex];
1813
- const from = Math.max(lineStart - starts[nodeIndex], 0);
1814
- const to = Math.min(lineEnd - starts[nodeIndex], node.data.length);
1815
- const direction = getElementDirection(node.parentElement);
1816
- const offsets = getGraphemeBoundaryOffsets(node.data.slice(from, to));
1817
- for (let index = 0; index < offsets.length - 1; index++) {
1818
- const start = from + offsets[index];
1819
- const end = from + offsets[index + 1];
1820
- if (TEXT_FLOW_UNPAINTED.test(node.data.slice(start, end))) continue;
1821
- range.setStart(node, start);
1822
- range.setEnd(node, end);
1823
- const rects = getUsableRangeRects(range);
1824
- const rect = rects.find((candidate) => getRectOverlap(candidate, nearest.rect) > VISUAL_LINE_TOLERANCE);
1825
- if (!rect) {
1826
- if (onLine && rects.length > 0) return best?.point ?? null;
1827
- continue;
1828
- }
1829
- onLine = true;
1830
- if (x >= rect.left && x <= rect.right) {
1831
- const midpoint = rect.left + rect.width / 2;
1832
- return [node, (direction === "rtl" ? x > midpoint : x <= midpoint) ? start : end];
1833
- }
1834
- for (const [offset, edgeX] of [[start, direction === "rtl" ? rect.right : rect.left], [end, direction === "rtl" ? rect.left : rect.right]]) {
1835
- const distance = Math.abs(edgeX - x);
1836
- if (!best || distance < best.distance) best = {
1837
- distance,
1838
- point: [node, offset]
1839
- };
1840
- }
1933
+ let hit = null;
1934
+ let left = Number.POSITIVE_INFINITY;
1935
+ let right = Number.NEGATIVE_INFINITY;
1936
+ let last = null;
1937
+ let end = pointAt(rowStart);
1938
+ let reachedNearest = false;
1939
+ let wrapped = false;
1940
+ for (const [start, stop] of getGraphemeRangesFrom(text, rowStart)) {
1941
+ const unit = text.slice(start, stop);
1942
+ if (isTextFlowBreak(unit)) break;
1943
+ if (unit === "") continue;
1944
+ const from = pointAt(start);
1945
+ const to = pointAt(stop, stop - 1);
1946
+ const direction = getElementDirection(from[0].parentElement);
1947
+ range.setStart(...from);
1948
+ range.setEnd(...to);
1949
+ const rects = getUsableRangeRects(range);
1950
+ if (rects.length === 0) continue;
1951
+ const rect = rects.find((candidate) => isOnVisualRow(candidate, row));
1952
+ const startsNextRow = rect && last && (rect.top >= last.rect.bottom || rect.top > last.rect.top + last.rect.height / 2 && (direction === "rtl" ? rect.right >= right : rect.left <= left));
1953
+ if (!rect || startsNextRow) {
1954
+ wrapped = true;
1955
+ break;
1956
+ }
1957
+ reachedNearest ||= stop > nearest.index;
1958
+ left = Math.min(left, rect.left);
1959
+ right = Math.max(right, rect.right);
1960
+ last = {
1961
+ rect,
1962
+ space: unit.length === 1 && CSS_BREAK_WHITESPACE_PATTERN.test(unit),
1963
+ start: from
1964
+ };
1965
+ end = to;
1966
+ if (!hit && x >= rect.left && x <= rect.right) {
1967
+ const midpoint = rect.left + rect.width / 2;
1968
+ hit = (direction === "rtl" ? x > midpoint : x <= midpoint) ? from : to;
1969
+ }
1970
+ for (const [point, edgeX] of [[from, direction === "rtl" ? rect.right : rect.left], [to, direction === "rtl" ? rect.left : rect.right]]) {
1971
+ const distance = Math.abs(edgeX - x);
1972
+ if (!best || distance < best.distance) best = {
1973
+ distance,
1974
+ point
1975
+ };
1841
1976
  }
1842
1977
  }
1978
+ if (!reachedNearest) return null;
1979
+ if (hit) return hit;
1980
+ const logicalStart = pointAt(rowStart);
1981
+ const logicalEnd = wrapped && last?.space ? last.start : end;
1982
+ const rtl = getElementDirection(host) === "rtl";
1983
+ if (x > right) return rtl ? logicalStart : logicalEnd;
1984
+ if (x < left) return rtl ? logicalEnd : logicalStart;
1843
1985
  return best?.point ?? null;
1844
1986
  };
1845
1987
  const getTextOffsetInVisualLineByX = ({ line, textNode, x }) => {
@@ -2845,6 +2987,10 @@ const readDOMSelectionPoints = (selection) => {
2845
2987
  const sameDOMPoint = ([node, offset], [otherNode, otherOffset]) => node === otherNode && offset === otherOffset;
2846
2988
  const sameDOMSelectionPoints = (points, other) => points === null || other === null ? points === other : sameDOMPoint(points.anchor, other.anchor) && sameDOMPoint(points.focus, other.focus);
2847
2989
  const readDOMSelectionRecord = (tree) => RECORDS.get(tree) ?? null;
2990
+ const isDOMSelectionWriteEcho = (tree, points) => {
2991
+ const record = RECORDS.get(tree);
2992
+ return record?.source === "write" && sameDOMSelectionPoints(points, record.points);
2993
+ };
2848
2994
  const recordDOMSelection = (tree, points, source) => {
2849
2995
  RECORDS.set(tree, {
2850
2996
  points,
@@ -2884,6 +3030,15 @@ const readsSelectionAsHost = (tree) => tree.nodeType === tree.DOCUMENT_FRAGMENT_
2884
3030
  const writeDOMSelection = (tree, points) => {
2885
3031
  changeDOMSelection(tree, points);
2886
3032
  };
3033
+ /**
3034
+ * Write `points` as `tree`'s selection on the user's behalf and keep no
3035
+ * record, so the selection claim reads them as the user's own selection, as
3036
+ * it reads a native Shift-click.
3037
+ */
3038
+ const writeUserDOMSelection = (tree, points) => {
3039
+ changeDOMSelection(tree, points);
3040
+ forgetDOMSelectionRecord(tree);
3041
+ };
2887
3042
  const changeDOMSelection = (tree, points, beforeChange) => {
2888
3043
  const selection = getSelection(tree);
2889
3044
  if (!selection) return;
@@ -3893,6 +4048,28 @@ const registerTreesAbove = (element) => {
3893
4048
  }
3894
4049
  };
3895
4050
  const shadowRootOf = (host) => host.shadowRoot ?? SHADOW_ROOT_BY_HOST.get(host);
4051
+ /**
4052
+ * Whether the element itself holds focus. It walks up from the element, so a
4053
+ * closed shadow root nobody registered counts, and a host whose own shadow
4054
+ * tree holds focus does not.
4055
+ */
4056
+ const isElementFocused = (element) => {
4057
+ const frameDocument = "contentDocument" in element ? element.contentDocument : null;
4058
+ const inner = shadowRootOf(element) ?? frameDocument;
4059
+ if (inner?.activeElement && inner.activeElement !== frameDocument?.body) return false;
4060
+ let node = element;
4061
+ for (;;) {
4062
+ const tree = node.getRootNode();
4063
+ if (tree.activeElement !== node) return false;
4064
+ if ("host" in tree) {
4065
+ node = tree.host;
4066
+ continue;
4067
+ }
4068
+ const frame = tree.defaultView?.frameElement;
4069
+ if (!frame) return true;
4070
+ node = frame;
4071
+ }
4072
+ };
3896
4073
  const resolveInnermostElementAtPoint = (document, x, y) => {
3897
4074
  let element = document.elementFromPoint(x, y);
3898
4075
  for (let inner = element && shadowRootOf(element)?.elementFromPoint(x, y); inner && inner !== element; inner = shadowRootOf(element)?.elementFromPoint(x, y)) element = inner;
@@ -3907,6 +4084,7 @@ const focusedElementOf = (top) => {
3907
4084
  }
3908
4085
  return null;
3909
4086
  };
4087
+ const focusedElementOnPage = (node) => focusedElementOf(pageOf(node.ownerDocument ?? node));
3910
4088
  const outerElementOf = (element) => {
3911
4089
  if (element.parentElement) return element.parentElement;
3912
4090
  const parent = element.parentNode;
@@ -6226,7 +6404,7 @@ const writeDOMRangeData = (editor, data, range, options = {}) => {
6226
6404
  div.remove();
6227
6405
  return data;
6228
6406
  };
6229
- const insertDOMData = (editor, data) => dispatchCommand(editor, domCommands.insertData, data);
6407
+ const insertDOMData = (editor, data) => dispatchPaste(editor, () => readClipboardCut(data), () => landPaste(editor, () => dispatchCommand(editor, domCommands.insertData, data)));
6230
6408
  const createDOMDataTransactionSpec = (editor, data, state) => {
6231
6409
  const slice = readDOMFragmentData(editor, data);
6232
6410
  if (!slice) return createDataTransferTransactionSpec(editor, data, { state });
@@ -6274,8 +6452,7 @@ const writeDOMClipboardSlice = (editor, data, { formats = {}, slice }) => {
6274
6452
  };
6275
6453
  const insertDOMFragmentData = (editor, data) => {
6276
6454
  const slice = readDOMFragmentData(editor, data);
6277
- if (slice) return dispatchCommand(editor, editorCommands.replaceSlice, { slice });
6278
- return false;
6455
+ return dispatchPaste(editor, () => readClipboardCut(data), () => slice ? landPaste(editor, () => dispatchCommand(editor, editorCommands.replaceSlice, { slice })) : false);
6279
6456
  };
6280
6457
  const insertDOMTextData = (editor, data) => insertDataTransfer(editor, data, { mimeType: "text/plain" });
6281
6458
  //#endregion
@@ -7191,6 +7368,116 @@ const resolveVoidEventRange = (editor, { node, path, target, x, y }) => {
7191
7368
  return point$1 ? range(editor, point$1) : null;
7192
7369
  };
7193
7370
  //#endregion
7371
+ //#region src/dom/plugin/dom-scroll-into-view.ts
7372
+ const MARGIN = 4;
7373
+ const SCROLLABLE_RE = /(auto|scroll|overlay)/;
7374
+ const isUsableScrollRect = (r) => r.width > 0 || r.height > 0 || r.x !== 0 || r.y !== 0 || r.top !== 0 || r.left !== 0 || r.bottom !== 0 || r.right !== 0;
7375
+ const toScrollRect = (r) => ({
7376
+ bottom: r.bottom,
7377
+ left: r.left,
7378
+ right: r.right,
7379
+ top: r.top
7380
+ });
7381
+ const shiftRect = (r, dx, dy) => ({
7382
+ bottom: r.bottom - dy,
7383
+ left: r.left - dx,
7384
+ right: r.right - dx,
7385
+ top: r.top - dy
7386
+ });
7387
+ const canScroll = (el, style, axis) => {
7388
+ const overflow = axis === "y" ? `${style?.overflowY ?? ""} ${style?.overflow ?? ""}` : `${style?.overflowX ?? ""} ${style?.overflow ?? ""}`;
7389
+ return SCROLLABLE_RE.test(overflow) && (axis === "y" ? el.scrollHeight > el.clientHeight : el.scrollWidth > el.clientWidth);
7390
+ };
7391
+ const pad = (value, size) => {
7392
+ const n = Number.parseFloat(value ?? "");
7393
+ if (!Number.isFinite(n) || n <= 0) return 0;
7394
+ return value?.trim().endsWith("%") ? n / 100 * size : n;
7395
+ };
7396
+ const paddedBox = (rect, style) => ({
7397
+ bottom: rect.bottom - pad(style?.scrollPaddingBottom, rect.height) - MARGIN,
7398
+ left: rect.left + pad(style?.scrollPaddingLeft, rect.width) + MARGIN,
7399
+ right: rect.right - pad(style?.scrollPaddingRight, rect.width) - MARGIN,
7400
+ top: rect.top + pad(style?.scrollPaddingTop, rect.height) + MARGIN
7401
+ });
7402
+ const getVisibleViewportBox = (win, scrollingElement) => {
7403
+ const vv = win.visualViewport;
7404
+ const height = vv?.height ?? win.innerHeight;
7405
+ const width = vv?.width ?? win.innerWidth;
7406
+ const top = vv ? Math.min(Math.max(0, vv.pageTop - win.scrollY), Math.max(0, vv.offsetTop)) : 0;
7407
+ const left = vv ? Math.min(Math.max(0, vv.pageLeft - win.scrollX), Math.max(0, vv.offsetLeft)) : 0;
7408
+ return paddedBox({
7409
+ bottom: top + height,
7410
+ height,
7411
+ left,
7412
+ right: left + width,
7413
+ top,
7414
+ width
7415
+ }, win.getComputedStyle(scrollingElement));
7416
+ };
7417
+ const axisDelta = (start, end, low, high, ownLow, ownHigh) => {
7418
+ if (low >= high) return 0;
7419
+ if (start < low) {
7420
+ const d = low - start;
7421
+ return ownHigh === void 0 ? -d : -Math.min(d, Math.max(0, ownHigh - end));
7422
+ }
7423
+ if (end > high) {
7424
+ const d = end - high;
7425
+ return ownLow === void 0 ? d : Math.min(d, Math.max(0, start - ownLow));
7426
+ }
7427
+ return 0;
7428
+ };
7429
+ const scrollAncestors = (startElement, scrollingElement, rect, visibleBox) => {
7430
+ let cur = rect;
7431
+ for (let el = getFlatTreeParentElement(startElement); el; el = getFlatTreeParentElement(el)) {
7432
+ if (el === scrollingElement) continue;
7433
+ const style = el.ownerDocument.defaultView?.getComputedStyle(el);
7434
+ const scrollY = canScroll(el, style, "y");
7435
+ const scrollX = canScroll(el, style, "x");
7436
+ if (!scrollY && !scrollX) continue;
7437
+ const own = paddedBox(el.getBoundingClientRect(), style);
7438
+ const dy = scrollY ? visibleBox ? axisDelta(cur.top, cur.bottom, Math.max(own.top, visibleBox.top), Math.min(own.bottom, visibleBox.bottom), own.top, own.bottom) : axisDelta(cur.top, cur.bottom, own.top, own.bottom) : 0;
7439
+ const dx = scrollX ? visibleBox ? axisDelta(cur.left, cur.right, Math.max(own.left, visibleBox.left), Math.min(own.right, visibleBox.right), own.left, own.right) : axisDelta(cur.left, cur.right, own.left, own.right) : 0;
7440
+ if (dy === 0 && dx === 0) continue;
7441
+ const prevTop = el.scrollTop;
7442
+ const prevLeft = el.scrollLeft;
7443
+ el.scrollTop += dy;
7444
+ el.scrollLeft += dx;
7445
+ cur = shiftRect(cur, el.scrollLeft - prevLeft, el.scrollTop - prevTop);
7446
+ }
7447
+ return cur;
7448
+ };
7449
+ const scrollRectIntoViewIfNeeded = ({ rect, startElement }) => {
7450
+ const scrollingElement = startElement.ownerDocument.scrollingElement ?? startElement.ownerDocument.documentElement;
7451
+ let cur = scrollAncestors(startElement, scrollingElement, rect, null);
7452
+ const win = startElement.ownerDocument.defaultView;
7453
+ if (!win) return;
7454
+ let visible = getVisibleViewportBox(win, scrollingElement);
7455
+ const dy = scrollingElement.scrollHeight > scrollingElement.clientHeight ? axisDelta(cur.top, cur.bottom, visible.top, visible.bottom) : 0;
7456
+ const dx = scrollingElement.scrollWidth > scrollingElement.clientWidth ? axisDelta(cur.left, cur.right, visible.left, visible.right) : 0;
7457
+ if (dy !== 0 || dx !== 0) {
7458
+ const prevY = win.scrollY;
7459
+ const prevX = win.scrollX;
7460
+ win.scrollBy(dx, dy);
7461
+ cur = shiftRect(cur, win.scrollX - prevX, win.scrollY - prevY);
7462
+ visible = getVisibleViewportBox(win, scrollingElement);
7463
+ }
7464
+ if (cur.top < visible.top || cur.bottom > visible.bottom || cur.left < visible.left || cur.right > visible.right) scrollAncestors(startElement, scrollingElement, cur, visible);
7465
+ };
7466
+ const scrollDOMRangeIntoViewIfNeeded = (domRange, isBackward = false) => {
7467
+ const focusRange = domRange.cloneRange();
7468
+ focusRange.collapse(isBackward);
7469
+ const container = focusRange.startContainer;
7470
+ const leafEl = isDOMElement(container) ? container : container.parentElement;
7471
+ if (!leafEl) return;
7472
+ const domRect = focusRange.getBoundingClientRect();
7473
+ const targetRect = isUsableScrollRect(domRect) ? domRect : leafEl.getBoundingClientRect();
7474
+ if (!isUsableScrollRect(targetRect)) return;
7475
+ scrollRectIntoViewIfNeeded({
7476
+ rect: toScrollRect(targetRect),
7477
+ startElement: leafEl
7478
+ });
7479
+ };
7480
+ //#endregion
7194
7481
  //#region src/dom/plugin/dom-view-caret.ts
7195
7482
  const liftCaretOutOfCollapsedSection = (view, coverage, composing, selection) => {
7196
7483
  if (!RangeApi.isRange(selection) || !RangeApi.isCollapsed(selection)) return selection;
@@ -7212,7 +7499,7 @@ const resolveNextKeyCaret = (view, editable) => {
7212
7499
  };
7213
7500
  const ensureFocusCaret = (view, editable) => {
7214
7501
  const caret = resolveNextKeyCaret(view, editable);
7215
- if (!caret) {
7502
+ if (!caret && getEditorReadDepth(getEditorRuntimeOwner(view)) === 0) {
7216
7503
  const start = view.read.points.start([]);
7217
7504
  if (start) setSelectionAsView(view, start);
7218
7505
  }
@@ -7222,19 +7509,26 @@ const ensureFocusCaret = (view, editable) => {
7222
7509
  //#region src/dom/plugin/dom-editor.ts
7223
7510
  const EDITOR_TO_CANCEL_FOCUS_RETRY = /* @__PURE__ */ new WeakMap();
7224
7511
  const EDITOR_TO_FOCUS_REQUEST_GENERATION = /* @__PURE__ */ new WeakMap();
7225
- const ROOT_TO_FOCUS_REQUEST_OWNER = /* @__PURE__ */ new WeakMap();
7512
+ const PAGE_TO_FOCUS_REQUEST_OWNER = /* @__PURE__ */ new WeakMap();
7226
7513
  const supersedeFocusRequest = (editor) => {
7227
7514
  EDITOR_TO_FOCUS_REQUEST_GENERATION.set(editor, (EDITOR_TO_FOCUS_REQUEST_GENERATION.get(editor) ?? 0) + 1);
7228
7515
  EDITOR_TO_CANCEL_FOCUS_RETRY.get(editor)?.();
7229
7516
  EDITOR_TO_CANCEL_FOCUS_RETRY.delete(editor);
7230
7517
  };
7231
- const focusRetries = (options) => options?.retries ?? 50;
7232
- const claimFocusRequest = (editor, root) => {
7518
+ const readFocusRequest = (node) => node && PAGE_TO_FOCUS_REQUEST_OWNER.get(pageOf(node.ownerDocument ?? node));
7519
+ const watchFocusSuperseded = (editor, node) => {
7520
+ const page = node ?? resolveLastEditorWindow(editor)?.document;
7521
+ const generation = EDITOR_TO_FOCUS_REQUEST_GENERATION.get(editor);
7522
+ const owner = readFocusRequest(page);
7523
+ return () => EDITOR_TO_FOCUS_REQUEST_GENERATION.get(editor) !== generation || readFocusRequest(page) !== owner;
7524
+ };
7525
+ const isFocusRequestedElsewhere = (editor, node) => {
7526
+ const holder = readFocusRequest(node)?.editor.deref();
7527
+ return !!holder && holder !== editor && holder !== reachView(editor);
7528
+ };
7529
+ const claimFocusRequest = (editor, element) => {
7233
7530
  supersedeFocusRequest(editor);
7234
- ROOT_TO_FOCUS_REQUEST_OWNER.set(root, {
7235
- editor,
7236
- generation: EDITOR_TO_FOCUS_REQUEST_GENERATION.get(editor) ?? 0
7237
- });
7531
+ PAGE_TO_FOCUS_REQUEST_OWNER.set(pageOf(element.ownerDocument), { editor: new WeakRef(editor) });
7238
7532
  };
7239
7533
  const getLastChildren = (element) => {
7240
7534
  if (element.childElementCount > 0) return getLastChildren(element.children[0]);
@@ -7581,8 +7875,9 @@ const DOMEditorImpl = {
7581
7875
  const el = DOMEditor.editable(editor);
7582
7876
  const root = DOMEditor.resolveDocumentOrShadowRoot(editor);
7583
7877
  if (!el || !root) return;
7584
- if (ROOT_TO_FOCUS_REQUEST_OWNER.get(root)?.editor === editor) ROOT_TO_FOCUS_REQUEST_OWNER.delete(root);
7585
- if (root.activeElement === el) el.blur();
7878
+ const focusElement = findDOMRootRuntime(el)?.nodeSelectionFocus();
7879
+ if (focusElement && isElementFocused(focusElement)) focusElement.blur();
7880
+ else if (isElementFocused(el)) el.blur();
7586
7881
  },
7587
7882
  deselect: (editor) => {
7588
7883
  const selection = editor.read((state) => state.selection());
@@ -7667,25 +7962,25 @@ const DOMEditorImpl = {
7667
7962
  },
7668
7963
  resolvePath: (editor, node) => resolvePliteNodePath(editor, node),
7669
7964
  focus: (editor, options = {}) => {
7670
- const retries = focusRetries(options);
7671
- const focusRequestGeneration = (EDITOR_TO_FOCUS_REQUEST_GENERATION.get(editor) ?? 0) + 1;
7672
- EDITOR_TO_FOCUS_REQUEST_GENERATION.set(editor, focusRequestGeneration);
7965
+ const retries = options.retries ?? 50;
7966
+ supersedeFocusRequest(editor);
7673
7967
  const el = DOMEditor.editable(editor);
7674
7968
  const root = DOMEditor.resolveDocumentOrShadowRoot(editor);
7675
7969
  if (!el || !root) return;
7676
- const focusRequestOwner = {
7677
- editor,
7678
- generation: focusRequestGeneration
7679
- };
7680
- ROOT_TO_FOCUS_REQUEST_OWNER.set(root, focusRequestOwner);
7681
7970
  if (retries <= 0) return;
7971
+ PAGE_TO_FOCUS_REQUEST_OWNER.set(pageOf(el.ownerDocument), { editor: new WeakRef(editor) });
7972
+ const superseded = watchFocusSuperseded(editor, el);
7973
+ const markAndFocus = () => {
7974
+ IS_FOCUSED.set(editor, true);
7975
+ setEditorFocused(editor, true);
7976
+ el.focus({ preventScroll: true });
7977
+ };
7682
7978
  if (IS_NODE_MAP_DIRTY.get(editor)) {
7683
- EDITOR_TO_CANCEL_FOCUS_RETRY.get(editor)?.();
7684
7979
  let cancel = () => {};
7685
7980
  const generation = getPlacementGeneration(editor);
7686
7981
  cancel = scheduleEditorDOMPhase(editor, "dom-write", "dom-editor-focus-retry", () => {
7687
7982
  if (EDITOR_TO_CANCEL_FOCUS_RETRY.get(editor) === cancel) EDITOR_TO_CANCEL_FOCUS_RETRY.delete(editor);
7688
- if (ROOT_TO_FOCUS_REQUEST_OWNER.get(root) !== focusRequestOwner || placedSince(editor, generation)) return;
7983
+ if (superseded() || placedSince(editor, generation)) return;
7689
7984
  DOMEditor.focus(editor, { retries: retries - 1 });
7690
7985
  }, {
7691
7986
  delay: 10,
@@ -7695,9 +7990,9 @@ const DOMEditorImpl = {
7695
7990
  EDITOR_TO_CANCEL_FOCUS_RETRY.set(editor, cancel);
7696
7991
  return;
7697
7992
  }
7698
- EDITOR_TO_CANCEL_FOCUS_RETRY.get(editor)?.();
7699
- EDITOR_TO_CANCEL_FOCUS_RETRY.delete(editor);
7993
+ if (findDOMRootRuntime(el)?.focusSelection(el)) return;
7700
7994
  const selection = ensureFocusCaret(editor, el);
7995
+ if (superseded()) return;
7701
7996
  const selectionAtFocus = selection ? getSelectionDOMRange(editor, selection) : null;
7702
7997
  const syncDomSelection = () => {
7703
7998
  if (findDOMRootRuntime(el)?.isSelectionHeld()) return;
@@ -7726,7 +8021,7 @@ const DOMEditorImpl = {
7726
8021
  };
7727
8022
  let ownedActiveElement = root.activeElement === el || root.activeElement && containsShadowAware(el, root.activeElement) ? root.activeElement : null;
7728
8023
  const settleFocus = () => {
7729
- if (EDITOR_TO_FOCUS_REQUEST_GENERATION.get(editor) !== focusRequestGeneration || ROOT_TO_FOCUS_REQUEST_OWNER.get(root) !== focusRequestOwner) return;
8024
+ if (superseded()) return;
7730
8025
  if (DOMEditor.editable(editor) !== el || !el.isConnected || el.getRootNode() !== root) return;
7731
8026
  const rootActiveElement = root.activeElement;
7732
8027
  const shadowHost = "host" in root ? root.host : null;
@@ -7740,9 +8035,8 @@ const DOMEditorImpl = {
7740
8035
  return;
7741
8036
  }
7742
8037
  if (!(activeElement === null || activeElement === el.ownerDocument.body || rootActiveElement === null && activeElement === shadowHost || activeElement === ownedActiveElement && !activeElement.isConnected)) return;
7743
- IS_FOCUSED.set(editor, true);
7744
- setEditorFocused(editor, true);
7745
- el.focus({ preventScroll: true });
8038
+ markAndFocus();
8039
+ if (superseded()) return;
7746
8040
  trySyncDomSelection();
7747
8041
  };
7748
8042
  const scheduleFocusSettle = () => {
@@ -7761,14 +8055,16 @@ const DOMEditorImpl = {
7761
8055
  });
7762
8056
  };
7763
8057
  if (root.activeElement !== el) {
7764
- IS_FOCUSED.set(editor, true);
7765
- setEditorFocused(editor, true);
7766
8058
  const { activeElement } = root;
7767
- if (isDOMElement(activeElement) && containsShadowAware(el, activeElement) && "blur" in activeElement && typeof activeElement.blur === "function") activeElement.blur();
7768
- el.focus({ preventScroll: true });
8059
+ if (isDOMElement(activeElement) && containsShadowAware(el, activeElement) && "blur" in activeElement && typeof activeElement.blur === "function") {
8060
+ activeElement.blur();
8061
+ if (superseded()) return;
8062
+ }
8063
+ markAndFocus();
8064
+ if (superseded()) return;
7769
8065
  trySyncDomSelection();
7770
8066
  if (selectionAtFocus) scheduleEditorDOMPhase(editor, "selection-repair", "dom-editor-focus-selection-sync", () => {
7771
- if (root.activeElement !== el) return;
8067
+ if (superseded() || !isElementFocused(el)) return;
7772
8068
  const currentSelection = getSelectionDOMRange(editor, resolveNextKeyCaret(editor, el));
7773
8069
  if (!currentSelection || !RangeApi.equals(currentSelection, selectionAtFocus)) return;
7774
8070
  trySyncDomSelection();
@@ -7888,6 +8184,7 @@ const DOMEditorImpl = {
7888
8184
  },
7889
8185
  scroll: (editor) => getRegisteredScrollElement(editor) ?? DOMEditor.root(editor) ?? DOMEditor.editable(editor) ?? null,
7890
8186
  scrollIntoView: (editor, target, options = { scrollMode: "if-needed" }) => {
8187
+ const usesDefaultReveal = typeof options === "object" && options !== null && (options.scrollMode === void 0 || options.scrollMode === "if-needed") && options.block === void 0 && options.inline === void 0 && options.behavior === void 0 && options.boundary === void 0 && options.skipOverflowHiddenElements === void 0;
7891
8188
  const requestedScrollMarginTop = PathApi.isPath(target) ? (() => {
7892
8189
  const node = editor.read((state) => state.nodes.get(target)?.[0]);
7893
8190
  const element = node ? DOMEditor.resolveDOMNode(editor, node) : null;
@@ -7911,6 +8208,12 @@ const DOMEditorImpl = {
7911
8208
  left: scrollElement.scrollLeft,
7912
8209
  top: scrollElement.scrollTop + elementRect.top - scrollRect.top - requestedScrollMarginTop
7913
8210
  });
8211
+ } else if (usesDefaultReveal) {
8212
+ const rect = element.getBoundingClientRect();
8213
+ if (isUsableScrollRect(rect)) scrollRectIntoViewIfNeeded({
8214
+ rect: toScrollRect(rect),
8215
+ startElement: element
8216
+ });
7914
8217
  } else scrollIntoViewIfNeeded(element, options);
7915
8218
  }
7916
8219
  return;
@@ -7924,9 +8227,17 @@ const DOMEditorImpl = {
7924
8227
  if (!leafElement) return;
7925
8228
  if (PointApi.isPoint(target)) revealInEditableRoot(leafElement, target.path);
7926
8229
  else if (RangeApi.isRange(target)) revealInEditableRoot(leafElement, RangeApi.start(target).path);
8230
+ if (usesDefaultReveal) {
8231
+ const range = RangeApi.isRange(target) ? target : PointApi.isPoint(target) ? null : editor.read((state) => state.selection());
8232
+ scrollDOMRangeIntoViewIfNeeded(domRange, Boolean(range && RangeApi.isBackward(range)));
8233
+ return;
8234
+ }
7927
8235
  const hadOwnRect = Object.hasOwn(leafElement, "getBoundingClientRect");
7928
8236
  const originalGetBoundingClientRect = leafElement.getBoundingClientRect;
7929
- leafElement.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
8237
+ leafElement.getBoundingClientRect = () => {
8238
+ const rangeRect = domRange.getBoundingClientRect();
8239
+ return isUsableScrollRect(rangeRect) ? rangeRect : originalGetBoundingClientRect.call(leafElement);
8240
+ };
7930
8241
  try {
7931
8242
  scrollIntoViewIfNeeded(leafElement, options);
7932
8243
  } finally {
@@ -8136,7 +8447,7 @@ const DOMEditorImpl = {
8136
8447
  ({focusNode} = domRange);
8137
8448
  const firstRange = readDOMSelectionRange(domRange);
8138
8449
  const lastRange = readDOMSelectionRange(domRange, domRange.rangeCount - 1);
8139
- if (focusNode instanceof HTMLTableRowElement && firstRange.startContainer instanceof HTMLTableRowElement && lastRange.startContainer instanceof HTMLTableRowElement) {
8450
+ if (isDOMTableRowElement(focusNode) && isDOMTableRowElement(firstRange.startContainer) && isDOMTableRowElement(lastRange.startContainer)) {
8140
8451
  const firstNodeRow = firstRange.startContainer;
8141
8452
  const lastNodeRow = lastRange.startContainer;
8142
8453
  const firstNode = getLastChildren(firstNodeRow.children[firstRange.startOffset]);
@@ -8146,7 +8457,7 @@ const DOMEditorImpl = {
8146
8457
  else anchorNode = lastNode;
8147
8458
  if (firstNode.childNodes.length > 0) focusNode = firstNode.childNodes[0];
8148
8459
  else focusNode = firstNode;
8149
- if (lastNode instanceof HTMLElement) anchorOffset = lastNode.innerHTML.length;
8460
+ if (isDOMHTMLElement(lastNode)) anchorOffset = lastNode.innerHTML.length;
8150
8461
  else anchorOffset = 0;
8151
8462
  } else if (firstRange.startContainer === focusNode) {
8152
8463
  anchorNode = lastRange.endContainer;
@@ -8418,12 +8729,7 @@ const createDOMEditorCapability = (editor) => {
8418
8729
  };
8419
8730
  const capability = {
8420
8731
  blur: () => {
8421
- const view = reachView(editor);
8422
- const el = DOMEditorImpl.editable(view);
8423
- const focusElement = el && findDOMRootRuntime(el)?.nodeSelectionFocus();
8424
- const held = !!focusElement && focusElement.getRootNode().activeElement === focusElement;
8425
- DOMEditorImpl.blur(view);
8426
- if (held) focusElement.blur();
8732
+ DOMEditor.blur(editor);
8427
8733
  },
8428
8734
  deselect: () => {
8429
8735
  DOMEditor.deselect(editor);
@@ -8435,12 +8741,6 @@ const createDOMEditorCapability = (editor) => {
8435
8741
  findKey: (node) => DOMEditor.findKey(editor, node),
8436
8742
  assertPath: (node) => DOMEditor.assertPath(editor, node),
8437
8743
  focus: (options) => {
8438
- const view = reachView(editor);
8439
- const el = DOMEditorImpl.editable(view);
8440
- if (focusRetries(options) > 0 && el) {
8441
- claimFocusRequest(view, el.getRootNode());
8442
- if (findDOMRootRuntime(el)?.focusSelection(el)) return;
8443
- }
8444
8744
  DOMEditor.focus(editor, options);
8445
8745
  },
8446
8746
  getWindow: () => DOMEditor.getWindow(editor),
@@ -9217,4 +9517,4 @@ const keyToDataAttribute = (key) => `data-editor-${toKebabCase(key)}`;
9217
9517
  /** Return DOM data attribute names that mirror primitive node properties. */
9218
9518
  const getNodeDataAttributeKeys = (node) => Object.keys(node).filter((key) => typeof node[key] !== "object" && (!TextApi.isText(node) || key !== "text")).map((key) => keyToDataAttribute(key));
9219
9519
  //#endregion
9220
- export { copyIntentOf as $, EDITOR_TO_RUNTIME_ID_TO_ELEMENTS as $n, readDOMSelectionPoints as $t, findDOMPointElementInRoot as A, getUsableRangeRects as An, isSoftLineEndBetween as At, setEditorDOMRootElement as B, setDOMTextFlowRecordIndex as Bn, findDOMRootRuntime as Bt, normalizeRange as C, getPliteStringEdgeOffset as Cn, isDOMElement as Cr, observeDataTransferInsertion as Ct, DOMEditor as D, getPliteTextHostBounds as Dn, isPlainTextOnlyPaste as Dr, SOFT_LINE_END_SELECTOR as Dt, verifyDiffState as E, getPliteStringPlacementDOMPoint as En, isDOMText as Er, SOFT_LINE_END as Et, resolveDOMPointInRoot as F, resolveDOMTextFlowEntry as Fn, recordSoftLineEnd as Ft, ensureFocusCaret as G, EDITOR_TO_FORCE_RENDER as Gn, isDOMSyncMutation as Gt, subscribeEditorDOMScope as H, DOMCoverage as Hn, getEditorDOMRoot as Ht, resolveDOMRangeInRoot as I, resolveDOMTextFlowInsertTarget as In, resolveSoftLineEndDOMPoint as It, eventCarriesBlockFragment as J, EDITOR_TO_PENDING_DIFFS as Jn, scheduleEditorDOMPhase as Jt, liftCaretOutOfCollapsedSection as K, EDITOR_TO_KEY_TO_ELEMENT as Kn, markDOMSyncMutationTarget as Kt, resolveWrittenDOMRange as L, resolveDOMTextFlowOffset as Ln, findMountedDOMNodeByPath as Lt, getOrCreateDOMNodeKey as M, isDOMTextFlowSegmentSynchronized as Mn, noteAfterInsertCaret as Mt, isSelectableDOMSelection as N, readDOMTextFlowPaint as Nn, readAfterInsertCaret as Nt, DOMResolutionError as O, getPliteTextHostStrings as On, markPlainTextPaste as Or, SOFT_LINE_FLAG as Ot, isTrackedMutation as P, releaseDOMTextFlowRecordIndex as Pn, readLowerSoftLineEnd as Pt, walkClipChain as Q, EDITOR_TO_ROOT_VIEW_EDITORS as Qn, getDOMRangeSelectionPoints as Qt, setEditableRootReveal as R, resolveDOMTextFlowRecordDOMText as Rn, resolvePliteNodePath as Rt, normalizePoint as S, getPliteStringDocumentOffset as Sn, isBefore as Sr, dataTransferFormats as St, targetRange as T, getPliteStringPlacementAtX as Tn, isDOMSelection as Tr, Key as Tt, supersedeFocusRequest as U, isCollapsedDOMCoverageBoundary as Un, resolveDOMReach as Ut, setEditorDOMScrollElement as V, setDOMTextFlowRecordIndexes as Vn, findEditorDOMRootRuntime as Vt, writeViewSelectionPart as W, EDITOR_TO_ELEMENT as Wn, resolveDOMTargetView as Wt, getDragAutoScrollTarget as X, EDITOR_TO_PENDING_SELECTION as Xn, forgetDOMSelectionRecord as Xt, resolveBlockFragmentDropRange as Y, EDITOR_TO_PENDING_INSERTION_MARKS as Yn, changeDOMSelection as Yt, intersectClipChain as Z, EDITOR_TO_PLACEHOLDER_ELEMENT as Zn, forgetDOMSelectionRecordWithin as Zt, TRIPLE_CLICK as _, createDOMGeometryKernel as _n, getDefaultView as _r, domCommands as _t, isLeaf as a, writeDOMSelection as an, ELEMENT_TO_EDITOR as ar, cancelDragRest as at, longestCommonPrefixLength as b, getPliteStringCoordinatePlacement as bn, hasShadowRoot as br, writeDOMFragmentData as bt, isText as c, CAN_USE_DOM as cn, IS_FOCUSED as cr, isDragSessionClaimed as ct, Hotkeys as d, isAndroidDOMHost as dn, NODE_TO_ELEMENT as dr, settleDragSession as dt, readDOMSelectionRange as en, EDITOR_TO_RUNTIME_ID_TO_KEY as er, indicateDOMDropTarget as et, getLineBoundaryKeyboardMove as f, isBlinkDOMHost as fn, NODE_TO_INDEX as fr, takeDragSession as ft, isHotkey as g, usesAppleDOMHotkeys as gn, getActiveElement as gr, cleanDOMClipboardContents as gt, createCompiledHotkeyMatcher as h, supportsDOMBeforeInput as hn, containsShadowAware as hr, subscribeDropIndicator as ht, isElement as i, sameDOMSelectionPoints as in, EDITOR_TO_WINDOW as ir, beginDragSession as it, getEditorDOMHostScrollElement as j, hasUsableDOMRect as jn, isSoftLineTextStale as jt, createDOMEditorCapability as k, getTextFlowPointAtCoordinates as kn, normalizeDOMPoint as kr, clearAfterInsertCaret as kt, isVoid as l, getDOMHostLanguage as ln, IS_NODE_MAP_DIRTY as lr, readDragSession as lt, ariaKeyShortcuts as m, isWebKitDOMHost as mn, closestShadowAware as mr, readDropIndicator as mt, getNodeDataAttributeKeys as n, readsSelectionAsHost as nn, EDITOR_TO_USER_MARKS as nr, resolveDOMDropTarget as nt, isNode as o, enableKernelTraceRetention as on, ELEMENT_TO_NODE as or, clearDragScrollRepaint as ot, isPasteWithoutFormatting as p, isGeckoDOMHost as pn, NODE_TO_PARENT as pr, publishDropIndicator as pt, resolveNextKeyCaret as q, EDITOR_TO_PENDING_ACTION as qn, watchDOMSyncTextMarks as qt, isEditor as r, recordDOMSelection as rn, EDITOR_TO_USER_SELECTION as rr, restDOMBlockDrag as rt, isString as s, selectDOMInputDefaultActionPhase as sn, IS_COMPOSING as sr, clearDragSession as st, getElements as t, readDOMSelectionRecord as tn, EDITOR_TO_SCHEDULE_FLUSH as tr, pointAt as tt, keyToDataAttribute as u, hasDOMHostQuirk as un, IS_READ_ONLY as ur, setDragScrollRepaint as ut, dom as v, getNearestPliteStringRect as vn, getFlatTreeParentElement as vr, getDOMClipboardFormatKey as vt, normalizeStringDiff as w, getPliteStringLength as wn, isDOMNode as wr, writeDataTransferFragment as wt, mergeStringDiffs as x, getPliteStringDirectPlacement as xn, isAfter as xr, writeDOMRangeData as xt, applyStringDiff as y, getOwnedPliteTextStrings as yn, getSelection as yr, writeDOMDataTransferFragment as yt, setEditorDOMEditableElement as z, resolveDOMTextFlowRecordText as zn, DOMRootRuntime as zt };
9520
+ export { getDragAutoScrollTarget as $, EDITOR_TO_FORCE_RENDER as $n, scheduleEditorDOMPhase as $t, createDOMEditorCapability as A, getPliteStringDocumentOffset as An, isBefore as Ar, SOFT_LINE_END_SELECTOR as At, setEditableRootReveal as B, isDOMTextFlowSegmentSynchronized as Bn, readClipboardCut as Br, findMountedDOMNodeByPath as Bt, normalizeRange as C, usesAppleDOMHotkeys as Cn, containsShadowAware as Cr, writeDOMFragmentData as Ct, DOMEditor as D, getOwnedPliteTextStrings as Dn, getSelection as Dr, writeDataTransferFragment as Dt, verifyDiffState as E, getNearestPliteStringRect as En, getFlatTreeParentElement as Er, observeDataTransferInsertion as Et, isSelectableDOMSelection as F, getPliteTextHostBounds as Fn, isDOMSelection as Fr, noteAfterInsertCaret as Ft, supersedeFocusRequest as G, resolveDOMTextFlowOffset as Gn, focusedElementOnPage as Gt, setEditorDOMRootElement as H, releaseDOMTextFlowRecordIndex as Hn, DOMRootRuntime as Ht, isTrackedMutation as I, getPliteTextHostStrings as In, isDOMText as Ir, readAfterInsertCaret as It, ensureFocusCaret as J, setDOMTextFlowRecordIndex as Jn, resolveDOMReach as Jt, watchFocusSuperseded as K, resolveDOMTextFlowRecordDOMText as Kn, getEditorDOMRoot as Kt, resolveDOMPointInRoot as L, getTextFlowPointAtCoordinates as Ln, isPlainTextOnlyPaste as Lr, readLowerSoftLineEnd as Lt, getEditorDOMHostScrollElement as M, getPliteStringLength as Mn, isDOMHTMLElement as Mr, clearAfterInsertCaret as Mt, getOrCreateDOMNodeKey as N, getPliteStringPlacementAtX as Nn, isDOMInputOrTextArea as Nr, isSoftLineEndBetween as Nt, DOMResolutionError as O, getPliteStringCoordinatePlacement as On, hasShadowRoot as Or, Key as Ot, isFocusRequestedElsewhere as P, getPliteStringPlacementDOMPoint as Pn, isDOMNode as Pr, isSoftLineTextStale as Pt, resolveBlockFragmentDropRange as Q, EDITOR_TO_ELEMENT as Qn, watchDOMSyncTextMarks as Qt, resolveDOMRangeInRoot as R, getUsableRangeRects as Rn, markPlainTextPaste as Rr, recordSoftLineEnd as Rt, normalizePoint as S, supportsDOMBeforeInput as Sn, closestShadowAware as Sr, writeDOMDataTransferFragment as St, targetRange as T, createDOMGeometryKernel as Tn, getDefaultView as Tr, dataTransferFormats as Tt, setEditorDOMScrollElement as U, resolveDOMTextFlowEntry as Un, findDOMRootRuntime as Ut, setEditorDOMEditableElement as V, readDOMTextFlowPaint as Vn, writeClipboardCut as Vr, resolvePliteNodePath as Vt, subscribeEditorDOMScope as W, resolveDOMTextFlowInsertTarget as Wn, findEditorDOMRootRuntime as Wt, resolveNextKeyCaret as X, DOMCoverage as Xn, isDOMSyncMutation as Xt, liftCaretOutOfCollapsedSection as Y, setDOMTextFlowRecordIndexes as Yn, resolveDOMTargetView as Yt, eventCarriesBlockFragment as Z, isCollapsedDOMCoverageBoundary as Zn, markDOMSyncMutationTarget as Zt, TRIPLE_CLICK as _, hasDOMHostQuirk as _n, IS_NODE_MAP_DIRTY as _r, readDropIndicator as _t, isLeaf as a, readDOMSelectionPoints as an, EDITOR_TO_PLACEHOLDER_ELEMENT as ar, resolveDOMDropTarget as at, longestCommonPrefixLength as b, isGeckoDOMHost as bn, NODE_TO_INDEX as br, domCommands as bt, isText as c, readsSelectionAsHost as cn, EDITOR_TO_RUNTIME_ID_TO_KEY as cr, cancelDragRest as ct, Hotkeys as d, writeDOMSelection as dn, EDITOR_TO_USER_SELECTION as dr, isDragSessionClaimed as dt, changeDOMSelection as en, EDITOR_TO_KEY_TO_ELEMENT as er, intersectClipChain as et, getLineBoundaryKeyboardMove as f, writeUserDOMSelection as fn, EDITOR_TO_WINDOW as fr, readDragSession as ft, isHotkey as g, getDOMHostLanguage as gn, IS_FOCUSED as gr, publishDropIndicator as gt, createCompiledHotkeyMatcher as h, CAN_USE_DOM as hn, IS_COMPOSING as hr, takeDragSession as ht, isElement as i, isDOMSelectionWriteEcho as in, EDITOR_TO_PENDING_SELECTION as ir, pointAt as it, findDOMPointElementInRoot as j, getPliteStringEdgeOffset as jn, isDOMElement as jr, SOFT_LINE_FLAG as jt, claimFocusRequest as k, getPliteStringDirectPlacement as kn, isAfter as kr, SOFT_LINE_END as kt, isVoid as l, recordDOMSelection as ln, EDITOR_TO_SCHEDULE_FLUSH as lr, clearDragScrollRepaint as lt, ariaKeyShortcuts as m, selectDOMInputDefaultActionPhase as mn, ELEMENT_TO_NODE as mr, settleDragSession as mt, getNodeDataAttributeKeys as n, forgetDOMSelectionRecordWithin as nn, EDITOR_TO_PENDING_DIFFS as nr, copyIntentOf as nt, isNode as o, readDOMSelectionRange as on, EDITOR_TO_ROOT_VIEW_EDITORS as or, restDOMBlockDrag as ot, isPasteWithoutFormatting as p, enableKernelTraceRetention as pn, ELEMENT_TO_EDITOR as pr, setDragScrollRepaint as pt, writeViewSelectionPart as q, resolveDOMTextFlowRecordText as qn, isElementFocused as qt, isEditor as r, getDOMRangeSelectionPoints as rn, EDITOR_TO_PENDING_INSERTION_MARKS as rr, indicateDOMDropTarget as rt, isString as s, readDOMSelectionRecord as sn, EDITOR_TO_RUNTIME_ID_TO_ELEMENTS as sr, beginDragSession as st, getElements as t, forgetDOMSelectionRecord as tn, EDITOR_TO_PENDING_ACTION as tr, walkClipChain as tt, keyToDataAttribute as u, sameDOMSelectionPoints as un, EDITOR_TO_USER_MARKS as ur, clearDragSession as ut, dom as v, isAndroidDOMHost as vn, IS_READ_ONLY as vr, subscribeDropIndicator as vt, normalizeStringDiff as w, caretShowsPointOffTextFlowCharacters as wn, getActiveElement as wr, writeDOMRangeData as wt, mergeStringDiffs as x, isWebKitDOMHost as xn, NODE_TO_PARENT as xr, getDOMClipboardFormatKey as xt, applyStringDiff as y, isBlinkDOMHost as yn, NODE_TO_ELEMENT as yr, cleanDOMClipboardContents as yt, resolveWrittenDOMRange as z, hasUsableDOMRect as zn, normalizeDOMPoint as zr, resolveSoftLineEndDOMPoint as zt };