dsh-ppt 0.14.0 → 0.15.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 CHANGED
@@ -4,6 +4,14 @@
4
4
 
5
5
  [历史英文记录](docs/CHANGELOG.en.md)
6
6
 
7
+ ## 0.15.0(2026-10-23)
8
+
9
+ - 新增可选数据模型:数字绑定原始材料行、CSV / TSV 单元格或受限算术公式;点击 HTML 数字逐层追问来源,未绑定数字明确提示。
10
+ - 工作台与离线 HTML 支持假设滑杆,文字、表格和图表联动;不修改来源事实。离线参数可导回 DSH,确认后生成相符的静态 PPTX。
11
+ - 来源更新和推演先显示指标、页面及字段差异,再确认保存;默认新副本保留原稿,支持撤销。旧预览、其他工程参数与外部 Office 修改受保护。
12
+ - PPTX 备注与 Markdown 报告附上来源摘录、定位、快照校验值、公式和假设。HTML 不嵌入完整材料;JSON 工程保留导入材料供后续编辑。
13
+ - 修复离线放映中隐藏页外框拦截数字点击的问题。验收范围见 [0.15.0 验证记录](docs/validation-0.15.0.md)。
14
+
7
15
  ## 0.14.0(2026-10-22)
8
16
 
9
17
  - 成品页新增按需开启的 AI 预审与人机模拟答辩,复用宿主已有模型,不影响直接交付。
