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
package/lib/client.js
CHANGED
|
@@ -235,13 +235,15 @@ function useLanguage(locale) {
|
|
|
235
235
|
return value;
|
|
236
236
|
}
|
|
237
237
|
function draftFor(slide) {
|
|
238
|
-
|
|
239
|
-
|
|
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
|
|
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,174 @@ 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 VisualPanel({ project, selected, blocked, onBusy, onAdopt }) {
|
|
472
|
+
const L = (zh,en) => languageOf() === 'en' ? en : zh;
|
|
473
|
+
const [expanded,setExpanded] = useState(false), [routes,setRoutes] = useState([]), [route,setRoute] = useState('');
|
|
474
|
+
const [scope,setScope] = useState(project.slides.length > 12 ? 'current' : 'all'), [repairs,setRepairs] = useState(1);
|
|
475
|
+
const [run,setRun] = useState(null), [history,setHistory] = useState([]), [busy,setBusy] = useState(false), [error,setError] = useState('');
|
|
476
|
+
const [compare,setCompare] = useState(''), [pictures,setPictures] = useState({}), [loading,setLoading] = useState(false);
|
|
477
|
+
const active=useRef(null), alive=useRef(true), current=useRef(null), runRef=useRef(null), progressVersion=useRef(0);
|
|
478
|
+
current.current={project,selected,blocked};runRef.current=run;
|
|
479
|
+
const request=(op,data={},signal) => action({operation:'visual-'+op,id:current.current.project.id,expectedRevision:current.current.project.revision,...data},signal);
|
|
480
|
+
const accept=value => {if(alive.current){progressVersion.current++;runRef.current=value;setRun(value);}};
|
|
481
|
+
const phaseName=value => ({render:L('正在渲染实际 PPTX','Rendering the actual PPTX'),inspect:L('正在看图检查','Inspecting rendered slides'),repair:L('正在生成排版副本','Creating a formatting copy'),done:L('检查已结束','Review finished')})[value]||value;
|
|
482
|
+
const failureText=value=>{const split=value.lastIndexOf(' / ');return split<0?value:L(value.slice(0,split),value.slice(split+3));};
|
|
483
|
+
const actionName=a => ({'title-size':L('标题字号','Title size'),'body-size':L('正文字号','Body size'),'chart-label-size':L('图表字号','Chart label size'),'chart-horizontal':L('改为横向条形图','Use horizontal bars'),'image-contain':L('完整显示图片','Show the complete image'),'split-bullets':L('拆分要点页','Split bullet slide'),'split-table':L('拆分表格页','Split table slide')})[a.type]+(a.value!==undefined?' · '+a.value:'');
|
|
484
|
+
useEffect(()=>{alive.current=true;return()=>{alive.current=false;active.current?.abort();if(runRef.current&&active.current)void request('stop',{runId:runRef.current.id}).catch(()=>{});};},[]);
|
|
485
|
+
useEffect(()=>{if(!run||['complete','paused'].includes(run.status)||!busy&&run.status!=='busy')return;const abort=new AbortController(),timer=setInterval(()=>{const version=progressVersion.current;void request('get',{runId:run.id},abort.signal).then(v=>{if(!abort.signal.aborted&&version===progressVersion.current)accept(v.run);}).catch(()=>{});},1000);return()=>{clearInterval(timer);abort.abort();};},[run?.id,run?.status,busy]);
|
|
486
|
+
async function refresh(signal){const value=await request('list',{},signal);if(alive.current)setHistory(value.runs);}
|
|
487
|
+
async function task(work,lock=false){
|
|
488
|
+
if(active.current)return;
|
|
489
|
+
const controller=new AbortController();active.current=controller;setBusy(true);setError('');if(lock)onBusy(true);
|
|
490
|
+
try{await work(controller.signal);}
|
|
491
|
+
catch(e){if(alive.current){if(!controller.signal.aborted)setError(e.message||L('视觉检查失败','Visual review failed'));if(runRef.current)try{accept((await request('get',{runId:runRef.current.id})).run);}catch{/* Keep the last checkpoint. */}}}
|
|
492
|
+
finally{if(active.current===controller)active.current=null;if(alive.current)setBusy(false);if(lock)onBusy(false);}
|
|
493
|
+
}
|
|
494
|
+
function configure(){setExpanded(true);return task(async signal=>{
|
|
495
|
+
const results=await Promise.allSettled([request('options',{},signal),refresh(signal)]);
|
|
496
|
+
if(results[0].status==='rejected')throw results[0].reason;
|
|
497
|
+
if(signal.aborted||!alive.current)return;
|
|
498
|
+
const models=results[0].value.routes;setRoutes(models);
|
|
499
|
+
const preferred=models.findIndex(m=>m.provider===project.modelRoute?.provider&&m.model===project.modelRoute?.model);setRoute(models.length?String(Math.max(0,preferred)):'');
|
|
500
|
+
if(results[1].status==='rejected')throw results[1].reason;
|
|
501
|
+
});}
|
|
502
|
+
function start(){if(current.current.blocked)return;return task(async signal=>{
|
|
503
|
+
const model=routes[Number(route)];if(!model)throw new Error(L('请选择支持图片输入的模型','Choose an image-capable model'));
|
|
504
|
+
let value=(await request('create',{confirmed:true,...model,repairs,language:languageOf(),...(scope==='current'?{slideId:current.current.selected}:{})},signal)).run;
|
|
505
|
+
accept(value);setPictures({});setCompare('');
|
|
506
|
+
while(value.status==='ready'&&!signal.aborted){value=(await request('step',{runId:value.id,confirmed:true},signal)).run;accept(value);}
|
|
507
|
+
await refresh(signal);
|
|
508
|
+
const last=value.rounds.at(-1);if(alive.current&&last?.rendered)setCompare(last.ids[0]);
|
|
509
|
+
},true);}
|
|
510
|
+
function stop(){active.current?.abort();if(runRef.current)void request('stop',{runId:runRef.current.id}).then(value=>accept(value.run)).catch(e=>{if(alive.current)setError(e.message);});}
|
|
511
|
+
function open(id){return task(async signal=>{const value=(await request('get',{runId:id},signal)).run;accept(value);setCompare(value.rounds.at(-1)?.rendered?value.rounds.at(-1).ids[0]:'');});}
|
|
512
|
+
function adopt(){if(blocked||!run?.canAdopt)return;return task(async signal=>{const value=await request('adopt',{runId:run.id,confirmed:true},signal);if(alive.current)onAdopt(value.project);},true);}
|
|
513
|
+
function remove(){if(!window.confirm(L('删除这次检查记录和预览图片?生成的 PPT 副本会保留。','Delete this review and its preview images? Presentation copies are kept.')))return;return task(async signal=>{await request('delete',{runId:run.id},signal);accept(null);setPictures({});setCompare('');await refresh(signal);});}
|
|
514
|
+
function download(){const url=new URL('api/dsh-ppt/download',document.baseURI);for(const[k,v]of Object.entries({id:project.id,kind:'visual',revision:project.revision,run:run.id}))url.searchParams.set(k,String(v));const a=document.createElement('a');a.href=url.href;a.download='';document.body.append(a);a.click();a.remove();}
|
|
515
|
+
useEffect(()=>{
|
|
516
|
+
if(!compare||!run)return;
|
|
517
|
+
const abort=new AbortController(),last=run.rounds.length-1;setPictures({});setLoading(true);
|
|
518
|
+
const initial=run.rounds[0].ids.includes(compare);
|
|
519
|
+
Promise.allSettled([initial?request('page',{runId:run.id,round:0,slideId:compare},abort.signal):Promise.resolve(null),request('page',{runId:run.id,round:last,slideId:compare},abort.signal)]).then(values=>{
|
|
520
|
+
if(abort.signal.aborted||!alive.current)return;
|
|
521
|
+
setPictures({before:values[0].status==='fulfilled'?values[0].value?.data:null,after:values[1].status==='fulfilled'?values[1].value?.data:null});
|
|
522
|
+
const failed=values.find(v=>v.status==='rejected');if(failed)setError(failed.reason.message);setLoading(false);
|
|
523
|
+
});return()=>abort.abort();
|
|
524
|
+
},[run?.id,run?.rounds.length,compare]);
|
|
525
|
+
useEffect(()=>{const last=run?.rounds.at(-1);if(!busy&&!compare&&last?.rendered)setCompare(last.ids[0]);},[run?.id,run?.rounds.length,run?.rounds.at(-1)?.rendered,busy,compare]);
|
|
526
|
+
const first=run?.rounds[0],last=run?.rounds.at(-1),stale=run&&(run.stale||run.revision!==project.revision),count=scope==='all'?project.slides.length:1;
|
|
527
|
+
const callCap=Array.from({length:repairs+1},(_,i)=>Math.ceil(count*2**i/2)).reduce((a,b)=>a+b,0);
|
|
528
|
+
function image(src,round,label){return h('figure',{style:{margin:0,minWidth:0}},h('figcaption',null,label),src?h('div',{style:{position:'relative',lineHeight:0}},h('img',{src,alt:label,style:{width:'100%',height:'auto',display:'block'}}),(round?.findings||[]).filter(f=>f.slideId===compare).map((f,i)=>h('span',{key:i,title:f.issue,style:{position:'absolute',pointerEvents:'none',border:'2px solid #f97316',boxSizing:'border-box',left:f.box[0]*100+'%',top:f.box[1]*100+'%',width:f.box[2]*100+'%',height:f.box[3]*100+'%'}}))):h('p',{className:'muted'},round===first&&!first.ids.includes(compare)?L('此页由拆分生成,没有对应的原页画面。','This page was created by a split and has no original counterpart.'):L('画面尚未载入,请重新选择页面。','Image not loaded; select the slide again.')));}
|
|
529
|
+
return h('section',{className:'card coaching','aria-label':L('视觉检查与修复','Visual review and repair')},
|
|
530
|
+
h('h3',null,L('让 AI 看完成品,再修排版','Let AI inspect the finished slides and repair formatting')),
|
|
531
|
+
h('p',{className:'muted'},L('可选功能。检查实际 PPTX 画面,另存修复副本,再渲染复查。原稿保留。','Optional. Inspect actual PPTX images, save a repaired copy, and render it again for rechecking. The original is kept.')),
|
|
532
|
+
!expanded?h('button',{disabled:busy||blocked,onClick:configure},L('视觉检查与修复','Visual review and repair')):h(React.Fragment,null,
|
|
533
|
+
error&&h('div',{role:'alert',className:'notice error'},error),
|
|
534
|
+
!run&&h(React.Fragment,null,
|
|
535
|
+
h('div',{className:'coaching-grid'},
|
|
536
|
+
h('label',null,L('视觉模型','Vision model'),h('select',{'aria-label':L('视觉模型','Vision model'),value:route,disabled:busy,onChange:e=>setRoute(e.target.value)},h('option',{value:''},L('请选择','Choose a model')),routes.map((m,i)=>h('option',{key:m.provider+':'+m.model,value:String(i)},m.label)))),
|
|
537
|
+
h('label',null,L('检查范围','Review scope'),h('select',{'aria-label':L('视觉检查范围','Visual review scope'),value:scope,disabled:busy,onChange:e=>setScope(e.target.value)},h('option',{value:'all',disabled:project.slides.length>12},L('全部页面(最多 12 页)','All slides (up to 12)')),h('option',{value:'current'},L('当前页','Current slide')))),
|
|
538
|
+
h('label',null,L('自动修复上限','Repair limit'),h('select',{'aria-label':L('自动修复上限','Repair limit'),value:repairs,disabled:busy,onChange:e=>setRepairs(Number(e.target.value))},h('option',{value:0},L('仅看图检查','Inspect only')),h('option',{value:1},L('最多修复 1 轮(推荐)','Up to 1 repair round (recommended)')),h('option',{value:2},L('最多修复 2 轮','Up to 2 repair rounds'))))),
|
|
539
|
+
!routes.length&&h('p',{className:'notice'},L('未找到声明支持图片输入的模型。请在 DSH 模型设置中检查图片输入配置;普通生成和下载仍可使用。','No model declares image input. Check the image-input configuration in DSH model settings; normal creation and downloads remain available.')),
|
|
540
|
+
h('p',null,L('会向所选模型发送 '+count+' 页的渲染图片和页面文字;拆页后会重新检查新增页面,最多 '+callCap+' 次模型调用。','Sends rendered images and text from '+count+' slides to the selected model. New split pages are rechecked, with up to '+callCap+' model calls.')),
|
|
541
|
+
h('p',{className:'muted'},L('只调整字号、拆页、图表方向和图片裁切,不改写原文、数字或公式。可随时停止;服务商仍可能收取已发起调用的费用。','Changes font sizes, pagination, chart orientation and image cropping. Original text, numbers and formulas are preserved. You can stop at any time; calls already sent may still be billed.')),
|
|
542
|
+
h('div',{className:'tools'},h('button',{className:'primary',disabled:busy||blocked||!routes[Number(route)]||route===''||count>12,onClick:start},L('开始看图检查','Start visual review')),h('button',{disabled:busy,onClick:configure},L('刷新视觉模型','Refresh vision models')))),
|
|
543
|
+
run&&h(React.Fragment,null,
|
|
544
|
+
h('p',{role:'status'},(run.status==='paused'?L('检查已停止','Review stopped'):run.status==='ready'&&!busy?L('等待检查','Review ready'):phaseName(run.phase))+' · '+L('已调用 ','Calls ')+run.usedCalls+'/'+run.maxCalls+' · '+L('本轮已检查 ','Slides checked this pass ')+(last?.cursor||0)+'/'+(last?.ids.length||0)),
|
|
545
|
+
busy&&h('button',{onClick:stop},L('停止视觉检查','Stop visual review')),
|
|
546
|
+
run.error&&h('p',{role:'alert',className:'notice error'},failureText(run.error)),
|
|
547
|
+
stale&&h('p',{className:'notice'},L('工程或成品已变化,旧记录可查看,但不能继续或采纳。','The project or output changed. This old record is readable, but cannot be continued or adopted.')),
|
|
548
|
+
run.status==='complete'&&h('p',{className:'notice'},last.findings.length?L('复查仍有 '+last.findings.length+' 个问题,请查看标记和说明。','Recheck still found '+last.findings.length+' issues. Review the highlighted regions and notes.'):L('AI 在本次范围内未发现明显视觉问题;这是一份模型检查记录。','AI found no obvious visual issues in this scope. This is a model review record.')),
|
|
549
|
+
(last?.missingFonts||[]).length>0&&h('p',{className:'notice error'},L('渲染引擎报告缺失字体:','Renderer reported missing fonts: ')+last.missingFonts.join(', ')),
|
|
550
|
+
run.rounds.map((r,i)=>h('details',{key:i,open:i===run.rounds.length-1},h('summary',null,L('检查轮次 ','Inspection pass ')+i+' · '+r.cursor+'/'+r.ids.length),r.findings.map((f,j)=>h('p',{key:j},h('strong',null,(project.slides.findIndex(s=>s.id===f.slideId)>=0?L('原第 '+(project.slides.findIndex(s=>s.id===f.slideId)+1)+' 页','Original slide '+(project.slides.findIndex(s=>s.id===f.slideId)+1)):L('拆分页','Split page'))+' · '),f.issue,h('br'),h('small',{className:'muted'},f.action?actionName(f.action):L('需要人工判断','Needs manual review')))),r.applied.length>0&&h('ul',null,r.applied.map((a,j)=>h('li',{key:j},L('已应用:','Applied: ')+actionName(a)))))),
|
|
551
|
+
!busy&&last?.rendered&&h(React.Fragment,null,
|
|
552
|
+
h('label',null,L('查看前后画面(橙框为 AI 定位区域)','Compare images (orange boxes mark AI findings)'),h('select',{'aria-label':L('对比页面','Comparison slide'),value:compare,onChange:e=>setCompare(e.target.value)},last.ids.map((id,i)=>h('option',{value:id,key:id},String(i+1)+'. '+(project.slides.find(s=>s.id===id)?.title||L('拆分页','Split page')))))),
|
|
553
|
+
loading?h('p',{role:'status'},L('正在载入画面…','Loading images…')):h('div',{className:'before-after'},image(pictures.before,first,L('原稿 · 实际 PPTX','Original · actual PPTX')),image(pictures.after,last,run.rounds.length>1?L('修复后 · 实际 PPTX','Repaired · actual PPTX'):L('本次检查画面','Reviewed image')))),
|
|
554
|
+
h('div',{className:'tools'},h('button',{className:'primary',disabled:busy||blocked||!run.canAdopt||stale,onClick:adopt},last?.findings.length?L('打开修复副本(仍有待处理问题)','Open repaired copy (issues remain)'):L('采用修复副本','Use repaired copy')),h('button',{disabled:busy,onClick:download},L('下载视觉检查记录','Download visual review')),h('button',{disabled:busy||run.status==='busy',onClick:remove},L('删除检查记录','Delete review')),h('button',{disabled:busy,onClick:()=>{accept(null);setCompare('');setPictures({});configure();}},L('新建视觉检查','New visual review')))),
|
|
555
|
+
!busy&&history.length>0&&h('details',null,h('summary',null,L('本机视觉检查历史','Local visual review history')),h('div',{className:'project-list'},history.map(item=>h('button',{key:item.id,onClick:()=>open(item.id)},L('修订 ','Revision ')+item.revision+' · '+new Date(item.createdAt).toLocaleString(languageOf()==='en'?'en-US':'zh-CN'))))),
|
|
556
|
+
h('button',{disabled:busy,onClick:()=>setExpanded(false)},L('收起视觉检查','Collapse visual review'))));
|
|
557
|
+
}
|
|
558
|
+
function DataPanel({project,blocked,incoming,onParameters,onDirty,onBusy,onAdopt,onChoose,onDownload}) {
|
|
559
|
+
const L=(zh,en)=>languageOf()==='en'?en:zh,model=project.dataModel;
|
|
560
|
+
const baseline=Object.fromEntries(model.metrics.filter(m=>m.kind==='input').map(m=>[m.id,String(m.value)]));
|
|
561
|
+
const [parameters,setParameters]=useState(baseline),[updates,setUpdates]=useState({}),[sourceId,setSourceId]=useState(model.sources[0]?.id||'');
|
|
562
|
+
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);
|
|
563
|
+
const pending=useRef(null),alive=useRef(true),reading=useRef(0),latest=useRef(''),guard=useRef(false);
|
|
564
|
+
const numeric=Object.fromEntries(Object.entries(parameters).map(([id,value])=>[id,value.trim()===''?null:Number(value)]));
|
|
565
|
+
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);
|
|
566
|
+
const body={parameters:numeric,sourceUpdates:Object.values(updates)},signature=JSON.stringify(body);latest.current=signature;
|
|
567
|
+
const changed=readingFile||!valid||Object.entries(baseline).some(([id,value])=>Number(parameters[id])!==Number(value)||parameters[id].trim()==='')||Object.keys(updates).length>0;
|
|
568
|
+
useEffect(()=>{onDirty(changed);return()=>onDirty(false);},[changed]);
|
|
569
|
+
useEffect(()=>{setPreview(null);},[signature]);
|
|
570
|
+
useEffect(()=>{if(incoming){setParameters(Object.fromEntries(Object.entries(incoming.parameters).map(([id,value])=>[id,Number.isFinite(value)?String(value):''])));setValid(incoming.valid!==false);}},[incoming]);
|
|
571
|
+
useEffect(()=>{alive.current=true;return()=>{alive.current=false;reading.current++;pending.current?.abort();onBusy(false);};},[]);
|
|
572
|
+
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)])));}
|
|
573
|
+
function reset(){reading.current++;setParameters(baseline);setUpdates({});setPreview(null);setError('');setValid(true);onParameters(Object.fromEntries(Object.entries(baseline).map(([id,value])=>[id,Number(value)])));}
|
|
574
|
+
async function task(work){
|
|
575
|
+
if(guard.current||blocked||readingFile)return;guard.current=true;setBusy(true);onBusy(true);setError('');
|
|
576
|
+
const controller=new AbortController();pending.current=controller;
|
|
577
|
+
try{await work(controller.signal);}catch(reason){if(alive.current&&!controller.signal.aborted)setError(reason.message||L('操作失败','Operation failed'));}
|
|
578
|
+
finally{pending.current=null;guard.current=false;if(alive.current){setBusy(false);onBusy(false);}}
|
|
579
|
+
}
|
|
580
|
+
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});});}
|
|
581
|
+
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);}});}
|
|
582
|
+
async function importSource(event){
|
|
583
|
+
const file=event.target.files?.[0];event.target.value='';if(!file)return;const stamp=++reading.current,target=sourceId;
|
|
584
|
+
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;}
|
|
585
|
+
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);}
|
|
586
|
+
}
|
|
587
|
+
async function importScenario(event){
|
|
588
|
+
const file=event.target.files?.[0];event.target.value='';if(!file)return;const stamp=++reading.current;
|
|
589
|
+
setReadingFile(true);
|
|
590
|
+
try{
|
|
591
|
+
if(file.size>32000)throw new Error(L('推演参数文件过大。','Scenario parameter file is too large.'));
|
|
592
|
+
const packet=JSON.parse(await file.text());if(!alive.current||stamp!==reading.current)return;
|
|
593
|
+
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.'));
|
|
594
|
+
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('');
|
|
595
|
+
}catch(reason){if(alive.current)setError(reason.message);}finally{if(alive.current)setReadingFile(false);}
|
|
596
|
+
}
|
|
597
|
+
const metric=model.metrics.find(m=>m.id===metricId),source=model.sources.find(s=>s.id===sourceId),replacement=updates[sourceId];
|
|
598
|
+
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||'');
|
|
599
|
+
const display=value=>typeof value==='string'?value:JSON.stringify(value,null,2),disabled=busy||blocked||readingFile;
|
|
600
|
+
return h('section',{className:'card data-workbench','aria-label':L('数据溯源与现场推演','Data lineage and what-if')},
|
|
601
|
+
h('style',null,dataCss),
|
|
602
|
+
h('h3',null,L('数据溯源与现场推演','Data lineage and what-if')),
|
|
603
|
+
h('p',{className:'muted'},L('点预览中的数字可追问来源。只有明确声明的假设可调;来源不等于事实已核验。','Click numbers in the preview to inspect their lineage. Only declared assumptions are adjustable. Lineage is not factual verification.')),
|
|
604
|
+
h('details',null,h('summary',null,L('数字来自哪里','Where the numbers come from')),
|
|
605
|
+
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+']')))),
|
|
606
|
+
metric&&h('div',{className:'data-evidence'},h('strong',null,metric.label+' = '+format(model.values[metric.id],metric)),
|
|
607
|
+
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))))),
|
|
608
|
+
h('button',{disabled:disabled||changed,onClick:()=>onDownload('data')},L('下载溯源与假设报告','Download lineage and assumptions'))),
|
|
609
|
+
model.metrics.some(m=>m.kind==='input')&&h('details',{open:true},h('summary',null,L('现场推演参数','What-if assumptions')),
|
|
610
|
+
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)})))),
|
|
611
|
+
h('label',null,L('导入离线 HTML 保存的推演参数','Import scenario parameters saved in offline HTML'),h('input',{type:'file',accept:'.json,application/json',disabled,onChange:importScenario}))),
|
|
612
|
+
model.sources.length>0&&h('details',null,h('summary',null,L('更新来源材料','Update source material')),
|
|
613
|
+
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.')),
|
|
614
|
+
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)))),
|
|
615
|
+
h('label',null,L('导入替换材料','Import replacement material'),h('input',{type:'file',accept:source?.kind==='table'?'.csv,.tsv':'.txt,.md',disabled,onChange:importSource})),
|
|
616
|
+
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'))),
|
|
617
|
+
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('');}})),
|
|
618
|
+
replacement&&h('button',{disabled,onClick:()=>{setUpdates(old=>{const next={...old};delete next[sourceId];return next;});setPreview(null);}},L('取消此来源更新','Cancel this source update'))),
|
|
619
|
+
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.')),
|
|
620
|
+
(!valid||!inputsValid)&&h('p',{className:'notice error',role:'alert'},L('参数无法计算,请检查范围、步长或除零,再恢复或修改。','Cannot calculate these parameters. Check ranges, steps or division by zero; adjust or reset.')),
|
|
621
|
+
error&&h('p',{className:'notice error',role:'alert'},error),
|
|
622
|
+
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'))),
|
|
623
|
+
preview&&preview.signature===signature&&h('div',{className:'data-diff'},h('h4',null,L('确认前核对','Review before confirming')),
|
|
624
|
+
!preview.changed?h('p',null,L('内容没有变化。','No content changes.')):h(React.Fragment,null,
|
|
625
|
+
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')))),
|
|
626
|
+
h('h4',null,L('受影响页面','Affected slides')),
|
|
627
|
+
!preview.affectedSlides.length&&h('p',{className:'muted'},L('指标尚未绑定到页面,只更新数据模型。','Metrics are not bound to slides; only the data model changes.')),
|
|
628
|
+
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))))))),
|
|
629
|
+
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)')),
|
|
630
|
+
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.')),
|
|
631
|
+
h('button',{className:'primary',disabled:disabled||!valid||!inputsValid,onClick:apply},saveAs?L('确认并保存推演副本','Confirm and save scenario copy'):L('确认并更新当前工程','Confirm and update this project')))));
|
|
632
|
+
}
|
|
467
633
|
function Workbench({ locale } = {}) {
|
|
468
634
|
useLanguage(locale);
|
|
469
635
|
const [projects, setProjects] = useState([]), [project, setProject] = useState(null), [selected, setSelected] = useState('');
|
|
470
636
|
const [draft, setDraft] = useState({}), [image, setImage] = useState(null), [dirty, setDirty] = useState(false);
|
|
637
|
+
const [dataDirty,setDataDirty]=useState(false),[incomingData,setIncomingData]=useState(null);
|
|
471
638
|
const [busy, setBusy] = useState(false), [job, setJob] = useState(''), [message, setMessage] = useState(''), [error, setError] = useState('');
|
|
472
639
|
const [mode, setMode] = useState('html'), [raster, setRaster] = useState('');
|
|
473
640
|
const [conflict, setConflict] = useState(false), [overlaps, setOverlaps] = useState([]);
|
|
@@ -476,11 +643,13 @@ function useLanguage(locale) {
|
|
|
476
643
|
if (!imageLoader.current) imageLoader.current = createImageLoader();
|
|
477
644
|
const imagePending = imageLoader.current.pending;
|
|
478
645
|
const nonce = useRef(crypto.randomUUID());
|
|
646
|
+
const dataCommand=useRef(0);
|
|
479
647
|
const previewDocument = useMemo(() => project?.html ? editorHtml(project.html, nonce.current) : '', [project?.html]);
|
|
480
648
|
const index = project ? Math.max(0, project.slides.findIndex(s => s.id === selected)) : 0;
|
|
481
649
|
const slide = project?.slides[index];
|
|
482
650
|
function adopt(next, preferred) {
|
|
483
651
|
imageLoader.current.cancel();
|
|
652
|
+
nonce.current=crypto.randomUUID();setDataDirty(false);setIncomingData(null);
|
|
484
653
|
setProject(next);
|
|
485
654
|
const row = next.slides.find(s => s.id === preferred) || next.slides[0];
|
|
486
655
|
setSelected(row.id); setDraft(draftFor(row)); setImage(null); setDirty(false); setRaster(''); setOverlaps([]);
|
|
@@ -502,6 +671,7 @@ function useLanguage(locale) {
|
|
|
502
671
|
useEffect(() => {
|
|
503
672
|
function receive(event) {
|
|
504
673
|
if (event.source !== frame.current?.contentWindow || event.data?.nonce !== nonce.current || mode !== 'html') return;
|
|
674
|
+
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
675
|
if (event.data.type === 'dsh-ppt-shortcut') { handleShortcut(event.data.key); return; }
|
|
506
676
|
if (event.data.type !== 'dsh-ppt-select') return;
|
|
507
677
|
const key = event.data.field;
|
|
@@ -509,7 +679,7 @@ function useLanguage(locale) {
|
|
|
509
679
|
if (field) { fieldRefs.current[key]?.focus(); fieldRefs.current[key]?.scrollIntoView({ block: 'nearest' }); setMessage(t("已定位到") + t(field[1]) + t(",在字段中修改后保存。")); }
|
|
510
680
|
}
|
|
511
681
|
window.addEventListener('message', receive); return () => window.removeEventListener('message', receive);
|
|
512
|
-
}, [mode, project, dirty, busy, imagePending, index, selected, draft, image]);
|
|
682
|
+
}, [mode, project, dirty, busy, imagePending, index, selected, draft, image, dataDirty]);
|
|
513
683
|
useEffect(() => {
|
|
514
684
|
if (mode !== 'html' || !project || !previewBox.current) return;
|
|
515
685
|
// Align iframe edges/dimensions when the host uses fractional text metrics.
|
|
@@ -533,6 +703,7 @@ function useLanguage(locale) {
|
|
|
533
703
|
return () => abort.abort();
|
|
534
704
|
}, [mode, index, project?.revision]);
|
|
535
705
|
function handleShortcut(key) {
|
|
706
|
+
if(dataDirty)return;
|
|
536
707
|
if (key === 'save') { if (project && dirty && !busy && !imagePending) save(); return; }
|
|
537
708
|
if (key === 'escape') {
|
|
538
709
|
if (!project || busy || imagePending) return;
|
|
@@ -570,13 +741,13 @@ function useLanguage(locale) {
|
|
|
570
741
|
}
|
|
571
742
|
document.addEventListener('keydown', onKey);
|
|
572
743
|
return () => document.removeEventListener('keydown', onKey);
|
|
573
|
-
}, [project, dirty, busy, imagePending, index, selected, draft, image]);
|
|
744
|
+
}, [project, dirty, busy, imagePending, index, selected, draft, image, dataDirty]);
|
|
574
745
|
useEffect(() => {
|
|
575
|
-
if (!dirty) return;
|
|
746
|
+
if (!dirty && !dataDirty) return;
|
|
576
747
|
function warn(event) { event.preventDefault(); event.returnValue = t("有未保存修改,离开页面会丢失。"); }
|
|
577
748
|
window.addEventListener('beforeunload', warn);
|
|
578
749
|
return () => window.removeEventListener('beforeunload', warn);
|
|
579
|
-
}, [dirty]);
|
|
750
|
+
}, [dirty,dataDirty]);
|
|
580
751
|
function open(id) { return perform(signal => action({ operation: 'open', id }, signal), value => { adopt(value.project); setMessage(t("点击预览里的文字,或在下方修改字段。")); }); }
|
|
581
752
|
function keepInputsAndReload() {
|
|
582
753
|
const original = draftFor(slide), keys = fields.filter(([key]) => draft[key] !== original[key]).map(([key]) => key), pending = { ...draft }, pendingImage = image;
|
|
@@ -591,6 +762,7 @@ function useLanguage(locale) {
|
|
|
591
762
|
}
|
|
592
763
|
function choose(row) { if (dirty || busy) return; imageLoader.current.cancel(); setSelected(row.id); setDraft(draftFor(row)); setImage(null); setMessage(''); }
|
|
593
764
|
function save(saveAs = false) {
|
|
765
|
+
if(dataDirty)return;
|
|
594
766
|
const original = draftFor(slide), patch = {};
|
|
595
767
|
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
768
|
if (image) patch.image = { src: image.src, alt: image.alt, fit: image.fit, caption: image.caption };
|
|
@@ -599,20 +771,24 @@ function useLanguage(locale) {
|
|
|
599
771
|
});
|
|
600
772
|
}
|
|
601
773
|
function move(delta) {
|
|
774
|
+
if(dataDirty)return;
|
|
602
775
|
const order = project.slides.map(s => s.id); [order[index], order[index + delta]] = [order[index + delta], order[index]];
|
|
603
776
|
return perform(signal => action({ operation: 'edit', id: project.id, expectedRevision: project.revision, order }, signal), value => { adopt(value.project, slide.id); setMessage(t("页面顺序已更新,可撤销。")); });
|
|
604
777
|
}
|
|
605
778
|
function structure(operation) {
|
|
779
|
+
if(dataDirty)return;
|
|
606
780
|
return perform(signal => action({ operation, id: project.id, expectedRevision: project.revision, slide: slide.id }, signal), value => {
|
|
607
781
|
adopt(value.project, value.selected);
|
|
608
782
|
setMessage(operation === 'duplicate' ? t("页面已复制,图片、图表和备注一并保留,可撤销。") : t("页面已删除,可撤销。"));
|
|
609
783
|
});
|
|
610
784
|
}
|
|
611
|
-
function undo() { return perform(signal => action({ operation: 'undo', id: project.id, expectedRevision: project.revision }, signal), value => { adopt(value.project, selected); setMessage(t("已撤销上次修改。")); }); }
|
|
785
|
+
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
786
|
function render() {
|
|
787
|
+
if(dataDirty)return;
|
|
613
788
|
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
789
|
}
|
|
615
790
|
function download(kind) {
|
|
791
|
+
if(dataDirty)return;
|
|
616
792
|
const url = new URL('api/dsh-ppt/download', document.baseURI);
|
|
617
793
|
url.searchParams.set('id', project.id); url.searchParams.set('kind', kind); url.searchParams.set('revision', String(project.revision));
|
|
618
794
|
// An authenticated attachment response keeps the click's user gesture and
|
|
@@ -640,8 +816,8 @@ function useLanguage(locale) {
|
|
|
640
816
|
return h('div', { className: 'pptw', 'aria-busy': busy ? 'true' : undefined }, h('style', null, css),
|
|
641
817
|
h('h2', null, t("演示文稿编辑")), h('p', { className: 'muted' }, t("修改本插件生成的成品,保存时同步更新 HTML、可编辑 PPTX 和工程文件。")),
|
|
642
818
|
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("载入最新版本,保留我的输入")),
|
|
819
|
+
error && h('div', { role: 'alert', className: 'notice error' }, error, ' ', h('button', { disabled: busy || dataDirty, onClick: () => project ? open(project.id) : refreshList() }, t("重试"))),
|
|
820
|
+
conflict && project && h('button', { disabled: busy || dataDirty, onClick: keepInputsAndReload }, t("载入最新版本,保留我的输入")),
|
|
645
821
|
message && h('div', { role: 'status', className: 'notice' }, message),
|
|
646
822
|
busy && h('div', { role: 'status', className: 'muted' }, job),
|
|
647
823
|
!project ? h(React.Fragment, null,
|
|
@@ -649,32 +825,39 @@ function useLanguage(locale) {
|
|
|
649
825
|
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
826
|
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
827
|
) : 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)),
|
|
828
|
+
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
829
|
h('div', { className: 'layout' },
|
|
654
830
|
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("删除本页")))),
|
|
831
|
+
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("下移")),
|
|
832
|
+
h('button', { disabled: busy || dirty || imagePending || dataDirty || project.slides.length >= 120, onClick: () => structure('duplicate') }, t("复制本页")),
|
|
833
|
+
h('button', { disabled: busy || dirty || imagePending || dataDirty || project.slides.length <= 1, onClick: () => structure('remove') }, t("删除本页")))),
|
|
658
834
|
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"))),
|
|
835
|
+
h('div', { className: 'tools' }, h('button', { disabled: busy || dataDirty, 'aria-pressed': mode === 'html', onClick: () => setMode('html') }, t("HTML 预览")),
|
|
836
|
+
h('button', { disabled: busy || dataDirty || !project.render, 'aria-pressed': mode === 'pptx', onClick: () => setMode('pptx') }, t("最终 PPTX 预览")),
|
|
837
|
+
h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: render }, t("渲染当前 PPTX"))),
|
|
662
838
|
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
839
|
h('p', { className: 'muted' }, mode === 'html' ? t("这是 HTML 放映预览。最终 PPTX 的字体和排版请用上方渲染检查。点击文字可定位编辑字段。") : t("这是当前 PPTX 文件的实际渲染图片,仍需检查每页画面;PowerPoint / WPS 可能因字体环境而不同。")),
|
|
664
840
|
project.render?.missingFonts?.length ? h('div', { role: 'alert', className: 'notice error' }, t("渲染引擎报告缺失字体:") + project.render.missingFonts.join('、') + t("。请替换为目标电脑可用字体后重新渲染。")) : null,
|
|
665
841
|
h('div', { className: 'card' }, h('h3', null, t("编辑第 ") + (index + 1) + t(" 页")),
|
|
666
842
|
dirty && h('p', { className: 'dirty' }, t("有未保存修改,请先保存或取消,再切换页面。")),
|
|
667
843
|
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); } }))),
|
|
844
|
+
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
845
|
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 }),
|
|
846
|
+
h('input', { id: 'pptw-image', type: 'file', accept: 'image/png,image/jpeg', disabled: busy || dataDirty, onChange: upload }),
|
|
671
847
|
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("撤销上次修改")))),
|
|
848
|
+
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("填满并裁切")))),
|
|
849
|
+
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
850
|
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
851
|
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(
|
|
852
|
+
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("备份工程"))),
|
|
853
|
+
project.dataModel&&mode!=='html'&&h('p',{className:'notice'},languageOf()==='en'?'Switch to HTML preview to adjust assumptions and inspect live data.':'切换到 HTML 预览后可调整假设并查看数据联动。'),
|
|
854
|
+
project.dataModel&&h(DataPanel,{key:project.id+':'+project.revision,project,blocked:busy||dirty||imagePending||mode!=='html',incoming:incomingData,
|
|
855
|
+
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…':'正在核对并更新数据…');},
|
|
856
|
+
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}),
|
|
857
|
+
h(VisualPanel,{key:'visual:'+project.id,project,selected,blocked:busy||dirty||imagePending||dataDirty,
|
|
858
|
+
onBusy:value=>{setBusy(value);setJob(languageOf()==='en'?'Reviewing rendered slides…':'正在检查和复查实际 PPTX 画面…');},
|
|
859
|
+
onAdopt:next=>{adopt(next,selected);setMode(next.render?'pptx':'html');setMessage(languageOf()==='en'?'Opened the repaired copy. The original is kept, and formatting changes can be undone.':'已打开修复副本,原稿保留,可撤销排版修改。');}}),
|
|
860
|
+
h(CoachingPanel, { key: project.id, project, selected, blocked: busy || dirty || imagePending || dataDirty,
|
|
678
861
|
onChoose: id => { choose(project.slides.find(s => s.id === id)); previewBox.current?.scrollIntoView({ behavior: 'smooth', block: 'center' }); },
|
|
679
862
|
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
863
|
)
|
package/lib/coaching.d.ts
CHANGED
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 });
|
package/lib/execution.d.ts
CHANGED
|
@@ -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/index.js
CHANGED
|
@@ -20,6 +20,7 @@ import { registerPptSkill } from './skill.js';
|
|
|
20
20
|
import { buildPptTools } from './tools.js';
|
|
21
21
|
import { PptWorkbench, installPptWorkbench } from './workbench.js';
|
|
22
22
|
import { nativeCoachingModel } from './coaching-model.js';
|
|
23
|
+
import { nativeVisualModel } from './visual-model.js';
|
|
23
24
|
/** cordis 服务注入:apply 里要使用 ctx.tools 与 ctx.skills。 */
|
|
24
25
|
export const inject = ['tools', 'skills'];
|
|
25
26
|
export const name = 'dsh-ppt';
|
|
@@ -34,7 +35,11 @@ export function apply(ctx, config = {}) {
|
|
|
34
35
|
workbench.coaching.setModel(nativeCoachingModel(host.llm));
|
|
35
36
|
host.effect?.(() => () => workbench.coaching.setModel());
|
|
36
37
|
});
|
|
37
|
-
|
|
38
|
+
ctx.inject?.(['llm', 'attachments'], host => {
|
|
39
|
+
workbench.visual.setModel(nativeVisualModel(host.llm, host.attachments));
|
|
40
|
+
host.effect?.(() => () => workbench.visual.setModel());
|
|
41
|
+
});
|
|
42
|
+
disposers.push(() => { workbench.coaching.dispose(); workbench.visual.dispose(); });
|
|
38
43
|
}
|
|
39
44
|
// 技能注册:单个技能文件缺失只告警,不弄崩宿主启动。
|
|
40
45
|
try {
|
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. 中文:撤销最近一次修改,恢复正文、图表、图片和品牌设置。',
|