@beyondwork/docx-react-component 1.0.28 → 1.0.29

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 (354) hide show
  1. package/dist/canonical-document-BLEbzL2J.d.cts +844 -0
  2. package/dist/canonical-document-BLEbzL2J.d.ts +844 -0
  3. package/dist/chunk-2FJS5GZM.js +763 -0
  4. package/dist/chunk-2FJS5GZM.js.map +1 -0
  5. package/{src/core/commands/section-layout-commands.ts → dist/chunk-2OQBZS3F.js} +106 -340
  6. package/dist/chunk-2OQBZS3F.js.map +1 -0
  7. package/dist/chunk-2S7W4KFO.js +127 -0
  8. package/dist/chunk-2S7W4KFO.js.map +1 -0
  9. package/dist/chunk-2TG72QSW.js +3874 -0
  10. package/dist/chunk-2TG72QSW.js.map +1 -0
  11. package/{src/core/commands/table-structure-commands.ts → dist/chunk-36QNIZBO.js} +126 -315
  12. package/dist/chunk-36QNIZBO.js.map +1 -0
  13. package/dist/chunk-4AQOYAW4.js +3069 -0
  14. package/dist/chunk-4AQOYAW4.js.map +1 -0
  15. package/dist/chunk-4D5EWJ3P.js +77 -0
  16. package/dist/chunk-4D5EWJ3P.js.map +1 -0
  17. package/dist/chunk-5FN54NDH.js +2257 -0
  18. package/dist/chunk-5FN54NDH.js.map +1 -0
  19. package/dist/chunk-BOYGQYRQ.js +7306 -0
  20. package/dist/chunk-BOYGQYRQ.js.map +1 -0
  21. package/dist/chunk-CN3XMECL.js +212 -0
  22. package/dist/chunk-CN3XMECL.js.map +1 -0
  23. package/dist/chunk-EBI3BX6U.js +164 -0
  24. package/dist/chunk-EBI3BX6U.js.map +1 -0
  25. package/dist/chunk-EILUG3VB.js +1275 -0
  26. package/dist/chunk-EILUG3VB.js.map +1 -0
  27. package/dist/chunk-FUDY333O.js +70 -0
  28. package/dist/chunk-FUDY333O.js.map +1 -0
  29. package/dist/chunk-GBVOWFIK.js +1237 -0
  30. package/dist/chunk-GBVOWFIK.js.map +1 -0
  31. package/dist/chunk-H4TQ3H3Y.js +262 -0
  32. package/dist/chunk-H4TQ3H3Y.js.map +1 -0
  33. package/{src/core/commands/style-commands.ts → dist/chunk-JGB3IXZO.js} +40 -113
  34. package/dist/chunk-JGB3IXZO.js.map +1 -0
  35. package/dist/chunk-KD2QRQPY.js +4342 -0
  36. package/dist/chunk-KD2QRQPY.js.map +1 -0
  37. package/dist/chunk-KLMXQVYK.js +369 -0
  38. package/dist/chunk-KLMXQVYK.js.map +1 -0
  39. package/dist/chunk-KZUG5KFQ.js +214 -0
  40. package/dist/chunk-KZUG5KFQ.js.map +1 -0
  41. package/{src/core/state/text-transaction.ts → dist/chunk-QDAQ4CJU.js} +79 -236
  42. package/dist/chunk-QDAQ4CJU.js.map +1 -0
  43. package/{src/legal/bookmarks.ts → dist/chunk-RMH72RZI.js} +44 -130
  44. package/dist/chunk-RMH72RZI.js.map +1 -0
  45. package/dist/chunk-SWKWQZXM.js +117 -0
  46. package/dist/chunk-SWKWQZXM.js.map +1 -0
  47. package/{src/core/commands/formatting-commands.ts → dist/chunk-TJBP2K4T.js} +196 -536
  48. package/dist/chunk-TJBP2K4T.js.map +1 -0
  49. package/dist/chunk-TLCEAQDQ.js +542 -0
  50. package/dist/chunk-TLCEAQDQ.js.map +1 -0
  51. package/{src/core/commands/text-commands.ts → dist/chunk-UZXBISGO.js} +86 -142
  52. package/dist/chunk-UZXBISGO.js.map +1 -0
  53. package/dist/chunk-WGBAKP3Q.js +3220 -0
  54. package/dist/chunk-WGBAKP3Q.js.map +1 -0
  55. package/dist/compare/index.cjs +5475 -0
  56. package/dist/compare/index.cjs.map +1 -0
  57. package/dist/compare/index.d.cts +114 -0
  58. package/dist/compare/index.d.ts +114 -0
  59. package/dist/compare/index.js +731 -0
  60. package/dist/compare/index.js.map +1 -0
  61. package/dist/core/commands/formatting-commands.cjs +828 -0
  62. package/dist/core/commands/formatting-commands.cjs.map +1 -0
  63. package/dist/core/commands/formatting-commands.d.cts +63 -0
  64. package/dist/core/commands/formatting-commands.d.ts +63 -0
  65. package/dist/core/commands/formatting-commands.js +37 -0
  66. package/dist/core/commands/formatting-commands.js.map +1 -0
  67. package/dist/core/commands/image-commands.cjs +2023 -0
  68. package/dist/core/commands/image-commands.cjs.map +1 -0
  69. package/dist/core/commands/image-commands.d.cts +58 -0
  70. package/dist/core/commands/image-commands.d.ts +58 -0
  71. package/dist/core/commands/image-commands.js +18 -0
  72. package/dist/core/commands/image-commands.js.map +1 -0
  73. package/dist/core/commands/section-layout-commands.cjs +477 -0
  74. package/dist/core/commands/section-layout-commands.cjs.map +1 -0
  75. package/dist/core/commands/section-layout-commands.d.cts +62 -0
  76. package/dist/core/commands/section-layout-commands.d.ts +62 -0
  77. package/dist/core/commands/section-layout-commands.js +21 -0
  78. package/dist/core/commands/section-layout-commands.js.map +1 -0
  79. package/dist/core/commands/style-commands.cjs +214 -0
  80. package/dist/core/commands/style-commands.cjs.map +1 -0
  81. package/dist/core/commands/style-commands.d.cts +13 -0
  82. package/dist/core/commands/style-commands.d.ts +13 -0
  83. package/dist/core/commands/style-commands.js +9 -0
  84. package/dist/core/commands/style-commands.js.map +1 -0
  85. package/dist/core/commands/table-structure-commands.cjs +1883 -0
  86. package/dist/core/commands/table-structure-commands.cjs.map +1 -0
  87. package/dist/core/commands/table-structure-commands.d.cts +59 -0
  88. package/dist/core/commands/table-structure-commands.d.ts +59 -0
  89. package/dist/core/commands/table-structure-commands.js +12 -0
  90. package/dist/core/commands/table-structure-commands.js.map +1 -0
  91. package/dist/core/commands/text-commands.cjs +2391 -0
  92. package/dist/core/commands/text-commands.cjs.map +1 -0
  93. package/dist/core/commands/text-commands.d.cts +24 -0
  94. package/dist/core/commands/text-commands.d.ts +24 -0
  95. package/dist/core/commands/text-commands.js +28 -0
  96. package/dist/core/commands/text-commands.js.map +1 -0
  97. package/dist/core/selection/mapping.cjs +200 -0
  98. package/dist/core/selection/mapping.cjs.map +1 -0
  99. package/dist/core/selection/mapping.d.cts +2 -0
  100. package/dist/core/selection/mapping.d.ts +2 -0
  101. package/dist/core/selection/mapping.js +31 -0
  102. package/dist/core/selection/mapping.js.map +1 -0
  103. package/dist/core/state/editor-state.cjs +2278 -0
  104. package/dist/core/state/editor-state.cjs.map +1 -0
  105. package/dist/core/state/editor-state.d.cts +2 -0
  106. package/dist/core/state/editor-state.d.ts +2 -0
  107. package/dist/core/state/editor-state.js +26 -0
  108. package/dist/core/state/editor-state.js.map +1 -0
  109. package/dist/index.cjs +38553 -0
  110. package/dist/index.cjs.map +1 -0
  111. package/dist/index.d.cts +15 -0
  112. package/dist/index.d.ts +15 -0
  113. package/dist/index.js +7856 -0
  114. package/dist/index.js.map +1 -0
  115. package/dist/io/docx-session.cjs +16236 -0
  116. package/dist/io/docx-session.cjs.map +1 -0
  117. package/dist/io/docx-session.d.cts +21 -0
  118. package/dist/io/docx-session.d.ts +21 -0
  119. package/dist/io/docx-session.js +18 -0
  120. package/dist/io/docx-session.js.map +1 -0
  121. package/dist/legal/index.cjs +3900 -0
  122. package/dist/legal/index.cjs.map +1 -0
  123. package/dist/legal/index.d.cts +86 -0
  124. package/dist/legal/index.d.ts +86 -0
  125. package/dist/legal/index.js +616 -0
  126. package/dist/legal/index.js.map +1 -0
  127. package/dist/public-types-7ZL_94cz.d.ts +1573 -0
  128. package/dist/public-types-CeMaDueh.d.cts +1573 -0
  129. package/dist/public-types.cjs +19 -0
  130. package/dist/public-types.cjs.map +1 -0
  131. package/dist/public-types.d.cts +2 -0
  132. package/dist/public-types.d.ts +2 -0
  133. package/dist/public-types.js +1 -0
  134. package/dist/public-types.js.map +1 -0
  135. package/dist/runtime/document-runtime.cjs +11140 -0
  136. package/dist/runtime/document-runtime.cjs.map +1 -0
  137. package/dist/runtime/document-runtime.d.cts +231 -0
  138. package/dist/runtime/document-runtime.d.ts +231 -0
  139. package/dist/runtime/document-runtime.js +21 -0
  140. package/dist/runtime/document-runtime.js.map +1 -0
  141. package/dist/structural-helpers-CilgOVhh.d.cts +10 -0
  142. package/dist/structural-helpers-q0Gd-eBN.d.ts +10 -0
  143. package/dist/ui-tailwind/editor-surface/search-plugin.cjs +313 -0
  144. package/dist/ui-tailwind/editor-surface/search-plugin.cjs.map +1 -0
  145. package/dist/ui-tailwind/editor-surface/search-plugin.d.cts +67 -0
  146. package/dist/ui-tailwind/editor-surface/search-plugin.d.ts +67 -0
  147. package/dist/ui-tailwind/editor-surface/search-plugin.js +23 -0
  148. package/dist/ui-tailwind/editor-surface/search-plugin.js.map +1 -0
  149. package/dist/ui-tailwind/index.cjs +4833 -0
  150. package/dist/ui-tailwind/index.cjs.map +1 -0
  151. package/dist/ui-tailwind/index.d.cts +617 -0
  152. package/dist/ui-tailwind/index.d.ts +617 -0
  153. package/dist/ui-tailwind/index.js +575 -0
  154. package/dist/ui-tailwind/index.js.map +1 -0
  155. package/package.json +61 -41
  156. package/src/README.md +0 -85
  157. package/src/api/README.md +0 -26
  158. package/src/api/public-types.ts +0 -1421
  159. package/src/api/session-state.ts +0 -60
  160. package/src/compare/diff-engine.ts +0 -623
  161. package/src/compare/export-redlines.ts +0 -280
  162. package/src/compare/index.ts +0 -25
  163. package/src/compare/snapshot.ts +0 -97
  164. package/src/component-inventory.md +0 -99
  165. package/src/core/README.md +0 -10
  166. package/src/core/commands/README.md +0 -3
  167. package/src/core/commands/image-commands.ts +0 -373
  168. package/src/core/commands/index.ts +0 -1757
  169. package/src/core/commands/list-commands.ts +0 -565
  170. package/src/core/commands/paragraph-layout-commands.ts +0 -339
  171. package/src/core/commands/review-commands.ts +0 -108
  172. package/src/core/commands/structural-helpers.ts +0 -309
  173. package/src/core/schema/README.md +0 -3
  174. package/src/core/schema/text-schema.ts +0 -516
  175. package/src/core/search/search-text.ts +0 -357
  176. package/src/core/selection/README.md +0 -3
  177. package/src/core/selection/mapping.ts +0 -289
  178. package/src/core/selection/review-anchors.ts +0 -183
  179. package/src/core/state/README.md +0 -3
  180. package/src/core/state/editor-state.ts +0 -892
  181. package/src/formats/xlsx/io/parse-shared-strings.ts +0 -41
  182. package/src/formats/xlsx/io/parse-sheet.ts +0 -459
  183. package/src/formats/xlsx/io/parse-styles.ts +0 -59
  184. package/src/formats/xlsx/io/parse-workbook.ts +0 -75
  185. package/src/formats/xlsx/io/serialize-shared-strings.ts +0 -72
  186. package/src/formats/xlsx/io/serialize-sheet.ts +0 -333
  187. package/src/formats/xlsx/io/serialize-styles.ts +0 -98
  188. package/src/formats/xlsx/io/serialize-workbook.ts +0 -429
  189. package/src/formats/xlsx/io/xlsx-session.ts +0 -314
  190. package/src/formats/xlsx/model/cell.ts +0 -189
  191. package/src/formats/xlsx/model/sheet.ts +0 -326
  192. package/src/formats/xlsx/model/styles.ts +0 -118
  193. package/src/formats/xlsx/model/workbook.ts +0 -453
  194. package/src/formats/xlsx/runtime/cell-commands.ts +0 -567
  195. package/src/formats/xlsx/runtime/sheet-commands.ts +0 -206
  196. package/src/formats/xlsx/runtime/workbook-runtime.ts +0 -177
  197. package/src/formats/xlsx/runtime/workbook-transaction.ts +0 -822
  198. package/src/index.ts +0 -101
  199. package/src/io/README.md +0 -10
  200. package/src/io/docx-session.ts +0 -2882
  201. package/src/io/export/README.md +0 -3
  202. package/src/io/export/export-session.ts +0 -220
  203. package/src/io/export/minimal-docx.ts +0 -115
  204. package/src/io/export/reattach-preserved-parts.ts +0 -54
  205. package/src/io/export/serialize-comments.ts +0 -947
  206. package/src/io/export/serialize-footnotes.ts +0 -399
  207. package/src/io/export/serialize-headers-footers.ts +0 -372
  208. package/src/io/export/serialize-main-document.ts +0 -1376
  209. package/src/io/export/serialize-numbering.ts +0 -118
  210. package/src/io/export/serialize-revisions.ts +0 -389
  211. package/src/io/export/serialize-runtime-revisions.ts +0 -269
  212. package/src/io/export/serialize-tables.ts +0 -174
  213. package/src/io/export/split-review-boundaries.ts +0 -356
  214. package/src/io/normalize/README.md +0 -3
  215. package/src/io/normalize/normalize-text.ts +0 -639
  216. package/src/io/ooxml/README.md +0 -3
  217. package/src/io/ooxml/highlight-colors.ts +0 -39
  218. package/src/io/ooxml/numbering-sentinels.ts +0 -44
  219. package/src/io/ooxml/parse-comments.ts +0 -846
  220. package/src/io/ooxml/parse-complex-content.ts +0 -287
  221. package/src/io/ooxml/parse-fields.ts +0 -834
  222. package/src/io/ooxml/parse-footnotes.ts +0 -896
  223. package/src/io/ooxml/parse-headers-footers.ts +0 -1169
  224. package/src/io/ooxml/parse-inline-media.ts +0 -461
  225. package/src/io/ooxml/parse-main-document.ts +0 -2877
  226. package/src/io/ooxml/parse-numbering.ts +0 -432
  227. package/src/io/ooxml/parse-revisions.ts +0 -931
  228. package/src/io/ooxml/parse-settings.ts +0 -184
  229. package/src/io/ooxml/parse-shapes.ts +0 -296
  230. package/src/io/ooxml/parse-styles.ts +0 -463
  231. package/src/io/ooxml/parse-tables.ts +0 -618
  232. package/src/io/ooxml/parse-theme.ts +0 -346
  233. package/src/io/ooxml/part-manifest.ts +0 -136
  234. package/src/io/ooxml/revision-boundaries.ts +0 -351
  235. package/src/io/opc/README.md +0 -3
  236. package/src/io/opc/corrupt-package.ts +0 -166
  237. package/src/io/opc/docx-package.ts +0 -74
  238. package/src/io/opc/package-reader.ts +0 -325
  239. package/src/io/opc/package-writer.ts +0 -273
  240. package/src/io/source-package-provenance.ts +0 -241
  241. package/src/legal/cross-references.ts +0 -414
  242. package/src/legal/defined-terms.ts +0 -203
  243. package/src/legal/index.ts +0 -32
  244. package/src/legal/signature-blocks.ts +0 -259
  245. package/src/model/README.md +0 -3
  246. package/src/model/canonical-document.ts +0 -2632
  247. package/src/model/cds-1.0.0.ts +0 -212
  248. package/src/model/snapshot.ts +0 -649
  249. package/src/preservation/README.md +0 -3
  250. package/src/preservation/markup-compatibility.ts +0 -48
  251. package/src/preservation/opaque-fragment-store.ts +0 -89
  252. package/src/preservation/opaque-region.ts +0 -233
  253. package/src/preservation/package-preservation.ts +0 -113
  254. package/src/preservation/preserved-part-manifest.ts +0 -56
  255. package/src/preservation/relationship-retention.ts +0 -57
  256. package/src/preservation/store.ts +0 -185
  257. package/src/review/README.md +0 -16
  258. package/src/review/store/README.md +0 -3
  259. package/src/review/store/comment-anchors.ts +0 -70
  260. package/src/review/store/comment-remapping.ts +0 -154
  261. package/src/review/store/comment-store.ts +0 -331
  262. package/src/review/store/comment-thread.ts +0 -109
  263. package/src/review/store/revision-actions.ts +0 -394
  264. package/src/review/store/revision-store.ts +0 -312
  265. package/src/review/store/revision-types.ts +0 -171
  266. package/src/review/store/runtime-comment-store.ts +0 -43
  267. package/src/runtime/README.md +0 -3
  268. package/src/runtime/ai-action-policy.ts +0 -764
  269. package/src/runtime/document-layout.ts +0 -332
  270. package/src/runtime/document-navigation.ts +0 -603
  271. package/src/runtime/document-runtime.ts +0 -3159
  272. package/src/runtime/document-search.ts +0 -145
  273. package/src/runtime/numbering-prefix.ts +0 -216
  274. package/src/runtime/page-layout-estimation.ts +0 -212
  275. package/src/runtime/read-only-diagnostics-runtime.ts +0 -241
  276. package/src/runtime/review-runtime.ts +0 -44
  277. package/src/runtime/revision-runtime.ts +0 -107
  278. package/src/runtime/session-capabilities.ts +0 -192
  279. package/src/runtime/story-context.ts +0 -164
  280. package/src/runtime/story-targeting.ts +0 -162
  281. package/src/runtime/surface-projection.ts +0 -1357
  282. package/src/runtime/table-commands.ts +0 -173
  283. package/src/runtime/table-schema.ts +0 -309
  284. package/src/runtime/view-state.ts +0 -477
  285. package/src/runtime/virtualized-rendering.ts +0 -258
  286. package/src/runtime/workflow-markup.ts +0 -353
  287. package/src/ui/README.md +0 -30
  288. package/src/ui/WordReviewEditor.tsx +0 -4086
  289. package/src/ui/browser-export.ts +0 -52
  290. package/src/ui/comments/README.md +0 -3
  291. package/src/ui/compatibility/README.md +0 -3
  292. package/src/ui/editor-command-bag.ts +0 -120
  293. package/src/ui/editor-runtime-boundary.ts +0 -1457
  294. package/src/ui/editor-shell-view.tsx +0 -142
  295. package/src/ui/editor-surface/README.md +0 -3
  296. package/src/ui/editor-surface-controller.tsx +0 -61
  297. package/src/ui/headless/comment-decoration-model.ts +0 -124
  298. package/src/ui/headless/preserve-editor-selection.ts +0 -5
  299. package/src/ui/headless/revision-decoration-model.ts +0 -128
  300. package/src/ui/headless/selection-helpers.ts +0 -54
  301. package/src/ui/headless/selection-toolbar-model.ts +0 -34
  302. package/src/ui/headless/use-editor-keyboard.ts +0 -103
  303. package/src/ui/review/README.md +0 -3
  304. package/src/ui/runtime-snapshot-selectors.ts +0 -197
  305. package/src/ui/shared/revision-filters.ts +0 -31
  306. package/src/ui/status/README.md +0 -3
  307. package/src/ui/theme/README.md +0 -3
  308. package/src/ui/toolbar/README.md +0 -3
  309. package/src/ui/workflow-surface-blocked-rails.ts +0 -94
  310. package/src/ui-tailwind/chrome/tw-alert-banner.tsx +0 -64
  311. package/src/ui-tailwind/chrome/tw-image-context-toolbar.tsx +0 -129
  312. package/src/ui-tailwind/chrome/tw-layout-panel.tsx +0 -114
  313. package/src/ui-tailwind/chrome/tw-object-context-toolbar.tsx +0 -34
  314. package/src/ui-tailwind/chrome/tw-page-ruler.tsx +0 -386
  315. package/src/ui-tailwind/chrome/tw-selection-toolbar.tsx +0 -186
  316. package/src/ui-tailwind/chrome/tw-suggestion-card.tsx +0 -139
  317. package/src/ui-tailwind/chrome/tw-table-context-toolbar.tsx +0 -128
  318. package/src/ui-tailwind/chrome/tw-unsaved-modal.tsx +0 -58
  319. package/src/ui-tailwind/chrome/use-before-unload.ts +0 -20
  320. package/src/ui-tailwind/editor-surface/perf-probe.ts +0 -179
  321. package/src/ui-tailwind/editor-surface/pm-command-bridge.ts +0 -184
  322. package/src/ui-tailwind/editor-surface/pm-contextual-ui.ts +0 -31
  323. package/src/ui-tailwind/editor-surface/pm-decorations.ts +0 -427
  324. package/src/ui-tailwind/editor-surface/pm-position-map.ts +0 -123
  325. package/src/ui-tailwind/editor-surface/pm-schema.ts +0 -876
  326. package/src/ui-tailwind/editor-surface/pm-state-from-snapshot.ts +0 -504
  327. package/src/ui-tailwind/editor-surface/search-plugin.ts +0 -168
  328. package/src/ui-tailwind/editor-surface/surface-build-keys.ts +0 -61
  329. package/src/ui-tailwind/editor-surface/tw-caret.tsx +0 -12
  330. package/src/ui-tailwind/editor-surface/tw-editor-surface.tsx +0 -150
  331. package/src/ui-tailwind/editor-surface/tw-inline-token.tsx +0 -129
  332. package/src/ui-tailwind/editor-surface/tw-opaque-block.tsx +0 -58
  333. package/src/ui-tailwind/editor-surface/tw-paragraph-block.tsx +0 -151
  334. package/src/ui-tailwind/editor-surface/tw-prosemirror-surface.tsx +0 -944
  335. package/src/ui-tailwind/editor-surface/tw-segment-view.tsx +0 -111
  336. package/src/ui-tailwind/editor-surface/tw-table-node-view.tsx +0 -436
  337. package/src/ui-tailwind/index.ts +0 -62
  338. package/src/ui-tailwind/page-chrome-model.ts +0 -27
  339. package/src/ui-tailwind/review/tw-comment-sidebar.tsx +0 -406
  340. package/src/ui-tailwind/review/tw-health-panel.tsx +0 -149
  341. package/src/ui-tailwind/review/tw-review-rail.tsx +0 -120
  342. package/src/ui-tailwind/review/tw-revision-sidebar.tsx +0 -164
  343. package/src/ui-tailwind/status/tw-status-bar.tsx +0 -61
  344. package/src/ui-tailwind/toolbar/tw-toolbar-icon-button.tsx +0 -52
  345. package/src/ui-tailwind/toolbar/tw-toolbar.tsx +0 -1064
  346. package/src/ui-tailwind/tw-review-workspace.tsx +0 -1417
  347. package/src/validation/README.md +0 -3
  348. package/src/validation/compatibility-engine.ts +0 -634
  349. package/src/validation/compatibility-report.ts +0 -161
  350. package/src/validation/diagnostics.ts +0 -204
  351. package/src/validation/docx-comment-proof.ts +0 -707
  352. package/src/validation/import-diagnostics.ts +0 -128
  353. package/src/validation/low-priority-word-surfaces.ts +0 -373
  354. /package/{src → dist}/ui-tailwind/theme/editor-theme.css +0 -0