package/README.en.md CHANGED
@@ -15,6 +15,7 @@ Feedback and contributions are welcome: report [issues](https://github.com/STARD
15
15
  ## What it does
16
16
 
17
17
  - Create branded decks with text, images, tables and native charts.
18
+ - Optionally trace numbers to material, CSV cells or formulas; adjust assumptions, preview affected slides, and save an undoable copy. HTML stays interactive; PPTX includes confirmed static values with formulas and assumptions. See the [data guide](docs/DATA.md#english).
18
19
  - Edit text and images in Settings, reorder, duplicate or delete slides, and undo changes.
19
20
  - Check quality and optionally render the final PPTX as images or PDF.
20
21
  - Download Markdown speaker notes with each slide's current title and notes.
package/README.md CHANGED
@@ -13,6 +13,7 @@
13
13
  ## 功能
14
14
 
15
15
  - 生成图文、表格、原生图表和品牌化演示文稿。
16
+ - 可选数字溯源与现场推演:点击数字追到原始材料、CSV 单元格或公式;调整假设、预览影响并确认保存。HTML 保留交互,PPTX 保存静态结果及公式 / 假设,见[数据说明](docs/DATA.md)。
16
17
  - 在设置页编辑文字和图片、调整顺序、复制或删除页面,并支持撤销。
17
18
  - 提供质量检查与可选的最终 PPTX 图片 / PDF 渲染。
18
19
  - 下载按页整理的 Markdown 讲稿,保留当前版本的标题与演讲备注。
package/docs/DATA.md ADDED
@@ -0,0 +1,43 @@
1
+ # 数字溯源与现场推演
2
+
3
+ 这两个功能按需启用。只需要成品时,照常给材料并下载,不必配置数据模型或开启演练。
4
+
5
+ ## 怎么用
6
+
7
+ 可以对 DSH 说:“用这份经营数据做汇报,给数字关联出处,并把增长率设为可调整的假设。”助手使用真实材料建立绑定后,打开「设置 → 演示文稿」:
8
+
9
+ 1. 点击预览中带点状下划线的数字,查看材料行、CSV 单元格或计算公式。公式中的输入可继续点开。灰色下划线表示没有关联来源,不会因数值相同自动认定来源相同。
10
+ 2. 调整「现场推演参数」中的滑杆或数值,预览文字、表格和图表的变化。只有明确声明的假设可调,原始事实保持只读。
11
+ 3. 点击「预览差异」,核对指标、受影响页面及字段的之前 / 之后。默认「保存为新副本」保留原稿,确认后才更新三件套,副本也可撤销。
12
+ 4. 来源有更新时,在「更新来源材料」选择已有来源,导入或粘贴新材料,再走同样的预览和确认流程。不会监视文件,也不会回写源文件。
13
+
14
+ 指标还没有绑定到页面时,预览会说明仅更新数据模型;来源摘录变了但数值没变,也会提示受影响页面。
15
+
16
+ ## 离线放映和静态 PPTX
17
+
18
+ 离线 HTML 保留推演面板(快捷键 D)、数字来源及公式,调整参数无需模型或网络。推演尚未保存时,旧 PPTX / JSON 的下载被暂缓。
19
+
20
+ 要交付对应的可编辑 PPTX,在 HTML 中「保存推演参数」,再回到同一 DSH 工程导入该 JSON、预览并确认保存。其他工程、旧修订的参数会被拒绝;新副本有自己的工程身份,不能继续套用原稿参数文件。
21
+
22
+ PPTX 保留确认后的静态数值及原生可编辑图表。每页的演讲备注附上该页用到的来源摘录、定位、快照校验值、公式及假设;也可单独下载 Markdown 溯源报告。它不是在 PowerPoint 中运行网页滑杆。
23
+
24
+ ## 材料与分享
25
+
26
+ 支持 UTF-8 CSV、TSV、TXT、Markdown 或内嵌表格。Excel 可先导出 CSV。本版不直接解析 XLSX,不自动联网寻找来源。
27
+
28
+ 来源只能说明“这个数字如何得到”,不代表材料真实或结论正确。JSON 工程包含导入的完整材料;HTML / PPTX 包含指标引用的材料行摘录和来源名称,摘录可能包含同一行的其他字段,分享前应核对。
29
+
30
+ 开发者示例、工具参数和范围见[数据模型参考](../skills/dsh-ppt/references/data.md)。
31
+
32
+ ## English
33
+
34
+ Both features are optional. Ordinary finished-deck delivery does not require a data model or rehearsal.
35
+
36
+ - Supply actual material and ask DSH to link its numbers and expose selected assumptions. In Settings → Presentations, click a linked number to inspect its source row, CSV cell or formula. Follow formula inputs to their origins. Unlinked numbers are labelled explicitly.
37
+ - Adjust declared assumptions; text, tables and charts change together. Source facts are read-only in what-if mode. Preview metric and slide differences before confirming. The default is an undoable new copy, preserving the original.
38
+ - Replace an existing source by importing or pasting UTF-8 CSV, TSV, TXT or Markdown. Excel tables can be exported as CSV. Nothing watches or writes the original source file; XLSX parsing and automatic online research are not included.
39
+ - Offline HTML retains controls and lineage (D opens the panel). Export scenario parameters, import them into the same DSH project, preview and confirm to create a matching static PPTX. Foreign or stale packets are rejected. Downloads of older PPTX/JSON files are blocked while the HTML has unsaved values.
40
+ - PPTX contains confirmed static values and native editable charts, with formulas, assumptions, source excerpts/locators and checksums in speaker notes. Download the Markdown lineage report separately. It does not execute HTML controls inside PowerPoint.
41
+ - A source link is not factual verification. JSON retains full imported material; HTML/PPTX include metric-referenced row excerpts, which may contain other fields from that row. Review before sharing.
42
+
43
+ See the [model reference](../skills/dsh-ppt/references/data.md) for schema, limits and tool examples.
package/docs/USAGE.en.md CHANGED
@@ -32,7 +32,7 @@ Example:
32
32
  dsh plugin --profile web add dsh-ppt
33
33
  ```
34
34
 
35
- On desktop, install `dsh-ppt` through plugin management. Restart the host after updating to load seven tools and the skill. Ask naturally to include screenshots/charts, edit only slide three, or undo the last edit; users do not need to write JSON.
35
+ On desktop, install `dsh-ppt` through plugin management. Restart the host after updating to load eight tools and the skill. Ask naturally to include screenshots/charts, edit only slide three, or undo the last edit; users do not need to write JSON. Optional `ppt_data` previews and confirms source/assumption changes; see the [data guide](DATA.md#english).
36
36
 
37
37
  ## Uninstall
38
38
 
package/docs/USAGE.md CHANGED
@@ -19,6 +19,7 @@
19
19
  | `ppt_edit` / `ppt_undo` | 修改指定页、保留其他页,支持最多 20 次历史与修订号冲突保护 |
20
20
  | `ppt_check` | 只读质量检查,定位具体页的问题;可复核当前渲染收据 |
21
21
  | `ppt_render` | 可选官方引擎生成 PNG / PDF,保留源 PPTX,报告缺失字体 |
22
+ | `ppt_data` | 可选来源更新与假设推演,先预览差异再确认保存;见[数据说明](DATA.md) |
22
23
  | 品牌 | 共享颜色、字体、Logo、页脚,同步到 HTML 与 PPTX |
23
24
  | 演讲者备注 | `<!-- 备注: ... -->` 或 `notes` 字段:HTML 按 `S` 呼出,PPTX 原生备注页(演示者视图) |
24
25
  | 动效(motion) | 默认开:HTML 页间淡入 + 要点逐条入场;PPTX 原生转场 + 要点逐条点击显现;`motion: 'off'` / `--motion off` 产出纯静态 |
@@ -39,7 +40,7 @@
39
40
  dsh plugin --profile web add dsh-ppt
40
41
  ```
41
42
 
42
- 桌面版可在插件管理中安装 `dsh-ppt`。更新后重启对应宿主,加载七个工具与 `dsh-ppt` 技能。无需手写 JSON,可直接要求 Agent「加入这两张截图和销售图表」「只修改第三页」「撤销上次修改」。
43
+ 桌面版可在插件管理中安装 `dsh-ppt`。更新后重启对应宿主,加载八个工具与 `dsh-ppt` 技能。无需手写 JSON,可直接要求 Agent「加入这两张截图和销售图表」「只修改第三页」「撤销上次修改」。
43
44
 
44
45
  ## 快速开始
45
46
 
@@ -6,6 +6,8 @@
6
6
 
7
7
  ## 最新记录
8
8
 
9
+ [0.15.0 数字溯源与推演验收](validation-0.15.0.md):自动测试、真实 DSH Web / 离线 HTML 操作、来源更新、参数回存、复制撤销、四页最终 PPTX 原生渲染及画面核对。桌面原生窗口内逐项操作另行验收。
10
+
9
11
  [0.14.0 可选 AI 预审与答辩验收](validation-0.14.0.md):151 项测试、真实 DSH Web 及原生模拟模型、复制 / 撤销 / 下载 / 取消 / 旧修订保护、中文与英文深色窄屏。真实模型效果、桌面原生窗口和完整 Office 视觉比对本次未测。
10
12
 
11
13
  [0.8.0 Windows 与浏览器操作验收](validation/0.8.0.md):113 项测试、编辑/冲突恢复、三种实际下载、五页官方引擎渲染及 390px 布局。桌面窗口内的新功能逐项操作待验收。
@@ -0,0 +1,25 @@
1
+ # 0.15.0 验证记录
2
+
3
+ 验收日期:2026-10-22–23。自动检查、真实 DSH Web、离线 HTML 和最终 PPTX 的证据分开记录。
4
+
5
+ ## 已通过
6
+
7
+ - Windows / Node 24:180 项测试,包括 29 项数据模式回归检查。覆盖 CSV / TSV、带引号与换行的单元格、材料行 / 百分比、受限算术、循环 / 除零 / 非有限值 / 范围步长、模板分页、更新差异、确认凭证与修订、外部文件改动、复制 / 撤销、浏览器路径限制、参数工程身份及导出备注。
8
+ - 普通纯文字生成在故意阻断数据解析依赖的独立进程中仍可用;启用数据绑定时缺依赖会给出安装提示。数据模式不要求模型或 API Key。
9
+ - 官方 DSH 0.2.1-rc.2 隔离 Web 宿主,通过原生 `ppt_create` 注册并生成数据工程;八个工具及技能正常加载。启动令牌交换 303、未登录 401、已登录 200。
10
+ - 实际浏览器点击数字,从利润追到收入公式,再追到 CSV 单元格;未关联数字给出明确状态。滑杆 / 数值输入、图表与文字联动、非法步长、恢复参数、旧下载拦截均检查。
11
+ - DSH 工作台实际替换 CSV:收入 1000→1200、成本 600→650,先显示指标与四页影响,再确认保存副本。原稿保留;副本撤销后恢复数据与绑定。
12
+ - 离线 HTML 实际保存参数 JSON,回 DSH 导入、预览和确认;再导入原稿参数到新副本会拒绝。下载的静态 PPTX 包含确认后的收入 1920、利润 1270,与页面结果一致。
13
+ - iframe 与外部工作台参数双向联动;非法输入立即提示,预览和下载受保护;伪造来源 / nonce 的消息被忽略。英文深色界面在 390px 下无横向溢出,内容语言保持原文。浏览器无未捕获异常。
14
+ - 最终下载的四页 PPTX 用官方 LibreOffice Kit 0.1.5 原生引擎生成 PNG / PDF,没有缺失字体;逐页查看封面、要点、原生图表及表格,核对确认数值和版式。XML / 原生备注检查包含公式、材料定位、来源校验值和假设。
15
+ - 修复并复验隐藏幻灯片外框拦截当前页点击的问题。数据面板隔离键盘、滚动和触摸事件;真实触屏设备未测。
16
+
17
+ Browser 插件在本次环境不可用,使用后台 Playwright / Chrome 访问真实 DSH Web 与本地 HTML;没有切换用户的前台窗口。
18
+
19
+ ## 范围
20
+
21
+ 桌面原生窗口中的新功能逐项点击、Microsoft PowerPoint / WPS 的实际应用渲染未测,不能由 Web 或官方 Kit 通过替代。模型效果不是本次数据功能的验收对象。
22
+
23
+ 本版不直接解析 XLSX / PDF,不监视源文件,不自动寻找或判定来源真实性。HTML / PPTX 保留引用摘录;JSON 保留完整导入材料。
24
+
25
+ 临时宿主、下载、渲染输出和截图在交付收尾中清理;仓库保留永久回归测试。npm 包、CI 与组合包安装另走发布校验,不以本地测试结果代替已发布状态。
package/lib/client.js CHANGED
@@ -235,13 +235,15 @@ function useLanguage(locale) {
235
235
  return value;
236
236
  }
237
237
  function draftFor(slide) {
238
- return { title: slide.title || '', subtitle: slide.subtitle || '', kicker: slide.kicker || '', text: slide.text || '',
239
- bullets: (slide.bullets || []).join('\n'), notes: slide.notes || '' };
238
+ const source={...slide,...slide.dataTemplate};
239
+ return { title: source.title || '', subtitle: source.subtitle || '', kicker: source.kicker || '', text: source.text || '',
240
+ bullets: (source.bullets || []).join('\n'), notes: source.notes || '' };
240
241
  }
241
242
  function editorHtml(html, nonce) {
242
243
  const bridge = `<style>#hud,#delivery-bar,#review-panel,#progress,#notes-panel,#help-panel,#toast,#blank{display:none!important}.slide-frame{pointer-events:none!important}.slide-frame .slide{pointer-events:auto!important}</style><script>(function(){const nonce=${JSON.stringify(nonce)};
243
244
  function tell(field){parent.postMessage({type:'dsh-ppt-select',nonce:nonce,field:field},'*')}
244
245
  document.addEventListener('keydown',function(e){
246
+ if(e.target.closest('#data-panel'))return;
245
247
  var mod=e.ctrlKey||e.metaKey;
246
248
  if(mod&&(e.key==='s'||e.key==='S')){e.preventDefault();e.stopImmediatePropagation();parent.postMessage({type:'dsh-ppt-shortcut',nonce:nonce,key:'save'},'*');return}
247
249
  if(e.key==='Escape'){e.preventDefault();e.stopImmediatePropagation();parent.postMessage({type:'dsh-ppt-shortcut',nonce:nonce,key:'escape'},'*');return}
@@ -251,9 +253,10 @@ function useLanguage(locale) {
251
253
  document.addEventListener('touchstart',function(e){e.stopImmediatePropagation()},true);
252
254
  document.addEventListener('touchend',function(e){e.stopImmediatePropagation()},true);
253
255
  document.addEventListener('wheel',function(e){e.stopImmediatePropagation()},{capture:true,passive:true});
254
- document.addEventListener('click',function(e){const n=e.target.closest('h1,h2,.subtitle,.kicker,.statement-title,.quote-text,.quote-attr,li');if(!n)return;
256
+ document.addEventListener('click',function(e){if(e.target.closest('#data-panel,.data-number,.data-chart-trace'))return;const n=e.target.closest('h1,h2,.subtitle,.kicker,.statement-title,.quote-text,.quote-attr,li');if(!n)return;
255
257
  e.preventDefault();e.stopImmediatePropagation();let field=n.matches('li')?'bullets':n.matches('.subtitle,.quote-attr')?'subtitle':n.matches('.kicker')?'kicker':'title';tell(field)},true);
256
- window.addEventListener('message',function(e){if(e.source!==parent||e.data?.nonce!==nonce||e.data.type!=='dsh-ppt-jump')return;window.__dshPpt?.jump(e.data.page)});
258
+ window.addEventListener('message',function(e){if(e.source!==parent||e.data?.nonce!==nonce)return;if(e.data.type==='dsh-ppt-jump')window.__dshPpt?.jump(e.data.page);if(e.data.type==='dsh-ppt-data-set'&&window.__dshData){window.__dshData.setParameters(e.data.parameters);const state=window.__dshData.getState();parent.postMessage({type:'dsh-ppt-data',nonce,parameters:e.data.parameters,valid:state.valid,command:e.data.command},'*')}});
259
+ if(window.__dshData)window.__dshData.onChange=function(parameters,dirty,valid){parent.postMessage({type:'dsh-ppt-data',nonce,parameters,dirty,valid},'*')};
257
260
  })();<\/script>`;
258
261
  const policy = `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; font-src data:; connect-src 'none'; form-action 'none'">`;
259
262
  // Presenter code contains a quoted </body>; only append at the document end.
@@ -464,10 +467,87 @@ function useLanguage(locale) {
464
467
  h('p', { className: 'muted' }, L('采纳后会生成新副本,原稿保留;副本中可“撤销上次修改”。备用页包含 AI 演练标记,请核对后再对外展示。', 'Adoption creates a copy and keeps the original. Undo last change also works in the copy. Backup slides identify AI rehearsal content; verify before presenting.'))),
465
468
  history.length > 0 && h('details', null, h('summary', null, L('本机历史记录(', 'Local history (') + history.length + L(')', ')')), h('div', { className: 'project-list' }, history.map(item => h('button', { key: item.id, disabled: busy, onClick: () => openReport(item.id) }, modeName(item.mode) + ' · ' + L('修订 ', 'Revision ') + item.revision + ' · ' + new Date(item.createdAt).toLocaleString(languageOf() === 'en' ? 'en-US' : 'zh-CN')))))));
466
469
  }
