plitejs 54.0.0-beta.5 → 54.0.0-beta.7

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 (59) hide show
  1. package/README.md +4 -4
  2. package/dist/authored/index.d.ts +25 -8
  3. package/dist/authored/index.js +4316 -735
  4. package/dist/{authored-veto-Cu-5JdVj.js → authored-veto-CferDljr.js} +1 -1
  5. package/dist/clipboard-format-key-CLFcThXH.js +14 -0
  6. package/dist/{comparison-plan-BJxnVPcS.js → comparison-plan-7iIABSWG.js} +108 -2
  7. package/dist/{comparison-types-Bvvxzxq2.d.ts → comparison-types-CsmDG5r2.d.ts} +1 -1
  8. package/dist/{create-editor-XvI_4sYc.js → create-editor-acDgsovY.js} +25 -49
  9. package/dist/diff/index.d.ts +2 -2
  10. package/dist/diff/index.js +111 -20
  11. package/dist/dom/index.d.ts +3 -2
  12. package/dist/dom/index.js +3 -2
  13. package/dist/{dom-BjspML2h.js → dom-B5bAma7X.js} +859 -210
  14. package/dist/history/index.d.ts +1 -1
  15. package/dist/history/index.js +5302 -4295
  16. package/dist/hyperscript/index.d.ts +1 -1
  17. package/dist/hyperscript/index.js +1 -1
  18. package/dist/{hyperscript-BFypA5qW.js → hyperscript-BXUV6sdO.js} +2 -2
  19. package/dist/{index-BwmXxqbi.d.ts → index-CTTjpWgb.d.ts} +1 -1
  20. package/dist/{index-DaXz-4c7.d.ts → index-D8DQ1YFB.d.ts} +22 -22
  21. package/dist/{index-CYac3_ID.d.ts → index-DJvrmSRP.d.ts} +82 -199
  22. package/dist/{index-BUJsM0oV.d.ts → index-LhVJuuEf.d.ts} +1 -1
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +4 -4
  25. package/dist/internal/index.d.ts +2 -2
  26. package/dist/internal/index.js +5 -5
  27. package/dist/pagination/index.d.ts +1 -1
  28. package/dist/pagination/index.js +1 -1
  29. package/dist/pagination/react.d.ts +14 -11
  30. package/dist/pagination/react.js +150 -103
  31. package/dist/{pagination-ChDBJtdC.js → pagination-CwjmxPoX.js} +1 -1
  32. package/dist/{plugin-BvM4s-Lr.js → plugin-BZCGtqMI.js} +8691 -2054
  33. package/dist/{range-geometry-wFuJaBlA.d.ts → range-geometry-CZari453.d.ts} +1 -1
  34. package/dist/{range-geometry-B5CITwMp.js → range-geometry-CqWrwkjH.js} +2 -2
  35. package/dist/react/index.d.ts +4 -5
  36. package/dist/react/index.js +7 -7
  37. package/dist/react/virtualized.d.ts +5 -5
  38. package/dist/react/virtualized.js +12 -7
  39. package/dist/{react-cmFeNP6P.js → react-DO9IETEQ.js} +128 -126
  40. package/dist/{retraction-lXQwo2Ia.js → retraction-RHEKiF3h.js} +1 -1
  41. package/dist/{src-BA6F9yxN.js → src-fLbHzUjC.js} +277 -72
  42. package/dist/testing/index.d.ts +2 -2
  43. package/dist/testing/index.js +3 -3
  44. package/dist/{index-QuqD4Dyj.d.ts → tx-only-1FM45FSj.d.ts} +9060 -8608
  45. package/dist/{editor-owner-CRgIQ625.js → update-policy-C32RjjGt.js} +53 -2
  46. package/dist/{use-editor-dom-scope-B4gF9t_Y.js → use-editor-dom-scope-CUBnNAZV.js} +6133 -4076
  47. package/dist/yjs/index.d.ts +1 -1
  48. package/dist/yjs/index.js +1 -1
  49. package/dist/yjs/react/index.d.ts +3 -3
  50. package/dist/yjs/react/index.js +3 -3
  51. package/dist/{yjs-CWdWDrpv.js → yjs-BMguSAX_.js} +311 -127
  52. package/package.json +1 -7
  53. package/dist/annotation-store-metrics-Ccjkef45.js +0 -12
  54. package/dist/annotations/index.d.ts +0 -2
  55. package/dist/annotations/index.js +0 -2
  56. package/dist/index-CRmyGzS8.d.ts +0 -71
  57. package/dist/mapped-view-store-XUJ-fnHE.js +0 -120
  58. package/dist/native-grouping-input-8kO12VK9.js +0 -8
  59. package/dist/store-Bllfuqp4.js +0 -717
@@ -1,5 +1,6 @@
1
- import { $a as resolveParkedCaret, Ai as captureSliceLanding, Au as hasEditorRuntime, B as NodeApi, Bt as point, Da as isTextCell, Di as withUpdateTagContext, Dl as getPluginRegistry, Du as getEditorRuntimeOwner, El as getPluginContributions, En as attachTransactionSpecAfterCommit, Es as getSelectionDOMRange, Et as isInline, Eu as getEditorRuntime, F as getActiveCommandEditor, Ha as getPlacementGeneration, Jf as RangeApi, Ko as txLocate, Lt as next, M as dispatchCommand, Mu as defineCommand, N as evaluateCommand, Na as nodes, Ou as getEditorRuntimeRoot, P as evaluateCommandWithState, Pn as getActiveEditorTransaction, Qn as getEditorReadDepth, Rd as DocumentIndex, Rn as getBaseCallRoot, Sc as getEditorCommitSnapshot, Su as TextApi, Tc as getEditorCommitValue, U as after, Us as EditorSchemaValidationError, V as above, Va as getCaretOwner, W as before, Wa as holdsCaret, Wt as range, Xa as placedSince, Yf as LocationApi, Zf as PointApi, _d as mapInternalDocumentChangePosition, _i as toEditorCoreStateView, _n as afterActiveTransactionEnds, _u as SelectionApi, at as getNodeKey, bt as isBlock, cl as toInternalRoot, ct as getSelection$1, dc as createDetachedContentSlice, dn as voidEditor, dp as countCoreWork, ds as getInternalEditorSchemaFromApi, fa as readRemovalLanding, ft as hasPath, gd as mapInternalDocumentChangePoint, go as getOwnViewPresentation, ks as mapSelectionThroughChange, kt as isVoid$2, ku as getEditorSchema, l as definePlugin, la as withLandingBlock, ll as toPublicRoot, lr as getNodeTargetRoot, lt as getSnapshot, m as getInstalledPlugin, mu as definePluginPoint, np as PathApi, ot as getPathByNodeKey, pd as hasInternalDocumentChangeRoot, pi as subscribeCaretTarget, pn as editorCommands, pr as getSetSite, pu as failInvariant, qr as resolveEditorNodeKeyForNode, ri as setEditorFocused, ro as setSelectionAsView, sf as getNodeKeyForNode, sl as getPublicExplicitLocationRoot, sn as unhangRange, tr as getEditorStateView, tt as getChildren, uc as ContentSlice, us as getCompiledEditorSchemaFromApi, vl as reportEditorLifecycleError, vp as getDefined, vu as ElementApi, wl as getCompiledEditorSchema, xn as applyTransactionSpec, yd as valueRoot, yo as getViewFollowTarget, yu as formatDebugValue, zl as getCompiledSchemaPropertyId } from "./plugin-BvM4s-Lr.js";
2
- import { a as transferEntries, n as checkFilesLanding, r as checkTransfer } from "./src-BA6F9yxN.js";
1
+ import { Ad as getEditorRuntimeRoot, Ai as toEditorCoreStateView, At as isVoid$2, Cd as TextApi, Cu as getCompiledEditorSchema, Df as valueRoot, Dm as countCoreWork, Dn as attachTransactionSpecAfterCommit, Do as getPlacementGeneration, Dt as isInline, Eo as getCaretOwner, Eu as getPluginRegistry, F as evaluateCommandWithState, Fo as placedSince, G as before, Gt as range, H as above, Ho as setSelectionAsView, I as getActiveCommandEditor, Md as hasEditorRuntime, Ms as txLocate, N as dispatchCommand, Od as getEditorRuntime, P as evaluateCommand, Pd as defineCommand, Pm as getDefined, Qf as DocumentIndex, Ro as resolveParkedCaret, Rt as next, Ru as getCompiledSchemaPropertyId, Sn as applyTransactionSpec, Tf as mapInternalDocumentChangePosition, Ti as subscribeCaretTarget, Tu as getPluginContributions, Un as getBaseCallRoot, V as NodeApi, Vi as withUpdateTagContext, Vt as point, W as after, Wi as captureSliceLanding, Xa as readRemovalLanding, _c as getSelectionDOMRange, _u as reportEditorLifecycleError, ar as getEditorReadDepth, au as getPublicExplicitLocationRoot, bd as formatDebugValue, bf as hasInternalDocumentChangeRoot, br as getSetSite, cn as unhangRange, cr as getEditorStateView, dm as LocationApi, ec as getCompiledEditorSchemaFromApi, fn as voidEditor, fo as isTextCell, gr as getNodeTargetRoot, hd as definePluginPoint, hl as getEditorCommitSnapshot, id as EditorSchemaValidationError, ii as resolveEditorNodeKeyForNode, il as createDetachedContentSlice, is as getViewFollowTarget, jd as getEditorSchema, kd as getEditorRuntimeOwner, ko as holdsCaret, l as definePlugin, lt as getSelection$1, m as getInstalledPlugin, md as failInvariant, mi as setEditorFocused, mn as editorCommands, nt as getChildren, ot as getNodeKey, ou as toInternalRoot, pm as PointApi, pt as hasPath, qa as withLandingBlock, rl as ContentSlice, st as getPathByNodeKey, su as toPublicRoot, tc as getInternalEditorSchemaFromApi, ts as getOwnViewPresentation, um as RangeApi, ut as getSnapshot, vd as SelectionApi, vl as getEditorCommitValue, vm as PathApi, vn as afterActiveTransactionEnds, vo as nodes, wf as mapInternalDocumentChangePoint, xc as mapSelectionThroughChange, xl as readRootEntries, xp as getNodeKeyForNode, xt as isBlock, yd as ElementApi, zn as getActiveEditorTransaction } from "./plugin-BZCGtqMI.js";
2
+ import { a as transferEntries, c as dispatchPaste, n as checkFilesLanding, r as checkTransfer, u as landPaste } from "./src-fLbHzUjC.js";
3
+ import { i as setDOMClipboardFormatKey, n as clearDOMClipboardFormatKey, r as getDOMClipboardFormatKey, t as DEFAULT_CLIPBOARD_FORMAT_KEY$2 } from "./clipboard-format-key-CLFcThXH.js";
3
4
  import scrollIntoViewIfNeeded from "scroll-into-view-if-needed";
4
5
  //#region src/dom/utils/dom.ts
5
6
  globalThis.Node;
@@ -22,13 +23,21 @@ const isDOMComment = (value) => isDOMNode(value) && value.nodeType === 8;
22
23
  * Check if a DOM node is an element node.
23
24
  */
24
25
  const isDOMElement = (value) => isDOMNode(value) && value.nodeType === 1;
26
+ const isDOMInstance = (value, key) => {
27
+ const GlobalConstructor = globalThis[key];
28
+ if (typeof GlobalConstructor === "function" && value instanceof GlobalConstructor) return true;
29
+ const view = getDefaultView(value);
30
+ if (!view || view === globalThis) return false;
31
+ const ViewConstructor = view[key];
32
+ return typeof ViewConstructor === "function" && value instanceof ViewConstructor;
33
+ };
25
34
  /**
26
35
  * Check if a value is a DOM node.
27
36
  */
28
- const isDOMNode = (value) => {
29
- const Node = getDefaultView(value)?.Node;
30
- return typeof Node === "function" && value instanceof Node;
31
- };
37
+ const isDOMNode = (value) => isDOMInstance(value, "Node");
38
+ const isDOMHTMLElement = (value) => isDOMInstance(value, "HTMLElement");
39
+ const isDOMInputOrTextArea = (value) => isDOMInstance(value, "HTMLInputElement") || isDOMInstance(value, "HTMLTextAreaElement");
40
+ const isDOMTableRowElement = (value) => isDOMInstance(value, "HTMLTableRowElement");
32
41
  /**
33
42
  * Check if a value is a DOM selection.
34
43
  */
@@ -152,18 +161,18 @@ const getPlainText = (domNode, skip) => {
152
161
  endLine();
153
162
  return lines.join("\n");
154
163
  };
155
- const DEFAULT_CLIPBOARD_FORMAT_KEY$2 = "x-editor-fragment";
164
+ const DEFAULT_CLIPBOARD_FORMAT_KEY$1 = "x-editor-fragment";
156
165
  const catchOpeningHtmlTag = /<[A-Za-z][^<>]*?>/g;
