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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/annotations/index.d.ts +1 -1
  2. package/dist/annotations/index.js +1 -1
  3. package/dist/authored/index.d.ts +2 -2
  4. package/dist/authored/index.js +1302 -490
  5. package/dist/{authored-veto-D_9wCJcK.js → authored-veto-BsBDXC0b.js} +1 -1
  6. package/dist/{comparison-plan-DY_vuGPq.js → comparison-plan-IOewH50q.js} +1 -1
  7. package/dist/{comparison-types-DdwE6mYq.d.ts → comparison-types-DBQFu7Rt.d.ts} +1 -1
  8. package/dist/{create-editor-CLQEkEZ1.js → create-editor-DRRzGwaC.js} +1 -1
  9. package/dist/diff/index.d.ts +2 -2
  10. package/dist/diff/index.js +2 -2
  11. package/dist/dom/index.d.ts +1 -1
  12. package/dist/dom/index.js +1 -1
  13. package/dist/{dom-CH2BXXj6.js → dom-CVYV5Qd5.js} +400 -100
  14. package/dist/{editor-owner-C9rVbMTs.js → editor-owner-CGj1wYCa.js} +1 -1
  15. package/dist/history/index.d.ts +1 -1
  16. package/dist/history/index.js +252 -178
  17. package/dist/hyperscript/index.d.ts +1 -1
  18. package/dist/hyperscript/index.js +1 -1
  19. package/dist/{hyperscript-CeT83ZLB.js → hyperscript-CT6hhnAY.js} +2 -2
  20. package/dist/{index-UrB4jAwl.d.ts → index-BT7D4vtf.d.ts} +5 -1
  21. package/dist/{index-BWPcE4ac.d.ts → index-BvQzYVAW.d.ts} +1 -1
  22. package/dist/{index-Db-ktCTE.d.ts → index-D7-n2GCk.d.ts} +6 -3
  23. package/dist/{index-BXjLmx1n.d.ts → index-DHt8nZQ6.d.ts} +143 -78
  24. package/dist/{index-Dq3Jlj8O.d.ts → index-PDROnF1G.d.ts} +1 -1
  25. package/dist/{index-DVMNewDn.d.ts → index-VZrKWWeh.d.ts} +20 -13
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.js +4 -4
  28. package/dist/internal/index.d.ts +2 -2
  29. package/dist/internal/index.js +4 -4
  30. package/dist/{mapped-view-store-CbWqba_1.js → mapped-view-store-CBk2-bDR.js} +1 -1
  31. package/dist/pagination/index.d.ts +1 -1
  32. package/dist/pagination/index.js +1 -1
  33. package/dist/pagination/react.d.ts +2 -2
  34. package/dist/pagination/react.js +5 -5
  35. package/dist/{pagination-CBdYiOuR.js → pagination-Cs5ka6hW.js} +1 -1
  36. package/dist/{plugin-SR3HTH0j.js → plugin-Bm6nsPHh.js} +1984 -751
  37. package/dist/{range-geometry-CdltxcH6.js → range-geometry-D1XfYWs0.js} +2 -2
  38. package/dist/{range-geometry-Dwp2oyCc.d.ts → range-geometry-DO-kbNrb.d.ts} +1 -1
  39. package/dist/react/index.d.ts +4 -4
  40. package/dist/react/index.js +6 -6
  41. package/dist/react/virtualized.d.ts +2 -2
  42. package/dist/react/virtualized.js +1 -1
  43. package/dist/{react-CN-iBh1z.js → react-BYtwRr4v.js} +18 -9
  44. package/dist/{retraction-BmPJB9cE.js → retraction-DnEUo8oE.js} +18 -2
  45. package/dist/{src-B-zm0kz4.js → src-DIQDddmh.js} +227 -40
  46. package/dist/{store-51r4zpCR.js → store-BLYxJgOU.js} +35 -5
  47. package/dist/testing/index.d.ts +2 -2
  48. package/dist/testing/index.js +3 -3
  49. package/dist/{use-editor-dom-scope-uDJQ692F.js → use-editor-dom-scope-hT7W9d-p.js} +1089 -606
  50. package/dist/yjs/index.d.ts +1 -1
  51. package/dist/yjs/index.js +1 -1
  52. package/dist/yjs/react/index.d.ts +3 -3
  53. package/dist/yjs/react/index.js +3 -3
  54. package/dist/{yjs-IGE0Al3n.js → yjs-C_g9gZwI.js} +6 -3
  55. package/package.json +1 -1
  56. package/dist/native-grouping-input-DXNhlPHd.js +0 -8
@@ -98,8 +98,10 @@ const coreWork = {
98
98
  formerPlaceVisits: 0,
99
99
  documentValues: 0,
100
100
  heldBlocks: 0,
101
+ generatorDraws: 0,
101
102
  contenderVisits: 0,
102
103
  decidedReads: 0,
104
+ decisionBlocks: 0,
103
105
  groupHolderVisits: 0,
104
106
  ownerChecks: 0,
105
107
  rootJudgments: 0,
@@ -134,6 +136,7 @@ const coreWork = {
134
136
  snapshotIndexes: 0,
135
137
  identityClaimsExamined: 0,
136
138
  identityPagesExamined: 0,
139
+ pairingContentKeys: 0,
137
140
  identityLocationsRepaired: 0,
138
141
  identityDirectoryNodesCopied: 0,
139
142
  identityMembershipsTouched: 0,
@@ -1425,28 +1428,27 @@ const setTableOf = (tree) => {
1425
1428
  }
1426
1429
  };
1427
1430
  };
1431
+ const TABLES_OF_JSON = /* @__PURE__ */ new WeakMap();
1428
1432
  let latestJson = null;
1429
- const BUILT_JSON = /* @__PURE__ */ new WeakSet();
1430
- const isBuiltRecordsJson = (json) => typeof json === "object" && json !== null && BUILT_JSON.has(json);
1431
- const recordStoreToJson = (store) => {
1433
+ const isBuiltRecordsJson = (json) => typeof json === "object" && json !== null && TABLES_OF_JSON.has(json);
1434
+ const recordStoreToJson = (store, reuseTablesFrom = latestJson?.json) => {
1432
1435
  if (latestJson?.store === store) return latestJson.json;
1433
- const latest = latestJson;
1436
+ const latest = reuseTablesFrom && TABLES_OF_JSON.get(reuseTablesFrom);
1434
1437
  const json = {};
1435
1438
  countCoreWork("recordsJsonObjects");
1436
1439
  const tables = /* @__PURE__ */ new Map();
1437
1440
  for (const [set, tree] of Object.entries(store)) {
1438
- const shared = latest?.tables.get(set);
1441
+ const shared = latest?.get(set);
1439
1442
  const table = shared?.tree === tree ? shared : setTableOf(tree);
1440
1443
  tables.set(set, table);
1441
1444
  setLazyJsonField(json, set, table);
1442
1445
  }
1443
1446
  freezeOwnedJsonValue(json);
1444
1447
  STORE_OF_JSON.set(json, store);
1445
- BUILT_JSON.add(json);
1448
+ TABLES_OF_JSON.set(json, tables);
1446
1449
  latestJson = {
1447
1450
  json,
1448
- store,
1449
- tables
1451
+ store
1450
1452
  };
1451
1453
  return json;
1452
1454
  };
@@ -1668,12 +1670,9 @@ const mintNodeKeys = (nodes, editor, kind) => {
1668
1670
  setNodeKey(node, editor, nodeKey);
1669
1671
  });
1670
1672
  };
1671
- //#endregion
1672
- //#region src/core/measured-sequence.ts
1673
- const WIDTH$1 = 32;
1674
1673
  const HEIGHT = 5;
1675
- const CAPACITY = WIDTH$1 ** HEIGHT;
1676
- const MERGE_BELOW = WIDTH$1 / 4;
1674
+ const CAPACITY = 32 ** HEIGHT;
1675
+ const MERGE_BELOW = 32 / 4;
1677
1676
  const isBranch = (node) => "children" in node;
1678
1677
  const measureOf = (node) => node.size === 0 ? 0 : getDefined(node.ends[node.size - 1]);
1679
1678
  const countOf = (node) => isBranch(node) && node.size > 0 ? getDefined(node.counts[node.size - 1]) : node.size;
@@ -1688,7 +1687,7 @@ const firstAboveOrLast = (bounds, size, value) => {
1688
1687
  return low;
1689
1688
  };