470
+ const dataCss=`.pptw .data-workbench{margin-top:18px}.pptw .data-workbench details{margin:12px 0}.pptw .data-workbench summary{cursor:pointer;font-weight:600}.pptw .data-workbench pre,.pptw .data-workbench code{white-space:pre-wrap;overflow-wrap:anywhere;font-size:13px;max-height:220px;overflow:auto}.pptw .data-input-row{margin:15px 0}.pptw .data-input-controls{display:grid;grid-template-columns:minmax(0,1fr) 115px;gap:12px;align-items:center}.pptw .data-input-controls input[type=range]{accent-color:var(--dsw-alias-brand-primary,#2563eb)}.pptw .data-before-after{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:10px}.pptw .data-before-after pre{padding:10px;border:1px solid var(--dsw-alias-divider-default,#b8c0cc);border-radius:8px}.pptw .data-copy{display:flex;gap:8px;align-items:center}.pptw .data-copy input{width:auto}@media(max-width:640px){.pptw .data-before-after{grid-template-columns:minmax(0,1fr)}.pptw .data-input-controls{grid-template-columns:minmax(0,1fr) 100px}}`;
471
+ function DataPanel({project,blocked,incoming,onParameters,onDirty,onBusy,onAdopt,onChoose,onDownload}) {
472
+ const L=(zh,en)=>languageOf()==='en'?en:zh,model=project.dataModel;
473
+ const baseline=Object.fromEntries(model.metrics.filter(m=>m.kind==='input').map(m=>[m.id,String(m.value)]));
474
+ const [parameters,setParameters]=useState(baseline),[updates,setUpdates]=useState({}),[sourceId,setSourceId]=useState(model.sources[0]?.id||'');
475
+ const [metricId,setMetricId]=useState(model.metrics[0]?.id||''),[preview,setPreview]=useState(null),[error,setError]=useState(''),[busy,setBusy]=useState(false),[valid,setValid]=useState(true),[saveAs,setSaveAs]=useState(true),[readingFile,setReadingFile]=useState(false);
476
+ const pending=useRef(null),alive=useRef(true),reading=useRef(0),latest=useRef(''),guard=useRef(false);
477
+ const numeric=Object.fromEntries(Object.entries(parameters).map(([id,value])=>[id,value.trim()===''?null:Number(value)]));
478
+ const inputsValid=model.metrics.filter(m=>m.kind==='input').every(m=>typeof numeric[m.id]==='number'&&Number.isFinite(numeric[m.id])&&numeric[m.id]>=m.min&&numeric[m.id]<=m.max&&Math.abs((numeric[m.id]-m.min)/m.step-Math.round((numeric[m.id]-m.min)/m.step))<=1e-6);
479
+ const body={parameters:numeric,sourceUpdates:Object.values(updates)},signature=JSON.stringify(body);latest.current=signature;
480
+ const changed=readingFile||!valid||Object.entries(baseline).some(([id,value])=>Number(parameters[id])!==Number(value)||parameters[id].trim()==='')||Object.keys(updates).length>0;
481
+ useEffect(()=>{onDirty(changed);return()=>onDirty(false);},[changed]);
482
+ useEffect(()=>{setPreview(null);},[signature]);
483
+ useEffect(()=>{if(incoming){setParameters(Object.fromEntries(Object.entries(incoming.parameters).map(([id,value])=>[id,Number.isFinite(value)?String(value):''])));setValid(incoming.valid!==false);}},[incoming]);
484
+ useEffect(()=>{alive.current=true;return()=>{alive.current=false;reading.current++;pending.current?.abort();onBusy(false);};},[]);
485
+ function changeParameter(id,value){const next={...parameters,[id]:value};setParameters(next);setValid(true);setPreview(null);setError('');onParameters(Object.fromEntries(Object.entries(next).map(([key,raw])=>[key,raw.trim()===''?NaN:Number(raw)])));}
486
+ function reset(){reading.current++;setParameters(baseline);setUpdates({});setPreview(null);setError('');setValid(true);onParameters(Object.fromEntries(Object.entries(baseline).map(([id,value])=>[id,Number(value)])));}
487
+ async function task(work){
488
+ if(guard.current||blocked||readingFile)return;guard.current=true;setBusy(true);onBusy(true);setError('');
489
+ const controller=new AbortController();pending.current=controller;
490
+ try{await work(controller.signal);}catch(reason){if(alive.current&&!controller.signal.aborted)setError(reason.message||L('操作失败','Operation failed'));}
491
+ finally{pending.current=null;guard.current=false;if(alive.current){setBusy(false);onBusy(false);}}
492
+ }
493
+ function inspect(){const sent=signature;return task(async signal=>{const value=await action({operation:'data-preview',id:project.id,expectedRevision:project.revision,...body},signal);if(alive.current&&latest.current===sent)setPreview({...value,signature:sent});});}
494
+ function apply(){if(!preview||preview.signature!==signature)return;const sent=signature;return task(async signal=>{const value=await action({operation:'data-apply',id:project.id,expectedRevision:project.revision,...body,confirmed:true,previewToken:preview.token,saveAs},signal);if(alive.current&&latest.current===sent){onDirty(false);onAdopt(value.project);}});}
495
+ async function importSource(event){
496
+ const file=event.target.files?.[0];event.target.value='';if(!file)return;const stamp=++reading.current,target=sourceId;
497
+ if(file.size>1024*1024||!['csv','tsv','txt','md'].includes(file.name.split('.').at(-1)?.toLowerCase())){setError(L('请选择 1 MiB 内的 CSV、TSV、TXT 或 Markdown。','Choose CSV, TSV, TXT or Markdown up to 1 MiB.'));return;}
498
+ setReadingFile(true);try{const content=await file.text();if(!alive.current||stamp!==reading.current)return;const ext=file.name.split('.').at(-1).toLowerCase();setUpdates(old=>({...old,[target]:{id:target,format:ext==='csv'||ext==='tsv'?ext:'text',content}}));setPreview(null);setError('');}catch{if(alive.current)setError(L('无法读取材料,请重试。','Could not read source. Try again.'));}finally{if(alive.current)setReadingFile(false);}
499
+ }
500
+ async function importScenario(event){
501
+ const file=event.target.files?.[0];event.target.value='';if(!file)return;const stamp=++reading.current;
502
+ setReadingFile(true);
503
+ try{
504
+ if(file.size>32000)throw new Error(L('推演参数文件过大。','Scenario parameter file is too large.'));
505
+ const packet=JSON.parse(await file.text());if(!alive.current||stamp!==reading.current)return;
506
+ if(packet.schemaVersion!==1||packet.deckId!==project.deckId||packet.revision!==project.revision||packet.fingerprint!==model.fingerprint||!packet.parameters||typeof packet.parameters!=='object'||Array.isArray(packet.parameters)||Object.keys(packet.parameters).some(id=>!Object.hasOwn(baseline,id))||Object.values(packet.parameters).some(value=>typeof value!=='number'||!Number.isFinite(value)))throw new Error(L('参数来自其他工程、旧版本或格式无效,请重新导出。','Scenario is stale, belongs to another project, or is invalid. Export it again.'));
507
+ const next={...baseline,...Object.fromEntries(Object.entries(packet.parameters).map(([id,value])=>[id,String(value)]))};setParameters(next);setValid(true);setPreview(null);onParameters(Object.fromEntries(Object.entries(next).map(([id,value])=>[id,Number(value)])));setError('');
508
+ }catch(reason){if(alive.current)setError(reason.message);}finally{if(alive.current)setReadingFile(false);}
509
+ }
510
+ const metric=model.metrics.find(m=>m.id===metricId),source=model.sources.find(s=>s.id===sourceId),replacement=updates[sourceId];
511
+ const format=(value,m)=>new Intl.NumberFormat(languageOf()==='en'?'en-US':'zh-CN',{style:m.format.style==='percent'?'percent':'decimal',minimumFractionDigits:m.format.digits,maximumFractionDigits:m.format.digits}).format(value)+(m.format.unit||'');
512
+ const display=value=>typeof value==='string'?value:JSON.stringify(value,null,2),disabled=busy||blocked||readingFile;
513
+ return h('section',{className:'card data-workbench','aria-label':L('数据溯源与现场推演','Data lineage and what-if')},
514
+ h('style',null,dataCss),
515
+ h('h3',null,L('数据溯源与现场推演','Data lineage and what-if')),
516
+ h('p',{className:'muted'},L('点预览中的数字可追问来源。只有明确声明的假设可调;来源不等于事实已核验。','Click numbers in the preview to inspect their lineage. Only declared assumptions are adjustable. Lineage is not factual verification.')),
517
+ h('details',null,h('summary',null,L('数字来自哪里','Where the numbers come from')),
518
+ h('label',null,L('指标','Metric'),h('select',{value:metricId,disabled,onChange:event=>setMetricId(event.target.value)},model.metrics.map(m=>h('option',{key:m.id,value:m.id},m.label+' ['+m.id+']')))),
519
+ metric&&h('div',{className:'data-evidence'},h('strong',null,metric.label+' = '+format(model.values[metric.id],metric)),
520
+ metric.kind==='source'?h(React.Fragment,null,h('p',null,metric.evidence.name+' · '+metric.evidence.locator),h('pre',null,metric.evidence.excerpt),h('details',null,h('summary',null,L('来源快照校验值','Source snapshot checksum')),h('code',null,metric.evidence.sha256))):metric.kind==='input'?h('p',null,L('用户假设','User assumption')+(metric.note?' · '+metric.note:'')):h(React.Fragment,null,h('pre',null,'= '+metric.formula),h('div',{className:'tools'},metric.dependencies.map(id=>h('button',{key:id,disabled,onClick:()=>setMetricId(id)},model.metrics.find(m=>m.id===id).label))))),
521
+ h('button',{disabled:disabled||changed,onClick:()=>onDownload('data')},L('下载溯源与假设报告','Download lineage and assumptions'))),
522
+ model.metrics.some(m=>m.kind==='input')&&h('details',{open:true},h('summary',null,L('现场推演参数','What-if assumptions')),
523
+ model.metrics.filter(m=>m.kind==='input').map(m=>h('div',{key:m.id,className:'data-input-row'},h('label',{htmlFor:'ppt-data-'+m.id},m.label,h('small',{className:'muted'},' · '+L('假设','Assumption')+(m.note?' · '+m.note:''))),h('div',{className:'data-input-controls'},h('input',{type:'range',min:m.min,max:m.max,step:m.step,value:Number(parameters[m.id]),disabled,'aria-label':m.label+' '+L('滑杆','slider'),onChange:event=>changeParameter(m.id,event.target.value)}),h('input',{id:'ppt-data-'+m.id,type:'number',min:m.min,max:m.max,step:m.step,value:parameters[m.id],disabled,onChange:event=>changeParameter(m.id,event.target.value)})))),
524
+ h('label',null,L('导入离线 HTML 保存的推演参数','Import scenario parameters saved in offline HTML'),h('input',{type:'file',accept:'.json,application/json',disabled,onChange:importScenario}))),
525
+ model.sources.length>0&&h('details',null,h('summary',null,L('更新来源材料','Update source material')),
526
+ h('p',{className:'muted'},L('先导入或粘贴新材料,预览影响后再确认;不会自动监视或修改原文件。表格可从 Excel 导出 CSV。','Import or paste new material, then preview the impact before confirming. Original source files are not watched or modified. Export Excel tables as CSV.')),
527
+ h('label',null,L('替换来源','Replace source'),h('select',{value:sourceId,disabled,onChange:event=>setSourceId(event.target.value)},model.sources.map(s=>h('option',{key:s.id,value:s.id},s.name)))),
528
+ h('label',null,L('导入替换材料','Import replacement material'),h('input',{type:'file',accept:source?.kind==='table'?'.csv,.tsv':'.txt,.md',disabled,onChange:importSource})),
529
+ source?.kind==='table'&&h('label',null,L('分隔格式','Delimiter format'),h('select',{value:replacement?.format||'csv',disabled,onChange:event=>{setUpdates(old=>({...old,[sourceId]:{id:sourceId,format:event.target.value,content:replacement?.content||''}}));setPreview(null);}},h('option',{value:'csv'},'CSV'),h('option',{value:'tsv'},'TSV'))),
530
+ h('label',null,L('或粘贴内容','Or paste content'),h('textarea',{rows:4,maxLength:1048576,value:replacement?.content??'',disabled,onChange:event=>{setUpdates(old=>({...old,[sourceId]:{id:sourceId,format:source.kind==='table'?replacement?.format||'csv':'text',content:event.target.value}}));setPreview(null);setError('');}})),
531
+ replacement&&h('button',{disabled,onClick:()=>{setUpdates(old=>{const next={...old};delete next[sourceId];return next;});setPreview(null);}},L('取消此来源更新','Cancel this source update'))),
532
+ changed&&h('p',{className:'dirty',role:'status'},L('推演或材料尚未保存,当前 PPTX 仍是已保存版本。先预览差异并确认,或恢复参数后下载。','Unsaved scenario or source changes. The PPTX still contains saved values. Preview and confirm, or reset before downloading.')),
533
+ (!valid||!inputsValid)&&h('p',{className:'notice error',role:'alert'},L('参数无法计算,请检查范围、步长或除零,再恢复或修改。','Cannot calculate these parameters. Check ranges, steps or division by zero; adjust or reset.')),
534
+ error&&h('p',{className:'notice error',role:'alert'},error),
535
+ h('div',{className:'tools'},h('button',{disabled:disabled||!changed||!valid||!inputsValid,onClick:inspect},L('预览差异','Preview changes')),h('button',{disabled:disabled||!changed,onClick:reset},L('恢复已保存数据','Reset to saved data'))),
536
+ preview&&preview.signature===signature&&h('div',{className:'data-diff'},h('h4',null,L('确认前核对','Review before confirming')),
537
+ !preview.changed?h('p',null,L('内容没有变化。','No content changes.')):h(React.Fragment,null,
538
+ h('ul',null,preview.changes.map(change=>h('li',{key:change.id},h('strong',null,change.label+': '),change.beforeText+' → '+change.afterText,change.before===change.after&&' · '+L('来源已更新','Source updated')))),
539
+ h('h4',null,L('受影响页面','Affected slides')),
540
+ !preview.affectedSlides.length&&h('p',{className:'muted'},L('指标尚未绑定到页面,只更新数据模型。','Metrics are not bound to slides; only the data model changes.')),
541
+ preview.affectedSlides.map(slide=>h('details',{key:slide.id},h('summary',null,(slide.page)+'. '+slide.title),h('button',{disabled,onClick:()=>onChoose(slide.id)},L('查看页面','View slide')),slide.evidenceChanged&&h('p',null,L('关联的来源快照有变化。','A linked source snapshot changed.')),slide.fields.map(field=>h('div',{key:field.field},h('strong',null,t(fields.find(([key])=>key===field.field)?.[1]||field.field)),h('div',{className:'data-before-after'},h('pre',null,L('之前:','Before: ')+display(field.before)),h('pre',null,L('之后:','After: ')+display(field.after))))))),
542
+ h('label',{className:'data-copy'},h('input',{type:'checkbox',checked:saveAs,disabled,onChange:event=>setSaveAs(event.target.checked)}),L('保存为新副本,保留原稿(推荐)','Save a new copy and keep the original (recommended)')),
543
+ h('p',{className:'muted'},L('PPTX 保存确认后的静态结果,并附公式、来源和假设;HTML 保留交互。JSON 工程包含导入的完整材料,分享前请检查。','PPTX saves confirmed static results with formulas, sources and assumptions; HTML retains interaction. The JSON project contains full imported material; review it before sharing.')),
544
+ h('button',{className:'primary',disabled:disabled||!valid||!inputsValid,onClick:apply},saveAs?L('确认并保存推演副本','Confirm and save scenario copy'):L('确认并更新当前工程','Confirm and update this project')))));
545
+ }
467
546
  function Workbench({ locale } = {}) {
468
547
  useLanguage(locale);
469
548
  const [projects, setProjects] = useState([]), [project, setProject] = useState(null), [selected, setSelected] = useState('');
470
549
  const [draft, setDraft] = useState({}), [image, setImage] = useState(null), [dirty, setDirty] = useState(false);
550
+ const [dataDirty,setDataDirty]=useState(false),[incomingData,setIncomingData]=useState(null);
471
551
  const [busy, setBusy] = useState(false), [job, setJob] = useState(''), [message, setMessage] = useState(''), [error, setError] = useState('');
472
552
  const [mode, setMode] = useState('html'), [raster, setRaster] = useState('');
473
553
  const [conflict, setConflict] = useState(false), [overlaps, setOverlaps] = useState([]);
@@ -476,11 +556,13 @@ function useLanguage(locale) {
476
556
  if (!imageLoader.current) imageLoader.current = createImageLoader();
477
557
  const imagePending = imageLoader.current.pending;
478
558
  const nonce = useRef(crypto.randomUUID());
559
+ const dataCommand=useRef(0);
479
560
  const previewDocument = useMemo(() => project?.html ? editorHtml(project.html, nonce.current) : '', [project?.html]);
480
561
  const index = project ? Math.max(0, project.slides.findIndex(s => s.id === selected)) : 0;
481
562
  const slide = project?.slides[index];
482
563
  function adopt(next, preferred) {
483
564
  imageLoader.current.cancel();
565
+ nonce.current=crypto.randomUUID();setDataDirty(false);setIncomingData(null);
484
566
  setProject(next);
485
567
  const row = next.slides.find(s => s.id === preferred) || next.slides[0];
486
568
  setSelected(row.id); setDraft(draftFor(row)); setImage(null); setDirty(false); setRaster(''); setOverlaps([]);
@@ -502,6 +584,7 @@ function useLanguage(locale) {
502
584
  useEffect(() => {
503
585
  function receive(event) {
504
586
  if (event.source !== frame.current?.contentWindow || event.data?.nonce !== nonce.current || mode !== 'html') return;
587
+ if(event.data.type==='dsh-ppt-data'){if(typeof event.data.command==='number'&&event.data.command!==dataCommand.current)return;setIncomingData({parameters:event.data.parameters,valid:event.data.valid});return;}
505
588
  if (event.data.type === 'dsh-ppt-shortcut') { handleShortcut(event.data.key); return; }
506
589
  if (event.data.type !== 'dsh-ppt-select') return;
507
590
  const key = event.data.field;
@@ -509,7 +592,7 @@ function useLanguage(locale) {
509
592
  if (field) { fieldRefs.current[key]?.focus(); fieldRefs.current[key]?.scrollIntoView({ block: 'nearest' }); setMessage(t("已定位到") + t(field[1]) + t(",在字段中修改后保存。")); }
510
593
  }
511
594
  window.addEventListener('message', receive); return () => window.removeEventListener('message', receive);
512
- }, [mode, project, dirty, busy, imagePending, index, selected, draft, image]);
595
+ }, [mode, project, dirty, busy, imagePending, index, selected, draft, image, dataDirty]);
513
596
  useEffect(() => {
514
597
  if (mode !== 'html' || !project || !previewBox.current) return;
515
598
  // Align iframe edges/dimensions when the host uses fractional text metrics.
@@ -533,6 +616,7 @@ function useLanguage(locale) {
533
616
  return () => abort.abort();
534
617
  }, [mode, index, project?.revision]);
535
618
  function handleShortcut(key) {
619
+ if(dataDirty)return;
536
620
  if (key === 'save') { if (project && dirty && !busy && !imagePending) save(); return; }
537
621
  if (key === 'escape') {
538
622
  if (!project || busy || imagePending) return;
@@ -570,13 +654,13 @@ function useLanguage(locale) {
570
654
  }
571
655
  document.addEventListener('keydown', onKey);
572
656
  return () => document.removeEventListener('keydown', onKey);
573
- }, [project, dirty, busy, imagePending, index, selected, draft, image]);
657
+ }, [project, dirty, busy, imagePending, index, selected, draft, image, dataDirty]);
574
658
  useEffect(() => {
575
- if (!dirty) return;
659
+ if (!dirty && !dataDirty) return;
576
660
  function warn(event) { event.preventDefault(); event.returnValue = t("有未保存修改,离开页面会丢失。"); }
577
661
  window.addEventListener('beforeunload', warn);
578
662
  return () => window.removeEventListener('beforeunload', warn);
579
- }, [dirty]);
663
+ }, [dirty,dataDirty]);
580
664
  function open(id) { return perform(signal => action({ operation: 'open', id }, signal), value => { adopt(value.project); setMessage(t("点击预览里的文字,或在下方修改字段。")); }); }
