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,190 @@
|
|
|
1
|
+
/** Data provenance and explicit what-if assumptions. File imports occur only in tool calls. */
|
|
2
|
+
import { createRequire } from 'node:module'
|
|
3
|
+
import { readFileSync, lstatSync } from 'node:fs'
|
|
4
|
+
import { basename, resolve, extname } from 'node:path'
|
|
5
|
+
import { createHash } from 'node:crypto'
|
|
6
|
+
import { createDataMath } from './deck-data-math.mjs'
|
|
7
|
+
|
|
8
|
+
const math = createDataMath(), MAX_BYTES = 1024 * 1024
|
|
9
|
+
const require = createRequire(import.meta.url)
|
|
10
|
+
function parser(name) { try { return require(name) } catch(error) { if(error.code==='MODULE_NOT_FOUND')fail('数据绑定需安装技能目录的依赖:npm install --ignore-scripts','Data binding requires skill dependencies: npm install --ignore-scripts');throw error } }
|
|
11
|
+
const identifier = value => typeof value === 'string' && /^[A-Za-z][A-Za-z0-9]{0,47}$/.test(value) && !['constructor','prototype','eval','Function','Math','process','window','globalThis'].includes(value)
|
|
12
|
+
const clone = value => structuredClone(value)
|
|
13
|
+
const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex')
|
|
14
|
+
const fail = (zh, en) => { throw new Error('dsh-ppt:' + zh + ' / ' + en) }
|
|
15
|
+
const token = /\{\{([A-Za-z][A-Za-z0-9]*)\}\}/g
|
|
16
|
+
const fields = ['title','subtitle','kicker','text','bullets','rows','notes','chart']
|
|
17
|
+
const numericPattern = /[-+]?(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?[%%]?/g
|
|
18
|
+
export const dataFingerprint = model => digest({ sources: model.sources, metrics: model.metrics.map(({ ast, dependencies, evidence, ...m }) => m) })
|
|
19
|
+
|
|
20
|
+
function boundedString(value, cap, label) {
|
|
21
|
+
if (typeof value !== 'string' || value.length > cap) fail(label + '过长或无效', 'Invalid or oversized ' + label)
|
|
22
|
+
return value
|
|
23
|
+
}
|
|
24
|
+
function sourceInput(input, cwd, allowFiles) {
|
|
25
|
+
if (!input || !identifier(input.id)) fail('数据源 ID 请使用字母开头的字母和数字', 'Source IDs must use letters and digits')
|
|
26
|
+
let format = input.format, content = input.content, name = input.name || input.id
|
|
27
|
+
if(format!==undefined&&!['csv','tsv','text'].includes(format)||input.kind!==undefined&&!['table','text'].includes(input.kind))fail('来源格式需为 CSV、TSV 或文本','Source format must be CSV, TSV or text')
|
|
28
|
+
if (input.path !== undefined) {
|
|
29
|
+
if (!allowFiles || typeof input.path !== 'string') fail('网页请求不能读取任意文件', 'Browser requests cannot read arbitrary files')
|
|
30
|
+
const path = resolve(cwd, input.path), stat = lstatSync(path)
|
|
31
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_BYTES) fail('源文件需为 1 MiB 内的普通文件', 'Source must be a regular file up to 1 MiB')
|
|
32
|
+
const suffix = extname(path).toLowerCase(); format ||= suffix === '.csv' ? 'csv' : suffix === '.tsv' ? 'tsv' : ['.md','.txt'].includes(suffix) ? 'text' : ''
|
|
33
|
+
if (!['csv','tsv','text'].includes(format)) fail('源文件支持 CSV、TSV、TXT 和 Markdown', 'Supported source files: CSV, TSV, TXT and Markdown')
|
|
34
|
+
content = readFileSync(path, 'utf8'); name = input.name || basename(path)
|
|
35
|
+
}
|
|
36
|
+
boundedString(String(name), 120, '数据源名称')
|
|
37
|
+
let source
|
|
38
|
+
if (format === 'csv' || format === 'tsv') {
|
|
39
|
+
boundedString(content, MAX_BYTES, '源数据')
|
|
40
|
+
const rows = parser('csv-parse/sync').parse(content, { bom: true, delimiter: format === 'tsv' ? '\t' : ',', skip_empty_lines: false, max_record_size: 100000 })
|
|
41
|
+
source = { id: input.id, name: String(name), kind: 'table', rows }
|
|
42
|
+
} else if (input.kind === 'table' || input.rows !== undefined) source = { id: input.id, name: String(name), kind: 'table', rows: clone(input.rows) }
|
|
43
|
+
else source = { id: input.id, name: String(name), kind: 'text', text: boundedString(content ?? input.text, MAX_BYTES, '材料') }
|
|
44
|
+
if (source.kind === 'table') {
|
|
45
|
+
const rows = source.rows
|
|
46
|
+
if (!Array.isArray(rows) || !rows.length || rows.length > 500 || !Array.isArray(rows[0]) || !rows[0].length || rows[0].length > 26 || rows.some(r => !Array.isArray(r) || r.length !== rows[0].length || r.some(v => !['string','number'].includes(typeof v) || typeof v === 'number' && !Number.isFinite(v) || String(v).length > 2000))) fail('表格需 1–500 行、1–26 列,行宽一致,单元格最多 2000 字符', 'Table limits: 500 rows, 26 columns, equal row widths, 2000 characters per cell')
|
|
47
|
+
}
|
|
48
|
+
source.sha256 = digest(source.kind === 'text' ? source.text : source.rows)
|
|
49
|
+
return source
|
|
50
|
+
}
|
|
51
|
+
function numeric(value) {
|
|
52
|
+
if (typeof value === 'number') return math.finite(value)
|
|
53
|
+
const text = String(value).trim()
|
|
54
|
+
if (!/^[-+]?(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?[%%]?$/.test(text)) fail('引用位置不是单个数值', 'The referenced location is not a single number')
|
|
55
|
+
return math.finite(Number(text.replaceAll(',', '').replace(/[%%]$/, '')) / (/[%%]$/.test(text) ? 100 : 1))
|
|
56
|
+
}
|
|
57
|
+
function evidenceOf(ref, sources) {
|
|
58
|
+
if (!ref || typeof ref !== 'object') fail('指标缺少来源', 'Metric source is missing')
|
|
59
|
+
const source = sources.find(s => s.id === ref.sourceId)
|
|
60
|
+
if (!source) fail('找不到数据源:' + ref.sourceId, 'Unknown source: ' + ref.sourceId)
|
|
61
|
+
let value, locator, excerpt, reference
|
|
62
|
+
if (source.kind === 'table') {
|
|
63
|
+
const cell = /^([A-Z])([1-9]\d{0,2})$/.exec(String(ref.cell || '').toUpperCase())
|
|
64
|
+
if (!cell) fail('单元格需使用 A1–Z500 地址', 'Use a cell address from A1 to Z500')
|
|
65
|
+
const row = Number(cell[2]) - 1, col = cell[1].charCodeAt(0) - 65
|
|
66
|
+
if (!source.rows[row] || col >= source.rows[row].length) fail('引用单元格超出数据源', 'Cell is outside the source table')
|
|
67
|
+
value = numeric(source.rows[row][col]); locator = cell[1] + cell[2]
|
|
68
|
+
excerpt = source.rows[row].map((c, i) => String.fromCharCode(65 + i) + ': ' + String(c)).join(' | ').slice(0,1000)
|
|
69
|
+
reference = { sourceId: source.id, cell: locator }
|
|
70
|
+
} else {
|
|
71
|
+
if (!Number.isInteger(ref.line) || ref.line < 1 || ref.line > 10000 || !Number.isInteger(ref.numberIndex ?? 0) || (ref.numberIndex ?? 0) < 0 || (ref.numberIndex ?? 0) > 100) fail('请指定材料行号与该行数值序号(从 0 开始)', 'Specify a line and zero-based numberIndex')
|
|
72
|
+
const line = source.text.split(/\r?\n/)[ref.line - 1]
|
|
73
|
+
if (line === undefined || line.length > 8000) fail('材料行不存在或超过 8000 字符', 'Source line missing or longer than 8000 characters')
|
|
74
|
+
const numbers = [...line.matchAll(numericPattern)], match = numbers[ref.numberIndex ?? 0]
|
|
75
|
+
if (!match) fail('该材料行没有指定的数值', 'Requested number not found on the source line')
|
|
76
|
+
value = numeric(match[0]); locator = 'L' + ref.line + ' #' + (Number(ref.numberIndex ?? 0) + 1); excerpt = line
|
|
77
|
+
reference = { sourceId: source.id, line: ref.line, numberIndex: ref.numberIndex ?? 0 }
|
|
78
|
+
}
|
|
79
|
+
return { value, reference, evidence: { sourceId: source.id, name: source.name, locator, excerpt, sha256: source.sha256 } }
|
|
80
|
+
}
|
|
81
|
+
export function normalizeDataModel(input, { cwd = '.', allowFiles = false } = {}) {
|
|
82
|
+
if (!input || input.schemaVersion !== undefined && input.schemaVersion !== 1 || !Array.isArray(input.sources) || input.sources.length > 8 || !Array.isArray(input.metrics) || !input.metrics.length || input.metrics.length > 80) fail('数据模型需包含最多 8 个来源和 1–80 个指标', 'Data model needs up to 8 sources and 1–80 metrics')
|
|
83
|
+
const sources = input.sources.map(s => sourceInput(s, cwd, allowFiles)), seen = new Set()
|
|
84
|
+
if (new Set(sources.map(s => s.id)).size !== sources.length || Buffer.byteLength(JSON.stringify(sources)) > MAX_BYTES) fail('数据源重复或总量超过 1 MiB', 'Duplicate sources or combined data exceeds 1 MiB')
|
|
85
|
+
const metrics = input.metrics.map(raw => {
|
|
86
|
+
if (!raw || !identifier(raw.id) || seen.has(raw.id) || !['source','input','formula'].includes(raw.kind)) fail('指标 ID 重复、无效或类型不受支持', 'Invalid, duplicate metric ID or unsupported kind')
|
|
87
|
+
seen.add(raw.id)
|
|
88
|
+
const format = raw.format || {}, style = format.style || 'number', digits = format.digits ?? 2
|
|
89
|
+
if (!['number','percent'].includes(style) || !Number.isInteger(digits) || digits < 0 || digits > 6) fail('显示格式只支持 number / percent 和 0–6 位小数', 'Use number/percent and 0–6 decimal places')
|
|
90
|
+
const metric = { id: raw.id, label: boundedString(raw.label || raw.id,120,'指标名称'), kind: raw.kind, format: { style, digits, ...(format.unit ? { unit: boundedString(format.unit,24,'单位') } : {}) }, ...(raw.note ? { note: boundedString(raw.note,1000,'假设说明') } : {}) }
|
|
91
|
+
if (raw.kind === 'source') { const result = evidenceOf(raw.source,sources); Object.assign(metric,{source:result.reference,value:result.value,evidence:result.evidence}) }
|
|
92
|
+
if (raw.kind === 'input') {
|
|
93
|
+
if ([raw.value,raw.min,raw.max,raw.step].some(v=>typeof v!=='number'||!Number.isFinite(v)||Math.abs(v)>1e15)||raw.min>=raw.max||raw.step<=0||(raw.max-raw.min)/raw.step>100000) fail('假设需提供数值、最小值、最大值和正步长(最多 100000 步)', 'Assumptions need finite value/min/max/positive step, at most 100000 steps')
|
|
94
|
+
Object.assign(metric,{value:raw.value,min:raw.min,max:raw.max,step:raw.step}); math.inputValue(metric,raw.value)
|
|
95
|
+
}
|
|
96
|
+
if (raw.kind === 'formula') { metric.formula = boundedString(raw.formula,512,'公式'); const jsep=parser('jsep');try { metric.ast = jsep(metric.formula) } catch { fail('公式无法解析:'+raw.id,'Formula cannot be parsed: '+raw.id) } }
|
|
97
|
+
return metric
|
|
98
|
+
})
|
|
99
|
+
if (metrics.filter(m=>m.kind==='input').length>12) fail('每个工程最多 12 个可调假设','At most 12 adjustable assumptions')
|
|
100
|
+
for (const metric of metrics) if (metric.ast) metric.dependencies = math.inspect(metric.ast, seen)
|
|
101
|
+
const values = math.solve(metrics)
|
|
102
|
+
return { schemaVersion:1,sources,metrics,values,fingerprint:dataFingerprint({sources,metrics}) }
|
|
103
|
+
}
|
|
104
|
+
export function substituteData(value, model, numericValue = false) {
|
|
105
|
+
if (typeof value !== 'string') return value
|
|
106
|
+
if (/\{\{|\}\}/.test(value.replace(token,''))) fail('数据占位符需使用 {{指标ID}}','Use {{metricId}} for data placeholders')
|
|
107
|
+
const match = /^\{\{([A-Za-z][A-Za-z0-9]*)\}\}$/.exec(value)
|
|
108
|
+
if (numericValue && match) {
|
|
109
|
+
if (!Object.hasOwn(model.values,match[1])) fail('未知指标:'+match[1],'Unknown metric: '+match[1])
|
|
110
|
+
return model.values[match[1]]
|
|
111
|
+
}
|
|
112
|
+
if (numericValue && value.includes('{{')) fail('图表数值需为完整的 {{指标ID}}','Chart values require an exact {{metricId}}')
|
|
113
|
+
return value.replace(token,(_,id)=>{
|
|
114
|
+
const metric=model.metrics.find(m=>m.id===id);if(!metric)fail('未知指标:'+id,'Unknown metric: '+id)
|
|
115
|
+
return math.format(model.values[id],metric)
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
function chartTemplate(chart) {
|
|
119
|
+
if (!chart || !chart.rows) return clone(chart)
|
|
120
|
+
return { ...chart, rows:undefined,categories:chart.rows.slice(1).map(r=>r[0]),series:chart.rows[0].slice(1).map((name,c)=>({name,values:chart.rows.slice(1).map(r=>r[c+1])})) }
|
|
121
|
+
}
|
|
122
|
+
export function resolveTemplate(template, model) {
|
|
123
|
+
const next=clone(template)
|
|
124
|
+
for (const key of ['title','subtitle','kicker','text','notes']) if(typeof next[key]==='string')next[key]=substituteData(next[key],model)
|
|
125
|
+
if(Array.isArray(next.bullets))next.bullets=next.bullets.map(v=>substituteData(v,model))
|
|
126
|
+
if(Array.isArray(next.rows))next.rows=next.rows.map(row=>row.map(v=>substituteData(v,model)))
|
|
127
|
+
if(next.chart){next.chart=chartTemplate(next.chart);next.chart.categories=next.chart.categories?.map(v=>substituteData(v,model));next.chart.series=next.chart.series?.map(s=>({...s,name:substituteData(s.name,model),values:s.values.map(v=>substituteData(v,model,true))}));for(const k of ['unit','caption'])if(next.chart[k])next.chart[k]=substituteData(next.chart[k],model)}
|
|
128
|
+
return next
|
|
129
|
+
}
|
|
130
|
+
function hasBinding(value){return typeof value==='string'?/\{\{[A-Za-z][A-Za-z0-9]*\}\}/.test(value):Array.isArray(value)?value.some(hasBinding):value&&typeof value==='object'?Object.values(value).some(hasBinding):false}
|
|
131
|
+
export function prepareDataSlides(rawSlides, model, normalize, language='zh') {
|
|
132
|
+
return rawSlides.flatMap(raw=>{
|
|
133
|
+
if(raw.dataTemplate && (typeof raw.dataTemplate!=='object'||Array.isArray(raw.dataTemplate)||Object.keys(raw.dataTemplate).some(key=>!fields.includes(key))))fail('数据模板只允许文本、表格和图表字段','Data templates only support text, table and chart fields')
|
|
134
|
+
const original={...raw,...raw.dataTemplate};delete original.dataTemplate
|
|
135
|
+
if(original.chart)original.chart=chartTemplate(original.chart)
|
|
136
|
+
const resolved=resolveTemplate(original,model), actual=normalize([resolved],120,language)
|
|
137
|
+
// Normalize text/table templates using the same pagination as real output.
|
|
138
|
+
// Charts are normalized with real values, then their canonical bindings restored.
|
|
139
|
+
const textTemplate={...original,...(original.chart?{chart:resolved.chart}:{})},templates=normalize([textTemplate],120,language)
|
|
140
|
+
if(templates.length!==actual.length)fail('数据绑定改变了页数,请先将表格分页','Binding changes pagination; split the table first')
|
|
141
|
+
return actual.map((slide,i)=>{
|
|
142
|
+
const candidate={...templates[i],...(original.chart?{chart:original.chart}:{})},dataTemplate={}
|
|
143
|
+
for(const key of fields)if(hasBinding(candidate[key]))dataTemplate[key]=candidate[key]
|
|
144
|
+
return {...slide,...(Object.keys(dataTemplate).length?{dataTemplate}:{})}
|
|
145
|
+
})
|
|
146
|
+
})
|
|
147
|
+
}
|
|
148
|
+
export function refreshDataSlides(slides, model, normalize, language) {
|
|
149
|
+
return slides.map(slide=>{const refreshed=prepareDataSlides([slide],model,normalize,language);if(refreshed.length!==1)fail('更新后页数发生变化,请分拆该页','Data refresh must preserve slide count');return{...refreshed[0],id:slide.id}})
|
|
150
|
+
}
|
|
151
|
+
/** Reject stale materialized values and unsafe persisted file references. */
|
|
152
|
+
export function validateDataSnapshot(manifest, normalize) {
|
|
153
|
+
if(!manifest.dataModel){if(manifest.slides.some(s=>s.dataTemplate))fail('数据模板缺少模型','Data templates require a data model');return}
|
|
154
|
+
const model=normalizeDataModel(manifest.dataModel)
|
|
155
|
+
if(JSON.stringify(model)!==JSON.stringify(manifest.dataModel))fail('数据模型快照不一致,请从原始材料重新生成','Data snapshot is inconsistent; rebuild from source material')
|
|
156
|
+
const refreshed=refreshDataSlides(manifest.slides,model,normalize,manifest.language)
|
|
157
|
+
for(let i=0;i<refreshed.length;i++)for(const key of [...fields,'dataTemplate'])if(JSON.stringify(refreshed[i][key])!==JSON.stringify(manifest.slides[i][key]))fail('第 '+(i+1)+' 页与数据绑定不一致','Slide '+(i+1)+' differs from its data bindings')
|
|
158
|
+
}
|
|
159
|
+
export function dataReferences(slide) {return [...new Set([...JSON.stringify(slide.dataTemplate||{}).matchAll(token)].map(match=>match[1]))]}
|
|
160
|
+
export function dataDependencies(model, ids) {
|
|
161
|
+
const found=new Set(),byId=new Map(model.metrics.map(m=>[m.id,m]))
|
|
162
|
+
function visit(id){if(found.has(id))return;const metric=byId.get(id);if(!metric)fail('未知指标:'+id,'Unknown metric: '+id);found.add(id);metric.dependencies?.forEach(visit)}
|
|
163
|
+
ids.forEach(visit);return model.metrics.filter(m=>found.has(m.id))
|
|
164
|
+
}
|
|
165
|
+
export function dataNotes(manifest, slide) {
|
|
166
|
+
if(!manifest.dataModel||!slide.dataTemplate)return slide.notes||''
|
|
167
|
+
const model=manifest.dataModel,en=manifest.language==='en',metrics=dataDependencies(model,dataReferences(slide))
|
|
168
|
+
const lines=[slide.notes||'',en?'--- Data and assumptions (confirmed static snapshot) ---':'--- 数据、公式与假设(已确认的静态快照) ---',...metrics.map(m=>m.label+' ['+m.id+'] = '+math.format(model.values[m.id],m,manifest.language)+'\n'+(m.kind==='formula'?'= '+m.formula:m.kind==='input'?(en?'User assumption':'用户假设')+(m.note?': '+m.note:''):m.evidence.name+' · '+m.evidence.locator+'\n'+m.evidence.excerpt+'\nSHA-256: '+m.evidence.sha256))]
|
|
169
|
+
return lines.join('\n\n')
|
|
170
|
+
}
|
|
171
|
+
export function dataReport(manifest) {
|
|
172
|
+
const en=manifest.language==='en',heading=String(manifest.title).replace(/[\r\n]/g,' '),lines=['# '+heading,en?'Data lineage and assumptions; source links are not factual verification.':'数据溯源与假设;关联到原文不代表事实已被核验。']
|
|
173
|
+
manifest.slides.forEach((slide,i)=>{if(slide.dataTemplate)lines.push('## '+(i+1)+'. '+slide.title,dataNotes(manifest,slide))})
|
|
174
|
+
return lines.join('\n\n')+'\n'
|
|
175
|
+
}
|
|
176
|
+
export function previewDataChange(manifest, options, normalize) {
|
|
177
|
+
if(!manifest.dataModel)fail('工程尚未配置数据模型','This project has no data model')
|
|
178
|
+
const raw=clone(manifest.dataModel),updates=options.sourceUpdates??[],parameters=options.parameters??{}
|
|
179
|
+
if(!Array.isArray(updates)||updates.length>8||!parameters||typeof parameters!=='object'||Array.isArray(parameters))fail('数据更新格式无效','Invalid data update')
|
|
180
|
+
const updated=new Set()
|
|
181
|
+
for(const update of updates){const index=raw.sources.findIndex(s=>s.id===update?.id);if(index<0||updated.has(update.id))fail('来源不存在或重复','Unknown or duplicate source');updated.add(update.id);const source=raw.sources[index];const next=sourceInput({...update,name:source.name},options.cwd||'.',options.allowFiles===true);if(next.kind!==source.kind)fail('替换材料需保持表格或文本类型','Keep the same source type');raw.sources[index]=next}
|
|
182
|
+
for(const [id,value]of Object.entries(parameters)){const metric=raw.metrics.find(m=>m.id===id);if(metric?.kind!=='input')fail('仅可更改明确声明的假设','Only declared assumptions can change');math.inputValue(metric,value);metric.value=value}
|
|
183
|
+
const model=normalizeDataModel(raw),slides=refreshDataSlides(manifest.slides,model,normalize,manifest.language)
|
|
184
|
+
const changes=model.metrics.filter(m=>model.values[m.id]!==manifest.dataModel.values[m.id]||JSON.stringify(m.evidence)!==JSON.stringify(manifest.dataModel.metrics.find(old=>old.id===m.id)?.evidence)).map(m=>({id:m.id,label:m.label,before:manifest.dataModel.values[m.id],after:model.values[m.id],beforeText:math.format(manifest.dataModel.values[m.id],m,manifest.language),afterText:math.format(model.values[m.id],m,manifest.language),kind:m.kind}))
|
|
185
|
+
const changedIds=new Set(changes.map(m=>m.id))
|
|
186
|
+
const affectedSlides=slides.flatMap((slide,i)=>JSON.stringify(slide)!==JSON.stringify(manifest.slides[i])||dataDependencies(model,dataReferences(slide)).some(m=>changedIds.has(m.id))?[{id:slide.id,page:i+1,title:slide.title,fields:fields.filter(key=>JSON.stringify(slide[key])!==JSON.stringify(manifest.slides[i][key])).map(key=>({field:key,before:manifest.slides[i][key]??'',after:slide[key]??''})),evidenceChanged:dataDependencies(model,dataReferences(slide)).some(m=>m.kind==='source'&&changedIds.has(m.id))}]:[])
|
|
187
|
+
// Include the full saved state, so hand edits that omit revision updates also invalidate confirmation.
|
|
188
|
+
const token=digest({state:digest(manifest),after:model.fingerprint,slides:slides.map(s=>({id:s.id,dataTemplate:s.dataTemplate}))})
|
|
189
|
+
return {model,slides,preview:{token,changes,affectedSlides,sourceChanges:[...updated],changed:model.fingerprint!==manifest.dataModel.fingerprint}}
|
|
190
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Deliberately small formatting vocabulary. Model output never contains text edits.
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
|
|
4
|
+
export function normalizeVisual(value) {
|
|
5
|
+
if (value == null) return undefined
|
|
6
|
+
if (typeof value !== 'object' || Array.isArray(value)) throw new Error('visual 需为字号设置对象 / Invalid visual settings')
|
|
7
|
+
const ranges = { titleSize: [24, 60], bodySize: [16, 28], chartLabelSize: [14, 24] }, out = {}
|
|
8
|
+
for (const [key, number] of Object.entries(value)) {
|
|
9
|
+
const range = ranges[key]
|
|
10
|
+
if (!range || !Number.isInteger(number) || number < range[0] || number > range[1]) throw new Error('visual 字号超出允许范围 / Invalid visual font size')
|
|
11
|
+
out[key] = number
|
|
12
|
+
}
|
|
13
|
+
return Object.keys(out).length ? out : undefined
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function visualHtmlStyle(value) {
|
|
17
|
+
const v = normalizeVisual(value)
|
|
18
|
+
if (!v) return ''
|
|
19
|
+
return Object.entries(v).map(([key, n]) => '--ppt-' + key + ':' + n).join(';')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const VISUAL_CSS = `
|
|
23
|
+
.slide[style*="--ppt-titleSize"] h1,.slide[style*="--ppt-titleSize"] h2,.slide[style*="--ppt-titleSize"] .statement-title,.slide[style*="--ppt-titleSize"] .quote-text{font-size:clamp(24px,calc(var(--ppt-titleSize) * .12vw),calc(var(--ppt-titleSize) * 2px))}
|
|
24
|
+
.slide[style*="--ppt-titleSize"] .media-title{font-size:calc(var(--ppt-titleSize) * .104167cqw)}
|
|
25
|
+
.slide[style*="--ppt-bodySize"] li,.slide[style*="--ppt-bodySize"] .subtitle,.slide[style*="--ppt-bodySize"] .quote-attr{font-size:clamp(16px,calc(var(--ppt-bodySize) * .13vw),calc(var(--ppt-bodySize) * 2px))}
|
|
26
|
+
.slide[style*="--ppt-bodySize"] .media-body,.slide[style*="--ppt-bodySize"] .media-body li{font-size:calc(var(--ppt-bodySize) * .104167cqw)}
|
|
27
|
+
.slide[style*="--ppt-bodySize"] .deck-table{font-size:clamp(12px,calc(var(--ppt-bodySize) * .09vw),calc(var(--ppt-bodySize) * 1.35px))}
|
|
28
|
+
.slide[style*="--ppt-chartLabelSize"] .native-chart text{font-size:calc(var(--ppt-chartLabelSize) * 1px)}
|
|
29
|
+
`
|
|
30
|
+
|
|
31
|
+
/** Apply formatting to the generator's known OOXML shapes, never arbitrary XML. */
|
|
32
|
+
export function visualShapeXml(xml, visual) {
|
|
33
|
+
const v = normalizeVisual(visual)
|
|
34
|
+
if (!v) return xml
|
|
35
|
+
return xml.replace(/<p:(sp|graphicFrame)>[\s\S]*?<\/p:\1>/g, shape => {
|
|
36
|
+
const name = shape.match(/<p:cNvPr\b[^>]*\bname="([^"]*)"/)?.[1]
|
|
37
|
+
const pt = ['Title', 'Statement', 'Quote'].includes(name) ? v.titleSize : ['Body', 'Subtitle', 'Attribution', 'Table'].includes(name) ? v.bodySize : undefined
|
|
38
|
+
return pt ? shape.replace(/(<a:(?:rPr|defRPr|endParaRPr)\b[^>]*\bsz=")[0-9]+"/g, '$1' + (pt * 100) + '"') : shape
|
|
39
|
+
})
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Facts, metrics, assets, titles and slide order are preserved by construction. */
|
|
43
|
+
export function applyVisualActions(manifest, actions) {
|
|
44
|
+
if (!Array.isArray(actions) || !actions.length || actions.length > 48) throw new Error('请选择有效的排版修改 / Invalid formatting actions')
|
|
45
|
+
const next = structuredClone(manifest), seen = new Set()
|
|
46
|
+
for (const a of actions) {
|
|
47
|
+
if (!a || typeof a !== 'object' || Object.keys(a).some(k => !['slideId', 'type', 'value'].includes(k))) throw new Error('排版操作包含无效字段 / Invalid formatting action fields')
|
|
48
|
+
const index = next.slides.findIndex(s => s.id === a.slideId), original = manifest.slides.find(s => s.id === a.slideId)
|
|
49
|
+
if (index < 0 || !original) throw new Error('排版操作关联的页面不存在 / Unknown slide')
|
|
50
|
+
const key = a.slideId + ':' + (a.type?.startsWith('split-') ? 'split' : a.type)
|
|
51
|
+
if (seen.has(key)) throw new Error('同一页的排版操作重复 / Duplicate formatting action')
|
|
52
|
+
seen.add(key)
|
|
53
|
+
const slide = next.slides[index]
|
|
54
|
+
const field = { 'title-size': 'titleSize', 'body-size': 'bodySize', 'chart-label-size': 'chartLabelSize' }[a.type]
|
|
55
|
+
if (field) {
|
|
56
|
+
if (field === 'chartLabelSize' && !slide.chart) throw new Error('本页没有图表 / Slide has no chart')
|
|
57
|
+
slide.visual = normalizeVisual({ ...slide.visual, [field]: a.value })
|
|
58
|
+
} else if (a.type === 'chart-horizontal') {
|
|
59
|
+
if (a.value !== undefined || slide.chart?.kind !== 'column') throw new Error('只支持将柱状图改为横向条形图 / Only column-to-bar conversion is supported')
|
|
60
|
+
slide.chart.kind = 'bar'
|
|
61
|
+
if (slide.dataTemplate?.chart) slide.dataTemplate.chart.kind = 'bar'
|
|
62
|
+
} else if (a.type === 'image-contain') {
|
|
63
|
+
if (a.value !== undefined || !slide.image) throw new Error('本页没有图片 / Slide has no image')
|
|
64
|
+
slide.image.fit = 'contain'
|
|
65
|
+
} else if (a.type === 'split-bullets' || a.type === 'split-table') {
|
|
66
|
+
const bullets = a.type === 'split-bullets', field = bullets ? 'bullets' : 'rows'
|
|
67
|
+
if (bullets ? !['bullets','image-left','image-right'].includes(slide.layout) : slide.layout !== 'table') throw new Error('此版式不支持所选拆页操作 / Split is not supported for this layout')
|
|
68
|
+
const data = slide[field], count = bullets ? data?.length : data?.length - 1
|
|
69
|
+
if (!Number.isInteger(a.value) || a.value < 1 || a.value >= count) throw new Error('拆页位置无效 / Invalid split position')
|
|
70
|
+
if (next.slides.length >= 120) throw new Error('拆页后超过 120 页 / Split would exceed 120 slides')
|
|
71
|
+
const added = structuredClone(slide); added.id = randomUUID()
|
|
72
|
+
const split = values => bullets ? [values.slice(0, a.value), values.slice(a.value)] : [values.slice(0, a.value + 1), [values[0], ...values.slice(a.value + 1)]]
|
|
73
|
+
;[slide[field], added[field]] = split(data)
|
|
74
|
+
if (slide.dataTemplate?.[field]) [slide.dataTemplate[field], added.dataTemplate[field]] = split(slide.dataTemplate[field])
|
|
75
|
+
next.slides.splice(index + 1, 0, added)
|
|
76
|
+
} else throw new Error('不支持此排版操作 / Unsupported formatting action')
|
|
77
|
+
}
|
|
78
|
+
return next.slides
|
|
79
|
+
}
|