@file-viewer/docx 0.3.36 → 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
  }
@@ -3733,6 +3735,8 @@ function parseVmlElement(elem, parser) {
3733
3735
  result.tagName = "g";
3734
3736
  result.isGroup = true;
3735
3737
  break;
3738
+ case "roundrect":
3739
+ result.roundRectArc = 0.2;
3736
3740
  case "rect":
3737
3741
  result.tagName = "rect";
3738
3742
  Object.assign(result.attrs, { width: '100%', height: '100%' });
@@ -3767,6 +3771,10 @@ function parseVmlElement(elem, parser) {
3767
3771
  case "coordsize":
3768
3772
  result.coordSize = parseNumericPoint(at.value);
3769
3773
  break;
3774
+ case "arcsize":
3775
+ if (result.roundRectArc != null)
3776
+ result.roundRectArc = parseRoundRectArc(at.value);
3777
+ break;
3770
3778
  case "inset":
3771
3779
  if (result.textInset) {
3772
3780
  const values = at.value.trim().split(/\s*,\s*|\s+/);
@@ -3864,6 +3872,13 @@ function parseVmlElement(elem, parser) {
3864
3872
  }
3865
3873
  return result;
3866
3874
  }
3875
+ function parseRoundRectArc(value) {
3876
+ const source = value.trim();
3877
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:%|f)?$/i.test(source))
3878
+ return 0.2;
3879
+ const fraction = parseFloat(source) / (/%$/.test(source) ? 100 : /f$/i.test(source) ? 65536 : 1);
3880
+ return Number.isFinite(fraction) ? Math.max(0, Math.min(1, fraction)) : 0.2;
3881
+ }
3867
3882
  function vmlImageAttrs(el) {
3868
3883
  const cropLeft = parseVmlFraction(globalXmlParser.attr(el, "cropleft"));
3869
3884
  const cropTop = parseVmlFraction(globalXmlParser.attr(el, "croptop"));
@@ -4023,6 +4038,44 @@ function createParagraphAddressResolver() {
4023
4038
  };
4024
4039
  }