581
665
  function keepInputsAndReload() {
582
666
  const original = draftFor(slide), keys = fields.filter(([key]) => draft[key] !== original[key]).map(([key]) => key), pending = { ...draft }, pendingImage = image;
@@ -591,6 +675,7 @@ function useLanguage(locale) {
591
675
  }
592
676
  function choose(row) { if (dirty || busy) return; imageLoader.current.cancel(); setSelected(row.id); setDraft(draftFor(row)); setImage(null); setMessage(''); }
593
677
  function save(saveAs = false) {
678
+ if(dataDirty)return;
594
679
  const original = draftFor(slide), patch = {};
595
680
  for (const [key] of fields) if (draft[key] !== original[key]) patch[key] = key === 'bullets' ? draft[key].split('\n').map(v => v.trim()).filter(Boolean) : draft[key];
596
681
  if (image) patch.image = { src: image.src, alt: image.alt, fit: image.fit, caption: image.caption };
@@ -599,20 +684,24 @@ function useLanguage(locale) {
599
684
  });
600
685
  }
601
686
  function move(delta) {
687
+ if(dataDirty)return;
602
688
  const order = project.slides.map(s => s.id); [order[index], order[index + delta]] = [order[index + delta], order[index]];
603
689
  return perform(signal => action({ operation: 'edit', id: project.id, expectedRevision: project.revision, order }, signal), value => { adopt(value.project, slide.id); setMessage(t("页面顺序已更新,可撤销。")); });
604
690
  }
