@stll/folio-core 0.75.0 → 0.77.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/dist/ai-edits/headless.d.ts +8 -5
  2. package/dist/ai-edits/headless.js +49 -26
  3. package/dist/ai-edits/pending-suggestions.d.ts +9 -0
  4. package/dist/ai-edits/pending-suggestions.js +13 -3
  5. package/dist/ai-edits/read.js +33 -4
  6. package/dist/ai-edits/table-geometry.js +12 -4
  7. package/dist/ai-edits/types.d.ts +9 -4
  8. package/dist/canonical/batchCommentReferences.js +2 -1
  9. package/dist/canonical/canonicalBatchReview.js +5 -8
  10. package/dist/canonical/canonicalComments.js +8 -2
  11. package/dist/canonical/canonicalCompilerRefusal.d.ts +2 -4
  12. package/dist/canonical/canonicalCompilerRefusal.js +20 -14
  13. package/dist/canonical/canonicalInlineProjection.d.ts +2 -2
  14. package/dist/canonical/canonicalInlineProjection.js +2 -2
  15. package/dist/canonical/canonicalProjectionBlocks.d.ts +10 -1
  16. package/dist/canonical/canonicalPublicOperations.js +214 -107
  17. package/dist/canonical/canonicalSeedContent.d.ts +18 -3
  18. package/dist/canonical/canonicalSeedContent.js +28 -15
  19. package/dist/canonical/canonicalSession.d.ts +22 -12
  20. package/dist/canonical/canonicalSession.js +181 -187
  21. package/dist/controller/canonicalClipboard.d.ts +3 -2
  22. package/dist/controller/canonicalClipboard.js +377 -58
  23. package/dist/controller/canonicalComposition.js +67 -14
  24. package/dist/controller/canonicalContentControlValue.js +7 -7
  25. package/dist/controller/canonicalReview.d.ts +21 -0
  26. package/dist/controller/canonicalReview.js +44 -9
  27. package/dist/controller/canonicalStoryEditor.js +2 -0
  28. package/dist/controller/canonicalStructure.d.ts +1 -2
  29. package/dist/controller/canonicalStructure.js +51 -24
  30. package/dist/controller/fontReadiness.js +50 -23
  31. package/dist/controller/hiddenEditorManager.js +7 -20
  32. package/dist/docx/bulletMarkers.d.ts +8 -0
  33. package/dist/docx/bulletMarkers.js +9 -1
  34. package/dist/docx/canonicalSessionInput.js +25 -11
  35. package/dist/docx/ensureParaIds.d.ts +31 -0
  36. package/dist/docx/ensureParaIds.js +57 -32
  37. package/dist/docx/ensureUniqueControlIds.d.ts +13 -0
  38. package/dist/docx/ensureUniqueControlIds.js +47 -29
  39. package/dist/docx/ensureUniqueRevisionIds.d.ts +13 -0
  40. package/dist/docx/ensureUniqueRevisionIds.js +52 -29
  41. package/dist/docx/importedIdCollisions.js +29 -4
  42. package/dist/docx/server/templatePlan/apply.js +108 -9
  43. package/dist/docx/server/templatePlan/blocks.d.ts +77 -5
  44. package/dist/docx/server/templatePlan/blocks.js +281 -14
  45. package/dist/docx/server/templatePlan/builders.d.ts +22 -1
  46. package/dist/docx/server/templatePlan/builders.js +37 -3
  47. package/dist/docx/server/templatePlan/effects.d.ts +27 -0
  48. package/dist/docx/server/templatePlan/effects.js +188 -0
  49. package/dist/docx/server/templatePlan/emit.d.ts +4 -1
  50. package/dist/docx/server/templatePlan/emit.js +152 -8
  51. package/dist/docx/server/templatePlan/inspect.js +21 -1
  52. package/dist/docx/server/templatePlan/labels.js +16 -1
  53. package/dist/docx/server/templatePlan/plan.d.ts +35 -3
  54. package/dist/docx/server/templatePlan/plan.js +197 -20
  55. package/dist/docx/server/templatePlan/planShape.js +58 -22
  56. package/dist/docx/server/templatePlan/revisions.d.ts +101 -0
  57. package/dist/docx/server/templatePlan/revisions.js +681 -0
  58. package/dist/docx/server/templatePlan/story.d.ts +61 -2
  59. package/dist/docx/server/templatePlan/story.js +175 -13
  60. package/dist/docx/server/templatePlan/types.d.ts +313 -1
  61. package/dist/docx/server/templatePlan/verify.js +175 -12
  62. package/dist/docx/server/templatePlan/xml.d.ts +3 -0
  63. package/dist/docx/server/templatePlan/xml.js +4 -1
  64. package/dist/docx/settingsHeaderFooterUpdate.d.ts +1 -1
  65. package/dist/docx/tableGridXml.d.ts +3 -7
  66. package/dist/docx/tableGridXml.js +5 -13
  67. package/dist/layout-bridge/convert/footnoteLayout.js +34 -8
  68. package/dist/prosemirror/canonicalMarkupDocument.d.ts +20 -0
  69. package/dist/prosemirror/canonicalMarkupDocument.js +73 -0
  70. package/dist/prosemirror/canonicalTableCommands.d.ts +1 -1
  71. package/dist/prosemirror/canonicalTableCommands.js +1 -3
  72. package/dist/prosemirror/commands/comments.d.ts +6 -234
  73. package/dist/prosemirror/commands/comments.js +5 -2464
  74. package/dist/prosemirror/commands/index.d.ts +4 -2
  75. package/dist/prosemirror/commands/index.js +4 -2
  76. package/dist/prosemirror/conversion/markupViewSource.d.ts +17 -0
  77. package/dist/prosemirror/conversion/markupViewSource.js +11 -0
  78. package/dist/prosemirror/conversion/toProseDoc.d.ts +3 -0
  79. package/dist/prosemirror/conversion/toProseDoc.js +31 -14
  80. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +6 -8
  81. package/dist/prosemirror/hyperlinkRemoval.d.ts +11 -8
  82. package/dist/prosemirror/hyperlinkRemoval.js +24 -15
  83. package/dist/prosemirror/independentMarkupProjection.d.ts +27 -0
  84. package/dist/prosemirror/independentMarkupProjection.js +147 -0
  85. package/dist/prosemirror/markupViewNotes.d.ts +1 -1
  86. package/dist/prosemirror/markupViewNotes.js +24 -27
  87. package/dist/prosemirror/markupViewPositionMap.d.ts +16 -0
  88. package/dist/prosemirror/markupViewPositionMap.js +316 -0
  89. package/dist/prosemirror/markupViewProjection.d.ts +3 -46
  90. package/dist/prosemirror/markupViewProjection.js +90 -17
  91. package/dist/prosemirror/paraIds.d.ts +1 -14
  92. package/dist/prosemirror/paraIds.js +1 -14
  93. package/dist/prosemirror/paragraphMarkJoin.d.ts +0 -16
  94. package/dist/prosemirror/paragraphMarkJoin.js +3 -46
  95. package/dist/prosemirror/projectionReview.d.ts +49 -0
  96. package/dist/prosemirror/projectionReview.js +292 -0
  97. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -13
  98. package/dist/prosemirror/rebaseParagraphRunFormatting.js +1 -16
  99. package/dist/prosemirror/replacedAnnotations.d.ts +6 -83
  100. package/dist/prosemirror/replacedAnnotations.js +11 -203
  101. package/dist/prosemirror/revisionCarriers.d.ts +9 -1
  102. package/dist/prosemirror/revisionCarriers.js +15 -1
  103. package/dist/prosemirror/revisionRangeQueries.d.ts +32 -0
  104. package/dist/prosemirror/revisionRangeQueries.js +76 -0
  105. package/dist/prosemirror/runFormattingMarkNames.d.ts +1 -1
  106. package/dist/prosemirror/runFormattingMarkNames.js +1 -1
  107. package/dist/prosemirror/styles/styleResolver.d.ts +1 -0
  108. package/dist/prosemirror/styles/styleResolver.js +4 -1
  109. package/dist/prosemirror/suggestionQueries.d.ts +114 -0
  110. package/dist/prosemirror/suggestionQueries.js +320 -0
  111. package/dist/prosemirror/tableGridMutation.d.ts +1 -16
  112. package/dist/prosemirror/tableGridMutation.js +1 -78
  113. package/dist/prosemirror/tableRowRevisionOwnership.d.ts +18 -0
  114. package/dist/prosemirror/tableRowRevisionOwnership.js +7 -0
  115. package/dist/prosemirror/utils/extractTrackedChanges.js +14 -4
  116. package/dist/server.d.ts +2 -2
  117. package/dist/types/canonicalCapabilities.d.ts +4 -35
  118. package/dist/types/canonicalCapabilities.js +4 -33
  119. package/package.json +2 -2
  120. package/dist/internal/headlessRevisionResolutionGuard.d.ts +0 -3
  121. package/dist/internal/headlessRevisionResolutionGuard.js +0 -18
  122. package/dist/internal/revisionResolutionEdits.d.ts +0 -11
  123. package/dist/internal/revisionResolutionEdits.js +0 -18
  124. package/dist/internal/revisionResolutionInline.d.ts +0 -24
  125. package/dist/internal/revisionResolutionInline.js +0 -302
  126. package/dist/internal/revisionResolutionStep.d.ts +0 -32
  127. package/dist/internal/revisionResolutionStep.js +0 -282
  128. package/dist/internal/revisionResolutionTracking.d.ts +0 -9
  129. package/dist/internal/revisionResolutionTracking.js +0 -124
  130. package/dist/internal/wholeStoryRevisionResolution.d.ts +0 -56
  131. package/dist/internal/wholeStoryRevisionResolution.js +0 -783
  132. package/dist/prosemirror/commands/resolveAllTableChanges.d.ts +0 -38
  133. package/dist/prosemirror/commands/resolveAllTableChanges.js +0 -642
  134. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.d.ts +0 -13
  135. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.js +0 -45
  136. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +0 -18
  137. package/dist/prosemirror/commands/tableCellMergeResolution.js +0 -207
  138. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +0 -60
  139. package/dist/prosemirror/commands/tableMergeFoldDecisions.js +0 -78
  140. package/dist/prosemirror/rejoinRunCarriers.d.ts +0 -42
  141. package/dist/prosemirror/rejoinRunCarriers.js +0 -65
  142. package/dist/prosemirror/runPropertyChangeResolution.d.ts +0 -15
  143. package/dist/prosemirror/runPropertyChangeResolution.js +0 -34