4025
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
+
4026
4079
  var autos = {
4027
4080
  shd: "inherit",
4028
4081
  color: "var(--docx-auto-color, black)",
@@ -5421,6 +5474,9 @@ class DocumentParser {
5421
5474
  const prstGeom = globalXmlParser.element(spPr, "prstGeom");
5422
5475
  const fillStyle = this.parseDmlFillStyle(spPr);
5423
5476
  const lineStyle = this.parseDmlLineStyle(globalXmlParser.element(spPr, "ln"));
5477
+ const roundedRadius = !geom ? this.parseDmlRoundRectRadius(spPr, bounds.width, bounds.height, transform) : null;
5478
+ if (roundedRadius != null)
5479
+ cssStyle["border-radius"] = roundedRadius;
5424
5480
  if (geom) {
5425
5481
  const path = this.parseDmlCustomGeometry(geom);
5426
5482
  return {
@@ -5458,6 +5514,23 @@ class DocumentParser {
5458
5514
  alt: cNvPr ? globalXmlParser.attr(cNvPr, "descr") : null
5459
5515
  };
5460
5516
  }
5517
+ parseDmlRoundRectRadius(spPr, width, height, transform) {
5518
+ const preset = globalXmlParser.element(spPr, "prstGeom");
5519
+ if (!preset || globalXmlParser.attr(preset, "prst") != "roundRect")
5520
+ return null;
5521
+ const guides = globalXmlParser.element(preset, "avLst");
5522
+ const adjustment = (guides ? globalXmlParser.elements(guides, "gd") : [])
5523
+ .find(guide => globalXmlParser.attr(guide, "name") == "adj");
5524
+ const formula = adjustment ? globalXmlParser.attr(adjustment, "fmla") : "";
5525
+ const value = /^val\s+[+-]?(?:\d+(?:\.\d*)?|\.\d+)\s*$/.test(formula ?? "")
5526
+ ? Number(formula.trim().split(/\s+/)[1]) : 16667;
5527
+ const fraction = Math.max(0, Math.min(50000, value)) / 100000;
5528
+ const scaleX = Math.abs(transform?.scaleX ?? 1);
5529
+ const scaleY = Math.abs(transform?.scaleY ?? 1);
5530
+ const radius = Number.isFinite(scaleX) && Number.isFinite(scaleY) && scaleX > 0 && scaleY > 0
5531
+ ? Math.min(width / scaleX, height / scaleY) * fraction : 0;
5532
+ return `${this.pt(Number.isFinite(radius * scaleX) ? radius * scaleX : 0)} / ${this.pt(Number.isFinite(radius * scaleY) ? radius * scaleY : 0)}`;
5533
+ }
5461
5534
  parseDmlShapeBounds(spPr, transform) {
5462
5535
  const xfrm = globalXmlParser.element(spPr, "xfrm");
5463
5536
  const off = xfrm ? globalXmlParser.element(xfrm, "off") : null;
@@ -5594,6 +5667,7 @@ class DocumentParser {
5594
5667
  return {
5595
5668
  dmlTextBox: true,
5596
5669
  textInsets: textInsetStyle,
5670
+ textCompatibleLineSpacing: bodyPr ? globalXmlParser.boolAttr(bodyPr, "compatLnSpc", false) : false,
5597
5671
  textVerticalAlign: this.dmlVerticalAlign(bodyPr)
5598
5672
  };
5599
5673
  }
@@ -5693,6 +5767,10 @@ class DocumentParser {
5693
5767
  }
5694
5768
  parseDmlShapeProperties(elem, style) {
5695
5769
  const xfrm = globalXmlParser.element(elem, "xfrm");
5770
+ const bounds = this.parseDmlShapeBounds(elem);
5771
+ const roundedRadius = this.parseDmlRoundRectRadius(elem, bounds.width, bounds.height);
5772
+ if (roundedRadius != null)
5773
+ style["border-radius"] = roundedRadius;
5696
5774
  if (xfrm) {
5697
5775
  for (const n of globalXmlParser.elements(xfrm)) {
5698
5776
  switch (n.localName) {
@@ -6137,6 +6215,10 @@ class DocumentParser {
6137
6215
  case "textAlignment":
6138
6216
  style["vertical-align"] = values.valueOfTextAlignment(c);
6139
6217
  break;
6218
+ case "autoSpaceDE":
6219
+ case "autoSpaceDN":
6220
+ style[c.localName == "autoSpaceDE" ? "--docx-auto-space-de" : "--docx-auto-space-dn"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6221
+ break;
6140
6222
  case "color":
6141
6223
  style["color"] = xmlUtil.colorAttr(c, "val", null, autos.color);
6142
6224
  break;
@@ -6144,8 +6226,10 @@ class DocumentParser {
6144
6226
  style["font-size"] = style["min-height"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize);
6145
6227
  break;
6146
6228
  case "szCs":
6147
- style["font-size"] ?? (style["font-size"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize));
6148
- 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)}`;
6149
6233
  break;
6150
6234
  case "shd":
6151
6235
  style["background-color"] = xmlUtil.colorAttr(c, "fill", null, autos.shd);
@@ -6209,6 +6293,7 @@ class DocumentParser {
6209
6293
  style["font-variant"] = globalXmlParser.boolAttr(c, "val", true) ? "small-caps" : "none";
6210
6294
  break;
6211
6295
  case "rtl":
6296
+ style["--docx-rtl-run"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6212
6297
  if (globalXmlParser.boolAttr(c, "val", true)) {
6213
6298
  style["direction"] = "rtl";
6214
6299
  style["unicode-bidi"] = "embed";
@@ -6341,9 +6426,11 @@ class DocumentParser {
6341
6426
  if (globalXmlParser.boolAttr(c, "val", true))
6342
6427
  style["display"] = "none";
6343
6428
  break;
6429
+ case "contextualSpacing":
6430
+ style["--docx-contextual-spacing"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6431
+ break;
6344
6432
  case "tabs":
6345
6433
  case "outlineLvl":
6346
- case "contextualSpacing":
6347
6434
  case "tblStyleColBandSize":
6348
6435
  case "tblStyleRowBandSize":
6349
6436
  case "suppressLineNumbers":
@@ -6435,6 +6522,7 @@ class DocumentParser {
6435
6522
  fonts.push(...[asciiTheme, hAnsiTheme]
6436
6523
  .filter(x => x)
6437
6524
  .map(x => x.startsWith("var(") ? x : encloseFontFamily(x)));
6525
+ const latinFonts = fonts.slice();
6438
6526
  if (eastAsia) {
6439
6527
  fonts.push(...eastAsianFontFamilyStack(eastAsia, eastAsiaScript));
6440
6528
  }
@@ -6448,6 +6536,21 @@ class DocumentParser {
6448
6536
  if (fonts.length > 0) {
6449
6537
  const currentFonts = (style["font-family"] ?? "").split(',').map(x => x.trim()).filter(x => x);
6450
6538
  style["font-family"] = [...new Set([...currentFonts, ...fonts])].join(', ');
6539
+ if (latinFonts.length)
6540
+ style["--docx-latin-font-family"] = [...new Set(latinFonts)].join(', ');
6541
+ style["--docx-partial-eastasia-font"] = !latinFonts.length && (eastAsia || eastAsiaTheme) && !cs && !csTheme ? "true" : "false";
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;
6451
6554
  }
6452
6555
  }
6453
6556
  scriptThemeFontValue(value, language) {
@@ -6493,18 +6596,28 @@ class DocumentParser {
6493
6596
  var afterAuto = globalXmlParser.boolAttr(node, "afterAutospacing", false);
6494
6597
  var line = globalXmlParser.intAttr(node, "line", null);
6495
6598
  var lineRule = globalXmlParser.attr(node, "lineRule");
6496
- if (beforeAuto)
6497
- style["margin-top"] = "auto";
6498
- else if (Number.isFinite(beforeLines) && beforeLines >= 0)
6499
- style["margin-top"] = `${(beforeLines / 100).toFixed(2)}em`;
6500
- else if (before)
6501
- style["margin-top"] = before;
6502
- if (afterAuto)
6503
- style["margin-bottom"] = "auto";
6504
- else if (Number.isFinite(afterLines) && afterLines >= 0)
6505
- style["margin-bottom"] = `${(afterLines / 100).toFixed(2)}em`;
6506
- else if (after)
6507
- 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
+ }
6508
6621
  if (line !== null) {
6509
6622
  switch (lineRule ?? "auto") {
6510
6623
  case "auto":
@@ -7980,6 +8093,18 @@ function layoutExplicitTabs(root, ownsElement = () => true) {
7980
8093
  return applied;
7981
8094
  }
7982
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
+
7983
8108
  const DEFAULT_DARK_MODE_BASE_L = 21.247;
7984
8109
  const LAB_EPSILON = Math.pow(6 / 29, 3);
7985
8110
  function srgbToLinear(c) {
@@ -8642,6 +8767,22 @@ function normalizeCachedPageBreaks(elements, isHiddenRevision) {
8642
8767
  return elements.map(copy);
8643
8768
  }
8644
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
+ }
8645
8786
  const chartNamespaces = [
8646
8787
  "http://schemas.openxmlformats.org/drawingml/2006/chart",
8647
8788
  "http://purl.oclc.org/ooxml/drawingml/chart"
@@ -8729,6 +8870,8 @@ class HtmlRenderer {
8729
8870
  this.headingIndex = 0;
8730
8871
  this.tasks = [];
8731
8872
  this.postRenderTasks = [];
8873
+ this.compatibleTextBoxSpacing = false;
8874
+ this.paragraphSpacingStates = new WeakMap();
8732
8875
  this.h = h;
8733
8876
  this.darkModeVarNames = new Map();
8734
8877
  this.darkModePrintReset = {};
@@ -8740,6 +8883,9 @@ class HtmlRenderer {
8740
8883
  this.rootSelector = options.inWrapper ? `.${this.className}-wrapper` : ':root';
8741
8884
  this.h = options.h ?? h;
8742
8885
  this.styleMap = null;
8886
+ this.defaultParagraphStyle = null;
8887
+ this.defaultCharacterStyle = null;
8888
+ this.defaultRunStyle = null;
8743
8889
  this.tasks = [];
8744
8890
  this.postRenderTasks = [];
8745
8891
  this.commentLayer = null;
@@ -8834,6 +8980,7 @@ class HtmlRenderer {
8834
8980
  variables['--docx-majorEastAsia-font'] = this.themeFontFamily(fontScheme.majorFont, "eastAsia", languages.eastAsia);
8835
8981
  variables['--docx-majorBidi-font'] = this.themeFontFamily(fontScheme.majorFont, "complexScript", languages.bidi);
8836
8982
  variables['--docx-majorCs-font'] = variables['--docx-majorBidi-font'];
8983
+ this.addThemeFontFallbackVariables(variables, "major", fontScheme.majorFont);
8837
8984
  this.addThemeScriptFontVariables(variables, "major", fontScheme.majorFont);
8838
8985
  }
8839
8986
  if (fontScheme.minorFont) {
@@ -8841,6 +8988,7 @@ class HtmlRenderer {
8841
8988
  variables['--docx-minorEastAsia-font'] = this.themeFontFamily(fontScheme.minorFont, "eastAsia", languages.eastAsia);
8842
8989
  variables['--docx-minorBidi-font'] = this.themeFontFamily(fontScheme.minorFont, "complexScript", languages.bidi);
8843
8990
  variables['--docx-minorCs-font'] = variables['--docx-minorBidi-font'];
8991
+ this.addThemeFontFallbackVariables(variables, "minor", fontScheme.minorFont);
8844
8992
  this.addThemeScriptFontVariables(variables, "minor", fontScheme.minorFont);
8845
8993
  }
8846
8994
  }
@@ -8876,6 +9024,15 @@ class HtmlRenderer {
8876
9024
  result.bidi = values["$lang-bidi"] ?? result.latin;
8877
9025
  return result;
8878
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
+ }
8879
9036
  addThemeScriptFontVariables(variables, size, font) {
8880
9037
  const eastAsianScripts = new Set(["Hans", "Hant", "Jpan", "Hang"]);
8881
9038
  for (const script of Object.keys(font.scriptTypefaces ?? {})) {
@@ -8934,6 +9091,9 @@ class HtmlRenderer {
8934
9091
  }
8935
9092
  processStyles(styles) {
8936
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);
8937
9097
  for (const style of styles.filter(x => x.basedOn)) {
8938
9098
  var baseStyle = stylesMap[style.basedOn];
8939
9099
  if (baseStyle) {
@@ -9633,14 +9793,20 @@ class HtmlRenderer {
9633
9793
  result.push({ paragraph: currentParagraph, breakAfter: false });
9634
9794
  }
9635
9795
  const last = result[result.length - 1]?.paragraph;
9796
+ const siblings = paragraph.parent?.children?.filter(child => ![DomType.BookmarkStart, DomType.BookmarkEnd].includes(child.type));
9636
9797
  for (const item of result) {
9637
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 };
9638
9802
  }
9639
- if (paragraph.props?.anchorId && result.length > 1) {
9640
- 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];
9641
9805
  for (const part of result) {
9642
- if (part !== owner)
9643
- 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
+ }
9644
9810
  }
9645
9811
  }
9646
9812
  return result;
@@ -9651,9 +9817,139 @@ class HtmlRenderer {
9651
9817
  styleValue(style, target, name) {
9652
9818
  return this.styleValuesForTarget(style, target)?.[name];
9653
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
+ }
9654
9887
  effectiveParagraphCssValue(elem, style, name) {
9655
9888
  return elem.cssStyle?.[name] ?? this.styleValue(style, "p", name);
9656
9889
  }
9890
+ textBoxAutospace(elem, style, supports = (value) => typeof CSS == "undefined" || typeof CSS.supports != "function" || CSS.supports("text-autospace", value)) {
9891
+ const enabled = (key) => !/^(0|false|off)$/i.test(this.effectiveParagraphCssValue(elem, style, key) ?? "true");
9892
+ const alpha = enabled("--docx-auto-space-de"), numeric = enabled("--docx-auto-space-dn");
9893
+ const value = alpha && numeric ? "normal" : alpha ? "ideograph-alpha" : numeric ? "ideograph-numeric" : "no-autospace";
9894
+ return supports(value) ? value : "no-autospace";
9895
+ }
9896
+ applyTextBoxFontInheritance(elem, style, result) {
9897
+ if (!this.compatibleTextBoxSpacing)
9898
+ return;
9899
+ const paragraph = elem.type == DomType.Paragraph ? elem : this.currentParagraph;
9900
+ const paragraphStyle = this.findStyle(paragraph?.styleName);
9901
+ const defaults = this.document.stylesPart?.styles?.find(item => item.id == null);
9902
+ const levels = [elem.cssStyle, this.styleValuesForTarget(style, elem.type == DomType.Paragraph ? "p" : "span"),
9903
+ paragraph?.cssStyle, this.styleValuesForTarget(paragraphStyle, "span"), this.styleValuesForTarget(defaults, "span")];
9904
+ const value = (key) => levels.find(level => level?.[key] != null)?.[key];
9905
+ if (value("--docx-partial-eastasia-font") != "true")
9906
+ return;
9907
+ const latin = value("--docx-latin-font-family"), family = value("font-family");
9908
+ if (!latin || !family)
9909
+ return;
9910
+ this.setCssStyle(result, "--docx-latin-font-family", latin);
9911
+ this.setCssStyle(result, "font-family", `var(--docx-latin-font-family), ${family}`);
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
+ }
9657
9953
  isInsideTableCell(elem) {
9658
9954
  for (let p = elem.parent; p; p = p.parent) {
9659
9955
  if (p.type == DomType.Cell)
@@ -9661,13 +9957,32 @@ class HtmlRenderer {
9661
9957
  }
9662
9958
  return false;
9663
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
+ }
9664
9978
  paragraphUsesDocumentGrid(elem, style) {
9665
- const linePitch = this.currentSectionProps?.docGrid?.linePitch;
9666
- if (!linePitch)
9979
+ const grid = this.currentSectionProps?.docGrid;
9980
+ const linePitch = grid?.linePitch;
9981
+ if (!linePitch || !grid.type || grid.type === "default")
9667
9982
  return false;
9668
9983
  if (this.isInsideTableCell(elem) && !this.document.settingsPart?.settings?.adjustLineHeightInTable)
9669
9984
  return false;
9670
- const snapToGrid = this.effectiveParagraphCssValue(elem, style, "--docx-snap-to-grid");
9985
+ const snapToGrid = this.paragraphSnapToGrid(elem, style);
9671
9986
  return snapToGrid == null || !/^(0|false|off)$/i.test(snapToGrid);
9672
9987
  }
9673
9988
  setCssStyle(element, name, value) {
@@ -9687,17 +10002,27 @@ class HtmlRenderer {
9687
10002
  const linePitch = this.currentSectionProps.docGrid.linePitch;
9688
10003
  const lineHeight = this.effectiveParagraphCssValue(elem, style, "line-height");
9689
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
+ }
9690
10015
  if (lineHeight) {
9691
- if (lineSpacing?.lineRule == "exact" || lineSpacing?.lineRule == "exactly")
10016
+ if (exact)
9692
10017
  return;
9693
- const comparableLineHeight = /^-?\d+(?:\.\d+)?$/.test(lineHeight)
9694
- ? `calc(${lineHeight} * 1em)`
9695
- : lineHeight;
10018
+ const comparableLineHeight = gridAutomaticLineHeight(lineHeight, linePitch);
9696
10019
  this.preserveGridInlineMetrics(result);
9697
10020
  this.setCssStyle(result, "line-height", `max(${comparableLineHeight}, ${linePitch})`);
9698
10021
  this.applyDocumentGridMinimumHeight(elem, style, result, linePitch);
9699
10022
  return;
9700
10023
  }
10024
+ this.preserveGridInlineMetrics(result);
10025
+ this.setCssStyle(result, "line-height", linePitch);
9701
10026
  this.applyDocumentGridMinimumHeight(elem, style, result, linePitch);
9702
10027
  }
9703
10028
  preserveGridInlineMetrics(result) {
@@ -9879,6 +10204,11 @@ class HtmlRenderer {
9879
10204
  movedAny = true;
9880
10205
  continue;
9881
10206
  }
10207
+ const tail = article.lastElementChild;
10208
+ if (this.canRetainTablePrefix(tail, page) && this.splitOverflowBlock(tail, page, nextArticle)) {
10209
+ movedAny = true;
10210
+ continue;
10211
+ }
9882
10212
  let chunk = this.pickPaginationChunk(article);
9883
10213
  if (chunk.length == 0)
9884
10214
  break;
@@ -10692,6 +11022,8 @@ class HtmlRenderer {
10692
11022
  splitParagraphBlock(paragraph, page, nextArticle) {
10693
11023
  if (!paragraph.hasChildNodes())
10694
11024
  return false;
11025
+ if (this.fitOversizedInlinePicture(paragraph, page))
11026
+ return false;
10695
11027
  const clone = this.cloneBlockShell(paragraph);
10696
11028
  clone.dataset.docxContinued = "true";
10697
11029
  nextArticle.prepend(clone);
@@ -10714,25 +11046,72 @@ class HtmlRenderer {
10714
11046
  this.rebalanceWidowOrphan(paragraph, clone, page);
10715
11047
  return true;
10716
11048
  }
11049
+ fitOversizedInlinePicture(paragraph, page) {
11050
+ const article = paragraph.parentElement;
11051
+ if (article?.localName !== "article" || article.firstElementChild !== paragraph
11052
+ || page.querySelector(":scope > article > *") !== paragraph
11053
+ || paragraph.textContent?.trim() || paragraph.querySelector("table,math,object,canvas,video,[data-docx-note-reference]"))
11054
+ return false;
11055
+ const drawings = Array.from(paragraph.querySelectorAll("[data-docx-drawing]"));
11056
+ const drawing = drawings[0];
11057
+ if (drawings.length !== 1 || !drawing || drawing.children.length !== 1
11058
+ || paragraph.querySelectorAll("img").length !== 1 || drawing.dataset.docxFloat)
11059
+ return false;
11060
+ const picture = drawing.firstElementChild;
11061
+ if (picture.localName !== "img" && picture.dataset.docxImageCrop !== "true")
11062
+ return false;
11063
+ const view = paragraph.ownerDocument.defaultView;
11064
+ const style = view?.getComputedStyle(drawing);
11065
+ if (!view || !style || style.position === "absolute" || style.position === "fixed"
11066
+ || style.transform !== "none" || style.cssFloat !== "none")
11067
+ return false;
11068
+ const paragraphRect = paragraph.getBoundingClientRect();
11069
+ const drawingRect = drawing.getBoundingClientRect();
11070
+ const pageRect = page.getBoundingClientRect();
11071
+ const screenScale = page.clientHeight > 0 ? pageRect.height / page.clientHeight : 1;
11072
+ const bottomMargin = (parseFloat(view.getComputedStyle(paragraph).marginBottom) || 0) * screenScale;
11073
+ const overhead = Math.max(0, paragraphRect.height - drawingRect.height);
11074
+ const available = this.getPageBodyBottom(page) - paragraphRect.top - overhead - bottomMargin - screenScale;
11075
+ const width = parseFloat(style.width), height = parseFloat(style.height);
11076
+ if (![available, width, height, drawingRect.height].every(Number.isFinite)
11077
+ || available <= 0 || width <= 0 || height <= 0 || drawingRect.height <= available)
11078
+ return false;
11079
+ const ratio = available / drawingRect.height;
11080
+ drawing.style.width = `${width * ratio}px`;
11081
+ drawing.style.height = `${height * ratio}px`;
11082
+ picture.style.width = "100%";
11083
+ picture.style.height = "100%";
11084
+ drawing.dataset.docxPageFitScale = `${ratio}`;
11085
+ return true;
11086
+ }
10717
11087
  splitTableBlock(table, page, nextArticle) {
10718
11088
  const rows = this.tableContentRows(table);
10719
11089
  if (rows.length <= 1)
10720
11090
  return false;
11091
+ const repeatHeaders = rows.filter(r => r.dataset.docxRepeatHeader == "true");
11092
+ if (repeatHeaders.length && !this.fitsTableRowPrefix(rows, page))
11093
+ return false;
10721
11094
  const clone = this.cloneBlockShell(table);
10722
11095
  clone.dataset.docxContinued = "true";
10723
11096
  for (const child of Array.from(table.children)) {
10724
11097
  if (child.tagName?.toLowerCase() == "colgroup")
10725
11098
  clone.appendChild(child.cloneNode(true));
10726
11099
  }
10727
- for (const header of rows.filter(r => r.dataset.docxRepeatHeader == "true")) {
11100
+ for (const [index, header] of repeatHeaders.entries()) {
10728
11101
  const repeated = header.cloneNode(true);
10729
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
+ }
10730
11108
  clone.appendChild(repeated);
10731
11109
  }
10732
11110
  nextArticle.prepend(clone);
10733
11111
  let movedAny = false;
10734
11112
  let guard = 0;
10735
- 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) {
10736
11115
  const currentRows = this.tableContentRows(table).filter(r => r.dataset.docxRepeatedHeader != "true");
10737
11116
  const last = currentRows[currentRows.length - 1];
10738
11117
  if (!last)
@@ -10744,8 +11123,58 @@ class HtmlRenderer {
10744
11123
  clone.remove();
10745
11124
  return false;
10746
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
+ }
10747
11156
  return true;
10748
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
+ }
10749
11178
  cloneBlockShell(element) {
10750
11179
  const clone = element.cloneNode(false);
10751
11180
  clone.removeAttribute("id");
@@ -11026,7 +11455,7 @@ class HtmlRenderer {
11026
11455
  wrapperStyle = `@media not print { ${wrapperStyle} }`;
11027
11456
  }
11028
11457
  var styleText = `${wrapperStyle}
11029
- .${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; }
11030
11459
  section.${c} { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: visible; isolation: isolate; }
11031
11460
  section.${c}>header, section.${c}>footer { flex-shrink: 0; }
11032
11461
  section.${c}>[data-docx-note-list] { flex-shrink: 0; }
@@ -11417,6 +11846,7 @@ section.${c}>footer { z-index: 1; }
11417
11846
  }
11418
11847
  const children = frameParagraphs
11419
11848
  .flatMap(item => asArray(this.renderElement(item)).filter(node => node != null));
11849
+ this.applyFlowParagraphSpacing(children);
11420
11850
  const frame = this.h({
11421
11851
  tagName: "div",
11422
11852
  className: `${this.className}-paragraph-frame`,
@@ -11436,6 +11866,7 @@ section.${c}>footer { z-index: 1; }
11436
11866
  }
11437
11867
  result.push(...asArray(this.renderElement(elems[i])).filter(e => e != null));
11438
11868
  }
11869
+ this.applyFlowParagraphSpacing(result);
11439
11870
  if (into)
11440
11871
  result.forEach(c => into.appendChild(isString(c) ? document.createTextNode(c) : c));
11441
11872
  return result;
@@ -11635,7 +12066,7 @@ section.${c}>footer { z-index: 1; }
11635
12066
  const style = this.findStyle(this.currentParagraph?.styleName);
11636
12067
  const isTocParagraph = this.isTocParagraphStyle(this.currentParagraph?.styleName, style);
11637
12068
  const isNumberedTocLeader = !!trailingLeader
11638
- && !!(this.currentParagraph?.numbering ?? style?.paragraphProps?.numbering)
12069
+ && !!this.effectiveParagraphNumbering(this.currentParagraph, style)
11639
12070
  && isTocParagraph;
11640
12071
  if (!trailingLeader)
11641
12072
  return stop;
@@ -11679,17 +12110,22 @@ section.${c}>footer { z-index: 1; }
11679
12110
  children = [flow];
11680
12111
  }
11681
12112
  var result = this.toHTML(elem, ns.html, "p", this.wrapTabLeaderChildren(children, true));
12113
+ this.applyParagraphAutoSpacing(elem, style, result);
12114
+ this.applyTextBoxFontInheritance(elem, style, result);
12115
+ this.applyRunFontSlots(elem, style, result);
11682
12116
  if (this.options.exposeDisplayTargets && elem.displayAddress) {
11683
12117
  const part = this.currentPart ?? this.document.documentPart;
11684
12118
  result.setAttribute("data-office-target", `${part.path}#${elem.displayAddress}`);
11685
12119
  }
11686
- const snapToGrid = this.effectiveParagraphCssValue(elem, style, "--docx-snap-to-grid");
12120
+ const snapToGrid = this.paragraphSnapToGrid(elem, style);
11687
12121
  if (/^(0|false|off)$/i.test(snapToGrid ?? ""))
11688
12122
  result.style.letterSpacing = "normal";
11689
12123
  this.currentParagraph = previousParagraph;
11690
12124
  this.currentParagraphTabIndex = previousParagraphTabIndex;
11691
12125
  this.currentParagraphTabCount = previousParagraphTabCount;
11692
- 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";
11693
12129
  if (numbering) {
11694
12130
  result.classList.add(this.numberingClass(numbering.id, numbering.level));
11695
12131
  }
@@ -11712,6 +12148,16 @@ section.${c}>footer { z-index: 1; }
11712
12148
  result.dataset.docxWidowControl = "true";
11713
12149
  }
11714
12150
  this.applyDocumentGridLinePitch(elem, style, result);
12151
+ if (this.compatibleTextBoxSpacing)
12152
+ this.setCssStyle(result, "text-autospace", this.textBoxAutospace(elem, style));
12153
+ const lineRule = (elem.lineSpacing ?? style?.paragraphProps?.lineSpacing)?.lineRule;
12154
+ if (this.compatibleTextBoxSpacing && ["lines", "linesAndChars"].includes(this.currentSectionProps?.docGrid?.type)
12155
+ && this.paragraphUsesDocumentGrid(elem, style)
12156
+ && lineRule != "exact" && lineRule != "exactly") {
12157
+ result.dataset.docxTextboxGridPitch = this.currentSectionProps.docGrid.linePitch;
12158
+ result.dataset.docxTextboxBaseLineHeight = result.style.lineHeight ?? "";
12159
+ result.style.flexShrink = "0";
12160
+ }
11715
12161
  const leaderTab = elem.tabs?.find(t => this.isLeaderTabStop(t));
11716
12162
  if (leaderTab) {
11717
12163
  result.classList.add(`${this.className}-tab-leader-paragraph`);
@@ -11735,7 +12181,7 @@ section.${c}>footer { z-index: 1; }
11735
12181
  return result;
11736
12182
  }
11737
12183
  uniformParagraphTextScale(paragraph, style) {
11738
- if (paragraph.numbering || style?.paragraphProps?.numbering || paragraph.frame
12184
+ if (this.effectiveParagraphNumbering(paragraph, style) || paragraph.frame
11739
12185
  || this.effectiveParagraphCssValue(paragraph, style, "writing-mode"))
11740
12186
  return null;
11741
12187
  const key = "--docx-text-scale";
@@ -11828,6 +12274,130 @@ section.${c}>footer { z-index: 1; }
11828
12274
  }
11829
12275
  return true;
11830
12276
  }
12277
+ textBoxGridLineHeight(natural, pitch) {
12278
+ if (!Number.isFinite(natural) || !Number.isFinite(pitch) || natural < 0 || pitch <= 0)
12279
+ return null;
12280
+ return Math.max(1, Math.ceil((natural - 1 / 64) / pitch)) * pitch;
12281
+ }
12282
+ refreshTextBoxLineGrid(root) {
12283
+ const view = root.ownerDocument?.defaultView;
12284
+ const paragraphs = Array.from(root.querySelectorAll("[data-docx-textbox-grid-pitch]"))
12285
+ .filter(paragraph => this.ownsLayoutElement(paragraph));
12286
+ if (!view || !paragraphs.length)
12287
+ return;
12288
+ const probe = root.ownerDocument.createElement("span");
12289
+ Object.assign(probe.style, {
12290
+ position: "absolute", visibility: "hidden", pointerEvents: "none", display: "inline-block",
12291
+ whiteSpace: "pre", width: "max-content", margin: "0", padding: "0", border: "0", minHeight: "0"
12292
+ });
12293
+ probe.setAttribute("aria-hidden", "true");
12294
+ const scope = root.getRootNode();
12295
+ const probeParent = scope.nodeType == 11 && "host" in scope ? scope : root.ownerDocument.body;
12296
+ probeParent.appendChild(probe);
12297
+ const setFont = (target, element, lineHeight = "normal") => {
12298
+ const style = view.getComputedStyle(element);
12299
+ Object.assign(target.style, {
12300
+ fontFamily: style.fontFamily, fontSize: style.fontSize, fontWeight: style.fontWeight,
12301
+ fontStyle: style.fontStyle, fontStretch: style.fontStretch, verticalAlign: style.verticalAlign, lineHeight
12302
+ });
12303
+ };
12304
+ try {
12305
+ for (const paragraph of paragraphs) {
12306
+ if (paragraph.querySelector("svg, img, table, math, [data-docx-drawing]"))
12307
+ continue;
12308
+ this.preserveGridInlineMetrics(paragraph);
12309
+ probe.style.height = paragraph.dataset.docxTextboxGridPitch;
12310
+ const pitch = parseFloat(view.getComputedStyle(probe).height);
12311
+ setFont(probe, paragraph, paragraph.dataset.docxTextboxBaseLineHeight || "normal");
12312
+ probe.style.height = "auto";
12313
+ probe.replaceChildren();
12314
+ const walker = root.ownerDocument.createTreeWalker(paragraph, 4);
12315
+ while (walker.nextNode()) {
12316
+ const node = walker.currentNode;
12317
+ const parent = node.parentElement;
12318
+ if (!node.textContent || !parent || !Array.from(parent.getClientRects()).some(rect => rect.width > 0 && rect.height > 0))
12319
+ continue;
12320
+ const lineHeight = parent == paragraph ? paragraph.dataset.docxTextboxBaseLineHeight : parent.style.lineHeight;
12321
+ const span = root.ownerDocument.createElement("span");
12322
+ setFont(span, parent, lineHeight || "normal");
12323
+ span.style.whiteSpace = "pre";
12324
+ span.textContent = node.textContent.replace(/[\r\n]/g, " ");
12325
+ probe.appendChild(span);
12326
+ }
12327
+ if (!probe.hasChildNodes())
12328
+ probe.textContent = "\u00a0";
12329
+ const natural = parseFloat(view.getComputedStyle(probe).height);
12330
+ const height = this.textBoxGridLineHeight(natural, pitch);
12331
+ if (height != null)
12332
+ paragraph.style.lineHeight = `${Math.round(height * 1000) / 1000}px`;
12333
+ }
12334
+ }
12335
+ finally {
12336
+ probe.remove();
12337
+ }
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
+ }
11831
12401
  async prepareLayout(root, generation = getLayoutGeneration(root)) {
11832
12402
  if (!root.isConnected || !generation.isCurrent())
11833
12403
  return;
@@ -11848,6 +12418,8 @@ section.${c}>footer { z-index: 1; }
11848
12418
  (owner ?? root).appendChild(this.commentLayer.root);
11849
12419
  }
11850
12420
  }
12421
+ this.refreshParagraphLineGrid(root);
12422
+ this.refreshTextBoxLineGrid(root);
11851
12423
  this.refreshTabStops(root);
11852
12424
  this.refreshAnchors(root);
11853
12425
  await this.commentLayer?.bind(root, generation);
@@ -12224,17 +12796,31 @@ section.${c}>footer { z-index: 1; }
12224
12796
  return result;
12225
12797
  }
12226
12798
  renderImage(elem) {
12227
- let result = this.toHTML(elem, ns.html, "img", []);
12799
+ const rect = elem.srcRect;
12800
+ const cropWidth = rect ? 1 - rect[0] - rect[2] : 1;
12801
+ const cropHeight = rect ? 1 - rect[1] - rect[3] : 1;
12802
+ const cropped = rect?.length === 4 && rect.some(x => x !== 0)
12803
+ && rect.every(Number.isFinite) && cropWidth > 0 && cropHeight > 0
12804
+ && Number.isFinite(100 / cropWidth) && Number.isFinite(100 / cropHeight);
12805
+ const result = this.toHTML(elem, ns.html, cropped ? "span" : "img", []);
12806
+ const image = cropped ? this.h({ tagName: "img" }) : result;
12228
12807
  let transform = elem.cssStyle?.transform;
12229
12808
  if (elem.alt)
12230
- result.alt = elem.alt;
12809
+ image.alt = elem.alt;
12231
12810
  if (elem.title)
12232
- result.title = elem.title;
12233
- if (elem.srcRect && elem.srcRect.some(x => x != 0)) {
12234
- var [left, top, right, bottom] = elem.srcRect;
12235
- transform = `${transform ?? ''} scale(${1 / (1 - left - right)}, ${1 / (1 - top - bottom)})`;
12236
- result.style.clipPath = `inset(${(100 * top).toFixed(2)}% ${(100 * right).toFixed(2)}% ${(100 * bottom).toFixed(2)}% ${(100 * left).toFixed(2)}%)`;
12237
- result.style.transformOrigin = "top left";
12811
+ image.title = elem.title;
12812
+ if (cropped) {
12813
+ result.setAttribute("data-docx-image-crop", "true");
12814
+ result.style.overflow = "hidden";
12815
+ result.style.position = "relative";
12816
+ Object.assign(image.style, {
12817
+ position: "absolute", display: "block", margin: "0",
12818
+ left: `${ -100 * rect[0] / cropWidth}%`,
12819
+ top: `${ -100 * rect[1] / cropHeight}%`,
12820
+ width: `${100 / cropWidth}%`, height: `${100 / cropHeight}%`,
12821
+ maxWidth: "none", maxHeight: "none", objectFit: "fill"
12822
+ });
12823
+ result.appendChild(image);
12238
12824
  }
12239
12825
  if (elem.rotation)
12240
12826
  transform = `rotate(${elem.rotation}deg) ${transform ?? ''}`;
@@ -12242,7 +12828,7 @@ section.${c}>footer { z-index: 1; }
12242
12828
  if (this.document && elem.src) {
12243
12829
  this.tasks.push(this.document.loadDocumentImage(elem.src, this.currentPart, this.options.externalResourcePolicy).then(x => {
12244
12830
  if (x)
12245
- result.setAttribute("src", x);
12831
+ image.setAttribute("src", x);
12246
12832
  }));
12247
12833
  }
12248
12834
  return result;
@@ -12264,9 +12850,17 @@ section.${c}>footer { z-index: 1; }
12264
12850
  }
12265
12851
  renderDmlTextBox(elem) {
12266
12852
  const previousParagraph = this.currentParagraph;
12853
+ const previousSpacing = this.compatibleTextBoxSpacing;
12267
12854
  this.currentParagraph = null;
12268
- const children = this.renderElements(elem.children);
12269
- this.currentParagraph = previousParagraph;
12855
+ this.compatibleTextBoxSpacing = elem.props?.textCompatibleLineSpacing === true;
12856
+ let children;
12857
+ try {
12858
+ children = this.renderElements(elem.children);
12859
+ }
12860
+ finally {
12861
+ this.currentParagraph = previousParagraph;
12862
+ this.compatibleTextBoxSpacing = previousSpacing;
12863
+ }
12270
12864
  const content = this.h({
12271
12865
  tagName: "div",
12272
12866
  className: `${this.className}-shape-textbox`,
@@ -13967,6 +14561,8 @@ section.${c}>footer { z-index: 1; }
13967
14561
  }
13968
14562
  const result = this.toHTML(elem, ns.html, "span", children);
13969
14563
  const style = this.findStyle(elem.styleName);
14564
+ this.applyTextBoxFontInheritance(elem, style, result);
14565
+ this.applyRunFontSlots(elem, style, result);
13970
14566
  const snapToGrid = elem.cssStyle?.["--docx-snap-to-grid"] ?? this.styleValue(style, "span", "--docx-snap-to-grid");
13971
14567
  if (/^(0|false|off)$/i.test(snapToGrid ?? ""))
13972
14568
  result.style.letterSpacing = "normal";
@@ -14294,6 +14890,11 @@ section.${c}>footer { z-index: 1; }
14294
14890
  rect.setAttribute("width", `${bounds.width}`);
14295
14891
  rect.setAttribute("height", `${bounds.height}`);
14296
14892
  this.applyVmlAttributes(rect, elem.attrs, new Set(["x", "y", "width", "height"]));
14893
+ if (elem.roundRectArc != null) {
14894
+ const radius = Math.min(bounds.width, bounds.height) * elem.roundRectArc / 2;
14895
+ rect.setAttribute("rx", `${radius}`);
14896
+ rect.setAttribute("ry", `${radius}`);
14897
+ }
14297
14898
  result = rect;
14298
14899
  break;
14299
14900
  }
@@ -14707,8 +15308,11 @@ section.${c}>footer { z-index: 1; }
14707
15308
  if (!style)
14708
15309
  return style;
14709
15310
  const result = { ...style };
14710
- if (normalized)
15311
+ if (normalized) {
14711
15312
  delete result["font-family"];
15313
+ delete result["--docx-latin-font-family"];
15314
+ delete result["--docx-partial-eastasia-font"];
15315
+ }
14712
15316
  return result;
14713
15317
  }
14714
15318
  normalizeNumberingLevelText(text, format, runStyle) {