605
691
  function structure(operation) {
692
+ if(dataDirty)return;
606
693
  return perform(signal => action({ operation, id: project.id, expectedRevision: project.revision, slide: slide.id }, signal), value => {
607
694
  adopt(value.project, value.selected);
608
695
  setMessage(operation === 'duplicate' ? t("页面已复制,图片、图表和备注一并保留,可撤销。") : t("页面已删除,可撤销。"));
609
696
  });
610
697
  }
611
- function undo() { return perform(signal => action({ operation: 'undo', id: project.id, expectedRevision: project.revision }, signal), value => { adopt(value.project, selected); setMessage(t("已撤销上次修改。")); }); }
698
+ function undo() { if(dataDirty)return;return perform(signal => action({ operation: 'undo', id: project.id, expectedRevision: project.revision }, signal), value => { adopt(value.project, selected); setMessage(t("已撤销上次修改。")); }); }
612
699
  function render() {
700
+ if(dataDirty)return;
613
701
  return perform(signal => action({ operation: 'render', id: project.id, expectedRevision: project.revision }, signal), value => { adopt(value.project, selected); setMode('pptx'); setMessage(t("当前 PPTX 已生成逐页图片,请查看画面。")); }, t("正在渲染最终 PPTX,较大文件可能需要几分钟…"));
614
702
  }
