@stll/folio-core 0.67.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 (350) hide show
  1. package/dist/ai-edits/apply.d.ts +9 -1
  2. package/dist/ai-edits/apply.js +94 -8
  3. package/dist/ai-edits/headless.d.ts +36 -21
  4. package/dist/ai-edits/headless.js +106 -36
  5. package/dist/ai-edits/index.d.ts +2 -2
  6. package/dist/ai-edits/newListNumbering.d.ts +14 -1
  7. package/dist/ai-edits/newListNumbering.js +24 -1
  8. package/dist/ai-edits/note-references.d.ts +6 -0
  9. package/dist/ai-edits/note-references.js +7 -1
  10. package/dist/ai-edits/pending-suggestions.js +2 -2
  11. package/dist/ai-edits/read.d.ts +19 -0
  12. package/dist/ai-edits/snapshot.d.ts +6 -0
  13. package/dist/ai-edits/snapshot.js +8 -3
  14. package/dist/ai-edits/types.d.ts +9 -1
  15. package/dist/ai-suggestions/apply.js +13 -4
  16. package/dist/compare/compare.js +2 -1
  17. package/dist/compare/inserted-resource-snapshot.d.ts +4 -1
  18. package/dist/compare/inserted-resource-snapshot.js +7 -3
  19. package/dist/controller/canonicalClipboard.js +31 -14
  20. package/dist/controller/canonicalComposition.js +35 -6
  21. package/dist/controller/canonicalInlineProjection.d.ts +35 -10
  22. package/dist/controller/canonicalInlineProjection.js +192 -28
  23. package/dist/controller/canonicalInput.d.ts +2 -1
  24. package/dist/controller/canonicalInput.js +32 -7
  25. package/dist/controller/canonicalListRendering.d.ts +2 -1
  26. package/dist/controller/canonicalListRendering.js +1 -1
  27. package/dist/controller/canonicalLockGuard.d.ts +23 -0
  28. package/dist/controller/canonicalLockGuard.js +133 -0
  29. package/dist/controller/canonicalProjectionBlocks.d.ts +79 -0
  30. package/dist/controller/canonicalProjectionBlocks.js +75 -0
  31. package/dist/controller/canonicalPublicOperations.d.ts +12 -4
  32. package/dist/controller/canonicalPublicOperations.js +676 -46
  33. package/dist/controller/canonicalSeedContent.d.ts +12 -0
  34. package/dist/controller/canonicalSeedContent.js +131 -0
  35. package/dist/controller/canonicalSession.d.ts +133 -21
  36. package/dist/controller/canonicalSession.js +738 -205
  37. package/dist/controller/canonicalSourceNormalization.d.ts +21 -0
  38. package/dist/controller/canonicalSourceNormalization.js +148 -0
  39. package/dist/controller/canonicalStoryEditor.d.ts +4 -3
  40. package/dist/controller/canonicalStoryEditor.js +20 -15
  41. package/dist/controller/canonicalStructure.d.ts +2 -1
  42. package/dist/controller/canonicalStructure.js +129 -7
  43. package/dist/controller/contentControlWidgetController.d.ts +5 -0
  44. package/dist/controller/contentControlWidgetController.js +13 -1
  45. package/dist/controller/folioEditor.js +4 -0
  46. package/dist/controller/headerFooterEditorManager.d.ts +7 -2
  47. package/dist/controller/headerFooterEditorManager.js +11 -6
  48. package/dist/controller/hiddenEditorApi.d.ts +17 -2
  49. package/dist/controller/hiddenEditorApi.js +4 -0
  50. package/dist/controller/hiddenEditorManager.d.ts +11 -3
  51. package/dist/controller/hiddenEditorManager.js +157 -48
  52. package/dist/controller/layoutPipeline.js +50 -16
  53. package/dist/controller/layoutSession.d.ts +3 -0
  54. package/dist/controller/layoutSession.js +3 -1
  55. package/dist/controller/noteEditorManager.d.ts +7 -2
  56. package/dist/controller/noteEditorManager.js +11 -6
  57. package/dist/display-list/build/pageFurniture.js +41 -19
  58. package/dist/display-list/build/tablePrimitives.js +23 -4
  59. package/dist/display-list/dom/renderDisplayListToDom.js +13 -11
  60. package/dist/document-operations.d.ts +9 -1
  61. package/dist/document-operations.js +4 -3
  62. package/dist/docx/blockContentParser.d.ts +7 -3
  63. package/dist/docx/blockContentParser.js +2 -3
  64. package/dist/docx/blockPlainText.js +2 -0
  65. package/dist/docx/bookmarkRangeJoin.d.ts +6 -0
  66. package/dist/docx/bookmarkRangeJoin.js +43 -0
  67. package/dist/docx/canonicalSave.js +11 -2
  68. package/dist/docx/canonicalSessionInput.d.ts +5 -1
  69. package/dist/docx/canonicalSessionInput.js +7 -2
  70. package/dist/docx/commentAnchorIndex.d.ts +40 -5
  71. package/dist/docx/commentAnchorIndex.js +94 -12
  72. package/dist/docx/commentRangeIntegrity.js +30 -24
  73. package/dist/docx/commentRangeJoin.d.ts +4 -0
  74. package/dist/docx/commentRangeJoin.js +26 -12
  75. package/dist/docx/commentReferenceCompletion.js +5 -4
  76. package/dist/docx/commentReferenceNormalization.js +40 -18
  77. package/dist/docx/compatibility.js +9 -2
  78. package/dist/docx/containerChildren.js +22 -1
  79. package/dist/docx/contentTypeRegistry.js +1 -1
  80. package/dist/docx/encryption/compoundFile.js +9 -1
  81. package/dist/docx/encryption/encryptionInfo.js +16 -2
  82. package/dist/docx/ensureParaIds.js +46 -7
  83. package/dist/docx/ensureUniqueControlIds.d.ts +25 -0
  84. package/dist/docx/ensureUniqueControlIds.js +110 -0
  85. package/dist/docx/headerFooterVerbatim.d.ts +7 -0
  86. package/dist/docx/headerFooterVerbatim.js +13 -2
  87. package/dist/docx/hostCommentThreads.d.ts +27 -0
  88. package/dist/docx/hostCommentThreads.js +72 -0
  89. package/dist/docx/hyperlinkParser.js +9 -2
  90. package/dist/docx/inlineWrapperContent.d.ts +8 -1
  91. package/dist/docx/inlineWrapperContent.js +9 -2
  92. package/dist/docx/listMarkerComputation.d.ts +35 -1
  93. package/dist/docx/listMarkerComputation.js +39 -1
  94. package/dist/docx/listModelNormalization.d.ts +44 -1
  95. package/dist/docx/listModelNormalization.js +226 -96
  96. package/dist/docx/listNumberingInstances.d.ts +1 -1
  97. package/dist/docx/listNumberingInstances.js +2 -2
  98. package/dist/docx/markupRangeMarker.d.ts +14 -0
  99. package/dist/docx/markupRangeMarker.js +15 -1
  100. package/dist/docx/metadataPrivacy.js +43 -22
  101. package/dist/docx/normalizeBaseDirection.js +3 -1
  102. package/dist/docx/numberingIds.d.ts +6 -0
  103. package/dist/docx/numberingIds.js +6 -1
  104. package/dist/docx/numberingReferenceNormalization.d.ts +4 -0
  105. package/dist/docx/numberingReferenceNormalization.js +12 -2
  106. package/dist/docx/paragraphParser.js +159 -48
  107. package/dist/docx/paragraphPropertySource.d.ts +29 -0
  108. package/dist/docx/paragraphPropertySource.js +106 -16
  109. package/dist/docx/paragraphTextBoxEnrichment.js +2 -1
  110. package/dist/docx/paragraphTraversal.js +2 -0
  111. package/dist/docx/parseWarningMessage.js +2 -1
  112. package/dist/docx/parser.js +8 -0
  113. package/dist/docx/removeHeaderFooterParts.js +1 -1
  114. package/dist/docx/renderedPageBreakNormalization.js +1 -1
  115. package/dist/docx/reviewProvenanceDiagnostics.d.ts +7 -0
  116. package/dist/docx/reviewProvenanceDiagnostics.js +39 -0
  117. package/dist/docx/reviewResolutionProvenance.d.ts +29 -3
  118. package/dist/docx/reviewResolutionProvenance.js +171 -33
  119. package/dist/docx/rezip.d.ts +6 -0
  120. package/dist/docx/rezip.js +38 -21
  121. package/dist/docx/selectiveSave.js +6 -10
  122. package/dist/docx/selectiveXmlPatch.d.ts +5 -4
  123. package/dist/docx/selectiveXmlPatch.js +11 -7
  124. package/dist/docx/serializer/documentSerializer.js +5 -2
  125. package/dist/docx/serializer/headerFooterSerializer.js +3 -1
  126. package/dist/docx/serializer/markupRangeAttributes.d.ts +6 -1
  127. package/dist/docx/serializer/markupRangeAttributes.js +6 -1
  128. package/dist/docx/serializer/noteSerializer.d.ts +17 -4
  129. package/dist/docx/serializer/noteSerializer.js +23 -16
  130. package/dist/docx/serializer/paragraphSerializer.js +56 -12
  131. package/dist/docx/serializer/partNamespaces.d.ts +1 -1
  132. package/dist/docx/serializer/partNamespaces.js +1 -1
  133. package/dist/docx/serializer/runSerializer.d.ts +1 -3
  134. package/dist/docx/serializer/runSerializer.js +2 -2
  135. package/dist/docx/serializer/tableSerializer.d.ts +4 -0
  136. package/dist/docx/serializer/tableSerializer.js +4 -2
  137. package/dist/docx/server/applyDocxXmlPatchProposal.js +8 -4
  138. package/dist/docx/server/build.d.ts +1 -1
  139. package/dist/docx/server/createBilingualDocument.js +27 -5
  140. package/dist/docx/server/migrateYjsAttrSchema.js +4 -0
  141. package/dist/docx/sessionListPruning.d.ts +2 -0
  142. package/dist/docx/sessionListPruning.js +50 -0
  143. package/dist/docx/splitRevisionPieces.d.ts +10 -0
  144. package/dist/docx/splitRevisionPieces.js +14 -0
  145. package/dist/docx/storyBlockReplay.js +19 -2
  146. package/dist/docx/structuralXmlPatch.js +44 -11
  147. package/dist/docx/tableParser.d.ts +6 -2
  148. package/dist/docx/tableParser.js +2 -3
  149. package/dist/docx/textBoxContentParser.d.ts +11 -0
  150. package/dist/docx/textBoxContentParser.js +51 -0
  151. package/dist/docx/textBoxParser.d.ts +0 -5
  152. package/dist/docx/textBoxParser.js +1 -23
  153. package/dist/docx/verticalMergeProjection.js +1 -1
  154. package/dist/docx/xmlParser.d.ts +1 -1
  155. package/dist/docx/xmlParser.js +2 -3
  156. package/dist/fonts/fontsourceFaces.d.ts +2 -8
  157. package/dist/fonts/fontsourceFaces.js +1 -7
  158. package/dist/i18n/messages/ar.gen.js +3 -0
  159. package/dist/i18n/messages/catalogs.gen.d.ts +51 -0
  160. package/dist/i18n/messages/catalogs.gen.js +51 -0
  161. package/dist/i18n/messages/cs.gen.js +3 -0
  162. package/dist/i18n/messages/de.gen.js +3 -0
  163. package/dist/i18n/messages/en.gen.js +3 -0
  164. package/dist/i18n/messages/es.gen.js +3 -0
  165. package/dist/i18n/messages/et.gen.js +3 -0
  166. package/dist/i18n/messages/fr.gen.js +3 -0
  167. package/dist/i18n/messages/he.gen.js +3 -0
  168. package/dist/i18n/messages/hi.gen.js +3 -0
  169. package/dist/i18n/messages/hu.gen.js +3 -0
  170. package/dist/i18n/messages/lt.gen.js +3 -0
  171. package/dist/i18n/messages/lv.gen.js +3 -0
  172. package/dist/i18n/messages/messages.gen.d.ts +3 -0
  173. package/dist/i18n/messages/pl.gen.js +3 -0
  174. package/dist/i18n/messages/pt-BR.gen.js +3 -0
  175. package/dist/i18n/messages/sk.gen.js +3 -0
  176. package/dist/i18n/messages/tr.gen.js +3 -0
  177. package/dist/i18n/messages/zh-CN.gen.js +3 -0
  178. package/dist/internal/acceptedBlockProjection.js +2 -0
  179. package/dist/internal/pageBreakRunDescendantIndex.d.ts +7 -2
  180. package/dist/internal/pageBreakRunDescendantIndex.js +12 -3
  181. package/dist/internal/pageBreakRunSourceDescendantIndex.d.ts +5 -0
  182. package/dist/internal/pageBreakRunSourceDescendantIndex.js +5 -0
  183. package/dist/internal/revisionResolutionInline.js +1 -2
  184. package/dist/internal/subtreeHolds.d.ts +12 -0
  185. package/dist/internal/subtreeHolds.js +25 -0
  186. package/dist/internal/wholeStoryRevisionResolution.js +1 -1
  187. package/dist/layout-bridge/cellSelectionHighlight.js +3 -3
  188. package/dist/layout-bridge/convert/flowBlockPostprocessing.js +20 -12
  189. package/dist/layout-bridge/convert/flowConversionShared.d.ts +15 -1
  190. package/dist/layout-bridge/convert/flowConversionShared.js +9 -1
  191. package/dist/layout-bridge/convert/paragraphAttrs.d.ts +15 -4
  192. package/dist/layout-bridge/convert/paragraphAttrs.js +11 -4
  193. package/dist/layout-bridge/convert/paragraphBlockCache.d.ts +26 -0
  194. package/dist/layout-bridge/convert/paragraphBlockCache.js +137 -0
  195. package/dist/layout-bridge/convert/paragraphConversion.d.ts +12 -2
  196. package/dist/layout-bridge/convert/paragraphConversion.js +37 -5
  197. package/dist/layout-bridge/convert/paragraphRuns.d.ts +2 -2
  198. package/dist/layout-bridge/convert/sectionBoundaries.js +16 -0
  199. package/dist/layout-bridge/convert/tableConversion.js +19 -8
  200. package/dist/layout-bridge/convert/toFlowBlocks.js +144 -15
  201. package/dist/layout-bridge/convert/topLevelConversion.d.ts +74 -0
  202. package/dist/layout-bridge/convert/topLevelConversion.js +109 -0
  203. package/dist/layout-bridge/dom/clickToPositionDom.js +41 -40
  204. package/dist/layout-bridge/dom/findBodyPmSpans.js +4 -3
  205. package/dist/layout-bridge/dom/findHfPmSpans.js +10 -15
  206. package/dist/layout-bridge/dom/imeCaretAnchor.d.ts +8 -0
  207. package/dist/layout-bridge/dom/imeCaretAnchor.js +71 -7
  208. package/dist/layout-bridge/dom/textStreamDom.js +3 -2
  209. package/dist/layout-bridge/engine/blockIndex.d.ts +7 -0
  210. package/dist/layout-bridge/engine/blockIndex.js +12 -0
  211. package/dist/layout-bridge/engine/hitTest.js +9 -10
  212. package/dist/layout-bridge/engine/selectionRects.js +6 -6
  213. package/dist/layout-bridge/headerFooterLayout.js +12 -11
  214. package/dist/layout-bridge/tableInsertHover.js +2 -1
  215. package/dist/layout-engine/footnoteContinuation.d.ts +36 -0
  216. package/dist/layout-engine/footnoteContinuation.js +210 -0
  217. package/dist/layout-engine/index.d.ts +2 -2
  218. package/dist/layout-engine/index.js +7 -2
  219. package/dist/layout-engine/measure/cache.d.ts +2 -0
  220. package/dist/layout-engine/measure/cache.js +16 -6
  221. package/dist/layout-engine/measure/measureParagraph.js +1 -1
  222. package/dist/layout-engine/measure/paragraphKeyMemo.d.ts +8 -0
  223. package/dist/layout-engine/measure/paragraphKeyMemo.js +92 -0
  224. package/dist/layout-engine/tableLayout.js +29 -5
  225. package/dist/layout-engine/tableRowBreak.d.ts +36 -0
  226. package/dist/layout-engine/tableRowBreak.js +43 -1
  227. package/dist/layout-engine/types.d.ts +42 -1
  228. package/dist/layout-painter/imageLayout.js +2 -1
  229. package/dist/layout-painter/pageShellStyles.d.ts +10 -0
  230. package/dist/layout-painter/pageShellStyles.js +32 -0
  231. package/dist/layout-painter/reconcileRenderedContent.d.ts +19 -0
  232. package/dist/layout-painter/reconcileRenderedContent.js +117 -0
  233. package/dist/layout-painter/renderFragment.js +4 -6
  234. package/dist/layout-painter/renderImage.js +2 -2
  235. package/dist/layout-painter/renderPage.d.ts +4 -4
  236. package/dist/layout-painter/renderPage.js +54 -46
  237. package/dist/layout-painter/renderParagraph.js +3 -3
  238. package/dist/layout-painter/renderTable.js +16 -16
  239. package/dist/layout-painter/renderTextBox.js +2 -2
  240. package/dist/layout-painter/sdtBoundary.js +3 -2
  241. package/dist/managers/AutoSaveManager.d.ts +5 -1
  242. package/dist/managers/FindReplaceManager.js +3 -10
  243. package/dist/markdown/escape.d.ts +20 -1
  244. package/dist/markdown/escape.js +43 -1
  245. package/dist/markdown/renderBlock.js +4 -1
  246. package/dist/markdown/renderParagraph.js +13 -27
  247. package/dist/markdown/renderTable.js +6 -2
  248. package/dist/markdown/trailers.js +1 -0
  249. package/dist/paged-layout/blockGeometry.js +3 -2
  250. package/dist/paged-layout/editorScrollRoot.d.ts +9 -0
  251. package/dist/paged-layout/editorScrollRoot.js +10 -1
  252. package/dist/paged-layout/rangeProjection.js +5 -4
  253. package/dist/paged-layout/scrollToPmPosition.js +3 -3
  254. package/dist/paged-layout/selectionViewportRect.d.ts +6 -0
  255. package/dist/paged-layout/selectionViewportRect.js +8 -2
  256. package/dist/pdf/images.d.ts +17 -1
  257. package/dist/pdf/images.js +22 -4
  258. package/dist/pdf/writePdf.js +4 -2
  259. package/dist/prosemirror/attrs/index.js +2 -0
  260. package/dist/prosemirror/canonicalCommands.d.ts +39 -1
  261. package/dist/prosemirror/canonicalTableCommands.d.ts +28 -0
  262. package/dist/prosemirror/canonicalTableCommands.js +362 -0
  263. package/dist/prosemirror/commands/comments.d.ts +30 -2
  264. package/dist/prosemirror/commands/comments.js +189 -18
  265. package/dist/prosemirror/commands/formatting.d.ts +1 -1
  266. package/dist/prosemirror/commands/index.d.ts +1 -1
  267. package/dist/prosemirror/commentIdAllocator.js +2 -2
  268. package/dist/prosemirror/commentRangeBoundaryAttrs.d.ts +6 -0
  269. package/dist/prosemirror/commentRangeBoundaryAttrs.js +9 -3
  270. package/dist/prosemirror/commentRecords.d.ts +137 -0
  271. package/dist/prosemirror/commentRecords.js +400 -0
  272. package/dist/prosemirror/commentReferenceIntegrity.js +3 -4
  273. package/dist/prosemirror/conversion/fromProseDoc.d.ts +2 -0
  274. package/dist/prosemirror/conversion/fromProseDoc.js +85 -34
  275. package/dist/prosemirror/conversion/index.d.ts +2 -2
  276. package/dist/prosemirror/conversion/toProseDoc.d.ts +140 -4
  277. package/dist/prosemirror/conversion/toProseDoc.js +432 -76
  278. package/dist/prosemirror/extensions/StarterKit.js +2 -0
  279. package/dist/prosemirror/extensions/core/DocExtension.js +1 -1
  280. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.d.ts +1 -1
  281. package/dist/prosemirror/extensions/features/JoinedRunStyleExtension.d.ts +1 -1
  282. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.d.ts +1 -1
  283. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +23 -1
  284. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +61 -32
  285. package/dist/prosemirror/extensions/features/pastedHtmlLists.js +5 -4
  286. package/dist/prosemirror/extensions/marks/CommentExtension.js +8 -3
  287. package/dist/prosemirror/extensions/nodes/BlockCommentRangeBoundaryExtension.d.ts +4 -0
  288. package/dist/prosemirror/extensions/nodes/BlockCommentRangeBoundaryExtension.js +49 -0
  289. package/dist/prosemirror/extensions/nodes/CommentReferenceExtension.js +3 -1
  290. package/dist/prosemirror/extensions/nodes/ImageExtension.js +12 -3
  291. package/dist/prosemirror/extensions/nodes/TableExtension.js +32 -31
  292. package/dist/prosemirror/extensions/nodes/TextBoxExtension.js +1 -1
  293. package/dist/prosemirror/index.d.ts +3 -3
  294. package/dist/prosemirror/listLabels.js +3 -2
  295. package/dist/prosemirror/listNumbering.d.ts +6 -0
  296. package/dist/prosemirror/listNumbering.js +12 -9
  297. package/dist/prosemirror/lockedControls.d.ts +13 -0
  298. package/dist/prosemirror/lockedControls.js +106 -0
  299. package/dist/prosemirror/markupViewProjection.js +1 -1
  300. package/dist/prosemirror/nativeSelection.d.ts +33 -0
  301. package/dist/prosemirror/nativeSelection.js +74 -0
  302. package/dist/prosemirror/noteReferenceReview.js +2 -2
  303. package/dist/prosemirror/numberedRefFields.d.ts +2 -0
  304. package/dist/prosemirror/numberedRefFields.js +16 -5
  305. package/dist/prosemirror/paragraphMarkJoin.d.ts +6 -8
  306. package/dist/prosemirror/paragraphMarkJoin.js +155 -16
  307. package/dist/prosemirror/plugins/contentControlWidgets.js +2 -2
  308. package/dist/prosemirror/plugins/documentNumbering.js +37 -15
  309. package/dist/prosemirror/plugins/suggestionMode.js +33 -10
  310. package/dist/prosemirror/plugins/templatePreviewValues.js +16 -1
  311. package/dist/prosemirror/rebaseParagraphRuns.js +1 -1
  312. package/dist/prosemirror/replacedAnnotations.js +1 -0
  313. package/dist/prosemirror/runFormattingFromMarks.d.ts +0 -1
  314. package/dist/prosemirror/runFormattingFromMarks.js +2 -4
  315. package/dist/prosemirror/runFormattingReconciliation.js +2 -2
  316. package/dist/prosemirror/runIdentityAcrossRevisions.d.ts +23 -1
  317. package/dist/prosemirror/runIdentityAcrossRevisions.js +57 -8
  318. package/dist/prosemirror/runPropertyChangeResolution.js +1 -2
  319. package/dist/prosemirror/runStyleFormatting.d.ts +14 -4
  320. package/dist/prosemirror/runStyleFormatting.js +16 -13
  321. package/dist/prosemirror/schema/marks.d.ts +13 -1
  322. package/dist/prosemirror/storyListNumbering.js +7 -2
  323. package/dist/prosemirror/styles/paragraphStyleCascade.js +2 -2
  324. package/dist/prosemirror/tableResize.d.ts +10 -9
  325. package/dist/prosemirror/tableResize.js +60 -49
  326. package/dist/prosemirror/textInput.d.ts +30 -1
  327. package/dist/prosemirror/textInput.js +144 -17
  328. package/dist/prosemirror/utils/visualLineNavigation.js +20 -18
  329. package/dist/prosemirror/validation.d.ts +19 -0
  330. package/dist/prosemirror/validation.js +79 -5
  331. package/dist/redline.js +23 -9
  332. package/dist/render-dom/HeaderFooterSelectionOverlay.js +5 -4
  333. package/dist/render-dom/RenderedDomContext.js +7 -6
  334. package/dist/server.d.ts +2 -2
  335. package/dist/style-sets/extract.js +2 -2
  336. package/dist/types/canonicalCapabilities.d.ts +38 -16
  337. package/dist/types/canonicalCapabilities.js +21 -18
  338. package/dist/utils/cssString.d.ts +7 -0
  339. package/dist/utils/cssString.js +9 -0
  340. package/dist/utils/findMatchView.js +4 -3
  341. package/dist/utils/fontResolver.js +4 -1
  342. package/dist/utils/formatToStyle.d.ts +1 -1
  343. package/dist/utils/mergeDocumentContent.js +2 -2
  344. package/dist/utils/paintedPositions.d.ts +60 -0
  345. package/dist/utils/paintedPositions.js +101 -0
  346. package/dist/utils/replaceText.d.ts +11 -0
  347. package/dist/utils/replaceText.js +39 -7
  348. package/dist/version-comparison.d.ts +9 -1
  349. package/dist/version-comparison.js +11 -5
  350. package/package.json +2 -3