1690
1689
  const leaf$1 = (items, padded) => {
1691
- const width = padded ? WIDTH$1 : items.length;
1690
+ const width = padded ? 32 : items.length;
1692
1691
  const slots = [];
1693
1692
  const ends = [];
1694
1693
  let total = 0;
@@ -1712,7 +1711,7 @@ const branch = (children) => {
1712
1711
  const ends = [];
1713
1712
  let count = 0;
1714
1713
  let total = 0;
1715
- for (let index = 0; index < WIDTH$1; index += 1) {
1714
+ for (let index = 0; index < 32; index += 1) {
1716
1715
  const child = children[index];
1717
1716
  if (child !== void 0) {
1718
1717
  count += countOf(child);
@@ -1723,7 +1722,7 @@ const branch = (children) => {
1723
1722
  ends.push(total);
1724
1723
  }
1725
1724
  coreWork.allocatedNodes += 1;
1726
- coreWork.copiedSlots += 3 * WIDTH$1;
1725
+ coreWork.copiedSlots += 96;
1727
1726
  return {
1728
1727
  children: slots,
1729
1728
  counts,
@@ -1734,7 +1733,7 @@ const branch = (children) => {
1734
1733
  const used = (values, size) => {
1735
1734
  const result = [];
1736
1735
  for (let index = 0; index < size; index += 1) result.push(getDefined(values[index]));
1737
- coreWork.copiedSlots += WIDTH$1;
1736
+ coreWork.copiedSlots += 32;
1738
1737
  return result;
1739
1738
  };
1740
1739
  const copied = (slots) => {
@@ -1748,7 +1747,7 @@ const shifted$1 = (ends, from, delta) => {
1748
1747
  return next;
1749
1748
  };
1750
1749
  const runs = (values) => {
1751
- const count = Math.ceil(values.length / WIDTH$1);
1750
+ const count = Math.ceil(values.length / 32);
1752
1751
  const result = [];
1753
1752
  let from = 0;
1754
1753
  for (let run = 1; run <= count; run += 1) {
@@ -1756,7 +1755,7 @@ const runs = (values) => {
1756
1755
  result.push(values.slice(from, to));
1757
1756
  from = to;
1758
1757
  }
1759
- coreWork.copiedSlots += count * WIDTH$1;
1758
+ coreWork.copiedSlots += count * 32;
1760
1759
  return result;
1761
1760
  };
1762
1761
  const leavesOf = (items) => runs(items).map((run) => leaf$1(run, true));
@@ -1909,7 +1908,7 @@ var MeasuredSequence = class MeasuredSequence {
1909
1908
  }
1910
1909
  static from(items) {
1911
1910
  refuseOver(items.length);
1912
- if (items.length <= WIDTH$1) return new MeasuredSequence(leaf$1(items, false), 1);
1911
+ if (items.length <= 32) return new MeasuredSequence(leaf$1(items, false), 1);
1913
1912
  let level = leavesOf(items);
1914
1913
  for (let height = 1; height < HEIGHT; height += 1) level = branchesOf(level);
1915
1914
  return new MeasuredSequence(getDefined(level[0]), HEIGHT);
@@ -1984,7 +1983,7 @@ var MeasuredSequence = class MeasuredSequence {
1984
1983
  return new MeasuredSequence(replace(this.root, index), this.height);
1985
1984
  }
1986
1985
  setAll(updated) {
1987
- if (updated.size * WIDTH$1 > this.size) return MeasuredSequence.from(this.toArray().map((item, index) => updated.get(index) ?? item));
1986
+ if (updated.size * 32 > this.size) return MeasuredSequence.from(this.toArray().map((item, index) => updated.get(index) ?? item));
1988
1987
  return [...updated].reduce((next, [index, item]) => next.set(index, item), this);
1989
1988
  }
1990
1989
  /**
@@ -2002,7 +2001,7 @@ var MeasuredSequence = class MeasuredSequence {
2002
2001
  if (!Number.isInteger(index) || !Number.isInteger(deleteCount) || index < 0 || deleteCount < 0 || index + deleteCount > this.size) throw new RangeError(`Invalid sequence splice of ${deleteCount} at ${index}.`);
2003
2002
  const size = this.size - deleteCount + inserted.length;
2004
2003
  refuseOver(size);
2005
- if (this.height === 1 || size <= WIDTH$1) {
2004
+ if (this.height === 1 || size <= 32) {
2006
2005
  const items = this.toArray();
2007
2006
  items.splice(index, deleteCount, ...inserted);
2008
2007
  return MeasuredSequence.from(items);
@@ -3663,6 +3662,44 @@ const profileCoreDuration = (id, callback) => {
3663
3662
  }
3664
3663
  };
3665
3664
  //#endregion
3665
+ //#region src/core/stored-element-id.ts
3666
+ const storedElementIdOf = (node) => {
3667
+ const id = isElementNode(node) ? node.id : void 0;
3668
+ return typeof id === "string" ? id : void 0;
3669
+ };
3670
+ const storedIds = (nodes, ids = []) => {
3671
+ for (const node of nodes) {
3672
+ const id = storedElementIdOf(node);
3673
+ if (id !== void 0) ids.push(id);
3674
+ if (isElementNode(node)) storedIds(node.children, ids);
3675
+ }
3676
+ return ids;
3677
+ };
3678
+ const misreadsIds = (merged, paired, known) => {
3679
+ const ids = storedIds(merged);
3680
+ const knownIds = new Set(storedIds(known));
3681
+ return new Set(ids).size < ids.length || storedIds(paired).some((id) => !knownIds.has(id));
3682
+ };
3683
+ const withoutStoredElementId = (props) => {
3684
+ if (typeof props.id !== "string") return props;
3685
+ const { id: _id, ...rest } = props;
3686
+ return rest;
3687
+ };
3688
+ const keysOf$1 = (node) => Object.keys(node).filter((key) => key !== "id" || storedElementIdOf(node) === void 0);
3689
+ const same = (left, right) => {
3690
+ if (Object.is(left, right)) return true;
3691
+ if (Array.isArray(left) || Array.isArray(right)) return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((item, index) => same(item, right[index]));
3692
+ if (!isRecord$5(left) || !isRecord$5(right)) return false;
3693
+ const keys = keysOf$1(left);
3694
+ return keys.length === keysOf$1(right).length && keys.every((key) => Object.hasOwn(right, key) && same(left[key], right[key]));
3695
+ };
3696
+ const withoutPropertiesId = (value) => isRecord$5(value) && !("text" in value) ? withoutStoredElementId(value) : value;
3697
+ const alike = (left, right) => same(withoutPropertiesId(left), withoutPropertiesId(right));
3698
+ const tokensAlike = (left, right) => left.length === right.length && left.every((token, index) => {
3699
+ const other = right[index];
3700
+ return token.kind === "open" && token.nodeKind === "element" && other?.kind === "open" && other.nodeKind === "element" ? alike(token.props, other.props) : jsonEqual$1(token, other);
3701
+ });
3702
+ //#endregion
3666
3703
  //#region src/core/change/join.ts
3667
3704
  const lineAt = (document, position) => {
3668
3705
  const text = document.textAt(position);
@@ -3957,26 +3994,18 @@ const editsInMovedLine = (edit, step, document) => {
3957
3994
  const rebaseOverLift = (a, b, document, options) => ifNested(() => liftRebase(a, b, document, options));
3958
3995
  const liftRebase = (a, b, document, options) => {
3959
3996
  const bLift = liftOf(b, document);
3960
- const aLift = bLift ? null : liftOf(a, document);
3961
- if (bLift) {
3962
- if (editsInsideWrap(b, bLift, a, document)) return null;
3963
- const first = overMove(a, bLift, document, options);
3964
- const second = RootChange.transformInDocument(first.edit, bLift.rest, bLift.lifted, options);
3965
- return convergedResult(document, a, b, {
3966
- a: second.a,
3967
- b: first.move.compose(second.b)
3968
- });
3969
- }
3970
- if (aLift) {
3971
- if (editsInsideWrap(a, aLift, b, document)) return null;
3972
- const first = overMove(b, aLift, document, options);
3973
- const second = RootChange.transformInDocument(aLift.rest, first.edit, aLift.lifted, options);
3974
- return convergedResult(document, a, b, {
3975
- a: first.move.compose(second.a),
3976
- b: second.b
3977
- });
3978
- }
3979
- return null;
3997
+ const lift = bLift ?? liftOf(a, document);
3998
+ const [step, edit] = bLift ? [b, a] : [a, b];
3999
+ if (!lift || editsInsideWrap(step, lift, edit, document)) return null;
4000
+ const first = overMove(edit, lift, document, options);
4001
+ const second = bLift ? RootChange.transformInDocument(first.edit, lift.rest, lift.lifted, options) : RootChange.transformInDocument(lift.rest, first.edit, lift.lifted, options);
4002
+ return convergedResult(document, a, b, bLift ? {
4003
+ a: second.a,
4004
+ b: first.move.compose(second.b)
4005
+ } : {
4006
+ a: first.move.compose(second.a),
4007
+ b: second.b
4008
+ });
3980
4009
  };
3981
4010
  /**
3982
4011
  * Whether a change removes either line of a join whole, and whether it also
@@ -3987,9 +4016,18 @@ const removedJoinedLines = (change, document) => {
3987
4016
  const removed = (join) => [join.first, join.second].filter((line) => runs.some(({ from, to }) => from <= line.from && line.to <= to));
3988
4017
  const inserts = (line) => {
3989
4018
  const json = document.slice(line.from, line.to).toJSON();
3990
- return runs.some(({ inserted }) => {
3991
- const tokens = inserted.toJSON();
3992
- return tokens.some((_, at) => at + json.length <= tokens.length && jsonEqual$1(tokens.slice(at, at + json.length), json));
4019
+ const pad = json.length - 1;
4020
+ return runs.some(({ from, inserted, to }, index) => {
4021
+ if (inserted.length === 0) return false;
4022
+ const prev = Math.max(runs[index - 1]?.to ?? 0, from - pad);
4023
+ const next = Math.min(runs[index + 1]?.from ?? document.length, to + pad);
4024
+ const lead = from - prev;
4025
+ const tokens = [
4026
+ ...document.slice(prev, from).toJSON(),
4027
+ ...inserted.toJSON(),
4028
+ ...document.slice(to, next).toJSON()
4029
+ ];
4030
+ return tokens.some((_, at) => at + json.length > lead && at < lead + inserted.length && tokensAlike(tokens.slice(at, at + json.length), json));
3993
4031
  });
3994
4032
  };
3995
4033
  return {
@@ -4681,6 +4719,91 @@ const markReadBack = (readBack) => {
4681
4719
  if (readBack) readBack.changed = true;
4682
4720
  };
4683
4721
  //#endregion
4722
+ //#region src/core/change/text-leaf-boundary.ts
4723
+ /**
4724
+ * Whether `target` in a change's output was retained verbatim (without
4725
+ * replacement) from a different range than `base` in its base document.
4726
+ */
4727
+ const isRetainedFromOtherRange = (sections, target, base) => {
4728
+ for (let i = 0, a = 0, b = 0, runA = 0, runB = 0; i < sections.length; i += 2) {
4729
+ const length = sections[i];
4730
+ const inserted = sections[i + 1];
4731
+ if (inserted < 0) {
4732
+ if (b !== runB + (a - runA)) {
4733
+ runA = a;
4734
+ runB = b;
4735
+ }
4736
+ a += length;
4737
+ b += length;
4738
+ if (runB <= target.from && target.to <= b) return runA + target.from - runB !== base.from || runA + target.to - runB !== base.to;
4739
+ } else {
4740
+ a += length;
4741
+ b += inserted;
4742
+ runA = a;
4743
+ runB = b;
4744
+ }
4745
+ }
4746
+ return false;
4747
+ };
4748
+ /**
4749
+ * When a pure deletion removes an empty text leaf next to an adjacent text
4750
+ * leaf of the same properties and the concurrent change inserts plain text
4751
+ * into that empty leaf, shift the cut by one token to `[close text, ..., open
4752
+ * text]`. Both cuts produce the same token stream, and the shifted cut keeps
4753
+ * inserts inside either text leaf on their edge instead of inside the deletion.
4754
+ */
4755
+ const shiftMergedEmptyTextDeletion = (replacements, otherReplacements, document) => {
4756
+ if (replacements.length === 0 || otherReplacements.length === 0) return null;
4757
+ const inserts = /* @__PURE__ */ new Set();
4758
+ for (const { from, insert, to } of otherReplacements) if (from === to && insert.length > 0 && insert.tokens.every((token) => token.kind === "text")) inserts.add(from);
4759
+ if (inserts.size === 0) return null;
4760
+ const sameTextProps = (leftPath, rightPath) => {
4761
+ const left = document.node(leftPath);
4762
+ const right = document.node(rightPath);
4763
+ return isTextNode$3(left) && isTextNode$3(right) && jsonEqual$1(nodeProps(left), nodeProps(right));
4764
+ };
4765
+ const touched = (pos) => otherReplacements.some(({ from, to }) => from <= pos && pos <= to);
4766
+ let moved = false;
4767
+ const shifted = replacements.map((replacement, index) => {
4768
+ const { from, insert, to } = replacement;
4769
+ if (insert.length > 0 || to - from < 2) return replacement;
4770
+ if (inserts.has(to - 1) && from > 0 && !touched(from - 1) && (index === 0 || replacements[index - 1].to < from)) {
4771
+ const right = document.nodeStartingAt(to - 2);
4772
+ const left = document.pointAt(from - 1, -1);
4773
+ if (right?.kind === "text" && right.to === to && left && document.nodeRange(left.path).to === from && sameTextProps(left.path, right.path)) {
4774
+ moved = true;
4775
+ return {
4776
+ from: from - 1,
4777
+ insert,
4778
+ to: to - 1
4779
+ };
4780
+ }
4781
+ }
4782
+ if (inserts.has(from + 1) && to < document.length && !touched(to) && (index + 1 === replacements.length || replacements[index + 1].from > to)) {
4783
+ const left = document.nodeStartingAt(from);
4784
+ const right = document.nodeStartingAt(to);
4785
+ if (left?.kind === "text" && left.to === from + 2 && right?.kind === "text" && sameTextProps(left.path, right.path)) {
4786
+ moved = true;
4787
+ return {
4788
+ from: from + 1,
4789
+ insert,
4790
+ to: to + 1
4791
+ };
4792
+ }
4793
+ }
4794
+ return replacement;
4795
+ });
4796
+ return moved ? shifted : null;
4797
+ };
4798
+ const shiftMergedEmptyTextPair = (a, b, document) => {
4799
+ const shiftedA = a.hasProperties ? null : shiftMergedEmptyTextDeletion(a.replacements, b.replacements, document);
4800
+ const shiftedB = b.hasProperties ? null : shiftMergedEmptyTextDeletion(b.replacements, shiftedA ?? a.replacements, document);
4801
+ return shiftedA || shiftedB ? {
4802
+ a: shiftedA,
4803
+ b: shiftedB
4804
+ } : null;
4805
+ };
4806
+ //#endregion
4684
4807
  //#region src/core/change/wrap-fidelity.ts
4685
4808
  const closesWithin = (tokens, from) => {
4686
4809
  let depth = 0;
@@ -5382,7 +5505,7 @@ const editKey = (from, to) => `${from}:${to}`;
5382
5505
  const sharedPlaceEdits = (document, aReplacements, bReplacements) => {
5383
5506
  const bByRange = new Map(bReplacements.map((replacement) => [editKey(replacement.from, replacement.to), replacement]));
5384
5507
  const blocks = [];
5385
- const alike = [];
5508
+ const equalEdits = [];
5386
5509
  let sameBlocks = false;
5387
5510
  let removes;
5388
5511
  for (const replacement of aReplacements) {
@@ -5392,7 +5515,7 @@ const sharedPlaceEdits = (document, aReplacements, bReplacements) => {
5392
5515
  const keys = insertedElementKeys(replacement);
5393
5516
  const otherKeys = insertedElementKeys(other);
5394
5517
  if (!keys || !otherKeys || !placesBlocks(document, from)) {
5395
- if (sameSlice(insert, other.insert) && netDepth(insert.tokens) === netDepth(document.slice(from, to).tokens)) alike.push({
5518
+ if (sameSlice(insert, other.insert) && netDepth(insert.tokens) === netDepth(document.slice(from, to).tokens)) equalEdits.push({
5396
5519
  from,
5397
5520
  kind: "same",
5398
5521
  merged: insert,
@@ -5424,7 +5547,7 @@ const sharedPlaceEdits = (document, aReplacements, bReplacements) => {
5424
5547
  });
5425
5548
  }
5426
5549
  if (blocks.length === 0) return null;
5427
- const edits = new Map([...blocks, ...sameBlocks ? alike : []].map((edit) => [editKey(edit.from, edit.to), edit]));
5550
+ const edits = new Map([...blocks, ...sameBlocks ? equalEdits : []].map((edit) => [editKey(edit.from, edit.to), edit]));
5428
5551
  const wraps = (replacements) => replacements.some(({ from, insert, to }) => !edits.has(editKey(from, to)) && opensEnclosure(insert));
5429
5552
  return wraps(aReplacements) && wraps(bReplacements) ? null : edits;
5430
5553
  };
@@ -5939,6 +6062,10 @@ const createStructurallyAlignedChanges = (before, after, options) => {
5939
6062
  boundaries.set(node, result);
5940
6063
  return result;
5941
6064
  };
6065
+ const boundaryOverlap = (sourceText, targetText) => {
6066
+ const prefix = commonTextPrefixLength(sourceText.prefix, targetText.prefix);
6067
+ return prefix + commonTextSuffixLength(sourceText.suffix, targetText.suffix, Math.max(0, Math.min(sourceText.length, targetText.length) - prefix));
6068
+ };
5942
6069
  const continuityScore = (source, target) => {
5943
6070
  if (isTextNode$3(source) !== isTextNode$3(target)) return 0;
5944
6071
  if (Object.is(source, target)) return 2e9;
@@ -5949,19 +6076,13 @@ const createStructurallyAlignedChanges = (before, after, options) => {
5949
6076
  const sourceType = sourceProperties.type;
5950
6077
  const targetType = targetProperties.type;
5951
6078
  if (!propertiesEqual && (sourceType === void 0 || sourceType !== targetType)) return 0;
5952
- const sourceText = getBoundary(source);
5953
- const targetText = getBoundary(target);
5954
- const prefix = commonTextPrefixLength(sourceText.prefix, targetText.prefix);
5955
- const overlap = prefix + commonTextSuffixLength(sourceText.suffix, targetText.suffix, Math.max(0, Math.min(sourceText.length, targetText.length) - prefix));
5956
- if (overlap === 0) return 0;
6079
+ const overlap = boundaryOverlap(getBoundary(source), getBoundary(target));
6080
+ if (overlap === 0) return propertiesEqual && storedElementIdOf(source) !== void 0 ? 1 : 0;
5957
6081
  return (propertiesEqual ? 1024 : 512) + overlap * 16;
5958
6082
  };
5959
6083
  const isCompleteTextContinuation = (source, target) => {
5960
6084
  const sourceText = getBoundary(source);
5961
- if (sourceText.length === 0 || sourceText.length > 128) return false;
5962
- const targetText = getBoundary(target);
5963
- const prefix = commonTextPrefixLength(sourceText.prefix, targetText.prefix);
5964
- return prefix + commonTextSuffixLength(sourceText.suffix, targetText.suffix, Math.max(0, Math.min(sourceText.length, targetText.length) - prefix)) === sourceText.length;
6085
+ return sourceText.length > 0 && sourceText.length <= 128 && boundaryOverlap(sourceText, getBoundary(target)) === sourceText.length;
5965
6086
  };
5966
6087
  const addPropertyChanges = (source, target, path) => {
5967
6088
  const sourceProperties = getProperties(source);
@@ -5990,14 +6111,13 @@ const createStructurallyAlignedChanges = (before, after, options) => {
5990
6111
  return true;
5991
6112
  }
5992
6113
  if (!isElementNode(source) || !isElementNode(target)) return false;
5993
- if (getProperties(source).type === getProperties(target).type && !jsonEqual$1(getProperties(source), getProperties(target)) && !jsonEqual$1(source.children, target.children)) flatDiffRekeys = true;
6114
+ flatDiffRekeys ||= getProperties(source).type === getProperties(target).type && !jsonEqual$1(getProperties(source), getProperties(target));
5994
6115
  return diffChildren(source.children, target.children, path);
5995
6116
  };
5996
6117
  const diffChildren = (source, target, parentPath) => {
5997
- let prefix = 0;
5998
- while (prefix < source.length && prefix < target.length && jsonEqual$1(source[prefix], target[prefix])) prefix += 1;
5999
- let suffix = 0;
6000
- while (suffix < source.length - prefix && suffix < target.length - prefix && jsonEqual$1(source.at(-suffix - 1), target.at(-suffix - 1))) suffix += 1;
6118
+ const shorter = Math.min(source.length, target.length);
6119
+ const prefix = equalRunLength(source, target, shorter);
6120
+ const suffix = equalRunLength(source, target, shorter - prefix, true);
6001
6121
  const sourceEnd = source.length - suffix;
6002
6122
  const targetEnd = target.length - suffix;
6003
6123
  const sourceCount = sourceEnd - prefix;
@@ -6075,15 +6195,21 @@ const createStructurallyAlignedChanges = (before, after, options) => {
6075
6195
  let sourceCursor = prefix;
6076
6196
  let targetCursor = prefix;
6077
6197
  const addGap = (sourceTo, targetTo) => {
6078
- if (sourceCursor === sourceTo && targetCursor === targetTo) return;
6198
+ if (sourceCursor === sourceTo && targetCursor === targetTo) return true;
6199
+ if (sourceTo === sourceCursor + 1 && targetTo === targetCursor + 1) {
6200
+ const left = source[sourceCursor];
6201
+ const right = target[targetCursor];
6202
+ if (isTextNode$3(left) === isTextNode$3(right) && jsonEqual$1(getProperties(left), getProperties(right))) return diffNode(left, right, [...parentPath, sourceCursor]);
6203
+ }
6079
6204
  changes.push({
6080
6205
  from: before.childPosition(parentPath, sourceCursor),
6081
6206
  insert: PreparedTokenSlice.fromNodes(target.slice(targetCursor, targetTo)),
6082
6207
  to: before.childPosition(parentPath, sourceTo)
6083
6208
  });
6209
+ return true;
6084
6210
  };
6085
6211
  for (const [matchedSource, matchedTarget] of matches) {
6086
- addGap(matchedSource, matchedTarget);
6212
+ if (!addGap(matchedSource, matchedTarget)) return false;
6087
6213
  const row = scores[matchedSource - prefix];
6088
6214
  const score = row[matchedTarget - prefix];
6089
6215
  const best = Math.max(...row);
@@ -6094,8 +6220,7 @@ const createStructurallyAlignedChanges = (before, after, options) => {
6094
6220
  sourceCursor = matchedSource + 1;
6095
6221
  targetCursor = matchedTarget + 1;
6096
6222
  }
6097
- addGap(sourceEnd, targetEnd);
6098
- return true;
6223
+ return addGap(sourceEnd, targetEnd);
6099
6224
  };
6100
6225
  return diffChildren(before.value, after.value, []) && flatDiffRekeys ? changes : null;
6101
6226
  };
@@ -6338,6 +6463,12 @@ const sameChangedChildren = (left, right, same) => left.size === right.size && l
6338
6463
  for (let at = 0; at < to - from; at += 1) if (!same(getDefined(left.child(from + at)), getDefined(right.child(otherFrom + at)))) return false;
6339
6464
  return true;
6340
6465
  });
6466
+ const equalRunLength = (left, right, limit, fromEnd = false, equal = jsonEqual$1) => {
6467
+ const at = (offset) => fromEnd ? -1 - offset : offset;
6468
+ let length = 0;
6469
+ while (length < limit && equal(left.at(at(length)), right.at(at(length)))) length += 1;
6470
+ return length;
6471
+ };
6341
6472
  const mergeStructuralRunByPosition = (structural, concurrent, concurrentReplacements, before, afterStructural, afterConcurrent) => {
6342
6473
  if (deletesBlocksAndInserts(before, concurrentReplacements)) return null;
6343
6474
  let rebased = null;
@@ -6382,16 +6513,8 @@ const mergeStructuralRunByPosition = (structural, concurrent, concurrentReplacem
6382
6513
  const structuralNodes = childrenAt(afterStructural, path);
6383
6514
  const concurrentNodes = childrenAt(afterConcurrent, concurrentPath);
6384
6515
  const shorter = Math.min(beforeNodes.length, structuralNodes.length);
6385
- const prefixOf = (limit) => {
6386
- let length = 0;
6387
- while (length < limit && jsonEqual$1(beforeNodes[length], structuralNodes[length])) length += 1;
6388
- return length;
6389
- };
6390
- const suffixOf = (limit) => {
6391
- let length = 0;
6392
- while (length < limit && jsonEqual$1(beforeNodes.at(-1 - length), structuralNodes.at(-1 - length))) length += 1;
6393
- return length;
6394
- };
6516
+ const prefixOf = (limit) => equalRunLength(beforeNodes, structuralNodes, limit);
6517
+ const suffixOf = (limit) => equalRunLength(beforeNodes, structuralNodes, limit, true);
6395
6518
  const from = prefixOf(shorter);
6396
6519
  const suffix = suffixOf(shorter - from);
6397
6520
  const lowest = prefixOf(shorter - suffixOf(shorter));
@@ -6469,22 +6592,40 @@ const mergeStructuralRunByPosition = (structural, concurrent, concurrentReplacem
6469
6592
  rebased: rebasedChange
6470
6593
  };
6471
6594
  };
6472
- const mergeStructuralChangeAtStableSiblingRange = (before, afterStructural, afterConcurrent) => {
6473
- let from = 0;
6474
- while (from < before.value.length && from < afterStructural.value.length && jsonEqual$1(before.value[from], afterStructural.value[from])) from += 1;
6475
- let suffix = 0;
6476
- while (suffix < before.value.length - from && suffix < afterStructural.value.length - from && jsonEqual$1(before.value.at(-1 - suffix), afterStructural.value.at(-1 - suffix))) suffix += 1;
6477
- const source = before.value.slice(from, before.value.length - suffix);
6478
- const replacement = afterStructural.value.slice(from, afterStructural.value.length - suffix);
6595
+ const SIBLING_RANGE_READS = [
6596
+ {
6597
+ head: jsonEqual$1,
6598
+ tail: jsonEqual$1
6599
+ },
6600
+ {
6601
+ head: jsonEqual$1,
6602
+ tail: alike
6603
+ },
6604
+ {
6605
+ head: alike,
6606
+ tail: alike
6607
+ }
6608
+ ];
6609
+ const mergeStructuralChangeAtStableSiblingRange = (before, afterStructural, afterConcurrent, read = 0) => {
6610
+ const left = before.value;
6611
+ const right = afterStructural.value;
6612
+ const shorter = Math.min(left.length, right.length);
6613
+ const { head, tail } = SIBLING_RANGE_READS[read];
6614
+ const from = equalRunLength(left, right, shorter, false, head);
6615
+ const suffix = equalRunLength(left, right, shorter - from, true, tail);
6616
+ const source = left.slice(from, left.length - suffix);
6617
+ const replacement = right.slice(from, right.length - suffix);
6479
6618
  if (source.length === 0 || sameDocumentStructure(source, replacement)) return null;
6480
6619
  let match = -1;
6481
- for (let index = 0; index <= afterConcurrent.value.length - source.length; index++) if (source.every((node, offset) => jsonEqual$1(node, afterConcurrent.value[index + offset]))) {
6620
+ for (let index = 0; index <= afterConcurrent.value.length - source.length; index++) if (source.every((node, offset) => head(node, afterConcurrent.value[index + offset]))) {
6482
6621
  if (match !== -1) return null;
6483
6622
  match = index;
6484
6623
  }
6485
- if (match === -1) return null;
6624
+ if (match === -1) return read + 1 === SIBLING_RANGE_READS.length ? null : mergeStructuralChangeAtStableSiblingRange(before, afterStructural, afterConcurrent, read + 1);
6625
+ const paired = afterConcurrent.value.slice(match, match + source.length);
6486
6626
  const merged = [...afterConcurrent.value];
6487
6627
  merged.splice(match, source.length, ...replacement);
6628
+ if (tail === alike && misreadsIds(merged, paired, left)) return null;
6488
6629
  const document = DocumentIndex.fromValue(merged);
6489
6630
  return {
6490
6631
  merged: document,
@@ -6521,6 +6662,8 @@ const mergeNestedChangeThroughStructuralRelocation = (nested, structural, before
6521
6662
  if (structuralRanges.every(([from, to]) => to <= range.from || range.to <= from)) continue;
6522
6663
  const targets = afterNodes.filter(({ node }) => jsonEqual$1(node, candidate.node));
6523
6664
  if (targets.length !== 1) continue;
6665
+ const targetPath = targets[0].path;
6666
+ if (isRetainedFromOtherRange(structural.sections, afterStructural.nodeRange(targetPath), range)) continue;
6524
6667
  const end = range.to + nested.newLength - nested.length;
6525
6668
  const parentPath = candidate.path.slice(0, -1);
6526
6669
  const edited = [];
@@ -6539,9 +6682,7 @@ const mergeNestedChangeThroughStructuralRelocation = (nested, structural, before
6539
6682
  } catch {
6540
6683
  continue;
6541
6684
  }
6542
- if (edited.length === 0 || at !== end && index < siblings.length) continue;
6543
- if (edited.some((node) => jsonEqual$1(node, candidate.node))) continue;
6544
- const targetPath = targets[0].path;
6685
+ if (edited.length === 0 || at !== end && index < siblings.length || edited.some((node) => jsonEqual$1(node, candidate.node))) continue;
6545
6686
  const targetIndex = targetPath.at(-1);
6546
6687
  if (targetIndex === void 0) continue;
6547
6688
  const merged = afterStructural.withSplicedNodes(targetPath.slice(0, -1), targetIndex, 1, edited);
@@ -7196,22 +7337,16 @@ var RootChange = class RootChange {
7196
7337
  static carryAcrossMove(a, b, document, options, runMoves) {
7197
7338
  if (changedRangesAreSeparated(a, b)) return null;
7198
7339
  const [aMove, bMove] = runMoves();
7199
- if (aMove && bMove) return null;
7200
- if (bMove) {
7201
- const carried = RootChange.carryEditAcrossMove(a, b, bMove, document, options, true);
7202
- return carried && {
7203
- a: carried.edit,
7204
- b: carried.move
7205
- };
7206
- }
7207
- if (aMove) {
7208
- const carried = RootChange.carryEditAcrossMove(b, a, aMove, document, options, false);
7209
- return carried && {
7210
- a: carried.move,
7211
- b: carried.edit
7212
- };
7213
- }
7214
- return null;
7340
+ const move = bMove ?? aMove;
7341
+ if (aMove && bMove || !move) return null;
7342
+ const carried = RootChange.carryEditAcrossMove(bMove ? a : b, bMove ? b : a, move, document, options, Boolean(bMove));
7343
+ return carried && (bMove ? {
7344
+ a: carried.edit,
7345
+ b: carried.move
7346
+ } : {
7347
+ a: carried.move,
7348
+ b: carried.edit
7349
+ });
7215
7350
  }
7216
7351
  static carryEditAcrossMove(edit, moveChange, move, document, options, editIsA) {
7217
7352
  if (move.count !== 1 || pathKey$2(move.path) === pathKey$2(move.targetPath) || !isElementNode(document.node(move.path)) || moveChange.propertyChanges().length > 0) return null;
@@ -7280,6 +7415,14 @@ var RootChange = class RootChange {
7280
7415
  markReadBack(readBack);
7281
7416
  return inMovedLine;
7282
7417
  }
7418
+ const shifted = shiftMergedEmptyTextPair({
7419
+ hasProperties: a.propertyChanges().length > 0,
7420
+ replacements: a.replacements()
7421
+ }, {
7422
+ hasProperties: b.propertyChanges().length > 0,
7423
+ replacements: b.replacements()
7424
+ }, document);
7425
+ if (shifted) return RootChange.transformInDocument(shifted.a ? RootChange.create(document, shifted.a) : a, shifted.b ? RootChange.create(document, shifted.b) : b, document, settings);
7283
7426
  const joined = rebaseOverJoins(a, b, document, replayBase, readBack);
7284
7427
  if (joined) return joined;
7285
7428
  const pieces = rebaseOverPieces(a, b, document, replay?.pieceProps, replayBase);
@@ -7299,36 +7442,54 @@ var RootChange = class RootChange {
7299
7442
  other: wrapping.invert(document).compose(rest).compose(over.b)
7300
7443
  };
7301
7444
  };
7302
- if (readBack && wrapsInsideReplacement(aReplacements, bReplacements, document)) {
7303
- const { kept, other } = wrapGoesWithReplaced(a, b);
7304
- return {
7305
- a: kept,
7306
- b: other
7307
- };
7308
- }
7309
- if (readBack && wrapsInsideReplacement(bReplacements, aReplacements, document)) {
7310
- const { kept, other } = wrapGoesWithReplaced(b, a);
7311
- return {
7445
+ if (readBack) for (const [first, second, firstReps, secondReps, flip] of [[
7446
+ a,
7447
+ b,
7448
+ aReplacements,
7449
+ bReplacements,
7450
+ false
7451
+ ], [
7452
+ b,
7453
+ a,
7454
+ bReplacements,
7455
+ aReplacements,
7456
+ true
7457
+ ]]) {
7458
+ if (!wrapsInsideReplacement(firstReps, secondReps, document)) continue;
7459
+ const { kept, other } = wrapGoesWithReplaced(first, second);
7460
+ return flip ? {
7312
7461
  a: other,
7313
7462
  b: kept
7463
+ } : {
7464
+ a: kept,
7465
+ b: other
7314
7466
  };
7315
7467
  }
7316
7468
  const absorbed = transformByPositionOverAbsorbedWraps(a, b, aReplacements, bReplacements, document, replayBase, readBack);
7317
7469
  if (absorbed) return absorbed;
7318
- const bPutBack = putBackOver(aReplacements, bReplacements, document);
7319
- if (bPutBack) {
7320
- const afterB = b.apply(document);
7321
- return {
7322
- a: RootChange.empty(afterB.length),
7323
- b: RootChange.create(a.apply(document), bPutBack)
7324
- };
7325
- }
7326
- const aPutBack = putBackOver(bReplacements, aReplacements, document);
7327
- if (aPutBack) {
7328
- const afterA = a.apply(document);
7329
- return {
7330
- a: RootChange.create(b.apply(document), aPutBack),
7331
- b: RootChange.empty(afterA.length)
7470
+ for (const [first, second, firstReps, secondReps, flip] of [[
7471
+ a,
7472
+ b,
7473
+ aReplacements,
7474
+ bReplacements,
7475
+ false
7476
+ ], [
7477
+ b,
7478
+ a,
7479
+ bReplacements,
7480
+ aReplacements,
7481
+ true
7482
+ ]]) {
7483
+ const putBack = putBackOver(firstReps, secondReps, document);
7484
+ if (!putBack) continue;
7485
+ const empty = RootChange.empty(second.apply(document).length);
7486
+ const created = RootChange.create(first.apply(document), putBack);
7487
+ return flip ? {
7488
+ a: created,
7489
+ b: empty
7490
+ } : {
7491
+ a: empty,
7492
+ b: created
7332
7493
  };
7333
7494
  }
7334
7495
  const aPropertyChanges = a.propertyChanges();
@@ -7375,31 +7536,42 @@ var RootChange = class RootChange {
7375
7536
  };
7376
7537
  };
7377
7538
  const carriesOver = (move, other) => !!move && (move.count === 1 ? other?.count !== 1 : !other);
7378
- if (carriesOver(bRunMove, aRunMove)) {
7379
- const carried = carryThroughMove(a, b, bRunMove);
7380
- if (carried) return {
7381
- a: carried.edit,
7382
- b: carried.move
7383
- };
7384
- }
7385
- if (carriesOver(aRunMove, bRunMove)) {
7386
- const carried = carryThroughMove(b, a, aRunMove);
7387
- if (carried) return {
7539
+ for (const [edit, moveChange, move, other, flip] of [[
7540
+ a,
7541
+ b,
7542
+ bRunMove,
7543
+ aRunMove,
7544
+ false
7545
+ ], [
7546
+ b,
7547
+ a,
7548
+ aRunMove,
7549
+ bRunMove,
7550
+ true
7551
+ ]]) {
7552
+ if (!carriesOver(move, other)) continue;
7553
+ const carried = carryThroughMove(edit, moveChange, move);
7554
+ if (carried) return flip ? {
7388
7555
  a: carried.move,
7389
7556
  b: carried.edit
7557
+ } : {
7558
+ a: carried.edit,
7559
+ b: carried.move
7390
7560
  };
7391
7561
  }
7392
7562
  const afterA = a.apply(document);
7393
7563
  const afterB = b.apply(document);
7394
7564
  const shared = keepEqualInserts ? null : sharedPlaceEdits(document, aReplacements, bReplacements);
7395
- if (shared && keptIn(b, afterB, afterA)) return {
7396
- a: RootChange.betweenWhole(afterB, afterA),
7397
- b: RootChange.empty(afterA.length)
7398
- };
7399
- if (shared && keptIn(a, afterA, afterB)) return {
7400
- a: RootChange.empty(afterB.length),
7401
- b: RootChange.betweenWhole(afterA, afterB)
7402
- };
7565
+ if (shared) {
7566
+ if (keptIn(b, afterB, afterA)) return {
7567
+ a: RootChange.betweenWhole(afterB, afterA),
7568
+ b: RootChange.empty(afterA.length)
7569
+ };
7570
+ if (keptIn(a, afterA, afterB)) return {
7571
+ a: RootChange.empty(afterB.length),
7572
+ b: RootChange.betweenWhole(afterA, afterB)
7573
+ };
7574
+ }
7403
7575
  const rebaseAfterShared = (edits) => {
7404
7576
  const rest = RootChange.transformInDocument(overSharedEdits(a, edits), overSharedEdits(b, edits), RootChange.create(document, [...edits.values()].map(({ from, merged, to }) => ({
7405
7577
  from,
@@ -7445,20 +7617,12 @@ var RootChange = class RootChange {
7445
7617
  move: moved
7446
7618
  };
7447
7619
  };
7448
- if (readBack && bMove && !aMove) {
7449
- const wrapped = wrapGoesWithMove(a, b, bMove);
7450
- const kept = wrapped && convergedResult(document, a, b, {
7620
+ if (readBack && Boolean(bMove) !== Boolean(aMove)) {
7621
+ const wrapped = bMove ? wrapGoesWithMove(a, b, bMove) : aMove && wrapGoesWithMove(b, a, aMove);
7622
+ const kept = wrapped && convergedResult(document, a, b, bMove ? {
7451
7623
  a: wrapped.edit,
7452
7624
  b: wrapped.move
7453
- });
7454
- if (kept) {
7455
- markReadBack(readBack);
7456
- return kept;
7457
- }
7458
- }
7459
- if (readBack && aMove && !bMove) {
7460
- const wrapped = wrapGoesWithMove(b, a, aMove);
7461
- const kept = wrapped && convergedResult(document, a, b, {
7625
+ } : {
7462
7626
  a: wrapped.move,
7463
7627
  b: wrapped.edit
7464
7628
  });
@@ -7487,41 +7651,64 @@ var RootChange = class RootChange {
7487
7651
  };
7488
7652
  }
7489
7653
  if (onlyAddsStructure(aReplacements) && onlyAddsStructure(bReplacements) && [...aReplacements, ...bReplacements].some(({ insert }) => opensEnclosure(insert)) && !addsInsideEnclosure(aReplacements, bReplacements) && !addsInsideEnclosure(bReplacements, aReplacements) && convergesOn(transformed, afterA, afterB)) return transformed;
7490
- const bThroughStableA = bChangesStructure ? mergeStructuralRunByPosition(b, a, aReplacements, document, afterB, afterA) ?? mergeStructuralChangeAtStableSiblingRange(document, afterB, afterA) : null;
7491
- if (bThroughStableA !== null) return {
7492
- a: bThroughStableA.other,
7493
- b: bThroughStableA.rebased
7494
- };
7495
- const aThroughStableB = aChangesStructure ? mergeStructuralRunByPosition(a, b, bReplacements, document, afterA, afterB) ?? mergeStructuralChangeAtStableSiblingRange(document, afterA, afterB) : null;
7496
- if (aThroughStableB !== null) return {
7497
- a: aThroughStableB.rebased,
7498
- b: aThroughStableB.other
7499
- };
7500
- const aThroughB = bChangesStructure ? mergeNestedChangeThroughStructuralRelocation(a, b, document, afterA, afterB) : null;
7501
- if (aThroughB !== null) return {
7502
- a: RootChange.betweenWhole(afterB, aThroughB),
7503
- b: RootChange.betweenWhole(afterA, aThroughB)
7504
- };
7505
- const bThroughA = aChangesStructure ? mergeNestedChangeThroughStructuralRelocation(b, a, document, afterB, afterA) : null;
7506
- if (bThroughA !== null) return {
7507
- a: RootChange.betweenWhole(afterB, bThroughA),
7508
- b: RootChange.betweenWhole(afterA, bThroughA)
7509
- };
7510
- if (convergesOn(transformed, afterA, afterB)) return transformed;
7511
- if (bMove && aReplacements.length === 1 && bMove.from <= aReplacement.from && aReplacement.to < bMove.to) {
7512
- const moveAfterA = moveNodeChange(afterA, bMove.path, bMove.targetPath);
7513
- const merged = moveAfterA.apply(afterA);
7514
- return {
7515
- a: RootChange.betweenWhole(afterB, merged),
7516
- b: moveAfterA
7654
+ const sideA = {
7655
+ after: afterA,
7656
+ change: a,
7657
+ move: aMove,
7658
+ props: aPropertyChanges,
7659
+ rep: aReplacement,
7660
+ reps: aReplacements,
7661
+ structural: aChangesStructure
7662
+ };
7663
+ const sideB = {
7664
+ after: afterB,
7665
+ change: b,
7666
+ move: bMove,
7667
+ props: bPropertyChanges,
7668
+ rep: bReplacement,
7669
+ reps: bReplacements,
7670
+ structural: bChangesStructure
7671
+ };
7672
+ const pairs = [[
7673
+ sideB,
7674
+ sideA,
7675
+ false
7676
+ ], [
7677
+ sideA,
7678
+ sideB,
7679
+ true
7680
+ ]];
7681
+ for (const [primary, other, flip] of pairs) {
7682
+ if (!primary.structural) continue;
7683
+ const throughStable = mergeStructuralRunByPosition(primary.change, other.change, other.reps, document, primary.after, other.after) ?? mergeStructuralChangeAtStableSiblingRange(document, primary.after, other.after);
7684
+ if (throughStable !== null) return flip ? {
7685
+ a: throughStable.rebased,
7686
+ b: throughStable.other
7687
+ } : {
7688
+ a: throughStable.other,
7689
+ b: throughStable.rebased
7517
7690
  };
7518
7691
  }
7519
- if (aMove && bReplacements.length === 1 && aMove.from <= bReplacement.from && bReplacement.to < aMove.to) {
7520
- const moveAfterB = moveNodeChange(afterB, aMove.path, aMove.targetPath);
7521
- const merged = moveAfterB.apply(afterB);
7522
- return {
7523
- a: moveAfterB,
7524
- b: RootChange.betweenWhole(afterA, merged)
7692
+ for (const [primary, other] of pairs) {
7693
+ if (!primary.structural) continue;
7694
+ const relocated = mergeNestedChangeThroughStructuralRelocation(other.change, primary.change, document, other.after, primary.after);
7695
+ if (relocated !== null) return {
7696
+ a: RootChange.betweenWhole(afterB, relocated),
7697
+ b: RootChange.betweenWhole(afterA, relocated)
7698
+ };
7699
+ }
7700
+ if (convergesOn(transformed, afterA, afterB)) return transformed;
7701
+ for (const [primary, other, flip] of pairs) {
7702
+ const { move } = primary;
7703
+ if (!move || other.reps.length !== 1 || move.from > other.rep.from || other.rep.to >= move.to) continue;
7704
+ const moved = moveNodeChange(other.after, move.path, move.targetPath);
7705
+ const rebased = RootChange.betweenWhole(primary.after, moved.apply(other.after));
7706
+ return flip ? {
7707
+ a: moved,
7708
+ b: rebased
7709
+ } : {
7710
+ a: rebased,
7711
+ b: moved
7525
7712
  };
7526
7713
  }
7527
7714
  const keepOutsideDeletion = (deletion, afterDeletion, propertyChanges) => {
@@ -7538,32 +7725,21 @@ var RootChange = class RootChange {
7538
7725
  if (position < afterDeletion.length) addSection(sections, data, afterDeletion.length - position, -1, null);
7539
7726
  return RootChange.fromSections(sections, data).apply(afterDeletion);
7540
7727
  };
7541
- const deletion = bReplacements.length === 1 && deletesWholeSiblings(document, bReplacement) && containsAll(bReplacement, aReplacements) ? {
7542
- edit: a,
7543
- kept: aPropertyChanges,
7544
- replacement: bReplacement,
7545
- side: "b"
7546
- } : aReplacements.length === 1 && deletesWholeSiblings(document, aReplacement) && containsAll(aReplacement, bReplacements) ? {
7547
- edit: b,
7548
- kept: bPropertyChanges,
7549
- replacement: aReplacement,
7550
- side: "a"
7551
- } : null;
7552
- if (deletion) {
7553
- const [afterEdit, afterDeletion] = deletion.side === "b" ? [afterA, afterB] : [afterB, afterA];
7554
- const merged = keepOutsideDeletion(deletion.replacement, afterDeletion, deletion.kept);
7555
- const deletionAfterEdit = RootChange.create(afterEdit, {
7556
- from: deletion.replacement.from,
7557
- to: deletion.replacement.to + deletion.edit.newLength - deletion.edit.length
7728
+ for (const [primary, other, flip] of pairs) {
7729
+ if (primary.reps.length !== 1 || !deletesWholeSiblings(document, primary.rep) || !containsAll(primary.rep, other.reps)) continue;
7730
+ const merged = keepOutsideDeletion(primary.rep, primary.after, other.props);
7731
+ const deletionAfterEdit = RootChange.create(other.after, {
7732
+ from: primary.rep.from,
7733
+ to: primary.rep.to + other.change.newLength - other.change.length
7558
7734
  });
7559
- const deleted = deletionAfterEdit.compose(RootChange.betweenWhole(deletionAfterEdit.apply(afterEdit), merged));
7560
- const edited = RootChange.betweenWhole(afterDeletion, merged);
7561
- return deletion.side === "b" ? {
7562
- a: edited,
7563
- b: deleted
7564
- } : {
7735
+ const deleted = deletionAfterEdit.compose(RootChange.betweenWhole(deletionAfterEdit.apply(other.after), merged));
7736
+ const edited = RootChange.betweenWhole(primary.after, merged);
7737
+ return flip ? {
7565
7738
  a: deleted,
7566
7739
  b: edited
7740
+ } : {
7741
+ a: edited,
7742
+ b: deleted
7567
7743
  };
7568
7744
  }
7569
7745
  const overRemoval = transformMixedEditOverSiblingRemoval(a, b, aReplacements, bReplacements, document, afterA, afterB);
@@ -8917,6 +9093,34 @@ const writesOnlyElementProperties = (change, document) => {
8917
9093
  /** @internal */
8918
9094
  const documentChangeWritesOnlyElementProperties = (change, value) => change.createRoots.size === 0 && change.deleteRoots.size === 0 && [...getInternalDocumentChangeRecords(change).values()].every((set) => set.size === 0) && [...getInternalDocumentChangeEntries(change)].every(([root, rootChange]) => writesOnlyElementProperties(rootChange, () => valueRootIndex(value, root)));
8919
9095
  /** @internal */
9096
+ const documentChangePropertyOnlyWrites = (change, value) => {
9097
+ if (change.createRoots.size > 0 || change.deleteRoots.size > 0) return null;
9098
+ const writes = [];
9099
+ for (const [root, rootChange] of getInternalDocumentChangeEntries(change)) {
9100
+ let index;
9101
+ let position = 0;
9102
+ for (let at = 0; at < rootChange.sections.length; at += 2) {
9103
+ const length = getDefined(rootChange.sections[at]);
9104
+ const inserted = getDefined(rootChange.sections[at + 1]);
9105
+ if (inserted >= 0) return null;
9106
+ if (inserted === -2) {
9107
+ index ??= valueRootIndex(value, root);
9108
+ const node = invertiblePropertyNode(index, position, length);
9109
+ if (!node) return null;
9110
+ const modifications = rootChange.data[at / 2];
9111
+ const keys = [...new Set(modifications.map(({ key }) => key))].sort();
9112
+ writes.push(Object.freeze({
9113
+ keys: Object.freeze(keys),
9114
+ path: node.path,
9115
+ root
9116
+ }));
9117
+ }
9118
+ position += length;
9119
+ }
9120
+ }
9121
+ return writes;
9122
+ };
9123
+ /** @internal */
8920
9124
  const collapseDocumentElementPropertyWrites = (change, value, isSetValued, { textLeaves = false } = {}) => createInternalDocumentChange(new Map([...getInternalDocumentChangeEntries(change)].map(([root, rootChange]) => [root, collapseElementPropertyWrites(rootChange, valueRootIndex(value, root), isSetValued, root === "main" ? null : root, textLeaves)])), {
8921
9125
  createRoots: change.createRoots,
8922
9126
  deleteRoots: change.deleteRoots,
@@ -9681,6 +9885,7 @@ const historyFollowsAllFacts = () => followsAllFacts;
9681
9885
  const isEmptyRoot = (facts) => TABLES.every((table) => facts[table].length === 0);
9682
9886
  const byFirst = (left, right) => left[0] - right[0];
9683
9887
  const continues = (last, [at, from]) => last !== void 0 && last[0] + last[2] === at && last[1] + last[2] === from;
9888
+ /** @internal */
9684
9889
  const sortedRootFacts = ({ carries, cuts = [], heirs, mends = [], merges }) => {
9685
9890
  const runs = [];
9686
9891
  for (const carry of carries.sort(byFirst)) {
@@ -9700,6 +9905,7 @@ const sortedRootFacts = ({ carries, cuts = [], heirs, mends = [], merges }) => {
9700
9905
  merges: merges.sort(byFirst)
9701
9906
  };
9702
9907
  };
9908
+ /** @internal */
9703
9909
  const recorded = (entries) => {
9704
9910
  const roots = [...entries].filter(([, facts]) => !isEmptyRoot(facts)).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
9705
9911
  if (roots.length === 0) return NO_FACTS;
@@ -9824,7 +10030,9 @@ const targetsOf = (change, facts) => sortSegments([
9824
10030
  start: at
9825
10031
  }))
9826
10032
  ]);
10033
+ /** @internal */
9827
10034
  const composeRoot = (a, aFacts, b, bFacts) => {
10035
+ if (isEmptyRoot(aFacts) && isEmptyRoot(bFacts)) return NO_ROOT_FACTS;
9828
10036
  const sources = sourcesOf(a, aFacts);
9829
10037
  const targets = targetsOf(b, bFacts);
9830
10038
  const carries = [];
@@ -10883,6 +11091,25 @@ const readUnnamed = (change, before, joinsLeaves) => {
10883
11091
  };
10884
11092
  };
10885
11093
  const UNSCOPED_ORIGINS = /* @__PURE__ */ new Set(["canonical", "migration"]);
11094
+ const lettersBeyond = (letters, covered) => {
11095
+ const beyond = /* @__PURE__ */ new Map();
11096
+ for (const [root, spans] of letters) {
11097
+ const held = mergeSpans(covered.get(root) ?? []);
11098
+ const rest = [];
11099
+ let next = 0;
11100
+ for (const [from, to] of mergeSpans(spans)) {
11101
+ let start = from;
11102
+ while (next < held.length && held[next][1] <= start) next += 1;
11103
+ for (let at = next; at < held.length && held[at][0] < to; at += 1) {
11104
+ if (held[at][0] > start) rest.push([start, held[at][0]]);
11105
+ start = Math.max(start, held[at][1]);
11106
+ }
11107
+ if (start < to) rest.push([start, to]);
11108
+ }
11109
+ if (rest.length > 0) beyond.set(root, rest);
11110
+ }
11111
+ return beyond;
11112
+ };
10886
11113
  const isClassified = (change) => [...getInternalDocumentChangeEntries(change)].every(([root]) => getInternalDocumentChangeClassification(change, root));
10887
11114
  const NO_INDEXES = freezeReadonlyMap(/* @__PURE__ */ new Map());
10888
11115
  const NO_RUNTIME_CANDIDATES = freezeReadonlyMap(/* @__PURE__ */ new Map());
@@ -10901,6 +11128,7 @@ var ChangeDraft = class ChangeDraft {
10901
11128
  assertCanonical;
10902
11129
  adoptCanonicalBaseline;
10903
11130
  canonical = true;
11131
+ sinceValidated = null;
10904
11132
  validationPending = false;
10905
11133
  construct;
10906
11134
  current;
@@ -10964,10 +11192,10 @@ var ChangeDraft = class ChangeDraft {
10964
11192
  }
10965
11193
  /** @internal */
10966
11194
  completedTextDeletion() {
10967
- const split = this.appliedSteps.findIndex((step) => step.origin === "canonical");
10968
- if (split <= 0) return null;
11195
+ const split = this.appliedSteps.findLastIndex((step) => step.origin !== "canonical") + 1;
11196
+ if (split === 0 || split === this.appliedSteps.length) return null;
10969
11197
  const own = this.appliedSteps.slice(0, split);
10970
- if (this.appliedSteps.slice(split).some((step) => step.origin !== "canonical") || own.some(({ change }) => change.createRoots.size > 0 || change.deleteRoots.size > 0)) return null;
11198
+ if (own.some(({ change }) => change.createRoots.size > 0 || change.deleteRoots.size > 0)) return null;
10971
11199
  const change = own.reduce((composed, step) => composed.compose(step.change), DocumentChange.empty);
10972
11200
  const [root, ...otherRoots] = getInternalDocumentChangeRootKeys(change);
10973
11201
  if (!root || otherRoots.length > 0) return null;
@@ -10995,18 +11223,32 @@ var ChangeDraft = class ChangeDraft {
10995
11223
  get newLetters() {
10996
11224
  return this.marks;
10997
11225
  }
10998
- /**
10999
- * Keep the steps of a draft this one replaces, such as a schema rebind that
11000
- * replays the accumulated change, so each original step stays recordable.
11001
- *
11002
- * @internal
11003
- */
11004
- keepSteps(from) {
11226
+ /** @internal */
11227
+ checkpoint() {
11228
+ return {
11229
+ change: this.accumulated,
11230
+ indexedAfter: this.indexedAfter(),
11231
+ letters: this.marks,
11232
+ record: this.record?.clone() ?? null,
11233
+ sinceValidated: this.sinceValidated,
11234
+ spanStart: this.spanStart,
11235
+ steps: [...this.appliedSteps]
11236
+ };
11237
+ }
11238
+ /** @internal */
11239
+ resume(checkpoint) {
11240
+ const step = checkpoint.change.empty ? null : this.apply(checkpoint.change, { indexedAfter: checkpoint.indexedAfter });
11005
11241
  this.appliedSteps.length = 0;
11006
- this.appliedSteps.push(...from.appliedSteps);
11007
- this.marks = from.marks;
11008
- this.record = from.record?.clone() ?? null;
11009
- this.spanStart = from.spanStart;
11242
+ this.appliedSteps.push(...checkpoint.steps);
11243
+ this.marks = checkpoint.letters;
11244
+ this.record = checkpoint.record?.clone() ?? null;
11245
+ this.sinceValidated = checkpoint.sinceValidated;
11246
+ this.spanStart = checkpoint.spanStart;
11247
+ return step;
11248
+ }
11249
+ /** @internal */
11250
+ stepsSince(checkpoint) {
11251
+ return this.appliedSteps.slice(checkpoint?.steps.length ?? 0);
11010
11252
  }
11011
11253
  factsFor(change) {
11012
11254
  return sameRootChanges(change, this.accumulated) ? this.record?.facts() ?? NO_FACTS : UNKNOWN_FACTS;
@@ -11105,10 +11347,17 @@ var ChangeDraft = class ChangeDraft {
11105
11347
  } : step;
11106
11348
  }
11107
11349
  land(step) {
11108
- this.appliedSteps.push(step);
11109
- if (this.marks.size === 0 && !step.letters) return;
11350
+ if (this.marks.size === 0 && !step.letters) {
11351
+ this.appliedSteps.push(step);
11352
+ return;
11353
+ }
11110
11354
  const marks = landMarks(this.marks, step);
11111
- for (const [root, spans] of step.letters ?? []) marks.set(root, mergeSpans([...marks.get(root) ?? [], ...spans]));
11355
+ const unlanded = step.letters && lettersBeyond(step.letters, marks);
11356
+ for (const [root, spans] of unlanded ?? []) marks.set(root, mergeSpans([...marks.get(root) ?? [], ...spans]));
11357
+ this.appliedSteps.push(unlanded ? {
11358
+ ...step,
11359
+ letters: unlanded
11360
+ } : step);
11112
11361
  this.marks = marks;
11113
11362
  }
11114
11363
  /**
@@ -11259,6 +11508,7 @@ var ChangeDraft = class ChangeDraft {
11259
11508
  for (const [root, index] of payload.indexes) this.indexes.set(root, index);
11260
11509
  for (const root of payload.change.deleteRoots) this.indexes.delete(root);
11261
11510
  this.accumulated = accumulated;
11511
+ this.composeSinceValidated(payload.change);
11262
11512
  for (const step of payload.steps) {
11263
11513
  if (!this.stepMove || step.move) {
11264
11514
  this.land(this.composed(step));
@@ -11364,6 +11614,7 @@ var ChangeDraft = class ChangeDraft {
11364
11614
  const prefix = this.accumulated;
11365
11615
  const facts = this.landedAsUnknown(options.facts ?? UNKNOWN_FACTS);
11366
11616
  this.accumulated = this.accumulated.empty ? classifiedChange : this.accumulated.compose(classifiedChange, this.source);
11617
+ this.composeSinceValidated(classifiedChange);
11367
11618
  if (!classifiedChange.empty) {
11368
11619
  const relocations = this.recordsRelocations ? options.relocations : void 0;
11369
11620
  this.recordFacts(prefix, classifiedChange, facts);
@@ -11422,12 +11673,14 @@ var ChangeDraft = class ChangeDraft {
11422
11673
  });
11423
11674
  } else this.validate?.(candidate.after, accumulated);
11424
11675
  this.assertCanonical?.(candidate.after, accumulated);
11425
- return this.applyTrustedCanonical(candidate.change, {
11676
+ const step = this.applyTrustedCanonical(candidate.change, {
11426
11677
  facts,
11427
11678
  indexedAfter: candidate.indexedAfter,
11428
11679
  recordsAfter: getValueRecords(candidate.after),
11429
11680
  runtimeCandidates: candidate.runtimeCandidates
11430
11681
  });
11682
+ this.standValidated();
11683
+ return step;
11431
11684
  }
11432
11685
  applyPropertyWrites(change) {
11433
11686
  if (!this.canonical || this.validationPending) return this.apply(change);
@@ -11453,6 +11706,7 @@ var ChangeDraft = class ChangeDraft {
11453
11706
  const before = this.current;
11454
11707
  const current = applyDocumentChangeWithIndexes(change, before, NO_INDEXES);
11455
11708
  this.accumulated = this.accumulated.empty ? change : this.accumulated.compose(change, this.source);
11709
+ this.composeSinceValidated(change);
11456
11710
  this.land(this.composed({
11457
11711
  indexedAfter: NO_INDEXES,
11458
11712
  indexedBefore: NO_INDEXES,
@@ -11566,6 +11820,7 @@ var ChangeDraft = class ChangeDraft {
11566
11820
  for (const root of change.deleteRoots) this.indexes.delete(root);
11567
11821
  const prefix = this.accumulated;
11568
11822
  this.accumulated = this.accumulated.empty ? canonicalChange : this.accumulated.compose(canonicalChange, this.source);
11823
+ this.composeSinceValidated(canonicalChange);
11569
11824
  if (!canonicalChange.empty) {
11570
11825
  this.recordFacts(prefix, canonicalChange, facts);
11571
11826
  this.land(this.composed({
@@ -11604,14 +11859,18 @@ var ChangeDraft = class ChangeDraft {
11604
11859
  const drops = [];
11605
11860
  if (!this.canonical && this.construct) {
11606
11861
  const steps = this.appliedSteps.slice(this.spanStart);
11607
- constructionChange = this.construct(this.tracksPlaces ? {
11862
+ const input = this.sinceValidated ? {
11608
11863
  ...this.validationInput(),
11864
+ sinceValidated: this.sinceValidated
11865
+ } : this.validationInput();
11866
+ constructionChange = this.construct(this.tracksPlaces ? {
11867
+ ...input,
11609
11868
  carried: {
11610
11869
  drops,
11611
11870
  steps,
11612
11871
  view: steps.length > 0 && (this.view?.() ?? false)
11613
11872
  }
11614
- } : this.validationInput(), preparation);
11873
+ } : input, preparation);
11615
11874
  }
11616
11875
  const classified = isClassified(this.accumulated);
11617
11876
  const step = constructionChange && !constructionChange.empty ? this.apply(constructionChange, {
@@ -11627,7 +11886,7 @@ var ChangeDraft = class ChangeDraft {
11627
11886
  this.record = null;
11628
11887
  this.indexes.clear();
11629
11888
  for (const [root, index] of this.sourceIndexes) this.indexes.set(root, index);
11630
- this.canonical = true;
11889
+ this.standValidated();
11631
11890
  this.validationPending = false;
11632
11891
  if (!step) return null;
11633
11892
  const indexedAfter = new Map(step.indexedAfter);
@@ -11649,10 +11908,27 @@ var ChangeDraft = class ChangeDraft {
11649
11908
  if (this.validate && this.hasUnindexedRootChange(input.after, input.indexedAfter)) this.validate(this.current, this.accumulated);
11650
11909
  else this.validateConstructed(input);
11651
11910
  } else this.validate?.(this.current, this.accumulated);
11652
- this.canonical = true;
11911
+ this.standValidated();
11653
11912
  this.validationPending = false;
11654
11913
  return step;
11655
11914
  }
11915
+ standValidated() {
11916
+ this.canonical = true;
11917
+ this.sinceValidated = this.accumulated.empty ? null : Object.freeze({
11918
+ before: this.current,
11919
+ change: DocumentChange.empty,
11920
+ indexedBefore: new Map(this.indexes)
11921
+ });
11922
+ }
11923
+ composeSinceValidated(change) {
11924
+ if (!this.sinceValidated || change.empty) return;
11925
+ const { before, change: since, indexedBefore } = this.sinceValidated;
11926
+ this.sinceValidated = Object.freeze({
11927
+ before,
11928
+ change: since.empty ? change : since.compose(change, before),
11929
+ indexedBefore
11930
+ });
11931
+ }
11656
11932
  createRoot(root, children) {
11657
11933
  if (root === "main" || Object.hasOwn(this.current.roots ?? {}, root)) throw new Error(`Cannot create editor root ${root}.`);
11658
11934
  const rootChange = replaceChildrenChange(DocumentIndex.fromValue([]), [], 0, 0, children);
@@ -11920,13 +12196,7 @@ const sameRootChanges = (left, right) => {
11920
12196
  return leftRoots.size === rightRoots.length && rightRoots.every(([root, change]) => leftRoots.get(root) === change) && sameSet(left.createRoots, right.createRoots) && sameSet(left.deleteRoots, right.deleteRoots);
11921
12197
  };
11922
12198
  const sameSet = (left, right) => left.size === right.size && [...left].every((item) => right.has(item));
11923
- /**
11924
- * The runs `steps` carried, as their composed change carries them: each
11925
- * run's source in the first step's input and its landing in the last step's
11926
- * output. A later step that edits inside a run ends it.
11927
- *
11928
- * @internal
11929
- */
12199
+ /** @internal */
11930
12200
  const carriedRunsOf = (steps) => {
11931
12201
  if (!steps.some((step) => step.carried)) return [];
11932
12202
  const rootChange = (step, root) => getInternalDocumentRootChange(step.change, root) ?? null;
@@ -11942,40 +12212,48 @@ const carriedRunsOf = (steps) => {
11942
12212
  return composed[step];
11943
12213
  };
11944
12214
  let runs = [];
12215
+ const dropRewrittenLeaves = (run, carriedAt, after) => run && after && run.length !== run.landed ? trimRunLeaves(run, getDefined(steps[carriedAt].indexedBefore.get(run.root)), after) : run;
11945
12216
  for (const [index, step] of steps.entries()) {
11946
- runs = runs.flatMap(({ run, step: carriedAt }) => {
12217
+ runs = runs.flatMap(({ carriedAt, run }) => {
12218
+ if (step.change.deleteRoots.has(run.root)) return [];
11947
12219
  const change = rootChange(step, run.root);
11948
12220
  if (!change) return [{
11949
- run,
11950
- step: carriedAt
12221
+ carriedAt,
12222
+ run
11951
12223
  }];
11952
12224
  const before = step.indexedBefore.get(run.root);
11953
12225
  const after = step.indexedAfter.get(run.root);
11954
- const mapped = before && after ? followCarriedRun(run, change, before, after) : mapCarriedRunThrough(run, change);
12226
+ const mapped = dropRewrittenLeaves(before && after ? followCarriedRun(run, change, before, after) : mapCarriedRunThrough(run, change), carriedAt, after);
11955
12227
  return mapped ? [{
11956
- run: mapped,
11957
- step: carriedAt
12228
+ carriedAt,
12229
+ run: mapped
11958
12230
  }] : [];
11959
12231
  });
11960
- for (const run of step.carried ?? []) runs.push({
11961
- run,
11962
- step: index
11963
- });
12232
+ for (const carried of step.carried ?? []) {
12233
+ const run = dropRewrittenLeaves(carried, index, step.indexedAfter.get(carried.root));
12234
+ if (run) runs.push({
12235
+ carriedAt: index,
12236
+ run
12237
+ });
12238
+ }
11964
12239
  }
11965
- return runs.flatMap(({ run: carried, step }) => {
11966
- const run = carried.length !== carried.landed ? trimRunLeaves(carried, getDefined(steps[step].indexedBefore.get(carried.root)), getDefined(steps.findLast((each) => each.indexedAfter.has(carried.root))?.indexedAfter.get(carried.root))) : carried;
11967
- if (!run) return [];
12240
+ return runs.flatMap(({ carriedAt, run }) => {
11968
12241
  const end = run.source + run.length;
11969
- const draft = draftBefore(run.root, step);
12242
+ const draft = draftBefore(run.root, carriedAt);
11970
12243
  const kept = draft ? keptRunsOf(draft, run.source, end) : [{
11971
12244
  at: run.source,
11972
12245
  from: run.source,
11973
12246
  to: end
11974
12247
  }];
11975
- return kept.length === 1 && kept[0].from === run.source && kept[0].to === end ? [{
12248
+ if (kept.length !== 1 || kept[0].from !== run.source || kept[0].to !== end) return [];
12249
+ const traced = {
11976
12250
  ...run,
11977
12251
  source: kept[0].at
11978
- }] : [];
12252
+ };
12253
+ const change = draftBefore(run.root, steps.length);
12254
+ const before = steps.find((step) => step.indexedBefore.has(run.root))?.indexedBefore.get(run.root);
12255
+ const after = steps.findLast((step) => step.indexedAfter.has(run.root))?.indexedAfter.get(run.root);
12256
+ return change && before && after && carriesRun(change, before, after, traced) ? [traced] : [];
11979
12257
  });
11980
12258
  };
11981
12259
  const classifyDocumentChange = (before, after, change) => {
@@ -12056,6 +12334,72 @@ const getEditorRuntimeRoot = (editor) => EDITOR_RUNTIME_ROOT.get(editor) ?? "mai
12056
12334
  const getEditorSchema = (editor) => getEditorRuntime(editor).schema;
12057
12335
  //#endregion
12058
12336
  //#region src/core/command-document.ts
12337
+ /**
12338
+ * The projection map of `change`, the change from the stored document to the
12339
+ * projected one.
12340
+ *
12341
+ * @internal
12342
+ */
12343
+ const projectionMapOf = (change) => Object.freeze({
12344
+ breaks: () => [],
12345
+ added: (root, position) => {
12346
+ const sections = getInternalDocumentRootChange(change, root)?.sections ?? [];
12347
+ let after = 0;
12348
+ for (let pair = 0; pair < sections.length; pair += 2) {
12349
+ countCoreWork("sectionsWalked");
12350
+ const inserted = sections[pair + 1];
12351
+ const length = inserted < 0 ? sections[pair] : inserted;
12352
+ if (inserted > 0 && after < position && position < after + length) return {
12353
+ from: after,
12354
+ to: after + length
12355
+ };
12356
+ after += length;
12357
+ if (after > position) return null;
12358
+ }
12359
+ return null;
12360
+ },
12361
+ change: () => {
12362
+ countCoreWork("projectionChanges");
12363
+ return change;
12364
+ },
12365
+ hides: (root, position) => {
12366
+ if (change.deleteRoots.has(root)) return true;
12367
+ const sections = getInternalDocumentRootChange(change, root)?.sections ?? [];
12368
+ let before = 0;
12369
+ for (let pair = 0; pair < sections.length; pair += 2) {
12370
+ countCoreWork("sectionsWalked");
12371
+ const length = sections[pair];
12372
+ if (sections[pair + 1] >= 0 && before < position && position < before + length) return true;
12373
+ before += length;
12374
+ if (before > position) return false;
12375
+ }
12376
+ return false;
12377
+ },
12378
+ moved: () => [],
12379
+ nodePath: () => null,
12380
+ projectRange: (root, low, high) => {
12381
+ if (change.deleteRoots.has(root)) return null;
12382
+ const rootChange = getInternalDocumentRootChange(change, root);
12383
+ const [from, to] = rootChange ? [getDefined(rootChange.mapPos(low, 1)), getDefined(rootChange.mapPos(high, -1))] : [low, high];
12384
+ return {
12385
+ from,
12386
+ kind: "placed",
12387
+ to
12388
+ };
12389
+ },
12390
+ reorders: () => false,
12391
+ roots: Object.freeze([...getInternalDocumentChangeEntries(change)].map(([root]) => root)),
12392
+ toProjected: (root, position, association) => {
12393
+ if (change.deleteRoots.has(root)) return null;
12394
+ const rootChange = getInternalDocumentRootChange(change, root);
12395
+ return rootChange ? getDefined(rootChange.mapPos(position, association === "forward" ? 1 : -1)) : position;
12396
+ },
12397
+ toStored: (root, position, assoc) => {
12398
+ if (change.deleteRoots.has(root)) return null;
12399
+ const rootChange = getInternalDocumentRootChange(change, root);
12400
+ return rootChange ? getDefined(mapRootChangePositionBackward(rootChange, position, assoc)) : position;
12401
+ }
12402
+ });
12059
12403
  const COMMAND_DOCUMENTS = /* @__PURE__ */ new WeakMap();
12060
12404
  /** @internal */
12061
12405
  const registerEditorCommandDocument = (editor, document) => {
@@ -12076,18 +12420,24 @@ const unplacedIn = (editor, what) => getEditorCommandDocument(editor)?.unplaced?
12076
12420
  //#region src/core/content.ts
12077
12421
  const CONTENT = /* @__PURE__ */ new WeakMap();
12078
12422
  /** @internal */
12079
- const registerEditorContent = (editor, predicate) => {
12423
+ const registerEditorContent = (editor, predicate, held = null) => {
12080
12424
  const owner = getEditorRuntimeOwner(editor);
12081
12425
  if (CONTENT.has(owner)) throw new Error("An editor accepts one content predicate.");
12082
- CONTENT.set(owner, predicate);
12426
+ const registered = {
12427
+ content: predicate,
12428
+ held
12429
+ };
12430
+ CONTENT.set(owner, registered);
12083
12431
  return () => {
12084
- if (CONTENT.get(owner) === predicate) CONTENT.delete(owner);
12432
+ if (CONTENT.get(owner) === registered) CONTENT.delete(owner);
12085
12433
  };
12086
12434
  };
12087
12435
  /** @internal */
12088
12436
  const hasEditorContent = (editor) => CONTENT.has(getEditorRuntimeOwner(editor));
12089
12437
  /** @internal */
12090
- const isEditorContent = (editor, node) => CONTENT.get(getEditorRuntimeOwner(editor))?.(editor, node) ?? true;
12438
+ const isEditorContent = (editor, node) => CONTENT.get(getEditorRuntimeOwner(editor))?.content(editor, node) ?? true;
12439
+ /** @internal */
12440
+ const holdsEditorWrite = (editor, point, document) => CONTENT.get(getEditorRuntimeOwner(editor))?.held?.(editor, point, document) ?? false;
12091
12441
  //#endregion
12092
12442
  //#region src/interfaces/text.ts
12093
12443
  const getOwnValue = (object, key) => Object.hasOwn(object, key) ? object[key] : void 0;
@@ -12593,6 +12943,129 @@ const readPersistedEnvelope = (input) => {
12593
12943
  };
12594
12944
  };
12595
12945
  //#endregion
12946
+ //#region src/core/schema-validation.ts
12947
+ const freezeTarget = (target) => {
12948
+ switch (target.kind) {
12949
+ case "and":
12950
+ case "or": return Object.freeze({
12951
+ ...target,
12952
+ targets: Object.freeze(target.targets.map(freezeTarget))
12953
+ });
12954
+ case "not":
12955
+ case "parent": return Object.freeze({
12956
+ ...target,
12957
+ target: freezeTarget(target.target)
12958
+ });
12959
+ case "types": return Object.freeze({
12960
+ ...target,
12961
+ types: Object.freeze([...target.types])
12962
+ });
12963
+ default: return Object.freeze({ ...target });
12964
+ }
12965
+ };
12966
+ const freezePropertyContext = (property) => Object.freeze({
12967
+ plugins: Object.freeze([...new Set(property.plugins)].sort()),
12968
+ ids: Object.freeze([...property.ids]),
12969
+ key: property.key,
12970
+ placement: property.placement,
12971
+ targets: Object.freeze(property.targets.map((target) => target === null ? null : freezeTarget(target)))
12972
+ });
12973
+ const freezeDiagnostic = (diagnostic) => Object.freeze({
12974
+ ...diagnostic.ancestorTypes ? { ancestorTypes: Object.freeze([...diagnostic.ancestorTypes]) } : {},
12975
+ code: diagnostic.code,
12976
+ message: diagnostic.message,
12977
+ ...diagnostic.nodeType === void 0 ? {} : { nodeType: diagnostic.nodeType },
12978
+ ...diagnostic.parentType === void 0 ? {} : { parentType: diagnostic.parentType },
12979
+ path: Object.freeze([...diagnostic.path]),
12980
+ ...diagnostic.property ? { property: freezePropertyContext(diagnostic.property) } : {},
12981
+ root: diagnostic.root === "main" ? null : diagnostic.root
12982
+ });
12983
+ /** Runtime document/fragment validation error with immutable diagnostics. */
12984
+ var EditorSchemaValidationError = class extends Error {
12985
+ diagnostics;
12986
+ constructor(diagnostics, options = {}) {
12987
+ const frozen = Object.freeze((typeof diagnostics === "string" ? [{
12988
+ code: "invalid-document",
12989
+ message: diagnostics,
12990
+ path: [],
12991
+ root: null
12992
+ }] : Array.isArray(diagnostics) ? diagnostics : [diagnostics]).map(freezeDiagnostic));
12993
+ super(frozen.map(({ message }) => message).join("\n"), options);
12994
+ this.name = "EditorSchemaValidationError";
12995
+ this.diagnostics = frozen;
12996
+ }
12997
+ };
12998
+ /** @internal */
12999
+ var EditorNoncanonicalChangeError = class extends EditorSchemaValidationError {
13000
+ constructor() {
13001
+ super("Document changes must already use canonical editor representation.");
13002
+ this.name = "EditorNoncanonicalChangeError";
13003
+ }
13004
+ };
13005
+ /**
13006
+ * Build one deterministic path-aware runtime schema error.
13007
+ *
13008
+ * @internal
13009
+ */
13010
+ const createEditorSchemaValidationError = (code, message, location, options = {}) => {
13011
+ const candidates = options.property ? [...options.property.candidates].sort((left, right) => left.id.localeCompare(right.id)) : [];
13012
+ return new EditorSchemaValidationError({
13013
+ ...location.ancestorTypes ? { ancestorTypes: location.ancestorTypes } : {},
13014
+ code,
13015
+ message,
13016
+ ...location.nodeType === void 0 ? {} : { nodeType: location.nodeType },
13017
+ ...location.parentType === void 0 ? {} : { parentType: location.parentType },
13018
+ path: location.path,
13019
+ ...options.property ? { property: {
13020
+ plugins: candidates.map(({ owner }) => owner),
13021
+ ids: candidates.map(({ id }) => id),
13022
+ key: options.property.key,
13023
+ placement: options.property.placement,
13024
+ targets: candidates.map(({ target }) => target)
13025
+ } } : {},
13026
+ root: location.root
13027
+ }, { cause: options.cause });
13028
+ };
13029
+ //#endregion
13030
+ //#region src/core/reserved-element-id.ts
13031
+ const ELEMENT_ID_SCOPE_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
13032
+ const ELEMENT_ID_SCOPE_LENGTH = 12;
13033
+ const ELEMENT_ID_SCOPE_UNIFORM_LIMIT = 256 - 256 % 36;
13034
+ const randomElementIdScope = () => {
13035
+ let scope = "";
13036
+ const bytes = /* @__PURE__ */ new Uint8Array(24);
13037
+ while (scope.length < ELEMENT_ID_SCOPE_LENGTH) {
13038
+ crypto.getRandomValues(bytes);
13039
+ for (const byte of bytes) {
13040
+ if (byte >= ELEMENT_ID_SCOPE_UNIFORM_LIMIT) continue;
13041
+ scope += ELEMENT_ID_SCOPE_ALPHABET.charAt(byte % 36);
13042
+ if (scope.length === ELEMENT_ID_SCOPE_LENGTH) break;
13043
+ }
13044
+ }
13045
+ return scope;
13046
+ };
13047
+ const createElementIdMint = () => {
13048
+ let scope;
13049
+ let counter = 0;
13050
+ const scopeOf = () => {
13051
+ scope ??= randomElementIdScope();
13052
+ return scope;
13053
+ };
13054
+ return Object.freeze({
13055
+ next: () => {
13056
+ const value = `${scopeOf()}.${counter}`;
13057
+ counter += 1;
13058
+ return value;
13059
+ },
13060
+ get scope() {
13061
+ return scopeOf();
13062
+ }
13063
+ });
13064
+ };
13065
+ function assertValidElementId(value, location) {
13066
+ if (typeof value !== "string" || value.length === 0) throw createEditorSchemaValidationError("invalid-property-value", "Element property \"id\" must be a non-empty string.", location);
13067
+ }
13068
+ //#endregion
12596
13069
  //#region src/core/schema-compiler.ts
12597
13070
  const BUILT_IN_GROUPS = [
12598
13071
  "all",
@@ -14166,7 +14639,7 @@ const assertPropertyAgreesAcrossPlaces = (properties) => {
14166
14639
  }
14167
14640
  });
14168
14641
  };
14169
- const compileEditorSchemaInternal = (inputRecords, revision) => {
14642
+ const compileEditorSchemaInternal = (inputRecords, revision, elementIdMint) => {
14170
14643
  if (!Number.isSafeInteger(revision) || revision < 0) compileFailure("invalid-schema-revision", "Compiled schema revision must be a non-negative integer.", [], "revision");
14171
14644
  assertSchemaDeclarationOwnership(inputRecords);
14172
14645
  collectSchemaKeyDiagnostics(inputRecords);
@@ -14849,6 +15322,7 @@ const compileEditorSchemaInternal = (inputRecords, revision) => {
14849
15322
  }));
14850
15323
  return Object.freeze({
14851
15324
  diagnostics: Object.freeze([]),
15325
+ elementIdMint: elementIdMint ?? createElementIdMint(),
14852
15326
  elements,
14853
15327
  everyElementHasId,
14854
15328
  identity: derived ? Object.freeze({
@@ -14884,7 +15358,7 @@ const compileEditorSchemaInternal = (inputRecords, revision) => {
14884
15358
  vocabulary
14885
15359
  });
14886
15360
  };
14887
- const compileEditorSchemaContributions = (records, options = {}) => profileCoreDuration("schema-compile", () => compileEditorSchemaInternal(prepareEditorSchemaRecords(records), options.revision ?? 0));
15361
+ const compileEditorSchemaContributions = (records, options = {}) => profileCoreDuration("schema-compile", () => compileEditorSchemaInternal(prepareEditorSchemaRecords(records), options.revision ?? 0, options.elementIdMint));
14888
15362
  const collectRuntimePropertyDescriptors = (records) => {
14889
15363
  const descriptors = /* @__PURE__ */ new Map();
14890
15364
  for (const record of records) {
@@ -14934,7 +15408,7 @@ const haveEquivalentRuntimeValidationBindings = (left, right) => {
14934
15408
  const rightItem = right.item;
14935
15409
  return Boolean(leftItem && rightItem && haveEquivalentRuntimeValidationBindings(leftItem, rightItem));
14936
15410
  };
14937
- const replaceCompiledPropertyDescriptors = (schema, descriptors, revision) => {
15411
+ const replaceCompiledPropertyDescriptors = (schema, descriptors, revision, elementIdMint) => {
14938
15412
  const byId = /* @__PURE__ */ new Map();
14939
15413
  for (const [id, { references: _references, ...property }] of schema.properties.byId) {
14940
15414
  const runtime = descriptors.get(id);
@@ -14947,6 +15421,7 @@ const replaceCompiledPropertyDescriptors = (schema, descriptors, revision) => {
14947
15421
  }
14948
15422
  return Object.freeze({
14949
15423
  ...schema,
15424
+ elementIdMint: elementIdMint ?? ("elementIdMint" in schema ? schema.elementIdMint : createElementIdMint()),
14950
15425
  properties: Object.freeze({
14951
15426
  ...schema.properties,
14952
15427
  byId: freezeMap$2(byId)
@@ -14974,8 +15449,9 @@ const toStructuralPropertyDescriptor = (descriptor) => {
14974
15449
  * @internal
14975
15450
  */
14976
15451
  const stripCompiledEditorSchemaRuntimeValidations = (schema) => {
15452
+ const { elementIdMint, ...rest } = schema;
14977
15453
  const byId = /* @__PURE__ */ new Map();
14978
- for (const [id, property] of schema.properties.byId) {
15454
+ for (const [id, property] of rest.properties.byId) {
14979
15455
  const { references, ...structural } = property;
14980
15456
  byId.set(id, Object.freeze({
14981
15457
  ...structural,
@@ -14984,14 +15460,14 @@ const stripCompiledEditorSchemaRuntimeValidations = (schema) => {
14984
15460
  }));
14985
15461
  }
14986
15462
  return Object.freeze({
14987
- ...schema,
15463
+ ...rest,
14988
15464
  properties: Object.freeze({
14989
- ...schema.properties,
15465
+ ...rest.properties,
14990
15466
  byId: freezeMap$2(byId)
14991
15467
  })
14992
15468
  });
14993
15469
  };
14994
- const isBoundTo = (schema, current, revision) => schema.revision === revision && schema.properties.byId.size === current.size && [...schema.properties.byId].every(([id, property]) => {
15470
+ const isBoundTo = (schema, current, revision, elementIdMint) => "elementIdMint" in schema && (elementIdMint === void 0 || schema.elementIdMint === elementIdMint) && schema.revision === revision && schema.properties.byId.size === current.size && [...schema.properties.byId].every(([id, property]) => {
14995
15471
  const runtime = current.get(id);
14996
15472
  return Boolean(runtime && (property.references === void 0 ? runtime.references === void 0 : "map" in property.references && property.references.map === runtime.references?.map) && haveEquivalentRuntimeValidationBindings(property.descriptor, runtime.descriptor));
14997
15473
  });
@@ -15000,9 +15476,9 @@ const isBoundTo = (schema, current, revision) => schema.revision === revision &&
15000
15476
  *
15001
15477
  * @internal
15002
15478
  */
15003
- const rebindCompiledEditorSchemaRuntimeValidations = (schema, records, revision) => {
15479
+ const rebindCompiledEditorSchemaRuntimeValidations = (schema, records, revision, elementIdMint) => {
15004
15480
  const current = collectRuntimePropertyDescriptors(records);
15005
- if (isBoundTo(schema, current, revision)) return schema;
15481
+ if (isBoundTo(schema, current, revision, elementIdMint)) return schema;
15006
15482
  const descriptors = /* @__PURE__ */ new Map();
15007
15483
  for (const id of schema.properties.byId.keys()) {
15008
15484
  const runtime = current.get(id);
@@ -15012,7 +15488,7 @@ const rebindCompiledEditorSchemaRuntimeValidations = (schema, records, revision)
15012
15488
  descriptor: clonePropertyDescriptor$1(runtime.descriptor, runtime.source)
15013
15489
  });
15014
15490
  }
15015
- return replaceCompiledPropertyDescriptors(schema, descriptors, revision);
15491
+ return replaceCompiledPropertyDescriptors(schema, descriptors, revision, elementIdMint);
15016
15492
  };
15017
15493
  const EDITOR_SCHEMA_CONTRACT_FORMAT = 1;
15018
15494
  const canonicalContentProgram = (program) => ({
@@ -15872,7 +16348,11 @@ const mergeSchemaContributionRegistries = (configured, base, revision, previous
15872
16348
  }
15873
16349
  const declarationKey = getEditorSchemaDeclarationKey([...records.values()]);
15874
16350
  const reusable = previous?.declarationKey === declarationKey ? previous.compiled : getCachedSchema(declarationKey);
15875
- const compiled = reusable ? rebindCompiledEditorSchemaRuntimeValidations(reusable, [...records.values()], revision) : compileEditorSchemaContributions([...records.values()], { revision });
16351
+ const elementIdMint = previous?.compiled.elementIdMint;
16352
+ const compiled = reusable ? rebindCompiledEditorSchemaRuntimeValidations(reusable, [...records.values()], revision, elementIdMint) : compileEditorSchemaContributions([...records.values()], {
16353
+ elementIdMint,
16354
+ revision
16355
+ });
15876
16356
  cacheSchema(declarationKey, compiled);
15877
16357
  const delta = createCompiledEditorSchemaDelta(previous?.compiled ?? null, compiled);
15878
16358
  return finalizeSchemaContributionRegistry({
@@ -16439,6 +16919,11 @@ const HISTORY_TAGS = [
16439
16919
  "history-skip"
16440
16920
  ];
16441
16921
  const HISTORY_TAG_SET = new Set(HISTORY_TAGS);
16922
+ /**
16923
+ * An update whose commit starts its own undo step, which no later commit
16924
+ * joins, such as a write that decides another author's change with it.
16925
+ */
16926
+ const HISTORY_BOUNDARY_TAG = "history-boundary";
16442
16927
  const historyPolicyTags = {
16443
16928
  merge: "history-merge",
16444
16929
  "new-batch": "history-push",
@@ -16551,13 +17036,40 @@ const refuseVetoedWrite = (editor, input) => {
16551
17036
  }, `A plugin refused to ${input.kind} the "${input.node.type}" element at [${input.path.join(",")}] of root "${input.root}".`);
16552
17037
  };
16553
17038
  //#endregion
16554
- //#region src/core/change/range-association.ts
16555
- const getRangeEndpointAssociations = (direction, association) => {
16556
- if (association === "backward") return [-1, -1];
16557
- if (association === "forward" || direction === "collapsed") return [1, 1];
16558
- const inward = association !== "outward";
16559
- if (direction === "forward") return inward ? [1, -1] : [-1, 1];
16560
- return inward ? [-1, 1] : [1, -1];
17039
+ //#region src/core/document-view-read.ts
17040
+ const DOCUMENT_VIEWS = /* @__PURE__ */ new WeakSet();
17041
+ const DOCUMENT_VIEW_READS = /* @__PURE__ */ new WeakMap();
17042
+ /** Whether a view renders its own document. @internal */
17043
+ const isDocumentView = (view) => DOCUMENT_VIEWS.has(view);
17044
+ /** Mark a view bound to its own document. @internal */
17045
+ const registerDocumentView = (view) => {
17046
+ DOCUMENT_VIEWS.add(view);
17047
+ };
17048
+ /**
17049
+ * Run code on behalf of a document view. While it runs, reading the source
17050
+ * editor through its own API throws: plugin code must read the view's
17051
+ * document through the editor or state passed to it. Other editors run `fn`
17052
+ * unchanged.
17053
+ *
17054
+ * @internal
17055
+ */
17056
+ const withDocumentViewRead = (editor, fn) => {
17057
+ if (!DOCUMENT_VIEWS.has(editor)) return fn();
17058
+ const owner = getEditorRuntimeOwner(editor);
17059
+ const depth = DOCUMENT_VIEW_READS.get(owner) ?? 0;
17060
+ DOCUMENT_VIEW_READS.set(owner, depth + 1);
17061
+ try {
17062
+ return fn();
17063
+ } finally {
17064
+ if (depth === 0) DOCUMENT_VIEW_READS.delete(owner);
17065
+ else DOCUMENT_VIEW_READS.set(owner, depth);
17066
+ }
17067
+ };
17068
+ /** @internal */
17069
+ const isDocumentViewReading = (editor) => DOCUMENT_VIEW_READS.has(getEditorRuntimeOwner(editor));
17070
+ /** Refuse a source-editor read made while a document view is reading. @internal */
17071
+ const assertNoDocumentViewRead = (editor) => {
17072
+ if (isDocumentViewReading(editor)) throw new Error("Editor read its own document while a document view was reading. Read through the editor or state passed to this call: an editor captured when a plugin was created is the source editor.");
16561
17073
  };
16562
17074
  //#endregion
16563
17075
  //#region src/core/public-root.ts
@@ -16606,6 +17118,89 @@ const toInternalRoot = (root) => {
16606
17118
  assertPublicRootKey(root);
16607
17119
  return root ?? "main";
16608
17120
  };
17121
+ //#endregion
17122
+ //#region src/core/authored-runtime.ts
17123
+ const AUTHORED_RUNTIMES = /* @__PURE__ */ new WeakMap();
17124
+ const UPDATE_VIEWS = /* @__PURE__ */ new WeakMap();
17125
+ const toStoredTarget = (view, target) => {
17126
+ const installed = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view));
17127
+ return installed ? installed.toStored(view, toInternalRoot(view.read.view.root()), target) : {
17128
+ kind: "stored",
17129
+ target
17130
+ };
17131
+ };
17132
+ /** `read` with every view of `view`'s editor reading the stored document. */
17133
+ const withStoredAuthoredRead = (view, read) => {
17134
+ const installed = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view));
17135
+ return installed ? installed.readStored(view, read) : read();
17136
+ };
17137
+ const mapToAuthoredView = (view, root, value) => {
17138
+ const installed = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view));
17139
+ return installed ? installed.mapToView(view, root, value) : value;
17140
+ };
17141
+ const readAuthoredView = (view) => AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view))?.view(view);
17142
+ const isAuthoredPreview = (view) => {
17143
+ const authored = readAuthoredView(view);
17144
+ return authored !== void 0 && "preview" in authored;
17145
+ };
17146
+ const readShownPreview = (view) => {
17147
+ const authored = isDocumentView(view) ? void 0 : readAuthoredView(view);
17148
+ return authored && "preview" in authored ? authored.preview : void 0;
17149
+ };
17150
+ const withAuthoredViewRead = (source, view, read) => {
17151
+ const installed = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(source));
17152
+ return installed ? installed.readView(view, read) : read();
17153
+ };
17154
+ const configureAuthoredView = (view, value) => {
17155
+ const installed = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view));
17156
+ if (!installed) {
17157
+ if (value) throw new Error("Authored changes are not installed.");
17158
+ return;
17159
+ }
17160
+ if (value) installed.setView(view, value);
17161
+ };
17162
+ /** Switch a live view's authored setting once its composition, if any, ends. */
17163
+ const requestAuthoredView = (view, value) => {
17164
+ const installed = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view));
17165
+ if (!installed) throw new Error("Authored changes are not installed.");
17166
+ installed.requestView(view, value);
17167
+ };
17168
+ /** Run an update as one view's, so the recorder reads that view's intent. */
17169
+ const withAuthoredUpdateView = (source, view, update) => {
17170
+ const owner = getEditorRuntimeOwner(source);
17171
+ const previous = UPDATE_VIEWS.get(owner);
17172
+ UPDATE_VIEWS.set(owner, view);
17173
+ try {
17174
+ return update();
17175
+ } finally {
17176
+ if (previous) UPDATE_VIEWS.set(owner, previous);
17177
+ else UPDATE_VIEWS.delete(owner);
17178
+ }
17179
+ };
17180
+ const getAuthoredUpdateView = (editor) => UPDATE_VIEWS.get(getEditorRuntimeOwner(editor)) ?? editor;
17181
+ const VIEW_COMMIT_SOURCES = /* @__PURE__ */ new WeakMap();
17182
+ const getViewCommitSource = (commit) => VIEW_COMMIT_SOURCES.get(commit) ?? commit;
17183
+ const getAuthoredViewCommit = (view, commit) => {
17184
+ const shown = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view))?.viewCommit(view, commit) ?? commit;
17185
+ if (shown !== commit) VIEW_COMMIT_SOURCES.set(shown, commit);
17186
+ return shown;
17187
+ };
17188
+ const registerAuthoredRuntime = (editor, runtime) => {
17189
+ const owner = getEditorRuntimeOwner(editor);
17190
+ AUTHORED_RUNTIMES.set(owner, runtime);
17191
+ return () => {
17192
+ if (AUTHORED_RUNTIMES.get(owner) === runtime) AUTHORED_RUNTIMES.delete(owner);
17193
+ };
17194
+ };
17195
+ //#endregion
17196
+ //#region src/core/change/range-association.ts
17197
+ const getRangeEndpointAssociations = (direction, association) => {
17198
+ if (association === "backward") return [-1, -1];
17199
+ if (association === "forward" || direction === "collapsed") return [1, 1];
17200
+ const inward = association !== "outward";
17201
+ if (direction === "forward") return inward ? [1, -1] : [-1, 1];
17202
+ return inward ? [-1, 1] : [1, -1];
17203
+ };
16609
17204
  const RECOVERY_AFTER_A_FORWARD = 1024;
16610
17205
  const RECOVERY_AFTER_B_FORWARD = 2048;
16611
17206
  const RECOVERY_AT_ONCE = 4096;
@@ -16628,6 +17223,7 @@ const COHERENT_ANCHOR_WORK = /* @__PURE__ */ new WeakMap();
16628
17223
  const ANCHOR_RUNTIME_ID = /* @__PURE__ */ new WeakMap();
16629
17224
  const ANCHOR_TRANSACTION_CEILING = /* @__PURE__ */ new WeakMap();
16630
17225
  const COMMIT_ANCHOR_HISTORY = /* @__PURE__ */ new WeakMap();
17226
+ const COMMIT_MOVED_ANCHORS = /* @__PURE__ */ new WeakMap();
16631
17227
  const STAGED_ANCHOR_PLACEMENTS = /* @__PURE__ */ new WeakMap();
16632
17228
  const STAGED_ANCHOR_HISTORY = /* @__PURE__ */ new WeakMap();
16633
17229
  const observeAnchorStateWork = (editor, observer) => {
@@ -16770,6 +17366,8 @@ const rebuildUnderAnchors = (editor, from, rebuild) => {
16770
17366
  const hasScopedAnchorListeners = (editor) => (getActiveAnchorState(editor)?.listeners.size ?? 0) > 0;
16771
17367
  const hasActiveAnchors = (editor) => hasScopedAnchorListeners(editor) || (BOUND_ANCHORS.get(editor) ?? 0) > 0;
16772
17368
  const getAnchorStateValue = (editor) => getActiveAnchorState(editor)?.value;
17369
+ const getPublishedAnchorValue = (editor) => ACTIVE_ANCHORS.get(editor)?.value;
17370
+ const getMovedAnchorIds = (commit) => COMMIT_MOVED_ANCHORS.get(getViewCommitSource(commit));
16773
17371
  const indexRoot = (value, indexes, root) => {
16774
17372
  let index = indexes.get(root);
16775
17373
  if (!index) {
@@ -17089,10 +17687,10 @@ const applyAnchorChange = (state, change, indexedAfter) => {
17089
17687
  beforeIndexes
17090
17688
  };
17091
17689
  };
17092
- const subscribeAnchorState = (editor, listener, getInitialValue) => {
17690
+ const subscribeAnchorState = (editor, listener, getInitialValue, reused) => {
17093
17691
  const scoped = ANCHOR_SCOPES.get(editor)?.at(-1);
17094
17692
  const state = scoped?.state ?? ACTIVE_ANCHORS.get(editor) ?? createActiveAnchorState(getInitialValue());
17095
- const runtimeId = scoped?.kind === "draft" ? void 0 : (() => {
17693
+ const runtimeId = scoped?.kind === "draft" ? void 0 : reused !== void 0 && reused <= (ANCHOR_RUNTIME_ID.get(editor) ?? 0) && ![state, ACTIVE_ANCHORS.get(editor)].some((held) => held?.listenersByRuntimeId.has(reused)) ? reused : (() => {
17096
17694
  const id = (ANCHOR_RUNTIME_ID.get(editor) ?? 0) + 1;
17097
17695
  if (id > 2147483647) throw new Error("Anchor runtime identity space is exhausted.");
17098
17696
  ANCHOR_RUNTIME_ID.set(editor, id);
@@ -17175,7 +17773,10 @@ const notifyAnchorChanges = (editor, change, indexedAfter, options = {}) => {
17175
17773
  listener.begin();
17176
17774
  state.activeTransaction.add(listener);
17177
17775
  }
17178
- if (listener.move?.place(context.afterRoot(listener.root), after, ...ends)) indexAnchorListener(state, listener);
17776
+ if (listener.move?.place(context.afterRoot(listener.root), after, ...ends)) {
17777
+ PREPARING_ANCHOR_STATES.get(state)?.moved.add(listener);
17778
+ indexAnchorListener(state, listener);
17779
+ }
17179
17780
  });
17180
17781
  };
17181
17782
  const placeAnchorsOnCommit = (editor, placement) => {
@@ -17209,6 +17810,7 @@ const commitAnchorTransaction = (editor, value, commit) => {
17209
17810
  listeners.add(listener);
17210
17811
  }
17211
17812
  listener.history.restore(data, offset, staged.target, state.value, deferredMemoize, true);
17813
+ preparing?.moved.add(listener);
17212
17814
  recoveredAnchors += 1;
17213
17815
  continue;
17214
17816
  }
@@ -17229,7 +17831,10 @@ const commitAnchorTransaction = (editor, value, commit) => {
17229
17831
  };
17230
17832
  restoreMemos.set(listener.root, memoize);
17231
17833
  }
17232
- if (listener.history.restore(data, offset, staged.target, state.value, memoize, false)) indexAnchorListener(state, listener);
17834
+ if (listener.history.restore(data, offset, staged.target, state.value, memoize, false)) {
17835
+ PREPARING_ANCHOR_STATES.get(state)?.moved.add(listener);
17836
+ indexAnchorListener(state, listener);
17837
+ }
17233
17838
  commitPreparedAnchorListener(state, listener, value, commit);
17234
17839
  listeners.delete(listener);
17235
17840
  recoveredAnchors += 1;
@@ -17330,6 +17935,7 @@ const prepareAnchorPublication = (editor, commit, prepare) => {
17330
17935
  const preparing = {
17331
17936
  before: before?.value,
17332
17937
  indexes: /* @__PURE__ */ new Map(),
17938
+ moved: /* @__PURE__ */ new Set(),
17333
17939
  pending: /* @__PURE__ */ new Set(),
17334
17940
  publications: []
17335
17941
  };
@@ -17386,6 +17992,7 @@ const prepareAnchorPublication = (editor, commit, prepare) => {
17386
17992
  state.value = next.value;
17387
17993
  state.indexes = next.indexes;
17388
17994
  for (const publish of preparing.publications) publish();
17995
+ if (preparing.indexes.size > 0 || preparing.moved.size > 0) COMMIT_MOVED_ANCHORS.set(commit, new Set([...preparing.indexes.keys(), ...preparing.moved].flatMap((listener) => state.runtimeIds.get(listener) ?? [])));
17389
17996
  for (const [listener, patch] of preparing.indexes) applyPreparedAnchorIndex(state, listener, patch.nodeKeys, patch.fallback);
17390
17997
  }
17391
17998
  if (additions?.kind === "prepared") {
@@ -17423,113 +18030,68 @@ const prepareAnchorPublication = (editor, commit, prepare) => {
17423
18030
  }
17424
18031
  };
17425
18032
  //#endregion
17426
- //#region src/core/document-view-read.ts
17427
- const DOCUMENT_VIEWS = /* @__PURE__ */ new WeakSet();
17428
- const DOCUMENT_VIEW_READS = /* @__PURE__ */ new WeakMap();
17429
- /** Whether a view renders its own document. @internal */
17430
- const isDocumentView = (view) => DOCUMENT_VIEWS.has(view);
17431
- /** Mark a view bound to its own document. @internal */
17432
- const registerDocumentView = (view) => {
17433
- DOCUMENT_VIEWS.add(view);
17434
- };
17435
- /**
17436
- * Run code on behalf of a document view. While it runs, reading the source
17437
- * editor through its own API throws: plugin code must read the view's
17438
- * document through the editor or state passed to it. Other editors run `fn`
17439
- * unchanged.
17440
- *
17441
- * @internal
17442
- */
17443
- const withDocumentViewRead = (editor, fn) => {
17444
- if (!DOCUMENT_VIEWS.has(editor)) return fn();
17445
- const owner = getEditorRuntimeOwner(editor);
17446
- const depth = DOCUMENT_VIEW_READS.get(owner) ?? 0;
17447
- DOCUMENT_VIEW_READS.set(owner, depth + 1);
17448
- try {
17449
- return fn();
17450
- } finally {
17451
- if (depth === 0) DOCUMENT_VIEW_READS.delete(owner);
17452
- else DOCUMENT_VIEW_READS.set(owner, depth);
18033
+ //#region src/core/change/range-content.ts
18034
+ const insideVoid = (voids, position) => {
18035
+ let low = 0;
18036
+ let high = voids.length - 1;
18037
+ while (low <= high) {
18038
+ const middle = low + high >> 1;
18039
+ const [voidFrom, voidTo] = voids[middle];
18040
+ if (position < voidFrom) high = middle - 1;
18041
+ else if (position >= voidTo) low = middle + 1;
18042
+ else return true;
17453
18043
  }
18044
+ return false;
17454
18045
  };
18046
+ const FIRST_WINDOW = 64;
17455
18047
  /** @internal */
17456
- const isDocumentViewReading = (editor) => DOCUMENT_VIEW_READS.has(getEditorRuntimeOwner(editor));
17457
- /** Refuse a source-editor read made while a document view is reading. @internal */
17458
- const assertNoDocumentViewRead = (editor) => {
17459
- if (isDocumentViewReading(editor)) throw new Error("Editor read its own document while a document view was reading. Read through the editor or state passed to this call: an editor captured when a plugin was created is the source editor.");
17460
- };
17461
- //#endregion
17462
- //#region src/core/authored-runtime.ts
17463
- const AUTHORED_RUNTIMES = /* @__PURE__ */ new WeakMap();
17464
- const UPDATE_VIEWS = /* @__PURE__ */ new WeakMap();
17465
- const toStoredTarget = (view, target) => {
17466
- const installed = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view));
17467
- return installed ? installed.toStored(view, toInternalRoot(view.read.view.root()), target) : {
17468
- kind: "stored",
17469
- target
17470
- };
17471
- };
17472
- /** `read` with every view of `view`'s editor reading the stored document. */
17473
- const withStoredAuthoredRead = (view, read) => {
17474
- const installed = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view));
17475
- return installed ? installed.readStored(view, read) : read();
17476
- };
17477
- const mapToAuthoredView = (view, root, value) => {
17478
- const installed = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view));
17479
- return installed ? installed.mapToView(view, root, value) : value;
17480
- };
17481
- const readAuthoredView = (view) => AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view))?.view(view);
17482
- const isAuthoredPreview = (view) => {
17483
- const authored = readAuthoredView(view);
17484
- return authored !== void 0 && "preview" in authored;
17485
- };
17486
- const readShownPreview = (view) => {
17487
- const authored = isDocumentView(view) ? void 0 : readAuthoredView(view);
17488
- return authored && "preview" in authored ? authored.preview : void 0;
17489
- };
17490
- const withAuthoredViewRead = (source, view, read) => {
17491
- const installed = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(source));
17492
- return installed ? installed.readView(view, read) : read();
17493
- };
17494
- const configureAuthoredView = (view, value) => {
17495
- const installed = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view));
17496
- if (!installed) {
17497
- if (value) throw new Error("Authored changes are not installed.");
17498
- return;
18048
+ const coversContent = (index, from, to, schema) => {
18049
+ if (from >= to) return false;
18050
+ for (let width = FIRST_WINDOW;; width *= 2) {
18051
+ const end = Math.min(to, from + width);
18052
+ if (coversContentUpTo(index, from, end, to, schema)) return true;
18053
+ if (end === to) return false;
17499
18054
  }
17500
- if (value) installed.setView(view, value);
17501
18055
  };
17502
- /** Switch a live view's authored setting once its composition, if any, ends. */
17503
- const requestAuthoredView = (view, value) => {
17504
- const installed = AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view));
17505
- if (!installed) throw new Error("Authored changes are not installed.");
17506
- installed.requestView(view, value);
17507
- };
17508
- /** Run an update as one view's, so the recorder reads that view's intent. */
17509
- const withAuthoredUpdateView = (source, view, update) => {
17510
- const owner = getEditorRuntimeOwner(source);
17511
- const previous = UPDATE_VIEWS.get(owner);
17512
- UPDATE_VIEWS.set(owner, view);
17513
- try {
17514
- return update();
17515
- } finally {
17516
- if (previous) UPDATE_VIEWS.set(owner, previous);
17517
- else UPDATE_VIEWS.delete(owner);
18056
+ const coversContentUpTo = (index, from, end, to, schema) => {
18057
+ const entries = index.nodeRangesTouching(from, end);
18058
+ const voids = [];
18059
+ countCoreWork("contentSpanNodes", entries.length);
18060
+ for (const entry of entries) {
18061
+ if (entry.kind === "text" || !schema.isVoid(index.node(entry.path))) continue;
18062
+ if (from <= entry.from && entry.to <= to) return true;
18063
+ voids.push([entry.from, entry.to]);
17518
18064
  }
17519
- };
17520
- const getAuthoredUpdateView = (editor) => UPDATE_VIEWS.get(getEditorRuntimeOwner(editor)) ?? editor;
17521
- const getAuthoredViewCommit = (view, commit) => AUTHORED_RUNTIMES.get(getEditorRuntimeOwner(view))?.viewCommit(view, commit) ?? commit;
17522
- const registerAuthoredRuntime = (editor, runtime) => {
17523
- const owner = getEditorRuntimeOwner(editor);
17524
- AUTHORED_RUNTIMES.set(owner, runtime);
17525
- return () => {
17526
- if (AUTHORED_RUNTIMES.get(owner) === runtime) AUTHORED_RUNTIMES.delete(owner);
17527
- };
18065
+ voids.sort(([a], [b]) => a - b);
18066
+ const outerVoids = [];
18067
+ for (const range of voids) if (range[0] >= (outerVoids.at(-1)?.[1] ?? -1)) outerVoids.push(range);
18068
+ return entries.some((entry) => {
18069
+ if (entry.kind !== "text") return false;
18070
+ const start = Math.max(from, entry.contentFrom);
18071
+ return start < Math.min(end, entry.contentTo) && !insideVoid(outerVoids, start);
18072
+ });
17528
18073
  };
17529
18074
  //#endregion
17530
18075
  //#region src/core/anchor.ts
17531
18076
  const SAVED_RANGES = /* @__PURE__ */ new WeakMap();
17532
18077
  const RELEASED_RANGES = /* @__PURE__ */ new WeakSet();
18078
+ const ANCHOR_RUNTIME_IDS = /* @__PURE__ */ new WeakMap();
18079
+ /** The runtime ID that history's anchor records name this anchor by. */
18080
+ const getAnchorRuntimeId = (anchor) => ANCHOR_RUNTIME_IDS.get(anchor) ?? null;
18081
+ /**
18082
+ * Restore a saved range under the runtime ID of the anchor it was saved from,
18083
+ * when no live anchor holds that ID, so redoing a step that moved the released
18084
+ * anchor moves the restored one.
18085
+ */
18086
+ const restoreAnchor = (editor, input, runtimeId) => {
18087
+ const saved = decodeSavedRange(input);
18088
+ const options = {
18089
+ association: saved.association,
18090
+ deletion: saved.deletion,
18091
+ ...saved.root === "main" ? {} : { root: saved.root }
18092
+ };
18093
+ return saved.range ? createAnchor(editor, saved.range, options, runtimeId ?? void 0) : createBoundAnchor(editor, saved, void 0, "range");
18094
+ };
17533
18095
  const assertAnchorView = (editor, root, view) => {
17534
18096
  if (!view) return;
17535
18097
  const viewRoot = getEditorRuntimeRoot(view);
@@ -17633,14 +18195,7 @@ const createEditorAnchorApi = (getEditor) => Object.assign((value, options) => {
17633
18195
  }, "Saved editor range");
17634
18196
  },
17635
18197
  restore(input) {
17636
- const editor = getEditor();
17637
- const saved = decodeSavedRange(input);
17638
- const options = {
17639
- association: saved.association,
17640
- deletion: saved.deletion,
17641
- ...saved.root === "main" ? {} : { root: saved.root }
17642
- };
17643
- return saved.range ? createAnchor(editor, saved.range, options) : createBoundAnchor(editor, saved, void 0, "range");
18198
+ return restoreAnchor(getEditor(), input, null);
17644
18199
  }
17645
18200
  });
17646
18201
  const nodeKeyAt = (editor, root, path) => withEditorRootChildren(editor, root, () => getEditorRuntime(editor).getNodeKey(path));
@@ -17748,7 +18303,7 @@ const createPointState = (editor, value, point, root, document = indexedRoot(val
17748
18303
  };
17749
18304
  };
17750
18305
  /** Create one root-aware anchor mapped by canonical document changes. */
17751
- function createAnchor(editor, value, options) {
18306
+ function createAnchor(editor, value, options, runtimeId) {
17752
18307
  const viewEditor = editor;
17753
18308
  const runtimeEditor = getEditorRuntimeOwner(viewEditor);
17754
18309
  const kind = LocationApi.isPath(value) ? "path" : PointApi.isPoint(value) ? "point" : RangeApi.isRange(value) ? "range" : null;
@@ -18070,11 +18625,7 @@ function createAnchor(editor, value, options) {
18070
18625
  const sourceNode = source.node(state.point.path);
18071
18626
  const currentNode = next.node(runtimePath);
18072
18627
  if (isTextNode$2(sourceNode) && isTextNode$2(currentNode)) {
18073
- if (change.mapPosition(source.positionAt(state.point), {
18074
- association: endpointAssociation === -1 ? "backward" : "forward",
18075
- track: "around",
18076
- ...root === "main" ? {} : { root }
18077
- }) !== null && canonicalMapping?.runtimeStable) return canonicalMapping;
18628
+ if (canonicalMapping?.runtimeStable) return canonicalMapping;
18078
18629
  if (preserveSamePathOffset && PathApi.equals(runtimePath, state.point.path)) return {
18079
18630
  point: withPublicPointRoot({
18080
18631
  offset: Math.min(state.point.offset, currentNode.text.length),
@@ -18165,16 +18716,6 @@ function createAnchor(editor, value, options) {
18165
18716
  const targetWasExpanded = kind === "range" && !PointApi.equals(pointStates[0].point, getDefined(pointStates[1]).point);
18166
18717
  const sourceFrom = beforeDocument.positionAt(pointStates[0].point);
18167
18718
  const sourceTo = kind === "range" ? beforeDocument.positionAt(getDefined(pointStates[1]).point) : sourceFrom;
18168
- const sourceNodesKeepIdentity = pointStates.every((state) => {
18169
- const runtimePath = runtimePathOf(state.nodeKey, context);
18170
- if (!runtimePath) return false;
18171
- try {
18172
- return beforeDocument.node(state.point.path) === nextDocument().node(runtimePath);
18173
- } catch {
18174
- return false;
18175
- }
18176
- });
18177
- const sourceRangeWasDeleted = targetWasExpanded && !sourceNodesKeepIdentity && changeCoversSourceRange(change, root, Math.min(sourceFrom, sourceTo), Math.max(sourceFrom, sourceTo));
18178
18719
  const associations = kind === "point" ? [association === "backward" ? -1 : 1] : getRangeEndpointAssociations(PointApi.equals(current.anchor, current.focus) ? "collapsed" : PointApi.isBefore(current.anchor, current.focus) ? "forward" : "backward", association);
18179
18720
  const replacement = kind === "range" && options.deletion === "nearest" && !PointApi.equals(pointStates[0].point, getDefined(pointStates[1]).point) ? mapDocumentRangeReplacement(change, root, getSourceDocument().positionAt(pointStates[0].point), getSourceDocument().positionAt(getDefined(pointStates[1]).point), associations) : null;
18180
18721
  const mappedPoints = pointStates.map((state, index) => {
@@ -18204,6 +18745,30 @@ function createAnchor(editor, value, options) {
18204
18745
  point: withPublicPointRoot(mapped.point, root, state.includeRoot)
18205
18746
  } : null;
18206
18747
  });
18748
+ const sourceRangeWasDeleted = (() => {
18749
+ if (!targetWasExpanded) return false;
18750
+ const afterDocument = nextDocument();
18751
+ if (pointStates.every((state) => {
18752
+ const runtimePath = runtimePathOf(state.nodeKey, context);
18753
+ if (!runtimePath) return false;
18754
+ try {
18755
+ return beforeDocument.node(state.point.path) === afterDocument.node(runtimePath);
18756
+ } catch {
18757
+ return false;
18758
+ }
18759
+ })) return false;
18760
+ const sourceMin = Math.min(sourceFrom, sourceTo);
18761
+ const sourceMax = Math.max(sourceFrom, sourceTo);
18762
+ if (changeCoversSourceRange(change, root, sourceMin, sourceMax)) return true;
18763
+ const mappedStart = mappedPoints[0]?.point;
18764
+ const mappedEnd = mappedPoints[1]?.point;
18765
+ if (!mappedStart || !mappedEnd) return false;
18766
+ const mappedFrom = afterDocument.positionAt(mappedStart);
18767
+ const mappedTo = afterDocument.positionAt(mappedEnd);
18768
+ const schema = getEditorSchema(runtimeEditor);
18769
+ if (coversContent(afterDocument, Math.min(mappedFrom, mappedTo), Math.max(mappedFrom, mappedTo), schema)) return false;
18770
+ return coversContent(beforeDocument, sourceMin, sourceMax, schema);
18771
+ })();
18207
18772
  const start = sourceFrom <= sourceTo ? 0 : 1;
18208
18773
  const sources = options.deletion === "nearest" && sourceRangeWasDeleted && !replacement ? [start, start] : mappedPoints.map((_, index) => index);
18209
18774
  const points = sources.map((index) => mappedPoints[index]?.point ?? null);
@@ -18341,7 +18906,7 @@ function createAnchor(editor, value, options) {
18341
18906
  return pointStates.flatMap((state) => state.nodeKey ? [state.nodeKey] : []);
18342
18907
  },
18343
18908
  root
18344
- }, () => readValue(runtimeEditor));
18909
+ }, () => readValue(runtimeEditor), runtimeId);
18345
18910
  const anchor = Object.freeze({
18346
18911
  association,
18347
18912
  deletion: options.deletion,
@@ -18370,6 +18935,7 @@ function createAnchor(editor, value, options) {
18370
18935
  },
18371
18936
  root: toPublicRoot(root)
18372
18937
  });
18938
+ if (subscription.runtimeId !== void 0) ANCHOR_RUNTIME_IDS.set(anchor, subscription.runtimeId);
18373
18939
  if (kind === "range") SAVED_RANGES.set(anchor, {
18374
18940
  editor: getEditorRuntimeOwner(runtimeEditor),
18375
18941
  save() {
@@ -22886,7 +23452,11 @@ const startCompletion = ({ children, content, editing, element, schema }) => {
22886
23452
  continue;
22887
23453
  }
22888
23454
  if (fate === "kept") return null;
22889
- const node = schema.create(prefix.type, prefix.properties, { prefix: slot });
23455
+ const kept = editing?.vacatedProperties?.(slot);
23456
+ const node = schema.create(prefix.type, kept ? {
23457
+ ...prefix.properties,
23458
+ ...kept
23459
+ } : prefix.properties, { prefix: slot });
22890
23460
  builtSlots.set(node, { prefix: slot });
22891
23461
  inserted.add(node);
22892
23462
  built.push(node);
@@ -23076,90 +23646,6 @@ const adoptVerdicts = (verdicts) => {
23076
23646
  for (const [validate, byKey] of verdicts) for (const [key, verdict] of byKey) if (!table.get(validate)?.has(key)) record(table, validate, key, verdict);
23077
23647
  };
23078
23648
  //#endregion
23079
- //#region src/core/schema-validation.ts
23080
- const freezeTarget = (target) => {
23081
- switch (target.kind) {
23082
- case "and":
23083
- case "or": return Object.freeze({
23084
- ...target,
23085
- targets: Object.freeze(target.targets.map(freezeTarget))
23086
- });
23087
- case "not":
23088
- case "parent": return Object.freeze({
23089
- ...target,
23090
- target: freezeTarget(target.target)
23091
- });
23092
- case "types": return Object.freeze({
23093
- ...target,
23094
- types: Object.freeze([...target.types])
23095
- });
23096
- default: return Object.freeze({ ...target });
23097
- }
23098
- };
23099
- const freezePropertyContext = (property) => Object.freeze({
23100
- plugins: Object.freeze([...new Set(property.plugins)].sort()),
23101
- ids: Object.freeze([...property.ids]),
23102
- key: property.key,
23103
- placement: property.placement,
23104
- targets: Object.freeze(property.targets.map((target) => target === null ? null : freezeTarget(target)))
23105
- });
23106
- const freezeDiagnostic = (diagnostic) => Object.freeze({
23107
- ...diagnostic.ancestorTypes ? { ancestorTypes: Object.freeze([...diagnostic.ancestorTypes]) } : {},
23108
- code: diagnostic.code,
23109
- message: diagnostic.message,
23110
- ...diagnostic.nodeType === void 0 ? {} : { nodeType: diagnostic.nodeType },
23111
- ...diagnostic.parentType === void 0 ? {} : { parentType: diagnostic.parentType },
23112
- path: Object.freeze([...diagnostic.path]),
23113
- ...diagnostic.property ? { property: freezePropertyContext(diagnostic.property) } : {},
23114
- root: diagnostic.root === "main" ? null : diagnostic.root
23115
- });
23116
- /** Runtime document/fragment validation error with immutable diagnostics. */
23117
- var EditorSchemaValidationError = class extends Error {
23118
- diagnostics;
23119
- constructor(diagnostics, options = {}) {
23120
- const frozen = Object.freeze((typeof diagnostics === "string" ? [{
23121
- code: "invalid-document",
23122
- message: diagnostics,
23123
- path: [],
23124
- root: null
23125
- }] : Array.isArray(diagnostics) ? diagnostics : [diagnostics]).map(freezeDiagnostic));
23126
- super(frozen.map(({ message }) => message).join("\n"), options);
23127
- this.name = "EditorSchemaValidationError";
23128
- this.diagnostics = frozen;
23129
- }
23130
- };
23131
- /** @internal */
23132
- var EditorNoncanonicalChangeError = class extends EditorSchemaValidationError {
23133
- constructor() {
23134
- super("Document changes must already use canonical editor representation.");
23135
- this.name = "EditorNoncanonicalChangeError";
23136
- }
23137
- };
23138
- /**
23139
- * Build one deterministic path-aware runtime schema error.
23140
- *
23141
- * @internal
23142
- */
23143
- const createEditorSchemaValidationError = (code, message, location, options = {}) => {
23144
- const candidates = options.property ? [...options.property.candidates].sort((left, right) => left.id.localeCompare(right.id)) : [];
23145
- return new EditorSchemaValidationError({
23146
- ...location.ancestorTypes ? { ancestorTypes: location.ancestorTypes } : {},
23147
- code,
23148
- message,
23149
- ...location.nodeType === void 0 ? {} : { nodeType: location.nodeType },
23150
- ...location.parentType === void 0 ? {} : { parentType: location.parentType },
23151
- path: location.path,
23152
- ...options.property ? { property: {
23153
- plugins: candidates.map(({ owner }) => owner),
23154
- ids: candidates.map(({ id }) => id),
23155
- key: options.property.key,
23156
- placement: options.property.placement,
23157
- targets: candidates.map(({ target }) => target)
23158
- } } : {},
23159
- root: location.root
23160
- }, { cause: options.cause });
23161
- };
23162
- //#endregion
23163
23649
  //#region src/core/change/slice-facts.ts
23164
23650
  const spanning = (document, at) => document.openContextAt(at).filter((range) => range.from < at && range.to - 1 >= at);
23165
23651
  const isLeafOrLine = (document, range) => {
@@ -23349,6 +23835,7 @@ const completeChildrenAt = (editor, site, children, root, occupant, part, take)
23349
23835
  sources: completion.children
23350
23836
  };
23351
23837
  };
23838
+ /** @internal */
23352
23839
  const partOf = (content, part) => {
23353
23840
  if (!content || !part) return content;
23354
23841
  const { prefix, ...rest } = content;
@@ -23840,6 +24327,14 @@ const writeKeepingElements = (draft, path, from, written, canonical, rebuilt) =>
23840
24327
  writeRuns(path, from, written, canonical);
23841
24328
  if (draft.pending.length > pending) draft.document = document.withSplicedNodes(path, from, written.length, canonical);
23842
24329
  };
24330
+ const vacatedBlockId = (schema, left, nodes) => {
24331
+ if (!getCompiledEditorSchemaFromApi(schema)?.everyElementHasId || !ElementApi.isElement(left) || typeof left.id !== "string") return;
24332
+ for (let index = 0; index < nodes.length; index += 1) {
24333
+ const node = nodes.at(index);
24334
+ if (ElementApi.isElement(node) && node.id === left.id) return void 0;
24335
+ }
24336
+ return { id: left.id };
24337
+ };
23843
24338
  const replaceCanonicalChildWindow = (draft, editor, schema, root, rootContent, path, window, beforeDocument, rootChange, options = {}) => {
23844
24339
  const rootChildren = draft.document.nodes;
23845
24340
  const { document } = draft;
@@ -23941,8 +24436,10 @@ const replaceCanonicalChildWindow = (draft, editor, schema, root, rootContent, p
23941
24436
  if (!contentSpec) return;
23942
24437
  const children = path.length === 0 ? null : draft.document.node(path).children;
23943
24438
  const nodes = children ?? draft.document.nodes;
23944
- const previousParent = beforeDocument ? path.length === 0 ? null : getDescendant$1(beforeDocument.nodes, path) : null;
23945
- const previousChildren = beforeDocument && options.displacement !== "none" ? path.length === 0 ? beforeDocument.nodes : previousParent && ElementApi.isElement(previousParent) ? previousParent.children : null : null;
24439
+ const displacedDocument = options.displacedFrom?.document ?? beforeDocument;
24440
+ const displacedChange = options.displacedFrom ? options.displacedFrom.change : rootChange;
24441
+ const previousParent = displacedDocument ? path.length === 0 ? null : getDescendant$1(displacedDocument.nodes, path) : null;
24442
+ const previousChildren = displacedDocument && options.displacement !== "none" ? path.length === 0 ? displacedDocument.nodes : previousParent && ElementApi.isElement(previousParent) ? previousParent.children : null : null;
23946
24443
  let positionAfterJoins;
23947
24444
  const completion = {
23948
24445
  content: contentSpec,
@@ -23951,12 +24448,15 @@ const replaceCanonicalChildWindow = (draft, editor, schema, root, rootContent, p
23951
24448
  element: ElementApi.isElement(parent),
23952
24449
  preserveInlineSpacersAdjacentTo: options.preserveInlineSpacersAdjacentTo,
23953
24450
  schema: completionSchemaAt(schema, ancestors, root),
23954
- ...previousChildren ? { editing: { occupant: (slot, child) => {
23955
- if (nodes.length >= previousChildren.length || previousChildren.at(slot) === child || !holdsAfter(previousChildren, child, slot + 1)) return "kept";
23956
- if (!beforeDocument || !rootChange) return "displaced";
23957
- positionAfterJoins ??= positionsAfterJoins(previousChildren, path, beforeDocument, rootChange);
23958
- return positionAfterJoins(child) <= slot ? "joined" : "displaced";
23959
- } } } : {}
24451
+ ...previousChildren ? { editing: {
24452
+ occupant: (slot, child) => {
24453
+ if (nodes.length >= previousChildren.length || previousChildren.at(slot) === child || !holdsAfter(previousChildren, child, slot + 1)) return "kept";
24454
+ if (!displacedDocument || !displacedChange) return "displaced";
24455
+ positionAfterJoins ??= positionsAfterJoins(previousChildren, path, displacedDocument, displacedChange);
24456
+ return positionAfterJoins(child) <= slot ? "joined" : "displaced";
24457
+ },
24458
+ vacatedProperties: (slot) => vacatedBlockId(schema, previousChildren.at(slot), nodes)
24459
+ } } : {}
23960
24460
  };
23961
24461
  if (holdsContent({
23962
24462
  ...completion,
@@ -24052,6 +24552,11 @@ const constructCanonicalDocumentChange = (editor, after, change, options = {}) =
24052
24552
  };
24053
24553
  const rootChange = getInternalDocumentRootChange(change, root);
24054
24554
  const beforeDocument = options.before ? options.indexedBefore?.get(root) ?? valueRootIndex(options.before, root) : null;
24555
+ const since = options.sinceValidated;
24556
+ const displacedFrom = since && {
24557
+ change: getInternalDocumentRootChange(since.change, root),
24558
+ document: since.indexedBefore.get(root) ?? valueRootIndex(since.before, root)
24559
+ };
24055
24560
  const move = beforeDocument && rootChange ? rootChange.exactMove(beforeDocument) : null;
24056
24561
  const movedNode = move ? document.node(move.targetPath) : void 0;
24057
24562
  const moveParent = move?.path.slice(0, -1);
@@ -24117,7 +24622,8 @@ const constructCanonicalDocumentChange = (editor, after, change, options = {}) =
24117
24622
  carried: carriedFor(root),
24118
24623
  displacement: options.displacement,
24119
24624
  document: after,
24120
- preserveInlineSpacersAdjacentTo: protectedInlineSpacersFor(root)
24625
+ preserveInlineSpacersAdjacentTo: protectedInlineSpacersFor(root),
24626
+ displacedFrom
24121
24627
  });
24122
24628
  });
24123
24629
  const canonical = draftChange(draft);
@@ -25447,17 +25953,129 @@ const getTextEdge = (node, path, edge) => {
25447
25953
  const pointsEqual = (left, right) => left.offset === right.offset && left.path.length === right.path.length && left.path.every((part, index) => part === right.path[index]);
25448
25954
  //#endregion
25449
25955
  //#region src/core/slice-fit/compiled-slice-fitter.ts
25956
+ const trimsEverything = (trimmed, { from, insert, to }) => trimmed === insert.length && trimmed === to - from;
25450
25957
  const withoutUnchangedTail = (document, candidate) => {
25451
25958
  if (candidate.semanticChange || candidate.to === candidate.from) return candidate;
25452
- const limit = Math.min(candidate.to - candidate.from, candidate.insert.length);
25453
- const tail = commonSuffixLength(document.slice(candidate.to - limit, candidate.to).tokens, candidate.insert.tokens, limit);
25454
- const identical = tail === candidate.insert.length && tail === candidate.to - candidate.from;
25455
- return tail === 0 || identical ? candidate : Object.freeze({
25959
+ const { insert } = candidate;
25960
+ const replaced = document.slice(candidate.from, candidate.to);
25961
+ const common = commonSuffixLength(replaced.tokens, insert.tokens, Math.min(replaced.length, insert.length));
25962
+ if (common === 0) return candidate;
25963
+ const replacedStart = replaced.length - common;
25964
+ const insertStart = insert.length - common;
25965
+ const insertSplits = [];
25966
+ let seenElementClose = false;
25967
+ for (const [index, token] of insert.tokens.entries()) {
25968
+ if (insert.offsets[index] >= insertStart) break;
25969
+ if (token.kind === "open" && token.nodeKind === "element") insertSplits.push(seenElementClose);
25970
+ else if (token.kind === "close" && token.nodeKind === "element") {
25971
+ seenElementClose = true;
25972
+ insertSplits.pop();
25973
+ }
25974
+ }
25975
+ let cut = replacedStart;
25976
+ let docOpen = 0;
25977
+ let tailDepth = 0;
25978
+ for (const [index, token] of replaced.tokens.entries()) {
25979
+ const at = replaced.offsets[index];
25980
+ if (at < replacedStart) {
25981
+ if (token.kind === "open" && token.nodeKind === "element") docOpen += 1;
25982
+ else if (token.kind === "close" && token.nodeKind === "element" && docOpen > 0) docOpen -= 1;
25983
+ } else if (token.kind === "open" && token.nodeKind === "element") tailDepth += 1;
25984
+ else if (token.kind === "close" && token.nodeKind === "element") if (tailDepth > 0) tailDepth -= 1;
25985
+ else {
25986
+ const inReplaced = docOpen > 0;
25987
+ if (inReplaced) docOpen -= 1;
25988
+ if (insertSplits.pop() && inReplaced) cut = at + 1;
25989
+ }
25990
+ }
25991
+ const tail = replaced.length - cut;
25992
+ return tail === 0 || trimsEverything(tail, candidate) ? candidate : Object.freeze({
25456
25993
  ...candidate,
25457
- insert: candidate.insert.slice(0, candidate.insert.length - tail),
25994
+ insert: insert.slice(0, insert.length - tail),
25458
25995
  to: candidate.to - tail
25459
25996
  });
25460
25997
  };
25998
+ const keptCloseOffsets = (slice, kept) => {
25999
+ const closes = new Array(kept);
26000
+ const { offsets, tokens } = slice;
26001
+ let depth = kept;
26002
+ for (let index = kept; index < tokens.length && depth > 0; index += 1) {
26003
+ const { kind } = tokens[index];
26004
+ if (kind === "open") depth += 1;
26005
+ else if (kind === "close") {
26006
+ depth -= 1;
26007
+ if (depth < kept) closes[depth] ??= offsets[index];
26008
+ }
26009
+ }
26010
+ return closes;
26011
+ };
26012
+ const closesWhatItOpens = ({ tokens }) => {
26013
+ let depth = 0;
26014
+ for (const { kind } of tokens) if (kind === "open") depth += 1;
26015
+ else if (kind === "close") {
26016
+ depth -= 1;
26017
+ if (depth < 0) return false;
26018
+ }
26019
+ return depth === 0;
26020
+ };
26021
+ const splitAtKeptCloses = ({ from, insert, to }, replaced, kept) => {
26022
+ const replacedCloses = keptCloseOffsets(replaced, kept);
26023
+ const insertCloses = keptCloseOffsets(insert, kept);
26024
+ const changes = [];
26025
+ let replacedFrom = kept;
26026
+ let insertFrom = kept;
26027
+ const replace = (replacedTo, insertTo) => {
26028
+ if (replacedFrom === replacedTo && insertFrom === insertTo) return;
26029
+ changes.push(Object.freeze({
26030
+ from: from + replacedFrom,
26031
+ insert: insert.slice(insertFrom, insertTo),
26032
+ to: from + replacedTo
26033
+ }));
26034
+ };
26035
+ for (let level = kept - 1; level >= 0; level -= 1) {
26036
+ const replacedClose = replacedCloses[level];
26037
+ const insertClose = insertCloses[level];
26038
+ if (replacedClose === void 0 || insertClose === void 0) break;
26039
+ replace(replacedClose, insertClose);
26040
+ replacedFrom = replacedClose + 1;
26041
+ insertFrom = insertClose + 1;
26042
+ }
26043
+ if (!closesWhatItOpens(replaced.slice(replacedFrom, to - from)) || !closesWhatItOpens(insert.slice(insertFrom))) return [Object.freeze({
26044
+ from: from + kept,
26045
+ insert: insert.slice(kept),
26046
+ to
26047
+ })];
26048
+ replace(to - from, insert.length);
26049
+ return changes;
26050
+ };
26051
+ const keepRewrittenHead = (document, change) => {
26052
+ const { from, insert, to } = change;
26053
+ const unchanged = {
26054
+ changes: [change],
26055
+ properties: []
26056
+ };
26057
+ if (to === from || insert.length === 0) return unchanged;
26058
+ const replaced = document.slice(from, to);
26059
+ const ownKeys = getDocumentSliceNodeKeys(insert);
26060
+ const properties = [];
26061
+ let head = 0;
26062
+ for (const token of replaced.tokens) {
26063
+ const landed = insert.tokens[head];
26064
+ if (token.kind !== "open" || token.nodeKind !== "element" || landed?.kind !== "open" || landed.nodeKind !== "element" || token.props.type !== landed.props.type || ownKeys.has(head)) break;
26065
+ const modifications = semanticPropertyModifications(token.props, landed.props, () => false);
26066
+ if (modifications.length > 0) properties.push({
26067
+ from: from + head,
26068
+ properties: propertyDeltaFromModifications(modifications)
26069
+ });
26070
+ head += 1;
26071
+ }
26072
+ if (head === 0) return unchanged;
26073
+ const changes = splitAtKeptCloses(change, replaced, head);
26074
+ return changes.length === 0 ? unchanged : {
26075
+ changes,
26076
+ properties
26077
+ };
26078
+ };
25461
26079
  const lookAlikeChange = (document, candidate) => {
25462
26080
  const trimmed = withoutUnchangedTail(document, candidate);
25463
26081
  return RootChange.create(document, trimmed.semanticChange ?? {
@@ -26638,21 +27256,32 @@ const compileSliceFitter = (input) => {
26638
27256
  const firstSourceBlock = variant.content[0];
26639
27257
  if (!firstSourceBlock || !ElementApi.isElement(firstSourceBlock) || !rootCanContain(firstSourceBlock)) return null;
26640
27258
  const sourceBlocks = variant.content;
27259
+ const hasElementIds = getDeclarativeSchema()?.everyElementHasId === true;
27260
+ const targetProps = hasElementIds ? withoutStoredElementId(targetBlock) : targetBlock;
26641
27261
  const targetType = getElementType(targetBlock);
26642
- const targetElementKeys = Object.keys(targetBlock).filter((key) => key !== "children");
27262
+ const targetElementKeys = Object.keys(targetProps).filter((key) => key !== "children");
26643
27263
  const targetTextKeys = Object.keys(targetText).filter((key) => key !== "text");
26644
27264
  if (sourceBlocks.some((block) => {
26645
27265
  const text = ElementApi.isElement(block) ? block.children[0] : void 0;
26646
- return !NodeApi.isText(text) || getElementType(block) !== targetType || block.children.length !== 1 || !nodePropertiesEqual(block, targetBlock, "children", targetElementKeys) || !nodePropertiesEqual(text, targetText, "text", targetTextKeys);
27266
+ return !NodeApi.isText(text) || getElementType(block) !== targetType || block.children.length !== 1 || !nodePropertiesEqual(hasElementIds ? withoutStoredElementId(block) : block, targetProps, "children", targetElementKeys) || !nodePropertiesEqual(text, targetText, "text", targetTextKeys);
26647
27267
  })) return null;
26648
27268
  const tailProperties = getTailSplitProperties(targetBlock, targetPath);
26649
- if (tailProperties && !nodePropertiesEqual(targetBlock, tailProperties, "children", Object.keys(tailProperties))) return null;
27269
+ const tailProps = tailProperties && hasElementIds ? withoutStoredElementId(tailProperties) : tailProperties;
27270
+ if (tailProps && !nodePropertiesEqual(targetProps, tailProps, "children", Object.keys(tailProps))) return null;
26650
27271
  const prefix = targetText.text.slice(0, start.offset);
26651
27272
  const suffix = targetText.text.slice(end.offset);
26652
27273
  if (!isDetachedContentSlice(variant)) return null;
26653
- const fullInsert = encodeContentSliceContent(variant);
27274
+ const lastSourceBlock = sourceBlocks.at(-1);
27275
+ const tailWithoutId = hasElementIds && suffix.length > 0 && tailProperties !== null && sourceBlocks.length > 1 && lastSourceBlock ? withoutStoredElementId(lastSourceBlock) : null;
27276
+ const fittedBlocks = lastSourceBlock && tailWithoutId && tailWithoutId !== lastSourceBlock ? [...sourceBlocks.slice(0, -1), Object.freeze({
27277
+ ...tailWithoutId,
27278
+ children: lastSourceBlock.children,
27279
+ type: lastSourceBlock.type
27280
+ })] : sourceBlocks;
27281
+ const fittedVariant = fittedBlocks === sourceBlocks ? variant : ContentSlice.withContent(variant, fittedBlocks, { open: "preserve" });
27282
+ const fullInsert = encodeContentSliceContent(fittedVariant);
26654
27283
  if (!getPreparedDocumentSlice(fullInsert)) return null;
26655
- const openInsert = encodeContentSlice(variant);
27284
+ const openInsert = encodeContentSlice(fittedVariant);
26656
27285
  const semanticInsert = openInsert.slice(1, openInsert.length - 1);
26657
27286
  const targetRange = document.nodeRange(targetPath);
26658
27287
  return Object.freeze({
@@ -26662,7 +27291,7 @@ const compileSliceFitter = (input) => {
26662
27291
  fullInsert,
26663
27292
  prefix,
26664
27293
  semanticInsert,
26665
- sourceBlocks: Object.freeze(sourceBlocks),
27294
+ sourceBlocks: Object.freeze(fittedBlocks),
26666
27295
  suffix,
26667
27296
  targetPath: Object.freeze(targetPath)
26668
27297
  }),
@@ -27045,6 +27674,7 @@ const compileSliceFitter = (input) => {
27045
27674
  origins.add(content.from, "document", base.from);
27046
27675
  origins.add(content.to - content.from, "slice");
27047
27676
  origins.add(insert.length - content.to, "document", exactTo);
27677
+ const hasElementIds = getDeclarativeSchema()?.everyElementHasId === true;
27048
27678
  return Object.freeze({
27049
27679
  ...base,
27050
27680
  content,
@@ -27057,7 +27687,7 @@ const compileSliceFitter = (input) => {
27057
27687
  to: exactTo
27058
27688
  }),
27059
27689
  selectionOffset,
27060
- trustedCanonical: true
27690
+ ...hasElementIds ? {} : { trustedCanonical: true }
27061
27691
  });
27062
27692
  };
27063
27693
  const getStructuralContext = (position) => document.openContextAt(position).filter((entry) => entry.from < position && position < entry.to);
@@ -27385,17 +28015,24 @@ const compileSliceFitter = (input) => {
27385
28015
  }));
27386
28016
  if (!selectedCandidate) return false;
27387
28017
  const fittedCandidate = profileCoreDuration("slice-fit-candidate-materialize", () => materializeCandidate(withTailSplit(selectedCandidate)));
27388
- const sections = options.target.kind === "range" && !exactBounds && options.target.byLook !== "commit" ? fitSections(fittedCandidate) : null;
28018
+ const sections = options.target.kind === "range" && !exactBounds && options.target.byLook !== "commit" ? fitSections(fittedCandidate).flatMap((section) => {
28019
+ const { changes, properties } = keepRewrittenHead(document, section);
28020
+ return [...properties, ...changes];
28021
+ }) : null;
27389
28022
  const materializedCandidate = options.target.kind === "range" && !exactBounds && !sections ? withoutUnchangedTail(document, fittedCandidate) : fittedCandidate;
28023
+ const plain = options.target.kind === "range" && !exactBounds && !sections && !materializedCandidate.semanticChange ? keepRewrittenHead(document, materializedCandidate) : {
28024
+ changes: [materializedCandidate],
28025
+ properties: []
28026
+ };
27390
28027
  const candidate = materializedCandidate.preparation ? Object.freeze({
27391
28028
  ...materializedCandidate,
27392
- preparation: bindCanonicalFitPreparation(materializedCandidate.preparation, sections?.flatMap(({ insert }) => insert && insert.length > 0 ? [insert] : []) ?? [materializedCandidate.insert])
28029
+ preparation: bindCanonicalFitPreparation(materializedCandidate.preparation, sections?.flatMap(({ insert }) => insert && insert.length > 0 ? [insert] : []) ?? plain.changes.map(({ insert }) => insert))
27393
28030
  }) : materializedCandidate;
27394
- const canonicalRootChange = profileCoreDuration("slice-fit-changeset-build", () => options.target.kind === "root" && candidate.from === 0 && candidate.to === document.length ? reconcileChildrenStep(document, [], 0, document.value.length, inputSlice.content).change : RootChange.create(document, {
27395
- from: candidate.from,
27396
- insert: candidate.insert,
27397
- to: candidate.to
27398
- }));
28031
+ const canonicalRootChange = profileCoreDuration("slice-fit-changeset-build", () => options.target.kind === "root" && candidate.from === 0 && candidate.to === document.length ? reconcileChildrenStep(document, [], 0, document.value.length, inputSlice.content).change : RootChange.create(document, [...plain.properties, ...plain.changes.map(({ from, insert, to }) => ({
28032
+ from,
28033
+ insert,
28034
+ to
28035
+ }))]));
27399
28036
  const rootChange = sections ? RootChange.create(document, sections) : candidate.semanticChange ? RootChange.create(document, candidate.semanticChange) : canonicalRootChange;
27400
28037
  const stepFit = options.target.kind === "range" && options.target.byLook === "carry" ? Object.freeze({
27401
28038
  ...sections ? { lookAlike: lookAlikeChange(document, fittedCandidate) } : {},
@@ -27778,6 +28415,20 @@ const withoutGeneration = (read) => withMask("every", read);
27778
28415
  * @internal
27779
28416
  */
27780
28417
  const withoutGenerationOf = (properties, read) => properties.size === 0 ? read() : withMask(properties, read);
28418
+ let draws = null;
28419
+ /** @internal */
28420
+ const withPropertyDraws = (descriptor, draw, read) => {
28421
+ const outer = draws;
28422
+ draws = {
28423
+ descriptor,
28424
+ draw
28425
+ };
28426
+ try {
28427
+ return read();
28428
+ } finally {
28429
+ draws = outer;
28430
+ }
28431
+ };
27781
28432
  /**
27782
28433
  * A `MissingPropertyError` from a generator's own schema build, such as
27783
28434
  * `schema.create`, fails the outer build instead of refusing it.
@@ -27785,6 +28436,8 @@ const withoutGenerationOf = (properties, read) => properties.size === 0 ? read()
27785
28436
  const generatePropertyValue = (property, placement) => {
27786
28437
  if (masked === "every" ? placement === "element" : masked?.has(property)) throw new ElementGenerationMaskedError();
27787
28438
  if (masked === "every") throw new EditorSchemaValidationError("An export cannot generate a property value.");
28439
+ if (draws?.descriptor === property.descriptor) return draws.draw();
28440
+ countCoreWork("generatorDraws");
27788
28441
  try {
27789
28442
  return property.descriptor.generate?.();
27790
28443
  } catch (error) {
@@ -27880,6 +28533,7 @@ const toSchemaValidationLocation = (root, path, nodeType, ancestors = []) => {
27880
28533
  root: root === "main" ? null : root
27881
28534
  };
27882
28535
  };
28536
+ /** @internal */
27883
28537
  const canonicalizePropertyValue = (owner, descriptor, value) => {
27884
28538
  let canonical;
27885
28539
  if (descriptor.kind === "set") {
@@ -28469,7 +29123,7 @@ const createEditorSchema = (getEditor, getRegistry = () => getPluginRegistry$1(g
28469
29123
  removing: replace ? at.slice(-1) : [],
28470
29124
  root
28471
29125
  });
28472
- const createDeclarativeAndFill = (schema, type, properties, creating = /* @__PURE__ */ new Set(), options = {}) => {
29126
+ const createDeclarativeAndFill = (schema, type, properties, creating = /* @__PURE__ */ new Set(), options = {}, filled) => {
28473
29127
  const compiled = schema.elements.byType.get(type);
28474
29128
  if (!compiled) throw new Error(`Unknown editor element spec "${type}".`);
28475
29129
  if (creating.has(type)) throw new Error(`Recursive default content for editor element "${type}".`);
@@ -28515,7 +29169,8 @@ const createEditorSchema = (getEditor, getRegistry = () => getPluginRegistry$1(g
28515
29169
  ancestors: [element, ...options.ancestors ?? []],
28516
29170
  root: options.root
28517
29171
  };
28518
- if (compiled.content) children.push(...completeContent({
29172
+ if (filled) children.push(...filled);
29173
+ else if (compiled.content) children.push(...completeContent({
28519
29174
  children: [],
28520
29175
  content: compiled.content,
28521
29176
  element: true,
@@ -28541,7 +29196,7 @@ const createEditorSchema = (getEditor, getRegistry = () => getPluginRegistry$1(g
28541
29196
  const createAt = (type, properties, site) => {
28542
29197
  const declarative = getDeclarativeSchema();
28543
29198
  if (!declarative) throw new Error(`Unknown editor element type "${type}".`);
28544
- return createDeclarativeAndFill(declarative, type, properties, /* @__PURE__ */ new Set(), site);
29199
+ return createDeclarativeAndFill(declarative, type, properties, /* @__PURE__ */ new Set(), site, site.children);
28545
29200
  };
28546
29201
  const defaultSlotIn = (content, index, site) => {
28547
29202
  const schema = getDeclarativeSchema();
@@ -30154,6 +30809,8 @@ const DOCUMENT_SETTLED_TAG = "document-settled";
30154
30809
  /** @internal */
30155
30810
  const documentAdmissionPoint = definePluginPoint("document.admission");
30156
30811
  /** @internal */
30812
+ const editorDocumentAdmission = (editor) => onlyDocumentAdmission(getPluginContributions(editor, documentAdmissionPoint));
30813
+ /** @internal */
30157
30814
  const onlyDocumentAdmission = (contributions) => {
30158
30815
  if (contributions.length > 1) throw new Error("An editor accepts one document admission.");
30159
30816
  return contributions[0] ?? null;
@@ -30182,8 +30839,9 @@ const admissionBound = (what) => {
30182
30839
  };
30183
30840
  };
30184
30841
  /** @internal */
30185
- const repairLoadedDocument = (admission, document, schema) => {
30842
+ const repairLoadedDocument = (admission, document, schema, ids = null) => {
30186
30843
  const writers = [
30844
+ ...ids ? [ids.fill] : [],
30187
30845
  (value) => admission?.load(value, schema) ?? null,
30188
30846
  (value) => repairLoadedUniqueValues(value, schema),
30189
30847
  (value) => {
@@ -30198,7 +30856,8 @@ const repairLoadedDocument = (admission, document, schema) => {
30198
30856
  let repaired = null;
30199
30857
  for (let at = 0, quiet = 0; quiet < writers.length; at += 1) {
30200
30858
  const value = repaired?.value ?? document;
30201
- const next = getDefined(writers[at % writers.length])(value);
30859
+ const writer = getDefined(writers[at % writers.length]);
30860
+ const next = ids ? ids.withStandInIds(() => writer(value)) : writer(value);
30202
30861
  quiet += 1;
30203
30862
  if (!next) continue;
30204
30863
  write();
@@ -30212,8 +30871,8 @@ const repairLoadedDocument = (admission, document, schema) => {
30212
30871
  return repaired;
30213
30872
  };
30214
30873
  /** @internal */
30215
- const admitDocument = (admission, document, schema) => {
30216
- const repaired = repairLoadedDocument(admission, document, schema);
30874
+ const admitDocument = (admission, document, schema, ids = null) => {
30875
+ const repaired = repairLoadedDocument(admission, document, schema, ids);
30217
30876
  if (!repaired) return {
30218
30877
  change: DocumentChange.empty,
30219
30878
  document
@@ -30225,7 +30884,7 @@ const admitDocument = (admission, document, schema) => {
30225
30884
  };
30226
30885
  };
30227
30886
  /** @internal */
30228
- const admitEditorDocument = (editor, document) => admitDocument(onlyDocumentAdmission(getPluginContributions(editor, documentAdmissionPoint)), document, getCompiledEditorSchema(editor));
30887
+ const admitEditorDocument = (editor, document, ids = null) => admitDocument(editorDocumentAdmission(editor), document, getCompiledEditorSchema(editor), ids);
30229
30888
  //#endregion
30230
30889
  //#region src/core/tx-only.ts
30231
30890
  const getRuntimeRegistry = (name, create) => {
@@ -30253,11 +30912,13 @@ const TX_LOCATES = getRuntimeRegistry("tx-locates", () => /* @__PURE__ */ new We
30253
30912
  * Declare where a plugin update method's arguments land. The method runs in
30254
30913
  * the root of the targets `locate` places. While a command document is
30255
30914
  * registered, `locate` also maps them into the document editing commands
30256
- * decide on, or returns null when they have no place there, so the method
30257
- * does nothing. `false` says the arguments hold no location. A call that
30258
- * passes a function runs in the caller's root, and `locate` only places its
30259
- * arguments, so an id that names no element still does nothing. A method
30260
- * called with arguments that has no declaration throws.
30915
+ * decide on, or returns null when they have no place there. A node key or
30916
+ * live node that no root holds has no place either. Either way the method
30917
+ * does nothing and the call returns undefined. `false` says the arguments
30918
+ * hold no location. A call that passes a function runs in the caller's root,
30919
+ * and `locate` only places its arguments, so an id or key that names no
30920
+ * element still does nothing. A method called with arguments that has no
30921
+ * declaration throws.
30261
30922
  */
30262
30923
  const txLocate = (locate, method) => {
30263
30924
  TX_LOCATES.set(method, locate);
@@ -30361,14 +31022,13 @@ const dispatchPluginUpdate = (caller, transaction, group, path, method, thisArg,
30361
31022
  let located = args;
30362
31023
  const inheritedRoot = context.pluginRoot;
30363
31024
  const locateCall = (framePlace) => {
30364
- const calledInFrame = !framePlace && COMMAND_FRAMES.has(editor);
30365
31025
  let targetRoot;
30366
31026
  if (typeof locate === "function") located = locate(args, { location: ((at) => {
30367
31027
  const id = elementIdOf(at);
30368
31028
  const holder = id === void 0 ? void 0 : framePlace ? placeElementIdIn(framePlace, id) : lookupElementId(editor, id);
30369
31029
  if (holder === null) return null;
30370
31030
  const keyRoot = holder ? holder.root : getNodeTargetRoot(editor, at);
30371
- if (calledInFrame && keyRoot === void 0 && (typeof at === "string" || NodeApi.isDescendant(at))) return null;
31031
+ if (!framePlace && keyRoot === void 0 && (typeof at === "string" || NodeApi.isDescendant(at))) return null;
30372
31032
  const root = keyRoot ?? (SelectionApi.isNode(at) || RangeApi.isRange(at) ? SelectionApi.root(at) : PointApi.isPoint(at) ? at.root : void 0) ?? ownRoot;
30373
31033
  if (!callback) {
30374
31034
  if (targetRoot !== void 0 && targetRoot !== root) throw new Error(`Plugin method "${name}" targets two roots.`);
@@ -30723,6 +31383,239 @@ const createEditorUpdateApi = (runUpdate, apiOptions) => {
30723
31383
  return defaultFacade;
30724
31384
  };
30725
31385
  //#endregion
31386
+ //#region src/core/element-id.ts
31387
+ const visitRootElements = (document, visit) => {
31388
+ for (const root of documentRootsOf(document)) visitElements(rootChildrenOf$1(document, root), (node, path) => visit(node, root, path));
31389
+ };
31390
+ const withIdAt = (node, path, id) => {
31391
+ const [at, ...rest] = path;
31392
+ if (at === void 0 || !isElementNode(node)) return {
31393
+ ...node,
31394
+ id
31395
+ };
31396
+ const children = [...node.children];
31397
+ children[at] = withIdAt(getDefined(children[at]), rest, id);
31398
+ return {
31399
+ ...node,
31400
+ children
31401
+ };
31402
+ };
31403
+ const loadElementIds = (schema, incoming, admission) => {
31404
+ if (!schema.everyElementHasId) return null;
31405
+ const { descriptor } = getDefined(uniquePropertiesOf(schema).get("id"));
31406
+ const reserved = /* @__PURE__ */ new Set();
31407
+ const standIns = /* @__PURE__ */ new Set();
31408
+ const sparesOf = (document) => admission?.spareLines?.(document, schema) ?? null;
31409
+ let next = 0;
31410
+ const idAt = (node, root, path) => ({
31411
+ nodeType: typeof node.type === "string" ? node.type : void 0,
31412
+ path,
31413
+ root: root === "main" ? null : root
31414
+ });
31415
+ const reserve = (node, root, path) => {
31416
+ if (!isElementNode(node) || node.id === void 0) return;
31417
+ assertValidElementId(node.id, idAt(node, root, path));
31418
+ reserved.add(node.id);
31419
+ };
31420
+ const drawStandIn = () => {
31421
+ let standIn = `\u0000${standIns.size}`;
31422
+ while (reserved.has(standIn)) standIn += "\0";
31423
+ standIns.add(standIn);
31424
+ return standIn;
31425
+ };
31426
+ visitRootElements(incoming, reserve);
31427
+ for (const { node } of sparesOf(incoming)?.lines ?? []) visitElements([node], (element, path) => reserve(element, null, path));
31428
+ return {
31429
+ fill: (document) => {
31430
+ const held = /* @__PURE__ */ new Set();
31431
+ const lacks = (node, countsAsHolder, root, path) => {
31432
+ if (!isElementNode(node)) return false;
31433
+ const { id } = node;
31434
+ if (id === void 0) return true;
31435
+ assertValidElementId(id, idAt(node, root, path));
31436
+ if (!standIns.has(id) && !(countsAsHolder && held.has(id))) {
31437
+ if (countsAsHolder) held.add(id);
31438
+ reserved.add(id);
31439
+ return false;
31440
+ }
31441
+ return true;
31442
+ };
31443
+ const fillId = () => {
31444
+ while (reserved.has(`fill.${next}`)) next += 1;
31445
+ const value = `fill.${next}`;
31446
+ reserved.add(value);
31447
+ return value;
31448
+ };
31449
+ const lacking = [];
31450
+ const spares = sparesOf(document);
31451
+ const hidden = [];
31452
+ visitRootElements(document, (node, root, path) => {
31453
+ if (lacks(node, true, root, path)) lacking.push({
31454
+ path,
31455
+ root
31456
+ });
31457
+ });
31458
+ spares?.lines.forEach(({ built, node }, line) => visitElements([node], (element, path) => {
31459
+ if (lacks(element, !built, null, path)) hidden.push({
31460
+ line,
31461
+ path
31462
+ });
31463
+ }));
31464
+ const renames = lacking.map((place) => ({
31465
+ ...place,
31466
+ value: fillId()
31467
+ }));
31468
+ const lines = spares?.lines.map(({ node }) => node) ?? [];
31469
+ for (const { line, path } of hidden) lines[line] = withIdAt(getDefined(lines[line]), path.slice(1), fillId());
31470
+ let repaired = hidden.length > 0 ? getDefined(spares).write(lines) : null;
31471
+ if (renames.length > 0) {
31472
+ const spared = repaired?.value ?? document;
31473
+ const indexOf = (root) => valueRootIndex(spared, root);
31474
+ const change = renameChange(renames.map(({ path, root, value }) => ({
31475
+ from: indexOf(root).nodeRange(path).from,
31476
+ key: "id",
31477
+ root,
31478
+ value
31479
+ })), indexOf);
31480
+ repaired = {
31481
+ change: repaired ? repaired.change.compose(change) : change,
31482
+ value: change.apply(spared)
31483
+ };
31484
+ }
31485
+ return repaired;
31486
+ },
31487
+ withStandInIds: (read) => withPropertyDraws(descriptor, drawStandIn, read)
31488
+ };
31489
+ };
31490
+ const firstAtOrAfter = (sorted, floor) => {
31491
+ let low = 0;
31492
+ let high = sorted.length;
31493
+ while (low < high) {
31494
+ const middle = low + high >>> 1;
31495
+ if (sorted[middle] < floor) low = middle + 1;
31496
+ else high = middle;
31497
+ }
31498
+ return sorted[low];
31499
+ };
31500
+ const longestRising = (pairs) => {
31501
+ const tails = [];
31502
+ const previous = [];
31503
+ pairs.forEach(([old], at) => {
31504
+ let low = 0;
31505
+ let high = tails.length;
31506
+ while (low < high) {
31507
+ const middle = low + high >>> 1;
31508
+ if (pairs[tails[middle]][0] < old) low = middle + 1;
31509
+ else high = middle;
31510
+ }
31511
+ previous[at] = low > 0 ? tails[low - 1] : -1;
31512
+ tails[low] = at;
31513
+ });
31514
+ const rising = [];
31515
+ for (let at = tails.at(-1) ?? -1; at >= 0; at = previous[at]) rising.push(pairs[at]);
31516
+ return rising.reverse();
31517
+ };
31518
+ const keepElementIds = (editor, lists) => {
31519
+ if (!getCompiledEditorSchema(editor).everyElementHasId) return lists.map(([, incoming]) => incoming);
31520
+ const reserved = /* @__PURE__ */ new Set();
31521
+ const reserve = (node) => {
31522
+ const id = storedElementIdOf(node);
31523
+ if (id !== void 0) reserved.add(id);
31524
+ if (isElementNode(node)) node.children.forEach(reserve);
31525
+ };
31526
+ for (const [, incoming] of lists) incoming.forEach(reserve);
31527
+ const keys = /* @__PURE__ */ new WeakMap();
31528
+ const contentOf = (node) => {
31529
+ let key = keys.get(node);
31530
+ if (key === void 0) {
31531
+ countCoreWork("pairingContentKeys");
31532
+ key = isElementNode(node) ? `${canonicalRecordJson(Object.fromEntries(Object.entries(node).filter(([name]) => name !== "id" && name !== "children")))}[${node.children.map(contentOf).join(",")}]` : canonicalRecordJson(node);
31533
+ keys.set(node, key);
31534
+ }
31535
+ return key;
31536
+ };
31537
+ const pairEqualContent = (old, incoming) => {
31538
+ const oldAt = /* @__PURE__ */ new Map();
31539
+ const incomingCount = /* @__PURE__ */ new Map();
31540
+ const unpaired = incoming.flatMap((node, at) => storedElementIdOf(node) === void 0 ? [at] : []);
31541
+ if (unpaired.length === 0) return [];
31542
+ old.forEach((node, at) => {
31543
+ const key = contentOf(node);
31544
+ const list = oldAt.get(key);
31545
+ if (list) list.push(at);
31546
+ else oldAt.set(key, [at]);
31547
+ });
31548
+ for (const at of unpaired) {
31549
+ const key = contentOf(incoming[at]);
31550
+ incomingCount.set(key, (incomingCount.get(key) ?? 0) + 1);
31551
+ }
31552
+ const anchors = longestRising(unpaired.flatMap((at) => {
31553
+ const key = contentOf(incoming[at]);
31554
+ const olds = oldAt.get(key);
31555
+ return olds?.length === 1 && incomingCount.get(key) === 1 ? [[olds[0], at]] : [];
31556
+ }));
31557
+ const pairs = [];
31558
+ let oldFloor = 0;
31559
+ let next = 0;
31560
+ for (const [anchorOld, anchorIncoming] of [...anchors, [old.length, incoming.length]]) {
31561
+ for (; next < unpaired.length && unpaired[next] < anchorIncoming; next++) {
31562
+ const at = unpaired[next];
31563
+ const match = firstAtOrAfter(oldAt.get(contentOf(incoming[at])) ?? [], oldFloor);
31564
+ if (match !== void 0 && match < anchorOld) {
31565
+ pairs.push([match, at]);
31566
+ oldFloor = match + 1;
31567
+ }
31568
+ }
31569
+ if (anchorOld < old.length) {
31570
+ pairs.push([anchorOld, anchorIncoming]);
31571
+ oldFloor = anchorOld + 1;
31572
+ next += 1;
31573
+ }
31574
+ }
31575
+ return pairs;
31576
+ };
31577
+ const keepListIds = (old, incoming) => {
31578
+ const partner = /* @__PURE__ */ new Map();
31579
+ let oldFrom = 0;
31580
+ let incomingFrom = 0;
31581
+ for (const [oldTo, incomingTo] of [...pairEqualContent(old, incoming), [old.length, incoming.length]]) {
31582
+ const olds = [];
31583
+ const incomings = [];
31584
+ for (let at = oldFrom; at < oldTo; at++) {
31585
+ const id = storedElementIdOf(old[at]);
31586
+ if (isElementNode(old[at]) && (id === void 0 || !reserved.has(id))) olds.push(at);
31587
+ }
31588
+ for (let at = incomingFrom; at < incomingTo; at++) {
31589
+ const node = incoming[at];
31590
+ if (isElementNode(node) && storedElementIdOf(node) === void 0) incomings.push(at);
31591
+ }
31592
+ for (let at = 0; at < Math.min(olds.length, incomings.length); at++) partner.set(incomings[at], olds[at]);
31593
+ if (oldTo < old.length) partner.set(incomingTo, oldTo);
31594
+ oldFrom = oldTo + 1;
31595
+ incomingFrom = incomingTo + 1;
31596
+ }
31597
+ let changed = false;
31598
+ const paired = [...incoming];
31599
+ for (const [at, oldAt] of partner) {
31600
+ const node = incoming[at];
31601
+ const before = old[oldAt];
31602
+ if (!isElementNode(node) || !isElementNode(before)) continue;
31603
+ const children = keepListIds(before.children, node.children);
31604
+ const id = storedElementIdOf(before);
31605
+ const keep = id !== void 0 && !reserved.has(id);
31606
+ if (!keep && children === node.children) continue;
31607
+ changed = true;
31608
+ paired[at] = {
31609
+ ...node,
31610
+ ...keep ? { id } : {},
31611
+ children
31612
+ };
31613
+ }
31614
+ return changed ? paired : incoming;
31615
+ };
31616
+ return lists.map(([old, incoming]) => keepListIds(old, incoming));
31617
+ };
31618
+ //#endregion
30726
31619
  //#region src/core/listener-state.ts
30727
31620
  const LISTENERS = /* @__PURE__ */ new WeakMap();
30728
31621
  const COMMIT_LISTENERS = /* @__PURE__ */ new WeakMap();
@@ -31010,6 +31903,11 @@ const withViewSnapshot = (snapshot, viewState, selectionRoot) => {
31010
31903
  };
31011
31904
  const withRootChildren = (editor, state, viewState) => {
31012
31905
  const namesItsRoot = (entry) => viewState.root === "main" || entry?.root !== void 0 ? entry : null;
31906
+ const getWithIdInOwnRoot = ((target, options) => {
31907
+ if (elementIdOf(target) === void 0) return state.nodes.get(target, options);
31908
+ const path = state.nodes.path(target);
31909
+ return path && state.nodes.get(path, options);
31910
+ });
31013
31911
  return withElementFinder({
31014
31912
  ...state.nodes,
31015
31913
  above: rootMethod(editor, viewState, state.nodes.above),
@@ -31021,7 +31919,7 @@ const withRootChildren = (editor, state, viewState) => {
31021
31919
  entries: rootGeneratorMethod(editor, viewState, state.nodes.entries),
31022
31920
  find: rootMethod(editor, viewState, state.nodes.find),
31023
31921
  first: rootMethod(editor, viewState, state.nodes.first),
31024
- get: rootMethod(editor, viewState, state.nodes.get),
31922
+ get: rootMethod(editor, viewState, getWithIdInOwnRoot),
31025
31923
  last: rootMethod(editor, viewState, state.nodes.last),
31026
31924
  leaf: rootMethod(editor, viewState, state.nodes.leaf),
31027
31925
  levels: rootGeneratorMethod(editor, viewState, state.nodes.levels),
@@ -31485,7 +32383,8 @@ const createEditorViewRuntime = (sourceEditor, options = {}, presentation, polic
31485
32383
  const runtimeEditor = getEditorRuntimeOwner(sourceEditor);
31486
32384
  const sourceRuntime = viewRuntimeOf(sourceEditor);
31487
32385
  const sourceView = sourceRuntime && VIEW_STATES.get(sourceRuntime);
31488
- const document = options.document ? admitEditorDocument(getEditorRuntimeOwner(sourceEditor), readViewDocument(sourceEditor, options.document)).document : sourceView?.document;
32386
+ const viewInput = options.document && readViewDocument(sourceEditor, options.document);
32387
+ const document = viewInput ? admitEditorDocument(getEditorRuntimeOwner(sourceEditor), viewInput, loadElementIds(getCompiledEditorSchema(sourceEditor), viewInput, editorDocumentAdmission(getEditorRuntimeOwner(sourceEditor)))).document : sourceView?.document;
31489
32388
  if (document) {
31490
32389
  if (options.authored) throw new Error("A document view cannot take an authored projection.");
31491
32390
  assertViewDocument(sourceEditor, document);
@@ -32714,7 +33613,7 @@ const writeLanding = (editor, document) => {
32714
33613
  const survives = contentSurvival(editor);
32715
33614
  const schema = getEditorSchema(editor);
32716
33615
  const writable = (element) => survives(element) && !schema.isVoid(element) && !schema.isReadOnly(element);
32717
- return (point) => nearestFrom(document, point, "backward", survives, writable) ?? nearestFrom(document, point, "forward", survives, writable);
33616
+ return (point) => highestGone(document, point, survives) === null || holdsEditorWrite(editor, point, document) ? point : nearestFrom(document, point, "backward", survives, writable) ?? nearestFrom(document, point, "forward", survives, writable);
32718
33617
  };
32719
33618
  /**
32720
33619
  * The outermost table, row or cell whose deletion is pending around `path`,
@@ -33489,7 +34388,8 @@ const getNextCharacterPoint = (editor, point) => {
33489
34388
  path: [...point.path],
33490
34389
  offset: point.offset + getCharacterDistance(text.text.slice(point.offset))
33491
34390
  };
33492
- return getNextTextStartPoint(editor, point.path);
34391
+ const next = getNextTextStartPoint(editor, point.path);
34392
+ return next && PathApi.isSibling(next.path, point.path) ? getNextCharacterPoint(editor, next) : next;
33493
34393
  };
33494
34394
  const getPreviousCharacterPoint = (editor, point) => {
33495
34395
  const text = getLiveText(editor, point.path);
@@ -33497,7 +34397,8 @@ const getPreviousCharacterPoint = (editor, point) => {
33497
34397
  path: [...point.path],
33498
34398
  offset: point.offset - getCharacterDistance(text.text.slice(0, point.offset), true)
33499
34399
  };
33500
- return getPreviousTextEndPoint(editor, point.path);
34400
+ const previous = getPreviousTextEndPoint(editor, point.path);
34401
+ return previous && PathApi.isSibling(previous.path, point.path) ? getPreviousCharacterPoint(editor, previous) : previous;
33501
34402
  };
33502
34403
  const getAdjacentCharacterPoint = (editor, point$12, { direction, distance, reach, voids }) => {
33503
34404
  let current = point$12;
@@ -34347,10 +35248,12 @@ const findNewNodes = (owner, children, at, index) => {
34347
35248
  children.forEach((child, offset) => collect(child, [...at, index + offset]));
34348
35249
  return found;
34349
35250
  };
34350
- const replaceChildren$1 = (editor, children, { at, count, index = 0, newSelection, preserveKeys = false }) => {
35251
+ const replaceChildren$1 = (editor, replacements, { at, count, index = 0, newSelection, preserveKeys = false }) => {
34351
35252
  const parentChildren = getParentChildren(editor, at);
34352
35253
  const replacementCount = count ?? parentChildren.length - index;
34353
35254
  const replacedChildren = parentChildren.slice(index, index + replacementCount);
35255
+ const owner = getEditorRuntimeOwner(editor);
35256
+ const [children] = keepElementIds(owner, [[replacedChildren, replacements]]);
34354
35257
  const updateRoot = getEditorUpdateRoot(editor);
34355
35258
  const liveSelection = getLiveSelection(editor);
34356
35259
  const selection = liveSelection && (SelectionApi.root(liveSelection) ?? getCurrentSelectionRoot(editor)) === updateRoot ? liveSelection : null;
@@ -34405,7 +35308,7 @@ const replaceChildren$1 = (editor, children, { at, count, index = 0, newSelectio
34405
35308
  };
34406
35309
  })() : void 0;
34407
35310
  const selectionAfter = newSelection === void 0 ? retainedSelection : newSelection;
34408
- const storedCopies = findNewNodes(getEditorRuntimeOwner(editor), children, at, index);
35311
+ const storedCopies = findNewNodes(owner, children, at, index);
34409
35312
  const apply = () => applyBuiltDocumentChange(editor, (builder, root) => builder.replaceChildren(root, at, index, replacedChildren.length, [...children]), {
34410
35313
  nodeKeyTransfers: preserveKeys ? children.slice(0, replacedChildren.length).map((_child, childIndex) => ({
34411
35314
  path: [...at, index + childIndex],
@@ -37425,6 +38328,7 @@ const applyDeleteFragment = (editor, { at, direction = "forward" } = {}) => {
37425
38328
  }
37426
38329
  if (selection && RangeApi.isRange(selection) && RangeApi.isExpanded(selection)) {
37427
38330
  refuseCrossing(getSetSite(editor), selection, getLocationRoot(selection) ?? getEditorUpdateRoot(editor));
38331
+ if (hasEdgeInReadOnlyInline(editor, selection)) return;
37428
38332
  tx.setSelection(SelectionApi.text(selection));
37429
38333
  deleteText(editor, {
37430
38334
  at: selection,
@@ -37532,6 +38436,213 @@ const exitBreak = (editor, { before = false, match } = {}) => {
37532
38436
  return insertDefaultChild(editor, landingAt(blockPath));
37533
38437
  };
37534
38438
  //#endregion
38439
+ //#region src/core/mixed-lines.ts
38440
+ const textLineRefusal = definePluginPoint("text-line.refusal");
38441
+ const remainderOf = (content) => content?.prefix ? content.remainder ?? null : content;
38442
+ const textLineAt = (editor, root, point) => {
38443
+ if (getPluginContributions(getEditorRuntimeOwner(editor), textLineRefusal).length > 0 || isPluginReconfigurationStagedInUpdate(editor)) return null;
38444
+ const schema = getEditorSchema(editor);
38445
+ const ancestors = [];
38446
+ let siblings = getChildList(editor);
38447
+ for (const index of point.path.slice(0, -1)) {
38448
+ const node = childAtPathIndex(siblings, index);
38449
+ if (!node?.children) return null;
38450
+ ancestors.unshift(node);
38451
+ siblings = node.children;
38452
+ }
38453
+ const depth = ancestors.findIndex((element) => !schema.isInline(element));
38454
+ const container = ancestors[depth];
38455
+ const content = container ? schema.getElementContent(container.type) : null;
38456
+ const program = remainderOf(content);
38457
+ if (!container || !program || contentKindOf(program, schema) !== "mixed") return null;
38458
+ if (ancestors.some((element) => schema.isIsolating(element) || schema.isReadOnly(element))) return null;
38459
+ const chain = ancestors.slice(depth);
38460
+ const path = point.path.slice(0, point.path.length - 1 - depth);
38461
+ const { children } = container;
38462
+ const isBlock = (index) => {
38463
+ const child = children[index];
38464
+ return NodeApi.isElement(child) && !schema.isInline(child);
38465
+ };
38466
+ let from = point.path[path.length] ?? 0;
38467
+ let to = from + 1;
38468
+ while (from > 0 && !isBlock(from - 1)) from -= 1;
38469
+ while (to < children.length && !isBlock(to)) to += 1;
38470
+ if (from === 0 && to === children.length) return null;
38471
+ return {
38472
+ chain,
38473
+ from,
38474
+ path,
38475
+ root,
38476
+ to
38477
+ };
38478
+ };
38479
+ const siteOf = (types, root) => ({
38480
+ ancestors: types.slice(1),
38481
+ root: root === "main" ? null : root,
38482
+ type: types[0] ?? ""
38483
+ });
38484
+ const declaredAt = (compiled, placement, site) => [...(placement === "element" ? compiled.properties.elementAllowedByType : compiled.properties.textAllowedByParentType).get(site.type) ?? []].flatMap((id) => {
38485
+ const property = compiled.properties.byId.get(id);
38486
+ return property && typeof property.key === "string" && matchesCompiledSchemaTarget(compiled, property.target, site) ? [property] : [];
38487
+ });
38488
+ const keepsDeclarations = (compiled) => {
38489
+ const effective = /* @__PURE__ */ new Map();
38490
+ const effectiveKeys = (placement, site) => {
38491
+ const id = JSON.stringify([
38492
+ placement,
38493
+ site.type,
38494
+ site.ancestors
38495
+ ]);
38496
+ let keys = effective.get(id);
38497
+ if (!keys) {
38498
+ keys = declaredAt(compiled, placement, site).flatMap(({ descriptor, key }) => descriptor.required || descriptor.generate || Object.hasOwn(descriptor, "default") ? [key] : []);
38499
+ effective.set(id, keys);
38500
+ }
38501
+ return keys;
38502
+ };
38503
+ return (placement, node, from, to) => [
38504
+ ...Object.keys(node),
38505
+ ...effectiveKeys(placement, from),
38506
+ ...effectiveKeys(placement, to)
38507
+ ].every((key) => key === "children" || key === "text" || key === "type" || resolveCompiledSchemaProperty(compiled, placement, key, from) === resolveCompiledSchemaProperty(compiled, placement, key, to));
38508
+ };
38509
+ const admitLineBlock = (editor, line, { at, end, marks }) => {
38510
+ const schema = getEditorSchema(editor);
38511
+ const compiled = getCompiledEditorSchemaFromApi(schema);
38512
+ const [container] = line.chain;
38513
+ const content = container && schema.getElementContent(container.type);
38514
+ const inLine = (point) => {
38515
+ const index = point.path[line.path.length] ?? -1;
38516
+ return point.path.length > line.path.length && line.path.every((step, depth) => point.path[depth] === step) && index >= line.from && index < line.to;
38517
+ };
38518
+ if (!compiled || !container || !content || !inLine(end)) return null;
38519
+ const { root } = line;
38520
+ const outer = line.chain.map((element) => element.type);
38521
+ const below = at.path.slice(line.path.length);
38522
+ const inlines = [];
38523
+ let caret = container;
38524
+ for (const [depth, index] of below.entries()) {
38525
+ if (!NodeApi.isElement(caret)) return null;
38526
+ caret = caret.children[index];
38527
+ if (NodeApi.isElement(caret)) {
38528
+ const own = schema.getElementContent(caret.type);
38529
+ if (!isStart(editor, at, [...line.path, ...below.slice(0, depth + 1)]) && own && own.min > 1) return null;
38530
+ inlines.unshift(caret);
38531
+ }
38532
+ }
38533
+ if (!NodeApi.isText(caret)) return null;
38534
+ const past = PointApi.equals(at, end) && caret.text[at.offset] === "\n" ? {
38535
+ ...at,
38536
+ offset: at.offset + 1
38537
+ } : end;
38538
+ const restIsEmpty = (inline, index) => {
38539
+ const path = [...line.path, ...below.slice(0, below.length - 1 - index)];
38540
+ return [...NodeApi.texts(inline)].every(([text, inner]) => {
38541
+ const order = PathApi.compare([...path, ...inner], past.path);
38542
+ return order < 0 || (order === 0 ? text.text.slice(past.offset) : text.text) === "";
38543
+ });
38544
+ };
38545
+ const kept = inlines.findIndex((inline, index) => !restIsEmpty(inline, index));
38546
+ const exits = kept === -1 ? inlines.length : kept;
38547
+ const caretTypes = inlines.map((inline) => inline.type);
38548
+ const keeps = keepsDeclarations(compiled);
38549
+ const lineNodes = container.children.slice(line.from, line.to);
38550
+ const caretSite = siteOf([...caretTypes, ...outer], root);
38551
+ const collapsed = PointApi.equals(at, end);
38552
+ const nextLetterMarks = collapsed ? Object.keys(marks ?? {}).map((key) => [key, caretSite]) : [];
38553
+ const readLetters = (node, path, types) => {
38554
+ if (!NodeApi.isText(node)) node.children.forEach((child, index) => {
38555
+ readLetters(child, [...path, index], [node.type, ...types]);
38556
+ });
38557
+ else if (PathApi.compare(path, at.path) >= 0 && PathApi.compare(path, end.path) <= 0) {
38558
+ for (const key of Object.keys(node)) if (key !== "text") nextLetterMarks.push([key, siteOf(types, root)]);
38559
+ }
38560
+ };
38561
+ if (!collapsed) {
38562
+ const last = end.path[line.path.length] ?? -1;
38563
+ for (let index = below[0] ?? line.to; index <= last; index += 1) readLetters(container.children[index], [...line.path, index], outer);
38564
+ }
38565
+ const removing = lineNodes.map((_, offset) => line.from + offset);
38566
+ const keepsDescendants = (nodes, before, after) => nodes.every((node) => {
38567
+ if (NodeApi.isText(node)) return keeps("text", node, siteOf(before, root), siteOf(after, root));
38568
+ const own = [node.type, ...before];
38569
+ const moved = [node.type, ...after];
38570
+ return keeps("element", node, siteOf(own, root), siteOf(moved, root)) && keepsDescendants(node.children, own, moved);
38571
+ });
38572
+ const needsNothing = ({ properties = {}, type }) => {
38573
+ const site = siteOf([type, ...outer], root);
38574
+ return declaredAt(compiled, "element", site).every(({ descriptor, key, lifecycle }) => descriptor.generate ? lifecycle.split === "drop" : !descriptor.required || Object.hasOwn(properties, key) && lifecycle.split === "preserve") && declaredAt(compiled, "text", site).every(({ descriptor }) => !descriptor.required);
38575
+ };
38576
+ const ownPropertiesHold = ({ properties = {}, type }) => {
38577
+ const site = siteOf([type, ...outer], root);
38578
+ return Object.entries(properties).every(([key, value]) => {
38579
+ const property = resolveCompiledSchemaProperty(compiled, "element", key, site);
38580
+ if (!property) return compiled.unknown === "preserve" && getCompiledPropertyCandidates(compiled, "element", key).length === 0;
38581
+ try {
38582
+ canonicalizePropertyValue(key, property.descriptor, value);
38583
+ return true;
38584
+ } catch (error) {
38585
+ if (error instanceof EditorSchemaValidationError) return false;
38586
+ throw error;
38587
+ }
38588
+ });
38589
+ };
38590
+ const marksHoldAtEveryExit = (block, compareWith) => Array.from({ length: exits + 1 }, (_, exited) => caretTypes.slice(exited)).every((around) => nextLetterMarks.every(([key, from]) => resolveCompiledSchemaProperty(compiled, "text", key, siteOf([
38591
+ ...around,
38592
+ block.type,
38593
+ ...outer
38594
+ ], root)) === resolveCompiledSchemaProperty(compiled, "text", key, compareWith(around, from))));
38595
+ const keepsMarks = (block) => marksHoldAtEveryExit(block, (_, from) => from);
38596
+ const readsMarksAsToday = (block) => marksHoldAtEveryExit(block, (around) => siteOf([...around, ...outer], root));
38597
+ const takes = (block) => {
38598
+ const element = compiled.elements.byType.get(block.type);
38599
+ const own = element?.content;
38600
+ const behavior = element?.behavior;
38601
+ const shell = {
38602
+ ...block.properties,
38603
+ children: [],
38604
+ type: block.type
38605
+ };
38606
+ return !!behavior && !!own && behavior.selectable && !behavior.atom && !behavior.readOnly && !behavior.inline && !behavior.isolating && !own.prefix && own.max === null && own.min <= 1 && element.contentRoots.size === 0 && lineNodes.every((child) => schema.canContain(shell, child)) && container.children.length - removing.length + 2 >= content.min && schema.canPlaceAt(container, container.children, [shell, shell], line.from, {
38607
+ removing,
38608
+ root
38609
+ }) && needsNothing(block) && ownPropertiesHold(block) && keepsDescendants(lineNodes, outer, [block.type, ...outer]);
38610
+ };
38611
+ const tried = /* @__PURE__ */ new Set();
38612
+ const fits = [];
38613
+ for (const plan of [remainderOf(content)?.defaultPlan, remainderOf(schema.getRootContent(root))?.defaultPlan]) {
38614
+ if (plan?.kind !== "element") continue;
38615
+ const block = {
38616
+ properties: plan.properties,
38617
+ type: plan.type
38618
+ };
38619
+ const id = JSON.stringify(block);
38620
+ if (tried.has(id)) continue;
38621
+ tried.add(id);
38622
+ if (takes(block)) fits.push(block);
38623
+ }
38624
+ return fits.find(keepsMarks) ?? fits.find(readsMarksAsToday) ?? null;
38625
+ };
38626
+ const wrapTextLine = (editor, line, block) => {
38627
+ const [container] = line.chain;
38628
+ for (let index = line.from; index < line.to; index += 1) {
38629
+ const node = container?.children[index];
38630
+ if (NodeApi.isElement(node)) refuseVetoedWrite(editor, {
38631
+ kind: "wrap",
38632
+ node,
38633
+ path: [...line.path, index],
38634
+ root: line.root
38635
+ });
38636
+ }
38637
+ const { children: _children, ...shell } = getEditorSchema(editor).createAt(block.type, block.properties, {
38638
+ ancestors: line.chain,
38639
+ children: [],
38640
+ root: line.root
38641
+ });
38642
+ syncImplicitTargetToCurrentSelection(editor);
38643
+ applyBuiltDocumentChange(editor, (builder, root) => builder.wrapChildren(root, line.path, line.from, line.to - line.from, shell));
38644
+ };
38645
+ //#endregion
37535
38646
  //#region src/editor/block-void-break.ts
37536
38647
  const breakAtSelectedBlockVoid = (editor) => {
37537
38648
  const selection = getSelection(editor);
@@ -37572,6 +38683,29 @@ const applyInsertBreak = (editor) => {
37572
38683
  if (selection && !RangeApi.isRange(selection)) return;
37573
38684
  const landed = selection && landTextWriteOutsideStruck(editor, selection, getChildList(editor));
37574
38685
  if (landed && (refusesReadOnlyWrite(editor, landed) || dividesTextCell(editor, landed))) return;
38686
+ const [at, end] = landed === selection && selection ? RangeApi.edges(selection) : [];
38687
+ const root = getActiveUpdateRoot(editor) ?? "main";
38688
+ const line = at && textLineAt(editor, root, at);
38689
+ const block = line && end && (PointApi.equals(at, end) || textLineAt(editor, root, end)) && admitLineBlock(editor, line, {
38690
+ at,
38691
+ end,
38692
+ marks: withoutTypedMarks(editor, getCurrentMarks(editor) ?? getSelectionMarks(editor))
38693
+ });
38694
+ const target = block && peekImplicitTarget(editor);
38695
+ const samePlace = (point, other) => point.offset === other.offset && PathApi.equals(point.path, other.path) && getPointRoot(point, root).root === getPointRoot(other, root).root;
38696
+ const targetIsCaret = at && end && RangeApi.isRange(target) && samePlace(RangeApi.start(target), at) && samePlace(RangeApi.end(target), end);
38697
+ if (line && block && targetIsCaret) {
38698
+ runEditorTransaction(editor, () => {
38699
+ wrapTextLine(editor, line, block);
38700
+ const softBreak = getNextSoftBreakRange(editor);
38701
+ if (softBreak) deleteText(editor, {
38702
+ at: softBreak,
38703
+ hanging: true
38704
+ });
38705
+ splitKeepingMarks(editor);
38706
+ });
38707
+ return;
38708
+ }
37575
38709
  if (landed && landed !== selection) runEditorTransaction(editor, (tx) => {
37576
38710
  tx.setSelection(SelectionApi.text(landed));
37577
38711
  });
@@ -37580,30 +38714,31 @@ const applyInsertBreak = (editor) => {
37580
38714
  hanging: true
37581
38715
  });
37582
38716
  if (selection && breakAtSelectedBlockVoid(editor)) return;
37583
- runEditorTransaction(editor, (tx) => {
37584
- const marks = withoutTypedMarks(editor, tx.marks ?? tx.getSelectionMarks());
37585
- splitNodes$1(editor, { always: true });
37586
- const caret = tx.getModelSelection();
37587
- if (!marks || !SelectionApi.isText(caret) || !RangeApi.isCollapsed(caret)) return;
37588
- const { path } = caret.anchor;
37589
- const text = NodeApi.get(editor, path);
37590
- if (!NodeApi.isText(text) || text.text !== "") return;
37591
- const schema = getEditorSchema(editor);
37592
- const root = getActiveUpdateRoot(editor) ?? "main";
37593
- const preserved = schema.textPropertiesForSplitAt({
37594
- ...marks,
37595
- text: ""
37596
- }, path, root);
37597
- const caretMarks = Object.keys(preserved).reduce((properties, key) => schema.canonicalizeTextPropertiesAt(properties, path, root, key), {
37598
- ...NodeApi.extractProps(text),
37599
- ...preserved
37600
- });
37601
- if (!textPropertiesEqual(text, {
37602
- ...caretMarks,
37603
- text: ""
37604
- })) tx.setMarks(caretMarks);
37605
- });
37606
- };
38717
+ splitKeepingMarks(editor);
38718
+ };
38719
+ const splitKeepingMarks = (editor) => runEditorTransaction(editor, (tx) => {
38720
+ const marks = withoutTypedMarks(editor, tx.marks ?? tx.getSelectionMarks());
38721
+ splitNodes$1(editor, { always: true });
38722
+ const caret = tx.getModelSelection();
38723
+ if (!marks || !SelectionApi.isText(caret) || !RangeApi.isCollapsed(caret)) return;
38724
+ const { path } = caret.anchor;
38725
+ const text = NodeApi.get(editor, path);
38726
+ if (!NodeApi.isText(text) || text.text !== "") return;
38727
+ const schema = getEditorSchema(editor);
38728
+ const root = getActiveUpdateRoot(editor) ?? "main";
38729
+ const preserved = schema.textPropertiesForSplitAt({
38730
+ ...marks,
38731
+ text: ""
38732
+ }, path, root);
38733
+ const caretMarks = Object.keys(preserved).reduce((properties, key) => schema.canonicalizeTextPropertiesAt(properties, path, root, key), {
38734
+ ...NodeApi.extractProps(text),
38735
+ ...preserved
38736
+ });
38737
+ if (!textPropertiesEqual(text, {
38738
+ ...caretMarks,
38739
+ text: ""
38740
+ })) tx.setMarks(caretMarks);
38741
+ });
37607
38742
  const insertBreak$1 = (editor) => {
37608
38743
  dispatchCommand(editor, editorCommands.insertBreak);
37609
38744
  };
@@ -38098,48 +39233,6 @@ const notifyEditorChangeListeners = (editor, commit, beforeValue, afterValue) =>
38098
39233
  });
38099
39234
  };
38100
39235
  //#endregion
38101
- //#region src/core/change/range-content.ts
38102
- const insideVoid = (voids, position) => {
38103
- let low = 0;
38104
- let high = voids.length - 1;
38105
- while (low <= high) {
38106
- const middle = low + high >> 1;
38107
- const [voidFrom, voidTo] = voids[middle];
38108
- if (position < voidFrom) high = middle - 1;
38109
- else if (position >= voidTo) low = middle + 1;
38110
- else return true;
38111
- }
38112
- return false;
38113
- };
38114
- const FIRST_WINDOW = 64;
38115
- /** @internal */
38116
- const coversContent = (index, from, to, schema) => {
38117
- if (from >= to) return false;
38118
- for (let width = FIRST_WINDOW;; width *= 2) {
38119
- const end = Math.min(to, from + width);
38120
- if (coversContentUpTo(index, from, end, to, schema)) return true;
38121
- if (end === to) return false;
38122
- }
38123
- };
38124
- const coversContentUpTo = (index, from, end, to, schema) => {
38125
- const entries = index.nodeRangesTouching(from, end);
38126
- const voids = [];
38127
- countCoreWork("contentSpanNodes", entries.length);
38128
- for (const entry of entries) {
38129
- if (entry.kind === "text" || !schema.isVoid(index.node(entry.path))) continue;
38130
- if (from <= entry.from && entry.to <= to) return true;
38131
- voids.push([entry.from, entry.to]);
38132
- }
38133
- voids.sort(([a], [b]) => a - b);
38134
- const outerVoids = [];
38135
- for (const range of voids) if (range[0] >= (outerVoids.at(-1)?.[1] ?? -1)) outerVoids.push(range);
38136
- return entries.some((entry) => {
38137
- if (entry.kind !== "text") return false;
38138
- const start = Math.max(from, entry.contentFrom);
38139
- return start < Math.min(end, entry.contentTo) && !insideVoid(outerVoids, start);
38140
- });
38141
- };
38142
- //#endregion
38143
39236
  //#region src/core/content-slice-roots.ts
38144
39237
  const namesContentRoot = (editor, children) => {
38145
39238
  const schema = getEditorSchema(editor);
@@ -38174,6 +39267,20 @@ const rewriteContentRootReferences = (editor, children, rewriteRoot) => {
38174
39267
  };
38175
39268
  //#endregion
38176
39269
  //#region src/core/document-recorder.ts
39270
+ /** @internal */
39271
+ const recordedCarriedRuns = (steps, writtenToRecorded, startToRecordedStart = (_root, position) => position) => carriedRunsOf(steps).flatMap((run) => {
39272
+ const source = startToRecordedStart(run.root, run.source, 1);
39273
+ const sourceEnd = startToRecordedStart(run.root, run.source + run.length, -1);
39274
+ const at = writtenToRecorded(run.root, run.at, 1);
39275
+ const end = writtenToRecorded(run.root, run.at + run.landed, -1);
39276
+ return source === null || sourceEnd === null || at === null || end === null || sourceEnd <= source || end <= at ? [] : [{
39277
+ at,
39278
+ landed: end - at,
39279
+ length: sourceEnd - source,
39280
+ root: run.root,
39281
+ source
39282
+ }];
39283
+ });
38177
39284
  const DOCUMENT_RECORDERS = /* @__PURE__ */ new WeakMap();
38178
39285
  const BY_LOOK_FITS = /* @__PURE__ */ new WeakMap();
38179
39286
  const DRAFT_GUARDS = /* @__PURE__ */ new WeakMap();
@@ -38776,6 +39883,16 @@ const renameSlice = (editor, slice, to) => {
38776
39883
  })();
38777
39884
  };
38778
39885
  //#endregion
39886
+ //#region src/core/native-grouping-input.ts
39887
+ const nativeGroupingInput = defineUpdateAnnotation({
39888
+ combine: (_previous, next) => next,
39889
+ key: "history.native-grouping-input"
39890
+ });
39891
+ const recordedDeleteGroupingInput = defineUpdateAnnotation({
39892
+ combine: () => null,
39893
+ key: "history.recorded-delete-grouping"
39894
+ });
39895
+ //#endregion
38779
39896
  //#region src/core/node-property-mutation.ts
38780
39897
  const isPropertyHandle = (value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "schema-property";
38781
39898
  const getExactPropertyKey = (property, resolve) => {
@@ -38986,6 +40103,20 @@ const readShownViewUse = (owner, presentation) => {
38986
40103
  return newest;
38987
40104
  };
38988
40105
  const tellViewUse = (owner) => notifyObservers(owner, USE_LISTENERS.get(owner), "commit-listener", (listener) => listener());
40106
+ const placeByUse = (entry, view) => {
40107
+ entry.usedLatestFirst = [...entry.usedLatestFirst.filter((used) => used !== view), view].sort((left, right) => readRootViewUse(right) - readRootViewUse(left));
40108
+ };
40109
+ const continueRootViewUse = (view, usedAt) => {
40110
+ const runtime = getEditorRuntime(view);
40111
+ const entry = VIEW_ENTRIES.get(runtime);
40112
+ if (usedAt <= (USED_AT.get(runtime) ?? 0)) return;
40113
+ USED_AT.set(runtime, usedAt);
40114
+ if (entry?.views.has(view)) {
40115
+ placeByUse(entry, view);
40116
+ invalidate(entry);
40117
+ tellViewUse(entry.owner);
40118
+ }
40119
+ };
38989
40120
  /**
38990
40121
  * Hear, in the same turn, each use of a view of the editor, and each of its
38991
40122
  * views that mounts, unmounts, or gains or loses its surface.
@@ -39011,7 +40142,7 @@ const mountRootView = (owner, presentation, root, view) => {
39011
40142
  });
39012
40143
  entry.views.add(view);
39013
40144
  VIEW_ENTRIES.set(runtime, entry);
39014
- if (USED_AT.has(runtime)) entry.usedLatestFirst = [...entry.usedLatestFirst, view].sort((left, right) => readRootViewUse(right) - readRootViewUse(left));
40145
+ if (USED_AT.has(runtime)) placeByUse(entry, view);
39015
40146
  invalidate(entry);
39016
40147
  announcePresentation(presentation);
39017
40148
  tellViewUse(owner);
@@ -39227,7 +40358,18 @@ const planPaste = (editor, state, input, intent, internal = {}) => {
39227
40358
  slice: slice.content.length === 0 && landed.slice.content.length > 0 ? null : slice
39228
40359
  };
39229
40360
  };
39230
- const writePaste = (editor, plan, options = {}) => {
40361
+ const TRACKED_PASTES = /* @__PURE__ */ new WeakSet();
40362
+ const withTrackedPastes = (editor, run) => {
40363
+ const owner = getEditorRuntimeOwner(editor);
40364
+ TRACKED_PASTES.add(owner);
40365
+ try {
40366
+ return run();
40367
+ } finally {
40368
+ TRACKED_PASTES.delete(owner);
40369
+ }
40370
+ };
40371
+ const writePaste = (editor, plan, requested = {}) => {
40372
+ const options = TRACKED_PASTES.has(getEditorRuntimeOwner(editor)) ? { landing: true } : requested;
39231
40373
  if (plan.emptyBlockReplacement) {
39232
40374
  const fit = fitSliceAtSite(editor, plan.site, plan.emptyBlockReplacement, {
39233
40375
  ...options,
@@ -39679,6 +40821,8 @@ const withContextsBelow = (editor, context, fn) => {
39679
40821
  };
39680
40822
  const getTransactionSnapshot = (editor) => getTransactionSpecContext(editor)?.snapshot;
39681
40823
  const getUpdateStartSnapshot = (editor) => TRANSACTION_SPEC_CONTEXTS.get(editor)?.at(0)?.snapshot;
40824
+ /** @internal */
40825
+ const isPluginReconfigurationStagedInUpdate = (editor) => TRANSACTION_SPEC_CONTEXTS.get(getEditorRuntimeOwner(editor))?.some(({ snapshot }) => snapshot.pluginReconfigurations.size > 0) ?? false;
39682
40826
  /**
39683
40827
  * Final semantic tags visible to the active command layer.
39684
40828
  *
@@ -39738,6 +40882,8 @@ const APPLIED_SPEC_LANDINGS = /* @__PURE__ */ new WeakMap();
39738
40882
  const TRANSACTION_SPEC_CARETS = /* @__PURE__ */ new WeakMap();
39739
40883
  /** @internal */
39740
40884
  const getAppliedSpecLanding = (spec) => APPLIED_SPEC_LANDINGS.get(spec);
40885
+ /** @internal */
40886
+ const getTransactionLanding = (editor) => getTransactionSpecContext(editor)?.lastSpecLanding;
39741
40887
  const trackLandedRange = (editor, range) => {
39742
40888
  const snapshot = getDefined(getTransactionSnapshot(editor));
39743
40889
  const root = range.anchor.root ?? "main";
@@ -39950,65 +41096,18 @@ const settleBeforeRecordingFrontier = (editor, snapshot) => {
39950
41096
  });
39951
41097
  dropOrphanedRoots(editor, { notifyTransactionListeners: false });
39952
41098
  };
39953
- /** The runs `steps` carried, as spans of the documents they ran between. */
39954
- const draftRunsOf = (steps, toBefore) => carriedRunsOf(steps).flatMap((run) => {
39955
- const source = toBefore ? toBefore(run.root, run.source, 1) : run.source;
39956
- const sourceEnd = toBefore ? toBefore(run.root, run.source + run.length, -1) : run.source + run.length;
39957
- return source === null || sourceEnd === null ? [] : [{
39958
- at: run.at,
39959
- end: run.at + run.landed,
39960
- root: run.root,
39961
- source,
39962
- sourceEnd
39963
- }];
39964
- });
39965
- /**
39966
- * The runs the recorded change carries, from the runs the plain draft
39967
- * carried: each landing follows the recorder's map, and each source maps back
39968
- * through the drafts recorded before. `ChangeDraft.apply` keeps only the runs
39969
- * whose two spans hold the same letters.
39970
- */
39971
- const recordedRunsOf = (runs, toRecorded, frontier) => runs.flatMap((run) => {
39972
- const at = toRecorded(run.root, run.at, 1);
39973
- const end = toRecorded(run.root, run.end, -1);
39974
- const length = run.sourceEnd - run.source;
39975
- const before = frontier ? getInternalDocumentRootChange(frontier, run.root) : void 0;
39976
- const kept = before ? keptRunsOf(before, run.source, run.sourceEnd) : [{
39977
- at: run.source,
39978
- from: run.source,
39979
- to: run.sourceEnd
39980
- }];
39981
- return at === null || end === null || end <= at || length <= 0 || kept.length !== 1 || kept[0].from !== run.source || kept[0].to !== run.sourceEnd ? [] : [{
39982
- at,
39983
- landed: end - at,
39984
- length,
39985
- root: run.root,
39986
- source: kept[0].at
39987
- }];
39988
- });
39989
- /**
39990
- * The runs an earlier frame's recorded change carried, as the next recorded
39991
- * change from that frame's document leaves them.
39992
- */
39993
- const frontierRunsThrough = (frontier, recorded) => frontier.runs.flatMap((run) => {
39994
- const change = getInternalDocumentRootChange(recorded.change, run.root);
39995
- if (!change) return [run];
39996
- const before = valueRootIndex(frontier.value, run.root);
39997
- const moved = followCarriedRun(run, change, before, recorded.indexedAfter?.get(run.root) ?? change.apply(before));
39998
- return moved ? [moved] : [];
39999
- });
40000
- const commitRecordedDraft = (editor, context, recorded, selectionRoot, { carried, letters, plain, runs, storedToWritten, typed }) => {
41099
+ const commitRecordedDraft = (editor, context, recorded, selectionRoot, { carried, writtenLanding, letters, plain, plainSteps, storedToWritten, typed }) => {
40001
41100
  const { snapshot } = context;
40002
41101
  const frontier = RECORDING_FRONTIERS.get(snapshot);
40003
41102
  const { mapPosition } = recorded;
40004
41103
  const plainBuilder = snapshot.builder;
40005
- const change = frontier ? frontier.change.compose(recorded.change) : recorded.change;
41104
+ const { change } = recorded;
40006
41105
  const plainToRecorded = mapPosition ? (root, position, assoc) => {
40007
41106
  const written = storedToWritten ? storedToWritten(root, position, assoc) : position;
40008
41107
  return written === null ? null : mapPosition(root, written, assoc);
40009
41108
  } : null;
40010
41109
  const recordedLetters = /* @__PURE__ */ new Map();
40011
- const recordedRuns = [...frontier ? frontierRunsThrough(frontier, recorded) : [], ...mapPosition && runs?.length ? recordedRunsOf(runs, mapPosition, frontier?.change ?? null) : []];
41110
+ const recordedRuns = mapPosition && plainSteps ? recordedCarriedRuns(plainSteps.steps, mapPosition, plainSteps.toStored) : [];
40012
41111
  if (mapPosition && plainToRecorded) for (const [root, spans] of [...mapNewLetters(plainBuilder.newLetters, plainToRecorded), ...letters ? mapNewLetters(letters, mapPosition) : []]) recordedLetters.set(root, mergeSpans([...recordedLetters.get(root) ?? [], ...spans]));
40013
41112
  if (plain) carryDraftNodeKeys(editor, snapshot, recorded, plain);
40014
41113
  const base = getChangeValue(snapshot.roots, snapshot.records);
@@ -40031,9 +41130,15 @@ const commitRecordedDraft = (editor, context, recorded, selectionRoot, { carried
40031
41130
  root: snapshot.selectionRoot,
40032
41131
  selection: null
40033
41132
  };
41133
+ const checkpoint = frontier?.checkpoint;
41134
+ const resumes = checkpoint !== void 0 && checkpoint.steps.length > 0;
41135
+ if (plainSteps && plainSteps.steps.length > 0 && !recorded.facts) snapshot.publishesUnknownFacts = true;
40034
41136
  const applyRecorded = () => {
41137
+ const resumed = resumes ? snapshot.builder.resume(checkpoint) : null;
41138
+ if (resumed) applyTransactionSpecDocumentChangeStep(editor, resumed, { notifyTransactionListeners: false });
40035
41139
  if (change.empty) return;
40036
41140
  applyTransactionSpecDocumentChangeStep(editor, snapshot.builder.apply(change, {
41141
+ ...recorded.facts ? { facts: recorded.facts } : {},
40037
41142
  ...recorded.indexedAfter ? { indexedAfter: recorded.indexedAfter } : {},
40038
41143
  ...recordedLetters.size > 0 ? { letters: recordedLetters } : {},
40039
41144
  ...recordedRuns.length > 0 ? { carried: recordedRuns } : {}
@@ -40043,6 +41148,8 @@ const commitRecordedDraft = (editor, context, recorded, selectionRoot, { carried
40043
41148
  else applyRecorded();
40044
41149
  snapshot.builder.beginSpan();
40045
41150
  moveDraftTracks(snapshot, plainBuilder, snapshot.builder, plainToRecorded);
41151
+ const landedSpans = writtenLanding && mapPosition && mapSpans(writtenLanding.root, writtenLanding.spans, mapPosition);
41152
+ if (writtenLanding && landedSpans) context.lastSpecLanding = trackDraftSpans(snapshot, snapshot.builder, writtenLanding.root, landedSpans);
40046
41153
  context.caret = {
40047
41154
  ...context.caret,
40048
41155
  ...carryCaret(getSetSite(editor), context.caret, {
@@ -40052,13 +41159,16 @@ const commitRecordedDraft = (editor, context, recorded, selectionRoot, { carried
40052
41159
  };
40053
41160
  if (carried) context.caret = landCarets(editor, context.caret, carried);
40054
41161
  if (snapshot.implicitTargetResolved) snapshot.implicitTarget = cloneValue(recorded.selection);
40055
- if (!change.empty) settleBeforeRecordingFrontier(editor, snapshot);
41162
+ if (resumes || !change.empty) settleBeforeRecordingFrontier(editor, snapshot);
41163
+ if (!frontier && recorded.deleteGrouping) snapshot.annotations.set(recordedDeleteGroupingInput.key, {
41164
+ type: recordedDeleteGroupingInput,
41165
+ value: recorded.deleteGrouping
41166
+ });
41167
+ else if (snapshot.annotations.has(recordedDeleteGroupingInput.key)) snapshot.annotations.delete(recordedDeleteGroupingInput.key);
40056
41168
  RECORDING_FRONTIERS.set(snapshot, {
40057
- change: snapshot.builder.change,
40058
- runs: snapshot.builder.carriedRuns(),
40059
41169
  selection: context.caret.selection,
40060
41170
  selectionRoot: context.caret.root,
40061
- steps: snapshot.builder.draftSteps.length,
41171
+ checkpoint: snapshot.builder.checkpoint(),
40062
41172
  value: snapshot.builder.value
40063
41173
  });
40064
41174
  setTypedMarks(editor, typed);
@@ -40084,11 +41194,15 @@ const runEditorDocumentRecorder = (editor) => {
40084
41194
  const snapshot = context?.snapshot;
40085
41195
  if (!context || !snapshot) return;
40086
41196
  const frontier = RECORDING_FRONTIERS.get(snapshot);
40087
- const steps = snapshot.builder.draftSteps.slice(frontier?.steps ?? 0);
41197
+ const steps = snapshot.builder.stepsSince(frontier?.checkpoint);
40088
41198
  if (frontier && steps.length === 0) return;
40089
41199
  runEditorDraftGuards(editor, "plain", snapshot.builder.value);
40090
41200
  const recorder = getEditorDocumentRecorder(editor);
40091
- if (!recorder || snapshot.activeChange.change.empty) return;
41201
+ if (!recorder) return;
41202
+ if (snapshot.activeChange.change.empty) {
41203
+ if (steps.length > 0) snapshot.publishesUnknownFacts = true;
41204
+ return;
41205
+ }
40092
41206
  const selectionRoot = context.caret.root;
40093
41207
  const carried = carryCarets(editor, context.baseCaret, context.caret);
40094
41208
  const plain = {
@@ -40112,7 +41226,7 @@ const runEditorDocumentRecorder = (editor) => {
40112
41226
  commitRecordedDraft(editor, context, recorded, selectionRoot, {
40113
41227
  carried: recordedCarets(carried, recorded),
40114
41228
  plain,
40115
- runs: draftRunsOf(steps),
41229
+ plainSteps: { steps },
40116
41230
  typed: getTypedMarks(editor)
40117
41231
  });
40118
41232
  };
@@ -40482,6 +41596,7 @@ const assertCanStartEditorWrite = (editor, authority) => {
40482
41596
  if (!authority) throw new Error("editor writes must run inside editor.update");
40483
41597
  };
40484
41598
  const getVersion = (editor) => SNAPSHOT_VERSION.get(editor) ?? 0;
41599
+ /** @internal */
40485
41600
  const getMutationVersion = (editor) => getTransactionSpecContext(editor)?.mutationVersion ?? MUTATION_VERSION.get(editor) ?? 0;
40486
41601
  const getSnapshotVersion = (editor) => getVersion(editor);
40487
41602
  const setSnapshotVersion = (editor, version) => {
@@ -40502,7 +41617,7 @@ const initializeVersionState = (editor) => {
40502
41617
  const getEditorRecordsJson = (editor, store) => {
40503
41618
  const cached = RECORDS_JSON.get(editor);
40504
41619
  if (cached?.store === store) return cached.json;
40505
- const json = recordStoreToJson(store);
41620
+ const json = recordStoreToJson(store, cached?.json);
40506
41621
  RECORDS_JSON.set(editor, {
40507
41622
  json,
40508
41623
  store
@@ -41933,7 +43048,7 @@ const getWholeBlockReplacements = (state, slice, at, root) => {
41933
43048
  }));
41934
43049
  return replacements.every((node) => node !== null) ? { replacements } : null;
41935
43050
  };
41936
- const replaceBlocksAtSite = (editor, transaction, place, slice) => {
43051
+ const replaceBlocksAtSite = (editor, transaction, place, slice, landed) => {
41937
43052
  const state = getStateView(editor);
41938
43053
  if (slice.content.length === 0) {
41939
43054
  const [first, ...rest] = place.blocks.map(([block]) => state.key(block));
@@ -41947,12 +43062,23 @@ const replaceBlocksAtSite = (editor, transaction, place, slice) => {
41947
43062
  const replacement = planned && getNodeSelectionReplacement(state, place.blocks, place.root, planned.replacements);
41948
43063
  if (!replacement) return false;
41949
43064
  replaceSelectedBlocks(transaction, replacement);
43065
+ if (landed) {
43066
+ const snapshot = getDefined(getTransactionSnapshot(editor));
43067
+ const index = snapshot.builder.getIndex(place.root);
43068
+ const { parentPath } = replacement;
43069
+ const first = replacement.index;
43070
+ const last = first + replacement.replacements.length - 1;
43071
+ landed(trackDraftSpans(snapshot, snapshot.builder, place.root, [{
43072
+ from: index.nodeRange([...parentPath, first]).from,
43073
+ to: index.nodeRange([...parentPath, last]).to
43074
+ }]));
43075
+ }
41950
43076
  return true;
41951
43077
  };
41952
43078
  const landSlice = (editor, transaction, place, slice, options = {}) => {
41953
43079
  const paste = {};
41954
43080
  const write = (target, content) => {
41955
- if (target.kind === "blocks") return replaceBlocksAtSite(editor, transaction, target, content);
43081
+ if (target.kind === "blocks") return replaceBlocksAtSite(editor, transaction, target, content, options.landed);
41956
43082
  if (!writeSliceAtRange(editor, target, content, {
41957
43083
  ...options,
41958
43084
  paste
@@ -43566,7 +44692,7 @@ const getUpdateView = (editor) => {
43566
44692
  runActive(() => {
43567
44693
  requireMutableRoot(root);
43568
44694
  if (Object.hasOwn(getEditorDocumentRoots(editor), root) || takenRootNames(editor).has(root)) throw new Error(`Cannot create existing editor root "${root}".`);
43569
- applyTransactionSpec(editor, createRootFitTransactionSpec(editor, root, ContentSlice.closed(children)));
44695
+ applyTransactionSpec(editor, createRootFitTransactionSpec(editor, root, children));
43570
44696
  });
43571
44697
  },
43572
44698
  delete: (root) => {
@@ -43584,7 +44710,7 @@ const getUpdateView = (editor) => {
43584
44710
  const roots = getEditorDocumentRoots(editor);
43585
44711
  const previousChildren = roots[root];
43586
44712
  if (!Object.hasOwn(roots, root) || previousChildren === void 0) throw new Error(`Cannot replace missing editor root "${root}".`);
43587
- applyTransactionSpec(editor, createRootFitTransactionSpec(editor, root, ContentSlice.closed(children)));
44713
+ applyTransactionSpec(editor, createRootFitTransactionSpec(editor, root, children));
43588
44714
  });
43589
44715
  }
43590
44716
  }),
@@ -44027,6 +45153,7 @@ const finalizeTransactionSpecContext = (editor, context) => {
44027
45153
  const carried = carryCarets(editor, context.baseCaret, context.caret);
44028
45154
  if (carried) TRANSACTION_SPEC_CARETS.set(spec, carried);
44029
45155
  keepSpecTypedMarks(context, spec);
45156
+ recordSpecLanding(spec, context.lastSpecLanding);
44030
45157
  return spec;
44031
45158
  };
44032
45159
  /**
@@ -44075,7 +45202,10 @@ const applyTransactionSpecContents = (editor, spec) => {
44075
45202
  } } : {},
44076
45203
  ...landing ? { beforeListeners: () => {
44077
45204
  const snapshot = getDefined(getTransactionSnapshot(editor));
44078
- APPLIED_SPEC_LANDINGS.set(spec, trackDraftSpans(snapshot, snapshot.builder, landing.root, [landing.span]));
45205
+ const track = trackDraftSpans(snapshot, snapshot.builder, landing.root, [landing.span]);
45206
+ const context = getTransactionSpecContext(editor);
45207
+ APPLIED_SPEC_LANDINGS.set(spec, track);
45208
+ if (context) context.lastSpecLanding = track;
44079
45209
  } } : {}
44080
45210
  };
44081
45211
  withoutPlacement(editor, () => {
@@ -44926,7 +46056,24 @@ const peekImplicitTarget = (editor) => {
44926
46056
  const owner = getEditorRuntimeOwner(editor);
44927
46057
  const snapshot = getTransactionSnapshot(owner);
44928
46058
  if (snapshot?.implicitTargetResolved) return cloneValue(snapshot.implicitTarget);
44929
- return moveImplicitTarget(owner)?.target ?? getCurrentSelection(owner);
46059
+ const moved = askImplicitTargetOnce(owner);
46060
+ return moved ? cloneValue(moved.target) : getCurrentSelection(owner);
46061
+ };
46062
+ const TARGET_ANSWERS = /* @__PURE__ */ new WeakMap();
46063
+ const askImplicitTargetOnce = (editor) => {
46064
+ const owner = getEditorRuntimeOwner(editor);
46065
+ const snapshot = getTransactionSnapshot(owner);
46066
+ const selection = readCurrentSelection(owner);
46067
+ const value = snapshot?.builder.value;
46068
+ const answered = snapshot && TARGET_ANSWERS.get(snapshot);
46069
+ if (answered && answered.selection === selection && answered.value === value) return answered.moved;
46070
+ const moved = moveImplicitTarget(owner);
46071
+ if (snapshot) TARGET_ANSWERS.set(snapshot, {
46072
+ moved,
46073
+ selection,
46074
+ value
46075
+ });
46076
+ return moved;
44930
46077
  };
44931
46078
  const moveImplicitTarget = (editor) => {
44932
46079
  const frame = getTransactionSnapshot(editor)?.implicitTargetFrame;
@@ -44957,8 +46104,8 @@ const getTransactionView = (editor) => {
44957
46104
  const snapshot = getTransactionSnapshot(editor);
44958
46105
  if (snapshot?.implicitTargetResolved) return cloneValue(snapshot.implicitTarget);
44959
46106
  const target = profileCoreDuration("resolve-implicit-target", () => {
44960
- const moved = moveImplicitTarget(editor);
44961
- if (moved) setCurrentSelection(editor, moved.target);
46107
+ const moved = askImplicitTargetOnce(editor);
46108
+ if (moved) setCurrentSelection(editor, cloneValue(moved.target));
44962
46109
  return getCurrentSelection(editor);
44963
46110
  });
44964
46111
  if (snapshot) {
@@ -45157,7 +46304,7 @@ const getActiveTransactionDocumentChange = (editor) => {
45157
46304
  return [...getInternalDocumentChangeEntries(change)].every(([root]) => !!getInternalDocumentChangeClassification(change, root)) ? change : snapshot.builder.classify(change);
45158
46305
  };
45159
46306
  const getActiveDocumentChangeBuilder = (editor) => {
45160
- const snapshot = getTransactionSnapshot(editor);
46307
+ const snapshot = getDraftSnapshot(editor);
45161
46308
  if (!snapshot) throw new Error("Document change builders require an active transaction.");
45162
46309
  return snapshot.builder;
45163
46310
  };
@@ -45195,7 +46342,7 @@ const createEditorDocumentChangeBuilder = (editor, value, options = {}) => {
45195
46342
  preserveInlineSpacersAdjacentTo: (root) => getProtectedInlineSpacerNodes(editor, candidate, root)
45196
46343
  }).empty) throw new EditorNoncanonicalChangeError();
45197
46344
  },
45198
- construct: ({ after, before, carried, change, indexedAfter, indexedBefore }, preparation) => {
46345
+ construct: ({ after, before, carried, change, indexedAfter, indexedBefore, sinceValidated }, preparation) => {
45199
46346
  assertRevision();
45200
46347
  return constructCanonicalDocumentChange(editor, after, change, {
45201
46348
  before,
@@ -45203,7 +46350,8 @@ const createEditorDocumentChangeBuilder = (editor, value, options = {}) => {
45203
46350
  fitPreparation: preparation,
45204
46351
  indexedAfter,
45205
46352
  indexedBefore,
45206
- preserveInlineSpacersAdjacentTo: (root) => getProtectedInlineSpacerNodes(editor, after, root)
46353
+ preserveInlineSpacersAdjacentTo: (root) => getProtectedInlineSpacerNodes(editor, after, root),
46354
+ sinceValidated
45207
46355
  });
45208
46356
  },
45209
46357
  indexConstructedRoot: schema.indexConstructedRoot,
@@ -45243,12 +46391,8 @@ const createEditorDocumentChangeBuilder = (editor, value, options = {}) => {
45243
46391
  });
45244
46392
  };
45245
46393
  const rebindTransactionBuilderToCurrentSchema = (editor, snapshot) => {
45246
- const accumulated = snapshot.activeChange.change;
45247
46394
  const builder = createEditorDocumentChangeBuilder(editor, getChangeValue(snapshot.roots, snapshot.records), { validation: "configuration-publication" });
45248
- if (!accumulated.empty) {
45249
- builder.apply(accumulated, { indexedAfter: snapshot.builder.indexedAfter(accumulated) });
45250
- builder.keepSteps(snapshot.builder);
45251
- }
46395
+ builder.resume(snapshot.builder.checkpoint());
45252
46396
  snapshot.builder = builder;
45253
46397
  snapshot.builderValidation = "configuration-publication";
45254
46398
  snapshot.activeChange = { change: builder.change };
@@ -46080,6 +47224,7 @@ const runEditorTransaction = (editor, fn, options = {}) => {
46080
47224
  const canonicalChanges = snapshot.activeChange.change;
46081
47225
  if (snapshot.builder.tracksLetters && canonicalChanges === snapshot.builder.change) markLetterOrigins(canonicalChanges, [...snapshot.builder.draftSteps]);
46082
47226
  const completedTextDeletion = canonicalChanges === snapshot.builder.change ? snapshot.builder.completedTextDeletion() : null;
47227
+ if (snapshot.annotations.has(recordedDeleteGroupingInput.key) && (canonicalChanges !== snapshot.builder.change || snapshot.builder.draftSteps.some((step, index) => index > 0 && step.origin !== "canonical"))) snapshot.annotations.delete(recordedDeleteGroupingInput.key);
46083
47228
  const canonicalIndexes = snapshot.builder.indexedAfter(canonicalChanges);
46084
47229
  const { previousSnapshot } = snapshot;
46085
47230
  const beforeSnapshot = snapshot.childrenRoot === "main" ? previousSnapshot : getTransactionBeforeRootSnapshot(editor, snapshot, MAIN_ROOT_KEY);
@@ -46101,7 +47246,7 @@ const runEditorTransaction = (editor, fn, options = {}) => {
46101
47246
  beforeValue,
46102
47247
  carried: canonicalChanges === snapshot.builder.change ? snapshot.builder.carriedRuns() : [],
46103
47248
  changes: canonicalChanges,
46104
- facts: snapshot.builder.factsFor(canonicalChanges),
47249
+ facts: snapshot.publishesUnknownFacts ? UNKNOWN_FACTS : snapshot.builder.factsFor(canonicalChanges),
46105
47250
  completedTextDeletion,
46106
47251
  dirtyStateKeys: [...snapshot.dirtyStateKeys],
46107
47252
  effects: [...snapshot.effects],
@@ -46288,7 +47433,9 @@ const runEditorTransaction = (editor, fn, options = {}) => {
46288
47433
  if (drainError) throw drainError.value;
46289
47434
  return answer;
46290
47435
  };
46291
- const createRootFitTransactionSpec = (editor, root, input, selection) => {
47436
+ const createRootFitTransactionSpec = (editor, root, content, selection) => {
47437
+ const [kept] = keepElementIds(editor, [[valueRoot$1(getActiveDocumentChangeBuilder(editor).value, root), content]]);
47438
+ const input = ContentSlice.closed(kept);
46292
47439
  let applicable = false;
46293
47440
  const spec = createTransactionSpec(editor, () => {
46294
47441
  applicable = getEditorSchema(editor).fit(input, {
@@ -46376,16 +47523,27 @@ const deserializeSnapshotMeta = (editor, meta) => {
46376
47523
  }
46377
47524
  return nextMeta;
46378
47525
  };
47526
+ const keepSnapshotIds = (editor, input) => {
47527
+ const inputRoots = isRecord$5(input.roots) ? Object.entries(input.roots) : [];
47528
+ if (!Array.isArray(input.children) || input.roots !== void 0 && !isRecord$5(input.roots) || !inputRoots.every(([, nodes]) => Array.isArray(nodes))) return input;
47529
+ const current = getActiveDocumentChangeBuilder(editor).value;
47530
+ const [children, ...roots] = keepElementIds(editor, [[current.children, input.children], ...inputRoots.map(([root, nodes]) => [valueRoot$1(current, root), nodes])]);
47531
+ return children === input.children && roots.every((nodes, at) => nodes === inputRoots[at][1]) ? input : {
47532
+ children,
47533
+ ...input.roots === void 0 ? {} : { roots: Object.fromEntries(inputRoots.map(([root], at) => [root, roots[at]])) }
47534
+ };
47535
+ };
46379
47536
  const replaceTransformedSnapshot = (editor, transformedInput, replacedRoot) => {
46380
47537
  const apply = () => {
46381
47538
  const snapshotInput = readDirectSnapshotInput(editor, transformedInput);
47539
+ const { children, roots } = keepSnapshotIds(editor, snapshotInput);
46382
47540
  const transaction = getTransactionSnapshot(editor);
46383
47541
  const explicitSelection = snapshotInput.selection && snapshotInput.selection !== "start" && snapshotInput.selection !== "end" ? snapshotInput.selection : null;
46384
47542
  const selectedRoot = replacedRoot ?? (explicitSelection ? SelectionApi.root(explicitSelection) ?? "main" : "main");
46385
47543
  const fitted = getEditorSchema(editor).fitDocument({
46386
- children: snapshotInput.children,
47544
+ children,
46387
47545
  ...snapshotInput.meta === void 0 ? {} : { meta: snapshotInput.meta },
46388
- ...snapshotInput.roots === void 0 ? {} : { roots: snapshotInput.roots }
47546
+ ...roots === void 0 ? {} : { roots }
46389
47547
  });
46390
47548
  const representationSelection = snapshotInput.selection && snapshotInput.selection !== "start" && snapshotInput.selection !== "end" ? SelectionApi.isNode(snapshotInput.selection) ? SelectionApi.nodes(snapshotInput.selection.paths, {
46391
47549
  anchorPath: snapshotInput.selection.anchorPath,
@@ -46396,7 +47554,7 @@ const replaceTransformedSnapshot = (editor, transformedInput, replacedRoot) => {
46396
47554
  anchor: stripLocationRoots(snapshotInput.selection.anchor),
46397
47555
  focus: stripLocationRoots(snapshotInput.selection.focus)
46398
47556
  } : null;
46399
- const selectedInputChildren = selectedRoot === "main" ? snapshotInput.children : snapshotInput.roots?.[selectedRoot];
47557
+ const selectedInputChildren = selectedRoot === "main" ? children : roots?.[selectedRoot];
46400
47558
  const protectedInlineSpacerPaths = representationSelection && RangeApi.isRange(representationSelection) ? getProtectedInlineSpacerEntries(editor, selectedInputChildren ?? [], [representationSelection.anchor, representationSelection.focus]).map(({ path }) => path) : [];
46401
47559
  if (transaction) transaction.protectedInlineSpacerPaths.set(selectedRoot, protectedInlineSpacerPaths);
46402
47560
  const fittedRoots = {
@@ -46407,7 +47565,7 @@ const replaceTransformedSnapshot = (editor, transformedInput, replacedRoot) => {
46407
47565
  for (const root of Object.keys(fittedRoots).sort((left, right) => left === "main" ? -1 : right === "main" ? 1 : left.localeCompare(right))) {
46408
47566
  if (replacedRoot !== void 0 && root !== replacedRoot) continue;
46409
47567
  const selectedSource = root === selectedRoot && selectedInputChildren ? selectedInputChildren : fittedRoots[root];
46410
- applyTransactionSpec(editor, createRootFitTransactionSpec(editor, root, ContentSlice.closed(selectedSource), root === selectedRoot ? representationSelection ?? void 0 : void 0));
47568
+ applyTransactionSpec(editor, createRootFitTransactionSpec(editor, root, selectedSource, root === selectedRoot ? representationSelection ?? void 0 : void 0));
46411
47569
  }
46412
47570
  for (const root of Object.keys(currentRoots).sort()) if (replacedRoot === void 0 && root !== "main" && !Object.hasOwn(fittedRoots, root) && Object.hasOwn(getEditorDocumentRoots(editor), root)) applyDocumentChangeStep(editor, getActiveDocumentChangeBuilder(editor).deleteRoot(root));
46413
47571
  if (replacedRoot === void 0) {
@@ -46495,20 +47653,22 @@ const initializeEditorSchemaSnapshot = (editor, transformedInput) => {
46495
47653
  ...snapshotInput.meta === void 0 ? {} : { meta: snapshotInput.meta },
46496
47654
  ...snapshotInput.roots === void 0 ? {} : { roots: snapshotInput.roots }
46497
47655
  };
46498
- const fitted = representationSelection ? getEditorSchema(editor).fitDocumentWithSelection(inputDocument, {
47656
+ const ids = loadElementIds(getCompiledEditorSchema(editor), inputDocument, editorDocumentAdmission(editor));
47657
+ const fit = () => representationSelection ? getEditorSchema(editor).fitDocumentWithSelection(inputDocument, {
46499
47658
  root: selectedRoot,
46500
47659
  selection: representationSelection
46501
47660
  }) : {
46502
47661
  document: getEditorSchema(editor).fitDocument(inputDocument),
46503
47662
  selection: void 0
46504
47663
  };
47664
+ const fitted = ids ? ids.withStandInIds(fit) : fit();
46505
47665
  const meta = deserializeSnapshotMeta(editor, fitted.document.meta);
46506
47666
  const document = withValueRecords({
46507
47667
  children: fitted.document.children,
46508
47668
  ...Object.keys(meta).length === 0 ? {} : { meta },
46509
47669
  ...fitted.document.roots === void 0 ? {} : { roots: fitted.document.roots }
46510
47670
  }, collectValueRecords(snapshotInput, getCompiledEditorSchema(editor)?.recordSets ?? /* @__PURE__ */ new Map()));
46511
- const admitted = admitEditorDocument(editor, document);
47671
+ const admitted = admitEditorDocument(editor, document, ids);
46512
47672
  initializeEditorSchemaDocument(editor, admitted.document, getCompiledEditorSchema(editor));
46513
47673
  const fittedSelection = representationSelection ? fitted.selection : snapshotInput.selection;
46514
47674
  const selectionInput = fittedSelection === "start" || fittedSelection === "end" ? fittedSelection : mapSelectionThroughChange(editor, fittedSelection ?? null, admitted.change, document, admitted.document, selectedRoot, {
@@ -46998,15 +48158,22 @@ const takeCompositionStamp = (editor) => {
46998
48158
  return stamp;
46999
48159
  };
47000
48160
  /** @internal */
47001
- const stampFrame = (stamp, place) => {
48161
+ const stampFrame = (stamp, place, options) => {
47002
48162
  const frame = {
48163
+ explicit: options?.explicit ?? stamp !== null,
47003
48164
  located: null,
47004
- stamp
48165
+ resolvePlace: options?.resolvePlace,
48166
+ stamp,
48167
+ used: false
47005
48168
  };
47006
48169
  PLACES.set(place, frame);
47007
48170
  return frame;
47008
48171
  };
47009
48172
  /** @internal */
48173
+ const setFrameStamp = (frame, stamp) => {
48174
+ if (frame && !frame.explicit) frame.stamp = stamp;
48175
+ };
48176
+ /** @internal */
47010
48177
  const runStampedFrame = (editor, frame, run) => {
47011
48178
  if (!frame) return run();
47012
48179
  const owner = getEditorRuntimeOwner(editor);
@@ -47018,26 +48185,21 @@ const runStampedFrame = (editor, frame, run) => {
47018
48185
  }
47019
48186
  };
47020
48187
  /** @internal */
47021
- const recordLocatedDestination = (place, at) => {
48188
+ const recordLocatedDestination = (place, at, storedAt) => {
47022
48189
  const frame = PLACES.get(place);
47023
- if (frame && !frame.located) frame.located = { at };
48190
+ if (!frame || frame.located) return;
48191
+ frame.located = { at };
48192
+ if (!frame.explicit && storedAt !== void 0 && frame.resolvePlace) frame.stamp = frame.resolvePlace(storedAt);
47024
48193
  };
47025
- /**
47026
- * Runs insert-text's own text write, tagged as the composition's when the
47027
- * write is the stamped invocation's: to the destination its entry located,
47028
- * with no caret placed since its frame began. The command registry refuses an
47029
- * insert-text command nested in another, so only the stamped invocation's
47030
- * build runs here. The tags live on the draft the write appends to, so a
47031
- * draft discarded later takes them with it.
47032
- *
47033
- * @internal
47034
- */
47035
- const writeComposedText = (editor, at, text, write) => {
48194
+ /** @internal */
48195
+ const writeComposedText = (editor, at, text, write, movedCaret = false) => {
47036
48196
  const owner = getEditorRuntimeOwner(editor);
47037
48197
  const frame = FRAMES.get(owner);
47038
- const builder = !!frame?.located && text.length > 0 && frame.located.at === at && getPlacementCount(owner) === 0 ? getTransactionSnapshot(owner)?.builder : void 0;
47039
- if (frame && builder) builder.withComposition(frame.stamp, write);
47040
- else write();
48198
+ const builder = !!frame?.stamp && !!frame.located && text.length > 0 && frame.located.at === at && getPlacementCount(owner) === (movedCaret ? 1 : 0) ? getTransactionSnapshot(owner)?.builder : void 0;
48199
+ if (frame?.stamp && builder) {
48200
+ frame.used = true;
48201
+ builder.withComposition(frame.stamp, write);
48202
+ } else write();
47041
48203
  };
47042
48204
  //#endregion
47043
48205
  //#region src/core/editor-commands.ts
@@ -47046,7 +48208,12 @@ const resolveCommandRange = (state, at) => {
47046
48208
  if (at === void 0) return state.selection() ?? void 0;
47047
48209
  return RangeApi.isRange(at) ? at : state.ranges.get(at);
47048
48210
  };
47049
- const readCommandTarget = (state, at) => at ?? (state.selection() === null ? null : peekImplicitTarget(getActiveCommandEditor()));
48211
+ const readCommandTarget = (state, at) => {
48212
+ if (at !== void 0) return at;
48213
+ if (state.selection() === null) return null;
48214
+ const editor = getActiveCommandEditor();
48215
+ return peekImplicitTarget(editor) ?? getCurrentSelection(editor);
48216
+ };
47050
48217
  const readLandingRange = (state, target) => !target || SelectionApi.isNode(target) ? null : resolveCommandRange(state, target) ?? null;
47051
48218
  const equalsInRoot = (point, target) => {
47052
48219
  if (!point) return false;
@@ -47057,7 +48224,11 @@ const equalsInRoot = (point, target) => {
47057
48224
  };
47058
48225
  const selectMovedTarget = (tx, state, at, target) => {
47059
48226
  const stored = state.selection();
47060
- if (at === void 0 && RangeApi.isRange(target) && !(stored && equalsInRoot(stored.anchor, target.anchor) && equalsInRoot(stored.focus, target.focus))) tx.selection.set(target);
48227
+ if (at === void 0 && RangeApi.isRange(target) && !(stored && equalsInRoot(stored.anchor, target.anchor) && equalsInRoot(stored.focus, target.focus))) {
48228
+ tx.selection.set(target);
48229
+ return true;
48230
+ }
48231
+ return false;
47061
48232
  };
47062
48233
  const withPointRoot = (point, root) => point && root !== void 0 ? {
47063
48234
  ...point,
@@ -47450,6 +48621,7 @@ const editorCommands = Object.freeze({
47450
48621
  }),
47451
48622
  deleteFragment: defineCommand$1("fragment.delete", {
47452
48623
  locate: (input, place) => {
48624
+ removesAtPlace(place, input.at);
47453
48625
  if (input.at === void 0) return input;
47454
48626
  const at = place.location(input.at);
47455
48627
  return at === null ? null : {
@@ -47497,7 +48669,7 @@ const editorCommands = Object.freeze({
47497
48669
  insertText: defineCommand$1("text.insert", {
47498
48670
  locate: (input, place) => {
47499
48671
  const located = locateTextOptionsAt(input, place);
47500
- if (located) recordLocatedDestination(place, located.options?.at);
48672
+ if (located) recordLocatedDestination(place, located.options?.at, input.options?.at);
47501
48673
  return located;
47502
48674
  },
47503
48675
  build: ({ input, state }) => {
@@ -47554,8 +48726,8 @@ const editorCommands = Object.freeze({
47554
48726
  if (typing) setNextKeyMarks(getActiveCommandEditor());
47555
48727
  });
47556
48728
  return state.transaction((tx) => {
47557
- selectMovedTarget(tx, state, input.options?.at, target);
47558
- writeComposedText(getActiveCommandEditor(), input.options?.at, input.text, () => tx.text.insert(input.text, input.options));
48729
+ const moved = selectMovedTarget(tx, state, input.options?.at, target);
48730
+ writeComposedText(getActiveCommandEditor(), input.options?.at, input.text, () => tx.text.insert(input.text, input.options), moved);
47559
48731
  });
47560
48732
  }
47561
48733
  }),
@@ -48443,6 +49615,14 @@ const runSelectionOnlyInEditorUpdate = (editor, declaration, run) => {
48443
49615
  const TEXT_STARTS = /* @__PURE__ */ new WeakMap();
48444
49616
  const ELEMENT_ID_PLACES = /* @__PURE__ */ new WeakMap();
48445
49617
  const OPTION_PLACES = /* @__PURE__ */ new WeakMap();
49618
+ const REMOVALS = /* @__PURE__ */ new WeakMap();
49619
+ /**
49620
+ * Tells a frame that its command removes `at`, or the selection without one,
49621
+ * so a removal of content the frame hides still reaches the recorder.
49622
+ *
49623
+ * @internal
49624
+ */
49625
+ const removesAtPlace = (place, at) => REMOVALS.get(place)?.(at);
48446
49626
  /** @internal */
48447
49627
  const placeElementIdIn = (place, id) => getDefined(ELEMENT_ID_PLACES.get(place))(id);
48448
49628
  const TARGET_OPTIONS = [
@@ -48578,6 +49758,7 @@ const keepWhereHeld = () => {};
48578
49758
  const createFramePlace = (editor, projected, stored, storedIndex, selectionRoot, refuse, stamp = null, refusesStruckTargets = true) => {
48579
49759
  let heldRefusal = null;
48580
49760
  let located = false;
49761
+ let removal = null;
48581
49762
  const compositionRoot = stamp && (stamp.place.root ?? selectionRoot);
48582
49763
  const compositionElement = stamp && compositionRoot !== null ? projected.map.nodePath(compositionRoot, stamp.place.path.slice(0, -1)) : null;
48583
49764
  const nodes = (selection, fallbackRoot) => {
@@ -48602,13 +49783,15 @@ const createFramePlace = (editor, projected, stored, storedIndex, selectionRoot,
48602
49783
  const position = projected.map.toProjected(root, valueRootIndex(stored, root).positionAt(point), mapAssoc < 0 ? "backward" : "forward");
48603
49784
  return position === null ? null : pointIn(point, root, position, assoc);
48604
49785
  };
48605
- const pointOnCompositionSide = (after, root, position, side) => {
49786
+ const pointOnStoredSide = (after, root, position, side, point) => {
48606
49787
  const placed = after.pointAt(position, side);
48607
- if (!compositionElement || root !== compositionRoot || !placed) return placed;
48608
- const inCompositionElement = (at) => PathApi.equals(at.path.slice(0, -1), compositionElement);
48609
- if (inCompositionElement(placed)) return placed;
49788
+ if (!placed) return placed;
49789
+ const element = compositionElement && root === compositionRoot ? compositionElement : hiddenCaretStamp(editor, stored, projected, point, root) ? projected.map.nodePath(root, point.path.slice(0, -1)) : null;
49790
+ if (!element) return placed;
49791
+ const inElement = (at) => PathApi.equals(at.path.slice(0, -1), element);
49792
+ if (inElement(placed)) return placed;
48610
49793
  const other = after.pointAt(position, side < 0 ? 1 : -1);
48611
- return other && inCompositionElement(other) ? other : placed;
49794
+ return other && inElement(other) ? other : placed;
48612
49795
  };
48613
49796
  const pointIn = (point, root, position, assoc) => {
48614
49797
  const after = projectedIndex(projected, root);
@@ -48616,7 +49799,7 @@ const createFramePlace = (editor, projected, stored, storedIndex, selectionRoot,
48616
49799
  const [previous] = position > 0 ? after.slice(position - 1, position).tokens : [];
48617
49800
  const isElement = (token, kind) => token?.kind === kind && token.nodeKind === "element";
48618
49801
  const side = isElement(next, "close") && previous?.kind !== "open" && !isElement(previous, "close") ? -1 : isElement(previous, "open") && next?.kind !== "close" && !isElement(next, "open") ? 1 : assoc;
48619
- const placed = pointOnCompositionSide(after, root, position, side);
49802
+ const placed = pointOnStoredSide(after, root, position, side, point);
48620
49803
  return placed && {
48621
49804
  ...point,
48622
49805
  offset: placed.offset,
@@ -48876,6 +50059,9 @@ const createFramePlace = (editor, projected, stored, storedIndex, selectionRoot,
48876
50059
  TEXT_STARTS.set(place, startsInStruckText);
48877
50060
  ELEMENT_ID_PLACES.set(place, placeElementId);
48878
50061
  OPTION_PLACES.set(place, placeOptions);
50062
+ REMOVALS.set(place, (at) => {
50063
+ removal = { at };
50064
+ });
48879
50065
  const placeSelection = (selection, root, onRefuse) => {
48880
50066
  if (selection?.kind !== "text") {
48881
50067
  if (selection) refusesStruck(selection.paths, SelectionApi.root(selection) ?? root, onRefuse);
@@ -48896,6 +50082,7 @@ const createFramePlace = (editor, projected, stored, storedIndex, selectionRoot,
48896
50082
  heldRefusal ??= reason;
48897
50083
  }),
48898
50084
  located: () => located,
50085
+ removal: () => removal,
48899
50086
  place,
48900
50087
  /**
48901
50088
  * Refuses a body that placed no location, which acts at the selection,
@@ -48944,6 +50131,15 @@ const effectChange = (projected, stored, wrote, recorded) => {
48944
50131
  return typeof value === "function" ? value.bind(change) : value;
48945
50132
  } });
48946
50133
  };
50134
+ const hiddenCaretStamp = (editor, stored, projected, target, fallbackRoot) => {
50135
+ if (!hasEditorContent(editor)) return null;
50136
+ const point = !NodeApi.isDescendant(target) && PointApi.isPoint(target) ? target : !NodeApi.isDescendant(target) && RangeApi.isRange(target) && PointApi.equals(target.anchor, target.focus) ? target.anchor : null;
50137
+ if (!point) return null;
50138
+ const root = point.root ?? fallbackRoot;
50139
+ if (!projected.map.roots.includes(root)) return null;
50140
+ const leaf = nodeAt$1(valueRootNodes(stored, root), point.path);
50141
+ return leaf !== void 0 && !isEditorContent(editor, leaf) ? { place: point } : null;
50142
+ };
48947
50143
  /** @internal */
48948
50144
  const runInEditorCommandFrame = (editor, body, { framedOn, ignoresSelection = false, refusesStruckTargets = true, targetRoot } = {}) => {
48949
50145
  const document = getEditorCommandDocument(editor);
@@ -48951,16 +50147,20 @@ const runInEditorCommandFrame = (editor, body, { framedOn, ignoresSelection = fa
48951
50147
  const outer = getTransactionSpecContext(editor);
48952
50148
  if (!document || !recorder || outer?.kind !== "update" || COMMAND_FRAMES.has(editor)) return null;
48953
50149
  runEditorDocumentRecorder(editor);
48954
- const stamp = takeCompositionStamp(editor);
50150
+ const explicitStamp = takeCompositionStamp(editor);
48955
50151
  const stored = outer.snapshot.builder.value;
48956
50152
  if (framedOn && (stored.children !== framedOn.children || outer.caret.generation !== framedOn.generation)) throw new Error("Cannot apply a stale framed spec.");
48957
50153
  const projected = document.project(stored);
48958
50154
  if (!projected) return null;
50155
+ const stamp = explicitStamp ?? hiddenCaretStamp(editor, stored, projected, outer.snapshot.implicitTargetResolved ? outer.snapshot.implicitTarget : outer.caret.selection, outer.caret.root);
48959
50156
  const storedIndex = (root) => retainTransactionSnapshotIndex(editor, outer.snapshot, root);
48960
50157
  const placed = createFramePlace(editor, projected, stored, storedIndex, outer.caret.root, (reason) => {
48961
50158
  throw refusedIn(editor, reason);
48962
50159
  }, stamp, refusesStruckTargets);
48963
- const stamped = stamp && stampFrame(stamp, placed.place);
50160
+ const stamped = stampFrame(stamp, placed.place, {
50161
+ explicit: explicitStamp !== null,
50162
+ resolvePlace: (at) => hiddenCaretStamp(editor, stored, projected, at, getEditorUpdateRoot(editor))
50163
+ });
48964
50164
  const selection = placed.held(outer.caret.selection);
48965
50165
  const target = outer.snapshot.implicitTarget ? placed.held(outer.snapshot.implicitTarget) : null;
48966
50166
  const run = body(placed.place);
@@ -48975,7 +50175,8 @@ const runInEditorCommandFrame = (editor, body, { framedOn, ignoresSelection = fa
48975
50175
  let written = null;
48976
50176
  let storedToWritten;
48977
50177
  let letters;
48978
- let runs = [];
50178
+ let steps = [];
50179
+ let landing = null;
48979
50180
  COMMAND_FRAMES.add(editor);
48980
50181
  try {
48981
50182
  enterFrameDraft(editor, frame, stored, projected, storedIndex, outer.caret.selection, outer.caret.root, selection, placed.bookCaret);
@@ -48984,7 +50185,10 @@ const runInEditorCommandFrame = (editor, body, { framedOn, ignoresSelection = fa
48984
50185
  else snapshot.implicitTargetFrame = {
48985
50186
  context: frame,
48986
50187
  storedSelection: outer.caret.selection,
48987
- toFrame: placed.selection
50188
+ toFrame: (moved) => {
50189
+ setFrameStamp(stamped, hiddenCaretStamp(editor, stored, projected, moved, outer.caret.root));
50190
+ return placed.selection(moved);
50191
+ }
48988
50192
  };
48989
50193
  if (!runStampedFrame(editor, stamped, () => withTransactionSpecDraftRead(editor, run))) return false;
48990
50194
  assertWritesPlaced(editor, snapshot);
@@ -49004,48 +50208,65 @@ const runInEditorCommandFrame = (editor, body, { framedOn, ignoresSelection = fa
49004
50208
  start: projected,
49005
50209
  stored
49006
50210
  });
49007
- runs = draftRunsOf(snapshot.builder.draftSteps, projected.map.toStored);
49008
- if (!wrote.empty || frame.selectionWritten) {
50211
+ steps = snapshot.builder.draftSteps;
50212
+ const removed = placed.removal();
50213
+ const removedRange = removed && (removed.at === void 0 ? outer.caret.selection : removed.at);
50214
+ const removal = removed && RangeApi.isRange(removedRange) && RangeApi.isExpanded(removedRange) ? {
50215
+ root: removed.at === void 0 ? outer.caret.root : removedRange.anchor.root ?? getEditorUpdateRoot(editor),
50216
+ selection: removedRange
50217
+ } : null;
50218
+ const hidden = wrote.empty && !frame.selectionWritten && removal !== null;
50219
+ if (!wrote.empty || frame.selectionWritten || hidden) {
49009
50220
  const inFrame = (root) => Object.hasOwn(snapshot.roots, root);
49010
50221
  const changed = carryCarets(editor, outer.baseCaret, frame.caret, (root) => inFrame(root) ? retainTransactionSnapshotIndex(editor, snapshot, root) : storedIndex(root));
49011
50222
  const framed = changed && {
49012
50223
  ...changed,
49013
50224
  moved: changed.moved.filter(({ root }) => inFrame(root))
49014
50225
  };
49015
- recorded = recorder({
50226
+ const recording = recorder({
49016
50227
  after: snapshot.builder.value,
49017
50228
  before: stored,
49018
50229
  bookmarks: recorderBookmarks(framed),
49019
50230
  change: wrote,
50231
+ ...removal ? { removal } : {},
49020
50232
  projection: projected,
49021
50233
  selection: frame.caret.selection,
49022
50234
  selectionBefore: outer.caret.selection,
49023
50235
  selectionBeforeRoot: outer.caret.root,
49024
50236
  selectionRoot: frame.caret.root,
49025
- composition: stamp,
50237
+ composition: stamped.used ? stamped.stamp : explicitStamp,
49026
50238
  steps: snapshot.builder.draftSteps,
49027
50239
  tags: getActiveEditorUpdateTags(editor),
49028
50240
  update: outer.id
49029
50241
  });
49030
- if (!recorded) throw new Error("A command frame needs a recorder that records it.");
49031
- carryDraftNodeKeys(editor, snapshot, recorded, {
49032
- before: projected.value,
49033
- change: wrote
49034
- }, keysReadIn(snapshot));
49035
- letters = snapshot.builder.newLetters;
49036
- const converted = recordedCarets(framed, recorded);
49037
- carried = converted && {
49038
- ...converted,
49039
- moved: [...converted.moved, ...changed?.moved.filter(({ root }) => !inFrame(root)) ?? []]
49040
- };
49041
- written = {
49042
- change: wrote,
49043
- frame: {
49044
- selection: frame.caret.selection,
49045
- value: snapshot.builder.value
49046
- }
49047
- };
50242
+ recorded = hidden && recording?.change.empty ? null : recording;
50243
+ if (!recorded && !hidden) throw new Error("A command frame needs a recorder that records it.");
50244
+ if (recorded) {
50245
+ carryDraftNodeKeys(editor, snapshot, recorded, {
50246
+ before: projected.value,
50247
+ change: wrote
50248
+ }, keysReadIn(snapshot));
50249
+ letters = snapshot.builder.newLetters;
50250
+ const converted = recordedCarets(framed, recorded);
50251
+ carried = converted && {
50252
+ ...converted,
50253
+ moved: [...converted.moved, ...changed?.moved.filter(({ root }) => !inFrame(root)) ?? []]
50254
+ };
50255
+ written = {
50256
+ change: wrote,
50257
+ frame: {
50258
+ selection: frame.caret.selection,
50259
+ value: snapshot.builder.value
50260
+ }
50261
+ };
50262
+ }
49048
50263
  }
50264
+ const track = frame.lastSpecLanding;
50265
+ const spans = track && recorded && settleDraftTrack(track);
50266
+ if (track && spans?.length) landing = {
50267
+ root: track.root,
50268
+ spans
50269
+ };
49049
50270
  if (snapshot.effects.length > 0) {
49050
50271
  const toStored = effectChange(projected, stored, wrote, recorded?.change ?? null);
49051
50272
  for (const effect of snapshot.effects) {
@@ -49079,16 +50300,22 @@ const runInEditorCommandFrame = (editor, body, { framedOn, ignoresSelection = fa
49079
50300
  disposeTransactionSpecContext(editor, frame);
49080
50301
  }
49081
50302
  if (!recorded) {
50303
+ if (steps.length > 0) outer.snapshot.publishesUnknownFacts = true;
49082
50304
  setTypedMarks(editor, typedAfter);
49083
50305
  return true;
49084
50306
  }
49085
50307
  commitRecordedDraft(editor, outer, recorded, frame.caret.root, {
49086
50308
  carried,
50309
+ writtenLanding: landing,
49087
50310
  letters,
49088
- runs,
50311
+ plainSteps: {
50312
+ steps,
50313
+ toStored: projected.map.toStored
50314
+ },
49089
50315
  storedToWritten,
49090
50316
  typed: typedAfter
49091
50317
  });
50318
+ if (recorded.historyBoundary) applyEditorUpdateTag(outer.snapshot.tags, HISTORY_BOUNDARY_TAG);
49092
50319
  outer.changed = true;
49093
50320
  if (written) document.recorded?.({
49094
50321
  ...written,
@@ -50968,7 +52195,9 @@ const buildConfiguredRegistry = (editor, previousRegistry, previousSchemaRevisio
50968
52195
  if (loadsInitialValue(options)) {
50969
52196
  loadOpenedRecords(editor, mergedCandidate.schemaContributions.compiled);
50970
52197
  const loaded = getEditorDocumentValue(editor);
50971
- const repair = repairLoadedDocument(onlyDocumentAdmission(getRegistryContributions(mergedCandidate, documentAdmissionPoint)), loaded, mergedCandidate.schemaContributions.compiled);
52198
+ const { compiled } = mergedCandidate.schemaContributions;
52199
+ const admission = onlyDocumentAdmission(getRegistryContributions(mergedCandidate, documentAdmissionPoint));
52200
+ const repair = repairLoadedDocument(admission, loaded, compiled, loadElementIds(compiled, loaded, admission));
50972
52201
  return Object.freeze({
50973
52202
  configured: candidate,
50974
52203
  documentChange: repair ? repair.change.compose(constructLoadedDocumentChange(editor, repair.value, schema)) : constructLoadedDocumentChange(editor, loaded, schema),
@@ -50995,9 +52224,13 @@ const buildConfiguredRegistry = (editor, previousRegistry, previousSchemaRevisio
50995
52224
  ...migrated.roots !== void 0 ? { roots: migrated.roots } : {}
50996
52225
  };
50997
52226
  })() : currentDocument;
50998
- const fitted = options.migrate ? classifyCandidatePublicationDocument(editor, schema, currentDocument, inputDocument) : fitCandidatePublicationDocument(editor, schema, currentDocument, inputDocument);
52227
+ const { compiled } = mergedCandidate.schemaContributions;
52228
+ const admission = onlyDocumentAdmission(getRegistryContributions(mergedCandidate, documentAdmissionPoint));
52229
+ const ids = options.initializeDocument ? loadElementIds(compiled, inputDocument, admission) : null;
52230
+ const fit = () => fitCandidatePublicationDocument(editor, schema, currentDocument, inputDocument);
52231
+ const fitted = options.migrate ? classifyCandidatePublicationDocument(editor, schema, currentDocument, inputDocument) : ids ? ids.withStandInIds(fit) : fit();
50999
52232
  if (!options.initializeDocument && !options.migrate && !fitted.change.empty) throw new EditorSchemaValidationError("Editor schema reconfiguration requires an explicit migration when the current document is not canonical under the candidate schema.");
51000
- const repair = repairLoadedDocument(onlyDocumentAdmission(getRegistryContributions(mergedCandidate, documentAdmissionPoint)), fitted.document, mergedCandidate.schemaContributions.compiled);
52233
+ const repair = repairLoadedDocument(admission, fitted.document, compiled, ids);
51001
52234
  documentChange = repair ? classifyCandidatePublicationDocument(editor, schema, currentDocument, repair.value).change : fitted.change;
51002
52235
  }
51003
52236
  }
@@ -51502,4 +52735,4 @@ const extendEditor = (editor, input, options = {}) => {
51502
52735
  };
51503
52736
  };
51504
52737
  //#endregion
51505
- export { first as $, restoreHistoryCarets as $a, mergeAnchorHistoryRecovery as $c, pathKey$2 as $d, PathApi as $f, trackDraftSpans as $i, tracksPlaces as $l, getEditorRuntimeElementEntries as $n, onlyDocumentAdmission as $o, setCurrentSelection as $r, orphanedRoots as $s, setPoint as $t, createInternalRootChangeFromSections as $u, definePluginSlot as A, leftWithNoGridPart as Aa, getExactDocumentChangeRelocation as Ac, propertyDeltaFromModifications as Ad, decodeVersionedValue as Af, planPaste as Ai, areEditorSchemaIdentitiesEqual as Al, finalizeTransactionRepresentation as An, withMountedPresentation as Ao, isNotifyingNestedCommit as Ar, rawNodeAt as As, last as At, UNSCOPED_ORIGINS as Au, NodeApi as B, getCaretOwner as Ba, readShownPreview as Bc, rootNodesOf as Bd, defineEffect as Bf, readRootViewPresentationRevision as Bi, holdsUniqueKey as Bl, getChildren$1 as Bn, mapSemanticUpdateMethodArguments as Bo, recordEditorHistoryReplayReceipt as Br, isEmptyElement as Bs, point as Bt, historyFollowsAllFacts as Bu, setPluginPortalFactory as C, getCharacterDistance as Ca, getEditorCommitUnsettle as Cc, addSection as Cd, showValueRecords as Cf, withEditorRootChildrenGenerator as Ci, getPluginContributions as Cl, applyUnnamedDocumentChange as Cn, mountViewPeer as Co, initializeEditorSchemaSelection as Cr, decodeEditorSelection as Cs, isElementReadOnly as Ct, getEditorRuntime as Cu, property as D, gridHoldersOf as Da, readRootEntries as Dc, getDocumentPropertyContext as Dd, assertEditorJsonValue as Df, setTargetRuntime as Di, markDefinedStateField as Dl, continueTransactionSpecOrDiscardPrefix as Dn, readViewPage as Do, isBuildingTransactionSpec as Dr, mapDetachedSelectionThroughChange as Ds, isSelectable as Dt, hasEditorRuntime as Du, getSchemaElementSourceReference as E, isTextCell as Ea, keyMovedAt as Ec, applyPropertyModificationsToSlice as Ed, areEditorJsonValuesEqual as Ef, withUpdateTagContext as Ei, initializeBasePluginRegistry as El, attachTransactionSpecAfterCommit as En, readShownRecords as Eo, invalidateEditorTransactionSpecs as Er, isObjectSelectionTarget as Es, isInline as Et, getEditorSchema as Eu, getActiveCommandEditor as F, capturePlacement as Fa, createEditorAnchorApi as Fc, DocumentIndex as Fd, snapshotEditorJsonValue as Ff, readCaretViewIn as Fi, getCompiledPropertyMergeStrategy as Fl, getActiveEditorUpdateId as Fn, subscribe as Fo, readEditorCommitHistoryEntry as Fr, completeChildrenAt as Fs, move as Ft, UNKNOWN_FACTS as Fu, collapse as G, keepBookmark as Ga, assertNoDocumentViewRead as Gc, PreparedTokenSliceStructureError as Gd, RangeApi as Gf, subscribeRootViewPresentation as Gi, propertyTargetsReadParents as Gl, getCurrentSelectionRoot as Gn, txLocate as Go, replaceSliceAtBlockBoundary as Gr, readingCovered as Gs, read as Gt, invertCarriedRun as Gu, addMark as H, getRangeBreakCount as Ha, requestAuthoredView as Hc, normalizeSetValues as Hd, invertEffect as Hf, readShownViewUse as Hi, isSupportedGeneratedElementProperty as Hl, getCollabEffects$1 as Hn, getRootTransaction as Ho, registerEditorSurface as Hr, EditorSchemaValidationError as Hs, previous as Ht, carriedLetterPairs as Hu, hasCommandHandler as I, changedBookmarks as Ia, configureAuthoredView as Ic, NO_NODES as Id, supportsEditorValuePersistenceVersion as If, readLatestShownWritableRootView as Ii, getCompiledSchemaPropertyId as Il, getActiveEditorUpdateTags as In, subscribeCommit as Io, readEditorHistoryHeadRoots as Ir, constructCanonicalDocumentChange as Is, moveNodes as It, composeFacts as Iu, deleteForward as J, nextMintedGeneration as Ja, withDocumentViewRead as Jc, getDocumentSliceNodeKeys as Jd, PointApi as Jf, getContentSlice as Ji, resolveCompiledSchemaProperty as Jl, getEditorDocumentValue as Jn, txStored as Jo, saveEditorSchemaDocument as Jr, isLeftOutDefault as Js, replace as Jt, widenRun as Ju, deleteBackward as K, liftShownTarget as Ka, isDocumentView as Kc, closeToken as Kd, LocationApi as Kf, subscribeShownViewUse as Ki, readEditorSchemaContract as Kl, getEditorChildrenRoot as Kn, txOnly as Ko, resolveEditorNodeKeyForNode as Kr, carriesDefault as Ks, removeMark as Kt, landCarriedRuns as Ku, probeCommandNativeEquivalent as L, clearCaretUnlessHeldElsewhere as La, getAuthoredUpdateView as Lc, childAtPathIndex as Ld, textPropertiesEqual as Lf, readLatestShownWritableView as Li, handoverKeysOf as Ll, getAppliedSpecLanding as Ln, subscribeSource$1 as Lo, readEditorHistoryReplayReceipt as Lr, constructLoadedDocumentChange as Ls, next as Lt, factsFromJSON as Lu, dispatchCommand as M, nodes as Ma, hasIndexedPathAncestor as Mc, markReadBack as Md, encodeVersionedValue as Mf, getSelectionStateCaret as Mi, crossesUniqueTarget as Ml, fitSlicePlacements as Mn, getStateViewPresentation as Mo, loadOpenedRecords as Mr, withLandedMarks as Ms, levels as Mt, letterOriginsOfChange as Mu, evaluateCommand as N, normalizeNodeMatch as Na, authoredDocumentCapabilityPoint as Nc, joinsOf as Nd, isEditorJsonValue as Nf, markRootViewUsed as Ni, diffEditorSchemaContracts as Nl, flushEditorViewState as Nn, onPresentationRelease as No, notifyPresentationViewState as Nr, sealsText as Ns, liftNodes as Nt, NO_FACTS as Nu, schema as O, gridPartsOf as Oa, snapshotIndexOf as Oc, keptRunsOf as Od, cloneEditorJsonValue as Of, resolveStateFieldInitial as Oi, registerEffectTypeInRegistry as Ol, createTransactionSpec as On, retainViewPresentation as Oo, isEditorPublishingCommit as Or, mapSelectionThroughChange as Os, isStart as Ot, setEditorRuntime as Ou, evaluateCommandWithState as P, node as Pa, isAuthorId as Pc, liftOf as Pd, normalizeEditorValuePersistence as Pf, mountRootView as Pi, getCompiledPropertyCandidates as Pl, getActiveEditorTransaction as Pn, retainPresentation as Po, readEditor as Pr, settleRange as Ps, mergeNodes as Pt, NO_ROOT_FACTS as Pu, elementReadOnly as Q, resolveParkedCaret as Qa, mapAnchorHistoryRecovery as Qc, openToken as Qd, getReaderRange as Qf, settleDraftTrack as Qi, toCompiledTargetContext as Ql, getEditorReadDepth as Qn, documentAdmissionPoint as Qo, setCurrentMarks as Qr, judgeProjectedRoots as Qs, setNodes as Qt, createInternalDocumentChange as Qu, commandViewHides as R, consumeCommitCarets as Ra, isAuthoredPreview as Rc, decodeNodes as Rd, valueCodecs as Rf, readNestedRootView as Ri, hasPlaceDependentElementProperty as Rl, getBaseCallRoot as Rn, createEditorReadApi as Ro, readElementById as Rr, fitImportedBlock as Rs, parent as Rt, factsToJSON as Ru, resolveInstalledPlugin as S, editorReads as Sa, getEditorCommitStartedAt as Sc, RootChange as Sd, recordSetIds as Sf, withEditorRootChildren as Si, getConfiguredPluginRegistry as Sl, applyTransactionSpecToDocument as Sn, matchesPresentationOf as So, initializeEditorSchemaDocument as Sr, assertSelectionSupported as Ss, isEditor as St, registerEditorCommandDocument as Su, withPluginPortalCandidates as T, getWordSegments as Ta, historyReplayClaim as Tc, applyPropertyModifications as Td, withoutValueRoots as Tf, withTransactionSpecDraftRead as Ti, inheritPluginRegistry as Tl, assertEditorExternalMutationAllowed as Tn, readShownDocument as To, initializePublicState as Tr, getSelectionDOMRange as Ts, isEnd as Tt, getEditorRuntimeRoot as Tu, after as U, holdsCaret as Ua, withAuthoredUpdateView as Uc, classifyRootChange as Ud, mapEffect as Uf, readShownWritableRootViews as Ui, matchesCompiledSchemaTarget as Ul, getCurrentMarks as Un, resolvePluginMethod as Uo, registerEditorTransactionGuard as Ur, adoptVerdicts as Us, projectRange as Ut, carriesRun as Uu, above as V, getPlacementGeneration as Va, registerAuthoredRuntime as Vc, canonicalJsonKey as Vd, defineUpdateAnnotation as Vf, readRootViewUse as Vi, isPlaceDependentElementProperty as Vl, getCollabEffectTypes as Vn, callPluginUpdateMethod as Vo, registerEditorHistoryRuntime as Vr, EditorNoncanonicalChangeError as Vs, positions as Vt, recordedFacts as Vu, before as W, holdsCaretAt as Wa, withStoredAuthoredRead as Wc, PreparedTokenSlice as Wd, readLastCommitAnnotation as Wf, subscribeRootTarget as Wi, preserveCompiledSchemaPropertyIdentity as Wl, getCurrentSelection as Wn, locateAt as Wo, repairEditorValue as Wr, judgedBy as Ws, range as Wt, exactRunOn as Wu, deselect as X, resolveBookmark as Xa, getMovableAnchors as Xc, isTextNode$3 as Xd, getCommonLocationRoot as Xf, readDraftTrack as Xi, splitDroppedKeysOf as Xl, getEditorNodeKeyForNode as Xn, admitDocument as Xo, seedUniqueMaps as Xr, readsAt as Xs, reset as Xt, alignedDocumentChange as Xu, deleteFragment as Y, placedSince as Ya, consumeAnchorHistoryCapture as Yc, isElementNode as Yd, MAIN_ROOT_KEY as Yf, assertEditorNotDestroyed as Yi, restoreEditorSchemaContract as Yl, getEditorMaxLength as Yn, DOCUMENT_SETTLED_TAG as Yo, scheduleAfterCommitNotification as Yr, isSplitOutput as Ys, replaceChildren as Yt, DocumentChange as Yu, edges as Z, resolveLiveCaret as Za, hasActiveAnchors as Zc, nodeProps as Zd, getRangeRoot as Zf, readDraftTrackAt as Zi, toCompiledNodeContext as Zl, getEditorProjectionSnapshotIndex as Zn, admitEditorDocument as Zo, setChildren as Zr, changedRootsOf as Zs, select as Zt, collapseDocumentElementPropertyWrites as Zu, markEditorDormant as _, before$1 as _a, getEditorCommitFacts as _c, valueRootIndex as _d, hasRecordWithPrefix as _f, trackEditorLetters as _i, setEditorLifecycleErrorSink as _l, afterActiveTransactionEnds as _n, getViewAuthor as _o, getTransactionSnapshot as _r, withoutGeneration as _s, insertSoftBreak as _t, setDebugValueScrubber as _u, compilePluginInput as a, rewriteContentRootReferences as aa, ownedRootsOf as ac, getInternalDocumentChangeEntries as ad, NO_RECORD_OPS as af, setEditorSnapshotInputTransform as ai, toInternalRoot as al, toggleBlock as an, watchFirstPlacement as ao, lazyRootOf as ap, getLiveSelection as ar, canonicalizeCompiledTextProperties as as, getNodeKey as at, readDocumentRecord as au, queueAfterPluginAcquisition as b, resolveShouldMergeNodesRemovePrevNode as ba, getEditorCommitSchemas as bc, withInternalDocumentRootChange as bd, recordOpsFromJson as bf, withDraftMove as bi, finalizePluginRegistry as bl, applyDocumentChange as bn, joinViewLockScope as bo, hasEditorSurface as br, withFitLanding as bs, isBlock as bt, isEditorContent as bu, defineEditorSchema as c, withLandingBlock as ca, lawCheckEnabled as cc, getInternalDocumentChangeRootKeys as cd, deriveValue as cf, setEditorViewing as ci, nodeWriteVeto as cl, unsetNodes as cn, createAuthoredEditorView as co, countCoreWork as cp, getNodeKey$1 as cr, generateElementPropertyValue as cs, getSelection as ct, readStoredEditorDocument as cu, extendEditor as d, readRemovalLanding as da, claimsHistoryReplay as dc, isDocumentRootKey as dd, getRecordIds as df, snapshotInitialDocumentState as di, publishEditorRefusal as dl, voidEditor as dn, createViewLockScope as do, deepFreeze as dp, getRestorableMarks as dr, getRepresentationEditorFromApi as ds, hasInlines as dt, definePluginPoint as du, isEditorDraftView as ea, orphanedValueRoots as ec, documentChangeBetween as ed, textToken as ef, setEditorComposing as ei, observeAnchorStateWork as el, setSelection as en, rootChildrenOf as eo, isObject as ep, getEditorRuntimeRootKeys as er, withoutRepairOrphans as es, fragment as et, uniquePropertiesOf as eu, getCandidatePluginApi as f, resolveDeletedRange as fa, createEditorCommit as fc, isInternalDocumentChangeNoop as fd, getRecordSetVersion as ff, subscribeCaretTarget as fi, subscribeEditorRefusals as fl, wrapNodes as fn, flushViewLockScope as fo, isRecord$5 as fp, getSelectionRoot as fr, holdsImportedRoot as fs, hasPath as ft, point$1 as fu, isPlugin as g, readOnlyInlineAt as ga, getEditorCommitCompletedTextDeletion as gc, valueRoot$1 as gd, hasRecord as gf, toEditorCoreStateView as gi, runEditorObserver as gl, withCompositionStamp as gn, getOwnViewReadOnly as go, getStateFieldEffectTypes as gr, readEmptyText as gs, insertNodes as gt, formatDebugValue as gu, getInstalledPluginApi as h, hasEdgeInReadOnlyInline as ha, getEditorCommitCarriedRuns as hc, transformInternalDocumentChange as hd, getValueRecords as hf, syncImplicitTargetToCurrentSelection as hi, reportEditorLifecycleError as hl, tripleClickedBlock as hn, getOwnViewPresentation as ho, getDefined as hp, getSnapshotVersion as hr, placeElementAt as hs, insertNode as ht, ElementApi as hu, compilePlugin as i, registerEditorFitsByLook as ia, ensureElementOwnedRootIndex as ic, getInternalDocumentChangeClassificationEntries as id, getNodeKeyForNode as if, setEditorReadOnly as ii, getPublicExplicitLocationRoot as il, subscribeSource as in, subscribeCommittedPlacement as io, isFrozenWithRoots as ip, getLiveNode as ir, canPlaceBlocksAtPath as is, getLastCommit as it, isEnvelopeInput as iu, createCommandDispatch as j, survivalUnder as ja, getExactDocumentChangeRelocations as jc, semanticPropertyModifications as jd, encodeEditorEffect as jf, writePaste as ji, compileEditorSchemaContributions as jl, fitSliceChildren as jn, getBaseViewPresentation as jo, isPresentationComposing as jr, settleSelectionMode as js, leaf as jt, classifyDocumentChange as ju, target as k, gridRolesOf as ka, getDocumentChangeRelocations as kc, mapRootChangePositionBackward as kd, decodeEditorEffect as kf, captureSliceLanding as ki, EditorSchemaCompileError as kl, documentReplacement as kn, setViewLockScopeLocked as ko, isInTransaction as kr, mapSelectionWithContext as ks, isVoid as kt, defineCommand$1 as ku, definePlugin as l, dividesTextCell as la, ContentSlice as lc, getInternalDocumentRootChange as ld, getRecordCount as lf, setRootCopyScope as li, vetoesWrite as ll, unwrapNodes as ln, createEditorView as lo, readCoreWork as lp, getNodeTargetRoot as lr, getCompiledEditorSchemaFromApi as ls, getSnapshot as lt, rejectEditorRecord as lu, getInstalledPlugin as m, elementReadOnly$1 as ma, getEditorCommitAdmission as mc, mapInternalDocumentChangePosition as md, getRecordsWithPrefix as mf, subscribePresentationComposition as mi, notifyObservers as ml, readWholeBlockLanding as mn, getCarriedMount as mo, cloneFrozen$1 as mp, getSnapshot$1 as mr, landNodePropertiesAt as ms, insertBreak as mt, SelectionApi as mu, brandPluginDescriptor as n, registerEditorDraftGuard as na, schemaHasContentRoots as nc, filterDocumentChangeRoots as nd, tokensEqual as nf, setEditorFocused as ni, stageAnchorHistoryRecovery as nl, splitNodes as nn, setSelectionAsView as no, copyRoot as np, getEditorUpdateRoot as nr, ElementGenerationMaskedError as ns, getCollabEffects as nt, assertEditorDocumentContainers as nu, containsCompleteEditorSchema as o, coversContent as oa, rebaseElementOwnedRootIndex as oc, getInternalDocumentChangeRanges as od, canonicalRecordJson as of, setEditorStateViewTransform as oi, toPublicRoot as ol, toggleMark as on, withoutPlacement as oo, setLazyRoot as op, getLiveText as or, createDetachedEditorSchema as os, getPathByNodeKey as ot, readEditorDocument as ou, getCompiledEditorConfiguration as p, removeNodes$1 as pa, getDocumentValueNode as pc, mapInternalDocumentChangePoint as pd, getRecordText as pf, subscribeEditorViewState as pi, REMOTE_UPDATE as pl, editorCommands as pn, getCarriedCaretEditor as po, jsonEqual$1 as pp, getSetSite as pr, holdsOneText as ps, hasTexts as pt, readTextEdge as pu, deleteEditor as q, mayClearCaret as qa, isDocumentViewReading as qc, encodeNodes as qd, SpanApi as qf, getFragment$1 as qi, readEditorSchemaIdentity as ql, getEditorDocumentRecords as qn, txSelection as qo, runTrustedUpdate as qr, elementSplitOutput as qs, removeNodes as qt, mapCarriedRunThrough as qu, carryPluginFactoryType as r, registerEditorDraftView as ra, advanceElementOwnedRootIndex as rc, getInternalDocumentChangeClassification as rd, getNodeKeyDOMValue as rf, setEditorMaxLength as ri, assertPublicRootKey as rl, string as rn, setShownSelectionAsView as ro, copyRoots as rp, getLastCommit$1 as rr, acceptsPropertyValue as rs, getFragment as rt, getEditorDocumentShapeIssueMessage as ru, createEditorViewPluginApis as s, range$1 as sa, rootsOwnedOnlyWithin as sc, getInternalDocumentChangeRecords as sd, composeRecordOps as sf, setEditorTransactionViewTransform as si, getRangeEndpointAssociations as sl, unhangRange as sn, carryRootEditors as so, visitRootNames as sp, getMutationVersion as sr, createEditorSchema as ss, getPluginRegistry as st, readPersistedEnvelope as su, PluginPublicationError as t, registerEditorDocumentRecorder as ta, rootsDeletedByName as tc, documentChangeWritesOnlyElementProperties as td, tokenLength as tf, setEditorCompositionPending as ti, placeAnchorsOnCommit as tl, shouldMergeNodesRemovePrevNode as tn, sameCarets as to, copyFields as tp, getEditorStateView as tr, documentRootsOf as ts, getChildren as tt, EDITOR_DOCUMENT_FIELDS as tu, destroyEditor as u, deleteText as ua, createDetachedContentSlice as uc, hasInternalDocumentChangeRoot as ud, getRecordEntries as uf, setTypedMarks as ui, EditorRefusalError as ul, update as un, createEditorViewRuntime as uo, cloneFrozen as up, getPathByNodeKey$1 as ur, getInternalEditorSchemaFromApi as us, hasBlocks as ut, failInvariant as uu, prepareInitialPluginPublication as v, after$1 as va, getEditorCommitNode as vc, valueRootNodes as vd, readRecord as vf, transformEditorSnapshotInput as vi, assertPluginPublicationInactive as vl, afterOpenDrafts as vn, getViewFollowTarget as vo, getUpdateView as vr, withoutGenerationOf as vs, insertText as vt, getTextSearchScope as vu, startEditor as w, getWordDistances as wa, getEditorCommitValue as wc, ancestorType as wd, withValueRecords as wf, withEditorUpdateRootScope as wi, getPluginRegistry$1 as wl, asSelectionMotion as wn, projectEditorView as wo, initializeEditorSchemaSnapshot as wr, encodeEditorSelection as ws, isEmpty as wt, getEditorRuntimeOwner as wu, releaseEditor as x, executeEditorRead as xa, getEditorCommitSnapshot as xc, withoutRetainedRecordSets as xd, recordSetChanges as xf, withEditorDocumentProjection as xi, getCompiledEditorSchema as xl, applyTransactionSpec as xn, linkViewLockScope as xo, inheritEditorProjectionIndexes as xr, assertDetachedSelectionSupported as xs, isEdge as xt, registerEditorContent as xu, prepareScopedPluginPublication as y, exportContentSlice as ya, getEditorCommitRest as yc, withDocumentChangeRecords as yd, recordOpsBetween as yf, updateEditor as yi, createPluginRegistry as yl, applyBuiltDocumentChange as yn, getViewPresentation as yo, hasEditorProjectionSnapshotIndex as yr, payloadKeyOf as ys, install as yt, TextApi as yu, prepareCommandFrame as z, getBookmark as za, readAuthoredView as zc, rootIndexOf as zd, createEditorEffect as zf, readRootTarget as zi, hashSchemaIdentityString as zl, getChildList as zn, createEditorUpdateApi as zo, readElementPropertyWrites as zr, joinedAway as zs, path as zt, flipFacts as zu };
52738
+ export { first as $, mayClearCaret as $a, observeAnchorStateWork as $c, semanticPropertyModifications as $d, decodeVersionedValue as $f, getFragment$1 as $i, holdsUniqueKey as $l, getEditorRuntimeElementEntries as $n, txSelection as $o, setChildren as $r, carriesDefault as $s, setPoint as $t, composeRoot as $u, definePluginSlot as A, getWordDistances as Aa, getEditorCommitUnsettle as Ac, getInternalDocumentRootChange as Ad, composeRecordOps as Af, resolveStateFieldInitial as Ai, setEditorLifecycleErrorSink as Al, finalizeTransactionRepresentation as An, projectEditorView as Ao, visitRootNames as Ap, isEditorPublishingCommit as Ar, assertSelectionSupported as As, last as At, ElementApi as Au, NodeApi as B, node as Ba, authoredDocumentCapabilityPoint as Bc, withDocumentChangeRecords as Bd, hasRecordWithPrefix as Bf, readLatestShownWritableRootView as Bi, markDefinedStateField as Bl, getChildren$1 as Bn, retainPresentation as Bo, readElementById as Br, withLandedMarks as Bs, point as Bt, getEditorRuntimeOwner as Bu, setPluginPortalFactory as C, before$1 as Ca, getEditorCommitCompletedTextDeletion as Cc, filterDocumentChangeRoots as Cd, tokenLength as Cf, withEditorDocumentProjection as Ci, publishEditorRefusal as Cl, applyUnnamedDocumentChange as Cn, getViewAuthor as Co, isObject as Cp, inheritEditorProjectionIndexes as Cr, placeElementAt as Cs, isElementReadOnly as Ct, readStoredEditorDocument as Cu, property as D, executeEditorRead as Da, getEditorCommitSchemas as Dc, getInternalDocumentChangeRanges as Dd, NO_RECORD_OPS as Df, withTransactionSpecDraftRead as Di, notifyObservers as Dl, continueTransactionSpecOrDiscardPrefix as Dn, linkViewLockScope as Do, isFrozenWithRoots as Dp, initializePublicState as Dr, payloadKeyOf as Ds, isSelectable as Dt, point$1 as Du, getSchemaElementSourceReference as E, resolveShouldMergeNodesRemovePrevNode as Ea, getEditorCommitRest as Ec, getInternalDocumentChangeEntries as Ed, getNodeKeyForNode as Ef, withEditorUpdateRootScope as Ei, REMOTE_UPDATE as El, attachTransactionSpecAfterCommit as En, joinViewLockScope as Eo, copyRoots as Ep, initializeEditorSchemaSnapshot as Er, withoutGenerationOf as Es, isInline as Et, definePluginPoint as Eu, getActiveCommandEditor as F, gridRolesOf as Fa, snapshotIndexOf as Fc, mapInternalDocumentChangePosition as Fd, getRecordSetVersion as Ff, getSelectionStateCaret as Fi, getConfiguredPluginRegistry as Fl, getActiveEditorUpdateId as Fn, setViewLockScopeLocked as Fo, isRecord$5 as Fp, notifyPresentationViewState as Fr, mapDetachedSelectionThroughChange as Fs, move as Ft, isEditorContent as Fu, collapse as G, getBookmark as Ga, coversContent as Gc, ancestorType as Gd, recordSetIds as Gf, readRootViewUse as Gi, crossesUniqueTarget as Gl, getCurrentSelectionRoot as Gn, createEditorUpdateApi as Go, registerEditorTransactionGuard as Gr, constructLoadedDocumentChange as Gs, read as Gt, defineCommand$1 as Gu, addMark as H, changedBookmarks as Ha, createEditorAnchorApi as Hc, withoutRetainedRecordSets as Hd, recordOpsBetween as Hf, readNestedRootView as Hi, EditorSchemaCompileError as Hl, getCollabEffects$1 as Hn, subscribeCommit as Ho, recordEditorHistoryReplayReceipt as Hr, settleRange as Hs, previous as Ht, getEditorSchema as Hu, hasCommandHandler as I, leftWithNoGridPart as Ia, getDocumentChangeRelocations as Ic, transformInternalDocumentChange as Id, getRecordText as If, continueRootViewUse as Ii, getPluginContributions as Il, getActiveEditorUpdateTags as In, withMountedPresentation as Io, jsonEqual$1 as Ip, readEditor as Ir, mapSelectionThroughChange as Is, moveNodes as It, registerEditorContent as Iu, deleteForward as J, getRangeBreakCount as Ja, getMovedAnchorIds as Jc, getDocumentPropertyContext as Jd, withoutValueRoots as Jf, subscribeRootTarget as Ji, getCompiledPropertyMergeStrategy as Jl, getEditorDocumentValue as Jn, getRootTransaction as Jo, resolveEditorNodeKeyForNode as Jr, partOf as Js, replace as Jt, letterOriginsOfChange as Ju, deleteBackward as K, getCaretOwner as Ka, consumeAnchorHistoryCapture as Kc, applyPropertyModifications as Kd, showValueRecords as Kf, readShownViewUse as Ki, diffEditorSchemaContracts as Kl, getEditorChildrenRoot as Kn, mapSemanticUpdateMethodArguments as Ko, repairEditorValue as Kr, fitImportedBlock as Ks, removeMark as Kt, UNSCOPED_ORIGINS as Ku, probeCommandNativeEquivalent as L, survivalUnder as La, getExactDocumentChangeRelocation as Lc, valueRoot$1 as Ld, getRecordsWithPrefix as Lf, markRootViewUsed as Li, getPluginRegistry$1 as Ll, getAppliedSpecLanding as Ln, getBaseViewPresentation as Lo, cloneFrozen$1 as Lp, readEditorCommitHistoryEntry as Lr, mapSelectionWithContext as Ls, next as Lt, projectionMapOf as Lu, dispatchCommand as M, isTextCell as Ma, historyReplayClaim as Mc, isDocumentRootKey as Md, getRecordCount as Mf, planPaste as Mi, createPluginRegistry as Ml, fitSlicePlacements as Mn, readShownRecords as Mo, readCoreWork as Mp, isNotifyingNestedCommit as Mr, encodeEditorSelection as Ms, levels as Mt, setDebugValueScrubber as Mu, evaluateCommand as N, gridHoldersOf as Na, keyMovedAt as Nc, isInternalDocumentChangeNoop as Nd, getRecordEntries as Nf, withTrackedPastes as Ni, finalizePluginRegistry as Nl, flushEditorViewState as Nn, readViewPage as No, cloneFrozen as Np, isPresentationComposing as Nr, getSelectionDOMRange as Ns, liftNodes as Nt, getTextSearchScope as Nu, schema as O, editorReads as Oa, getEditorCommitSnapshot as Oc, getInternalDocumentChangeRecords as Od, applyRecordOps as Of, withUpdateTagContext as Oi, reportEditorLifecycleError as Ol, createTransactionSpec as On, matchesPresentationOf as Oo, lazyRootOf as Op, invalidateEditorTransactionSpecs as Or, withFitLanding as Os, isStart as Ot, readTextEdge as Ou, evaluateCommandWithState as P, gridPartsOf as Pa, readRootEntries as Pc, mapInternalDocumentChangePoint as Pd, getRecordIds as Pf, writePaste as Pi, getCompiledEditorSchema as Pl, getActiveEditorTransaction as Pn, retainViewPresentation as Po, deepFreeze as Pp, loadOpenedRecords as Pr, isObjectSelectionTarget as Ps, mergeNodes as Pt, TextApi as Pu, elementReadOnly as Q, liftShownTarget as Qa, mergeAnchorHistoryRecovery as Qc, propertyDeltaFromModifications as Qd, decodeEditorEffect as Qf, recordedDeleteGroupingInput as Qi, hashSchemaIdentityString as Ql, getEditorReadDepth as Qn, txOnly as Qo, seedUniqueMaps as Qr, readingCovered as Qs, setNodes as Qt, composeFacts as Qu, commandViewHides as R, nodes as Ra, getExactDocumentChangeRelocations as Rc, valueRootIndex as Rd, getValueRecords as Rf, mountRootView as Ri, inheritPluginRegistry as Rl, getBaseCallRoot as Rn, getStateViewPresentation as Ro, getDefined as Rp, readEditorHistoryHeadRoots as Rr, rawNodeAt as Rs, parent as Rt, registerEditorCommandDocument as Ru, resolveInstalledPlugin as S, readOnlyInlineAt as Sa, getEditorCommitCarriedRuns as Sc, documentChangeWritesOnlyElementProperties as Sd, textToken as Sf, withDraftMove as Si, EditorRefusalError as Sl, applyTransactionSpecToDocument as Sn, getOwnViewReadOnly as So, PathApi as Sp, hasOpenDraft as Sr, landNodePropertiesAt as Ss, isEditor as St, readPersistedEnvelope as Su, withPluginPortalCandidates as T, exportContentSlice as Ta, getEditorCommitNode as Tc, getInternalDocumentChangeClassificationEntries as Td, getNodeKeyDOMValue as Tf, withEditorRootChildrenGenerator as Ti, HISTORY_BOUNDARY_TAG as Tl, assertEditorExternalMutationAllowed as Tn, getViewPresentation as To, copyRoot as Tp, initializeEditorSchemaSelection as Tr, withoutGeneration as Ts, isEnd as Tt, failInvariant as Tu, after as U, clearCaretUnlessHeldElsewhere as Ua, getAnchorRuntimeId as Uc, RootChange as Ud, recordOpsFromJson as Uf, readRootTarget as Ui, areEditorSchemaIdentitiesEqual as Ul, getCurrentMarks as Un, subscribeSource$1 as Uo, registerEditorHistoryRuntime as Ur, completeChildrenAt as Us, projectRange as Ut, hasEditorRuntime as Uu, above as V, capturePlacement as Va, isAuthorId as Vc, withInternalDocumentRootChange as Vd, readRecord as Vf, readLatestShownWritableView as Vi, registerEffectTypeInRegistry as Vl, getCollabEffectTypes as Vn, subscribe as Vo, readElementPropertyWrites as Vr, sealsText as Vs, positions as Vt, getEditorRuntimeRoot as Vu, before as W, consumeCommitCarets as Wa, restoreAnchor as Wc, addSection as Wd, recordSetChanges as Wf, readRootViewPresentationRevision as Wi, compileEditorSchemaContributions as Wl, getCurrentSelection as Wn, createEditorReadApi as Wo, registerEditorSurface as Wr, constructCanonicalDocumentChange as Ws, range as Wt, setEditorRuntime as Wu, deselect as X, holdsCaretAt as Xa, hasActiveAnchors as Xc, keptRunsOf as Xd, assertEditorJsonValue as Xf, subscribeShownViewUse as Xi, handoverKeysOf as Xl, getEditorNodeKeyForNode as Xn, locateAt as Xo, saveEditorSchemaDocument as Xr, adoptVerdicts as Xs, reset as Xt, NO_ROOT_FACTS as Xu, deleteFragment as Y, holdsCaret as Ya, getPublishedAnchorValue as Yc, isRootChangeRangeReplaced as Yd, areEditorJsonValuesEqual as Yf, subscribeRootViewPresentation as Yi, getCompiledSchemaPropertyId as Yl, getEditorMaxLength as Yn, resolvePluginMethod as Yo, runTrustedUpdate as Yr, isEmptyElement as Ys, replaceChildren as Yt, NO_FACTS as Yu, edges as Z, keepBookmark as Za, mapAnchorHistoryRecovery as Zc, mapRootChangePositionBackward as Zd, cloneEditorJsonValue as Zf, nativeGroupingInput as Zi, hasPlaceDependentElementProperty as Zl, getEditorProjectionSnapshotIndex as Zn, txLocate as Zo, scheduleAfterCommitNotification as Zr, judgedBy as Zs, select as Zt, UNKNOWN_FACTS as Zu, markEditorDormant as _, readRemovalLanding as _a, createDetachedContentSlice as _c, collapseDocumentElementPropertyWrites as _d, isElementNode as _f, syncImplicitTargetToCurrentSelection as _i, isDocumentView as _l, afterActiveTransactionEnds as _n, createViewLockScope as _o, PointApi as _p, getTransactionLanding as _r, getCompiledEditorSchemaFromApi as _s, insertSoftBreak as _t, assertEditorDocumentContainers as _u, compilePluginInput as a, trackDraftSpans as aa, judgeProjectedRoots as ac, recordedFacts as ad, childAtPathIndex as af, setEditorMaxLength as ai, isAuthoredPreview as al, toggleBlock as an, restoreHistoryCarets as ao, supportsEditorValuePersistenceVersion as ap, getLiveSelection as ar, onlyDocumentAdmission as as, getNodeKey as at, readEditorSchemaContract as au, queueAfterPluginAcquisition as b, elementReadOnly$1 as ba, getDocumentValueNode as bc, documentChangeBetween as bd, openToken as bf, transformEditorSnapshotInput as bi, nodeWriteVeto as bl, applyDocumentChange as bn, getCarriedMount as bo, getRangeRoot as bp, hasEditorProjectionSnapshotIndex as br, holdsImportedRoot as bs, isBlock as bt, readDocumentRecord as bu, defineEditorSchema as c, registerEditorDraftGuard as ca, rootsDeletedByName as cc, carriesRun as cd, rootNodesOf as cf, setEditorStateViewTransform as ci, registerAuthoredRuntime as cl, unsetNodes as cn, setSelectionAsView as co, createEditorEffect as cp, getNodeKey$1 as cr, rootChildrenOf$1 as cs, getSelection as ct, restoreEditorSchemaContract as cu, extendEditor as d, rewriteContentRootReferences as da, ensureElementOwnedRootIndex as dc, landCarriedRuns as dd, classifyRootChange as df, setRootCopyScope as di, withStoredAuthoredRead as dl, voidEditor as dn, watchFirstPlacement as do, invertEffect as dp, getRestorableMarks as dr, acceptsPropertyValue as ds, hasInlines as dt, toCompiledTargetContext as du, getContentSlice as ea, elementSplitOutput as ec, factsFromJSON as ed, markReadBack as ef, setCurrentMarks as ei, placeAnchorsOnCommit as el, setSelection as en, nextMintedGeneration as eo, encodeEditorEffect as ep, getEditorRuntimeRootKeys as er, txStored as es, fragment as et, isPlaceDependentElementProperty as eu, getCandidatePluginApi as f, range$1 as fa, ownedRootsOf as fc, mapCarriedRunThrough as fd, PreparedTokenSlice as ff, setTypedMarks as fi, assertPublicRootKey as fl, wrapNodes as fn, withoutPlacement as fo, mapEffect as fp, getSelectionRoot as fr, canPlaceBlocksAtPath as fs, hasPath as ft, tracksPlaces as fu, isPlugin as g, deleteText as ga, ContentSlice as gc, applyDocumentChangeValue as gd, getDocumentSliceNodeKeys as gf, subscribePresentationComposition as gi, assertNoDocumentViewRead as gl, withCompositionStamp as gn, createEditorViewRuntime as go, SpanApi as gp, getStateFieldEffectTypes as gr, generateElementPropertyValue as gs, insertNodes as gt, EDITOR_DOCUMENT_FIELDS as gu, getInstalledPluginApi as h, dividesTextCell as ha, lawCheckEnabled as hc, alignedDocumentChange as hd, encodeNodes as hf, subscribeEditorViewState as hi, toPublicRoot as hl, tripleClickedBlock as hn, createEditorView as ho, LocationApi as hp, getSnapshotVersion as hr, createEditorSchema as hs, insertNode as ht, EditorSchemaValidationError as hu, compilePlugin as i, settleDraftTrack as ia, changedRootsOf as ic, recorded as id, NO_NODES as if, setEditorFocused as ii, getAuthoredUpdateView as il, subscribeSource as in, resolveParkedCaret as io, snapshotEditorJsonValue as ip, getLiveNode as ir, documentAdmissionPoint as is, getLastCommit as it, propertyTargetsReadParents as iu, createCommandDispatch as j, getWordSegments as ja, getEditorCommitValue as jc, hasInternalDocumentChangeRoot as jd, deriveValue as jf, captureSliceLanding as ji, assertPluginPublicationInactive as jl, fitSliceChildren as jn, readShownDocument as jo, countCoreWork as jp, isInTransaction as jr, decodeEditorSelection as js, leaf as jt, formatDebugValue as ju, target as k, getCharacterDistance as ka, getEditorCommitStartedAt as kc, getInternalDocumentChangeRootKeys as kd, canonicalRecordJson as kf, setTargetRuntime as ki, runEditorObserver as kl, documentReplacement as kn, mountViewPeer as ko, setLazyRoot as kp, isBuildingTransactionSpec as kr, assertDetachedSelectionSupported as ks, isVoid as kt, SelectionApi as ku, definePlugin as l, registerEditorDraftView as la, schemaHasContentRoots as lc, exactRunOn as ld, canonicalJsonKey as lf, setEditorTransactionViewTransform as li, requestAuthoredView as ll, unwrapNodes as ln, setShownSelectionAsView as lo, defineEffect as lp, getNodeTargetRoot as lr, visitElements as ls, getSnapshot as lt, splitDroppedKeysOf as lu, getInstalledPlugin as m, withLandingBlock as ma, rootsOwnedOnlyWithin as mc, DocumentChange as md, closeToken as mf, subscribeCaretTarget as mi, toInternalRoot as ml, readWholeBlockLanding as mn, createAuthoredEditorView as mo, RangeApi as mp, getSnapshot$1 as mr, createDetachedEditorSchema as ms, insertBreak as mt, EditorNoncanonicalChangeError as mu, brandPluginDescriptor as n, readDraftTrack as na, isSplitOutput as nc, flipFacts as nd, liftOf as nf, setEditorComposing as ni, getRangeEndpointAssociations as nl, splitNodes as nn, resolveBookmark as no, isEditorJsonValue as np, getEditorUpdateRoot as nr, admitDocument as ns, getCollabEffects as nt, matchesCompiledSchemaTarget as nu, containsCompleteEditorSchema as o, isEditorDraftView as oa, orphanedRoots as oc, sortedRootFacts as od, decodeNodes as of, setEditorReadOnly as oi, readAuthoredView as ol, toggleMark as on, rootChildrenOf as oo, textPropertiesEqual as op, getLiveText as or, withoutRepairOrphans as os, getPathByNodeKey as ot, readEditorSchemaIdentity as ou, getCompiledEditorConfiguration as p, textLineRefusal as pa, rebaseElementOwnedRootIndex as pc, widenRun as pd, PreparedTokenSliceStructureError as pf, snapshotInitialDocumentState as pi, getPublicExplicitLocationRoot as pl, editorCommands as pn, carryRootEditors as po, readLastCommitAnnotation as pp, getSetSite as pr, canonicalizeCompiledTextProperties as ps, hasTexts as pt, uniquePropertiesOf as pu, deleteEditor as q, getPlacementGeneration as qa, getMovableAnchors as qc, applyPropertyModificationsToSlice as qd, withValueRecords as qf, readShownWritableRootViews as qi, getCompiledPropertyCandidates as ql, getEditorDocumentRecords as qn, callPluginUpdateMethod as qo, replaceSliceAtBlockBoundary as qr, joinedAway as qs, removeNodes as qt, classifyDocumentChange as qu, carryPluginFactoryType as r, readDraftTrackAt as ra, readsAt as rc, historyFollowsAllFacts as rd, DocumentIndex as rf, setEditorCompositionPending as ri, configureAuthoredView as rl, string as rn, resolveLiveCaret as ro, normalizeEditorValuePersistence as rp, getLastCommit$1 as rr, admitEditorDocument as rs, getFragment as rt, preserveCompiledSchemaPropertyIdentity as ru, createEditorViewPluginApis as s, registerEditorDocumentRecorder as sa, orphanedValueRoots as sc, carriedLetterPairs as sd, rootIndexOf as sf, setEditorSnapshotInputTransform as si, readShownPreview as sl, unhangRange as sn, sameCarets as so, valueCodecs as sp, getMutationVersion as sr, documentRootsOf as ss, getPluginRegistry as st, resolveCompiledSchemaProperty as su, PluginPublicationError as t, assertEditorNotDestroyed as ta, isLeftOutDefault as tc, factsToJSON as td, joinsOf as tf, setCurrentSelection as ti, stageAnchorHistoryRecovery as tl, shouldMergeNodesRemovePrevNode as tn, placedSince as to, encodeVersionedValue as tp, getEditorStateView as tr, DOCUMENT_SETTLED_TAG as ts, getChildren as tt, isSupportedGeneratedElementProperty as tu, destroyEditor as u, registerEditorFitsByLook as ua, advanceElementOwnedRootIndex as uc, invertCarriedRun as ud, normalizeSetValues as uf, setEditorViewing as ui, withAuthoredUpdateView as ul, update as un, subscribeCommittedPlacement as uo, defineUpdateAnnotation as up, getPathByNodeKey$1 as ur, ElementGenerationMaskedError as us, hasBlocks as ut, toCompiledNodeContext as uu, prepareInitialPluginPublication as v, resolveDeletedRange as va, claimsHistoryReplay as vc, createInternalDocumentChange as vd, isTextNode$3 as vf, toEditorCoreStateView as vi, isDocumentViewReading as vl, afterOpenDrafts as vn, flushViewLockScope as vo, MAIN_ROOT_KEY as vp, getTransactionSnapshot as vr, getInternalEditorSchemaFromApi as vs, insertText as vt, getEditorDocumentShapeIssueMessage as vu, startEditor as w, after$1 as wa, getEditorCommitFacts as wc, getInternalDocumentChangeClassification as wd, tokensEqual as wf, withEditorRootChildren as wi, subscribeEditorRefusals as wl, asSelectionMotion as wn, getViewFollowTarget as wo, copyFields as wp, initializeEditorSchemaDocument as wr, readEmptyText as ws, isEmpty as wt, rejectEditorRecord as wu, releaseEditor as x, hasEdgeInReadOnlyInline as xa, getEditorCommitAdmission as xc, documentChangePropertyOnlyWrites as xd, pathKey$2 as xf, updateEditor as xi, vetoesWrite as xl, applyTransactionSpec as xn, getOwnViewPresentation as xo, getReaderRange as xp, hasEditorSurface as xr, holdsOneText as xs, isEdge as xt, readEditorDocument as xu, prepareScopedPluginPublication as y, removeNodes$1 as ya, createEditorCommit as yc, createInternalRootChangeFromSections as yd, nodeProps as yf, trackEditorLetters as yi, withDocumentViewRead as yl, applyBuiltDocumentChange as yn, getCarriedCaretEditor as yo, getCommonLocationRoot as yp, getUpdateView as yr, getRepresentationEditorFromApi as ys, install as yt, isEnvelopeInput as yu, prepareCommandFrame as z, normalizeNodeMatch as za, hasIndexedPathAncestor as zc, valueRootNodes as zd, hasRecord as zf, readCaretViewIn as zi, initializeBasePluginRegistry as zl, getChildList as zn, onPresentationRelease as zo, readEditorHistoryReplayReceipt as zr, settleSelectionMode as zs, path as zt, getEditorRuntime as zu };