@a3s-lab/office 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (463) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +470 -0
  3. package/THIRD_PARTY_NOTICES.md +33 -0
  4. package/dist/0~1403.js +245 -0
  5. package/dist/0~152.js +94 -0
  6. package/dist/0~3539.js +1856 -0
  7. package/dist/0~3557.js +179 -0
  8. package/dist/0~3635.js +302 -0
  9. package/dist/0~4595.js +1162 -0
  10. package/dist/0~5050.js +308 -0
  11. package/dist/0~6552.js +787 -0
  12. package/dist/0~7048.js +2110 -0
  13. package/dist/0~7614.js +1037 -0
  14. package/dist/0~8155.js +299 -0
  15. package/dist/0~9445.js +283 -0
  16. package/dist/0~9512.js +743 -0
  17. package/dist/0~document-editor.js +10967 -0
  18. package/dist/0~markdown-editor.js +2260 -0
  19. package/dist/0~pdf-viewer.js +2156 -0
  20. package/dist/0~presentation-editor.js +8359 -0
  21. package/dist/0~rslib-runtime.js +27 -0
  22. package/dist/0~spreadsheet-editor.js +10388 -0
  23. package/dist/0~use-office-draft.js +46 -0
  24. package/dist/0~work-document-extensions.js +2470 -0
  25. package/dist/0~work-document-links.js +14 -0
  26. package/dist/0~work-document-model-codec.js +42 -0
  27. package/dist/0~work-document-page-color.js +11 -0
  28. package/dist/0~work-document-paragraph-formatting.js +425 -0
  29. package/dist/0~work-docx-bibliography.js +347 -0
  30. package/dist/0~work-docx-export.js +1151 -0
  31. package/dist/0~work-docx-import.js +3116 -0
  32. package/dist/0~work-docx-page-color.js +42 -0
  33. package/dist/0~work-office-diagnostics.js +1377 -0
  34. package/dist/0~work-pptx-export.js +1009 -0
  35. package/dist/0~work-pptx-import.js +1138 -0
  36. package/dist/0~work-presentation-charts.js +442 -0
  37. package/dist/0~work-presentation-transition.js +38 -0
  38. package/dist/0~work-presentation-visual-scale.js +38 -0
  39. package/dist/0~work-spreadsheet-formula-support.js +9 -0
  40. package/dist/1134.js +445 -0
  41. package/dist/4104.js +5786 -0
  42. package/dist/432.js +211 -0
  43. package/dist/4704.js +1364 -0
  44. package/dist/6489.js +182 -0
  45. package/dist/8715.js +3959 -0
  46. package/dist/8728.js +723 -0
  47. package/dist/9356.js +10 -0
  48. package/dist/core.d.ts +15 -0
  49. package/dist/core.js +4 -0
  50. package/dist/index.d.ts +2 -0
  51. package/dist/index.js +5 -0
  52. package/dist/internal/design-system/primitives/button/button.d.ts +9 -0
  53. package/dist/internal/design-system/primitives/button/icon-button.d.ts +7 -0
  54. package/dist/internal/design-system/primitives/dialog/dialog.d.ts +12 -0
  55. package/dist/internal/design-system/primitives/feedback/collection-state.d.ts +9 -0
  56. package/dist/internal/design-system/primitives/feedback/inline-notice.d.ts +10 -0
  57. package/dist/internal/design-system/primitives/feedback/state-view.d.ts +13 -0
  58. package/dist/internal/design-system/primitives/form/field.d.ts +19 -0
  59. package/dist/internal/design-system/primitives/index.d.ts +14 -0
  60. package/dist/internal/design-system/primitives/layout/split-handle.d.ts +17 -0
  61. package/dist/internal/design-system/primitives/navigation/segmented-control.d.ts +19 -0
  62. package/dist/internal/design-system/primitives/navigation/tab-navigation.d.ts +13 -0
  63. package/dist/internal/design-system/primitives/navigation/tabs.d.ts +21 -0
  64. package/dist/internal/design-system/primitives/overlay/dialog-focus-scope.d.ts +17 -0
  65. package/dist/internal/design-system/primitives/overlay/popover.d.ts +34 -0
  66. package/dist/internal/design-system/primitives/overlay/portal-root.d.ts +1 -0
  67. package/dist/internal/design-system/primitives/status/status-badge.d.ts +6 -0
  68. package/dist/internal/features/work/components/work-document-pages.d.ts +4 -0
  69. package/dist/internal/features/work/components/work-editor-agent-menus.d.ts +12 -0
  70. package/dist/internal/features/work/components/work-editor-loading-state.d.ts +3 -0
  71. package/dist/internal/features/work/editors/document-changes-panel.d.ts +9 -0
  72. package/dist/internal/features/work/editors/document-citation-source-form.d.ts +33 -0
  73. package/dist/internal/features/work/editors/document-citations-panel.d.ts +8 -0
  74. package/dist/internal/features/work/editors/document-columns-panel.d.ts +5 -0
  75. package/dist/internal/features/work/editors/document-comment-composer.d.ts +13 -0
  76. package/dist/internal/features/work/editors/document-comments-panel.d.ts +17 -0
  77. package/dist/internal/features/work/editors/document-editor-focus.d.ts +1 -0
  78. package/dist/internal/features/work/editors/document-editor-pagination.d.ts +3 -0
  79. package/dist/internal/features/work/editors/document-editor-support.d.ts +34 -0
  80. package/dist/internal/features/work/editors/document-editor.d.ts +20 -0
  81. package/dist/internal/features/work/editors/document-find-highlight.d.ts +8 -0
  82. package/dist/internal/features/work/editors/document-find-replace-panel.d.ts +10 -0
  83. package/dist/internal/features/work/editors/document-formatting-options.d.ts +113 -0
  84. package/dist/internal/features/work/editors/document-home-ribbon.d.ts +9 -0
  85. package/dist/internal/features/work/editors/document-layout-panel.d.ts +10 -0
  86. package/dist/internal/features/work/editors/document-list-gallery.d.ts +4 -0
  87. package/dist/internal/features/work/editors/document-navigation-panel.d.ts +9 -0
  88. package/dist/internal/features/work/editors/document-page-chrome-editor.d.ts +39 -0
  89. package/dist/internal/features/work/editors/document-page-chrome-panel.d.ts +5 -0
  90. package/dist/internal/features/work/editors/document-page-chrome-ribbon.d.ts +10 -0
  91. package/dist/internal/features/work/editors/document-page-navigation.d.ts +14 -0
  92. package/dist/internal/features/work/editors/document-page-stack.d.ts +8 -0
  93. package/dist/internal/features/work/editors/document-pagination-popover.d.ts +4 -0
  94. package/dist/internal/features/work/editors/document-paragraph-spacing-popover.d.ts +4 -0
  95. package/dist/internal/features/work/editors/document-picture-ribbon.d.ts +4 -0
  96. package/dist/internal/features/work/editors/document-ruler-tab-stops.d.ts +12 -0
  97. package/dist/internal/features/work/editors/document-ruler.d.ts +15 -0
  98. package/dist/internal/features/work/editors/document-selection-context-menu.d.ts +22 -0
  99. package/dist/internal/features/work/editors/document-selection-toolbar.d.ts +8 -0
  100. package/dist/internal/features/work/editors/document-status-bar.d.ts +19 -0
  101. package/dist/internal/features/work/editors/document-style-gallery.d.ts +4 -0
  102. package/dist/internal/features/work/editors/document-table-insert-popover.d.ts +4 -0
  103. package/dist/internal/features/work/editors/document-table-ribbon.d.ts +7 -0
  104. package/dist/internal/features/work/editors/document-task-pane.d.ts +11 -0
  105. package/dist/internal/features/work/editors/document-toolbar.d.ts +100 -0
  106. package/dist/internal/features/work/editors/document-vertical-ruler.d.ts +6 -0
  107. package/dist/internal/features/work/editors/markdown-editor-focus.d.ts +2 -0
  108. package/dist/internal/features/work/editors/markdown-editor.d.ts +16 -0
  109. package/dist/internal/features/work/editors/markdown-insert-dialog.d.ts +19 -0
  110. package/dist/internal/features/work/editors/markdown-selection-context-menu.d.ts +14 -0
  111. package/dist/internal/features/work/editors/markdown-source-commands.d.ts +41 -0
  112. package/dist/internal/features/work/editors/markdown-status.d.ts +7 -0
  113. package/dist/internal/features/work/editors/markdown-toolbar.d.ts +22 -0
  114. package/dist/internal/features/work/editors/markdown-workspace.d.ts +26 -0
  115. package/dist/internal/features/work/editors/office-checkbox.d.ts +9 -0
  116. package/dist/internal/features/work/editors/office-color-picker.d.ts +11 -0
  117. package/dist/internal/features/work/editors/office-controls.d.ts +7 -0
  118. package/dist/internal/features/work/editors/office-dialog.d.ts +35 -0
  119. package/dist/internal/features/work/editors/office-editor-extension.d.ts +86 -0
  120. package/dist/internal/features/work/editors/office-file-data.d.ts +1 -0
  121. package/dist/internal/features/work/editors/office-font-families.d.ts +187 -0
  122. package/dist/internal/features/work/editors/office-menu-keyboard.d.ts +2 -0
  123. package/dist/internal/features/work/editors/office-number-field.d.ts +21 -0
  124. package/dist/internal/features/work/editors/office-number-normalization.d.ts +9 -0
  125. package/dist/internal/features/work/editors/office-select.d.ts +19 -0
  126. package/dist/internal/features/work/editors/office-shortcuts.d.ts +1 -0
  127. package/dist/internal/features/work/editors/office-slider.d.ts +10 -0
  128. package/dist/internal/features/work/editors/office-table-dimensions.d.ts +4 -0
  129. package/dist/internal/features/work/editors/office-table-insert-popover.d.ts +7 -0
  130. package/dist/internal/features/work/editors/office-task-pane.d.ts +7 -0
  131. package/dist/internal/features/work/editors/office-text-field.d.ts +20 -0
  132. package/dist/internal/features/work/editors/office-tiptap-extensions.d.ts +2 -0
  133. package/dist/internal/features/work/editors/pdf-annotation-controller.d.ts +23 -0
  134. package/dist/internal/features/work/editors/pdf-editor-extensions.d.ts +36 -0
  135. package/dist/internal/features/work/editors/pdf-thumbnail-rail.d.ts +26 -0
  136. package/dist/internal/features/work/editors/pdf-toolbar.d.ts +23 -0
  137. package/dist/internal/features/work/editors/pdf-viewer-controller.d.ts +48 -0
  138. package/dist/internal/features/work/editors/pdf-viewer.d.ts +11 -0
  139. package/dist/internal/features/work/editors/presentation-arrangement-controller.d.ts +19 -0
  140. package/dist/internal/features/work/editors/presentation-chart-analysis-canvas.d.ts +21 -0
  141. package/dist/internal/features/work/editors/presentation-chart-axis-canvas.d.ts +33 -0
  142. package/dist/internal/features/work/editors/presentation-chart-axis-editor.d.ts +5 -0
  143. package/dist/internal/features/work/editors/presentation-chart-canvas.d.ts +5 -0
  144. package/dist/internal/features/work/editors/presentation-chart-cartesian-canvas.d.ts +3 -0
  145. package/dist/internal/features/work/editors/presentation-chart-data-label-editor.d.ts +6 -0
  146. package/dist/internal/features/work/editors/presentation-chart-data-labels.d.ts +26 -0
  147. package/dist/internal/features/work/editors/presentation-chart-layout-editor.d.ts +5 -0
  148. package/dist/internal/features/work/editors/presentation-chart-legend-canvas.d.ts +15 -0
  149. package/dist/internal/features/work/editors/presentation-chart-panel.d.ts +7 -0
  150. package/dist/internal/features/work/editors/presentation-chart-series-analysis-editor.d.ts +6 -0
  151. package/dist/internal/features/work/editors/presentation-chart-series-canvas.d.ts +15 -0
  152. package/dist/internal/features/work/editors/presentation-command-controller.d.ts +3 -0
  153. package/dist/internal/features/work/editors/presentation-command-types.d.ts +206 -0
  154. package/dist/internal/features/work/editors/presentation-comments-panel.d.ts +9 -0
  155. package/dist/internal/features/work/editors/presentation-context-menu.d.ts +11 -0
  156. package/dist/internal/features/work/editors/presentation-design-panel.d.ts +13 -0
  157. package/dist/internal/features/work/editors/presentation-editor-focus.d.ts +12 -0
  158. package/dist/internal/features/work/editors/presentation-editor-operations.d.ts +10 -0
  159. package/dist/internal/features/work/editors/presentation-editor-types.d.ts +22 -0
  160. package/dist/internal/features/work/editors/presentation-editor.d.ts +3 -0
  161. package/dist/internal/features/work/editors/presentation-keyboard-extension.d.ts +3 -0
  162. package/dist/internal/features/work/editors/presentation-player.d.ts +7 -0
  163. package/dist/internal/features/work/editors/presentation-presenter-view.d.ts +15 -0
  164. package/dist/internal/features/work/editors/presentation-selection.d.ts +21 -0
  165. package/dist/internal/features/work/editors/presentation-slide-canvas.d.ts +26 -0
  166. package/dist/internal/features/work/editors/presentation-slide-thumbnail.d.ts +18 -0
  167. package/dist/internal/features/work/editors/presentation-status-bar.d.ts +10 -0
  168. package/dist/internal/features/work/editors/presentation-text-editor.d.ts +22 -0
  169. package/dist/internal/features/work/editors/presentation-text-formatting.d.ts +3 -0
  170. package/dist/internal/features/work/editors/presentation-thumbnail-rail.d.ts +20 -0
  171. package/dist/internal/features/work/editors/presentation-toolbar.d.ts +19 -0
  172. package/dist/internal/features/work/editors/presentation-transition-panel.d.ts +9 -0
  173. package/dist/internal/features/work/editors/presentation-workspace.d.ts +38 -0
  174. package/dist/internal/features/work/editors/spreadsheet-calculation-model.d.ts +8 -0
  175. package/dist/internal/features/work/editors/spreadsheet-calculation-projection.d.ts +32 -0
  176. package/dist/internal/features/work/editors/spreadsheet-chart-axis-editor.d.ts +9 -0
  177. package/dist/internal/features/work/editors/spreadsheet-chart-draft.d.ts +17 -0
  178. package/dist/internal/features/work/editors/spreadsheet-chart-layout-editor.d.ts +13 -0
  179. package/dist/internal/features/work/editors/spreadsheet-chart-panel.d.ts +10 -0
  180. package/dist/internal/features/work/editors/spreadsheet-chart-series-style-editor.d.ts +9 -0
  181. package/dist/internal/features/work/editors/spreadsheet-clipboard-shortcuts.d.ts +9 -0
  182. package/dist/internal/features/work/editors/spreadsheet-command-controller.d.ts +121 -0
  183. package/dist/internal/features/work/editors/spreadsheet-conditional-comparison-fields.d.ts +7 -0
  184. package/dist/internal/features/work/editors/spreadsheet-conditional-format-model.d.ts +72 -0
  185. package/dist/internal/features/work/editors/spreadsheet-conditional-format-panel.d.ts +7 -0
  186. package/dist/internal/features/work/editors/spreadsheet-conditional-threshold-fields.d.ts +10 -0
  187. package/dist/internal/features/work/editors/spreadsheet-context-menu.d.ts +36 -0
  188. package/dist/internal/features/work/editors/spreadsheet-data-label-editor.d.ts +9 -0
  189. package/dist/internal/features/work/editors/spreadsheet-editor-ribbon.d.ts +46 -0
  190. package/dist/internal/features/work/editors/spreadsheet-editor-support.d.ts +31 -0
  191. package/dist/internal/features/work/editors/spreadsheet-editor.d.ts +16 -0
  192. package/dist/internal/features/work/editors/spreadsheet-error-bar-editor.d.ts +10 -0
  193. package/dist/internal/features/work/editors/spreadsheet-find-bar.d.ts +8 -0
  194. package/dist/internal/features/work/editors/spreadsheet-find.d.ts +9 -0
  195. package/dist/internal/features/work/editors/spreadsheet-formula-panel.d.ts +10 -0
  196. package/dist/internal/features/work/editors/spreadsheet-header-footer-fields.d.ts +5 -0
  197. package/dist/internal/features/work/editors/spreadsheet-keyboard-navigation.d.ts +18 -0
  198. package/dist/internal/features/work/editors/spreadsheet-number-format.d.ts +11 -0
  199. package/dist/internal/features/work/editors/spreadsheet-pivot-panel.d.ts +10 -0
  200. package/dist/internal/features/work/editors/spreadsheet-print-settings-panel.d.ts +6 -0
  201. package/dist/internal/features/work/editors/spreadsheet-protection-panel.d.ts +7 -0
  202. package/dist/internal/features/work/editors/spreadsheet-sheet-bar.d.ts +17 -0
  203. package/dist/internal/features/work/editors/spreadsheet-sheet-model.d.ts +13 -0
  204. package/dist/internal/features/work/editors/spreadsheet-trendline-editor.d.ts +8 -0
  205. package/dist/internal/features/work/editors/spreadsheet-workbook-panel.d.ts +16 -0
  206. package/dist/internal/features/work/editors/use-document-comments.d.ts +26 -0
  207. package/dist/internal/features/work/editors/use-document-insert-commands.d.ts +19 -0
  208. package/dist/internal/features/work/editors/use-document-layout-fonts.d.ts +2 -0
  209. package/dist/internal/features/work/editors/use-document-page-chrome.d.ts +33 -0
  210. package/dist/internal/features/work/editors/use-document-pagination.d.ts +46 -0
  211. package/dist/internal/features/work/editors/use-markdown-source-history.d.ts +16 -0
  212. package/dist/internal/features/work/editors/use-office-draft.d.ts +10 -0
  213. package/dist/internal/features/work/editors/use-office-editor-keyboard-shortcuts.d.ts +9 -0
  214. package/dist/internal/features/work/editors/use-office-editor-runtime.d.ts +6 -0
  215. package/dist/internal/features/work/editors/use-office-editor-wheel-zoom.d.ts +19 -0
  216. package/dist/internal/features/work/editors/use-office-history.d.ts +10 -0
  217. package/dist/internal/features/work/editors/use-presentation-clipboard.d.ts +22 -0
  218. package/dist/internal/features/work/editors/use-presentation-design-commands.d.ts +33 -0
  219. package/dist/internal/features/work/editors/use-presentation-element-commands.d.ts +29 -0
  220. package/dist/internal/features/work/editors/use-presentation-geometry.d.ts +17 -0
  221. package/dist/internal/features/work/editors/use-presentation-history.d.ts +12 -0
  222. package/dist/internal/features/work/editors/use-presentation-review-commands.d.ts +22 -0
  223. package/dist/internal/features/work/editors/use-presentation-selection.d.ts +11 -0
  224. package/dist/internal/features/work/editors/use-presentation-slide-commands.d.ts +18 -0
  225. package/dist/internal/features/work/editors/use-presentation-thumbnail-visibility.d.ts +4 -0
  226. package/dist/internal/features/work/editors/use-presentation-thumbnail-window.d.ts +17 -0
  227. package/dist/internal/features/work/editors/use-presentation-transform.d.ts +53 -0
  228. package/dist/internal/features/work/editors/use-spreadsheet-calculation.d.ts +17 -0
  229. package/dist/internal/features/work/editors/use-spreadsheet-workbook-sync.d.ts +10 -0
  230. package/dist/internal/features/work/editors/work-office-chrome.d.ts +61 -0
  231. package/dist/internal/features/work/editors/work-office-ribbon-overflow.d.ts +18 -0
  232. package/dist/internal/features/work/work-agent-proposal-apply.d.ts +8 -0
  233. package/dist/internal/features/work/work-agent-proposal.d.ts +55 -0
  234. package/dist/internal/features/work/work-agent-request.d.ts +6 -0
  235. package/dist/internal/features/work/work-chart-series-analysis-context.d.ts +3 -0
  236. package/dist/internal/features/work/work-document-caption-nodes.d.ts +13 -0
  237. package/dist/internal/features/work/work-document-captions.d.ts +14 -0
  238. package/dist/internal/features/work/work-document-changes.d.ts +35 -0
  239. package/dist/internal/features/work/work-document-character-formatting.d.ts +13 -0
  240. package/dist/internal/features/work/work-document-citation-nodes.d.ts +25 -0
  241. package/dist/internal/features/work/work-document-citations.d.ts +21 -0
  242. package/dist/internal/features/work/work-document-columns.d.ts +15 -0
  243. package/dist/internal/features/work/work-document-comments.d.ts +48 -0
  244. package/dist/internal/features/work/work-document-extensions.d.ts +11 -0
  245. package/dist/internal/features/work/work-document-field-node.d.ts +12 -0
  246. package/dist/internal/features/work/work-document-fields.d.ts +15 -0
  247. package/dist/internal/features/work/work-document-file-io.d.ts +4 -0
  248. package/dist/internal/features/work/work-document-fonts.d.ts +16 -0
  249. package/dist/internal/features/work/work-document-image-layout.d.ts +29 -0
  250. package/dist/internal/features/work/work-document-incremental-layout.d.ts +17 -0
  251. package/dist/internal/features/work/work-document-layout.d.ts +5 -0
  252. package/dist/internal/features/work/work-document-line-measurement.d.ts +24 -0
  253. package/dist/internal/features/work/work-document-links.d.ts +2 -0
  254. package/dist/internal/features/work/work-document-lists.d.ts +25 -0
  255. package/dist/internal/features/work/work-document-model-codec.d.ts +3 -0
  256. package/dist/internal/features/work/work-document-model.d.ts +12 -0
  257. package/dist/internal/features/work/work-document-note-nodes.d.ts +11 -0
  258. package/dist/internal/features/work/work-document-notes.d.ts +18 -0
  259. package/dist/internal/features/work/work-document-outline.d.ts +14 -0
  260. package/dist/internal/features/work/work-document-page-break.d.ts +2 -0
  261. package/dist/internal/features/work/work-document-page-chrome-commands.d.ts +15 -0
  262. package/dist/internal/features/work/work-document-page-chrome.d.ts +19 -0
  263. package/dist/internal/features/work/work-document-page-color.d.ts +3 -0
  264. package/dist/internal/features/work/work-document-pages.d.ts +19 -0
  265. package/dist/internal/features/work/work-document-pagination-decorations.d.ts +3 -0
  266. package/dist/internal/features/work/work-document-pagination-dom.d.ts +35 -0
  267. package/dist/internal/features/work/work-document-pagination-measurement.d.ts +9 -0
  268. package/dist/internal/features/work/work-document-pagination-types.d.ts +88 -0
  269. package/dist/internal/features/work/work-document-pagination.d.ts +17 -0
  270. package/dist/internal/features/work/work-document-paragraph-formatting.d.ts +61 -0
  271. package/dist/internal/features/work/work-document-search.d.ts +11 -0
  272. package/dist/internal/features/work/work-document-section-editor.d.ts +20 -0
  273. package/dist/internal/features/work/work-document-section-node.d.ts +13 -0
  274. package/dist/internal/features/work/work-document-section.d.ts +34 -0
  275. package/dist/internal/features/work/work-document-selection-menu.d.ts +54 -0
  276. package/dist/internal/features/work/work-document-tab-node.d.ts +6 -0
  277. package/dist/internal/features/work/work-document-tab-stops.d.ts +29 -0
  278. package/dist/internal/features/work/work-document-table-cell-formatting.d.ts +46 -0
  279. package/dist/internal/features/work/work-document-table-commands.d.ts +17 -0
  280. package/dist/internal/features/work/work-document-table-pagination.d.ts +5 -0
  281. package/dist/internal/features/work/work-document-table-row.d.ts +37 -0
  282. package/dist/internal/features/work/work-document-table-sizing.d.ts +27 -0
  283. package/dist/internal/features/work/work-document-text-layout.d.ts +14 -0
  284. package/dist/internal/features/work/work-docx-bibliography.d.ts +12 -0
  285. package/dist/internal/features/work/work-docx-caption-diagnostics.d.ts +6 -0
  286. package/dist/internal/features/work/work-docx-caption-export.d.ts +4 -0
  287. package/dist/internal/features/work/work-docx-caption-fields.d.ts +5 -0
  288. package/dist/internal/features/work/work-docx-caption-import.d.ts +20 -0
  289. package/dist/internal/features/work/work-docx-change-import.d.ts +12 -0
  290. package/dist/internal/features/work/work-docx-citation-diagnostics.d.ts +3 -0
  291. package/dist/internal/features/work/work-docx-citation-export.d.ts +3 -0
  292. package/dist/internal/features/work/work-docx-citation-import.d.ts +23 -0
  293. package/dist/internal/features/work/work-docx-column-export.d.ts +14 -0
  294. package/dist/internal/features/work/work-docx-column-import.d.ts +2 -0
  295. package/dist/internal/features/work/work-docx-comment-import.d.ts +14 -0
  296. package/dist/internal/features/work/work-docx-export-formatting.d.ts +30 -0
  297. package/dist/internal/features/work/work-docx-export-image.d.ts +2 -0
  298. package/dist/internal/features/work/work-docx-export.d.ts +2 -0
  299. package/dist/internal/features/work/work-docx-field-export.d.ts +2 -0
  300. package/dist/internal/features/work/work-docx-field-import.d.ts +16 -0
  301. package/dist/internal/features/work/work-docx-field-instructions.d.ts +8 -0
  302. package/dist/internal/features/work/work-docx-image-layout-import.d.ts +12 -0
  303. package/dist/internal/features/work/work-docx-import.d.ts +50 -0
  304. package/dist/internal/features/work/work-docx-list-import.d.ts +14 -0
  305. package/dist/internal/features/work/work-docx-note-diagnostics.d.ts +3 -0
  306. package/dist/internal/features/work/work-docx-note-import.d.ts +3 -0
  307. package/dist/internal/features/work/work-docx-page-chrome-diagnostics.d.ts +3 -0
  308. package/dist/internal/features/work/work-docx-page-chrome-import.d.ts +11 -0
  309. package/dist/internal/features/work/work-docx-page-color.d.ts +2 -0
  310. package/dist/internal/features/work/work-docx-paragraph-alignment-import.d.ts +12 -0
  311. package/dist/internal/features/work/work-docx-paragraph-direction-import.d.ts +12 -0
  312. package/dist/internal/features/work/work-docx-paragraph-indent-import.d.ts +12 -0
  313. package/dist/internal/features/work/work-docx-paragraph-pagination-import.d.ts +12 -0
  314. package/dist/internal/features/work/work-docx-paragraph-spacing-import.d.ts +12 -0
  315. package/dist/internal/features/work/work-docx-paragraph-styles.d.ts +18 -0
  316. package/dist/internal/features/work/work-docx-run-formatting-import.d.ts +19 -0
  317. package/dist/internal/features/work/work-docx-tab-stop-import.d.ts +13 -0
  318. package/dist/internal/features/work/work-docx-table-cell-export.d.ts +4 -0
  319. package/dist/internal/features/work/work-docx-table-cell-import.d.ts +16 -0
  320. package/dist/internal/features/work/work-docx-table-row-import.d.ts +13 -0
  321. package/dist/internal/features/work/work-docx-table-sizing-export.d.ts +8 -0
  322. package/dist/internal/features/work/work-docx-table-sizing-import.d.ts +12 -0
  323. package/dist/internal/features/work/work-docx-theme.d.ts +9 -0
  324. package/dist/internal/features/work/work-file-data.d.ts +1 -0
  325. package/dist/internal/features/work/work-file-download.d.ts +3 -0
  326. package/dist/internal/features/work/work-file-io.d.ts +8 -0
  327. package/dist/internal/features/work/work-markdown-extensions.d.ts +19 -0
  328. package/dist/internal/features/work/work-markdown-file-io.d.ts +3 -0
  329. package/dist/internal/features/work/work-markdown-selection-menu.d.ts +57 -0
  330. package/dist/internal/features/work/work-office-diagnostics.d.ts +9 -0
  331. package/dist/internal/features/work/work-ooxml-package.d.ts +28 -0
  332. package/dist/internal/features/work/work-pdf-export.d.ts +23 -0
  333. package/dist/internal/features/work/work-pptx-chart-axes.d.ts +3 -0
  334. package/dist/internal/features/work/work-pptx-chart-axis-diagnostics.d.ts +5 -0
  335. package/dist/internal/features/work/work-pptx-chart-data-labels.d.ts +12 -0
  336. package/dist/internal/features/work/work-pptx-chart-import.d.ts +11 -0
  337. package/dist/internal/features/work/work-pptx-chart-layout-style.d.ts +15 -0
  338. package/dist/internal/features/work/work-pptx-chart-series-analysis.d.ts +13 -0
  339. package/dist/internal/features/work/work-pptx-chart-xy.d.ts +3 -0
  340. package/dist/internal/features/work/work-pptx-comments.d.ts +17 -0
  341. package/dist/internal/features/work/work-pptx-export.d.ts +4 -0
  342. package/dist/internal/features/work/work-pptx-groups.d.ts +19 -0
  343. package/dist/internal/features/work/work-pptx-import.d.ts +6 -0
  344. package/dist/internal/features/work/work-pptx-layout-export.d.ts +13 -0
  345. package/dist/internal/features/work/work-pptx-layout-import.d.ts +30 -0
  346. package/dist/internal/features/work/work-pptx-style.d.ts +13 -0
  347. package/dist/internal/features/work/work-pptx-transition.d.ts +13 -0
  348. package/dist/internal/features/work/work-presentation-agent-context.d.ts +6 -0
  349. package/dist/internal/features/work/work-presentation-chart-axes.d.ts +14 -0
  350. package/dist/internal/features/work/work-presentation-charts.d.ts +37 -0
  351. package/dist/internal/features/work/work-presentation-clipboard.d.ts +26 -0
  352. package/dist/internal/features/work/work-presentation-file-io.d.ts +15 -0
  353. package/dist/internal/features/work/work-presentation-groups.d.ts +17 -0
  354. package/dist/internal/features/work/work-presentation-layouts.d.ts +13 -0
  355. package/dist/internal/features/work/work-presentation-transition.d.ts +4 -0
  356. package/dist/internal/features/work/work-presentation-visual-scale.d.ts +2 -0
  357. package/dist/internal/features/work/work-repository.d.ts +4 -0
  358. package/dist/internal/features/work/work-spreadsheet-agent-context.d.ts +15 -0
  359. package/dist/internal/features/work/work-spreadsheet-chart-axis.d.ts +42 -0
  360. package/dist/internal/features/work/work-spreadsheet-chart-layout.d.ts +29 -0
  361. package/dist/internal/features/work/work-spreadsheet-chart-legend-svg.d.ts +18 -0
  362. package/dist/internal/features/work/work-spreadsheet-chart-series-layout.d.ts +24 -0
  363. package/dist/internal/features/work/work-spreadsheet-chart-series-style.d.ts +29 -0
  364. package/dist/internal/features/work/work-spreadsheet-chart-svg-utils.d.ts +7 -0
  365. package/dist/internal/features/work/work-spreadsheet-chart-svg.d.ts +3 -0
  366. package/dist/internal/features/work/work-spreadsheet-chart-types.d.ts +147 -0
  367. package/dist/internal/features/work/work-spreadsheet-chart-validation.d.ts +2 -0
  368. package/dist/internal/features/work/work-spreadsheet-charts.d.ts +17 -0
  369. package/dist/internal/features/work/work-spreadsheet-combination-chart-svg.d.ts +9 -0
  370. package/dist/internal/features/work/work-spreadsheet-comments.d.ts +7 -0
  371. package/dist/internal/features/work/work-spreadsheet-conditional-canvas.d.ts +5 -0
  372. package/dist/internal/features/work/work-spreadsheet-conditional-colors.d.ts +9 -0
  373. package/dist/internal/features/work/work-spreadsheet-conditional-comparisons.d.ts +4 -0
  374. package/dist/internal/features/work/work-spreadsheet-conditional-data-bar.d.ts +8 -0
  375. package/dist/internal/features/work/work-spreadsheet-conditional-format.d.ts +10 -0
  376. package/dist/internal/features/work/work-spreadsheet-conditional-icons.d.ts +107 -0
  377. package/dist/internal/features/work/work-spreadsheet-conditional-values.d.ts +19 -0
  378. package/dist/internal/features/work/work-spreadsheet-data-label-svg.d.ts +27 -0
  379. package/dist/internal/features/work/work-spreadsheet-error-bar-svg.d.ts +5 -0
  380. package/dist/internal/features/work/work-spreadsheet-error-bars.d.ts +8 -0
  381. package/dist/internal/features/work/work-spreadsheet-formula-analysis.d.ts +30 -0
  382. package/dist/internal/features/work/work-spreadsheet-formula-support.d.ts +1 -0
  383. package/dist/internal/features/work/work-spreadsheet-formulas.d.ts +19 -0
  384. package/dist/internal/features/work/work-spreadsheet-header-footer.d.ts +14 -0
  385. package/dist/internal/features/work/work-spreadsheet-line-chart-svg.d.ts +10 -0
  386. package/dist/internal/features/work/work-spreadsheet-page-breaks.d.ts +4 -0
  387. package/dist/internal/features/work/work-spreadsheet-page-setup.d.ts +26 -0
  388. package/dist/internal/features/work/work-spreadsheet-pivot-engine.d.ts +21 -0
  389. package/dist/internal/features/work/work-spreadsheet-pivot-values.d.ts +7 -0
  390. package/dist/internal/features/work/work-spreadsheet-pivots.d.ts +27 -0
  391. package/dist/internal/features/work/work-spreadsheet-protection.d.ts +55 -0
  392. package/dist/internal/features/work/work-spreadsheet-ranges.d.ts +25 -0
  393. package/dist/internal/features/work/work-spreadsheet-trendline-svg.d.ts +9 -0
  394. package/dist/internal/features/work/work-spreadsheet-trendlines.d.ts +11 -0
  395. package/dist/internal/features/work/work-spreadsheet-xy-chart-axes-svg.d.ts +10 -0
  396. package/dist/internal/features/work/work-templates.d.ts +4 -0
  397. package/dist/internal/features/work/work-types.d.ts +513 -0
  398. package/dist/internal/features/work/work-xlsx-chart-axes.d.ts +4 -0
  399. package/dist/internal/features/work/work-xlsx-chart-diagnostics.d.ts +3 -0
  400. package/dist/internal/features/work/work-xlsx-chart-layout.d.ts +16 -0
  401. package/dist/internal/features/work/work-xlsx-chart-series-style.d.ts +6 -0
  402. package/dist/internal/features/work/work-xlsx-chart-values.d.ts +10 -0
  403. package/dist/internal/features/work/work-xlsx-charts.d.ts +32 -0
  404. package/dist/internal/features/work/work-xlsx-conditional-format-diagnostics.d.ts +6 -0
  405. package/dist/internal/features/work/work-xlsx-conditional-format-write.d.ts +11 -0
  406. package/dist/internal/features/work/work-xlsx-conditional-format.d.ts +29 -0
  407. package/dist/internal/features/work/work-xlsx-defined-names.d.ts +4 -0
  408. package/dist/internal/features/work/work-xlsx-drawing-geometry.d.ts +27 -0
  409. package/dist/internal/features/work/work-xlsx-formula-diagnostics.d.ts +3 -0
  410. package/dist/internal/features/work/work-xlsx-formulas.d.ts +40 -0
  411. package/dist/internal/features/work/work-xlsx-header-footer.d.ts +12 -0
  412. package/dist/internal/features/work/work-xlsx-images.d.ts +17 -0
  413. package/dist/internal/features/work/work-xlsx-interop.d.ts +39 -0
  414. package/dist/internal/features/work/work-xlsx-page-breaks.d.ts +7 -0
  415. package/dist/internal/features/work/work-xlsx-page-setup-diagnostics.d.ts +2 -0
  416. package/dist/internal/features/work/work-xlsx-page-setup.d.ts +5 -0
  417. package/dist/internal/features/work/work-xlsx-pivot-diagnostics.d.ts +3 -0
  418. package/dist/internal/features/work/work-xlsx-pivot-xml.d.ts +9 -0
  419. package/dist/internal/features/work/work-xlsx-pivots.d.ts +32 -0
  420. package/dist/internal/features/work/work-xlsx-protection.d.ts +24 -0
  421. package/dist/internal/features/workspace/components/workspace-context-menu.d.ts +29 -0
  422. package/dist/internal/features/workspace/components/workspace-text-control-selection.d.ts +7 -0
  423. package/dist/internal/kernel/office-kernel-client-types.d.ts +40 -0
  424. package/dist/internal/kernel/office-kernel-client.d.ts +4 -0
  425. package/dist/internal/kernel/office-kernel-fallback.d.ts +2 -0
  426. package/dist/internal/kernel/office-kernel-presentation-fallback.d.ts +2 -0
  427. package/dist/internal/kernel/office-kernel-protocol.d.ts +229 -0
  428. package/dist/internal/kernel/office-kernel-spreadsheet-fallback-formula.d.ts +3 -0
  429. package/dist/internal/kernel/office-kernel-spreadsheet-fallback-validation.d.ts +5 -0
  430. package/dist/internal/kernel/office-kernel-spreadsheet-fallback-value.d.ts +6 -0
  431. package/dist/internal/kernel/office-kernel-spreadsheet-fallback.d.ts +2 -0
  432. package/dist/internal/kernel/office-kernel-spreadsheet-protocol.d.ts +112 -0
  433. package/dist/internal/kernel/office-kernel-spreadsheet-session-fallback.d.ts +8 -0
  434. package/dist/internal/kernel/office-kernel-text-fallback.d.ts +10 -0
  435. package/dist/internal/kernel/office-kernel-version.d.ts +1 -0
  436. package/dist/internal/kernel/office-kernel.worker.d.ts +1 -0
  437. package/dist/internal/keyboard-shortcuts.d.ts +2 -0
  438. package/dist/internal/state/app-state.d.ts +8 -0
  439. package/dist/noto-naskh-arabic-regular.ttf +0 -0
  440. package/dist/noto-naskh-arabic.LICENSE.txt +94 -0
  441. package/dist/noto-sans-hans-regular.otf +0 -0
  442. package/dist/noto-sans-hans.LICENSE.txt +94 -0
  443. package/dist/noto-sans-hebrew-regular.ttf +0 -0
  444. package/dist/noto-sans-hebrew.LICENSE.txt +94 -0
  445. package/dist/noto-sans-regular.ttf +0 -0
  446. package/dist/noto-sans.LICENSE.txt +94 -0
  447. package/dist/office-kernel.wasm +0 -0
  448. package/dist/office-kernel.worker.js +14605 -0
  449. package/dist/office-surface.d.ts +10 -0
  450. package/dist/pdfium.LICENSE.txt +196 -0
  451. package/dist/pdfium.wasm +0 -0
  452. package/dist/pptxgen.LICENSE.txt +21 -0
  453. package/dist/pptxgen.bundle.js +11244 -0
  454. package/dist/react.d.ts +51 -0
  455. package/dist/react.js +1 -0
  456. package/dist/styles.css +17435 -0
  457. package/dist/styles.js +0 -0
  458. package/dist/vue.d.ts +282 -0
  459. package/dist/vue.js +231 -0
  460. package/dist/web-component.d.ts +98 -0
  461. package/dist/web-component.js +335 -0
  462. package/docs/browser-editor-architecture.md +947 -0
  463. package/package.json +165 -0
