@superdoc-dev/cli 0.16.0-next.14 → 0.16.0-next.16

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 (2) hide show
  1. package/dist/index.js +866 -340
  2. package/package.json +7 -7
package/dist/index.js CHANGED
@@ -68110,7 +68110,7 @@ var init_remark_gfm_BhnWr3yf_es = __esm(() => {
68110
68110
  emptyOptions2 = {};
68111
68111
  });
68112
68112
 
68113
- // ../../packages/superdoc/dist/chunks/SuperConverter-CcHCWpfX.es.js
68113
+ // ../../packages/superdoc/dist/chunks/SuperConverter-EumzHoTv.es.js
68114
68114
  function getExtensionConfigField(extension$1, field, context = { name: "" }) {
68115
68115
  const fieldValue = extension$1.config[field];
68116
68116
  if (typeof fieldValue === "function")
@@ -77655,6 +77655,46 @@ function effectiveTableCellSpacing(spacing, isBoundary, padding) {
77655
77655
  return 0;
77656
77656
  return isBoundary ? Math.max(0, spacing - padding) : spacing;
77657
77657
  }
77658
+ function selectHeaderFooterVariantForPage({ documentPageNumber, sectionPageNumber, titlePg, alternateHeaders }) {
77659
+ if (!Number.isFinite(documentPageNumber) || !Number.isFinite(sectionPageNumber))
77660
+ return null;
77661
+ if (sectionPageNumber < 1)
77662
+ return null;
77663
+ if (sectionPageNumber === 1 && titlePg === true)
77664
+ return "first";
77665
+ if (alternateHeaders === true)
77666
+ return documentPageNumber % 2 === 0 ? "even" : "odd";
77667
+ return "default";
77668
+ }
77669
+ function candidateVariantsFor(variant) {
77670
+ return variant === "odd" ? ["odd", "default"] : [variant];
77671
+ }
77672
+ function sectionRefsFor(section, kind) {
77673
+ return kind === "header" ? section?.headerRefs : section?.footerRefs;
77674
+ }
77675
+ function resolveEffectiveHeaderFooterRef({ sections, sectionIndex, kind, variant }) {
77676
+ if (sectionIndex < 0)
77677
+ return null;
77678
+ const sectionsByIndex = /* @__PURE__ */ new Map;
77679
+ for (const section of sections)
77680
+ sectionsByIndex.set(section.sectionIndex, section);
77681
+ const candidates = candidateVariantsFor(variant);
77682
+ for (let currentIndex = sectionIndex;currentIndex >= 0; currentIndex -= 1) {
77683
+ const refs = sectionRefsFor(sectionsByIndex.get(currentIndex), kind);
77684
+ if (!refs)
77685
+ continue;
77686
+ for (const candidate of candidates) {
77687
+ const refId = refs[candidate];
77688
+ if (refId)
77689
+ return {
77690
+ refId,
77691
+ matchedSectionIndex: currentIndex,
77692
+ matchedVariant: candidate
77693
+ };
77694
+ }
77695
+ }
77696
+ return null;
77697
+ }
77658
77698
  function rescaleColumnWidths(measureColumnWidths, measureTotalWidth, fragmentWidth) {
77659
77699
  if (!measureColumnWidths || measureColumnWidths.length === 0 || measureTotalWidth <= fragmentWidth || measureTotalWidth <= 0)
77660
77700
  return;
@@ -78058,6 +78098,77 @@ function getSdtContainerKeyForBlock(block) {
78058
78098
  return null;
78059
78099
  return getSdtContainerKey(block.attrs?.sdt, block.attrs?.containerSdt);
78060
78100
  }
78101
+ function toUpperRoman$1(value) {
78102
+ if (value < 1 || value > 3999)
78103
+ return String(value);
78104
+ const values = [
78105
+ 1000,
78106
+ 900,
78107
+ 500,
78108
+ 400,
78109
+ 100,
78110
+ 90,
78111
+ 50,
78112
+ 40,
78113
+ 10,
78114
+ 9,
78115
+ 5,
78116
+ 4,
78117
+ 1
78118
+ ];
78119
+ const numerals = [
78120
+ "M",
78121
+ "CM",
78122
+ "D",
78123
+ "CD",
78124
+ "C",
78125
+ "XC",
78126
+ "L",
78127
+ "XL",
78128
+ "X",
78129
+ "IX",
78130
+ "V",
78131
+ "IV",
78132
+ "I"
78133
+ ];
78134
+ let remaining = value;
78135
+ let result = "";
78136
+ for (let i$1 = 0;i$1 < values.length; i$1 += 1)
78137
+ while (remaining >= values[i$1]) {
78138
+ result += numerals[i$1];
78139
+ remaining -= values[i$1];
78140
+ }
78141
+ return result;
78142
+ }
78143
+ function toUpperLetter$1(value) {
78144
+ const normalized = Math.max(1, value);
78145
+ const index2 = (normalized - 1) % 26;
78146
+ const repeatCount = Math.floor((normalized - 1) / 26) + 1;
78147
+ return String.fromCharCode(65 + index2).repeat(repeatCount);
78148
+ }
78149
+ function formatPageNumber(pageNumber, format) {
78150
+ const value = Math.max(1, Math.trunc(Number.isFinite(pageNumber) ? pageNumber : 1));
78151
+ switch (format) {
78152
+ case "upperRoman":
78153
+ return toUpperRoman$1(value);
78154
+ case "lowerRoman":
78155
+ return toUpperRoman$1(value).toLowerCase();
78156
+ case "upperLetter":
78157
+ return toUpperLetter$1(value);
78158
+ case "lowerLetter":
78159
+ return toUpperLetter$1(value).toLowerCase();
78160
+ case "numberInDash":
78161
+ return `- ${value} -`;
78162
+ case "decimal":
78163
+ default:
78164
+ return String(value);
78165
+ }
78166
+ }
78167
+ function formatPageNumberFieldValue$1(pageNumber, fieldFormat) {
78168
+ const format = fieldFormat?.format ?? "decimal";
78169
+ const formatted = formatPageNumber(pageNumber, format);
78170
+ return fieldFormat?.zeroPadding && format === "decimal" ? formatted.padStart(fieldFormat.zeroPadding, "0") : formatted;
78171
+ }
78061
78172
  function resolveSpacingIndent(style, numbering) {
78062
78173
  const spacing = {
78063
78174
  before: style.spacing?.before ?? 0,
@@ -82446,10 +82557,48 @@ function convertTiffToPng(data) {
82446
82557
  return null;
82447
82558
  }
82448
82559
  }
82449
- function preProcessPageInstruction(nodesToCombine, _instrText, fieldRunRPr = null) {
82560
+ function parsePageNumberFieldSwitches(instruction, fieldType) {
82561
+ const normalizedInstruction = typeof instruction === "string" ? instruction.trim().replace(/\s+/g, " ") : fieldType;
82562
+ const result = {};
82563
+ if (normalizedInstruction && normalizedInstruction !== fieldType)
82564
+ result.instruction = normalizedInstruction;
82565
+ for (const match of normalizedInstruction.matchAll(/\\\*\s+("[^"]+"|\S+)/g)) {
82566
+ const rawValue = unquote(match[1]);
82567
+ const mapped = GENERAL_FORMATS.get(rawValue) ?? CASE_INSENSITIVE_GENERAL_FORMATS.get(rawValue.toLowerCase());
82568
+ if (mapped) {
82569
+ result.pageNumberFormat = mapped;
82570
+ break;
82571
+ }
82572
+ }
82573
+ for (const match of normalizedInstruction.matchAll(/\\#\s+("[^"]+"|\S+)/g)) {
82574
+ const picture = unquote(match[1]);
82575
+ if (/^0+$/.test(picture)) {
82576
+ result.pageNumberFormat ??= "decimal";
82577
+ result.pageNumberZeroPadding = picture.length;
82578
+ break;
82579
+ }
82580
+ }
82581
+ return result;
82582
+ }
82583
+ function formatPageNumberFieldValue(pageNumber, attrs = {}) {
82584
+ return formatPageNumberFieldValue$1(pageNumber, {
82585
+ format: attrs.pageNumberFormat || "decimal",
82586
+ zeroPadding: attrs.pageNumberZeroPadding ?? undefined
82587
+ });
82588
+ }
82589
+ function unquote(value) {
82590
+ return value.startsWith('"') && value.endsWith('"') ? value.slice(1, -1) : value;
82591
+ }
82592
+ function preProcessPageInstruction(nodesToCombine, instrText = "PAGE", options = {}) {
82593
+ const fieldRunRPr = options.fieldRunRPr ?? null;
82594
+ const normalizedInstruction = typeof instrText === "string" && instrText.trim() ? instrText.trim().replace(/\s+/g, " ") : "PAGE";
82450
82595
  const pageNumNode = {
82451
82596
  name: "sd:autoPageNumber",
82452
- type: "element"
82597
+ type: "element",
82598
+ attributes: {
82599
+ instruction: normalizedInstruction,
82600
+ ...parsePageNumberFieldSwitches(normalizedInstruction, "PAGE")
82601
+ }
82453
82602
  };
82454
82603
  let foundContentRPr = false;
82455
82604
  nodesToCombine.forEach((n) => {
@@ -82463,11 +82612,12 @@ function preProcessPageInstruction(nodesToCombine, _instrText, fieldRunRPr = nul
82463
82612
  pageNumNode.elements = [fieldRunRPr];
82464
82613
  return [pageNumNode];
82465
82614
  }
82466
- function preProcessNumPagesInstruction(nodesToCombine, _instrText, fieldRunRPr = null) {
82615
+ function preProcessNumPagesInstruction(nodesToCombine, instrText = "NUMPAGES", options = {}) {
82616
+ const fieldRunRPr = options.fieldRunRPr ?? null;
82467
82617
  const totalPageNumNode = {
82468
82618
  name: "sd:totalPageNumber",
82469
82619
  type: "element",
82470
- attributes: {}
82620
+ attributes: { ...parsePageNumberFieldSwitches(instrText, "NUMPAGES") }
82471
82621
  };
82472
82622
  const cachedText = extractCachedText$1(nodesToCombine);
82473
82623
  if (cachedText)
@@ -82496,7 +82646,7 @@ function extractCachedText$1(nodes) {
82496
82646
  }
82497
82647
  return texts.join("");
82498
82648
  }
82499
- function preProcessPageRefInstruction(nodesToCombine, instrText) {
82649
+ function preProcessPageRefInstruction(nodesToCombine, instrText, options = {}) {
82500
82650
  return [{
82501
82651
  name: "sd:pageReference",
82502
82652
  type: "element",
@@ -82505,7 +82655,7 @@ function preProcessPageRefInstruction(nodesToCombine, instrText) {
82505
82655
  }];
82506
82656
  }
82507
82657
  function resolveHyperlinkAttributes(instruction, docx) {
82508
- const urlMatch = instruction.match(/HYPERLINK\s+"([^"]+)"/);
82658
+ const urlMatch = instruction.match(/^\s*HYPERLINK\s+"([^"]+)"/i);
82509
82659
  if (urlMatch && urlMatch.length >= 2) {
82510
82660
  const url2 = urlMatch[1];
82511
82661
  const relationships = docx?.["word/_rels/document.xml.rels"]?.elements?.find((el) => el.name === "Relationships");
@@ -82545,7 +82695,8 @@ function resolveHyperlinkAttributes(instruction, docx) {
82545
82695
  return null;
82546
82696
  return { ...parsedSwitches };
82547
82697
  }
82548
- function preProcessHyperlinkInstruction(nodesToCombine, instruction, docx) {
82698
+ function preProcessHyperlinkInstruction(nodesToCombine, instruction, options = {}) {
82699
+ const docx = options.docx;
82549
82700
  return [{
82550
82701
  name: "w:hyperlink",
82551
82702
  type: "element",
@@ -82553,7 +82704,7 @@ function preProcessHyperlinkInstruction(nodesToCombine, instruction, docx) {
82553
82704
  elements: nodesToCombine
82554
82705
  }];
82555
82706
  }
82556
- function preProcessTocInstruction(nodesToCombine, instrText) {
82707
+ function preProcessTocInstruction(nodesToCombine, instrText, options = {}) {
82557
82708
  return [{
82558
82709
  name: "sd:tableOfContents",
82559
82710
  type: "element",
@@ -82604,10 +82755,11 @@ function buildBlockFieldNode(xmlName, nodesToCombine, instrText, instructionToke
82604
82755
  elements: normalizeFieldContentToParagraphs(nodesToCombine)
82605
82756
  }];
82606
82757
  }
82607
- function preProcessIndexInstruction(nodesToCombine, instrText, _docx, instructionTokens = null) {
82608
- return buildBlockFieldNode("sd:index", nodesToCombine, instrText, instructionTokens);
82758
+ function preProcessIndexInstruction(nodesToCombine, instrText, options = {}, legacyInstructionTokens = null) {
82759
+ return buildBlockFieldNode("sd:index", nodesToCombine, instrText, options?.instructionTokens ?? legacyInstructionTokens);
82609
82760
  }
82610
- function preProcessXeInstruction(nodesToCombine, instrText, _docx, instructionTokens = null) {
82761
+ function preProcessXeInstruction(nodesToCombine, instrText, options = {}) {
82762
+ const instructionTokens = options.instructionTokens ?? null;
82611
82763
  return [{
82612
82764
  name: "sd:indexEntry",
82613
82765
  type: "element",
@@ -82618,7 +82770,8 @@ function preProcessXeInstruction(nodesToCombine, instrText, _docx, instructionTo
82618
82770
  elements: nodesToCombine
82619
82771
  }];
82620
82772
  }
82621
- function preProcessTcInstruction(nodesToCombine, instrText, _docx, instructionTokens = null) {
82773
+ function preProcessTcInstruction(nodesToCombine, instrText, options = {}) {
82774
+ const instructionTokens = options.instructionTokens ?? null;
82622
82775
  return [{
82623
82776
  name: "sd:tableOfContentsEntry",
82624
82777
  type: "element",
@@ -82629,7 +82782,7 @@ function preProcessTcInstruction(nodesToCombine, instrText, _docx, instructionTo
82629
82782
  elements: nodesToCombine
82630
82783
  }];
82631
82784
  }
82632
- function preProcessRefInstruction(nodesToCombine, instrText) {
82785
+ function preProcessRefInstruction(nodesToCombine, instrText, options = {}) {
82633
82786
  return [{
82634
82787
  name: "sd:crossReference",
82635
82788
  type: "element",
@@ -82640,7 +82793,7 @@ function preProcessRefInstruction(nodesToCombine, instrText) {
82640
82793
  elements: nodesToCombine
82641
82794
  }];
82642
82795
  }
82643
- function preProcessNoterefInstruction(nodesToCombine, instrText) {
82796
+ function preProcessNoterefInstruction(nodesToCombine, instrText, options = {}) {
82644
82797
  return [{
82645
82798
  name: "sd:crossReference",
82646
82799
  type: "element",
@@ -82651,7 +82804,7 @@ function preProcessNoterefInstruction(nodesToCombine, instrText) {
82651
82804
  elements: nodesToCombine
82652
82805
  }];
82653
82806
  }
82654
- function preProcessStylerefInstruction(nodesToCombine, instrText) {
82807
+ function preProcessStylerefInstruction(nodesToCombine, instrText, options = {}) {
82655
82808
  return [{
82656
82809
  name: "sd:crossReference",
82657
82810
  type: "element",
@@ -82662,7 +82815,8 @@ function preProcessStylerefInstruction(nodesToCombine, instrText) {
82662
82815
  elements: nodesToCombine
82663
82816
  }];
82664
82817
  }
82665
- function preProcessSeqInstruction(nodesToCombine, instrText, _docx, instructionTokens = null) {
82818
+ function preProcessSeqInstruction(nodesToCombine, instrText, options = {}) {
82819
+ const instructionTokens = options.instructionTokens ?? null;
82666
82820
  return [{
82667
82821
  name: "sd:sequenceField",
82668
82822
  type: "element",
@@ -82673,7 +82827,8 @@ function preProcessSeqInstruction(nodesToCombine, instrText, _docx, instructionT
82673
82827
  elements: nodesToCombine
82674
82828
  }];
82675
82829
  }
82676
- function preProcessCitationInstruction(nodesToCombine, instrText, _docx, instructionTokens = null) {
82830
+ function preProcessCitationInstruction(nodesToCombine, instrText, options = {}) {
82831
+ const instructionTokens = options.instructionTokens ?? null;
82677
82832
  return [{
82678
82833
  name: "sd:citation",
82679
82834
  type: "element",
@@ -82684,10 +82839,11 @@ function preProcessCitationInstruction(nodesToCombine, instrText, _docx, instruc
82684
82839
  elements: nodesToCombine
82685
82840
  }];
82686
82841
  }
82687
- function preProcessBibliographyInstruction(nodesToCombine, instrText, _docx, instructionTokens = null) {
82688
- return buildBlockFieldNode("sd:bibliography", nodesToCombine, instrText, instructionTokens);
82842
+ function preProcessBibliographyInstruction(nodesToCombine, instrText, options = {}, legacyInstructionTokens = null) {
82843
+ return buildBlockFieldNode("sd:bibliography", nodesToCombine, instrText, options?.instructionTokens ?? legacyInstructionTokens);
82689
82844
  }
82690
- function preProcessTaInstruction(nodesToCombine, instrText, _docx, instructionTokens = null) {
82845
+ function preProcessTaInstruction(nodesToCombine, instrText, options = {}) {
82846
+ const instructionTokens = options.instructionTokens ?? null;
82691
82847
  return [{
82692
82848
  name: "sd:authorityEntry",
82693
82849
  type: "element",
@@ -82698,11 +82854,11 @@ function preProcessTaInstruction(nodesToCombine, instrText, _docx, instructionTo
82698
82854
  elements: nodesToCombine
82699
82855
  }];
82700
82856
  }
82701
- function preProcessToaInstruction(nodesToCombine, instrText, _docx, instructionTokens = null) {
82702
- return buildBlockFieldNode("sd:tableOfAuthorities", nodesToCombine, instrText, instructionTokens);
82857
+ function preProcessToaInstruction(nodesToCombine, instrText, options = {}, legacyInstructionTokens = null) {
82858
+ return buildBlockFieldNode("sd:tableOfAuthorities", nodesToCombine, instrText, options?.instructionTokens ?? legacyInstructionTokens);
82703
82859
  }
82704
- function preProcessDocumentStatInstruction(nodesToCombine, instrText, _docxOrFieldRunRPr = null, instructionTokensOrFieldRunRPr = null, fieldRunRPr = null) {
82705
- const effectiveFieldRunRPr = fieldRunRPr ?? (instructionTokensOrFieldRunRPr?.name === "w:rPr" ? instructionTokensOrFieldRunRPr : null) ?? (_docxOrFieldRunRPr?.name === "w:rPr" ? _docxOrFieldRunRPr : null);
82860
+ function preProcessDocumentStatInstruction(nodesToCombine, instrText, options = {}) {
82861
+ const fieldRunRPr = options.fieldRunRPr ?? null;
82706
82862
  const statFieldNode = {
82707
82863
  name: "sd:documentStatField",
82708
82864
  type: "element",
@@ -82719,10 +82875,13 @@ function preProcessDocumentStatInstruction(nodesToCombine, instrText, _docxOrFie
82719
82875
  foundContentRPr = true;
82720
82876
  }
82721
82877
  });
82722
- if (!foundContentRPr && effectiveFieldRunRPr && effectiveFieldRunRPr.name === "w:rPr")
82723
- statFieldNode.elements = [effectiveFieldRunRPr, ...nodesToCombine];
82878
+ if (!foundContentRPr && fieldRunRPr && fieldRunRPr.name === "w:rPr")
82879
+ statFieldNode.elements = [fieldRunRPr, ...nodesToCombine];
82724
82880
  return [statFieldNode];
82725
82881
  }
82882
+ function extractFieldKeyword(instruction) {
82883
+ return String(instruction ?? "").trim().split(/\s+/)[0].toUpperCase();
82884
+ }
82726
82885
  function scanFieldSequence(nodes, beginIndex) {
82727
82886
  let instrText = "";
82728
82887
  let separateIndex = -1;
@@ -82754,7 +82913,7 @@ function scanFieldSequence(nodes, beginIndex) {
82754
82913
  if (endIndex === -1)
82755
82914
  return null;
82756
82915
  return {
82757
- fieldType: instrText.trim().split(" ")[0],
82916
+ fieldType: extractFieldKeyword(instrText),
82758
82917
  instrText: instrText.trim(),
82759
82918
  contentNodes,
82760
82919
  fieldRunRPr,
@@ -98239,7 +98398,16 @@ function parseSeqInstruction(instruction) {
98239
98398
  function extractResolvedText(content$2) {
98240
98399
  if (!Array.isArray(content$2))
98241
98400
  return "";
98242
- return content$2.filter((n) => n.type === "text").map((n) => n.text || "").join("");
98401
+ let text$2 = "";
98402
+ for (const node3 of content$2) {
98403
+ if (!node3)
98404
+ continue;
98405
+ if (node3.type === "text")
98406
+ text$2 += node3.text || "";
98407
+ if (Array.isArray(node3.content))
98408
+ text$2 += extractResolvedText(node3.content);
98409
+ }
98410
+ return text$2;
98243
98411
  }
98244
98412
  function deriveRightAlignPageNumbers(content$2) {
98245
98413
  for (const para of content$2) {
@@ -98250,6 +98418,33 @@ function deriveRightAlignPageNumbers(content$2) {
98250
98418
  }
98251
98419
  return true;
98252
98420
  }
98421
+ function pageNumberFormatToInstructionSwitch(pageNumberFormat) {
98422
+ for (const [switchName, format] of Object.entries(PAGE_VALUE_FORMAT_SWITCHES))
98423
+ if (format === pageNumberFormat)
98424
+ return switchName;
98425
+ }
98426
+ function getPageNumberFieldAttrs$1(node3) {
98427
+ const attrs = {};
98428
+ if (node3.attributes?.instruction)
98429
+ attrs.instruction = node3.attributes.instruction;
98430
+ if (node3.attributes?.pageNumberFormat)
98431
+ attrs.pageNumberFormat = node3.attributes.pageNumberFormat;
98432
+ if (node3.attributes?.pageNumberZeroPadding != null)
98433
+ attrs.pageNumberZeroPadding = Number(node3.attributes.pageNumberZeroPadding);
98434
+ return attrs;
98435
+ }
98436
+ function getPageInstructionText(attrs = {}) {
98437
+ if (typeof attrs.instruction === "string" && attrs.instruction.trim())
98438
+ return attrs.instruction.trim();
98439
+ if (typeof attrs.pageNumberFormat === "string") {
98440
+ const instructionSwitch = pageNumberFormatToInstructionSwitch(attrs.pageNumberFormat);
98441
+ if (instructionSwitch)
98442
+ return `PAGE \\* ${instructionSwitch}${typeof attrs.pageNumberZeroPadding === "number" && attrs.pageNumberZeroPadding > 0 ? ` \\# ${"0".repeat(attrs.pageNumberZeroPadding)}` : ""}`;
98443
+ }
98444
+ if (typeof attrs.pageNumberZeroPadding === "number" && attrs.pageNumberZeroPadding > 0)
98445
+ return `PAGE \\# ${"0".repeat(attrs.pageNumberZeroPadding)}`;
98446
+ return "PAGE";
98447
+ }
98253
98448
  function buildComplexFieldRuns({ instruction, cachedText, outputMarks, dirty }) {
98254
98449
  const beginAttrs = { "w:fldCharType": "begin" };
98255
98450
  if (dirty)
@@ -98315,10 +98510,24 @@ function buildComplexFieldRuns({ instruction, cachedText, outputMarks, dirty })
98315
98510
  }
98316
98511
  ];
98317
98512
  }
98513
+ function getPageNumberFieldAttrs(node3) {
98514
+ const attrs = {};
98515
+ if (node3.attributes?.instruction)
98516
+ attrs.instruction = node3.attributes.instruction;
98517
+ if (node3.attributes?.pageNumberFormat)
98518
+ attrs.pageNumberFormat = node3.attributes.pageNumberFormat;
98519
+ if (node3.attributes?.pageNumberZeroPadding != null)
98520
+ attrs.pageNumberZeroPadding = Number(node3.attributes.pageNumberZeroPadding);
98521
+ return attrs;
98522
+ }
98318
98523
  function resolveCachedPageCount(params3, node3) {
98319
98524
  const cacheMap = params3.statFieldCacheMap;
98320
- if (cacheMap?.has?.("NUMPAGES"))
98525
+ if (cacheMap?.has?.("NUMPAGES")) {
98526
+ const pageCount = Number(cacheMap.get("NUMPAGES"));
98527
+ if (node3.attrs?.pageNumberFormat || node3.attrs?.pageNumberZeroPadding)
98528
+ return formatPageNumberFieldValue(pageCount, node3.attrs);
98321
98529
  return String(cacheMap.get("NUMPAGES"));
98530
+ }
98322
98531
  if (node3.attrs?.resolvedText)
98323
98532
  return String(node3.attrs.resolvedText);
98324
98533
  if (node3.attrs?.importedCachedText)
@@ -100685,11 +100894,37 @@ function translateHeadingNode(params3) {
100685
100894
  function mergeMcIgnorable(defaultIgnorable = "", originalIgnorable = "") {
100686
100895
  return [...new Set([...defaultIgnorable.split(/\s+/).filter(Boolean), ...originalIgnorable.split(/\s+/).filter(Boolean)])].join(" ");
100687
100896
  }
100897
+ function normalizeDocumentBackgroundColorForExport(value) {
100898
+ if (typeof value !== "string")
100899
+ return null;
100900
+ const trimmed = value.trim();
100901
+ const hex = trimmed.startsWith("#") ? trimmed.slice(1) : trimmed;
100902
+ if (!/^[0-9a-fA-F]{6}$/.test(hex))
100903
+ return null;
100904
+ return hex.toUpperCase();
100905
+ }
100906
+ function translateDocumentBackgroundNode(params3) {
100907
+ const background = params3?.node?.attrs?.documentBackground;
100908
+ if (!background || typeof background !== "object")
100909
+ return null;
100910
+ if (background.originalXml && typeof background.originalXml === "object")
100911
+ return carbonCopy(background.originalXml);
100912
+ const color2 = normalizeDocumentBackgroundColorForExport(background.color);
100913
+ if (!color2)
100914
+ return null;
100915
+ return {
100916
+ type: "element",
100917
+ name: "w:background",
100918
+ attributes: { "w:color": color2 },
100919
+ elements: []
100920
+ };
100921
+ }
100688
100922
  function translateDocumentNode(params3) {
100689
100923
  const bodyNode = {
100690
100924
  type: "body",
100691
100925
  content: params3.node.content
100692
100926
  };
100927
+ const translatedBackgroundNode = translateDocumentBackgroundNode(params3);
100693
100928
  const translatedBodyNode = exportSchemaToJson({
100694
100929
  ...params3,
100695
100930
  node: bodyNode
@@ -100704,7 +100939,7 @@ function translateDocumentNode(params3) {
100704
100939
  attributes["mc:Ignorable"] = mergedIgnorable;
100705
100940
  const node3 = {
100706
100941
  name: "w:document",
100707
- elements: [translatedBodyNode],
100942
+ elements: translatedBackgroundNode ? [translatedBackgroundNode, translatedBodyNode] : [translatedBodyNode],
100708
100943
  attributes
100709
100944
  };
100710
100945
  normalizePgMarTwipsInTree(node3);
@@ -102320,6 +102555,18 @@ function computeWordParagraphLayout(input) {
102320
102555
  };
102321
102556
  return layout;
102322
102557
  }
102558
+ function getPageNumberFieldFormat(attrs) {
102559
+ if (!attrs)
102560
+ return;
102561
+ const format = typeof attrs.pageNumberFormat === "string" ? attrs.pageNumberFormat : undefined;
102562
+ const zeroPadding = typeof attrs.pageNumberZeroPadding === "number" && Number.isFinite(attrs.pageNumberZeroPadding) ? attrs.pageNumberZeroPadding : undefined;
102563
+ if (!format && !zeroPadding)
102564
+ return;
102565
+ return {
102566
+ ...format ? { format } : {},
102567
+ ...zeroPadding ? { zeroPadding } : {}
102568
+ };
102569
+ }
102323
102570
  function textNodeToRun({ node: node3, positions, storyKey, defaultFont, defaultSize, inheritedMarks = [], sdtMetadata, hyperlinkConfig = DEFAULT_HYPERLINK_CONFIG, themeColors, enableComments, runProperties, inlineRunProperties, converterContext }) {
102324
102571
  let run$1 = {
102325
102572
  text: node3.text || "",
@@ -103545,6 +103792,9 @@ function tokenNodeToRun({ node: node3, positions, storyKey, defaultFont, default
103545
103792
  fontFamily: defaultFont,
103546
103793
  fontSize: defaultSize
103547
103794
  };
103795
+ const pageNumberFieldFormat = getPageNumberFieldFormat(node3.attrs);
103796
+ if (pageNumberFieldFormat)
103797
+ run$1.pageNumberFieldFormat = pageNumberFieldFormat;
103548
103798
  const pos = positions.get(node3);
103549
103799
  if (pos) {
103550
103800
  run$1.pmStart = pos.start;
@@ -107647,31 +107897,29 @@ function createHeaderFooterPart(editor, input) {
107647
107897
  throw new Error(`[createHeaderFooterPart] Failed to create ${newPartPath}: mutation rolled back (possible afterCommit degradation).`);
107648
107898
  return finalResult;
107649
107899
  }
107650
- function resolveEffectiveRef(editor, sections, startSectionIndex, kind, variant) {
107651
- for (let i$1 = startSectionIndex - 1;i$1 >= 0; i$1--) {
107652
- const section = sections.find((s) => s.range.sectionIndex === i$1);
107653
- if (!section)
107654
- continue;
107655
- const sectPr = readTargetSectPr(editor, section);
107656
- if (!sectPr)
107657
- continue;
107658
- const refs = readSectPrHeaderFooterRefs(sectPr, kind);
107659
- if (!refs)
107660
- continue;
107661
- if (refs[variant])
107662
- return {
107663
- refId: refs[variant],
107664
- resolvedFromSection: section.address,
107665
- resolvedVariant: variant
107666
- };
107667
- if (variant !== "default" && refs.default)
107668
- return {
107669
- refId: refs.default,
107670
- resolvedFromSection: section.address,
107671
- resolvedVariant: "default"
107672
- };
107673
- }
107674
- return null;
107900
+ function resolveEffectiveRef(sections, startSectionIndex, kind, variant) {
107901
+ const refsFor = (section, refKind) => refKind === "header" ? section.range.headerRefs ?? section.domain.headerRefs : section.range.footerRefs ?? section.domain.footerRefs;
107902
+ const resolved = resolveEffectiveHeaderFooterRef({
107903
+ sections: sections.map((section) => ({
107904
+ sectionIndex: section.range.sectionIndex,
107905
+ titlePg: section.range.titlePg,
107906
+ headerRefs: refsFor(section, "header"),
107907
+ footerRefs: refsFor(section, "footer")
107908
+ })),
107909
+ sectionIndex: startSectionIndex - 1,
107910
+ kind,
107911
+ variant
107912
+ });
107913
+ if (!resolved)
107914
+ return null;
107915
+ const resolvedSection = sections.find((section) => section.range.sectionIndex === resolved.matchedSectionIndex);
107916
+ if (!resolvedSection)
107917
+ return null;
107918
+ return {
107919
+ refId: resolved.refId,
107920
+ resolvedFromSection: resolvedSection.address,
107921
+ resolvedVariant: resolved.matchedVariant
107922
+ };
107675
107923
  }
107676
107924
  function getConverter$5(editor) {
107677
107925
  return editor.converter;
@@ -107748,7 +107996,7 @@ function setLinkedToPreviousMutation(sectPr, projection, sections, kind, variant
107748
107996
  message: `${operationName} already has an explicit reference.`
107749
107997
  }
107750
107998
  };
107751
- const resolved = resolveEffectiveRef(editor, sections, projection.range.sectionIndex, kind, variant);
107999
+ const resolved = resolveEffectiveRef(sections, projection.range.sectionIndex, kind, variant);
107752
108000
  if (dryRun) {
107753
108001
  setSectPrHeaderFooterRef(sectPr, kind, variant, "(dry-run)");
107754
108002
  return;
@@ -108264,7 +108512,7 @@ function ensureExplicitHeaderFooterSlot(editor, input) {
108264
108512
  created: false
108265
108513
  };
108266
108514
  }
108267
- const inheritedRef = resolveEffectiveRef(editor, sections, sections.indexOf(projection), kind, variant);
108515
+ const inheritedRef = resolveEffectiveRef(sections, sections.indexOf(projection), kind, variant);
108268
108516
  const effectiveSourceRefId = sourceRefId ?? inheritedRef?.refId ?? undefined;
108269
108517
  let result = null;
108270
108518
  if (!compoundMutation({
@@ -108331,7 +108579,7 @@ function resolveHeaderFooterSlotRuntime(hostEditor, locator, options = {}) {
108331
108579
  storyKey,
108332
108580
  resolution
108333
108581
  });
108334
- effectiveRefId = resolveEffectiveRef(hostEditor, sections, projection.range.sectionIndex, headerFooterKind, variant)?.refId ?? null;
108582
+ effectiveRefId = resolveEffectiveRef(sections, projection.range.sectionIndex, headerFooterKind, variant)?.refId ?? null;
108335
108583
  }
108336
108584
  const isInherited = explicitRefId === null;
108337
108585
  const onWrite = locator.onWrite ?? "materializeIfInherited";
@@ -118931,8 +119179,9 @@ var isRegExp = (value) => {
118931
119179
  domEnvironment$1 = env || null;
118932
119180
  }, MM_ANISOTROPIC = 8, EMF_SIGNATURE = 1179469088, EMF_PLUS_SIGNATURE = 726027589, EMR_COMMENT = 70, EMF_PLUS_OBJECT = 16392, EMF_PLUS_OBJECT_TYPE_IMAGE = 5, EMF_PLUS_IMAGE_TYPE_BITMAP = 1, EMF_PLUS_BITMAP_TYPE_PIXEL = 0, EMF_PLUS_BITMAP_TYPE_COMPRESSED = 1, EMF_PLUS_PIXEL_FORMAT_INDEXED_FLAG = 65536, EMF_PLUS_PIXEL_FORMAT_24BPP_RGB = 137224, EMF_PLUS_PIXEL_FORMAT_32BPP_RGB = 139273, EMF_PLUS_PIXEL_FORMAT_32BPP_ARGB = 2498570, EMF_PLUS_PIXEL_FORMAT_32BPP_PARGB = 925707, MAX_PIXEL_BITMAP_PIXELS = 1e8, base64ToArrayBuffer, require_common, require_trees, require_adler32, require_crc32, require_messages, require_deflate$1, require_strings, require_zstream, require_deflate, require_inffast, require_inftrees, require_inflate$1, require_constants2, require_gzheader, require_inflate, require_pako, import_UTIF, domEnvironment = null, MAX_PIXEL_COUNT = 1e8, setTiffDomEnvironment = (env) => {
118933
119181
  domEnvironment = env || null;
118934
- }, getInstructionPreProcessor = (instruction) => {
118935
- switch (instruction.split(" ")[0]) {
119182
+ }, GENERAL_FORMATS, CASE_INSENSITIVE_GENERAL_FORMATS, getInstructionPreProcessor = (instruction) => {
119183
+ const rawInstructionType = String(instruction ?? "").trim().split(/\s+/)[0];
119184
+ switch (extractFieldKeyword(instruction)) {
118936
119185
  case "PAGE":
118937
119186
  return preProcessPageInstruction;
118938
119187
  case "NUMPAGES":
@@ -118959,6 +119208,8 @@ var isRegExp = (value) => {
118959
119208
  case "STYLEREF":
118960
119209
  return preProcessStylerefInstruction;
118961
119210
  case "SEQ":
119211
+ if (rawInstructionType !== "SEQ")
119212
+ return null;
118962
119213
  return preProcessSeqInstruction;
118963
119214
  case "CITATION":
118964
119215
  return preProcessCitationInstruction;
@@ -119032,10 +119283,9 @@ var isRegExp = (value) => {
119032
119283
  if (node3.name === "w:fldSimple") {
119033
119284
  const instr = node3.attributes?.["w:instr"];
119034
119285
  if (typeof instr === "string") {
119035
- const instructionType = instr.trim().split(" ")[0];
119036
- const instructionPreProcessor = getInstructionPreProcessor(instructionType);
119286
+ const instructionPreProcessor = getInstructionPreProcessor(instr);
119037
119287
  if (instructionPreProcessor) {
119038
- const processed = instructionPreProcessor(node3.elements ?? [], instr, docx, null);
119288
+ const processed = instructionPreProcessor(node3.elements ?? [], instr, { docx });
119039
119289
  if (collecting) {
119040
119290
  collectedNodesStack[collectedNodesStack.length - 1].push(...processed);
119041
119291
  rawCollectedNodesStack[rawCollectedNodesStack.length - 1].push(...processed);
@@ -119167,11 +119417,14 @@ var isRegExp = (value) => {
119167
119417
  unpairedEndPreserveRaw
119168
119418
  };
119169
119419
  }, _processCombinedNodesForFldChar = (nodesToCombine = [], instrText, docx, instructionTokens, fieldRunRPr) => {
119170
- const instructionType = instrText.trim().split(" ")[0];
119171
- const instructionPreProcessor = getInstructionPreProcessor(instructionType);
119420
+ const instructionPreProcessor = getInstructionPreProcessor(instrText);
119172
119421
  if (instructionPreProcessor)
119173
119422
  return {
119174
- nodes: instructionPreProcessor(nodesToCombine, instrText, docx, instructionTokens, fieldRunRPr),
119423
+ nodes: instructionPreProcessor(nodesToCombine, instrText, {
119424
+ docx,
119425
+ instructionTokens,
119426
+ fieldRunRPr
119427
+ }),
119175
119428
  handled: true
119176
119429
  };
119177
119430
  return {
@@ -119179,7 +119432,7 @@ var isRegExp = (value) => {
119179
119432
  handled: false
119180
119433
  };
119181
119434
  }, applyConstructiveFieldInterpretation = (rawNodes, instrText, docx) => {
119182
- if (instrText.split(" ")[0] !== "HYPERLINK")
119435
+ if (extractFieldKeyword(instrText) !== "HYPERLINK")
119183
119436
  return;
119184
119437
  const linkAttributes = resolveHyperlinkAttributes(instrText, docx);
119185
119438
  if (!linkAttributes)
@@ -119334,8 +119587,7 @@ var isRegExp = (value) => {
119334
119587
  const fldType = node3.elements?.find((el) => el.name === "w:fldChar")?.attributes?.["w:fldCharType"];
119335
119588
  if (node3.name === "w:fldSimple") {
119336
119589
  const instrAttr = node3.attributes?.["w:instr"] || "";
119337
- const fieldType = instrAttr.trim().split(/\s+/)[0];
119338
- const fldSimplePreprocessor = getHeaderFooterFieldPreprocessor(fieldType);
119590
+ const fldSimplePreprocessor = getHeaderFooterFieldPreprocessor(extractFieldKeyword(instrAttr));
119339
119591
  if (fldSimplePreprocessor) {
119340
119592
  const contentNodes = node3.elements || [];
119341
119593
  let fieldRunRPr = null;
@@ -119346,7 +119598,7 @@ var isRegExp = (value) => {
119346
119598
  break;
119347
119599
  }
119348
119600
  }
119349
- const processedField = fldSimplePreprocessor(contentNodes, instrAttr.trim(), fieldRunRPr);
119601
+ const processedField = fldSimplePreprocessor(contentNodes, instrAttr.trim(), { fieldRunRPr });
119350
119602
  processedNodes.push(...processedField);
119351
119603
  i$1++;
119352
119604
  continue;
@@ -119368,7 +119620,7 @@ var isRegExp = (value) => {
119368
119620
  if (fieldInfo && complexFieldPreprocessor) {
119369
119621
  const preprocessor = complexFieldPreprocessor;
119370
119622
  const contentNodes = fieldInfo.contentNodes;
119371
- const processedField = preprocessor(contentNodes, fieldInfo.instrText, fieldInfo.fieldRunRPr);
119623
+ const processedField = preprocessor(contentNodes, fieldInfo.instrText, { fieldRunRPr: fieldInfo.fieldRunRPr });
119372
119624
  processedNodes.push(...processedField);
119373
119625
  i$1 = fieldInfo.endIndex + 1;
119374
119626
  continue;
@@ -119384,7 +119636,7 @@ var isRegExp = (value) => {
119384
119636
  }
119385
119637
  }
119386
119638
  if (node3.name === "w:r" && node3.elements?.some((el) => el.name === "w:pgNum")) {
119387
- const processedField = preProcessPageInstruction([], "", node3.elements.find((el) => el.name === "w:rPr") || null);
119639
+ const processedField = preProcessPageInstruction([], "", { fieldRunRPr: node3.elements.find((el) => el.name === "w:rPr") || null });
119388
119640
  processedNodes.push(...processedField);
119389
119641
  i$1++;
119390
119642
  continue;
@@ -125170,16 +125422,26 @@ var isRegExp = (value) => {
125170
125422
  }]
125171
125423
  }
125172
125424
  ];
125173
- }, config$9, translator$26, XML_NODE_NAME$7 = "sd:autoPageNumber", SD_NODE_NAME$7 = "page-number", encode$11 = (params3) => {
125425
+ }, config$9, translator$26, PAGE_VALUE_FORMAT_SWITCHES, XML_NODE_NAME$7 = "sd:autoPageNumber", SD_NODE_NAME$7 = "page-number", encode$11 = (params3) => {
125174
125426
  const { nodes = [] } = params3 || {};
125175
- const rPr = nodes[0].elements?.find((el) => el.name === "w:rPr");
125176
- return {
125427
+ const node3 = nodes[0];
125428
+ const rPr = node3.elements?.find((el) => el.name === "w:rPr");
125429
+ const processedNode = {
125177
125430
  type: "page-number",
125178
- attrs: { marksAsAttrs: parseMarks(rPr || { elements: [] }) }
125431
+ attrs: {
125432
+ marksAsAttrs: parseMarks(rPr || { elements: [] }),
125433
+ ...getPageNumberFieldAttrs$1(node3)
125434
+ }
125179
125435
  };
125436
+ if (typeof node3.attributes?.instruction === "string")
125437
+ processedNode.attrs.instruction = node3.attributes.instruction;
125438
+ if (typeof node3.attributes?.pageNumberFormat === "string")
125439
+ processedNode.attrs.pageNumberFormat = node3.attributes.pageNumberFormat;
125440
+ return processedNode;
125180
125441
  }, decode$11 = (params3) => {
125181
125442
  const { node: node3 } = params3;
125182
125443
  const outputMarks = processOutputMarks(node3.attrs?.marksAsAttrs || []);
125444
+ const instruction = getPageInstructionText(node3.attrs);
125183
125445
  return [
125184
125446
  {
125185
125447
  name: "w:r",
@@ -125201,7 +125463,7 @@ var isRegExp = (value) => {
125201
125463
  attributes: { "xml:space": "preserve" },
125202
125464
  elements: [{
125203
125465
  type: "text",
125204
- text: " PAGE"
125466
+ text: ` ${instruction}`
125205
125467
  }]
125206
125468
  }]
125207
125469
  },
@@ -125234,17 +125496,20 @@ var isRegExp = (value) => {
125234
125496
  type: "total-page-number",
125235
125497
  attrs: {
125236
125498
  marksAsAttrs: parseMarks(rPr || { elements: [] }),
125237
- importedCachedText: node3.attributes?.importedCachedText || null
125499
+ importedCachedText: node3.attributes?.importedCachedText || null,
125500
+ ...getPageNumberFieldAttrs(node3)
125238
125501
  }
125239
125502
  };
125240
125503
  }, decode$10 = (params3) => {
125241
125504
  const { node: node3 } = params3;
125242
125505
  const outputMarks = processOutputMarks(node3.attrs?.marksAsAttrs || []);
125506
+ const cachedText = resolveCachedPageCount(params3, node3);
125507
+ const dirty = !params3.statFieldCacheMap?.has?.("NUMPAGES");
125243
125508
  return buildComplexFieldRuns({
125244
- instruction: "NUMPAGES",
125245
- cachedText: resolveCachedPageCount(params3, node3),
125509
+ instruction: node3.attrs?.instruction || "NUMPAGES",
125510
+ cachedText,
125246
125511
  outputMarks,
125247
- dirty: !params3.statFieldCacheMap?.has?.("NUMPAGES")
125512
+ dirty
125248
125513
  });
125249
125514
  }, config$7, translator$28, XML_NODE_NAME$5 = "sd:documentStatField", SD_NODE_NAME$5 = "documentStatField", encode$9 = (params3) => {
125250
125515
  const { nodes = [] } = params3 || {};
@@ -126599,7 +126864,23 @@ var isRegExp = (value) => {
126599
126864
  } catch {
126600
126865
  return /* @__PURE__ */ new Map;
126601
126866
  }
126602
- }, readTrackedChangeSourceIdMap = (docx) => parseTrackedChangeSourceIdMap(readCustomProperty(docx, TRACKED_CHANGE_SOURCE_ID_MAP_PROPERTY)), detectCommentThreadingProfile = (docx) => {
126867
+ }, readTrackedChangeSourceIdMap = (docx) => parseTrackedChangeSourceIdMap(readCustomProperty(docx, TRACKED_CHANGE_SOURCE_ID_MAP_PROPERTY)), normalizeDocumentBackgroundColor = (value) => {
126868
+ if (typeof value !== "string")
126869
+ return null;
126870
+ const trimmed = value.trim();
126871
+ if (!/^[0-9a-fA-F]{6}$/.test(trimmed))
126872
+ return null;
126873
+ return `#${trimmed.toUpperCase()}`;
126874
+ }, getDocumentBackground = (documentNode) => {
126875
+ const background = documentNode?.elements?.find((el) => el?.name === "w:background");
126876
+ const color2 = normalizeDocumentBackgroundColor(background?.attributes?.["w:color"] ?? background?.attributes?.color);
126877
+ if (!background || !color2)
126878
+ return null;
126879
+ return {
126880
+ color: color2,
126881
+ originalXml: carbonCopy(background)
126882
+ };
126883
+ }, detectCommentThreadingProfile = (docx) => {
126603
126884
  const hasCommentsExtended = !!docx["word/commentsExtended.xml"];
126604
126885
  const hasCommentsExtensible = !!docx["word/commentsExtensible.xml"];
126605
126886
  const hasCommentsIds = !!docx["word/commentsIds.xml"];
@@ -126616,6 +126897,7 @@ var isRegExp = (value) => {
126616
126897
  const json = carbonCopy(getInitialJSON(docx));
126617
126898
  if (!json)
126618
126899
  return null;
126900
+ const documentBackground = getDocumentBackground(json.elements?.[0]);
126619
126901
  if (converter) {
126620
126902
  importFootnotePropertiesFromSettings(docx, converter);
126621
126903
  importViewSettingFromSettings(docx, converter);
@@ -126686,17 +126968,22 @@ var isRegExp = (value) => {
126686
126968
  parsedContent = normalizeTableBookmarksInContent(parsedContent, editor);
126687
126969
  collapseWhitespaceNextToInlinePassthrough(parsedContent);
126688
126970
  parsedContent = normalizeDuplicateBlockIdentitiesInContent(parsedContent);
126971
+ const result = {
126972
+ type: "doc",
126973
+ content: parsedContent,
126974
+ attrs: {
126975
+ attributes: json.elements[0].attributes,
126976
+ ...bodySectPr ? { bodySectPr } : {},
126977
+ ...documentBackground ? { documentBackground } : {}
126978
+ }
126979
+ };
126980
+ const pageStyles = getDocumentStyles(node3, docx, converter, editor, numbering, translatedNumbering, translatedLinkedStyles);
126981
+ if (documentBackground)
126982
+ pageStyles.documentBackground = { color: documentBackground.color };
126689
126983
  return {
126690
- pmDoc: {
126691
- type: "doc",
126692
- content: parsedContent,
126693
- attrs: {
126694
- attributes: json.elements[0].attributes,
126695
- ...bodySectPr ? { bodySectPr } : {}
126696
- }
126697
- },
126984
+ pmDoc: result,
126698
126985
  savedTagsToRestore: node3,
126699
- pageStyles: getDocumentStyles(node3, docx, converter, editor, numbering, translatedNumbering, translatedLinkedStyles),
126986
+ pageStyles,
126700
126987
  comments,
126701
126988
  footnotes,
126702
126989
  endnotes,
@@ -130806,7 +131093,7 @@ var isRegExp = (value) => {
130806
131093
  state.kern = kernNode.attributes["w:val"];
130807
131094
  }
130808
131095
  }, SuperConverter;
130809
- var init_SuperConverter_CcHCWpfX_es = __esm(() => {
131096
+ var init_SuperConverter_EumzHoTv_es = __esm(() => {
130810
131097
  init_rolldown_runtime_Bg48TavK_es();
130811
131098
  init_jszip_C49i9kUs_es();
130812
131099
  init_xml_js_CqGKpaft_es();
@@ -159390,6 +159677,16 @@ var init_SuperConverter_CcHCWpfX_es = __esm(() => {
159390
159677
  })(UTIF, pako$1);
159391
159678
  })();
159392
159679
  }))(), 1);
159680
+ GENERAL_FORMATS = new Map([
159681
+ ["Arabic", "decimal"],
159682
+ ["roman", "lowerRoman"],
159683
+ ["Roman", "upperRoman"],
159684
+ ["ROMAN", "upperRoman"],
159685
+ ["alphabetic", "lowerLetter"],
159686
+ ["ALPHABETIC", "upperLetter"],
159687
+ ["ArabicDash", "numberInDash"]
159688
+ ]);
159689
+ CASE_INSENSITIVE_GENERAL_FORMATS = new Map([["arabic", "decimal"], ["arabicdash", "numberInDash"]]);
159393
159690
  TRACK_CHANGE_ELEMENT_NAMES = new Set([
159394
159691
  "w:del",
159395
159692
  "w:ins",
@@ -167092,6 +167389,15 @@ var init_SuperConverter_CcHCWpfX_es = __esm(() => {
167092
167389
  decode: decode$12
167093
167390
  };
167094
167391
  translator$26 = NodeTranslator.from(config$9);
167392
+ PAGE_VALUE_FORMAT_SWITCHES = {
167393
+ Arabic: "decimal",
167394
+ Roman: "upperRoman",
167395
+ ROMAN: "upperRoman",
167396
+ roman: "lowerRoman",
167397
+ ALPHABETIC: "upperLetter",
167398
+ alphabetic: "lowerLetter",
167399
+ ArabicDash: "numberInDash"
167400
+ };
167095
167401
  config$8 = {
167096
167402
  xmlName: XML_NODE_NAME$7,
167097
167403
  sdNodeOrKeyName: SD_NODE_NAME$7,
@@ -169580,7 +169886,7 @@ var init_SuperConverter_CcHCWpfX_es = __esm(() => {
169580
169886
  };
169581
169887
  });
169582
169888
 
169583
- // ../../packages/superdoc/dist/chunks/create-headless-toolbar-DKwoydAR.es.js
169889
+ // ../../packages/superdoc/dist/chunks/create-headless-toolbar-CRyPCXZF.es.js
169584
169890
  function parseSizeUnit(val = "0") {
169585
169891
  const length3 = val.toString() || "0";
169586
169892
  const value = Number.parseFloat(length3);
@@ -179911,8 +180217,8 @@ var CSS_DIMENSION_REGEX, DOM_SIZE_UNITS, normalizeActorId = (value) => {
179911
180217
  }
179912
180218
  };
179913
180219
  };
179914
- var init_create_headless_toolbar_DKwoydAR_es = __esm(() => {
179915
- init_SuperConverter_CcHCWpfX_es();
180220
+ var init_create_headless_toolbar_CRyPCXZF_es = __esm(() => {
180221
+ init_SuperConverter_EumzHoTv_es();
179916
180222
  init_uuid_qzgm05fK_es();
179917
180223
  init_constants_D_X7xF4s_es();
179918
180224
  init_dist_B8HfvhaK_es();
@@ -229075,7 +229381,7 @@ var init_remark_gfm_eZN6yzWQ_es = __esm(() => {
229075
229381
  init_remark_gfm_BhnWr3yf_es();
229076
229382
  });
229077
229383
 
229078
- // ../../packages/superdoc/dist/chunks/src-BAgFSihz.es.js
229384
+ // ../../packages/superdoc/dist/chunks/src-CibMiO0y.es.js
229079
229385
  function deleteProps(obj, propOrProps) {
229080
229386
  const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps;
229081
229387
  const removeNested = (target, pathParts, index2 = 0) => {
@@ -260004,7 +260310,7 @@ function headerFootersResolveAdapter(editor, input2) {
260004
260310
  section: projection.address
260005
260311
  };
260006
260312
  }
260007
- const resolved = resolveEffectiveRef(editor, sections, projection.range.sectionIndex, headerFooterKind, variant);
260313
+ const resolved = resolveEffectiveRef(sections, projection.range.sectionIndex, headerFooterKind, variant);
260008
260314
  if (resolved)
260009
260315
  return {
260010
260316
  status: "inherited",
@@ -268737,6 +269043,55 @@ function convertOmmlToMathml(ommlJson, doc$12) {
268737
269043
  function isMinimalWordLayout$1(value) {
268738
269044
  return isMinimalWordLayout(value);
268739
269045
  }
269046
+ function pageContextSignature(context) {
269047
+ return [
269048
+ context.pageNumber,
269049
+ context.totalPages,
269050
+ context.pageNumberText ?? "",
269051
+ context.displayPageNumber ?? ""
269052
+ ].join("|");
269053
+ }
269054
+ function hasPageContextTokenInShapeText(textContent$1) {
269055
+ return Array.isArray(textContent$1?.parts) && textContent$1.parts.some((part) => part.fieldType === "PAGE" || part.fieldType === "NUMPAGES");
269056
+ }
269057
+ function hasPageContextTokenInShapeGroup(shapes) {
269058
+ return Array.isArray(shapes) && shapes.some((shape) => {
269059
+ if (shape.shapeType !== "vectorShape")
269060
+ return false;
269061
+ return hasPageContextTokenInShapeText(shape.attrs.textContent);
269062
+ });
269063
+ }
269064
+ function hasPageContextTokenInBlock(block) {
269065
+ if (!block)
269066
+ return false;
269067
+ if (block.kind === "paragraph") {
269068
+ for (const run2 of block.runs)
269069
+ if ("token" in run2 && (run2.token === "pageNumber" || run2.token === "totalPageCount"))
269070
+ return true;
269071
+ } else if (block.kind === "list") {
269072
+ const list5 = block;
269073
+ for (const item of list5.items ?? [])
269074
+ if (hasPageContextTokenInBlock(item.paragraph))
269075
+ return true;
269076
+ } else if (block.kind === "table") {
269077
+ const table2 = block;
269078
+ for (const row2 of table2.rows ?? [])
269079
+ for (const cell2 of row2.cells ?? [])
269080
+ if ((cell2.blocks ? cell2.blocks : cell2.paragraph ? [cell2.paragraph] : []).some(hasPageContextTokenInBlock))
269081
+ return true;
269082
+ } else if (block.kind === "drawing") {
269083
+ const drawing = block;
269084
+ if (drawing.drawingKind === "vectorShape")
269085
+ return hasPageContextTokenInShapeText(drawing.textContent);
269086
+ if (drawing.drawingKind === "shapeGroup")
269087
+ return hasPageContextTokenInShapeGroup(drawing.shapes);
269088
+ }
269089
+ return false;
269090
+ }
269091
+ function needsRebuildForPageContext(currentContext, nextContext, resolvedItem) {
269092
+ const block = resolvedItem?.kind === "fragment" && "block" in resolvedItem ? resolvedItem.block : undefined;
269093
+ return pageContextSignature(currentContext) !== pageContextSignature(nextContext) && hasPageContextTokenInBlock(block);
269094
+ }
268740
269095
  function roundSnapshotMetric(value) {
268741
269096
  if (!Number.isFinite(value))
268742
269097
  return null;
@@ -269533,6 +269888,7 @@ function resolveLayout(input2) {
269533
269888
  footnoteReserved: page.footnoteReserved,
269534
269889
  displayNumber: page.displayNumber,
269535
269890
  numberText: page.numberText,
269891
+ effectivePageNumber: page.effectivePageNumber,
269536
269892
  vAlign: page.vAlign,
269537
269893
  baseMargins: page.baseMargins,
269538
269894
  sectionIndex: page.sectionIndex,
@@ -269543,7 +269899,8 @@ function resolveLayout(input2) {
269543
269899
  version: 1,
269544
269900
  flowMode,
269545
269901
  pageGap: layout.pageGap ?? 0,
269546
- pages
269902
+ pages,
269903
+ ...layout.documentBackground ? { documentBackground: layout.documentBackground } : {}
269547
269904
  };
269548
269905
  if (blocks2.length > 0)
269549
269906
  resolved.blockVersions = Object.fromEntries(blocks2.map((block) => [block.id, computeBlockVersion(block.id, blockMap, blockVersionCache)]));
@@ -271952,85 +272309,6 @@ function createPaginator(opts) {
271952
272309
  pruneTrailingEmptyPages
271953
272310
  };
271954
272311
  }
271955
- function toUpperRoman2(num) {
271956
- if (num < 1 || num > 3999)
271957
- return String(num);
271958
- const values = [
271959
- 1000,
271960
- 900,
271961
- 500,
271962
- 400,
271963
- 100,
271964
- 90,
271965
- 50,
271966
- 40,
271967
- 10,
271968
- 9,
271969
- 5,
271970
- 4,
271971
- 1
271972
- ];
271973
- const numerals = [
271974
- "M",
271975
- "CM",
271976
- "D",
271977
- "CD",
271978
- "C",
271979
- "XC",
271980
- "L",
271981
- "XL",
271982
- "X",
271983
- "IX",
271984
- "V",
271985
- "IV",
271986
- "I"
271987
- ];
271988
- let result = "";
271989
- let remaining = num;
271990
- for (let i4 = 0;i4 < values.length; i4++)
271991
- while (remaining >= values[i4]) {
271992
- result += numerals[i4];
271993
- remaining -= values[i4];
271994
- }
271995
- return result;
271996
- }
271997
- function toLowerRoman(num) {
271998
- return toUpperRoman2(num).toLowerCase();
271999
- }
272000
- function toUpperLetter2(num) {
272001
- if (num < 1)
272002
- return "A";
272003
- let result = "";
272004
- let n = num;
272005
- while (n > 0) {
272006
- const remainder = (n - 1) % 26;
272007
- result = String.fromCharCode(65 + remainder) + result;
272008
- n = Math.floor((n - 1) / 26);
272009
- }
272010
- return result;
272011
- }
272012
- function toLowerLetter(num) {
272013
- return toUpperLetter2(num).toLowerCase();
272014
- }
272015
- function formatPageNumber(pageNumber, format) {
272016
- const num = Math.max(1, pageNumber);
272017
- switch (format) {
272018
- case "decimal":
272019
- return String(num);
272020
- case "upperRoman":
272021
- return toUpperRoman2(num);
272022
- case "lowerRoman":
272023
- return toLowerRoman(num);
272024
- case "upperLetter":
272025
- return toUpperLetter2(num);
272026
- case "lowerLetter":
272027
- return toLowerLetter(num);
272028
- case "numberInDash":
272029
- return `-${num}-`;
272030
- default:
272031
- return String(num);
272032
- }
272033
- }
272034
272312
  function computeDisplayPageNumber(pages, sections) {
272035
272313
  const result = [];
272036
272314
  if (pages.length === 0)
@@ -272495,7 +272773,6 @@ function resolvePageNumberTokens(layout, blocks2, measures, numberingCtx) {
272495
272773
  console.warn(`[resolvePageTokens] No display page info for page ${page.number} - skipping`);
272496
272774
  continue;
272497
272775
  }
272498
- const displayPageText = displayPageInfo.displayText;
272499
272776
  for (const fragment2 of page.fragments)
272500
272777
  if (fragment2.kind === "para") {
272501
272778
  const blockId = fragment2.blockId;
@@ -272510,7 +272787,7 @@ function resolvePageNumberTokens(layout, blocks2, measures, numberingCtx) {
272510
272787
  processedBlocks.add(blockId);
272511
272788
  continue;
272512
272789
  }
272513
- const clonedBlock = cloneBlockWithResolvedTokens(block, displayPageText, totalPagesStr);
272790
+ const clonedBlock = cloneBlockWithResolvedTokens(block, displayPageInfo, totalPagesStr, numberingCtx.totalPages);
272514
272791
  updatedBlocks.set(blockId, clonedBlock);
272515
272792
  affectedBlockIds.add(blockId);
272516
272793
  processedBlocks.add(blockId);
@@ -272528,20 +272805,20 @@ function hasPageTokens$1(block) {
272528
272805
  return true;
272529
272806
  return false;
272530
272807
  }
272531
- function cloneBlockWithResolvedTokens(block, displayPageText, totalPagesStr) {
272808
+ function cloneBlockWithResolvedTokens(block, displayPageInfo, totalPagesStr, totalPages) {
272532
272809
  const clonedRuns = block.runs.map((run2) => {
272533
272810
  if ("token" in run2 && run2.token) {
272534
272811
  if (run2.token === "pageNumber") {
272535
- const { token: _token, ...runWithoutToken } = run2;
272812
+ const { token: _token, pageNumberFieldFormat, ...runWithoutToken } = run2;
272536
272813
  return {
272537
272814
  ...runWithoutToken,
272538
- text: displayPageText
272815
+ text: pageNumberFieldFormat ? formatPageNumberFieldValue$1(displayPageInfo.displayNumber, pageNumberFieldFormat) : displayPageInfo.displayText
272539
272816
  };
272540
272817
  } else if (run2.token === "totalPageCount") {
272541
272818
  const { token: _token, ...runWithoutToken } = run2;
272542
272819
  return {
272543
272820
  ...runWithoutToken,
272544
- text: totalPagesStr
272821
+ text: run2.pageNumberFieldFormat ? formatPageNumberFieldValue$1(totalPages, run2.pageNumberFieldFormat) : totalPagesStr
272545
272822
  };
272546
272823
  }
272547
272824
  }
@@ -272731,13 +273008,6 @@ function layoutDocument(blocks2, measures, options = {}) {
272731
273008
  const headerContentHeightsBySectionRef = options.headerContentHeightsBySectionRef;
272732
273009
  const footerContentHeightsByRId = options.footerContentHeightsByRId;
272733
273010
  const footerContentHeightsBySectionRef = options.footerContentHeightsBySectionRef;
272734
- const getVariantTypeForPage = (args$1) => {
272735
- if (args$1.sectionPageNumber === 1 && args$1.titlePgEnabled)
272736
- return "first";
272737
- if (args$1.alternateHeaders)
272738
- return args$1.parityPageNumber % 2 === 0 ? "even" : "odd";
272739
- return "default";
272740
- };
272741
273011
  const getHeaderHeightForPage = (variantType, headerRef, sectionIndex) => {
272742
273012
  if (headerRef && sectionIndex != null) {
272743
273013
  const sectionKey = buildSectionAwareReferenceKey(headerRef, sectionIndex);
@@ -272804,9 +273074,7 @@ function layoutDocument(blocks2, measures, options = {}) {
272804
273074
  const maxFooterContentHeight = footerContentHeights ? Math.max(0, validateContentHeight(footerContentHeights.default), validateContentHeight(footerContentHeights.first), validateContentHeight(footerContentHeights.even), validateContentHeight(footerContentHeights.odd)) : 0;
272805
273075
  const headerDistance = margins.header ?? margins.top;
272806
273076
  const footerDistance = margins.footer ?? margins.bottom;
272807
- const defaultHeaderHeight = getHeaderHeightForPage("default", undefined, 0);
272808
- const defaultFooterHeight = getFooterHeightForPage("default", undefined, 0);
272809
- const effectiveMargins = clampHeaderFooterInflatedMargins(calculateEffectiveTopMargin(defaultHeaderHeight, headerDistance, margins.top), calculateEffectiveBottomMargin(defaultFooterHeight, footerDistance, margins.bottom), margins.top, margins.bottom, pageSize.h);
273077
+ const effectiveMargins = clampHeaderFooterInflatedMargins(calculateEffectiveTopMargin(0, headerDistance, margins.top), calculateEffectiveBottomMargin(0, footerDistance, margins.bottom), margins.top, margins.bottom, pageSize.h);
272810
273078
  let activeTopMargin = effectiveMargins.top;
272811
273079
  let activeBottomMargin = effectiveMargins.bottom;
272812
273080
  let activeLeftMargin = margins.left;
@@ -272911,7 +273179,7 @@ function layoutDocument(blocks2, measures, options = {}) {
272911
273179
  const firstMetadataIndex = typeof firstSectionIndexRaw === "number" ? firstSectionIndexRaw : Number(firstSectionIndexRaw ?? NaN);
272912
273180
  if (Number.isFinite(firstMetadataIndex))
272913
273181
  activeSectionIndex = firstMetadataIndex;
272914
- const firstSectionMetadata = Number.isFinite(firstMetadataIndex) ? sectionMetadataList[firstMetadataIndex] : undefined;
273182
+ const firstSectionMetadata = Number.isFinite(firstMetadataIndex) ? getSectionMetadata(firstMetadataIndex) : undefined;
272915
273183
  if (firstSectionMetadata?.numbering) {
272916
273184
  if (firstSectionMetadata.numbering.format)
272917
273185
  activeNumberFormat = firstSectionMetadata.numbering.format;
@@ -272969,7 +273237,7 @@ function layoutDocument(blocks2, measures, options = {}) {
272969
273237
  const metadataIndex = typeof sectionIndexRaw === "number" ? sectionIndexRaw : Number(sectionIndexRaw ?? NaN);
272970
273238
  if (Number.isFinite(metadataIndex))
272971
273239
  pendingSectionIndex = metadataIndex;
272972
- const sectionMetadata = Number.isFinite(metadataIndex) ? sectionMetadataList[metadataIndex] : undefined;
273240
+ const sectionMetadata = Number.isFinite(metadataIndex) ? getSectionMetadata(metadataIndex) : undefined;
272973
273241
  if (sectionMetadata?.numbering)
272974
273242
  pendingNumbering = { ...sectionMetadata.numbering };
272975
273243
  else if (block.numbering)
@@ -273212,6 +273480,29 @@ function layoutDocument(blocks2, measures, options = {}) {
273212
273480
  };
273213
273481
  };
273214
273482
  const sectionMetadataList = options.sectionMetadata ?? [];
273483
+ const getSectionMetadata = (sectionIndex) => sectionMetadataList.find((section, fallbackIndex) => (section.sectionIndex ?? fallbackIndex) === sectionIndex);
273484
+ const runtimeSectionRefsByIndex = /* @__PURE__ */ new Map;
273485
+ const buildHeaderFooterResolutionSections = () => {
273486
+ const sectionIndexes = /* @__PURE__ */ new Set;
273487
+ sectionMetadataList.forEach((section, fallbackIndex) => sectionIndexes.add(section.sectionIndex ?? fallbackIndex));
273488
+ runtimeSectionRefsByIndex.forEach((_refs, sectionIndex) => sectionIndexes.add(sectionIndex));
273489
+ if (sectionIndexes.size === 0)
273490
+ sectionIndexes.add(0);
273491
+ return Array.from(sectionIndexes).sort((a2, b$1) => a2 - b$1).map((sectionIndex) => {
273492
+ const metadata = getSectionMetadata(sectionIndex);
273493
+ const runtimeRefs = runtimeSectionRefsByIndex.get(sectionIndex);
273494
+ return {
273495
+ sectionIndex,
273496
+ titlePg: metadata?.titlePg === true,
273497
+ headerRefs: runtimeRefs?.headerRefs ?? metadata?.headerRefs,
273498
+ footerRefs: runtimeRefs?.footerRefs ?? metadata?.footerRefs
273499
+ };
273500
+ });
273501
+ };
273502
+ const hasAnyHeaderFooterRefs = (sections, kind) => {
273503
+ const refKey = kind === "header" ? "headerRefs" : "footerRefs";
273504
+ return sections.some((section) => Object.values(section[refKey] ?? {}).some(Boolean));
273505
+ };
273215
273506
  const initialSectionMetadata = sectionMetadataList[0];
273216
273507
  if (initialSectionMetadata?.numbering?.format)
273217
273508
  activeNumberFormat = initialSectionMetadata.numbering.format;
@@ -273221,11 +273512,13 @@ function layoutDocument(blocks2, measures, options = {}) {
273221
273512
  }
273222
273513
  let activeSectionRefs = null;
273223
273514
  let pendingSectionRefs = null;
273224
- if (initialSectionMetadata?.headerRefs || initialSectionMetadata?.footerRefs)
273515
+ if (initialSectionMetadata?.headerRefs || initialSectionMetadata?.footerRefs) {
273225
273516
  activeSectionRefs = {
273226
273517
  ...initialSectionMetadata.headerRefs && { headerRefs: initialSectionMetadata.headerRefs },
273227
273518
  ...initialSectionMetadata.footerRefs && { footerRefs: initialSectionMetadata.footerRefs }
273228
273519
  };
273520
+ runtimeSectionRefsByIndex.set(initialSectionMetadata.sectionIndex ?? 0, activeSectionRefs);
273521
+ }
273229
273522
  if (initialSectionMetadata?.vAlign)
273230
273523
  activeVAlign = initialSectionMetadata.vAlign;
273231
273524
  let activeSectionIndex = initialSectionMetadata?.sectionIndex ?? 0;
@@ -273317,6 +273610,8 @@ function layoutDocument(blocks2, measures, options = {}) {
273317
273610
  activeSectionIndex = pendingSectionIndex;
273318
273611
  pendingSectionIndex = null;
273319
273612
  }
273613
+ if (activeSectionRefs)
273614
+ runtimeSectionRefsByIndex.set(activeSectionIndex, activeSectionRefs);
273320
273615
  if (pendingVAlign !== undefined) {
273321
273616
  activeVAlign = pendingVAlign;
273322
273617
  pendingVAlign = undefined;
@@ -273336,53 +273631,42 @@ function layoutDocument(blocks2, measures, options = {}) {
273336
273631
  if (isEnteringNewSection || !sectionFirstPageNumbers.has(activeSectionIndex))
273337
273632
  sectionFirstPageNumbers.set(activeSectionIndex, newPageNumber);
273338
273633
  const sectionPageNumber = newPageNumber - (sectionFirstPageNumbers.get(activeSectionIndex) ?? newPageNumber) + 1;
273339
- const titlePgEnabled = sectionMetadataList[activeSectionIndex]?.titlePg ?? false;
273634
+ const titlePgEnabled = getSectionMetadata(activeSectionIndex)?.titlePg ?? false;
273340
273635
  const alternateHeaders = options.alternateHeaders ?? false;
273341
- const variantType = getVariantTypeForPage({
273636
+ const variantType = selectHeaderFooterVariantForPage({
273342
273637
  sectionPageNumber,
273343
- parityPageNumber: activePageCounter,
273344
- titlePgEnabled,
273638
+ documentPageNumber: activePageCounter,
273639
+ titlePg: titlePgEnabled,
273345
273640
  alternateHeaders
273346
273641
  });
273347
- let headerRef = activeSectionRefs?.headerRefs?.[variantType];
273348
- let footerRef = activeSectionRefs?.footerRefs?.[variantType];
273349
- let effectiveVariantType = variantType;
273350
- if (!headerRef && variantType !== "default" && activeSectionIndex > 0) {
273351
- const prevSectionMetadata = sectionMetadataList[activeSectionIndex - 1];
273352
- if (prevSectionMetadata?.headerRefs?.[variantType]) {
273353
- headerRef = prevSectionMetadata.headerRefs[variantType];
273354
- layoutLog(`[Layout] Page ${newPageNumber}: Inheriting header '${variantType}' from section ${activeSectionIndex - 1}: ${headerRef}`);
273355
- }
273356
- }
273357
- if (!footerRef && variantType !== "default" && activeSectionIndex > 0) {
273358
- const prevSectionMetadata = sectionMetadataList[activeSectionIndex - 1];
273359
- if (prevSectionMetadata?.footerRefs?.[variantType]) {
273360
- footerRef = prevSectionMetadata.footerRefs[variantType];
273361
- layoutLog(`[Layout] Page ${newPageNumber}: Inheriting footer '${variantType}' from section ${activeSectionIndex - 1}: ${footerRef}`);
273362
- }
273363
- }
273364
- const defaultHeaderRef = activeSectionRefs?.headerRefs?.default;
273365
- const defaultFooterRef = activeSectionRefs?.footerRefs?.default;
273366
- const shouldUseDefaultHeaderRef = variantType !== "default" && defaultHeaderRef && (!alternateHeaders || variantType === "odd");
273367
- const shouldUseDefaultFooterRef = variantType !== "default" && defaultFooterRef && (!alternateHeaders || variantType === "odd");
273368
- if (!headerRef && shouldUseDefaultHeaderRef) {
273369
- headerRef = defaultHeaderRef;
273370
- effectiveVariantType = "default";
273371
- }
273372
- if (!footerRef && shouldUseDefaultFooterRef)
273373
- footerRef = defaultFooterRef;
273374
- const headerHeight = getHeaderHeightForPage(effectiveVariantType, headerRef, activeSectionIndex);
273375
- const footerHeight = getFooterHeightForPage(variantType !== "default" && !activeSectionRefs?.footerRefs?.[variantType] ? "default" : variantType, footerRef, activeSectionIndex);
273642
+ const resolutionSections = buildHeaderFooterResolutionSections();
273643
+ const headerResolved = variantType && resolveEffectiveHeaderFooterRef({
273644
+ sections: resolutionSections,
273645
+ sectionIndex: activeSectionIndex,
273646
+ kind: "header",
273647
+ variant: variantType
273648
+ });
273649
+ const footerResolved = variantType && resolveEffectiveHeaderFooterRef({
273650
+ sections: resolutionSections,
273651
+ sectionIndex: activeSectionIndex,
273652
+ kind: "footer",
273653
+ variant: variantType
273654
+ });
273655
+ const hasHeaderRefs = hasAnyHeaderFooterRefs(resolutionSections, "header");
273656
+ const hasFooterRefs = hasAnyHeaderFooterRefs(resolutionSections, "footer");
273657
+ const headerHeight = headerResolved ? getHeaderHeightForPage(headerResolved.matchedVariant, headerResolved.refId, activeSectionIndex) : variantType && !hasHeaderRefs ? getHeaderHeightForPage(variantType, undefined, activeSectionIndex) : 0;
273658
+ const footerHeight = footerResolved ? getFooterHeightForPage(footerResolved.matchedVariant, footerResolved.refId, activeSectionIndex) : variantType && !hasFooterRefs ? getFooterHeightForPage(variantType, undefined, activeSectionIndex) : 0;
273376
273659
  const adjustedMargins = clampHeaderFooterInflatedMargins(calculateEffectiveTopMargin(headerHeight, activeHeaderDistance, activeSectionBaseTopMargin), calculateEffectiveBottomMargin(footerHeight, activeFooterDistance, activeSectionBaseBottomMargin), activeSectionBaseTopMargin, activeSectionBaseBottomMargin, activePageSize.h);
273377
273660
  activeTopMargin = adjustedMargins.top;
273378
273661
  activeBottomMargin = adjustedMargins.bottom;
273379
- layoutLog(`[Layout] Page ${newPageNumber}: Using variant '${variantType}' - headerHeight: ${headerHeight}, footerHeight: ${footerHeight}`);
273662
+ layoutLog(`[Layout] Page ${newPageNumber}: Using variant '${variantType ?? "none"}' - headerHeight: ${headerHeight}, footerHeight: ${footerHeight}`);
273380
273663
  layoutLog(`[Layout] Page ${newPageNumber}: Adjusted margins - top: ${activeTopMargin}, bottom: ${activeBottomMargin} (base: ${activeSectionBaseTopMargin}, ${activeSectionBaseBottomMargin})`);
273381
273664
  return;
273382
273665
  }
273383
273666
  if (state?.page) {
273384
273667
  state.page.displayNumber = activePageCounter;
273385
273668
  state.page.numberText = formatPageNumber(activePageCounter, activeNumberFormat);
273669
+ state.page.effectivePageNumber = activePageCounter;
273386
273670
  state.page.sectionIndex = activeSectionIndex;
273387
273671
  layoutLog(`[Layout] Page ${state.page.number}: Stamped sectionIndex:`, activeSectionIndex);
273388
273672
  if (activeSectionRefs) {
@@ -273691,7 +273975,7 @@ function layoutDocument(blocks2, measures, options = {}) {
273691
273975
  activeSectionIndex = metadataIndex;
273692
273976
  else
273693
273977
  pendingSectionIndex = metadataIndex;
273694
- const sectionMetadata = Number.isFinite(metadataIndex) ? sectionMetadataList[metadataIndex] : undefined;
273978
+ const sectionMetadata = Number.isFinite(metadataIndex) ? getSectionMetadata(metadataIndex) : undefined;
273695
273979
  if (sectionMetadata?.numbering)
273696
273980
  if (isFirstSection) {
273697
273981
  if (sectionMetadata.numbering.format)
@@ -274229,6 +274513,7 @@ function layoutDocument(blocks2, measures, options = {}) {
274229
274513
  return {
274230
274514
  pageSize,
274231
274515
  pages,
274516
+ ...options.documentBackground ? { documentBackground: options.documentBackground } : {},
274232
274517
  columns: activeColumns.count > 1 ? cloneColumnLayout(activeColumns) : undefined
274233
274518
  };
274234
274519
  }
@@ -274672,6 +274957,25 @@ function extractParagraphIndent(indent2) {
274672
274957
  hanging: typeof indent2?.hanging === "number" && Number.isFinite(indent2.hanging) ? indent2.hanging : 0
274673
274958
  };
274674
274959
  }
274960
+ function refreshResolutionSections(identifier) {
274961
+ if (identifier.sectionCount === 0 && identifier.sectionHeaderIds.size === 0 && identifier.sectionFooterIds.size === 0 && identifier.sectionTitlePg.size === 0) {
274962
+ identifier.sections = [];
274963
+ return;
274964
+ }
274965
+ const maxIndex = Math.max(identifier.sectionCount - 1, ...Array.from(identifier.sectionHeaderIds.keys()), ...Array.from(identifier.sectionFooterIds.keys()), ...Array.from(identifier.sectionTitlePg.keys()));
274966
+ const sections = [];
274967
+ for (let sectionIndex = 0;sectionIndex <= maxIndex; sectionIndex += 1)
274968
+ sections.push({
274969
+ sectionIndex,
274970
+ titlePg: identifier.sectionTitlePg.get(sectionIndex) ?? false,
274971
+ headerRefs: identifier.sectionHeaderIds.get(sectionIndex),
274972
+ footerRefs: identifier.sectionFooterIds.get(sectionIndex)
274973
+ });
274974
+ identifier.sections = sections;
274975
+ }
274976
+ function getSectionTitlePg(identifier, sectionIndex) {
274977
+ return identifier.sectionTitlePg.get(sectionIndex) ?? false;
274978
+ }
274675
274979
  function buildMultiSectionIdentifier(sectionMetadata, pageStyles$1, converterIds) {
274676
274980
  const identifier = defaultMultiSectionIdentifier();
274677
274981
  identifier.alternateHeaders = Boolean(pageStyles$1?.alternateHeaders ?? false);
@@ -274692,7 +274996,8 @@ function buildMultiSectionIdentifier(sectionMetadata, pageStyles$1, converterIds
274692
274996
  even: section.footerRefs.even ?? null,
274693
274997
  odd: section.footerRefs.odd ?? null
274694
274998
  });
274695
- identifier.sectionTitlePg.set(idx, section.titlePg === true);
274999
+ if (Object.prototype.hasOwnProperty.call(section, "titlePg"))
275000
+ identifier.sectionTitlePg.set(idx, section.titlePg === true);
274696
275001
  }
274697
275002
  const section0Headers = identifier.sectionHeaderIds.get(0);
274698
275003
  const section0Footers = identifier.sectionFooterIds.get(0);
@@ -274717,45 +275022,28 @@ function buildMultiSectionIdentifier(sectionMetadata, pageStyles$1, converterIds
274717
275022
  identifier.footerIds.even = identifier.footerIds.even ?? converterIds.footerIds.even ?? null;
274718
275023
  identifier.footerIds.odd = identifier.footerIds.odd ?? converterIds.footerIds.odd ?? null;
274719
275024
  }
275025
+ refreshResolutionSections(identifier);
274720
275026
  return identifier;
274721
275027
  }
274722
275028
  function getHeaderFooterTypeForSection(pageNumber, sectionIndex, identifier, options) {
274723
- if (pageNumber <= 0)
275029
+ if (!Number.isFinite(pageNumber))
274724
275030
  return null;
274725
275031
  const kind = options?.kind ?? "header";
274726
275032
  const sectionPageNumber = options?.sectionPageNumber ?? pageNumber;
274727
- const parityPageNumber = options?.parityPageNumber ?? pageNumber;
274728
- const ids = (kind === "header" ? identifier.sectionHeaderIds.get(sectionIndex) : identifier.sectionFooterIds.get(sectionIndex)) ?? (kind === "header" ? identifier.headerIds : identifier.footerIds);
274729
- const hasFirst = Boolean(ids.first);
274730
- const hasEven = Boolean(ids.even);
274731
- const hasOdd = Boolean(ids.odd);
274732
- const hasDefault = Boolean(ids.default);
274733
- const legacyIds = kind === "header" ? identifier.headerIds : identifier.footerIds;
274734
- let hasAny = hasFirst || hasEven || hasOdd || hasDefault;
274735
- if (!hasAny)
274736
- for (let index2 = sectionIndex - 1;index2 >= 0; index2 -= 1) {
274737
- const inheritedIds = kind === "header" ? identifier.sectionHeaderIds.get(index2) : identifier.sectionFooterIds.get(index2);
274738
- if (inheritedIds?.first || inheritedIds?.even || inheritedIds?.odd || inheritedIds?.default) {
274739
- hasAny = true;
274740
- break;
274741
- }
274742
- }
274743
- if (!hasAny)
274744
- hasAny = Boolean(legacyIds.first || legacyIds.even || legacyIds.odd || legacyIds.default);
274745
- const titlePgEnabled = (identifier.sectionTitlePg.has(sectionIndex) ? identifier.sectionTitlePg.get(sectionIndex) : identifier.titlePg) === true;
274746
- if (sectionPageNumber === 1 && titlePgEnabled) {
274747
- if (hasAny)
274748
- return "first";
275033
+ const variant = selectHeaderFooterVariantForPage({
275034
+ documentPageNumber: options?.parityPageNumber ?? pageNumber,
275035
+ sectionPageNumber,
275036
+ titlePg: getSectionTitlePg(identifier, sectionIndex),
275037
+ alternateHeaders: identifier.alternateHeaders
275038
+ });
275039
+ if (!variant)
274749
275040
  return null;
274750
- }
274751
- if (identifier.alternateHeaders) {
274752
- if (!hasAny)
274753
- return null;
274754
- return parityPageNumber % 2 === 0 ? "even" : "odd";
274755
- }
274756
- if (hasDefault)
274757
- return "default";
274758
- return null;
275041
+ return resolveEffectiveHeaderFooterRef({
275042
+ sections: identifier.sections,
275043
+ sectionIndex,
275044
+ kind,
275045
+ variant
275046
+ }) ? variant : null;
274759
275047
  }
274760
275048
  function isNoneBorder(value) {
274761
275049
  return typeof value === "object" && value !== null && "none" in value && value.none === true;
@@ -274780,7 +275068,7 @@ function forEachParagraphBlock(blocks2, visit2) {
274780
275068
  forEachParagraphBlock([cell2.paragraph], visit2);
274781
275069
  }
274782
275070
  }
274783
- function resolveHeaderFooterTokens(blocks2, pageNumber, totalPages, pageNumberText) {
275071
+ function resolveHeaderFooterTokens(blocks2, pageNumber, totalPages, pageNumberText, displayPageNumber) {
274784
275072
  if (!blocks2 || blocks2.length === 0)
274785
275073
  return;
274786
275074
  if (!Number.isFinite(pageNumber) || pageNumber < 1) {
@@ -274793,13 +275081,14 @@ function resolveHeaderFooterTokens(blocks2, pageNumber, totalPages, pageNumberTe
274793
275081
  }
274794
275082
  const pageNumberStr = pageNumberText ?? String(pageNumber);
274795
275083
  const totalPagesStr = String(totalPages);
275084
+ const displayNumber = displayPageNumber ?? pageNumber;
274796
275085
  forEachParagraphBlock(blocks2, (paraBlock) => {
274797
275086
  for (const run2 of paraBlock.runs)
274798
275087
  if ("token" in run2 && run2.token) {
274799
275088
  if (run2.token === "pageNumber")
274800
- run2.text = pageNumberStr;
275089
+ run2.text = run2.pageNumberFieldFormat ? formatPageNumberFieldValue$1(displayNumber, run2.pageNumberFieldFormat) : pageNumberStr;
274801
275090
  else if (run2.token === "totalPageCount")
274802
- run2.text = totalPagesStr;
275091
+ run2.text = run2.pageNumberFieldFormat ? formatPageNumberFieldValue$1(totalPages, run2.pageNumberFieldFormat) : totalPagesStr;
274803
275092
  }
274804
275093
  });
274805
275094
  }
@@ -274864,17 +275153,122 @@ function getBucketRepresentative(bucket) {
274864
275153
  return 5000;
274865
275154
  }
274866
275155
  }
275156
+ function getBucketForDigitCount(digitCount) {
275157
+ if (digitCount <= 1)
275158
+ return "d1";
275159
+ if (digitCount === 2)
275160
+ return "d2";
275161
+ if (digitCount === 3)
275162
+ return "d3";
275163
+ return "d4";
275164
+ }
275165
+ function getBucketForRenderedPageNumberText(text5) {
275166
+ const digitCount = (text5.match(/\d/g) ?? []).length;
275167
+ if (digitCount <= 0)
275168
+ return null;
275169
+ return getBucketForDigitCount(digitCount);
275170
+ }
275171
+ function forEachPageNumberRun(blocks2, visit2) {
275172
+ for (const block of blocks2)
275173
+ if (block.kind === "paragraph") {
275174
+ const paraBlock = block;
275175
+ for (const run2 of paraBlock.runs)
275176
+ if ("token" in run2 && run2.token === "pageNumber")
275177
+ visit2(run2);
275178
+ } else if (block.kind === "list") {
275179
+ const list5 = block;
275180
+ for (const item of list5.items ?? [])
275181
+ for (const run2 of item.paragraph.runs)
275182
+ if ("token" in run2 && run2.token === "pageNumber")
275183
+ visit2(run2);
275184
+ } else if (block.kind === "table") {
275185
+ const table2 = block;
275186
+ for (const row2 of table2.rows ?? [])
275187
+ for (const cell2 of row2.cells ?? [])
275188
+ forEachPageNumberRun(cell2.blocks ? cell2.blocks : cell2.paragraph ? [cell2.paragraph] : [], visit2);
275189
+ }
275190
+ }
275191
+ function buildCompatibleFieldFormatKey(fieldFormat) {
275192
+ return `${fieldFormat.format ?? "decimal"}:${fieldFormat.zeroPadding ?? ""}`;
275193
+ }
275194
+ function getPageNumberBucketingStrategy(blocks2) {
275195
+ let sawImplicitPageNumber = false;
275196
+ const explicitFieldFormats = /* @__PURE__ */ new Map;
275197
+ forEachPageNumberRun(blocks2, (run2) => {
275198
+ const fieldFormat = run2.pageNumberFieldFormat;
275199
+ if (!fieldFormat) {
275200
+ sawImplicitPageNumber = true;
275201
+ return;
275202
+ }
275203
+ if (!isDigitBucketCompatiblePageNumberFormat(fieldFormat.format)) {
275204
+ explicitFieldFormats.clear();
275205
+ sawImplicitPageNumber = true;
275206
+ return;
275207
+ }
275208
+ explicitFieldFormats.set(buildCompatibleFieldFormatKey(fieldFormat), fieldFormat);
275209
+ });
275210
+ if (explicitFieldFormats.size === 0)
275211
+ return sawImplicitPageNumber ? { kind: "displayText" } : null;
275212
+ if (sawImplicitPageNumber || explicitFieldFormats.size > 1)
275213
+ return null;
275214
+ return {
275215
+ kind: "fieldFormat",
275216
+ fieldFormat: explicitFieldFormats.values().next().value
275217
+ };
275218
+ }
275219
+ function canUseDigitBucketingForVariant(blocks2, docTotalPages, pageResolver) {
275220
+ const strategy = getPageNumberBucketingStrategy(blocks2);
275221
+ if (!strategy)
275222
+ return false;
275223
+ const renderedBucketForPage = (pageNumber) => {
275224
+ const pageInfo = pageResolver(pageNumber);
275225
+ const renderedText = strategy.kind === "fieldFormat" ? Number.isFinite(pageInfo.displayNumber) ? formatPageNumberFieldValue$1(pageInfo.displayNumber ?? pageNumber, strategy.fieldFormat) : null : pageInfo.displayText;
275226
+ return renderedText ? getBucketForRenderedPageNumberText(renderedText) : null;
275227
+ };
275228
+ const expectedRenderedBuckets = /* @__PURE__ */ new Map;
275229
+ for (let pageNumber = 1;pageNumber <= docTotalPages; pageNumber += 1) {
275230
+ const physicalBucket = getBucketForPageNumber(pageNumber);
275231
+ const renderedBucket = renderedBucketForPage(pageNumber);
275232
+ if (!renderedBucket)
275233
+ return false;
275234
+ const expectedBucket = expectedRenderedBuckets.get(physicalBucket);
275235
+ if (!expectedBucket) {
275236
+ expectedRenderedBuckets.set(physicalBucket, renderedBucket);
275237
+ continue;
275238
+ }
275239
+ if (expectedBucket !== renderedBucket)
275240
+ return false;
275241
+ }
275242
+ for (const [physicalBucket, expectedRenderedBucket] of expectedRenderedBuckets)
275243
+ if (renderedBucketForPage(getBucketRepresentative(physicalBucket)) !== expectedRenderedBucket)
275244
+ return false;
275245
+ return true;
275246
+ }
274867
275247
  function paragraphHasPageToken(para) {
274868
275248
  for (const run2 of para.runs)
274869
275249
  if ("token" in run2 && (run2.token === "pageNumber" || run2.token === "totalPageCount"))
274870
275250
  return true;
274871
275251
  return false;
274872
275252
  }
275253
+ function isDigitBucketCompatiblePageNumberFormat(format) {
275254
+ return !format || format === "decimal" || format === "numberInDash";
275255
+ }
275256
+ function paragraphRequiresPerPageLayout(para) {
275257
+ for (const run2 of para.runs)
275258
+ if ("token" in run2 && run2.token === "pageNumber" && run2.pageNumberFieldFormat && !isDigitBucketCompatiblePageNumberFormat(run2.pageNumberFieldFormat.format))
275259
+ return true;
275260
+ return false;
275261
+ }
274873
275262
  function hasPageTokens(blocks2) {
274874
275263
  for (const block of blocks2)
274875
275264
  if (block.kind === "paragraph") {
274876
275265
  if (paragraphHasPageToken(block))
274877
275266
  return true;
275267
+ } else if (block.kind === "list") {
275268
+ const list5 = block;
275269
+ for (const item of list5.items ?? [])
275270
+ if (paragraphHasPageToken(item.paragraph))
275271
+ return true;
274878
275272
  } else if (block.kind === "table") {
274879
275273
  const table2 = block;
274880
275274
  for (const row2 of table2.rows ?? [])
@@ -274884,6 +275278,25 @@ function hasPageTokens(blocks2) {
274884
275278
  }
274885
275279
  return false;
274886
275280
  }
275281
+ function hasPageNumberTokensRequiringPerPageLayout(blocks2) {
275282
+ for (const block of blocks2)
275283
+ if (block.kind === "paragraph") {
275284
+ if (paragraphRequiresPerPageLayout(block))
275285
+ return true;
275286
+ } else if (block.kind === "list") {
275287
+ const list5 = block;
275288
+ for (const item of list5.items ?? [])
275289
+ if (paragraphRequiresPerPageLayout(item.paragraph))
275290
+ return true;
275291
+ } else if (block.kind === "table") {
275292
+ const table2 = block;
275293
+ for (const row2 of table2.rows ?? [])
275294
+ for (const cell2 of row2.cells ?? [])
275295
+ if (hasPageNumberTokensRequiringPerPageLayout(cell2.blocks ? cell2.blocks : cell2.paragraph ? [cell2.paragraph] : []))
275296
+ return true;
275297
+ }
275298
+ return false;
275299
+ }
274887
275300
  async function layoutHeaderFooterWithCache(sections, constraints, measureBlock$1, cache$2 = sharedHeaderFooterCache, totalPages, pageResolver, kind) {
274888
275301
  const result = {};
274889
275302
  if (!pageResolver) {
@@ -274919,7 +275332,7 @@ async function layoutHeaderFooterWithCache(sections, constraints, measureBlock$1
274919
275332
  continue;
274920
275333
  }
274921
275334
  let pagesToLayout;
274922
- if (!useBucketing) {
275335
+ if (!(useBucketing && !hasPageNumberTokensRequiringPerPageLayout(blocks2) && canUseDigitBucketingForVariant(blocks2, docTotalPages, pageResolver))) {
274923
275336
  pagesToLayout = Array.from({ length: docTotalPages }, (_$1, i4) => i4 + 1);
274924
275337
  HeaderFooterCacheLogger.logBucketingDecision(docTotalPages, false);
274925
275338
  } else {
@@ -274932,8 +275345,8 @@ async function layoutHeaderFooterWithCache(sections, constraints, measureBlock$1
274932
275345
  const pages = [];
274933
275346
  for (const pageNum of pagesToLayout) {
274934
275347
  const clonedBlocks = cloneHeaderFooterBlocks(blocks2);
274935
- const { displayText, totalPages: totalPagesForPage } = pageResolver(pageNum);
274936
- resolveHeaderFooterTokens(clonedBlocks, pageNum, totalPagesForPage, displayText);
275348
+ const { displayText, displayNumber, totalPages: totalPagesForPage } = pageResolver(pageNum);
275349
+ resolveHeaderFooterTokens(clonedBlocks, pageNum, totalPagesForPage, displayText, displayNumber);
274937
275350
  const measures = await cache$2.measureBlocks(clonedBlocks, constraints, measureBlock$1);
274938
275351
  const pageLayout = layoutHeaderFooter(clonedBlocks, measures, constraints, kind);
274939
275352
  const measuresById = /* @__PURE__ */ new Map;
@@ -274952,9 +275365,11 @@ async function layoutHeaderFooterWithCache(sections, constraints, measureBlock$1
274952
275365
  }) ?? [];
274953
275366
  pages.push({
274954
275367
  number: pageNum,
275368
+ displayNumber,
274955
275369
  blocks: clonedBlocks,
274956
275370
  measures,
274957
- fragments: fragmentsWithLines
275371
+ fragments: fragmentsWithLines,
275372
+ numberText: displayText
274958
275373
  });
274959
275374
  }
274960
275375
  const firstPageLayout = pages[0] ? layoutHeaderFooter(pages[0].blocks, pages[0].measures, constraints, kind) : {
@@ -274968,7 +275383,9 @@ async function layoutHeaderFooterWithCache(sections, constraints, measureBlock$1
274968
275383
  renderHeight: firstPageLayout.renderHeight,
274969
275384
  pages: pages.map((p$12) => ({
274970
275385
  number: p$12.number,
275386
+ displayNumber: p$12.displayNumber,
274971
275387
  fragments: p$12.fragments,
275388
+ numberText: p$12.numberText,
274972
275389
  blocks: p$12.blocks,
274973
275390
  measures: p$12.measures
274974
275391
  }))
@@ -275588,6 +276005,8 @@ function computeHeaderFooterContentHash(blocks2) {
275588
276005
  parts.push("i");
275589
276006
  if ("token" in run2 && run2.token)
275590
276007
  parts.push(`token:${run2.token}`);
276008
+ if ("pageNumberFormat" in run2 && run2.pageNumberFormat)
276009
+ parts.push(`pnf:${run2.pageNumberFormat}`);
275591
276010
  }
275592
276011
  }
275593
276012
  return parts.join("|");
@@ -276960,8 +277379,10 @@ async function incrementalLayout(previousBlocks, _previousLayout, nextBlocks, op
276960
277379
  const numberingCtx = buildNumberingContext(layout, sections);
276961
277380
  const pageResolver = FeatureFlags.HEADER_FOOTER_PAGE_TOKENS ? (pageNumber) => {
276962
277381
  const pageIndex = pageNumber - 1;
277382
+ const displayInfo = numberingCtx.displayPages[pageIndex];
276963
277383
  return {
276964
- displayText: numberingCtx.displayPages[pageIndex]?.displayText ?? String(pageNumber),
277384
+ displayText: displayInfo?.displayText ?? String(pageNumber),
277385
+ displayNumber: displayInfo?.displayNumber ?? pageNumber,
276965
277386
  totalPages: numberingCtx.totalPages
276966
277387
  };
276967
277388
  } : undefined;
@@ -285267,8 +285688,10 @@ async function layoutPerRIdHeaderFooters(headerFooterInput, layout, sectionMetad
285267
285688
  const displayPages = computeDisplayPageNumber(layout.pages, sectionMetadata);
285268
285689
  const totalPages = layout.pages.length;
285269
285690
  const pageResolver = (pageNumber) => {
285691
+ const displayInfo = displayPages[pageNumber - 1];
285270
285692
  return {
285271
- displayText: displayPages[pageNumber - 1]?.displayText ?? String(pageNumber),
285693
+ displayText: displayInfo?.displayText ?? String(pageNumber),
285694
+ displayNumber: displayInfo?.displayNumber ?? pageNumber,
285272
285695
  totalPages
285273
285696
  };
285274
285697
  };
@@ -285371,6 +285794,10 @@ async function layoutWithPerSectionConstraints(kind, blocksByRId, sectionMetadat
285371
285794
  }
285372
285795
  }
285373
285796
  }
285797
+ function hasSectionRefsForKind(identifier, kind) {
285798
+ const refKey = kind === "header" ? "headerRefs" : "footerRefs";
285799
+ return Boolean(identifier?.sections?.some((section) => section[refKey] !== undefined));
285800
+ }
285374
285801
  function buildSurfacePmEntries(surface) {
285375
285802
  const nodes = Array.from(surface.querySelectorAll("[data-pm-start][data-pm-end]"));
285376
285803
  const nonLeaf = /* @__PURE__ */ new WeakSet;
@@ -285475,6 +285902,18 @@ function buildHeaderFooterStory(kind, id2) {
285475
285902
  function storyIdFromHeaderFooterLayoutKey(key2) {
285476
285903
  return key2.replace(/::s\d+$/, "");
285477
285904
  }
285905
+ function refForVariant(refs, variant) {
285906
+ const ref$1 = refs?.[variant];
285907
+ if (ref$1)
285908
+ return {
285909
+ refId: ref$1,
285910
+ matchedVariant: variant
285911
+ };
285912
+ return variant === "odd" && refs?.default ? {
285913
+ refId: refs.default,
285914
+ matchedVariant: "default"
285915
+ } : undefined;
285916
+ }
285478
285917
  function resolveResult(result, storyId) {
285479
285918
  const story = buildHeaderFooterStory(result.kind, storyId ?? String(result.type));
285480
285919
  return resolveHeaderFooterLayout(result.layout, result.blocks, result.measures, story);
@@ -285491,19 +285930,34 @@ function shiftResolvedPaintItemY(item, yOffset) {
285491
285930
  y: item.y + yOffset
285492
285931
  };
285493
285932
  }
285494
- function normalizeDecorationFragments(fragments, layoutMinY) {
285495
- if (layoutMinY >= 0)
285933
+ function isExplicitBehindDocMediaFragment(fragment2) {
285934
+ return (fragment2.kind === "image" || fragment2.kind === "drawing") && fragment2.behindDoc === true;
285935
+ }
285936
+ function getDecorationNormalizationMinY(fragments, layoutMinY) {
285937
+ if (!Number.isFinite(layoutMinY) || layoutMinY >= 0)
285938
+ return 0;
285939
+ let minY = Infinity;
285940
+ for (const fragment2 of fragments) {
285941
+ if (isExplicitBehindDocMediaFragment(fragment2))
285942
+ continue;
285943
+ if (Number.isFinite(fragment2.y))
285944
+ minY = Math.min(minY, fragment2.y);
285945
+ }
285946
+ return minY < 0 ? minY : 0;
285947
+ }
285948
+ function normalizeDecorationFragments(fragments, normalizationMinY) {
285949
+ if (normalizationMinY >= 0)
285496
285950
  return fragments;
285497
- const yOffset = -layoutMinY;
285951
+ const yOffset = -normalizationMinY;
285498
285952
  return fragments.map((fragment2) => ({
285499
285953
  ...fragment2,
285500
285954
  y: fragment2.y + yOffset
285501
285955
  }));
285502
285956
  }
285503
- function normalizeDecorationItems(items, layoutMinY) {
285504
- if (layoutMinY >= 0)
285957
+ function normalizeDecorationItems(items, normalizationMinY) {
285958
+ if (normalizationMinY >= 0)
285505
285959
  return items;
285506
- const yOffset = -layoutMinY;
285960
+ const yOffset = -normalizationMinY;
285507
285961
  return items.map((item) => shiftResolvedPaintItemY(item, yOffset));
285508
285962
  }
285509
285963
  function createStoryHiddenHost(doc$12, widthPx, options = {}) {
@@ -306208,6 +306662,7 @@ menclose::after {
306208
306662
  highlight: run2.highlight ?? null,
306209
306663
  textTransform: run2.textTransform ?? null,
306210
306664
  token: run2.token ?? null,
306665
+ pageNumberFieldFormat: run2.pageNumberFieldFormat ?? null,
306211
306666
  pageRefMetadata: run2.pageRefMetadata ?? null,
306212
306667
  trackedChange: run2.trackedChange ?? null,
306213
306668
  trackedChanges: run2.trackedChanges ?? null,
@@ -309326,10 +309781,16 @@ menclose::after {
309326
309781
  return "";
309327
309782
  if (!runToken)
309328
309783
  return run2.text ?? "";
309329
- if (runToken === "pageNumber")
309784
+ if (runToken === "pageNumber") {
309785
+ if (run2.pageNumberFieldFormat)
309786
+ return formatPageNumberFieldValue$1(context.displayPageNumber ?? context.pageNumber, run2.pageNumberFieldFormat);
309330
309787
  return context.pageNumberText ?? String(context.pageNumber);
309331
- if (runToken === "totalPageCount")
309788
+ }
309789
+ if (runToken === "totalPageCount") {
309790
+ if (run2.pageNumberFieldFormat)
309791
+ return formatPageNumberFieldValue$1(context.totalPages || 1, run2.pageNumberFieldFormat);
309332
309792
  return context.totalPages ? String(context.totalPages) : run2.text ?? "";
309793
+ }
309333
309794
  return run2.text ?? "";
309334
309795
  }, extractLinkData = (run2) => {
309335
309796
  if (run2.kind === "tab" || run2.kind === "image" || run2.kind === "lineBreak" || run2.kind === "math")
@@ -311215,16 +311676,17 @@ menclose::after {
311215
311676
  this.mount = mount;
311216
311677
  this.beginPaintSnapshot(resolvedLayout);
311217
311678
  this.totalPages = resolvedLayout.pages.length;
311679
+ const previousLayout = this.currentLayout;
311680
+ this.currentLayout = resolvedLayout;
311218
311681
  if (this.isSemanticFlow) {
311219
311682
  applyStyles(mount, containerStyles);
311220
311683
  mount.style.gap = "0px";
311221
311684
  mount.style.alignItems = "stretch";
311222
- if (!this.currentLayout || this.pageStates.length === 0)
311685
+ if (!previousLayout || this.pageStates.length === 0)
311223
311686
  this.fullRender(resolvedLayout);
311224
311687
  else
311225
311688
  this.patchLayout(resolvedLayout);
311226
311689
  this.setMountedPageIndices(this.createAllPageIndices(resolvedLayout.pages.length));
311227
- this.currentLayout = resolvedLayout;
311228
311690
  this.changedBlocks.clear();
311229
311691
  this.currentMapping = null;
311230
311692
  return;
@@ -311264,7 +311726,7 @@ menclose::after {
311264
311726
  this.currentMapping = null;
311265
311727
  } else {
311266
311728
  mount.style.gap = `${this.pageGap}px`;
311267
- if (!this.currentLayout || this.pageStates.length === 0)
311729
+ if (!previousLayout || this.pageStates.length === 0)
311268
311730
  this.fullRender(resolvedLayout);
311269
311731
  else {
311270
311732
  this.patchLayout(resolvedLayout);
@@ -311586,6 +312048,7 @@ menclose::after {
311586
312048
  totalPages: this.totalPages,
311587
312049
  section: "body",
311588
312050
  pageNumberText: page.numberText,
312051
+ displayPageNumber: page.displayNumber,
311589
312052
  pageIndex
311590
312053
  };
311591
312054
  const resolvedItems = page.items;
@@ -311800,6 +312263,7 @@ menclose::after {
311800
312263
  section: kind,
311801
312264
  story: resolveDecorationStory(kind, data),
311802
312265
  pageNumberText: page.numberText,
312266
+ displayPageNumber: page.displayNumber,
311803
312267
  pageIndex
311804
312268
  };
311805
312269
  const decorationItems = data.items ?? [];
@@ -311945,6 +312409,7 @@ menclose::after {
311945
312409
  totalPages: this.totalPages,
311946
312410
  section: "body",
311947
312411
  pageNumberText: page.numberText,
312412
+ displayPageNumber: page.displayNumber,
311948
312413
  pageIndex
311949
312414
  };
311950
312415
  resolvedItems.forEach((resolvedItem, index2) => {
@@ -311961,9 +312426,10 @@ menclose::after {
311961
312426
  const geometryChanged = hasFragmentGeometryChanged(current.fragment, fragment2);
311962
312427
  const sdtBoundaryMismatch = shouldRebuildForSdtBoundary(current.element, sdtBoundary);
311963
312428
  const betweenBorderMismatch = current.element.dataset.betweenBorder === "true" !== (betweenInfo?.showBetweenBorder ?? false) || current.element.dataset.suppressTopBorder === "true" !== (betweenInfo?.suppressTopBorder ?? false) || (current.element.dataset.gapBelow ?? "") !== (betweenInfo?.gapBelow ? String(betweenInfo.gapBelow) : "");
312429
+ const pageContextChanged = needsRebuildForPageContext(current.context, contextBase, resolvedItem);
311964
312430
  const newPmStart = fragment2.pmStart;
311965
312431
  const mappingUnreliable = this.currentMapping != null && newPmStart != null && current.element.dataset.pmStart != null && this.currentMapping.map(Number(current.element.dataset.pmStart)) !== newPmStart;
311966
- if (geometryChanged || this.changedBlocks.has(fragment2.blockId) || current.signature !== resolvedSig || sdtBoundaryMismatch || betweenBorderMismatch || mappingUnreliable) {
312432
+ if (geometryChanged || this.changedBlocks.has(fragment2.blockId) || current.signature !== resolvedSig || sdtBoundaryMismatch || betweenBorderMismatch || pageContextChanged || mappingUnreliable) {
311967
312433
  const replacement = this.renderFragment(fragment2, contextBase, sdtBoundary, betweenInfo, resolvedItem);
311968
312434
  pageEl.replaceChild(replacement, current.element);
311969
312435
  current.element = replacement;
@@ -312045,6 +312511,7 @@ menclose::after {
312045
312511
  totalPages: this.totalPages,
312046
312512
  section: "body",
312047
312513
  pageNumberText: page.numberText,
312514
+ displayPageNumber: page.displayNumber,
312048
312515
  pageIndex
312049
312516
  };
312050
312517
  const resolvedItems = page.items;
@@ -312081,22 +312548,26 @@ menclose::after {
312081
312548
  }
312082
312549
  }
312083
312550
  getEffectivePageStyles() {
312084
- if (this.isSemanticFlow) {
312085
- const base5 = this.options.pageStyles ?? {};
312551
+ const documentBackgroundColor = this.currentLayout?.documentBackground?.color;
312552
+ const base5 = this.options.pageStyles ?? {};
312553
+ const baseWithDocumentBackground = documentBackgroundColor ? {
312554
+ ...base5,
312555
+ background: documentBackgroundColor
312556
+ } : base5;
312557
+ if (this.isSemanticFlow)
312086
312558
  return {
312087
- ...base5,
312088
- background: base5.background ?? "var(--sd-layout-page-bg, #fff)",
312559
+ ...baseWithDocumentBackground,
312560
+ background: baseWithDocumentBackground.background ?? "var(--sd-layout-page-bg, #fff)",
312089
312561
  boxShadow: "none",
312090
312562
  border: "none",
312091
312563
  margin: "0"
312092
312564
  };
312093
- }
312094
312565
  if (this.virtualEnabled && this.layoutMode === "vertical")
312095
312566
  return {
312096
- ...this.options.pageStyles ?? {},
312567
+ ...baseWithDocumentBackground,
312097
312568
  margin: "0 auto"
312098
312569
  };
312099
- return this.options.pageStyles;
312570
+ return documentBackgroundColor ? baseWithDocumentBackground : this.options.pageStyles;
312100
312571
  }
312101
312572
  renderFragment(fragment2, context, sdtBoundary, betweenInfo, resolvedItem) {
312102
312573
  if (fragment2.kind === "para")
@@ -313595,6 +314066,7 @@ menclose::after {
313595
314066
  textRun.vertAlign ?? "",
313596
314067
  textRun.baselineShift != null ? textRun.baselineShift : "",
313597
314068
  textRun.token ?? "",
314069
+ textRun.pageNumberFieldFormat ? JSON.stringify(textRun.pageNumberFieldFormat) : "",
313598
314070
  trackedVersion,
313599
314071
  textRun.comments?.length ?? 0,
313600
314072
  textRun.bidi ? JSON.stringify(textRun.bidi) : ""
@@ -313751,6 +314223,9 @@ menclose::after {
313751
314223
  hash$3 = hashString(hash$3, getRunBooleanProp(run2, "strike") ? "1" : "");
313752
314224
  hash$3 = hashString(hash$3, getRunStringProp(run2, "vertAlign"));
313753
314225
  hash$3 = hashNumber(hash$3, getRunNumberProp(run2, "baselineShift"));
314226
+ hash$3 = hashString(hash$3, getRunStringProp(run2, "token"));
314227
+ const pageNumberFieldFormat = run2.pageNumberFieldFormat;
314228
+ hash$3 = hashString(hash$3, pageNumberFieldFormat ? JSON.stringify(pageNumberFieldFormat) : "");
313754
314229
  const bidi = run2.bidi;
313755
314230
  hash$3 = hashString(hash$3, bidi ? JSON.stringify(bidi) : "");
313756
314231
  hash$3 = hashString(hash$3, trackedChangeVersion(run2));
@@ -314144,7 +314619,8 @@ menclose::after {
314144
314619
  sectionCount: 0,
314145
314620
  sectionHeaderIds: /* @__PURE__ */ new Map,
314146
314621
  sectionFooterIds: /* @__PURE__ */ new Map,
314147
- sectionTitlePg: /* @__PURE__ */ new Map
314622
+ sectionTitlePg: /* @__PURE__ */ new Map,
314623
+ sections: []
314148
314624
  }), fieldAnnotationKey = (run2) => {
314149
314625
  if (run2.kind !== "fieldAnnotation")
314150
314626
  return "";
@@ -321302,17 +321778,20 @@ menclose::after {
321302
321778
  }
321303
321779
  #computeExpectedSectionType(kind, page, sectionFirstPageNumbers) {
321304
321780
  const pageNumber = page.number;
321781
+ const effectivePageNumber = page.effectivePageNumber ?? page.displayNumber ?? pageNumber;
321305
321782
  const sectionIndex = page.sectionIndex ?? 0;
321306
321783
  const isFirstPageOfSection = sectionFirstPageNumbers.get(sectionIndex) === pageNumber;
321307
321784
  const converter = this.#options.editor.converter;
321308
- const hasAlternateHeaders = converter?.pageStyles?.alternateHeaders === true;
321785
+ const hasAlternateHeaders = this.#multiSectionIdentifier?.alternateHeaders === true || converter?.pageStyles?.alternateHeaders === true;
321309
321786
  const headerIds = converter?.headerIds;
321310
321787
  const footerIds = converter?.footerIds;
321311
- const titlePgEnabled = headerIds?.titlePg === true || footerIds?.titlePg === true;
321788
+ let titlePgEnabled = headerIds?.titlePg === true || footerIds?.titlePg === true;
321789
+ if (this.#multiSectionIdentifier?.sectionTitlePg?.has(sectionIndex))
321790
+ titlePgEnabled = this.#multiSectionIdentifier.sectionTitlePg.get(sectionIndex) === true;
321312
321791
  if (isFirstPageOfSection && titlePgEnabled)
321313
321792
  return "first";
321314
321793
  if (hasAlternateHeaders)
321315
- return (page.displayNumber ?? page.number) % 2 === 0 ? "even" : "odd";
321794
+ return effectivePageNumber % 2 === 0 ? "even" : "odd";
321316
321795
  return "default";
321317
321796
  }
321318
321797
  #stripFootnoteReserveFromBottomMargin(margins, page) {
@@ -321693,37 +322172,33 @@ menclose::after {
321693
322172
  if (!sectionFirstPageNumbers.has(idx))
321694
322173
  sectionFirstPageNumbers.set(idx, p$12.number);
321695
322174
  }
322175
+ const hasSectionResolution = hasSectionRefsForKind(multiSectionId, kind);
321696
322176
  return (pageNumber, pageMargins, page) => {
321697
322177
  const sectionIndex = page?.sectionIndex ?? 0;
322178
+ const effectivePageNumber = page?.effectivePageNumber ?? page?.displayNumber ?? pageNumber;
321698
322179
  const firstPageInSection = sectionFirstPageNumbers.get(sectionIndex);
321699
322180
  const sectionPageNumber = typeof firstPageInSection === "number" ? pageNumber - firstPageInSection + 1 : pageNumber;
321700
- const parityPageNumber = page?.displayNumber ?? pageNumber;
321701
- const headerFooterType = multiSectionId ? getHeaderFooterTypeForSection(pageNumber, sectionIndex, multiSectionId, {
322181
+ const headerFooterType = hasSectionResolution ? getHeaderFooterTypeForSection(effectivePageNumber, sectionIndex, multiSectionId, {
321702
322182
  kind,
321703
322183
  sectionPageNumber,
321704
- parityPageNumber
322184
+ parityPageNumber: effectivePageNumber
321705
322185
  }) : getHeaderFooterType2(pageNumber, legacyIdentifier, {
321706
322186
  kind,
321707
- parityPageNumber
321708
- });
321709
- let sectionRId;
321710
- if (page?.sectionRefs && kind === "header") {
321711
- sectionRId = page.sectionRefs.headerRefs?.[headerFooterType];
321712
- if (!sectionRId && headerFooterType && headerFooterType !== "default" && sectionIndex > 0 && multiSectionId)
321713
- sectionRId = multiSectionId.sectionHeaderIds.get(sectionIndex - 1)?.[headerFooterType] ?? undefined;
321714
- const shouldUseDefaultHeaderRef = headerFooterType !== "default" && page.sectionRefs.headerRefs?.default && (!multiSectionId?.alternateHeaders || headerFooterType === "odd");
321715
- if (!sectionRId && shouldUseDefaultHeaderRef)
321716
- sectionRId = page.sectionRefs.headerRefs?.default;
321717
- } else if (page?.sectionRefs && kind === "footer") {
321718
- sectionRId = page.sectionRefs.footerRefs?.[headerFooterType];
321719
- if (!sectionRId && headerFooterType && headerFooterType !== "default" && sectionIndex > 0 && multiSectionId)
321720
- sectionRId = multiSectionId.sectionFooterIds.get(sectionIndex - 1)?.[headerFooterType] ?? undefined;
321721
- const shouldUseDefaultFooterRef = headerFooterType !== "default" && page.sectionRefs.footerRefs?.default && (!multiSectionId?.alternateHeaders || headerFooterType === "odd");
321722
- if (!sectionRId && shouldUseDefaultFooterRef)
321723
- sectionRId = page.sectionRefs.footerRefs?.default;
321724
- }
322187
+ parityPageNumber: effectivePageNumber
322188
+ });
321725
322189
  if (!headerFooterType)
321726
322190
  return null;
322191
+ const pageSectionRefs = kind === "header" ? page?.sectionRefs?.headerRefs : page?.sectionRefs?.footerRefs;
322192
+ const sectionResolvedRef = hasSectionResolution ? resolveEffectiveHeaderFooterRef({
322193
+ sections: multiSectionId.sections,
322194
+ sectionIndex,
322195
+ kind,
322196
+ variant: headerFooterType
322197
+ }) : null;
322198
+ const legacyRefs = kind === "header" ? legacyIdentifier.headerIds : legacyIdentifier.footerIds;
322199
+ const resolvedRef = refForVariant(pageSectionRefs, headerFooterType) ?? sectionResolvedRef ?? (!hasSectionResolution ? refForVariant(legacyRefs, headerFooterType) : undefined);
322200
+ const sectionRId = resolvedRef?.refId;
322201
+ const layoutVariantType = resolvedRef?.matchedVariant ?? headerFooterType;
321727
322202
  const compositeKey = sectionRId ? `${sectionRId}::s${sectionIndex}` : undefined;
321728
322203
  const rIdLayoutKey = compositeKey && layoutsByRId.has(compositeKey) && compositeKey || sectionRId && layoutsByRId.has(sectionRId) && sectionRId || undefined;
321729
322204
  if (rIdLayoutKey) {
@@ -321746,8 +322221,9 @@ menclose::after {
321746
322221
  const rawLayoutHeight$1 = rIdLayout.layout.height ?? 0;
321747
322222
  const metrics$1 = this.#computeMetrics(kind, rawLayoutHeight$1, box$1, pageHeight$1, margins$1?.footer ?? 0);
321748
322223
  const layoutMinY$1 = rIdLayout.layout.minY ?? 0;
321749
- const normalizedFragments$1 = normalizeDecorationFragments(fragments$1, layoutMinY$1);
321750
- const normalizedItems$1 = normalizeDecorationItems(alignedItems, layoutMinY$1);
322224
+ const normalizationMinY$1 = getDecorationNormalizationMinY(fragments$1, layoutMinY$1);
322225
+ const normalizedFragments$1 = normalizeDecorationFragments(fragments$1, normalizationMinY$1);
322226
+ const normalizedItems$1 = normalizeDecorationItems(alignedItems, normalizationMinY$1);
321751
322227
  const isActiveHeaderFooter$1 = this.#isActiveDecoration(kind, sectionRId, pageNumber);
321752
322228
  return {
321753
322229
  fragments: normalizedFragments$1,
@@ -321779,7 +322255,7 @@ menclose::after {
321779
322255
  }
321780
322256
  if (!results || results.length === 0)
321781
322257
  return null;
321782
- const variantIndex = results.findIndex((entry) => entry.type === headerFooterType);
322258
+ const variantIndex = results.findIndex((entry) => entry.type === layoutVariantType);
321783
322259
  const variant = variantIndex >= 0 ? results[variantIndex] : undefined;
321784
322260
  if (!variant || !variant.layout?.pages?.length)
321785
322261
  return null;
@@ -321790,7 +322266,7 @@ menclose::after {
321790
322266
  const fallbackId = this.#headerFooterManager?.getVariantId(kind, headerFooterType);
321791
322267
  const finalHeaderId = sectionRId ?? fallbackId ?? undefined;
321792
322268
  const resolvedVariant = resolvedResults?.[variantIndex];
321793
- const alignedVariantItems = this.resolveAlignedDecorationItems(fragments, slotPage.number, variant, resolvedVariant, `variant '${headerFooterType}' page ${pageNumber}`, finalHeaderId ?? headerFooterType);
322269
+ const alignedVariantItems = this.resolveAlignedDecorationItems(fragments, slotPage.number, variant, resolvedVariant, `variant '${layoutVariantType}' page ${pageNumber}`, finalHeaderId ?? headerFooterType);
321794
322270
  if (!alignedVariantItems)
321795
322271
  return null;
321796
322272
  const pageHeight = page?.height ?? resolvedLayout.pages[0]?.height ?? layoutOptions.pageSize?.h ?? defaultPageSize.h;
@@ -321800,8 +322276,9 @@ menclose::after {
321800
322276
  const rawLayoutHeight = variant.layout.height ?? 0;
321801
322277
  const metrics = this.#computeMetrics(kind, rawLayoutHeight, box, pageHeight, margins?.footer ?? 0);
321802
322278
  const layoutMinY = variant.layout.minY ?? 0;
321803
- const normalizedFragments = normalizeDecorationFragments(fragments, layoutMinY);
321804
- const normalizedItems = normalizeDecorationItems(alignedVariantItems, layoutMinY);
322279
+ const normalizationMinY = getDecorationNormalizationMinY(fragments, layoutMinY);
322280
+ const normalizedFragments = normalizeDecorationFragments(fragments, normalizationMinY);
322281
+ const normalizedItems = normalizeDecorationItems(alignedVariantItems, normalizationMinY);
321805
322282
  const isActiveHeaderFooter = this.#isActiveDecoration(kind, finalHeaderId, pageNumber);
321806
322283
  return {
321807
322284
  fragments: normalizedFragments,
@@ -322382,13 +322859,13 @@ menclose::after {
322382
322859
  return;
322383
322860
  console.log(...args$1);
322384
322861
  }, HEADER_FOOTER_INIT_BUDGET_MS = 200, MAX_ZOOM_WARNING_THRESHOLD = 10, MAX_SELECTION_RECTS_PER_USER = 100, SEMANTIC_RESIZE_DEBOUNCE_MS = 120, MIN_SEMANTIC_CONTENT_WIDTH_PX = 1, GLOBAL_PERFORMANCE, PresentationEditor, ICONS, TEXTS, tableActionsOptions, TRACKED_MARK_NAMES;
322385
- var init_src_BAgFSihz_es = __esm(() => {
322862
+ var init_src_CibMiO0y_es = __esm(() => {
322386
322863
  init_rolldown_runtime_Bg48TavK_es();
322387
- init_SuperConverter_CcHCWpfX_es();
322864
+ init_SuperConverter_EumzHoTv_es();
322388
322865
  init_jszip_C49i9kUs_es();
322389
322866
  init_xml_js_CqGKpaft_es();
322390
322867
  init_uuid_qzgm05fK_es();
322391
- init_create_headless_toolbar_DKwoydAR_es();
322868
+ init_create_headless_toolbar_CRyPCXZF_es();
322392
322869
  init_constants_D_X7xF4s_es();
322393
322870
  init_dist_B8HfvhaK_es();
322394
322871
  init_unified_Dsuw2be5_es();
@@ -325232,6 +325709,10 @@ ${err.toString()}`);
325232
325709
  bodySectPr: {
325233
325710
  rendered: false,
325234
325711
  default: null
325712
+ },
325713
+ documentBackground: {
325714
+ rendered: false,
325715
+ default: null
325235
325716
  }
325236
325717
  };
325237
325718
  },
@@ -329268,10 +329749,24 @@ ${err.toString()}`);
329268
329749
  } };
329269
329750
  },
329270
329751
  addAttributes() {
329271
- return { marksAsAttrs: {
329272
- default: null,
329273
- rendered: false
329274
- } };
329752
+ return {
329753
+ marksAsAttrs: {
329754
+ default: null,
329755
+ rendered: false
329756
+ },
329757
+ instruction: {
329758
+ default: null,
329759
+ rendered: false
329760
+ },
329761
+ pageNumberFormat: {
329762
+ default: null,
329763
+ rendered: false
329764
+ },
329765
+ pageNumberZeroPadding: {
329766
+ default: null,
329767
+ rendered: false
329768
+ }
329769
+ };
329275
329770
  },
329276
329771
  addNodeView() {
329277
329772
  return ({ node: node3, editor, getPos, decorations }) => {
@@ -329328,6 +329823,18 @@ ${err.toString()}`);
329328
329823
  default: null,
329329
329824
  rendered: false
329330
329825
  },
329826
+ instruction: {
329827
+ default: null,
329828
+ rendered: false
329829
+ },
329830
+ pageNumberFormat: {
329831
+ default: null,
329832
+ rendered: false
329833
+ },
329834
+ pageNumberZeroPadding: {
329835
+ default: null,
329836
+ rendered: false
329837
+ },
329331
329838
  importedCachedText: {
329332
329839
  default: null,
329333
329840
  rendered: false
@@ -350272,6 +350779,7 @@ function print() { __p += __j.call(arguments, '') }
350272
350779
  #hiddenHost;
350273
350780
  #hiddenHostWrapper;
350274
350781
  #layoutOptions;
350782
+ #configuredDocumentBackground;
350275
350783
  #layoutState = {
350276
350784
  blocks: [],
350277
350785
  measures: [],
@@ -350387,6 +350895,7 @@ function print() { __p += __j.call(arguments, '') }
350387
350895
  } : undefined;
350388
350896
  const requestedFlowMode = options.layoutEngineOptions?.flowMode === "semantic" ? "semantic" : "paginated";
350389
350897
  const requestedLayoutMode = options.layoutEngineOptions?.layoutMode ?? "vertical";
350898
+ this.#configuredDocumentBackground = this.#coerceDocumentBackground(options.layoutEngineOptions?.documentBackground);
350390
350899
  this.#layoutOptions = {
350391
350900
  pageSize: options.layoutEngineOptions?.pageSize ?? DEFAULT_PAGE_SIZE,
350392
350901
  margins: options.layoutEngineOptions?.margins ?? DEFAULT_MARGINS,
@@ -350395,6 +350904,7 @@ function print() { __p += __j.call(arguments, '') }
350395
350904
  enabled: false
350396
350905
  } : options.layoutEngineOptions?.virtualization,
350397
350906
  zoom: options.layoutEngineOptions?.zoom ?? 1,
350907
+ ...this.#configuredDocumentBackground ? { documentBackground: this.#configuredDocumentBackground } : {},
350398
350908
  pageStyles: options.layoutEngineOptions?.pageStyles,
350399
350909
  debugLabel: options.layoutEngineOptions?.debugLabel,
350400
350910
  layoutMode: requestedFlowMode === "semantic" ? "vertical" : requestedLayoutMode,
@@ -354702,6 +355212,11 @@ function print() { __p += __j.call(arguments, '') }
354702
355212
  this.#layoutOptions.pageSize = pageSize;
354703
355213
  this.#layoutOptions.margins = margins;
354704
355214
  const flowMode = this.#layoutOptions.flowMode ?? "paginated";
355215
+ const documentBackground = this.#resolveDocumentBackground();
355216
+ if (documentBackground)
355217
+ this.#layoutOptions.documentBackground = documentBackground;
355218
+ else
355219
+ delete this.#layoutOptions.documentBackground;
354705
355220
  const resolvedMargins = {
354706
355221
  top: margins.top,
354707
355222
  right: margins.right,
@@ -354741,7 +355256,8 @@ function print() { __p += __j.call(arguments, '') }
354741
355256
  marginTop: semanticMargins.top,
354742
355257
  marginBottom: semanticMargins.bottom
354743
355258
  },
354744
- sectionMetadata
355259
+ sectionMetadata,
355260
+ ...documentBackground ? { documentBackground } : {}
354745
355261
  };
354746
355262
  }
354747
355263
  this.#hiddenHost.style.width = `${pageSize.w}px`;
@@ -354750,6 +355266,7 @@ function print() { __p += __j.call(arguments, '') }
354750
355266
  flowMode: "paginated",
354751
355267
  pageSize,
354752
355268
  margins: resolvedMargins,
355269
+ ...documentBackground ? { documentBackground } : {},
354753
355270
  ...columns ? { columns } : {},
354754
355271
  sectionMetadata,
354755
355272
  alternateHeaders
@@ -354769,6 +355286,15 @@ function print() { __p += __j.call(arguments, '') }
354769
355286
  out.push(...blocks2);
354770
355287
  return out;
354771
355288
  }
355289
+ #coerceDocumentBackground(candidate) {
355290
+ if (!candidate || typeof candidate !== "object")
355291
+ return;
355292
+ const color2 = candidate.color;
355293
+ return typeof color2 === "string" && color2.length > 0 ? { color: color2 } : undefined;
355294
+ }
355295
+ #resolveDocumentBackground() {
355296
+ return this.#coerceDocumentBackground(this.#editor?.state?.doc?.attrs?.documentBackground) ?? (this.#configuredDocumentBackground ? { ...this.#configuredDocumentBackground } : undefined);
355297
+ }
354772
355298
  #buildHeaderFooterInput() {
354773
355299
  if (this.#isSemanticFlowMode())
354774
355300
  return null;
@@ -356738,11 +357264,11 @@ function print() { __p += __j.call(arguments, '') }
356738
357264
  ]);
356739
357265
  });
356740
357266
 
356741
- // ../../packages/superdoc/dist/chunks/create-super-doc-ui-CEjelItp.es.js
357267
+ // ../../packages/superdoc/dist/chunks/create-super-doc-ui-DcawZW5k.es.js
356742
357268
  var MOD_ALIASES, ALT_ALIASES, CTRL_ALIASES, SHIFT_ALIASES, BUILTIN_CONTEXT_MENU_GROUPS, BUILTIN_GROUP_ORDER, RESERVED_PROXY_PROPERTY_NAMES, ALL_TOOLBAR_COMMAND_IDS, EMPTY_ACTIVE_IDS;
356743
- var init_create_super_doc_ui_CEjelItp_es = __esm(() => {
356744
- init_SuperConverter_CcHCWpfX_es();
356745
- init_create_headless_toolbar_DKwoydAR_es();
357269
+ var init_create_super_doc_ui_DcawZW5k_es = __esm(() => {
357270
+ init_SuperConverter_EumzHoTv_es();
357271
+ init_create_headless_toolbar_CRyPCXZF_es();
356746
357272
  MOD_ALIASES = new Set([
356747
357273
  "Mod",
356748
357274
  "Meta",
@@ -356784,16 +357310,16 @@ var init_zipper_yaJVJ4z9_es = __esm(() => {
356784
357310
 
356785
357311
  // ../../packages/superdoc/dist/super-editor.es.js
356786
357312
  var init_super_editor_es = __esm(() => {
356787
- init_src_BAgFSihz_es();
356788
- init_SuperConverter_CcHCWpfX_es();
357313
+ init_src_CibMiO0y_es();
357314
+ init_SuperConverter_EumzHoTv_es();
356789
357315
  init_jszip_C49i9kUs_es();
356790
357316
  init_xml_js_CqGKpaft_es();
356791
- init_create_headless_toolbar_DKwoydAR_es();
357317
+ init_create_headless_toolbar_CRyPCXZF_es();
356792
357318
  init_constants_D_X7xF4s_es();
356793
357319
  init_dist_B8HfvhaK_es();
356794
357320
  init_unified_Dsuw2be5_es();
356795
357321
  init_DocxZipper_nv_KfOqb_es();
356796
- init_create_super_doc_ui_CEjelItp_es();
357322
+ init_create_super_doc_ui_DcawZW5k_es();
356797
357323
  init_ui_C5PAS9hY_es();
356798
357324
  init_eventemitter3_BnGqBE_Q_es();
356799
357325
  init_errors_CNaD6vcg_es();