@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.
@@ -403,7 +403,7 @@
403
403
  props.fontSize = xml.lengthAttr(elem, "val", LengthUsage.FontSize);
404
404
  break;
405
405
  case "szCs":
406
- props.fontSize ?? (props.fontSize = xml.lengthAttr(elem, "val", LengthUsage.FontSize));
406
+ props.complexFontSize = xml.lengthAttr(elem, "val", LengthUsage.FontSize);
407
407
  break;
408
408
  default:
409
409
  return false;
@@ -1669,6 +1669,8 @@
1669
1669
  for (const c of xml.elements(el)) {
1670
1670
  if (c.localName == "adjustLineHeightInTable")
1671
1671
  result.adjustLineHeightInTable = xml.boolAttr(c, "val", true);
1672
+ else if (c.localName == "doNotUseHTMLParagraphAutoSpacing")
1673
+ result.doNotUseHTMLParagraphAutoSpacing = xml.boolAttr(c, "val", true);
1672
1674
  }
1673
1675
  break;
1674
1676
  }
@@ -3737,6 +3739,8 @@
3737
3739
  result.tagName = "g";
3738
3740
  result.isGroup = true;
3739
3741
  break;
3742
+ case "roundrect":
3743
+ result.roundRectArc = 0.2;
3740
3744
  case "rect":
3741
3745
  result.tagName = "rect";
3742
3746
  Object.assign(result.attrs, { width: '100%', height: '100%' });
@@ -3771,6 +3775,10 @@
3771
3775
  case "coordsize":
3772
3776
  result.coordSize = parseNumericPoint(at.value);
3773
3777
  break;
3778
+ case "arcsize":
3779
+ if (result.roundRectArc != null)
3780
+ result.roundRectArc = parseRoundRectArc(at.value);
3781
+ break;
3774
3782
  case "inset":
3775
3783
  if (result.textInset) {
3776
3784
  const values = at.value.trim().split(/\s*,\s*|\s+/);
@@ -3868,6 +3876,13 @@
3868
3876
  }
3869
3877
  return result;
3870
3878
  }
3879
+ function parseRoundRectArc(value) {
3880
+ const source = value.trim();
3881
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:%|f)?$/i.test(source))
3882
+ return 0.2;
3883
+ const fraction = parseFloat(source) / (/%$/.test(source) ? 100 : /f$/i.test(source) ? 65536 : 1);
3884
+ return Number.isFinite(fraction) ? Math.max(0, Math.min(1, fraction)) : 0.2;
3885
+ }
3871
3886
  function vmlImageAttrs(el) {
3872
3887
  const cropLeft = parseVmlFraction(globalXmlParser.attr(el, "cropleft"));
3873
3888
  const cropTop = parseVmlFraction(globalXmlParser.attr(el, "croptop"));
@@ -4027,6 +4042,44 @@
4027
4042
  };
4028
4043
  }
4029
4044
 
4045
+ const WORD_PARAGRAPH_LINE_UNIT_PT = 12;
4046
+ function paragraphSpacingDeclaration(points, lines) {
4047
+ const lineValue = Number.isFinite(lines) && lines >= 0 ? `${(lines * WORD_PARAGRAPH_LINE_UNIT_PT / 100).toFixed(2)}pt` : null;
4048
+ const validPoints = /^(?:\d+(?:\.\d*)?|\.\d+)pt$/i.test(points ?? "");
4049
+ return { lines: lineValue, fallback: lines === 0 && validPoints ? points : lineValue ?? points };
4050
+ }
4051
+ const WORD_HTML_AUTO_SPACING_PT = 14;
4052
+ function effectiveParagraphSpacing(levels, fixed, styleId) {
4053
+ const value = (key) => levels.find(level => level?.[key] != null)?.[key];
4054
+ const side = (name) => {
4055
+ const prefix = `--docx-spacing-${name}`;
4056
+ const autoValue = value(`${prefix}-auto`);
4057
+ const auto = autoValue === "true";
4058
+ const lines = value(`${prefix}-lines`), points = value(`${prefix}-points`);
4059
+ const declared = autoValue === "true" || autoValue === "false"
4060
+ || spacingPoints(lines) != null || spacingPoints(points) != null;
4061
+ const ordinary = parseFloat(lines) > 0 ? lines : points ?? lines ?? "0pt";
4062
+ return { auto: auto && !fixed, declared, length: auto && !fixed ? `${WORD_HTML_AUTO_SPACING_PT}pt` : ordinary };
4063
+ };
4064
+ const before = side("before"), after = side("after");
4065
+ return { before: before.length, after: after.length, beforeAuto: before.auto, afterAuto: after.auto,
4066
+ beforeDeclared: before.declared, afterDeclared: after.declared,
4067
+ contextual: value("--docx-contextual-spacing") === "true", styleId };
4068
+ }
4069
+ function spacingPoints(length) {
4070
+ const match = /^(\d+(?:\.\d*)?|\.\d+)(pt|px)$/i.exec(length ?? "");
4071
+ return match ? Number(match[1]) * (match[2].toLowerCase() === "px" ? .75 : 1) : null;
4072
+ }
4073
+ function paragraphSpacingGap(previous, next, fixed) {
4074
+ const after = spacingPoints(previous.after), before = spacingPoints(next.before);
4075
+ if (after == null || before == null)
4076
+ return null;
4077
+ const same = previous.styleId === next.styleId;
4078
+ const remainder = fixed ? before : Math.max(0, before - after);
4079
+ const gap = (same && previous.contextual ? 0 : after) + (same && next.contextual ? 0 : remainder);
4080
+ return `${Math.round(gap * 1000000) / 1000000}pt`;
4081
+ }
4082
+
4030
4083
  var autos = {
4031
4084
  shd: "inherit",
4032
4085
  color: "var(--docx-auto-color, black)",
@@ -5425,6 +5478,9 @@
5425
5478
  const prstGeom = globalXmlParser.element(spPr, "prstGeom");
5426
5479
  const fillStyle = this.parseDmlFillStyle(spPr);
5427
5480
  const lineStyle = this.parseDmlLineStyle(globalXmlParser.element(spPr, "ln"));
5481
+ const roundedRadius = !geom ? this.parseDmlRoundRectRadius(spPr, bounds.width, bounds.height, transform) : null;
5482
+ if (roundedRadius != null)
5483
+ cssStyle["border-radius"] = roundedRadius;
5428
5484
  if (geom) {
5429
5485
  const path = this.parseDmlCustomGeometry(geom);
5430
5486
  return {
@@ -5462,6 +5518,23 @@
5462
5518
  alt: cNvPr ? globalXmlParser.attr(cNvPr, "descr") : null
5463
5519
  };
5464
5520
  }
5521
+ parseDmlRoundRectRadius(spPr, width, height, transform) {
5522
+ const preset = globalXmlParser.element(spPr, "prstGeom");
5523
+ if (!preset || globalXmlParser.attr(preset, "prst") != "roundRect")
5524
+ return null;
5525
+ const guides = globalXmlParser.element(preset, "avLst");
5526
+ const adjustment = (guides ? globalXmlParser.elements(guides, "gd") : [])
5527
+ .find(guide => globalXmlParser.attr(guide, "name") == "adj");
5528
+ const formula = adjustment ? globalXmlParser.attr(adjustment, "fmla") : "";
5529
+ const value = /^val\s+[+-]?(?:\d+(?:\.\d*)?|\.\d+)\s*$/.test(formula ?? "")
5530
+ ? Number(formula.trim().split(/\s+/)[1]) : 16667;
5531
+ const fraction = Math.max(0, Math.min(50000, value)) / 100000;
5532
+ const scaleX = Math.abs(transform?.scaleX ?? 1);
5533
+ const scaleY = Math.abs(transform?.scaleY ?? 1);
5534
+ const radius = Number.isFinite(scaleX) && Number.isFinite(scaleY) && scaleX > 0 && scaleY > 0
5535
+ ? Math.min(width / scaleX, height / scaleY) * fraction : 0;
5536
+ return `${this.pt(Number.isFinite(radius * scaleX) ? radius * scaleX : 0)} / ${this.pt(Number.isFinite(radius * scaleY) ? radius * scaleY : 0)}`;
5537
+ }
5465
5538
  parseDmlShapeBounds(spPr, transform) {
5466
5539
  const xfrm = globalXmlParser.element(spPr, "xfrm");
5467
5540
  const off = xfrm ? globalXmlParser.element(xfrm, "off") : null;
@@ -5598,6 +5671,7 @@
5598
5671
  return {
5599
5672
  dmlTextBox: true,
5600
5673
  textInsets: textInsetStyle,
5674
+ textCompatibleLineSpacing: bodyPr ? globalXmlParser.boolAttr(bodyPr, "compatLnSpc", false) : false,
5601
5675
  textVerticalAlign: this.dmlVerticalAlign(bodyPr)
5602
5676
  };
5603
5677
  }
@@ -5697,6 +5771,10 @@
5697
5771
  }
