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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/annotations/index.d.ts +1 -1
  2. package/dist/annotations/index.js +1 -1
  3. package/dist/authored/index.d.ts +2 -2
  4. package/dist/authored/index.js +1302 -490
  5. package/dist/{authored-veto-D_9wCJcK.js → authored-veto-BsBDXC0b.js} +1 -1
  6. package/dist/{comparison-plan-DY_vuGPq.js → comparison-plan-IOewH50q.js} +1 -1
  7. package/dist/{comparison-types-DdwE6mYq.d.ts → comparison-types-DBQFu7Rt.d.ts} +1 -1
  8. package/dist/{create-editor-CLQEkEZ1.js → create-editor-DRRzGwaC.js} +1 -1
  9. package/dist/diff/index.d.ts +2 -2
  10. package/dist/diff/index.js +2 -2
  11. package/dist/dom/index.d.ts +1 -1
  12. package/dist/dom/index.js +1 -1
  13. package/dist/{dom-CH2BXXj6.js → dom-CVYV5Qd5.js} +400 -100
  14. package/dist/{editor-owner-C9rVbMTs.js → editor-owner-CGj1wYCa.js} +1 -1
  15. package/dist/history/index.d.ts +1 -1
  16. package/dist/history/index.js +252 -178
  17. package/dist/hyperscript/index.d.ts +1 -1
  18. package/dist/hyperscript/index.js +1 -1
  19. package/dist/{hyperscript-CeT83ZLB.js → hyperscript-CT6hhnAY.js} +2 -2
  20. package/dist/{index-UrB4jAwl.d.ts → index-BT7D4vtf.d.ts} +5 -1
  21. package/dist/{index-BWPcE4ac.d.ts → index-BvQzYVAW.d.ts} +1 -1
  22. package/dist/{index-Db-ktCTE.d.ts → index-D7-n2GCk.d.ts} +6 -3
  23. package/dist/{index-BXjLmx1n.d.ts → index-DHt8nZQ6.d.ts} +143 -78
  24. package/dist/{index-Dq3Jlj8O.d.ts → index-PDROnF1G.d.ts} +1 -1
  25. package/dist/{index-DVMNewDn.d.ts → index-VZrKWWeh.d.ts} +20 -13
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.js +4 -4
  28. package/dist/internal/index.d.ts +2 -2
  29. package/dist/internal/index.js +4 -4
  30. package/dist/{mapped-view-store-CbWqba_1.js → mapped-view-store-CBk2-bDR.js} +1 -1
  31. package/dist/pagination/index.d.ts +1 -1
  32. package/dist/pagination/index.js +1 -1
  33. package/dist/pagination/react.d.ts +2 -2
  34. package/dist/pagination/react.js +5 -5
  35. package/dist/{pagination-CBdYiOuR.js → pagination-Cs5ka6hW.js} +1 -1
  36. package/dist/{plugin-SR3HTH0j.js → plugin-Bm6nsPHh.js} +1984 -751
  37. package/dist/{range-geometry-CdltxcH6.js → range-geometry-D1XfYWs0.js} +2 -2
  38. package/dist/{range-geometry-Dwp2oyCc.d.ts → range-geometry-DO-kbNrb.d.ts} +1 -1
  39. package/dist/react/index.d.ts +4 -4
  40. package/dist/react/index.js +6 -6
  41. package/dist/react/virtualized.d.ts +2 -2
  42. package/dist/react/virtualized.js +1 -1
  43. package/dist/{react-CN-iBh1z.js → react-BYtwRr4v.js} +18 -9
  44. package/dist/{retraction-BmPJB9cE.js → retraction-DnEUo8oE.js} +18 -2
  45. package/dist/{src-B-zm0kz4.js → src-DIQDddmh.js} +227 -40
  46. package/dist/{store-51r4zpCR.js → store-BLYxJgOU.js} +35 -5
  47. package/dist/testing/index.d.ts +2 -2
  48. package/dist/testing/index.js +3 -3
  49. package/dist/{use-editor-dom-scope-uDJQ692F.js → use-editor-dom-scope-hT7W9d-p.js} +1089 -606
  50. package/dist/yjs/index.d.ts +1 -1
  51. package/dist/yjs/index.js +1 -1
  52. package/dist/yjs/react/index.d.ts +3 -3
  53. package/dist/yjs/react/index.js +3 -3
  54. package/dist/{yjs-IGE0Al3n.js → yjs-C_g9gZwI.js} +6 -3
  55. package/package.json +1 -1
  56. package/dist/native-grouping-input-DXNhlPHd.js +0 -8
@@ -1,7 +1,7 @@
1
- import { $f as PathApi, $l as tracksPlaces, $s as orphanedRoots, Aa as leftWithNoGridPart, Ad as propertyDeltaFromModifications, As as rawNodeAt, Au as UNSCOPED_ORIGINS, Bd as rootNodesOf, Bl as holdsUniqueKey, Cd as addSection, Cl as getPluginContributions, Cu as getEditorRuntime, D as property, Da as gridHoldersOf, Ef as areEditorJsonValuesEqual, Eu as getEditorSchema, Fd as DocumentIndex, Fn as getActiveEditorUpdateId, Fs as completeChildrenAt, Gd as PreparedTokenSliceStructureError, Gf as RangeApi, Gn as getCurrentSelectionRoot, Gs as readingCovered, Hd as normalizeSetValues, Hl as isSupportedGeneratedElementProperty, Hs as EditorSchemaValidationError, Id as NO_NODES, In as getActiveEditorUpdateTags, Ja as nextMintedGeneration, Jf as PointApi, Jl as resolveCompiledSchemaProperty, Jo as txStored, Js as isLeftOutDefault, Kd as closeToken, Ko as txOnly, Ks as carriesDefault, Lc as getAuthoredUpdateView, Ll as handoverKeysOf, Ml as crossesUniqueTarget, Nc as authoredDocumentCapabilityPoint, Nf as isEditorJsonValue, Nr as notifyPresentationViewState, O as schema, Oa as gridPartsOf, Od as keptRunsOf, Pl as getCompiledPropertyCandidates, Qd as openToken, Ql as toCompiledTargetContext, Qo as documentAdmissionPoint, Qs as judgeProjectedRoots, Qu as createInternalDocumentChange, Sa as editorReads, Sd as RootChange, Su as registerEditorCommandDocument, Td as applyPropertyModifications, Tf as withoutValueRoots, Tu as getEditorRuntimeRoot, Ud as classifyRootChange, Ul as matchesCompiledSchemaTarget, Us as adoptVerdicts, Va as getPlacementGeneration, Vc as registerAuthoredRuntime, Vd as canonicalJsonKey, Wd as PreparedTokenSlice, Wn as getCurrentSelection, Ws as judgedBy, Xd as isTextNode, Xl as splitDroppedKeysOf, Xo as admitDocument, Xs as readsAt, Yd as isElementNode, Ys as isSplitOutput, Yu as DocumentChange, Zd as nodeProps, Zn as getEditorProjectionSnapshotIndex, Zs as changedRootsOf, _d as valueRootIndex, _f as hasRecordWithPrefix, _o as getViewAuthor, _r as getTransactionSnapshot, _s as withoutGeneration, ac as ownedRootsOf, ad as getInternalDocumentChangeEntries, af as NO_RECORD_OPS, al as toInternalRoot, ap as lazyRootOf, as as canonicalizeCompiledTextProperties, bc as getEditorCommitSchemas, bn as applyDocumentChange, cd as getInternalDocumentChangeRootKeys, cf as deriveValue, cp as countCoreWork, cs as generateElementPropertyValue, df as getRecordIds, dl as publishEditorRefusal, dp as deepFreeze, ds as getRepresentationEditorFromApi, ec as orphanedValueRoots, ef as textToken, eu as uniquePropertiesOf, fc as createEditorCommit, ff as getRecordSetVersion, fl as subscribeEditorRefusals, gd as valueRoot, gf as hasRecord, gs as readEmptyText, hf as getValueRecords, hp as getDefined, hu as ElementApi, ia as registerEditorFitsByLook, ic as ensureElementOwnedRootIndex, if as getNodeKeyForNode, io as subscribeCommittedPlacement, ip as isFrozenWithRoots, ja as survivalUnder, jd as semanticPropertyModifications, jo as getBaseViewPresentation, jr as isPresentationComposing, js as settleSelectionMode, k as target, ka as gridRolesOf, kd as mapRootChangePositionBackward, ks as mapSelectionWithContext, l as definePlugin, ld as getInternalDocumentRootChange, lf as getRecordCount, mf as getRecordsWithPrefix, mi as subscribePresentationComposition, ml as notifyObservers, mu as SelectionApi, na as registerEditorDraftGuard, nc as schemaHasContentRoots, nd as filterDocumentChangeRoots, np as copyRoot, ns as ElementGenerationMaskedError, oc as rebaseElementOwnedRootIndex, od as getInternalDocumentChangeRanges, of as canonicalRecordJson, ol as toPublicRoot, op as setLazyRoot, os as createDetachedEditorSchema, pf as getRecordText, pp as jsonEqual, ps as holdsOneText, qc as isDocumentViewReading, qd as encodeNodes, qs as elementSplitOutput, ra as registerEditorDraftView, rc as advanceElementOwnedRootIndex, rp as copyRoots, rs as acceptsPropertyValue, sc as rootsOwnedOnlyWithin, sd as getInternalDocumentChangeRecords, sf as composeRecordOps, sl as getRangeEndpointAssociations, sp as visitRootNames, ta as registerEditorDocumentRecorder, tc as rootsDeletedByName, tf as tokenLength$1, tp as copyFields, ts as documentRootsOf, uf as getRecordEntries, ul as EditorRefusalError, vd as valueRootNodes, vs as withoutGenerationOf, wc as getEditorCommitValue, wf as withValueRecords, wt as isEmpty, wu as getEditorRuntimeOwner, xa as executeEditorRead, xf as recordSetChanges, xi as withEditorDocumentProjection, xl as getCompiledEditorSchema, xr as inheritEditorProjectionIndexes, xu as registerEditorContent, yd as withDocumentChangeRecords, yf as recordOpsBetween, yo as getViewPresentation, yr as hasEditorProjectionSnapshotIndex, z as prepareCommandFrame, zd as rootIndexOf, zl as hashSchemaIdentityString, zs as joinedAway } from "../plugin-SR3HTH0j.js";
2
- import { t as authoredVeto } from "../authored-veto-D_9wCJcK.js";
3
- import { n as EditorMissingReferenceError, t as retractionOf } from "../retraction-BmPJB9cE.js";
4
- import { S as fingerprintEditorJson, c as COMPARISON_POLICY, n as comparisonPlanOf, t as closeOverRequired } from "../comparison-plan-DY_vuGPq.js";
1
+ import { $d as semanticPropertyModifications, $l as holdsUniqueKey, $s as carriesDefault, $u as composeRoot, Ad as getInternalDocumentRootChange, Af as composeRecordOps, Ap as visitRootNames, Au as ElementApi, Bc as authoredDocumentCapabilityPoint, Bd as withDocumentChangeRecords, Bf as hasRecordWithPrefix, Bu as getEditorRuntimeOwner, Cd as filterDocumentChangeRoots, Cf as tokenLength$1, Ci as withEditorDocumentProjection, Cl as publishEditorRefusal, Co as getViewAuthor, Cr as inheritEditorProjectionIndexes, D as property, Da as executeEditorRead, Dc as getEditorCommitSchemas, Dd as getInternalDocumentChangeRanges, Df as NO_RECORD_OPS, Dl as notifyObservers, Dp as isFrozenWithRoots, Ed as getInternalDocumentChangeEntries, Ef as getNodeKeyForNode, Ep as copyRoots, Es as withoutGenerationOf, Fa as gridRolesOf, Ff as getRecordSetVersion, Fn as getActiveEditorUpdateId, Fr as notifyPresentationViewState, Gl as crossesUniqueTarget, Gn as getCurrentSelectionRoot, Hf as recordOpsBetween, Hu as getEditorSchema, Ia as leftWithNoGridPart, If as getRecordText, Il as getPluginContributions, In as getActiveEditorUpdateTags, Ip as jsonEqual, Iu as registerEditorContent, Jf as withoutValueRoots, Js as partOf, Kd as applyPropertyModifications, Ku as UNSCOPED_ORIGINS, La as survivalUnder, Ld as valueRoot, Lf as getRecordsWithPrefix, Lo as getBaseViewPresentation, Ls as mapSelectionWithContext, Lu as projectionMapOf, Mf as getRecordCount, Na as gridHoldersOf, Nf as getRecordEntries, Nr as isPresentationComposing, O as schema, Oa as editorReads, Od as getInternalDocumentChangeRecords, Of as applyRecordOps, Op as lazyRootOf, Pa as gridPartsOf, Pf as getRecordIds, Pl as getCompiledEditorSchema, Pp as deepFreeze, Qd as propertyDeltaFromModifications, Ql as hashSchemaIdentityString, Qo as txOnly, Qs as readingCovered, Rd as valueRootIndex, Rf as getValueRecords, Rp as getDefined, Rs as rawNodeAt, Ru as registerEditorCommandDocument, Sf as textToken, Sl as EditorRefusalError, Sp as PathApi, To as getViewPresentation, Tp as copyRoot, Ts as withoutGeneration, Ud as RootChange, Us as completeChildrenAt, Vu as getEditorRuntimeRoot, Wd as addSection, Wf as recordSetChanges, Wn as getCurrentSelection, Xd as keptRunsOf, Xl as handoverKeysOf, Xs as adoptVerdicts, Xu as NO_ROOT_FACTS, Yd as isRootChangeRangeReplaced, Yf as areEditorJsonValuesEqual, Zd as mapRootChangePositionBackward, Zn as getEditorProjectionSnapshotIndex, Zs as judgedBy, _f as isElementNode, _p as PointApi, ac as judgeProjectedRoots, bf as openToken, bn as applyDocumentChange, br as hasEditorProjectionSnapshotIndex, ca as registerEditorDraftGuard, cc as rootsDeletedByName, cf as rootNodesOf, cl as registerAuthoredRuntime, cs as rootChildrenOf, dc as ensureElementOwnedRootIndex, df as classifyRootChange, ds as acceptsPropertyValue, du as toCompiledTargetContext, ec as elementSplitOutput, eo as nextMintedGeneration, es as txStored, fc as ownedRootsOf, ff as PreparedTokenSlice, fu as tracksPlaces, gd as applyDocumentChangeValue, gi as subscribePresentationComposition, gs as generateElementPropertyValue, hf as encodeNodes, hl as toPublicRoot, hu as EditorSchemaValidationError, ic as changedRootsOf, id as recorded, if as NO_NODES$1, il as getAuthoredUpdateView, is as documentAdmissionPoint, jc as getEditorCommitValue, jf as deriveValue, jp as countCoreWork, k as target, kd as getInternalDocumentChangeRootKeys, kf as canonicalRecordJson, kp as setLazyRoot, ku as SelectionApi, l as definePlugin, la as registerEditorDraftView, lc as schemaHasContentRoots, lf as canonicalJsonKey, ls as visitElements, lu as splitDroppedKeysOf, mc as rootsOwnedOnlyWithin, md as DocumentChange, mf as closeToken, ml as toInternalRoot, mp as RangeApi, ms as createDetachedEditorSchema, nc as isSplitOutput, nl as getRangeEndpointAssociations, np as isEditorJsonValue, ns as admitDocument, nu as matchesCompiledSchemaTarget, oc as orphanedRoots, od as sortedRootFacts, pa as textLineRefusal, pc as rebaseElementOwnedRootIndex, pf as PreparedTokenSliceStructureError, ps as canonicalizeCompiledTextProperties, pu as uniquePropertiesOf, qa as getPlacementGeneration, qf as withValueRecords, ql as getCompiledPropertyCandidates, qs as joinedAway, rc as readsAt, rf as DocumentIndex, sa as registerEditorDocumentRecorder, sc as orphanedValueRoots, sf as rootIndexOf, ss as documentRootsOf, su as resolveCompiledSchemaProperty, tc as isLeftOutDefault, tu as isSupportedGeneratedElementProperty, ua as registerEditorFitsByLook, uc as advanceElementOwnedRootIndex, uf as normalizeSetValues, uo as subscribeCommittedPlacement, us as ElementGenerationMaskedError, vd as createInternalDocumentChange, vf as isTextNode, vl as isDocumentViewReading, vp as MAIN_ROOT_KEY, vr as getTransactionSnapshot, wl as subscribeEditorRefusals, wp as copyFields, ws as readEmptyText, wt as isEmpty, xs as holdsOneText, yc as createEditorCommit, yf as nodeProps, ys as getRepresentationEditorFromApi, z as prepareCommandFrame, zd as valueRootNodes, zf as hasRecord, zs as settleSelectionMode, zu as getEditorRuntime } from "../plugin-Bm6nsPHh.js";
2
+ import { t as authoredVeto } from "../authored-veto-BsBDXC0b.js";
3
+ import { a as isBoundToSharedRoom, n as EditorMissingReferenceError, t as retractionOf } from "../retraction-DnEUo8oE.js";
4
+ import { S as fingerprintEditorJson, c as COMPARISON_POLICY, n as comparisonPlanOf, t as closeOverRequired } from "../comparison-plan-IOewH50q.js";
5
5
  //#region src/authored/ledger/roots.ts
6
6
  /** @internal */
7
7
  const rootOf = (value, root) => root === "main" ? rootIndexOf(value, "children") : rootIndexOf(value.roots ?? {}, root);