157
166
  const catchEditorFragment = /\bdata-editor-fragment\s*=\s*(["'])(.*?)\1/i;
158
167
  const catchEditorFragmentFormat = /\bdata-editor-fragment-format\s*=\s*(["'])(.*?)\1/i;
159
168
  /** Read an HTML clipboard envelope for the editor's configured format. */
160
- const getFragmentAttribute = (dataTransfer, clipboardFormatKey = DEFAULT_CLIPBOARD_FORMAT_KEY$2) => {
169
+ const getFragmentAttribute = (dataTransfer, clipboardFormatKey = DEFAULT_CLIPBOARD_FORMAT_KEY$1) => {
161
170
  const openingTags = dataTransfer.getData("text/html").match(catchOpeningHtmlTag) ?? [];
162
171
  for (const tag of openingTags) {
163
172
  const fragment = tag.match(catchEditorFragment)?.[2];
164
173
  if (fragment === void 0) continue;
165
174
  const fragmentFormat = tag.match(catchEditorFragmentFormat)?.[2];
166
- if (fragmentFormat === clipboardFormatKey || fragmentFormat === void 0 && clipboardFormatKey === DEFAULT_CLIPBOARD_FORMAT_KEY$2) return fragment;
175
+ if (fragmentFormat === clipboardFormatKey || fragmentFormat === void 0 && clipboardFormatKey === DEFAULT_CLIPBOARD_FORMAT_KEY$1) return fragment;
167
176
  }
168
177
  };
169
178
  const plainTextPastes = /* @__PURE__ */ new WeakSet();
@@ -171,6 +180,27 @@ const markPlainTextPaste = (data) => {
171
180
  plainTextPastes.add(data);
172
181
  };
173
182
  const isPlainTextPaste = (data) => plainTextPastes.has(data);
183
+ const CUT_MIME_TYPE = "application/x-editor-cut";
184
+ const catchTagName = /^<[A-Za-z][^\s/>]*/;
185
+ const catchLeadingEditorCut = /^<[A-Za-z][^\s/>]*\s+data-editor-cut="([^"]*)"/;
186
+ const readClipboardCut = (data) => {
187
+ if (isPlainTextPaste(data)) return null;
188
+ const id = data.getData(CUT_MIME_TYPE);
189
+ if (id) return id;
190
+ for (const [tag] of data.getData("text/html").matchAll(catchOpeningHtmlTag)) if (catchEditorFragment.test(tag)) return tag.match(catchLeadingEditorCut)?.[1] ?? null;
191
+ return null;
192
+ };
193
+ const writeClipboardCut = (data, id) => {
194
+ const html = data.getData("text/html");
195
+ let tagged = false;
196
+ data.setData(CUT_MIME_TYPE, id);
197
+ if (!html) return;
198
+ data.setData("text/html", html.replace(catchOpeningHtmlTag, (tag) => {
199
+ if (tagged || !catchEditorFragment.test(tag)) return tag;
200
+ tagged = true;
201
+ return tag.replace(catchTagName, `$& data-editor-cut="${id}"`);
202
+ }));
203
+ };
174
204
  const readClipboardFragmentPayload = (data, clipboardFormatKey) => {
175
205
  if (isPlainTextPaste(data)) return null;
176
206
  const mime = `application/${clipboardFormatKey}`;
@@ -1190,7 +1220,7 @@ const getPliteStringLength = (string) => {
1190
1220
  };
1191
1221
  const PLITE_STRING_SELECTOR = "[data-editor-string], [data-editor-zero-width]";
1192
1222
  const getPliteTextHostStrings = (textHost) => {
1193
- if (textHost instanceof HTMLElement && textHost.matches("[data-editor-string], [data-editor-zero-width]")) return [textHost];
1223
+ if (isDOMHTMLElement(textHost) && textHost.matches("[data-editor-string], [data-editor-zero-width]")) return [textHost];
1194
1224
  const owner = textHost.closest("[data-editor-node=\"text\"]");
1195
1225
  return Array.from(textHost.querySelectorAll(PLITE_STRING_SELECTOR)).filter((string) => string.closest("[data-editor-node=\"text\"]") === owner);
1196
1226
  };
@@ -1601,6 +1631,30 @@ const getOwnedPliteStrings = ({ root, target }) => {
1601
1631
  return root.contains(string) && (!owner || owner === root);
1602
1632
  });
1603
1633
  };
1634
+ const caretShowsPointOffTextFlowCharacters = ({ host, x, y }) => {
1635
+ const point = getNativeDOMPointAtCoordinates(host.ownerDocument, x, y);
1636
+ if (!point) return false;
1637
+ const [node, offset] = point;
1638
+ if (!isPointInside(point, host) || !isDOMText(node)) return true;
1639
+ const range = host.ownerDocument.createRange();
1640
+ range.setStart(...moveTextPoint(host, node, offset, -TEXT_FLOW_CARET_REACH));
1641
+ range.setEnd(...moveTextPoint(host, node, offset, TEXT_FLOW_CARET_REACH));
1642
+ return !getUsableRangeRects(range).some((rect) => x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom);
1643
+ };
1644
+ const TEXT_FLOW_CARET_REACH = 16;
1645
+ const moveTextPoint = (host, node, offset, units) => {
1646
+ const walker = host.ownerDocument.createTreeWalker(host, host.ownerDocument.defaultView?.NodeFilter.SHOW_TEXT ?? 4);
1647
+ let current = node;
1648
+ let at = offset + units;
1649
+ walker.currentNode = node;
1650
+ while (at < 0 || at > current.data.length) {
1651
+ const next = at < 0 ? walker.previousNode() : walker.nextNode();
1652
+ if (!next) return [current, at < 0 ? 0 : current.data.length];
1653
+ at = at < 0 ? at + next.data.length : at - current.data.length;
1654
+ current = next;
1655
+ }
1656
+ return [current, at];
1657
+ };
1604
1658
  const getRootEdgeCoordinatePlacement = ({ root, strings, x, y }) => {
1605
1659
  const rootRect = root.getBoundingClientRect();
1606
1660
  if (y < rootRect.top || y > rootRect.bottom) return null;
@@ -1739,6 +1793,37 @@ const getElementTextNodes = (element) => {
1739
1793
  };
1740
1794
  const TEXT_FLOW_LINE_BREAKS = /\r\n|[\n\r]/g;
1741
1795
  const TEXT_FLOW_UNPAINTED = /^(?:\r\n|[\n\r\uFEFF])$/;
1796
+ const GRAPHEME_CHUNK_LENGTH = 32;
1797
+ const codePointLengthAt = (data, offset) => (data.codePointAt(offset) ?? 0) > 65535 ? 2 : 1;
1798
+ const isTextFlowBreak = (unit) => unit === "\n" || unit === "\r" || unit === "\r\n";
1799
+ const isOnVisualRow = (rect, row) => getRectOverlap(rect, row) > Math.min(rect.height, row.height) / 2;
1800
+ function* getGraphemeRangesFrom(data, from) {
1801
+ let start = from;
1802
+ let length = GRAPHEME_CHUNK_LENGTH;
1803
+ while (start < data.length) {
1804
+ let chunkEnd = Math.min(start + length, data.length);
1805
+ if (chunkEnd < data.length && /[\uD800-\uDBFF]/.test(data[chunkEnd - 1])) chunkEnd += 1;
1806
+ const chunk = data.slice(start, chunkEnd);
1807
+ let next = chunkEnd;
1808
+ if (graphemeSegmenter) for (const { index, segment } of graphemeSegmenter.segment(chunk)) {
1809
+ const end = start + index + segment.length;
1810
+ if (end === chunkEnd && chunkEnd < data.length) {
1811
+ next = start + index;
1812
+ break;
1813
+ }
1814
+ yield [start + index, end];
1815
+ }
1816
+ else {
1817
+ let offset = start;
1818
+ for (const character of chunk) {
1819
+ yield [offset, offset + character.length];
1820
+ offset += character.length;
1821
+ }
1822
+ }
1823
+ if (next === start) length *= 2;
1824
+ start = next;
1825
+ }
1826
+ }
1742
1827
  const getTextFlowPointAtCoordinates = ({ host, x, y }) => {
1743
1828
  const nodes = getElementTextNodes(host).filter((node) => node.data !== "");
1744
1829
  const starts = [];
@@ -1747,6 +1832,7 @@ const getTextFlowPointAtCoordinates = ({ host, x, y }) => {
1747
1832
  starts.push(text.length);
1748
1833
  text += node.data;
1749
1834
  }
1835
+ if (nodes.length === 0) return null;
1750
1836
  const range = host.ownerDocument.createRange();
1751
1837
  const nodeIndexAt = (index) => {
1752
1838
  let low = 0;
@@ -1758,17 +1844,24 @@ const getTextFlowPointAtCoordinates = ({ host, x, y }) => {
1758
1844
  }
1759
1845
  return low;
1760
1846
  };
1761
- const pointAt = (index) => {
1762
- const nodeIndex = nodeIndexAt(index);
1847
+ const pointAt = (index, from = index) => {
1848
+ const nodeIndex = nodeIndexAt(from);
1763
1849
  return [nodes[nodeIndex], index - starts[nodeIndex]];
1764
1850
  };
1851
+ const probes = /* @__PURE__ */ new Map();
1852
+ const unitRectAt = (index) => {
1853
+ if (!probes.has(index)) {
1854
+ const end = index + codePointLengthAt(text, index);
1855
+ range.setStart(...pointAt(index));
1856
+ range.setEnd(...pointAt(end, end - 1));
1857
+ probes.set(index, getUsableRangeRects(range)[0] ?? null);
1858
+ }
1859
+ return probes.get(index) ?? null;
1860
+ };
1765
1861
  const paintedUnitAt = (from, step) => {
1766
1862
  for (let index = from; index >= 0 && index < text.length; index += step) {
1767
1863
  if (TEXT_FLOW_UNPAINTED.test(text[index])) continue;
1768
- const [node, offset] = pointAt(index);
1769
- range.setStart(node, offset);
1770
- range.setEnd(node, offset + 1);
1771
- const rect = getUsableRangeRects(range)[0];
1864
+ const rect = unitRectAt(index);
1772
1865
  if (rect) return {
1773
1866
  index,
1774
1867
  rect
@@ -1776,6 +1869,15 @@ const getTextFlowPointAtCoordinates = ({ host, x, y }) => {
1776
1869
  }
1777
1870
  return null;
1778
1871
  };
1872
+ const probesInSourceOrder = () => {
1873
+ let maxTop = Number.NEGATIVE_INFINITY;
1874
+ for (const [, rect] of [...probes].sort(([a], [b]) => a - b)) {
1875
+ if (!rect) continue;
1876
+ if (rect.bottom < maxTop) return false;
1877
+ maxTop = Math.max(maxTop, rect.top);
1878
+ }
1879
+ return true;
1880
+ };
1779
1881
  const firstIndexEndingBelowY = () => {
1780
1882
  let low = 0;
1781
1883
  let high = text.length;
@@ -1791,7 +1893,19 @@ const getTextFlowPointAtCoordinates = ({ host, x, y }) => {
1791
1893
  const below = paintedUnitAt(split, 1);
1792
1894
  const above = split > 0 ? paintedUnitAt(split - 1, -1) : null;
1793
1895
  const nearest = below && (!above || getRectVerticalDistance(below.rect, y) <= getRectVerticalDistance(above.rect, y)) ? below : above;
1794
- if (!nearest) return null;
1896
+ if (!nearest) {
1897
+ const rowStarts = [...text.matchAll(TEXT_FLOW_LINE_BREAKS)].map((match) => match.index + match[0].length);
1898
+ let low = 0;
1899
+ let high = rowStarts.length;
1900
+ while (low < high) {
1901
+ const middle = Math.floor((low + high) / 2);
1902
+ const rect = unitRectAt(rowStarts[middle] - 1);
1903
+ if (!rect) return null;
1904
+ if (rect.bottom <= y) low = middle + 1;
1905
+ else high = middle;
1906
+ }
1907
+ return (rowStarts.length > 0 || unitRectAt(0)) && probesInSourceOrder() ? pointAt(low === 0 ? 0 : rowStarts[low - 1]) : null;
1908
+ }
1795
1909
  if (!below || below.rect.top > y) {
1796
1910
  const from = above ? above.index + 1 : 0;
1797
1911
  const breaks = [...text.slice(from, below?.index ?? text.length).matchAll(TEXT_FLOW_LINE_BREAKS)];
@@ -1805,45 +1919,70 @@ const getTextFlowPointAtCoordinates = ({ host, x, y }) => {
1805
1919
  return pointAt(previousBreak ? from + previousBreak.index + previousBreak[0].length : from);
1806
1920
  }
1807
1921
  }
1808
- const lineStart = Math.max(text.lastIndexOf("\n", nearest.index), text.lastIndexOf("\r", nearest.index)) + 1;
1809
- const lineEnd = Math.min(...["\n", "\r"].map((lineBreak) => {
1810
- const index = text.indexOf(lineBreak, nearest.index);
1811
- return index === -1 ? text.length : index;
1812
- }));
1922
+ const row = nearest.rect;
1923
+ let low = 0;
1924
+ let high = nearest.index;
1925
+ while (low < high) {
1926
+ const middle = Math.floor((low + high) / 2);
1927
+ const unit = paintedUnitAt(middle, 1);
1928
+ if (unit && unit.index < nearest.index && unit.rect.top < row.top && !isOnVisualRow(unit.rect, row)) low = unit.index + 1;
1929
+ else high = middle;
1930
+ }
1931
+ if (!probesInSourceOrder()) return null;
1932
+ const rowStart = paintedUnitAt(low, 1)?.index ?? nearest.index;
1813
1933
  let best = null;
1814
- let onLine = false;
1815
- for (let nodeIndex = nodeIndexAt(lineStart); nodeIndex < nodes.length && starts[nodeIndex] < lineEnd; nodeIndex++) {
1816
- const node = nodes[nodeIndex];
1817
- const from = Math.max(lineStart - starts[nodeIndex], 0);
1818
- const to = Math.min(lineEnd - starts[nodeIndex], node.data.length);
1819
- const direction = getElementDirection(node.parentElement);
1820
- const offsets = getGraphemeBoundaryOffsets(node.data.slice(from, to));
1821
- for (let index = 0; index < offsets.length - 1; index++) {
1822
- const start = from + offsets[index];
1823
- const end = from + offsets[index + 1];
1824
- if (TEXT_FLOW_UNPAINTED.test(node.data.slice(start, end))) continue;
1825
- range.setStart(node, start);
1826
- range.setEnd(node, end);
1827
- const rects = getUsableRangeRects(range);
1828
- const rect = rects.find((candidate) => getRectOverlap(candidate, nearest.rect) > VISUAL_LINE_TOLERANCE);
1829
- if (!rect) {
1830
- if (onLine && rects.length > 0) return best?.point ?? null;
1831
- continue;
1832
- }
1833
- onLine = true;
1834
- if (x >= rect.left && x <= rect.right) {
1835
- const midpoint = rect.left + rect.width / 2;
1836
- return [node, (direction === "rtl" ? x > midpoint : x <= midpoint) ? start : end];
1837
- }
1838
- for (const [offset, edgeX] of [[start, direction === "rtl" ? rect.right : rect.left], [end, direction === "rtl" ? rect.left : rect.right]]) {
1839
- const distance = Math.abs(edgeX - x);
1840
- if (!best || distance < best.distance) best = {
1841
- distance,
1842
- point: [node, offset]
1843
- };
1844
- }
1934
+ let hit = null;
1935
+ let left = Number.POSITIVE_INFINITY;
1936
+ let right = Number.NEGATIVE_INFINITY;
1937
+ let last = null;
1938
+ let end = pointAt(rowStart);
1939
+ let reachedNearest = false;
1940
+ let wrapped = false;
1941
+ for (const [start, stop] of getGraphemeRangesFrom(text, rowStart)) {
1942
+ const unit = text.slice(start, stop);
1943
+ if (isTextFlowBreak(unit)) break;
1944
+ if (unit === "") continue;
1945
+ const from = pointAt(start);
1946
+ const to = pointAt(stop, stop - 1);
1947
+ const direction = getElementDirection(from[0].parentElement);
1948
+ range.setStart(...from);
1949
+ range.setEnd(...to);
1950
+ const rects = getUsableRangeRects(range);
1951
+ if (rects.length === 0) continue;
1952
+ const rect = rects.find((candidate) => isOnVisualRow(candidate, row));
1953
+ 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));
1954
+ if (!rect || startsNextRow) {
1955
+ wrapped = true;
1956
+ break;
1957
+ }
1958
+ reachedNearest ||= stop > nearest.index;
1959
+ left = Math.min(left, rect.left);
1960
+ right = Math.max(right, rect.right);
1961
+ last = {
1962
+ rect,
1963
+ space: unit.length === 1 && CSS_BREAK_WHITESPACE_PATTERN.test(unit),
1964
+ start: from
1965
+ };
1966
+ end = to;
1967
+ if (!hit && x >= rect.left && x <= rect.right) {
1968
+ const midpoint = rect.left + rect.width / 2;
1969
+ hit = (direction === "rtl" ? x > midpoint : x <= midpoint) ? from : to;
1970
+ }
1971
+ for (const [point, edgeX] of [[from, direction === "rtl" ? rect.right : rect.left], [to, direction === "rtl" ? rect.left : rect.right]]) {
1972
+ const distance = Math.abs(edgeX - x);
1973
+ if (!best || distance < best.distance) best = {
1974
+ distance,
1975
+ point
1976
+ };
1845
1977
  }
1846
1978
  }
1979
+ if (!reachedNearest) return null;
1980
+ if (hit) return hit;
1981
+ const logicalStart = pointAt(rowStart);
1982
+ const logicalEnd = wrapped && last?.space ? last.start : end;
1983
+ const rtl = getElementDirection(host) === "rtl";
1984
+ if (x > right) return rtl ? logicalStart : logicalEnd;
1985
+ if (x < left) return rtl ? logicalEnd : logicalStart;
1847
1986
  return best?.point ?? null;
1848
1987
  };
1849
1988
  const getTextOffsetInVisualLineByX = ({ line, textNode, x }) => {
@@ -2263,6 +2402,88 @@ const hasDOMHostQuirk = (source, quirk) => resolveDOMSourceFacts(source)?.quirks
2263
2402
  /** True when the current environment exposes the browser DOM APIs Plite needs. */
2264
2403
  const CAN_USE_DOM = !!(typeof window !== "undefined" && window.document !== void 0 && "createElement" in window.document);
2265
2404
  //#endregion
2405
+ //#region src/dom/utils/selection-writes.ts
2406
+ const RECORDS = /* @__PURE__ */ new WeakMap();
2407
+ const UNPLACED_WRITES = /* @__PURE__ */ new WeakMap();
2408
+ const hasLayoutBox = ([node]) => {
2409
+ const element = node.nodeType === 1 ? node : node.parentElement;
2410
+ return !!element && element.getClientRects().length > 0;
2411
+ };
2412
+ const readDOMSelectionPoints = (selection) => {
2413
+ const { anchorNode, focusNode } = selection;
2414
+ return selection.rangeCount > 0 && anchorNode && focusNode ? {
2415
+ anchor: [anchorNode, selection.anchorOffset],
2416
+ focus: [focusNode, selection.focusOffset]
2417
+ } : null;
2418
+ };
2419
+ const sameDOMPoint = ([node, offset], [otherNode, otherOffset]) => node === otherNode && offset === otherOffset;
2420
+ const sameDOMSelectionPoints = (points, other) => points === null || other === null ? points === other : sameDOMPoint(points.anchor, other.anchor) && sameDOMPoint(points.focus, other.focus);
2421
+ const readDOMSelectionRecord = (tree) => RECORDS.get(tree) ?? null;
2422
+ const isDOMSelectionWriteEcho = (tree, points) => {
2423
+ const record = RECORDS.get(tree);
2424
+ return record?.source === "write" && sameDOMSelectionPoints(points, record.points);
2425
+ };
2426
+ const recordDOMSelection = (tree, points, source) => {
2427
+ RECORDS.set(tree, {
2428
+ points,
2429
+ source
2430
+ });
2431
+ UNPLACED_WRITES.delete(tree);
2432
+ };
2433
+ const forgetDOMSelectionRecord = (tree) => {
2434
+ RECORDS.delete(tree);
2435
+ UNPLACED_WRITES.delete(tree);
2436
+ };
2437
+ const touches = (container, points) => !!points && (container.contains(points.anchor[0]) || container.contains(points.focus[0]));
2438
+ const forgetDOMSelectionRecordWithin = (tree, container) => {
2439
+ if (touches(container, RECORDS.get(tree)?.points)) RECORDS.delete(tree);
2440
+ if (touches(container, UNPLACED_WRITES.get(tree))) UNPLACED_WRITES.delete(tree);
2441
+ };
2442
+ const getDOMRangeSelectionPoints = (range, backward = false) => {
2443
+ const start = [range.startContainer, range.startOffset];
2444
+ const end = [range.endContainer, range.endOffset];
2445
+ return backward ? {
2446
+ anchor: end,
2447
+ focus: start
2448
+ } : {
2449
+ anchor: start,
2450
+ focus: end
2451
+ };
2452
+ };
2453
+ const readsSelectionAsHost = (tree) => tree.nodeType === tree.DOCUMENT_FRAGMENT_NODE && isWebKitDOMHost(tree);
2454
+ /**
2455
+ * Write `points` as `tree`'s selection, keeping their direction, or clear its
2456
+ * ranges for null, and record what the tree then shows, or the points written
2457
+ * where the tree reads its selection as its host. A selection that already
2458
+ * shows them is left alone, and so is the record, unless WebKit got them from
2459
+ * a write while their anchor had no layout box, neither the user nor a write
2460
+ * of other points has come since, and the anchor has one now.
2461
+ */
2462
+ const writeDOMSelection = (tree, points) => {
2463
+ changeDOMSelection(tree, points);
2464
+ };
2465
+ const changeDOMSelection = (tree, points, beforeChange, canCommit) => {
2466
+ const selection = getSelection(tree);
2467
+ if (!selection) return false;
2468
+ const rewritesUnplaced = points !== null && sameDOMSelectionPoints(UNPLACED_WRITES.get(tree) ?? null, points);
2469
+ if (!rewritesUnplaced) UNPLACED_WRITES.delete(tree);
2470
+ if (!(points === null && tree.nodeType === tree.DOCUMENT_FRAGMENT_NODE && !!canCommit) && sameDOMSelectionPoints(readDOMSelectionPoints(selection), points) && !(rewritesUnplaced && hasLayoutBox(points.anchor))) return true;
2471
+ beforeChange?.();
2472
+ if (canCommit && !canCommit()) return false;
2473
+ if (points) selection.setBaseAndExtent(points.anchor[0], points.anchor[1], points.focus[0], points.focus[1]);
2474
+ else selection.removeAllRanges();
2475
+ if (points && hasDOMHostQuirk(tree, "unrendered-caret-needs-rewrite") && !hasLayoutBox(points.anchor)) UNPLACED_WRITES.set(tree, points);
2476
+ else UNPLACED_WRITES.delete(tree);
2477
+ const writtenPoints = readDOMSelectionPoints(selection);
2478
+ RECORDS.set(tree, {
2479
+ points: readsSelectionAsHost(tree) || tree.nodeType === tree.DOCUMENT_FRAGMENT_NODE && points !== null && !writtenPoints ? points : writtenPoints,
2480
+ source: "write"
2481
+ });
2482
+ return true;
2483
+ };
2484
+ /** A copy of `selection`'s range at `index`, safe to keep or change. */
2485
+ const readDOMSelectionRange = (selection, index = 0) => selection.getRangeAt(index).cloneRange();
2486
+ //#endregion
2266
2487
  //#region src/dom/plugin/dom-input-runtime.ts
2267
2488
  /**
2268
2489
  * Choose the event phase that owns a default editing action.
@@ -2832,81 +3053,6 @@ var DOMInputRuntime = class {
2832
3053
  }
2833
3054
  };
2834
3055
  //#endregion
2835
- //#region src/dom/utils/selection-writes.ts
2836
- const RECORDS = /* @__PURE__ */ new WeakMap();
2837
- const UNPLACED_WRITES = /* @__PURE__ */ new WeakMap();
2838
- const hasLayoutBox = ([node]) => {
2839
- const element = node.nodeType === 1 ? node : node.parentElement;
2840
- return !!element && element.getClientRects().length > 0;
2841
- };
2842
- const readDOMSelectionPoints = (selection) => {
2843
- const { anchorNode, focusNode } = selection;
2844
- return selection.rangeCount > 0 && anchorNode && focusNode ? {
2845
- anchor: [anchorNode, selection.anchorOffset],
2846
- focus: [focusNode, selection.focusOffset]
2847
- } : null;
2848
- };
2849
- const sameDOMPoint = ([node, offset], [otherNode, otherOffset]) => node === otherNode && offset === otherOffset;
2850
- const sameDOMSelectionPoints = (points, other) => points === null || other === null ? points === other : sameDOMPoint(points.anchor, other.anchor) && sameDOMPoint(points.focus, other.focus);
2851
- const readDOMSelectionRecord = (tree) => RECORDS.get(tree) ?? null;
2852
- const recordDOMSelection = (tree, points, source) => {
2853
- RECORDS.set(tree, {
2854
- points,
2855
- source
2856
- });
2857
- UNPLACED_WRITES.delete(tree);
2858
- };
2859
- const forgetDOMSelectionRecord = (tree) => {
2860
- RECORDS.delete(tree);
2861
- UNPLACED_WRITES.delete(tree);
2862
- };
2863
- const touches = (container, points) => !!points && (container.contains(points.anchor[0]) || container.contains(points.focus[0]));
2864
- const forgetDOMSelectionRecordWithin = (tree, container) => {
2865
- if (touches(container, RECORDS.get(tree)?.points)) RECORDS.delete(tree);
2866
- if (touches(container, UNPLACED_WRITES.get(tree))) UNPLACED_WRITES.delete(tree);
2867
- };
2868
- const getDOMRangeSelectionPoints = (range, backward = false) => {
2869
- const start = [range.startContainer, range.startOffset];
2870
- const end = [range.endContainer, range.endOffset];
2871
- return backward ? {
2872
- anchor: end,
2873
- focus: start
2874
- } : {
2875
- anchor: start,
2876
- focus: end
2877
- };
2878
- };
2879
- const readsSelectionAsHost = (tree) => tree.nodeType === tree.DOCUMENT_FRAGMENT_NODE && isWebKitDOMHost(tree);
2880
- /**
2881
- * Write `points` as `tree`'s selection, keeping their direction, or clear its
2882
- * ranges for null, and record what the tree then shows, or the points written
2883
- * where the tree reads its selection as its host. A selection that already
2884
- * shows them is left alone, and so is the record, unless WebKit got them from
2885
- * a write while their anchor had no layout box, neither the user nor a write
2886
- * of other points has come since, and the anchor has one now.
2887
- */
2888
- const writeDOMSelection = (tree, points) => {
2889
- changeDOMSelection(tree, points);
2890
- };
2891
- const changeDOMSelection = (tree, points, beforeChange) => {
2892
- const selection = getSelection(tree);
2893
- if (!selection) return;
2894
- const rewritesUnplaced = points !== null && sameDOMSelectionPoints(UNPLACED_WRITES.get(tree) ?? null, points);
2895
- if (!rewritesUnplaced) UNPLACED_WRITES.delete(tree);
2896
- if (sameDOMSelectionPoints(readDOMSelectionPoints(selection), points) && !(rewritesUnplaced && hasLayoutBox(points.anchor))) return;
2897
- beforeChange?.();
2898
- if (points) selection.setBaseAndExtent(points.anchor[0], points.anchor[1], points.focus[0], points.focus[1]);
2899
- else selection.removeAllRanges();
2900
- if (points && hasDOMHostQuirk(tree, "unrendered-caret-needs-rewrite") && !hasLayoutBox(points.anchor)) UNPLACED_WRITES.set(tree, points);
2901
- else UNPLACED_WRITES.delete(tree);
2902
- RECORDS.set(tree, {
2903
- points: readsSelectionAsHost(tree) ? points : readDOMSelectionPoints(selection),
2904
- source: "write"
2905
- });
2906
- };
2907
- /** A copy of `selection`'s range at `index`, safe to keep or change. */
2908
- const readDOMSelectionRange = (selection, index = 0) => selection.getRangeAt(index).cloneRange();
2909
- //#endregion
2910
3056
  //#region src/dom/plugin/dom-integrity-observer.ts
2911
3057
  const OBSERVER_OPTIONS = {
2912
3058
  attributeOldValue: true,
@@ -3016,9 +3162,9 @@ const captureSelection = (root) => {
3016
3162
  };
3017
3163
  };
3018
3164
  const maxOffset = (node) => node.nodeType === TEXT_NODE ? node.nodeValue?.length ?? 0 : node.childNodes.length;
3019
- const restoreSelection = (root, snapshot) => {
3020
- if (!snapshot || !root.contains(snapshot.anchorNode) || !root.contains(snapshot.focusNode)) return;
3021
- writeDOMSelection(root.getRootNode(), {
3165
+ const restoreSelection = (root, snapshot, writeSelection) => {
3166
+ if (!snapshot || !writeSelection || !root.contains(snapshot.anchorNode) || !root.contains(snapshot.focusNode)) return;
3167
+ writeSelection(root, {
3022
3168
  anchor: [snapshot.anchorNode, Math.min(snapshot.anchorOffset, maxOffset(snapshot.anchorNode))],
3023
3169
  focus: [snapshot.focusNode, Math.min(snapshot.focusOffset, maxOffset(snapshot.focusNode))]
3024
3170
  });
@@ -3295,7 +3441,7 @@ var DOMIntegrityObserver = class {
3295
3441
  }));
3296
3442
  const selection = captureSelection(root);
3297
3443
  for (const mutation of mutations.reverse()) restoreMutation(mutation);
3298
- restoreSelection(root, selection);
3444
+ restoreSelection(root, selection, this.options.writeSelection);
3299
3445
  this.repairPassesInFrame += 1;
3300
3446
  this.scheduleRepairPassReset();
3301
3447
  this.diagnosticsValue.repairPasses += 1;
@@ -3863,12 +4009,21 @@ const findDOMRootRuntime = (node) => {
3863
4009
  }
3864
4010
  return null;
3865
4011
  };
4012
+ const isNestedEditableOrInput = (root, node) => {
4013
+ let current = node ? asElement(node) : null;
4014
+ while (current && current !== root) {
4015
+ const tag = current.tagName;
4016
+ const ce = current.getAttribute("contenteditable");
4017
+ if (tag === "INPUT" || tag === "TEXTAREA" || current.hasAttribute("data-editor") || ce !== null && ce.toLowerCase() !== "false") return true;
4018
+ current = composedParent(current);
4019
+ }
4020
+ return false;
4021
+ };
3866
4022
  const isRuntimeRootActive = (runtime) => {
3867
4023
  const root = runtime.rootRef.current;
3868
4024
  if (!root) return false;
3869
- const rootNode = root.getRootNode();
3870
- const activeElement = "activeElement" in rootNode ? rootNode.activeElement : root.ownerDocument.activeElement;
3871
- return activeElement === root || !!activeElement && root.contains(activeElement);
4025
+ const active = focusedElementOnPage(root);
4026
+ return !!active && (active === root || containsShadowAware(root, active) && !isNestedEditableOrInput(root, active));
3872
4027
  };
3873
4028
  const hasMountedDOMRoot = (editor) => DOM_ROOT_RUNTIMES_BY_EDITOR.has(editor);
3874
4029
  const hasMountedDocumentView = (editor) => MOUNTED_VIEWS_BY_DOCUMENT.has(documentOf(editor));
@@ -3919,6 +4074,104 @@ const isElementFocused = (element) => {
3919
4074
  node = frame;
3920
4075
  }
3921
4076
  };
4077
+ const isReadOnlyRoot = (editable, editor) => {
4078
+ const owner = editor ?? findDOMRootRuntime(editable)?.editor;
4079
+ return !!owner && !!IS_READ_ONLY.get(owner) || editable.getAttribute("contenteditable") === "false";
4080
+ };
4081
+ const canWriteDOMSelection = (editable, editor) => {
4082
+ if (isElementFocused(editable)) return true;
4083
+ if (!isReadOnlyRoot(editable, editor)) return false;
4084
+ const active = focusedElementOnPage(editable);
4085
+ return !active || active === active.ownerDocument.body || active === active.ownerDocument.documentElement || containsShadowAware(editable, active) && !isNestedEditableOrInput(editable, active);
4086
+ };
4087
+ const shadowRootsAbove = (element) => {
4088
+ const roots = [];
4089
+ let current = element;
4090
+ while (current) {
4091
+ const rootNode = current.getRootNode();
4092
+ if ("host" in rootNode) {
4093
+ const shadowRoot = rootNode;
4094
+ roots.push(shadowRoot);
4095
+ current = shadowRoot.host;
4096
+ } else break;
4097
+ }
4098
+ return roots;
4099
+ };
4100
+ const readComposedSelectionRange = (editable, selection, shadowRoots = shadowRootsAbove(editable)) => {
4101
+ const composedSelection = selection;
4102
+ if (typeof composedSelection.getComposedRanges !== "function") return null;
4103
+ try {
4104
+ return composedSelection.getComposedRanges({ shadowRoots })[0] ?? null;
4105
+ } catch {
4106
+ try {
4107
+ return composedSelection.getComposedRanges(...shadowRoots)[0] ?? null;
4108
+ } catch {
4109
+ return null;
4110
+ }
4111
+ }
4112
+ };
4113
+ const readEditableDOMSelectionPoints = (editable, selection) => {
4114
+ if (!selection) return null;
4115
+ const tree = editable.getRootNode();
4116
+ if (tree.nodeType === tree.DOCUMENT_FRAGMENT_NODE) {
4117
+ const composed = readComposedSelectionRange(editable, selection);
4118
+ if (composed) return {
4119
+ anchor: [composed.startContainer, composed.startOffset],
4120
+ focus: [composed.endContainer, composed.endOffset]
4121
+ };
4122
+ }
4123
+ return readDOMSelectionPoints(selection);
4124
+ };
4125
+ const isSelectionOwnedByEditable = (editable, selection, exclude) => {
4126
+ if (!selection) return false;
4127
+ const owns = (node) => !!node && containsShadowAware(editable, node) && !(exclude && exclude !== editable && containsShadowAware(exclude, node)) && !isNestedEditableOrInput(editable, node);
4128
+ if (owns(selection.anchorNode) || owns(selection.focusNode)) return true;
4129
+ const tree = editable.getRootNode();
4130
+ if (tree.nodeType !== tree.DOCUMENT_FRAGMENT_NODE) return false;
4131
+ const shadowRoots = shadowRootsAbove(editable);
4132
+ if (typeof selection.getComposedRanges === "function") {
4133
+ const composed = readComposedSelectionRange(editable, selection, shadowRoots);
4134
+ return !!composed && (owns(composed.startContainer) || owns(composed.endContainer));
4135
+ }
4136
+ if (!readsSelectionAsHost(tree)) return false;
4137
+ if (!shadowRoots.some((shadowRoot) => selection.anchorNode === shadowRoot.host || selection.focusNode === shadowRoot.host)) return false;
4138
+ if (selection.rangeCount > 0) try {
4139
+ const range = readDOMSelectionRange(selection);
4140
+ if (!shadowRoots.some((shadowRoot) => range.startContainer === shadowRoot.host && range.endContainer === shadowRoot.host)) return owns(range.startContainer) || owns(range.endContainer);
4141
+ } catch {
4142
+ return false;
4143
+ }
4144
+ const recorded = readDOMSelectionRecord(tree)?.points;
4145
+ return !!recorded && (owns(recorded.anchor[0]) || owns(recorded.focus[0]));
4146
+ };
4147
+ const shouldClearEditableDOMSelection = (editable, editor) => {
4148
+ const focusElement = findDOMRootRuntime(editable)?.nodeSelectionFocus();
4149
+ if (!canWriteDOMSelection(editable, editor) && !(focusElement && isElementFocused(focusElement))) return false;
4150
+ return isSelectionOwnedByEditable(editable, getSelection(editable.getRootNode()), focusElement);
4151
+ };
4152
+ const canWriteEditableDOMSelection = (editable, { editor, policy = "editable" } = {}) => policy === "focused" ? isElementFocused(editable) : canWriteDOMSelection(editable, editor);
4153
+ const writeEditableDOMSelection = (editable, points, { beforeChange, editor, policy = "editable", record = "write" } = {}) => {
4154
+ const tree = editable.getRootNode();
4155
+ const isAllowed = () => editable.getRootNode() === tree && canWriteEditableDOMSelection(editable, {
4156
+ editor,
4157
+ policy
4158
+ });
4159
+ if (!isAllowed()) return false;
4160
+ if (!changeDOMSelection(tree, points, beforeChange, isAllowed)) return false;
4161
+ if (record === "user") forgetDOMSelectionRecord(tree);
4162
+ return true;
4163
+ };
4164
+ const clearEditableDOMSelection = (editable, { beforeChange, editor, policy = "editable" } = {}) => {
4165
+ const tree = editable.getRootNode();
4166
+ const isAllowed = () => {
4167
+ if (editable.getRootNode() !== tree) return false;
4168
+ const focusElement = findDOMRootRuntime(editable)?.nodeSelectionFocus();
4169
+ const selection = getSelection(tree);
4170
+ return policy === "owned" ? isSelectionOwnedByEditable(editable, selection, focusElement) : policy === "focused" ? isElementFocused(editable) && isSelectionOwnedByEditable(editable, selection, focusElement) : shouldClearEditableDOMSelection(editable, editor);
4171
+ };
4172
+ if (!isAllowed()) return false;
4173
+ return changeDOMSelection(tree, null, beforeChange, isAllowed);
4174
+ };
3922
4175
  const resolveInnermostElementAtPoint = (document, x, y) => {
3923
4176
  let element = document.elementFromPoint(x, y);
3924
4177
  for (let inner = element && shadowRootOf(element)?.elementFromPoint(x, y); inner && inner !== element; inner = shadowRootOf(element)?.elementFromPoint(x, y)) element = inner;
@@ -3934,6 +4187,12 @@ const focusedElementOf = (top) => {
3934
4187
  return null;
3935
4188
  };
3936
4189
  const focusedElementOnPage = (node) => focusedElementOf(pageOf(node.ownerDocument ?? node));
4190
+ const movedFocusElsewhere = (element, before, after) => {
4191
+ if (!after || after === before || after === element || containsShadowAware(element, after) && !isNestedEditableOrInput(element, after)) return false;
4192
+ const ownDoc = element.ownerDocument;
4193
+ const topDoc = pageOf(ownDoc);
4194
+ return after !== ownDoc.body && after !== ownDoc.documentElement && after !== topDoc.body && after !== topDoc.documentElement;
4195
+ };
3937
4196
  const outerElementOf = (element) => {
3938
4197
  if (element.parentElement) return element.parentElement;
3939
4198
  const parent = element.parentNode;
@@ -3980,6 +4239,16 @@ const resolveDOMReach = (handle, request = {}) => {
3980
4239
  if (presentation) return reachOwnView(mounted, handle, presentation, request);
3981
4240
  return handle === owner ? reachDocumentView(mounted, handle, request) : null;
3982
4241
  };
4242
+ const resolveMountedViewForRoot = (handle, root) => {
4243
+ if (!hasEditorRuntime(handle)) return null;
4244
+ if (hasMountedDOMRoot(handle) && getEditorRuntimeRoot(handle) === root) return handle;
4245
+ const owner = documentOf(handle);
4246
+ const mounted = MOUNTED_VIEWS_BY_DOCUMENT.get(owner);
4247
+ if (!mounted) return null;
4248
+ const presentation = getOwnViewPresentation(handle);
4249
+ if (presentation) return pickView(mounted, (view) => getOwnViewPresentation(view) === presentation && getEditorRuntimeRoot(view) === root);
4250
+ return handle === owner ? reachDocumentView(mounted, handle, { root }) : null;
4251
+ };
3983
4252
  const resolveDOMTargetView = (handle, node) => {
3984
4253
  if (hasMountedDOMRoot(handle)) return handle;
3985
4254
  const view = node ? findDOMRootRuntime(node)?.editor : null;
@@ -4077,6 +4346,7 @@ var DOMRootRuntime = class DOMRootRuntime {
4077
4346
  this.schedulerImplementation = this.createScheduler();
4078
4347
  this.domSyncMutationOwnership = new DOMSyncMutationOwnership((phase, label, callback, scheduleOptions) => this.schedulerImplementation?.schedule(phase, label, callback, scheduleOptions) ?? (() => {}));
4079
4348
  this.domIntegrityObserver = new DOMIntegrityObserver({
4349
+ writeSelection: (root, points) => writeEditableDOMSelection(root, points, { editor: this.editor }),
4080
4350
  getAndroidMutationHandler: options.getAndroidMutationHandler,
4081
4351
  isAndroidMutationOwned: options.isAndroidMutationOwned,
4082
4352
  isCanonicalTextMutation: options.isCanonicalTextMutation,
@@ -5841,9 +6111,7 @@ const writeDataTransferFragment = (editor, data, slice, options = {}) => {
5841
6111
  //#region src/dom/plugin/dom-clipboard-runtime.ts
5842
6112
  const PLITE_FRAGMENT_ATTRIBUTE_RE = /\bdata-editor-fragment\s*=/i;
5843
6113
  const OPENING_HTML_TAG_RE = /<[A-Za-z][^<>]*?>/;
5844
- const DEFAULT_CLIPBOARD_FORMAT_KEY$1 = "x-editor-fragment";
5845
6114
  const PLITE_FRAGMENT_FORMAT_ATTRIBUTE = "data-editor-fragment-format";
5846
- const EDITOR_TO_CLIPBOARD_FORMAT_KEY = /* @__PURE__ */ new WeakMap();
5847
6115
  /** Semantic commands that own DOM clipboard ingress. */
5848
6116
  const domCommands = Object.freeze({ insertData: defineCommand("dom.insertData", {
5849
6117
  locate: false,
@@ -5861,14 +6129,6 @@ const stripRenderOnlyLeafWrappers = (root, ui) => {
5861
6129
  }
5862
6130
  });
5863
6131
  };
5864
- const setDOMClipboardFormatKey = (editor, clipboardFormatKey) => {
5865
- EDITOR_TO_CLIPBOARD_FORMAT_KEY.set(getEditorRuntimeOwner(editor), clipboardFormatKey);
5866
- };
5867
- const clearDOMClipboardFormatKey = (editor) => {
5868
- EDITOR_TO_CLIPBOARD_FORMAT_KEY.delete(getEditorRuntimeOwner(editor));
5869
- };
5870
- /** Read the configured MIME suffix used for exact Plite clipboard payloads. */
5871
- const getDOMClipboardFormatKey = (editor) => EDITOR_TO_CLIPBOARD_FORMAT_KEY.get(getEditorRuntimeOwner(editor)) ?? DEFAULT_CLIPBOARD_FORMAT_KEY$1;
5872
6132
  const escapeHtmlText = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
5873
6133
  const escapeHtmlAttribute = (text) => escapeHtmlText(text).replaceAll("\"", "&quot;");
5874
6134
  const attachFragmentMetadataToHtml = (html, encoded, clipboardFormatKey) => {
@@ -5996,7 +6256,7 @@ const encodeDOMFragmentData = (slice, window) => {
5996
6256
  return (window?.btoa ?? globalThis.btoa)(encodeURIComponent(string));
5997
6257
  };
5998
6258
  /** Write Plite fragment MIME, HTML, and plain-text clipboard payloads. */
5999
- const writeDOMFragmentData = (data, { clipboardFormatKey = DEFAULT_CLIPBOARD_FORMAT_KEY$1, html, slice, text, window }) => {
6259
+ const writeDOMFragmentData = (data, { clipboardFormatKey = DEFAULT_CLIPBOARD_FORMAT_KEY$2, html, slice, text, window }) => {
6000
6260
  const sourceSlice = ContentSlice.fromJSON(slice);
6001
6261
  const sourceText = text ?? getFragmentText(sourceSlice);
6002
6262
  const encoded = encodeDOMFragmentData(sourceSlice, window);
@@ -6253,7 +6513,7 @@ const writeDOMRangeData = (editor, data, range, options = {}) => {
6253
6513
  div.remove();
6254
6514
  return data;
6255
6515
  };
6256
- const insertDOMData = (editor, data) => dispatchCommand(editor, domCommands.insertData, data);
6516
+ const insertDOMData = (editor, data) => dispatchPaste(editor, () => readClipboardCut(data), () => landPaste(editor, () => dispatchCommand(editor, domCommands.insertData, data)));
6257
6517
  const createDOMDataTransactionSpec = (editor, data, state) => {
6258
6518
  const slice = readDOMFragmentData(editor, data);
6259
6519
  if (!slice) return createDataTransferTransactionSpec(editor, data, { state });
@@ -6301,8 +6561,7 @@ const writeDOMClipboardSlice = (editor, data, { formats = {}, slice }) => {
6301
6561
  };
6302
6562
  const insertDOMFragmentData = (editor, data) => {
6303
6563
  const slice = readDOMFragmentData(editor, data);
6304
- if (slice) return dispatchCommand(editor, editorCommands.replaceSlice, { slice });
6305
- return false;
6564
+ return dispatchPaste(editor, () => readClipboardCut(data), () => slice ? landPaste(editor, () => dispatchCommand(editor, editorCommands.replaceSlice, { slice })) : false);
6306
6565
  };
6307
6566
  const insertDOMTextData = (editor, data) => insertDataTransfer(editor, data, { mimeType: "text/plain" });
6308
6567
  //#endregion
@@ -7218,6 +7477,178 @@ const resolveVoidEventRange = (editor, { node, path, target, x, y }) => {
7218
7477
  return point$1 ? range(editor, point$1) : null;
7219
7478
  };
7220
7479
  //#endregion
7480
+ //#region src/dom/plugin/dom-scroll-into-view.ts
7481
+ const MARGIN = 4;
7482
+ const SCROLLABLE_RE = /(auto|scroll|overlay)/;
7483
+ 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;
7484
+ const toScrollRect = (r) => ({
7485
+ bottom: r.bottom,
7486
+ left: r.left,
7487
+ right: r.right,
7488
+ top: r.top
7489
+ });
7490
+ const shiftRect = (r, dx, dy) => ({
7491
+ bottom: r.bottom - dy,
7492
+ left: r.left - dx,
7493
+ right: r.right - dx,
7494
+ top: r.top - dy
7495
+ });
7496
+ const canScroll = (el, style, axis) => {
7497
+ const overflow = axis === "y" ? `${style?.overflowY ?? ""} ${style?.overflow ?? ""}` : `${style?.overflowX ?? ""} ${style?.overflow ?? ""}`;
7498
+ return SCROLLABLE_RE.test(overflow) && (axis === "y" ? el.scrollHeight > el.clientHeight : el.scrollWidth > el.clientWidth);
7499
+ };
7500
+ const pad = (value, size) => {
7501
+ const n = Number.parseFloat(value ?? "");
7502
+ if (!Number.isFinite(n) || n <= 0) return 0;
7503
+ return value?.trim().endsWith("%") ? n / 100 * size : n;
7504
+ };
7505
+ const paddedBox = (rect, style) => ({
7506
+ bottom: rect.bottom - pad(style?.scrollPaddingBottom, rect.height) - MARGIN,
7507
+ left: rect.left + pad(style?.scrollPaddingLeft, rect.width) + MARGIN,
7508
+ right: rect.right - pad(style?.scrollPaddingRight, rect.width) - MARGIN,
7509
+ top: rect.top + pad(style?.scrollPaddingTop, rect.height) + MARGIN
7510
+ });
7511
+ const getVisibleViewportBox = (win, scrollingElement) => {
7512
+ const vv = win.visualViewport;
7513
+ const height = vv?.height ?? win.innerHeight;
7514
+ const width = vv?.width ?? win.innerWidth;
7515
+ const top = vv ? Math.min(Math.max(0, vv.pageTop - win.scrollY), Math.max(0, vv.offsetTop)) : 0;
7516
+ const left = vv ? Math.min(Math.max(0, vv.pageLeft - win.scrollX), Math.max(0, vv.offsetLeft)) : 0;
7517
+ return paddedBox({
7518
+ bottom: top + height,
7519
+ height,
7520
+ left,
7521
+ right: left + width,
7522
+ top,
7523
+ width
7524
+ }, win.getComputedStyle(scrollingElement));
7525
+ };
7526
+ const axisDelta = (start, end, low, high, ownLow, ownHigh) => {
7527
+ if (low >= high) return 0;
7528
+ if (start < low) {
7529
+ const d = low - start;
7530
+ return ownHigh === void 0 ? -d : -Math.min(d, Math.max(0, ownHigh - end));
7531
+ }
7532
+ if (end > high) {
7533
+ const d = end - high;
7534
+ return ownLow === void 0 ? d : Math.min(d, Math.max(0, start - ownLow));
7535
+ }
7536
+ return 0;
7537
+ };
7538
+ const scrollAncestors = (startElement, scrollingElement, rect, visibleBox) => {
7539
+ let cur = rect;
7540
+ for (let el = getFlatTreeParentElement(startElement); el; el = getFlatTreeParentElement(el)) {
7541
+ if (el === scrollingElement) continue;
7542
+ const style = el.ownerDocument.defaultView?.getComputedStyle(el);
7543
+ const scrollY = canScroll(el, style, "y");
7544
+ const scrollX = canScroll(el, style, "x");
7545
+ if (!scrollY && !scrollX) continue;
7546
+ const own = paddedBox(el.getBoundingClientRect(), style);
7547
+ 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;
7548
+ 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;
7549
+ if (dy === 0 && dx === 0) continue;
7550
+ const prevTop = el.scrollTop;
7551
+ const prevLeft = el.scrollLeft;
7552
+ el.scrollTop += dy;
7553
+ el.scrollLeft += dx;
7554
+ cur = shiftRect(cur, el.scrollLeft - prevLeft, el.scrollTop - prevTop);
7555
+ }
7556
+ return cur;
7557
+ };
7558
+ const outsideBox = (rect, box, tolerance = 0) => rect.top < box.top - tolerance || rect.bottom > box.bottom + tolerance || rect.left < box.left - tolerance || rect.right > box.right + tolerance;
7559
+ const setCaretScrollMargin = (el, elRect, caret, top, right, bottom, left) => {
7560
+ el.style.setProperty("scroll-margin", `${top - (caret.top - elRect.top)}px ${right - (elRect.right - caret.right)}px ${bottom - (elRect.bottom - caret.bottom)}px ${left - (caret.left - elRect.left)}px`);
7561
+ };
7562
+ const canPanVisualViewport = (win, scrollingElement, el) => {
7563
+ const vv = win.visualViewport;
7564
+ return Boolean(vv && isDOMHTMLElement(el) && typeof el.scrollIntoView === "function" && (vv.height < scrollingElement.clientHeight || vv.width < scrollingElement.clientWidth));
7565
+ };
7566
+ const panVisualViewportNearest = (win, scrollingElement, el, caret) => {
7567
+ const vv = win.visualViewport;
7568
+ if (!vv || !canPanVisualViewport(win, scrollingElement, el)) return caret;
7569
+ const elRect = el.getBoundingClientRect();
7570
+ const prev = el.style.getPropertyValue("scroll-margin");
7571
+ const priority = el.style.getPropertyPriority("scroll-margin");
7572
+ const caretAfter = () => {
7573
+ const afterRect = el.getBoundingClientRect();
7574
+ return shiftRect(caret, elRect.left - afterRect.left, elRect.top - afterRect.top);
7575
+ };
7576
+ setCaretScrollMargin(el, elRect, caret, MARGIN, MARGIN, MARGIN, MARGIN);
7577
+ el.scrollIntoView({
7578
+ block: "nearest",
7579
+ inline: "nearest"
7580
+ });
7581
+ let nextCaret = caretAfter();
7582
+ if (outsideBox(nextCaret, getVisibleViewportBox(win, scrollingElement), 1)) {
7583
+ const rootStyle = win.getComputedStyle(scrollingElement);
7584
+ const padTop = pad(rootStyle.scrollPaddingTop, vv.height);
7585
+ const padRight = pad(rootStyle.scrollPaddingRight, vv.width);
7586
+ const padBottom = pad(rootStyle.scrollPaddingBottom, vv.height);
7587
+ const padLeft = pad(rootStyle.scrollPaddingLeft, vv.width);
7588
+ if (padTop > 0 || padRight > 0 || padBottom > 0 || padLeft > 0) {
7589
+ setCaretScrollMargin(el, elRect, caret, MARGIN + padTop, MARGIN + padRight, MARGIN + padBottom, MARGIN + padLeft);
7590
+ el.scrollIntoView({
7591
+ block: "nearest",
7592
+ inline: "nearest"
7593
+ });
7594
+ nextCaret = caretAfter();
7595
+ }
7596
+ }
7597
+ if (prev) el.style.setProperty("scroll-margin", prev, priority);
7598
+ else el.style.removeProperty("scroll-margin");
7599
+ return nextCaret;
7600
+ };
7601
+ const panVisualViewportCenter = (win, scrollingElement, el, caret) => {
7602
+ if (!canPanVisualViewport(win, scrollingElement, el)) return;
7603
+ const elRect = el.getBoundingClientRect();
7604
+ const prev = el.style.getPropertyValue("scroll-margin");
7605
+ const priority = el.style.getPropertyPriority("scroll-margin");
7606
+ setCaretScrollMargin(el, elRect, caret, MARGIN, MARGIN, MARGIN, MARGIN);
7607
+ el.scrollIntoView({
7608
+ block: "center",
7609
+ inline: "nearest"
7610
+ });
7611
+ if (prev) el.style.setProperty("scroll-margin", prev, priority);
7612
+ else el.style.removeProperty("scroll-margin");
7613
+ };
7614
+ const scrollRectIntoViewIfNeeded = ({ rect, startElement }) => {
7615
+ const scrollingElement = startElement.ownerDocument.scrollingElement ?? startElement.ownerDocument.documentElement;
7616
+ let cur = scrollAncestors(startElement, scrollingElement, rect, null);
7617
+ const win = startElement.ownerDocument.defaultView;
7618
+ if (!win) return;
7619
+ let visible = getVisibleViewportBox(win, scrollingElement);
7620
+ const dy = scrollingElement.scrollHeight > scrollingElement.clientHeight ? axisDelta(cur.top, cur.bottom, visible.top, visible.bottom) : 0;
7621
+ const dx = scrollingElement.scrollWidth > scrollingElement.clientWidth ? axisDelta(cur.left, cur.right, visible.left, visible.right) : 0;
7622
+ if (dy !== 0 || dx !== 0) {
7623
+ const prevY = win.scrollY;
7624
+ const prevX = win.scrollX;
7625
+ win.scrollBy(dx, dy);
7626
+ cur = shiftRect(cur, win.scrollX - prevX, win.scrollY - prevY);
7627
+ visible = getVisibleViewportBox(win, scrollingElement);
7628
+ }
7629
+ if (outsideBox(cur, visible, 1)) {
7630
+ cur = panVisualViewportNearest(win, scrollingElement, startElement, cur);
7631
+ visible = getVisibleViewportBox(win, scrollingElement);
7632
+ }
7633
+ if (outsideBox(cur, visible)) cur = scrollAncestors(startElement, scrollingElement, cur, visible);
7634
+ if (outsideBox(cur, visible, 1)) panVisualViewportCenter(win, scrollingElement, startElement, cur);
7635
+ };
7636
+ const scrollDOMRangeFocusIntoViewIfNeeded = (domRange, isBackward = false) => {
7637
+ const focusRange = domRange.cloneRange();
7638
+ focusRange.collapse(isBackward);
7639
+ const container = focusRange.startContainer;
7640
+ const leafEl = isDOMElement(container) ? container : container.parentElement;
7641
+ if (!leafEl) return;
7642
+ if (typeof focusRange.getBoundingClientRect !== "function") return;
7643
+ const domRect = focusRange.getBoundingClientRect();
7644
+ const targetRect = isUsableScrollRect(domRect) ? domRect : leafEl.getBoundingClientRect();
7645
+ if (!isUsableScrollRect(targetRect)) return;
7646
+ scrollRectIntoViewIfNeeded({
7647
+ rect: toScrollRect(targetRect),
7648
+ startElement: leafEl
7649
+ });
7650
+ };
7651
+ //#endregion
7221
7652
  //#region src/dom/plugin/dom-view-caret.ts
7222
7653
  const liftCaretOutOfCollapsedSection = (view, coverage, composing, selection) => {
7223
7654
  if (!RangeApi.isRange(selection) || !RangeApi.isCollapsed(selection)) return selection;
@@ -7270,6 +7701,41 @@ const claimFocusRequest = (editor, element) => {
7270
7701
  supersedeFocusRequest(editor);
7271
7702
  PAGE_TO_FOCUS_REQUEST_OWNER.set(pageOf(element.ownerDocument), { editor: new WeakRef(editor) });
7272
7703
  };
7704
+ const isAncestorChainActive = (node) => {
7705
+ let current = node;
7706
+ while (current) {
7707
+ const tree = current.getRootNode();
7708
+ if (tree.activeElement !== current) return false;
7709
+ current = "host" in tree ? tree.host : tree.defaultView?.frameElement ?? null;
7710
+ }
7711
+ return true;
7712
+ };
7713
+ const focusEnclosingFrames = (el) => {
7714
+ const frames = [];
7715
+ for (let frame = el.ownerDocument.defaultView?.frameElement; frame; frame = frame.ownerDocument.defaultView?.frameElement) if ("focus" in frame && typeof frame.focus === "function") frames.push(frame);
7716
+ for (let i = frames.length - 1; i >= 0; i -= 1) {
7717
+ const frame = frames[i];
7718
+ const frameDoc = "contentDocument" in frame ? frame.contentDocument : null;
7719
+ const expectedChild = i > 0 ? frames[i - 1] : el;
7720
+ const childBefore = frameDoc?.activeElement ?? null;
7721
+ if (isAncestorChainActive(frame)) continue;
7722
+ frame.focus({ preventScroll: true });
7723
+ if (!isAncestorChainActive(frame)) return false;
7724
+ const childAfter = frameDoc?.activeElement ?? null;
7725
+ if (childAfter && childAfter !== childBefore && childAfter !== expectedChild && childAfter !== frameDoc?.body && childAfter !== frameDoc?.documentElement) return false;
7726
+ }
7727
+ return true;
7728
+ };
7729
+ const focusEditableElement = (editor, el) => {
7730
+ if (!focusEnclosingFrames(el)) return false;
7731
+ IS_FOCUSED.set(editor, true);
7732
+ setEditorFocused(editor, true);
7733
+ el.focus({ preventScroll: true });
7734
+ if (isElementFocused(el)) return true;
7735
+ IS_FOCUSED.delete(editor);
7736
+ setEditorFocused(editor, false);
7737
+ return false;
7738
+ };
7273
7739
  const getLastChildren = (element) => {
7274
7740
  if (element.childElementCount > 0) return getLastChildren(element.children[0]);
7275
7741
  return element;
@@ -7383,15 +7849,81 @@ const setEditorDOMScrollElement = (editor, element, { fallback = false } = {}) =
7383
7849
  if (setWeakElement(fallback ? EDITOR_TO_DOM_FALLBACK_SCROLL : EDITOR_TO_DOM_SCROLL, owner, element)) notifyEditorDOMScopeListeners(owner);
7384
7850
  };
7385
7851
  const ELEMENT_TO_ROOT_REVEAL = /* @__PURE__ */ new WeakMap();
7852
+ const VIEW_TO_SCROLL_TOKEN = /* @__PURE__ */ new WeakMap();
7853
+ const nextScrollIntoViewToken = (scope) => {
7854
+ const token = (VIEW_TO_SCROLL_TOKEN.get(scope) ?? 0) + 1;
7855
+ VIEW_TO_SCROLL_TOKEN.set(scope, token);
7856
+ return token;
7857
+ };
7858
+ const hasCSSScrollMargin = (element) => {
7859
+ const win = element.ownerDocument?.defaultView;
7860
+ if (!win) return false;
7861
+ const style = win.getComputedStyle(element);
7862
+ return (Number.parseFloat(element.style.scrollMarginTop || style.scrollMarginTop) || 0) > 0 || (Number.parseFloat(element.style.scrollMarginBottom || style.scrollMarginBottom) || 0) > 0 || (Number.parseFloat(element.style.scrollMarginLeft || style.scrollMarginLeft) || 0) > 0 || (Number.parseFloat(element.style.scrollMarginRight || style.scrollMarginRight) || 0) > 0;
7863
+ };
7864
+ const runScrollIntoViewIfNeeded = (element, options) => {
7865
+ if (typeof options !== "object" || options === null || typeof options.behavior === "function" || !hasCSSScrollMargin(element)) {
7866
+ scrollIntoViewIfNeeded(element, options);
7867
+ return;
7868
+ }
7869
+ const { behavior } = options;
7870
+ scrollIntoViewIfNeeded(element, {
7871
+ ...options,
7872
+ behavior: (actions) => {
7873
+ for (const { el, left, top } of actions) if (el.scrollTop !== top || el.scrollLeft !== left) el.scroll({
7874
+ behavior,
7875
+ left,
7876
+ top
7877
+ });
7878
+ }
7879
+ });
7880
+ };
7881
+ const getScrollIntoViewScope = (editor, fallback) => hasEditorRuntime(editor) ? getOwnViewPresentation(editor) ?? documentOf(editor) : fallback;
7882
+ const findMountedAncestorRevealStep = (editor, targetRoot) => {
7883
+ if (!hasEditorRuntime(editor)) return null;
7884
+ const owner = getEditorRuntimeOwner(editor);
7885
+ const entryByRoot = new Map(readRootEntries(owner).map((entry) => [entry.root, entry]));
7886
+ const visited = /* @__PURE__ */ new Set([targetRoot]);
7887
+ const queue = [targetRoot];
7888
+ for (const currentRoot of queue) {
7889
+ const entry = entryByRoot.get(currentRoot);
7890
+ if (!entry) continue;
7891
+ for (const edge of entry.owners) {
7892
+ const parentRoot = toInternalRoot(edge.root);
7893
+ const mountedParent = resolveMountedViewForRoot(editor, parentRoot);
7894
+ if (mountedParent) return {
7895
+ ownerPath: edge.path,
7896
+ ownerRoot: parentRoot,
7897
+ ownerView: mountedParent
7898
+ };
7899
+ if (!visited.has(parentRoot)) {
7900
+ visited.add(parentRoot);
7901
+ queue.push(parentRoot);
7902
+ }
7903
+ }
7904
+ }
7905
+ return null;
7906
+ };
7907
+ const getScrollTargetRoot = (editor, target) => {
7908
+ if (!PathApi.isPath(target) && !PointApi.isPoint(target) && !RangeApi.isRange(target)) return null;
7909
+ const explicitRoot = getPublicExplicitLocationRoot(target);
7910
+ if (explicitRoot !== void 0) return toInternalRoot(explicitRoot);
7911
+ if (hasEditorRuntime(editor)) return getEditorRuntimeRoot(editor);
7912
+ return null;
7913
+ };
7386
7914
  const setEditableRootReveal = (element, reveal) => {
7387
- ELEMENT_TO_ROOT_REVEAL.set(element, reveal);
7915
+ const registration = typeof reveal === "function" ? {
7916
+ revealCulled: reveal,
7917
+ revealMounted: reveal
7918
+ } : reveal;
7919
+ ELEMENT_TO_ROOT_REVEAL.set(element, registration);
7388
7920
  return () => {
7389
- if (ELEMENT_TO_ROOT_REVEAL.get(element) === reveal) ELEMENT_TO_ROOT_REVEAL.delete(element);
7921
+ if (ELEMENT_TO_ROOT_REVEAL.get(element) === registration) ELEMENT_TO_ROOT_REVEAL.delete(element);
7390
7922
  };
7391
7923
  };
7392
7924
  const revealInEditableRoot = (element, path) => {
7393
7925
  const root = element.closest("[data-editor-root]");
7394
- if (root) ELEMENT_TO_ROOT_REVEAL.get(root)?.(path, "auto");
7926
+ if (root) ELEMENT_TO_ROOT_REVEAL.get(root)?.revealMounted?.(path, "auto");
7395
7927
  };
7396
7928
  const getEditorDOMHostScrollElement = (editor) => EDITOR_TO_DOM_SCROLL.get(documentOf(editor)) ?? null;
7397
7929
  const getRegisteredScrollElement = (editor) => getEditorDOMHostScrollElement(editor) ?? EDITOR_TO_DOM_FALLBACK_SCROLL.get(editor) ?? EDITOR_TO_DOM_FALLBACK_SCROLL.get(documentOf(editor));
@@ -7621,8 +8153,11 @@ const DOMEditorImpl = {
7621
8153
  },
7622
8154
  deselect: (editor) => {
7623
8155
  const selection = editor.read((state) => state.selection());
7624
- const root = DOMEditor.resolveDocumentOrShadowRoot(editor);
7625
- if (root) writeDOMSelection(root, null);
8156
+ const el = DOMEditor.editable(editor);
8157
+ if (el) clearEditableDOMSelection(el, {
8158
+ editor,
8159
+ policy: "owned"
8160
+ });
7626
8161
  if (selection) editor.update((tx) => {
7627
8162
  tx.selection.set(null);
7628
8163
  });
@@ -7710,11 +8245,6 @@ const DOMEditorImpl = {
7710
8245
  if (retries <= 0) return;
7711
8246
  PAGE_TO_FOCUS_REQUEST_OWNER.set(pageOf(el.ownerDocument), { editor: new WeakRef(editor) });
7712
8247
  const superseded = watchFocusSuperseded(editor, el);
7713
- const markAndFocus = () => {
7714
- IS_FOCUSED.set(editor, true);
7715
- setEditorFocused(editor, true);
7716
- el.focus({ preventScroll: true });
7717
- };
7718
8248
  if (IS_NODE_MAP_DIRTY.get(editor)) {
7719
8249
  let cancel = () => {};
7720
8250
  const generation = getPlacementGeneration(editor);
@@ -7731,8 +8261,10 @@ const DOMEditorImpl = {
7731
8261
  return;
7732
8262
  }
7733
8263
  if (findDOMRootRuntime(el)?.focusSelection(el)) return;
8264
+ const activeBeforeCaret = focusedElementOnPage(el);
7734
8265
  const selection = ensureFocusCaret(editor, el);
7735
- if (superseded()) return;
8266
+ if (superseded() || movedFocusElsewhere(el, activeBeforeCaret, focusedElementOnPage(el))) return;
8267
+ const focusPlacement = getPlacementGeneration(editor);
7736
8268
  const selectionAtFocus = selection ? getSelectionDOMRange(editor, selection) : null;
7737
8269
  const syncDomSelection = () => {
7738
8270
  if (findDOMRootRuntime(el)?.isSelectionHeld()) return;
@@ -7740,7 +8272,7 @@ const DOMEditorImpl = {
7740
8272
  if (innerSelection) {
7741
8273
  const projectedSelection = getSelectionDOMRange(editor, innerSelection);
7742
8274
  if (!projectedSelection) {
7743
- writeDOMSelection(root, null);
8275
+ clearEditableDOMSelection(el, { editor });
7744
8276
  return;
7745
8277
  }
7746
8278
  const view = reachAt(editor, projectedSelection);
@@ -7748,7 +8280,10 @@ const DOMEditorImpl = {
7748
8280
  exportingSelection: true,
7749
8281
  rejectStaleText: true
7750
8282
  });
7751
- if (domRange) writeDOMSelection(root, getDOMRangeSelectionPoints(domRange, RangeApi.isBackward(projectedSelection)));
8283
+ if (domRange) writeEditableDOMSelection((view && view !== editor ? DOMEditor.editable(view) : null) ?? el, getDOMRangeSelectionPoints(domRange, RangeApi.isBackward(projectedSelection)), {
8284
+ editor: view ?? editor,
8285
+ policy: "focused"
8286
+ });
7752
8287
  }
7753
8288
  };
7754
8289
  const trySyncDomSelection = () => {
@@ -7766,18 +8301,20 @@ const DOMEditorImpl = {
7766
8301
  const rootActiveElement = root.activeElement;
7767
8302
  const shadowHost = "host" in root ? root.host : null;
7768
8303
  const activeElement = rootActiveElement ?? (root === el.ownerDocument ? null : el.ownerDocument.activeElement);
7769
- if (activeElement === el) {
8304
+ if (isElementFocused(el)) {
8305
+ if (placedSince(editor, focusPlacement)) return;
7770
8306
  trySyncDomSelection();
7771
8307
  return;
7772
8308
  }
7773
- if (activeElement?.isConnected && containsShadowAware(el, activeElement)) {
8309
+ if (activeElement && activeElement !== el && activeElement.isConnected && containsShadowAware(el, activeElement)) {
7774
8310
  ownedActiveElement = activeElement;
7775
8311
  return;
7776
8312
  }
7777
- if (!(activeElement === null || activeElement === el.ownerDocument.body || rootActiveElement === null && activeElement === shadowHost || activeElement === ownedActiveElement && !activeElement.isConnected)) return;
7778
- markAndFocus();
8313
+ const pageActive = focusedElementOnPage(el);
8314
+ if (!(pageActive === null || pageActive === pageActive.ownerDocument.body || rootActiveElement === null && activeElement === shadowHost || activeElement !== null && activeElement === ownedActiveElement && !activeElement.isConnected)) return;
8315
+ const focused = focusEditableElement(editor, el);
7779
8316
  if (superseded()) return;
7780
- trySyncDomSelection();
8317
+ if (focused) trySyncDomSelection();
7781
8318
  };
7782
8319
  const scheduleFocusSettle = () => {
7783
8320
  scheduleEditorDOMPhase(editor, "dom-write", "dom-editor-focus-settle-microtask", settleFocus, {
@@ -7794,15 +8331,16 @@ const DOMEditorImpl = {
7794
8331
  timing: "timeout"
7795
8332
  });
7796
8333
  };
7797
- if (root.activeElement !== el) {
8334
+ if (!isElementFocused(el)) {
7798
8335
  const { activeElement } = root;
7799
- if (isDOMElement(activeElement) && containsShadowAware(el, activeElement) && "blur" in activeElement && typeof activeElement.blur === "function") {
8336
+ if (isDOMElement(activeElement) && activeElement !== el && containsShadowAware(el, activeElement) && "blur" in activeElement && typeof activeElement.blur === "function") {
8337
+ const activeBeforeBlur = focusedElementOnPage(el);
7800
8338
  activeElement.blur();
7801
- if (superseded()) return;
8339
+ if (superseded() || movedFocusElsewhere(el, activeBeforeBlur, focusedElementOnPage(el))) return;
7802
8340
  }
7803
- markAndFocus();
8341
+ const focused = focusEditableElement(editor, el);
7804
8342
  if (superseded()) return;
7805
- trySyncDomSelection();
8343
+ if (focused) trySyncDomSelection();
7806
8344
  if (selectionAtFocus) scheduleEditorDOMPhase(editor, "selection-repair", "dom-editor-focus-selection-sync", () => {
7807
8345
  if (superseded() || !isElementFocused(el)) return;
7808
8346
  const currentSelection = getSelectionDOMRange(editor, resolveNextKeyCaret(editor, el));
@@ -7924,67 +8462,178 @@ const DOMEditorImpl = {
7924
8462
  },
7925
8463
  scroll: (editor) => getRegisteredScrollElement(editor) ?? DOMEditor.root(editor) ?? DOMEditor.editable(editor) ?? null,
7926
8464
  scrollIntoView: (editor, target, options = { scrollMode: "if-needed" }) => {
7927
- const requestedScrollMarginTop = PathApi.isPath(target) ? (() => {
7928
- const node = editor.read((state) => state.nodes.get(target)?.[0]);
7929
- const element = node ? DOMEditor.resolveDOMNode(editor, node) : null;
7930
- const window = element?.ownerDocument?.defaultView;
7931
- if (!element || !window) return 0;
8465
+ 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;
8466
+ const readScrollMarginTop = (element) => {
8467
+ const window = element.ownerDocument?.defaultView;
8468
+ if (!window) return 0;
7932
8469
  const style = window.getComputedStyle(element);
7933
8470
  return Number.parseFloat(element.style.scrollMarginTop || style.scrollMarginTop) || 0;
7934
- })() : 0;
8471
+ };
8472
+ const canReadEditor = typeof editor.read === "function";
8473
+ const isLocationTarget = PathApi.isPath(target) || PointApi.isPoint(target) || RangeApi.isRange(target);
8474
+ const targetRoot = canReadEditor ? getScrollTargetRoot(editor, target) : null;
8475
+ const resolveTargetView = () => {
8476
+ if (!canReadEditor) return editor;
8477
+ if (isLocationTarget) return reachAt(editor, target) ?? (targetRoot ? resolveMountedViewForRoot(editor, targetRoot) : null);
8478
+ return hasMountedDocumentView(editor) ? resolveDOMReach(editor) : editor;
8479
+ };
8480
+ const initialView = resolveTargetView();
8481
+ const initialAncestorStep = !initialView && targetRoot ? findMountedAncestorRevealStep(editor, targetRoot) : null;
8482
+ const initialSchedulerView = initialView ?? initialAncestorStep?.ownerView ?? null;
8483
+ if (!initialSchedulerView) return () => {};
8484
+ const scrollScope = getScrollIntoViewScope(editor, initialSchedulerView);
8485
+ const scrollToken = nextScrollIntoViewToken(scrollScope);
8486
+ const isStale = () => cancelled || VIEW_TO_SCROLL_TOKEN.get(scrollScope) !== scrollToken;
8487
+ const initialPathElement = initialView && PathApi.isPath(target) && typeof initialView.read === "function" ? (() => {
8488
+ const node = initialView.read((state) => state.nodes.get(target)?.[0]);
8489
+ return node ? DOMEditor.resolveDOMNode(initialView, node) : null;
8490
+ })() : null;
8491
+ const initialScrollMarginTop = initialPathElement ? readScrollMarginTop(initialPathElement) : 0;
8492
+ const resolveCulledPaths = (view) => {
8493
+ if (PathApi.isPath(target)) return [target];
8494
+ if (PointApi.isPoint(target)) return [target.path];
8495
+ if (!RangeApi.isRange(target)) return [];
8496
+ const startPath = RangeApi.start(target).path;
8497
+ const endPath = RangeApi.end(target).path;
8498
+ if (PathApi.equals(startPath, endPath) || typeof view.read !== "function") return [startPath];
8499
+ const missing = [];
8500
+ const startNode = view.read((state) => state.nodes.get(startPath)?.[0]);
8501
+ const endNode = view.read((state) => state.nodes.get(endPath)?.[0]);
8502
+ if (!startNode || !DOMEditor.resolveDOMNode(view, startNode)) missing.push(startPath);
8503
+ if (!endNode || !DOMEditor.resolveDOMNode(view, endNode)) missing.push(endPath);
8504
+ return missing.length > 0 ? missing : [startPath];
8505
+ };
8506
+ const alwaysMode = typeof options === "object" && options?.scrollMode === "always";
8507
+ const schedulePhase = (schedulerView, label, callback) => scheduleEditorDOMPhase(schedulerView, alwaysMode ? "post-selection" : "dom-write", label, callback, {
8508
+ key: "dom-editor-scroll-into-view",
8509
+ timing: "animation-frame"
8510
+ });
8511
+ let cancelled = false;
8512
+ let retriedTarget = false;
8513
+ const revealedAncestors = /* @__PURE__ */ new Set();
8514
+ let cancelRetry;
8515
+ const revealCulledOnView = (view, paths) => {
8516
+ if (paths.length === 0) return false;
8517
+ const editable = EDITOR_TO_ELEMENT.get(view) ?? (typeof view.read === "function" ? DOMEditorImpl.editable(view) : null);
8518
+ const reveal = editable ? ELEMENT_TO_ROOT_REVEAL.get(editable)?.revealCulled : void 0;
8519
+ if (!reveal) return false;
8520
+ let revealed = false;
8521
+ for (const path of paths) {
8522
+ if (reveal(path, "auto") === true) revealed = true;
8523
+ if (isStale()) return false;
8524
+ }
8525
+ return revealed;
8526
+ };
8527
+ const retryAfterTargetReveal = (view) => {
8528
+ if (isStale() || retriedTarget) return;
8529
+ const paths = resolveCulledPaths(view);
8530
+ if (!revealCulledOnView(view, paths) || isStale()) return;
8531
+ retriedTarget = true;
8532
+ cancelRetry = schedulePhase(view, "dom-editor-scroll-into-view-retry", run);
8533
+ };
7935
8534
  const run = () => {
8535
+ if (isStale()) return;
8536
+ const activeView = resolveTargetView();
8537
+ if (!activeView) {
8538
+ if (!targetRoot) return;
8539
+ const step = findMountedAncestorRevealStep(editor, targetRoot);
8540
+ if (!step) return;
8541
+ const stepKey = `${step.ownerRoot}:${step.ownerPath.join(".")}`;
8542
+ if (revealedAncestors.has(stepKey)) return;
8543
+ revealedAncestors.add(stepKey);
8544
+ if (!revealCulledOnView(step.ownerView, [step.ownerPath]) || isStale()) return;
8545
+ cancelRetry = schedulePhase(step.ownerView, "dom-editor-scroll-into-view-ancestor-retry", run);
8546
+ return;
8547
+ }
8548
+ const canReadActiveView = typeof activeView.read === "function";
7936
8549
  if (PathApi.isPath(target)) {
7937
- const node = editor.read((state) => state.nodes.get(target)?.[0]);
7938
- const element = node ? DOMEditor.resolveDOMNode(editor, node) : null;
7939
- if (element) {
7940
- revealInEditableRoot(element, target);
7941
- const scrollElement = getRegisteredScrollElement(editor);
7942
- if (scrollElement && requestedScrollMarginTop > 0 && typeof options === "object" && options.block === "start" && options.scrollMode === "always") {
7943
- const elementRect = element.getBoundingClientRect();
7944
- const scrollRect = scrollElement.getBoundingClientRect();
7945
- scrollElement.scroll({
7946
- behavior: options.behavior ?? "auto",
7947
- left: scrollElement.scrollLeft,
7948
- top: scrollElement.scrollTop + elementRect.top - scrollRect.top - requestedScrollMarginTop
7949
- });
7950
- } else scrollIntoViewIfNeeded(element, options);
8550
+ const node = canReadActiveView ? activeView.read((state) => state.nodes.get(target)?.[0]) : void 0;
8551
+ const element = node ? DOMEditor.resolveDOMNode(activeView, node) : null;
8552
+ if (!element) {
8553
+ retryAfterTargetReveal(activeView);
8554
+ return;
7951
8555
  }
8556
+ revealInEditableRoot(element, target);
8557
+ const scrollElement = getRegisteredScrollElement(activeView);
8558
+ const requestedScrollMarginTop = initialPathElement ? initialScrollMarginTop : readScrollMarginTop(element);
8559
+ if (scrollElement && requestedScrollMarginTop > 0 && typeof options === "object" && options.block === "start" && options.scrollMode === "always") {
8560
+ const elementRect = element.getBoundingClientRect();
8561
+ const scrollRect = scrollElement.getBoundingClientRect();
8562
+ scrollElement.scroll({
8563
+ behavior: options.behavior ?? "auto",
8564
+ left: scrollElement.scrollLeft,
8565
+ top: scrollElement.scrollTop + elementRect.top - scrollRect.top - requestedScrollMarginTop
8566
+ });
8567
+ } else if (usesDefaultReveal) {
8568
+ const rect = element.getBoundingClientRect();
8569
+ if (isUsableScrollRect(rect)) scrollRectIntoViewIfNeeded({
8570
+ rect: toScrollRect(rect),
8571
+ startElement: element
8572
+ });
8573
+ } else runScrollIntoViewIfNeeded(element, options);
7952
8574
  return;
7953
8575
  }
7954
- const domRange = PointApi.isPoint(target) ? DOMEditor.resolveDOMRange(editor, {
8576
+ const domRange = PointApi.isPoint(target) ? DOMEditor.resolveDOMRange(activeView, {
7955
8577
  anchor: target,
7956
8578
  focus: target
7957
- }) : RangeApi.isRange(target) ? DOMEditor.resolveDOMRange(editor, target) : target;
7958
- if (!domRange) return;
8579
+ }) : RangeApi.isRange(target) ? DOMEditor.resolveDOMRange(activeView, target) : target;
8580
+ if (!domRange) {
8581
+ retryAfterTargetReveal(activeView);
8582
+ return;
8583
+ }
7959
8584
  const leafElement = isDOMElement(domRange.startContainer) ? domRange.startContainer : domRange.startContainer.parentElement;
7960
8585
  if (!leafElement) return;
7961
8586
  if (PointApi.isPoint(target)) revealInEditableRoot(leafElement, target.path);
7962
8587
  else if (RangeApi.isRange(target)) revealInEditableRoot(leafElement, RangeApi.start(target).path);
8588
+ if (usesDefaultReveal) {
8589
+ const range = RangeApi.isRange(target) ? target : PointApi.isPoint(target) ? null : editor.read((state) => state.selection());
8590
+ scrollDOMRangeFocusIntoViewIfNeeded(domRange, Boolean(range && RangeApi.isBackward(range)));
8591
+ return;
8592
+ }
7963
8593
  const hadOwnRect = Object.hasOwn(leafElement, "getBoundingClientRect");
7964
8594
  const originalGetBoundingClientRect = leafElement.getBoundingClientRect;
7965
- leafElement.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
8595
+ const nearestScrollMarginTop = typeof options === "object" && options !== null && (options.block === void 0 || options.block === "nearest") ? readScrollMarginTop(leafElement) : 0;
8596
+ leafElement.getBoundingClientRect = () => {
8597
+ const rangeRect = domRange.getBoundingClientRect();
8598
+ const baseRect = isUsableScrollRect(rangeRect) ? rangeRect : originalGetBoundingClientRect.call(leafElement);
8599
+ if (nearestScrollMarginTop <= 0) return baseRect;
8600
+ return {
8601
+ bottom: baseRect.bottom + nearestScrollMarginTop,
8602
+ height: baseRect.height + nearestScrollMarginTop,
8603
+ left: baseRect.left,
8604
+ right: baseRect.right,
8605
+ toJSON: () => baseRect.toJSON?.() ?? {},
8606
+ top: baseRect.top,
8607
+ width: baseRect.width,
8608
+ x: baseRect.x,
8609
+ y: baseRect.y
8610
+ };
8611
+ };
7966
8612
  try {
7967
- scrollIntoViewIfNeeded(leafElement, options);
8613
+ runScrollIntoViewIfNeeded(leafElement, options);
7968
8614
  } finally {
7969
8615
  if (hadOwnRect) leafElement.getBoundingClientRect = originalGetBoundingClientRect;
7970
8616
  else Reflect.deleteProperty(leafElement, "getBoundingClientRect");
7971
8617
  }
7972
8618
  };
7973
- if (typeof options !== "object" || options.scrollMode !== "always") return scheduleEditorDOMPhase(editor, "dom-write", "dom-editor-scroll-into-view", run, {
7974
- key: "dom-editor-scroll-into-view",
7975
- timing: "animation-frame"
7976
- });
7977
- const scheduleNavigation = (label, callback) => scheduleEditorDOMPhase(editor, "post-selection", label, callback, {
7978
- key: "dom-editor-scroll-into-view",
7979
- timing: "animation-frame"
7980
- });
8619
+ if (!alwaysMode) {
8620
+ const cancelInitial = schedulePhase(initialSchedulerView, "dom-editor-scroll-into-view", run);
8621
+ return () => {
8622
+ cancelled = true;
8623
+ cancelInitial();
8624
+ cancelRetry?.();
8625
+ };
8626
+ }
7981
8627
  let cancelScroll;
7982
- const cancelSettle = scheduleNavigation("dom-editor-scroll-into-view-settle", () => {
7983
- cancelScroll = scheduleNavigation("dom-editor-scroll-into-view", run);
8628
+ const cancelSettle = schedulePhase(initialSchedulerView, "dom-editor-scroll-into-view-settle", () => {
8629
+ if (cancelled) return;
8630
+ cancelScroll = schedulePhase(initialSchedulerView, "dom-editor-scroll-into-view", run);
7984
8631
  });
7985
8632
  return () => {
8633
+ cancelled = true;
7986
8634
  cancelSettle();
7987
8635
  cancelScroll?.();
8636
+ cancelRetry?.();
7988
8637
  };
7989
8638
  },
7990
8639
  resolveNode: (editor, domNode) => {
@@ -8172,7 +8821,7 @@ const DOMEditorImpl = {
8172
8821
  ({focusNode} = domRange);
8173
8822
  const firstRange = readDOMSelectionRange(domRange);
8174
8823
  const lastRange = readDOMSelectionRange(domRange, domRange.rangeCount - 1);
8175
- if (focusNode instanceof HTMLTableRowElement && firstRange.startContainer instanceof HTMLTableRowElement && lastRange.startContainer instanceof HTMLTableRowElement) {
8824
+ if (isDOMTableRowElement(focusNode) && isDOMTableRowElement(firstRange.startContainer) && isDOMTableRowElement(lastRange.startContainer)) {
8176
8825
  const firstNodeRow = firstRange.startContainer;
8177
8826
  const lastNodeRow = lastRange.startContainer;
8178
8827
  const firstNode = getLastChildren(firstNodeRow.children[firstRange.startOffset]);
@@ -8182,7 +8831,7 @@ const DOMEditorImpl = {
8182
8831
  else anchorNode = lastNode;
8183
8832
  if (firstNode.childNodes.length > 0) focusNode = firstNode.childNodes[0];
8184
8833
  else focusNode = firstNode;
8185
- if (lastNode instanceof HTMLElement) anchorOffset = lastNode.innerHTML.length;
8834
+ if (isDOMHTMLElement(lastNode)) anchorOffset = lastNode.innerHTML.length;
8186
8835
  else anchorOffset = 0;
8187
8836
  } else if (firstRange.startContainer === focusNode) {
8188
8837
  anchorNode = lastRange.endContainer;
@@ -9242,4 +9891,4 @@ const keyToDataAttribute = (key) => `data-editor-${toKebabCase(key)}`;
9242
9891
  /** Return DOM data attribute names that mirror primitive node properties. */
9243
9892
  const getNodeDataAttributeKeys = (node) => Object.keys(node).filter((key) => typeof node[key] !== "object" && (!TextApi.isText(node) || key !== "text")).map((key) => keyToDataAttribute(key));
9244
9893
  //#endregion
9245
- export { getDragAutoScrollTarget as $, EDITOR_TO_PENDING_DIFFS as $n, scheduleEditorDOMPhase as $t, createDOMEditorCapability as A, getPliteStringPlacementAtX as An, isDOMSelection as Ar, SOFT_LINE_END_SELECTOR as At, setEditableRootReveal as B, resolveDOMTextFlowEntry as Bn, findMountedDOMNodeByPath as Bt, normalizeRange as C, getNearestPliteStringRect as Cn, getFlatTreeParentElement as Cr, writeDOMFragmentData as Ct, DOMEditor as D, getPliteStringDocumentOffset as Dn, isBefore as Dr, writeDataTransferFragment as Dt, verifyDiffState as E, getPliteStringDirectPlacement as En, isAfter as Er, observeDataTransferInsertion as Et, isSelectableDOMSelection as F, getUsableRangeRects as Fn, noteAfterInsertCaret as Ft, supersedeFocusRequest as G, setDOMTextFlowRecordIndex as Gn, focusedElementOnPage as Gt, setEditorDOMRootElement as H, resolveDOMTextFlowOffset as Hn, DOMRootRuntime as Ht, isTrackedMutation as I, hasUsableDOMRect as In, readAfterInsertCaret as It, ensureFocusCaret as J, isCollapsedDOMCoverageBoundary as Jn, resolveDOMReach as Jt, watchFocusSuperseded as K, setDOMTextFlowRecordIndexes as Kn, getEditorDOMRoot as Kt, resolveDOMPointInRoot as L, isDOMTextFlowSegmentSynchronized as Ln, readLowerSoftLineEnd as Lt, getEditorDOMHostScrollElement as M, getPliteTextHostBounds as Mn, isPlainTextOnlyPaste as Mr, clearAfterInsertCaret as Mt, getOrCreateDOMNodeKey as N, getPliteTextHostStrings as Nn, markPlainTextPaste as Nr, isSoftLineEndBetween as Nt, DOMResolutionError as O, getPliteStringEdgeOffset as On, isDOMElement as Or, Key as Ot, isFocusRequestedElsewhere as P, getTextFlowPointAtCoordinates as Pn, normalizeDOMPoint as Pr, isSoftLineTextStale as Pt, resolveBlockFragmentDropRange as Q, EDITOR_TO_PENDING_ACTION as Qn, watchDOMSyncTextMarks as Qt, resolveDOMRangeInRoot as R, readDOMTextFlowPaint as Rn, recordSoftLineEnd as Rt, normalizePoint as S, createDOMGeometryKernel as Sn, getDefaultView as Sr, writeDOMDataTransferFragment as St, targetRange as T, getPliteStringCoordinatePlacement as Tn, hasShadowRoot as Tr, dataTransferFormats as Tt, setEditorDOMScrollElement as U, resolveDOMTextFlowRecordDOMText as Un, findDOMRootRuntime as Ut, setEditorDOMEditableElement as V, resolveDOMTextFlowInsertTarget as Vn, resolvePliteNodePath as Vt, subscribeEditorDOMScope as W, resolveDOMTextFlowRecordText as Wn, findEditorDOMRootRuntime as Wt, resolveNextKeyCaret as X, EDITOR_TO_FORCE_RENDER as Xn, isDOMSyncMutation as Xt, liftCaretOutOfCollapsedSection as Y, EDITOR_TO_ELEMENT as Yn, resolveDOMTargetView as Yt, eventCarriesBlockFragment as Z, EDITOR_TO_KEY_TO_ELEMENT as Zn, markDOMSyncMutationTarget as Zt, TRIPLE_CLICK as _, isBlinkDOMHost as _n, NODE_TO_INDEX as _r, readDropIndicator as _t, isLeaf as a, readDOMSelectionRange as an, EDITOR_TO_RUNTIME_ID_TO_KEY as ar, resolveDOMDropTarget as at, longestCommonPrefixLength as b, supportsDOMBeforeInput as bn, containsShadowAware as br, domCommands as bt, isText as c, recordDOMSelection as cn, EDITOR_TO_USER_SELECTION as cr, cancelDragRest as ct, Hotkeys as d, enableKernelTraceRetention as dn, ELEMENT_TO_NODE as dr, isDragSessionClaimed as dt, changeDOMSelection as en, EDITOR_TO_PENDING_INSERTION_MARKS as er, intersectClipChain as et, getLineBoundaryKeyboardMove as f, selectDOMInputDefaultActionPhase as fn, IS_COMPOSING as fr, readDragSession as ft, isHotkey as g, isAndroidDOMHost as gn, NODE_TO_ELEMENT as gr, publishDropIndicator as gt, createCompiledHotkeyMatcher as h, hasDOMHostQuirk as hn, IS_READ_ONLY as hr, takeDragSession as ht, isElement as i, readDOMSelectionPoints as in, EDITOR_TO_RUNTIME_ID_TO_ELEMENTS as ir, pointAt as it, findDOMPointElementInRoot as j, getPliteStringPlacementDOMPoint as jn, isDOMText as jr, SOFT_LINE_FLAG as jt, claimFocusRequest as k, getPliteStringLength as kn, isDOMNode as kr, SOFT_LINE_END as kt, isVoid as l, sameDOMSelectionPoints as ln, EDITOR_TO_WINDOW as lr, clearDragScrollRepaint as lt, ariaKeyShortcuts as m, getDOMHostLanguage as mn, IS_NODE_MAP_DIRTY as mr, settleDragSession as mt, getNodeDataAttributeKeys as n, forgetDOMSelectionRecordWithin as nn, EDITOR_TO_PLACEHOLDER_ELEMENT as nr, copyIntentOf as nt, isNode as o, readDOMSelectionRecord as on, EDITOR_TO_SCHEDULE_FLUSH as or, restDOMBlockDrag as ot, isPasteWithoutFormatting as p, CAN_USE_DOM as pn, IS_FOCUSED as pr, setDragScrollRepaint as pt, writeViewSelectionPart as q, DOMCoverage as qn, isElementFocused as qt, isEditor as r, getDOMRangeSelectionPoints as rn, EDITOR_TO_ROOT_VIEW_EDITORS as rr, indicateDOMDropTarget as rt, isString as s, readsSelectionAsHost as sn, EDITOR_TO_USER_MARKS as sr, beginDragSession as st, getElements as t, forgetDOMSelectionRecord as tn, EDITOR_TO_PENDING_SELECTION as tr, walkClipChain as tt, keyToDataAttribute as u, writeDOMSelection as un, ELEMENT_TO_EDITOR as ur, clearDragSession as ut, dom as v, isGeckoDOMHost as vn, NODE_TO_PARENT as vr, subscribeDropIndicator as vt, normalizeStringDiff as w, getOwnedPliteTextStrings as wn, getSelection as wr, writeDOMRangeData as wt, mergeStringDiffs as x, usesAppleDOMHotkeys as xn, getActiveElement as xr, getDOMClipboardFormatKey as xt, applyStringDiff as y, isWebKitDOMHost as yn, closestShadowAware as yr, cleanDOMClipboardContents as yt, resolveWrittenDOMRange as z, releaseDOMTextFlowRecordIndex as zn, resolveSoftLineEndDOMPoint as zt };
9894
+ export { eventCarriesBlockFragment as $, resolveDOMTextFlowInsertTarget as $n, isElementFocused as $t, createDOMEditorCapability as A, isWebKitDOMHost as An, NODE_TO_PARENT as Ar, SOFT_LINE_END as At, resolveWrittenDOMRange as B, getPliteStringEdgeOffset as Bn, isDOMElement as Br, resolveSoftLineEndDOMPoint as Bt, normalizeRange as C, writeDOMSelection as Cn, ELEMENT_TO_NODE as Cr, writeDOMDataTransferFragment as Ct, DOMEditor as D, isAndroidDOMHost as Dn, IS_READ_ONLY as Dr, observeDataTransferInsertion as Dt, verifyDiffState as E, hasDOMHostQuirk as En, IS_NODE_MAP_DIRTY as Er, dataTransferFormats as Et, isFocusRequestedElsewhere as F, getNearestPliteStringRect as Fn, getFlatTreeParentElement as Fr, isSoftLineTextStale as Ft, subscribeEditorDOMScope as G, getPliteTextHostStrings as Gn, isDOMText as Gr, canWriteEditableDOMSelection as Gt, setEditorDOMEditableElement as H, getPliteStringPlacementAtX as Hn, isDOMInputOrTextArea as Hr, resolvePliteNodePath as Ht, isSelectableDOMSelection as I, getOwnedPliteTextStrings as In, getSelection as Ir, noteAfterInsertCaret as It, writeViewSelectionPart as J, hasUsableDOMRect as Jn, normalizeDOMPoint as Jr, findDOMRootRuntime as Jt, supersedeFocusRequest as K, getTextFlowPointAtCoordinates as Kn, isPlainTextOnlyPaste as Kr, clearEditableDOMSelection as Kt, isTrackedMutation as L, getPliteStringCoordinatePlacement as Ln, hasShadowRoot as Lr, readAfterInsertCaret as Lt, focusEditableElement as M, usesAppleDOMHotkeys as Mn, containsShadowAware as Mr, SOFT_LINE_FLAG as Mt, getEditorDOMHostScrollElement as N, caretShowsPointOffTextFlowCharacters as Nn, getActiveElement as Nr, clearAfterInsertCaret as Nt, DOMResolutionError as O, isBlinkDOMHost as On, NODE_TO_ELEMENT as Or, writeDataTransferFragment as Ot, getOrCreateDOMNodeKey as P, createDOMGeometryKernel as Pn, getDefaultView as Pr, isSoftLineEndBetween as Pt, scrollDOMRangeFocusIntoViewIfNeeded as Q, resolveDOMTextFlowEntry as Qn, hasMountedDOMRoot as Qt, resolveDOMPointInRoot as R, getPliteStringDirectPlacement as Rn, isAfter as Rr, readLowerSoftLineEnd as Rt, normalizePoint as S, sameDOMSelectionPoints as Sn, ELEMENT_TO_EDITOR as Sr, domCommands as St, targetRange as T, getDOMHostLanguage as Tn, IS_FOCUSED as Tr, writeDOMRangeData as Tt, setEditorDOMRootElement as U, getPliteStringPlacementDOMPoint as Un, isDOMNode as Ur, DOMRootRuntime as Ut, setEditableRootReveal as V, getPliteStringLength as Vn, isDOMHTMLElement as Vr, findMountedDOMNodeByPath as Vt, setEditorDOMScrollElement as W, getPliteTextHostBounds as Wn, isDOMSelection as Wr, canWriteDOMSelection as Wt, liftCaretOutOfCollapsedSection as X, readDOMTextFlowPaint as Xn, writeClipboardCut as Xr, focusedElementOnPage as Xt, ensureFocusCaret as Y, isDOMTextFlowSegmentSynchronized as Yn, readClipboardCut as Yr, findEditorDOMRootRuntime as Yt, resolveNextKeyCaret as Z, releaseDOMTextFlowRecordIndex as Zn, getEditorDOMRoot as Zt, TRIPLE_CLICK as _, readDOMSelectionPoints as _n, EDITOR_TO_RUNTIME_ID_TO_KEY as _r, takeDragSession as _t, isLeaf as a, shouldClearEditableDOMSelection as an, DOMCoverage as ar, indicateDOMDropTarget as at, longestCommonPrefixLength as b, readsSelectionAsHost as bn, EDITOR_TO_USER_SELECTION as br, subscribeDropIndicator as bt, isText as c, markDOMSyncMutationTarget as cn, EDITOR_TO_FORCE_RENDER as cr, restDOMBlockDrag as ct, Hotkeys as d, enableKernelTraceRetention as dn, EDITOR_TO_PENDING_DIFFS as dr, clearDragScrollRepaint as dt, isSelectionOwnedByEditable as en, resolveDOMTextFlowOffset as er, resolveBlockFragmentDropRange as et, getLineBoundaryKeyboardMove as f, selectDOMInputDefaultActionPhase as fn, EDITOR_TO_PENDING_INSERTION_MARKS as fr, clearDragSession as ft, isHotkey as g, isDOMSelectionWriteEcho as gn, EDITOR_TO_RUNTIME_ID_TO_ELEMENTS as gr, settleDragSession as gt, createCompiledHotkeyMatcher as h, getDOMRangeSelectionPoints as hn, EDITOR_TO_ROOT_VIEW_EDITORS as hr, setDragScrollRepaint as ht, isElement as i, resolveDOMTargetView as in, setDOMTextFlowRecordIndexes as ir, copyIntentOf as it, findDOMPointElementInRoot as j, supportsDOMBeforeInput as jn, closestShadowAware as jr, SOFT_LINE_END_SELECTOR as jt, claimFocusRequest as k, isGeckoDOMHost as kn, NODE_TO_INDEX as kr, Key as kt, isVoid as l, watchDOMSyncTextMarks as ln, EDITOR_TO_KEY_TO_ELEMENT as lr, beginDragSession as lt, ariaKeyShortcuts as m, forgetDOMSelectionRecordWithin as mn, EDITOR_TO_PLACEHOLDER_ELEMENT as mr, readDragSession as mt, getNodeDataAttributeKeys as n, readEditableDOMSelectionPoints as nn, resolveDOMTextFlowRecordText as nr, intersectClipChain as nt, isNode as o, writeEditableDOMSelection as on, isCollapsedDOMCoverageBoundary as or, pointAt as ot, isPasteWithoutFormatting as p, forgetDOMSelectionRecord as pn, EDITOR_TO_PENDING_SELECTION as pr, isDragSessionClaimed as pt, watchFocusSuperseded as q, getUsableRangeRects as qn, markPlainTextPaste as qr, documentOf as qt, isEditor as r, resolveDOMReach as rn, setDOMTextFlowRecordIndex as rr, walkClipChain as rt, isString as s, isDOMSyncMutation as sn, EDITOR_TO_ELEMENT as sr, resolveDOMDropTarget as st, getElements as t, movedFocusElsewhere as tn, resolveDOMTextFlowRecordDOMText as tr, getDragAutoScrollTarget as tt, keyToDataAttribute as u, scheduleEditorDOMPhase as un, EDITOR_TO_PENDING_ACTION as ur, cancelDragRest as ut, dom as v, readDOMSelectionRange as vn, EDITOR_TO_SCHEDULE_FLUSH as vr, publishDropIndicator as vt, normalizeStringDiff as w, CAN_USE_DOM as wn, IS_COMPOSING as wr, writeDOMFragmentData as wt, mergeStringDiffs as x, recordDOMSelection as xn, EDITOR_TO_WINDOW as xr, cleanDOMClipboardContents as xt, applyStringDiff as y, readDOMSelectionRecord as yn, EDITOR_TO_USER_MARKS as yr, readDropIndicator as yt, resolveDOMRangeInRoot as z, getPliteStringDocumentOffset as zn, isBefore as zr, recordSoftLineEnd as zt };