@windoc/core 0.3.26 → 0.3.28

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.
package/dist/index.js CHANGED
@@ -78,7 +78,7 @@ __export(index_exports, {
78
78
  module.exports = __toCommonJS(index_exports);
79
79
 
80
80
  // src/version.ts
81
- var version = "0.3.26";
81
+ var version = "0.3.28";
82
82
 
83
83
  // src/dataset/enum/Common.ts
84
84
  var MaxHeightRatio = /* @__PURE__ */ ((MaxHeightRatio2) => {
@@ -19074,10 +19074,11 @@ var ListParticle = class {
19074
19074
  const curIndex = isSetCursor ? endIndex : startIndex;
19075
19075
  this.draw.render({ curIndex, isSetCursor });
19076
19076
  }
19077
- getListIndentWidth(element) {
19078
- const { scale } = this.options;
19077
+ // Each level indents by the list's marker column, so a nested marker starts
19078
+ // exactly where its parent's text starts
19079
+ getListIndentWidth(element, markerWidth) {
19079
19080
  const level = element.listLevel ?? 0;
19080
- return level * INDENT_PER_LEVEL * scale;
19081
+ return level * markerWidth;
19081
19082
  }
19082
19083
  _getListMarkerStyleElement(elementList, startIndex = 0) {
19083
19084
  const startElement = elementList[startIndex];
@@ -19190,10 +19191,11 @@ var ListParticle = class {
19190
19191
  if (!cycle) return "\u25CF";
19191
19192
  return cycle[level % cycle.length];
19192
19193
  }
19193
- drawListStyle(ctx, row, position) {
19194
- const { elementList, offsetX, listIndex, ascent } = row;
19194
+ // Marker x for a list row's first line (shared by canvas drawing and export)
19195
+ getListMarkerX(row, position) {
19196
+ const { elementList, offsetX } = row;
19195
19197
  const startElement = elementList[0];
19196
- if (startElement.value !== ZERO || startElement.listWrap) return;
19198
+ if (startElement.value !== ZERO || startElement.listWrap) return null;
19197
19199
  let tabWidth = 0;
19198
19200
  const { defaultTabWidth, scale } = this.options;
19199
19201
  for (let i = 1; i < elementList.length; i++) {
@@ -19203,12 +19205,30 @@ var ListParticle = class {
19203
19205
  }
19204
19206
  const {
19205
19207
  coordinate: {
19206
- leftTop: [startX, startY]
19208
+ leftTop: [startX]
19207
19209
  }
19208
19210
  } = position;
19209
- const indentWidth = this.getListIndentWidth(startElement);
19210
- const x = startX - offsetX + tabWidth + indentWidth;
19211
- const y = startY + ascent;
19211
+ const level = startElement.listLevel ?? 0;
19212
+ const markerWidth = offsetX / (level + 1);
19213
+ return startX - markerWidth + tabWidth;
19214
+ }
19215
+ getListMarker(row) {
19216
+ const startElement = row.elementList[0];
19217
+ if (startElement.listStyle === "checkbox" /* CHECKBOX */) return null;
19218
+ const text = this._getListMarkerText(startElement, row.listIndex);
19219
+ if (!text) return null;
19220
+ return {
19221
+ text,
19222
+ styleElement: this._getListMarkerStyleElement(row.elementList)
19223
+ };
19224
+ }
19225
+ drawListStyle(ctx, row, position) {
19226
+ const { elementList, ascent } = row;
19227
+ const startElement = elementList[0];
19228
+ const x = this.getListMarkerX(row, position);
19229
+ if (x === null) return;
19230
+ const { scale } = this.options;
19231
+ const y = position.coordinate.leftTop[1] + ascent;
19212
19232
  if (startElement.listStyle === "checkbox" /* CHECKBOX */) {
19213
19233
  const { width, height, gap } = this.options.checkbox;
19214
19234
  const checkboxRowElement = {
@@ -19233,12 +19253,11 @@ var ListParticle = class {
19233
19253
  }
19234
19254
  });
19235
19255
  } else {
19236
- const text = this._getListMarkerText(startElement, listIndex);
19237
- if (!text) return;
19238
- const markerStyleElement = this._getListMarkerStyleElement(elementList);
19256
+ const marker = this.getListMarker(row);
19257
+ if (!marker) return;
19239
19258
  ctx.save();
19240
- ctx.font = this.draw.getElementFont(markerStyleElement, scale);
19241
- ctx.fillText(text, x, y);
19259
+ ctx.font = this.draw.getElementFont(marker.styleElement, scale);
19260
+ ctx.fillText(marker.text, x, y);
19242
19261
  ctx.restore();
19243
19262
  }
19244
19263
  }
@@ -22474,8 +22493,9 @@ var Draw = class {
22474
22493
  boundingBoxAscent: 0,
22475
22494
  boundingBoxDescent: 0
22476
22495
  };
22477
- const listIndentWidth = element.listId ? this.listParticle.getListIndentWidth(element) : 0;
22478
- const offsetX = curRow.offsetX || (element.listId && listStyleMap.get(element.listId) || 0) + listIndentWidth || 0;
22496
+ const listMarkerWidth = element.listId && listStyleMap.get(element.listId) || 0;
22497
+ const listIndentWidth = element.listId ? this.listParticle.getListIndentWidth(element, listMarkerWidth) : 0;
22498
+ const offsetX = curRow.offsetX || listMarkerWidth + listIndentWidth || 0;
22479
22499
  const availableWidth = innerWidth - offsetX;
22480
22500
  const isStartElement = curRow.elementList.length === 1;
22481
22501
  x += isStartElement ? offsetX : 0;
@@ -23223,7 +23243,10 @@ var Draw = class {
23223
23243
  if (element.listId) {
23224
23244
  row.isList = true;
23225
23245
  const baseListOffset = listStyleMap.get(element.listId) || 0;
23226
- const rowListIndent = this.listParticle.getListIndentWidth(element);
23246
+ const rowListIndent = this.listParticle.getListIndentWidth(
23247
+ element,
23248
+ baseListOffset
23249
+ );
23227
23250
  row.offsetX = baseListOffset + rowListIndent;
23228
23251
  row.listIndex = listState.listIndex;
23229
23252
  }
@@ -24426,1247 +24449,1015 @@ var Command = class {
24426
24449
  }
24427
24450
  };
24428
24451
 
24452
+ // src/utils/docxLayout.ts
24453
+ var import_docx2 = require("docx");
24454
+
24429
24455
  // src/utils/docx.ts
24430
24456
  var import_docx = require("docx");
24431
24457
  var DEFAULT_DOCX_FILE_NAME = "document.docx";
24432
24458
  var DEFAULT_IMAGE_WIDTH = 320;
24433
24459
  var DEFAULT_IMAGE_HEIGHT = 180;
24434
- var DEFAULT_LINE_HEIGHT = 1.15;
24435
- var DOCX_FOOTER_TEXT_COLOR = "#000000";
24436
- var docxBulletCharMap = {
24437
- ["disc" /* DISC */]: "\u2022",
24438
- ["circle" /* CIRCLE */]: "\u25E6",
24439
- ["square" /* SQUARE */]: "\u25A0",
24440
- ["checkbox" /* CHECKBOX */]: "\u2611"
24441
- };
24442
- var titleHeadingMap = {
24443
- ["first" /* FIRST */]: import_docx.HeadingLevel.HEADING_1,
24444
- ["second" /* SECOND */]: import_docx.HeadingLevel.HEADING_2,
24445
- ["third" /* THIRD */]: import_docx.HeadingLevel.HEADING_3,
24446
- ["fourth" /* FOURTH */]: import_docx.HeadingLevel.HEADING_4,
24447
- ["fifth" /* FIFTH */]: import_docx.HeadingLevel.HEADING_5,
24448
- ["sixth" /* SIXTH */]: import_docx.HeadingLevel.HEADING_6
24449
- };
24450
- var orderedStyleFormatMap = {
24451
- ["decimal" /* DECIMAL */]: import_docx.LevelFormat.DECIMAL,
24452
- ["lowerAlpha" /* LOWER_ALPHA */]: import_docx.LevelFormat.LOWER_LETTER,
24453
- ["upperAlpha" /* UPPER_ALPHA */]: import_docx.LevelFormat.UPPER_LETTER,
24454
- ["lowerRoman" /* LOWER_ROMAN */]: import_docx.LevelFormat.LOWER_ROMAN,
24455
- ["upperRoman" /* UPPER_ROMAN */]: import_docx.LevelFormat.UPPER_ROMAN,
24456
- ["decimalParen" /* DECIMAL_PAREN */]: import_docx.LevelFormat.DECIMAL,
24457
- decimalZero: import_docx.LevelFormat.DECIMAL_ZERO,
24458
- lowerAlphaParen: import_docx.LevelFormat.LOWER_LETTER,
24459
- lowerRomanParen: import_docx.LevelFormat.LOWER_ROMAN,
24460
- outline: import_docx.LevelFormat.DECIMAL
24461
- };
24462
- async function exportEditorDataToDocx(payload, options = {}) {
24463
- const fileName = normalizeDocxFileName(options.fileName);
24464
- const file = await createDocxDocument(payload);
24465
- const blob = await import_docx.Packer.toBlob(file);
24460
+ async function loadImagePayload(src) {
24461
+ const source = src.trim();
24462
+ if (source.startsWith("data:")) {
24463
+ return getImagePayloadFromDataUrl(source);
24464
+ }
24465
+ const response = await fetch(source);
24466
+ if (!response.ok) {
24467
+ throw new Error(`Image request failed: ${response.status}`);
24468
+ }
24469
+ const contentType = response.headers.get("content-type") || "";
24470
+ const data2 = await response.arrayBuffer();
24471
+ return normalizeImagePayload(data2, contentType);
24472
+ }
24473
+ async function getImagePayloadFromDataUrl(src) {
24474
+ const [, meta = "", encoded = ""] = src.match(/^data:([^,]*),(.*)$/) || [];
24475
+ const mime = meta.split(";")[0] || "";
24476
+ const isBase64 = meta.includes(";base64");
24477
+ const text = isBase64 ? atob(encoded) : decodeURIComponent(encoded);
24478
+ const bytes = new Uint8Array(text.length);
24479
+ for (let i = 0; i < text.length; i++) {
24480
+ bytes[i] = text.charCodeAt(i);
24481
+ }
24482
+ return normalizeImagePayload(bytes.buffer, mime);
24483
+ }
24484
+ async function normalizeImagePayload(data2, mime) {
24485
+ const type = getRegularImageType(mime);
24486
+ if (type) {
24487
+ return {
24488
+ type,
24489
+ data: data2
24490
+ };
24491
+ }
24492
+ if (mime.includes("svg")) {
24493
+ return {
24494
+ type: "svg",
24495
+ data: data2,
24496
+ fallbackPng: await rasterizeSvgToPng(data2)
24497
+ };
24498
+ }
24499
+ const fallbackPng = await rasterizeImageToPng(data2, mime);
24466
24500
  return {
24467
- blob,
24468
- fileName
24501
+ type: "png",
24502
+ data: fallbackPng
24469
24503
  };
24470
24504
  }
24471
- async function createDocxDocument(payload) {
24472
- const { data: data2, options } = payload;
24473
- const editorOptions = options;
24474
- const context = createSerializeContext();
24475
- const headerChildren = editorOptions.header.disabled ? [] : await serializeElementList(data2.header || [], editorOptions, context);
24476
- const docxFooterElementList = forceDocxFooterTextColor(data2.footer || []);
24477
- const footerChildren = editorOptions.footer.disabled ? [] : await serializeElementList(
24478
- docxFooterElementList,
24479
- editorOptions,
24480
- context
24481
- );
24482
- const pageNumberParagraph = createPageNumberParagraph(
24483
- {
24484
- ...editorOptions.pageNumber,
24485
- color: DOCX_FOOTER_TEXT_COLOR
24505
+ async function rasterizeSvgToPng(data2) {
24506
+ return rasterizeImageToPng(data2, "image/svg+xml");
24507
+ }
24508
+ async function rasterizeImageToPng(data2, mime) {
24509
+ const blob = new Blob([data2], {
24510
+ type: mime || "image/png"
24511
+ });
24512
+ const url = URL.createObjectURL(blob);
24513
+ try {
24514
+ const image = await loadHtmlImage(url);
24515
+ const canvas = document.createElement("canvas");
24516
+ canvas.width = image.naturalWidth || DEFAULT_IMAGE_WIDTH;
24517
+ canvas.height = image.naturalHeight || DEFAULT_IMAGE_HEIGHT;
24518
+ const context = canvas.getContext("2d");
24519
+ if (!context) {
24520
+ throw new Error("Canvas context is unavailable");
24486
24521
  }
24487
- );
24488
- if (pageNumberParagraph) {
24489
- footerChildren.push(pageNumberParagraph);
24522
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
24523
+ const pngBlob = await new Promise((resolve, reject) => {
24524
+ canvas.toBlob((output) => {
24525
+ if (output) {
24526
+ resolve(output);
24527
+ } else {
24528
+ reject(new Error("Failed to create PNG blob"));
24529
+ }
24530
+ }, "image/png");
24531
+ });
24532
+ return await pngBlob.arrayBuffer();
24533
+ } finally {
24534
+ URL.revokeObjectURL(url);
24490
24535
  }
24491
- const sectionChildren = await serializeElementList(
24492
- data2.main,
24493
- editorOptions,
24494
- context
24495
- );
24496
- const { width, height, paperDirection } = editorOptions;
24497
- const pageWidth = paperDirection === "horizontal" /* HORIZONTAL */ ? height : width;
24498
- const pageHeight = paperDirection === "horizontal" /* HORIZONTAL */ ? width : height;
24499
- return new import_docx.Document({
24500
- features: {
24501
- updateFields: true
24502
- },
24503
- numbering: {
24504
- config: createNumberingConfig()
24536
+ }
24537
+ function loadHtmlImage(src) {
24538
+ return new Promise((resolve, reject) => {
24539
+ const image = new Image();
24540
+ image.onload = () => resolve(image);
24541
+ image.onerror = () => reject(new Error("Failed to load image"));
24542
+ image.src = src;
24543
+ });
24544
+ }
24545
+ function mapUnderlineType(style) {
24546
+ switch (style) {
24547
+ case "double" /* DOUBLE */:
24548
+ return import_docx.UnderlineType.DOUBLE;
24549
+ case "dashed" /* DASHED */:
24550
+ return import_docx.UnderlineType.DASH;
24551
+ case "dotted" /* DOTTED */:
24552
+ return import_docx.UnderlineType.DOTTED;
24553
+ case "wavy" /* WAVY */:
24554
+ return import_docx.UnderlineType.WAVE;
24555
+ default:
24556
+ return import_docx.UnderlineType.SINGLE;
24557
+ }
24558
+ }
24559
+ function normalizeHexColor(color, fallback) {
24560
+ const normalized = normalizeHexLiteral(color) || normalizeRgbColor(color) || normalizeBrowserColor(color);
24561
+ if (normalized) {
24562
+ return normalized;
24563
+ }
24564
+ return fallback ? normalizeHexLiteral(fallback) || void 0 : void 0;
24565
+ }
24566
+ function normalizeHexLiteral(color) {
24567
+ const value = color.trim().replace(/^#/, "");
24568
+ if (/^[\da-f]{3}$/i.test(value)) {
24569
+ return value.split("").map((part) => `${part}${part}`).join("").toUpperCase();
24570
+ }
24571
+ if (/^[\da-f]{4}$/i.test(value)) {
24572
+ return value.slice(0, 3).split("").map((part) => `${part}${part}`).join("").toUpperCase();
24573
+ }
24574
+ if (/^[\da-f]{6}$/i.test(value)) {
24575
+ return value.toUpperCase();
24576
+ }
24577
+ if (/^[\da-f]{8}$/i.test(value)) {
24578
+ return value.slice(0, 6).toUpperCase();
24579
+ }
24580
+ return void 0;
24581
+ }
24582
+ function normalizeRgbColor(color) {
24583
+ const match = color.trim().match(/^rgba?\((.+)\)$/i);
24584
+ if (!match) {
24585
+ return void 0;
24586
+ }
24587
+ const parts = match[1].replace(/\s*\/\s*/g, ",").split(/\s*,\s*|\s+/).filter(Boolean);
24588
+ if (parts.length < 3) {
24589
+ return void 0;
24590
+ }
24591
+ const red = parseRgbChannel(parts[0]);
24592
+ const green = parseRgbChannel(parts[1]);
24593
+ const blue = parseRgbChannel(parts[2]);
24594
+ if (red === null || green === null || blue === null) {
24595
+ return void 0;
24596
+ }
24597
+ const alpha = parts[3] !== void 0 ? parseAlphaChannel(parts[3]) : 1;
24598
+ if (alpha === null || alpha <= 0) {
24599
+ return void 0;
24600
+ }
24601
+ const flattened = alpha >= 1 ? [red, green, blue] : [
24602
+ flattenChannel(red, alpha),
24603
+ flattenChannel(green, alpha),
24604
+ flattenChannel(blue, alpha)
24605
+ ];
24606
+ return flattened.map(toHexChannel).join("");
24607
+ }
24608
+ function normalizeBrowserColor(color) {
24609
+ if (typeof document === "undefined") {
24610
+ return void 0;
24611
+ }
24612
+ const canvas = document.createElement("canvas");
24613
+ const context = canvas.getContext("2d");
24614
+ if (!context) {
24615
+ return void 0;
24616
+ }
24617
+ context.fillStyle = "#000000";
24618
+ context.fillStyle = color;
24619
+ const normalized = context.fillStyle;
24620
+ if (typeof normalized !== "string") {
24621
+ return void 0;
24622
+ }
24623
+ return normalizeHexLiteral(normalized) || normalizeRgbColor(normalized);
24624
+ }
24625
+ function parseRgbChannel(value) {
24626
+ if (value.endsWith("%")) {
24627
+ const percent = Number(value.slice(0, -1));
24628
+ if (!Number.isFinite(percent)) {
24629
+ return null;
24630
+ }
24631
+ return clampColorChannel(Math.round(percent / 100 * 255));
24632
+ }
24633
+ const channel = Number(value);
24634
+ if (!Number.isFinite(channel)) {
24635
+ return null;
24636
+ }
24637
+ return clampColorChannel(Math.round(channel));
24638
+ }
24639
+ function parseAlphaChannel(value) {
24640
+ if (value.endsWith("%")) {
24641
+ const percent = Number(value.slice(0, -1));
24642
+ if (!Number.isFinite(percent)) {
24643
+ return null;
24644
+ }
24645
+ return Math.min(Math.max(percent / 100, 0), 1);
24646
+ }
24647
+ const alpha = Number(value);
24648
+ if (!Number.isFinite(alpha)) {
24649
+ return null;
24650
+ }
24651
+ return Math.min(Math.max(alpha, 0), 1);
24652
+ }
24653
+ function clampColorChannel(value) {
24654
+ return Math.min(Math.max(value, 0), 255);
24655
+ }
24656
+ function flattenChannel(value, alpha) {
24657
+ return clampColorChannel(Math.round(255 * (1 - alpha) + value * alpha));
24658
+ }
24659
+ function toHexChannel(value) {
24660
+ return value.toString(16).padStart(2, "0").toUpperCase();
24661
+ }
24662
+ function getRegularImageType(mime) {
24663
+ if (mime.includes("png")) return "png";
24664
+ if (mime.includes("jpeg") || mime.includes("jpg")) return "jpg";
24665
+ if (mime.includes("gif")) return "gif";
24666
+ if (mime.includes("bmp")) return "bmp";
24667
+ return null;
24668
+ }
24669
+ function normalizeDocxFileName(fileName) {
24670
+ const trimmed = fileName?.trim();
24671
+ if (!trimmed) {
24672
+ return DEFAULT_DOCX_FILE_NAME;
24673
+ }
24674
+ return trimmed.toLowerCase().endsWith(".docx") ? trimmed : `${trimmed}.docx`;
24675
+ }
24676
+
24677
+ // src/utils/docxLayout.ts
24678
+ var PX_TO_TWIP = 15;
24679
+ var ANCHOR_EPS = 0.5;
24680
+ var RIGHT_SLACK_TWIP = -14400;
24681
+ var TINY_TWIP = 1;
24682
+ var tw = (ctx, layoutPx) => Math.round(layoutPx / ctx.scale * PX_TO_TWIP);
24683
+ var pxTw = (px) => Math.round(px * PX_TO_TWIP);
24684
+ async function exportDrawToDocx(draw, options = {}) {
24685
+ const canvas = document.createElement("canvas");
24686
+ const measureCtx = canvas.getContext("2d");
24687
+ const ctx = {
24688
+ draw,
24689
+ scale: draw.getOptions().scale,
24690
+ measureCtx
24691
+ };
24692
+ const file = await createDocument(ctx);
24693
+ const blob = await import_docx2.Packer.toBlob(file);
24694
+ return { blob, fileName: normalizeDocxFileName(options.fileName) };
24695
+ }
24696
+ async function createDocument(ctx) {
24697
+ const { draw, scale } = ctx;
24698
+ const opts = draw.getOptions();
24699
+ const width = draw.getOriginalWidth();
24700
+ const height = draw.getOriginalHeight();
24701
+ const margins = draw.getOriginalMargins();
24702
+ const header = draw.getHeader();
24703
+ const footer = draw.getFooter();
24704
+ const headerTop = header.getHeaderTop() / scale;
24705
+ const headerExtra = header.getExtraHeight() / scale;
24706
+ const footerExtra = footer.getExtraHeight() / scale;
24707
+ const layoutMargins = draw.getMargins();
24708
+ const body = await serializeMain(ctx, layoutMargins[3]);
24709
+ const headerChildren = opts.header.disabled ? [] : await serializeRows(ctx, header.getRowList(), {
24710
+ startX: layoutMargins[3],
24711
+ width: draw.getInnerWidth(),
24712
+ positionList: header.getPositionList()
24713
+ });
24714
+ const footerChildren = opts.footer.disabled ? [] : await serializeFooter(ctx, width, height, margins);
24715
+ const { pageNumber } = draw.getOptions();
24716
+ endWithParagraph(headerChildren);
24717
+ endWithParagraph(footerChildren);
24718
+ return new import_docx2.Document({
24719
+ compatabilityModeVersion: 15,
24720
+ // LibreOffice formats PAGE/NUMPAGES results from the paragraph style
24721
+ styles: {
24722
+ paragraphStyles: [
24723
+ {
24724
+ id: PAGE_NUMBER_STYLE,
24725
+ name: "Windoc Page Number",
24726
+ run: pageNumberRunStyle(pageNumber)
24727
+ }
24728
+ ]
24505
24729
  },
24730
+ defaultTabStop: pxTw(width),
24506
24731
  sections: [
24507
24732
  {
24508
24733
  properties: {
24509
24734
  page: {
24510
24735
  size: {
24511
- width: pxToTwips(pageWidth),
24512
- height: pxToTwips(pageHeight),
24513
- orientation: paperDirection === "horizontal" /* HORIZONTAL */ ? import_docx.PageOrientation.LANDSCAPE : import_docx.PageOrientation.PORTRAIT
24736
+ width: pxTw(width),
24737
+ height: pxTw(height),
24738
+ orientation: opts.paperDirection === "horizontal" /* HORIZONTAL */ ? import_docx2.PageOrientation.LANDSCAPE : import_docx2.PageOrientation.PORTRAIT
24514
24739
  },
24515
24740
  margin: {
24516
- top: pxToTwips(editorOptions.margins[0]),
24517
- right: pxToTwips(editorOptions.margins[1]),
24518
- bottom: pxToTwips(editorOptions.margins[2]),
24519
- left: pxToTwips(editorOptions.margins[3]),
24520
- header: pxToTwips(editorOptions.header.top),
24521
- footer: pxToTwips(editorOptions.footer.bottom)
24522
- },
24523
- pageNumbers: !editorOptions.pageNumber.disabled && editorOptions.pageNumber.fromPageNo === 0 ? {
24524
- start: editorOptions.pageNumber.startPageNo
24525
- } : void 0
24741
+ top: pxTw(margins[0] + headerExtra),
24742
+ right: pxTw(margins[1]),
24743
+ bottom: pxTw(margins[2] + footerExtra),
24744
+ left: pxTw(margins[3]),
24745
+ header: pxTw(headerTop),
24746
+ footer: pxTw(footer.getFooterBottom() / scale),
24747
+ gutter: 0
24748
+ }
24526
24749
  }
24527
24750
  },
24528
- headers: headerChildren.length > 0 ? {
24529
- default: new import_docx.Header({
24530
- children: headerChildren
24531
- })
24532
- } : void 0,
24533
- footers: footerChildren.length > 0 ? {
24534
- default: new import_docx.Footer({
24535
- children: footerChildren
24536
- })
24537
- } : void 0,
24538
- children: sectionChildren.length ? sectionChildren : [new import_docx.Paragraph({})]
24751
+ headers: headerChildren.length ? { default: new import_docx2.Header({ children: headerChildren }) } : void 0,
24752
+ footers: footerChildren.length ? { default: new import_docx2.Footer({ children: footerChildren }) } : void 0,
24753
+ children: body.length ? body : [new import_docx2.Paragraph({})]
24539
24754
  }
24540
24755
  ]
24541
24756
  });
24542
24757
  }
24543
- async function serializeElementList(elementList, options, context) {
24544
- const blocks = [];
24545
- let inlineBuffer = [];
24546
- const flushInlineBuffer = async () => {
24547
- if (!inlineBuffer.length) return;
24548
- blocks.push(
24549
- ...await serializeInlineElements(inlineBuffer, options, context)
24550
- );
24551
- inlineBuffer = [];
24758
+ async function serializeMain(ctx, startX) {
24759
+ const { draw } = ctx;
24760
+ const zone = {
24761
+ startX,
24762
+ width: draw.getInnerWidth(),
24763
+ positionList: draw.getPosition().getOriginalMainPositionList()
24552
24764
  };
24553
- for (let i = 0; i < elementList.length; i++) {
24554
- const element = elementList[i];
24555
- if (element.type === "area" /* AREA */ && element.valueList?.length) {
24556
- await flushInlineBuffer();
24557
- blocks.push(
24558
- ...await serializeElementList(element.valueList, options, context)
24559
- );
24560
- continue;
24561
- }
24562
- if (element.type === "title" /* TITLE */ && element.valueList?.length) {
24563
- await flushInlineBuffer();
24564
- blocks.push(
24565
- ...await serializeInlineElements(element.valueList, options, context, {
24566
- heading: titleHeadingMap[element.level || "first" /* FIRST */]
24567
- })
24568
- );
24569
- continue;
24570
- }
24571
- if (element.type === "list" /* LIST */ && element.valueList?.length) {
24572
- await flushInlineBuffer();
24573
- blocks.push(...await serializeListElement(element, options, context));
24574
- continue;
24575
- }
24576
- if (element.type === "table" /* TABLE */ && element.trList?.length) {
24577
- await flushInlineBuffer();
24578
- blocks.push(await serializeTableElement(element, options, context));
24579
- continue;
24580
- }
24581
- if (element.type === "pageBreak" /* PAGE_BREAK */) {
24582
- await flushInlineBuffer();
24583
- blocks.push(
24584
- new import_docx.Paragraph({
24585
- children: [new import_docx.PageBreak()]
24586
- })
24587
- );
24588
- continue;
24589
- }
24590
- if (element.type === "separator" /* SEPARATOR */) {
24591
- await flushInlineBuffer();
24592
- blocks.push(
24593
- new import_docx.Paragraph({
24594
- thematicBreak: true
24595
- })
24596
- );
24597
- continue;
24598
- }
24599
- if (element.type === "image" /* IMAGE */ && element.imgDisplay && element.imgDisplay !== "inline") {
24600
- await flushInlineBuffer();
24601
- blocks.push(...await serializeInlineElements([element], options));
24602
- continue;
24603
- }
24604
- if (element.type === "block" /* BLOCK */) {
24605
- await flushInlineBuffer();
24606
- const blockText = getBlockFallbackText(element);
24607
- if (blockText) {
24608
- blocks.push(
24609
- ...await serializeInlineElements(
24610
- [{ value: blockText }],
24611
- options,
24612
- context
24765
+ const children = [];
24766
+ const pageRowList = draw.getPageRowList();
24767
+ for (let p = 0; p < pageRowList.length; p++) {
24768
+ children.push(
24769
+ ...await serializeRows(ctx, pageRowList[p], zone, {
24770
+ pageBreakBefore: p > 0
24771
+ })
24772
+ );
24773
+ }
24774
+ return children;
24775
+ }
24776
+ async function serializeRows(ctx, rowList, zone, options = {}) {
24777
+ const { pageBreakBefore = false, padTop = 0, padBottom = 0 } = options;
24778
+ const children = [];
24779
+ for (let r = 0; r < rowList.length; r++) {
24780
+ const row = rowList[r];
24781
+ const isFirst = r === 0;
24782
+ const isLast = r === rowList.length - 1;
24783
+ const table = row.elementList.find((el) => el.type === "table" /* TABLE */);
24784
+ if (table) {
24785
+ if (isFirst && (pageBreakBefore || padTop) || row.offsetY) {
24786
+ children.push(
24787
+ createSpacerParagraph(
24788
+ isFirst && pageBreakBefore,
24789
+ (isFirst ? padTop : 0) + (row.offsetY || 0) / ctx.scale
24613
24790
  )
24614
24791
  );
24615
24792
  }
24793
+ const position = zone.positionList[row.startIndex + row.elementList.indexOf(table)];
24794
+ children.push(await serializeTable(ctx, table, position, zone));
24795
+ const rest = (row.height + (row.spaceBelow || 0)) / ctx.scale - table.height + (isLast ? padBottom : 0);
24796
+ if (rest * PX_TO_TWIP >= 1) {
24797
+ children.push(createSpacerParagraph(false, rest));
24798
+ }
24616
24799
  continue;
24617
24800
  }
24618
- inlineBuffer.push(element);
24801
+ const rowOptions = {
24802
+ pageBreakBefore: isFirst && pageBreakBefore,
24803
+ padTop: isFirst ? padTop : 0,
24804
+ padBottom: isLast ? padBottom : 0
24805
+ };
24806
+ if (!isFirst && isTextRow(rowList[r - 1])) rowOptions.skipLead = true;
24807
+ rowOptions.rowY = rowY(zone, row);
24808
+ if (!isLast && isTextRow(rowList[r + 1])) {
24809
+ rowOptions.extraAfter = rowLead(ctx, rowList[r + 1], {
24810
+ rowY: rowY(zone, rowList[r + 1])
24811
+ });
24812
+ }
24813
+ const lead = rowOptions.pageBreakBefore ? rowLead(ctx, row, rowOptions) : 0;
24814
+ if (lead) {
24815
+ children.push(createSpacerParagraph(true, lead / PX_TO_TWIP));
24816
+ rowOptions.pageBreakBefore = false;
24817
+ rowOptions.skipLead = true;
24818
+ }
24819
+ children.push(await serializeRow(ctx, row, zone, rowOptions));
24619
24820
  }
24620
- await flushInlineBuffer();
24621
- return blocks;
24821
+ return children;
24622
24822
  }
24623
- async function serializeInlineElements(elementList, options, _context, overrides = {}) {
24624
- const paragraphs = [];
24625
- let current = null;
24626
- const getParagraphContext = (element) => ({
24627
- heading: overrides.heading,
24628
- numbering: overrides.numbering,
24629
- alignment: overrides.alignment !== void 0 ? overrides.alignment : mapRowFlexToAlignment(element?.rowFlex),
24630
- rowMargin: overrides.rowMargin !== void 0 ? overrides.rowMargin : element?.rowMargin
24631
- });
24632
- const flushParagraph = (context) => {
24633
- if (!current) {
24634
- if (!context) return;
24635
- paragraphs.push(createParagraph([], context, options.defaultRowMargin));
24823
+ function rowY(zone, row) {
24824
+ return zone.positionList[row.startIndex]?.coordinate.leftTop[1];
24825
+ }
24826
+ function isTextRow(row) {
24827
+ return !row.elementList.some((el) => el.type === "table" /* TABLE */);
24828
+ }
24829
+ async function serializeRow(ctx, row, zone, options, suffix) {
24830
+ const { pageBreakBefore = false } = options;
24831
+ const { draw, scale } = ctx;
24832
+ const positions = zone.positionList;
24833
+ const children = [];
24834
+ const tabStops = [];
24835
+ const firstPosition = positions[row.startIndex];
24836
+ let pen = 0;
24837
+ let indent = firstPosition ? (firstPosition.coordinate.leftTop[0] - zone.startX) / scale : 0;
24838
+ let started = false;
24839
+ const anchorTo = (layoutX) => {
24840
+ const target = (layoutX - zone.startX) / scale;
24841
+ if (!started) {
24842
+ indent = target;
24843
+ pen = target;
24844
+ started = true;
24636
24845
  return;
24637
24846
  }
24638
- paragraphs.push(
24639
- createParagraph(
24640
- current.children,
24641
- current.context,
24642
- options.defaultRowMargin
24643
- )
24644
- );
24645
- current = null;
24646
- };
24647
- const ensureParagraph = (element) => {
24648
- if (!current) {
24649
- current = {
24650
- children: [],
24651
- context: getParagraphContext(element)
24652
- };
24847
+ if (target - pen > ANCHOR_EPS) {
24848
+ tabStops.push(pxTw(target));
24849
+ children.push(new import_docx2.TextRun({ children: [new import_docx2.Tab()] }));
24850
+ pen = target;
24653
24851
  }
24654
- return current;
24655
24852
  };
24656
- const appendText = (element, text, childFactory, preserveTrailingBreak = false) => {
24657
- const normalized = normalizeText(text);
24658
- const parts = normalized.split("\n");
24659
- let lastSeparatorFlushedContent = false;
24660
- for (let i = 0; i < parts.length; i++) {
24661
- const segment = parts[i];
24662
- if (segment) {
24663
- ensureParagraph(element).children.push(childFactory(segment));
24664
- }
24665
- if (i < parts.length - 1) {
24666
- if (!current) {
24667
- paragraphs.push(
24668
- createParagraph(
24669
- [],
24670
- getParagraphContext(element),
24671
- options.defaultRowMargin
24672
- )
24673
- );
24674
- lastSeparatorFlushedContent = false;
24675
- } else {
24676
- flushParagraph();
24677
- lastSeparatorFlushedContent = true;
24678
- }
24679
- }
24680
- }
24681
- if (preserveTrailingBreak && normalized.endsWith("\n") && lastSeparatorFlushedContent) {
24682
- paragraphs.push(
24683
- createParagraph(
24684
- [],
24685
- getParagraphContext(element),
24686
- options.defaultRowMargin
24687
- )
24853
+ if (row.isList && firstPosition) {
24854
+ const listParticle = draw.getListParticle();
24855
+ const markerX = listParticle.getListMarkerX(row, firstPosition);
24856
+ const marker = markerX === null ? null : listParticle.getListMarker(row);
24857
+ if (markerX !== null && marker) {
24858
+ anchorTo(markerX);
24859
+ children.push(createTextRun(ctx, marker.text, marker.styleElement));
24860
+ pen += measure(ctx, marker.text, marker.styleElement);
24861
+ }
24862
+ }
24863
+ let run = null;
24864
+ const flush = () => {
24865
+ if (!run) return;
24866
+ children.push(createTextRun(ctx, run.text, run.element));
24867
+ run = null;
24868
+ };
24869
+ for (let j = 0; j < row.elementList.length; j++) {
24870
+ const element = row.elementList[j];
24871
+ const position = positions[row.startIndex + j];
24872
+ if (!position) continue;
24873
+ if (element.hide || element.control?.hide || element.area?.hide) continue;
24874
+ if (element.type === "separator" /* SEPARATOR */) {
24875
+ flush();
24876
+ return createSeparatorParagraph(
24877
+ ctx,
24878
+ row,
24879
+ element,
24880
+ position.coordinate.leftTop[0],
24881
+ position.coordinate.leftTop[1],
24882
+ zone,
24883
+ options
24688
24884
  );
24689
24885
  }
24690
- };
24691
- for (let i = 0; i < elementList.length; i++) {
24692
- const element = elementList[i];
24693
- if (element.type === "hyperlink" /* HYPERLINK */ && element.valueList?.length) {
24694
- const hyperlink = await createHyperlinkChild(element, options);
24695
- if (hyperlink) {
24696
- ensureParagraph(element).children.push(hyperlink);
24697
- }
24886
+ if (element.value === ZERO || element.type === "tab" /* TAB */ || element.type === "pageBreak" /* PAGE_BREAK */ || element.type === "columnBreak" /* COLUMN_BREAK */) {
24698
24887
  continue;
24699
24888
  }
24889
+ const x = position.coordinate.leftTop[0];
24890
+ const layoutWidth = element.metrics.width / scale;
24700
24891
  if (element.type === "image" /* IMAGE */) {
24701
- const imageChild = await createImageChild(element);
24702
- if (!imageChild) {
24703
- appendText(
24704
- element,
24705
- "[Image unavailable]",
24706
- (segment) => createTextRun(
24707
- segment,
24708
- element,
24709
- options.defaultSize,
24710
- options.defaultFont
24711
- ),
24712
- i === elementList.length - 1
24713
- );
24714
- continue;
24715
- }
24716
- ensureParagraph(element).children.push(imageChild);
24892
+ flush();
24893
+ anchorTo(x);
24894
+ const image = await createImageRun(element);
24895
+ if (image) children.push(image);
24896
+ pen += layoutWidth;
24717
24897
  continue;
24718
24898
  }
24719
- if (element.type === "columnBreak" /* COLUMN_BREAK */) {
24720
- ensureParagraph(element).children.push(new import_docx.ColumnBreak());
24721
- continue;
24722
- }
24723
- if (element.type === "tab" /* TAB */) {
24724
- appendText(
24725
- element,
24726
- " ",
24727
- (segment) => createTextRun(
24728
- segment,
24729
- element,
24730
- options.defaultSize,
24731
- options.defaultFont
24732
- ),
24733
- i === elementList.length - 1
24899
+ if (element.type === "label" /* LABEL */) {
24900
+ flush();
24901
+ const padding = element.label?.padding || draw.getOptions().label.defaultPadding;
24902
+ anchorTo(x + padding[3] * scale);
24903
+ children.push(
24904
+ createTextRun(ctx, element.value, element, labelShading(ctx, element))
24734
24905
  );
24906
+ pen += measure(ctx, element.value, element);
24735
24907
  continue;
24736
24908
  }
24737
- const textValue = getInlineElementText(element);
24738
- if (!textValue) {
24739
- continue;
24740
- }
24741
- appendText(
24742
- element,
24743
- textValue,
24744
- (segment) => createTextRun(
24745
- segment,
24746
- element,
24747
- options.defaultSize,
24748
- options.defaultFont
24749
- ),
24750
- i === elementList.length - 1
24751
- );
24752
- }
24753
- if (current) {
24754
- flushParagraph();
24755
- }
24756
- return paragraphs.length ? paragraphs : [createParagraph([], overrides, options.defaultRowMargin)];
24757
- }
24758
- async function serializeListElement(element, options, context) {
24759
- const zipList = zipElementList(element.valueList || []);
24760
- const listItemMap = splitListElement(zipList);
24761
- const paragraphs = [];
24762
- const listInstance = createListInstance(context);
24763
- for (const listItemElements of listItemMap.values()) {
24764
- const numbering = getListNumbering(
24765
- getListItemNumberingElement(listItemElements, element),
24766
- listInstance
24767
- );
24768
- paragraphs.push(
24769
- ...await serializeInlineElements(listItemElements, options, context, {
24770
- numbering
24771
- })
24772
- );
24773
- }
24774
- return paragraphs;
24775
- }
24776
- async function serializeTableElement(element, options, context) {
24777
- const rows = [];
24778
- const trList = element.trList || [];
24779
- const tableContext = createTableSerializeContext(element);
24780
- for (let i = 0; i < trList.length; i++) {
24781
- rows.push(
24782
- await serializeTableRow(trList[i], options, context, tableContext)
24783
- );
24784
- }
24785
- const tableWidth = getTableWidthFromColgroup(element.colgroup);
24786
- return new import_docx.Table({
24787
- rows,
24788
- width: tableWidth ? {
24789
- size: pxToTwips(tableWidth),
24790
- type: import_docx.WidthType.DXA
24791
- } : {
24792
- size: 100,
24793
- type: import_docx.WidthType.PERCENTAGE
24794
- },
24795
- columnWidths: element.colgroup?.map((col) => pxToTwips(col.width)),
24796
- layout: import_docx.TableLayoutType.FIXED,
24797
- borders: createTableBorders(element)
24798
- });
24799
- }
24800
- async function serializeTableRow(tr, options, context, tableContext) {
24801
- const children = [];
24802
- for (let i = 0; i < tr.tdList.length; i++) {
24803
- children.push(
24804
- await serializeTableCell(tr.tdList[i], options, context, tableContext)
24805
- );
24806
- }
24807
- return new import_docx.TableRow({
24808
- children
24809
- });
24810
- }
24811
- async function serializeTableCell(td, options, context, tableContext) {
24812
- const children = await serializeElementList(td.value, options, context);
24813
- const shadingFill = td.backgroundColor ? normalizeHexColor(td.backgroundColor) : void 0;
24814
- const cellWidth = tableContext.cellLayoutMap.get(td)?.width || td.width;
24815
- return new import_docx.TableCell({
24816
- children: children.length ? children : [new import_docx.Paragraph({})],
24817
- columnSpan: td.colspan > 1 ? td.colspan : void 0,
24818
- rowSpan: td.rowspan > 1 ? td.rowspan : void 0,
24819
- verticalAlign: mapCellVerticalAlign(td.verticalAlign),
24820
- width: cellWidth ? {
24821
- size: pxToTwips(cellWidth),
24822
- type: import_docx.WidthType.DXA
24823
- } : void 0,
24824
- shading: shadingFill ? {
24825
- fill: shadingFill,
24826
- type: import_docx.ShadingType.CLEAR
24827
- } : void 0,
24828
- margins: mapPaddingToTableMargins(td.padding),
24829
- borders: createTableCellBorders(
24830
- td,
24831
- tableContext.borderColor,
24832
- tableContext.borderWidth
24833
- )
24834
- });
24835
- }
24836
- function createParagraph(children, context, defaultRowMargin) {
24837
- return new import_docx.Paragraph({
24838
- children,
24839
- heading: context.heading,
24840
- numbering: context.numbering,
24841
- alignment: context.alignment,
24842
- spacing: {
24843
- line: Math.round(
24844
- 240 * (context.rowMargin || defaultRowMargin || DEFAULT_LINE_HEIGHT)
24845
- ),
24846
- lineRule: import_docx.LineRuleType.AUTO
24847
- }
24848
- });
24849
- }
24850
- function createTextRun(text, element, defaultSize, defaultFont) {
24851
- const color = element.color ? normalizeHexColor(element.color, "000000") : void 0;
24852
- const highlightFill = element.highlight ? normalizeHexColor(element.highlight) : void 0;
24853
- return new import_docx.TextRun({
24854
- text,
24855
- bold: !!element.bold,
24856
- italics: !!element.italic,
24857
- strike: !!element.strikeout,
24858
- subScript: element.type === "subscript" /* SUBSCRIPT */,
24859
- superScript: element.type === "superscript" /* SUPERSCRIPT */,
24860
- color,
24861
- shading: highlightFill ? {
24862
- fill: highlightFill,
24863
- type: import_docx.ShadingType.CLEAR
24864
- } : void 0,
24865
- underline: element.underline ? {
24866
- type: mapUnderlineType(element.textDecoration?.style)
24867
- } : void 0,
24868
- font: element.font || defaultFont,
24869
- size: Math.round((element.size || defaultSize) * 2)
24870
- });
24871
- }
24872
- async function createHyperlinkChild(element, options) {
24873
- if (!element.url) {
24874
- const fallbackText = getTextFromElementList(element.valueList || []);
24875
- return fallbackText ? createTextRun(
24876
- fallbackText,
24877
- element.valueList?.[0] || element,
24878
- options.defaultSize,
24879
- options.defaultFont
24880
- ) : null;
24881
- }
24882
- const children = await createHyperlinkRuns(
24883
- element.valueList || [],
24884
- options.defaultSize,
24885
- options.defaultFont
24886
- );
24887
- if (!children.length) {
24888
- return null;
24889
- }
24890
- return new import_docx.ExternalHyperlink({
24891
- link: element.url,
24892
- children
24893
- });
24894
- }
24895
- async function createHyperlinkRuns(valueList, defaultSize, defaultFont) {
24896
- const children = [];
24897
- for (let i = 0; i < valueList.length; i++) {
24898
- const element = valueList[i];
24899
- if (element.type === "tab" /* TAB */) {
24900
- children.push(createTextRun(" ", element, defaultSize, defaultFont));
24901
- continue;
24902
- }
24903
- const text = normalizeText(getInlineElementText(element)).replace(
24904
- /\n/g,
24905
- " "
24906
- );
24907
- if (text) {
24908
- children.push(createTextRun(text, element, defaultSize, defaultFont));
24909
- }
24910
- }
24911
- return children;
24912
- }
24913
- async function createImageChild(element) {
24914
- try {
24915
- const image = await loadImagePayload(element.value);
24916
- const width = Math.max(1, Math.round(element.width || DEFAULT_IMAGE_WIDTH));
24917
- const height = Math.max(
24918
- 1,
24919
- Math.round(element.height || DEFAULT_IMAGE_HEIGHT)
24920
- );
24921
- if (image.type === "svg" && image.fallbackPng) {
24922
- return new import_docx.ImageRun({
24923
- type: "svg",
24924
- data: image.data,
24925
- fallback: {
24926
- type: "png",
24927
- data: image.fallbackPng
24928
- },
24929
- transformation: {
24930
- width,
24931
- height
24932
- }
24933
- });
24934
- }
24935
- return new import_docx.ImageRun({
24936
- type: image.type,
24937
- data: image.data,
24938
- transformation: {
24939
- width,
24940
- height
24909
+ const text = getElementText(element);
24910
+ if (!text) continue;
24911
+ const natural = measure(ctx, text, element);
24912
+ const target = (x - zone.startX) / scale;
24913
+ const isDrift = !started || target - pen > ANCHOR_EPS;
24914
+ const extra = layoutWidth - natural;
24915
+ const needsSpacing = Math.abs(extra) * PX_TO_TWIP >= 1;
24916
+ const canJoin = run && !isDrift && !needsSpacing && isSameRunStyle(run.element, element);
24917
+ if (canJoin) {
24918
+ run.text += text;
24919
+ } else {
24920
+ flush();
24921
+ anchorTo(x);
24922
+ if (needsSpacing) {
24923
+ children.push(
24924
+ createTextRun(ctx, text, element, void 0, pxTw(extra))
24925
+ );
24926
+ } else {
24927
+ run = { text, element };
24941
24928
  }
24942
- });
24943
- } catch {
24944
- return null;
24945
- }
24946
- }
24947
- async function loadImagePayload(src) {
24948
- const source = src.trim();
24949
- if (source.startsWith("data:")) {
24950
- return getImagePayloadFromDataUrl(source);
24951
- }
24952
- const response = await fetch(source);
24953
- if (!response.ok) {
24954
- throw new Error(`Image request failed: ${response.status}`);
24955
- }
24956
- const contentType = response.headers.get("content-type") || "";
24957
- const data2 = await response.arrayBuffer();
24958
- return normalizeImagePayload(data2, contentType);
24959
- }
24960
- async function getImagePayloadFromDataUrl(src) {
24961
- const [, meta = "", encoded = ""] = src.match(/^data:([^,]*),(.*)$/) || [];
24962
- const mime = meta.split(";")[0] || "";
24963
- const isBase64 = meta.includes(";base64");
24964
- const text = isBase64 ? atob(encoded) : decodeURIComponent(encoded);
24965
- const bytes = new Uint8Array(text.length);
24966
- for (let i = 0; i < text.length; i++) {
24967
- bytes[i] = text.charCodeAt(i);
24968
- }
24969
- return normalizeImagePayload(bytes.buffer, mime);
24970
- }
24971
- async function normalizeImagePayload(data2, mime) {
24972
- const type = getRegularImageType(mime);
24973
- if (type) {
24974
- return {
24975
- type,
24976
- data: data2
24977
- };
24978
- }
24979
- if (mime.includes("svg")) {
24980
- return {
24981
- type: "svg",
24982
- data: data2,
24983
- fallbackPng: await rasterizeSvgToPng(data2)
24984
- };
24985
- }
24986
- const fallbackPng = await rasterizeImageToPng(data2, mime);
24987
- return {
24988
- type: "png",
24989
- data: fallbackPng
24990
- };
24991
- }
24992
- async function rasterizeSvgToPng(data2) {
24993
- return rasterizeImageToPng(data2, "image/svg+xml");
24994
- }
24995
- async function rasterizeImageToPng(data2, mime) {
24996
- const blob = new Blob([data2], {
24997
- type: mime || "image/png"
24998
- });
24999
- const url = URL.createObjectURL(blob);
25000
- try {
25001
- const image = await loadHtmlImage(url);
25002
- const canvas = document.createElement("canvas");
25003
- canvas.width = image.naturalWidth || DEFAULT_IMAGE_WIDTH;
25004
- canvas.height = image.naturalHeight || DEFAULT_IMAGE_HEIGHT;
25005
- const context = canvas.getContext("2d");
25006
- if (!context) {
25007
- throw new Error("Canvas context is unavailable");
25008
24929
  }
25009
- context.drawImage(image, 0, 0, canvas.width, canvas.height);
25010
- const pngBlob = await new Promise((resolve, reject) => {
25011
- canvas.toBlob((output) => {
25012
- if (output) {
25013
- resolve(output);
25014
- } else {
25015
- reject(new Error("Failed to create PNG blob"));
25016
- }
25017
- }, "image/png");
25018
- });
25019
- return await pngBlob.arrayBuffer();
25020
- } finally {
25021
- URL.revokeObjectURL(url);
24930
+ pen = target + layoutWidth;
25022
24931
  }
25023
- }
25024
- function loadHtmlImage(src) {
25025
- return new Promise((resolve, reject) => {
25026
- const image = new Image();
25027
- image.onload = () => resolve(image);
25028
- image.onerror = () => reject(new Error("Failed to load image"));
25029
- image.src = src;
25030
- });
25031
- }
25032
- function createPageNumberParagraph(pageNumber) {
25033
- if (pageNumber.disabled || pageNumber.fromPageNo > 0) {
25034
- return null;
24932
+ flush();
24933
+ if (!children.length && !suffix) {
24934
+ const total = (options.skipLead ? 0 : rowLead(ctx, row, options)) + rowLine(ctx, row).lineTw + rowSpacing(ctx, row, options).after;
24935
+ return createSpacerParagraph(pageBreakBefore, total / PX_TO_TWIP);
25035
24936
  }
25036
- const children = [];
25037
- const format = pageNumber.format || FORMAT_PLACEHOLDER.PAGE_NO;
25038
- const tokens = format.split(/(\{pageNo\}|\{pageCount\})/);
25039
- for (let i = 0; i < tokens.length; i++) {
25040
- const token = tokens[i];
25041
- if (!token) continue;
25042
- const runChildren = token === FORMAT_PLACEHOLDER.PAGE_NO ? [import_docx.PageNumber.CURRENT] : token === FORMAT_PLACEHOLDER.PAGE_COUNT ? [import_docx.PageNumber.TOTAL_PAGES] : void 0;
25043
- children.push(
25044
- new import_docx.TextRun({
25045
- text: runChildren ? void 0 : token,
25046
- children: runChildren,
25047
- color: normalizeHexColor(pageNumber.color || "#000000", "000000"),
25048
- font: pageNumber.font,
25049
- size: Math.round((pageNumber.size || 12) * 2)
25050
- })
25051
- );
25052
- }
25053
- return new import_docx.Paragraph({
25054
- children,
25055
- alignment: mapRowFlexToAlignment(pageNumber.rowFlex)
25056
- });
25057
- }
25058
- function forceDocxFooterTextColor(elementList) {
25059
- const footerElementList = deepClone(elementList);
25060
- forceColorValue(footerElementList);
25061
- return footerElementList;
25062
- }
25063
- function forceColorValue(value) {
25064
- if (!value || typeof value !== "object") {
25065
- return;
24937
+ const stops = tabStops.map((position) => ({ type: import_docx2.TabStopType.LEFT, position }));
24938
+ if (suffix) {
24939
+ stops.push({ type: suffix.tabType, position: suffix.tabStop });
24940
+ children.push(new import_docx2.TextRun({ children: [new import_docx2.Tab()] }), ...suffix.children);
25066
24941
  }
25067
- if (Array.isArray(value)) {
25068
- for (let i = 0; i < value.length; i++) {
25069
- forceColorValue(value[i]);
25070
- }
25071
- return;
25072
- }
25073
- const record = value;
25074
- if ("color" in record) {
25075
- record.color = DOCX_FOOTER_TEXT_COLOR;
25076
- }
25077
- const keys = Object.keys(record);
25078
- for (let i = 0; i < keys.length; i++) {
25079
- forceColorValue(record[keys[i]]);
25080
- }
25081
- }
25082
- function createNumberingConfig() {
25083
- const config = [
25084
- createOrderedReference("windoc-ol-decimal", Array(9).fill("decimal" /* DECIMAL */)),
25085
- createOrderedReference(
25086
- "windoc-ol-lower-alpha",
25087
- Array(9).fill("lowerAlpha" /* LOWER_ALPHA */)
25088
- ),
25089
- createOrderedReference(
25090
- "windoc-ol-upper-alpha",
25091
- Array(9).fill("upperAlpha" /* UPPER_ALPHA */)
25092
- ),
25093
- createOrderedReference(
25094
- "windoc-ol-lower-roman",
25095
- Array(9).fill("lowerRoman" /* LOWER_ROMAN */)
25096
- ),
25097
- createOrderedReference(
25098
- "windoc-ol-upper-roman",
25099
- Array(9).fill("upperRoman" /* UPPER_ROMAN */)
25100
- ),
25101
- createOrderedReference(
25102
- "windoc-ol-decimal-paren",
25103
- Array(9).fill("decimalParen" /* DECIMAL_PAREN */)
25104
- ),
25105
- createOrderedReference(
25106
- `windoc-ol-${"olDefault" /* DEFAULT */}`,
25107
- createCycleList(olPresetCycles["olDefault" /* DEFAULT */], 9)
25108
- ),
25109
- createOrderedReference(
25110
- `windoc-ol-${"olParen" /* PARENTHESIS */}`,
25111
- createCycleList(olPresetCycles["olParen" /* PARENTHESIS */], 9)
25112
- ),
25113
- createOrderedReference(
25114
- `windoc-ol-${"olOutline" /* OUTLINE */}`,
25115
- createCycleList(olPresetCycles["olOutline" /* OUTLINE */], 9)
25116
- ),
25117
- createOrderedReference(
25118
- `windoc-ol-${"olUpperA" /* UPPER_ALPHA */}`,
25119
- createCycleList(olPresetCycles["olUpperA" /* UPPER_ALPHA */], 9)
25120
- ),
25121
- createOrderedReference(
25122
- `windoc-ol-${"olRoman" /* ROMAN */}`,
25123
- createCycleList(olPresetCycles["olRoman" /* ROMAN */], 9)
25124
- ),
25125
- createOrderedReference(
25126
- `windoc-ol-${"olZeroPad" /* ZERO_PAD */}`,
25127
- createCycleList(olPresetCycles["olZeroPad" /* ZERO_PAD */], 9)
25128
- ),
25129
- createBulletReference(
25130
- "windoc-ul-disc",
25131
- Array(9).fill(docxBulletCharMap["disc" /* DISC */])
25132
- ),
25133
- createBulletReference(
25134
- "windoc-ul-circle",
25135
- Array(9).fill(docxBulletCharMap["circle" /* CIRCLE */])
25136
- ),
25137
- createBulletReference(
25138
- "windoc-ul-square",
25139
- Array(9).fill(docxBulletCharMap["square" /* SQUARE */])
25140
- ),
25141
- createBulletReference(
25142
- "windoc-ul-checkbox",
25143
- Array(9).fill(docxBulletCharMap["checkbox" /* CHECKBOX */])
25144
- ),
25145
- createBulletReference(
25146
- `windoc-ul-${"ulDefault" /* DEFAULT */}`,
25147
- createCycleList(ulPresetCycles["ulDefault" /* DEFAULT */], 9)
25148
- ),
25149
- createBulletReference(
25150
- `windoc-ul-${"ulDiamond" /* DIAMOND */}`,
25151
- createCycleList(ulPresetCycles["ulDiamond" /* DIAMOND */], 9)
25152
- ),
25153
- createBulletReference(
25154
- `windoc-ul-${"ulHollowSq" /* HOLLOW_SQ */}`,
25155
- createCycleList(ulPresetCycles["ulHollowSq" /* HOLLOW_SQ */], 9)
25156
- ),
25157
- createBulletReference(
25158
- `windoc-ul-${"ulArrow" /* ARROW */}`,
25159
- createCycleList(ulPresetCycles["ulArrow" /* ARROW */], 9)
25160
- ),
25161
- createBulletReference(
25162
- `windoc-ul-${"ulStar" /* STAR */}`,
25163
- createCycleList(ulPresetCycles["ulStar" /* STAR */], 9)
25164
- ),
25165
- createBulletReference(
25166
- `windoc-ul-${"ulCheckArr" /* CHECK_ARROW */}`,
25167
- createCycleList(ulPresetCycles["ulCheckArr" /* CHECK_ARROW */], 9)
25168
- )
25169
- ];
25170
- return config;
25171
- }
25172
- function createOrderedReference(reference, styles) {
25173
- return {
25174
- reference,
25175
- levels: styles.map((style, level) => ({
25176
- level,
25177
- format: orderedStyleFormatMap[style] || import_docx.LevelFormat.DECIMAL,
25178
- text: getOrderedLevelText(style, level),
25179
- alignment: import_docx.AlignmentType.START,
25180
- style: {
25181
- paragraph: {
25182
- indent: {
25183
- left: 720 * (level + 1),
25184
- hanging: 360
25185
- }
25186
- }
25187
- }
25188
- }))
25189
- };
25190
- }
25191
- function createBulletReference(reference, bullets) {
25192
- return {
25193
- reference,
25194
- levels: bullets.map((bullet, level) => ({
25195
- level,
25196
- format: import_docx.LevelFormat.BULLET,
25197
- text: bullet,
25198
- alignment: import_docx.AlignmentType.START,
25199
- style: {
25200
- paragraph: {
25201
- indent: {
25202
- left: 720 * (level + 1),
25203
- hanging: 360
25204
- }
25205
- }
25206
- }
25207
- }))
25208
- };
25209
- }
25210
- function getOrderedLevelText(style, level) {
25211
- const placeholder = `%${level + 1}`;
25212
- if (style === "outline") {
25213
- return Array.from({ length: level + 1 }, (_, index) => `%${index + 1}`).join(
25214
- "."
25215
- ) + ".";
25216
- }
25217
- if (style.endsWith("Paren") || style === "decimalParen" /* DECIMAL_PAREN */) {
25218
- return `${placeholder})`;
25219
- }
25220
- return `${placeholder}.`;
25221
- }
25222
- function createCycleList(source = [], size) {
25223
- const result = [];
25224
- for (let i = 0; i < size; i++) {
25225
- result.push(source[i % source.length]);
25226
- }
25227
- return result;
25228
- }
25229
- function getListNumbering(element, instance) {
25230
- const level = Math.max(0, Math.min(element.listLevel || 0, 8));
25231
- if (element.listType === "ul" /* UL */) {
25232
- const reference2 = element.listPreset ? `windoc-ul-${element.listPreset}` : `windoc-ul-${element.listStyle || "disc" /* DISC */}`;
25233
- return {
25234
- reference: reference2,
25235
- level,
25236
- instance
25237
- };
25238
- }
25239
- const reference = element.listPreset ? `windoc-ol-${element.listPreset}` : getOrderedReferenceFromStyle(element.listStyle);
25240
- return {
25241
- reference,
25242
- level,
25243
- instance
25244
- };
25245
- }
25246
- function getOrderedReferenceFromStyle(style) {
25247
- switch (style) {
25248
- case "lowerAlpha" /* LOWER_ALPHA */:
25249
- return "windoc-ol-lower-alpha";
25250
- case "upperAlpha" /* UPPER_ALPHA */:
25251
- return "windoc-ol-upper-alpha";
25252
- case "lowerRoman" /* LOWER_ROMAN */:
25253
- return "windoc-ol-lower-roman";
25254
- case "upperRoman" /* UPPER_ROMAN */:
25255
- return "windoc-ol-upper-roman";
25256
- case "decimalParen" /* DECIMAL_PAREN */:
25257
- return "windoc-ol-decimal-paren";
25258
- default:
25259
- return "windoc-ol-decimal";
25260
- }
25261
- }
25262
- function createTableBorders(element) {
25263
- const outerBorder = createBorder(
25264
- element.borderColor,
25265
- import_docx.BorderStyle.SINGLE,
25266
- element.borderExternalWidth || element.borderWidth
25267
- );
25268
- const innerBorder = createBorder(
25269
- element.borderColor,
25270
- import_docx.BorderStyle.SINGLE,
25271
- element.borderWidth
25272
- );
25273
- switch (element.borderType) {
25274
- case "empty" /* EMPTY */:
25275
- return {
25276
- top: noneBorder(),
25277
- bottom: noneBorder(),
25278
- left: noneBorder(),
25279
- right: noneBorder(),
25280
- insideHorizontal: noneBorder(),
25281
- insideVertical: noneBorder()
25282
- };
25283
- case "external" /* EXTERNAL */:
25284
- return {
25285
- top: outerBorder,
25286
- bottom: outerBorder,
25287
- left: outerBorder,
25288
- right: outerBorder,
25289
- insideHorizontal: noneBorder(),
25290
- insideVertical: noneBorder()
25291
- };
25292
- case "internal" /* INTERNAL */:
25293
- return {
25294
- top: noneBorder(),
25295
- bottom: noneBorder(),
25296
- left: noneBorder(),
25297
- right: noneBorder(),
25298
- insideHorizontal: innerBorder,
25299
- insideVertical: innerBorder
25300
- };
25301
- case "dash" /* DASH */:
25302
- return {
25303
- top: createBorder(
25304
- element.borderColor,
25305
- import_docx.BorderStyle.DASHED,
25306
- element.borderExternalWidth || element.borderWidth
25307
- ),
25308
- bottom: createBorder(
25309
- element.borderColor,
25310
- import_docx.BorderStyle.DASHED,
25311
- element.borderExternalWidth || element.borderWidth
25312
- ),
25313
- left: createBorder(
25314
- element.borderColor,
25315
- import_docx.BorderStyle.DASHED,
25316
- element.borderExternalWidth || element.borderWidth
25317
- ),
25318
- right: createBorder(
25319
- element.borderColor,
25320
- import_docx.BorderStyle.DASHED,
25321
- element.borderExternalWidth || element.borderWidth
25322
- ),
25323
- insideHorizontal: createBorder(
25324
- element.borderColor,
25325
- import_docx.BorderStyle.DASHED,
25326
- element.borderWidth
25327
- ),
25328
- insideVertical: createBorder(
25329
- element.borderColor,
25330
- import_docx.BorderStyle.DASHED,
25331
- element.borderWidth
25332
- )
25333
- };
25334
- default:
25335
- return {
25336
- top: outerBorder,
25337
- bottom: outerBorder,
25338
- left: outerBorder,
25339
- right: outerBorder,
25340
- insideHorizontal: innerBorder,
25341
- insideVertical: innerBorder
25342
- };
25343
- }
25344
- }
25345
- function createTableCellBorders(td, inheritedColor, inheritedWidth) {
25346
- if (!td.borderTypes?.length && !td.borderColor) {
25347
- return void 0;
25348
- }
25349
- const color = td.borderColor || inheritedColor;
25350
- const createCellBorder = () => createBorder(color, import_docx.BorderStyle.SINGLE, inheritedWidth);
25351
- if (td.borderColor && !td.borderTypes?.length) {
25352
- return {
25353
- top: createCellBorder(),
25354
- right: createCellBorder(),
25355
- bottom: createCellBorder(),
25356
- left: createCellBorder()
25357
- };
25358
- }
25359
- const top = td.borderTypes?.includes("top" /* TOP */) ? createCellBorder() : noneBorder();
25360
- const right2 = td.borderTypes?.includes("right" /* RIGHT */) ? createCellBorder() : noneBorder();
25361
- const bottom = td.borderTypes?.includes("bottom" /* BOTTOM */) ? createCellBorder() : noneBorder();
25362
- const left2 = td.borderTypes?.includes("left" /* LEFT */) ? createCellBorder() : noneBorder();
25363
- return {
25364
- top,
25365
- right: right2,
25366
- bottom,
25367
- left: left2
25368
- };
25369
- }
25370
- function createBorder(color = "#000000", style = import_docx.BorderStyle.SINGLE, width = 1) {
25371
- return {
25372
- style,
25373
- color: normalizeHexColor(color, "000000") || "000000",
25374
- size: pxBorderToDocxSize(width)
25375
- };
25376
- }
25377
- function noneBorder() {
25378
- return {
25379
- style: import_docx.BorderStyle.NONE,
25380
- size: 0,
25381
- color: "FFFFFF"
25382
- };
25383
- }
25384
- function mapPaddingToTableMargins(padding) {
25385
- if (!padding) return void 0;
25386
- return {
25387
- top: pxToTwips(padding[0]),
25388
- right: pxToTwips(padding[1]),
25389
- bottom: pxToTwips(padding[2]),
25390
- left: pxToTwips(padding[3]),
25391
- marginUnitType: import_docx.WidthType.DXA
25392
- };
25393
- }
25394
- function mapCellVerticalAlign(verticalAlign) {
25395
- switch (verticalAlign) {
25396
- case VerticalAlign.CENTER:
25397
- return import_docx.VerticalAlign.CENTER;
25398
- case "bottom" /* BOTTOM */:
25399
- return import_docx.VerticalAlign.BOTTOM;
25400
- default:
25401
- return import_docx.VerticalAlign.TOP;
25402
- }
25403
- }
25404
- function mapRowFlexToAlignment(rowFlex) {
25405
- switch (rowFlex) {
25406
- case "center" /* CENTER */:
25407
- return import_docx.AlignmentType.CENTER;
25408
- case "right" /* RIGHT */:
25409
- return import_docx.AlignmentType.RIGHT;
25410
- case "alignment" /* ALIGNMENT */:
25411
- case "justify" /* JUSTIFY */:
25412
- return import_docx.AlignmentType.JUSTIFIED;
25413
- default:
25414
- return import_docx.AlignmentType.LEFT;
25415
- }
25416
- }
25417
- function mapUnderlineType(style) {
25418
- switch (style) {
25419
- case "double" /* DOUBLE */:
25420
- return import_docx.UnderlineType.DOUBLE;
25421
- case "dashed" /* DASHED */:
25422
- return import_docx.UnderlineType.DASH;
25423
- case "dotted" /* DOTTED */:
25424
- return import_docx.UnderlineType.DOTTED;
25425
- case "wavy" /* WAVY */:
25426
- return import_docx.UnderlineType.WAVE;
25427
- default:
25428
- return import_docx.UnderlineType.SINGLE;
25429
- }
25430
- }
25431
- function getInlineElementText(element) {
25432
- switch (element.type) {
25433
- case "control" /* CONTROL */:
25434
- return getControlText(element.control);
25435
- case "date" /* DATE */:
25436
- return element.valueList?.length ? getTextFromElementList(element.valueList) : element.value;
25437
- case "checkbox" /* CHECKBOX */:
25438
- return element.checkbox?.value ? "\u2611" : "\u2610";
25439
- case "radio" /* RADIO */:
25440
- return element.radio?.value ? "\u25C9" : "\u25CB";
25441
- case "label" /* LABEL */:
25442
- case "latex" /* LATEX */:
25443
- case "subscript" /* SUBSCRIPT */:
25444
- case "superscript" /* SUPERSCRIPT */:
25445
- return element.value;
25446
- default:
25447
- return element.value;
25448
- }
25449
- }
25450
- function getControlText(control) {
25451
- if (!control) return "";
25452
- if (control.type === "text" /* TEXT */ || control.type === "date" /* DATE */ || control.type === "number" /* NUMBER */) {
25453
- const value = control.value?.length ? getTextFromElementList(control.value) : "";
25454
- const content = value || control.placeholder || "";
25455
- return `${control.preText || ""}${content}${control.postText || ""}`;
25456
- }
25457
- if (control.type === "select" /* SELECT */) {
25458
- const labels = getSelectedControlLabels(control.code, control.valueSets);
25459
- const content = labels.length ? labels.join(control.multiSelectDelimiter || ", ") : control.placeholder || "";
25460
- return `${control.preText || ""}${content}${control.postText || ""}`;
25461
- }
25462
- if (control.type === "checkbox" /* CHECKBOX */ || control.type === "radio" /* RADIO */) {
25463
- const isRadio = control.type === "radio" /* RADIO */;
25464
- return (control.valueSets || []).map((valueSet) => {
25465
- const checked = control.code?.split(",").includes(valueSet.code) || false;
25466
- return `${checked ? isRadio ? "\u25C9" : "\u2611" : isRadio ? "\u25CB" : "\u2610"} ${valueSet.value}`;
25467
- }).join(" ");
25468
- }
25469
- return "";
25470
- }
25471
- function getSelectedControlLabels(code, valueSets) {
25472
- if (!code || !valueSets?.length) return [];
25473
- return code.split(",").map(
25474
- (selectCode) => valueSets.find((valueSet) => valueSet.code === selectCode)?.value
25475
- ).filter((value) => !!value);
25476
- }
25477
- function getBlockFallbackText(element) {
25478
- if (element.block?.iframeBlock?.src) {
25479
- return element.block.iframeBlock.src;
25480
- }
25481
- if (element.block?.videoBlock?.src) {
25482
- return element.block.videoBlock.src;
25483
- }
25484
- return "";
24942
+ return new import_docx2.Paragraph({
24943
+ children,
24944
+ run: hasInlineImage(row) ? { size: IMAGE_MARK_HALF_POINTS } : void 0,
24945
+ style: suffix?.style,
24946
+ pageBreakBefore,
24947
+ widowControl: false,
24948
+ tabStops: stops,
24949
+ indent: { left: pxTw(indent), right: RIGHT_SLACK_TWIP },
24950
+ spacing: rowSpacing(ctx, row, options)
24951
+ });
25485
24952
  }
25486
- function normalizeText(text = "") {
25487
- return text.replace(new RegExp(ZERO, "g"), "").replace(/\r\n/g, "\n");
24953
+ var EXACT_BASELINE_RATIO = 0.8;
24954
+ var IMAGE_MARK_HALF_POINTS = 2;
24955
+ var IMAGE_MARK_DESCENT_PX = 0.3;
24956
+ function hasInlineImage(row) {
24957
+ return row.elementList.some((el) => el.type === "image" /* IMAGE */);
24958
+ }
24959
+ function rowLine(ctx, row, baseline = row.ascent / ctx.scale) {
24960
+ const { scale } = ctx;
24961
+ const height = row.height / scale;
24962
+ if (hasInlineImage(row)) {
24963
+ const lineTw2 = pxTw(Math.min(baseline, height) + IMAGE_MARK_DESCENT_PX);
24964
+ return {
24965
+ lineTw: lineTw2,
24966
+ beforeTw: 0,
24967
+ afterTw: Math.max(0, pxTw(height) - lineTw2),
24968
+ atLeast: true
24969
+ };
24970
+ }
24971
+ const ascent = Math.min(baseline, height);
24972
+ const line = Math.min(
24973
+ ascent / EXACT_BASELINE_RATIO,
24974
+ (height - ascent) / (1 - EXACT_BASELINE_RATIO)
24975
+ );
24976
+ const lineTw = Math.max(TINY_TWIP, pxTw(line));
24977
+ const beforeTw = Math.max(
24978
+ 0,
24979
+ pxTw(ascent) - Math.round(lineTw * EXACT_BASELINE_RATIO)
24980
+ );
24981
+ const afterTw = Math.max(0, pxTw(height) - lineTw - beforeTw);
24982
+ return { lineTw, beforeTw, afterTw, atLeast: false };
25488
24983
  }
25489
- function createSerializeContext() {
24984
+ function rowLead(ctx, row, options) {
24985
+ const separator = row.elementList.find(
24986
+ (el) => el.type === "separator" /* SEPARATOR */
24987
+ );
24988
+ const baseline = separator && options.rowY !== void 0 ? separatorBaseline(
24989
+ ctx,
24990
+ row,
24991
+ options.rowY,
24992
+ separator.lineWidth || ctx.draw.getOptions().separator.lineWidth
24993
+ ) : void 0;
24994
+ return rowLine(ctx, row, baseline).beforeTw + tw(ctx, (row.offsetY || 0) + (row.spaceAbove || 0)) + pxTw(options.padTop || 0);
24995
+ }
24996
+ function rowSpacing(ctx, row, options) {
24997
+ const { lineTw, afterTw, atLeast } = rowLine(ctx, row);
25490
24998
  return {
25491
- nextListInstance: 1
24999
+ before: options.skipLead ? 0 : rowLead(ctx, row, options),
25000
+ after: afterTw + tw(ctx, row.spaceBelow || 0) + pxTw(options.padBottom || 0) + (options.extraAfter || 0),
25001
+ line: lineTw,
25002
+ lineRule: atLeast ? import_docx2.LineRuleType.AT_LEAST : import_docx2.LineRuleType.EXACT
25492
25003
  };
25493
25004
  }
25494
- function getListItemNumberingElement(listItemElements, fallback) {
25495
- return listItemElements.find(
25496
- (listItem) => listItem.listId || listItem.listLevel !== void 0 || !!listItem.listPreset || !!listItem.listStyle || !!listItem.listType
25497
- ) || fallback;
25498
- }
25499
- function createListInstance(context) {
25500
- return context.nextListInstance++;
25005
+ function createSeparatorParagraph(ctx, row, element, x, rowY2, zone, options) {
25006
+ const { scale } = ctx;
25007
+ const opts = ctx.draw.getOptions();
25008
+ const lineWidth = element.lineWidth || opts.separator.lineWidth;
25009
+ const sideGap = 4;
25010
+ const left2 = (x - zone.startX) / scale + sideGap;
25011
+ const width = Math.max(1, (element.width || 0) - sideGap * 2);
25012
+ const color = element.color || opts.separator.strokeStyle;
25013
+ const line = rowLine(ctx, row, separatorBaseline(ctx, row, rowY2, lineWidth));
25014
+ return new import_docx2.Paragraph({
25015
+ pageBreakBefore: options.pageBreakBefore,
25016
+ widowControl: false,
25017
+ indent: { left: pxTw(left2), right: RIGHT_SLACK_TWIP },
25018
+ children: [
25019
+ new import_docx2.ImageRun({
25020
+ type: "png",
25021
+ data: createLineImage(width, lineWidth, color, element.dashArray),
25022
+ transformation: { width, height: lineWidth }
25023
+ })
25024
+ ],
25025
+ spacing: {
25026
+ before: options.skipLead ? 0 : rowLead(ctx, row, options),
25027
+ after: line.afterTw + tw(ctx, row.spaceBelow || 0) + pxTw(options.padBottom || 0) + (options.extraAfter || 0),
25028
+ line: line.lineTw,
25029
+ lineRule: import_docx2.LineRuleType.EXACT
25030
+ }
25031
+ });
25501
25032
  }
25502
- function createTableSerializeContext(element) {
25503
- return {
25504
- cellLayoutMap: computeTableCellLayout(
25505
- element.trList || [],
25506
- element.colgroup || []
25507
- ),
25508
- borderColor: element.borderColor,
25509
- borderWidth: element.borderWidth,
25510
- borderExternalWidth: element.borderExternalWidth
25511
- };
25033
+ function separatorBaseline(ctx, row, rowY2, lineWidth) {
25034
+ return (Math.round(rowY2 + row.ascent) - rowY2) / ctx.scale + lineWidth;
25512
25035
  }
25513
- function computeTableCellLayout(trList, colgroup) {
25514
- const cellLayoutMap = /* @__PURE__ */ new WeakMap();
25515
- if (!trList.length || !colgroup.length) {
25516
- return cellLayoutMap;
25036
+ function createLineImage(width, height, color, dashArray) {
25037
+ const ratio = 4;
25038
+ const canvas = document.createElement("canvas");
25039
+ canvas.width = Math.max(1, Math.round(width * ratio));
25040
+ canvas.height = Math.max(1, Math.round(height * ratio));
25041
+ const ctx = canvas.getContext("2d");
25042
+ ctx.strokeStyle = color;
25043
+ ctx.lineWidth = canvas.height;
25044
+ if (dashArray?.length) ctx.setLineDash(dashArray.map((v) => v * ratio));
25045
+ ctx.beginPath();
25046
+ ctx.moveTo(0, canvas.height / 2);
25047
+ ctx.lineTo(canvas.width, canvas.height / 2);
25048
+ ctx.stroke();
25049
+ const binary = atob(canvas.toDataURL("image/png").split(",")[1]);
25050
+ const bytes = new Uint8Array(binary.length);
25051
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
25052
+ return bytes;
25053
+ }
25054
+ function endWithParagraph(children) {
25055
+ if (children[children.length - 1] instanceof import_docx2.Table) {
25056
+ children.push(createSpacerParagraph(false));
25517
25057
  }
25518
- const occupiedUntilRow = Array(colgroup.length).fill(0);
25519
- for (let rowIndex = 0; rowIndex < trList.length; rowIndex++) {
25520
- const tr = trList[rowIndex];
25521
- let colIndex = 0;
25522
- for (let tdIndex = 0; tdIndex < tr.tdList.length; tdIndex++) {
25523
- while (colIndex < colgroup.length && occupiedUntilRow[colIndex] > rowIndex) {
25524
- colIndex += 1;
25525
- }
25526
- const td = tr.tdList[tdIndex];
25527
- let width = 0;
25528
- for (let currentCol = colIndex; currentCol < colIndex + td.colspan && currentCol < colgroup.length; currentCol++) {
25529
- width += colgroup[currentCol].width;
25530
- occupiedUntilRow[currentCol] = Math.max(
25531
- occupiedUntilRow[currentCol],
25532
- rowIndex + td.rowspan
25533
- );
25534
- }
25535
- cellLayoutMap.set(td, { width });
25536
- colIndex += td.colspan;
25058
+ return children;
25059
+ }
25060
+ function createSpacerParagraph(pageBreakBefore, height = 0) {
25061
+ return new import_docx2.Paragraph({
25062
+ pageBreakBefore,
25063
+ widowControl: false,
25064
+ children: [new import_docx2.TextRun({ text: "", size: 2 })],
25065
+ spacing: {
25066
+ before: 0,
25067
+ after: 0,
25068
+ line: Math.max(TINY_TWIP, pxTw(height)),
25069
+ lineRule: import_docx2.LineRuleType.EXACT
25537
25070
  }
25538
- }
25539
- return cellLayoutMap;
25071
+ });
25540
25072
  }
25541
- function getTableWidthFromColgroup(colgroup) {
25542
- if (!colgroup?.length) {
25543
- return void 0;
25073
+ async function serializeTable(ctx, element, position, zone) {
25074
+ const { draw, scale } = ctx;
25075
+ const opts = draw.getOptions();
25076
+ const tableX = position.coordinate.leftTop[0];
25077
+ const trList = element.trList || [];
25078
+ const colgroup = element.colgroup || [];
25079
+ const rows = [];
25080
+ for (let t = 0; t < trList.length; t++) {
25081
+ const tr = trList[t];
25082
+ const cells = [];
25083
+ let rowTopBorder = 0;
25084
+ for (let d = 0; d < tr.tdList.length; d++) {
25085
+ const td = tr.tdList[d];
25086
+ const padding = td.padding || opts.table.tdPadding;
25087
+ const borders = createCellBorders(ctx, element, td);
25088
+ const topBorder = t === 0 ? borderPx(borders.top) : 0;
25089
+ rowTopBorder = Math.max(rowTopBorder, topBorder);
25090
+ const cellChildren = await serializeRows(
25091
+ ctx,
25092
+ td.rowList || [],
25093
+ {
25094
+ startX: (td.x + padding[3]) * scale + tableX,
25095
+ width: (td.width - padding[1] - padding[3]) * scale,
25096
+ positionList: td.positionList || []
25097
+ },
25098
+ { padTop: Math.max(0, padding[0] - topBorder), padBottom: padding[2] }
25099
+ );
25100
+ cells.push(
25101
+ new import_docx2.TableCell({
25102
+ children: cellChildren.length ? endWithParagraph(cellChildren) : [createSpacerParagraph(false)],
25103
+ columnSpan: td.colspan > 1 ? td.colspan : void 0,
25104
+ rowSpan: td.rowspan > 1 ? td.rowspan : void 0,
25105
+ width: { size: pxTw(td.width), type: import_docx2.WidthType.DXA },
25106
+ verticalAlign: mapVerticalAlign(td.verticalAlign),
25107
+ margins: {
25108
+ top: 0,
25109
+ right: pxTw(padding[1]),
25110
+ bottom: 0,
25111
+ left: pxTw(Math.max(0, padding[3] - borderPx(borders.left) / 2)),
25112
+ marginUnitType: import_docx2.WidthType.DXA
25113
+ },
25114
+ shading: td.backgroundColor ? {
25115
+ fill: normalizeHexColor(td.backgroundColor, "FFFFFF"),
25116
+ type: import_docx2.ShadingType.CLEAR,
25117
+ color: "auto"
25118
+ } : void 0,
25119
+ borders
25120
+ })
25121
+ );
25122
+ }
25123
+ rows.push(
25124
+ new import_docx2.TableRow({
25125
+ children: cells,
25126
+ cantSplit: true,
25127
+ height: {
25128
+ value: pxTw(tr.height - rowTopBorder),
25129
+ rule: import_docx2.HeightRule.EXACT
25130
+ }
25131
+ })
25132
+ );
25544
25133
  }
25545
- return colgroup.reduce((sum, col) => sum + col.width, 0);
25134
+ return new import_docx2.Table({
25135
+ rows,
25136
+ layout: import_docx2.TableLayoutType.FIXED,
25137
+ width: { size: pxTw(element.width), type: import_docx2.WidthType.DXA },
25138
+ columnWidths: colgroup.map((col) => pxTw(col.width)),
25139
+ indent: { size: tw(ctx, tableX - zone.startX), type: import_docx2.WidthType.DXA },
25140
+ borders: noTableBorders()
25141
+ });
25546
25142
  }
25547
- function normalizeHexColor(color, fallback) {
25548
- const normalized = normalizeHexLiteral(color) || normalizeRgbColor(color) || normalizeBrowserColor(color);
25549
- if (normalized) {
25550
- return normalized;
25551
- }
25552
- return fallback ? normalizeHexLiteral(fallback) || void 0 : void 0;
25143
+ function createCellBorders(ctx, table, td) {
25144
+ const opts = ctx.draw.getOptions();
25145
+ const color = normalizeHexColor(
25146
+ td.borderColor || table.borderColor || opts.table.defaultBorderColor,
25147
+ "000000"
25148
+ );
25149
+ const width = table.borderWidth || 1;
25150
+ const externalWidth = table.borderExternalWidth || width;
25151
+ const isDash = table.borderType === "dash" /* DASH */;
25152
+ const line = (w) => ({
25153
+ style: isDash ? import_docx2.BorderStyle.DASHED : import_docx2.BorderStyle.SINGLE,
25154
+ size: Math.max(2, Math.round(w * 6)),
25155
+ color
25156
+ });
25157
+ const none = { style: import_docx2.BorderStyle.NONE, size: 0, color: "auto" };
25158
+ const isTop = td.rowIndex === 0;
25159
+ const isLeft = td.colIndex === 0;
25160
+ const isBottom = td.rowIndex + td.rowspan === table.trList.length;
25161
+ const isRight = td.colIndex + td.colspan === table.colgroup.length;
25162
+ const edge = (outer) => outer ? line(externalWidth) : line(width);
25163
+ let top = none;
25164
+ let right2 = none;
25165
+ let bottom = none;
25166
+ let left2 = none;
25167
+ switch (table.borderType) {
25168
+ case "empty" /* EMPTY */:
25169
+ break;
25170
+ case "external" /* EXTERNAL */:
25171
+ if (isTop) top = edge(true);
25172
+ if (isBottom) bottom = edge(true);
25173
+ if (isLeft) left2 = edge(true);
25174
+ if (isRight) right2 = edge(true);
25175
+ break;
25176
+ case "internal" /* INTERNAL */:
25177
+ if (!isTop) top = edge(false);
25178
+ if (!isBottom) bottom = edge(false);
25179
+ if (!isLeft) left2 = edge(false);
25180
+ if (!isRight) right2 = edge(false);
25181
+ break;
25182
+ default:
25183
+ top = edge(isTop);
25184
+ bottom = edge(isBottom);
25185
+ left2 = edge(isLeft);
25186
+ right2 = edge(isRight);
25187
+ }
25188
+ if (td.borderTypes?.includes("top" /* TOP */)) top = line(width);
25189
+ if (td.borderTypes?.includes("right" /* RIGHT */)) right2 = line(width);
25190
+ if (td.borderTypes?.includes("bottom" /* BOTTOM */)) bottom = line(width);
25191
+ if (td.borderTypes?.includes("left" /* LEFT */)) left2 = line(width);
25192
+ return { top, right: right2, bottom, left: left2 };
25193
+ }
25194
+ function borderPx(border) {
25195
+ return border.style === import_docx2.BorderStyle.NONE ? 0 : border.size / 8 * (4 / 3);
25196
+ }
25197
+ function noTableBorders() {
25198
+ const none = { style: import_docx2.BorderStyle.NONE, size: 0, color: "auto" };
25199
+ return {
25200
+ top: none,
25201
+ bottom: none,
25202
+ left: none,
25203
+ right: none,
25204
+ insideHorizontal: none,
25205
+ insideVertical: none
25206
+ };
25553
25207
  }
25554
- function normalizeHexLiteral(color) {
25555
- const value = color.trim().replace(/^#/, "");
25556
- if (/^[\da-f]{3}$/i.test(value)) {
25557
- return value.split("").map((part) => `${part}${part}`).join("").toUpperCase();
25558
- }
25559
- if (/^[\da-f]{4}$/i.test(value)) {
25560
- return value.slice(0, 3).split("").map((part) => `${part}${part}`).join("").toUpperCase();
25561
- }
25562
- if (/^[\da-f]{6}$/i.test(value)) {
25563
- return value.toUpperCase();
25208
+ function mapVerticalAlign(verticalAlign) {
25209
+ switch (verticalAlign) {
25210
+ case "middle" /* MIDDLE */:
25211
+ return import_docx2.VerticalAlign.CENTER;
25212
+ case "bottom" /* BOTTOM */:
25213
+ return import_docx2.VerticalAlign.BOTTOM;
25214
+ default:
25215
+ return import_docx2.VerticalAlign.TOP;
25216
+ }
25217
+ }
25218
+ async function serializeFooter(ctx, pageWidth, pageHeight, margins) {
25219
+ const { draw, scale } = ctx;
25220
+ const footer = draw.getFooter();
25221
+ const opts = draw.getOptions();
25222
+ const barHeight = footer.getHeight() / scale;
25223
+ const contentHeight = footer.getRowHeight() / scale;
25224
+ const paddingTop = Math.floor(Math.max(0, (barHeight - contentHeight) / 2) * scale) / scale;
25225
+ const zone = {
25226
+ startX: draw.getMargins()[3],
25227
+ width: draw.getInnerWidth(),
25228
+ positionList: footer.getPositionList()
25229
+ };
25230
+ const rowList = footer.getRowList();
25231
+ const textWidth = pageWidth - margins[1] - margins[3];
25232
+ const pageNumber = createPageNumberRuns(ctx, pageHeight, textWidth);
25233
+ let pageNumberRow = -1;
25234
+ if (pageNumber) {
25235
+ pageNumberRow = rowList.length - 1;
25236
+ for (let r = 0; r < rowList.length; r++) {
25237
+ const top = zone.positionList[rowList[r].startIndex].coordinate.leftTop[1] / scale;
25238
+ if (pageNumber.baseline <= top + rowList[r].height / scale) {
25239
+ pageNumberRow = r;
25240
+ break;
25241
+ }
25242
+ }
25564
25243
  }
25565
- if (/^[\da-f]{8}$/i.test(value)) {
25566
- return value.slice(0, 6).toUpperCase();
25244
+ const children = [];
25245
+ for (let r = 0; r < rowList.length; r++) {
25246
+ const row = rowList[r];
25247
+ const rowOptions = { padTop: r === 0 ? paddingTop : 0 };
25248
+ if (r !== pageNumberRow) {
25249
+ children.push(...await serializeRows(ctx, [row], zone, rowOptions));
25250
+ continue;
25251
+ }
25252
+ const top = zone.positionList[row.startIndex].coordinate.leftTop[1] / scale;
25253
+ const shift = pageNumber.baseline - (top + row.ascent / scale);
25254
+ children.push(
25255
+ await serializeRow(ctx, row, zone, rowOptions, {
25256
+ tabStop: pageNumber.tabStop,
25257
+ tabType: pageNumber.tabType,
25258
+ children: pageNumber.runs(shift),
25259
+ style: PAGE_NUMBER_STYLE
25260
+ })
25261
+ );
25567
25262
  }
25568
- return void 0;
25263
+ const fill = opts.footer.backgroundColor ? normalizeHexColor(opts.footer.backgroundColor, "FFFFFF") : void 0;
25264
+ const none = { style: import_docx2.BorderStyle.NONE, size: 0, color: "auto" };
25265
+ const band = new import_docx2.Table({
25266
+ layout: import_docx2.TableLayoutType.FIXED,
25267
+ width: { size: pxTw(pageWidth), type: import_docx2.WidthType.DXA },
25268
+ columnWidths: [pxTw(pageWidth)],
25269
+ indent: { size: -pxTw(margins[3]), type: import_docx2.WidthType.DXA },
25270
+ borders: noTableBorders(),
25271
+ rows: [
25272
+ new import_docx2.TableRow({
25273
+ cantSplit: true,
25274
+ height: { value: pxTw(barHeight), rule: import_docx2.HeightRule.EXACT },
25275
+ children: [
25276
+ new import_docx2.TableCell({
25277
+ width: { size: pxTw(pageWidth), type: import_docx2.WidthType.DXA },
25278
+ margins: {
25279
+ top: 0,
25280
+ bottom: 0,
25281
+ left: pxTw(margins[3]),
25282
+ right: pxTw(margins[1]),
25283
+ marginUnitType: import_docx2.WidthType.DXA
25284
+ },
25285
+ shading: fill ? { fill, type: import_docx2.ShadingType.CLEAR, color: "auto" } : void 0,
25286
+ borders: { top: none, right: none, bottom: none, left: none },
25287
+ children: children.length ? children : [createSpacerParagraph(false)]
25288
+ })
25289
+ ]
25290
+ })
25291
+ ]
25292
+ });
25293
+ return [band];
25569
25294
  }
25570
- function normalizeRgbColor(color) {
25571
- const match = color.trim().match(/^rgba?\((.+)\)$/i);
25572
- if (!match) {
25573
- return void 0;
25295
+ var PAGE_NUMBER_STYLE = "WindocPageNumber";
25296
+ var FieldCharAttributes = class extends import_docx2.XmlAttributeComponent {
25297
+ constructor() {
25298
+ super(...arguments);
25299
+ this.xmlKeys = { type: "w:fldCharType" };
25574
25300
  }
25575
- const parts = match[1].replace(/\s*\/\s*/g, ",").split(/\s*,\s*|\s+/).filter(Boolean);
25576
- if (parts.length < 3) {
25577
- return void 0;
25301
+ };
25302
+ var FieldChar = class extends import_docx2.XmlComponent {
25303
+ constructor(type) {
25304
+ super("w:fldChar");
25305
+ this.root.push(new FieldCharAttributes({ type }));
25578
25306
  }
25579
- const red = parseRgbChannel(parts[0]);
25580
- const green = parseRgbChannel(parts[1]);
25581
- const blue = parseRgbChannel(parts[2]);
25582
- if (red === null || green === null || blue === null) {
25583
- return void 0;
25307
+ };
25308
+ var InstrTextAttributes = class extends import_docx2.XmlAttributeComponent {
25309
+ constructor() {
25310
+ super(...arguments);
25311
+ this.xmlKeys = { space: "xml:space" };
25584
25312
  }
25585
- const alpha = parts[3] !== void 0 ? parseAlphaChannel(parts[3]) : 1;
25586
- if (alpha === null || alpha <= 0) {
25587
- return void 0;
25313
+ };
25314
+ var InstrText = class extends import_docx2.XmlComponent {
25315
+ constructor(instruction) {
25316
+ super("w:instrText");
25317
+ this.root.push(new InstrTextAttributes({ space: "preserve" }));
25318
+ this.root.push(` ${instruction} `);
25588
25319
  }
25589
- const flattened = alpha >= 1 ? [red, green, blue] : [
25590
- flattenChannel(red, alpha),
25591
- flattenChannel(green, alpha),
25592
- flattenChannel(blue, alpha)
25320
+ };
25321
+ function createFieldRuns(instruction, cached, style) {
25322
+ return [
25323
+ new import_docx2.TextRun({ ...style, children: [new FieldChar("begin")] }),
25324
+ new import_docx2.TextRun({ ...style, children: [new InstrText(instruction)] }),
25325
+ new import_docx2.TextRun({ ...style, children: [new FieldChar("separate")] }),
25326
+ new import_docx2.TextRun({ ...style, text: cached }),
25327
+ new import_docx2.TextRun({ ...style, children: [new FieldChar("end")] })
25593
25328
  ];
25594
- return flattened.map(toHexChannel).join("");
25595
25329
  }
25596
- function normalizeBrowserColor(color) {
25597
- if (typeof document === "undefined") {
25598
- return void 0;
25599
- }
25600
- const canvas = document.createElement("canvas");
25601
- const context = canvas.getContext("2d");
25602
- if (!context) {
25603
- return void 0;
25604
- }
25605
- context.fillStyle = "#000000";
25606
- context.fillStyle = color;
25607
- const normalized = context.fillStyle;
25608
- if (typeof normalized !== "string") {
25609
- return void 0;
25610
- }
25611
- return normalizeHexLiteral(normalized) || normalizeRgbColor(normalized);
25330
+ function pageNumberRunStyle(pageNumber) {
25331
+ return {
25332
+ font: mapFont(pageNumber?.font || "sans-serif"),
25333
+ // PageNumber draws `${size}px`; half-points = px * 0.75 * 2
25334
+ size: Math.round((pageNumber?.size || 12) * 1.5),
25335
+ color: normalizeHexColor(pageNumber?.color || "#000000", "000000")
25336
+ };
25612
25337
  }
25613
- function parseRgbChannel(value) {
25614
- if (value.endsWith("%")) {
25615
- const percent = Number(value.slice(0, -1));
25616
- if (!Number.isFinite(percent)) {
25617
- return null;
25618
- }
25619
- return clampColorChannel(Math.round(percent / 100 * 255));
25620
- }
25621
- const channel = Number(value);
25622
- if (!Number.isFinite(channel)) {
25623
- return null;
25338
+ function createPageNumberRuns(ctx, pageHeight, textWidth) {
25339
+ const { pageNumber } = ctx.draw.getOptions();
25340
+ if (pageNumber.disabled || pageNumber.fromPageNo > 0) return null;
25341
+ const pageCount = ctx.draw.getPageCount();
25342
+ const tokens = (pageNumber.format || FORMAT_PLACEHOLDER.PAGE_NO).split(
25343
+ /(\{pageNo\}|\{pageCount\})/
25344
+ );
25345
+ const tabType = pageNumber.rowFlex === "center" /* CENTER */ ? import_docx2.TabStopType.CENTER : pageNumber.rowFlex === "right" /* RIGHT */ ? import_docx2.TabStopType.RIGHT : import_docx2.TabStopType.LEFT;
25346
+ const tabStop = tabType === import_docx2.TabStopType.CENTER ? pxTw(textWidth / 2) : tabType === import_docx2.TabStopType.RIGHT ? pxTw(textWidth) : 0;
25347
+ const position = (shift) => {
25348
+ const halfPoints = Math.round(-shift * 0.75 * 2);
25349
+ return halfPoints ? `${halfPoints}` : void 0;
25350
+ };
25351
+ return {
25352
+ baseline: pageHeight - pageNumber.bottom,
25353
+ tabType,
25354
+ tabStop,
25355
+ // shift > 0 means the number sits lower than the row baseline
25356
+ runs: (shift) => tokens.filter(Boolean).map((token) => {
25357
+ const style = {
25358
+ ...pageNumberRunStyle(pageNumber),
25359
+ position: position(shift)
25360
+ };
25361
+ const field = token === FORMAT_PLACEHOLDER.PAGE_NO ? { instruction: "PAGE", cached: "1" } : token === FORMAT_PLACEHOLDER.PAGE_COUNT ? { instruction: "NUMPAGES", cached: `${pageCount}` } : null;
25362
+ if (!field) return [new import_docx2.TextRun({ text: token, ...style })];
25363
+ return createFieldRuns(field.instruction, field.cached, style);
25364
+ }).flat()
25365
+ };
25366
+ }
25367
+ function createTextRun(ctx, text, element, shading, characterSpacing) {
25368
+ const opts = ctx.draw.getOptions();
25369
+ const isLink = element.type === "hyperlink" /* HYPERLINK */;
25370
+ const color = normalizeHexColor(
25371
+ element.color || (isLink ? opts.defaultHyperlinkColor : opts.defaultColor),
25372
+ "000000"
25373
+ );
25374
+ const highlight = element.highlight ? normalizeHexColor(element.highlight) : void 0;
25375
+ const textRun = new import_docx2.TextRun({
25376
+ text,
25377
+ font: mapFont(element.font || opts.defaultFont),
25378
+ size: Math.round(getSize(ctx, element) * 2),
25379
+ bold: !!element.bold,
25380
+ italics: !!element.italic,
25381
+ strike: !!element.strikeout,
25382
+ superScript: element.type === "superscript" /* SUPERSCRIPT */,
25383
+ subScript: element.type === "subscript" /* SUBSCRIPT */,
25384
+ underline: element.underline || isLink ? { type: mapUnderlineType(element.textDecoration?.style) } : void 0,
25385
+ color,
25386
+ shading: shading || (highlight ? { fill: highlight, type: import_docx2.ShadingType.CLEAR, color: "auto" } : void 0),
25387
+ characterSpacing
25388
+ });
25389
+ if (isLink && element.url) {
25390
+ return new import_docx2.ExternalHyperlink({ link: element.url, children: [textRun] });
25624
25391
  }
25625
- return clampColorChannel(Math.round(channel));
25392
+ return textRun;
25626
25393
  }
25627
- function parseAlphaChannel(value) {
25628
- if (value.endsWith("%")) {
25629
- const percent = Number(value.slice(0, -1));
25630
- if (!Number.isFinite(percent)) {
25631
- return null;
25394
+ function labelShading(ctx, element) {
25395
+ const { defaultBackgroundColor } = ctx.draw.getOptions().label;
25396
+ return {
25397
+ fill: normalizeHexColor(
25398
+ element.label?.backgroundColor || defaultBackgroundColor,
25399
+ "FFFFFF"
25400
+ ),
25401
+ type: import_docx2.ShadingType.CLEAR,
25402
+ color: "auto"
25403
+ };
25404
+ }
25405
+ async function createImageRun(element) {
25406
+ try {
25407
+ const image = await loadImagePayload(element.value);
25408
+ const transformation = {
25409
+ width: Math.max(1, element.width || 1),
25410
+ height: Math.max(1, element.height || 1)
25411
+ };
25412
+ if (image.type === "svg" && image.fallbackPng) {
25413
+ return new import_docx2.ImageRun({
25414
+ type: "svg",
25415
+ data: image.data,
25416
+ fallback: { type: "png", data: image.fallbackPng },
25417
+ transformation
25418
+ });
25632
25419
  }
25633
- return Math.min(Math.max(percent / 100, 0), 1);
25634
- }
25635
- const alpha = Number(value);
25636
- if (!Number.isFinite(alpha)) {
25420
+ return new import_docx2.ImageRun({
25421
+ type: image.type,
25422
+ data: image.data,
25423
+ transformation
25424
+ });
25425
+ } catch {
25637
25426
  return null;
25638
25427
  }
25639
- return Math.min(Math.max(alpha, 0), 1);
25640
- }
25641
- function clampColorChannel(value) {
25642
- return Math.min(Math.max(value, 0), 255);
25643
25428
  }
25644
- function flattenChannel(value, alpha) {
25645
- return clampColorChannel(Math.round(255 * (1 - alpha) + value * alpha));
25429
+ function getElementText(element) {
25430
+ switch (element.type) {
25431
+ case "checkbox" /* CHECKBOX */:
25432
+ return element.checkbox?.value ? "\u2611" : "\u2610";
25433
+ case "radio" /* RADIO */:
25434
+ return element.radio?.value ? "\u25C9" : "\u25CB";
25435
+ default:
25436
+ return (element.value || "").replace(new RegExp(ZERO, "g"), "");
25437
+ }
25646
25438
  }
25647
- function toHexChannel(value) {
25648
- return value.toString(16).padStart(2, "0").toUpperCase();
25439
+ function getSize(ctx, element) {
25440
+ return element.actualSize || element.size || ctx.draw.getOptions().defaultSize;
25649
25441
  }
25650
- function pxBorderToDocxSize(width) {
25651
- const safeWidth = Number.isFinite(width) && width > 0 ? width : 1;
25652
- return Math.max(2, Math.round(safeWidth * 6));
25442
+ function measure(ctx, text, element) {
25443
+ ctx.measureCtx.font = ctx.draw.getElementFont(element, 1);
25444
+ return ctx.measureCtx.measureText(text).width;
25653
25445
  }
25654
- function getRegularImageType(mime) {
25655
- if (mime.includes("png")) return "png";
25656
- if (mime.includes("jpeg") || mime.includes("jpg")) return "jpg";
25657
- if (mime.includes("gif")) return "gif";
25658
- if (mime.includes("bmp")) return "bmp";
25659
- return null;
25446
+ function isSameRunStyle(a, b) {
25447
+ return a.type === b.type && a.font === b.font && a.size === b.size && a.actualSize === b.actualSize && !!a.bold === !!b.bold && !!a.italic === !!b.italic && !!a.underline === !!b.underline && !!a.strikeout === !!b.strikeout && a.color === b.color && a.highlight === b.highlight && a.url === b.url;
25660
25448
  }
25661
- function normalizeDocxFileName(fileName) {
25662
- const trimmed = fileName?.trim();
25663
- if (!trimmed) {
25664
- return DEFAULT_DOCX_FILE_NAME;
25449
+ function mapFont(font) {
25450
+ const name = font.trim().replace(/^['"]|['"]$/g, "");
25451
+ switch (name.toLowerCase()) {
25452
+ case "sans-serif":
25453
+ return "Arial";
25454
+ case "serif":
25455
+ return "Times New Roman";
25456
+ case "monospace":
25457
+ return "Courier New";
25458
+ default:
25459
+ return name;
25665
25460
  }
25666
- return trimmed.toLowerCase().endsWith(".docx") ? trimmed : `${trimmed}.docx`;
25667
- }
25668
- function pxToTwips(px) {
25669
- return Math.round(px * 15);
25670
25461
  }
25671
25462
 
25672
25463
  // src/utils/pdf.ts
@@ -25674,7 +25465,7 @@ var import_pdf_lib = require("pdf-lib");
25674
25465
  var DEFAULT_PDF_FILE_NAME = "document.pdf";
25675
25466
  var DEFAULT_IMAGE_WIDTH2 = 320;
25676
25467
  var DEFAULT_IMAGE_HEIGHT2 = 180;
25677
- var DEFAULT_LINE_HEIGHT2 = 1.15;
25468
+ var DEFAULT_LINE_HEIGHT = 1.15;
25678
25469
  var PAGE_REGION_GAP = 12;
25679
25470
  var SEPARATOR_HEIGHT = 12;
25680
25471
  var LIST_GAP = 8;
@@ -25869,7 +25660,7 @@ async function parseElementList(elementList, context, options) {
25869
25660
  }
25870
25661
  if (element.type === "block" /* BLOCK */) {
25871
25662
  await flushInlineBuffer();
25872
- const blockText = getBlockFallbackText2(element);
25663
+ const blockText = getBlockFallbackText(element);
25873
25664
  if (blockText) {
25874
25665
  blocks.push(
25875
25666
  ...await parseInlineElements(
@@ -25921,7 +25712,7 @@ async function parseInlineElements(elementList, context, options, overrides = {}
25921
25712
  current = null;
25922
25713
  };
25923
25714
  const appendText = (element, text, factory, preserveTrailingBreak = false) => {
25924
- const normalized = normalizeText2(text);
25715
+ const normalized = normalizeText(text);
25925
25716
  const parts = normalized.split("\n");
25926
25717
  let lastSeparatorFlushedContent = false;
25927
25718
  for (let i = 0; i < parts.length; i++) {
@@ -25957,7 +25748,7 @@ async function parseInlineElements(elementList, context, options, overrides = {}
25957
25748
  const children = element.valueList || [];
25958
25749
  for (let childIndex = 0; childIndex < children.length; childIndex++) {
25959
25750
  const child = children[childIndex];
25960
- const text = normalizeText2(getInlineElementText2(child));
25751
+ const text = normalizeText(getInlineElementText(child));
25961
25752
  if (!text) continue;
25962
25753
  appendText(
25963
25754
  element,
@@ -26006,7 +25797,7 @@ async function parseInlineElements(elementList, context, options, overrides = {}
26006
25797
  ensureParagraph(element).runs.push(badgeRun);
26007
25798
  continue;
26008
25799
  }
26009
- const textValue = getInlineElementText2(element);
25800
+ const textValue = getInlineElementText(element);
26010
25801
  if (!textValue) {
26011
25802
  continue;
26012
25803
  }
@@ -26034,7 +25825,7 @@ async function parseListBlock(element, context, options) {
26034
25825
  const blocks = [];
26035
25826
  const orderedCounts = Array(9).fill(0);
26036
25827
  for (const listItemElements of listItemMap.values()) {
26037
- const itemElement = getListItemNumberingElement2(listItemElements, element);
25828
+ const itemElement = getListItemNumberingElement(listItemElements, element);
26038
25829
  const marker = getListMarker(itemElement, orderedCounts);
26039
25830
  blocks.push(
26040
25831
  ...await parseInlineElements(listItemElements, context, options, {
@@ -26593,10 +26384,11 @@ function layoutParagraph(block, width, context) {
26593
26384
  }
26594
26385
  if (token.width > availableWidth && token.kind === "text" && token.run.type === "text") {
26595
26386
  const segments = splitTextToken(token, availableWidth, context);
26596
- for (let segmentIndex = 0; segmentIndex < segments.length; segmentIndex++) {
26597
- tokens.splice(i + segmentIndex, 0, segments[segmentIndex]);
26387
+ if (segments.length > 1) {
26388
+ tokens.splice(i, 1, ...segments);
26389
+ i--;
26390
+ continue;
26598
26391
  }
26599
- continue;
26600
26392
  }
26601
26393
  if (line.width + token.width > availableWidth && line.fragments.length) {
26602
26394
  commitLine();
@@ -26955,7 +26747,7 @@ function getEmptyLineHeight(block, context) {
26955
26747
  block.context.rowMargin || context.options.defaultRowMargin
26956
26748
  );
26957
26749
  }
26958
- function getRunHeight(run, rowMargin = DEFAULT_LINE_HEIGHT2) {
26750
+ function getRunHeight(run, rowMargin = DEFAULT_LINE_HEIGHT) {
26959
26751
  return run.size * rowMargin;
26960
26752
  }
26961
26753
  function resolveTextMetrics(run, context) {
@@ -27164,10 +26956,10 @@ function loadHtmlImage2(src) {
27164
26956
  image.src = src;
27165
26957
  });
27166
26958
  }
27167
- function getInlineElementText2(element) {
26959
+ function getInlineElementText(element) {
27168
26960
  switch (element.type) {
27169
26961
  case "control" /* CONTROL */:
27170
- return getControlText2(element.control);
26962
+ return getControlText(element.control);
27171
26963
  case "date" /* DATE */:
27172
26964
  return element.valueList?.length ? getTextFromElementList(element.valueList) : element.value;
27173
26965
  case "checkbox" /* CHECKBOX */:
@@ -27183,7 +26975,7 @@ function getInlineElementText2(element) {
27183
26975
  return element.value;
27184
26976
  }
27185
26977
  }
27186
- function getControlText2(control) {
26978
+ function getControlText(control) {
27187
26979
  if (!control) return "";
27188
26980
  if (control.type === "text" /* TEXT */ || control.type === "date" /* DATE */ || control.type === "number" /* NUMBER */) {
27189
26981
  const value = control.value?.length ? getTextFromElementList(control.value) : "";
@@ -27191,7 +26983,7 @@ function getControlText2(control) {
27191
26983
  return `${control.preText || ""}${content}${control.postText || ""}`;
27192
26984
  }
27193
26985
  if (control.type === "select" /* SELECT */) {
27194
- const labels = getSelectedControlLabels2(control.code, control.valueSets);
26986
+ const labels = getSelectedControlLabels(control.code, control.valueSets);
27195
26987
  const content = labels.length ? labels.join(control.multiSelectDelimiter || ", ") : control.placeholder || "";
27196
26988
  return `${control.preText || ""}${content}${control.postText || ""}`;
27197
26989
  }
@@ -27204,13 +26996,13 @@ function getControlText2(control) {
27204
26996
  }
27205
26997
  return "";
27206
26998
  }
27207
- function getSelectedControlLabels2(code, valueSets) {
26999
+ function getSelectedControlLabels(code, valueSets) {
27208
27000
  if (!code || !valueSets?.length) return [];
27209
27001
  return code.split(",").map(
27210
27002
  (selectCode) => valueSets.find((valueSet) => valueSet.code === selectCode)?.value
27211
27003
  ).filter((value) => !!value);
27212
27004
  }
27213
- function getBlockFallbackText2(element) {
27005
+ function getBlockFallbackText(element) {
27214
27006
  if (element.block?.iframeBlock?.src) {
27215
27007
  return element.block.iframeBlock.src;
27216
27008
  }
@@ -27219,7 +27011,7 @@ function getBlockFallbackText2(element) {
27219
27011
  }
27220
27012
  return "";
27221
27013
  }
27222
- function getListItemNumberingElement2(listItemElements, fallback) {
27014
+ function getListItemNumberingElement(listItemElements, fallback) {
27223
27015
  return listItemElements.find(
27224
27016
  (listItem) => listItem.listId || listItem.listLevel !== void 0 || !!listItem.listPreset || !!listItem.listStyle || !!listItem.listType
27225
27017
  ) || fallback;
@@ -27441,7 +27233,7 @@ function getReservedPageNumberBottom(pageNumber, pageNumberHeight) {
27441
27233
  }
27442
27234
  return pxToPt(pageNumber.bottom + 4) + pageNumberHeight;
27443
27235
  }
27444
- function normalizeText2(text = "") {
27236
+ function normalizeText(text = "") {
27445
27237
  return text.replace(new RegExp(ZERO, "g"), "").replace(/\r\n/g, "\n");
27446
27238
  }
27447
27239
  function normalizePdfFileName(fileName) {
@@ -28781,8 +28573,7 @@ var CommandAdapt = class {
28781
28573
  }
28782
28574
  }
28783
28575
  async exportDocx(payload = {}) {
28784
- const result = this.draw.getValue();
28785
- const { blob, fileName } = await exportEditorDataToDocx(result, payload);
28576
+ const { blob, fileName } = await exportDrawToDocx(this.draw, payload);
28786
28577
  downloadBlob(blob, fileName);
28787
28578
  }
28788
28579
  async exportPdf(payload = {}) {