dsh-ppt 0.21.1 → 0.22.1

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.en.md +18 -18
  3. package/README.md +16 -16
  4. package/docs/COACHING.md +14 -13
  5. package/docs/DATA.md +8 -8
  6. package/docs/REFERENCE.en.md +17 -19
  7. package/docs/REFERENCE.zh.md +16 -18
  8. package/docs/USAGE.en.md +107 -60
  9. package/docs/USAGE.md +115 -84
  10. package/docs/VALIDATION.md +2 -0
  11. package/docs/VISUAL.md +27 -20
  12. package/docs/WORKBENCH.md +17 -6
  13. package/docs/assets/intro/screen-en.webp +0 -0
  14. package/docs/assets/intro/screen-zh.webp +0 -0
  15. package/lib/client.js +905 -46
  16. package/lib/coaching.d.ts +1 -1
  17. package/lib/coaching.js +25 -12
  18. package/lib/config.d.ts +2 -0
  19. package/lib/config.js +30 -2
  20. package/lib/execution.d.ts +2 -1
  21. package/lib/execution.js +21 -1
  22. package/lib/tools.d.ts +1 -1
  23. package/lib/tools.js +151 -24
  24. package/lib/types.d.ts +108 -8
  25. package/lib/visual.d.ts +3 -1
  26. package/lib/visual.js +40 -13
  27. package/lib/workbench-language.js +45 -9
  28. package/lib/workbench.d.ts +5 -0
  29. package/lib/workbench.js +485 -9
  30. package/package.json +8 -3
  31. package/skills/dsh-ppt/SKILL.md +56 -54
  32. package/skills/dsh-ppt/package.json +1 -1
  33. package/skills/dsh-ppt/references/advanced.md +122 -41
  34. package/skills/dsh-ppt/references/copywriting.md +63 -41
  35. package/skills/dsh-ppt/references/data.md +83 -36
  36. package/skills/dsh-ppt/references/syntax.md +157 -28
  37. package/skills/dsh-ppt/references/themes.md +90 -41
  38. package/skills/dsh-ppt/references/troubleshooting.md +21 -16
  39. package/skills/dsh-ppt/scripts/build-deck.mjs +67 -28
  40. package/skills/dsh-ppt/scripts/deck-absorb.mjs +1029 -0
  41. package/skills/dsh-ppt/scripts/deck-advanced.mjs +406 -99
  42. package/skills/dsh-ppt/scripts/deck-core.mjs +568 -717
  43. package/skills/dsh-ppt/scripts/deck-data-view.mjs +30 -11
  44. package/skills/dsh-ppt/scripts/deck-data.mjs +35 -5
  45. package/skills/dsh-ppt/scripts/deck-director.mjs +1717 -0
  46. package/skills/dsh-ppt/scripts/deck-layouts.mjs +4557 -0
  47. package/skills/dsh-ppt/scripts/deck-media.mjs +1408 -86
  48. package/skills/dsh-ppt/scripts/deck-themes.mjs +1503 -0
  49. package/skills/dsh-ppt/scripts/deck-visual.mjs +133 -31
@@ -2,40 +2,37 @@ import { mkdirSync, readFileSync, statSync, openSync, closeSync, rmSync } from '
2
2
  import { resolve, dirname, extname, basename } from 'node:path'
3
3
  import { createHash, randomUUID } from 'node:crypto'
4
4
  import { inflateSync } from 'node:zlib'
5
- import { buildPptx, renderHtml, normalizeBuildOptions, normalizeSlides, resolveTheme, resolveLanguage, resolveDeckFileName, commitDeckArtifacts, DECK_VERSION, pptxEastAsianFont } from './deck-core.mjs'
6
- import { MEDIA_LAYOUTS, mediaBoxes, LOGO_BOX, FOOTER_BOX, chartColors, normalizeChart } from './deck-media.mjs'
5
+ import { buildPptx, renderHtml, normalizeBuildOptions, normalizeSlides, resolveLanguage, resolveDeckFileName, commitDeckArtifacts, DECK_VERSION, buildDeck } from './deck-core.mjs'
6
+ import { listThemes, resolveTheme, buildThemePreview as buildThemePreviewFromThemes, deriveBrandedTheme, pptxEastAsianFont } from './deck-themes.mjs'
7
+ import { CORE_LAYOUTS, LAYOUT_ALIASES, stripInlineMarkdown } from './deck-layouts.mjs'
8
+ import { MEDIA_LAYOUTS, mediaBoxes, LOGO_BOX, FOOTER_BOX, normalizeChart, buildOfficeKitChartSpec, computeWaterfallGeometry } from './deck-media.mjs'
7
9
  import { normalizeDataModel, prepareDataSlides, validateDataSnapshot, previewDataChange, dataNotes, dataReport } from './deck-data.mjs'
8
10
  import { normalizeVisual, applyVisualActions } from './deck-visual.mjs'
11
+ import { absorbPptx, CHROME_STYLE_IDS } from './deck-absorb.mjs'
12
+ import { SCENARIO_TEMPLATES, findScenarioTemplate, buildScenarioSlides, listScenarioTemplates, inferThemeFromContent, promoteMarkdownSlides, auditSlideAesthetics } from './deck-director.mjs'
9
13
  export { readRenderReceipt } from './deck-render.mjs'
10
14
  export { dataNotes, dataReport } from './deck-data.mjs'
11
- export { buildDeck, buildThemePreview, listThemes, resolveTheme, resolveLanguage } from './deck-core.mjs'
15
+ export { buildDeck, resolveLanguage } from './deck-core.mjs'
16
+ export { listThemes, resolveTheme } from './deck-themes.mjs'
17
+ export { absorbPptx } from './deck-absorb.mjs'
18
+ export { inferThemeFromContent } from './deck-director.mjs'
19
+
20
+ export function buildThemePreview(options = {}) {
21
+ return buildThemePreviewFromThemes(options, resolveLanguage, DECK_VERSION)
22
+ }
12
23
 
13
24
  const MAX_IMAGE = 5 * 1024 * 1024, MAX_ASSETS = 32 * 1024 * 1024, MAX_DOCUMENT = 64 * 1024 * 1024
14
25
  const MAX_HISTORY = 20
15
- const layouts = new Set(['cover', 'section', 'bullets', 'statement', 'closing', 'quote', 'table', ...MEDIA_LAYOUTS])
26
+ const canonicalLayouts = new Set([...CORE_LAYOUTS, ...MEDIA_LAYOUTS])
27
+ const layouts = new Set([...canonicalLayouts, ...Object.keys(LAYOUT_ALIASES)])
16
28
  const hash = data => createHash('sha256').update(data).digest('hex')
17
29
  const clone = value => structuredClone(value)
18
30
  function abort(signal) { signal?.throwIfAborted() }
19
31
  function fail(message) { throw new Error('dsh-ppt:' + message) }
20
32
 
