@beyondwork/docx-react-component 1.0.29 → 1.0.30

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 (381) hide show
  1. package/package.json +65 -96
  2. package/src/README.md +85 -0
  3. package/src/api/README.md +26 -0
  4. package/src/api/public-types.ts +1952 -0
  5. package/src/api/session-state.ts +62 -0
  6. package/src/compare/diff-engine.ts +623 -0
  7. package/src/compare/export-redlines.ts +280 -0
  8. package/src/compare/index.ts +25 -0
  9. package/src/compare/snapshot.ts +97 -0
  10. package/src/component-inventory.md +99 -0
  11. package/src/core/README.md +10 -0
  12. package/src/core/commands/README.md +3 -0
  13. package/{dist/chunk-TJBP2K4T.js → src/core/commands/formatting-commands.ts} +536 -196
  14. package/src/core/commands/image-commands.ts +373 -0
  15. package/src/core/commands/index.ts +1879 -0
  16. package/src/core/commands/list-commands.ts +565 -0
  17. package/src/core/commands/paragraph-layout-commands.ts +339 -0
  18. package/src/core/commands/review-commands.ts +108 -0
  19. package/{dist/core/commands/section-layout-commands.cjs → src/core/commands/section-layout-commands.ts} +340 -137
  20. package/src/core/commands/structural-helpers.ts +309 -0
  21. package/{dist/core/commands/style-commands.cjs → src/core/commands/style-commands.ts} +113 -65
  22. package/src/core/commands/table-structure-commands.ts +854 -0
  23. package/{dist/chunk-UZXBISGO.js → src/core/commands/text-commands.ts} +142 -86
  24. package/src/core/schema/README.md +3 -0
  25. package/src/core/schema/text-schema.ts +516 -0
  26. package/src/core/search/search-text.ts +357 -0
  27. package/src/core/selection/README.md +3 -0
  28. package/src/core/selection/mapping.ts +289 -0
  29. package/src/core/selection/review-anchors.ts +183 -0
  30. package/src/core/state/README.md +3 -0
  31. package/src/core/state/editor-state.ts +892 -0
  32. package/src/core/state/text-transaction.ts +869 -0
  33. package/src/formats/xlsx/io/parse-shared-strings.ts +41 -0
  34. package/src/formats/xlsx/io/parse-sheet.ts +459 -0
  35. package/src/formats/xlsx/io/parse-styles.ts +59 -0
  36. package/src/formats/xlsx/io/parse-workbook.ts +75 -0
  37. package/src/formats/xlsx/io/serialize-shared-strings.ts +72 -0
  38. package/src/formats/xlsx/io/serialize-sheet.ts +333 -0
  39. package/src/formats/xlsx/io/serialize-styles.ts +98 -0
  40. package/src/formats/xlsx/io/serialize-workbook.ts +429 -0
  41. package/src/formats/xlsx/io/xlsx-session.ts +314 -0
  42. package/src/formats/xlsx/model/cell.ts +189 -0
  43. package/src/formats/xlsx/model/sheet.ts +326 -0
  44. package/src/formats/xlsx/model/styles.ts +118 -0
  45. package/src/formats/xlsx/model/workbook.ts +453 -0
  46. package/src/formats/xlsx/runtime/cell-commands.ts +567 -0
  47. package/src/formats/xlsx/runtime/sheet-commands.ts +206 -0
  48. package/src/formats/xlsx/runtime/workbook-runtime.ts +177 -0
  49. package/src/formats/xlsx/runtime/workbook-transaction.ts +822 -0
  50. package/src/index.ts +142 -0
  51. package/src/io/README.md +10 -0
  52. package/src/io/docx-session.ts +3175 -0
  53. package/src/io/export/README.md +3 -0
  54. package/src/io/export/export-session.ts +220 -0
  55. package/src/io/export/minimal-docx.ts +115 -0
  56. package/src/io/export/reattach-preserved-parts.ts +54 -0
  57. package/src/io/export/serialize-comments.ts +947 -0
  58. package/src/io/export/serialize-footnotes.ts +394 -0
  59. package/src/io/export/serialize-headers-footers.ts +368 -0
  60. package/src/io/export/serialize-main-document.ts +1342 -0
  61. package/src/io/export/serialize-numbering.ts +218 -0
  62. package/src/io/export/serialize-revisions.ts +389 -0
  63. package/src/io/export/serialize-runtime-revisions.ts +463 -0
  64. package/src/io/export/serialize-tables.ts +174 -0
  65. package/src/io/export/split-review-boundaries.ts +356 -0
  66. package/src/io/export/split-story-blocks-for-runtime-revisions.ts +252 -0
  67. package/src/io/export/table-properties-xml.ts +318 -0
  68. package/src/io/normalize/README.md +3 -0
  69. package/src/io/normalize/normalize-text.ts +670 -0
  70. package/src/io/ooxml/README.md +3 -0
  71. package/src/io/ooxml/highlight-colors.ts +39 -0
  72. package/src/io/ooxml/numbering-sentinels.ts +44 -0
  73. package/src/io/ooxml/parse-comments.ts +852 -0
  74. package/src/io/ooxml/parse-complex-content.ts +287 -0
  75. package/src/io/ooxml/parse-fields.ts +834 -0
  76. package/src/io/ooxml/parse-footnotes.ts +952 -0
  77. package/src/io/ooxml/parse-headers-footers.ts +1212 -0
  78. package/src/io/ooxml/parse-inline-media.ts +461 -0
  79. package/src/io/ooxml/parse-main-document.ts +2947 -0
  80. package/src/io/ooxml/parse-numbering.ts +747 -0
  81. package/src/io/ooxml/parse-revisions.ts +1045 -0
  82. package/src/io/ooxml/parse-settings.ts +184 -0
  83. package/src/io/ooxml/parse-shapes.ts +296 -0
  84. package/src/io/ooxml/parse-styles.ts +639 -0
  85. package/src/io/ooxml/parse-tables.ts +627 -0
  86. package/src/io/ooxml/parse-theme.ts +346 -0
  87. package/src/io/ooxml/part-manifest.ts +136 -0
  88. package/src/io/ooxml/revision-boundaries.ts +475 -0
  89. package/src/io/ooxml/workflow-payload.ts +544 -0
  90. package/src/io/opc/README.md +3 -0
  91. package/src/io/opc/corrupt-package.ts +166 -0
  92. package/src/io/opc/docx-package.ts +74 -0
  93. package/src/io/opc/package-reader.ts +325 -0
  94. package/src/io/opc/package-writer.ts +273 -0
  95. package/src/io/source-package-provenance.ts +241 -0
  96. package/{dist/chunk-RMH72RZI.js → src/legal/bookmarks.ts} +130 -44
  97. package/src/legal/cross-references.ts +414 -0
  98. package/src/legal/defined-terms.ts +203 -0
  99. package/src/legal/index.ts +32 -0
  100. package/src/legal/signature-blocks.ts +259 -0
  101. package/src/model/README.md +3 -0
  102. package/src/model/canonical-document.ts +2722 -0
  103. package/src/model/cds-1.0.0.ts +212 -0
  104. package/src/model/snapshot.ts +760 -0
  105. package/src/preservation/README.md +3 -0
  106. package/src/preservation/markup-compatibility.ts +48 -0
  107. package/src/preservation/opaque-fragment-store.ts +89 -0
  108. package/src/preservation/opaque-region.ts +233 -0
  109. package/src/preservation/package-preservation.ts +113 -0
  110. package/src/preservation/preserved-part-manifest.ts +56 -0
  111. package/src/preservation/relationship-retention.ts +57 -0
  112. package/src/preservation/store.ts +255 -0
  113. package/src/review/README.md +16 -0
  114. package/src/review/store/README.md +3 -0
  115. package/src/review/store/comment-anchors.ts +70 -0
  116. package/src/review/store/comment-remapping.ts +154 -0
  117. package/src/review/store/comment-store.ts +349 -0
  118. package/src/review/store/comment-thread.ts +109 -0
  119. package/src/review/store/revision-actions.ts +423 -0
  120. package/src/review/store/revision-store.ts +323 -0
  121. package/src/review/store/revision-types.ts +182 -0
  122. package/src/review/store/runtime-comment-store.ts +43 -0
  123. package/src/runtime/README.md +3 -0
  124. package/src/runtime/ai-action-policy.ts +764 -0
  125. package/src/runtime/context-analytics.ts +824 -0
  126. package/src/runtime/document-layout.ts +332 -0
  127. package/src/runtime/document-locations.ts +521 -0
  128. package/src/runtime/document-navigation.ts +616 -0
  129. package/src/runtime/document-outline.ts +440 -0
  130. package/src/runtime/document-runtime.ts +4055 -0
  131. package/src/runtime/document-search.ts +145 -0
  132. package/src/runtime/event-refresh-hints.ts +137 -0
  133. package/src/runtime/numbering-prefix.ts +244 -0
  134. package/src/runtime/page-layout-estimation.ts +305 -0
  135. package/src/runtime/read-only-diagnostics-runtime.ts +241 -0
  136. package/src/runtime/resolved-numbering-geometry.ts +293 -0
  137. package/src/runtime/review-runtime.ts +44 -0
  138. package/src/runtime/revision-runtime.ts +107 -0
  139. package/src/runtime/session-capabilities.ts +192 -0
  140. package/src/runtime/story-context.ts +164 -0
  141. package/src/runtime/story-targeting.ts +162 -0
  142. package/src/runtime/suggestions-snapshot.ts +137 -0
  143. package/src/runtime/surface-projection.ts +1553 -0
  144. package/src/runtime/table-commands.ts +173 -0
  145. package/src/runtime/table-schema.ts +309 -0
  146. package/src/runtime/table-style-resolver.ts +409 -0
  147. package/src/runtime/view-state.ts +493 -0
  148. package/src/runtime/virtualized-rendering.ts +258 -0
  149. package/src/runtime/workflow-markup.ts +393 -0
  150. package/src/ui/README.md +30 -0
  151. package/src/ui/WordReviewEditor.tsx +5268 -0
  152. package/src/ui/browser-export.ts +52 -0
  153. package/src/ui/comments/README.md +3 -0
  154. package/src/ui/compatibility/README.md +3 -0
  155. package/src/ui/editor-command-bag.ts +127 -0
  156. package/src/ui/editor-runtime-boundary.ts +1558 -0
  157. package/src/ui/editor-shell-view.tsx +144 -0
  158. package/src/ui/editor-surface/README.md +3 -0
  159. package/src/ui/editor-surface-controller.tsx +66 -0
  160. package/src/ui/headless/comment-decoration-model.ts +124 -0
  161. package/src/ui/headless/preserve-editor-selection.ts +5 -0
  162. package/src/ui/headless/revision-decoration-model.ts +128 -0
  163. package/src/ui/headless/selection-helpers.ts +54 -0
  164. package/src/ui/headless/selection-tool-context.ts +19 -0
  165. package/src/ui/headless/selection-tool-resolver.ts +752 -0
  166. package/src/ui/headless/selection-tool-types.ts +129 -0
  167. package/src/ui/headless/selection-toolbar-model.ts +11 -0
  168. package/src/ui/headless/use-editor-keyboard.ts +103 -0
  169. package/src/ui/review/README.md +3 -0
  170. package/src/ui/runtime-shortcut-dispatch.ts +365 -0
  171. package/src/ui/runtime-snapshot-selectors.ts +197 -0
  172. package/src/ui/shared/revision-filters.ts +31 -0
  173. package/src/ui/status/README.md +3 -0
  174. package/src/ui/theme/README.md +3 -0
  175. package/src/ui/toolbar/README.md +3 -0
  176. package/src/ui/workflow-surface-blocked-rails.ts +94 -0
  177. package/src/ui-tailwind/chrome/chrome-preset-model.ts +107 -0
  178. package/src/ui-tailwind/chrome/chrome-preset-toolbar.tsx +15 -0
  179. package/src/ui-tailwind/chrome/review-queue-bar.tsx +97 -0
  180. package/src/ui-tailwind/chrome/tw-alert-banner.tsx +64 -0
  181. package/src/ui-tailwind/chrome/tw-context-analytics-summary.tsx +122 -0
  182. package/src/ui-tailwind/chrome/tw-image-context-toolbar.tsx +121 -0
  183. package/src/ui-tailwind/chrome/tw-layout-panel.tsx +114 -0
  184. package/src/ui-tailwind/chrome/tw-object-context-toolbar.tsx +30 -0
  185. package/src/ui-tailwind/chrome/tw-page-ruler.tsx +365 -0
  186. package/src/ui-tailwind/chrome/tw-selection-tool-blocked.tsx +23 -0
  187. package/src/ui-tailwind/chrome/tw-selection-tool-comment.tsx +35 -0
  188. package/src/ui-tailwind/chrome/tw-selection-tool-formatting.tsx +37 -0
  189. package/src/ui-tailwind/chrome/tw-selection-tool-host.tsx +298 -0
  190. package/src/ui-tailwind/chrome/tw-selection-tool-structure.tsx +116 -0
  191. package/src/ui-tailwind/chrome/tw-selection-tool-suggestion.tsx +29 -0
  192. package/src/ui-tailwind/chrome/tw-selection-tool-workflow.tsx +27 -0
  193. package/src/ui-tailwind/chrome/tw-selection-toolbar.tsx +186 -0
  194. package/src/ui-tailwind/chrome/tw-suggestion-card.tsx +139 -0
  195. package/src/ui-tailwind/chrome/tw-table-context-toolbar.tsx +200 -0
  196. package/src/ui-tailwind/chrome/tw-unsaved-modal.tsx +58 -0
  197. package/src/ui-tailwind/chrome/use-before-unload.ts +20 -0
  198. package/src/ui-tailwind/editor-surface/perf-probe.ts +179 -0
  199. package/src/ui-tailwind/editor-surface/pm-command-bridge.ts +189 -0
  200. package/src/ui-tailwind/editor-surface/pm-contextual-ui.ts +31 -0
  201. package/src/ui-tailwind/editor-surface/pm-decorations.ts +411 -0
  202. package/src/ui-tailwind/editor-surface/pm-position-map.ts +123 -0
  203. package/src/ui-tailwind/editor-surface/pm-schema.ts +927 -0
  204. package/src/ui-tailwind/editor-surface/pm-state-from-snapshot.ts +567 -0
  205. package/src/ui-tailwind/editor-surface/search-plugin.ts +168 -0
  206. package/src/ui-tailwind/editor-surface/surface-build-keys.ts +65 -0
  207. package/src/ui-tailwind/editor-surface/tw-caret.tsx +12 -0
  208. package/src/ui-tailwind/editor-surface/tw-editor-surface.tsx +150 -0
  209. package/src/ui-tailwind/editor-surface/tw-inline-token.tsx +129 -0
  210. package/src/ui-tailwind/editor-surface/tw-opaque-block.tsx +58 -0
  211. package/src/ui-tailwind/editor-surface/tw-paragraph-block.tsx +151 -0
  212. package/src/ui-tailwind/editor-surface/tw-prosemirror-surface.tsx +1047 -0
  213. package/src/ui-tailwind/editor-surface/tw-segment-view.tsx +111 -0
  214. package/src/ui-tailwind/editor-surface/tw-table-node-view.tsx +503 -0
  215. package/src/ui-tailwind/index.ts +62 -0
  216. package/src/ui-tailwind/page-chrome-model.ts +27 -0
  217. package/src/ui-tailwind/review/tw-comment-sidebar.tsx +406 -0
  218. package/src/ui-tailwind/review/tw-health-panel.tsx +149 -0
  219. package/src/ui-tailwind/review/tw-review-rail.tsx +122 -0
  220. package/src/ui-tailwind/review/tw-revision-sidebar.tsx +164 -0
  221. package/src/ui-tailwind/status/tw-status-bar.tsx +65 -0
  222. package/{dist → src}/ui-tailwind/theme/editor-theme.css +58 -40
  223. package/src/ui-tailwind/toolbar/tw-toolbar-icon-button.tsx +52 -0
  224. package/src/ui-tailwind/toolbar/tw-toolbar.tsx +1133 -0
  225. package/src/ui-tailwind/tw-review-workspace.tsx +1460 -0
  226. package/src/validation/README.md +3 -0
  227. package/src/validation/compatibility-engine.ts +878 -0
  228. package/src/validation/compatibility-report.ts +161 -0
  229. package/src/validation/diagnostics.ts +204 -0
  230. package/src/validation/docx-comment-proof.ts +720 -0
  231. package/src/validation/import-diagnostics.ts +128 -0
  232. package/src/validation/low-priority-word-surfaces.ts +373 -0
  233. package/dist/canonical-document-BLEbzL2J.d.cts +0 -844
  234. package/dist/canonical-document-BLEbzL2J.d.ts +0 -844
  235. package/dist/chunk-2FJS5GZM.js +0 -763
  236. package/dist/chunk-2FJS5GZM.js.map +0 -1
  237. package/dist/chunk-2OQBZS3F.js +0 -446
  238. package/dist/chunk-2OQBZS3F.js.map +0 -1
  239. package/dist/chunk-2S7W4KFO.js +0 -127
  240. package/dist/chunk-2S7W4KFO.js.map +0 -1
  241. package/dist/chunk-2TG72QSW.js +0 -3874
  242. package/dist/chunk-2TG72QSW.js.map +0 -1
  243. package/dist/chunk-36QNIZBO.js +0 -532
  244. package/dist/chunk-36QNIZBO.js.map +0 -1
  245. package/dist/chunk-4AQOYAW4.js +0 -3069
  246. package/dist/chunk-4AQOYAW4.js.map +0 -1
  247. package/dist/chunk-4D5EWJ3P.js +0 -77
  248. package/dist/chunk-4D5EWJ3P.js.map +0 -1
  249. package/dist/chunk-5FN54NDH.js +0 -2257
  250. package/dist/chunk-5FN54NDH.js.map +0 -1
  251. package/dist/chunk-BOYGQYRQ.js +0 -7306
  252. package/dist/chunk-BOYGQYRQ.js.map +0 -1
  253. package/dist/chunk-CN3XMECL.js +0 -212
  254. package/dist/chunk-CN3XMECL.js.map +0 -1
  255. package/dist/chunk-EBI3BX6U.js +0 -164
  256. package/dist/chunk-EBI3BX6U.js.map +0 -1
  257. package/dist/chunk-EILUG3VB.js +0 -1275
  258. package/dist/chunk-EILUG3VB.js.map +0 -1
  259. package/dist/chunk-FUDY333O.js +0 -70
  260. package/dist/chunk-FUDY333O.js.map +0 -1
  261. package/dist/chunk-GBVOWFIK.js +0 -1237
  262. package/dist/chunk-GBVOWFIK.js.map +0 -1
  263. package/dist/chunk-H4TQ3H3Y.js +0 -262
  264. package/dist/chunk-H4TQ3H3Y.js.map +0 -1
  265. package/dist/chunk-JGB3IXZO.js +0 -189
  266. package/dist/chunk-JGB3IXZO.js.map +0 -1
  267. package/dist/chunk-KD2QRQPY.js +0 -4342
  268. package/dist/chunk-KD2QRQPY.js.map +0 -1
  269. package/dist/chunk-KLMXQVYK.js +0 -369
  270. package/dist/chunk-KLMXQVYK.js.map +0 -1
  271. package/dist/chunk-KZUG5KFQ.js +0 -214
  272. package/dist/chunk-KZUG5KFQ.js.map +0 -1
  273. package/dist/chunk-QDAQ4CJU.js +0 -345
  274. package/dist/chunk-QDAQ4CJU.js.map +0 -1
  275. package/dist/chunk-RMH72RZI.js.map +0 -1
  276. package/dist/chunk-SWKWQZXM.js +0 -117
  277. package/dist/chunk-SWKWQZXM.js.map +0 -1
  278. package/dist/chunk-TJBP2K4T.js.map +0 -1
  279. package/dist/chunk-TLCEAQDQ.js +0 -542
  280. package/dist/chunk-TLCEAQDQ.js.map +0 -1
  281. package/dist/chunk-UZXBISGO.js.map +0 -1
  282. package/dist/chunk-WGBAKP3Q.js +0 -3220
  283. package/dist/chunk-WGBAKP3Q.js.map +0 -1
  284. package/dist/compare/index.cjs +0 -5475
  285. package/dist/compare/index.cjs.map +0 -1
  286. package/dist/compare/index.d.cts +0 -114
  287. package/dist/compare/index.d.ts +0 -114
  288. package/dist/compare/index.js +0 -731
  289. package/dist/compare/index.js.map +0 -1
  290. package/dist/core/commands/formatting-commands.cjs +0 -828
  291. package/dist/core/commands/formatting-commands.cjs.map +0 -1
  292. package/dist/core/commands/formatting-commands.d.cts +0 -63
  293. package/dist/core/commands/formatting-commands.d.ts +0 -63
  294. package/dist/core/commands/formatting-commands.js +0 -37
  295. package/dist/core/commands/formatting-commands.js.map +0 -1
  296. package/dist/core/commands/image-commands.cjs +0 -2023
  297. package/dist/core/commands/image-commands.cjs.map +0 -1
  298. package/dist/core/commands/image-commands.d.cts +0 -58
  299. package/dist/core/commands/image-commands.d.ts +0 -58
  300. package/dist/core/commands/image-commands.js +0 -18
  301. package/dist/core/commands/image-commands.js.map +0 -1
  302. package/dist/core/commands/section-layout-commands.cjs.map +0 -1
  303. package/dist/core/commands/section-layout-commands.d.cts +0 -62
  304. package/dist/core/commands/section-layout-commands.d.ts +0 -62
  305. package/dist/core/commands/section-layout-commands.js +0 -21
  306. package/dist/core/commands/section-layout-commands.js.map +0 -1
  307. package/dist/core/commands/style-commands.cjs.map +0 -1
  308. package/dist/core/commands/style-commands.d.cts +0 -13
  309. package/dist/core/commands/style-commands.d.ts +0 -13
  310. package/dist/core/commands/style-commands.js +0 -9
  311. package/dist/core/commands/style-commands.js.map +0 -1
  312. package/dist/core/commands/table-structure-commands.cjs +0 -1883
  313. package/dist/core/commands/table-structure-commands.cjs.map +0 -1
  314. package/dist/core/commands/table-structure-commands.d.cts +0 -59
  315. package/dist/core/commands/table-structure-commands.d.ts +0 -59
  316. package/dist/core/commands/table-structure-commands.js +0 -12
  317. package/dist/core/commands/table-structure-commands.js.map +0 -1
  318. package/dist/core/commands/text-commands.cjs +0 -2391
  319. package/dist/core/commands/text-commands.cjs.map +0 -1
  320. package/dist/core/commands/text-commands.d.cts +0 -24
  321. package/dist/core/commands/text-commands.d.ts +0 -24
  322. package/dist/core/commands/text-commands.js +0 -28
  323. package/dist/core/commands/text-commands.js.map +0 -1
  324. package/dist/core/selection/mapping.cjs +0 -200
  325. package/dist/core/selection/mapping.cjs.map +0 -1
  326. package/dist/core/selection/mapping.d.cts +0 -2
  327. package/dist/core/selection/mapping.d.ts +0 -2
  328. package/dist/core/selection/mapping.js +0 -31
  329. package/dist/core/selection/mapping.js.map +0 -1
  330. package/dist/core/state/editor-state.cjs +0 -2278
  331. package/dist/core/state/editor-state.cjs.map +0 -1
  332. package/dist/core/state/editor-state.d.cts +0 -2
  333. package/dist/core/state/editor-state.d.ts +0 -2
  334. package/dist/core/state/editor-state.js +0 -26
  335. package/dist/core/state/editor-state.js.map +0 -1
  336. package/dist/index.cjs +0 -38553
  337. package/dist/index.cjs.map +0 -1
  338. package/dist/index.d.cts +0 -15
  339. package/dist/index.d.ts +0 -15
  340. package/dist/index.js +0 -7856
  341. package/dist/index.js.map +0 -1
  342. package/dist/io/docx-session.cjs +0 -16236
  343. package/dist/io/docx-session.cjs.map +0 -1
  344. package/dist/io/docx-session.d.cts +0 -21
  345. package/dist/io/docx-session.d.ts +0 -21
  346. package/dist/io/docx-session.js +0 -18
  347. package/dist/io/docx-session.js.map +0 -1
  348. package/dist/legal/index.cjs +0 -3900
  349. package/dist/legal/index.cjs.map +0 -1
  350. package/dist/legal/index.d.cts +0 -86
  351. package/dist/legal/index.d.ts +0 -86
  352. package/dist/legal/index.js +0 -616
  353. package/dist/legal/index.js.map +0 -1
  354. package/dist/public-types-7ZL_94cz.d.ts +0 -1573
  355. package/dist/public-types-CeMaDueh.d.cts +0 -1573
  356. package/dist/public-types.cjs +0 -19
  357. package/dist/public-types.cjs.map +0 -1
  358. package/dist/public-types.d.cts +0 -2
  359. package/dist/public-types.d.ts +0 -2
  360. package/dist/public-types.js +0 -1
  361. package/dist/public-types.js.map +0 -1
  362. package/dist/runtime/document-runtime.cjs +0 -11140
  363. package/dist/runtime/document-runtime.cjs.map +0 -1
  364. package/dist/runtime/document-runtime.d.cts +0 -231
  365. package/dist/runtime/document-runtime.d.ts +0 -231
  366. package/dist/runtime/document-runtime.js +0 -21
  367. package/dist/runtime/document-runtime.js.map +0 -1
  368. package/dist/structural-helpers-CilgOVhh.d.cts +0 -10
  369. package/dist/structural-helpers-q0Gd-eBN.d.ts +0 -10
  370. package/dist/ui-tailwind/editor-surface/search-plugin.cjs +0 -313
  371. package/dist/ui-tailwind/editor-surface/search-plugin.cjs.map +0 -1
  372. package/dist/ui-tailwind/editor-surface/search-plugin.d.cts +0 -67
  373. package/dist/ui-tailwind/editor-surface/search-plugin.d.ts +0 -67
  374. package/dist/ui-tailwind/editor-surface/search-plugin.js +0 -23
  375. package/dist/ui-tailwind/editor-surface/search-plugin.js.map +0 -1
  376. package/dist/ui-tailwind/index.cjs +0 -4833
  377. package/dist/ui-tailwind/index.cjs.map +0 -1
  378. package/dist/ui-tailwind/index.d.cts +0 -617
  379. package/dist/ui-tailwind/index.d.ts +0 -617
  380. package/dist/ui-tailwind/index.js +0 -575
  381. package/dist/ui-tailwind/index.js.map +0 -1
