dsh-ppt 0.14.0 → 0.16.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.
- package/CHANGELOG.md +16 -0
- package/README.en.md +3 -0
- package/README.md +2 -0
- package/docs/DATA.md +43 -0
- package/docs/USAGE.en.md +1 -1
- package/docs/USAGE.md +3 -1
- package/docs/VALIDATION.md +4 -0
- package/docs/VISUAL.md +54 -0
- package/docs/validation-0.15.0.md +25 -0
- package/docs/validation-0.16.0.md +30 -0
- package/lib/client.js +207 -24
- package/lib/coaching.d.ts +1 -0
- package/lib/coaching.js +1 -1
- package/lib/execution.d.ts +1 -0
- package/lib/execution.js +11 -0
- package/lib/index.d.ts +1 -1
- package/lib/index.js +6 -1
- package/lib/tools.js +27 -0
- package/lib/types.d.ts +51 -0
- package/lib/visual-model.d.ts +13 -0
- package/lib/visual-model.js +104 -0
- package/lib/visual.d.ts +197 -0
- package/lib/visual.js +382 -0
- package/lib/workbench.d.ts +4 -0
- package/lib/workbench.js +55 -8
- package/package.json +5 -3
- package/skills/dsh-ppt/SKILL.md +4 -1
- package/skills/dsh-ppt/package.json +3 -3
- package/skills/dsh-ppt/references/data.md +67 -0
- package/skills/dsh-ppt/scripts/build-deck.mjs +3 -0
- package/skills/dsh-ppt/scripts/deck-advanced.mjs +56 -10
- package/skills/dsh-ppt/scripts/deck-core.mjs +19 -4
- package/skills/dsh-ppt/scripts/deck-data-math.mjs +76 -0
- package/skills/dsh-ppt/scripts/deck-data-view.mjs +113 -0
- package/skills/dsh-ppt/scripts/deck-data.mjs +190 -0
- package/skills/dsh-ppt/scripts/deck-visual.mjs +79 -0
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# 数据来源、公式和推演
|
|
2
|
+
|
|
3
|
+
默认直接交付成品。需要解释数字或现场推演时,才在 `ppt_create` 提供 `dataModel` 和结构化 `slides`。不从相同数值猜来源,不虚构单元格、原文或文件。
|
|
4
|
+
|
|
5
|
+
## 最小完整示例
|
|
6
|
+
|
|
7
|
+
```json
|
|
8
|
+
{
|
|
9
|
+
"title": "经营情景",
|
|
10
|
+
"slides": [
|
|
11
|
+
{ "layout": "cover", "title": "经营情景", "subtitle": "基期收入 {{base}}" },
|
|
12
|
+
{ "layout": "bullets", "title": "增长 {{growth}}", "bullets": ["推演收入 {{revenue}}", "以上增长率是讨论假设"] },
|
|
13
|
+
{ "layout": "chart", "title": "收入对比", "chart": { "kind": "column", "categories": ["基期", "情景"], "series": [{"name": "收入", "values": ["{{base}}", "{{revenue}}"]}], "unit": "万元" } }
|
|
14
|
+
],
|
|
15
|
+
"dataModel": {
|
|
16
|
+
"schemaVersion": 1,
|
|
17
|
+
"sources": [{ "id": "sales", "name": "经营数据.csv", "format": "csv", "content": "项目,收入\n基期,1000" }],
|
|
18
|
+
"metrics": [
|
|
19
|
+
{ "id": "base", "label": "基期收入", "kind": "source", "source": { "sourceId": "sales", "cell": "B2" }, "format": { "digits": 0, "unit": "万元" } },
|
|
20
|
+
{ "id": "growth", "label": "增长率", "kind": "input", "value": 0.3, "min": 0, "max": 1, "step": 0.1, "note": "用于讨论的假设,不是业绩承诺", "format": { "style": "percent", "digits": 0 } },
|
|
21
|
+
{ "id": "revenue", "label": "情景收入", "kind": "formula", "formula": "base * (1 + growth)", "format": { "digits": 0, "unit": "万元" } }
|
|
22
|
+
]
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`source` 是材料中的事实,`input` 是可调假设,`formula` 是推导。百分比以比例计算:30% 是 `0.3`。数字格式为 `number`(默认)或 `percent`、0–6 位小数及可选 `unit`。显示舍入不改变计算输入。
|
|
28
|
+
|
|
29
|
+
文本、要点、表格、备注和图表标签用 `{{metricId}}`;图表数值必须是完整占位符,计算仍使用原始数值。ID 使用字母开头的字母和数字,最多 48 字符。
|
|
30
|
+
|
|
31
|
+
## 来源
|
|
32
|
+
|
|
33
|
+
- 表格:`format:csv/tsv` + `content`,或 `kind:table` + `rows`。地址 `A1–Z500`,首行表头也算第 1 行。引用格必须是单一数值,可含千位逗号或百分号。
|
|
34
|
+
- 材料:`format:text` + `content`,或 `kind:text` + `text`。引用 `{sourceId,line:1,numberIndex:0}`;行号从 1 开始,该行数值序号从 0 开始。日期、版本号也可能被识别为数字,必须检查截取位置。
|
|
35
|
+
- 工具调用可显式给 `path` 读取本地普通文件,按会话 cwd 解析;只读取一次并嵌入,不监视源文件。网页只能使用用户选取或粘贴的内容,不能让浏览器请求读取任意路径。
|
|
36
|
+
- UTF-8 CSV / TSV / TXT / Markdown;最多 8 个来源、合计 1 MiB,表格最多 500 行 / 26 列,各行等宽,每格最多 2000 字符。文本引用行最多 8000 字符。无 XLSX / PDF 数字自动提取。
|
|
37
|
+
|
|
38
|
+
## 算术与范围
|
|
39
|
+
|
|
40
|
+
最多 80 个指标和 12 个假设。假设必须提供有限的 `value/min/max/step`,处于范围和步长网格内,最多 100000 步。计算结果绝对值不超过 1e15。
|
|
41
|
+
|
|
42
|
+
公式允许指标 ID、括号、`+ - * / % **`、一元正负,以及 `min/max/sum/abs/floor/ceil/round`。`round(value,digits)` 的 digits 为 0–6。最多 256 个 AST 节点、32 层表达式和 40 层指标依赖。循环、除零、未知指标、非有限结果会报错。没有 `eval`、属性访问、赋值、网络或文件执行。
|
|
43
|
+
|
|
44
|
+
## 更新与确认
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
// 1. 先预览,不修改任何成品。
|
|
48
|
+
ppt_data({ action: 'preview', deckPath, expectedRevision: 0,
|
|
49
|
+
parameters: { growth: 0.5 } })
|
|
50
|
+
// 或替换已有来源:sourceUpdates:[{id:'sales',format:'csv',content:'项目,收入\n基期,1200'}]
|
|
51
|
+
|
|
52
|
+
// 2. 向用户展示 changes、affectedSlides 与字段前后差异,确认后再保存。
|
|
53
|
+
ppt_data({ action: 'apply', deckPath, expectedRevision: 0,
|
|
54
|
+
parameters: { growth: 0.5 }, confirmed: true, previewToken: preview.token })
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
应用默认 `saveAs:true`,原稿不变,新副本可撤销;`saveAs:false` 仍执行外部成品修改保护。预览凭证绑定完整工程状态、数据与修订,任一变化都应重新预览。`ppt_undo` 同步恢复来源、参数、公式和页面。
|
|
58
|
+
|
|
59
|
+
`ppt_edit` 会保留未修改字段的绑定。用普通文字替换绑定字段会解除该字段绑定;需要继续联动时保留占位符。确认后的静态 PPTX 备注和下载报告附上引用链。可选 AI 预审也会获得页面相关的公式与假设说明,不把来源关联当作事实核验。
|
|
60
|
+
|
|
61
|
+
离线 HTML 的 `scenario.json` 包含 `schemaVersion/deckId/revision/fingerprint/parameters`。导回相同 DSH 工程后预览、确认,再下载匹配的静态 PPTX;也可作为 `ppt_data.scenario` 传入。不可将旧工程参数强套到新副本。
|
|
62
|
+
|
|
63
|
+
跨 harness:在技能目录 `npm install --ignore-scripts` 后,使用 `node scripts/build-deck.mjs --title ... --slides @slides.json --data-model @model.json --out ...`。直接 JS 调用使用 `deck-advanced.mjs` 的 `buildDeckAsync`;同步 `deck-core.buildDeck` 不支持数据模型。
|
|
64
|
+
|
|
65
|
+
## Dependencies
|
|
66
|
+
|
|
67
|
+
CSV parsing uses [csv-parse](https://csv.js.org/parse/api/sync/) 6.1.0 ([MIT](https://github.com/adaltas/node-csv/blob/master/LICENSE)). Formulas are parsed with [jsep](https://github.com/EricSmekens/jsep) 1.4.0 ([MIT](https://github.com/EricSmekens/jsep/blob/main/LICENSE)); the plugin supplies its own restricted evaluator. Dependencies retain their own license notices. Offline HTML embeds the plugin's validated arithmetic representation and runtime, not those parser implementations.
|
|
@@ -28,6 +28,7 @@ const HELP = `dsh-ppt —— 一句话 / 一篇文档 → HTML 放映 + PPTX 导
|
|
|
28
28
|
--slides <json> 结构化 slides JSON(可选,与 --content 二选一)
|
|
29
29
|
--template <id> weekly / defense / project / pitch;仅模板会生成草稿
|
|
30
30
|
--brand <json|@path> 品牌颜色、字体、Logo、页脚
|
|
31
|
+
--data-model <json|@path> 可选数字来源、公式与推演假设;配合 --slides
|
|
31
32
|
--edit <deck.json> 修改指定页,配合 --edits <json|@path>
|
|
32
33
|
--undo <deck.json> 撤销最近一次修改
|
|
33
34
|
--check <deck.json> 查看质量报告和页码 / ID
|
|
@@ -76,6 +77,7 @@ export function parseArgv(argv) {
|
|
|
76
77
|
else if (key === '--slides') args.slides = readJson(nextValue())
|
|
77
78
|
else if (key === '--template') args.template = nextValue()
|
|
78
79
|
else if (key === '--brand') args.brand = readJson(nextValue())
|
|
80
|
+
else if (key === '--data-model') args.dataModel = readJson(nextValue())
|
|
79
81
|
else if (key === '--edit') args.edit = nextValue()
|
|
80
82
|
else if (key === '--edits') args.edits = readJson(nextValue())
|
|
81
83
|
else if (key === '--undo') args.undo = nextValue()
|
|
@@ -163,6 +165,7 @@ export async function main(argv = process.argv.slice(2), io = {}) {
|
|
|
163
165
|
overwrite: args.overwrite,
|
|
164
166
|
template: args.template,
|
|
165
167
|
brand: args.brand,
|
|
168
|
+
dataModel: args.dataModel,
|
|
166
169
|
}
|
|
167
170
|
const result = await buildDeckAsync(options)
|
|
168
171
|
log('dsh-ppt 已生成 ' + result.slideCount + ' 页演示文稿:')
|
|
@@ -4,6 +4,10 @@ import { createHash, randomUUID } from 'node:crypto'
|
|
|
4
4
|
import { inflateSync } from 'node:zlib'
|
|
5
5
|
import { buildPptx, renderHtml, normalizeBuildOptions, normalizeSlides, resolveTheme, resolveLanguage, resolveDeckFileName, commitDeckArtifacts, DECK_VERSION, pptxEastAsianFont } from './deck-core.mjs'
|
|
6
6
|
import { MEDIA_LAYOUTS, mediaBoxes, LOGO_BOX, FOOTER_BOX, chartColors, normalizeChart } from './deck-media.mjs'
|
|
7
|
+
import { normalizeDataModel, prepareDataSlides, validateDataSnapshot, previewDataChange, dataNotes, dataReport } from './deck-data.mjs'
|
|
8
|
+
import { normalizeVisual, applyVisualActions } from './deck-visual.mjs'
|
|
9
|
+
export { readRenderReceipt } from './deck-render.mjs'
|
|
10
|
+
export { dataNotes, dataReport } from './deck-data.mjs'
|
|
7
11
|
export { buildDeck, buildThemePreview, listThemes, resolveTheme, resolveLanguage } from './deck-core.mjs'
|
|
8
12
|
|
|
9
13
|
const MAX_IMAGE = 5 * 1024 * 1024, MAX_ASSETS = 32 * 1024 * 1024, MAX_DOCUMENT = 64 * 1024 * 1024
|
|
@@ -143,13 +147,14 @@ function validateRawSlides(slides) {
|
|
|
143
147
|
slides.forEach((s, i) => {
|
|
144
148
|
if (!s || typeof s !== 'object' || Array.isArray(s)) fail(`第 ${i + 1} 页必须是对象`)
|
|
145
149
|
if (s.layout && !layouts.has(s.layout)) fail(`第 ${i + 1} 页未知布局 ${s.layout}`)
|
|
150
|
+
normalizeVisual(s.visual)
|
|
146
151
|
if (s.chart && s.image) fail(`第 ${i + 1} 页不能同时放入 image 和 chart`)
|
|
147
152
|
if (s.image && s.layout && !['image', 'image-left', 'image-right'].includes(s.layout)) fail(`第 ${i + 1} 页图片需使用 image / image-left / image-right 布局`)
|
|
148
153
|
if (s.chart && s.layout && s.layout !== 'chart') fail(`第 ${i + 1} 页图表需使用 chart 布局`)
|
|
149
154
|
})
|
|
150
155
|
}
|
|
151
156
|
function snapshot(manifest) {
|
|
152
|
-
return clone(Object.fromEntries(['title', 'theme', 'language', 'motion', 'slides', 'brand', 'template'].filter(k => manifest[k] !== undefined).map(k => [k, manifest[k]])))
|
|
157
|
+
return clone(Object.fromEntries(['title', 'theme', 'language', 'motion', 'slides', 'brand', 'template', 'dataModel'].filter(k => manifest[k] !== undefined).map(k => [k, manifest[k]])))
|
|
153
158
|
}
|
|
154
159
|
function collectAssets(manifest) {
|
|
155
160
|
const ids = new Set()
|
|
@@ -231,7 +236,7 @@ export function checkManifest(manifest) {
|
|
|
231
236
|
}
|
|
232
237
|
|
|
233
238
|
async function exportPptx(manifest, theme, language, signal) {
|
|
234
|
-
const base = buildPptx(manifest, theme, language)
|
|
239
|
+
const base = buildPptx({ ...manifest, slides: manifest.slides.map(s => ({ ...s, notes: dataNotes(manifest,s) })) }, theme, language)
|
|
235
240
|
if (!manifest.brand?.logoAssetId && !manifest.brand?.footer && !manifest.slides.some(s => s.image || s.chart)) return base
|
|
236
241
|
abort(signal)
|
|
237
242
|
let lib
|
|
@@ -255,7 +260,7 @@ async function exportPptx(manifest, theme, language, signal) {
|
|
|
255
260
|
if (source.image) putImage(slide, source.image.assetId, boxes.image, source.image.fit, 'Slide image', source.image.alt)
|
|
256
261
|
if (source.chart) {
|
|
257
262
|
const colors = chartColors(theme), font = pptxEastAsianFont(theme.fonts.body)
|
|
258
|
-
const style = { font, sizePt: 17, color: theme.palette.fg }
|
|
263
|
+
const style = { font, sizePt: source.visual?.chartLabelSize ?? 17, color: theme.palette.fg }
|
|
259
264
|
lib.addSlideChart(slide, { ...emu(boxes.chart), name: 'Editable data chart', spec: {
|
|
260
265
|
kind: source.chart.kind, categories: source.chart.categories,
|
|
261
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]) } : {}) })),
|
|
@@ -327,6 +332,7 @@ function commit(paths, data) {
|
|
|
327
332
|
function validateSnapshot(value, assets) {
|
|
328
333
|
resolveTheme(value.theme); resolveLanguage(value.language)
|
|
329
334
|
validateRawSlides(value.slides)
|
|
335
|
+
validateDataSnapshot(value, normalizeSlides)
|
|
330
336
|
if (value.brand != null) {
|
|
331
337
|
if (Object.hasOwn(value.brand, 'logo')) fail('工程品牌仅支持嵌入的 logoAssetId,不读取本地 logo 路径')
|
|
332
338
|
for (const key of ['primaryColor', 'backgroundColor', 'textColor', 'fontFamily', 'name', 'footer']) {
|
|
@@ -357,12 +363,17 @@ export async function buildDeckAsync(options = {}) {
|
|
|
357
363
|
if (options.template && !scenario) fail('未知 template,请使用 weekly / defense / project / pitch')
|
|
358
364
|
const input = { ...options, theme: options.theme || scenario?.theme,
|
|
359
365
|
...(!options.content?.trim() && !options.slides?.length && scenario ? { slides: templateSlides(scenario, String(options.title ?? ''), options.lang) } : {}) }
|
|
360
|
-
const
|
|
366
|
+
const cwd = resolve(options.cwd || '.')
|
|
367
|
+
const dataModel = options.dataModel ? normalizeDataModel(options.dataModel, { cwd, allowFiles:true }) : undefined
|
|
368
|
+
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
|
|
361
372
|
const assets = {}
|
|
362
373
|
const brand = normalizeBrand(options.brand, assets, cwd)
|
|
363
374
|
const manifest = { version: DECK_VERSION, schemaVersion: 1, deckId: randomUUID(), revision: 0,
|
|
364
375
|
title: normalized.title, theme: normalized.theme.id, language: normalized.language.id, motion: normalized.motion,
|
|
365
|
-
...(scenario ? { template: scenario.id } : {}), ...(brand ? { brand } : {}), assets, history: [],
|
|
376
|
+
...(scenario ? { template: scenario.id } : {}), ...(brand ? { brand } : {}), ...(dataModel ? {dataModel} : {}), assets, history: [],
|
|
366
377
|
slides: embedSlides(normalized.deck.slides, assets, cwd).map(s => ({ ...s, id: randomUUID() })) }
|
|
367
378
|
const data = await generate(manifest, options.signal)
|
|
368
379
|
mkdirSync(normalized.outputDir, { recursive: true })
|
|
@@ -439,7 +450,7 @@ export async function editDeck(options = {}) {
|
|
|
439
450
|
if (!Array.isArray(options.edits) || !options.edits.length) {
|
|
440
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')
|
|
441
452
|
}
|
|
442
|
-
const used = new Set(), allowed = new Set(['layout', 'title', 'subtitle', 'kicker', 'text', 'bullets', 'rows', 'notes', 'image', 'chart'])
|
|
453
|
+
const used = new Set(), allowed = new Set(['layout', 'title', 'subtitle', 'kicker', 'text', 'bullets', 'rows', 'notes', 'image', 'chart', 'visual'])
|
|
443
454
|
for (const edit of options.edits ?? []) {
|
|
444
455
|
const index = typeof edit.slide === 'number' && Number.isInteger(edit.slide) ? edit.slide - 1 : next.slides.findIndex(s => s.id === edit.slide)
|
|
445
456
|
if (index < 0 || index >= next.slides.length) fail('找不到要修改的页面:' + edit.slide)
|
|
@@ -448,14 +459,15 @@ export async function editDeck(options = {}) {
|
|
|
448
459
|
if (!edit.patch || typeof edit.patch !== 'object' || Array.isArray(edit.patch)) fail('第 ' + (index + 1) + ' 页 patch 需为对象')
|
|
449
460
|
for (const key of Object.keys(edit.patch)) if (!allowed.has(key)) fail('不支持修改页面字段:' + key)
|
|
450
461
|
validateRawSlides([edit.patch])
|
|
451
|
-
const changed = { ...next.slides[index], ...edit.patch }
|
|
462
|
+
const changed = { ...next.slides[index], ...next.slides[index].dataTemplate, ...edit.patch }
|
|
463
|
+
delete changed.dataTemplate
|
|
452
464
|
for (const key of Object.keys(changed)) if (changed[key] === null) delete changed[key]
|
|
453
465
|
if (edit.patch.chart) { if (!edit.patch.layout) changed.layout = 'chart'; if (changed.layout === 'chart') delete changed.image }
|
|
454
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 }
|
|
455
467
|
if (edit.patch.layout && !MEDIA_LAYOUTS.has(edit.patch.layout)) { delete changed.image; delete changed.chart }
|
|
456
468
|
validateRawSlides([changed])
|
|
457
469
|
let slides
|
|
458
|
-
try { slides = normalizeSlides([changed], 120, next.language) } catch (error) { fail(`第 ${index + 1} 页修改失败:${error.message}`) }
|
|
470
|
+
try { slides = next.dataModel ? prepareDataSlides([changed], next.dataModel, normalizeSlides, next.language) : normalizeSlides([changed], 120, next.language) } catch (error) { fail(`第 ${index + 1} 页修改失败:${error.message}`) }
|
|
459
471
|
if (slides.length !== 1) fail(`第 ${index + 1} 页修改会产生分页,请减少表格行数或另建演示文稿`)
|
|
460
472
|
const embedded = embedSlides(slides, next.assets, resolve(options.cwd || '.'))[0]
|
|
461
473
|
next.slides[index] = { ...embedded, id: current.slides[index].id }
|
|
@@ -487,7 +499,7 @@ export async function editDeck(options = {}) {
|
|
|
487
499
|
if (options.append !== undefined) {
|
|
488
500
|
if (!Array.isArray(options.append) || options.append.length < 1 || options.append.length > 5) fail('append 需为 1-5 页')
|
|
489
501
|
validateRawSlides(options.append)
|
|
490
|
-
const added = normalizeSlides(options.append, 120, next.language)
|
|
502
|
+
const added = next.dataModel ? prepareDataSlides(options.append, next.dataModel, normalizeSlides, next.language) : normalizeSlides(options.append, 120, next.language)
|
|
491
503
|
if (next.slides.length + added.length > 120) fail('工程页数超过 120')
|
|
492
504
|
next.slides.push(...embedSlides(added, next.assets, resolve(options.cwd || '.')).map(slide => ({ ...slide, id: randomUUID() })))
|
|
493
505
|
}
|
|
@@ -498,17 +510,51 @@ export async function editDeck(options = {}) {
|
|
|
498
510
|
return { ...await saveRevision(state, next, options.signal, options.saveAs === true, options.preserveUndo === true), changed: true }
|
|
499
511
|
}
|
|
500
512
|
|
|
513
|
+
/** An AI-selected, bounded formatting vocabulary; always an undoable new copy. */
|
|
514
|
+
export async function repairDeckVisual(options = {}) {
|
|
515
|
+
abort(options.signal)
|
|
516
|
+
const state = readDocument(options.deckPath, options.cwd)
|
|
517
|
+
expected(state.manifest, options.expectedRevision)
|
|
518
|
+
const next = clone(state.manifest)
|
|
519
|
+
next.slides = applyVisualActions(next, options.actions)
|
|
520
|
+
// Splitting can move the only binding off a continuation page. Rebuild each
|
|
521
|
+
// page's canonical template so plain fields do not remain falsely bound.
|
|
522
|
+
if (next.dataModel) next.slides = next.slides.map(slide => ({ ...prepareDataSlides([slide], next.dataModel, normalizeSlides, next.language)[0], id: slide.id }))
|
|
523
|
+
if (JSON.stringify(next.slides) === JSON.stringify(state.manifest.slides)) fail('排版操作没有变化 / Formatting actions made no changes')
|
|
524
|
+
return saveRevision(state, next, options.signal, true, true)
|
|
525
|
+
}
|
|
526
|
+
|
|
501
527
|
export async function undoDeck(options = {}) {
|
|
502
528
|
abort(options.signal)
|
|
503
529
|
const state = readDocument(options.deckPath, options.cwd)
|
|
504
530
|
expected(state.manifest, options.expectedRevision)
|
|
505
531
|
if (!state.manifest.history.length) fail('该工程没有可撤销的修改')
|
|
506
532
|
const next = clone(state.manifest), prior = next.history.pop()
|
|
507
|
-
for (const key of ['brand', 'template']) delete next[key]
|
|
533
|
+
for (const key of ['brand', 'template', 'dataModel']) delete next[key]
|
|
508
534
|
Object.assign(next, prior)
|
|
509
535
|
return saveRevision(state, next, options.signal)
|
|
510
536
|
}
|
|
511
537
|
|
|
538
|
+
function dataChange(state, options) {
|
|
539
|
+
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)
|
|
543
|
+
}
|
|
544
|
+
export function previewDeckData(options = {}) {
|
|
545
|
+
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 }
|
|
548
|
+
}
|
|
549
|
+
export async function updateDeckData(options = {}) {
|
|
550
|
+
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}
|
|
556
|
+
}
|
|
557
|
+
|
|
512
558
|
export function checkDeck(options = {}) {
|
|
513
559
|
abort(options.signal)
|
|
514
560
|
const { manifest, path } = readDocument(options.deckPath, options.cwd)
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* deck.pptx 可编辑 PPTX(16:9,OOXML 由本文件手写,zip 用 node:zlib)
|
|
12
12
|
* deck.json 结构化 deck manifest
|
|
13
13
|
*
|
|
14
|
-
*
|
|
14
|
+
* 零外部运行时依赖,仅使用 Node 内置模块。
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
@@ -19,6 +19,8 @@ import { resolve as resolvePath, join as joinPath } from 'node:path'
|
|
|
19
19
|
import { deflateRawSync } from 'node:zlib'
|
|
20
20
|
import { MEDIA_LAYOUTS, MEDIA_CSS, normalizeMediaSlide, renderMediaHtml, mediaBoxes } from './deck-media.mjs'
|
|
21
21
|
import { renderDelivery } from './deck-delivery.mjs'
|
|
22
|
+
import { renderDataView } from './deck-data-view.mjs'
|
|
23
|
+
import { normalizeVisual, visualHtmlStyle, visualShapeXml, VISUAL_CSS } from './deck-visual.mjs'
|
|
22
24
|
|
|
23
25
|
/**
|
|
24
26
|
* manifest 版本跟随发布包 package.json;把 skills/dsh-ppt 独立复制到其他
|
|
@@ -803,6 +805,10 @@ export function parseMarkdownDeck(titleInput, content, lang = 'zh') {
|
|
|
803
805
|
const SLIDE_LAYOUTS = new Set(['cover', 'section', 'bullets', 'statement', 'closing', 'quote', 'table', ...MEDIA_LAYOUTS])
|
|
804
806
|
|
|
805
807
|
function normalizeSlide(raw, index) {
|
|
808
|
+
const result = normalizeSlideContent(raw, index), visual = normalizeVisual(raw?.visual)
|
|
809
|
+
return visual ? { ...result, visual } : result
|
|
810
|
+
}
|
|
811
|
+
function normalizeSlideContent(raw, index) {
|
|
806
812
|
const source = (raw !== null && typeof raw === 'object') ? raw : {}
|
|
807
813
|
const layout = SLIDE_LAYOUTS.has(source.layout) ? source.layout : source.chart ? 'chart' : source.image ? 'image-right' : 'bullets'
|
|
808
814
|
const title = stripInlineMarkdown(source.title ?? '')
|
|
@@ -952,6 +958,7 @@ export function commitDeckArtifacts(artifacts) {
|
|
|
952
958
|
}
|
|
953
959
|
|
|
954
960
|
export function buildDeck(options = {}) {
|
|
961
|
+
if(options.dataModel!==undefined)throw new Error('dsh-ppt:数据绑定请使用 deck-advanced.mjs 的 buildDeckAsync / Data models require buildDeckAsync from deck-advanced.mjs')
|
|
955
962
|
if (options.brand || options.template || options.slides?.some(slide => MEDIA_LAYOUTS.has(slide.layout) || slide.image || slide.chart)) {
|
|
956
963
|
throw new Error('dsh-ppt:图片、图表、模板与品牌请使用异步 buildDeckAsync 或 ppt_create / CLI')
|
|
957
964
|
}
|
|
@@ -1024,6 +1031,7 @@ body.motion .bullets li{
|
|
|
1024
1031
|
const themeLabel = t.name[lang.id] ?? t.name.en
|
|
1025
1032
|
const total = manifest.slides.length
|
|
1026
1033
|
const delivery = renderDelivery(manifest, files, lang.id)
|
|
1034
|
+
const dataView = renderDataView(manifest, t)
|
|
1027
1035
|
|
|
1028
1036
|
return `<!DOCTYPE html>
|
|
1029
1037
|
<html lang="${lang.attr}">
|
|
@@ -1051,7 +1059,8 @@ body{
|
|
|
1051
1059
|
-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility;
|
|
1052
1060
|
}
|
|
1053
1061
|
#stage{position:fixed;inset:0}
|
|
1054
|
-
.slide-frame{position:fixed;inset:0}
|
|
1062
|
+
.slide-frame{position:fixed;inset:0;pointer-events:none}
|
|
1063
|
+
.slide-frame.is-current,body.overview .slide-frame{pointer-events:auto}
|
|
1055
1064
|
.slide{
|
|
1056
1065
|
position:absolute;inset:0;display:none;flex-direction:column;justify-content:center;
|
|
1057
1066
|
padding:clamp(34px,7vw,110px);overflow:hidden;
|
|
@@ -1066,6 +1075,7 @@ body{
|
|
|
1066
1075
|
.slide.is-active{display:flex}
|
|
1067
1076
|
${motionCss}
|
|
1068
1077
|
${MEDIA_CSS}
|
|
1078
|
+
${VISUAL_CSS}
|
|
1069
1079
|
.kicker{
|
|
1070
1080
|
color:var(--accent);font-weight:700;letter-spacing:.18em;text-transform:uppercase;
|
|
1071
1081
|
font-size:clamp(12px,1.3vw,18px);margin-bottom:22px;
|
|
@@ -1236,11 +1246,13 @@ body.presenting #hud:hover{opacity:1;pointer-events:auto}
|
|
|
1236
1246
|
#progress,#hud,#notes-panel,#help-panel,#toast{display:none !important}
|
|
1237
1247
|
}
|
|
1238
1248
|
${delivery.css}
|
|
1249
|
+
${dataView.css}
|
|
1239
1250
|
</style>
|
|
1240
1251
|
</head>
|
|
1241
1252
|
<body class="${motion ? 'motion' : 'no-motion'}">
|
|
1242
1253
|
<div id="progress" aria-hidden="true"></div>
|
|
1243
1254
|
${delivery.body}
|
|
1255
|
+
${dataView.body}
|
|
1244
1256
|
<div id="stage">
|
|
1245
1257
|
${slides}
|
|
1246
1258
|
</div>
|
|
@@ -1650,10 +1662,12 @@ ${slides}
|
|
|
1650
1662
|
window.addEventListener('beforeunload', closePresenter);
|
|
1651
1663
|
|
|
1652
1664
|
${delivery.script}
|
|
1665
|
+
window.addEventListener('dsh-data-change', () => { syncNotes(); if (presenterOpen()) sendInit(); updatePresenter(); });
|
|
1653
1666
|
const start = Number.parseInt(location.hash?.replace('#slide-', ''), 10);
|
|
1654
1667
|
go(Number.isInteger(start) ? start - 1 : 0);
|
|
1655
1668
|
})();
|
|
1656
1669
|
</script>
|
|
1670
|
+
${dataView.script}
|
|
1657
1671
|
</body>
|
|
1658
1672
|
</html>`
|
|
1659
1673
|
}
|
|
@@ -1725,7 +1739,8 @@ function renderHtmlSlide(slide, index, ui, langId, manifest = {}, theme) {
|
|
|
1725
1739
|
const notesAttr = typeof slide.notes === 'string' && slide.notes.trim() !== ''
|
|
1726
1740
|
? ' data-notes="' + escapeHtml(slide.notes) + '"'
|
|
1727
1741
|
: ''
|
|
1728
|
-
|
|
1742
|
+
const visualStyle = visualHtmlStyle(slide.visual)
|
|
1743
|
+
return '<section class="slide slide--' + escapeHtml(slide.layout || 'bullets') + '" data-index="' + number + '"' + notesAttr + (visualStyle ? ' style="' + escapeHtml(visualStyle) + '"' : '') + '>' +
|
|
1729
1744
|
'<div class="slide-inner">' + inner + '</div>' +
|
|
1730
1745
|
(manifest.brand?.logoAssetId ? '<img class="brand-logo" src="' + escapeHtml(manifest.assets?.[manifest.brand.logoAssetId]?.data ?? '') + '" alt="' + escapeHtml(manifest.brand.name || 'Logo') + '"/>' : '') +
|
|
1731
1746
|
(manifest.brand?.footer ? '<div class="brand-footer">' + escapeHtml(manifest.brand.footer) + '</div>' : '') + '</section>'
|
|
@@ -1977,7 +1992,7 @@ function slideShapeList(slide, index, total, theme, langId) {
|
|
|
1977
1992
|
para(footer, { size: 1000, color: p.muted, align: 'r', font: theme.fonts.body }),
|
|
1978
1993
|
]))
|
|
1979
1994
|
|
|
1980
|
-
return shapes.join('')
|
|
1995
|
+
return visualShapeXml(shapes.join(''), slide.visual)
|
|
1981
1996
|
}
|
|
1982
1997
|
|
|
1983
1998
|
/**
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/** Shared Node/browser arithmetic. No eval, property access, assignments or I/O. */
|
|
2
|
+
export function createDataMath() {
|
|
3
|
+
const functions = {
|
|
4
|
+
min: values => Math.min(...values), max: values => Math.max(...values),
|
|
5
|
+
sum: values => values.reduce((a, b) => a + b, 0), abs: values => Math.abs(values[0]),
|
|
6
|
+
floor: values => Math.floor(values[0]), ceil: values => Math.ceil(values[0]),
|
|
7
|
+
round: values => {
|
|
8
|
+
const digits = values[1] ?? 0;
|
|
9
|
+
if (!Number.isInteger(digits) || digits < 0 || digits > 6) throw new Error('round digits: 0–6');
|
|
10
|
+
const scale = 10 ** digits; return Math.round((values[0] + Number.EPSILON) * scale) / scale;
|
|
11
|
+
},
|
|
12
|
+
};
|
|
13
|
+
function finite(value) {
|
|
14
|
+
if (!Number.isFinite(value) || Math.abs(value) > 1e15) throw new Error('Result must be finite and within ±1e15');
|
|
15
|
+
return Object.is(value, -0) ? 0 : value;
|
|
16
|
+
}
|
|
17
|
+
function inspect(ast, known) {
|
|
18
|
+
const dependencies = new Set(); let nodes = 0;
|
|
19
|
+
function visit(node, depth = 0) {
|
|
20
|
+
if (!node || ++nodes > 256 || depth > 32) throw new Error('Formula exceeds its complexity limit');
|
|
21
|
+
if (node.type === 'Literal' && typeof node.value === 'number') { finite(node.value); return; }
|
|
22
|
+
if (node.type === 'Identifier') {
|
|
23
|
+
if (!known.has(node.name)) throw new Error('Unknown metric: ' + node.name);
|
|
24
|
+
dependencies.add(node.name); return;
|
|
25
|
+
}
|
|
26
|
+
if (node.type === 'UnaryExpression' && ['+', '-'].includes(node.operator)) { visit(node.argument, depth + 1); return; }
|
|
27
|
+
if (node.type === 'BinaryExpression' && ['+', '-', '*', '/', '%', '**'].includes(node.operator)) {
|
|
28
|
+
visit(node.left, depth + 1); visit(node.right, depth + 1); return;
|
|
29
|
+
}
|
|
30
|
+
if (node.type === 'CallExpression' && node.callee?.type === 'Identifier' && Object.hasOwn(functions, node.callee.name.toLowerCase())) {
|
|
31
|
+
const name = node.callee.name.toLowerCase(), args = node.arguments;
|
|
32
|
+
if (!Array.isArray(args) || args.length < 1 || args.length > 16 || ['abs', 'floor', 'ceil'].includes(name) && args.length !== 1 || name === 'round' && args.length > 2) throw new Error('Invalid function arguments');
|
|
33
|
+
args.forEach(arg => visit(arg, depth + 1)); return;
|
|
34
|
+
}
|
|
35
|
+
throw new Error('Only arithmetic and min/max/sum/abs/floor/ceil/round are supported');
|
|
36
|
+
}
|
|
37
|
+
visit(ast); return [...dependencies];
|
|
38
|
+
}
|
|
39
|
+
function evaluate(ast, lookup) {
|
|
40
|
+
function visit(node) {
|
|
41
|
+
if (node.type === 'Literal') return finite(node.value);
|
|
42
|
+
if (node.type === 'Identifier') return finite(lookup(node.name));
|
|
43
|
+
if (node.type === 'UnaryExpression') return finite((node.operator === '-' ? -1 : 1) * visit(node.argument));
|
|
44
|
+
if (node.type === 'CallExpression') return finite(functions[node.callee.name.toLowerCase()](node.arguments.map(visit)));
|
|
45
|
+
const left = visit(node.left), right = visit(node.right);
|
|
46
|
+
if (['/', '%'].includes(node.operator) && right === 0) throw new Error('Division by zero');
|
|
47
|
+
return finite(({ '+': () => left + right, '-': () => left - right, '*': () => left * right,
|
|
48
|
+
'/': () => left / right, '%': () => left % right, '**': () => left ** right })[node.operator]());
|
|
49
|
+
}
|
|
50
|
+
return visit(ast);
|
|
51
|
+
}
|
|
52
|
+
function inputValue(metric, value) {
|
|
53
|
+
if (typeof value !== 'number') throw new Error('Input must be a number');
|
|
54
|
+
finite(value);
|
|
55
|
+
if (value < metric.min || value > metric.max || Math.abs((value - metric.min) / metric.step - Math.round((value - metric.min) / metric.step)) > 1e-6) throw new Error('Input outside range or step: ' + metric.id);
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
function solve(metrics, overrides = {}) {
|
|
59
|
+
const byId = new Map(metrics.map(m => [m.id, m])), values = new Map(), visiting = new Set();
|
|
60
|
+
for (const key of Object.keys(overrides)) if (byId.get(key)?.kind !== 'input') throw new Error('Only declared assumptions can change: ' + key);
|
|
61
|
+
function value(id) {
|
|
62
|
+
if (values.has(id)) return values.get(id);
|
|
63
|
+
const metric = byId.get(id); if (!metric) throw new Error('Unknown metric: ' + id);
|
|
64
|
+
if (visiting.has(id) || visiting.size >= 40) throw new Error('Cyclic or excessively deep formula: ' + id);
|
|
65
|
+
visiting.add(id);
|
|
66
|
+
const result = metric.kind === 'formula' ? evaluate(metric.ast, value) : metric.kind === 'input' ? inputValue(metric, Object.hasOwn(overrides, id) ? overrides[id] : metric.value) : finite(metric.value);
|
|
67
|
+
visiting.delete(id); values.set(id, result); return result;
|
|
68
|
+
}
|
|
69
|
+
metrics.forEach(m => value(m.id)); return Object.fromEntries(values);
|
|
70
|
+
}
|
|
71
|
+
function format(value, metric, language = 'zh') {
|
|
72
|
+
const style = metric.format?.style || 'number', digits = metric.format?.digits ?? 2;
|
|
73
|
+
return new Intl.NumberFormat(language === 'en' ? 'en-US' : 'zh-CN', { style:style==='number'?'decimal':style, minimumFractionDigits: digits, maximumFractionDigits: digits }).format(value) + (metric.format?.unit || '');
|
|
74
|
+
}
|
|
75
|
+
return { inspect, solve, format, finite, inputValue };
|
|
76
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { createDataMath } from './deck-data-math.mjs'
|
|
2
|
+
import { chartColors, renderChartSvg } from './deck-media.mjs'
|
|
3
|
+
|
|
4
|
+
/** Only referenced excerpts and arithmetic enter the offline HTML, not full sources. */
|
|
5
|
+
export function renderDataView(manifest, theme) {
|
|
6
|
+
if (!manifest.dataModel) return { css: '', body: '', script: '' }
|
|
7
|
+
const model = manifest.dataModel
|
|
8
|
+
const payload = { metrics:model.metrics.map(({source,...m})=>m),values:model.values,fingerprint:model.fingerprint,
|
|
9
|
+
deckId:manifest.deckId,revision:manifest.revision,language:manifest.language,theme,
|
|
10
|
+
slides:manifest.slides.map((s,i)=>({id:s.id,page:i+1,template:s.dataTemplate||{},chart:s.chart})) }
|
|
11
|
+
const json=JSON.stringify(payload).replace(/</g,'\\u003c').replace(/\u2028/g,'\\u2028').replace(/\u2029/g,'\\u2029')
|
|
12
|
+
return { css: DATA_CSS,body:'<dialog id="data-panel" aria-labelledby="data-title"></dialog>',
|
|
13
|
+
script:`<script>(()=>{const esc=value=>String(value??'').replaceAll('&','&').replaceAll('<','<').replaceAll('>','>').replaceAll('"','"').replaceAll("'",''');const chartColors=${chartColors.toString()};const chart=${renderChartSvg.toString()};(${initDataView.toString()})(${json},(${createDataMath.toString()})(),chart);})();</script>` }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Embedded verbatim. All material text is written with DOM text APIs. */
|
|
17
|
+
function initDataView(data, math, chartRenderer) {
|
|
18
|
+
const en=data.language==='en',L=(zh,english)=>en?english:zh,byId=new Map(data.metrics.map(m=>[m.id,m]));
|
|
19
|
+
const panel=document.getElementById('data-panel'),controls=[],baseline=Object.fromEntries(data.metrics.filter(m=>m.kind==='input').map(m=>[m.id,m.value]));
|
|
20
|
+
let parameters={...baseline},values=math.solve(data.metrics),valid=true,dirty=false,selection=data.metrics[0]?.id;
|
|
21
|
+
for(const metric of data.metrics)if(metric.ast)math.inspect(metric.ast,new Set(byId.keys()));
|
|
22
|
+
function el(tag,text,parent,attributes={}){const node=document.createElement(tag);if(text!==undefined)node.textContent=text;for(const[key,value]of Object.entries(attributes))node.setAttribute(key,String(value));if(parent)parent.append(node);return node;}
|
|
23
|
+
function button(text,parent,click){const node=el('button',text,parent,{type:'button'});node.addEventListener('click',event=>{event.stopPropagation();click(event);});return node;}
|
|
24
|
+
const header=el('div',undefined,panel,{class:'data-head'});el('h2',L('数字溯源与现场推演','Data lineage and what-if'),header,{id:'data-title'});button(L('关闭','Close'),header,()=>panel.close());
|
|
25
|
+
el('p',L('来源表示数字如何得到,不代表事实已核验。推演参数均为用户假设。','Lineage explains how numbers were obtained, not whether they are true. Adjustable parameters are assumptions.'),panel,{class:'data-muted'});
|
|
26
|
+
const notice=el('div','',panel,{role:'status',class:'data-notice'}),error=el('div','',panel,{role:'alert',class:'data-error'});error.hidden=true;
|
|
27
|
+
const scenario=el('section',undefined,panel);el('h3',L('现场推演','What-if assumptions'),scenario);
|
|
28
|
+
for(const metric of data.metrics.filter(m=>m.kind==='input')){
|
|
29
|
+
const row=el('div',undefined,scenario,{class:'data-control'}),label=el('label',metric.label,row,{for:'data-input-'+metric.id}),formatted=el('output','',label);
|
|
30
|
+
const range=el('input',undefined,row,{type:'range',min:metric.min,max:metric.max,step:metric.step,value:metric.value,'aria-label':metric.label+' '+L('滑杆','slider')}),number=el('input',undefined,row,{type:'number',id:'data-input-'+metric.id,min:metric.min,max:metric.max,step:metric.step,value:metric.value});
|
|
31
|
+
controls.push({metric,range,number,formatted});
|
|
32
|
+
function change(event){const raw=event.target.value;const next={...parameters,[metric.id]:raw===''?NaN:Number(raw)};update(next);}
|
|
33
|
+
range.addEventListener('input',change);number.addEventListener('input',change);
|
|
34
|
+
if(metric.note)el('p',metric.note,row,{class:'data-muted'});
|
|
35
|
+
}
|
|
36
|
+
if(!controls.length)el('p',L('本工程没有可调假设,原始事实不会被滑杆修改。','No adjustable assumptions. Source facts cannot be changed with sliders.'),scenario);
|
|
37
|
+
const actions=el('div',undefined,scenario,{class:'data-actions'});button(L('恢复已保存参数','Reset to saved values'),actions,()=>update({...baseline}));
|
|
38
|
+
const save=button(L('保存推演参数','Save scenario parameters'),actions,()=>download('scenario.json',JSON.stringify({schemaVersion:1,deckId:data.deckId,revision:data.revision,fingerprint:data.fingerprint,parameters},null,2),'application/json'));
|
|
39
|
+
if(window.parent!==window){save.disabled=true;save.title=L('在 DSH 工作台中确认并保存静态 PPTX','Confirm and save the static PPTX in the DSH workbench');}
|
|
40
|
+
el('p',L('HTML 可离线推演。要生成对应的可编辑 PPTX,请在 DSH 工作台导入参数并确认保存。未保存推演时,旧 PPTX 的下载会暂缓。','HTML supports offline what-if. Import saved parameters into the DSH workbench and confirm to create the matching editable PPTX. Older PPTX downloads are blocked while values are unsaved.'),scenario,{class:'data-muted'});
|
|
41
|
+
el('h3',L('追问数字出处','Inspect a number'),panel);
|
|
42
|
+
const chooser=el('select',undefined,panel,{'aria-label':L('溯源指标','Trace metric')});data.metrics.forEach(m=>el('option',m.label,chooser,{value:m.id}));chooser.addEventListener('change',()=>{selection=chooser.value;showEvidence();});
|
|
43
|
+
const evidence=el('section',undefined,panel,{class:'data-evidence'});
|
|
44
|
+
const toggle=button(L('数字来源 / 推演','Sources / what-if'),document.getElementById('delivery-bar'),()=>open());toggle.id='data-toggle';
|
|
45
|
+
function open(id,missing){if(id&&byId.has(id)){selection=id;chooser.value=id;}showEvidence(missing);if(!panel.open)panel.showModal();if(id||missing)evidence.scrollIntoView({block:'nearest'});}
|
|
46
|
+
function showEvidence(missing){
|
|
47
|
+
evidence.replaceChildren();
|
|
48
|
+
if(missing){el('h3',L('此数字未关联原始材料','This number has no linked source'),evidence);el('p',L('请在 DSH 中提供来源,并用指标绑定替换固定数字。不能将相同数值自动当作同一来源。','Provide the source in DSH and bind a metric. Matching numeric values alone do not establish a common source.'),evidence);return;}
|
|
49
|
+
const metric=byId.get(selection);if(!metric)return;
|
|
50
|
+
el('h3',metric.label+' = '+math.format(values[metric.id],metric,data.language),evidence);
|
|
51
|
+
if(metric.kind==='source'){
|
|
52
|
+
el('strong',metric.evidence.name+' · '+metric.evidence.locator,evidence);el('pre',metric.evidence.excerpt,evidence);
|
|
53
|
+
const more=el('details',undefined,evidence);el('summary',L('来源快照校验值','Source snapshot checksum'),more);el('code','SHA-256: '+metric.evidence.sha256,more);
|
|
54
|
+
}else if(metric.kind==='input')el('p',L('用户假设;不是从源材料证明的事实。','User assumption, not a fact established by source material.')+(metric.note?' '+metric.note:''),evidence);
|
|
55
|
+
else{
|
|
56
|
+
el('pre','= '+metric.formula,evidence);el('p',L('计算输入(点击继续追问):','Inputs (click to trace further):'),evidence);
|
|
57
|
+
for(const id of metric.dependencies){const dependency=byId.get(id);button(dependency.label+' = '+math.format(values[id],dependency,data.language),evidence,()=>open(id));}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function fragment(template){
|
|
61
|
+
const result=document.createDocumentFragment(),pattern=/\{\{([A-Za-z][A-Za-z0-9]*)\}\}/g;let end=0;
|
|
62
|
+
for(const match of template.matchAll(pattern)){result.append(document.createTextNode(template.slice(end,match.index)));const metric=byId.get(match[1]);const number=el('button',math.format(values[metric.id],metric,data.language),result,{type:'button',class:'data-number','data-metric':metric.id,title:L('查看数字出处','Inspect source')});end=match.index+match[0].length;}
|
|
63
|
+
result.append(document.createTextNode(template.slice(end)));return result;
|
|
64
|
+
}
|
|
65
|
+
function fill(node,template){if(node&&typeof template==='string')node.replaceChildren(fragment(template));}
|
|
66
|
+
function graphFor(template,solved){const graph=structuredClone(template),text=value=>typeof value==='string'?value.replace(/\{\{([A-Za-z][A-Za-z0-9]*)\}\}/g,(_,id)=>math.format(solved[id],byId.get(id),data.language)):value;graph.categories=graph.categories.map(text);graph.series=graph.series.map(s=>({...s,name:text(s.name),values:s.values.map(v=>typeof v==='string'&&/^\{\{[A-Za-z][A-Za-z0-9]*\}\}$/.test(v)?solved[v.slice(2,-2)]:Number(v))}));graph.unit=text(graph.unit);graph.caption=text(graph.caption);if(graph.kind==='pie'&&(graph.series[0].values.some(v=>v<0)||graph.series[0].values.reduce((a,b)=>a+b,0)<=0))throw new Error(L('饼图数值需非负且总和大于零','Pie values must be non-negative with a positive total'));return graph;}
|
|
67
|
+
function missingNumbers(root){
|
|
68
|
+
const targets=root.querySelectorAll('h1,h2,.statement-title,.quote-text,.subtitle,.quote-attr,.deck-table th,.deck-table td,li,.media-body p,.media-caption');
|
|
69
|
+
const texts=[];for(const target of targets){const walker=document.createTreeWalker(target,NodeFilter.SHOW_TEXT);while(walker.nextNode()){const node=walker.currentNode;if(node.parentElement?.closest('.data-number,svg,.chart-data'))continue;texts.push(node);}}
|
|
70
|
+
for(const node of new Set(texts)){const pattern=/[-+]?(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?[%%]?/g,content=node.textContent,matches=[...content.matchAll(pattern)];if(!matches.length)continue;const output=document.createDocumentFragment();let end=0;for(const match of matches){output.append(document.createTextNode(content.slice(end,match.index)));el('button',match[0],output,{type:'button',class:'data-number data-unlinked','data-unlinked':'1',title:L('未关联来源','Source not linked')});end=match.index+match[0].length;}output.append(document.createTextNode(content.slice(end)));node.replaceWith(output);}
|
|
71
|
+
}
|
|
72
|
+
function redraw(){
|
|
73
|
+
for(const slide of data.slides){const root=document.querySelectorAll('.slide')[slide.page-1];if(!root)continue;const template=slide.template;
|
|
74
|
+
fill(root.querySelector('.media-title,h1,h2,.statement-title,.quote-text'),template.title);
|
|
75
|
+
fill(root.querySelector('.subtitle,.quote-attr,.media-body > p'),template.subtitle);fill(root.querySelector('.kicker'),template.kicker);
|
|
76
|
+
if(template.bullets)root.querySelectorAll('li').forEach((li,i)=>fill(li,template.bullets[i]));
|
|
77
|
+
if(template.rows)root.querySelectorAll('.deck-table tr').forEach((row,r)=>Array.from(row.children).forEach((cell,c)=>fill(cell,template.rows[r]?.[c])));
|
|
78
|
+
if(template.notes)root.dataset.notes=template.notes.replace(/\{\{([A-Za-z][A-Za-z0-9]*)\}\}/g,(_,id)=>math.format(values[id],byId.get(id),data.language));
|
|
79
|
+
if(template.chart){const graph=graphFor(template.chart,values),area=root.querySelector('.media-chart');if(area)area.innerHTML=chartRenderer(graph,data.theme);fill(root.querySelector('.media-caption'),template.chart.caption);}
|
|
80
|
+
if(slide.chart&&!root.querySelector('.data-chart-trace')){const link=button(L('图表数字来源','Chart sources'),root.querySelector('.media-canvas'),()=>{const id=Object.keys(template.chart||{}).length?[...JSON.stringify(template.chart).matchAll(/\{\{([A-Za-z][A-Za-z0-9]*)\}\}/g)][0]?.[1]:null;open(id,!id);});link.className='data-chart-trace';}
|
|
81
|
+
missingNumbers(root);
|
|
82
|
+
}
|
|
83
|
+
for(const {metric,range,number,formatted}of controls){range.value=String(parameters[metric.id]);number.value=String(parameters[metric.id]);formatted.textContent=' '+math.format(values[metric.id],metric,data.language);}
|
|
84
|
+
notice.textContent=dirty?L('当前为未保存推演,PPTX 尚未更新。','Unsaved what-if values. The PPTX has not been updated.'):L('当前显示已保存的静态基线;公式和假设随 PPTX 附上。','Showing saved values; formulas and assumptions accompany the PPTX.');
|
|
85
|
+
downloadState();
|
|
86
|
+
showEvidence();window.dispatchEvent(new Event('dsh-data-change'));
|
|
87
|
+
}
|
|
88
|
+
function downloadState(){save.disabled=window.parent!==window||!valid;document.querySelectorAll('a[download]').forEach(link=>{if(/\.(?:pptx|json)(?:[?#]|$)/i.test(link.href)){if(dirty||!valid)link.setAttribute('aria-disabled','true');else link.removeAttribute('aria-disabled');}});}
|
|
89
|
+
function notifyState(){window.__dshData.onChange?.({...parameters},dirty,valid);}
|
|
90
|
+
function update(next,notify=true){
|
|
91
|
+
try{const complete={...baseline,...next},solved=math.solve(data.metrics,complete);for(const slide of data.slides)if(slide.template.chart)graphFor(slide.template.chart,solved);parameters=complete;values=solved;valid=true;dirty=Object.keys(baseline).some(id=>parameters[id]!==baseline[id]);error.hidden=true;redraw();if(notify)notifyState();return true;}
|
|
92
|
+
catch(reason){valid=false;error.hidden=false;error.textContent=L('无法计算,请检查数值或恢复已保存参数:','Cannot calculate. Check values or reset: ')+reason.message;downloadState();if(notify)notifyState();return false;}
|
|
93
|
+
}
|
|
94
|
+
function download(name,text,type){if(!valid)return;const url=URL.createObjectURL(new Blob([text],{type})),link=document.createElement('a');link.href=url;link.download=name;document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);}
|
|
95
|
+
document.getElementById('stage').addEventListener('click',event=>{const target=event.target.closest('[data-metric],[data-unlinked]');if(target){event.preventDefault();event.stopImmediatePropagation();open(target.dataset.metric,!!target.dataset.unlinked);}},true);
|
|
96
|
+
document.addEventListener('click',event=>{const link=event.target.closest('a[download]');if(link&&/\.(?:pptx|json)(?:[?#]|$)/i.test(link.href)&&(dirty||!valid)){event.preventDefault();event.stopImmediatePropagation();open();}},true);
|
|
97
|
+
panel.addEventListener('keydown',event=>event.stopPropagation());
|
|
98
|
+
for(const name of ['wheel','touchstart','touchend'])panel.addEventListener(name,event=>event.stopPropagation(),{passive:true});
|
|
99
|
+
document.addEventListener('keydown',event=>{if(event.key.toLowerCase()==='d'&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!event.target.closest('input,textarea,select')){event.preventDefault();open();}});
|
|
100
|
+
window.__dshData={getState:()=>({schemaVersion:1,deckId:data.deckId,revision:data.revision,fingerprint:data.fingerprint,parameters:{...parameters},dirty,valid}),setParameters:next=>update(next,false),onChange:null};redraw();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const DATA_CSS=`
|
|
104
|
+
.data-number{font:inherit!important;line-height:inherit!important;color:inherit!important;background:transparent!important;border:0!important;border-bottom:2px dotted var(--accent)!important;border-radius:0!important;padding:0!important;cursor:pointer;display:inline;white-space:inherit;letter-spacing:inherit}.data-number.data-unlinked{border-bottom-color:var(--muted)!important}
|
|
105
|
+
.data-chart-trace{position:absolute;right:6.4%;top:18%;font:12px var(--font-body);border:1px solid var(--muted);border-radius:9px;padding:6px 9px;background:var(--panel);color:var(--fg);cursor:pointer}
|
|
106
|
+
#data-panel{background:var(--panel);color:var(--fg);border:1px solid var(--muted);border-radius:18px;width:min(700px,calc(100vw - 24px));max-height:88vh;padding:24px;overflow:auto;font:15px/1.6 var(--font-body)}#data-panel::backdrop{background:#0009}
|
|
107
|
+
#data-panel h2{font-size:23px;margin:0;max-width:none}#data-panel h3{font-size:17px;margin:20px 0 8px}#data-panel p{font-size:14px}.data-head,.data-actions{display:flex;gap:10px;align-items:center;justify-content:space-between;flex-wrap:wrap}
|
|
108
|
+
#data-panel button,#data-panel select,#data-panel input[type=number]{font:inherit;background:var(--bg);color:var(--fg);border:1px solid var(--muted);border-radius:9px;padding:8px 11px}#data-panel button{cursor:pointer}#data-panel button:disabled{opacity:.45;cursor:default}#data-panel select{width:100%}
|
|
109
|
+
.data-muted{color:var(--muted)}.data-control{display:grid;grid-template-columns:minmax(0,1fr) 115px;gap:8px;margin:14px 0}.data-control label{grid-column:1/-1}.data-control p{grid-column:1/-1;margin:0}.data-control input{min-width:0;width:100%;accent-color:var(--accent)}.data-control output{font-variant-numeric:tabular-nums;color:var(--accent)}
|
|
110
|
+
.data-notice,.data-error{padding:10px 12px;border:1px solid var(--muted);border-radius:9px;margin:12px 0}.data-error{color:#e67878}.data-evidence pre,.data-evidence code{font:inherit;white-space:pre-wrap;overflow-wrap:anywhere}.data-evidence button{display:block;margin:7px 0;text-align:left}
|
|
111
|
+
a[aria-disabled=true]{opacity:.5;cursor:not-allowed}@media(max-width:640px){#data-panel{padding:16px}.data-control{grid-template-columns:minmax(0,1fr) 105px}#delivery-bar{flex-wrap:wrap;row-gap:5px}#delivery-bar button,#delivery-bar a{font-size:12px;padding:7px 9px}}
|
|
112
|
+
@media print{#data-panel,.data-chart-trace{display:none!important}.data-number{border:0!important}}
|
|
113
|
+
`
|