@yudaocode/univer-docs 1.6.211 → 1.6.212

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/lib/cjs/index.js CHANGED
@@ -46,6 +46,7 @@ __export(src_exports, {
46
46
  DEFAULT_CASCADER_OPTIONS: () => DEFAULT_CASCADER_OPTIONS,
47
47
  DEFAULT_ENDNOTE_SETTINGS: () => DEFAULT_ENDNOTE_SETTINGS,
48
48
  DEFAULT_FOOTNOTE_SETTINGS: () => DEFAULT_FOOTNOTE_SETTINGS,
49
+ DOC_DRAWING_PLUGIN_RESOURCE: () => DOC_DRAWING_PLUGIN_RESOURCE,
49
50
  DOC_HYPERLINK_DEFAULT_COLOR: () => DOC_HYPERLINK_DEFAULT_COLOR,
50
51
  DOC_IO_CAPABILITY_FORMATS: () => DOC_IO_CAPABILITY_FORMATS,
51
52
  DOC_TRACK_DELETE_STYLE: () => DOC_TRACK_DELETE_STYLE,
@@ -378,6 +379,7 @@ __export(src_exports, {
378
379
  listLiveSmartArts: () => listLiveSmartArts,
379
380
  matchSdtHighlightRule: () => matchSdtHighlightRule,
380
381
  mergeDocTableCellsInSnapshot: () => mergeDocTableCellsInSnapshot,
382
+ normalizeDocDrawingsAndPluginResource: () => normalizeDocDrawingsAndPluginResource,
381
383
  normalizeImageDataUriForSdt: () => normalizeImageDataUriForSdt,
382
384
  normalizeMacroName: () => normalizeMacroName,
383
385
  normalizeSdtListItems: () => normalizeSdtListItems,
@@ -397,6 +399,7 @@ __export(src_exports, {
397
399
  recordDocTrackRevisionOnSnapshot: () => recordDocTrackRevisionOnSnapshot,
398
400
  refreshTableOfContentsInSnapshot: () => refreshTableOfContentsInSnapshot,
399
401
  registerDocMacro: () => registerDocMacro,
402
+ reinitializeDocHeaderFooterModels: () => reinitializeDocHeaderFooterModels,
400
403
  removeBookmarkFromSnapshot: () => removeBookmarkFromSnapshot,
401
404
  removeCalloutFromSnapshot: () => removeCalloutFromSnapshot,
402
405
  removeDocCascadeRule: () => removeDocCascadeRuleFromSnapshot,
@@ -475,6 +478,7 @@ __export(src_exports, {
475
478
  splitDocTableCellInSnapshot: () => splitDocTableCellInSnapshot,
476
479
  stripDocEditorChromeForView: () => stripDocEditorChromeForView,
477
480
  stripSdtAffixes: () => stripSdtAffixes,
481
+ syncDocDrawingsToUniverServices: () => syncDocDrawingsToUniverServices,
478
482
  syncSnapshotAuxFields: () => syncSnapshotAuxFields,
479
483
  toControlSpecSnapshot: () => toControlSpecSnapshot,
480
484
  toggleDocListCheckboxInSnapshot: () => toggleDocListCheckboxInSnapshot,
@@ -510,6 +514,7 @@ var import_core13 = require("@univerjs/core");
510
514
 
511
515
  // src/types/doc-sdt.ts
512
516
  var YUDAO_DOCS_TEMPLATE_RESOURCE = "YUDAO_DOCS_TEMPLATE_RESOURCE";
517
+ var DOC_DRAWING_PLUGIN_RESOURCE = "DOC_DRAWING_PLUGIN";
513
518
 
514
519
  // src/utils/doc-medical-and-blocks.ts
515
520
  var import_core = require("@univerjs/core");
@@ -1331,6 +1336,7 @@ function insertInlineDrawingIntoSnapshot(sourceSnapshot, params) {
1331
1336
  order.push(blockId);
1332
1337
  }
1333
1338
  nextSnapshot.drawingsOrder = order;
1339
+ normalizeDocDrawingsAndPluginResource(nextSnapshot);
1334
1340
  return {
1335
1341
  snapshot: nextSnapshot,
1336
1342
  blockId,
@@ -10223,12 +10229,123 @@ function resolveUnderlineCssStyle(ul) {
10223
10229
  const color = ul?.c !== 0 && ul?.cl?.rgb ? ul.cl.rgb : void 0;
10224
10230
  return { style, ...color ? { color } : {} };
10225
10231
  }
10232
+ function dxaToPt(dxa) {
10233
+ return Math.round(dxa / 20 * 100) / 100;
10234
+ }
10235
+ function toPoints(nu) {
10236
+ if (!nu || typeof nu.v !== "number" || !Number.isFinite(nu.v)) return 0;
10237
+ return nu.v;
10238
+ }
10239
+ var OOXML_REL_H_TO_CODE = {
10240
+ page: import_core7.ObjectRelativeFromH.PAGE,
10241
+ column: import_core7.ObjectRelativeFromH.COLUMN,
10242
+ character: import_core7.ObjectRelativeFromH.CHARACTER,
10243
+ margin: import_core7.ObjectRelativeFromH.MARGIN,
10244
+ insideMargin: import_core7.ObjectRelativeFromH.INSIDE_MARGIN,
10245
+ outsideMargin: import_core7.ObjectRelativeFromH.OUTSIDE_MARGIN,
10246
+ leftMargin: import_core7.ObjectRelativeFromH.LEFT_MARGIN,
10247
+ rightMargin: import_core7.ObjectRelativeFromH.RIGHT_MARGIN
10248
+ };
10249
+ var CODE_TO_OOXML_REL_H = {
10250
+ [import_core7.ObjectRelativeFromH.PAGE]: "page",
10251
+ [import_core7.ObjectRelativeFromH.COLUMN]: "column",
10252
+ [import_core7.ObjectRelativeFromH.CHARACTER]: "character",
10253
+ [import_core7.ObjectRelativeFromH.MARGIN]: "margin",
10254
+ [import_core7.ObjectRelativeFromH.INSIDE_MARGIN]: "insideMargin",
10255
+ [import_core7.ObjectRelativeFromH.OUTSIDE_MARGIN]: "outsideMargin",
10256
+ [import_core7.ObjectRelativeFromH.LEFT_MARGIN]: "leftMargin",
10257
+ [import_core7.ObjectRelativeFromH.RIGHT_MARGIN]: "rightMargin"
10258
+ };
10259
+ var OOXML_REL_V_TO_CODE = {
10260
+ page: import_core7.ObjectRelativeFromV.PAGE,
10261
+ paragraph: import_core7.ObjectRelativeFromV.PARAGRAPH,
10262
+ line: import_core7.ObjectRelativeFromV.LINE,
10263
+ margin: import_core7.ObjectRelativeFromV.MARGIN,
10264
+ topMargin: import_core7.ObjectRelativeFromV.TOP_MARGIN,
10265
+ bottomMargin: import_core7.ObjectRelativeFromV.BOTTOM_MARGIN,
10266
+ insideMargin: import_core7.ObjectRelativeFromV.INSIDE_MARGIN,
10267
+ outsideMargin: import_core7.ObjectRelativeFromV.OUTSIDE_MARGIN
10268
+ };
10269
+ var CODE_TO_OOXML_REL_V = {
10270
+ [import_core7.ObjectRelativeFromV.PAGE]: "page",
10271
+ [import_core7.ObjectRelativeFromV.PARAGRAPH]: "paragraph",
10272
+ [import_core7.ObjectRelativeFromV.LINE]: "line",
10273
+ [import_core7.ObjectRelativeFromV.MARGIN]: "margin",
10274
+ [import_core7.ObjectRelativeFromV.TOP_MARGIN]: "topMargin",
10275
+ [import_core7.ObjectRelativeFromV.BOTTOM_MARGIN]: "bottomMargin",
10276
+ [import_core7.ObjectRelativeFromV.INSIDE_MARGIN]: "insideMargin",
10277
+ [import_core7.ObjectRelativeFromV.OUTSIDE_MARGIN]: "outsideMargin"
10278
+ };
10279
+ var OOXML_ALIGN_H_TO_CODE = {
10280
+ center: import_core7.AlignTypeH.CENTER,
10281
+ inside: import_core7.AlignTypeH.INSIDE,
10282
+ left: import_core7.AlignTypeH.LEFT,
10283
+ outside: import_core7.AlignTypeH.OUTSIDE,
10284
+ right: import_core7.AlignTypeH.RIGHT
10285
+ };
10286
+ var CODE_TO_OOXML_ALIGN_H = {
10287
+ [import_core7.AlignTypeH.CENTER]: "center",
10288
+ [import_core7.AlignTypeH.INSIDE]: "inside",
10289
+ [import_core7.AlignTypeH.LEFT]: "left",
10290
+ [import_core7.AlignTypeH.OUTSIDE]: "outside",
10291
+ [import_core7.AlignTypeH.RIGHT]: "right"
10292
+ };
10293
+ var OOXML_ALIGN_V_TO_CODE = {
10294
+ bottom: import_core7.AlignTypeV.BOTTOM,
10295
+ center: import_core7.AlignTypeV.CENTER,
10296
+ inside: import_core7.AlignTypeV.INSIDE,
10297
+ outside: import_core7.AlignTypeV.OUTSIDE,
10298
+ top: import_core7.AlignTypeV.TOP
10299
+ };
10300
+ var CODE_TO_OOXML_ALIGN_V = {
10301
+ [import_core7.AlignTypeV.BOTTOM]: "bottom",
10302
+ [import_core7.AlignTypeV.CENTER]: "center",
10303
+ [import_core7.AlignTypeV.INSIDE]: "inside",
10304
+ [import_core7.AlignTypeV.OUTSIDE]: "outside",
10305
+ [import_core7.AlignTypeV.TOP]: "top"
10306
+ };
10307
+ var OOXML_WRAP_TEXT_TO_CODE = {
10308
+ bothSides: import_core7.WrapTextType.BOTH_SIDES,
10309
+ left: import_core7.WrapTextType.LEFT,
10310
+ right: import_core7.WrapTextType.RIGHT,
10311
+ largest: import_core7.WrapTextType.LARGEST
10312
+ };
10313
+ var CODE_TO_OOXML_WRAP_TEXT = {
10314
+ [import_core7.WrapTextType.BOTH_SIDES]: "bothSides",
10315
+ [import_core7.WrapTextType.LEFT]: "left",
10316
+ [import_core7.WrapTextType.RIGHT]: "right",
10317
+ [import_core7.WrapTextType.LARGEST]: "largest"
10318
+ };
10226
10319
  function buildRunPrXml(ts) {
10227
10320
  if (!ts) return "";
10228
10321
  const rPrParts = [];
10229
- if (ts.ff) {
10230
- const ff = escapeXml(ts.ff);
10231
- rPrParts.push(`<w:rFonts w:ascii="${ff}" w:hAnsi="${ff}" w:eastAsia="${ff}" w:cs="${ff}"/>`);
10322
+ const rFonts = ts.yudaoRFonts;
10323
+ const ea = ts.eastAsiaFontFamily || rFonts?.eastAsia;
10324
+ const latin = rFonts ? ts.ff && ts.ff !== rFonts.eastAsia ? ts.ff : rFonts.ascii || rFonts.hAnsi : ts.ff;
10325
+ const cs = rFonts?.cs || (!rFonts ? latin || ea : void 0);
10326
+ const hint = ts.fontHint || rFonts?.hint;
10327
+ if (latin || ea || cs || hint) {
10328
+ const fontAttrs = [];
10329
+ if (latin) {
10330
+ fontAttrs.push(`w:ascii="${escapeXml(latin)}"`);
10331
+ const hAnsi = rFonts?.hAnsi && (!ts.ff || ts.ff === rFonts.ascii) ? rFonts.hAnsi : latin;
10332
+ fontAttrs.push(`w:hAnsi="${escapeXml(hAnsi)}"`);
10333
+ } else if (rFonts?.hAnsi) {
10334
+ fontAttrs.push(`w:hAnsi="${escapeXml(rFonts.hAnsi)}"`);
10335
+ }
10336
+ const effEa = ea || (!rFonts ? latin : void 0);
10337
+ if (effEa) {
10338
+ fontAttrs.push(`w:eastAsia="${escapeXml(effEa)}"`);
10339
+ }
10340
+ if (cs) {
10341
+ fontAttrs.push(`w:cs="${escapeXml(cs)}"`);
10342
+ }
10343
+ if (hint) {
10344
+ fontAttrs.push(`w:hint="${escapeXml(hint)}"`);
10345
+ }
10346
+ if (fontAttrs.length > 0) {
10347
+ rPrParts.push(`<w:rFonts ${fontAttrs.join(" ")}/>`);
10348
+ }
10232
10349
  }
10233
10350
  if (ts.bl === 1) rPrParts.push("<w:b/>");
10234
10351
  if (ts.it === 1) rPrParts.push("<w:i/>");
@@ -10292,37 +10409,68 @@ function toOoxmlCropPct1000(val) {
10292
10409
  }
10293
10410
  return Math.max(0, Math.min(95e3, Math.round(val * 1e3)));
10294
10411
  }
10295
- function buildInlineImageDrawingXml(relId, docPrId, widthPt, heightPt, blockId, transform) {
10412
+ function buildInlineImageDrawingXml(relId, docPrId, widthPt, heightPt, blockId, transform, drawingObj) {
10296
10413
  const cx = Math.max(91440, Math.round(widthPt * 12700));
10297
10414
  const cy = Math.max(91440, Math.round(heightPt * 12700));
10298
10415
  const picName = escapeXml(blockId || `Picture_${docPrId}`);
10299
10416
  const crop = transform?.crop;
10300
10417
  const srcRectXml = crop && (crop.left || crop.top || crop.right || crop.bottom) ? `<a:srcRect l="${toOoxmlCropPct1000(crop.left)}" t="${toOoxmlCropPct1000(crop.top)}" r="${toOoxmlCropPct1000(crop.right)}" b="${toOoxmlCropPct1000(crop.bottom)}"/>` : "";
10301
- const rotAttr = typeof transform?.rotationDeg === "number" && transform.rotationDeg !== 0 ? ` rot="${Math.round(transform.rotationDeg * 6e4)}"` : "";
10418
+ const effRotDeg = typeof transform?.rotationDeg === "number" ? transform.rotationDeg : typeof drawingObj?.docTransform?.angle === "number" ? drawingObj.docTransform.angle : 0;
10419
+ const rotAttr = effRotDeg !== 0 ? ` rot="${Math.round(effRotDeg * 6e4)}"` : "";
10302
10420
  const graphicXml = `<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="${docPrId}" name="${picName}"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="${relId}" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"/>${srcRectXml}<a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm${rotAttr}><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic>`;
10303
- const wrapType = transform?.wrapType ?? "inline";
10304
- const distTEmu = Math.max(0, Math.round((transform?.distT ?? 0) * 12700));
10305
- const distBEmu = Math.max(0, Math.round((transform?.distB ?? 0) * 12700));
10306
- const distLEmu = Math.max(0, Math.round((transform?.distL ?? (wrapType === "inline" ? 0 : 9)) * 12700));
10307
- const distREmu = Math.max(0, Math.round((transform?.distR ?? (wrapType === "inline" ? 0 : 9)) * 12700));
10308
- if (wrapType === "inline") {
10421
+ let layoutCode = typeof drawingObj?.layoutType === "number" ? drawingObj.layoutType : import_core7.PositionedObjectLayoutType.INLINE;
10422
+ if (transform?.wrapType) {
10423
+ if (transform.wrapType === "inline") layoutCode = import_core7.PositionedObjectLayoutType.INLINE;
10424
+ else if (transform.wrapType === "square") layoutCode = import_core7.PositionedObjectLayoutType.WRAP_SQUARE;
10425
+ else if (transform.wrapType === "tight") layoutCode = import_core7.PositionedObjectLayoutType.WRAP_TIGHT;
10426
+ else if (transform.wrapType === "through") layoutCode = import_core7.PositionedObjectLayoutType.WRAP_THROUGH;
10427
+ else if (transform.wrapType === "polygon") layoutCode = import_core7.PositionedObjectLayoutType.WRAP_POLYGON;
10428
+ else if (transform.wrapType === "topAndBottom") layoutCode = import_core7.PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM;
10429
+ else layoutCode = import_core7.PositionedObjectLayoutType.WRAP_NONE;
10430
+ }
10431
+ const isInline = layoutCode === import_core7.PositionedObjectLayoutType.INLINE;
10432
+ const distTEmu = Math.max(0, Math.round((transform?.distT ?? drawingObj?.distT ?? 0) * 12700));
10433
+ const distBEmu = Math.max(0, Math.round((transform?.distB ?? drawingObj?.distB ?? 0) * 12700));
10434
+ const distLEmu = Math.max(
10435
+ 0,
10436
+ Math.round((transform?.distL ?? drawingObj?.distL ?? (isInline ? 0 : 9)) * 12700)
10437
+ );
10438
+ const distREmu = Math.max(
10439
+ 0,
10440
+ Math.round((transform?.distR ?? drawingObj?.distR ?? (isInline ? 0 : 9)) * 12700)
10441
+ );
10442
+ if (isInline) {
10309
10443
  return `<w:r><w:drawing><wp:inline distT="${distTEmu}" distB="${distBEmu}" distL="${distLEmu}" distR="${distREmu}" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"><wp:extent cx="${cx}" cy="${cy}"/><wp:docPr id="${docPrId}" name="${picName}"/>${graphicXml}</wp:inline></w:drawing></w:r>`;
10310
10444
  }
10311
- const behindDoc = transform?.behindDoc !== void 0 ? transform.behindDoc ? "1" : "0" : wrapType === "behindText" ? "1" : "0";
10312
- const wrapTextAttr = escapeXml(transform?.wrapText || "bothSides");
10445
+ const behindDoc = transform?.behindDoc !== void 0 ? transform.behindDoc ? "1" : "0" : transform?.wrapType === "behindText" ? "1" : transform?.wrapType === "inFrontOfText" ? "0" : drawingObj?.behindDoc === import_core7.BooleanNumber.TRUE ? "1" : "0";
10446
+ const resolvedWrapText = transform?.wrapText || (typeof drawingObj?.wrapText === "number" ? CODE_TO_OOXML_WRAP_TEXT[drawingObj.wrapText] : typeof drawingObj?.wrapText === "string" ? drawingObj.wrapText : void 0) || "bothSides";
10447
+ const wrapTextAttr = escapeXml(resolvedWrapText);
10313
10448
  let wrapNodeXml = "<wp:wrapNone/>";
10314
- if (wrapType === "square") {
10449
+ if (layoutCode === import_core7.PositionedObjectLayoutType.WRAP_SQUARE) {
10315
10450
  wrapNodeXml = `<wp:wrapSquare wrapText="${wrapTextAttr}"/>`;
10316
- } else if (wrapType === "topAndBottom") {
10451
+ } else if (layoutCode === import_core7.PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM) {
10317
10452
  wrapNodeXml = "<wp:wrapTopAndBottom/>";
10318
- } else if (wrapType === "tight") {
10453
+ } else if (layoutCode === import_core7.PositionedObjectLayoutType.WRAP_THROUGH) {
10454
+ wrapNodeXml = `<wp:wrapThrough wrapText="${wrapTextAttr}"><wp:wrapPolygon edited="0"><wp:start x="0" y="0"/><wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/><wp:lineTo x="21600" y="0"/><wp:lineTo x="0" y="0"/></wp:wrapPolygon></wp:wrapThrough>`;
10455
+ } else if (layoutCode === import_core7.PositionedObjectLayoutType.WRAP_TIGHT || layoutCode === import_core7.PositionedObjectLayoutType.WRAP_POLYGON) {
10319
10456
  wrapNodeXml = `<wp:wrapTight wrapText="${wrapTextAttr}"><wp:wrapPolygon edited="0"><wp:start x="0" y="0"/><wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/><wp:lineTo x="21600" y="0"/><wp:lineTo x="0" y="0"/></wp:wrapPolygon></wp:wrapTight>`;
10320
10457
  }
10321
- const relH = escapeXml(transform?.relativeFromH || "column");
10322
- const relV = escapeXml(transform?.relativeFromV || "paragraph");
10323
- const posHEmu = Math.round((transform?.posOffsetH ?? 0) * 12700);
10324
- const posVEmu = Math.round((transform?.posOffsetV ?? 0) * 12700);
10325
- return `<w:r><w:drawing><wp:anchor distT="${distTEmu}" distB="${distBEmu}" distL="${distLEmu}" distR="${distREmu}" simplePos="0" relativeHeight="251658240" behindDoc="${behindDoc}" locked="0" layoutInCell="1" allowOverlap="1" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="${relH}"><wp:posOffset>${posHEmu}</wp:posOffset></wp:positionH><wp:positionV relativeFrom="${relV}"><wp:posOffset>${posVEmu}</wp:posOffset></wp:positionV><wp:extent cx="${cx}" cy="${cy}"/>${wrapNodeXml}<wp:docPr id="${docPrId}" name="${picName}"/>${graphicXml}</wp:anchor></w:drawing></w:r>`;
10458
+ const modelPosH = drawingObj?.docTransform?.positionH;
10459
+ const modelPosV = drawingObj?.docTransform?.positionV;
10460
+ const relH = escapeXml(
10461
+ transform?.relativeFromH || (typeof modelPosH?.relativeFrom === "number" ? CODE_TO_OOXML_REL_H[modelPosH.relativeFrom] : void 0) || "column"
10462
+ );
10463
+ const relV = escapeXml(
10464
+ transform?.relativeFromV || (typeof modelPosV?.relativeFrom === "number" ? CODE_TO_OOXML_REL_V[modelPosV.relativeFrom] : void 0) || "paragraph"
10465
+ );
10466
+ const alignH = transform?.alignH || (typeof modelPosH?.align === "number" ? CODE_TO_OOXML_ALIGN_H[modelPosH.align] : void 0);
10467
+ const alignV = transform?.alignV || (typeof modelPosV?.align === "number" ? CODE_TO_OOXML_ALIGN_V[modelPosV.align] : void 0);
10468
+ const posHInnerXml = alignH && transform?.posOffsetH === void 0 && modelPosH?.posOffset === void 0 ? `<wp:align>${escapeXml(alignH)}</wp:align>` : `<wp:posOffset>${Math.round((transform?.posOffsetH ?? modelPosH?.posOffset ?? 0) * 12700)}</wp:posOffset>`;
10469
+ const posVInnerXml = alignV && transform?.posOffsetV === void 0 && modelPosV?.posOffset === void 0 ? `<wp:align>${escapeXml(alignV)}</wp:align>` : `<wp:posOffset>${Math.round((transform?.posOffsetV ?? modelPosV?.posOffset ?? 0) * 12700)}</wp:posOffset>`;
10470
+ const relHeight = typeof drawingObj?.relativeHeight === "number" ? drawingObj.relativeHeight : 251658240;
10471
+ const layoutInCell = drawingObj?.layoutInCell !== void 0 ? drawingObj.layoutInCell ? "1" : "0" : "1";
10472
+ const allowOverlap = drawingObj?.allowOverlap !== void 0 ? drawingObj.allowOverlap ? "1" : "0" : "1";
10473
+ return `<w:r><w:drawing><wp:anchor distT="${distTEmu}" distB="${distBEmu}" distL="${distLEmu}" distR="${distREmu}" simplePos="0" relativeHeight="${relHeight}" behindDoc="${behindDoc}" locked="0" layoutInCell="${layoutInCell}" allowOverlap="${allowOverlap}" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="${relH}">${posHInnerXml}</wp:positionH><wp:positionV relativeFrom="${relV}">${posVInnerXml}</wp:positionV><wp:extent cx="${cx}" cy="${cy}"/>${wrapNodeXml}<wp:docPr id="${docPrId}" name="${picName}"/>${graphicXml}</wp:anchor></w:drawing></w:r>`;
10326
10474
  }
10327
10475
  function decodeDataUriImage(dataUri) {
10328
10476
  const utf8SvgMatch = dataUri.match(/^data:(image\/svg\+xml)(?:;charset=utf-8|;utf8)?,([\s\S]+)$/i);
@@ -10472,9 +10620,17 @@ function serializeSpanToRunsAndSdtXml(body, spanStart, spanEndExclusive, exportC
10472
10620
  const instrText = String(fldObj?.instrText || fldObj?.fieldType || "PAGE").trim();
10473
10621
  const fldValText = stream.slice(fieldAtCursor.startIndex, fieldAtCursor.endIndex + 1).replace(/[\r\n\u0000-\u001F]/g, "");
10474
10622
  const fldStyle = findStyleAtBody(body, fieldAtCursor.startIndex);
10475
- innerXml.push(
10476
- `<w:fldSimple w:instr=" ${escapeXml(instrText)} ">${buildRunXmlWithBreaks(fldValText, fldStyle)}</w:fldSimple>`
10477
- );
10623
+ if (fldObj?.sourceKind === "complex") {
10624
+ const rPr = buildRunPrXml(fldStyle);
10625
+ const valRuns = buildRunXmlWithBreaks(fldValText, fldStyle);
10626
+ innerXml.push(
10627
+ `<w:r>${rPr}<w:fldChar w:fldCharType="begin"/></w:r><w:r>${rPr}<w:instrText xml:space="preserve"> ${escapeXml(instrText)} </w:instrText></w:r><w:r>${rPr}<w:fldChar w:fldCharType="separate"/></w:r>` + (valRuns || `<w:r>${rPr}<w:t xml:space="preserve">${escapeXml(fldValText)}</w:t></w:r>`) + `<w:r>${rPr}<w:fldChar w:fldCharType="end"/></w:r>`
10628
+ );
10629
+ } else {
10630
+ innerXml.push(
10631
+ `<w:fldSimple w:instr=" ${escapeXml(instrText)} ">${buildRunXmlWithBreaks(fldValText, fldStyle)}</w:fldSimple>`
10632
+ );
10633
+ }
10478
10634
  cursor = fieldAtCursor.endIndex + 1;
10479
10635
  continue;
10480
10636
  }
@@ -10624,8 +10780,14 @@ function buildTableBordersOoxml(preset) {
10624
10780
  }
10625
10781
  return '<w:tblBorders><w:top w:val="dashed" w:sz="4" w:space="0" w:color="CBD5E1"/><w:left w:val="dashed" w:sz="4" w:space="0" w:color="CBD5E1"/><w:bottom w:val="dashed" w:sz="4" w:space="0" w:color="CBD5E1"/><w:right w:val="dashed" w:sz="4" w:space="0" w:color="CBD5E1"/><w:insideH w:val="dashed" w:sz="4" w:space="0" w:color="CBD5E1"/><w:insideV w:val="dashed" w:sz="4" w:space="0" w:color="CBD5E1"/></w:tblBorders>';
10626
10782
  }
10627
- function buildTcBordersOoxml(preset, rIdx, cIdx, rowCount, colCount, slashType, cellBorders) {
10783
+ function buildTcBordersOoxml(preset, rIdx, cIdx, rowCount, colCount, slashType, cellBorders, cellDef) {
10628
10784
  const edgeVal = preset === "dash" ? "dashed" : "single";
10785
+ const defEdgeMap = {
10786
+ top: "borderTop",
10787
+ left: "borderLeft",
10788
+ bottom: "borderBottom",
10789
+ right: "borderRight"
10790
+ };
10629
10791
  const mk = (active, tag) => {
10630
10792
  const customEdge = cellBorders?.[tag];
10631
10793
  if (customEdge) {
@@ -10637,6 +10799,18 @@ function buildTcBordersOoxml(preset, rIdx, cIdx, rowCount, colCount, slashType,
10637
10799
  const wCol = normalizeHex6(customEdge.color) || "CBD5E1";
10638
10800
  return `<w:${tag} w:val="${wVal}" w:sz="${wSz}" w:space="0" w:color="${wCol}"/>`;
10639
10801
  }
10802
+ if (!preset && cellDef) {
10803
+ const defBorder = cellDef[defEdgeMap[tag]];
10804
+ const defWidthPt = defBorder?.width?.v;
10805
+ if (typeof defWidthPt === "number") {
10806
+ if (defWidthPt <= 0) {
10807
+ return `<w:${tag} w:val="none" w:sz="0" w:space="0" w:color="auto"/>`;
10808
+ }
10809
+ const wSz = Math.max(2, Math.round(defWidthPt * 8));
10810
+ const wCol = normalizeHex6(defBorder?.color?.rgb) || "CBD5E1";
10811
+ return `<w:${tag} w:val="${edgeVal}" w:sz="${wSz}" w:space="0" w:color="${wCol}"/>`;
10812
+ }
10813
+ }
10640
10814
  return active ? `<w:${tag} w:val="${edgeVal}" w:sz="4" w:space="0" w:color="CBD5E1"/>` : `<w:${tag} w:val="none" w:sz="0" w:space="0" w:color="auto"/>`;
10641
10815
  };
10642
10816
  const isTop = rIdx === 0;
@@ -10672,18 +10846,32 @@ function buildTcBordersOoxml(preset, rIdx, cIdx, rowCount, colCount, slashType,
10672
10846
  function buildParagraphOpenPrXml(para, opts) {
10673
10847
  const pStyle = para?.paragraphStyle;
10674
10848
  const pPrParts = [];
10675
- if (pStyle?.namedStyleType >= 1 && pStyle?.namedStyleType <= 6) {
10849
+ if (para?.styleId) {
10850
+ pPrParts.push(`<w:pStyle w:val="${escapeXml(String(para.styleId))}"/>`);
10851
+ } else if (pStyle?.namedStyleType >= 1 && pStyle?.namedStyleType <= 6) {
10676
10852
  pPrParts.push(`<w:pStyle w:val="Heading${Number(pStyle.namedStyleType)}"/>`);
10677
10853
  }
10854
+ const pag = pStyle?.yudaoPagination;
10855
+ if (pag?.keepNext || pStyle?.keepNext) {
10856
+ pPrParts.push("<w:keepNext/>");
10857
+ }
10858
+ if (pag?.keepLines || pStyle?.keepLines) {
10859
+ pPrParts.push("<w:keepLines/>");
10860
+ }
10861
+ if (pag?.pageBreakBefore || pStyle?.pageBreakBefore) {
10862
+ pPrParts.push("<w:pageBreakBefore/>");
10863
+ }
10864
+ if (pag?.widowControl !== void 0) {
10865
+ pPrParts.push(pag.widowControl ? "<w:widowControl/>" : '<w:widowControl w:val="0"/>');
10866
+ } else if (pStyle?.widowControl !== void 0) {
10867
+ pPrParts.push(pStyle.widowControl ? "<w:widowControl/>" : '<w:widowControl w:val="0"/>');
10868
+ }
10678
10869
  if (para?.bullet?.listId) {
10679
10870
  const ilvl = Math.max(0, Number(para.bullet.nestingLevel ?? 0));
10680
10871
  const mappedNumId = opts?.listNumIdMap?.get(String(para.bullet.listId));
10681
10872
  const numId = mappedNumId ?? (String(para.bullet.listId).toLowerCase().includes("order") ? 2 : 1);
10682
10873
  pPrParts.push(`<w:numPr><w:ilvl w:val="${ilvl}"/><w:numId w:val="${numId}"/></w:numPr>`);
10683
10874
  }
10684
- if (opts?.isRtl || pStyle?.yudaoTextDirection === "rtl" || pStyle?.textDirection === 2) {
10685
- pPrParts.push("<w:bidi/>");
10686
- }
10687
10875
  if (opts?.callout) {
10688
10876
  const bdrHex = normalizeHex6(opts.callout.borderColor) || "2C53F1";
10689
10877
  const bgHex = normalizeHex6(opts.callout.backgroundColor) || "F3F5FF";
@@ -10696,7 +10884,6 @@ function buildParagraphOpenPrXml(para, opts) {
10696
10884
  pPrParts.push(
10697
10885
  `<w:pBdr><w:left w:val="single" w:sz="24" w:space="8" w:color="${lineHex}"/></w:pBdr>`
10698
10886
  );
10699
- pPrParts.push('<w:ind w:left="480"/>');
10700
10887
  } else if (opts?.isCodeBlockPara) {
10701
10888
  pPrParts.push(
10702
10889
  '<w:pBdr><w:top w:val="single" w:sz="4" w:space="2" w:color="CBD5E1"/><w:left w:val="single" w:sz="12" w:space="6" w:color="3B82F6"/><w:bottom w:val="single" w:sz="4" w:space="2" w:color="CBD5E1"/><w:right w:val="single" w:sz="4" w:space="4" w:color="CBD5E1"/></w:pBdr>'
@@ -10748,21 +10935,6 @@ function buildParagraphOpenPrXml(para, opts) {
10748
10935
  pPrParts.push(`<w:shd w:val="clear" w:color="auto" w:fill="${shdHex}"/>`);
10749
10936
  }
10750
10937
  }
10751
- const pag = pStyle?.yudaoPagination;
10752
- if (pag?.keepNext || pStyle?.keepNext) {
10753
- pPrParts.push("<w:keepNext/>");
10754
- }
10755
- if (pag?.keepLines || pStyle?.keepLines) {
10756
- pPrParts.push("<w:keepLines/>");
10757
- }
10758
- if (pag?.pageBreakBefore || pStyle?.pageBreakBefore) {
10759
- pPrParts.push("<w:pageBreakBefore/>");
10760
- }
10761
- if (pag?.widowControl !== void 0) {
10762
- pPrParts.push(pag.widowControl ? "<w:widowControl/>" : '<w:widowControl w:val="0"/>');
10763
- } else if (pStyle?.widowControl) {
10764
- pPrParts.push("<w:widowControl/>");
10765
- }
10766
10938
  const tabStops = pStyle?.yudaoTabStops;
10767
10939
  if (Array.isArray(tabStops) && tabStops.length > 0) {
10768
10940
  const tabTags = tabStops.map((t) => {
@@ -10773,6 +10945,72 @@ function buildParagraphOpenPrXml(para, opts) {
10773
10945
  }).join("");
10774
10946
  pPrParts.push(`<w:tabs>${tabTags}</w:tabs>`);
10775
10947
  }
10948
+ if (pStyle?.snapToGrid !== void 0) {
10949
+ pPrParts.push(pStyle.snapToGrid ? "<w:snapToGrid/>" : '<w:snapToGrid w:val="0"/>');
10950
+ }
10951
+ if (opts?.isRtl || pStyle?.yudaoTextDirection === "rtl" || pStyle?.textDirection === 2) {
10952
+ pPrParts.push("<w:bidi/>");
10953
+ }
10954
+ const spacingAttrs = [];
10955
+ if (typeof pStyle?.spaceAbove?.v === "number") {
10956
+ spacingAttrs.push(`w:before="${Math.max(0, Math.round(pStyle.spaceAbove.v * 20))}"`);
10957
+ }
10958
+ if (pStyle?.beforeAutoSpacing !== void 0) {
10959
+ spacingAttrs.push(`w:beforeAutospacing="${pStyle.beforeAutoSpacing ? "1" : "0"}"`);
10960
+ }
10961
+ if (typeof pStyle?.spaceBelow?.v === "number") {
10962
+ spacingAttrs.push(`w:after="${Math.max(0, Math.round(pStyle.spaceBelow.v * 20))}"`);
10963
+ }
10964
+ if (pStyle?.afterAutoSpacing !== void 0) {
10965
+ spacingAttrs.push(`w:afterAutospacing="${pStyle.afterAutoSpacing ? "1" : "0"}"`);
10966
+ }
10967
+ if (typeof pStyle?.lineSpacing === "number" && pStyle.lineSpacing > 0) {
10968
+ if (pStyle.spacingRule === import_core7.SpacingRule.EXACT) {
10969
+ spacingAttrs.push(`w:line="${Math.max(1, Math.round(pStyle.lineSpacing * 20))}"`);
10970
+ spacingAttrs.push('w:lineRule="exact"');
10971
+ } else if (pStyle.spacingRule === import_core7.SpacingRule.AT_LEAST) {
10972
+ spacingAttrs.push(`w:line="${Math.max(1, Math.round(pStyle.lineSpacing * 20))}"`);
10973
+ spacingAttrs.push('w:lineRule="atLeast"');
10974
+ } else {
10975
+ spacingAttrs.push(`w:line="${Math.max(1, Math.round(pStyle.lineSpacing * 240))}"`);
10976
+ spacingAttrs.push('w:lineRule="auto"');
10977
+ }
10978
+ }
10979
+ if (spacingAttrs.length > 0) {
10980
+ pPrParts.push(`<w:spacing ${spacingAttrs.join(" ")}/>`);
10981
+ }
10982
+ if (opts?.quote) {
10983
+ pPrParts.push('<w:ind w:left="480"/>');
10984
+ } else {
10985
+ const indAttrs = [];
10986
+ if (typeof pStyle?.indentStart?.v === "number") {
10987
+ indAttrs.push(`w:left="${Math.max(0, Math.round(pStyle.indentStart.v * 20))}"`);
10988
+ }
10989
+ if (typeof pStyle?.indentEnd?.v === "number") {
10990
+ indAttrs.push(`w:right="${Math.max(0, Math.round(pStyle.indentEnd.v * 20))}"`);
10991
+ }
10992
+ if (typeof pStyle?.hanging?.v === "number" && pStyle.hanging.v > 0) {
10993
+ indAttrs.push(`w:hanging="${Math.max(0, Math.round(pStyle.hanging.v * 20))}"`);
10994
+ } else if (typeof pStyle?.indentFirstLine?.v === "number") {
10995
+ if (pStyle.indentFirstLine.u === import_core7.NumberUnitType.CHARACTER) {
10996
+ indAttrs.push(
10997
+ `w:firstLineChars="${Math.max(0, Math.round(pStyle.indentFirstLine.v * 100))}"`
10998
+ );
10999
+ } else if (pStyle.indentFirstLine.v > 0) {
11000
+ indAttrs.push(`w:firstLine="${Math.max(0, Math.round(pStyle.indentFirstLine.v * 20))}"`);
11001
+ } else if (indAttrs.length === 0) {
11002
+ indAttrs.push('w:left="0"');
11003
+ }
11004
+ }
11005
+ if (indAttrs.length > 0) {
11006
+ pPrParts.push(`<w:ind ${indAttrs.join(" ")}/>`);
11007
+ }
11008
+ }
11009
+ if (pStyle?.contextualSpacing !== void 0) {
11010
+ pPrParts.push(
11011
+ pStyle.contextualSpacing ? "<w:contextualSpacing/>" : '<w:contextualSpacing w:val="0"/>'
11012
+ );
11013
+ }
10776
11014
  if (pStyle?.horizontalAlign === 2) {
10777
11015
  pPrParts.push('<w:jc w:val="center"/>');
10778
11016
  } else if (pStyle?.horizontalAlign === 3) {
@@ -10780,24 +11018,6 @@ function buildParagraphOpenPrXml(para, opts) {
10780
11018
  } else if (pStyle?.horizontalAlign === 4) {
10781
11019
  pPrParts.push('<w:jc w:val="both"/>');
10782
11020
  }
10783
- const spaceAbove = pStyle?.spaceAbove?.v;
10784
- const spaceBelow = pStyle?.spaceBelow?.v;
10785
- if (typeof spaceAbove === "number" || typeof spaceBelow === "number") {
10786
- const before = Math.max(0, Math.round((spaceAbove ?? 0) * 20));
10787
- const after = Math.max(0, Math.round((spaceBelow ?? 0) * 20));
10788
- pPrParts.push(`<w:spacing w:before="${before}" w:after="${after}"/>`);
10789
- }
10790
- if (!opts?.quote) {
10791
- const indentFirst = pStyle?.indentFirstLine?.v;
10792
- const indentStart = pStyle?.indentStart?.v;
10793
- if (typeof indentFirst === "number" || typeof indentStart === "number") {
10794
- const left = Math.max(0, Math.round((indentStart ?? 0) * 20));
10795
- const firstLine = Math.max(0, Math.round((indentFirst ?? 0) * 20));
10796
- pPrParts.push(
10797
- firstLine > 0 ? `<w:ind w:left="${left}" w:firstLine="${firstLine}"/>` : `<w:ind w:left="${left}"/>`
10798
- );
10799
- }
10800
- }
10801
11021
  if (pStyle?.yudaoSectionBreakType) {
10802
11022
  const orient = opts?.sectionOrientation ?? pStyle?.yudaoSectionOrientation;
10803
11023
  let sectPgSzXml = "";
@@ -10895,25 +11115,65 @@ function serializeStoryBodyXml(snapshot, body, exportCtx) {
10895
11115
  pCursor++;
10896
11116
  }
10897
11117
  const parsedRows = parseTableRowsInStream(stream, nextTbl.startIndex, nextTbl.endIndex);
10898
- const tblDef = snapshot.tableSource?.[nextTbl.tableId];
11118
+ const tblDef = exportCtx?.storyTableSource?.[nextTbl.tableId] ?? snapshot.tableSource?.[nextTbl.tableId];
10899
11119
  const hdrRowCount = resolveTableHeaderRowCount(snapshot, nextTbl.tableId);
10900
11120
  const tblDir = getDocTableDirection(snapshot, nextTbl.tableId);
10901
11121
  const tblBorderPreset = templateMeta.tableBorderPresets?.[nextTbl.tableId];
10902
11122
  const tblAutoFitWindow = tblDef?.yudaoAutoFitMode === "window";
10903
11123
  const colCount = tblDef?.tableColumns?.length || Math.max(1, ...parsedRows.map((r) => r.cells.length));
10904
11124
  const gridColsXml = Array.from({ length: colCount }, (_, cIdx) => {
10905
- const wPt = tblDef?.tableColumns?.[cIdx]?.size?.width?.v ?? Math.floor(460 / colCount);
10906
- return `<w:gridCol w:w="${Math.max(400, Math.round(wPt * 20))}"/>`;
11125
+ const colW = toPoints(tblDef?.tableColumns?.[cIdx]?.size?.width);
11126
+ const wPt = colW > 0 ? colW : Math.floor(460 / colCount);
11127
+ return `<w:gridCol w:w="${Math.max(20, Math.round(wPt * 20))}"/>`;
10907
11128
  }).join("");
11129
+ const buildTcWXml = (targetCellDef, cIdx, spanCols) => {
11130
+ const tcWType = targetCellDef?.tcWidthType;
11131
+ if (tcWType === "pct") {
11132
+ const pctVal = typeof targetCellDef?.yudaoTcWidthPct === "number" ? Math.max(1, Math.round(targetCellDef.yudaoTcWidthPct)) : Math.max(1, Math.round(toPoints(targetCellDef?.size?.width) * 50));
11133
+ return `<w:tcW w:w="${pctVal}" w:type="pct"/>`;
11134
+ }
11135
+ if (tcWType === "auto") {
11136
+ return '<w:tcW w:w="0" w:type="auto"/>';
11137
+ }
11138
+ if (tcWType === "nil") {
11139
+ return '<w:tcW w:w="0" w:type="nil"/>';
11140
+ }
11141
+ if (tcWType === "dxa" || targetCellDef?.size?.type === import_core7.TableSizeType.SPECIFIED) {
11142
+ const wPt = toPoints(targetCellDef?.size?.width);
11143
+ if (wPt > 0) {
11144
+ return `<w:tcW w:w="${Math.max(20, Math.round(wPt * 20))}" w:type="dxa"/>`;
11145
+ }
11146
+ }
11147
+ if (tblDef?.layout === import_core7.TableLayoutType.FIXED && tblDef.tableColumns?.length) {
11148
+ let sumPt = 0;
11149
+ for (let k = 0; k < spanCols; k++) {
11150
+ sumPt += toPoints(tblDef.tableColumns[cIdx + k]?.size?.width);
11151
+ }
11152
+ if (sumPt > 0) {
11153
+ return `<w:tcW w:w="${Math.max(20, Math.round(sumPt * 20))}" w:type="dxa"/>`;
11154
+ }
11155
+ }
11156
+ return "";
11157
+ };
10908
11158
  const trXmlList = parsedRows.map((rSpan, rIdx) => {
10909
11159
  const rowDef = tblDef?.tableRows?.[rIdx];
10910
11160
  const trPrParts = [];
11161
+ if (rowDef?.cantSplit === import_core7.BooleanNumber.TRUE) {
11162
+ trPrParts.push("<w:cantSplit/>");
11163
+ } else if (rowDef?.cantSplit === import_core7.BooleanNumber.FALSE) {
11164
+ trPrParts.push('<w:cantSplit w:val="0"/>');
11165
+ }
11166
+ const hValPt = toPoints(rowDef?.trHeight?.val);
11167
+ const hRule = rowDef?.trHeight?.hRule;
11168
+ if (hValPt > 0 && hRule !== import_core7.TableRowHeightRule.AUTO) {
11169
+ const wRule = hRule === import_core7.TableRowHeightRule.EXACT ? "exact" : "atLeast";
11170
+ trPrParts.push(
11171
+ `<w:trHeight w:val="${Math.max(1, Math.round(hValPt * 20))}" w:hRule="${wRule}"/>`
11172
+ );
11173
+ }
10911
11174
  if (rowDef?.repeatHeaderRow === import_core7.BooleanNumber.TRUE || rIdx < hdrRowCount) {
10912
11175
  trPrParts.push("<w:tblHeader/>");
10913
11176
  }
10914
- if (rowDef?.trHeight?.val?.v) {
10915
- trPrParts.push(`<w:trHeight w:val="${Math.round(rowDef.trHeight.val.v * 20)}"/>`);
10916
- }
10917
11177
  const trPrXml = trPrParts.length ? `<w:trPr>${trPrParts.join("")}</w:trPr>` : "";
10918
11178
  const tcXmlList = [];
10919
11179
  rSpan.cells.forEach((cSpan, cIdx) => {
@@ -10930,6 +11190,11 @@ function serializeStoryBodyXml(snapshot, body, exportCtx) {
10930
11190
  }
10931
11191
  if (master && rIdx > master.row && cIdx === master.col) {
10932
11192
  const contPr = [];
11193
+ const contCellDef = cellDef ?? tblDef?.tableRows?.[master.row]?.tableCells?.[master.col];
11194
+ const contTcW = buildTcWXml(contCellDef, cIdx, master.colSpan);
11195
+ if (contTcW) {
11196
+ contPr.push(contTcW);
11197
+ }
10933
11198
  if (master.colSpan > 1) {
10934
11199
  contPr.push(`<w:gridSpan w:val="${master.colSpan}"/>`);
10935
11200
  }
@@ -10943,6 +11208,10 @@ function serializeStoryBodyXml(snapshot, body, exportCtx) {
10943
11208
  const tcPrParts = [];
10944
11209
  const colSpan = cellDef?.columnSpan ?? 1;
10945
11210
  const rowSpan = cellDef?.rowSpan ?? 1;
11211
+ const tcWXml = buildTcWXml(cellDef, cIdx, colSpan);
11212
+ if (tcWXml) {
11213
+ tcPrParts.push(tcWXml);
11214
+ }
10946
11215
  if (colSpan > 1) {
10947
11216
  tcPrParts.push(`<w:gridSpan w:val="${colSpan}"/>`);
10948
11217
  }
@@ -10964,7 +11233,8 @@ function serializeStoryBodyXml(snapshot, body, exportCtx) {
10964
11233
  parsedRows.length,
10965
11234
  colCount,
10966
11235
  cellProps?.slashType,
10967
- cellProps?.borders
11236
+ cellProps?.borders,
11237
+ cellDef
10968
11238
  )
10969
11239
  );
10970
11240
  const cellParas = paragraphs.filter(
@@ -11008,11 +11278,25 @@ function serializeStoryBodyXml(snapshot, body, exportCtx) {
11008
11278
  });
11009
11279
  return `<w:tr>${trPrXml}${tcXmlList.join("")}</w:tr>`;
11010
11280
  });
11281
+ const yudaoTblWType = tblDef?.yudaoTblWidthType;
11282
+ let tblWXml;
11283
+ if (tblAutoFitWindow || yudaoTblWType === "pct") {
11284
+ const pctVal = Math.max(1, Math.round(Number(tblDef?.yudaoTblWidthPct ?? 5e3)));
11285
+ tblWXml = `<w:tblW w:w="${pctVal}" w:type="pct"/>`;
11286
+ } else if (yudaoTblWType === "nil") {
11287
+ tblWXml = '<w:tblW w:w="0" w:type="nil"/>';
11288
+ } else if (yudaoTblWType === "dxa" || tblDef?.size?.type === import_core7.TableSizeType.SPECIFIED) {
11289
+ const rawDxa = typeof tblDef?.yudaoTblWidthDxa === "number" ? Math.max(20, Math.round(tblDef.yudaoTblWidthDxa)) : Math.max(20, Math.round(toPoints(tblDef?.size?.width) * 20));
11290
+ tblWXml = `<w:tblW w:w="${rawDxa}" w:type="dxa"/>`;
11291
+ } else {
11292
+ tblWXml = '<w:tblW w:w="0" w:type="auto"/>';
11293
+ }
11294
+ const tblLayoutXml = tblDef?.layout === import_core7.TableLayoutType.FIXED ? '<w:tblLayout w:type="fixed"/>' : tblDef?.layout === import_core7.TableLayoutType.AUTO_FIT ? '<w:tblLayout w:type="autofit"/>' : "";
11011
11295
  const tblPrExtra = [
11012
11296
  tblDir === "rtl" ? "<w:bidiVisual/>" : "",
11013
- buildTableBordersOoxml(tblBorderPreset)
11297
+ buildTableBordersOoxml(tblBorderPreset),
11298
+ tblLayoutXml
11014
11299
  ].join("");
11015
- const tblWXml = tblAutoFitWindow ? '<w:tblW w:w="5000" w:type="pct"/>' : '<w:tblW w:w="0" w:type="auto"/>';
11016
11300
  blocksXml.push(
11017
11301
  `<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/>${tblWXml}${tblPrExtra}</w:tblPr><w:tblGrid>${gridColsXml}</w:tblGrid>${trXmlList.join("")}</w:tbl>`
11018
11302
  );
@@ -11032,9 +11316,13 @@ function serializeStoryBodyXml(snapshot, body, exportCtx) {
11032
11316
  return blocksXml.join("\n ");
11033
11317
  }
11034
11318
  function exportDocxBytes(rawSnapshot, data, exportOptions) {
11035
- const snapshot = evaluateDocTableFormulas(
11319
+ const evaluatedSnapshot = evaluateDocTableFormulas(
11036
11320
  data ? fillDatasetIntoDocSnapshot(rawSnapshot, data) : rawSnapshot
11037
11321
  );
11322
+ const snapshot = Object.keys(evaluatedSnapshot.drawings ?? {}).length === 0 && (evaluatedSnapshot.resources ?? []).some((r) => r.name === "DOC_DRAWING_PLUGIN") ? normalizeDocDrawingsAndPluginResource({
11323
+ ...evaluatedSnapshot,
11324
+ resources: evaluatedSnapshot.resources ? [...evaluatedSnapshot.resources] : void 0
11325
+ }) : evaluatedSnapshot;
11038
11326
  const body = snapshot.body ?? {
11039
11327
  dataStream: "\r\n",
11040
11328
  paragraphs: [{ startIndex: 0, paragraphId: "p0" }]
@@ -11127,7 +11415,8 @@ function exportDocxBytes(rawSnapshot, data, exportOptions) {
11127
11415
  wPt,
11128
11416
  hPt,
11129
11417
  block.blockId,
11130
- drwTransform
11418
+ drwTransform,
11419
+ drawing
11131
11420
  );
11132
11421
  const embedSpec = exportMeta.embedBlocks?.[block.blockId];
11133
11422
  if (embedSpec?.url) {
@@ -11216,6 +11505,7 @@ function exportDocxBytes(rawSnapshot, data, exportOptions) {
11216
11505
  const mediaName = `media/image${imgSeq}.${dec.ext}`;
11217
11506
  const wPt = drw?.docTransform?.size?.width ?? 90;
11218
11507
  const hPt = drw?.docTransform?.size?.height ?? 36;
11508
+ const hfDrwTransform = exportMeta.imageTransforms?.[blk.blockId] ?? drw?.yudaoTransform;
11219
11509
  extraZipFiles.push({ name: `word/${mediaName}`, content: dec.bytes });
11220
11510
  imageExts.set(dec.ext, dec.mime);
11221
11511
  hfRels.push(
@@ -11223,7 +11513,7 @@ function exportDocxBytes(rawSnapshot, data, exportOptions) {
11223
11513
  );
11224
11514
  hfDrawingMap.set(
11225
11515
  blk.startIndex,
11226
- buildInlineImageDrawingXml(rId, imgSeq, wPt, hPt, blk.blockId)
11516
+ buildInlineImageDrawingXml(rId, imgSeq, wPt, hPt, blk.blockId, hfDrwTransform, drw)
11227
11517
  );
11228
11518
  imgSeq++;
11229
11519
  }
@@ -11251,7 +11541,8 @@ function exportDocxBytes(rawSnapshot, data, exportOptions) {
11251
11541
  <Override PartName="/word/${target}" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml"/>`;
11252
11542
  const hfDrw = collectHfDrawings(entry.body, target);
11253
11543
  const hdrBodyXml = serializeStoryBodyXml(snapshot, entry.body, {
11254
- drawingXmlByOffset: hfDrw
11544
+ drawingXmlByOffset: hfDrw,
11545
+ storyTableSource: entry.tableSource
11255
11546
  });
11256
11547
  extraZipFiles.push({
11257
11548
  name: `word/${target}`,
@@ -11273,7 +11564,8 @@ function exportDocxBytes(rawSnapshot, data, exportOptions) {
11273
11564
  <Override PartName="/word/${target}" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml"/>`;
11274
11565
  const hfDrw = collectHfDrawings(entry.body, target);
11275
11566
  const ftrBodyXml = serializeStoryBodyXml(snapshot, entry.body, {
11276
- drawingXmlByOffset: hfDrw
11567
+ drawingXmlByOffset: hfDrw,
11568
+ storyTableSource: entry.tableSource
11277
11569
  });
11278
11570
  extraZipFiles.push({
11279
11571
  name: `word/${target}`,
@@ -11369,14 +11661,21 @@ function exportDocxBytes(rawSnapshot, data, exportOptions) {
11369
11661
  <w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:p>${wmDrawingXml}</w:p></w:hdr>`
11370
11662
  });
11371
11663
  }
11372
- const hasFirstPageHf = resolvedHeaders.some((h) => h.slot === "first") || resolvedFooters.some((f) => f.slot === "first") || docStyle?.useFirstPageHeaderFooter === import_core7.BooleanNumber.TRUE;
11373
- const hasEvenPageHf = resolvedHeaders.some((h) => h.slot === "even") || resolvedFooters.some((f) => f.slot === "even") || docStyle?.evenAndOddHeaders === import_core7.BooleanNumber.TRUE;
11664
+ const explicitUseFirstHf = docStyle?.useFirstPageHeaderFooter ?? firstSectionBreak?.useFirstPageHeaderFooter;
11665
+ const hasFirstPageHf = explicitUseFirstHf === import_core7.BooleanNumber.TRUE || explicitUseFirstHf === void 0 && (resolvedHeaders.some((h) => h.slot === "first") || resolvedFooters.some((f) => f.slot === "first"));
11666
+ const explicitEvenOdd = docStyle?.evenAndOddHeaders ?? firstSectionBreak?.evenAndOddHeaders;
11667
+ const hasEvenPageHf = explicitEvenOdd === import_core7.BooleanNumber.TRUE || explicitEvenOdd === void 0 && (resolvedHeaders.some((h) => h.slot === "even") || resolvedFooters.some((f) => f.slot === "even"));
11668
+ const liveDocFields = listDocFields(snapshot);
11669
+ const hasTocField = Boolean(
11670
+ (body.customRanges ?? []).some((r) => r.properties?.yudaoBlockKind === "toc")
11671
+ );
11672
+ const wantUpdateFields = liveDocFields.length > 0 || hasTocField;
11374
11673
  const wantAutoHyphenation = Boolean(exportMeta.printConfig?.autoHyphenation);
11375
11674
  const wantGutterAtTop = exportMeta.printConfig?.gutterPosition === "top";
11376
11675
  const fnSettings = exportMeta.noteSettings?.footnote;
11377
11676
  const enSettings = exportMeta.noteSettings?.endnote;
11378
11677
  const mapNoteFmtOoxml = (fmt3) => fmt3 === "lowerRoman" ? "lowerRoman" : fmt3 === "circled" ? "chicago" : "decimal";
11379
- if (hasEvenPageHf || wantAutoHyphenation || wantGutterAtTop || fnSettings || enSettings) {
11678
+ if (hasEvenPageHf || wantAutoHyphenation || wantGutterAtTop || fnSettings || enSettings || wantUpdateFields) {
11380
11679
  relEntries.push({
11381
11680
  id: "rIdSettings",
11382
11681
  type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",
@@ -11390,6 +11689,7 @@ function exportDocxBytes(rawSnapshot, data, exportOptions) {
11390
11689
  hasEvenPageHf ? " <w:evenAndOddHeaders/>" : "",
11391
11690
  wantAutoHyphenation ? " <w:autoHyphenation/>" : "",
11392
11691
  wantGutterAtTop ? " <w:gutterAtTop/>" : "",
11692
+ wantUpdateFields ? ' <w:updateFields w:val="true"/>' : "",
11393
11693
  fnPrXml,
11394
11694
  enPrXml
11395
11695
  ].filter(Boolean).join("\n");
@@ -11488,7 +11788,6 @@ ${commentsItemsXml}
11488
11788
  const liveShapesArr = listLiveDocShapes(snapshot);
11489
11789
  const liveInlineFormulas = listDocInlineFormulas(snapshot);
11490
11790
  const liveSmartArtsArr = listLiveSmartArts(snapshot);
11491
- const liveDocFields = listDocFields(snapshot);
11492
11791
  const liveCaptions = listDocCaptions(snapshot);
11493
11792
  const liveCitations = listDocCitations(snapshot);
11494
11793
  const serializedLatexMap = liveLatexArr.length > 0 ? Object.fromEntries(liveLatexArr.map((f) => [f.id, f])) : templateMeta.latexFormulas;
@@ -11689,10 +11988,18 @@ ${commentsItemsXml}
11689
11988
  const pageW = trailingOrient === "landscape" ? Math.max(basePageWTw, basePageHTw) : trailingOrient === "portrait" ? Math.min(basePageWTw, basePageHTw) : basePageWTw;
11690
11989
  const pageH = trailingOrient === "landscape" ? Math.min(basePageWTw, basePageHTw) : trailingOrient === "portrait" ? Math.max(basePageWTw, basePageHTw) : basePageHTw;
11691
11990
  const orientAttr = pageW > pageH ? ' w:orient="landscape"' : "";
11692
- const marTop = Math.round((docStyle?.marginTop ?? 56) * 20);
11693
- const marBottom = Math.round((docStyle?.marginBottom ?? 56) * 20);
11694
- const marLeft = Math.round((docStyle?.marginLeft ?? 64) * 20);
11695
- const marRight = Math.round((docStyle?.marginRight ?? 64) * 20);
11991
+ const marTop = Math.round((docStyle?.marginTop ?? firstSectionBreak?.marginTop ?? 56) * 20);
11992
+ const marBottom = Math.round(
11993
+ (docStyle?.marginBottom ?? firstSectionBreak?.marginBottom ?? 56) * 20
11994
+ );
11995
+ const marLeft = Math.round((docStyle?.marginLeft ?? firstSectionBreak?.marginLeft ?? 64) * 20);
11996
+ const marRight = Math.round((docStyle?.marginRight ?? firstSectionBreak?.marginRight ?? 64) * 20);
11997
+ const marHeader = Math.round(
11998
+ (docStyle?.marginHeader ?? firstSectionBreak?.marginHeader ?? 36) * 20
11999
+ );
12000
+ const marFooter = Math.round(
12001
+ (docStyle?.marginFooter ?? firstSectionBreak?.marginFooter ?? 36) * 20
12002
+ );
11696
12003
  const gutterTwips = Math.max(0, Math.round((templateMeta.printConfig?.gutterPt ?? 0) * 20));
11697
12004
  const gutterAttr = gutterTwips > 0 ? ` w:gutter="${gutterTwips}"` : "";
11698
12005
  let pgBordersXml = "";
@@ -11744,6 +12051,24 @@ ${commentsItemsXml}
11744
12051
  }
11745
12052
  }
11746
12053
  const titlePgXml = hasFirstPageHf ? "\n <w:titlePg/>" : "";
12054
+ let docGridXml = "";
12055
+ const savedGrid = docStyle?.yudaoDocGrid;
12056
+ const effGridType = firstSectionBreak?.gridType ?? docStyle?.gridType;
12057
+ const effLinePitch = firstSectionBreak?.linePitch ?? docStyle?.linePitch;
12058
+ const effCharSpace = firstSectionBreak?.charSpace ?? docStyle?.charSpace;
12059
+ if (savedGrid || effGridType !== void 0 || typeof effLinePitch === "number" || typeof effCharSpace === "number") {
12060
+ const gAttrs = [];
12061
+ const gTypeStr = savedGrid?.type ?? (effGridType === import_core7.GridType.LINES ? "lines" : effGridType === import_core7.GridType.LINES_AND_CHARS ? "linesAndChars" : effGridType === import_core7.GridType.SNAP_TO_CHARS ? "snapToChars" : effGridType === import_core7.GridType.DEFAULT ? "default" : void 0);
12062
+ if (gTypeStr) gAttrs.push(`w:type="${escapeXml(gTypeStr)}"`);
12063
+ const lpTwips = typeof savedGrid?.linePitch === "number" ? Math.round(savedGrid.linePitch) : typeof effLinePitch === "number" && effLinePitch > 0 ? Math.round(effLinePitch * 20) : void 0;
12064
+ if (lpTwips !== void 0) gAttrs.push(`w:linePitch="${lpTwips}"`);
12065
+ const csVal = typeof savedGrid?.charSpace === "number" ? Math.round(savedGrid.charSpace) : typeof effCharSpace === "number" && effCharSpace !== 0 ? Math.round(effCharSpace) : void 0;
12066
+ if (csVal !== void 0) gAttrs.push(`w:charSpace="${csVal}"`);
12067
+ if (gAttrs.length > 0) {
12068
+ docGridXml = `
12069
+ <w:docGrid ${gAttrs.join(" ")}/>`;
12070
+ }
12071
+ }
11747
12072
  const documentXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
11748
12073
  <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/wordprocessingml" xmlns:w06="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml">`.replace(
11749
12074
  'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/wordprocessingml" xmlns:w06=',
@@ -11754,28 +12079,103 @@ ${commentsItemsXml}
11754
12079
  <w:sectPr>
11755
12080
  ${sectHeaderFooterRefs}${titlePgXml}
11756
12081
  <w:pgSz w:w="${pageW}" w:h="${pageH}"${orientAttr}/>
11757
- <w:pgMar w:top="${marTop}" w:right="${marRight}" w:bottom="${marBottom}" w:left="${marLeft}" w:header="720" w:footer="720"${gutterAttr}/>${pgBordersXml}${lnNumXml}${colsXml}
12082
+ <w:pgMar w:top="${marTop}" w:right="${marRight}" w:bottom="${marBottom}" w:left="${marLeft}" w:header="${marHeader}" w:footer="${marFooter}"${gutterAttr}/>${pgBordersXml}${lnNumXml}${colsXml}${docGridXml}
11758
12083
  </w:sectPr>
11759
12084
  </w:body>
11760
12085
  </w:document>`;
11761
- const headingStylesXml = [1, 2, 3, 4, 5, 6].map(
11762
- (lvl) => ` <w:style w:type="paragraph" w:styleId="Heading${lvl}"><w:name w:val="heading ${lvl}"/><w:pPr><w:outlineLvl w:val="${lvl - 1}"/></w:pPr></w:style>`
11763
- ).join("\n");
12086
+ const defTs = docStyle?.textStyle;
12087
+ const defRFonts = defTs?.yudaoRFonts;
12088
+ const defLatin = defTs?.ff && (!defRFonts?.eastAsia || defTs.ff !== defRFonts.eastAsia || defRFonts.ascii || defRFonts.hAnsi) ? defTs.ff : defRFonts?.ascii || defRFonts?.hAnsi || "Calibri";
12089
+ const defHAnsi = defRFonts?.hAnsi || defLatin;
12090
+ const defEa = defTs?.eastAsiaFontFamily || defRFonts?.eastAsia || "Microsoft YaHei";
12091
+ const defCs = defRFonts?.cs || (defTs?.ff ? defLatin : "Times New Roman");
12092
+ const defHintAttr = defTs?.fontHint || defRFonts?.hint ? ` w:hint="${escapeXml(String(defTs?.fontHint || defRFonts?.hint))}"` : "";
12093
+ const defSzHalfPt = Math.max(2, Math.round((defTs?.fs ?? 11) * 2));
12094
+ const defExtraRPr = defTs ? buildRunPrXml({
12095
+ ...defTs,
12096
+ ff: void 0,
12097
+ eastAsiaFontFamily: void 0,
12098
+ fontHint: void 0,
12099
+ fs: void 0,
12100
+ ...{ yudaoRFonts: void 0 }
12101
+ }).replace(/^<w:rPr>|<\/w:rPr>$/g, "") : "";
12102
+ const pPrDefaultInner = docStyle?.defaultParagraphStyle ? buildParagraphOpenPrXml({ paragraphStyle: docStyle.defaultParagraphStyle }) : "";
12103
+ const pPrDefaultXml = pPrDefaultInner ? `
12104
+ <w:pPrDefault>
12105
+ ${pPrDefaultInner}
12106
+ </w:pPrDefault>` : "";
12107
+ const defaultParaStyleId = docStyle?.defaultParagraphStyleId || "Normal";
12108
+ const snapshotStyles = snapshot.styles ?? {};
12109
+ const serializeNamedStyleXml = (styleId, st, isDefault = false, outlineLvl) => {
12110
+ const wType = st.type === import_core7.DocStyleType.character ? "character" : st.type === import_core7.DocStyleType.table ? "table" : st.type === import_core7.DocStyleType.numbering ? "numbering" : "paragraph";
12111
+ const defAttr = isDefault ? ' w:default="1"' : "";
12112
+ const customAttr = st.customStyle ? ' w:customStyle="1"' : "";
12113
+ const nameXml = `<w:name w:val="${escapeXml(st.name || styleId)}"/>`;
12114
+ const basedOnXml = st.basedOn ? `<w:basedOn w:val="${escapeXml(st.basedOn)}"/>` : "";
12115
+ const linkXml = st.link ? `<w:link w:val="${escapeXml(st.link)}"/>` : "";
12116
+ let pPrXml = st.paragraphStyle ? buildParagraphOpenPrXml({ paragraphStyle: st.paragraphStyle }) : "";
12117
+ if (typeof outlineLvl === "number") {
12118
+ const outlineTag = `<w:outlineLvl w:val="${outlineLvl}"/>`;
12119
+ if (pPrXml) {
12120
+ pPrXml = pPrXml.replace(/^<w:pPr>/, `<w:pPr>${outlineTag}`);
12121
+ } else {
12122
+ pPrXml = `<w:pPr>${outlineTag}</w:pPr>`;
12123
+ }
12124
+ }
12125
+ const rPrXml = st.textStyle ? buildRunPrXml(st.textStyle) : "";
12126
+ return ` <w:style w:type="${wType}"${defAttr}${customAttr} w:styleId="${escapeXml(styleId)}">${nameXml}${basedOnXml}${linkXml}${pPrXml}${rPrXml}</w:style>`;
12127
+ };
12128
+ const styleBlocksXml = [];
12129
+ const emittedStyleIds = /* @__PURE__ */ new Set();
12130
+ if (snapshotStyles[defaultParaStyleId]) {
12131
+ styleBlocksXml.push(
12132
+ serializeNamedStyleXml(defaultParaStyleId, snapshotStyles[defaultParaStyleId], true)
12133
+ );
12134
+ emittedStyleIds.add(defaultParaStyleId);
12135
+ } else {
12136
+ styleBlocksXml.push(
12137
+ ` <w:style w:type="paragraph" w:default="1" w:styleId="${escapeXml(defaultParaStyleId)}"><w:name w:val="Normal"/></w:style>`
12138
+ );
12139
+ emittedStyleIds.add(defaultParaStyleId);
12140
+ }
12141
+ if (!emittedStyleIds.has("Normal")) {
12142
+ if (snapshotStyles.Normal) {
12143
+ styleBlocksXml.push(serializeNamedStyleXml("Normal", snapshotStyles.Normal, false));
12144
+ } else {
12145
+ styleBlocksXml.push(
12146
+ ' <w:style w:type="paragraph" w:styleId="Normal"><w:name w:val="Normal"/></w:style>'
12147
+ );
12148
+ }
12149
+ emittedStyleIds.add("Normal");
12150
+ }
12151
+ for (let lvl = 1; lvl <= 6; lvl++) {
12152
+ const hId = `Heading${lvl}`;
12153
+ if (snapshotStyles[hId]) {
12154
+ styleBlocksXml.push(serializeNamedStyleXml(hId, snapshotStyles[hId], false, lvl - 1));
12155
+ } else {
12156
+ styleBlocksXml.push(
12157
+ ` <w:style w:type="paragraph" w:styleId="${hId}"><w:name w:val="heading ${lvl}"/><w:pPr><w:outlineLvl w:val="${lvl - 1}"/></w:pPr></w:style>`
12158
+ );
12159
+ }
12160
+ emittedStyleIds.add(hId);
12161
+ }
12162
+ for (const [sId, st] of Object.entries(snapshotStyles)) {
12163
+ if (emittedStyleIds.has(sId) || sId === "TableGrid" || !st) continue;
12164
+ styleBlocksXml.push(serializeNamedStyleXml(sId, st, false));
12165
+ emittedStyleIds.add(sId);
12166
+ }
11764
12167
  const stylesXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
11765
12168
  <w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
11766
12169
  <w:docDefaults>
11767
12170
  <w:rPrDefault>
11768
12171
  <w:rPr>
11769
- <w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:eastAsia="Microsoft YaHei" w:cs="Times New Roman"/>
11770
- <w:sz w:val="22"/>
11771
- <w:szCs w:val="22"/>
12172
+ <w:rFonts w:ascii="${escapeXml(defLatin)}" w:hAnsi="${escapeXml(defHAnsi)}" w:eastAsia="${escapeXml(defEa)}" w:cs="${escapeXml(defCs)}"${defHintAttr}/>${defExtraRPr}
12173
+ <w:sz w:val="${defSzHalfPt}"/>
12174
+ <w:szCs w:val="${defSzHalfPt}"/>
11772
12175
  </w:rPr>
11773
- </w:rPrDefault>
12176
+ </w:rPrDefault>${pPrDefaultXml}
11774
12177
  </w:docDefaults>
11775
- <w:style w:type="paragraph" w:default="1" w:styleId="Normal">
11776
- <w:name w:val="Normal"/>
11777
- </w:style>
11778
- ${headingStylesXml}
12178
+ ${styleBlocksXml.join("\n")}
11779
12179
  <w:style w:type="table" w:styleId="TableGrid">
11780
12180
  <w:name w:val="Table Grid"/>
11781
12181
  <w:tblPr>
@@ -12751,8 +13151,62 @@ async function extractAllDocxZipEntries(bytes) {
12751
13151
  }
12752
13152
  return out;
12753
13153
  }
12754
- function parseRunStyleFromXml(rXml) {
12755
- const rPrMatch = rXml.match(/<w:rPr[\s>][\s\S]*?<\/w:rPr>/);
13154
+ function parseThemeFontsFromXml(themeXml) {
13155
+ const extractSlot = (tag) => {
13156
+ const block = themeXml.match(new RegExp(`<a:${tag}[\\s>][\\s\\S]*?<\\/a:${tag}>`))?.[0] || "";
13157
+ if (!block) return {};
13158
+ const latin = block.match(/<a:latin\b[^>]*\btypeface="([^"]*)"/)?.[1]?.trim() || void 0;
13159
+ const eaDirect = block.match(/<a:ea\b[^>]*\btypeface="([^"]*)"/)?.[1]?.trim() || void 0;
13160
+ const hans = block.match(/<a:font\b[^>]*\bscript="Hans"[^>]*\btypeface="([^"]+)"/)?.[1]?.trim() || block.match(/<a:font\b[^>]*\btypeface="([^"]+)"[^>]*\bscript="Hans"/)?.[1]?.trim() || void 0;
13161
+ return {
13162
+ latin: latin ? unescapeXml(latin) : void 0,
13163
+ eastAsia: eaDirect ? unescapeXml(eaDirect) : hans ? unescapeXml(hans) : void 0
13164
+ };
13165
+ };
13166
+ const major = extractSlot("majorFont");
13167
+ const minor = extractSlot("minorFont");
13168
+ return {
13169
+ ...major.latin ? { majorLatin: major.latin } : {},
13170
+ ...minor.latin ? { minorLatin: minor.latin } : {},
13171
+ ...major.eastAsia ? { majorEastAsia: major.eastAsia } : {},
13172
+ ...minor.eastAsia ? { minorEastAsia: minor.eastAsia } : {}
13173
+ };
13174
+ }
13175
+ function resolveThemeFontToken(token, theme) {
13176
+ if (!token || !theme) return void 0;
13177
+ const lower = token.toLowerCase();
13178
+ if (lower === "majoreastasia") return theme.majorEastAsia || theme.majorLatin;
13179
+ if (lower === "minoreastasia") return theme.minorEastAsia || theme.minorLatin;
13180
+ if (lower.startsWith("major")) return theme.majorLatin;
13181
+ if (lower.startsWith("minor")) return theme.minorLatin;
13182
+ return void 0;
13183
+ }
13184
+ function mergeDocTextStyles(base, override) {
13185
+ if (!base && !override) return void 0;
13186
+ if (!base) return override ? { ...override } : void 0;
13187
+ if (!override) return { ...base };
13188
+ const baseRF = base.yudaoRFonts;
13189
+ const overRF = override.yudaoRFonts;
13190
+ const mergedRF = baseRF || overRF ? {
13191
+ ...baseRF ?? {},
13192
+ ...overRF ?? {}
13193
+ } : void 0;
13194
+ const merged = {
13195
+ ...base,
13196
+ ...override
13197
+ };
13198
+ if (mergedRF) {
13199
+ merged.yudaoRFonts = mergedRF;
13200
+ const latin = mergedRF.ascii || mergedRF.hAnsi || mergedRF.cs;
13201
+ const ea = override.eastAsiaFontFamily || base.eastAsiaFontFamily || mergedRF.eastAsia;
13202
+ if (ea) merged.eastAsiaFontFamily = ea;
13203
+ if (latin) merged.ff = latin;
13204
+ else if (ea) merged.ff = ea;
13205
+ }
13206
+ return merged;
13207
+ }
13208
+ function parseRunStyleFromXml(rXml, themeFonts) {
13209
+ const rPrMatch = rXml.startsWith("<w:rPr") ? [rXml] : rXml.match(/<w:rPr[\s>][\s\S]*?<\/w:rPr>/);
12756
13210
  if (!rPrMatch) return void 0;
12757
13211
  const rPr = rPrMatch[0];
12758
13212
  const style = {};
@@ -12807,15 +13261,49 @@ function parseRunStyleFromXml(rXml) {
12807
13261
  hasAny = true;
12808
13262
  }
12809
13263
  }
12810
- const szMatch = rPr.match(/<w:sz\s[^>]*w:val="(\d+)"/);
13264
+ const szMatch = rPr.match(/<w:sz\b[^>]*w:val="(\d+)"/) || rPr.match(/<w:szCs\b[^>]*w:val="(\d+)"/);
12811
13265
  if (szMatch) {
12812
- style.fs = Math.max(6, Math.round(Number(szMatch[1]) / 2 * 10) / 10);
13266
+ style.fs = Math.max(6, Math.round(Number(szMatch[1]) / 2 * 100) / 100);
12813
13267
  hasAny = true;
12814
13268
  }
12815
- const fontMatch = rPr.match(/w:eastAsia="([^"]+)"/) || rPr.match(/w:ascii="([^"]+)"/);
12816
- if (fontMatch) {
12817
- style.ff = unescapeXml(fontMatch[1]);
12818
- hasAny = true;
13269
+ const rFontsMatch = rPr.match(/<w:rFonts\b([^>]*)\/?>/);
13270
+ if (rFontsMatch) {
13271
+ const rfAttrs = rFontsMatch[1] || "";
13272
+ const rawAscii = rfAttrs.match(/\bw:ascii="([^"]+)"/)?.[1];
13273
+ const rawHAnsi = rfAttrs.match(/\bw:hAnsi="([^"]+)"/)?.[1];
13274
+ const rawEa = rfAttrs.match(/\bw:eastAsia="([^"]+)"/)?.[1];
13275
+ const rawCs = rfAttrs.match(/\bw:cs="([^"]+)"/)?.[1];
13276
+ const rawHint = rfAttrs.match(/\bw:hint="([^"]+)"/)?.[1];
13277
+ const ascii = (rawAscii ? unescapeXml(rawAscii) : void 0) ?? resolveThemeFontToken(rfAttrs.match(/\bw:asciiTheme="([^"]+)"/)?.[1], themeFonts);
13278
+ const hAnsi = (rawHAnsi ? unescapeXml(rawHAnsi) : void 0) ?? resolveThemeFontToken(rfAttrs.match(/\bw:hAnsiTheme="([^"]+)"/)?.[1], themeFonts);
13279
+ const eastAsia = (rawEa ? unescapeXml(rawEa) : void 0) ?? resolveThemeFontToken(rfAttrs.match(/\bw:eastAsiaTheme="([^"]+)"/)?.[1], themeFonts);
13280
+ const cs = (rawCs ? unescapeXml(rawCs) : void 0) ?? resolveThemeFontToken(rfAttrs.match(/\bw:csTheme="([^"]+)"/)?.[1], themeFonts);
13281
+ const hint = rawHint ? unescapeXml(rawHint) : void 0;
13282
+ const latin = ascii || hAnsi || cs;
13283
+ if (eastAsia) {
13284
+ style.eastAsiaFontFamily = eastAsia;
13285
+ hasAny = true;
13286
+ }
13287
+ if (latin) {
13288
+ style.ff = latin;
13289
+ hasAny = true;
13290
+ } else if (eastAsia) {
13291
+ style.ff = eastAsia;
13292
+ hasAny = true;
13293
+ }
13294
+ if (hint === "default" || hint === "eastAsia" || hint === "cs") {
13295
+ style.fontHint = hint;
13296
+ hasAny = true;
13297
+ }
13298
+ const yudaoRFonts = {};
13299
+ if (ascii) yudaoRFonts.ascii = ascii;
13300
+ if (hAnsi) yudaoRFonts.hAnsi = hAnsi;
13301
+ if (eastAsia) yudaoRFonts.eastAsia = eastAsia;
13302
+ if (cs) yudaoRFonts.cs = cs;
13303
+ if (hint) yudaoRFonts.hint = hint;
13304
+ if (Object.keys(yudaoRFonts).length > 0) {
13305
+ style.yudaoRFonts = yudaoRFonts;
13306
+ }
12819
13307
  }
12820
13308
  const colorMatch = rPr.match(/<w:color\s[^>]*w:val="([0-9a-fA-F]{6})"/);
12821
13309
  if (colorMatch) {
@@ -12890,7 +13378,10 @@ function extractDrawingFromXmlChunk(chunk, relsMap, entries, collectedDrawings,
12890
13378
  const ext = (zipKey.split(".").pop() || "png").toLowerCase();
12891
13379
  const mime = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : ext === "svg" ? "image/svg+xml" : `image/${ext}`;
12892
13380
  const docPrName = chunk.match(/<wp:docPr\s[^>]*name="([^"]+)"/)?.[1];
12893
- const blockId = docPrName && !docPrName.startsWith("Picture_") && !docPrName.startsWith("Picture ") ? unescapeXml(docPrName) : `img_${(0, import_core7.generateRandomId)(6)}`;
13381
+ let blockId = docPrName && !docPrName.startsWith("Picture_") && !docPrName.startsWith("Picture ") ? unescapeXml(docPrName) : `img_${(0, import_core7.generateRandomId)(6)}`;
13382
+ if (collectedDrawings[blockId]) {
13383
+ blockId = `${blockId}_${(0, import_core7.generateRandomId)(4)}`;
13384
+ }
12894
13385
  const extMatch = chunk.match(/<wp:extent\s[^>]*cx="(\d+)"[^>]*cy="(\d+)"/);
12895
13386
  const wPt = extMatch ? Math.round(Number(extMatch[1]) / 12700 * 100) / 100 : 140;
12896
13387
  const hPt = extMatch ? Math.round(Number(extMatch[2]) / 12700 * 100) / 100 : 90;
@@ -12922,29 +13413,41 @@ function extractDrawingFromXmlChunk(chunk, relsMap, entries, collectedDrawings,
12922
13413
  let posOffsetVPt = 0;
12923
13414
  let relFromHStr = "column";
12924
13415
  let relFromVStr = "paragraph";
13416
+ let alignHCode;
13417
+ let alignVCode;
12925
13418
  let behindDocBool = false;
12926
13419
  let wrapTextStr = "bothSides";
12927
- let layoutType = 0;
13420
+ let layoutType = import_core7.PositionedObjectLayoutType.INLINE;
12928
13421
  if (isAnchor) {
12929
13422
  behindDocBool = /\bbehindDoc="(?:1|true)"/.test(containerTag);
12930
13423
  parsedTransform.behindDoc = behindDocBool;
12931
- const posHMatch = chunk.match(
12932
- /<wp:positionH\b([^>]*)>[\s\S]*?(?:<wp:posOffset>(-?\d+)<\/wp:posOffset>)?[\s\S]*?<\/wp:positionH>/
12933
- );
13424
+ const posHMatch = chunk.match(/<wp:positionH\b([^>]*)>([\s\S]*?)<\/wp:positionH>/);
12934
13425
  if (posHMatch) {
12935
13426
  relFromHStr = posHMatch[1]?.match(/\brelativeFrom="([^"]+)"/)?.[1] || "column";
12936
- posOffsetHPt = posHMatch[2] ? Math.round(Number(posHMatch[2]) / 12700 * 100) / 100 : 0;
12937
13427
  parsedTransform.relativeFromH = relFromHStr;
12938
- parsedTransform.posOffsetH = posOffsetHPt;
13428
+ const alignHRaw = posHMatch[2]?.match(/<wp:align>\s*([^<\s]+)\s*<\/wp:align>/)?.[1];
13429
+ const offsetHEmu = posHMatch[2]?.match(/<wp:posOffset>\s*(-?\d+)\s*<\/wp:posOffset>/)?.[1];
13430
+ if (alignHRaw && OOXML_ALIGN_H_TO_CODE[alignHRaw] !== void 0) {
13431
+ alignHCode = OOXML_ALIGN_H_TO_CODE[alignHRaw];
13432
+ parsedTransform.alignH = alignHRaw;
13433
+ } else {
13434
+ posOffsetHPt = offsetHEmu ? Math.round(Number(offsetHEmu) / 12700 * 100) / 100 : 0;
13435
+ parsedTransform.posOffsetH = posOffsetHPt;
13436
+ }
12939
13437
  }
12940
- const posVMatch = chunk.match(
12941
- /<wp:positionV\b([^>]*)>[\s\S]*?(?:<wp:posOffset>(-?\d+)<\/wp:posOffset>)?[\s\S]*?<\/wp:positionV>/
12942
- );
13438
+ const posVMatch = chunk.match(/<wp:positionV\b([^>]*)>([\s\S]*?)<\/wp:positionV>/);
12943
13439
  if (posVMatch) {
12944
13440
  relFromVStr = posVMatch[1]?.match(/\brelativeFrom="([^"]+)"/)?.[1] || "paragraph";
12945
- posOffsetVPt = posVMatch[2] ? Math.round(Number(posVMatch[2]) / 12700 * 100) / 100 : 0;
12946
13441
  parsedTransform.relativeFromV = relFromVStr;
12947
- parsedTransform.posOffsetV = posOffsetVPt;
13442
+ const alignVRaw = posVMatch[2]?.match(/<wp:align>\s*([^<\s]+)\s*<\/wp:align>/)?.[1];
13443
+ const offsetVEmu = posVMatch[2]?.match(/<wp:posOffset>\s*(-?\d+)\s*<\/wp:posOffset>/)?.[1];
13444
+ if (alignVRaw && OOXML_ALIGN_V_TO_CODE[alignVRaw] !== void 0) {
13445
+ alignVCode = OOXML_ALIGN_V_TO_CODE[alignVRaw];
13446
+ parsedTransform.alignV = alignVRaw;
13447
+ } else {
13448
+ posOffsetVPt = offsetVEmu ? Math.round(Number(offsetVEmu) / 12700 * 100) / 100 : 0;
13449
+ parsedTransform.posOffsetV = posOffsetVPt;
13450
+ }
12948
13451
  }
12949
13452
  const wrapTextAttr = chunk.match(/\bwrapText="([^"]+)"/)?.[1];
12950
13453
  if (wrapTextAttr === "bothSides" || wrapTextAttr === "left" || wrapTextAttr === "right" || wrapTextAttr === "largest") {
@@ -12953,25 +13456,37 @@ function extractDrawingFromXmlChunk(chunk, relsMap, entries, collectedDrawings,
12953
13456
  }
12954
13457
  if (/<wp:wrapSquare[\s/>]/.test(chunk)) {
12955
13458
  parsedTransform.wrapType = "square";
12956
- layoutType = 3;
13459
+ layoutType = import_core7.PositionedObjectLayoutType.WRAP_SQUARE;
12957
13460
  } else if (/<wp:wrapTopAndBottom[\s/>]/.test(chunk)) {
12958
13461
  parsedTransform.wrapType = "topAndBottom";
12959
- layoutType = 4;
13462
+ layoutType = import_core7.PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM;
12960
13463
  } else if (/<wp:wrapTight[\s/>]/.test(chunk)) {
12961
13464
  parsedTransform.wrapType = "tight";
12962
- layoutType = 3;
13465
+ layoutType = import_core7.PositionedObjectLayoutType.WRAP_TIGHT;
13466
+ } else if (/<wp:wrapThrough[\s/>]/.test(chunk)) {
13467
+ parsedTransform.wrapType = "through";
13468
+ layoutType = import_core7.PositionedObjectLayoutType.WRAP_THROUGH;
13469
+ } else if (/<wp:wrapPolygon[\s/>]/.test(chunk)) {
13470
+ parsedTransform.wrapType = "polygon";
13471
+ layoutType = import_core7.PositionedObjectLayoutType.WRAP_POLYGON;
13472
+ } else if (/<wp:wrapNone[\s/>]/.test(chunk)) {
13473
+ parsedTransform.wrapType = behindDocBool ? "behindText" : "inFrontOfText";
13474
+ layoutType = import_core7.PositionedObjectLayoutType.WRAP_NONE;
12963
13475
  } else if (behindDocBool) {
12964
13476
  parsedTransform.wrapType = "behindText";
12965
- layoutType = 2;
13477
+ layoutType = import_core7.PositionedObjectLayoutType.WRAP_NONE;
12966
13478
  } else {
12967
13479
  parsedTransform.wrapType = "inFrontOfText";
12968
- layoutType = 1;
13480
+ layoutType = import_core7.PositionedObjectLayoutType.WRAP_NONE;
12969
13481
  }
12970
13482
  } else if (Object.keys(parsedTransform).length > 0) {
12971
13483
  parsedTransform.wrapType = "inline";
12972
13484
  }
12973
- const relHCode = relFromHStr === "page" ? 1 : relFromHStr === "margin" ? 2 : 0;
12974
- const relVCode = relFromVStr === "page" ? 1 : relFromVStr === "line" ? 2 : 0;
13485
+ const relHCode = OOXML_REL_H_TO_CODE[relFromHStr] ?? import_core7.ObjectRelativeFromH.COLUMN;
13486
+ const relVCode = OOXML_REL_V_TO_CODE[relFromVStr] ?? import_core7.ObjectRelativeFromV.PARAGRAPH;
13487
+ const wrapTextCode = OOXML_WRAP_TEXT_TO_CODE[wrapTextStr] ?? import_core7.WrapTextType.BOTH_SIDES;
13488
+ const positionH = alignHCode !== void 0 ? { relativeFrom: relHCode, align: alignHCode } : { relativeFrom: relHCode, posOffset: posOffsetHPt };
13489
+ const positionV = alignVCode !== void 0 ? { relativeFrom: relVCode, align: alignVCode } : { relativeFrom: relVCode, posOffset: posOffsetVPt };
12975
13490
  const dataUri = `data:${mime};base64,${uint8ToBase64(imgBytes)}`;
12976
13491
  collectedDrawings[blockId] = {
12977
13492
  unitId: docUnitId,
@@ -12983,8 +13498,8 @@ function extractDrawingFromXmlChunk(chunk, relsMap, entries, collectedDrawings,
12983
13498
  title: "",
12984
13499
  description: "",
12985
13500
  layoutType,
12986
- behindDoc: behindDocBool ? 1 : 0,
12987
- wrapText: wrapTextStr,
13501
+ behindDoc: behindDocBool ? import_core7.BooleanNumber.TRUE : import_core7.BooleanNumber.FALSE,
13502
+ wrapText: wrapTextCode,
12988
13503
  distT: distTPt,
12989
13504
  distB: distBPt,
12990
13505
  distL: distLPt,
@@ -13002,17 +13517,246 @@ function extractDrawingFromXmlChunk(chunk, relsMap, entries, collectedDrawings,
13002
13517
  },
13003
13518
  docTransform: {
13004
13519
  size: { width: wPt, height: hPt },
13005
- positionH: { relativeFrom: relHCode, posOffset: posOffsetHPt },
13006
- positionV: { relativeFrom: relVCode, posOffset: posOffsetVPt },
13007
- angle: rotDeg
13520
+ positionH,
13521
+ positionV,
13522
+ angle: rotDeg,
13523
+ wrapText: wrapTextCode
13008
13524
  },
13009
13525
  ...Object.keys(parsedTransform).length > 0 ? { yudaoTransform: parsedTransform } : {}
13010
13526
  };
13011
13527
  inlineBlocksQueue.push({ blockId });
13012
13528
  return { blockId, dataUri };
13013
13529
  }
13530
+ function applyParagraphSpacingAndIndentFromPrXml(pPrXml, pStyle, includeIndentation = true) {
13531
+ if (!pPrXml) return;
13532
+ const spacingMatch = pPrXml.match(/<w:spacing\b([^>]*)\/?>/);
13533
+ if (spacingMatch) {
13534
+ const spAttrs = spacingMatch[1] || "";
13535
+ const beforeVal = spAttrs.match(/\bw:before="(-?\d+)"/)?.[1];
13536
+ if (beforeVal !== void 0) {
13537
+ pStyle.spaceAbove = {
13538
+ v: dxaToPt(Math.max(0, Number(beforeVal))),
13539
+ u: import_core7.NumberUnitType.POINT
13540
+ };
13541
+ }
13542
+ const beforeAutoVal = spAttrs.match(/\bw:beforeAutospacing="([^"]+)"/)?.[1];
13543
+ if (beforeAutoVal !== void 0) {
13544
+ const autoOn = /^(?:1|true|on)$/i.test(beforeAutoVal);
13545
+ pStyle.beforeAutoSpacing = autoOn ? import_core7.BooleanNumber.TRUE : import_core7.BooleanNumber.FALSE;
13546
+ }
13547
+ const afterVal = spAttrs.match(/\bw:after="(-?\d+)"/)?.[1];
13548
+ if (afterVal !== void 0) {
13549
+ pStyle.spaceBelow = {
13550
+ v: dxaToPt(Math.max(0, Number(afterVal))),
13551
+ u: import_core7.NumberUnitType.POINT
13552
+ };
13553
+ }
13554
+ const afterAutoVal = spAttrs.match(/\bw:afterAutospacing="([^"]+)"/)?.[1];
13555
+ if (afterAutoVal !== void 0) {
13556
+ const autoOn = /^(?:1|true|on)$/i.test(afterAutoVal);
13557
+ pStyle.afterAutoSpacing = autoOn ? import_core7.BooleanNumber.TRUE : import_core7.BooleanNumber.FALSE;
13558
+ }
13559
+ const lineVal = spAttrs.match(/\bw:line="(-?\d+)"/)?.[1];
13560
+ if (lineVal !== void 0) {
13561
+ const rawLine = Number(lineVal);
13562
+ const rawRule = (spAttrs.match(/\bw:lineRule="([^"]+)"/)?.[1] || "").toLowerCase();
13563
+ if (rawRule === "exact" || rawLine < 0) {
13564
+ pStyle.lineSpacing = dxaToPt(Math.abs(rawLine));
13565
+ pStyle.spacingRule = import_core7.SpacingRule.EXACT;
13566
+ } else if (rawRule === "atleast") {
13567
+ pStyle.lineSpacing = dxaToPt(Math.abs(rawLine));
13568
+ pStyle.spacingRule = import_core7.SpacingRule.AT_LEAST;
13569
+ } else if (rawLine > 0) {
13570
+ pStyle.lineSpacing = Math.round(rawLine / 240 * 1e4) / 1e4;
13571
+ pStyle.spacingRule = import_core7.SpacingRule.AUTO;
13572
+ }
13573
+ }
13574
+ }
13575
+ const ctxSpMatch = pPrXml.match(/<w:contextualSpacing\b([^>]*)\/?>/);
13576
+ if (ctxSpMatch) {
13577
+ const off = /\bw:val="(?:0|false|off)"/i.test(ctxSpMatch[1] || "");
13578
+ pStyle.contextualSpacing = off ? import_core7.BooleanNumber.FALSE : import_core7.BooleanNumber.TRUE;
13579
+ }
13580
+ const snapMatch = pPrXml.match(/<w:snapToGrid\b([^>]*)\/?>/);
13581
+ if (snapMatch) {
13582
+ const off = /\bw:val="(?:0|false|off)"/i.test(snapMatch[1] || "");
13583
+ pStyle.snapToGrid = off ? import_core7.BooleanNumber.FALSE : import_core7.BooleanNumber.TRUE;
13584
+ }
13585
+ if (includeIndentation) {
13586
+ const indMatch = pPrXml.match(/<w:ind\b([^>]*)\/?>/);
13587
+ if (indMatch) {
13588
+ const indAttrs = indMatch[1] || "";
13589
+ const leftRaw = indAttrs.match(/\bw:left="(-?\d+)"/)?.[1] ?? indAttrs.match(/\bw:start="(-?\d+)"/)?.[1];
13590
+ const rightRaw = indAttrs.match(/\bw:right="(-?\d+)"/)?.[1] ?? indAttrs.match(/\bw:end="(-?\d+)"/)?.[1];
13591
+ const hangingRaw = indAttrs.match(/\bw:hanging="(\d+)"/)?.[1];
13592
+ const firstCharsRaw = indAttrs.match(/\bw:firstLineChars="(\d+)"/)?.[1];
13593
+ const firstLineRaw = indAttrs.match(/\bw:firstLine="(\d+)"/)?.[1];
13594
+ if (leftRaw !== void 0) {
13595
+ pStyle.indentStart = {
13596
+ v: dxaToPt(Math.max(0, Number(leftRaw))),
13597
+ u: import_core7.NumberUnitType.POINT
13598
+ };
13599
+ }
13600
+ if (rightRaw !== void 0) {
13601
+ pStyle.indentEnd = {
13602
+ v: dxaToPt(Math.max(0, Number(rightRaw))),
13603
+ u: import_core7.NumberUnitType.POINT
13604
+ };
13605
+ }
13606
+ if (hangingRaw !== void 0 && Number(hangingRaw) > 0) {
13607
+ pStyle.hanging = {
13608
+ v: dxaToPt(Number(hangingRaw)),
13609
+ u: import_core7.NumberUnitType.POINT
13610
+ };
13611
+ } else if (firstCharsRaw !== void 0 && Number(firstCharsRaw) > 0) {
13612
+ pStyle.indentFirstLine = {
13613
+ v: Math.round(Number(firstCharsRaw) / 100 * 100) / 100,
13614
+ u: import_core7.NumberUnitType.CHARACTER
13615
+ };
13616
+ } else if (firstLineRaw !== void 0) {
13617
+ pStyle.indentFirstLine = {
13618
+ v: dxaToPt(Number(firstLineRaw)),
13619
+ u: import_core7.NumberUnitType.POINT
13620
+ };
13621
+ }
13622
+ }
13623
+ }
13624
+ }
13625
+ function parseStyleParagraphPropsFromPrXml(pPrXml) {
13626
+ if (!pPrXml) return void 0;
13627
+ const pStyle = {};
13628
+ const jcMatch = pPrXml.match(/<w:jc\s[^>]*w:val="([^"]+)"/);
13629
+ if (jcMatch) {
13630
+ if (jcMatch[1] === "center") pStyle.horizontalAlign = 2;
13631
+ else if (jcMatch[1] === "right") pStyle.horizontalAlign = 3;
13632
+ else if (jcMatch[1] === "both" || jcMatch[1] === "distribute") pStyle.horizontalAlign = 4;
13633
+ }
13634
+ const outLvl = pPrXml.match(/<w:outlineLvl\s[^>]*w:val="([0-5])"/)?.[1];
13635
+ if (outLvl !== void 0) {
13636
+ pStyle.namedStyleType = Number(outLvl) + 1;
13637
+ }
13638
+ if (/<w:keepLines(?:\s|\/|>)/.test(pPrXml) && !/<w:keepLines\s[^>]*w:val="(?:0|false)"/.test(pPrXml)) {
13639
+ pStyle.keepLines = 1;
13640
+ }
13641
+ if (/<w:keepNext(?:\s|\/|>)/.test(pPrXml) && !/<w:keepNext\s[^>]*w:val="(?:0|false)"/.test(pPrXml)) {
13642
+ pStyle.keepNext = 1;
13643
+ }
13644
+ if (/<w:pageBreakBefore(?:\s|\/|>)/.test(pPrXml) && !/<w:pageBreakBefore\s[^>]*w:val="(?:0|false)"/.test(pPrXml)) {
13645
+ pStyle.pageBreakBefore = 1;
13646
+ }
13647
+ if (/<w:widowControl(?:\s|\/|>)/.test(pPrXml)) {
13648
+ const wcOff = /<w:widowControl\s[^>]*w:val="(?:0|false)"/.test(pPrXml);
13649
+ pStyle.widowControl = wcOff ? 0 : 1;
13650
+ }
13651
+ applyParagraphSpacingAndIndentFromPrXml(pPrXml, pStyle, true);
13652
+ return Object.keys(pStyle).length > 0 ? pStyle : void 0;
13653
+ }
13654
+ function parseStylesXmlIntoDoc(stylesXml, themeFonts, docData) {
13655
+ const docDefaultsXml = stylesXml.match(/<w:docDefaults[\s>][\s\S]*?<\/w:docDefaults>/)?.[0] || "";
13656
+ const rPrDefXml = docDefaultsXml.match(/<w:rPrDefault[\s>][\s\S]*?<\/w:rPrDefault>/)?.[0] || "";
13657
+ const pPrDefXml = docDefaultsXml.match(/<w:pPrDefault[\s>][\s\S]*?<\/w:pPrDefault>/)?.[0] || "";
13658
+ const docDefaultTextStyle = rPrDefXml ? parseRunStyleFromXml(rPrDefXml, themeFonts) : void 0;
13659
+ const docDefaultParaPPr = pPrDefXml.match(/<w:pPr[\s>][\s\S]*?<\/w:pPr>/)?.[0] || "";
13660
+ const docDefaultParaStyle = parseStyleParagraphPropsFromPrXml(docDefaultParaPPr);
13661
+ const rawStyles = /* @__PURE__ */ new Map();
13662
+ let defaultParaStyleId;
13663
+ for (const sm of stylesXml.matchAll(/<w:style\b([^>]*)>([\s\S]*?)<\/w:style>/g)) {
13664
+ const attrs = sm[1] || "";
13665
+ const inner = sm[2] || "";
13666
+ const styleId = unescapeXml(attrs.match(/\bw:styleId="([^"]+)"/)?.[1] || "");
13667
+ if (!styleId) continue;
13668
+ const wType = (attrs.match(/\bw:type="([^"]+)"/)?.[1] || "paragraph").toLowerCase();
13669
+ const type = wType === "character" ? import_core7.DocStyleType.character : wType === "table" ? import_core7.DocStyleType.table : wType === "numbering" ? import_core7.DocStyleType.numbering : import_core7.DocStyleType.paragraph;
13670
+ const isDefault = /\bw:default="(?:1|true|on)"/i.test(attrs);
13671
+ const customStyle = /\bw:customStyle="(?:1|true|on)"/i.test(attrs);
13672
+ const name = unescapeXml(inner.match(/<w:name\b[^>]*\bw:val="([^"]+)"/)?.[1] || styleId);
13673
+ const basedOnRaw = inner.match(/<w:basedOn\b[^>]*\bw:val="([^"]+)"/)?.[1];
13674
+ const basedOn = basedOnRaw ? unescapeXml(basedOnRaw) : void 0;
13675
+ const linkRaw = inner.match(/<w:link\b[^>]*\bw:val="([^"]+)"/)?.[1];
13676
+ const link = linkRaw ? unescapeXml(linkRaw) : void 0;
13677
+ const strippedTblStylePr = inner.replace(/<w:tblStylePr[\s>][\s\S]*?<\/w:tblStylePr>/g, "");
13678
+ const stylePPrXml = strippedTblStylePr.match(/<w:pPr[\s>][\s\S]*?<\/w:pPr>/)?.[0] || "";
13679
+ const withoutPPr = stylePPrXml ? strippedTblStylePr.replace(stylePPrXml, "") : strippedTblStylePr;
13680
+ const styleRPrXml = withoutPPr.match(/<w:rPr[\s>][\s\S]*?<\/w:rPr>/)?.[0] || "";
13681
+ const paragraphStyle = parseStyleParagraphPropsFromPrXml(stylePPrXml);
13682
+ const textStyle = styleRPrXml ? parseRunStyleFromXml(styleRPrXml, themeFonts) : void 0;
13683
+ if (wType === "paragraph" && isDefault && !defaultParaStyleId) {
13684
+ defaultParaStyleId = styleId;
13685
+ }
13686
+ rawStyles.set(styleId, {
13687
+ styleId,
13688
+ name,
13689
+ type,
13690
+ wType,
13691
+ isDefault,
13692
+ ...customStyle ? { customStyle: true } : {},
13693
+ ...basedOn ? { basedOn } : {},
13694
+ ...link ? { link } : {},
13695
+ ...paragraphStyle ? { paragraphStyle } : {},
13696
+ ...textStyle ? { textStyle } : {}
13697
+ });
13698
+ }
13699
+ if (!defaultParaStyleId) {
13700
+ if (rawStyles.has("Normal")) {
13701
+ defaultParaStyleId = "Normal";
13702
+ } else {
13703
+ for (const [sId, st] of rawStyles.entries()) {
13704
+ if (st.wType === "paragraph" && st.name.toLowerCase() === "normal") {
13705
+ defaultParaStyleId = sId;
13706
+ break;
13707
+ }
13708
+ }
13709
+ }
13710
+ }
13711
+ const resolvedCache = /* @__PURE__ */ new Map();
13712
+ const resolveStyleChain = (sId, visited = /* @__PURE__ */ new Set()) => {
13713
+ if (resolvedCache.has(sId)) return resolvedCache.get(sId);
13714
+ const item = rawStyles.get(sId);
13715
+ if (!item || visited.has(sId)) return {};
13716
+ visited.add(sId);
13717
+ const parent = item.basedOn && item.basedOn !== sId ? resolveStyleChain(item.basedOn, visited) : {};
13718
+ const mergedP = parent.paragraphStyle || item.paragraphStyle ? { ...parent.paragraphStyle ?? {}, ...item.paragraphStyle ?? {} } : void 0;
13719
+ const mergedT = mergeDocTextStyles(parent.textStyle, item.textStyle);
13720
+ const out = {
13721
+ ...mergedP ? { paragraphStyle: mergedP } : {},
13722
+ ...mergedT ? { textStyle: mergedT } : {}
13723
+ };
13724
+ resolvedCache.set(sId, out);
13725
+ return out;
13726
+ };
13727
+ const docStylesOut = {};
13728
+ for (const [sId, item] of rawStyles.entries()) {
13729
+ if (item.wType === "table" && !item.paragraphStyle && !item.textStyle) continue;
13730
+ const resolved = resolveStyleChain(sId);
13731
+ docStylesOut[sId] = {
13732
+ name: item.name,
13733
+ type: item.type,
13734
+ ...item.customStyle ? { customStyle: true } : {},
13735
+ ...item.basedOn ? { basedOn: item.basedOn } : {},
13736
+ ...item.link ? { link: item.link } : {},
13737
+ ...resolved.paragraphStyle ? { paragraphStyle: resolved.paragraphStyle } : {},
13738
+ ...resolved.textStyle ? { textStyle: resolved.textStyle } : {}
13739
+ };
13740
+ }
13741
+ if (Object.keys(docStylesOut).length > 0) {
13742
+ docData.styles = docStylesOut;
13743
+ }
13744
+ const normalResolved = defaultParaStyleId ? resolveStyleChain(defaultParaStyleId) : {};
13745
+ const effectiveDocTextStyle = mergeDocTextStyles(docDefaultTextStyle, normalResolved.textStyle);
13746
+ if (effectiveDocTextStyle && docData.documentStyle) {
13747
+ docData.documentStyle.textStyle = effectiveDocTextStyle;
13748
+ }
13749
+ const effectiveDocParaStyle = docDefaultParaStyle || normalResolved.paragraphStyle ? { ...docDefaultParaStyle ?? {}, ...normalResolved.paragraphStyle ?? {} } : void 0;
13750
+ if (effectiveDocParaStyle && Object.keys(effectiveDocParaStyle).length > 0 && docData.documentStyle) {
13751
+ docData.documentStyle.defaultParagraphStyle = effectiveDocParaStyle;
13752
+ }
13753
+ if (defaultParaStyleId && docData.documentStyle) {
13754
+ docData.documentStyle.defaultParagraphStyleId = defaultParaStyleId;
13755
+ }
13756
+ }
13014
13757
  function parseParagraphXmlToBuilder(pXml, relsMap, entries, collectedDrawings, inlineBlocksQueue, warningsCounter, numCtx) {
13015
13758
  const docUnitId = numCtx?.docUnitId || "doc-imported";
13759
+ const themeFonts = numCtx?.themeFonts;
13016
13760
  const pStyle = {};
13017
13761
  let parsedBullet;
13018
13762
  const pPrXml = pXml.match(/<w:pPr[\s>][\s\S]*?<\/w:pPr>/)?.[0] || "";
@@ -13021,9 +13765,10 @@ function parseParagraphXmlToBuilder(pXml, relsMap, entries, collectedDrawings, i
13021
13765
  if (jcMatch) {
13022
13766
  if (jcMatch[1] === "center") pStyle.horizontalAlign = 2;
13023
13767
  else if (jcMatch[1] === "right") pStyle.horizontalAlign = 3;
13024
- else if (jcMatch[1] === "both") pStyle.horizontalAlign = 4;
13768
+ else if (jcMatch[1] === "both" || jcMatch[1] === "distribute") pStyle.horizontalAlign = 4;
13025
13769
  }
13026
- const pStyleVal = pPrXml.match(/<w:pStyle\s[^>]*w:val="([^"]+)"/)?.[1] || "";
13770
+ const rawPStyleVal = pPrXml.match(/<w:pStyle\s[^>]*w:val="([^"]+)"/)?.[1] || "";
13771
+ const pStyleVal = rawPStyleVal ? unescapeXml(rawPStyleVal) : "";
13027
13772
  const hMatch = pStyleVal.match(/^(?:Heading|heading\s*)([1-6])$/i);
13028
13773
  if (hMatch) {
13029
13774
  pStyle.namedStyleType = Number(hMatch[1]);
@@ -13075,6 +13820,7 @@ function parseParagraphXmlToBuilder(pXml, relsMap, entries, collectedDrawings, i
13075
13820
  if (Object.keys(parsedPag).length > 0) {
13076
13821
  pStyle.yudaoPagination = parsedPag;
13077
13822
  }
13823
+ applyParagraphSpacingAndIndentFromPrXml(pPrXml, pStyle, false);
13078
13824
  const tabsXml = pPrXml.match(/<w:tabs[\s>][\s\S]*?<\/w:tabs>/)?.[0] || "";
13079
13825
  if (tabsXml) {
13080
13826
  const parsedTabs = [];
@@ -13121,7 +13867,131 @@ function parseParagraphXmlToBuilder(pXml, relsMap, entries, collectedDrawings, i
13121
13867
  const parseInlineSegments = (srcXml) => {
13122
13868
  const outSegs = [];
13123
13869
  const chunks = tokenizeParagraphInlineChunks(srcXml);
13870
+ let fieldDepth = 0;
13871
+ let fldInstrParts = [];
13872
+ let fldResultParts = [];
13873
+ let fldBeginStyle;
13874
+ let fldResultStyle;
13875
+ let fldHasSeparate = false;
13876
+ const finalizeComplexField = () => {
13877
+ const instrRaw = fldInstrParts.join("").trim();
13878
+ const resultText = fldResultParts.join("");
13879
+ const effStyle = fldResultStyle ?? fldBeginStyle;
13880
+ if (!instrRaw) {
13881
+ if (resultText) {
13882
+ outSegs.push(effStyle ? { text: resultText, style: effStyle } : resultText);
13883
+ }
13884
+ return;
13885
+ }
13886
+ const upperFirstTok = (instrRaw.split(/\s+/)[0] || "").toUpperCase();
13887
+ const isDynamicPageField = upperFirstTok === "PAGE" || upperFirstTok === "NUMPAGES" || upperFirstTok === "SECTIONPAGES";
13888
+ const supportedStaticComplex = /* @__PURE__ */ new Set([
13889
+ "DATE",
13890
+ "TIME",
13891
+ "AUTHOR",
13892
+ "FILENAME",
13893
+ "TITLE",
13894
+ "COMPANY",
13895
+ "DOCPROPERTY"
13896
+ ]);
13897
+ const isPassthroughComplex = upperFirstTok === "TOC" || upperFirstTok === "HYPERLINK";
13898
+ if (isDynamicPageField || !supportedStaticComplex.has(upperFirstTok) && !isPassthroughComplex) {
13899
+ warningsCounter.dynamicFields = (warningsCounter.dynamicFields ?? 0) + 1;
13900
+ }
13901
+ if (isPassthroughComplex) {
13902
+ if (resultText) {
13903
+ outSegs.push(effStyle ? { text: resultText, style: effStyle } : resultText);
13904
+ }
13905
+ return;
13906
+ }
13907
+ const parsedInstr = parseFieldInstrString(instrRaw);
13908
+ const fallbackVal = resultText || (isDynamicPageField ? "1" : `{${upperFirstTok}}`);
13909
+ outSegs.push({
13910
+ docField: {
13911
+ fieldType: parsedInstr.fieldType,
13912
+ instructionArgs: parsedInstr.instructionArgs,
13913
+ instrText: instrRaw,
13914
+ value: fallbackVal,
13915
+ sourceKind: "complex",
13916
+ preserveStyle: true,
13917
+ ...effStyle ? { style: effStyle } : {}
13918
+ }
13919
+ });
13920
+ };
13124
13921
  for (const chunk of chunks) {
13922
+ if (chunk.startsWith("<w:r") && (fieldDepth > 0 || /<w:fldChar\b/.test(chunk))) {
13923
+ const runStyle = parseRunStyleFromXml(chunk, themeFonts);
13924
+ const tokenRe = /<w:fldChar\b([^>]*)\/?>|<w:instrText(?=[\s>])[^>]*>([\s\S]*?)<\/w:instrText>|<w:t(?=[\s>])[^>]*>([\s\S]*?)<\/w:t>|<w:tab(?:\s|\/|>)|<w:br\s[^>]*w:type="page"/g;
13925
+ let tm;
13926
+ while ((tm = tokenRe.exec(chunk)) !== null) {
13927
+ const fullTok = tm[0];
13928
+ if (fullTok.startsWith("<w:fldChar")) {
13929
+ const fcType = (tm[1]?.match(/\bw:fldCharType="([^"]+)"/)?.[1] || "").toLowerCase();
13930
+ if (fcType === "begin") {
13931
+ fieldDepth++;
13932
+ if (fieldDepth === 1) {
13933
+ fldInstrParts = [];
13934
+ fldResultParts = [];
13935
+ fldBeginStyle = runStyle;
13936
+ fldResultStyle = void 0;
13937
+ fldHasSeparate = false;
13938
+ }
13939
+ } else if (fcType === "separate") {
13940
+ if (fieldDepth === 1) {
13941
+ fldHasSeparate = true;
13942
+ }
13943
+ } else if (fcType === "end") {
13944
+ if (fieldDepth > 0) {
13945
+ fieldDepth--;
13946
+ if (fieldDepth === 0) {
13947
+ finalizeComplexField();
13948
+ }
13949
+ }
13950
+ }
13951
+ } else if (fullTok.startsWith("<w:instrText")) {
13952
+ if (fieldDepth === 1 && !fldHasSeparate) {
13953
+ fldInstrParts.push(unescapeXml(tm[2] || ""));
13954
+ }
13955
+ } else if (fullTok.startsWith("<w:t")) {
13956
+ const txt = unescapeXml(tm[3] || "");
13957
+ if (fieldDepth > 0) {
13958
+ if (fldHasSeparate) {
13959
+ const isTocInstr = fldInstrParts.join("").trim().toUpperCase().startsWith("TOC");
13960
+ if (isTocInstr) {
13961
+ if (txt) outSegs.push(runStyle ? { text: txt, style: runStyle } : txt);
13962
+ } else if (txt) {
13963
+ fldResultParts.push(txt);
13964
+ if (!fldResultStyle && runStyle) {
13965
+ fldResultStyle = runStyle;
13966
+ }
13967
+ }
13968
+ }
13969
+ } else if (txt) {
13970
+ outSegs.push(runStyle ? { text: txt, style: runStyle } : txt);
13971
+ }
13972
+ } else if (fullTok.startsWith("<w:tab")) {
13973
+ if (fieldDepth === 0 || fldHasSeparate && fldInstrParts.join("").trim().toUpperCase().startsWith("TOC")) {
13974
+ outSegs.push({ tab: true });
13975
+ }
13976
+ } else if (fullTok.startsWith("<w:br")) {
13977
+ if (fieldDepth === 0) {
13978
+ outSegs.push({ pageBreak: true });
13979
+ }
13980
+ }
13981
+ }
13982
+ continue;
13983
+ }
13984
+ if (fieldDepth > 0 && !fldInstrParts.join("").trim().toUpperCase().startsWith("TOC")) {
13985
+ if (fldHasSeparate) {
13986
+ const innerTexts = Array.from(
13987
+ chunk.matchAll(/<w:t(?=[\s>])[^>]*>([\s\S]*?)<\/w:t>/g)
13988
+ ).map((m) => unescapeXml(m[1]));
13989
+ if (innerTexts.length > 0) {
13990
+ fldResultParts.push(innerTexts.join(""));
13991
+ }
13992
+ }
13993
+ continue;
13994
+ }
13125
13995
  if (chunk.startsWith("<w:bookmarkStart")) {
13126
13996
  const bmId = chunk.match(/w:id="([^"]*)"/)?.[1] || "";
13127
13997
  const bmName = unescapeXml(chunk.match(/w:name="([^"]*)"/)?.[1] || "");
@@ -13201,16 +14071,24 @@ function parseParagraphXmlToBuilder(pXml, relsMap, entries, collectedDrawings, i
13201
14071
  }
13202
14072
  if (chunk.startsWith("<w:fldSimple")) {
13203
14073
  const instrRaw = unescapeXml(chunk.match(/w:instr="([^"]*)"/)?.[1] || "PAGE").trim();
14074
+ const upperFirst = (instrRaw.split(/\s+/)[0] || "").toUpperCase();
14075
+ if (upperFirst === "PAGE" || upperFirst === "NUMPAGES" || upperFirst === "SECTIONPAGES") {
14076
+ warningsCounter.dynamicFields = (warningsCounter.dynamicFields ?? 0) + 1;
14077
+ }
13204
14078
  const parsedInstr = parseFieldInstrString(instrRaw);
13205
14079
  const fldTexts = Array.from(chunk.matchAll(/<w:t(?=[\s>])[^>]*>([\s\S]*?)<\/w:t>/g)).map(
13206
14080
  (m) => unescapeXml(m[1])
13207
14081
  );
14082
+ const firstFldRun = chunk.match(/<w:r[\s>][\s\S]*?<\/w:r>/)?.[0];
14083
+ const fldStyle = firstFldRun ? parseRunStyleFromXml(firstFldRun, themeFonts) : void 0;
13208
14084
  outSegs.push({
13209
14085
  docField: {
13210
14086
  fieldType: parsedInstr.fieldType,
13211
14087
  instructionArgs: parsedInstr.instructionArgs,
13212
14088
  instrText: instrRaw,
13213
- value: fldTexts.join("") || "1"
14089
+ value: fldTexts.join("") || "1",
14090
+ sourceKind: "simple",
14091
+ ...fldStyle ? { preserveStyle: true, style: fldStyle } : {}
13214
14092
  }
13215
14093
  });
13216
14094
  continue;
@@ -13220,7 +14098,7 @@ function parseParagraphXmlToBuilder(pXml, relsMap, entries, collectedDrawings, i
13220
14098
  const cStartMatch = chunk.match(/<w:sdtContent(?=[\s>])[^>]*>/);
13221
14099
  const cEndIdx = chunk.lastIndexOf("</w:sdtContent>");
13222
14100
  const sdtContentXml = cStartMatch && cEndIdx > (cStartMatch.index ?? 0) ? chunk.slice((cStartMatch.index ?? 0) + cStartMatch[0].length, cEndIdx) : "";
13223
- const sdtPrStyle = parseRunStyleFromXml(sdtPrXml);
14101
+ const sdtPrStyle = parseRunStyleFromXml(sdtPrXml, themeFonts);
13224
14102
  const aliasMatch = sdtPrXml.match(/<w:alias[^>]*w:val="([^"]*)"/);
13225
14103
  const tagMatch = sdtPrXml.match(/<w:tag[^>]*w:val="([^"]*)"/);
13226
14104
  const lockMatch = sdtPrXml.match(/<w:lock[^>]*w:val="([^"]*)"/);
@@ -13407,10 +14285,14 @@ function parseParagraphXmlToBuilder(pXml, relsMap, entries, collectedDrawings, i
13407
14285
  );
13408
14286
  const plain = textMatches.join("");
13409
14287
  if (plain) {
13410
- const style = parseRunStyleFromXml(chunk);
14288
+ const style = parseRunStyleFromXml(chunk, themeFonts);
13411
14289
  outSegs.push(style ? { text: plain, style } : plain);
13412
14290
  }
13413
14291
  }
14292
+ if (fieldDepth > 0) {
14293
+ fieldDepth = 0;
14294
+ finalizeComplexField();
14295
+ }
13414
14296
  return outSegs;
13415
14297
  };
13416
14298
  const pBodyOnly = pPrXml ? pXml.replace(pPrXml, "") : pXml;
@@ -13452,6 +14334,9 @@ function parseParagraphXmlToBuilder(pXml, relsMap, entries, collectedDrawings, i
13452
14334
  };
13453
14335
  }
13454
14336
  }
14337
+ if (!detectedQuote) {
14338
+ applyParagraphSpacingAndIndentFromPrXml(pPrXml, pStyle, true);
14339
+ }
13455
14340
  if (!detectedCallout && !detectedQuote) {
13456
14341
  const shdFillOnly = pPrXml.match(/<w:shd\b[^>]*w:fill="([0-9a-fA-F]{6})"/);
13457
14342
  if (pBdrXml || shdFillOnly) {
@@ -13494,6 +14379,7 @@ function parseParagraphXmlToBuilder(pXml, relsMap, entries, collectedDrawings, i
13494
14379
  return {
13495
14380
  kind: "paragraph",
13496
14381
  segments: segments.length > 0 ? segments : [""],
14382
+ ...pStyleVal ? { styleId: pStyleVal } : {},
13497
14383
  ...Object.keys(pStyle).length > 0 ? { paragraphStyle: pStyle } : {},
13498
14384
  ...parsedBullet ? { bullet: parsedBullet } : {},
13499
14385
  ...detectedCallout ? { callout: detectedCallout } : {},
@@ -13549,7 +14435,53 @@ function tokenizeBodyTopLevelBlocks(bodyXml) {
13549
14435
  }
13550
14436
  return blocks;
13551
14437
  }
13552
- function scanUnsupportedDocxFeatures(xml, floatingImages) {
14438
+ function tokenizeNestedTagBlocks(xml, tagName) {
14439
+ const out = [];
14440
+ const tagRe = new RegExp(`<\\/?w:${tagName}(?=[\\s/>])[^>]*>`, "g");
14441
+ let depth = 0;
14442
+ let startIdx = -1;
14443
+ let m;
14444
+ while ((m = tagRe.exec(xml)) !== null) {
14445
+ const full = m[0];
14446
+ const isClose = full.startsWith("</");
14447
+ const isSelfClose = full.endsWith("/>");
14448
+ if (depth === 0) {
14449
+ if (!isClose) {
14450
+ if (isSelfClose) {
14451
+ out.push(full);
14452
+ } else {
14453
+ depth = 1;
14454
+ startIdx = m.index;
14455
+ }
14456
+ }
14457
+ continue;
14458
+ }
14459
+ if (isSelfClose) continue;
14460
+ depth += isClose ? -1 : 1;
14461
+ if (depth === 0 && startIdx >= 0) {
14462
+ out.push(xml.slice(startIdx, m.index + full.length));
14463
+ startIdx = -1;
14464
+ }
14465
+ }
14466
+ return out;
14467
+ }
14468
+ function unwrapCellParagraphBlocks(xml) {
14469
+ const out = [];
14470
+ for (const blk of tokenizeBodyTopLevelBlocks(xml)) {
14471
+ if (blk.tag === "p") {
14472
+ out.push(blk.xml);
14473
+ } else if (blk.tag === "sdt") {
14474
+ const cStart = blk.xml.match(/<w:sdtContent(?=[\s>])[^>]*>/);
14475
+ const cEnd = blk.xml.lastIndexOf("</w:sdtContent>");
14476
+ const inner = cStart && cEnd > (cStart.index ?? 0) ? blk.xml.slice((cStart.index ?? 0) + cStart[0].length, cEnd) : "";
14477
+ if (inner) {
14478
+ out.push(...unwrapCellParagraphBlocks(inner));
14479
+ }
14480
+ }
14481
+ }
14482
+ return out;
14483
+ }
14484
+ function scanUnsupportedDocxFeatures(xml, floatingImages, dynamicFields = 0) {
13553
14485
  const warnings = [];
13554
14486
  const check = (re, code, label) => {
13555
14487
  const matches = xml.match(re);
@@ -13580,6 +14512,13 @@ function scanUnsupportedDocxFeatures(xml, floatingImages) {
13580
14512
  message: `${floatingImages} \u5F20\u6D6E\u52A8\u951A\u5B9A\u56FE\u7247\u5DF2\u81EA\u52A8\u964D\u7EA7\u4E3A\u884C\u5185\u5D4C\u5165\u56FE\u7247`
13581
14513
  });
13582
14514
  }
14515
+ if (dynamicFields > 0) {
14516
+ warnings.push({
14517
+ code: "UNSUPPORTED_FIELD",
14518
+ count: dynamicFields,
14519
+ message: "\u68C0\u6D4B\u5230\u52A8\u6001\u9875\u7801/\u6587\u6863\u57DF\uFF08\u5982 PAGE / NUMPAGES\uFF09\uFF0C\u6D4F\u89C8\u5668\u753B\u5E03\u9884\u89C8\u5C06\u663E\u793A\u7F13\u5B58\u9759\u6001\u6587\u672C\uFF0C\u5BFC\u51FA DOCX \u65F6\u4FDD\u7559\u52A8\u6001\u57DF\u6307\u4EE4"
14520
+ });
14521
+ }
13583
14522
  return warnings;
13584
14523
  }
13585
14524
  async function parseDocxBytesWithReport(bytes, title = "Imported Word Document") {
@@ -13708,25 +14647,25 @@ async function parseDocxBytesWithReport(bytes, title = "Imported Word Document")
13708
14647
  });
13709
14648
  }
13710
14649
  }
14650
+ const themeBytes = entries.get("word/theme/theme1.xml");
14651
+ const themeFonts = themeBytes ? parseThemeFontsFromXml(decoder.decode(themeBytes)) : void 0;
13711
14652
  const numCtx = {
13712
14653
  numIdToInfo,
13713
14654
  docUnitId,
13714
14655
  commentsMap,
13715
- openedCommentIds: /* @__PURE__ */ new Set()
14656
+ openedCommentIds: /* @__PURE__ */ new Set(),
14657
+ themeFonts
13716
14658
  };
13717
14659
  const bodyInnerMatch = xml.match(/<w:body[\s>]([\s\S]*?)<\/w:body>/);
13718
14660
  const bodyXml = bodyInnerMatch ? bodyInnerMatch[1] : xml;
13719
- const rawBlocks = tokenizeBodyTopLevelBlocks(bodyXml);
13720
14661
  const collectedDrawings = {};
13721
14662
  const inlineBlocksQueue = [];
13722
- const warningsCounter = { floatingImages: 0 };
13723
- const builderBlocks = [];
14663
+ const warningsCounter = { floatingImages: 0, dynamicFields: 0 };
13724
14664
  const xmlTableDirections = {};
13725
14665
  const xmlTableBorderPresets = {};
13726
14666
  const xmlTableCellProperties = {};
13727
14667
  const xmlTableAutoFitWindow = /* @__PURE__ */ new Set();
13728
14668
  let detectedTocSpan = null;
13729
- let topLevelParaCounter = 0;
13730
14669
  const parseTblBordersPreset = (tblPrXml) => {
13731
14670
  const bXml = tblPrXml.match(/<w:tblBorders[\s>][\s\S]*?<\/w:tblBorders>/)?.[0];
13732
14671
  if (!bXml) return void 0;
@@ -13745,231 +14684,441 @@ async function parseDocxBytesWithReport(bytes, title = "Imported Word Document")
13745
14684
  if (!ext && inn) return "internal";
13746
14685
  return "all";
13747
14686
  };
13748
- for (const item of rawBlocks) {
13749
- if (item.tag === "p") {
13750
- builderBlocks.push(
13751
- parseParagraphXmlToBuilder(
13752
- item.xml,
13753
- relsMap,
13754
- entries,
13755
- collectedDrawings,
13756
- inlineBlocksQueue,
13757
- warningsCounter,
13758
- numCtx
13759
- )
13760
- );
13761
- topLevelParaCounter++;
13762
- } else if (item.tag === "sdt") {
13763
- const isTocSdt = /<w:docPartGallery\s[^>]*w:val="Table of Contents"/i.test(item.xml) || /\bTOC\s+\\o\b/.test(item.xml);
13764
- const cStart = item.xml.match(/<w:sdtContent(?=[\s>])[^>]*>/);
13765
- const cEnd = item.xml.lastIndexOf("</w:sdtContent>");
13766
- const innerContent = cStart && cEnd > (cStart.index ?? 0) ? item.xml.slice((cStart.index ?? 0) + cStart[0].length, cEnd) : item.xml;
13767
- const innerBlocks = tokenizeBodyTopLevelBlocks(innerContent);
13768
- if (isTocSdt) {
13769
- const instrMatch = item.xml.match(/TOC\s+\\o\s+(?:&quot;|")1-(\d+)(?:&quot;|")/);
13770
- const maxLvl = instrMatch ? Math.max(1, Math.min(6, Number(instrMatch[1]))) : 3;
13771
- const hidePg = /\s\\n\b/.test(item.xml);
13772
- const startIdx = topLevelParaCounter;
13773
- for (const ib of innerBlocks) {
13774
- if (ib.tag !== "p") continue;
13775
- if (/<w:fldChar\b/.test(ib.xml) && !/<w:t(?=[\s>])/.test(ib.xml)) {
13776
- continue;
14687
+ const parseTableXmlToBuilder = (tblXml, storyRelsMap, storyInlineQueue) => {
14688
+ const tableId = `tbl_${(0, import_core7.generateRandomId)(6)}`;
14689
+ const firstTrMatch = tblXml.match(/<w:tr(?=[\s>])/);
14690
+ const tblHeadXml = firstTrMatch && typeof firstTrMatch.index === "number" ? tblXml.slice(0, firstTrMatch.index) : tblXml;
14691
+ const tblPrXml = tblHeadXml.match(/<w:tblPr[\s>][\s\S]*?<\/w:tblPr>/)?.[0] || "";
14692
+ const tblGridXml = tblHeadXml.match(/<w:tblGrid[\s>][\s\S]*?<\/w:tblGrid>/)?.[0] || "";
14693
+ if (/<w:bidiVisual(?:\s|\/|>)/.test(tblPrXml) && !/<w:bidiVisual\s[^>]*w:val="(?:0|false)"/.test(tblPrXml)) {
14694
+ xmlTableDirections[tableId] = "rtl";
14695
+ }
14696
+ const detectedPreset = parseTblBordersPreset(tblPrXml);
14697
+ if (detectedPreset) {
14698
+ xmlTableBorderPresets[tableId] = detectedPreset;
14699
+ }
14700
+ const tblBordersBlockXml = tblPrXml.match(/<w:tblBorders[\s>][\s\S]*?<\/w:tblBorders>/)?.[0] || "";
14701
+ const parseOoxmlBorderTag = (containerXml, edgeTag) => {
14702
+ if (!containerXml) return void 0;
14703
+ const em = containerXml.match(new RegExp(`<w:${edgeTag}\\b([^>]*)\\/?>`));
14704
+ if (!em) return void 0;
14705
+ const eAttrs = em[1] || "";
14706
+ const rawVal = (eAttrs.match(/w:val="([^"]+)"/)?.[1] || "single").toLowerCase();
14707
+ if (rawVal === "none" || rawVal === "nil") {
14708
+ return { style: "none", widthPt: 0 };
14709
+ }
14710
+ const szEighths = Number(eAttrs.match(/w:sz="(\d+)"/)?.[1] ?? 4);
14711
+ const widthPt = Math.max(0.25, Math.round(szEighths / 8 * 100) / 100);
14712
+ const rawColor = (eAttrs.match(/w:color="([0-9a-fA-F]{6})"/)?.[1] || "CBD5E1").toUpperCase();
14713
+ const style = rawVal === "double" ? "double" : rawVal.includes("dash") ? "dashed" : rawVal.includes("dot") ? "dotted" : "single";
14714
+ return { style, widthPt, color: `#${rawColor}` };
14715
+ };
14716
+ const defaultGridEdge = {
14717
+ style: "single",
14718
+ widthPt: 0.5,
14719
+ color: "#CBD5E1"
14720
+ };
14721
+ const noneGridEdge = { style: "none", widthPt: 0 };
14722
+ const tblLevelBorders = tblBordersBlockXml ? {
14723
+ top: parseOoxmlBorderTag(tblBordersBlockXml, "top") ?? noneGridEdge,
14724
+ bottom: parseOoxmlBorderTag(tblBordersBlockXml, "bottom") ?? noneGridEdge,
14725
+ left: parseOoxmlBorderTag(tblBordersBlockXml, "left") ?? noneGridEdge,
14726
+ right: parseOoxmlBorderTag(tblBordersBlockXml, "right") ?? noneGridEdge,
14727
+ insideH: parseOoxmlBorderTag(tblBordersBlockXml, "insideH") ?? noneGridEdge,
14728
+ insideV: parseOoxmlBorderTag(tblBordersBlockXml, "insideV") ?? noneGridEdge
14729
+ } : {
14730
+ top: defaultGridEdge,
14731
+ bottom: defaultGridEdge,
14732
+ left: defaultGridEdge,
14733
+ right: defaultGridEdge,
14734
+ insideH: defaultGridEdge,
14735
+ insideV: defaultGridEdge
14736
+ };
14737
+ let yudaoTblWidthType;
14738
+ let yudaoTblWidthDxa;
14739
+ let yudaoTblWidthPct;
14740
+ let tableSize;
14741
+ const tblWMatch = tblPrXml.match(/<w:tblW\b([^>]*)\/?>/);
14742
+ if (tblWMatch) {
14743
+ const tblWAttrs = tblWMatch[1] || "";
14744
+ const rawWVal = Number(tblWAttrs.match(/\bw:w="(-?\d+)"/)?.[1] ?? 0);
14745
+ const rawWType = (tblWAttrs.match(/\bw:type="([^"]+)"/)?.[1] || (rawWVal > 0 ? "dxa" : "auto")).toLowerCase();
14746
+ if (rawWType === "pct") {
14747
+ yudaoTblWidthType = "pct";
14748
+ yudaoTblWidthPct = rawWVal > 0 ? rawWVal : 5e3;
14749
+ xmlTableAutoFitWindow.add(tableId);
14750
+ tableSize = {
14751
+ type: import_core7.TableSizeType.UNSPECIFIED,
14752
+ width: { v: 0, u: import_core7.NumberUnitType.POINT }
14753
+ };
14754
+ } else if (rawWType === "nil") {
14755
+ yudaoTblWidthType = "nil";
14756
+ tableSize = {
14757
+ type: import_core7.TableSizeType.SPECIFIED,
14758
+ width: { v: 0, u: import_core7.NumberUnitType.POINT }
14759
+ };
14760
+ } else if (rawWType === "auto") {
14761
+ yudaoTblWidthType = "auto";
14762
+ tableSize = {
14763
+ type: import_core7.TableSizeType.UNSPECIFIED,
14764
+ width: { v: 0, u: import_core7.NumberUnitType.POINT }
14765
+ };
14766
+ } else {
14767
+ yudaoTblWidthType = "dxa";
14768
+ yudaoTblWidthDxa = Math.max(20, Math.round(rawWVal));
14769
+ tableSize = {
14770
+ type: import_core7.TableSizeType.SPECIFIED,
14771
+ width: { v: Math.max(1, dxaToPt(rawWVal)), u: import_core7.NumberUnitType.POINT }
14772
+ };
14773
+ }
14774
+ }
14775
+ let tableLayout;
14776
+ const tblLayoutMatch = tblPrXml.match(/<w:tblLayout\b[^>]*\bw:type="(fixed|autofit)"/i);
14777
+ if (tblLayoutMatch) {
14778
+ tableLayout = tblLayoutMatch[1].toLowerCase() === "fixed" ? import_core7.TableLayoutType.FIXED : import_core7.TableLayoutType.AUTO_FIT;
14779
+ }
14780
+ let colWidthsPt = Array.from(tblGridXml.matchAll(/<w:gridCol\b[^>]*\bw:w="(\d+)"/g)).map(
14781
+ (m) => Math.max(1, dxaToPt(Number(m[1])))
14782
+ );
14783
+ const trMatches = tokenizeNestedTagBlocks(tblXml, "tr");
14784
+ const trHeadList = trMatches.map((trXml) => {
14785
+ const firstTc = trXml.match(/<w:tc(?=[\s>])/);
14786
+ const head = firstTc && typeof firstTc.index === "number" ? trXml.slice(0, firstTc.index) : trXml;
14787
+ return head.match(/<w:trPr[\s>][\s\S]*?<\/w:trPr>/)?.[0] || "";
14788
+ });
14789
+ let headerRowCount = 0;
14790
+ while (headerRowCount < trHeadList.length && /<w:tblHeader(?:\s|\/|>)/.test(trHeadList[headerRowCount]) && !/<w:tblHeader\s[^>]*w:val="(?:0|false|off)"/i.test(trHeadList[headerRowCount])) {
14791
+ headerRowCount++;
14792
+ }
14793
+ const repeatHeaderRow = headerRowCount > 0;
14794
+ const rows = [];
14795
+ const rowMeta = [];
14796
+ const activeVMerges = /* @__PURE__ */ new Map();
14797
+ trMatches.forEach((trXml, trIdx) => {
14798
+ const trPrXml = trHeadList[trIdx] || "";
14799
+ let rowCantSplit;
14800
+ const cantSplitMatch = trPrXml.match(/<w:cantSplit\b([^>]*)\/?>/);
14801
+ if (cantSplitMatch) {
14802
+ const csOff = /\bw:val="(?:0|false|off)"/i.test(cantSplitMatch[1] || "");
14803
+ rowCantSplit = csOff ? import_core7.BooleanNumber.FALSE : import_core7.BooleanNumber.TRUE;
14804
+ }
14805
+ let rowTrHeight;
14806
+ const trHeightMatch = trPrXml.match(/<w:trHeight\b([^>]*)\/?>/);
14807
+ if (trHeightMatch) {
14808
+ const hAttrs = trHeightMatch[1] || "";
14809
+ const hDxa = Number(hAttrs.match(/\bw:val="(\d+)"/)?.[1] ?? 0);
14810
+ const rawHRule = (hAttrs.match(/\bw:hRule="([^"]+)"/)?.[1] || "").toLowerCase();
14811
+ if (rawHRule === "auto") {
14812
+ rowTrHeight = {
14813
+ val: { v: 0, u: import_core7.NumberUnitType.POINT },
14814
+ hRule: import_core7.TableRowHeightRule.AUTO
14815
+ };
14816
+ } else if (rawHRule === "exact") {
14817
+ rowTrHeight = {
14818
+ val: { v: dxaToPt(hDxa), u: import_core7.NumberUnitType.POINT },
14819
+ hRule: import_core7.TableRowHeightRule.EXACT
14820
+ };
14821
+ } else {
14822
+ rowTrHeight = {
14823
+ val: { v: dxaToPt(hDxa), u: import_core7.NumberUnitType.POINT },
14824
+ hRule: import_core7.TableRowHeightRule.AT_LEAST
14825
+ };
14826
+ }
14827
+ } else {
14828
+ rowTrHeight = {
14829
+ val: { v: 0, u: import_core7.NumberUnitType.POINT },
14830
+ hRule: import_core7.TableRowHeightRule.AUTO
14831
+ };
14832
+ }
14833
+ const tcMatches = tokenizeNestedTagBlocks(trXml, "tc");
14834
+ const rowIdx = rows.length;
14835
+ const rowCells = [];
14836
+ let gridCol = 0;
14837
+ for (const tcXml of tcMatches) {
14838
+ const firstTcBodyMatch = tcXml.match(/<w:(?:p|tbl|sdt)(?=[\s/>])/);
14839
+ const tcHeadXml = firstTcBodyMatch && typeof firstTcBodyMatch.index === "number" ? tcXml.slice(0, firstTcBodyMatch.index) : tcXml;
14840
+ const tcPrXml = tcHeadXml.match(/<w:tcPr[\s>][\s\S]*?<\/w:tcPr>/)?.[0] || "";
14841
+ const spanMatch = tcPrXml.match(/<w:gridSpan\s[^>]*w:val="(\d+)"/);
14842
+ const colSpan = spanMatch ? Math.max(1, Number(spanMatch[1])) : 1;
14843
+ const vMergeTag = tcPrXml.match(/<w:vMerge\b([^>]*)\/?>/);
14844
+ const isVMergeRestart = Boolean(vMergeTag && /w:val="restart"/.test(vMergeTag[1] || ""));
14845
+ const isVMergeContinue = Boolean(vMergeTag && !isVMergeRestart);
14846
+ let tcWidthType;
14847
+ let cellSize;
14848
+ let yudaoTcWidthPct;
14849
+ const tcWMatch = tcPrXml.match(/<w:tcW\b([^>]*)\/?>/);
14850
+ if (tcWMatch) {
14851
+ const tcWAttrs = tcWMatch[1] || "";
14852
+ const rawTcWVal = Number(tcWAttrs.match(/\bw:w="(-?\d+)"/)?.[1] ?? 0);
14853
+ const rawTcWType = (tcWAttrs.match(/\bw:type="([^"]+)"/)?.[1] || (rawTcWVal > 0 ? "dxa" : "auto")).toLowerCase();
14854
+ if (rawTcWType === "pct") {
14855
+ tcWidthType = "pct";
14856
+ yudaoTcWidthPct = rawTcWVal > 0 ? rawTcWVal : void 0;
14857
+ cellSize = {
14858
+ type: import_core7.TableSizeType.UNSPECIFIED,
14859
+ width: { v: 0, u: import_core7.NumberUnitType.POINT }
14860
+ };
14861
+ } else if (rawTcWType === "nil") {
14862
+ tcWidthType = "nil";
14863
+ cellSize = {
14864
+ type: import_core7.TableSizeType.SPECIFIED,
14865
+ width: { v: 0, u: import_core7.NumberUnitType.POINT }
14866
+ };
14867
+ } else if (rawTcWType === "auto") {
14868
+ tcWidthType = "auto";
14869
+ cellSize = {
14870
+ type: import_core7.TableSizeType.UNSPECIFIED,
14871
+ width: { v: 0, u: import_core7.NumberUnitType.POINT }
14872
+ };
14873
+ } else {
14874
+ tcWidthType = "dxa";
14875
+ cellSize = {
14876
+ type: import_core7.TableSizeType.SPECIFIED,
14877
+ width: { v: Math.max(1, dxaToPt(rawTcWVal)), u: import_core7.NumberUnitType.POINT }
14878
+ };
13777
14879
  }
13778
- builderBlocks.push(
13779
- parseParagraphXmlToBuilder(
13780
- ib.xml,
13781
- relsMap,
14880
+ }
14881
+ const shdMatch = tcPrXml.match(/<w:shd\s[^>]*w:fill="([0-9a-fA-F]{6})"/);
14882
+ const vAlignMatch = tcPrXml.match(/<w:vAlign\s[^>]*w:val="([^"]+)"/)?.[1];
14883
+ const tcBordersXml = tcPrXml.match(/<w:tcBorders[\s>][\s\S]*?<\/w:tcBorders>/)?.[0] || "";
14884
+ const parseTcBorderEdge = (edgeTag) => {
14885
+ const em = tcBordersXml.match(new RegExp(`<w:${edgeTag}\\b([^>]*)\\/?>`));
14886
+ if (!em) return void 0;
14887
+ const eAttrs = em[1] || "";
14888
+ const rawVal = (eAttrs.match(/w:val="([^"]+)"/)?.[1] || "single").toLowerCase();
14889
+ if (rawVal === "none" || rawVal === "nil") {
14890
+ return { style: "none", widthPt: 0 };
14891
+ }
14892
+ const szEighths = Number(eAttrs.match(/w:sz="(\d+)"/)?.[1] ?? 4);
14893
+ const widthPt = Math.max(0.25, Math.round(szEighths / 8 * 100) / 100);
14894
+ const rawColor = (eAttrs.match(/w:color="([0-9a-fA-F]{6})"/)?.[1] || "CBD5E1").toUpperCase();
14895
+ const style = rawVal === "double" ? "double" : rawVal.includes("dash") ? "dashed" : rawVal.includes("dot") ? "dotted" : "single";
14896
+ return { style, widthPt, color: `#${rawColor}` };
14897
+ };
14898
+ const parsedCellBorders = {};
14899
+ const effectiveColCount = Math.max(colWidthsPt.length, tcMatches.length, gridCol + colSpan);
14900
+ const inhTop = trIdx === 0 ? tblLevelBorders.top : tblLevelBorders.insideH;
14901
+ const inhBot = trIdx === trMatches.length - 1 ? tblLevelBorders.bottom : tblLevelBorders.insideH;
14902
+ const inhLeft = gridCol === 0 ? tblLevelBorders.left : tblLevelBorders.insideV;
14903
+ const inhRight = gridCol + colSpan >= effectiveColCount ? tblLevelBorders.right : tblLevelBorders.insideV;
14904
+ const bTop = tcBordersXml ? parseTcBorderEdge("top") : void 0;
14905
+ const bBot = tcBordersXml ? parseTcBorderEdge("bottom") : void 0;
14906
+ const bLeft = tcBordersXml ? parseTcBorderEdge("left") : void 0;
14907
+ const bRight = tcBordersXml ? parseTcBorderEdge("right") : void 0;
14908
+ parsedCellBorders.top = bTop ?? inhTop;
14909
+ parsedCellBorders.bottom = bBot ?? inhBot;
14910
+ parsedCellBorders.left = bLeft ?? inhLeft;
14911
+ parsedCellBorders.right = bRight ?? inhRight;
14912
+ const hasExplicitCellBorders = Boolean(bTop || bBot || bLeft || bRight);
14913
+ const hasTl2Br = /<w:tl2br\b/.test(tcBordersXml) && !/<w:tl2br\b[^>]*w:val="(?:none|nil)"/.test(tcBordersXml);
14914
+ const hasTr2Bl = /<w:tr2bl\b/.test(tcBordersXml) && !/<w:tr2bl\b[^>]*w:val="(?:none|nil)"/.test(tcBordersXml);
14915
+ const cellProps = {};
14916
+ if (hasTl2Br && hasTr2Bl) cellProps.slashType = "both";
14917
+ else if (hasTl2Br) cellProps.slashType = "back";
14918
+ else if (hasTr2Bl) cellProps.slashType = "forward";
14919
+ if (vAlignMatch === "top" || vAlignMatch === "center" || vAlignMatch === "bottom") {
14920
+ cellProps.verticalAlign = vAlignMatch;
14921
+ }
14922
+ if (shdMatch) {
14923
+ cellProps.backgroundColor = `#${shdMatch[1].toUpperCase()}`;
14924
+ }
14925
+ if (hasExplicitCellBorders) {
14926
+ cellProps.borders = {
14927
+ ...bTop ? { top: bTop } : {},
14928
+ ...bBot ? { bottom: bBot } : {},
14929
+ ...bLeft ? { left: bLeft } : {},
14930
+ ...bRight ? { right: bRight } : {}
14931
+ };
14932
+ }
14933
+ if (Object.keys(cellProps).length > 0) {
14934
+ xmlTableCellProperties[`${tableId}:${rowIdx}:${gridCol}`] = cellProps;
14935
+ }
14936
+ if (isVMergeContinue && activeVMerges.has(gridCol)) {
14937
+ const masterInfo = activeVMerges.get(gridCol);
14938
+ const masterCell = rows[masterInfo.startRow]?.[gridCol];
14939
+ if (masterCell) {
14940
+ masterCell.rowSpan = (masterCell.rowSpan ?? 1) + 1;
14941
+ }
14942
+ rowCells.push({
14943
+ text: "",
14944
+ colSpan,
14945
+ rowSpan: 0,
14946
+ borders: parsedCellBorders,
14947
+ ...tcWidthType ? { tcWidthType } : {},
14948
+ ...cellSize ? { cellSize } : {},
14949
+ ...yudaoTcWidthPct !== void 0 ? { yudaoTcWidthPct } : {}
14950
+ });
14951
+ for (let k = 1; k < colSpan; k++) {
14952
+ rowCells.push({ text: "", colSpan: 0, rowSpan: 0 });
14953
+ }
14954
+ } else {
14955
+ if (isVMergeRestart) {
14956
+ activeVMerges.set(gridCol, { startRow: rowIdx, colSpan });
14957
+ } else {
14958
+ activeVMerges.delete(gridCol);
14959
+ }
14960
+ const tcBodyOnly = tcPrXml ? tcXml.replace(tcPrXml, "") : tcXml;
14961
+ const tcInnerMatch = tcBodyOnly.match(/^<w:tc(?=[\s>])[^>]*>([\s\S]*)<\/w:tc>$/);
14962
+ const tcInnerXml = tcInnerMatch ? tcInnerMatch[1] : tcBodyOnly;
14963
+ const tcPXmlList = unwrapCellParagraphBlocks(tcInnerXml);
14964
+ const tcParas = tcPXmlList.length > 0 ? tcPXmlList.map(
14965
+ (pXmlItem) => parseParagraphXmlToBuilder(
14966
+ pXmlItem,
14967
+ storyRelsMap,
13782
14968
  entries,
13783
14969
  collectedDrawings,
13784
- inlineBlocksQueue,
14970
+ storyInlineQueue,
13785
14971
  warningsCounter,
13786
14972
  numCtx
13787
14973
  )
13788
- );
13789
- topLevelParaCounter++;
13790
- }
13791
- if (topLevelParaCounter > startIdx) {
13792
- detectedTocSpan = {
13793
- startTopParaIdx: startIdx,
13794
- endTopParaIdx: topLevelParaCounter - 1,
13795
- maxLevel: maxLvl,
13796
- showPageNumbers: !hidePg
13797
- };
13798
- }
13799
- } else {
13800
- for (const ib of innerBlocks) {
13801
- if (ib.tag === "p") {
13802
- builderBlocks.push(
13803
- parseParagraphXmlToBuilder(
13804
- ib.xml,
13805
- relsMap,
13806
- entries,
13807
- collectedDrawings,
13808
- inlineBlocksQueue,
13809
- warningsCounter,
13810
- numCtx
13811
- )
13812
- );
13813
- topLevelParaCounter++;
14974
+ ) : void 0;
14975
+ const cellTexts = Array.from(
14976
+ tcXml.matchAll(/<w:t(?=[\s>])[^>]*>([\s\S]*?)<\/w:t>/g)
14977
+ ).map((m) => unescapeXml(m[1]));
14978
+ const firstRunMatch = tcXml.match(/<w:r[\s>][\s\S]*?<\/w:r>/);
14979
+ rowCells.push({
14980
+ text: cellTexts.join("\n"),
14981
+ style: firstRunMatch ? parseRunStyleFromXml(firstRunMatch[0], themeFonts) : void 0,
14982
+ colSpan,
14983
+ rowSpan: 1,
14984
+ backgroundRgb: shdMatch ? `#${shdMatch[1]}` : void 0,
14985
+ borders: parsedCellBorders,
14986
+ ...tcWidthType ? { tcWidthType } : {},
14987
+ ...cellSize ? { cellSize } : {},
14988
+ ...yudaoTcWidthPct !== void 0 ? { yudaoTcWidthPct } : {},
14989
+ ...tcParas ? { paragraphs: tcParas } : {}
14990
+ });
14991
+ for (let k = 1; k < colSpan; k++) {
14992
+ rowCells.push({ text: "", colSpan: 0, rowSpan: 1 });
13814
14993
  }
13815
14994
  }
14995
+ gridCol += colSpan;
13816
14996
  }
13817
- } else if (item.tag === "tbl") {
13818
- const tableId = `tbl_${(0, import_core7.generateRandomId)(6)}`;
13819
- const tblPrXml = item.xml.match(/<w:tblPr[\s>][\s\S]*?<\/w:tblPr>/)?.[0] || "";
13820
- if (/<w:bidiVisual(?:\s|\/|>)/.test(tblPrXml) && !/<w:bidiVisual\s[^>]*w:val="(?:0|false)"/.test(tblPrXml)) {
13821
- xmlTableDirections[tableId] = "rtl";
13822
- }
13823
- if (/<w:tblW\b[^>]*w:type="pct"/.test(tblPrXml)) {
13824
- xmlTableAutoFitWindow.add(tableId);
14997
+ if (rowCells.length > 0) {
14998
+ rows.push(rowCells);
14999
+ rowMeta.push({
15000
+ ...rowCantSplit !== void 0 ? { cantSplit: rowCantSplit } : {},
15001
+ trHeight: rowTrHeight
15002
+ });
13825
15003
  }
13826
- const detectedPreset = parseTblBordersPreset(tblPrXml);
13827
- if (detectedPreset) {
13828
- xmlTableBorderPresets[tableId] = detectedPreset;
15004
+ });
15005
+ if (colWidthsPt.length === 0 && rows[0]?.length) {
15006
+ const derivedCols = [];
15007
+ let cCursor = 0;
15008
+ while (cCursor < rows[0].length) {
15009
+ const cell = rows[0][cCursor];
15010
+ const span = Math.max(1, cell.colSpan ?? 1);
15011
+ const wPt = cell.cellSize?.width?.v;
15012
+ if (typeof wPt === "number" && wPt > 0) {
15013
+ const each = Math.max(1, Math.round(wPt / span * 100) / 100);
15014
+ for (let k = 0; k < span; k++) derivedCols.push(each);
15015
+ } else {
15016
+ derivedCols.length = 0;
15017
+ break;
15018
+ }
15019
+ cCursor += span;
13829
15020
  }
13830
- const colWidthsPt = Array.from(item.xml.matchAll(/<w:gridCol\s[^>]*w:w="(\d+)"/g)).map(
13831
- (m) => Math.max(24, Math.round(Number(m[1]) / 20))
13832
- );
13833
- const trMatches = item.xml.match(/<w:tr[\s>][\s\S]*?<\/w:tr>/g) ?? [];
13834
- let headerRowCount = 0;
13835
- while (headerRowCount < trMatches.length && /<w:tblHeader(?:\s|\/|>)/.test(trMatches[headerRowCount])) {
13836
- headerRowCount++;
15021
+ if (derivedCols.length > 0) {
15022
+ colWidthsPt = derivedCols;
13837
15023
  }
13838
- const repeatHeaderRow = headerRowCount > 0;
13839
- const rows = [];
13840
- const activeVMerges = /* @__PURE__ */ new Map();
13841
- trMatches.forEach((trXml) => {
13842
- const tcMatches = trXml.match(/<w:tc[\s>][\s\S]*?<\/w:tc>/g) ?? [];
13843
- const rowIdx = rows.length;
13844
- const rowCells = [];
13845
- let gridCol = 0;
13846
- for (const tcXml of tcMatches) {
13847
- const tcPrXml = tcXml.match(/<w:tcPr[\s>][\s\S]*?<\/w:tcPr>/)?.[0] || "";
13848
- const spanMatch = tcPrXml.match(/<w:gridSpan\s[^>]*w:val="(\d+)"/);
13849
- const colSpan = spanMatch ? Math.max(1, Number(spanMatch[1])) : 1;
13850
- const vMergeTag = tcPrXml.match(/<w:vMerge\b([^>]*)\/?>/);
13851
- const isVMergeRestart = Boolean(vMergeTag && /w:val="restart"/.test(vMergeTag[1] || ""));
13852
- const isVMergeContinue = Boolean(vMergeTag && !isVMergeRestart);
13853
- const shdMatch = tcPrXml.match(/<w:shd\s[^>]*w:fill="([0-9a-fA-F]{6})"/);
13854
- const vAlignMatch = tcPrXml.match(/<w:vAlign\s[^>]*w:val="([^"]+)"/)?.[1];
13855
- const tcBordersXml = tcPrXml.match(/<w:tcBorders[\s>][\s\S]*?<\/w:tcBorders>/)?.[0] || "";
13856
- const parseTcBorderEdge = (edgeTag) => {
13857
- const em = tcBordersXml.match(new RegExp(`<w:${edgeTag}\\b([^>]*)\\/?>`));
13858
- if (!em) return void 0;
13859
- const eAttrs = em[1] || "";
13860
- const rawVal = (eAttrs.match(/w:val="([^"]+)"/)?.[1] || "single").toLowerCase();
13861
- if (rawVal === "none" || rawVal === "nil") {
13862
- return { style: "none", widthPt: 0 };
13863
- }
13864
- const szEighths = Number(eAttrs.match(/w:sz="(\d+)"/)?.[1] ?? 4);
13865
- const widthPt = Math.max(0.25, Math.round(szEighths / 8 * 100) / 100);
13866
- const rawColor = (eAttrs.match(/w:color="([0-9a-fA-F]{6})"/)?.[1] || "CBD5E1").toUpperCase();
13867
- const style = rawVal === "double" ? "double" : rawVal.includes("dash") ? "dashed" : rawVal.includes("dot") ? "dotted" : "single";
13868
- return { style, widthPt, color: `#${rawColor}` };
13869
- };
13870
- const parsedCellBorders = {};
13871
- if (tcBordersXml) {
13872
- const bTop = parseTcBorderEdge("top");
13873
- const bBot = parseTcBorderEdge("bottom");
13874
- const bLeft = parseTcBorderEdge("left");
13875
- const bRight = parseTcBorderEdge("right");
13876
- if (bTop) parsedCellBorders.top = bTop;
13877
- if (bBot) parsedCellBorders.bottom = bBot;
13878
- if (bLeft) parsedCellBorders.left = bLeft;
13879
- if (bRight) parsedCellBorders.right = bRight;
13880
- }
13881
- const hasCellBorders = Object.keys(parsedCellBorders).length > 0;
13882
- const hasTl2Br = /<w:tl2br\b/.test(tcBordersXml) && !/<w:tl2br\b[^>]*w:val="(?:none|nil)"/.test(tcBordersXml);
13883
- const hasTr2Bl = /<w:tr2bl\b/.test(tcBordersXml) && !/<w:tr2bl\b[^>]*w:val="(?:none|nil)"/.test(tcBordersXml);
13884
- const cellProps = {};
13885
- if (hasTl2Br && hasTr2Bl) cellProps.slashType = "both";
13886
- else if (hasTl2Br) cellProps.slashType = "back";
13887
- else if (hasTr2Bl) cellProps.slashType = "forward";
13888
- if (vAlignMatch === "top" || vAlignMatch === "center" || vAlignMatch === "bottom") {
13889
- cellProps.verticalAlign = vAlignMatch;
13890
- }
13891
- if (shdMatch) {
13892
- cellProps.backgroundColor = `#${shdMatch[1].toUpperCase()}`;
13893
- }
13894
- if (hasCellBorders) {
13895
- cellProps.borders = parsedCellBorders;
13896
- }
13897
- if (Object.keys(cellProps).length > 0) {
13898
- xmlTableCellProperties[`${tableId}:${rowIdx}:${gridCol}`] = cellProps;
13899
- }
13900
- if (isVMergeContinue && activeVMerges.has(gridCol)) {
13901
- const masterInfo = activeVMerges.get(gridCol);
13902
- const masterCell = rows[masterInfo.startRow]?.[gridCol];
13903
- if (masterCell) {
13904
- masterCell.rowSpan = (masterCell.rowSpan ?? 1) + 1;
15024
+ }
15025
+ if (rows.length === 0) return null;
15026
+ return {
15027
+ kind: "table",
15028
+ tableId,
15029
+ columnWidthsPt: colWidthsPt.length > 0 ? colWidthsPt : void 0,
15030
+ repeatHeaderRow,
15031
+ headerRowCount,
15032
+ rows,
15033
+ rowMeta,
15034
+ ...tableSize ? { tableSize } : {},
15035
+ ...tableLayout !== void 0 ? { tableLayout } : {},
15036
+ ...yudaoTblWidthType ? { yudaoTblWidthType } : {},
15037
+ ...yudaoTblWidthDxa !== void 0 ? { yudaoTblWidthDxa } : {},
15038
+ ...yudaoTblWidthPct !== void 0 ? { yudaoTblWidthPct } : {}
15039
+ };
15040
+ };
15041
+ const parseStoryBlocksFromXml = (storyXml, storyRelsMap, storyInlineQueue, allowTocDetection) => {
15042
+ const storyBlocks = [];
15043
+ let topLevelParaCounter = 0;
15044
+ const appendBlocksFromXml = (containerXml) => {
15045
+ const items = tokenizeBodyTopLevelBlocks(containerXml);
15046
+ for (const item of items) {
15047
+ if (item.tag === "p") {
15048
+ storyBlocks.push(
15049
+ parseParagraphXmlToBuilder(
15050
+ item.xml,
15051
+ storyRelsMap,
15052
+ entries,
15053
+ collectedDrawings,
15054
+ storyInlineQueue,
15055
+ warningsCounter,
15056
+ numCtx
15057
+ )
15058
+ );
15059
+ topLevelParaCounter++;
15060
+ } else if (item.tag === "sdt") {
15061
+ const isTocSdt = allowTocDetection && (/<w:docPartGallery\s[^>]*w:val="Table of Contents"/i.test(item.xml) || /\bTOC\s+\\o\b/.test(item.xml));
15062
+ const cStart = item.xml.match(/<w:sdtContent(?=[\s>])[^>]*>/);
15063
+ const cEnd = item.xml.lastIndexOf("</w:sdtContent>");
15064
+ const innerContent = cStart && cEnd > (cStart.index ?? 0) ? item.xml.slice((cStart.index ?? 0) + cStart[0].length, cEnd) : item.xml;
15065
+ if (isTocSdt) {
15066
+ const innerBlocks = tokenizeBodyTopLevelBlocks(innerContent);
15067
+ const instrMatch = item.xml.match(/TOC\s+\\o\s+(?:&quot;|")1-(\d+)(?:&quot;|")/);
15068
+ const maxLvl = instrMatch ? Math.max(1, Math.min(6, Number(instrMatch[1]))) : 3;
15069
+ const hidePg = /\s\\n\b/.test(item.xml);
15070
+ const startIdx = topLevelParaCounter;
15071
+ for (const ib of innerBlocks) {
15072
+ if (ib.tag !== "p") continue;
15073
+ if (/<w:fldChar\b/.test(ib.xml) && !/<w:t(?=[\s>])/.test(ib.xml)) {
15074
+ continue;
15075
+ }
15076
+ storyBlocks.push(
15077
+ parseParagraphXmlToBuilder(
15078
+ ib.xml,
15079
+ storyRelsMap,
15080
+ entries,
15081
+ collectedDrawings,
15082
+ storyInlineQueue,
15083
+ warningsCounter,
15084
+ numCtx
15085
+ )
15086
+ );
15087
+ topLevelParaCounter++;
13905
15088
  }
13906
- rowCells.push({
13907
- text: "",
13908
- colSpan,
13909
- rowSpan: 0
13910
- });
13911
- for (let k = 1; k < colSpan; k++) {
13912
- rowCells.push({ text: "", colSpan: 0, rowSpan: 0 });
15089
+ if (topLevelParaCounter > startIdx) {
15090
+ detectedTocSpan = {
15091
+ startTopParaIdx: startIdx,
15092
+ endTopParaIdx: topLevelParaCounter - 1,
15093
+ maxLevel: maxLvl,
15094
+ showPageNumbers: !hidePg
15095
+ };
13913
15096
  }
13914
15097
  } else {
13915
- if (isVMergeRestart) {
13916
- activeVMerges.set(gridCol, { startRow: rowIdx, colSpan });
13917
- } else {
13918
- activeVMerges.delete(gridCol);
13919
- }
13920
- const tcBodyOnly = tcPrXml ? tcXml.replace(tcPrXml, "") : tcXml;
13921
- const tcInnerMatch = tcBodyOnly.match(/^<w:tc(?=[\s>])[^>]*>([\s\S]*)<\/w:tc>$/);
13922
- const tcInnerXml = tcInnerMatch ? tcInnerMatch[1] : tcBodyOnly;
13923
- const tcPBlocks = tokenizeBodyTopLevelBlocks(tcInnerXml).filter((b) => b.tag === "p");
13924
- const tcParas = tcPBlocks.length > 0 ? tcPBlocks.map(
13925
- (pb) => parseParagraphXmlToBuilder(
13926
- pb.xml,
13927
- relsMap,
13928
- entries,
13929
- collectedDrawings,
13930
- inlineBlocksQueue,
13931
- warningsCounter,
13932
- numCtx
13933
- )
13934
- ) : void 0;
13935
- const cellTexts = Array.from(
13936
- tcXml.matchAll(/<w:t(?=[\s>])[^>]*>([\s\S]*?)<\/w:t>/g)
13937
- ).map((m) => unescapeXml(m[1]));
13938
- const firstRunMatch = tcXml.match(/<w:r[\s>][\s\S]*?<\/w:r>/);
13939
- rowCells.push({
13940
- text: cellTexts.join("\n"),
13941
- style: firstRunMatch ? parseRunStyleFromXml(firstRunMatch[0]) : void 0,
13942
- colSpan,
13943
- rowSpan: 1,
13944
- backgroundRgb: shdMatch ? `#${shdMatch[1]}` : void 0,
13945
- ...hasCellBorders ? { borders: parsedCellBorders } : {},
13946
- ...tcParas ? { paragraphs: tcParas } : {}
13947
- });
13948
- for (let k = 1; k < colSpan; k++) {
13949
- rowCells.push({ text: "", colSpan: 0, rowSpan: 1 });
13950
- }
15098
+ appendBlocksFromXml(innerContent);
15099
+ }
15100
+ } else if (item.tag === "tbl") {
15101
+ const builtTbl = parseTableXmlToBuilder(item.xml, storyRelsMap, storyInlineQueue);
15102
+ if (builtTbl) {
15103
+ storyBlocks.push(builtTbl);
13951
15104
  }
13952
- gridCol += colSpan;
13953
- }
13954
- if (rowCells.length > 0) {
13955
- rows.push(rowCells);
13956
15105
  }
13957
- });
13958
- if (rows.length > 0) {
13959
- builderBlocks.push({
13960
- kind: "table",
13961
- tableId,
13962
- columnWidthsPt: colWidthsPt.length > 0 ? colWidthsPt : void 0,
13963
- repeatHeaderRow,
13964
- headerRowCount,
13965
- rows
13966
- });
13967
15106
  }
13968
- }
13969
- }
13970
- const pgSzMatch = xml.match(/<w:pgSz\s[^>]*w:w="(\d+)"[^>]*w:h="(\d+)"/);
13971
- const pageWidthPt = pgSzMatch ? Math.round(Number(pgSzMatch[1]) / 20 * 100) / 100 : 595.28;
13972
- const pageHeightPt = pgSzMatch ? Math.round(Number(pgSzMatch[2]) / 20 * 100) / 100 : 841.89;
15107
+ };
15108
+ appendBlocksFromXml(storyXml);
15109
+ return storyBlocks;
15110
+ };
15111
+ const builderBlocks = parseStoryBlocksFromXml(bodyXml, relsMap, inlineBlocksQueue, true);
15112
+ const trailingSectMatch = bodyXml.match(
15113
+ /<w:sectPr(?=[\s>])(?![\s\S]*<w:sectPr)([\s\S]*?)<\/w:sectPr>/
15114
+ );
15115
+ const sectPrXml = trailingSectMatch ? trailingSectMatch[0] : xml;
15116
+ const pgSzTag = sectPrXml.match(/<w:pgSz\b([^>]*)\/?>/) ?? xml.match(/<w:pgSz\b([^>]*)\/?>/);
15117
+ const pgSzAttrs = pgSzTag?.[1] || "";
15118
+ const pgSzW = pgSzAttrs.match(/\bw:w="(\d+)"/)?.[1];
15119
+ const pgSzH = pgSzAttrs.match(/\bw:h="(\d+)"/)?.[1];
15120
+ const pageWidthPt = pgSzW ? dxaToPt(Number(pgSzW)) : 595.28;
15121
+ const pageHeightPt = pgSzH ? dxaToPt(Number(pgSzH)) : 841.89;
13973
15122
  const docData = buildStructuredDocData({
13974
15123
  id: docUnitId,
13975
15124
  title,
@@ -13977,19 +15126,79 @@ async function parseDocxBytesWithReport(bytes, title = "Imported Word Document")
13977
15126
  pageWidthPt,
13978
15127
  pageHeightPt
13979
15128
  });
15129
+ if (themeFonts && docData.documentStyle) {
15130
+ if (themeFonts.majorLatin || themeFonts.minorLatin) {
15131
+ docData.documentStyle.latinFontScheme = {
15132
+ ...themeFonts.majorLatin ? { major: themeFonts.majorLatin } : {},
15133
+ ...themeFonts.minorLatin ? { minor: themeFonts.minorLatin } : {}
15134
+ };
15135
+ }
15136
+ if (themeFonts.majorEastAsia || themeFonts.minorEastAsia) {
15137
+ docData.documentStyle.eastAsiaFontScheme = {
15138
+ major: { ...themeFonts.majorEastAsia ? { fontFamily: themeFonts.majorEastAsia } : {} },
15139
+ minor: { ...themeFonts.minorEastAsia ? { fontFamily: themeFonts.minorEastAsia } : {} }
15140
+ };
15141
+ }
15142
+ }
15143
+ const stylesBytes = entries.get("word/styles.xml");
15144
+ if (stylesBytes) {
15145
+ parseStylesXmlIntoDoc(decoder.decode(stylesBytes), themeFonts, docData);
15146
+ }
13980
15147
  for (const autoTblId of xmlTableAutoFitWindow) {
13981
15148
  if (docData.tableSource?.[autoTblId]) {
13982
15149
  docData.tableSource[autoTblId].yudaoAutoFitMode = "window";
13983
15150
  }
13984
15151
  }
13985
- const pgMarMatch = xml.match(
13986
- /<w:pgMar\s[^>]*w:top="(\d+)"[^>]*w:right="(\d+)"[^>]*w:bottom="(\d+)"[^>]*w:left="(\d+)"/
13987
- );
13988
- if (pgMarMatch && docData.documentStyle) {
13989
- docData.documentStyle.marginTop = Math.round(Number(pgMarMatch[1]) / 20);
13990
- docData.documentStyle.marginRight = Math.round(Number(pgMarMatch[2]) / 20);
13991
- docData.documentStyle.marginBottom = Math.round(Number(pgMarMatch[3]) / 20);
13992
- docData.documentStyle.marginLeft = Math.round(Number(pgMarMatch[4]) / 20);
15152
+ const pgMarTag = sectPrXml.match(/<w:pgMar\b([^>]*)\/?>/) ?? xml.match(/<w:pgMar\b([^>]*)\/?>/);
15153
+ if (pgMarTag && docData.documentStyle) {
15154
+ const pmAttrs = pgMarTag[1] || "";
15155
+ const pmTop = pmAttrs.match(/\bw:top="(-?\d+)"/)?.[1];
15156
+ const pmRight = pmAttrs.match(/\bw:right="(-?\d+)"/)?.[1];
15157
+ const pmBottom = pmAttrs.match(/\bw:bottom="(-?\d+)"/)?.[1];
15158
+ const pmLeft = pmAttrs.match(/\bw:left="(-?\d+)"/)?.[1];
15159
+ const pmHeader = pmAttrs.match(/\bw:header="(-?\d+)"/)?.[1];
15160
+ const pmFooter = pmAttrs.match(/\bw:footer="(-?\d+)"/)?.[1];
15161
+ if (pmTop !== void 0) docData.documentStyle.marginTop = dxaToPt(Math.max(0, Number(pmTop)));
15162
+ if (pmRight !== void 0) {
15163
+ docData.documentStyle.marginRight = dxaToPt(Math.max(0, Number(pmRight)));
15164
+ }
15165
+ if (pmBottom !== void 0) {
15166
+ docData.documentStyle.marginBottom = dxaToPt(Math.max(0, Number(pmBottom)));
15167
+ }
15168
+ if (pmLeft !== void 0) docData.documentStyle.marginLeft = dxaToPt(Math.max(0, Number(pmLeft)));
15169
+ if (pmHeader !== void 0) {
15170
+ docData.documentStyle.marginHeader = dxaToPt(Math.max(0, Number(pmHeader)));
15171
+ }
15172
+ if (pmFooter !== void 0) {
15173
+ docData.documentStyle.marginFooter = dxaToPt(Math.max(0, Number(pmFooter)));
15174
+ }
15175
+ }
15176
+ if (docData.documentStyle) {
15177
+ docData.documentStyle.documentFlavor = 1;
15178
+ }
15179
+ const docGridTag = sectPrXml.match(/<w:docGrid\b([^>]*)\/?>/) ?? xml.match(/<w:docGrid\b([^>]*)\/?>/);
15180
+ if (docGridTag && docData.documentStyle) {
15181
+ const dgAttrs = docGridTag[1] || "";
15182
+ const dgTypeRaw = dgAttrs.match(/\bw:type="([^"]+)"/)?.[1];
15183
+ const dgLinePitchRaw = dgAttrs.match(/\bw:linePitch="(-?\d+)"/)?.[1];
15184
+ const dgCharSpaceRaw = dgAttrs.match(/\bw:charSpace="(-?\d+)"/)?.[1];
15185
+ const savedGrid = {};
15186
+ if (dgTypeRaw) {
15187
+ savedGrid.type = dgTypeRaw;
15188
+ const lowerDg = dgTypeRaw.toLowerCase();
15189
+ docData.documentStyle.gridType = lowerDg === "lines" ? import_core7.GridType.LINES : lowerDg === "linesandchars" ? import_core7.GridType.LINES_AND_CHARS : lowerDg === "snaptochars" ? import_core7.GridType.SNAP_TO_CHARS : import_core7.GridType.DEFAULT;
15190
+ }
15191
+ if (dgLinePitchRaw !== void 0) {
15192
+ savedGrid.linePitch = Number(dgLinePitchRaw);
15193
+ docData.documentStyle.linePitch = dxaToPt(Math.max(0, Number(dgLinePitchRaw)));
15194
+ }
15195
+ if (dgCharSpaceRaw !== void 0) {
15196
+ savedGrid.charSpace = Number(dgCharSpaceRaw);
15197
+ docData.documentStyle.charSpace = Number(dgCharSpaceRaw);
15198
+ }
15199
+ if (Object.keys(savedGrid).length > 0) {
15200
+ docData.documentStyle.yudaoDocGrid = savedGrid;
15201
+ }
13993
15202
  }
13994
15203
  const colsTagMatch = xml.match(/<w:cols\b([^>]*)(?:\/>|>([\s\S]*?)<\/w:cols>)/);
13995
15204
  if (colsTagMatch && docData.body) {
@@ -14158,6 +15367,8 @@ async function parseDocxBytesWithReport(bytes, title = "Imported Word Document")
14158
15367
  const hfBytes = entries.get(key);
14159
15368
  if (!hfBytes) return null;
14160
15369
  const hfXml = decoder.decode(hfBytes);
15370
+ const hfInnerMatch = hfXml.match(/<w:(?:hdr|ftr)[\s>]([\s\S]*?)<\/w:(?:hdr|ftr)>/);
15371
+ const hfBodyXml = hfInnerMatch ? hfInnerMatch[1] : hfXml;
14161
15372
  const hfFileName = key.split("/").pop() || "header1.xml";
14162
15373
  const hfRelsBytes = entries.get(`word/_rels/${hfFileName}.rels`);
14163
15374
  const hfRelsMap = new Map(relsMap);
@@ -14168,43 +15379,59 @@ async function parseDocxBytesWithReport(bytes, title = "Imported Word Document")
14168
15379
  }
14169
15380
  }
14170
15381
  const hfQueue = [];
14171
- const pBlocks = tokenizeBodyTopLevelBlocks(hfXml).filter((b) => b.tag === "p");
14172
- const paras = pBlocks.length > 0 ? pBlocks.map(
14173
- (pb) => parseParagraphXmlToBuilder(
14174
- pb.xml,
14175
- hfRelsMap,
14176
- entries,
14177
- collectedDrawings,
14178
- hfQueue,
14179
- { floatingImages: 0 },
14180
- numCtx
14181
- )
14182
- ) : [
14183
- {
14184
- segments: [
14185
- Array.from(hfXml.matchAll(/<w:t(?=[\s>])[^>]*>([\s\S]*?)<\/w:t>/g)).map((m) => unescapeXml(m[1])).join("")
14186
- ]
15382
+ const hfBlocks = parseStoryBlocksFromXml(hfBodyXml, hfRelsMap, hfQueue, false);
15383
+ const hfDoc = buildStructuredDocData({
15384
+ id: docUnitId,
15385
+ title: key,
15386
+ blocks: hfBlocks.length > 0 ? hfBlocks : [
15387
+ {
15388
+ segments: [
15389
+ Array.from(hfBodyXml.matchAll(/<w:t(?=[\s>])[^>]*>([\s\S]*?)<\/w:t>/g)).map((m) => unescapeXml(m[1])).join("")
15390
+ ]
15391
+ }
15392
+ ],
15393
+ pageWidthPt,
15394
+ pageHeightPt
15395
+ });
15396
+ if (hfDoc.tableSource && Object.keys(hfDoc.tableSource).length > 0) {
15397
+ for (const autoTblId of xmlTableAutoFitWindow) {
15398
+ if (hfDoc.tableSource[autoTblId]) {
15399
+ hfDoc.tableSource[autoTblId].yudaoAutoFitMode = "window";
15400
+ }
14187
15401
  }
14188
- ];
14189
- const hfDoc = buildStructuredDocData({ title: key, paragraphs: paras });
15402
+ docData.tableSource = {
15403
+ ...docData.tableSource ?? {},
15404
+ ...hfDoc.tableSource
15405
+ };
15406
+ }
14190
15407
  if (hfDoc.body && hfQueue.length > 0) {
14191
15408
  const hfStream = hfDoc.body.dataStream;
14192
15409
  const hfCustomBlocks = [];
14193
15410
  let hq = 0;
14194
15411
  for (let i = 0; i < hfStream.length && hq < hfQueue.length; i++) {
14195
15412
  if (hfStream[i] === import_core7.DataStreamTreeTokenType.CUSTOM_BLOCK) {
15413
+ const blkId = hfQueue[hq++].blockId;
14196
15414
  hfCustomBlocks.push({
14197
15415
  startIndex: i,
14198
- blockId: hfQueue[hq++].blockId,
15416
+ blockId: blkId,
14199
15417
  blockType: 0
14200
15418
  });
15419
+ const drw = collectedDrawings[blkId];
15420
+ if (drw) {
15421
+ drw.isMultiTransform = import_core7.BooleanNumber.TRUE;
15422
+ drw.transforms = Array.isArray(drw.transforms) && drw.transforms.length > 0 ? drw.transforms : drw.transform ? [import_core7.Tools.deepClone(drw.transform)] : [];
15423
+ }
14201
15424
  }
14202
15425
  }
14203
15426
  hfDoc.body.customBlocks = hfCustomBlocks;
14204
15427
  docData.drawings = collectedDrawings;
14205
15428
  docData.drawingsOrder = Object.keys(collectedDrawings);
14206
15429
  }
14207
- return hfDoc.body ?? null;
15430
+ if (!hfDoc.body) return null;
15431
+ return {
15432
+ body: hfDoc.body,
15433
+ ...hfDoc.tableSource && Object.keys(hfDoc.tableSource).length > 0 ? { tableSource: hfDoc.tableSource } : {}
15434
+ };
14208
15435
  };
14209
15436
  const parsedHeaders = {};
14210
15437
  for (const hm of xml.matchAll(/<w:headerReference\b([^>]*)\/?>/g)) {
@@ -14213,16 +15440,28 @@ async function parseDocxBytesWithReport(bytes, title = "Imported Word Document")
14213
15440
  if (!rId) continue;
14214
15441
  if (relsMap.get(rId)?.endsWith("header_wm.xml")) continue;
14215
15442
  const rawType = (attrs.match(/w:type="([^"]+)"/)?.[1] || "default").toLowerCase();
14216
- const headerBody = parseHfBodyFromZip(rId, "word/header1.xml");
14217
- if (!headerBody) continue;
15443
+ const headerRes = parseHfBodyFromZip(rId, "word/header1.xml");
15444
+ if (!headerRes) continue;
14218
15445
  if (rawType === "first") {
14219
- parsedHeaders.firstPageHeader = { headerId: "firstPageHeader", body: headerBody };
15446
+ parsedHeaders.firstPageHeader = {
15447
+ headerId: "firstPageHeader",
15448
+ body: headerRes.body,
15449
+ ...headerRes.tableSource ? { tableSource: headerRes.tableSource } : {}
15450
+ };
14220
15451
  docData.documentStyle.firstPageHeaderId = "firstPageHeader";
14221
15452
  } else if (rawType === "even") {
14222
- parsedHeaders.evenPageHeader = { headerId: "evenPageHeader", body: headerBody };
15453
+ parsedHeaders.evenPageHeader = {
15454
+ headerId: "evenPageHeader",
15455
+ body: headerRes.body,
15456
+ ...headerRes.tableSource ? { tableSource: headerRes.tableSource } : {}
15457
+ };
14223
15458
  docData.documentStyle.evenPageHeaderId = "evenPageHeader";
14224
15459
  } else {
14225
- parsedHeaders.defaultHeader = { headerId: "defaultHeader", body: headerBody };
15460
+ parsedHeaders.defaultHeader = {
15461
+ headerId: "defaultHeader",
15462
+ body: headerRes.body,
15463
+ ...headerRes.tableSource ? { tableSource: headerRes.tableSource } : {}
15464
+ };
14226
15465
  docData.documentStyle.defaultHeaderId = "defaultHeader";
14227
15466
  }
14228
15467
  }
@@ -14235,30 +15474,78 @@ async function parseDocxBytesWithReport(bytes, title = "Imported Word Document")
14235
15474
  const rId = attrs.match(/r:id="([^"]+)"/)?.[1];
14236
15475
  if (!rId) continue;
14237
15476
  const rawType = (attrs.match(/w:type="([^"]+)"/)?.[1] || "default").toLowerCase();
14238
- const footerBody = parseHfBodyFromZip(rId, "word/footer1.xml");
14239
- if (!footerBody) continue;
15477
+ const footerRes = parseHfBodyFromZip(rId, "word/footer1.xml");
15478
+ if (!footerRes) continue;
14240
15479
  if (rawType === "first") {
14241
- parsedFooters.firstPageFooter = { footerId: "firstPageFooter", body: footerBody };
15480
+ parsedFooters.firstPageFooter = {
15481
+ footerId: "firstPageFooter",
15482
+ body: footerRes.body,
15483
+ ...footerRes.tableSource ? { tableSource: footerRes.tableSource } : {}
15484
+ };
14242
15485
  docData.documentStyle.firstPageFooterId = "firstPageFooter";
14243
15486
  } else if (rawType === "even") {
14244
- parsedFooters.evenPageFooter = { footerId: "evenPageFooter", body: footerBody };
15487
+ parsedFooters.evenPageFooter = {
15488
+ footerId: "evenPageFooter",
15489
+ body: footerRes.body,
15490
+ ...footerRes.tableSource ? { tableSource: footerRes.tableSource } : {}
15491
+ };
14245
15492
  docData.documentStyle.evenPageFooterId = "evenPageFooter";
14246
15493
  } else {
14247
- parsedFooters.defaultFooter = { footerId: "defaultFooter", body: footerBody };
15494
+ parsedFooters.defaultFooter = {
15495
+ footerId: "defaultFooter",
15496
+ body: footerRes.body,
15497
+ ...footerRes.tableSource ? { tableSource: footerRes.tableSource } : {}
15498
+ };
14248
15499
  docData.documentStyle.defaultFooterId = "defaultFooter";
14249
15500
  }
14250
15501
  }
14251
15502
  if (Object.keys(parsedFooters).length > 0) {
14252
15503
  docData.footers = parsedFooters;
14253
15504
  }
14254
- if (/<w:titlePg(?:\s|\/|>)/.test(xml) || docData.documentStyle.firstPageHeaderId || docData.documentStyle.firstPageFooterId) {
15505
+ const titlePgTag = sectPrXml.match(/<w:titlePg\b([^>]*)\/?>/) ?? xml.match(/<w:titlePg\b([^>]*)\/?>/);
15506
+ const hasActiveTitlePg = Boolean(
15507
+ titlePgTag && !/\bw:val="(?:0|false|off)"/i.test(titlePgTag[1] || "")
15508
+ );
15509
+ if (hasActiveTitlePg) {
14255
15510
  docData.documentStyle.useFirstPageHeaderFooter = import_core7.BooleanNumber.TRUE;
15511
+ } else if (titlePgTag || docData.documentStyle.firstPageHeaderId || docData.documentStyle.firstPageFooterId) {
15512
+ docData.documentStyle.useFirstPageHeaderFooter = import_core7.BooleanNumber.FALSE;
14256
15513
  }
14257
15514
  const settingsBytes = entries.get("word/settings.xml");
14258
15515
  const settingsXml = settingsBytes ? decoder.decode(settingsBytes) : "";
14259
- if (/<w:evenAndOddHeaders(?:\s|\/|>)/.test(settingsXml) || /<w:evenAndOddHeaders(?:\s|\/|>)/.test(xml) || docData.documentStyle.evenPageHeaderId || docData.documentStyle.evenPageFooterId) {
15516
+ const evenOddTag = settingsXml.match(/<w:evenAndOddHeaders\b([^>]*)\/?>/) ?? xml.match(/<w:evenAndOddHeaders\b([^>]*)\/?>/);
15517
+ const hasActiveEvenOdd = Boolean(
15518
+ evenOddTag && !/\bw:val="(?:0|false|off)"/i.test(evenOddTag[1] || "")
15519
+ );
15520
+ if (hasActiveEvenOdd || !evenOddTag && (docData.documentStyle.evenPageHeaderId || docData.documentStyle.evenPageFooterId)) {
14260
15521
  docData.documentStyle.evenAndOddHeaders = import_core7.BooleanNumber.TRUE;
14261
15522
  }
15523
+ if (docData.body?.sectionBreaks?.length && docData.documentStyle) {
15524
+ const ds = docData.documentStyle;
15525
+ for (const sb of docData.body.sectionBreaks) {
15526
+ if (ds.useFirstPageHeaderFooter !== void 0) {
15527
+ sb.useFirstPageHeaderFooter = ds.useFirstPageHeaderFooter;
15528
+ }
15529
+ if (ds.evenAndOddHeaders !== void 0) {
15530
+ sb.evenAndOddHeaders = ds.evenAndOddHeaders;
15531
+ }
15532
+ if (ds.defaultHeaderId !== void 0) sb.defaultHeaderId = ds.defaultHeaderId;
15533
+ if (ds.defaultFooterId !== void 0) sb.defaultFooterId = ds.defaultFooterId;
15534
+ if (ds.firstPageHeaderId !== void 0) sb.firstPageHeaderId = ds.firstPageHeaderId;
15535
+ if (ds.firstPageFooterId !== void 0) sb.firstPageFooterId = ds.firstPageFooterId;
15536
+ if (ds.evenPageHeaderId !== void 0) sb.evenPageHeaderId = ds.evenPageHeaderId;
15537
+ if (ds.evenPageFooterId !== void 0) sb.evenPageFooterId = ds.evenPageFooterId;
15538
+ if (ds.marginTop !== void 0) sb.marginTop = ds.marginTop;
15539
+ if (ds.marginBottom !== void 0) sb.marginBottom = ds.marginBottom;
15540
+ if (ds.marginLeft !== void 0) sb.marginLeft = ds.marginLeft;
15541
+ if (ds.marginRight !== void 0) sb.marginRight = ds.marginRight;
15542
+ if (ds.marginHeader !== void 0) sb.marginHeader = ds.marginHeader;
15543
+ if (ds.marginFooter !== void 0) sb.marginFooter = ds.marginFooter;
15544
+ if (ds.gridType !== void 0) sb.gridType = ds.gridType;
15545
+ if (ds.linePitch !== void 0) sb.linePitch = ds.linePitch;
15546
+ if (ds.charSpace !== void 0) sb.charSpace = ds.charSpace;
15547
+ }
15548
+ }
14262
15549
  const parsedPrintCfg = {};
14263
15550
  const headerWmBytes = entries.get("word/header_wm.xml");
14264
15551
  if (headerWmBytes) {
@@ -14364,7 +15651,6 @@ async function parseDocxBytesWithReport(bytes, title = "Imported Word Document")
14364
15651
  const xmlParaPagination = {};
14365
15652
  const xmlParaDirections = {};
14366
15653
  const xmlSectionOrientations = {};
14367
- const trailingSectMatch = bodyXml.match(/<w:sectPr(?=[\s>])(?![\s\S]*<w:sectPr)([\s\S]*?)<\/w:sectPr>/);
14368
15654
  if (trailingSectMatch) {
14369
15655
  const tPgSz = trailingSectMatch[1].match(/<w:pgSz\b([^>]*)\/?>/);
14370
15656
  if (tPgSz && /\bw:orient="landscape"/.test(tPgSz[1] || "")) {
@@ -14790,7 +16076,12 @@ async function parseDocxBytesWithReport(bytes, title = "Imported Word Document")
14790
16076
  }
14791
16077
  }
14792
16078
  renumberDocNotesInPlace(docData);
14793
- const warnings = scanUnsupportedDocxFeatures(xml, warningsCounter.floatingImages);
16079
+ normalizeDocDrawingsAndPluginResource(docData);
16080
+ const warnings = scanUnsupportedDocxFeatures(
16081
+ xml,
16082
+ warningsCounter.floatingImages,
16083
+ warningsCounter.dynamicFields ?? 0
16084
+ );
14794
16085
  return {
14795
16086
  documentData: docData,
14796
16087
  warnings
@@ -14858,6 +16149,7 @@ function updateDocImageTransformInSnapshot(sourceSnapshot, drawingId, spec) {
14858
16149
  [drawingId]: mergedTransform
14859
16150
  }
14860
16151
  });
16152
+ normalizeDocDrawingsAndPluginResource(nextSnapshot);
14861
16153
  return nextSnapshot;
14862
16154
  }
14863
16155
  function getDocImageTransformFromSnapshot(snapshot, drawingId) {
@@ -15628,6 +16920,7 @@ function parseFieldInstrString(rawInstr) {
15628
16920
  const allowed = [
15629
16921
  "PAGE",
15630
16922
  "NUMPAGES",
16923
+ "SECTIONPAGES",
15631
16924
  "DATE",
15632
16925
  "TIME",
15633
16926
  "AUTHOR",
@@ -15649,7 +16942,8 @@ function evaluateSingleFieldValue(snapshot, fieldType, instructionArgs, seqCount
15649
16942
  switch (fieldType) {
15650
16943
  case "PAGE":
15651
16944
  return String(context?.page ?? 1);
15652
- case "NUMPAGES": {
16945
+ case "NUMPAGES":
16946
+ case "SECTIONPAGES": {
15653
16947
  if (typeof context?.numPages === "number") return String(context.numPages);
15654
16948
  const stream = snapshot.body?.dataStream ?? "";
15655
16949
  let breaks = 1;
@@ -15807,24 +17101,37 @@ function getDocCustomPropertiesFromSnapshot(snapshot) {
15807
17101
  };
15808
17102
  }
15809
17103
  function listDocFields(snapshot) {
15810
- const body = snapshot?.body;
15811
- const stream = body?.dataStream ?? "";
15812
17104
  const out = [];
15813
- for (const r of body?.customRanges ?? []) {
15814
- const props = r.properties;
15815
- if (props?.yudaoBlockKind === "docField" && props.field) {
15816
- const f = props.field;
15817
- const liveVal = stream.slice(r.startIndex, r.endIndex + 1).replace(/[\r\n\u0000-\u001F]/g, "");
15818
- out.push({
15819
- ...import_core8.Tools.deepClone(f),
15820
- id: r.rangeId,
15821
- value: liveVal || f.value,
15822
- startIndex: r.startIndex,
15823
- endIndex: r.endIndex
15824
- });
17105
+ const scanStoryBody = (storyBody, segmentId) => {
17106
+ if (!storyBody) return;
17107
+ const stream = storyBody.dataStream ?? "";
17108
+ const items = [];
17109
+ for (const r of storyBody.customRanges ?? []) {
17110
+ const props = r.properties;
17111
+ if (props?.yudaoBlockKind === "docField" && props.field) {
17112
+ const f = props.field;
17113
+ const liveVal = stream.slice(r.startIndex, r.endIndex + 1).replace(/[\r\n\u0000-\u001F]/g, "");
17114
+ items.push({
17115
+ ...import_core8.Tools.deepClone(f),
17116
+ id: r.rangeId,
17117
+ value: liveVal || f.value,
17118
+ ...segmentId ? { segmentId } : {},
17119
+ startIndex: r.startIndex,
17120
+ endIndex: r.endIndex
17121
+ });
17122
+ }
15825
17123
  }
17124
+ items.sort((a, b) => (a.startIndex ?? 0) - (b.startIndex ?? 0));
17125
+ out.push(...items);
17126
+ };
17127
+ scanStoryBody(snapshot?.body, void 0);
17128
+ for (const [hdrId, hdr] of Object.entries(snapshot?.headers ?? {})) {
17129
+ scanStoryBody(hdr?.body, hdrId);
15826
17130
  }
15827
- return out.sort((a, b) => (a.startIndex ?? 0) - (b.startIndex ?? 0));
17131
+ for (const [ftrId, ftr] of Object.entries(snapshot?.footers ?? {})) {
17132
+ scanStoryBody(ftr?.body, ftrId);
17133
+ }
17134
+ return out;
15828
17135
  }
15829
17136
  function updateAllDocFieldsInSnapshot(snapshot, context) {
15830
17137
  if (!snapshot.body) return false;
@@ -15834,7 +17141,8 @@ function updateAllDocFieldsInSnapshot(snapshot, context) {
15834
17141
  const seqCounters = /* @__PURE__ */ new Map();
15835
17142
  for (const fld of initialFields) {
15836
17143
  if (fld.fieldType === "REF") continue;
15837
- const liveBody = snapshot.body;
17144
+ const liveBody = resolveSegmentBodyInSnapshot(snapshot, fld.segmentId);
17145
+ if (!liveBody) continue;
15838
17146
  const range = (liveBody.customRanges ?? []).find(
15839
17147
  (r) => r.rangeId === fld.id && r.properties?.yudaoBlockKind === "docField"
15840
17148
  );
@@ -15854,7 +17162,7 @@ function updateAllDocFieldsInSnapshot(snapshot, context) {
15854
17162
  endIndex: range.startIndex + Math.max(0, nextVal.length - 1)
15855
17163
  };
15856
17164
  if (curVal !== nextVal) {
15857
- snapshot.body = spliceDocumentBodySpan(
17165
+ const nextBody = spliceDocumentBodySpan(
15858
17166
  liveBody,
15859
17167
  range.startIndex,
15860
17168
  range.endIndex,
@@ -15865,9 +17173,10 @@ function updateAllDocFieldsInSnapshot(snapshot, context) {
15865
17173
  yudaoBlockKind: "docField",
15866
17174
  field: import_core8.Tools.deepClone(updatedEntry)
15867
17175
  },
15868
- textStyle: { cl: { rgb: "#2C53F1" }, bg: { rgb: "#F3F5FF" } }
17176
+ textStyle: fld.preserveStyle ? void 0 : { cl: { rgb: "#2C53F1" }, bg: { rgb: "#F3F5FF" } }
15869
17177
  }
15870
17178
  );
17179
+ writeSegmentBodyInSnapshot(snapshot, nextBody, fld.segmentId);
15871
17180
  changed = true;
15872
17181
  }
15873
17182
  }
@@ -15881,7 +17190,8 @@ function updateAllDocFieldsInSnapshot(snapshot, context) {
15881
17190
  }
15882
17191
  for (const fld of listDocFields(snapshot)) {
15883
17192
  if (fld.fieldType !== "REF") continue;
15884
- const liveBody = snapshot.body;
17193
+ const liveBody = resolveSegmentBodyInSnapshot(snapshot, fld.segmentId);
17194
+ if (!liveBody) continue;
15885
17195
  const range = (liveBody.customRanges ?? []).find(
15886
17196
  (r) => r.rangeId === fld.id && r.properties?.yudaoBlockKind === "docField"
15887
17197
  );
@@ -15901,7 +17211,7 @@ function updateAllDocFieldsInSnapshot(snapshot, context) {
15901
17211
  endIndex: range.startIndex + Math.max(0, nextVal.length - 1)
15902
17212
  };
15903
17213
  if (curVal !== nextVal) {
15904
- snapshot.body = spliceDocumentBodySpan(
17214
+ const nextBody = spliceDocumentBodySpan(
15905
17215
  liveBody,
15906
17216
  range.startIndex,
15907
17217
  range.endIndex,
@@ -15912,9 +17222,10 @@ function updateAllDocFieldsInSnapshot(snapshot, context) {
15912
17222
  yudaoBlockKind: "docField",
15913
17223
  field: import_core8.Tools.deepClone(updatedEntry)
15914
17224
  },
15915
- textStyle: { cl: { rgb: "#2C53F1" }, bg: { rgb: "#F3F5FF" } }
17225
+ textStyle: fld.preserveStyle ? void 0 : { cl: { rgb: "#2C53F1" }, bg: { rgb: "#F3F5FF" } }
15916
17226
  }
15917
17227
  );
17228
+ writeSegmentBodyInSnapshot(snapshot, nextBody, fld.segmentId);
15918
17229
  changed = true;
15919
17230
  }
15920
17231
  }
@@ -21549,6 +22860,121 @@ function writeDocTemplateMetadataToSnapshot(snapshot, metadata) {
21549
22860
  snapshot.resources = resources;
21550
22861
  return snapshot;
21551
22862
  }
22863
+ var WRAP_TEXT_STRING_TO_CODE = {
22864
+ bothSides: 0,
22865
+ left: 1,
22866
+ right: 2,
22867
+ largest: 3
22868
+ };
22869
+ function normalizeDocDrawingsAndPluginResource(snapshot) {
22870
+ if (!snapshot || typeof snapshot !== "object") return snapshot;
22871
+ for (const segMap of [snapshot.headers, snapshot.footers]) {
22872
+ if (!segMap || typeof segMap !== "object") continue;
22873
+ for (const seg of Object.values(segMap)) {
22874
+ const segTables = seg?.body?.tables;
22875
+ if (!Array.isArray(segTables) || segTables.length === 0) continue;
22876
+ for (const tbl of segTables) {
22877
+ const tid = tbl?.tableId;
22878
+ if (!tid) continue;
22879
+ if (snapshot.tableSource?.[tid] && !seg.tableSource?.[tid]) {
22880
+ seg.tableSource = { ...seg.tableSource ?? {}, [tid]: import_core13.Tools.deepClone(snapshot.tableSource[tid]) };
22881
+ } else if (seg.tableSource?.[tid] && !snapshot.tableSource?.[tid]) {
22882
+ snapshot.tableSource = {
22883
+ ...snapshot.tableSource ?? {},
22884
+ [tid]: import_core13.Tools.deepClone(seg.tableSource[tid])
22885
+ };
22886
+ }
22887
+ }
22888
+ }
22889
+ }
22890
+ const existingResources = snapshot.resources;
22891
+ const pluginIdx = Array.isArray(existingResources) ? existingResources.findIndex((r) => r.name === DOC_DRAWING_PLUGIN_RESOURCE) : -1;
22892
+ let parsedPlugin;
22893
+ if (pluginIdx >= 0 && existingResources?.[pluginIdx]?.data) {
22894
+ try {
22895
+ const raw = JSON.parse(existingResources[pluginIdx].data);
22896
+ if (raw && typeof raw === "object") {
22897
+ parsedPlugin = raw;
22898
+ }
22899
+ } catch {
22900
+ parsedPlugin = void 0;
22901
+ }
22902
+ }
22903
+ const snapDrawings = snapshot.drawings && typeof snapshot.drawings === "object" ? snapshot.drawings : void 0;
22904
+ const snapKeys = Object.keys(snapDrawings ?? {});
22905
+ const pluginData = parsedPlugin?.data && typeof parsedPlugin.data === "object" ? parsedPlugin.data : {};
22906
+ const pluginKeys = Object.keys(pluginData);
22907
+ if (snapKeys.length === 0 && pluginKeys.length === 0) {
22908
+ if (pluginIdx >= 0 && Array.isArray(existingResources)) {
22909
+ snapshot.resources = existingResources.filter((r) => r.name !== DOC_DRAWING_PLUGIN_RESOURCE);
22910
+ }
22911
+ return snapshot;
22912
+ }
22913
+ const mergedDrawings = snapKeys.length > 0 ? { ...import_core13.Tools.deepClone(pluginData), ...import_core13.Tools.deepClone(snapDrawings) } : import_core13.Tools.deepClone(pluginData);
22914
+ const hfBlockIds = /* @__PURE__ */ new Set();
22915
+ for (const hdr of Object.values(snapshot.headers ?? {})) {
22916
+ for (const blk of hdr?.body?.customBlocks ?? []) {
22917
+ if (blk?.blockId) hfBlockIds.add(blk.blockId);
22918
+ }
22919
+ }
22920
+ for (const ftr of Object.values(snapshot.footers ?? {})) {
22921
+ for (const blk of ftr?.body?.customBlocks ?? []) {
22922
+ if (blk?.blockId) hfBlockIds.add(blk.blockId);
22923
+ }
22924
+ }
22925
+ const unitId = typeof snapshot.id === "string" && snapshot.id.length > 0 ? snapshot.id : void 0;
22926
+ for (const [drawingId, drw] of Object.entries(mergedDrawings)) {
22927
+ if (!drw || typeof drw !== "object") continue;
22928
+ drw.drawingId = drw.drawingId || drawingId;
22929
+ if (unitId) {
22930
+ drw.unitId = unitId;
22931
+ drw.subUnitId = unitId;
22932
+ }
22933
+ if (typeof drw.wrapText === "string" && drw.wrapText in WRAP_TEXT_STRING_TO_CODE) {
22934
+ drw.wrapText = WRAP_TEXT_STRING_TO_CODE[drw.wrapText];
22935
+ }
22936
+ if (drw.docTransform && typeof drw.docTransform === "object" && typeof drw.docTransform.wrapText === "string" && drw.docTransform.wrapText in WRAP_TEXT_STRING_TO_CODE) {
22937
+ drw.docTransform.wrapText = WRAP_TEXT_STRING_TO_CODE[drw.docTransform.wrapText];
22938
+ }
22939
+ if (hfBlockIds.has(drawingId)) {
22940
+ drw.isMultiTransform = import_core13.BooleanNumber.TRUE;
22941
+ drw.transforms = Array.isArray(drw.transforms) && drw.transforms.length > 0 ? drw.transforms : drw.transform ? [import_core13.Tools.deepClone(drw.transform)] : [];
22942
+ }
22943
+ }
22944
+ snapshot.drawings = mergedDrawings;
22945
+ const seedOrder = Array.isArray(snapshot.drawingsOrder) && snapshot.drawingsOrder.length > 0 ? snapshot.drawingsOrder : Array.isArray(parsedPlugin?.order) ? parsedPlugin.order : [];
22946
+ const seenOrder = /* @__PURE__ */ new Set();
22947
+ const normalizedOrder = [];
22948
+ for (const id of seedOrder) {
22949
+ if (typeof id === "string" && id in mergedDrawings && !seenOrder.has(id)) {
22950
+ seenOrder.add(id);
22951
+ normalizedOrder.push(id);
22952
+ }
22953
+ }
22954
+ for (const id of Object.keys(mergedDrawings)) {
22955
+ if (!seenOrder.has(id)) {
22956
+ seenOrder.add(id);
22957
+ normalizedOrder.push(id);
22958
+ }
22959
+ }
22960
+ snapshot.drawingsOrder = normalizedOrder;
22961
+ const serializedPluginEntry = {
22962
+ id: DOC_DRAWING_PLUGIN_RESOURCE,
22963
+ name: DOC_DRAWING_PLUGIN_RESOURCE,
22964
+ data: JSON.stringify({
22965
+ data: snapshot.drawings,
22966
+ order: snapshot.drawingsOrder
22967
+ })
22968
+ };
22969
+ const nextResources = [...existingResources ?? []];
22970
+ if (pluginIdx >= 0) {
22971
+ nextResources[pluginIdx] = serializedPluginEntry;
22972
+ } else {
22973
+ nextResources.push(serializedPluginEntry);
22974
+ }
22975
+ snapshot.resources = nextResources;
22976
+ return snapshot;
22977
+ }
21552
22978
  function getLocalTodayIso() {
21553
22979
  const now = /* @__PURE__ */ new Date();
21554
22980
  const y = now.getFullYear();
@@ -21695,6 +23121,20 @@ function extractAnchorTypography(ts) {
21695
23121
  out.ff = ts.ff;
21696
23122
  has = true;
21697
23123
  }
23124
+ if (ts.eastAsiaFontFamily !== void 0) {
23125
+ out.eastAsiaFontFamily = ts.eastAsiaFontFamily;
23126
+ has = true;
23127
+ }
23128
+ if (ts.fontHint !== void 0) {
23129
+ out.fontHint = ts.fontHint;
23130
+ has = true;
23131
+ }
23132
+ if (ts.yudaoRFonts !== void 0) {
23133
+ out.yudaoRFonts = import_core13.Tools.deepClone(
23134
+ ts.yudaoRFonts
23135
+ );
23136
+ has = true;
23137
+ }
21698
23138
  if (ts.fs !== void 0) {
21699
23139
  out.fs = ts.fs;
21700
23140
  has = true;
@@ -22935,6 +24375,15 @@ function applyPictureOrSignatureSdtValueInSnapshot(snapshot, ctrl, rawImageValue
22935
24375
  textStyle: style
22936
24376
  });
22937
24377
  writeSegmentBodyInSnapshot(snapshot, nextBody2, targetSegId);
24378
+ if (prevBlockId && snapshot.drawings && prevBlockId in snapshot.drawings) {
24379
+ const nextDrawings = { ...snapshot.drawings };
24380
+ delete nextDrawings[prevBlockId];
24381
+ snapshot.drawings = nextDrawings;
24382
+ if (Array.isArray(snapshot.drawingsOrder)) {
24383
+ snapshot.drawingsOrder = snapshot.drawingsOrder.filter((id) => id !== prevBlockId);
24384
+ }
24385
+ normalizeDocDrawingsAndPluginResource(snapshot);
24386
+ }
22938
24387
  return true;
22939
24388
  }
22940
24389
  const blockId = prevBlockId || `sdt_img_${ctrl.id}`;
@@ -22996,6 +24445,7 @@ function applyPictureOrSignatureSdtValueInSnapshot(snapshot, ctrl, rawImageValue
22996
24445
  const order = [...snapshot.drawingsOrder ?? []];
22997
24446
  if (!order.includes(blockId)) order.push(blockId);
22998
24447
  snapshot.drawingsOrder = order;
24448
+ normalizeDocDrawingsAndPluginResource(snapshot);
22999
24449
  return true;
23000
24450
  }
23001
24451
  function parseTableRowsInStream(dataStream, tableStartIndex, tableEndExclusive) {
@@ -23430,6 +24880,36 @@ function expandDocTableRowLoopsInPlace(nextSnapshot, data, explicitLoops) {
23430
24880
  tblSource.tableRows[0] = { ...tblSource.tableRows[0], isFirstRow: import_core13.BooleanNumber.TRUE };
23431
24881
  }
23432
24882
  }
24883
+ if (snapMeta.tableCellProperties) {
24884
+ const tblPrefix = `${tblRef.tableId}:`;
24885
+ const hasTblCellProps = Object.keys(snapMeta.tableCellProperties).some(
24886
+ (k) => k.startsWith(tblPrefix)
24887
+ );
24888
+ if (hasTblCellProps) {
24889
+ const shiftedCellProps = {};
24890
+ for (const [k, v] of Object.entries(snapMeta.tableCellProperties)) {
24891
+ if (!k.startsWith(tblPrefix)) {
24892
+ shiftedCellProps[k] = v;
24893
+ continue;
24894
+ }
24895
+ const rest = k.slice(tblPrefix.length);
24896
+ const sepIdx = rest.indexOf(":");
24897
+ if (sepIdx <= 0) {
24898
+ shiftedCellProps[k] = v;
24899
+ continue;
24900
+ }
24901
+ const oldRow = Number(rest.slice(0, sepIdx));
24902
+ const colPart = rest.slice(sepIdx + 1);
24903
+ if (!Number.isFinite(oldRow) || oldRow === rIdx) {
24904
+ continue;
24905
+ }
24906
+ const newRow = oldRow > rIdx ? oldRow - 1 : oldRow;
24907
+ shiftedCellProps[`${tblPrefix}${newRow}:${colPart}`] = v;
24908
+ }
24909
+ snapMeta.tableCellProperties = shiftedCellProps;
24910
+ metaChanged = true;
24911
+ }
24912
+ }
23433
24913
  continue;
23434
24914
  }
23435
24915
  const effectiveRows = items.length > 0 ? items : [null];
@@ -23600,6 +25080,49 @@ function expandDocTableRowLoopsInPlace(nextSnapshot, data, explicitLoops) {
23600
25080
  });
23601
25081
  tblSource.tableRows.splice(rIdx, 1, ...clonedRowDefs);
23602
25082
  }
25083
+ if (snapMeta.tableCellProperties && effectiveRows.length !== 1) {
25084
+ const tblPrefix = `${tblRef.tableId}:`;
25085
+ const hasTblCellProps = Object.keys(snapMeta.tableCellProperties).some(
25086
+ (k) => k.startsWith(tblPrefix)
25087
+ );
25088
+ if (hasTblCellProps) {
25089
+ const rowDelta = effectiveRows.length - 1;
25090
+ const shiftedCellProps = {};
25091
+ const tplRowCellProps = [];
25092
+ for (const [k, v] of Object.entries(snapMeta.tableCellProperties)) {
25093
+ if (!k.startsWith(tblPrefix)) {
25094
+ shiftedCellProps[k] = v;
25095
+ continue;
25096
+ }
25097
+ const rest = k.slice(tblPrefix.length);
25098
+ const sepIdx = rest.indexOf(":");
25099
+ if (sepIdx <= 0) {
25100
+ shiftedCellProps[k] = v;
25101
+ continue;
25102
+ }
25103
+ const oldRow = Number(rest.slice(0, sepIdx));
25104
+ const colPart = rest.slice(sepIdx + 1);
25105
+ if (!Number.isFinite(oldRow)) {
25106
+ shiftedCellProps[k] = v;
25107
+ continue;
25108
+ }
25109
+ if (oldRow === rIdx) {
25110
+ tplRowCellProps.push({ colPart, prop: v });
25111
+ } else if (oldRow > rIdx) {
25112
+ shiftedCellProps[`${tblPrefix}${oldRow + rowDelta}:${colPart}`] = v;
25113
+ } else {
25114
+ shiftedCellProps[k] = v;
25115
+ }
25116
+ }
25117
+ for (let cloneIdx = 0; cloneIdx < effectiveRows.length; cloneIdx++) {
25118
+ for (const { colPart, prop } of tplRowCellProps) {
25119
+ shiftedCellProps[`${tblPrefix}${rIdx + cloneIdx}:${colPart}`] = import_core13.Tools.deepClone(prop);
25120
+ }
25121
+ }
25122
+ snapMeta.tableCellProperties = shiftedCellProps;
25123
+ metaChanged = true;
25124
+ }
25125
+ }
23603
25126
  }
23604
25127
  }
23605
25128
  if (consumedLoopKeys.size > 0 || metaChanged) {
@@ -23608,10 +25131,12 @@ function expandDocTableRowLoopsInPlace(nextSnapshot, data, explicitLoops) {
23608
25131
  delete nextLoops[k];
23609
25132
  }
23610
25133
  const nextRepeatHeaders = snapMeta.tableRepeatHeaders ? { ...snapMeta.tableRepeatHeaders } : void 0;
25134
+ const nextCellProps = snapMeta.tableCellProperties ? { ...snapMeta.tableCellProperties } : void 0;
23611
25135
  writeDocTemplateMetadataToSnapshot(nextSnapshot, {
23612
25136
  ...snapMeta,
23613
25137
  tableRowLoops: Object.keys(nextLoops).length > 0 ? nextLoops : void 0,
23614
- tableRepeatHeaders: nextRepeatHeaders && Object.keys(nextRepeatHeaders).length > 0 ? nextRepeatHeaders : void 0
25138
+ tableRepeatHeaders: nextRepeatHeaders && Object.keys(nextRepeatHeaders).length > 0 ? nextRepeatHeaders : void 0,
25139
+ tableCellProperties: nextCellProps && Object.keys(nextCellProps).length > 0 ? nextCellProps : void 0
23615
25140
  });
23616
25141
  }
23617
25142
  }
@@ -23941,6 +25466,10 @@ function fillDatasetIntoDocSnapshot(snapshot, data, options) {
23941
25466
  }
23942
25467
  }
23943
25468
  }
25469
+ const hasDrawingsToNormalize = nextSnapshot.drawings && Object.keys(nextSnapshot.drawings).length > 0 || (nextSnapshot.resources ?? []).some((r) => r.name === DOC_DRAWING_PLUGIN_RESOURCE);
25470
+ if (hasDrawingsToNormalize) {
25471
+ normalizeDocDrawingsAndPluginResource(nextSnapshot);
25472
+ }
23944
25473
  return nextSnapshot;
23945
25474
  }
23946
25475
  function makeDefaultCellBorder() {
@@ -24013,14 +25542,26 @@ function buildStructuredDocData(params) {
24013
25542
  ...seg.docField.instructionArgs ? { instructionArgs: seg.docField.instructionArgs } : {},
24014
25543
  instrText: seg.docField.instrText,
24015
25544
  value: valStr,
25545
+ ...seg.docField.sourceKind ? { sourceKind: seg.docField.sourceKind } : {},
25546
+ ...seg.docField.preserveStyle ? { preserveStyle: true } : {},
24016
25547
  startIndex: st,
24017
25548
  endIndex: ed - 1
24018
25549
  };
24019
- textRuns.push({
24020
- st,
24021
- ed,
24022
- ts: { cl: { rgb: "#2C53F1" }, bg: { rgb: "#F3F5FF" } }
24023
- });
25550
+ if (seg.docField.preserveStyle) {
25551
+ if (seg.docField.style && ed > st) {
25552
+ textRuns.push({
25553
+ st,
25554
+ ed,
25555
+ ts: import_core13.Tools.deepClone(seg.docField.style)
25556
+ });
25557
+ }
25558
+ } else {
25559
+ textRuns.push({
25560
+ st,
25561
+ ed,
25562
+ ts: { cl: { rgb: "#2C53F1" }, bg: { rgb: "#F3F5FF" } }
25563
+ });
25564
+ }
24024
25565
  customRanges.push({
24025
25566
  rangeId: fldId,
24026
25567
  rangeType: import_core13.CustomRangeType.CUSTOM,
@@ -24334,6 +25875,7 @@ function buildStructuredDocData(params) {
24334
25875
  paragraphs.push({
24335
25876
  startIndex: pIdx,
24336
25877
  paragraphId: `p_${(0, import_core13.generateRandomId)(6)}`,
25878
+ ...para.styleId ? { styleId: para.styleId } : {},
24337
25879
  ...para.paragraphStyle ? { paragraphStyle: para.paragraphStyle } : {},
24338
25880
  ...para.bullet ? { bullet: para.bullet } : {}
24339
25881
  });
@@ -24403,6 +25945,9 @@ function buildStructuredDocData(params) {
24403
25945
  },
24404
25946
  rowSpan: cellObj.rowSpan ?? 1,
24405
25947
  columnSpan: cellObj.colSpan ?? 1,
25948
+ ...cellObj.tcWidthType ? { tcWidthType: cellObj.tcWidthType } : {},
25949
+ ...cellObj.cellSize ? { size: import_core13.Tools.deepClone(cellObj.cellSize) } : {},
25950
+ ...cellObj.yudaoTcWidthPct !== void 0 ? { yudaoTcWidthPct: cellObj.yudaoTcWidthPct } : {},
24406
25951
  ...cellObj.backgroundRgb ? { backgroundColor: { rgb: cellObj.backgroundRgb } } : {},
24407
25952
  borderTop: toCellBorderObj(cellObj.borders?.top),
24408
25953
  borderBottom: toCellBorderObj(cellObj.borders?.bottom),
@@ -24415,12 +25960,14 @@ function buildStructuredDocData(params) {
24415
25960
  repeatHeaderMeta[tableId] = block.headerRowCount;
24416
25961
  }
24417
25962
  dataStream += import_core13.DataStreamTreeTokenType.TABLE_ROW_END;
25963
+ const rMeta = block.rowMeta?.[rIdx];
24418
25964
  tableRows.push({
24419
25965
  tableCells: cellDefs,
24420
- trHeight: {
25966
+ trHeight: rMeta?.trHeight ? import_core13.Tools.deepClone(rMeta.trHeight) : {
24421
25967
  val: { v: 24, u: import_core13.NumberUnitType.POINT },
24422
25968
  hRule: import_core13.TableRowHeightRule.AT_LEAST
24423
25969
  },
25970
+ ...rMeta?.cantSplit !== void 0 ? { cantSplit: rMeta.cantSplit } : {},
24424
25971
  isFirstRow: rIdx === 0 ? import_core13.BooleanNumber.TRUE : import_core13.BooleanNumber.FALSE,
24425
25972
  repeatHeaderRow: rIdx < effectiveHdrCount ? import_core13.BooleanNumber.TRUE : import_core13.BooleanNumber.FALSE
24426
25973
  });
@@ -24432,7 +25979,7 @@ function buildStructuredDocData(params) {
24432
25979
  startIndex: tblStart,
24433
25980
  endIndex: tblEndExclusive
24434
25981
  });
24435
- tableSource[tableId] = {
25982
+ const tblEntry = {
24436
25983
  tableId,
24437
25984
  tableRows,
24438
25985
  tableColumns: colWidths.map((w) => ({
@@ -24446,14 +25993,19 @@ function buildStructuredDocData(params) {
24446
25993
  positionV: { relativeFrom: 0, posOffset: 0 }
24447
25994
  },
24448
25995
  dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
24449
- size: {
25996
+ size: block.tableSize ? import_core13.Tools.deepClone(block.tableSize) : {
24450
25997
  width: {
24451
25998
  v: colWidths.reduce((a, b) => a + b, 0),
24452
25999
  u: import_core13.NumberUnitType.POINT
24453
26000
  },
24454
26001
  type: 0
24455
- }
26002
+ },
26003
+ ...block.tableLayout !== void 0 ? { layout: block.tableLayout } : {},
26004
+ ...block.yudaoTblWidthType ? { yudaoTblWidthType: block.yudaoTblWidthType } : {},
26005
+ ...block.yudaoTblWidthDxa !== void 0 ? { yudaoTblWidthDxa: block.yudaoTblWidthDxa } : {},
26006
+ ...block.yudaoTblWidthPct !== void 0 ? { yudaoTblWidthPct: block.yudaoTblWidthPct } : {}
24456
26007
  };
26008
+ tableSource[tableId] = tblEntry;
24457
26009
  if (block.rowLoop) {
24458
26010
  rowLoopMeta[`${tableId}:${block.rowLoop.rowIndex}`] = {
24459
26011
  tableId,
@@ -24519,6 +26071,9 @@ function buildStructuredDocData(params) {
24519
26071
  } : {}
24520
26072
  });
24521
26073
  }
26074
+ if (docData.drawings && Object.keys(docData.drawings).length > 0) {
26075
+ normalizeDocDrawingsAndPluginResource(docData);
26076
+ }
24522
26077
  return docData;
24523
26078
  }
24524
26079
  function extractDocCatalog(snapshot) {
@@ -26073,11 +27628,17 @@ var SyncDocAuxStateMutation = {
26073
27628
  if (params.footers !== void 0) {
26074
27629
  snap.footers = import_core15.Tools.deepClone(params.footers);
26075
27630
  }
27631
+ if (params.headers !== void 0 || params.footers !== void 0) {
27632
+ reinitializeDocHeaderFooterModels(docModel);
27633
+ }
26076
27634
  if (params.metadata !== void 0) {
26077
27635
  const nextMeta = import_core15.Tools.deepClone(params.metadata);
26078
27636
  accessor.get(IDocSdtService).setTemplateMetadata(docModel.getUnitId(), nextMeta);
26079
27637
  writeDocTemplateMetadataToSnapshot(snap, nextMeta);
26080
27638
  }
27639
+ if (params.drawings !== void 0 || params.drawingsOrder !== void 0) {
27640
+ syncDocDrawingsToUniverServices(accessor, docModel.getUnitId(), snap);
27641
+ }
26081
27642
  return true;
26082
27643
  }
26083
27644
  };
@@ -28844,6 +30405,49 @@ function getTargetDocModel(accessor, unitId) {
28844
30405
  function buildBodyReplaceEditOp(prevBody, nextBody) {
28845
30406
  return import_core20.JSONX.getInstance().replaceOp(["body"], prevBody, nextBody);
28846
30407
  }
30408
+ function reinitializeDocHeaderFooterModels(docModel) {
30409
+ const anyModel = docModel;
30410
+ anyModel.headerModelMap?.forEach?.((m) => m?.dispose?.());
30411
+ anyModel.headerModelMap?.clear?.();
30412
+ anyModel.footerModelMap?.forEach?.((m) => m?.dispose?.());
30413
+ anyModel.footerModelMap?.clear?.();
30414
+ anyModel._initializeHeaderFooterModel?.();
30415
+ }
30416
+ function syncDocDrawingsToUniverServices(injector, unitId, snapshot) {
30417
+ if (!snapshot || typeof snapshot !== "object") return;
30418
+ if (!snapshot.id && unitId) {
30419
+ snapshot.id = unitId;
30420
+ }
30421
+ normalizeDocDrawingsAndPluginResource(snapshot);
30422
+ const accessor = injector;
30423
+ const docModel = getTargetDocModel(accessor, unitId);
30424
+ const nextDrawings = import_core20.Tools.deepClone(snapshot.drawings ?? {});
30425
+ const nextOrder = import_core20.Tools.deepClone(snapshot.drawingsOrder ?? []);
30426
+ if (docModel) {
30427
+ const liveSnap = docModel.getSnapshot();
30428
+ liveSnap.drawings = import_core20.Tools.deepClone(nextDrawings);
30429
+ liveSnap.drawingsOrder = import_core20.Tools.deepClone(nextOrder);
30430
+ if (snapshot.resources !== void 0) {
30431
+ liveSnap.resources = import_core20.Tools.deepClone(snapshot.resources);
30432
+ }
30433
+ docModel.resetDrawing?.(import_core20.Tools.deepClone(nextDrawings), import_core20.Tools.deepClone(nextOrder));
30434
+ }
30435
+ try {
30436
+ const resourceManagerService = accessor.get(import_core20.IResourceManagerService);
30437
+ const hook = resourceManagerService?.getAllResourceHooks?.().find((h) => h.pluginName === DOC_DRAWING_PLUGIN_RESOURCE);
30438
+ if (hook) {
30439
+ if (Object.keys(nextDrawings).length > 0) {
30440
+ hook.onLoad(unitId, {
30441
+ data: import_core20.Tools.deepClone(nextDrawings),
30442
+ order: import_core20.Tools.deepClone(nextOrder)
30443
+ });
30444
+ } else {
30445
+ hook.onUnLoad?.(unitId);
30446
+ }
30447
+ }
30448
+ } catch {
30449
+ }
30450
+ }
28847
30451
  function syncSnapshotAuxFields(docModel, nextSnapshot) {
28848
30452
  const liveSnap = docModel.getSnapshot();
28849
30453
  if (nextSnapshot.tableSource !== void 0) {
@@ -28885,8 +30489,11 @@ function syncSnapshotAuxFields(docModel, nextSnapshot) {
28885
30489
  if (nextSnapshot.documentStyle) {
28886
30490
  liveSnap.documentStyle = import_core20.Tools.deepClone(nextSnapshot.documentStyle);
28887
30491
  }
30492
+ if (nextSnapshot.headers !== void 0 || nextSnapshot.footers !== void 0) {
30493
+ reinitializeDocHeaderFooterModels(docModel);
30494
+ }
28888
30495
  }
28889
- function executeBodyUpdateViaRichTextMutation(accessor, docModel, nextBody, cursorOffset, bypassContentLock = false, allowInViewMode = false) {
30496
+ function executeBodyUpdateViaRichTextMutation(accessor, docModel, nextBody, cursorOffset, bypassContentLock = false, allowInViewMode = false, forceRecalculate = false) {
28890
30497
  const sdtService = accessor.get(IDocSdtService);
28891
30498
  const unitId = docModel.getUnitId();
28892
30499
  if (!allowInViewMode && sdtService.getDocMode(unitId) === "view") {
@@ -28896,17 +30503,34 @@ function executeBodyUpdateViaRichTextMutation(accessor, docModel, nextBody, curs
28896
30503
  const prevSnap = docModel.getSnapshot();
28897
30504
  const prevBody = prevSnap.body;
28898
30505
  if (!prevBody) return false;
28899
- if (import_core20.Tools.diffValue(prevBody, nextBody)) return true;
30506
+ const bodyEqual = import_core20.Tools.diffValue(prevBody, nextBody);
30507
+ if (bodyEqual && !forceRecalculate) return true;
28900
30508
  const wasDisabled = Boolean(prevSnap.disabled);
28901
30509
  if (allowInViewMode && wasDisabled) {
28902
30510
  prevSnap.disabled = false;
28903
30511
  }
28904
30512
  try {
28905
- const hasLockedSdt = bypassContentLock && (prevBody.customRanges ?? []).some(
30513
+ if (bodyEqual && forceRecalculate) {
30514
+ const tempBody = {
30515
+ ...import_core20.Tools.deepClone(prevBody),
30516
+ payloads: { ...prevBody.payloads ?? {}, __recalc: (0, import_core20.generateRandomId)(4) }
30517
+ };
30518
+ const recalcUnlockOp = buildBodyReplaceEditOp(prevBody, tempBody);
30519
+ if (recalcUnlockOp) {
30520
+ commandService.syncExecuteCommand(import_docs4.RichTextEditingMutation.id, {
30521
+ unitId,
30522
+ actions: recalcUnlockOp,
30523
+ noHistory: true,
30524
+ noNeedSetTextRange: true
30525
+ });
30526
+ }
30527
+ }
30528
+ const liveBeforeLockCheck = docModel.getSnapshot().body;
30529
+ const hasLockedSdt = bypassContentLock && (liveBeforeLockCheck.customRanges ?? []).some(
28906
30530
  (r) => r.rangeType === import_core20.CustomRangeType.SDT && r.properties?.lock && r.properties.lock !== "unlocked"
28907
30531
  );
28908
30532
  if (hasLockedSdt) {
28909
- const unlockedBody = import_core20.Tools.deepClone(prevBody);
30533
+ const unlockedBody = import_core20.Tools.deepClone(liveBeforeLockCheck);
28910
30534
  unlockedBody.customRanges = (unlockedBody.customRanges ?? []).map(
28911
30535
  (r) => r.rangeType === import_core20.CustomRangeType.SDT ? {
28912
30536
  ...r,
@@ -28916,7 +30540,7 @@ function executeBodyUpdateViaRichTextMutation(accessor, docModel, nextBody, curs
28916
30540
  }
28917
30541
  } : r
28918
30542
  );
28919
- const unlockActions = buildBodyReplaceEditOp(prevBody, unlockedBody);
30543
+ const unlockActions = buildBodyReplaceEditOp(liveBeforeLockCheck, unlockedBody);
28920
30544
  if (unlockActions) {
28921
30545
  commandService.syncExecuteCommand(import_docs4.RichTextEditingMutation.id, {
28922
30546
  unitId,
@@ -28935,7 +30559,7 @@ function executeBodyUpdateViaRichTextMutation(accessor, docModel, nextBody, curs
28935
30559
  actions,
28936
30560
  textRanges: clampedCursor !== void 0 ? [{ startOffset: clampedCursor, endOffset: clampedCursor, collapsed: true }] : void 0,
28937
30561
  noNeedSetTextRange: clampedCursor === void 0,
28938
- noHistory: allowInViewMode && wasDisabled ? true : void 0
30562
+ noHistory: allowInViewMode && wasDisabled || bodyEqual ? true : void 0
28939
30563
  });
28940
30564
  if (typeof result === "boolean") return result;
28941
30565
  return Boolean(result && Array.isArray(result.actions) && result.actions.length > 0);
@@ -29445,16 +31069,29 @@ var ReplaceDocUnitSnapshotCommand = {
29445
31069
  if (!params?.snapshot?.body) return false;
29446
31070
  const docModel = getTargetDocModel(accessor, params.unitId);
29447
31071
  if (!docModel) return false;
29448
- syncSnapshotAuxFields(docModel, params.snapshot);
29449
- const snapMeta = readDocTemplateMetadataFromSnapshot(params.snapshot);
29450
- accessor.get(IDocSdtService).setTemplateMetadata(docModel.getUnitId(), snapMeta);
31072
+ const unitId = docModel.getUnitId();
31073
+ const normalizedSnap = import_core20.Tools.deepClone(params.snapshot);
31074
+ if (!normalizedSnap.id) {
31075
+ normalizedSnap.id = unitId;
31076
+ }
31077
+ normalizeDocDrawingsAndPluginResource(normalizedSnap);
31078
+ const prevSnap = docModel.getSnapshot();
31079
+ const auxChanged = normalizedSnap.headers !== void 0 && !import_core20.Tools.diffValue(prevSnap.headers ?? {}, normalizedSnap.headers ?? {}) || normalizedSnap.footers !== void 0 && !import_core20.Tools.diffValue(prevSnap.footers ?? {}, normalizedSnap.footers ?? {}) || normalizedSnap.drawings !== void 0 && !import_core20.Tools.diffValue(prevSnap.drawings ?? {}, normalizedSnap.drawings ?? {}) || normalizedSnap.drawingsOrder !== void 0 && !import_core20.Tools.diffValue(prevSnap.drawingsOrder ?? [], normalizedSnap.drawingsOrder ?? []) || normalizedSnap.documentStyle !== void 0 && !import_core20.Tools.diffValue(prevSnap.documentStyle ?? {}, normalizedSnap.documentStyle ?? {}) || normalizedSnap.styles !== void 0 && !import_core20.Tools.diffValue(prevSnap.styles ?? {}, normalizedSnap.styles ?? {}) || normalizedSnap.tableSource !== void 0 && !import_core20.Tools.diffValue(prevSnap.tableSource ?? {}, normalizedSnap.tableSource ?? {});
31080
+ syncSnapshotAuxFields(docModel, normalizedSnap);
31081
+ reinitializeDocHeaderFooterModels(docModel);
31082
+ syncDocDrawingsToUniverServices(accessor, unitId, normalizedSnap);
31083
+ const snapMeta = readDocTemplateMetadataFromSnapshot(normalizedSnap);
31084
+ const sdtService = accessor.get(IDocSdtService);
31085
+ sdtService.setTemplateMetadata(unitId, snapMeta);
31086
+ sdtService.bumpRevision(unitId);
29451
31087
  return executeBodyUpdateViaRichTextMutation(
29452
31088
  accessor,
29453
31089
  docModel,
29454
- params.snapshot.body,
31090
+ normalizedSnap.body,
29455
31091
  0,
29456
31092
  true,
29457
- Boolean(params.allowInViewMode)
31093
+ Boolean(params.allowInViewMode),
31094
+ auxChanged
29458
31095
  );
29459
31096
  }
29460
31097
  };
@@ -31995,6 +33632,7 @@ UniverDocsExtPlugin = __decorateClass([
31995
33632
  DEFAULT_CASCADER_OPTIONS,
31996
33633
  DEFAULT_ENDNOTE_SETTINGS,
31997
33634
  DEFAULT_FOOTNOTE_SETTINGS,
33635
+ DOC_DRAWING_PLUGIN_RESOURCE,
31998
33636
  DOC_HYPERLINK_DEFAULT_COLOR,
31999
33637
  DOC_IO_CAPABILITY_FORMATS,
32000
33638
  DOC_TRACK_DELETE_STYLE,
@@ -32327,6 +33965,7 @@ UniverDocsExtPlugin = __decorateClass([
32327
33965
  listLiveSmartArts,
32328
33966
  matchSdtHighlightRule,
32329
33967
  mergeDocTableCellsInSnapshot,
33968
+ normalizeDocDrawingsAndPluginResource,
32330
33969
  normalizeImageDataUriForSdt,
32331
33970
  normalizeMacroName,
32332
33971
  normalizeSdtListItems,
@@ -32346,6 +33985,7 @@ UniverDocsExtPlugin = __decorateClass([
32346
33985
  recordDocTrackRevisionOnSnapshot,
32347
33986
  refreshTableOfContentsInSnapshot,
32348
33987
  registerDocMacro,
33988
+ reinitializeDocHeaderFooterModels,
32349
33989
  removeBookmarkFromSnapshot,
32350
33990
  removeCalloutFromSnapshot,
32351
33991
  removeDocCascadeRule,
@@ -32424,6 +34064,7 @@ UniverDocsExtPlugin = __decorateClass([
32424
34064
  splitDocTableCellInSnapshot,
32425
34065
  stripDocEditorChromeForView,
32426
34066
  stripSdtAffixes,
34067
+ syncDocDrawingsToUniverServices,
32427
34068
  syncSnapshotAuxFields,
32428
34069
  toControlSpecSnapshot,
32429
34070
  toggleDocListCheckboxInSnapshot,