21
- const scenarios = [
22
- { id: 'weekly', name: { zh: '工作周报', en: 'Weekly report' }, theme: 'data', sections: [['本周工作', 'This week'], ['完成情况', 'Progress'], ['问题与风险', 'Risks'], ['下周计划', 'Next week']] },
23
- { id: 'defense', name: { zh: '论文答辩', en: 'Thesis defense' }, theme: 'soft', sections: [['研究问题', 'Research question'], ['相关研究', 'Related work'], ['研究方法', 'Method'], ['研究结果', 'Results'], ['结论与局限', 'Conclusions and limitations']] },
24
- { id: 'project', name: { zh: '项目汇报', en: 'Project update' }, theme: 'swiss', sections: [['目标与范围', 'Goals and scope'], ['进度与交付', 'Progress and delivery'], ['数据与证据', 'Evidence'], ['风险与决策', 'Risks and decisions'], ['下一步', 'Next steps']] },
25
- { id: 'pitch', name: { zh: '项目路演', en: 'Pitch deck' }, theme: 'velvet', sections: [['用户问题', 'Customer problem'], ['解决方案', 'Solution'], ['产品与证据', 'Product and evidence'], ['商业模式', 'Business model'], ['计划与需求', 'Plan and ask']] },
26
- ]
27
-
28
33
  export function listTemplates(lang = 'zh') {
29
34
  const language = resolveLanguage(lang).id === 'en' ? 'en' : 'zh'
30
- return scenarios.map(s => ({ id: s.id, name: s.name[language], theme: s.theme,
31
- outline: s.sections.map(p => p[language === 'en' ? 1 : 0]),
32
- slides: templateSlides(s, s.name[language], language) }))
33
- }
34
- function templateSlides(scenario, title, lang) {
35
- const en = lang === 'en'
36
- return [{ layout: 'cover', title, subtitle: en ? 'To fill: presenter and date' : '待填写:汇报人和日期' },
37
- ...scenario.sections.map(section => ({ layout: 'bullets', title: section[en ? 1 : 0], bullets: [en ? 'To fill: specific facts, evidence and next action' : '待填写:具体事实、依据与下一步行动'] })),
38
- { layout: 'closing', title: en ? 'Next action' : '下一步行动', subtitle: en ? 'To fill: owner and deadline' : '待填写:负责人和时间' }]
35
+ return listScenarioTemplates(language)
39
36
  }
40
37
 
