@beyondwork/docx-react-component 1.0.29 → 1.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (381) hide show
  1. package/package.json +65 -96
  2. package/src/README.md +85 -0
  3. package/src/api/README.md +26 -0
  4. package/src/api/public-types.ts +1952 -0
  5. package/src/api/session-state.ts +62 -0
  6. package/src/compare/diff-engine.ts +623 -0
  7. package/src/compare/export-redlines.ts +280 -0
  8. package/src/compare/index.ts +25 -0
  9. package/src/compare/snapshot.ts +97 -0
  10. package/src/component-inventory.md +99 -0
  11. package/src/core/README.md +10 -0
  12. package/src/core/commands/README.md +3 -0
  13. package/{dist/chunk-TJBP2K4T.js → src/core/commands/formatting-commands.ts} +536 -196
  14. package/src/core/commands/image-commands.ts +373 -0
  15. package/src/core/commands/index.ts +1879 -0
  16. package/src/core/commands/list-commands.ts +565 -0
  17. package/src/core/commands/paragraph-layout-commands.ts +339 -0
  18. package/src/core/commands/review-commands.ts +108 -0
  19. package/{dist/core/commands/section-layout-commands.cjs → src/core/commands/section-layout-commands.ts} +340 -137
  20. package/src/core/commands/structural-helpers.ts +309 -0
  21. package/{dist/core/commands/style-commands.cjs → src/core/commands/style-commands.ts} +113 -65
  22. package/src/core/commands/table-structure-commands.ts +854 -0
  23. package/{dist/chunk-UZXBISGO.js → src/core/commands/text-commands.ts} +142 -86
  24. package/src/core/schema/README.md +3 -0
  25. package/src/core/schema/text-schema.ts +516 -0
  26. package/src/core/search/search-text.ts +357 -0
  27. package/src/core/selection/README.md +3 -0
  28. package/src/core/selection/mapping.ts +289 -0
  29. package/src/core/selection/review-anchors.ts +183 -0
  30. package/src/core/state/README.md +3 -0
  31. package/src/core/state/editor-state.ts +892 -0
  32. package/src/core/state/text-transaction.ts +869 -0
  33. package/src/formats/xlsx/io/parse-shared-strings.ts +41 -0
  34. package/src/formats/xlsx/io/parse-sheet.ts +459 -0
  35. package/src/formats/xlsx/io/parse-styles.ts +59 -0
  36. package/src/formats/xlsx/io/parse-workbook.ts +75 -0
  37. package/src/formats/xlsx/io/serialize-shared-strings.ts +72 -0
  38. package/src/formats/xlsx/io/serialize-sheet.ts +333 -0
  39. package/src/formats/xlsx/io/serialize-styles.ts +98 -0
  40. package/src/formats/xlsx/io/serialize-workbook.ts +429 -0
  41. package/src/formats/xlsx/io/xlsx-session.ts +314 -0
  42. package/src/formats/xlsx/model/cell.ts +189 -0
  43. package/src/formats/xlsx/model/sheet.ts +326 -0
  44. package/src/formats/xlsx/model/styles.ts +118 -0
  45. package/src/formats/xlsx/model/workbook.ts +453 -0
  46. package/src/formats/xlsx/runtime/cell-commands.ts +567 -0
  47. package/src/formats/xlsx/runtime/sheet-commands.ts +206 -0
  48. package/src/formats/xlsx/runtime/workbook-runtime.ts +177 -0
  49. package/src/formats/xlsx/runtime/workbook-transaction.ts +822 -0
  50. package/src/index.ts +142 -0
  51. package/src/io/README.md +10 -0
  52. package/src/io/docx-session.ts +3175 -0
  53. package/src/io/export/README.md +3 -0
  54. package/src/io/export/export-session.ts +220 -0
  55. package/src/io/export/minimal-docx.ts +115 -0
  56. package/src/io/export/reattach-preserved-parts.ts +54 -0
  57. package/src/io/export/serialize-comments.ts +947 -0
  58. package/src/io/export/serialize-footnotes.ts +394 -0
  59. package/src/io/export/serialize-headers-footers.ts +368 -0
  60. package/src/io/export/serialize-main-document.ts +1342 -0
  61. package/src/io/export/serialize-numbering.ts +218 -0
  62. package/src/io/export/serialize-revisions.ts +389 -0
  63. package/src/io/export/serialize-runtime-revisions.ts +463 -0
  64. package/src/io/export/serialize-tables.ts +174 -0
  65. package/src/io/export/split-review-boundaries.ts +356 -0
  66. package/src/io/export/split-story-blocks-for-runtime-revisions.ts +252 -0
  67. package/src/io/export/table-properties-xml.ts +318 -0
  68. package/src/io/normalize/README.md +3 -0
  69. package/src/io/normalize/normalize-text.ts +670 -0
  70. package/src/io/ooxml/README.md +3 -0
  71. package/src/io/ooxml/highlight-colors.ts +39 -0
  72. package/src/io/ooxml/numbering-sentinels.ts +44 -0
  73. package/src/io/ooxml/parse-comments.ts +852 -0
  74. package/src/io/ooxml/parse-complex-content.ts +287 -0
  75. package/src/io/ooxml/parse-fields.ts +834 -0
  76. package/src/io/ooxml/parse-footnotes.ts +952 -0
  77. package/src/io/ooxml/parse-headers-footers.ts +1212 -0
  78. package/src/io/ooxml/parse-inline-media.ts +461 -0
  79. package/src/io/ooxml/parse-main-document.ts +2947 -0
  80. package/src/io/ooxml/parse-numbering.ts +747 -0
  81. package/src/io/ooxml/parse-revisions.ts +1045 -0
  82. package/src/io/ooxml/parse-settings.ts +184 -0
  83. package/src/io/ooxml/parse-shapes.ts +296 -0
  84. package/src/io/ooxml/parse-styles.ts +639 -0
  85. package/src/io/ooxml/parse-tables.ts +627 -0
  86. package/src/io/ooxml/parse-theme.ts +346 -0
  87. package/src/io/ooxml/part-manifest.ts +136 -0
  88. package/src/io/ooxml/revision-boundaries.ts +475 -0
  89. package/src/io/ooxml/workflow-payload.ts +544 -0
  90. package/src/io/opc/README.md +3 -0
  91. package/src/io/opc/corrupt-package.ts +166 -0
  92. package/src/io/opc/docx-package.ts +74 -0
  93. package/src/io/opc/package-reader.ts +325 -0
  94. package/src/io/opc/package-writer.ts +273 -0
  95. package/src/io/source-package-provenance.ts +241 -0
  96. package/{dist/chunk-RMH72RZI.js → src/legal/bookmarks.ts} +130 -44
  97. package/src/legal/cross-references.ts +414 -0
  98. package/src/legal/defined-terms.ts +203 -0
  99. package/src/legal/index.ts +32 -0
  100. package/src/legal/signature-blocks.ts +259 -0
  101. package/src/model/README.md +3 -0
  102. package/src/model/canonical-document.ts +2722 -0
  103. package/src/model/cds-1.0.0.ts +212 -0
  104. package/src/model/snapshot.ts +760 -0
  105. package/src/preservation/README.md +3 -0
  106. package/src/preservation/markup-compatibility.ts +48 -0
  107. package/src/preservation/opaque-fragment-store.ts +89 -0
  108. package/src/preservation/opaque-region.ts +233 -0
  109. package/src/preservation/package-preservation.ts +113 -0
  110. package/src/preservation/preserved-part-manifest.ts +56 -0
  111. package/src/preservation/relationship-retention.ts +57 -0
  112. package/src/preservation/store.ts +255 -0
  113. package/src/review/README.md +16 -0
  114. package/src/review/store/README.md +3 -0
  115. package/src/review/store/comment-anchors.ts +70 -0
  116. package/src/review/store/comment-remapping.ts +154 -0
  117. package/src/review/store/comment-store.ts +349 -0
  118. package/src/review/store/comment-thread.ts +109 -0
  119. package/src/review/store/revision-actions.ts +423 -0
  120. package/src/review/store/revision-store.ts +323 -0
  121. package/src/review/store/revision-types.ts +182 -0
  122. package/src/review/store/runtime-comment-store.ts +43 -0
  123. package/src/runtime/README.md +3 -0
  124. package/src/runtime/ai-action-policy.ts +764 -0
  125. package/src/runtime/context-analytics.ts +824 -0
  126. package/src/runtime/document-layout.ts +332 -0
  127. package/src/runtime/document-locations.ts +521 -0
  128. package/src/runtime/document-navigation.ts +616 -0
  129. package/src/runtime/document-outline.ts +440 -0
  130. package/src/runtime/document-runtime.ts +4055 -0
  131. package/src/runtime/document-search.ts +145 -0
  132. package/src/runtime/event-refresh-hints.ts +137 -0
  133. package/src/runtime/numbering-prefix.ts +244 -0
  134. package/src/runtime/page-layout-estimation.ts +305 -0
  135. package/src/runtime/read-only-diagnostics-runtime.ts +241 -0
  136. package/src/runtime/resolved-numbering-geometry.ts +293 -0
  137. package/src/runtime/review-runtime.ts +44 -0
  138. package/src/runtime/revision-runtime.ts +107 -0
  139. package/src/runtime/session-capabilities.ts +192 -0
  140. package/src/runtime/story-context.ts +164 -0
  141. package/src/runtime/story-targeting.ts +162 -0
  142. package/src/runtime/suggestions-snapshot.ts +137 -0
  143. package/src/runtime/surface-projection.ts +1553 -0
  144. package/src/runtime/table-commands.ts +173 -0
  145. package/src/runtime/table-schema.ts +309 -0
  146. package/src/runtime/table-style-resolver.ts +409 -0
  147. package/src/runtime/view-state.ts +493 -0
  148. package/src/runtime/virtualized-rendering.ts +258 -0
  149. package/src/runtime/workflow-markup.ts +393 -0
  150. package/src/ui/README.md +30 -0
  151. package/src/ui/WordReviewEditor.tsx +5268 -0
  152. package/src/ui/browser-export.ts +52 -0
  153. package/src/ui/comments/README.md +3 -0
  154. package/src/ui/compatibility/README.md +3 -0
  155. package/src/ui/editor-command-bag.ts +127 -0
  156. package/src/ui/editor-runtime-boundary.ts +1558 -0
  157. package/src/ui/editor-shell-view.tsx +144 -0
  158. package/src/ui/editor-surface/README.md +3 -0
  159. package/src/ui/editor-surface-controller.tsx +66 -0
  160. package/src/ui/headless/comment-decoration-model.ts +124 -0
  161. package/src/ui/headless/preserve-editor-selection.ts +5 -0
  162. package/src/ui/headless/revision-decoration-model.ts +128 -0
  163. package/src/ui/headless/selection-helpers.ts +54 -0
  164. package/src/ui/headless/selection-tool-context.ts +19 -0
  165. package/src/ui/headless/selection-tool-resolver.ts +752 -0
  166. package/src/ui/headless/selection-tool-types.ts +129 -0
  167. package/src/ui/headless/selection-toolbar-model.ts +11 -0
  168. package/src/ui/headless/use-editor-keyboard.ts +103 -0
  169. package/src/ui/review/README.md +3 -0
  170. package/src/ui/runtime-shortcut-dispatch.ts +365 -0
  171. package/src/ui/runtime-snapshot-selectors.ts +197 -0
  172. package/src/ui/shared/revision-filters.ts +31 -0
  173. package/src/ui/status/README.md +3 -0
  174. package/src/ui/theme/README.md +3 -0
  175. package/src/ui/toolbar/README.md +3 -0
  176. package/src/ui/workflow-surface-blocked-rails.ts +94 -0
  177. package/src/ui-tailwind/chrome/chrome-preset-model.ts +107 -0
  178. package/src/ui-tailwind/chrome/chrome-preset-toolbar.tsx +15 -0
  179. package/src/ui-tailwind/chrome/review-queue-bar.tsx +97 -0
  180. package/src/ui-tailwind/chrome/tw-alert-banner.tsx +64 -0
  181. package/src/ui-tailwind/chrome/tw-context-analytics-summary.tsx +122 -0
  182. package/src/ui-tailwind/chrome/tw-image-context-toolbar.tsx +121 -0
  183. package/src/ui-tailwind/chrome/tw-layout-panel.tsx +114 -0
  184. package/src/ui-tailwind/chrome/tw-object-context-toolbar.tsx +30 -0
  185. package/src/ui-tailwind/chrome/tw-page-ruler.tsx +365 -0
  186. package/src/ui-tailwind/chrome/tw-selection-tool-blocked.tsx +23 -0
  187. package/src/ui-tailwind/chrome/tw-selection-tool-comment.tsx +35 -0
  188. package/src/ui-tailwind/chrome/tw-selection-tool-formatting.tsx +37 -0
  189. package/src/ui-tailwind/chrome/tw-selection-tool-host.tsx +298 -0
  190. package/src/ui-tailwind/chrome/tw-selection-tool-structure.tsx +116 -0
  191. package/src/ui-tailwind/chrome/tw-selection-tool-suggestion.tsx +29 -0
  192. package/src/ui-tailwind/chrome/tw-selection-tool-workflow.tsx +27 -0
  193. package/src/ui-tailwind/chrome/tw-selection-toolbar.tsx +186 -0
  194. package/src/ui-tailwind/chrome/tw-suggestion-card.tsx +139 -0
  195. package/src/ui-tailwind/chrome/tw-table-context-toolbar.tsx +200 -0
  196. package/src/ui-tailwind/chrome/tw-unsaved-modal.tsx +58 -0
  197. package/src/ui-tailwind/chrome/use-before-unload.ts +20 -0
  198. package/src/ui-tailwind/editor-surface/perf-probe.ts +179 -0
  199. package/src/ui-tailwind/editor-surface/pm-command-bridge.ts +189 -0
  200. package/src/ui-tailwind/editor-surface/pm-contextual-ui.ts +31 -0
  201. package/src/ui-tailwind/editor-surface/pm-decorations.ts +411 -0
  202. package/src/ui-tailwind/editor-surface/pm-position-map.ts +123 -0
  203. package/src/ui-tailwind/editor-surface/pm-schema.ts +927 -0
  204. package/src/ui-tailwind/editor-surface/pm-state-from-snapshot.ts +567 -0
  205. package/src/ui-tailwind/editor-surface/search-plugin.ts +168 -0
  206. package/src/ui-tailwind/editor-surface/surface-build-keys.ts +65 -0
  207. package/src/ui-tailwind/editor-surface/tw-caret.tsx +12 -0
  208. package/src/ui-tailwind/editor-surface/tw-editor-surface.tsx +150 -0
  209. package/src/ui-tailwind/editor-surface/tw-inline-token.tsx +129 -0
  210. package/src/ui-tailwind/editor-surface/tw-opaque-block.tsx +58 -0
  211. package/src/ui-tailwind/editor-surface/tw-paragraph-block.tsx +151 -0
  212. package/src/ui-tailwind/editor-surface/tw-prosemirror-surface.tsx +1047 -0
  213. package/src/ui-tailwind/editor-surface/tw-segment-view.tsx +111 -0
  214. package/src/ui-tailwind/editor-surface/tw-table-node-view.tsx +503 -0
  215. package/src/ui-tailwind/index.ts +62 -0
  216. package/src/ui-tailwind/page-chrome-model.ts +27 -0
  217. package/src/ui-tailwind/review/tw-comment-sidebar.tsx +406 -0
  218. package/src/ui-tailwind/review/tw-health-panel.tsx +149 -0
  219. package/src/ui-tailwind/review/tw-review-rail.tsx +122 -0
  220. package/src/ui-tailwind/review/tw-revision-sidebar.tsx +164 -0
  221. package/src/ui-tailwind/status/tw-status-bar.tsx +65 -0
  222. package/{dist → src}/ui-tailwind/theme/editor-theme.css +58 -40
  223. package/src/ui-tailwind/toolbar/tw-toolbar-icon-button.tsx +52 -0
  224. package/src/ui-tailwind/toolbar/tw-toolbar.tsx +1133 -0
  225. package/src/ui-tailwind/tw-review-workspace.tsx +1460 -0
  226. package/src/validation/README.md +3 -0
  227. package/src/validation/compatibility-engine.ts +878 -0
  228. package/src/validation/compatibility-report.ts +161 -0
  229. package/src/validation/diagnostics.ts +204 -0
  230. package/src/validation/docx-comment-proof.ts +720 -0
  231. package/src/validation/import-diagnostics.ts +128 -0
  232. package/src/validation/low-priority-word-surfaces.ts +373 -0
  233. package/dist/canonical-document-BLEbzL2J.d.cts +0 -844
  234. package/dist/canonical-document-BLEbzL2J.d.ts +0 -844
  235. package/dist/chunk-2FJS5GZM.js +0 -763
  236. package/dist/chunk-2FJS5GZM.js.map +0 -1
  237. package/dist/chunk-2OQBZS3F.js +0 -446
  238. package/dist/chunk-2OQBZS3F.js.map +0 -1
  239. package/dist/chunk-2S7W4KFO.js +0 -127
  240. package/dist/chunk-2S7W4KFO.js.map +0 -1
  241. package/dist/chunk-2TG72QSW.js +0 -3874
  242. package/dist/chunk-2TG72QSW.js.map +0 -1
  243. package/dist/chunk-36QNIZBO.js +0 -532
  244. package/dist/chunk-36QNIZBO.js.map +0 -1
  245. package/dist/chunk-4AQOYAW4.js +0 -3069
  246. package/dist/chunk-4AQOYAW4.js.map +0 -1
  247. package/dist/chunk-4D5EWJ3P.js +0 -77
  248. package/dist/chunk-4D5EWJ3P.js.map +0 -1
  249. package/dist/chunk-5FN54NDH.js +0 -2257
  250. package/dist/chunk-5FN54NDH.js.map +0 -1
  251. package/dist/chunk-BOYGQYRQ.js +0 -7306
  252. package/dist/chunk-BOYGQYRQ.js.map +0 -1
  253. package/dist/chunk-CN3XMECL.js +0 -212
  254. package/dist/chunk-CN3XMECL.js.map +0 -1
  255. package/dist/chunk-EBI3BX6U.js +0 -164
  256. package/dist/chunk-EBI3BX6U.js.map +0 -1
  257. package/dist/chunk-EILUG3VB.js +0 -1275
  258. package/dist/chunk-EILUG3VB.js.map +0 -1
  259. package/dist/chunk-FUDY333O.js +0 -70
  260. package/dist/chunk-FUDY333O.js.map +0 -1
  261. package/dist/chunk-GBVOWFIK.js +0 -1237
  262. package/dist/chunk-GBVOWFIK.js.map +0 -1
  263. package/dist/chunk-H4TQ3H3Y.js +0 -262
  264. package/dist/chunk-H4TQ3H3Y.js.map +0 -1
  265. package/dist/chunk-JGB3IXZO.js +0 -189
  266. package/dist/chunk-JGB3IXZO.js.map +0 -1
  267. package/dist/chunk-KD2QRQPY.js +0 -4342
  268. package/dist/chunk-KD2QRQPY.js.map +0 -1
  269. package/dist/chunk-KLMXQVYK.js +0 -369
  270. package/dist/chunk-KLMXQVYK.js.map +0 -1
  271. package/dist/chunk-KZUG5KFQ.js +0 -214
  272. package/dist/chunk-KZUG5KFQ.js.map +0 -1
  273. package/dist/chunk-QDAQ4CJU.js +0 -345
  274. package/dist/chunk-QDAQ4CJU.js.map +0 -1
  275. package/dist/chunk-RMH72RZI.js.map +0 -1
  276. package/dist/chunk-SWKWQZXM.js +0 -117
  277. package/dist/chunk-SWKWQZXM.js.map +0 -1
  278. package/dist/chunk-TJBP2K4T.js.map +0 -1
  279. package/dist/chunk-TLCEAQDQ.js +0 -542
  280. package/dist/chunk-TLCEAQDQ.js.map +0 -1
  281. package/dist/chunk-UZXBISGO.js.map +0 -1
  282. package/dist/chunk-WGBAKP3Q.js +0 -3220
  283. package/dist/chunk-WGBAKP3Q.js.map +0 -1
  284. package/dist/compare/index.cjs +0 -5475
  285. package/dist/compare/index.cjs.map +0 -1
  286. package/dist/compare/index.d.cts +0 -114
  287. package/dist/compare/index.d.ts +0 -114
  288. package/dist/compare/index.js +0 -731
  289. package/dist/compare/index.js.map +0 -1
  290. package/dist/core/commands/formatting-commands.cjs +0 -828
  291. package/dist/core/commands/formatting-commands.cjs.map +0 -1
  292. package/dist/core/commands/formatting-commands.d.cts +0 -63
  293. package/dist/core/commands/formatting-commands.d.ts +0 -63
  294. package/dist/core/commands/formatting-commands.js +0 -37
  295. package/dist/core/commands/formatting-commands.js.map +0 -1
  296. package/dist/core/commands/image-commands.cjs +0 -2023
  297. package/dist/core/commands/image-commands.cjs.map +0 -1
  298. package/dist/core/commands/image-commands.d.cts +0 -58
  299. package/dist/core/commands/image-commands.d.ts +0 -58
  300. package/dist/core/commands/image-commands.js +0 -18
  301. package/dist/core/commands/image-commands.js.map +0 -1
  302. package/dist/core/commands/section-layout-commands.cjs.map +0 -1
  303. package/dist/core/commands/section-layout-commands.d.cts +0 -62
  304. package/dist/core/commands/section-layout-commands.d.ts +0 -62
  305. package/dist/core/commands/section-layout-commands.js +0 -21
  306. package/dist/core/commands/section-layout-commands.js.map +0 -1
  307. package/dist/core/commands/style-commands.cjs.map +0 -1
  308. package/dist/core/commands/style-commands.d.cts +0 -13
  309. package/dist/core/commands/style-commands.d.ts +0 -13
  310. package/dist/core/commands/style-commands.js +0 -9
  311. package/dist/core/commands/style-commands.js.map +0 -1
  312. package/dist/core/commands/table-structure-commands.cjs +0 -1883
  313. package/dist/core/commands/table-structure-commands.cjs.map +0 -1
  314. package/dist/core/commands/table-structure-commands.d.cts +0 -59
  315. package/dist/core/commands/table-structure-commands.d.ts +0 -59
  316. package/dist/core/commands/table-structure-commands.js +0 -12
  317. package/dist/core/commands/table-structure-commands.js.map +0 -1
  318. package/dist/core/commands/text-commands.cjs +0 -2391
  319. package/dist/core/commands/text-commands.cjs.map +0 -1
  320. package/dist/core/commands/text-commands.d.cts +0 -24
  321. package/dist/core/commands/text-commands.d.ts +0 -24
  322. package/dist/core/commands/text-commands.js +0 -28
  323. package/dist/core/commands/text-commands.js.map +0 -1
  324. package/dist/core/selection/mapping.cjs +0 -200
  325. package/dist/core/selection/mapping.cjs.map +0 -1
  326. package/dist/core/selection/mapping.d.cts +0 -2
  327. package/dist/core/selection/mapping.d.ts +0 -2
  328. package/dist/core/selection/mapping.js +0 -31
  329. package/dist/core/selection/mapping.js.map +0 -1
  330. package/dist/core/state/editor-state.cjs +0 -2278
  331. package/dist/core/state/editor-state.cjs.map +0 -1
  332. package/dist/core/state/editor-state.d.cts +0 -2
  333. package/dist/core/state/editor-state.d.ts +0 -2
  334. package/dist/core/state/editor-state.js +0 -26
  335. package/dist/core/state/editor-state.js.map +0 -1
  336. package/dist/index.cjs +0 -38553
  337. package/dist/index.cjs.map +0 -1
  338. package/dist/index.d.cts +0 -15
  339. package/dist/index.d.ts +0 -15
  340. package/dist/index.js +0 -7856
  341. package/dist/index.js.map +0 -1
  342. package/dist/io/docx-session.cjs +0 -16236
  343. package/dist/io/docx-session.cjs.map +0 -1
  344. package/dist/io/docx-session.d.cts +0 -21
  345. package/dist/io/docx-session.d.ts +0 -21
  346. package/dist/io/docx-session.js +0 -18
  347. package/dist/io/docx-session.js.map +0 -1
  348. package/dist/legal/index.cjs +0 -3900
  349. package/dist/legal/index.cjs.map +0 -1
  350. package/dist/legal/index.d.cts +0 -86
  351. package/dist/legal/index.d.ts +0 -86
  352. package/dist/legal/index.js +0 -616
  353. package/dist/legal/index.js.map +0 -1
  354. package/dist/public-types-7ZL_94cz.d.ts +0 -1573
  355. package/dist/public-types-CeMaDueh.d.cts +0 -1573
  356. package/dist/public-types.cjs +0 -19
  357. package/dist/public-types.cjs.map +0 -1
  358. package/dist/public-types.d.cts +0 -2
  359. package/dist/public-types.d.ts +0 -2
  360. package/dist/public-types.js +0 -1
  361. package/dist/public-types.js.map +0 -1
  362. package/dist/runtime/document-runtime.cjs +0 -11140
  363. package/dist/runtime/document-runtime.cjs.map +0 -1
  364. package/dist/runtime/document-runtime.d.cts +0 -231
  365. package/dist/runtime/document-runtime.d.ts +0 -231
  366. package/dist/runtime/document-runtime.js +0 -21
  367. package/dist/runtime/document-runtime.js.map +0 -1
  368. package/dist/structural-helpers-CilgOVhh.d.cts +0 -10
  369. package/dist/structural-helpers-q0Gd-eBN.d.ts +0 -10
  370. package/dist/ui-tailwind/editor-surface/search-plugin.cjs +0 -313
  371. package/dist/ui-tailwind/editor-surface/search-plugin.cjs.map +0 -1
  372. package/dist/ui-tailwind/editor-surface/search-plugin.d.cts +0 -67
  373. package/dist/ui-tailwind/editor-surface/search-plugin.d.ts +0 -67
  374. package/dist/ui-tailwind/editor-surface/search-plugin.js +0 -23
  375. package/dist/ui-tailwind/editor-surface/search-plugin.js.map +0 -1
  376. package/dist/ui-tailwind/index.cjs +0 -4833
  377. package/dist/ui-tailwind/index.cjs.map +0 -1
  378. package/dist/ui-tailwind/index.d.cts +0 -617
  379. package/dist/ui-tailwind/index.d.ts +0 -617
  380. package/dist/ui-tailwind/index.js +0 -575
  381. package/dist/ui-tailwind/index.js.map +0 -1