@@ -1,33 +1,47 @@
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
+ import { ListNormalizationCache } from "../docx/listModelNormalization.js";
3
4
  import { cloneDocumentWithParagraphPropertySources, copyDocumentParagraphPropertySourceContract, copyParagraphPropertySource, restoreParagraphIndentationProjection } from "../docx/paragraphPropertySource.js";
5
+ import { visitInlineContentSlots } from "../docx/paragraphTraversal.js";
4
6
  import { isCellMergeContinuation } from "../docx/tableParser.js";
5
7
  import { calculateRowSpans } from "../docx/verticalMergeProjection.js";
6
8
  import { canonicalCellSelectionRanges, canonicalContentPosition, canonicalSelectionRange } from "../prosemirror/canonicalSelectionRange.js";
7
- import { collectPairedBookmarkIds, footnoteToProseDoc, headerFooterToProseDoc, toProseDoc } from "../prosemirror/conversion/toProseDoc.js";
9
+ import { expectCommentRangeBoundaryAttrs } from "../prosemirror/commentRangeBoundaryAttrs.js";
10
+ import { ProjectionBlockCache, collectPairedBookmarkIds, footnoteToProseDoc, headerFooterToProseDoc, toProseDoc } from "../prosemirror/conversion/toProseDoc.js";
8
11
  import { markPackageChange } from "../prosemirror/extensions/features/ParagraphChangeTrackerExtension.js";
