@stll/folio-core 0.68.0 → 0.69.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 (177) hide show
  1. package/dist/ai-edits/headless.js +2 -2
  2. package/dist/ai-edits/newListNumbering.d.ts +14 -1
  3. package/dist/ai-edits/newListNumbering.js +24 -1
  4. package/dist/ai-edits/pending-suggestions.js +2 -2
  5. package/dist/controller/canonicalClipboard.js +2 -2
  6. package/dist/controller/canonicalComposition.js +34 -5
  7. package/dist/controller/canonicalInput.js +4 -6
  8. package/dist/controller/canonicalLockGuard.d.ts +17 -2
  9. package/dist/controller/canonicalLockGuard.js +46 -1
  10. package/dist/controller/canonicalProjectionBlocks.d.ts +79 -0
  11. package/dist/controller/canonicalProjectionBlocks.js +75 -0
  12. package/dist/controller/canonicalPublicOperations.js +476 -100
  13. package/dist/controller/canonicalSeedContent.d.ts +12 -0
  14. package/dist/controller/canonicalSeedContent.js +131 -0
  15. package/dist/controller/canonicalSession.d.ts +53 -21
  16. package/dist/controller/canonicalSession.js +489 -210
  17. package/dist/controller/canonicalSourceNormalization.d.ts +21 -0
  18. package/dist/controller/canonicalSourceNormalization.js +148 -0
  19. package/dist/controller/canonicalStoryEditor.d.ts +1 -1
  20. package/dist/controller/canonicalStoryEditor.js +16 -12
  21. package/dist/controller/folioEditor.js +3 -0
  22. package/dist/controller/headerFooterEditorManager.d.ts +5 -0
  23. package/dist/controller/headerFooterEditorManager.js +7 -2
  24. package/dist/controller/hiddenEditorApi.d.ts +11 -2
  25. package/dist/controller/hiddenEditorApi.js +3 -0
  26. package/dist/controller/hiddenEditorManager.d.ts +7 -0
  27. package/dist/controller/hiddenEditorManager.js +66 -11
  28. package/dist/controller/layoutPipeline.js +2 -1
  29. package/dist/controller/layoutSession.d.ts +3 -0
  30. package/dist/controller/layoutSession.js +3 -1
  31. package/dist/controller/noteEditorManager.d.ts +5 -0
  32. package/dist/controller/noteEditorManager.js +7 -2
  33. package/dist/display-list/dom/renderDisplayListToDom.js +9 -7
  34. package/dist/document-operations.d.ts +1 -1
  35. package/dist/docx/canonicalSave.js +7 -2
  36. package/dist/docx/commentAnchorIndex.d.ts +19 -0
  37. package/dist/docx/commentAnchorIndex.js +55 -1
  38. package/dist/docx/containerChildren.js +1 -1
  39. package/dist/docx/contentTypeRegistry.js +1 -1
  40. package/dist/docx/hostCommentThreads.d.ts +11 -1
  41. package/dist/docx/hostCommentThreads.js +25 -2
  42. package/dist/docx/listModelNormalization.js +4 -5
  43. package/dist/docx/listNumberingInstances.d.ts +1 -1
  44. package/dist/docx/listNumberingInstances.js +2 -2
  45. package/dist/docx/numberingIds.d.ts +6 -0
  46. package/dist/docx/numberingIds.js +6 -1
  47. package/dist/docx/numberingReferenceNormalization.d.ts +4 -0
  48. package/dist/docx/numberingReferenceNormalization.js +12 -2
  49. package/dist/docx/paragraphPropertySource.d.ts +22 -0
  50. package/dist/docx/paragraphPropertySource.js +85 -16
  51. package/dist/docx/parser.js +2 -0
  52. package/dist/docx/removeHeaderFooterParts.js +1 -1
  53. package/dist/docx/reviewResolutionProvenance.js +72 -19
  54. package/dist/docx/serializer/documentSerializer.js +2 -1
  55. package/dist/docx/serializer/partNamespaces.d.ts +1 -1
  56. package/dist/docx/serializer/partNamespaces.js +1 -1
  57. package/dist/docx/server/build.d.ts +1 -1
  58. package/dist/docx/storyBlockReplay.js +15 -2
  59. package/dist/docx/structuralXmlPatch.js +25 -4
  60. package/dist/docx/xmlParser.d.ts +1 -1
  61. package/dist/docx/xmlParser.js +2 -3
  62. package/dist/i18n/messages/ar.gen.js +1 -0
  63. package/dist/i18n/messages/catalogs.gen.d.ts +17 -0
  64. package/dist/i18n/messages/catalogs.gen.js +17 -0
  65. package/dist/i18n/messages/cs.gen.js +1 -0
  66. package/dist/i18n/messages/de.gen.js +1 -0
  67. package/dist/i18n/messages/en.gen.js +1 -0
  68. package/dist/i18n/messages/es.gen.js +1 -0
  69. package/dist/i18n/messages/et.gen.js +1 -0
  70. package/dist/i18n/messages/fr.gen.js +1 -0
  71. package/dist/i18n/messages/he.gen.js +1 -0
  72. package/dist/i18n/messages/hi.gen.js +1 -0
  73. package/dist/i18n/messages/hu.gen.js +1 -0
  74. package/dist/i18n/messages/lt.gen.js +1 -0
  75. package/dist/i18n/messages/lv.gen.js +1 -0
  76. package/dist/i18n/messages/messages.gen.d.ts +1 -0
  77. package/dist/i18n/messages/pl.gen.js +1 -0
  78. package/dist/i18n/messages/pt-BR.gen.js +1 -0
  79. package/dist/i18n/messages/sk.gen.js +1 -0
  80. package/dist/i18n/messages/tr.gen.js +1 -0
  81. package/dist/i18n/messages/zh-CN.gen.js +1 -0
  82. package/dist/internal/pageBreakRunDescendantIndex.d.ts +7 -2
  83. package/dist/internal/pageBreakRunDescendantIndex.js +12 -3
  84. package/dist/internal/subtreeHolds.d.ts +12 -0
  85. package/dist/internal/subtreeHolds.js +25 -0
  86. package/dist/internal/wholeStoryRevisionResolution.js +1 -1
  87. package/dist/layout-bridge/cellSelectionHighlight.js +3 -3
  88. package/dist/layout-bridge/convert/flowBlockPostprocessing.js +20 -12
  89. package/dist/layout-bridge/convert/flowConversionShared.d.ts +15 -1
  90. package/dist/layout-bridge/convert/flowConversionShared.js +9 -1
  91. package/dist/layout-bridge/convert/paragraphAttrs.d.ts +15 -4
  92. package/dist/layout-bridge/convert/paragraphAttrs.js +11 -4
  93. package/dist/layout-bridge/convert/paragraphBlockCache.d.ts +26 -0
  94. package/dist/layout-bridge/convert/paragraphBlockCache.js +137 -0
  95. package/dist/layout-bridge/convert/paragraphConversion.d.ts +12 -2
  96. package/dist/layout-bridge/convert/paragraphConversion.js +37 -5
  97. package/dist/layout-bridge/convert/paragraphRuns.d.ts +2 -2
  98. package/dist/layout-bridge/convert/sectionBoundaries.js +16 -0
  99. package/dist/layout-bridge/convert/toFlowBlocks.js +144 -15
  100. package/dist/layout-bridge/convert/topLevelConversion.d.ts +74 -0
  101. package/dist/layout-bridge/convert/topLevelConversion.js +109 -0
  102. package/dist/layout-bridge/dom/clickToPositionDom.js +41 -40
  103. package/dist/layout-bridge/dom/findBodyPmSpans.js +4 -3
  104. package/dist/layout-bridge/dom/findHfPmSpans.js +10 -15
  105. package/dist/layout-bridge/dom/imeCaretAnchor.d.ts +8 -0
  106. package/dist/layout-bridge/dom/imeCaretAnchor.js +71 -7
  107. package/dist/layout-bridge/dom/textStreamDom.js +3 -2
  108. package/dist/layout-bridge/headerFooterLayout.js +12 -11
  109. package/dist/layout-bridge/tableInsertHover.js +2 -1
  110. package/dist/layout-engine/measure/cache.d.ts +2 -0
  111. package/dist/layout-engine/measure/cache.js +6 -1
  112. package/dist/layout-engine/measure/paragraphKeyMemo.d.ts +8 -0
  113. package/dist/layout-engine/measure/paragraphKeyMemo.js +92 -0
  114. package/dist/layout-engine/types.d.ts +6 -0
  115. package/dist/layout-painter/imageLayout.js +2 -1
  116. package/dist/layout-painter/pageShellStyles.d.ts +10 -0
  117. package/dist/layout-painter/pageShellStyles.js +32 -0
  118. package/dist/layout-painter/reconcileRenderedContent.d.ts +19 -0
  119. package/dist/layout-painter/reconcileRenderedContent.js +117 -0
  120. package/dist/layout-painter/renderFragment.js +4 -6
  121. package/dist/layout-painter/renderImage.js +2 -2
  122. package/dist/layout-painter/renderPage.js +8 -29
  123. package/dist/layout-painter/renderParagraph.js +3 -3
  124. package/dist/layout-painter/renderTable.js +9 -12
  125. package/dist/layout-painter/renderTextBox.js +2 -2
  126. package/dist/layout-painter/sdtBoundary.js +3 -2
  127. package/dist/paged-layout/blockGeometry.js +3 -2
  128. package/dist/paged-layout/editorScrollRoot.d.ts +9 -0
  129. package/dist/paged-layout/editorScrollRoot.js +10 -1
  130. package/dist/paged-layout/rangeProjection.js +5 -4
  131. package/dist/paged-layout/scrollToPmPosition.js +3 -3
  132. package/dist/paged-layout/selectionViewportRect.d.ts +6 -0
  133. package/dist/paged-layout/selectionViewportRect.js +8 -2
  134. package/dist/prosemirror/attrs/index.js +1 -0
  135. package/dist/prosemirror/commands/comments.d.ts +5 -2
  136. package/dist/prosemirror/commands/comments.js +88 -8
  137. package/dist/prosemirror/commentRecords.d.ts +137 -0
  138. package/dist/prosemirror/commentRecords.js +400 -0
  139. package/dist/prosemirror/conversion/fromProseDoc.js +9 -3
  140. package/dist/prosemirror/conversion/index.d.ts +1 -1
  141. package/dist/prosemirror/conversion/toProseDoc.d.ts +13 -4
  142. package/dist/prosemirror/conversion/toProseDoc.js +126 -38
  143. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +22 -0
  144. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +61 -32
  145. package/dist/prosemirror/extensions/marks/CommentExtension.js +3 -1
  146. package/dist/prosemirror/extensions/nodes/CommentReferenceExtension.js +3 -1
  147. package/dist/prosemirror/index.d.ts +1 -1
  148. package/dist/prosemirror/nativeSelection.d.ts +33 -0
  149. package/dist/prosemirror/nativeSelection.js +74 -0
  150. package/dist/prosemirror/numberedRefFields.d.ts +2 -0
  151. package/dist/prosemirror/numberedRefFields.js +16 -5
  152. package/dist/prosemirror/paragraphMarkJoin.d.ts +6 -8
  153. package/dist/prosemirror/paragraphMarkJoin.js +155 -16
  154. package/dist/prosemirror/plugins/contentControlWidgets.js +2 -2
  155. package/dist/prosemirror/plugins/documentNumbering.js +33 -14
  156. package/dist/prosemirror/plugins/suggestionMode.js +13 -1
  157. package/dist/prosemirror/runIdentityAcrossRevisions.d.ts +23 -1
  158. package/dist/prosemirror/runIdentityAcrossRevisions.js +57 -8
  159. package/dist/prosemirror/schema/marks.d.ts +7 -1
  160. package/dist/prosemirror/storyListNumbering.js +7 -2
  161. package/dist/prosemirror/tableResize.d.ts +10 -9
  162. package/dist/prosemirror/tableResize.js +60 -49
  163. package/dist/prosemirror/textInput.d.ts +30 -1
  164. package/dist/prosemirror/textInput.js +144 -17
  165. package/dist/prosemirror/utils/visualLineNavigation.js +20 -18
  166. package/dist/prosemirror/validation.d.ts +19 -0
  167. package/dist/prosemirror/validation.js +78 -5
  168. package/dist/render-dom/HeaderFooterSelectionOverlay.js +5 -4
  169. package/dist/render-dom/RenderedDomContext.js +7 -6
  170. package/dist/types/canonicalCapabilities.d.ts +12 -11
  171. package/dist/types/canonicalCapabilities.js +12 -13
  172. package/dist/utils/findMatchView.js +4 -3
  173. package/dist/utils/formatToStyle.d.ts +1 -1
  174. package/dist/utils/mergeDocumentContent.js +2 -2
  175. package/dist/utils/paintedPositions.d.ts +60 -0
  176. package/dist/utils/paintedPositions.js +101 -0
  177. package/package.json +2 -3
