@windoc/core 0.3.25 → 0.3.27

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.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var version = "0.3.25";
2
+ var version = "0.3.27";
3
3
 
4
4
  // src/dataset/enum/Common.ts
5
5
  var MaxHeightRatio = /* @__PURE__ */ ((MaxHeightRatio2) => {
@@ -19111,10 +19111,11 @@ var ListParticle = class {
19111
19111
  if (!cycle) return "\u25CF";
19112
19112
  return cycle[level % cycle.length];
19113
19113
  }
19114
- drawListStyle(ctx, row, position) {
19115
- const { elementList, offsetX, listIndex, ascent } = row;
19114
+ // Marker x for a list row's first line (shared by canvas drawing and export)
19115
+ getListMarkerX(row, position) {
19116
+ const { elementList, offsetX } = row;
19116
19117
  const startElement = elementList[0];
19117
- if (startElement.value !== ZERO || startElement.listWrap) return;
19118
+ if (startElement.value !== ZERO || startElement.listWrap) return null;
19118
19119
  let tabWidth = 0;
19119
19120
  const { defaultTabWidth, scale } = this.options;
19120
19121
  for (let i = 1; i < elementList.length; i++) {
@@ -19124,12 +19125,29 @@ var ListParticle = class {
19124
19125
  }
19125
19126
  const {
19126
19127
  coordinate: {
19127
- leftTop: [startX, startY]
19128
+ leftTop: [startX]
19128
19129
  }
19129
19130
  } = position;
19130
19131
  const indentWidth = this.getListIndentWidth(startElement);
19131
- const x = startX - offsetX + tabWidth + indentWidth;
19132
- const y = startY + ascent;
19132
+ return startX - offsetX + tabWidth + indentWidth;
19133
+ }
19134
+ getListMarker(row) {
19135
+ const startElement = row.elementList[0];
19136
+ if (startElement.listStyle === "checkbox" /* CHECKBOX */) return null;
19137
+ const text = this._getListMarkerText(startElement, row.listIndex);
19138
+ if (!text) return null;
19139
+ return {
19140
+ text,
19141
+ styleElement: this._getListMarkerStyleElement(row.elementList)
19142
+ };
19143
+ }
19144
+ drawListStyle(ctx, row, position) {
19145
+ const { elementList, ascent } = row;
19146
+ const startElement = elementList[0];
19147
+ const x = this.getListMarkerX(row, position);
19148
+ if (x === null) return;
19149
+ const { scale } = this.options;
19150
+ const y = position.coordinate.leftTop[1] + ascent;
19133
19151
  if (startElement.listStyle === "checkbox" /* CHECKBOX */) {
19134
19152
  const { width, height, gap } = this.options.checkbox;
19135
19153
  const checkboxRowElement = {
@@ -19154,12 +19172,11 @@ var ListParticle = class {
19154
19172
  }
19155
19173
  });
19156
19174
  } else {
19157
- const text = this._getListMarkerText(startElement, listIndex);
19158
- if (!text) return;
19159
- const markerStyleElement = this._getListMarkerStyleElement(elementList);
19175
+ const marker = this.getListMarker(row);
19176
+ if (!marker) return;
19160
19177
  ctx.save();
19161
- ctx.font = this.draw.getElementFont(markerStyleElement, scale);
19162
- ctx.fillText(text, x, y);
19178
+ ctx.font = this.draw.getElementFont(marker.styleElement, scale);
19179
+ ctx.fillText(marker.text, x, y);
19163
19180
  ctx.restore();
19164
19181
  }
19165
19182
  }
@@ -24347,1240 +24364,1016 @@ var Command = class {
24347
24364
  }
24348
24365
  };
24349
24366
 
24350
- // src/utils/docx.ts
24367
+ // src/utils/docxLayout.ts
24351
24368
  import {
24352
- AlignmentType,
24353
24369
  BorderStyle,
24354
- ColumnBreak,
24355
24370
  Document as Document2,
24356
24371
  ExternalHyperlink,
24357
24372
  Footer as Footer2,
24358
24373
  Header as Header2,
24359
- HeadingLevel,
24374
+ HeightRule,
24360
24375
  ImageRun,
24361
- LevelFormat,
24362
24376
  LineRuleType,
24363
24377
  Packer,
24364
- PageBreak,
24365
- PageNumber as PageNumber2,
24366
24378
  PageOrientation,
24367
24379
  Paragraph,
24368
24380
  ShadingType,
24381
+ Tab,
24382
+ TabStopType,
24369
24383
  Table,
24370
24384
  TableCell,
24371
24385
  TableLayoutType,
24372
24386
  TableRow,
24373
24387
  TextRun,
24374
- UnderlineType,
24375
24388
  VerticalAlign as DocxVerticalAlign,
24376
- WidthType
24389
+ WidthType,
24390
+ XmlAttributeComponent,
24391
+ XmlComponent
24377
24392
  } from "docx";
24393
+
24394
+ // src/utils/docx.ts
24395
+ import { UnderlineType } from "docx";
24378
24396
  var DEFAULT_DOCX_FILE_NAME = "document.docx";
24379
24397
  var DEFAULT_IMAGE_WIDTH = 320;
24380
24398
  var DEFAULT_IMAGE_HEIGHT = 180;
24381
- var DEFAULT_LINE_HEIGHT = 1.15;
24382
- var docxBulletCharMap = {
24383
- ["disc" /* DISC */]: "\u2022",
24384
- ["circle" /* CIRCLE */]: "\u25E6",
24385
- ["square" /* SQUARE */]: "\u25A0",
24386
- ["checkbox" /* CHECKBOX */]: "\u2611"
24387
- };
24388
- var titleHeadingMap = {
24389
- ["first" /* FIRST */]: HeadingLevel.HEADING_1,
24390
- ["second" /* SECOND */]: HeadingLevel.HEADING_2,
24391
- ["third" /* THIRD */]: HeadingLevel.HEADING_3,
24392
- ["fourth" /* FOURTH */]: HeadingLevel.HEADING_4,
24393
- ["fifth" /* FIFTH */]: HeadingLevel.HEADING_5,
24394
- ["sixth" /* SIXTH */]: HeadingLevel.HEADING_6
24395
- };
24396
- var orderedStyleFormatMap = {
24397
- ["decimal" /* DECIMAL */]: LevelFormat.DECIMAL,
24398
- ["lowerAlpha" /* LOWER_ALPHA */]: LevelFormat.LOWER_LETTER,
24399
- ["upperAlpha" /* UPPER_ALPHA */]: LevelFormat.UPPER_LETTER,
24400
- ["lowerRoman" /* LOWER_ROMAN */]: LevelFormat.LOWER_ROMAN,
24401
- ["upperRoman" /* UPPER_ROMAN */]: LevelFormat.UPPER_ROMAN,
24402
- ["decimalParen" /* DECIMAL_PAREN */]: LevelFormat.DECIMAL,
24403
- decimalZero: LevelFormat.DECIMAL_ZERO,
24404
- lowerAlphaParen: LevelFormat.LOWER_LETTER,
24405
- lowerRomanParen: LevelFormat.LOWER_ROMAN,
24406
- outline: LevelFormat.DECIMAL
24407
- };
24408
- async function exportEditorDataToDocx(payload, options = {}) {
24409
- const fileName = normalizeDocxFileName(options.fileName);
24410
- const file = await createDocxDocument(payload);
24411
- const blob = await Packer.toBlob(file);
24399
+ async function loadImagePayload(src) {
24400
+ const source = src.trim();
24401
+ if (source.startsWith("data:")) {
24402
+ return getImagePayloadFromDataUrl(source);
24403
+ }
24404
+ const response = await fetch(source);
24405
+ if (!response.ok) {
24406
+ throw new Error(`Image request failed: ${response.status}`);
24407
+ }
24408
+ const contentType = response.headers.get("content-type") || "";
24409
+ const data2 = await response.arrayBuffer();
24410
+ return normalizeImagePayload(data2, contentType);
24411
+ }
24412
+ async function getImagePayloadFromDataUrl(src) {
24413
+ const [, meta = "", encoded = ""] = src.match(/^data:([^,]*),(.*)$/) || [];
24414
+ const mime = meta.split(";")[0] || "";
24415
+ const isBase64 = meta.includes(";base64");
24416
+ const text = isBase64 ? atob(encoded) : decodeURIComponent(encoded);
24417
+ const bytes = new Uint8Array(text.length);
24418
+ for (let i = 0; i < text.length; i++) {
24419
+ bytes[i] = text.charCodeAt(i);
24420
+ }
24421
+ return normalizeImagePayload(bytes.buffer, mime);
24422
+ }
24423
+ async function normalizeImagePayload(data2, mime) {
24424
+ const type = getRegularImageType(mime);
24425
+ if (type) {
24426
+ return {
24427
+ type,
24428
+ data: data2
24429
+ };
24430
+ }
24431
+ if (mime.includes("svg")) {
24432
+ return {
24433
+ type: "svg",
24434
+ data: data2,
24435
+ fallbackPng: await rasterizeSvgToPng(data2)
24436
+ };
24437
+ }
24438
+ const fallbackPng = await rasterizeImageToPng(data2, mime);
24412
24439
  return {
24413
- blob,
24414
- fileName
24440
+ type: "png",
24441
+ data: fallbackPng
24415
24442
  };
24416
24443
  }
24417
- async function createDocxDocument(payload) {
24418
- const { data: data2, options } = payload;
24419
- const editorOptions = options;
24420
- const context = createSerializeContext();
24421
- const headerChildren = editorOptions.header.disabled ? [] : await serializeElementList(data2.header || [], editorOptions, context);
24422
- const footerChildren = editorOptions.footer.disabled ? [] : await serializeElementList(data2.footer || [], editorOptions, context);
24423
- const pageNumberParagraph = createPageNumberParagraph(
24424
- editorOptions.pageNumber
24425
- );
24426
- if (pageNumberParagraph) {
24427
- footerChildren.push(pageNumberParagraph);
24444
+ async function rasterizeSvgToPng(data2) {
24445
+ return rasterizeImageToPng(data2, "image/svg+xml");
24446
+ }
24447
+ async function rasterizeImageToPng(data2, mime) {
24448
+ const blob = new Blob([data2], {
24449
+ type: mime || "image/png"
24450
+ });
24451
+ const url = URL.createObjectURL(blob);
24452
+ try {
24453
+ const image = await loadHtmlImage(url);
24454
+ const canvas = document.createElement("canvas");
24455
+ canvas.width = image.naturalWidth || DEFAULT_IMAGE_WIDTH;
24456
+ canvas.height = image.naturalHeight || DEFAULT_IMAGE_HEIGHT;
24457
+ const context = canvas.getContext("2d");
24458
+ if (!context) {
24459
+ throw new Error("Canvas context is unavailable");
24460
+ }
24461
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
24462
+ const pngBlob = await new Promise((resolve, reject) => {
24463
+ canvas.toBlob((output) => {
24464
+ if (output) {
24465
+ resolve(output);
24466
+ } else {
24467
+ reject(new Error("Failed to create PNG blob"));
24468
+ }
24469
+ }, "image/png");
24470
+ });
24471
+ return await pngBlob.arrayBuffer();
24472
+ } finally {
24473
+ URL.revokeObjectURL(url);
24428
24474
  }
24429
- const sectionChildren = await serializeElementList(
24430
- data2.main,
24431
- editorOptions,
24432
- context
24433
- );
24434
- const { width, height, paperDirection } = editorOptions;
24435
- const pageWidth = paperDirection === "horizontal" /* HORIZONTAL */ ? height : width;
24436
- const pageHeight = paperDirection === "horizontal" /* HORIZONTAL */ ? width : height;
24475
+ }
24476
+ function loadHtmlImage(src) {
24477
+ return new Promise((resolve, reject) => {
24478
+ const image = new Image();
24479
+ image.onload = () => resolve(image);
24480
+ image.onerror = () => reject(new Error("Failed to load image"));
24481
+ image.src = src;
24482
+ });
24483
+ }
24484
+ function mapUnderlineType(style) {
24485
+ switch (style) {
24486
+ case "double" /* DOUBLE */:
24487
+ return UnderlineType.DOUBLE;
24488
+ case "dashed" /* DASHED */:
24489
+ return UnderlineType.DASH;
24490
+ case "dotted" /* DOTTED */:
24491
+ return UnderlineType.DOTTED;
24492
+ case "wavy" /* WAVY */:
24493
+ return UnderlineType.WAVE;
24494
+ default:
24495
+ return UnderlineType.SINGLE;
24496
+ }
24497
+ }
24498
+ function normalizeHexColor(color, fallback) {
24499
+ const normalized = normalizeHexLiteral(color) || normalizeRgbColor(color) || normalizeBrowserColor(color);
24500
+ if (normalized) {
24501
+ return normalized;
24502
+ }
24503
+ return fallback ? normalizeHexLiteral(fallback) || void 0 : void 0;
24504
+ }
24505
+ function normalizeHexLiteral(color) {
24506
+ const value = color.trim().replace(/^#/, "");
24507
+ if (/^[\da-f]{3}$/i.test(value)) {
24508
+ return value.split("").map((part) => `${part}${part}`).join("").toUpperCase();
24509
+ }
24510
+ if (/^[\da-f]{4}$/i.test(value)) {
24511
+ return value.slice(0, 3).split("").map((part) => `${part}${part}`).join("").toUpperCase();
24512
+ }
24513
+ if (/^[\da-f]{6}$/i.test(value)) {
24514
+ return value.toUpperCase();
24515
+ }
24516
+ if (/^[\da-f]{8}$/i.test(value)) {
24517
+ return value.slice(0, 6).toUpperCase();
24518
+ }
24519
+ return void 0;
24520
+ }
24521
+ function normalizeRgbColor(color) {
24522
+ const match = color.trim().match(/^rgba?\((.+)\)$/i);
24523
+ if (!match) {
24524
+ return void 0;
24525
+ }
24526
+ const parts = match[1].replace(/\s*\/\s*/g, ",").split(/\s*,\s*|\s+/).filter(Boolean);
24527
+ if (parts.length < 3) {
24528
+ return void 0;
24529
+ }
24530
+ const red = parseRgbChannel(parts[0]);
24531
+ const green = parseRgbChannel(parts[1]);
24532
+ const blue = parseRgbChannel(parts[2]);
24533
+ if (red === null || green === null || blue === null) {
24534
+ return void 0;
24535
+ }
24536
+ const alpha = parts[3] !== void 0 ? parseAlphaChannel(parts[3]) : 1;
24537
+ if (alpha === null || alpha <= 0) {
24538
+ return void 0;
24539
+ }
24540
+ const flattened = alpha >= 1 ? [red, green, blue] : [
24541
+ flattenChannel(red, alpha),
24542
+ flattenChannel(green, alpha),
24543
+ flattenChannel(blue, alpha)
24544
+ ];
24545
+ return flattened.map(toHexChannel).join("");
24546
+ }
24547
+ function normalizeBrowserColor(color) {
24548
+ if (typeof document === "undefined") {
24549
+ return void 0;
24550
+ }
24551
+ const canvas = document.createElement("canvas");
24552
+ const context = canvas.getContext("2d");
24553
+ if (!context) {
24554
+ return void 0;
24555
+ }
24556
+ context.fillStyle = "#000000";
24557
+ context.fillStyle = color;
24558
+ const normalized = context.fillStyle;
24559
+ if (typeof normalized !== "string") {
24560
+ return void 0;
24561
+ }
24562
+ return normalizeHexLiteral(normalized) || normalizeRgbColor(normalized);
24563
+ }
24564
+ function parseRgbChannel(value) {
24565
+ if (value.endsWith("%")) {
24566
+ const percent = Number(value.slice(0, -1));
24567
+ if (!Number.isFinite(percent)) {
24568
+ return null;
24569
+ }
24570
+ return clampColorChannel(Math.round(percent / 100 * 255));
24571
+ }
24572
+ const channel = Number(value);
24573
+ if (!Number.isFinite(channel)) {
24574
+ return null;
24575
+ }
24576
+ return clampColorChannel(Math.round(channel));
24577
+ }
24578
+ function parseAlphaChannel(value) {
24579
+ if (value.endsWith("%")) {
24580
+ const percent = Number(value.slice(0, -1));
24581
+ if (!Number.isFinite(percent)) {
24582
+ return null;
24583
+ }
24584
+ return Math.min(Math.max(percent / 100, 0), 1);
24585
+ }
24586
+ const alpha = Number(value);
24587
+ if (!Number.isFinite(alpha)) {
24588
+ return null;
24589
+ }
24590
+ return Math.min(Math.max(alpha, 0), 1);
24591
+ }
24592
+ function clampColorChannel(value) {
24593
+ return Math.min(Math.max(value, 0), 255);
24594
+ }
24595
+ function flattenChannel(value, alpha) {
24596
+ return clampColorChannel(Math.round(255 * (1 - alpha) + value * alpha));
24597
+ }
24598
+ function toHexChannel(value) {
24599
+ return value.toString(16).padStart(2, "0").toUpperCase();
24600
+ }
24601
+ function getRegularImageType(mime) {
24602
+ if (mime.includes("png")) return "png";
24603
+ if (mime.includes("jpeg") || mime.includes("jpg")) return "jpg";
24604
+ if (mime.includes("gif")) return "gif";
24605
+ if (mime.includes("bmp")) return "bmp";
24606
+ return null;
24607
+ }
24608
+ function normalizeDocxFileName(fileName) {
24609
+ const trimmed = fileName?.trim();
24610
+ if (!trimmed) {
24611
+ return DEFAULT_DOCX_FILE_NAME;
24612
+ }
24613
+ return trimmed.toLowerCase().endsWith(".docx") ? trimmed : `${trimmed}.docx`;
24614
+ }
24615
+
24616
+ // src/utils/docxLayout.ts
24617
+ var PX_TO_TWIP = 15;
24618
+ var ANCHOR_EPS = 0.5;
24619
+ var RIGHT_SLACK_TWIP = -14400;
24620
+ var TINY_TWIP = 1;
24621
+ var tw = (ctx, layoutPx) => Math.round(layoutPx / ctx.scale * PX_TO_TWIP);
24622
+ var pxTw = (px) => Math.round(px * PX_TO_TWIP);
24623
+ async function exportDrawToDocx(draw, options = {}) {
24624
+ const canvas = document.createElement("canvas");
24625
+ const measureCtx = canvas.getContext("2d");
24626
+ const ctx = {
24627
+ draw,
24628
+ scale: draw.getOptions().scale,
24629
+ measureCtx
24630
+ };
24631
+ const file = await createDocument(ctx);
24632
+ const blob = await Packer.toBlob(file);
24633
+ return { blob, fileName: normalizeDocxFileName(options.fileName) };
24634
+ }
24635
+ async function createDocument(ctx) {
24636
+ const { draw, scale } = ctx;
24637
+ const opts = draw.getOptions();
24638
+ const width = draw.getOriginalWidth();
24639
+ const height = draw.getOriginalHeight();
24640
+ const margins = draw.getOriginalMargins();
24641
+ const header = draw.getHeader();
24642
+ const footer = draw.getFooter();
24643
+ const headerTop = header.getHeaderTop() / scale;
24644
+ const headerExtra = header.getExtraHeight() / scale;
24645
+ const footerExtra = footer.getExtraHeight() / scale;
24646
+ const layoutMargins = draw.getMargins();
24647
+ const body = await serializeMain(ctx, layoutMargins[3]);
24648
+ const headerChildren = opts.header.disabled ? [] : await serializeRows(ctx, header.getRowList(), {
24649
+ startX: layoutMargins[3],
24650
+ width: draw.getInnerWidth(),
24651
+ positionList: header.getPositionList()
24652
+ });
24653
+ const footerChildren = opts.footer.disabled ? [] : await serializeFooter(ctx, width, height, margins);
24654
+ const { pageNumber } = draw.getOptions();
24437
24655
  return new Document2({
24438
- features: {
24439
- updateFields: true
24440
- },
24441
- numbering: {
24442
- config: createNumberingConfig()
24656
+ compatabilityModeVersion: 15,
24657
+ // LibreOffice formats PAGE/NUMPAGES results from the paragraph style
24658
+ styles: {
24659
+ paragraphStyles: [
24660
+ {
24661
+ id: PAGE_NUMBER_STYLE,
24662
+ name: "Windoc Page Number",
24663
+ run: pageNumberRunStyle(pageNumber)
24664
+ }
24665
+ ]
24443
24666
  },
24667
+ defaultTabStop: pxTw(width),
24444
24668
  sections: [
24445
24669
  {
24446
24670
  properties: {
24447
24671
  page: {
24448
24672
  size: {
24449
- width: pxToTwips(pageWidth),
24450
- height: pxToTwips(pageHeight),
24451
- orientation: paperDirection === "horizontal" /* HORIZONTAL */ ? PageOrientation.LANDSCAPE : PageOrientation.PORTRAIT
24673
+ width: pxTw(width),
24674
+ height: pxTw(height),
24675
+ orientation: opts.paperDirection === "horizontal" /* HORIZONTAL */ ? PageOrientation.LANDSCAPE : PageOrientation.PORTRAIT
24452
24676
  },
24453
24677
  margin: {
24454
- top: pxToTwips(editorOptions.margins[0]),
24455
- right: pxToTwips(editorOptions.margins[1]),
24456
- bottom: pxToTwips(editorOptions.margins[2]),
24457
- left: pxToTwips(editorOptions.margins[3]),
24458
- header: pxToTwips(editorOptions.header.top),
24459
- footer: pxToTwips(editorOptions.footer.bottom)
24460
- },
24461
- pageNumbers: !editorOptions.pageNumber.disabled && editorOptions.pageNumber.fromPageNo === 0 ? {
24462
- start: editorOptions.pageNumber.startPageNo
24463
- } : void 0
24678
+ top: pxTw(margins[0] + headerExtra),
24679
+ right: pxTw(margins[1]),
24680
+ bottom: pxTw(margins[2] + footerExtra),
24681
+ left: pxTw(margins[3]),
24682
+ header: pxTw(headerTop),
24683
+ footer: pxTw(footer.getFooterBottom() / scale),
24684
+ gutter: 0
24685
+ }
24464
24686
  }
24465
24687
  },
24466
- headers: headerChildren.length > 0 ? {
24467
- default: new Header2({
24468
- children: headerChildren
24469
- })
24470
- } : void 0,
24471
- footers: footerChildren.length > 0 ? {
24472
- default: new Footer2({
24473
- children: footerChildren
24474
- })
24475
- } : void 0,
24476
- children: sectionChildren.length ? sectionChildren : [new Paragraph({})]
24688
+ headers: headerChildren.length ? { default: new Header2({ children: headerChildren }) } : void 0,
24689
+ footers: footerChildren.length ? { default: new Footer2({ children: footerChildren }) } : void 0,
24690
+ children: body.length ? body : [new Paragraph({})]
24477
24691
  }
24478
24692
  ]
24479
24693
  });
24480
24694
  }
24481
- async function serializeElementList(elementList, options, context) {
24482
- const blocks = [];
24483
- let inlineBuffer = [];
24484
- const flushInlineBuffer = async () => {
24485
- if (!inlineBuffer.length) return;
24486
- blocks.push(
24487
- ...await serializeInlineElements(inlineBuffer, options, context)
24488
- );
24489
- inlineBuffer = [];
24695
+ async function serializeMain(ctx, startX) {
24696
+ const { draw } = ctx;
24697
+ const zone = {
24698
+ startX,
24699
+ width: draw.getInnerWidth(),
24700
+ positionList: draw.getPosition().getOriginalMainPositionList()
24490
24701
  };
24491
- for (let i = 0; i < elementList.length; i++) {
24492
- const element = elementList[i];
24493
- if (element.type === "area" /* AREA */ && element.valueList?.length) {
24494
- await flushInlineBuffer();
24495
- blocks.push(
24496
- ...await serializeElementList(element.valueList, options, context)
24497
- );
24498
- continue;
24499
- }
24500
- if (element.type === "title" /* TITLE */ && element.valueList?.length) {
24501
- await flushInlineBuffer();
24502
- blocks.push(
24503
- ...await serializeInlineElements(element.valueList, options, context, {
24504
- heading: titleHeadingMap[element.level || "first" /* FIRST */]
24505
- })
24506
- );
24507
- continue;
24508
- }
24509
- if (element.type === "list" /* LIST */ && element.valueList?.length) {
24510
- await flushInlineBuffer();
24511
- blocks.push(...await serializeListElement(element, options, context));
24512
- continue;
24513
- }
24514
- if (element.type === "table" /* TABLE */ && element.trList?.length) {
24515
- await flushInlineBuffer();
24516
- blocks.push(await serializeTableElement(element, options, context));
24517
- continue;
24518
- }
24519
- if (element.type === "pageBreak" /* PAGE_BREAK */) {
24520
- await flushInlineBuffer();
24521
- blocks.push(
24522
- new Paragraph({
24523
- children: [new PageBreak()]
24524
- })
24525
- );
24526
- continue;
24527
- }
24528
- if (element.type === "separator" /* SEPARATOR */) {
24529
- await flushInlineBuffer();
24530
- blocks.push(
24531
- new Paragraph({
24532
- thematicBreak: true
24533
- })
24534
- );
24535
- continue;
24536
- }
24537
- if (element.type === "image" /* IMAGE */ && element.imgDisplay && element.imgDisplay !== "inline") {
24538
- await flushInlineBuffer();
24539
- blocks.push(...await serializeInlineElements([element], options));
24540
- continue;
24541
- }
24542
- if (element.type === "block" /* BLOCK */) {
24543
- await flushInlineBuffer();
24544
- const blockText = getBlockFallbackText(element);
24545
- if (blockText) {
24546
- blocks.push(
24547
- ...await serializeInlineElements(
24548
- [{ value: blockText }],
24549
- options,
24550
- context
24702
+ const children = [];
24703
+ const pageRowList = draw.getPageRowList();
24704
+ for (let p = 0; p < pageRowList.length; p++) {
24705
+ children.push(
24706
+ ...await serializeRows(ctx, pageRowList[p], zone, {
24707
+ pageBreakBefore: p > 0
24708
+ })
24709
+ );
24710
+ }
24711
+ return children;
24712
+ }
24713
+ async function serializeRows(ctx, rowList, zone, options = {}) {
24714
+ const { pageBreakBefore = false, padTop = 0, padBottom = 0 } = options;
24715
+ const children = [];
24716
+ for (let r = 0; r < rowList.length; r++) {
24717
+ const row = rowList[r];
24718
+ const isFirst = r === 0;
24719
+ const isLast = r === rowList.length - 1;
24720
+ const table = row.elementList.find((el) => el.type === "table" /* TABLE */);
24721
+ if (table) {
24722
+ if (isFirst && (pageBreakBefore || padTop) || row.offsetY) {
24723
+ children.push(
24724
+ createSpacerParagraph(
24725
+ isFirst && pageBreakBefore,
24726
+ (isFirst ? padTop : 0) + (row.offsetY || 0) / ctx.scale
24551
24727
  )
24552
24728
  );
24553
24729
  }
24730
+ const position = zone.positionList[row.startIndex + row.elementList.indexOf(table)];
24731
+ children.push(await serializeTable(ctx, table, position, zone));
24732
+ const rest = (row.height + (row.spaceBelow || 0)) / ctx.scale - table.height + (isLast ? padBottom : 0);
24733
+ if (rest * PX_TO_TWIP >= 1) {
24734
+ children.push(createSpacerParagraph(false, rest));
24735
+ }
24554
24736
  continue;
24555
24737
  }
24556
- inlineBuffer.push(element);
24738
+ const rowOptions = {
24739
+ pageBreakBefore: isFirst && pageBreakBefore,
24740
+ padTop: isFirst ? padTop : 0,
24741
+ padBottom: isLast ? padBottom : 0
24742
+ };
24743
+ if (!isFirst && isTextRow(rowList[r - 1])) rowOptions.skipLead = true;
24744
+ rowOptions.rowY = rowY(zone, row);
24745
+ if (!isLast && isTextRow(rowList[r + 1])) {
24746
+ rowOptions.extraAfter = rowLead(ctx, rowList[r + 1], {
24747
+ rowY: rowY(zone, rowList[r + 1])
24748
+ });
24749
+ }
24750
+ const lead = rowOptions.pageBreakBefore ? rowLead(ctx, row, rowOptions) : 0;
24751
+ if (lead) {
24752
+ children.push(createSpacerParagraph(true, lead / PX_TO_TWIP));
24753
+ rowOptions.pageBreakBefore = false;
24754
+ rowOptions.skipLead = true;
24755
+ }
24756
+ children.push(await serializeRow(ctx, row, zone, rowOptions));
24557
24757
  }
24558
- await flushInlineBuffer();
24559
- return blocks;
24758
+ return children;
24560
24759
  }
24561
- async function serializeInlineElements(elementList, options, _context, overrides = {}) {
24562
- const paragraphs = [];
24563
- let current = null;
24564
- const getParagraphContext = (element) => ({
24565
- heading: overrides.heading,
24566
- numbering: overrides.numbering,
24567
- alignment: overrides.alignment !== void 0 ? overrides.alignment : mapRowFlexToAlignment(element?.rowFlex),
24568
- rowMargin: overrides.rowMargin !== void 0 ? overrides.rowMargin : element?.rowMargin
24569
- });
24570
- const flushParagraph = (context) => {
24571
- if (!current) {
24572
- if (!context) return;
24573
- paragraphs.push(createParagraph([], context, options.defaultRowMargin));
24760
+ function rowY(zone, row) {
24761
+ return zone.positionList[row.startIndex]?.coordinate.leftTop[1];
24762
+ }
24763
+ function isTextRow(row) {
24764
+ return !row.elementList.some((el) => el.type === "table" /* TABLE */);
24765
+ }
24766
+ async function serializeRow(ctx, row, zone, options, suffix) {
24767
+ const { pageBreakBefore = false } = options;
24768
+ const { draw, scale } = ctx;
24769
+ const positions = zone.positionList;
24770
+ const children = [];
24771
+ const tabStops = [];
24772
+ const firstPosition = positions[row.startIndex];
24773
+ let pen = 0;
24774
+ let indent = firstPosition ? (firstPosition.coordinate.leftTop[0] - zone.startX) / scale : 0;
24775
+ let started = false;
24776
+ const anchorTo = (layoutX) => {
24777
+ const target = (layoutX - zone.startX) / scale;
24778
+ if (!started) {
24779
+ indent = target;
24780
+ pen = target;
24781
+ started = true;
24574
24782
  return;
24575
24783
  }
24576
- paragraphs.push(
24577
- createParagraph(
24578
- current.children,
24579
- current.context,
24580
- options.defaultRowMargin
24581
- )
24582
- );
24583
- current = null;
24584
- };
24585
- const ensureParagraph = (element) => {
24586
- if (!current) {
24587
- current = {
24588
- children: [],
24589
- context: getParagraphContext(element)
24590
- };
24784
+ if (target - pen > ANCHOR_EPS) {
24785
+ tabStops.push(pxTw(target));
24786
+ children.push(new TextRun({ children: [new Tab()] }));
24787
+ pen = target;
24591
24788
  }
24592
- return current;
24593
24789
  };
24594
- const appendText = (element, text, childFactory, preserveTrailingBreak = false) => {
24595
- const normalized = normalizeText(text);
24596
- const parts = normalized.split("\n");
24597
- let lastSeparatorFlushedContent = false;
24598
- for (let i = 0; i < parts.length; i++) {
24599
- const segment = parts[i];
24600
- if (segment) {
24601
- ensureParagraph(element).children.push(childFactory(segment));
24602
- }
24603
- if (i < parts.length - 1) {
24604
- if (!current) {
24605
- paragraphs.push(
24606
- createParagraph(
24607
- [],
24608
- getParagraphContext(element),
24609
- options.defaultRowMargin
24610
- )
24611
- );
24612
- lastSeparatorFlushedContent = false;
24613
- } else {
24614
- flushParagraph();
24615
- lastSeparatorFlushedContent = true;
24616
- }
24617
- }
24618
- }
24619
- if (preserveTrailingBreak && normalized.endsWith("\n") && lastSeparatorFlushedContent) {
24620
- paragraphs.push(
24621
- createParagraph(
24622
- [],
24623
- getParagraphContext(element),
24624
- options.defaultRowMargin
24625
- )
24790
+ if (row.isList && firstPosition) {
24791
+ const listParticle = draw.getListParticle();
24792
+ const markerX = listParticle.getListMarkerX(row, firstPosition);
24793
+ const marker = markerX === null ? null : listParticle.getListMarker(row);
24794
+ if (markerX !== null && marker) {
24795
+ anchorTo(markerX);
24796
+ children.push(createTextRun(ctx, marker.text, marker.styleElement));
24797
+ pen += measure(ctx, marker.text, marker.styleElement);
24798
+ }
24799
+ }
24800
+ let run = null;
24801
+ const flush = () => {
24802
+ if (!run) return;
24803
+ children.push(createTextRun(ctx, run.text, run.element));
24804
+ run = null;
24805
+ };
24806
+ for (let j = 0; j < row.elementList.length; j++) {
24807
+ const element = row.elementList[j];
24808
+ const position = positions[row.startIndex + j];
24809
+ if (!position) continue;
24810
+ if (element.hide || element.control?.hide || element.area?.hide) continue;
24811
+ if (element.type === "separator" /* SEPARATOR */) {
24812
+ flush();
24813
+ return createSeparatorParagraph(
24814
+ ctx,
24815
+ row,
24816
+ element,
24817
+ position.coordinate.leftTop[0],
24818
+ position.coordinate.leftTop[1],
24819
+ zone,
24820
+ options
24626
24821
  );
24627
24822
  }
24628
- };
24629
- for (let i = 0; i < elementList.length; i++) {
24630
- const element = elementList[i];
24631
- if (element.type === "hyperlink" /* HYPERLINK */ && element.valueList?.length) {
24632
- const hyperlink = await createHyperlinkChild(element, options);
24633
- if (hyperlink) {
24634
- ensureParagraph(element).children.push(hyperlink);
24635
- }
24823
+ if (element.value === ZERO || element.type === "tab" /* TAB */ || element.type === "pageBreak" /* PAGE_BREAK */ || element.type === "columnBreak" /* COLUMN_BREAK */) {
24636
24824
  continue;
24637
24825
  }
24826
+ const x = position.coordinate.leftTop[0];
24827
+ const layoutWidth = element.metrics.width / scale;
24638
24828
  if (element.type === "image" /* IMAGE */) {
24639
- const imageChild = await createImageChild(element);
24640
- if (!imageChild) {
24641
- appendText(
24642
- element,
24643
- "[Image unavailable]",
24644
- (segment) => createTextRun(
24645
- segment,
24646
- element,
24647
- options.defaultSize,
24648
- options.defaultFont
24649
- ),
24650
- i === elementList.length - 1
24651
- );
24652
- continue;
24653
- }
24654
- ensureParagraph(element).children.push(imageChild);
24829
+ flush();
24830
+ anchorTo(x);
24831
+ const image = await createImageRun(element);
24832
+ if (image) children.push(image);
24833
+ pen += layoutWidth;
24655
24834
  continue;
24656
24835
  }
24657
- if (element.type === "columnBreak" /* COLUMN_BREAK */) {
24658
- ensureParagraph(element).children.push(new ColumnBreak());
24659
- continue;
24660
- }
24661
- if (element.type === "tab" /* TAB */) {
24662
- appendText(
24663
- element,
24664
- " ",
24665
- (segment) => createTextRun(
24666
- segment,
24667
- element,
24668
- options.defaultSize,
24669
- options.defaultFont
24670
- ),
24671
- i === elementList.length - 1
24836
+ if (element.type === "label" /* LABEL */) {
24837
+ flush();
24838
+ const padding = element.label?.padding || draw.getOptions().label.defaultPadding;
24839
+ anchorTo(x + padding[3] * scale);
24840
+ children.push(
24841
+ createTextRun(ctx, element.value, element, labelShading(ctx, element))
24672
24842
  );
24843
+ pen += measure(ctx, element.value, element);
24673
24844
  continue;
24674
24845
  }
24675
- const textValue = getInlineElementText(element);
24676
- if (!textValue) {
24677
- continue;
24678
- }
24679
- appendText(
24680
- element,
24681
- textValue,
24682
- (segment) => createTextRun(
24683
- segment,
24684
- element,
24685
- options.defaultSize,
24686
- options.defaultFont
24687
- ),
24688
- i === elementList.length - 1
24689
- );
24690
- }
24691
- if (current) {
24692
- flushParagraph();
24693
- }
24694
- return paragraphs.length ? paragraphs : [createParagraph([], overrides, options.defaultRowMargin)];
24695
- }
24696
- async function serializeListElement(element, options, context) {
24697
- const zipList = zipElementList(element.valueList || []);
24698
- const listItemMap = splitListElement(zipList);
24699
- const paragraphs = [];
24700
- const listInstance = createListInstance(context);
24701
- for (const listItemElements of listItemMap.values()) {
24702
- const numbering = getListNumbering(
24703
- getListItemNumberingElement(listItemElements, element),
24704
- listInstance
24705
- );
24706
- paragraphs.push(
24707
- ...await serializeInlineElements(listItemElements, options, context, {
24708
- numbering
24709
- })
24710
- );
24711
- }
24712
- return paragraphs;
24713
- }
24714
- async function serializeTableElement(element, options, context) {
24715
- const rows = [];
24716
- const trList = element.trList || [];
24717
- const tableContext = createTableSerializeContext(element);
24718
- for (let i = 0; i < trList.length; i++) {
24719
- rows.push(
24720
- await serializeTableRow(trList[i], options, context, tableContext)
24721
- );
24722
- }
24723
- const tableWidth = getTableWidthFromColgroup(element.colgroup);
24724
- return new Table({
24725
- rows,
24726
- width: tableWidth ? {
24727
- size: pxToTwips(tableWidth),
24728
- type: WidthType.DXA
24729
- } : {
24730
- size: 100,
24731
- type: WidthType.PERCENTAGE
24732
- },
24733
- columnWidths: element.colgroup?.map((col) => pxToTwips(col.width)),
24734
- layout: TableLayoutType.FIXED,
24735
- borders: createTableBorders(element)
24736
- });
24737
- }
24738
- async function serializeTableRow(tr, options, context, tableContext) {
24739
- const children = [];
24740
- for (let i = 0; i < tr.tdList.length; i++) {
24741
- children.push(
24742
- await serializeTableCell(tr.tdList[i], options, context, tableContext)
24743
- );
24744
- }
24745
- return new TableRow({
24746
- children
24747
- });
24748
- }
24749
- async function serializeTableCell(td, options, context, tableContext) {
24750
- const children = await serializeElementList(td.value, options, context);
24751
- const shadingFill = td.backgroundColor ? normalizeHexColor(td.backgroundColor) : void 0;
24752
- const cellWidth = tableContext.cellLayoutMap.get(td)?.width || td.width;
24753
- return new TableCell({
24754
- children: children.length ? children : [new Paragraph({})],
24755
- columnSpan: td.colspan > 1 ? td.colspan : void 0,
24756
- rowSpan: td.rowspan > 1 ? td.rowspan : void 0,
24757
- verticalAlign: mapCellVerticalAlign(td.verticalAlign),
24758
- width: cellWidth ? {
24759
- size: pxToTwips(cellWidth),
24760
- type: WidthType.DXA
24761
- } : void 0,
24762
- shading: shadingFill ? {
24763
- fill: shadingFill,
24764
- type: ShadingType.CLEAR
24765
- } : void 0,
24766
- margins: mapPaddingToTableMargins(td.padding),
24767
- borders: createTableCellBorders(
24768
- td,
24769
- tableContext.borderColor,
24770
- tableContext.borderWidth
24771
- )
24772
- });
24773
- }
24774
- function createParagraph(children, context, defaultRowMargin) {
24775
- return new Paragraph({
24776
- children,
24777
- heading: context.heading,
24778
- numbering: context.numbering,
24779
- alignment: context.alignment,
24780
- spacing: {
24781
- line: Math.round(
24782
- 240 * (context.rowMargin || defaultRowMargin || DEFAULT_LINE_HEIGHT)
24783
- ),
24784
- lineRule: LineRuleType.AUTO
24785
- }
24786
- });
24787
- }
24788
- function createTextRun(text, element, defaultSize, defaultFont) {
24789
- const color = element.color ? normalizeHexColor(element.color, "000000") : void 0;
24790
- const highlightFill = element.highlight ? normalizeHexColor(element.highlight) : void 0;
24791
- return new TextRun({
24792
- text,
24793
- bold: !!element.bold,
24794
- italics: !!element.italic,
24795
- strike: !!element.strikeout,
24796
- subScript: element.type === "subscript" /* SUBSCRIPT */,
24797
- superScript: element.type === "superscript" /* SUPERSCRIPT */,
24798
- color,
24799
- shading: highlightFill ? {
24800
- fill: highlightFill,
24801
- type: ShadingType.CLEAR
24802
- } : void 0,
24803
- underline: element.underline ? {
24804
- type: mapUnderlineType(element.textDecoration?.style)
24805
- } : void 0,
24806
- font: element.font || defaultFont,
24807
- size: Math.round((element.size || defaultSize) * 2)
24808
- });
24809
- }
24810
- async function createHyperlinkChild(element, options) {
24811
- if (!element.url) {
24812
- const fallbackText = getTextFromElementList(element.valueList || []);
24813
- return fallbackText ? createTextRun(
24814
- fallbackText,
24815
- element.valueList?.[0] || element,
24816
- options.defaultSize,
24817
- options.defaultFont
24818
- ) : null;
24819
- }
24820
- const children = await createHyperlinkRuns(
24821
- element.valueList || [],
24822
- options.defaultSize,
24823
- options.defaultFont
24824
- );
24825
- if (!children.length) {
24826
- return null;
24827
- }
24828
- return new ExternalHyperlink({
24829
- link: element.url,
24830
- children
24831
- });
24832
- }
24833
- async function createHyperlinkRuns(valueList, defaultSize, defaultFont) {
24834
- const children = [];
24835
- for (let i = 0; i < valueList.length; i++) {
24836
- const element = valueList[i];
24837
- if (element.type === "tab" /* TAB */) {
24838
- children.push(createTextRun(" ", element, defaultSize, defaultFont));
24839
- continue;
24840
- }
24841
- const text = normalizeText(getInlineElementText(element)).replace(
24842
- /\n/g,
24843
- " "
24844
- );
24845
- if (text) {
24846
- children.push(createTextRun(text, element, defaultSize, defaultFont));
24847
- }
24848
- }
24849
- return children;
24850
- }
24851
- async function createImageChild(element) {
24852
- try {
24853
- const image = await loadImagePayload(element.value);
24854
- const width = Math.max(1, Math.round(element.width || DEFAULT_IMAGE_WIDTH));
24855
- const height = Math.max(
24856
- 1,
24857
- Math.round(element.height || DEFAULT_IMAGE_HEIGHT)
24858
- );
24859
- if (image.type === "svg" && image.fallbackPng) {
24860
- return new ImageRun({
24861
- type: "svg",
24862
- data: image.data,
24863
- fallback: {
24864
- type: "png",
24865
- data: image.fallbackPng
24866
- },
24867
- transformation: {
24868
- width,
24869
- height
24870
- }
24871
- });
24872
- }
24873
- return new ImageRun({
24874
- type: image.type,
24875
- data: image.data,
24876
- transformation: {
24877
- width,
24878
- height
24846
+ const text = getElementText(element);
24847
+ if (!text) continue;
24848
+ const natural = measure(ctx, text, element);
24849
+ const target = (x - zone.startX) / scale;
24850
+ const isDrift = !started || target - pen > ANCHOR_EPS;
24851
+ const extra = layoutWidth - natural;
24852
+ const needsSpacing = Math.abs(extra) * PX_TO_TWIP >= 1;
24853
+ const canJoin = run && !isDrift && !needsSpacing && isSameRunStyle(run.element, element);
24854
+ if (canJoin) {
24855
+ run.text += text;
24856
+ } else {
24857
+ flush();
24858
+ anchorTo(x);
24859
+ if (needsSpacing) {
24860
+ children.push(
24861
+ createTextRun(ctx, text, element, void 0, pxTw(extra))
24862
+ );
24863
+ } else {
24864
+ run = { text, element };
24879
24865
  }
24880
- });
24881
- } catch {
24882
- return null;
24883
- }
24884
- }
24885
- async function loadImagePayload(src) {
24886
- const source = src.trim();
24887
- if (source.startsWith("data:")) {
24888
- return getImagePayloadFromDataUrl(source);
24889
- }
24890
- const response = await fetch(source);
24891
- if (!response.ok) {
24892
- throw new Error(`Image request failed: ${response.status}`);
24893
- }
24894
- const contentType = response.headers.get("content-type") || "";
24895
- const data2 = await response.arrayBuffer();
24896
- return normalizeImagePayload(data2, contentType);
24897
- }
24898
- async function getImagePayloadFromDataUrl(src) {
24899
- const [, meta = "", encoded = ""] = src.match(/^data:([^,]*),(.*)$/) || [];
24900
- const mime = meta.split(";")[0] || "";
24901
- const isBase64 = meta.includes(";base64");
24902
- const text = isBase64 ? atob(encoded) : decodeURIComponent(encoded);
24903
- const bytes = new Uint8Array(text.length);
24904
- for (let i = 0; i < text.length; i++) {
24905
- bytes[i] = text.charCodeAt(i);
24906
- }
24907
- return normalizeImagePayload(bytes.buffer, mime);
24908
- }
24909
- async function normalizeImagePayload(data2, mime) {
24910
- const type = getRegularImageType(mime);
24911
- if (type) {
24912
- return {
24913
- type,
24914
- data: data2
24915
- };
24916
- }
24917
- if (mime.includes("svg")) {
24918
- return {
24919
- type: "svg",
24920
- data: data2,
24921
- fallbackPng: await rasterizeSvgToPng(data2)
24922
- };
24923
- }
24924
- const fallbackPng = await rasterizeImageToPng(data2, mime);
24925
- return {
24926
- type: "png",
24927
- data: fallbackPng
24928
- };
24929
- }
24930
- async function rasterizeSvgToPng(data2) {
24931
- return rasterizeImageToPng(data2, "image/svg+xml");
24932
- }
24933
- async function rasterizeImageToPng(data2, mime) {
24934
- const blob = new Blob([data2], {
24935
- type: mime || "image/png"
24936
- });
24937
- const url = URL.createObjectURL(blob);
24938
- try {
24939
- const image = await loadHtmlImage(url);
24940
- const canvas = document.createElement("canvas");
24941
- canvas.width = image.naturalWidth || DEFAULT_IMAGE_WIDTH;
24942
- canvas.height = image.naturalHeight || DEFAULT_IMAGE_HEIGHT;
24943
- const context = canvas.getContext("2d");
24944
- if (!context) {
24945
- throw new Error("Canvas context is unavailable");
24946
24866
  }
24947
- context.drawImage(image, 0, 0, canvas.width, canvas.height);
24948
- const pngBlob = await new Promise((resolve, reject) => {
24949
- canvas.toBlob((output) => {
24950
- if (output) {
24951
- resolve(output);
24952
- } else {
24953
- reject(new Error("Failed to create PNG blob"));
24954
- }
24955
- }, "image/png");
24956
- });
24957
- return await pngBlob.arrayBuffer();
24958
- } finally {
24959
- URL.revokeObjectURL(url);
24867
+ pen = target + layoutWidth;
24960
24868
  }
24961
- }
24962
- function loadHtmlImage(src) {
24963
- return new Promise((resolve, reject) => {
24964
- const image = new Image();
24965
- image.onload = () => resolve(image);
24966
- image.onerror = () => reject(new Error("Failed to load image"));
24967
- image.src = src;
24968
- });
24969
- }
24970
- function createPageNumberParagraph(pageNumber) {
24971
- if (pageNumber.disabled || pageNumber.fromPageNo > 0) {
24972
- return null;
24869
+ flush();
24870
+ if (!children.length && !suffix) {
24871
+ const total = (options.skipLead ? 0 : rowLead(ctx, row, options)) + rowLine(ctx, row).lineTw + rowSpacing(ctx, row, options).after;
24872
+ return createSpacerParagraph(pageBreakBefore, total / PX_TO_TWIP);
24973
24873
  }
24974
- const children = [];
24975
- const format = pageNumber.format || FORMAT_PLACEHOLDER.PAGE_NO;
24976
- const tokens = format.split(/(\{pageNo\}|\{pageCount\})/);
24977
- for (let i = 0; i < tokens.length; i++) {
24978
- const token = tokens[i];
24979
- if (!token) continue;
24980
- const runChildren = token === FORMAT_PLACEHOLDER.PAGE_NO ? [PageNumber2.CURRENT] : token === FORMAT_PLACEHOLDER.PAGE_COUNT ? [PageNumber2.TOTAL_PAGES] : void 0;
24981
- children.push(
24982
- new TextRun({
24983
- text: runChildren ? void 0 : token,
24984
- children: runChildren,
24985
- color: normalizeHexColor(pageNumber.color || "#000000", "000000"),
24986
- font: pageNumber.font,
24987
- size: Math.round((pageNumber.size || 12) * 2)
24988
- })
24989
- );
24874
+ const stops = tabStops.map((position) => ({ type: TabStopType.LEFT, position }));
24875
+ if (suffix) {
24876
+ stops.push({ type: suffix.tabType, position: suffix.tabStop });
24877
+ children.push(new TextRun({ children: [new Tab()] }), ...suffix.children);
24990
24878
  }
24991
24879
  return new Paragraph({
24992
24880
  children,
24993
- alignment: mapRowFlexToAlignment(pageNumber.rowFlex)
24881
+ style: suffix?.style,
24882
+ pageBreakBefore,
24883
+ widowControl: false,
24884
+ tabStops: stops,
24885
+ indent: { left: pxTw(indent), right: RIGHT_SLACK_TWIP },
24886
+ spacing: rowSpacing(ctx, row, options)
24994
24887
  });
24995
24888
  }
24996
- function createNumberingConfig() {
24997
- const config = [
24998
- createOrderedReference("windoc-ol-decimal", Array(9).fill("decimal" /* DECIMAL */)),
24999
- createOrderedReference(
25000
- "windoc-ol-lower-alpha",
25001
- Array(9).fill("lowerAlpha" /* LOWER_ALPHA */)
25002
- ),
25003
- createOrderedReference(
25004
- "windoc-ol-upper-alpha",
25005
- Array(9).fill("upperAlpha" /* UPPER_ALPHA */)
25006
- ),
25007
- createOrderedReference(
25008
- "windoc-ol-lower-roman",
25009
- Array(9).fill("lowerRoman" /* LOWER_ROMAN */)
25010
- ),
25011
- createOrderedReference(
25012
- "windoc-ol-upper-roman",
25013
- Array(9).fill("upperRoman" /* UPPER_ROMAN */)
25014
- ),
25015
- createOrderedReference(
25016
- "windoc-ol-decimal-paren",
25017
- Array(9).fill("decimalParen" /* DECIMAL_PAREN */)
25018
- ),
25019
- createOrderedReference(
25020
- `windoc-ol-${"olDefault" /* DEFAULT */}`,
25021
- createCycleList(olPresetCycles["olDefault" /* DEFAULT */], 9)
25022
- ),
25023
- createOrderedReference(
25024
- `windoc-ol-${"olParen" /* PARENTHESIS */}`,
25025
- createCycleList(olPresetCycles["olParen" /* PARENTHESIS */], 9)
25026
- ),
25027
- createOrderedReference(
25028
- `windoc-ol-${"olOutline" /* OUTLINE */}`,
25029
- createCycleList(olPresetCycles["olOutline" /* OUTLINE */], 9)
25030
- ),
25031
- createOrderedReference(
25032
- `windoc-ol-${"olUpperA" /* UPPER_ALPHA */}`,
25033
- createCycleList(olPresetCycles["olUpperA" /* UPPER_ALPHA */], 9)
25034
- ),
25035
- createOrderedReference(
25036
- `windoc-ol-${"olRoman" /* ROMAN */}`,
25037
- createCycleList(olPresetCycles["olRoman" /* ROMAN */], 9)
25038
- ),
25039
- createOrderedReference(
25040
- `windoc-ol-${"olZeroPad" /* ZERO_PAD */}`,
25041
- createCycleList(olPresetCycles["olZeroPad" /* ZERO_PAD */], 9)
25042
- ),
25043
- createBulletReference(
25044
- "windoc-ul-disc",
25045
- Array(9).fill(docxBulletCharMap["disc" /* DISC */])
25046
- ),
25047
- createBulletReference(
25048
- "windoc-ul-circle",
25049
- Array(9).fill(docxBulletCharMap["circle" /* CIRCLE */])
25050
- ),
25051
- createBulletReference(
25052
- "windoc-ul-square",
25053
- Array(9).fill(docxBulletCharMap["square" /* SQUARE */])
25054
- ),
25055
- createBulletReference(
25056
- "windoc-ul-checkbox",
25057
- Array(9).fill(docxBulletCharMap["checkbox" /* CHECKBOX */])
25058
- ),
25059
- createBulletReference(
25060
- `windoc-ul-${"ulDefault" /* DEFAULT */}`,
25061
- createCycleList(ulPresetCycles["ulDefault" /* DEFAULT */], 9)
25062
- ),
25063
- createBulletReference(
25064
- `windoc-ul-${"ulDiamond" /* DIAMOND */}`,
25065
- createCycleList(ulPresetCycles["ulDiamond" /* DIAMOND */], 9)
25066
- ),
25067
- createBulletReference(
25068
- `windoc-ul-${"ulHollowSq" /* HOLLOW_SQ */}`,
25069
- createCycleList(ulPresetCycles["ulHollowSq" /* HOLLOW_SQ */], 9)
25070
- ),
25071
- createBulletReference(
25072
- `windoc-ul-${"ulArrow" /* ARROW */}`,
25073
- createCycleList(ulPresetCycles["ulArrow" /* ARROW */], 9)
25074
- ),
25075
- createBulletReference(
25076
- `windoc-ul-${"ulStar" /* STAR */}`,
25077
- createCycleList(ulPresetCycles["ulStar" /* STAR */], 9)
25078
- ),
25079
- createBulletReference(
25080
- `windoc-ul-${"ulCheckArr" /* CHECK_ARROW */}`,
25081
- createCycleList(ulPresetCycles["ulCheckArr" /* CHECK_ARROW */], 9)
25082
- )
25083
- ];
25084
- return config;
25085
- }
25086
- function createOrderedReference(reference, styles) {
25087
- return {
25088
- reference,
25089
- levels: styles.map((style, level) => ({
25090
- level,
25091
- format: orderedStyleFormatMap[style] || LevelFormat.DECIMAL,
25092
- text: getOrderedLevelText(style, level),
25093
- alignment: AlignmentType.START,
25094
- style: {
25095
- paragraph: {
25096
- indent: {
25097
- left: 720 * (level + 1),
25098
- hanging: 360
25099
- }
25100
- }
25101
- }
25102
- }))
25103
- };
25104
- }
25105
- function createBulletReference(reference, bullets) {
25106
- return {
25107
- reference,
25108
- levels: bullets.map((bullet, level) => ({
25109
- level,
25110
- format: LevelFormat.BULLET,
25111
- text: bullet,
25112
- alignment: AlignmentType.START,
25113
- style: {
25114
- paragraph: {
25115
- indent: {
25116
- left: 720 * (level + 1),
25117
- hanging: 360
25118
- }
25119
- }
25120
- }
25121
- }))
25122
- };
25123
- }
25124
- function getOrderedLevelText(style, level) {
25125
- const placeholder = `%${level + 1}`;
25126
- if (style === "outline") {
25127
- return Array.from({ length: level + 1 }, (_, index) => `%${index + 1}`).join(
25128
- "."
25129
- ) + ".";
25130
- }
25131
- if (style.endsWith("Paren") || style === "decimalParen" /* DECIMAL_PAREN */) {
25132
- return `${placeholder})`;
25133
- }
25134
- return `${placeholder}.`;
25135
- }
25136
- function createCycleList(source = [], size) {
25137
- const result = [];
25138
- for (let i = 0; i < size; i++) {
25139
- result.push(source[i % source.length]);
25140
- }
25141
- return result;
25142
- }
25143
- function getListNumbering(element, instance) {
25144
- const level = Math.max(0, Math.min(element.listLevel || 0, 8));
25145
- if (element.listType === "ul" /* UL */) {
25146
- const reference2 = element.listPreset ? `windoc-ul-${element.listPreset}` : `windoc-ul-${element.listStyle || "disc" /* DISC */}`;
25147
- return {
25148
- reference: reference2,
25149
- level,
25150
- instance
25151
- };
25152
- }
25153
- const reference = element.listPreset ? `windoc-ol-${element.listPreset}` : getOrderedReferenceFromStyle(element.listStyle);
25154
- return {
25155
- reference,
25156
- level,
25157
- instance
25158
- };
25159
- }
25160
- function getOrderedReferenceFromStyle(style) {
25161
- switch (style) {
25162
- case "lowerAlpha" /* LOWER_ALPHA */:
25163
- return "windoc-ol-lower-alpha";
25164
- case "upperAlpha" /* UPPER_ALPHA */:
25165
- return "windoc-ol-upper-alpha";
25166
- case "lowerRoman" /* LOWER_ROMAN */:
25167
- return "windoc-ol-lower-roman";
25168
- case "upperRoman" /* UPPER_ROMAN */:
25169
- return "windoc-ol-upper-roman";
25170
- case "decimalParen" /* DECIMAL_PAREN */:
25171
- return "windoc-ol-decimal-paren";
25172
- default:
25173
- return "windoc-ol-decimal";
25174
- }
25175
- }
25176
- function createTableBorders(element) {
25177
- const outerBorder = createBorder(
25178
- element.borderColor,
25179
- BorderStyle.SINGLE,
25180
- element.borderExternalWidth || element.borderWidth
25181
- );
25182
- const innerBorder = createBorder(
25183
- element.borderColor,
25184
- BorderStyle.SINGLE,
25185
- element.borderWidth
25186
- );
25187
- switch (element.borderType) {
25188
- case "empty" /* EMPTY */:
25189
- return {
25190
- top: noneBorder(),
25191
- bottom: noneBorder(),
25192
- left: noneBorder(),
25193
- right: noneBorder(),
25194
- insideHorizontal: noneBorder(),
25195
- insideVertical: noneBorder()
25196
- };
25197
- case "external" /* EXTERNAL */:
25198
- return {
25199
- top: outerBorder,
25200
- bottom: outerBorder,
25201
- left: outerBorder,
25202
- right: outerBorder,
25203
- insideHorizontal: noneBorder(),
25204
- insideVertical: noneBorder()
25205
- };
25206
- case "internal" /* INTERNAL */:
25207
- return {
25208
- top: noneBorder(),
25209
- bottom: noneBorder(),
25210
- left: noneBorder(),
25211
- right: noneBorder(),
25212
- insideHorizontal: innerBorder,
25213
- insideVertical: innerBorder
25214
- };
25215
- case "dash" /* DASH */:
25216
- return {
25217
- top: createBorder(
25218
- element.borderColor,
25219
- BorderStyle.DASHED,
25220
- element.borderExternalWidth || element.borderWidth
25221
- ),
25222
- bottom: createBorder(
25223
- element.borderColor,
25224
- BorderStyle.DASHED,
25225
- element.borderExternalWidth || element.borderWidth
25226
- ),
25227
- left: createBorder(
25228
- element.borderColor,
25229
- BorderStyle.DASHED,
25230
- element.borderExternalWidth || element.borderWidth
25231
- ),
25232
- right: createBorder(
25233
- element.borderColor,
25234
- BorderStyle.DASHED,
25235
- element.borderExternalWidth || element.borderWidth
25236
- ),
25237
- insideHorizontal: createBorder(
25238
- element.borderColor,
25239
- BorderStyle.DASHED,
25240
- element.borderWidth
25241
- ),
25242
- insideVertical: createBorder(
25243
- element.borderColor,
25244
- BorderStyle.DASHED,
25245
- element.borderWidth
25246
- )
25247
- };
25248
- default:
25249
- return {
25250
- top: outerBorder,
25251
- bottom: outerBorder,
25252
- left: outerBorder,
25253
- right: outerBorder,
25254
- insideHorizontal: innerBorder,
25255
- insideVertical: innerBorder
25256
- };
25257
- }
25258
- }
25259
- function createTableCellBorders(td, inheritedColor, inheritedWidth) {
25260
- if (!td.borderTypes?.length && !td.borderColor) {
25261
- return void 0;
25262
- }
25263
- const color = td.borderColor || inheritedColor;
25264
- const createCellBorder = () => createBorder(color, BorderStyle.SINGLE, inheritedWidth);
25265
- if (td.borderColor && !td.borderTypes?.length) {
25266
- return {
25267
- top: createCellBorder(),
25268
- right: createCellBorder(),
25269
- bottom: createCellBorder(),
25270
- left: createCellBorder()
25271
- };
25272
- }
25273
- const top = td.borderTypes?.includes("top" /* TOP */) ? createCellBorder() : noneBorder();
25274
- const right2 = td.borderTypes?.includes("right" /* RIGHT */) ? createCellBorder() : noneBorder();
25275
- const bottom = td.borderTypes?.includes("bottom" /* BOTTOM */) ? createCellBorder() : noneBorder();
25276
- const left2 = td.borderTypes?.includes("left" /* LEFT */) ? createCellBorder() : noneBorder();
25277
- return {
25278
- top,
25279
- right: right2,
25280
- bottom,
25281
- left: left2
25282
- };
25283
- }
25284
- function createBorder(color = "#000000", style = BorderStyle.SINGLE, width = 1) {
25285
- return {
25286
- style,
25287
- color: normalizeHexColor(color, "000000") || "000000",
25288
- size: pxBorderToDocxSize(width)
25289
- };
25290
- }
25291
- function noneBorder() {
25292
- return {
25293
- style: BorderStyle.NONE,
25294
- size: 0,
25295
- color: "FFFFFF"
25296
- };
25297
- }
25298
- function mapPaddingToTableMargins(padding) {
25299
- if (!padding) return void 0;
25300
- return {
25301
- top: pxToTwips(padding[0]),
25302
- right: pxToTwips(padding[1]),
25303
- bottom: pxToTwips(padding[2]),
25304
- left: pxToTwips(padding[3]),
25305
- marginUnitType: WidthType.DXA
25306
- };
25307
- }
25308
- function mapCellVerticalAlign(verticalAlign) {
25309
- switch (verticalAlign) {
25310
- case VerticalAlign.CENTER:
25311
- return DocxVerticalAlign.CENTER;
25312
- case "bottom" /* BOTTOM */:
25313
- return DocxVerticalAlign.BOTTOM;
25314
- default:
25315
- return DocxVerticalAlign.TOP;
25316
- }
25317
- }
25318
- function mapRowFlexToAlignment(rowFlex) {
25319
- switch (rowFlex) {
25320
- case "center" /* CENTER */:
25321
- return AlignmentType.CENTER;
25322
- case "right" /* RIGHT */:
25323
- return AlignmentType.RIGHT;
25324
- case "alignment" /* ALIGNMENT */:
25325
- case "justify" /* JUSTIFY */:
25326
- return AlignmentType.JUSTIFIED;
25327
- default:
25328
- return AlignmentType.LEFT;
25329
- }
25330
- }
25331
- function mapUnderlineType(style) {
25332
- switch (style) {
25333
- case "double" /* DOUBLE */:
25334
- return UnderlineType.DOUBLE;
25335
- case "dashed" /* DASHED */:
25336
- return UnderlineType.DASH;
25337
- case "dotted" /* DOTTED */:
25338
- return UnderlineType.DOTTED;
25339
- case "wavy" /* WAVY */:
25340
- return UnderlineType.WAVE;
25341
- default:
25342
- return UnderlineType.SINGLE;
25343
- }
25344
- }
25345
- function getInlineElementText(element) {
25346
- switch (element.type) {
25347
- case "control" /* CONTROL */:
25348
- return getControlText(element.control);
25349
- case "date" /* DATE */:
25350
- return element.valueList?.length ? getTextFromElementList(element.valueList) : element.value;
25351
- case "checkbox" /* CHECKBOX */:
25352
- return element.checkbox?.value ? "\u2611" : "\u2610";
25353
- case "radio" /* RADIO */:
25354
- return element.radio?.value ? "\u25C9" : "\u25CB";
25355
- case "label" /* LABEL */:
25356
- case "latex" /* LATEX */:
25357
- case "subscript" /* SUBSCRIPT */:
25358
- case "superscript" /* SUPERSCRIPT */:
25359
- return element.value;
25360
- default:
25361
- return element.value;
25362
- }
25363
- }
25364
- function getControlText(control) {
25365
- if (!control) return "";
25366
- if (control.type === "text" /* TEXT */ || control.type === "date" /* DATE */ || control.type === "number" /* NUMBER */) {
25367
- const value = control.value?.length ? getTextFromElementList(control.value) : "";
25368
- const content = value || control.placeholder || "";
25369
- return `${control.preText || ""}${content}${control.postText || ""}`;
25370
- }
25371
- if (control.type === "select" /* SELECT */) {
25372
- const labels = getSelectedControlLabels(control.code, control.valueSets);
25373
- const content = labels.length ? labels.join(control.multiSelectDelimiter || ", ") : control.placeholder || "";
25374
- return `${control.preText || ""}${content}${control.postText || ""}`;
25375
- }
25376
- if (control.type === "checkbox" /* CHECKBOX */ || control.type === "radio" /* RADIO */) {
25377
- const isRadio = control.type === "radio" /* RADIO */;
25378
- return (control.valueSets || []).map((valueSet) => {
25379
- const checked = control.code?.split(",").includes(valueSet.code) || false;
25380
- return `${checked ? isRadio ? "\u25C9" : "\u2611" : isRadio ? "\u25CB" : "\u2610"} ${valueSet.value}`;
25381
- }).join(" ");
25382
- }
25383
- return "";
25384
- }
25385
- function getSelectedControlLabels(code, valueSets) {
25386
- if (!code || !valueSets?.length) return [];
25387
- return code.split(",").map(
25388
- (selectCode) => valueSets.find((valueSet) => valueSet.code === selectCode)?.value
25389
- ).filter((value) => !!value);
25390
- }
25391
- function getBlockFallbackText(element) {
25392
- if (element.block?.iframeBlock?.src) {
25393
- return element.block.iframeBlock.src;
25394
- }
25395
- if (element.block?.videoBlock?.src) {
25396
- return element.block.videoBlock.src;
25397
- }
25398
- return "";
25399
- }
25400
- function normalizeText(text = "") {
25401
- return text.replace(new RegExp(ZERO, "g"), "").replace(/\r\n/g, "\n");
24889
+ var EXACT_BASELINE_RATIO = 0.8;
24890
+ function rowLine(ctx, row, baseline = row.ascent / ctx.scale) {
24891
+ const { scale } = ctx;
24892
+ const height = row.height / scale;
24893
+ const ascent = Math.min(baseline, height);
24894
+ const line = Math.min(
24895
+ ascent / EXACT_BASELINE_RATIO,
24896
+ (height - ascent) / (1 - EXACT_BASELINE_RATIO)
24897
+ );
24898
+ const lineTw = Math.max(TINY_TWIP, pxTw(line));
24899
+ const beforeTw = Math.max(
24900
+ 0,
24901
+ pxTw(ascent) - Math.round(lineTw * EXACT_BASELINE_RATIO)
24902
+ );
24903
+ const afterTw = Math.max(0, pxTw(height) - lineTw - beforeTw);
24904
+ return { lineTw, beforeTw, afterTw };
25402
24905
  }
25403
- function createSerializeContext() {
24906
+ function rowLead(ctx, row, options) {
24907
+ const separator = row.elementList.find(
24908
+ (el) => el.type === "separator" /* SEPARATOR */
24909
+ );
24910
+ const baseline = separator && options.rowY !== void 0 ? separatorBaseline(
24911
+ ctx,
24912
+ row,
24913
+ options.rowY,
24914
+ separator.lineWidth || ctx.draw.getOptions().separator.lineWidth
24915
+ ) : void 0;
24916
+ return rowLine(ctx, row, baseline).beforeTw + tw(ctx, (row.offsetY || 0) + (row.spaceAbove || 0)) + pxTw(options.padTop || 0);
24917
+ }
24918
+ function rowSpacing(ctx, row, options) {
24919
+ const { lineTw, afterTw } = rowLine(ctx, row);
25404
24920
  return {
25405
- nextListInstance: 1
24921
+ before: options.skipLead ? 0 : rowLead(ctx, row, options),
24922
+ after: afterTw + tw(ctx, row.spaceBelow || 0) + pxTw(options.padBottom || 0) + (options.extraAfter || 0),
24923
+ line: lineTw,
24924
+ lineRule: LineRuleType.EXACT
25406
24925
  };
25407
24926
  }
25408
- function getListItemNumberingElement(listItemElements, fallback) {
25409
- return listItemElements.find(
25410
- (listItem) => listItem.listId || listItem.listLevel !== void 0 || !!listItem.listPreset || !!listItem.listStyle || !!listItem.listType
25411
- ) || fallback;
24927
+ function createSeparatorParagraph(ctx, row, element, x, rowY2, zone, options) {
24928
+ const { scale } = ctx;
24929
+ const opts = ctx.draw.getOptions();
24930
+ const lineWidth = element.lineWidth || opts.separator.lineWidth;
24931
+ const sideGap = 4;
24932
+ const left2 = (x - zone.startX) / scale + sideGap;
24933
+ const width = Math.max(1, (element.width || 0) - sideGap * 2);
24934
+ const color = element.color || opts.separator.strokeStyle;
24935
+ const line = rowLine(ctx, row, separatorBaseline(ctx, row, rowY2, lineWidth));
24936
+ return new Paragraph({
24937
+ pageBreakBefore: options.pageBreakBefore,
24938
+ widowControl: false,
24939
+ indent: { left: pxTw(left2), right: RIGHT_SLACK_TWIP },
24940
+ children: [
24941
+ new ImageRun({
24942
+ type: "png",
24943
+ data: createLineImage(width, lineWidth, color, element.dashArray),
24944
+ transformation: { width, height: lineWidth }
24945
+ })
24946
+ ],
24947
+ spacing: {
24948
+ before: options.skipLead ? 0 : rowLead(ctx, row, options),
24949
+ after: line.afterTw + tw(ctx, row.spaceBelow || 0) + pxTw(options.padBottom || 0) + (options.extraAfter || 0),
24950
+ line: line.lineTw,
24951
+ lineRule: LineRuleType.EXACT
24952
+ }
24953
+ });
25412
24954
  }
25413
- function createListInstance(context) {
25414
- return context.nextListInstance++;
24955
+ function separatorBaseline(ctx, row, rowY2, lineWidth) {
24956
+ return (Math.round(rowY2 + row.ascent) - rowY2) / ctx.scale + lineWidth;
25415
24957
  }
25416
- function createTableSerializeContext(element) {
25417
- return {
25418
- cellLayoutMap: computeTableCellLayout(
25419
- element.trList || [],
25420
- element.colgroup || []
25421
- ),
25422
- borderColor: element.borderColor,
25423
- borderWidth: element.borderWidth,
25424
- borderExternalWidth: element.borderExternalWidth
25425
- };
24958
+ function createLineImage(width, height, color, dashArray) {
24959
+ const ratio = 4;
24960
+ const canvas = document.createElement("canvas");
24961
+ canvas.width = Math.max(1, Math.round(width * ratio));
24962
+ canvas.height = Math.max(1, Math.round(height * ratio));
24963
+ const ctx = canvas.getContext("2d");
24964
+ ctx.strokeStyle = color;
24965
+ ctx.lineWidth = canvas.height;
24966
+ if (dashArray?.length) ctx.setLineDash(dashArray.map((v) => v * ratio));
24967
+ ctx.beginPath();
24968
+ ctx.moveTo(0, canvas.height / 2);
24969
+ ctx.lineTo(canvas.width, canvas.height / 2);
24970
+ ctx.stroke();
24971
+ const binary = atob(canvas.toDataURL("image/png").split(",")[1]);
24972
+ const bytes = new Uint8Array(binary.length);
24973
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
24974
+ return bytes;
24975
+ }
24976
+ function createSpacerParagraph(pageBreakBefore, height = 0) {
24977
+ return new Paragraph({
24978
+ pageBreakBefore,
24979
+ widowControl: false,
24980
+ children: [new TextRun({ text: "", size: 2 })],
24981
+ spacing: {
24982
+ before: 0,
24983
+ after: 0,
24984
+ line: Math.max(TINY_TWIP, pxTw(height)),
24985
+ lineRule: LineRuleType.EXACT
24986
+ }
24987
+ });
25426
24988
  }
25427
- function computeTableCellLayout(trList, colgroup) {
25428
- const cellLayoutMap = /* @__PURE__ */ new WeakMap();
25429
- if (!trList.length || !colgroup.length) {
25430
- return cellLayoutMap;
25431
- }
25432
- const occupiedUntilRow = Array(colgroup.length).fill(0);
25433
- for (let rowIndex = 0; rowIndex < trList.length; rowIndex++) {
25434
- const tr = trList[rowIndex];
25435
- let colIndex = 0;
25436
- for (let tdIndex = 0; tdIndex < tr.tdList.length; tdIndex++) {
25437
- while (colIndex < colgroup.length && occupiedUntilRow[colIndex] > rowIndex) {
25438
- colIndex += 1;
25439
- }
25440
- const td = tr.tdList[tdIndex];
25441
- let width = 0;
25442
- for (let currentCol = colIndex; currentCol < colIndex + td.colspan && currentCol < colgroup.length; currentCol++) {
25443
- width += colgroup[currentCol].width;
25444
- occupiedUntilRow[currentCol] = Math.max(
25445
- occupiedUntilRow[currentCol],
25446
- rowIndex + td.rowspan
25447
- );
25448
- }
25449
- cellLayoutMap.set(td, { width });
25450
- colIndex += td.colspan;
24989
+ async function serializeTable(ctx, element, position, zone) {
24990
+ const { draw, scale } = ctx;
24991
+ const opts = draw.getOptions();
24992
+ const tableX = position.coordinate.leftTop[0];
24993
+ const trList = element.trList || [];
24994
+ const colgroup = element.colgroup || [];
24995
+ const rows = [];
24996
+ for (let t = 0; t < trList.length; t++) {
24997
+ const tr = trList[t];
24998
+ const cells = [];
24999
+ let rowTopBorder = 0;
25000
+ for (let d = 0; d < tr.tdList.length; d++) {
25001
+ const td = tr.tdList[d];
25002
+ const padding = td.padding || opts.table.tdPadding;
25003
+ const borders = createCellBorders(ctx, element, td);
25004
+ const topBorder = t === 0 ? borderPx(borders.top) : 0;
25005
+ rowTopBorder = Math.max(rowTopBorder, topBorder);
25006
+ const cellChildren = await serializeRows(
25007
+ ctx,
25008
+ td.rowList || [],
25009
+ {
25010
+ startX: (td.x + padding[3]) * scale + tableX,
25011
+ width: (td.width - padding[1] - padding[3]) * scale,
25012
+ positionList: td.positionList || []
25013
+ },
25014
+ { padTop: Math.max(0, padding[0] - topBorder), padBottom: padding[2] }
25015
+ );
25016
+ cells.push(
25017
+ new TableCell({
25018
+ children: cellChildren.length ? cellChildren : [createSpacerParagraph(false)],
25019
+ columnSpan: td.colspan > 1 ? td.colspan : void 0,
25020
+ rowSpan: td.rowspan > 1 ? td.rowspan : void 0,
25021
+ width: { size: pxTw(td.width), type: WidthType.DXA },
25022
+ verticalAlign: mapVerticalAlign(td.verticalAlign),
25023
+ margins: {
25024
+ top: 0,
25025
+ right: pxTw(padding[1]),
25026
+ bottom: 0,
25027
+ left: pxTw(Math.max(0, padding[3] - borderPx(borders.left) / 2)),
25028
+ marginUnitType: WidthType.DXA
25029
+ },
25030
+ shading: td.backgroundColor ? {
25031
+ fill: normalizeHexColor(td.backgroundColor, "FFFFFF"),
25032
+ type: ShadingType.CLEAR,
25033
+ color: "auto"
25034
+ } : void 0,
25035
+ borders
25036
+ })
25037
+ );
25451
25038
  }
25039
+ rows.push(
25040
+ new TableRow({
25041
+ children: cells,
25042
+ cantSplit: true,
25043
+ height: {
25044
+ value: pxTw(tr.height - rowTopBorder),
25045
+ rule: HeightRule.EXACT
25046
+ }
25047
+ })
25048
+ );
25452
25049
  }
25453
- return cellLayoutMap;
25050
+ return new Table({
25051
+ rows,
25052
+ layout: TableLayoutType.FIXED,
25053
+ width: { size: pxTw(element.width), type: WidthType.DXA },
25054
+ columnWidths: colgroup.map((col) => pxTw(col.width)),
25055
+ indent: { size: tw(ctx, tableX - zone.startX), type: WidthType.DXA },
25056
+ borders: noTableBorders()
25057
+ });
25454
25058
  }
25455
- function getTableWidthFromColgroup(colgroup) {
25456
- if (!colgroup?.length) {
25457
- return void 0;
25458
- }
25459
- return colgroup.reduce((sum, col) => sum + col.width, 0);
25059
+ function createCellBorders(ctx, table, td) {
25060
+ const opts = ctx.draw.getOptions();
25061
+ const color = normalizeHexColor(
25062
+ td.borderColor || table.borderColor || opts.table.defaultBorderColor,
25063
+ "000000"
25064
+ );
25065
+ const width = table.borderWidth || 1;
25066
+ const externalWidth = table.borderExternalWidth || width;
25067
+ const isDash = table.borderType === "dash" /* DASH */;
25068
+ const line = (w) => ({
25069
+ style: isDash ? BorderStyle.DASHED : BorderStyle.SINGLE,
25070
+ size: Math.max(2, Math.round(w * 6)),
25071
+ color
25072
+ });
25073
+ const none = { style: BorderStyle.NONE, size: 0, color: "auto" };
25074
+ const isTop = td.rowIndex === 0;
25075
+ const isLeft = td.colIndex === 0;
25076
+ const isBottom = td.rowIndex + td.rowspan === table.trList.length;
25077
+ const isRight = td.colIndex + td.colspan === table.colgroup.length;
25078
+ const edge = (outer) => outer ? line(externalWidth) : line(width);
25079
+ let top = none;
25080
+ let right2 = none;
25081
+ let bottom = none;
25082
+ let left2 = none;
25083
+ switch (table.borderType) {
25084
+ case "empty" /* EMPTY */:
25085
+ break;
25086
+ case "external" /* EXTERNAL */:
25087
+ if (isTop) top = edge(true);
25088
+ if (isBottom) bottom = edge(true);
25089
+ if (isLeft) left2 = edge(true);
25090
+ if (isRight) right2 = edge(true);
25091
+ break;
25092
+ case "internal" /* INTERNAL */:
25093
+ if (!isTop) top = edge(false);
25094
+ if (!isBottom) bottom = edge(false);
25095
+ if (!isLeft) left2 = edge(false);
25096
+ if (!isRight) right2 = edge(false);
25097
+ break;
25098
+ default:
25099
+ top = edge(isTop);
25100
+ bottom = edge(isBottom);
25101
+ left2 = edge(isLeft);
25102
+ right2 = edge(isRight);
25103
+ }
25104
+ if (td.borderTypes?.includes("top" /* TOP */)) top = line(width);
25105
+ if (td.borderTypes?.includes("right" /* RIGHT */)) right2 = line(width);
25106
+ if (td.borderTypes?.includes("bottom" /* BOTTOM */)) bottom = line(width);
25107
+ if (td.borderTypes?.includes("left" /* LEFT */)) left2 = line(width);
25108
+ return { top, right: right2, bottom, left: left2 };
25109
+ }
25110
+ function borderPx(border) {
25111
+ return border.style === BorderStyle.NONE ? 0 : border.size / 8 * (4 / 3);
25112
+ }
25113
+ function noTableBorders() {
25114
+ const none = { style: BorderStyle.NONE, size: 0, color: "auto" };
25115
+ return {
25116
+ top: none,
25117
+ bottom: none,
25118
+ left: none,
25119
+ right: none,
25120
+ insideHorizontal: none,
25121
+ insideVertical: none
25122
+ };
25460
25123
  }
25461
- function normalizeHexColor(color, fallback) {
25462
- const normalized = normalizeHexLiteral(color) || normalizeRgbColor(color) || normalizeBrowserColor(color);
25463
- if (normalized) {
25464
- return normalized;
25124
+ function mapVerticalAlign(verticalAlign) {
25125
+ switch (verticalAlign) {
25126
+ case "middle" /* MIDDLE */:
25127
+ return DocxVerticalAlign.CENTER;
25128
+ case "bottom" /* BOTTOM */:
25129
+ return DocxVerticalAlign.BOTTOM;
25130
+ default:
25131
+ return DocxVerticalAlign.TOP;
25465
25132
  }
25466
- return fallback ? normalizeHexLiteral(fallback) || void 0 : void 0;
25467
25133
  }
25468
- function normalizeHexLiteral(color) {
25469
- const value = color.trim().replace(/^#/, "");
25470
- if (/^[\da-f]{3}$/i.test(value)) {
25471
- return value.split("").map((part) => `${part}${part}`).join("").toUpperCase();
25472
- }
25473
- if (/^[\da-f]{4}$/i.test(value)) {
25474
- return value.slice(0, 3).split("").map((part) => `${part}${part}`).join("").toUpperCase();
25475
- }
25476
- if (/^[\da-f]{6}$/i.test(value)) {
25477
- return value.toUpperCase();
25134
+ async function serializeFooter(ctx, pageWidth, pageHeight, margins) {
25135
+ const { draw, scale } = ctx;
25136
+ const footer = draw.getFooter();
25137
+ const opts = draw.getOptions();
25138
+ const barHeight = footer.getHeight() / scale;
25139
+ const contentHeight = footer.getRowHeight() / scale;
25140
+ const paddingTop = Math.floor(Math.max(0, (barHeight - contentHeight) / 2) * scale) / scale;
25141
+ const zone = {
25142
+ startX: draw.getMargins()[3],
25143
+ width: draw.getInnerWidth(),
25144
+ positionList: footer.getPositionList()
25145
+ };
25146
+ const rowList = footer.getRowList();
25147
+ const textWidth = pageWidth - margins[1] - margins[3];
25148
+ const pageNumber = createPageNumberRuns(ctx, pageHeight, textWidth);
25149
+ let pageNumberRow = -1;
25150
+ if (pageNumber) {
25151
+ pageNumberRow = rowList.length - 1;
25152
+ for (let r = 0; r < rowList.length; r++) {
25153
+ const top = zone.positionList[rowList[r].startIndex].coordinate.leftTop[1] / scale;
25154
+ if (pageNumber.baseline <= top + rowList[r].height / scale) {
25155
+ pageNumberRow = r;
25156
+ break;
25157
+ }
25158
+ }
25478
25159
  }
25479
- if (/^[\da-f]{8}$/i.test(value)) {
25480
- return value.slice(0, 6).toUpperCase();
25160
+ const children = [];
25161
+ for (let r = 0; r < rowList.length; r++) {
25162
+ const row = rowList[r];
25163
+ const rowOptions = { padTop: r === 0 ? paddingTop : 0 };
25164
+ if (r !== pageNumberRow) {
25165
+ children.push(...await serializeRows(ctx, [row], zone, rowOptions));
25166
+ continue;
25167
+ }
25168
+ const top = zone.positionList[row.startIndex].coordinate.leftTop[1] / scale;
25169
+ const shift = pageNumber.baseline - (top + row.ascent / scale);
25170
+ children.push(
25171
+ await serializeRow(ctx, row, zone, rowOptions, {
25172
+ tabStop: pageNumber.tabStop,
25173
+ tabType: pageNumber.tabType,
25174
+ children: pageNumber.runs(shift),
25175
+ style: PAGE_NUMBER_STYLE
25176
+ })
25177
+ );
25481
25178
  }
25482
- return void 0;
25179
+ const fill = opts.footer.backgroundColor ? normalizeHexColor(opts.footer.backgroundColor, "FFFFFF") : void 0;
25180
+ const none = { style: BorderStyle.NONE, size: 0, color: "auto" };
25181
+ const band = new Table({
25182
+ layout: TableLayoutType.FIXED,
25183
+ width: { size: pxTw(pageWidth), type: WidthType.DXA },
25184
+ columnWidths: [pxTw(pageWidth)],
25185
+ indent: { size: -pxTw(margins[3]), type: WidthType.DXA },
25186
+ borders: noTableBorders(),
25187
+ rows: [
25188
+ new TableRow({
25189
+ cantSplit: true,
25190
+ height: { value: pxTw(barHeight), rule: HeightRule.EXACT },
25191
+ children: [
25192
+ new TableCell({
25193
+ width: { size: pxTw(pageWidth), type: WidthType.DXA },
25194
+ margins: {
25195
+ top: 0,
25196
+ bottom: 0,
25197
+ left: pxTw(margins[3]),
25198
+ right: pxTw(margins[1]),
25199
+ marginUnitType: WidthType.DXA
25200
+ },
25201
+ shading: fill ? { fill, type: ShadingType.CLEAR, color: "auto" } : void 0,
25202
+ borders: { top: none, right: none, bottom: none, left: none },
25203
+ children: children.length ? children : [createSpacerParagraph(false)]
25204
+ })
25205
+ ]
25206
+ })
25207
+ ]
25208
+ });
25209
+ return [band];
25483
25210
  }
25484
- function normalizeRgbColor(color) {
25485
- const match = color.trim().match(/^rgba?\((.+)\)$/i);
25486
- if (!match) {
25487
- return void 0;
25211
+ var PAGE_NUMBER_STYLE = "WindocPageNumber";
25212
+ var FieldCharAttributes = class extends XmlAttributeComponent {
25213
+ constructor() {
25214
+ super(...arguments);
25215
+ this.xmlKeys = { type: "w:fldCharType" };
25488
25216
  }
25489
- const parts = match[1].replace(/\s*\/\s*/g, ",").split(/\s*,\s*|\s+/).filter(Boolean);
25490
- if (parts.length < 3) {
25491
- return void 0;
25217
+ };
25218
+ var FieldChar = class extends XmlComponent {
25219
+ constructor(type) {
25220
+ super("w:fldChar");
25221
+ this.root.push(new FieldCharAttributes({ type }));
25492
25222
  }
25493
- const red = parseRgbChannel(parts[0]);
25494
- const green = parseRgbChannel(parts[1]);
25495
- const blue = parseRgbChannel(parts[2]);
25496
- if (red === null || green === null || blue === null) {
25497
- return void 0;
25223
+ };
25224
+ var InstrTextAttributes = class extends XmlAttributeComponent {
25225
+ constructor() {
25226
+ super(...arguments);
25227
+ this.xmlKeys = { space: "xml:space" };
25498
25228
  }
25499
- const alpha = parts[3] !== void 0 ? parseAlphaChannel(parts[3]) : 1;
25500
- if (alpha === null || alpha <= 0) {
25501
- return void 0;
25229
+ };
25230
+ var InstrText = class extends XmlComponent {
25231
+ constructor(instruction) {
25232
+ super("w:instrText");
25233
+ this.root.push(new InstrTextAttributes({ space: "preserve" }));
25234
+ this.root.push(` ${instruction} `);
25502
25235
  }
25503
- const flattened = alpha >= 1 ? [red, green, blue] : [
25504
- flattenChannel(red, alpha),
25505
- flattenChannel(green, alpha),
25506
- flattenChannel(blue, alpha)
25236
+ };
25237
+ function createFieldRuns(instruction, cached, style) {
25238
+ return [
25239
+ new TextRun({ ...style, children: [new FieldChar("begin")] }),
25240
+ new TextRun({ ...style, children: [new InstrText(instruction)] }),
25241
+ new TextRun({ ...style, children: [new FieldChar("separate")] }),
25242
+ new TextRun({ ...style, text: cached }),
25243
+ new TextRun({ ...style, children: [new FieldChar("end")] })
25507
25244
  ];
25508
- return flattened.map(toHexChannel).join("");
25509
25245
  }
25510
- function normalizeBrowserColor(color) {
25511
- if (typeof document === "undefined") {
25512
- return void 0;
25513
- }
25514
- const canvas = document.createElement("canvas");
25515
- const context = canvas.getContext("2d");
25516
- if (!context) {
25517
- return void 0;
25518
- }
25519
- context.fillStyle = "#000000";
25520
- context.fillStyle = color;
25521
- const normalized = context.fillStyle;
25522
- if (typeof normalized !== "string") {
25523
- return void 0;
25524
- }
25525
- return normalizeHexLiteral(normalized) || normalizeRgbColor(normalized);
25246
+ function pageNumberRunStyle(pageNumber) {
25247
+ return {
25248
+ font: mapFont(pageNumber?.font || "sans-serif"),
25249
+ // PageNumber draws `${size}px`; half-points = px * 0.75 * 2
25250
+ size: Math.round((pageNumber?.size || 12) * 1.5),
25251
+ color: normalizeHexColor(pageNumber?.color || "#000000", "000000")
25252
+ };
25526
25253
  }
25527
- function parseRgbChannel(value) {
25528
- if (value.endsWith("%")) {
25529
- const percent = Number(value.slice(0, -1));
25530
- if (!Number.isFinite(percent)) {
25531
- return null;
25532
- }
25533
- return clampColorChannel(Math.round(percent / 100 * 255));
25534
- }
25535
- const channel = Number(value);
25536
- if (!Number.isFinite(channel)) {
25537
- return null;
25254
+ function createPageNumberRuns(ctx, pageHeight, textWidth) {
25255
+ const { pageNumber } = ctx.draw.getOptions();
25256
+ if (pageNumber.disabled || pageNumber.fromPageNo > 0) return null;
25257
+ const pageCount = ctx.draw.getPageCount();
25258
+ const tokens = (pageNumber.format || FORMAT_PLACEHOLDER.PAGE_NO).split(
25259
+ /(\{pageNo\}|\{pageCount\})/
25260
+ );
25261
+ const tabType = pageNumber.rowFlex === "center" /* CENTER */ ? TabStopType.CENTER : pageNumber.rowFlex === "right" /* RIGHT */ ? TabStopType.RIGHT : TabStopType.LEFT;
25262
+ const tabStop = tabType === TabStopType.CENTER ? pxTw(textWidth / 2) : tabType === TabStopType.RIGHT ? pxTw(textWidth) : 0;
25263
+ const position = (shift) => {
25264
+ const halfPoints = Math.round(-shift * 0.75 * 2);
25265
+ return halfPoints ? `${halfPoints}` : void 0;
25266
+ };
25267
+ return {
25268
+ baseline: pageHeight - pageNumber.bottom,
25269
+ tabType,
25270
+ tabStop,
25271
+ // shift > 0 means the number sits lower than the row baseline
25272
+ runs: (shift) => tokens.filter(Boolean).map((token) => {
25273
+ const style = {
25274
+ ...pageNumberRunStyle(pageNumber),
25275
+ position: position(shift)
25276
+ };
25277
+ const field = token === FORMAT_PLACEHOLDER.PAGE_NO ? { instruction: "PAGE", cached: "1" } : token === FORMAT_PLACEHOLDER.PAGE_COUNT ? { instruction: "NUMPAGES", cached: `${pageCount}` } : null;
25278
+ if (!field) return [new TextRun({ text: token, ...style })];
25279
+ return createFieldRuns(field.instruction, field.cached, style);
25280
+ }).flat()
25281
+ };
25282
+ }
25283
+ function createTextRun(ctx, text, element, shading, characterSpacing) {
25284
+ const opts = ctx.draw.getOptions();
25285
+ const isLink = element.type === "hyperlink" /* HYPERLINK */;
25286
+ const color = normalizeHexColor(
25287
+ element.color || (isLink ? opts.defaultHyperlinkColor : opts.defaultColor),
25288
+ "000000"
25289
+ );
25290
+ const highlight = element.highlight ? normalizeHexColor(element.highlight) : void 0;
25291
+ const textRun = new TextRun({
25292
+ text,
25293
+ font: mapFont(element.font || opts.defaultFont),
25294
+ size: Math.round(getSize(ctx, element) * 2),
25295
+ bold: !!element.bold,
25296
+ italics: !!element.italic,
25297
+ strike: !!element.strikeout,
25298
+ superScript: element.type === "superscript" /* SUPERSCRIPT */,
25299
+ subScript: element.type === "subscript" /* SUBSCRIPT */,
25300
+ underline: element.underline || isLink ? { type: mapUnderlineType(element.textDecoration?.style) } : void 0,
25301
+ color,
25302
+ shading: shading || (highlight ? { fill: highlight, type: ShadingType.CLEAR, color: "auto" } : void 0),
25303
+ characterSpacing
25304
+ });
25305
+ if (isLink && element.url) {
25306
+ return new ExternalHyperlink({ link: element.url, children: [textRun] });
25538
25307
  }
25539
- return clampColorChannel(Math.round(channel));
25308
+ return textRun;
25540
25309
  }
25541
- function parseAlphaChannel(value) {
25542
- if (value.endsWith("%")) {
25543
- const percent = Number(value.slice(0, -1));
25544
- if (!Number.isFinite(percent)) {
25545
- return null;
25310
+ function labelShading(ctx, element) {
25311
+ const { defaultBackgroundColor } = ctx.draw.getOptions().label;
25312
+ return {
25313
+ fill: normalizeHexColor(
25314
+ element.label?.backgroundColor || defaultBackgroundColor,
25315
+ "FFFFFF"
25316
+ ),
25317
+ type: ShadingType.CLEAR,
25318
+ color: "auto"
25319
+ };
25320
+ }
25321
+ async function createImageRun(element) {
25322
+ try {
25323
+ const image = await loadImagePayload(element.value);
25324
+ const transformation = {
25325
+ width: Math.max(1, element.width || 1),
25326
+ height: Math.max(1, element.height || 1)
25327
+ };
25328
+ if (image.type === "svg" && image.fallbackPng) {
25329
+ return new ImageRun({
25330
+ type: "svg",
25331
+ data: image.data,
25332
+ fallback: { type: "png", data: image.fallbackPng },
25333
+ transformation
25334
+ });
25546
25335
  }
25547
- return Math.min(Math.max(percent / 100, 0), 1);
25548
- }
25549
- const alpha = Number(value);
25550
- if (!Number.isFinite(alpha)) {
25336
+ return new ImageRun({
25337
+ type: image.type,
25338
+ data: image.data,
25339
+ transformation
25340
+ });
25341
+ } catch {
25551
25342
  return null;
25552
25343
  }
25553
- return Math.min(Math.max(alpha, 0), 1);
25554
- }
25555
- function clampColorChannel(value) {
25556
- return Math.min(Math.max(value, 0), 255);
25557
25344
  }
25558
- function flattenChannel(value, alpha) {
25559
- return clampColorChannel(Math.round(255 * (1 - alpha) + value * alpha));
25345
+ function getElementText(element) {
25346
+ switch (element.type) {
25347
+ case "checkbox" /* CHECKBOX */:
25348
+ return element.checkbox?.value ? "\u2611" : "\u2610";
25349
+ case "radio" /* RADIO */:
25350
+ return element.radio?.value ? "\u25C9" : "\u25CB";
25351
+ default:
25352
+ return (element.value || "").replace(new RegExp(ZERO, "g"), "");
25353
+ }
25560
25354
  }
25561
- function toHexChannel(value) {
25562
- return value.toString(16).padStart(2, "0").toUpperCase();
25355
+ function getSize(ctx, element) {
25356
+ return element.actualSize || element.size || ctx.draw.getOptions().defaultSize;
25563
25357
  }
25564
- function pxBorderToDocxSize(width) {
25565
- const safeWidth = Number.isFinite(width) && width > 0 ? width : 1;
25566
- return Math.max(2, Math.round(safeWidth * 6));
25358
+ function measure(ctx, text, element) {
25359
+ ctx.measureCtx.font = ctx.draw.getElementFont(element, 1);
25360
+ return ctx.measureCtx.measureText(text).width;
25567
25361
  }
25568
- function getRegularImageType(mime) {
25569
- if (mime.includes("png")) return "png";
25570
- if (mime.includes("jpeg") || mime.includes("jpg")) return "jpg";
25571
- if (mime.includes("gif")) return "gif";
25572
- if (mime.includes("bmp")) return "bmp";
25573
- return null;
25362
+ function isSameRunStyle(a, b) {
25363
+ 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;
25574
25364
  }
25575
- function normalizeDocxFileName(fileName) {
25576
- const trimmed = fileName?.trim();
25577
- if (!trimmed) {
25578
- return DEFAULT_DOCX_FILE_NAME;
25365
+ function mapFont(font) {
25366
+ const name = font.trim().replace(/^['"]|['"]$/g, "");
25367
+ switch (name.toLowerCase()) {
25368
+ case "sans-serif":
25369
+ return "Arial";
25370
+ case "serif":
25371
+ return "Times New Roman";
25372
+ case "monospace":
25373
+ return "Courier New";
25374
+ default:
25375
+ return name;
25579
25376
  }
25580
- return trimmed.toLowerCase().endsWith(".docx") ? trimmed : `${trimmed}.docx`;
25581
- }
25582
- function pxToTwips(px) {
25583
- return Math.round(px * 15);
25584
25377
  }
25585
25378
 
25586
25379
  // src/utils/pdf.ts
@@ -25592,7 +25385,7 @@ import {
25592
25385
  var DEFAULT_PDF_FILE_NAME = "document.pdf";
25593
25386
  var DEFAULT_IMAGE_WIDTH2 = 320;
25594
25387
  var DEFAULT_IMAGE_HEIGHT2 = 180;
25595
- var DEFAULT_LINE_HEIGHT2 = 1.15;
25388
+ var DEFAULT_LINE_HEIGHT = 1.15;
25596
25389
  var PAGE_REGION_GAP = 12;
25597
25390
  var SEPARATOR_HEIGHT = 12;
25598
25391
  var LIST_GAP = 8;
@@ -25787,7 +25580,7 @@ async function parseElementList(elementList, context, options) {
25787
25580
  }
25788
25581
  if (element.type === "block" /* BLOCK */) {
25789
25582
  await flushInlineBuffer();
25790
- const blockText = getBlockFallbackText2(element);
25583
+ const blockText = getBlockFallbackText(element);
25791
25584
  if (blockText) {
25792
25585
  blocks.push(
25793
25586
  ...await parseInlineElements(
@@ -25839,7 +25632,7 @@ async function parseInlineElements(elementList, context, options, overrides = {}
25839
25632
  current = null;
25840
25633
  };
25841
25634
  const appendText = (element, text, factory, preserveTrailingBreak = false) => {
25842
- const normalized = normalizeText2(text);
25635
+ const normalized = normalizeText(text);
25843
25636
  const parts = normalized.split("\n");
25844
25637
  let lastSeparatorFlushedContent = false;
25845
25638
  for (let i = 0; i < parts.length; i++) {
@@ -25875,7 +25668,7 @@ async function parseInlineElements(elementList, context, options, overrides = {}
25875
25668
  const children = element.valueList || [];
25876
25669
  for (let childIndex = 0; childIndex < children.length; childIndex++) {
25877
25670
  const child = children[childIndex];
25878
- const text = normalizeText2(getInlineElementText2(child));
25671
+ const text = normalizeText(getInlineElementText(child));
25879
25672
  if (!text) continue;
25880
25673
  appendText(
25881
25674
  element,
@@ -25924,7 +25717,7 @@ async function parseInlineElements(elementList, context, options, overrides = {}
25924
25717
  ensureParagraph(element).runs.push(badgeRun);
25925
25718
  continue;
25926
25719
  }
25927
- const textValue = getInlineElementText2(element);
25720
+ const textValue = getInlineElementText(element);
25928
25721
  if (!textValue) {
25929
25722
  continue;
25930
25723
  }
@@ -25952,7 +25745,7 @@ async function parseListBlock(element, context, options) {
25952
25745
  const blocks = [];
25953
25746
  const orderedCounts = Array(9).fill(0);
25954
25747
  for (const listItemElements of listItemMap.values()) {
25955
- const itemElement = getListItemNumberingElement2(listItemElements, element);
25748
+ const itemElement = getListItemNumberingElement(listItemElements, element);
25956
25749
  const marker = getListMarker(itemElement, orderedCounts);
25957
25750
  blocks.push(
25958
25751
  ...await parseInlineElements(listItemElements, context, options, {
@@ -26511,10 +26304,11 @@ function layoutParagraph(block, width, context) {
26511
26304
  }
26512
26305
  if (token.width > availableWidth && token.kind === "text" && token.run.type === "text") {
26513
26306
  const segments = splitTextToken(token, availableWidth, context);
26514
- for (let segmentIndex = 0; segmentIndex < segments.length; segmentIndex++) {
26515
- tokens.splice(i + segmentIndex, 0, segments[segmentIndex]);
26307
+ if (segments.length > 1) {
26308
+ tokens.splice(i, 1, ...segments);
26309
+ i--;
26310
+ continue;
26516
26311
  }
26517
- continue;
26518
26312
  }
26519
26313
  if (line.width + token.width > availableWidth && line.fragments.length) {
26520
26314
  commitLine();
@@ -26873,7 +26667,7 @@ function getEmptyLineHeight(block, context) {
26873
26667
  block.context.rowMargin || context.options.defaultRowMargin
26874
26668
  );
26875
26669
  }
26876
- function getRunHeight(run, rowMargin = DEFAULT_LINE_HEIGHT2) {
26670
+ function getRunHeight(run, rowMargin = DEFAULT_LINE_HEIGHT) {
26877
26671
  return run.size * rowMargin;
26878
26672
  }
26879
26673
  function resolveTextMetrics(run, context) {
@@ -27082,10 +26876,10 @@ function loadHtmlImage2(src) {
27082
26876
  image.src = src;
27083
26877
  });
27084
26878
  }
27085
- function getInlineElementText2(element) {
26879
+ function getInlineElementText(element) {
27086
26880
  switch (element.type) {
27087
26881
  case "control" /* CONTROL */:
27088
- return getControlText2(element.control);
26882
+ return getControlText(element.control);
27089
26883
  case "date" /* DATE */:
27090
26884
  return element.valueList?.length ? getTextFromElementList(element.valueList) : element.value;
27091
26885
  case "checkbox" /* CHECKBOX */:
@@ -27101,7 +26895,7 @@ function getInlineElementText2(element) {
27101
26895
  return element.value;
27102
26896
  }
27103
26897
  }
27104
- function getControlText2(control) {
26898
+ function getControlText(control) {
27105
26899
  if (!control) return "";
27106
26900
  if (control.type === "text" /* TEXT */ || control.type === "date" /* DATE */ || control.type === "number" /* NUMBER */) {
27107
26901
  const value = control.value?.length ? getTextFromElementList(control.value) : "";
@@ -27109,7 +26903,7 @@ function getControlText2(control) {
27109
26903
  return `${control.preText || ""}${content}${control.postText || ""}`;
27110
26904
  }
27111
26905
  if (control.type === "select" /* SELECT */) {
27112
- const labels = getSelectedControlLabels2(control.code, control.valueSets);
26906
+ const labels = getSelectedControlLabels(control.code, control.valueSets);
27113
26907
  const content = labels.length ? labels.join(control.multiSelectDelimiter || ", ") : control.placeholder || "";
27114
26908
  return `${control.preText || ""}${content}${control.postText || ""}`;
27115
26909
  }
@@ -27122,13 +26916,13 @@ function getControlText2(control) {
27122
26916
  }
27123
26917
  return "";
27124
26918
  }
27125
- function getSelectedControlLabels2(code, valueSets) {
26919
+ function getSelectedControlLabels(code, valueSets) {
27126
26920
  if (!code || !valueSets?.length) return [];
27127
26921
  return code.split(",").map(
27128
26922
  (selectCode) => valueSets.find((valueSet) => valueSet.code === selectCode)?.value
27129
26923
  ).filter((value) => !!value);
27130
26924
  }
27131
- function getBlockFallbackText2(element) {
26925
+ function getBlockFallbackText(element) {
27132
26926
  if (element.block?.iframeBlock?.src) {
27133
26927
  return element.block.iframeBlock.src;
27134
26928
  }
@@ -27137,7 +26931,7 @@ function getBlockFallbackText2(element) {
27137
26931
  }
27138
26932
  return "";
27139
26933
  }
27140
- function getListItemNumberingElement2(listItemElements, fallback) {
26934
+ function getListItemNumberingElement(listItemElements, fallback) {
27141
26935
  return listItemElements.find(
27142
26936
  (listItem) => listItem.listId || listItem.listLevel !== void 0 || !!listItem.listPreset || !!listItem.listStyle || !!listItem.listType
27143
26937
  ) || fallback;
@@ -27359,7 +27153,7 @@ function getReservedPageNumberBottom(pageNumber, pageNumberHeight) {
27359
27153
  }
27360
27154
  return pxToPt(pageNumber.bottom + 4) + pageNumberHeight;
27361
27155
  }
27362
- function normalizeText2(text = "") {
27156
+ function normalizeText(text = "") {
27363
27157
  return text.replace(new RegExp(ZERO, "g"), "").replace(/\r\n/g, "\n");
27364
27158
  }
27365
27159
  function normalizePdfFileName(fileName) {
@@ -28699,8 +28493,7 @@ var CommandAdapt = class {
28699
28493
  }
28700
28494
  }
28701
28495
  async exportDocx(payload = {}) {
28702
- const result = this.draw.getValue();
28703
- const { blob, fileName } = await exportEditorDataToDocx(result, payload);
28496
+ const { blob, fileName } = await exportDrawToDocx(this.draw, payload);
28704
28497
  downloadBlob(blob, fileName);
28705
28498
  }
28706
28499
  async exportPdf(payload = {}) {