5698
5772
  parseDmlShapeProperties(elem, style) {
5699
5773
  const xfrm = globalXmlParser.element(elem, "xfrm");
5774
+ const bounds = this.parseDmlShapeBounds(elem);
5775
+ const roundedRadius = this.parseDmlRoundRectRadius(elem, bounds.width, bounds.height);
5776
+ if (roundedRadius != null)
5777
+ style["border-radius"] = roundedRadius;
5700
5778
  if (xfrm) {
5701
5779
  for (const n of globalXmlParser.elements(xfrm)) {
5702
5780
  switch (n.localName) {
@@ -6141,6 +6219,10 @@
6141
6219
  case "textAlignment":
6142
6220
  style["vertical-align"] = values.valueOfTextAlignment(c);
6143
6221
  break;
6222
+ case "autoSpaceDE":
6223
+ case "autoSpaceDN":
6224
+ style[c.localName == "autoSpaceDE" ? "--docx-auto-space-de" : "--docx-auto-space-dn"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6225
+ break;
6144
6226
  case "color":
6145
6227
  style["color"] = xmlUtil.colorAttr(c, "val", null, autos.color);
6146
6228
  break;
@@ -6148,8 +6230,10 @@
6148
6230
  style["font-size"] = style["min-height"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize);
6149
6231
  break;
6150
6232
  case "szCs":
6151
- style["font-size"] ?? (style["font-size"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize));
6152
- style["min-height"] ?? (style["min-height"] = style["font-size"]);
6233
+ style["--docx-complex-font-size"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize);
6234
+ break;
6235
+ case "cs":
6236
+ style["--docx-complex-script"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6153
6237
  break;
6154
6238
  case "shd":
6155
6239
  style["background-color"] = xmlUtil.colorAttr(c, "fill", null, autos.shd);
@@ -6213,6 +6297,7 @@
6213
6297
  style["font-variant"] = globalXmlParser.boolAttr(c, "val", true) ? "small-caps" : "none";
6214
6298
  break;
6215
6299
  case "rtl":
6300
+ style["--docx-rtl-run"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6216
6301
  if (globalXmlParser.boolAttr(c, "val", true)) {
6217
6302
  style["direction"] = "rtl";
6218
6303
  style["unicode-bidi"] = "embed";
@@ -6345,9 +6430,11 @@
6345
6430
  if (globalXmlParser.boolAttr(c, "val", true))
6346
6431
  style["display"] = "none";
6347
6432
  break;
6433
+ case "contextualSpacing":
6434
+ style["--docx-contextual-spacing"] = `${globalXmlParser.boolAttr(c, "val", true)}`;
6435
+ break;
6348
6436
  case "tabs":
6349
6437
  case "outlineLvl":
6350
- case "contextualSpacing":
6351
6438
  case "tblStyleColBandSize":
6352
6439
  case "tblStyleRowBandSize":
6353
6440
  case "suppressLineNumbers":
@@ -6439,6 +6526,7 @@
6439
6526
  fonts.push(...[asciiTheme, hAnsiTheme]
6440
6527
  .filter(x => x)
6441
6528
  .map(x => x.startsWith("var(") ? x : encloseFontFamily(x)));
6529
+ const latinFonts = fonts.slice();
6442
6530
  if (eastAsia) {
6443
6531
  fonts.push(...eastAsianFontFamilyStack(eastAsia, eastAsiaScript));
6444
6532
  }
@@ -6452,6 +6540,21 @@
6452
6540
  if (fonts.length > 0) {
6453
6541
  const currentFonts = (style["font-family"] ?? "").split(',').map(x => x.trim()).filter(x => x);
6454
6542
  style["font-family"] = [...new Set([...currentFonts, ...fonts])].join(', ');
6543
+ if (latinFonts.length)
6544
+ style["--docx-latin-font-family"] = [...new Set(latinFonts)].join(', ');
6545
+ style["--docx-partial-eastasia-font"] = !latinFonts.length && (eastAsia || eastAsiaTheme) && !cs && !csTheme ? "true" : "false";
6546
+ }
6547
+ const slots = {
6548
+ ascii: [ascii, asciiTheme], hansi: [hAnsi, hAnsiTheme],
6549
+ eastasia: [eastAsia, eastAsiaTheme], complex: [cs, csTheme]
6550
+ };
6551
+ for (const [slot, [direct, themed]] of Object.entries(slots)) {
6552
+ const selected = themed || direct;
6553
+ if (!selected)
6554
+ continue;
6555
+ const family = selected.startsWith("var(") ? selected
6556
+ : expandDirectFont(selected, slot == "complex" ? themeScriptForLanguage(languages.bidi) : eastAsiaScript).join(', ');
6557
+ style[`--docx-font-${slot}`] = family;
6455
6558
  }
6456
6559
  }
6457
6560
  scriptThemeFontValue(value, language) {
@@ -6497,18 +6600,28 @@
6497
6600
  var afterAuto = globalXmlParser.boolAttr(node, "afterAutospacing", false);
6498
6601
  var line = globalXmlParser.intAttr(node, "line", null);
6499
6602
  var lineRule = globalXmlParser.attr(node, "lineRule");
6500
- if (beforeAuto)
6501
- style["margin-top"] = "auto";
6502
- else if (Number.isFinite(beforeLines) && beforeLines >= 0)
6503
- style["margin-top"] = `${(beforeLines / 100).toFixed(2)}em`;
6504
- else if (before)
6505
- style["margin-top"] = before;
6506
- if (afterAuto)
6507
- style["margin-bottom"] = "auto";
6508
- else if (Number.isFinite(afterLines) && afterLines >= 0)
6509
- style["margin-bottom"] = `${(afterLines / 100).toFixed(2)}em`;
6510
- else if (after)
6511
- style["margin-bottom"] = after;
6603
+ for (const [side, margin, points, lines, auto] of [
6604
+ ["before", "margin-top", before, beforeLines, beforeAuto],
6605
+ ["after", "margin-bottom", after, afterLines, afterAuto]
6606
+ ]) {
6607
+ const prefix = `--docx-spacing-${side}`;
6608
+ const { lines: lineValue, fallback } = paragraphSpacingDeclaration(points, lines);
6609
+ const autoSpecified = globalXmlParser.attr(node, `${side}Autospacing`) != null;
6610
+ if (points != null)
6611
+ style[`${prefix}-points`] = points;
6612
+ if (lineValue != null)
6613
+ style[`${prefix}-lines`] = lineValue;
6614
+ if (fallback != null)
6615
+ style[`${prefix}-fallback`] = fallback;
6616
+ if (autoSpecified)
6617
+ style[`${prefix}-auto`] = `${auto}`;
6618
+ if (auto)
6619
+ style[margin] = `${WORD_HTML_AUTO_SPACING_PT}pt`;
6620
+ else if (fallback != null)
6621
+ style[margin] = fallback;
6622
+ else if (autoSpecified)
6623
+ style[margin] = "0pt";
6624
+ }
6512
6625
  if (line !== null) {
6513
6626
  switch (lineRule ?? "auto") {
6514
6627
  case "auto":
@@ -7984,6 +8097,18 @@
7984
8097
  return applied;
7985
8098
  }
7986
8099
 
8100
+ function gridAutomaticLineHeight(lineHeight, linePitch) {
8101
+ const multiplier = /^\d+(?:\.\d+)?$/.test(lineHeight ?? "") ? Number(lineHeight) : NaN;
8102
+ return Number.isFinite(multiplier) && multiplier >= 1
8103
+ ? `calc(${linePitch} * ${multiplier})`
8104
+ : /^-?\d+(?:\.\d+)?$/.test(lineHeight ?? "") ? `calc(${lineHeight} * 1em)` : lineHeight;
8105
+ }
8106
+ function gridFontLineHeight(natural, pitch, multiplier = 1) {
8107
+ if (![natural, pitch, multiplier].every(Number.isFinite) || natural < 0 || pitch <= 0 || multiplier < 1)
8108
+ return null;
8109
+ return Math.max(pitch * multiplier, Math.max(1, Math.ceil((natural - 1 / 64) / pitch)) * pitch);
8110
+ }
8111
+
7987
8112
  const DEFAULT_DARK_MODE_BASE_L = 21.247;
7988
8113
  const LAB_EPSILON = Math.pow(6 / 29, 3);
7989
8114
  function srgbToLinear(c) {
@@ -8646,6 +8771,22 @@
8646
8771
  return elements.map(copy);
8647
8772
  }
8648
8773
 
8774
+ const legacyComplexScriptCharacters = /[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufeff]/u;
8775
+ const additionalComplexScriptCharacters = new RegExp([
8776
+ 'Devanagari', 'Bengali', 'Gurmukhi', 'Gujarati', 'Oriya', 'Tamil', 'Telugu',
8777
+ 'Kannada', 'Malayalam', 'Sinhala', 'Thai', 'Lao', 'Tibetan', 'Myanmar', 'Khmer'
8778
+ ].map(script => `\\p{Script=${script}}`).join('|'), 'u');
8779
+ const neutralScriptCharacters = /[\p{Script=Common}\p{Script=Inherited}]/u;
8780
+ function isAdditionalComplexScriptRun(text) {
8781
+ if (!additionalComplexScriptCharacters.test(text))
8782
+ return false;
8783
+ for (const character of text) {
8784
+ if (!additionalComplexScriptCharacters.test(character)
8785
+ && !legacyComplexScriptCharacters.test(character) && !neutralScriptCharacters.test(character))
8786
+ return false;
8787
+ }
8788
+ return true;
8789
+ }
8649
8790
  const chartNamespaces = [
8650
8791
  "http://schemas.openxmlformats.org/drawingml/2006/chart",
8651
8792
  "http://purl.oclc.org/ooxml/drawingml/chart"
@@ -8733,6 +8874,8 @@
8733
8874
  this.headingIndex = 0;
8734
8875
  this.tasks = [];
8735
8876
  this.postRenderTasks = [];
8877
+ this.compatibleTextBoxSpacing = false;
8878
+ this.paragraphSpacingStates = new WeakMap();
8736
8879
  this.h = h;
8737
8880
  this.darkModeVarNames = new Map();
8738
8881
  this.darkModePrintReset = {};
@@ -8744,6 +8887,9 @@
8744
8887
  this.rootSelector = options.inWrapper ? `.${this.className}-wrapper` : ':root';
8745
8888
  this.h = options.h ?? h;
8746
8889
  this.styleMap = null;
8890
+ this.defaultParagraphStyle = null;
8891
+ this.defaultCharacterStyle = null;
8892
+ this.defaultRunStyle = null;
8747
8893
  this.tasks = [];
8748
8894
  this.postRenderTasks = [];
8749
8895
  this.commentLayer = null;
@@ -8838,6 +8984,7 @@
8838
8984
  variables['--docx-majorEastAsia-font'] = this.themeFontFamily(fontScheme.majorFont, "eastAsia", languages.eastAsia);
8839
8985
  variables['--docx-majorBidi-font'] = this.themeFontFamily(fontScheme.majorFont, "complexScript", languages.bidi);
8840
8986
  variables['--docx-majorCs-font'] = variables['--docx-majorBidi-font'];
8987
+ this.addThemeFontFallbackVariables(variables, "major", fontScheme.majorFont);
8841
8988
  this.addThemeScriptFontVariables(variables, "major", fontScheme.majorFont);
8842
8989
  }
8843
8990
  if (fontScheme.minorFont) {
@@ -8845,6 +8992,7 @@
8845
8992
  variables['--docx-minorEastAsia-font'] = this.themeFontFamily(fontScheme.minorFont, "eastAsia", languages.eastAsia);
8846
8993
  variables['--docx-minorBidi-font'] = this.themeFontFamily(fontScheme.minorFont, "complexScript", languages.bidi);
8847
8994
  variables['--docx-minorCs-font'] = variables['--docx-minorBidi-font'];
8995
+ this.addThemeFontFallbackVariables(variables, "minor", fontScheme.minorFont);
8848
8996
  this.addThemeScriptFontVariables(variables, "minor", fontScheme.minorFont);
8849
8997
  }
8850
8998
  }
@@ -8880,6 +9028,15 @@
8880
9028
  result.bidi = values["$lang-bidi"] ?? result.latin;
8881
9029
  return result;
8882
9030
  }
9031
+ addThemeFontFallbackVariables(variables, size, font) {
9032
+ const fallback = (direct, generic) => {
9033
+ const typeface = direct?.trim() || font.latinTypeface?.trim();
9034
+ return typeface ? `${encloseFontFamily(typeface)}, ${generic}` : generic;
9035
+ };
9036
+ variables[`--docx-${size}EastAsia-font-fallback`] = fallback(font.eaTypeface, "sans-serif");
9037
+ variables[`--docx-${size}Bidi-font-fallback`] = fallback(font.csTypeface, "serif");
9038
+ variables[`--docx-${size}Cs-font-fallback`] = variables[`--docx-${size}Bidi-font-fallback`];
9039
+ }
8883
9040
  addThemeScriptFontVariables(variables, size, font) {
8884
9041
  const eastAsianScripts = new Set(["Hans", "Hant", "Jpan", "Hang"]);
8885
9042
  for (const script of Object.keys(font.scriptTypefaces ?? {})) {
@@ -8938,6 +9095,9 @@
8938
9095
  }
8939
9096
  processStyles(styles) {
8940
9097
  const stylesMap = keyBy(styles.filter(x => x.id != null), x => x.id);
9098
+ this.defaultParagraphStyle = styles.find(style => style.isDefault && style.target == "p");
9099
+ this.defaultCharacterStyle = styles.find(style => style.isDefault && style.target == "span");
9100
+ this.defaultRunStyle = styles.find(style => style.id == null);
8941
9101
  for (const style of styles.filter(x => x.basedOn)) {
8942
9102
  var baseStyle = stylesMap[style.basedOn];
8943
9103
  if (baseStyle) {
@@ -9637,14 +9797,20 @@
9637
9797
  result.push({ paragraph: currentParagraph, breakAfter: false });
9638
9798
  }
9639
9799
  const last = result[result.length - 1]?.paragraph;
9800
+ const siblings = paragraph.parent?.children?.filter(child => ![DomType.BookmarkStart, DomType.BookmarkEnd].includes(child.type));
9640
9801
  for (const item of result) {
9641
9802
  item.paragraph.sectionProps = item.paragraph === last ? paragraph.sectionProps : null;
9803
+ item.paragraph.props = { ...item.paragraph.props,
9804
+ spacingFirstInFlow: siblings?.[0] === paragraph && item === result[0],
9805
+ spacingLastInFlow: siblings?.[siblings.length - 1] === paragraph && item.paragraph === last };
9642
9806
  }
9643
- if (paragraph.props?.anchorId && result.length > 1) {
9644
- const owner = result.find(part => this.extractText(part.paragraph).trim()) ?? result[0];
9807
+ if (result.length > 1) {
9808
+ const owner = result.find(part => this.hasPageModelContent(part.paragraph)) ?? result[0];
9645
9809
  for (const part of result) {
9646
- if (part !== owner)
9647
- part.paragraph.props = { ...part.paragraph.props, anchorId: undefined };
9810
+ if (part !== owner) {
9811
+ part.paragraph.props = { ...part.paragraph.props, anchorId: undefined,
9812
+ pageBreakContinuation: true, pageBreakEmpty: !this.hasPageModelContent(part.paragraph) };
9813
+ }
9648
9814
  }
9649
9815
  }
9650
9816
  return result;
@@ -9655,9 +9821,139 @@
9655
9821
  styleValue(style, target, name) {
9656
9822
  return this.styleValuesForTarget(style, target)?.[name];
9657
9823
  }
9824
+ styleValueLevels(style, target) {
9825
+ const levels = [];
9826
+ const seen = new Set();
9827
+ while (style && !seen.has(style)) {
9828
+ seen.add(style);
9829
+ levels.push(this.styleValuesForTarget(style, target));
9830
+ style = this.findStyle(style.basedOn);
9831
+ }
9832
+ return levels;
9833
+ }
9834
+ effectiveParagraphNumbering(elem, style) {
9835
+ let numbering = elem?.numbering;
9836
+ let current = elem?.styleName ? style : this.defaultParagraphStyle;
9837
+ const seen = new Set();
9838
+ while (!numbering && current?.target == "p" && !seen.has(current)) {
9839
+ seen.add(current);
9840
+ numbering = current.paragraphProps?.numbering;
9841
+ current = this.findStyle(current.basedOn);
9842
+ }
9843
+ return numbering && !/^0+$/.test(String(numbering.id ?? "").trim()) ? numbering : null;
9844
+ }
9845
+ applyParagraphAutoSpacing(elem, style, result) {
9846
+ const paragraphStyle = elem.styleName ? style : this.defaultParagraphStyle;
9847
+ const numbering = this.effectiveParagraphNumbering(elem, style);
9848
+ const numberingStyle = numbering && this.document?.numberingPart?.domNumberings
9849
+ ?.find(num => num.id == numbering.id && num.level == numbering.level)?.pStyle;
9850
+ const levels = [elem.cssStyle, ...this.styleValueLevels(paragraphStyle, "p"), numberingStyle,
9851
+ this.styleValuesForTarget(this.defaultRunStyle, "p")];
9852
+ const fixed = this.document?.settingsPart?.settings?.doNotUseHTMLParagraphAutoSpacing;
9853
+ const state = effectiveParagraphSpacing(levels, fixed, elem.styleName ?? paragraphStyle?.id ?? "");
9854
+ const siblings = elem.parent?.children?.filter(child => ![DomType.BookmarkStart, DomType.BookmarkEnd].includes(child.type));
9855
+ const first = elem.props?.spacingFirstInFlow ?? siblings?.[0] === elem;
9856
+ const last = elem.props?.spacingLastInFlow ?? siblings?.[siblings.length - 1] === elem;
9857
+ if (state.beforeAuto && first && [DomType.Document, DomType.Cell].includes(elem.parent?.type))
9858
+ state.before = "0pt";
9859
+ if (state.afterAuto && last && elem.parent?.type === DomType.Cell)
9860
+ state.after = "0pt";
9861
+ if (state.beforeDeclared)
9862
+ this.setCssStyle(result, "margin-top", state.before);
9863
+ if (state.afterDeclared)
9864
+ this.setCssStyle(result, "margin-bottom", state.after);
9865
+ this.paragraphSpacingStates.set(result, state);
9866
+ }
9867
+ applyFlowParagraphSpacing(nodes) {
9868
+ let previous = null;
9869
+ const fixed = this.document?.settingsPart?.settings?.doNotUseHTMLParagraphAutoSpacing;
9870
+ for (const node of nodes) {
9871
+ const state = typeof node === "object" && node && this.paragraphSpacingStates.get(node);
9872
+ if (!state) {
9873
+ const element = node;
9874
+ if (element?.nodeType === 3 && !element.textContent?.trim())
9875
+ continue;
9876
+ if (/^(a|span)$/i.test(element?.tagName ?? "") && !element.textContent && element.id)
9877
+ continue;
9878
+ previous = null;
9879
+ continue;
9880
+ }
9881
+ if (previous && (previous.state.afterDeclared || state.beforeDeclared)) {
9882
+ const gap = paragraphSpacingGap(previous.state, state, fixed);
9883
+ if (gap != null) {
9884
+ this.setCssStyle(previous.node, "margin-bottom", "0pt");
9885
+ this.setCssStyle(node, "margin-top", gap);
9886
+ }
9887
+ }
9888
+ previous = { node: node, state };
9889
+ }
9890
+ }
9658
9891
  effectiveParagraphCssValue(elem, style, name) {
9659
9892
  return elem.cssStyle?.[name] ?? this.styleValue(style, "p", name);
9660
9893
  }
9894
+ textBoxAutospace(elem, style, supports = (value) => typeof CSS == "undefined" || typeof CSS.supports != "function" || CSS.supports("text-autospace", value)) {
9895
+ const enabled = (key) => !/^(0|false|off)$/i.test(this.effectiveParagraphCssValue(elem, style, key) ?? "true");
9896
+ const alpha = enabled("--docx-auto-space-de"), numeric = enabled("--docx-auto-space-dn");
9897
+ const value = alpha && numeric ? "normal" : alpha ? "ideograph-alpha" : numeric ? "ideograph-numeric" : "no-autospace";
9898
+ return supports(value) ? value : "no-autospace";
9899
+ }
9900
+ applyTextBoxFontInheritance(elem, style, result) {
9901
+ if (!this.compatibleTextBoxSpacing)
9902
+ return;
9903
+ const paragraph = elem.type == DomType.Paragraph ? elem : this.currentParagraph;
9904
+ const paragraphStyle = this.findStyle(paragraph?.styleName);
9905
+ const defaults = this.document.stylesPart?.styles?.find(item => item.id == null);
9906
+ const levels = [elem.cssStyle, this.styleValuesForTarget(style, elem.type == DomType.Paragraph ? "p" : "span"),
9907
+ paragraph?.cssStyle, this.styleValuesForTarget(paragraphStyle, "span"), this.styleValuesForTarget(defaults, "span")];
9908
+ const value = (key) => levels.find(level => level?.[key] != null)?.[key];
9909
+ if (value("--docx-partial-eastasia-font") != "true")
9910
+ return;
9911
+ const latin = value("--docx-latin-font-family"), family = value("font-family");
9912
+ if (!latin || !family)
9913
+ return;
9914
+ this.setCssStyle(result, "--docx-latin-font-family", latin);
9915
+ this.setCssStyle(result, "font-family", `var(--docx-latin-font-family), ${family}`);
9916
+ }
9917
+ applyRunFontSlots(elem, style, result) {
9918
+ const paragraph = elem.type == DomType.Paragraph ? elem : this.currentParagraph;
9919
+ const paragraphStyle = this.findStyle(paragraph?.styleName) ?? this.defaultParagraphStyle;
9920
+ const levels = [elem.cssStyle, ...this.styleValueLevels(style, "span"),
9921
+ paragraph?.cssStyle, ...this.styleValueLevels(paragraphStyle, "span"),
9922
+ this.styleValuesForTarget(this.defaultCharacterStyle, "span"),
9923
+ this.styleValuesForTarget(this.defaultRunStyle, "span")];
9924
+ const value = (key) => levels.find(level => level?.[key] != null)?.[key];
9925
+ const language = (key) => value(key) ?? value("$lang");
9926
+ const themedFont = (font, language) => {
9927
+ const match = /^var\((--docx-(?:major|minor)(?:EastAsia|Bidi|Cs)-font)(?:-[A-Za-z]{4}, var\(\1\))?\)$/.exec(font ?? "");
9928
+ if (!match)
9929
+ return font;
9930
+ const script = themeScriptForLanguage(language);
9931
+ const base = `var(${match[1]}-fallback)`;
9932
+ return script ? `var(${match[1]}-${script}, ${base})` : base;
9933
+ };
9934
+ const text = elem.type == DomType.Run ? (elem.children ?? [])
9935
+ .filter(child => child.type == DomType.Text || child.type == DomType.DeletedText)
9936
+ .map(child => child.text).join("") : "";
9937
+ const forceComplex = value("--docx-complex-script");
9938
+ const complex = forceComplex == "true" || value("--docx-rtl-run") == "true"
9939
+ || (forceComplex != "false" && ((legacyComplexScriptCharacters.test(text)
9940
+ && !/[\p{Script=Latin}\p{Script=Cyrillic}\p{Script=Han}]/u.test(text))
9941
+ || isAdditionalComplexScriptRun(text)));
9942
+ const highAnsi = /[\p{Script=Cyrillic}\p{Script=Greek}]/u.test(text);
9943
+ const slots = complex ? ["complex", "ascii", "hansi", "eastasia"]
9944
+ : highAnsi ? ["hansi", "ascii", "eastasia", "complex"] : ["ascii", "hansi", "eastasia", "complex"];
9945
+ const fonts = slots.map(slot => {
9946
+ const font = value(`--docx-font-${slot}`);
9947
+ return slot == "eastasia" ? themedFont(font, language("$lang-eastAsia"))
9948
+ : slot == "complex" ? themedFont(font, language("$lang-bidi")) : font;
9949
+ }).filter(Boolean);
9950
+ if (fonts.length)
9951
+ this.setCssStyle(result, "font-family", [...new Set(fonts)].join(', '));
9952
+ if (complex && value("--docx-complex-font-size")) {
9953
+ this.setCssStyle(result, "font-size", value("--docx-complex-font-size"));
9954
+ this.setCssStyle(result, "min-height", value("--docx-complex-font-size"));
9955
+ }
9956
+ }
9661
9957
  isInsideTableCell(elem) {
9662
9958
  for (let p = elem.parent; p; p = p.parent) {
9663
9959
  if (p.type == DomType.Cell)
@@ -9665,13 +9961,32 @@
9665
9961
  }
9666
9962
  return false;
9667
9963
  }
9964
+ paragraphSnapToGrid(elem, style) {
9965
+ const key = "--docx-snap-to-grid";
9966
+ if (elem.cssStyle?.[key] != null)
9967
+ return elem.cssStyle[key];
9968
+ let current = elem.styleName ? style : this.defaultParagraphStyle;
9969
+ const numbering = this.effectiveParagraphNumbering(elem, style);
9970
+ const seen = new Set();
9971
+ while (current?.target == "p" && !seen.has(current)) {
9972
+ seen.add(current);
9973
+ const value = this.styleValue(current, "p", key);
9974
+ if (value != null)
9975
+ return value;
9976
+ current = this.findStyle(current.basedOn);
9977
+ }
9978
+ const numberingStyle = numbering && this.document?.numberingPart?.domNumberings
9979
+ ?.find(num => num.id == numbering.id && num.level == numbering.level)?.pStyle;
9980
+ return numberingStyle?.[key] ?? this.styleValue(this.defaultRunStyle, "p", key);
9981
+ }
9668
9982
  paragraphUsesDocumentGrid(elem, style) {
9669
- const linePitch = this.currentSectionProps?.docGrid?.linePitch;
9670
- if (!linePitch)
9983
+ const grid = this.currentSectionProps?.docGrid;
9984
+ const linePitch = grid?.linePitch;
9985
+ if (!linePitch || !grid.type || grid.type === "default")
9671
9986
  return false;
9672
9987
  if (this.isInsideTableCell(elem) && !this.document.settingsPart?.settings?.adjustLineHeightInTable)
9673
9988
  return false;
9674
- const snapToGrid = this.effectiveParagraphCssValue(elem, style, "--docx-snap-to-grid");
9989
+ const snapToGrid = this.paragraphSnapToGrid(elem, style);
9675
9990
  return snapToGrid == null || !/^(0|false|off)$/i.test(snapToGrid);
9676
9991
  }
9677
9992
  setCssStyle(element, name, value) {
@@ -9691,17 +10006,27 @@
9691
10006
  const linePitch = this.currentSectionProps.docGrid.linePitch;
9692
10007
  const lineHeight = this.effectiveParagraphCssValue(elem, style, "line-height");
9693
10008
  const lineSpacing = elem.lineSpacing ?? style?.paragraphProps?.lineSpacing;
10009
+ const exact = lineSpacing?.lineRule == "exact" || lineSpacing?.lineRule == "exactly";
10010
+ if (!exact && !this.compatibleTextBoxSpacing && result.dataset
10011
+ && ["lines", "linesAndChars"].includes(this.currentSectionProps.docGrid.type)) {
10012
+ const numeric = /^\d+(?:\.\d+)?$/.test(lineHeight ?? "") ? Number(lineHeight) : 1;
10013
+ if (numeric >= 1) {
10014
+ result.dataset.docxParagraphGridPitch = linePitch;
10015
+ result.dataset.docxParagraphGridMultiple = `${numeric}`;
10016
+ result.dataset.docxParagraphGridAtLeast = `${lineSpacing?.lineRule == "atLeast"}`;
10017
+ }
10018
+ }
9694
10019
  if (lineHeight) {
9695
- if (lineSpacing?.lineRule == "exact" || lineSpacing?.lineRule == "exactly")
10020
+ if (exact)
9696
10021
  return;
9697
- const comparableLineHeight = /^-?\d+(?:\.\d+)?$/.test(lineHeight)
9698
- ? `calc(${lineHeight} * 1em)`
9699
- : lineHeight;
10022
+ const comparableLineHeight = gridAutomaticLineHeight(lineHeight, linePitch);
9700
10023
  this.preserveGridInlineMetrics(result);
9701
10024
  this.setCssStyle(result, "line-height", `max(${comparableLineHeight}, ${linePitch})`);
9702
10025
  this.applyDocumentGridMinimumHeight(elem, style, result, linePitch);
9703
10026
  return;
9704
10027
  }
10028
+ this.preserveGridInlineMetrics(result);
10029
+ this.setCssStyle(result, "line-height", linePitch);
9705
10030
  this.applyDocumentGridMinimumHeight(elem, style, result, linePitch);
9706
10031
  }
9707
10032
  preserveGridInlineMetrics(result) {
@@ -9883,6 +10208,11 @@
9883
10208
  movedAny = true;
9884
10209
  continue;
9885
10210
  }
10211
+ const tail = article.lastElementChild;
10212
+ if (this.canRetainTablePrefix(tail, page) && this.splitOverflowBlock(tail, page, nextArticle)) {
10213
+ movedAny = true;
10214
+ continue;
10215
+ }
9886
10216
  let chunk = this.pickPaginationChunk(article);
9887
10217
  if (chunk.length == 0)
9888
10218
  break;
@@ -10696,6 +11026,8 @@
10696
11026
  splitParagraphBlock(paragraph, page, nextArticle) {
10697
11027
  if (!paragraph.hasChildNodes())
10698
11028
  return false;
11029
+ if (this.fitOversizedInlinePicture(paragraph, page))
11030
+ return false;
10699
11031
  const clone = this.cloneBlockShell(paragraph);
10700
11032
  clone.dataset.docxContinued = "true";
10701
11033
  nextArticle.prepend(clone);
@@ -10718,25 +11050,72 @@
10718
11050
  this.rebalanceWidowOrphan(paragraph, clone, page);
10719
11051
  return true;
10720
11052
  }
11053
+ fitOversizedInlinePicture(paragraph, page) {
11054
+ const article = paragraph.parentElement;
11055
+ if (article?.localName !== "article" || article.firstElementChild !== paragraph
11056
+ || page.querySelector(":scope > article > *") !== paragraph
11057
+ || paragraph.textContent?.trim() || paragraph.querySelector("table,math,object,canvas,video,[data-docx-note-reference]"))
11058
+ return false;
11059
+ const drawings = Array.from(paragraph.querySelectorAll("[data-docx-drawing]"));
11060
+ const drawing = drawings[0];
11061
+ if (drawings.length !== 1 || !drawing || drawing.children.length !== 1
11062
+ || paragraph.querySelectorAll("img").length !== 1 || drawing.dataset.docxFloat)
11063
+ return false;
11064
+ const picture = drawing.firstElementChild;
11065
+ if (picture.localName !== "img" && picture.dataset.docxImageCrop !== "true")
11066
+ return false;
11067
+ const view = paragraph.ownerDocument.defaultView;
11068
+ const style = view?.getComputedStyle(drawing);
11069
+ if (!view || !style || style.position === "absolute" || style.position === "fixed"
11070
+ || style.transform !== "none" || style.cssFloat !== "none")
11071
+ return false;
11072
+ const paragraphRect = paragraph.getBoundingClientRect();
11073
+ const drawingRect = drawing.getBoundingClientRect();
11074
+ const pageRect = page.getBoundingClientRect();
11075
+ const screenScale = page.clientHeight > 0 ? pageRect.height / page.clientHeight : 1;
11076
+ const bottomMargin = (parseFloat(view.getComputedStyle(paragraph).marginBottom) || 0) * screenScale;
11077
+ const overhead = Math.max(0, paragraphRect.height - drawingRect.height);
11078
+ const available = this.getPageBodyBottom(page) - paragraphRect.top - overhead - bottomMargin - screenScale;
11079
+ const width = parseFloat(style.width), height = parseFloat(style.height);
11080
+ if (![available, width, height, drawingRect.height].every(Number.isFinite)
11081
+ || available <= 0 || width <= 0 || height <= 0 || drawingRect.height <= available)
11082
+ return false;
11083
+ const ratio = available / drawingRect.height;
11084
+ drawing.style.width = `${width * ratio}px`;
11085
+ drawing.style.height = `${height * ratio}px`;
11086
+ picture.style.width = "100%";
11087
+ picture.style.height = "100%";
11088
+ drawing.dataset.docxPageFitScale = `${ratio}`;
11089
+ return true;
11090
+ }
10721
11091
  splitTableBlock(table, page, nextArticle) {
10722
11092
  const rows = this.tableContentRows(table);
10723
11093
  if (rows.length <= 1)
10724
11094
  return false;
11095
+ const repeatHeaders = rows.filter(r => r.dataset.docxRepeatHeader == "true");
11096
+ if (repeatHeaders.length && !this.fitsTableRowPrefix(rows, page))
11097
+ return false;
10725
11098
  const clone = this.cloneBlockShell(table);
10726
11099
  clone.dataset.docxContinued = "true";
10727
11100
  for (const child of Array.from(table.children)) {
10728
11101
  if (child.tagName?.toLowerCase() == "colgroup")
10729
11102
  clone.appendChild(child.cloneNode(true));
10730
11103
  }
10731
- for (const header of rows.filter(r => r.dataset.docxRepeatHeader == "true")) {
11104
+ for (const [index, header] of repeatHeaders.entries()) {
10732
11105
  const repeated = header.cloneNode(true);
10733
11106
  repeated.dataset.docxRepeatedHeader = "true";
11107
+ for (const cell of Array.from(repeated.cells)) {
11108
+ const headerRowsRemaining = repeatHeaders.length - index;
11109
+ if (cell.rowSpan === 0 || cell.rowSpan > headerRowsRemaining)
11110
+ cell.rowSpan = headerRowsRemaining;
11111
+ }
10734
11112
  clone.appendChild(repeated);
10735
11113
  }
10736
11114
  nextArticle.prepend(clone);
10737
11115
  let movedAny = false;
10738
11116
  let guard = 0;
10739
- while (this.isPageOverflowing(page) && this.tableContentRows(table).length > 1 && guard++ < 500) {
11117
+ const minimumSourceRows = repeatHeaders.length + 1;
11118
+ while (this.isPageOverflowing(page) && this.tableContentRows(table).length > minimumSourceRows && guard++ < 500) {
10740
11119
  const currentRows = this.tableContentRows(table).filter(r => r.dataset.docxRepeatedHeader != "true");
10741
11120
  const last = currentRows[currentRows.length - 1];
10742
11121
  if (!last)
@@ -10748,8 +11127,58 @@
10748
11127
  clone.remove();
10749
11128
  return false;
10750
11129
  }
11130
+ const sourceRowCount = this.tableContentRows(table).length;
11131
+ const firstContinuationRow = this.firstMovedTableRow(clone);
11132
+ for (let rowIndex = 0; rowIndex < sourceRowCount; rowIndex++) {
11133
+ let column = 0;
11134
+ for (const cell of Array.from(rows[rowIndex].cells)) {
11135
+ const nextColumn = column + cell.colSpan;
11136
+ const remainingSpan = rowIndex + cell.rowSpan - sourceRowCount;
11137
+ if (remainingSpan > 0) {
11138
+ const continuation = this.cloneBlockShell(cell);
11139
+ continuation.textContent = "";
11140
+ continuation.rowSpan = remainingSpan;
11141
+ continuation.dataset.docxContinued = "true";
11142
+ let targetColumn = 0;
11143
+ let anchor = null;
11144
+ for (const targetCell of Array.from(firstContinuationRow.cells)) {
11145
+ if (targetColumn >= column) {
11146
+ anchor = targetCell;
11147
+ break;
11148
+ }
11149
+ targetColumn += targetCell.colSpan;
11150
+ }
11151
+ if (anchor && targetColumn === column && anchor.style.display === "none")
11152
+ anchor.replaceWith(continuation);
11153
+ else
11154
+ firstContinuationRow.insertBefore(continuation, anchor);
11155
+ cell.rowSpan = sourceRowCount - rowIndex;
11156
+ }
11157
+ column = nextColumn;
11158
+ }
11159
+ }
10751
11160
  return true;
10752
11161
  }
11162
+ canRetainTablePrefix(block, page) {
11163
+ if (block?.localName !== "table")
11164
+ return false;
11165
+ const style = getComputedStyle(block);
11166
+ if (style.position !== "static" || style.cssFloat !== "none" || block.dataset.docxFloat)
11167
+ return false;
11168
+ return this.fitsTableRowPrefix(this.tableContentRows(block), page);
11169
+ }
11170
+ fitsTableRowPrefix(rows, page) {
11171
+ if (rows.length < 2 || rows.some((row, index) => Array.from(row.cells).some(cell => cell.rowSpan < 1 || index + cell.rowSpan > rows.length)))
11172
+ return false;
11173
+ const firstBody = rows.findIndex(row => row.dataset.docxRepeatHeader != "true");
11174
+ if (firstBody < 0 || rows.slice(firstBody + 1).some(row => row.dataset.docxRepeatHeader == "true"))
11175
+ return false;
11176
+ const bottom = this.getPageBodyBottom(page) + (this.options.paginationTolerance ?? 2);
11177
+ return rows.slice(0, firstBody + 1).every(row => {
11178
+ const rect = row.getBoundingClientRect();
11179
+ return rect.height > 0 && rect.bottom <= bottom;
11180
+ });
11181
+ }
10753
11182
  cloneBlockShell(element) {
10754
11183
  const clone = element.cloneNode(false);
10755
11184
  clone.removeAttribute("id");
@@ -11030,7 +11459,7 @@
11030
11459
  wrapperStyle = `@media not print { ${wrapperStyle} }`;
11031
11460
  }
11032
11461
  var styleText = `${wrapperStyle}
11033
- .${c} { --docx-auto-color: ${autoColor}; color: var(--docx-auto-color); font-size: 10.5pt; font-family: var(--docx-minorHAnsi-font, "Times New Roman", serif); hyphens: auto; text-underline-position: from-font; font-kerning: normal; font-variant-ligatures: common-ligatures contextual; text-rendering: optimizeLegibility; line-break: auto; }
11462
+ .${c} { --docx-auto-color: ${autoColor}; color: var(--docx-auto-color); font-size: 10.5pt; font-family: var(--docx-minorHAnsi-font, "Times New Roman", serif); line-height: normal; hyphens: auto; text-underline-position: from-font; font-kerning: normal; font-variant-ligatures: common-ligatures contextual; text-rendering: optimizeLegibility; line-break: auto; }
11034
11463
  section.${c} { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: visible; isolation: isolate; }
11035
11464
  section.${c}>header, section.${c}>footer { flex-shrink: 0; }
11036
11465
  section.${c}>[data-docx-note-list] { flex-shrink: 0; }
@@ -11421,6 +11850,7 @@ section.${c}>footer { z-index: 1; }
11421
11850
  }
11422
11851
  const children = frameParagraphs
11423
11852
  .flatMap(item => asArray(this.renderElement(item)).filter(node => node != null));
11853
+ this.applyFlowParagraphSpacing(children);
11424
11854
  const frame = this.h({
11425
11855
  tagName: "div",
11426
11856
  className: `${this.className}-paragraph-frame`,
@@ -11440,6 +11870,7 @@ section.${c}>footer { z-index: 1; }
11440
11870
  }
11441
11871
  result.push(...asArray(this.renderElement(elems[i])).filter(e => e != null));
11442
11872
  }
11873
+ this.applyFlowParagraphSpacing(result);
11443
11874
  if (into)
11444
11875
  result.forEach(c => into.appendChild(isString(c) ? document.createTextNode(c) : c));
11445
11876
  return result;
@@ -11639,7 +12070,7 @@ section.${c}>footer { z-index: 1; }
11639
12070
  const style = this.findStyle(this.currentParagraph?.styleName);
11640
12071
  const isTocParagraph = this.isTocParagraphStyle(this.currentParagraph?.styleName, style);
11641
12072
  const isNumberedTocLeader = !!trailingLeader
11642
- && !!(this.currentParagraph?.numbering ?? style?.paragraphProps?.numbering)
12073
+ && !!this.effectiveParagraphNumbering(this.currentParagraph, style)
11643
12074
  && isTocParagraph;
11644
12075
  if (!trailingLeader)
11645
12076
  return stop;
@@ -11683,17 +12114,22 @@ section.${c}>footer { z-index: 1; }
11683
12114
  children = [flow];
11684
12115
  }
11685
12116
  var result = this.toHTML(elem, ns.html, "p", this.wrapTabLeaderChildren(children, true));
12117
+ this.applyParagraphAutoSpacing(elem, style, result);
12118
+ this.applyTextBoxFontInheritance(elem, style, result);
12119
+ this.applyRunFontSlots(elem, style, result);
11686
12120
  if (this.options.exposeDisplayTargets && elem.displayAddress) {
11687
12121
  const part = this.currentPart ?? this.document.documentPart;
11688
12122
  result.setAttribute("data-office-target", `${part.path}#${elem.displayAddress}`);
11689
12123
  }
11690
- const snapToGrid = this.effectiveParagraphCssValue(elem, style, "--docx-snap-to-grid");
12124
+ const snapToGrid = this.paragraphSnapToGrid(elem, style);
11691
12125
  if (/^(0|false|off)$/i.test(snapToGrid ?? ""))
11692
12126
  result.style.letterSpacing = "normal";
11693
12127
  this.currentParagraph = previousParagraph;
11694
12128
  this.currentParagraphTabIndex = previousParagraphTabIndex;
11695
12129
  this.currentParagraphTabCount = previousParagraphTabCount;
11696
- const numbering = elem.numbering ?? style?.paragraphProps?.numbering;
12130
+ const numbering = elem.props?.pageBreakContinuation ? null : this.effectiveParagraphNumbering(elem, style);
12131
+ if (elem.props?.pageBreakEmpty)
12132
+ result.style.display = "none";
11697
12133
  if (numbering) {
11698
12134
  result.classList.add(this.numberingClass(numbering.id, numbering.level));
11699
12135
  }
@@ -11716,6 +12152,16 @@ section.${c}>footer { z-index: 1; }
11716
12152
  result.dataset.docxWidowControl = "true";
11717
12153
  }
11718
12154
  this.applyDocumentGridLinePitch(elem, style, result);
12155
+ if (this.compatibleTextBoxSpacing)
12156
+ this.setCssStyle(result, "text-autospace", this.textBoxAutospace(elem, style));
12157
+ const lineRule = (elem.lineSpacing ?? style?.paragraphProps?.lineSpacing)?.lineRule;
12158
+ if (this.compatibleTextBoxSpacing && ["lines", "linesAndChars"].includes(this.currentSectionProps?.docGrid?.type)
12159
+ && this.paragraphUsesDocumentGrid(elem, style)
12160
+ && lineRule != "exact" && lineRule != "exactly") {
12161
+ result.dataset.docxTextboxGridPitch = this.currentSectionProps.docGrid.linePitch;
12162
+ result.dataset.docxTextboxBaseLineHeight = result.style.lineHeight ?? "";
12163
+ result.style.flexShrink = "0";
12164
+ }
11719
12165
  const leaderTab = elem.tabs?.find(t => this.isLeaderTabStop(t));
11720
12166
  if (leaderTab) {
11721
12167
  result.classList.add(`${this.className}-tab-leader-paragraph`);
@@ -11739,7 +12185,7 @@ section.${c}>footer { z-index: 1; }
11739
12185
  return result;
11740
12186
  }
11741
12187
  uniformParagraphTextScale(paragraph, style) {
11742
- if (paragraph.numbering || style?.paragraphProps?.numbering || paragraph.frame
12188
+ if (this.effectiveParagraphNumbering(paragraph, style) || paragraph.frame
11743
12189
  || this.effectiveParagraphCssValue(paragraph, style, "writing-mode"))
11744
12190
  return null;
11745
12191
  const key = "--docx-text-scale";
@@ -11832,6 +12278,130 @@ section.${c}>footer { z-index: 1; }
11832
12278
  }
11833
12279
  return true;
11834
12280
  }
12281
+ textBoxGridLineHeight(natural, pitch) {
12282
+ if (!Number.isFinite(natural) || !Number.isFinite(pitch) || natural < 0 || pitch <= 0)
12283
+ return null;
12284
+ return Math.max(1, Math.ceil((natural - 1 / 64) / pitch)) * pitch;
12285
+ }
12286
+ refreshTextBoxLineGrid(root) {
12287
+ const view = root.ownerDocument?.defaultView;
12288
+ const paragraphs = Array.from(root.querySelectorAll("[data-docx-textbox-grid-pitch]"))
12289
+ .filter(paragraph => this.ownsLayoutElement(paragraph));
12290
+ if (!view || !paragraphs.length)
12291
+ return;
12292
+ const probe = root.ownerDocument.createElement("span");
12293
+ Object.assign(probe.style, {
12294
+ position: "absolute", visibility: "hidden", pointerEvents: "none", display: "inline-block",
12295
+ whiteSpace: "pre", width: "max-content", margin: "0", padding: "0", border: "0", minHeight: "0"
12296
+ });
12297
+ probe.setAttribute("aria-hidden", "true");
12298
+ const scope = root.getRootNode();
12299
+ const probeParent = scope.nodeType == 11 && "host" in scope ? scope : root.ownerDocument.body;
12300
+ probeParent.appendChild(probe);
12301
+ const setFont = (target, element, lineHeight = "normal") => {
12302
+ const style = view.getComputedStyle(element);
12303
+ Object.assign(target.style, {
12304
+ fontFamily: style.fontFamily, fontSize: style.fontSize, fontWeight: style.fontWeight,
12305
+ fontStyle: style.fontStyle, fontStretch: style.fontStretch, verticalAlign: style.verticalAlign, lineHeight
12306
+ });
12307
+ };
12308
+ try {
12309
+ for (const paragraph of paragraphs) {
12310
+ if (paragraph.querySelector("svg, img, table, math, [data-docx-drawing]"))
12311
+ continue;
12312
+ this.preserveGridInlineMetrics(paragraph);
12313
+ probe.style.height = paragraph.dataset.docxTextboxGridPitch;
12314
+ const pitch = parseFloat(view.getComputedStyle(probe).height);
12315
+ setFont(probe, paragraph, paragraph.dataset.docxTextboxBaseLineHeight || "normal");
12316
+ probe.style.height = "auto";
12317
+ probe.replaceChildren();
12318
+ const walker = root.ownerDocument.createTreeWalker(paragraph, 4);
12319
+ while (walker.nextNode()) {
12320
+ const node = walker.currentNode;
12321
+ const parent = node.parentElement;
12322
+ if (!node.textContent || !parent || !Array.from(parent.getClientRects()).some(rect => rect.width > 0 && rect.height > 0))
12323
+ continue;
12324
+ const lineHeight = parent == paragraph ? paragraph.dataset.docxTextboxBaseLineHeight : parent.style.lineHeight;
12325
+ const span = root.ownerDocument.createElement("span");
12326
+ setFont(span, parent, lineHeight || "normal");
12327
+ span.style.whiteSpace = "pre";
12328
+ span.textContent = node.textContent.replace(/[\r\n]/g, " ");
12329
+ probe.appendChild(span);
12330
+ }
12331
+ if (!probe.hasChildNodes())
12332
+ probe.textContent = "\u00a0";
12333
+ const natural = parseFloat(view.getComputedStyle(probe).height);
12334
+ const height = this.textBoxGridLineHeight(natural, pitch);
12335
+ if (height != null)
12336
+ paragraph.style.lineHeight = `${Math.round(height * 1000) / 1000}px`;
12337
+ }
12338
+ }
12339
+ finally {
12340
+ probe.remove();
12341
+ }
12342
+ }
12343
+ refreshParagraphLineGrid(root) {
12344
+ const view = root.ownerDocument?.defaultView;
12345
+ const paragraphs = Array.from(root.querySelectorAll("[data-docx-paragraph-grid-pitch]"))
12346
+ .filter(paragraph => this.ownsLayoutElement(paragraph));
12347
+ if (!view || !paragraphs.length)
12348
+ return;
12349
+ const probe = root.ownerDocument.createElement("span");
12350
+ Object.assign(probe.style, { position: "absolute", visibility: "hidden", pointerEvents: "none",
12351
+ display: "inline-block", whiteSpace: "pre", width: "max-content", margin: "0", padding: "0", border: "0" });
12352
+ probe.setAttribute("aria-hidden", "true");
12353
+ probe.textContent = "Mg";
12354
+ const scope = root.getRootNode();
12355
+ (scope.nodeType == 11 && "host" in scope ? scope : root.ownerDocument.body).appendChild(probe);
12356
+ const cache = new Map();
12357
+ const natural = (style) => {
12358
+ const font = { fontFamily: style.fontFamily, fontSize: style.fontSize, fontWeight: style.fontWeight,
12359
+ fontStyle: style.fontStyle, fontStretch: style.fontStretch, lineHeight: "normal", height: "auto" };
12360
+ const key = JSON.stringify(font);
12361
+ if (!cache.has(key)) {
12362
+ Object.assign(probe.style, font);
12363
+ cache.set(key, probe.getBoundingClientRect().height);
12364
+ }
12365
+ return cache.get(key);
12366
+ };
12367
+ try {
12368
+ for (const paragraph of paragraphs) {
12369
+ const style = view.getComputedStyle(paragraph), size = parseFloat(style.fontSize);
12370
+ probe.style.height = paragraph.dataset.docxParagraphGridPitch;
12371
+ const pitch = parseFloat(view.getComputedStyle(probe).height);
12372
+ const multiplier = Number(paragraph.dataset.docxParagraphGridMultiple);
12373
+ let height = gridFontLineHeight(natural(style), pitch, multiplier);
12374
+ if (height == null)
12375
+ continue;
12376
+ if (paragraph.dataset.docxParagraphGridAtLeast === "true")
12377
+ height = Math.max(height, parseFloat(style.lineHeight) || 0);
12378
+ paragraph.style.lineHeight = `${height}px`;
12379
+ const visit = (parent, script = false) => {
12380
+ for (const child of Array.from(parent.children)) {
12381
+ if (child.namespaceURI !== ns.html || !/^(span|a|sub|sup|b|i|u|s|strike|strong|em)$/.test(child.localName))
12382
+ continue;
12383
+ const own = child.dataset.docxGridOwnedHeight === "true";
12384
+ if ((!own && child.style.lineHeight && child.style.lineHeight !== "normal")
12385
+ || (child.style.display && child.style.display !== "inline" && !child.dataset.docxTextScale)
12386
+ || /^(absolute|fixed)$/.test(child.style.position) || (child.style.cssFloat && child.style.cssFloat !== "none"))
12387
+ continue;
12388
+ const childStyle = view.getComputedStyle(child);
12389
+ const raised = script || /^(super|sub)$/.test(childStyle.verticalAlign);
12390
+ const breakOnly = !child.textContent && !!child.querySelector("br") && !child.querySelector("img,svg,math");
12391
+ const childHeight = breakOnly || (raised && parseFloat(childStyle.fontSize) <= size) ? 0
12392
+ : Math.max(height, gridFontLineHeight(natural(childStyle), pitch) ?? height);
12393
+ child.style.lineHeight = `${childHeight}px`;
12394
+ child.dataset.docxGridOwnedHeight = "true";
12395
+ visit(child, raised);
12396
+ }
12397
+ };
12398
+ visit(paragraph);
12399
+ }
12400
+ }
12401
+ finally {
12402
+ probe.remove();
12403
+ }
12404
+ }
11835
12405
  async prepareLayout(root, generation = getLayoutGeneration(root)) {
11836
12406
  if (!root.isConnected || !generation.isCurrent())
11837
12407
  return;
@@ -11852,6 +12422,8 @@ section.${c}>footer { z-index: 1; }
11852
12422
  (owner ?? root).appendChild(this.commentLayer.root);
11853
12423
  }
11854
12424
  }
12425
+ this.refreshParagraphLineGrid(root);
12426
+ this.refreshTextBoxLineGrid(root);
11855
12427
  this.refreshTabStops(root);
11856
12428
  this.refreshAnchors(root);
11857
12429
  await this.commentLayer?.bind(root, generation);
@@ -12228,17 +12800,31 @@ section.${c}>footer { z-index: 1; }
12228
12800
  return result;
12229
12801
  }
12230
12802
  renderImage(elem) {
12231
- let result = this.toHTML(elem, ns.html, "img", []);
12803
+ const rect = elem.srcRect;
12804
+ const cropWidth = rect ? 1 - rect[0] - rect[2] : 1;
12805
+ const cropHeight = rect ? 1 - rect[1] - rect[3] : 1;
12806
+ const cropped = rect?.length === 4 && rect.some(x => x !== 0)
12807
+ && rect.every(Number.isFinite) && cropWidth > 0 && cropHeight > 0
12808
+ && Number.isFinite(100 / cropWidth) && Number.isFinite(100 / cropHeight);
12809
+ const result = this.toHTML(elem, ns.html, cropped ? "span" : "img", []);
12810
+ const image = cropped ? this.h({ tagName: "img" }) : result;
12232
12811
  let transform = elem.cssStyle?.transform;
12233
12812
  if (elem.alt)
12234
- result.alt = elem.alt;
12813
+ image.alt = elem.alt;
12235
12814
  if (elem.title)
12236
- result.title = elem.title;
12237
- if (elem.srcRect && elem.srcRect.some(x => x != 0)) {
12238
- var [left, top, right, bottom] = elem.srcRect;
12239
- transform = `${transform ?? ''} scale(${1 / (1 - left - right)}, ${1 / (1 - top - bottom)})`;
12240
- result.style.clipPath = `inset(${(100 * top).toFixed(2)}% ${(100 * right).toFixed(2)}% ${(100 * bottom).toFixed(2)}% ${(100 * left).toFixed(2)}%)`;
12241
- result.style.transformOrigin = "top left";
12815
+ image.title = elem.title;
12816
+ if (cropped) {
12817
+ result.setAttribute("data-docx-image-crop", "true");
12818
+ result.style.overflow = "hidden";
12819
+ result.style.position = "relative";
12820
+ Object.assign(image.style, {
12821
+ position: "absolute", display: "block", margin: "0",
12822
+ left: `${ -100 * rect[0] / cropWidth}%`,
12823
+ top: `${ -100 * rect[1] / cropHeight}%`,
12824
+ width: `${100 / cropWidth}%`, height: `${100 / cropHeight}%`,
12825
+ maxWidth: "none", maxHeight: "none", objectFit: "fill"
12826
+ });
12827
+ result.appendChild(image);
12242
12828
  }
12243
12829
  if (elem.rotation)
12244
12830
  transform = `rotate(${elem.rotation}deg) ${transform ?? ''}`;
@@ -12246,7 +12832,7 @@ section.${c}>footer { z-index: 1; }
12246
12832
  if (this.document && elem.src) {
12247
12833
  this.tasks.push(this.document.loadDocumentImage(elem.src, this.currentPart, this.options.externalResourcePolicy).then(x => {
12248
12834
  if (x)
12249
- result.setAttribute("src", x);
12835
+ image.setAttribute("src", x);
12250
12836
  }));
12251
12837
  }
12252
12838
  return result;
@@ -12268,9 +12854,17 @@ section.${c}>footer { z-index: 1; }
12268
12854
  }
12269
12855
  renderDmlTextBox(elem) {
12270
12856
  const previousParagraph = this.currentParagraph;
12857
+ const previousSpacing = this.compatibleTextBoxSpacing;
12271
12858
  this.currentParagraph = null;
12272
- const children = this.renderElements(elem.children);
12273
- this.currentParagraph = previousParagraph;
12859
+ this.compatibleTextBoxSpacing = elem.props?.textCompatibleLineSpacing === true;
12860
+ let children;
12861
+ try {
12862
+ children = this.renderElements(elem.children);
12863
+ }
12864
+ finally {
12865
+ this.currentParagraph = previousParagraph;
12866
+ this.compatibleTextBoxSpacing = previousSpacing;
12867
+ }
12274
12868
  const content = this.h({
12275
12869
  tagName: "div",
12276
12870
  className: `${this.className}-shape-textbox`,
@@ -13971,6 +14565,8 @@ section.${c}>footer { z-index: 1; }
13971
14565
  }
13972
14566
  const result = this.toHTML(elem, ns.html, "span", children);
13973
14567
  const style = this.findStyle(elem.styleName);
14568
+ this.applyTextBoxFontInheritance(elem, style, result);
14569
+ this.applyRunFontSlots(elem, style, result);
13974
14570
  const snapToGrid = elem.cssStyle?.["--docx-snap-to-grid"] ?? this.styleValue(style, "span", "--docx-snap-to-grid");
13975
14571
  if (/^(0|false|off)$/i.test(snapToGrid ?? ""))
13976
14572
  result.style.letterSpacing = "normal";
@@ -14298,6 +14894,11 @@ section.${c}>footer { z-index: 1; }
14298
14894
  rect.setAttribute("width", `${bounds.width}`);
14299
14895
  rect.setAttribute("height", `${bounds.height}`);
14300
14896
  this.applyVmlAttributes(rect, elem.attrs, new Set(["x", "y", "width", "height"]));
14897
+ if (elem.roundRectArc != null) {
14898
+ const radius = Math.min(bounds.width, bounds.height) * elem.roundRectArc / 2;
14899
+ rect.setAttribute("rx", `${radius}`);
14900
+ rect.setAttribute("ry", `${radius}`);
14901
+ }
14301
14902
  result = rect;
14302
14903
  break;
14303
14904
  }
@@ -14711,8 +15312,11 @@ section.${c}>footer { z-index: 1; }
14711
15312
  if (!style)
14712
15313
  return style;
14713
15314
  const result = { ...style };
14714
- if (normalized)
15315
+ if (normalized) {
14715
15316
  delete result["font-family"];
15317
+ delete result["--docx-latin-font-family"];
15318
+ delete result["--docx-partial-eastasia-font"];
15319
+ }
14716
15320
  return result;
14717
15321
  }
14718
15322
  normalizeNumberingLevelText(text, format, runStyle) {