@stll/folio-core 0.67.0 → 0.68.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 (251) hide show
  1. package/dist/ai-edits/apply.d.ts +9 -1
  2. package/dist/ai-edits/apply.js +94 -8
  3. package/dist/ai-edits/headless.d.ts +36 -21
  4. package/dist/ai-edits/headless.js +104 -34
  5. package/dist/ai-edits/index.d.ts +2 -2
  6. package/dist/ai-edits/note-references.d.ts +6 -0
  7. package/dist/ai-edits/note-references.js +7 -1
  8. package/dist/ai-edits/read.d.ts +19 -0
  9. package/dist/ai-edits/snapshot.d.ts +6 -0
  10. package/dist/ai-edits/snapshot.js +8 -3
  11. package/dist/ai-edits/types.d.ts +9 -1
  12. package/dist/ai-suggestions/apply.js +13 -4
  13. package/dist/compare/compare.js +2 -1
  14. package/dist/compare/inserted-resource-snapshot.d.ts +4 -1
  15. package/dist/compare/inserted-resource-snapshot.js +7 -3
  16. package/dist/controller/canonicalClipboard.js +29 -12
  17. package/dist/controller/canonicalComposition.js +1 -1
  18. package/dist/controller/canonicalInlineProjection.d.ts +35 -10
  19. package/dist/controller/canonicalInlineProjection.js +192 -28
  20. package/dist/controller/canonicalInput.d.ts +2 -1
  21. package/dist/controller/canonicalInput.js +28 -1
  22. package/dist/controller/canonicalListRendering.d.ts +2 -1
  23. package/dist/controller/canonicalListRendering.js +1 -1
  24. package/dist/controller/canonicalLockGuard.d.ts +8 -0
  25. package/dist/controller/canonicalLockGuard.js +88 -0
  26. package/dist/controller/canonicalPublicOperations.d.ts +12 -4
  27. package/dist/controller/canonicalPublicOperations.js +274 -20
  28. package/dist/controller/canonicalSession.d.ts +87 -7
  29. package/dist/controller/canonicalSession.js +327 -73
  30. package/dist/controller/canonicalStoryEditor.d.ts +3 -2
  31. package/dist/controller/canonicalStoryEditor.js +4 -3
  32. package/dist/controller/canonicalStructure.d.ts +2 -1
  33. package/dist/controller/canonicalStructure.js +129 -7
  34. package/dist/controller/contentControlWidgetController.d.ts +5 -0
  35. package/dist/controller/contentControlWidgetController.js +13 -1
  36. package/dist/controller/folioEditor.js +1 -0
  37. package/dist/controller/headerFooterEditorManager.d.ts +2 -2
  38. package/dist/controller/headerFooterEditorManager.js +5 -5
  39. package/dist/controller/hiddenEditorApi.d.ts +6 -0
  40. package/dist/controller/hiddenEditorApi.js +1 -0
  41. package/dist/controller/hiddenEditorManager.d.ts +4 -3
  42. package/dist/controller/hiddenEditorManager.js +91 -37
  43. package/dist/controller/layoutPipeline.js +48 -15
  44. package/dist/controller/noteEditorManager.d.ts +2 -2
  45. package/dist/controller/noteEditorManager.js +5 -5
  46. package/dist/display-list/build/pageFurniture.js +41 -19
  47. package/dist/display-list/build/tablePrimitives.js +23 -4
  48. package/dist/display-list/dom/renderDisplayListToDom.js +4 -4
  49. package/dist/document-operations.d.ts +8 -0
  50. package/dist/document-operations.js +4 -3
  51. package/dist/docx/blockContentParser.d.ts +7 -3
  52. package/dist/docx/blockContentParser.js +2 -3
  53. package/dist/docx/blockPlainText.js +2 -0
  54. package/dist/docx/bookmarkRangeJoin.d.ts +6 -0
  55. package/dist/docx/bookmarkRangeJoin.js +43 -0
  56. package/dist/docx/canonicalSave.js +5 -1
  57. package/dist/docx/canonicalSessionInput.d.ts +5 -1
  58. package/dist/docx/canonicalSessionInput.js +7 -2
  59. package/dist/docx/commentAnchorIndex.d.ts +21 -5
  60. package/dist/docx/commentAnchorIndex.js +39 -11
  61. package/dist/docx/commentRangeIntegrity.js +30 -24
  62. package/dist/docx/commentRangeJoin.d.ts +4 -0
  63. package/dist/docx/commentRangeJoin.js +26 -12
  64. package/dist/docx/commentReferenceCompletion.js +5 -4
  65. package/dist/docx/commentReferenceNormalization.js +40 -18
  66. package/dist/docx/compatibility.js +9 -2
  67. package/dist/docx/containerChildren.js +22 -1
  68. package/dist/docx/encryption/compoundFile.js +9 -1
  69. package/dist/docx/encryption/encryptionInfo.js +16 -2
  70. package/dist/docx/ensureParaIds.js +46 -7
  71. package/dist/docx/ensureUniqueControlIds.d.ts +25 -0
  72. package/dist/docx/ensureUniqueControlIds.js +110 -0
  73. package/dist/docx/headerFooterVerbatim.d.ts +7 -0
  74. package/dist/docx/headerFooterVerbatim.js +13 -2
  75. package/dist/docx/hostCommentThreads.d.ts +17 -0
  76. package/dist/docx/hostCommentThreads.js +49 -0
  77. package/dist/docx/hyperlinkParser.js +9 -2
  78. package/dist/docx/inlineWrapperContent.d.ts +8 -1
  79. package/dist/docx/inlineWrapperContent.js +9 -2
  80. package/dist/docx/listMarkerComputation.d.ts +35 -1
  81. package/dist/docx/listMarkerComputation.js +39 -1
  82. package/dist/docx/listModelNormalization.d.ts +44 -1
  83. package/dist/docx/listModelNormalization.js +227 -96
  84. package/dist/docx/markupRangeMarker.d.ts +14 -0
  85. package/dist/docx/markupRangeMarker.js +15 -1
  86. package/dist/docx/metadataPrivacy.js +43 -22
  87. package/dist/docx/normalizeBaseDirection.js +3 -1
  88. package/dist/docx/paragraphParser.js +159 -48
  89. package/dist/docx/paragraphPropertySource.d.ts +7 -0
  90. package/dist/docx/paragraphPropertySource.js +22 -1
  91. package/dist/docx/paragraphTextBoxEnrichment.js +2 -1
  92. package/dist/docx/paragraphTraversal.js +2 -0
  93. package/dist/docx/parseWarningMessage.js +2 -1
  94. package/dist/docx/parser.js +6 -0
  95. package/dist/docx/renderedPageBreakNormalization.js +1 -1
  96. package/dist/docx/reviewProvenanceDiagnostics.d.ts +7 -0
  97. package/dist/docx/reviewProvenanceDiagnostics.js +39 -0
  98. package/dist/docx/reviewResolutionProvenance.d.ts +29 -3
  99. package/dist/docx/reviewResolutionProvenance.js +110 -25
  100. package/dist/docx/rezip.d.ts +6 -0
  101. package/dist/docx/rezip.js +38 -21
  102. package/dist/docx/selectiveSave.js +6 -10
  103. package/dist/docx/selectiveXmlPatch.d.ts +5 -4
  104. package/dist/docx/selectiveXmlPatch.js +11 -7
  105. package/dist/docx/serializer/documentSerializer.js +3 -1
  106. package/dist/docx/serializer/headerFooterSerializer.js +3 -1
  107. package/dist/docx/serializer/markupRangeAttributes.d.ts +6 -1
  108. package/dist/docx/serializer/markupRangeAttributes.js +6 -1
  109. package/dist/docx/serializer/noteSerializer.d.ts +17 -4
  110. package/dist/docx/serializer/noteSerializer.js +23 -16
  111. package/dist/docx/serializer/paragraphSerializer.js +56 -12
  112. package/dist/docx/serializer/runSerializer.d.ts +1 -3
  113. package/dist/docx/serializer/runSerializer.js +2 -2
  114. package/dist/docx/serializer/tableSerializer.d.ts +4 -0
  115. package/dist/docx/serializer/tableSerializer.js +4 -2
  116. package/dist/docx/server/applyDocxXmlPatchProposal.js +8 -4
  117. package/dist/docx/server/createBilingualDocument.js +27 -5
  118. package/dist/docx/server/migrateYjsAttrSchema.js +4 -0
  119. package/dist/docx/sessionListPruning.d.ts +2 -0
  120. package/dist/docx/sessionListPruning.js +50 -0
  121. package/dist/docx/splitRevisionPieces.d.ts +10 -0
  122. package/dist/docx/splitRevisionPieces.js +14 -0
  123. package/dist/docx/storyBlockReplay.js +4 -0
  124. package/dist/docx/structuralXmlPatch.js +19 -7
  125. package/dist/docx/tableParser.d.ts +6 -2
  126. package/dist/docx/tableParser.js +2 -3
  127. package/dist/docx/textBoxContentParser.d.ts +11 -0
  128. package/dist/docx/textBoxContentParser.js +51 -0
  129. package/dist/docx/textBoxParser.d.ts +0 -5
  130. package/dist/docx/textBoxParser.js +1 -23
  131. package/dist/docx/verticalMergeProjection.js +1 -1
  132. package/dist/fonts/fontsourceFaces.d.ts +2 -8
  133. package/dist/fonts/fontsourceFaces.js +1 -7
  134. package/dist/i18n/messages/ar.gen.js +2 -0
  135. package/dist/i18n/messages/catalogs.gen.d.ts +34 -0
  136. package/dist/i18n/messages/catalogs.gen.js +34 -0
  137. package/dist/i18n/messages/cs.gen.js +2 -0
  138. package/dist/i18n/messages/de.gen.js +2 -0
  139. package/dist/i18n/messages/en.gen.js +2 -0
  140. package/dist/i18n/messages/es.gen.js +2 -0
  141. package/dist/i18n/messages/et.gen.js +2 -0
  142. package/dist/i18n/messages/fr.gen.js +2 -0
  143. package/dist/i18n/messages/he.gen.js +2 -0
  144. package/dist/i18n/messages/hi.gen.js +2 -0
  145. package/dist/i18n/messages/hu.gen.js +2 -0
  146. package/dist/i18n/messages/lt.gen.js +2 -0
  147. package/dist/i18n/messages/lv.gen.js +2 -0
  148. package/dist/i18n/messages/messages.gen.d.ts +2 -0
  149. package/dist/i18n/messages/pl.gen.js +2 -0
  150. package/dist/i18n/messages/pt-BR.gen.js +2 -0
  151. package/dist/i18n/messages/sk.gen.js +2 -0
  152. package/dist/i18n/messages/tr.gen.js +2 -0
  153. package/dist/i18n/messages/zh-CN.gen.js +2 -0
  154. package/dist/internal/acceptedBlockProjection.js +2 -0
  155. package/dist/internal/pageBreakRunSourceDescendantIndex.d.ts +5 -0
  156. package/dist/internal/pageBreakRunSourceDescendantIndex.js +5 -0
  157. package/dist/internal/revisionResolutionInline.js +1 -2
  158. package/dist/layout-bridge/convert/tableConversion.js +19 -8
  159. package/dist/layout-bridge/engine/blockIndex.d.ts +7 -0
  160. package/dist/layout-bridge/engine/blockIndex.js +12 -0
  161. package/dist/layout-bridge/engine/hitTest.js +9 -10
  162. package/dist/layout-bridge/engine/selectionRects.js +6 -6
  163. package/dist/layout-engine/footnoteContinuation.d.ts +36 -0
  164. package/dist/layout-engine/footnoteContinuation.js +210 -0
  165. package/dist/layout-engine/index.d.ts +2 -2
  166. package/dist/layout-engine/index.js +7 -2
  167. package/dist/layout-engine/measure/cache.js +10 -5
  168. package/dist/layout-engine/measure/measureParagraph.js +1 -1
  169. package/dist/layout-engine/tableLayout.js +29 -5
  170. package/dist/layout-engine/tableRowBreak.d.ts +36 -0
  171. package/dist/layout-engine/tableRowBreak.js +43 -1
  172. package/dist/layout-engine/types.d.ts +36 -1
  173. package/dist/layout-painter/renderPage.d.ts +4 -4
  174. package/dist/layout-painter/renderPage.js +46 -17
  175. package/dist/layout-painter/renderTable.js +7 -4
  176. package/dist/managers/AutoSaveManager.d.ts +5 -1
  177. package/dist/managers/FindReplaceManager.js +3 -10
  178. package/dist/markdown/escape.d.ts +20 -1
  179. package/dist/markdown/escape.js +43 -1
  180. package/dist/markdown/renderBlock.js +4 -1
  181. package/dist/markdown/renderParagraph.js +13 -27
  182. package/dist/markdown/renderTable.js +6 -2
  183. package/dist/markdown/trailers.js +1 -0
  184. package/dist/pdf/images.d.ts +17 -1
  185. package/dist/pdf/images.js +22 -4
  186. package/dist/pdf/writePdf.js +4 -2
  187. package/dist/prosemirror/attrs/index.js +1 -0
  188. package/dist/prosemirror/canonicalCommands.d.ts +39 -1
  189. package/dist/prosemirror/canonicalTableCommands.d.ts +28 -0
  190. package/dist/prosemirror/canonicalTableCommands.js +362 -0
  191. package/dist/prosemirror/commands/comments.d.ts +25 -0
  192. package/dist/prosemirror/commands/comments.js +102 -11
  193. package/dist/prosemirror/commands/formatting.d.ts +1 -1
  194. package/dist/prosemirror/commands/index.d.ts +1 -1
  195. package/dist/prosemirror/commentIdAllocator.js +2 -2
  196. package/dist/prosemirror/commentRangeBoundaryAttrs.d.ts +6 -0
  197. package/dist/prosemirror/commentRangeBoundaryAttrs.js +9 -3
  198. package/dist/prosemirror/commentReferenceIntegrity.js +3 -4
  199. package/dist/prosemirror/conversion/fromProseDoc.d.ts +2 -0
  200. package/dist/prosemirror/conversion/fromProseDoc.js +76 -31
  201. package/dist/prosemirror/conversion/index.d.ts +1 -1
  202. package/dist/prosemirror/conversion/toProseDoc.d.ts +128 -1
  203. package/dist/prosemirror/conversion/toProseDoc.js +319 -51
  204. package/dist/prosemirror/extensions/StarterKit.js +2 -0
  205. package/dist/prosemirror/extensions/core/DocExtension.js +1 -1
  206. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.d.ts +1 -1
  207. package/dist/prosemirror/extensions/features/JoinedRunStyleExtension.d.ts +1 -1
  208. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.d.ts +1 -1
  209. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +1 -1
  210. package/dist/prosemirror/extensions/features/pastedHtmlLists.js +5 -4
  211. package/dist/prosemirror/extensions/marks/CommentExtension.js +6 -3
  212. package/dist/prosemirror/extensions/nodes/BlockCommentRangeBoundaryExtension.d.ts +4 -0
  213. package/dist/prosemirror/extensions/nodes/BlockCommentRangeBoundaryExtension.js +49 -0
  214. package/dist/prosemirror/extensions/nodes/ImageExtension.js +12 -3
  215. package/dist/prosemirror/extensions/nodes/TableExtension.js +32 -31
  216. package/dist/prosemirror/extensions/nodes/TextBoxExtension.js +1 -1
  217. package/dist/prosemirror/index.d.ts +2 -2
  218. package/dist/prosemirror/listLabels.js +3 -2
  219. package/dist/prosemirror/listNumbering.d.ts +6 -0
  220. package/dist/prosemirror/listNumbering.js +12 -9
  221. package/dist/prosemirror/lockedControls.d.ts +13 -0
  222. package/dist/prosemirror/lockedControls.js +106 -0
  223. package/dist/prosemirror/markupViewProjection.js +1 -1
  224. package/dist/prosemirror/noteReferenceReview.js +2 -2
  225. package/dist/prosemirror/plugins/documentNumbering.js +4 -1
  226. package/dist/prosemirror/plugins/suggestionMode.js +20 -9
  227. package/dist/prosemirror/plugins/templatePreviewValues.js +16 -1
  228. package/dist/prosemirror/rebaseParagraphRuns.js +1 -1
  229. package/dist/prosemirror/replacedAnnotations.js +1 -0
  230. package/dist/prosemirror/runFormattingFromMarks.d.ts +0 -1
  231. package/dist/prosemirror/runFormattingFromMarks.js +2 -4
  232. package/dist/prosemirror/runFormattingReconciliation.js +2 -2
  233. package/dist/prosemirror/runPropertyChangeResolution.js +1 -2
  234. package/dist/prosemirror/runStyleFormatting.d.ts +14 -4
  235. package/dist/prosemirror/runStyleFormatting.js +16 -13
  236. package/dist/prosemirror/schema/marks.d.ts +6 -0
  237. package/dist/prosemirror/styles/paragraphStyleCascade.js +2 -2
  238. package/dist/prosemirror/validation.js +1 -0
  239. package/dist/redline.js +23 -9
  240. package/dist/server.d.ts +2 -2
  241. package/dist/style-sets/extract.js +2 -2
  242. package/dist/types/canonicalCapabilities.d.ts +29 -8
  243. package/dist/types/canonicalCapabilities.js +13 -9
  244. package/dist/utils/cssString.d.ts +7 -0
  245. package/dist/utils/cssString.js +9 -0
  246. package/dist/utils/fontResolver.js +4 -1
  247. package/dist/utils/replaceText.d.ts +11 -0
  248. package/dist/utils/replaceText.js +39 -7
  249. package/dist/version-comparison.d.ts +9 -1
  250. package/dist/version-comparison.js +11 -5
  251. package/package.json +2 -2