@@ -0,0 +1,3116 @@
1
+ import jszip from "jszip";
2
+ import { contentTypeForPart, directChildren, bytesToDataUrl, OoxmlPackage, firstDescendant, descendants, directChild, childPath, attribute } from "./8715.js";
3
+ import { docxCaptionSequenceKind, docxFieldOccurrences, docxCaptionBookmark, docxFieldResultText, docxCaptionReferenceTarget } from "./0~152.js";
4
+ import { documentContentLayoutProperties, documentPageChromeLegacyFields, normalizeDocumentFieldsHtml, documentInitialSectionLayout, documentSectionDomAttributes, documentCaptionLabel, normalizeDocumentPageChrome, normalizeDocumentCitationsHtml, normalizeDocumentColumns, normalizeDocumentCaptionsHtml, normalizeDocumentNotesHtml, documentCitationTagsFromInstruction, docxDocumentFieldKind, createDocumentNoteElement } from "./4704.js";
5
+ import { normalizeDocumentImageAlignment, serializeDocumentTabStops, normalizeDocumentImageLayoutOptions, normalizeDocumentTabStops } from "./0~8155.js";
6
+ import { normalizeDocumentParagraphIndent } from "./0~work-document-paragraph-formatting.js";
7
+ import { readDocxBibliography } from "./0~work-docx-bibliography.js";
8
+ import { importDocxPageColor } from "./0~work-docx-page-color.js";
9
+ const WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
10
+ const XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
11
+ function markDocxCaptionFields(document) {
12
+ const captions = [];
13
+ const bookmarkTargets = new Map();
14
+ const paragraphs = descendants(document, 'p');
15
+ for (const paragraph of paragraphs){
16
+ const sequence = docxFieldOccurrences(paragraph).map((field)=>({
17
+ field,
18
+ kind: docxCaptionSequenceKind(field.instruction)
19
+ })).find((item)=>Boolean(item.kind));
20
+ if (!sequence) continue;
21
+ const bookmark = docxCaptionBookmark(paragraph, sequence.field);
22
+ const bookmarkName = attribute(bookmark ?? paragraph, 'name')?.trim() ?? '';
23
+ const id = uniqueCaptionId(bookmarkName, sequence.kind, captions.length + 1, captions);
24
+ if (bookmarkName) bookmarkTargets.set(bookmarkName, id);
25
+ const marker = captionMarker(captions.length + 1, id, sequence.kind);
26
+ insertParagraphBoundaryMarkers(document, paragraph, marker.start, marker.end);
27
+ captions.push(marker);
28
+ }
29
+ const references = [];
30
+ for (const paragraph of paragraphs)for (const field of docxFieldOccurrences(paragraph)){
31
+ const bookmarkName = docxCaptionReferenceTarget(field.instruction);
32
+ const targetId = bookmarkName ? bookmarkTargets.get(bookmarkName) : void 0;
33
+ if (!targetId) continue;
34
+ const marker = referenceMarker(references.length + 1, targetId);
35
+ insertFieldBoundaryMarkers(document, field, marker.start, marker.end);
36
+ references.push(marker);
37
+ }
38
+ return {
39
+ captions,
40
+ references
41
+ };
42
+ }
43
+ function applyImportedDocxCaptionMarkers(document, markers) {
44
+ for (const reference of markers.references){
45
+ const element = document.createElement('span');
46
+ element.dataset.documentCrossReference = 'true';
47
+ element.dataset.referenceTargetId = reference.targetId;
48
+ replaceMarkerRange(document.body, reference.start, reference.end, element);
49
+ }
50
+ for (const caption of markers.captions){
51
+ const block = markerBlock(document.body, caption.start, caption.end);
52
+ if (!block) continue;
53
+ removeMarkerText(block, caption.start);
54
+ removeMarkerText(block, caption.end);
55
+ removeCaptionPrefix(block, caption.kind);
56
+ const element = document.createElement('figcaption');
57
+ element.dataset.documentCaption = 'true';
58
+ element.dataset.captionId = caption.id;
59
+ element.dataset.captionKind = caption.kind;
60
+ element.className = 'work-document-caption';
61
+ element.append(...Array.from(block.childNodes));
62
+ block.replaceWith(element);
63
+ }
64
+ }
65
+ function hasImportedDocxCaptionMarkers(markers) {
66
+ return markers.captions.length > 0 || markers.references.length > 0;
67
+ }
68
+ function uniqueCaptionId(bookmark, kind, index, existing) {
69
+ const base = bookmark ? `docx-caption-${bookmark}` : `docx-${kind}-caption-${index}`;
70
+ const ids = new Set(existing.map((caption)=>caption.id));
71
+ if (!ids.has(base)) return base;
72
+ let suffix = 2;
73
+ while(ids.has(`${base}-${suffix}`))suffix += 1;
74
+ return `${base}-${suffix}`;
75
+ }
76
+ function captionMarker(index, id, kind) {
77
+ return {
78
+ start: `__A3S_WORK_CAPTION_START_${index}__`,
79
+ end: `__A3S_WORK_CAPTION_END_${index}__`,
80
+ id,
81
+ kind
82
+ };
83
+ }
84
+ function referenceMarker(index, targetId) {
85
+ return {
86
+ start: `__A3S_WORK_REFERENCE_START_${index}__`,
87
+ end: `__A3S_WORK_REFERENCE_END_${index}__`,
88
+ targetId
89
+ };
90
+ }
91
+ function insertParagraphBoundaryMarkers(document, paragraph, start, end) {
92
+ const firstContent = Array.from(paragraph.children).find((element)=>'pPr' !== element.localName);
93
+ paragraph.insertBefore(work_docx_caption_import_markerRun(document, start), firstContent ?? null);
94
+ paragraph.append(work_docx_caption_import_markerRun(document, end));
95
+ }
96
+ function insertFieldBoundaryMarkers(document, field, start, end) {
97
+ if ('fldChar' === field.start.localName && 'fldChar' === field.end.localName) {
98
+ field.start.parentNode?.insertBefore(markerText(document, start), field.start);
99
+ field.end.parentNode?.insertBefore(markerText(document, end), field.end.nextSibling);
100
+ return;
101
+ }
102
+ field.start.parentNode?.insertBefore(work_docx_caption_import_markerRun(document, start), field.start);
103
+ field.end.parentNode?.insertBefore(work_docx_caption_import_markerRun(document, end), field.end.nextSibling);
104
+ }
105
+ function work_docx_caption_import_markerRun(document, text) {
106
+ const run = document.createElementNS(WORD_NAMESPACE, 'w:r');
107
+ run.append(markerText(document, text));
108
+ return run;
109
+ }
110
+ function markerText(document, text) {
111
+ const value = document.createElementNS(WORD_NAMESPACE, 'w:t');
112
+ value.setAttributeNS(XML_NAMESPACE, 'xml:space', 'preserve');
113
+ value.textContent = text;
114
+ return value;
115
+ }
116
+ function markerBlock(root, start, end) {
117
+ const startNode = textNodes(root).find((node)=>node.data.includes(start));
118
+ const endNode = textNodes(root).find((node)=>node.data.includes(end));
119
+ if (!startNode || !endNode) return null;
120
+ let current = startNode.parentElement;
121
+ while(current && current !== root){
122
+ if (current.contains(endNode) && /^(?:P|DIV|LI)$/.test(current.tagName)) return current;
123
+ current = current.parentElement;
124
+ }
125
+ return null;
126
+ }
127
+ function replaceMarkerRange(root, start, end, replacement) {
128
+ const nodes = textNodes(root);
129
+ const startNode = nodes.find((node)=>node.data.includes(start));
130
+ const endNode = nodes.find((node)=>node.data.includes(end));
131
+ if (!startNode || !endNode) return false;
132
+ const range = root.ownerDocument.createRange();
133
+ range.setStart(startNode, startNode.data.indexOf(start));
134
+ range.setEnd(endNode, endNode.data.indexOf(end) + end.length);
135
+ range.deleteContents();
136
+ range.insertNode(replacement);
137
+ return true;
138
+ }
139
+ function removeMarkerText(root, marker) {
140
+ for (const node of textNodes(root))node.data = node.data.replace(marker, '');
141
+ }
142
+ function removeCaptionPrefix(root, kind) {
143
+ const label = documentCaptionLabel(kind);
144
+ const source = root.textContent ?? '';
145
+ const expression = 'table' === kind ? /^\s*(?:表|Table)\s*(?:\d+)?[\s::.\-–— ]*/i : /^\s*(?:图|Figure|Fig\.?)\s*(?:\d+)?[\s::.\-–— ]*/i;
146
+ const match = expression.exec(source);
147
+ if (!match || !source.trimStart().startsWith(label) && !/^(?:Figure|Fig|Table)/i.test(source.trimStart())) return;
148
+ let remaining = match[0].length;
149
+ for (const node of textNodes(root)){
150
+ if (remaining <= 0) break;
151
+ const removed = Math.min(remaining, node.data.length);
152
+ node.data = node.data.slice(removed);
153
+ remaining -= removed;
154
+ }
155
+ }
156
+ function textNodes(root) {
157
+ const walker = root.ownerDocument?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
158
+ const nodes = [];
159
+ if (!walker) return nodes;
160
+ while(walker.nextNode())nodes.push(walker.currentNode);
161
+ return nodes;
162
+ }
163
+ const work_docx_change_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
164
+ const work_docx_change_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
165
+ function markDocxTextChanges(document) {
166
+ const changes = [];
167
+ const revisions = [
168
+ ...descendants(document, 'ins'),
169
+ ...descendants(document, 'del')
170
+ ].sort(compareDocumentOrder);
171
+ for (const revision of revisions){
172
+ if (!revision.parentNode || closestRevision(revision.parentElement)) continue;
173
+ const kind = 'del' === revision.localName ? 'deletion' : 'insertion';
174
+ if (!revisionText(revision, kind)) continue;
175
+ if ('deletion' === kind) convertDeletedText(document, revision);
176
+ const index = changes.length + 1;
177
+ const sourceId = attribute(revision, 'id')?.trim() ?? '';
178
+ const id = uniqueChangeId(sourceId ? `docx-change-${sourceId}` : `docx-change-${index}`, changes);
179
+ const marker = {
180
+ id,
181
+ kind,
182
+ author: attribute(revision, 'author')?.trim() || '未知审阅者',
183
+ date: normalizeDate(attribute(revision, 'date')),
184
+ start: `__A3S_WORK_CHANGE_START_${index}__`,
185
+ end: `__A3S_WORK_CHANGE_END_${index}__`
186
+ };
187
+ unwrapRevision(document, revision, marker.start, marker.end);
188
+ changes.push(marker);
189
+ }
190
+ return {
191
+ changes
192
+ };
193
+ }
194
+ function applyImportedDocxChangeMarkers(document, markers) {
195
+ for (const marker of markers.changes){
196
+ const element = document.createElement('deletion' === marker.kind ? 'del' : 'ins');
197
+ element.dataset.documentChange = 'true';
198
+ element.dataset.changeKind = marker.kind;
199
+ element.dataset.changeId = marker.id;
200
+ element.dataset.changeAuthor = marker.author;
201
+ element.dataset.changeDate = marker.date;
202
+ wrapMarkerRange(document.body, marker.start, marker.end, element);
203
+ }
204
+ }
205
+ function hasImportedDocxChangeMarkers(markers) {
206
+ return markers.changes.length > 0;
207
+ }
208
+ function revisionText(revision, kind) {
209
+ const names = 'deletion' === kind ? [
210
+ 'delText',
211
+ 't'
212
+ ] : [
213
+ 't'
214
+ ];
215
+ return names.flatMap((name)=>descendants(revision, name)).map((element)=>element.textContent ?? '').join('');
216
+ }
217
+ function convertDeletedText(document, revision) {
218
+ for (const deleted of descendants(revision, 'delText')){
219
+ const text = document.createElementNS(work_docx_change_import_WORD_NAMESPACE, 'w:t');
220
+ const preserve = deleted.getAttributeNS(work_docx_change_import_XML_NAMESPACE, 'space') ?? deleted.getAttribute('xml:space');
221
+ if (preserve) text.setAttributeNS(work_docx_change_import_XML_NAMESPACE, 'xml:space', preserve);
222
+ text.textContent = deleted.textContent;
223
+ deleted.replaceWith(text);
224
+ }
225
+ }
226
+ function unwrapRevision(document, revision, start, end) {
227
+ const parent = revision.parentNode;
228
+ if (!parent) return;
229
+ parent.insertBefore(work_docx_change_import_markerRun(document, start), revision);
230
+ while(revision.firstChild)parent.insertBefore(revision.firstChild, revision);
231
+ parent.insertBefore(work_docx_change_import_markerRun(document, end), revision);
232
+ revision.remove();
233
+ }
234
+ function work_docx_change_import_markerRun(document, value) {
235
+ const run = document.createElementNS(work_docx_change_import_WORD_NAMESPACE, 'w:r');
236
+ const text = document.createElementNS(work_docx_change_import_WORD_NAMESPACE, 'w:t');
237
+ text.setAttributeNS(work_docx_change_import_XML_NAMESPACE, 'xml:space', 'preserve');
238
+ text.textContent = value;
239
+ run.append(text);
240
+ return run;
241
+ }
242
+ function wrapMarkerRange(root, start, end, wrapper) {
243
+ const nodes = work_docx_change_import_textNodes(root);
244
+ const startNode = nodes.find((node)=>node.data.includes(start));
245
+ const endNode = nodes.find((node)=>node.data.includes(end));
246
+ if (!startNode || !endNode) return false;
247
+ const startIndex = startNode.data.indexOf(start);
248
+ const endIndex = endNode.data.indexOf(end);
249
+ if (startNode === endNode && endIndex < startIndex) return false;
250
+ const range = root.ownerDocument.createRange();
251
+ range.setStart(startNode, startIndex);
252
+ range.setEnd(endNode, endIndex + end.length);
253
+ const content = range.extractContents();
254
+ work_docx_change_import_removeMarkerText(content, start);
255
+ work_docx_change_import_removeMarkerText(content, end);
256
+ wrapper.append(content);
257
+ range.insertNode(wrapper);
258
+ return true;
259
+ }
260
+ function work_docx_change_import_removeMarkerText(root, marker) {
261
+ for (const node of work_docx_change_import_textNodes(root))node.data = node.data.replace(marker, '');
262
+ }
263
+ function work_docx_change_import_textNodes(root) {
264
+ const document = root.ownerDocument;
265
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
266
+ const nodes = [];
267
+ if (!walker) return nodes;
268
+ while(walker.nextNode())nodes.push(walker.currentNode);
269
+ return nodes;
270
+ }
271
+ function closestRevision(element) {
272
+ let current = element;
273
+ while(current){
274
+ if ('ins' === current.localName || 'del' === current.localName) return current;
275
+ current = current.parentElement;
276
+ }
277
+ return null;
278
+ }
279
+ function uniqueChangeId(base, changes) {
280
+ const ids = new Set(changes.map((change)=>change.id));
281
+ if (!ids.has(base)) return base;
282
+ let suffix = 2;
283
+ while(ids.has(`${base}-${suffix}`))suffix += 1;
284
+ return `${base}-${suffix}`;
285
+ }
286
+ function normalizeDate(value) {
287
+ if (!value) return '';
288
+ const time = Date.parse(value);
289
+ return Number.isFinite(time) ? new Date(time).toISOString() : '';
290
+ }
291
+ function compareDocumentOrder(left, right) {
292
+ if (left === right) return 0;
293
+ return left.compareDocumentPosition(right) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
294
+ }
295
+ const work_docx_citation_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
296
+ const work_docx_citation_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
297
+ function markDocxCitationFields(document) {
298
+ const citations = [];
299
+ const bibliographies = [];
300
+ for (const field of docxFieldOccurrences(document)){
301
+ if (!canMarkField(field)) continue;
302
+ const tags = documentCitationTagsFromInstruction(field.instruction);
303
+ if (tags.length) {
304
+ const index = citations.length + 1;
305
+ const marker = {
306
+ start: `__A3S_WORK_CITATION_START_${index}__`,
307
+ end: `__A3S_WORK_CITATION_END_${index}__`,
308
+ id: `docx-citation-${index}`,
309
+ instruction: field.instruction,
310
+ tags,
311
+ display: docxFieldResultText(field)
312
+ };
313
+ work_docx_citation_import_insertFieldBoundaryMarkers(document, field, marker.start, marker.end);
314
+ citations.push(marker);
315
+ continue;
316
+ }
317
+ if (/^\s*BIBLIOGRAPHY\b/i.test(field.instruction)) {
318
+ const index = bibliographies.length + 1;
319
+ const marker = {
320
+ start: `__A3S_WORK_BIBLIOGRAPHY_START_${index}__`,
321
+ end: `__A3S_WORK_BIBLIOGRAPHY_END_${index}__`,
322
+ id: `docx-bibliography-${index}`,
323
+ instruction: field.instruction,
324
+ display: docxFieldResultText(field)
325
+ };
326
+ work_docx_citation_import_insertFieldBoundaryMarkers(document, field, marker.start, marker.end);
327
+ bibliographies.push(marker);
328
+ }
329
+ }
330
+ return {
331
+ citations,
332
+ bibliographies
333
+ };
334
+ }
335
+ function applyImportedDocxCitationMarkers(document, markers) {
336
+ for (const citation of markers.citations){
337
+ const element = document.createElement('span');
338
+ element.dataset.documentCitation = 'true';
339
+ element.dataset.citationId = citation.id;
340
+ element.dataset.citationTags = citation.tags.join(' ');
341
+ element.dataset.citationInstruction = citation.instruction;
342
+ const convertedDisplay = work_docx_citation_import_replaceMarkerRange(document.body, citation.start, citation.end, element);
343
+ const display = citation.display.trim() || convertedDisplay.trim();
344
+ element.dataset.citationDisplay = display;
345
+ element.textContent = display;
346
+ }
347
+ for (const bibliography of markers.bibliographies)replaceBibliographyMarkerRange(document.body, bibliography);
348
+ }
349
+ function hasImportedDocxCitationMarkers(markers) {
350
+ return markers.citations.length > 0 || markers.bibliographies.length > 0;
351
+ }
352
+ function canMarkField(field) {
353
+ return field.start !== field.end || 'fldSimple' === field.start.localName;
354
+ }
355
+ function work_docx_citation_import_insertFieldBoundaryMarkers(document, field, start, end) {
356
+ if ('fldChar' === field.start.localName && 'fldChar' === field.end.localName) {
357
+ field.start.parentNode?.insertBefore(work_docx_citation_import_markerText(document, start), field.start);
358
+ field.end.parentNode?.insertBefore(work_docx_citation_import_markerText(document, end), field.end.nextSibling);
359
+ return;
360
+ }
361
+ field.start.parentNode?.insertBefore(work_docx_citation_import_markerRun(document, start), field.start);
362
+ field.end.parentNode?.insertBefore(work_docx_citation_import_markerRun(document, end), field.end.nextSibling);
363
+ }
364
+ function work_docx_citation_import_markerRun(document, text) {
365
+ const run = document.createElementNS(work_docx_citation_import_WORD_NAMESPACE, 'w:r');
366
+ run.append(work_docx_citation_import_markerText(document, text));
367
+ return run;
368
+ }
369
+ function work_docx_citation_import_markerText(document, text) {
370
+ const value = document.createElementNS(work_docx_citation_import_WORD_NAMESPACE, 'w:t');
371
+ value.setAttributeNS(work_docx_citation_import_XML_NAMESPACE, 'xml:space', 'preserve');
372
+ value.textContent = text;
373
+ return value;
374
+ }
375
+ function work_docx_citation_import_replaceMarkerRange(root, start, end, replacement) {
376
+ const nodes = work_docx_citation_import_textNodes(root);
377
+ const startNode = nodes.find((node)=>node.data.includes(start));
378
+ const endNode = nodes.find((node)=>node.data.includes(end));
379
+ if (!startNode || !endNode) return '';
380
+ const range = root.ownerDocument.createRange();
381
+ range.setStart(startNode, startNode.data.indexOf(start));
382
+ range.setEnd(endNode, endNode.data.indexOf(end) + end.length);
383
+ const content = range.cloneContents();
384
+ work_docx_citation_import_removeMarkerText(content, start);
385
+ work_docx_citation_import_removeMarkerText(content, end);
386
+ const display = content.textContent ?? '';
387
+ range.deleteContents();
388
+ range.insertNode(replacement);
389
+ return display;
390
+ }
391
+ function replaceBibliographyMarkerRange(root, marker) {
392
+ const nodes = work_docx_citation_import_textNodes(root);
393
+ const startNode = nodes.find((node)=>node.data.includes(marker.start));
394
+ const endNode = nodes.find((node)=>node.data.includes(marker.end));
395
+ if (!startNode || !endNode) return false;
396
+ const startBlock = closestHtmlBlock(startNode.parentElement, root);
397
+ const endBlock = closestHtmlBlock(endNode.parentElement, root);
398
+ if (!startBlock || !endBlock || startBlock.parentElement !== endBlock.parentElement) return false;
399
+ const blocks = [];
400
+ let current = startBlock;
401
+ while(current){
402
+ if (current instanceof HTMLElement) blocks.push(current);
403
+ if (current === endBlock) break;
404
+ current = current.nextElementSibling;
405
+ }
406
+ if (!blocks.length || blocks.at(-1) !== endBlock) return false;
407
+ const convertedDisplay = blocks.map((block)=>block.textContent ?? '').join('\n').replace(marker.start, '').replace(marker.end, '').trim();
408
+ const section = root.ownerDocument.createElement('section');
409
+ section.dataset.documentBibliography = 'true';
410
+ section.dataset.bibliographyId = marker.id;
411
+ section.dataset.bibliographyInstruction = marker.instruction;
412
+ section.dataset.bibliographyDisplay = marker.display.trim() || convertedDisplay;
413
+ section.className = 'work-document-bibliography';
414
+ const heading = root.ownerDocument.createElement('h2');
415
+ heading.textContent = '参考文献';
416
+ const paragraph = root.ownerDocument.createElement('p');
417
+ paragraph.textContent = marker.display.trim() || convertedDisplay || '尚无文献源';
418
+ section.append(heading, paragraph);
419
+ startBlock.parentElement?.insertBefore(section, startBlock);
420
+ for (const block of blocks)block.remove();
421
+ return true;
422
+ }
423
+ function closestHtmlBlock(element, root) {
424
+ let current = element;
425
+ while(current && current !== root){
426
+ if (/^(?:P|DIV|LI|SECTION)$/.test(current.tagName)) return current;
427
+ current = current.parentElement;
428
+ }
429
+ return null;
430
+ }
431
+ function work_docx_citation_import_removeMarkerText(root, marker) {
432
+ for (const node of work_docx_citation_import_textNodes(root))node.data = node.data.replace(marker, '');
433
+ }
434
+ function work_docx_citation_import_textNodes(root) {
435
+ const document = root.ownerDocument;
436
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
437
+ const nodes = [];
438
+ if (!walker) return nodes;
439
+ while(walker.nextNode())nodes.push(walker.currentNode);
440
+ return nodes;
441
+ }
442
+ const work_docx_comment_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
443
+ const work_docx_comment_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
444
+ async function markDocxComments(document, archive) {
445
+ if (!archive.has('word/comments.xml')) return {
446
+ comments: [],
447
+ ranges: []
448
+ };
449
+ const definitions = await readCommentDefinitions(archive);
450
+ const bySourceId = new Map(definitions.map((definition)=>[
451
+ definition.sourceId,
452
+ definition
453
+ ]));
454
+ const workIds = new Map();
455
+ const ranges = [];
456
+ const comments = [];
457
+ const starts = descendants(document, 'commentRangeStart').sort(work_docx_comment_import_compareDocumentOrder);
458
+ for (const start of starts){
459
+ const sourceId = attribute(start, 'id')?.trim() ?? '';
460
+ if (!sourceId) continue;
461
+ const end = descendants(document, 'commentRangeEnd').find((candidate)=>attribute(candidate, 'id') === sourceId && Boolean(start.compareDocumentPosition(candidate) & Node.DOCUMENT_POSITION_FOLLOWING));
462
+ if (!end?.parentNode || !start.parentNode) continue;
463
+ const workId = workIds.get(sourceId) ?? uniqueWorkCommentId(`docx-comment-${sourceId}`, comments);
464
+ if (!workIds.has(sourceId)) {
465
+ workIds.set(sourceId, workId);
466
+ comments.push(toWorkComment(workId, bySourceId.get(sourceId), definitions));
467
+ }
468
+ const index = ranges.length + 1;
469
+ const range = {
470
+ id: workId,
471
+ start: `__A3S_WORK_COMMENT_START_${index}__`,
472
+ end: `__A3S_WORK_COMMENT_END_${index}__`
473
+ };
474
+ start.parentNode.insertBefore(work_docx_comment_import_markerRun(document, range.start), start);
475
+ end.parentNode.insertBefore(work_docx_comment_import_markerRun(document, range.end), end.nextSibling);
476
+ start.remove();
477
+ end.remove();
478
+ for (const reference of descendants(document, 'commentReference').filter((candidate)=>attribute(candidate, 'id') === sourceId))reference.remove();
479
+ ranges.push(range);
480
+ }
481
+ return {
482
+ comments,
483
+ ranges
484
+ };
485
+ }
486
+ function applyImportedDocxCommentMarkers(document, markers) {
487
+ for (const marker of markers.ranges)wrapTextBetweenMarkers(document.body, marker.start, marker.end, ()=>{
488
+ const element = document.createElement('span');
489
+ element.dataset.documentComment = 'true';
490
+ element.dataset.commentId = marker.id;
491
+ return element;
492
+ });
493
+ }
494
+ function hasImportedDocxCommentMarkers(markers) {
495
+ return markers.ranges.length > 0;
496
+ }
497
+ async function readCommentDefinitions(archive) {
498
+ const document = await archive.xml('word/comments.xml');
499
+ const extended = await readCommentExtended(archive);
500
+ return descendants(document, 'comment').map((comment)=>{
501
+ const paragraphs = descendants(comment, 'p');
502
+ const paraId = attribute(paragraphs.at(-1) ?? comment, 'paraId')?.trim() ?? '';
503
+ const metadata = extended.get(paraId);
504
+ return {
505
+ sourceId: attribute(comment, 'id')?.trim() ?? '',
506
+ author: attribute(comment, 'author')?.trim() || '未知审阅者',
507
+ date: work_docx_comment_import_normalizeDate(attribute(comment, 'date')),
508
+ text: commentText(comment),
509
+ paraId,
510
+ parentParaId: metadata?.parentParaId ?? '',
511
+ resolved: metadata?.resolved ?? false
512
+ };
513
+ });
514
+ }
515
+ async function readCommentExtended(archive) {
516
+ if (!archive.has('word/commentsExtended.xml')) return new Map();
517
+ const document = await archive.xml('word/commentsExtended.xml');
518
+ return new Map(descendants(document, 'commentEx').map((comment)=>{
519
+ const paraId = attribute(comment, 'paraId')?.trim() ?? '';
520
+ return [
521
+ paraId,
522
+ {
523
+ parentParaId: attribute(comment, 'paraIdParent')?.trim() ?? '',
524
+ resolved: '1' === attribute(comment, 'done') || 'true' === attribute(comment, 'done')
525
+ }
526
+ ];
527
+ }).filter(([paraId])=>Boolean(paraId)));
528
+ }
529
+ function toWorkComment(id, root, definitions) {
530
+ if (!root) return {
531
+ id,
532
+ author: '未知审阅者',
533
+ date: '',
534
+ text: '此批注的内容无法读取。',
535
+ resolved: false
536
+ };
537
+ const replies = definitions.filter((definition)=>definition !== root && commentRoot(definition, definitions) === root).map((definition)=>({
538
+ id: `docx-comment-reply-${definition.sourceId}`,
539
+ author: definition.author,
540
+ date: definition.date,
541
+ text: definition.text
542
+ }));
543
+ return {
544
+ id,
545
+ author: root.author,
546
+ date: root.date,
547
+ text: root.text,
548
+ resolved: root.resolved,
549
+ replies: replies.length ? replies : void 0
550
+ };
551
+ }
552
+ function commentRoot(definition, definitions) {
553
+ const byParaId = new Map(definitions.map((item)=>[
554
+ item.paraId,
555
+ item
556
+ ]));
557
+ const visited = new Set();
558
+ let current = definition;
559
+ while(current.parentParaId && !visited.has(current.parentParaId)){
560
+ visited.add(current.parentParaId);
561
+ const parent = byParaId.get(current.parentParaId);
562
+ if (!parent) break;
563
+ current = parent;
564
+ }
565
+ return current;
566
+ }
567
+ function commentText(comment) {
568
+ const paragraphs = descendants(comment, 'p');
569
+ const text = paragraphs.map((paragraph)=>descendants(paragraph, 't').map((node)=>node.textContent ?? '').join('').trim()).filter(Boolean).join('\n');
570
+ return text || '(空批注)';
571
+ }
572
+ function work_docx_comment_import_markerRun(document, value) {
573
+ const run = document.createElementNS(work_docx_comment_import_WORD_NAMESPACE, 'w:r');
574
+ const text = document.createElementNS(work_docx_comment_import_WORD_NAMESPACE, 'w:t');
575
+ text.setAttributeNS(work_docx_comment_import_XML_NAMESPACE, 'xml:space', 'preserve');
576
+ text.textContent = value;
577
+ run.append(text);
578
+ return run;
579
+ }
580
+ function wrapTextBetweenMarkers(root, startMarker, endMarker, createWrapper) {
581
+ const nodes = work_docx_comment_import_textNodes(root);
582
+ const startNode = nodes.find((node)=>node.data.includes(startMarker));
583
+ const endNode = nodes.find((node)=>node.data.includes(endMarker));
584
+ if (!startNode || !endNode) return false;
585
+ const startNodeIndex = nodes.indexOf(startNode);
586
+ const endNodeIndex = nodes.indexOf(endNode);
587
+ const startIndex = startNode.data.indexOf(startMarker);
588
+ const endIndex = endNode.data.indexOf(endMarker);
589
+ if (startNodeIndex > endNodeIndex || startNode === endNode && endIndex < startIndex + startMarker.length) return false;
590
+ const startOffset = startIndex;
591
+ let endOffset = endIndex;
592
+ if (startNode === endNode) {
593
+ const value = startNode.data;
594
+ endOffset = endIndex - startMarker.length;
595
+ startNode.data = value.slice(0, startIndex) + value.slice(startIndex + startMarker.length, endIndex) + value.slice(endIndex + endMarker.length);
596
+ } else {
597
+ startNode.data = startNode.data.slice(0, startIndex) + startNode.data.slice(startIndex + startMarker.length);
598
+ endNode.data = endNode.data.slice(0, endIndex) + endNode.data.slice(endIndex + endMarker.length);
599
+ }
600
+ let wrapped = false;
601
+ for(let index = startNodeIndex; index <= endNodeIndex; index += 1){
602
+ const node = nodes[index];
603
+ const from = index === startNodeIndex ? startOffset : 0;
604
+ const to = index === endNodeIndex ? endOffset : node.data.length;
605
+ if (!(from >= to) && node.parentNode) {
606
+ wrapTextSegment(node, from, to, createWrapper());
607
+ wrapped = true;
608
+ }
609
+ }
610
+ return wrapped;
611
+ }
612
+ function wrapTextSegment(node, from, to, wrapper) {
613
+ let selected = node;
614
+ if (from > 0) selected = node.splitText(from);
615
+ const length = to - from;
616
+ if (length < selected.data.length) selected.splitText(length);
617
+ selected.parentNode?.insertBefore(wrapper, selected);
618
+ wrapper.append(selected);
619
+ }
620
+ function work_docx_comment_import_textNodes(root) {
621
+ const document = root.ownerDocument;
622
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
623
+ const nodes = [];
624
+ if (!walker) return nodes;
625
+ while(walker.nextNode())nodes.push(walker.currentNode);
626
+ return nodes;
627
+ }
628
+ function uniqueWorkCommentId(base, comments) {
629
+ const ids = new Set(comments.map((comment)=>comment.id));
630
+ if (!ids.has(base)) return base;
631
+ let suffix = 2;
632
+ while(ids.has(`${base}-${suffix}`))suffix += 1;
633
+ return `${base}-${suffix}`;
634
+ }
635
+ function work_docx_comment_import_normalizeDate(value) {
636
+ if (!value) return '';
637
+ const time = Date.parse(value);
638
+ return Number.isFinite(time) ? new Date(time).toISOString() : '';
639
+ }
640
+ function work_docx_comment_import_compareDocumentOrder(left, right) {
641
+ if (left === right) return 0;
642
+ return left.compareDocumentPosition(right) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
643
+ }
644
+ const TWIPS_PER_MILLIMETER = 1440 / 25.4;
645
+ function importDocxColumns(element, fallback) {
646
+ const columnElements = directChildren(element, 'col');
647
+ const sourceCount = numberAttribute(element, 'num') || columnElements.length || fallback.count;
648
+ const count = Math.min(6, Math.max(1, sourceCount));
649
+ const spacingAttribute = attribute(element, 'space');
650
+ const spacing = null === spacingAttribute ? fallback.spacing : twipsToMillimeters(Number(spacingAttribute), fallback.spacing);
651
+ const base = {
652
+ count,
653
+ spacing,
654
+ separator: enabledAttribute(element, 'sep')
655
+ };
656
+ if (!columnElements.length) return normalizeDocumentColumns(base);
657
+ return normalizeDocumentColumns({
658
+ ...base,
659
+ count: Math.min(count, columnElements.length),
660
+ custom: columnElements.slice(0, count).map((column, index)=>{
661
+ const columnSpacing = attribute(column, 'space');
662
+ return {
663
+ widthPercent: Math.max(1, numberAttribute(column, 'w')),
664
+ spacing: index === Math.min(count, columnElements.length) - 1 ? 0 : null === columnSpacing ? spacing : twipsToMillimeters(Number(columnSpacing), spacing)
665
+ };
666
+ })
667
+ });
668
+ }
669
+ function numberAttribute(element, name) {
670
+ const value = Number(attribute(element, name));
671
+ return Number.isFinite(value) ? value : 0;
672
+ }
673
+ function enabledAttribute(element, name) {
674
+ const value = attribute(element, name)?.toLowerCase();
675
+ return '1' === value || 'true' === value || 'on' === value;
676
+ }
677
+ function twipsToMillimeters(value, fallback) {
678
+ return Number.isFinite(value) ? roundOne(Math.max(0, value) / TWIPS_PER_MILLIMETER) : fallback;
679
+ }
680
+ function roundOne(value) {
681
+ return Math.round(10 * value) / 10;
682
+ }
683
+ const work_docx_field_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
684
+ const work_docx_field_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
685
+ function markDocxBodyFields(document) {
686
+ const fields = docxFieldOccurrences(document).flatMap((field, index)=>{
687
+ const kind = docxDocumentFieldKind(field.instruction);
688
+ if (!kind || !work_docx_field_import_canMarkField(field)) return [];
689
+ const marker = {
690
+ start: `__A3S_WORK_FIELD_START_${index + 1}__`,
691
+ end: `__A3S_WORK_FIELD_END_${index + 1}__`,
692
+ id: `docx-field-${index + 1}`,
693
+ kind,
694
+ instruction: field.instruction,
695
+ display: docxFieldResultText(field)
696
+ };
697
+ work_docx_field_import_insertFieldBoundaryMarkers(document, field, marker.start, marker.end);
698
+ return [
699
+ marker
700
+ ];
701
+ });
702
+ return {
703
+ fields
704
+ };
705
+ }
706
+ function applyImportedDocxFieldMarkers(document, markers) {
707
+ for (const field of markers.fields){
708
+ const element = document.createElement('span');
709
+ element.dataset.documentField = 'true';
710
+ element.dataset.fieldId = field.id;
711
+ element.dataset.fieldKind = field.kind;
712
+ element.dataset.fieldInstruction = field.instruction;
713
+ const convertedDisplay = work_docx_field_import_replaceMarkerRange(document.body, field.start, field.end, element);
714
+ const display = field.display.trim() || convertedDisplay.trim();
715
+ element.dataset.fieldDisplay = display;
716
+ element.textContent = display;
717
+ }
718
+ }
719
+ function hasImportedDocxFieldMarkers(markers) {
720
+ return markers.fields.length > 0;
721
+ }
722
+ function work_docx_field_import_canMarkField(field) {
723
+ return field.start !== field.end || 'fldSimple' === field.start.localName;
724
+ }
725
+ function work_docx_field_import_insertFieldBoundaryMarkers(document, field, start, end) {
726
+ if ('fldChar' === field.start.localName && 'fldChar' === field.end.localName) {
727
+ field.start.parentNode?.insertBefore(work_docx_field_import_markerText(document, start), field.start);
728
+ field.end.parentNode?.insertBefore(work_docx_field_import_markerText(document, end), field.end.nextSibling);
729
+ return;
730
+ }
731
+ field.start.parentNode?.insertBefore(work_docx_field_import_markerRun(document, start), field.start);
732
+ field.end.parentNode?.insertBefore(work_docx_field_import_markerRun(document, end), field.end.nextSibling);
733
+ }
734
+ function work_docx_field_import_markerRun(document, text) {
735
+ const run = document.createElementNS(work_docx_field_import_WORD_NAMESPACE, 'w:r');
736
+ run.append(work_docx_field_import_markerText(document, text));
737
+ return run;
738
+ }
739
+ function work_docx_field_import_markerText(document, text) {
740
+ const value = document.createElementNS(work_docx_field_import_WORD_NAMESPACE, 'w:t');
741
+ value.setAttributeNS(work_docx_field_import_XML_NAMESPACE, 'xml:space', 'preserve');
742
+ value.textContent = text;
743
+ return value;
744
+ }
745
+ function work_docx_field_import_replaceMarkerRange(root, start, end, replacement) {
746
+ const nodes = work_docx_field_import_textNodes(root);
747
+ const startNode = nodes.find((node)=>node.data.includes(start));
748
+ const endNode = nodes.find((node)=>node.data.includes(end));
749
+ if (!startNode || !endNode) return '';
750
+ const range = root.ownerDocument.createRange();
751
+ range.setStart(startNode, startNode.data.indexOf(start));
752
+ range.setEnd(endNode, endNode.data.indexOf(end) + end.length);
753
+ const content = range.cloneContents();
754
+ work_docx_field_import_removeMarkerText(content, start);
755
+ work_docx_field_import_removeMarkerText(content, end);
756
+ const display = content.textContent ?? '';
757
+ range.deleteContents();
758
+ range.insertNode(replacement);
759
+ return display;
760
+ }
761
+ function work_docx_field_import_removeMarkerText(root, marker) {
762
+ for (const node of work_docx_field_import_textNodes(root))node.data = node.data.replace(marker, '');
763
+ }
764
+ function work_docx_field_import_textNodes(root) {
765
+ const document = root.ownerDocument;
766
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
767
+ const nodes = [];
768
+ if (!walker) return nodes;
769
+ while(walker.nextNode())nodes.push(walker.currentNode);
770
+ return nodes;
771
+ }
772
+ function extractMammothDocumentNotes(document) {
773
+ const definitions = extractDefinitions(document);
774
+ const notes = new Map();
775
+ const counters = {
776
+ footnote: 0,
777
+ endnote: 0
778
+ };
779
+ const references = Array.from(document.body.querySelectorAll('a[href^="#footnote-"], a[href^="#endnote-"]'));
780
+ for (const reference of references){
781
+ const target = reference.getAttribute('href')?.slice(1) ?? '';
782
+ const kind = noteKindFromTarget(target);
783
+ if (!kind) continue;
784
+ let note = notes.get(target);
785
+ if (!note) {
786
+ counters[kind] += 1;
787
+ note = {
788
+ id: `document-${kind}-${counters[kind]}`,
789
+ kind,
790
+ number: counters[kind],
791
+ html: definitions.get(target) ?? '<p></p>'
792
+ };
793
+ notes.set(target, note);
794
+ }
795
+ const marker = document.createElement('sup');
796
+ marker.setAttribute('data-document-note-reference', 'true');
797
+ marker.setAttribute('data-note-kind', note.kind);
798
+ marker.setAttribute('data-note-id', note.id);
799
+ marker.setAttribute('data-note-number', String(note.number));
800
+ marker.textContent = String(note.number);
801
+ const wrapper = reference.parentElement;
802
+ if (wrapper?.tagName.toLowerCase() === 'sup' && 1 === wrapper.childNodes.length) wrapper.replaceWith(marker);
803
+ else reference.replaceWith(marker);
804
+ }
805
+ return Array.from(notes.values());
806
+ }
807
+ function placeMammothDocumentNotes(document, notes) {
808
+ const sections = Array.from(document.body.querySelectorAll('section[data-document-section]'));
809
+ for (const note of notes){
810
+ const reference = Array.from(document.body.querySelectorAll('sup[data-document-note-reference]')).find((element)=>element.dataset.noteKind === note.kind && element.dataset.noteId === note.id);
811
+ const target = 'footnote' === note.kind ? reference?.closest('section[data-document-section]') : sections.at(-1);
812
+ (target ?? document.body).append(createDocumentNoteElement(document, note));
813
+ }
814
+ }
815
+ function extractDefinitions(document) {
816
+ const definitions = new Map();
817
+ const elements = Array.from(document.body.querySelectorAll('li[id^="footnote-"], li[id^="endnote-"]'));
818
+ for (const element of elements){
819
+ const id = element.id;
820
+ const clone = element.cloneNode(true);
821
+ for (const backlink of Array.from(clone.querySelectorAll('a[href^="#footnote-ref-"], a[href^="#endnote-ref-"]')))backlink.remove();
822
+ definitions.set(id, clone.innerHTML.trim() || '<p></p>');
823
+ const parent = element.parentElement;
824
+ element.remove();
825
+ if (parent && !parent.children.length) parent.remove();
826
+ }
827
+ return definitions;
828
+ }
829
+ function noteKindFromTarget(target) {
830
+ if (target.startsWith('footnote-')) return 'footnote';
831
+ if (target.startsWith('endnote-')) return 'endnote';
832
+ return null;
833
+ }
834
+ const work_docx_list_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
835
+ const work_docx_list_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
836
+ const LIST_START_MARKER_PATTERN = /__A3S_WORK_LIST_START_\d+__/g;
837
+ function markDocxLists(document, numbering) {
838
+ if (!numbering) return {
839
+ lists: []
840
+ };
841
+ const abstractNumbering = new Map(descendants(numbering, 'abstractNum').flatMap((element)=>{
842
+ const id = integerAttribute(element, 'abstractNumId');
843
+ return null === id ? [] : [
844
+ [
845
+ id,
846
+ element
847
+ ]
848
+ ];
849
+ }));
850
+ const concreteNumbering = new Map(descendants(numbering, 'num').flatMap((element)=>{
851
+ const id = integerAttribute(element, 'numId');
852
+ return null === id ? [] : [
853
+ [
854
+ id,
855
+ element
856
+ ]
857
+ ];
858
+ }));
859
+ const seen = new Set();
860
+ const lists = [];
861
+ for (const paragraph of descendants(document, 'p')){
862
+ const properties = directChild(paragraph, 'pPr');
863
+ const numberingProperties = properties ? directChild(properties, 'numPr') : void 0;
864
+ const numId = integerAttribute(numberingProperties ? directChild(numberingProperties, 'numId') : null, 'val');
865
+ if (null === numId) continue;
866
+ const level = integerAttribute(numberingProperties ? directChild(numberingProperties, 'ilvl') : null, 'val') ?? 0;
867
+ const key = `${numId}:${level}`;
868
+ if (seen.has(key)) continue;
869
+ seen.add(key);
870
+ const concrete = concreteNumbering.get(numId);
871
+ const abstractId = integerAttribute(concrete ? directChild(concrete, 'abstractNumId') : null, 'val');
872
+ const abstract = null === abstractId ? void 0 : abstractNumbering.get(abstractId);
873
+ const start = effectiveListStart(concrete, abstract, level);
874
+ const type = effectiveOrderedListType(concrete, abstract, level);
875
+ const bulletStyle = effectiveBulletListStyle(concrete, abstract, level);
876
+ if (start <= 1 && !type && !bulletStyle) continue;
877
+ const marker = `__A3S_WORK_LIST_START_${lists.length + 1}__`;
878
+ insertParagraphMarker(document, paragraph, marker);
879
+ lists.push({
880
+ marker,
881
+ start,
882
+ ...type ? {
883
+ type
884
+ } : {},
885
+ ...bulletStyle ? {
886
+ bulletStyle
887
+ } : {}
888
+ });
889
+ }
890
+ return {
891
+ lists
892
+ };
893
+ }
894
+ function applyImportedDocxListMarkers(document, markers) {
895
+ const listByMarker = new Map(markers.lists.map((list)=>[
896
+ list.marker,
897
+ list
898
+ ]));
899
+ for (const node of work_docx_list_import_textNodes(document.body)){
900
+ if (!node.data.includes('__A3S_WORK_LIST_START_')) continue;
901
+ const item = node.parentElement?.closest('li');
902
+ const list = item?.parentElement;
903
+ node.data = node.data.replace(LIST_START_MARKER_PATTERN, (marker)=>{
904
+ const imported = listByMarker.get(marker);
905
+ if (imported && list instanceof HTMLElement) {
906
+ if ('ol' === list.tagName.toLowerCase()) {
907
+ if (imported.start > 1) list.setAttribute('start', String(imported.start));
908
+ if (imported.type) list.setAttribute('type', imported.type);
909
+ }
910
+ if ('ul' === list.tagName.toLowerCase() && imported.bulletStyle) {
911
+ list.dataset.officeBulletStyle = imported.bulletStyle;
912
+ list.style.listStyleType = imported.bulletStyle;
913
+ }
914
+ }
915
+ return '';
916
+ });
917
+ }
918
+ document.body.normalize();
919
+ }
920
+ function hasImportedDocxListMarkers(markers) {
921
+ return markers.lists.length > 0;
922
+ }
923
+ function effectiveListStart(concrete, abstract, level) {
924
+ const override = concrete ? descendants(concrete, 'lvlOverride').find((candidate)=>integerAttribute(candidate, 'ilvl') === level) : void 0;
925
+ const overrideStart = integerAttribute(override ? directChild(override, 'startOverride') : null, 'val');
926
+ if (null !== overrideStart) return overrideStart;
927
+ const overrideLevel = override ? directChild(override, 'lvl') : void 0;
928
+ const abstractLevel = abstract ? descendants(abstract, 'lvl').find((candidate)=>integerAttribute(candidate, 'ilvl') === level) : void 0;
929
+ return integerAttribute(overrideLevel ? directChild(overrideLevel, 'start') : null, 'val') ?? integerAttribute(abstractLevel ? directChild(abstractLevel, 'start') : null, 'val') ?? 1;
930
+ }
931
+ function effectiveOrderedListType(concrete, abstract, level) {
932
+ const override = concrete ? descendants(concrete, 'lvlOverride').find((candidate)=>integerAttribute(candidate, 'ilvl') === level) : void 0;
933
+ const overrideLevel = override ? directChild(override, 'lvl') : void 0;
934
+ const abstractLevel = abstract ? descendants(abstract, 'lvl').find((candidate)=>integerAttribute(candidate, 'ilvl') === level) : void 0;
935
+ const format = stringAttribute(overrideLevel ? directChild(overrideLevel, 'numFmt') : null, 'val') ?? stringAttribute(abstractLevel ? directChild(abstractLevel, 'numFmt') : null, 'val');
936
+ if ('lowerLetter' === format) return 'a';
937
+ if ('upperLetter' === format) return 'A';
938
+ if ('lowerRoman' === format) return 'i';
939
+ if ('upperRoman' === format) return 'I';
940
+ }
941
+ function effectiveBulletListStyle(concrete, abstract, level) {
942
+ const definition = effectiveListLevel(concrete, abstract, level);
943
+ const format = stringAttribute(definition ? directChild(definition, 'numFmt') : null, 'val');
944
+ if ('bullet' !== format) return;
945
+ const marker = stringAttribute(definition ? directChild(definition, 'lvlText') : null, 'val') ?? '';
946
+ if (/^[o○◦\uF06F]$/u.test(marker)) return 'circle';
947
+ if (/^[■▪□\uF0A7]$/u.test(marker)) return 'square';
948
+ return 'disc';
949
+ }
950
+ function effectiveListLevel(concrete, abstract, level) {
951
+ const override = concrete ? descendants(concrete, 'lvlOverride').find((candidate)=>integerAttribute(candidate, 'ilvl') === level) : void 0;
952
+ return (override ? directChild(override, 'lvl') : void 0) ?? (abstract ? descendants(abstract, 'lvl').find((candidate)=>integerAttribute(candidate, 'ilvl') === level) : void 0);
953
+ }
954
+ function insertParagraphMarker(document, paragraph, marker) {
955
+ const run = document.createElementNS(work_docx_list_import_WORD_NAMESPACE, 'w:r');
956
+ const text = document.createElementNS(work_docx_list_import_WORD_NAMESPACE, 'w:t');
957
+ text.setAttributeNS(work_docx_list_import_XML_NAMESPACE, 'xml:space', 'preserve');
958
+ text.textContent = marker;
959
+ run.append(text);
960
+ const properties = directChild(paragraph, 'pPr');
961
+ paragraph.insertBefore(run, properties?.nextSibling ?? paragraph.firstChild);
962
+ }
963
+ function integerAttribute(element, name) {
964
+ if (!element) return null;
965
+ const source = attribute(element, name) ?? (name.includes(':') ? null : attribute(element, `w:${name}`));
966
+ if (null === source) return null;
967
+ const value = Number(source);
968
+ return Number.isSafeInteger(value) && value >= 0 ? value : null;
969
+ }
970
+ function stringAttribute(element, name) {
971
+ if (!element) return null;
972
+ const value = attribute(element, name) ?? (name.includes(':') ? null : attribute(element, `w:${name}`));
973
+ return value?.trim() || null;
974
+ }
975
+ function work_docx_list_import_textNodes(root) {
976
+ const document = root.ownerDocument;
977
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
978
+ const nodes = [];
979
+ if (!walker) return nodes;
980
+ while(walker.nextNode())nodes.push(walker.currentNode);
981
+ return nodes;
982
+ }
983
+ const work_docx_image_layout_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
984
+ const work_docx_image_layout_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
985
+ const EMUS_PER_MILLIMETER = 36000;
986
+ const IMAGE_LAYOUT_MARKER_PATTERN = /__A3S_WORK_IMAGE_LAYOUT_\d+_(?:START|END)__/g;
987
+ function markDocxImageLayouts(document) {
988
+ const images = [];
989
+ const markedRuns = new Set();
990
+ for (const anchor of descendants(document, 'anchor')){
991
+ const run = closestAncestor(anchor, 'r');
992
+ if (!run || markedRuns.has(run)) continue;
993
+ const layout = anchorLayout(anchor);
994
+ if (!layout) continue;
995
+ markedRuns.add(run);
996
+ const index = images.length + 1;
997
+ const startMarker = `__A3S_WORK_IMAGE_LAYOUT_${index}_START__`;
998
+ const endMarker = `__A3S_WORK_IMAGE_LAYOUT_${index}_END__`;
999
+ insertMarkerRun(document, run, startMarker, 'before');
1000
+ insertMarkerRun(document, run, endMarker, 'after');
1001
+ images.push({
1002
+ startMarker,
1003
+ endMarker,
1004
+ options: normalizeDocumentImageLayoutOptions({
1005
+ layout,
1006
+ alignment: anchorAlignment(anchor),
1007
+ wrapDistance: anchorWrapDistance(anchor, layout)
1008
+ })
1009
+ });
1010
+ }
1011
+ return {
1012
+ images
1013
+ };
1014
+ }
1015
+ function applyImportedDocxImageLayoutMarkers(document, markers) {
1016
+ const starts = new Map(markers.images.map((image)=>[
1017
+ image.startMarker,
1018
+ image
1019
+ ]));
1020
+ const ends = new Set(markers.images.map((image)=>image.endMarker));
1021
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);
1022
+ const nodes = [];
1023
+ while(walker.nextNode())nodes.push(walker.currentNode);
1024
+ const state = {
1025
+ active: null,
1026
+ applied: false
1027
+ };
1028
+ for (const node of nodes){
1029
+ if (node instanceof Text) {
1030
+ node.data = node.data.replace(IMAGE_LAYOUT_MARKER_PATTERN, (marker)=>{
1031
+ const start = starts.get(marker);
1032
+ if (start) {
1033
+ state.active = start;
1034
+ state.applied = false;
1035
+ } else if (ends.has(marker)) {
1036
+ state.active = null;
1037
+ state.applied = false;
1038
+ }
1039
+ return '';
1040
+ });
1041
+ continue;
1042
+ }
1043
+ if (!state.applied && state.active && node instanceof HTMLImageElement) {
1044
+ applyImageLayout(node, state.active.options);
1045
+ state.applied = true;
1046
+ }
1047
+ }
1048
+ document.body.normalize();
1049
+ }
1050
+ function hasImportedDocxImageLayoutMarkers(markers) {
1051
+ return markers.images.length > 0;
1052
+ }
1053
+ function anchorLayout(anchor) {
1054
+ if (directChild(anchor, 'wrapTopAndBottom')) return 'topBottom';
1055
+ if (directChild(anchor, 'wrapSquare') || directChild(anchor, 'wrapTight') || directChild(anchor, 'wrapThrough')) return 'square';
1056
+ return null;
1057
+ }
1058
+ function anchorAlignment(anchor) {
1059
+ const position = directChild(anchor, 'positionH');
1060
+ const alignment = position ? directChild(position, 'align') : void 0;
1061
+ const value = alignment?.textContent?.trim();
1062
+ if ('inside' === value) return 'left';
1063
+ if ('outside' === value) return 'right';
1064
+ return normalizeDocumentImageAlignment(value);
1065
+ }
1066
+ function anchorWrapDistance(anchor, layout) {
1067
+ const wrap = directChild(anchor, 'square' === layout ? 'wrapSquare' : 'wrapTopAndBottom') ?? ('square' === layout ? directChild(anchor, 'wrapTight') ?? directChild(anchor, 'wrapThrough') : void 0);
1068
+ const names = 'square' === layout ? [
1069
+ 'distL',
1070
+ 'distR'
1071
+ ] : [
1072
+ 'distT',
1073
+ 'distB'
1074
+ ];
1075
+ const distance = Math.max(0, ...names.flatMap((name)=>[
1076
+ numericAttribute(wrap, name) ?? 0,
1077
+ numericAttribute(anchor, name) ?? 0
1078
+ ]));
1079
+ return distance / EMUS_PER_MILLIMETER;
1080
+ }
1081
+ function insertMarkerRun(document, run, marker, position) {
1082
+ const markerRun = document.createElementNS(work_docx_image_layout_import_WORD_NAMESPACE, 'w:r');
1083
+ const text = document.createElementNS(work_docx_image_layout_import_WORD_NAMESPACE, 'w:t');
1084
+ text.setAttributeNS(work_docx_image_layout_import_XML_NAMESPACE, 'xml:space', 'preserve');
1085
+ text.textContent = marker;
1086
+ markerRun.append(text);
1087
+ const parent = run.parentNode;
1088
+ if (!parent) return;
1089
+ parent.insertBefore(markerRun, 'before' === position ? run : run.nextSibling);
1090
+ }
1091
+ function applyImageLayout(image, options) {
1092
+ image.dataset.officeImageLayout = options.layout;
1093
+ image.dataset.officeImageAlignment = options.alignment;
1094
+ image.dataset.officeImageWrapDistance = formatNumber(options.wrapDistance);
1095
+ image.style.setProperty('--work-document-image-wrap-distance', `${formatNumber(options.wrapDistance)}mm`);
1096
+ }
1097
+ function numericAttribute(element, name) {
1098
+ if (!element) return null;
1099
+ const source = attribute(element, name);
1100
+ if (null === source || !source.trim()) return null;
1101
+ const value = Number(source);
1102
+ return Number.isFinite(value) && value >= 0 ? value : null;
1103
+ }
1104
+ function closestAncestor(element, localName) {
1105
+ let current = element;
1106
+ while(current){
1107
+ if (current.localName === localName) return current;
1108
+ current = current.parentElement;
1109
+ }
1110
+ return null;
1111
+ }
1112
+ function formatNumber(value) {
1113
+ return Number(value.toFixed(2)).toString();
1114
+ }
1115
+ async function importSectionPageChrome(section, archive, documentRelationships, previous, oddEvenEnabled) {
1116
+ const fallback = normalizeDocumentPageChrome(previous.pageChrome, previous);
1117
+ const variants = await Promise.all([
1118
+ 'default',
1119
+ 'first',
1120
+ 'even'
1121
+ ].map(async (variant)=>{
1122
+ const content = await importVariant(section, variant, archive, documentRelationships, fallback[variant]);
1123
+ return [
1124
+ variant,
1125
+ content
1126
+ ];
1127
+ }));
1128
+ const hasFirstReferences = hasVariantReference(section, 'first');
1129
+ const hasEvenReferences = hasVariantReference(section, 'even');
1130
+ const pageChrome = normalizeDocumentPageChrome({
1131
+ differentFirstPage: enabledElement(firstDescendant(section, 'titlePg')) || hasFirstReferences,
1132
+ differentOddEvenPages: oddEvenEnabled || hasEvenReferences,
1133
+ ...Object.fromEntries(variants)
1134
+ });
1135
+ return {
1136
+ pageChrome,
1137
+ ...documentPageChromeLegacyFields(pageChrome)
1138
+ };
1139
+ }
1140
+ function documentUsesOddEvenPageChrome(settings) {
1141
+ return Boolean(settings && descendants(settings, 'evenAndOddHeaders').some(enabledElement));
1142
+ }
1143
+ async function importVariant(section, variant, archive, documentRelationships, fallback) {
1144
+ const header = await importReferencedPart(section, 'headerReference', variant, archive, documentRelationships);
1145
+ const footer = await importReferencedPart(section, 'footerReference', variant, archive, documentRelationships);
1146
+ const hasImportedPart = Boolean(header || footer);
1147
+ return {
1148
+ headerHtml: header?.html ?? fallback.headerHtml,
1149
+ footerHtml: footer?.html ?? fallback.footerHtml,
1150
+ showPageNumber: hasImportedPart ? Boolean(header?.showPageNumber || footer?.showPageNumber) : fallback.showPageNumber
1151
+ };
1152
+ }
1153
+ async function importReferencedPart(section, referenceName, variant, archive, documentRelationships) {
1154
+ const reference = directChildren(section, referenceName).find((element)=>(attribute(element, 'type') ?? 'default') === variant);
1155
+ const relationship = documentRelationships.get(attribute(reference ?? section, 'r:id') ?? '');
1156
+ if (!relationship || 'External' === relationship.targetMode || !archive.has(relationship.target)) return null;
1157
+ const document = await archive.xml(relationship.target);
1158
+ return {
1159
+ html: await pageChromePartHtml(document, archive, relationship.target),
1160
+ showPageNumber: containsPageNumber(document)
1161
+ };
1162
+ }
1163
+ async function pageChromePartHtml(document, archive, partPath) {
1164
+ const relationships = await archive.relationships(partPath);
1165
+ const root = document.documentElement;
1166
+ const blocks = [];
1167
+ for (const child of directChildren(root)){
1168
+ if ('p' === child.localName) blocks.push(await paragraphHtml(child, archive, relationships));
1169
+ if ('tbl' === child.localName) blocks.push(await tableHtml(child, archive, relationships));
1170
+ }
1171
+ return blocks.join('');
1172
+ }
1173
+ async function paragraphHtml(paragraph, archive, relationships) {
1174
+ const alignmentValue = attribute(firstDescendant(directChild(paragraph, 'pPr'), 'jc') ?? paragraph, 'val');
1175
+ const alignment = 'center' === alignmentValue ? 'center' : 'right' === alignmentValue || 'end' === alignmentValue ? 'right' : 'both' === alignmentValue || 'distribute' === alignmentValue ? 'justify' : 'left' === alignmentValue || 'start' === alignmentValue ? 'left' : '';
1176
+ const field = {
1177
+ active: false,
1178
+ instruction: '',
1179
+ separated: false,
1180
+ skipResult: false
1181
+ };
1182
+ let html = '';
1183
+ for (const child of directChildren(paragraph))if ('pPr' !== child.localName) {
1184
+ if ('hyperlink' === child.localName) {
1185
+ const content = await containerRunsHtml(child, field, archive, relationships);
1186
+ const relationship = relationships.get(attribute(child, 'r:id') ?? '');
1187
+ const anchor = attribute(child, 'anchor');
1188
+ const href = relationship?.targetMode === 'External' ? relationship.target : anchor ? `#${anchor}` : '';
1189
+ html += href ? `<a href="${escapeHtml(href)}">${content}</a>` : content;
1190
+ continue;
1191
+ }
1192
+ if ('fldSimple' === child.localName) {
1193
+ const instruction = attribute(child, 'instr') ?? '';
1194
+ if (!/\bPAGE\b/i.test(instruction)) html += await containerRunsHtml(child, field, archive, relationships);
1195
+ continue;
1196
+ }
1197
+ html += await containerRunsHtml(child, field, archive, relationships);
1198
+ }
1199
+ return `<p${alignment ? ` style="text-align: ${alignment}"` : ''}>${html}</p>`;
1200
+ }
1201
+ async function containerRunsHtml(container, field, archive, relationships) {
1202
+ if ('r' === container.localName) return runHtml(container, field, archive, relationships);
1203
+ let html = '';
1204
+ for (const run of descendants(container, 'r'))html += await runHtml(run, field, archive, relationships);
1205
+ return html;
1206
+ }
1207
+ async function runHtml(run, field, archive, relationships) {
1208
+ let content = '';
1209
+ for (const child of directChildren(run)){
1210
+ if ('fldChar' === child.localName) {
1211
+ updateFieldState(field, attribute(child, 'fldCharType'));
1212
+ continue;
1213
+ }
1214
+ if ('instrText' === child.localName) {
1215
+ if (field.active && !field.separated) field.instruction += child.textContent ?? '';
1216
+ continue;
1217
+ }
1218
+ if (fieldContentVisible(field)) {
1219
+ if ('t' === child.localName) content += escapeHtml(child.textContent ?? '');
1220
+ if ('tab' === child.localName) content += '&#9;';
1221
+ if ('br' === child.localName || 'cr' === child.localName) content += '<br>';
1222
+ if ('drawing' === child.localName) content += await drawingHtml(child, archive, relationships);
1223
+ }
1224
+ }
1225
+ if (!content) return '';
1226
+ const properties = directChild(run, 'rPr');
1227
+ if (enabledElement(directChild(properties ?? run, 'b'))) content = `<strong>${content}</strong>`;
1228
+ if (enabledElement(directChild(properties ?? run, 'i'))) content = `<em>${content}</em>`;
1229
+ const underline = directChild(properties ?? run, 'u');
1230
+ if (underline && 'none' !== attribute(underline, 'val')) content = `<u>${content}</u>`;
1231
+ if (enabledElement(directChild(properties ?? run, 'strike')) || enabledElement(directChild(properties ?? run, 'dstrike'))) content = `<s>${content}</s>`;
1232
+ const verticalAlign = attribute(directChild(properties ?? run, 'vertAlign') ?? run, 'val');
1233
+ if ("superscript" === verticalAlign) content = `<sup>${content}</sup>`;
1234
+ if ("subscript" === verticalAlign) content = `<sub>${content}</sub>`;
1235
+ const color = attribute(directChild(properties ?? run, 'color') ?? run, 'val');
1236
+ if (color && /^[0-9a-f]{6}$/i.test(color)) content = `<span style="color: #${color}">${content}</span>`;
1237
+ return content;
1238
+ }
1239
+ async function drawingHtml(drawing, archive, relationships) {
1240
+ const relationship = relationships.get(attribute(firstDescendant(drawing, 'blip') ?? drawing, 'embed') ?? '');
1241
+ if (!relationship || 'External' === relationship.targetMode || !archive.has(relationship.target)) return '';
1242
+ const source = bytesToDataUrl(await archive.bytes(relationship.target), contentTypeForPart(relationship.target));
1243
+ const extent = firstDescendant(drawing, 'extent');
1244
+ const width = Math.max(1, Math.round(Number(attribute(extent ?? drawing, 'cx')) / 9525));
1245
+ const height = Math.max(1, Math.round(Number(attribute(extent ?? drawing, 'cy')) / 9525));
1246
+ return `<img src="${source}" alt="Header or footer image"${width > 1 ? ` width="${width}"` : ''}${height > 1 ? ` height="${height}"` : ''}>`;
1247
+ }
1248
+ async function tableHtml(table, archive, relationships) {
1249
+ const rows = [];
1250
+ for (const row of directChildren(table, 'tr')){
1251
+ const cells = [];
1252
+ for (const cell of directChildren(row, 'tc')){
1253
+ const paragraphs = await Promise.all(directChildren(cell, 'p').map((item)=>paragraphHtml(item, archive, relationships)));
1254
+ cells.push(`<td>${paragraphs.join('')}</td>`);
1255
+ }
1256
+ rows.push(`<tr>${cells.join('')}</tr>`);
1257
+ }
1258
+ return `<table><tbody>${rows.join('')}</tbody></table>`;
1259
+ }
1260
+ function containsPageNumber(document) {
1261
+ return descendants(document, 'instrText').some((element)=>/\bPAGE\b/i.test(element.textContent ?? '')) || descendants(document, 'fldSimple').some((element)=>/\bPAGE\b/i.test(attribute(element, 'instr') ?? ''));
1262
+ }
1263
+ function hasVariantReference(section, variant) {
1264
+ return [
1265
+ ...directChildren(section, 'headerReference'),
1266
+ ...directChildren(section, 'footerReference')
1267
+ ].some((element)=>(attribute(element, 'type') ?? 'default') === variant);
1268
+ }
1269
+ function enabledElement(element) {
1270
+ if (!element) return false;
1271
+ const value = attribute(element, 'val')?.toLowerCase();
1272
+ return '0' !== value && 'false' !== value && 'off' !== value;
1273
+ }
1274
+ function escapeHtml(value) {
1275
+ return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
1276
+ }
1277
+ function updateFieldState(field, fieldType) {
1278
+ if ('begin' === fieldType) {
1279
+ field.active = true;
1280
+ field.instruction = '';
1281
+ field.separated = false;
1282
+ field.skipResult = false;
1283
+ return;
1284
+ }
1285
+ if ('separate' === fieldType && field.active) {
1286
+ field.separated = true;
1287
+ field.skipResult = /\bPAGE\b/i.test(field.instruction);
1288
+ return;
1289
+ }
1290
+ if ('end' === fieldType) {
1291
+ field.active = false;
1292
+ field.instruction = '';
1293
+ field.separated = false;
1294
+ field.skipResult = false;
1295
+ }
1296
+ }
1297
+ function fieldContentVisible(field) {
1298
+ return !field.active || field.separated && !field.skipResult;
1299
+ }
1300
+ const MAX_STYLE_INHERITANCE_DEPTH = 64;
1301
+ function createDocxParagraphStyleResolver(stylesDocument) {
1302
+ if (!stylesDocument) return {
1303
+ styles: new Map(),
1304
+ characterStyles: new Map()
1305
+ };
1306
+ const styles = new Map();
1307
+ const characterStyles = new Map();
1308
+ let defaultStyleId;
1309
+ for (const style of descendants(stylesDocument, 'style')){
1310
+ const type = wordAttribute(style, 'type');
1311
+ if ('paragraph' !== type && 'character' !== type) continue;
1312
+ const styleId = wordAttribute(style, 'styleId')?.trim();
1313
+ if (!styleId) continue;
1314
+ const basedOn = directChild(style, 'basedOn');
1315
+ const value = {
1316
+ basedOn: basedOn ? wordAttribute(basedOn, 'val')?.trim() || void 0 : void 0,
1317
+ paragraphProperties: directChild(style, 'pPr'),
1318
+ runProperties: directChild(style, 'rPr')
1319
+ };
1320
+ if ('paragraph' === type) styles.set(styleId, value);
1321
+ else characterStyles.set(styleId, value);
1322
+ if ('paragraph' === type && !defaultStyleId && onOffAttribute(style, 'default')) defaultStyleId = styleId;
1323
+ }
1324
+ return {
1325
+ defaultProperties: childPath(stylesDocument.documentElement, 'docDefaults', 'pPrDefault', 'pPr'),
1326
+ defaultRunProperties: childPath(stylesDocument.documentElement, 'docDefaults', 'rPrDefault', 'rPr'),
1327
+ defaultStyleId,
1328
+ styles,
1329
+ characterStyles
1330
+ };
1331
+ }
1332
+ function resolveDocxParagraphStyleResolver(source) {
1333
+ return source && 'styles' in source ? source : createDocxParagraphStyleResolver(source);
1334
+ }
1335
+ function docxParagraphPropertySources(directProperties, resolver) {
1336
+ const sources = [];
1337
+ if (resolver.defaultProperties) sources.push(resolver.defaultProperties);
1338
+ const styleReference = directProperties ? directChild(directProperties, 'pStyle') : void 0;
1339
+ const styleId = (styleReference ? wordAttribute(styleReference, 'val')?.trim() : void 0) || resolver.defaultStyleId;
1340
+ if (styleId) sources.push(...stylePropertySources(resolver.styles, styleId, 'paragraphProperties'));
1341
+ if (directProperties) sources.push(directProperties);
1342
+ return sources;
1343
+ }
1344
+ function docxRunPropertySources(paragraphProperties, runProperties, resolver) {
1345
+ const sources = [];
1346
+ if (resolver.defaultRunProperties) sources.push(resolver.defaultRunProperties);
1347
+ const paragraphStyleReference = paragraphProperties ? directChild(paragraphProperties, 'pStyle') : void 0;
1348
+ const paragraphStyleId = (paragraphStyleReference ? wordAttribute(paragraphStyleReference, 'val')?.trim() : void 0) || resolver.defaultStyleId;
1349
+ if (paragraphStyleId) sources.push(...stylePropertySources(resolver.styles, paragraphStyleId, 'runProperties'));
1350
+ const paragraphRunProperties = paragraphProperties ? directChild(paragraphProperties, 'rPr') : void 0;
1351
+ if (paragraphRunProperties) sources.push(paragraphRunProperties);
1352
+ const characterStyleReference = runProperties ? directChild(runProperties, 'rStyle') : void 0;
1353
+ const characterStyleId = characterStyleReference ? wordAttribute(characterStyleReference, 'val')?.trim() : void 0;
1354
+ if (characterStyleId) sources.push(...stylePropertySources(resolver.characterStyles, characterStyleId, 'runProperties'));
1355
+ if (runProperties) sources.push(runProperties);
1356
+ return sources;
1357
+ }
1358
+ function stylePropertySources(styles, styleId, property) {
1359
+ const inherited = [];
1360
+ const visited = new Set();
1361
+ let currentStyleId = styleId;
1362
+ let depth = 0;
1363
+ while(currentStyleId && depth < MAX_STYLE_INHERITANCE_DEPTH && !visited.has(currentStyleId)){
1364
+ depth += 1;
1365
+ visited.add(currentStyleId);
1366
+ const style = styles.get(currentStyleId);
1367
+ if (!style) break;
1368
+ const properties = style[property];
1369
+ if (properties) inherited.push(properties);
1370
+ currentStyleId = style.basedOn;
1371
+ }
1372
+ return inherited.reverse();
1373
+ }
1374
+ function onOffAttribute(element, name) {
1375
+ const value = wordAttribute(element, name)?.trim().toLowerCase();
1376
+ if (null == value) return false;
1377
+ return '0' !== value && 'false' !== value && 'off' !== value;
1378
+ }
1379
+ function wordAttribute(element, name) {
1380
+ return attribute(element, name) ?? attribute(element, `w:${name}`);
1381
+ }
1382
+ const work_docx_paragraph_direction_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
1383
+ const work_docx_paragraph_direction_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
1384
+ const PARAGRAPH_DIRECTION_MARKER_PATTERN = /__A3S_WORK_PARAGRAPH_DIRECTION_\d+__/g;
1385
+ function markDocxParagraphDirections(document, styleSource) {
1386
+ const paragraphs = [];
1387
+ const styles = resolveDocxParagraphStyleResolver(styleSource);
1388
+ for (const paragraph of descendants(document, 'p')){
1389
+ let properties = directChild(paragraph, 'pPr');
1390
+ const sources = docxParagraphPropertySources(properties, styles);
1391
+ const direction = paragraphDirection(sources);
1392
+ if (!direction) continue;
1393
+ properties ??= insertParagraphProperties(document, paragraph);
1394
+ const marker = `__A3S_WORK_PARAGRAPH_DIRECTION_${paragraphs.length + 1}__`;
1395
+ work_docx_paragraph_direction_import_insertParagraphMarker(document, paragraph, properties, marker);
1396
+ paragraphs.push({
1397
+ marker,
1398
+ direction
1399
+ });
1400
+ }
1401
+ return {
1402
+ paragraphs
1403
+ };
1404
+ }
1405
+ function applyImportedDocxParagraphDirectionMarkers(document, markers) {
1406
+ const directionByMarker = new Map(markers.paragraphs.map(({ marker, direction })=>[
1407
+ marker,
1408
+ direction
1409
+ ]));
1410
+ for (const node of work_docx_paragraph_direction_import_textNodes(document.body)){
1411
+ if (!node.data.includes('__A3S_WORK_PARAGRAPH_DIRECTION_')) continue;
1412
+ const block = closestParagraphBlock(node.parentElement);
1413
+ node.data = node.data.replace(PARAGRAPH_DIRECTION_MARKER_PATTERN, (marker)=>{
1414
+ const direction = directionByMarker.get(marker);
1415
+ if (block && direction) block.setAttribute('dir', direction);
1416
+ return '';
1417
+ });
1418
+ }
1419
+ document.body.normalize();
1420
+ }
1421
+ function hasImportedDocxParagraphDirectionMarkers(markers) {
1422
+ return markers.paragraphs.length > 0;
1423
+ }
1424
+ function paragraphDirection(propertySources) {
1425
+ let direction = null;
1426
+ for (const properties of propertySources){
1427
+ const bidi = directChild(properties, 'bidi');
1428
+ if (bidi) direction = onOffValue(bidi) ? 'rtl' : 'ltr';
1429
+ }
1430
+ return direction;
1431
+ }
1432
+ function onOffValue(element) {
1433
+ const value = (attribute(element, 'val') ?? attribute(element, 'w:val'))?.trim().toLowerCase();
1434
+ return '0' !== value && 'false' !== value && 'off' !== value;
1435
+ }
1436
+ function work_docx_paragraph_direction_import_insertParagraphMarker(document, paragraph, properties, marker) {
1437
+ const run = document.createElementNS(work_docx_paragraph_direction_import_WORD_NAMESPACE, 'w:r');
1438
+ const text = document.createElementNS(work_docx_paragraph_direction_import_WORD_NAMESPACE, 'w:t');
1439
+ text.setAttributeNS(work_docx_paragraph_direction_import_XML_NAMESPACE, 'xml:space', 'preserve');
1440
+ text.textContent = marker;
1441
+ run.append(text);
1442
+ paragraph.insertBefore(run, properties.nextSibling);
1443
+ }
1444
+ function insertParagraphProperties(document, paragraph) {
1445
+ const properties = document.createElementNS(work_docx_paragraph_direction_import_WORD_NAMESPACE, 'w:pPr');
1446
+ paragraph.insertBefore(properties, paragraph.firstChild);
1447
+ return properties;
1448
+ }
1449
+ function closestParagraphBlock(element) {
1450
+ const block = element?.closest('p, h1, h2, h3, h4, h5, h6, blockquote, li');
1451
+ return block instanceof HTMLElement ? block : null;
1452
+ }
1453
+ function work_docx_paragraph_direction_import_textNodes(root) {
1454
+ const document = root.ownerDocument;
1455
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
1456
+ const nodes = [];
1457
+ if (!walker) return nodes;
1458
+ while(walker.nextNode())nodes.push(walker.currentNode);
1459
+ return nodes;
1460
+ }
1461
+ const work_docx_paragraph_alignment_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
1462
+ const work_docx_paragraph_alignment_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
1463
+ const PARAGRAPH_ALIGNMENT_MARKER_PATTERN = /__A3S_WORK_PARAGRAPH_ALIGNMENT_\d+__/g;
1464
+ function markDocxParagraphAlignments(document, styleSource) {
1465
+ const paragraphs = [];
1466
+ const styles = resolveDocxParagraphStyleResolver(styleSource);
1467
+ for (const paragraph of descendants(document, 'p')){
1468
+ let properties = directChild(paragraph, 'pPr');
1469
+ const sources = docxParagraphPropertySources(properties, styles);
1470
+ const alignment = paragraphAlignment(sources);
1471
+ if (!alignment) continue;
1472
+ properties ??= work_docx_paragraph_alignment_import_insertParagraphProperties(document, paragraph);
1473
+ const marker = `__A3S_WORK_PARAGRAPH_ALIGNMENT_${paragraphs.length + 1}__`;
1474
+ work_docx_paragraph_alignment_import_insertParagraphMarker(document, paragraph, properties, marker);
1475
+ paragraphs.push({
1476
+ marker,
1477
+ alignment
1478
+ });
1479
+ }
1480
+ return {
1481
+ paragraphs
1482
+ };
1483
+ }
1484
+ function applyImportedDocxParagraphAlignmentMarkers(document, markers) {
1485
+ const alignmentByMarker = new Map(markers.paragraphs.map(({ marker, alignment })=>[
1486
+ marker,
1487
+ alignment
1488
+ ]));
1489
+ for (const node of work_docx_paragraph_alignment_import_textNodes(document.body))if (node.data.includes('__A3S_WORK_PARAGRAPH_ALIGNMENT_')) node.data = node.data.replace(PARAGRAPH_ALIGNMENT_MARKER_PATTERN, (marker)=>{
1490
+ const alignment = alignmentByMarker.get(marker);
1491
+ const block = alignment ? work_docx_paragraph_alignment_import_closestParagraphBlock(node.parentElement, node) : null;
1492
+ if (block && alignment) block.style.textAlign = alignment;
1493
+ return '';
1494
+ });
1495
+ document.body.normalize();
1496
+ }
1497
+ function hasImportedDocxParagraphAlignmentMarkers(markers) {
1498
+ return markers.paragraphs.length > 0;
1499
+ }
1500
+ function paragraphAlignment(propertySources) {
1501
+ let direction = 'ltr';
1502
+ let justification = null;
1503
+ let hasJustification = false;
1504
+ for (const properties of propertySources){
1505
+ const bidi = directChild(properties, 'bidi');
1506
+ if (bidi) direction = work_docx_paragraph_alignment_import_onOffValue(bidi) ? 'rtl' : 'ltr';
1507
+ const source = directChild(properties, 'jc');
1508
+ if (source) {
1509
+ hasJustification = true;
1510
+ justification = work_docx_paragraph_alignment_import_wordAttribute(source, 'val')?.trim() ?? null;
1511
+ }
1512
+ }
1513
+ if (!hasJustification || !justification) return null;
1514
+ if ('center' === justification) return 'center';
1515
+ if ('left' === justification) return 'left';
1516
+ if ('right' === justification) return 'right';
1517
+ if ('start' === justification) return 'rtl' === direction ? 'right' : 'left';
1518
+ if ('end' === justification) return 'rtl' === direction ? 'left' : 'right';
1519
+ if ('both' === justification || 'distribute' === justification || 'highKashida' === justification || 'lowKashida' === justification || 'mediumKashida' === justification || 'thaiDistribute' === justification) return 'justify';
1520
+ return null;
1521
+ }
1522
+ function work_docx_paragraph_alignment_import_onOffValue(element) {
1523
+ const value = work_docx_paragraph_alignment_import_wordAttribute(element, 'val')?.trim().toLowerCase();
1524
+ return '0' !== value && 'false' !== value && 'off' !== value;
1525
+ }
1526
+ function work_docx_paragraph_alignment_import_wordAttribute(element, name) {
1527
+ return attribute(element, name) ?? attribute(element, `w:${name}`);
1528
+ }
1529
+ function work_docx_paragraph_alignment_import_insertParagraphMarker(document, paragraph, properties, marker) {
1530
+ const run = document.createElementNS(work_docx_paragraph_alignment_import_WORD_NAMESPACE, 'w:r');
1531
+ const text = document.createElementNS(work_docx_paragraph_alignment_import_WORD_NAMESPACE, 'w:t');
1532
+ text.setAttributeNS(work_docx_paragraph_alignment_import_XML_NAMESPACE, 'xml:space', 'preserve');
1533
+ text.textContent = marker;
1534
+ run.append(text);
1535
+ paragraph.insertBefore(run, properties.nextSibling);
1536
+ }
1537
+ function work_docx_paragraph_alignment_import_insertParagraphProperties(document, paragraph) {
1538
+ const properties = document.createElementNS(work_docx_paragraph_alignment_import_WORD_NAMESPACE, 'w:pPr');
1539
+ paragraph.insertBefore(properties, paragraph.firstChild);
1540
+ return properties;
1541
+ }
1542
+ function work_docx_paragraph_alignment_import_closestParagraphBlock(element, markerNode) {
1543
+ const block = element?.closest('p, h1, h2, h3, h4, h5, h6, blockquote, li');
1544
+ if (!(block instanceof HTMLElement)) return null;
1545
+ return 'li' === block.tagName.toLowerCase() ? wrapListItemParagraph(block, markerNode) : block;
1546
+ }
1547
+ function wrapListItemParagraph(item, markerNode) {
1548
+ let anchor = markerNode;
1549
+ while(anchor.parentNode && anchor.parentNode !== item)anchor = anchor.parentNode;
1550
+ const children = Array.from(item.childNodes);
1551
+ const anchorIndex = children.indexOf(anchor);
1552
+ if (anchorIndex < 0) return item;
1553
+ let start = anchorIndex;
1554
+ let end = anchorIndex;
1555
+ while(start > 0 && !isListItemBlock(children[start - 1]))start -= 1;
1556
+ while(end + 1 < children.length && !isListItemBlock(children[end + 1]))end += 1;
1557
+ const paragraph = item.ownerDocument.createElement('p');
1558
+ const grouped = children.slice(start, end + 1);
1559
+ item.insertBefore(paragraph, grouped[0] ?? null);
1560
+ paragraph.append(...grouped);
1561
+ return paragraph;
1562
+ }
1563
+ function isListItemBlock(node) {
1564
+ if (!(node instanceof HTMLElement)) return false;
1565
+ return [
1566
+ 'blockquote',
1567
+ 'div',
1568
+ 'h1',
1569
+ 'h2',
1570
+ 'h3',
1571
+ 'h4',
1572
+ 'h5',
1573
+ 'h6',
1574
+ 'hr',
1575
+ 'ol',
1576
+ 'p',
1577
+ 'pre',
1578
+ 'table',
1579
+ 'ul'
1580
+ ].includes(node.tagName.toLowerCase());
1581
+ }
1582
+ function work_docx_paragraph_alignment_import_textNodes(root) {
1583
+ const document = root.ownerDocument;
1584
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
1585
+ const nodes = [];
1586
+ if (!walker) return nodes;
1587
+ while(walker.nextNode())nodes.push(walker.currentNode);
1588
+ return nodes;
1589
+ }
1590
+ const work_docx_paragraph_indent_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
1591
+ const work_docx_paragraph_indent_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
1592
+ const TWIPS_PER_CSS_PIXEL = 15;
1593
+ const PARAGRAPH_INDENT_MARKER_PATTERN = /__A3S_WORK_PARAGRAPH_INDENT_\d+__/g;
1594
+ function markDocxParagraphIndents(document, styleSource) {
1595
+ const paragraphs = [];
1596
+ const styles = resolveDocxParagraphStyleResolver(styleSource);
1597
+ for (const paragraph of descendants(document, 'p')){
1598
+ let properties = directChild(paragraph, 'pPr');
1599
+ const sources = docxParagraphPropertySources(properties, styles);
1600
+ if (sources.some((source)=>directChild(source, 'numPr'))) continue;
1601
+ const indent = paragraphIndent(sources);
1602
+ if (!indent.left && !indent.right && !indent.firstLine) continue;
1603
+ properties ??= work_docx_paragraph_indent_import_insertParagraphProperties(document, paragraph);
1604
+ const marker = `__A3S_WORK_PARAGRAPH_INDENT_${paragraphs.length + 1}__`;
1605
+ work_docx_paragraph_indent_import_insertParagraphMarker(document, paragraph, properties, marker);
1606
+ paragraphs.push({
1607
+ marker,
1608
+ indent
1609
+ });
1610
+ }
1611
+ return {
1612
+ paragraphs
1613
+ };
1614
+ }
1615
+ function applyImportedDocxParagraphIndentMarkers(document, markers) {
1616
+ const indentByMarker = new Map(markers.paragraphs.map(({ marker, indent })=>[
1617
+ marker,
1618
+ indent
1619
+ ]));
1620
+ for (const node of work_docx_paragraph_indent_import_textNodes(document.body)){
1621
+ if (!node.data.includes('__A3S_WORK_PARAGRAPH_INDENT_')) continue;
1622
+ const block = work_docx_paragraph_indent_import_closestParagraphBlock(node.parentElement);
1623
+ node.data = node.data.replace(PARAGRAPH_INDENT_MARKER_PATTERN, (marker)=>{
1624
+ const indent = indentByMarker.get(marker);
1625
+ if (block && indent) applyParagraphIndent(block, indent);
1626
+ return '';
1627
+ });
1628
+ }
1629
+ document.body.normalize();
1630
+ }
1631
+ function hasImportedDocxParagraphIndentMarkers(markers) {
1632
+ return markers.paragraphs.length > 0;
1633
+ }
1634
+ function paragraphIndent(propertySources) {
1635
+ let left;
1636
+ let right;
1637
+ let firstLine;
1638
+ for (const properties of propertySources){
1639
+ const indent = directChild(properties, 'ind');
1640
+ if (!indent) continue;
1641
+ const sourceLeft = work_docx_paragraph_indent_import_numericAttribute(indent, 'start') ?? work_docx_paragraph_indent_import_numericAttribute(indent, 'left');
1642
+ const sourceRight = work_docx_paragraph_indent_import_numericAttribute(indent, 'end') ?? work_docx_paragraph_indent_import_numericAttribute(indent, 'right');
1643
+ const sourceFirstLine = work_docx_paragraph_indent_import_numericAttribute(indent, 'firstLine');
1644
+ const sourceHanging = work_docx_paragraph_indent_import_numericAttribute(indent, 'hanging');
1645
+ if (void 0 !== sourceLeft) left = sourceLeft;
1646
+ if (void 0 !== sourceRight) right = sourceRight;
1647
+ if (void 0 !== sourceFirstLine) firstLine = sourceFirstLine;
1648
+ else if (void 0 !== sourceHanging) firstLine = -sourceHanging;
1649
+ }
1650
+ return normalizeDocumentParagraphIndent({
1651
+ left: twipsToPixels(left),
1652
+ right: twipsToPixels(right),
1653
+ firstLine: twipsToPixels(firstLine)
1654
+ });
1655
+ }
1656
+ function work_docx_paragraph_indent_import_insertParagraphMarker(document, paragraph, properties, marker) {
1657
+ const run = document.createElementNS(work_docx_paragraph_indent_import_WORD_NAMESPACE, 'w:r');
1658
+ const text = document.createElementNS(work_docx_paragraph_indent_import_WORD_NAMESPACE, 'w:t');
1659
+ text.setAttributeNS(work_docx_paragraph_indent_import_XML_NAMESPACE, 'xml:space', 'preserve');
1660
+ text.textContent = marker;
1661
+ run.append(text);
1662
+ paragraph.insertBefore(run, properties.nextSibling);
1663
+ }
1664
+ function work_docx_paragraph_indent_import_insertParagraphProperties(document, paragraph) {
1665
+ const properties = document.createElementNS(work_docx_paragraph_indent_import_WORD_NAMESPACE, 'w:pPr');
1666
+ paragraph.insertBefore(properties, paragraph.firstChild);
1667
+ return properties;
1668
+ }
1669
+ function work_docx_paragraph_indent_import_closestParagraphBlock(element) {
1670
+ const block = element?.closest('p, h1, h2, h3, h4, h5, h6, blockquote');
1671
+ return block instanceof HTMLElement ? block : null;
1672
+ }
1673
+ function applyParagraphIndent(element, value) {
1674
+ const indent = normalizeDocumentParagraphIndent(value);
1675
+ if (indent.left) {
1676
+ element.dataset.officeIndentLevel = work_docx_paragraph_indent_import_formatNumber(indent.left / 24);
1677
+ element.style.marginLeft = `${work_docx_paragraph_indent_import_formatNumber(indent.left)}px`;
1678
+ }
1679
+ if (indent.right) {
1680
+ element.dataset.officeIndentRight = work_docx_paragraph_indent_import_formatNumber(indent.right);
1681
+ element.style.marginRight = `${work_docx_paragraph_indent_import_formatNumber(indent.right)}px`;
1682
+ }
1683
+ if (indent.firstLine) {
1684
+ element.dataset.officeIndentFirstLine = work_docx_paragraph_indent_import_formatNumber(indent.firstLine);
1685
+ element.style.textIndent = `${work_docx_paragraph_indent_import_formatNumber(indent.firstLine)}px`;
1686
+ }
1687
+ }
1688
+ function work_docx_paragraph_indent_import_numericAttribute(element, name) {
1689
+ const raw = attribute(element, name) ?? attribute(element, `w:${name}`);
1690
+ if (null === raw || !raw.trim()) return;
1691
+ const value = Number(raw);
1692
+ return Number.isFinite(value) ? value : void 0;
1693
+ }
1694
+ function twipsToPixels(value) {
1695
+ if (void 0 === value) return 0;
1696
+ return Math.round(value / TWIPS_PER_CSS_PIXEL);
1697
+ }
1698
+ function work_docx_paragraph_indent_import_formatNumber(value) {
1699
+ return Number(value.toFixed(2)).toString();
1700
+ }
1701
+ function work_docx_paragraph_indent_import_textNodes(root) {
1702
+ const document = root.ownerDocument;
1703
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
1704
+ const nodes = [];
1705
+ if (!walker) return nodes;
1706
+ while(walker.nextNode())nodes.push(walker.currentNode);
1707
+ return nodes;
1708
+ }
1709
+ const work_docx_paragraph_pagination_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
1710
+ const work_docx_paragraph_pagination_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
1711
+ const PARAGRAPH_PAGINATION_MARKER_PATTERN = /__A3S_WORK_PARAGRAPH_PAGINATION_\d+__/g;
1712
+ function markDocxParagraphPagination(document, styleSource) {
1713
+ const paragraphs = [];
1714
+ const styles = resolveDocxParagraphStyleResolver(styleSource);
1715
+ for (const paragraph of descendants(document, 'p')){
1716
+ let properties = directChild(paragraph, 'pPr');
1717
+ if (properties && directChild(properties, 'numPr')) continue;
1718
+ const pagination = paragraphPagination(docxParagraphPropertySources(properties, styles));
1719
+ if (!Object.keys(pagination).length) continue;
1720
+ properties ??= work_docx_paragraph_pagination_import_insertParagraphProperties(document, paragraph);
1721
+ const marker = `__A3S_WORK_PARAGRAPH_PAGINATION_${paragraphs.length + 1}__`;
1722
+ work_docx_paragraph_pagination_import_insertParagraphMarker(document, paragraph, properties, marker);
1723
+ paragraphs.push({
1724
+ marker,
1725
+ pagination
1726
+ });
1727
+ }
1728
+ return {
1729
+ paragraphs
1730
+ };
1731
+ }
1732
+ function applyImportedDocxParagraphPaginationMarkers(document, markers) {
1733
+ const paginationByMarker = new Map(markers.paragraphs.map(({ marker, pagination })=>[
1734
+ marker,
1735
+ pagination
1736
+ ]));
1737
+ for (const node of work_docx_paragraph_pagination_import_textNodes(document.body)){
1738
+ if (!node.data.includes('__A3S_WORK_PARAGRAPH_PAGINATION_')) continue;
1739
+ const block = work_docx_paragraph_pagination_import_closestParagraphBlock(node.parentElement);
1740
+ node.data = node.data.replace(PARAGRAPH_PAGINATION_MARKER_PATTERN, (marker)=>{
1741
+ const pagination = paginationByMarker.get(marker);
1742
+ if (block && pagination) applyParagraphPagination(block, pagination);
1743
+ return '';
1744
+ });
1745
+ }
1746
+ document.body.normalize();
1747
+ }
1748
+ function hasImportedDocxParagraphPaginationMarkers(markers) {
1749
+ return markers.paragraphs.length > 0;
1750
+ }
1751
+ function paragraphPagination(sources) {
1752
+ const pagination = {};
1753
+ for (const properties of sources){
1754
+ const keepLines = directChild(properties, 'keepLines');
1755
+ const keepWithNext = directChild(properties, 'keepNext');
1756
+ const pageBreakBefore = directChild(properties, 'pageBreakBefore');
1757
+ const widowControl = directChild(properties, 'widowControl');
1758
+ if (keepLines) pagination.keepLines = work_docx_paragraph_pagination_import_onOffValue(keepLines);
1759
+ if (keepWithNext) pagination.keepWithNext = work_docx_paragraph_pagination_import_onOffValue(keepWithNext);
1760
+ if (pageBreakBefore) pagination.pageBreakBefore = work_docx_paragraph_pagination_import_onOffValue(pageBreakBefore);
1761
+ if (widowControl) pagination.widowControl = work_docx_paragraph_pagination_import_onOffValue(widowControl);
1762
+ }
1763
+ return pagination;
1764
+ }
1765
+ function work_docx_paragraph_pagination_import_onOffValue(element) {
1766
+ const value = (attribute(element, 'val') ?? attribute(element, 'w:val'))?.trim().toLowerCase();
1767
+ return '0' !== value && 'false' !== value && 'off' !== value;
1768
+ }
1769
+ function work_docx_paragraph_pagination_import_insertParagraphMarker(document, paragraph, properties, marker) {
1770
+ const run = document.createElementNS(work_docx_paragraph_pagination_import_WORD_NAMESPACE, 'w:r');
1771
+ const text = document.createElementNS(work_docx_paragraph_pagination_import_WORD_NAMESPACE, 'w:t');
1772
+ text.setAttributeNS(work_docx_paragraph_pagination_import_XML_NAMESPACE, 'xml:space', 'preserve');
1773
+ text.textContent = marker;
1774
+ run.append(text);
1775
+ paragraph.insertBefore(run, properties.nextSibling);
1776
+ }
1777
+ function work_docx_paragraph_pagination_import_insertParagraphProperties(document, paragraph) {
1778
+ const properties = document.createElementNS(work_docx_paragraph_pagination_import_WORD_NAMESPACE, 'w:pPr');
1779
+ paragraph.insertBefore(properties, paragraph.firstChild);
1780
+ return properties;
1781
+ }
1782
+ function work_docx_paragraph_pagination_import_closestParagraphBlock(element) {
1783
+ const block = element?.closest('p, h1, h2, h3, h4, h5, h6, blockquote');
1784
+ return block instanceof HTMLElement ? block : null;
1785
+ }
1786
+ function applyParagraphPagination(element, pagination) {
1787
+ setBooleanAttribute(element, 'data-office-keep-lines', pagination.keepLines);
1788
+ setBooleanAttribute(element, 'data-office-keep-with-next', pagination.keepWithNext);
1789
+ setBooleanAttribute(element, 'data-office-page-break-before', pagination.pageBreakBefore);
1790
+ setBooleanAttribute(element, 'data-office-widow-control', pagination.widowControl);
1791
+ }
1792
+ function setBooleanAttribute(element, name, value) {
1793
+ if (void 0 !== value) element.setAttribute(name, String(value));
1794
+ }
1795
+ function work_docx_paragraph_pagination_import_textNodes(root) {
1796
+ const document = root.ownerDocument;
1797
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
1798
+ const nodes = [];
1799
+ if (!walker) return nodes;
1800
+ while(walker.nextNode())nodes.push(walker.currentNode);
1801
+ return nodes;
1802
+ }
1803
+ const work_docx_paragraph_spacing_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
1804
+ const work_docx_paragraph_spacing_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
1805
+ const PARAGRAPH_SPACING_MARKER_PATTERN = /__A3S_WORK_PARAGRAPH_SPACING_\d+__/g;
1806
+ function markDocxParagraphSpacing(document, styleSource) {
1807
+ const paragraphs = [];
1808
+ const styles = resolveDocxParagraphStyleResolver(styleSource);
1809
+ for (const paragraph of descendants(document, 'p')){
1810
+ let properties = directChild(paragraph, 'pPr');
1811
+ const sources = docxParagraphPropertySources(properties, styles);
1812
+ if (sources.some((source)=>directChild(source, 'numPr'))) continue;
1813
+ const spacing = paragraphSpacing(sources);
1814
+ if (!Object.keys(spacing).length) continue;
1815
+ properties ??= work_docx_paragraph_spacing_import_insertParagraphProperties(document, paragraph);
1816
+ const marker = `__A3S_WORK_PARAGRAPH_SPACING_${paragraphs.length + 1}__`;
1817
+ work_docx_paragraph_spacing_import_insertParagraphMarker(document, paragraph, properties, marker);
1818
+ paragraphs.push({
1819
+ marker,
1820
+ spacing
1821
+ });
1822
+ }
1823
+ return {
1824
+ paragraphs
1825
+ };
1826
+ }
1827
+ function applyImportedDocxParagraphSpacingMarkers(document, markers) {
1828
+ const spacingByMarker = new Map(markers.paragraphs.map(({ marker, spacing })=>[
1829
+ marker,
1830
+ spacing
1831
+ ]));
1832
+ for (const node of work_docx_paragraph_spacing_import_textNodes(document.body)){
1833
+ if (!node.data.includes('__A3S_WORK_PARAGRAPH_SPACING_')) continue;
1834
+ const block = work_docx_paragraph_spacing_import_closestParagraphBlock(node.parentElement);
1835
+ node.data = node.data.replace(PARAGRAPH_SPACING_MARKER_PATTERN, (marker)=>{
1836
+ const spacing = spacingByMarker.get(marker);
1837
+ if (block && spacing) applyParagraphSpacing(block, spacing);
1838
+ return '';
1839
+ });
1840
+ }
1841
+ document.body.normalize();
1842
+ }
1843
+ function hasImportedDocxParagraphSpacingMarkers(markers) {
1844
+ return markers.paragraphs.length > 0;
1845
+ }
1846
+ function paragraphSpacing(propertySources) {
1847
+ let before;
1848
+ let after;
1849
+ let line;
1850
+ let lineRule;
1851
+ for (const properties of propertySources){
1852
+ const spacing = directChild(properties, 'spacing');
1853
+ if (!spacing) continue;
1854
+ const sourceBefore = work_docx_paragraph_spacing_import_numericAttribute(spacing, 'before');
1855
+ const sourceAfter = work_docx_paragraph_spacing_import_numericAttribute(spacing, 'after');
1856
+ const sourceLine = work_docx_paragraph_spacing_import_numericAttribute(spacing, 'line');
1857
+ const sourceLineRule = normalizedLineRule(work_docx_paragraph_spacing_import_wordAttribute(spacing, 'lineRule'));
1858
+ if (void 0 !== sourceBefore) before = sourceBefore;
1859
+ if (void 0 !== sourceAfter) after = sourceAfter;
1860
+ if (void 0 !== sourceLine) {
1861
+ line = sourceLine;
1862
+ lineRule = sourceLineRule ?? 'auto';
1863
+ } else if (sourceLineRule) lineRule = sourceLineRule;
1864
+ }
1865
+ const result = {};
1866
+ if (void 0 !== before) result.before = twipsToPoints(before);
1867
+ if (void 0 !== after) result.after = twipsToPoints(after);
1868
+ if (void 0 !== line) {
1869
+ const rule = lineRule ?? 'auto';
1870
+ result.lineHeight = 'auto' === rule ? work_docx_paragraph_spacing_import_formatNumber(line / 240) : `${work_docx_paragraph_spacing_import_formatNumber(line / 20)}pt`;
1871
+ result.lineRule = rule;
1872
+ }
1873
+ return result;
1874
+ }
1875
+ function applyParagraphSpacing(element, spacing) {
1876
+ if (void 0 !== spacing.before && null !== spacing.before) {
1877
+ const value = work_docx_paragraph_spacing_import_formatNumber(spacing.before);
1878
+ element.dataset.officeSpaceBefore = value;
1879
+ element.style.marginTop = `${value}pt`;
1880
+ }
1881
+ if (void 0 !== spacing.after && null !== spacing.after) {
1882
+ const value = work_docx_paragraph_spacing_import_formatNumber(spacing.after);
1883
+ element.dataset.officeSpaceAfter = value;
1884
+ element.style.marginBottom = `${value}pt`;
1885
+ }
1886
+ if (spacing.lineHeight) element.style.lineHeight = spacing.lineHeight;
1887
+ if (spacing.lineRule) element.dataset.officeLineRule = spacing.lineRule;
1888
+ }
1889
+ function work_docx_paragraph_spacing_import_insertParagraphMarker(document, paragraph, properties, marker) {
1890
+ const run = document.createElementNS(work_docx_paragraph_spacing_import_WORD_NAMESPACE, 'w:r');
1891
+ const text = document.createElementNS(work_docx_paragraph_spacing_import_WORD_NAMESPACE, 'w:t');
1892
+ text.setAttributeNS(work_docx_paragraph_spacing_import_XML_NAMESPACE, 'xml:space', 'preserve');
1893
+ text.textContent = marker;
1894
+ run.append(text);
1895
+ paragraph.insertBefore(run, properties.nextSibling);
1896
+ }
1897
+ function work_docx_paragraph_spacing_import_insertParagraphProperties(document, paragraph) {
1898
+ const properties = document.createElementNS(work_docx_paragraph_spacing_import_WORD_NAMESPACE, 'w:pPr');
1899
+ paragraph.insertBefore(properties, paragraph.firstChild);
1900
+ return properties;
1901
+ }
1902
+ function work_docx_paragraph_spacing_import_closestParagraphBlock(element) {
1903
+ const block = element?.closest('p, h1, h2, h3, h4, h5, h6, blockquote');
1904
+ return block instanceof HTMLElement ? block : null;
1905
+ }
1906
+ function work_docx_paragraph_spacing_import_numericAttribute(element, name) {
1907
+ const raw = work_docx_paragraph_spacing_import_wordAttribute(element, name);
1908
+ if (null === raw || !raw.trim()) return;
1909
+ const value = Number(raw);
1910
+ return Number.isFinite(value) ? value : void 0;
1911
+ }
1912
+ function work_docx_paragraph_spacing_import_wordAttribute(element, name) {
1913
+ return attribute(element, name) ?? attribute(element, `w:${name}`);
1914
+ }
1915
+ function normalizedLineRule(value) {
1916
+ if ('auto' === value || 'atLeast' === value) return value;
1917
+ if ('exact' === value || 'exactly' === value) return 'exact';
1918
+ }
1919
+ function twipsToPoints(value) {
1920
+ return Number((value / 20).toFixed(2));
1921
+ }
1922
+ function work_docx_paragraph_spacing_import_formatNumber(value) {
1923
+ return Number(value.toFixed(3)).toString();
1924
+ }
1925
+ function work_docx_paragraph_spacing_import_textNodes(root) {
1926
+ const document = root.ownerDocument;
1927
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
1928
+ const nodes = [];
1929
+ if (!walker) return nodes;
1930
+ while(walker.nextNode())nodes.push(walker.currentNode);
1931
+ return nodes;
1932
+ }
1933
+ function createDocxThemeResolver(themeDocument) {
1934
+ if (!themeDocument) return {
1935
+ colors: new Map(),
1936
+ fonts: new Map()
1937
+ };
1938
+ const fonts = new Map();
1939
+ const fontScheme = firstDescendant(themeDocument, 'fontScheme');
1940
+ addThemeFontFamily(fonts, 'major', fontScheme ? directChild(fontScheme, 'majorFont') : void 0);
1941
+ addThemeFontFamily(fonts, 'minor', fontScheme ? directChild(fontScheme, 'minorFont') : void 0);
1942
+ const colors = new Map();
1943
+ const colorScheme = firstDescendant(themeDocument, 'clrScheme');
1944
+ if (colorScheme) for (const entry of directChildren(colorScheme)){
1945
+ const color = themeColorValue(directChildren(entry)[0]);
1946
+ if (color) colors.set(entry.localName.toLowerCase(), color);
1947
+ }
1948
+ return {
1949
+ colors,
1950
+ fonts
1951
+ };
1952
+ }
1953
+ function resolveDocxThemeResolver(source) {
1954
+ return isDocxThemeResolver(source) ? source : createDocxThemeResolver(source);
1955
+ }
1956
+ function docxThemeFont(resolver, key) {
1957
+ return key ? resolver.fonts.get(key.trim().toLowerCase()) : void 0;
1958
+ }
1959
+ function docxThemeColor(resolver, key, tint, shade) {
1960
+ const color = key ? resolver.colors.get(key.trim().toLowerCase()) : void 0;
1961
+ if (!color) return;
1962
+ const channels = [
1963
+ Number.parseInt(color.slice(0, 2), 16),
1964
+ Number.parseInt(color.slice(2, 4), 16),
1965
+ Number.parseInt(color.slice(4, 6), 16)
1966
+ ];
1967
+ const shadeFactor = hexFactor(shade);
1968
+ const tintFactor = hexFactor(tint);
1969
+ const transformed = channels.map((channel)=>{
1970
+ const shaded = void 0 === shadeFactor ? channel : channel * shadeFactor;
1971
+ const tinted = void 0 === tintFactor ? shaded : shaded + (255 - shaded) * tintFactor;
1972
+ return Math.max(0, Math.min(255, Math.round(tinted)));
1973
+ });
1974
+ return transformed.map((channel)=>channel.toString(16).padStart(2, '0')).join('');
1975
+ }
1976
+ function addThemeFontFamily(fonts, prefix, family) {
1977
+ if (!family) return;
1978
+ const latin = typeface(directChild(family, 'latin'));
1979
+ const eastAsia = typeface(directChild(family, 'ea')) || scriptTypeface(family, [
1980
+ 'Hans',
1981
+ 'Hant',
1982
+ 'Jpan',
1983
+ 'Hang'
1984
+ ]) || latin;
1985
+ const complex = typeface(directChild(family, 'cs')) || latin;
1986
+ if (latin) {
1987
+ fonts.set(`${prefix}ascii`, latin);
1988
+ fonts.set(`${prefix}hansi`, latin);
1989
+ }
1990
+ if (eastAsia) fonts.set(`${prefix}eastasia`, eastAsia);
1991
+ if (complex) fonts.set(`${prefix}bidi`, complex);
1992
+ }
1993
+ function scriptTypeface(family, scripts) {
1994
+ const fonts = directChildren(family, 'font');
1995
+ for (const script of scripts){
1996
+ const font = fonts.find((candidate)=>drawingAttribute(candidate, "script") === script);
1997
+ const value = font ? typeface(font) : void 0;
1998
+ if (value) return value;
1999
+ }
2000
+ }
2001
+ function typeface(element) {
2002
+ const value = element ? drawingAttribute(element, 'typeface')?.trim() : void 0;
2003
+ return value || void 0;
2004
+ }
2005
+ function themeColorValue(element) {
2006
+ if (!element) return;
2007
+ const value = 'sysClr' === element.localName ? drawingAttribute(element, 'lastClr') : drawingAttribute(element, 'val');
2008
+ return value && /^[0-9a-f]{6}$/i.test(value) ? value.toLowerCase() : void 0;
2009
+ }
2010
+ function drawingAttribute(element, name) {
2011
+ return attribute(element, name) ?? attribute(element, `a:${name}`);
2012
+ }
2013
+ function hexFactor(value) {
2014
+ if (!value || !/^[0-9a-f]{2}$/i.test(value)) return;
2015
+ return Number.parseInt(value, 16) / 255;
2016
+ }
2017
+ function isDocxThemeResolver(source) {
2018
+ return Boolean(source && 'colors' in source && source.colors instanceof Map && 'fonts' in source && source.fonts instanceof Map);
2019
+ }
2020
+ const work_docx_run_formatting_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
2021
+ const work_docx_run_formatting_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
2022
+ const RUN_FORMATTING_MARKER_PATTERN = /__A3S_WORK_RUN_(?:START|END)_\d+__/g;
2023
+ function markDocxRunFormatting(document, styleSource, themeSource) {
2024
+ const runs = [];
2025
+ const styles = resolveDocxParagraphStyleResolver(styleSource);
2026
+ const theme = resolveDocxThemeResolver(themeSource);
2027
+ for (const run of descendants(document, 'r')){
2028
+ const runText = directRunText(run);
2029
+ if (!runText || runText.includes('__A3S_')) continue;
2030
+ const paragraph = work_docx_run_formatting_import_closestAncestor(run, 'p');
2031
+ if (!paragraph) continue;
2032
+ const paragraphProperties = directChild(paragraph, 'pPr');
2033
+ const runProperties = directChild(run, 'rPr');
2034
+ const formatting = resolvedRunFormatting(docxRunPropertySources(paragraphProperties, runProperties, styles), theme);
2035
+ if (!Object.keys(formatting).length) continue;
2036
+ const index = runs.length + 1;
2037
+ const startMarker = `__A3S_WORK_RUN_START_${index}__`;
2038
+ const endMarker = `__A3S_WORK_RUN_END_${index}__`;
2039
+ insertRunMarkers(document, run, runProperties, startMarker, endMarker);
2040
+ runs.push({
2041
+ startMarker,
2042
+ endMarker,
2043
+ formatting
2044
+ });
2045
+ }
2046
+ return {
2047
+ runs
2048
+ };
2049
+ }
2050
+ function applyImportedDocxRunFormattingMarkers(document, markers) {
2051
+ const replacements = new Map();
2052
+ for (const marker of markers.runs){
2053
+ replacements.set(marker.startMarker, formattingSpanStart(document, marker.formatting));
2054
+ replacements.set(marker.endMarker, '</span>');
2055
+ }
2056
+ document.body.innerHTML = document.body.innerHTML.replace(RUN_FORMATTING_MARKER_PATTERN, (marker)=>replacements.get(marker) ?? '');
2057
+ }
2058
+ function hasImportedDocxRunFormattingMarkers(markers) {
2059
+ return markers.runs.length > 0;
2060
+ }
2061
+ function resolvedRunFormatting(propertySources, theme) {
2062
+ const fonts = {};
2063
+ let fontSize;
2064
+ let color;
2065
+ let backgroundColor;
2066
+ for (const properties of propertySources){
2067
+ const runFonts = directChild(properties, 'rFonts');
2068
+ if (runFonts) {
2069
+ assignFont(fonts, 'ascii', resolvedFont(runFonts, 'ascii', 'asciiTheme', theme));
2070
+ assignFont(fonts, 'hAnsi', resolvedFont(runFonts, 'hAnsi', 'hAnsiTheme', theme));
2071
+ assignFont(fonts, 'eastAsia', resolvedFont(runFonts, 'eastAsia', 'eastAsiaTheme', theme));
2072
+ assignFont(fonts, 'complex', resolvedFont(runFonts, 'cs', 'cstheme', theme));
2073
+ }
2074
+ const size = work_docx_run_formatting_import_numericAttribute(directChild(properties, 'sz'), 'val');
2075
+ if (void 0 !== size && size > 0) fontSize = Math.min(512, size / 2);
2076
+ const colorElement = directChild(properties, 'color');
2077
+ if (colorElement) {
2078
+ const value = work_docx_run_formatting_import_wordAttribute(colorElement, 'val')?.trim();
2079
+ const themed = docxThemeColor(theme, work_docx_run_formatting_import_wordAttribute(colorElement, 'themeColor'), work_docx_run_formatting_import_wordAttribute(colorElement, 'themeTint'), work_docx_run_formatting_import_wordAttribute(colorElement, 'themeShade'));
2080
+ if (themed) color = `#${themed}`;
2081
+ else if (value?.toLowerCase() === 'auto') color = 'inherit';
2082
+ else if (value && /^[0-9a-f]{6}$/i.test(value)) color = `#${value.toLowerCase()}`;
2083
+ }
2084
+ const highlight = directChild(properties, 'highlight');
2085
+ if (highlight) {
2086
+ const value = work_docx_run_formatting_import_wordAttribute(highlight, 'val')?.trim().toLowerCase();
2087
+ if (value) backgroundColor = wordHighlightColor(value);
2088
+ } else {
2089
+ const shading = directChild(properties, 'shd');
2090
+ const fill = shading ? work_docx_run_formatting_import_wordAttribute(shading, 'fill')?.trim() : void 0;
2091
+ const themed = shading ? docxThemeColor(theme, work_docx_run_formatting_import_wordAttribute(shading, 'themeFill'), work_docx_run_formatting_import_wordAttribute(shading, 'themeFillTint'), work_docx_run_formatting_import_wordAttribute(shading, 'themeFillShade')) : void 0;
2092
+ if (themed) backgroundColor = `#${themed}`;
2093
+ else if (fill?.toLowerCase() === 'auto') backgroundColor = 'transparent';
2094
+ else if (fill && /^[0-9a-f]{6}$/i.test(fill)) backgroundColor = `#${fill.toLowerCase()}`;
2095
+ }
2096
+ }
2097
+ const fontFamily = uniqueFonts([
2098
+ fonts.eastAsia,
2099
+ fonts.hAnsi,
2100
+ fonts.ascii,
2101
+ fonts.complex
2102
+ ]);
2103
+ return {
2104
+ ...fontFamily ? {
2105
+ fontFamily
2106
+ } : {},
2107
+ ...void 0 !== fontSize ? {
2108
+ fontSize
2109
+ } : {},
2110
+ ...color ? {
2111
+ color
2112
+ } : {},
2113
+ ...backgroundColor ? {
2114
+ backgroundColor
2115
+ } : {}
2116
+ };
2117
+ }
2118
+ function insertRunMarkers(document, run, properties, startMarker, endMarker) {
2119
+ const start = work_docx_run_formatting_import_markerText(document, startMarker);
2120
+ const end = work_docx_run_formatting_import_markerText(document, endMarker);
2121
+ run.insertBefore(start, properties?.nextSibling ?? run.firstChild);
2122
+ run.append(end);
2123
+ }
2124
+ function work_docx_run_formatting_import_markerText(document, marker) {
2125
+ const text = document.createElementNS(work_docx_run_formatting_import_WORD_NAMESPACE, 'w:t');
2126
+ text.setAttributeNS(work_docx_run_formatting_import_XML_NAMESPACE, 'xml:space', 'preserve');
2127
+ text.textContent = marker;
2128
+ return text;
2129
+ }
2130
+ function formattingSpanStart(document, formatting) {
2131
+ const span = document.createElement('span');
2132
+ if (formatting.fontFamily) span.style.fontFamily = formatting.fontFamily;
2133
+ if (void 0 !== formatting.fontSize) span.style.fontSize = `${work_docx_run_formatting_import_formatNumber(formatting.fontSize)}pt`;
2134
+ if (formatting.color) span.style.color = formatting.color;
2135
+ if (formatting.backgroundColor) span.style.backgroundColor = formatting.backgroundColor;
2136
+ const html = span.outerHTML;
2137
+ return html.slice(0, html.indexOf('>') + 1);
2138
+ }
2139
+ function directRunText(run) {
2140
+ return Array.from(run.children).filter((child)=>'t' === child.localName || 'delText' === child.localName).map((child)=>child.textContent ?? '').join('');
2141
+ }
2142
+ function work_docx_run_formatting_import_closestAncestor(element, localName) {
2143
+ let current = element.parentElement;
2144
+ while(current){
2145
+ if (current.localName === localName) return current;
2146
+ current = current.parentElement;
2147
+ }
2148
+ return null;
2149
+ }
2150
+ function assignFont(fonts, key, value) {
2151
+ const normalized = value?.trim();
2152
+ if (normalized) fonts[key] = normalized;
2153
+ }
2154
+ function resolvedFont(element, explicitName, themeName, theme) {
2155
+ const explicit = work_docx_run_formatting_import_wordAttribute(element, explicitName);
2156
+ if (explicit?.trim()) return explicit;
2157
+ return docxThemeFont(theme, work_docx_run_formatting_import_wordAttribute(element, themeName)) ?? null;
2158
+ }
2159
+ function uniqueFonts(values) {
2160
+ const fonts = [
2161
+ ...new Set(values.filter((value)=>!!value))
2162
+ ];
2163
+ return fonts.length ? fonts.map(cssFontFamily).join(', ') : void 0;
2164
+ }
2165
+ function cssFontFamily(value) {
2166
+ return /[\s"',]/.test(value) ? `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"` : value;
2167
+ }
2168
+ function work_docx_run_formatting_import_numericAttribute(element, name) {
2169
+ if (!element) return;
2170
+ const raw = work_docx_run_formatting_import_wordAttribute(element, name);
2171
+ if (null === raw || !raw.trim()) return;
2172
+ const value = Number(raw);
2173
+ return Number.isFinite(value) ? value : void 0;
2174
+ }
2175
+ function work_docx_run_formatting_import_wordAttribute(element, name) {
2176
+ return attribute(element, name) ?? attribute(element, `w:${name}`);
2177
+ }
2178
+ function wordHighlightColor(value) {
2179
+ const colors = {
2180
+ black: '#000000',
2181
+ blue: '#0000ff',
2182
+ cyan: '#00ffff',
2183
+ darkblue: '#000080',
2184
+ darkcyan: '#008080',
2185
+ darkgray: '#808080',
2186
+ darkgreen: '#008000',
2187
+ darkmagenta: '#800080',
2188
+ darkred: '#800000',
2189
+ darkyellow: '#808000',
2190
+ green: '#00ff00',
2191
+ lightgray: '#c0c0c0',
2192
+ magenta: '#ff00ff',
2193
+ none: 'transparent',
2194
+ red: '#ff0000',
2195
+ white: '#ffffff',
2196
+ yellow: '#ffff00'
2197
+ };
2198
+ return colors[value] ?? 'transparent';
2199
+ }
2200
+ function work_docx_run_formatting_import_formatNumber(value) {
2201
+ return Number(value.toFixed(2)).toString();
2202
+ }
2203
+ const work_docx_tab_stop_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
2204
+ const work_docx_tab_stop_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
2205
+ const work_docx_tab_stop_import_TWIPS_PER_CSS_PIXEL = 15;
2206
+ const PARAGRAPH_TAB_STOP_MARKER_PATTERN = /__A3S_WORK_PARAGRAPH_TAB_STOPS_\d+__/g;
2207
+ const INLINE_TAB_MARKER_PATTERN = /__A3S_WORK_INLINE_TAB_\d+__/g;
2208
+ function markDocxParagraphTabStops(document, styleSource) {
2209
+ const paragraphs = [];
2210
+ const inlineTabs = [];
2211
+ const styles = resolveDocxParagraphStyleResolver(styleSource);
2212
+ for (const paragraph of descendants(document, 'p')){
2213
+ let properties = directChild(paragraph, 'pPr');
2214
+ const tabStops = resolvedParagraphTabStops(docxParagraphPropertySources(properties, styles));
2215
+ if (tabStops.length) {
2216
+ properties ??= work_docx_tab_stop_import_insertParagraphProperties(document, paragraph);
2217
+ const marker = `__A3S_WORK_PARAGRAPH_TAB_STOPS_${paragraphs.length + 1}__`;
2218
+ work_docx_tab_stop_import_insertParagraphMarker(document, paragraph, properties, marker);
2219
+ paragraphs.push({
2220
+ marker,
2221
+ tabStops
2222
+ });
2223
+ }
2224
+ for (const tab of inlineRunTabs(paragraph)){
2225
+ const marker = `__A3S_WORK_INLINE_TAB_${inlineTabs.length + 1}__`;
2226
+ const text = document.createElementNS(work_docx_tab_stop_import_WORD_NAMESPACE, 'w:t');
2227
+ text.setAttributeNS(work_docx_tab_stop_import_XML_NAMESPACE, 'xml:space', 'preserve');
2228
+ text.textContent = marker;
2229
+ tab.replaceWith(text);
2230
+ inlineTabs.push(marker);
2231
+ }
2232
+ }
2233
+ return {
2234
+ paragraphs,
2235
+ inlineTabs
2236
+ };
2237
+ }
2238
+ function applyImportedDocxParagraphTabStopMarkers(document, markers) {
2239
+ const tabStopsByMarker = new Map(markers.paragraphs.map(({ marker, tabStops })=>[
2240
+ marker,
2241
+ tabStops
2242
+ ]));
2243
+ for (const node of work_docx_tab_stop_import_textNodes(document.body)){
2244
+ if (!node.data.includes('__A3S_WORK_PARAGRAPH_TAB_STOPS_')) continue;
2245
+ const block = work_docx_tab_stop_import_closestParagraphBlock(node.parentElement);
2246
+ node.data = node.data.replace(PARAGRAPH_TAB_STOP_MARKER_PATTERN, (marker)=>{
2247
+ const tabStops = tabStopsByMarker.get(marker);
2248
+ if (block && tabStops?.length) block.dataset.officeTabStops = serializeDocumentTabStops(tabStops);
2249
+ return '';
2250
+ });
2251
+ }
2252
+ const inlineMarkers = new Set(markers.inlineTabs);
2253
+ for (const node of work_docx_tab_stop_import_textNodes(document.body))if (node.data.includes('__A3S_WORK_INLINE_TAB_')) replaceInlineTabMarkers(node, inlineMarkers);
2254
+ document.body.normalize();
2255
+ }
2256
+ function hasImportedDocxParagraphTabStopMarkers(markers) {
2257
+ return markers.paragraphs.length > 0 || markers.inlineTabs.length > 0;
2258
+ }
2259
+ function resolvedParagraphTabStops(sources) {
2260
+ const byPosition = new Map();
2261
+ for (const properties of sources){
2262
+ const tabs = directChild(properties, 'tabs');
2263
+ if (tabs) for (const tab of directChildren(tabs, 'tab')){
2264
+ const positionTwips = work_docx_tab_stop_import_numericAttribute(tab, 'pos');
2265
+ if (void 0 === positionTwips || positionTwips <= 0) continue;
2266
+ const position = positionTwips / work_docx_tab_stop_import_TWIPS_PER_CSS_PIXEL;
2267
+ const value = work_docx_tab_stop_import_wordAttribute(tab, 'val')?.trim();
2268
+ if ('clear' === value || 'bar' === value) {
2269
+ byPosition.delete(position);
2270
+ continue;
2271
+ }
2272
+ byPosition.set(position, {
2273
+ position,
2274
+ alignment: docxTabAlignment(value),
2275
+ leader: docxTabLeader(work_docx_tab_stop_import_wordAttribute(tab, 'leader'))
2276
+ });
2277
+ }
2278
+ }
2279
+ return normalizeDocumentTabStops(Array.from(byPosition.values()));
2280
+ }
2281
+ function inlineRunTabs(paragraph) {
2282
+ return descendants(paragraph, 'tab').filter((tab)=>{
2283
+ let parent = tab.parentElement;
2284
+ while(parent && parent !== paragraph){
2285
+ if ('tabs' === parent.localName) return false;
2286
+ parent = parent.parentElement;
2287
+ }
2288
+ return parent === paragraph;
2289
+ });
2290
+ }
2291
+ function replaceInlineTabMarkers(node, markers) {
2292
+ const matches = Array.from(node.data.matchAll(INLINE_TAB_MARKER_PATTERN));
2293
+ if (!matches.length) return;
2294
+ const fragment = node.ownerDocument.createDocumentFragment();
2295
+ let offset = 0;
2296
+ for (const match of matches){
2297
+ const marker = match[0];
2298
+ const index = match.index ?? 0;
2299
+ if (index > offset) fragment.append(node.data.slice(offset, index));
2300
+ if (markers.has(marker)) {
2301
+ const tab = node.ownerDocument.createElement('span');
2302
+ tab.dataset.documentTab = 'true';
2303
+ tab.className = 'work-document-tab';
2304
+ tab.setAttribute('role', 'separator');
2305
+ tab.setAttribute('aria-label', '制表符');
2306
+ fragment.append(tab);
2307
+ } else fragment.append(marker);
2308
+ offset = index + marker.length;
2309
+ }
2310
+ if (offset < node.data.length) fragment.append(node.data.slice(offset));
2311
+ node.replaceWith(fragment);
2312
+ }
2313
+ function work_docx_tab_stop_import_insertParagraphMarker(document, paragraph, properties, marker) {
2314
+ const run = document.createElementNS(work_docx_tab_stop_import_WORD_NAMESPACE, 'w:r');
2315
+ const text = document.createElementNS(work_docx_tab_stop_import_WORD_NAMESPACE, 'w:t');
2316
+ text.setAttributeNS(work_docx_tab_stop_import_XML_NAMESPACE, 'xml:space', 'preserve');
2317
+ text.textContent = marker;
2318
+ run.append(text);
2319
+ paragraph.insertBefore(run, properties.nextSibling);
2320
+ }
2321
+ function work_docx_tab_stop_import_insertParagraphProperties(document, paragraph) {
2322
+ const properties = document.createElementNS(work_docx_tab_stop_import_WORD_NAMESPACE, 'w:pPr');
2323
+ paragraph.insertBefore(properties, paragraph.firstChild);
2324
+ return properties;
2325
+ }
2326
+ function work_docx_tab_stop_import_closestParagraphBlock(element) {
2327
+ const block = element?.closest('p, h1, h2, h3, h4, h5, h6, blockquote');
2328
+ return block instanceof HTMLElement ? block : null;
2329
+ }
2330
+ function docxTabAlignment(value) {
2331
+ if ('center' === value) return 'center';
2332
+ if ('right' === value || 'end' === value) return 'right';
2333
+ if ('decimal' === value || 'num' === value) return 'decimal';
2334
+ return 'left';
2335
+ }
2336
+ function docxTabLeader(value) {
2337
+ if ('dot' === value) return 'dot';
2338
+ if ('hyphen' === value) return 'hyphen';
2339
+ if ('underscore' === value || 'heavy' === value) return 'underscore';
2340
+ if ('middleDot' === value) return 'middleDot';
2341
+ return 'none';
2342
+ }
2343
+ function work_docx_tab_stop_import_numericAttribute(element, name) {
2344
+ const raw = work_docx_tab_stop_import_wordAttribute(element, name);
2345
+ if (null === raw || !raw.trim()) return;
2346
+ const value = Number(raw);
2347
+ return Number.isFinite(value) ? value : void 0;
2348
+ }
2349
+ function work_docx_tab_stop_import_wordAttribute(element, name) {
2350
+ return attribute(element, name) ?? attribute(element, `w:${name}`);
2351
+ }
2352
+ function work_docx_tab_stop_import_textNodes(root) {
2353
+ const document = root.ownerDocument;
2354
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
2355
+ const nodes = [];
2356
+ if (!walker) return nodes;
2357
+ while(walker.nextNode())nodes.push(walker.currentNode);
2358
+ return nodes;
2359
+ }
2360
+ const work_docx_table_cell_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
2361
+ const work_docx_table_cell_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
2362
+ const TABLE_CELL_MARKER_PATTERN = /__A3S_WORK_TABLE_CELL_\d+__/g;
2363
+ function markDocxTableCells(document) {
2364
+ const cells = [];
2365
+ for (const cell of descendants(document, 'tc')){
2366
+ const properties = directChild(cell, 'tcPr');
2367
+ const shading = properties ? directChild(properties, 'shd') : void 0;
2368
+ const verticalAlignment = properties ? directChild(properties, 'vAlign') : void 0;
2369
+ const directBorders = properties ? uniformBorders(directChild(properties, 'tcBorders')) : null;
2370
+ const border = directBorders ?? uniformTableBorders(cell);
2371
+ const backgroundColor = ooxmlColor(attribute(shading ?? cell, 'fill'));
2372
+ const verticalAlign = tableVerticalAlign(attribute(verticalAlignment ?? cell, 'val'));
2373
+ if (!backgroundColor && !verticalAlign && !border) continue;
2374
+ const paragraph = firstTableCellParagraph(document, cell);
2375
+ if (!paragraph) continue;
2376
+ const marker = `__A3S_WORK_TABLE_CELL_${cells.length + 1}__`;
2377
+ insertCellMarker(document, paragraph, marker);
2378
+ cells.push({
2379
+ marker,
2380
+ ...backgroundColor ? {
2381
+ backgroundColor
2382
+ } : {},
2383
+ ...verticalAlign ? {
2384
+ verticalAlign
2385
+ } : {},
2386
+ ...border ? {
2387
+ borderColor: border.color,
2388
+ borderStyle: border.style,
2389
+ borderWidth: border.width
2390
+ } : {}
2391
+ });
2392
+ }
2393
+ return {
2394
+ cells
2395
+ };
2396
+ }
2397
+ function applyImportedDocxTableCellMarkers(document, markers) {
2398
+ const cellByMarker = new Map(markers.cells.map((cell)=>[
2399
+ cell.marker,
2400
+ cell
2401
+ ]));
2402
+ for (const node of work_docx_table_cell_import_textNodes(document.body)){
2403
+ if (!node.data.includes('__A3S_WORK_TABLE_CELL_')) continue;
2404
+ const cell = node.parentElement?.closest('td, th');
2405
+ node.data = node.data.replace(TABLE_CELL_MARKER_PATTERN, (marker)=>{
2406
+ const format = cellByMarker.get(marker);
2407
+ if (cell instanceof HTMLElement && format) applyCellFormat(cell, format);
2408
+ return '';
2409
+ });
2410
+ }
2411
+ document.body.normalize();
2412
+ }
2413
+ function hasImportedDocxTableCellMarkers(markers) {
2414
+ return markers.cells.length > 0;
2415
+ }
2416
+ function applyCellFormat(cell, format) {
2417
+ if (format.backgroundColor) {
2418
+ cell.dataset.officeCellFill = format.backgroundColor;
2419
+ cell.style.backgroundColor = format.backgroundColor;
2420
+ }
2421
+ if (format.verticalAlign) {
2422
+ cell.dataset.officeCellVerticalAlign = format.verticalAlign;
2423
+ cell.style.verticalAlign = format.verticalAlign;
2424
+ }
2425
+ if (format.borderColor && format.borderStyle && void 0 !== format.borderWidth) {
2426
+ cell.dataset.officeCellBorderColor = format.borderColor;
2427
+ cell.dataset.officeCellBorderStyle = format.borderStyle;
2428
+ cell.dataset.officeCellBorderWidth = String(format.borderWidth);
2429
+ cell.style.border = 'none' === format.borderStyle || 0 === format.borderWidth ? '0px none transparent' : `${format.borderWidth}px ${format.borderStyle} ${format.borderColor}`;
2430
+ }
2431
+ }
2432
+ function uniformTableBorders(cell) {
2433
+ const table = work_docx_table_cell_import_closestAncestor(cell, 'tbl');
2434
+ const properties = table ? directChild(table, 'tblPr') : void 0;
2435
+ return properties ? uniformBorders(directChild(properties, 'tblBorders'), true) : null;
2436
+ }
2437
+ function uniformBorders(borders, includeInside = false) {
2438
+ if (!borders) return null;
2439
+ const edgeNames = includeInside ? [
2440
+ 'top',
2441
+ 'right',
2442
+ 'bottom',
2443
+ 'left',
2444
+ 'insideH',
2445
+ 'insideV'
2446
+ ] : [
2447
+ 'top',
2448
+ 'right',
2449
+ 'bottom',
2450
+ 'left'
2451
+ ];
2452
+ const edgeElements = new Map(directChildren(borders).map((edge)=>[
2453
+ edge.localName,
2454
+ edge
2455
+ ]));
2456
+ const formats = edgeNames.map((name)=>parseBorder(edgeElements.get(name)));
2457
+ if (formats.some((format)=>!format)) return null;
2458
+ const first = formats[0];
2459
+ if (!first) return null;
2460
+ return formats.every((format)=>format?.color === first.color && format.style === first.style && format.width === first.width) ? first : null;
2461
+ }
2462
+ function parseBorder(edge) {
2463
+ if (!edge) return null;
2464
+ const style = tableBorderStyle(attribute(edge, 'val'));
2465
+ if (!style) return null;
2466
+ if ('none' === style) return {
2467
+ color: '#000000',
2468
+ style,
2469
+ width: 0
2470
+ };
2471
+ const color = ooxmlColor(attribute(edge, 'color')) ?? '#000000';
2472
+ const size = Number(attribute(edge, 'sz'));
2473
+ const width = Number.isFinite(size) && size > 0 ? size / 6 : 1;
2474
+ return {
2475
+ color,
2476
+ style,
2477
+ width: Math.max(0.5, Math.min(6, Math.round(2 * width) / 2))
2478
+ };
2479
+ }
2480
+ function tableBorderStyle(value) {
2481
+ const normalized = value?.trim();
2482
+ if (!normalized) return null;
2483
+ if ('nil' === normalized || 'none' === normalized) return 'none';
2484
+ if ('double' === normalized || 'triple' === normalized) return 'double';
2485
+ if ('dotted' === normalized) return 'dotted';
2486
+ if (/dash|dotDash|dotDotDash/i.test(normalized)) return 'dashed';
2487
+ return 'solid';
2488
+ }
2489
+ function tableVerticalAlign(value) {
2490
+ if ('center' === value) return 'middle';
2491
+ if ('top' === value || 'bottom' === value) return value;
2492
+ return null;
2493
+ }
2494
+ function ooxmlColor(value) {
2495
+ const normalized = value?.trim().replace(/^#/, '').toLowerCase();
2496
+ if (!normalized || 'auto' === normalized) return null;
2497
+ if (/^[0-9a-f]{3}$/.test(normalized)) return `#${normalized.split('').map((part)=>`${part}${part}`).join('')}`;
2498
+ return /^[0-9a-f]{6}$/.test(normalized) ? `#${normalized}` : null;
2499
+ }
2500
+ function firstTableCellParagraph(document, cell) {
2501
+ const existing = directChild(cell, 'p') ?? descendants(cell, 'p').find((paragraph)=>work_docx_table_cell_import_closestAncestor(paragraph, 'tc') === cell);
2502
+ if (existing) return existing;
2503
+ const paragraph = document.createElementNS(work_docx_table_cell_import_WORD_NAMESPACE, 'w:p');
2504
+ cell.append(paragraph);
2505
+ return paragraph;
2506
+ }
2507
+ function insertCellMarker(document, paragraph, marker) {
2508
+ const run = document.createElementNS(work_docx_table_cell_import_WORD_NAMESPACE, 'w:r');
2509
+ const text = document.createElementNS(work_docx_table_cell_import_WORD_NAMESPACE, 'w:t');
2510
+ text.setAttributeNS(work_docx_table_cell_import_XML_NAMESPACE, 'xml:space', 'preserve');
2511
+ text.textContent = marker;
2512
+ run.append(text);
2513
+ const properties = directChild(paragraph, 'pPr');
2514
+ paragraph.insertBefore(run, properties?.nextSibling ?? paragraph.firstChild);
2515
+ }
2516
+ function work_docx_table_cell_import_closestAncestor(element, localName) {
2517
+ let current = element;
2518
+ while(current){
2519
+ if (current.localName === localName) return current;
2520
+ current = current.parentElement;
2521
+ }
2522
+ return null;
2523
+ }
2524
+ function work_docx_table_cell_import_textNodes(root) {
2525
+ const document = root.ownerDocument;
2526
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
2527
+ const nodes = [];
2528
+ if (!walker) return nodes;
2529
+ while(walker.nextNode())nodes.push(walker.currentNode);
2530
+ return nodes;
2531
+ }
2532
+ const work_docx_table_row_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
2533
+ const work_docx_table_row_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
2534
+ const TABLE_ROW_MARKER_PATTERN = /__A3S_WORK_TABLE_ROW_\d+__/g;
2535
+ const PIXELS_PER_TWIP = 96 / 1440;
2536
+ function markDocxTableRows(document) {
2537
+ const rows = [];
2538
+ for (const row of descendants(document, 'tr')){
2539
+ const properties = directChild(row, 'trPr');
2540
+ const cantSplit = properties ? directChild(properties, 'cantSplit') : void 0;
2541
+ const repeatHeader = properties ? directChild(properties, 'tblHeader') : void 0;
2542
+ const height = properties ? directChild(properties, 'trHeight') : void 0;
2543
+ const rowHeight = height ? work_docx_table_row_import_twipsToPixels(Number(attribute(height, 'val'))) : null;
2544
+ const rowHeightRule = tableRowHeightRule(attribute(height ?? row, 'hRule'));
2545
+ if (!cantSplit && !repeatHeader && null === rowHeight) continue;
2546
+ const paragraph = firstTableRowParagraph(document, row);
2547
+ if (!paragraph) continue;
2548
+ const marker = `__A3S_WORK_TABLE_ROW_${rows.length + 1}__`;
2549
+ insertRowMarker(document, paragraph, marker);
2550
+ rows.push({
2551
+ marker,
2552
+ ...cantSplit ? {
2553
+ cantSplit: work_docx_table_row_import_onOffValue(cantSplit)
2554
+ } : {},
2555
+ ...repeatHeader ? {
2556
+ repeatHeader: work_docx_table_row_import_onOffValue(repeatHeader)
2557
+ } : {},
2558
+ ...null !== rowHeight ? {
2559
+ rowHeight
2560
+ } : {},
2561
+ ...null !== rowHeight && rowHeightRule ? {
2562
+ rowHeightRule
2563
+ } : {}
2564
+ });
2565
+ }
2566
+ return {
2567
+ rows
2568
+ };
2569
+ }
2570
+ function applyImportedDocxTableRowMarkers(document, markers) {
2571
+ const rowByMarker = new Map(markers.rows.map((row)=>[
2572
+ row.marker,
2573
+ row
2574
+ ]));
2575
+ for (const node of work_docx_table_row_import_textNodes(document.body)){
2576
+ if (!node.data.includes('__A3S_WORK_TABLE_ROW_')) continue;
2577
+ const row = node.parentElement?.closest('tr');
2578
+ node.data = node.data.replace(TABLE_ROW_MARKER_PATTERN, (marker)=>{
2579
+ const properties = rowByMarker.get(marker);
2580
+ if (row instanceof HTMLTableRowElement && properties) {
2581
+ work_docx_table_row_import_setBooleanAttribute(row, 'data-office-cant-split', properties.cantSplit);
2582
+ work_docx_table_row_import_setBooleanAttribute(row, 'data-office-repeat-header', properties.repeatHeader);
2583
+ if (void 0 !== properties.rowHeight) {
2584
+ row.dataset.officeRowHeight = String(properties.rowHeight);
2585
+ row.style.height = `${properties.rowHeight}px`;
2586
+ row.dataset.officeRowHeightRule = properties.rowHeightRule ?? 'atLeast';
2587
+ }
2588
+ }
2589
+ return '';
2590
+ });
2591
+ }
2592
+ document.body.normalize();
2593
+ }
2594
+ function hasImportedDocxTableRowMarkers(markers) {
2595
+ return markers.rows.length > 0;
2596
+ }
2597
+ function firstTableRowParagraph(document, row) {
2598
+ const cell = directChild(row, 'tc');
2599
+ if (!cell) return null;
2600
+ const existing = directChild(cell, 'p') ?? descendants(cell, 'p').find((paragraph)=>work_docx_table_row_import_closestAncestor(paragraph, 'tr') === row);
2601
+ if (existing) return existing;
2602
+ const paragraph = document.createElementNS(work_docx_table_row_import_WORD_NAMESPACE, 'w:p');
2603
+ cell.append(paragraph);
2604
+ return paragraph;
2605
+ }
2606
+ function insertRowMarker(document, paragraph, marker) {
2607
+ const run = document.createElementNS(work_docx_table_row_import_WORD_NAMESPACE, 'w:r');
2608
+ const text = document.createElementNS(work_docx_table_row_import_WORD_NAMESPACE, 'w:t');
2609
+ text.setAttributeNS(work_docx_table_row_import_XML_NAMESPACE, 'xml:space', 'preserve');
2610
+ text.textContent = marker;
2611
+ run.append(text);
2612
+ const properties = directChild(paragraph, 'pPr');
2613
+ paragraph.insertBefore(run, properties?.nextSibling ?? paragraph.firstChild);
2614
+ }
2615
+ function work_docx_table_row_import_onOffValue(element) {
2616
+ const value = (attribute(element, 'val') ?? attribute(element, 'w:val'))?.trim().toLowerCase();
2617
+ return '0' !== value && 'false' !== value && 'off' !== value;
2618
+ }
2619
+ function work_docx_table_row_import_setBooleanAttribute(element, name, value) {
2620
+ if (void 0 !== value) element.setAttribute(name, String(value));
2621
+ }
2622
+ function tableRowHeightRule(value) {
2623
+ if ('exact' === value) return 'exact';
2624
+ return 'atLeast' === value ? 'atLeast' : null;
2625
+ }
2626
+ function work_docx_table_row_import_twipsToPixels(value) {
2627
+ if (!Number.isFinite(value) || value <= 0) return null;
2628
+ return Math.round(value * PIXELS_PER_TWIP * 100) / 100;
2629
+ }
2630
+ function work_docx_table_row_import_closestAncestor(element, localName) {
2631
+ let current = element;
2632
+ while(current){
2633
+ if (current.localName === localName) return current;
2634
+ current = current.parentElement;
2635
+ }
2636
+ return null;
2637
+ }
2638
+ function work_docx_table_row_import_textNodes(root) {
2639
+ const document = root.ownerDocument;
2640
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
2641
+ const nodes = [];
2642
+ if (!walker) return nodes;
2643
+ while(walker.nextNode())nodes.push(walker.currentNode);
2644
+ return nodes;
2645
+ }
2646
+ const work_docx_table_sizing_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
2647
+ const work_docx_table_sizing_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
2648
+ const TABLE_SIZING_MARKER_PATTERN = /__A3S_WORK_TABLE_SIZING_\d+__/g;
2649
+ const work_docx_table_sizing_import_PIXELS_PER_TWIP = 96 / 1440;
2650
+ function markDocxTableSizing(document) {
2651
+ const tables = [];
2652
+ for (const table of descendants(document, 'tbl')){
2653
+ const paragraph = firstTableParagraph(document, table);
2654
+ if (!paragraph) continue;
2655
+ const properties = directChild(table, 'tblPr');
2656
+ const layout = properties ? directChild(properties, 'tblLayout') : void 0;
2657
+ const preferredWidth = properties ? directChild(properties, 'tblW') : void 0;
2658
+ const grid = directChild(table, 'tblGrid');
2659
+ const columnWidths = grid ? directChildren(grid, 'gridCol').map((column)=>work_docx_table_sizing_import_twipsToPixels(Number(attribute(column, 'w')))).filter((width)=>null !== width) : [];
2660
+ const marker = `__A3S_WORK_TABLE_SIZING_${tables.length + 1}__`;
2661
+ insertMarker(document, paragraph, marker);
2662
+ tables.push({
2663
+ marker,
2664
+ layoutMode: importedTableLayoutMode(layout, preferredWidth),
2665
+ columnWidths
2666
+ });
2667
+ }
2668
+ return {
2669
+ tables
2670
+ };
2671
+ }
2672
+ function applyImportedDocxTableSizingMarkers(document, markers) {
2673
+ const tableByMarker = new Map(markers.tables.map((table)=>[
2674
+ table.marker,
2675
+ table
2676
+ ]));
2677
+ for (const node of work_docx_table_sizing_import_textNodes(document.body)){
2678
+ if (!node.data.includes('__A3S_WORK_TABLE_SIZING_')) continue;
2679
+ const table = node.parentElement?.closest('table');
2680
+ node.data = node.data.replace(TABLE_SIZING_MARKER_PATTERN, (marker)=>{
2681
+ const sizing = tableByMarker.get(marker);
2682
+ if (table instanceof HTMLTableElement && sizing) {
2683
+ table.dataset.officeTableLayout = sizing.layoutMode;
2684
+ if ('fixed' === sizing.layoutMode && sizing.columnWidths.length) applyColumnWidths(table, sizing.columnWidths);
2685
+ }
2686
+ return '';
2687
+ });
2688
+ }
2689
+ document.body.normalize();
2690
+ }
2691
+ function hasImportedDocxTableSizingMarkers(markers) {
2692
+ return markers.tables.length > 0;
2693
+ }
2694
+ function importedTableLayoutMode(layout, preferredWidth) {
2695
+ const layoutType = layout ? attribute(layout, 'type') : null;
2696
+ const widthType = preferredWidth ? attribute(preferredWidth, 'type') : null;
2697
+ if ('autofit' === layoutType || 'auto' === widthType) return 'contents';
2698
+ if ('pct' === widthType) return 'window';
2699
+ return 'fixed';
2700
+ }
2701
+ function applyColumnWidths(table, columnWidths) {
2702
+ const occupiedUntilRow = [];
2703
+ Array.from(table.rows).forEach((row, rowIndex)=>{
2704
+ let columnIndex = 0;
2705
+ for (const cell of Array.from(row.cells)){
2706
+ while((occupiedUntilRow[columnIndex] ?? 0) > rowIndex)columnIndex += 1;
2707
+ const widths = columnWidths.slice(columnIndex, columnIndex + cell.colSpan);
2708
+ if (widths.length === cell.colSpan) cell.setAttribute('colwidth', widths.join(','));
2709
+ if (cell.rowSpan > 1) for(let offset = 0; offset < cell.colSpan; offset += 1)occupiedUntilRow[columnIndex + offset] = rowIndex + cell.rowSpan;
2710
+ columnIndex += cell.colSpan;
2711
+ }
2712
+ });
2713
+ }
2714
+ function firstTableParagraph(document, table) {
2715
+ const cell = descendants(table, 'tc').find((candidate)=>work_docx_table_sizing_import_closestAncestor(candidate, 'tbl') === table);
2716
+ if (!cell) return null;
2717
+ const existing = descendants(cell, 'p').find((paragraph)=>work_docx_table_sizing_import_closestAncestor(paragraph, 'tc') === cell);
2718
+ if (existing) return existing;
2719
+ const paragraph = document.createElementNS(work_docx_table_sizing_import_WORD_NAMESPACE, 'w:p');
2720
+ cell.append(paragraph);
2721
+ return paragraph;
2722
+ }
2723
+ function insertMarker(document, paragraph, marker) {
2724
+ const run = document.createElementNS(work_docx_table_sizing_import_WORD_NAMESPACE, 'w:r');
2725
+ const text = document.createElementNS(work_docx_table_sizing_import_WORD_NAMESPACE, 'w:t');
2726
+ text.setAttributeNS(work_docx_table_sizing_import_XML_NAMESPACE, 'xml:space', 'preserve');
2727
+ text.textContent = marker;
2728
+ run.append(text);
2729
+ const properties = directChild(paragraph, 'pPr');
2730
+ paragraph.insertBefore(run, properties?.nextSibling ?? paragraph.firstChild);
2731
+ }
2732
+ function work_docx_table_sizing_import_twipsToPixels(value) {
2733
+ if (!Number.isFinite(value) || value <= 0) return null;
2734
+ return Math.round(value * work_docx_table_sizing_import_PIXELS_PER_TWIP * 100) / 100;
2735
+ }
2736
+ function work_docx_table_sizing_import_closestAncestor(element, localName) {
2737
+ let current = element;
2738
+ while(current){
2739
+ if (current.localName === localName) return current;
2740
+ current = current.parentElement;
2741
+ }
2742
+ return null;
2743
+ }
2744
+ function work_docx_table_sizing_import_textNodes(root) {
2745
+ const document = root.ownerDocument;
2746
+ const walker = document?.createTreeWalker(root, NodeFilter.SHOW_TEXT);
2747
+ const nodes = [];
2748
+ if (!walker) return nodes;
2749
+ while(walker.nextNode())nodes.push(walker.currentNode);
2750
+ return nodes;
2751
+ }
2752
+ const work_docx_import_TWIPS_PER_MILLIMETER = 1440 / 25.4;
2753
+ const work_docx_import_WORD_NAMESPACE = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
2754
+ const work_docx_import_XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
2755
+ async function prepareDocxImport(buffer) {
2756
+ const archive = await OoxmlPackage.load(buffer);
2757
+ const bibliography = (await readDocxBibliography(archive)).bibliography;
2758
+ const fallback = documentInitialSectionLayout({
2759
+ type: 'document',
2760
+ html: '<p></p>',
2761
+ pageSize: 'a4'
2762
+ });
2763
+ if (!archive.has('word/document.xml')) return {
2764
+ conversionBuffer: buffer,
2765
+ sections: [
2766
+ {
2767
+ id: 'document-section-1',
2768
+ layout: fallback
2769
+ }
2770
+ ],
2771
+ captionMarkers: {
2772
+ captions: [],
2773
+ references: []
2774
+ },
2775
+ changeMarkers: {
2776
+ changes: []
2777
+ },
2778
+ commentMarkers: {
2779
+ comments: [],
2780
+ ranges: []
2781
+ },
2782
+ fieldMarkers: {
2783
+ fields: []
2784
+ },
2785
+ citationMarkers: {
2786
+ citations: [],
2787
+ bibliographies: []
2788
+ },
2789
+ listMarkers: {
2790
+ lists: []
2791
+ },
2792
+ imageLayoutMarkers: {
2793
+ images: []
2794
+ },
2795
+ paragraphAlignmentMarkers: {
2796
+ paragraphs: []
2797
+ },
2798
+ paragraphDirectionMarkers: {
2799
+ paragraphs: []
2800
+ },
2801
+ paragraphIndentMarkers: {
2802
+ paragraphs: []
2803
+ },
2804
+ paragraphPaginationMarkers: {
2805
+ paragraphs: []
2806
+ },
2807
+ paragraphSpacingMarkers: {
2808
+ paragraphs: []
2809
+ },
2810
+ runFormattingMarkers: {
2811
+ runs: []
2812
+ },
2813
+ tabStopMarkers: {
2814
+ paragraphs: [],
2815
+ inlineTabs: []
2816
+ },
2817
+ tableCellMarkers: {
2818
+ cells: []
2819
+ },
2820
+ tableRowMarkers: {
2821
+ rows: []
2822
+ },
2823
+ tableSizingMarkers: {
2824
+ tables: []
2825
+ },
2826
+ bibliography,
2827
+ trackChanges: false
2828
+ };
2829
+ const document = await archive.xml('word/document.xml');
2830
+ const pageColor = importDocxPageColor(document);
2831
+ const numbering = archive.has('word/numbering.xml') ? await archive.xml('word/numbering.xml') : null;
2832
+ const commentMarkers = await markDocxComments(document, archive);
2833
+ const changeMarkers = markDocxTextChanges(document);
2834
+ const captionMarkers = markDocxCaptionFields(document);
2835
+ const citationMarkers = markDocxCitationFields(document);
2836
+ const fieldMarkers = markDocxBodyFields(document);
2837
+ const listMarkers = markDocxLists(document, numbering);
2838
+ const imageLayoutMarkers = markDocxImageLayouts(document);
2839
+ const paragraphStylesDocument = archive.has('word/styles.xml') ? await archive.xml('word/styles.xml') : null;
2840
+ const paragraphStyles = createDocxParagraphStyleResolver(paragraphStylesDocument);
2841
+ const paragraphDirectionMarkers = markDocxParagraphDirections(document, paragraphStyles);
2842
+ const paragraphAlignmentMarkers = markDocxParagraphAlignments(document, paragraphStyles);
2843
+ const paragraphIndentMarkers = markDocxParagraphIndents(document, paragraphStyles);
2844
+ const paragraphSpacingMarkers = markDocxParagraphSpacing(document, paragraphStyles);
2845
+ const paragraphPaginationMarkers = markDocxParagraphPagination(document, paragraphStyles);
2846
+ const themePath = archive.paths('word/theme/').find((path)=>/\/theme\d*\.xml$/i.test(path));
2847
+ const themeDocument = themePath ? await archive.xml(themePath) : null;
2848
+ const runFormattingMarkers = markDocxRunFormatting(document, paragraphStyles, themeDocument);
2849
+ const tabStopMarkers = markDocxParagraphTabStops(document, paragraphStyles);
2850
+ const tableCellMarkers = markDocxTableCells(document);
2851
+ const tableRowMarkers = markDocxTableRows(document);
2852
+ const tableSizingMarkers = markDocxTableSizing(document);
2853
+ const settings = archive.has('word/settings.xml') ? await archive.xml('word/settings.xml') : null;
2854
+ const trackChanges = Boolean(settings && firstDescendant(settings, 'trackRevisions')) || changeMarkers.changes.length > 0;
2855
+ const sectionElements = effectiveSectionProperties(document);
2856
+ if (!sectionElements.length) return {
2857
+ conversionBuffer: hasImportedDocxCaptionMarkers(captionMarkers) || hasImportedDocxChangeMarkers(changeMarkers) || hasImportedDocxCommentMarkers(commentMarkers) || hasImportedDocxCitationMarkers(citationMarkers) || hasImportedDocxFieldMarkers(fieldMarkers) || hasImportedDocxListMarkers(listMarkers) || hasImportedDocxImageLayoutMarkers(imageLayoutMarkers) || hasImportedDocxParagraphAlignmentMarkers(paragraphAlignmentMarkers) || hasImportedDocxParagraphDirectionMarkers(paragraphDirectionMarkers) || hasImportedDocxParagraphIndentMarkers(paragraphIndentMarkers) || hasImportedDocxParagraphSpacingMarkers(paragraphSpacingMarkers) || hasImportedDocxParagraphPaginationMarkers(paragraphPaginationMarkers) || hasImportedDocxRunFormattingMarkers(runFormattingMarkers) || hasImportedDocxParagraphTabStopMarkers(tabStopMarkers) || hasImportedDocxTableCellMarkers(tableCellMarkers) || hasImportedDocxTableRowMarkers(tableRowMarkers) || hasImportedDocxTableSizingMarkers(tableSizingMarkers) ? await writeDocumentXml(buffer, document) : buffer,
2858
+ sections: [
2859
+ {
2860
+ id: 'document-section-1',
2861
+ layout: fallback
2862
+ }
2863
+ ],
2864
+ pageColor,
2865
+ captionMarkers,
2866
+ changeMarkers,
2867
+ commentMarkers,
2868
+ fieldMarkers,
2869
+ citationMarkers,
2870
+ listMarkers,
2871
+ imageLayoutMarkers,
2872
+ paragraphAlignmentMarkers,
2873
+ paragraphDirectionMarkers,
2874
+ paragraphIndentMarkers,
2875
+ paragraphPaginationMarkers,
2876
+ paragraphSpacingMarkers,
2877
+ runFormattingMarkers,
2878
+ tabStopMarkers,
2879
+ tableCellMarkers,
2880
+ tableRowMarkers,
2881
+ tableSizingMarkers,
2882
+ bibliography,
2883
+ trackChanges
2884
+ };
2885
+ const relationships = await archive.relationships('word/document.xml');
2886
+ const oddEvenPageChrome = documentUsesOddEvenPageChrome(settings);
2887
+ const sections = [];
2888
+ let previous = fallback;
2889
+ for (const [index, element] of sectionElements.entries()){
2890
+ const layout = await parseSectionLayout(element, archive, relationships, previous, oddEvenPageChrome);
2891
+ sections.push({
2892
+ id: `document-section-${index + 1}`,
2893
+ layout
2894
+ });
2895
+ previous = layout;
2896
+ }
2897
+ if (sections.length > 1) addSectionMarkers(document, sectionElements);
2898
+ return {
2899
+ conversionBuffer: sections.length > 1 || hasImportedDocxCaptionMarkers(captionMarkers) || hasImportedDocxChangeMarkers(changeMarkers) || hasImportedDocxCommentMarkers(commentMarkers) || hasImportedDocxCitationMarkers(citationMarkers) || hasImportedDocxFieldMarkers(fieldMarkers) || hasImportedDocxListMarkers(listMarkers) || hasImportedDocxImageLayoutMarkers(imageLayoutMarkers) || hasImportedDocxParagraphAlignmentMarkers(paragraphAlignmentMarkers) || hasImportedDocxParagraphDirectionMarkers(paragraphDirectionMarkers) || hasImportedDocxParagraphIndentMarkers(paragraphIndentMarkers) || hasImportedDocxParagraphSpacingMarkers(paragraphSpacingMarkers) || hasImportedDocxParagraphPaginationMarkers(paragraphPaginationMarkers) || hasImportedDocxRunFormattingMarkers(runFormattingMarkers) || hasImportedDocxParagraphTabStopMarkers(tabStopMarkers) || hasImportedDocxTableCellMarkers(tableCellMarkers) || hasImportedDocxTableRowMarkers(tableRowMarkers) || hasImportedDocxTableSizingMarkers(tableSizingMarkers) ? await writeDocumentXml(buffer, document) : buffer,
2900
+ sections,
2901
+ pageColor,
2902
+ captionMarkers,
2903
+ changeMarkers,
2904
+ commentMarkers,
2905
+ fieldMarkers,
2906
+ citationMarkers,
2907
+ listMarkers,
2908
+ imageLayoutMarkers,
2909
+ paragraphAlignmentMarkers,
2910
+ paragraphDirectionMarkers,
2911
+ paragraphIndentMarkers,
2912
+ paragraphPaginationMarkers,
2913
+ paragraphSpacingMarkers,
2914
+ runFormattingMarkers,
2915
+ tabStopMarkers,
2916
+ tableCellMarkers,
2917
+ tableRowMarkers,
2918
+ tableSizingMarkers,
2919
+ bibliography,
2920
+ trackChanges
2921
+ };
2922
+ }
2923
+ function applyDocxSectionsToHtml(html, sections, captionMarkers = {
2924
+ captions: [],
2925
+ references: []
2926
+ }, changeMarkers = {
2927
+ changes: []
2928
+ }, commentMarkers = {
2929
+ comments: [],
2930
+ ranges: []
2931
+ }, fieldMarkers = {
2932
+ fields: []
2933
+ }, citationMarkers = {
2934
+ citations: [],
2935
+ bibliographies: []
2936
+ }, listMarkers = {
2937
+ lists: []
2938
+ }, imageLayoutMarkers = {
2939
+ images: []
2940
+ }, paragraphAlignmentMarkers = {
2941
+ paragraphs: []
2942
+ }, runFormattingMarkers = {
2943
+ runs: []
2944
+ }, paragraphDirectionMarkers = {
2945
+ paragraphs: []
2946
+ }, paragraphIndentMarkers = {
2947
+ paragraphs: []
2948
+ }, paragraphSpacingMarkers = {
2949
+ paragraphs: []
2950
+ }, paragraphPaginationMarkers = {
2951
+ paragraphs: []
2952
+ }, bibliography, tabStopMarkers = {
2953
+ paragraphs: [],
2954
+ inlineTabs: []
2955
+ }, tableCellMarkers = {
2956
+ cells: []
2957
+ }, tableRowMarkers = {
2958
+ rows: []
2959
+ }, tableSizingMarkers = {
2960
+ tables: []
2961
+ }) {
2962
+ const document = new DOMParser().parseFromString(html, 'text/html');
2963
+ applyImportedDocxRunFormattingMarkers(document, runFormattingMarkers);
2964
+ applyImportedDocxCaptionMarkers(document, captionMarkers);
2965
+ applyImportedDocxCitationMarkers(document, citationMarkers);
2966
+ applyImportedDocxFieldMarkers(document, fieldMarkers);
2967
+ applyImportedDocxListMarkers(document, listMarkers);
2968
+ applyImportedDocxImageLayoutMarkers(document, imageLayoutMarkers);
2969
+ applyImportedDocxParagraphDirectionMarkers(document, paragraphDirectionMarkers);
2970
+ applyImportedDocxParagraphIndentMarkers(document, paragraphIndentMarkers);
2971
+ applyImportedDocxParagraphSpacingMarkers(document, paragraphSpacingMarkers);
2972
+ applyImportedDocxParagraphPaginationMarkers(document, paragraphPaginationMarkers);
2973
+ applyImportedDocxParagraphTabStopMarkers(document, tabStopMarkers);
2974
+ applyImportedDocxParagraphAlignmentMarkers(document, paragraphAlignmentMarkers);
2975
+ applyImportedDocxTableCellMarkers(document, tableCellMarkers);
2976
+ applyImportedDocxTableSizingMarkers(document, tableSizingMarkers);
2977
+ applyImportedDocxTableRowMarkers(document, tableRowMarkers);
2978
+ applyImportedDocxChangeMarkers(document, changeMarkers);
2979
+ applyImportedDocxCommentMarkers(document, commentMarkers);
2980
+ const notes = extractMammothDocumentNotes(document);
2981
+ const sourceNodes = Array.from(document.body.childNodes);
2982
+ document.body.replaceChildren();
2983
+ let sectionIndex = 0;
2984
+ let section = createHtmlSection(document, sections[sectionIndex]);
2985
+ for (const node of sourceNodes){
2986
+ if (isSectionMarker(node, sectionIndex)) {
2987
+ ensureSectionContent(section);
2988
+ document.body.append(section);
2989
+ sectionIndex += 1;
2990
+ section = createHtmlSection(document, sections[sectionIndex] ?? sections.at(-1));
2991
+ continue;
2992
+ }
2993
+ section.append(node);
2994
+ }
2995
+ ensureSectionContent(section);
2996
+ document.body.append(section);
2997
+ while(sectionIndex + 1 < sections.length){
2998
+ sectionIndex += 1;
2999
+ const missing = createHtmlSection(document, sections[sectionIndex]);
3000
+ ensureSectionContent(missing);
3001
+ document.body.append(missing);
3002
+ }
3003
+ placeMammothDocumentNotes(document, notes);
3004
+ return normalizeDocumentCitationsHtml(normalizeDocumentFieldsHtml(normalizeDocumentCaptionsHtml(normalizeDocumentNotesHtml(document.body.innerHTML))), bibliography);
3005
+ }
3006
+ async function readDocxLayout(buffer) {
3007
+ const prepared = await prepareDocxImport(buffer);
3008
+ return {
3009
+ ...documentContentLayoutProperties(prepared.sections[0].layout),
3010
+ ...prepared.pageColor ? {
3011
+ pageColor: prepared.pageColor
3012
+ } : {}
3013
+ };
3014
+ }
3015
+ async function parseSectionLayout(section, archive, relationships, previous, oddEvenPageChrome) {
3016
+ const pageSize = firstDescendant(section, 'pgSz');
3017
+ const width = work_docx_import_numberAttribute(pageSize, 'w');
3018
+ const height = work_docx_import_numberAttribute(pageSize, 'h');
3019
+ const orientation = 'landscape' === attribute(pageSize ?? section, 'orient') || width > 0 && height > 0 && width > height ? 'landscape' : pageSize ? 'portrait' : previous.orientation;
3020
+ const shortEdge = Math.min(width || 11906, height || 16838);
3021
+ const size = pageSize ? Math.abs(shortEdge - 12240) < Math.abs(shortEdge - 11906) ? 'letter' : 'a4' : previous.pageSize;
3022
+ const marginsElement = firstDescendant(section, 'pgMar');
3023
+ const columnsElement = firstDescendant(section, 'cols');
3024
+ const pageChrome = await importSectionPageChrome(section, archive, relationships, previous, oddEvenPageChrome);
3025
+ const pageNumberStart = work_docx_import_numberAttribute(firstDescendant(section, 'pgNumType'), 'start');
3026
+ return {
3027
+ pageSize: size,
3028
+ orientation,
3029
+ margins: marginsElement ? parseMargins(marginsElement, previous.margins) : {
3030
+ ...previous.margins
3031
+ },
3032
+ columns: columnsElement ? importDocxColumns(columnsElement, previous.columns) : {
3033
+ ...previous.columns
3034
+ },
3035
+ breakAfter: parseSectionBreak(firstDescendant(section, 'type')),
3036
+ ...pageChrome,
3037
+ pageNumberStart: pageNumberStart > 0 ? pageNumberStart : void 0
3038
+ };
3039
+ }
3040
+ function addSectionMarkers(document, sectionElements) {
3041
+ for(let index = 0; index < sectionElements.length - 1; index += 1){
3042
+ const paragraph = work_docx_import_closestAncestor(sectionElements[index], 'p');
3043
+ if (!paragraph?.parentNode) continue;
3044
+ const marker = document.createElementNS(work_docx_import_WORD_NAMESPACE, 'w:p');
3045
+ const run = document.createElementNS(work_docx_import_WORD_NAMESPACE, 'w:r');
3046
+ const text = document.createElementNS(work_docx_import_WORD_NAMESPACE, 'w:t');
3047
+ text.setAttributeNS(work_docx_import_XML_NAMESPACE, 'xml:space', 'preserve');
3048
+ text.textContent = sectionMarker(index);
3049
+ run.append(text);
3050
+ marker.append(run);
3051
+ paragraph.parentNode.insertBefore(marker, paragraph.nextSibling);
3052
+ }
3053
+ }
3054
+ async function writeDocumentXml(buffer, document) {
3055
+ const zip = await jszip.loadAsync(buffer);
3056
+ zip.file('word/document.xml', new XMLSerializer().serializeToString(document));
3057
+ return zip.generateAsync({
3058
+ type: 'arraybuffer'
3059
+ });
3060
+ }
3061
+ function effectiveSectionProperties(document) {
3062
+ return descendants(document, 'sectPr').filter((element)=>!work_docx_import_closestAncestor(element, 'sectPrChange'));
3063
+ }
3064
+ function createHtmlSection(document, section) {
3065
+ const element = document.createElement('section');
3066
+ const fallback = documentInitialSectionLayout({
3067
+ type: 'document',
3068
+ html: '<p></p>',
3069
+ pageSize: 'a4'
3070
+ });
3071
+ const layout = section?.layout ?? fallback;
3072
+ const id = section?.id ?? 'document-section';
3073
+ for (const [name, value] of Object.entries(documentSectionDomAttributes(layout, id)))element.setAttribute(name, value);
3074
+ return element;
3075
+ }
3076
+ function ensureSectionContent(section) {
3077
+ if (!section.childNodes.length) section.innerHTML = '<p></p>';
3078
+ }
3079
+ function isSectionMarker(node, index) {
3080
+ return node instanceof HTMLElement && node.textContent?.trim() === sectionMarker(index);
3081
+ }
3082
+ function sectionMarker(index) {
3083
+ return `__A3S_WORK_DOCUMENT_SECTION_${index + 1}__`;
3084
+ }
3085
+ function parseMargins(element, fallback) {
3086
+ return {
3087
+ top: work_docx_import_twipsToMillimeters(work_docx_import_numberAttribute(element, 'top'), fallback.top),
3088
+ right: work_docx_import_twipsToMillimeters(work_docx_import_numberAttribute(element, 'right'), fallback.right),
3089
+ bottom: work_docx_import_twipsToMillimeters(work_docx_import_numberAttribute(element, 'bottom'), fallback.bottom),
3090
+ left: work_docx_import_twipsToMillimeters(work_docx_import_numberAttribute(element, 'left'), fallback.left)
3091
+ };
3092
+ }
3093
+ function parseSectionBreak(element) {
3094
+ if (!element) return 'nextPage';
3095
+ const value = attribute(element, 'val');
3096
+ if ('continuous' === value || 'evenPage' === value || 'oddPage' === value || 'nextColumn' === value) return value;
3097
+ return 'nextPage';
3098
+ }
3099
+ function work_docx_import_numberAttribute(element, name) {
3100
+ if (!element) return 0;
3101
+ const value = Number(attribute(element, name));
3102
+ return Number.isFinite(value) ? value : 0;
3103
+ }
3104
+ function work_docx_import_closestAncestor(element, localName) {
3105
+ let current = element;
3106
+ while(current){
3107
+ if (current.localName === localName) return current;
3108
+ current = current.parentElement;
3109
+ }
3110
+ return null;
3111
+ }
3112
+ function work_docx_import_twipsToMillimeters(value, fallback) {
3113
+ if (value <= 0) return fallback;
3114
+ return Math.round(value / work_docx_import_TWIPS_PER_MILLIMETER * 10) / 10;
3115
+ }
3116
+ export { applyDocxSectionsToHtml, prepareDocxImport, readDocxLayout };