@@ -0,0 +1,1879 @@
1
+ import {
2
+ createSelectionSnapshot,
3
+ type CanonicalDocumentEnvelope,
4
+ type CommentThreadRecord,
5
+ type EditorState,
6
+ type EditorWarning,
7
+ normalizeCommentThreadRecord,
8
+ type SelectionSnapshot,
9
+ } from "../state/editor-state.ts";
10
+ import {
11
+ areAnchorsEqual,
12
+ createDetachedAnchor,
13
+ createEmptyMapping,
14
+ createNodeAnchor,
15
+ createRangeAnchor,
16
+ DEFAULT_BOUNDARY_ASSOC,
17
+ mapAnchor,
18
+ type BoundaryAssoc,
19
+ type EditorAnchorProjection,
20
+ type MappingStep,
21
+ type TransactionMapping,
22
+ } from "../selection/mapping.ts";
23
+ import {
24
+ createAcceptRevisionCommand,
25
+ createRejectRevisionCommand,
26
+ type ReviewCommand,
27
+ } from "./review-commands.ts";
28
+ import {
29
+ deleteSelectionOrBackward,
30
+ deleteSelectionOrForward,
31
+ insertHardBreak,
32
+ insertTab,
33
+ insertText,
34
+ splitParagraph,
35
+ } from "./text-commands.ts";
36
+ import type { RevisionRecord as CanonicalRevisionRecord } from "../../model/canonical-document.ts";
37
+ import { remapCommentThreads } from "../../review/store/comment-remapping.ts";
38
+ import { applyRevisionRuntimeCommand } from "../../runtime/revision-runtime.ts";
39
+ import type { RevisionStore } from "../../review/store/revision-store.ts";
40
+
41
+ export interface CommandOrigin {
42
+ source:
43
+ | "keyboard"
44
+ | "toolbar"
45
+ | "context_menu"
46
+ | "comment_panel"
47
+ | "review_panel"
48
+ | "api"
49
+ | "runtime";
50
+ timestamp: string;
51
+ }
52
+
53
+ export type EditorCommand =
54
+ | {
55
+ type: "selection.set";
56
+ selection: SelectionSnapshot;
57
+ origin?: CommandOrigin;
58
+ }
59
+ | {
60
+ type: "document.replace";
61
+ document: CanonicalDocumentEnvelope;
62
+ mapping?: TransactionMapping;
63
+ selection?: SelectionSnapshot;
64
+ protectionSelection?: SelectionSnapshot;
65
+ origin?: CommandOrigin;
66
+ }
67
+ | {
68
+ type: "text.insert";
69
+ text: string;
70
+ origin?: CommandOrigin;
71
+ }
72
+ | {
73
+ type: "text.delete-backward";
74
+ origin?: CommandOrigin;
75
+ }
76
+ | {
77
+ type: "text.delete-forward";
78
+ origin?: CommandOrigin;
79
+ }
80
+ | {
81
+ type: "text.insert-tab";
82
+ origin?: CommandOrigin;
83
+ }
84
+ | {
85
+ type: "text.insert-hard-break";
86
+ origin?: CommandOrigin;
87
+ }
88
+ | {
89
+ type: "paragraph.split";
90
+ origin?: CommandOrigin;
91
+ }
92
+ | {
93
+ type: "runtime.set-read-only";
94
+ readOnly: boolean;
95
+ origin?: CommandOrigin;
96
+ }
97
+ | {
98
+ type: "runtime.focus";
99
+ focused: boolean;
100
+ origin?: CommandOrigin;
101
+ }
102
+ | {
103
+ type: "warning.add";
104
+ warning: EditorWarning;
105
+ origin?: CommandOrigin;
106
+ }
107
+ | {
108
+ type: "warning.clear";
109
+ warningId: string;
110
+ origin?: CommandOrigin;
111
+ }
112
+ | {
113
+ type: "comment.add";
114
+ comment: CommentThreadRecord;
115
+ selection?: SelectionSnapshot;
116
+ origin?: CommandOrigin;
117
+ }
118
+ | {
119
+ type: "comment.open";
120
+ commentId: string;
121
+ origin?: CommandOrigin;
122
+ }
123
+ | {
124
+ type: "comment.resolve";
125
+ commentId: string;
126
+ resolvedBy?: string;
127
+ origin?: CommandOrigin;
128
+ }
129
+ | {
130
+ type: "comment.reopen";
131
+ commentId: string;
132
+ origin?: CommandOrigin;
133
+ }
134
+ | {
135
+ type: "comment.add-reply";
136
+ commentId: string;
137
+ body: string;
138
+ authorId?: string;
139
+ origin?: CommandOrigin;
140
+ }
141
+ | {
142
+ type: "comment.edit-body";
143
+ commentId: string;
144
+ body: string;
145
+ origin?: CommandOrigin;
146
+ }
147
+ | {
148
+ type: "change.accept";
149
+ changeId: string;
150
+ origin?: CommandOrigin;
151
+ }
152
+ | {
153
+ type: "change.reject";
154
+ changeId: string;
155
+ origin?: CommandOrigin;
156
+ }
157
+ | {
158
+ type: "change.accept-all";
159
+ origin?: CommandOrigin;
160
+ }
161
+ | {
162
+ type: "change.reject-all";
163
+ origin?: CommandOrigin;
164
+ }
165
+ | {
166
+ type: "history.undo";
167
+ origin?: CommandOrigin;
168
+ }
169
+ | {
170
+ type: "history.redo";
171
+ origin?: CommandOrigin;
172
+ };
173
+
174
+ export interface TransactionEffects {
175
+ warningsAdded: EditorWarning[];
176
+ warningsCleared: Array<{ warningId: string; code: EditorWarning["code"] }>;
177
+ commentAdded?: { commentId: string; anchor: EditorAnchorProjection };
178
+ commentResolved?: { commentId: string };
179
+ commentReopened?: { commentId: string };
180
+ commentReplyAdded?: { commentId: string };
181
+ commentBodyEdited?: { commentId: string };
182
+ changeAccepted?: { changeId: string };
183
+ changeRejected?: { changeId: string };
184
+ revisionAuthored?: { changeId: string; kind: "insertion" | "deletion" };
185
+ commandBlocked?: { code: string; message: string };
186
+ }
187
+
188
+ export interface EditorTransaction {
189
+ nextState: EditorState;
190
+ mapping: TransactionMapping;
191
+ effects: TransactionEffects;
192
+ historyBoundary: "push" | "skip";
193
+ markDirty: boolean;
194
+ }
195
+
196
+ export interface CommandExecutionContext {
197
+ timestamp: string;
198
+ documentMode?: "editing" | "suggesting" | "viewing";
199
+ defaultAuthorId?: string;
200
+ }
201
+
202
+ export function executeEditorCommand(
203
+ state: EditorState,
204
+ command: Exclude<EditorCommand, { type: "history.undo" } | { type: "history.redo" }>,
205
+ context: CommandExecutionContext,
206
+ ): EditorTransaction {
207
+ switch (command.type) {
208
+ case "selection.set":
209
+ return createTransaction(
210
+ {
211
+ ...state,
212
+ selection: normalizeSelection(command.selection),
213
+ },
214
+ {
215
+ historyBoundary: "skip",
216
+ markDirty: false,
217
+ },
218
+ );
219
+ case "document.replace": {
220
+ const mapping = command.mapping ?? createEmptyMapping();
221
+ const selection =
222
+ command.selection ?? remapSelection(state.selection, mapping);
223
+ const reviewState = remapReviewStateAfterContentChange(
224
+ state,
225
+ command.document,
226
+ mapping,
227
+ );
228
+
229
+ return createTransaction(
230
+ {
231
+ ...state,
232
+ document: reviewState.document,
233
+ selection,
234
+ warnings: reviewState.warnings,
235
+ runtime: {
236
+ ...state.runtime,
237
+ activeCommentId: reviewState.activeCommentId,
238
+ },
239
+ compatibility: {
240
+ ...state.compatibility,
241
+ generatedAt: context.timestamp,
242
+ warnings: reviewState.warnings,
243
+ featureEntries: state.compatibility.featureEntries.map((entry) =>
244
+ entry.affectedAnchor
245
+ ? {
246
+ ...entry,
247
+ affectedAnchor: mapAnchor(entry.affectedAnchor, mapping),
248
+ }
249
+ : entry,
250
+ ),
251
+ },
252
+ },
253
+ {
254
+ historyBoundary: "push",
255
+ markDirty: true,
256
+ mapping,
257
+ effects: reviewState.effects,
258
+ },
259
+ );
260
+ }
261
+ case "text.insert": {
262
+ const suggestingResult = context.documentMode === "suggesting"
263
+ ? applySuggestingInsert(state, command.text, context)
264
+ : undefined;
265
+ if (suggestingResult) return suggestingResult;
266
+ return applyTextCommand(state, context.timestamp, (document, selection) =>
267
+ insertText(document, selection, command.text, context),
268
+ );
269
+ }
270
+ case "text.delete-backward": {
271
+ const suggestingResult = context.documentMode === "suggesting"
272
+ ? applySuggestingDelete(state, "backward", context)
273
+ : undefined;
274
+ if (suggestingResult) return suggestingResult;
275
+ return applyTextCommand(state, context.timestamp, (document, selection) =>
276
+ deleteSelectionOrBackward(document, selection, context),
277
+ );
278
+ }
279
+ case "text.delete-forward": {
280
+ const suggestingResult = context.documentMode === "suggesting"
281
+ ? applySuggestingDelete(state, "forward", context)
282
+ : undefined;
283
+ if (suggestingResult) return suggestingResult;
284
+ return applyTextCommand(state, context.timestamp, (document, selection) =>
285
+ deleteSelectionOrForward(document, selection, context),
286
+ );
287
+ }
288
+ case "text.insert-tab": {
289
+ const suggestingResult = context.documentMode === "suggesting"
290
+ ? applySuggestingInsertUnit(state, "tab", context)
291
+ : undefined;
292
+ if (suggestingResult) return suggestingResult;
293
+ return applyTextCommand(state, context.timestamp, (document, selection) =>
294
+ insertTab(document, selection, context),
295
+ );
296
+ }
297
+ case "text.insert-hard-break": {
298
+ const suggestingResult = context.documentMode === "suggesting"
299
+ ? applySuggestingInsertUnit(state, "hard_break", context)
300
+ : undefined;
301
+ if (suggestingResult) return suggestingResult;
302
+ return applyTextCommand(state, context.timestamp, (document, selection) =>
303
+ insertHardBreak(document, selection, context),
304
+ );
305
+ }
306
+ case "paragraph.split":
307
+ if (context.documentMode === "suggesting") {
308
+ const suggestingResult = applySuggestingParagraphSplit(state, context);
309
+ if (suggestingResult) return suggestingResult;
310
+ }
311
+ return applyTextCommand(state, context.timestamp, (document, selection) =>
312
+ splitParagraph(document, selection, context),
313
+ );
314
+ case "runtime.set-read-only":
315
+ return createTransaction(
316
+ {
317
+ ...state,
318
+ readOnly: command.readOnly,
319
+ },
320
+ {
321
+ historyBoundary: "skip",
322
+ markDirty: false,
323
+ },
324
+ );
325
+ case "runtime.focus":
326
+ return createTransaction(
327
+ {
328
+ ...state,
329
+ runtime: {
330
+ ...state.runtime,
331
+ hasFocus: command.focused,
332
+ },
333
+ },
334
+ {
335
+ historyBoundary: "skip",
336
+ markDirty: false,
337
+ },
338
+ );
339
+ case "warning.add": {
340
+ if (state.warnings.some((warning) => warning.warningId === command.warning.warningId)) {
341
+ return createTransaction(state, {
342
+ historyBoundary: "skip",
343
+ markDirty: false,
344
+ });
345
+ }
346
+
347
+ const warnings = [...state.warnings, command.warning];
348
+ return createTransaction(
349
+ {
350
+ ...state,
351
+ warnings,
352
+ compatibility: {
353
+ ...state.compatibility,
354
+ generatedAt: context.timestamp,
355
+ warnings,
356
+ },
357
+ },
358
+ {
359
+ historyBoundary: "skip",
360
+ markDirty: false,
361
+ effects: {
362
+ warningsAdded: [command.warning],
363
+ },
364
+ },
365
+ );
366
+ }
367
+ case "warning.clear": {
368
+ const existing = state.warnings.find((warning) => warning.warningId === command.warningId);
369
+
370
+ if (!existing) {
371
+ return createTransaction(state, {
372
+ historyBoundary: "skip",
373
+ markDirty: false,
374
+ });
375
+ }
376
+
377
+ const warnings = state.warnings.filter((warning) => warning.warningId !== command.warningId);
378
+ return createTransaction(
379
+ {
380
+ ...state,
381
+ warnings,
382
+ compatibility: {
383
+ ...state.compatibility,
384
+ generatedAt: context.timestamp,
385
+ warnings,
386
+ },
387
+ },
388
+ {
389
+ historyBoundary: "skip",
390
+ markDirty: false,
391
+ effects: {
392
+ warningsCleared: [
393
+ {
394
+ warningId: existing.warningId,
395
+ code: existing.code,
396
+ },
397
+ ],
398
+ },
399
+ },
400
+ );
401
+ }
402
+ case "comment.add": {
403
+ const comments = {
404
+ ...state.document.review.comments,
405
+ [command.comment.commentId]: normalizeCommentThreadRecord(command.comment),
406
+ };
407
+
408
+ return createTransaction(
409
+ {
410
+ ...state,
411
+ document: {
412
+ ...state.document,
413
+ updatedAt: context.timestamp,
414
+ review: {
415
+ ...state.document.review,
416
+ comments,
417
+ },
418
+ },
419
+ runtime: {
420
+ ...state.runtime,
421
+ activeCommentId: command.comment.commentId,
422
+ },
423
+ },
424
+ {
425
+ historyBoundary: "push",
426
+ markDirty: true,
427
+ effects: {
428
+ commentAdded: {
429
+ commentId: command.comment.commentId,
430
+ anchor: command.comment.anchor,
431
+ },
432
+ },
433
+ },
434
+ );
435
+ }
436
+ case "comment.open":
437
+ return createTransaction(
438
+ {
439
+ ...state,
440
+ runtime: {
441
+ ...state.runtime,
442
+ activeCommentId: command.commentId,
443
+ },
444
+ },
445
+ {
446
+ historyBoundary: "skip",
447
+ markDirty: false,
448
+ },
449
+ );
450
+ case "comment.resolve": {
451
+ const existing = state.document.review.comments[command.commentId];
452
+ if (!existing) {
453
+ return createTransaction(state, {
454
+ historyBoundary: "skip",
455
+ markDirty: false,
456
+ });
457
+ }
458
+
459
+ const comments = {
460
+ ...state.document.review.comments,
461
+ [command.commentId]: {
462
+ ...existing,
463
+ status: (existing.anchor.kind === "detached" ? "detached" : "resolved") as "detached" | "resolved",
464
+ resolution: {
465
+ resolvedAt: context.timestamp,
466
+ resolvedBy:
467
+ command.resolvedBy ??
468
+ existing.createdBy ??
469
+ existing.authorId ??
470
+ existing.entries?.[0]?.authorId ??
471
+ "unknown",
472
+ },
473
+ isResolved: true,
474
+ resolvedAt: context.timestamp,
475
+ },
476
+ };
477
+
478
+ return createTransaction(
479
+ {
480
+ ...state,
481
+ document: {
482
+ ...state.document,
483
+ updatedAt: context.timestamp,
484
+ review: {
485
+ ...state.document.review,
486
+ comments,
487
+ },
488
+ },
489
+ },
490
+ {
491
+ historyBoundary: "push",
492
+ markDirty: true,
493
+ effects: {
494
+ commentResolved: {
495
+ commentId: command.commentId,
496
+ },
497
+ },
498
+ },
499
+ );
500
+ }
501
+ case "comment.reopen": {
502
+ const existingThread = state.document.review.comments[command.commentId];
503
+ if (!existingThread || existingThread.status === "detached") {
504
+ return createTransaction(state, { historyBoundary: "skip", markDirty: false });
505
+ }
506
+ const reopenedComments = {
507
+ ...state.document.review.comments,
508
+ [command.commentId]: {
509
+ ...existingThread,
510
+ status: "open" as const,
511
+ isResolved: false,
512
+ resolvedAt: undefined,
513
+ resolution: undefined,
514
+ },
515
+ };
516
+ return createTransaction(
517
+ {
518
+ ...state,
519
+ document: {
520
+ ...state.document,
521
+ updatedAt: context.timestamp,
522
+ review: { ...state.document.review, comments: reopenedComments },
523
+ },
524
+ runtime: { ...state.runtime, activeCommentId: command.commentId },
525
+ },
526
+ {
527
+ historyBoundary: "push",
528
+ markDirty: true,
529
+ effects: { commentReopened: { commentId: command.commentId } },
530
+ },
531
+ );
532
+ }
533
+ case "comment.add-reply": {
534
+ const threadForReply = state.document.review.comments[command.commentId];
535
+ if (!threadForReply) {
536
+ return createTransaction(state, { historyBoundary: "skip", markDirty: false });
537
+ }
538
+ // Block reply on resolved or detached threads (must reopen first)
539
+ if (threadForReply.status === "resolved" || threadForReply.status === "detached") {
540
+ return createTransaction(state, { historyBoundary: "skip", markDirty: false });
541
+ }
542
+ const entryId = `${command.commentId}-entry-${(threadForReply.entries?.length ?? 0) + 1}`;
543
+ const newEntry = {
544
+ entryId,
545
+ authorId: command.authorId ?? threadForReply.createdBy ?? "unknown",
546
+ body: command.body,
547
+ createdAt: context.timestamp,
548
+ };
549
+ const updatedThread = {
550
+ ...threadForReply,
551
+ entries: [...(threadForReply.entries ?? []), newEntry],
552
+ };
553
+ const replyComments = {
554
+ ...state.document.review.comments,
555
+ [command.commentId]: updatedThread,
556
+ };
557
+ return createTransaction(
558
+ {
559
+ ...state,
560
+ document: {
561
+ ...state.document,
562
+ updatedAt: context.timestamp,
563
+ review: { ...state.document.review, comments: replyComments },
564
+ },
565
+ },
566
+ {
567
+ historyBoundary: "push",
568
+ markDirty: true,
569
+ effects: { commentReplyAdded: { commentId: command.commentId } },
570
+ },
571
+ );
572
+ }
573
+ case "comment.edit-body": {
574
+ const threadToEdit = state.document.review.comments[command.commentId];
575
+ if (!threadToEdit || !threadToEdit.entries?.length) {
576
+ return createTransaction(state, { historyBoundary: "skip", markDirty: false });
577
+ }
578
+ const editedEntries = [...threadToEdit.entries];
579
+ editedEntries[0] = { ...editedEntries[0], body: command.body };
580
+ const editedThread = {
581
+ ...threadToEdit,
582
+ body: command.body,
583
+ entries: editedEntries,
584
+ };
585
+ const editedComments = {
586
+ ...state.document.review.comments,
587
+ [command.commentId]: editedThread,
588
+ };
589
+ return createTransaction(
590
+ {
591
+ ...state,
592
+ document: {
593
+ ...state.document,
594
+ updatedAt: context.timestamp,
595
+ review: { ...state.document.review, comments: editedComments },
596
+ },
597
+ },
598
+ {
599
+ historyBoundary: "push",
600
+ markDirty: true,
601
+ effects: { commentBodyEdited: { commentId: command.commentId } },
602
+ },
603
+ );
604
+ }
605
+ case "change.accept":
606
+ return applyReviewCommand(
607
+ state,
608
+ createAcceptRevisionCommand(command.changeId, command.origin),
609
+ context.timestamp,
610
+ );
611
+ case "change.reject":
612
+ return applyReviewCommand(
613
+ state,
614
+ createRejectRevisionCommand(command.changeId, command.origin),
615
+ context.timestamp,
616
+ );
617
+ case "change.accept-all":
618
+ return applyReviewCommand(
619
+ state,
620
+ {
621
+ type: "review.accept-all-revisions",
622
+ ...(command.origin ? { origin: command.origin } : {}),
623
+ },
624
+ context.timestamp,
625
+ );
626
+ case "change.reject-all":
627
+ return applyReviewCommand(
628
+ state,
629
+ {
630
+ type: "review.reject-all-revisions",
631
+ ...(command.origin ? { origin: command.origin } : {}),
632
+ },
633
+ context.timestamp,
634
+ );
635
+ }
636
+ }
637
+
638
+ export function remapSelection(
639
+ selection: SelectionSnapshot,
640
+ mapping: TransactionMapping,
641
+ ): SelectionSnapshot {
642
+ const activeRange = mapAnchor(selection.activeRange, mapping);
643
+
644
+ if (activeRange.kind === "range") {
645
+ return {
646
+ anchor: activeRange.range.from,
647
+ head: activeRange.range.to,
648
+ isCollapsed: activeRange.range.from === activeRange.range.to,
649
+ activeRange,
650
+ };
651
+ }
652
+
653
+ if (activeRange.kind === "node") {
654
+ return {
655
+ anchor: activeRange.at,
656
+ head: activeRange.at,
657
+ isCollapsed: true,
658
+ activeRange,
659
+ };
660
+ }
661
+
662
+ return {
663
+ anchor: selection.anchor,
664
+ head: selection.head,
665
+ isCollapsed: selection.anchor === selection.head,
666
+ activeRange,
667
+ };
668
+ }
669
+
670
+ export function selectionChanged(
671
+ left: SelectionSnapshot,
672
+ right: SelectionSnapshot,
673
+ ): boolean {
674
+ return (
675
+ left.anchor !== right.anchor ||
676
+ left.head !== right.head ||
677
+ left.isCollapsed !== right.isCollapsed ||
678
+ !areAnchorsEqual(left.activeRange, right.activeRange)
679
+ );
680
+ }
681
+
682
+ function createTransaction(
683
+ nextState: EditorState,
684
+ options: {
685
+ mapping?: TransactionMapping;
686
+ historyBoundary: "push" | "skip";
687
+ markDirty: boolean;
688
+ effects?: Partial<TransactionEffects>;
689
+ },
690
+ ): EditorTransaction {
691
+ return {
692
+ nextState,
693
+ mapping: options.mapping ?? createEmptyMapping(),
694
+ historyBoundary: options.historyBoundary,
695
+ markDirty: options.markDirty,
696
+ effects: {
697
+ warningsAdded: options.effects?.warningsAdded ?? [],
698
+ warningsCleared: options.effects?.warningsCleared ?? [],
699
+ commentAdded: options.effects?.commentAdded,
700
+ commentResolved: options.effects?.commentResolved,
701
+ changeAccepted: options.effects?.changeAccepted,
702
+ changeRejected: options.effects?.changeRejected,
703
+ revisionAuthored: options.effects?.revisionAuthored,
704
+ commandBlocked: options.effects?.commandBlocked,
705
+ },
706
+ };
707
+ }
708
+
709
+ function normalizeSelection(selection: SelectionSnapshot): SelectionSnapshot {
710
+ const activeRange = normalizeSelectionAnchor(
711
+ selection.activeRange,
712
+ selection.anchor,
713
+ selection.head,
714
+ );
715
+
716
+ if (activeRange.kind === "range") {
717
+ const rangeFrom = activeRange.range.from;
718
+ const rangeTo = activeRange.range.to;
719
+ const collapsed = rangeFrom === rangeTo;
720
+ const anchorWithinRange = selection.anchor >= rangeFrom && selection.anchor <= rangeTo;
721
+ const headWithinRange = selection.head >= rangeFrom && selection.head <= rangeTo;
722
+ const preserveDirectionalEndpoints = anchorWithinRange && headWithinRange;
723
+ const fallbackForward = selection.anchor <= selection.head;
724
+ const anchor = collapsed
725
+ ? rangeFrom
726
+ : preserveDirectionalEndpoints
727
+ ? selection.anchor
728
+ : fallbackForward
729
+ ? rangeFrom
730
+ : rangeTo;
731
+ const head = collapsed
732
+ ? rangeTo
733
+ : preserveDirectionalEndpoints
734
+ ? selection.head
735
+ : fallbackForward
736
+ ? rangeTo
737
+ : rangeFrom;
738
+ return {
739
+ anchor,
740
+ head,
741
+ isCollapsed: collapsed,
742
+ activeRange,
743
+ };
744
+ }
745
+
746
+ if (activeRange.kind === "node") {
747
+ return {
748
+ anchor: activeRange.at,
749
+ head: activeRange.at,
750
+ isCollapsed: true,
751
+ activeRange,
752
+ };
753
+ }
754
+
755
+ return {
756
+ anchor: activeRange.lastKnownRange.from,
757
+ head: activeRange.lastKnownRange.to,
758
+ isCollapsed: activeRange.lastKnownRange.from === activeRange.lastKnownRange.to,
759
+ activeRange,
760
+ };
761
+ }
762
+
763
+ function normalizeSelectionAnchor(
764
+ value: SelectionSnapshot["activeRange"],
765
+ anchor: number,
766
+ head: number,
767
+ ): EditorAnchorProjection {
768
+ if (!value || typeof value !== "object") {
769
+ return createRangeAnchor(anchor, head, DEFAULT_BOUNDARY_ASSOC);
770
+ }
771
+
772
+ const record = value as unknown as Record<string, unknown>;
773
+ switch (record.kind) {
774
+ case "range": {
775
+ const assoc = normalizeBoundaryAssoc(record.assoc);
776
+ const internalRange = record.range;
777
+ if (
778
+ internalRange &&
779
+ typeof internalRange === "object" &&
780
+ typeof (internalRange as { from?: unknown }).from === "number" &&
781
+ typeof (internalRange as { to?: unknown }).to === "number"
782
+ ) {
783
+ return createRangeAnchor(
784
+ (internalRange as { from: number }).from,
785
+ (internalRange as { to: number }).to,
786
+ assoc,
787
+ );
788
+ }
789
+
790
+ if (typeof record.from === "number" && typeof record.to === "number") {
791
+ return createRangeAnchor(record.from, record.to, assoc);
792
+ }
793
+
794
+ return createRangeAnchor(anchor, head, assoc);
795
+ }
796
+ case "node":
797
+ return createNodeAnchor(
798
+ typeof record.at === "number" ? record.at : anchor,
799
+ normalizeAssoc(record.assoc),
800
+ );
801
+ case "detached": {
802
+ const lastKnownRange = record.lastKnownRange;
803
+ if (
804
+ lastKnownRange &&
805
+ typeof lastKnownRange === "object" &&
806
+ typeof (lastKnownRange as { from?: unknown }).from === "number" &&
807
+ typeof (lastKnownRange as { to?: unknown }).to === "number"
808
+ ) {
809
+ return createDetachedAnchor(
810
+ {
811
+ from: (lastKnownRange as { from: number }).from,
812
+ to: (lastKnownRange as { to: number }).to,
813
+ },
814
+ normalizeDetachedReason(record.reason),
815
+ );
816
+ }
817
+
818
+ return createDetachedAnchor({ from: anchor, to: head }, normalizeDetachedReason(record.reason));
819
+ }
820
+ default:
821
+ return createRangeAnchor(anchor, head, DEFAULT_BOUNDARY_ASSOC);
822
+ }
823
+ }
824
+
825
+ function normalizeBoundaryAssoc(value: unknown): BoundaryAssoc {
826
+ if (value && typeof value === "object") {
827
+ const record = value as unknown as Record<string, unknown>;
828
+ return {
829
+ start: normalizeAssoc(record.start),
830
+ end: normalizeAssoc(record.end),
831
+ };
832
+ }
833
+
834
+ return DEFAULT_BOUNDARY_ASSOC;
835
+ }
836
+
837
+ function normalizeAssoc(value: unknown): -1 | 1 {
838
+ return value === -1 ? -1 : 1;
839
+ }
840
+
841
+ function normalizeDetachedReason(
842
+ value: unknown,
843
+ ): "deleted" | "invalidatedByStructureChange" | "importAmbiguity" {
844
+ if (
845
+ value === "deleted" ||
846
+ value === "invalidatedByStructureChange" ||
847
+ value === "importAmbiguity"
848
+ ) {
849
+ return value;
850
+ }
851
+
852
+ return "importAmbiguity";
853
+ }
854
+
855
+ function applyTextCommand(
856
+ state: EditorState,
857
+ timestamp: string,
858
+ apply: (
859
+ document: CanonicalDocumentEnvelope,
860
+ selection: SelectionSnapshot,
861
+ ) => {
862
+ document: CanonicalDocumentEnvelope;
863
+ selection: SelectionSnapshot;
864
+ mapping: TransactionMapping;
865
+ },
866
+ ): EditorTransaction {
867
+ if (state.readOnly) {
868
+ return createTransaction(state, {
869
+ historyBoundary: "skip",
870
+ markDirty: false,
871
+ });
872
+ }
873
+
874
+ const result = apply(state.document, state.selection);
875
+ const reviewState = remapReviewStateAfterContentChange(
876
+ state,
877
+ result.document,
878
+ result.mapping,
879
+ );
880
+
881
+ return createTransaction(
882
+ {
883
+ ...state,
884
+ document: reviewState.document,
885
+ selection: result.selection,
886
+ warnings: reviewState.warnings,
887
+ runtime: {
888
+ ...state.runtime,
889
+ activeCommentId: reviewState.activeCommentId,
890
+ },
891
+ },
892
+ {
893
+ historyBoundary: "push",
894
+ markDirty: true,
895
+ mapping: result.mapping,
896
+ effects: reviewState.effects,
897
+ },
898
+ );
899
+ }
900
+
901
+ function applyReviewCommand(
902
+ state: EditorState,
903
+ command: ReviewCommand,
904
+ timestamp: string,
905
+ ): EditorTransaction {
906
+ if (state.readOnly) {
907
+ return createTransaction(state, {
908
+ historyBoundary: "skip",
909
+ markDirty: false,
910
+ });
911
+ }
912
+
913
+ const result = applyRevisionRuntimeCommand({
914
+ state: {
915
+ document: state.document,
916
+ store: createRevisionStoreFromState(state),
917
+ },
918
+ command,
919
+ timestamp,
920
+ });
921
+ const hasAppliedOutcome = result.outcomes.some((outcome) => outcome.kind === "applied");
922
+
923
+ if (!hasAppliedOutcome) {
924
+ return createTransaction(state, {
925
+ historyBoundary: "skip",
926
+ markDirty: false,
927
+ });
928
+ }
929
+
930
+ let selection = state.selection;
931
+ let comments = result.document.review.comments;
932
+ let warnings = state.warnings;
933
+ let activeCommentId = state.runtime.activeCommentId;
934
+ const mappingSteps: MappingStep[] = [];
935
+
936
+ for (const entry of result.mappings) {
937
+ if (entry.steps === 0) {
938
+ continue;
939
+ }
940
+
941
+ selection = remapSelection(selection, entry.mapping);
942
+ mappingSteps.push(...entry.mapping.steps);
943
+
944
+ const remappedComments = remapCommentThreads({
945
+ comments,
946
+ mapping: entry.mapping,
947
+ nextContent: result.document.content,
948
+ existingWarnings: mapWarningsThroughMapping(warnings, entry.mapping),
949
+ });
950
+ comments = remappedComments.comments;
951
+ warnings = remappedComments.warnings;
952
+ activeCommentId =
953
+ activeCommentId && comments[activeCommentId]
954
+ ? activeCommentId
955
+ : undefined;
956
+ }
957
+
958
+ warnings = mergeDetachedRevisionWarnings(result.store, warnings);
959
+
960
+ const nextDocument = {
961
+ ...result.document,
962
+ review: {
963
+ ...result.document.review,
964
+ comments,
965
+ revisions: toEditorRevisionRecords(result.store),
966
+ },
967
+ };
968
+ const appliedRevisionIds = result.effects.appliedRevisionIds;
969
+
970
+ return createTransaction(
971
+ {
972
+ ...state,
973
+ document: nextDocument,
974
+ selection,
975
+ warnings,
976
+ runtime: {
977
+ ...state.runtime,
978
+ activeCommentId,
979
+ },
980
+ },
981
+ {
982
+ historyBoundary: "push",
983
+ markDirty: true,
984
+ mapping: combineMappingSteps(mappingSteps),
985
+ effects: {
986
+ ...buildWarningEffects(state.warnings, warnings),
987
+ changeAccepted:
988
+ command.type === "review.accept-revision" && appliedRevisionIds[0]
989
+ ? {
990
+ changeId: appliedRevisionIds[0],
991
+ }
992
+ : undefined,
993
+ changeRejected:
994
+ command.type === "review.reject-revision" && appliedRevisionIds[0]
995
+ ? {
996
+ changeId: appliedRevisionIds[0],
997
+ }
998
+ : undefined,
999
+ },
1000
+ },
1001
+ );
1002
+ }
1003
+
1004
+ function remapReviewStateAfterContentChange(
1005
+ state: EditorState,
1006
+ nextDocument: CanonicalDocumentEnvelope,
1007
+ mapping: TransactionMapping,
1008
+ ): {
1009
+ document: CanonicalDocumentEnvelope;
1010
+ warnings: EditorWarning[];
1011
+ activeCommentId?: string;
1012
+ effects: Pick<TransactionEffects, "warningsAdded" | "warningsCleared">;
1013
+ } {
1014
+ const mappedWarnings = mapWarningsThroughMapping(state.warnings, mapping);
1015
+ const remappedComments = remapCommentThreads({
1016
+ comments: nextDocument.review.comments,
1017
+ mapping,
1018
+ nextContent: nextDocument.content,
1019
+ existingWarnings: mappedWarnings,
1020
+ });
1021
+ const revisions = Object.fromEntries(
1022
+ Object.entries(nextDocument.review.revisions).map(([changeId, revision]) => [
1023
+ changeId,
1024
+ {
1025
+ ...revision,
1026
+ anchor: mapAnchor(revision.anchor, mapping),
1027
+ },
1028
+ ]),
1029
+ );
1030
+ const activeCommentId =
1031
+ state.runtime.activeCommentId &&
1032
+ remappedComments.comments[state.runtime.activeCommentId]
1033
+ ? state.runtime.activeCommentId
1034
+ : undefined;
1035
+ const warnings = remappedComments.warnings;
1036
+
1037
+ return {
1038
+ document: {
1039
+ ...nextDocument,
1040
+ review: {
1041
+ ...nextDocument.review,
1042
+ comments: remappedComments.comments,
1043
+ revisions,
1044
+ },
1045
+ },
1046
+ warnings,
1047
+ activeCommentId,
1048
+ effects: buildWarningEffects(state.warnings, warnings),
1049
+ };
1050
+ }
1051
+
1052
+ function createRevisionStoreFromState(
1053
+ state: Pick<EditorState, "document">,
1054
+ ): RevisionStore {
1055
+ return {
1056
+ version: "revision-store/1",
1057
+ revisions: Object.fromEntries(
1058
+ Object.values(state.document.review.revisions).map((revision) => [
1059
+ revision.changeId,
1060
+ {
1061
+ revisionId: revision.changeId,
1062
+ kind: revision.kind,
1063
+ anchor: revision.anchor,
1064
+ authorId: revision.authorId ?? "unknown",
1065
+ createdAt: revision.createdAt,
1066
+ status: revision.status === "open" ? "active" : revision.status,
1067
+ warningIds: [...(revision.warningIds ?? [])],
1068
+ metadata: {
1069
+ source: revision.metadata?.source ?? "runtime",
1070
+ storyTarget: revision.metadata?.storyTarget,
1071
+ preserveOnlyReason: revision.metadata?.preserveOnlyReason,
1072
+ suggestionId: revision.metadata?.suggestionId,
1073
+ semanticKind: revision.metadata?.semanticKind,
1074
+ linkedRevisionIds: revision.metadata?.linkedRevisionIds,
1075
+ predecessorSuggestionId: revision.metadata?.predecessorSuggestionId,
1076
+ importedRevisionForm: revision.metadata?.importedRevisionForm,
1077
+ originalRevisionType: revision.metadata?.originalRevisionType,
1078
+ ooxmlRevisionId: revision.metadata?.ooxmlRevisionId,
1079
+ },
1080
+ },
1081
+ ]),
1082
+ ),
1083
+ };
1084
+ }
1085
+
1086
+ function toEditorRevisionRecords(
1087
+ store: RevisionStore,
1088
+ ): EditorState["document"]["review"]["revisions"] {
1089
+ return Object.fromEntries(
1090
+ Object.values(store.revisions).map((revision) => [
1091
+ revision.revisionId,
1092
+ {
1093
+ changeId: revision.revisionId,
1094
+ kind: revision.kind,
1095
+ anchor: revision.anchor,
1096
+ authorId: revision.authorId,
1097
+ createdAt: revision.createdAt,
1098
+ warningIds: [...revision.warningIds],
1099
+ metadata: {
1100
+ source: revision.metadata.source,
1101
+ storyTarget: revision.metadata.storyTarget,
1102
+ preserveOnlyReason: revision.metadata.preserveOnlyReason,
1103
+ suggestionId: revision.metadata.suggestionId,
1104
+ semanticKind: revision.metadata.semanticKind,
1105
+ linkedRevisionIds: revision.metadata.linkedRevisionIds,
1106
+ predecessorSuggestionId: revision.metadata.predecessorSuggestionId,
1107
+ importedRevisionForm: revision.metadata.importedRevisionForm,
1108
+ originalRevisionType: revision.metadata.originalRevisionType,
1109
+ ooxmlRevisionId: revision.metadata.ooxmlRevisionId,
1110
+ },
1111
+ status: revision.status === "active" ? "open" : revision.status,
1112
+ },
1113
+ ]),
1114
+ );
1115
+ }
1116
+
1117
+ function mapWarningsThroughMapping(
1118
+ warnings: EditorWarning[],
1119
+ mapping: TransactionMapping,
1120
+ ): EditorWarning[] {
1121
+ return warnings.map((warning) =>
1122
+ warning.affectedAnchor
1123
+ ? {
1124
+ ...warning,
1125
+ affectedAnchor: mapAnchor(warning.affectedAnchor, mapping),
1126
+ }
1127
+ : warning,
1128
+ );
1129
+ }
1130
+
1131
+ function buildWarningEffects(
1132
+ previousWarnings: EditorWarning[],
1133
+ nextWarnings: EditorWarning[],
1134
+ ): Pick<TransactionEffects, "warningsAdded" | "warningsCleared"> {
1135
+ const previousById = new Set(previousWarnings.map((warning) => warning.warningId));
1136
+ const nextById = new Set(nextWarnings.map((warning) => warning.warningId));
1137
+
1138
+ return {
1139
+ warningsAdded: nextWarnings.filter((warning) => !previousById.has(warning.warningId)),
1140
+ warningsCleared: previousWarnings
1141
+ .filter((warning) => !nextById.has(warning.warningId))
1142
+ .map((warning) => ({
1143
+ warningId: warning.warningId,
1144
+ code: warning.code,
1145
+ })),
1146
+ };
1147
+ }
1148
+
1149
+ function mergeDetachedRevisionWarnings(
1150
+ store: RevisionStore,
1151
+ existingWarnings: EditorWarning[],
1152
+ ): EditorWarning[] {
1153
+ const retainedWarnings = existingWarnings.filter(
1154
+ (warning) =>
1155
+ warning.code !== "revision_anchor_detached" ||
1156
+ !warning.details ||
1157
+ typeof warning.details.changeId !== "string" ||
1158
+ store.revisions[warning.details.changeId]?.status === "detached",
1159
+ );
1160
+
1161
+ const knownDetachedIds = new Set(
1162
+ retainedWarnings
1163
+ .filter((warning) => warning.code === "revision_anchor_detached")
1164
+ .map((warning) =>
1165
+ typeof warning.details?.changeId === "string"
1166
+ ? warning.details.changeId
1167
+ : undefined,
1168
+ )
1169
+ .filter((value): value is string => Boolean(value)),
1170
+ );
1171
+
1172
+ const detachedWarnings = Object.values(store.revisions)
1173
+ .filter(
1174
+ (revision) =>
1175
+ revision.status === "detached" && !knownDetachedIds.has(revision.revisionId),
1176
+ )
1177
+ .map((revision) => ({
1178
+ warningId: `warning:revision-anchor-detached:${revision.revisionId}`,
1179
+ code: "revision_anchor_detached" as const,
1180
+ severity: "warning" as const,
1181
+ message: `Revision ${revision.revisionId} detached after review remapping.`,
1182
+ source: "review" as const,
1183
+ affectedAnchor: revision.anchor.kind === "detached" ? revision.anchor : undefined,
1184
+ details: {
1185
+ changeId: revision.revisionId,
1186
+ reason:
1187
+ revision.anchor.kind === "detached"
1188
+ ? revision.anchor.reason
1189
+ : undefined,
1190
+ },
1191
+ }));
1192
+
1193
+ return [...retainedWarnings, ...detachedWarnings];
1194
+ }
1195
+
1196
+ function combineMappingSteps(
1197
+ steps: MappingStep[],
1198
+ ): TransactionMapping {
1199
+ return steps.length > 0
1200
+ ? {
1201
+ steps,
1202
+ }
1203
+ : createEmptyMapping();
1204
+ }
1205
+
1206
+ // ---------------------------------------------------------------------------
1207
+ // Suggesting mode: creates revision records instead of (or alongside) text mutations
1208
+ // ---------------------------------------------------------------------------
1209
+
1210
+ let suggestingRevisionCounter = 0;
1211
+
1212
+ function createSuggestingRevisionId(
1213
+ existing: Record<string, unknown>,
1214
+ timestamp: string,
1215
+ ): string {
1216
+ suggestingRevisionCounter += 1;
1217
+ const ts = timestamp.replace(/[^0-9]/gu, "");
1218
+ let id = `change-${ts}-s${suggestingRevisionCounter}`;
1219
+ while (existing[id]) {
1220
+ suggestingRevisionCounter += 1;
1221
+ id = `change-${ts}-s${suggestingRevisionCounter}`;
1222
+ }
1223
+ return id;
1224
+ }
1225
+
1226
+ function createAuthoredRevision(
1227
+ existing: Record<string, unknown>,
1228
+ kind: "insertion" | "deletion",
1229
+ from: number,
1230
+ to: number,
1231
+ authorId: string,
1232
+ timestamp: string,
1233
+ metadata: Partial<NonNullable<CanonicalRevisionRecord["metadata"]>> = {},
1234
+ ): CanonicalRevisionRecord {
1235
+ const changeId = createSuggestingRevisionId(existing, timestamp);
1236
+ return {
1237
+ changeId,
1238
+ kind,
1239
+ anchor: {
1240
+ kind: "range",
1241
+ range: { from, to },
1242
+ assoc: { start: 1, end: -1 },
1243
+ },
1244
+ authorId,
1245
+ createdAt: timestamp,
1246
+ warningIds: [],
1247
+ metadata: {
1248
+ source: "runtime",
1249
+ ...metadata,
1250
+ },
1251
+ status: "open",
1252
+ };
1253
+ }
1254
+
1255
+ function createSuggestionMetadata(args: {
1256
+ suggestionId?: string;
1257
+ semanticKind:
1258
+ | "insertion"
1259
+ | "deletion"
1260
+ | "replacement"
1261
+ | "formatting-change"
1262
+ | "paragraph-property-change"
1263
+ | "structural-change"
1264
+ | "object-change";
1265
+ linkedRevisionIds?: string[];
1266
+ predecessorSuggestionId?: string;
1267
+ }): Partial<NonNullable<CanonicalRevisionRecord["metadata"]>> {
1268
+ return {
1269
+ suggestionId: args.suggestionId,
1270
+ semanticKind: args.semanticKind,
1271
+ linkedRevisionIds: args.linkedRevisionIds,
1272
+ predecessorSuggestionId: args.predecessorSuggestionId,
1273
+ };
1274
+ }
1275
+
1276
+ function createSuggestingUnsupportedTransaction(
1277
+ state: EditorState,
1278
+ message: string,
1279
+ ): EditorTransaction {
1280
+ return createTransaction(state, {
1281
+ historyBoundary: "skip",
1282
+ markDirty: false,
1283
+ effects: {
1284
+ commandBlocked: {
1285
+ code: "suggesting_unsupported",
1286
+ message,
1287
+ },
1288
+ },
1289
+ });
1290
+ }
1291
+
1292
+ function isSingleParagraphSuggestingRange(
1293
+ document: CanonicalDocumentEnvelope,
1294
+ from: number,
1295
+ to: number,
1296
+ ): boolean {
1297
+ const ranges: Array<{ start: number; end: number }> = [];
1298
+ let cursor = 0;
1299
+ let previousWasParagraph = false;
1300
+
1301
+ for (const block of document.content.children) {
1302
+ if (block.type === "paragraph") {
1303
+ if (previousWasParagraph) {
1304
+ cursor += 1;
1305
+ }
1306
+ const start = cursor;
1307
+ cursor += block.children.reduce<number>((size, child) => {
1308
+ if (child.type === "text") {
1309
+ return size + child.text.length;
1310
+ }
1311
+ if (child.type === "hyperlink") {
1312
+ return size + child.children.reduce<number>((childSize, entry) => {
1313
+ if (entry.type === "text") {
1314
+ return childSize + entry.text.length;
1315
+ }
1316
+ return childSize + 1;
1317
+ }, 0);
1318
+ }
1319
+ return size + 1;
1320
+ }, 0);
1321
+ ranges.push({ start, end: cursor });
1322
+ previousWasParagraph = true;
1323
+ continue;
1324
+ }
1325
+
1326
+ cursor += 1;
1327
+ previousWasParagraph = false;
1328
+ }
1329
+
1330
+ return ranges.some((range) => from >= range.start && to <= range.end);
1331
+ }
1332
+
1333
+ function applySuggestingInsert(
1334
+ state: EditorState,
1335
+ text: string,
1336
+ context: CommandExecutionContext,
1337
+ ): EditorTransaction | undefined {
1338
+ if (state.readOnly) {
1339
+ return createTransaction(state, { historyBoundary: "skip", markDirty: false });
1340
+ }
1341
+
1342
+ const authorId = context.defaultAuthorId ?? "unknown";
1343
+ const selection = state.selection;
1344
+ const from = Math.min(selection.anchor, selection.head);
1345
+ const to = Math.max(selection.anchor, selection.head);
1346
+ const isCollapsed = from === to;
1347
+
1348
+ if (!isCollapsed && !isSingleParagraphSuggestingRange(state.document, from, to)) {
1349
+ return createSuggestingUnsupportedTransaction(
1350
+ state,
1351
+ "Suggesting mode does not yet support multi-paragraph replacement ranges.",
1352
+ );
1353
+ }
1354
+
1355
+ if (isCollapsed) {
1356
+ // Pure insertion at cursor: apply normally, then create insertion revision
1357
+ const result = insertText(state.document, selection, text, { timestamp: context.timestamp });
1358
+ const insertedFrom = from;
1359
+ const insertedTo = from + Array.from(text).length;
1360
+
1361
+ // Remap existing review state first (comments, pre-existing revisions)
1362
+ const reviewState = remapReviewStateAfterContentChange(
1363
+ state,
1364
+ result.document,
1365
+ result.mapping,
1366
+ );
1367
+
1368
+ // Create the revision with pre-mapping positions — it refers to content
1369
+ // that was just inserted, so its anchors are already correct in the new document
1370
+ const revision = createAuthoredRevision(
1371
+ reviewState.document.review.revisions,
1372
+ "insertion",
1373
+ insertedFrom,
1374
+ insertedTo,
1375
+ authorId,
1376
+ context.timestamp,
1377
+ createSuggestionMetadata({
1378
+ semanticKind: "insertion",
1379
+ }),
1380
+ );
1381
+
1382
+ const finalDocument: CanonicalDocumentEnvelope = {
1383
+ ...reviewState.document,
1384
+ review: {
1385
+ ...reviewState.document.review,
1386
+ revisions: {
1387
+ ...reviewState.document.review.revisions,
1388
+ [revision.changeId]: revision,
1389
+ },
1390
+ },
1391
+ };
1392
+
1393
+ return createTransaction(
1394
+ {
1395
+ ...state,
1396
+ document: finalDocument,
1397
+ selection: result.selection,
1398
+ warnings: reviewState.warnings,
1399
+ runtime: {
1400
+ ...state.runtime,
1401
+ activeCommentId: reviewState.activeCommentId,
1402
+ },
1403
+ },
1404
+ {
1405
+ historyBoundary: "push",
1406
+ markDirty: true,
1407
+ mapping: result.mapping,
1408
+ effects: {
1409
+ ...reviewState.effects,
1410
+ revisionAuthored: { changeId: revision.changeId, kind: "insertion" },
1411
+ },
1412
+ },
1413
+ );
1414
+ }
1415
+
1416
+ // Non-collapsed selection: mark selected text as deletion, insert new text after selection
1417
+ // Step 1: Insert new text at the end of the selection
1418
+ const insertSelection = createSelectionSnapshot(to, to);
1419
+ const result = insertText(state.document, insertSelection, text, { timestamp: context.timestamp });
1420
+ const insertedFrom = to;
1421
+ const insertedTo = to + Array.from(text).length;
1422
+
1423
+ // Step 2: Remap existing review state through the mapping first
1424
+ const reviewState = remapReviewStateAfterContentChange(
1425
+ state,
1426
+ result.document,
1427
+ result.mapping,
1428
+ );
1429
+ const replacementSuggestionId = createSuggestingRevisionId(
1430
+ reviewState.document.review.revisions,
1431
+ context.timestamp,
1432
+ );
1433
+
1434
+ // Step 3: Create deletion revision for the selected range (text stays in place).
1435
+ // Deletion range uses pre-mapping positions since content was not removed.
1436
+ let deletionRevision = createAuthoredRevision(
1437
+ reviewState.document.review.revisions,
1438
+ "deletion",
1439
+ from,
1440
+ to,
1441
+ authorId,
1442
+ context.timestamp,
1443
+ createSuggestionMetadata({
1444
+ suggestionId: replacementSuggestionId,
1445
+ semanticKind: "replacement",
1446
+ }),
1447
+ );
1448
+
1449
+ // Step 4: Create insertion revision for the new text (positions already correct)
1450
+ const insertionRevision = createAuthoredRevision(
1451
+ {
1452
+ ...reviewState.document.review.revisions,
1453
+ [deletionRevision.changeId]: deletionRevision,
1454
+ },
1455
+ "insertion",
1456
+ insertedFrom,
1457
+ insertedTo,
1458
+ authorId,
1459
+ context.timestamp,
1460
+ createSuggestionMetadata({
1461
+ suggestionId: replacementSuggestionId,
1462
+ semanticKind: "replacement",
1463
+ linkedRevisionIds: [deletionRevision.changeId],
1464
+ }),
1465
+ );
1466
+ deletionRevision = {
1467
+ ...deletionRevision,
1468
+ metadata: {
1469
+ ...deletionRevision.metadata,
1470
+ linkedRevisionIds: [insertionRevision.changeId],
1471
+ },
1472
+ };
1473
+
1474
+ const finalDocument: CanonicalDocumentEnvelope = {
1475
+ ...reviewState.document,
1476
+ review: {
1477
+ ...reviewState.document.review,
1478
+ revisions: {
1479
+ ...reviewState.document.review.revisions,
1480
+ [deletionRevision.changeId]: deletionRevision,
1481
+ [insertionRevision.changeId]: insertionRevision,
1482
+ },
1483
+ },
1484
+ };
1485
+
1486
+ // Move cursor to after inserted text
1487
+ const caretPos = insertedTo;
1488
+
1489
+ return createTransaction(
1490
+ {
1491
+ ...state,
1492
+ document: finalDocument,
1493
+ selection: createSelectionSnapshot(caretPos, caretPos),
1494
+ warnings: reviewState.warnings,
1495
+ runtime: {
1496
+ ...state.runtime,
1497
+ activeCommentId: reviewState.activeCommentId,
1498
+ },
1499
+ },
1500
+ {
1501
+ historyBoundary: "push",
1502
+ markDirty: true,
1503
+ mapping: result.mapping,
1504
+ effects: {
1505
+ ...reviewState.effects,
1506
+ revisionAuthored: { changeId: insertionRevision.changeId, kind: "insertion" },
1507
+ },
1508
+ },
1509
+ );
1510
+ }
1511
+
1512
+ function applySuggestingDelete(
1513
+ state: EditorState,
1514
+ direction: "backward" | "forward",
1515
+ context: CommandExecutionContext,
1516
+ ): EditorTransaction | undefined {
1517
+ if (state.readOnly) {
1518
+ return createTransaction(state, { historyBoundary: "skip", markDirty: false });
1519
+ }
1520
+
1521
+ const authorId = context.defaultAuthorId ?? "unknown";
1522
+ const selection = state.selection;
1523
+ const from = Math.min(selection.anchor, selection.head);
1524
+ const to = Math.max(selection.anchor, selection.head);
1525
+ const isCollapsed = from === to;
1526
+
1527
+ if (!isCollapsed && !isSingleParagraphSuggestingRange(state.document, from, to)) {
1528
+ return createSuggestingUnsupportedTransaction(
1529
+ state,
1530
+ "Suggesting mode does not yet support multi-paragraph deletion ranges.",
1531
+ );
1532
+ }
1533
+
1534
+ let deleteFrom: number;
1535
+ let deleteTo: number;
1536
+
1537
+ if (isCollapsed) {
1538
+ if (direction === "backward") {
1539
+ deleteFrom = Math.max(0, from - 1);
1540
+ deleteTo = from;
1541
+ } else {
1542
+ deleteFrom = from;
1543
+ deleteTo = from + 1;
1544
+ }
1545
+ } else {
1546
+ deleteFrom = from;
1547
+ deleteTo = to;
1548
+ }
1549
+
1550
+ // Validate the deletion range doesn't cross protected content
1551
+ if (deleteFrom === deleteTo) {
1552
+ return createTransaction(state, { historyBoundary: "skip", markDirty: false });
1553
+ }
1554
+
1555
+ // Check if the range overlaps an existing deletion revision from this suggesting session
1556
+ // If so, extend the existing revision rather than creating a new one
1557
+ const existingDeletion = findOverlappingAuthoredDeletion(
1558
+ state.document.review.revisions,
1559
+ deleteFrom,
1560
+ deleteTo,
1561
+ );
1562
+
1563
+ if (existingDeletion) {
1564
+ // Extend the existing deletion revision to cover the new range
1565
+ const extendedFrom = Math.min(
1566
+ existingDeletion.anchor.kind === "range" ? existingDeletion.anchor.range.from : deleteFrom,
1567
+ deleteFrom,
1568
+ );
1569
+ const extendedTo = Math.max(
1570
+ existingDeletion.anchor.kind === "range" ? existingDeletion.anchor.range.to : deleteTo,
1571
+ deleteTo,
1572
+ );
1573
+
1574
+ const updatedRevision: CanonicalRevisionRecord = {
1575
+ ...existingDeletion,
1576
+ anchor: {
1577
+ kind: "range",
1578
+ range: { from: extendedFrom, to: extendedTo },
1579
+ assoc: { start: 1, end: -1 },
1580
+ },
1581
+ };
1582
+
1583
+ const nextDocument: CanonicalDocumentEnvelope = {
1584
+ ...state.document,
1585
+ updatedAt: context.timestamp,
1586
+ review: {
1587
+ ...state.document.review,
1588
+ revisions: {
1589
+ ...state.document.review.revisions,
1590
+ [updatedRevision.changeId]: updatedRevision,
1591
+ },
1592
+ },
1593
+ };
1594
+
1595
+ const caretPos = direction === "backward" ? deleteFrom : deleteTo;
1596
+
1597
+ return createTransaction(
1598
+ {
1599
+ ...state,
1600
+ document: nextDocument,
1601
+ selection: createSelectionSnapshot(caretPos, caretPos),
1602
+ },
1603
+ {
1604
+ historyBoundary: "push",
1605
+ markDirty: true,
1606
+ effects: {
1607
+ revisionAuthored: { changeId: updatedRevision.changeId, kind: "deletion" },
1608
+ },
1609
+ },
1610
+ );
1611
+ }
1612
+
1613
+ // Create a new deletion revision — text stays in the document
1614
+ const revision = createAuthoredRevision(
1615
+ state.document.review.revisions,
1616
+ "deletion",
1617
+ deleteFrom,
1618
+ deleteTo,
1619
+ authorId,
1620
+ context.timestamp,
1621
+ createSuggestionMetadata({
1622
+ semanticKind: "deletion",
1623
+ }),
1624
+ );
1625
+
1626
+ const nextDocument: CanonicalDocumentEnvelope = {
1627
+ ...state.document,
1628
+ updatedAt: context.timestamp,
1629
+ review: {
1630
+ ...state.document.review,
1631
+ revisions: {
1632
+ ...state.document.review.revisions,
1633
+ [revision.changeId]: revision,
1634
+ },
1635
+ },
1636
+ };
1637
+
1638
+ const caretPos = direction === "backward" ? deleteFrom : deleteTo;
1639
+
1640
+ return createTransaction(
1641
+ {
1642
+ ...state,
1643
+ document: nextDocument,
1644
+ selection: createSelectionSnapshot(caretPos, caretPos),
1645
+ },
1646
+ {
1647
+ historyBoundary: "push",
1648
+ markDirty: true,
1649
+ effects: {
1650
+ revisionAuthored: { changeId: revision.changeId, kind: "deletion" },
1651
+ },
1652
+ },
1653
+ );
1654
+ }
1655
+
1656
+ function applySuggestingInsertUnit(
1657
+ state: EditorState,
1658
+ unitType: "tab" | "hard_break",
1659
+ context: CommandExecutionContext,
1660
+ ): EditorTransaction | undefined {
1661
+ if (state.readOnly) {
1662
+ return createTransaction(state, { historyBoundary: "skip", markDirty: false });
1663
+ }
1664
+
1665
+ const authorId = context.defaultAuthorId ?? "unknown";
1666
+ const selection = state.selection;
1667
+ const from = Math.min(selection.anchor, selection.head);
1668
+ const to = Math.max(selection.anchor, selection.head);
1669
+
1670
+ if (from !== to && !isSingleParagraphSuggestingRange(state.document, from, to)) {
1671
+ return createSuggestingUnsupportedTransaction(
1672
+ state,
1673
+ "Suggesting mode does not yet support multi-paragraph replacement ranges.",
1674
+ );
1675
+ }
1676
+
1677
+ // Insert the unit at the end of the selection (or at cursor if collapsed)
1678
+ const insertPos = to;
1679
+ const insertSelection = createSelectionSnapshot(insertPos, insertPos);
1680
+ const applyFn = unitType === "tab" ? insertTab : insertHardBreak;
1681
+ const result = applyFn(state.document, insertSelection, { timestamp: context.timestamp });
1682
+
1683
+ // Remap existing review state first, before adding new revisions
1684
+ const reviewState = remapReviewStateAfterContentChange(
1685
+ state,
1686
+ result.document,
1687
+ result.mapping,
1688
+ );
1689
+ const replacementSuggestionId = from !== to
1690
+ ? createSuggestingRevisionId(reviewState.document.review.revisions, context.timestamp)
1691
+ : undefined;
1692
+
1693
+ // If non-collapsed, mark selected range as deletion (positions are pre-mapping, content preserved)
1694
+ let deletionRevision = from !== to
1695
+ ? createAuthoredRevision(
1696
+ reviewState.document.review.revisions,
1697
+ "deletion",
1698
+ from,
1699
+ to,
1700
+ authorId,
1701
+ context.timestamp,
1702
+ createSuggestionMetadata({
1703
+ suggestionId: replacementSuggestionId,
1704
+ semanticKind: "replacement",
1705
+ }),
1706
+ )
1707
+ : undefined;
1708
+
1709
+ // Create insertion revision for the single inserted unit (positions already correct)
1710
+ const insertionRevision = createAuthoredRevision(
1711
+ {
1712
+ ...reviewState.document.review.revisions,
1713
+ ...(deletionRevision ? { [deletionRevision.changeId]: deletionRevision } : {}),
1714
+ },
1715
+ "insertion",
1716
+ insertPos,
1717
+ insertPos + 1,
1718
+ authorId,
1719
+ context.timestamp,
1720
+ createSuggestionMetadata(
1721
+ from !== to
1722
+ ? {
1723
+ suggestionId: replacementSuggestionId,
1724
+ semanticKind: "replacement",
1725
+ linkedRevisionIds: deletionRevision ? [deletionRevision.changeId] : undefined,
1726
+ }
1727
+ : {
1728
+ semanticKind: "insertion",
1729
+ },
1730
+ ),
1731
+ );
1732
+ if (deletionRevision) {
1733
+ deletionRevision = {
1734
+ ...deletionRevision,
1735
+ metadata: {
1736
+ ...deletionRevision.metadata,
1737
+ linkedRevisionIds: [insertionRevision.changeId],
1738
+ },
1739
+ };
1740
+ }
1741
+
1742
+ const finalDocument: CanonicalDocumentEnvelope = {
1743
+ ...reviewState.document,
1744
+ review: {
1745
+ ...reviewState.document.review,
1746
+ revisions: {
1747
+ ...reviewState.document.review.revisions,
1748
+ ...(deletionRevision ? { [deletionRevision.changeId]: deletionRevision } : {}),
1749
+ [insertionRevision.changeId]: insertionRevision,
1750
+ },
1751
+ },
1752
+ };
1753
+
1754
+ return createTransaction(
1755
+ {
1756
+ ...state,
1757
+ document: finalDocument,
1758
+ selection: result.selection,
1759
+ warnings: reviewState.warnings,
1760
+ runtime: {
1761
+ ...state.runtime,
1762
+ activeCommentId: reviewState.activeCommentId,
1763
+ },
1764
+ },
1765
+ {
1766
+ historyBoundary: "push",
1767
+ markDirty: true,
1768
+ mapping: result.mapping,
1769
+ effects: {
1770
+ ...reviewState.effects,
1771
+ revisionAuthored: { changeId: insertionRevision.changeId, kind: "insertion" },
1772
+ },
1773
+ },
1774
+ );
1775
+ }
1776
+
1777
+ function applySuggestingParagraphSplit(
1778
+ state: EditorState,
1779
+ context: CommandExecutionContext,
1780
+ ): EditorTransaction | undefined {
1781
+ if (state.readOnly) {
1782
+ return createTransaction(state, { historyBoundary: "skip", markDirty: false });
1783
+ }
1784
+
1785
+ const selection = state.selection;
1786
+ const from = Math.min(selection.anchor, selection.head);
1787
+ const to = Math.max(selection.anchor, selection.head);
1788
+ if (from !== to) {
1789
+ return createSuggestingUnsupportedTransaction(
1790
+ state,
1791
+ "Suggesting mode paragraph split currently requires a collapsed selection.",
1792
+ );
1793
+ }
1794
+
1795
+ const authorId = context.defaultAuthorId ?? "unknown";
1796
+ const result = splitParagraph(state.document, selection, { timestamp: context.timestamp });
1797
+
1798
+ const reviewState = remapReviewStateAfterContentChange(
1799
+ state,
1800
+ result.document,
1801
+ result.mapping,
1802
+ );
1803
+ const revision = createAuthoredRevision(
1804
+ reviewState.document.review.revisions,
1805
+ "insertion",
1806
+ from,
1807
+ from,
1808
+ authorId,
1809
+ context.timestamp,
1810
+ {
1811
+ ...createSuggestionMetadata({
1812
+ semanticKind: "structural-change",
1813
+ }),
1814
+ importedRevisionForm: "paragraph-insertion",
1815
+ originalRevisionType: "paragraph-ins",
1816
+ },
1817
+ );
1818
+
1819
+ const finalDocument: CanonicalDocumentEnvelope = {
1820
+ ...reviewState.document,
1821
+ review: {
1822
+ ...reviewState.document.review,
1823
+ revisions: {
1824
+ ...reviewState.document.review.revisions,
1825
+ [revision.changeId]: revision,
1826
+ },
1827
+ },
1828
+ };
1829
+
1830
+ return createTransaction(
1831
+ {
1832
+ ...state,
1833
+ document: finalDocument,
1834
+ selection: result.selection,
1835
+ warnings: reviewState.warnings,
1836
+ runtime: {
1837
+ ...state.runtime,
1838
+ activeCommentId: reviewState.activeCommentId,
1839
+ },
1840
+ },
1841
+ {
1842
+ historyBoundary: "push",
1843
+ markDirty: true,
1844
+ mapping: result.mapping,
1845
+ effects: {
1846
+ ...reviewState.effects,
1847
+ revisionAuthored: { changeId: revision.changeId, kind: "insertion" },
1848
+ },
1849
+ },
1850
+ );
1851
+ }
1852
+
1853
+ function findOverlappingAuthoredDeletion(
1854
+ revisions: Record<string, CanonicalRevisionRecord>,
1855
+ from: number,
1856
+ to: number,
1857
+ ): CanonicalRevisionRecord | undefined {
1858
+ for (const revision of Object.values(revisions)) {
1859
+ if (
1860
+ revision.kind === "deletion" &&
1861
+ revision.status === "open" &&
1862
+ revision.metadata?.source === "runtime" &&
1863
+ revision.anchor.kind === "range"
1864
+ ) {
1865
+ const revFrom = revision.anchor.range.from;
1866
+ const revTo = revision.anchor.range.to;
1867
+ // Adjacent or overlapping: the deletion is directly next to or overlapping the range
1868
+ if (
1869
+ (from >= revFrom && from <= revTo) ||
1870
+ (to >= revFrom && to <= revTo) ||
1871
+ (from === revTo) ||
1872
+ (to === revFrom)
1873
+ ) {
1874
+ return revision;
1875
+ }
1876
+ }
1877
+ }
1878
+ return undefined;
1879
+ }