41
38
  function imageInfo(bytes, page) {
@@ -98,6 +95,8 @@ function addAsset(image, assets, cwd, page) {
98
95
  return id
99
96
  }
100
97
 
98
+ const CHROME_STYLE_SET = new Set(CHROME_STYLE_IDS)
99
+
101
100
  function normalizeBrand(input, assets, cwd) {
102
101
  if (input === undefined || input === null) return undefined
103
102
  if (typeof input !== 'object' || Array.isArray(input)) fail('brand 必须是对象')
@@ -118,6 +117,11 @@ function normalizeBrand(input, assets, cwd) {
118
117
  if (String(input.footer).length > 100) fail('brand.footer 最多 100 字符')
119
118
  brand.footer = String(input.footer)
120
119
  }
120
+ if (input.chromeStyle !== undefined && input.chromeStyle !== null && input.chromeStyle !== '') {
121
+ const cs = String(input.chromeStyle).trim().toLowerCase()
122
+ if (!CHROME_STYLE_SET.has(cs)) fail('brand.chromeStyle 需为 ' + CHROME_STYLE_IDS.join(' / '))
123
+ brand.chromeStyle = cs
124
+ }
121
125
  if (input.logo) brand.logoAssetId = addAsset({ src: input.logo }, assets, cwd, '品牌 Logo')
122
126
  else if (input.logoAssetId) {
123
127
  if (!assets[input.logoAssetId]) fail('品牌 Logo 嵌入资产不存在')
@@ -125,42 +129,70 @@ function normalizeBrand(input, assets, cwd) {
125
129
  }
126
130
  return brand
127
131
  }
132
+
128
133
  function brandedTheme(manifest) {
129
- const theme = clone(resolveTheme(manifest.theme)), brand = manifest.brand
130
- if (brand?.primaryColor) theme.palette.accent = brand.primaryColor
131
- if (brand?.backgroundColor) theme.palette.bg = brand.backgroundColor
132
- if (brand?.textColor) theme.palette.fg = brand.textColor
133
- if (brand?.fontFamily) theme.fonts = { heading: brand.fontFamily, body: brand.fontFamily }
134
- return theme
134
+ return deriveBrandedTheme(manifest.theme, manifest.brand)
135
135
  }
136
+
136
137
  function embedSlides(slides, assets, cwd) {
137
138
  return slides.map((slide, index) => {
138
- if (!slide.image) return slide
139
- const assetId = addAsset(slide.image, assets, cwd, `第 ${index + 1} 页`)
140
- const { src, ...image } = slide.image
141
- return { ...slide, image: { ...image, assetId } }
139
+ const pageLabel = `第 ${index + 1} 页`
140
+ let nextSlide = slide
141
+ if (slide.image) {
142
+ const assetId = addAsset(slide.image, assets, cwd, pageLabel)
143
+ const { src, ...image } = slide.image
144
+ nextSlide = { ...nextSlide, image: { ...image, assetId } }
145
+ }
146
+ if (Array.isArray(slide.images) && slide.images.length > 0) {
147
+ const embeddedImages = slide.images.map((img, gIdx) => {
148
+ const assetId = addAsset(img, assets, cwd, `${pageLabel}图 ${gIdx + 1}`)
149
+ const { src, ...rest } = img
150
+ return { ...rest, assetId }
151
+ })
152
+ nextSlide = { ...nextSlide, images: embeddedImages }
153
+ }
154
+ return nextSlide
142
155
  })
143
156
  }
157
+
158
+ function effectiveLayout(rawLayout) {
159
+ if (!rawLayout) return undefined
160
+ return LAYOUT_ALIASES[rawLayout]?.layout || rawLayout
161
+ }
162
+
144
163
  function validateRawSlides(slides) {
145
164
  if (slides === undefined || slides === null) return
146
165
  if (!Array.isArray(slides)) fail('slides 必须是数组')
147
166
  slides.forEach((s, i) => {
148
167
  if (!s || typeof s !== 'object' || Array.isArray(s)) fail(`第 ${i + 1} 页必须是对象`)
149
168
  if (s.layout && !layouts.has(s.layout)) fail(`第 ${i + 1} 页未知布局 ${s.layout}`)
169
+ if (s.chrome !== undefined && s.chrome !== null && s.chrome !== '') {
170
+ const ch = String(s.chrome).trim().toLowerCase()
171
+ if (!CHROME_STYLE_SET.has(ch)) fail(`第 ${i + 1} 页未知母版骨架 chrome: ${s.chrome}`)
172
+ }
150
173
  normalizeVisual(s.visual)
151
- if (s.chart && s.image) fail(`第 ${i + 1} 页不能同时放入 image 和 chart`)
152
- if (s.image && s.layout && !['image', 'image-left', 'image-right'].includes(s.layout)) fail(`第 ${i + 1} 页图片需使用 image / image-left / image-right 布局`)
153
- if (s.chart && s.layout && s.layout !== 'chart') fail(`第 ${i + 1} 页图表需使用 chart 布局`)
174
+ const eff = effectiveLayout(s.layout)
175
+ const hasImg = Boolean(s.image || (Array.isArray(s.images) && s.images.length > 0))
176
+ if (s.chart && hasImg) fail(`第 ${i + 1} 页不能同时放入 image 和 chart`)
177
+ if (hasImg && eff && !['image', 'image-left', 'image-right'].includes(eff)) fail(`第 ${i + 1} 页图片需使用 image / image-left / image-right / gallery 布局`)
178
+ if (s.chart && eff && !['chart', 'chart-split'].includes(eff)) fail(`第 ${i + 1} 页图表需使用 chart / chart-split / waterfall 布局`)
154
179
  })
155
180
  }
181
+
156
182
  function snapshot(manifest) {
157
183
  return clone(Object.fromEntries(['title', 'theme', 'language', 'motion', 'slides', 'brand', 'template', 'dataModel'].filter(k => manifest[k] !== undefined).map(k => [k, manifest[k]])))
158
184
  }
185
+
159
186
  function collectAssets(manifest) {
160
187
  const ids = new Set()
161
188
  for (const state of [manifest, ...(manifest.history ?? [])]) {
162
189
  if (state.brand?.logoAssetId) ids.add(state.brand.logoAssetId)
163
- for (const slide of state.slides) if (slide.image?.assetId) ids.add(slide.image.assetId)
190
+ for (const slide of state.slides) {
191
+ if (slide.image?.assetId) ids.add(slide.image.assetId)
192
+ if (Array.isArray(slide.images)) {
193
+ for (const img of slide.images) if (img?.assetId) ids.add(img.assetId)
194
+ }
195
+ }
164
196
  }
165
197
  manifest.assets = Object.fromEntries([...ids].map(id => [id, manifest.assets[id]]))
166
198
  const size = Object.values(manifest.assets).reduce((sum, asset) => sum + (asset?.data?.length ?? 0), 0)
@@ -181,7 +213,7 @@ function embeddedAssetError(asset, id) {
181
213
  }
182
214
 
183
215
  // This is a conservative fit estimate. Fonts and PowerPoint/WPS rendering still need visual inspection.
184
- function textWidth(text) { return [...String(text ?? '')].reduce((n, c) => n + (/[^\x00-\xff]/.test(c) ? 1 : 0.55), 0) }
216
+ function textWidth(text) { return [...stripInlineMarkdown(String(text ?? ''))].reduce((n, c) => n + (/[^\x00-\xff]/.test(c) ? 1 : 0.55), 0) }
185
217
  function contrast(a, b) {
186
218
  const lum = color => {
187
219
  const rgb = color.slice(1).match(/../g).map(v => parseInt(v, 16) / 255).map(v => v <= .04045 ? v / 12.92 : ((v + .055) / 1.055) ** 2.4)
@@ -189,6 +221,7 @@ function contrast(a, b) {
189
221
  }
190
222
  const x = lum(a), y = lum(b); return (Math.max(x, y) + .05) / (Math.min(x, y) + .05)
191
223
  }
224
+
192
225
  export function checkManifest(manifest) {
193
226
  const issues = [], theme = brandedTheme(manifest)
194
227
  const invalidAssets = new Map()
@@ -199,21 +232,39 @@ export function checkManifest(manifest) {
199
232
  const issue = (index, code, message, suggestion, severity = 'warning') => issues.push({ slide: index + 1, slideId: manifest.slides[index]?.id, severity, code, message, suggestion })
200
233
  manifest.slides.forEach((slide, i) => {
201
234
  if (!slide.title?.trim()) issue(i, 'missing-title', '页面没有标题', '补充能说明本页内容的标题')
202
- const titleLimit = ['cover', 'closing', 'statement', 'quote', 'section'].includes(slide.layout) ? 40 : 24
235
+ const titleLimit = ['cover', 'closing', 'statement', 'quote', 'section'].includes(slide.layout) ? 40 : 34
203
236
  if (textWidth(slide.title) > titleLimit) issue(i, 'title-overflow', '标题可能换行过多或超过标题区域', '缩短标题,把解释移入正文')
204
- const mixed = ['image-left', 'image-right'].includes(slide.layout), bullets = slide.bullets ?? []
237
+ const mixed = ['image-left', 'image-right', 'chart-split'].includes(slide.layout), bullets = slide.bullets ?? []
205
238
  if (bullets.length > (mixed ? 5 : 8)) issue(i, 'dense-bullets', `本页有 ${bullets.length} 条要点,放映时过密`, '减少要点或拆成多页')
206
- const width = mixed ? 19 : 37
239
+ const width = mixed ? 24 : 37
207
240
  const lines = bullets.reduce((sum, b) => sum + Math.max(1, Math.ceil(textWidth(b) / width)), 0)
208
241
  + (slide.subtitle ? Math.ceil(textWidth(slide.subtitle) / width) : 0)
209
- if (lines > (mixed ? 9 : 11)) issue(i, 'body-overflow', '正文估计超过可用高度', '先精简文字,再分拆页面,避免继续缩小字体')
210
- if ([slide.title, slide.subtitle, ...bullets].some(s => /待填写|To fill:/i.test(String(s)))) issue(i, 'template-unfilled', '模板中还有待填写内容', '提供实际事实、依据和行动,填完后重新检查')
242
+ if (slide.layout === 'bullets' || mixed) {
243
+ if (lines > (mixed ? 9 : 11)) issue(i, 'body-overflow', '正文估计超过可用高度', '先精简文字,再分拆页面,避免继续缩小字体')
244
+ }
245
+ const itemStrings = Array.isArray(slide.items)
246
+ ? slide.items.flatMap(it => [it?.title, it?.text, it?.value, ...(it?.bullets ?? [])]).filter(Boolean)
247
+ : []
248
+ if ([slide.title, slide.subtitle, slide.takeaway, ...bullets, ...itemStrings].some(s => /待填写|To fill:/i.test(String(s)))) {
249
+ issue(i, 'template-unfilled', '模板中还有待填写内容', '提供实际事实、依据和行动,填完后重新检查')
250
+ }
211
251
  if (slide.layout === 'table') {
212
- if ((slide.rows?.[0]?.length ?? 0) > 6) issue(i, 'small-font', '表格超过 6 列,使用 14pt,小屏放映可能难以阅读', '减少列数或把重点数据改成图表,导出后检查可读性')
252
+ if ((slide.rows?.[0]?.length ?? 0) > 6) issue(i, 'small-font', '表格超过 6 列,使用较小字号,小屏放映可能难以阅读', '减少列数或把重点数据改成图表,导出后检查可读性')
213
253
  if (slide.rows?.some(row => row.some(c => textWidth(c) > 18))) issue(i, 'table-density', '表格单元格文字较长,可能换行拥挤', '精简单元格或减少列数')
214
254
  }
215
- if (slide.image) {
216
- const asset = manifest.assets?.[slide.image.assetId], box = mediaBoxes(slide.layout).image
255
+ const boxes = MEDIA_LAYOUTS.has(slide.layout) ? mediaBoxes(slide.layout, slide.variant, slide) : null
256
+ if (Array.isArray(boxes?.gallery) && Array.isArray(slide.images) && slide.images.length > 1) {
257
+ slide.images.forEach((img, gIdx) => {
258
+ const asset = manifest.assets?.[img?.assetId], gBox = boxes.gallery[gIdx] || boxes.image
259
+ if (!asset) issue(i, 'missing-image', `找不到本页第 ${gIdx + 1} 张嵌入图片`, '重新指定图片路径后编辑本页', 'error')
260
+ else {
261
+ if (assetError(img.assetId)) issue(i, 'invalid-image', assetError(img.assetId), '重新提供本地图片后编辑该页', 'error')
262
+ if (asset.width < gBox.w * 100 || asset.height < gBox.h * 100) issue(i, 'low-resolution', `图片为 ${asset.width}×${asset.height},放大后可能模糊`, '换成更高分辨率图片;Logo 等小图可忽略此提示')
263
+ }
264
+ if (!img?.alt?.trim()) issue(i, 'missing-alt', '图片没有说明文字', '填写 images[].alt,方便读屏及理解图片')
265
+ })
266
+ } else if (slide.image) {
267
+ const asset = manifest.assets?.[slide.image.assetId], box = boxes?.image || mediaBoxes('image').image
217
268
  if (!asset) issue(i, 'missing-image', '找不到本页的嵌入图片', '重新指定图片路径后编辑本页', 'error')
218
269
  else {
219
270
  if (assetError(slide.image.assetId)) issue(i, 'invalid-image', assetError(slide.image.assetId), '重新提供本地图片后编辑该页', 'error')
@@ -223,21 +274,83 @@ export function checkManifest(manifest) {
223
274
  }
224
275
  if (slide.chart) {
225
276
  try { normalizeChart(slide.chart, i + 1) } catch (error) { issue(i, 'invalid-chart', error.message, '修正图表类别和数值', 'error') }
226
- if (slide.chart.categories?.length > 10 || slide.chart.categories?.some(c => textWidth(c) > 10)) issue(i, 'chart-density', '图表类别较多或标签较长,可能相互遮挡', '减少类别,或使用横向条形图')
277
+ if (slide.chart.categories?.length > 10 || (slide.chart.kind !== 'bar' && slide.chart.kind !== 'stacked-bar' && slide.chart.kind !== 'percent-bar' && slide.chart.categories?.some(c => textWidth(c) > 10))) {
278
+ issue(i, 'chart-density', '图表类别较多或标签较长,可能相互遮挡', '减少类别,或使用横向条形图 bar')
279
+ }
227
280
  if (slide.chart.series?.some(s => textWidth(s.name) > 14)) issue(i, 'chart-legend', '图例名称较长', '精简系列名称并检查渲染')
228
281
  }
229
282
  if (contrast(theme.palette.bg, theme.palette.fg) < 4.5) issue(i, 'low-contrast', '正文与背景对比度低于 4.5:1', '调整品牌背景色或文字色')
230
283
  })
231
284
  if (manifest.brand?.logoAssetId && !manifest.assets?.[manifest.brand.logoAssetId]) issue(0, 'missing-logo', '品牌 Logo 资产不存在', '重新提供 Logo', 'error')
232
285
  else if (manifest.brand?.logoAssetId && assetError(manifest.brand.logoAssetId)) issue(0, 'invalid-logo', assetError(manifest.brand.logoAssetId), '重新提供 Logo', 'error')
286
+
287
+ // 追加 SLOP-01..10 审美反模式静态诊断
288
+ for (const aestheticIssue of auditSlideAesthetics(manifest, theme, textWidth)) {
289
+ issues.push(aestheticIssue)
290
+ }
291
+
233
292
  return { ok: !issues.some(i => i.severity === 'error'), slideCount: manifest.slides.length,
234
293
  errorCount: issues.filter(i => i.severity === 'error').length, warningCount: issues.filter(i => i.severity === 'warning').length,
235
294
  issues, note: '文字尺寸与溢出为静态估算;最终请检查 HTML 放映和 PowerPoint / WPS 实际显示。页脚和页码的小字号不计入正文检查。' }
236
295
  }
237
296
 
297
+ function drawNativeWaterfallWithKit(lib, slide, chart, boxIn, theme) {
298
+ const emuVal = inches => Math.round(inches * 914400)
299
+ const cb = { x: emuVal(boxIn.x), y: emuVal(boxIn.y), w: emuVal(boxIn.w), h: emuVal(boxIn.h) }
300
+ const plotLeft = cb.x + Math.round(cb.w * 0.085)
301
+ const plotRight = cb.x + Math.round(cb.w * 0.975)
302
+ const plotTop = cb.y + Math.round(cb.h * 0.11)
303
+ const plotBottom = cb.y + Math.round(cb.h * 0.83)
304
+ const geom = computeWaterfallGeometry(chart, { left: plotLeft, right: plotRight, top: plotTop, bottom: plotBottom })
305
+
306
+ const tokens = theme.tokens || {}
307
+ const fg = tokens.inkPrimary || theme.palette.fg
308
+ const muted = tokens.inkMuted || theme.palette.muted
309
+ const hairline = tokens.hairline || theme.palette.panel
310
+ const focalColor = tokens.chartFocal || theme.palette.accent
311
+ const posColor = tokens.positive || '#0D7A4E'
312
+ const negColor = tokens.negative || '#C81E1E'
313
+ const font = pptxEastAsianFont(theme.fonts.body)
314
+
315
+ geom.ticks.forEach((tk, idx) => {
316
+ const grid = lib.addSlideLine(slide, { x1: plotLeft, y1: Math.round(tk.y), x2: plotRight, y2: Math.round(tk.y), name: `Waterfall Grid ${idx}` })
317
+ lib.setShapeStroke(grid, { color: hairline, width: 9525 })
318
+ const lbl = lib.addSlideTextBox(slide, { x: cb.x, y: Math.round(tk.y - 95000), w: Math.max(91440, plotLeft - cb.x - 68000), h: 190000, text: tk.label, name: `Waterfall Tick ${idx}` })
319
+ lib.setShapeTextFormat(lbl, { size: 11, font, color: muted })
320
+ lib.setShapeAlignment(lbl, 'right')
321
+ })
322
+
323
+ geom.connectors.forEach((cn, idx) => {
324
+ const bridge = lib.addSlideLine(slide, { x1: Math.round(cn.x1), y1: Math.round(cn.y1), x2: Math.round(cn.x2), y2: Math.round(cn.y2), name: `Waterfall Bridge ${idx + 1}` })
325
+ lib.setShapeStroke(bridge, { color: muted, width: 11430, dash: 'dash' })
326
+ })
327
+
328
+ geom.bars.forEach((b, idx) => {
329
+ const col = b.role === 'total' ? focalColor : b.role === 'positive' ? posColor : negColor
330
+ const bar = lib.addSlideShape(slide, 'roundRect', { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.max(25400, Math.round(b.h)), name: `Waterfall Bar ${idx + 1}` })
331
+ lib.setShapeFill(bar, col)
332
+ lib.setShapeNoStroke(bar)
333
+ const labelY = b.value >= 0 || b.isTotal ? Math.round(b.y - 220000) : Math.round(b.y + b.h + 25000)
334
+ const valBox = lib.addSlideTextBox(slide, { x: Math.round(b.x - 95000), y: labelY, w: Math.round(b.w + 190000), h: 205000, text: b.label, name: `Waterfall Value ${idx + 1}` })
335
+ lib.setShapeTextFormat(valBox, { size: 11.5, font, color: b.role === 'total' ? fg : col, bold: true })
336
+ lib.setShapeAlignment(valBox, 'center')
337
+ const catBox = lib.addSlideTextBox(slide, { x: Math.round(b.x - 110000), y: plotBottom + 42000, w: Math.round(b.w + 220000), h: 240000, text: b.category, name: `Waterfall Category ${idx + 1}` })
338
+ lib.setShapeTextFormat(catBox, { size: 12, font, color: fg })
339
+ lib.setShapeAlignment(catBox, 'center')
340
+ })
341
+
342
+ const axis = lib.addSlideLine(slide, { x1: plotLeft, y1: Math.round(geom.zeroY), x2: plotRight, y2: Math.round(geom.zeroY), name: 'Waterfall Baseline' })
343
+ lib.setShapeStroke(axis, { color: tokens.inkSecondary || muted, width: 15875 })
344
+ }
345
+
238
346
  async function exportPptx(manifest, theme, language, signal) {
239
- const base = buildPptx({ ...manifest, slides: manifest.slides.map(s => ({ ...s, notes: dataNotes(manifest,s) })) }, theme, language)
240
- if (!manifest.brand?.logoAssetId && !manifest.brand?.footer && !manifest.slides.some(s => s.image || s.chart)) return base
347
+ const base = buildPptx({ ...manifest, slides: manifest.slides.map(s => ({ ...s, notes: dataNotes(manifest, s) })) }, theme, language)
348
+ const hasWaterfall = manifest.slides.some(s => s.chart?.kind === 'waterfall')
349
+ const waterfallMissingInBase = hasWaterfall && !base.includes(Buffer.from('Waterfall Bar 1'))
350
+ const hasOfficeKitChart = manifest.slides.some(s => s.chart && s.chart.kind !== 'waterfall')
351
+ const hasImages = manifest.slides.some(s => s.image || (Array.isArray(s.images) && s.images.length > 0))
352
+ if (!manifest.brand?.logoAssetId && !manifest.brand?.footer && !hasImages && !hasOfficeKitChart && !waterfallMissingInBase) return base
353
+
241
354
  abort(signal)
242
355
  let lib
243
356
  try { lib = await import('@office-kit/pptx') } catch (error) { fail('图片、图表和品牌导出需要 @office-kit/pptx@0.21.0。插件请重新安装;独立技能请在技能目录运行 npm install --ignore-scripts。' + error.message) }
@@ -256,26 +369,29 @@ async function exportPptx(manifest, theme, language, signal) {
256
369
  }
257
370
  manifest.slides.forEach((source, index) => {
258
371
  abort(signal)
259
- const slide = slides[index], boxes = mediaBoxes(source.layout)
260
- if (source.image) putImage(slide, source.image.assetId, boxes.image, source.image.fit, 'Slide image', source.image.alt)
372
+ const slide = slides[index]
373
+ const boxes = MEDIA_LAYOUTS.has(source.layout) ? mediaBoxes(source.layout, source.variant, source) : mediaBoxes('image')
374
+ if (Array.isArray(boxes.gallery) && Array.isArray(source.images) && source.images.length > 1) {
375
+ boxes.gallery.forEach((gBox, gIdx) => {
376
+ const img = source.images[gIdx]
377
+ if (img?.assetId) putImage(slide, img.assetId, gBox, img.fit || 'cover', `Gallery image ${gIdx + 1}`, img.alt)
378
+ })
379
+ } else if (source.image) {
380
+ putImage(slide, source.image.assetId, boxes.image, source.image.fit, 'Slide image', source.image.alt)
381
+ }
261
382
  if (source.chart) {
262
- const colors = chartColors(theme), font = pptxEastAsianFont(theme.fonts.body)
263
- const style = { font, sizePt: source.visual?.chartLabelSize ?? 17, color: theme.palette.fg }
264
- lib.addSlideChart(slide, { ...emu(boxes.chart), name: 'Editable data chart', spec: {
265
- kind: source.chart.kind, categories: source.chart.categories,
266
- series: source.chart.series.map((s, i) => ({ ...s, color: colors[i], ...(source.chart.kind === 'pie' ? { pointColors: source.chart.categories.map((_, j) => colors[j % colors.length]) } : {}) })),
267
- chartAreaFill: theme.palette.bg, chartAreaStrokeColor: theme.palette.bg, plotAreaFill: theme.palette.bg,
268
- categoryAxisLabelStyle: style, valueAxisLabelStyle: style,
269
- valueAxisMinorTickMark: 'none', categoryAxisMinorTickMark: 'none', valueAxisMajorTickMark: 'none', categoryAxisMajorTickMark: 'none',
270
- valueAxisMajorGridlines: true, valueAxisMajorGridlineColor: theme.palette.panel,
271
- ...(source.chart.kind === 'bar' ? { categoryAxisOrientation: 'maxMin', valueAxisCrosses: 'max' } : {}),
272
- ...(source.chart.kind === 'pie' ? { dataLabels: { showPercent: true, showValue: false, showCategory: false, showSeriesName: false, numberFormat: '0.0%', position: 'bestFit', textStyle: style } } : {}),
273
- ...(source.chart.unit ? { valueAxisTitle: source.chart.unit, valueAxisTitleStyle: style } : {}),
274
- legend: { position: 'b', textStyle: style },
275
- } })
383
+ if (source.chart.kind === 'waterfall') {
384
+ if (!lib.findShapeByName(slide, 'Waterfall Bar 1')) {
385
+ drawNativeWaterfallWithKit(lib, slide, source.chart, boxes.chart, theme)
386
+ }
387
+ } else {
388
+ const font = pptxEastAsianFont(theme.fonts.body)
389
+ const spec = buildOfficeKitChartSpec(source.chart, theme, source.visual, font)
390
+ lib.addSlideChart(slide, { ...emu(boxes.chart), name: 'Editable data chart', spec })
391
+ }
276
392
  }
277
393
  if (manifest.brand?.logoAssetId) putImage(slide, manifest.brand.logoAssetId, LOGO_BOX, 'contain', 'Brand logo', manifest.brand.name)
278
- if (manifest.brand?.footer) {
394
+ if (manifest.brand?.footer && !lib.findShapeByName(slide, 'Footer source')) {
279
395
  const footer = lib.addSlideTextBox(slide, { ...emu(FOOTER_BOX), text: manifest.brand.footer, name: 'Brand footer' })
280
396
  lib.setShapeTextFormat(footer, { size: 10, font: pptxEastAsianFont(theme.fonts.body), color: theme.palette.muted })
281
397
  }
@@ -329,25 +445,31 @@ function commit(paths, data) {
329
445
  commitDeckArtifacts([{ path: paths.json, data: documentBytes(data.manifest), encoding: 'utf8' }, { path: paths.html, data: html, encoding: 'utf8' }, { path: paths.pptx, data: data.pptx }])
330
446
  }
331
447
 
448
+ function validateEmbeddedImgObject(img, assets) {
449
+ if (img.fit !== undefined && !['contain', 'cover'].includes(img.fit)) fail('工程 image.fit 只允许 contain / cover')
450
+ if (img.src !== undefined || !assets[img.assetId]) fail('工程图片必须使用有效的嵌入资产')
451
+ }
452
+
332
453
  function validateSnapshot(value, assets) {
333
454
  resolveTheme(value.theme); resolveLanguage(value.language)
334
455
  validateRawSlides(value.slides)
335
456
  validateDataSnapshot(value, normalizeSlides)
336
457
  if (value.brand != null) {
337
458
  if (Object.hasOwn(value.brand, 'logo')) fail('工程品牌仅支持嵌入的 logoAssetId,不读取本地 logo 路径')
338
- for (const key of ['primaryColor', 'backgroundColor', 'textColor', 'fontFamily', 'name', 'footer']) {
459
+ for (const key of ['primaryColor', 'backgroundColor', 'textColor', 'fontFamily', 'name', 'footer', 'chromeStyle']) {
339
460
  if (value.brand[key] !== undefined && typeof value.brand[key] !== 'string') fail('工程 brand.' + key + ' 必须为字符串')
340
461
  }
341
462
  normalizeBrand(value.brand, assets, '.')
342
463
  }
343
464
  for (const slide of value.slides) {
344
- if (slide.image) {
345
- if (slide.image.fit !== undefined && !['contain', 'cover'].includes(slide.image.fit)) fail('工程 image.fit 只允许 contain / cover')
346
- if (slide.image.src !== undefined || !assets[slide.image.assetId]) fail('工程图片必须使用有效的嵌入资产')
465
+ if (slide.image) validateEmbeddedImgObject(slide.image, assets)
466
+ if (Array.isArray(slide.images)) {
467
+ for (const img of slide.images) validateEmbeddedImgObject(img, assets)
347
468
  }
348
469
  if (slide.chart) normalizeChart(slide.chart)
349
470
  }
350
471
  }
472
+
351
473
  function artifactProblem(manifest, paths) {
352
474
  if (!manifest.artifacts) return '旧工程没有成品校验记录,无法确认外部修改;请另存副本,保留原文件。'
353
475
  for (const kind of ['html', 'pptx']) {
@@ -356,25 +478,152 @@ function artifactProblem(manifest, paths) {
356
478
  }
357
479
  }
358
480
 
481
+ const SKELETON_METRIC_RE = /(?:^|[^\d])[-+]?\d+(?:,\d{3})*(?:\.\d+)?\s*(?:[%%倍xX万亿千百元美元刀kKmMbB+家个席天周月年项次]|pp\b|bps\b|ms\b|pts?\b)/i
482
+
483
+ function mapSlidesToAbsorbedSkeleton(slides, slideSkeleton, langId) {
484
+ if (!Array.isArray(slides) || !Array.isArray(slideSkeleton) || slideSkeleton.length === 0) return slides
485
+ const bodySkeleton = slideSkeleton.filter((entry) => entry && !['cover', 'closing', 'section'].includes(entry.inferredLayout))
486
+ const cyclePool = bodySkeleton.length > 0 ? bodySkeleton : slideSkeleton
487
+ let cursor = 0
488
+ const mapped = slides.map((slide, idx) => {
489
+ if (slide.layout === 'cover' || slide.layout === 'closing' || slide.layout === 'section' || slide.layout === 'agenda') {
490
+ return slide
491
+ }
492
+ const target = cyclePool[cursor % cyclePool.length]
493
+ cursor += 1
494
+ if (!target || !target.inferredLayout) return slide
495
+ const want = target.inferredLayout
496
+ const bullets = Array.isArray(slide.bullets) ? slide.bullets : []
497
+ const n = bullets.length
498
+ const metricHits = bullets.filter((b) => SKELETON_METRIC_RE.test(stripInlineMarkdown(b))).length
499
+ const hasMetrics = n >= 2 && n <= 4 && (metricHits / n) >= 0.75
500
+ // Avoid breaking Markdown-only slides that lack media assets (chart/image) by mapping media slots to visual card equivalents
501
+ if (want === 'chart' || want === 'chart-split') {
502
+ return { ...slide, layout: hasMetrics ? 'kpi' : 'cards', variant: hasMetrics ? 'grid' : 'bento' }
503
+ }
504
+ if (want === 'image' || want === 'image-left' || want === 'image-right') {
505
+ return { ...slide, layout: n <= 2 ? 'callout' : 'cards', variant: n <= 2 ? 'takeaways' : 'pillars' }
506
+ }
507
+ if (want === 'matrix' && n !== 4) {
508
+ return { ...slide, layout: 'cards', variant: 'bento' }
509
+ }
510
+ if (want === 'kpi' && (!hasMetrics || n < 1 || n > 4)) {
511
+ return { ...slide, layout: 'cards', variant: 'pillars' }
512
+ }
513
+ if (want === 'table' && (!Array.isArray(slide.rows) || slide.rows.length === 0)) {
514
+ return { ...slide, layout: 'cards', variant: 'pillars' }
515
+ }
516
+ if (want === 'harvey' && (!Array.isArray(slide.rows) || slide.rows.length === 0)) {
517
+ return { ...slide, layout: 'comparison', variant: 'versus' }
518
+ }
519
+ if (['cards', 'kpi', 'comparison', 'matrix', 'process', 'callout', 'statement', 'bullets', 'gantt', 'architecture', 'tam', 'org'].includes(want)) {
520
+ return {
521
+ ...slide,
522
+ layout: want,
523
+ ...(target.variant ? { variant: target.variant } : {}),
524
+ ...(want === 'gantt' && !Array.isArray(slide.columns) ? { columns: ['Q1', 'Q2', 'Q3', 'Q4'] } : {}),
525
+ }
526
+ }
527
+ return slide
528
+ })
529
+ return normalizeSlides(mapped, 120, langId)
530
+ }
531
+
359
532
  export async function buildDeckAsync(options = {}) {
360
533
  abort(options.signal)
361
534
  validateRawSlides(options.slides)
362
- const scenario = options.template ? scenarios.find(s => s.id === options.template) : undefined
363
- if (options.template && !scenario) fail('未知 template,请使用 weekly / defense / project / pitch')
364
- const input = { ...options, theme: options.theme || scenario?.theme,
365
- ...(!options.content?.trim() && !options.slides?.length && scenario ? { slides: templateSlides(scenario, String(options.title ?? ''), options.lang) } : {}) }
366
535
  const cwd = resolve(options.cwd || '.')
367
- const dataModel = options.dataModel ? normalizeDataModel(options.dataModel, { cwd, allowFiles:true }) : undefined
536
+ const scenario = options.template ? findScenarioTemplate(options.template) : undefined
537
+ if (options.template && !scenario) fail('未知 template,请使用 ' + SCENARIO_TEMPLATES.map(s => s.id).join(' / '))
538
+
539
+ let absorbed = null
540
+ if (options.referencePptx !== undefined && options.referencePptx !== null && String(options.referencePptx).trim() !== '') {
541
+ absorbed = await absorbPptx({ pptxPath: String(options.referencePptx).trim(), cwd, extractLogo: true, signal: options.signal })
542
+ }
543
+
544
+ const rawThemeOpt = typeof options.theme === 'string' && options.theme.trim() ? options.theme.trim() : undefined
545
+ let chosenThemeId = rawThemeOpt
546
+ let directorHint = null
547
+ if (chosenThemeId === 'auto' || (!chosenThemeId && (options.persona || absorbed || scenario))) {
548
+ if (absorbed && (!rawThemeOpt || rawThemeOpt === 'auto') && !options.persona && !scenario) {
549
+ chosenThemeId = absorbed.recommendedTheme
550
+ } else {
551
+ directorHint = inferThemeFromContent({
552
+ title: options.title,
553
+ content: options.content,
554
+ slides: options.slides,
555
+ template: scenario?.id,
556
+ persona: options.persona,
557
+ })
558
+ chosenThemeId = directorHint.theme
559
+ }
560
+ }
561
+
562
+ const langId = resolveLanguage(options.lang).id
563
+ const fromMarkdown = !options.slides?.length && !scenario && Boolean(options.content?.trim())
564
+ const input = {
565
+ ...options,
566
+ theme: chosenThemeId,
567
+ ...(!options.content?.trim() && !options.slides?.length && scenario
568
+ ? { slides: buildScenarioSlides(scenario, String(options.title ?? ''), langId === 'en' ? 'en' : 'zh') }
569
+ : {}),
570
+ }
571
+
572
+ const dataModel = options.dataModel ? normalizeDataModel(options.dataModel, { cwd, allowFiles: true }) : undefined
368
573
  if (dataModel && (!Array.isArray(input.slides) || !input.slides.length)) fail('数据绑定需使用结构化 slides / Data binding requires structured slides')
369
- const prepared = dataModel ? prepareDataSlides(input.slides, dataModel, normalizeSlides, resolveLanguage(input.lang).id) : undefined
370
- const normalized = normalizeBuildOptions({ ...input, ...(prepared ? { slides:prepared } : {}) })
371
- if(prepared) normalized.deck.slides = prepared
574
+ const prepared = dataModel ? prepareDataSlides(input.slides, dataModel, normalizeSlides, langId) : undefined
575
+ const normalized = normalizeBuildOptions({ ...input, ...(prepared ? { slides: prepared } : {}) })
576
+ if (prepared) normalized.deck.slides = prepared
577
+
578
+ if (fromMarkdown) {
579
+ if (absorbed && options.cloneStructure === true && Array.isArray(absorbed.slideSkeleton) && absorbed.slideSkeleton.length > 0) {
580
+ normalized.deck.slides = mapSlidesToAbsorbedSkeleton(normalized.deck.slides, absorbed.slideSkeleton, langId)
581
+ } else {
582
+ const shouldPromote = options.smartLayout === true || (options.smartLayout !== false && (rawThemeOpt === 'auto' || Boolean(options.persona) || Boolean(absorbed)))
583
+ if (shouldPromote) {
584
+ normalized.deck.slides = promoteMarkdownSlides(normalized.deck.slides, { explicitSmartLayout: options.smartLayout === true })
585
+ }
586
+ }
587
+ }
588
+ if (directorHint?.tableStyle === 'booktabs') {
589
+ normalized.deck.slides = normalized.deck.slides.map(s => s.layout === 'table' && !s.tableStyle ? { ...s, tableStyle: 'booktabs' } : s)
590
+ }
591
+
372
592
  const assets = {}
373
- const brand = normalizeBrand(options.brand, assets, cwd)
374
- const manifest = { version: DECK_VERSION, schemaVersion: 1, deckId: randomUUID(), revision: 0,
375
- title: normalized.title, theme: normalized.theme.id, language: normalized.language.id, motion: normalized.motion,
376
- ...(scenario ? { template: scenario.id } : {}), ...(brand ? { brand } : {}), ...(dataModel ? {dataModel} : {}), assets, history: [],
377
- slides: embedSlides(normalized.deck.slides, assets, cwd).map(s => ({ ...s, id: randomUUID() })) }
593
+ let brandInput = options.brand
594
+ if (absorbed) {
595
+ const baseAbsorbedBrand = {
596
+ ...absorbed.sanitizedBrand,
597
+ ...(options.cloneStructure === true && absorbed.recommendedChrome ? { chromeStyle: absorbed.recommendedChrome } : {}),
598
+ }
599
+ const targetTheme = resolveTheme(normalized.theme.id)
600
+ if (
601
+ absorbed.sanitizedTokens?.coverMode === 'inverted-accent' &&
602
+ targetTheme.tokens?.coverMode === 'inverted-accent' &&
603
+ !options.brand?.backgroundColor
604
+ ) {
605
+ delete baseAbsorbedBrand.backgroundColor
606
+ }
607
+ brandInput = options.brand === null ? null : { ...baseAbsorbedBrand, ...(options.brand || {}) }
608
+ }
609
+ const brand = normalizeBrand(brandInput, assets, cwd)
610
+
611
+ const manifest = {
612
+ version: DECK_VERSION,
613
+ schemaVersion: 1,
614
+ deckId: randomUUID(),
615
+ revision: 0,
616
+ title: normalized.title,
617
+ theme: normalized.theme.id,
618
+ language: normalized.language.id,
619
+ motion: normalized.motion,
620
+ ...(scenario ? { template: scenario.id } : {}),
621
+ ...(brand ? { brand } : {}),
622
+ ...(dataModel ? { dataModel } : {}),
623
+ assets,
624
+ history: [],
625
+ slides: embedSlides(normalized.deck.slides, assets, cwd).map(s => ({ ...s, id: randomUUID() })),
626
+ }
378
627
  const data = await generate(manifest, options.signal)
379
628
  mkdirSync(normalized.outputDir, { recursive: true })
380
629
  // Resolve collisions after asynchronous rendering; an earlier call may have committed meanwhile.
@@ -413,6 +662,7 @@ function readDocument(pathInput, cwd = '.') {
413
662
  }
414
663
  return { manifest: document, path, fingerprint: hash(bytes) }
415
664
  }
665
+
416
666
  /** Validated project snapshot for the operator workbench; no file is modified. */
417
667
  export function readDeckProject(options = {}) {
418
668
  abort(options.signal)
@@ -444,13 +694,30 @@ async function saveRevision(state, next, signal, saveAs = false, preserveUndo =
444
694
 
445
695
  export async function editDeck(options = {}) {
446
696
  abort(options.signal)
697
+ const cwd = resolve(options.cwd || '.')
447
698
  const state = readDocument(options.deckPath, options.cwd), current = state.manifest
448
699
  expected(current, options.expectedRevision)
449
700
  const next = clone(current)
450
701
  if (!Array.isArray(options.edits) || !options.edits.length) {
451
- if (options.brand === undefined && options.order === undefined && options.duplicate === undefined && options.remove === undefined && options.append === undefined && options.saveAs !== true) fail('请提供 edits、order、duplicate、remove、append 或 brand')
702
+ if (
703
+ options.brand === undefined &&
704
+ options.theme === undefined &&
705
+ options.referencePptx === undefined &&
706
+ options.order === undefined &&
707
+ options.duplicate === undefined &&
708
+ options.remove === undefined &&
709
+ options.append === undefined &&
710
+ options.saveAs !== true
711
+ ) {
712
+ fail('请提供 edits、theme、referencePptx、order、duplicate、remove、append 或 brand')
713
+ }
452
714
  }
453
- const used = new Set(), allowed = new Set(['layout', 'title', 'subtitle', 'kicker', 'text', 'bullets', 'rows', 'notes', 'image', 'chart', 'visual'])
715
+ const used = new Set()
716
+ const allowed = new Set([
717
+ 'layout', 'variant', 'chrome', 'title', 'subtitle', 'kicker', 'takeaway', 'source',
718
+ 'text', 'activeIndex', 'tableStyle', 'bullets', 'items', 'cards', 'metrics',
719
+ 'columns', 'steps', 'quadrants', 'rows', 'notes', 'image', 'images', 'chart', 'visual',
720
+ ])
454
721
  for (const edit of options.edits ?? []) {
455
722
  const index = typeof edit.slide === 'number' && Number.isInteger(edit.slide) ? edit.slide - 1 : next.slides.findIndex(s => s.id === edit.slide)
456
723
  if (index < 0 || index >= next.slides.length) fail('找不到要修改的页面:' + edit.slide)
@@ -462,14 +729,28 @@ export async function editDeck(options = {}) {
462
729
  const changed = { ...next.slides[index], ...next.slides[index].dataTemplate, ...edit.patch }
463
730
  delete changed.dataTemplate
464
731
  for (const key of Object.keys(changed)) if (changed[key] === null) delete changed[key]
465
- if (edit.patch.chart) { if (!edit.patch.layout) changed.layout = 'chart'; if (changed.layout === 'chart') delete changed.image }
466
- if (edit.patch.image) { if (!edit.patch.layout && !['image', 'image-left', 'image-right'].includes(changed.layout)) changed.layout = 'image-right'; if (['image', 'image-left', 'image-right'].includes(changed.layout)) delete changed.chart }
467
- if (edit.patch.layout && !MEDIA_LAYOUTS.has(edit.patch.layout)) { delete changed.image; delete changed.chart }
732
+ if (edit.patch.bullets && !edit.patch.items && !edit.patch.cards && !edit.patch.metrics && !edit.patch.steps && !edit.patch.columns && !edit.patch.quadrants && !next.slides[index].dataTemplate?.items) {
733
+ delete changed.items
734
+ }
735
+ if (edit.patch.chart) {
736
+ if (!edit.patch.layout && !['chart', 'chart-split', 'waterfall'].includes(changed.layout)) changed.layout = 'chart'
737
+ if (['chart', 'chart-split', 'waterfall'].includes(changed.layout)) { delete changed.image; delete changed.images }
738
+ }
739
+ if (edit.patch.image || edit.patch.images) {
740
+ if (!edit.patch.layout && !['image', 'image-left', 'image-right', 'gallery'].includes(changed.layout)) {
741
+ changed.layout = Array.isArray(edit.patch.images) && edit.patch.images.length > 1 ? 'image' : 'image-right'
742
+ }
743
+ if (['image', 'image-left', 'image-right', 'gallery'].includes(changed.layout)) delete changed.chart
744
+ }
745
+ if (edit.patch.layout) {
746
+ const eff = effectiveLayout(edit.patch.layout)
747
+ if (!MEDIA_LAYOUTS.has(eff)) { delete changed.image; delete changed.images; delete changed.chart }
748
+ }
468
749
  validateRawSlides([changed])
469
750
  let slides
470
751
  try { slides = next.dataModel ? prepareDataSlides([changed], next.dataModel, normalizeSlides, next.language) : normalizeSlides([changed], 120, next.language) } catch (error) { fail(`第 ${index + 1} 页修改失败:${error.message}`) }
471
752
  if (slides.length !== 1) fail(`第 ${index + 1} 页修改会产生分页,请减少表格行数或另建演示文稿`)
472
- const embedded = embedSlides(slides, next.assets, resolve(options.cwd || '.'))[0]
753
+ const embedded = embedSlides(slides, next.assets, cwd)[0]
473
754
  next.slides[index] = { ...embedded, id: current.slides[index].id }
474
755
  }
475
756
  if (options.order !== undefined) {
@@ -501,10 +782,36 @@ export async function editDeck(options = {}) {
501
782
  validateRawSlides(options.append)
502
783
  const added = next.dataModel ? prepareDataSlides(options.append, next.dataModel, normalizeSlides, next.language) : normalizeSlides(options.append, 120, next.language)
503
784
  if (next.slides.length + added.length > 120) fail('工程页数超过 120')
504
- next.slides.push(...embedSlides(added, next.assets, resolve(options.cwd || '.')).map(slide => ({ ...slide, id: randomUUID() })))
785
+ next.slides.push(...embedSlides(added, next.assets, cwd).map(slide => ({ ...slide, id: randomUUID() })))
786
+ }
787
+
788
+ if (options.theme !== undefined) {
789
+ const requestedTheme = String(options.theme ?? '').trim()
790
+ if (!requestedTheme) fail('theme 不能为空')
791
+ next.theme = requestedTheme === 'auto'
792
+ ? inferThemeFromContent({ title: next.title, slides: next.slides, template: next.template }).theme
793
+ : resolveTheme(requestedTheme).id
794
+ }
795
+
796
+ if (options.referencePptx !== undefined && options.referencePptx !== null && String(options.referencePptx).trim() !== '') {
797
+ const absorbed = await absorbPptx({ pptxPath: String(options.referencePptx).trim(), cwd, extractLogo: true, signal: options.signal })
798
+ if (options.theme === undefined) next.theme = absorbed.recommendedTheme
799
+ const absorbedBrand = { ...absorbed.sanitizedBrand }
800
+ if (
801
+ absorbed.sanitizedTokens?.coverMode === 'inverted-accent' &&
802
+ resolveTheme(next.theme).tokens?.coverMode === 'inverted-accent' &&
803
+ !options.brand?.backgroundColor
804
+ ) {
805
+ delete absorbedBrand.backgroundColor
806
+ }
807
+ next.brand = normalizeBrand({ ...next.brand, ...absorbedBrand }, next.assets, cwd)
808
+ }
809
+
810
+ if (options.brand !== undefined) {
811
+ next.brand = normalizeBrand(options.brand === null ? null : { ...next.brand, ...options.brand,
812
+ ...(options.brand?.logo === null ? { logo: undefined, logoAssetId: undefined } : {}) }, next.assets, cwd)
813
+ if (next.brand && Object.keys(next.brand).length === 0) delete next.brand
505
814
  }
506
- if (options.brand !== undefined) next.brand = normalizeBrand(options.brand === null ? null : { ...next.brand, ...options.brand,
507
- ...(options.brand?.logo === null ? { logo: undefined, logoAssetId: undefined } : {}) }, next.assets, resolve(options.cwd || '.'))
508
815
  if (options.saveAs !== true && JSON.stringify(snapshot(next)) === JSON.stringify(snapshot(current))) return { ...result(current, pathsFor(state.path)), changed: false }
509
816
  next.history = [...next.history, snapshot(current)].slice(-MAX_HISTORY)
510
817
  return { ...await saveRevision(state, next, options.signal, options.saveAs === true, options.preserveUndo === true), changed: true }
@@ -537,22 +844,22 @@ export async function undoDeck(options = {}) {
537
844
 
538
845
  function dataChange(state, options) {
539
846
  expected(state.manifest, options.expectedRevision)
540
- const packet=options.scenario
541
- if(packet && (packet.schemaVersion!==1||packet.deckId!==state.manifest.deckId||packet.revision!==state.manifest.revision||packet.fingerprint!==state.manifest.dataModel?.fingerprint))fail('推演参数来自其他工程或旧版本,请重新导出 / Scenario belongs to another project or revision')
542
- return previewDataChange(state.manifest,{...options,...(packet?{parameters:packet.parameters}:{})},normalizeSlides)
847
+ const packet = options.scenario
848
+ if (packet && (packet.schemaVersion !== 1 || packet.deckId !== state.manifest.deckId || packet.revision !== state.manifest.revision || packet.fingerprint !== state.manifest.dataModel?.fingerprint)) fail('推演参数来自其他工程或旧版本,请重新导出 / Scenario belongs to another project or revision')
849
+ return previewDataChange(state.manifest, { ...options, ...(packet ? { parameters: packet.parameters } : {}) }, normalizeSlides)
543
850
  }
544
851
  export function previewDeckData(options = {}) {
545
852
  abort(options.signal)
546
- const state=readDocument(options.deckPath, options.cwd)
547
- return { ok:true, deckId:state.manifest.deckId, revision:state.manifest.revision, ...dataChange(state,options).preview }
853
+ const state = readDocument(options.deckPath, options.cwd)
854
+ return { ok: true, deckId: state.manifest.deckId, revision: state.manifest.revision, ...dataChange(state, options).preview }
548
855
  }
549
856
  export async function updateDeckData(options = {}) {
550
857
  abort(options.signal)
551
- const state=readDocument(options.deckPath,options.cwd),change=dataChange(state,options)
552
- if(options.confirmed!==true||options.expectedRevision===undefined||options.previewToken!==change.preview.token)fail('请先预览差异,再携带修订号与预览凭证确认 / Preview changes and confirm with the revision and preview token')
553
- if(!change.preview.changed)return {...result(state.manifest,pathsFor(state.path)),changed:false}
554
- const next={...clone(state.manifest),dataModel:change.model,slides:change.slides,history:[...state.manifest.history,snapshot(state.manifest)].slice(-MAX_HISTORY)}
555
- return {...await saveRevision(state,next,options.signal,options.saveAs!==false,true),changed:true}
858
+ const state = readDocument(options.deckPath, options.cwd), change = dataChange(state, options)
859
+ if (options.confirmed !== true || options.expectedRevision === undefined || options.previewToken !== change.preview.token) fail('请先预览差异,再携带修订号与预览凭证确认 / Preview changes and confirm with the revision and preview token')
860
+ if (!change.preview.changed) return { ...result(state.manifest, pathsFor(state.path)), changed: false }
861
+ const next = { ...clone(state.manifest), dataModel: change.model, slides: change.slides, history: [...state.manifest.history, snapshot(state.manifest)].slice(-MAX_HISTORY) }
862
+ return { ...await saveRevision(state, next, options.signal, options.saveAs !== false, true), changed: true }
556
863
  }
557
864
 
558
865
  export function checkDeck(options = {}) {