@@ -1,5 +1,5 @@
1
1
  import { splitsGraphemeCluster, splitsSurrogatePair } from "../ai-edits/character-boundaries.js";
2
- import { rangedCommentIds, visitCommentMarkers } from "../docx/commentAnchorIndex.js";
2
+ import { CommentMarkerCache, paragraphCommentMarkers, visitCommentMarkerItems } from "../docx/commentAnchorIndex.js";
3
3
  import { ListNormalizationCache } from "../docx/listModelNormalization.js";
4
4
  import { cloneDocumentWithParagraphPropertySources, copyDocumentParagraphPropertySourceContract, copyParagraphPropertySource, restoreParagraphIndentationProjection } from "../docx/paragraphPropertySource.js";
5
5
  import { visitInlineContentSlots } from "../docx/paragraphTraversal.js";
@@ -11,17 +11,20 @@ import { ProjectionBlockCache, collectPairedBookmarkIds, footnoteToProseDoc, hea
11
11
  import { markPackageChange } from "../prosemirror/extensions/features/ParagraphChangeTrackerExtension.js";
12
12
  import { runFormattingPatchFromMarks } from "../prosemirror/runFormattingFromMarks.js";
13
13
  import { CANONICAL_GAP, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
14
- import { InlineProjectionCache, canonicalInlineSourceIssue, canonicalNativeCells, projectCanonicalInline } from "./canonicalInlineProjection.js";
14
+ import { InlineProjectionCache, canonicalNativeCells, projectCanonicalInline } from "./canonicalInlineProjection.js";
15
15
  import { normalizeCanonicalListRendering } from "./canonicalListRendering.js";
16
16
  import { lockViolationBetween } from "./canonicalLockGuard.js";
17
+ import { ParagraphIdIndex, sameIdOrder, storyFactContributions } from "./canonicalProjectionBlocks.js";
18
+ import { unsupportedSeedReason } from "./canonicalSeedContent.js";
17
19
  import { restoreCanonicalSelection } from "./canonicalSelection.js";
20
+ import { canonicalSourceRestores, normalizeCanonicalSource, withUneditedSourceRestored } from "./canonicalSourceNormalization.js";
18
21
  import { mapTocSelection } from "./canonicalTocSelection.js";
19
22
  import { Result, TaggedError, panic } from "better-result";
20
23
  import { hasIllegalXmlCharacters } from "@stll/docx-core";
21
24
  import { lockedControlMessage } from "@stll/docx-core/model";
22
25
  import { Fragment } from "prosemirror-model";
23
26
  import { CellSelection } from "prosemirror-tables";
24
- import { DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_TYPES, OP_STORIES, applyDocumentOp, applyDocumentOps, combineEdits, commentDocumentIssue, compileEditorIntent, createEditorIntentIdAllocator, documentStories, editorParagraphGroups, findStoryBody, normalizeForOps, packageParagraphIds, paragraphIdsIn, sameStory, suggestionRevisionInfos, survivingComments, validateOpsDocument } from "@stll/docx-core/ops";
27
+ import { DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_TYPES, OP_STORIES, applyDocumentOp, applyDocumentOps, combineEdits, compileEditorIntent, createEditorIntentIdAllocator, documentStories, editorParagraphGroups, findStoryBody, normalizeForOps, packageParagraphIds, paragraphIdsIn, sameStory, suggestedCommentIds, suggestionRevisionInfos, survivingComments, validateOpsDocument } from "@stll/docx-core/ops";
25
28
  import { AllSelection, NodeSelection, Selection, TextSelection } from "prosemirror-state";
26
29
  // src/controller/canonicalSession.ts
27
30
  const CanonicalSessionErrorBase = TaggedError("CanonicalSessionError");
@@ -153,13 +156,34 @@ const CANONICAL_PROJECTION_META = "folioCanonicalProjection";
153
156
  var CanonicalProjection = class CanonicalProjection {
154
157
  doc;
155
158
  story;
156
- paragraphs;
157
- paragraphsById;
158
- constructor({ doc, paragraphs, story }) {
159
- this.story = story;
160
- this.doc = doc;
161
- this.paragraphs = paragraphs;
162
- this.paragraphsById = new Map(paragraphs.map((paragraph) => [paragraph.blockId, paragraph]));
159
+ content;
160
+ blocks;
161
+ index;
162
+ facts;
163
+ reusable;
164
+ /** Where each top-level node starts. */
165
+ starts;
166
+ addresses;
167
+ constructor(options, held) {
168
+ this.doc = options.doc;
169
+ this.story = options.story;
170
+ this.content = options.content;
171
+ this.blocks = options.blocks;
172
+ this.index = options.index;
173
+ this.facts = options.facts;
174
+ this.reusable = options.reusable;
175
+ this.addresses = held?.addresses ?? /* @__PURE__ */ new Map();
176
+ if (held !== void 0) {
177
+ this.starts = held.starts;
178
+ return;
179
+ }
180
+ const starts = [];
181
+ let position = 0;
182
+ for (let child = 0; child < this.doc.childCount; child += 1) {
183
+ starts.push(position);
184
+ position += this.doc.child(child).nodeSize;
185
+ }
186
+ this.starts = starts;
163
187
  }
164
188
  /**
165
189
  * The same projection held as `doc`, a document equal to this one's. A
@@ -170,14 +194,67 @@ var CanonicalProjection = class CanonicalProjection {
170
194
  heldAs(doc) {
171
195
  return new CanonicalProjection({
172
196
  doc,
173
- paragraphs: this.paragraphs,
174
- story: this.story
197
+ story: this.story,
198
+ content: this.content,
199
+ blocks: this.blocks,
200
+ index: this.index,
201
+ facts: this.facts,
202
+ reusable: this.reusable
203
+ }, {
204
+ starts: this.starts,
205
+ addresses: this.addresses
175
206
  });
176
207
  }
208
+ addressOf(block, paragraph) {
209
+ const entry = this.blocks[block]?.paragraphs[paragraph] ?? panic("Missing canonical paragraph");
210
+ const known = this.addresses.get(entry.blockId);
211
+ if (known !== void 0) return known;
212
+ const address = {
213
+ blockId: entry.blockId,
214
+ container: entry.container ?? this.content,
215
+ start: (this.starts[block] ?? panic("Missing block start")) + entry.offset,
216
+ text: entry.inline.text,
217
+ boundaries: entry.inline.boundaries,
218
+ seams: entry.inline.seams,
219
+ node: entry.node,
220
+ source: entry.source
221
+ };
222
+ this.addresses.set(entry.blockId, address);
223
+ return address;
224
+ }
225
+ /** The paragraph whose content holds `position`, its ends included. */
226
+ paragraphAround(position) {
227
+ let low = 0;
228
+ let high = this.starts.length - 1;
229
+ let block = -1;
230
+ while (low <= high) {
231
+ const middle = low + high >> 1;
232
+ if ((this.starts[middle] ?? 0) < position) {
233
+ block = middle;
234
+ low = middle + 1;
235
+ } else high = middle - 1;
236
+ }
237
+ const paragraphs = this.blocks[block]?.paragraphs;
238
+ if (paragraphs === void 0) return void 0;
239
+ const relative = position - (this.starts[block] ?? 0);
240
+ low = 0;
241
+ high = paragraphs.length - 1;
242
+ let found = -1;
243
+ while (low <= high) {
244
+ const middle = low + high >> 1;
245
+ if ((paragraphs[middle]?.offset ?? 0) <= relative) {
246
+ found = middle;
247
+ low = middle + 1;
248
+ } else high = middle - 1;
249
+ }
250
+ const paragraph = paragraphs[found];
251
+ if (paragraph === void 0 || relative > paragraph.offset + paragraph.node.content.size) return void 0;
252
+ return this.addressOf(block, found);
253
+ }
177
254
  addressAt(position, edge = "caret") {
178
255
  if (!Number.isInteger(position)) return refuse("The input position is not an integer.");
179
256
  position = canonicalContentPosition(this.doc, position);
180
- const paragraph = this.paragraphs.find(({ start, node }) => position >= start && position <= start + node.content.size);
257
+ const paragraph = this.paragraphAround(position);
181
258
  if (paragraph === void 0) return refuse("The input is outside a plain paragraph.");
182
259
  const relative = position - paragraph.start;
183
260
  const offset = paragraph.boundaries.findIndex((gaps) => gaps.some((gap) => gap.position === relative));
@@ -209,10 +286,7 @@ var CanonicalProjection = class CanonicalProjection {
209
286
  * text would empty it.
210
287
  */
211
288
  rangeEdgesAt(from, to) {
212
- const paragraphOf = (position) => {
213
- const content = canonicalContentPosition(this.doc, position);
214
- return this.paragraphs.find(({ start, node }) => content >= start && content <= start + node.content.size);
215
- };
289
+ const paragraphOf = (position) => this.paragraphAround(canonicalContentPosition(this.doc, position));
216
290
  const first = paragraphOf(from);
217
291
  const last = paragraphOf(to);
218
292
  const startsWhole = first !== void 0 && canonicalContentPosition(this.doc, from) === first.start && canonicalContentPosition(this.doc, to) >= first.start + first.node.content.size;
@@ -277,17 +351,32 @@ var CanonicalProjection = class CanonicalProjection {
277
351
  }
278
352
  /** The first paragraph the projection addresses, in document order. */
279
353
  get firstParagraph() {
280
- return this.paragraphs.at(0);
354
+ const block = this.blocks.findIndex(({ paragraphs }) => paragraphs.length > 0);
355
+ return block < 0 ? void 0 : this.addressOf(block, 0);
281
356
  }
282
357
  paragraph(blockId) {
283
- return this.paragraphsById.get(blockId);
358
+ const slot = this.index.get(blockId);
359
+ if (slot === void 0 || slot.paragraph < 0) return void 0;
360
+ return this.addressOf(slot.block, slot.paragraph);
361
+ }
362
+ /** The paragraph whose node starts at `before`. */
363
+ paragraphStartingAt(before) {
364
+ const paragraph = this.paragraphAround(before + 1);
365
+ return paragraph?.start === before + 1 ? paragraph : void 0;
284
366
  }
285
367
  nextParagraphInContainer(blockId) {
286
- const index = this.paragraphs.findIndex((paragraph) => paragraph.blockId === blockId);
287
- if (index < 0) return void 0;
288
- const paragraph = this.paragraphs.at(index);
289
- const next = this.paragraphs.at(index + 1);
290
- return paragraph?.container === next?.container ? next : void 0;
368
+ const slot = this.index.get(blockId);
369
+ if (slot === void 0 || slot.paragraph < 0) return void 0;
370
+ const paragraph = this.addressOf(slot.block, slot.paragraph);
371
+ let block = slot.block;
372
+ let next = slot.paragraph + 1;
373
+ while (block < this.blocks.length && next >= (this.blocks[block]?.paragraphs.length ?? 0)) {
374
+ block += 1;
375
+ next = 0;
376
+ }
377
+ if (block >= this.blocks.length) return void 0;
378
+ const following = this.addressOf(block, next);
379
+ return paragraph.container === following.container ? following : void 0;
291
380
  }
292
381
  };
293
382
  /** Immutable operations retain content identities for every untouched story. */
@@ -351,53 +440,11 @@ const preservePropertySources = ({ target, source, stories = documentStories(sou
351
440
  }
352
441
  copyDocumentParagraphPropertySourceContract(target, source);
353
442
  };
354
- const unsupportedSeedReason = (document, stories = documentStories(document)) => {
355
- const commentIssue = commentDocumentIssue(document, "all");
356
- if (commentIssue !== void 0) return commentIssue;
357
- for (const story of stories) {
358
- const body = findStoryBody(document, story);
359
- if (story !== OP_STORIES.MAIN && (story.kind === "footnote" || story.kind === "endnote")) {
360
- const note = (story.kind === "footnote" ? document.package.footnotes : document.package.endnotes)?.find(({ id }) => id === story.id);
361
- if (note?.noteType !== void 0 && note.noteType !== "normal") continue;
362
- }
363
- const content = body?.content;
364
- if (!content || content.length === 0) return "Canonical sessions require a nonempty paragraph story.";
365
- const paragraphs = [];
366
- const collect = (blocks) => {
367
- for (const block of blocks) {
368
- if (block.type === "paragraph") {
369
- paragraphs.push(block);
370
- continue;
371
- }
372
- if (block.type === "commentRangeStart" || block.type === "commentRangeEnd" || block.type === "bookmarkStart" || block.type === "bookmarkEnd" || block.type === "moveFromRangeStart" || block.type === "moveFromRangeEnd" || block.type === "moveToRangeStart" || block.type === "moveToRangeEnd") continue;
373
- if (block.type === "preservedBlock") continue;
374
- if (block.type === "blockSdt") {
375
- const issue = collect(block.content);
376
- if (issue !== null) return issue;
377
- continue;
378
- }
379
- if (block.type !== "table") return "Canonical sessions currently require paragraphs, tables and supported inline atoms.";
380
- for (const row of block.rows) for (const cell of row.cells) {
381
- const issue = collect(cell.content);
382
- if (issue !== null) return issue;
383
- }
384
- }
385
- return null;
386
- };
387
- const blockIssue = collect(content);
388
- if (blockIssue !== null) return blockIssue;
389
- for (const paragraph of paragraphs) {
390
- if (paragraph.reviewCarrier !== void 0) return "Canonical sessions currently require plain paragraphs and supported inline atoms.";
391
- const issue = canonicalInlineSourceIssue(paragraph.content);
392
- if (issue !== null) return issue;
393
- }
394
- }
395
- return null;
396
- };
397
443
  const newStoryProjectionCaches = () => ({
398
444
  blocks: new ProjectionBlockCache(),
399
445
  inline: new InlineProjectionCache(),
400
- lists: new ListNormalizationCache()
446
+ lists: new ListNormalizationCache(),
447
+ comments: new CommentMarkerCache()
401
448
  });
402
449
  /** Whether a paragraph anchors a text box, which converts to a block of its own. */
403
450
  const holdsTextBox = (paragraph) => {
@@ -407,136 +454,137 @@ const holdsTextBox = (paragraph) => {
407
454
  });
408
455
  return found;
409
456
  };
410
- const project = ({ document, styles, story = OP_STORIES.MAIN, caches }) => {
411
- const body = findStoryBody(document, story);
412
- if (!body) return refuse("The canonical story no longer exists.");
413
- const currentStyles = Object.hasOwn(document.package, "styles") ? document.package.styles : styles;
414
- const options = {
415
- ...currentStyles == null ? {} : { styles: currentStyles },
416
- ...document.package.theme === void 0 ? {} : { theme: document.package.theme }
417
- };
418
- const converted = Result.try({
419
- try: () => {
420
- if (story === OP_STORIES.MAIN) return toProseDoc(document, caches === void 0 ? options : {
421
- ...options,
422
- blockCache: caches.blocks
423
- });
424
- if (story.kind === "header" || story.kind === "footer") return headerFooterToProseDoc(body.content, options);
425
- return footnoteToProseDoc(body.content, options);
426
- },
427
- catch: (cause) => new CanonicalSessionError({
428
- ground: { gap: CANONICAL_GAP.dispatch },
429
- reason: "refused",
430
- message: `Canonical projection failed: ${cause instanceof Error ? cause.message : String(cause)}`
431
- })
432
- });
433
- if (converted.isErr()) return converted;
434
- const pairedBookmarkIds = collectPairedBookmarkIds(body.content);
435
- const commentContext = {
436
- rangedIds: rangedCommentIds(body.content),
437
- pointIds: /* @__PURE__ */ new Set(),
438
- openIds: /* @__PURE__ */ new Set()
439
- };
440
- visitCommentMarkers(body.content, ({ item }) => {
441
- if (item.type === "commentReference" && !commentContext.rangedIds.has(item.id)) commentContext.pointIds.add(item.id);
442
- });
443
- const sources = /* @__PURE__ */ new Map();
444
- const allSources = /* @__PURE__ */ new Set();
445
- const continuationSources = /* @__PURE__ */ new Set();
446
- const collectSources = (blocks, insideSkippedContinuation = false) => {
447
- for (const block of blocks) {
448
- if (block.type === "paragraph") {
449
- allSources.add(block);
450
- if (insideSkippedContinuation) continuationSources.add(block);
451
- if (block.paraId !== void 0) sources.set(block.paraId, {
452
- source: block,
453
- container: blocks
454
- });
455
- continue;
456
- }
457
- if (block.type === "blockSdt") {
458
- collectSources(block.content, insideSkippedContinuation);
459
- continue;
460
- }
461
- if (block.type !== "table") continue;
462
- const rowSpans = calculateRowSpans(block);
463
- for (const [rowIndex, row] of block.rows.entries()) {
464
- let column = row.formatting?.gridBefore ?? 0;
465
- for (const cell of row.cells) {
466
- const skippedContinuation = isCellMergeContinuation(cell) && (rowSpans.get(`${rowIndex}-${column}`)?.skip ?? false);
467
- collectSources(cell.content, insideSkippedContinuation || skippedContinuation);
468
- column += cell.formatting?.gridSpan ?? 1;
469
- }
470
- }
457
+ const structureRefusal = () => new CanonicalSessionError({
458
+ ground: { gap: CANONICAL_GAP.storyContentProjection },
459
+ reason: "refused",
460
+ message: "The projection changed paragraph structure."
461
+ });
462
+ /**
463
+ * Every paragraph a projection addresses or skips under `blocks`, with
464
+ * whether it lies in a merged cell's skipped continuation, in document order.
465
+ */
466
+ const visitSourceParagraphs = (blocks, visit, insideSkippedContinuation = false) => {
467
+ for (const block of blocks) visitBlockSources(block, blocks, visit, insideSkippedContinuation);
468
+ };
469
+ const visitBlockSources = (block, container, visit, insideSkippedContinuation) => {
470
+ if (block.type === "paragraph") {
471
+ visit(block, container, insideSkippedContinuation);
472
+ return;
473
+ }
474
+ if (block.type === "blockSdt") {
475
+ visitSourceParagraphs(block.content, visit, insideSkippedContinuation);
476
+ return;
477
+ }
478
+ if (block.type !== "table") return;
479
+ const rowSpans = calculateRowSpans(block);
480
+ for (const [rowIndex, row] of block.rows.entries()) {
481
+ let column = row.formatting?.gridBefore ?? 0;
482
+ for (const cell of row.cells) {
483
+ const skippedContinuation = isCellMergeContinuation(cell) && (rowSpans.get(`${rowIndex}-${column}`)?.skip ?? false);
484
+ visitSourceParagraphs(cell.content, visit, insideSkippedContinuation || skippedContinuation);
485
+ column += cell.formatting?.gridSpan ?? 1;
471
486
  }
487
+ }
488
+ };
489
+ const collectSources = (content, start, end, takenElsewhere) => {
490
+ const found = {
491
+ located: /* @__PURE__ */ new Map(),
492
+ idsByBlock: [],
493
+ all: [],
494
+ continuation: /* @__PURE__ */ new Set(),
495
+ repeated: false
472
496
  };
473
- collectSources(body.content);
474
- const paragraphs = [];
475
- const projectedSources = /* @__PURE__ */ new Set();
476
- const orderedSources = [...allSources];
477
- const sourceOrder = new Map(orderedSources.map((source, index) => [source, index]));
478
- const textBoxHosts = /* @__PURE__ */ new Set();
479
- let nextSource = 0;
480
- const claimTextBoxHost = () => {
481
- let index = nextSource;
482
- while (index < orderedSources.length && continuationSources.has(orderedSources[index] ?? panic("No source"))) index += 1;
483
- const host = orderedSources[index];
484
- if (host === void 0 || !holdsTextBox(host)) return false;
485
- textBoxHosts.add(host);
486
- nextSource = index + 1;
487
- visitCommentMarkers([host], ({ item }) => {
488
- if (item.type === "commentRangeStart") commentContext.openIds.add(item.id);
489
- if (item.type === "commentRangeEnd") commentContext.openIds.delete(item.id);
497
+ const at = {
498
+ top: start,
499
+ ids: []
500
+ };
501
+ const visit = (source, container, continuation) => {
502
+ found.all.push(source);
503
+ if (continuation) found.continuation.add(source);
504
+ if (source.paraId === void 0) return;
505
+ if (found.located.has(source.paraId) || takenElsewhere(source.paraId)) found.repeated = true;
506
+ found.located.set(source.paraId, {
507
+ source,
508
+ container,
509
+ top: at.top
490
510
  });
491
- return true;
511
+ at.ids.push(source.paraId);
492
512
  };
513
+ for (let top = start; top < end; top += 1) {
514
+ at.top = top;
515
+ at.ids = [];
516
+ found.idsByBlock.push(at.ids);
517
+ visitBlockSources(content[top] ?? panic("Missing story block"), content, visit, false);
518
+ }
519
+ return found;
520
+ };
521
+ /** The comment ranges open as a walk goes, with a copy kept while they stay the same. */
522
+ var OpenComments = class {
523
+ ids;
524
+ kept;
525
+ constructor(open) {
526
+ this.ids = new Set(open);
527
+ this.kept = open;
528
+ }
529
+ /** The open ranges now, in their set's order. */
530
+ get current() {
531
+ let same = this.kept.length === this.ids.size;
532
+ let at = 0;
533
+ for (const id of this.ids) {
534
+ if (!same) break;
535
+ same = this.kept[at] === id;
536
+ at += 1;
537
+ }
538
+ if (!same) this.kept = [...this.ids];
539
+ return this.kept;
540
+ }
541
+ };
542
+ /**
543
+ * The paragraphs of the top-level node at `index`, each start from the
544
+ * node's own, and whether each came from the story block at that index.
545
+ */
546
+ const projectBlock = (top, index, walk) => {
547
+ const paragraphs = [];
548
+ let local = true;
493
549
  let failure;
494
- converted.value.descendants((node, offset, parent) => {
550
+ const commentContext = {
551
+ rangedIds: walk.facts.rangedIds,
552
+ pointIds: walk.facts.pointIds,
553
+ openIds: walk.open.ids
554
+ };
555
+ const visit = (node, offset, parent) => {
495
556
  if (failure !== void 0) return false;
496
557
  if (node.type.name === "textBox") {
497
- if (node.attrs["_docxPlacement"] === "standalone" && node.attrs["_docxHostParagraph"] != null && !claimTextBoxHost()) failure = new CanonicalSessionError({
498
- ground: { gap: CANONICAL_GAP.storyContentProjection },
499
- reason: "refused",
500
- message: "The projection changed paragraph structure."
501
- });
558
+ if (node.attrs["_docxPlacement"] === "standalone" && node.attrs["_docxHostParagraph"] != null && !walk.claimTextBoxHost()) failure = structureRefusal();
502
559
  return false;
503
560
  }
504
561
  if (node.type.name === "blockCommentRangeBoundary") {
505
562
  const { marker } = expectCommentRangeBoundaryAttrs(node);
506
- if (marker.type === "commentRangeStart") commentContext.openIds.add(marker.id);
507
- else commentContext.openIds.delete(marker.id);
563
+ if (marker.type === "commentRangeStart") walk.open.ids.add(marker.id);
564
+ else walk.open.ids.delete(marker.id);
508
565
  return false;
509
566
  }
510
567
  if (node.type.name !== "paragraph") return true;
511
568
  if (parent?.attrs["_omittedGridSlot"] != null) return false;
512
569
  const paraId = node.attrs["paraId"];
513
- const located = typeof paraId === "string" ? sources.get(paraId) : void 0;
570
+ const located = typeof paraId === "string" ? walk.locate(paraId) : void 0;
514
571
  if (typeof paraId !== "string" || located === void 0) {
515
- failure = new CanonicalSessionError({
516
- ground: { gap: CANONICAL_GAP.storyContentProjection },
517
- reason: "refused",
518
- message: "The projection changed paragraph structure."
519
- });
572
+ failure = structureRefusal();
520
573
  return false;
521
574
  }
522
575
  const { source, container } = located;
523
- if (projectedSources.has(source)) {
524
- failure = new CanonicalSessionError({
525
- ground: { gap: CANONICAL_GAP.storyContentProjection },
526
- reason: "refused",
527
- message: "The projection changed paragraph structure."
528
- });
576
+ if (!walk.take(source)) {
577
+ failure = structureRefusal();
529
578
  return false;
530
579
  }
531
- projectedSources.add(source);
532
- nextSource = (sourceOrder.get(source) ?? panic("Unordered source")) + 1;
580
+ if (located.top !== index) local = false;
533
581
  const inlineArgs = {
534
582
  source,
535
583
  paragraph: node,
536
- pairedBookmarkIds,
584
+ pairedBookmarkIds: walk.facts.pairedBookmarkIds,
537
585
  commentContext
538
586
  };
539
- const inline = caches === void 0 ? projectCanonicalInline(inlineArgs) : caches.inline.project(inlineArgs);
587
+ const inline = walk.inline === void 0 ? projectCanonicalInline(inlineArgs) : walk.inline.project(inlineArgs);
540
588
  if (inline.isErr()) {
541
589
  failure = new CanonicalSessionError({
542
590
  ground: { gap: CANONICAL_GAP.dispatch },
@@ -547,26 +595,225 @@ const project = ({ document, styles, story = OP_STORIES.MAIN, caches }) => {
547
595
  }
548
596
  paragraphs.push({
549
597
  blockId: paraId,
550
- container,
551
- start: offset + 1,
552
- ...inline.value,
598
+ container: container === walk.content ? void 0 : container,
599
+ offset: offset + 1,
600
+ inline: inline.value,
553
601
  node,
554
602
  source
555
603
  });
556
- visitCommentMarkers([source], ({ item }) => {
557
- if (item.type === "commentRangeStart") commentContext.openIds.add(item.id);
558
- if (item.type === "commentRangeEnd") commentContext.openIds.delete(item.id);
559
- });
604
+ walk.passComments(source);
560
605
  return false;
561
- });
606
+ };
607
+ if (visit(top, 0, null) && top.content.size > 0) top.descendants((node, offset, parent) => visit(node, offset + 1, parent));
562
608
  if (failure !== void 0) return Result.err(failure);
609
+ return Result.ok({
610
+ paragraphs,
611
+ local
612
+ });
613
+ };
614
+ /** Opens and closes the ranges a paragraph's markers start and end. */
615
+ const commentPasser = (markersOf, open) => (paragraph) => {
616
+ for (const item of markersOf(paragraph)) {
617
+ if (item.type === "commentRangeStart") open.ids.add(item.id);
618
+ if (item.type === "commentRangeEnd") open.ids.delete(item.id);
619
+ }
620
+ };
621
+ /** Every paragraph's address, walking every top-level node. */
622
+ const projectEveryBlock = ({ doc, content, story, markersOf, inline }) => {
623
+ const pairedBookmarkIds = collectPairedBookmarkIds(content);
624
+ const rangedIds = /* @__PURE__ */ new Set();
625
+ const referencedIds = /* @__PURE__ */ new Set();
626
+ visitCommentMarkerItems(content, markersOf, (item) => {
627
+ if (item.type === "commentRangeStart") rangedIds.add(item.id);
628
+ if (item.type === "commentReference") referencedIds.add(item.id);
629
+ });
630
+ const facts = {
631
+ pairedBookmarkIds,
632
+ rangedIds,
633
+ pointIds: new Set([...referencedIds].filter((id) => !rangedIds.has(id)))
634
+ };
635
+ const open = new OpenComments([]);
636
+ const passComments = commentPasser(markersOf, open);
637
+ const aligned = doc.childCount === content.length;
638
+ const found = collectSources(content, 0, content.length, () => false);
639
+ let reusable = aligned && !found.repeated;
640
+ const sources = found.located;
641
+ const allSources = new Set(found.all);
642
+ const continuationSources = found.continuation;
643
+ const idsByBlock = found.idsByBlock;
644
+ const projectedSources = /* @__PURE__ */ new Set();
645
+ const orderedSources = [...allSources];
646
+ const sourceOrder = new Map(orderedSources.map((source, index) => [source, index]));
647
+ const textBoxHosts = /* @__PURE__ */ new Set();
648
+ let nextSource = 0;
649
+ const walk = {
650
+ facts,
651
+ open,
652
+ content,
653
+ locate: (paraId) => sources.get(paraId),
654
+ claimTextBoxHost: () => {
655
+ reusable = false;
656
+ let index = nextSource;
657
+ while (index < orderedSources.length && continuationSources.has(orderedSources[index] ?? panic("No source"))) index += 1;
658
+ const host = orderedSources[index];
659
+ if (host === void 0 || !holdsTextBox(host)) return false;
660
+ textBoxHosts.add(host);
661
+ nextSource = index + 1;
662
+ passComments(host);
663
+ return true;
664
+ },
665
+ take: (source) => {
666
+ if (projectedSources.has(source)) return false;
667
+ projectedSources.add(source);
668
+ nextSource = (sourceOrder.get(source) ?? panic("Unordered source")) + 1;
669
+ return true;
670
+ },
671
+ passComments,
672
+ inline
673
+ };
674
+ const blocks = [];
675
+ for (let index = 0; index < doc.childCount; index += 1) {
676
+ const node = doc.child(index);
677
+ const openBefore = open.current;
678
+ const projected = projectBlock(node, index, walk);
679
+ if (projected.isErr()) return projected;
680
+ if (!projected.value.local) reusable = false;
681
+ blocks.push({
682
+ node,
683
+ source: aligned ? content[index] : void 0,
684
+ paragraphs: projected.value.paragraphs,
685
+ sourceIds: aligned ? idsByBlock[index] ?? [] : [],
686
+ openBefore,
687
+ openAfter: open.current
688
+ });
689
+ }
563
690
  if (projectedSources.size + continuationSources.size + textBoxHosts.size !== allSources.size || [...projectedSources].some((source) => continuationSources.has(source) || textBoxHosts.has(source)) || [...textBoxHosts].some((source) => continuationSources.has(source))) return refuse("The projection changed paragraph structure.");
564
691
  return Result.ok(new CanonicalProjection({
565
- doc: converted.value,
566
- paragraphs,
567
- story
692
+ doc,
693
+ story,
694
+ content,
695
+ blocks,
696
+ index: ParagraphIdIndex.of(blocks),
697
+ facts,
698
+ reusable
568
699
  }));
569
700
  };
701
+ /**
702
+ * The projection keeping every top-level block of `previous` an edit left:
703
+ * the run of blocks from the start and the run to the end whose story block
704
+ * and converted node are both the ones `previous` walked. Only the blocks
705
+ * between are walked, from the comment ranges open where they start. Nothing
706
+ * when the kept blocks would read other story facts than they did, or the
707
+ * walked ones reach outside themselves; the story is then walked in full.
708
+ */
709
+ const projectChangedBlocks = (previous, { doc, content, story, markersOf, inline }) => {
710
+ if (!previous.reusable || !sameStory(previous.story, story)) return void 0;
711
+ const before = previous.blocks;
712
+ const count = content.length;
713
+ if (doc.childCount !== count) return void 0;
714
+ const unchanged = (block, at) => block !== void 0 && block.source === content[at] && block.node === doc.child(at);
715
+ let start = 0;
716
+ while (start < count && start < before.length && unchanged(before[start], start)) start += 1;
717
+ let after = 0;
718
+ while (after < count - start && after < before.length - start && unchanged(before[before.length - 1 - after], count - 1 - after)) after += 1;
719
+ const end = before.length - after;
720
+ const newEnd = count - after;
721
+ if (!sameIdOrder(storyFactContributions(previous.content.slice(start, end), markersOf), storyFactContributions(content.slice(start, newEnd), markersOf))) return void 0;
722
+ const removed = /* @__PURE__ */ new Set();
723
+ for (let index = start; index < end; index += 1) for (const id of before[index]?.sourceIds ?? []) removed.add(id);
724
+ const found = collectSources(content, start, newEnd, (paraId) => previous.index.get(paraId) !== void 0 && !removed.has(paraId));
725
+ if (found.repeated) return void 0;
726
+ const sources = found.located;
727
+ const continuationSources = found.continuation;
728
+ const open = new OpenComments(before[start - 1]?.openAfter ?? []);
729
+ const projectedSources = /* @__PURE__ */ new Set();
730
+ const walk = {
731
+ facts: previous.facts,
732
+ open,
733
+ content,
734
+ locate: (paraId) => sources.get(paraId),
735
+ claimTextBoxHost: () => false,
736
+ take: (source) => {
737
+ if (projectedSources.has(source)) return false;
738
+ projectedSources.add(source);
739
+ return true;
740
+ },
741
+ passComments: commentPasser(markersOf, open),
742
+ inline
743
+ };
744
+ const window = [];
745
+ for (let index = start; index < newEnd; index += 1) {
746
+ const node = doc.child(index);
747
+ const openBefore = open.current;
748
+ const projected = projectBlock(node, index, walk);
749
+ if (projected.isErr() || !projected.value.local) return void 0;
750
+ window.push({
751
+ node,
752
+ source: content[index],
753
+ paragraphs: projected.value.paragraphs,
754
+ sourceIds: found.idsByBlock[index - start] ?? [],
755
+ openBefore,
756
+ openAfter: open.current
757
+ });
758
+ }
759
+ if (projectedSources.size + continuationSources.size !== found.all.length || [...projectedSources].some((source) => continuationSources.has(source))) return void 0;
760
+ const following = before[end];
761
+ if (following !== void 0 && !sameIdOrder(open.current, following.openBefore)) return void 0;
762
+ const blocks = [
763
+ ...before.slice(0, start),
764
+ ...window,
765
+ ...before.slice(end)
766
+ ];
767
+ return new CanonicalProjection({
768
+ doc,
769
+ story,
770
+ content,
771
+ blocks,
772
+ index: previous.index.replaced({
773
+ start,
774
+ end,
775
+ removed,
776
+ window,
777
+ blocks
778
+ }),
779
+ facts: previous.facts,
780
+ reusable: true
781
+ });
782
+ };
783
+ const project = ({ document, styles, story = OP_STORIES.MAIN, caches, previous }) => {
784
+ const body = findStoryBody(document, story);
785
+ if (!body) return refuse("The canonical story no longer exists.");
786
+ const currentStyles = Object.hasOwn(document.package, "styles") ? document.package.styles : styles;
787
+ const options = {
788
+ ...currentStyles == null ? {} : { styles: currentStyles },
789
+ ...document.package.theme === void 0 ? {} : { theme: document.package.theme }
790
+ };
791
+ const converted = Result.try({
792
+ try: () => {
793
+ if (story === OP_STORIES.MAIN) return toProseDoc(document, caches === void 0 ? options : {
794
+ ...options,
795
+ blockCache: caches.blocks
796
+ });
797
+ if (story.kind === "header" || story.kind === "footer") return headerFooterToProseDoc(body.content, options);
798
+ return footnoteToProseDoc(body.content, options);
799
+ },
800
+ catch: (cause) => new CanonicalSessionError({
801
+ ground: { gap: CANONICAL_GAP.dispatch },
802
+ reason: "refused",
803
+ message: `Canonical projection failed: ${cause instanceof Error ? cause.message : String(cause)}`
804
+ })
805
+ });
806
+ if (converted.isErr()) return converted;
807
+ const walk = {
808
+ doc: converted.value,
809
+ content: body.content,
810
+ story,
811
+ markersOf: caches?.comments.read ?? paragraphCommentMarkers,
812
+ inline: caches?.inline
813
+ };
814
+ const kept = previous === void 0 ? void 0 : projectChangedBlocks(previous, walk);
815
+ return kept === void 0 ? projectEveryBlock(walk) : Result.ok(kept);
816
+ };
570
817
  const intentStory = (intent) => {
571
818
  switch (intent.type) {
572
819
  case "setHyperlink":
@@ -582,7 +829,8 @@ const intentStory = (intent) => {
582
829
  case "formatParagraph": return intent.at.story;
583
830
  case "setList": return intent.items.at(0)?.at.story ?? panic("A list intent requires a paragraph.");
584
831
  case "joinParagraphs":
585
- case "insertParagraphs": return intent.story;
832
+ case "insertParagraphs":
833
+ case "deleteParagraphs": return intent.story;
586
834
  case "table":
587
835
  case "tableRow":
588
836
  case "tableBlock": return intent.operation.story;
@@ -660,9 +908,11 @@ var CanonicalSession = class {
660
908
  lifecycle = { type: "committed" };
661
909
  undone = [];
662
910
  styles;
911
+ sourceRestores;
663
912
  /** What earlier projections converted, reused by every later one. */
664
913
  caches;
665
- constructor({ document, projection, styles, caches }) {
914
+ constructor({ document, projection, styles, sourceRestores = [], caches }) {
915
+ this.sourceRestores = sourceRestores;
666
916
  this.caches = caches;
667
917
  this.currentDocument = document;
668
918
  this.currentProjection = projection;
@@ -741,7 +991,8 @@ var CanonicalSession = class {
741
991
  case "table":
742
992
  case "tableRow":
743
993
  case "tableBlock":
744
- case "insertParagraphs": return true;
994
+ case "insertParagraphs":
995
+ case "deleteParagraphs": return true;
745
996
  case "generateTOC":
746
997
  case "setList":
747
998
  case "formatParagraph": return false;
@@ -796,7 +1047,7 @@ var CanonicalSession = class {
796
1047
  });
797
1048
  const retainedBlockIdKeys = new Set([...this.sourceBlockIds, ...packageParagraphIds(this.currentDocument.package)].map((blockId) => blockId.toUpperCase()));
798
1049
  return {
799
- document: cloneDocumentWithParagraphPropertySources(this.currentDocument),
1050
+ document: withUneditedSourceRestored(cloneDocumentWithParagraphPropertySources(this.currentDocument), this.sourceRestores),
800
1051
  version: this.currentVersion,
801
1052
  changedBlockIds: [...this.saveTouched].filter((blockId) => retainedBlockIdKeys.has(blockId.toUpperCase())),
802
1053
  structure: this.saveStructure
@@ -815,6 +1066,10 @@ var CanonicalSession = class {
815
1066
  get selection() {
816
1067
  return this.currentSelection;
817
1068
  }
1069
+ /** Every paragraph identity this session has read or minted, live or retired. */
1070
+ get reservedBlockIds() {
1071
+ return this.allocatedBlockIds;
1072
+ }
818
1073
  get version() {
819
1074
  return this.currentVersion;
820
1075
  }
@@ -930,6 +1185,7 @@ var CanonicalSession = class {
930
1185
  ops,
931
1186
  selection: postSelection,
932
1187
  origin: "input",
1188
+ ...compiled.value.applied === void 0 ? {} : { stagedApplied: compiled.value.applied },
933
1189
  onPublish: (inverse, version) => {
934
1190
  const entry = {
935
1191
  type: "applied",
@@ -1043,7 +1299,7 @@ var CanonicalSession = class {
1043
1299
  }));
1044
1300
  return refuse(compiled.error.message);
1045
1301
  }
1046
- const applied = applyDocumentOps(document, compiled.value.ops);
1302
+ const applied = compiled.value.applied === void 0 ? applyDocumentOps(document, compiled.value.ops) : Result.ok(compiled.value.applied);
1047
1303
  if (applied.isErr()) return applied.error.reason === DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE ? noChange(applied.error.message) : refuse(applied.error.message);
1048
1304
  document = applied.value.document;
1049
1305
  edits.push(applied.value);
@@ -1172,7 +1428,7 @@ var CanonicalSession = class {
1172
1428
  nextBlockId: second.paraId
1173
1429
  });
1174
1430
  }
1175
- prepareResolve(state, { revisionIds, resolution }) {
1431
+ prepareResolve(state, { revisionIds, resolution, before = [] }) {
1176
1432
  const checked = this.checkState(state);
1177
1433
  if (checked.isErr()) return checked;
1178
1434
  const preSelection = this.projection.selectionAt(state);
@@ -1192,13 +1448,15 @@ var CanonicalSession = class {
1192
1448
  return violation !== null;
1193
1449
  });
1194
1450
  if (firstHeld !== null && lockHeld.length === revisionIds.length) return lockRefusal(firstHeld);
1195
- const ops = resolve(revisionIds.filter((id) => !lockHeld.includes(id)));
1451
+ const resolved = revisionIds.filter((id) => !lockHeld.includes(id));
1452
+ const ops = [...before, ...resolved.length === 0 ? [] : resolve(resolved)];
1196
1453
  const applied = applyDocumentOps(this.currentDocument, ops);
1197
1454
  if (applied.isErr()) return refuse(applied.error.message);
1198
1455
  const projected = project({
1199
1456
  document: applied.value.document,
1200
1457
  styles: this.styles,
1201
- caches: this.caches
1458
+ caches: this.caches,
1459
+ previous: this.currentProjection
1202
1460
  });
1203
1461
  if (projected.isErr()) return projected;
1204
1462
  const surviving = projected.value.paragraph(preSelection.value.head.blockId);
@@ -1228,32 +1486,48 @@ var CanonicalSession = class {
1228
1486
  }
1229
1487
  /**
1230
1488
  * Accept or reject one pending suggestion. Rejecting it rejects its
1231
- * revisions. Accepting it adopts them as ordinary tracked changes by
1232
- * `author`, keeping their ids, as the editor does: the change then waits
1233
- * for review like any other.
1489
+ * revisions and removes the comments it proposes. Accepting it adopts its
1490
+ * revisions as ordinary tracked changes by `author`, keeping their ids, as
1491
+ * the editor does: the change then waits for review like any other. Its
1492
+ * comments stay as ordinary comments.
1234
1493
  */
1235
1494
  prepareSuggestion(state, { suggestionId, resolution, author, date }) {
1236
1495
  const infos = suggestionRevisionInfos(this.currentDocument, OP_STORIES.MAIN, suggestionId);
1237
- if (infos.length === 0) return noChange(`No pending suggestion ${suggestionId}.`);
1496
+ const commentIds = suggestedCommentIds(this.currentDocument, suggestionId);
1497
+ if (infos.length === 0 && commentIds.length === 0) return noChange(`No pending suggestion ${suggestionId}.`);
1238
1498
  if (resolution === "reject") return this.prepareResolve(state, {
1239
1499
  revisionIds: infos.map(({ id }) => id),
1240
- resolution: "reject"
1500
+ resolution: "reject",
1501
+ before: commentIds.map((id) => ({
1502
+ type: DOCUMENT_OP_TYPES.DELETE_COMMENT,
1503
+ id,
1504
+ scope: "thread"
1505
+ }))
1241
1506
  });
1242
1507
  const checked = this.checkState(state);
1243
1508
  if (checked.isErr()) return checked;
1244
1509
  const selection = this.projection.selectionAt(state);
1245
1510
  if (selection.isErr()) return selection;
1511
+ const comments = this.currentDocument.package.document.comments ?? [];
1512
+ const ops = [];
1513
+ if (infos.length > 0) ops.push({
1514
+ type: DOCUMENT_OP_TYPES.SET_REVISION_INFO,
1515
+ story: OP_STORIES.MAIN,
1516
+ infos: infos.map(({ id }) => ({
1517
+ id,
1518
+ author,
1519
+ date
1520
+ }))
1521
+ });
1522
+ for (const comment of comments) if (commentIds.includes(comment.id)) ops.push({
1523
+ type: DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT,
1524
+ id: comment.id,
1525
+ content: comment.content,
1526
+ patch: { suggestionId: null }
1527
+ });
1246
1528
  return this.prepareJournalledOps({
1247
1529
  state,
1248
- ops: [{
1249
- type: DOCUMENT_OP_TYPES.SET_REVISION_INFO,
1250
- story: OP_STORIES.MAIN,
1251
- infos: infos.map(({ id }) => ({
1252
- id,
1253
- author,
1254
- date
1255
- }))
1256
- }],
1530
+ ops,
1257
1531
  postSelection: selection.value
1258
1532
  });
1259
1533
  }
@@ -1272,7 +1546,8 @@ var CanonicalSession = class {
1272
1546
  document: this.currentDocument,
1273
1547
  styles: this.styles,
1274
1548
  caches: this.caches,
1275
- story
1549
+ story,
1550
+ ...cached === void 0 ? {} : { previous: cached.projection }
1276
1551
  });
1277
1552
  if (projected.isOk()) this.storyProjections.set(key, {
1278
1553
  content: body.content,
@@ -1469,7 +1744,8 @@ var CanonicalSession = class {
1469
1744
  document: applied.value.document,
1470
1745
  styles: this.styles,
1471
1746
  caches: this.caches,
1472
- story: projectedStory
1747
+ story: projectedStory,
1748
+ previous: sameStory(projectedStory, OP_STORIES.MAIN) ? this.currentProjection : previous.value
1473
1749
  });
1474
1750
  if (projected.isErr()) return projected;
1475
1751
  const bodyProjection = (() => {
@@ -1477,7 +1753,8 @@ var CanonicalSession = class {
1477
1753
  if (ops.some(operationChangesBodyProjection)) return project({
1478
1754
  document: applied.value.document,
1479
1755
  styles: this.styles,
1480
- caches: this.caches
1756
+ caches: this.caches,
1757
+ previous: this.currentProjection
1481
1758
  });
1482
1759
  return Result.ok(this.currentProjection);
1483
1760
  })();
@@ -1580,10 +1857,11 @@ var CanonicalSession = class {
1580
1857
  }
1581
1858
  };
1582
1859
  const createCanonicalSession = (document, styles) => {
1583
- const unsupported = unsupportedSeedReason(document);
1584
- if (unsupported !== null) return refuse(unsupported);
1585
1860
  const owned = cloneDocumentWithParagraphPropertySources(document);
1586
- const identified = normalizeForOps(owned);
1861
+ const source = normalizeCanonicalSource(owned);
1862
+ const unsupported = unsupportedSeedReason(source.document);
1863
+ if (unsupported !== null) return refuse(unsupported);
1864
+ const identified = normalizeForOps(source.document);
1587
1865
  preservePropertySources({
1588
1866
  target: identified,
1589
1867
  source: owned
@@ -1606,6 +1884,7 @@ const createCanonicalSession = (document, styles) => {
1606
1884
  document: normalized,
1607
1885
  projection: projected.value,
1608
1886
  styles,
1887
+ sourceRestores: canonicalSourceRestores(normalized, source.normalized),
1609
1888
  caches
1610
1889
  }));
1611
1890
  };