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