@@ -1,4086 +0,0 @@
1
- import React, {
2
- forwardRef,
3
- type FocusEvent,
4
- useCallback,
5
- useEffect,
6
- useImperativeHandle,
7
- useMemo,
8
- useRef,
9
- useState,
10
- } from "react";
11
-
12
- import type {
13
- AutosaveState,
14
- CompatibilityReport,
15
- DocumentNavigationSnapshot,
16
- EditorAnchorProjection,
17
- EditorDatastoreAdapter,
18
- EditorHostAdapter,
19
- EditorSessionState,
20
- ExportResult,
21
- EditorError,
22
- EditorStoryTarget,
23
- EditorViewStateSnapshot,
24
- EditorWarning,
25
- ExportDocxOptions,
26
- FieldSnapshot,
27
- FormattingAlignment,
28
- FormattingStateSnapshot,
29
- HeaderFooterLinkPatch,
30
- InteractionGuardSnapshot,
31
- InsertImageOptions,
32
- InsertTableOptions,
33
- PageLayoutSnapshot,
34
- PersistedEditorSnapshot,
35
- RuntimeRenderSnapshot,
36
- SectionBreakType,
37
- SectionLayoutPatch,
38
- SectionPageNumberingPatch,
39
- SearchOptions,
40
- SearchResultSnapshot,
41
- SelectionSnapshot as PublicSelectionSnapshot,
42
- StyleCatalogSnapshot,
43
- SurfaceBlockSnapshot,
44
- TrackedChangeEntrySnapshot,
45
- TocRefreshResult,
46
- UpdateFieldsResult,
47
- ViewMode as EditorViewMode,
48
- WorkflowBlockedCommandReason,
49
- WorkflowMarkupSnapshot,
50
- WorkflowScopeSnapshot,
51
- WordReviewEditorChromeVisibility,
52
- WordReviewEditorEvent,
53
- WordReviewEditorProps,
54
- WordReviewEditorRef,
55
- WorkspaceMode,
56
- ZoomLevel,
57
- } from "../api/public-types";
58
- import {
59
- editorSessionStateFromPersistedSnapshot,
60
- persistedSnapshotFromEditorSessionState,
61
- } from "../api/session-state.ts";
62
- import {
63
- createDetachedAnchor,
64
- createNodeAnchor,
65
- createRangeAnchor,
66
- storyTargetsEqual,
67
- type TransactionMapping,
68
- } from "../core/selection/mapping.ts";
69
- import {
70
- applyFormattingOperationToDocument,
71
- getFormattingStateFromRenderSnapshot,
72
- } from "../core/commands/formatting-commands.ts";
73
- import {
74
- applyParagraphStyleToDocument,
75
- applyTableStyleToDocument,
76
- } from "../core/commands/style-commands.ts";
77
- import {
78
- continueNumbering as continueListNumbering,
79
- backspaceAtListStart,
80
- indentListItems,
81
- outdentListItems,
82
- restartNumbering as restartListNumbering,
83
- splitListParagraph,
84
- } from "../core/commands/list-commands.ts";
85
- import {
86
- resolveActiveParagraphIndex,
87
- setActiveParagraphIndentation,
88
- setActiveParagraphTabStops,
89
- } from "../core/commands/paragraph-layout-commands.ts";
90
- import {
91
- deleteSectionBreakAtSectionIndex,
92
- insertSectionBreakAfterSectionIndex,
93
- setHeaderFooterLinkAtSectionIndex,
94
- setSectionPageNumberingAtSectionIndex,
95
- updateSectionLayoutAtSectionIndex,
96
- } from "../core/commands/section-layout-commands.ts";
97
- import {
98
- insertImage as insertImageInDocument,
99
- resizeImage as resizeImageInCatalog,
100
- repositionFloatingImage as repositionFloatingImageInDocument,
101
- } from "../core/commands/image-commands.ts";
102
- import {
103
- applyTableStructureOperation,
104
- } from "../core/commands/table-structure-commands.ts";
105
- import {
106
- deleteSelectionOrBackward,
107
- deleteSelectionOrForward,
108
- insertHardBreak as insertHardBreakInDocument,
109
- insertPageBreak as insertPageBreakInDocument,
110
- insertTab as insertTabInDocument,
111
- insertText as insertTextInDocument,
112
- insertTable as insertTableInDocument,
113
- splitParagraph as splitParagraphInDocument,
114
- } from "../core/commands/text-commands.ts";
115
- import { type SelectionSnapshot as InternalSelectionSnapshot } from "../core/state/editor-state.ts";
116
- import {
117
- getStoryBlocks,
118
- replaceStoryBlocks,
119
- } from "../runtime/story-targeting.ts";
120
- import {
121
- decodePersistedSourcePackageBytes,
122
- hasValidPersistedSourcePackageDigest,
123
- } from "../io/source-package-provenance.ts";
124
- import { readOpcPackage } from "../io/opc/package-reader.ts";
125
- import { deriveCapabilities } from "../runtime/session-capabilities";
126
- import { searchDocument } from "../runtime/document-search.ts";
127
- import {
128
- createEditorViewStateSnapshot,
129
- createViewState,
130
- } from "../runtime/view-state.ts";
131
- import {
132
- type TwProseMirrorSurfaceRef,
133
- } from "../ui-tailwind/editor-surface/tw-prosemirror-surface";
134
- import type { MediaPreviewDescriptor } from "../ui-tailwind/editor-surface/pm-state-from-snapshot";
135
- import {
136
- incrementInvalidationCounter,
137
- recordPerfSample,
138
- } from "../ui-tailwind/editor-surface/perf-probe.ts";
139
- import type { ReviewRailTab } from "../ui-tailwind/review/tw-review-rail";
140
- import {
141
- selectMetaSlice,
142
- selectReviewSlice,
143
- selectStatusSlice,
144
- selectSurfaceSlice,
145
- selectToolbarSlice,
146
- selectViewSlice,
147
- shallowEqualRecord,
148
- useRuntimeSnapshotSlice,
149
- useRuntimeValue,
150
- } from "./runtime-snapshot-selectors.ts";
151
- import type { MarkupDisplay } from "./headless/comment-decoration-model";
152
- import type {
153
- SelectionToolbarAnchor,
154
- SelectionToolbarModel,
155
- SuggestionCardModel,
156
- } from "./headless/selection-toolbar-model";
157
- import { type EditorCommandBag, useCommandBag } from "./editor-command-bag.ts";
158
- import { deriveVisibleWorkflowBlockedRails } from "./workflow-surface-blocked-rails.ts";
159
- import {
160
- type WordReviewEditorRuntime,
161
- persistAndExport as persistAndExportFromBoundary,
162
- persistSession as persistSessionFromBoundary,
163
- rejectExportWhileLoading as rejectExportWhileLoadingFromBoundary,
164
- useEditorRuntimeBoundary,
165
- } from "./editor-runtime-boundary.ts";
166
- import {
167
- downloadExportResult,
168
- withExportDelivery,
169
- } from "./browser-export";
170
- import { EditorShellView } from "./editor-shell-view.tsx";
171
- import { EditorSurfaceController } from "./editor-surface-controller.tsx";
172
-
173
- export {
174
- __createFallbackRuntime,
175
- __resolveWordReviewEditorSource,
176
- } from "./editor-runtime-boundary.ts";
177
-
178
- const VISUALLY_HIDDEN_STYLES: React.CSSProperties = {
179
- position: "absolute",
180
- width: "1px",
181
- height: "1px",
182
- padding: 0,
183
- margin: "-1px",
184
- overflow: "hidden",
185
- clip: "rect(0 0 0 0)",
186
- whiteSpace: "nowrap",
187
- border: 0,
188
- };
189
-
190
- const BROWSER_SAFE_PREVIEW_TYPES = new Set([
191
- "image/png",
192
- "image/jpeg",
193
- "image/jpg",
194
- "image/gif",
195
- "image/webp",
196
- "image/bmp",
197
- ]);
198
-
199
- const ACCESSIBLE_REGION_ORDER = [
200
- "toolbar",
201
- "document",
202
- "review-rail",
203
- "status",
204
- ] as const;
205
-
206
- type AccessibleRegionId = (typeof ACCESSIBLE_REGION_ORDER)[number];
207
-
208
- type SelectionToolbarDismissReason =
209
- | "blur"
210
- | "chrome-action"
211
- | "comment-action"
212
- | "escape";
213
-
214
- export function __createWordReviewEditorRefBridge(
215
- runtime: WordReviewEditorRuntime,
216
- mountedSurface?: TwProseMirrorSurfaceRef | null,
217
- ): WordReviewEditorRef {
218
- return {
219
- focus: () => runtime.focus(),
220
- blur: () => runtime.blur(),
221
- undo: () => runtime.undo(),
222
- redo: () => runtime.redo(),
223
- replaceText: (text, target) => runtime.replaceText(text, target),
224
- addComment: (params) => runtime.addComment(params),
225
- openComment: (commentId) => runtime.openComment(commentId),
226
- resolveComment: (commentId) => runtime.resolveComment(commentId),
227
- reopenComment: (commentId) => runtime.reopenComment(commentId),
228
- addCommentReply: (commentId, body) => runtime.addCommentReply(commentId, body),
229
- editCommentBody: (commentId, body) => runtime.editCommentBody(commentId, body),
230
- deleteComment: (commentId) => {
231
- applyRuntimeDeleteComment(runtime, commentId);
232
- },
233
- acceptChange: (changeId) => runtime.acceptChange(changeId),
234
- rejectChange: (changeId) => runtime.rejectChange(changeId),
235
- acceptAllChanges: () => runtime.acceptAllChanges(),
236
- rejectAllChanges: () => runtime.rejectAllChanges(),
237
- exportDocx: (options) => runtime.exportDocx(options),
238
- getSessionState: () => runtime.getSessionState(),
239
- getSnapshot: () => runtime.getPersistedSnapshot(),
240
- getRenderSnapshot: () => clonePublicValue(runtime.getRenderSnapshot()),
241
- getCompatibilityReport: () => runtime.getCompatibilityReport(),
242
- getWarnings: () => runtime.getWarnings(),
243
- getCommentSidebarSnapshot: () =>
244
- clonePublicValue(runtime.getRenderSnapshot().comments),
245
- getTrackedChangesSnapshot: () =>
246
- clonePublicValue(runtime.getRenderSnapshot().trackedChanges),
247
- getComments: () => clonePublicValue(runtime.getRenderSnapshot().comments),
248
- getTrackedChanges: () =>
249
- clonePublicValue(runtime.getRenderSnapshot().trackedChanges),
250
- isDirty: () => runtime.getRenderSnapshot().isDirty,
251
- getFormattingState: () => getFormattingStateFromRenderSnapshot(runtime.getRenderSnapshot()),
252
- getStyleCatalog: () => getRuntimeStyleCatalog(runtime),
253
- toggleBold: () => {
254
- applyRuntimeFormattingOperation(runtime, { type: "toggle", mark: "bold" });
255
- },
256
- toggleItalic: () => {
257
- applyRuntimeFormattingOperation(runtime, { type: "toggle", mark: "italic" });
258
- },
259
- toggleUnderline: () => {
260
- applyRuntimeFormattingOperation(runtime, { type: "toggle", mark: "underline" });
261
- },
262
- toggleStrikethrough: () => {
263
- applyRuntimeFormattingOperation(runtime, {
264
- type: "toggle",
265
- mark: "strikethrough",
266
- });
267
- },
268
- toggleSuperscript: () => {
269
- applyRuntimeFormattingOperation(runtime, {
270
- type: "toggle",
271
- mark: "superscript",
272
- });
273
- },
274
- toggleSubscript: () => {
275
- applyRuntimeFormattingOperation(runtime, { type: "toggle", mark: "subscript" });
276
- },
277
- setFontFamily: (fontFamily) => {
278
- applyRuntimeFormattingOperation(runtime, {
279
- type: "set-font-family",
280
- fontFamily,
281
- });
282
- },
283
- setFontSize: (size) => {
284
- applyRuntimeFormattingOperation(runtime, { type: "set-font-size", size });
285
- },
286
- setTextColor: (color) => {
287
- applyRuntimeFormattingOperation(runtime, { type: "set-text-color", color });
288
- },
289
- setHighlightColor: (color) => {
290
- applyRuntimeFormattingOperation(runtime, {
291
- type: "set-highlight-color",
292
- color,
293
- });
294
- },
295
- setAlignment: (alignment) => {
296
- applyRuntimeFormattingOperation(runtime, {
297
- type: "set-alignment",
298
- alignment,
299
- });
300
- },
301
- setParagraphStyle: (styleId) => {
302
- applyRuntimeParagraphStyle(runtime, styleId);
303
- },
304
- setTableStyle: (styleId) => {
305
- applyRuntimeTableStyle(runtime, styleId);
306
- },
307
- indent: () => {
308
- applyRuntimeFormattingOperation(runtime, { type: "indent" });
309
- },
310
- outdent: () => {
311
- applyRuntimeFormattingOperation(runtime, { type: "outdent" });
312
- },
313
- insertPageBreak: () => {
314
- applyRuntimeInsertPageBreak(runtime);
315
- },
316
- insertTable: (options) => {
317
- applyRuntimeInsertTable(runtime, options);
318
- },
319
- insertImage: (options) => {
320
- applyRuntimeInsertImage(runtime, options);
321
- },
322
- addRowBefore: () => {
323
- applyRuntimeTableStructureOperation(runtime, mountedSurface ?? null, {
324
- type: "add-row-before",
325
- });
326
- },
327
- addRowAfter: () => {
328
- applyRuntimeTableStructureOperation(runtime, mountedSurface ?? null, {
329
- type: "add-row-after",
330
- });
331
- },
332
- addColumnBefore: () => {
333
- applyRuntimeTableStructureOperation(runtime, mountedSurface ?? null, {
334
- type: "add-column-before",
335
- });
336
- },
337
- addColumnAfter: () => {
338
- applyRuntimeTableStructureOperation(runtime, mountedSurface ?? null, {
339
- type: "add-column-after",
340
- });
341
- },
342
- deleteRow: () => {
343
- applyRuntimeTableStructureOperation(runtime, mountedSurface ?? null, {
344
- type: "delete-row",
345
- });
346
- },
347
- deleteColumn: () => {
348
- applyRuntimeTableStructureOperation(runtime, mountedSurface ?? null, {
349
- type: "delete-column",
350
- });
351
- },
352
- deleteTable: () => {
353
- applyRuntimeTableStructureOperation(runtime, mountedSurface ?? null, {
354
- type: "delete-table",
355
- });
356
- },
357
- mergeCells: () => {
358
- applyRuntimeTableStructureOperation(runtime, mountedSurface ?? null, {
359
- type: "merge-cells",
360
- });
361
- },
362
- splitCell: () => {
363
- applyRuntimeTableStructureOperation(runtime, mountedSurface ?? null, {
364
- type: "split-cell",
365
- });
366
- },
367
- setCellBackground: (color) => {
368
- applyRuntimeTableStructureOperation(runtime, mountedSurface ?? null, {
369
- type: "set-cell-background",
370
- color,
371
- });
372
- },
373
- search: (query, options) =>
374
- searchRuntimeDocument(runtime, mountedSurface ?? null, query, options),
375
- clearSearch: () => {
376
- mountedSurface?.clearSearch();
377
- },
378
- setSelection: (selection) => {
379
- applyRuntimeSelection(
380
- runtime,
381
- normalizeRequestedSelection(runtime.getRenderSnapshot(), selection),
382
- );
383
- },
384
- scrollToRevision: (revisionId: string) => {
385
- const revision = runtime.getRenderSnapshot().trackedChanges.revisions.find(
386
- (r) => r.revisionId === revisionId,
387
- );
388
- if (!revision || revision.anchor.kind === "detached") return;
389
- applyRuntimeSelection(runtime, createSelectionFromAnchor(revision.anchor));
390
- },
391
- scrollToComment: (commentId: string) => {
392
- const comment = runtime.getRenderSnapshot().comments.threads.find(
393
- (t) => t.commentId === commentId,
394
- );
395
- if (!comment || comment.anchor.kind === "detached") return;
396
- applyRuntimeSelection(runtime, createSelectionFromAnchor(comment.anchor));
397
- },
398
- openStory: (target: EditorStoryTarget) => {
399
- runtime.openStory(target);
400
- },
401
- closeStory: () => {
402
- runtime.closeStory();
403
- },
404
- getPageLayoutSnapshot: () => {
405
- return clonePublicValue(runtime.getPageLayoutSnapshot());
406
- },
407
- getDocumentNavigationSnapshot: () => {
408
- return clonePublicValue(runtime.getDocumentNavigationSnapshot());
409
- },
410
- getFieldSnapshot: () => {
411
- return clonePublicValue(runtime.getFieldSnapshot());
412
- },
413
- updateFields: (options) => {
414
- return runtime.updateFields(options);
415
- },
416
- updateTableOfContents: (options) => {
417
- return runtime.updateTableOfContents(options);
418
- },
419
- getViewState: () => {
420
- return clonePublicValue(runtime.getViewState());
421
- },
422
- setDocumentMode: (mode) => {
423
- runtime.setDocumentMode(mode);
424
- },
425
- getProtectionSnapshot: () => {
426
- return clonePublicValue(runtime.getProtectionSnapshot());
427
- },
428
- setWorkspaceMode: (mode) => {
429
- runtime.setWorkspaceMode(mode);
430
- },
431
- setZoom: (level) => {
432
- runtime.setZoom(level);
433
- },
434
- insertSectionBreak: (type, options) => {
435
- applyRuntimeInsertSectionBreak(runtime, type, options);
436
- },
437
- deleteSectionBreak: (sectionIndex) => {
438
- applyRuntimeDeleteSectionBreak(runtime, sectionIndex);
439
- },
440
- updateSectionLayout: (sectionIndex, patch) => {
441
- applyRuntimeUpdateSectionLayout(runtime, sectionIndex, patch);
442
- },
443
- setSectionPageNumbering: (sectionIndex, patch) => {
444
- applyRuntimeSetSectionPageNumbering(runtime, sectionIndex, patch);
445
- },
446
- setHeaderFooterLink: (sectionIndex, params) => {
447
- applyRuntimeSetHeaderFooterLink(runtime, sectionIndex, params);
448
- },
449
- setImageLayout: (mediaId, dimensions) => {
450
- applyRuntimeImageResize(runtime, mediaId, dimensions);
451
- },
452
- setImageFrame: (mediaId, offsets) => {
453
- applyRuntimeImageReposition(runtime, mediaId, offsets);
454
- },
455
- setWorkflowOverlay: (overlay) => {
456
- runtime.setWorkflowOverlay(clonePublicValue(overlay));
457
- },
458
- clearWorkflowOverlay: () => {
459
- runtime.clearWorkflowOverlay();
460
- },
461
- getWorkflowScopeSnapshot: () => {
462
- return clonePublicValue(runtime.getWorkflowScopeSnapshot());
463
- },
464
- getInteractionGuardSnapshot: () => {
465
- return clonePublicValue(runtime.getInteractionGuardSnapshot());
466
- },
467
- getWorkflowMarkupSnapshot: () => {
468
- return clonePublicValue(runtime.getWorkflowMarkupSnapshot());
469
- },
470
- setHostAnnotationOverlay: (overlay) => {
471
- runtime.setHostAnnotationOverlay(clonePublicValue(overlay));
472
- },
473
- clearHostAnnotationOverlay: () => {
474
- runtime.clearHostAnnotationOverlay();
475
- },
476
- getHostAnnotationSnapshot: () => {
477
- return clonePublicValue(runtime.getHostAnnotationSnapshot());
478
- },
479
- getWorkflowCandidateRanges: (options) => {
480
- return clonePublicValue(runtime.getWorkflowCandidateRanges(options));
481
- },
482
- replaceWorkflowMarkupText: (markupId, text) => {
483
- runtime.replaceWorkflowMarkupText(markupId, text);
484
- },
485
- };
486
- }
487
-
488
- export function __applyRuntimeTextCommand(
489
- runtime: WordReviewEditorRuntime,
490
- command:
491
- | { type: "insert-text"; text: string }
492
- | { type: "delete-backward" }
493
- | { type: "delete-forward" }
494
- | { type: "insert-tab" }
495
- | { type: "outdent-tab" }
496
- | { type: "insert-hard-break" }
497
- | { type: "split-paragraph" },
498
- ): void {
499
- applyRuntimeTextCommand(runtime, command);
500
- }
501
-
502
- export const WordReviewEditor = forwardRef<WordReviewEditorRef, WordReviewEditorProps>(
503
- function WordReviewEditor(props, ref) {
504
- const {
505
- currentUser,
506
- hostAdapter,
507
- datastore,
508
- documentId,
509
- externalDocSource,
510
- externalDocumentRevision,
511
- initialDocx,
512
- loadRevision,
513
- loadSourcePolicy = "prefer-saved-state",
514
- initialSessionState,
515
- initialSnapshot,
516
- initialSourceLabel,
517
- markupDisplay,
518
- onError,
519
- onEvent,
520
- onWarning,
521
- readOnly = false,
522
- reviewMode = "review",
523
- suggestionsEnabled = false,
524
- showReviewPanel = true,
525
- chromeVisibility,
526
- } = props;
527
-
528
- const [activeRailTab, setActiveRailTab] = useState<ReviewRailTab>("comments");
529
- const [showTrackedChanges, setShowTrackedChanges] = useState(false);
530
- const [activeRevisionId, setActiveRevisionId] = useState<string | undefined>();
531
- const [suppressedSuggestionRevisionId, setSuppressedSuggestionRevisionId] = useState<string | null>(null);
532
- const [selectionToolbarAnchor, setSelectionToolbarAnchor] = useState<SelectionToolbarAnchor | null>(null);
533
- const [selectionToolbarDismissedKey, setSelectionToolbarDismissedKey] = useState<string | null>(null);
534
- const [selectionToolbarFocusWithin, setSelectionToolbarFocusWithin] = useState(false);
535
- const surfaceRef = useRef<TwProseMirrorSurfaceRef | null>(null);
536
- const selectionToolbarElementRef = useRef<HTMLDivElement | null>(null);
537
- const shellRef = useRef<HTMLDivElement | null>(null);
538
- const lastSelectionToolbarKeyRef = useRef<string | null>(null);
539
- const lastAnnouncedErrorIdRef = useRef<string | null>(null);
540
- const {
541
- runtime,
542
- loadError,
543
- activeRuntime,
544
- fallbackSnapshot,
545
- loadingSessionState,
546
- loadingViewState,
547
- loadingNavigation,
548
- hostAdapterRef,
549
- datastoreRef,
550
- onEventRef,
551
- onWarningRef,
552
- onErrorRef,
553
- autosaveTimerRef,
554
- lastSavedRevisionTokenRef,
555
- runtimeViewStateSeedRef,
556
- } = useEditorRuntimeBoundary(props);
557
- const metaSlice = useRuntimeSnapshotSlice(
558
- runtime,
559
- fallbackSnapshot,
560
- selectMetaSlice,
561
- shallowEqualRecord,
562
- );
563
- const toolbarSlice = useRuntimeSnapshotSlice(
564
- runtime,
565
- fallbackSnapshot,
566
- selectToolbarSlice,
567
- shallowEqualRecord,
568
- );
569
- const surfaceSlice = useRuntimeSnapshotSlice(
570
- runtime,
571
- fallbackSnapshot,
572
- selectSurfaceSlice,
573
- shallowEqualRecord,
574
- );
575
- const reviewSlice = useRuntimeSnapshotSlice(
576
- runtime,
577
- fallbackSnapshot,
578
- selectReviewSlice,
579
- shallowEqualRecord,
580
- );
581
- const viewSlice = useRuntimeSnapshotSlice(
582
- runtime,
583
- fallbackSnapshot,
584
- selectViewSlice,
585
- shallowEqualRecord,
586
- );
587
- const statusSlice = useRuntimeSnapshotSlice(
588
- runtime,
589
- fallbackSnapshot,
590
- selectStatusSlice,
591
- shallowEqualRecord,
592
- );
593
- const snapshot = useMemo(
594
- () => ({
595
- documentId: metaSlice.documentId,
596
- sessionId: metaSlice.sessionId,
597
- sourceLabel: metaSlice.sourceLabel,
598
- revisionToken: surfaceSlice.revisionToken,
599
- isReady: toolbarSlice.isReady,
600
- isDirty: statusSlice.isDirty,
601
- readOnly: toolbarSlice.readOnly,
602
- documentMode: viewSlice.documentMode,
603
- selection: surfaceSlice.selection,
604
- activeStory: viewSlice.activeStory,
605
- pageLayout: viewSlice.pageLayout,
606
- documentStats: statusSlice.documentStats,
607
- comments: reviewSlice.comments,
608
- trackedChanges: reviewSlice.trackedChanges,
609
- compatibility: reviewSlice.compatibility,
610
- warnings: statusSlice.warnings,
611
- fatalError: statusSlice.fatalError,
612
- commandState: toolbarSlice.commandState,
613
- surface: surfaceSlice.surface,
614
- protectionSnapshot: statusSlice.protectionSnapshot,
615
- }),
616
- [
617
- metaSlice.documentId,
618
- metaSlice.sessionId,
619
- metaSlice.sourceLabel,
620
- surfaceSlice.revisionToken,
621
- surfaceSlice.selection,
622
- surfaceSlice.surface,
623
- toolbarSlice.isReady,
624
- toolbarSlice.readOnly,
625
- toolbarSlice.commandState,
626
- statusSlice.isDirty,
627
- statusSlice.documentStats,
628
- statusSlice.warnings,
629
- statusSlice.fatalError,
630
- statusSlice.protectionSnapshot,
631
- reviewSlice.comments,
632
- reviewSlice.trackedChanges,
633
- reviewSlice.compatibility,
634
- viewSlice.documentMode,
635
- viewSlice.activeStory,
636
- viewSlice.pageLayout,
637
- ],
638
- );
639
- const viewState = useRuntimeValue(
640
- runtime
641
- ? {
642
- subscribe: (listener) => runtime.subscribe(listener),
643
- getValue: () => runtime.getViewState(),
644
- }
645
- : null,
646
- loadingViewState,
647
- );
648
- const isPageWorkspace = viewState.workspaceMode === "page";
649
- const liveMarkupDisplay = __resolveLiveMarkupDisplay(markupDisplay, isPageWorkspace);
650
- const documentNavigation = useRuntimeValue(
651
- runtime
652
- ? {
653
- subscribe: (listener) => runtime.subscribe(listener),
654
- getValue: () => runtime.getDocumentNavigationSnapshot(),
655
- }
656
- : null,
657
- loadingNavigation,
658
- );
659
- const workflowScopeSnapshot = useRuntimeValue(
660
- runtime
661
- ? {
662
- subscribe: (listener) => runtime.subscribe(listener),
663
- getValue: () => runtime.getWorkflowScopeSnapshot(),
664
- }
665
- : null,
666
- null,
667
- workflowScopeSnapshotsEqual,
668
- );
669
- const interactionGuardSnapshot = useRuntimeValue(
670
- runtime
671
- ? {
672
- subscribe: (listener) => runtime.subscribe(listener),
673
- getValue: () => runtime.getInteractionGuardSnapshot(),
674
- }
675
- : null,
676
- { effectiveMode: "edit", blockedReasons: [] } satisfies InteractionGuardSnapshot,
677
- interactionGuardSnapshotsEqual,
678
- );
679
- const workflowMarkupSnapshot = useMemo(
680
- () => (runtime ? runtime.getWorkflowMarkupSnapshot() : null),
681
- [runtime, snapshot.revisionToken],
682
- );
683
- const workflowBlockedRails = useMemo(
684
- () => deriveVisibleWorkflowBlockedRails(snapshot.surface, workflowMarkupSnapshot),
685
- [snapshot.surface, workflowMarkupSnapshot],
686
- );
687
- const canonicalDocument = useMemo(
688
- () => (runtime ? runtime.getCanonicalDocument() : loadingSessionState.canonicalDocument),
689
- [loadingSessionState.canonicalDocument, runtime, snapshot.revisionToken],
690
- );
691
- const effectiveViewMode = deriveEditorViewMode(snapshot.readOnly, reviewMode);
692
-
693
- useEffect(() => {
694
- activeRuntime.setViewMode(effectiveViewMode);
695
- }, [activeRuntime, effectiveViewMode]);
696
-
697
- useEffect(() => {
698
- activeRuntime.setDocumentMode(suggestionsEnabled ? "suggesting" : "editing");
699
- }, [activeRuntime, suggestionsEnabled]);
700
-
701
- useEffect(() => {
702
- runtimeViewStateSeedRef.current = {
703
- workspaceMode: viewState.workspaceMode,
704
- zoomLevel: viewState.zoomLevel,
705
- };
706
- }, [viewState.workspaceMode, viewState.zoomLevel]);
707
-
708
- useEffect(() => {
709
- recordPerfSample("shell.render");
710
- incrementInvalidationCounter("shell.rerenders");
711
- }, [snapshot.revisionToken, snapshot.selection, viewState, documentNavigation]);
712
-
713
- useImperativeHandle(
714
- ref,
715
- () => ({
716
- focus: () => activeRuntime.focus(),
717
- blur: () => activeRuntime.blur(),
718
- undo: () => activeRuntime.undo(),
719
- redo: () => activeRuntime.redo(),
720
- replaceText: (text, target) => activeRuntime.replaceText(text, target),
721
- addComment: (params) =>
722
- activeRuntime.addComment({
723
- ...params,
724
- authorId: params.authorId ?? currentUser.userId,
725
- }),
726
- openComment: (commentId) => activeRuntime.openComment(commentId),
727
- resolveComment: (commentId) => activeRuntime.resolveComment(commentId),
728
- reopenComment: (commentId) => activeRuntime.reopenComment(commentId),
729
- addCommentReply: (commentId, body) =>
730
- activeRuntime.addCommentReply(commentId, body, currentUser.userId),
731
- editCommentBody: (commentId, body) =>
732
- activeRuntime.editCommentBody(commentId, body),
733
- deleteComment: (commentId) => {
734
- applyRuntimeDeleteComment(activeRuntime, commentId);
735
- },
736
- acceptChange: (changeId) => activeRuntime.acceptChange(changeId),
737
- rejectChange: (changeId) => activeRuntime.rejectChange(changeId),
738
- acceptAllChanges: () => activeRuntime.acceptAllChanges(),
739
- rejectAllChanges: () => activeRuntime.rejectAllChanges(),
740
- exportDocx: (options) =>
741
- runtime
742
- ? persistAndExportFromBoundary({
743
- hostAdapter: hostAdapterRef.current,
744
- datastore: datastoreRef.current,
745
- documentId,
746
- runtime,
747
- onError: onErrorRef.current,
748
- onEvent: onEventRef.current,
749
- options,
750
- lastSavedRevisionTokenRef,
751
- autosaveTimerRef,
752
- })
753
- : rejectExportWhileLoadingFromBoundary({
754
- documentId,
755
- hostAdapter: hostAdapterRef.current,
756
- datastore: datastoreRef.current,
757
- onError: onErrorRef.current,
758
- onEvent: onEventRef.current,
759
- }),
760
- getSessionState: () => activeRuntime.getSessionState(),
761
- getSnapshot: () => activeRuntime.getPersistedSnapshot(),
762
- getRenderSnapshot: () => clonePublicValue(activeRuntime.getRenderSnapshot()),
763
- getCompatibilityReport: () => activeRuntime.getCompatibilityReport(),
764
- getWarnings: () => activeRuntime.getWarnings(),
765
- getCommentSidebarSnapshot: () =>
766
- clonePublicValue(activeRuntime.getRenderSnapshot().comments),
767
- getTrackedChangesSnapshot: () =>
768
- clonePublicValue(activeRuntime.getRenderSnapshot().trackedChanges),
769
- getComments: () =>
770
- clonePublicValue(activeRuntime.getRenderSnapshot().comments),
771
- getTrackedChanges: () =>
772
- clonePublicValue(activeRuntime.getRenderSnapshot().trackedChanges),
773
- isDirty: () => activeRuntime.getRenderSnapshot().isDirty,
774
- getFormattingState: () =>
775
- getFormattingStateFromRenderSnapshot(activeRuntime.getRenderSnapshot()),
776
- getStyleCatalog: () => getRuntimeStyleCatalog(activeRuntime),
777
- toggleBold: () => {
778
- applyRuntimeFormattingOperation(activeRuntime, {
779
- type: "toggle",
780
- mark: "bold",
781
- });
782
- },
783
- toggleItalic: () => {
784
- applyRuntimeFormattingOperation(activeRuntime, {
785
- type: "toggle",
786
- mark: "italic",
787
- });
788
- },
789
- toggleUnderline: () => {
790
- applyRuntimeFormattingOperation(activeRuntime, {
791
- type: "toggle",
792
- mark: "underline",
793
- });
794
- },
795
- toggleStrikethrough: () => {
796
- applyRuntimeFormattingOperation(activeRuntime, {
797
- type: "toggle",
798
- mark: "strikethrough",
799
- });
800
- },
801
- toggleSuperscript: () => {
802
- applyRuntimeFormattingOperation(activeRuntime, {
803
- type: "toggle",
804
- mark: "superscript",
805
- });
806
- },
807
- toggleSubscript: () => {
808
- applyRuntimeFormattingOperation(activeRuntime, {
809
- type: "toggle",
810
- mark: "subscript",
811
- });
812
- },
813
- setFontFamily: (fontFamily) => {
814
- applyRuntimeFormattingOperation(activeRuntime, {
815
- type: "set-font-family",
816
- fontFamily,
817
- });
818
- },
819
- setFontSize: (size) => {
820
- applyRuntimeFormattingOperation(activeRuntime, {
821
- type: "set-font-size",
822
- size,
823
- });
824
- },
825
- setTextColor: (color) => {
826
- applyRuntimeFormattingOperation(activeRuntime, {
827
- type: "set-text-color",
828
- color,
829
- });
830
- },
831
- setHighlightColor: (color) => {
832
- applyRuntimeFormattingOperation(activeRuntime, {
833
- type: "set-highlight-color",
834
- color,
835
- });
836
- },
837
- setAlignment: (alignment) => {
838
- applyRuntimeFormattingOperation(activeRuntime, {
839
- type: "set-alignment",
840
- alignment,
841
- });
842
- },
843
- setParagraphStyle: (styleId) => {
844
- applyRuntimeParagraphStyle(activeRuntime, styleId);
845
- },
846
- setTableStyle: (styleId) => {
847
- applyRuntimeTableStyle(activeRuntime, styleId);
848
- },
849
- indent: () => {
850
- applyRuntimeFormattingOperation(activeRuntime, { type: "indent" });
851
- },
852
- outdent: () => {
853
- applyRuntimeFormattingOperation(activeRuntime, { type: "outdent" });
854
- },
855
- insertPageBreak: () => {
856
- applyRuntimeInsertPageBreak(activeRuntime);
857
- },
858
- insertTable: (options) => {
859
- applyRuntimeInsertTable(activeRuntime, options);
860
- },
861
- insertImage: (options) => {
862
- applyRuntimeInsertImage(activeRuntime, options);
863
- },
864
- addRowBefore: () => {
865
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current, {
866
- type: "add-row-before",
867
- });
868
- },
869
- addRowAfter: () => {
870
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current, {
871
- type: "add-row-after",
872
- });
873
- },
874
- addColumnBefore: () => {
875
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current, {
876
- type: "add-column-before",
877
- });
878
- },
879
- addColumnAfter: () => {
880
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current, {
881
- type: "add-column-after",
882
- });
883
- },
884
- deleteRow: () => {
885
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current, {
886
- type: "delete-row",
887
- });
888
- },
889
- deleteColumn: () => {
890
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current, {
891
- type: "delete-column",
892
- });
893
- },
894
- deleteTable: () => {
895
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current, {
896
- type: "delete-table",
897
- });
898
- },
899
- mergeCells: () => {
900
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current, {
901
- type: "merge-cells",
902
- });
903
- },
904
- splitCell: () => {
905
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current, {
906
- type: "split-cell",
907
- });
908
- },
909
- setCellBackground: (color) => {
910
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current, {
911
- type: "set-cell-background",
912
- color,
913
- });
914
- },
915
- search: (query, options) =>
916
- searchRuntimeDocument(
917
- activeRuntime,
918
- surfaceRef.current,
919
- query,
920
- options,
921
- ),
922
- clearSearch: () => {
923
- surfaceRef.current?.clearSearch();
924
- },
925
- setSelection: (selection) => {
926
- applyRuntimeSelection(
927
- activeRuntime,
928
- normalizeRequestedSelection(activeRuntime.getRenderSnapshot(), selection),
929
- );
930
- },
931
- scrollToRevision: (revisionId: string) => {
932
- const revision = activeRuntime.getRenderSnapshot().trackedChanges.revisions.find(
933
- (r) => r.revisionId === revisionId,
934
- );
935
- if (!revision || revision.anchor.kind === "detached") return;
936
- applyRuntimeSelection(
937
- activeRuntime,
938
- createSelectionFromAnchor(revision.anchor, revision.storyTarget),
939
- );
940
- },
941
- scrollToComment: (commentId: string) => {
942
- const comment = activeRuntime.getRenderSnapshot().comments.threads.find(
943
- (t) => t.commentId === commentId,
944
- );
945
- if (!comment || comment.anchor.kind === "detached") return;
946
- applyRuntimeSelection(
947
- activeRuntime,
948
- createSelectionFromAnchor(comment.anchor),
949
- );
950
- },
951
- openStory: (target: EditorStoryTarget) => {
952
- activeRuntime.openStory(target);
953
- },
954
- closeStory: () => {
955
- activeRuntime.closeStory();
956
- },
957
- getPageLayoutSnapshot: () => {
958
- return clonePublicValue(activeRuntime.getPageLayoutSnapshot());
959
- },
960
- getDocumentNavigationSnapshot: () => {
961
- return clonePublicValue(activeRuntime.getDocumentNavigationSnapshot());
962
- },
963
- getFieldSnapshot: () => {
964
- return clonePublicValue(activeRuntime.getFieldSnapshot());
965
- },
966
- updateFields: (options) => {
967
- return activeRuntime.updateFields(options);
968
- },
969
- updateTableOfContents: (options) => {
970
- return activeRuntime.updateTableOfContents(options);
971
- },
972
- getViewState: () => {
973
- return clonePublicValue(activeRuntime.getViewState());
974
- },
975
- setDocumentMode: (mode) => {
976
- activeRuntime.setDocumentMode(mode);
977
- },
978
- getProtectionSnapshot: () => {
979
- return clonePublicValue(activeRuntime.getProtectionSnapshot());
980
- },
981
- setWorkspaceMode: (mode) => {
982
- activeRuntime.setWorkspaceMode(mode);
983
- },
984
- setZoom: (level) => {
985
- activeRuntime.setZoom(level);
986
- },
987
- insertSectionBreak: (type, options) => {
988
- applyRuntimeInsertSectionBreak(activeRuntime, type, options);
989
- },
990
- deleteSectionBreak: (sectionIndex) => {
991
- applyRuntimeDeleteSectionBreak(activeRuntime, sectionIndex);
992
- },
993
- updateSectionLayout: (sectionIndex, patch) => {
994
- applyRuntimeUpdateSectionLayout(activeRuntime, sectionIndex, patch);
995
- },
996
- setSectionPageNumbering: (sectionIndex, patch) => {
997
- applyRuntimeSetSectionPageNumbering(activeRuntime, sectionIndex, patch);
998
- },
999
- setHeaderFooterLink: (sectionIndex, params) => {
1000
- applyRuntimeSetHeaderFooterLink(activeRuntime, sectionIndex, params);
1001
- },
1002
- setImageLayout: (mediaId, dimensions) => {
1003
- applyRuntimeImageResize(activeRuntime, mediaId, dimensions);
1004
- },
1005
- setImageFrame: (mediaId, offsets) => {
1006
- applyRuntimeImageReposition(activeRuntime, mediaId, offsets);
1007
- },
1008
- setWorkflowOverlay: (overlay) => {
1009
- activeRuntime.setWorkflowOverlay(clonePublicValue(overlay));
1010
- },
1011
- clearWorkflowOverlay: () => {
1012
- activeRuntime.clearWorkflowOverlay();
1013
- },
1014
- getWorkflowScopeSnapshot: () => {
1015
- return clonePublicValue(activeRuntime.getWorkflowScopeSnapshot());
1016
- },
1017
- getInteractionGuardSnapshot: () => {
1018
- return clonePublicValue(activeRuntime.getInteractionGuardSnapshot());
1019
- },
1020
- getWorkflowMarkupSnapshot: () => {
1021
- return clonePublicValue(activeRuntime.getWorkflowMarkupSnapshot());
1022
- },
1023
- setHostAnnotationOverlay: (overlay) => {
1024
- activeRuntime.setHostAnnotationOverlay(clonePublicValue(overlay));
1025
- },
1026
- clearHostAnnotationOverlay: () => {
1027
- activeRuntime.clearHostAnnotationOverlay();
1028
- },
1029
- getHostAnnotationSnapshot: () => {
1030
- return clonePublicValue(activeRuntime.getHostAnnotationSnapshot());
1031
- },
1032
- getWorkflowCandidateRanges: (options) => {
1033
- return clonePublicValue(activeRuntime.getWorkflowCandidateRanges(options));
1034
- },
1035
- replaceWorkflowMarkupText: (markupId, text) => {
1036
- activeRuntime.replaceWorkflowMarkupText(markupId, text);
1037
- },
1038
- }),
1039
- [activeRuntime, currentUser.userId, documentId, runtime],
1040
- );
1041
-
1042
- useEffect(() => {
1043
- const canPersist =
1044
- Boolean(hostAdapterRef.current?.saveSession) || Boolean(datastoreRef.current?.saveSnapshot);
1045
- if (!canPersist || props.autosave?.enabled === false || !runtime || readOnly) {
1046
- if (autosaveTimerRef.current) {
1047
- clearTimeout(autosaveTimerRef.current);
1048
- autosaveTimerRef.current = null;
1049
- }
1050
- return;
1051
- }
1052
-
1053
- if (!snapshot.isReady || !snapshot.isDirty) {
1054
- return;
1055
- }
1056
-
1057
- if (lastSavedRevisionTokenRef.current === snapshot.revisionToken) {
1058
- return;
1059
- }
1060
-
1061
- if (autosaveTimerRef.current) {
1062
- clearTimeout(autosaveTimerRef.current);
1063
- }
1064
-
1065
- const debounceMs = props.autosave?.debounceMs ?? 800;
1066
- if (debounceMs <= 0) {
1067
- void persistSessionFromBoundary({
1068
- hostAdapter: hostAdapterRef.current,
1069
- datastore: datastoreRef.current,
1070
- documentId,
1071
- runtime,
1072
- isAutosave: true,
1073
- onError: onErrorRef.current,
1074
- onEvent: onEventRef.current,
1075
- lastSavedRevisionTokenRef,
1076
- });
1077
- return;
1078
- }
1079
-
1080
- autosaveTimerRef.current = setTimeout(() => {
1081
- void persistSessionFromBoundary({
1082
- hostAdapter: hostAdapterRef.current,
1083
- datastore: datastoreRef.current,
1084
- documentId,
1085
- runtime,
1086
- isAutosave: true,
1087
- onError: onErrorRef.current,
1088
- onEvent: onEventRef.current,
1089
- lastSavedRevisionTokenRef,
1090
- });
1091
- }, debounceMs);
1092
-
1093
- return () => {
1094
- if (autosaveTimerRef.current) {
1095
- clearTimeout(autosaveTimerRef.current);
1096
- autosaveTimerRef.current = null;
1097
- }
1098
- };
1099
- }, [
1100
- documentId,
1101
- props.autosave?.debounceMs,
1102
- props.autosave?.enabled,
1103
- readOnly,
1104
- runtime,
1105
- snapshot.isDirty,
1106
- snapshot.isReady,
1107
- snapshot.revisionToken,
1108
- ]);
1109
-
1110
- // Auto-select the most relevant rail tab based on content.
1111
- // Health tab was moved to toolbar popover — rail has only comments/changes.
1112
- useEffect(() => {
1113
- if (
1114
- activeRailTab === "comments" &&
1115
- snapshot.comments.totalCount === 0 &&
1116
- snapshot.trackedChanges.totalCount > 0
1117
- ) {
1118
- setActiveRailTab("changes");
1119
- return;
1120
- }
1121
- }, [
1122
- activeRailTab,
1123
- loadError,
1124
- snapshot.comments.totalCount,
1125
- snapshot.compatibility.blockExport,
1126
- snapshot.fatalError,
1127
- snapshot.trackedChanges.totalCount,
1128
- ]);
1129
-
1130
- function focusAnchor(
1131
- anchor: PublicSelectionSnapshot["activeRange"],
1132
- storyTarget?: EditorStoryTarget,
1133
- ): void {
1134
- if (anchor.kind === "detached") {
1135
- return;
1136
- }
1137
- applyRuntimeSelection(activeRuntime, createSelectionFromAnchor(anchor, storyTarget));
1138
- }
1139
-
1140
- function addReviewComment(): string | null {
1141
- try {
1142
- const commentId = activeRuntime.addComment({
1143
- anchor: snapshot.selection.activeRange,
1144
- body: "",
1145
- authorId: currentUser.userId,
1146
- });
1147
- activeRuntime.openComment(commentId);
1148
- setActiveRailTab("comments");
1149
- return commentId;
1150
- } catch {
1151
- // Runtime already emitted a concrete export-safety error for invalid anchors.
1152
- return null;
1153
- }
1154
- }
1155
-
1156
- function exportCurrentDocument(): void {
1157
- void (runtime
1158
- ? persistAndExportFromBoundary({
1159
- hostAdapter: hostAdapterRef.current,
1160
- datastore: datastoreRef.current,
1161
- documentId,
1162
- runtime,
1163
- onError: onErrorRef.current,
1164
- onEvent: onEventRef.current,
1165
- lastSavedRevisionTokenRef,
1166
- autosaveTimerRef,
1167
- })
1168
- : rejectExportWhileLoadingFromBoundary({
1169
- documentId,
1170
- hostAdapter: hostAdapterRef.current,
1171
- datastore: datastoreRef.current,
1172
- onError: onErrorRef.current,
1173
- onEvent: onEventRef.current,
1174
- }));
1175
- }
1176
-
1177
- const derivedCapabilities = deriveCapabilities(
1178
- snapshot,
1179
- reviewMode,
1180
- workflowScopeSnapshot,
1181
- );
1182
- const resolvedChromeVisibility = resolveWordReviewEditorChromeVisibility(
1183
- chromeVisibility,
1184
- showReviewPanel,
1185
- );
1186
- const capabilities = resolvedChromeVisibility.reviewRail
1187
- ? derivedCapabilities
1188
- : { ...derivedCapabilities, reviewRailVisible: false };
1189
- const formattingState = getFormattingStateFromRenderSnapshot(snapshot);
1190
- const styleCatalog = useMemo(
1191
- () => getRuntimeStyleCatalog(canonicalDocument.styles),
1192
- [canonicalDocument.styles],
1193
- );
1194
- const diagnosticsModeMessage = getDiagnosticsModeMessage(loadError ?? snapshot.fatalError);
1195
- const addCommentDisabledReason =
1196
- !capabilities.canAddComment && !snapshot.selection.isCollapsed
1197
- ? "Select text within one paragraph to add a DOCX comment."
1198
- : undefined;
1199
- const activeImageContext = useMemo(
1200
- () =>
1201
- buildActiveImageContext({
1202
- canonicalDocument,
1203
- selection: snapshot.selection,
1204
- storyTarget: viewState.activeStory,
1205
- surface: snapshot.surface,
1206
- }),
1207
- [canonicalDocument, snapshot.selection, snapshot.surface, viewState.activeStory],
1208
- );
1209
- const sourcePackage = runtime
1210
- ? runtime.getSourcePackage()
1211
- : loadingSessionState.sourcePackage;
1212
- const mediaPreviewCatalogKey = Object.values(canonicalDocument.media.items)
1213
- .map((item) =>
1214
- [
1215
- item.mediaId,
1216
- item.packagePartName,
1217
- item.contentType ?? "",
1218
- item.widthEmu ?? "",
1219
- item.heightEmu ?? "",
1220
- ].join(":"),
1221
- )
1222
- .sort()
1223
- .join("|");
1224
- const mediaPreviews = useMemo(() => {
1225
- if (!sourcePackage) {
1226
- return {} as Record<string, MediaPreviewDescriptor>;
1227
- }
1228
- try {
1229
- const bytes = decodePersistedSourcePackageBytes(sourcePackage);
1230
- if (!hasValidPersistedSourcePackageDigest(sourcePackage, bytes)) {
1231
- return {} as Record<string, MediaPreviewDescriptor>;
1232
- }
1233
- const opc = readOpcPackage(bytes);
1234
- const previews: Record<string, MediaPreviewDescriptor> = {};
1235
- for (const item of Object.values(canonicalDocument.media.items)) {
1236
- const contentType = item.contentType?.toLowerCase();
1237
- const part = opc.parts.get(item.packagePartName);
1238
- if (
1239
- !part?.bytes ||
1240
- !contentType ||
1241
- !BROWSER_SAFE_PREVIEW_TYPES.has(contentType)
1242
- ) {
1243
- continue;
1244
- }
1245
- previews[item.mediaId] = {
1246
- src: createImageDataUrl(contentType, part.bytes),
1247
- ...(item.widthEmu !== undefined ? { widthEmu: item.widthEmu } : {}),
1248
- ...(item.heightEmu !== undefined ? { heightEmu: item.heightEmu } : {}),
1249
- };
1250
- }
1251
- return previews;
1252
- } catch {
1253
- return {} as Record<string, MediaPreviewDescriptor>;
1254
- }
1255
- }, [mediaPreviewCatalogKey, sourcePackage?.sha256Hex]);
1256
- const activeObjectContext = useMemo(
1257
- () =>
1258
- viewState.activeObjectFrame && viewState.activeObjectFrame.kind !== "image"
1259
- ? {
1260
- kind: viewState.activeObjectFrame.kind,
1261
- display: viewState.activeObjectFrame.display,
1262
- }
1263
- : null,
1264
- [viewState.activeObjectFrame],
1265
- );
1266
- const selectionToolbar = buildSelectionToolbarModel({
1267
- snapshot,
1268
- viewState,
1269
- capabilities,
1270
- documentNavigation,
1271
- styleCatalog,
1272
- formattingState,
1273
- workflowScopeSnapshot,
1274
- interactionGuardSnapshot,
1275
- addCommentDisabledReason,
1276
- });
1277
- const suggestionCard = buildSuggestionCardModel({
1278
- snapshot,
1279
- viewState,
1280
- capabilities,
1281
- workflowScopeSnapshot,
1282
- interactionGuardSnapshot,
1283
- activeRevisionId,
1284
- suppressedSuggestionRevisionId,
1285
- addCommentDisabledReason,
1286
- });
1287
- const selectionToolbarSelectionKey = useMemo(
1288
- () => createSelectionToolbarSelectionKey(snapshot.selection, viewState.activeStory, activeRevisionId),
1289
- [activeRevisionId, snapshot.selection, viewState.activeStory],
1290
- );
1291
- const shouldRenderSelectionChrome = Boolean(
1292
- (selectionToolbar || suggestionCard) &&
1293
- selectionToolbarSelectionKey &&
1294
- selectionToolbarDismissedKey !== selectionToolbarSelectionKey &&
1295
- (viewState.isFocused || selectionToolbarFocusWithin),
1296
- );
1297
- const accessibilityInstructionsId = `${documentId}-accessibility-instructions`;
1298
- const accessibilityStatusId = `${documentId}-accessibility-status`;
1299
- const accessibilityAlertId = `${documentId}-accessibility-alert`;
1300
-
1301
- const dispatchSelection = (selection: PublicSelectionSnapshot) =>
1302
- applyRuntimeSelection(activeRuntime, selection);
1303
-
1304
- const dismissSelectionToolbar = useCallback(
1305
- (_reason: SelectionToolbarDismissReason) => {
1306
- if (selectionToolbarSelectionKey) {
1307
- setSelectionToolbarDismissedKey(selectionToolbarSelectionKey);
1308
- } else {
1309
- setSelectionToolbarDismissedKey(null);
1310
- }
1311
- setSelectionToolbarAnchor(null);
1312
- setSelectionToolbarFocusWithin(false);
1313
- },
1314
- [selectionToolbarSelectionKey],
1315
- );
1316
-
1317
- const getDocumentSurfaceElement = useCallback((): HTMLElement | null => {
1318
- return shellRef.current?.querySelector<HTMLElement>("[data-wre-document-surface='true']") ?? null;
1319
- }, []);
1320
-
1321
- const isTargetWithinSelectionToolbar = useCallback((target: EventTarget | null): boolean => {
1322
- return target instanceof Node && Boolean(selectionToolbarElementRef.current?.contains(target));
1323
- }, []);
1324
-
1325
- const isTargetWithinDocumentSurface = useCallback(
1326
- (target: EventTarget | null): boolean => {
1327
- const surfaceElement = getDocumentSurfaceElement();
1328
- return target instanceof Node && Boolean(surfaceElement?.contains(target));
1329
- },
1330
- [getDocumentSurfaceElement],
1331
- );
1332
-
1333
- const focusDocumentSurface = useCallback((): void => {
1334
- const surfaceElement = getDocumentSurfaceElement();
1335
- surfaceElement?.focus();
1336
- activeRuntime.focus();
1337
- }, [activeRuntime, getDocumentSurfaceElement]);
1338
-
1339
- const handleSurfaceFocus = useCallback(
1340
- (_event: FocusEvent<HTMLDivElement>) => {
1341
- setSelectionToolbarFocusWithin(false);
1342
- activeRuntime.focus();
1343
- },
1344
- [activeRuntime],
1345
- );
1346
-
1347
- const handleSurfaceBlur = useCallback(
1348
- (event: FocusEvent<HTMLDivElement>) => {
1349
- if (isTargetWithinSelectionToolbar(event.relatedTarget)) {
1350
- setSelectionToolbarFocusWithin(true);
1351
- activeRuntime.focus();
1352
- return;
1353
- }
1354
-
1355
- setSelectionToolbarFocusWithin(false);
1356
- activeRuntime.blur();
1357
- dismissSelectionToolbar("blur");
1358
- },
1359
- [activeRuntime, dismissSelectionToolbar, isTargetWithinSelectionToolbar],
1360
- );
1361
-
1362
- const handleSelectionToolbarFocusCapture = useCallback(() => {
1363
- setSelectionToolbarFocusWithin(true);
1364
- activeRuntime.focus();
1365
- }, [activeRuntime]);
1366
-
1367
- const handleSelectionToolbarBlurCapture = useCallback(
1368
- (event: FocusEvent<HTMLDivElement>) => {
1369
- if (isTargetWithinSelectionToolbar(event.relatedTarget)) {
1370
- return;
1371
- }
1372
-
1373
- if (isTargetWithinDocumentSurface(event.relatedTarget)) {
1374
- setSelectionToolbarFocusWithin(false);
1375
- activeRuntime.focus();
1376
- return;
1377
- }
1378
-
1379
- setSelectionToolbarFocusWithin(false);
1380
- activeRuntime.blur();
1381
- dismissSelectionToolbar("blur");
1382
- },
1383
- [
1384
- activeRuntime,
1385
- dismissSelectionToolbar,
1386
- isTargetWithinDocumentSurface,
1387
- isTargetWithinSelectionToolbar,
1388
- ],
1389
- );
1390
-
1391
- const addSelectionToolbarComment = useCallback(() => {
1392
- const commentId = addReviewComment();
1393
- if (!commentId) {
1394
- return;
1395
- }
1396
- dismissSelectionToolbar("comment-action");
1397
- queueMicrotask(() => {
1398
- focusDocumentSurface();
1399
- });
1400
- }, [dismissSelectionToolbar, focusDocumentSurface]);
1401
-
1402
- const handleSelectionToolbarAnchorChange = useCallback(
1403
- (nextAnchor: SelectionToolbarAnchor | null) => {
1404
- setSelectionToolbarAnchor((current) =>
1405
- selectionToolbarAnchorsEqual(current, nextAnchor) ? current : nextAnchor);
1406
- },
1407
- [],
1408
- );
1409
-
1410
- useEffect(() => {
1411
- if (!selectionToolbarSelectionKey) {
1412
- setSuppressedSuggestionRevisionId(null);
1413
- setSelectionToolbarDismissedKey(null);
1414
- setSelectionToolbarFocusWithin(false);
1415
- setSelectionToolbarAnchor(null);
1416
- lastSelectionToolbarKeyRef.current = null;
1417
- return;
1418
- }
1419
-
1420
- if (lastSelectionToolbarKeyRef.current !== selectionToolbarSelectionKey) {
1421
- lastSelectionToolbarKeyRef.current = selectionToolbarSelectionKey;
1422
- setSuppressedSuggestionRevisionId(null);
1423
- setSelectionToolbarDismissedKey(null);
1424
- setSelectionToolbarFocusWithin(false);
1425
- }
1426
- }, [selectionToolbarSelectionKey]);
1427
-
1428
- useEffect(() => {
1429
- if (!selectionToolbar && !suggestionCard) {
1430
- setSelectionToolbarAnchor(null);
1431
- setSelectionToolbarFocusWithin(false);
1432
- }
1433
- }, [selectionToolbar, suggestionCard]);
1434
-
1435
- useEffect(() => {
1436
- const shell = shellRef.current;
1437
- if (!shell) {
1438
- return;
1439
- }
1440
-
1441
- applyRegionAttributes(shell);
1442
- }, [runtime, snapshot.fatalError, snapshot.isReady]);
1443
-
1444
- useEffect(() => {
1445
- const shell = shellRef.current;
1446
- const fatalError = loadError ?? snapshot.fatalError;
1447
- if (!shell || !fatalError) {
1448
- lastAnnouncedErrorIdRef.current = null;
1449
- return;
1450
- }
1451
-
1452
- if (lastAnnouncedErrorIdRef.current === fatalError.errorId) {
1453
- return;
1454
- }
1455
-
1456
- lastAnnouncedErrorIdRef.current = fatalError.errorId;
1457
- const alertTarget = shell.querySelector<HTMLElement>("[data-wre-alert='true']");
1458
- alertTarget?.focus();
1459
- }, [loadError, snapshot.fatalError]);
1460
-
1461
- function handleShellKeyDownCapture(event: React.KeyboardEvent<HTMLDivElement>): void {
1462
- const targetWithinDocument = isTargetWithinDocumentSurface(event.target);
1463
- const isUndoShortcut = (event.ctrlKey || event.metaKey) && !event.shiftKey && event.key.toLowerCase() === "z";
1464
- const isRedoShortcut =
1465
- ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key.toLowerCase() === "z") ||
1466
- (event.ctrlKey && event.key.toLowerCase() === "y");
1467
-
1468
- if ((isUndoShortcut || isRedoShortcut) && targetWithinDocument) {
1469
- event.preventDefault();
1470
- event.stopPropagation();
1471
- if (isUndoShortcut) {
1472
- activeRuntime.undo();
1473
- } else {
1474
- activeRuntime.redo();
1475
- }
1476
- return;
1477
- }
1478
-
1479
- if (
1480
- event.key === "Escape" &&
1481
- shouldRenderSelectionChrome &&
1482
- (isTargetWithinDocumentSurface(event.target) || isTargetWithinSelectionToolbar(event.target))
1483
- ) {
1484
- event.preventDefault();
1485
- event.stopPropagation();
1486
- const restoreSurfaceFocus = isTargetWithinSelectionToolbar(event.target);
1487
- dismissSelectionToolbar("escape");
1488
- if (restoreSurfaceFocus) {
1489
- queueMicrotask(() => {
1490
- focusDocumentSurface();
1491
- });
1492
- }
1493
- return;
1494
- }
1495
-
1496
- if (event.key !== "F6") {
1497
- return;
1498
- }
1499
-
1500
- const shell = shellRef.current;
1501
- if (!shell) {
1502
- return;
1503
- }
1504
-
1505
- event.preventDefault();
1506
- focusRelativeRegion(shell, event.shiftKey ? -1 : 1);
1507
- }
1508
-
1509
- const editorCallbacks = {
1510
- onFocus: handleSurfaceFocus,
1511
- onBlur: handleSurfaceBlur,
1512
- onSelectionChange: dispatchSelection,
1513
- onInsertText: (text: string) => applyRuntimeTextCommand(activeRuntime, { type: "insert-text", text }),
1514
- onDeleteBackward: () => applyRuntimeTextCommand(activeRuntime, { type: "delete-backward" }),
1515
- onDeleteForward: () => applyRuntimeTextCommand(activeRuntime, { type: "delete-forward" }),
1516
- onInsertTab: () => applyRuntimeTextCommand(activeRuntime, { type: "insert-tab" }),
1517
- onOutdentTab: () => applyRuntimeTextCommand(activeRuntime, { type: "outdent-tab" }),
1518
- onInsertHardBreak: () => applyRuntimeTextCommand(activeRuntime, { type: "insert-hard-break" }),
1519
- onSplitParagraph: () => applyRuntimeTextCommand(activeRuntime, { type: "split-paragraph" }),
1520
- onUndo: () => activeRuntime.undo(),
1521
- onRedo: () => activeRuntime.redo(),
1522
- onBlockedInput: (command: "paste" | "drop", message: string) =>
1523
- activeRuntime.emitBlockedCommand(command, [{
1524
- code: "unsupported_surface",
1525
- message,
1526
- }]),
1527
- };
1528
-
1529
- const reviewCallbacks = {
1530
- onUndo: () => activeRuntime.undo(),
1531
- onRedo: () => activeRuntime.redo(),
1532
- onAddComment: addReviewComment,
1533
- onExport: exportCurrentDocument,
1534
- onOpenComment: (thread: typeof snapshot.comments.threads[number]) => {
1535
- activeRuntime.openComment(thread.commentId);
1536
- focusAnchor(thread.anchor);
1537
- setActiveRailTab("comments");
1538
- },
1539
- onResolveComment: (commentId: string) => {
1540
- activeRuntime.resolveComment(commentId);
1541
- setActiveRailTab("comments");
1542
- },
1543
- onReopenComment: (commentId: string) => {
1544
- activeRuntime.reopenComment(commentId);
1545
- setActiveRailTab("comments");
1546
- },
1547
- onAddReply: (commentId: string, body: string) => {
1548
- activeRuntime.addCommentReply(commentId, body, currentUser.userId);
1549
- },
1550
- onEditBody: (commentId: string, body: string) => {
1551
- activeRuntime.editCommentBody(commentId, body);
1552
- },
1553
- onOpenRevision: (revision: typeof snapshot.trackedChanges.revisions[number]) => {
1554
- setActiveRevisionId(revision.revisionId);
1555
- focusAnchor(revision.anchor, revision.storyTarget);
1556
- setActiveRailTab("changes");
1557
- },
1558
- onAcceptRevision: (revisionId: string) => {
1559
- activeRuntime.acceptChange(revisionId);
1560
- setActiveRailTab("changes");
1561
- },
1562
- onRejectRevision: (revisionId: string) => {
1563
- activeRuntime.rejectChange(revisionId);
1564
- setActiveRailTab("changes");
1565
- },
1566
- onAcceptAllChanges: () => {
1567
- activeRuntime.acceptAllChanges();
1568
- setActiveRailTab("changes");
1569
- },
1570
- onRejectAllChanges: () => {
1571
- activeRuntime.rejectAllChanges();
1572
- setActiveRailTab("changes");
1573
- },
1574
- onCloseStory: () => {
1575
- activeRuntime.closeStory();
1576
- },
1577
- };
1578
-
1579
- const commands = useCommandBag<EditorCommandBag>({
1580
- ...reviewCallbacks,
1581
- onWorkspaceModeChange: (mode) => activeRuntime.setWorkspaceMode(mode),
1582
- onZoomChange: (level) => activeRuntime.setZoom(level),
1583
- onActiveRailTabChange: setActiveRailTab,
1584
- onShowTrackedChangesChange: setShowTrackedChanges,
1585
- onToggleBold: () =>
1586
- applyRuntimeFormattingOperation(activeRuntime, { type: "toggle", mark: "bold" }),
1587
- onToggleItalic: () =>
1588
- applyRuntimeFormattingOperation(activeRuntime, { type: "toggle", mark: "italic" }),
1589
- onToggleUnderline: () =>
1590
- applyRuntimeFormattingOperation(activeRuntime, { type: "toggle", mark: "underline" }),
1591
- onSetSelectionTextColor: (color) =>
1592
- applyRuntimeFormattingOperation(activeRuntime, { type: "set-text-color", color }),
1593
- onSetSelectionHighlightColor: (color) =>
1594
- applyRuntimeFormattingOperation(activeRuntime, { type: "set-highlight-color", color }),
1595
- onToggleStrikethrough: () =>
1596
- applyRuntimeFormattingOperation(activeRuntime, {
1597
- type: "toggle",
1598
- mark: "strikethrough",
1599
- }),
1600
- onToggleSuperscript: () =>
1601
- applyRuntimeFormattingOperation(activeRuntime, {
1602
- type: "toggle",
1603
- mark: "superscript",
1604
- }),
1605
- onToggleSubscript: () =>
1606
- applyRuntimeFormattingOperation(activeRuntime, { type: "toggle", mark: "subscript" }),
1607
- onSetFontFamily: (fontFamily) =>
1608
- applyRuntimeFormattingOperation(activeRuntime, { type: "set-font-family", fontFamily }),
1609
- onSetFontSize: (fontSize) =>
1610
- applyRuntimeFormattingOperation(activeRuntime, { type: "set-font-size", size: fontSize }),
1611
- onSetTextColor: (color) =>
1612
- applyRuntimeFormattingOperation(activeRuntime, { type: "set-text-color", color }),
1613
- onSetHighlightColor: (color) =>
1614
- applyRuntimeFormattingOperation(activeRuntime, { type: "set-highlight-color", color }),
1615
- onSetAlignment: (alignment) =>
1616
- applyRuntimeFormattingOperation(activeRuntime, { type: "set-alignment", alignment }),
1617
- onSetParagraphStyle: (styleId) => applyRuntimeParagraphStyle(activeRuntime, styleId),
1618
- onOutdent: () => applyRuntimeFormattingOperation(activeRuntime, { type: "outdent" }),
1619
- onIndent: () => applyRuntimeFormattingOperation(activeRuntime, { type: "indent" }),
1620
- onInsertPageBreak: () => applyRuntimeInsertPageBreak(activeRuntime),
1621
- onInsertTable: () => applyRuntimeInsertTable(activeRuntime, { rows: 3, columns: 3 }),
1622
- onInsertSectionBreak: (type) => applyRuntimeInsertSectionBreak(activeRuntime, type),
1623
- onInsertImage: (options) => applyRuntimeInsertImage(activeRuntime, options),
1624
- onSetTableStyle: (styleId) => applyRuntimeTableStyle(activeRuntime, styleId),
1625
- onAddRowBefore: () =>
1626
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current ?? null, {
1627
- type: "add-row-before",
1628
- }),
1629
- onAddRowAfter: () =>
1630
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current ?? null, {
1631
- type: "add-row-after",
1632
- }),
1633
- onAddColumnBefore: () =>
1634
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current ?? null, {
1635
- type: "add-column-before",
1636
- }),
1637
- onAddColumnAfter: () =>
1638
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current ?? null, {
1639
- type: "add-column-after",
1640
- }),
1641
- onDeleteRow: () =>
1642
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current ?? null, {
1643
- type: "delete-row",
1644
- }),
1645
- onDeleteColumn: () =>
1646
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current ?? null, {
1647
- type: "delete-column",
1648
- }),
1649
- onDeleteTable: () =>
1650
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current ?? null, {
1651
- type: "delete-table",
1652
- }),
1653
- onMergeCells: () =>
1654
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current ?? null, {
1655
- type: "merge-cells",
1656
- }),
1657
- onSplitCell: () =>
1658
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current ?? null, {
1659
- type: "split-cell",
1660
- }),
1661
- onSetCellBackground: (color) =>
1662
- applyRuntimeTableStructureOperation(activeRuntime, surfaceRef.current ?? null, {
1663
- type: "set-cell-background",
1664
- color,
1665
- }),
1666
- onSetImageLayout: (mediaId, dimensions) =>
1667
- applyRuntimeImageResize(activeRuntime, mediaId, dimensions),
1668
- onSetImageFrame: (mediaId, offsets) =>
1669
- applyRuntimeImageReposition(activeRuntime, mediaId, offsets),
1670
- onOpenHeaderStory: () =>
1671
- openDefaultStoryVariant(activeRuntime, snapshot.pageLayout, documentNavigation, "header"),
1672
- onOpenFooterStory: () =>
1673
- openDefaultStoryVariant(activeRuntime, snapshot.pageLayout, documentNavigation, "footer"),
1674
- onDeleteSectionBreak: (sectionIndex) =>
1675
- applyRuntimeDeleteSectionBreak(activeRuntime, sectionIndex),
1676
- onUpdateSectionLayout: (sectionIndex, patch) =>
1677
- applyRuntimeUpdateSectionLayout(activeRuntime, sectionIndex, patch),
1678
- onSetSectionPageNumbering: (sectionIndex, patch) =>
1679
- applyRuntimeSetSectionPageNumbering(activeRuntime, sectionIndex, patch),
1680
- onSetHeaderFooterLink: (sectionIndex, patch) =>
1681
- applyRuntimeSetHeaderFooterLink(activeRuntime, sectionIndex, patch),
1682
- onSetParagraphIndentation: (indentation) =>
1683
- applyRuntimeParagraphIndentation(activeRuntime, indentation),
1684
- onSetParagraphTabStops: (tabStops) =>
1685
- applyRuntimeParagraphTabStops(activeRuntime, tabStops),
1686
- onRestartNumbering: () =>
1687
- applyRuntimeNumberingFlow(activeRuntime, { type: "restart" }),
1688
- onContinueNumbering: () =>
1689
- applyRuntimeNumberingFlow(activeRuntime, { type: "continue" }),
1690
- onNavigateHeading: (headingId) => {
1691
- const heading = documentNavigation.headings.find(
1692
- (entry) => entry.headingId === headingId,
1693
- );
1694
- if (!heading) {
1695
- return;
1696
- }
1697
- applyRuntimeSelection(
1698
- activeRuntime,
1699
- createCollapsedPublicSelection(heading.offset),
1700
- );
1701
- },
1702
- });
1703
-
1704
- const documentElement = (
1705
- <EditorSurfaceController
1706
- ref={surfaceRef}
1707
- currentUser={currentUser}
1708
- snapshot={snapshot}
1709
- canonicalDocument={canonicalDocument}
1710
- documentNavigation={documentNavigation}
1711
- reviewMode={reviewMode}
1712
- markupDisplay={liveMarkupDisplay}
1713
- activeRevisionId={activeRevisionId}
1714
- showTrackedChanges={showTrackedChanges}
1715
- suggestionsEnabled={suggestionsEnabled}
1716
- mediaPreviews={mediaPreviews}
1717
- isPageWorkspace={isPageWorkspace}
1718
- workflowScopes={workflowScopeSnapshot?.scopes}
1719
- workflowCandidates={workflowScopeSnapshot?.candidates}
1720
- workflowBlockedReasons={workflowBlockedRails}
1721
- activeWorkflowWorkItemId={workflowScopeSnapshot?.activeWorkItemId ?? null}
1722
- activeWorkflowScopeIds={workflowScopeSnapshot?.activeWorkItem?.scopeIds ?? []}
1723
- onSelectionToolbarAnchorChange={handleSelectionToolbarAnchorChange}
1724
- {...editorCallbacks}
1725
- onCommentActivated={(commentId) => {
1726
- activeRuntime.openComment(commentId);
1727
- setActiveRailTab("comments");
1728
- }}
1729
- onRevisionActivated={(revisionId) => {
1730
- setActiveRevisionId(revisionId);
1731
- setActiveRailTab("changes");
1732
- }}
1733
- />
1734
- );
1735
-
1736
- return (
1737
- <EditorShellView
1738
- shellRef={shellRef}
1739
- documentId={documentId}
1740
- snapshot={snapshot}
1741
- loadError={loadError}
1742
- diagnosticsModeMessage={diagnosticsModeMessage}
1743
- accessibilityInstructionsId={accessibilityInstructionsId}
1744
- accessibilityStatusId={accessibilityStatusId}
1745
- accessibilityAlertId={accessibilityAlertId}
1746
- accessibilityStatusMessage={buildAccessibilityStatusMessage(
1747
- snapshot,
1748
- loadError ?? undefined,
1749
- )}
1750
- visuallyHiddenStyles={VISUALLY_HIDDEN_STYLES}
1751
- onShellKeyDownCapture={handleShellKeyDownCapture}
1752
- viewState={viewState}
1753
- markupDisplay={liveMarkupDisplay}
1754
- currentUserId={currentUser.userId}
1755
- capabilities={capabilities}
1756
- chromeVisibility={resolvedChromeVisibility}
1757
- documentNavigation={documentNavigation}
1758
- reviewMode={reviewMode}
1759
- workspaceMode={viewState.workspaceMode}
1760
- zoomLevel={viewState.zoomLevel}
1761
- formattingState={formattingState}
1762
- styleCatalog={styleCatalog}
1763
- activeRailTab={activeRailTab}
1764
- activeCommentId={snapshot.comments.activeCommentId}
1765
- activeRevisionId={activeRevisionId}
1766
- showTrackedChanges={showTrackedChanges}
1767
- workflowScopeSnapshot={workflowScopeSnapshot}
1768
- interactionGuardSnapshot={interactionGuardSnapshot}
1769
- selectionToolbar={shouldRenderSelectionChrome ? selectionToolbar : null}
1770
- suggestionCard={shouldRenderSelectionChrome ? suggestionCard : null}
1771
- selectionToolbarAnchor={shouldRenderSelectionChrome ? selectionToolbarAnchor : null}
1772
- onAddCommentFromSelection={addSelectionToolbarComment}
1773
- onAddCommentFromSuggestion={addSelectionToolbarComment}
1774
- onAcceptSuggestion={suggestionCard
1775
- ? () => {
1776
- activeRuntime.acceptChange(suggestionCard.revisionId);
1777
- dismissSelectionToolbar("chrome-action");
1778
- }
1779
- : undefined}
1780
- onRejectSuggestion={suggestionCard
1781
- ? () => {
1782
- activeRuntime.rejectChange(suggestionCard.revisionId);
1783
- dismissSelectionToolbar("chrome-action");
1784
- }
1785
- : undefined}
1786
- onEditSuggestion={suggestionCard
1787
- ? () => {
1788
- setSuppressedSuggestionRevisionId(suggestionCard.revisionId);
1789
- }
1790
- : undefined}
1791
- onDismissSelectionToolbar={() => dismissSelectionToolbar("chrome-action")}
1792
- onSelectionToolbarFocusCapture={handleSelectionToolbarFocusCapture}
1793
- onSelectionToolbarBlurCapture={handleSelectionToolbarBlurCapture}
1794
- selectionToolbarRef={selectionToolbarElementRef}
1795
- activeImageContext={activeImageContext}
1796
- activeObjectContext={activeObjectContext}
1797
- commands={commands}
1798
- document={documentElement}
1799
- />
1800
- );
1801
- },
1802
- );
1803
-
1804
- function applyRuntimeFormattingOperation(
1805
- runtime: WordReviewEditorRuntime,
1806
- operation:
1807
- | { type: "toggle"; mark: "bold" | "italic" | "underline" | "strikethrough" | "superscript" | "subscript" }
1808
- | { type: "set-font-family"; fontFamily: string | null }
1809
- | { type: "set-font-size"; size: number | null }
1810
- | { type: "set-text-color"; color: string | null }
1811
- | { type: "set-highlight-color"; color: string | null }
1812
- | { type: "set-alignment"; alignment: FormattingAlignment }
1813
- | { type: "indent" }
1814
- | { type: "outdent" },
1815
- ): void {
1816
- if (emitSuggestingUnsupportedMutation(runtime, getFormattingOperationCommandName(operation))) {
1817
- return;
1818
- }
1819
- const context = getStoryMutationContext(runtime, getFormattingOperationCommandName(operation));
1820
- if (!context) {
1821
- return;
1822
- }
1823
-
1824
- const result = applyFormattingOperationToDocument(
1825
- context.localDocument,
1826
- context.localSnapshot,
1827
- operation,
1828
- );
1829
- dispatchStoryMutationResult(
1830
- runtime,
1831
- context,
1832
- {
1833
- ...result,
1834
- selection: toRuntimeSelectionSnapshot(result.selection),
1835
- },
1836
- context.timestamp,
1837
- );
1838
- }
1839
-
1840
- function getRuntimeStyleCatalog(
1841
- input:
1842
- | WordReviewEditorRuntime
1843
- | EditorSessionState["canonicalDocument"]["styles"],
1844
- ): StyleCatalogSnapshot {
1845
- const styles =
1846
- "getSessionState" in input
1847
- ? input.getSessionState().canonicalDocument.styles
1848
- : input;
1849
- const mapRecord = <
1850
- T extends {
1851
- styleId: string;
1852
- displayName: string;
1853
- kind: "paragraph" | "character" | "table";
1854
- isDefault: boolean;
1855
- basedOn?: string;
1856
- nextStyle?: string;
1857
- },
1858
- >(
1859
- record: Record<string, T>,
1860
- ) =>
1861
- Object.values(record)
1862
- .map((entry) => ({
1863
- styleId: entry.styleId,
1864
- displayName: entry.displayName,
1865
- kind: entry.kind,
1866
- isDefault: entry.isDefault,
1867
- ...(entry.basedOn ? { basedOn: entry.basedOn } : {}),
1868
- ...(entry.nextStyle ? { nextStyle: entry.nextStyle } : {}),
1869
- }))
1870
- .sort((left, right) =>
1871
- left.displayName.localeCompare(right.displayName) ||
1872
- left.styleId.localeCompare(right.styleId),
1873
- );
1874
-
1875
- return {
1876
- paragraphs: mapRecord(styles.paragraphs),
1877
- characters: mapRecord(styles.characters),
1878
- tables: mapRecord(styles.tables),
1879
- fromPackage: styles.fromPackage === true,
1880
- };
1881
- }
1882
-
1883
- function applyRuntimeParagraphStyle(
1884
- runtime: WordReviewEditorRuntime,
1885
- styleId: string | null,
1886
- ): void {
1887
- if (emitSuggestingUnsupportedMutation(runtime, "setParagraphStyle")) {
1888
- return;
1889
- }
1890
- const context = getStoryMutationContext(runtime, "setParagraphStyle");
1891
- if (!context) {
1892
- return;
1893
- }
1894
-
1895
- const result = applyParagraphStyleToDocument(
1896
- context.localDocument,
1897
- context.localSnapshot,
1898
- styleId,
1899
- );
1900
- dispatchStoryMutationResult(
1901
- runtime,
1902
- context,
1903
- {
1904
- ...result,
1905
- selection: toRuntimeSelectionSnapshot(result.selection),
1906
- },
1907
- context.timestamp,
1908
- );
1909
- }
1910
-
1911
- function applyRuntimeTableStyle(
1912
- runtime: WordReviewEditorRuntime,
1913
- styleId: string | null,
1914
- ): void {
1915
- if (emitSuggestingUnsupportedMutation(runtime, "setTableStyle")) {
1916
- return;
1917
- }
1918
- const context = getStoryMutationContext(runtime, "setTableStyle");
1919
- if (!context) {
1920
- return;
1921
- }
1922
-
1923
- const result = applyTableStyleToDocument(
1924
- context.localDocument,
1925
- context.localSnapshot,
1926
- styleId,
1927
- );
1928
- dispatchStoryMutationResult(
1929
- runtime,
1930
- context,
1931
- {
1932
- ...result,
1933
- selection: toRuntimeSelectionSnapshot(result.selection),
1934
- },
1935
- context.timestamp,
1936
- );
1937
- }
1938
-
1939
- function applyRuntimeParagraphIndentation(
1940
- runtime: WordReviewEditorRuntime,
1941
- indentation: {
1942
- left?: number;
1943
- right?: number;
1944
- firstLine?: number;
1945
- hanging?: number;
1946
- },
1947
- ): void {
1948
- if (emitSuggestingUnsupportedMutation(runtime, "setParagraphIndentation")) {
1949
- return;
1950
- }
1951
- const context = getStoryMutationContext(runtime, "setParagraphIndentation");
1952
- if (!context) {
1953
- return;
1954
- }
1955
-
1956
- const result = setActiveParagraphIndentation(
1957
- context.localDocument,
1958
- context.localSnapshot,
1959
- indentation,
1960
- { timestamp: context.timestamp },
1961
- );
1962
- dispatchStoryMutationResult(
1963
- runtime,
1964
- context,
1965
- {
1966
- ...result,
1967
- selection: toRuntimeSelectionSnapshot(result.selection),
1968
- },
1969
- context.timestamp,
1970
- );
1971
- }
1972
-
1973
- function applyRuntimeParagraphTabStops(
1974
- runtime: WordReviewEditorRuntime,
1975
- tabStops: Array<{ pos: number; val?: string; leader?: string }>,
1976
- ): void {
1977
- if (emitSuggestingUnsupportedMutation(runtime, "setParagraphTabStops")) {
1978
- return;
1979
- }
1980
- const context = getStoryMutationContext(runtime, "setParagraphTabStops");
1981
- if (!context) {
1982
- return;
1983
- }
1984
-
1985
- const result = setActiveParagraphTabStops(
1986
- context.localDocument,
1987
- context.localSnapshot,
1988
- tabStops,
1989
- { timestamp: context.timestamp },
1990
- );
1991
- dispatchStoryMutationResult(
1992
- runtime,
1993
- context,
1994
- {
1995
- ...result,
1996
- selection: toRuntimeSelectionSnapshot(result.selection),
1997
- },
1998
- context.timestamp,
1999
- );
2000
- }
2001
-
2002
- function applyRuntimeNumberingFlow(
2003
- runtime: WordReviewEditorRuntime,
2004
- operation: { type: "restart"; startAt?: number } | { type: "continue" },
2005
- ): void {
2006
- if (
2007
- emitSuggestingUnsupportedMutation(
2008
- runtime,
2009
- operation.type === "restart" ? "restartNumbering" : "continueNumbering",
2010
- )
2011
- ) {
2012
- return;
2013
- }
2014
- const context = getStoryMutationContext(
2015
- runtime,
2016
- operation.type === "restart" ? "restartNumbering" : "continueNumbering",
2017
- );
2018
- if (!context) {
2019
- return;
2020
- }
2021
-
2022
- const paragraphContext = resolveActiveParagraphContext(context.localSnapshot);
2023
- if (!paragraphContext?.paragraph.numbering) {
2024
- return;
2025
- }
2026
-
2027
- const result =
2028
- operation.type === "restart"
2029
- ? restartListNumbering(
2030
- context.localDocument,
2031
- paragraphContext.paragraphIndex,
2032
- { timestamp: context.timestamp },
2033
- operation.startAt,
2034
- )
2035
- : continueListNumbering(
2036
- context.localDocument,
2037
- paragraphContext.paragraphIndex,
2038
- { timestamp: context.timestamp },
2039
- );
2040
-
2041
- dispatchStoryMutationResult(
2042
- runtime,
2043
- context,
2044
- {
2045
- changed: result.affectedParagraphIndexes.length > 0,
2046
- document: result.document,
2047
- selection: toRuntimeSelectionSnapshot(context.localSnapshot.selection),
2048
- },
2049
- context.timestamp,
2050
- );
2051
- }
2052
-
2053
- function applyRuntimeInsertSectionBreak(
2054
- runtime: WordReviewEditorRuntime,
2055
- breakType: SectionBreakType,
2056
- options?: { afterSectionIndex?: number },
2057
- ): void {
2058
- const snapshot = runtime.getRenderSnapshot();
2059
- if (!canApplyRuntimeMutation(snapshot) || snapshot.activeStory.kind !== "main") {
2060
- return;
2061
- }
2062
- if (emitWorkflowBlockedMutation(runtime, "insertSectionBreak")) {
2063
- return;
2064
- }
2065
- if (isSelectionSuggesting(runtime)) {
2066
- runtime.emitBlockedCommand("insertSectionBreak", [{
2067
- code: "unsupported_surface",
2068
- message: "Section break insertion is not supported in suggesting mode.",
2069
- }]);
2070
- return;
2071
- }
2072
-
2073
- const sessionState = runtime.getSessionState();
2074
- const timestamp = new Date().toISOString();
2075
- const result =
2076
- typeof options?.afterSectionIndex === "number"
2077
- ? insertSectionBreakAfterSectionIndex(
2078
- sessionState.canonicalDocument,
2079
- options.afterSectionIndex,
2080
- breakType,
2081
- { timestamp },
2082
- )
2083
- : insertSectionBreakAfterSectionIndex(
2084
- sessionState.canonicalDocument,
2085
- runtime.getDocumentNavigationSnapshot().activeSectionIndex,
2086
- breakType,
2087
- { timestamp },
2088
- );
2089
-
2090
- dispatchRuntimeDocumentMutation(
2091
- runtime,
2092
- {
2093
- changed: result.changed,
2094
- document: result.document,
2095
- selection: toRuntimeSelectionSnapshot(result.selection),
2096
- },
2097
- timestamp,
2098
- );
2099
- }
2100
-
2101
- function emitSuggestingUnsupportedMutation(
2102
- runtime: WordReviewEditorRuntime,
2103
- command: string,
2104
- ): boolean {
2105
- if (!isSelectionSuggesting(runtime)) {
2106
- return false;
2107
- }
2108
-
2109
- runtime.emitBlockedCommand(command, [{
2110
- code: "suggesting_unsupported",
2111
- message: `"${command}" is not supported in suggesting mode.`,
2112
- }]);
2113
- return true;
2114
- }
2115
-
2116
- function isSelectionSuggesting(runtime: WordReviewEditorRuntime): boolean {
2117
- return runtime.getInteractionGuardSnapshot().effectiveMode === "suggest";
2118
- }
2119
-
2120
- function getFormattingOperationCommandName(
2121
- operation:
2122
- | { type: "toggle"; mark: "bold" | "italic" | "underline" | "strikethrough" | "superscript" | "subscript" }
2123
- | { type: "set-font-family"; fontFamily: string | null }
2124
- | { type: "set-font-size"; size: number | null }
2125
- | { type: "set-text-color"; color: string | null }
2126
- | { type: "set-highlight-color"; color: string | null }
2127
- | { type: "set-alignment"; alignment: FormattingAlignment }
2128
- | { type: "indent" }
2129
- | { type: "outdent" },
2130
- ): string {
2131
- switch (operation.type) {
2132
- case "toggle":
2133
- return `toggle${operation.mark.charAt(0).toUpperCase()}${operation.mark.slice(1)}`;
2134
- case "set-font-family":
2135
- return "setFontFamily";
2136
- case "set-font-size":
2137
- return "setFontSize";
2138
- case "set-text-color":
2139
- return "setTextColor";
2140
- case "set-highlight-color":
2141
- return "setHighlightColor";
2142
- case "set-alignment":
2143
- return "setAlignment";
2144
- case "indent":
2145
- return "indent";
2146
- case "outdent":
2147
- return "outdent";
2148
- }
2149
- }
2150
-
2151
- function applyRuntimeDeleteSectionBreak(
2152
- runtime: WordReviewEditorRuntime,
2153
- sectionIndex: number,
2154
- ): void {
2155
- const snapshot = runtime.getRenderSnapshot();
2156
- if (!canApplyRuntimeMutation(snapshot) || snapshot.activeStory.kind !== "main") {
2157
- return;
2158
- }
2159
- if (emitWorkflowBlockedMutation(runtime, "deleteSectionBreak")) {
2160
- return;
2161
- }
2162
- if (isSelectionSuggesting(runtime)) {
2163
- runtime.emitBlockedCommand("deleteSectionBreak", [{
2164
- code: "unsupported_surface",
2165
- message: "Section break deletion is not supported in suggesting mode.",
2166
- }]);
2167
- return;
2168
- }
2169
-
2170
- const sessionState = runtime.getSessionState();
2171
- const timestamp = new Date().toISOString();
2172
- const result = deleteSectionBreakAtSectionIndex(
2173
- sessionState.canonicalDocument,
2174
- sectionIndex,
2175
- { timestamp },
2176
- );
2177
-
2178
- dispatchRuntimeDocumentMutation(
2179
- runtime,
2180
- {
2181
- changed: result.changed,
2182
- document: result.document,
2183
- selection: toRuntimeSelectionSnapshot(result.selection),
2184
- },
2185
- timestamp,
2186
- );
2187
- }
2188
-
2189
- function applyRuntimeUpdateSectionLayout(
2190
- runtime: WordReviewEditorRuntime,
2191
- sectionIndex: number,
2192
- patch: SectionLayoutPatch,
2193
- ): void {
2194
- const snapshot = runtime.getRenderSnapshot();
2195
- if (!canApplyRuntimeMutation(snapshot) || snapshot.activeStory.kind !== "main") {
2196
- return;
2197
- }
2198
- if (emitWorkflowBlockedMutation(runtime, "updateSectionLayout")) {
2199
- return;
2200
- }
2201
- if (isSelectionSuggesting(runtime)) {
2202
- runtime.emitBlockedCommand("updateSectionLayout", [{
2203
- code: "unsupported_surface",
2204
- message: "Section layout updates are not supported in suggesting mode.",
2205
- }]);
2206
- return;
2207
- }
2208
-
2209
- const sessionState = runtime.getSessionState();
2210
- const timestamp = new Date().toISOString();
2211
- const result = updateSectionLayoutAtSectionIndex(
2212
- sessionState.canonicalDocument,
2213
- sectionIndex,
2214
- {
2215
- ...(patch.pageSize ? { pageSize: patch.pageSize } : {}),
2216
- ...(patch.pageMargins ? { pageMargins: patch.pageMargins } : {}),
2217
- ...(patch.columns ? { columns: patch.columns } : {}),
2218
- ...(patch.titlePage !== undefined ? { titlePage: patch.titlePage } : {}),
2219
- ...(patch.sectionType ? { sectionType: patch.sectionType } : {}),
2220
- },
2221
- { timestamp },
2222
- );
2223
-
2224
- dispatchRuntimeDocumentMutation(
2225
- runtime,
2226
- {
2227
- changed: result.changed,
2228
- document: result.document,
2229
- selection: toRuntimeSelectionSnapshot(result.selection),
2230
- },
2231
- timestamp,
2232
- );
2233
- }
2234
-
2235
- function applyRuntimeSetSectionPageNumbering(
2236
- runtime: WordReviewEditorRuntime,
2237
- sectionIndex: number,
2238
- patch: SectionPageNumberingPatch | null,
2239
- ): void {
2240
- const snapshot = runtime.getRenderSnapshot();
2241
- if (!canApplyRuntimeMutation(snapshot) || snapshot.activeStory.kind !== "main") {
2242
- return;
2243
- }
2244
- if (emitWorkflowBlockedMutation(runtime, "setSectionPageNumbering")) {
2245
- return;
2246
- }
2247
- if (isSelectionSuggesting(runtime)) {
2248
- runtime.emitBlockedCommand("setSectionPageNumbering", [{
2249
- code: "unsupported_surface",
2250
- message: "Section page numbering updates are not supported in suggesting mode.",
2251
- }]);
2252
- return;
2253
- }
2254
-
2255
- const sessionState = runtime.getSessionState();
2256
- const timestamp = new Date().toISOString();
2257
- const normalizedPatch =
2258
- patch === null
2259
- ? null
2260
- : {
2261
- ...(patch.format !== undefined
2262
- ? { format: patch.format ?? undefined }
2263
- : {}),
2264
- ...(patch.start !== undefined
2265
- ? { start: patch.start ?? undefined }
2266
- : {}),
2267
- ...(patch.chapterStyle !== undefined
2268
- ? { chapStyle: patch.chapterStyle ?? undefined }
2269
- : {}),
2270
- ...(patch.chapterSeparator !== undefined
2271
- ? { chapSep: patch.chapterSeparator ?? undefined }
2272
- : {}),
2273
- };
2274
- const result = setSectionPageNumberingAtSectionIndex(
2275
- sessionState.canonicalDocument,
2276
- sectionIndex,
2277
- normalizedPatch,
2278
- { timestamp },
2279
- );
2280
-
2281
- dispatchRuntimeDocumentMutation(
2282
- runtime,
2283
- {
2284
- changed: result.changed,
2285
- document: result.document,
2286
- selection: toRuntimeSelectionSnapshot(result.selection),
2287
- },
2288
- timestamp,
2289
- );
2290
- }
2291
-
2292
- function applyRuntimeSetHeaderFooterLink(
2293
- runtime: WordReviewEditorRuntime,
2294
- sectionIndex: number,
2295
- patch: HeaderFooterLinkPatch,
2296
- ): void {
2297
- const snapshot = runtime.getRenderSnapshot();
2298
- if (!canApplyRuntimeMutation(snapshot) || snapshot.activeStory.kind !== "main") {
2299
- return;
2300
- }
2301
- if (emitWorkflowBlockedMutation(runtime, "setHeaderFooterLink")) {
2302
- return;
2303
- }
2304
- if (isSelectionSuggesting(runtime)) {
2305
- runtime.emitBlockedCommand("setHeaderFooterLink", [{
2306
- code: "unsupported_surface",
2307
- message: "Header and footer linkage updates are not supported in suggesting mode.",
2308
- }]);
2309
- return;
2310
- }
2311
-
2312
- const sessionState = runtime.getSessionState();
2313
- const timestamp = new Date().toISOString();
2314
- const result = setHeaderFooterLinkAtSectionIndex(
2315
- sessionState.canonicalDocument,
2316
- sectionIndex,
2317
- patch,
2318
- { timestamp },
2319
- );
2320
-
2321
- dispatchRuntimeDocumentMutation(
2322
- runtime,
2323
- {
2324
- changed: result.changed,
2325
- document: result.document,
2326
- selection: toRuntimeSelectionSnapshot(result.selection),
2327
- },
2328
- timestamp,
2329
- );
2330
- }
2331
-
2332
- function applyRuntimeInsertPageBreak(runtime: WordReviewEditorRuntime): void {
2333
- if (isSelectionSuggesting(runtime)) {
2334
- runtime.emitBlockedCommand("insertPageBreak", [{
2335
- code: "unsupported_surface",
2336
- message: "Page break insertion is not supported in suggesting mode.",
2337
- }]);
2338
- return;
2339
- }
2340
- const context = getStoryMutationContext(runtime, "insertPageBreak");
2341
- if (!context) {
2342
- return;
2343
- }
2344
-
2345
- const result = insertPageBreakInDocument(
2346
- context.localDocument,
2347
- toRuntimeSelectionSnapshot(context.localSnapshot.selection),
2348
- { timestamp: context.timestamp },
2349
- );
2350
- dispatchStoryMutationResult(runtime, context, result, context.timestamp);
2351
- }
2352
-
2353
- function applyRuntimeInsertTable(
2354
- runtime: WordReviewEditorRuntime,
2355
- options: InsertTableOptions,
2356
- ): void {
2357
- if (isSelectionSuggesting(runtime)) {
2358
- runtime.emitBlockedCommand("insertTable", [{
2359
- code: "unsupported_surface",
2360
- message: "Table insertion is not supported in suggesting mode.",
2361
- }]);
2362
- return;
2363
- }
2364
- const context = getStoryMutationContext(runtime, "insertTable");
2365
- if (!context) {
2366
- return;
2367
- }
2368
-
2369
- const result = insertTableInDocument(
2370
- context.localDocument,
2371
- toRuntimeSelectionSnapshot(context.localSnapshot.selection),
2372
- options,
2373
- { timestamp: context.timestamp },
2374
- );
2375
- dispatchStoryMutationResult(runtime, context, result, context.timestamp);
2376
- }
2377
-
2378
- function applyRuntimeInsertImage(
2379
- runtime: WordReviewEditorRuntime,
2380
- options: InsertImageOptions,
2381
- ): void {
2382
- if (isSelectionSuggesting(runtime)) {
2383
- runtime.emitBlockedCommand("insertImage", [{
2384
- code: "unsupported_surface",
2385
- message: "Image insertion is not supported in suggesting mode.",
2386
- }]);
2387
- return;
2388
- }
2389
- const context = getStoryMutationContext(runtime, "insertImage");
2390
- if (!context) {
2391
- return;
2392
- }
2393
-
2394
- try {
2395
- const result = insertImageInDocument(
2396
- context.localDocument,
2397
- toRuntimeSelectionSnapshot(context.localSnapshot.selection),
2398
- options.data,
2399
- options.mimeType,
2400
- options.width,
2401
- options.height,
2402
- {
2403
- timestamp: context.timestamp,
2404
- altText: options.altText,
2405
- },
2406
- );
2407
- dispatchStoryMutationResult(runtime, context, {
2408
- changed: true,
2409
- document: result.document,
2410
- selection: result.selection,
2411
- mapping: result.mapping,
2412
- }, context.timestamp);
2413
- } catch {
2414
- return;
2415
- }
2416
- }
2417
-
2418
- function applyRuntimeImageResize(
2419
- runtime: WordReviewEditorRuntime,
2420
- mediaId: string,
2421
- dimensions: { widthEmu: number; heightEmu: number },
2422
- ): void {
2423
- const snapshot = runtime.getRenderSnapshot();
2424
- if (!canApplyRuntimeMutation(snapshot)) {
2425
- return;
2426
- }
2427
- if (emitWorkflowBlockedMutation(runtime, "setImageLayout")) {
2428
- return;
2429
- }
2430
- if (isSelectionSuggesting(runtime)) {
2431
- runtime.emitBlockedCommand("setImageLayout", [{
2432
- code: "unsupported_surface",
2433
- message: "Image resize is not supported in suggesting mode.",
2434
- }]);
2435
- return;
2436
- }
2437
-
2438
- try {
2439
- const sessionState = runtime.getSessionState();
2440
- const result = resizeImageInCatalog(
2441
- sessionState.canonicalDocument,
2442
- mediaId,
2443
- dimensions,
2444
- );
2445
- runtime.dispatch({
2446
- type: "document.replace",
2447
- document: result.document,
2448
- selection: toRuntimeSelectionSnapshot(snapshot.selection),
2449
- origin: { source: "api", timestamp: new Date().toISOString() },
2450
- });
2451
- } catch {
2452
- return;
2453
- }
2454
- }
2455
-
2456
- function applyRuntimeImageReposition(
2457
- runtime: WordReviewEditorRuntime,
2458
- mediaId: string,
2459
- offsets: { horizontalOffsetEmu?: number; verticalOffsetEmu?: number },
2460
- ): void {
2461
- if (emitWorkflowBlockedMutation(runtime, "setImageFrame")) {
2462
- return;
2463
- }
2464
- if (isSelectionSuggesting(runtime)) {
2465
- runtime.emitBlockedCommand("setImageFrame", [{
2466
- code: "unsupported_surface",
2467
- message: "Image reposition is not supported in suggesting mode.",
2468
- }]);
2469
- return;
2470
- }
2471
- const context = getStoryMutationContext(runtime, "setImageFrame");
2472
- if (!context) {
2473
- return;
2474
- }
2475
-
2476
- try {
2477
- const result = repositionFloatingImageInDocument(
2478
- context.localDocument,
2479
- mediaId,
2480
- offsets,
2481
- context.timestamp,
2482
- );
2483
- dispatchStoryMutationResult(
2484
- runtime,
2485
- context,
2486
- {
2487
- changed: true,
2488
- document: result.document,
2489
- selection: toRuntimeSelectionSnapshot(context.localSnapshot.selection),
2490
- },
2491
- context.timestamp,
2492
- );
2493
- } catch {
2494
- return;
2495
- }
2496
- }
2497
-
2498
- // deriveViewState removed — the runtime's getViewState() is now the single
2499
- // source of truth for EditorViewStateSnapshot, backed by view-state.ts.
2500
-
2501
- function applyRuntimeTableStructureOperation(
2502
- runtime: WordReviewEditorRuntime,
2503
- mountedSurface: TwProseMirrorSurfaceRef | null | undefined,
2504
- operation:
2505
- | { type: "add-row-before" }
2506
- | { type: "add-row-after" }
2507
- | { type: "add-column-before" }
2508
- | { type: "add-column-after" }
2509
- | { type: "delete-row" }
2510
- | { type: "delete-column" }
2511
- | { type: "delete-table" }
2512
- | { type: "merge-cells" }
2513
- | { type: "split-cell" }
2514
- | { type: "set-cell-background"; color: string },
2515
- ): void {
2516
- if (isSelectionSuggesting(runtime)) {
2517
- runtime.emitBlockedCommand(`table.${operation.type}`, [{
2518
- code: "unsupported_surface",
2519
- message: `Table operation "${operation.type}" is not supported in suggesting mode.`,
2520
- }]);
2521
- return;
2522
- }
2523
- const context = getStoryMutationContext(runtime, `table.${operation.type}`);
2524
- if (!context) {
2525
- return;
2526
- }
2527
-
2528
- const result = applyTableStructureOperation(
2529
- context.localDocument,
2530
- context.localSnapshot,
2531
- mountedSurface?.getTableSelection() ?? null,
2532
- operation,
2533
- );
2534
- dispatchStoryMutationResult(runtime, context, result, context.timestamp);
2535
- }
2536
-
2537
- function applyRuntimeTextCommand(
2538
- runtime: WordReviewEditorRuntime,
2539
- command:
2540
- | { type: "insert-text"; text: string }
2541
- | { type: "delete-backward" }
2542
- | { type: "delete-forward" }
2543
- | { type: "insert-tab" }
2544
- | { type: "outdent-tab" }
2545
- | { type: "insert-hard-break" }
2546
- | { type: "split-paragraph" },
2547
- ): void {
2548
- const snapshot = runtime.getRenderSnapshot();
2549
- const context = getStoryMutationContext(runtime, getMountedTextCommandName(command));
2550
- if (!context) {
2551
- return;
2552
- }
2553
-
2554
- const effectiveSelectionMode = runtime.getInteractionGuardSnapshot().effectiveMode;
2555
- const listAwareResult = applyListAwareTextCommand(context, command);
2556
- if (effectiveSelectionMode === "suggest" && listAwareResult) {
2557
- runtime.emitBlockedCommand(getMountedTextCommandName(command), [{
2558
- code: "suggesting_unsupported",
2559
- message: "List structure changes are not supported in suggesting mode.",
2560
- }]);
2561
- return;
2562
- }
2563
-
2564
- if (listAwareResult) {
2565
- dispatchStoryMutationResult(runtime, context, listAwareResult, context.timestamp);
2566
- return;
2567
- }
2568
-
2569
- switch (command.type) {
2570
- case "insert-text":
2571
- runtime.applyActiveStoryTextCommand({ type: "text.insert", text: command.text });
2572
- return;
2573
- case "delete-backward":
2574
- runtime.applyActiveStoryTextCommand({ type: "text.delete-backward" });
2575
- return;
2576
- case "delete-forward":
2577
- runtime.applyActiveStoryTextCommand({ type: "text.delete-forward" });
2578
- return;
2579
- case "insert-tab":
2580
- runtime.applyActiveStoryTextCommand({ type: "text.insert-tab" });
2581
- return;
2582
- case "outdent-tab":
2583
- return;
2584
- case "insert-hard-break":
2585
- runtime.applyActiveStoryTextCommand({ type: "text.insert-hard-break" });
2586
- return;
2587
- case "split-paragraph":
2588
- runtime.applyActiveStoryTextCommand({ type: "paragraph.split" });
2589
- return;
2590
- }
2591
- }
2592
-
2593
- function getMountedTextCommandName(
2594
- command:
2595
- | { type: "insert-text"; text: string }
2596
- | { type: "delete-backward" }
2597
- | { type: "delete-forward" }
2598
- | { type: "insert-tab" }
2599
- | { type: "outdent-tab" }
2600
- | { type: "insert-hard-break" }
2601
- | { type: "split-paragraph" },
2602
- ): string {
2603
- switch (command.type) {
2604
- case "insert-text":
2605
- return "text.insert";
2606
- case "delete-backward":
2607
- return "text.delete-backward";
2608
- case "delete-forward":
2609
- return "text.delete-forward";
2610
- case "insert-tab":
2611
- case "outdent-tab":
2612
- return "text.insert-tab";
2613
- case "insert-hard-break":
2614
- return "text.insert-hard-break";
2615
- case "split-paragraph":
2616
- return "paragraph.split";
2617
- }
2618
- }
2619
-
2620
- function applyListAwareTextCommand(
2621
- context: NonNullable<ReturnType<typeof getStoryMutationContext>>,
2622
- command:
2623
- | { type: "insert-text"; text: string }
2624
- | { type: "delete-backward" }
2625
- | { type: "delete-forward" }
2626
- | { type: "insert-tab" }
2627
- | { type: "outdent-tab" }
2628
- | { type: "insert-hard-break" }
2629
- | { type: "split-paragraph" },
2630
- ): {
2631
- changed: boolean;
2632
- document: EditorSessionState["canonicalDocument"];
2633
- selection: InternalSelectionSnapshot;
2634
- } | null {
2635
- const paragraphContext = resolveActiveParagraphContext(context.localSnapshot);
2636
- if (!paragraphContext?.paragraph.numbering) {
2637
- return null;
2638
- }
2639
-
2640
- switch (command.type) {
2641
- case "insert-tab": {
2642
- const result = indentListItems(
2643
- context.localDocument,
2644
- [paragraphContext.paragraphIndex],
2645
- { timestamp: context.timestamp },
2646
- );
2647
- return createListMutationResult(result, context.localSnapshot.selection);
2648
- }
2649
- case "outdent-tab": {
2650
- const result = outdentListItems(
2651
- context.localDocument,
2652
- [paragraphContext.paragraphIndex],
2653
- { timestamp: context.timestamp },
2654
- );
2655
- return createListMutationResult(result, context.localSnapshot.selection);
2656
- }
2657
- case "delete-backward": {
2658
- if (!paragraphContext.atParagraphStart || !context.localSnapshot.selection.isCollapsed) {
2659
- return null;
2660
- }
2661
- const result = backspaceAtListStart(
2662
- context.localDocument,
2663
- paragraphContext.paragraphIndex,
2664
- { timestamp: context.timestamp },
2665
- );
2666
- return result.handled
2667
- ? createListMutationResult(result, context.localSnapshot.selection)
2668
- : null;
2669
- }
2670
- case "split-paragraph": {
2671
- if (!context.localSnapshot.selection.isCollapsed || !paragraphContext.isEmpty) {
2672
- return null;
2673
- }
2674
- const result = splitListParagraph(
2675
- context.localDocument,
2676
- paragraphContext.paragraphIndex,
2677
- true,
2678
- { timestamp: context.timestamp },
2679
- );
2680
- return result.action === "split"
2681
- ? null
2682
- : createListMutationResult(result, context.localSnapshot.selection);
2683
- }
2684
- default:
2685
- return null;
2686
- }
2687
- }
2688
-
2689
- function createListMutationResult(
2690
- result: {
2691
- document: EditorSessionState["canonicalDocument"];
2692
- affectedParagraphIndexes: number[];
2693
- },
2694
- selection: RuntimeRenderSnapshot["selection"],
2695
- ): {
2696
- changed: boolean;
2697
- document: EditorSessionState["canonicalDocument"];
2698
- selection: InternalSelectionSnapshot;
2699
- } {
2700
- return {
2701
- changed: result.affectedParagraphIndexes.length > 0,
2702
- document: result.document,
2703
- selection: toRuntimeSelectionSnapshot(selection),
2704
- };
2705
- }
2706
-
2707
- function resolveActiveParagraphContext(
2708
- snapshot: Pick<RuntimeRenderSnapshot, "surface" | "selection">,
2709
- ): {
2710
- paragraphIndex: number;
2711
- paragraph: Extract<SurfaceBlockSnapshot, { kind: "paragraph" }>;
2712
- atParagraphStart: boolean;
2713
- isEmpty: boolean;
2714
- } | null {
2715
- if (!snapshot.surface) {
2716
- return null;
2717
- }
2718
-
2719
- const paragraphIndex = resolveActiveParagraphIndex(
2720
- snapshot.surface.blocks,
2721
- snapshot.selection,
2722
- );
2723
- if (paragraphIndex === null) {
2724
- return null;
2725
- }
2726
-
2727
- const selectionPosition =
2728
- snapshot.selection.activeRange.kind === "node"
2729
- ? snapshot.selection.activeRange.at
2730
- : snapshot.selection.head;
2731
- const paragraph = findSurfaceParagraphAtPosition(snapshot.surface.blocks, selectionPosition);
2732
- if (!paragraph) {
2733
- return null;
2734
- }
2735
-
2736
- return {
2737
- paragraphIndex,
2738
- paragraph,
2739
- atParagraphStart:
2740
- snapshot.selection.isCollapsed &&
2741
- snapshot.selection.activeRange.kind !== "node" &&
2742
- snapshot.selection.anchor === snapshot.selection.head &&
2743
- snapshot.selection.head === paragraph.from,
2744
- isEmpty: isSurfaceParagraphEmpty(paragraph),
2745
- };
2746
- }
2747
-
2748
- function findSurfaceParagraphAtPosition(
2749
- blocks: readonly SurfaceBlockSnapshot[],
2750
- position: number,
2751
- ): Extract<SurfaceBlockSnapshot, { kind: "paragraph" }> | null {
2752
- for (const block of blocks) {
2753
- if (position < block.from || position > block.to) {
2754
- continue;
2755
- }
2756
- if (block.kind === "paragraph") {
2757
- return block;
2758
- }
2759
- if (block.kind === "table") {
2760
- for (const row of block.rows) {
2761
- for (const cell of row.cells) {
2762
- const paragraph = findSurfaceParagraphAtPosition(cell.content, position);
2763
- if (paragraph) {
2764
- return paragraph;
2765
- }
2766
- }
2767
- }
2768
- continue;
2769
- }
2770
- if (block.kind === "sdt_block") {
2771
- const paragraph = findSurfaceParagraphAtPosition(block.children, position);
2772
- if (paragraph) {
2773
- return paragraph;
2774
- }
2775
- }
2776
- }
2777
- return null;
2778
- }
2779
-
2780
- function isSurfaceParagraphEmpty(
2781
- paragraph: Extract<SurfaceBlockSnapshot, { kind: "paragraph" }>,
2782
- ): boolean {
2783
- if (paragraph.segments.length === 0) {
2784
- return true;
2785
- }
2786
- return paragraph.segments.every((segment) => segment.kind === "text" && segment.text.length === 0);
2787
- }
2788
-
2789
- function applyRuntimeSelection(
2790
- runtime: WordReviewEditorRuntime,
2791
- selection: PublicSelectionSnapshot,
2792
- ): void {
2793
- const requestedStory = selection.storyTarget ?? { kind: "main" };
2794
- if (requestedStory.kind === "main") {
2795
- runtime.closeStory();
2796
- } else if (!storyTargetsEqual(runtime.getActiveStory(), requestedStory)) {
2797
- if (!runtime.openStory(requestedStory)) {
2798
- return;
2799
- }
2800
- }
2801
-
2802
- runtime.dispatch({
2803
- type: "selection.set",
2804
- selection: toRuntimeSelectionSnapshot(stripStoryTarget(selection)),
2805
- });
2806
- }
2807
-
2808
- function canApplyRuntimeMutation(snapshot: RuntimeRenderSnapshot): boolean {
2809
- return snapshot.isReady && !snapshot.readOnly && !snapshot.fatalError;
2810
- }
2811
-
2812
- function emitWorkflowBlockedMutation(
2813
- runtime: WordReviewEditorRuntime,
2814
- command: string,
2815
- ): boolean {
2816
- const interactionGuardSnapshot = runtime.getInteractionGuardSnapshot();
2817
- if (interactionGuardSnapshot.blockedReasons.length === 0) {
2818
- return false;
2819
- }
2820
- runtime.emitBlockedCommand(command, interactionGuardSnapshot.blockedReasons);
2821
- return true;
2822
- }
2823
-
2824
- function getStoryMutationContext(
2825
- runtime: WordReviewEditorRuntime,
2826
- command?: string,
2827
- ): {
2828
- timestamp: string;
2829
- activeStory: EditorStoryTarget;
2830
- persistedDocument: EditorSessionState["canonicalDocument"];
2831
- localDocument: EditorSessionState["canonicalDocument"];
2832
- localSnapshot: RuntimeRenderSnapshot;
2833
- } | null {
2834
- const snapshot = runtime.getRenderSnapshot();
2835
- if (!canApplyRuntimeMutation(snapshot)) {
2836
- return null;
2837
- }
2838
- if (command && emitWorkflowBlockedMutation(runtime, command)) {
2839
- return null;
2840
- }
2841
-
2842
- const persistedDocument = runtime.getSessionState().canonicalDocument;
2843
- const activeStory = snapshot.activeStory;
2844
- if (activeStory.kind === "main") {
2845
- return {
2846
- timestamp: new Date().toISOString(),
2847
- activeStory,
2848
- persistedDocument,
2849
- localDocument: persistedDocument,
2850
- localSnapshot: snapshot,
2851
- };
2852
- }
2853
-
2854
- return {
2855
- timestamp: new Date().toISOString(),
2856
- activeStory,
2857
- persistedDocument,
2858
- localDocument: {
2859
- ...persistedDocument,
2860
- content: {
2861
- type: "doc",
2862
- children: [...getStoryBlocks(persistedDocument, activeStory)],
2863
- },
2864
- },
2865
- localSnapshot: {
2866
- ...snapshot,
2867
- activeStory: { kind: "main" },
2868
- selection: stripStoryTarget(snapshot.selection),
2869
- },
2870
- };
2871
- }
2872
-
2873
- function dispatchStoryMutationResult(
2874
- runtime: WordReviewEditorRuntime,
2875
- context: {
2876
- activeStory: EditorStoryTarget;
2877
- persistedDocument: EditorSessionState["canonicalDocument"];
2878
- },
2879
- result: {
2880
- changed: boolean;
2881
- document: EditorSessionState["canonicalDocument"];
2882
- selection: InternalSelectionSnapshot;
2883
- mapping?: TransactionMapping;
2884
- },
2885
- timestamp: string,
2886
- ): void {
2887
- if (context.activeStory.kind === "main") {
2888
- dispatchRuntimeDocumentMutation(runtime, result, timestamp);
2889
- return;
2890
- }
2891
-
2892
- if (!result.changed) {
2893
- return;
2894
- }
2895
-
2896
- const nextDocument = replaceStoryBlocks(
2897
- context.persistedDocument,
2898
- context.activeStory,
2899
- result.document.content.children,
2900
- );
2901
- dispatchRuntimeDocumentMutation(
2902
- runtime,
2903
- {
2904
- changed: true,
2905
- document: nextDocument,
2906
- selection: result.selection,
2907
- },
2908
- timestamp,
2909
- );
2910
- }
2911
-
2912
- function dispatchRuntimeDocumentMutation(
2913
- runtime: WordReviewEditorRuntime,
2914
- result: {
2915
- changed: boolean;
2916
- document: EditorSessionState["canonicalDocument"];
2917
- selection: InternalSelectionSnapshot;
2918
- mapping?: TransactionMapping;
2919
- },
2920
- timestamp: string,
2921
- ): void {
2922
- if (!result.changed) {
2923
- return;
2924
- }
2925
-
2926
- runtime.dispatch({
2927
- type: "document.replace",
2928
- document: {
2929
- ...result.document,
2930
- updatedAt: timestamp,
2931
- },
2932
- mapping: result.mapping,
2933
- selection: result.selection,
2934
- origin: {
2935
- source: "api",
2936
- timestamp,
2937
- },
2938
- });
2939
- }
2940
-
2941
- function stripStoryTarget(
2942
- selection: PublicSelectionSnapshot,
2943
- ): PublicSelectionSnapshot {
2944
- const { storyTarget: _storyTarget, ...rest } = selection;
2945
- return rest;
2946
- }
2947
-
2948
- function applyRuntimeDeleteComment(
2949
- runtime: WordReviewEditorRuntime,
2950
- commentId: string,
2951
- ): void {
2952
- const snapshot = runtime.getRenderSnapshot();
2953
- if (!snapshot.isReady || snapshot.readOnly || snapshot.fatalError) {
2954
- return;
2955
- }
2956
-
2957
- const sessionState = runtime.getSessionState();
2958
- if (!sessionState.canonicalDocument.review.comments[commentId]) {
2959
- return;
2960
- }
2961
-
2962
- const nextComments = {
2963
- ...sessionState.canonicalDocument.review.comments,
2964
- };
2965
- delete nextComments[commentId];
2966
-
2967
- runtime.dispatch({
2968
- type: "document.replace",
2969
- document: {
2970
- ...sessionState.canonicalDocument,
2971
- review: {
2972
- ...sessionState.canonicalDocument.review,
2973
- comments: nextComments,
2974
- },
2975
- },
2976
- selection: toRuntimeSelectionSnapshot(snapshot.selection),
2977
- origin: {
2978
- source: "api",
2979
- timestamp: new Date().toISOString(),
2980
- },
2981
- });
2982
- }
2983
-
2984
- function normalizeRequestedSelection(
2985
- snapshot: RuntimeRenderSnapshot,
2986
- selection: PublicSelectionSnapshot | null,
2987
- ): PublicSelectionSnapshot {
2988
- return (
2989
- selection ??
2990
- createCollapsedPublicSelection(
2991
- snapshot.selection.head,
2992
- snapshot.activeStory.kind === "main" ? undefined : snapshot.activeStory,
2993
- )
2994
- );
2995
- }
2996
-
2997
- export function __resolveLiveMarkupDisplay(
2998
- requested: MarkupDisplay | undefined,
2999
- isPageWorkspace: boolean,
3000
- ): MarkupDisplay {
3001
- return requested ?? (isPageWorkspace ? "all" : "clean");
3002
- }
3003
-
3004
- function createCollapsedPublicSelection(
3005
- position: number,
3006
- storyTarget?: EditorStoryTarget,
3007
- ): PublicSelectionSnapshot {
3008
- return {
3009
- anchor: position,
3010
- head: position,
3011
- isCollapsed: true,
3012
- activeRange: {
3013
- kind: "range",
3014
- from: position,
3015
- to: position,
3016
- assoc: {
3017
- start: -1,
3018
- end: 1,
3019
- },
3020
- },
3021
- ...(storyTarget ? { storyTarget } : {}),
3022
- };
3023
- }
3024
-
3025
- function clonePublicValue<T>(value: T): T {
3026
- return structuredClone(value);
3027
- }
3028
-
3029
- function openDefaultStoryVariant(
3030
- runtime: WordReviewEditorRuntime,
3031
- pageLayout: PageLayoutSnapshot | undefined,
3032
- navigation: ReturnType<WordReviewEditorRuntime["getDocumentNavigationSnapshot"]> | undefined,
3033
- kind: "header" | "footer",
3034
- ): void {
3035
- const variants =
3036
- kind === "header"
3037
- ? pageLayout?.headerVariants
3038
- : pageLayout?.footerVariants;
3039
- const activePage = navigation?.pages[navigation.activePageIndex];
3040
- const isFirstPageInSection =
3041
- activePage !== undefined &&
3042
- activePage.sectionIndex === pageLayout?.sectionIndex &&
3043
- activePage.pageInSection === 0;
3044
- const isEvenDocumentPage = activePage !== undefined && (activePage.pageIndex + 1) % 2 === 0;
3045
-
3046
- let variant =
3047
- pageLayout?.differentFirstPage && isFirstPageInSection
3048
- ? variants?.find((entry) => entry.variant === "first")
3049
- : undefined;
3050
-
3051
- if (!variant && pageLayout?.differentOddEvenPages && isEvenDocumentPage) {
3052
- variant = variants?.find((entry) => entry.variant === "even");
3053
- }
3054
-
3055
- if (!variant) {
3056
- variant = variants?.find((entry) => entry.variant === "default") ?? variants?.[0];
3057
- }
3058
-
3059
- if (!variant) {
3060
- return;
3061
- }
3062
- runtime.openStory({
3063
- kind,
3064
- relationshipId: variant.relationshipId,
3065
- variant: variant.variant,
3066
- sectionIndex: pageLayout?.sectionIndex,
3067
- });
3068
- }
3069
-
3070
- function searchRuntimeDocument(
3071
- runtime: WordReviewEditorRuntime,
3072
- mountedSurface: TwProseMirrorSurfaceRef | null,
3073
- query: string,
3074
- options: SearchOptions = {},
3075
- ): SearchResultSnapshot[] {
3076
- if (mountedSurface) {
3077
- return mountedSurface.search(query, options);
3078
- }
3079
-
3080
- const snapshot = runtime.getRenderSnapshot();
3081
- return searchDocument(
3082
- runtime.getSessionState().canonicalDocument,
3083
- snapshot.selection,
3084
- snapshot.activeStory,
3085
- runtime.getDocumentNavigationSnapshot(),
3086
- query,
3087
- options,
3088
- );
3089
- }
3090
-
3091
- function applyRegionAttributes(shell: HTMLElement): void {
3092
- const toolbar = shell.querySelector<HTMLElement>("header");
3093
- if (toolbar) {
3094
- toolbar.dataset.wreRegion = "toolbar";
3095
- toolbar.setAttribute("role", toolbar.getAttribute("role") ?? "toolbar");
3096
- toolbar.setAttribute("aria-label", toolbar.getAttribute("aria-label") ?? "Editor toolbar");
3097
- toolbar.tabIndex = -1;
3098
- }
3099
-
3100
- const documentSurface = shell.querySelector<HTMLElement>('[aria-label="Document surface"]');
3101
- if (documentSurface) {
3102
- documentSurface.dataset.wreRegion = "document";
3103
- }
3104
-
3105
- const reviewRail = shell.querySelector<HTMLElement>('[aria-label="Review rail"]');
3106
- if (reviewRail) {
3107
- reviewRail.dataset.wreRegion = "review-rail";
3108
- reviewRail.tabIndex = -1;
3109
- }
3110
-
3111
- const statusBar = shell.querySelector<HTMLElement>("footer");
3112
- if (statusBar) {
3113
- statusBar.dataset.wreRegion = "status";
3114
- statusBar.setAttribute("role", statusBar.getAttribute("role") ?? "status");
3115
- statusBar.setAttribute("aria-label", statusBar.getAttribute("aria-label") ?? "Editor status bar");
3116
- statusBar.tabIndex = -1;
3117
- }
3118
- }
3119
-
3120
- function focusRelativeRegion(shell: HTMLElement, direction: -1 | 1): void {
3121
- const activeRegion = getActiveRegionId(shell);
3122
- const startIndex =
3123
- activeRegion === null ? (direction === 1 ? -1 : 0) : ACCESSIBLE_REGION_ORDER.indexOf(activeRegion);
3124
-
3125
- for (let offset = 1; offset <= ACCESSIBLE_REGION_ORDER.length; offset += 1) {
3126
- const index =
3127
- (startIndex + direction * offset + ACCESSIBLE_REGION_ORDER.length) %
3128
- ACCESSIBLE_REGION_ORDER.length;
3129
- const regionId = ACCESSIBLE_REGION_ORDER[index];
3130
- const target = findRegionFocusTarget(shell, regionId);
3131
- if (target) {
3132
- target.focus();
3133
- return;
3134
- }
3135
- }
3136
- }
3137
-
3138
- function getActiveRegionId(shell: HTMLElement): AccessibleRegionId | null {
3139
- const activeElement = shell.ownerDocument.activeElement;
3140
- if (!(activeElement instanceof HTMLElement)) {
3141
- return null;
3142
- }
3143
-
3144
- const region = activeElement.closest<HTMLElement>("[data-wre-region]");
3145
- const regionId = region?.dataset.wreRegion;
3146
- return isAccessibleRegionId(regionId) ? regionId : null;
3147
- }
3148
-
3149
- function findRegionFocusTarget(
3150
- shell: HTMLElement,
3151
- regionId: AccessibleRegionId,
3152
- ): HTMLElement | null {
3153
- const region = shell.querySelector<HTMLElement>(`[data-wre-region="${regionId}"]`);
3154
- if (!region) {
3155
- return null;
3156
- }
3157
-
3158
- if (regionId === "document" || regionId === "toolbar" || regionId === "review-rail" || regionId === "status") {
3159
- return region;
3160
- }
3161
-
3162
- return null;
3163
- }
3164
-
3165
- function isAccessibleRegionId(value: string | undefined): value is AccessibleRegionId {
3166
- return value === "toolbar" || value === "document" || value === "review-rail" || value === "status";
3167
- }
3168
-
3169
- function buildAccessibilityStatusMessage(
3170
- snapshot: RuntimeRenderSnapshot,
3171
- loadError?: EditorError,
3172
- ): string {
3173
- if (loadError) {
3174
- return `Editor failed to load. ${loadError.message}`;
3175
- }
3176
-
3177
- if (!snapshot.isReady) {
3178
- return "Editor loading. Document surface is not ready yet.";
3179
- }
3180
-
3181
- if (snapshot.fatalError) {
3182
- return `Editor opened in diagnostics mode. ${snapshot.fatalError.message}`;
3183
- }
3184
-
3185
- return [
3186
- snapshot.readOnly ? "Read-only mode." : "Editing enabled.",
3187
- `${snapshot.comments.totalCount} comment${snapshot.comments.totalCount === 1 ? "" : "s"}.`,
3188
- `${snapshot.trackedChanges.totalCount} tracked change${
3189
- snapshot.trackedChanges.totalCount === 1 ? "" : "s"
3190
- }.`,
3191
- snapshot.compatibility.blockExport ? "Export blocked." : "Export available.",
3192
- ].join(" ");
3193
- }
3194
-
3195
- function getDiagnosticsModeMessage(error?: EditorError | null): string | null {
3196
- if (!error) {
3197
- return null;
3198
- }
3199
-
3200
- if (error.code === "package_corrupt") {
3201
- return `${error.message} The document opened in read-only diagnostics mode so you can inspect the issue safely, but editing and export stay blocked until you reload a valid .docx package.`;
3202
- }
3203
-
3204
- if (error.code === "validation_failed") {
3205
- return `${error.message} The document opened in read-only diagnostics mode because OOXML validation failed, so editing and export stay blocked until the source package is repaired.`;
3206
- }
3207
-
3208
- return error.isFatal ? error.message : null;
3209
- }
3210
-
3211
- function normalizeEditorError(error: unknown): EditorError {
3212
- if (
3213
- typeof error === "object" &&
3214
- error !== null &&
3215
- "errorId" in error &&
3216
- "code" in error &&
3217
- "message" in error
3218
- ) {
3219
- return error as EditorError;
3220
- }
3221
-
3222
- return {
3223
- errorId: "word-review-editor-load",
3224
- code: "internal_invariant",
3225
- message: error instanceof Error ? error.message : "Unknown editor load failure.",
3226
- isFatal: true,
3227
- source: "runtime",
3228
- };
3229
- }
3230
-
3231
- function guessSourceLabel(
3232
- initialSourceLabel?: string,
3233
- initialSessionState?: EditorSessionState,
3234
- initialSnapshot?: PersistedEditorSnapshot,
3235
- externalDocSource?: WordReviewEditorProps["externalDocSource"],
3236
- ): string | undefined {
3237
- return (
3238
- externalDocSource?.sourceLabel ??
3239
- (externalDocSource?.kind === "session"
3240
- ? externalDocSource.sessionState.sourcePackage?.sourceLabel
3241
- : undefined) ??
3242
- (externalDocSource?.kind === "snapshot"
3243
- ? externalDocSource.snapshot.sourcePackage?.sourceLabel
3244
- : undefined) ??
3245
- initialSourceLabel ??
3246
- initialSessionState?.sourcePackage?.sourceLabel ??
3247
- initialSessionState?.editorBuild ??
3248
- initialSnapshot?.sourcePackage?.sourceLabel ??
3249
- initialSnapshot?.editorBuild ??
3250
- undefined
3251
- );
3252
- }
3253
-
3254
- function deriveEditorViewMode(
3255
- readOnly: boolean,
3256
- reviewMode: WordReviewEditorProps["reviewMode"] = "review",
3257
- ): EditorViewMode {
3258
- if (readOnly) {
3259
- return "view";
3260
- }
3261
- return reviewMode === "editing" ? "editing" : "review";
3262
- }
3263
-
3264
- function resolveWordReviewEditorChromeVisibility(
3265
- chromeVisibility: WordReviewEditorProps["chromeVisibility"],
3266
- showReviewPanel: boolean,
3267
- ): Partial<WordReviewEditorChromeVisibility> {
3268
- const legacyVisibility =
3269
- showReviewPanel
3270
- ? {}
3271
- : { reviewRail: false } satisfies Partial<WordReviewEditorChromeVisibility>;
3272
- return {
3273
- ...legacyVisibility,
3274
- ...chromeVisibility,
3275
- };
3276
- }
3277
-
3278
- function toRuntimeSelectionSnapshot(selection: PublicSelectionSnapshot) {
3279
- return {
3280
- anchor: selection.anchor,
3281
- head: selection.head,
3282
- isCollapsed: selection.isCollapsed,
3283
- activeRange:
3284
- selection.activeRange.kind === "range"
3285
- ? createRangeAnchor(
3286
- selection.activeRange.from,
3287
- selection.activeRange.to,
3288
- selection.activeRange.assoc,
3289
- )
3290
- : selection.activeRange.kind === "node"
3291
- ? createNodeAnchor(selection.activeRange.at, selection.activeRange.assoc)
3292
- : createDetachedAnchor(
3293
- selection.activeRange.lastKnownRange,
3294
- selection.activeRange.reason,
3295
- ),
3296
- };
3297
- }
3298
-
3299
- function createSelectionFromAnchor(
3300
- anchor: PublicSelectionSnapshot["activeRange"],
3301
- storyTarget?: EditorStoryTarget,
3302
- ): PublicSelectionSnapshot {
3303
- switch (anchor.kind) {
3304
- case "range":
3305
- return {
3306
- anchor: anchor.from,
3307
- head: anchor.to,
3308
- isCollapsed: anchor.from === anchor.to,
3309
- activeRange: anchor,
3310
- ...(storyTarget ? { storyTarget } : {}),
3311
- };
3312
- case "node":
3313
- return {
3314
- anchor: anchor.at,
3315
- head: anchor.at,
3316
- isCollapsed: true,
3317
- activeRange: anchor,
3318
- ...(storyTarget ? { storyTarget } : {}),
3319
- };
3320
- case "detached":
3321
- return {
3322
- anchor: anchor.lastKnownRange.from,
3323
- head: anchor.lastKnownRange.to,
3324
- isCollapsed: anchor.lastKnownRange.from === anchor.lastKnownRange.to,
3325
- activeRange: anchor,
3326
- ...(storyTarget ? { storyTarget } : {}),
3327
- };
3328
- }
3329
- }
3330
-
3331
- function estimateStoryLength(
3332
- sessionStateOrSnapshot?: EditorSessionState | PersistedEditorSnapshot,
3333
- ): number {
3334
- if (!sessionStateOrSnapshot) {
3335
- return 0;
3336
- }
3337
-
3338
- const content = "sessionVersion" in sessionStateOrSnapshot
3339
- ? sessionStateOrSnapshot.canonicalDocument.content
3340
- : sessionStateOrSnapshot.canonicalDocument.content;
3341
- return Array.isArray(content?.children) ? content.children.length : 0;
3342
- }
3343
-
3344
- function collapsedSelection(): RuntimeRenderSnapshot["selection"] {
3345
- return {
3346
- anchor: 0,
3347
- head: 0,
3348
- isCollapsed: true,
3349
- activeRange: {
3350
- kind: "range",
3351
- from: 0,
3352
- to: 0,
3353
- assoc: {
3354
- start: -1,
3355
- end: 1,
3356
- },
3357
- },
3358
- };
3359
- }
3360
-
3361
- function toUint8Array(bytes: Uint8Array | ArrayBuffer): Uint8Array {
3362
- return bytes instanceof Uint8Array ? new Uint8Array(bytes) : new Uint8Array(bytes);
3363
- }
3364
-
3365
- function summarizeSelectionPreview(snapshot: RuntimeRenderSnapshot): string | null {
3366
- if (!snapshot.surface || snapshot.selection.isCollapsed) {
3367
- return null;
3368
- }
3369
-
3370
- const range = snapshot.selection.activeRange;
3371
- if (range.kind !== "range") {
3372
- return "Selected range";
3373
- }
3374
-
3375
- const preview = snapshot.surface.plainText
3376
- .slice(range.from, range.to)
3377
- .replace(/\s+/g, " ")
3378
- .trim();
3379
-
3380
- if (!preview) {
3381
- return "Selected range";
3382
- }
3383
-
3384
- return preview.length > 48 ? `${preview.slice(0, 45)}...` : preview;
3385
- }
3386
-
3387
- function selectionToolbarAnchorsEqual(
3388
- left: SelectionToolbarAnchor | null,
3389
- right: SelectionToolbarAnchor | null,
3390
- ): boolean {
3391
- if (left === right) {
3392
- return true;
3393
- }
3394
- if (!left || !right) {
3395
- return false;
3396
- }
3397
- return (
3398
- left.left === right.left &&
3399
- left.right === right.right &&
3400
- left.top === right.top &&
3401
- left.bottom === right.bottom
3402
- );
3403
- }
3404
-
3405
- function workflowScopeSnapshotsEqual(
3406
- left: WorkflowScopeSnapshot | null,
3407
- right: WorkflowScopeSnapshot | null,
3408
- ): boolean {
3409
- if (left === right) {
3410
- return true;
3411
- }
3412
- if (!left || !right) {
3413
- return false;
3414
- }
3415
- return (
3416
- left.overlayPresent === right.overlayPresent &&
3417
- left.activeWorkItemId === right.activeWorkItemId &&
3418
- left.activeWorkItem === right.activeWorkItem &&
3419
- left.scopes === right.scopes &&
3420
- left.candidates === right.candidates &&
3421
- workflowBlockedReasonsEqual(left.blockedReasons, right.blockedReasons)
3422
- );
3423
- }
3424
-
3425
- function interactionGuardSnapshotsEqual(
3426
- left: InteractionGuardSnapshot,
3427
- right: InteractionGuardSnapshot,
3428
- ): boolean {
3429
- if (left === right) {
3430
- return true;
3431
- }
3432
- return (
3433
- left.effectiveMode === right.effectiveMode &&
3434
- left.matchedScopeId === right.matchedScopeId &&
3435
- left.matchedScopeMode === right.matchedScopeMode &&
3436
- left.disabledReason === right.disabledReason &&
3437
- workflowBlockedReasonsEqual(left.blockedReasons, right.blockedReasons)
3438
- );
3439
- }
3440
-
3441
- function workflowBlockedReasonsEqual(
3442
- left: readonly WorkflowBlockedCommandReason[],
3443
- right: readonly WorkflowBlockedCommandReason[],
3444
- ): boolean {
3445
- if (left === right) {
3446
- return true;
3447
- }
3448
- if (left.length !== right.length) {
3449
- return false;
3450
- }
3451
- for (let index = 0; index < left.length; index += 1) {
3452
- if (!workflowBlockedReasonEqual(left[index]!, right[index]!)) {
3453
- return false;
3454
- }
3455
- }
3456
- return true;
3457
- }
3458
-
3459
- function workflowBlockedReasonEqual(
3460
- left: WorkflowBlockedCommandReason,
3461
- right: WorkflowBlockedCommandReason,
3462
- ): boolean {
3463
- return (
3464
- left.code === right.code &&
3465
- left.message === right.message &&
3466
- left.scopeId === right.scopeId &&
3467
- left.workItemId === right.workItemId &&
3468
- editorAnchorProjectionEqual(left.anchor, right.anchor) &&
3469
- storyTargetsEqual(left.storyTarget, right.storyTarget)
3470
- );
3471
- }
3472
-
3473
- function editorAnchorProjectionEqual(
3474
- left: EditorAnchorProjection | undefined,
3475
- right: EditorAnchorProjection | undefined,
3476
- ): boolean {
3477
- if (left === right) {
3478
- return true;
3479
- }
3480
- if (!left || !right || left.kind !== right.kind) {
3481
- return false;
3482
- }
3483
-
3484
- switch (left.kind) {
3485
- case "range":
3486
- return (
3487
- right.kind === "range" &&
3488
- left.from === right.from &&
3489
- left.to === right.to &&
3490
- left.assoc.start === right.assoc.start &&
3491
- left.assoc.end === right.assoc.end
3492
- );
3493
- case "node":
3494
- return right.kind === "node" && left.at === right.at && left.assoc === right.assoc;
3495
- case "detached":
3496
- return (
3497
- right.kind === "detached" &&
3498
- left.lastKnownRange.from === right.lastKnownRange.from &&
3499
- left.lastKnownRange.to === right.lastKnownRange.to &&
3500
- left.reason === right.reason
3501
- );
3502
- }
3503
-
3504
- return false;
3505
- }
3506
-
3507
- function createSelectionToolbarSelectionKey(
3508
- selection: RuntimeRenderSnapshot["selection"],
3509
- activeStory: EditorStoryTarget,
3510
- activeRevisionId?: string,
3511
- ): string | null {
3512
- if (activeRevisionId) {
3513
- return JSON.stringify({
3514
- story: activeStory,
3515
- revisionId: activeRevisionId,
3516
- });
3517
- }
3518
- if (selection.isCollapsed || selection.activeRange.kind !== "range") {
3519
- return null;
3520
- }
3521
-
3522
- return JSON.stringify({
3523
- story: activeStory,
3524
- from: selection.activeRange.from,
3525
- to: selection.activeRange.to,
3526
- });
3527
- }
3528
-
3529
- function buildSelectionToolbarModel(args: {
3530
- snapshot: RuntimeRenderSnapshot;
3531
- viewState: ReturnType<WordReviewEditorRuntime["getViewState"]>;
3532
- capabilities: ReturnType<typeof deriveCapabilities>;
3533
- documentNavigation: ReturnType<WordReviewEditorRuntime["getDocumentNavigationSnapshot"]>;
3534
- styleCatalog: StyleCatalogSnapshot;
3535
- formattingState: FormattingStateSnapshot;
3536
- workflowScopeSnapshot?: WorkflowScopeSnapshot | null;
3537
- interactionGuardSnapshot?: InteractionGuardSnapshot;
3538
- addCommentDisabledReason?: string;
3539
- }): SelectionToolbarModel | null {
3540
- const {
3541
- snapshot,
3542
- viewState,
3543
- capabilities,
3544
- documentNavigation,
3545
- styleCatalog,
3546
- formattingState,
3547
- workflowScopeSnapshot,
3548
- interactionGuardSnapshot,
3549
- addCommentDisabledReason,
3550
- } = args;
3551
-
3552
- if (
3553
- !snapshot.surface ||
3554
- snapshot.selection.isCollapsed ||
3555
- snapshot.selection.activeRange.kind !== "range" ||
3556
- !capabilities.canEdit ||
3557
- viewState.viewMode === "view"
3558
- ) {
3559
- return null;
3560
- }
3561
-
3562
- const previewText = summarizeSelectionPreview(snapshot);
3563
- if (!previewText) {
3564
- return null;
3565
- }
3566
-
3567
- const badges = [
3568
- createSelectionToolbarStoryBadge(viewState.activeStory),
3569
- createSelectionToolbarWorkflowBadge(
3570
- resolveSelectionWorkflowPosture(
3571
- snapshot,
3572
- viewState,
3573
- workflowScopeSnapshot,
3574
- interactionGuardSnapshot,
3575
- ),
3576
- ),
3577
- viewState.workspaceMode === "page" && documentNavigation.pageCount > 0
3578
- ? { label: `Page ${documentNavigation.activePageIndex + 1}` as const }
3579
- : null,
3580
- createSelectionToolbarStyleBadge(styleCatalog, formattingState),
3581
- createSelectionToolbarListBadge(viewState),
3582
- ].filter((badge): badge is SelectionToolbarModel["badges"][number] => Boolean(badge));
3583
-
3584
- const workflowPosture = resolveSelectionWorkflowPosture(
3585
- snapshot,
3586
- viewState,
3587
- workflowScopeSnapshot,
3588
- interactionGuardSnapshot,
3589
- );
3590
- const canToggleFormatting = workflowPosture.mode === "edit";
3591
- const canAddComment = workflowPosture.mode === "view" || workflowPosture.mode === "blocked"
3592
- ? false
3593
- : capabilities.canAddComment;
3594
- const disabledReason =
3595
- workflowPosture.disabledReason ??
3596
- (canAddComment ? undefined : addCommentDisabledReason);
3597
-
3598
- return {
3599
- previewText,
3600
- badges,
3601
- canToggleFormatting,
3602
- boldActive: formattingState.bold,
3603
- italicActive: formattingState.italic,
3604
- underlineActive: formattingState.underline,
3605
- canAddComment,
3606
- ...(disabledReason ? { disabledReason } : {}),
3607
- };
3608
- }
3609
-
3610
- function buildSuggestionCardModel(args: {
3611
- snapshot: RuntimeRenderSnapshot;
3612
- viewState: ReturnType<WordReviewEditorRuntime["getViewState"]>;
3613
- capabilities: ReturnType<typeof deriveCapabilities>;
3614
- workflowScopeSnapshot?: WorkflowScopeSnapshot | null;
3615
- interactionGuardSnapshot?: InteractionGuardSnapshot;
3616
- activeRevisionId?: string;
3617
- suppressedSuggestionRevisionId?: string | null;
3618
- addCommentDisabledReason?: string;
3619
- }): SuggestionCardModel | null {
3620
- const {
3621
- snapshot,
3622
- viewState,
3623
- capabilities,
3624
- workflowScopeSnapshot,
3625
- interactionGuardSnapshot,
3626
- activeRevisionId,
3627
- suppressedSuggestionRevisionId,
3628
- addCommentDisabledReason,
3629
- } = args;
3630
-
3631
- if (
3632
- !snapshot.surface ||
3633
- !capabilities.canEdit ||
3634
- viewState.viewMode === "view"
3635
- ) {
3636
- return null;
3637
- }
3638
-
3639
- const activeRange =
3640
- !snapshot.selection.isCollapsed && snapshot.selection.activeRange.kind === "range"
3641
- ? snapshot.selection.activeRange
3642
- : null;
3643
- const selectionFrom = activeRange
3644
- ? Math.min(activeRange.from, activeRange.to)
3645
- : null;
3646
- const selectionTo = activeRange
3647
- ? Math.max(activeRange.from, activeRange.to)
3648
- : null;
3649
- const candidateRevisions = snapshot.trackedChanges.revisions.filter((revision) =>
3650
- storyTargetsEqual(revision.storyTarget ?? { kind: "main" }, viewState.activeStory) &&
3651
- revision.status === "active" &&
3652
- revision.actionability === "actionable" &&
3653
- revision.anchor.kind === "range" &&
3654
- (
3655
- activeRevisionId === revision.revisionId ||
3656
- (
3657
- selectionFrom !== null &&
3658
- selectionTo !== null &&
3659
- rangesOverlap(
3660
- selectionFrom,
3661
- selectionTo,
3662
- revision.anchor.from,
3663
- revision.anchor.to,
3664
- )
3665
- )
3666
- )
3667
- );
3668
- const focusedRevision = (
3669
- activeRevisionId
3670
- ? candidateRevisions.find((revision) => revision.revisionId === activeRevisionId)
3671
- : null
3672
- ) ?? candidateRevisions[0];
3673
-
3674
- if (!focusedRevision || focusedRevision.revisionId === suppressedSuggestionRevisionId) {
3675
- return null;
3676
- }
3677
-
3678
- const badges = [
3679
- createSelectionToolbarStoryBadge(viewState.activeStory),
3680
- workflowScopeSnapshot?.activeWorkItem?.title
3681
- ? {
3682
- label: workflowScopeSnapshot.activeWorkItem.title,
3683
- tone: "accent" as const,
3684
- }
3685
- : null,
3686
- ].filter((badge): badge is SuggestionCardModel["badges"][number] => Boolean(badge));
3687
- const workflowPosture = resolveSelectionWorkflowPosture(
3688
- snapshot,
3689
- viewState,
3690
- workflowScopeSnapshot,
3691
- interactionGuardSnapshot,
3692
- );
3693
- const canReviewSuggestion = workflowPosture.mode === "edit" || workflowPosture.mode === "suggest";
3694
- const canAddComment = workflowPosture.mode === "view" || workflowPosture.mode === "blocked"
3695
- ? false
3696
- : capabilities.canAddComment;
3697
- const disabledReason =
3698
- workflowPosture.disabledReason ??
3699
- (canAddComment ? undefined : addCommentDisabledReason);
3700
-
3701
- return {
3702
- revisionId: focusedRevision.revisionId,
3703
- kindLabel: getSuggestionKindLabel(focusedRevision.kind),
3704
- previewText:
3705
- focusedRevision.excerpt ??
3706
- focusedRevision.detail ??
3707
- focusedRevision.label ??
3708
- "Suggested change",
3709
- badges,
3710
- canAccept: canReviewSuggestion && capabilities.canAcceptChange && focusedRevision.canAccept,
3711
- canReject: canReviewSuggestion && capabilities.canRejectChange && focusedRevision.canReject,
3712
- canEditSuggestion: canReviewSuggestion,
3713
- canAddComment,
3714
- ...(disabledReason ? { disabledReason } : {}),
3715
- };
3716
- }
3717
-
3718
- function createSelectionToolbarStoryBadge(
3719
- target: EditorStoryTarget,
3720
- ): SelectionToolbarModel["badges"][number] | null {
3721
- if (target.kind === "main") {
3722
- return null;
3723
- }
3724
-
3725
- return {
3726
- label:
3727
- target.kind === "header"
3728
- ? target.variant === "default"
3729
- ? "Header"
3730
- : `Header ${target.variant}`
3731
- : target.kind === "footer"
3732
- ? target.variant === "default"
3733
- ? "Footer"
3734
- : `Footer ${target.variant}`
3735
- : target.kind === "footnote"
3736
- ? "Footnote"
3737
- : "Endnote",
3738
- tone: "accent",
3739
- };
3740
- }
3741
-
3742
- function createSelectionToolbarStyleBadge(
3743
- styleCatalog: StyleCatalogSnapshot,
3744
- formattingState: FormattingStateSnapshot,
3745
- ): SelectionToolbarModel["badges"][number] | null {
3746
- if (!formattingState.paragraphStyleId) {
3747
- return null;
3748
- }
3749
-
3750
- const styleEntry = styleCatalog.paragraphs.find(
3751
- (entry) => entry.styleId === formattingState.paragraphStyleId,
3752
- );
3753
- if (!styleEntry || styleEntry.isDefault) {
3754
- return null;
3755
- }
3756
-
3757
- return { label: styleEntry.displayName };
3758
- }
3759
-
3760
- function createSelectionToolbarListBadge(
3761
- viewState: ReturnType<WordReviewEditorRuntime["getViewState"]>,
3762
- ): SelectionToolbarModel["badges"][number] | null {
3763
- if (!viewState.activeListContext) {
3764
- return null;
3765
- }
3766
-
3767
- return {
3768
- label: viewState.activeListContext.isOrdered ? "Numbered list" : "Bulleted list",
3769
- };
3770
- }
3771
-
3772
- function createSelectionToolbarWorkflowBadge(
3773
- posture: ReturnType<typeof resolveSelectionWorkflowPosture>,
3774
- ): SelectionToolbarModel["badges"][number] | null {
3775
- switch (posture.mode) {
3776
- case "suggest":
3777
- return { label: "Suggest", tone: "accent" };
3778
- case "comment":
3779
- return { label: "Comment only", tone: "accent" };
3780
- case "view":
3781
- return { label: "View only" };
3782
- case "blocked":
3783
- return { label: "Blocked" };
3784
- default:
3785
- return null;
3786
- }
3787
- }
3788
-
3789
- function resolveSelectionWorkflowPosture(
3790
- snapshot: RuntimeRenderSnapshot,
3791
- viewState: ReturnType<WordReviewEditorRuntime["getViewState"]>,
3792
- workflowScopeSnapshot?: WorkflowScopeSnapshot | null,
3793
- interactionGuardSnapshot?: InteractionGuardSnapshot,
3794
- ): {
3795
- mode: "edit" | "suggest" | "comment" | "view" | "blocked";
3796
- disabledReason?: string;
3797
- } {
3798
- const blockedReasons =
3799
- interactionGuardSnapshot?.blockedReasons ??
3800
- workflowScopeSnapshot?.blockedReasons ??
3801
- [];
3802
- const blockingReason = blockedReasons[0];
3803
- if (blockingReason) {
3804
- if (blockingReason.code === "workflow_comment_only") {
3805
- return {
3806
- mode: "comment",
3807
- disabledReason: blockingReason.message,
3808
- };
3809
- }
3810
- if (blockingReason.code === "workflow_view_only") {
3811
- return {
3812
- mode: "view",
3813
- disabledReason: blockingReason.message,
3814
- };
3815
- }
3816
- return {
3817
- mode: "blocked",
3818
- disabledReason: blockingReason.message,
3819
- };
3820
- }
3821
-
3822
- if (interactionGuardSnapshot) {
3823
- if (interactionGuardSnapshot.effectiveMode === "suggest") {
3824
- return {
3825
- mode: "suggest",
3826
- disabledReason:
3827
- interactionGuardSnapshot.disabledReason ??
3828
- "Suggestion authoring is active here; direct formatting changes are blocked.",
3829
- };
3830
- }
3831
- if (interactionGuardSnapshot.effectiveMode === "comment") {
3832
- return {
3833
- mode: "comment",
3834
- disabledReason: interactionGuardSnapshot.disabledReason,
3835
- };
3836
- }
3837
- if (interactionGuardSnapshot.effectiveMode === "view") {
3838
- return {
3839
- mode: "view",
3840
- disabledReason: interactionGuardSnapshot.disabledReason,
3841
- };
3842
- }
3843
- if (interactionGuardSnapshot.effectiveMode === "blocked") {
3844
- return {
3845
- mode: "blocked",
3846
- disabledReason: interactionGuardSnapshot.disabledReason,
3847
- };
3848
- }
3849
- }
3850
-
3851
- const activeRange =
3852
- !snapshot.selection.isCollapsed && snapshot.selection.activeRange.kind === "range"
3853
- ? snapshot.selection.activeRange
3854
- : null;
3855
- const matchingScope = activeRange && workflowScopeSnapshot
3856
- ? workflowScopeSnapshot.scopes.find((scope) => {
3857
- const scopeStoryTarget = scope.storyTarget ?? { kind: "main" as const };
3858
- if (!storyTargetsEqual(scopeStoryTarget, viewState.activeStory)) {
3859
- return false;
3860
- }
3861
- if (scope.anchor.kind === "detached") {
3862
- return false;
3863
- }
3864
- const scopeFrom = scope.anchor.kind === "range" ? scope.anchor.from : scope.anchor.at;
3865
- const scopeTo = scope.anchor.kind === "range" ? scope.anchor.to : scope.anchor.at;
3866
- return activeRange.from >= scopeFrom && activeRange.to <= scopeTo;
3867
- })
3868
- : null;
3869
-
3870
- if (matchingScope?.mode === "suggest") {
3871
- return {
3872
- mode: "suggest",
3873
- disabledReason: "Suggestion authoring is active here; direct formatting changes are blocked.",
3874
- };
3875
- }
3876
- if (matchingScope?.mode === "comment") {
3877
- return {
3878
- mode: "comment",
3879
- disabledReason: `Scope "${matchingScope.label ?? matchingScope.scopeId}" allows comments only.`,
3880
- };
3881
- }
3882
- if (matchingScope?.mode === "view") {
3883
- return {
3884
- mode: "view",
3885
- disabledReason: `Scope "${matchingScope.label ?? matchingScope.scopeId}" is view-only.`,
3886
- };
3887
- }
3888
- return { mode: "edit" };
3889
- }
3890
-
3891
- function rangesOverlap(
3892
- leftFrom: number,
3893
- leftTo: number,
3894
- rightFrom: number,
3895
- rightTo: number,
3896
- ): boolean {
3897
- return leftFrom < rightTo && rightFrom < leftTo;
3898
- }
3899
-
3900
- function getSuggestionKindLabel(kind: TrackedChangeEntrySnapshot["kind"]): string {
3901
- switch (kind) {
3902
- case "insertion":
3903
- return "Suggested insertion";
3904
- case "deletion":
3905
- return "Suggested deletion";
3906
- case "formatting":
3907
- return "Suggested formatting change";
3908
- case "property-change":
3909
- return "Suggested property change";
3910
- case "move":
3911
- return "Suggested move";
3912
- }
3913
- }
3914
-
3915
- function buildActiveImageContext(args: {
3916
- canonicalDocument: PersistedEditorSnapshot["canonicalDocument"];
3917
- selection: RuntimeRenderSnapshot["selection"];
3918
- storyTarget: EditorStoryTarget;
3919
- surface?: RuntimeRenderSnapshot["surface"];
3920
- }): {
3921
- mediaId: string;
3922
- display: "inline" | "floating";
3923
- widthEmu?: number;
3924
- heightEmu?: number;
3925
- horizontalOffsetEmu?: number;
3926
- verticalOffsetEmu?: number;
3927
- } | null {
3928
- const imageSegment = findSelectedImageSegment(args.surface, args.selection);
3929
- if (!imageSegment) {
3930
- return null;
3931
- }
3932
-
3933
- const storyBlocks = getStoryBlocks(args.canonicalDocument, args.storyTarget);
3934
- const imageNode = findImageNodeByMediaId(storyBlocks, imageSegment.mediaId);
3935
- const mediaItem = args.canonicalDocument.media.items[imageSegment.mediaId];
3936
-
3937
- return {
3938
- mediaId: imageSegment.mediaId,
3939
- display: imageSegment.display === "floating" ? "floating" : "inline",
3940
- widthEmu: mediaItem?.widthEmu,
3941
- heightEmu: mediaItem?.heightEmu,
3942
- horizontalOffsetEmu: imageNode?.floating?.horizontalPosition?.offset,
3943
- verticalOffsetEmu: imageNode?.floating?.verticalPosition?.offset,
3944
- };
3945
- }
3946
-
3947
- function findSelectedImageSegment(
3948
- surface: RuntimeRenderSnapshot["surface"] | undefined,
3949
- selection: RuntimeRenderSnapshot["selection"],
3950
- ): Extract<NonNullable<RuntimeRenderSnapshot["surface"]>["blocks"][number], { kind: "paragraph" }>["segments"][number] & {
3951
- kind: "image";
3952
- } | null {
3953
- if (!surface) {
3954
- return null;
3955
- }
3956
-
3957
- const position =
3958
- selection.activeRange.kind === "node" ? selection.activeRange.at : selection.head;
3959
-
3960
- return findSelectedImageSegmentInBlocks(surface.blocks, position);
3961
- }
3962
-
3963
- function findSelectedImageSegmentInBlocks(
3964
- blocks: readonly SurfaceBlockSnapshot[],
3965
- position: number,
3966
- ): Extract<NonNullable<RuntimeRenderSnapshot["surface"]>["blocks"][number], { kind: "paragraph" }>["segments"][number] & {
3967
- kind: "image";
3968
- } | null {
3969
- for (const block of blocks) {
3970
- if (position < block.from || position > block.to) {
3971
- continue;
3972
- }
3973
-
3974
- if (block.kind === "paragraph") {
3975
- const imageSegment = block.segments.find(
3976
- (segment) => segment.kind === "image" && position >= segment.from && position <= segment.to,
3977
- );
3978
- if (imageSegment && imageSegment.kind === "image") {
3979
- return imageSegment;
3980
- }
3981
- continue;
3982
- }
3983
-
3984
- if (block.kind === "table") {
3985
- for (const row of block.rows) {
3986
- for (const cell of row.cells) {
3987
- const match = findSelectedImageSegmentInBlocks(cell.content, position);
3988
- if (match) {
3989
- return match;
3990
- }
3991
- }
3992
- }
3993
- continue;
3994
- }
3995
-
3996
- if (block.kind === "sdt_block") {
3997
- const match = findSelectedImageSegmentInBlocks(block.children, position);
3998
- if (match) {
3999
- return match;
4000
- }
4001
- }
4002
- }
4003
-
4004
- return null;
4005
- }
4006
-
4007
- function findImageNodeByMediaId(blocks: readonly unknown[], mediaId: string): {
4008
- floating?: {
4009
- horizontalPosition?: { offset?: number };
4010
- verticalPosition?: { offset?: number };
4011
- };
4012
- } | null {
4013
- for (const block of blocks) {
4014
- const match = findImageNodeInValue(block, mediaId);
4015
- if (match) {
4016
- return match;
4017
- }
4018
- }
4019
- return null;
4020
- }
4021
-
4022
- function findImageNodeInValue(
4023
- value: unknown,
4024
- mediaId: string,
4025
- ): {
4026
- floating?: {
4027
- horizontalPosition?: { offset?: number };
4028
- verticalPosition?: { offset?: number };
4029
- };
4030
- } | null {
4031
- if (!value || typeof value !== "object") {
4032
- return null;
4033
- }
4034
-
4035
- const record = value as {
4036
- type?: string;
4037
- mediaId?: string;
4038
- children?: unknown[];
4039
- rows?: Array<{ cells?: Array<{ children?: unknown[] }> }>;
4040
- floating?: {
4041
- horizontalPosition?: { offset?: number };
4042
- verticalPosition?: { offset?: number };
4043
- };
4044
- };
4045
-
4046
- if (record.type === "image" && record.mediaId === mediaId) {
4047
- return record;
4048
- }
4049
-
4050
- if (Array.isArray(record.children)) {
4051
- for (const child of record.children) {
4052
- const match = findImageNodeInValue(child, mediaId);
4053
- if (match) {
4054
- return match;
4055
- }
4056
- }
4057
- }
4058
-
4059
- if (Array.isArray(record.rows)) {
4060
- for (const row of record.rows) {
4061
- for (const cell of row.cells ?? []) {
4062
- for (const child of cell.children ?? []) {
4063
- const match = findImageNodeInValue(child, mediaId);
4064
- if (match) {
4065
- return match;
4066
- }
4067
- }
4068
- }
4069
- }
4070
- }
4071
-
4072
- return null;
4073
- }
4074
-
4075
- function createImageDataUrl(contentType: string, bytes: Uint8Array): string {
4076
- const base64 = bytesToBase64(bytes);
4077
- return `data:${contentType};base64,${base64}`;
4078
- }
4079
-
4080
- function bytesToBase64(bytes: Uint8Array): string {
4081
- let binary = "";
4082
- for (let index = 0; index < bytes.length; index += 1) {
4083
- binary += String.fromCharCode(bytes[index] ?? 0);
4084
- }
4085
- return btoa(binary);
4086
- }