615
703
  function download(kind) {
704
+ if(dataDirty)return;
616
705
  const url = new URL('api/dsh-ppt/download', document.baseURI);
617
706
  url.searchParams.set('id', project.id); url.searchParams.set('kind', kind); url.searchParams.set('revision', String(project.revision));
618
707
  // An authenticated attachment response keeps the click's user gesture and
@@ -640,8 +729,8 @@ function useLanguage(locale) {
640
729
  return h('div', { className: 'pptw', 'aria-busy': busy ? 'true' : undefined }, h('style', null, css),
641
730
  h('h2', null, t("演示文稿编辑")), h('p', { className: 'muted' }, t("修改本插件生成的成品,保存时同步更新 HTML、可编辑 PPTX 和工程文件。")),
642
731
  h('p', { className: 'muted' }, t("快捷键:Ctrl/⌘+S 保存 · Esc 取消或返回 · Alt+←/→ 切换页面")),
643
- error && h('div', { role: 'alert', className: 'notice error' }, error, ' ', h('button', { disabled: busy, onClick: () => project ? open(project.id) : refreshList() }, t("重试"))),
644
- conflict && project && h('button', { disabled: busy, onClick: keepInputsAndReload }, t("载入最新版本,保留我的输入")),
732
+ error && h('div', { role: 'alert', className: 'notice error' }, error, ' ', h('button', { disabled: busy || dataDirty, onClick: () => project ? open(project.id) : refreshList() }, t("重试"))),
733
+ conflict && project && h('button', { disabled: busy || dataDirty, onClick: keepInputsAndReload }, t("载入最新版本,保留我的输入")),
645
734
  message && h('div', { role: 'status', className: 'notice' }, message),
646
735
  busy && h('div', { role: 'status', className: 'muted' }, job),
647
736
  !project ? h(React.Fragment, null,
@@ -649,32 +738,36 @@ function useLanguage(locale) {
649
738
  projects.length ? h('div', { className: 'project-list' }, projects.map(row => h('button', { key: row.id, onClick: () => open(row.id), disabled: busy }, h('strong', null, row.title), h('div', { className: 'file muted' }, row.path)))) :
650
739
  h('div', { className: 'card' }, h('h3', null, t("还没有可以编辑的项目")), h('p', null, t("先在对话中让助手生成演示文稿。已有项目可以让助手调用 ppt_check 检查一次,它会出现在这里。")), h('p', { className: 'muted' }, t("示例:请把这份材料制作成可直接交付的演示文稿,生成 HTML、PPTX 和工程文件。")), h('div', { className: 'tools' }, h('button', { onClick: copyExample }, t("复制示例"))))
651
740
  ) : h(React.Fragment, null,
652
- h('div', { className: 'tools' }, h('button', { disabled: busy || dirty, onClick: () => { imageLoader.current.cancel(); setImage(null); setProject(null); refreshList(); } }, t("返回项目")), h('strong', null, project.title), dirty && h('span', { className: 'badge-dirty', role: 'status' }, t("未保存")), h('span', { className: 'muted' }, project.slides.length + t(" 页 · 修订 ") + project.revision)),
741
+ h('div', { className: 'tools' }, h('button', { disabled: busy || dirty || dataDirty, onClick: () => { imageLoader.current.cancel(); setImage(null); setProject(null); refreshList(); } }, t("返回项目")), h('strong', null, project.title), (dirty||dataDirty) && h('span', { className: 'badge-dirty', role: 'status' }, t("未保存")), h('span', { className: 'muted' }, project.slides.length + t(" 页 · 修订 ") + project.revision)),
653
742
  h('div', { className: 'layout' },
654
743
  h('div', null, h('h3', null, t("页面")), h('div', { className: 'pages' }, project.slides.map((row, i) => h('button', { key: row.id, 'aria-current': row.id === selected ? 'true' : undefined, disabled: busy || dirty, onClick: () => choose(row) }, (i + 1) + '. ' + (row.title || t("未命名页"))))),
655
- h('div', { className: 'tools' }, h('button', { disabled: busy || dirty || imagePending || index === 0, onClick: () => move(-1) }, t("上移")), h('button', { disabled: busy || dirty || imagePending || index === project.slides.length - 1, onClick: () => move(1) }, t("下移")),
656
- h('button', { disabled: busy || dirty || imagePending || project.slides.length >= 120, onClick: () => structure('duplicate') }, t("复制本页")),
657
- h('button', { disabled: busy || dirty || imagePending || project.slides.length <= 1, onClick: () => structure('remove') }, t("删除本页")))),
744
+ h('div', { className: 'tools' }, h('button', { disabled: busy || dirty || imagePending || dataDirty || index === 0, onClick: () => move(-1) }, t("上移")), h('button', { disabled: busy || dirty || imagePending || dataDirty || index === project.slides.length - 1, onClick: () => move(1) }, t("下移")),
745
+ h('button', { disabled: busy || dirty || imagePending || dataDirty || project.slides.length >= 120, onClick: () => structure('duplicate') }, t("复制本页")),
746
+ h('button', { disabled: busy || dirty || imagePending || dataDirty || project.slides.length <= 1, onClick: () => structure('remove') }, t("删除本页")))),
658
747
  h('div', null,
659
- h('div', { className: 'tools' }, h('button', { disabled: busy, 'aria-pressed': mode === 'html', onClick: () => setMode('html') }, t("HTML 预览")),
660
- h('button', { disabled: busy || !project.render, 'aria-pressed': mode === 'pptx', onClick: () => setMode('pptx') }, t("最终 PPTX 预览")),
661
- h('button', { disabled: busy || dirty || imagePending, onClick: render }, t("渲染当前 PPTX"))),
748
+ h('div', { className: 'tools' }, h('button', { disabled: busy || dataDirty, 'aria-pressed': mode === 'html', onClick: () => setMode('html') }, t("HTML 预览")),
749
+ h('button', { disabled: busy || dataDirty || !project.render, 'aria-pressed': mode === 'pptx', onClick: () => setMode('pptx') }, t("最终 PPTX 预览")),
750
+ h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: render }, t("渲染当前 PPTX"))),
662
751
  h('div', { className: 'preview', ref: previewBox }, mode === 'html' ? (project.html ? h('iframe', { ref: frame, title: t("演示文稿 HTML 预览"), sandbox: 'allow-scripts', srcDoc: previewDocument, onLoad: jump }) : h('p', null, t("此项目尚无 HTML,请保存一次生成预览。"))) : raster ? h('img', { className: 'render-page', src: raster, alt: t("最终 PPTX 第 ") + (index + 1) + t(" 页渲染结果") }) : h('p', null, t("正在载入当前页渲染…"))),
663
752
  h('p', { className: 'muted' }, mode === 'html' ? t("这是 HTML 放映预览。最终 PPTX 的字体和排版请用上方渲染检查。点击文字可定位编辑字段。") : t("这是当前 PPTX 文件的实际渲染图片,仍需检查每页画面;PowerPoint / WPS 可能因字体环境而不同。")),
664
753
  project.render?.missingFonts?.length ? h('div', { role: 'alert', className: 'notice error' }, t("渲染引擎报告缺失字体:") + project.render.missingFonts.join('、') + t("。请替换为目标电脑可用字体后重新渲染。")) : null,
665
754
  h('div', { className: 'card' }, h('h3', null, t("编辑第 ") + (index + 1) + t(" 页")),
666
755
  dirty && h('p', { className: 'dirty' }, t("有未保存修改,请先保存或取消,再切换页面。")),
667
756
  overlaps.length ? h('div', { className: 'notice' }, h('strong', null, t("这些字段也被修改过,请比较后决定是否保存:")), overlaps.map(row => h('div', { key: row.key }, h('strong', null, t(fields.find(([key]) => key === row.key)[1])), h('p', null, t("最新版本:") + row.latest), h('p', null, t("你的修改:") + row.yours)))) : null,
668
- fields.filter(([key]) => key === 'title' || key === 'notes' || key === 'bullets' && (slide.layout === 'bullets' || slide.bullets?.length > 0) || key !== 'bullets' && (slide[key] || key === 'subtitle' && ['cover','section','closing','quote'].includes(slide.layout) || key === 'kicker' && ['cover','section','closing'].includes(slide.layout))).map(([key, label]) => h('div', { key }, h('label', { htmlFor: 'pptw-' + key }, t(label)), h(key === 'title' || key === 'kicker' ? 'input' : 'textarea', { id: 'pptw-' + key, ref: el => { fieldRefs.current[key] = el }, disabled: busy, value: draft[key] || '', rows: key === 'bullets' ? 4 : 2, maxLength: 8000, onChange: e => { setDraft({ ...draft, [key]: e.target.value }); setDirty(true); } }))),
757
+ fields.filter(([key]) => key === 'title' || key === 'notes' || key === 'bullets' && (slide.layout === 'bullets' || slide.bullets?.length > 0) || key !== 'bullets' && (slide[key] || key === 'subtitle' && ['cover','section','closing','quote'].includes(slide.layout) || key === 'kicker' && ['cover','section','closing'].includes(slide.layout))).map(([key, label]) => h('div', { key }, h('label', { htmlFor: 'pptw-' + key }, t(label)), h(key === 'title' || key === 'kicker' ? 'input' : 'textarea', { id: 'pptw-' + key, ref: el => { fieldRefs.current[key] = el }, disabled: busy || dataDirty, value: draft[key] || '', rows: key === 'bullets' ? 4 : 2, maxLength: 8000, onChange: e => { setDraft({ ...draft, [key]: e.target.value }); setDirty(true); } }))),
669
758
  h('label', { htmlFor: 'pptw-image' }, slide.image ? t("替换图片(PNG / JPEG)") : t("添加图片(会改为图文布局)")),
670
- h('input', { id: 'pptw-image', type: 'file', accept: 'image/png,image/jpeg', disabled: busy, onChange: upload }),
759
+ h('input', { id: 'pptw-image', type: 'file', accept: 'image/png,image/jpeg', disabled: busy || dataDirty, onChange: upload }),
671
760
  currentImage && h('img', { className: 'image-preview', src: currentImage, alt: image?.alt || slide.image?.alt || t("当前图片") }),
672
- image && h(React.Fragment, null, h('p', { className: 'muted' }, t("已选择:") + image.name), h('label', { htmlFor: 'pptw-alt' }, t("图片说明")), h('input', { id: 'pptw-alt', value: image.alt, disabled: busy, onChange: e => setImage({ ...image, alt: e.target.value }) }), h('label', { htmlFor: 'pptw-fit' }, t("图片适应方式")), h('select', { id: 'pptw-fit', value: image.fit, disabled: busy, onChange: e => setImage({ ...image, fit: e.target.value }) }, h('option', { value: 'contain' }, t("完整显示")), h('option', { value: 'cover' }, t("填满并裁切")))),
673
- h('div', { className: 'tools' }, h('button', { className: 'primary', 'aria-keyshortcuts': 'Control+S Meta+S', disabled: busy || imagePending || !dirty, onClick: () => save() }, t("保存此页")), h('button', { 'aria-keyshortcuts': 'Control+Shift+S Meta+Shift+S', disabled: busy || imagePending, onClick: () => save(true) }, t("另存副本")), h('button', { 'aria-keyshortcuts': 'Escape', disabled: busy || (!dirty && !imagePending), onClick: () => { imageLoader.current.cancel(); setDraft(draftFor(slide)); setImage(null); setDirty(false); setError(''); setMessage(''); setConflict(false); setOverlaps([]); } }, t("取消修改")), h('button', { disabled: busy || dirty || imagePending || !project.undoAvailable, onClick: undo }, t("撤销上次修改")))),
761
+ image && h(React.Fragment, null, h('p', { className: 'muted' }, t("已选择:") + image.name), h('label', { htmlFor: 'pptw-alt' }, t("图片说明")), h('input', { id: 'pptw-alt', value: image.alt, disabled: busy || dataDirty, onChange: e => setImage({ ...image, alt: e.target.value }) }), h('label', { htmlFor: 'pptw-fit' }, t("图片适应方式")), h('select', { id: 'pptw-fit', value: image.fit, disabled: busy || dataDirty, onChange: e => setImage({ ...image, fit: e.target.value }) }, h('option', { value: 'contain' }, t("完整显示")), h('option', { value: 'cover' }, t("填满并裁切")))),
762
+ h('div', { className: 'tools' }, h('button', { className: 'primary', 'aria-keyshortcuts': 'Control+S Meta+S', disabled: busy || dataDirty || imagePending || !dirty, onClick: () => save() }, t("保存此页")), h('button', { 'aria-keyshortcuts': 'Control+Shift+S Meta+Shift+S', disabled: busy || dataDirty || imagePending, onClick: () => save(true) }, t("另存副本")), h('button', { 'aria-keyshortcuts': 'Escape', disabled: busy || (!dirty && !imagePending), onClick: () => { imageLoader.current.cancel(); setDraft(draftFor(slide)); setImage(null); setDirty(false); setError(''); setMessage(''); setConflict(false); setOverlaps([]); } }, t("取消修改")), h('button', { disabled: busy || dirty || imagePending || dataDirty || !project.undoAvailable, onClick: undo }, t("撤销上次修改")))),
674
763
  h('details', { className: 'card' }, h('summary', null, t("质量提醒(") + (project.quality.warningCount + project.quality.errorCount) + (languageOf() === 'en' ? ')' : ')')), (project.quality.issues || []).map((issue, i) => h('p', { key: i }, (issue.slide > 0 ? t("第 ") + issue.slide + t(" 页:") : "") + (languageOf() === 'en' ? issue.messageEn : issue.message) + (languageOf() === 'en' ? ' ' : ';') + (languageOf() === 'en' ? issue.suggestionEn : issue.suggestion)))),
675
764
  h('p', { className: 'muted' }, t("成品包包含 PPTX、HTML 和工程文件。请先保存修改,再下载最新版本。")),
676
- h('div', { className: 'tools' }, h('button', { className: 'primary', disabled: busy || dirty || imagePending, onClick: () => download('bundle') }, t("下载成品包 ZIP")), h('button', { disabled: busy || dirty || imagePending, onClick: () => download('pptx') }, t("下载最新 PPTX")), h('button', { disabled: busy || dirty || imagePending, onClick: () => download('html') }, t("下载 HTML")), h('button', { disabled: busy || dirty || imagePending, onClick: () => download('notes') }, t("下载讲稿 Markdown")), h('button', { disabled: busy || dirty || imagePending, onClick: () => download('json') }, t("备份工程"))),
677
- h(CoachingPanel, { key: project.id, project, selected, blocked: busy || dirty || imagePending,
765
+ h('div', { className: 'tools' }, h('button', { className: 'primary', disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('bundle') }, t("下载成品包 ZIP")), h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('pptx') }, t("下载最新 PPTX")), h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('html') }, t("下载 HTML")), h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('notes') }, t("下载讲稿 Markdown")), h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('json') }, t("备份工程"))),
766
+ project.dataModel&&mode!=='html'&&h('p',{className:'notice'},languageOf()==='en'?'Switch to HTML preview to adjust assumptions and inspect live data.':'切换到 HTML 预览后可调整假设并查看数据联动。'),
767
+ project.dataModel&&h(DataPanel,{key:project.id+':'+project.revision,project,blocked:busy||dirty||imagePending||mode!=='html',incoming:incomingData,
768
+ onParameters:parameters=>frame.current?.contentWindow?.postMessage({type:'dsh-ppt-data-set',nonce:nonce.current,parameters,command:++dataCommand.current},'*'),onDirty:setDataDirty,onBusy:value=>{setBusy(value);setJob(languageOf()==='en'?'Updating presentation data…':'正在核对并更新数据…');},
769
+ onAdopt:next=>{adopt(next,selected);setMessage(languageOf()==='en'?'Saved confirmed data. HTML, PPTX and project are synchronized; undo is available.':'已保存确认后的数据,HTML、PPTX 和工程已同步,可撤销。');},onChoose:id=>choose(project.slides.find(s=>s.id===id)),onDownload:download}),
770
+ h(CoachingPanel, { key: project.id, project, selected, blocked: busy || dirty || imagePending || dataDirty,
678
771
  onChoose: id => { choose(project.slides.find(s => s.id === id)); previewBox.current?.scrollIntoView({ behavior: 'smooth', block: 'center' }); },
679
772
  onAdopt: next => { adopt(next, selected); setMessage(languageOf() === 'en' ? 'Saved to a new copy. The original is kept; you can undo the adopted changes in this copy.' : '已保存为新副本,原稿保留;可在当前副本中撤销采纳的修改。'); } })