@@ -295,7 +295,7 @@ const decideKey = (tags, reading, live) => {
295
295
  steps.forEach((step, index) => {
296
296
  if (statuses[index] !== "keep" || free[index]) return;
297
297
  if (firstReject !== -1 && index > firstReject || index < lastAccept) {
298
- for (const tag of step.tags) if (of(tag) === "keep") waits.add(tag.change);
298
+ for (const tag of step.tags) if (of(tag) === "keep" && !reading.onAnotherAuthorsCard?.(tag)) waits.add(tag.change);
299
299
  }
300
300
  });
301
301
  if (waits.size > 0) return {
@@ -439,6 +439,13 @@ const isAuthoredSetValued = (_node, key) => key === AUTHORED_MARKS_KEY;
439
439
  const isContextInsertion = (mark) => mark.kind === "insert" && mark.follows === void 0;
440
440
  const isStructureChange = (mark) => mark.kind === "join" || mark.kind === "split" || mark.kind === "unwrap" || mark.kind === "wrap";
441
441
  const isUnwrap = (mark) => mark.kind === "unwrap";
442
+ const dissolveClaimsOf = (marks) => marks.flatMap((mark) => mark.kind === "wrap" ? [{
443
+ ...mark,
444
+ kind: "insert"
445
+ }] : mark.kind === "unwrap" ? [{
446
+ ...mark,
447
+ kind: "delete"
448
+ }] : []);
442
449
  const followsOf = (mark) => mark.kind === "split" && mark.cut === void 0 || mark.kind === "insert" ? mark.follows : void 0;
443
450
  /**
444
451
  * An Editing claim that follows a join only moves its block, which its
@@ -1291,8 +1298,8 @@ const decidedIn = (before, after, change, indexOf) => {
1291
1298
  const facts = factsOf(after);
1292
1299
  const added = /* @__PURE__ */ new Map();
1293
1300
  for (const root of /* @__PURE__ */ new Set([...previous.roots.keys(), ...roots.keys()])) {
1294
- const old = previous.roots.get(root) ?? NO_NODES;
1295
- const next = roots.get(root) ?? NO_NODES;
1301
+ const old = previous.roots.get(root) ?? NO_NODES$1;
1302
+ const next = roots.get(root) ?? NO_NODES$1;
1296
1303
  if (old === next) continue;
1297
1304
  for (const [fromBefore, toBefore, from, to] of changedChildrenOf(change, root, before, indexOf(root))) {
1298
1305
  for (const node of old.slice(fromBefore, toBefore)) addCounts(added, insertionsIn(node, beforeFacts), -1);
@@ -1401,6 +1408,10 @@ const claimsOf = (node, facts) => {
1401
1408
  });
1402
1409
  return claims;
1403
1410
  };
1411
+ const holdsBase = (nodes, base, facts) => {
1412
+ const incarnation = incarnationOf(base);
1413
+ return nodes.some((node) => claimsOf(node, facts).some((claim) => claim.author === base.author && incarnationOf(claim) === incarnation));
1414
+ };
1404
1415
  const marksOf = (node, facts) => {
1405
1416
  const claims = claimsOf(node, facts);
1406
1417
  return !facts.hasVerdicts && !claims.some((mark) => isEditingChange(mark.change)) ? claims : claims.filter((mark) => outcomeOf(facts, mark) === "pending");
@@ -1838,10 +1849,11 @@ const rangeOf = ({ node, path, root }) => {
1838
1849
  const isNextSibling = (left, right) => left.length === right.length && left.length > 0 && left.every((index, depth) => depth === left.length - 1 ? index + 1 === right[depth] : index === right[depth]);
1839
1850
  const isInside = (ancestor, path) => ancestor.length < path.length && ancestor.every((index, depth) => path[depth] === index);
1840
1851
  const isLineBreak = (mark) => mark.kind === "join" || mark.kind === "joined" || mark.kind === "split" && !isCut(mark);
1852
+ const isEmptyBlock = (node) => !isText$7(node) && (node.children ?? []).every((child) => isText$7(child) && !child.text);
1841
1853
  /** @internal */
1842
1854
  const touches = (left, right) => {
1843
1855
  if (left.root !== right.root) return false;
1844
- if (left.path.join(",") === right.path.join(",") || isNextSibling(left.path, right.path)) return true;
1856
+ if (left.path.join(",") === right.path.join(",") || (!isLineBreak(left.mark) || isEmptyBlock(left.node)) && isNextSibling(left.path, right.path)) return true;
1845
1857
  if (right.first !== left.last + 1) return false;
1846
1858
  if (isLineBreak(left.mark) || isLineBreak(right.mark)) return true;
1847
1859
  const [, end] = edgeText(left.node, left.path, true);
@@ -2231,7 +2243,7 @@ const BOUNDARY_KINDS$1 = /* @__PURE__ */ new Set([
2231
2243
  "split"
2232
2244
  ]);
2233
2245
  const startsAtBoundary = (node) => !!node && (node.authored?.some(({ kind }) => BOUNDARY_KINDS$1.has(kind)) || startsAtBoundary(node.children?.[0]));
2234
- const holdsSpares = (node, root, spares) => node.authored?.some(({ kind }) => kind === "reserve" || kind === "as") || typeof node.type === "string" && spares.builds(node.type, root) || (node.children ?? []).some((child) => holdsSpares(child, root, spares));
2246
+ const holdsSpares = (node, spares) => node.authored?.some(({ kind }) => kind === "reserve" || kind === "as") || typeof node.type === "string" && spares.typeBuildsGenerated(node.type) || (node.children ?? []).some((child) => holdsSpares(child, spares));
2235
2247
  const decisionWindowsOf = (value, ids, occurrencesOf, spares) => {
2236
2248
  if (spares?.stored) return null;
2237
2249
  const spans = /* @__PURE__ */ new Map();
@@ -2247,18 +2259,19 @@ const decisionWindowsOf = (value, ids, occurrencesOf, spares) => {
2247
2259
  const windows = [];
2248
2260
  for (const [root, [from, to]] of spans) {
2249
2261
  const nodes = valueRootNodes(value, root);
2250
- if (spares?.builds(null, root)) return null;
2262
+ const window = {
2263
+ from,
2264
+ root,
2265
+ to
2266
+ };
2267
+ if (spares?.windowBuildsGenerated(window)) return null;
2251
2268
  if (startsAtBoundary(nodes.at(from)) || startsAtBoundary(nodes.at(to))) return null;
2252
2269
  for (let at = from; at < to; at += 1) {
2253
2270
  const block = nodes.at(at);
2254
2271
  if (!block || ownsRoot(block)) return null;
2255
- if (spares && holdsSpares(block, root, spares)) return null;
2272
+ if (spares && holdsSpares(block, spares)) return null;
2256
2273
  }
2257
- windows.push({
2258
- from,
2259
- root,
2260
- to
2261
- });
2274
+ windows.push(window);
2262
2275
  }
2263
2276
  return windows;
2264
2277
  };
@@ -2721,12 +2734,14 @@ const isPendingHolder = (holder, pending) => holder.holds === "restores" ? pendi
2721
2734
  const decidable = (mark) => !isEditingChange(mark.change);
2722
2735
  const aboveOf = (claimed, spare, waitsOn) => ({
2723
2736
  below: /* @__PURE__ */ new Map(),
2737
+ childReads: /* @__PURE__ */ new WeakMap(),
2724
2738
  claimed,
2725
2739
  reads: /* @__PURE__ */ new WeakMap(),
2726
2740
  spare,
2727
2741
  waitsOn
2728
2742
  });
2729
2743
  const NO_READS = Object.freeze([]);
2744
+ const NO_NODES = Object.freeze([]);
2730
2745
  const NO_ROOTS$2 = Object.freeze([]);
2731
2746
  /**
2732
2747
  * Reads elements for the generated values they hold, once per element and
@@ -2808,17 +2823,8 @@ var ElementReads = class {
2808
2823
  if (new Set(holders.slice(first).map(([at]) => at)).size > 1) links.push(key);
2809
2824
  }
2810
2825
  const below = this.below(above, node, claimed, contexts, joins, types);
2811
- let marked = readMembers(node).length > 0;
2812
- const children = [];
2813
- for (const child of node.children ?? []) {
2814
- if (isText$5(child)) {
2815
- marked ||= readMembers(child).length > 0;
2816
- continue;
2817
- }
2818
- const read = this.of(child, below);
2819
- marked ||= read.marked;
2820
- children.push(read);
2821
- }
2826
+ const { children, marked: childMarked } = this.childrenOf(node.children ?? NO_NODES, below);
2827
+ const marked = childMarked || readMembers(node).length > 0;
2822
2828
  const spares = above.spare ? NO_READS : sparesIn(node).flatMap((member) => member.built ? [] : [this.of(member.node, this.spare)]);
2823
2829
  const owns = above.spare ? NO_ROOTS$2 : ownedRootsOf(reading.schema, node);
2824
2830
  const read = {
@@ -2839,6 +2845,28 @@ var ElementReads = class {
2839
2845
  above.reads.set(node, read);
2840
2846
  return read;
2841
2847
  }
2848
+ childrenOf(nodes, below) {
2849
+ const known = below.childReads.get(nodes);
2850
+ if (known) return known;
2851
+ let marked = false;
2852
+ const children = [];
2853
+ for (const child of nodes) {
2854
+ countCoreWork("readChildScans");
2855
+ if (isText$5(child)) {
2856
+ marked ||= readMembers(child).length > 0;
2857
+ continue;
2858
+ }
2859
+ const read = this.of(child, below);
2860
+ marked ||= read.marked;
2861
+ children.push(read);
2862
+ }
2863
+ const reads = {
2864
+ children,
2865
+ marked
2866
+ };
2867
+ below.childReads.set(nodes, reads);
2868
+ return reads;
2869
+ }
2842
2870
  below(above, node, claimed, contexts, joins, types) {
2843
2871
  if (claimed === above.claimed && contexts.length === 0 && joins.length === 0 && types.length === 0) return above;
2844
2872
  const adds = JSON.stringify([
@@ -2861,6 +2889,7 @@ var ElementReads = class {
2861
2889
  }
2862
2890
  };
2863
2891
  const diffLists = (before, after, visit) => {
2892
+ if (before === after) return;
2864
2893
  let start = 0;
2865
2894
  let endBefore = before.length;
2866
2895
  let endAfter = after.length;
@@ -3172,6 +3201,7 @@ const buildsElement = (mark) => removes(mark, "reject") || mergesUp(mark, "rejec
3172
3201
  * @internal
3173
3202
  */
3174
3203
  const changesBuild = (mark, on) => on === "container" ? isPlaceChange(mark) : removes(mark, "accept") || removes(mark, "reject") || mergesUp(mark, "accept") || mergesUp(mark, "reject") || isStructureChange(mark);
3204
+ const someSlotInReach = (slots, standingUnderEveryVerdict) => slots.some((slot) => "prefix" in slot) || standingUnderEveryVerdict <= Math.max(...slots.map((slot) => "min" in slot ? slot.min : -1));
3175
3205
  /**
3176
3206
  * The claims that can change what completing a container builds: the
3177
3207
  * container's own and each child's that `changesBuild` names, among those
@@ -3183,11 +3213,19 @@ const changesBuild = (mark, on) => on === "container" ? isPlaceChange(mark) : re
3183
3213
  *
3184
3214
  * @internal
3185
3215
  */
3186
- const buildClaimsOf = (container, children, claimsOf, isPending, joinOf) => [...container === null ? [] : claimsOf(container).filter((mark) => isPending(mark) && changesBuild(mark, "container")), ...children.flatMap((child) => claimsOf(child).flatMap((mark) => {
3187
- const follows = followsOf(mark);
3188
- const join = follows === void 0 ? null : joinOf(follows, child);
3189
- return [...isPending(mark) && changesBuild(mark, "child") ? [mark] : [], ...join ? [join] : []];
3190
- }))];
3216
+ const buildClaimsOf = (container, children, claimsOf, isPending, joinOf, reach) => {
3217
+ const own = container === null ? [] : claimsOf(container).filter((mark) => isPending(mark) && changesBuild(mark, "container"));
3218
+ const onChild = (child) => claimsOf(child).flatMap((mark) => {
3219
+ const follows = followsOf(mark);
3220
+ const join = follows === void 0 ? null : joinOf(follows, child);
3221
+ return [...isPending(mark) && changesBuild(mark, "child") ? [mark] : [], ...join ? [join] : []];
3222
+ });
3223
+ const perChild = children.map(onChild);
3224
+ const claims = [...own, ...perChild.flat()];
3225
+ if (!reach || own.length > 0 || claims.length === 0) return claims;
3226
+ const standing = (reach.unlistedStanding ?? 0) + children.filter((child, index) => (reach.kept?.(child) ?? true) && perChild[index]?.length === 0).length;
3227
+ return someSlotInReach(reach.slots, standing) ? claims : [];
3228
+ };
3191
3229
  const joinKeysOf = (marks) => new Set(marks.flatMap((mark) => mark.kind === "join" ? [linkOf(mark)] : []));
3192
3230
  const followerPassage = (children, claimsOf) => {
3193
3231
  const blocks = textBlocksIn(children, []);
@@ -3295,6 +3333,7 @@ const cutIndexIn = (value, dependencies, schema) => {
3295
3333
  if (index) return index;
3296
3334
  const fragments = /* @__PURE__ */ new Map();
3297
3335
  const copies = /* @__PURE__ */ new Map();
3336
+ const rights = /* @__PURE__ */ new Set();
3298
3337
  const visit = (nodes, block, root) => {
3299
3338
  for (const node of nodes) {
3300
3339
  for (const tag of cutsOf(node)) {
@@ -3306,6 +3345,7 @@ const cutIndexIn = (value, dependencies, schema) => {
3306
3345
  });
3307
3346
  continue;
3308
3347
  }
3348
+ rights.add(tag.cut);
3309
3349
  const copied = splitCopiesOf(dependencies.marks(node), tag.change);
3310
3350
  const entry = {
3311
3351
  copied,
@@ -3327,13 +3367,17 @@ const cutIndexIn = (value, dependencies, schema) => {
3327
3367
  for (const [root, children] of [["main", value.children], ...Object.entries(value.roots ?? {})]) for (const block of textBlocksOf(children)) visit(block.node.children ?? [], block, root);
3328
3368
  index = {
3329
3369
  copies,
3330
- fragments
3370
+ fragments,
3371
+ rights
3331
3372
  };
3332
3373
  return index;
3333
3374
  };
3334
3375
  return {
3335
3376
  copiedFrom: (key) => read().copies.get(key) ?? [],
3336
- ...ownedRootsDropLate ? {} : { leftOf: (cut) => read().fragments.get(cut) }
3377
+ ...ownedRootsDropLate ? {} : {
3378
+ hasRight: (cut) => read().rights.has(cut),
3379
+ leftOf: (cut) => read().fragments.get(cut)
3380
+ }
3337
3381
  };
3338
3382
  };
3339
3383
  const pastFollowers = (children, from, claimsOf) => {
@@ -3556,6 +3600,34 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
3556
3600
  const wait = (marks) => {
3557
3601
  for (const mark of marks) if (decisionOf(mark) === "keep") waits.add(mark.change);
3558
3602
  };
3603
+ let { deciding } = options;
3604
+ const decidingIn = (nodes, into) => {
3605
+ for (const node of nodes) {
3606
+ for (const mark of readAuthoredMarks(node)) {
3607
+ if (outcomeOf(mark.change) === "keep") continue;
3608
+ into.authors.add(mark.author);
3609
+ into.changes.add(mark.change);
3610
+ }
3611
+ decidingIn(node.children ?? [], into);
3612
+ }
3613
+ return into;
3614
+ };
3615
+ const decidingCards = () => deciding ??= typeof outcome === "string" ? "every" : decidingIn(children, {
3616
+ authors: /* @__PURE__ */ new Set(),
3617
+ changes: /* @__PURE__ */ new Set()
3618
+ });
3619
+ const onAnotherCard = (mark) => {
3620
+ const cards = decidingCards();
3621
+ return !isEditingChange(mark.change) && cards !== "every" && !cards.changes.has(mark.change);
3622
+ };
3623
+ const onAnotherAuthorsCard = (mark) => {
3624
+ const cards = decidingCards();
3625
+ return onAnotherCard(mark) && cards !== "every" && !cards.authors.has(mark.author);
3626
+ };
3627
+ const waitOnOwn = (marks, apart) => {
3628
+ for (const mark of marks) if (decisionOf(mark) === "keep" && !apart(mark)) waits.add(mark.change);
3629
+ };
3630
+ const waitOnType = (marks) => waitOnOwn(marks.filter((mark) => mark.kind === "format" && mark.key === "type"), onAnotherAuthorsCard);
3559
3631
  const waitOnPlaceChanges = (at) => {
3560
3632
  for (const node of at) wait(pending(node).filter(isPlaceChange));
3561
3633
  };
@@ -3597,12 +3669,13 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
3597
3669
  const takesWhole = (node) => ownMarkRemoves(node) && gridPart(node);
3598
3670
  const decidedWholeByGridPart = (mark, above) => (mark.kind === "insert" || mark.kind === "delete") && above.some((ancestor) => gridPart(ancestor) && pending(ancestor).some((outer) => outer.kind === mark.kind && outer.change === mark.change));
3599
3671
  const gridHolder = schema ? gridHoldersOf(schema.ownership) : () => false;
3600
- const { survives } = survivalUnder(ownMarkRemoves, gridPart);
3672
+ const { liveContent, survives } = survivalUnder(ownMarkRemoves, gridPart);
3601
3673
  const reading = {
3602
3674
  accepted: (member) => isAccepted(facts, member),
3603
3675
  landed: facts.landed,
3604
3676
  outcome: (tag) => isRejected(facts, tag) ? "reject" : outcomeOf(tag.change),
3605
- output: elementSplitOutput(schema?.ownership ?? null)
3677
+ output: elementSplitOutput(schema?.ownership ?? null),
3678
+ onAnotherAuthorsCard
3606
3679
  };
3607
3680
  const decidedPropsOf = (node) => decideFormats(propsOf$4(node), pending(node), reading)?.props ?? propsOf$4(node);
3608
3681
  /** The place of a node under `chain`, its containers nearest first. */
@@ -3615,8 +3688,11 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
3615
3688
  };
3616
3689
  };
3617
3690
  /** One side of a cut, from the claims its verdict site already read. */
3618
- const halfOf = (node, claims, place) => {
3619
- const formats = decideFormats(propsOf$4(node), claims, reading);
3691
+ const halfOf = (node, claims, place, othersStayJoined = () => false) => {
3692
+ const formats = decideFormats(propsOf$4(node), claims, {
3693
+ ...reading,
3694
+ outcome: (tag) => othersStayJoined(tag) ? "reject" : reading.outcome(tag)
3695
+ });
3620
3696
  const values = formats?.props ?? propsOf$4(node);
3621
3697
  return {
3622
3698
  decided: values,
@@ -3643,11 +3719,12 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
3643
3719
  return values;
3644
3720
  };
3645
3721
  const probed = /* @__PURE__ */ new Map();
3646
- const probeUnder = (assignment, key, left, rightKeys) => {
3647
- const id = [...assignment].map(([change, action]) => `${action}:${change}`).join(" ");
3722
+ const probeUnder = (assignment, key, left, rightKeys, othersPending) => {
3723
+ const id = [...[...assignment].map(([change, action]) => `${action}:${change}`), ...[...othersPending].map((change) => `others:${change}`)].join(" ");
3648
3724
  const known = probed.get(key)?.get(id);
3649
3725
  if (known) return known;
3650
3726
  const run = {
3727
+ othersPending,
3651
3728
  key,
3652
3729
  left,
3653
3730
  rightKeys,
@@ -3655,6 +3732,7 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
3655
3732
  };
3656
3733
  resolveIn(given, (change) => assignment.get(change) ?? outcomeOf(change), schema, root, {
3657
3734
  ...options,
3735
+ deciding: decidingCards(),
3658
3736
  dependencies: createDependencies(facts),
3659
3737
  facts
3660
3738
  }, run);
@@ -3677,20 +3755,32 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
3677
3755
  };
3678
3756
  const cutVerdict = (key, storedLeft, halves, around, stays) => {
3679
3757
  let rightKeys;
3680
- const undecided = (mark) => !decidedWholeByGridPart(mark, around.place) && !stays?.(mark);
3681
- const unheld = (half) => ({
3682
- ...half,
3683
- pending: half.pending.filter(undecided)
3684
- });
3685
- const result = verdictOf(schema?.ownership ?? null, {
3686
- ...halves,
3687
- left: unheld(halves.left),
3688
- right: unheld(halves.right)
3689
- }, around, {
3690
- pendingOf: pendingOf && ((node) => pendingOf(node).filter(undecided)),
3691
- probe: probe ? null : (assignment) => probeUnder(assignment, key, storedLeft, rightKeys ??= rightKeysOf(halves)),
3692
- survives
3693
- });
3758
+ const others = /* @__PURE__ */ new Set();
3759
+ const settleWithOthersPending = (othersPending) => {
3760
+ const undecided = (mark) => {
3761
+ if (onAnotherAuthorsCard(mark)) others.add(mark.change);
3762
+ return !decidedWholeByGridPart(mark, around.place) && !stays?.(mark) && !othersPending.has(mark.change);
3763
+ };
3764
+ const unheld = (half) => ({
3765
+ ...half,
3766
+ pending: half.pending.filter(undecided)
3767
+ });
3768
+ return verdictOf(schema?.ownership ?? null, {
3769
+ ...halves,
3770
+ left: unheld(halves.left),
3771
+ right: unheld(halves.right)
3772
+ }, around, {
3773
+ pendingOf: pendingOf && ((node) => pendingOf(node).filter(undecided)),
3774
+ probe: probe ? null : (assignment) => probeUnder(assignment, key, storedLeft, rightKeys ??= rightKeysOf(halves), othersPending),
3775
+ survives
3776
+ });
3777
+ };
3778
+ let othersPending = probe?.othersPending ?? /* @__PURE__ */ new Set();
3779
+ let result = settleWithOthersPending(othersPending);
3780
+ if (probe?.key !== key) while ("waits" in result && result.waits.length > 0 && result.waits.every((change) => others.has(change) && !othersPending.has(change))) {
3781
+ othersPending = /* @__PURE__ */ new Set([...othersPending, ...result.waits]);
3782
+ result = settleWithOthersPending(othersPending);
3783
+ }
3694
3784
  if (probe?.key === key) probe.settled = probe.left !== storedLeft ? { verdict: "apart" } : "verdict" in result && result.verdict === "together" && !joinKeeps(key, halves, probe.rightKeys) ? { waits: [] } : result;
3695
3785
  if ("waits" in result) {
3696
3786
  for (const change of result.waits) waits.add(change);
@@ -3746,6 +3836,15 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
3746
3836
  const { liveContent: liveAt } = survivalUnder((node) => pending(node).some((mark) => removes(mark, resultOf(mark)) && (mark.kind !== "delete" || deletesBeforeJoin(mark, join))), gridPart);
3747
3837
  return (target.children ?? []).some(liveAt) || (mergedBlocks.get(target) ?? []).some((block) => (block.children ?? []).some(liveAt));
3748
3838
  };
3839
+ const emptiedByJoin = (target, join, editing) => {
3840
+ const ownRemoved = (child) => pending(child).some((mark) => mark.kind === "delete" && resultOf(mark) === "accept" && join.own.has(incarnationOf(mark)));
3841
+ const { liveContent: liveNow } = survivalUnder(() => false, gridPart);
3842
+ const { liveContent: liveAfter } = survivalUnder(ownRemoved, gridPart);
3843
+ const pieces = [target, ...mergedBlocks.get(target) ?? []];
3844
+ const hasLiveNow = pieces.some((block) => (block.children ?? []).some(liveNow));
3845
+ const hasLiveAfter = pieces.some((block) => (block.children ?? []).some(liveAfter));
3846
+ return editing ? !hasLiveNow : hasLiveNow && !hasLiveAfter;
3847
+ };
3749
3848
  const { liveContent: keptContent } = survivalUnder((node) => pending(node).some((mark) => removes(mark, decisionOf(mark)) || (mark.kind === "insert" || mark.kind === "delete") && decisionOf(mark) === "keep"), gridPart);
3750
3849
  const joinOf = (node) => {
3751
3850
  const marks = pending(node).filter((mark) => mergesUp(mark, resultOf(mark)));
@@ -3765,7 +3864,8 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
3765
3864
  const rejoinOf = (cut, node, own, into, target, ancestors) => {
3766
3865
  const chain = [...[...ancestors].reverse(), ...site];
3767
3866
  const place = placeUnder(chain);
3768
- const left = halfOf(into, target, place);
3867
+ const uncopied = (tag) => onAnotherAuthorsCard(tag) && !own.some((mark) => mark.kind === "format" && mark.id === tag.id);
3868
+ const left = halfOf(into, target, place, uncopied);
3769
3869
  const forced = own.some((mark) => mark.kind === "format" && mark.key === "type" && mark.change === cut.change) || !schema?.continuationType ? null : schema.continuationType({
3770
3870
  ...left.props,
3771
3871
  children: into.children ?? []
@@ -3788,7 +3888,8 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
3788
3888
  reads: []
3789
3889
  };
3790
3890
  const reads = (into.children ?? []).some(keptContent) ? [] : (into.children ?? []).flatMap(contentMarksIn);
3791
- return !rejoins || keepsContent(into, joinOf(node)) ? {
3891
+ const shapedByAnother = () => pending(into).some((mark) => isStructureChange(mark) && onAnotherCard(mark) || mark.kind === "format" && undecided(facts, mark) && onAnotherAuthorsCard(mark));
3892
+ return !rejoins || keepsContent(into, joinOf(node)) || shapedByAnother() ? {
3792
3893
  merges: true,
3793
3894
  reads
3794
3895
  } : {
@@ -3879,12 +3980,7 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
3879
3980
  blocks.forEach(({ ancestors, node }, index) => {
3880
3981
  const { editingJoin, join } = structureOf(node);
3881
3982
  if (!join) return;
3882
- let deciders;
3883
- const othersPendingOnText = (mark) => {
3884
- if (editingJoin || mark.kind !== "insert" && mark.kind !== "delete") return false;
3885
- deciders ??= new Set(pending(node).flatMap((own) => mergesUp(own, resultOf(own)) ? [own.author] : []));
3886
- return !deciders.has(mark.author) && marksNonEmptyText(mark);
3887
- };
3983
+ const othersPendingOnText = (mark) => !editingJoin && (mark.kind === "insert" || mark.kind === "delete") && onAnotherAuthorsCard(mark) && marksNonEmptyText(mark);
3888
3984
  let target = null;
3889
3985
  const waited = editingJoin || (node.children ?? []).some(keptContent) ? [] : contentMarksIn(node);
3890
3986
  const land = (effect) => {
@@ -3896,7 +3992,7 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
3896
3992
  retainedJoins.add(node);
3897
3993
  return;
3898
3994
  }
3899
- wait(waiting);
3995
+ waitOnOwn(waiting, onAnotherAuthorsCard);
3900
3996
  effect?.();
3901
3997
  };
3902
3998
  if (!survives(node)) {
@@ -3966,6 +4062,7 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
3966
4062
  }
3967
4063
  land(() => {
3968
4064
  if (left) rejoined.set(node, left);
4065
+ if (!cut && handover.keys.size > 0 && typeOf$2(decidedPropsOf(into)) === typeOf$2(decidedPropsOf(node)) && emptiedByJoin(into, joinOf(node), editingJoin) && (ancestors.length > 0 || site.length > 0 || blocks.some((block) => block.node !== into && block.node !== node && survives(block.node)) || (node.children ?? []).some((child) => liveContent(child) && !pending(child).some((mark) => mark.kind === "insert" && joinOf(node).own.has(incarnationOf(mark)))))) handover.pass(node, into);
3969
4066
  mergedInto.set(node, into);
3970
4067
  mergedBlocks.set(into, [...mergedBlocks.get(into) ?? [], node]);
3971
4068
  });
@@ -4005,6 +4102,18 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
4005
4102
  const line = standsFor.get(node);
4006
4103
  return [node, ...line ? movedWith(line) : []];
4007
4104
  };
4105
+ const ownJoinWaits = (previous, previousIndex) => {
4106
+ const target = finalOf(previous);
4107
+ if (emptiedTargets.has(target) || placedAfter.has(standingOf(target))) return true;
4108
+ for (let at = previousIndex - 1; at >= 0; at -= 1) {
4109
+ const middle = getDefined(blocks[at]);
4110
+ if (middle.node === target) return false;
4111
+ const emptiedDepth = emptiedDepthOf(middle.ancestors);
4112
+ const emptiedHost = emptiedDepth >= 0 ? middle.ancestors[emptiedDepth] : void 0;
4113
+ if (survives(middle.node) && !mergedInto.has(middle.node) && !placed.has(middle.node) && !standsIn.has(middle.node) || emptiedHost !== void 0 && !structureOf(emptiedHost).unwrap) return true;
4114
+ }
4115
+ return true;
4116
+ };
4008
4117
  blocks.forEach(({ ancestors, node }, index) => {
4009
4118
  const joins = pending(node).filter((mark) => mark.kind === "join" && decisionOf(mark) === "keep");
4010
4119
  if (joins.length === 0 || !survives(node)) return;
@@ -4014,7 +4123,10 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
4014
4123
  while (before >= 0 && precedesJoin(getDefined(blocks[before]), keys)) before -= 1;
4015
4124
  const candidate = blocks[before];
4016
4125
  const previous = candidate && (!container || candidate.ancestors.includes(container)) ? candidate.node : null;
4017
- if (previous && (!survives(previous) || mergedInto.has(previous) || emptiedTargets.has(previous))) wait(joins);
4126
+ if (!previous) return;
4127
+ if (mergedInto.has(previous)) {
4128
+ if (ownJoinWaits(previous, before)) waitOnOwn(joins, onAnotherAuthorsCard);
4129
+ } else if (!survives(previous) || emptiedTargets.has(previous)) waitOnOwn(joins, onAnotherAuthorsCard);
4018
4130
  });
4019
4131
  const cutSides = /* @__PURE__ */ new Map();
4020
4132
  const holdsRejectedSplitCopies = (node) => {
@@ -4049,6 +4161,15 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
4049
4161
  root
4050
4162
  } : cutIndex?.leftOf?.(cut);
4051
4163
  };
4164
+ const inBlockCutsOnly = (node) => {
4165
+ const cuts = cutsOf(node);
4166
+ return cuts.length > 0 && cuts.every(({ change, cut }) => {
4167
+ const sides = cutSides.get(cut);
4168
+ if (change !== cuts[0]?.change || !sides) return false;
4169
+ if (sides.start !== void 0 && sides.end !== void 0) return sides.start === sides.end;
4170
+ return sides.start === void 0 ? !!cutIndex?.hasRight && !cutIndex.hasRight(cut) : !!cutIndex?.leftOf && !cutIndex.leftOf(cut);
4171
+ });
4172
+ };
4052
4173
  const standsWhenCutDecides = ({ block, node }) => survives(node) || ownMarkRemoves(node) && survives(block.node);
4053
4174
  const predecessorsOf = ({ node }, seen = /* @__PURE__ */ new Set()) => {
4054
4175
  if (seen.has(node)) return [];
@@ -4118,7 +4239,7 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
4118
4239
  if (!endNode || decisionOf(tag) !== "keep") continue;
4119
4240
  const starts = cutsOf(endNode).filter(({ side }) => side === "start");
4120
4241
  if (starts.every((start) => decisionOf(start) === "keep")) {
4121
- if (!survives(endNode)) wait(starts);
4242
+ if (!survives(endNode)) waitOnOwn(starts, ({ change }) => change === tag.change);
4122
4243
  } else if (survives(endNode)) wait(pending(endNode).filter(({ kind }) => kind === "delete"));
4123
4244
  }
4124
4245
  if (probe?.settled) return null;
@@ -4278,6 +4399,7 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
4278
4399
  wait(inner);
4279
4400
  if (ownMarkRemoves(node) && !survives(node)) {
4280
4401
  if (whole) takenWhole.add(original);
4402
+ else if (inBlockCutsOnly(node)) waitOnOwn(cutsOf(node), onAnotherAuthorsCard);
4281
4403
  else wait(cutsOf(node));
4282
4404
  if (isText$4(node)) changed = true;
4283
4405
  else {
@@ -4310,7 +4432,7 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
4310
4432
  const kept = withBuiltSpares(keptMembers(shell, marks, (mark) => {
4311
4433
  const result = resultOf(mark);
4312
4434
  return mark.kind === "format" ? formats?.kept.has(mark) ?? false : result === "keep" && !mergesBeyondMark(node, mark) || mark.kind === "join" && result === "accept" && retainedJoins.has(node) || (retainedFollowers.get(node)?.has(followerKeyOf(mark)) ?? false);
4313
- }, stores && sparesIn(shell).length > 0 && stillBuilds(shell, [...node.children ?? [], ...(mergedBlocks.get(node) ?? []).flatMap((block) => block.children ?? [])])), landedSpares.get(original) ?? landedSpares.get(node));
4435
+ }, stores && sparesIn(shell).length > 0 && stillBuilds(shell, [...node.children ?? [], ...(mergedBlocks.get(node) ?? []).flatMap((block) => block.children ?? [])], sparesIn(shell).map(({ slot }) => slot))), landedSpares.get(original) ?? landedSpares.get(node));
4314
4436
  const dropsValue = placedProps !== decidedProps;
4315
4437
  if (dropsValue) waitOnPlaceChanges([node, ...above]);
4316
4438
  const outlived = [...new Map(inner.filter((mark) => mark.kind === "delete" && decisionOf(mark) === "keep" && !kept.includes(mark)).map((mark) => [incarnationOf(mark), mark])).values()];
@@ -4359,8 +4481,8 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
4359
4481
  restructured = true;
4360
4482
  unwrapped.add(node);
4361
4483
  if (resolved.some(isText$4) && contentOf(parentType)?.allowsText === false) unplaceable = true;
4362
- wait(pending({ [AUTHORED_MARKS_KEY]: formatted.kept }));
4363
- wait([resolved[0], nodes[index + 1]].flatMap((item) => pending(item).filter((mark) => mark.kind === "join" || mark.kind === "split")));
4484
+ waitOnOwn(pending({ [AUTHORED_MARKS_KEY]: formatted.kept }), onAnotherAuthorsCard);
4485
+ waitOnOwn([resolved[0], nodes[index + 1]].flatMap((item) => pending(item).filter((mark) => mark.kind === "join" || mark.kind === "split")), onAnotherCard);
4364
4486
  landFormats();
4365
4487
  for (const at of childDirty) dirty.push(out.length + at);
4366
4488
  out.push(...resolved);
@@ -4378,7 +4500,7 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
4378
4500
  }
4379
4501
  landFormats();
4380
4502
  if (emptied) {
4381
- wait(pending({ [AUTHORED_MARKS_KEY]: formatted.kept }).filter((mark) => !decidedWholeByGridPart(mark, above)));
4503
+ waitOnType(pending({ [AUTHORED_MARKS_KEY]: formatted.kept }));
4382
4504
  restructured = true;
4383
4505
  }
4384
4506
  out.push(track(element, original));
@@ -4402,27 +4524,43 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
4402
4524
  list: out
4403
4525
  };
4404
4526
  };
4405
- const stillBuilds = (container, inside) => {
4527
+ const stillBuilds = (container, inside, slots, resolvedLevel) => {
4406
4528
  const keeps = (mark) => decisionOf(mark) === "keep";
4529
+ const joins = /* @__PURE__ */ new Set();
4407
4530
  const standing = (level) => level.flatMap((child) => ownMarkRemoves(child) && !survives(child) ? [] : structureOf(child).unwrap ? standing(child.children ?? []) : [child]);
4408
- return buildClaimsOf(container, standing(inside), pending, keeps, (link, child) => {
4531
+ const claims = buildClaimsOf(container, standing(inside), pending, keeps, (link, child) => {
4409
4532
  const join = links.sourceOf([link], getDefined(followerOrders.get(child)))?.mark;
4410
- return join && keeps(join) ? join : null;
4411
- }).length > 0;
4533
+ if (!join || !keeps(join)) return null;
4534
+ joins.add(join);
4535
+ return join;
4536
+ }, { slots });
4537
+ if (!resolvedLevel || claims.length === 0) return claims.length > 0;
4538
+ const standingChanges = /* @__PURE__ */ new Set();
4539
+ const collect = (level) => {
4540
+ for (const node of level) {
4541
+ const marks = readAuthoredMarks(node);
4542
+ for (const mark of marks) standingChanges.add(mark.change);
4543
+ if (marks.some((mark) => mark.kind === "unwrap")) collect(node.children ?? []);
4544
+ }
4545
+ };
4546
+ collect(resolvedLevel);
4547
+ return claims.some((mark) => joins.has(mark) || standingChanges.has(mark.change));
4412
4548
  };
4413
4549
  const builtIn = /* @__PURE__ */ new WeakMap();
4414
4550
  const rootBuilt = /* @__PURE__ */ new Set();
4415
4551
  const waitOnBuild = (level, at) => {
4416
4552
  const [parent, ...ancestors] = at;
4417
- wait(pending(parent).filter((mark) => isPlaceChange(mark) || mark.kind === "delete"));
4418
- for (const child of level) wait(pending(child).filter(isStructureChange));
4419
- for (const ancestor of ancestors) wait(pending(ancestor).filter(isStructureChange));
4553
+ waitOnType(pending(parent));
4554
+ for (const node of [...level, ...ancestors]) waitOnOwn(pending(node).filter(isStructureChange), onAnotherAuthorsCard);
4420
4555
  };
4421
4556
  const waitOnPrefix = (level, completed, start, completeHere, slots) => {
4422
4557
  wait(slotDecidingInsertions(level, completed, completeHere, slots, (node) => start.includes(origins.get(node) ?? node), isInserted).flatMap((node) => pending(node).filter((mark) => mark.kind === "insert")));
4423
4558
  };
4424
- const underInsertions = (completion, at) => {
4425
- const marks = at.flatMap((node) => pending(node).filter((mark) => mark.kind === "insert" && decisionOf(mark) === "keep"));
4559
+ const underPendingContent = (completion, at) => {
4560
+ const marks = at.flatMap((node, index) => {
4561
+ const kept = pending(node).filter((mark) => decisionOf(mark) === "keep");
4562
+ return [...kept.filter((mark) => mark.kind === "insert" || mark.kind === "delete"), ...index === 0 ? dissolveClaimsOf(kept) : []];
4563
+ });
4426
4564
  if (marks.length === 0 || completion.built.length === 0) return completion;
4427
4565
  const marked = new Map(completion.built.map(({ node }) => [node, dependencies.throughout(node, marks)]));
4428
4566
  return {
@@ -4500,7 +4638,7 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
4500
4638
  if (at[0]) builtIn.set(at[0], keys);
4501
4639
  else for (const key of keys) rootBuilt.add(key);
4502
4640
  }
4503
- const completion = underInsertions(completed, at);
4641
+ const completion = underPendingContent(completed, at);
4504
4642
  if (completion.built.length > 0) {
4505
4643
  for (const item of completion.built) addUnstored(item.node);
4506
4644
  waitOnBuild(nodes, at);
@@ -4542,7 +4680,7 @@ const resolveIn = (given, outcome, schema, root, options, probe) => {
4542
4680
  };
4543
4681
  for (const node of removed ?? []) hidden.add(node);
4544
4682
  const spares = /* @__PURE__ */ new Map();
4545
- if (stores && rootSpares.length > 0) putRootSpares(rootSpares, stillBuilds(null, given), rootBuilt, spares);
4683
+ if (stores && rootSpares.length > 0) putRootSpares(rootSpares, stillBuilds(null, given, rootSpares.map(({ slot }) => slot), resolvedChildren), rootBuilt, spares);
4546
4684
  return {
4547
4685
  blockers: [...waits],
4548
4686
  children: resolvedChildren,
@@ -4777,12 +4915,17 @@ const resolveValueIn = (value, outcome, schema, options) => {
4777
4915
  resolvedOf: (original) => live.reduce((found, resolution) => found ?? resolution.resolvedOf(original), null),
4778
4916
  takenWhole: new Set(all.flatMap((resolution) => [...resolution.takenWhole])),
4779
4917
  unplaceable: live.some((resolution) => resolution.unplaceable),
4918
+ unstored: new Set(live.flatMap((resolution) => [...resolution.unstored])),
4780
4919
  value: deriveValue(base, {
4781
4920
  children: childrenIn("main"),
4782
4921
  ...base.roots ? { roots: Object.fromEntries(kept.map(([root]) => [root, childrenIn(root)])) } : {}
4783
4922
  }, composeRecordOps(composeRecordOps(putContexts(dependencies.minted()), putLanded(live.flatMap((resolution) => resolution.landed))), reserveOps))
4784
4923
  };
4785
4924
  };
4925
+ const windowPart = ({ from }) => ({
4926
+ head: from === 0,
4927
+ min: 0
4928
+ });
4786
4929
  const resolveAuthoredWindows = (value, windows, outcome, schema, options) => readingCovered({
4787
4930
  cover: () => schema && coverStoredValues(schema.ownership, reserveNodesIn(getValueRecords(value))),
4788
4931
  read: () => {
@@ -4795,10 +4938,16 @@ const resolveAuthoredWindows = (value, windows, outcome, schema, options) => rea
4795
4938
  crossed = true;
4796
4939
  return cuts.copiedFrom(key);
4797
4940
  },
4798
- ...cuts.leftOf ? { leftOf: (cut) => {
4799
- crossed = true;
4800
- return cuts.leftOf?.(cut);
4801
- } } : {}
4941
+ ...cuts.leftOf ? {
4942
+ hasRight: (cut) => {
4943
+ crossed = true;
4944
+ return !!cuts.hasRight?.(cut);
4945
+ },
4946
+ leftOf: (cut) => {
4947
+ crossed = true;
4948
+ return cuts.leftOf?.(cut);
4949
+ }
4950
+ } : {}
4802
4951
  };
4803
4952
  const resolved = windows.map((window) => {
4804
4953
  const before = valueRootNodes(value, window.root).slice(window.from, window.to);
@@ -4810,10 +4959,7 @@ const resolveAuthoredWindows = (value, windows, outcome, schema, options) => rea
4810
4959
  cutIndex,
4811
4960
  dependencies,
4812
4961
  facts,
4813
- part: {
4814
- head: window.from === 0,
4815
- min: 0
4816
- }
4962
+ part: windowPart(window)
4817
4963
  })
4818
4964
  };
4819
4965
  });
@@ -4828,6 +4974,7 @@ const resolveAuthoredWindows = (value, windows, outcome, schema, options) => rea
4828
4974
  resolvedOf: (original) => all.reduce((found, resolution) => found ?? resolution.resolvedOf(original), null),
4829
4975
  takenWhole: new Set(all.flatMap((resolution) => [...resolution.takenWhole])),
4830
4976
  unplaceable: all.some((resolution) => resolution.unplaceable),
4977
+ unstored: new Set(all.flatMap((resolution) => [...resolution.unstored])),
4831
4978
  windows: resolved.map(({ before, resolution, ...window }) => ({
4832
4979
  ...window,
4833
4980
  after: resolution.children,
@@ -5064,6 +5211,19 @@ const UNSET_MARKS = Object.freeze([Object.freeze({
5064
5211
  key: AUTHORED_MARKS_KEY,
5065
5212
  type: "unset"
5066
5213
  })]);
5214
+ const memberWrites = (stored, next) => {
5215
+ const added = next.filter((member) => !stored.some((was) => jsonEqual(was, member)));
5216
+ const removed = stored.filter((member) => !next.some((kept) => jsonEqual(member, kept)));
5217
+ return [...removed.length > 0 ? [{
5218
+ key: AUTHORED_MARKS_KEY,
5219
+ type: "remove",
5220
+ values: removed
5221
+ }] : [], ...added.length > 0 ? [{
5222
+ key: AUTHORED_MARKS_KEY,
5223
+ type: "add",
5224
+ values: added
5225
+ }] : []];
5226
+ };
5067
5227
  const leafProps = (node) => {
5068
5228
  const { [AUTHORED_MARKS_KEY]: _marks, text: _text, ...props } = node;
5069
5229
  return props;
@@ -5251,11 +5411,7 @@ const structuralChange = (blocks, accepted) => {
5251
5411
  const modeled = normalizeSetValues([...ops[at] === 2 ? [] : stored.filter((member) => member.kind !== "reserve"), ...sparesIn(decided[rank])]);
5252
5412
  if (ops[at] === 0 && jsonEqual(modeled, stored)) continue;
5253
5413
  ops[at] = 2;
5254
- if (modeled.length > 0) members.set(at, [{
5255
- key: AUTHORED_MARKS_KEY,
5256
- type: "set",
5257
- value: modeled
5258
- }]);
5414
+ members.set(at, memberWrites(stored, modeled));
5259
5415
  }
5260
5416
  }
5261
5417
  const sections = [];
@@ -7705,25 +7861,31 @@ const nodeAt$1 = (children, path) => {
7705
7861
  return {
7706
7862
  ancestors,
7707
7863
  children: level,
7708
- node
7864
+ node,
7865
+ unlistedStanding: 0
7709
7866
  };
7710
7867
  };
7711
7868
  const rootChildren = (value, root) => root === "main" ? value.children : value.roots?.[root] ?? null;
7712
7869
  const siteIn = (blocks, { path, root }) => {
7713
7870
  const index = blocks.indexes.get(root);
7714
7871
  if (!index) return null;
7715
- if (path.length === 0) return {
7716
- ancestors: [],
7717
- children: [...blocks.marked(root)],
7718
- node: null
7719
- };
7872
+ if (path.length === 0) {
7873
+ const children = [...blocks.marked(root)];
7874
+ return {
7875
+ ancestors: [],
7876
+ children,
7877
+ node: null,
7878
+ unlistedStanding: index.size - children.length
7879
+ };
7880
+ }
7720
7881
  const [head, ...rest] = path;
7721
7882
  const top = index.child(head);
7722
7883
  if (!top) return null;
7723
7884
  if (rest.length === 0) return {
7724
7885
  ancestors: [top],
7725
7886
  children: top.children ?? [],
7726
- node: top
7887
+ node: top,
7888
+ unlistedStanding: 0
7727
7889
  };
7728
7890
  const found = nodeAt$1(top.children ?? [], rest);
7729
7891
  return found && {
@@ -7785,7 +7947,7 @@ const buildClaimsIn = (facts, lookup, eachBlock) => {
7785
7947
  const join = sourceOf(link, child)?.mark;
7786
7948
  return join && isPending(join) ? join : null;
7787
7949
  };
7788
- return (container, children, root) => buildClaimsOf(container, children, claimsOf, isPending, joinOf(root));
7950
+ return (container, children, root, reach) => buildClaimsOf(container, children, claimsOf, isPending, joinOf(root), reach);
7789
7951
  };
7790
7952
  /**
7791
7953
  * The spares a write stores in `sites`, the containers it touched, or every
@@ -7802,7 +7964,7 @@ const buildClaimsIn = (facts, lookup, eachBlock) => {
7802
7964
  * unbuilt spares with the command frame's element. Given `blocks`, a site
7803
7965
  * reads its document through them.
7804
7966
  */
7805
- const sparesFor = (document, schema, sites, fills = [], blocks = null) => {
7967
+ const sparesFor = (document, schema, sites, fills = [], blocks = null, author = null) => {
7806
7968
  const generating = generatingOf(schema);
7807
7969
  if (!generating) return NO_SPARE_WRITES;
7808
7970
  const value = document;
@@ -7830,9 +7992,20 @@ const sparesFor = (document, schema, sites, fills = [], blocks = null) => {
7830
7992
  const claims = buildClaims(container, level, site.root);
7831
7993
  const writer = firstOf(claims);
7832
7994
  const filling = fillsAt.get(siteKey) ?? [];
7833
- if (!writer && filling.length === 0) continue;
7834
7995
  const stored = container ? sparesIn(container) : [];
7835
7996
  const rootStored = container ? [] : rootSparesOf(value, site.root);
7997
+ if (!writer && filling.length === 0) {
7998
+ const siteNodes = container ? [container, ...level] : level;
7999
+ const takenBackByWriter = (spare) => !spare.built && spare.author === author && !holdsBase(siteNodes, spare, facts);
8000
+ const dropped = stored.filter(takenBackByWriter);
8001
+ if (dropped.length > 0) containers.push({
8002
+ ...site,
8003
+ added: [],
8004
+ replaced: dropped
8005
+ });
8006
+ for (const { id, record } of rootStored) if (takenBackByWriter(record)) records.set(id, null);
8007
+ continue;
8008
+ }
7836
8009
  const siteOf = (type) => container ? [{
7837
8010
  ...withMembers(container, []),
7838
8011
  children: [],
@@ -7885,6 +8058,7 @@ const sparesFor = (document, schema, sites, fills = [], blocks = null) => {
7885
8058
  const content = type === null ? api().getRootContent(site.root, document) : api().getElementContent(type);
7886
8059
  if (!content || !generating.builds(content)) continue;
7887
8060
  const completion = completeChildrenAt(getRepresentationEditorFromApi(api()), siteOf(type), [], site.root);
8061
+ if (noVerdictReaches(buildClaims, found, site.root, completion.built)) continue;
7888
8062
  for (const { node, slot } of completion.built) {
7889
8063
  if (!generating.generates(String(node.type)) || filled(type, slot)) continue;
7890
8064
  const unbuilt = unbuiltAt(type, slot, String(node.type));
@@ -7905,6 +8079,10 @@ const sparesFor = (document, schema, sites, fills = [], blocks = null) => {
7905
8079
  records: records.size === 0 ? NO_RECORD_OPS : /* @__PURE__ */ new Map([[RESERVES, records]])
7906
8080
  };
7907
8081
  };
8082
+ const noVerdictReaches = (buildClaims, found, root, built) => buildClaims(found.node, found.children, root, {
8083
+ slots: built.map(({ slot }) => slot),
8084
+ unlistedStanding: found.unlistedStanding
8085
+ }).length === 0;
7908
8086
  /**
7909
8087
  * Every container a pending claim sits in or on, for a load to visit, found
7910
8088
  * as they are read so a schema that stores no spare walks nothing.
@@ -8000,6 +8178,88 @@ const withSpareWrites = (document, writes) => {
8000
8178
  } } : {}
8001
8179
  }, writes.records);
8002
8180
  };
8181
+ function* removedElementHostsOf(rootChange, was, index, fromA, toA) {
8182
+ for (const entry of was.nodeRangesTouching(fromA, toA)) {
8183
+ const close = entry.to - 1;
8184
+ if (entry.kind !== "element" || !(fromA <= entry.from && entry.from < toA) && !(fromA <= close && close < toA)) continue;
8185
+ const parent = entry.path.slice(0, -1);
8186
+ if (parent.length === 0) {
8187
+ yield parent;
8188
+ continue;
8189
+ }
8190
+ const start = rootChange.mapPos(was.nodeRange(parent).from, -1);
8191
+ const host = start === null ? null : index.nodeStartingAt(start);
8192
+ if (host?.from === start && host.kind === "element") yield host.path;
8193
+ }
8194
+ }
8195
+ const spareLinesOf = (document, schema) => {
8196
+ if (!storesSpares(schema)) return null;
8197
+ const sites = [];
8198
+ for (const root of documentRootsOf(document)) visitElements(rootChildrenOf(document, root), (node, path) => {
8199
+ const members = sparesIn(node);
8200
+ if (members.length > 0) sites.push({
8201
+ members,
8202
+ path,
8203
+ root
8204
+ });
8205
+ });
8206
+ const records = [...getRecordEntries(getValueRecords(document), RESERVES)].flatMap(([id, json]) => {
8207
+ const record = parseReserve(id, json);
8208
+ return record ? [{
8209
+ id,
8210
+ record
8211
+ }] : [];
8212
+ });
8213
+ const spares = [...sites.flatMap(({ members }) => members), ...records.map(({ record }) => record)];
8214
+ if (spares.length === 0) return null;
8215
+ return {
8216
+ lines: spares.map(({ built, node }) => ({
8217
+ built: built === true,
8218
+ node
8219
+ })),
8220
+ write: (nodes) => {
8221
+ const next = nodes.values();
8222
+ const nodeOf = () => next.next().value;
8223
+ const containers = sites.flatMap(({ members, path, root }) => {
8224
+ const filled = members.flatMap((member) => {
8225
+ const node = nodeOf();
8226
+ return node === member.node ? [] : [{
8227
+ member,
8228
+ node
8229
+ }];
8230
+ });
8231
+ return filled.length === 0 ? [] : [{
8232
+ added: filled.map(({ member, node }) => ({
8233
+ ...member,
8234
+ node
8235
+ })),
8236
+ path,
8237
+ replaced: filled.map(({ member }) => member),
8238
+ root
8239
+ }];
8240
+ });
8241
+ const ops = /* @__PURE__ */ new Map();
8242
+ for (const { id, record } of records) {
8243
+ const node = nodeOf();
8244
+ if (node === record.node) continue;
8245
+ const filled = {
8246
+ ...record,
8247
+ node
8248
+ };
8249
+ ops.set(id, null);
8250
+ ops.set(reserveIdOf(filled), canonicalRecordJson(filled));
8251
+ }
8252
+ const value = withSpareWrites(document, {
8253
+ containers,
8254
+ records: ops.size === 0 ? NO_RECORD_OPS : /* @__PURE__ */ new Map([[RESERVES, ops]])
8255
+ });
8256
+ return {
8257
+ change: DocumentChange.between(document, value, { isSetValued: isAuthoredSetValued }),
8258
+ value
8259
+ };
8260
+ }
8261
+ };
8262
+ };
8003
8263
  /**
8004
8264
  * The containers a recorded `change` touched, read in `indexes`, the
8005
8265
  * document after it: each element whose own tokens it wrote, the element or
@@ -8008,13 +8268,18 @@ const withSpareWrites = (document, writes) => {
8008
8268
  *
8009
8269
  * @yields {SpareSite} Each such container's site, once.
8010
8270
  */
8011
- function* changedSitesOf(change, indexes) {
8271
+ function* changedSitesOf(change, indexes, before) {
8012
8272
  for (const [root, index] of indexes) {
8013
8273
  const rootChange = getInternalDocumentRootChange(change, root);
8014
8274
  if (!rootChange || rootChange.empty) continue;
8015
8275
  const paths = /* @__PURE__ */ new Map();
8016
8276
  const add = (path) => paths.set(path.join(","), path);
8017
- rootChange.iterChangedRanges((_fromA, _toA, from, to) => {
8277
+ let was;
8278
+ rootChange.iterChangedRanges((fromA, toA, from, to) => {
8279
+ if (fromA < toA) {
8280
+ was ??= valueRootIndex(before, root);
8281
+ for (const path of removedElementHostsOf(rootChange, was, index, fromA, toA)) add(path);
8282
+ }
8018
8283
  const open = index.openContextAt(from).filter((entry) => entry.kind === "element" && entry.contentFrom <= from && from <= entry.contentTo);
8019
8284
  add(open.at(-1)?.path ?? []);
8020
8285
  for (const entry of index.nodeRangesTouching(from, to)) {
@@ -8120,6 +8385,32 @@ const storedResolveSchemaOf = (schema, document, options = {}) => detachedResolv
8120
8385
  const detachedResolveSchemaOf = (schema, detached, options = {}) => resolveSchemaOver(getRepresentationEditorFromApi(detached), detached, schema, options);
8121
8386
  //#endregion
8122
8387
  //#region src/authored/decision.ts
8388
+ const NO_BUILT_SPANS = /* @__PURE__ */ new Map();
8389
+ const collectBuiltSpans = (nodes, built, start, spans) => {
8390
+ let offset = start;
8391
+ for (const node of nodes) {
8392
+ const length = tokenLength(node);
8393
+ if (built.has(node)) spans.push([offset, offset + length]);
8394
+ else if (typeof node.text !== "string") collectBuiltSpans(node.children ?? [], built, offset + 1, spans);
8395
+ offset += length;
8396
+ }
8397
+ };
8398
+ const builtSpansOf = (value, decided, windowed, whole) => {
8399
+ const unstored = windowed ? windowed.unstored : whole?.unstored;
8400
+ if (!unstored || unstored.size === 0) return NO_BUILT_SPANS;
8401
+ const byRoot = /* @__PURE__ */ new Map();
8402
+ const add = (root, nodes, start) => {
8403
+ const spans = byRoot.get(root) ?? [];
8404
+ collectBuiltSpans(nodes, unstored, start, spans);
8405
+ if (spans.length > 0) byRoot.set(root, spans);
8406
+ };
8407
+ if (windowed && decided) for (const { after, from, root } of windowed.windows) add(root, after, (decided.indexedAfter.get(root) ?? valueRootIndex(value, root)).childPosition([], from));
8408
+ else if (whole) {
8409
+ add(MAIN_ROOT_KEY, whole.value.children, 0);
8410
+ for (const [root, children] of Object.entries(whole.value.roots ?? {})) add(root, children, 0);
8411
+ }
8412
+ return byRoot;
8413
+ };
8123
8414
  const isRefusal = (error) => error instanceof EditorSchemaValidationError || error instanceof AuthoredMarkError || error instanceof ElementGenerationMaskedError;
8124
8415
  const claimIn = (blocks, facts, change) => {
8125
8416
  const find = (nodes) => {
@@ -8135,8 +8426,9 @@ const claimIn = (blocks, facts, change) => {
8135
8426
  };
8136
8427
  const claimOf = (value, change) => claimIn([...value.children, ...Object.values(value.roots ?? {}).flat()], factsOf(value), change);
8137
8428
  const spareGuardOver = (compiled, schema, value) => storesSpares(compiled) ? {
8138
- builds: (type, root) => completionBuilds(compiled, type === null ? schema.getRootContent(root, value) : schema.getElementContent(type)),
8139
- stored: reserveNodesIn(getValueRecords(value)).length > 0
8429
+ stored: reserveNodesIn(getValueRecords(value)).length > 0,
8430
+ typeBuildsGenerated: (type) => completionBuilds(compiled, schema.getElementContent(type)),
8431
+ windowBuildsGenerated: (window) => completionBuilds(compiled, partOf(schema.getRootContent(window.root, value), windowPart(window)) ?? null)
8140
8432
  } : null;
8141
8433
  const windowedValue = (value, { records, windows }, actions, schema) => {
8142
8434
  const facts = factsOf(value);
@@ -8323,10 +8615,49 @@ const takenWithoutVerdict = (value, actions, takenWhole, ownership) => {
8323
8615
  return remover ? !marksOf(remover, facts).some((mark) => mark.change === change && removes(mark)) : taken;
8324
8616
  });
8325
8617
  };
8618
+ const contentRangeOf = (index, path) => {
8619
+ const { from, to } = index.nodeRange(path);
8620
+ const letters = index.nodeRangesTouching(from, to).filter((entry) => entry.kind === "text" && entry.contentTo > entry.contentFrom && path.every((step, depth) => entry.path[depth] === step));
8621
+ return letters.length === 0 ? [from, to] : [getDefined(letters[0]).contentFrom, getDefined(letters.at(-1)).contentTo];
8622
+ };
8623
+ /**
8624
+ * The pending deletions of authors other than `writer` that the stored range
8625
+ * `from` to `to` of `root` covers whole, or `null` when it touches one only in
8626
+ * part. The cover counts content positions, so a range holding a struck
8627
+ * line's letters covers it wherever the line's own tokens sit. A deletion's
8628
+ * line break is covered when the range crosses it, and its insertions when
8629
+ * the range holds their letters. A node a write over it `keeps`, such as a
8630
+ * table row, is never covered.
8631
+ */
8632
+ const coveredDeletionsOf = (book, index, { from, keeps, root, to, writer }) => {
8633
+ const touched = /* @__PURE__ */ new Set();
8634
+ for (const entry of index.nodeRangesTouching(from, to)) for (const mark of readAuthoredMarks(index.node(entry.path))) {
8635
+ if (mark.kind !== "delete" || mark.author === writer || touched.has(mark.change) || !book.change(mark.change)) continue;
8636
+ const [low, high] = contentRangeOf(index, entry.path);
8637
+ if (low < to && from < high) touched.add(mark.change);
8638
+ }
8639
+ const covers = ({ mark, node, path, root: at }) => {
8640
+ if (at !== root || keeps(node)) return false;
8641
+ if (mark.kind === "join") {
8642
+ const start = index.nodeRange(path).from;
8643
+ return from < start && start < to;
8644
+ }
8645
+ if (mark.kind !== "delete" && mark.kind !== "insert") return false;
8646
+ const [low, high] = contentRangeOf(index, path);
8647
+ return from <= low && high <= to;
8648
+ };
8649
+ for (const id of touched) if (!book.occurrences(id).every(covers)) return null;
8650
+ return [...touched];
8651
+ };
8326
8652
  const decide = (value, { actions, token, withdraws }, { book, resolveSchema, spares }) => {
8327
8653
  const ids = [...actions.keys()];
8328
8654
  const outcome = (change) => actions.get(change) ?? "keep";
8655
+ const deciding = {
8656
+ authors: new Set(ids.flatMap((id) => book.occurrences(id).map(({ mark }) => mark.author))),
8657
+ changes: new Set(ids.flatMap((id) => [id, ...book.members(id).map((entry) => entry.id)]))
8658
+ };
8329
8659
  const resolveOptions = {
8660
+ deciding,
8330
8661
  stores: true,
8331
8662
  withdraws
8332
8663
  };
@@ -8334,9 +8665,12 @@ const decide = (value, { actions, token, withdraws }, { book, resolveSchema, spa
8334
8665
  let windowed = null;
8335
8666
  let whole = null;
8336
8667
  try {
8668
+ for (const { from, to } of windows ?? []) countCoreWork("decisionBlocks", to - from);
8337
8669
  windowed = windows && resolveAuthoredWindows(value, windows, outcome, resolveSchema, resolveOptions);
8338
8670
  if (!windowed) {
8339
- coverStoredValues(resolveSchema.ownership, [...value.children, ...Object.values(value.roots ?? {}).flat()]);
8671
+ const blocks = [...value.children, ...Object.values(value.roots ?? {}).flat()];
8672
+ countCoreWork("decisionBlocks", blocks.length);
8673
+ coverStoredValues(resolveSchema.ownership, blocks);
8340
8674
  whole = resolveAuthoredValue(value, outcome, resolveSchema, resolveOptions);
8341
8675
  }
8342
8676
  } catch (error) {
@@ -8384,13 +8718,14 @@ const decide = (value, { actions, token, withdraws }, { book, resolveSchema, spa
8384
8718
  };
8385
8719
  const inDroppedRoots = windowed ? /* @__PURE__ */ new Set() : insertionsInDroppedRoots(value, decidedValue, rootsTaken);
8386
8720
  const losesText = ({ mark, node, path, root }) => mark.kind === "insert" && typeof node.text === "string" && node.text !== "" && !insideTaken(value, root, path, resolution.takenWhole) && (root === "main" || !rootsTaken().has(root));
8387
- const undecidedLosingText = book.pendingInOrder(/* @__PURE__ */ new Set([...candidates, ...inDroppedRoots])).filter((id) => !actions.has(id) && (inDroppedRoots.has(id) || !remains(id) && book.occurrences(id).some(losesText)));
8388
- if (undecidedLosingText.length > 0) return {
8721
+ const decidersLosingText = book.pendingInOrder(/* @__PURE__ */ new Set([...candidates, ...inDroppedRoots])).filter((id) => !actions.has(id) && book.occurrences(id).some(({ mark }) => deciding.authors.has(mark.author)) && (inDroppedRoots.has(id) || !remains(id) && book.occurrences(id).some(losesText)));
8722
+ if (decidersLosingText.length > 0) return {
8389
8723
  status: "blocked",
8390
- with: undecidedLosingText
8724
+ with: decidersLosingText
8391
8725
  };
8392
8726
  const records = recordOpsBetween(getValueRecords(value), getValueRecords(decidedValue));
8393
8727
  return {
8728
+ built: builtSpansOf(value, decided, windowed, whole),
8394
8729
  change: withDocumentChangeRecords(decided ? decided.change : decidedContentChange(value, decidedValue, {
8395
8730
  facts: factsOf(value),
8396
8731
  outcomes: actions,
@@ -10749,6 +11084,27 @@ var Level = class Level {
10749
11084
  };
10750
11085
  this.shownNode = null;
10751
11086
  }
11087
+ collectPassthroughNodes(out) {
11088
+ this.slots.forEach(0, this.slots.size, (slot) => {
11089
+ if (slot.run === null) out.add(slot.node);
11090
+ else if (isLevelRun(slot.run)) if (!slot.run.changed) out.add(slot.node);
11091
+ else slot.run.level.collectPassthroughNodes(out);
11092
+ });
11093
+ }
11094
+ bindLevels() {
11095
+ let at = 0;
11096
+ this.slots.forEach(0, this.slots.size, (slot) => {
11097
+ if (isLevelRun(slot.run)) {
11098
+ slot.run.level.showAt(this.projected, at);
11099
+ const children = this.projected.childrenAt(at);
11100
+ if (children) {
11101
+ slot.run.level.projected = children;
11102
+ slot.run.level.bindLevels();
11103
+ }
11104
+ }
11105
+ at += getDefined(slot.measures[OUTPUT_BLOCKS]);
11106
+ });
11107
+ }
10752
11108
  pend(ranges, stored, context) {
10753
11109
  let composed = null;
10754
11110
  for (let next = ranges.length - 1; next >= 0;) {
@@ -11518,6 +11874,77 @@ const assertShowsWritten = (whole, shown, windows) => {
11518
11874
  else compare(range);
11519
11875
  }
11520
11876
  };
11877
+ const keepUnchanged = (from, after, change, passthroughs) => {
11878
+ if (change.empty && passthroughs.size === 0) return from;
11879
+ const ranges = [];
11880
+ change.iterChangedRanges((fromA, toA, fromB, toB) => {
11881
+ ranges.push({
11882
+ fromA,
11883
+ fromB,
11884
+ toA,
11885
+ toB
11886
+ });
11887
+ });
11888
+ if (ranges.length === 0 && passthroughs.size === 0) return from;
11889
+ const firstRangeAt = (nodeFrom) => {
11890
+ let low = 0;
11891
+ let high = ranges.length;
11892
+ while (low < high) {
11893
+ const mid = low + high >> 1;
11894
+ if (getDefined(ranges[mid]).toB <= nodeFrom) low = mid + 1;
11895
+ else high = mid;
11896
+ }
11897
+ return low;
11898
+ };
11899
+ const reconcile = (node, path, nodeFrom, nodeTo) => {
11900
+ if (passthroughs.has(node)) return node;
11901
+ const start = firstRangeAt(nodeFrom);
11902
+ let touched = false;
11903
+ for (let index = start; index < ranges.length; index += 1) {
11904
+ const range = getDefined(ranges[index]);
11905
+ if (range.fromB > nodeTo) break;
11906
+ if (range.fromB === range.toB) {
11907
+ if (range.fromB <= nodeFrom || range.fromB >= nodeTo) continue;
11908
+ touched = true;
11909
+ break;
11910
+ }
11911
+ if (range.fromB >= nodeTo) break;
11912
+ if (range.fromB <= nodeFrom && nodeTo <= range.toB) return node;
11913
+ touched = true;
11914
+ }
11915
+ if (!touched) {
11916
+ const previous = start > 0 ? getDefined(ranges[start - 1]) : null;
11917
+ const shift = previous ? previous.toA - previous.toB : 0;
11918
+ const beforeFrom = nodeFrom + shift;
11919
+ const entry = from.nodeStartingAt(beforeFrom);
11920
+ if (entry && entry.from === beforeFrom && entry.to === nodeTo + shift) return from.node(entry.path);
11921
+ return node;
11922
+ }
11923
+ if (typeof node.text === "string" || !node.children?.length) return node;
11924
+ let changedChild = false;
11925
+ const children = node.children.map((child, childIndex) => {
11926
+ const childPath = [...path, childIndex];
11927
+ const range = after.nodeRange(childPath);
11928
+ const kept = reconcile(child, childPath, range.from, range.to);
11929
+ if (kept !== child) changedChild = true;
11930
+ return kept;
11931
+ });
11932
+ return changedChild ? Object.freeze({
11933
+ ...node,
11934
+ children: Object.freeze(children)
11935
+ }) : node;
11936
+ };
11937
+ let changedRoot = false;
11938
+ const nodes = [];
11939
+ for (let index = 0; index < after.size; index += 1) {
11940
+ const node = getDefined(after.child(index));
11941
+ const range = after.nodeRange([index]);
11942
+ const kept = reconcile(node, [index], range.from, range.to);
11943
+ if (kept !== node) changedRoot = true;
11944
+ nodes.push(kept);
11945
+ }
11946
+ return changedRoot ? DocumentIndex.fromIndexedNodes(nodes) : after;
11947
+ };
11521
11948
  const sharesNothing = (ranges, before, after) => {
11522
11949
  const [whole] = ranges;
11523
11950
  return ranges.length === 1 && whole?.[0] === 0 && whole[1] === before.size && before.size > 1 && after.size > 1;
@@ -11571,10 +11998,20 @@ var RootProjection = class extends Level {
11571
11998
  this.schema = context.schema;
11572
11999
  this.cache = /* @__PURE__ */ new WeakMap();
11573
12000
  this.build(stored, context);
11574
- change = RootChange.betweenChangedBlocks(from, this.projected);
12001
+ change = this.diffFrom(from, context);
11575
12002
  }
11576
12003
  return this.publish(from, change);
11577
12004
  }
12005
+ diffFrom(from, context) {
12006
+ const change = RootChange.betweenChangedBlocks(from, this.projected, { isSetValued: context.isSetValued });
12007
+ if (this.changed) {
12008
+ const passthroughs = /* @__PURE__ */ new Set();
12009
+ this.collectPassthroughNodes(passthroughs);
12010
+ this.projected = keepUnchanged(from, this.projected, change, passthroughs);
12011
+ this.bindLevels();
12012
+ }
12013
+ return change;
12014
+ }
11578
12015
  publish(from, change) {
11579
12016
  if (!this.changed) {
11580
12017
  this.projected = this.stored;
@@ -11602,7 +12039,7 @@ var RootProjection = class extends Level {
11602
12039
  inner: null
11603
12040
  }]);
11604
12041
  }
11605
- return RootChange.betweenChangedBlocks(from, this.projected);
12042
+ return this.diffFrom(from, context);
11606
12043
  }
11607
12044
  const pended = this.pend(ranges, stored, context);
11608
12045
  this.stored = stored;
@@ -12779,7 +13216,12 @@ const chainOf = (site) => {
12779
13216
  return chain;
12780
13217
  };
12781
13218
  const pendingOn = (node, facts, test) => claimsOf(node, facts).some((mark) => outcomeOf(facts, mark) === "pending" && test(mark));
12782
- const buildWaits = (chain, left, facts) => chain.some((node, at) => pendingOn(node, facts, (mark) => mark.kind === "insert" || isStructureChange(mark) || at === 0 && (isPlaceChange(mark) || mark.kind === "delete"))) || left.some((node) => pendingOn(node, facts, isStructureChange));
13219
+ const acceptsIn = (nodes, facts) => nodes.some((node) => readAuthoredMarks(node).some((mark) => outcomeOf(facts, mark) === "accept") || acceptsIn(node.children ?? [], facts));
13220
+ const buildWaits = (chain, left, removed, facts) => {
13221
+ const accepts = acceptsIn(removed, facts);
13222
+ const own = (mark) => !accepts || isEditingChange(mark.change);
13223
+ return chain.some((node, at) => pendingOn(node, facts, (mark) => own(mark) && (mark.kind === "insert" || isStructureChange(mark) || at === 0 && (isPlaceChange(mark) || mark.kind === "delete")))) || left.some((node) => pendingOn(node, facts, (mark) => own(mark) && isStructureChange(mark)));
13224
+ };
12783
13225
  const donationRetracts = (read, built, site, pass) => {
12784
13226
  if (isText$1(read) || isText$1(built)) return false;
12785
13227
  const index = DocumentIndex.fromValue([read]);
@@ -12832,8 +13274,13 @@ const replacementsOf = (size, removed, childAt, readAt, site, pass) => {
12832
13274
  };
12833
13275
  const completion = completeHere(left);
12834
13276
  const slots = content?.prefix ?? 0;
12835
- if (completion.built.length > 0 && buildWaits(chain, left, pass.facts) || slots > 0 && slotDecidingInsertions(left, completion, completeHere, slots, (node) => start.includes(origin(node)), inserted).some((node) => pendingOn(origin(node), pass.facts, (mark) => mark.kind === "insert"))) return null;
12836
- const children = completion.children;
13277
+ if (completion.built.length > 0 && buildWaits(chain, left, removed.map((at) => readAt(at)), pass.facts) || slots > 0 && slotDecidingInsertions(left, completion, completeHere, slots, (node) => start.includes(origin(node)), inserted).some((node) => pendingOn(origin(node), pass.facts, (mark) => mark.kind === "insert"))) return null;
13278
+ const enclosing = chain.flatMap((node, index) => {
13279
+ const pending = standingClaimsOf(node, pass.facts, pass.facts).filter((mark) => outcomeOf(pass.facts, mark) === "pending");
13280
+ return [...pending.filter((mark) => mark.kind === "insert" || mark.kind === "delete"), ...index === 0 ? dissolveClaimsOf(pending) : []];
13281
+ });
13282
+ const builtNodes = new Set(completion.built.map(({ node }) => node));
13283
+ const children = completion.children.map((node) => enclosing.length > 0 && builtNodes.has(node) ? pass.dependencies.throughout(node, enclosing) : node);
12837
13284
  const into = new Map(removed.map((at) => [at, []]));
12838
13285
  let gap = [];
12839
13286
  let filled = 0;
@@ -12865,12 +13312,12 @@ const replacementsOf = (size, removed, childAt, readAt, site, pass) => {
12865
13312
  const withSettledSpares = (stored, container, taken, pass, root) => {
12866
13313
  const members = readMembers(container);
12867
13314
  if (!members.some((member) => member.kind === "reserve")) return container;
12868
- if (!pass.stillBuilds(stored, stored.children ?? [], root)) return withMembers(container, members.filter((member) => member.kind !== "reserve"));
13315
+ if (!pass.stillBuilds(stored, stored.children ?? [], root, sparesIn(stored).map(({ slot }) => slot))) return withMembers(container, members.filter((member) => member.kind !== "reserve"));
12869
13316
  return taken.size > 0 ? withMembers(container, withBuiltSpares(members, taken)) : container;
12870
13317
  };
12871
13318
  const settleRootSpares = (pass, root, stored, taken) => {
12872
13319
  const records = pass.facts.reserves(root);
12873
- if (records.length > 0) putRootSpares(records, pass.stillBuilds(null, stored(), root), taken, pass.reserveWrites);
13320
+ if (records.length > 0) putRootSpares(records, pass.stillBuilds(null, stored(), root, records.map(({ slot }) => slot)), taken, pass.reserveWrites);
12874
13321
  };
12875
13322
  const leaveLevel = (level, stored, site, pass) => {
12876
13323
  const { nodes, readIndex } = level;
@@ -13056,7 +13503,10 @@ const settleValue = (value, facts, scope, { returnsHeld = scope === "document",
13056
13503
  resolveSchema: () => resolve ??= resolveSchema(),
13057
13504
  returnsHeld,
13058
13505
  schema,
13059
- stillBuilds: (container, children, root) => buildClaims(container, children, root).length > 0
13506
+ stillBuilds: (container, children, root, slots) => buildClaims(container, children, root, {
13507
+ slots,
13508
+ kept: (child) => !pass.gone.has(child)
13509
+ }).length > 0
13060
13510
  };
13061
13511
  if (!facts.hasVerdicts && !restoreMissingFormats) return {
13062
13512
  change: null,
@@ -13316,6 +13766,11 @@ const settleDecidedApart = (value, facts, decided, settled, options) => {
13316
13766
  value: decidedValue
13317
13767
  };
13318
13768
  };
13769
+ const settleAuthoredValue = (value, schema, commit) => {
13770
+ if (!storesSpares(schema) || commit && quietCommit(value, commit)) return null;
13771
+ const ledger = commit && getReviewLedger(getEditorRuntimeOwner(commit.editor));
13772
+ return settleShownValues(value, schema, ledger ? commit : null, ledger ? ledger.shown : null);
13773
+ };
13319
13774
  const authoredAdmission = {
13320
13775
  commit: ({ after, before, change, editor, indexOf, loads }) => {
13321
13776
  const records = getInternalDocumentChangeRecords(change);
@@ -13329,8 +13784,8 @@ const authoredAdmission = {
13329
13784
  const scope = /* @__PURE__ */ new Map();
13330
13785
  const facts = factsOf(after);
13331
13786
  for (const root of /* @__PURE__ */ new Set([...previous.roots.keys(), ...roots.keys()])) {
13332
- const next = roots.get(root) ?? NO_NODES;
13333
- if ((previous.roots.get(root) ?? NO_NODES) === next) continue;
13787
+ const next = roots.get(root) ?? NO_NODES$1;
13788
+ if ((previous.roots.get(root) ?? NO_NODES$1) === next) continue;
13334
13789
  const ranges = changedChildrenOf(change, root, before, indexOf(root));
13335
13790
  if (next.length > 0 && ranges.length > 0) scope.set(root, childrenAround(ranges, next.length));
13336
13791
  }
@@ -13417,11 +13872,8 @@ const authoredAdmission = {
13417
13872
  value: spared
13418
13873
  };
13419
13874
  },
13420
- settle: (value, schema, commit) => {
13421
- if (!storesSpares(schema) || commit && quietCommit(value, commit)) return null;
13422
- const ledger = commit && getReviewLedger(getEditorRuntimeOwner(commit.editor));
13423
- return settleShownValues(value, schema, ledger ? commit : null, ledger ? ledger.shown : null);
13424
- }
13875
+ settle: settleAuthoredValue,
13876
+ spareLines: spareLinesOf
13425
13877
  };
13426
13878
  const NO_DECIDED = [];
13427
13879
  const settleShownValues = (value, schema, commit, book) => {
@@ -13731,6 +14183,13 @@ const reviewed = (token) => token.kind === "open" && readMembers(token.props).le
13731
14183
  * outside that order.
13732
14184
  */
13733
14185
  const innermostInsert = (marks) => marks.findLast((mark) => mark.kind === "insert");
14186
+ const contentClaim = (insertion) => ({
14187
+ at: insertion.at,
14188
+ author: insertion.author,
14189
+ change: insertion.change,
14190
+ ...insertion.inc === void 0 ? {} : { inc: insertion.inc },
14191
+ kind: "insert"
14192
+ });
13734
14193
  const othersDelete = (member) => member.kind === "delete" && !isEditingChange(member.change);
13735
14194
  const struckWhole = (node) => {
13736
14195
  const members = readMembers(node);
@@ -13899,7 +14358,10 @@ const rebaseProperties = (step, map, plain, review) => {
13899
14358
  const reviewTokens = (token) => {
13900
14359
  const entry = plain === review ? null : plain.nodeStartingAt(token);
13901
14360
  const text = entry && plain.node(entry.path).text;
13902
- if (!entry || typeof text !== "string" || text === "") return [map(token, 1, false)];
14361
+ if (!entry || typeof text !== "string" || text === "") {
14362
+ const at = map(token, 1, false);
14363
+ return plain === review || review.nodeStartingAt(at)?.from === at ? [at] : [];
14364
+ }
13903
14365
  return reviewOpensOf(map, review, token, text.length);
13904
14366
  };
13905
14367
  let before = 0;
@@ -14420,19 +14882,24 @@ const lowerAcrossBreaks = (step, breaks, frame, isInline) => {
14420
14882
  /**
14421
14883
  * Where a composition commit's claimed write lands in the review draft: at
14422
14884
  * the commit's stored place, in the props of the leaf the command wrote, when
14423
- * the command wrote into the element that holds that place. Hidden struck
14885
+ * the command wrote into the element that shows that place. Hidden struck
14424
14886
  * text gives the frame's write position several stored places, and only the
14425
14887
  * stored one keeps the word where the person saw it.
14426
14888
  */
14427
14889
  const compositionLanding = (input, fold, root, change, written) => {
14428
14890
  const { composition, projection } = input;
14429
14891
  if (composition?.root !== root || !projection || !written) return null;
14430
- const element = projection.map.nodePath(root, composition.element);
14431
14892
  const stretch = changedStretch([change]);
14432
- if (!element || !stretch) return null;
14433
- const at = fold.frameChange ? getDefined(mapRootChangePositionBackward(fold.frameChange, stretch.from, -1)) : stretch.from;
14434
- const holder = getDefined(projection.indexes.get(root)).openContextAt(at).findLast((entry) => entry.kind === "element" && entry.contentFrom <= at && at <= entry.contentTo);
14435
- if (!holder || !jsonEqual(holder.path, element)) return null;
14893
+ if (!stretch) return null;
14894
+ const holderAt = (position) => position === null ? void 0 : getDefined(projection.indexes.get(root)).openContextAt(position).findLast((entry) => entry.kind === "element" && entry.contentFrom <= position && position <= entry.contentTo)?.path;
14895
+ const joinedInto = () => {
14896
+ const { to } = valueRootIndex(input.before, root).nodeRange(composition.element);
14897
+ const end = projection.map.toProjected(root, to - 1, "forward");
14898
+ return end === projection.map.toProjected(root, to, "forward") ? void 0 : holderAt(end);
14899
+ };
14900
+ const element = projection.map.nodePath(root, composition.element) ?? joinedInto();
14901
+ const holder = holderAt(fold.frameChange ? getDefined(mapRootChangePositionBackward(fold.frameChange, stretch.from, -1)) : stretch.from);
14902
+ if (!element || !holder || !jsonEqual(holder, element)) return null;
14436
14903
  const point = written.pointAt(getDefined(change.mapPos(stretch.from, -1)), 1);
14437
14904
  const { [AUTHORED_MARKS_KEY]: _marks, ...leaf } = point ? propsOf$1(written.node(point.path)) : {};
14438
14905
  return {
@@ -14445,15 +14912,10 @@ const applyReusingStep = (step, root, index, change) => {
14445
14912
  const written = getInternalDocumentRootChange(step.change, root);
14446
14913
  return index === step.indexedBefore.get(root) && written && change.sameAs(written) ? getDefined(step.indexedAfter.get(root)) : change.apply(index);
14447
14914
  };
14448
- /**
14449
- * Record a transaction's steps as the review tree's change. Each step folds
14450
- * through a review draft: it is rebased from the plain draft into the review
14451
- * draft, recorded there and applied, so each step reads the review state the
14452
- * earlier ones left. Recording keys only on token kind, existing marks, the
14453
- * step's origin and move link, intent and writer, so it imports no plugin or
14454
- * command module.
14455
- */
14456
- const recordSteps = (input, reading) => {
14915
+ var MixedMovesError = class extends Error {
14916
+ name = "MixedMovesError";
14917
+ };
14918
+ const recordSteps = (input, reading, allowStoredMoves) => {
14457
14919
  const facts = factsOf(input.before);
14458
14920
  const changeId = input.forcedChangeId ?? input.changeId;
14459
14921
  const inc = input.inc ?? void 0;
@@ -14473,13 +14935,10 @@ const recordSteps = (input, reading) => {
14473
14935
  change: changeId,
14474
14936
  ...inc === void 0 ? {} : { inc }
14475
14937
  };
14476
- const markOf = (kind) => kind === "split" ? {
14477
- ...base,
14478
- kind
14479
- } : {
14938
+ const markOf = (kind) => ({
14480
14939
  ...base,
14481
14940
  kind
14482
- };
14941
+ });
14483
14942
  const folds = /* @__PURE__ */ new Map();
14484
14943
  let writtenPlain = true;
14485
14944
  const ownedRootsOf = (props) => input.ownedRoots?.(props) ?? [];
@@ -14499,6 +14958,10 @@ const recordSteps = (input, reading) => {
14499
14958
  const holds = (nodes) => nodes.some((node) => !ownInsertion(node) || node.children !== void 0 && (holdsWithdrawal(propsOf$1(node)) || holds(node.children)));
14500
14959
  return index !== null && holds(index.value);
14501
14960
  });
14961
+ const canStoreMoves = allowStoredMoves && isEditingChange(changeId) && input.createRoots.size === 0 && input.deleteRoots.size === 0 && input.followed.size === 0 && input.steps.every((step) => step.origin === "move" && step.facts.kind === "recorded");
14962
+ let storesMoves = canStoreMoves;
14963
+ let storedAnyMove = false;
14964
+ let factsLost = !canStoreMoves;
14502
14965
  const foldOf = (root) => {
14503
14966
  let fold = folds.get(root);
14504
14967
  if (!fold) {
@@ -14506,6 +14969,7 @@ const recordSteps = (input, reading) => {
14506
14969
  fold = {
14507
14970
  breaks: [],
14508
14971
  composed: null,
14972
+ facts: NO_ROOT_FACTS,
14509
14973
  frameChange: null,
14510
14974
  frameIndex: null,
14511
14975
  index: created ? DocumentIndex.fromValue([]) : valueRootIndex(input.before, root),
@@ -14537,8 +15001,13 @@ const recordSteps = (input, reading) => {
14537
15001
  }
14538
15002
  });
14539
15003
  const composeFrame = (fold, change) => fold.frameChange ? fold.frameChange.compose(change) : change;
14540
- const foldIn = (fold, change, reusing) => {
15004
+ const foldIn = (fold, change, reusing, moveFacts) => {
14541
15005
  if (!change) return;
15006
+ if (!factsLost) {
15007
+ const nextFacts = moveFacts ?? NO_ROOT_FACTS;
15008
+ if (!fold.composed) fold.facts = nextFacts;
15009
+ else if (nextFacts !== NO_ROOT_FACTS || !changesOnlyProperties(change)) fold.facts = composeRoot(fold.composed, fold.facts, change, nextFacts);
15010
+ }
14542
15011
  fold.index = reusing ? applyReusingStep(reusing.step, reusing.root, fold.index, change) : change.apply(fold.index);
14543
15012
  fold.composed = fold.composed ? fold.composed.compose(change) : change;
14544
15013
  };
@@ -14599,11 +15068,15 @@ const recordSteps = (input, reading) => {
14599
15068
  }
14600
15069
  let removesStruckParts = false;
14601
15070
  let writesOther = false;
15071
+ let recordedStrike = !isEditingChange(changeId) && input.createRoots.size === 0 && input.deleteRoots.size === 0 && input.followed.size === 0 && input.selectionBefore !== null ? null : "invalid";
14602
15072
  for (const { changes, step } of stepChanges) for (const [root, rootChange, retypedStarts, recordsAlone] of changes) {
14603
15073
  const fold = foldOf(root);
14604
15074
  if (step.origin === "canonical") {
14605
15075
  const previous = fold.map;
14606
- if (carried && step.drops) foldIn(fold, carried.drops(root, fold.index, getDefined(step.indexedBefore.get(root)), step.drops, (position, assoc) => previous(position, assoc, false)));
15076
+ if (carried && step.drops) {
15077
+ recordedStrike = "invalid";
15078
+ foldIn(fold, carried.drops(root, fold.index, getDefined(step.indexedBefore.get(root)), step.drops, (position, assoc) => previous(position, assoc, false)));
15079
+ }
14607
15080
  const back = (position, assoc, caret) => previous(getDefined(mapRootChangePositionBackward(rootChange, position, assoc)), assoc, caret);
14608
15081
  const frame = fold.frameIndex && rootChange.apply(fold.frameIndex);
14609
15082
  const leaves = frame ? emptyLeavesOf(rootChange, frame, fold.index, back) : [];
@@ -14618,6 +15091,7 @@ const recordSteps = (input, reading) => {
14618
15091
  fold.map = back;
14619
15092
  continue;
14620
15093
  }
15094
+ recordedStrike = "invalid";
14621
15095
  foldIn(fold, recorded);
14622
15096
  fold.map = (position, assoc, caret) => {
14623
15097
  const leaf = leaves.find(({ from, to }) => from <= position && position <= to);
@@ -14663,8 +15137,11 @@ const recordSteps = (input, reading) => {
14663
15137
  let recorded;
14664
15138
  let mapRecorded = identity;
14665
15139
  let copies = [];
14666
- if (fold.created || step.origin === "migration") recorded = groupsChange(groups);
14667
- else {
15140
+ let moveFacts = null;
15141
+ if (fold.created || step.origin === "migration") {
15142
+ recorded = groupsChange(groups);
15143
+ recordedStrike = "invalid";
15144
+ } else {
14668
15145
  const result = new RootRecorder(fold.index, {
14669
15146
  joinAside: (mark) => isJoinAside(facts, mark),
14670
15147
  dependencies: input.dependencies,
@@ -14695,14 +15172,36 @@ const recordSteps = (input, reading) => {
14695
15172
  commitWriteId: input.commitWriteId,
14696
15173
  selectionBefore: !fold.touched && input.selectionBefore?.root === root ? input.selectionBefore.position : null,
14697
15174
  source: step.source,
15175
+ storesMoves,
14698
15176
  holdsUnique: input.holdsUnique,
14699
15177
  unique: input.unique
14700
15178
  }).record(groups);
14701
15179
  recorded = result.change;
14702
15180
  mapRecorded = result.mapPosition;
14703
15181
  ({copies} = result);
15182
+ moveFacts = result.facts;
14704
15183
  fold.leftward = result.leftward;
14705
15184
  writtenPlain &&= result.writtenPlain;
15185
+ if (recordedStrike === null && result.textStrike && retypedStarts.size === 0 && subSteps.length === 1 && copies.length === 0 && input.selectionBefore?.root === root) {
15186
+ const strike = result.textStrike;
15187
+ const plainBefore = fold.frameIndex ?? getDefined(step.indexedBefore.get(root));
15188
+ const plainCaret = input.projection ? input.projection.map.toProjected(root, input.selectionBefore.position, "backward") : input.selectionBefore.position;
15189
+ const onlyTextEdges = (from, to) => from === to || plainBefore.slice(from, to).tokens.every((token) => token.kind !== "text" && token.nodeKind === "text");
15190
+ const direction = plainCaret === null ? null : plainCaret >= strike.plainTo && onlyTextEdges(strike.plainTo, plainCaret) ? "backward" : plainCaret <= strike.plainFrom && onlyTextEdges(plainCaret, strike.plainFrom) ? "forward" : null;
15191
+ recordedStrike = direction ? {
15192
+ author: strike.author,
15193
+ blockPath: strike.blockPath,
15194
+ change: strike.change,
15195
+ direction,
15196
+ root
15197
+ } : "invalid";
15198
+ } else recordedStrike = "invalid";
15199
+ }
15200
+ if (storesMoves) if (moveFacts !== null) storedAnyMove = true;
15201
+ else if (storedAnyMove) throw new MixedMovesError("a move recorded as a copy follows a stored move");
15202
+ else {
15203
+ storesMoves = false;
15204
+ factsLost = true;
14706
15205
  }
14707
15206
  fold.touched = true;
14708
15207
  if (frameAfter) {
@@ -14713,7 +15212,7 @@ const recordSteps = (input, reading) => {
14713
15212
  foldIn(fold, recorded.empty ? null : recorded, {
14714
15213
  root,
14715
15214
  step
14716
- });
15215
+ }, moveFacts);
14717
15216
  if (carried && copies.length > 0) foldIn(fold, carried.copied(root, fold.index, composedBefore, copies));
14718
15217
  fold.breaks = advanceBreaks(fold.breaks, sub.change, recorded);
14719
15218
  fold.map = (position, assoc, caret) => mapRecorded(afterMap(position, assoc, caret), assoc, caret);
@@ -14725,7 +15224,11 @@ const recordSteps = (input, reading) => {
14725
15224
  }
14726
15225
  if (removesStruckParts && !writesOther) throw unrepresentableFor("grid");
14727
15226
  if (carried) {
14728
- for (const [root, fold] of folds) if (!fold.created && fold.composed && !fold.composed.empty) foldIn(fold, carried.settle(root, fold.index, fold.composed));
15227
+ for (const [root, fold] of folds) if (!fold.created && fold.composed && !fold.composed.empty) {
15228
+ const settled = carried.settle(root, fold.index, fold.composed);
15229
+ if (settled && !settled.empty) recordedStrike = "invalid";
15230
+ foldIn(fold, settled);
15231
+ }
14729
15232
  }
14730
15233
  for (const [root, roots] of doubled) {
14731
15234
  const owners = /* @__PURE__ */ new Map();
@@ -14757,28 +15260,43 @@ const recordSteps = (input, reading) => {
14757
15260
  }
14758
15261
  const changes = /* @__PURE__ */ new Map();
14759
15262
  const indexedAfter = /* @__PURE__ */ new Map();
15263
+ const told = [];
14760
15264
  for (const [root, fold] of folds) {
14761
- if (fold.composed && !fold.composed.empty) changes.set(root, fold.composed);
15265
+ if (fold.composed && !fold.composed.empty) {
15266
+ changes.set(root, fold.composed);
15267
+ if (!factsLost && fold.facts.carries.length > 0) told.push([root, fold.facts]);
15268
+ }
14762
15269
  if (!input.deleteRoots.has(root)) indexedAfter.set(root, fold.index);
14763
15270
  }
15271
+ if (doubled.size > 0 || loweredRoots.size > 0) recordedStrike = "invalid";
14764
15272
  return {
14765
15273
  anchorChange: (plainAfter) => createInternalDocumentChange(new Map([...folds].filter(([root]) => !input.deleteRoots.has(root) && !input.followed.has(root)).map(([root, fold]) => [root, correspondence(plainAfter(root), fold.index, fold.map)]))),
14766
15274
  change: createInternalDocumentChange(changes, {
14767
15275
  createRoots: input.createRoots,
14768
15276
  deleteRoots: input.deleteRoots
14769
15277
  }),
15278
+ ...told.length > 0 ? { facts: recorded(told) } : {},
14770
15279
  indexedAfter,
14771
15280
  mapPosition: (root, position, assoc, caret = true) => folds.get(root)?.map(position, assoc, caret) ?? position,
15281
+ textStrike: recordedStrike === "invalid" ? null : recordedStrike,
14772
15282
  writtenPlain
14773
15283
  };
14774
15284
  };
15285
+ const recordWithFallback = (input, reading) => {
15286
+ try {
15287
+ return recordSteps(input, reading, true);
15288
+ } catch (error) {
15289
+ if (!(error instanceof MixedMovesError)) throw error;
15290
+ return recordSteps(input, reading, false);
15291
+ }
15292
+ };
14775
15293
  const recordAuthoredSteps = (input) => {
14776
15294
  try {
14777
- return recordSteps(input, "written");
15295
+ return recordWithFallback(input, "written");
14778
15296
  } catch (error) {
14779
15297
  if (!(error instanceof EditorRefusalError)) throw error;
14780
15298
  if (!input.steps.some((step) => step.fit?.lookAlike)) throw error;
14781
- return recordSteps(input, "lookAlike");
15299
+ return recordWithFallback(input, "lookAlike");
14782
15300
  }
14783
15301
  };
14784
15302
  const restoredBy = (tag) => [tag.before, ...[tag.base, ...(tag.over ?? []).flat().map(({ write }) => write)].flatMap((write) => write?.kind === "set" ? [write.value] : [])];
@@ -14837,6 +15355,39 @@ const replaceRetyped = (change, before, replaces, ownedRoots, doubled, lowered)
14837
15355
  }
14838
15356
  return after === null || replaced.length === 0 ? change : change.compose(RootChange.create(after, replaced));
14839
15357
  };
15358
+ const holdsLiveText = (index, marks, line, removed) => {
15359
+ const gone = (from, to) => removed.some((span) => span.from <= from && to <= span.to);
15360
+ const { offsets, tokens } = index.slice(line.contentFrom, line.contentTo);
15361
+ let liveLeaf = false;
15362
+ return tokens.some((token, at) => {
15363
+ const position = line.contentFrom + offsets[at];
15364
+ if (token.kind === "text") return liveLeaf && !gone(position, position + token.text.length);
15365
+ if (token.kind !== "open") return false;
15366
+ const live = !marks(token.props).some((mark) => mark.kind === "delete");
15367
+ if (token.nodeKind === "text") {
15368
+ liveLeaf = live;
15369
+ return false;
15370
+ }
15371
+ return live && !gone(position, position + 1);
15372
+ });
15373
+ };
15374
+ const emptiesStruckLine = (index, marks, line, from, to) => to <= line.contentTo && marks(line.props).some((mark) => mark.kind === "delete") && isTextBlock(index.node(line.path)) && holdsLiveText(index, marks, line, [{
15375
+ from,
15376
+ to: from
15377
+ }]) && !holdsLiveText(index, marks, line, [{
15378
+ from,
15379
+ to
15380
+ }]);
15381
+ const emptiedStruckLine = (index, marks, from, to) => {
15382
+ const entry = index.openContextAt(from).findLast((each) => each.kind === "element" && each.contentFrom <= from && from <= each.contentTo);
15383
+ return entry && emptiesStruckLine(index, marks, {
15384
+ ...entry,
15385
+ props: propsOf$1(index.node(entry.path))
15386
+ }, from, to) ? {
15387
+ from: entry.contentFrom,
15388
+ to: entry.contentTo
15389
+ } : null;
15390
+ };
14840
15391
  var RootRecorder = class {
14841
15392
  copies = [];
14842
15393
  ops = [];
@@ -14845,9 +15396,12 @@ var RootRecorder = class {
14845
15396
  freshened = /* @__PURE__ */ new WeakSet();
14846
15397
  splitHalves = /* @__PURE__ */ new WeakSet();
14847
15398
  joinIndex = null;
14848
- framedStrikes = [];
15399
+ framedRemovals = [];
15400
+ keptLines = [];
14849
15401
  index;
14850
15402
  options;
15403
+ activeTextStrike = null;
15404
+ textStrike = null;
14851
15405
  withdrawsWrap = false;
14852
15406
  constructor(index, options) {
14853
15407
  this.index = index;
@@ -14856,6 +15410,30 @@ var RootRecorder = class {
14856
15410
  marks(props) {
14857
15411
  return this.options.dependencies.marks(props);
14858
15412
  }
15413
+ get isEditing() {
15414
+ return isEditingChange(this.options.changeId);
15415
+ }
15416
+ storesMovedElement(tokens) {
15417
+ const first = tokens[0];
15418
+ return first?.kind === "open" && first.nodeKind === "element" && !this.options.isInline(first.props) && closeIndexOf(tokens, 0) === tokens.length - 1 && !tokens.some((token) => token.kind === "open" && this.marks(token.props).some((mark) => mark.kind === "join" || mark.kind === "joined"));
15419
+ }
15420
+ noteFramedRemoval(from, to, contexts) {
15421
+ if (this.options.framed && from < to) this.framedRemovals.push({
15422
+ contexts,
15423
+ from,
15424
+ to
15425
+ });
15426
+ }
15427
+ storedMove(from, to, at, tokens) {
15428
+ this.copies.push({
15429
+ at,
15430
+ from,
15431
+ offset: 0,
15432
+ stored: true,
15433
+ to
15434
+ });
15435
+ return tokens.map((token) => token.kind === "open" ? openToken(token.nodeKind, withoutSpares(token.props)) : token);
15436
+ }
14859
15437
  isLiveJoin = (mark) => mark.kind === "join" && !this.options.joinAside(mark);
14860
15438
  droppedOnSplit(continued, continuation, marks) {
14861
15439
  const formats = marks.filter((mark) => mark.kind === "format");
@@ -14891,6 +15469,15 @@ var RootRecorder = class {
14891
15469
  const removals = group.kind === "replace" ? this.plainRemovals(group) : null;
14892
15470
  return removals ? [[group, removals]] : [];
14893
15471
  }));
15472
+ if (!isEditingChange(this.options.changeId) && this.options.origin !== "move" && this.options.moveRole === null) {
15473
+ const replaces = groups.filter((group) => group.kind === "replace");
15474
+ const hasProps = groups.some((group) => group.kind === "kept" && group.data !== null);
15475
+ const only = replaces.length === 1 && !hasProps ? replaces[0] : null;
15476
+ if (only && only.slice.length === 0 && only.removed > 0) this.activeTextStrike = {
15477
+ plainFrom: only.plainFrom,
15478
+ plainTo: only.plainFrom + only.plainRemoved
15479
+ };
15480
+ }
14894
15481
  if (this.options.origin !== "move" || !this.recordNodeMove(groups)) for (const group of groups) {
14895
15482
  if (group.kind === "replace") {
14896
15483
  const start = this.ops.length;
@@ -14908,18 +15495,35 @@ var RootRecorder = class {
14908
15495
  kind: "kept"
14909
15496
  });
14910
15497
  }
15498
+ const opsBeforeWrappers = this.ops.length;
14911
15499
  this.strikeEmptiedWrappers();
15500
+ if (this.ops.length > opsBeforeWrappers) this.textStrike = null;
14912
15501
  this.freshCopyKeys();
14913
15502
  const recorded = RootChange.create(this.index, this.sections());
15503
+ const carries = [];
14914
15504
  return {
14915
15505
  change: recorded,
14916
- copies: this.copies.map(({ at, from, offset, to }) => ({
14917
- at: getDefined(recorded.mapPos(at, -1)) + offset,
14918
- from,
14919
- to
14920
- })),
15506
+ copies: this.copies.map(({ at, from, offset, stored, to }) => {
15507
+ const mapped = getDefined(recorded.mapPos(at, -1)) + offset;
15508
+ if (stored) carries.push([
15509
+ mapped,
15510
+ from,
15511
+ to - from
15512
+ ]);
15513
+ return {
15514
+ at: mapped,
15515
+ from,
15516
+ to
15517
+ };
15518
+ }),
15519
+ facts: carries.length > 0 ? sortedRootFacts({
15520
+ carries,
15521
+ heirs: [],
15522
+ merges: []
15523
+ }) : null,
14921
15524
  leftward: this.pieces.findLast((piece) => piece.kind === "removed")?.leftward ?? this.options.leftward,
14922
15525
  mapPosition: (position, assoc, caret) => this.mapPosition(recorded, position, assoc, caret === true, caret === false),
15526
+ textStrike: this.textStrike,
14923
15527
  writtenPlain: groups.every((group) => group.kind === "replace" ? plain.has(group) : !group.data)
14924
15528
  };
14925
15529
  }
@@ -15212,10 +15816,6 @@ var RootRecorder = class {
15212
15816
  const textEnd = this.options.plainToReview(plainFrom - 1, -1);
15213
15817
  return this.index.slice(textEnd, before).tokens.some((token) => token.kind === "text");
15214
15818
  }
15215
- /**
15216
- * A container split in Suggesting records as a new container holding a
15217
- * moved copy of the children after the split point.
15218
- */
15219
15819
  recordContainerSplit(group) {
15220
15820
  const { after, before, slice } = group;
15221
15821
  const [close, open] = slice.tokens;
@@ -15224,6 +15824,25 @@ var RootRecorder = class {
15224
15824
  if (container?.kind !== "element" || open.props.type !== container.props.type) return false;
15225
15825
  const entry = this.index.nodeRange(container.path);
15226
15826
  if (isTextBlock(this.index.node(container.path))) return false;
15827
+ if (this.isEditing && readMembers(container.props).length === 0) {
15828
+ this.ops.push({
15829
+ at: before,
15830
+ kind: "insert",
15831
+ tokens: [close, open]
15832
+ });
15833
+ this.pieces.push({
15834
+ afterFrom: after,
15835
+ afterTo: after + 2,
15836
+ at: before,
15837
+ kind: "inserted",
15838
+ offsets: [
15839
+ 0,
15840
+ 1,
15841
+ 2
15842
+ ]
15843
+ });
15844
+ return true;
15845
+ }
15227
15846
  const children = this.index.slice(before, container.contentTo);
15228
15847
  this.strike(before, container.contentTo, this.contextAt(before), "move");
15229
15848
  this.ops.push({
@@ -15251,11 +15870,6 @@ var RootRecorder = class {
15251
15870
  });
15252
15871
  return true;
15253
15872
  }
15254
- /**
15255
- * A builder move: the source keeps its place under the mover's deletion in
15256
- * Suggesting, and the landing gets the source as the review draft holds it,
15257
- * with its marks, under the mover's insertion.
15258
- */
15259
15873
  recordNodeMove(groups) {
15260
15874
  const replacements = groups.filter((group) => group.kind === "replace");
15261
15875
  const source = replacements.find((group) => group.removed > 0 && group.slice.length === 0);
@@ -15263,6 +15877,8 @@ var RootRecorder = class {
15263
15877
  if (replacements.length !== 2 || !source || !landing) return false;
15264
15878
  const { plainToReview } = this.options;
15265
15879
  const [copyFrom, copyTo] = this.withoutStruckEdges(source.before, source.before + source.removed);
15880
+ const movedTokens = this.options.storesMoves ? this.index.slice(copyFrom, copyTo).tokens : null;
15881
+ const stores = movedTokens !== null && this.storesMovedElement(movedTokens);
15266
15882
  for (const group of groups) if (group.kind === "kept") this.pieces.push({
15267
15883
  afterFrom: group.after,
15268
15884
  afterTo: group.after + group.length,
@@ -15270,14 +15886,21 @@ var RootRecorder = class {
15270
15886
  kind: "kept"
15271
15887
  });
15272
15888
  else if (group === source) {
15273
- this.strike(copyFrom, copyTo, this.contextAt(copyFrom), "move");
15889
+ if (stores) {
15890
+ this.ops.push({
15891
+ from: copyFrom,
15892
+ kind: "remove",
15893
+ to: copyTo
15894
+ });
15895
+ this.noteFramedRemoval(copyFrom, copyTo, this.contextAt(copyFrom));
15896
+ } else this.strike(copyFrom, copyTo, this.contextAt(copyFrom), "move");
15274
15897
  this.pushRemoved(source.after, copyFrom, copyTo);
15275
15898
  } else {
15276
15899
  this.ops.push({
15277
15900
  at: landing.before,
15278
15901
  kind: "insert",
15279
15902
  moved: true,
15280
- tokens: this.recordCopy(copyFrom, copyTo, landing.before)
15903
+ tokens: stores ? this.storedMove(copyFrom, copyTo, landing.before, movedTokens) : this.recordCopy(copyFrom, copyTo, landing.before)
15281
15904
  });
15282
15905
  this.followJoin(landing, this.ops.length - 1);
15283
15906
  this.pieces.push({
@@ -15353,10 +15976,17 @@ var RootRecorder = class {
15353
15976
  }
15354
15977
  depth += 1;
15355
15978
  if (depth !== 1 || token.nodeKind !== "element") return token;
15356
- const linkedTo = (link) => link === null ? token.props : this.withMarks(token.props, this.marks(token.props).map((each) => each.kind === "insert" && incarnationOf(each) === own ? {
15357
- ...each,
15358
- follows: link
15359
- } : each));
15979
+ const linkedTo = (link) => {
15980
+ if (link === null) return token.props;
15981
+ const marks = this.marks(token.props);
15982
+ return this.withMarks(token.props, isEditingMoveCopy(op, mark.change) && !marks.some((each) => each.kind === "insert" && incarnationOf(each) === own) ? [...marks, {
15983
+ ...mark,
15984
+ follows: link
15985
+ }] : marks.map((each) => each.kind === "insert" && incarnationOf(each) === own ? {
15986
+ ...each,
15987
+ follows: link
15988
+ } : each));
15989
+ };
15360
15990
  const alone = this.followedAt(group.before, group.plainFrom, previous);
15361
15991
  const end = closeIndexOf(copied.tokens, at);
15362
15992
  const moved = alone === null ? void 0 : copied.links.get(alone)?.find((copy) => copy.at > at && copy.at < end)?.link;
@@ -15555,7 +16185,12 @@ var RootRecorder = class {
15555
16185
  const landing = this.options.moveRole === "landing";
15556
16186
  const reinserted = new Set(inserted.tokens.flatMap((token) => token.kind === "open" ? this.marks(token.props).filter((mark) => mark.kind === "delete").map(incarnationOf) : []));
15557
16187
  const struck = this.strike(from, to, startContext, this.options.moveRole === "source" ? "move" : "delete", reinserted);
15558
- if (this.options.framed && inserted.length === 0) this.keepEmptiedLine(from, to, startContext);
16188
+ this.activeTextStrike = null;
16189
+ if (inserted.length === 0) {
16190
+ const opsBeforeKeep = this.ops.length;
16191
+ this.keepEmptiedLine(from, to, startContext);
16192
+ if (this.ops.length > opsBeforeKeep) this.textStrike = null;
16193
+ }
15559
16194
  this.recordInsertion({
15560
16195
  after,
15561
16196
  at: to,
@@ -15572,19 +16207,14 @@ var RootRecorder = class {
15572
16207
  /**
15573
16208
  * A line another author's pending deletion strikes stands in the frame only
15574
16209
  * through its live content. When a removal inside it takes the last of that
15575
- * content, the frame still holds the emptied line, so an empty line with its
15576
- * properties follows it. A suggested one stood only while the line's
16210
+ * content, the edit still holds the emptied line, so an empty line with its
16211
+ * properties follows it and takes the positions in and after the line. A
16212
+ * suggested one stood only while the line's
15577
16213
  * deletions and the removed content's insertions did, so it rests on both.
15578
16214
  */
15579
16215
  keepEmptiedLine(from, to, contexts) {
15580
16216
  const line = contexts.findLast((context) => context.kind === "element");
15581
- if (!line || to > line.contentTo || !isTextBlock(this.index.node(line.path)) || !this.hasMarkKind(line.props, "delete") || !this.holdsLiveContent(line, [{
15582
- from,
15583
- to: from
15584
- }]) || this.holdsLiveContent(line, [{
15585
- from,
15586
- to
15587
- }])) return;
16217
+ if (!line || !emptiesStruckLine(this.index, (props) => this.marks(props), line, from, to)) return;
15588
16218
  const { isOwn, markOf } = this.options;
15589
16219
  const lineMarks = this.marks(line.props);
15590
16220
  const resting = [...lineMarks.flatMap((mark) => mark.kind === "delete" ? [asInsertion(mark)] : mark.kind === "insert" ? [mark] : []), ...this.removedLiveContent(line, from, to).flatMap((props) => this.marks(props).filter((mark) => mark.kind === "insert"))].filter((mark) => !isOwn(mark));
@@ -15595,10 +16225,19 @@ var RootRecorder = class {
15595
16225
  text: ""
15596
16226
  }]
15597
16227
  }, [...resting, markOf("insert")]);
16228
+ const at = line.contentTo + 1;
16229
+ const { tokens } = encodeNodes([node]).slice;
15598
16230
  this.ops.push({
15599
- at: line.contentTo + 1,
16231
+ at,
15600
16232
  kind: "insert",
15601
- tokens: encodeNodes([node]).slice.tokens
16233
+ tokens
16234
+ });
16235
+ this.keptLines.push({
16236
+ at,
16237
+ contentFrom: line.contentFrom,
16238
+ contentTo: line.contentTo,
16239
+ from,
16240
+ inside: tokens.findIndex((token) => token.kind === "open" && token.nodeKind === "text") + 1
15602
16241
  });
15603
16242
  }
15604
16243
  /**
@@ -15609,9 +16248,9 @@ var RootRecorder = class {
15609
16248
  */
15610
16249
  strikeEmptiedWrappers() {
15611
16250
  const wrappers = /* @__PURE__ */ new Map();
15612
- for (const { contexts } of this.framedStrikes) for (const context of contexts) if (context.kind === "element" && this.hasMarkKind(context.props, "unwrap") && !this.marks(context.props).some((mark) => mark.kind === "delete" && mark.change === this.options.changeId)) wrappers.set(context.contentFrom, context);
16251
+ for (const { contexts } of this.framedRemovals) for (const context of contexts) if (context.kind === "element" && this.hasMarkKind(context.props, "unwrap") && !this.marks(context.props).some((mark) => mark.kind === "delete" && mark.change === this.options.changeId)) wrappers.set(context.contentFrom, context);
15613
16252
  if (wrappers.size === 0) return;
15614
- const removed = [...this.framedStrikes];
16253
+ const removed = [...this.framedRemovals];
15615
16254
  const liveLandings = this.ops.flatMap((op) => op.kind === "insert" && op.tokens.some((token) => token.kind === "open" && !this.hasMarkKind(token.props, "delete")) ? [op.at] : []);
15616
16255
  for (const wrapper of [...wrappers.values()].sort((left, right) => right.path.length - left.path.length)) {
15617
16256
  if (liveLandings.some((at) => at >= wrapper.contentFrom && at <= wrapper.contentTo) || this.holdsLiveContent(wrapper, removed)) continue;
@@ -15640,19 +16279,7 @@ var RootRecorder = class {
15640
16279
  }
15641
16280
  return false;
15642
16281
  }
15643
- const { offsets, tokens } = this.index.slice(element.contentFrom, element.contentTo);
15644
- let liveLeaf = false;
15645
- return tokens.some((token, index) => {
15646
- const at = element.contentFrom + offsets[index];
15647
- if (token.kind === "text") return liveLeaf && !gone(at, at + token.text.length);
15648
- if (token.kind !== "open") return false;
15649
- const live = !this.hasMarkKind(token.props, "delete");
15650
- if (token.nodeKind === "text") {
15651
- liveLeaf = live;
15652
- return false;
15653
- }
15654
- return live && !gone(at, at + 1);
15655
- });
16282
+ return holdsLiveText(this.index, (props) => this.marks(props), element, removed);
15656
16283
  }
15657
16284
  removedLiveContent(line, from, to) {
15658
16285
  const { offsets, tokens } = this.index.slice(line.contentFrom, line.contentTo);
@@ -15731,6 +16358,17 @@ var RootRecorder = class {
15731
16358
  kind: "join"
15732
16359
  };
15733
16360
  };
16361
+ const strikeTracking = mode === "delete" ? this.activeTextStrike : null;
16362
+ const strikeParent = strikeTracking ? startContext.findLast((context) => context.kind === "element") : void 0;
16363
+ const textStrikeState = {
16364
+ mark: null,
16365
+ pure: Boolean(strikeTracking && strikeParent && to <= strikeParent.contentTo)
16366
+ };
16367
+ const noteTextStrike = (mark) => {
16368
+ if (!textStrikeState.pure) return;
16369
+ if (textStrikeState.mark && (textStrikeState.mark.author !== mark.author || textStrikeState.mark.change !== mark.change)) textStrikeState.pure = false;
16370
+ else textStrikeState.mark = mark;
16371
+ };
15734
16372
  for (let index = 0; index < local.length; index += 1) {
15735
16373
  const token = local[index];
15736
16374
  const position = from + localOffsets[index];
@@ -15740,6 +16378,7 @@ var RootRecorder = class {
15740
16378
  const marks = this.marks(leaf.props);
15741
16379
  if (struck(marks)) continue;
15742
16380
  if (withdrawn(marks)) {
16381
+ textStrikeState.pure = false;
15743
16382
  this.ops.push({
15744
16383
  from: position,
15745
16384
  kind: "remove",
@@ -15748,7 +16387,9 @@ var RootRecorder = class {
15748
16387
  continue;
15749
16388
  }
15750
16389
  if (!opened.has(leaf.contentFrom) && firstSplitLeaf !== leaf) {
15751
- const struckProps = this.withMarks(leaf.props, [...marks, strikeMark(leaf, position)]);
16390
+ const mark = strikeMark(leaf, position);
16391
+ noteTextStrike(mark);
16392
+ const struckProps = this.withMarks(leaf.props, [...marks, mark]);
15752
16393
  this.ops.push({
15753
16394
  at: position,
15754
16395
  kind: "insert",
@@ -15775,6 +16416,7 @@ var RootRecorder = class {
15775
16416
  const removedOutright = close !== void 0 && withdrawnThroughout(index, close);
15776
16417
  const parent = stack.at(-1);
15777
16418
  const parentChildren = parent && keptElementChildren.get(parent);
16419
+ if (token.nodeKind !== "text" || removedOutright) textStrikeState.pure = false;
15778
16420
  if (parentChildren && !removedOutright) parentChildren.survived = true;
15779
16421
  else if (parentChildren) parentChildren.removed = true;
15780
16422
  if (close !== void 0) {
@@ -15795,11 +16437,15 @@ var RootRecorder = class {
15795
16437
  props,
15796
16438
  strikeOpIndex
15797
16439
  });
15798
- if (strikeOpIndex !== null) this.ops.push({
15799
- at: position,
15800
- kind: "props",
15801
- props: this.withMarks(props, [...marks, markOf("delete")])
15802
- });
16440
+ if (strikeOpIndex !== null) {
16441
+ const mark = markOf("delete");
16442
+ if (token.nodeKind === "text") noteTextStrike(mark);
16443
+ this.ops.push({
16444
+ at: position,
16445
+ kind: "props",
16446
+ props: this.withMarks(props, [...marks, mark])
16447
+ });
16448
+ }
15803
16449
  if (token.nodeKind === "text") index = close;
15804
16450
  else {
15805
16451
  stack.push(context);
@@ -15815,15 +16461,21 @@ var RootRecorder = class {
15815
16461
  opened.add(context.contentFrom);
15816
16462
  if (token.nodeKind === "text") {
15817
16463
  openLeaf = props;
15818
- if (struck(marks) || withdrawn(marks)) continue;
15819
- const struckProps = this.withMarks(props, [...marks, strikeMark(context, context.contentFrom)]);
16464
+ if (withdrawn(marks)) {
16465
+ textStrikeState.pure = false;
16466
+ continue;
16467
+ }
16468
+ if (struck(marks)) continue;
16469
+ const mark = strikeMark(context, context.contentFrom);
16470
+ noteTextStrike(mark);
16471
+ const struckProps = this.withMarks(props, [...marks, mark]);
15820
16472
  this.ops.push({
15821
16473
  at: position,
15822
16474
  kind: "props",
15823
16475
  props: struckProps
15824
16476
  });
15825
16477
  openLeaf = struckProps;
15826
- reopen = props;
16478
+ reopen = context.contentTo > to ? props : leafOf(startContext);
15827
16479
  continue;
15828
16480
  }
15829
16481
  if (this.options.framed && marks.some((mark) => mark.kind === "unwrap")) {
@@ -15896,11 +16548,14 @@ var RootRecorder = class {
15896
16548
  tokens: encodeNodes(children.map((child) => this.options.dependencies.throughout(child, marks))).slice.tokens
15897
16549
  });
15898
16550
  }
15899
- if (this.options.framed && from < to) this.framedStrikes.push({
15900
- contexts: [...startContext, ...stack],
15901
- from,
15902
- to
15903
- });
16551
+ if (textStrikeState.pure && strikeTracking && strikeParent && textStrikeState.mark && emptiedKeptElementAt.size === 0) this.textStrike = {
16552
+ author: textStrikeState.mark.author,
16553
+ blockPath: strikeParent.path,
16554
+ change: textStrikeState.mark.change,
16555
+ plainFrom: strikeTracking.plainFrom,
16556
+ plainTo: strikeTracking.plainTo
16557
+ };
16558
+ this.noteFramedRemoval(from, to, [...startContext, ...stack]);
15904
16559
  return {
15905
16560
  contexts: stack,
15906
16561
  openLeaf,
@@ -15937,21 +16592,29 @@ var RootRecorder = class {
15937
16592
  emit(openToken("text", props));
15938
16593
  outLeaf = props;
15939
16594
  };
16595
+ const claimOf = (marks) => {
16596
+ const inserts = marks.filter((mark) => mark.kind === "insert");
16597
+ const pending = inserts.filter((mark) => !isEditingChange(mark.change));
16598
+ const ownEditing = pending.length ? inserts.find((mark) => isEditingChange(mark.change) && mark.change === this.options.changeId) : void 0;
16599
+ return ownEditing ? {
16600
+ insertion: ownEditing,
16601
+ outer: pending
16602
+ } : {
16603
+ insertion: innermostInsert(pending),
16604
+ outer: pending.slice(0, -1)
16605
+ };
16606
+ };
15940
16607
  const ownElement = () => {
15941
16608
  for (const context of [...stack].reverse()) {
15942
16609
  if (context.kind !== "element") continue;
15943
- const insertion = innermostInsert(this.marks(context.props).filter((mark) => !isEditingChange(mark.change)));
16610
+ const { insertion, outer } = claimOf(this.marks(context.props));
15944
16611
  if (!insertion) continue;
15945
16612
  if (!this.options.isOwn(insertion)) return null;
15946
16613
  const { type } = context.props;
16614
+ const mark = contentClaim(insertion);
15947
16615
  return {
15948
- mark: {
15949
- at: insertion.at,
15950
- author: insertion.author,
15951
- change: insertion.change,
15952
- ...insertion.inc === void 0 ? {} : { inc: insertion.inc },
15953
- kind: "insert"
15954
- },
16616
+ mark,
16617
+ marks: [...outer, mark],
15955
16618
  oneText: typeof type === "string" && this.options.oneText(type)
15956
16619
  };
15957
16620
  }
@@ -15964,13 +16627,13 @@ var RootRecorder = class {
15964
16627
  const joinedOneTextInserts = () => inOneText() && baseLeaf ? this.oneTextMarksButOwnInserts(this.marks(baseLeaf)) : null;
15965
16628
  const insertedMarks = () => {
15966
16629
  const own = ownElement();
15967
- if (own) return own.oneText && baseLeaf ? this.marks(baseLeaf).filter((mark) => mark.kind !== "delete") : [own.mark];
16630
+ if (own) return own.oneText && baseLeaf ? this.marks(baseLeaf).filter((mark) => mark.kind !== "delete") : own.marks;
15968
16631
  return [...joinedOneTextInserts() ?? this.containedInsertMarks(stack, at), this.continuedOwnInsert(stack, at) ?? this.options.markOf("insert")];
15969
16632
  };
15970
16633
  const withInserted = (props, added) => this.withMarks(withoutSpares(props), [...this.marks(props), ...added]);
15971
16634
  const insertedLeaves = /* @__PURE__ */ new Set();
15972
16635
  const landed = (props) => {
15973
- const marks = this.withoutCuts(props);
16636
+ const marks = this.withoutCuts(props).filter((mark) => this.isEditing || mark.kind !== "delete");
15974
16637
  return this.withMarks(withoutSpares(props), [...marks, this.options.markOf("insert")]);
15975
16638
  };
15976
16639
  let trailingLeafProps = input.reopen ?? leafOf(stack);
@@ -16248,7 +16911,7 @@ var RootRecorder = class {
16248
16911
  return this.formattedProps(base, this.withMarks(next, this.marks(base))) ?? base;
16249
16912
  }
16250
16913
  suggestedTextProps(leaf, at, ownElement, inOneText) {
16251
- if (!leaf || leaf.kind !== "text") return this.withMarks({}, [ownElement?.mark ?? this.options.markOf("insert")]);
16914
+ if (!leaf || leaf.kind !== "text") return this.withMarks({}, ownElement ? ownElement.marks : [this.options.markOf("insert")]);
16252
16915
  const marks = this.marks(leaf.props);
16253
16916
  const innermost = innermostInsert(marks);
16254
16917
  const foreign = innermost !== void 0 && !this.options.isOwn(innermost);
@@ -16256,7 +16919,7 @@ var RootRecorder = class {
16256
16919
  if (innermost && !foreign && !struck) return withoutHeld(leaf.props);
16257
16920
  if (ownElement && (ownElement.oneText || !foreign)) {
16258
16921
  const live = marks.filter((mark) => mark.kind !== "delete" && mark.kind !== "format");
16259
- return this.withMarks(leaf.props, ownElement.oneText ? marks.filter((mark) => mark.kind !== "delete") : [...live, ownElement.mark], true);
16922
+ return this.withMarks(leaf.props, ownElement.oneText ? marks.filter((mark) => mark.kind !== "delete") : [...live, ...ownElement.marks], true);
16260
16923
  }
16261
16924
  const kept = inOneText ? this.oneTextMarksButOwnInserts(marks) : leaf.contentFrom < at && at < leaf.contentTo ? marks.filter((mark) => mark.kind === "insert") : this.sharedNeighborInserts(leaf, at);
16262
16925
  return this.withMarks(leaf.props, [...kept, this.continuedOwnInsert([leaf], at) ?? this.options.markOf("insert")], true);
@@ -16566,7 +17229,17 @@ var RootRecorder = class {
16566
17229
  for (const piece of this.pieces) if (!startsInserted && piece.kind === "removed" && (piece.after === position || caret && this.besideRemoval(piece, position))) removed = piece;
16567
17230
  const replacing = removed && !caret && assoc === 1 ? this.insertionStartingAt(position) : void 0;
16568
17231
  if (replacing) return (recorded.mapPos(replacing.at, -1) ?? position) + (replacing.offsets[0] ?? 0);
16569
- const throughKept = (piece) => recorded.mapPos(piece.beforeFrom + position - piece.afterFrom, assoc) ?? position;
17232
+ const inKeptLine = (at) => {
17233
+ const kept = this.keptLines.find((line) => line.contentFrom <= at && at <= line.contentTo);
17234
+ if (!kept) return null;
17235
+ return (recorded.mapPos(kept.at, -1) ?? position) + (caret || at === kept.from ? kept.inside : at < kept.from ? kept.inside - 1 : kept.inside + 1);
17236
+ };
17237
+ const throughKept = (piece) => {
17238
+ const at = piece.beforeFrom + position - piece.afterFrom;
17239
+ const kept = inKeptLine(at);
17240
+ if (kept !== null) return kept;
17241
+ return recorded.mapPos(at, this.keptLines.some((line) => line.at === at) ? 1 : assoc) ?? position;
17242
+ };
16570
17243
  for (const piece of this.pieces) {
16571
17244
  if (piece.kind === "removed") continue;
16572
17245
  if (position < piece.afterFrom || position > piece.afterTo) continue;
@@ -16585,6 +17258,8 @@ var RootRecorder = class {
16585
17258
  return (recorded.mapPos(piece.at, -1) ?? position) + (piece.offsets[position - piece.afterFrom] ?? 0);
16586
17259
  }
16587
17260
  if (removed) {
17261
+ const kept = inKeptLine(removed.beforeFrom);
17262
+ if (kept !== null) return kept;
16588
17263
  const right = caret ? !removed.leftward : assoc === 1;
16589
17264
  const edge = right ? removed.beforeTo : removed.beforeFrom;
16590
17265
  if (!caret) return recorded.mapPos(edge, right ? 1 : -1) ?? position;
@@ -16757,6 +17432,10 @@ const restingChanges = (host, lifted, children, isOwn) => {
16757
17432
  reshapes: insertionsOf(reshaping)
16758
17433
  };
16759
17434
  };
17435
+ const elementsEnclosing = (index, at) => {
17436
+ const position = Math.min(at, index.length);
17437
+ return index.openContextAt(position).filter((range) => range.kind !== "text" && range.from < position && position < range.to);
17438
+ };
16760
17439
  /**
16761
17440
  * Each element whose proposed children the change touched, once, as its path
16762
17441
  * after the change and before it, with the elements whose pending unwraps
@@ -16771,8 +17450,8 @@ const changedHosts = (rootChange, before, after, afterChildren, schema) => {
16771
17450
  }]]);
16772
17451
  rootChange.iterChangedRanges((fromA, toA, fromB, toB) => {
16773
17452
  for (const [positionA, positionB] of [[fromA, fromB], [toA, toB]]) {
16774
- const opened = after.openContextAt(Math.min(positionB, after.length)).filter((range) => range.kind !== "text");
16775
- const openedBefore = before.openContextAt(Math.min(positionA, before.length)).filter((range) => range.kind !== "text");
17453
+ const opened = elementsEnclosing(after, positionB);
17454
+ const openedBefore = elementsEnclosing(before, positionA);
16776
17455
  opened.forEach((range, depth) => {
16777
17456
  const path = proposedHost(afterChildren, range.path, schema);
16778
17457
  if (!path) return;
@@ -17229,6 +17908,35 @@ const isStruck = (editor, node) => {
17229
17908
  const facts = factsOf(storedValue(editor));
17230
17909
  return isSettledDeletion(node, facts) || marksOf(node, facts).some((mark) => mark.kind === "delete");
17231
17910
  };
17911
+ const emptiedInUpdate = (editor, point, document) => {
17912
+ const builder = (getTransactionSnapshot(editor) ?? getTransactionSnapshot(getEditorRuntimeOwner(editor)))?.builder;
17913
+ if (!builder) return false;
17914
+ const root = point.root ?? "main";
17915
+ const index = builder.getIndex(root);
17916
+ if (index.nodes !== document) return false;
17917
+ const at = index.positionAt(point);
17918
+ const facts = factsOf(storedValue(editor));
17919
+ const marks = (props) => marksOf(props, facts);
17920
+ const steps = builder.draftSteps;
17921
+ return steps.some((step, first) => {
17922
+ const before = step.indexedBefore.get(root);
17923
+ const change = getInternalDocumentRootChange(step.change, root);
17924
+ if (!before || !change) return false;
17925
+ const later = steps.slice(first);
17926
+ const after = (position, assoc) => later.reduce((mapped, each) => mapped === null ? null : getInternalDocumentRootChange(each.change, root)?.mapPos(mapped, assoc) ?? mapped, position);
17927
+ let position = 0;
17928
+ for (let pair = 0; pair < change.sections.length; pair += 2) {
17929
+ const length = change.sections[pair];
17930
+ const line = change.sections[pair + 1] === 0 && length > 0 ? emptiedStruckLine(before, marks, position, position + length) : null;
17931
+ position += length;
17932
+ if (!line) continue;
17933
+ const start = after(line.from, 1);
17934
+ const end = after(line.to, -1);
17935
+ if (start !== null && end !== null && start <= at && at <= end) return true;
17936
+ }
17937
+ return false;
17938
+ });
17939
+ };
17232
17940
  const positionOf = (value, root, point) => valueRootIndex(value, root).positionAt(point);
17233
17941
  const mapPoint = (point, input, assoc) => {
17234
17942
  const index = input.indexes.get(input.root);
@@ -17792,7 +18500,8 @@ const createAuthoredPlugin = (options) => {
17792
18500
  ids: [...outcome.decided],
17793
18501
  status: "applied"
17794
18502
  },
17795
- settles: settlesTextAlone(value, change, [.../* @__PURE__ */ new Set([...ids, ...outcome.decided])], actions, (id) => book.occurrences(id), withdraws)
18503
+ settles: settlesTextAlone(value, change, [.../* @__PURE__ */ new Set([...ids, ...outcome.decided])], actions, (id) => book.occurrences(id), withdraws),
18504
+ value: decidedValue
17796
18505
  };
17797
18506
  };
17798
18507
  const decideOn = (editor, value, decisions, withdraws, apply) => readingCovered({
@@ -17802,16 +18511,20 @@ const createAuthoredPlugin = (options) => {
17802
18511
  return definePlugin("authored", {
17803
18512
  dependencies: [authoredRecords],
17804
18513
  schema: authoredMarksSchema,
17805
- contributions: [documentAdmissionPoint.of(authoredAdmission), authoredDocumentCapabilityPoint.of({
17806
- claimsBreakBefore,
17807
- pending: (document) => indexAuthoredChanges(document).changes.size,
17808
- project: (document, projection, schema) => withoutGeneration(() => projectAuthoredDocumentUnder(document, projection, storedResolveSchemaOf(schema, document))),
17809
- projectDecided: (document, projection, schema) => projectAuthoredDocumentUnder(document, projection, storedResolveSchemaOf(schema, document)),
17810
- projectBlocks: (document, projection, schema, root, paths) => withoutGeneration(() => projectAuthoredBlocks(document, projection, storedResolveSchemaOf(schema, document), root, paths)),
17811
- repair: (document, schema) => admitDocument(authoredAdmission, document, schema).document,
17812
- spareBlock,
17813
- spareRoot
17814
- })],
18514
+ contributions: [
18515
+ documentAdmissionPoint.of(authoredAdmission),
18516
+ authoredDocumentCapabilityPoint.of({
18517
+ claimsBreakBefore,
18518
+ pending: (document) => indexAuthoredChanges(document).changes.size,
18519
+ project: (document, projection, schema) => withoutGeneration(() => projectAuthoredDocumentUnder(document, projection, storedResolveSchemaOf(schema, document))),
18520
+ projectDecided: (document, projection, schema) => projectAuthoredDocumentUnder(document, projection, storedResolveSchemaOf(schema, document)),
18521
+ projectBlocks: (document, projection, schema, root, paths) => withoutGeneration(() => projectAuthoredBlocks(document, projection, storedResolveSchemaOf(schema, document), root, paths)),
18522
+ repair: (document, schema) => admitDocument(authoredAdmission, document, schema).document,
18523
+ spareBlock,
18524
+ spareRoot
18525
+ }),
18526
+ textLineRefusal.of(true)
18527
+ ],
17815
18528
  api: ({ editor }) => ({
17816
18529
  setView: (view) => {
17817
18530
  if (("preview" in view || view.intent === "propose") && !storesGeneratedValues(getCompiledEditorSchema(editor))) {
@@ -18105,7 +18818,7 @@ const createAuthoredPlugin = (options) => {
18105
18818
  if (storesSpares(schema)) ledger.shown.load(storedRead(editor, (stored) => stored.read.value()), schema);
18106
18819
  });
18107
18820
  onCleanup(registerEditorDraftGuard(editor, (value) => ledger.check(value)));
18108
- onCleanup(registerEditorContent(editor, (reader, node) => !isStruck(reader, node)));
18821
+ onCleanup(registerEditorContent(editor, (reader, node) => !isStruck(reader, node), emptiedInUpdate));
18109
18822
  onCleanup(registerEditorCommandDocument(editor, {
18110
18823
  recorded: (input) => {
18111
18824
  ledger.recorded(input);
@@ -18129,6 +18842,47 @@ const createAuthoredPlugin = (options) => {
18129
18842
  }));
18130
18843
  onCleanup(registerEditorFitsByLook(editor, holdsMembers));
18131
18844
  const minted = /* @__PURE__ */ new WeakMap();
18845
+ const coverOf = (input, writer) => {
18846
+ const { projection } = input;
18847
+ const target = input.removal ?? (input.selectionBefore?.kind === "text" && !RangeApi.isCollapsed(input.selectionBefore) ? {
18848
+ root: input.selectionBeforeRoot,
18849
+ selection: input.selectionBefore
18850
+ } : null);
18851
+ if (!projection || !target || input.composition || minted.has(input.update) || isBoundToSharedRoom(editor)) return null;
18852
+ const before = input.before;
18853
+ const { root } = target;
18854
+ const stored = rootOf(before, root);
18855
+ const [start, end] = RangeApi.edges(target.selection);
18856
+ const from = stored.positionAt(start);
18857
+ const to = stored.positionAt(end);
18858
+ if (!(input.change.empty ? input.removal : replacesRange(input, projection, root, from, to))) return null;
18859
+ const book = changesOf(editor, before);
18860
+ const ids = coveredDeletionsOf(book, stored, {
18861
+ from,
18862
+ keeps: gridRolesOf(getCompiledEditorSchema(editor)).isPart,
18863
+ root,
18864
+ to,
18865
+ writer
18866
+ });
18867
+ if (!ids || ids.length === 0) return null;
18868
+ const decided = decisionOn(editor, before, {
18869
+ action: "accept",
18870
+ changes: ids.map((id) => getDefined(book.change(id)))
18871
+ }, false);
18872
+ if (!("change" in decided)) return null;
18873
+ const relink = relinkCuts(decided.change, before, decided.value, (at) => rootOf(decided.value, at));
18874
+ const value = relink ? applyDocumentChangeValue(relink.change, decided.value, relink.indexes) : decided.value;
18875
+ const decidedProjection = new ReviewLedger(owner, () => authoredResolveSchemaOf(editor), state.marks).frame(value) ?? {
18876
+ indexes: /* @__PURE__ */ new Map(),
18877
+ map: projectionMapOf(createInternalDocumentChange(/* @__PURE__ */ new Map())),
18878
+ value
18879
+ };
18880
+ return jsonEqual(decidedProjection.value.children, projection.value.children) && jsonEqual(decidedProjection.value.roots ?? null, projection.value.roots ?? null) ? {
18881
+ change: relink ? decided.change.compose(relink.change) : decided.change,
18882
+ projection: decidedProjection,
18883
+ value
18884
+ } : null;
18885
+ };
18132
18886
  onCleanup(registerEditorDocumentRecorder(editor, (input) => {
18133
18887
  if (isReplay(input.tags)) return null;
18134
18888
  if (input.steps.length > 0 && input.steps.every((step) => step.origin === "migration")) return null;
@@ -18144,7 +18898,6 @@ const createAuthoredPlugin = (options) => {
18144
18898
  const viewEditor = getAuthoredUpdateView(editor);
18145
18899
  settleWaitingView(viewEditor);
18146
18900
  const updateView = viewOf(viewEditor);
18147
- const before = input.before;
18148
18901
  const after = input.after;
18149
18902
  const contentChange = contentChangeOf(input.change);
18150
18903
  const steps = input.steps.map((step) => {
@@ -18156,272 +18909,331 @@ const createAuthoredPlugin = (options) => {
18156
18909
  });
18157
18910
  const contentSteps = steps.filter((step) => step.origin !== "root");
18158
18911
  const ownRecords = getInternalDocumentChangeRecords(input.change);
18159
- const known = factsOf(withStore(before, getValueRecords(after)));
18160
18912
  if ("preview" in updateView) throw new Error("A preview view does not take this write.");
18161
18913
  if (!input.projection) {
18162
18914
  const written = writtenNamedRoots(contentSteps);
18163
18915
  if (written.size > 0) {
18164
- const dropped = ledger.dropped(before);
18916
+ const dropped = ledger.dropped(input.before);
18165
18917
  if ([...written].some((root) => dropped.has(root))) throw unplaced();
18166
18918
  }
18167
18919
  }
18168
18920
  const editing = !forced && updateView.intent === "edit";
18169
18921
  const writer = authorOf(viewEditor);
18170
18922
  if (writer === null) throw new Error("An author ID is required for authored writes.");
18171
- const byName = contentChange.deleteRoots.size > 0 ? new Set(rootsDeletedByName(getCompiledEditorSchema(editor), input.projection?.value ?? before, after, changedRootsOf(contentChange), contentChange.deleteRoots)) : NO_ROOTS;
18172
- if (!editing && byName.size > 0) throw unrepresentable("Suggesting cannot delete a named root; suggest deleting its content.");
18173
- const followed = byName.size === 0 ? contentChange.deleteRoots : new Set([...contentChange.deleteRoots].filter((root) => !byName.has(root)));
18174
- const createdThenDeleted = new Set(steps.flatMap((step) => [...step.change.createRoots].filter((root) => !contentChange.createRoots.has(root) && !before.roots?.[root])));
18175
- const createRoots = createdThenDeleted.size === 0 ? contentChange.createRoots : /* @__PURE__ */ new Set([...contentChange.createRoots, ...createdThenDeleted]);
18176
- const withdrawable = createdThenDeleted.size === 0 ? followed : /* @__PURE__ */ new Set([...followed, ...createdThenDeleted]);
18177
- if (!editing) {
18178
- const vetoes = options.vetoes === false || updateView.intent !== "propose" ? [] : getPluginContributions(editor, authoredVeto);
18179
- const refusal = (update && state.refused.get(update)) ?? (!storesGeneratedValues(getCompiledEditorSchema(editor)) ? GENERATED_VALUES_REFUSAL : vetoes.length > 0 ? proposalRefusal(contentSteps, vetoes) : null);
18180
- if (refusal) {
18181
- if (update) state.refused.set(update, refusal);
18182
- throw new EditorRefusalError(refusal, refusal.message);
18923
+ const covered = editing ? coverOf(input, writer) : null;
18924
+ const recordOn = (before, projection, storedRecords) => {
18925
+ const known = factsOf(withStore(before, storedRecords));
18926
+ const byName = contentChange.deleteRoots.size > 0 ? new Set(rootsDeletedByName(getCompiledEditorSchema(editor), projection?.value ?? before, after, changedRootsOf(contentChange), contentChange.deleteRoots)) : NO_ROOTS;
18927
+ if (!editing && byName.size > 0) throw unrepresentable("Suggesting cannot delete a named root; suggest deleting its content.");
18928
+ const followed = byName.size === 0 ? contentChange.deleteRoots : new Set([...contentChange.deleteRoots].filter((root) => !byName.has(root)));
18929
+ const createdThenDeleted = new Set(steps.flatMap((step) => [...step.change.createRoots].filter((root) => !contentChange.createRoots.has(root) && !before.roots?.[root])));
18930
+ const createRoots = createdThenDeleted.size === 0 ? contentChange.createRoots : /* @__PURE__ */ new Set([...contentChange.createRoots, ...createdThenDeleted]);
18931
+ const withdrawable = createdThenDeleted.size === 0 ? followed : /* @__PURE__ */ new Set([...followed, ...createdThenDeleted]);
18932
+ if (!editing) {
18933
+ const vetoes = options.vetoes === false || updateView.intent !== "propose" ? [] : getPluginContributions(editor, authoredVeto);
18934
+ const refusal = (update && state.refused.get(update)) ?? (!storesGeneratedValues(getCompiledEditorSchema(editor)) ? GENERATED_VALUES_REFUSAL : vetoes.length > 0 ? proposalRefusal(contentSteps, vetoes) : null);
18935
+ if (refusal) {
18936
+ if (update) state.refused.set(update, refusal);
18937
+ throw new EditorRefusalError(refusal, refusal.message);
18938
+ }
18183
18939
  }
18184
- }
18185
- const { composition } = input;
18186
- const focusBefore = input.selectionBefore?.kind !== "text" ? null : PointApi.equals(input.selectionBefore.anchor, input.selectionBefore.focus) ? input.selectionBefore.focus : composition ? RangeApi.start(input.selectionBefore) : null;
18187
- const compositionRoot = composition ? composition.place.root ?? input.selectionBeforeRoot : null;
18188
- const selectionPosition = focusBefore ? positionOf(before, input.selectionBeforeRoot, focusBefore) : null;
18189
- const minting = minted.get(input.update) ?? {
18190
- at: forced?.at ?? now(),
18191
- changeId: editing ? editingChangeOf(writer) : createChangeId()
18192
- };
18193
- minted.set(input.update, minting);
18194
- const { at, changeId } = minting;
18195
- const dependencies = createDependencies(known, carriedIn(after));
18196
- let commitWrite;
18197
- const commitWriteId = () => commitWrite ??= createTagId();
18198
- const landedHere = (write) => editing && write === commitWrite || known.landed(write);
18199
- const standing = {
18200
- accepted: (member) => isAccepted(known, member),
18201
- landed: landedHere
18202
- };
18203
- const compiled = getCompiledEditorSchema(editor);
18204
- const oneText = (type) => holdsOneText(getEditorSchema(editor), type);
18205
- const recorded = recordAuthoredSteps({
18206
- before,
18207
- changeId,
18208
- composition: composition && compositionRoot !== null ? {
18209
- element: composition.place.path.slice(0, -1),
18210
- position: positionOf(before, compositionRoot, composition.place),
18211
- root: compositionRoot
18212
- } : null,
18213
- createRoots,
18214
- createTagId,
18215
- crossesUnique: (from, to) => crossesUniqueTarget(compiled, from, to),
18216
- holdsUnique: (type, key) => holdsUniqueKey(compiled, type, key),
18217
- deleteRoots: byName,
18218
- dependencies,
18219
- fill: (site, root) => completeChildrenAt(editor, site.map(elementOf), [], root).children,
18220
- followed,
18221
- forcedChangeId: forced?.changeId ?? (editing ? changeId : null),
18222
- projection: input.projection,
18223
- inc: forced?.inc ?? null,
18224
- gridRoles: gridRolesOf(compiled),
18225
- isInline: (props) => getEditorSchema(editor).isInline(elementOf(props)),
18226
- emptyTextKeeps: (key, value, parents, root) => {
18227
- const [parent, ...ancestors] = parents.map(elementOf);
18228
- return !getEditorSchema(editor).emptyTextDrops({
18229
- ancestors,
18230
- parent,
18940
+ const { composition } = input;
18941
+ const focusBefore = input.selectionBefore?.kind !== "text" ? null : PointApi.equals(input.selectionBefore.anchor, input.selectionBefore.focus) ? input.selectionBefore.focus : composition ? RangeApi.start(input.selectionBefore) : null;
18942
+ const compositionRoot = composition ? composition.place.root ?? input.selectionBeforeRoot : null;
18943
+ const selectionPosition = focusBefore ? positionOf(before, input.selectionBeforeRoot, focusBefore) : null;
18944
+ const minting = minted.get(input.update) ?? {
18945
+ at: forced?.at ?? now(),
18946
+ changeId: editing ? editingChangeOf(writer) : createChangeId()
18947
+ };
18948
+ minted.set(input.update, minting);
18949
+ const { at, changeId } = minting;
18950
+ const dependencies = createDependencies(known, carriedIn(after));
18951
+ let commitWrite;
18952
+ const commitWriteId = () => commitWrite ??= createTagId();
18953
+ const landedHere = (write) => editing && write === commitWrite || known.landed(write);
18954
+ const standing = {
18955
+ accepted: (member) => isAccepted(known, member),
18956
+ landed: landedHere
18957
+ };
18958
+ const compiled = getCompiledEditorSchema(editor);
18959
+ const oneText = (type) => holdsOneText(getEditorSchema(editor), type);
18960
+ const recorded = recordAuthoredSteps({
18961
+ before,
18962
+ changeId,
18963
+ composition: composition && compositionRoot !== null ? {
18964
+ element: composition.place.path.slice(0, -1),
18965
+ position: positionOf(before, compositionRoot, composition.place),
18966
+ root: compositionRoot
18967
+ } : null,
18968
+ createRoots,
18969
+ createTagId,
18970
+ crossesUnique: (from, to) => crossesUniqueTarget(compiled, from, to),
18971
+ holdsUnique: (type, key) => holdsUniqueKey(compiled, type, key),
18972
+ deleteRoots: byName,
18973
+ dependencies,
18974
+ fill: (site, root) => completeChildrenAt(editor, site.map(elementOf), [], root).children,
18975
+ followed,
18976
+ forcedChangeId: forced?.changeId ?? (editing ? changeId : null),
18977
+ projection,
18978
+ inc: forced?.inc ?? null,
18979
+ gridRoles: gridRolesOf(compiled),
18980
+ isInline: (props) => getEditorSchema(editor).isInline(elementOf(props)),
18981
+ emptyTextKeeps: (key, value, parents, root) => {
18982
+ const [parent, ...ancestors] = parents.map(elementOf);
18983
+ return !getEditorSchema(editor).emptyTextDrops({
18984
+ ancestors,
18985
+ parent,
18986
+ root
18987
+ })?.(key, value);
18988
+ },
18989
+ keepsOnSplit: ({ continuation, path, reviewDraft, source }, root) => getEditorSchema(editor).elementSplitKeepsAt(elementOf(source), elementOf(continuation), {
18990
+ children: reviewDraft,
18991
+ path: [...path],
18231
18992
  root
18232
- })?.(key, value);
18233
- },
18234
- keepsOnSplit: ({ continuation, path, reviewDraft, source }, root) => getEditorSchema(editor).elementSplitKeepsAt(elementOf(source), elementOf(continuation), {
18235
- children: reviewDraft,
18236
- path: [...path],
18237
- root
18238
- }),
18239
- slotted: (type, root) => (authoredResolveSchemaOf(editor).content(type, root)?.prefix ?? 0) > 0,
18240
- declaredIn: (element, ancestors, root) => getEditorSchema(editor).elementDeclaredPropertiesIn(elementOf(element), {
18241
- ancestors: ancestors.map(elementOf),
18242
- root
18243
- }),
18244
- splitKeepsIn: (source, continuation, place, root) => getEditorSchema(editor).elementSplitKeepsIn(elementOf(source), elementOf(continuation), {
18245
- continuationAncestors: place.continuationAncestors.map(elementOf),
18246
- continuationIndex: place.continuationIndex,
18247
- root,
18248
- sourceAncestors: place.sourceAncestors.map(elementOf)
18249
- }),
18250
- joinCompares: (key) => joinCompares(getCompiledEditorSchema(editor), key),
18251
- maxChildren: (type, root) => authoredResolveSchemaOf(editor).content(type, root)?.max ?? null,
18252
- now: at,
18253
- oneText,
18254
- ownedRoots: (props) => {
18255
- return getEditorSchema(editor).getElementOwnedRoots(props).map(({ ownership, root }) => ({
18256
- exclusive: ownership === "exclusive",
18993
+ }),
18994
+ slotted: (type, root) => (authoredResolveSchemaOf(editor).content(type, root)?.prefix ?? 0) > 0,
18995
+ declaredIn: (element, ancestors, root) => getEditorSchema(editor).elementDeclaredPropertiesIn(elementOf(element), {
18996
+ ancestors: ancestors.map(elementOf),
18257
18997
  root
18258
- }));
18259
- },
18260
- selectionBefore: selectionPosition === null ? null : {
18261
- position: selectionPosition,
18262
- root: input.selectionBeforeRoot
18263
- },
18264
- schema: tracksPlaces(compiled) ? compiled : null,
18265
- unique: uniquePropertiesOf(compiled),
18266
- standing,
18267
- steps,
18268
- commitWriteId,
18269
- writer
18270
- });
18271
- const map = {
18272
- after,
18273
- indexes: recorded.indexedAfter,
18274
- map: recorded.mapPosition
18275
- };
18276
- const kept = [.../* @__PURE__ */ new Set([...visitRootNames(before.roots), ...recorded.indexedAfter.keys()])].filter((root) => root !== "main" && !byName.has(root));
18277
- const beforeRecords = getValueRecords(before);
18278
- const valueWith = (roots, indexes) => {
18279
- const next = copyFields({}, before, ["records", "roots"]);
18280
- setLazyRoot(next, "children", indexes.get("main") ?? rootIndexOf(before, "children"));
18281
- if (roots.length > 0) {
18282
- const named = {};
18283
- for (const root of roots) {
18284
- const index = indexes.get(root) ?? lazyRootOf(before.roots, root);
18285
- if (index) setLazyRoot(named, root, index);
18286
- else named[root] = valueRoot(before, root);
18287
- }
18288
- next.roots = named;
18289
- }
18290
- return withValueRecords(next, beforeRecords);
18291
- };
18292
- const withdrawn = withdrawable.size > 0 ? orphanedValueRoots(getCompiledEditorSchema(editor), before, valueWith(kept, recorded.indexedAfter), changedRootsOf(recorded.change), createdThenDeleted).filter((root) => withdrawable.has(root)) : [];
18293
- const roots = withdrawn.length > 0 ? kept.filter((root) => !withdrawn.includes(root)) : kept;
18294
- const valueOf = (indexes) => valueWith(roots, indexes);
18295
- const unborn = withdrawn.filter((root) => createdThenDeleted.has(root));
18296
- const deleted = withdrawn.filter((root) => !createdThenDeleted.has(root));
18297
- const born = unborn.length > 0 ? filterDocumentChangeRoots(recorded.change, (root) => !unborn.includes(root)) : recorded.change;
18298
- const recordedChange = deleted.length > 0 ? born.compose(createInternalDocumentChange(/* @__PURE__ */ new Map(), { deleteRoots: deleted }), before) : born;
18299
- const written = valueOf(recorded.indexedAfter);
18300
- const relink = relinkCuts(recordedChange, before, written, (root) => recorded.indexedAfter.get(root) ?? DocumentIndex.fromValue(valueRoot(written, root)));
18301
- const change = relink ? recordedChange.compose(relink.change, before) : recordedChange;
18302
- const indexes = relink ? new Map([...recorded.indexedAfter, ...relink.indexes]) : recorded.indexedAfter;
18303
- const writtenPlain = editing && recorded.writtenPlain;
18304
- const mark = {
18305
- at,
18306
- author: writer,
18307
- change: forced?.changeId ?? changeId,
18308
- ...forced?.inc === void 0 ? {} : { inc: forced.inc }
18309
- };
18310
- const filled = writtenPlain ? null : completeProposed({
18311
- after: valueOf(indexes),
18312
- before,
18313
- change,
18314
- dependencies,
18315
- editor,
18316
- indexes,
18317
- mark,
18318
- standing,
18319
- commitWriteId
18320
- });
18321
- const content = filled ? change.compose(filled.change, before) : change;
18322
- const writtenIndexes = filled?.indexes ?? indexes;
18323
- const accepted = editing && !writtenPlain ? acceptOwn(content, writtenIndexes, dependencies, {
18324
- ...known,
18325
- landed: landedHere
18326
- }) : null;
18327
- const relinkedOwn = accepted && relinkCuts(accepted.change, valueOf(writtenIndexes), valueOf(accepted.indexes), (root) => accepted.indexes.get(root) ?? DocumentIndex.fromValue(valueRoot(valueOf(accepted.indexes), root)), (root) => writtenIndexes.get(root) ?? DocumentIndex.fromValue(valueRoot(before, root)));
18328
- const owned = accepted && relinkedOwn ? {
18329
- change: accepted.change.compose(relinkedOwn.change),
18330
- indexes: new Map([...accepted.indexes, ...relinkedOwn.indexes]),
18331
- landed: accepted.landed
18332
- } : accepted;
18333
- const through = (changes) => (root, position, assoc) => changes.reduce((mapped, later) => (later && getInternalDocumentRootChange(later, root)?.mapPos(mapped, assoc)) ?? mapped, position);
18334
- const mapPosition = (root, position, assoc) => through([
18335
- relink?.change,
18336
- filled?.change,
18337
- owned?.change
18338
- ])(root, recorded.mapPosition(root, position, assoc, false), assoc);
18339
- const staysAfter = 1;
18340
- const record = (draftSelection, root) => {
18341
- const selection = mapSelection(draftSelection, {
18342
- ...map,
18343
- root
18998
+ }),
18999
+ splitKeepsIn: (source, continuation, place, root) => getEditorSchema(editor).elementSplitKeepsIn(elementOf(source), elementOf(continuation), {
19000
+ continuationAncestors: place.continuationAncestors.map(elementOf),
19001
+ continuationIndex: place.continuationIndex,
19002
+ root,
19003
+ sourceAncestors: place.sourceAncestors.map(elementOf)
19004
+ }),
19005
+ joinCompares: (key) => joinCompares(getCompiledEditorSchema(editor), key),
19006
+ maxChildren: (type, root) => authoredResolveSchemaOf(editor).content(type, root)?.max ?? null,
19007
+ now: at,
19008
+ oneText,
19009
+ ownedRoots: (props) => {
19010
+ return getEditorSchema(editor).getElementOwnedRoots(props).map(({ ownership, root }) => ({
19011
+ exclusive: ownership === "exclusive",
19012
+ root
19013
+ }));
19014
+ },
19015
+ selectionBefore: selectionPosition === null ? null : {
19016
+ position: selectionPosition,
19017
+ root: input.selectionBeforeRoot
19018
+ },
19019
+ schema: tracksPlaces(compiled) ? compiled : null,
19020
+ unique: uniquePropertiesOf(compiled),
19021
+ standing,
19022
+ steps,
19023
+ commitWriteId,
19024
+ writer
18344
19025
  });
18345
- const filledSelection = filled ? mapSelection(selection, {
19026
+ const map = {
19027
+ after,
19028
+ indexes: recorded.indexedAfter,
19029
+ map: recorded.mapPosition
19030
+ };
19031
+ const kept = [.../* @__PURE__ */ new Set([...visitRootNames(before.roots), ...recorded.indexedAfter.keys()])].filter((root) => root !== "main" && !byName.has(root));
19032
+ const beforeRecords = getValueRecords(before);
19033
+ const valueWith = (roots, indexes) => {
19034
+ const next = copyFields({}, before, ["records", "roots"]);
19035
+ setLazyRoot(next, "children", indexes.get("main") ?? rootIndexOf(before, "children"));
19036
+ if (roots.length > 0) {
19037
+ const named = {};
19038
+ for (const root of roots) {
19039
+ const index = indexes.get(root) ?? lazyRootOf(before.roots, root);
19040
+ if (index) setLazyRoot(named, root, index);
19041
+ else named[root] = valueRoot(before, root);
19042
+ }
19043
+ next.roots = named;
19044
+ }
19045
+ return withValueRecords(next, beforeRecords);
19046
+ };
19047
+ const withdrawn = withdrawable.size > 0 ? orphanedValueRoots(getCompiledEditorSchema(editor), before, valueWith(kept, recorded.indexedAfter), changedRootsOf(recorded.change), createdThenDeleted).filter((root) => withdrawable.has(root)) : [];
19048
+ const roots = withdrawn.length > 0 ? kept.filter((root) => !withdrawn.includes(root)) : kept;
19049
+ const valueOf = (indexes) => valueWith(roots, indexes);
19050
+ const unborn = withdrawn.filter((root) => createdThenDeleted.has(root));
19051
+ const deleted = withdrawn.filter((root) => !createdThenDeleted.has(root));
19052
+ const born = unborn.length > 0 ? filterDocumentChangeRoots(recorded.change, (root) => !unborn.includes(root)) : recorded.change;
19053
+ const recordedChange = deleted.length > 0 ? born.compose(createInternalDocumentChange(/* @__PURE__ */ new Map(), { deleteRoots: deleted }), before) : born;
19054
+ const written = valueOf(recorded.indexedAfter);
19055
+ const relink = relinkCuts(recordedChange, before, written, (root) => recorded.indexedAfter.get(root) ?? DocumentIndex.fromValue(valueRoot(written, root)));
19056
+ const change = relink ? recordedChange.compose(relink.change, before) : recordedChange;
19057
+ const indexes = relink ? new Map([...recorded.indexedAfter, ...relink.indexes]) : recorded.indexedAfter;
19058
+ const writtenPlain = editing && recorded.writtenPlain;
19059
+ const mark = {
19060
+ at,
19061
+ author: writer,
19062
+ change: forced?.changeId ?? changeId,
19063
+ ...forced?.inc === void 0 ? {} : { inc: forced.inc }
19064
+ };
19065
+ const filled = writtenPlain ? null : completeProposed({
18346
19066
  after: valueOf(indexes),
18347
- indexes: filled.indexes,
18348
- map: through([filled.change]),
18349
- root
18350
- }) : selection;
18351
- return owned ? mapSelection(filledSelection, {
18352
- after: valueOf(writtenIndexes),
18353
- indexes: owned.indexes,
18354
- map: through([owned.change]),
18355
- root
18356
- }, staysAfter) : filledSelection;
18357
- };
18358
- const recordedLater = owned ? content.compose(owned.change, before) : content;
18359
- const recordedIndexes = owned?.indexes ?? writtenIndexes;
18360
- const recordedRecords = [putContexts(restedOn(dependencies.minted(), recordedLater, recordedIndexes)), putLanded([...editing && commitWrite !== void 0 ? [landedOf({
18361
- at,
18362
- change: changeId,
18363
- id: commitWrite
18364
- })] : [], ...owned?.landed ?? []])].reduce(composeRecordOps, ownRecords);
18365
- const deferred = (filled?.deferred ?? []).flatMap((build) => {
18366
- if (!owned || build.path.length === 0) return [build];
18367
- const { from } = getDefined(writtenIndexes.get(build.root)).nodeRange(build.path);
18368
- const rootChange = getInternalDocumentRootChange(owned.change, build.root);
18369
- const start = rootChange ? rootChange.mapPos(from, 1, "after") : from;
18370
- const host = start === null ? null : recordedIndexes.get(build.root)?.nodeStartingAt(start);
18371
- return host && host.from === start && host.kind === "element" ? [{
19067
+ before,
19068
+ change,
19069
+ dependencies,
19070
+ editor,
19071
+ indexes,
19072
+ mark,
19073
+ standing,
19074
+ commitWriteId
19075
+ });
19076
+ const content = filled ? change.compose(filled.change, before) : change;
19077
+ const writtenIndexes = filled?.indexes ?? indexes;
19078
+ const accepted = editing && !writtenPlain ? acceptOwn(content, writtenIndexes, dependencies, {
19079
+ ...known,
19080
+ landed: landedHere
19081
+ }) : null;
19082
+ const relinkedOwn = accepted && relinkCuts(accepted.change, valueOf(writtenIndexes), valueOf(accepted.indexes), (root) => accepted.indexes.get(root) ?? DocumentIndex.fromValue(valueRoot(valueOf(accepted.indexes), root)), (root) => writtenIndexes.get(root) ?? DocumentIndex.fromValue(valueRoot(before, root)));
19083
+ const owned = accepted && relinkedOwn ? {
19084
+ change: accepted.change.compose(relinkedOwn.change),
19085
+ indexes: new Map([...accepted.indexes, ...relinkedOwn.indexes]),
19086
+ landed: accepted.landed
19087
+ } : accepted;
19088
+ const through = (changes) => (root, position, assoc) => changes.reduce((mapped, later) => (later && getInternalDocumentRootChange(later, root)?.mapPos(mapped, assoc)) ?? mapped, position);
19089
+ const mapPosition = (root, position, assoc) => through([
19090
+ relink?.change,
19091
+ filled?.change,
19092
+ owned?.change
19093
+ ])(root, recorded.mapPosition(root, position, assoc, false), assoc);
19094
+ const staysAfter = 1;
19095
+ const record = (draftSelection, root) => {
19096
+ const selection = mapSelection(draftSelection, {
19097
+ ...map,
19098
+ root
19099
+ });
19100
+ const filledSelection = filled ? mapSelection(selection, {
19101
+ after: valueOf(indexes),
19102
+ indexes: filled.indexes,
19103
+ map: through([filled.change]),
19104
+ root
19105
+ }) : selection;
19106
+ return owned ? mapSelection(filledSelection, {
19107
+ after: valueOf(writtenIndexes),
19108
+ indexes: owned.indexes,
19109
+ map: through([owned.change]),
19110
+ root
19111
+ }, staysAfter) : filledSelection;
19112
+ };
19113
+ const recordedLater = owned ? content.compose(owned.change, before) : content;
19114
+ const recordedIndexes = owned?.indexes ?? writtenIndexes;
19115
+ const recordedRecords = [putContexts(restedOn(dependencies.minted(), recordedLater, recordedIndexes)), putLanded([...editing && commitWrite !== void 0 ? [landedOf({
19116
+ at,
19117
+ change: changeId,
19118
+ id: commitWrite
19119
+ })] : [], ...owned?.landed ?? []])].reduce(composeRecordOps, ownRecords);
19120
+ const deferred = (filled?.deferred ?? []).flatMap((build) => {
19121
+ if (!owned || build.path.length === 0) return [build];
19122
+ const { from } = getDefined(writtenIndexes.get(build.root)).nodeRange(build.path);
19123
+ const rootChange = getInternalDocumentRootChange(owned.change, build.root);
19124
+ const start = rootChange ? rootChange.mapPos(from, 1, "after") : from;
19125
+ const host = start === null ? null : recordedIndexes.get(build.root)?.nodeStartingAt(start);
19126
+ return host && host.from === start && host.kind === "element" ? [{
19127
+ ...build,
19128
+ path: host.path
19129
+ }] : [];
19130
+ });
19131
+ const recordedValue = deriveValue(valueOf(recordedIndexes), {}, recordedRecords);
19132
+ const writes = storesSpares(compiled) ? sparesFor(recordedValue, compiled, changedSitesOf(recordedLater, recordedIndexes, before), deferred.map(({ index, ...build }) => ({
18372
19133
  ...build,
18373
- path: host.path
18374
- }] : [];
18375
- });
18376
- const recordedValue = deriveValue(valueOf(recordedIndexes), {}, recordedRecords);
18377
- const writes = storesSpares(compiled) ? sparesFor(recordedValue, compiled, changedSitesOf(recordedLater, recordedIndexes), deferred.map(({ index, ...build }) => ({
18378
- ...build,
18379
- node: framedChild(valueRootIndex(after, build.root), build.path.length === 0 ? null : getDefined(recordedIndexes.get(build.root)).nodeRange(build.path).from, index, String(build.node.type), (position, assoc) => mapPosition(build.root, position, assoc)) ?? build.node,
18380
- writer: owned ? null : mark
18381
- })), spareBlocksOf(recordedValue)) : NO_SPARE_WRITES;
18382
- const spares = writes.containers.length > 0 ? spareWritesChange(writes, recordedIndexes) : null;
18383
- const spared = spares ? recordedLater.compose(spares.change, before) : recordedLater;
18384
- const sparedIndexes = spares?.indexes ?? recordedIndexes;
18385
- const records = composeRecordOps(recordedRecords, writes.records);
18386
- const shown = storesSpares(compiled) ? closeCommandValues({
18387
- before,
18388
- change: spared,
18389
- compiled,
18390
- editing,
18391
- frame: after,
18392
- framed: !!input.projection,
18393
- holders,
18394
- indexes: sparedIndexes,
18395
- peek: (values, read) => ledger.peek(values, read),
18396
- standing,
18397
- storedOf: (edited) => deriveValue(valueOf(edited), {}, records),
18398
- writer: {
18399
- ...mark,
18400
- commitWriteId,
18401
- isOwn: (tag) => tag.change === mark.change
18402
- }
18403
- }) : null;
18404
- const later = shown ? spared.compose(shown.change, before) : spared;
18405
- const indexedAfter = shown?.indexes ?? sparedIndexes;
18406
- const split = splitOneTextRefusal(later, indexedAfter, oneText);
18407
- if (split) throw split;
19134
+ node: framedChild(valueRootIndex(after, build.root), build.path.length === 0 ? null : getDefined(recordedIndexes.get(build.root)).nodeRange(build.path).from, index, String(build.node.type), (position, assoc) => mapPosition(build.root, position, assoc)) ?? build.node,
19135
+ writer: owned ? null : mark
19136
+ })), spareBlocksOf(recordedValue), writer) : NO_SPARE_WRITES;
19137
+ const spares = writes.containers.length > 0 ? spareWritesChange(writes, recordedIndexes) : null;
19138
+ const spared = spares ? recordedLater.compose(spares.change, before) : recordedLater;
19139
+ const sparedIndexes = spares?.indexes ?? recordedIndexes;
19140
+ const records = composeRecordOps(recordedRecords, writes.records);
19141
+ const shown = storesSpares(compiled) ? closeCommandValues({
19142
+ before,
19143
+ change: spared,
19144
+ compiled,
19145
+ editing,
19146
+ frame: after,
19147
+ framed: !!projection,
19148
+ holders,
19149
+ indexes: sparedIndexes,
19150
+ peek: (values, read) => ledger.peek(values, read),
19151
+ standing,
19152
+ storedOf: (edited) => deriveValue(valueOf(edited), {}, records),
19153
+ writer: {
19154
+ ...mark,
19155
+ commitWriteId,
19156
+ isOwn: (tag) => tag.change === mark.change
19157
+ }
19158
+ }) : null;
19159
+ const later = shown ? spared.compose(shown.change, before) : spared;
19160
+ const indexedAfter = shown?.indexes ?? sparedIndexes;
19161
+ const split = splitOneTextRefusal(later, indexedAfter, oneText);
19162
+ if (split) throw split;
19163
+ const selection = record(input.selection, input.selectionRoot);
19164
+ const strike = !editing && !composition && recorded.textStrike && !relink && !filled && !owned && !spares && !shown && [...records.values()].every((set) => set.size === 0) && selection?.kind === "text" && PointApi.equals(selection.anchor, selection.focus) && (selection.anchor.root ?? input.selectionRoot) === recorded.textStrike.root ? recorded.textStrike : null;
19165
+ const onlySetsProperties = (pass) => !pass || [...getInternalDocumentChangeEntries(pass.change)].every(([, root]) => changesOnlyProperties(root));
19166
+ const facts = [
19167
+ relink,
19168
+ filled,
19169
+ owned,
19170
+ spares,
19171
+ shown
19172
+ ].every(onlySetsProperties) ? recorded.facts : void 0;
19173
+ return {
19174
+ anchorChange: (plainAfter) => [
19175
+ filled?.change,
19176
+ owned?.change,
19177
+ spares?.change,
19178
+ shown?.change
19179
+ ].reduce((anchor, next) => next ? anchor.compose(next) : anchor, recorded.anchorChange(plainAfter)),
19180
+ bookmarks: input.bookmarks.map(({ root, selection: bookmark }) => record(bookmark, root)),
19181
+ change: withDocumentChangeRecords(later, records),
19182
+ ...strike ? { deleteGrouping: Object.freeze({
19183
+ blockPath: strike.blockPath,
19184
+ direction: strike.direction,
19185
+ group: `${strike.author}\0${strike.change}`,
19186
+ root: strike.root
19187
+ }) } : {},
19188
+ ...facts ? { facts } : {},
19189
+ indexedAfter,
19190
+ mapPosition,
19191
+ selection
19192
+ };
19193
+ };
19194
+ if (!covered) return recordOn(input.before, input.projection, getValueRecords(after));
19195
+ const { facts: _facts, ...recorded } = recordOn(covered.value, covered.projection, applyRecordOps(getValueRecords(after), getInternalDocumentChangeRecords(covered.change)));
19196
+ const decidedRoots = [...getInternalDocumentChangeEntries(covered.change)].flatMap(([root]) => recorded.indexedAfter.has(root) ? [] : [[root, rootOf(covered.value, root)]]);
18408
19197
  return {
18409
- anchorChange: (plainAfter) => [
18410
- filled?.change,
18411
- owned?.change,
18412
- spares?.change,
18413
- shown?.change
18414
- ].reduce((anchor, next) => next ? anchor.compose(next) : anchor, recorded.anchorChange(plainAfter)),
18415
- bookmarks: input.bookmarks.map(({ root, selection }) => record(selection, root)),
18416
- change: withDocumentChangeRecords(later, records),
18417
- indexedAfter,
18418
- mapPosition,
18419
- selection: record(input.selection, input.selectionRoot)
19198
+ ...recorded,
19199
+ change: covered.change.compose(recorded.change, input.before),
19200
+ historyBoundary: true,
19201
+ indexedAfter: decidedRoots.length === 0 ? recorded.indexedAfter : new Map([...decidedRoots, ...recorded.indexedAfter])
18420
19202
  };
18421
19203
  }));
18422
19204
  }
18423
19205
  });
18424
19206
  };
19207
+ const CONTENT_ORIGINS = /* @__PURE__ */ new Set([
19208
+ "change",
19209
+ "insert-node",
19210
+ "merge",
19211
+ "remove-node",
19212
+ "replace",
19213
+ "slice",
19214
+ "split",
19215
+ "text"
19216
+ ]);
19217
+ const replacesRange = (input, projection, root, from, to) => {
19218
+ const rootChange = getInternalDocumentRootChange(input.change, root);
19219
+ const start = projection.map.toProjected(root, from, "forward");
19220
+ const end = projection.map.toProjected(root, to, "backward");
19221
+ if (!rootChange || start === null || end === null || input.change.createRoots.size > 0 || input.change.deleteRoots.size > 0 || getInternalDocumentChangeRootKeys(input.change).some((at) => at !== root) || !input.steps.some((step) => CONTENT_ORIGINS.has(step.origin))) return false;
19222
+ const low = Math.min(start, end);
19223
+ const high = Math.max(start, end);
19224
+ const shown = projection.indexes.get(root) ?? rootOf(input.before, root);
19225
+ const letters = (at, until) => shown.nodeRangesTouching(at, until).flatMap((entry) => {
19226
+ const first = Math.max(entry.contentFrom, at);
19227
+ const last = Math.min(entry.contentTo, until);
19228
+ return entry.kind === "text" && first < last ? [[first, last]] : [];
19229
+ });
19230
+ const holdsEdge = (at, until) => shown.nodeRangesTouching(at, until).every((entry) => entry.from < low && low < entry.to || entry.from < high && high < entry.to);
19231
+ let away = false;
19232
+ rootChange.iterChangedRanges((fromA, toA) => {
19233
+ away ||= (fromA > high || toA < low) && !holdsEdge(fromA, toA) || letters(fromA, toA).some(([first, last]) => first < low || last > high);
19234
+ });
19235
+ return !away && letters(low, high).every(([first, last]) => isRootChangeRangeReplaced(rootChange, first, last));
19236
+ };
18425
19237
  /** Suggestions recorded as review marks in the document. */
18426
19238
  const authored = (options) => createAuthoredPlugin({ authorId: options.authorId });
18427
19239
  //#endregion