@stll/folio-core 0.74.0 → 0.76.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 (174) hide show
  1. package/dist/ai-edits/clean-text.d.ts +4 -1
  2. package/dist/ai-edits/clean-text.js +21 -7
  3. package/dist/ai-edits/headless.d.ts +7 -3
  4. package/dist/ai-edits/headless.js +36 -21
  5. package/dist/ai-edits/note-references.d.ts +1 -1
  6. package/dist/ai-edits/note-references.js +1 -1
  7. package/dist/ai-edits/pending-suggestions.d.ts +9 -7
  8. package/dist/ai-edits/pending-suggestions.js +135 -90
  9. package/dist/ai-edits/pendingJoin.d.ts +5 -1
  10. package/dist/ai-edits/pendingJoin.js +6 -2
  11. package/dist/ai-edits/read.js +9 -3
  12. package/dist/ai-edits/retired-comment-receipts.d.ts +2 -2
  13. package/dist/ai-edits/retired-comment-receipts.js +3 -18
  14. package/dist/ai-edits/tracked-batch-fidelity.d.ts +6 -10
  15. package/dist/ai-edits/tracked-batch-fidelity.js +3 -182
  16. package/dist/ai-edits/types.d.ts +9 -4
  17. package/dist/canonical/batchCommentReferences.js +2 -1
  18. package/dist/canonical/canonicalBatchReview.d.ts +4 -1
  19. package/dist/canonical/canonicalBatchReview.js +37 -22
  20. package/dist/canonical/canonicalComments.d.ts +6 -2
  21. package/dist/canonical/canonicalComments.js +16 -6
  22. package/dist/canonical/canonicalCompilerRefusal.d.ts +2 -4
  23. package/dist/canonical/canonicalCompilerRefusal.js +20 -14
  24. package/dist/canonical/canonicalPublicOperations.js +231 -79
  25. package/dist/canonical/canonicalRefusalGrounds.d.ts +4 -0
  26. package/dist/canonical/canonicalRefusalGrounds.js +56 -0
  27. package/dist/canonical/canonicalSession.d.ts +12 -6
  28. package/dist/canonical/canonicalSession.js +119 -122
  29. package/dist/canonical/canonicalTrackedBatchFidelity.js +3 -3
  30. package/dist/compare/inline-atoms.d.ts +35 -41
  31. package/dist/compare/inline-atoms.js +2 -465
  32. package/dist/compare/section-boundary-properties.d.ts +3 -30
  33. package/dist/compare/section-boundary-properties.js +4 -72
  34. package/dist/controller/canonicalClipboard.d.ts +1 -1
  35. package/dist/controller/canonicalClipboard.js +110 -55
  36. package/dist/controller/canonicalComposition.d.ts +1 -1
  37. package/dist/controller/canonicalComposition.js +5 -5
  38. package/dist/controller/canonicalContentControlValue.js +7 -7
  39. package/dist/controller/canonicalInput.d.ts +4 -2
  40. package/dist/controller/canonicalInput.js +33 -16
  41. package/dist/controller/canonicalReview.d.ts +21 -0
  42. package/dist/controller/canonicalReview.js +44 -9
  43. package/dist/controller/canonicalStoryEditor.d.ts +2 -3
  44. package/dist/controller/canonicalStoryEditor.js +43 -25
  45. package/dist/controller/canonicalStructure.d.ts +19 -3
  46. package/dist/controller/canonicalStructure.js +182 -58
  47. package/dist/controller/deferredDisplayListPainter.d.ts +8 -0
  48. package/dist/controller/deferredDisplayListPainter.js +34 -0
  49. package/dist/controller/folioEditor.js +4 -2
  50. package/dist/controller/fontReadiness.js +50 -23
  51. package/dist/controller/headerFooterEditorManager.js +3 -17
  52. package/dist/controller/hiddenEditorApi.d.ts +24 -3
  53. package/dist/controller/hiddenEditorApi.js +2 -0
  54. package/dist/controller/hiddenEditorManager.js +135 -207
  55. package/dist/controller/layoutPipeline.d.ts +4 -86
  56. package/dist/controller/layoutPipeline.js +8 -727
  57. package/dist/controller/layoutPipelineExecution.d.ts +94 -0
  58. package/dist/controller/layoutPipelineExecution.js +730 -0
  59. package/dist/controller/noteEditorManager.js +3 -16
  60. package/dist/docx/blockContentParser.d.ts +1 -3
  61. package/dist/docx/blockContentParser.js +3 -10
  62. package/dist/docx/bulletMarkers.d.ts +8 -0
  63. package/dist/docx/bulletMarkers.js +9 -1
  64. package/dist/docx/canonicalSave.d.ts +4 -3
  65. package/dist/docx/canonicalSave.js +4 -3
  66. package/dist/docx/canonicalSessionInput.js +25 -11
  67. package/dist/docx/ensureParaIds.d.ts +31 -0
  68. package/dist/docx/ensureParaIds.js +57 -32
  69. package/dist/docx/ensureUniqueControlIds.d.ts +13 -0
  70. package/dist/docx/ensureUniqueControlIds.js +47 -29
  71. package/dist/docx/ensureUniqueRevisionIds.d.ts +13 -0
  72. package/dist/docx/ensureUniqueRevisionIds.js +52 -29
  73. package/dist/docx/listMarkerComputation.d.ts +24 -17
  74. package/dist/docx/listMarkerComputation.js +31 -60
  75. package/dist/docx/listModelNormalization.js +8 -15
  76. package/dist/docx/rezip.d.ts +16 -3
  77. package/dist/docx/rezip.js +35 -9
  78. package/dist/docx/selectiveSave.js +13 -5
  79. package/dist/docx/server/templatePlan/apply.js +96 -7
  80. package/dist/docx/server/templatePlan/blocks.d.ts +70 -3
  81. package/dist/docx/server/templatePlan/blocks.js +272 -10
  82. package/dist/docx/server/templatePlan/builders.d.ts +52 -2
  83. package/dist/docx/server/templatePlan/builders.js +224 -5
  84. package/dist/docx/server/templatePlan/effects.d.ts +27 -0
  85. package/dist/docx/server/templatePlan/effects.js +188 -0
  86. package/dist/docx/server/templatePlan/emit.d.ts +4 -1
  87. package/dist/docx/server/templatePlan/emit.js +46 -2
  88. package/dist/docx/server/templatePlan/inspect.js +39 -52
  89. package/dist/docx/server/templatePlan/labels.d.ts +7 -2
  90. package/dist/docx/server/templatePlan/labels.js +120 -23
  91. package/dist/docx/server/templatePlan/plan.d.ts +24 -3
  92. package/dist/docx/server/templatePlan/plan.js +54 -15
  93. package/dist/docx/server/templatePlan/planShape.js +76 -22
  94. package/dist/docx/server/templatePlan/revisions.d.ts +46 -0
  95. package/dist/docx/server/templatePlan/revisions.js +407 -0
  96. package/dist/docx/server/templatePlan/story.d.ts +23 -1
  97. package/dist/docx/server/templatePlan/story.js +60 -2
  98. package/dist/docx/server/templatePlan/types.d.ts +354 -16
  99. package/dist/docx/server/templatePlan/verify.js +164 -14
  100. package/dist/docx/server/templatePlan/xml.d.ts +3 -0
  101. package/dist/docx/server/templatePlan/xml.js +4 -1
  102. package/dist/i18n/messages/ar.gen.js +1 -0
  103. package/dist/i18n/messages/catalogs.gen.d.ts +17 -0
  104. package/dist/i18n/messages/catalogs.gen.js +17 -0
  105. package/dist/i18n/messages/cs.gen.js +1 -0
  106. package/dist/i18n/messages/de.gen.js +1 -0
  107. package/dist/i18n/messages/en.gen.js +1 -0
  108. package/dist/i18n/messages/es.gen.js +1 -0
  109. package/dist/i18n/messages/et.gen.js +1 -0
  110. package/dist/i18n/messages/fr.gen.js +1 -0
  111. package/dist/i18n/messages/he.gen.js +1 -0
  112. package/dist/i18n/messages/hi.gen.js +1 -0
  113. package/dist/i18n/messages/hu.gen.js +1 -0
  114. package/dist/i18n/messages/lt.gen.js +1 -0
  115. package/dist/i18n/messages/lv.gen.js +1 -0
  116. package/dist/i18n/messages/messages.gen.d.ts +1 -0
  117. package/dist/i18n/messages/pl.gen.js +1 -0
  118. package/dist/i18n/messages/pt-BR.gen.js +1 -0
  119. package/dist/i18n/messages/sk.gen.js +1 -0
  120. package/dist/i18n/messages/tr.gen.js +1 -0
  121. package/dist/i18n/messages/zh-CN.gen.js +1 -0
  122. package/dist/internal/revisionResolutionStep.d.ts +2 -31
  123. package/dist/internal/revisionResolutionStep.js +2 -171
  124. package/dist/layout-bridge/convert/toFlowBlocks.js +0 -12
  125. package/dist/layout-bridge/convert/topLevelConversion.js +1 -10
  126. package/dist/prosemirror/commands/comments.d.ts +6 -234
  127. package/dist/prosemirror/commands/comments.js +5 -2464
  128. package/dist/prosemirror/commands/index.d.ts +4 -2
  129. package/dist/prosemirror/commands/index.js +4 -2
  130. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -11
  131. package/dist/prosemirror/commands/tableCellMergeResolution.js +3 -154
  132. package/dist/prosemirror/extensions/features/ImagePasteExtension.js +1 -1
  133. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +6 -8
  134. package/dist/prosemirror/hyperlinkRemoval.d.ts +11 -8
  135. package/dist/prosemirror/hyperlinkRemoval.js +24 -15
  136. package/dist/prosemirror/listMarker.d.ts +1 -6
  137. package/dist/prosemirror/listMarker.js +4 -56
  138. package/dist/prosemirror/paraIds.d.ts +1 -14
  139. package/dist/prosemirror/paraIds.js +1 -14
  140. package/dist/prosemirror/paragraphMarkJoin.d.ts +0 -16
  141. package/dist/prosemirror/paragraphMarkJoin.js +3 -46
  142. package/dist/prosemirror/projectionReview.d.ts +49 -0
  143. package/dist/prosemirror/projectionReview.js +292 -0
  144. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -13
  145. package/dist/prosemirror/rebaseParagraphRunFormatting.js +1 -16
  146. package/dist/prosemirror/replacedAnnotations.d.ts +2 -5
  147. package/dist/prosemirror/replacedAnnotations.js +1 -10
  148. package/dist/prosemirror/revisionCarriers.d.ts +9 -1
  149. package/dist/prosemirror/revisionCarriers.js +15 -1
  150. package/dist/prosemirror/revisionRangeQueries.d.ts +32 -0
  151. package/dist/prosemirror/revisionRangeQueries.js +76 -0
  152. package/dist/prosemirror/runFormattingMarkNames.d.ts +1 -1
  153. package/dist/prosemirror/runFormattingMarkNames.js +1 -1
  154. package/dist/prosemirror/suggestionQueries.d.ts +114 -0
  155. package/dist/prosemirror/suggestionQueries.js +320 -0
  156. package/dist/prosemirror/tableGridMutation.d.ts +1 -16
  157. package/dist/prosemirror/tableGridMutation.js +1 -78
  158. package/dist/prosemirror/tableRowRevisionOwnership.d.ts +18 -0
  159. package/dist/prosemirror/tableRowRevisionOwnership.js +7 -0
  160. package/dist/prosemirror/utils/extractTrackedChanges.js +14 -4
  161. package/dist/server.d.ts +2 -2
  162. package/dist/types/canonicalCapabilities.d.ts +40 -69
  163. package/dist/types/canonicalCapabilities.js +51 -65
  164. package/dist/types/canonicalComments.d.ts +2 -2
  165. package/dist/types/canonicalSections.d.ts +2 -2
  166. package/dist/utils/clipboard.d.ts +2 -28
  167. package/dist/utils/clipboard.js +1 -96
  168. package/dist/utils/clipboardFiles.d.ts +27 -0
  169. package/dist/utils/clipboardFiles.js +98 -0
  170. package/dist/utils/rulerControl.d.ts +1 -0
  171. package/dist/utils/rulerControl.js +2 -1
  172. package/package.json +2 -2
  173. package/dist/internal/headlessRevisionResolutionGuard.d.ts +0 -3
  174. package/dist/internal/headlessRevisionResolutionGuard.js +0 -18