@@ -52,6 +52,8 @@ const PAGE_CLASS_NAMES = {
52
52
  const HEADER_FOOTER_RULE_CLIP_MARGIN = pointsToPixels(1.5);
53
53
  const DEFAULT_MARGIN_GUIDE_COLOR = "#c0c0c0";
54
54
  const getDefaultPageFontFamily = () => resolveFontFamily(DEFAULT_FONT_FAMILY).cssFallback;
55
+ /** The part of a note a page shows, when the note continues across pages. */
56
+ const windowOfNote = (windows, noteId) => windows?.find((candidate) => candidate.noteId === noteId);
55
57
  /**
56
58
  * Apply page styles to an element
57
59
  */
@@ -621,10 +623,11 @@ function isPositionedHeaderFooterTextBoxBlock(block) {
621
623
  * from eigenpal/docx-editor#485, extended for folio's fallback rendering
622
624
  * and any wrapper margin so the helper matches the painted stack.
623
625
  */
624
- function calculateFootnoteAreaRenderHeight(footnotes) {
626
+ function calculateFootnoteAreaRenderHeight(footnotes, windows) {
625
627
  let height = 12;
626
628
  for (const fn of footnotes) {
627
- const entryHeight = fn.content ? fn.content.height : 13;
629
+ const noteWindow = windowOfNote(windows, fn.noteId);
630
+ const entryHeight = noteWindow ? noteWindow.to - noteWindow.from : fn.content?.height ?? 13;
628
631
  height += entryHeight + 0;
629
632
  }
630
633
  return height;
@@ -652,7 +655,7 @@ function renderFlowedNoteSeparators(page, contentEl, doc) {
652
655
  * Render the footnote area at the bottom of a page.
653
656
  * Includes a separator line (33% width) and footnote entries.
654
657
  */
655
- function renderFootnoteArea(footnotes, contentWidth, doc, context) {
658
+ function renderFootnoteArea(footnotes, contentWidth, doc, context, windows) {
656
659
  const container = doc.createElement("div");
657
660
  container.className = "layout-footnote-area";
658
661
  container.style.width = `${contentWidth}px`;
@@ -671,7 +674,7 @@ function renderFootnoteArea(footnotes, contentWidth, doc, context) {
671
674
  fnEl.style.marginBottom = `0px`;
672
675
  fnEl.style.color = "var(--doc-canvas-text, #000)";
673
676
  if (fn.content) {
674
- const contentEl = renderFootnoteContent(fn, contentWidth, doc, context);
677
+ const contentEl = renderFootnoteContent(fn, contentWidth, doc, context, windowOfNote(windows, fn.noteId));
675
678
  fnEl.append(contentEl);
676
679
  } else {
677
680
  fnEl.style.fontSize = "10px";
@@ -688,7 +691,7 @@ function renderFootnoteArea(footnotes, contentWidth, doc, context) {
688
691
  }
689
692
  return container;
690
693
  }
691
- function renderFootnoteContent(footnote, contentWidth, doc, context) {
694
+ function renderFootnoteContent(footnote, contentWidth, doc, context, noteWindow) {
692
695
  const content = footnote.content;
693
696
  if (!content) panic("Missing structured footnote content");
694
697
  const wrapper = doc.createElement("div");
@@ -696,6 +699,16 @@ function renderFootnoteContent(footnote, contentWidth, doc, context) {
696
699
  wrapper.style.position = "relative";
697
700
  wrapper.style.width = `${contentWidth}px`;
698
701
  wrapper.style.height = `${content.height}px`;
702
+ const shown = noteWindow ? doc.createElement("div") : wrapper;
703
+ if (noteWindow) {
704
+ shown.className = "layout-footnote-window";
705
+ shown.style.position = "relative";
706
+ shown.style.overflow = "hidden";
707
+ shown.style.width = `${contentWidth}px`;
708
+ shown.style.height = `${noteWindow.to - noteWindow.from}px`;
709
+ wrapper.style.top = `${-noteWindow.from}px`;
710
+ shown.append(wrapper);
711
+ }
699
712
  const renderContext = {
700
713
  pageNumber: context?.pageNumber ?? 0,
701
714
  ...context?.pageNumberFormat === void 0 ? {} : { pageNumberFormat: context.pageNumberFormat },
@@ -719,7 +732,7 @@ function renderFootnoteContent(footnote, contentWidth, doc, context) {
719
732
  wrapper.append(blockEl);
720
733
  y += getFootnoteMeasureHeight(measure);
721
734
  }
722
- return wrapper;
735
+ return shown;
723
736
  }
724
737
  function renderFootnoteBlock(block, measure, contentWidth, y, context, doc) {
725
738
  const renderBlock = stripFlowBlockPmAnchors(block);
@@ -1071,9 +1084,9 @@ function renderPage(page, context, options = {}) {
1071
1084
  }
1072
1085
  renderFlowedNoteSeparators(page, contentEl, doc);
1073
1086
  if (options.footnoteArea && options.footnoteArea.length > 0) {
1074
- const fnAreaEl = renderFootnoteArea(options.footnoteArea, contentWidth, doc, context);
1087
+ const fnAreaEl = renderFootnoteArea(options.footnoteArea, contentWidth, doc, context, page.footnoteWindows);
1075
1088
  fnAreaEl.style.position = "absolute";
1076
- const reservedHeight = Math.max(page.footnoteReservedHeight ?? 0, calculateFootnoteAreaRenderHeight(options.footnoteArea));
1089
+ const reservedHeight = Math.max(page.footnoteReservedHeight ?? 0, calculateFootnoteAreaRenderHeight(options.footnoteArea, page.footnoteWindows));
1077
1090
  const contentAreaBottom = page.size.h - page.margins.bottom - page.margins.top;
1078
1091
  fnAreaEl.style.top = `${Math.max(-page.margins.top, contentAreaBottom - reservedHeight)}px`;
1079
1092
  fnAreaEl.style.left = "0";
@@ -1306,11 +1319,17 @@ function buildPageRenderArgs(page, totalPages, options) {
1306
1319
  * Compute a fingerprint string for a page that changes when its content changes.
1307
1320
  * Used to detect which pages need re-rendering on incremental updates.
1308
1321
  */
1309
- function computePageFingerprint(page, blockLookup) {
1310
- return computePageFingerprintInternal(page, blockLookup, { includePmPositions: true });
1322
+ function computePageFingerprint(page, blockLookup, footnotes) {
1323
+ return computePageFingerprintInternal(page, blockLookup, {
1324
+ includePmPositions: true,
1325
+ footnotes
1326
+ });
1311
1327
  }
1312
- function computePageRenderFingerprint(page, blockLookup) {
1313
- return computePageFingerprintInternal(page, blockLookup, { includePmPositions: false });
1328
+ function computePageRenderFingerprint(page, blockLookup, footnotes) {
1329
+ return computePageFingerprintInternal(page, blockLookup, {
1330
+ includePmPositions: false,
1331
+ footnotes
1332
+ });
1314
1333
  }
1315
1334
  const pageMarginsFingerprint = (margins) => [
1316
1335
  margins.top,
@@ -1330,7 +1349,14 @@ function computePageFingerprintInternal(page, blockLookup, options) {
1330
1349
  if (page.sectionIndex !== void 0) parts.push(`si:${page.sectionIndex}`);
1331
1350
  if (page.sectionPageNumber !== void 0) parts.push(`sp:${page.sectionPageNumber}`);
1332
1351
  if (page.headerFooterRefs) parts.push(`hf:${JSON.stringify(page.headerFooterRefs)}`);
1333
- if (page.footnoteReservedHeight) parts.push(`fn:${page.footnoteReservedHeight}`);
1352
+ if (page.footnoteReservedHeight) {
1353
+ parts.push(`fn:${page.footnoteReservedHeight}`);
1354
+ if (page.footnoteWindows) parts.push(`fnw:${JSON.stringify(page.footnoteWindows)}`);
1355
+ }
1356
+ for (const note of options.footnotes ?? []) {
1357
+ parts.push(`fnc:${note.noteId ?? ""},${note.displayNumber},${note.text ?? ""}`);
1358
+ for (const block of note.content?.blocks ?? []) parts.push(computeContentFingerprint(block), computeAnnotationFingerprint(block, false));
1359
+ }
1334
1360
  for (const frag of page.fragments) {
1335
1361
  let fp = `${frag.kind}:${frag.blockId},${frag.x},${frag.y},${frag.width},${frag.height}`;
1336
1362
  if (options.includePmPositions && frag.pmStart !== void 0) fp += `,ps:${frag.pmStart}`;
@@ -1341,6 +1367,7 @@ function computePageFingerprintInternal(page, blockLookup, options) {
1341
1367
  if (frag.headerRowCount !== void 0) fp += `,hr:${frag.headerRowCount}`;
1342
1368
  if (frag.topClip !== void 0) fp += `,tc:${frag.topClip}`;
1343
1369
  if (frag.bottomClip !== void 0) fp += `,bc:${frag.bottomClip}`;
1370
+ if (frag.cellLineBand !== void 0) fp += `,clb:${frag.cellLineBand.shownThrough}:${frag.cellLineBand.cut}:${JSON.stringify(frag.cellLineBand.cells)}`;
1344
1371
  if (frag.continuesFromPrev) fp += ",cfp";
1345
1372
  if (frag.continuesOnNext) fp += ",con";
1346
1373
  }
@@ -1583,7 +1610,8 @@ function renderPages(pages, container, options = {}) {
1583
1610
  prev.element.dataset["pageNumber"] = String(page.number);
1584
1611
  continue;
1585
1612
  }
1586
- const newFp = computePageFingerprint(page, options.blockLookup);
1613
+ const pageFootnotes = options.footnotesByPage?.get(page.number);
1614
+ const newFp = computePageFingerprint(page, options.blockLookup, pageFootnotes);
1587
1615
  if (prev.fingerprint === newFp && !totalPagesChanged && !fieldContextChanged) continue;
1588
1616
  const shell = prev.element;
1589
1617
  if (totalPagesChanged || fieldContextChanged) {
@@ -1596,7 +1624,7 @@ function renderPages(pages, container, options = {}) {
1596
1624
  shell.dataset["pageNumber"] = String(page.number);
1597
1625
  continue;
1598
1626
  }
1599
- const newRenderFp = computePageRenderFingerprint(page, options.blockLookup);
1627
+ const newRenderFp = computePageRenderFingerprint(page, options.blockLookup, pageFootnotes);
1600
1628
  if (!(!(prev.renderFingerprint !== newRenderFp) && syncRenderedPmPositionData(shell, oldPage, data.page))) repopulatePageContent(shell, prevDataMap, totalPages, options);
1601
1629
  prev.fingerprint = newFp;
1602
1630
  prev.renderFingerprint = newRenderFp;
@@ -1929,8 +1957,9 @@ function shiftNumericDatasetValue(element, key, delta) {
1929
1957
  function syncPageShellFingerprints(shell, data, options) {
1930
1958
  const pageState = shell.parentElement?.__pageRenderState?.pageStates[data.index];
1931
1959
  if (!pageState || pageState.element !== shell) return;
1932
- pageState.fingerprint = computePageFingerprint(data.page, options.blockLookup);
1933
- pageState.renderFingerprint = computePageRenderFingerprint(data.page, options.blockLookup);
1960
+ const pageFootnotes = options.footnotesByPage?.get(data.page.number);
1961
+ pageState.fingerprint = computePageFingerprint(data.page, options.blockLookup, pageFootnotes);
1962
+ pageState.renderFingerprint = computePageRenderFingerprint(data.page, options.blockLookup, pageFootnotes);
1934
1963
  }
1935
1964
  /**
1936
1965
  * Find the page shell whose layout fragments cover (or are nearest
@@ -523,7 +523,7 @@ const continuationRowBottomBorderOffsets = (fragment, block, measure, cellGrid)
523
523
  snapAfterRow
524
524
  });
525
525
  };
526
- function renderTableRow({ row, rowMeasure, rowIndex, y, columnWidths, totalRows, context, doc, rowYPositions, isFirstRowInFragment, bidi = false, columnsPinned = false, cellGrid, cellPlacements, cellSpacing, contentClip, visibleBand, pageContentPosition, inlineOffset = 0, bottomBorderOffset = 0 }) {
526
+ function renderTableRow({ row, rowMeasure, rowIndex, y, columnWidths, totalRows, context, doc, rowYPositions, isFirstRowInFragment, bidi = false, columnsPinned = false, cellGrid, cellPlacements, cellSpacing, contentClip, cellBands, visibleBand, pageContentPosition, inlineOffset = 0, bottomBorderOffset = 0 }) {
527
527
  const bordersSeparated = (cellSpacing ?? 0) > 0;
528
528
  const rowEl = doc.createElement("div");
529
529
  rowEl.className = TABLE_CLASS_NAMES.row;
@@ -560,9 +560,10 @@ function renderTableRow({ row, rowMeasure, rowIndex, y, columnWidths, totalRows,
560
560
  const drawLeft = bordersSeparated || isFirstCol || !hasVisibleBorder(leftCell?.borders?.right);
561
561
  const spacing = getTableCellSpacingInsetsY(cellSpacing, rowIndex, rowSpan, totalRows);
562
562
  const boxHeight = Math.max(0, cellHeight - spacing.top - spacing.bottom);
563
- const boxClip = contentClip ? {
564
- top: contentClip.top - spacing.top,
565
- bottom: contentClip.bottom - spacing.top
563
+ const cellClip = cellBands?.[cellIndex] ?? contentClip;
564
+ const boxClip = cellClip ? {
565
+ top: cellClip.top - spacing.top,
566
+ bottom: cellClip.bottom - spacing.top
566
567
  } : void 0;
567
568
  const paintBottomBorderSeparately = bottomBorderOffset > 0 && hasVisibleBorder(cell.borders?.bottom);
568
569
  const cellEl = renderTableCell({
@@ -740,7 +741,9 @@ function renderTableFragment(fragment, block, measure, context, options = {}) {
740
741
  top: rowTopClip ?? 0,
741
742
  bottom: rowBottomClip ?? rowMeasure.height
742
743
  } : void 0;
744
+ const cellBands = rowIndex === fragment.fromRow ? fragment.cellLineBand?.cells : void 0;
743
745
  const rowEl = renderTableRow({
746
+ ...cellBands ? { cellBands } : {},
744
747
  row,
745
748
  rowMeasure,
746
749
  rowIndex,
@@ -4,7 +4,11 @@ import { Subscribable } from "./Subscribable.js";
4
4
  export type AutoSaveStatus = "idle" | "saving" | "saved" | "error";
5
5
  /** Configuration for {@link AutoSaveManager}. */
6
6
  export type AutoSaveManagerOptions = {
7
- /** Storage key for localStorage (default: 'docx-editor-autosave'). */
7
+ /**
8
+ * Storage key for localStorage (default: 'docx-editor-autosave'). Recovery
9
+ * offers whatever this key holds, so a host whose origin serves several
10
+ * users or documents should derive the key from both.
11
+ */
8
12
  storageKey?: string;
9
13
  /** Save interval in milliseconds (default: 30000 - 30 seconds). */
10
14
  interval?: number;
@@ -1,5 +1,5 @@
1
1
  import { replaceEligibility } from "../utils/findReplace.js";
2
- import { replaceTextInDocument } from "../utils/replaceText.js";
2
+ import { replaceTextInDocument, replaceTextRangesInDocument } from "../utils/replaceText.js";
3
3
  // src/managers/FindReplaceManager.ts
4
4
  /**
5
5
  * The cursor index after stepping `direction` over `totalCount` matches,
@@ -103,19 +103,12 @@ var FindReplaceManager = class {
103
103
  replaceAll(document, matches, replaceText) {
104
104
  if (matches.length === 0) return null;
105
105
  const eligibleMatches = matches.filter((match) => replaceEligibility(match).status === "allowed");
106
- let skippedCount = matches.length - eligibleMatches.length;
107
- let replacedCount = 0;
108
106
  const sortedMatches = [...eligibleMatches].toSorted((a, b) => {
109
107
  if (a.paragraphIndex !== b.paragraphIndex) return b.paragraphIndex - a.paragraphIndex;
110
108
  return b.startOffset - a.startOffset;
111
109
  });
112
- let nextDocument = document;
113
- for (const match of sortedMatches) try {
114
- nextDocument = replaceTextInDocument(nextDocument, toReplaceRange(match), replaceText);
115
- replacedCount++;
116
- } catch {
117
- skippedCount++;
118
- }
110
+ const { document: nextDocument, replacedCount, failedCount } = replaceTextRangesInDocument(document, sortedMatches.map((match) => toReplaceRange(match)), replaceText);
111
+ const skippedCount = matches.length - eligibleMatches.length + failedCount;
119
112
  if (replacedCount > 0) this.result = null;
120
113
  return {
121
114
  document: nextDocument,
@@ -24,6 +24,13 @@ export declare function escapeInline(text: string): string;
24
24
  * line.
25
25
  */
26
26
  export declare function escapeTableCell(text: string): string;
27
+ /**
28
+ * CommonMark strips the blanks at the start of a line and takes the blanks
29
+ * before a line ending as the hard break's own syntax, so text blanks next to
30
+ * an inline break would be lost on reading. They are written as character
31
+ * references instead, which read back as the blanks they are.
32
+ */
33
+ export declare const protectBreakBlanks: (text: string) => string;
27
34
  /** Single-line Markdown blocks express inline breaks without their two-space syntax. */
28
35
  export declare const inlineBreaksToHtml: (text: string) => string;
29
36
  export declare function escapeLinkUrl(url: string): string;
@@ -32,4 +39,16 @@ export declare function escapeLinkUrl(url: string): string;
32
39
  * first, then the brackets that would confuse the link parser, and collapse
33
40
  * newlines so the alt stays single-line.
34
41
  */
35
- export declare function escapeAltText(text: string): string;
42
+ export declare function escapeAltText(text: string): string;
43
+ /**
44
+ * A plain paragraph whose visible text begins with markdown block syntax (e.g.
45
+ * `# Not a heading`, `- value`, `1. value`, `> quote`) would be reclassified as
46
+ * a heading/list/blockquote on re-parse, even though Word carries no matching
47
+ * style/list metadata. Escape the leading marker so literal text round-trips.
48
+ */
49
+ export declare function escapeLeadingBlockMarker(text: string): string;
50
+ /**
51
+ * Text that is not Markdown (a `text/plain` alternative-format chunk) as a
52
+ * Markdown block that reads back as the same literal text.
53
+ */
54
+ export declare const escapePlainTextBlock: (text: string) => string;
@@ -32,9 +32,37 @@ function escapeInline(text) {
32
32
  function escapeTableCell(text) {
33
33
  return inlineBreaksToHtml(text.replace(/\|/gu, "|"));
34
34
  }
35
+ const TWO_SPACE_BREAK = " \n";
36
+ const BACKSLASH_BREAK = "\\\n";
37
+ /** A blank as a character reference, which no line-edge rule strips. */
38
+ const BLANK_REFERENCES = {
39
+ " ": " ",
40
+ " ": "	"
41
+ };
42
+ const blankReferences = (blanks) => blanks.replace(/[ \t]/gu, (blank) => BLANK_REFERENCES[blank] ?? blank);
43
+ /**
44
+ * CommonMark strips the blanks at the start of a line and takes the blanks
45
+ * before a line ending as the hard break's own syntax, so text blanks next to
46
+ * an inline break would be lost on reading. They are written as character
47
+ * references instead, which read back as the blanks they are.
48
+ */
49
+ const protectBreakBlanks = (text) => {
50
+ const lines = text.split(TWO_SPACE_BREAK);
51
+ let out = "";
52
+ lines.forEach((line, index) => {
53
+ const last = index === lines.length - 1;
54
+ const start = index === 0 ? 0 : /^[ \t]*/u.exec(line)?.[0].length ?? 0;
55
+ const end = last ? line.length : line.length - (/[ \t]*$/u.exec(line)?.[0].length ?? 0);
56
+ out += end <= start ? blankReferences(line) : blankReferences(line.slice(0, start)) + line.slice(start, end) + blankReferences(line.slice(end));
57
+ if (last) return;
58
+ out += line.length === 0 ? BACKSLASH_BREAK : TWO_SPACE_BREAK;
59
+ });
60
+ return out;
61
+ };
35
62
  /** Single-line Markdown blocks express inline breaks without their two-space syntax. */
36
63
  const inlineBreaksToHtml = (text) => text.split(/\r?\n/u).map((line, index, lines) => {
37
64
  if (index === lines.length - 1) return line;
65
+ if (line === "\\") return "";
38
66
  let end = line.length;
39
67
  while (end > 0 && line.at(end - 1) === " ") end--;
40
68
  return line.slice(0, end);
@@ -61,4 +89,18 @@ function escapeLinkUrl(url) {
61
89
  function escapeAltText(text) {
62
90
  return text.replace(/(?<ch>[\\[\]])/gu, "\\$<ch>").replace(/\r?\n/gu, " ");
63
91
  }
64
- export { escapeAltText, escapeInline, escapeLinkUrl, escapeTableCell, inlineBreaksToHtml };
92
+ /**
93
+ * A plain paragraph whose visible text begins with markdown block syntax (e.g.
94
+ * `# Not a heading`, `- value`, `1. value`, `> quote`) would be reclassified as
95
+ * a heading/list/blockquote on re-parse, even though Word carries no matching
96
+ * style/list metadata. Escape the leading marker so literal text round-trips.
97
+ */
98
+ function escapeLeadingBlockMarker(text) {
99
+ return text.replace(/^(?<ws>[ \t]*)(?<marker>[#>=])/gmu, "$<ws>\\$<marker>").replace(/^(?<ws>[ \t]*)(?<marker>[-+*])(?=[ \t]|$)/gmu, "$<ws>\\$<marker>").replace(/^(?<ws>[ \t]*)-(?=[- \t]*$)/gmu, "$<ws>\\-").replace(/^(?<ws>[ \t]*)(?<num>\d{1,9})(?<marker>[.)])(?<after>[ \t])/gmu, "$<ws>$<num>\\$<marker>$<after>");
100
+ }
101
+ /**
102
+ * Text that is not Markdown (a `text/plain` alternative-format chunk) as a
103
+ * Markdown block that reads back as the same literal text.
104
+ */
105
+ const escapePlainTextBlock = (text) => escapeLeadingBlockMarker(escapeInline(text));
106
+ export { escapeAltText, escapeInline, escapeLeadingBlockMarker, escapeLinkUrl, escapePlainTextBlock, escapeTableCell, inlineBreaksToHtml, protectBreakBlanks };
@@ -1,6 +1,7 @@
1
1
  import { ALT_CHUNK_READER_DIAGNOSTIC, isAltChunkMarkup } from "../docx/altChunk.js";
2
2
  import { OPAQUE_REVISION_CARRIER_READER_DIAGNOSTIC, isOpaqueNestedRowMarkup, opaqueRevisionCarrierName } from "../docx/opaqueCarrier.js";
3
3
  import { projectAcceptedBlocks } from "../internal/acceptedBlockProjection.js";
4
+ import { escapePlainTextBlock } from "./escape.js";
4
5
  import { pushWarning } from "./internals.js";
5
6
  import { renderParagraphBlock } from "./renderParagraph.js";
6
7
  import { renderTable } from "./renderTable.js";
@@ -43,7 +44,7 @@ function renderBlocks(ctx, pkg, blocks) {
43
44
  }
44
45
  case "preservedBlock": {
45
46
  let markdown;
46
- if (isAltChunkMarkup(block.xml)) markdown = block.readerText === void 0 ? ALT_CHUNK_READER_DIAGNOSTIC : `${ALT_CHUNK_READER_DIAGNOSTIC}\n\n${block.readerText}`;
47
+ if (isAltChunkMarkup(block.xml)) markdown = block.readerText === void 0 ? ALT_CHUNK_READER_DIAGNOSTIC : `${ALT_CHUNK_READER_DIAGNOSTIC}\n\n${escapePlainTextBlock(block.readerText)}`;
47
48
  else if (opaqueRevisionCarrierName(block.xml) !== void 0) markdown = OPAQUE_REVISION_CARRIER_READER_DIAGNOSTIC;
48
49
  else if (isOpaqueNestedRowMarkup(block.xml)) markdown = "[Unsupported nested w:tr content]";
49
50
  else return { type: "delimiter" };
@@ -55,6 +56,8 @@ function renderBlocks(ctx, pkg, blocks) {
55
56
  }
56
57
  case "bookmarkStart":
57
58
  case "bookmarkEnd":
59
+ case "commentRangeStart":
60
+ case "commentRangeEnd":
58
61
  case "moveFromRangeStart":
59
62
  case "moveFromRangeEnd":
60
63
  case "moveToRangeStart":
@@ -1,6 +1,6 @@
1
1
  import { isQuoteStyle, resolveHeadingLevel } from "../docx/builtInStyles.js";
2
2
  import { countParagraphList } from "./countParagraphList.js";
3
- import { inlineBreaksToHtml } from "./escape.js";
3
+ import { escapeLeadingBlockMarker, inlineBreaksToHtml, protectBreakBlanks } from "./escape.js";
4
4
  import { renderParagraphInline } from "./renderRuns.js";
5
5
  // src/markdown/renderParagraph.ts
6
6
  /**
@@ -33,12 +33,14 @@ function renderParagraph(ctx, pkg, para) {
33
33
  */
34
34
  function renderParagraphBlock(ctx, pkg, para) {
35
35
  const { visibleList, label } = countParagraphList(ctx, pkg, para);
36
- const inline = renderParagraphInline(ctx, pkg, para.content, para.paraId);
36
+ const written = renderParagraphInline(ctx, pkg, para.content, para.paraId);
37
+ const blank = written.trim().length === 0;
38
+ const inline = protectBreakBlanks(written);
37
39
  const styleId = para.formatting?.styleId;
38
40
  const headingLevel = markdownHeadingLevel(ctx, para);
39
41
  if (headingLevel !== void 0) {
40
42
  ctx.listIndentWidths = [];
41
- if (!inline || !inline.trim() && label === void 0) return {
43
+ if (!inline || blank && label === void 0) return {
42
44
  type: "paragraph",
43
45
  markdown: ""
44
46
  };
@@ -49,7 +51,12 @@ function renderParagraphBlock(ctx, pkg, para) {
49
51
  type: "paragraph"
50
52
  };
51
53
  }
52
- if (visibleList && label !== void 0) return renderListItem(ctx, visibleList, label, inline);
54
+ if (visibleList && label !== void 0) return renderListItem(ctx, {
55
+ list: visibleList,
56
+ label,
57
+ inline,
58
+ blank
59
+ });
53
60
  ctx.listIndentWidths = [];
54
61
  if (isQuoteStyle(styleId, ctx.builtInStyles)) return {
55
62
  markdown: inline.split("\n").map((line) => `> ${line}`).join("\n"),
@@ -68,15 +75,6 @@ function markdownHeadingLevel(ctx, para) {
68
75
  }, ctx.builtInStyles);
69
76
  }
70
77
  /**
71
- * A plain paragraph whose visible text begins with markdown block syntax (e.g.
72
- * `# Not a heading`, `- value`, `1. value`, `> quote`) would be reclassified as
73
- * a heading/list/blockquote on re-parse, even though Word carries no matching
74
- * style/list metadata. Escape the leading marker so literal text round-trips.
75
- */
76
- function escapeLeadingBlockMarker(text) {
77
- return text.replace(/^(?<ws>[ \t]*)(?<marker>[#>=])/gmu, "$<ws>\\$<marker>").replace(/^(?<ws>[ \t]*)(?<marker>[-+*])(?=[ \t]|$)/gmu, "$<ws>\\$<marker>").replace(/^(?<ws>[ \t]*)-(?=[- \t]*$)/gmu, "$<ws>\\-").replace(/^(?<ws>[ \t]*)(?<num>\d{1,9})(?<marker>[.)])(?<after>[ \t])/gmu, "$<ws>$<num>\\$<marker>$<after>");
78
- }
79
- /**
80
78
  * Only emitted Markdown ancestors contribute columns. OOXML levels may skip
81
79
  * ancestors or resume after prose; inventing those columns creates code blocks.
82
80
  */
@@ -85,19 +83,7 @@ function listIndentWidth(ctx, level) {
85
83
  for (let ancestor = 0; ancestor < level; ancestor++) width += ctx.listIndentWidths[ancestor] ?? 0;
86
84
  return width;
87
85
  }
88
- /**
89
- * A list item line with the label the page shows (`1.`, `a)`, `i.`), counted
90
- * in document order across the whole render, list items inside tables and
91
- * block SDTs included. A bullet is Markdown's `-`.
92
- *
93
- * The indent before the marker is not a fixed two spaces: CommonMark keeps a
94
- * child nested under its parent only when it starts at or past the column
95
- * where the parent item's content begins, which is the width of the parent's
96
- * marker plus its one trailing space (`1. ` is 3 columns, `10. ` is 4, `- ` is
97
- * 2). `ctx.listIndentWidths` is updated with this item's own marker width so
98
- * a following, deeper item can indent correctly under it.
99
- */
100
- function renderListItem(ctx, list, label, inline) {
86
+ function renderListItem(ctx, { list, label, inline, blank }) {
101
87
  if (!(list.isBullet || /^\d{1,9}[.)]$/u.test(label))) {
102
88
  ctx.listIndentWidths = [];
103
89
  return {
@@ -112,7 +98,7 @@ function renderListItem(ctx, list, label, inline) {
112
98
  return {
113
99
  type: "listItem",
114
100
  markdown: `${indent}${marker}${escapeLeadingBlockMarker(inline)}`.trimEnd(),
115
- separation: inline.trim().length === 0 ? "loose" : "tight"
101
+ separation: blank ? "loose" : "tight"
116
102
  };
117
103
  }
118
104
  export { renderParagraph, renderParagraphBlock };
@@ -3,7 +3,7 @@ import { getHyperlinkRuns } from "../docx/hyperlinkParser.js";
3
3
  import { OPAQUE_REVISION_CARRIER_READER_DIAGNOSTIC, isOpaqueNestedRowMarkup, opaqueRevisionCarrierName } from "../docx/opaqueCarrier.js";
4
4
  import { RELATIONSHIP_TYPES, resolveRelationshipIdOfType } from "../docx/relsParser.js";
5
5
  import { decodeOoxmlSymbolCharacter } from "../utils/ooxmlSymbol.js";
6
- import { escapeTableCell } from "./escape.js";
6
+ import { escapeTableCell, inlineBreaksToHtml } from "./escape.js";
7
7
  import { registerImage } from "./images.js";
8
8
  import { numberNoteReference, pushWarning } from "./internals.js";
9
9
  import { renderParagraph } from "./renderParagraph.js";
@@ -90,6 +90,8 @@ function renderGfmCell(ctx, pkg, cell) {
90
90
  break;
91
91
  case "bookmarkStart":
92
92
  case "bookmarkEnd":
93
+ case "commentRangeStart":
94
+ case "commentRangeEnd":
93
95
  case "moveFromRangeStart":
94
96
  case "moveFromRangeEnd":
95
97
  case "moveToRangeStart":
@@ -167,12 +169,14 @@ function renderHtmlCell(ctx, pkg, cell) {
167
169
  renderBlocks(item.content);
168
170
  break;
169
171
  case "preservedBlock":
170
- if (isAltChunkMarkup(item.xml)) parts.push(item.readerText === void 0 ? ALT_CHUNK_READER_DIAGNOSTIC : `${ALT_CHUNK_READER_DIAGNOSTIC} ${item.readerText}`);
172
+ if (isAltChunkMarkup(item.xml)) parts.push(item.readerText === void 0 ? ALT_CHUNK_READER_DIAGNOSTIC : `${ALT_CHUNK_READER_DIAGNOSTIC} ${inlineBreaksToHtml(escapeHtml(item.readerText))}`);
171
173
  else if (opaqueRevisionCarrierName(item.xml) !== void 0) parts.push(OPAQUE_REVISION_CARRIER_READER_DIAGNOSTIC);
172
174
  else if (isOpaqueNestedRowMarkup(item.xml)) parts.push("[Unsupported nested w:tr content]");
173
175
  break;
174
176
  case "bookmarkStart":
175
177
  case "bookmarkEnd":
178
+ case "commentRangeStart":
179
+ case "commentRangeEnd":
176
180
  case "moveFromRangeStart":
177
181
  case "moveFromRangeEnd":
178
182
  case "moveToRangeStart":
@@ -55,6 +55,7 @@ function inlineText(content) {
55
55
  break;
56
56
  case "hyperlink":
57
57
  for (const child of item.children) if (child.type === "run") out += runText(child);
58
+ else if (child.type === "complexField") out += inlineText(child.fieldResult);
58
59
  break;
59
60
  case "complexField":
60
61
  out += inlineText(item.fieldResult);
@@ -22,5 +22,21 @@ export type PdfImageSamples = {
22
22
  readonly decode?: readonly number[];
23
23
  readonly alpha?: PdfImageAlpha;
24
24
  };
25
- export declare const decodeImage: (source: DisplayImageSource) => Result<PdfImageSamples, PdfImageError>;
25
+ /**
26
+ * Largest PNG raster decoded for one image. A PNG's IDAT can compress an
27
+ * empty raster about a thousandfold, so the encoded size says little about
28
+ * the decode: 64 MP of RGBA is 256 MB per raster copy before the alpha split
29
+ * and the re-deflate. Matches the per-image TIFF ceiling at import.
30
+ */
31
+ export declare const MAX_PDF_PNG_PIXELS = 64000000;
32
+ /**
33
+ * Pixels decoded across every PNG in one PDF. The per-image ceiling bounds a
34
+ * single decode; without a running total many large images still add up.
35
+ */
36
+ export declare const MAX_PDF_DOCUMENT_PNG_PIXELS = 256000000;
37
+ /**
38
+ * Decode one image for painting. `maxPngPixels` is what remains of the
39
+ * document's PNG pixel budget; JPEG passes through undecoded and spends none.
40
+ */
41
+ export declare const decodeImage: (source: DisplayImageSource, maxPngPixels?: number) => Result<PdfImageSamples, PdfImageError>;
26
42
  export {};
@@ -48,6 +48,18 @@ const FULLY_OPAQUE = 255;
48
48
  const EIGHT_BIT = 8;
49
49
  /** IHDR interlace method 1: the only one PNG defines besides "none". */
50
50
  const ADAM7_INTERLACE = 1;
51
+ /**
52
+ * Largest PNG raster decoded for one image. A PNG's IDAT can compress an
53
+ * empty raster about a thousandfold, so the encoded size says little about
54
+ * the decode: 64 MP of RGBA is 256 MB per raster copy before the alpha split
55
+ * and the re-deflate. Matches the per-image TIFF ceiling at import.
56
+ */
57
+ const MAX_PDF_PNG_PIXELS = 64e6;
58
+ /**
59
+ * Pixels decoded across every PNG in one PDF. The per-image ceiling bounds a
60
+ * single decode; without a running total many large images still add up.
61
+ */
62
+ const MAX_PDF_DOCUMENT_PNG_PIXELS = 256e6;
51
63
  const toHex = (bytes) => {
52
64
  let out = "";
53
65
  for (const byte of bytes) out += byte.toString(16).padStart(2, "0").toUpperCase();
@@ -281,7 +293,7 @@ const expandIndices = ({ rows, bytesPerRow, width, height, bitDepth }) => {
281
293
  }
282
294
  return out;
283
295
  };
284
- const decodePng = (bytes) => {
296
+ const decodePng = (bytes, maxPixels) => {
285
297
  const chunks = readPngChunks(bytes);
286
298
  if (chunks.isErr()) return Result.err(chunks.error);
287
299
  const { header, palette, transparency, pixels } = chunks.value;
@@ -292,6 +304,8 @@ const decodePng = (bytes) => {
292
304
  const colorType = header[9] ?? 0;
293
305
  const interlace = header[12] ?? 0;
294
306
  if (width === 0 || height === 0) return Result.err(new PdfImageError({ message: "PNG has a zero dimension" }));
307
+ const pixelLimit = Math.min(maxPixels, MAX_PDF_PNG_PIXELS);
308
+ if (width * height > pixelLimit) return Result.err(new PdfImageError({ message: `PNG is ${String(width)}x${String(height)} pixels, above the ${String(pixelLimit)} pixels allowed` }));
295
309
  if (interlace !== 0 && interlace !== ADAM7_INTERLACE) return Result.err(new PdfImageError({ message: `unknown PNG interlace method ${String(interlace)}` }));
296
310
  const channels = CHANNELS_PER_COLOR_TYPE[colorType];
297
311
  if (channels === void 0) return Result.err(new PdfImageError({ message: `unknown PNG colour type ${String(colorType)}` }));
@@ -566,9 +580,13 @@ const decodeJpeg = (bytes) => {
566
580
  }
567
581
  return Result.err(new PdfImageError({ message: "JPEG has no frame header" }));
568
582
  };
569
- const decodeImage = (source) => {
583
+ /**
584
+ * Decode one image for painting. `maxPngPixels` is what remains of the
585
+ * document's PNG pixel budget; JPEG passes through undecoded and spends none.
586
+ */
587
+ const decodeImage = (source, maxPngPixels = MAX_PDF_PNG_PIXELS) => {
570
588
  switch (source.format) {
571
- case "png": return decodePng(source.bytes);
589
+ case "png": return decodePng(source.bytes, maxPngPixels);
572
590
  case "jpeg": return decodeJpeg(source.bytes);
573
591
  case "svg": return Result.err(new PdfImageError({ message: "SVG images are not supported in PDF" }));
574
592
  default: {
@@ -577,4 +595,4 @@ const decodeImage = (source) => {
577
595
  }
578
596
  }
579
597
  };
580
- export { PdfImageError, decodeImage };
598
+ export { MAX_PDF_DOCUMENT_PNG_PIXELS, MAX_PDF_PNG_PIXELS, PdfImageError, decodeImage };
@@ -2,7 +2,7 @@ import { getShaper } from "../shaping/shaper.js";
2
2
  import { encodeUtf8 } from "../utils/textEncoding.js";
3
3
  import { collectResources, renderContentStream } from "./contentStream.js";
4
4
  import { prepareFonts } from "./fonts.js";
5
- import { decodeImage } from "./images.js";
5
+ import { MAX_PDF_DOCUMENT_PNG_PIXELS, decodeImage } from "./images.js";
6
6
  import { createPdfDocument, pdfArray, pdfAsciiString, pdfDict, pdfFlateStream, pdfName, pdfNull, pdfNumber, pdfNumberArray, pdfStream, pdfTextString } from "./objects.js";
7
7
  import { displayPointToPdf, pxToPt } from "./pageSpace.js";
8
8
  import { collectUsage, paintPage } from "./paint.js";
@@ -265,14 +265,16 @@ const writePdf = async (list, options) => {
265
265
  });
266
266
  if (options.strictGlyphCoverage === true && unencodable.length > 0) return Result.err(new WritePdfError({ message: describeUnencodable(unencodable) }));
267
267
  const imageRefs = /* @__PURE__ */ new Map();
268
+ let remainingPngPixels = MAX_PDF_DOCUMENT_PNG_PIXELS;
268
269
  for (const imageIndex of [...usage.value.imageIndices].sort((left, right) => left - right)) {
269
270
  const source = list.images[imageIndex];
270
271
  if (source === void 0) return Result.err(new WritePdfError({ message: `image ${String(imageIndex)} is outside the image table` }));
271
- const decoded = decodeImage(source);
272
+ const decoded = decodeImage(source, remainingPngPixels);
272
273
  if (decoded.isErr()) return Result.err(new WritePdfError({
273
274
  message: `image ${String(imageIndex)} could not be decoded: ${decoded.error.message}`,
274
275
  cause: decoded.error
275
276
  }));
277
+ if (source.format === "png") remainingPngPixels -= decoded.value.widthPx * decoded.value.heightPx;
276
278
  imageRefs.set(imageIndex, buildImageObject(document, decoded.value));
277
279
  }
278
280
  const outlineRoots = buildOutlineTree(list.outline, document);
@@ -978,6 +978,7 @@ const readCommentMarkAttrs = (mark) => {
978
978
  const issues = [];
979
979
  expectMarkType(mark, "comment", issues);
980
980
  requiredNumber(attrs, "commentId", "comment.attrs.commentId", issues);
981
+ optionalBoolean(attrs, "point", "comment.attrs.point", issues);
981
982
  return attrsResult(attrs, issues);
982
983
  };
983
984
  const expectCommentMarkAttrs = (mark) => expectCachedMarkAttrs(mark, commentAttrsCache, readCommentMarkAttrs, "comment attrs");
@@ -1,9 +1,47 @@
1
1
  import { document_d_exports } from "../types/document.js";
2
+ import { TableCellFormatting, TableFormatting, TableRowFormatting } from "../types/formatting.js";
2
3
  import { Node } from "prosemirror-model";
3
4
  import { Command, EditorState } from "prosemirror-state";
4
- import { FormattingPatch, ParagraphPropsPatch, RunPropsPatch } from "@stll/docx-core/ops";
5
+ import { FormattingPatch, ParagraphPropsPatch, RunPropsPatch, TableBlockIntentOperation, TableIntentOperation, TableRowIntentOperation } from "@stll/docx-core/ops";
6
+ /** One table, row or cell, addressed by a position inside its first paragraph. */
7
+ export type CanonicalTableFormatTarget = {
8
+ scope: "table";
9
+ at: number;
10
+ patch: FormattingPatch<TableFormatting>;
11
+ } | {
12
+ scope: "row";
13
+ at: number;
14
+ patch: FormattingPatch<TableRowFormatting>;
15
+ } | {
16
+ scope: "cell";
17
+ at: number;
18
+ patch: FormattingPatch<TableCellFormatting>;
19
+ };
20
+ type WithoutTableTarget<Operation> = Operation extends unknown ? Omit<Operation, "story" | "blockId"> : never;
21
+ /**
22
+ * A change to a table's columns, cells or grid. The session addresses the
23
+ * table through a paragraph of its own; the engine derives fresh ids.
24
+ */
25
+ export type CanonicalTableEdit = WithoutTableTarget<Exclude<TableIntentOperation, {
26
+ type: "setCellProps" | "setRowProps" | "setTableProps";
27
+ }>>;
5
28
  /** Command meaning before canonical positions are resolved by the session. */
6
29
  export type CanonicalCommandIntent = {
30
+ type: "formatTable";
31
+ targets: readonly CanonicalTableFormatTarget[];
32
+ } | {
33
+ type: "editTable";
34
+ at: number;
35
+ edit: CanonicalTableEdit;
36
+ } | {
37
+ type: "editTableBlock";
38
+ at: number;
39
+ edit: WithoutTableTarget<TableBlockIntentOperation>;
40
+ } | {
41
+ type: "editTableRow";
42
+ at: number;
43
+ edit: WithoutTableTarget<TableRowIntentOperation>;
44
+ } | {
7
45
  type: "generateTOC";
8
46
  at: number;
9
47
  title: string;