@file-viewer/docx 0.3.39 → 0.3.41

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.
@@ -403,7 +403,7 @@
403
403
  props.fontSize = xml.lengthAttr(elem, "val", LengthUsage.FontSize);
404
404
  break;
405
405
  case "szCs":
406
- props.fontSize ?? (props.fontSize = xml.lengthAttr(elem, "val", LengthUsage.FontSize));
406
+ props.complexFontSize = xml.lengthAttr(elem, "val", LengthUsage.FontSize);
407
407
  break;
408
408
  default:
409
409
  return false;
@@ -1669,6 +1669,8 @@
1669
1669
  for (const c of xml.elements(el)) {
1670
1670
  if (c.localName == "adjustLineHeightInTable")
1671
1671
  result.adjustLineHeightInTable = xml.boolAttr(c, "val", true);
1672
+ else if (c.localName == "doNotUseHTMLParagraphAutoSpacing")
1673
+ result.doNotUseHTMLParagraphAutoSpacing = xml.boolAttr(c, "val", true);
1672
1674
  }
1673
1675
  break;
1674
1676
  }
@@ -4040,6 +4042,44 @@
4040
4042
  };
4041
4043
  }
4042
4044
 
4045
+ const WORD_PARAGRAPH_LINE_UNIT_PT = 12;
4046
+ function paragraphSpacingDeclaration(points, lines) {
4047
+ const lineValue = Number.isFinite(lines) && lines >= 0 ? `${(lines * WORD_PARAGRAPH_LINE_UNIT_PT / 100).toFixed(2)}pt` : null;
4048
+ const validPoints = /^(?:\d+(?:\.\d*)?|\.\d+)pt$/i.test(points ?? "");
4049
+ return { lines: lineValue, fallback: lines === 0 && validPoints ? points : lineValue ?? points };
4050
+ }
4051
+ const WORD_HTML_AUTO_SPACING_PT = 14;
4052
+ function effectiveParagraphSpacing(levels, fixed, styleId) {
4053
+ const value = (key) => levels.find(level => level?.[key] != null)?.[key];
4054
+ const side = (name) => {
4055
+ const prefix = `--docx-spacing-${name}`;
4056
+ const autoValue = value(`${prefix}-auto`);
4057
+ const auto = autoValue === "true";
4058
+ const lines = value(`${prefix}-lines`), points = value(`${prefix}-points`);
4059
+ const declared = autoValue === "true" || autoValue === "false"
4060
+ || spacingPoints(lines) != null || spacingPoints(points) != null;
4061
+ const ordinary = parseFloat(lines) > 0 ? lines : points ?? lines ?? "0pt";
4062
+ return { auto: auto && !fixed, declared, length: auto && !fixed ? `${WORD_HTML_AUTO_SPACING_PT}pt` : ordinary };
4063
+ };
4064
+ const before = side("before"), after = side("after");
4065
+ return { before: before.length, after: after.length, beforeAuto: before.auto, afterAuto: after.auto,
4066
+ beforeDeclared: before.declared, afterDeclared: after.declared,
4067
+ contextual: value("--docx-contextual-spacing") === "true", styleId };
4068
+ }
4069
+ function spacingPoints(length) {
4070
+ const match = /^(\d+(?:\.\d*)?|\.\d+)(pt|px)$/i.exec(length ?? "");
4071
+ return match ? Number(match[1]) * (match[2].toLowerCase() === "px" ? .75 : 1) : null;
4072
+ }
4073
+ function paragraphSpacingGap(previous, next, fixed) {
4074
+ const after = spacingPoints(previous.after), before = spacingPoints(next.before);
4075
+ if (after == null || before == null)
4076
+ return null;
4077
+ const same = previous.styleId === next.styleId;
4078
+ const remainder = fixed ? before : Math.max(0, before - after);
4079
+ const gap = (same && previous.contextual ? 0 : after) + (same && next.contextual ? 0 : remainder);
4080
+ return `${Math.round(gap * 1000000) / 1000000}pt`;
4081
+ }
4082
+
4043
4083
  var autos = {
4044
4084
  shd: "inherit",
4045
4085
  color: "var(--docx-auto-color, black)",
@@ -6190,8 +6230,10 @@
6190
6230
  style["font-size"] = style["min-height"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize);
6191
6231
  break;
6192
6232
  case "szCs":
6193
- style["font-size"] ?? (style["font-size"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize));
6194
- style["min-height"] ?? (style["min-height"] = style["font-size"]);
6233
+ style["--docx-complex-font-size"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize);
6234
+ break;
6235
+ case "cs":
6236
+ style["--docx-complex-script"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6195
6237
  break;
6196
6238
  case "shd":
6197
6239
  style["background-color"] = xmlUtil.colorAttr(c, "fill", null, autos.shd);
@@ -6255,6 +6297,7 @@
6255
6297
  style["font-variant"] = globalXmlParser.boolAttr(c, "val", true) ? "small-caps" : "none";
6256
6298
  break;
6257
6299
  case "rtl":
6300
+ style["--docx-rtl-run"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6258
6301
  if (globalXmlParser.boolAttr(c, "val", true)) {
6259
6302
  style["direction"] = "rtl";
6260
6303
  style["unicode-bidi"] = "embed";
@@ -6387,9 +6430,11 @@
6387
6430
  if (globalXmlParser.boolAttr(c, "val", true))
6388
6431
  style["display"] = "none";
6389
6432
  break;
6433
+ case "contextualSpacing":
6434
+ style["--docx-contextual-spacing"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6435
+ break;
6390
6436
  case "tabs":
6391
6437
  case "outlineLvl":
6392
- case "contextualSpacing":
6393
6438
  case "tblStyleColBandSize":
6394
6439
  case "tblStyleRowBandSize":
6395
6440
  case "suppressLineNumbers":
@@ -6499,6 +6544,18 @@
6499
6544
  style["--docx-latin-font-family"] = [...new Set(latinFonts)].join(', ');
6500
6545
  style["--docx-partial-eastasia-font"] = !latinFonts.length && (eastAsia || eastAsiaTheme) && !cs && !csTheme ? "true" : "false";
6501
6546
  }
6547
+ const slots = {
6548
+ ascii: [ascii, asciiTheme], hansi: [hAnsi, hAnsiTheme],
6549
+ eastasia: [eastAsia, eastAsiaTheme], complex: [cs, csTheme]
6550
+ };
6551
+ for (const [slot, [direct, themed]] of Object.entries(slots)) {
6552
+ const selected = themed || direct;
6553
+ if (!selected)
6554
+ continue;
6555
+ const family = selected.startsWith("var(") ? selected
6556
+ : expandDirectFont(selected, slot == "complex" ? themeScriptForLanguage(languages.bidi) : eastAsiaScript).join(', ');
6557
+ style[`--docx-font-${slot}`] = family;
6558
+ }
6502
6559
  }
6503
6560
  scriptThemeFontValue(value, language) {
6504
6561
  if (!value)
@@ -6543,18 +6600,28 @@
6543
6600
  var afterAuto = globalXmlParser.boolAttr(node, "afterAutospacing", false);
6544
6601
  var line = globalXmlParser.intAttr(node, "line", null);
6545
6602
  var lineRule = globalXmlParser.attr(node, "lineRule");
6546
- if (beforeAuto)
6547
- style["margin-top"] = "auto";
6548
- else if (Number.isFinite(beforeLines) && beforeLines >= 0)
6549
- style["margin-top"] = `${(beforeLines / 100).toFixed(2)}em`;
6550
- else if (before)
6551
- style["margin-top"] = before;
6552
- if (afterAuto)
6553
- style["margin-bottom"] = "auto";
6554
- else if (Number.isFinite(afterLines) && afterLines >= 0)
6555
- style["margin-bottom"] = `${(afterLines / 100).toFixed(2)}em`;
6556
- else if (after)
6557
- style["margin-bottom"] = after;
6603
+ for (const [side, margin, points, lines, auto] of [
6604
+ ["before", "margin-top", before, beforeLines, beforeAuto],
6605
+ ["after", "margin-bottom", after, afterLines, afterAuto]
6606
+ ]) {
6607
+ const prefix = `--docx-spacing-${side}`;
6608
+ const { lines: lineValue, fallback } = paragraphSpacingDeclaration(points, lines);
6609
+ const autoSpecified = globalXmlParser.attr(node, `${side}Autospacing`) != null;
6610
+ if (points != null)
6611
+ style[`${prefix}-points`] = points;
6612
+ if (lineValue != null)
6613
+ style[`${prefix}-lines`] = lineValue;
6614
+ if (fallback != null)
6615
+ style[`${prefix}-fallback`] = fallback;
6616
+ if (autoSpecified)
6617
+ style[`${prefix}-auto`] = `${auto}`;
6618
+ if (auto)
6619
+ style[margin] = `${WORD_HTML_AUTO_SPACING_PT}pt`;
6620
+ else if (fallback != null)
6621
+ style[margin] = fallback;
6622
+ else if (autoSpecified)
6623
+ style[margin] = "0pt";
6624
+ }
6558
6625
  if (line !== null) {
6559
6626
  switch (lineRule ?? "auto") {
6560
6627
  case "auto":
@@ -8030,6 +8097,18 @@
8030
8097
  return applied;
8031
8098
  }
8032
8099
 
8100
+ function gridAutomaticLineHeight(lineHeight, linePitch) {
8101
+ const multiplier = /^\d+(?:\.\d+)?$/.test(lineHeight ?? "") ? Number(lineHeight) : NaN;
8102
+ return Number.isFinite(multiplier) && multiplier >= 1
8103
+ ? `calc(${linePitch} * ${multiplier})`
8104
+ : /^-?\d+(?:\.\d+)?$/.test(lineHeight ?? "") ? `calc(${lineHeight} * 1em)` : lineHeight;
8105
+ }
8106
+ function gridFontLineHeight(natural, pitch, multiplier = 1) {
8107
+ if (![natural, pitch, multiplier].every(Number.isFinite) || natural < 0 || pitch <= 0 || multiplier < 1)
8108
+ return null;
8109
+ return Math.max(pitch * multiplier, Math.max(1, Math.ceil((natural - 1 / 64) / pitch)) * pitch);
8110
+ }
8111
+
8033
8112
  const DEFAULT_DARK_MODE_BASE_L = 21.247;
8034
8113
  const LAB_EPSILON = Math.pow(6 / 29, 3);
8035
8114
  function srgbToLinear(c) {
@@ -8692,6 +8771,22 @@
8692
8771
  return elements.map(copy);
8693
8772
  }
8694
8773
 
8774
+ const legacyComplexScriptCharacters = /[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufeff]/u;
8775
+ const additionalComplexScriptCharacters = new RegExp([
8776
+ 'Devanagari', 'Bengali', 'Gurmukhi', 'Gujarati', 'Oriya', 'Tamil', 'Telugu',
8777
+ 'Kannada', 'Malayalam', 'Sinhala', 'Thai', 'Lao', 'Tibetan', 'Myanmar', 'Khmer'
8778
+ ].map(script => `\\p{Script=${script}}`).join('|'), 'u');
8779
+ const neutralScriptCharacters = /[\p{Script=Common}\p{Script=Inherited}]/u;
8780
+ function isAdditionalComplexScriptRun(text) {
8781
+ if (!additionalComplexScriptCharacters.test(text))
8782
+ return false;
8783
+ for (const character of text) {
8784
+ if (!additionalComplexScriptCharacters.test(character)
8785
+ && !legacyComplexScriptCharacters.test(character) && !neutralScriptCharacters.test(character))
8786
+ return false;
8787
+ }
8788
+ return true;
8789
+ }
8695
8790
  const chartNamespaces = [
8696
8791
  "http://schemas.openxmlformats.org/drawingml/2006/chart",
8697
8792
  "http://purl.oclc.org/ooxml/drawingml/chart"
@@ -8780,6 +8875,7 @@
8780
8875
  this.tasks = [];
8781
8876
  this.postRenderTasks = [];
8782
8877
  this.compatibleTextBoxSpacing = false;
8878
+ this.paragraphSpacingStates = new WeakMap();
8783
8879
  this.h = h;
8784
8880
  this.darkModeVarNames = new Map();
8785
8881
  this.darkModePrintReset = {};
@@ -8791,6 +8887,9 @@
8791
8887
  this.rootSelector = options.inWrapper ? `.${this.className}-wrapper` : ':root';
8792
8888
  this.h = options.h ?? h;
8793
8889
  this.styleMap = null;
8890
+ this.defaultParagraphStyle = null;
8891
+ this.defaultCharacterStyle = null;
8892
+ this.defaultRunStyle = null;
8794
8893
  this.tasks = [];
8795
8894
  this.postRenderTasks = [];
8796
8895
  this.commentLayer = null;
@@ -8885,6 +8984,7 @@
8885
8984
  variables['--docx-majorEastAsia-font'] = this.themeFontFamily(fontScheme.majorFont, "eastAsia", languages.eastAsia);
8886
8985
  variables['--docx-majorBidi-font'] = this.themeFontFamily(fontScheme.majorFont, "complexScript", languages.bidi);
8887
8986
  variables['--docx-majorCs-font'] = variables['--docx-majorBidi-font'];
8987
+ this.addThemeFontFallbackVariables(variables, "major", fontScheme.majorFont);
8888
8988
  this.addThemeScriptFontVariables(variables, "major", fontScheme.majorFont);
8889
8989
  }
8890
8990
  if (fontScheme.minorFont) {
@@ -8892,6 +8992,7 @@
8892
8992
  variables['--docx-minorEastAsia-font'] = this.themeFontFamily(fontScheme.minorFont, "eastAsia", languages.eastAsia);
8893
8993
  variables['--docx-minorBidi-font'] = this.themeFontFamily(fontScheme.minorFont, "complexScript", languages.bidi);
8894
8994
  variables['--docx-minorCs-font'] = variables['--docx-minorBidi-font'];
8995
+ this.addThemeFontFallbackVariables(variables, "minor", fontScheme.minorFont);
8895
8996
  this.addThemeScriptFontVariables(variables, "minor", fontScheme.minorFont);
8896
8997
  }
8897
8998
  }
@@ -8927,6 +9028,15 @@
8927
9028
  result.bidi = values["$lang-bidi"] ?? result.latin;
8928
9029
  return result;
8929
9030
  }
9031
+ addThemeFontFallbackVariables(variables, size, font) {
9032
+ const fallback = (direct, generic) => {
9033
+ const typeface = direct?.trim() || font.latinTypeface?.trim();
9034
+ return typeface ? `${encloseFontFamily(typeface)}, ${generic}` : generic;
9035
+ };
9036
+ variables[`--docx-${size}EastAsia-font-fallback`] = fallback(font.eaTypeface, "sans-serif");
9037
+ variables[`--docx-${size}Bidi-font-fallback`] = fallback(font.csTypeface, "serif");
9038
+ variables[`--docx-${size}Cs-font-fallback`] = variables[`--docx-${size}Bidi-font-fallback`];
9039
+ }
8930
9040
  addThemeScriptFontVariables(variables, size, font) {
8931
9041
  const eastAsianScripts = new Set(["Hans", "Hant", "Jpan", "Hang"]);
8932
9042
  for (const script of Object.keys(font.scriptTypefaces ?? {})) {
@@ -8985,6 +9095,9 @@
8985
9095
  }
8986
9096
  processStyles(styles) {
8987
9097
  const stylesMap = keyBy(styles.filter(x => x.id != null), x => x.id);
9098
+ this.defaultParagraphStyle = styles.find(style => style.isDefault && style.target == "p");
9099
+ this.defaultCharacterStyle = styles.find(style => style.isDefault && style.target == "span");
9100
+ this.defaultRunStyle = styles.find(style => style.id == null);
8988
9101
  for (const style of styles.filter(x => x.basedOn)) {
8989
9102
  var baseStyle = stylesMap[style.basedOn];
8990
9103
  if (baseStyle) {
@@ -9684,14 +9797,20 @@
9684
9797
  result.push({ paragraph: currentParagraph, breakAfter: false });
9685
9798
  }
9686
9799
  const last = result[result.length - 1]?.paragraph;
9800
+ const siblings = paragraph.parent?.children?.filter(child => ![DomType.BookmarkStart, DomType.BookmarkEnd].includes(child.type));
9687
9801
  for (const item of result) {
9688
9802
  item.paragraph.sectionProps = item.paragraph === last ? paragraph.sectionProps : null;
9803
+ item.paragraph.props = { ...item.paragraph.props,
9804
+ spacingFirstInFlow: siblings?.[0] === paragraph && item === result[0],
9805
+ spacingLastInFlow: siblings?.[siblings.length - 1] === paragraph && item.paragraph === last };
9689
9806
  }
9690
- if (paragraph.props?.anchorId && result.length > 1) {
9691
- const owner = result.find(part => this.extractText(part.paragraph).trim()) ?? result[0];
9807
+ if (result.length > 1) {
9808
+ const owner = result.find(part => this.hasPageModelContent(part.paragraph)) ?? result[0];
9692
9809
  for (const part of result) {
9693
- if (part !== owner)
9694
- part.paragraph.props = { ...part.paragraph.props, anchorId: undefined };
9810
+ if (part !== owner) {
9811
+ part.paragraph.props = { ...part.paragraph.props, anchorId: undefined,
9812
+ pageBreakContinuation: true, pageBreakEmpty: !this.hasPageModelContent(part.paragraph) };
9813
+ }
9695
9814
  }
9696
9815
  }
9697
9816
  return result;
@@ -9702,6 +9821,73 @@
9702
9821
  styleValue(style, target, name) {
9703
9822
  return this.styleValuesForTarget(style, target)?.[name];
9704
9823
  }
9824
+ styleValueLevels(style, target) {
9825
+ const levels = [];
9826
+ const seen = new Set();
9827
+ while (style && !seen.has(style)) {
9828
+ seen.add(style);
9829
+ levels.push(this.styleValuesForTarget(style, target));
9830
+ style = this.findStyle(style.basedOn);
9831
+ }
9832
+ return levels;
9833
+ }
9834
+ effectiveParagraphNumbering(elem, style) {
9835
+ let numbering = elem?.numbering;
9836
+ let current = elem?.styleName ? style : this.defaultParagraphStyle;
9837
+ const seen = new Set();
9838
+ while (!numbering && current?.target == "p" && !seen.has(current)) {
9839
+ seen.add(current);
9840
+ numbering = current.paragraphProps?.numbering;
9841
+ current = this.findStyle(current.basedOn);
9842
+ }
9843
+ return numbering && !/^0+$/.test(String(numbering.id ?? "").trim()) ? numbering : null;
9844
+ }
9845
+ applyParagraphAutoSpacing(elem, style, result) {
9846
+ const paragraphStyle = elem.styleName ? style : this.defaultParagraphStyle;
9847
+ const numbering = this.effectiveParagraphNumbering(elem, style);
9848
+ const numberingStyle = numbering && this.document?.numberingPart?.domNumberings
9849
+ ?.find(num => num.id == numbering.id && num.level == numbering.level)?.pStyle;
9850
+ const levels = [elem.cssStyle, ...this.styleValueLevels(paragraphStyle, "p"), numberingStyle,
9851
+ this.styleValuesForTarget(this.defaultRunStyle, "p")];
9852
+ const fixed = this.document?.settingsPart?.settings?.doNotUseHTMLParagraphAutoSpacing;
9853
+ const state = effectiveParagraphSpacing(levels, fixed, elem.styleName ?? paragraphStyle?.id ?? "");
9854
+ const siblings = elem.parent?.children?.filter(child => ![DomType.BookmarkStart, DomType.BookmarkEnd].includes(child.type));
9855
+ const first = elem.props?.spacingFirstInFlow ?? siblings?.[0] === elem;
9856
+ const last = elem.props?.spacingLastInFlow ?? siblings?.[siblings.length - 1] === elem;
9857
+ if (state.beforeAuto && first && [DomType.Document, DomType.Cell].includes(elem.parent?.type))
9858
+ state.before = "0pt";
9859
+ if (state.afterAuto && last && elem.parent?.type === DomType.Cell)
9860
+ state.after = "0pt";
9861
+ if (state.beforeDeclared)
9862
+ this.setCssStyle(result, "margin-top", state.before);
9863
+ if (state.afterDeclared)
9864
+ this.setCssStyle(result, "margin-bottom", state.after);
9865
+ this.paragraphSpacingStates.set(result, state);
9866
+ }
9867
+ applyFlowParagraphSpacing(nodes) {
9868
+ let previous = null;
9869
+ const fixed = this.document?.settingsPart?.settings?.doNotUseHTMLParagraphAutoSpacing;
9870
+ for (const node of nodes) {
9871
+ const state = typeof node === "object" && node && this.paragraphSpacingStates.get(node);
9872
+ if (!state) {
9873
+ const element = node;
9874
+ if (element?.nodeType === 3 && !element.textContent?.trim())
9875
+ continue;
9876
+ if (/^(a|span)$/i.test(element?.tagName ?? "") && !element.textContent && element.id)
9877
+ continue;
9878
+ previous = null;
9879
+ continue;
9880
+ }
9881
+ if (previous && (previous.state.afterDeclared || state.beforeDeclared)) {
9882
+ const gap = paragraphSpacingGap(previous.state, state, fixed);
9883
+ if (gap != null) {
9884
+ this.setCssStyle(previous.node, "margin-bottom", "0pt");
9885
+ this.setCssStyle(node, "margin-top", gap);
9886
+ }
9887
+ }
9888
+ previous = { node: node, state };
9889
+ }
9890
+ }
9705
9891
  effectiveParagraphCssValue(elem, style, name) {
9706
9892
  return elem.cssStyle?.[name] ?? this.styleValue(style, "p", name);
9707
9893
  }
@@ -9728,6 +9914,46 @@
9728
9914
  this.setCssStyle(result, "--docx-latin-font-family", latin);
9729
9915
  this.setCssStyle(result, "font-family", `var(--docx-latin-font-family), ${family}`);
9730
9916
  }
9917
+ applyRunFontSlots(elem, style, result) {
9918
+ const paragraph = elem.type == DomType.Paragraph ? elem : this.currentParagraph;
9919
+ const paragraphStyle = this.findStyle(paragraph?.styleName) ?? this.defaultParagraphStyle;
9920
+ const levels = [elem.cssStyle, ...this.styleValueLevels(style, "span"),
9921
+ paragraph?.cssStyle, ...this.styleValueLevels(paragraphStyle, "span"),
9922
+ this.styleValuesForTarget(this.defaultCharacterStyle, "span"),
9923
+ this.styleValuesForTarget(this.defaultRunStyle, "span")];
9924
+ const value = (key) => levels.find(level => level?.[key] != null)?.[key];
9925
+ const language = (key) => value(key) ?? value("$lang");
9926
+ const themedFont = (font, language) => {
9927
+ const match = /^var\((--docx-(?:major|minor)(?:EastAsia|Bidi|Cs)-font)(?:-[A-Za-z]{4}, var\(\1\))?\)$/.exec(font ?? "");
9928
+ if (!match)
9929
+ return font;
9930
+ const script = themeScriptForLanguage(language);
9931
+ const base = `var(${match[1]}-fallback)`;
9932
+ return script ? `var(${match[1]}-${script}, ${base})` : base;
9933
+ };
9934
+ const text = elem.type == DomType.Run ? (elem.children ?? [])
9935
+ .filter(child => child.type == DomType.Text || child.type == DomType.DeletedText)
9936
+ .map(child => child.text).join("") : "";
9937
+ const forceComplex = value("--docx-complex-script");
9938
+ const complex = forceComplex == "true" || value("--docx-rtl-run") == "true"
9939
+ || (forceComplex != "false" && ((legacyComplexScriptCharacters.test(text)
9940
+ && !/[\p{Script=Latin}\p{Script=Cyrillic}\p{Script=Han}]/u.test(text))
9941
+ || isAdditionalComplexScriptRun(text)));
9942
+ const highAnsi = /[\p{Script=Cyrillic}\p{Script=Greek}]/u.test(text);
9943
+ const slots = complex ? ["complex", "ascii", "hansi", "eastasia"]
9944
+ : highAnsi ? ["hansi", "ascii", "eastasia", "complex"] : ["ascii", "hansi", "eastasia", "complex"];
9945
+ const fonts = slots.map(slot => {
9946
+ const font = value(`--docx-font-${slot}`);
9947
+ return slot == "eastasia" ? themedFont(font, language("$lang-eastAsia"))
9948
+ : slot == "complex" ? themedFont(font, language("$lang-bidi")) : font;
9949
+ }).filter(Boolean);
9950
+ if (fonts.length)
9951
+ this.setCssStyle(result, "font-family", [...new Set(fonts)].join(', '));
9952
+ if (complex && value("--docx-complex-font-size")) {
9953
+ this.setCssStyle(result, "font-size", value("--docx-complex-font-size"));
9954
+ this.setCssStyle(result, "min-height", value("--docx-complex-font-size"));
9955
+ }
9956
+ }
9731
9957
  isInsideTableCell(elem) {
9732
9958
  for (let p = elem.parent; p; p = p.parent) {
9733
9959
  if (p.type == DomType.Cell)
@@ -9735,13 +9961,32 @@
9735
9961
  }
9736
9962
  return false;
9737
9963
  }
9964
+ paragraphSnapToGrid(elem, style) {
9965
+ const key = "--docx-snap-to-grid";
9966
+ if (elem.cssStyle?.[key] != null)
9967
+ return elem.cssStyle[key];
9968
+ let current = elem.styleName ? style : this.defaultParagraphStyle;
9969
+ const numbering = this.effectiveParagraphNumbering(elem, style);
9970
+ const seen = new Set();
9971
+ while (current?.target == "p" && !seen.has(current)) {
9972
+ seen.add(current);
9973
+ const value = this.styleValue(current, "p", key);
9974
+ if (value != null)
9975
+ return value;
9976
+ current = this.findStyle(current.basedOn);
9977
+ }
9978
+ const numberingStyle = numbering && this.document?.numberingPart?.domNumberings
9979
+ ?.find(num => num.id == numbering.id && num.level == numbering.level)?.pStyle;
9980
+ return numberingStyle?.[key] ?? this.styleValue(this.defaultRunStyle, "p", key);
9981
+ }
9738
9982
  paragraphUsesDocumentGrid(elem, style) {
9739
- const linePitch = this.currentSectionProps?.docGrid?.linePitch;
9740
- if (!linePitch)
9983
+ const grid = this.currentSectionProps?.docGrid;
9984
+ const linePitch = grid?.linePitch;
9985
+ if (!linePitch || !grid.type || grid.type === "default")
9741
9986
  return false;
9742
9987
  if (this.isInsideTableCell(elem) && !this.document.settingsPart?.settings?.adjustLineHeightInTable)
9743
9988
  return false;
9744
- const snapToGrid = this.effectiveParagraphCssValue(elem, style, "--docx-snap-to-grid");
9989
+ const snapToGrid = this.paragraphSnapToGrid(elem, style);
9745
9990
  return snapToGrid == null || !/^(0|false|off)$/i.test(snapToGrid);
9746
9991
  }
9747
9992
  setCssStyle(element, name, value) {
@@ -9761,17 +10006,27 @@
9761
10006
  const linePitch = this.currentSectionProps.docGrid.linePitch;
9762
10007
  const lineHeight = this.effectiveParagraphCssValue(elem, style, "line-height");
9763
10008
  const lineSpacing = elem.lineSpacing ?? style?.paragraphProps?.lineSpacing;
10009
+ const exact = lineSpacing?.lineRule == "exact" || lineSpacing?.lineRule == "exactly";
10010
+ if (!exact && !this.compatibleTextBoxSpacing && result.dataset
10011
+ && ["lines", "linesAndChars"].includes(this.currentSectionProps.docGrid.type)) {
10012
+ const numeric = /^\d+(?:\.\d+)?$/.test(lineHeight ?? "") ? Number(lineHeight) : 1;
10013
+ if (numeric >= 1) {
10014
+ result.dataset.docxParagraphGridPitch = linePitch;
10015
+ result.dataset.docxParagraphGridMultiple = `${numeric}`;
10016
+ result.dataset.docxParagraphGridAtLeast = `${lineSpacing?.lineRule == "atLeast"}`;
10017
+ }
10018
+ }
9764
10019
  if (lineHeight) {
9765
- if (lineSpacing?.lineRule == "exact" || lineSpacing?.lineRule == "exactly")
10020
+ if (exact)
9766
10021
  return;
9767
- const comparableLineHeight = /^-?\d+(?:\.\d+)?$/.test(lineHeight)
9768
- ? `calc(${lineHeight} * 1em)`
9769
- : lineHeight;
10022
+ const comparableLineHeight = gridAutomaticLineHeight(lineHeight, linePitch);
9770
10023
  this.preserveGridInlineMetrics(result);
9771
10024
  this.setCssStyle(result, "line-height", `max(${comparableLineHeight}, ${linePitch})`);
9772
10025
  this.applyDocumentGridMinimumHeight(elem, style, result, linePitch);
9773
10026
  return;
9774
10027
  }
10028
+ this.preserveGridInlineMetrics(result);
10029
+ this.setCssStyle(result, "line-height", linePitch);
9775
10030
  this.applyDocumentGridMinimumHeight(elem, style, result, linePitch);
9776
10031
  }
9777
10032
  preserveGridInlineMetrics(result) {
@@ -9953,6 +10208,11 @@
9953
10208
  movedAny = true;
9954
10209
  continue;
9955
10210
  }
10211
+ const tail = article.lastElementChild;
10212
+ if (this.canRetainTablePrefix(tail, page) && this.splitOverflowBlock(tail, page, nextArticle)) {
10213
+ movedAny = true;
10214
+ continue;
10215
+ }
9956
10216
  let chunk = this.pickPaginationChunk(article);
9957
10217
  if (chunk.length == 0)
9958
10218
  break;
@@ -10832,21 +11092,30 @@
10832
11092
  const rows = this.tableContentRows(table);
10833
11093
  if (rows.length <= 1)
10834
11094
  return false;
11095
+ const repeatHeaders = rows.filter(r => r.dataset.docxRepeatHeader == "true");
11096
+ if (repeatHeaders.length && !this.fitsTableRowPrefix(rows, page))
11097
+ return false;
10835
11098
  const clone = this.cloneBlockShell(table);
10836
11099
  clone.dataset.docxContinued = "true";
10837
11100
  for (const child of Array.from(table.children)) {
10838
11101
  if (child.tagName?.toLowerCase() == "colgroup")
10839
11102
  clone.appendChild(child.cloneNode(true));
10840
11103
  }
10841
- for (const header of rows.filter(r => r.dataset.docxRepeatHeader == "true")) {
11104
+ for (const [index, header] of repeatHeaders.entries()) {
10842
11105
  const repeated = header.cloneNode(true);
10843
11106
  repeated.dataset.docxRepeatedHeader = "true";
11107
+ for (const cell of Array.from(repeated.cells)) {
11108
+ const headerRowsRemaining = repeatHeaders.length - index;
11109
+ if (cell.rowSpan === 0 || cell.rowSpan > headerRowsRemaining)
11110
+ cell.rowSpan = headerRowsRemaining;
11111
+ }
10844
11112
  clone.appendChild(repeated);
10845
11113
  }
10846
11114
  nextArticle.prepend(clone);
10847
11115
  let movedAny = false;
10848
11116
  let guard = 0;
10849
- while (this.isPageOverflowing(page) && this.tableContentRows(table).length > 1 && guard++ < 500) {
11117
+ const minimumSourceRows = repeatHeaders.length + 1;
11118
+ while (this.isPageOverflowing(page) && this.tableContentRows(table).length > minimumSourceRows && guard++ < 500) {
10850
11119
  const currentRows = this.tableContentRows(table).filter(r => r.dataset.docxRepeatedHeader != "true");
10851
11120
  const last = currentRows[currentRows.length - 1];
10852
11121
  if (!last)
@@ -10858,8 +11127,58 @@
10858
11127
  clone.remove();
10859
11128
  return false;
10860
11129
  }
11130
+ const sourceRowCount = this.tableContentRows(table).length;
11131
+ const firstContinuationRow = this.firstMovedTableRow(clone);
11132
+ for (let rowIndex = 0; rowIndex < sourceRowCount; rowIndex++) {
11133
+ let column = 0;
11134
+ for (const cell of Array.from(rows[rowIndex].cells)) {
11135
+ const nextColumn = column + cell.colSpan;
11136
+ const remainingSpan = rowIndex + cell.rowSpan - sourceRowCount;
11137
+ if (remainingSpan > 0) {
11138
+ const continuation = this.cloneBlockShell(cell);
11139
+ continuation.textContent = "";
11140
+ continuation.rowSpan = remainingSpan;
11141
+ continuation.dataset.docxContinued = "true";
11142
+ let targetColumn = 0;
11143
+ let anchor = null;
11144
+ for (const targetCell of Array.from(firstContinuationRow.cells)) {
11145
+ if (targetColumn >= column) {
11146
+ anchor = targetCell;
11147
+ break;
11148
+ }
11149
+ targetColumn += targetCell.colSpan;
11150
+ }
11151
+ if (anchor && targetColumn === column && anchor.style.display === "none")
11152
+ anchor.replaceWith(continuation);
11153
+ else
11154
+ firstContinuationRow.insertBefore(continuation, anchor);
11155
+ cell.rowSpan = sourceRowCount - rowIndex;
11156
+ }
11157
+ column = nextColumn;
11158
+ }
11159
+ }
10861
11160
  return true;
10862
11161
  }
11162
+ canRetainTablePrefix(block, page) {
11163
+ if (block?.localName !== "table")
11164
+ return false;
11165
+ const style = getComputedStyle(block);
11166
+ if (style.position !== "static" || style.cssFloat !== "none" || block.dataset.docxFloat)
11167
+ return false;
11168
+ return this.fitsTableRowPrefix(this.tableContentRows(block), page);
11169
+ }
11170
+ fitsTableRowPrefix(rows, page) {
11171
+ if (rows.length < 2 || rows.some((row, index) => Array.from(row.cells).some(cell => cell.rowSpan < 1 || index + cell.rowSpan > rows.length)))
11172
+ return false;
11173
+ const firstBody = rows.findIndex(row => row.dataset.docxRepeatHeader != "true");
11174
+ if (firstBody < 0 || rows.slice(firstBody + 1).some(row => row.dataset.docxRepeatHeader == "true"))
11175
+ return false;
11176
+ const bottom = this.getPageBodyBottom(page) + (this.options.paginationTolerance ?? 2);
11177
+ return rows.slice(0, firstBody + 1).every(row => {
11178
+ const rect = row.getBoundingClientRect();
11179
+ return rect.height > 0 && rect.bottom <= bottom;
11180
+ });
11181
+ }
10863
11182
  cloneBlockShell(element) {
10864
11183
  const clone = element.cloneNode(false);
10865
11184
  clone.removeAttribute("id");
@@ -11140,7 +11459,7 @@
11140
11459
  wrapperStyle = `@media not print { ${wrapperStyle} }`;
11141
11460
  }
11142
11461
  var styleText = `${wrapperStyle}
11143
- .${c} { --docx-auto-color: ${autoColor}; color: var(--docx-auto-color); font-size: 10.5pt; font-family: var(--docx-minorHAnsi-font, "Times New Roman", serif); hyphens: auto; text-underline-position: from-font; font-kerning: normal; font-variant-ligatures: common-ligatures contextual; text-rendering: optimizeLegibility; line-break: auto; }
11462
+ .${c} { --docx-auto-color: ${autoColor}; color: var(--docx-auto-color); font-size: 10.5pt; font-family: var(--docx-minorHAnsi-font, "Times New Roman", serif); line-height: normal; hyphens: auto; text-underline-position: from-font; font-kerning: normal; font-variant-ligatures: common-ligatures contextual; text-rendering: optimizeLegibility; line-break: auto; }
11144
11463
  section.${c} { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: visible; isolation: isolate; }
11145
11464
  section.${c}>header, section.${c}>footer { flex-shrink: 0; }
11146
11465
  section.${c}>[data-docx-note-list] { flex-shrink: 0; }
@@ -11531,6 +11850,7 @@ section.${c}>footer { z-index: 1; }
11531
11850
  }
11532
11851
  const children = frameParagraphs
11533
11852
  .flatMap(item => asArray(this.renderElement(item)).filter(node => node != null));
11853
+ this.applyFlowParagraphSpacing(children);
11534
11854
  const frame = this.h({
11535
11855
  tagName: "div",
11536
11856
  className: `${this.className}-paragraph-frame`,
@@ -11550,6 +11870,7 @@ section.${c}>footer { z-index: 1; }
11550
11870
  }
11551
11871
  result.push(...asArray(this.renderElement(elems[i])).filter(e => e != null));
11552
11872
  }
11873
+ this.applyFlowParagraphSpacing(result);
11553
11874
  if (into)
11554
11875
  result.forEach(c => into.appendChild(isString(c) ? document.createTextNode(c) : c));
11555
11876
  return result;
@@ -11749,7 +12070,7 @@ section.${c}>footer { z-index: 1; }
11749
12070
  const style = this.findStyle(this.currentParagraph?.styleName);
11750
12071
  const isTocParagraph = this.isTocParagraphStyle(this.currentParagraph?.styleName, style);
11751
12072
  const isNumberedTocLeader = !!trailingLeader
11752
- && !!(this.currentParagraph?.numbering ?? style?.paragraphProps?.numbering)
12073
+ && !!this.effectiveParagraphNumbering(this.currentParagraph, style)
11753
12074
  && isTocParagraph;
11754
12075
  if (!trailingLeader)
11755
12076
  return stop;
@@ -11793,18 +12114,22 @@ section.${c}>footer { z-index: 1; }
11793
12114
  children = [flow];
11794
12115
  }
11795
12116
  var result = this.toHTML(elem, ns.html, "p", this.wrapTabLeaderChildren(children, true));
12117
+ this.applyParagraphAutoSpacing(elem, style, result);
11796
12118
  this.applyTextBoxFontInheritance(elem, style, result);
12119
+ this.applyRunFontSlots(elem, style, result);
11797
12120
  if (this.options.exposeDisplayTargets && elem.displayAddress) {
11798
12121
  const part = this.currentPart ?? this.document.documentPart;
11799
12122
  result.setAttribute("data-office-target", `${part.path}#${elem.displayAddress}`);
11800
12123
  }
11801
- const snapToGrid = this.effectiveParagraphCssValue(elem, style, "--docx-snap-to-grid");
12124
+ const snapToGrid = this.paragraphSnapToGrid(elem, style);
11802
12125
  if (/^(0|false|off)$/i.test(snapToGrid ?? ""))
11803
12126
  result.style.letterSpacing = "normal";
11804
12127
  this.currentParagraph = previousParagraph;
11805
12128
  this.currentParagraphTabIndex = previousParagraphTabIndex;
11806
12129
  this.currentParagraphTabCount = previousParagraphTabCount;
11807
- const numbering = elem.numbering ?? style?.paragraphProps?.numbering;
12130
+ const numbering = elem.props?.pageBreakContinuation ? null : this.effectiveParagraphNumbering(elem, style);
12131
+ if (elem.props?.pageBreakEmpty)
12132
+ result.style.display = "none";
11808
12133
  if (numbering) {
11809
12134
  result.classList.add(this.numberingClass(numbering.id, numbering.level));
11810
12135
  }
@@ -11860,7 +12185,7 @@ section.${c}>footer { z-index: 1; }
11860
12185
  return result;
11861
12186
  }
11862
12187
  uniformParagraphTextScale(paragraph, style) {
11863
- if (paragraph.numbering || style?.paragraphProps?.numbering || paragraph.frame
12188
+ if (this.effectiveParagraphNumbering(paragraph, style) || paragraph.frame
11864
12189
  || this.effectiveParagraphCssValue(paragraph, style, "writing-mode"))
11865
12190
  return null;
11866
12191
  const key = "--docx-text-scale";
@@ -12015,6 +12340,68 @@ section.${c}>footer { z-index: 1; }
12015
12340
  probe.remove();
12016
12341
  }
12017
12342
  }
12343
+ refreshParagraphLineGrid(root) {
12344
+ const view = root.ownerDocument?.defaultView;
12345
+ const paragraphs = Array.from(root.querySelectorAll("[data-docx-paragraph-grid-pitch]"))
12346
+ .filter(paragraph => this.ownsLayoutElement(paragraph));
12347
+ if (!view || !paragraphs.length)
12348
+ return;
12349
+ const probe = root.ownerDocument.createElement("span");
12350
+ Object.assign(probe.style, { position: "absolute", visibility: "hidden", pointerEvents: "none",
12351
+ display: "inline-block", whiteSpace: "pre", width: "max-content", margin: "0", padding: "0", border: "0" });
12352
+ probe.setAttribute("aria-hidden", "true");
12353
+ probe.textContent = "Mg";
12354
+ const scope = root.getRootNode();
12355
+ (scope.nodeType == 11 && "host" in scope ? scope : root.ownerDocument.body).appendChild(probe);
12356
+ const cache = new Map();
12357
+ const natural = (style) => {
12358
+ const font = { fontFamily: style.fontFamily, fontSize: style.fontSize, fontWeight: style.fontWeight,
12359
+ fontStyle: style.fontStyle, fontStretch: style.fontStretch, lineHeight: "normal", height: "auto" };
12360
+ const key = JSON.stringify(font);
12361
+ if (!cache.has(key)) {
12362
+ Object.assign(probe.style, font);
12363
+ cache.set(key, probe.getBoundingClientRect().height);
12364
+ }
12365
+ return cache.get(key);
12366
+ };
12367
+ try {
12368
+ for (const paragraph of paragraphs) {
12369
+ const style = view.getComputedStyle(paragraph), size = parseFloat(style.fontSize);
12370
+ probe.style.height = paragraph.dataset.docxParagraphGridPitch;
12371
+ const pitch = parseFloat(view.getComputedStyle(probe).height);
12372
+ const multiplier = Number(paragraph.dataset.docxParagraphGridMultiple);
12373
+ let height = gridFontLineHeight(natural(style), pitch, multiplier);
12374
+ if (height == null)
12375
+ continue;
12376
+ if (paragraph.dataset.docxParagraphGridAtLeast === "true")
12377
+ height = Math.max(height, parseFloat(style.lineHeight) || 0);
12378
+ paragraph.style.lineHeight = `${height}px`;
12379
+ const visit = (parent, script = false) => {
12380
+ for (const child of Array.from(parent.children)) {
12381
+ if (child.namespaceURI !== ns.html || !/^(span|a|sub|sup|b|i|u|s|strike|strong|em)$/.test(child.localName))
12382
+ continue;
12383
+ const own = child.dataset.docxGridOwnedHeight === "true";
12384
+ if ((!own && child.style.lineHeight && child.style.lineHeight !== "normal")
12385
+ || (child.style.display && child.style.display !== "inline" && !child.dataset.docxTextScale)
12386
+ || /^(absolute|fixed)$/.test(child.style.position) || (child.style.cssFloat && child.style.cssFloat !== "none"))
12387
+ continue;
12388
+ const childStyle = view.getComputedStyle(child);
12389
+ const raised = script || /^(super|sub)$/.test(childStyle.verticalAlign);
12390
+ const breakOnly = !child.textContent && !!child.querySelector("br") && !child.querySelector("img,svg,math");
12391
+ const childHeight = breakOnly || (raised && parseFloat(childStyle.fontSize) <= size) ? 0
12392
+ : Math.max(height, gridFontLineHeight(natural(childStyle), pitch) ?? height);
12393
+ child.style.lineHeight = `${childHeight}px`;
12394
+ child.dataset.docxGridOwnedHeight = "true";
12395
+ visit(child, raised);
12396
+ }
12397
+ };
12398
+ visit(paragraph);
12399
+ }
12400
+ }
12401
+ finally {
12402
+ probe.remove();
12403
+ }
12404
+ }
12018
12405
  async prepareLayout(root, generation = getLayoutGeneration(root)) {
12019
12406
  if (!root.isConnected || !generation.isCurrent())
12020
12407
  return;
@@ -12035,6 +12422,7 @@ section.${c}>footer { z-index: 1; }
12035
12422
  (owner ?? root).appendChild(this.commentLayer.root);
12036
12423
  }
12037
12424
  }
12425
+ this.refreshParagraphLineGrid(root);
12038
12426
  this.refreshTextBoxLineGrid(root);
12039
12427
  this.refreshTabStops(root);
12040
12428
  this.refreshAnchors(root);
@@ -14178,6 +14566,7 @@ section.${c}>footer { z-index: 1; }
14178
14566
  const result = this.toHTML(elem, ns.html, "span", children);
14179
14567
  const style = this.findStyle(elem.styleName);
14180
14568
  this.applyTextBoxFontInheritance(elem, style, result);
14569
+ this.applyRunFontSlots(elem, style, result);
14181
14570
  const snapToGrid = elem.cssStyle?.["--docx-snap-to-grid"] ?? this.styleValue(style, "span", "--docx-snap-to-grid");
14182
14571
  if (/^(0|false|off)$/i.test(snapToGrid ?? ""))
14183
14572
  result.style.letterSpacing = "normal";