dsh-ppt 0.23.1 → 0.24.0

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.
@@ -6,6 +6,20 @@
6
6
  */
7
7
 
8
8
  import { pptxFontName, pptxEastAsianFont, hexToRgba, relativeLuminance, resolveChromeStyle, mixHex } from './deck-themes.mjs'
9
+ import {
10
+ containsLatexMath,
11
+ looksLikeRawLatex,
12
+ unwrapOuterMathDelimiters,
13
+ maskMathSpans,
14
+ unmaskMathSpans,
15
+ splitMathSegments,
16
+ parseLatexMath,
17
+ latexToMathMl,
18
+ astToOmml,
19
+ astToOoxmlInlineRuns,
20
+ has2dMathConstruct,
21
+ fitFormulaBoxIn,
22
+ } from './deck-math.mjs'
9
23
 
10
24
  // ---------------------------------------------------------------------------
11
25
  // 常量与坐标换算(16:9 画布:13.3333" × 7.5" = 12192000 × 6858000 EMU)
@@ -28,7 +42,11 @@ export const CORE_LAYOUTS = new Set([
28
42
  'cards',
29
43
  'comparison',
30
44
  'matrix',
45
+ 'swot',
31
46
  'process',
47
+ 'value-chain',
48
+ 'marimekko',
49
+ 'sankey',
32
50
  'callout',
33
51
  'gantt',
34
52
  'architecture',
@@ -51,7 +69,9 @@ export const LAYOUT_ALIASES = Object.freeze({
51
69
  funnel: { layout: 'process', variant: 'funnel' },
52
70
  flywheel: { layout: 'process', variant: 'flywheel' },
53
71
  chevron: { layout: 'process', variant: 'chevron' },
54
- 'value-chain': { layout: 'process', variant: 'chevron' },
72
+ porter: { layout: 'value-chain' },
73
+ mekko: { layout: 'marimekko' },
74
+ 'swot-matrix': { layout: 'swot' },
55
75
  'issue-action': { layout: 'comparison', variant: 'issue-action' },
56
76
  'before-after': { layout: 'comparison', variant: 'before-after' },
57
77
  'matrix-2x2': { layout: 'matrix', variant: '2x2' },
@@ -126,7 +146,8 @@ export function escapeHtml(value) {
126
146
  }
127
147
 
128
148
  export function stripInlineMarkdown(value) {
129
- return String(value ?? '')
149
+ const { masked, stash } = maskMathSpans(String(value ?? ''))
150
+ const stripped = masked
130
151
  .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
131
152
  .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
132
153
  .replace(/`([^`]*)`/g, '$1')
@@ -137,30 +158,28 @@ export function stripInlineMarkdown(value) {
137
158
  .replace(/<[^>]+>/g, '')
138
159
  .replace(/\s+/g, ' ')
139
160
  .trim()
161
+ return unmaskMathSpans(stripped, stash).replace(/`([^`]*)`/g, '$1')
140
162
  }
141
163
 
142
164
  /**
143
- * 清理不安全标签与链接语法,但保留成对的 **粗体**、*斜体* 与 `代码` 标记。
165
+ * 清理不安全标签与链接语法,但保留成对的 **粗体**、*斜体*、`代码` 以及 $...$ / $$...$$ 公式标记。
144
166
  * 纯文本输入(无标记)输出与 stripInlineMarkdown 完全一致。
145
167
  */
146
168
  export function cleanRichText(value) {
147
- return String(value ?? '')
169
+ const { masked, stash } = maskMathSpans(String(value ?? ''))
170
+ const cleaned = masked
148
171
  .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
149
172
  .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
150
173
  .replace(/<[^>]+>/g, '')
151
174
  .replace(/__([^_]+)__/g, '**$1**')
152
175
  .replace(/\s+/g, ' ')
153
176
  .trim()
177
+ return unmaskMathSpans(cleaned, stash)
154
178
  }
155
179
 
156
180
  const INLINE_TOKEN_RE = /(\*\*[^*]+\*\*|`[^`]+`|\*[^*\s][^*]*?\*)/g
157
181
 
158
- /**
159
- * 将单行富文本拆分为结构化 Run 数组,用于 HTML 与 PPTX 多 <a:r> 同构输出。
160
- * 支持可选 autoLeadBold:对「短前缀:正文说明」自动加粗前缀(不篡改源字符串)。
161
- */
162
- export function parseInlineRuns(input, options = {}) {
163
- const text = String(input ?? '')
182
+ function parseMarkdownRunsOnly(text, options = {}) {
164
183
  if (text === '') return []
165
184
  const hasExplicitMarkup = /\*\*[^*]+\*\*|`[^`]+`|\*[^*\s][^*]*?\*/.test(text)
166
185
 
@@ -203,10 +222,55 @@ export function parseInlineRuns(input, options = {}) {
203
222
  return runs.filter((r) => r.text !== '')
204
223
  }
205
224
 
206
- export function renderInlineHtml(input, options = {}) {
225
+ /**
226
+ * 将单行富文本拆分为结构化 Run 数组,用于 HTML 与 PPTX 多 <a:r> 同构输出。
227
+ * 支持可选 autoLeadBold 与内联 LaTeX 数学符号/上下标编译。
228
+ */
229
+ export function parseInlineRuns(input, options = {}) {
207
230
  const text = String(input ?? '')
208
- const runs = parseInlineRuns(text, options)
209
- if (runs.length === 1 && !runs[0].bold && !runs[0].italic && !runs[0].code) {
231
+ if (text === '') return []
232
+ if (!containsLatexMath(text)) {
233
+ return parseMarkdownRunsOnly(text, options)
234
+ }
235
+
236
+ // 支持跨 $math$ 边界的 **粗体** 包裹(如 "**$Q, K, V$ 查询矩阵**")
237
+ const out = []
238
+ let inBold = false
239
+ const boldParts = text.split('**')
240
+ const hasBalancedBold = boldParts.length >= 3 && boldParts.length % 2 === 1
241
+ if (hasBalancedBold) {
242
+ boldParts.forEach((chunkText, idx) => {
243
+ const boldActive = idx % 2 === 1
244
+ if (!chunkText) return
245
+ const segs = splitMathSegments(chunkText)
246
+ segs.forEach((seg, sIdx) => {
247
+ if (seg.type === 'math') {
248
+ const mathRuns = astToOoxmlInlineRuns(parseLatexMath(seg.latex))
249
+ out.push(...mathRuns.map((r) => (boldActive ? { ...r, bold: true } : r)))
250
+ } else {
251
+ const mdRuns = parseMarkdownRunsOnly(seg.value, idx === 0 && sIdx === 0 && !boldActive ? options : {})
252
+ out.push(...mdRuns.map((r) => (boldActive ? { ...r, bold: true } : r)))
253
+ }
254
+ })
255
+ })
256
+ return out.filter((r) => r.text !== '')
257
+ }
258
+
259
+ const segs = splitMathSegments(text)
260
+ segs.forEach((seg, sIdx) => {
261
+ if (seg.type === 'math') {
262
+ const mathRuns = astToOoxmlInlineRuns(parseLatexMath(seg.latex))
263
+ out.push(...mathRuns.map((r) => (inBold ? { ...r, bold: true } : r)))
264
+ } else {
265
+ const mdRuns = parseMarkdownRunsOnly(seg.value, sIdx === 0 ? options : {})
266
+ out.push(...mdRuns)
267
+ }
268
+ })
269
+ return out.filter((r) => r.text !== '')
270
+ }
271
+
272
+ function renderRunsToHtml(runs) {
273
+ if (runs.length === 1 && !runs[0].bold && !runs[0].italic && !runs[0].code && !runs[0].secondary) {
210
274
  return escapeHtml(runs[0].text)
211
275
  }
212
276
  return runs.map((run) => {
@@ -220,6 +284,39 @@ export function renderInlineHtml(input, options = {}) {
220
284
  }).join('')
221
285
  }
222
286
 
287
+ export function renderInlineHtml(input, options = {}) {
288
+ const text = String(input ?? '')
289
+ if (!containsLatexMath(text)) {
290
+ return renderRunsToHtml(parseMarkdownRunsOnly(text, options))
291
+ }
292
+ const boldParts = text.split('**')
293
+ if (boldParts.length >= 3 && boldParts.length % 2 === 1) {
294
+ return boldParts.map((chunkText, idx) => {
295
+ if (!chunkText) return ''
296
+ const innerHtml = splitMathSegments(chunkText).map((seg, sIdx) => {
297
+ if (seg.type === 'math') {
298
+ return latexToMathMl(seg.latex, {
299
+ display: seg.display,
300
+ className: seg.display ? 'deck-math is-block' : 'deck-math is-inline',
301
+ })
302
+ }
303
+ return renderRunsToHtml(parseMarkdownRunsOnly(seg.value, idx === 0 && sIdx === 0 ? options : {}))
304
+ }).join('')
305
+ return idx % 2 === 1 ? '<strong>' + innerHtml + '</strong>' : innerHtml
306
+ }).join('')
307
+ }
308
+ const segs = splitMathSegments(text)
309
+ return segs.map((seg, sIdx) => {
310
+ if (seg.type === 'math') {
311
+ return latexToMathMl(seg.latex, {
312
+ display: seg.display,
313
+ className: seg.display ? 'deck-math is-block' : 'deck-math is-inline',
314
+ })
315
+ }
316
+ return renderRunsToHtml(parseMarkdownRunsOnly(seg.value, sIdx === 0 ? options : {}))
317
+ }).join('')
318
+ }
319
+
223
320
  // ---------------------------------------------------------------------------
224
321
  // CJK + Latin 视觉宽度与确定性字号拟合算法 computeTextFit()
225
322
  // ---------------------------------------------------------------------------
@@ -356,6 +453,42 @@ function parseBulletToItem(rawBullet, index, layout) {
356
453
  }
357
454
  }
358
455
 
456
+ if (layout === 'sankey') {
457
+ const flowMatch = /^(.+?)\s*(?:->|→|=>|──>|——>)\s*([^::||]+?)(?:\s*[::||]\s*(.+))?$/.exec(clean)
458
+ if (flowMatch) {
459
+ const srcNode = stripInlineMarkdown(flowMatch[1])
460
+ const dstNode = stripInlineMarkdown(flowMatch[2])
461
+ const rest = stripInlineMarkdown(flowMatch[3] ?? '')
462
+ const statusTag = /\[(positive|negative|warning|accent|neutral)\]/i.exec(rest)
463
+ const cleanedRest = rest.replace(/\[(positive|negative|warning|accent|neutral)\]/gi, '').trim()
464
+ const deltaMatch = /\(([+-][^)]+)\)/.exec(cleanedRest)
465
+ const valMatch = /^([¥$€£]?\s*[+-]?\d[\d,.]*)\s*([^\s((]*)/.exec(cleanedRest)
466
+ return {
467
+ tag: srcNode,
468
+ title: dstNode,
469
+ ...(valMatch ? { value: valMatch[1].replace(/\s+/g, ''), ...(valMatch[2] ? { unit: valMatch[2] } : {}) } : (cleanedRest ? { value: cleanedRest } : {})),
470
+ ...(deltaMatch ? { delta: deltaMatch[1].trim() } : {}),
471
+ ...(statusTag ? { status: statusTag[1].toLowerCase() } : {}),
472
+ }
473
+ }
474
+ }
475
+
476
+ if (layout === 'marimekko') {
477
+ // 识别形如 "华东政务 (450亿):本方案 42% | 厂商B 33% | 其他 25%"
478
+ const mekkoMatch = /^([^::]+?)[::]\s*(.+)$/.exec(clean)
479
+ if (mekkoMatch) {
480
+ const rawHead = stripInlineMarkdown(mekkoMatch[1])
481
+ const sizeInHead = /^(.*?)\s*[((]\s*([¥$€£]?\s*\d[\d,.]*)\s*([^))]*)[))]\s*$/.exec(rawHead)
482
+ const colTitle = sizeInHead ? (sizeInHead[1].trim() || rawHead) : rawHead
483
+ const segs = mekkoMatch[2].split(/\s*[||;;,,]\s*/).map((s) => s.trim()).filter(Boolean)
484
+ return {
485
+ title: colTitle,
486
+ ...(sizeInHead ? { value: sizeInHead[2].replace(/\s+/g, ''), ...(sizeInHead[3].trim() ? { unit: sizeInHead[3].trim() } : {}) } : {}),
487
+ ...(segs.length > 0 ? { bullets: segs } : {}),
488
+ }
489
+ }
490
+ }
491
+
359
492
  if (layout === 'comparison') {
360
493
  const arrowMatch = /^(.+?)\s*(?:->|→|=>|──>|——>|vs\.?|VS)\s*(.+)$/.exec(clean)
361
494
  if (arrowMatch) {
@@ -392,15 +525,18 @@ function parseBulletToItem(rawBullet, index, layout) {
392
525
  }
393
526
  }
394
527
 
528
+ const EXTENDED_ITEM_LAYOUTS = new Set(['sankey', 'value-chain', 'marimekko', 'swot'])
529
+
395
530
  export function normalizeSlideItems(rawItems, layout) {
396
531
  if (!Array.isArray(rawItems) || rawItems.length === 0) return undefined
532
+ const maxItems = EXTENDED_ITEM_LAYOUTS.has(layout) ? 12 : 8
397
533
  const out = rawItems
398
- .slice(0, 8)
534
+ .slice(0, maxItems)
399
535
  .map((entry, idx) => {
400
536
  if (typeof entry === 'string') return parseBulletToItem(entry, idx, layout)
401
537
  if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return null
402
- const tag = stripInlineMarkdown(entry.tag ?? entry.badge ?? entry.step ?? entry.phase ?? '')
403
- const title = stripInlineMarkdown(entry.title ?? entry.label ?? entry.heading ?? entry.name ?? '')
538
+ const tag = stripInlineMarkdown(entry.tag ?? entry.badge ?? entry.step ?? entry.phase ?? entry.source ?? entry.from ?? '')
539
+ const title = stripInlineMarkdown(entry.title ?? entry.label ?? entry.heading ?? entry.name ?? entry.target ?? entry.to ?? '')
404
540
  const text = cleanRichText(entry.text ?? entry.body ?? entry.description ?? entry.detail ?? '')
405
541
  const value = entry.value !== undefined && entry.value !== null ? stripInlineMarkdown(String(entry.value)) : ''
406
542
  const unit = stripInlineMarkdown(entry.unit ?? '')
@@ -415,7 +551,7 @@ export function normalizeSlideItems(rawItems, layout) {
415
551
  const role = stripInlineMarkdown(entry.role ?? '')
416
552
  const conversion = stripInlineMarkdown(entry.conversion ?? '')
417
553
  const bullets = Array.isArray(entry.bullets ?? entry.items)
418
- ? (entry.bullets ?? entry.items).map((b) => cleanRichText(String(b))).filter(Boolean).slice(0, 6)
554
+ ? (entry.bullets ?? entry.items).map((b) => cleanRichText(String(b))).filter(Boolean).slice(0, 8)
419
555
  : undefined
420
556
  if (!title && !text && !value && (!bullets || bullets.length === 0)) return null
421
557
  return {
@@ -440,9 +576,10 @@ export function normalizeSlideItems(rawItems, layout) {
440
576
 
441
577
  export function resolveEffectiveItems(slide) {
442
578
  if (Array.isArray(slide.items) && slide.items.length > 0) return slide.items
579
+ const maxItems = EXTENDED_ITEM_LAYOUTS.has(slide.layout) ? 12 : 8
443
580
  const bullets = Array.isArray(slide.bullets) ? slide.bullets : []
444
581
  if (bullets.length > 0) {
445
- return bullets.slice(0, 8).map((b, i) => parseBulletToItem(b, i, slide.layout))
582
+ return bullets.slice(0, maxItems).map((b, i) => parseBulletToItem(b, i, slide.layout))
446
583
  }
447
584
  if (slide.subtitle || slide.text) {
448
585
  return [parseBulletToItem(slide.text || slide.subtitle, 0, slide.layout)]
@@ -534,17 +671,22 @@ export function ooxmlRichParagraph(textOrRuns, options = {}) {
534
671
  const runItalic = Boolean(italic || run.italic)
535
672
  const runColor = run.accent ? accentColor : run.secondary ? secondaryColor : color
536
673
  const runSize = run.sizePt ? Math.round(run.sizePt * 100) : sz
537
- const spcAttr = spc !== 0 ? ' spc="' + Math.round(spc) + '"' : ''
674
+ const effSpc = run.spcEm ? Math.round(spc + run.spcEm * (run.sizePt ?? sizePt) * 100) : spc
675
+ const spcAttr = effSpc !== 0 ? ' spc="' + Math.round(effSpc) + '"' : ''
676
+ const baselineAttr = run.baseline ? ' baseline="' + Math.round(run.baseline) + '"' : ''
677
+ const isPureMathNonCjk = Boolean(run.math && !/[\u2E80-\u9FFF\uF900-\uFAFF\uFF00-\uFFEF]/.test(run.text))
678
+ const runLang = isPureMathNonCjk ? 'en-US' : lang
679
+ const runLatin = isPureMathNonCjk ? 'Georgia' : latinFont
538
680
  const hlXml = run.code && codeHighlight
539
681
  ? '<a:highlight><a:srgbClr val="' + hex6(codeHighlight) + '"/></a:highlight>'
540
682
  : ''
541
683
  return (
542
- '<a:r><a:rPr lang="' + lang + '" sz="' + runSize + '" b="' + (runBold ? 1 : 0) + '"' +
543
- (runItalic ? ' i="1"' : '') + spcAttr + ' dirty="0">' +
684
+ '<a:r><a:rPr lang="' + runLang + '" sz="' + runSize + '" b="' + (runBold ? 1 : 0) + '"' +
685
+ (runItalic ? ' i="1"' : '') + baselineAttr + spcAttr + ' dirty="0">' +
544
686
  ooxmlSolidFill(runColor) +
545
687
  hlXml +
546
- '<a:latin typeface="' + escapeXml(latinFont) + '"/>' +
547
- '<a:ea typeface="' + escapeXml(eaFont) + '"/>' +
688
+ '<a:latin typeface="' + escapeXml(runLatin) + '"/>' +
689
+ '<a:ea typeface="' + escapeXml(isPureMathNonCjk ? runLatin : eaFont) + '"/>' +
548
690
  '</a:rPr><a:t>' + escapeXml(run.text) + '</a:t></a:r>'
549
691
  )
550
692
  }).join('')
@@ -613,6 +755,105 @@ export function ooxmlShape(id, name, boxIn, options = {}) {
613
755
  )
614
756
  }
615
757
 
758
+ /**
759
+ * 原生自由矢量路径图元 <a:custGeom>(用于桑基图三次贝塞尔流向丝带等高精度几何绘制)。
760
+ */
761
+ export function ooxmlCustGeomShape(id, name, boxIn, pathCommandsXml, options = {}) {
762
+ const {
763
+ pathW = 10000,
764
+ pathH = 10000,
765
+ fill = '',
766
+ fillAlpha = 1,
767
+ gradientStops = null,
768
+ gradientAngle = 0,
769
+ stroke = '',
770
+ strokePt = 0.75,
771
+ } = options
772
+ const b = boxToEmu(boxIn)
773
+ const fillXml = gradientStops
774
+ ? ooxmlLinearGradientFill(gradientStops, gradientAngle)
775
+ : fill
776
+ ? ooxmlSolidFill(fill, fillAlpha)
777
+ : '<a:noFill/>'
778
+ const lnXml = stroke
779
+ ? '<a:ln w="' + ptToEmu(strokePt) + '" cap="flat">' + ooxmlSolidFill(stroke) + '</a:ln>'
780
+ : '<a:ln><a:noFill/></a:ln>'
781
+
782
+ return (
783
+ '<p:sp>' +
784
+ '<p:nvSpPr><p:cNvPr id="' + id + '" name="' + escapeXml(name) + '"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>' +
785
+ '<p:spPr>' +
786
+ '<a:xfrm><a:off x="' + b.x + '" y="' + b.y + '"/><a:ext cx="' + Math.max(12700, b.w) + '" cy="' + Math.max(12700, b.h) + '"/></a:xfrm>' +
787
+ '<a:custGeom><a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/><a:rect l="l" t="t" r="r" b="b"/>' +
788
+ '<a:pathLst><a:path w="' + Math.round(pathW) + '" h="' + Math.round(pathH) + '">' +
789
+ pathCommandsXml +
790
+ '</a:path></a:pathLst></a:custGeom>' +
791
+ fillXml + lnXml +
792
+ '</p:spPr>' +
793
+ '<p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody>' +
794
+ '</p:sp>'
795
+ )
796
+ }
797
+
798
+ /**
799
+ * 原生 ECMA-376 Office Math (<a14:m><m:oMathPara><m:oMath>) 公式卡片构建器。
800
+ * 为深色主题自动铺设高对比度学术象牙瓷板,确保 LibreOffice StarMath 与 PowerPoint 均呈现 15:1+ 锐利对比且 1:1 自然宽高比无拉伸。
801
+ */
802
+ export function ooxmlMathShape(id, name, boxIn, latex, options = {}) {
803
+ const ast = parseLatexMath(latex)
804
+ const fit = fitFormulaBoxIn(ast, boxIn, {
805
+ padXIn: options.padXIn ?? 0.24,
806
+ padYIn: options.padYIn ?? 0.10,
807
+ emIn: options.emIn ?? 0.30,
808
+ align: options.align ?? 'ctr',
809
+ })
810
+ const b = boxToEmu(fit)
811
+ const ommlXml = astToOmml(ast, {
812
+ wrapDrawingMl: true,
813
+ sizePt: options.sizePt ?? 20,
814
+ color: options.color ?? '#0F172A',
815
+ })
816
+ const algn = options.align === 'l' ? 'l' : 'ctr'
817
+ return (
818
+ '<p:sp>' +
819
+ '<p:nvSpPr><p:cNvPr id="' + id + '" name="' + escapeXml(name) + '"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>' +
820
+ '<p:spPr><a:xfrm><a:off x="' + b.x + '" y="' + b.y + '"/><a:ext cx="' + b.w + '" cy="' + b.h + '"/></a:xfrm>' +
821
+ '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/><a:ln><a:noFill/></a:ln></p:spPr>' +
822
+ '<p:txBody><a:bodyPr wrap="none" lIns="0" tIns="0" rIns="0" bIns="0" anchor="ctr"><a:noAutofit/></a:bodyPr><a:lstStyle/>' +
823
+ '<a:p><a:pPr algn="' + algn + '"><a:buNone/></a:pPr>' + ommlXml + '</a:p>' +
824
+ '</p:txBody></p:sp>'
825
+ )
826
+ }
827
+
828
+ function renderMathCardPptx(namePrefix, boxIn, latex, nextIdFn, chromeCfg, theme, options = {}) {
829
+ const tk = theme.tokens
830
+ const cardPreset = chromeCfg.cardRadiusPx > 0 ? 'roundRect' : 'rect'
831
+ // 深色主题下使用象牙白学术公式衬板,确保 LibreOffice StarMath 墨色与底板保持 >16:1 对比度
832
+ const plateFill = theme.dark ? '#F8FAFC' : tk.surface2
833
+ const out = [
834
+ ooxmlShape(nextIdFn(), namePrefix + ' Surface', boxIn, {
835
+ preset: cardPreset,
836
+ adj: roundRectAdj(boxIn.w, boxIn.h, chromeCfg.cardRadiusPx),
837
+ fill: plateFill,
838
+ stroke: chromeCfg.cardBorderless ? '' : tk.accentPrimary,
839
+ strokePt: 1.0,
840
+ }),
841
+ ooxmlShape(nextIdFn(), namePrefix + ' Accent Rail', { x: boxIn.x, y: boxIn.y, w: 0.07, h: boxIn.h }, {
842
+ preset: 'rect',
843
+ fill: tk.accentPrimary,
844
+ }),
845
+ ooxmlMathShape(nextIdFn(), namePrefix + ' Equation', boxIn, latex, {
846
+ padXIn: 0.34,
847
+ padYIn: 0.14,
848
+ emIn: options.emIn ?? 0.30,
849
+ sizePt: options.sizePt ?? 20,
850
+ color: '#0F172A',
851
+ align: options.align ?? 'ctr',
852
+ }),
853
+ ]
854
+ return out.join('')
855
+ }
856
+
616
857
  export function ooxmlLine(id, name, fromIn, toIn, options = {}) {
617
858
  const {
618
859
  color = '#CBD5E1',
@@ -1552,101 +1793,1752 @@ function renderHarveyBallPptx(parsed, cx, cy, sizeIn, isOurs, nextIdFn, theme, l
1552
1793
  }))
1553
1794
  }
1554
1795
 
1555
- return shapes.join('')
1796
+ return shapes.join('')
1797
+ }
1798
+
1799
+ function renderHarveyMatrixPptx(slide, area, nextIdFn, chromeCfg, theme, langAttr) {
1800
+ const tk = theme.tokens
1801
+ const items = resolveEffectiveItems(slide)
1802
+ const rawRows = Array.isArray(slide.rows) && slide.rows.length > 0
1803
+ ? slide.rows
1804
+ : items.length > 0
1805
+ ? [['评估维度', '行业基线', '本方案 / Ours'], ...items.map((it) => [it.title || '', it.delta || '50%', it.value || (it.status === 'positive' ? 'full' : 'full')])]
1806
+ : [['维度', '本方案 / Ours'], ['能力项', 'full']]
1807
+ const safeRows = rawRows.slice(0, 9)
1808
+ const cols = Math.max(2, ...safeRows.map((r) => r.length))
1809
+ const headerRow = Array.from({ length: cols }, (_, c) => String(safeRows[0]?.[c] ?? ''))
1810
+ const oursCol = findHarveyOursCol(headerRow, cols)
1811
+
1812
+ // Compute proportional column widths (first col wider for criteria label)
1813
+ const firstColW = Math.min(4.6, Math.max(2.8, area.w * (cols <= 3 ? 0.44 : 0.34)))
1814
+ const otherW = (area.w - firstColW) / Math.max(1, cols - 1)
1815
+ const colXs = []
1816
+ const colWs = []
1817
+ let cursorX = area.x
1818
+ for (let c = 0; c < cols; c += 1) {
1819
+ const w = c === 0 ? firstColW : otherW
1820
+ colXs.push(cursorX)
1821
+ colWs.push(w)
1822
+ cursorX += w
1823
+ }
1824
+
1825
+ const rowCount = safeRows.length
1826
+ const rowH = Math.min(0.62, Math.max(0.40, area.h / Math.max(1, rowCount)))
1827
+ const startY = area.y + Math.max(0, (area.h - rowH * rowCount) / 2)
1828
+ const shapes = []
1829
+ const cellPreset = chromeCfg.cardRadiusPx > 0 ? 'roundRect' : 'rect'
1830
+
1831
+ safeRows.forEach((row, rIdx) => {
1832
+ const isHeader = rIdx === 0
1833
+ const y = startY + rIdx * rowH
1834
+ for (let c = 0; c < cols; c += 1) {
1835
+ const cellText = String(row[c] ?? '')
1836
+ const isOurs = c === oursCol
1837
+ const x = colXs[c]
1838
+ const w = colWs[c]
1839
+ const cellFill = isHeader
1840
+ ? (isOurs ? tk.accentPrimary : tk.surface2)
1841
+ : (isOurs ? tk.accentSoft : (rIdx % 2 === 0 ? tk.surface1 : tk.canvas))
1842
+
1843
+ shapes.push(ooxmlShape(nextIdFn(), 'Harvey Cell ' + rIdx + '-' + c, { x, y, w, h: rowH }, {
1844
+ preset: isHeader && c === 0 ? cellPreset : 'rect',
1845
+ adj: 0,
1846
+ fill: cellFill,
1847
+ stroke: isOurs ? tk.accentPrimary : tk.hairline,
1848
+ strokePt: isOurs ? 0.75 : 0.5,
1849
+ }))
1850
+
1851
+ const parsed = !isHeader && c > 0 ? parseHarveyValue(cellText) : null
1852
+ if (parsed) {
1853
+ const ballSize = Math.min(0.28, rowH * 0.56)
1854
+ shapes.push(renderHarveyBallPptx(parsed, x + w / 2, y + rowH / 2, ballSize, isOurs, nextIdFn, theme, langAttr))
1855
+ } else {
1856
+ shapes.push(ooxmlShape(nextIdFn(), 'Harvey Text ' + rIdx + '-' + c, { x: x + 0.08, y: y + 0.03, w: w - 0.16, h: rowH - 0.06 }, {
1857
+ txBox: true,
1858
+ anchor: 'ctr',
1859
+ marginsIn: { l: 0.04, r: 0.04, t: 0.01, b: 0.01 },
1860
+ paragraphs: [
1861
+ ooxmlRichParagraph(cellText, {
1862
+ sizePt: isHeader ? 13.5 : (cols >= 6 ? 12 : 13.5),
1863
+ color: isHeader && isOurs ? tk.inkOnAccent : (isOurs ? tk.accentText : tk.inkPrimary),
1864
+ bold: isHeader || isOurs,
1865
+ lang: langAttr,
1866
+ align: c === 0 ? 'l' : 'ctr',
1867
+ font: isHeader ? theme.fonts.heading : theme.fonts.body,
1868
+ lineHeight: 1.18,
1869
+ }),
1870
+ ],
1871
+ }))
1872
+ }
1873
+ }
1874
+ })
1875
+
1876
+ return shapes.join('')
1877
+ }
1878
+
1879
+ function monogramLetters(name) {
1880
+ const clean = stripInlineMarkdown(String(name ?? ''))
1881
+ .replace(/\s*(?:博士|教授|先生|女士|院士|院长|主任|总|Ph\.?D\.?|M\.?D\.?|MBA).*$/i, '')
1882
+ .trim()
1883
+ if (!clean) return 'T'
1884
+ if (/[\u4E00-\u9FFF]/.test(clean)) {
1885
+ return clean.replace(/\s+/g, '').slice(0, 1)
1886
+ }
1887
+ const parts = clean.split(/\s+/).filter(Boolean)
1888
+ return parts.length >= 2
1889
+ ? (parts[0][0] + parts[1][0]).toUpperCase()
1890
+ : clean.slice(0, 2).toUpperCase()
1891
+ }
1892
+
1893
+ // ---------------------------------------------------------------------------
1894
+ // Phase 4 Pinnacle Layouts 1..4(Marimekko / Sankey / Porter Value Chain / SWOT)
1895
+ // ---------------------------------------------------------------------------
1896
+
1897
+ function extractNumberAndUnit(raw) {
1898
+ const s = stripInlineMarkdown(String(raw ?? '')).trim()
1899
+ if (!s) return { num: 0, unit: '', raw: '' }
1900
+ const parenMatch = /[((]\s*([¥$€£]?\s*[+-]?\d[\d,.]*)\s*([^))]*)[))]/.exec(s)
1901
+ if (parenMatch) {
1902
+ const num = parseFloat(parenMatch[1].replace(/[¥$€£,\s]/g, ''))
1903
+ const prefixSym = /^[¥$€£]/.exec(parenMatch[1].trim())?.[0] ?? ''
1904
+ const suffixUnit = parenMatch[2].trim()
1905
+ return {
1906
+ num: Number.isFinite(num) ? Math.abs(num) : 0,
1907
+ unit: suffixUnit || prefixSym,
1908
+ prefixSym,
1909
+ label: parenMatch[1].trim() + (suffixUnit ? suffixUnit : ''),
1910
+ cleanTitle: s.replace(parenMatch[0], '').trim(),
1911
+ }
1912
+ }
1913
+ const direct = /([¥$€£]?\s*[+-]?\d[\d,.]*)\s*([%%万亿元美元BmkMKTb]*)/.exec(s)
1914
+ if (direct) {
1915
+ const num = parseFloat(direct[1].replace(/[¥$€£,\s]/g, ''))
1916
+ const prefixSym = /^[¥$€£]/.exec(direct[1].trim())?.[0] ?? ''
1917
+ const suffixUnit = direct[2].trim()
1918
+ return {
1919
+ num: Number.isFinite(num) ? Math.abs(num) : 0,
1920
+ unit: suffixUnit || prefixSym,
1921
+ prefixSym,
1922
+ label: direct[1].trim() + suffixUnit,
1923
+ cleanTitle: s.replace(direct[0], '').replace(/^[·::\-—\s]+|[·::\-—\s]+$/g, '').trim() || s,
1924
+ }
1925
+ }
1926
+ return { num: 0, unit: '', prefixSym: '', label: '', cleanTitle: s }
1927
+ }
1928
+
1929
+ const OURS_SERIES_RE = /本方案|我们|ours|dsh|推荐|自有|\bour\b|\bself\b/i
1930
+
1931
+ export function computeMarimekkoModel(slide, langOrAttr = 'zh') {
1932
+ const isEn = langOrAttr === 'en' || langOrAttr === 'en-US'
1933
+ const rawRows = Array.isArray(slide.rows) ? slide.rows.filter((r) => Array.isArray(r) && r.length >= 2) : []
1934
+
1935
+ if (rawRows.length >= 2) {
1936
+ const headerRow = rawRows[0].map((c) => stripInlineMarkdown(c))
1937
+ const colCount = Math.min(7, headerRow.length - 1)
1938
+ const parsedHeaders = Array.from({ length: colCount }, (_, i) => {
1939
+ const cell = headerRow[i + 1] ?? ('S' + (i + 1))
1940
+ const ext = extractNumberAndUnit(cell)
1941
+ return {
1942
+ title: ext.cleanTitle || cell,
1943
+ weight: ext.num,
1944
+ unit: ext.unit,
1945
+ prefixSym: ext.prefixSym || '',
1946
+ sizeLabel: ext.label,
1947
+ }
1948
+ })
1949
+
1950
+ // 判断第 1 行是否为独立市场规模/权重行
1951
+ let seriesStartRow = 1
1952
+ if (rawRows.length >= 3) {
1953
+ const row1Label = stripInlineMarkdown(rawRows[1][0] ?? '')
1954
+ const row1Cells = rawRows[1].slice(1, colCount + 1).map((c) => String(c ?? ''))
1955
+ const explicitWeightRow = /规模|容量|体量|权重|总额|size|weight|tam|market|volume/i.test(row1Label)
1956
+ const headersLackWeights = parsedHeaders.every((h) => h.weight <= 0)
1957
+ const row1NoPct = !row1Cells.some((c) => /[%%]/.test(c))
1958
+ const row1Nums = row1Cells.map((c) => extractNumberAndUnit(c))
1959
+ const row1Sum = row1Nums.reduce((s, x) => s + x.num, 0)
1960
+ if (explicitWeightRow || (headersLackWeights && row1NoPct && row1Sum > 105)) {
1961
+ seriesStartRow = 2
1962
+ row1Nums.forEach((n, idx) => {
1963
+ if (n.num > 0) {
1964
+ parsedHeaders[idx].weight = n.num
1965
+ parsedHeaders[idx].unit = n.unit || parsedHeaders[idx].unit
1966
+ parsedHeaders[idx].prefixSym = n.prefixSym || parsedHeaders[idx].prefixSym
1967
+ parsedHeaders[idx].sizeLabel = n.label
1968
+ }
1969
+ })
1970
+ }
1971
+ }
1972
+
1973
+ const totalRawWeight = parsedHeaders.reduce((s, h) => s + (h.weight > 0 ? h.weight : 0), 0)
1974
+ const effectiveWeights = parsedHeaders.map((h) => (totalRawWeight > 0 ? (h.weight > 0 ? h.weight : totalRawWeight / colCount * 0.35) : 100 / colCount))
1975
+ const weightSum = effectiveWeights.reduce((a, b) => a + b, 0) || 1
1976
+ const dominantUnit = parsedHeaders.find((h) => h.unit && h.unit !== '%')?.unit ?? ''
1977
+ const dominantPrefix = parsedHeaders.find((h) => h.prefixSym)?.prefixSym ?? ''
1978
+
1979
+ const seriesRows = rawRows.slice(seriesStartRow, seriesStartRow + 6)
1980
+ const seriesNames = seriesRows.map((r, idx) => stripInlineMarkdown(r[0] || (isEn ? 'Segment ' + (idx + 1) : '竞争方 ' + (idx + 1))))
1981
+
1982
+ let cursorX = 0
1983
+ const columns = parsedHeaders.map((h, cIdx) => {
1984
+ const widthRatio = effectiveWeights[cIdx] / weightSum
1985
+ const colStart = cursorX
1986
+ cursorX += widthRatio
1987
+
1988
+ const rawVals = seriesRows.map((r) => {
1989
+ const num = extractNumberAndUnit(r[cIdx + 1] ?? '0').num
1990
+ return num > 0 ? num : 0
1991
+ })
1992
+ const colSum = rawVals.reduce((a, b) => a + b, 0) || 1
1993
+ let cursorY = 0
1994
+ const segments = seriesNames.map((sName, sIdx) => {
1995
+ const heightRatio = rawVals[sIdx] / colSum
1996
+ const seg = {
1997
+ seriesName: sName,
1998
+ seriesIndex: sIdx,
1999
+ rawVal: rawVals[sIdx],
2000
+ heightRatio,
2001
+ sharePct: Math.round(heightRatio * 100),
2002
+ yRatio: cursorY,
2003
+ isOurs: OURS_SERIES_RE.test(sName),
2004
+ }
2005
+ cursorY += heightRatio
2006
+ return seg
2007
+ })
2008
+
2009
+ return {
2010
+ title: h.title,
2011
+ weight: effectiveWeights[cIdx],
2012
+ sizeLabel: h.sizeLabel || (Math.round(widthRatio * 100) + '%'),
2013
+ widthRatio,
2014
+ xRatio: colStart,
2015
+ segments,
2016
+ }
2017
+ })
2018
+
2019
+ const seriesSummary = seriesNames.map((name, sIdx) => {
2020
+ const weightedShare = columns.reduce((acc, col) => acc + col.widthRatio * (col.segments[sIdx]?.heightRatio ?? 0), 0)
2021
+ return {
2022
+ name,
2023
+ index: sIdx,
2024
+ weightedPct: Math.round(weightedShare * 100),
2025
+ isOurs: OURS_SERIES_RE.test(name),
2026
+ }
2027
+ })
2028
+
2029
+ const totalLabel = totalRawWeight > 0
2030
+ ? (dominantPrefix + (Number.isInteger(totalRawWeight) ? totalRawWeight.toLocaleString('en-US') : totalRawWeight.toFixed(1)) + (dominantUnit && dominantUnit !== dominantPrefix ? ' ' + dominantUnit : ''))
2031
+ : '100%'
2032
+
2033
+ return { columns, seriesSummary, totalLabel, hasExplicitWeights: totalRawWeight > 0 }
2034
+ }
2035
+
2036
+ // 从 items[] / bullets[] 归一构建 Marimekko 模型
2037
+ const rawItems = resolveEffectiveItems(slide).slice(0, 7)
2038
+ const items = rawItems.length > 0
2039
+ ? rawItems
2040
+ : [
2041
+ { title: isEn ? 'Enterprise' : '政企市场', value: '450', unit: isEn ? 'B' : '亿', bullets: [(isEn ? 'Ours: 42%' : '本方案: 42%'), (isEn ? 'Peer B: 33%' : '厂商B: 33%'), (isEn ? 'Others: 25%' : '其他: 25%')] },
2042
+ { title: isEn ? 'Finance' : '金融信创', value: '320', unit: isEn ? 'B' : '亿', bullets: [(isEn ? 'Ours: 36%' : '本方案: 36%'), (isEn ? 'Peer B: 39%' : '厂商B: 39%'), (isEn ? 'Others: 25%' : '其他: 25%')] },
2043
+ ]
2044
+
2045
+ const seriesOrder = []
2046
+ const ensureSeries = (name) => {
2047
+ const key = name.trim()
2048
+ let idx = seriesOrder.indexOf(key)
2049
+ if (idx < 0 && seriesOrder.length < 6) {
2050
+ idx = seriesOrder.length
2051
+ seriesOrder.push(key)
2052
+ }
2053
+ return idx
2054
+ }
2055
+
2056
+ const parsedCols = items.map((it, idx) => {
2057
+ const valInfo = it.value
2058
+ ? extractNumberAndUnit(it.value + (it.unit ? it.unit : ''))
2059
+ : extractNumberAndUnit(it.title || '')
2060
+ const rawSegLines = Array.isArray(it.bullets) && it.bullets.length > 0
2061
+ ? it.bullets
2062
+ : (it.text ? it.text.split(/\s*[||;;]\s*/) : [])
2063
+ const segPairs = rawSegLines.map((line, lIdx) => {
2064
+ const cleanLine = stripInlineMarkdown(line)
2065
+ const kv = /^([^::]+?)[::\s]\s*([+-]?\d+(?:\.\d+)?)\s*[%%]?/.exec(cleanLine)
2066
+ || /^(.+?)\s+([+-]?\d+(?:\.\d+)?)\s*[%%]$/.exec(cleanLine)
2067
+ if (kv) {
2068
+ const sName = kv[1].trim()
2069
+ ensureSeries(sName)
2070
+ return { name: sName, val: Math.max(0, parseFloat(kv[2]) || 0) }
2071
+ }
2072
+ const fallbackNum = extractNumberAndUnit(cleanLine)
2073
+ const sName = fallbackNum.cleanTitle || (isEn ? 'Tier ' + (lIdx + 1) : '份额 ' + (lIdx + 1))
2074
+ ensureSeries(sName)
2075
+ return { name: sName, val: fallbackNum.num > 0 ? fallbackNum.num : 100 / Math.max(1, rawSegLines.length) }
2076
+ })
2077
+ if (segPairs.length === 0) {
2078
+ const defaultName = isEn ? 'Ours' : '本方案'
2079
+ const restName = isEn ? 'Others' : '其他厂商'
2080
+ const pVal = valInfo.num > 0 && valInfo.unit === '%' ? Math.min(100, valInfo.num) : 45
2081
+ ensureSeries(defaultName)
2082
+ ensureSeries(restName)
2083
+ segPairs.push({ name: defaultName, val: pVal }, { name: restName, val: Math.max(0, 100 - pVal) })
2084
+ }
2085
+ return {
2086
+ title: (it.value ? (it.title || ('S' + (idx + 1))) : (valInfo.cleanTitle || it.title || ('S' + (idx + 1)))),
2087
+ weight: valInfo.unit !== '%' && valInfo.num > 0 ? valInfo.num : 0,
2088
+ unit: it.unit || (valInfo.unit !== '%' ? valInfo.unit : ''),
2089
+ prefixSym: valInfo.prefixSym || '',
2090
+ sizeLabel: it.value ? (it.value + (it.unit || '')) : (valInfo.unit !== '%' ? valInfo.label : ''),
2091
+ segPairs,
2092
+ }
2093
+ })
2094
+
2095
+ const totalRawWeight = parsedCols.reduce((s, c) => s + (c.weight > 0 ? c.weight : 0), 0)
2096
+ const effWeights = parsedCols.map((c) => (totalRawWeight > 0 ? (c.weight > 0 ? c.weight : totalRawWeight / parsedCols.length * 0.35) : 100 / parsedCols.length))
2097
+ const weightSum = effWeights.reduce((a, b) => a + b, 0) || 1
2098
+ const domUnit = parsedCols.find((c) => c.unit)?.unit ?? ''
2099
+ const domPrefix = parsedCols.find((c) => c.prefixSym)?.prefixSym ?? ''
2100
+
2101
+ let cursorX = 0
2102
+ const columns = parsedCols.map((col, cIdx) => {
2103
+ const widthRatio = effWeights[cIdx] / weightSum
2104
+ const xRatio = cursorX
2105
+ cursorX += widthRatio
2106
+
2107
+ const valBySeries = seriesOrder.map((sName) => {
2108
+ const hit = col.segPairs.find((p) => p.name === sName)
2109
+ return hit ? hit.val : 0
2110
+ })
2111
+ const colSum = valBySeries.reduce((a, b) => a + b, 0) || 1
2112
+ let cursorY = 0
2113
+ const segments = seriesOrder.map((sName, sIdx) => {
2114
+ const heightRatio = valBySeries[sIdx] / colSum
2115
+ const seg = {
2116
+ seriesName: sName,
2117
+ seriesIndex: sIdx,
2118
+ rawVal: valBySeries[sIdx],
2119
+ heightRatio,
2120
+ sharePct: Math.round(heightRatio * 100),
2121
+ yRatio: cursorY,
2122
+ isOurs: OURS_SERIES_RE.test(sName),
2123
+ }
2124
+ cursorY += heightRatio
2125
+ return seg
2126
+ })
2127
+
2128
+ return {
2129
+ title: col.title,
2130
+ weight: effWeights[cIdx],
2131
+ sizeLabel: col.sizeLabel || (Math.round(widthRatio * 100) + '%'),
2132
+ widthRatio,
2133
+ xRatio,
2134
+ segments,
2135
+ }
2136
+ })
2137
+
2138
+ const seriesSummary = seriesOrder.map((name, sIdx) => {
2139
+ const weightedShare = columns.reduce((acc, col) => acc + col.widthRatio * (col.segments[sIdx]?.heightRatio ?? 0), 0)
2140
+ return {
2141
+ name,
2142
+ index: sIdx,
2143
+ weightedPct: Math.round(weightedShare * 100),
2144
+ isOurs: OURS_SERIES_RE.test(name),
2145
+ }
2146
+ })
2147
+
2148
+ const totalLabel = totalRawWeight > 0
2149
+ ? (domPrefix + (Number.isInteger(totalRawWeight) ? totalRawWeight.toLocaleString('en-US') : totalRawWeight.toFixed(1)) + (domUnit && domUnit !== domPrefix ? ' ' + domUnit : ''))
2150
+ : '100%'
2151
+
2152
+ return { columns, seriesSummary, totalLabel, hasExplicitWeights: totalRawWeight > 0 }
2153
+ }
2154
+
2155
+ function mekkoSeriesPalette(theme, seriesSummary) {
2156
+ const tk = theme.tokens
2157
+ const baseColors = [
2158
+ tk.accentPrimary,
2159
+ tk.accentSecondary,
2160
+ mixHex(tk.accentPrimary, theme.dark ? '#94A3B8' : '#475569', 0.48),
2161
+ mixHex(tk.accentSecondary, theme.dark ? '#334155' : '#CBD5E1', 0.45),
2162
+ theme.dark ? '#334155' : '#CBD5E1',
2163
+ theme.dark ? '#1E293B' : '#E2E8F0',
2164
+ ]
2165
+ return seriesSummary.map((s, idx) => {
2166
+ const fill = s.isOurs ? tk.accentPrimary : baseColors[(idx + (seriesSummary[0]?.isOurs ? 0 : 1)) % baseColors.length]
2167
+ const lum = relativeLuminance(fill)
2168
+ const ink = lum < 0.40 ? '#FFFFFF' : '#0F172A'
2169
+ return { fill, ink }
2170
+ })
2171
+ }
2172
+
2173
+ function renderMarimekkoPptx(slide, area, nextIdFn, chromeCfg, theme, langAttr) {
2174
+ const tk = theme.tokens
2175
+ const isEn = langAttr === 'en-US'
2176
+ const model = computeMarimekkoModel(slide, langAttr)
2177
+ const palette = mekkoSeriesPalette(theme, model.seriesSummary)
2178
+ const shapes = []
2179
+
2180
+ const legendW = 2.34
2181
+ const gapLegend = 0.26
2182
+ const plotX = area.x
2183
+ const plotW = area.w - legendW - gapLegend
2184
+ const headerH = 0.58
2185
+ const axisH = 0.38
2186
+ const gridY = area.y + headerH + 0.04
2187
+ const gridH = Math.max(2.2, area.h - headerH - axisH - 0.08)
2188
+
2189
+ // 1. 顶部列宽市场容量标题 + 不等宽 100% 堆叠矩形网格
2190
+ model.columns.forEach((col, cIdx) => {
2191
+ const cx = plotX + col.xRatio * plotW
2192
+ const cw = Math.max(0.28, col.widthRatio * plotW)
2193
+
2194
+ // 列顶标题 + 规模标签(窄列自动收敛至 8pt 零内边距,确保 5 字区域名如“中东及拉美”单行不折字)
2195
+ const isNarrowCol = cw < 0.95
2196
+ const headFontPt = cw >= 1.65 ? 11.5 : cw >= 1.15 ? 10 : cw >= 0.95 ? 9 : cw >= 0.60 ? 8 : 7.5
2197
+ shapes.push(ooxmlShape(nextIdFn(), 'Mekko Col Header ' + (cIdx + 1), {
2198
+ x: isNarrowCol ? cx : cx + 0.02,
2199
+ y: area.y,
2200
+ w: isNarrowCol ? Math.max(0.28, cw) : Math.max(0.24, cw - 0.04),
2201
+ h: headerH,
2202
+ }, {
2203
+ txBox: true,
2204
+ anchor: 'b',
2205
+ marginsIn: { l: isNarrowCol ? 0 : 0.02, r: isNarrowCol ? 0 : 0.02, t: 0, b: 0.03 },
2206
+ paragraphs: [
2207
+ ooxmlRichParagraph(col.title, {
2208
+ sizePt: headFontPt,
2209
+ color: tk.inkPrimary,
2210
+ bold: true,
2211
+ lang: langAttr,
2212
+ align: 'ctr',
2213
+ font: theme.fonts.heading,
2214
+ lineHeight: 1.12,
2215
+ spaceAfterPt: 1,
2216
+ }),
2217
+ ooxmlRichParagraph(col.sizeLabel, {
2218
+ sizePt: isNarrowCol ? 7.5 : Math.max(8.5, headFontPt - 1),
2219
+ color: tk.accentText,
2220
+ bold: true,
2221
+ lang: langAttr,
2222
+ align: 'ctr',
2223
+ font: theme.fonts.body,
2224
+ lineHeight: 1.08,
2225
+ }),
2226
+ ],
2227
+ }))
2228
+
2229
+ col.segments.forEach((seg, sIdx) => {
2230
+ if (seg.heightRatio <= 0.002) return
2231
+ const sy = gridY + seg.yRatio * gridH
2232
+ const sh = Math.max(0.04, seg.heightRatio * gridH)
2233
+ const pal = palette[sIdx] ?? { fill: tk.surface2, ink: tk.inkPrimary }
2234
+ const pctText = seg.sharePct + '%'
2235
+ const showTwoLines = sh >= 0.50 && cw >= 1.22
2236
+ const showPctOnly = !showTwoLines && sh >= 0.25 && cw >= 0.72
2237
+
2238
+ const paras = showTwoLines
2239
+ ? [
2240
+ ooxmlRichParagraph(seg.seriesName, {
2241
+ sizePt: cw >= 1.6 ? 11 : 10,
2242
+ color: pal.ink,
2243
+ bold: true,
2244
+ lang: langAttr,
2245
+ align: 'ctr',
2246
+ font: theme.fonts.body,
2247
+ lineHeight: 1.1,
2248
+ spaceAfterPt: 1,
2249
+ }),
2250
+ ooxmlRichParagraph(pctText, {
2251
+ sizePt: cw >= 1.6 ? 12 : 10.5,
2252
+ color: pal.ink,
2253
+ bold: true,
2254
+ lang: langAttr,
2255
+ align: 'ctr',
2256
+ font: theme.fonts.heading,
2257
+ lineHeight: 1.05,
2258
+ }),
2259
+ ]
2260
+ : showPctOnly
2261
+ ? [
2262
+ ooxmlRichParagraph(pctText, {
2263
+ sizePt: 10,
2264
+ color: pal.ink,
2265
+ bold: true,
2266
+ lang: langAttr,
2267
+ align: 'ctr',
2268
+ font: theme.fonts.heading,
2269
+ lineHeight: 1.0,
2270
+ }),
2271
+ ]
2272
+ : []
2273
+
2274
+ shapes.push(ooxmlShape(nextIdFn(), 'Mekko Cell ' + (cIdx + 1) + '-' + (sIdx + 1), { x: cx, y: sy, w: cw, h: sh }, {
2275
+ preset: 'rect',
2276
+ fill: pal.fill,
2277
+ stroke: tk.canvas,
2278
+ strokePt: 1.5,
2279
+ anchor: 'ctr',
2280
+ autofit: false,
2281
+ marginsIn: { l: 0.04, r: 0.04, t: 0.02, b: 0.02 },
2282
+ paragraphs: paras,
2283
+ }))
2284
+ })
2285
+ })
2286
+
2287
+ // 2. 底部 0%..100% 市场宽度累计坐标轴
2288
+ const axisY = gridY + gridH + 0.08
2289
+ shapes.push(ooxmlLine(nextIdFn(), 'Mekko Width Axis', { x: plotX, y: axisY }, { x: plotX + plotW, y: axisY }, {
2290
+ color: tk.inkMuted,
2291
+ widthPt: 1.0,
2292
+ }))
2293
+ ;[0, 25, 50, 75, 100].forEach((tick) => {
2294
+ const tx = plotX + (tick / 100) * plotW
2295
+ shapes.push(ooxmlLine(nextIdFn(), 'Mekko Tick ' + tick, { x: tx, y: axisY }, { x: tx, y: axisY + 0.06 }, {
2296
+ color: tk.inkMuted,
2297
+ widthPt: 0.75,
2298
+ }))
2299
+ const lblW = 0.68
2300
+ const lblX = tick === 0 ? tx : tick === 100 ? tx - lblW : tx - lblW / 2
2301
+ const algn = tick === 0 ? 'l' : tick === 100 ? 'r' : 'ctr'
2302
+ shapes.push(ooxmlShape(nextIdFn(), 'Mekko Tick Label ' + tick, { x: lblX, y: axisY + 0.07, w: lblW, h: 0.24 }, {
2303
+ txBox: true,
2304
+ anchor: 'ctr',
2305
+ marginsIn: { l: 0, r: 0, t: 0, b: 0 },
2306
+ paragraphs: [
2307
+ ooxmlRichParagraph(tick + '%', {
2308
+ sizePt: 9.5,
2309
+ color: tk.inkMuted,
2310
+ lang: langAttr,
2311
+ align: algn,
2312
+ font: theme.fonts.body,
2313
+ lineHeight: 1.0,
2314
+ }),
2315
+ ],
2316
+ }))
2317
+ })
2318
+
2319
+ // 3. 右侧总市场规模 + 系列图例卡片
2320
+ const legX = plotX + plotW + gapLegend
2321
+ const legBox = { x: legX, y: gridY, w: legendW, h: gridH }
2322
+ shapes.push(renderSurfaceCardPptx('Mekko Legend Card', legBox, {
2323
+ fill: tk.surface1,
2324
+ focal: false,
2325
+ }, nextIdFn, chromeCfg, theme))
2326
+
2327
+ shapes.push(ooxmlShape(nextIdFn(), 'Mekko Total Summary', { x: legX + 0.16, y: gridY + 0.14, w: legendW - 0.32, h: 0.78 }, {
2328
+ txBox: true,
2329
+ anchor: 't',
2330
+ marginsIn: { l: 0, r: 0, t: 0, b: 0 },
2331
+ paragraphs: [
2332
+ ooxmlRichParagraph(isEn ? 'TOTAL MARKET' : '总市场规模', {
2333
+ sizePt: 9.5,
2334
+ color: tk.inkMuted,
2335
+ bold: true,
2336
+ lang: langAttr,
2337
+ font: theme.fonts.body,
2338
+ spc: 90,
2339
+ spaceAfterPt: 2,
2340
+ }),
2341
+ ooxmlRichParagraph(model.totalLabel, {
2342
+ sizePt: 20,
2343
+ color: tk.accentText,
2344
+ bold: true,
2345
+ lang: langAttr,
2346
+ font: theme.fonts.heading,
2347
+ lineHeight: 1.1,
2348
+ }),
2349
+ ],
2350
+ }))
2351
+ shapes.push(ooxmlLine(nextIdFn(), 'Mekko Legend Rule', { x: legX + 0.16, y: gridY + 0.98 }, { x: legX + legendW - 0.16, y: gridY + 0.98 }, {
2352
+ color: tk.hairline,
2353
+ widthPt: 0.75,
2354
+ }))
2355
+
2356
+ const itemStartY = gridY + 1.12
2357
+ const availLegH = Math.max(1.0, gridH - 1.24)
2358
+ const itemStepY = Math.min(0.46, availLegH / Math.max(1, model.seriesSummary.length))
2359
+ model.seriesSummary.forEach((s, idx) => {
2360
+ const iy = itemStartY + idx * itemStepY
2361
+ const pal = palette[idx] ?? { fill: tk.surface2 }
2362
+ shapes.push(ooxmlShape(nextIdFn(), 'Mekko Swatch ' + (idx + 1), { x: legX + 0.18, y: iy + 0.08, w: 0.18, h: 0.18 }, {
2363
+ preset: 'rect',
2364
+ fill: pal.fill,
2365
+ stroke: tk.hairline,
2366
+ strokePt: 0.5,
2367
+ }))
2368
+ shapes.push(ooxmlShape(nextIdFn(), 'Mekko Series Label ' + (idx + 1), { x: legX + 0.44, y: iy, w: legendW - 0.58, h: 0.34 }, {
2369
+ txBox: true,
2370
+ anchor: 'ctr',
2371
+ marginsIn: { l: 0, r: 0, t: 0, b: 0 },
2372
+ paragraphs: [
2373
+ ooxmlRichParagraph(s.name + ' **' + s.weightedPct + '%**', {
2374
+ sizePt: 11,
2375
+ color: s.isOurs ? tk.accentText : tk.inkPrimary,
2376
+ bold: s.isOurs,
2377
+ lang: langAttr,
2378
+ font: theme.fonts.body,
2379
+ lineHeight: 1.15,
2380
+ }),
2381
+ ],
2382
+ }))
2383
+ })
2384
+
2385
+ return shapes.join('')
2386
+ }
2387
+
2388
+ function renderMarimekkoHtml(slide, theme, langId) {
2389
+ const isEn = langId === 'en'
2390
+ const model = computeMarimekkoModel(slide, langId)
2391
+ const palette = mekkoSeriesPalette(theme, model.seriesSummary)
2392
+
2393
+ return (
2394
+ '<div class="mekko-board">' +
2395
+ '<div class="mekko-main">' +
2396
+ '<div class="mekko-headers">' +
2397
+ model.columns.map((col) =>
2398
+ '<div class="mekko-col-head" style="flex:' + col.widthRatio.toFixed(5) + ' 0 0%">' +
2399
+ '<strong class="mekko-col-title">' + escapeHtml(col.title) + '</strong>' +
2400
+ '<span class="mekko-col-size">' + escapeHtml(col.sizeLabel) + '</span>' +
2401
+ '</div>',
2402
+ ).join('') +
2403
+ '</div>' +
2404
+ '<div class="mekko-columns">' +
2405
+ model.columns.map((col, cIdx) =>
2406
+ '<div class="mekko-col" data-col-index="' + cIdx + '" style="flex:' + col.widthRatio.toFixed(5) + ' 0 0%">' +
2407
+ col.segments.filter((s) => s.heightRatio > 0.002).map((seg) => {
2408
+ const pal = palette[seg.seriesIndex] ?? { fill: theme.tokens.surface2, ink: theme.tokens.inkPrimary }
2409
+ const showFull = seg.heightRatio >= 0.14 && col.widthRatio >= 0.14
2410
+ const showPct = seg.heightRatio >= 0.07 && col.widthRatio >= 0.08
2411
+ return (
2412
+ '<div class="mekko-cell' + (seg.isOurs ? ' is-ours' : '') + '" style="flex:' + seg.heightRatio.toFixed(5) + ' 0 0%;background:' + pal.fill + ';color:' + pal.ink + '">' +
2413
+ (showFull ? '<span class="mekko-seg-name">' + escapeHtml(seg.seriesName) + '</span>' : '') +
2414
+ (showFull || showPct ? '<strong class="mekko-seg-pct">' + seg.sharePct + '%</strong>' : '') +
2415
+ '</div>'
2416
+ )
2417
+ }).join('') +
2418
+ '</div>',
2419
+ ).join('') +
2420
+ '</div>' +
2421
+ '<div class="mekko-axis"><span>0%</span><span>25%</span><span>50%</span><span>75%</span><span>100%</span></div>' +
2422
+ '</div>' +
2423
+ '<aside class="surface-card mekko-legend">' +
2424
+ '<div class="mekko-total"><span class="kicker">' + (isEn ? 'TOTAL MARKET' : '总市场规模') + '</span><strong>' + escapeHtml(model.totalLabel) + '</strong></div>' +
2425
+ '<ul class="mekko-legend-list">' +
2426
+ model.seriesSummary.map((s, idx) => {
2427
+ const pal = palette[idx] ?? { fill: theme.tokens.surface2 }
2428
+ return (
2429
+ '<li class="' + (s.isOurs ? 'is-ours' : '') + '">' +
2430
+ '<span class="mekko-swatch" style="background:' + pal.fill + '"></span>' +
2431
+ '<span class="mekko-leg-name">' + escapeHtml(s.name) + '</span>' +
2432
+ '<strong class="mekko-leg-pct">' + s.weightedPct + '%</strong>' +
2433
+ '</li>'
2434
+ )
2435
+ }).join('') +
2436
+ '</ul></aside></div>'
2437
+ )
2438
+ }
2439
+
2440
+ function classifySankeyNodeTone(name, explicitStatus) {
2441
+ if (explicitStatus && VALID_STATUS.has(explicitStatus)) return explicitStatus
2442
+ const s = String(name ?? '')
2443
+ if (/成本|费用|支出|损耗|流失|税|折旧|研发投入|营销|管理费|cost|cogs|opex|expense|tax|loss|churn/i.test(s)) return 'negative'
2444
+ if (/净利润|营业利润|毛利润|毛利|净利|盈余|自由现金流|留存|profit|income|ebitda|margin|fcf/i.test(s)) return 'positive'
2445
+ return 'accent'
2446
+ }
2447
+
2448
+ export function computeSankeyLayout(slide, areaBox = { x: 0.62, y: 1.88, w: 12.09, h: 4.50 }, langOrAttr = 'zh') {
2449
+ const isEn = langOrAttr === 'en' || langOrAttr === 'en-US'
2450
+ const rawEdges = []
2451
+
2452
+ const effItems = resolveEffectiveItems(slide)
2453
+ if (effItems.length > 0 && effItems.some((it) => it.tag && it.title && !/^\d+$/.test(it.tag))) {
2454
+ for (const it of effItems) {
2455
+ const src = (it.tag || '').trim()
2456
+ const dst = (it.title || '').trim()
2457
+ if (!src || !dst || src === dst) continue
2458
+ const parsed = extractNumberAndUnit((it.value ?? '') + (it.unit ?? ''))
2459
+ const val = parsed.num > 0 ? parsed.num : 10
2460
+ const unit = it.unit || parsed.unit || ''
2461
+ const valLabel = it.value
2462
+ ? (it.value + (it.unit && !String(it.value).endsWith(it.unit) ? it.unit : ''))
2463
+ : (parsed.label || String(val))
2464
+ rawEdges.push({
2465
+ source: src,
2466
+ target: dst,
2467
+ value: val,
2468
+ unit,
2469
+ valueLabel: valLabel,
2470
+ delta: it.delta || '',
2471
+ status: it.status,
2472
+ })
2473
+ }
2474
+ } else if (Array.isArray(slide.rows) && slide.rows.length >= 2) {
2475
+ const startIdx = isNumericCell(slide.rows[0]?.[2] ?? '') ? 0 : 1
2476
+ for (const r of slide.rows.slice(startIdx)) {
2477
+ const src = stripInlineMarkdown(r[0] ?? '')
2478
+ const dst = stripInlineMarkdown(r[1] ?? '')
2479
+ if (!src || !dst || src === dst) continue
2480
+ const parsed = extractNumberAndUnit(r[2] ?? '10')
2481
+ rawEdges.push({
2482
+ source: src,
2483
+ target: dst,
2484
+ value: parsed.num > 0 ? parsed.num : 10,
2485
+ unit: parsed.unit,
2486
+ valueLabel: parsed.label || stripInlineMarkdown(r[2] ?? ''),
2487
+ delta: stripInlineMarkdown(r[3] ?? ''),
2488
+ status: undefined,
2489
+ })
2490
+ }
2491
+ }
2492
+
2493
+ if (rawEdges.length === 0) {
2494
+ if (isEn) {
2495
+ rawEdges.push(
2496
+ { source: 'Total Revenue', target: 'Gross Profit', value: 68.5, unit: 'B', valueLabel: '$68.5B', status: 'positive' },
2497
+ { source: 'Total Revenue', target: 'Cost of Revenue', value: 31.5, unit: 'B', valueLabel: '$31.5B', status: 'negative' },
2498
+ { source: 'Gross Profit', target: 'Operating Income', value: 34.5, unit: 'B', valueLabel: '$34.5B', status: 'positive' },
2499
+ { source: 'Gross Profit', target: 'R&D', value: 22.0, unit: 'B', valueLabel: '$22.0B', status: 'negative' },
2500
+ { source: 'Gross Profit', target: 'SG&A', value: 12.0, unit: 'B', valueLabel: '$12.0B', status: 'negative' },
2501
+ )
2502
+ } else {
2503
+ rawEdges.push(
2504
+ { source: '总营收', target: '毛利润', value: 68.5, unit: '亿', valueLabel: '68.5亿', status: 'positive' },
2505
+ { source: '总营收', target: '营业成本', value: 31.5, unit: '亿', valueLabel: '31.5亿', status: 'negative' },
2506
+ { source: '毛利润', target: '营业利润', value: 34.5, unit: '亿', valueLabel: '34.5亿', status: 'positive' },
2507
+ { source: '毛利润', target: '研发投入', value: 22.0, unit: '亿', valueLabel: '22.0亿', status: 'negative' },
2508
+ { source: '毛利润', target: '营销及管理', value: 12.0, unit: '亿', valueLabel: '12.0亿', status: 'negative' },
2509
+ )
2510
+ }
2511
+ }
2512
+
2513
+ const nodeMap = new Map()
2514
+ const getOrCreate = (name) => {
2515
+ if (!nodeMap.has(name)) {
2516
+ nodeMap.set(name, {
2517
+ name,
2518
+ inEdges: [],
2519
+ outEdges: [],
2520
+ inSum: 0,
2521
+ outSum: 0,
2522
+ layer: 0,
2523
+ tone: 'accent',
2524
+ unit: '',
2525
+ delta: '',
2526
+ })
2527
+ }
2528
+ return nodeMap.get(name)
2529
+ }
2530
+
2531
+ const edges = []
2532
+ for (const e of rawEdges) {
2533
+ const u = getOrCreate(e.source)
2534
+ const v = getOrCreate(e.target)
2535
+ const edgeObj = { ...e, sourceNode: u, targetNode: v }
2536
+ u.outEdges.push(edgeObj)
2537
+ v.inEdges.push(edgeObj)
2538
+ u.outSum += e.value
2539
+ v.inSum += e.value
2540
+ if (!v.unit && e.unit) v.unit = e.unit
2541
+ if (!u.unit && e.unit) u.unit = e.unit
2542
+ if (e.delta && !v.delta) v.delta = e.delta
2543
+ if (e.status) v.tone = e.status
2544
+ edges.push(edgeObj)
2545
+ }
2546
+
2547
+ const nodes = [...nodeMap.values()]
2548
+ // 拓扑分层(防环最多迭代 nodes.length 次,最多 4 列)
2549
+ for (let pass = 0; pass < nodes.length; pass += 1) {
2550
+ let changed = false
2551
+ for (const e of edges) {
2552
+ if (e.targetNode.layer <= e.sourceNode.layer && e.sourceNode.layer < 3) {
2553
+ const nextL = Math.min(3, e.sourceNode.layer + 1)
2554
+ if (nextL > e.targetNode.layer) {
2555
+ e.targetNode.layer = nextL
2556
+ changed = true
2557
+ }
2558
+ }
2559
+ }
2560
+ if (!changed) break
2561
+ }
2562
+
2563
+ const maxLayer = Math.max(1, ...nodes.map((n) => n.layer))
2564
+ const layerCount = maxLayer + 1
2565
+
2566
+ for (const n of nodes) {
2567
+ n.val = Math.max(n.inSum, n.outSum, 0.01)
2568
+ n.tone = classifySankeyNodeTone(n.name, n.inEdges[0]?.status)
2569
+ const formattedNum = Number.isInteger(n.val) ? String(n.val) : n.val.toFixed(1).replace(/\.0$/, '')
2570
+ n.displayValue = (n.inEdges.length === 1 && n.outEdges.length === 0 && n.inEdges[0].valueLabel)
2571
+ ? n.inEdges[0].valueLabel
2572
+ : formattedNum + (n.unit || '')
2573
+ }
2574
+
2575
+ const layers = Array.from({ length: layerCount }, (_, l) => nodes.filter((n) => n.layer === l))
2576
+ // 预留顶部浮动标签高度 + 左右标签栏宽度
2577
+ const leftLabelW = 2.02
2578
+ const rightLabelW = 2.62
2579
+ const topPad = 0.46
2580
+ const botPad = 0.14
2581
+ const plotX = areaBox.x + leftLabelW
2582
+ const plotW = Math.max(3.6, areaBox.w - leftLabelW - rightLabelW)
2583
+ const plotY = areaBox.y + topPad
2584
+ const plotH = Math.max(2.0, areaBox.h - topPad - botPad)
2585
+ const barW = 0.24
2586
+ const nodeGap = 0.30
2587
+
2588
+ // 能量守恒全局比例尺 ky(英寸/单位数值)
2589
+ let ky = Infinity
2590
+ for (const col of layers) {
2591
+ if (col.length === 0) continue
2592
+ const valSum = col.reduce((s, n) => s + n.val, 0)
2593
+ const avail = Math.max(0.8, plotH * 0.84 - Math.max(0, col.length - 1) * nodeGap)
2594
+ ky = Math.min(ky, avail / Math.max(valSum, 1e-6))
2595
+ }
2596
+ if (!Number.isFinite(ky) || ky <= 0) ky = 0.03
2597
+
2598
+ // 在同层内将正向/主干节点排上方、负向成本节点排下方,减少交叉且符合损益表视觉直觉
2599
+ const toneRank = (n) => (n.outEdges.length > 0 ? 0 : n.tone === 'positive' ? 1 : n.tone === 'accent' ? 2 : 3)
2600
+ layers[0].sort((a, b) => toneRank(a) - toneRank(b) || b.val - a.val)
2601
+
2602
+ // Layer 0 垂直居中排布
2603
+ {
2604
+ const col0 = layers[0]
2605
+ col0.forEach((n) => {
2606
+ n.x = plotX
2607
+ n.w = barW
2608
+ n.h = Math.max(0.16, n.val * ky)
2609
+ })
2610
+ const totalH0 = col0.reduce((s, n) => s + n.h, 0) + Math.max(0, col0.length - 1) * nodeGap
2611
+ let cy = plotY + Math.max(0, (plotH - totalH0) / 2)
2612
+ for (const n of col0) {
2613
+ n.y = cy
2614
+ cy += n.h + nodeGap
2615
+ }
2616
+ }
2617
+
2618
+ // 逐层计算父节点出港端口,再用父端口加权重心法定位子层节点 Y(使毛利润拆解保持在上半带、营业成本独占下半带!)
2619
+ const assignOutPorts = (col) => {
2620
+ for (const u of col) {
2621
+ u.outEdges.sort((a, b) => toneRank(a.targetNode) - toneRank(b.targetNode) || a.targetNode.layer - b.targetNode.layer)
2622
+ const outTotal = u.outEdges.reduce((s, e) => s + e.value, 0) || u.val
2623
+ const scale = u.h / Math.max(outTotal, u.val)
2624
+ let py = u.y
2625
+ for (const e of u.outEdges) {
2626
+ const eh = Math.max(0.03, e.value * scale)
2627
+ e.sy0 = py
2628
+ e.sy1 = py + eh
2629
+ py += eh
2630
+ }
2631
+ }
2632
+ }
2633
+
2634
+ assignOutPorts(layers[0])
2635
+
2636
+ for (let l = 1; l < layerCount; l += 1) {
2637
+ const col = layers[l]
2638
+ const colX = plotX + (l / Math.max(1, layerCount - 1)) * (plotW - barW)
2639
+ for (const n of col) {
2640
+ n.x = colX
2641
+ n.w = barW
2642
+ n.h = Math.max(0.16, n.val * ky)
2643
+ if (n.inEdges.length > 0) {
2644
+ const wSum = n.inEdges.reduce((s, e) => s + e.value, 0) || 1
2645
+ const targetMid = n.inEdges.reduce((s, e) => s + ((e.sy0 + e.sy1) / 2) * e.value, 0) / wSum
2646
+ n.idealY = targetMid - n.h / 2
2647
+ } else {
2648
+ n.idealY = plotY
2649
+ }
2650
+ }
2651
+ col.sort((a, b) => a.idealY - b.idealY || toneRank(a) - toneRank(b))
2652
+
2653
+ // 自顶向下与自底向上碰撞消解,严格守住画布上下界与最小节点间距
2654
+ let cursor = plotY
2655
+ for (const n of col) {
2656
+ n.y = Math.max(cursor, n.idealY)
2657
+ cursor = n.y + n.h + nodeGap
2658
+ }
2659
+ let bottomLimit = plotY + plotH
2660
+ for (let i = col.length - 1; i >= 0; i -= 1) {
2661
+ const n = col[i]
2662
+ if (n.y + n.h > bottomLimit) {
2663
+ n.y = Math.max(plotY, bottomLimit - n.h)
2664
+ }
2665
+ bottomLimit = n.y - nodeGap
2666
+ }
2667
+ assignOutPorts(col)
2668
+ }
2669
+
2670
+ // 计算每个目标节点的入港端口 [ty0, ty1]
2671
+ for (const v of nodes) {
2672
+ v.inEdges.sort((a, b) => a.sourceNode.y - b.sourceNode.y)
2673
+ const inTotal = v.inEdges.reduce((s, e) => s + e.value, 0) || v.val
2674
+ const scale = v.h / Math.max(inTotal, v.val)
2675
+ let py = v.y
2676
+ for (const e of v.inEdges) {
2677
+ const eh = Math.max(0.03, e.value * scale)
2678
+ e.ty0 = py
2679
+ e.ty1 = py + eh
2680
+ py += eh
2681
+ }
2682
+ }
2683
+
2684
+ return { nodes, edges, layers, layerCount, areaBox, plotX, plotW, plotY, plotH, leftLabelW, rightLabelW }
2685
+ }
2686
+
2687
+ function sankeyNodeColor(node, theme) {
2688
+ const tk = theme.tokens
2689
+ if (node.layer === 0) return tk.accentPrimary
2690
+ if (node.tone === 'positive') return tk.positive
2691
+ if (node.tone === 'negative') return tk.negative
2692
+ if (node.tone === 'warning') return tk.warning
2693
+ return tk.accentSecondary
2694
+ }
2695
+
2696
+ function renderSankeyPptx(slide, area, nextIdFn, chromeCfg, theme, langAttr) {
2697
+ const tk = theme.tokens
2698
+ const model = computeSankeyLayout(slide, area, langAttr)
2699
+ const shapes = []
2700
+
2701
+ // 1. 先绘制平滑三次贝塞尔闭合流向丝带 (<a:custGeom>)
2702
+ model.edges.forEach((e, idx) => {
2703
+ const x0 = e.sourceNode.x + e.sourceNode.w
2704
+ const x1 = e.targetNode.x
2705
+ const rw = Math.max(0.08, x1 - x0)
2706
+ const ry = Math.min(e.sy0, e.ty0)
2707
+ const maxBottom = Math.max(e.sy1, e.ty1)
2708
+ const rh = Math.max(0.04, maxBottom - ry)
2709
+
2710
+ const W = 10000
2711
+ const H = 10000
2712
+ const sy0 = Math.round(((e.sy0 - ry) / rh) * H)
2713
+ const sy1 = Math.round(((e.sy1 - ry) / rh) * H)
2714
+ const ty0 = Math.round(((e.ty0 - ry) / rh) * H)
2715
+ const ty1 = Math.round(((e.ty1 - ry) / rh) * H)
2716
+
2717
+ const pathXml =
2718
+ '<a:moveTo><a:pt x="0" y="' + sy0 + '"/></a:moveTo>' +
2719
+ '<a:cubicBezTo><a:pt x="4600" y="' + sy0 + '"/><a:pt x="5400" y="' + ty0 + '"/><a:pt x="' + W + '" y="' + ty0 + '"/></a:cubicBezTo>' +
2720
+ '<a:lnTo><a:pt x="' + W + '" y="' + ty1 + '"/></a:lnTo>' +
2721
+ '<a:cubicBezTo><a:pt x="5400" y="' + ty1 + '"/><a:pt x="4600" y="' + sy1 + '"/><a:pt x="0" y="' + sy1 + '"/></a:cubicBezTo>' +
2722
+ '<a:close/>'
2723
+
2724
+ const ribbonColor = sankeyNodeColor(e.targetNode, theme)
2725
+ shapes.push(ooxmlCustGeomShape(nextIdFn(), 'Sankey Ribbon ' + (idx + 1), { x: x0, y: ry, w: rw, h: rh }, pathXml, {
2726
+ pathW: W,
2727
+ pathH: H,
2728
+ fill: ribbonColor,
2729
+ fillAlpha: theme.dark ? 0.42 : 0.32,
2730
+ }))
2731
+ })
2732
+
2733
+ // 2. 绘制守恒节点立柱 + 零碰撞语义数值标签
2734
+ model.nodes.forEach((n, idx) => {
2735
+ const barColor = sankeyNodeColor(n, theme)
2736
+ shapes.push(ooxmlShape(nextIdFn(), 'Sankey Node ' + (idx + 1), { x: n.x, y: n.y, w: n.w, h: n.h }, {
2737
+ preset: chromeCfg.cardRadiusPx > 0 ? 'roundRect' : 'rect',
2738
+ adj: roundRectAdj(n.w, n.h, Math.min(4, chromeCfg.cardRadiusPx)),
2739
+ fill: barColor,
2740
+ }))
2741
+
2742
+ const valColor = n.tone === 'positive'
2743
+ ? tk.positive
2744
+ : n.tone === 'negative'
2745
+ ? tk.negative
2746
+ : tk.accentText
2747
+ const valLine = n.displayValue + (n.delta ? ' (' + n.delta + ')' : '')
2748
+ const isLeftRoot = n.layer === 0
2749
+ const isLeaf = n.outEdges.length === 0
2750
+
2751
+ if (isLeftRoot) {
2752
+ const lblBox = {
2753
+ x: area.x,
2754
+ y: n.y + n.h / 2 - 0.32,
2755
+ w: Math.max(1.2, n.x - area.x - 0.12),
2756
+ h: 0.64,
2757
+ }
2758
+ shapes.push(ooxmlShape(nextIdFn(), 'Sankey Label ' + (idx + 1), lblBox, {
2759
+ txBox: true,
2760
+ anchor: 'ctr',
2761
+ marginsIn: { l: 0, r: 0.02, t: 0, b: 0 },
2762
+ paragraphs: [
2763
+ ooxmlRichParagraph(n.name, { sizePt: 12.5, color: tk.inkPrimary, bold: true, lang: langAttr, align: 'r', font: theme.fonts.heading, lineHeight: 1.12, spaceAfterPt: 1 }),
2764
+ ooxmlRichParagraph(valLine, { sizePt: 13.5, color: tk.accentText, bold: true, lang: langAttr, align: 'r', font: theme.fonts.heading, lineHeight: 1.08 }),
2765
+ ],
2766
+ }))
2767
+ } else if (isLeaf) {
2768
+ const rightEdge = area.x + area.w
2769
+ const lx = n.x + n.w + 0.12
2770
+ const maxLeafW = model.layerCount >= 4 && n.layer < model.layerCount - 1 ? 2.02 : 2.6
2771
+ const lw = Math.min(maxLeafW, Math.max(1.3, rightEdge - lx))
2772
+ const lblBox = {
2773
+ x: lx,
2774
+ y: n.y + n.h / 2 - 0.28,
2775
+ w: lw,
2776
+ h: 0.56,
2777
+ }
2778
+ shapes.push(ooxmlShape(nextIdFn(), 'Sankey Label ' + (idx + 1), lblBox, {
2779
+ txBox: true,
2780
+ anchor: 'ctr',
2781
+ marginsIn: { l: 0.02, r: 0, t: 0, b: 0 },
2782
+ paragraphs: [
2783
+ ooxmlRichParagraph(n.name + ' **' + valLine + '**', {
2784
+ sizePt: model.layerCount >= 4 && n.layer < model.layerCount - 1 ? 10.5 : 11.5,
2785
+ color: tk.inkPrimary,
2786
+ accentColor: valColor,
2787
+ bold: false,
2788
+ lang: langAttr,
2789
+ align: 'l',
2790
+ font: theme.fonts.body,
2791
+ lineHeight: 1.15,
2792
+ }),
2793
+ ],
2794
+ }))
2795
+ } else {
2796
+ // 中间枢纽节点(既有入流又有出流):置于立柱正上方胶囊标签,彻底避开左右两侧流向丝带!
2797
+ const pillFontPt = model.layerCount >= 4 ? 10 : 11
2798
+ const pillMaxW = model.layerCount >= 4 ? 2.22 : 2.8
2799
+ const pillText = n.name + ' · ' + valLine
2800
+ const pillW = computeBadgePillWidth(pillText, pillFontPt, pillMaxW, 1.30)
2801
+ const pillBox = {
2802
+ x: n.x + n.w / 2 - pillW / 2,
2803
+ y: Math.max(area.y, n.y - 0.40),
2804
+ w: pillW,
2805
+ h: 0.34,
2806
+ }
2807
+ shapes.push(ooxmlShape(nextIdFn(), 'Sankey Label ' + (idx + 1), pillBox, {
2808
+ preset: chromeCfg.cardRadiusPx > 0 ? 'roundRect' : 'rect',
2809
+ adj: roundRectAdj(pillBox.w, pillBox.h, Math.min(8, chromeCfg.cardRadiusPx)),
2810
+ fill: tk.surface2,
2811
+ stroke: barColor,
2812
+ strokePt: 0.75,
2813
+ anchor: 'ctr',
2814
+ marginsIn: { l: 0.06, r: 0.06, t: 0.02, b: 0.02 },
2815
+ paragraphs: [
2816
+ ooxmlRichParagraph(n.name + ' **' + valLine + '**', {
2817
+ sizePt: pillFontPt,
2818
+ color: tk.inkPrimary,
2819
+ bold: true,
2820
+ lang: langAttr,
2821
+ align: 'ctr',
2822
+ font: theme.fonts.heading,
2823
+ lineHeight: 1.05,
2824
+ }),
2825
+ ],
2826
+ }))
2827
+ }
2828
+ })
2829
+
2830
+ return shapes.join('')
2831
+ }
2832
+
2833
+ function renderSankeyHtml(slide, theme, langId) {
2834
+ const tk = theme.tokens
2835
+ const area = { x: 0, y: 0, w: 12.0, h: 4.5 }
2836
+ const model = computeSankeyLayout(slide, area, langId)
2837
+ const scale = 100 // 1200 x 450 SVG 视口
2838
+
2839
+ const ribbonsSvg = model.edges.map((e) => {
2840
+ const x0 = (e.sourceNode.x + e.sourceNode.w) * scale
2841
+ const x1 = e.targetNode.x * scale
2842
+ const cx0 = x0 + (x1 - x0) * 0.46
2843
+ const cx1 = x0 + (x1 - x0) * 0.54
2844
+ const sy0 = e.sy0 * scale
2845
+ const sy1 = e.sy1 * scale
2846
+ const ty0 = e.ty0 * scale
2847
+ const ty1 = e.ty1 * scale
2848
+ const d =
2849
+ 'M ' + x0.toFixed(1) + ' ' + sy0.toFixed(1) +
2850
+ ' C ' + cx0.toFixed(1) + ' ' + sy0.toFixed(1) + ', ' + cx1.toFixed(1) + ' ' + ty0.toFixed(1) + ', ' + x1.toFixed(1) + ' ' + ty0.toFixed(1) +
2851
+ ' L ' + x1.toFixed(1) + ' ' + ty1.toFixed(1) +
2852
+ ' C ' + cx1.toFixed(1) + ' ' + ty1.toFixed(1) + ', ' + cx0.toFixed(1) + ' ' + sy1.toFixed(1) + ', ' + x0.toFixed(1) + ' ' + sy1.toFixed(1) +
2853
+ ' Z'
2854
+ const fill = sankeyNodeColor(e.targetNode, theme)
2855
+ const op = theme.dark ? '0.42' : '0.32'
2856
+ return '<path class="sankey-ribbon" d="' + d + '" fill="' + fill + '" fill-opacity="' + op + '"/>'
2857
+ }).join('')
2858
+
2859
+ const nodesSvg = model.nodes.map((n) => {
2860
+ const barColor = sankeyNodeColor(n, theme)
2861
+ const rx = n.x * scale
2862
+ const ry = n.y * scale
2863
+ const rw = n.w * scale
2864
+ const rh = n.h * scale
2865
+ const valLine = n.displayValue + (n.delta ? ' (' + n.delta + ')' : '')
2866
+ const isLeftRoot = n.layer === 0
2867
+ const isLeaf = n.outEdges.length === 0
2868
+
2869
+ let labelSvg = ''
2870
+ if (isLeftRoot) {
2871
+ const lx = (rx - 12).toFixed(1)
2872
+ const ly = (ry + rh / 2).toFixed(1)
2873
+ labelSvg =
2874
+ '<text x="' + lx + '" y="' + (Number(ly) - 7).toFixed(1) + '" text-anchor="end" fill="' + tk.inkPrimary + '" font-size="15" font-weight="700">' + escapeHtml(n.name) + '</text>' +
2875
+ '<text x="' + lx + '" y="' + (Number(ly) + 14).toFixed(1) + '" text-anchor="end" fill="' + tk.accentText + '" font-size="16" font-weight="800">' + escapeHtml(valLine) + '</text>'
2876
+ } else if (isLeaf) {
2877
+ const lx = (rx + rw + 12).toFixed(1)
2878
+ const ly = (ry + rh / 2 + 5).toFixed(1)
2879
+ labelSvg =
2880
+ '<text x="' + lx + '" y="' + ly + '" text-anchor="start" fill="' + tk.inkPrimary + '" font-size="14" font-weight="600">' +
2881
+ escapeHtml(n.name) + ' <tspan fill="' + barColor + '" font-weight="800">' + escapeHtml(valLine) + '</tspan></text>'
2882
+ } else {
2883
+ const cx = (rx + rw / 2).toFixed(1)
2884
+ const cy = Math.max(20, ry - 12).toFixed(1)
2885
+ labelSvg =
2886
+ '<text x="' + cx + '" y="' + cy + '" text-anchor="middle" fill="' + tk.inkPrimary + '" font-size="14" font-weight="700">' +
2887
+ escapeHtml(n.name + ' · ' + valLine) + '</text>'
2888
+ }
2889
+
2890
+ return (
2891
+ '<g class="sankey-node">' +
2892
+ '<rect x="' + rx.toFixed(1) + '" y="' + ry.toFixed(1) + '" width="' + rw.toFixed(1) + '" height="' + rh.toFixed(1) + '" rx="3" fill="' + barColor + '"/>' +
2893
+ labelSvg +
2894
+ '</g>'
2895
+ )
2896
+ }).join('')
2897
+
2898
+ return (
2899
+ '<div class="sankey-board">' +
2900
+ '<svg class="sankey-svg" viewBox="0 0 1200 450" role="img" aria-label="' + escapeHtml(slide.title || 'Sankey Flow') + '">' +
2901
+ ribbonsSvg +
2902
+ nodesSvg +
2903
+ '</svg></div>'
2904
+ )
2905
+ }
2906
+
2907
+ const SUPPORT_ACTIVITY_RE = /辅助|支撑|基础|治理|平台|人才|人力|采购|财务|法务|support|infra|hr|talent|procure|governance|admin/i
2908
+
2909
+ export function partitionValueChainItems(slide, langOrAttr = 'zh') {
2910
+ const isEn = langOrAttr === 'en' || langOrAttr === 'en-US'
2911
+ const all = resolveEffectiveItems(slide)
2912
+
2913
+ const taggedSupport = all.filter((it) => SUPPORT_ACTIVITY_RE.test(String(it.tag || '')) || SUPPORT_ACTIVITY_RE.test(String(it.role || '')))
2914
+ const taggedPrimary = all.filter((it) => !taggedSupport.includes(it))
2915
+
2916
+ let supportItems = []
2917
+ let primaryItems = []
2918
+
2919
+ if (taggedSupport.length >= 1 && taggedPrimary.length >= 2) {
2920
+ supportItems = taggedSupport.slice(0, 4)
2921
+ primaryItems = taggedPrimary.slice(0, 5)
2922
+ } else if (all.length >= 6) {
2923
+ const k = Math.min(4, Math.max(2, all.length - 5))
2924
+ supportItems = all.slice(0, k)
2925
+ primaryItems = all.slice(k, k + 5)
2926
+ } else if (Array.isArray(slide.columns) && slide.columns.length >= 1 && all.length >= 2) {
2927
+ supportItems = slide.columns.slice(0, 3).map((col, idx) => ({
2928
+ tag: isEn ? 'SUPPORT ' + (idx + 1) : '辅助 ' + (idx + 1),
2929
+ title: col,
2930
+ }))
2931
+ primaryItems = all.slice(0, 5)
2932
+ } else if (all.length >= 4) {
2933
+ // 若用户仅传 4–5 条核心活动,自动保留为底部基本活动并补齐顶部 2 条标准波特辅助支撑横梁
2934
+ primaryItems = all.slice(0, 5)
2935
+ supportItems = isEn
2936
+ ? [
2937
+ { tag: 'SUPPORT', title: 'Firm Infrastructure & Governance', text: 'Unified strategy, compliance & financial control' },
2938
+ { tag: 'SUPPORT', title: 'Technology R&D & Talent Enablement', text: 'Core platform engineering & organization capability' },
2939
+ ]
2940
+ : [
2941
+ { tag: '辅助活动', title: '企业基础设施与数字化治理', text: '统一战略管控、合规风控与业财一体底座' },
2942
+ { tag: '辅助活动', title: '核心技术研发与组织人才支撑', text: '共性平台研发复用与复合型人才梯队赋能' },
2943
+ ]
2944
+ } else {
2945
+ supportItems = all.length >= 3 ? all.slice(0, 1) : [
2946
+ { tag: isEn ? 'SUPPORT' : '辅助活动', title: isEn ? 'Platform & Governance' : '平台与治理支撑' },
2947
+ ]
2948
+ primaryItems = (all.length >= 3 ? all.slice(1) : all).length > 0
2949
+ ? (all.length >= 3 ? all.slice(1) : all)
2950
+ : [
2951
+ { tag: '01', title: isEn ? 'Inbound' : '供给接入' },
2952
+ { tag: '02', title: isEn ? 'Operations' : '核心交付' },
2953
+ { tag: '03', title: isEn ? 'Distribution' : '渠道触达' },
2954
+ { tag: '04', title: isEn ? 'Service' : '持续增值' },
2955
+ ]
2956
+ }
2957
+
2958
+ const rawMargin = (slide.text && slide.text.trim().length <= 22 ? slide.text.trim() : '')
2959
+ || (slide.subtitle && slide.subtitle.trim().length <= 22 ? slide.subtitle.trim() : '')
2960
+ const marginLabel = rawMargin || (isEn ? 'MARGIN' : '利润池\nMARGIN')
2961
+
2962
+ return { supportItems, primaryItems, marginLabel }
2963
+ }
2964
+
2965
+ function renderPorterValueChainPptx(slide, area, nextIdFn, chromeCfg, theme, langAttr) {
2966
+ const tk = theme.tokens
2967
+ const isEn = langAttr === 'en-US'
2968
+ const { supportItems, primaryItems, marginLabel } = partitionValueChainItems(slide, langAttr)
2969
+ const shapes = []
2970
+ const cardPreset = chromeCfg.cardRadiusPx > 0 ? 'roundRect' : 'rect'
2971
+
2972
+ const marginW = 1.66
2973
+ const marginGap = 0.14
2974
+ const mainW = area.w - marginW - marginGap
2975
+ const mainX = area.x
2976
+
2977
+ // 顶部辅助活动横梁区
2978
+ const nSup = Math.max(1, supportItems.length)
2979
+ const supGap = 0.08
2980
+ const supZoneH = Math.min(1.88, Math.max(1.10, area.h * (nSup >= 3 ? 0.42 : 0.34)))
2981
+ const beamH = (supZoneH - supGap * (nSup - 1)) / nSup
2982
+
2983
+ // 左侧“辅助活动”竖向标签轨(分行独立居中段落,杜绝单段落换行缩进错位)
2984
+ const railW = 0.92
2985
+ const railLines = isEn ? ['SUPPORT'] : ['辅助', '活动']
2986
+ shapes.push(ooxmlShape(nextIdFn(), 'Porter Support Rail', { x: mainX, y: area.y, w: railW, h: supZoneH }, {
2987
+ preset: cardPreset,
2988
+ adj: roundRectAdj(railW, supZoneH, Math.min(6, chromeCfg.cardRadiusPx)),
2989
+ fill: tk.accentSoft,
2990
+ stroke: tk.accentPrimary,
2991
+ strokePt: 0.75,
2992
+ anchor: 'ctr',
2993
+ marginsIn: { l: 0.06, r: 0.06, t: 0.06, b: 0.06 },
2994
+ paragraphs: railLines.map((ln) =>
2995
+ ooxmlRichParagraph(ln, {
2996
+ sizePt: 11.5,
2997
+ color: tk.accentText,
2998
+ bold: true,
2999
+ lang: langAttr,
3000
+ align: 'ctr',
3001
+ font: theme.fonts.heading,
3002
+ lineHeight: 1.16,
3003
+ }),
3004
+ ),
3005
+ }))
3006
+
3007
+ const beamX = mainX + railW + 0.10
3008
+ const beamW = mainW - railW - 0.10
3009
+ supportItems.forEach((sup, sIdx) => {
3010
+ const by = area.y + sIdx * (beamH + supGap)
3011
+ const detail = [sup.text, ...(sup.bullets ?? [])].filter(Boolean).join(' · ')
3012
+ const beamCopy = '**' + (sup.title || '') + '**' + (detail ? ' — ' + detail : '')
3013
+ shapes.push(ooxmlShape(nextIdFn(), 'Porter Support Beam ' + (sIdx + 1), { x: beamX, y: by, w: beamW, h: beamH }, {
3014
+ preset: cardPreset,
3015
+ adj: roundRectAdj(beamW, beamH, Math.min(6, chromeCfg.cardRadiusPx)),
3016
+ fill: sIdx % 2 === 0 ? tk.surface2 : tk.surface1,
3017
+ stroke: chromeCfg.cardBorderless ? '' : tk.hairline,
3018
+ strokePt: 0.75,
3019
+ anchor: 'ctr',
3020
+ marginsIn: { l: 0.18, r: 0.16, t: 0.03, b: 0.03 },
3021
+ paragraphs: [
3022
+ ooxmlRichParagraph(beamCopy, {
3023
+ sizePt: nSup >= 3 ? 11.5 : 12.5,
3024
+ color: tk.inkPrimary,
3025
+ secondaryColor: tk.inkSecondary,
3026
+ lang: langAttr,
3027
+ font: theme.fonts.body,
3028
+ lineHeight: 1.18,
3029
+ }),
3030
+ ],
3031
+ }))
3032
+ shapes.push(ooxmlShape(nextIdFn(), 'Porter Support Stripe ' + (sIdx + 1), { x: beamX, y: by, w: 0.06, h: beamH }, {
3033
+ preset: 'rect',
3034
+ fill: tk.accentSecondary,
3035
+ }))
3036
+ })
3037
+
3038
+ // 底部基本活动互锁 Chevron + 支撑明细卡片
3039
+ const primTopY = area.y + supZoneH + 0.16
3040
+ const primZoneH = Math.max(1.85, area.y + area.h - primTopY)
3041
+ const nPrim = Math.max(1, primaryItems.length)
3042
+ const overlap = nPrim > 1 ? 0.07 : 0
3043
+ const chevW = (mainW + (nPrim - 1) * overlap) / nPrim
3044
+ const chevH = Math.min(0.84, primZoneH * 0.36)
3045
+ const detailGap = 0.12
3046
+ const colW = (mainW - detailGap * (nPrim - 1)) / nPrim
3047
+ const detailY = primTopY + chevH + 0.12
3048
+ const detailH = Math.max(0.95, area.y + area.h - detailY)
3049
+
3050
+ primaryItems.forEach((it, idx) => {
3051
+ const isFirst = idx === 0
3052
+ const isLast = idx === nPrim - 1 && nPrim >= 3
3053
+ const cx = mainX + idx * (chevW - overlap)
3054
+ const fillHex = isFirst ? tk.accentPrimary : isLast ? tk.accentSecondary : tk.surface2
3055
+ const inkHex = isFirst
3056
+ ? tk.inkOnAccent
3057
+ : isLast
3058
+ ? (relativeLuminance(tk.accentSecondary) > 0.38 ? '#0F172A' : '#FFFFFF')
3059
+ : tk.inkPrimary
3060
+ const stageTag = (it.tag && !SUPPORT_ACTIVITY_RE.test(it.tag)) ? it.tag : String(idx + 1).padStart(2, '0')
3061
+ const titleStr = it.title || ''
3062
+ const titlePt = titleStr.length >= 7 ? 11 : nPrim >= 5 ? 11.5 : 12.5
3063
+ const chevParas = [
3064
+ ...(stageTag
3065
+ ? [ooxmlRichParagraph(stageTag, {
3066
+ sizePt: 9,
3067
+ color: inkHex,
3068
+ bold: true,
3069
+ lang: langAttr,
3070
+ align: 'ctr',
3071
+ font: theme.fonts.heading,
3072
+ lineHeight: 1.05,
3073
+ spaceAfterPt: 1,
3074
+ })]
3075
+ : []),
3076
+ ooxmlRichParagraph(titleStr, {
3077
+ sizePt: titlePt,
3078
+ color: inkHex,
3079
+ bold: true,
3080
+ lang: langAttr,
3081
+ align: 'ctr',
3082
+ font: theme.fonts.heading,
3083
+ lineHeight: 1.12,
3084
+ }),
3085
+ ]
3086
+
3087
+ shapes.push(ooxmlShape(nextIdFn(), 'Porter Primary Chevron ' + (idx + 1), { x: cx, y: primTopY, w: chevW, h: chevH }, {
3088
+ preset: isFirst ? 'homePlate' : 'chevron',
3089
+ adjs: { adj: 18000 },
3090
+ fill: fillHex,
3091
+ stroke: tk.canvas,
3092
+ strokePt: 1.75,
3093
+ anchor: 'ctr',
3094
+ marginsIn: { l: isFirst ? 0.10 : 0.22, r: 0.18, t: 0.03, b: 0.03 },
3095
+ paragraphs: chevParas,
3096
+ }))
3097
+
3098
+ const dx = mainX + idx * (colW + detailGap)
3099
+ const cardBox = { x: dx, y: detailY, w: colW, h: detailH }
3100
+ shapes.push(renderSurfaceCardPptx('Porter Detail Surface ' + (idx + 1), cardBox, {
3101
+ fill: isFirst ? tk.accentSoft : tk.surface1,
3102
+ focal: isFirst,
3103
+ }, nextIdFn, chromeCfg, theme))
3104
+
3105
+ const metric = it.conversion || it.delta || (it.value ? it.value + (it.unit ? ' ' + it.unit : '') : '')
3106
+ const lines = [
3107
+ ...(metric ? ['**' + metric + '**'] : []),
3108
+ ...(it.text ? [it.text] : []),
3109
+ ...(Array.isArray(it.bullets) ? it.bullets : []),
3110
+ ]
3111
+ if (lines.length > 0) {
3112
+ const innerBox = { x: cardBox.x + 0.12, y: cardBox.y + 0.12, w: cardBox.w - 0.24, h: cardBox.h - 0.22 }
3113
+ const fit = computeTextFit(lines, innerBox, 'cardBody', { maxPt: 12.5, minPt: 11 })
3114
+ shapes.push(ooxmlShape(nextIdFn(), 'Porter Detail ' + (idx + 1), innerBox, {
3115
+ txBox: true,
3116
+ anchor: 't',
3117
+ marginsIn: { l: 0, r: 0, t: 0, b: 0 },
3118
+ fontScale: fit.fontScale,
3119
+ paragraphs: lines.map((line, lIdx) =>
3120
+ ooxmlRichParagraph(line, {
3121
+ sizePt: fit.fontPt,
3122
+ color: lIdx === 0 && metric ? tk.accentText : tk.inkSecondary,
3123
+ lang: langAttr,
3124
+ font: theme.fonts.body,
3125
+ lineHeight: 1.3,
3126
+ spaceAfterPt: 3,
3127
+ }),
3128
+ ),
3129
+ }))
3130
+ }
3131
+ })
3132
+
3133
+ // 右侧贯通全高的“利润池 / MARGIN”箭头尖楔
3134
+ const wedgeBox = { x: mainX + mainW + marginGap, y: area.y, w: marginW, h: area.h }
3135
+ shapes.push(ooxmlShape(nextIdFn(), 'Porter Margin Wedge', wedgeBox, {
3136
+ preset: 'homePlate',
3137
+ adjs: { adj: 28000 },
3138
+ fill: tk.accentPrimary,
3139
+ stroke: tk.canvas,
3140
+ strokePt: 2.0,
3141
+ anchor: 'ctr',
3142
+ marginsIn: { l: 0.12, r: 0.26, t: 0.16, b: 0.16 },
3143
+ paragraphs: String(marginLabel).split('\n').map((ln, lIdx) =>
3144
+ ooxmlRichParagraph(ln, {
3145
+ sizePt: lIdx === 0 ? 15.5 : 11.5,
3146
+ color: tk.inkOnAccent,
3147
+ bold: true,
3148
+ lang: langAttr,
3149
+ align: 'ctr',
3150
+ font: theme.fonts.heading,
3151
+ lineHeight: 1.2,
3152
+ spaceAfterPt: 2,
3153
+ }),
3154
+ ),
3155
+ }))
3156
+
3157
+ return shapes.join('')
3158
+ }
3159
+
3160
+ function renderPorterValueChainHtml(slide, langId) {
3161
+ const isEn = langId === 'en'
3162
+ const { supportItems, primaryItems, marginLabel } = partitionValueChainItems(slide, langId)
3163
+
3164
+ return (
3165
+ '<div class="porter-board">' +
3166
+ '<div class="porter-main">' +
3167
+ '<div class="porter-support-zone">' +
3168
+ '<div class="porter-support-rail">' + (isEn ? 'SUPPORT' : '辅助活动') + '</div>' +
3169
+ '<div class="porter-support-beams">' +
3170
+ supportItems.map((sup) => {
3171
+ const detail = [sup.text, ...(sup.bullets ?? [])].filter(Boolean).join(' · ')
3172
+ return (
3173
+ '<div class="surface-card porter-beam">' +
3174
+ '<strong>' + renderInlineHtml(sup.title || '') + '</strong>' +
3175
+ (detail ? '<span>' + renderInlineHtml(detail) + '</span>' : '') +
3176
+ '</div>'
3177
+ )
3178
+ }).join('') +
3179
+ '</div></div>' +
3180
+ '<ol class="layout-grid chevron-board porter-primary-zone cols-' + Math.max(1, primaryItems.length) + '">' +
3181
+ primaryItems.map((it, idx) => {
3182
+ const isFirst = idx === 0
3183
+ const isLast = idx === primaryItems.length - 1 && primaryItems.length >= 3
3184
+ const stageTag = (it.tag && !SUPPORT_ACTIVITY_RE.test(it.tag)) ? it.tag : String(idx + 1).padStart(2, '0')
3185
+ const metric = it.conversion || it.delta || (it.value ? it.value + (it.unit ? ' ' + it.unit : '') : '')
3186
+ const lines = [...(it.text ? [it.text] : []), ...(Array.isArray(it.bullets) ? it.bullets : [])]
3187
+ return (
3188
+ '<li class="chevron-col" data-item-index="' + idx + '">' +
3189
+ '<div class="chevron-arrow' + (isFirst ? ' is-first' : isLast ? ' is-last' : '') + '">' +
3190
+ '<span class="chevron-tag">' + escapeHtml(stageTag) + '</span>' +
3191
+ '<span class="chevron-title">' + renderInlineHtml(it.title || '') + '</span>' +
3192
+ '</div>' +
3193
+ '<div class="surface-card chevron-detail' + (isFirst ? ' is-focal' : '') + '">' +
3194
+ (metric ? '<span class="funnel-conversion-badge chevron-metric">' + escapeHtml(metric) + '</span>' : '') +
3195
+ (lines.length ? '<div class="card-body">' + lines.map((l) => renderInlineHtml(l)).join('<br>') + '</div>' : '') +
3196
+ '</div></li>'
3197
+ )
3198
+ }).join('') +
3199
+ '</ol>' +
3200
+ '</div>' +
3201
+ '<aside class="porter-margin-wedge"><span>' + escapeHtml(marginLabel).replace(/\n/g, '<br>') + '</span></aside>' +
3202
+ '</div>'
3203
+ )
3204
+ }
3205
+
3206
+ function formatSwotAnchorText(raw, isEn) {
3207
+ const cleaned = stripInlineMarkdown(String(raw ?? '')).trim()
3208
+ if (!cleaned) return isEn ? 'Strategic\nCore' : '破局核心'
3209
+ const rawLines = String(raw ?? '')
3210
+ .split(/\n+/)
3211
+ .map((ln) => stripInlineMarkdown(ln).trim())
3212
+ .filter(Boolean)
3213
+ if (rawLines.length >= 2) return rawLines.slice(0, 2).join('\n')
3214
+
3215
+ const sepParts = cleaned.split(/\s*[·||//—\-]\s*/).filter(Boolean)
3216
+ if (sepParts.length >= 2) return [sepParts[0], sepParts.slice(1).join('·')].join('\n')
3217
+
3218
+ const hasCjk = /[\u4E00-\u9FFF]/.test(cleaned)
3219
+ if (hasCjk) {
3220
+ const wsParts = cleaned.split(/\s+/).filter(Boolean)
3221
+ if (wsParts.length >= 2) {
3222
+ return [wsParts[0], wsParts.slice(1).join('')].join('\n')
3223
+ }
3224
+ if (cleaned.length > 5) {
3225
+ const mid = Math.ceil(cleaned.length / 2)
3226
+ return cleaned.slice(0, mid) + '\n' + cleaned.slice(mid)
3227
+ }
3228
+ return cleaned
3229
+ }
3230
+
3231
+ const words = cleaned.split(/\s+/).filter(Boolean)
3232
+ if (cleaned.length > 10 && words.length >= 2) {
3233
+ let bestIdx = 1
3234
+ let bestDiff = Infinity
3235
+ for (let i = 1; i < words.length; i += 1) {
3236
+ const l1 = words.slice(0, i).join(' ').length
3237
+ const l2 = words.slice(i).join(' ').length
3238
+ const diff = Math.abs(l1 - l2)
3239
+ if (diff < bestDiff) { bestDiff = diff; bestIdx = i }
3240
+ }
3241
+ return words.slice(0, bestIdx).join(' ') + '\n' + words.slice(bestIdx).join(' ')
3242
+ }
3243
+ return cleaned
1556
3244
  }
1557
3245
 
1558
- function renderHarveyMatrixPptx(slide, area, nextIdFn, chromeCfg, theme, langAttr) {
1559
- const tk = theme.tokens
3246
+ export function computeSwotModel(slide, langOrAttr = 'zh') {
3247
+ const isEn = langOrAttr === 'en' || langOrAttr === 'en-US'
1560
3248
  const items = resolveEffectiveItems(slide)
1561
- const rawRows = Array.isArray(slide.rows) && slide.rows.length > 0
1562
- ? slide.rows
1563
- : items.length > 0
1564
- ? [['评估维度', '行业基线', '本方案 / Ours'], ...items.map((it) => [it.title || '', it.delta || '50%', it.value || (it.status === 'positive' ? 'full' : 'full')])]
1565
- : [['维度', '本方案 / Ours'], ['能力项', 'full']]
1566
- const safeRows = rawRows.slice(0, 9)
1567
- const cols = Math.max(2, ...safeRows.map((r) => r.length))
1568
- const headerRow = Array.from({ length: cols }, (_, c) => String(safeRows[0]?.[c] ?? ''))
1569
- const oursCol = findHarveyOursCol(headerRow, cols)
1570
3249
 
1571
- // Compute proportional column widths (first col wider for criteria label)
1572
- const firstColW = Math.min(4.6, Math.max(2.8, area.w * (cols <= 3 ? 0.44 : 0.34)))
1573
- const otherW = (area.w - firstColW) / Math.max(1, cols - 1)
1574
- const colXs = []
1575
- const colWs = []
1576
- let cursorX = area.x
1577
- for (let c = 0; c < cols; c += 1) {
1578
- const w = c === 0 ? firstColW : otherW
1579
- colXs.push(cursorX)
1580
- colWs.push(w)
1581
- cursorX += w
3250
+ const quadrantMeta = [
3251
+ { key: 'S', badge: 'S', header: isEn ? 'S · Core Strengths' : 'S · 核心优势', role: 'positive', match: /^(?:s\b|strength|优势|强项|长板)/i },
3252
+ { key: 'W', badge: 'W', header: isEn ? 'W · Key Weaknesses' : 'W · 关键短板', role: 'warning', match: /^(?:w\b|weakness|劣势|短板|不足|痛点)/i },
3253
+ { key: 'O', badge: 'O', header: isEn ? 'O · External Opportunities' : 'O · 外部机遇', role: 'accent', match: /^(?:o\b|opportunit|机遇|机会|红利)/i },
3254
+ { key: 'T', badge: 'T', header: isEn ? 'T · Potential Threats' : 'T · 潜在威胁', role: 'negative', match: /^(?:t\b|threat|威胁|风险|挑战)/i },
3255
+ ]
3256
+
3257
+ const towsMeta = [
3258
+ { key: 'SO', label: isEn ? 'SO · Growth Offense' : 'SO · 乘势增长', match: /^so\b/i },
3259
+ { key: 'WO', label: isEn ? 'WO · Capability Turnaround' : 'WO · 借势补短', match: /^wo\b/i },
3260
+ { key: 'ST', label: isEn ? 'ST · Moat Defense' : 'ST · 壁垒防御', match: /^st\b/i },
3261
+ { key: 'WT', label: isEn ? 'WT · Risk Containment' : 'WT · 风险收敛', match: /^wt\b/i },
3262
+ ]
3263
+
3264
+ // 提取显式 SO/WO/ST/WT 行动策略项与 S/W/O/T 四象限项
3265
+ const towsExplicit = new Map()
3266
+ const quadPool = []
3267
+ for (const it of items) {
3268
+ const probe = ((it.tag || '') + ' ' + (it.title || '')).trim()
3269
+ const hitTows = towsMeta.find((tm) => tm.match.test(probe))
3270
+ if (hitTows && !towsExplicit.has(hitTows.key)) {
3271
+ towsExplicit.set(hitTows.key, it.text || (it.bullets ?? [])[0] || it.title || '')
3272
+ } else {
3273
+ quadPool.push(it)
3274
+ }
1582
3275
  }
1583
3276
 
1584
- const rowCount = safeRows.length
1585
- const rowH = Math.min(0.62, Math.max(0.40, area.h / Math.max(1, rowCount)))
1586
- const startY = area.y + Math.max(0, (area.h - rowH * rowCount) / 2)
3277
+ const used = new Set()
3278
+ const quadrants = quadrantMeta.map((qm, qIdx) => {
3279
+ let hit = quadPool.find((it, idx) => !used.has(idx) && (qm.match.test(it.tag || '') || qm.match.test(it.title || '')))
3280
+ if (hit) {
3281
+ used.add(quadPool.indexOf(hit))
3282
+ } else {
3283
+ const nextIdx = quadPool.findIndex((_, idx) => !used.has(idx))
3284
+ if (nextIdx >= 0) {
3285
+ hit = quadPool[nextIdx]
3286
+ used.add(nextIdx)
3287
+ }
3288
+ }
3289
+ const cleanTitle = hit?.title ? hit.title.replace(/^[SWOT]\s*[·::\-—]\s*/i, '').trim() : ''
3290
+ return {
3291
+ ...qm,
3292
+ title: cleanTitle,
3293
+ text: hit?.text || '',
3294
+ bullets: hit?.bullets ?? [],
3295
+ }
3296
+ })
3297
+
3298
+ const rawAnchor = (slide.text && slide.text.trim().length <= 24 ? slide.text.trim() : '')
3299
+ || (slide.subtitle && slide.subtitle.trim().length <= 24 ? slide.subtitle.trim() : '')
3300
+ const anchorText = formatSwotAnchorText(rawAnchor, isEn)
3301
+
3302
+ // 生成底部 SO / WO / ST / WT 行动策略条(优先采用显式策略或 slide.columns,否则根据四象限标题智能凝练)
3303
+ const shortPhrase = (q, fallbackZh, fallbackEn) => {
3304
+ const cand = q.title || (q.bullets[0] ? stripInlineMarkdown(q.bullets[0]).split(/[::,,;;]/)[0] : '') || stripInlineMarkdown(q.text).split(/[::,,;;]/)[0]
3305
+ if (cand && cand.length <= 14) return cand
3306
+ if (cand) return cand.slice(0, 12) + '…'
3307
+ return isEn ? fallbackEn : fallbackZh
3308
+ }
3309
+ const sShort = shortPhrase(quadrants[0], '核心壁垒', 'core strength')
3310
+ const wShort = shortPhrase(quadrants[1], '关键短板', 'gap')
3311
+ const oShort = shortPhrase(quadrants[2], '市场窗口', 'market window')
3312
+ const tShort = shortPhrase(quadrants[3], '外部冲击', 'headwinds')
3313
+
3314
+ const synthesizedDefaults = isEn
3315
+ ? [
3316
+ 'Leverage ' + sShort + ' to capture ' + oShort,
3317
+ 'Use ' + oShort + ' to close ' + wShort,
3318
+ 'Reinforce ' + sShort + ' against ' + tShort,
3319
+ 'Hedge ' + wShort + ' & ' + tShort,
3320
+ ]
3321
+ : [
3322
+ '以「' + sShort + '」抢占「' + oShort + '」',
3323
+ '借「' + oShort + '」补齐「' + wShort + '」',
3324
+ '凭「' + sShort + '」抵御「' + tShort + '」',
3325
+ '收敛「' + wShort + '」严防「' + tShort + '」',
3326
+ ]
3327
+
3328
+ const strategies = towsMeta.map((tm, idx) => {
3329
+ const fromCol = Array.isArray(slide.columns) && slide.columns[idx] ? slide.columns[idx].replace(/^(?:SO|WO|ST|WT)\s*[·::\-—]\s*/i, '') : ''
3330
+ return {
3331
+ key: tm.key,
3332
+ label: tm.label,
3333
+ action: towsExplicit.get(tm.key) || fromCol || synthesizedDefaults[idx],
3334
+ }
3335
+ })
3336
+
3337
+ return { quadrants, anchorText, strategies }
3338
+ }
3339
+
3340
+ function swotRoleColor(role, tk) {
3341
+ if (role === 'positive') return tk.positive
3342
+ if (role === 'warning') return tk.warning
3343
+ if (role === 'negative') return tk.negative
3344
+ return tk.accentPrimary
3345
+ }
3346
+
3347
+ function renderSwotPptx(slide, area, nextIdFn, chromeCfg, theme, langAttr) {
3348
+ const tk = theme.tokens
3349
+ const model = computeSwotModel(slide, langAttr)
1587
3350
  const shapes = []
1588
- const cellPreset = chromeCfg.cardRadiusPx > 0 ? 'roundRect' : 'rect'
3351
+ const cardPreset = chromeCfg.cardRadiusPx > 0 ? 'roundRect' : 'rect'
1589
3352
 
1590
- safeRows.forEach((row, rIdx) => {
1591
- const isHeader = rIdx === 0
1592
- const y = startY + rIdx * rowH
1593
- for (let c = 0; c < cols; c += 1) {
1594
- const cellText = String(row[c] ?? '')
1595
- const isOurs = c === oursCol
1596
- const x = colXs[c]
1597
- const w = colWs[c]
1598
- const cellFill = isHeader
1599
- ? (isOurs ? tk.accentPrimary : tk.surface2)
1600
- : (isOurs ? tk.accentSoft : (rIdx % 2 === 0 ? tk.surface1 : tk.canvas))
3353
+ const stripH = 0.62
3354
+ const stripGap = 0.14
3355
+ const gridH = Math.max(2.6, area.h - stripH - stripGap)
3356
+ const gapX = 0.24
3357
+ const gapY = 0.20
3358
+ const qW = (area.w - gapX) / 2
3359
+ const qH = (gridH - gapY) / 2
3360
+
3361
+ const anchorW = 2.16
3362
+ const anchorH = 0.92
3363
+ const anchorHalfOverlap = Math.max(0.95, anchorW / 2 - gapX / 2 + 0.10)
3364
+
3365
+ model.quadrants.forEach((q, idx) => {
3366
+ const col = idx % 2
3367
+ const row = Math.floor(idx / 2)
3368
+ const qx = area.x + col * (qW + gapX)
3369
+ const qy = area.y + row * (qH + gapY)
3370
+ const toneColor = swotRoleColor(q.role, tk)
3371
+
3372
+ shapes.push(ooxmlShape(nextIdFn(), 'SWOT Quadrant ' + q.key, { x: qx, y: qy, w: qW, h: qH }, {
3373
+ preset: cardPreset,
3374
+ adj: roundRectAdj(qW, qH, chromeCfg.cardRadiusPx),
3375
+ fill: idx === 2 ? tk.accentSoft : tk.surface1,
3376
+ stroke: chromeCfg.cardBorderless ? '' : (idx === 0 || idx === 2 ? toneColor : tk.hairline),
3377
+ strokePt: idx === 0 || idx === 2 ? 1.0 : 0.75,
3378
+ }))
1601
3379
 
1602
- shapes.push(ooxmlShape(nextIdFn(), 'Harvey Cell ' + rIdx + '-' + c, { x, y, w, h: rowH }, {
1603
- preset: isHeader && c === 0 ? cellPreset : 'rect',
1604
- adj: 0,
1605
- fill: cellFill,
1606
- stroke: isOurs ? tk.accentPrimary : tk.hairline,
1607
- strokePt: isOurs ? 0.75 : 0.5,
1608
- }))
3380
+ // 象限顶部语义色带标题栏(全部左对齐,下排 O/T 自动避让中央战略锚点)
3381
+ const headH = 0.40
3382
+ const headLeftIn = row === 1 && col === 1 ? anchorHalfOverlap : 0.18
3383
+ const headRightIn = row === 1 && col === 0 ? anchorHalfOverlap : 0.18
3384
+ shapes.push(ooxmlShape(nextIdFn(), 'SWOT Header ' + q.key, { x: qx, y: qy, w: qW, h: headH }, {
3385
+ preset: 'rect',
3386
+ fill: toneColor,
3387
+ anchor: 'ctr',
3388
+ marginsIn: { l: headLeftIn, r: headRightIn, t: 0.02, b: 0.02 },
3389
+ paragraphs: [
3390
+ ooxmlRichParagraph(q.header + (q.title && q.title !== q.header ? ' · ' + q.title : ''), {
3391
+ sizePt: 12.5,
3392
+ color: relativeLuminance(toneColor) > 0.42 ? '#0F172A' : '#FFFFFF',
3393
+ bold: true,
3394
+ lang: langAttr,
3395
+ align: 'l',
3396
+ font: theme.fonts.heading,
3397
+ lineHeight: 1.1,
3398
+ }),
3399
+ ],
3400
+ }))
1609
3401
 
1610
- const parsed = !isHeader && c > 0 ? parseHarveyValue(cellText) : null
1611
- if (parsed) {
1612
- const ballSize = Math.min(0.28, rowH * 0.56)
1613
- shapes.push(renderHarveyBallPptx(parsed, x + w / 2, y + rowH / 2, ballSize, isOurs, nextIdFn, theme, langAttr))
1614
- } else {
1615
- shapes.push(ooxmlShape(nextIdFn(), 'Harvey Text ' + rIdx + '-' + c, { x: x + 0.08, y: y + 0.03, w: w - 0.16, h: rowH - 0.06 }, {
1616
- txBox: true,
1617
- anchor: 'ctr',
1618
- marginsIn: { l: 0.04, r: 0.04, t: 0.01, b: 0.01 },
1619
- paragraphs: [
1620
- ooxmlRichParagraph(cellText, {
1621
- sizePt: isHeader ? 13.5 : (cols >= 6 ? 12 : 13.5),
1622
- color: isHeader && isOurs ? tk.inkOnAccent : (isOurs ? tk.accentText : tk.inkPrimary),
1623
- bold: isHeader || isOurs,
1624
- lang: langAttr,
1625
- align: c === 0 ? 'l' : 'ctr',
1626
- font: isHeader ? theme.fonts.heading : theme.fonts.body,
1627
- lineHeight: 1.18,
1628
- }),
1629
- ],
3402
+ // 象限内容框(上排顶对齐且左边缘与标题严格对齐;密集多条要点时内侧避让中央锚点)
3403
+ const lines = [
3404
+ ...(q.text ? [q.text] : []),
3405
+ ...(q.bullets ?? []),
3406
+ ]
3407
+ const needInnerClearance = row === 0 && lines.length >= 4
3408
+ const leftPad = needInnerClearance && col === 1 ? anchorHalfOverlap : 0.18
3409
+ const rightPad = needInnerClearance && col === 0 ? anchorHalfOverlap : 0.22
3410
+ const contentBox = {
3411
+ x: qx + leftPad,
3412
+ y: qy + headH + 0.08,
3413
+ w: Math.max(1.8, qW - leftPad - rightPad),
3414
+ h: Math.max(0.6, qH - headH - 0.14),
3415
+ }
3416
+ if (lines.length > 0) {
3417
+ const fit = computeTextFit(lines, contentBox, 'cardBody', { maxPt: 13.5, minPt: 11.5 })
3418
+ const paras = []
3419
+ if (q.text) {
3420
+ paras.push(ooxmlRichParagraph(q.text, {
3421
+ sizePt: fit.fontPt,
3422
+ color: tk.inkPrimary,
3423
+ secondaryColor: tk.inkSecondary,
3424
+ lang: langAttr,
3425
+ font: theme.fonts.body,
3426
+ lineHeight: 1.32,
3427
+ spaceAfterPt: q.bullets?.length ? 4 : 0,
3428
+ autoLeadBold: true,
1630
3429
  }))
1631
3430
  }
3431
+ for (const b of q.bullets ?? []) {
3432
+ paras.push(ooxmlRichParagraph(b, {
3433
+ sizePt: fit.fontPt,
3434
+ color: tk.inkPrimary,
3435
+ secondaryColor: tk.inkSecondary,
3436
+ bullet: true,
3437
+ bulletColor: toneColor,
3438
+ lang: langAttr,
3439
+ font: theme.fonts.body,
3440
+ lineHeight: 1.3,
3441
+ spaceAfterPt: 3,
3442
+ autoLeadBold: true,
3443
+ }))
3444
+ }
3445
+ shapes.push(ooxmlShape(nextIdFn(), 'SWOT Body ' + q.key, contentBox, {
3446
+ txBox: true,
3447
+ anchor: row === 0 ? 't' : 'ctr',
3448
+ marginsIn: { l: 0, r: 0, t: 0, b: 0 },
3449
+ fontScale: fit.fontScale,
3450
+ paragraphs: paras,
3451
+ }))
1632
3452
  }
1633
3453
  })
1634
3454
 
3455
+ // 中央十字交汇“破局核心”八角徽章战略锚点(宽阔内切文本框,4~6 字词组绝不半词折行)
3456
+ const midX = area.x + area.w / 2
3457
+ const midY = area.y + gridH / 2
3458
+ const anchorLines = String(model.anchorText).split('\n').filter(Boolean)
3459
+ const maxAnchorLen = Math.max(1, ...anchorLines.map((ln) => ln.length))
3460
+ shapes.push(ooxmlShape(nextIdFn(), 'SWOT Strategic Anchor', {
3461
+ x: midX - anchorW / 2,
3462
+ y: midY - anchorH / 2,
3463
+ w: anchorW,
3464
+ h: anchorH,
3465
+ }, {
3466
+ preset: 'octagon',
3467
+ adjs: { adj: 22000 },
3468
+ fill: tk.accentPrimary,
3469
+ stroke: tk.canvas,
3470
+ strokePt: 2.5,
3471
+ shadow: true,
3472
+ anchor: 'ctr',
3473
+ marginsIn: { l: 0.14, r: 0.14, t: 0.06, b: 0.06 },
3474
+ paragraphs: anchorLines.map((ln) =>
3475
+ ooxmlRichParagraph(ln, {
3476
+ sizePt: maxAnchorLen >= 7 ? 10.5 : 11.5,
3477
+ color: tk.inkOnAccent,
3478
+ bold: true,
3479
+ lang: langAttr,
3480
+ align: 'ctr',
3481
+ font: theme.fonts.heading,
3482
+ lineHeight: 1.15,
3483
+ }),
3484
+ ),
3485
+ }))
3486
+
3487
+ // 底部 SO / WO / ST / WT 四栏可执行策略合成条
3488
+ const stripY = area.y + gridH + stripGap
3489
+ const stGap = 0.16
3490
+ const stW = (area.w - stGap * 3) / 4
3491
+ model.strategies.forEach((st, idx) => {
3492
+ const sx = area.x + idx * (stW + stGap)
3493
+ shapes.push(ooxmlShape(nextIdFn(), 'SWOT Strategy ' + st.key, { x: sx, y: stripY, w: stW, h: stripH }, {
3494
+ preset: cardPreset,
3495
+ adj: roundRectAdj(stW, stripH, Math.min(8, chromeCfg.cardRadiusPx)),
3496
+ fill: idx === 0 ? tk.accentSoft : tk.surface2,
3497
+ stroke: idx === 0 ? tk.accentPrimary : tk.hairline,
3498
+ strokePt: 0.75,
3499
+ anchor: 'ctr',
3500
+ marginsIn: { l: 0.12, r: 0.12, t: 0.04, b: 0.04 },
3501
+ paragraphs: [
3502
+ ooxmlRichParagraph('**' + st.key + '** · ' + st.action, {
3503
+ sizePt: 11,
3504
+ color: tk.inkPrimary,
3505
+ accentColor: tk.accentText,
3506
+ lang: langAttr,
3507
+ font: theme.fonts.body,
3508
+ lineHeight: 1.2,
3509
+ }),
3510
+ ],
3511
+ }))
3512
+ })
3513
+
1635
3514
  return shapes.join('')
1636
3515
  }
1637
3516
 
1638
- function monogramLetters(name) {
1639
- const clean = stripInlineMarkdown(String(name ?? ''))
1640
- .replace(/\s*(?:博士|教授|先生|女士|院士|院长|主任|总|Ph\.?D\.?|M\.?D\.?|MBA).*$/i, '')
1641
- .trim()
1642
- if (!clean) return 'T'
1643
- if (/[\u4E00-\u9FFF]/.test(clean)) {
1644
- return clean.replace(/\s+/g, '').slice(0, 1)
1645
- }
1646
- const parts = clean.split(/\s+/).filter(Boolean)
1647
- return parts.length >= 2
1648
- ? (parts[0][0] + parts[1][0]).toUpperCase()
1649
- : clean.slice(0, 2).toUpperCase()
3517
+ function renderSwotHtml(slide, langId) {
3518
+ const model = computeSwotModel(slide, langId)
3519
+
3520
+ return (
3521
+ '<div class="swot-board">' +
3522
+ '<div class="swot-cross">' +
3523
+ model.quadrants.map((q, idx) =>
3524
+ '<article class="surface-card swot-quad swot-' + q.key.toLowerCase() + ' tone-' + q.role + '" data-item-index="' + idx + '">' +
3525
+ '<div class="swot-quad-head">' + escapeHtml(q.header + (q.title && q.title !== q.header ? ' · ' + q.title : '')) + '</div>' +
3526
+ '<div class="swot-quad-body">' +
3527
+ (q.text ? '<p class="card-body">' + renderInlineHtml(q.text, { autoLeadBold: true }) + '</p>' : '') +
3528
+ (q.bullets?.length ? '<ul class="card-bullets">' + q.bullets.map((b) => '<li>' + renderInlineHtml(b, { autoLeadBold: true }) + '</li>').join('') + '</ul>' : '') +
3529
+ '</div></article>',
3530
+ ).join('') +
3531
+ '<div class="swot-anchor"><span>' + escapeHtml(model.anchorText).replace(/\n/g, '<br>') + '</span></div>' +
3532
+ '</div>' +
3533
+ '<div class="layout-grid cols-4 swot-tows-strip">' +
3534
+ model.strategies.map((st) =>
3535
+ '<div class="surface-card swot-tows-pill">' +
3536
+ '<span class="item-badge">' + escapeHtml(st.key) + '</span>' +
3537
+ '<span class="swot-tows-text">' + renderInlineHtml(st.action) + '</span>' +
3538
+ '</div>',
3539
+ ).join('') +
3540
+ '</div></div>'
3541
+ )
1650
3542
  }
1651
3543
 
1652
3544
  export function renderCoreSlidePptx(slide, index, total, theme, langAttr, manifest = {}) {
@@ -3264,6 +5156,30 @@ export function renderCoreSlidePptx(slide, index, total, theme, langAttr, manife
3264
5156
  return shapes.join('')
3265
5157
  }
3266
5158
 
5159
+ if (layout === 'marimekko') {
5160
+ shapes.push(renderMarimekkoPptx(slide, { x: 0.62, y: bodyTopY + 0.04, w: 12.09, h: bodyH - 0.10 }, nextId, chromeCfg, theme, langAttr))
5161
+ shapes.push(renderSlideChromePptx(slide, index, total, theme, langAttr, manifest, nextId))
5162
+ return shapes.join('')
5163
+ }
5164
+
5165
+ if (layout === 'sankey') {
5166
+ shapes.push(renderSankeyPptx(slide, { x: 0.62, y: bodyTopY + 0.04, w: 12.09, h: bodyH - 0.10 }, nextId, chromeCfg, theme, langAttr))
5167
+ shapes.push(renderSlideChromePptx(slide, index, total, theme, langAttr, manifest, nextId))
5168
+ return shapes.join('')
5169
+ }
5170
+
5171
+ if (layout === 'value-chain') {
5172
+ shapes.push(renderPorterValueChainPptx(slide, { x: 0.62, y: bodyTopY + 0.04, w: 12.09, h: bodyH - 0.10 }, nextId, chromeCfg, theme, langAttr))
5173
+ shapes.push(renderSlideChromePptx(slide, index, total, theme, langAttr, manifest, nextId))
5174
+ return shapes.join('')
5175
+ }
5176
+
5177
+ if (layout === 'swot' || (layout === 'matrix' && variant === 'swot')) {
5178
+ shapes.push(renderSwotPptx(slide, { x: 0.62, y: bodyTopY + 0.04, w: 12.09, h: bodyH - 0.10 }, nextId, chromeCfg, theme, langAttr))
5179
+ shapes.push(renderSlideChromePptx(slide, index, total, theme, langAttr, manifest, nextId))
5180
+ return shapes.join('')
5181
+ }
5182
+
3267
5183
  if (layout === 'matrix') {
3268
5184
  const items = resolveEffectiveItems(slide).slice(0, 4)
3269
5185
  const plotX = 1.18
@@ -3702,11 +5618,46 @@ export function renderCoreSlidePptx(slide, index, total, theme, langAttr, manife
3702
5618
 
3703
5619
  if (layout === 'callout') {
3704
5620
  const heroText = slide.text || subtitle || ''
5621
+ const explicitFormula = typeof slide.formula === 'string' ? slide.formula.trim() : ''
3705
5622
  const items = resolveEffectiveItems(slide)
3706
- const hasHero = heroText !== ''
3707
- if (hasHero) {
5623
+ const heroSegs = splitMathSegments(heroText)
5624
+ const isSingleMathHero = heroSegs.length === 1 && heroSegs[0].type === 'math'
5625
+ const formulaSource = explicitFormula
5626
+ || (isSingleMathHero ? heroSegs[0].latex : '')
5627
+ || (variant === 'formula' && looksLikeRawLatex(heroText) ? unwrapOuterMathDelimiters(heroText) : '')
5628
+
5629
+ let cursorY = bodyTopY + 0.06
5630
+ if (formulaSource !== '') {
5631
+ const hasDistinctCaption = explicitFormula !== '' && heroText !== '' && unwrapOuterMathDelimiters(heroText) !== unwrapOuterMathDelimiters(explicitFormula)
5632
+ const calloutH = items.length > 0
5633
+ ? (hasDistinctCaption ? 1.54 : 1.76)
5634
+ : Math.min(3.10, bodyH - (hasDistinctCaption ? 0.68 : 0.16))
5635
+ const box = { x: 0.62, y: cursorY, w: 12.09, h: calloutH }
5636
+ shapes.push(renderMathCardPptx('Callout Formula', box, formulaSource, nextId, chromeCfg, theme, {
5637
+ emIn: items.length > 0 ? 0.28 : 0.34,
5638
+ sizePt: 20,
5639
+ }))
5640
+ cursorY += calloutH + 0.14
5641
+ if (hasDistinctCaption) {
5642
+ shapes.push(ooxmlShape(nextId(), 'Callout Formula Caption', { x: 0.62, y: cursorY, w: 12.09, h: 0.42 }, {
5643
+ txBox: true,
5644
+ anchor: 'ctr',
5645
+ marginsIn: { l: 0.12, r: 0.12, t: 0.02, b: 0.02 },
5646
+ paragraphs: [
5647
+ ooxmlRichParagraph(heroText, {
5648
+ sizePt: 14.5,
5649
+ color: tk.inkSecondary,
5650
+ lang: langAttr,
5651
+ align: 'ctr',
5652
+ font: theme.fonts.body,
5653
+ }),
5654
+ ],
5655
+ }))
5656
+ cursorY += 0.50
5657
+ }
5658
+ } else if (heroText !== '') {
3708
5659
  const calloutH = items.length > 0 ? 1.55 : 2.85
3709
- const box = { x: 0.62, y: bodyTopY + 0.06, w: 12.09, h: calloutH }
5660
+ const box = { x: 0.62, y: cursorY, w: 12.09, h: calloutH }
3710
5661
  shapes.push(ooxmlShape(nextId(), 'Callout surface', box, {
3711
5662
  preset: cardPreset,
3712
5663
  adj: roundRectAdj(box.w, box.h, chromeCfg.cardRadiusPx),
@@ -3728,10 +5679,18 @@ export function renderCoreSlidePptx(slide, index, total, theme, langAttr, manife
3728
5679
  }),
3729
5680
  ],
3730
5681
  }))
5682
+ cursorY += calloutH + 0.20
3731
5683
  }
5684
+
3732
5685
  if (items.length > 0) {
3733
- const listTop = hasHero ? bodyTopY + 1.82 : bodyTopY + 0.08
3734
- const listBox = { x: 0.62, y: listTop, w: 12.09, h: Math.max(1.2, bodyBottomY - listTop) }
5686
+ const listTop = Math.max(cursorY, bodyTopY + 0.08)
5687
+ const listBox = { x: 0.62, y: listTop, w: 12.09, h: Math.max(1.0, bodyBottomY - listTop) }
5688
+ const normalizeLegendPart = (val) => {
5689
+ const s = String(val ?? '').trim()
5690
+ if (!s) return ''
5691
+ if (variant === 'formula' && looksLikeRawLatex(s) && !containsLatexMath(s)) return '$' + s + '$'
5692
+ return s
5693
+ }
3735
5694
  const lines = items.map((it, idx) => (it.tag || (idx + 1) + '.') + ' ' + [it.title, it.text].filter(Boolean).join(':'))
3736
5695
  const fit = computeTextFit(lines, listBox, 'body', { maxPt: 16.5, minPt: 13.5 })
3737
5696
  shapes.push(ooxmlShape(nextId(), 'Callout 1', listBox, {
@@ -3739,9 +5698,11 @@ export function renderCoreSlidePptx(slide, index, total, theme, langAttr, manife
3739
5698
  anchor: 't',
3740
5699
  marginsIn: { l: 0.08, r: 0.08, t: 0.04, b: 0.04 },
3741
5700
  fontScale: fit.fontScale,
3742
- paragraphs: items.map((it, idx) =>
3743
- ooxmlRichParagraph(
3744
- '**' + (it.tag || String(idx + 1).padStart(2, '0')) + (it.title ? ' ' + it.title : '') + '**' + (it.text ? ':' + it.text : ''),
5701
+ paragraphs: items.map((it, idx) => {
5702
+ const tagPart = normalizeLegendPart(it.tag || String(idx + 1).padStart(2, '0'))
5703
+ const titlePart = normalizeLegendPart(it.title || '')
5704
+ return ooxmlRichParagraph(
5705
+ '**' + tagPart + (titlePart ? ' ' + titlePart : '') + '**' + (it.text ? ':' + it.text : ''),
3745
5706
  {
3746
5707
  sizePt: fit.fontPt,
3747
5708
  color: tk.inkPrimary,
@@ -3751,16 +5712,26 @@ export function renderCoreSlidePptx(slide, index, total, theme, langAttr, manife
3751
5712
  lineHeight: 1.44,
3752
5713
  spaceAfterPt: 8,
3753
5714
  },
3754
- ),
3755
- ),
5715
+ )
5716
+ }),
3756
5717
  }))
3757
5718
  }
3758
5719
  shapes.push(renderSlideChromePptx(slide, index, total, theme, langAttr, manifest, nextId))
3759
5720
  return shapes.join('')
3760
5721
  }
3761
5722
 
3762
- // 默认版式:bullets(保留 idBase + 3 Body 以严格兼容逐条点击动画 spid)
3763
- const surfaceBox = { x: 0.62, y: bodyTopY + 0.06, w: 12.09, h: bodyH - 0.12 }
5723
+ // 默认版式:bullets(若带 slide.formula 先渲染顶部原生公式条;保留 idBase + 3 Body 兼容逐条点击动画 spid)
5724
+ let bulletsAreaTopY = bodyTopY + 0.06
5725
+ if (typeof slide.formula === 'string' && slide.formula.trim() !== '') {
5726
+ const fBox = { x: 0.62, y: bulletsAreaTopY, w: 12.09, h: 1.42 }
5727
+ shapes.push(renderMathCardPptx('Bullets Formula', fBox, slide.formula.trim(), nextId, chromeCfg, theme, {
5728
+ emIn: 0.27,
5729
+ sizePt: 19,
5730
+ }))
5731
+ bulletsAreaTopY += 1.56
5732
+ }
5733
+
5734
+ const surfaceBox = { x: 0.62, y: bulletsAreaTopY, w: 12.09, h: Math.max(1.4, bodyBottomY - bulletsAreaTopY - 0.06) }
3764
5735
  shapes.push(ooxmlShape(nextId(), 'Bullets container', surfaceBox, {
3765
5736
  preset: cardPreset,
3766
5737
  adj: roundRectAdj(surfaceBox.w, surfaceBox.h, chromeCfg.cardRadiusPx),
@@ -3769,13 +5740,116 @@ export function renderCoreSlidePptx(slide, index, total, theme, langAttr, manife
3769
5740
  strokePt: 0.75,
3770
5741
  }))
3771
5742
  if (chromeCfg.cardLeftBar || chromeCfg.chrome === 'saas-bento' || chromeCfg.chrome === 'gov-ceremonial') {
3772
- shapes.push(ooxmlShape(nextId(), 'Bullets accent rail', { x: 0.62, y: bodyTopY + 0.06, w: 0.07, h: surfaceBox.h }, {
5743
+ shapes.push(ooxmlShape(nextId(), 'Bullets accent rail', { x: 0.62, y: bulletsAreaTopY, w: 0.07, h: surfaceBox.h }, {
3773
5744
  preset: 'rect',
3774
5745
  fill: tk.accentPrimary,
3775
5746
  }))
3776
5747
  }
3777
5748
 
3778
- const bodyBox = { x: 0.98, y: bodyTopY + 0.24, w: 11.42, h: surfaceBox.h - 0.36 }
5749
+ const has2dMathBullets = bullets.length > 0 && bullets.some((b) => {
5750
+ const segs = splitMathSegments(b)
5751
+ return segs.some((s) => s.type === 'math' && (s.display || has2dMathConstruct(parseLatexMath(s.latex))))
5752
+ })
5753
+
5754
+ if (has2dMathBullets) {
5755
+ const innerTop = bulletsAreaTopY + 0.16
5756
+ const innerH = surfaceBox.h - 0.32
5757
+ const rowGap = 0.10
5758
+ const nRows = Math.min(6, bullets.length)
5759
+ const rowH = Math.max(0.52, (innerH - rowGap * (nRows - 1)) / nRows)
5760
+ bullets.slice(0, nRows).forEach((b, bIdx) => {
5761
+ const ry = innerTop + bIdx * (rowH + rowGap)
5762
+ const segs = splitMathSegments(b)
5763
+ const firstMathIdx = segs.findIndex((s) => s.type === 'math' && (s.display || has2dMathConstruct(parseLatexMath(s.latex))))
5764
+ if (firstMathIdx >= 0) {
5765
+ const prefixText = segs.slice(0, firstMathIdx).map((s) => s.type === 'text' ? s.value : ('$' + s.latex + '$')).join('').trim()
5766
+ const suffixText = segs.slice(firstMathIdx + 1).map((s) => s.type === 'text' ? s.value : ('$' + s.latex + '$')).join('').trim()
5767
+ const mathSeg = segs[firstMathIdx]
5768
+ if (!prefixText && !suffixText) {
5769
+ const eqBox = { x: 0.98, y: ry, w: 11.42, h: rowH }
5770
+ if (theme.dark) {
5771
+ shapes.push(ooxmlShape(nextId(), 'Bullet Math Plate ' + (bIdx + 1), eqBox, {
5772
+ preset: cardPreset,
5773
+ adj: roundRectAdj(eqBox.w, eqBox.h, Math.min(6, chromeCfg.cardRadiusPx)),
5774
+ fill: '#F8FAFC',
5775
+ }))
5776
+ }
5777
+ shapes.push(ooxmlMathShape(nextId(), 'Bullet Equation ' + (bIdx + 1), eqBox, mathSeg.latex, {
5778
+ emIn: Math.min(0.28, rowH * 0.34),
5779
+ sizePt: 18,
5780
+ align: 'ctr',
5781
+ }))
5782
+ } else {
5783
+ const labelStr = [prefixText, suffixText].filter(Boolean).join(' ')
5784
+ const labelW = Math.min(4.6, Math.max(2.4, measureEmWidth(labelStr, true) * 0.24 + 0.45))
5785
+ shapes.push(ooxmlShape(nextId(), 'Bullet Math Label ' + (bIdx + 1), { x: 0.94, y: ry, w: labelW, h: rowH }, {
5786
+ txBox: true,
5787
+ anchor: 'ctr',
5788
+ marginsIn: { l: 0.04, r: 0.06, t: 0.02, b: 0.02 },
5789
+ paragraphs: [
5790
+ ooxmlRichParagraph(prefixText || labelStr, {
5791
+ sizePt: 14.5,
5792
+ color: tk.inkPrimary,
5793
+ secondaryColor: tk.inkSecondary,
5794
+ bullet: true,
5795
+ bulletChar: '▪',
5796
+ bulletColor: tk.accentPrimary,
5797
+ lang: langAttr,
5798
+ font: theme.fonts.body,
5799
+ autoLeadBold: true,
5800
+ }),
5801
+ ],
5802
+ }))
5803
+ const eqBox = { x: 0.94 + labelW + 0.12, y: ry, w: Math.max(2.4, 12.42 - (0.94 + labelW + 0.12)), h: rowH }
5804
+ if (theme.dark) {
5805
+ const astPreview = parseLatexMath(mathSeg.latex)
5806
+ const fittedEq = fitFormulaBoxIn(astPreview, eqBox, {
5807
+ padXIn: 0.24,
5808
+ padYIn: 0.10,
5809
+ emIn: Math.min(0.27, rowH * 0.34),
5810
+ align: 'l',
5811
+ })
5812
+ const plateW = Math.min(eqBox.w, Math.max(2.2, fittedEq.w + 0.48))
5813
+ shapes.push(ooxmlShape(nextId(), 'Bullet Math Plate ' + (bIdx + 1), { x: eqBox.x, y: ry + 0.04, w: plateW, h: rowH - 0.08 }, {
5814
+ preset: cardPreset,
5815
+ adj: roundRectAdj(plateW, rowH - 0.08, Math.min(8, chromeCfg.cardRadiusPx)),
5816
+ fill: '#F8FAFC',
5817
+ stroke: tk.accentPrimary,
5818
+ strokePt: 0.75,
5819
+ }))
5820
+ }
5821
+ shapes.push(ooxmlMathShape(nextId(), 'Bullet Equation ' + (bIdx + 1), eqBox, mathSeg.latex, {
5822
+ emIn: Math.min(0.27, rowH * 0.34),
5823
+ sizePt: 18,
5824
+ align: 'l',
5825
+ }))
5826
+ }
5827
+ } else {
5828
+ shapes.push(ooxmlShape(nextId(), 'Bullet Row ' + (bIdx + 1), { x: 0.94, y: ry, w: 11.46, h: rowH }, {
5829
+ txBox: true,
5830
+ anchor: 'ctr',
5831
+ marginsIn: { l: 0.04, r: 0.04, t: 0.02, b: 0.02 },
5832
+ paragraphs: [
5833
+ ooxmlRichParagraph(b, {
5834
+ sizePt: 15.5,
5835
+ color: tk.inkPrimary,
5836
+ secondaryColor: tk.inkSecondary,
5837
+ bullet: true,
5838
+ bulletChar: '▪',
5839
+ bulletColor: tk.accentPrimary,
5840
+ lang: langAttr,
5841
+ font: theme.fonts.body,
5842
+ autoLeadBold: true,
5843
+ }),
5844
+ ],
5845
+ }))
5846
+ }
5847
+ })
5848
+ shapes.push(renderSlideChromePptx(slide, index, total, theme, langAttr, manifest, nextId))
5849
+ return shapes.join('')
5850
+ }
5851
+
5852
+ const bodyBox = { x: 0.98, y: bulletsAreaTopY + 0.18, w: 11.42, h: surfaceBox.h - 0.36 }
3779
5853
  const sourceLines = bullets.length > 0 ? bullets : [subtitle || slide.text || '']
3780
5854
  const bodyFit = computeTextFit(sourceLines, bodyBox, 'body', { maxPt: bullets.length <= 4 ? 19 : 17.5, minPt: 13.5 })
3781
5855
  const bodyParagraphs = bullets.length > 0
@@ -4296,6 +6370,14 @@ export function renderCoreSlideHtml(slide, index, total, ui, langId, manifest =
4296
6370
  }).join('') +
4297
6371
  '</div>'
4298
6372
  }
6373
+ } else if (layout === 'marimekko') {
6374
+ inner = renderHeader() + renderMarimekkoHtml(slide, theme, langId)
6375
+ } else if (layout === 'sankey') {
6376
+ inner = renderHeader() + renderSankeyHtml(slide, theme, langId)
6377
+ } else if (layout === 'value-chain') {
6378
+ inner = renderHeader() + renderPorterValueChainHtml(slide, langId)
6379
+ } else if (layout === 'swot' || (layout === 'matrix' && variant === 'swot')) {
6380
+ inner = renderHeader() + renderSwotHtml(slide, langId)
4299
6381
  } else if (layout === 'matrix') {
4300
6382
  const items = resolveEffectiveItems(slide).slice(0, 4)
4301
6383
  inner =
@@ -4387,15 +6469,31 @@ export function renderCoreSlideHtml(slide, index, total, ui, langId, manifest =
4387
6469
  }
4388
6470
  } else if (layout === 'callout') {
4389
6471
  const heroText = slide.text || subtitle || ''
6472
+ const explicitFormula = typeof slide.formula === 'string' ? slide.formula.trim() : ''
6473
+ const heroSegs = splitMathSegments(heroText)
6474
+ const isSingleMathHero = heroSegs.length === 1 && heroSegs[0].type === 'math'
6475
+ const formulaSource = explicitFormula
6476
+ || (isSingleMathHero ? heroSegs[0].latex : '')
6477
+ || (variant === 'formula' && looksLikeRawLatex(heroText) ? unwrapOuterMathDelimiters(heroText) : '')
6478
+ const hasDistinctCaption = explicitFormula !== '' && heroText !== '' && unwrapOuterMathDelimiters(heroText) !== unwrapOuterMathDelimiters(explicitFormula)
4390
6479
  const items = resolveEffectiveItems(slide)
6480
+ const renderLegendBadge = (rawBadge) => {
6481
+ if (variant === 'formula' && looksLikeRawLatex(rawBadge) && !containsLatexMath(rawBadge)) {
6482
+ return latexToMathMl(rawBadge, { display: false, className: 'deck-math is-inline' })
6483
+ }
6484
+ return containsLatexMath(rawBadge) ? renderInlineHtml(rawBadge) : escapeHtml(rawBadge)
6485
+ }
4391
6486
  inner =
4392
6487
  renderHeader() +
4393
- (heroText ? '<div class="callout-hero' + (variant === 'formula' ? ' is-formula' : '') + '">' + renderInlineHtml(heroText) + '</div>' : '') +
6488
+ (formulaSource !== ''
6489
+ ? '<div class="callout-hero is-formula is-omath callout-formula formula-plate">' + latexToMathMl(formulaSource, { display: true, className: 'deck-math is-block' }) + '</div>' +
6490
+ (hasDistinctCaption ? '<div class="formula-caption">' + renderInlineHtml(heroText) + '</div>' : '')
6491
+ : (heroText ? '<div class="callout-hero' + (variant === 'formula' ? ' is-formula callout-formula' : '') + '">' + renderInlineHtml(heroText) + '</div>' : '')) +
4394
6492
  (items.length
4395
6493
  ? '<ul class="layout-grid callout-list">' +
4396
6494
  items.map((it, idx) =>
4397
6495
  '<li class="surface-card callout-row" data-item-index="' + idx + '">' +
4398
- '<span class="item-badge">' + escapeHtml(it.tag || String(idx + 1).padStart(2, '0')) + '</span>' +
6496
+ '<span class="item-badge">' + renderLegendBadge(it.tag || String(idx + 1).padStart(2, '0')) + '</span>' +
4399
6497
  '<div class="card-body"><strong data-item-field="title">' + renderInlineHtml(it.title || '') + '</strong>' +
4400
6498
  (it.text ? ' <span data-item-field="text">' + renderInlineHtml(it.text) + '</span>' : '') +
4401
6499
  '</div></li>',
@@ -4404,8 +6502,12 @@ export function renderCoreSlideHtml(slide, index, total, ui, langId, manifest =
4404
6502
  : '')
4405
6503
  } else {
4406
6504
  // bullets 默认版式(严格保持 <li style="--i:0">纯文本</li> 无多余包裹,兼容 test/features.test.mjs:202)
6505
+ const topFormulaBanner = typeof slide.formula === 'string' && slide.formula.trim() !== ''
6506
+ ? '<div class="callout-hero is-formula is-omath callout-formula formula-plate">' + latexToMathMl(slide.formula.trim(), { display: true, className: 'deck-math is-block' }) + '</div>'
6507
+ : ''
4407
6508
  inner =
4408
6509
  renderHeader() +
6510
+ topFormulaBanner +
4409
6511
  (subtitle !== '' && bullets.length === 0 ? '<div class="subtitle">' + renderInlineHtml(subtitle) + '</div>' : '') +
4410
6512
  (bullets.length > 0
4411
6513
  ? '<ul class="bullets-list' + (variant === 'two-column' ? ' cols-2' : '') + '">' +
@@ -4664,10 +6766,62 @@ export const LAYOUT_CSS = `
4664
6766
  .slide[data-chrome="academic-minimal"] .slide-takeaway{background:transparent;border:0;border-top:1px solid var(--accent);border-bottom:1px solid var(--hairline);border-radius:0;padding:8px 0}
4665
6767
  .slide[data-chrome="gov-ceremonial"] .gov-header{border-bottom:2px solid var(--accent);box-shadow:0 4px 0 0 var(--bg),0 5.5px 0 0 var(--accent2);padding-bottom:12px;margin-bottom:4px}
4666
6768
  .slide[data-chrome="gov-ceremonial"] .gov-ribbon{letter-spacing:.08em}
6769
+ /* Phase 4 MathML & 4 Pinnacle Consulting Layouts CSS */
6770
+ math.deck-math{font-family:"Cambria Math","Latin Modern Math",Georgia,serif}
6771
+ math.deck-math.is-block{display:block;font-size:clamp(20px,2.2vw,32px);margin:4px auto;overflow-x:auto}
6772
+ math.deck-math.is-inline{font-size:1.06em;vertical-align:middle}
6773
+ .callout-hero.is-omath{padding:22px 30px;display:flex;align-items:center;justify-content:center}
6774
+ .formula-caption{text-align:center;color:var(--ink-secondary);font-size:clamp(14px,1.35vw,18px);margin-top:-6px}
6775
+ .mekko-board{display:grid;grid-template-columns:1fr minmax(190px,21%);gap:20px;width:100%;min-height:360px;align-items:stretch}
6776
+ .mekko-main{display:flex;flex-direction:column;gap:6px;min-width:0}
6777
+ .mekko-headers{display:flex;width:100%;align-items:flex-end}
6778
+ .mekko-col-head{display:flex;flex-direction:column;align-items:center;text-align:center;padding:0 4px;min-width:0;overflow:hidden}
6779
+ .mekko-col-title{font-family:var(--font-heading);font-size:clamp(11px,1.05vw,14px);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%}
6780
+ .mekko-col-size{font-size:11px;font-weight:700;color:var(--accent-text);font-variant-numeric:tabular-nums}
6781
+ .mekko-columns{display:flex;width:100%;flex:1;min-height:290px;border:1px solid var(--hairline)}
6782
+ .mekko-col{display:flex;flex-direction:column;min-width:0}
6783
+ .mekko-cell{display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;border:1.5px solid var(--bg);padding:2px 4px;overflow:hidden;font-variant-numeric:tabular-nums}
6784
+ .mekko-seg-name{font-size:12px;font-weight:600;line-height:1.15;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
6785
+ .mekko-seg-pct{font-family:var(--font-heading);font-size:13px;font-weight:800}
6786
+ .mekko-axis{display:flex;justify-content:space-between;border-top:1.5px solid var(--muted);padding-top:4px;font-size:11px;color:var(--muted);font-variant-numeric:tabular-nums}
6787
+ .mekko-legend{justify-content:flex-start;gap:14px}
6788
+ .mekko-total{display:flex;flex-direction:column;gap:4px;padding-bottom:12px;border-bottom:1px solid var(--hairline)}
6789
+ .mekko-total strong{font-family:var(--font-heading);font-size:clamp(22px,2.3vw,32px);color:var(--accent-text);font-variant-numeric:tabular-nums}
6790
+ .mekko-legend-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:10px}
6791
+ .mekko-legend-list li{display:flex;align-items:center;gap:8px;font-size:13px}
6792
+ .mekko-legend-list li.is-ours{color:var(--accent-text);font-weight:700}
6793
+ .mekko-swatch{width:14px;height:14px;border-radius:3px;flex-shrink:0;border:1px solid var(--hairline)}
6794
+ .mekko-leg-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
6795
+ .mekko-leg-pct{font-variant-numeric:tabular-nums}
6796
+ .sankey-board{width:100%;display:flex;align-items:center;justify-content:center}
6797
+ .sankey-svg{width:100%;height:auto;max-height:430px;overflow:visible;font-family:var(--font-body)}
6798
+ .porter-board{display:grid;grid-template-columns:1fr minmax(120px,13.5%);gap:12px;width:100%;align-items:stretch}
6799
+ .porter-main{display:flex;flex-direction:column;gap:14px;min-width:0}
6800
+ .porter-support-zone{display:grid;grid-template-columns:84px 1fr;gap:10px;align-items:stretch}
6801
+ .porter-support-rail{background:var(--accent-soft);border:1px solid var(--accent);border-radius:calc(var(--radius) * .7);color:var(--accent-text);font-family:var(--font-heading);font-weight:800;font-size:13px;display:flex;align-items:center;justify-content:center;text-align:center;padding:8px}
6802
+ .porter-support-beams{display:flex;flex-direction:column;gap:8px}
6803
+ .porter-beam{flex-direction:row;align-items:center;gap:12px;padding:10px 16px;border-left:4px solid var(--accent2)}
6804
+ .porter-beam strong{font-family:var(--font-heading);font-size:14px;white-space:nowrap}
6805
+ .porter-beam span{font-size:13px;color:var(--ink-secondary);overflow:hidden;text-overflow:ellipsis}
6806
+ .porter-margin-wedge{background:var(--accent);color:var(--ink-on-accent);font-family:var(--font-heading);font-weight:800;font-size:clamp(15px,1.5vw,21px);display:flex;align-items:center;justify-content:center;text-align:center;padding:16px 24px 16px 12px;clip-path:polygon(0 0,74% 0,100% 50%,74% 100%,0 100%,14% 50%)}
6807
+ .swot-board{display:flex;flex-direction:column;gap:14px;width:100%}
6808
+ .swot-cross{position:relative;display:grid;grid-template-columns:1fr 1fr;gap:16px;width:100%}
6809
+ .swot-quad{padding:0;overflow:hidden;gap:0}
6810
+ .swot-quad-head{padding:9px 18px;font-family:var(--font-heading);font-weight:800;font-size:14px;color:#FFF;background:var(--accent)}
6811
+ .swot-quad.tone-positive .swot-quad-head{background:var(--positive)}
6812
+ .swot-quad.tone-warning .swot-quad-head{background:var(--warning);color:#0F172A}
6813
+ .swot-quad.tone-negative .swot-quad-head{background:var(--negative)}
6814
+ .swot-quad.swot-o .swot-quad-head{padding-right:108px}
6815
+ .swot-quad.swot-t .swot-quad-head{padding-left:108px}
6816
+ .swot-quad-body{padding:14px 18px;display:flex;flex-direction:column;gap:6px}
6817
+ .swot-anchor{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);z-index:3;background:var(--accent);color:var(--ink-on-accent);border:4px solid var(--bg);border-radius:999px;padding:10px 24px;min-width:168px;font-family:var(--font-heading);font-weight:800;font-size:14px;line-height:1.25;text-align:center;box-shadow:0 10px 26px rgba(0,0,0,.16)}
6818
+ .swot-tows-strip{gap:12px}
6819
+ .swot-tows-pill{flex-direction:row;align-items:center;gap:10px;padding:10px 14px}
6820
+ .swot-tows-text{font-size:13px;color:var(--fg);font-weight:600}
4667
6821
  @media (max-width:900px){
4668
- .cols-3,.cols-4,.cols-5,.cols-6,.bento-grid.bento-3,.bento-grid.bento-4,.bento-grid.bento-5,.bento-grid.bento-6,.tam-board,.arch-board.has-sidecar,.org-children,.flywheel-stage{grid-template-columns:1fr}
6822
+ .cols-3,.cols-4,.cols-5,.cols-6,.bento-grid.bento-3,.bento-grid.bento-4,.bento-grid.bento-5,.bento-grid.bento-6,.tam-board,.arch-board.has-sidecar,.org-children,.flywheel-stage,.mekko-board,.porter-board,.swot-cross{grid-template-columns:1fr}
4669
6823
  .bento-grid.bento-3 > :first-child,.bento-grid.bento-4 > *{grid-row:auto;grid-column:auto}
4670
- .issue-action-row,.gantt-head,.gantt-row,.arch-tier{grid-template-columns:1fr}
4671
- .flywheel-hub{position:static;transform:none;margin:0 auto}
6824
+ .issue-action-row,.gantt-head,.gantt-row,.arch-tier,.porter-support-zone{grid-template-columns:1fr}
6825
+ .flywheel-hub,.swot-anchor{position:static;transform:none;margin:0 auto}
4672
6826
  }
4673
6827
  `