9
12
  import { runFormattingPatchFromMarks } from "../prosemirror/runFormattingFromMarks.js";
10
- import { CANONICAL_GAP } from "../types/canonicalCapabilities.js";
11
- import { canonicalInlineSourceIssue, canonicalNativeCells, projectCanonicalInline } from "./canonicalInlineProjection.js";
13
+ import { CANONICAL_GAP, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
14
+ import { InlineProjectionCache, canonicalNativeCells, projectCanonicalInline } from "./canonicalInlineProjection.js";
12
15
  import { normalizeCanonicalListRendering } from "./canonicalListRendering.js";
16
+ import { lockViolationBetween } from "./canonicalLockGuard.js";
17
+ import { ParagraphIdIndex, sameIdOrder, storyFactContributions } from "./canonicalProjectionBlocks.js";
18
+ import { unsupportedSeedReason } from "./canonicalSeedContent.js";
13
19
  import { restoreCanonicalSelection } from "./canonicalSelection.js";
20
+ import { canonicalSourceRestores, normalizeCanonicalSource, withUneditedSourceRestored } from "./canonicalSourceNormalization.js";
14
21
  import { mapTocSelection } from "./canonicalTocSelection.js";
15
22
  import { Result, TaggedError, panic } from "better-result";
16
23
  import { hasIllegalXmlCharacters } from "@stll/docx-core";
24
+ import { lockedControlMessage } from "@stll/docx-core/model";
17
25
  import { Fragment } from "prosemirror-model";
18
26
  import { CellSelection } from "prosemirror-tables";
19
- import { DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_TYPES, OP_STORIES, applyDocumentOp, applyDocumentOps, combineEdits, commentDocumentIssue, compileEditorIntent, createEditorIntentIdAllocator, documentStories, editorParagraphGroups, findStoryBody, normalizeForOps, packageParagraphIds, paragraphIdsIn, sameStory, 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";
20
28
  import { AllSelection, NodeSelection, Selection, TextSelection } from "prosemirror-state";
21
29
  // src/controller/canonicalSession.ts
22
30
  const CanonicalSessionErrorBase = TaggedError("CanonicalSessionError");
23
31
  var CanonicalSessionError = class extends CanonicalSessionErrorBase {};
24
32
  const refuse = (message) => Result.err(new CanonicalSessionError({
25
- gap: CANONICAL_GAP.dispatch,
33
+ ground: { gap: CANONICAL_GAP.dispatch },
26
34
  message,
27
35
  reason: "refused"
28
36
  }));
37
+ /** A change a content control's lock forbids: the document's rule, not a gap. */
38
+ const lockRefusal = (violation) => Result.err(new CanonicalSessionError({
39
+ ground: { rule: CANONICAL_RULE.contentControlLock },
40
+ message: `Refused: ${lockedControlMessage(violation)}`,
41
+ reason: "refused"
42
+ }));
29
43
  const noChange = (message) => Result.err(new CanonicalSessionError({
30
- gap: CANONICAL_GAP.dispatch,
44
+ ground: { gap: CANONICAL_GAP.dispatch },
31
45
  message,
32
46
  reason: "noChange"
33
47
  }));
@@ -80,7 +94,12 @@ const operationChangesStructure = (op) => {
80
94
  case DOCUMENT_OP_TYPES.MERGE_CELLS:
81
95
  case DOCUMENT_OP_TYPES.SPLIT_CELL:
82
96
  case DOCUMENT_OP_TYPES.SET_TABLE:
83
- case DOCUMENT_OP_TYPES.RESOLVE_REVISION: return true;
97
+ case DOCUMENT_OP_TYPES.RESOLVE_REVISION:
98
+ case DOCUMENT_OP_TYPES.SET_TABLE_GRID:
99
+ case DOCUMENT_OP_TYPES.SET_CELL_PROPS:
100
+ case DOCUMENT_OP_TYPES.SET_ROW_PROPS:
101
+ case DOCUMENT_OP_TYPES.SET_TABLE_PROPS:
102
+ case DOCUMENT_OP_TYPES.SET_REVISION_INFO: return true;
84
103
  case DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER:
85
104
  case DOCUMENT_OP_TYPES.REMOVE_HEADER_FOOTER:
86
105
  case DOCUMENT_OP_TYPES.ADD_NOTE:
@@ -100,10 +119,6 @@ const operationChangesStructure = (op) => {
100
119
  case DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS:
101
120
  case DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW:
102
121
  case DOCUMENT_OP_TYPES.REPLACE_INLINE:
103
- case DOCUMENT_OP_TYPES.SET_TABLE_GRID:
104
- case DOCUMENT_OP_TYPES.SET_CELL_PROPS:
105
- case DOCUMENT_OP_TYPES.SET_ROW_PROPS:
106
- case DOCUMENT_OP_TYPES.SET_TABLE_PROPS:
107
122
  case DOCUMENT_OP_TYPES.CREATE_COMMENT:
108
123
  case DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT:
109
124
  case DOCUMENT_OP_TYPES.SET_COMMENT_RESOLUTION:
@@ -138,53 +153,172 @@ const operationChangesBodyProjection = (op) => {
138
153
  };
139
154
  const CANONICAL_PROJECTION_META = "folioCanonicalProjection";
140
155
  /** Paragraph gaps bind logical units and source zero-width ordinals to PM positions. */
141
- var CanonicalProjection = class {
156
+ var CanonicalProjection = class CanonicalProjection {
142
157
  doc;
143
158
  story;
144
- paragraphs;
145
- paragraphsById;
146
- constructor({ doc, paragraphs, story }) {
147
- this.story = story;
148
- this.doc = doc;
149
- this.paragraphs = paragraphs;
150
- this.paragraphsById = new Map(paragraphs.map((paragraph) => [paragraph.blockId, paragraph]));
151
- }
152
- addressAt(position) {
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;
187
+ }
188
+ /**
189
+ * The same projection held as `doc`, a document equal to this one's. A
190
+ * commit's transaction ends on a document equal to the projection it staged,
191
+ * sharing the blocks it left; holding that document lets the next commit see
192
+ * the state it was given is the projection without comparing every node.
193
+ */
194
+ heldAs(doc) {
195
+ return new CanonicalProjection({
196
+ doc,
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
206
+ });
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
+ }
254
+ addressAt(position, edge = "caret") {
153
255
  if (!Number.isInteger(position)) return refuse("The input position is not an integer.");
154
256
  position = canonicalContentPosition(this.doc, position);
155
- const paragraph = this.paragraphs.find(({ start, node }) => position >= start && position <= start + node.content.size);
257
+ const paragraph = this.paragraphAround(position);
156
258
  if (paragraph === void 0) return refuse("The input is outside a plain paragraph.");
157
259
  const relative = position - paragraph.start;
158
260
  const offset = paragraph.boundaries.findIndex((gaps) => gaps.some((gap) => gap.position === relative));
159
261
  if (offset < 0) return refuse("The input splits an indivisible inline element.");
160
262
  if (splitsSurrogatePair(paragraph.text, offset)) return refuse("The input would split a surrogate pair.");
161
263
  const gaps = paragraph.boundaries.at(offset) ?? panic("Missing canonical boundary");
162
- const gap = gaps.find((entry) => entry.position === relative) ?? panic("Missing canonical native gap");
264
+ const index = gaps.findIndex((entry) => entry.position === relative);
265
+ const gap = gaps[index] ?? panic("Missing canonical native gap");
266
+ const seam = paragraph.seams.at(offset)?.[index] ?? panic("Missing canonical seam");
267
+ let ordinal = gap.zeroWidthBefore;
268
+ if (edge === "afterMarkers") ordinal = seam.last;
269
+ if (edge === "beforeMarkers") ordinal = seam.first;
163
270
  return Result.ok({
164
271
  story: this.story,
165
272
  blockId: paragraph.blockId,
166
273
  offset,
167
- ...gaps.length > 1 || gap.zeroWidthBefore > 0 ? { zeroWidthBefore: gap.zeroWidthBefore } : {}
274
+ ...gaps.length > 1 || ordinal > 0 || seam.first !== seam.last ? { zeroWidthBefore: ordinal } : {}
168
275
  });
169
276
  }
170
- inputAddressAt(position) {
171
- const address = this.addressAt(position);
277
+ /**
278
+ * The source gaps a selection from `from` to `to` replaces between. Its
279
+ * edges stay inside the markers beside them, so replacing exactly the
280
+ * words a comment covers keeps the comment on the new text. A selection of
281
+ * a paragraph's whole text takes that paragraph's markers with it: an edge
282
+ * at the very start of a paragraph whose text the selection covers to its
283
+ * end reaches before the markers there, and an edge at the very end of a
284
+ * paragraph the selection covers from its start reaches after them, so a
285
+ * comment on nothing but the replaced text is emptied, as removing the
286
+ * text would empty it.
287
+ */
288
+ rangeEdgesAt(from, to) {
289
+ const paragraphOf = (position) => this.paragraphAround(canonicalContentPosition(this.doc, position));
290
+ const first = paragraphOf(from);
291
+ const last = paragraphOf(to);
292
+ const startsWhole = first !== void 0 && canonicalContentPosition(this.doc, from) === first.start && canonicalContentPosition(this.doc, to) >= first.start + first.node.content.size;
293
+ const endsWhole = last !== void 0 && canonicalContentPosition(this.doc, to) === last.start + last.node.content.size && canonicalContentPosition(this.doc, from) <= last.start;
294
+ return {
295
+ start: startsWhole ? "beforeMarkers" : "afterMarkers",
296
+ end: endsWhole ? "afterMarkers" : "beforeMarkers"
297
+ };
298
+ }
299
+ inputAddressAt(position, edge = "caret") {
300
+ const address = this.addressAt(position, edge);
172
301
  if (address.isErr()) return address;
173
302
  const paragraph = this.paragraph(address.value.blockId);
174
303
  if (paragraph === void 0) panic("Input lost its paragraph.");
175
304
  let destination = position;
176
305
  paragraph.node.forEach((node, start) => {
177
- if (node.marks.some((mark) => mark.type.name === "deletion") && destination >= paragraph.start + start && destination < paragraph.start + start + node.nodeSize) destination = paragraph.start + start + node.nodeSize;
306
+ if (node.marks.some((mark) => mark.type.name === "deletion") && destination > paragraph.start + start && destination < paragraph.start + start + node.nodeSize) destination = paragraph.start + start + node.nodeSize;
178
307
  });
179
- return destination === position ? address : this.addressAt(destination);
308
+ return destination === position ? address : this.addressAt(destination, edge);
180
309
  }
181
310
  positionAt(address) {
182
311
  const paragraph = this.paragraph(address.blockId);
183
312
  if (!sameStory(address.story, this.story) || paragraph === void 0 || !Number.isInteger(address.offset) || address.offset < 0 || address.offset > paragraph.text.length || splitsSurrogatePair(paragraph.text, address.offset)) return refuse("The canonical selection is outside a plain paragraph.");
184
313
  const gaps = paragraph.boundaries.at(address.offset) ?? panic("Missing canonical boundary");
185
- const ordinal = address.zeroWidthBefore ?? (gaps.at(-1) ?? panic("Missing canonical gap")).zeroWidthBefore;
186
- const gap = gaps.find(({ zeroWidthBefore }) => zeroWidthBefore === ordinal);
187
- if (!Number.isInteger(ordinal) || ordinal < 0 || ordinal > (gaps.at(-1)?.zeroWidthBefore ?? 0)) return refuse("The canonical selection is outside a paragraph gap.");
314
+ const seams = paragraph.seams.at(address.offset) ?? panic("Missing canonical seams");
315
+ const lastOrdinal = (seams.at(-1) ?? panic("Missing canonical seam")).last;
316
+ const ordinal = address.zeroWidthBefore ?? lastOrdinal;
317
+ const gap = gaps.find(({ zeroWidthBefore }) => zeroWidthBefore === ordinal) ?? gaps.find((_, index) => {
318
+ const seam = seams[index];
319
+ return seam !== void 0 && seam.first <= ordinal && ordinal <= seam.last;
320
+ });
321
+ if (!Number.isInteger(ordinal) || ordinal < 0 || ordinal > lastOrdinal) return refuse("The canonical selection is outside a paragraph gap.");
188
322
  if (gap === void 0) return refuse("This source gap is inside a collapsed or erased inline boundary and has no editor position.");
189
323
  return Result.ok(paragraph.start + gap.position);
190
324
  }
@@ -215,15 +349,34 @@ var CanonicalProjection = class {
215
349
  head: head.value
216
350
  });
217
351
  }
352
+ /** The first paragraph the projection addresses, in document order. */
353
+ get firstParagraph() {
354
+ const block = this.blocks.findIndex(({ paragraphs }) => paragraphs.length > 0);
355
+ return block < 0 ? void 0 : this.addressOf(block, 0);
356
+ }
218
357
  paragraph(blockId) {
219
- 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;
220
366
  }
221
367
  nextParagraphInContainer(blockId) {
222
- const index = this.paragraphs.findIndex((paragraph) => paragraph.blockId === blockId);
223
- if (index < 0) return void 0;
224
- const paragraph = this.paragraphs.at(index);
225
- const next = this.paragraphs.at(index + 1);
226
- 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;
227
380
  }
228
381
  };
229
382
  /** Immutable operations retain content identities for every untouched story. */
@@ -287,160 +440,380 @@ const preservePropertySources = ({ target, source, stories = documentStories(sou
287
440
  }
288
441
  copyDocumentParagraphPropertySourceContract(target, source);
289
442
  };
290
- const unsupportedSeedReason = (document, stories = documentStories(document)) => {
291
- const commentIssue = commentDocumentIssue(document, "all");
292
- if (commentIssue !== void 0) return commentIssue;
293
- for (const story of stories) {
294
- const body = findStoryBody(document, story);
295
- if (story !== OP_STORIES.MAIN && (story.kind === "footnote" || story.kind === "endnote")) {
296
- const note = (story.kind === "footnote" ? document.package.footnotes : document.package.endnotes)?.find(({ id }) => id === story.id);
297
- if (note?.noteType !== void 0 && note.noteType !== "normal") continue;
298
- }
299
- const content = body?.content;
300
- if (!content || content.length === 0) return "Canonical sessions require a nonempty paragraph story.";
301
- const paragraphs = [];
302
- const collect = (blocks) => {
303
- for (const block of blocks) {
304
- if (block.type === "paragraph") {
305
- paragraphs.push(block);
306
- continue;
307
- }
308
- if (block.type !== "table") return "Canonical sessions currently require paragraphs, tables and supported inline atoms.";
309
- for (const row of block.rows) for (const cell of row.cells) {
310
- const issue = collect(cell.content);
311
- if (issue !== null) return issue;
312
- }
313
- }
314
- return null;
315
- };
316
- const blockIssue = collect(content);
317
- if (blockIssue !== null) return blockIssue;
318
- for (const paragraph of paragraphs) {
319
- if (paragraph.reviewCarrier !== void 0) return "Canonical sessions currently require plain paragraphs and supported inline atoms.";
320
- const issue = canonicalInlineSourceIssue(paragraph.content);
321
- if (issue !== null) return issue;
443
+ const newStoryProjectionCaches = () => ({
444
+ blocks: new ProjectionBlockCache(),
445
+ inline: new InlineProjectionCache(),
446
+ lists: new ListNormalizationCache(),
447
+ comments: new CommentMarkerCache()
448
+ });
449
+ /** Whether a paragraph anchors a text box, which converts to a block of its own. */
450
+ const holdsTextBox = (paragraph) => {
451
+ let found = false;
452
+ visitInlineContentSlots(paragraph, ({ item }) => {
453
+ if (item.type === "run" && item.content.some((content) => content.type === "shape" && content.shape.textBody !== void 0)) found = true;
454
+ });
455
+ return found;
456
+ };
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;
322
486
  }
323
487
  }
324
- return null;
325
488
  };
326
- const project = ({ document, styles, story = OP_STORIES.MAIN }) => {
327
- const body = findStoryBody(document, story);
328
- if (!body) return refuse("The canonical story no longer exists.");
329
- const currentStyles = Object.hasOwn(document.package, "styles") ? document.package.styles : styles;
330
- const options = {
331
- ...currentStyles == null ? {} : { styles: currentStyles },
332
- ...document.package.theme === void 0 ? {} : { theme: document.package.theme }
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
333
496
  };
334
- const converted = Result.try({
335
- try: () => {
336
- if (story === OP_STORIES.MAIN) return toProseDoc(document, options);
337
- if (story.kind === "header" || story.kind === "footer") return headerFooterToProseDoc(body.content, options);
338
- return footnoteToProseDoc(body.content, options);
339
- },
340
- catch: (cause) => new CanonicalSessionError({
341
- gap: CANONICAL_GAP.dispatch,
342
- reason: "refused",
343
- message: `Canonical projection failed: ${cause instanceof Error ? cause.message : String(cause)}`
344
- })
345
- });
346
- if (converted.isErr()) return converted;
347
- const pairedBookmarkIds = collectPairedBookmarkIds(body.content);
348
- const commentContext = {
349
- rangedIds: rangedCommentIds(body.content),
350
- pointIds: /* @__PURE__ */ new Set(),
351
- openIds: /* @__PURE__ */ new Set()
497
+ const at = {
498
+ top: start,
499
+ ids: []
352
500
  };
353
- visitCommentMarkers(body.content, ({ item }) => {
354
- if (item.type === "commentReference" && !commentContext.rangedIds.has(item.id)) commentContext.pointIds.add(item.id);
355
- });
356
- const sources = /* @__PURE__ */ new Map();
357
- const allSources = /* @__PURE__ */ new Set();
358
- const continuationSources = /* @__PURE__ */ new Set();
359
- const collectSources = (blocks, insideSkippedContinuation = false) => {
360
- for (const block of blocks) {
361
- if (block.type === "paragraph") {
362
- allSources.add(block);
363
- if (insideSkippedContinuation) continuationSources.add(block);
364
- if (block.paraId !== void 0) sources.set(block.paraId, {
365
- source: block,
366
- container: blocks
367
- });
368
- continue;
369
- }
370
- if (block.type !== "table") continue;
371
- const rowSpans = calculateRowSpans(block);
372
- for (const [rowIndex, row] of block.rows.entries()) {
373
- let column = row.formatting?.gridBefore ?? 0;
374
- for (const cell of row.cells) {
375
- const skippedContinuation = isCellMergeContinuation(cell) && (rowSpans.get(`${rowIndex}-${column}`)?.skip ?? false);
376
- collectSources(cell.content, insideSkippedContinuation || skippedContinuation);
377
- column += cell.formatting?.gridSpan ?? 1;
378
- }
379
- }
380
- }
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
510
+ });
511
+ at.ids.push(source.paraId);
381
512
  };
382
- collectSources(body.content);
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) => {
383
547
  const paragraphs = [];
384
- const projectedSources = /* @__PURE__ */ new Set();
548
+ let local = true;
385
549
  let failure;
386
- converted.value.descendants((node, offset) => {
387
- if (failure !== void 0) return;
388
- if (node.type.name !== "paragraph") return;
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) => {
556
+ if (failure !== void 0) return false;
557
+ if (node.type.name === "textBox") {
558
+ if (node.attrs["_docxPlacement"] === "standalone" && node.attrs["_docxHostParagraph"] != null && !walk.claimTextBoxHost()) failure = structureRefusal();
559
+ return false;
560
+ }
561
+ if (node.type.name === "blockCommentRangeBoundary") {
562
+ const { marker } = expectCommentRangeBoundaryAttrs(node);
563
+ if (marker.type === "commentRangeStart") walk.open.ids.add(marker.id);
564
+ else walk.open.ids.delete(marker.id);
565
+ return false;
566
+ }
567
+ if (node.type.name !== "paragraph") return true;
568
+ if (parent?.attrs["_omittedGridSlot"] != null) return false;
389
569
  const paraId = node.attrs["paraId"];
390
- const located = typeof paraId === "string" ? sources.get(paraId) : void 0;
570
+ const located = typeof paraId === "string" ? walk.locate(paraId) : void 0;
391
571
  if (typeof paraId !== "string" || located === void 0) {
392
- failure = new CanonicalSessionError({
393
- gap: CANONICAL_GAP.storyContentProjection,
394
- reason: "refused",
395
- message: "The projection changed paragraph structure."
396
- });
397
- return;
572
+ failure = structureRefusal();
573
+ return false;
398
574
  }
399
575
  const { source, container } = located;
400
- if (projectedSources.has(source)) {
401
- failure = new CanonicalSessionError({
402
- gap: CANONICAL_GAP.storyContentProjection,
403
- reason: "refused",
404
- message: "The projection changed paragraph structure."
405
- });
406
- return;
576
+ if (!walk.take(source)) {
577
+ failure = structureRefusal();
578
+ return false;
407
579
  }
408
- projectedSources.add(source);
409
- const inline = projectCanonicalInline({
580
+ if (located.top !== index) local = false;
581
+ const inlineArgs = {
410
582
  source,
411
583
  paragraph: node,
412
- pairedBookmarkIds,
584
+ pairedBookmarkIds: walk.facts.pairedBookmarkIds,
413
585
  commentContext
414
- });
586
+ };
587
+ const inline = walk.inline === void 0 ? projectCanonicalInline(inlineArgs) : walk.inline.project(inlineArgs);
415
588
  if (inline.isErr()) {
416
589
  failure = new CanonicalSessionError({
417
- gap: CANONICAL_GAP.dispatch,
590
+ ground: { gap: CANONICAL_GAP.dispatch },
418
591
  reason: "refused",
419
592
  message: inline.error.message
420
593
  });
421
- return;
594
+ return false;
422
595
  }
423
596
  paragraphs.push({
424
597
  blockId: paraId,
425
- container,
426
- start: offset + 1,
427
- ...inline.value,
598
+ container: container === walk.content ? void 0 : container,
599
+ offset: offset + 1,
600
+ inline: inline.value,
428
601
  node,
429
602
  source
430
603
  });
431
- visitCommentMarkers([source], ({ item }) => {
432
- if (item.type === "commentRangeStart") commentContext.openIds.add(item.id);
433
- if (item.type === "commentRangeEnd") commentContext.openIds.delete(item.id);
434
- });
435
- });
604
+ walk.passComments(source);
605
+ return false;
606
+ };
607
+ if (visit(top, 0, null) && top.content.size > 0) top.descendants((node, offset, parent) => visit(node, offset + 1, parent));
436
608
  if (failure !== void 0) return Result.err(failure);
437
- if (projectedSources.size + continuationSources.size !== allSources.size || [...projectedSources].some((source) => continuationSources.has(source))) return refuse("The projection changed paragraph structure.");
438
- return Result.ok(new CanonicalProjection({
439
- doc: converted.value,
609
+ return Result.ok({
440
610
  paragraphs,
441
- story
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
+ }
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.");
691
+ return Result.ok(new CanonicalProjection({
692
+ doc,
693
+ story,
694
+ content,
695
+ blocks,
696
+ index: ParagraphIdIndex.of(blocks),
697
+ facts,
698
+ reusable
442
699
  }));
443
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
+ };
444
817
  const intentStory = (intent) => {
445
818
  switch (intent.type) {
446
819
  case "setHyperlink":
@@ -455,8 +828,12 @@ const intentStory = (intent) => {
455
828
  case "splitParagraph":
456
829
  case "formatParagraph": return intent.at.story;
457
830
  case "setList": return intent.items.at(0)?.at.story ?? panic("A list intent requires a paragraph.");
458
- case "joinParagraphs": return intent.story;
459
- case "table": return intent.operation.story;
831
+ case "joinParagraphs":
832
+ case "insertParagraphs":
833
+ case "deleteParagraphs": return intent.story;
834
+ case "table":
835
+ case "tableRow":
836
+ case "tableBlock": return intent.operation.story;
460
837
  default: return intent;
461
838
  }
462
839
  };
@@ -490,7 +867,7 @@ const publishCanonicalProjection = ({ state, commit, session }) => {
490
867
  const applied = Result.try({
491
868
  try: () => state.applyTransaction(commit.transaction),
492
869
  catch: (cause) => new CanonicalSessionError({
493
- gap: CANONICAL_GAP.dispatch,
870
+ ground: { gap: CANONICAL_GAP.dispatch },
494
871
  reason: "refused",
495
872
  message: `Canonical plugin staging failed: ${cause instanceof Error ? cause.message : String(cause)}`
496
873
  })
@@ -531,7 +908,12 @@ var CanonicalSession = class {
531
908
  lifecycle = { type: "committed" };
532
909
  undone = [];
533
910
  styles;
534
- constructor({ document, projection, styles }) {
911
+ sourceRestores;
912
+ /** What earlier projections converted, reused by every later one. */
913
+ caches;
914
+ constructor({ document, projection, styles, sourceRestores = [], caches }) {
915
+ this.sourceRestores = sourceRestores;
916
+ this.caches = caches;
535
917
  this.currentDocument = document;
536
918
  this.currentProjection = projection;
537
919
  this.sourceBlockIds = new Set(packageParagraphIds(document.package));
@@ -606,7 +988,11 @@ var CanonicalSession = class {
606
988
  intentNeedsIdentityIds(document, intent) {
607
989
  let blockIds;
608
990
  switch (intent.type) {
609
- case "table": return true;
991
+ case "table":
992
+ case "tableRow":
993
+ case "tableBlock":
994
+ case "insertParagraphs":
995
+ case "deleteParagraphs": return true;
610
996
  case "generateTOC":
611
997
  case "setList":
612
998
  case "formatParagraph": return false;
@@ -647,7 +1033,7 @@ var CanonicalSession = class {
647
1033
  }
648
1034
  get document() {
649
1035
  if (this.isComposing) throw new CanonicalSessionError({
650
- gap: CANONICAL_GAP.dispatch,
1036
+ ground: { gap: CANONICAL_GAP.dispatch },
651
1037
  reason: "refused",
652
1038
  message: "Composition must finish before taking a snapshot."
653
1039
  });
@@ -655,13 +1041,13 @@ var CanonicalSession = class {
655
1041
  }
656
1042
  captureSaveSnapshot() {
657
1043
  if (this.isComposing) throw new CanonicalSessionError({
658
- gap: CANONICAL_GAP.save,
1044
+ ground: { gap: CANONICAL_GAP.save },
659
1045
  reason: "refused",
660
1046
  message: "Composition must finish before saving the canonical document."
661
1047
  });
662
1048
  const retainedBlockIdKeys = new Set([...this.sourceBlockIds, ...packageParagraphIds(this.currentDocument.package)].map((blockId) => blockId.toUpperCase()));
663
1049
  return {
664
- document: cloneDocumentWithParagraphPropertySources(this.currentDocument),
1050
+ document: withUneditedSourceRestored(cloneDocumentWithParagraphPropertySources(this.currentDocument), this.sourceRestores),
665
1051
  version: this.currentVersion,
666
1052
  changedBlockIds: [...this.saveTouched].filter((blockId) => retainedBlockIdKeys.has(blockId.toUpperCase())),
667
1053
  structure: this.saveStructure
@@ -670,9 +1056,20 @@ var CanonicalSession = class {
670
1056
  get projection() {
671
1057
  return this.currentProjection;
672
1058
  }
1059
+ /** The caret the last published edit returned, when the editor shows it at `position`. */
1060
+ editCaretAt(projection, position) {
1061
+ const caret = this.currentSelection;
1062
+ if (caret === null || caret.type !== "text" || caret.anchor.offset !== caret.head.offset || caret.anchor.blockId !== caret.head.blockId || (caret.anchor.zeroWidthBefore ?? null) !== (caret.head.zeroWidthBefore ?? null) || !sameStory(caret.head.story, projection.story)) return void 0;
1063
+ const shown = projection.positionAt(caret.head);
1064
+ return shown.isOk() && shown.value === position ? caret.head : void 0;
1065
+ }
673
1066
  get selection() {
674
1067
  return this.currentSelection;
675
1068
  }
1069
+ /** Every paragraph identity this session has read or minted, live or retired. */
1070
+ get reservedBlockIds() {
1071
+ return this.allocatedBlockIds;
1072
+ }
676
1073
  get version() {
677
1074
  return this.currentVersion;
678
1075
  }
@@ -700,7 +1097,7 @@ var CanonicalSession = class {
700
1097
  }
701
1098
  checkState(state, projection = this.projection) {
702
1099
  if (this.isComposing) return refuse("Composition must finish before committing another edit.");
703
- if (!state.doc.eq(projection.doc)) return refuse("The input uses a stale canonical projection.");
1100
+ if (state.doc !== projection.doc && !state.doc.eq(projection.doc)) return refuse("The input uses a stale canonical projection.");
704
1101
  return Result.ok(void 0);
705
1102
  }
706
1103
  prepareReplace(state, { from, to, text, story = OP_STORIES.MAIN, semantic = "replacement", compositionPhase, time = Date.now() }) {
@@ -715,19 +1112,21 @@ var CanonicalSession = class {
715
1112
  const replacesStructuralSelection = state.selection instanceof AllSelection && from === state.selection.from && to === state.selection.to;
716
1113
  if (state.selection instanceof CellSelection) {
717
1114
  if (from !== state.selection.from || to !== state.selection.to) return refuse("A replacement range cannot partially address a cell selection.");
718
- if (text.length > 0) return refuse("Replacing a cell selection requires a per-cell replacement.");
719
1115
  const intents = [];
1116
+ let first = true;
720
1117
  for (const range of canonicalCellSelectionRanges(state.selection)) {
721
- const cellFrom = projection.inputAddressAt(range.from);
1118
+ const edges = projection.rangeEdgesAt(range.from, range.to);
1119
+ const cellFrom = projection.inputAddressAt(range.from, edges.start);
722
1120
  if (cellFrom.isErr()) return cellFrom;
723
- const cellTo = projection.inputAddressAt(range.to);
1121
+ const cellTo = projection.inputAddressAt(range.to, edges.end);
724
1122
  if (cellTo.isErr()) return cellTo;
725
1123
  intents.push({
726
1124
  type: "replaceText",
727
1125
  from: cellFrom.value,
728
1126
  to: cellTo.value,
729
- text: ""
1127
+ text: first ? text : ""
730
1128
  });
1129
+ first = false;
731
1130
  }
732
1131
  return this.prepareIntents(state, {
733
1132
  intents,
@@ -737,17 +1136,32 @@ var CanonicalSession = class {
737
1136
  const range = canonicalSelectionRange(state);
738
1137
  const inputFrom = replacesStructuralSelection ? range.from : from;
739
1138
  const inputTo = replacesStructuralSelection ? range.to : to;
740
- const start = projection.inputAddressAt(inputFrom);
1139
+ const edges = inputFrom === inputTo ? {
1140
+ start: "caret",
1141
+ end: "caret"
1142
+ } : projection.rangeEdgesAt(inputFrom, inputTo);
1143
+ const editCaret = this.editCaretAt(projection, inputFrom);
1144
+ const start = inputFrom === inputTo && editCaret !== void 0 ? Result.ok(editCaret) : projection.inputAddressAt(inputFrom, edges.start);
741
1145
  if (start.isErr()) return start;
742
- const end = projection.inputAddressAt(inputTo);
1146
+ const end = inputFrom === inputTo && editCaret !== void 0 ? Result.ok(editCaret) : projection.inputAddressAt(inputTo, edges.end);
743
1147
  if (end.isErr()) return end;
744
1148
  const preSelection = projection.selectionAt(state);
745
1149
  if (preSelection.isErr()) return preSelection;
1150
+ const innerEdge = (position, side) => {
1151
+ const resolved = state.doc.resolve(position);
1152
+ return resolved.parent.type.name === "sdt" && resolved.parentOffset === (side === "start" ? 0 : resolved.parent.content.size);
1153
+ };
1154
+ const inside = {
1155
+ ...innerEdge(inputFrom, "start") ? { start: true } : {},
1156
+ ...innerEdge(inputTo, "end") ? { end: true } : {}
1157
+ };
1158
+ if (this.mode.type === "suggesting" && text.length > 0 && inside.start === true && inside.end === true && state.doc.resolve(inputFrom).parent === state.doc.resolve(inputTo).parent) return refuse("A suggestion over a content control's whole text is unavailable in this session.");
746
1159
  const intent = {
747
1160
  type: "replaceText",
748
1161
  from: start.value,
749
1162
  to: end.value,
750
1163
  text,
1164
+ ...Object.keys(inside).length === 0 ? {} : { inside },
751
1165
  ...state.storedMarks === null ? {} : { runPropsPatch: runFormattingPatchFromMarks(state.selection.$from.marks(), state.storedMarks) }
752
1166
  };
753
1167
  const compiled = compileEditorIntent(this.currentDocument, {
@@ -771,6 +1185,7 @@ var CanonicalSession = class {
771
1185
  ops,
772
1186
  selection: postSelection,
773
1187
  origin: "input",
1188
+ ...compiled.value.applied === void 0 ? {} : { stagedApplied: compiled.value.applied },
774
1189
  onPublish: (inverse, version) => {
775
1190
  const entry = {
776
1191
  type: "applied",
@@ -802,6 +1217,44 @@ var CanonicalSession = class {
802
1217
  }
803
1218
  });
804
1219
  }
1220
+ /**
1221
+ * A structural edit over selected cells: each selected cell is cleared and
1222
+ * the edit happens at the start of the first, as the editor's own command
1223
+ * does over a cell selection. One commit, so one undo step.
1224
+ */
1225
+ prepareCellSelectionStructure(state, structure, { resourceOps = [], semantic = "structure" } = {}) {
1226
+ if (!(state.selection instanceof CellSelection)) return refuse("The structural edit needs a cell selection.");
1227
+ const projected = this.projectStory(OP_STORIES.MAIN);
1228
+ if (projected.isErr()) return projected;
1229
+ const projection = projected.value;
1230
+ const intents = [];
1231
+ let first;
1232
+ for (const range of canonicalCellSelectionRanges(state.selection)) {
1233
+ const edges = projection.rangeEdgesAt(range.from, range.to);
1234
+ const cellFrom = projection.inputAddressAt(range.from, edges.start);
1235
+ if (cellFrom.isErr()) return cellFrom;
1236
+ const cellTo = projection.inputAddressAt(range.to, edges.end);
1237
+ if (cellTo.isErr()) return cellTo;
1238
+ first ??= cellFrom.value;
1239
+ if (cellFrom.value.blockId !== cellTo.value.blockId || cellFrom.value.offset !== cellTo.value.offset) intents.push({
1240
+ type: "replaceText",
1241
+ from: cellFrom.value,
1242
+ to: cellTo.value,
1243
+ text: ""
1244
+ });
1245
+ }
1246
+ if (first === void 0) return refuse("The cell selection is empty.");
1247
+ intents.push(structure({
1248
+ ...first,
1249
+ offset: 0,
1250
+ zeroWidthBefore: 0
1251
+ }));
1252
+ return this.prepareIntents(state, {
1253
+ intents,
1254
+ resourceOps,
1255
+ semantic
1256
+ });
1257
+ }
805
1258
  prepareIntent(state, intent) {
806
1259
  return this.prepareIntents(state, { intents: [intent] });
807
1260
  }
@@ -828,7 +1281,7 @@ var CanonicalSession = class {
828
1281
  }
829
1282
  for (const intent of intents) {
830
1283
  if (this.mode.type === "suggesting" && (intent.type === "setHyperlink" || intent.type === "removeHyperlink" || intent.type === "insertHyperlink" || intent.type === "generateTOC")) return Result.err(new CanonicalSessionError({
831
- gap: CANONICAL_GAP.trackedHyperlinkResolution,
1284
+ ground: { gap: CANONICAL_GAP.trackedHyperlinkResolution },
832
1285
  reason: "refused",
833
1286
  message: "Hyperlink and TOC suggestions require serializable wrapper review provenance."
834
1287
  }));
@@ -840,13 +1293,13 @@ var CanonicalSession = class {
840
1293
  if (compiled.isErr()) {
841
1294
  if (compiled.error.reason === DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE) return noChange(compiled.error.message);
842
1295
  if (compiled.error.reason === DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE && (intent.type === "setHyperlink" || intent.type === "removeHyperlink" || intent.type === "insertHyperlink")) return Result.err(new CanonicalSessionError({
843
- gap: CANONICAL_GAP.trackedHyperlinkResolution,
1296
+ ground: { gap: CANONICAL_GAP.trackedHyperlinkResolution },
844
1297
  reason: "refused",
845
1298
  message: compiled.error.message
846
1299
  }));
847
1300
  return refuse(compiled.error.message);
848
1301
  }
849
- 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);
850
1303
  if (applied.isErr()) return applied.error.reason === DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE ? noChange(applied.error.message) : refuse(applied.error.message);
851
1304
  document = applied.value.document;
852
1305
  edits.push(applied.value);
@@ -975,35 +1428,48 @@ var CanonicalSession = class {
975
1428
  nextBlockId: second.paraId
976
1429
  });
977
1430
  }
978
- prepareResolve(state, { revisionIds, resolution }) {
1431
+ prepareResolve(state, { revisionIds, resolution, before = [] }) {
979
1432
  const checked = this.checkState(state);
980
1433
  if (checked.isErr()) return checked;
981
1434
  const preSelection = this.projection.selectionAt(state);
982
1435
  if (preSelection.isErr()) return preSelection;
983
- const ops = [{
1436
+ const resolve = (ids) => [{
984
1437
  type: DOCUMENT_OP_TYPES.RESOLVE_REVISION,
985
1438
  story: OP_STORIES.MAIN,
986
- revisionIds,
1439
+ revisionIds: ids,
987
1440
  decision: resolution
988
1441
  }];
1442
+ let firstHeld = null;
1443
+ const lockHeld = revisionIds.filter((id) => {
1444
+ const alone = applyDocumentOps(this.currentDocument, resolve([id]));
1445
+ if (alone.isErr()) return false;
1446
+ const violation = lockViolationBetween(this.currentDocument, alone.value.document);
1447
+ firstHeld ??= violation;
1448
+ return violation !== null;
1449
+ });
1450
+ if (firstHeld !== null && lockHeld.length === revisionIds.length) return lockRefusal(firstHeld);
1451
+ const resolved = revisionIds.filter((id) => !lockHeld.includes(id));
1452
+ const ops = [...before, ...resolved.length === 0 ? [] : resolve(resolved)];
989
1453
  const applied = applyDocumentOps(this.currentDocument, ops);
990
1454
  if (applied.isErr()) return refuse(applied.error.message);
991
1455
  const projected = project({
992
1456
  document: applied.value.document,
993
- styles: this.styles
1457
+ styles: this.styles,
1458
+ caches: this.caches,
1459
+ previous: this.currentProjection
994
1460
  });
995
1461
  if (projected.isErr()) return projected;
996
1462
  const surviving = projected.value.paragraph(preSelection.value.head.blockId);
997
- const first = applied.value.document.package.document.content.at(0);
998
- if (first?.type !== "paragraph" || first.paraId === void 0) return refuse("Resolution left no paragraph.");
1463
+ const first = projected.value.firstParagraph;
1464
+ if (first === void 0) return refuse("Resolution left no paragraph.");
999
1465
  let offset = surviving ? Math.min(preSelection.value.head.offset, surviving.text.length) : 0;
1000
1466
  if (surviving && splitsSurrogatePair(surviving.text, offset)) offset -= 1;
1001
1467
  const caret = {
1002
1468
  story: OP_STORIES.MAIN,
1003
- blockId: surviving?.blockId ?? first.paraId,
1469
+ blockId: surviving?.blockId ?? first.blockId,
1004
1470
  offset
1005
1471
  };
1006
- return this.prepareJournalledOps({
1472
+ const prepared = this.prepareJournalledOps({
1007
1473
  state,
1008
1474
  ops,
1009
1475
  postSelection: {
@@ -1013,6 +1479,57 @@ var CanonicalSession = class {
1013
1479
  },
1014
1480
  stagedApplied: applied.value
1015
1481
  });
1482
+ return prepared.isOk() && lockHeld.length > 0 ? Result.ok({
1483
+ ...prepared.value,
1484
+ lockHeld
1485
+ }) : prepared;
1486
+ }
1487
+ /**
1488
+ * Accept or reject one pending suggestion. Rejecting it rejects its
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.
1493
+ */
1494
+ prepareSuggestion(state, { suggestionId, resolution, author, date }) {
1495
+ const infos = suggestionRevisionInfos(this.currentDocument, OP_STORIES.MAIN, suggestionId);
1496
+ const commentIds = suggestedCommentIds(this.currentDocument, suggestionId);
1497
+ if (infos.length === 0 && commentIds.length === 0) return noChange(`No pending suggestion ${suggestionId}.`);
1498
+ if (resolution === "reject") return this.prepareResolve(state, {
1499
+ revisionIds: infos.map(({ id }) => id),
1500
+ resolution: "reject",
1501
+ before: commentIds.map((id) => ({
1502
+ type: DOCUMENT_OP_TYPES.DELETE_COMMENT,
1503
+ id,
1504
+ scope: "thread"
1505
+ }))
1506
+ });
1507
+ const checked = this.checkState(state);
1508
+ if (checked.isErr()) return checked;
1509
+ const selection = this.projection.selectionAt(state);
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
+ });
1528
+ return this.prepareJournalledOps({
1529
+ state,
1530
+ ops,
1531
+ postSelection: selection.value
1532
+ });
1016
1533
  }
1017
1534
  projectStory(story) {
1018
1535
  if (story === OP_STORIES.MAIN) return Result.ok(this.projection);
@@ -1028,7 +1545,9 @@ var CanonicalSession = class {
1028
1545
  const projected = project({
1029
1546
  document: this.currentDocument,
1030
1547
  styles: this.styles,
1031
- story
1548
+ caches: this.caches,
1549
+ story,
1550
+ ...cached === void 0 ? {} : { previous: cached.projection }
1032
1551
  });
1033
1552
  if (projected.isOk()) this.storyProjections.set(key, {
1034
1553
  content: body.content,
@@ -1186,12 +1705,14 @@ var CanonicalSession = class {
1186
1705
  const applied = stagedApplied === void 0 ? applyDocumentOps(this.currentDocument, ops) : Result.ok(stagedApplied);
1187
1706
  if (applied.isErr()) return refuse(applied.error.message);
1188
1707
  if (applied.value.inverse.length === 0) return noChange("The intent makes no document change.");
1708
+ const locked = lockViolationBetween(this.currentDocument, applied.value.document);
1709
+ if (locked !== null) return lockRefusal(locked);
1189
1710
  if (propertySourceDocument !== void 0) preservePropertySources({
1190
1711
  target: applied.value.document,
1191
1712
  source: propertySourceDocument,
1192
1713
  indentation: "restore"
1193
1714
  });
1194
- const normalized = normalizeCanonicalListRendering(applied.value.document);
1715
+ const normalized = normalizeCanonicalListRendering(applied.value.document, this.caches.lists);
1195
1716
  applied.value.document = normalized.document;
1196
1717
  applied.value.inverse = normalized.inverse.concat(applied.value.inverse);
1197
1718
  const changed = changedStories({
@@ -1199,7 +1720,7 @@ var CanonicalSession = class {
1199
1720
  previous: this.currentDocument
1200
1721
  });
1201
1722
  if (unsupportedSeedReason(applied.value.document, changed) !== null) return Result.err(new CanonicalSessionError({
1202
- gap: CANONICAL_GAP.storyContentProjection,
1723
+ ground: { gap: CANONICAL_GAP.storyContentProjection },
1203
1724
  reason: "refused",
1204
1725
  message: "The operations produce unsupported canonical story content."
1205
1726
  }));
@@ -1222,14 +1743,18 @@ var CanonicalSession = class {
1222
1743
  const projected = project({
1223
1744
  document: applied.value.document,
1224
1745
  styles: this.styles,
1225
- story: projectedStory
1746
+ caches: this.caches,
1747
+ story: projectedStory,
1748
+ previous: sameStory(projectedStory, OP_STORIES.MAIN) ? this.currentProjection : previous.value
1226
1749
  });
1227
1750
  if (projected.isErr()) return projected;
1228
1751
  const bodyProjection = (() => {
1229
1752
  if (sameStory(projectedStory, OP_STORIES.MAIN)) return projected;
1230
1753
  if (ops.some(operationChangesBodyProjection)) return project({
1231
1754
  document: applied.value.document,
1232
- styles: this.styles
1755
+ styles: this.styles,
1756
+ caches: this.caches,
1757
+ previous: this.currentProjection
1233
1758
  });
1234
1759
  return Result.ok(this.currentProjection);
1235
1760
  })();
@@ -1257,6 +1782,7 @@ var CanonicalSession = class {
1257
1782
  transaction.replaceWith(from, to, Fragment.fromArray(replacement));
1258
1783
  }
1259
1784
  if (!transaction.doc.eq(projected.value.doc)) transaction.replaceWith(0, transaction.doc.content.size, projected.value.doc.content);
1785
+ for (const [name, value] of Object.entries(projected.value.doc.attrs)) if (transaction.doc.attrs[name] !== value) transaction.setDocAttribute(name, value);
1260
1786
  if (sameStory(selection.anchor.story, projectedStory) && sameStory(selection.head.story, projectedStory)) {
1261
1787
  if (!restoreCanonicalSelection({
1262
1788
  transaction,
@@ -1268,6 +1794,8 @@ var CanonicalSession = class {
1268
1794
  }
1269
1795
  })) return refuse("Canonical history cannot restore the selected inline atom.");
1270
1796
  }
1797
+ const held = projected.value.heldAs(transaction.doc);
1798
+ const heldBody = bodyProjection.value === projected.value ? held : bodyProjection.value;
1271
1799
  transaction.setMeta(CANONICAL_PROJECTION_META, {
1272
1800
  type: "canonical",
1273
1801
  origin,
@@ -1285,8 +1813,8 @@ var CanonicalSession = class {
1285
1813
  return Result.ok({
1286
1814
  transaction,
1287
1815
  document: applied.value.document,
1288
- projection: projected.value,
1289
- bodyProjection: bodyProjection.value,
1816
+ projection: held,
1817
+ bodyProjection: heldBody,
1290
1818
  selection,
1291
1819
  touched: applied.value.touched,
1292
1820
  version: baseVersion + 1,
@@ -1308,12 +1836,12 @@ var CanonicalSession = class {
1308
1836
  this.storyProjections.set(storyProjectionKey(projectedStory), {
1309
1837
  content: body.content,
1310
1838
  theme: applied.value.document.package.theme,
1311
- projection: projected.value
1839
+ projection: held
1312
1840
  });
1313
1841
  }
1314
1842
  this.currentSelection = selection;
1315
1843
  this.currentDocument = applied.value.document;
1316
- this.currentProjection = bodyProjection.value;
1844
+ this.currentProjection = heldBody;
1317
1845
  for (const ids of [
1318
1846
  applied.value.touched.modified,
1319
1847
  applied.value.touched.inserted,
@@ -1329,30 +1857,35 @@ var CanonicalSession = class {
1329
1857
  }
1330
1858
  };
1331
1859
  const createCanonicalSession = (document, styles) => {
1332
- const unsupported = unsupportedSeedReason(document);
1333
- if (unsupported !== null) return refuse(unsupported);
1334
1860
  const owned = cloneDocumentWithParagraphPropertySources(document);
1335
- 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);
1336
1865
  preservePropertySources({
1337
1866
  target: identified,
1338
1867
  source: owned
1339
1868
  });
1340
1869
  const validated = validateOpsDocument(identified);
1341
1870
  if (validated.isErr()) return refuse(validated.error.message);
1342
- const normalized = normalizeCanonicalListRendering(identified).document;
1871
+ const caches = newStoryProjectionCaches();
1872
+ const normalized = normalizeCanonicalListRendering(identified, caches.lists).document;
1343
1873
  preservePropertySources({
1344
1874
  target: normalized,
1345
1875
  source: owned
1346
1876
  });
1347
1877
  const projected = project({
1348
1878
  document: normalized,
1349
- styles
1879
+ styles,
1880
+ caches
1350
1881
  });
1351
1882
  if (projected.isErr()) return projected;
1352
1883
  return Result.ok(new CanonicalSession({
1353
1884
  document: normalized,
1354
1885
  projection: projected.value,
1355
- styles
1886
+ styles,
1887
+ sourceRestores: canonicalSourceRestores(normalized, source.normalized),
1888
+ caches
1356
1889
  }));
1357
1890
  };
1358
1891
  const hasDeletedParagraphMark = (node) => {
@@ -1382,7 +1915,7 @@ const visibleDeletionContext = (state) => {
1382
1915
  const native = canonicalNativeCells(paragraph);
1383
1916
  if (native.isErr()) {
1384
1917
  issue = new CanonicalSessionError({
1385
- gap: CANONICAL_GAP.dispatch,
1918
+ ground: { gap: CANONICAL_GAP.dispatch },
1386
1919
  reason: "refused",
1387
1920
  message: native.error.message
1388
1921
  });
@@ -1395,7 +1928,7 @@ const visibleDeletionContext = (state) => {
1395
1928
  const to = containerStart + paragraphOffset + 1 + cell.to;
1396
1929
  if (cell.type !== "text" && selection.from > from && selection.from < to) {
1397
1930
  issue = new CanonicalSessionError({
1398
- gap: CANONICAL_GAP.dispatch,
1931
+ ground: { gap: CANONICAL_GAP.dispatch },
1399
1932
  reason: "refused",
1400
1933
  message: "Character deletion cannot start inside an inline atom."
1401
1934
  });
@@ -1460,4 +1993,4 @@ const deletionRange = (state, direction) => {
1460
1993
  to
1461
1994
  });
1462
1995
  };
1463
- export { CANONICAL_PROJECTION_META, CanonicalSessionError, createCanonicalSession, deletionRange, isCanonicalJoinBoundary, isCanonicalProjectionTransaction, publishCanonicalProjection };
1996
+ export { CANONICAL_PROJECTION_META, CanonicalSessionError, createCanonicalSession, deletionRange, isCanonicalJoinBoundary, isCanonicalProjectionTransaction, newStoryProjectionCaches, project as projectCanonicalStory, publishCanonicalProjection };