@@ -0,0 +1,730 @@
1
+ import { displayCommentsFrom } from "../display-list/build/commentAnnotations.js";
2
+ import { displayListFurnitureFrom } from "../display-list/editor/pageRenderer.js";
3
+ import { resolveDocumentGridLinePitch } from "../docx/documentGrid.js";
4
+ import { formatOoxmlCounter } from "../docx/ooxmlCounterFormatter.js";
5
+ import { buildBookmarkPageMap } from "../fields/bookmarkPages.js";
6
+ import { buildBookmarkText } from "../fields/bookmarkText.js";
7
+ import { buildHeaderFooterFieldValues, fieldValuesEqual, resolveFieldValues } from "../fields/resolveFieldValues.js";
8
+ import { buildSectionPageCounts } from "../fields/sectionPageCounts.js";
9
+ import { buildSeqValues } from "../fields/seqValues.js";
10
+ import { buildDocumentFontFacts, documentFontFactsCacheIdentity } from "../fonts/documentFontFacts.js";
11
+ import { buildFontAlternates } from "../fonts/fontAlternates.js";
12
+ import { prepareEndnoteAreas, resolveEndnotePosition, spliceEndnoteAreas, trailingEndnoteIds } from "../layout-bridge/convert/endnoteLayout.js";
13
+ import { buildFootnoteContentMap, collectEndnoteRefs, collectFootnoteRefs, computeNoteDisplayNumbers, remapNoteMarkerText } from "../layout-bridge/convert/footnoteLayout.js";
14
+ import { remapMarkupViewBlocks } from "../layout-bridge/convert/markupViewFlow.js";
15
+ import { applyTemplatePreviewToBlocks } from "../layout-bridge/convert/templatePreviewFlow.js";
16
+ import { toFlowBlocks } from "../layout-bridge/convert/toFlowBlocks.js";
17
+ import { getColumns } from "../layout-bridge/sectionColumns.js";
18
+ import { resolveAnchorLayoutInCellCompatibility } from "../layout-engine/anchorLayoutInCellCompatibility.js";
19
+ import { applyFootnoteContinuation, footnoteContinuationSettled, planFootnoteContinuation } from "../layout-engine/footnoteContinuation.js";
20
+ import { layoutDocument } from "../layout-engine/index.js";
21
+ import { resolveJustificationCompatibility } from "../layout-engine/justificationCompatibility.js";
22
+ import { recordLayoutComplete, recordLayoutError, recordLayoutPhase, recordLayoutStart, recordMarkupViewIncomplete } from "../layout-engine/layoutInstrumentation.js";
23
+ import { labelMeasureCachesFontSet, syncMeasureCachesToFontSet } from "../layout-engine/measure/cache.js";
24
+ import { collectRequestedHyphenationDictionaries } from "../layout-engine/measure/hyphenationDictionaries.js";
25
+ import { measureBlocks, measureSingleBlockWithoutFloatingZones } from "../layout-engine/measure/measureBlocks.js";
26
+ import { installCanvasMeasureProvider, resetCanvasContext } from "../layout-engine/measure/measureContainer.js";
27
+ import { settleRaisedTableWrap } from "../layout-engine/measure/raisedTableWrap.js";
28
+ import { forgetTableMeasures } from "../layout-engine/measure/tableMeasureMemo.js";
29
+ import { columnBalancingForCompatibility } from "../layout-engine/noColumnBalanceCompatibility.js";
30
+ import { resolveBodyTableLeadingSpacing, resolveEffectiveParagraphSpacingTree } from "../layout-engine/paragraphSpacing.js";
31
+ import { tableHeaderGroupStartForCompatibility } from "../layout-engine/tableHeaderCompatibility.js";
32
+ import { resolveTableIndentCompatibility } from "../layout-engine/tableIndentCompatibility.js";
33
+ import "../layout-engine/types.js";
34
+ import { renderPages } from "../layout-painter/renderPage.js";
35
+ import { tryBuildIncrementalMeasures } from "../paged-layout/incrementalMeasure.js";
36
+ import { computePerBlockMeasureInputs } from "../paged-layout/sectionBlockWidths.js";
37
+ import { getMargins, getPageNumbering, getPageSize, twipsToPixels } from "../paged-layout/sectionGeometry.js";
38
+ import { markupViewNotes } from "../prosemirror/markupViewNotes.js";
39
+ import { projectMarkupView } from "../prosemirror/markupViewProjection.js";
40
+ import { templatePreviewValuesKey } from "../prosemirror/plugins/templatePreviewValues.js";
41
+ import { readModel } from "../types/documentModel.js";
42
+ import { getDocumentWatermark } from "../watermark/index.js";
43
+ import { diffAgainstCommittedLayout } from "./committedLayoutDiff.js";
44
+ import { LAYOUT_MEASURE } from "./layoutRunOptions.js";
45
+ import { survivingComments } from "@stll/docx-core/ops";
46
+ // src/controller/layoutPipelineExecution.ts
47
+ const MAX_FOOTNOTE_CONTINUATION_ROUNDS = 4;
48
+ const formatEndnoteTexts = (numbers, formatNumber) => {
49
+ const texts = /* @__PURE__ */ new Map();
50
+ for (const [id, displayNumber] of numbers) texts.set(id, formatNumber(displayNumber));
51
+ return texts;
52
+ };
53
+ const sameMeasureInputs = (left, right) => left.embeddedFontFamilyMap === right.embeddedFontFamilyMap && left.documentFontFactsCacheIdentity === right.documentFontFactsCacheIdentity && left.styles === right.styles && left.theme === right.theme && left.defaultTabStop === right.defaultTabStop && left.pageContentHeight === right.pageContentHeight && left.fontSet === right.fontSet && left.fontAlternates.size === right.fontAlternates.size && [...left.fontAlternates].every(([name, alternate]) => right.fontAlternates.get(name) === alternate) && left.markupView === right.markupView && left.showCommentHighlights === right.showCommentHighlights && left.altChunkMarkerText === right.altChunkMarkerText;
54
+ /**
55
+ * The range an incremental pass re-measures, or `null` for a full measure: the
56
+ * committed measures must come from the same measure inputs, and the range is
57
+ * where the current document and preview differ from the committed ones.
58
+ */
59
+ const incrementalDirtyRange = ({ session, state, preview, measureInputs }) => {
60
+ const { lastPmDoc, lastMeasureInputs } = session;
61
+ if (!lastPmDoc || !lastMeasureInputs || !sameMeasureInputs(lastMeasureInputs, measureInputs)) return null;
62
+ const diff = diffAgainstCommittedLayout({
63
+ doc: lastPmDoc,
64
+ preview: session.lastTemplatePreview
65
+ }, {
66
+ doc: state.doc,
67
+ preview
68
+ });
69
+ switch (diff.type) {
70
+ case "full": return null;
71
+ case "range": return diff.range;
72
+ default: return diff;
73
+ }
74
+ };
75
+ /** Resolve only package-owned picture-watermark bytes for the DOM painter. */
76
+ const resolveWatermarkImageSrc = (document, watermark) => {
77
+ if (watermark?.kind !== "picture" || watermark.imageTargetExternal === true) return;
78
+ const target = watermark.imageTarget;
79
+ return target === void 0 ? void 0 : document.package.media?.get(target)?.dataUrl;
80
+ };
81
+ function bodyMarginsClearHeaderFooter({ authoredMargins, preparedHeader, preparedFooter }) {
82
+ const top = authoredMargins.top < 0 ? -authoredMargins.top : Math.max(authoredMargins.top, preparedHeader ? (authoredMargins.header ?? 0) + (preparedHeader.marginPushBottom ?? preparedHeader.height) : 0, preparedHeader?.bodyTopClearance ?? 0);
83
+ const bottom = authoredMargins.bottom < 0 ? -authoredMargins.bottom : Math.max(authoredMargins.bottom, preparedFooter ? (authoredMargins.footer ?? 0) + (preparedFooter.marginPushBottom ?? preparedFooter.height) : 0);
84
+ if (top === authoredMargins.top && bottom === authoredMargins.bottom) return authoredMargins;
85
+ return {
86
+ ...authoredMargins,
87
+ top,
88
+ bottom
89
+ };
90
+ }
91
+ function bodyBlocksClearSectionHeaderFooter(blocks, { authoredMargins, sectionHeaderFooterRefs, headerContentByRId, footerContentByRId }) {
92
+ if (!sectionHeaderFooterRefs) return blocks;
93
+ let sectionIndex = 0;
94
+ let currentAuthoredMargins = authoredMargins;
95
+ let changed = false;
96
+ const nextBlocks = blocks.map((block) => {
97
+ if (block.kind !== "sectionBreak") return block;
98
+ currentAuthoredMargins = block.margins ?? currentAuthoredMargins;
99
+ const refs = sectionHeaderFooterRefs[sectionIndex];
100
+ sectionIndex += 1;
101
+ const effectiveMargins = bodyMarginsClearHeaderFooter({
102
+ authoredMargins: currentAuthoredMargins,
103
+ preparedHeader: refs?.headerDefault ? headerContentByRId?.get(refs.headerDefault) : void 0,
104
+ preparedFooter: refs?.footerDefault ? footerContentByRId?.get(refs.footerDefault) : void 0
105
+ });
106
+ if (effectiveMargins === currentAuthoredMargins && block.margins === currentAuthoredMargins) return block;
107
+ changed = true;
108
+ return {
109
+ ...block,
110
+ margins: effectiveMargins
111
+ };
112
+ });
113
+ return changed ? nextBlocks : blocks;
114
+ }
115
+ const arePageMarginsEqual = (left, right) => left.top === right.top && left.right === right.right && left.bottom === right.bottom && left.left === right.left && left.header === right.header && left.footer === right.footer;
116
+ const mirrorPageMarginsIfNeeded = (authoredMargins, pageNumber, mirrorMargins) => mirrorMargins && pageNumber % 2 === 0 ? {
117
+ ...authoredMargins,
118
+ left: authoredMargins.right,
119
+ right: authoredMargins.left
120
+ } : authoredMargins;
121
+ function attachAuthoredMarginsToLayoutPages(layout, options) {
122
+ let changed = false;
123
+ const pages = layout.pages.map((page) => {
124
+ const sectionProperties = options.sectionPropertiesForMargins[page.sectionIndex ?? 0];
125
+ const authoredMargins = mirrorPageMarginsIfNeeded(sectionProperties ? getMargins(sectionProperties) : options.authoredMargins, page.number, options.mirrorMargins);
126
+ if (page.authoredMargins && arePageMarginsEqual(page.authoredMargins, authoredMargins)) return page;
127
+ changed = true;
128
+ return {
129
+ ...page,
130
+ authoredMargins
131
+ };
132
+ });
133
+ return changed ? {
134
+ ...layout,
135
+ pages
136
+ } : layout;
137
+ }
138
+ function runLayoutPipelineWithPainter(deps, state, options = {}) {
139
+ const { result, missing } = collectRequestedHyphenationDictionaries(() => runLayoutPipelineMeasured(deps, state, options));
140
+ deps.hyphenationReadiness.track(missing);
141
+ return result;
142
+ }
143
+ function runLayoutPipelineMeasured(deps, state, options) {
144
+ const { contentWidth, columns, pageSize, margins, pageGap, showMarginGuides, marginGuideColor, syncCoordinator, headerContent, footerContent, firstPageHeaderContent, firstPageFooterContent, headerContentRId, footerContentRId, firstPageHeaderContentRId, firstPageFooterContentRId, sectionHeaderFooterRefs, theme: _theme, sectionProperties, document: model, defaultTabStop, mirrorMargins, styles, layout, hfPMs, painter, pagesContainer, session, renderHfFromContentOrPm, renderHeaderFooterContentByRId, readFontSetSignature, buildFootnoteRenderItems, describeInvalidHighlightMarks, displayListPagePainter, emptyTemplatePreviewEntries: EMPTY_TEMPLATE_PREVIEW_ENTRIES, emptyTemplatePreviewHidden: EMPTY_TEMPLATE_PREVIEW_HIDDEN, markupView, showCommentHighlights = true, altChunkMarkerText } = deps;
145
+ const document = model && readModel(model);
146
+ let outcome = {};
147
+ let pendingArtifacts;
148
+ let pendingTemplatePreview;
149
+ installCanvasMeasureProvider();
150
+ const fontSet = readFontSetSignature();
151
+ if (syncMeasureCachesToFontSet(fontSet)) resetCanvasContext();
152
+ const reason = options.reason ?? "manual";
153
+ const recordPhaseDuration = (phase, startedAt) => {
154
+ recordLayoutPhase(reason, phase, performance.now() - startedAt);
155
+ };
156
+ const currentEpoch = syncCoordinator.getStateSeq();
157
+ recordLayoutStart(reason);
158
+ syncCoordinator.onLayoutStart();
159
+ try {
160
+ let phaseStartedAt = performance.now();
161
+ const pageContentHeight = pageSize.h - margins.top - margins.bottom;
162
+ const fontAlternates = buildFontAlternates(document?.package.fontTable);
163
+ const documentFontFacts = buildDocumentFontFacts(document?.package.fontTable);
164
+ const displayCommentHighlights = showCommentHighlights && markupView !== "no-markup" && markupView !== "original";
165
+ const embeddedFontFamilies = session.embeddedFontFamilyMap ? { embeddedFontFamilyMap: session.embeddedFontFamilyMap } : {};
166
+ const measureInputs = {
167
+ ...embeddedFontFamilies,
168
+ documentFontFactsCacheIdentity: documentFontFactsCacheIdentity(documentFontFacts),
169
+ styles,
170
+ theme: _theme,
171
+ defaultTabStop,
172
+ pageContentHeight,
173
+ fontSet,
174
+ fontAlternates,
175
+ markupView,
176
+ showCommentHighlights: displayCommentHighlights,
177
+ ...altChunkMarkerText === void 0 ? {} : { altChunkMarkerText }
178
+ };
179
+ if (session.lastMeasureInputs && !sameMeasureInputs(session.lastMeasureInputs, measureInputs)) forgetTableMeasures();
180
+ const flowOpts = {
181
+ showCommentHighlights: displayCommentHighlights,
182
+ ...altChunkMarkerText === void 0 ? {} : { altChunkMarkerText },
183
+ ...embeddedFontFamilies,
184
+ ...documentFontFacts === void 0 ? {} : { documentFontFacts },
185
+ pageContentHeight,
186
+ fontAlternates,
187
+ ...styles ? { styles } : {},
188
+ ...document === null ? {} : { defaultSize: 10 },
189
+ paragraphBlocks: session.paragraphBlocks
190
+ };
191
+ if (_theme !== void 0) flowOpts.theme = _theme;
192
+ if (defaultTabStop !== void 0) flowOpts.defaultTabStopTwips = defaultTabStop;
193
+ if (document?.package.settings?.splitPageBreakAndParagraphMark === true) flowOpts.splitPageBreakAndParagraphMark = true;
194
+ if (document?.package.settings?.lineBreakRules) flowOpts.lineBreakRules = document.package.settings.lineBreakRules;
195
+ const documentSettings = document?.package.settings;
196
+ const justificationCompatibility = resolveJustificationCompatibility(documentSettings?.compatibilityMode);
197
+ if (justificationCompatibility) flowOpts.justificationCompatibility = justificationCompatibility;
198
+ const tableIndentCompatibility = resolveTableIndentCompatibility(documentSettings?.compatibilityMode);
199
+ if (tableIndentCompatibility) flowOpts.tableIndentCompatibility = tableIndentCompatibility;
200
+ if (resolveAnchorLayoutInCellCompatibility(documentSettings?.compatibilityMode)) flowOpts.forceAnchorLayoutInCell = true;
201
+ if (documentSettings?.autoHyphenation === true) flowOpts.automaticHyphenation = {
202
+ enabled: true,
203
+ ...documentSettings.doNotHyphenateCaps !== void 0 ? { doNotHyphenateCaps: documentSettings.doNotHyphenateCaps } : {},
204
+ ...documentSettings.consecutiveHyphenLimit !== void 0 ? { consecutiveLineLimit: documentSettings.consecutiveHyphenLimit } : {},
205
+ ...documentSettings.hyphenationZoneTwips !== void 0 ? { hyphenationZoneTwips: documentSettings.hyphenationZoneTwips } : {}
206
+ };
207
+ const finalSectionDocumentGridLinePitchTwips = resolveDocumentGridLinePitch(document?.package.document.sections?.at(-1)?.properties.docGrid);
208
+ if (finalSectionDocumentGridLinePitchTwips !== void 0) flowOpts.finalSectionDocumentGridLinePitchTwips = finalSectionDocumentGridLinePitchTwips;
209
+ const endnotePosition = resolveEndnotePosition(document?.package.settings?.endnotePr?.position, document?.package.document.sections?.at(-1)?.properties);
210
+ const bodyTrailingEndnoteIds = trailingEndnoteIds(document?.package.endnotes, endnotePosition);
211
+ if (bodyTrailingEndnoteIds.size > 0) flowOpts.trailingEndnoteIds = bodyTrailingEndnoteIds;
212
+ const projection = projectMarkupView(state, markupView);
213
+ if (projection.type === "resolved" && projection.completeness === "partial") recordMarkupViewIncomplete(markupView);
214
+ const viewDoc = projection.type === "resolved" ? projection.doc : state.doc;
215
+ const flowDoc = document === null ? viewDoc.type.create({
216
+ ...viewDoc.attrs,
217
+ _finalSectionStart: sectionProperties?.sectionStart ?? null
218
+ }, viewDoc.content, viewDoc.marks) : viewDoc;
219
+ let newBlocks = toFlowBlocks(flowDoc, flowOpts);
220
+ if (projection.type === "resolved") newBlocks = remapMarkupViewBlocks(newBlocks, projection);
221
+ const previewState = templatePreviewValuesKey.getState(state);
222
+ const previewEntries = previewState?.entries ?? EMPTY_TEMPLATE_PREVIEW_ENTRIES;
223
+ const previewHidden = previewState?.hidden ?? EMPTY_TEMPLATE_PREVIEW_HIDDEN;
224
+ const previewMode = previewState?.preview?.mode ?? "plain";
225
+ if (previewEntries.length > 0 || previewHidden.length > 0) newBlocks = applyTemplatePreviewToBlocks(newBlocks, {
226
+ entries: previewEntries,
227
+ hidden: previewHidden,
228
+ mode: previewMode
229
+ });
230
+ pendingTemplatePreview = {
231
+ entries: previewEntries,
232
+ hidden: previewHidden,
233
+ mode: previewMode
234
+ };
235
+ outcome.blocks = newBlocks;
236
+ recordPhaseDuration("flow-blocks", phaseStartedAt);
237
+ phaseStartedAt = performance.now();
238
+ const footnoteRefs = collectFootnoteRefs(newBlocks);
239
+ const documentFootnotes = markupViewNotes(document?.package.footnotes, markupView, state, document);
240
+ const hasFootnotes = footnoteRefs.length > 0 && documentFootnotes !== void 0;
241
+ const footnoteDisplayNumbers = documentFootnotes ? computeNoteDisplayNumbers(documentFootnotes, footnoteRefs.map((ref) => ref.footnoteId)) : void 0;
242
+ const documentEndnotes = markupViewNotes(document?.package.endnotes, markupView, state, document);
243
+ const endnoteDisplayNumbers = documentEndnotes ? computeNoteDisplayNumbers(documentEndnotes, collectEndnoteRefs(newBlocks).map((ref) => ref.endnoteId)) : void 0;
244
+ const endnoteNumberFormat = document?.package.document.sections?.at(-1)?.properties.endnotePr?.numFmt ?? document?.package.settings?.endnotePr?.numFmt ?? "lowerRoman";
245
+ const endnoteTexts = endnoteDisplayNumbers ? formatEndnoteTexts(endnoteDisplayNumbers, (displayNumber) => formatOoxmlCounter(displayNumber, endnoteNumberFormat)) : void 0;
246
+ newBlocks = remapNoteMarkerText(newBlocks, {
247
+ ...footnoteDisplayNumbers ? { footnoteNumbers: footnoteDisplayNumbers } : {},
248
+ ...endnoteTexts ? { endnoteTexts } : {}
249
+ });
250
+ newBlocks = resolveBodyTableLeadingSpacing(newBlocks);
251
+ outcome.blocks = newBlocks;
252
+ const hfMetricsHeader = {
253
+ section: "header",
254
+ pageSize,
255
+ margins
256
+ };
257
+ const hfMetricsFooter = {
258
+ section: "footer",
259
+ pageSize,
260
+ margins
261
+ };
262
+ const hfPageCountEstimate = layout?.pages.length ?? 1;
263
+ const hfClock = /* @__PURE__ */ new Date();
264
+ const buildHfOptions = (pageCount, fieldInputs) => {
265
+ const hfMeasureBlocks = (hfBlocks, hfWidth) => measureBlocks(hfBlocks, hfWidth, void 0, void 0, buildHeaderFooterFieldValues(hfBlocks, pageCount, hfClock, fieldInputs), { allowEndTabOverflow: true });
266
+ return {
267
+ markupView,
268
+ showCommentHighlights: displayCommentHighlights,
269
+ ...altChunkMarkerText === void 0 ? {} : { altChunkMarkerText },
270
+ ...flowOpts.styles ? { styles: flowOpts.styles } : {},
271
+ ...document?.package.numbering === void 0 ? {} : { numbering: document.package.numbering },
272
+ ...flowOpts.defaultSize === void 0 ? {} : { defaultSize: flowOpts.defaultSize },
273
+ ..._theme !== void 0 ? { theme: _theme } : {},
274
+ fontAlternates,
275
+ ...embeddedFontFamilies,
276
+ ...flowOpts.documentFontFacts === void 0 ? {} : { documentFontFacts: flowOpts.documentFontFacts },
277
+ measureBlocks: hfMeasureBlocks,
278
+ ...defaultTabStop !== void 0 ? { defaultTabStopTwips: defaultTabStop } : {},
279
+ ...flowOpts.lineBreakRules ? { lineBreakRules: flowOpts.lineBreakRules } : {},
280
+ ...flowOpts.justificationCompatibility ? { justificationCompatibility: flowOpts.justificationCompatibility } : {},
281
+ ...flowOpts.tableIndentCompatibility ? { tableIndentCompatibility: flowOpts.tableIndentCompatibility } : {},
282
+ ...flowOpts.automaticHyphenation ? { automaticHyphenation: flowOpts.automaticHyphenation } : {}
283
+ };
284
+ };
285
+ const hfOptions = buildHfOptions(hfPageCountEstimate);
286
+ let headerContentForRender = renderHfFromContentOrPm(headerContent, headerContentRId, hfPMs, contentWidth, hfMetricsHeader, hfOptions);
287
+ let footerContentForRender = renderHfFromContentOrPm(footerContent, footerContentRId, hfPMs, contentWidth, hfMetricsFooter, hfOptions);
288
+ const hasTitlePg = sectionProperties?.titlePg === true;
289
+ let firstPageHeaderForRender = hasTitlePg ? renderHfFromContentOrPm(firstPageHeaderContent, firstPageHeaderContentRId, hfPMs, contentWidth, hfMetricsHeader, hfOptions) : void 0;
290
+ let firstPageFooterForRender = hasTitlePg ? renderHfFromContentOrPm(firstPageFooterContent, firstPageFooterContentRId, hfPMs, contentWidth, hfMetricsFooter, hfOptions) : void 0;
291
+ let headerContentByRId = renderHeaderFooterContentByRId(document?.package.headers, hfPMs, contentWidth, hfMetricsHeader, hfOptions);
292
+ let footerContentByRId = renderHeaderFooterContentByRId(document?.package.footers, hfPMs, contentWidth, hfMetricsFooter, hfOptions);
293
+ const sectionPropertiesForMargins = document?.package.document.sections?.map((section) => section.properties) ?? (sectionProperties ? [sectionProperties] : []);
294
+ const sectionEvenPageMargins = sectionHeaderFooterRefs?.map((refs, index) => {
295
+ if (refs.evenAndOddHeaders !== true) return;
296
+ const properties = sectionPropertiesForMargins[index];
297
+ return bodyMarginsClearHeaderFooter({
298
+ authoredMargins: properties ? getMargins(properties) : margins,
299
+ preparedHeader: refs.headerEven ? headerContentByRId?.get(refs.headerEven) : void 0,
300
+ preparedFooter: refs.footerEven ? footerContentByRId?.get(refs.footerEven) : void 0
301
+ });
302
+ });
303
+ const sectionFirstPageMargins = sectionHeaderFooterRefs?.map((refs, index) => {
304
+ if (refs.titlePg !== true) return;
305
+ const properties = sectionPropertiesForMargins[index];
306
+ return bodyMarginsClearHeaderFooter({
307
+ authoredMargins: properties ? getMargins(properties) : margins,
308
+ preparedHeader: refs.headerFirst ? headerContentByRId?.get(refs.headerFirst) : void 0,
309
+ preparedFooter: refs.footerFirst ? footerContentByRId?.get(refs.footerFirst) : void 0
310
+ });
311
+ });
312
+ newBlocks = bodyBlocksClearSectionHeaderFooter(newBlocks, {
313
+ authoredMargins: margins,
314
+ sectionHeaderFooterRefs,
315
+ headerContentByRId,
316
+ footerContentByRId
317
+ });
318
+ outcome.blocks = newBlocks;
319
+ const initialBodyMargins = bodyMarginsClearHeaderFooter({
320
+ authoredMargins: margins,
321
+ preparedHeader: headerContentForRender,
322
+ preparedFooter: footerContentForRender
323
+ });
324
+ recordPhaseDuration("header-footer", phaseStartedAt);
325
+ phaseStartedAt = performance.now();
326
+ const bodyLayoutConfig = {
327
+ pageSize,
328
+ margins: initialBodyMargins,
329
+ pageNumbering: getPageNumbering(sectionProperties)
330
+ };
331
+ if (columns !== void 0) bodyLayoutConfig.columns = columns;
332
+ const finalSectionProperties = document?.package.document.sections?.at(-1)?.properties;
333
+ const finalHeaderRId = sectionHeaderFooterRefs?.at(-1)?.headerDefault;
334
+ let finalHeaderForLayout = headerContentForRender;
335
+ if (finalHeaderRId) finalHeaderForLayout = headerContentByRId?.get(finalHeaderRId);
336
+ else if (sectionHeaderFooterRefs !== void 0) finalHeaderForLayout = void 0;
337
+ const finalFooterRId = sectionHeaderFooterRefs?.at(-1)?.footerDefault;
338
+ let finalFooterForLayout = footerContentForRender;
339
+ if (finalFooterRId) finalFooterForLayout = footerContentByRId?.get(finalFooterRId);
340
+ else if (sectionHeaderFooterRefs !== void 0) finalFooterForLayout = void 0;
341
+ const finalLayoutConfig = finalSectionProperties ? {
342
+ pageSize: getPageSize(finalSectionProperties),
343
+ margins: bodyMarginsClearHeaderFooter({
344
+ authoredMargins: getMargins(finalSectionProperties),
345
+ preparedHeader: finalHeaderForLayout,
346
+ preparedFooter: finalFooterForLayout
347
+ }),
348
+ pageNumbering: getPageNumbering(finalSectionProperties)
349
+ } : bodyLayoutConfig;
350
+ const finalColumns = getColumns(finalSectionProperties);
351
+ if (finalColumns !== void 0) finalLayoutConfig.columns = finalColumns;
352
+ const blockMeasureInputs = computePerBlockMeasureInputs({
353
+ blocks: newBlocks,
354
+ bodyConfig: bodyLayoutConfig,
355
+ finalConfig: finalLayoutConfig
356
+ });
357
+ const blockWidths = blockMeasureInputs.widths;
358
+ const bodyMeasureGeometry = {
359
+ pageWidth: blockMeasureInputs.pageWidths,
360
+ pageHeight: blockMeasureInputs.pageHeights,
361
+ marginLeft: blockMeasureInputs.marginLefts,
362
+ marginRight: blockMeasureInputs.marginRights,
363
+ marginBottom: blockMeasureInputs.marginBottoms,
364
+ contentLeft: blockMeasureInputs.contentLefts,
365
+ physicalPage: {
366
+ pageWidth: blockMeasureInputs.physicalPageGeometry.pageWidths,
367
+ pageHeight: blockMeasureInputs.physicalPageGeometry.pageHeights,
368
+ marginTop: blockMeasureInputs.physicalPageGeometry.marginTops,
369
+ marginLeft: blockMeasureInputs.physicalPageGeometry.marginLefts,
370
+ marginRight: blockMeasureInputs.physicalPageGeometry.marginRights,
371
+ marginBottom: blockMeasureInputs.physicalPageGeometry.marginBottoms
372
+ },
373
+ columnIndex: blockMeasureInputs.columnIndices,
374
+ columnCount: blockMeasureInputs.columnCounts,
375
+ sectionAdvances: blockMeasureInputs.sectionAdvances
376
+ };
377
+ const measureBody = (inputs = {}) => measureBlocks(newBlocks, blockWidths, blockMeasureInputs.marginTops, bodyMeasureGeometry, inputs.fieldValues, inputs);
378
+ const previousArtifacts = session.artifacts;
379
+ const dirtyRange = options.measure === LAYOUT_MEASURE.incremental ? incrementalDirtyRange({
380
+ session,
381
+ state,
382
+ preview: pendingTemplatePreview,
383
+ measureInputs
384
+ }) : null;
385
+ const incrementalResult = dirtyRange && previousArtifacts ? tryBuildIncrementalMeasures({
386
+ previousBlocks: previousArtifacts.blocks,
387
+ previousMeasures: previousArtifacts.measures,
388
+ previousBlockWidths: previousArtifacts.blockWidths,
389
+ nextBlocks: newBlocks,
390
+ nextBlockWidths: blockWidths,
391
+ dirtyRange,
392
+ measureBlock: measureSingleBlockWithoutFloatingZones
393
+ }) : null;
394
+ let forwardMeasures = incrementalResult?.measures ?? measureBody();
395
+ let newMeasures = forwardMeasures;
396
+ newBlocks = resolveEffectiveParagraphSpacingTree(newBlocks);
397
+ outcome.blocks = newBlocks;
398
+ pendingArtifacts = {
399
+ blocks: newBlocks,
400
+ blockWidths,
401
+ measures: newMeasures
402
+ };
403
+ outcome.measures = newMeasures;
404
+ recordPhaseDuration("measure-blocks", phaseStartedAt);
405
+ const buildNoteOptions = () => {
406
+ const noteOptions = {
407
+ measureBlocks,
408
+ showCommentHighlights: displayCommentHighlights,
409
+ ...altChunkMarkerText === void 0 ? {} : { altChunkMarkerText },
410
+ markupView
411
+ };
412
+ if (flowOpts.styles) noteOptions.styles = flowOpts.styles;
413
+ if (flowOpts.defaultSize !== void 0) noteOptions.defaultSize = flowOpts.defaultSize;
414
+ if (_theme !== void 0) noteOptions.theme = _theme;
415
+ if (document?.package.numbering !== void 0) noteOptions.numbering = document.package.numbering;
416
+ noteOptions.fontAlternates = fontAlternates;
417
+ if (session.embeddedFontFamilyMap) noteOptions.embeddedFontFamilyMap = session.embeddedFontFamilyMap;
418
+ if (flowOpts.documentFontFacts !== void 0) noteOptions.documentFontFacts = flowOpts.documentFontFacts;
419
+ if (defaultTabStop !== void 0) noteOptions.defaultTabStopTwips = defaultTabStop;
420
+ if (flowOpts.lineBreakRules) noteOptions.lineBreakRules = flowOpts.lineBreakRules;
421
+ if (flowOpts.justificationCompatibility) noteOptions.justificationCompatibility = flowOpts.justificationCompatibility;
422
+ if (flowOpts.tableIndentCompatibility) noteOptions.tableIndentCompatibility = flowOpts.tableIndentCompatibility;
423
+ if (flowOpts.automaticHyphenation) noteOptions.automaticHyphenation = flowOpts.automaticHyphenation;
424
+ return noteOptions;
425
+ };
426
+ const endnoteAreas = documentEndnotes && endnoteDisplayNumbers && endnoteTexts ? prepareEndnoteAreas({
427
+ blocks: newBlocks,
428
+ endnotes: documentEndnotes,
429
+ displayNumbers: endnoteDisplayNumbers,
430
+ displayTexts: endnoteTexts,
431
+ position: endnotePosition,
432
+ sections: sectionPropertiesForMargins,
433
+ options: buildNoteOptions()
434
+ }) : void 0;
435
+ const paginateBody = (measures, nextLayoutOpts) => {
436
+ if (endnoteAreas === void 0) return layoutDocument(newBlocks, measures, nextLayoutOpts);
437
+ const flow = spliceEndnoteAreas(newBlocks, measures, endnoteAreas);
438
+ return layoutDocument(flow.blocks, flow.measures, {
439
+ ...nextLayoutOpts,
440
+ noteAreas: endnoteAreas.noteAreas
441
+ });
442
+ };
443
+ let stabilizedFieldValues;
444
+ const layoutWithNoteAreas = (nextLayoutOpts) => {
445
+ const settled = settleRaisedTableWrap({
446
+ blocks: newBlocks,
447
+ measures: forwardMeasures,
448
+ layout: (measures) => paginateBody(measures, nextLayoutOpts),
449
+ measure: (raisedTableWrap) => measureBody({
450
+ fieldValues: stabilizedFieldValues,
451
+ raisedTableWrap
452
+ })
453
+ });
454
+ if (newMeasures !== settled.measures) {
455
+ newMeasures = settled.measures;
456
+ pendingArtifacts = {
457
+ blocks: newBlocks,
458
+ blockWidths,
459
+ measures: newMeasures
460
+ };
461
+ outcome.measures = newMeasures;
462
+ }
463
+ return settled.layout;
464
+ };
465
+ const withFootnoteHeights = (nextLayoutOpts) => {
466
+ if (!hasFootnotes) return nextLayoutOpts;
467
+ const footnoteHeightById = /* @__PURE__ */ new Map();
468
+ for (const [id, content] of footnoteContentMap) footnoteHeightById.set(id, content.height + 0);
469
+ return {
470
+ ...nextLayoutOpts,
471
+ footnoteHeightById,
472
+ footnoteContinuation: nextLayoutOpts.footnoteContinuation ?? { trailingPages: 0 }
473
+ };
474
+ };
475
+ phaseStartedAt = performance.now();
476
+ let newLayout;
477
+ let pageFootnoteMap = /* @__PURE__ */ new Map();
478
+ let footnoteContentMap = /* @__PURE__ */ new Map();
479
+ const buildLayoutOpts = () => {
480
+ const nextLayoutOpts = {
481
+ pageSize,
482
+ margins: initialBodyMargins,
483
+ pageNumbering: bodyLayoutConfig.pageNumbering,
484
+ pageGap,
485
+ mirrorMargins,
486
+ columnBalancing: columnBalancingForCompatibility(document?.package.settings?.noColumnBalance, document?.package.settings?.compatibilityMode),
487
+ tableHeaderGroupStart: tableHeaderGroupStartForCompatibility(document?.package.settings?.compatibilityMode)
488
+ };
489
+ if (document?.package.document.sections !== void 0) nextLayoutOpts.sectionVerticalAlignments = document.package.document.sections.map(({ properties }) => properties.verticalAlign);
490
+ else if (sectionProperties !== null && sectionProperties !== void 0) nextLayoutOpts.sectionVerticalAlignments = [sectionProperties.verticalAlign];
491
+ if (sectionFirstPageMargins !== void 0) nextLayoutOpts.sectionFirstPageMargins = sectionFirstPageMargins;
492
+ else if (hasTitlePg) nextLayoutOpts.firstPageMargins = bodyMarginsClearHeaderFooter({
493
+ authoredMargins: margins,
494
+ preparedHeader: firstPageHeaderForRender,
495
+ preparedFooter: firstPageFooterForRender
496
+ });
497
+ if (finalSectionProperties) {
498
+ nextLayoutOpts.finalPageSize = finalLayoutConfig.pageSize;
499
+ nextLayoutOpts.finalMargins = finalLayoutConfig.margins;
500
+ nextLayoutOpts.finalColumns = finalLayoutConfig.columns ?? {
501
+ count: 1,
502
+ gap: 0
503
+ };
504
+ nextLayoutOpts.finalPageNumbering = finalLayoutConfig.pageNumbering;
505
+ }
506
+ if (columns !== void 0) nextLayoutOpts.columns = columns;
507
+ if (sectionHeaderFooterRefs !== void 0) nextLayoutOpts.sectionHeaderFooterRefs = sectionHeaderFooterRefs;
508
+ if (sectionEvenPageMargins !== void 0) nextLayoutOpts.sectionEvenPageMargins = sectionEvenPageMargins;
509
+ return nextLayoutOpts;
510
+ };
511
+ const layoutOpts = buildLayoutOpts();
512
+ let layoutOptsUsed = layoutOpts;
513
+ if (hasFootnotes) {
514
+ footnoteContentMap = buildFootnoteContentMap(documentFootnotes, footnoteRefs, contentWidth, buildNoteOptions());
515
+ layoutOptsUsed = withFootnoteHeights(layoutOpts);
516
+ newLayout = layoutWithNoteAreas(layoutOptsUsed);
517
+ pageFootnoteMap = /* @__PURE__ */ new Map();
518
+ for (const page of newLayout.pages) if (page.footnoteIds && page.footnoteIds.length > 0) pageFootnoteMap.set(page.number, page.footnoteIds);
519
+ } else newLayout = layoutWithNoteAreas(layoutOpts);
520
+ const rebuildFootnotePageMap = () => {
521
+ pageFootnoteMap = /* @__PURE__ */ new Map();
522
+ for (const page of newLayout.pages) if (page.footnoteIds && page.footnoteIds.length > 0) pageFootnoteMap.set(page.number, page.footnoteIds);
523
+ };
524
+ const relayoutWithCurrentMeasures = (nextLayoutOpts) => {
525
+ layoutOptsUsed = withFootnoteHeights(nextLayoutOpts);
526
+ newLayout = layoutWithNoteAreas(layoutOptsUsed);
527
+ if (hasFootnotes) rebuildFootnotePageMap();
528
+ };
529
+ const stabilizeFieldWidths = () => {
530
+ if (incrementalResult) return;
531
+ const MAX_FIELD_STABILIZATION_PASSES = 3;
532
+ const fieldClock = /* @__PURE__ */ new Date();
533
+ let previousFieldValues = null;
534
+ for (let pass = 0; pass < MAX_FIELD_STABILIZATION_PASSES; pass++) {
535
+ const seqValues = buildSeqValues(newBlocks);
536
+ const bookmarkTextInputs = previousFieldValues === null ? { seqValues } : {
537
+ fieldValues: previousFieldValues,
538
+ seqValues
539
+ };
540
+ const { values, changed } = resolveFieldValues(newBlocks, newLayout.pages, {
541
+ totalPages: newLayout.pages.length,
542
+ bookmarkPages: buildBookmarkPageMap(newLayout.pages, newBlocks),
543
+ bookmarkText: buildBookmarkText(newBlocks, bookmarkTextInputs),
544
+ seqValues,
545
+ sectionPageCounts: buildSectionPageCounts(newLayout.pages),
546
+ now: fieldClock
547
+ });
548
+ if (previousFieldValues === null ? !changed : fieldValuesEqual(previousFieldValues, values)) {
549
+ stabilizedFieldValues = values;
550
+ break;
551
+ }
552
+ previousFieldValues = values;
553
+ stabilizedFieldValues = values;
554
+ forwardMeasures = measureBody({ fieldValues: values });
555
+ relayoutWithCurrentMeasures(layoutOptsUsed);
556
+ pendingArtifacts = {
557
+ blocks: newBlocks,
558
+ blockWidths,
559
+ measures: newMeasures
560
+ };
561
+ outcome.measures = newMeasures;
562
+ }
563
+ };
564
+ stabilizeFieldWidths();
565
+ if (hasFootnotes) {
566
+ const usedTrailingPages = () => layoutOptsUsed.footnoteContinuation?.trailingPages ?? 0;
567
+ const planContinuation = () => planFootnoteContinuation({
568
+ pages: newLayout.pages,
569
+ contentById: footnoteContentMap,
570
+ trailingPages: usedTrailingPages()
571
+ });
572
+ const relayoutFor = (reservedHeights, trailingPages) => {
573
+ relayoutWithCurrentMeasures({
574
+ ...layoutOptsUsed,
575
+ ...reservedHeights === void 0 ? {} : { footnoteReservedHeights: reservedHeights },
576
+ footnoteContinuation: { trailingPages }
577
+ });
578
+ stabilizeFieldWidths();
579
+ };
580
+ let continuation = planContinuation();
581
+ for (let round = 0; round < MAX_FOOTNOTE_CONTINUATION_ROUNDS && !footnoteContinuationSettled({
582
+ reservedHeights: layoutOptsUsed.footnoteReservedHeights,
583
+ trailingPages: usedTrailingPages()
584
+ }, continuation); round += 1) {
585
+ relayoutFor(continuation.reservedHeights, continuation.trailingPages);
586
+ continuation = planContinuation();
587
+ }
588
+ while (continuation.extraPages > 0) {
589
+ relayoutFor(layoutOptsUsed.footnoteReservedHeights, continuation.trailingPages);
590
+ continuation = planContinuation();
591
+ }
592
+ if (continuation.pages.size > 0) {
593
+ newLayout = {
594
+ ...newLayout,
595
+ pages: applyFootnoteContinuation(newLayout.pages, continuation)
596
+ };
597
+ rebuildFootnotePageMap();
598
+ }
599
+ }
600
+ newLayout = attachAuthoredMarginsToLayoutPages(newLayout, {
601
+ authoredMargins: margins,
602
+ mirrorMargins,
603
+ sectionPropertiesForMargins
604
+ });
605
+ const rebuildHeaderFooterForLayout = () => {
606
+ const seqValues = buildSeqValues(newBlocks);
607
+ const bookmarkTextInputs = stabilizedFieldValues === void 0 ? { seqValues } : {
608
+ fieldValues: stabilizedFieldValues,
609
+ seqValues
610
+ };
611
+ const finalHfFieldInputs = {
612
+ bookmarkPages: buildBookmarkPageMap(newLayout.pages, newBlocks),
613
+ bookmarkText: buildBookmarkText(newBlocks, bookmarkTextInputs),
614
+ seqValues,
615
+ sectionPageCounts: buildSectionPageCounts(newLayout.pages)
616
+ };
617
+ const finalHfOptions = buildHfOptions(newLayout.pages.length, finalHfFieldInputs);
618
+ headerContentForRender = renderHfFromContentOrPm(headerContent, headerContentRId, hfPMs, contentWidth, hfMetricsHeader, finalHfOptions);
619
+ footerContentForRender = renderHfFromContentOrPm(footerContent, footerContentRId, hfPMs, contentWidth, hfMetricsFooter, finalHfOptions);
620
+ firstPageHeaderForRender = hasTitlePg ? renderHfFromContentOrPm(firstPageHeaderContent, firstPageHeaderContentRId, hfPMs, contentWidth, hfMetricsHeader, finalHfOptions) : void 0;
621
+ firstPageFooterForRender = hasTitlePg ? renderHfFromContentOrPm(firstPageFooterContent, firstPageFooterContentRId, hfPMs, contentWidth, hfMetricsFooter, finalHfOptions) : void 0;
622
+ headerContentByRId = renderHeaderFooterContentByRId(document?.package.headers, hfPMs, contentWidth, hfMetricsHeader, finalHfOptions);
623
+ footerContentByRId = renderHeaderFooterContentByRId(document?.package.footers, hfPMs, contentWidth, hfMetricsFooter, finalHfOptions);
624
+ };
625
+ rebuildHeaderFooterForLayout();
626
+ outcome.layout = newLayout;
627
+ recordPhaseDuration("layout-document", phaseStartedAt);
628
+ if (pagesContainer && painter) {
629
+ phaseStartedAt = performance.now();
630
+ const blockLookup = /* @__PURE__ */ new Map();
631
+ for (let i = 0; i < newBlocks.length; i++) {
632
+ const block = newBlocks[i];
633
+ const measure = newMeasures[i];
634
+ if (block && measure) blockLookup.set(String(block.id), {
635
+ block,
636
+ measure
637
+ });
638
+ }
639
+ for (const area of endnoteAreas?.areas ?? []) for (const [index, block] of area.blocks.entries()) {
640
+ const measure = area.measures[index];
641
+ if (!measure) continue;
642
+ const noteStory = endnoteAreas?.noteStoryByBlockId.get(String(block.id));
643
+ blockLookup.set(String(block.id), {
644
+ block,
645
+ measure,
646
+ ...noteStory === void 0 ? {} : { noteStory }
647
+ });
648
+ }
649
+ const continuationSeparator = endnoteAreas?.noteAreas.continuationSeparator;
650
+ if (continuationSeparator) blockLookup.set(String(continuationSeparator.block.id), continuationSeparator);
651
+ outcome.blockLookup = blockLookup;
652
+ const footnotesByPage = hasFootnotes ? buildFootnoteRenderItems(pageFootnoteMap, footnoteContentMap, document) : void 0;
653
+ const renderOpts = {
654
+ ...embeddedFontFamilies,
655
+ ...documentFontFacts === void 0 ? {} : { documentFontFacts },
656
+ pageGap,
657
+ showShadow: true,
658
+ blockLookup,
659
+ titlePg: hasTitlePg
660
+ };
661
+ if (showMarginGuides) {
662
+ renderOpts.showMarginGuides = true;
663
+ if (marginGuideColor !== void 0) renderOpts.marginGuideColor = marginGuideColor;
664
+ }
665
+ if (headerContentForRender) renderOpts.headerContent = headerContentForRender;
666
+ if (footerContentForRender) renderOpts.footerContent = footerContentForRender;
667
+ if (firstPageHeaderForRender) renderOpts.firstPageHeaderContent = firstPageHeaderForRender;
668
+ if (firstPageFooterForRender) renderOpts.firstPageFooterContent = firstPageFooterForRender;
669
+ if (headerContentByRId) renderOpts.headerContentByRId = headerContentByRId;
670
+ if (footerContentByRId) renderOpts.footerContentByRId = footerContentByRId;
671
+ if (sectionHeaderFooterRefs === void 0 && sectionProperties?.headerDistance !== void 0 && sectionProperties.headerDistance !== 0) renderOpts.headerDistance = twipsToPixels(sectionProperties.headerDistance);
672
+ if (sectionHeaderFooterRefs === void 0 && sectionProperties?.footerDistance !== void 0 && sectionProperties.footerDistance !== 0) renderOpts.footerDistance = twipsToPixels(sectionProperties.footerDistance);
673
+ if (sectionProperties?.pageBorders) renderOpts.pageBorders = sectionProperties.pageBorders;
674
+ if (_theme) renderOpts.theme = _theme;
675
+ if (footnotesByPage !== void 0 && footnotesByPage.size > 0) renderOpts.footnotesByPage = footnotesByPage;
676
+ const bookmarkPages = buildBookmarkPageMap(newLayout.pages, newBlocks);
677
+ if (bookmarkPages.size > 0) renderOpts.bookmarkPages = bookmarkPages;
678
+ const seqValues = buildSeqValues(newBlocks);
679
+ if (seqValues.size > 0) renderOpts.seqValues = seqValues;
680
+ const bookmarkText = buildBookmarkText(newBlocks, stabilizedFieldValues === void 0 ? { seqValues } : {
681
+ fieldValues: stabilizedFieldValues,
682
+ seqValues
683
+ });
684
+ if (bookmarkText.size > 0) renderOpts.bookmarkText = bookmarkText;
685
+ renderOpts.sectionPageCounts = buildSectionPageCounts(newLayout.pages);
686
+ if (document) {
687
+ const watermark = getDocumentWatermark(document);
688
+ if (watermark) renderOpts.watermark = watermark;
689
+ let watermarkByHeaderRId;
690
+ const headers = document.package.headers;
691
+ if (headers) {
692
+ watermarkByHeaderRId = /* @__PURE__ */ new Map();
693
+ for (const [rId, header] of headers) if (header.watermark) watermarkByHeaderRId.set(rId, header.watermark);
694
+ if (watermarkByHeaderRId.size > 0) renderOpts.watermarkByHeaderRId = watermarkByHeaderRId;
695
+ }
696
+ const pictureSources = new Set([watermark, ...watermarkByHeaderRId?.values() ?? []].filter((candidate) => candidate !== void 0).map((candidate) => resolveWatermarkImageSrc(document, candidate)));
697
+ const watermarkImageSrc = pictureSources.size === 1 ? [...pictureSources].at(0) : void 0;
698
+ if (watermarkImageSrc !== void 0) renderOpts.watermarkImageSrc = watermarkImageSrc;
699
+ }
700
+ if (displayListPagePainter) renderOpts.paintPage = displayListPagePainter({
701
+ layout: newLayout,
702
+ blockLookup,
703
+ doc: pagesContainer.ownerDocument,
704
+ ...document?.package.document.comments === void 0 ? {} : { comments: displayCommentsFrom(survivingComments(document)) },
705
+ ...displayListFurnitureFrom(renderOpts),
706
+ ...footnoteContentMap.size === 0 ? {} : { footnoteContentById: footnoteContentMap }
707
+ }).paintPage;
708
+ renderPages(newLayout.pages, pagesContainer, renderOpts);
709
+ recordPhaseDuration("render-pages", phaseStartedAt);
710
+ }
711
+ const measuredFontSet = readFontSetSignature();
712
+ labelMeasureCachesFontSet(measuredFontSet);
713
+ session.artifacts = pendingArtifacts;
714
+ session.lastTemplatePreview = pendingTemplatePreview;
715
+ session.lastEditorState = state;
716
+ session.lastPmDoc = state.doc;
717
+ session.lastMeasureInputs = {
718
+ ...measureInputs,
719
+ fontSet: measuredFontSet
720
+ };
721
+ recordLayoutComplete(reason);
722
+ } catch (error) {
723
+ const invalidHighlights = describeInvalidHighlightMarks(state.doc);
724
+ recordLayoutError(reason, invalidHighlights ? /* @__PURE__ */ new Error(`${String(error)} Invalid highlights: ${invalidHighlights}`) : error);
725
+ outcome = {};
726
+ }
727
+ syncCoordinator.onLayoutComplete(currentEpoch);
728
+ return outcome;
729
+ }
730
+ export { runLayoutPipelineWithPainter };