@@ -0,0 +1,1553 @@
1
+ import type {
2
+ EditorStoryTarget,
3
+ EditorSurfaceSnapshot,
4
+ SecondaryStorySurface,
5
+ SurfaceBlockSnapshot,
6
+ SurfaceInlineSegment,
7
+ SurfaceTableCellSnapshot,
8
+ SurfaceTableRowSnapshot,
9
+ SurfaceTextMark,
10
+ } from "../api/public-types";
11
+ import type {
12
+ CanonicalDocumentEnvelope,
13
+ SelectionSnapshot,
14
+ } from "../core/state/editor-state.ts";
15
+ import type {
16
+ BlockNode,
17
+ ChartPreviewNode,
18
+ DocumentRootNode,
19
+ InlineNode,
20
+ MediaCatalog,
21
+ ParagraphNode,
22
+ SdtNode,
23
+ ShapeNode,
24
+ SmartArtPreviewNode,
25
+ TableCellBorders,
26
+ TableNode,
27
+ TextMark,
28
+ VmlShapeNode,
29
+ WordArtNode,
30
+ } from "../model/canonical-document.ts";
31
+ import {
32
+ describeOpaqueFragment,
33
+ describeStructuredWrapperBlock,
34
+ getOpaqueFragment,
35
+ isBlockedImportFeatureKey,
36
+ } from "../preservation/store.ts";
37
+ import { getStoryBlocks } from "./story-targeting.ts";
38
+ import {
39
+ createNumberingPrefixResolver,
40
+ type NumberingPrefixResult,
41
+ type NumberingPrefixResolver,
42
+ } from "./numbering-prefix.ts";
43
+ import {
44
+ collectSectionContexts,
45
+ findHeaderFooterDocumentEntry,
46
+ resolveSectionVariants,
47
+ } from "./story-context.ts";
48
+ import { resolveTableStyleResolution } from "./table-style-resolver.ts";
49
+
50
+ interface ParagraphAccumulator {
51
+ blockId: string;
52
+ kind: "paragraph";
53
+ from: number;
54
+ to: number;
55
+ styleId?: string;
56
+ numbering?: ParagraphNode["numbering"];
57
+ numberingPrefix?: string;
58
+ numberingSuffix?: "tab" | "space" | "nothing";
59
+ resolvedNumbering?: Extract<SurfaceBlockSnapshot, { kind: "paragraph" }>["resolvedNumbering"];
60
+ contextualSpacing?: boolean;
61
+ segments: SurfaceInlineSegment[];
62
+ }
63
+
64
+ export function createEditorSurfaceSnapshot(
65
+ document: CanonicalDocumentEnvelope,
66
+ _selection: SelectionSnapshot,
67
+ activeStory: EditorStoryTarget = { kind: "main" },
68
+ ): EditorSurfaceSnapshot {
69
+ const root = normalizeDocumentRoot({
70
+ type: "doc",
71
+ children: [...getStoryBlocks(document, activeStory)],
72
+ });
73
+ const blocks: SurfaceBlockSnapshot[] = [];
74
+ const lockedFragmentIds: string[] = [];
75
+ const numberingPrefixResolver = createNumberingPrefixResolver(document.numbering);
76
+ let cursor = 0;
77
+ const counters = {
78
+ paragraph: 0,
79
+ table: 0,
80
+ opaque: 0,
81
+ sdt: 0,
82
+ customXml: 0,
83
+ altChunk: 0,
84
+ };
85
+
86
+ for (let index = 0; index < root.children.length; index += 1) {
87
+ const surfaceBlock = createSurfaceBlock(
88
+ root.children[index],
89
+ document,
90
+ cursor,
91
+ counters,
92
+ numberingPrefixResolver,
93
+ );
94
+ blocks.push(surfaceBlock.block);
95
+ lockedFragmentIds.push(...surfaceBlock.lockedFragmentIds);
96
+ cursor = surfaceBlock.nextCursor;
97
+ if (index < root.children.length - 1 && root.children[index + 1]?.type === "paragraph") {
98
+ cursor += 1;
99
+ }
100
+ }
101
+
102
+ const secondaryStories = createSecondaryStorySurfaces(document);
103
+
104
+ return {
105
+ storySize: cursor,
106
+ plainText: createPlainText(blocks),
107
+ blocks,
108
+ lockedFragmentIds,
109
+ secondaryStories,
110
+ };
111
+ }
112
+
113
+ function createSurfaceBlock(
114
+ block: BlockNode,
115
+ document: CanonicalDocumentEnvelope,
116
+ cursor: number,
117
+ counters: {
118
+ paragraph: number;
119
+ table: number;
120
+ opaque: number;
121
+ sdt: number;
122
+ customXml: number;
123
+ altChunk: number;
124
+ },
125
+ numberingPrefixResolver: NumberingPrefixResolver,
126
+ ): { block: SurfaceBlockSnapshot; lockedFragmentIds: string[]; nextCursor: number } {
127
+ if (block.type === "opaque_block") {
128
+ const fragment = getOpaqueFragment(document.preservation as never, block.fragmentId);
129
+ const descriptor = fragment ? describeOpaqueFragment(fragment) : null;
130
+ const blockedReasonCode = descriptor && isBlockedImportFeatureKey(descriptor.featureKey)
131
+ ? "workflow_blocked_import"
132
+ : "workflow_preserve_only";
133
+ const blockId = `opaque-${counters.opaque}`;
134
+ counters.opaque += 1;
135
+ return {
136
+ block: {
137
+ blockId,
138
+ kind: "opaque_block",
139
+ from: cursor,
140
+ to: cursor + 1,
141
+ fragmentId: block.fragmentId,
142
+ warningId: block.warningId,
143
+ label: descriptor?.label ?? "Unsupported OOXML fragment",
144
+ detail:
145
+ descriptor?.detail ??
146
+ "Locked whole-unit to keep unsupported OOXML intact through export.",
147
+ ...(descriptor ? { featureKey: descriptor.featureKey, blockedReasonCode } : {}),
148
+ state: "locked-preserve-only",
149
+ },
150
+ lockedFragmentIds: [block.fragmentId],
151
+ nextCursor: cursor + 1,
152
+ };
153
+ }
154
+
155
+ if (block.type === "table") {
156
+ const tableIndex = counters.table;
157
+ counters.table += 1;
158
+ return createTableBlock(
159
+ tableIndex,
160
+ block,
161
+ document,
162
+ cursor,
163
+ counters,
164
+ numberingPrefixResolver,
165
+ );
166
+ }
167
+
168
+ if (block.type === "sdt") {
169
+ const descriptor = describeStructuredWrapperBlock(block);
170
+ if (descriptor) {
171
+ const blockId = `sdt-wrapper-${counters.sdt}`;
172
+ counters.sdt += 1;
173
+ return {
174
+ block: {
175
+ blockId,
176
+ kind: "opaque_block",
177
+ from: cursor,
178
+ to: cursor + 1,
179
+ fragmentId: blockId,
180
+ warningId: blockId,
181
+ label: descriptor.label,
182
+ detail: descriptor.detail,
183
+ featureKey: descriptor.featureKey,
184
+ blockedReasonCode: isBlockedImportFeatureKey(descriptor.featureKey)
185
+ ? "workflow_blocked_import"
186
+ : "workflow_preserve_only",
187
+ state: "locked-preserve-only",
188
+ },
189
+ lockedFragmentIds: [],
190
+ nextCursor: cursor + 1,
191
+ };
192
+ }
193
+
194
+ const sdtIndex = counters.sdt;
195
+ counters.sdt += 1;
196
+ return createSdtBlock(
197
+ sdtIndex,
198
+ block,
199
+ document,
200
+ cursor,
201
+ counters,
202
+ numberingPrefixResolver,
203
+ );
204
+ }
205
+
206
+ if (block.type === "custom_xml") {
207
+ const descriptor = describeStructuredWrapperBlock(block);
208
+ const blockId = `custom-xml-${counters.customXml}`;
209
+ counters.customXml += 1;
210
+ return {
211
+ block: {
212
+ blockId,
213
+ kind: "opaque_block",
214
+ from: cursor,
215
+ to: cursor + 1,
216
+ fragmentId: blockId,
217
+ warningId: blockId,
218
+ label: descriptor?.label ?? "Custom XML wrapper",
219
+ detail: descriptor?.detail ?? "Custom XML wrapper remains package-backed and read-only.",
220
+ ...(descriptor
221
+ ? {
222
+ featureKey: descriptor.featureKey,
223
+ blockedReasonCode: isBlockedImportFeatureKey(descriptor.featureKey)
224
+ ? "workflow_blocked_import"
225
+ : "workflow_preserve_only",
226
+ }
227
+ : {}),
228
+ state: "locked-preserve-only",
229
+ },
230
+ lockedFragmentIds: [],
231
+ nextCursor: cursor + 1,
232
+ };
233
+ }
234
+
235
+ if (block.type === "alt_chunk") {
236
+ const descriptor = describeStructuredWrapperBlock(block);
237
+ const blockId = `alt-chunk-${counters.altChunk}`;
238
+ counters.altChunk += 1;
239
+ return {
240
+ block: {
241
+ blockId,
242
+ kind: "opaque_block",
243
+ from: cursor,
244
+ to: cursor + 1,
245
+ fragmentId: blockId,
246
+ warningId: blockId,
247
+ label: descriptor?.label ?? "AltChunk import",
248
+ detail:
249
+ descriptor?.detail ??
250
+ `AltChunk import remains package-backed and blocked through relationship ${block.relationshipId}.`,
251
+ ...(descriptor
252
+ ? {
253
+ featureKey: descriptor.featureKey,
254
+ blockedReasonCode: isBlockedImportFeatureKey(descriptor.featureKey)
255
+ ? "workflow_blocked_import"
256
+ : "workflow_preserve_only",
257
+ }
258
+ : {}),
259
+ state: "locked-preserve-only",
260
+ },
261
+ lockedFragmentIds: [],
262
+ nextCursor: cursor + 1,
263
+ };
264
+ }
265
+
266
+ if (block.type === "section_break") {
267
+ const blockId = `section-break-${counters.opaque}`;
268
+ counters.opaque += 1;
269
+ return {
270
+ block: {
271
+ blockId,
272
+ kind: "opaque_block",
273
+ from: cursor,
274
+ to: cursor + 1,
275
+ fragmentId: blockId,
276
+ warningId: blockId,
277
+ label: "Section break",
278
+ detail: "Section properties preserved as a read-only boundary.",
279
+ state: "locked-preserve-only",
280
+ },
281
+ lockedFragmentIds: [],
282
+ nextCursor: cursor + 1,
283
+ };
284
+ }
285
+
286
+ const paragraphIndex = counters.paragraph;
287
+ counters.paragraph += 1;
288
+ return createParagraphBlock(
289
+ paragraphIndex,
290
+ block,
291
+ document,
292
+ cursor,
293
+ numberingPrefixResolver,
294
+ );
295
+ }
296
+
297
+ function createTableBlock(
298
+ tableIndex: number,
299
+ table: TableNode,
300
+ document: CanonicalDocumentEnvelope,
301
+ cursor: number,
302
+ counters: {
303
+ paragraph: number;
304
+ table: number;
305
+ opaque: number;
306
+ sdt: number;
307
+ customXml: number;
308
+ altChunk: number;
309
+ },
310
+ numberingPrefixResolver: NumberingPrefixResolver,
311
+ ): { block: SurfaceBlockSnapshot; lockedFragmentIds: string[]; nextCursor: number } {
312
+ const lockedFragmentIds: string[] = [];
313
+ let innerCursor = cursor;
314
+ const rows: SurfaceTableRowSnapshot[] = [];
315
+ const rowSpans = computeTableRowSpans(table);
316
+ const resolvedTable = resolveTableStyleResolution(table, document.styles.tables);
317
+
318
+ for (const [rowIndex, row] of table.rows.entries()) {
319
+ const cells: SurfaceTableCellSnapshot[] = [];
320
+ const resolvedRow = resolvedTable.rows[rowIndex];
321
+ for (const [cellIndex, cell] of row.cells.entries()) {
322
+ const cellContent: SurfaceBlockSnapshot[] = [];
323
+ for (const child of cell.children) {
324
+ const result = createSurfaceBlock(
325
+ child,
326
+ document,
327
+ innerCursor,
328
+ counters,
329
+ numberingPrefixResolver,
330
+ );
331
+ cellContent.push(result.block);
332
+ lockedFragmentIds.push(...result.lockedFragmentIds);
333
+ innerCursor = result.nextCursor;
334
+ }
335
+ const resolvedCell = resolvedRow?.cells[cellIndex];
336
+ const cellBorders = resolveCellBorderStyles(resolvedCell?.borders ?? cell.borders);
337
+ cells.push({
338
+ gridSpan: cell.gridSpan ?? 1,
339
+ verticalMerge: cell.verticalMerge ?? null,
340
+ colspan: cell.gridSpan ?? 1,
341
+ rowspan: rowSpans.get(`${rowIndex}:${cellIndex}`) ?? 1,
342
+ ...(resolvedCell?.shading?.fill ? { backgroundColor: `#${resolvedCell.shading.fill}` } : {}),
343
+ ...(resolvedCell?.verticalAlign ? { verticalAlign: resolvedCell.verticalAlign } : {}),
344
+ ...(cellBorders.borderTop ? { borderTop: cellBorders.borderTop } : {}),
345
+ ...(cellBorders.borderRight ? { borderRight: cellBorders.borderRight } : {}),
346
+ ...(cellBorders.borderBottom ? { borderBottom: cellBorders.borderBottom } : {}),
347
+ ...(cellBorders.borderLeft ? { borderLeft: cellBorders.borderLeft } : {}),
348
+ content: cellContent,
349
+ });
350
+ }
351
+ const headerLike =
352
+ row.isHeader === true ||
353
+ resolvedRow?.style.isHeader === true;
354
+ rows.push({
355
+ cells,
356
+ ...(row.gridBefore !== undefined ? { gridBefore: row.gridBefore } : {}),
357
+ ...(row.gridAfter !== undefined ? { gridAfter: row.gridAfter } : {}),
358
+ ...(resolvedRow?.style.height !== undefined ? { height: resolvedRow.style.height } : {}),
359
+ ...(resolvedRow?.style.heightRule ? { heightRule: resolvedRow.style.heightRule } : {}),
360
+ ...(headerLike ? { isHeader: true } : {}),
361
+ });
362
+ }
363
+
364
+ return {
365
+ block: {
366
+ blockId: `table-${tableIndex}`,
367
+ kind: "table",
368
+ from: cursor,
369
+ to: innerCursor,
370
+ styleId: table.styleId,
371
+ gridColumns: table.gridColumns,
372
+ ...(resolvedTable.table?.alignment ? { alignment: resolvedTable.table.alignment } : {}),
373
+ tblLook: resolvedTable.effectiveTblLook,
374
+ rows,
375
+ },
376
+ lockedFragmentIds,
377
+ nextCursor: innerCursor,
378
+ };
379
+ }
380
+
381
+ function computeTableRowSpans(table: TableNode): Map<string, number> {
382
+ const positionedRows = table.rows.map((row) => {
383
+ let startColumn = 0;
384
+
385
+ return row.cells.map((cell, cellIndex) => {
386
+ const width = cell.gridSpan ?? 1;
387
+ const positionedCell = {
388
+ cell,
389
+ cellIndex,
390
+ startColumn,
391
+ endColumn: startColumn + width - 1,
392
+ };
393
+ startColumn += width;
394
+ return positionedCell;
395
+ });
396
+ });
397
+
398
+ const rowSpans = new Map<string, number>();
399
+
400
+ for (const [rowIndex, row] of positionedRows.entries()) {
401
+ for (const positionedCell of row) {
402
+ if (positionedCell.cell.verticalMerge !== "restart") {
403
+ rowSpans.set(`${rowIndex}:${positionedCell.cellIndex}`, 1);
404
+ continue;
405
+ }
406
+
407
+ let rowspan = 1;
408
+ for (let nextRowIndex = rowIndex + 1; nextRowIndex < positionedRows.length; nextRowIndex += 1) {
409
+ const continuedCell = positionedRows[nextRowIndex]?.find(
410
+ (candidate) =>
411
+ candidate.cell.verticalMerge === "continue" &&
412
+ candidate.startColumn === positionedCell.startColumn &&
413
+ candidate.endColumn === positionedCell.endColumn,
414
+ );
415
+
416
+ if (!continuedCell) {
417
+ break;
418
+ }
419
+
420
+ rowspan += 1;
421
+ }
422
+
423
+ rowSpans.set(`${rowIndex}:${positionedCell.cellIndex}`, rowspan);
424
+ }
425
+ }
426
+
427
+ return rowSpans;
428
+ }
429
+
430
+ function resolveCellBorderStyles(
431
+ borders: TableCellBorders | undefined,
432
+ ): { borderTop?: string; borderRight?: string; borderBottom?: string; borderLeft?: string } {
433
+ if (!borders) return {};
434
+ const result: { borderTop?: string; borderRight?: string; borderBottom?: string; borderLeft?: string } = {};
435
+ const sides = [["top", "borderTop"], ["right", "borderRight"], ["bottom", "borderBottom"], ["left", "borderLeft"]] as const;
436
+ for (const [side, key] of sides) {
437
+ const spec = borders[side];
438
+ if (!spec || spec.value === "none" || spec.value === "nil") continue;
439
+ const width = spec.size ? `${Math.max(1, Math.round(spec.size / 8))}px` : "1px";
440
+ const style = spec.value === "double" ? "double" : spec.value === "dashed" || spec.value === "dashSmallGap" ? "dashed" : spec.value === "dotted" ? "dotted" : "solid";
441
+ const color = spec.color && spec.color !== "auto" ? `#${spec.color}` : "currentColor";
442
+ result[key] = `${width} ${style} ${color}`;
443
+ }
444
+ return result;
445
+ }
446
+
447
+ function createSdtBlock(
448
+ sdtIndex: number,
449
+ block: SdtNode,
450
+ document: CanonicalDocumentEnvelope,
451
+ cursor: number,
452
+ counters: {
453
+ paragraph: number;
454
+ table: number;
455
+ opaque: number;
456
+ sdt: number;
457
+ customXml: number;
458
+ altChunk: number;
459
+ },
460
+ numberingPrefixResolver: NumberingPrefixResolver,
461
+ ): { block: SurfaceBlockSnapshot; lockedFragmentIds: string[]; nextCursor: number } {
462
+ const children: SurfaceBlockSnapshot[] = [];
463
+ const lockedFragmentIds: string[] = [];
464
+ let innerCursor = cursor;
465
+
466
+ for (const child of block.children) {
467
+ const result = createSurfaceBlock(
468
+ child,
469
+ document,
470
+ innerCursor,
471
+ counters,
472
+ numberingPrefixResolver,
473
+ );
474
+ children.push(result.block);
475
+ lockedFragmentIds.push(...result.lockedFragmentIds);
476
+ innerCursor = result.nextCursor;
477
+ }
478
+
479
+ return {
480
+ block: {
481
+ blockId: `sdt-${sdtIndex}`,
482
+ kind: "sdt_block",
483
+ from: cursor,
484
+ to: innerCursor,
485
+ ...(block.properties.sdtType ? { sdtType: block.properties.sdtType } : {}),
486
+ ...(block.properties.alias ? { alias: block.properties.alias } : {}),
487
+ ...(block.properties.tag ? { tag: block.properties.tag } : {}),
488
+ ...(block.properties.lock ? { lock: block.properties.lock } : {}),
489
+ ...(block.properties.checkbox ? { checkboxChecked: block.properties.checkbox.checked } : {}),
490
+ ...(block.properties.datePicker?.fullDate ? { dateValue: block.properties.datePicker.fullDate } : {}),
491
+ ...(block.properties.dropdownList ? { dropdownItems: block.properties.dropdownList } : {}),
492
+ ...(block.properties.comboBox ? { comboBoxItems: block.properties.comboBox } : {}),
493
+ ...(block.properties.showingPlcHdr ? { showingPlcHdr: true } : {}),
494
+ children,
495
+ },
496
+ lockedFragmentIds,
497
+ nextCursor: innerCursor,
498
+ };
499
+ }
500
+
501
+ function createParagraphBlock(
502
+ paragraphIndex: number,
503
+ paragraph: ParagraphNode,
504
+ document: CanonicalDocumentEnvelope,
505
+ start: number,
506
+ numberingPrefixResolver: NumberingPrefixResolver,
507
+ ): {
508
+ block: SurfaceBlockSnapshot;
509
+ nextCursor: number;
510
+ lockedFragmentIds: string[];
511
+ } {
512
+ const effectiveNumbering = resolveEffectiveParagraphNumbering(document, paragraph);
513
+ const resolvedNumbering = effectiveNumbering
514
+ ? numberingPrefixResolver.resolveDetailed(effectiveNumbering, paragraph)
515
+ : null;
516
+ const accumulator: ParagraphAccumulator = {
517
+ blockId: `paragraph-${paragraphIndex}`,
518
+ kind: "paragraph",
519
+ from: start,
520
+ to: start,
521
+ ...(paragraph.styleId ? { styleId: paragraph.styleId } : {}),
522
+ ...(effectiveNumbering ? { numbering: effectiveNumbering } : {}),
523
+ ...(resolvedNumbering
524
+ ? {
525
+ ...(resolvedNumbering.text !== null ? { numberingPrefix: resolvedNumbering.text } : {}),
526
+ ...(resolvedNumbering.text !== null && resolvedNumbering.suffix
527
+ ? { numberingSuffix: resolvedNumbering.suffix }
528
+ : {}),
529
+ resolvedNumbering: toSurfaceResolvedNumbering(resolvedNumbering),
530
+ }
531
+ : {}),
532
+ ...(paragraph.alignment ? { alignment: paragraph.alignment } : {}),
533
+ ...(paragraph.spacing ? { spacing: paragraph.spacing } : {}),
534
+ ...(paragraph.contextualSpacing !== undefined
535
+ ? { contextualSpacing: paragraph.contextualSpacing }
536
+ : {}),
537
+ ...(paragraph.indentation ? { indentation: paragraph.indentation } : {}),
538
+ ...(paragraph.borders ? { borders: paragraph.borders } : {}),
539
+ ...(paragraph.shading ? { shading: paragraph.shading } : {}),
540
+ ...(paragraph.tabStops && paragraph.tabStops.length > 0
541
+ ? { tabStops: paragraph.tabStops.map((tabStop) => toSurfaceTabStop(tabStop)) }
542
+ : {}),
543
+ ...(paragraph.keepNext ? { keepNext: true } : {}),
544
+ ...(paragraph.keepLines ? { keepLines: true } : {}),
545
+ ...(paragraph.pageBreakBefore ? { pageBreakBefore: true } : {}),
546
+ ...(paragraph.outlineLevel !== undefined ? { outlineLevel: paragraph.outlineLevel } : {}),
547
+ ...(paragraph.bidi ? { bidi: true } : {}),
548
+ ...(paragraph.suppressLineNumbers ? { suppressLineNumbers: true } : {}),
549
+ segments: [],
550
+ };
551
+ const lockedFragmentIds: string[] = [];
552
+ let cursor = start;
553
+ const children = Array.isArray(paragraph.children) ? paragraph.children : [];
554
+
555
+ for (const child of children) {
556
+ const result = appendInlineSegments(accumulator, child, document, cursor);
557
+ cursor = result.nextCursor;
558
+ lockedFragmentIds.push(...result.lockedFragmentIds);
559
+ }
560
+
561
+ accumulator.to = cursor;
562
+ return {
563
+ block: accumulator,
564
+ nextCursor: cursor,
565
+ lockedFragmentIds,
566
+ };
567
+ }
568
+
569
+ function resolveEffectiveParagraphNumbering(
570
+ document: CanonicalDocumentEnvelope,
571
+ paragraph: ParagraphNode,
572
+ ): ParagraphNode["numbering"] | undefined {
573
+ if (paragraph.numbering) {
574
+ return paragraph.numbering;
575
+ }
576
+ if (!paragraph.styleId) {
577
+ return undefined;
578
+ }
579
+
580
+ const paragraphStyles = document.styles?.paragraphs ?? {};
581
+ const styleChain = collectParagraphStyleChain(document, paragraph.styleId);
582
+ let styleNumbering:
583
+ | CanonicalDocumentEnvelope["styles"]["paragraphs"][string]["numbering"]
584
+ | undefined;
585
+ for (const styleId of styleChain) {
586
+ const style = paragraphStyles[styleId];
587
+ if (style?.numbering) {
588
+ styleNumbering = style.numbering;
589
+ break;
590
+ }
591
+ }
592
+ if (!styleNumbering) {
593
+ return undefined;
594
+ }
595
+ if (styleNumbering.level !== undefined) {
596
+ return {
597
+ numberingInstanceId: styleNumbering.numberingInstanceId,
598
+ level: styleNumbering.level,
599
+ };
600
+ }
601
+
602
+ const resolvedLevel = resolveStyleLinkedNumberingLevel(
603
+ document,
604
+ styleNumbering.numberingInstanceId,
605
+ styleChain,
606
+ );
607
+ return resolvedLevel !== undefined
608
+ ? {
609
+ numberingInstanceId: styleNumbering.numberingInstanceId,
610
+ level: resolvedLevel,
611
+ }
612
+ : undefined;
613
+ }
614
+
615
+ function collectParagraphStyleChain(
616
+ document: CanonicalDocumentEnvelope,
617
+ styleId: string,
618
+ ): string[] {
619
+ const paragraphStyles = document.styles?.paragraphs ?? {};
620
+ const chain: string[] = [];
621
+ const visited = new Set<string>();
622
+ let currentStyleId: string | undefined = styleId;
623
+
624
+ while (currentStyleId && !visited.has(currentStyleId)) {
625
+ visited.add(currentStyleId);
626
+ chain.push(currentStyleId);
627
+ currentStyleId = paragraphStyles[currentStyleId]?.basedOn;
628
+ }
629
+
630
+ return chain;
631
+ }
632
+
633
+ function resolveStyleLinkedNumberingLevel(
634
+ document: CanonicalDocumentEnvelope,
635
+ numberingInstanceId: string,
636
+ styleChain: readonly string[],
637
+ ): number | undefined {
638
+ const instance = document.numbering.instances[numberingInstanceId];
639
+ if (!instance) {
640
+ return undefined;
641
+ }
642
+
643
+ for (const styleId of styleChain) {
644
+ const overrideMatch = instance.overrides.find(
645
+ (override) => override.levelDefinition?.paragraphStyleId === styleId,
646
+ );
647
+ if (overrideMatch) {
648
+ return overrideMatch.level;
649
+ }
650
+ }
651
+
652
+ const abstractDefinition = document.numbering.abstractDefinitions[instance.abstractNumberingId];
653
+ if (!abstractDefinition) {
654
+ return undefined;
655
+ }
656
+
657
+ for (const styleId of styleChain) {
658
+ const levelMatch = abstractDefinition.levels.find(
659
+ (levelDefinition) => levelDefinition.paragraphStyleId === styleId,
660
+ );
661
+ if (levelMatch) {
662
+ return levelMatch.level;
663
+ }
664
+ }
665
+
666
+ return undefined;
667
+ }
668
+
669
+ function appendInlineSegments(
670
+ paragraph: ParagraphAccumulator,
671
+ node: InlineNode,
672
+ document: CanonicalDocumentEnvelope,
673
+ start: number,
674
+ hyperlinkHref?: string,
675
+ ): { nextCursor: number; lockedFragmentIds: string[] } {
676
+ switch (node.type) {
677
+ case "text":
678
+ paragraph.segments.push({
679
+ segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,
680
+ kind: "text",
681
+ from: start,
682
+ to: start + Array.from(node.text).length,
683
+ text: node.text,
684
+ ...(node.marks ? (() => {
685
+ const result = cloneMarks(node.marks);
686
+ return {
687
+ ...(result.marks.length > 0 ? { marks: result.marks } : {}),
688
+ ...(result.markAttrs ? { markAttrs: result.markAttrs } : {}),
689
+ };
690
+ })() : {}),
691
+ ...(hyperlinkHref ? { hyperlinkHref } : {}),
692
+ });
693
+ return { nextCursor: start + Array.from(node.text).length, lockedFragmentIds: [] };
694
+ case "tab":
695
+ paragraph.segments.push({
696
+ segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,
697
+ kind: "tab",
698
+ from: start,
699
+ to: start + 1,
700
+ ...(hyperlinkHref ? { hyperlinkHref } : {}),
701
+ });
702
+ return { nextCursor: start + 1, lockedFragmentIds: [] };
703
+ case "hard_break":
704
+ paragraph.segments.push({
705
+ segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,
706
+ kind: "hard_break",
707
+ from: start,
708
+ to: start + 1,
709
+ ...(hyperlinkHref ? { hyperlinkHref } : {}),
710
+ });
711
+ return { nextCursor: start + 1, lockedFragmentIds: [] };
712
+ case "hyperlink": {
713
+ let cursor = start;
714
+ for (const child of node.children) {
715
+ const result = appendInlineSegments(paragraph, child, document, cursor, node.href);
716
+ cursor = result.nextCursor;
717
+ }
718
+ return { nextCursor: cursor, lockedFragmentIds: [] };
719
+ }
720
+ case "image":
721
+ paragraph.segments.push({
722
+ segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,
723
+ kind: "image",
724
+ from: start,
725
+ to: start + 1,
726
+ mediaId: node.mediaId,
727
+ altText: node.altText,
728
+ state: hasMediaItem(document.media, node.mediaId) ? "editable" : "missing",
729
+ ...(node.display ? { display: node.display } : {}),
730
+ detail:
731
+ node.display === "floating"
732
+ ? createFloatingImageDetail(node.altText, node.floating)
733
+ : node.altText
734
+ ? `Alt text ${node.altText}.`
735
+ : "Inline image remains a whole-unit render surface.",
736
+ });
737
+ return { nextCursor: start + 1, lockedFragmentIds: [] };
738
+ case "opaque_inline": {
739
+ const fragment = getOpaqueFragment(document.preservation as never, node.fragmentId);
740
+ const descriptor = fragment ? describeOpaqueFragment(fragment) : null;
741
+ const preview = fragment ? describePreservedInlinePreview(fragment.payloadReference) : null;
742
+ const blockedReasonCode = descriptor && isBlockedImportFeatureKey(descriptor.featureKey)
743
+ ? "workflow_blocked_import"
744
+ : "workflow_preserve_only";
745
+ paragraph.segments.push({
746
+ segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,
747
+ kind: "opaque_inline",
748
+ from: start,
749
+ to: start + 1,
750
+ fragmentId: node.fragmentId,
751
+ warningId: node.warningId,
752
+ label: preview?.label ?? descriptor?.label ?? "Unsupported inline OOXML",
753
+ detail:
754
+ preview?.detail ??
755
+ descriptor?.detail ??
756
+ "Locked whole-unit to keep unsupported inline OOXML intact through export.",
757
+ ...(descriptor ? { featureKey: descriptor.featureKey, blockedReasonCode } : {}),
758
+ ...(preview?.presentation ? { presentation: preview.presentation } : {}),
759
+ state: "locked-preserve-only",
760
+ });
761
+ return { nextCursor: start + 1, lockedFragmentIds: [node.fragmentId] };
762
+ }
763
+ case "chart_preview":
764
+ return appendComplexPreviewSegment(paragraph, node, start, "Embedded chart", createChartDetail(node));
765
+ case "smartart_preview":
766
+ return appendComplexPreviewSegment(paragraph, node, start, "SmartArt diagram", createSmartArtDetail(node));
767
+ case "shape":
768
+ return appendComplexPreviewSegment(paragraph, node, start,
769
+ node.isTextBox ? "Text box" : "Drawing shape", createShapeDetail(node));
770
+ case "wordart":
771
+ return appendComplexPreviewSegment(paragraph, node, start, "WordArt", createWordArtDetail(node));
772
+ case "vml_shape":
773
+ return appendComplexPreviewSegment(paragraph, node, start, "Legacy VML drawing", createVmlDetail(node));
774
+ case "symbol":
775
+ paragraph.segments.push({
776
+ segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,
777
+ kind: "text",
778
+ from: start,
779
+ to: start + 1,
780
+ text: node.char ? String.fromCodePoint(parseInt(node.char, 16)) : "\uFFFD",
781
+ });
782
+ return { nextCursor: start + 1, lockedFragmentIds: [] };
783
+ case "column_break":
784
+ paragraph.segments.push({
785
+ segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,
786
+ kind: "opaque_inline",
787
+ from: start,
788
+ to: start + 1,
789
+ fragmentId: "",
790
+ warningId: "",
791
+ label: "Column break",
792
+ detail: "Word column break marker preserved for export safety.",
793
+ presentation: "quiet-marker",
794
+ state: "locked-preserve-only",
795
+ });
796
+ return { nextCursor: start + 1, lockedFragmentIds: [] };
797
+ case "footnote_ref":
798
+ paragraph.segments.push({
799
+ segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,
800
+ kind: "note_ref",
801
+ from: start,
802
+ to: start + 1,
803
+ noteKind: node.noteKind ?? "footnote",
804
+ noteId: node.noteId ?? "",
805
+ label: node.noteId ?? "*",
806
+ });
807
+ return { nextCursor: start + 1, lockedFragmentIds: [] };
808
+ case "field": {
809
+ const isSupportedField =
810
+ node.fieldFamily === "REF" ||
811
+ node.fieldFamily === "PAGEREF" ||
812
+ node.fieldFamily === "NOTEREF" ||
813
+ node.fieldFamily === "TOC";
814
+ if (node.children && node.children.length > 0) {
815
+ let cursor = start;
816
+ const lockedIds: string[] = [];
817
+ for (const child of node.children) {
818
+ const result = appendInlineSegments(paragraph, child, document, cursor);
819
+ cursor = result.nextCursor;
820
+ lockedIds.push(...result.lockedFragmentIds);
821
+ }
822
+ return { nextCursor: cursor, lockedFragmentIds: lockedIds };
823
+ }
824
+ if (isSupportedField) {
825
+ // Supported field with no resolved content — show as field chip
826
+ const fieldLabel =
827
+ node.fieldFamily === "TOC"
828
+ ? "Table of Contents"
829
+ : `${node.fieldFamily ?? "Field"}: ${node.fieldTarget ?? node.instruction.trim()}`;
830
+ paragraph.segments.push({
831
+ segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,
832
+ kind: "field_ref",
833
+ from: start,
834
+ to: start + 1,
835
+ fieldFamily: node.fieldFamily!,
836
+ fieldTarget: node.fieldTarget,
837
+ instruction: node.instruction,
838
+ refreshStatus: node.refreshStatus ?? "stale",
839
+ label: fieldLabel,
840
+ } as SurfaceInlineSegment);
841
+ return { nextCursor: start + 1, lockedFragmentIds: [] };
842
+ }
843
+ paragraph.segments.push({
844
+ segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,
845
+ kind: "opaque_inline",
846
+ from: start,
847
+ to: start + 1,
848
+ fragmentId: "",
849
+ warningId: "",
850
+ label: "Field",
851
+ detail: `Preserve-only field: ${node.instruction.trim()}`,
852
+ state: "locked-preserve-only",
853
+ });
854
+ return { nextCursor: start + 1, lockedFragmentIds: [] };
855
+ }
856
+ case "bookmark_start":
857
+ case "bookmark_end":
858
+ // Zero-width markers — no visual, no cursor advancement
859
+ return { nextCursor: start, lockedFragmentIds: [] };
860
+ default:
861
+ return { nextCursor: start + 1, lockedFragmentIds: [] };
862
+ }
863
+ }
864
+
865
+ function appendComplexPreviewSegment(
866
+ paragraph: ParagraphAccumulator,
867
+ node: { rawXml: string },
868
+ start: number,
869
+ label: string,
870
+ detail: string,
871
+ ): { nextCursor: number; lockedFragmentIds: string[] } {
872
+ paragraph.segments.push({
873
+ segmentId: `${paragraph.blockId}-segment-${paragraph.segments.length}`,
874
+ kind: "opaque_inline",
875
+ from: start,
876
+ to: start + 1,
877
+ fragmentId: `complex:${label.replace(/\s/g, "-").toLowerCase()}:${start}`,
878
+ warningId: `warning:complex-preview:${start}`,
879
+ label,
880
+ detail,
881
+ state: "locked-preserve-only",
882
+ });
883
+ return { nextCursor: start + 1, lockedFragmentIds: [] };
884
+ }
885
+
886
+ function createChartDetail(node: ChartPreviewNode): string {
887
+ const parts = ["Embedded chart."];
888
+ if (node.previewMediaId) {
889
+ parts.push(`Preview available via fallback image (${node.previewMediaId}).`);
890
+ } else {
891
+ parts.push("No fallback preview image found; chart data preserved in package.");
892
+ }
893
+ parts.push("Edit in Word to modify chart data. Original DrawingML preserved for lossless export.");
894
+ return parts.join(" ");
895
+ }
896
+
897
+ function createSmartArtDetail(node: SmartArtPreviewNode): string {
898
+ const parts = ["SmartArt diagram."];
899
+ if (node.previewMediaId) {
900
+ parts.push(`Preview available via fallback image (${node.previewMediaId}).`);
901
+ } else {
902
+ parts.push("No fallback preview image found; diagram structure preserved in package.");
903
+ }
904
+ parts.push("Edit in Word to modify diagram layout and content. Original DrawingML preserved for lossless export.");
905
+ return parts.join(" ");
906
+ }
907
+
908
+ function createShapeDetail(node: ShapeNode): string {
909
+ if (node.isTextBox) {
910
+ const parts = ["Text box."];
911
+ if (node.text) parts.push(`Content: "${node.text}".`);
912
+ parts.push("Text content is visible; formatting and geometry preserved for export.");
913
+ return parts.join(" ");
914
+ }
915
+ const parts = ["Drawing shape."];
916
+ if (node.geometry) parts.push(`Geometry: ${node.geometry}.`);
917
+ if (node.text) parts.push(`Text content: "${node.text}".`);
918
+ parts.push("Visual geometry is preview-only. Original DrawingML preserved for export.");
919
+ return parts.join(" ");
920
+ }
921
+
922
+ function createWordArtDetail(node: WordArtNode): string {
923
+ const parts = ["WordArt decorative text."];
924
+ if (node.text) parts.push(`Text: "${node.text}".`);
925
+ if (node.geometry) parts.push(`Effect: ${node.geometry}.`);
926
+ parts.push("Text effect is preview-only. Edit in Word for full formatting. Original DrawingML preserved for export.");
927
+ return parts.join(" ");
928
+ }
929
+
930
+ function createVmlDetail(node: VmlShapeNode): string {
931
+ const parts = ["Legacy VML drawing."];
932
+ if (node.shapeType) parts.push(`Type: ${node.shapeType}.`);
933
+ if (node.text) parts.push(`Text content: "${node.text}".`);
934
+ parts.push("VML content is preview-only. Edit in Word for full control. Original VML XML preserved for export.");
935
+ return parts.join(" ");
936
+ }
937
+
938
+ function createPlainText(
939
+ blocks: SurfaceBlockSnapshot[],
940
+ ): string {
941
+ const text: string[] = [];
942
+ for (const block of blocks) {
943
+ if (block.kind === "opaque_block") {
944
+ if (block.fragmentId.startsWith("preview:")) {
945
+ continue;
946
+ }
947
+ text.push("\uFFFA");
948
+ continue;
949
+ }
950
+
951
+ if (block.kind === "table") {
952
+ for (const row of block.rows) {
953
+ for (const cell of row.cells) {
954
+ text.push(createPlainText(cell.content));
955
+ }
956
+ }
957
+ continue;
958
+ }
959
+
960
+ if (block.kind === "sdt_block") {
961
+ text.push(createPlainText(block.children));
962
+ continue;
963
+ }
964
+
965
+ for (const segment of block.segments) {
966
+ switch (segment.kind) {
967
+ case "text":
968
+ text.push(segment.text);
969
+ break;
970
+ case "tab":
971
+ text.push("\t");
972
+ break;
973
+ case "hard_break":
974
+ text.push("\n");
975
+ break;
976
+ case "image":
977
+ text.push("\uFFFC");
978
+ break;
979
+ case "opaque_inline":
980
+ text.push("\uFFF9");
981
+ break;
982
+ }
983
+ }
984
+ }
985
+
986
+ return text.join("");
987
+ }
988
+
989
+ function createSecondaryStorySurfaces(
990
+ document: CanonicalDocumentEnvelope,
991
+ ): SecondaryStorySurface[] {
992
+ const surfaces: SecondaryStorySurface[] = [];
993
+ const subParts = document.subParts;
994
+ if (!subParts) {
995
+ return surfaces;
996
+ }
997
+
998
+ const numberingPrefixResolver = createNumberingPrefixResolver(document.numbering);
999
+
1000
+ for (const section of collectSectionContexts(document)) {
1001
+ const headerVariants = resolveSectionVariants(
1002
+ "header",
1003
+ section.index,
1004
+ section.properties?.headerReferences,
1005
+ subParts.headers ?? [],
1006
+ );
1007
+ for (const headerVariant of headerVariants) {
1008
+ const target: EditorStoryTarget = {
1009
+ kind: "header",
1010
+ relationshipId: headerVariant.relationshipId,
1011
+ variant: headerVariant.variant,
1012
+ sectionIndex: section.index,
1013
+ };
1014
+ const header = findHeaderFooterDocumentEntry(document, target);
1015
+ if (!header) {
1016
+ continue;
1017
+ }
1018
+ surfaces.push(
1019
+ createStorySurface(
1020
+ target,
1021
+ `Header · ${headerVariant.variant}`,
1022
+ header.blocks,
1023
+ document,
1024
+ numberingPrefixResolver,
1025
+ ),
1026
+ );
1027
+ }
1028
+
1029
+ const footerVariants = resolveSectionVariants(
1030
+ "footer",
1031
+ section.index,
1032
+ section.properties?.footerReferences,
1033
+ subParts.footers ?? [],
1034
+ );
1035
+ for (const footerVariant of footerVariants) {
1036
+ const target: EditorStoryTarget = {
1037
+ kind: "footer",
1038
+ relationshipId: footerVariant.relationshipId,
1039
+ variant: footerVariant.variant,
1040
+ sectionIndex: section.index,
1041
+ };
1042
+ const footer = findHeaderFooterDocumentEntry(document, target);
1043
+ if (!footer) {
1044
+ continue;
1045
+ }
1046
+ surfaces.push(
1047
+ createStorySurface(
1048
+ target,
1049
+ `Footer · ${footerVariant.variant}`,
1050
+ footer.blocks,
1051
+ document,
1052
+ numberingPrefixResolver,
1053
+ ),
1054
+ );
1055
+ }
1056
+ }
1057
+
1058
+ const footnotes = Object.values(subParts.footnoteCollection?.footnotes ?? {}).sort(compareNoteIds);
1059
+ for (const note of footnotes) {
1060
+ const target: EditorStoryTarget = { kind: "footnote", noteId: note.noteId };
1061
+ surfaces.push(createStorySurface(target, `Footnote ${note.noteId}`, note.blocks, document, numberingPrefixResolver));
1062
+ }
1063
+
1064
+ const endnotes = Object.values(subParts.footnoteCollection?.endnotes ?? {}).sort(compareNoteIds);
1065
+ for (const note of endnotes) {
1066
+ const target: EditorStoryTarget = { kind: "endnote", noteId: note.noteId };
1067
+ surfaces.push(createStorySurface(target, `Endnote ${note.noteId}`, note.blocks, document, numberingPrefixResolver));
1068
+ }
1069
+
1070
+ return surfaces;
1071
+ }
1072
+
1073
+ function createStorySurface(
1074
+ target: EditorStoryTarget,
1075
+ label: string,
1076
+ blocks: readonly BlockNode[],
1077
+ document: CanonicalDocumentEnvelope,
1078
+ numberingPrefixResolver: NumberingPrefixResolver,
1079
+ ): SecondaryStorySurface {
1080
+ const surfaceBlocks: SurfaceBlockSnapshot[] = [];
1081
+ let cursor = 0;
1082
+ const counters = {
1083
+ paragraph: 0,
1084
+ table: 0,
1085
+ opaque: 0,
1086
+ sdt: 0,
1087
+ customXml: 0,
1088
+ altChunk: 0,
1089
+ };
1090
+
1091
+ for (let index = 0; index < blocks.length; index += 1) {
1092
+ const surfaceBlock = createSurfaceBlock(
1093
+ blocks[index],
1094
+ document,
1095
+ cursor,
1096
+ counters,
1097
+ numberingPrefixResolver,
1098
+ );
1099
+ surfaceBlocks.push(surfaceBlock.block);
1100
+ cursor = surfaceBlock.nextCursor;
1101
+ if (index < blocks.length - 1 && blocks[index + 1]?.type === "paragraph") {
1102
+ cursor += 1;
1103
+ }
1104
+ }
1105
+
1106
+ return {
1107
+ target,
1108
+ label,
1109
+ storySize: cursor,
1110
+ blocks: surfaceBlocks,
1111
+ };
1112
+ }
1113
+
1114
+ function createSecondaryStoryPreviewBlocks(
1115
+ document: CanonicalDocumentEnvelope,
1116
+ cursor: number,
1117
+ ): SurfaceBlockSnapshot[] {
1118
+ const previews: SurfaceBlockSnapshot[] = [];
1119
+ const subParts = document.subParts;
1120
+ if (!subParts) {
1121
+ return previews;
1122
+ }
1123
+
1124
+ for (const header of subParts.headers ?? []) {
1125
+ previews.push(
1126
+ createSecondaryStoryPreviewBlock(
1127
+ `Header · ${header.variant}`,
1128
+ `header:${header.relationshipId}`,
1129
+ cursor,
1130
+ createSecondaryStoryPreviewDetail(header.partPath, header.blocks),
1131
+ ),
1132
+ );
1133
+ }
1134
+
1135
+ for (const footer of subParts.footers ?? []) {
1136
+ previews.push(
1137
+ createSecondaryStoryPreviewBlock(
1138
+ `Footer · ${footer.variant}`,
1139
+ `footer:${footer.relationshipId}`,
1140
+ cursor,
1141
+ createSecondaryStoryPreviewDetail(footer.partPath, footer.blocks),
1142
+ ),
1143
+ );
1144
+ }
1145
+
1146
+ const footnotes = Object.values(subParts.footnoteCollection?.footnotes ?? {}).sort(compareNoteIds);
1147
+ for (const note of footnotes) {
1148
+ previews.push(
1149
+ createSecondaryStoryPreviewBlock(
1150
+ `Footnote ${note.noteId}`,
1151
+ `footnote:${note.noteId}`,
1152
+ cursor,
1153
+ createSecondaryStoryPreviewDetail(`/word/footnotes.xml#${note.noteId}`, note.blocks),
1154
+ ),
1155
+ );
1156
+ }
1157
+
1158
+ const endnotes = Object.values(subParts.footnoteCollection?.endnotes ?? {}).sort(compareNoteIds);
1159
+ for (const note of endnotes) {
1160
+ previews.push(
1161
+ createSecondaryStoryPreviewBlock(
1162
+ `Endnote ${note.noteId}`,
1163
+ `endnote:${note.noteId}`,
1164
+ cursor,
1165
+ createSecondaryStoryPreviewDetail(`/word/endnotes.xml#${note.noteId}`, note.blocks),
1166
+ ),
1167
+ );
1168
+ }
1169
+
1170
+ return previews;
1171
+ }
1172
+
1173
+ function createSecondaryStoryPreviewBlock(
1174
+ label: string,
1175
+ previewId: string,
1176
+ cursor: number,
1177
+ detail: string,
1178
+ ): Extract<SurfaceBlockSnapshot, { kind: "opaque_block" }> {
1179
+ return {
1180
+ blockId: `secondary-story-${previewId.replace(/[^a-z0-9._:-]+/gi, "-")}`,
1181
+ kind: "opaque_block",
1182
+ from: cursor,
1183
+ to: cursor,
1184
+ fragmentId: `preview:${previewId}`,
1185
+ warningId: `preview:${previewId}`,
1186
+ label,
1187
+ detail,
1188
+ state: "locked-preserve-only",
1189
+ };
1190
+ }
1191
+
1192
+ function createSecondaryStoryPreviewDetail(
1193
+ sourceLabel: string,
1194
+ blocks: readonly BlockNode[],
1195
+ ): string {
1196
+ const previewLines = blocks
1197
+ .map((block) => summarizePreviewBlock(block))
1198
+ .filter((line) => line.trim().length > 0);
1199
+ const previewText = previewLines.length > 0 ? previewLines.join("\n\n") : "Empty story.";
1200
+ return `Read-only preview from ${sourceLabel}.\n${previewText}`;
1201
+ }
1202
+
1203
+ function summarizePreviewBlock(block: BlockNode): string {
1204
+ switch (block.type) {
1205
+ case "paragraph": {
1206
+ const text = block.children.map((child) => summarizePreviewInline(child)).join("");
1207
+ return text.trim().length > 0 ? text : "¶";
1208
+ }
1209
+ case "table":
1210
+ return "[Table preserved in secondary story]";
1211
+ case "opaque_block":
1212
+ return "[Locked block preserved for export]";
1213
+ case "sdt":
1214
+ return "[Content control preview]";
1215
+ case "custom_xml":
1216
+ return "[Custom XML preview]";
1217
+ case "alt_chunk":
1218
+ return "[AltChunk preview]";
1219
+ case "section_break":
1220
+ return "[Section boundary]";
1221
+ }
1222
+ }
1223
+
1224
+ function summarizePreviewInline(node: InlineNode): string {
1225
+ switch (node.type) {
1226
+ case "text":
1227
+ return node.text;
1228
+ case "tab":
1229
+ return "\t";
1230
+ case "hard_break":
1231
+ return "\n";
1232
+ case "hyperlink":
1233
+ return node.children.map((child) => summarizePreviewInline(child)).join("");
1234
+ case "footnote_ref":
1235
+ return node.noteKind === "footnote" ? `[fn ${node.noteId}]` : `[en ${node.noteId}]`;
1236
+ case "field": {
1237
+ const instruction = node.instruction.trim();
1238
+ return instruction.length > 0 ? `[Field: ${instruction}]` : "[Field]";
1239
+ }
1240
+ case "bookmark_start":
1241
+ return node.name ? `[Bookmark: ${node.name}]` : "[Bookmark]";
1242
+ case "bookmark_end":
1243
+ return "";
1244
+ case "image":
1245
+ return node.altText ? `[Image: ${node.altText}]` : "[Image]";
1246
+ case "opaque_inline":
1247
+ return "[Locked inline content]";
1248
+ case "symbol":
1249
+ return node.char ? String.fromCodePoint(parseInt(node.char, 16)) : "\uFFFD";
1250
+ case "column_break":
1251
+ return "[Column break]";
1252
+ case "chart_preview":
1253
+ return "[Embedded chart]";
1254
+ case "smartart_preview":
1255
+ return "[SmartArt diagram]";
1256
+ case "shape":
1257
+ if (node.isTextBox && node.text) return `[Text box: ${node.text}]`;
1258
+ return node.text ? `[Shape: ${node.text}]` : "[Drawing shape]";
1259
+ case "wordart":
1260
+ return node.text ? `[WordArt: ${node.text}]` : "[WordArt]";
1261
+ case "vml_shape":
1262
+ return node.text ? `[VML: ${node.text}]` : "[Legacy VML drawing]";
1263
+ }
1264
+ }
1265
+
1266
+ function compareNoteIds(
1267
+ left: { noteId: string },
1268
+ right: { noteId: string },
1269
+ ): number {
1270
+ return Number.parseInt(left.noteId, 10) - Number.parseInt(right.noteId, 10);
1271
+ }
1272
+
1273
+ function toSurfaceTabStop(
1274
+ tabStop: NonNullable<ParagraphNode["tabStops"]>[number],
1275
+ ): { pos: number; val?: string; leader?: string } {
1276
+ return {
1277
+ pos: tabStop.position,
1278
+ ...(tabStop.align ? { val: tabStop.align } : {}),
1279
+ ...(tabStop.leader ? { leader: tabStop.leader } : {}),
1280
+ };
1281
+ }
1282
+
1283
+ function toSurfaceResolvedNumbering(
1284
+ numbering: NumberingPrefixResult,
1285
+ ): NonNullable<Extract<SurfaceBlockSnapshot, { kind: "paragraph" }>["resolvedNumbering"]> {
1286
+ return {
1287
+ level: numbering.level,
1288
+ format: numbering.format,
1289
+ ...(numbering.text !== null ? { text: numbering.text } : {}),
1290
+ startAt: numbering.startAt,
1291
+ ...(numbering.paragraphStyleId ? { paragraphStyleId: numbering.paragraphStyleId } : {}),
1292
+ ...(numbering.isLegalNumbering ? { isLegalNumbering: true } : {}),
1293
+ ...(numbering.suffix ? { suffix: numbering.suffix } : {}),
1294
+ geometry: {
1295
+ ...(numbering.geometry.markerJustification
1296
+ ? { markerJustification: numbering.geometry.markerJustification }
1297
+ : {}),
1298
+ ...(numbering.geometry.spacing ? { spacing: { ...numbering.geometry.spacing } } : {}),
1299
+ ...(numbering.geometry.indentation
1300
+ ? { indentation: { ...numbering.geometry.indentation } }
1301
+ : {}),
1302
+ ...(numbering.geometry.tabStops && numbering.geometry.tabStops.length > 0
1303
+ ? { tabStops: numbering.geometry.tabStops.map((tabStop) => toSurfaceTabStop(tabStop)) }
1304
+ : {}),
1305
+ ...(numbering.geometry.markerLane
1306
+ ? { markerLane: { ...numbering.geometry.markerLane } }
1307
+ : {}),
1308
+ ...(numbering.geometry.textColumn
1309
+ ? { textColumn: { ...numbering.geometry.textColumn } }
1310
+ : {}),
1311
+ },
1312
+ };
1313
+ }
1314
+
1315
+ function describePreservedInlinePreview(
1316
+ payloadReference: string,
1317
+ ): {
1318
+ label: string;
1319
+ detail: string;
1320
+ presentation?: "inline-chip" | "quiet-marker";
1321
+ } | null {
1322
+ if (/\b(?:w:)?proofErr\b/u.test(payloadReference)) {
1323
+ const proofType = /\bw:type="([^"]+)"/u.exec(payloadReference)?.[1];
1324
+ return {
1325
+ label: "Proofing marker",
1326
+ detail:
1327
+ proofType && proofType.trim().length > 0
1328
+ ? `Word proofing marker (${proofType}) preserved for export safety.`
1329
+ : "Word proofing marker preserved for export safety.",
1330
+ presentation: "quiet-marker",
1331
+ };
1332
+ }
1333
+
1334
+ if (/\b(?:w:)?lastRenderedPageBreak\b/u.test(payloadReference)) {
1335
+ return {
1336
+ label: "Rendered page break",
1337
+ detail: "Word rendered page-break marker preserved for export safety.",
1338
+ presentation: "quiet-marker",
1339
+ };
1340
+ }
1341
+
1342
+ if (/\b(?:w:)?permStart\b/u.test(payloadReference)) {
1343
+ const editorGroup = /\bw:edGrp="([^"]+)"/u.exec(payloadReference)?.[1];
1344
+ return {
1345
+ label: "Protected range start",
1346
+ detail:
1347
+ editorGroup && editorGroup.trim().length > 0
1348
+ ? `Protected range start for ${editorGroup} preserved for export safety.`
1349
+ : "Protected range start preserved for export safety.",
1350
+ presentation: "quiet-marker",
1351
+ };
1352
+ }
1353
+
1354
+ if (/\b(?:w:)?permEnd\b/u.test(payloadReference)) {
1355
+ return {
1356
+ label: "Protected range end",
1357
+ detail: "Protected range end preserved for export safety.",
1358
+ presentation: "quiet-marker",
1359
+ };
1360
+ }
1361
+
1362
+ if (/\b(?:w:)?bookmarkStart\b/u.test(payloadReference)) {
1363
+ const name = /\bw:name="([^"]+)"/u.exec(payloadReference)?.[1];
1364
+ return {
1365
+ label: name ? `Bookmark · ${name}` : "Bookmark",
1366
+ detail: name
1367
+ ? `Bookmark anchor \"${name}\" is preserved as a read-only inline token for export safety.`
1368
+ : "Bookmark anchor is preserved as a read-only inline token for export safety.",
1369
+ };
1370
+ }
1371
+
1372
+ if (/\b(?:w:)?bookmarkEnd\b/u.test(payloadReference)) {
1373
+ return {
1374
+ label: "Bookmark end",
1375
+ detail: "Bookmark end marker is preserved as a read-only inline token for export safety.",
1376
+ };
1377
+ }
1378
+
1379
+ if (/\b(?:w:)?fldSimple\b|\b(?:w:)?fldChar\b|\b(?:w:)?instrText\b/u.test(payloadReference)) {
1380
+ const simpleInstruction = /\bw:instr="([^"]*)"/u.exec(payloadReference)?.[1];
1381
+ const complexInstruction = [...payloadReference.matchAll(/<(?:\w+:)?instrText\b[^>]*>([\s\S]*?)<\/(?:\w+:)?instrText>/gu)]
1382
+ .map((match) => decodeXmlEntities(match[1] ?? ""))
1383
+ .join("")
1384
+ .trim();
1385
+ const instruction = (simpleInstruction ?? complexInstruction ?? "").trim();
1386
+ const family = /^([A-Z]+)/i.exec(instruction)?.[1]?.toUpperCase();
1387
+ const label =
1388
+ family === "TOC"
1389
+ ? "Table of Contents field"
1390
+ : family
1391
+ ? `${family} field`
1392
+ : "Field";
1393
+ return {
1394
+ label,
1395
+ detail:
1396
+ instruction.length > 0
1397
+ ? `Read-only field preserved for export safety. Instruction: ${instruction}.`
1398
+ : "Read-only field preserved for export safety.",
1399
+ };
1400
+ }
1401
+
1402
+ return null;
1403
+ }
1404
+
1405
+ function decodeXmlEntities(text: string): string {
1406
+ return text
1407
+ .replace(/&lt;/g, "<")
1408
+ .replace(/&gt;/g, ">")
1409
+ .replace(/&quot;/g, "\"")
1410
+ .replace(/&apos;/g, "'")
1411
+ .replace(/&amp;/g, "&");
1412
+ }
1413
+
1414
+ function cloneMarks(marks: TextMark[]): {
1415
+ marks: SurfaceTextMark[];
1416
+ markAttrs?: {
1417
+ backgroundColor?: string;
1418
+ charSpacing?: number;
1419
+ kerning?: number;
1420
+ textFill?: string;
1421
+ fontFamily?: string;
1422
+ fontSize?: number;
1423
+ textColor?: string;
1424
+ };
1425
+ } {
1426
+ const supported: SurfaceTextMark[] = [];
1427
+ const attrs: {
1428
+ backgroundColor?: string;
1429
+ charSpacing?: number;
1430
+ kerning?: number;
1431
+ textFill?: string;
1432
+ fontFamily?: string;
1433
+ fontSize?: number;
1434
+ textColor?: string;
1435
+ } = {};
1436
+ let shadingColor: string | undefined;
1437
+ let highlightColor: string | undefined;
1438
+ for (const mark of marks) {
1439
+ switch (mark.type) {
1440
+ case "bold":
1441
+ case "italic":
1442
+ case "underline":
1443
+ case "strikethrough":
1444
+ case "doubleStrikethrough":
1445
+ case "vanish":
1446
+ case "emboss":
1447
+ case "imprint":
1448
+ case "shadow":
1449
+ supported.push(mark.type);
1450
+ break;
1451
+ case "position":
1452
+ if (mark.val > 0) supported.push("superscript");
1453
+ else if (mark.val < 0) supported.push("subscript");
1454
+ break;
1455
+ case "backgroundColor":
1456
+ shadingColor = mark.color;
1457
+ break;
1458
+ case "highlight":
1459
+ highlightColor = mark.color;
1460
+ break;
1461
+ case "charSpacing":
1462
+ attrs.charSpacing = mark.val;
1463
+ break;
1464
+ case "kerning":
1465
+ attrs.kerning = mark.val;
1466
+ break;
1467
+ case "textFill":
1468
+ attrs.textFill = mark.xml;
1469
+ break;
1470
+ case "fontFamily":
1471
+ attrs.fontFamily = mark.val;
1472
+ break;
1473
+ case "fontSize":
1474
+ attrs.fontSize = mark.val;
1475
+ break;
1476
+ case "textColor":
1477
+ attrs.textColor = mark.color;
1478
+ break;
1479
+ case "smallCaps":
1480
+ supported.push("smallCaps");
1481
+ break;
1482
+ case "allCaps":
1483
+ supported.push("allCaps");
1484
+ break;
1485
+ case "lang":
1486
+ // no visual effect — skip
1487
+ break;
1488
+ }
1489
+ }
1490
+ if (highlightColor || shadingColor) {
1491
+ attrs.backgroundColor = highlightColor ?? shadingColor;
1492
+ }
1493
+ const hasAttrs = Object.keys(attrs).length > 0;
1494
+ return hasAttrs ? { marks: supported, markAttrs: attrs } : { marks: supported };
1495
+ }
1496
+
1497
+ function normalizeDocumentRoot(content: unknown): DocumentRootNode {
1498
+ if (content && typeof content === "object" &&
1499
+ ((content as { type?: string }).type === "doc" || (content as { type?: string }).type === "document_root")) {
1500
+ return content as DocumentRootNode;
1501
+ }
1502
+
1503
+ if (Array.isArray(content)) {
1504
+ return {
1505
+ type: "doc",
1506
+ children: content.filter(
1507
+ (value): value is DocumentRootNode["children"][number] =>
1508
+ Boolean(value) &&
1509
+ typeof value === "object" &&
1510
+ ((value as { type?: string }).type === "paragraph" ||
1511
+ (value as { type?: string }).type === "table" ||
1512
+ (value as { type?: string }).type === "sdt" ||
1513
+ (value as { type?: string }).type === "custom_xml" ||
1514
+ (value as { type?: string }).type === "alt_chunk" ||
1515
+ (value as { type?: string }).type === "opaque_block"),
1516
+ ),
1517
+ };
1518
+ }
1519
+
1520
+ return {
1521
+ type: "doc",
1522
+ children: [{ type: "paragraph", children: [] }],
1523
+ };
1524
+ }
1525
+
1526
+ function createFloatingImageDetail(
1527
+ altText: string | undefined,
1528
+ floating: {
1529
+ horizontalPosition?: { relativeFrom?: string; align?: string; offset?: number };
1530
+ verticalPosition?: { relativeFrom?: string; align?: string; offset?: number };
1531
+ wrap?: string;
1532
+ } | undefined,
1533
+ ): string {
1534
+ const parts = [altText ? `Alt text ${altText}.` : "Floating image rendered inline in the editor."];
1535
+ if (floating?.wrap) {
1536
+ parts.push(`Wrap ${floating.wrap}.`);
1537
+ }
1538
+ if (floating?.horizontalPosition?.align || floating?.horizontalPosition?.offset !== undefined) {
1539
+ parts.push(
1540
+ `Horizontal ${floating.horizontalPosition.align ?? floating.horizontalPosition.offset}.`,
1541
+ );
1542
+ }
1543
+ if (floating?.verticalPosition?.align || floating?.verticalPosition?.offset !== undefined) {
1544
+ parts.push(
1545
+ `Vertical ${floating.verticalPosition.align ?? floating.verticalPosition.offset}.`,
1546
+ );
1547
+ }
1548
+ return parts.join(" ");
1549
+ }
1550
+
1551
+ function hasMediaItem(media: MediaCatalog, mediaId: string): boolean {
1552
+ return mediaId in media.items;
1553
+ }