680
773
  )
package/lib/coaching.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { CoachingModel, ModelRoute } from './coaching-model.js';
2
2
  export type CoachingContext = {
3
3
  id: string;
4
4
  manifest: any;
5
+ dataNotes?: Record<string, string>;
5
6
  };
6
7
  type Kind = 'expression' | 'logic' | 'evidence';
7
8
  type Finding = {
package/lib/coaching.js CHANGED
@@ -142,7 +142,7 @@ export class PptCoaching {
142
142
  const selected = body.slideId === undefined ? context.manifest.slides : context.manifest.slides.filter((s) => s.id === body.slideId);
143
143
  if (!selected.length)
144
144
  throw new Error('检查范围没有页面 / No slides in the selected scope');
145
- const slides = selected.map((s) => ({ id: s.id, ...JSON.parse(slideText(s)) }));
145
+ const slides = selected.map((s) => ({ id: s.id, ...JSON.parse(slideText({ ...s, ...(context.dataNotes?.[s.id] ? { notes: context.dataNotes[s.id] } : {}) })) }));
146
146
  if (JSON.stringify(slides).length + material.length > 60000)
147
147
  throw new Error('材料超过 60000 字符,请选择当前页检查 / Input too long; check the current slide');
148
148
  mkdirSync(this.directory, { recursive: true, mode: 0o700 });
@@ -26,4 +26,5 @@ export declare function createPptExecutors(config: ResolvedPptConfig, loadEngine
26
26
  undo(rawArgs: unknown, exec?: PptExecution): Promise<import("./types.js").PptCreateResult>;
27
27
  check(rawArgs: unknown, exec?: PptExecution): Promise<import("./types.js").PptQualityResult | import("./types.js").PptCheckResult>;
28
28
  render(rawArgs: unknown, exec?: PptExecution): Promise<import("./types.js").PptRenderResult>;
29
+ data(rawArgs: unknown, exec?: PptExecution): Promise<import("./types.js").PptCreateResult | Record<string, any>>;
29
30
  };
package/lib/execution.js CHANGED
@@ -63,6 +63,7 @@ export function createPptExecutors(config, loadEngine = getEngine) {
63
63
  maxSlides: config.maxSlides,
64
64
  template: args.template,
65
65
  brand: args.brand,
66
+ dataModel: args.dataModel,
66
67
  cwd,
67
68
  signal: exec?.signal,
68
69
  });
@@ -98,5 +99,15 @@ export function createPptExecutors(config, loadEngine = getEngine) {
98
99
  exec?.signal?.throwIfAborted();
99
100
  return engine.renderDeck({ ...asRecord(rawArgs), cwd: exec?.agent?.session.header.cwd ?? process.cwd(), signal: exec?.signal });
100
101
  },
102
+ async data(rawArgs, exec) {
103
+ exec?.signal?.throwIfAborted();
104
+ const engine = await loadEngine(), args = asRecord(rawArgs);
105
+ const options = { ...args, cwd: exec?.agent?.session.header.cwd ?? process.cwd(), signal: exec?.signal, allowFiles: true };
106
+ if (args.action === 'preview')
107
+ return engine.previewDeckData(options);
108
+ if (args.action === 'apply')
109
+ return engine.updateDeckData(options);
110
+ throw new Error('dsh-ppt:action 需为 preview 或 apply / Use preview or apply');
111
+ },
101
112
  };