@@ -1,2464 +1,5 @@
1
- import { sameStatedParagraphNumbering as sameStatedParagraphNumbering$1 } from "../../docx/numberingReference.js";
2
- import { markParagraphPropertySourceTransfers } from "../../docx/paragraphPropertySource.js";
3
- import { RevisionResolutionStep } from "../../internal/revisionResolutionStep.js";
4
- import { finalRevisionParagraphRanges } from "../../internal/revisionResolutionTracking.js";
5
- import { deleteTextBoxesAnchoredAt, droppedTextBoxAnchorIds, moveTextBoxesPastNextParagraph } from "../anchoredTextBoxes.js";
6
- import { expectCommentMarkAttrs, expectFieldAttrs, expectParagraphAttrs, expectRunPropertyChangeMarkAttrs, expectTableAttrs, expectTableCellAttrs, expectTableRowAttrs, expectTrackedChangeMarkAttrs } from "../attrs/index.js";
7
- import { removeCommentAnchors, retireThreadsResolvedAway } from "../commentRecords.js";
8
- import { addedBreakCarrierBefore, finalParagraphsOf, paragraphEndsItsContainer } from "../containerFinalParagraph.js";
9
- import { enclosingRevisionIds, resolutionRemovesControl, withoutResolvedEnclosures } from "../contentControlRevisions.js";
10
- import { copyOriginBoundaryAttrsAfterResolution } from "../copyOriginResolution.js";
11
- import { resolveEmptyFieldResultRuns } from "../emptyFieldResultRuns.js";
12
- import { JOINED_RUNS_RESTYLED_META } from "../extensions/features/JoinedRunStyleExtension.js";
13
- import "../extensions/nodes/SdtExtension.js";
14
- import { canonicalFieldNode } from "../fieldRepresentation.js";
15
- import { isBlockBoundaryNode, normalizeKeptRangeBoundaries, paragraphRemainsOf, removeResolvedSubtree, revisionLayerRemovesContent } from "../keptRangeBoundaries.js";
16
- import { lockedControlSpans, lockedControlViolationOfTransform } from "../lockedControls.js";
17
- import { resolveStateStory } from "../markupViewProjection.js";
18
- import { requestDeterministicParaIds } from "../paraIds.js";
19
- import { markChangedParagraphRanges, markStructuralChange, markTrackedSectionEndpointRemoval } from "../paragraphChangeTrackerMeta.js";
20
- import { joinAtParagraphMark } from "../paragraphMarkJoin.js";
21
- import { carryParagraphProperties, paragraphLeftAfter } from "../paragraphPropertyCarry.js";
22
- import { getDocumentNumbering } from "../plugins/documentNumbering.js";
23
- import { getDocumentStyleResolver } from "../plugins/documentStyleState.js";
24
- import { resolvedPreservedXmlAttrs } from "../preservedXmlReview.js";
25
- import { setParagraphAttrsWithRebasedRunFormatting } from "../rebaseParagraphRunFormatting.js";
26
- import { rejoinRunsAt } from "../rejoinRunCarriers.js";
27
- import { resolvedCommentPoints } from "../replacedAnnotations.js";
28
- import { getFolioNodeRevisionCarriers, nodePropertyRevisionSites } from "../revisionCarriers.js";
29
- import { RUN_FORMATTING_MARK_NAMES } from "../runFormattingMarkNames.js";
30
- import { rejectedRunFormatting } from "../runPropertyChangeResolution.js";
31
- import { paragraphRunStyleContextAt } from "../runStyleFormatting.js";
32
- import { sectionRecordCopyPositions } from "../sectionCarrier.js";
33
- import { getTableCellMergeChange } from "../tableCellMergeRevision.js";
34
- import { isTableCellRetainedInReviewView } from "../tableCellRevisionVisibility.js";
35
- import { deleteTableRowAt, markRowEmptiedInBatch, reconcileOmittedGridSlots, reconcileTableGridAfterColumnRemoval, removeRowsWithoutCellsAfterBatch, rowHoldsNoCells } from "../tableGridMutation.js";
36
- import { runInCellPending, runParagraphIntoTable } from "../tableRunIn.js";
37
- import { retainedTrackedRevisionMark, trackedRevisionPathOf } from "../trackedRevisionPath.js";
38
- import { extractTrackedChanges } from "../utils/extractTrackedChanges.js";
39
- import { paragraphContentOf } from "../zeroWidthAnchors.js";
40
- import { hasSerializableParagraphPropertyChange, paragraphPropertiesSnapshot } from "./propertyChangeScope.js";
41
- import { resolveNodePropertyChangeAttrs } from "./resolveNodePropertyChangeAttrs.js";
42
- import { resolveParagraphChangeAttrs } from "./resolveParagraphProperties.js";
43
- import { hasMatchingCollapsedTableCellMerge, resolveCollapsedTableCellMerge, resolveVisibleTableCellMerge } from "./tableCellMergeResolution.js";
44
- import { panic } from "better-result";
45
- import { PARAGRAPH_MARK_CHANGE_KINDS, REVIEW_CARRIERS } from "@stll/docx-core/model";
46
- import { paragraphMarkOutcome } from "@stll/docx-core/ops";
47
- import { TableMap } from "prosemirror-tables";
48
- import { Fragment } from "prosemirror-model";
49
- import { Mapping } from "prosemirror-transform";
50
- import { closeHistory } from "prosemirror-history";
51
- // src/prosemirror/commands/comments.ts
52
- /**
53
- * Comment and Track Changes Commands
54
- *
55
- * PM commands for adding/removing comments and accepting/rejecting tracked changes.
56
- */
57
- /**
58
- * Add a comment mark to the current selection.
59
- */
60
- function addCommentMark(commentId) {
61
- return (state, dispatch) => {
62
- const { from, to, empty } = state.selection;
63
- if (empty) return false;
64
- const commentType = state.schema.marks["comment"];
65
- if (!commentType) return false;
66
- if (dispatch) dispatch(state.tr.addMark(from, to, commentType.create({ commentId })));
67
- return true;
68
- };
69
- }
70
- /**
71
- * Remove a comment mark by ID from the entire document.
72
- */
73
- function removeCommentMark(commentId) {
74
- return (state, dispatch) => {
75
- const commentType = state.schema.marks["comment"];
76
- if (!commentType) return false;
77
- if (dispatch) {
78
- const tr = state.tr;
79
- state.doc.descendants((node, pos) => {
80
- if (node.isText) {
81
- for (const mark of node.marks) if (mark.type === commentType && mark.attrs["commentId"] === commentId) tr.removeMark(pos, pos + node.nodeSize, mark);
82
- }
83
- });
84
- if (tr.steps.length > 0) dispatch(tr);
85
- }
86
- return true;
87
- };
88
- }
89
- /**
90
- * What every review resolution does before it is dispatched: it retires the
91
- * comment threads it left without an anchor, and it is an undo step of its
92
- * own, never merged into the edit it resolves.
93
- */
94
- const finishResolution = (state, tr) => {
95
- retireThreadsResolvedAway(state, tr);
96
- closeHistory(tr);
97
- };
98
- const keptIn = (range) => range.removals.flatMap(({ kept }) => kept);
99
- function resolveChangeUnguarded(from, to, mode, revisionIds) {
100
- return (state, dispatch) => {
101
- const insertionType = state.schema.marks["insertion"];
102
- const deletionType = state.schema.marks["deletion"];
103
- const styleResolver = getDocumentStyleResolver(state);
104
- const numbering = getDocumentNumbering(state);
105
- const keepType = mode === "accept" ? insertionType : deletionType;
106
- const removeType = mode === "accept" ? deletionType : insertionType;
107
- const revisionSet = revisionIds === void 0 ? null : new Set(revisionIds);
108
- const removeKeptMarksInBulk = revisionSet === null && keepType !== void 0;
109
- const matchesRevision = (mark) => revisionSet === null || typeof mark.attrs["revisionId"] === "number" && revisionSet.has(mark.attrs["revisionId"]);
110
- if (dispatch) {
111
- const points = mode === "accept" ? resolvedCommentPoints({
112
- doc: state.doc,
113
- retiresStructure: (node, position) => {
114
- if (node.type.name === "paragraph") return collectPPrMarkOp(node, position, from, to, mode, revisionSet)?.action === "join";
115
- if (!rangeCoversNode(from, to, position, node)) return false;
116
- if (node.type.name === "tableRow") return collectTableRowStructuralOp(node, position, mode, revisionSet)?.action === "remove";
117
- return collectTableCellStructuralOps(node, position, mode, revisionSet).some((op) => op.type === "membership" && op.action === "remove");
118
- },
119
- removes: (node, position) => position >= from && position + node.nodeSize <= to && node.marks.some((mark) => mark.type === removeType && matchesRevision(mark))
120
- }) : /* @__PURE__ */ new Map();
121
- const tr = state.tr;
122
- tr.setMeta(JOINED_RUNS_RESTYLED_META, true);
123
- /** Content this resolution takes out, and what each removal keeps. */
124
- const deleteRanges = [];
125
- /** The boundaries removed content left standing, for the range repair. */
126
- const keptBoundaries = /* @__PURE__ */ new Set();
127
- /** What this resolution resolves, for what removed content keeps. */
128
- const selection = {
129
- mode,
130
- resolves: (revisionId) => revisionSet === null || revisionSet.has(revisionId)
131
- };
132
- const removeRange = (rangeFrom, rangeTo, removed) => {
133
- deleteRanges.push({
134
- from: rangeFrom,
135
- to: rangeTo,
136
- removals: [removed]
137
- });
138
- };
139
- const resolveCopyOriginAttrs = (source, position) => {
140
- const current = tr.doc.nodeAt(position);
141
- if (!current) return;
142
- const attrs = copyOriginBoundaryAttrsAfterResolution({
143
- source,
144
- current,
145
- baseAttrs: current.attrs,
146
- selection
147
- });
148
- if (attrs === null) panic("A copied boundary owner cannot be rejected outside removal.");
149
- if (attrs !== current.attrs) tr.setNodeMarkup(position, void 0, attrs);
150
- };
151
- /** Where resolved inline content began and ended, in `state.doc`. */
152
- const resolvedBoundaries = [];
153
- const pPrMarkOps = [];
154
- const tableRowStructuralOps = [];
155
- const tableCellStructuralOps = [];
156
- let removedSectionEndpointCount = 0;
157
- const removedSectionReferences = [];
158
- const countedSectionEndpoints = /* @__PURE__ */ new Set();
159
- const countRemovedSectionEndpoint = (paragraph) => {
160
- if (!ownsSectionEndpoint(paragraph) || countedSectionEndpoints.has(paragraph)) return;
161
- countedSectionEndpoints.add(paragraph);
162
- removedSectionEndpointCount++;
163
- removedSectionReferences.push(...sectionReferencesOf(paragraph));
164
- };
165
- const carryRestoredProperties = (position) => {
166
- if (mode !== "reject" || revisionSet === null) return;
167
- const source = tr.doc.nodeAt(position);
168
- const mark = source ? expectParagraphAttrs(source).pPrMark : null;
169
- if (!source || mark?.kind !== "del" && mark?.kind !== "moveFrom" || revisionSet.has(mark.info.id)) return;
170
- const survivor = paragraphLeftAfter({
171
- doc: tr.doc,
172
- paragraphPos: position
173
- });
174
- if (survivor === null) return;
175
- carryParagraphProperties({
176
- tr,
177
- position: survivor,
178
- source,
179
- styleResolver,
180
- numbering,
181
- revision: mark.info
182
- });
183
- };
184
- state.doc.nodesBetween(from, to, (node, pos) => {
185
- if (node.type.name === "paragraph") {
186
- const op = collectPPrMarkOp(node, pos, from, to, mode, revisionSet);
187
- if (op) pPrMarkOps.push(op);
188
- const boundaryCovered = rangeCoversParagraphBoundary(from, to, pos, node);
189
- const nextAttrs = resolveParagraphChangeAttrs({
190
- node,
191
- boundaryCovered,
192
- mode,
193
- revisionSet,
194
- styleResolver,
195
- numbering
196
- });
197
- if (nextAttrs) {
198
- if (nextAttrs["_sectionProperties"] == null) countRemovedSectionEndpoint(node);
199
- if (nextAttrs["styleId"] !== node.attrs["styleId"] && styleResolver) setParagraphAttrsWithRebasedRunFormatting({
200
- nextAttrs,
201
- paragraphPosition: pos,
202
- styleResolver,
203
- tr
204
- });
205
- else tr.setNodeMarkup(pos, void 0, nextAttrs);
206
- carryRestoredProperties(pos);
207
- }
208
- return true;
209
- }
210
- if (node.type.name === "tableRow" && rangeCoversNode(from, to, pos, node)) {
211
- const op = collectTableRowStructuralOp(node, pos, mode, revisionSet);
212
- if (op) tableRowStructuralOps.push(op);
213
- }
214
- if ((node.type.name === "tableCell" || node.type.name === "tableHeader") && rangeCoversNode(from, to, pos, node)) tableCellStructuralOps.push(...collectTableCellStructuralOps(node, pos, mode, revisionSet));
215
- const nodeAttrSites = nodePropertyRevisionSites(node.type.name).filter((site) => site.resolution === "node-attrs");
216
- if (nodeAttrSites.length > 0) {
217
- if (rangeCoversNode(from, to, pos, node)) for (const site of nodeAttrSites) {
218
- const nextAttrs = resolveNodePropertyChangeAttrs({
219
- node: tr.doc.nodeAt(pos) ?? node,
220
- site,
221
- mode,
222
- revisionSet
223
- });
224
- if (nextAttrs) {
225
- tr.setNodeMarkup(pos, void 0, nextAttrs);
226
- markStructuralChange(tr);
227
- }
228
- }
229
- return true;
230
- }
231
- if (!node.isInline) return true;
232
- const nodeEnd = pos + node.nodeSize;
233
- const rangeFrom = Math.max(from, pos);
234
- const rangeTo = Math.min(to, nodeEnd);
235
- if (node.type.name === "sdt") {
236
- if (!rangeCoversNode(from, to, pos, node)) return true;
237
- const resolvesRevision = (revisionId) => revisionSet === null || revisionSet.has(revisionId);
238
- if (resolutionRemovesControl({
239
- control: node,
240
- removeType,
241
- resolves: resolvesRevision
242
- })) {
243
- removeRange(pos, nodeEnd, removeResolvedSubtree(node, selection));
244
- return false;
245
- }
246
- const released = withoutResolvedEnclosures(node, resolvesRevision);
247
- if (released) tr.setNodeMarkup(pos, void 0, released);
248
- return true;
249
- }
250
- const runPropertyChangeMark = node.marks.find((mark) => mark.type.name === "runPropertyChange");
251
- const removesNode = removeType !== void 0 && node.marks.some((mark) => mark.type === removeType && matchesRevision(mark));
252
- if (removesNode || runPropertyChangeMark !== void 0 || node.marks.some((mark) => (mark.type === insertionType || mark.type === deletionType) && matchesRevision(mark))) resolvedBoundaries.push(rangeFrom, rangeTo);
253
- if (runPropertyChangeMark) resolveRunPropertyChange({
254
- tr,
255
- node,
256
- from: rangeFrom,
257
- to: rangeTo,
258
- mark: runPropertyChangeMark,
259
- mode,
260
- revisionSet,
261
- styleResolver
262
- });
263
- const nestedMark = node.marks.find((mark) => (mark.type === insertionType || mark.type === deletionType) && (expectTrackedChangeMarkAttrs(mark)._docxRevisionAncestors?.length ?? 0) > 0);
264
- if (nestedMark) {
265
- const path = trackedRevisionPathOf(nestedMark);
266
- const selected = (layer) => revisionSet === null || revisionSet.has(layer.revisionId);
267
- let nestedContentRemoved = false;
268
- if (path.some(selected)) {
269
- if (path.some((layer) => selected(layer) && revisionLayerRemovesContent(layer, mode))) {
270
- removeRange(rangeFrom, rangeTo, removeResolvedSubtree(node, selection));
271
- nestedContentRemoved = true;
272
- if (!node.isLeaf) return false;
273
- } else {
274
- tr.removeMark(rangeFrom, rangeTo, nestedMark);
275
- const retained = retainedTrackedRevisionMark(nestedMark, (layer) => !selected(layer));
276
- if (retained) tr.addMark(rangeFrom, rangeTo, retained);
277
- }
278
- }
279
- const current = tr.doc.nodeAt(pos);
280
- if (current) {
281
- const attrs = resolvedPreservedXmlAttrs(node, current.marks);
282
- if (attrs !== node.attrs) tr.setNodeMarkup(pos, void 0, attrs);
283
- }
284
- if (!nestedContentRemoved) resolveCopyOriginAttrs(node, pos);
285
- return true;
286
- }
287
- if (removesNode) {
288
- removeRange(rangeFrom, rangeTo, removeResolvedSubtree(node, selection));
289
- if (!node.isLeaf) return false;
290
- }
291
- if (!removesNode && keepType && node.marks.some((mark) => mark.type === keepType && matchesRevision(mark))) {
292
- const retained = node.marks.filter((mark) => !(mark.type === keepType && matchesRevision(mark)));
293
- const attrs = resolvedPreservedXmlAttrs(node, retained);
294
- if (attrs !== node.attrs) tr.setNodeMarkup(pos, void 0, attrs);
295
- }
296
- if (!removeKeptMarksInBulk) {
297
- for (const mark of node.marks) if (keepType && mark.type === keepType && matchesRevision(mark)) tr.removeMark(rangeFrom, rangeTo, mark);
298
- }
299
- if (!removesNode) resolveCopyOriginAttrs(node, pos);
300
- return true;
301
- });
302
- if (removeKeptMarksInBulk) tr.removeMark(from, to, keepType);
303
- let rangesToDelete = deleteRanges;
304
- if (revisionSet === null) {
305
- const coalescedDeleteRanges = [];
306
- for (const range of deleteRanges) {
307
- const previous = coalescedDeleteRanges.at(-1);
308
- if (previous && range.from <= previous.to) {
309
- previous.to = Math.max(previous.to, range.to);
310
- previous.removals = [...previous.removals, ...range.removals];
311
- continue;
312
- }
313
- coalescedDeleteRanges.push({ ...range });
314
- }
315
- rangesToDelete = coalescedDeleteRanges;
316
- }
317
- for (const range of rangesToDelete.toReversed()) {
318
- const start = tr.doc.resolve(range.from);
319
- const field = start.parent;
320
- if (keptIn(range).length === 0 && field.type.name === "structuredField" && start.parentOffset === 0 && range.to === start.end()) {
321
- const position = start.before();
322
- const empty = canonicalFieldNode(field.copy(Fragment.empty));
323
- tr.replaceWith(position, position + field.nodeSize, empty);
324
- continue;
325
- }
326
- const kept = keptIn(range);
327
- for (const boundary of kept) keptBoundaries.add(boundary);
328
- if (kept.length === 0) tr.delete(range.from, range.to);
329
- else tr.replaceWith(range.from, range.to, kept);
330
- }
331
- if (deleteTextBoxesAnchoredAt(tr, droppedTextBoxAnchorIds(state.doc, tr.doc))) markStructuralChange(tr);
332
- const standingAt = (position) => {
333
- const mapped = tr.mapping.mapResult(position, 1);
334
- return mapped.deletedAcross ? null : mapped.pos;
335
- };
336
- tableRowStructuralOps.sort((left, right) => right.rowPos - left.rowPos);
337
- let resolvedTableRowStructure = false;
338
- for (const op of tableRowStructuralOps) {
339
- const mappedPos = standingAt(op.rowPos);
340
- if (mappedPos === null) continue;
341
- const row = tr.doc.nodeAt(mappedPos);
342
- if (!row || row.type.name !== "tableRow") continue;
343
- if (op.action === "clear") {
344
- tr.setNodeAttribute(mappedPos, op.attrName, null);
345
- clearTableRowContentMarks({
346
- tr,
347
- rowPos: mappedPos,
348
- markType: keepType,
349
- revision: op.revision
350
- });
351
- resolvedTableRowStructure = true;
352
- continue;
353
- }
354
- deleteTableRowAt(tr, mappedPos);
355
- resolvedTableRowStructure = true;
356
- }
357
- if (resolvedTableRowStructure) markStructuralChange(tr);
358
- tableCellStructuralOps.sort((left, right) => right.cellPos - left.cellPos);
359
- let resolvedTableCellStructure = false;
360
- let failedTableCellMergeResolution = false;
361
- const emptiedTables = { pending: false };
362
- for (const op of tableCellStructuralOps) {
363
- const mappedPos = standingAt(op.cellPos);
364
- if (mappedPos === null) continue;
365
- const cell = tr.doc.nodeAt(mappedPos);
366
- if (!cell || cell.type.name !== "tableCell" && cell.type.name !== "tableHeader") continue;
367
- if (op.type === "merge") {
368
- const resolved = op.source === "collapsed" ? resolveCollapsedTableCellMerge(tr, mappedPos, op.mode, op.revisionSet) : resolveVisibleTableCellMerge({
369
- tr,
370
- cellPos: mappedPos,
371
- mode: op.mode,
372
- revisionSet: op.revisionSet
373
- });
374
- if (!resolved) {
375
- failedTableCellMergeResolution = true;
376
- break;
377
- }
378
- resolvedTableCellStructure ||= resolved;
379
- continue;
380
- }
381
- if (op.action === "clear") {
382
- tr.setNodeAttribute(mappedPos, "cellMarker", null);
383
- resolvedTableCellStructure = true;
384
- continue;
385
- }
386
- deleteTableCellAt(tr, mappedPos, emptiedTables);
387
- resolvedTableCellStructure = true;
388
- }
389
- if (failedTableCellMergeResolution) return false;
390
- removeRowsWithoutCellsAfterBatch(tr, emptiedTables);
391
- if (resolvedTableCellStructure) markStructuralChange(tr);
392
- pPrMarkOps.sort((a, b) => b.paragraphPos - a.paragraphPos);
393
- const pendingTables = [];
394
- state.doc.descendants((node, position) => {
395
- if (node.type.spec["tableRole"] === "table" && runInCellPending(node)) pendingTables.push(position);
396
- return !node.isTextblock;
397
- });
398
- if (pPrMarkOps.some(({ action }) => action === "join")) for (const position of sectionRecordCopyPositions(tr.doc)) tr.setNodeAttribute(position, "_sectionProperties", null);
399
- const joinSeams = [];
400
- const joinedParagraphs = [];
401
- for (const op of pPrMarkOps) {
402
- const mappedPos = standingAt(op.paragraphPos);
403
- if (mappedPos === null) continue;
404
- const paragraph = tr.doc.nodeAt(mappedPos);
405
- if (!paragraph || paragraph.type.name !== "paragraph") continue;
406
- if (op.action === "clear") {
407
- tr.setNodeAttribute(mappedPos, "pPrMark", null);
408
- continue;
409
- }
410
- if (op.action === "settle") {
411
- tr.setNodeAttribute(mappedPos, "pPrMark", op.mark ?? null);
412
- continue;
413
- }
414
- if (moveTextBoxesPastNextParagraph(tr, mappedPos)) markStructuralChange(tr);
415
- let nextPos = mappedPos + paragraph.nodeSize;
416
- const boundaries = [];
417
- while (nextPos < tr.doc.content.size) {
418
- const boundary = tr.doc.nodeAt(nextPos);
419
- if (boundary !== null && boundary.attrs["pPrMark"] == null && rejectionRemovesWholeNode(boundary, {
420
- mode,
421
- resolves: (revisionId) => revisionSet?.has(revisionId) === true
422
- }) && !endsItsContainer(tr.doc.resolve(nextPos))) {
423
- tr.delete(nextPos, nextPos + boundary.nodeSize);
424
- continue;
425
- }
426
- if (boundary === null || !isBlockBoundaryNode(boundary)) break;
427
- boundaries.push(boundary);
428
- nextPos += boundary.nodeSize;
429
- }
430
- const nextNode = nextPos < tr.doc.content.size ? tr.doc.nodeAt(nextPos) : null;
431
- const joinable = nextNode?.type.name === paragraph.type.name;
432
- let follows = "nothing";
433
- if (joinable) follows = "paragraph";
434
- else if (nextNode?.type.spec["tableRole"] === "table") follows = "table";
435
- else if (nextNode !== null && nextNode.type.name !== "textBox") follows = "block";
436
- const resolved = tr.doc.resolve(mappedPos);
437
- const preceding = resolved.parent.maybeChild(resolved.index() - 1);
438
- const retainedBoundaries = paragraphRemainsOf(paragraph);
439
- const outcome = paragraphMarkOutcome({
440
- follows,
441
- holdsContent: paragraphContentOf(paragraph),
442
- markWasAdded: op.markWasAdded,
443
- containerStillEndsWithParagraph: follows !== "nothing" ? resolved.parent.lastChild?.type.name === "paragraph" : preceding?.type.name === "paragraph" || preceding !== void 0 && resolved.parent.type.name === "blockSdt",
444
- followingTableCanReceiveRunIn: follows === "table" && boundaries.length === 0 && !pendingTables.some((position) => tr.mapping.map(position) === nextPos) && !ownsSectionEndpoint(paragraph),
445
- needsFollowingCommentHost: follows === "table" && preceding?.type.name !== "paragraph" && retainedBoundaries.length > 0
446
- });
447
- const ranIn = outcome.kind === "run-in" ? runParagraphIntoTable({
448
- tr,
449
- paragraphPos: mappedPos,
450
- styleResolver
451
- }) : null;
452
- if (ranIn) {
453
- tr.setMeta(JOINED_RUNS_RESTYLED_META, true);
454
- markParagraphPropertySourceTransfers(tr, [ranIn.transfer]);
455
- continue;
456
- }
457
- if (!joinable) {
458
- const remains = outcome.kind === "remove" ? paragraphRemainsOf(paragraph) : null;
459
- const toPrevious = remains ?? [];
460
- if (remains !== null && (toPrevious.length === 0 || preceding?.type.name === "paragraph")) {
461
- countRemovedSectionEndpoint(paragraph);
462
- tr.delete(mappedPos, mappedPos + paragraph.nodeSize);
463
- if (toPrevious.length > 0) tr.insert(mappedPos - 1, toPrevious);
464
- continue;
465
- }
466
- tr.setNodeAttribute(mappedPos, "pPrMark", null);
467
- if (op.markWasAdded && ownsSectionEndpoint(paragraph)) {
468
- countRemovedSectionEndpoint(paragraph);
469
- tr.setNodeAttribute(mappedPos, "_sectionProperties", null);
470
- }
471
- continue;
472
- }
473
- try {
474
- const destination = tr.doc.nodeAt(nextPos);
475
- const next = destination?.type.name === "paragraph" ? destination : nextNode;
476
- const displaced = suggestedBreaksAJoinDisplaces(paragraph, next);
477
- joinAtParagraphMark({
478
- tr,
479
- paragraphPos: mappedPos,
480
- paragraph,
481
- next,
482
- styleResolver
483
- });
484
- joinSeams.push({
485
- position: mappedPos + 1 + paragraph.content.size,
486
- step: tr.steps.length
487
- });
488
- joinedParagraphs.push({
489
- position: mappedPos,
490
- step: tr.steps.length,
491
- displaced
492
- });
493
- countRemovedSectionEndpoint(paragraph);
494
- } catch {
495
- continue;
496
- }
497
- if (op.markWasAdded) carryRestoredProperties(mappedPos);
498
- }
499
- if (!placeSuggestedBreaksOfJoins(tr, joinedParagraphs)) return false;
500
- if (removedSectionEndpointCount > 0) markTrackedSectionEndpointRemoval(tr, {
501
- sourceDoc: state.doc,
502
- removedEndpointCount: removedSectionEndpointCount,
503
- removedReferences: removedSectionReferences
504
- });
505
- if (!terminalTableDeletionIsPending(tr)) resolveTerminalTableReviewCarrier(tr, mode);
506
- const seams = new Set(joinSeams.map(({ position, step }) => tr.mapping.slice(step).map(position)));
507
- rejoinRunsAt({
508
- tr,
509
- boundaries: resolvedBoundaries.map((position) => tr.mapping.map(position)).filter((position) => !seams.has(position)),
510
- styleResolver
511
- });
512
- const resolvedFields = [];
513
- tr.doc.descendants((node, position) => {
514
- const canonical = canonicalFieldNode(node);
515
- if (canonical !== node) resolvedFields.push({
516
- node: canonical,
517
- position
518
- });
519
- });
520
- for (const { node, position } of resolvedFields.toReversed()) {
521
- const field = tr.doc.nodeAt(position);
522
- if (!field) continue;
523
- if (field.type === node.type) tr.setNodeMarkup(position, void 0, node.attrs, node.marks);
524
- else tr.replaceWith(position, position + field.nodeSize, node);
525
- }
526
- if (points.size > 0) {
527
- const doomed = new Set(points.keys());
528
- removeCommentAnchors(tr, doomed);
529
- }
530
- normalizeKeptRangeBoundaries(tr, keptBoundaries);
531
- finishResolution(state, tr);
532
- if (tr.steps.length > 0) dispatch(tr);
533
- }
534
- return true;
535
- };
536
- }
537
- /**
538
- * The receiver belongs to the deleted terminal table, not every revision in
539
- * the document. Keep it through independently resolved changes, then resolve
540
- * it as soon as that table's deletion has been decided.
541
- */
542
- const terminalTableDeletionIsPending = (tr) => {
543
- let terminalTable = null;
544
- for (let index = tr.doc.childCount - 1; index >= 0; index--) {
545
- const node = tr.doc.child(index);
546
- if (node.type.name === "table") {
547
- terminalTable = node;
548
- break;
549
- }
550
- }
551
- if (terminalTable === null) return false;
552
- let pending = false;
553
- terminalTable.descendants((node) => {
554
- pending ||= node.type.name === "tableRow" && isTableRowRevisionAttr(node.attrs["trDel"]) || node.type.name !== "tableRow" && node.marks.some((mark) => mark.type.name === "deletion");
555
- return !pending;
556
- });
557
- return pending;
558
- };
559
- /** Resolve the Folio-only receiver Word needs after a terminal deleted table. */
560
- const resolveTerminalTableReviewCarrier = (tr, mode) => {
561
- let position = tr.doc.content.size;
562
- let carrier = null;
563
- for (let index = tr.doc.childCount - 1; index >= 0; index--) {
564
- carrier = tr.doc.child(index);
565
- position -= carrier.nodeSize;
566
- if (carrier.type.name !== "textBox") break;
567
- }
568
- if (carrier?.type.name !== "paragraph" || carrier.attrs["reviewCarrier"] !== REVIEW_CARRIERS.TERMINAL_TABLE) return;
569
- let pending = carrier.attrs["pPrMark"] != null;
570
- carrier.forEach((child) => {
571
- pending ||= child.marks.some(({ type }) => ["insertion", "deletion"].includes(type.name));
572
- });
573
- if (pending) return;
574
- if (mode === "accept" || carrier.content.size > 0) {
575
- tr.setNodeAttribute(position, "reviewCarrier", void 0);
576
- return;
577
- }
578
- tr.delete(position, position + carrier.nodeSize);
579
- };
580
- const resolveRunPropertyChange = ({ tr, node, from, to, mark, mode, revisionSet, styleResolver }) => {
581
- const { changes } = expectRunPropertyChangeMarkAttrs(mark);
582
- const matches = changes.filter((change) => revisionSet === null || revisionSet.has(change.info.id));
583
- if (matches.length === 0) return;
584
- tr.removeMark(from, to, mark);
585
- const remaining = changes.filter((change) => revisionSet !== null && !revisionSet.has(change.info.id));
586
- if (remaining.length > 0) tr.addMark(from, to, mark.type.create({ changes: remaining }));
587
- const emptyRuns = node.type.name === "field" || node.type.name === "structuredField" ? expectFieldAttrs(node)._docxEmptyResultRuns : void 0;
588
- const resolvedRuns = emptyRuns ? resolveEmptyFieldResultRuns({
589
- runs: emptyRuns,
590
- mode,
591
- revisionIds: revisionSet
592
- }) : null;
593
- if (resolvedRuns) {
594
- const current = tr.doc.nodeAt(from);
595
- if (!current) panic("A resolved field has no node at its position");
596
- tr.setNodeMarkup(from, void 0, {
597
- ...current.attrs,
598
- _docxEmptyResultRuns: resolvedRuns.runs
599
- });
600
- if (resolvedRuns.visibleFormattingChanged) {
601
- const styleContext = paragraphRunStyleContextAt({
602
- doc: tr.doc,
603
- pos: from,
604
- styleResolver
605
- });
606
- for (const currentMark of node.marks) if (RUN_FORMATTING_MARK_NAMES.has(currentMark.type.name)) tr.removeMark(from, to, currentMark.type);
607
- for (const nextMark of rejectedRunFormatting({
608
- node,
609
- paragraphContext: styleContext,
610
- previousFormatting: resolvedRuns.visibleFormatting,
611
- styleResolver
612
- }).marks ?? []) tr.addMark(from, to, nextMark);
613
- }
614
- return;
615
- }
616
- if (mode === "accept") return;
617
- const rejected = rejectedRunFormatting({
618
- node,
619
- paragraphContext: paragraphRunStyleContextAt({
620
- doc: tr.doc,
621
- pos: from,
622
- styleResolver
623
- }),
624
- previousFormatting: matches.at(0)?.previousFormatting,
625
- styleResolver
626
- });
627
- if (rejected.atomRunFormatting !== null) {
628
- const current = tr.doc.nodeAt(from);
629
- if (!current) panic("A resolved run atom has no node at its position");
630
- tr.setNodeMarkup(from, void 0, {
631
- ...current.attrs,
632
- _docxRunFormatting: rejected.atomRunFormatting
633
- });
634
- }
635
- if (rejected.marks === null) return;
636
- for (const currentMark of node.marks) if (RUN_FORMATTING_MARK_NAMES.has(currentMark.type.name)) tr.removeMark(from, to, currentMark.type);
637
- for (const previousMark of rejected.marks) tr.addMark(from, to, previousMark);
638
- };
639
- function collectTableRowStructuralOp(node, rowPos, mode, revisionSet) {
640
- for (const attrName of ["trIns", "trDel"]) {
641
- const marker = node.attrs[attrName];
642
- if (!isTableRowRevisionAttr(marker)) continue;
643
- if (revisionSet !== null && !revisionSet.has(marker.revisionId)) continue;
644
- return {
645
- rowPos,
646
- attrName,
647
- action: attrName === "trIns" === (mode === "accept") ? "clear" : "remove",
648
- revision: marker
649
- };
650
- }
651
- return null;
652
- }
653
- function isTableRowRevisionAttr(value) {
654
- return typeof value === "object" && value !== null && "revisionId" in value && typeof value.revisionId === "number";
655
- }
656
- /**
657
- * Whether an inline revision mark inside a row belongs to that row's own
658
- * structural revision. Folio writes both halves under one id; Word mints a
659
- * fresh `w:id` per element, so an author + timestamp match counts too. A third
660
- * party's edit inside the same row matches neither and survives untouched.
661
- */
662
- function markBelongsToRowRevision(mark, revision) {
663
- if (mark.attrs["revisionId"] === revision.revisionId) return true;
664
- return revision.author !== void 0 && mark.attrs["author"] === revision.author && (mark.attrs["date"] ?? null) === (revision.date ?? null);
665
- }
666
- /**
667
- * Clear the run-level revision marks a row's structural revision wrote.
668
- *
669
- * A tracked row insertion or deletion is marked twice — on the row and around
670
- * every run in its cells — so resolving one half and leaving the other would
671
- * hand back a row whose text still reads as inserted (or struck through) after
672
- * the change was accepted. Both halves resolve in the caller's transaction.
673
- */
674
- function clearTableRowContentMarks({ tr, rowPos, markType, revision }) {
675
- const row = tr.doc.nodeAt(rowPos);
676
- if (!row || !markType) return;
677
- const contentFrom = rowPos + 1;
678
- const removals = [];
679
- row.descendants((node, offset) => {
680
- if (!node.isInline) return true;
681
- for (const mark of node.marks) if (mark.type === markType && markBelongsToRowRevision(mark, revision)) {
682
- const from = contentFrom + offset;
683
- removals.push({
684
- from,
685
- to: from + node.nodeSize,
686
- mark
687
- });
688
- }
689
- return false;
690
- });
691
- for (const removal of removals) tr.removeMark(removal.from, removal.to, removal.mark);
692
- }
693
- function collectTableCellStructuralOps(node, cellPos, mode, revisionSet) {
694
- const operations = [];
695
- const marker = node.attrs["cellMarker"];
696
- if (isTableCellRevisionAttr(marker) && (revisionSet === null || revisionSet.has(marker.info.revisionId))) {
697
- if (marker.kind === "merge") operations.push({
698
- type: "merge",
699
- cellPos,
700
- source: "visible",
701
- mode,
702
- revisionSet
703
- });
704
- else {
705
- const view = mode === "accept" ? "final" : "original";
706
- operations.push({
707
- type: "membership",
708
- cellPos,
709
- action: isTableCellRetainedInReviewView(marker.kind, view) ? "clear" : "remove"
710
- });
711
- }
712
- }
713
- if (hasMatchingCollapsedTableCellMerge(node, revisionSet)) operations.push({
714
- type: "merge",
715
- cellPos,
716
- source: "collapsed",
717
- mode,
718
- revisionSet
719
- });
720
- return operations;
721
- }
722
- function isTableCellRevisionAttr(value) {
723
- if (typeof value !== "object" || value === null || !("kind" in value) || !("info" in value)) return false;
724
- if (value.kind !== "ins" && value.kind !== "del" && value.kind !== "merge") return false;
725
- const info = value.info;
726
- return typeof info === "object" && info !== null && "revisionId" in info && typeof info.revisionId === "number";
727
- }
728
- /** Record rows for a final sweep after every cell revision has resolved. */
729
- function deleteTableCellAt(tr, cellPos, emptied) {
730
- const cell = tr.doc.nodeAt(cellPos);
731
- if (!cell || cell.type.name !== "tableCell" && cell.type.name !== "tableHeader") return;
732
- const resolved = tr.doc.resolve(cellPos);
733
- const row = resolved.parent;
734
- if (row.type.spec["tableRole"] !== "row") return;
735
- const tableDepth = resolved.depth - 1;
736
- const table = resolved.node(tableDepth);
737
- if (table.type.spec["tableRole"] !== "table") return;
738
- const tablePosition = resolved.before(tableDepth);
739
- const cellOffset = cellPos - resolved.start(tableDepth);
740
- const removedColumn = TableMap.get(table).findCell(cellOffset).left;
741
- const spansDown = Number(cell.attrs["rowspan"]) > 1;
742
- const holdsOtherCells = !rowHoldsNoCells(row, cell);
743
- if (holdsOtherCells || spansDown) {
744
- if (!holdsOtherCells) markRowEmptiedInBatch({
745
- tr,
746
- rowPosition: resolved.start() - 1,
747
- emptied
748
- });
749
- tr.delete(cellPos, cellPos + cell.nodeSize);
750
- reconcileOmittedGridSlots(tr, tablePosition, table, removedColumn);
751
- reconcileTableGridAfterColumnRemoval({
752
- tr,
753
- tablePosition,
754
- previousTable: table,
755
- removedColumn
756
- });
757
- return;
758
- }
759
- if (table.childCount === 1) {
760
- deleteTableRowAt(tr, resolved.start() - 1);
761
- return;
762
- }
763
- deleteTableRowAt(tr, resolved.start() - 1);
764
- reconcileOmittedGridSlots(tr, tablePosition, table, removedColumn);
765
- reconcileTableGridAfterColumnRemoval({
766
- tr,
767
- tablePosition,
768
- previousTable: table,
769
- removedColumn
770
- });
771
- }
772
- function collectPPrMarkOp(node, pos, from, to, mode, revisionSet) {
773
- if (!rangeCoversParagraphBoundary(from, to, pos, node)) return null;
774
- const pPrMark = node.attrs["pPrMark"];
775
- if (!isPPrMarkAttr(pPrMark)) return null;
776
- const deletion = pPrMark.deletion;
777
- if (deletion !== void 0) {
778
- const chosen = (id) => revisionSet === null || revisionSet.has(id);
779
- const insertionChosen = chosen(pPrMark.info.id);
780
- const deletionChosen = chosen(deletion.info.id);
781
- if (!insertionChosen && !deletionChosen) return null;
782
- if (mode === "accept" ? deletionChosen : insertionChosen) return {
783
- paragraphPos: pos,
784
- action: "join",
785
- markWasAdded: true
786
- };
787
- const { deletion: _resolved, ...added } = pPrMark;
788
- return {
789
- paragraphPos: pos,
790
- action: "settle",
791
- mark: mode === "accept" ? {
792
- kind: "del",
793
- info: deletion.info
794
- } : added,
795
- markWasAdded: true
796
- };
797
- }
798
- if (revisionSet !== null && !revisionSet.has(pPrMark.info.id)) return null;
799
- const markWasAdded = paragraphMarkWasAdded(pPrMark.kind);
800
- return {
801
- paragraphPos: pos,
802
- action: markWasAdded === (mode === "accept") ? "clear" : "join",
803
- markWasAdded
804
- };
805
- }
806
- function rangeCoversParagraphBoundary(from, to, pos, node) {
807
- const boundaryFrom = pos + node.nodeSize - 1;
808
- const boundaryTo = pos + node.nodeSize;
809
- return from <= boundaryFrom && to >= boundaryTo;
810
- }
811
- /** Whether [from, to] fully covers the node — the range property-change cards
812
- * and accept-all / reject-all sweeps supply for table-level records. */
813
- function rangeCoversNode(from, to, pos, node) {
814
- return from <= pos && to >= pos + node.nodeSize;
815
- }
816
- function isPPrMarkAttr(value) {
817
- if (typeof value !== "object" || value === null) return false;
818
- const kind = value.kind;
819
- const info = value.info;
820
- if (!PARAGRAPH_MARK_CHANGE_KINDS.some((allowed) => allowed === kind)) return false;
821
- if (typeof info !== "object" || info === null) return false;
822
- return typeof info.id === "number";
823
- }
824
- /**
825
- * Whether the mark says the paragraph break was ADDED. A relocation's
826
- * destination break was added exactly as an insertion's was, and its source
827
- * break went exactly as a deletion's did; the kinds differ so a reader is told
828
- * the two ends belong together, not because they resolve differently.
829
- */
830
- const paragraphMarkWasAdded = (kind) => kind === "ins" || kind === "moveTo";
831
- const ownsSectionEndpoint = (paragraph) => expectParagraphAttrs(paragraph)._sectionProperties != null;
832
- const sectionReferencesOf = (paragraph) => {
833
- const sectionProperties = expectParagraphAttrs(paragraph)._sectionProperties;
834
- if (!sectionProperties) return [];
835
- return [...(sectionProperties.headerReferences ?? []).map(({ type, rId }) => ({
836
- part: "header",
837
- type,
838
- relationshipId: rId
839
- })), ...(sectionProperties.footerReferences ?? []).map(({ type, rId }) => ({
840
- part: "footer",
841
- type,
842
- relationshipId: rId
843
- }))];
844
- };
845
- const isAddedPPrMarkAttr = (value) => isPPrMarkAttr(value) && (value.kind === "ins" || value.kind === "moveTo");
846
- function readRevisionInfo(info) {
847
- const revision = {};
848
- if (typeof info?.author === "string") revision.author = info.author;
849
- if (typeof info?.date === "string") revision.date = info.date;
850
- if (typeof info?.id === "number") revision.revisionId = info.id;
851
- return revision;
852
- }
853
- function getListPropertyChangeType(node, change) {
854
- const previousFormatting = change.previousFormatting;
855
- if (previousFormatting == null || !Object.hasOwn(previousFormatting, "numPr")) return null;
856
- const current = expectParagraphAttrs(node).numPr;
857
- const previous = previousFormatting["numPr"] ?? void 0;
858
- if (sameStatedParagraphNumbering$1(previous, current)) return null;
859
- return current === void 0 ? "deletion" : "insertion";
860
- }
861
- function toParagraphBoundaryChange(node, pos, type, info) {
862
- return {
863
- from: pos + node.nodeSize - 1,
864
- to: pos + node.nodeSize,
865
- type,
866
- ...readRevisionInfo(info)
867
- };
868
- }
869
- function findParagraphBoundaryChangeAtPosition(state, pos) {
870
- const $pos = state.doc.resolve(pos);
871
- const node = $pos.parent;
872
- if (node.type.name !== "paragraph") return null;
873
- const paragraphPos = $pos.before($pos.depth);
874
- const pPrMark = node.attrs["pPrMark"];
875
- if (isPPrMarkAttr(pPrMark)) return toParagraphBoundaryChange(node, paragraphPos, paragraphMarkWasAdded(pPrMark.kind) ? "insertion" : "deletion", pPrMark.info);
876
- const propertyChanges = expectParagraphAttrs(node)._propertyChanges;
877
- if (!Array.isArray(propertyChanges)) return null;
878
- for (const change of propertyChanges) {
879
- const type = getListPropertyChangeType(node, change);
880
- if (type) return toParagraphBoundaryChange(node, paragraphPos, type, change.info);
881
- }
882
- return null;
883
- }
884
- /** The transaction `command` would dispatch on `state`, or `null` when it would not apply. */
885
- const attemptedTransaction = (command, state, view) => {
886
- let attempted = null;
887
- return command(state, (transaction) => {
888
- attempted = transaction;
889
- }, view) ? attempted : null;
890
- };
891
- /**
892
- * `command`, refused when what it would do breaks a content control's lock
893
- * (`lockedControlViolationOfTransform`). A document without a locked control
894
- * runs it as it is.
895
- */
896
- const honouringContentControlLocks = (command) => (state, dispatch, view) => {
897
- if (lockedControlSpans(state.doc).length === 0) return command(state, dispatch, view);
898
- const attempted = attemptedTransaction(command, state, view);
899
- if (attempted === null) return false;
900
- if (lockedControlViolationOfTransform(attempted) !== null) return false;
901
- dispatch?.(attempted);
902
- return true;
903
- };
904
- function resolveChange(from, to, mode, revisionIds) {
905
- return honouringContentControlLocks(resolveChangeUnguarded(from, to, mode, revisionIds));
906
- }
907
- /**
908
- * What the content-control locks say about resolving the tracked changes
909
- * between `from` and `to` (only those of `revisionIds`, when given): `null`
910
- * when they allow it or there is nothing there to resolve. A revision whose
911
- * resolution would change a content-locked control's content, or remove a
912
- * control locked against removal, stays pending.
913
- */
914
- const changeResolutionLockViolation = (state, { from, to, mode, revisionIds }) => {
915
- if (lockedControlSpans(state.doc).length === 0) return null;
916
- const attempted = attemptedTransaction(resolveChangeUnguarded(from, to, mode, revisionIds), state);
917
- return attempted === null ? null : lockedControlViolationOfTransform(attempted);
918
- };
919
- /** {@link changeResolutionLockViolation} for the revisions `revisionIds`, wherever they are. */
920
- const revisionResolutionLockViolation = (state, revisionIds, mode) => {
921
- const range = findAIEditRevisionRange(state, revisionIds);
922
- return range === null ? null : changeResolutionLockViolation(state, {
923
- ...range,
924
- mode,
925
- revisionIds: typeof revisionIds === "number" ? [revisionIds] : revisionIds
926
- });
927
- };
928
- /**
929
- * Accept a tracked change at the given range.
930
- * - Insertion: remove mark, keep text
931
- * - Deletion: remove mark AND text
932
- */
933
- function acceptChange(from, to) {
934
- return resolveChange(from, to, "accept");
935
- }
936
- /**
937
- * Reject a tracked change at the given range.
938
- * - Insertion: remove mark AND text
939
- * - Deletion: remove mark, keep text
940
- */
941
- function rejectChange(from, to) {
942
- return resolveChange(from, to, "reject");
943
- }
944
- const resolveAllChanges = (mode) => (state, dispatch) => {
945
- if (!dispatch) return true;
946
- const result = resolveStateStory(state, mode);
947
- if (result.failed) return false;
948
- if (result.resolved.eq(state.doc)) return true;
949
- const tr = state.tr.step(new RevisionResolutionStep({
950
- beforeDoc: state.doc,
951
- afterDoc: result.resolved,
952
- steps: result.steps,
953
- positionMap: result.positionMap
954
- }));
955
- const resolvedAt = tr.steps.length;
956
- normalizeKeptRangeBoundaries(tr, result.keptBoundaries);
957
- requestDeterministicParaIds(tr, `resolve-all:${mode}`);
958
- markChangedParagraphRanges(tr, {
959
- ranges: finalRevisionParagraphRanges(result),
960
- mappingFrom: resolvedAt,
961
- replacesStepMapAt: 0
962
- });
963
- markParagraphPropertySourceTransfers(tr, result.transfers);
964
- if (result.structural) markStructuralChange(tr);
965
- if (result.removedEndpointCount > 0) markTrackedSectionEndpointRemoval(tr, {
966
- sourceDoc: state.doc,
967
- removedEndpointCount: result.removedEndpointCount,
968
- removedReferences: result.removedReferences
969
- });
970
- finishResolution(state, tr);
971
- dispatch(tr);
972
- return true;
973
- };
974
- /**
975
- * Accept all tracked changes in the document. Returns `false` while pending
976
- * suggestions are present because this command cannot restage them.
977
- */
978
- function acceptAllChanges() {
979
- const resolve = resolveAllChangesHonouringLocks("accept");
980
- return (state, dispatch, view) => {
981
- if (getSuggestions(state).length > 0) return false;
982
- return resolve(state, dispatch, view);
983
- };
984
- }
985
- /**
986
- * Reject all tracked changes in the document.
987
- */
988
- function rejectAllChanges() {
989
- return resolveAllChangesHonouringLocks("reject");
990
- }
991
- /**
992
- * The revisions of `state` that a content control's lock keeps from being
993
- * resolved in `mode`, each with the lock's verdict: see
994
- * {@link changeResolutionLockViolation}. Empty without a locked control.
995
- */
996
- const lockHeldRevisions = (state, mode) => {
997
- const held = /* @__PURE__ */ new Map();
998
- if (lockedControlSpans(state.doc).length === 0) return held;
999
- for (const id of new Set(extractTrackedChanges(state).entries.flatMap(trackedChangeEntryRevisionIds))) {
1000
- const violation = revisionResolutionLockViolation(state, id, mode);
1001
- if (violation !== null) held.set(id, violation);
1002
- }
1003
- return held;
1004
- };
1005
- /** Every revision id one sidebar entry stands for. */
1006
- const trackedChangeEntryRevisionIds = (entry) => [.../* @__PURE__ */ new Set([
1007
- entry.revisionId,
1008
- ...entry.insertionRevisionId === void 0 ? [] : [entry.insertionRevisionId],
1009
- ...entry.coalescedRevisionIds ?? []
1010
- ])];
1011
- /**
1012
- * Resolve every tracked change a content control's lock allows. Without a
1013
- * change the locks hold, the whole story resolves in one pass, as before;
1014
- * otherwise each other change resolves on its own, in an editor view (a
1015
- * transaction each), and the held ones stay pending as they are. Without a
1016
- * view nothing resolves when any change is held.
1017
- */
1018
- const resolveAllChangesHonouringLocks = (mode) => (state, dispatch, view) => {
1019
- const resolveAll = resolveAllChanges(mode);
1020
- if (lockedControlSpans(state.doc).length === 0) return resolveAll(state, dispatch, view);
1021
- const attempted = attemptedTransaction(resolveAll, state, view);
1022
- if (attempted === null) return false;
1023
- if (lockedControlViolationOfTransform(attempted) === null) {
1024
- dispatch?.(attempted);
1025
- return true;
1026
- }
1027
- if (!dispatch) return true;
1028
- if (!view) return false;
1029
- const held = lockHeldRevisions(state, mode);
1030
- const ids = new Set(extractTrackedChanges(state).entries.flatMap(trackedChangeEntryRevisionIds));
1031
- for (const id of [...ids].toReversed()) {
1032
- if (held.has(id)) continue;
1033
- (mode === "accept" ? acceptAIEditRevision(id) : rejectAIEditRevision(id))(view.state, view.dispatch, view);
1034
- }
1035
- return true;
1036
- };
1037
- /**
1038
- * Resolve a complete state synchronously for a headless reader or writer.
1039
- *
1040
- * Uses the same single-step resolver as the interactive editor command.
1041
- */
1042
- function resolveAllChangesInHeadlessState(state, mode) {
1043
- return projectAllChangesInHeadlessState(state, mode) ?? state;
1044
- }
1045
- /** The review transaction, or null when its content cannot be resolved. */
1046
- const projectAllChangesInHeadlessState = (state, mode) => {
1047
- let resolvedState = state;
1048
- return resolveAllChanges(mode)(state, (transaction) => {
1049
- resolvedState = state.apply(transaction);
1050
- }) ? resolvedState : null;
1051
- };
1052
- /**
1053
- * Resolve a story and retain its position map for callers addressing the tracked source.
1054
- */
1055
- const resolveAllChangesInHeadlessStateWithMapping = (state, mode) => {
1056
- let resolvedState = state;
1057
- let mapping = new Mapping();
1058
- resolveAllChanges(mode)(state, (transaction) => {
1059
- resolvedState = state.apply(transaction);
1060
- mapping = transaction.mapping;
1061
- });
1062
- return {
1063
- state: resolvedState,
1064
- mapping
1065
- };
1066
- };
1067
- /**
1068
- * Find the document range covered by all revision carriers with any of the
1069
- * given ids. Returns null when none are present (already accepted/rejected, or
1070
- * never existed). A replace operation typically passes two ids; standalone
1071
- * text, formatting, paragraph, section, and table revisions pass a single id.
1072
- */
1073
- function findAIEditRevisionRange(state, revisionIds) {
1074
- const insertionType = state.schema.marks["insertion"];
1075
- const deletionType = state.schema.marks["deletion"];
1076
- const runPropertyChangeType = state.schema.marks["runPropertyChange"];
1077
- const idSet = new Set(typeof revisionIds === "number" ? [revisionIds] : revisionIds);
1078
- const range = {
1079
- from: null,
1080
- to: null
1081
- };
1082
- const includeRange = (from, to) => {
1083
- if (range.from === null || from < range.from) range.from = from;
1084
- if (range.to === null || to > range.to) range.to = to;
1085
- };
1086
- state.doc.descendants((node, pos) => {
1087
- for (const carrier of getFolioNodeRevisionCarriers(node, pos)) if (idSet.has(carrier.id)) includeRange(carrier.from, carrier.to);
1088
- if (node.type.name === "sdt" && enclosingRevisionIds(node).some((id) => idSet.has(id))) includeRange(pos, pos + node.nodeSize);
1089
- if (node.type.name === "tableRow") for (const attrName of ["trIns", "trDel"]) {
1090
- const marker = node.attrs[attrName];
1091
- if (isTableRowRevisionAttr(marker) && idSet.has(marker.revisionId)) {
1092
- includeRange(pos, pos + node.nodeSize);
1093
- return false;
1094
- }
1095
- }
1096
- if (node.type.name === "tableCell" || node.type.name === "tableHeader") {
1097
- const marker = node.attrs["cellMarker"];
1098
- const hasDirectRevision = isTableCellRevisionAttr(marker) && idSet.has(marker.info.revisionId);
1099
- const continuationCells = node.attrs["_docxVMergeContinuationCells"];
1100
- const hasCollapsedRevision = Array.isArray(continuationCells) && continuationCells.some((cell) => {
1101
- const change = getTableCellMergeChange(cell);
1102
- return change !== null && idSet.has(change.info.id);
1103
- });
1104
- if (hasDirectRevision || hasCollapsedRevision) {
1105
- includeRange(pos, pos + node.nodeSize);
1106
- return false;
1107
- }
1108
- }
1109
- if (!node.isInline) return;
1110
- for (const mark of node.marks) {
1111
- if (mark.type === runPropertyChangeType && expectRunPropertyChangeMarkAttrs(mark).changes.some((change) => idSet.has(change.info.id))) {
1112
- includeRange(pos, pos + node.nodeSize);
1113
- break;
1114
- }
1115
- if ((mark.type === insertionType || mark.type === deletionType) && (idSet.has(expectTrackedChangeMarkAttrs(mark).revisionId) || (expectTrackedChangeMarkAttrs(mark)._docxRevisionAncestors ?? []).some((ancestor) => idSet.has(ancestor.revisionId)))) {
1116
- includeRange(pos, pos + node.nodeSize);
1117
- break;
1118
- }
1119
- }
1120
- });
1121
- if (range.from === null || range.to === null) return null;
1122
- return {
1123
- from: range.from,
1124
- to: range.to
1125
- };
1126
- }
1127
- /**
1128
- * Accept the tracked-change marks belonging to an AI-edit operation.
1129
- * Pass a single revisionId for inserts, standalone deletions, or formatting changes; or the
1130
- * full id list for a replace (one id per side). Returns false when
1131
- * none of the ids match anything in the doc.
1132
- */
1133
- function acceptAIEditRevision(revisionIds) {
1134
- return (state, dispatch) => {
1135
- const range = findAIEditRevisionRange(state, revisionIds);
1136
- if (!range) return false;
1137
- const ids = typeof revisionIds === "number" ? [revisionIds] : revisionIds;
1138
- return resolveChange(range.from, range.to, "accept", ids)(state, dispatch);
1139
- };
1140
- }
1141
- /**
1142
- * Reject the tracked-change marks belonging to an AI-edit operation.
1143
- * See {@link acceptAIEditRevision} for the id semantics.
1144
- */
1145
- function rejectAIEditRevision(revisionIds) {
1146
- return (state, dispatch) => {
1147
- const range = findAIEditRevisionRange(state, revisionIds);
1148
- if (!range) return false;
1149
- const ids = typeof revisionIds === "number" ? [revisionIds] : revisionIds;
1150
- return resolveChange(range.from, range.to, "reject", ids)(state, dispatch);
1151
- };
1152
- }
1153
- /**
1154
- * Suggestion (AI-proposed tracked change) commands.
1155
- *
1156
- * A suggestion is a set of `insertion` / `deletion` / `runPropertyChange` marks
1157
- * sharing one `suggestionId` and carrying `provenance: "suggested"`. Accepting
1158
- * rewrites those marks to normal (`"user"`) tracked changes authored by the
1159
- * accepting user; rejecting inverse-applies them like `rejectChange`, reusing
1160
- * the same {@link resolveChange} machinery scoped to the suggestion's revision
1161
- * ids. All three operate as ordinary PM transactions, so they sync via collab
1162
- * and are undoable.
1163
- */
1164
- const SUGGESTION_MARK_NAMES = /* @__PURE__ */ new Set([
1165
- "insertion",
1166
- "deletion",
1167
- "runPropertyChange"
1168
- ]);
1169
- const isSuggestionMark = (mark) => mark.attrs["provenance"] === "suggested" && SUGGESTION_MARK_NAMES.has(mark.type.name);
1170
- /**
1171
- * The suggestion a comment mark belongs to: a comment a suggestion proposed
1172
- * is pending with it, never saved, accepted and rejected with it.
1173
- */
1174
- const suggestedCommentOf = (mark) => {
1175
- if (mark.type.name !== "comment") return null;
1176
- const suggestionId = mark.attrs["suggestionId"];
1177
- return typeof suggestionId === "string" && suggestionId.length > 0 ? suggestionId : null;
1178
- };
1179
- /** The ids of the comments a pending suggestion proposes. */
1180
- function suggestionCommentIds(state, suggestionId) {
1181
- return [...collectSuggestions(state).get(suggestionId)?.commentIds ?? []];
1182
- }
1183
- /**
1184
- * Remove the comment marks of the suggestions `matches` selects, or, with
1185
- * `keep`, clear their suggestion so they stay as ordinary comments. Mark
1186
- * steps do not shift positions.
1187
- */
1188
- const resolveSuggestedCommentMarks = (tr, matches, keep) => {
1189
- const found = [];
1190
- tr.doc.descendants((node, pos) => {
1191
- if (!node.isInline) return void 0;
1192
- for (const mark of node.marks) {
1193
- const suggestionId = suggestedCommentOf(mark);
1194
- if (suggestionId !== null && matches(suggestionId)) found.push({
1195
- from: pos,
1196
- to: pos + node.nodeSize,
1197
- mark
1198
- });
1199
- }
1200
- });
1201
- for (const { from, to, mark } of found) {
1202
- tr.removeMark(from, to, mark);
1203
- if (keep) tr.addMark(from, to, mark.type.create({
1204
- ...mark.attrs,
1205
- suggestionId: null
1206
- }));
1207
- }
1208
- return found.length > 0;
1209
- };
1210
- const suggestionKindOf = (mark) => {
1211
- if (mark.type.name === "insertion") return "insertion";
1212
- if (mark.type.name === "deletion") return "deletion";
1213
- return "formatting";
1214
- };
1215
- const readSuggestedMarker = (marker) => {
1216
- if (typeof marker !== "object" || marker === null || marker.provenance !== "suggested") return null;
1217
- const suggestionId = marker.suggestionId;
1218
- const revisionId = marker.revisionId;
1219
- if (typeof suggestionId !== "string" || typeof revisionId !== "number") return null;
1220
- return {
1221
- suggestionId,
1222
- revisionId
1223
- };
1224
- };
1225
- const readSuggestedParagraphPropertyChange = (change) => {
1226
- if (change.info.provenance !== "suggested" || typeof change.info.suggestionId !== "string") return null;
1227
- return {
1228
- suggestionId: change.info.suggestionId,
1229
- revisionId: change.info.id
1230
- };
1231
- };
1232
- /**
1233
- * The property changes a table, row or cell carries as the model holds them:
1234
- * a pending suggestion's names its suggestion in its info.
1235
- */
1236
- const tablePropertyChangesOf = (node) => {
1237
- switch (node.type.name) {
1238
- case "table": return expectTableAttrs(node).tblPrChange ?? [];
1239
- case "tableRow": return expectTableRowAttrs(node).trPrChange ?? [];
1240
- case "tableCell":
1241
- case "tableHeader": return expectTableCellAttrs(node).tcPrChange ?? [];
1242
- default: return [];
1243
- }
1244
- };
1245
- /** The suggestion one paragraph-mark record belongs to, read off its info. */
1246
- const suggestionIdOfMarkRecord = (info) => "provenance" in info && info.provenance === "suggested" && "suggestionId" in info && typeof info.suggestionId === "string" ? info.suggestionId : null;
1247
- const suggestedRecordOf = (info, kind) => {
1248
- const suggestionId = suggestionIdOfMarkRecord(info);
1249
- return suggestionId === null ? null : {
1250
- suggestionId,
1251
- revisionId: info.id,
1252
- kind
1253
- };
1254
- };
1255
- /** The suggestion the paragraph mark's own record, its break's, belongs to. */
1256
- const readSuggestedParagraphMark = (node) => {
1257
- if (node.type.name !== "paragraph") return null;
1258
- const mark = node.attrs["pPrMark"];
1259
- if (!isPPrMarkAttr(mark)) return null;
1260
- return suggestedRecordOf(mark.info, paragraphMarkWasAdded(mark.kind) ? "insertion" : "deletion");
1261
- };
1262
- /**
1263
- * Every suggested record of a paragraph's mark: its own, and the later
1264
- * deletion an added mark holds beside its insertion.
1265
- */
1266
- const readSuggestedParagraphMarkRecords = (node) => {
1267
- const own = readSuggestedParagraphMark(node);
1268
- const mark = node.attrs["pPrMark"];
1269
- return [own, node.type.name === "paragraph" && isPPrMarkAttr(mark) && mark.deletion !== void 0 ? suggestedRecordOf(mark.deletion.info, "deletion") : null].filter((record) => record !== null);
1270
- };
1271
- const readStructuralSuggestion = (node) => {
1272
- const attrs = node.attrs;
1273
- const name = node.type.name;
1274
- const insertMarker = attrs["_suggestedInsert"];
1275
- if ((name === "paragraph" || name === "table") && typeof insertMarker === "object" && insertMarker !== null) {
1276
- const suggestionId = insertMarker.suggestionId;
1277
- const revisionId = insertMarker.revisionId;
1278
- if (typeof suggestionId === "string" && typeof revisionId === "number") return {
1279
- suggestionId,
1280
- revisionId,
1281
- kind: name === "table" ? "insertTable" : "insertBlock",
1282
- isNodeInsert: true
1283
- };
1284
- }
1285
- if (node.type.name === "tableRow") {
1286
- const ins = readSuggestedMarker(attrs["trIns"]);
1287
- if (ins) return {
1288
- ...ins,
1289
- kind: "insertRow",
1290
- isNodeInsert: false
1291
- };
1292
- const del = readSuggestedMarker(attrs["trDel"]);
1293
- if (del) return {
1294
- ...del,
1295
- kind: "deleteRow",
1296
- isNodeInsert: false
1297
- };
1298
- }
1299
- if (node.type.name === "tableCell" || node.type.name === "tableHeader") {
1300
- const cellMarker = attrs["cellMarker"];
1301
- if (typeof cellMarker === "object" && cellMarker !== null) {
1302
- const markerKind = cellMarker.kind;
1303
- if (markerKind === "ins" || markerKind === "del") {
1304
- const marker = readSuggestedMarker(cellMarker.info);
1305
- if (marker) {
1306
- const kind = markerKind === "del" ? "deleteColumn" : "insertColumn";
1307
- return {
1308
- ...marker,
1309
- kind,
1310
- isNodeInsert: false
1311
- };
1312
- }
1313
- }
1314
- }
1315
- }
1316
- return null;
1317
- };
1318
- /**
1319
- * Whether a rejection takes `node` out whole: a wholly suggested paragraph or
1320
- * table whose insertion it rejects. The suggestion rejections remove it, and
1321
- * a paragraph break the same rejection takes out joins past it.
1322
- */
1323
- const rejectionRemovesWholeNode = (node, selection) => {
1324
- const structural = readStructuralSuggestion(node);
1325
- return selection.mode === "reject" && structural?.isNodeInsert === true && selection.resolves(structural.revisionId);
1326
- };
1327
- /** Whether the node at `at` is its parent's last child. */
1328
- const endsItsContainer = (at) => at.index() >= at.parent.childCount - 1;
1329
- const collectSuggestions = (state) => {
1330
- const runPropertyChangeType = state.schema.marks["runPropertyChange"];
1331
- const bySuggestion = /* @__PURE__ */ new Map();
1332
- const entryFor = (suggestionId) => {
1333
- const existing = bySuggestion.get(suggestionId);
1334
- if (existing) return existing;
1335
- const created = {
1336
- segments: [],
1337
- kinds: /* @__PURE__ */ new Set(),
1338
- revisionIds: /* @__PURE__ */ new Set(),
1339
- commentIds: /* @__PURE__ */ new Set()
1340
- };
1341
- bySuggestion.set(suggestionId, created);
1342
- return created;
1343
- };
1344
- state.doc.descendants((node, pos) => {
1345
- const structural = readStructuralSuggestion(node);
1346
- if (structural) {
1347
- const entry = entryFor(structural.suggestionId);
1348
- entry.segments.push({
1349
- from: pos,
1350
- to: pos + node.nodeSize
1351
- });
1352
- entry.kinds.add(structural.kind);
1353
- entry.revisionIds.add(structural.revisionId);
1354
- }
1355
- for (const { info } of tablePropertyChangesOf(node)) {
1356
- if (info.suggestionId === void 0) continue;
1357
- const entry = entryFor(info.suggestionId);
1358
- entry.segments.push({
1359
- from: pos,
1360
- to: pos + node.nodeSize
1361
- });
1362
- entry.kinds.add("formatting");
1363
- entry.revisionIds.add(info.id);
1364
- }
1365
- if (node.type.name === "paragraph") {
1366
- for (const paragraphMark of readSuggestedParagraphMarkRecords(node)) {
1367
- const entry = entryFor(paragraphMark.suggestionId);
1368
- entry.segments.push({
1369
- from: pos,
1370
- to: pos + node.nodeSize
1371
- });
1372
- entry.kinds.add(paragraphMark.kind);
1373
- entry.revisionIds.add(paragraphMark.revisionId);
1374
- }
1375
- const propertyChanges = expectParagraphAttrs(node)._propertyChanges;
1376
- if (Array.isArray(propertyChanges)) for (const change of propertyChanges) {
1377
- const suggested = readSuggestedParagraphPropertyChange(change);
1378
- if (!suggested) continue;
1379
- const entry = entryFor(suggested.suggestionId);
1380
- entry.segments.push({
1381
- from: pos,
1382
- to: pos + node.nodeSize
1383
- });
1384
- entry.kinds.add("formatting");
1385
- entry.revisionIds.add(suggested.revisionId);
1386
- }
1387
- }
1388
- if (!node.isInline) return;
1389
- for (const mark of node.marks) {
1390
- const commentSuggestion = suggestedCommentOf(mark);
1391
- if (commentSuggestion !== null) {
1392
- const entry = entryFor(commentSuggestion);
1393
- entry.segments.push({
1394
- from: pos,
1395
- to: pos + node.nodeSize
1396
- });
1397
- entry.kinds.add("comment");
1398
- entry.commentIds.add(expectCommentMarkAttrs(mark).commentId);
1399
- continue;
1400
- }
1401
- if (mark.type.name === "insertion" || mark.type.name === "deletion") for (const ancestor of expectTrackedChangeMarkAttrs(mark)._docxRevisionAncestors ?? []) {
1402
- if (ancestor.suggestionId === void 0) continue;
1403
- const entry = entryFor(ancestor.suggestionId);
1404
- entry.segments.push({
1405
- from: pos,
1406
- to: pos + node.nodeSize
1407
- });
1408
- entry.kinds.add(ancestor.type === "insertion" || ancestor.type === "moveTo" ? "insertion" : "deletion");
1409
- entry.revisionIds.add(ancestor.revisionId);
1410
- }
1411
- if (!isSuggestionMark(mark)) continue;
1412
- const suggestionId = mark.attrs["suggestionId"];
1413
- if (typeof suggestionId !== "string" || suggestionId.length === 0) continue;
1414
- const entry = entryFor(suggestionId);
1415
- entry.segments.push({
1416
- from: pos,
1417
- to: pos + node.nodeSize
1418
- });
1419
- entry.kinds.add(suggestionKindOf(mark));
1420
- if (mark.type === runPropertyChangeType) for (const change of expectRunPropertyChangeMarkAttrs(mark).changes) entry.revisionIds.add(change.info.id);
1421
- else if (typeof mark.attrs["revisionId"] === "number") entry.revisionIds.add(mark.attrs["revisionId"]);
1422
- }
1423
- });
1424
- return bySuggestion;
1425
- };
1426
- /**
1427
- * A whole inserted table (`insertTable`) has no OOXML tracked representation and
1428
- * accepts directly; every other kind accepts as a tracked change. A group that
1429
- * mixes a table insert with any other kind (a caller stamping heterogeneous
1430
- * operations with one `suggestionId`) is `"mixed"`.
1431
- */
1432
- const suggestionAppliedAs = (kinds) => {
1433
- const changes = [...kinds].filter((kind) => kind !== "comment");
1434
- if (changes.length === 0) return "direct";
1435
- if (!kinds.has("insertTable")) return "tracked";
1436
- return changes.some((kind) => kind !== "insertTable") ? "mixed" : "direct";
1437
- };
1438
- /** Merge sorted, possibly adjacent/overlapping segments into contiguous ranges. */
1439
- const mergeSegments = (segments) => {
1440
- const sorted = [...segments].toSorted((a, b) => a.from - b.from || a.to - b.to);
1441
- const merged = [];
1442
- for (const segment of sorted) {
1443
- const last = merged.at(-1);
1444
- if (last && segment.from <= last.to) {
1445
- last.to = Math.max(last.to, segment.to);
1446
- continue;
1447
- }
1448
- merged.push({ ...segment });
1449
- }
1450
- return merged;
1451
- };
1452
- const SUGGESTION_KIND_ORDER = [
1453
- "insertion",
1454
- "deletion",
1455
- "formatting",
1456
- "insertBlock",
1457
- "insertTable",
1458
- "insertRow",
1459
- "deleteRow",
1460
- "insertColumn",
1461
- "deleteColumn",
1462
- "comment"
1463
- ];
1464
- /**
1465
- * List every suggestion in the document for host consumption: its id, the
1466
- * contiguous ranges it covers, which kinds of change it contains, and how
1467
- * accepting it applies (tracked vs direct).
1468
- */
1469
- function getSuggestions(state) {
1470
- const bySuggestion = collectSuggestions(state);
1471
- const suggestions = [];
1472
- for (const [suggestionId, entry] of bySuggestion) suggestions.push({
1473
- suggestionId,
1474
- ranges: mergeSegments(entry.segments),
1475
- kinds: SUGGESTION_KIND_ORDER.filter((kind) => entry.kinds.has(kind)),
1476
- appliedAs: suggestionAppliedAs(entry.kinds)
1477
- });
1478
- return suggestions.toSorted((a, b) => (a.ranges[0]?.from ?? 0) - (b.ranges[0]?.from ?? 0));
1479
- }
1480
- /** Physical revision IDs of every pending suggestion, in one document walk. */
1481
- const pendingSuggestionRevisionIds = (state) => {
1482
- const ids = /* @__PURE__ */ new Set();
1483
- for (const { revisionIds } of collectSuggestions(state).values()) for (const id of revisionIds) ids.add(id);
1484
- return ids;
1485
- };
1486
- /** The first owning suggestion for each physical revision, in source order. */
1487
- const suggestionOwnersByRevision = (state) => {
1488
- const owners = /* @__PURE__ */ new Map();
1489
- for (const [suggestionId, entry] of collectSuggestions(state)) for (const id of entry.revisionIds) if (!owners.has(id)) owners.set(id, suggestionId);
1490
- return owners;
1491
- };
1492
- /** The suggestion a revision belongs to, or `null` for an ordinary tracked change. */
1493
- function suggestionIdOfRevision(state, revisionId) {
1494
- for (const [suggestionId, entry] of collectSuggestions(state)) if (entry.revisionIds.has(revisionId)) return suggestionId;
1495
- return null;
1496
- }
1497
- /**
1498
- * The document range covering every mark belonging to `suggestionId`, plus the
1499
- * revision ids those marks carry. Returns null when the suggestion is absent
1500
- * (already accepted/rejected, or never existed).
1501
- */
1502
- function findSuggestionRange(state, suggestionId) {
1503
- const entry = collectSuggestions(state).get(suggestionId);
1504
- if (!entry || entry.segments.length === 0) return null;
1505
- const ranges = mergeSegments(entry.segments);
1506
- const from = ranges[0]?.from ?? 0;
1507
- return {
1508
- from,
1509
- to: ranges.at(-1)?.to ?? from,
1510
- revisionIds: [...entry.revisionIds]
1511
- };
1512
- }
1513
- /**
1514
- * Normalize an optional acceptance date to a canonical ISO 8601 string. Absent
1515
- * or unparseable input falls back to the current time — a malformed `w:date`
1516
- * must never reach the serialized document (fail-safe boundary validation).
1517
- */
1518
- const normalizeAcceptDate = (date) => {
1519
- if (date === void 0) return (/* @__PURE__ */ new Date()).toISOString();
1520
- const parsed = new Date(date);
1521
- return Number.isNaN(parsed.getTime()) ? (/* @__PURE__ */ new Date()).toISOString() : parsed.toISOString();
1522
- };
1523
- const acceptedParagraphMark = (node, author, date) => {
1524
- if (node.type.name !== "paragraph") return null;
1525
- const marker = node.attrs["_suggestedInsert"];
1526
- if (typeof marker !== "object" || marker === null || !("revisionId" in marker)) return null;
1527
- if (typeof marker.revisionId !== "number") return null;
1528
- const initials = "initials" in marker ? marker.initials : void 0;
1529
- return {
1530
- kind: "ins",
1531
- info: {
1532
- id: marker.revisionId,
1533
- author,
1534
- date,
1535
- ...typeof initials === "string" ? { initials } : {}
1536
- }
1537
- };
1538
- };
1539
- /**
1540
- * The node-attr patch that converts a suggested block/table revision into a
1541
- * normal (`"user"`) one authored by the accepting user. Returns `null` when the
1542
- * node carries no matching suggested revision. Position-stable (attr writes
1543
- * only), so callers can apply it during a single descendants walk.
1544
- */
1545
- const convertStructuralSuggestionAttrs = (node, author, date) => {
1546
- const attrs = node.attrs;
1547
- const userInfo = (marker) => {
1548
- const source = marker.info ?? marker;
1549
- return {
1550
- revisionId: source.revisionId,
1551
- author,
1552
- date,
1553
- ...typeof source.initials === "string" ? { initials: source.initials } : {}
1554
- };
1555
- };
1556
- const name = node.type.name;
1557
- const insertMarker = attrs["_suggestedInsert"];
1558
- if ((name === "paragraph" || name === "table") && typeof insertMarker === "object" && insertMarker !== null) {
1559
- if (name === "table") return {
1560
- ...attrs,
1561
- _suggestedInsert: null
1562
- };
1563
- const paragraphMark = acceptedParagraphMark(node, author, date);
1564
- if (paragraphMark) return {
1565
- ...attrs,
1566
- _suggestedInsert: null,
1567
- pPrMark: attrs["pPrMark"] ?? paragraphMark
1568
- };
1569
- }
1570
- if (node.type.name === "tableRow") {
1571
- if (readSuggestedMarker(attrs["trIns"])) return {
1572
- ...attrs,
1573
- trIns: userInfo(attrs["trIns"])
1574
- };
1575
- if (readSuggestedMarker(attrs["trDel"])) return {
1576
- ...attrs,
1577
- trDel: userInfo(attrs["trDel"])
1578
- };
1579
- }
1580
- if (node.type.name === "tableCell" || node.type.name === "tableHeader") {
1581
- const cellMarker = attrs["cellMarker"];
1582
- if (cellMarker && (cellMarker.kind === "ins" || cellMarker.kind === "del") && readSuggestedMarker(cellMarker.info)) return {
1583
- ...attrs,
1584
- cellMarker: {
1585
- kind: cellMarker.kind,
1586
- info: userInfo(cellMarker)
1587
- }
1588
- };
1589
- }
1590
- return null;
1591
- };
1592
- const reauthorParagraphPropertySuggestions = ({ node, matchesSuggestion, author, date }) => {
1593
- if (node.type.name !== "paragraph") return null;
1594
- const propertyChanges = expectParagraphAttrs(node)._propertyChanges;
1595
- if (!Array.isArray(propertyChanges)) return null;
1596
- let changed = false;
1597
- const next = propertyChanges.map((change) => {
1598
- const suggested = readSuggestedParagraphPropertyChange(change);
1599
- if (!suggested || !matchesSuggestion(suggested.suggestionId)) return change;
1600
- changed = true;
1601
- return Object.assign({}, change, { info: {
1602
- ...change.info,
1603
- author,
1604
- date,
1605
- provenance: "user",
1606
- suggestionId: null
1607
- } });
1608
- });
1609
- return changed ? next : null;
1610
- };
1611
- const canReauthorParagraphPropertySuggestions = (doc, matchesSuggestion) => {
1612
- let valid = true;
1613
- doc.descendants((node) => {
1614
- if (!valid || node.type.name !== "paragraph") return;
1615
- const propertyChanges = expectParagraphAttrs(node)._propertyChanges;
1616
- if (!Array.isArray(propertyChanges)) return;
1617
- let serializableCount = 0;
1618
- for (const change of propertyChanges) {
1619
- const suggested = readSuggestedParagraphPropertyChange(change);
1620
- if (!suggested || matchesSuggestion(suggested.suggestionId)) serializableCount++;
1621
- }
1622
- if (serializableCount > 1) {
1623
- valid = false;
1624
- return false;
1625
- }
1626
- });
1627
- return valid;
1628
- };
1629
- const appendRotatedParagraphPropertyChange = ({ tr, currentPosition, previous, mark, fallbackAuthor }) => {
1630
- const current = tr.doc.nodeAt(currentPosition);
1631
- if (!current || current.type.name !== "paragraph") return false;
1632
- const author = typeof mark.info.author === "string" ? mark.info.author : fallbackAuthor;
1633
- if (author === void 0) return false;
1634
- const existing = expectParagraphAttrs(current)._propertyChanges;
1635
- const suggestionId = mark.info.provenance === "suggested" && typeof mark.info.suggestionId === "string" ? mark.info.suggestionId : null;
1636
- if (suggestionId === null && hasSerializableParagraphPropertyChange(existing)) return false;
1637
- tr.setNodeMarkup(currentPosition, void 0, {
1638
- ...current.attrs,
1639
- _propertyChanges: [...Array.isArray(existing) ? existing : [], {
1640
- type: "paragraphPropertyChange",
1641
- info: {
1642
- id: mark.info.id,
1643
- author,
1644
- ...typeof mark.info.date === "string" ? { date: mark.info.date } : {},
1645
- ...typeof mark.info.initials === "string" ? { initials: mark.info.initials } : {},
1646
- ...suggestionId === null ? {} : {
1647
- provenance: "suggested",
1648
- suggestionId
1649
- }
1650
- },
1651
- previousFormatting: paragraphPropertiesSnapshot(previous)
1652
- }]
1653
- });
1654
- return true;
1655
- };
1656
- /**
1657
- * Shift a final run of inserted paragraph marks one paragraph to the left.
1658
- * The container-final paragraph stays markless, while every inserted
1659
- * paragraph keeps a same-revision property snapshot that makes targeted
1660
- * rejection restore the paragraph whose mark now carries its break.
1661
- */
1662
- const rotateAddedFinalParagraphBreaks = ({ tr, shouldRotate, fallbackAuthor }) => {
1663
- const paragraphTypeName = tr.doc.type.schema.nodes["paragraph"]?.name ?? "paragraph";
1664
- const finals = finalParagraphsOf(tr.doc, paragraphTypeName).filter(({ node, position }) => shouldRotate(node, position));
1665
- for (const { position: finalPosition } of finals) {
1666
- const final = tr.doc.nodeAt(finalPosition);
1667
- const finalMark = final?.attrs["pPrMark"];
1668
- if (!final || !isAddedPPrMarkAttr(finalMark)) continue;
1669
- tr.setNodeAttribute(finalPosition, "pPrMark", null);
1670
- if (!shiftAddedParagraphBreakBefore({
1671
- tr,
1672
- paragraphPosition: finalPosition,
1673
- mark: finalMark,
1674
- ...fallbackAuthor !== void 0 && { fallbackAuthor }
1675
- })) return false;
1676
- }
1677
- return true;
1678
- };
1679
- const rebaseRotatedParagraphPropertyChange = ({ tr, currentPosition, previous, revisionId }) => {
1680
- const current = tr.doc.nodeAt(currentPosition);
1681
- if (!current || current.type.name !== "paragraph") return false;
1682
- const existing = expectParagraphAttrs(current)._propertyChanges;
1683
- if (!Array.isArray(existing)) return false;
1684
- if (existing.filter(({ info }) => info.id === revisionId).length !== 1) return false;
1685
- tr.setNodeMarkup(currentPosition, void 0, {
1686
- ...current.attrs,
1687
- _propertyChanges: existing.map((change) => change.info.id === revisionId ? Object.assign({}, change, { previousFormatting: paragraphPropertiesSnapshot(previous) }) : change)
1688
- });
1689
- return true;
1690
- };
1691
- /**
1692
- * Rebase every property change in one rotated paragraph-break chain to the
1693
- * formatting of its original, leftmost carrier. A later targeted suggestion
1694
- * may extend an already-rotated chain, so normalizing only the newly shifted
1695
- * prefix would leave the serialized history dependent on acceptance order.
1696
- */
1697
- const rebaseAddedParagraphBreakChain = ({ tr, carrierPosition, previous }) => {
1698
- const carrier = tr.doc.nodeAt(carrierPosition);
1699
- if (!carrier || carrier.type.name !== "paragraph") return false;
1700
- const resolved = tr.doc.resolve(carrierPosition);
1701
- let current = carrier;
1702
- let nextPosition = carrierPosition + carrier.nodeSize;
1703
- for (let index = resolved.index() + 1; index < resolved.parent.childCount; index++) {
1704
- const currentMark = current.attrs["pPrMark"];
1705
- if (!isAddedPPrMarkAttr(currentMark)) return true;
1706
- const sibling = resolved.parent.child(index);
1707
- if (sibling.type.name !== carrier.type.name) {
1708
- if (sibling.type.spec["tableRole"] === "table") return false;
1709
- nextPosition += sibling.nodeSize;
1710
- continue;
1711
- }
1712
- if (!rebaseRotatedParagraphPropertyChange({
1713
- tr,
1714
- currentPosition: nextPosition,
1715
- previous,
1716
- revisionId: currentMark.info.id
1717
- })) return false;
1718
- const next = tr.doc.nodeAt(nextPosition);
1719
- if (!next || next.type.name !== carrier.type.name) return false;
1720
- current = next;
1721
- nextPosition += sibling.nodeSize;
1722
- }
1723
- return !isAddedPPrMarkAttr(current.attrs["pPrMark"]);
1724
- };
1725
- /**
1726
- * Insert an added paragraph break immediately before `paragraphPosition`.
1727
- * Existing added marks shift left as one chain until the first free carrier;
1728
- * each shifted mark keeps a property snapshot on the paragraph to its right.
1729
- */
1730
- const shiftAddedParagraphBreakBefore = ({ tr, paragraphPosition, mark, fallbackAuthor, firstPropertyChange = { type: "append" } }) => {
1731
- const paragraph = tr.doc.nodeAt(paragraphPosition);
1732
- if (!paragraph || paragraph.type.name !== "paragraph") return false;
1733
- const resolved = tr.doc.resolve(paragraphPosition);
1734
- const carrier = addedBreakCarrierBefore({
1735
- at: resolved,
1736
- paragraphTypeName: paragraph.type.name
1737
- });
1738
- if (!carrier) return false;
1739
- const path = [{
1740
- node: paragraph,
1741
- position: paragraphPosition
1742
- }];
1743
- let position = paragraphPosition;
1744
- for (let index = resolved.index() - 1; index >= 0; index--) {
1745
- const sibling = resolved.parent.child(index);
1746
- position -= sibling.nodeSize;
1747
- if (sibling.type.name !== paragraph.type.name) {
1748
- if (sibling.type.spec["tableRole"] === "table") break;
1749
- continue;
1750
- }
1751
- path.push({
1752
- node: sibling,
1753
- position
1754
- });
1755
- if (position === carrier.position) break;
1756
- }
1757
- if (path.at(-1)?.position !== carrier.position) return false;
1758
- const propertyChangeBaseline = carrier.node;
1759
- let carriedMark = mark;
1760
- for (let index = 1; index < path.length; index++) {
1761
- const current = path[index - 1];
1762
- const previous = path[index];
1763
- if (!current || !previous) return false;
1764
- const displacedMark = previous.node.attrs["pPrMark"];
1765
- tr.setNodeAttribute(previous.position, "pPrMark", carriedMark);
1766
- if (!(index === 1 && firstPropertyChange.type === "rebase" ? rebaseRotatedParagraphPropertyChange({
1767
- tr,
1768
- currentPosition: current.position,
1769
- previous: propertyChangeBaseline,
1770
- revisionId: firstPropertyChange.revisionId
1771
- }) : appendRotatedParagraphPropertyChange({
1772
- tr,
1773
- currentPosition: current.position,
1774
- previous: propertyChangeBaseline,
1775
- mark: carriedMark,
1776
- ...fallbackAuthor !== void 0 && { fallbackAuthor }
1777
- }))) return false;
1778
- if (displacedMark == null) return rebaseAddedParagraphBreakChain({
1779
- tr,
1780
- carrierPosition: carrier.position,
1781
- previous: propertyChangeBaseline
1782
- });
1783
- if (!isAddedPPrMarkAttr(displacedMark)) return false;
1784
- carriedMark = displacedMark;
1785
- }
1786
- return false;
1787
- };
1788
- /** A wholly suggested paragraph's break, as the inserted mark that records it. */
1789
- const suggestedParagraphBreakOf = (paragraph) => {
1790
- const structural = readStructuralSuggestion(paragraph);
1791
- if (structural?.kind !== "insertBlock") return null;
1792
- const marker = paragraph.attrs["_suggestedInsert"];
1793
- return {
1794
- kind: "ins",
1795
- info: {
1796
- id: structural.revisionId,
1797
- author: marker.author,
1798
- ...typeof marker.date === "string" ? { date: marker.date } : {},
1799
- ...typeof marker.initials === "string" ? { initials: marker.initials } : {},
1800
- provenance: "suggested",
1801
- suggestionId: structural.suggestionId
1802
- }
1803
- };
1804
- };
1805
- /**
1806
- * The suggested paragraph breaks a join of `paragraph` into `next` leaves
1807
- * with no mark to stand on.
1808
- *
1809
- * A wholly suggested paragraph's break is its own mark while that mark is
1810
- * free. Where another revision's mark stands there (the break of a paragraph
1811
- * inserted after it, or a deleted break it took over), the suggestion's break
1812
- * is the free mark before it, which is where accepting the suggestion writes
1813
- * it. A join that leaves the paragraph holding other words ends its
1814
- * whole-paragraph marker, so such a break must then be written there: the
1815
- * joined paragraph's mark is another revision's (the next side's own), or is
1816
- * gone (the side whose mark the join removes). The next side's break with a
1817
- * free mark is not among them: the joined mark records it (`joinedParagraphAttrs`).
1818
- */
1819
- const suggestedBreaksAJoinDisplaces = (paragraph, next) => {
1820
- const left = readStructuralSuggestion(paragraph);
1821
- const right = readStructuralSuggestion(next);
1822
- if (left?.kind === "insertBlock" && right?.kind === "insertBlock" && left.suggestionId === right.suggestionId) return [];
1823
- const displaced = [];
1824
- for (const side of [paragraph, next]) {
1825
- const suggested = suggestedParagraphBreakOf(side);
1826
- if (suggested === null || side.attrs["pPrMark"] == null) continue;
1827
- if (readSuggestedParagraphMark(side)?.suggestionId !== suggested.info.suggestionId) displaced.push(suggested);
1828
- }
1829
- return displaced;
1830
- };
1831
- /** The paragraph a join left at `position`, once `step` and every later step ran. */
1832
- const joinedParagraphAt = (tr, position, step) => {
1833
- const at = tr.mapping.slice(step).map(position);
1834
- if (tr.doc.nodeAt(at)?.type.name === "paragraph") return at;
1835
- const resolved = tr.doc.resolve(at);
1836
- return resolved.parent.type.name === "paragraph" ? resolved.before() : null;
1837
- };
1838
- /**
1839
- * Write the suggested breaks the joins of one resolution left without a mark.
1840
- *
1841
- * A wholly suggested paragraph whose own mark another revision holds has its
1842
- * break on the free mark before it: accepting the suggestion writes it there
1843
- * ({@link placeAcceptedParagraphBreakBefore}), and rejecting the suggestion
1844
- * takes that break out. A join that ends the paragraph's whole-paragraph
1845
- * marker has to write the break there, or rejecting the suggestion leaves its
1846
- * paragraph standing. A container's last paragraph carries no added break
1847
- * either, so a suggested one a join wrote there moves back the same way.
1848
- * After every join of the resolution, so no break lands on a mark it still
1849
- * resolves.
1850
- */
1851
- const placeSuggestedBreaksOfJoins = (tr, joins) => {
1852
- for (const { position: joinedAt, step, displaced } of joins) {
1853
- const position = joinedParagraphAt(tr, joinedAt, step);
1854
- const joined = position === null ? null : tr.doc.nodeAt(position);
1855
- if (position === null || !joined) continue;
1856
- const breaks = [...displaced];
1857
- const own = joined.attrs["pPrMark"];
1858
- const at = tr.doc.resolve(position);
1859
- if (isAddedPPrMarkAttr(own) && readSuggestedParagraphMark(joined) !== null && paragraphEndsItsContainer(at, joined.type.name) && addedBreakCarrierBefore({
1860
- at,
1861
- paragraphTypeName: joined.type.name
1862
- })) {
1863
- tr.setNodeAttribute(position, "pPrMark", null);
1864
- breaks.unshift(own);
1865
- }
1866
- for (const mark of breaks) if (!shiftAddedParagraphBreakBefore({
1867
- tr,
1868
- paragraphPosition: position,
1869
- mark
1870
- })) return false;
1871
- }
1872
- return true;
1873
- };
1874
- /**
1875
- * Place an accepted paragraph's break when its own break slot is taken: a
1876
- * following accepted insertion has rotated its break onto the paragraph, or
1877
- * the paragraph carries the break of the one it was inserted after, pending
1878
- * deletion. Either way that boundary stays, and the accepted break goes on
1879
- * the preceding free carrier.
1880
- */
1881
- const placeAcceptedParagraphBreakBefore = ({ tr, paragraphPosition, mark, fallbackAuthor }) => {
1882
- const paragraph = tr.doc.nodeAt(paragraphPosition);
1883
- const displaced = paragraph?.attrs["pPrMark"];
1884
- if (!paragraph || paragraph.type.name !== "paragraph" || !isPPrMarkAttr(displaced)) return false;
1885
- return shiftAddedParagraphBreakBefore({
1886
- tr,
1887
- paragraphPosition,
1888
- mark,
1889
- fallbackAuthor
1890
- });
1891
- };
1892
- /**
1893
- * Remember non-final added breaks before suggested nodes are removed. If one
1894
- * becomes final because of those removals, it must rotate with its own
1895
- * revision rather than remain as an unresolvable final mark.
1896
- */
1897
- const collectAddedBreakRotationCandidates = (doc) => {
1898
- const paragraphTypeName = doc.type.schema.nodes["paragraph"]?.name ?? "paragraph";
1899
- const finalPositions = new Set(finalParagraphsOf(doc, paragraphTypeName).map(({ position }) => position));
1900
- const candidates = [];
1901
- doc.descendants((node, position) => {
1902
- if (node.type.name !== paragraphTypeName || finalPositions.has(position)) return;
1903
- const mark = node.attrs["pPrMark"];
1904
- if (isPPrMarkAttr(mark) && paragraphMarkWasAdded(mark.kind)) candidates.push({
1905
- position,
1906
- revisionId: mark.info.id
1907
- });
1908
- });
1909
- return candidates;
1910
- };
1911
- const mappedRotationCandidatePredicate = ({ candidates, tr }) => {
1912
- const revisionIdsByPosition = /* @__PURE__ */ new Map();
1913
- for (const candidate of candidates) {
1914
- const mapped = tr.mapping.mapResult(candidate.position, 1);
1915
- if (mapped.deleted) continue;
1916
- const mappedPosition = mapped.pos;
1917
- const revisionIds = revisionIdsByPosition.get(mappedPosition) ?? /* @__PURE__ */ new Set();
1918
- revisionIds.add(candidate.revisionId);
1919
- revisionIdsByPosition.set(mappedPosition, revisionIds);
1920
- }
1921
- return (node, position) => {
1922
- const mark = node.attrs["pPrMark"];
1923
- return isPPrMarkAttr(mark) && paragraphMarkWasAdded(mark.kind) && revisionIdsByPosition.get(position)?.has(mark.info.id) === true;
1924
- };
1925
- };
1926
- /**
1927
- * Remove suggested nodes without removing another revision's paragraph break
1928
- * that stands on one of them.
1929
- *
1930
- * A suggested paragraph whose own mark another revision holds has its break
1931
- * on the free mark before it (see {@link placeSuggestedBreaksOfJoins}), so
1932
- * rejecting it takes that break out and the other revision's stays: it moves
1933
- * onto that mark. An added break (a following insertion's, rotated or placed
1934
- * there) shifts back as any added break does, its property snapshot rebased
1935
- * when a rotation recorded one; a removed break simply moves.
1936
- */
1937
- const removeSuggestedInsertNodes = ({ tr, positions, resolvedRevisionIds }) => {
1938
- for (const position of positions.toSorted((left, right) => right - left)) {
1939
- const node = tr.doc.nodeAt(position);
1940
- if (!node) continue;
1941
- const mark = node.attrs["pPrMark"];
1942
- const standingBreak = node.type.name === "paragraph" && isPPrMarkAttr(mark) && !resolvedRevisionIds.has(mark.info.id) ? mark : null;
1943
- tr.delete(position, position + node.nodeSize);
1944
- if (!standingBreak) continue;
1945
- if (!isAddedPPrMarkAttr(standingBreak)) {
1946
- moveRemovedBreakBefore(tr, position, standingBreak);
1947
- continue;
1948
- }
1949
- const following = tr.doc.nodeAt(position);
1950
- const recordedSnapshot = (following?.type.name === "paragraph" ? expectParagraphAttrs(following)._propertyChanges ?? [] : []).some(({ info }) => info.id === standingBreak.info.id);
1951
- if (!shiftAddedParagraphBreakBefore({
1952
- tr,
1953
- paragraphPosition: position,
1954
- mark: standingBreak,
1955
- ...recordedSnapshot && { firstPropertyChange: {
1956
- type: "rebase",
1957
- revisionId: standingBreak.info.id
1958
- } }
1959
- })) return false;
1960
- }
1961
- return true;
1962
- };
1963
- /**
1964
- * Put a removed break (`del`, `moveFrom`) that stood on a removed suggested
1965
- * paragraph on the free mark of the paragraph right before it. With none
1966
- * there, the break goes with the paragraph, as before.
1967
- */
1968
- const moveRemovedBreakBefore = (tr, position, mark) => {
1969
- const before = tr.doc.resolve(position).nodeBefore;
1970
- if (before?.type.name !== "paragraph" || before.attrs["pPrMark"] != null) return;
1971
- tr.setNodeAttribute(position - before.nodeSize, "pPrMark", mark);
1972
- };
1973
- /**
1974
- * Convert suggested marks AND block/table node revisions to normal (`"user"`)
1975
- * tracked changes. `matchesSuggestion(id)` selects which suggestion to convert
1976
- * (one id, or all).
1977
- */
1978
- const acceptSuggestions = (matchesSuggestion, options) => {
1979
- return (state, dispatch) => {
1980
- if (!canReauthorParagraphPropertySuggestions(state.doc, matchesSuggestion)) return false;
1981
- const insertionType = state.schema.marks["insertion"];
1982
- const deletionType = state.schema.marks["deletion"];
1983
- const runPropertyChangeType = state.schema.marks["runPropertyChange"];
1984
- const date = normalizeAcceptDate(options.date);
1985
- const tr = state.tr;
1986
- const acceptedParagraphBreaks = [];
1987
- let changed = false;
1988
- state.doc.descendants((node, pos) => {
1989
- const structural = readStructuralSuggestion(node);
1990
- let nextAttrs = null;
1991
- if (structural && matchesSuggestion(structural.suggestionId)) {
1992
- nextAttrs = convertStructuralSuggestionAttrs(node, options.author, date);
1993
- if (structural.kind === "insertBlock") {
1994
- const mark = acceptedParagraphMark(node, options.author, date);
1995
- if (!mark) return;
1996
- acceptedParagraphBreaks.push({
1997
- position: pos,
1998
- mark,
1999
- hadBreak: node.attrs["pPrMark"] != null
2000
- });
2001
- }
2002
- }
2003
- const propertyChanges = reauthorParagraphPropertySuggestions({
2004
- node,
2005
- matchesSuggestion,
2006
- author: options.author,
2007
- date
2008
- });
2009
- if (propertyChanges) nextAttrs = {
2010
- ...nextAttrs ?? node.attrs,
2011
- _propertyChanges: propertyChanges
2012
- };
2013
- const paragraphMark = node.attrs["pPrMark"];
2014
- if (isPPrMarkAttr(paragraphMark)) {
2015
- const accepted = (info) => {
2016
- const suggestionId = suggestionIdOfMarkRecord(info);
2017
- return suggestionId !== null && matchesSuggestion(suggestionId) ? {
2018
- ...info,
2019
- author: options.author,
2020
- date,
2021
- provenance: "user",
2022
- suggestionId: null
2023
- } : null;
2024
- };
2025
- const own = accepted(paragraphMark.info);
2026
- const { deletion: pendingDeletion } = paragraphMark;
2027
- const deletion = pendingDeletion === void 0 ? null : accepted(pendingDeletion.info);
2028
- if (own !== null || deletion !== null) nextAttrs = {
2029
- ...nextAttrs ?? node.attrs,
2030
- pPrMark: {
2031
- ...paragraphMark,
2032
- ...own === null ? {} : { info: own },
2033
- ...deletion === null || pendingDeletion === void 0 ? {} : { deletion: {
2034
- ...pendingDeletion,
2035
- info: deletion
2036
- } }
2037
- }
2038
- };
2039
- }
2040
- if (nextAttrs) {
2041
- tr.setNodeMarkup(pos, void 0, nextAttrs);
2042
- changed = true;
2043
- }
2044
- if (!node.isInline) return;
2045
- const from = pos;
2046
- const to = pos + node.nodeSize;
2047
- for (const mark of node.marks) {
2048
- if (!isSuggestionMark(mark) || typeof mark.attrs["suggestionId"] !== "string" || !matchesSuggestion(mark.attrs["suggestionId"])) continue;
2049
- changed = true;
2050
- tr.removeMark(from, to, mark);
2051
- if (mark.type === runPropertyChangeType) {
2052
- const nextChanges = [];
2053
- for (const change of expectRunPropertyChangeMarkAttrs(mark).changes) nextChanges.push({
2054
- ...change,
2055
- info: {
2056
- ...change.info,
2057
- author: options.author,
2058
- date
2059
- }
2060
- });
2061
- tr.addMark(from, to, mark.type.create({
2062
- changes: nextChanges,
2063
- provenance: "user",
2064
- suggestionId: null
2065
- }));
2066
- continue;
2067
- }
2068
- if (mark.type === insertionType || mark.type === deletionType) tr.addMark(from, to, mark.type.create({
2069
- ...mark.attrs,
2070
- author: options.author,
2071
- date,
2072
- provenance: "user",
2073
- suggestionId: null
2074
- }));
2075
- }
2076
- });
2077
- for (const accepted of acceptedParagraphBreaks) if (accepted.hadBreak && !placeAcceptedParagraphBreakBefore({
2078
- tr,
2079
- paragraphPosition: accepted.position,
2080
- mark: accepted.mark,
2081
- fallbackAuthor: options.author
2082
- })) return false;
2083
- const directlyMarkedParagraphPositions = new Set(acceptedParagraphBreaks.filter(({ hadBreak }) => !hadBreak).map(({ position }) => position));
2084
- if (directlyMarkedParagraphPositions.size > 0 && !rotateAddedFinalParagraphBreaks({
2085
- tr,
2086
- shouldRotate: (_node, position) => directlyMarkedParagraphPositions.has(position),
2087
- fallbackAuthor: options.author
2088
- })) return false;
2089
- if (resolveSuggestedCommentMarks(tr, matchesSuggestion, true)) changed = true;
2090
- if (!changed) return false;
2091
- if (dispatch) {
2092
- finishResolution(state, tr);
2093
- dispatch(tr);
2094
- }
2095
- return true;
2096
- };
2097
- };
2098
- /**
2099
- * Accept one suggestion: convert its inline marks and block/table node
2100
- * revisions into normal tracked changes authored by `author`, keeping revision
2101
- * ids. A whole inserted table (which OOXML cannot track) is applied directly;
2102
- * everything else becomes a tracked change. See {@link getSuggestions} for the
2103
- * per-suggestion `appliedAs`.
2104
- */
2105
- function acceptSuggestion(suggestionId, options) {
2106
- return acceptSuggestions((id) => id === suggestionId, options);
2107
- }
2108
- /** Accept every suggestion in the document. */
2109
- function acceptAllSuggestions(options) {
2110
- return acceptSuggestions(() => true, options);
2111
- }
2112
- /**
2113
- * Reject one suggestion: inverse-apply it in a single transaction. Runs BOTH
2114
- * phases so a heterogeneous group (one `suggestionId` spanning whole-node
2115
- * inserts AND other edits) is fully resolved:
2116
- * 1. inline marks and suggested `trIns`/`trDel`/`cellMarker` revisions are
2117
- * inverse-applied through {@link resolveChange} (delete suggested-inserted
2118
- * text/rows/cells, drop suggested deletions/formatting);
2119
- * 2. any remaining whole-node inserts (paragraph/table) are then deleted,
2120
- * mapped through the accumulated transaction so positions stay valid.
2121
- *
2122
- * A paragraph whole-node insert carries inline marks with the same revision id,
2123
- * so phase 1 empties its text and phase 2 removes the now-empty node; a whole
2124
- * inserted table has no matching revision, so only phase 2 removes it.
2125
- */
2126
- function rejectSuggestion(suggestionId) {
2127
- return (state, dispatch) => {
2128
- const entry = collectSuggestions(state).get(suggestionId);
2129
- if (!entry) return false;
2130
- const rotationCandidates = entry.kinds.has("insertBlock") || entry.kinds.has("insertTable") ? collectAddedBreakRotationCandidates(state.doc) : [];
2131
- let tr = null;
2132
- if (entry.revisionIds.size > 0) {
2133
- const ranges = mergeSegments(entry.segments);
2134
- const from = ranges[0]?.from ?? 0;
2135
- resolveChangeUnguarded(from, ranges.at(-1)?.to ?? from, "reject", [...entry.revisionIds])(state, (resolved) => {
2136
- tr = resolved;
2137
- });
2138
- }
2139
- const workingTr = tr ?? state.tr;
2140
- const positions = [];
2141
- const rejected = {
2142
- mode: "reject",
2143
- resolves: (revisionId) => entry.revisionIds.has(revisionId)
2144
- };
2145
- workingTr.doc.descendants((node, pos) => {
2146
- if (rejectionRemovesWholeNode(node, rejected) && readStructuralSuggestion(node)?.suggestionId === suggestionId) positions.push(pos);
2147
- });
2148
- if (!removeSuggestedInsertNodes({
2149
- tr: workingTr,
2150
- positions,
2151
- resolvedRevisionIds: entry.revisionIds
2152
- })) return false;
2153
- if (positions.length > 0 && rotationCandidates.length > 0 && !rotateAddedFinalParagraphBreaks({
2154
- tr: workingTr,
2155
- shouldRotate: mappedRotationCandidatePredicate({
2156
- candidates: rotationCandidates,
2157
- tr: workingTr
2158
- })
2159
- })) return false;
2160
- resolveSuggestedCommentMarks(workingTr, (id) => id === suggestionId, false);
2161
- if (workingTr.steps.length === 0) return false;
2162
- if (dispatch) {
2163
- finishResolution(state, workingTr);
2164
- dispatch(workingTr);
2165
- }
2166
- return true;
2167
- };
2168
- }
2169
- /** Reject every suggestion in the document. */
2170
- function rejectAllSuggestions() {
2171
- return (state, dispatch) => {
2172
- const bySuggestion = collectSuggestions(state);
2173
- if (bySuggestion.size === 0) return false;
2174
- const revisionIds = /* @__PURE__ */ new Set();
2175
- let removesWholeNode = false;
2176
- for (const entry of bySuggestion.values()) {
2177
- removesWholeNode ||= entry.kinds.has("insertBlock") || entry.kinds.has("insertTable");
2178
- for (const id of entry.revisionIds) revisionIds.add(id);
2179
- }
2180
- const rotationCandidates = removesWholeNode ? collectAddedBreakRotationCandidates(state.doc) : [];
2181
- let tr = null;
2182
- if (revisionIds.size > 0) resolveChangeUnguarded(0, state.doc.content.size, "reject", [...revisionIds])(state, (resolved) => {
2183
- tr = resolved;
2184
- });
2185
- const workingTr = tr ?? state.tr;
2186
- const positions = [];
2187
- const rejected = {
2188
- mode: "reject",
2189
- resolves: (revisionId) => revisionIds.has(revisionId)
2190
- };
2191
- workingTr.doc.descendants((node, pos) => {
2192
- if (rejectionRemovesWholeNode(node, rejected)) positions.push(pos);
2193
- });
2194
- if (!removeSuggestedInsertNodes({
2195
- tr: workingTr,
2196
- positions,
2197
- resolvedRevisionIds: revisionIds
2198
- })) return false;
2199
- if (positions.length > 0 && rotationCandidates.length > 0 && !rotateAddedFinalParagraphBreaks({
2200
- tr: workingTr,
2201
- shouldRotate: mappedRotationCandidatePredicate({
2202
- candidates: rotationCandidates,
2203
- tr: workingTr
2204
- })
2205
- })) return false;
2206
- resolveSuggestedCommentMarks(workingTr, () => true, false);
2207
- if (workingTr.steps.length === 0) return false;
2208
- if (dispatch) {
2209
- finishResolution(state, workingTr);
2210
- dispatch(workingTr);
2211
- }
2212
- return true;
2213
- };
2214
- }
2215
- /**
2216
- * The story with every pending suggestion rejected: what a save writes, what a
2217
- * read of the saved package shows and what rejecting every change starts from.
2218
- *
2219
- * One rejection resolves each suggestion's revisions against a story the
2220
- * others still stand in. Where a paragraph break it takes out joins into, or
2221
- * is displaced onto, another rejected suggestion's paragraph, that suggestion
2222
- * is left holding a break of its own; the rejection runs again until no
2223
- * suggestion is left, so the story never keeps a rejected break.
2224
- */
2225
- const rejectEverySuggestion = (state) => rejectEverySuggestionMapped(state).state;
2226
- /** {@link rejectEverySuggestion}, with where each position of `state` ends. */
2227
- const rejectEverySuggestionMapped = (state) => {
2228
- const mapping = new Mapping();
2229
- const count = collectSuggestions(state).size;
2230
- let settled = state;
2231
- if (count === 0) return {
2232
- state: settled,
2233
- mapping
2234
- };
2235
- for (let rounds = count; rounds >= 0; rounds -= 1) {
2236
- const next = rejectSuggestionsOnce(settled);
2237
- if (next === null) break;
2238
- mapping.appendMapping(next.mapping);
2239
- settled = next.state;
2240
- }
2241
- return {
2242
- state: settled,
2243
- mapping
2244
- };
2245
- };
2246
- /** One `rejectAllSuggestions` over `state`; `null` when nothing was left to reject. */
2247
- const rejectSuggestionsOnce = (state) => {
2248
- const settled = {
2249
- state,
2250
- mapping: new Mapping()
2251
- };
2252
- return rejectAllSuggestions()(state, (transaction) => {
2253
- settled.state = state.apply(transaction);
2254
- settled.mapping = transaction.mapping;
2255
- }) ? settled : null;
2256
- };
2257
- const pairedReplacementRangesByDoc = /* @__PURE__ */ new WeakMap();
2258
- const pairedReplacementRanges = (state) => {
2259
- const cached = pairedReplacementRangesByDoc.get(state.doc);
2260
- if (cached) return cached;
2261
- const ranges = [];
2262
- const { entries } = extractTrackedChanges(state);
2263
- for (const entry of entries) {
2264
- if (entry.type !== "replacement" || entry.insertionRevisionId === void 0) continue;
2265
- ranges.push({
2266
- from: entry.from,
2267
- to: entry.to
2268
- });
2269
- }
2270
- pairedReplacementRangesByDoc.set(state.doc, ranges);
2271
- return ranges;
2272
- };
2273
- const pairedReplacementRangeAt = ({ ranges, from, to }) => {
2274
- let low = 0;
2275
- let high = ranges.length;
2276
- while (low < high) {
2277
- const middle = Math.floor((low + high) / 2);
2278
- if (ranges[middle].from <= from) low = middle + 1;
2279
- else high = middle;
2280
- }
2281
- const candidate = ranges[low - 1];
2282
- return candidate && from >= candidate.from && to <= candidate.to ? candidate : void 0;
2283
- };
2284
- /**
2285
- * Find the tracked change mark range at a given cursor position.
2286
- * If the cursor is inside a tracked change, returns the full extent
2287
- * of that mark (expanding to cover all adjacent nodes with the same
2288
- * revision ID). If from !== to (range selection), returns {from, to}.
2289
- */
2290
- function findChangeAtPosition(state, from, to) {
2291
- if (from !== to) return {
2292
- from,
2293
- to
2294
- };
2295
- const insertionType = state.schema.marks["insertion"];
2296
- const deletionType = state.schema.marks["deletion"];
2297
- if (!insertionType && !deletionType) return {
2298
- from,
2299
- to
2300
- };
2301
- const $pos = state.doc.resolve(from);
2302
- const node = $pos.parent;
2303
- if (!node.inlineContent) return {
2304
- from,
2305
- to
2306
- };
2307
- let markStart = from;
2308
- let markEnd = from;
2309
- let foundMark;
2310
- node.forEach((child, offset) => {
2311
- const childStart = $pos.start() + offset;
2312
- const childEnd = childStart + child.nodeSize;
2313
- if (from >= childStart && from <= childEnd && child.isText) {
2314
- for (const mark of child.marks) if (mark.type === insertionType || mark.type === deletionType) {
2315
- foundMark = mark;
2316
- markStart = childStart;
2317
- markEnd = childEnd;
2318
- }
2319
- }
2320
- });
2321
- if (foundMark === void 0) {
2322
- const paragraphChange = findParagraphBoundaryChangeAtPosition(state, from);
2323
- return paragraphChange ? {
2324
- from: paragraphChange.from,
2325
- to: paragraphChange.to
2326
- } : {
2327
- from,
2328
- to
2329
- };
2330
- }
2331
- const sameMark = foundMark;
2332
- const children = [];
2333
- node.forEach((child, offset) => {
2334
- if (!child.isText) return;
2335
- const childStart = $pos.start() + offset;
2336
- children.push({
2337
- childStart,
2338
- childEnd: childStart + child.nodeSize,
2339
- marks: child.marks
2340
- });
2341
- });
2342
- let extended = true;
2343
- while (extended) {
2344
- extended = false;
2345
- for (const child of children) {
2346
- if (!child.marks.some((m) => m.eq(sameMark))) continue;
2347
- if (child.childEnd === markStart) {
2348
- markStart = child.childStart;
2349
- extended = true;
2350
- }
2351
- if (child.childStart === markEnd) {
2352
- markEnd = child.childEnd;
2353
- extended = true;
2354
- }
2355
- }
2356
- }
2357
- return {
2358
- from: markStart,
2359
- to: markEnd
2360
- };
2361
- }
2362
- /**
2363
- * Walk outward from `[fromHint, toHint]` and return the full extent of the
2364
- * tracked-change span carrying `mark` (matched via `Mark.eq`, so attrs like
2365
- * `revisionId` distinguish adjacent changes). Used to keep the
2366
- * navigation/scroll helpers honest when a tracked-change span is split
2367
- * across multiple text nodes due to inline formatting (e.g., a bold word
2368
- * inside an insertion).
2369
- */
2370
- function expandTrackedChangeRange(state, mark, fromHint, toHint) {
2371
- const carriesSameInlineMark = (node) => node?.isInline === true && node.marks.some((m) => m.eq(mark));
2372
- let from = fromHint;
2373
- let to = toHint;
2374
- const revisionId = mark.attrs["revisionId"];
2375
- for (;;) {
2376
- let $from = state.doc.resolve(from);
2377
- let nodeBefore = $from.nodeBefore;
2378
- while (carriesSameInlineMark(nodeBefore)) {
2379
- from -= nodeBefore.nodeSize;
2380
- $from = state.doc.resolve(from);
2381
- nodeBefore = $from.nodeBefore;
2382
- }
2383
- let $to = state.doc.resolve(to);
2384
- let nodeAfter = $to.nodeAfter;
2385
- while (carriesSameInlineMark(nodeAfter)) {
2386
- to += nodeAfter.nodeSize;
2387
- $to = state.doc.resolve(to);
2388
- nodeAfter = $to.nodeAfter;
2389
- }
2390
- const control = $from.parent;
2391
- if (control.type.name !== "sdt" || typeof revisionId !== "number" || !enclosingRevisionIds(control).includes(revisionId) || from !== $from.start() || to !== $from.end()) return {
2392
- from,
2393
- to
2394
- };
2395
- from = $from.before();
2396
- to = $from.after();
2397
- }
2398
- }
2399
- /**
2400
- * Find the next tracked change after the given position. Returns the full
2401
- * range of the change (including adjacent text nodes that share the same
2402
- * insertion/deletion mark instance), not just the first text node.
2403
- */
2404
- function findNextChange(state, startPos) {
2405
- const insertionType = state.schema.marks["insertion"];
2406
- const deletionType = state.schema.marks["deletion"];
2407
- if (!insertionType && !deletionType) return null;
2408
- const replacementRanges = pairedReplacementRanges(state);
2409
- const result = { value: null };
2410
- state.doc.descendants((node, pos) => {
2411
- if (result.value) return false;
2412
- if (!node.isInline) return;
2413
- if (pos + node.nodeSize <= startPos) return;
2414
- for (const mark of node.marks) if (mark.type === insertionType || mark.type === deletionType) {
2415
- const expanded = pairedReplacementRangeAt({
2416
- ranges: replacementRanges,
2417
- from: pos,
2418
- to: pos + node.nodeSize
2419
- }) ?? expandTrackedChangeRange(state, mark, pos, pos + node.nodeSize);
2420
- result.value = {
2421
- from: expanded.from,
2422
- to: expanded.to,
2423
- type: mark.type === insertionType ? "insertion" : "deletion"
2424
- };
2425
- return false;
2426
- }
2427
- });
2428
- if (result.value === null && startPos > 0) return findNextChange(state, 0);
2429
- return result.value;
2430
- }
2431
- /**
2432
- * Find the previous tracked change before the given position. Returns the
2433
- * full range of the change (including adjacent text nodes that share the
2434
- * same insertion/deletion mark instance), not just the last text node.
2435
- */
2436
- function findPreviousChange(state, startPos) {
2437
- const insertionType = state.schema.marks["insertion"];
2438
- const deletionType = state.schema.marks["deletion"];
2439
- if (!insertionType && !deletionType) return null;
2440
- const replacementRanges = pairedReplacementRanges(state);
2441
- const result = { value: null };
2442
- let resultMark = null;
2443
- state.doc.descendants((node, pos) => {
2444
- if (!node.isInline) return;
2445
- if (pos >= startPos) return false;
2446
- if (result.value && resultMark && pos < result.value.to && node.marks.every((m) => m.type !== insertionType && m.type !== deletionType || m.eq(resultMark))) return;
2447
- for (const mark of node.marks) if (mark.type === insertionType || mark.type === deletionType) {
2448
- const expanded = pairedReplacementRangeAt({
2449
- ranges: replacementRanges,
2450
- from: pos,
2451
- to: pos + node.nodeSize
2452
- }) ?? expandTrackedChangeRange(state, mark, pos, pos + node.nodeSize);
2453
- result.value = {
2454
- from: expanded.from,
2455
- to: expanded.to,
2456
- type: mark.type === insertionType ? "insertion" : "deletion"
2457
- };
2458
- resultMark = mark;
2459
- }
2460
- });
2461
- if (result.value === null && startPos < state.doc.content.size) return findPreviousChange(state, state.doc.content.size);
2462
- return result.value;
2463
- }
2464
- export { acceptAIEditRevision, acceptAllChanges, acceptAllSuggestions, acceptChange, acceptSuggestion, addCommentMark, changeResolutionLockViolation, findAIEditRevisionRange, findChangeAtPosition, findNextChange, findParagraphBoundaryChangeAtPosition, findPreviousChange, findSuggestionRange, getSuggestions, lockHeldRevisions, pendingSuggestionRevisionIds, projectAllChangesInHeadlessState, rejectAIEditRevision, rejectAllChanges, rejectAllSuggestions, rejectChange, rejectEverySuggestion, rejectEverySuggestionMapped, rejectSuggestion, removeCommentMark, resolveAllChangesInHeadlessState, resolveAllChangesInHeadlessStateWithMapping, revisionResolutionLockViolation, suggestionCommentIds, suggestionIdOfRevision, suggestionOwnersByRevision, trackedChangeEntryRevisionIds };
1
+ import { addCommentMark, findChangeAtPosition, findNextChange, findParagraphBoundaryChangeAtPosition, findPreviousChange, removeCommentMark, trackedChangeEntryRevisionIds } from "../projectionReview.js";
2
+ import { isPPrMarkAttr, paragraphMarkWasAdded } from "../revisionCarriers.js";
3
+ import { findAIEditRevisionRange, isTableCellRevisionAttr, isTableRowRevisionAttr } from "../revisionRangeQueries.js";
4
+ import { collectSuggestions, findSuggestionRange, getSuggestions, isSuggestionMark, mergeSegments, pendingSuggestionRevisionIds, readStructuralSuggestion, readSuggestedMarker, readSuggestedParagraphMark, readSuggestedParagraphPropertyChange, suggestedCommentOf, suggestionCommentIds, suggestionIdOfMarkRecord, suggestionIdOfRevision, suggestionOwnersByRevision } from "../suggestionQueries.js";
5
+ export { addCommentMark, collectSuggestions, findAIEditRevisionRange, findChangeAtPosition, findNextChange, findParagraphBoundaryChangeAtPosition, findPreviousChange, findSuggestionRange, getSuggestions, isPPrMarkAttr, isSuggestionMark, isTableCellRevisionAttr, isTableRowRevisionAttr, mergeSegments, paragraphMarkWasAdded, pendingSuggestionRevisionIds, readStructuralSuggestion, readSuggestedMarker, readSuggestedParagraphMark, readSuggestedParagraphPropertyChange, removeCommentMark, suggestedCommentOf, suggestionCommentIds, suggestionIdOfMarkRecord, suggestionIdOfRevision, suggestionOwnersByRevision, trackedChangeEntryRevisionIds };