@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.
@@ -399,7 +399,7 @@ function parseCommonProperty(elem, props, xml) {
399
399
  props.fontSize = xml.lengthAttr(elem, "val", LengthUsage.FontSize);
400
400
  break;
401
401
  case "szCs":
402
- props.fontSize ?? (props.fontSize = xml.lengthAttr(elem, "val", LengthUsage.FontSize));
402
+ props.complexFontSize = xml.lengthAttr(elem, "val", LengthUsage.FontSize);
403
403
  break;
404
404
  default:
405
405
  return false;
@@ -1665,6 +1665,8 @@ function parseSettings(elem, xml) {
1665
1665
  for (const c of xml.elements(el)) {
1666
1666
  if (c.localName == "adjustLineHeightInTable")
1667
1667
  result.adjustLineHeightInTable = xml.boolAttr(c, "val", true);
1668
+ else if (c.localName == "doNotUseHTMLParagraphAutoSpacing")
1669
+ result.doNotUseHTMLParagraphAutoSpacing = xml.boolAttr(c, "val", true);
1668
1670
  }
1669
1671
  break;
1670
1672
  }
@@ -4036,6 +4038,44 @@ function createParagraphAddressResolver() {
4036
4038
  };
4037
4039
  }
4038
4040
 
4041
+ const WORD_PARAGRAPH_LINE_UNIT_PT = 12;
4042
+ function paragraphSpacingDeclaration(points, lines) {
4043
+ const lineValue = Number.isFinite(lines) && lines >= 0 ? `${(lines * WORD_PARAGRAPH_LINE_UNIT_PT / 100).toFixed(2)}pt` : null;
4044
+ const validPoints = /^(?:\d+(?:\.\d*)?|\.\d+)pt$/i.test(points ?? "");
4045
+ return { lines: lineValue, fallback: lines === 0 && validPoints ? points : lineValue ?? points };
4046
+ }
4047
+ const WORD_HTML_AUTO_SPACING_PT = 14;
4048
+ function effectiveParagraphSpacing(levels, fixed, styleId) {
4049
+ const value = (key) => levels.find(level => level?.[key] != null)?.[key];
4050
+ const side = (name) => {
4051
+ const prefix = `--docx-spacing-${name}`;
4052
+ const autoValue = value(`${prefix}-auto`);
4053
+ const auto = autoValue === "true";
4054
+ const lines = value(`${prefix}-lines`), points = value(`${prefix}-points`);
4055
+ const declared = autoValue === "true" || autoValue === "false"
4056
+ || spacingPoints(lines) != null || spacingPoints(points) != null;
4057
+ const ordinary = parseFloat(lines) > 0 ? lines : points ?? lines ?? "0pt";
4058
+ return { auto: auto && !fixed, declared, length: auto && !fixed ? `${WORD_HTML_AUTO_SPACING_PT}pt` : ordinary };
4059
+ };
4060
+ const before = side("before"), after = side("after");
4061
+ return { before: before.length, after: after.length, beforeAuto: before.auto, afterAuto: after.auto,
4062
+ beforeDeclared: before.declared, afterDeclared: after.declared,
4063
+ contextual: value("--docx-contextual-spacing") === "true", styleId };
4064
+ }
4065
+ function spacingPoints(length) {
4066
+ const match = /^(\d+(?:\.\d*)?|\.\d+)(pt|px)$/i.exec(length ?? "");
4067
+ return match ? Number(match[1]) * (match[2].toLowerCase() === "px" ? .75 : 1) : null;
4068
+ }
4069
+ function paragraphSpacingGap(previous, next, fixed) {
4070
+ const after = spacingPoints(previous.after), before = spacingPoints(next.before);
4071
+ if (after == null || before == null)
4072
+ return null;
4073
+ const same = previous.styleId === next.styleId;
4074
+ const remainder = fixed ? before : Math.max(0, before - after);
4075
+ const gap = (same && previous.contextual ? 0 : after) + (same && next.contextual ? 0 : remainder);
4076
+ return `${Math.round(gap * 1000000) / 1000000}pt`;
4077
+ }
4078
+
4039
4079
  var autos = {
4040
4080
  shd: "inherit",
4041
4081
  color: "var(--docx-auto-color, black)",
@@ -6186,8 +6226,10 @@ class DocumentParser {
6186
6226
  style["font-size"] = style["min-height"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize);
6187
6227
  break;
6188
6228
  case "szCs":
6189
- style["font-size"] ?? (style["font-size"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize));
6190
- style["min-height"] ?? (style["min-height"] = style["font-size"]);
6229
+ style["--docx-complex-font-size"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize);
6230
+ break;
6231
+ case "cs":
6232
+ style["--docx-complex-script"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6191
6233
  break;
6192
6234
  case "shd":
6193
6235
  style["background-color"] = xmlUtil.colorAttr(c, "fill", null, autos.shd);
@@ -6251,6 +6293,7 @@ class DocumentParser {
6251
6293
  style["font-variant"] = globalXmlParser.boolAttr(c, "val", true) ? "small-caps" : "none";
6252
6294
  break;
6253
6295
  case "rtl":
6296
+ style["--docx-rtl-run"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6254
6297
  if (globalXmlParser.boolAttr(c, "val", true)) {
6255
6298
  style["direction"] = "rtl";
6256
6299
  style["unicode-bidi"] = "embed";
@@ -6383,9 +6426,11 @@ class DocumentParser {
6383
6426
  if (globalXmlParser.boolAttr(c, "val", true))
6384
6427
  style["display"] = "none";
6385
6428
  break;
6429
+ case "contextualSpacing":
6430
+ style["--docx-contextual-spacing"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6431
+ break;
6386
6432
  case "tabs":
6387
6433
  case "outlineLvl":
6388
- case "contextualSpacing":
6389
6434
  case "tblStyleColBandSize":
6390
6435
  case "tblStyleRowBandSize":
6391
6436
  case "suppressLineNumbers":
@@ -6495,6 +6540,18 @@ class DocumentParser {
6495
6540
  style["--docx-latin-font-family"] = [...new Set(latinFonts)].join(', ');
6496
6541
  style["--docx-partial-eastasia-font"] = !latinFonts.length && (eastAsia || eastAsiaTheme) && !cs && !csTheme ? "true" : "false";
6497
6542
  }
6543
+ const slots = {
6544
+ ascii: [ascii, asciiTheme], hansi: [hAnsi, hAnsiTheme],
6545
+ eastasia: [eastAsia, eastAsiaTheme], complex: [cs, csTheme]
6546
+ };
6547
+ for (const [slot, [direct, themed]] of Object.entries(slots)) {
6548
+ const selected = themed || direct;
6549
+ if (!selected)
6550
+ continue;
6551
+ const family = selected.startsWith("var(") ? selected
6552
+ : expandDirectFont(selected, slot == "complex" ? themeScriptForLanguage(languages.bidi) : eastAsiaScript).join(', ');
6553
+ style[`--docx-font-${slot}`] = family;
6554
+ }
6498
6555
  }
6499
6556
  scriptThemeFontValue(value, language) {
6500
6557
  if (!value)
@@ -6539,18 +6596,28 @@ class DocumentParser {
6539
6596
  var afterAuto = globalXmlParser.boolAttr(node, "afterAutospacing", false);
6540
6597
  var line = globalXmlParser.intAttr(node, "line", null);
6541
6598
  var lineRule = globalXmlParser.attr(node, "lineRule");
6542
- if (beforeAuto)
6543
- style["margin-top"] = "auto";
6544
- else if (Number.isFinite(beforeLines) && beforeLines >= 0)
6545
- style["margin-top"] = `${(beforeLines / 100).toFixed(2)}em`;
6546
- else if (before)
6547
- style["margin-top"] = before;
6548
- if (afterAuto)
6549
- style["margin-bottom"] = "auto";
6550
- else if (Number.isFinite(afterLines) && afterLines >= 0)
6551
- style["margin-bottom"] = `${(afterLines / 100).toFixed(2)}em`;
6552
- else if (after)
6553
- style["margin-bottom"] = after;
6599
+ for (const [side, margin, points, lines, auto] of [
6600
+ ["before", "margin-top", before, beforeLines, beforeAuto],
6601
+ ["after", "margin-bottom", after, afterLines, afterAuto]
6602
+ ]) {
6603
+ const prefix = `--docx-spacing-${side}`;
6604
+ const { lines: lineValue, fallback } = paragraphSpacingDeclaration(points, lines);
6605
+ const autoSpecified = globalXmlParser.attr(node, `${side}Autospacing`) != null;
6606
+ if (points != null)
6607
+ style[`${prefix}-points`] = points;
6608
+ if (lineValue != null)
6609
+ style[`${prefix}-lines`] = lineValue;
6610
+ if (fallback != null)
6611
+ style[`${prefix}-fallback`] = fallback;
6612
+ if (autoSpecified)
6613
+ style[`${prefix}-auto`] = `${auto}`;
6614
+ if (auto)
6615
+ style[margin] = `${WORD_HTML_AUTO_SPACING_PT}pt`;
6616
+ else if (fallback != null)
6617
+ style[margin] = fallback;
6618
+ else if (autoSpecified)
6619
+ style[margin] = "0pt";
6620
+ }
6554
6621
  if (line !== null) {
6555
6622
  switch (lineRule ?? "auto") {
6556
6623
  case "auto":
@@ -8026,6 +8093,18 @@ function layoutExplicitTabs(root, ownsElement = () => true) {
8026
8093
  return applied;
8027
8094
  }
8028
8095
 
8096
+ function gridAutomaticLineHeight(lineHeight, linePitch) {
8097
+ const multiplier = /^\d+(?:\.\d+)?$/.test(lineHeight ?? "") ? Number(lineHeight) : NaN;
8098
+ return Number.isFinite(multiplier) && multiplier >= 1
8099
+ ? `calc(${linePitch} * ${multiplier})`
8100
+ : /^-?\d+(?:\.\d+)?$/.test(lineHeight ?? "") ? `calc(${lineHeight} * 1em)` : lineHeight;
8101
+ }
8102
+ function gridFontLineHeight(natural, pitch, multiplier = 1) {
8103
+ if (![natural, pitch, multiplier].every(Number.isFinite) || natural < 0 || pitch <= 0 || multiplier < 1)
8104
+ return null;
8105
+ return Math.max(pitch * multiplier, Math.max(1, Math.ceil((natural - 1 / 64) / pitch)) * pitch);
8106
+ }
8107
+
8029
8108
  const DEFAULT_DARK_MODE_BASE_L = 21.247;
8030
8109
  const LAB_EPSILON = Math.pow(6 / 29, 3);
8031
8110
  function srgbToLinear(c) {
@@ -8688,6 +8767,22 @@ function normalizeCachedPageBreaks(elements, isHiddenRevision) {
8688
8767
  return elements.map(copy);
8689
8768
  }
8690
8769
 
8770
+ const legacyComplexScriptCharacters = /[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufeff]/u;
8771
+ const additionalComplexScriptCharacters = new RegExp([
8772
+ 'Devanagari', 'Bengali', 'Gurmukhi', 'Gujarati', 'Oriya', 'Tamil', 'Telugu',
8773
+ 'Kannada', 'Malayalam', 'Sinhala', 'Thai', 'Lao', 'Tibetan', 'Myanmar', 'Khmer'
8774
+ ].map(script => `\\p{Script=${script}}`).join('|'), 'u');
8775
+ const neutralScriptCharacters = /[\p{Script=Common}\p{Script=Inherited}]/u;
8776
+ function isAdditionalComplexScriptRun(text) {
8777
+ if (!additionalComplexScriptCharacters.test(text))
8778
+ return false;
8779
+ for (const character of text) {
8780
+ if (!additionalComplexScriptCharacters.test(character)
8781
+ && !legacyComplexScriptCharacters.test(character) && !neutralScriptCharacters.test(character))
8782
+ return false;
8783
+ }
8784
+ return true;
8785
+ }
8691
8786
  const chartNamespaces = [
8692
8787
  "http://schemas.openxmlformats.org/drawingml/2006/chart",
8693
8788
  "http://purl.oclc.org/ooxml/drawingml/chart"
@@ -8776,6 +8871,7 @@ class HtmlRenderer {
8776
8871
  this.tasks = [];
8777
8872
  this.postRenderTasks = [];
8778
8873
  this.compatibleTextBoxSpacing = false;
8874
+ this.paragraphSpacingStates = new WeakMap();
8779
8875
  this.h = h;
8780
8876
  this.darkModeVarNames = new Map();
8781
8877
  this.darkModePrintReset = {};
@@ -8787,6 +8883,9 @@ class HtmlRenderer {
8787
8883
  this.rootSelector = options.inWrapper ? `.${this.className}-wrapper` : ':root';
8788
8884
  this.h = options.h ?? h;
8789
8885
  this.styleMap = null;
8886
+ this.defaultParagraphStyle = null;
8887
+ this.defaultCharacterStyle = null;
8888
+ this.defaultRunStyle = null;
8790
8889
  this.tasks = [];
8791
8890
  this.postRenderTasks = [];
8792
8891
  this.commentLayer = null;
@@ -8881,6 +8980,7 @@ class HtmlRenderer {
8881
8980
  variables['--docx-majorEastAsia-font'] = this.themeFontFamily(fontScheme.majorFont, "eastAsia", languages.eastAsia);
8882
8981
  variables['--docx-majorBidi-font'] = this.themeFontFamily(fontScheme.majorFont, "complexScript", languages.bidi);
8883
8982
  variables['--docx-majorCs-font'] = variables['--docx-majorBidi-font'];
8983
+ this.addThemeFontFallbackVariables(variables, "major", fontScheme.majorFont);
8884
8984
  this.addThemeScriptFontVariables(variables, "major", fontScheme.majorFont);
8885
8985
  }
8886
8986
  if (fontScheme.minorFont) {
@@ -8888,6 +8988,7 @@ class HtmlRenderer {
8888
8988
  variables['--docx-minorEastAsia-font'] = this.themeFontFamily(fontScheme.minorFont, "eastAsia", languages.eastAsia);
8889
8989
  variables['--docx-minorBidi-font'] = this.themeFontFamily(fontScheme.minorFont, "complexScript", languages.bidi);
8890
8990
  variables['--docx-minorCs-font'] = variables['--docx-minorBidi-font'];
8991
+ this.addThemeFontFallbackVariables(variables, "minor", fontScheme.minorFont);
8891
8992
  this.addThemeScriptFontVariables(variables, "minor", fontScheme.minorFont);
8892
8993
  }
8893
8994
  }
@@ -8923,6 +9024,15 @@ class HtmlRenderer {
8923
9024
  result.bidi = values["$lang-bidi"] ?? result.latin;
8924
9025
  return result;
8925
9026
  }
9027
+ addThemeFontFallbackVariables(variables, size, font) {
9028
+ const fallback = (direct, generic) => {
9029
+ const typeface = direct?.trim() || font.latinTypeface?.trim();
9030
+ return typeface ? `${encloseFontFamily(typeface)}, ${generic}` : generic;
9031
+ };
9032
+ variables[`--docx-${size}EastAsia-font-fallback`] = fallback(font.eaTypeface, "sans-serif");
9033
+ variables[`--docx-${size}Bidi-font-fallback`] = fallback(font.csTypeface, "serif");
9034
+ variables[`--docx-${size}Cs-font-fallback`] = variables[`--docx-${size}Bidi-font-fallback`];
9035
+ }
8926
9036
  addThemeScriptFontVariables(variables, size, font) {
8927
9037
  const eastAsianScripts = new Set(["Hans", "Hant", "Jpan", "Hang"]);
8928
9038
  for (const script of Object.keys(font.scriptTypefaces ?? {})) {
@@ -8981,6 +9091,9 @@ class HtmlRenderer {
8981
9091
  }
8982
9092
  processStyles(styles) {
8983
9093
  const stylesMap = keyBy(styles.filter(x => x.id != null), x => x.id);
9094
+ this.defaultParagraphStyle = styles.find(style => style.isDefault && style.target == "p");
9095
+ this.defaultCharacterStyle = styles.find(style => style.isDefault && style.target == "span");
9096
+ this.defaultRunStyle = styles.find(style => style.id == null);
8984
9097
  for (const style of styles.filter(x => x.basedOn)) {
8985
9098
  var baseStyle = stylesMap[style.basedOn];
8986
9099
  if (baseStyle) {
@@ -9680,14 +9793,20 @@ class HtmlRenderer {
9680
9793
  result.push({ paragraph: currentParagraph, breakAfter: false });
9681
9794
  }
9682
9795
  const last = result[result.length - 1]?.paragraph;
9796
+ const siblings = paragraph.parent?.children?.filter(child => ![DomType.BookmarkStart, DomType.BookmarkEnd].includes(child.type));
9683
9797
  for (const item of result) {
9684
9798
  item.paragraph.sectionProps = item.paragraph === last ? paragraph.sectionProps : null;
9799
+ item.paragraph.props = { ...item.paragraph.props,
9800
+ spacingFirstInFlow: siblings?.[0] === paragraph && item === result[0],
9801
+ spacingLastInFlow: siblings?.[siblings.length - 1] === paragraph && item.paragraph === last };
9685
9802
  }
9686
- if (paragraph.props?.anchorId && result.length > 1) {
9687
- const owner = result.find(part => this.extractText(part.paragraph).trim()) ?? result[0];
9803
+ if (result.length > 1) {
9804
+ const owner = result.find(part => this.hasPageModelContent(part.paragraph)) ?? result[0];
9688
9805
  for (const part of result) {
9689
- if (part !== owner)
9690
- part.paragraph.props = { ...part.paragraph.props, anchorId: undefined };
9806
+ if (part !== owner) {
9807
+ part.paragraph.props = { ...part.paragraph.props, anchorId: undefined,
9808
+ pageBreakContinuation: true, pageBreakEmpty: !this.hasPageModelContent(part.paragraph) };
9809
+ }
9691
9810
  }
9692
9811
  }
9693
9812
  return result;
@@ -9698,6 +9817,73 @@ class HtmlRenderer {
9698
9817
  styleValue(style, target, name) {
9699
9818
  return this.styleValuesForTarget(style, target)?.[name];
9700
9819
  }
9820
+ styleValueLevels(style, target) {
9821
+ const levels = [];
9822
+ const seen = new Set();
9823
+ while (style && !seen.has(style)) {
9824
+ seen.add(style);
9825
+ levels.push(this.styleValuesForTarget(style, target));
9826
+ style = this.findStyle(style.basedOn);
9827
+ }
9828
+ return levels;
9829
+ }
9830
+ effectiveParagraphNumbering(elem, style) {
9831
+ let numbering = elem?.numbering;
9832
+ let current = elem?.styleName ? style : this.defaultParagraphStyle;
9833
+ const seen = new Set();
9834
+ while (!numbering && current?.target == "p" && !seen.has(current)) {
9835
+ seen.add(current);
9836
+ numbering = current.paragraphProps?.numbering;
9837
+ current = this.findStyle(current.basedOn);
9838
+ }
9839
+ return numbering && !/^0+$/.test(String(numbering.id ?? "").trim()) ? numbering : null;
9840
+ }
9841
+ applyParagraphAutoSpacing(elem, style, result) {
9842
+ const paragraphStyle = elem.styleName ? style : this.defaultParagraphStyle;
9843
+ const numbering = this.effectiveParagraphNumbering(elem, style);
9844
+ const numberingStyle = numbering && this.document?.numberingPart?.domNumberings
9845
+ ?.find(num => num.id == numbering.id && num.level == numbering.level)?.pStyle;
9846
+ const levels = [elem.cssStyle, ...this.styleValueLevels(paragraphStyle, "p"), numberingStyle,
9847
+ this.styleValuesForTarget(this.defaultRunStyle, "p")];
9848
+ const fixed = this.document?.settingsPart?.settings?.doNotUseHTMLParagraphAutoSpacing;
9849
+ const state = effectiveParagraphSpacing(levels, fixed, elem.styleName ?? paragraphStyle?.id ?? "");
9850
+ const siblings = elem.parent?.children?.filter(child => ![DomType.BookmarkStart, DomType.BookmarkEnd].includes(child.type));
9851
+ const first = elem.props?.spacingFirstInFlow ?? siblings?.[0] === elem;
9852
+ const last = elem.props?.spacingLastInFlow ?? siblings?.[siblings.length - 1] === elem;
9853
+ if (state.beforeAuto && first && [DomType.Document, DomType.Cell].includes(elem.parent?.type))
9854
+ state.before = "0pt";
9855
+ if (state.afterAuto && last && elem.parent?.type === DomType.Cell)
9856
+ state.after = "0pt";
9857
+ if (state.beforeDeclared)
9858
+ this.setCssStyle(result, "margin-top", state.before);
9859
+ if (state.afterDeclared)
9860
+ this.setCssStyle(result, "margin-bottom", state.after);
9861
+ this.paragraphSpacingStates.set(result, state);
9862
+ }
9863
+ applyFlowParagraphSpacing(nodes) {
9864
+ let previous = null;
9865
+ const fixed = this.document?.settingsPart?.settings?.doNotUseHTMLParagraphAutoSpacing;
9866
+ for (const node of nodes) {
9867
+ const state = typeof node === "object" && node && this.paragraphSpacingStates.get(node);
9868
+ if (!state) {
9869
+ const element = node;
9870
+ if (element?.nodeType === 3 && !element.textContent?.trim())
9871
+ continue;
9872
+ if (/^(a|span)$/i.test(element?.tagName ?? "") && !element.textContent && element.id)
9873
+ continue;
9874
+ previous = null;
9875
+ continue;
9876
+ }
9877
+ if (previous && (previous.state.afterDeclared || state.beforeDeclared)) {
9878
+ const gap = paragraphSpacingGap(previous.state, state, fixed);
9879
+ if (gap != null) {
9880
+ this.setCssStyle(previous.node, "margin-bottom", "0pt");
9881
+ this.setCssStyle(node, "margin-top", gap);
9882
+ }
9883
+ }
9884
+ previous = { node: node, state };
9885
+ }
9886
+ }
9701
9887
  effectiveParagraphCssValue(elem, style, name) {
9702
9888
  return elem.cssStyle?.[name] ?? this.styleValue(style, "p", name);
9703
9889
  }
@@ -9724,6 +9910,46 @@ class HtmlRenderer {
9724
9910
  this.setCssStyle(result, "--docx-latin-font-family", latin);
9725
9911
  this.setCssStyle(result, "font-family", `var(--docx-latin-font-family), ${family}`);
9726
9912
  }
9913
+ applyRunFontSlots(elem, style, result) {
9914
+ const paragraph = elem.type == DomType.Paragraph ? elem : this.currentParagraph;
9915
+ const paragraphStyle = this.findStyle(paragraph?.styleName) ?? this.defaultParagraphStyle;
9916
+ const levels = [elem.cssStyle, ...this.styleValueLevels(style, "span"),
9917
+ paragraph?.cssStyle, ...this.styleValueLevels(paragraphStyle, "span"),
9918
+ this.styleValuesForTarget(this.defaultCharacterStyle, "span"),
9919
+ this.styleValuesForTarget(this.defaultRunStyle, "span")];
9920
+ const value = (key) => levels.find(level => level?.[key] != null)?.[key];
9921
+ const language = (key) => value(key) ?? value("$lang");
9922
+ const themedFont = (font, language) => {
9923
+ const match = /^var\((--docx-(?:major|minor)(?:EastAsia|Bidi|Cs)-font)(?:-[A-Za-z]{4}, var\(\1\))?\)$/.exec(font ?? "");
9924
+ if (!match)
9925
+ return font;
9926
+ const script = themeScriptForLanguage(language);
9927
+ const base = `var(${match[1]}-fallback)`;
9928
+ return script ? `var(${match[1]}-${script}, ${base})` : base;
9929
+ };
9930
+ const text = elem.type == DomType.Run ? (elem.children ?? [])
9931
+ .filter(child => child.type == DomType.Text || child.type == DomType.DeletedText)
9932
+ .map(child => child.text).join("") : "";
9933
+ const forceComplex = value("--docx-complex-script");
9934
+ const complex = forceComplex == "true" || value("--docx-rtl-run") == "true"
9935
+ || (forceComplex != "false" && ((legacyComplexScriptCharacters.test(text)
9936
+ && !/[\p{Script=Latin}\p{Script=Cyrillic}\p{Script=Han}]/u.test(text))
9937
+ || isAdditionalComplexScriptRun(text)));
9938
+ const highAnsi = /[\p{Script=Cyrillic}\p{Script=Greek}]/u.test(text);
9939
+ const slots = complex ? ["complex", "ascii", "hansi", "eastasia"]
9940
+ : highAnsi ? ["hansi", "ascii", "eastasia", "complex"] : ["ascii", "hansi", "eastasia", "complex"];
9941
+ const fonts = slots.map(slot => {
9942
+ const font = value(`--docx-font-${slot}`);
9943
+ return slot == "eastasia" ? themedFont(font, language("$lang-eastAsia"))
9944
+ : slot == "complex" ? themedFont(font, language("$lang-bidi")) : font;
9945
+ }).filter(Boolean);
9946
+ if (fonts.length)
9947
+ this.setCssStyle(result, "font-family", [...new Set(fonts)].join(', '));
9948
+ if (complex && value("--docx-complex-font-size")) {
9949
+ this.setCssStyle(result, "font-size", value("--docx-complex-font-size"));
9950
+ this.setCssStyle(result, "min-height", value("--docx-complex-font-size"));
9951
+ }
9952
+ }
9727
9953
  isInsideTableCell(elem) {
9728
9954
  for (let p = elem.parent; p; p = p.parent) {
9729
9955
  if (p.type == DomType.Cell)
@@ -9731,13 +9957,32 @@ class HtmlRenderer {
9731
9957
  }
9732
9958
  return false;
9733
9959
  }
9960
+ paragraphSnapToGrid(elem, style) {
9961
+ const key = "--docx-snap-to-grid";
9962
+ if (elem.cssStyle?.[key] != null)
9963
+ return elem.cssStyle[key];
9964
+ let current = elem.styleName ? style : this.defaultParagraphStyle;
9965
+ const numbering = this.effectiveParagraphNumbering(elem, style);
9966
+ const seen = new Set();
9967
+ while (current?.target == "p" && !seen.has(current)) {
9968
+ seen.add(current);
9969
+ const value = this.styleValue(current, "p", key);
9970
+ if (value != null)
9971
+ return value;
9972
+ current = this.findStyle(current.basedOn);
9973
+ }
9974
+ const numberingStyle = numbering && this.document?.numberingPart?.domNumberings
9975
+ ?.find(num => num.id == numbering.id && num.level == numbering.level)?.pStyle;
9976
+ return numberingStyle?.[key] ?? this.styleValue(this.defaultRunStyle, "p", key);
9977
+ }
9734
9978
  paragraphUsesDocumentGrid(elem, style) {
9735
- const linePitch = this.currentSectionProps?.docGrid?.linePitch;
9736
- if (!linePitch)
9979
+ const grid = this.currentSectionProps?.docGrid;
9980
+ const linePitch = grid?.linePitch;
9981
+ if (!linePitch || !grid.type || grid.type === "default")
9737
9982
  return false;
9738
9983
  if (this.isInsideTableCell(elem) && !this.document.settingsPart?.settings?.adjustLineHeightInTable)
9739
9984
  return false;
9740
- const snapToGrid = this.effectiveParagraphCssValue(elem, style, "--docx-snap-to-grid");
9985
+ const snapToGrid = this.paragraphSnapToGrid(elem, style);
9741
9986
  return snapToGrid == null || !/^(0|false|off)$/i.test(snapToGrid);
9742
9987
  }
9743
9988
  setCssStyle(element, name, value) {
@@ -9757,17 +10002,27 @@ class HtmlRenderer {
9757
10002
  const linePitch = this.currentSectionProps.docGrid.linePitch;
9758
10003
  const lineHeight = this.effectiveParagraphCssValue(elem, style, "line-height");
9759
10004
  const lineSpacing = elem.lineSpacing ?? style?.paragraphProps?.lineSpacing;
10005
+ const exact = lineSpacing?.lineRule == "exact" || lineSpacing?.lineRule == "exactly";
10006
+ if (!exact && !this.compatibleTextBoxSpacing && result.dataset
10007
+ && ["lines", "linesAndChars"].includes(this.currentSectionProps.docGrid.type)) {
10008
+ const numeric = /^\d+(?:\.\d+)?$/.test(lineHeight ?? "") ? Number(lineHeight) : 1;
10009
+ if (numeric >= 1) {
10010
+ result.dataset.docxParagraphGridPitch = linePitch;
10011
+ result.dataset.docxParagraphGridMultiple = `${numeric}`;
10012
+ result.dataset.docxParagraphGridAtLeast = `${lineSpacing?.lineRule == "atLeast"}`;
10013
+ }
10014
+ }
9760
10015
  if (lineHeight) {
9761
- if (lineSpacing?.lineRule == "exact" || lineSpacing?.lineRule == "exactly")
10016
+ if (exact)
9762
10017
  return;
9763
- const comparableLineHeight = /^-?\d+(?:\.\d+)?$/.test(lineHeight)
9764
- ? `calc(${lineHeight} * 1em)`
9765
- : lineHeight;
10018
+ const comparableLineHeight = gridAutomaticLineHeight(lineHeight, linePitch);
9766
10019
  this.preserveGridInlineMetrics(result);
9767
10020
  this.setCssStyle(result, "line-height", `max(${comparableLineHeight}, ${linePitch})`);
9768
10021
  this.applyDocumentGridMinimumHeight(elem, style, result, linePitch);
9769
10022
  return;
9770
10023
  }
10024
+ this.preserveGridInlineMetrics(result);
10025
+ this.setCssStyle(result, "line-height", linePitch);
9771
10026
  this.applyDocumentGridMinimumHeight(elem, style, result, linePitch);
9772
10027
  }
9773
10028
  preserveGridInlineMetrics(result) {
@@ -9949,6 +10204,11 @@ class HtmlRenderer {
9949
10204
  movedAny = true;
9950
10205
  continue;
9951
10206
  }
10207
+ const tail = article.lastElementChild;
10208
+ if (this.canRetainTablePrefix(tail, page) && this.splitOverflowBlock(tail, page, nextArticle)) {
10209
+ movedAny = true;
10210
+ continue;
10211
+ }
9952
10212
  let chunk = this.pickPaginationChunk(article);
9953
10213
  if (chunk.length == 0)
9954
10214
  break;
@@ -10828,21 +11088,30 @@ class HtmlRenderer {
10828
11088
  const rows = this.tableContentRows(table);
10829
11089
  if (rows.length <= 1)
10830
11090
  return false;
11091
+ const repeatHeaders = rows.filter(r => r.dataset.docxRepeatHeader == "true");
11092
+ if (repeatHeaders.length && !this.fitsTableRowPrefix(rows, page))
11093
+ return false;
10831
11094
  const clone = this.cloneBlockShell(table);
10832
11095
  clone.dataset.docxContinued = "true";
10833
11096
  for (const child of Array.from(table.children)) {
10834
11097
  if (child.tagName?.toLowerCase() == "colgroup")
10835
11098
  clone.appendChild(child.cloneNode(true));
10836
11099
  }
10837
- for (const header of rows.filter(r => r.dataset.docxRepeatHeader == "true")) {
11100
+ for (const [index, header] of repeatHeaders.entries()) {
10838
11101
  const repeated = header.cloneNode(true);
10839
11102
  repeated.dataset.docxRepeatedHeader = "true";
11103
+ for (const cell of Array.from(repeated.cells)) {
11104
+ const headerRowsRemaining = repeatHeaders.length - index;
11105
+ if (cell.rowSpan === 0 || cell.rowSpan > headerRowsRemaining)
11106
+ cell.rowSpan = headerRowsRemaining;
11107
+ }
10840
11108
  clone.appendChild(repeated);
10841
11109
  }
10842
11110
  nextArticle.prepend(clone);
10843
11111
  let movedAny = false;
10844
11112
  let guard = 0;
10845
- while (this.isPageOverflowing(page) && this.tableContentRows(table).length > 1 && guard++ < 500) {
11113
+ const minimumSourceRows = repeatHeaders.length + 1;
11114
+ while (this.isPageOverflowing(page) && this.tableContentRows(table).length > minimumSourceRows && guard++ < 500) {
10846
11115
  const currentRows = this.tableContentRows(table).filter(r => r.dataset.docxRepeatedHeader != "true");
10847
11116
  const last = currentRows[currentRows.length - 1];
10848
11117
  if (!last)
@@ -10854,8 +11123,58 @@ class HtmlRenderer {
10854
11123
  clone.remove();
10855
11124
  return false;
10856
11125
  }
11126
+ const sourceRowCount = this.tableContentRows(table).length;
11127
+ const firstContinuationRow = this.firstMovedTableRow(clone);
11128
+ for (let rowIndex = 0; rowIndex < sourceRowCount; rowIndex++) {
11129
+ let column = 0;
11130
+ for (const cell of Array.from(rows[rowIndex].cells)) {
11131
+ const nextColumn = column + cell.colSpan;
11132
+ const remainingSpan = rowIndex + cell.rowSpan - sourceRowCount;
11133
+ if (remainingSpan > 0) {
11134
+ const continuation = this.cloneBlockShell(cell);
11135
+ continuation.textContent = "";
11136
+ continuation.rowSpan = remainingSpan;
11137
+ continuation.dataset.docxContinued = "true";
11138
+ let targetColumn = 0;
11139
+ let anchor = null;
11140
+ for (const targetCell of Array.from(firstContinuationRow.cells)) {
11141
+ if (targetColumn >= column) {
11142
+ anchor = targetCell;
11143
+ break;
11144
+ }
11145
+ targetColumn += targetCell.colSpan;
11146
+ }
11147
+ if (anchor && targetColumn === column && anchor.style.display === "none")
11148
+ anchor.replaceWith(continuation);
11149
+ else
11150
+ firstContinuationRow.insertBefore(continuation, anchor);
11151
+ cell.rowSpan = sourceRowCount - rowIndex;
11152
+ }
11153
+ column = nextColumn;
11154
+ }
11155
+ }
10857
11156
  return true;
10858
11157
  }
11158
+ canRetainTablePrefix(block, page) {
11159
+ if (block?.localName !== "table")
11160
+ return false;
11161
+ const style = getComputedStyle(block);
11162
+ if (style.position !== "static" || style.cssFloat !== "none" || block.dataset.docxFloat)
11163
+ return false;
11164
+ return this.fitsTableRowPrefix(this.tableContentRows(block), page);
11165
+ }
11166
+ fitsTableRowPrefix(rows, page) {
11167
+ if (rows.length < 2 || rows.some((row, index) => Array.from(row.cells).some(cell => cell.rowSpan < 1 || index + cell.rowSpan > rows.length)))
11168
+ return false;
11169
+ const firstBody = rows.findIndex(row => row.dataset.docxRepeatHeader != "true");
11170
+ if (firstBody < 0 || rows.slice(firstBody + 1).some(row => row.dataset.docxRepeatHeader == "true"))
11171
+ return false;
11172
+ const bottom = this.getPageBodyBottom(page) + (this.options.paginationTolerance ?? 2);
11173
+ return rows.slice(0, firstBody + 1).every(row => {
11174
+ const rect = row.getBoundingClientRect();
11175
+ return rect.height > 0 && rect.bottom <= bottom;
11176
+ });
11177
+ }
10859
11178
  cloneBlockShell(element) {
10860
11179
  const clone = element.cloneNode(false);
10861
11180
  clone.removeAttribute("id");
@@ -11136,7 +11455,7 @@ class HtmlRenderer {
11136
11455
  wrapperStyle = `@media not print { ${wrapperStyle} }`;
11137
11456
  }
11138
11457
  var styleText = `${wrapperStyle}
11139
- .${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; }
11458
+ .${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; }
11140
11459
  section.${c} { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: visible; isolation: isolate; }
11141
11460
  section.${c}>header, section.${c}>footer { flex-shrink: 0; }
11142
11461
  section.${c}>[data-docx-note-list] { flex-shrink: 0; }
@@ -11527,6 +11846,7 @@ section.${c}>footer { z-index: 1; }
11527
11846
  }
11528
11847
  const children = frameParagraphs
11529
11848
  .flatMap(item => asArray(this.renderElement(item)).filter(node => node != null));
11849
+ this.applyFlowParagraphSpacing(children);
11530
11850
  const frame = this.h({
11531
11851
  tagName: "div",
11532
11852
  className: `${this.className}-paragraph-frame`,
@@ -11546,6 +11866,7 @@ section.${c}>footer { z-index: 1; }
11546
11866
  }
11547
11867
  result.push(...asArray(this.renderElement(elems[i])).filter(e => e != null));
11548
11868
  }
11869
+ this.applyFlowParagraphSpacing(result);
11549
11870
  if (into)
11550
11871
  result.forEach(c => into.appendChild(isString(c) ? document.createTextNode(c) : c));
11551
11872
  return result;
@@ -11745,7 +12066,7 @@ section.${c}>footer { z-index: 1; }
11745
12066
  const style = this.findStyle(this.currentParagraph?.styleName);
11746
12067
  const isTocParagraph = this.isTocParagraphStyle(this.currentParagraph?.styleName, style);
11747
12068
  const isNumberedTocLeader = !!trailingLeader
11748
- && !!(this.currentParagraph?.numbering ?? style?.paragraphProps?.numbering)
12069
+ && !!this.effectiveParagraphNumbering(this.currentParagraph, style)
11749
12070
  && isTocParagraph;
11750
12071
  if (!trailingLeader)
11751
12072
  return stop;
@@ -11789,18 +12110,22 @@ section.${c}>footer { z-index: 1; }
11789
12110
  children = [flow];
11790
12111
  }
11791
12112
  var result = this.toHTML(elem, ns.html, "p", this.wrapTabLeaderChildren(children, true));
12113
+ this.applyParagraphAutoSpacing(elem, style, result);
11792
12114
  this.applyTextBoxFontInheritance(elem, style, result);
12115
+ this.applyRunFontSlots(elem, style, result);
11793
12116
  if (this.options.exposeDisplayTargets && elem.displayAddress) {
11794
12117
  const part = this.currentPart ?? this.document.documentPart;
11795
12118
  result.setAttribute("data-office-target", `${part.path}#${elem.displayAddress}`);
11796
12119
  }
11797
- const snapToGrid = this.effectiveParagraphCssValue(elem, style, "--docx-snap-to-grid");
12120
+ const snapToGrid = this.paragraphSnapToGrid(elem, style);
11798
12121
  if (/^(0|false|off)$/i.test(snapToGrid ?? ""))
11799
12122
  result.style.letterSpacing = "normal";
11800
12123
  this.currentParagraph = previousParagraph;
11801
12124
  this.currentParagraphTabIndex = previousParagraphTabIndex;
11802
12125
  this.currentParagraphTabCount = previousParagraphTabCount;
11803
- const numbering = elem.numbering ?? style?.paragraphProps?.numbering;
12126
+ const numbering = elem.props?.pageBreakContinuation ? null : this.effectiveParagraphNumbering(elem, style);
12127
+ if (elem.props?.pageBreakEmpty)
12128
+ result.style.display = "none";
11804
12129
  if (numbering) {
11805
12130
  result.classList.add(this.numberingClass(numbering.id, numbering.level));
11806
12131
  }
@@ -11856,7 +12181,7 @@ section.${c}>footer { z-index: 1; }
11856
12181
  return result;
11857
12182
  }
11858
12183
  uniformParagraphTextScale(paragraph, style) {
11859
- if (paragraph.numbering || style?.paragraphProps?.numbering || paragraph.frame
12184
+ if (this.effectiveParagraphNumbering(paragraph, style) || paragraph.frame
11860
12185
  || this.effectiveParagraphCssValue(paragraph, style, "writing-mode"))
11861
12186
  return null;
11862
12187
  const key = "--docx-text-scale";
@@ -12011,6 +12336,68 @@ section.${c}>footer { z-index: 1; }
12011
12336
  probe.remove();
12012
12337
  }
12013
12338
  }
12339
+ refreshParagraphLineGrid(root) {
12340
+ const view = root.ownerDocument?.defaultView;
12341
+ const paragraphs = Array.from(root.querySelectorAll("[data-docx-paragraph-grid-pitch]"))
12342
+ .filter(paragraph => this.ownsLayoutElement(paragraph));
12343
+ if (!view || !paragraphs.length)
12344
+ return;
12345
+ const probe = root.ownerDocument.createElement("span");
12346
+ Object.assign(probe.style, { position: "absolute", visibility: "hidden", pointerEvents: "none",
12347
+ display: "inline-block", whiteSpace: "pre", width: "max-content", margin: "0", padding: "0", border: "0" });
12348
+ probe.setAttribute("aria-hidden", "true");
12349
+ probe.textContent = "Mg";
12350
+ const scope = root.getRootNode();
12351
+ (scope.nodeType == 11 && "host" in scope ? scope : root.ownerDocument.body).appendChild(probe);
12352
+ const cache = new Map();
12353
+ const natural = (style) => {
12354
+ const font = { fontFamily: style.fontFamily, fontSize: style.fontSize, fontWeight: style.fontWeight,
12355
+ fontStyle: style.fontStyle, fontStretch: style.fontStretch, lineHeight: "normal", height: "auto" };
12356
+ const key = JSON.stringify(font);
12357
+ if (!cache.has(key)) {
12358
+ Object.assign(probe.style, font);
12359
+ cache.set(key, probe.getBoundingClientRect().height);
12360
+ }
12361
+ return cache.get(key);
12362
+ };
12363
+ try {
12364
+ for (const paragraph of paragraphs) {
12365
+ const style = view.getComputedStyle(paragraph), size = parseFloat(style.fontSize);
12366
+ probe.style.height = paragraph.dataset.docxParagraphGridPitch;
12367
+ const pitch = parseFloat(view.getComputedStyle(probe).height);
12368
+ const multiplier = Number(paragraph.dataset.docxParagraphGridMultiple);
12369
+ let height = gridFontLineHeight(natural(style), pitch, multiplier);
12370
+ if (height == null)
12371
+ continue;
12372
+ if (paragraph.dataset.docxParagraphGridAtLeast === "true")
12373
+ height = Math.max(height, parseFloat(style.lineHeight) || 0);
12374
+ paragraph.style.lineHeight = `${height}px`;
12375
+ const visit = (parent, script = false) => {
12376
+ for (const child of Array.from(parent.children)) {
12377
+ if (child.namespaceURI !== ns.html || !/^(span|a|sub|sup|b|i|u|s|strike|strong|em)$/.test(child.localName))
12378
+ continue;
12379
+ const own = child.dataset.docxGridOwnedHeight === "true";
12380
+ if ((!own && child.style.lineHeight && child.style.lineHeight !== "normal")
12381
+ || (child.style.display && child.style.display !== "inline" && !child.dataset.docxTextScale)
12382
+ || /^(absolute|fixed)$/.test(child.style.position) || (child.style.cssFloat && child.style.cssFloat !== "none"))
12383
+ continue;
12384
+ const childStyle = view.getComputedStyle(child);
12385
+ const raised = script || /^(super|sub)$/.test(childStyle.verticalAlign);
12386
+ const breakOnly = !child.textContent && !!child.querySelector("br") && !child.querySelector("img,svg,math");
12387
+ const childHeight = breakOnly || (raised && parseFloat(childStyle.fontSize) <= size) ? 0
12388
+ : Math.max(height, gridFontLineHeight(natural(childStyle), pitch) ?? height);
12389
+ child.style.lineHeight = `${childHeight}px`;
12390
+ child.dataset.docxGridOwnedHeight = "true";
12391
+ visit(child, raised);
12392
+ }
12393
+ };
12394
+ visit(paragraph);
12395
+ }
12396
+ }
12397
+ finally {
12398
+ probe.remove();
12399
+ }
12400
+ }
12014
12401
  async prepareLayout(root, generation = getLayoutGeneration(root)) {
12015
12402
  if (!root.isConnected || !generation.isCurrent())
12016
12403
  return;
@@ -12031,6 +12418,7 @@ section.${c}>footer { z-index: 1; }
12031
12418
  (owner ?? root).appendChild(this.commentLayer.root);
12032
12419
  }
12033
12420
  }
12421
+ this.refreshParagraphLineGrid(root);
12034
12422
  this.refreshTextBoxLineGrid(root);
12035
12423
  this.refreshTabStops(root);
12036
12424
  this.refreshAnchors(root);
@@ -14174,6 +14562,7 @@ section.${c}>footer { z-index: 1; }
14174
14562
  const result = this.toHTML(elem, ns.html, "span", children);
14175
14563
  const style = this.findStyle(elem.styleName);
14176
14564
  this.applyTextBoxFontInheritance(elem, style, result);
14565
+ this.applyRunFontSlots(elem, style, result);
14177
14566
  const snapToGrid = elem.cssStyle?.["--docx-snap-to-grid"] ?? this.styleValue(style, "span", "--docx-snap-to-grid");
14178
14567
  if (/^(0|false|off)$/i.test(snapToGrid ?? ""))
14179
14568
  result.style.letterSpacing = "normal";