102
113
  }
package/lib/index.d.ts CHANGED
@@ -21,4 +21,4 @@ export interface PptPluginContext {
21
21
  export declare function apply(ctx: PptPluginContext, config?: Config): void;
22
22
  export { resolvePptConfig, PPT_OUTPUT_DIR_ENV, DEFAULT_MAX_SLIDES, clampInt } from './config.js';
23
23
  export { bundledSkillsDir, parseSkillFile, registerPptSkill, SKILL_NAMES } from './skill.js';
24
- export type { PptConfig, PptCreateArgs, PptCreateResult, PptLanguage, PptSlideLayout, PptSlideSpec, PptThemeId, PptThemeInfo, PptThemesResult, PptTemplateId, PptImageSpec, PptChartSpec, PptBrand, PptQualityIssue, PptQualityResult, PptVerification, PptRenderArgs, PptRenderResult, PptCheckResult, PptEditArgs, PptProjectArgs, } from './types.js';
24
+ export type { PptConfig, PptCreateArgs, PptCreateResult, PptLanguage, PptSlideLayout, PptSlideSpec, PptThemeId, PptThemeInfo, PptThemesResult, PptTemplateId, PptImageSpec, PptChartSpec, PptBrand, PptQualityIssue, PptQualityResult, PptVerification, PptRenderArgs, PptRenderResult, PptCheckResult, PptEditArgs, PptProjectArgs, PptDataModel, PptDataSource, PptDataMetric, } from './types.js';
package/lib/tools.js CHANGED
@@ -162,6 +162,19 @@ const projectParameters = {
162
162
  deckPath: { type: 'string', required: true, description: 'Path to a dsh-ppt .json project, relative to this session cwd or absolute. Arbitrary external PPTX editing is not supported.' },
163
163
  expectedRevision: { type: 'integer', description: 'Use revision returned by ppt_create/ppt_check to prevent overwriting another edit.' },
164
164
  };
165
+ const sourceProperties = {
166
+ id: { type: 'string', description: 'Letters and digits, starting with a letter; unique ID.' }, name: { type: 'string' },
167
+ format: { type: 'string', enum: ['csv', 'tsv', 'text'] }, content: { type: 'string', description: 'CSV/TSV or text content, combined sources at most 1 MiB.' },
168
+ path: { type: 'string', description: 'Explicit local CSV/TSV/TXT/Markdown import path, relative to session cwd. Embedded once; no file watcher.' },
169
+ kind: { type: 'string', enum: ['table', 'text'] }, rows: { type: 'array', items: { type: 'array', items: { oneOf: [{ type: 'string' }, { type: 'number' }] } } }, text: { type: 'string' },
170
+ };
171
+ const metricProperties = {
172
+ id: { type: 'string' }, label: { type: 'string' }, kind: { type: 'string', enum: ['source', 'input', 'formula'] },
173
+ source: { type: 'object', properties: { sourceId: { type: 'string' }, cell: { type: 'string', description: 'A1 to Z500; first CSV row counts as row 1.' }, line: { type: 'integer', description: '1-based text line.' }, numberIndex: { type: 'integer', description: '0-based numeric token on that line.' } }, required: ['sourceId'] },
174
+ value: { type: 'number' }, min: { type: 'number' }, max: { type: 'number' }, step: { type: 'number' }, note: { type: 'string', description: 'Explain the user assumption; do not invent factual provenance.' },
175
+ formula: { type: 'string', description: 'Metric IDs, + - * / % **, parentheses and min/max/sum/abs/floor/ceil/round only. No JS property access or I/O.' },
176
+ format: { type: 'object', properties: { style: { type: 'string', enum: ['number', 'percent'] }, digits: { type: 'integer' }, unit: { type: 'string' } } },
177
+ };
165
178
  /** Assemble presentation schemas, rendering and the session-aware executors. */
166
179
  export function buildPptTools(config) {
167
180
  const executors = createPptExecutors(config);
@@ -193,6 +206,7 @@ export function buildPptTools(config) {
193
206
  slides: { type: 'array', items: { type: 'object', properties: slideProperties, additionalProperties: true }, description: 'Structured slides including image/image-left/image-right and chart. Images: {src, alt, fit: contain|cover, caption}. Charts: {kind: column|bar|line|pie, categories, series:[{name,values}]} or rows with header. Tables paginate at 8 data rows. Keep full content editable; use images only for actual photos/screenshots/logos.' },
194
207
  template: { type: 'string', enum: ['weekly', 'defense', 'project', 'pitch'], description: 'Scenario reference from ppt_templates. Provide finished content/slides following its outline. Template alone creates a clearly marked draft with unfilled slots, never a finished presentation.' },
195
208
  brand: { type: 'object', properties: brandProperties, additionalProperties: false, description: 'Shared brand: #RRGGBB primary/background/text colors, fontFamily, logo and footer. Applied to HTML and PPTX.' },
209
+ dataModel: { type: 'object', properties: { schemaVersion: { type: 'integer', enum: [1] }, sources: { type: 'array', items: { type: 'object', properties: sourceProperties, required: ['id'] } }, metrics: { type: 'array', items: { type: 'object', properties: metricProperties, required: ['id', 'kind'] } } }, additionalProperties: false, description: 'Optional explicit lineage and what-if model. Use with structured slides containing {{metricId}} in text/tables or an exact token as chart values. Source facts reference a real cell or text line; assumptions require value/min/max/step. Formulas compute derived metrics. HTML offers live sliders; PPTX includes confirmed static values, formulas and assumptions in speaker notes. Leave absent for ordinary finished decks.' },
196
210
  outputDir: { type: 'string', description: 'Directory to write the files into. Default: session working directory (or the plugin outputDir config).' },
197
211
  fileName: { type: 'string', description: 'Base file name for the three artifacts. Default: sanitized deck title.' },
198
212
  overwrite: { type: 'boolean', description: 'Replace an existing same-name HTML/PPTX/JSON trio. Default false: choose a unique numeric suffix instead.' },
@@ -224,6 +238,19 @@ export function buildPptTools(config) {
224
238
  output: { schema: createResultSchema, render: (_args, value) => renderCreate(value) },
225
239
  execute: executors.edit,
226
240
  },
241
+ {
242
+ name: 'ppt_data',
243
+ description: 'Preview or confirm source/assumption changes in a data-enabled project. Preview first; inspect affected slides and before/after values, then apply with confirmed:true, exact previewToken and expectedRevision. Default saves an undoable new copy. HTML remains interactive; PPTX is a confirmed static snapshot. Never invent provenance or silently treat assumptions as facts. 中文:预览来源更新或推演参数的影响,确认后保存可撤销副本;只允许更改声明的假设。',
244
+ parameters: compileParameters({ ...projectParameters,
245
+ action: { type: 'string', enum: ['preview', 'apply'], required: true },
246
+ parameters: { type: 'object', additionalProperties: true, description: 'Declared input metric IDs to numeric values only.' },
247
+ sourceUpdates: { type: 'array', items: { type: 'object', properties: sourceProperties, required: ['id'] }, description: 'Replacement content for existing source IDs; keep source type.' },
248
+ scenario: { type: 'object', additionalProperties: true, description: 'Exact scenario.json from HTML: schemaVersion, deckId, revision, fingerprint, parameters. Rejects stale/foreign projects.' },
249
+ previewToken: { type: 'string' }, confirmed: { type: 'boolean' }, saveAs: { type: 'boolean', description: 'Default true. false updates only when artifacts have not been externally modified.' },
250
+ }),
251
+ output: { schema: { type: 'object', additionalProperties: true }, render: (_args, value) => oneText(JSON.stringify(value, null, 2)) },
252
+ execute: executors.data,
253
+ },
227
254
  {
228
255
  name: 'ppt_undo',
229
256
  description: 'Undo the most recent edit in a dsh-ppt JSON project, restoring slides, charts, embedded images and branding together. Revision increases so stale edits cannot overwrite the undo. Keeps up to 20 edits. 中文:撤销最近一次修改,恢复正文、图表、图片和品牌设置。',